-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·258 lines (214 loc) · 8.17 KB
/
Copy pathmain.py
File metadata and controls
executable file
·258 lines (214 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env -S uv run --script
"""
BoidShaded Example
This script demonstrates how to use OpenGL and Qt to render a simple 3D object (a "boid") with Phong shading.
It sets up a window, handles user input for rotation/translation/zoom, and manages OpenGL resources.
"""
import argparse
import math
import sys
import traceback
import OpenGL.GL as gl
from ncca.ngl import Mat4, Vec3, look_at, perspective
from ncca.ngl.opengl import (
PySideEventHandlingMixin,
ShaderLib,
Texture,
VAOFactory,
VAOType,
VertexData,
)
from PySide6.QtCore import QTimer
from PySide6.QtGui import QSurfaceFormat
from PySide6.QtOpenGL import QOpenGLWindow
from PySide6.QtWidgets import QApplication
TEXTURE_SHADER = "TextureShader"
class MainWindow(PySideEventHandlingMixin, QOpenGLWindow):
"""
Handles OpenGL initialization, rendering, and user input for interactive control.
"""
def __init__(self, parent: object = None) -> None:
"""
Initialize the window and set up default parameters.
"""
super().__init__()
self.setup_event_handling(
rotation_sensitivity=0.5,
translation_sensitivity=0.01,
zoom_sensitivity=0.1,
initial_position=Vec3(0, 0, 0),
)
self.mouse_global_tx: Mat4 = Mat4()
self.window_width: int = 1024
self.window_height: int = 720
self.setTitle("VAO Sphere with Texture")
self.view: Mat4 = Mat4()
self.project: Mat4 = Mat4()
def initializeGL(self) -> None:
"""
Set up OpenGL context, load shaders, and initialize scene.
"""
self.makeCurrent()
gl.glClearColor(0.4, 0.4, 0.4, 1.0) # Set background color
gl.glEnable(gl.GL_DEPTH_TEST) # Enable depth testing
gl.glEnable(gl.GL_MULTISAMPLE) # Enable anti-aliasing
# Set up camera/view matrix
eye = Vec3(0, 1, 4)
to = Vec3(0, 0, 0)
up = Vec3(0, 1, 0)
self.view = look_at(eye, to, up)
# Load and use Phong shader
if not ShaderLib.load_shader(
TEXTURE_SHADER, "shaders/TextureVertex.glsl", "shaders/TextureFragment.glsl"
):
print("error loading shaders")
self.close()
ShaderLib.use(TEXTURE_SHADER)
texture = Texture("textures/earth.png")
self.texture_id = texture.set_texture_gl()
self.build_vao_sphere()
def build_vao_sphere(self, radius: float = 1.0, precision: int = 100):
"""
Creates a sphere VAO using triangle strips.
based on an algorithm by Paul Bourke.
http://astronomy.swin.edu.au/~pbourke/opengl/sphere/
Parameters
----------
radius : float
The radius of the sphere.
precision : int
The number of divisions around the sphere. Higher is more detailed.
Returns
-------
A configured ngl.AbstractVAO containing the sphere geometry.
"""
# In NGL, "simpleVAO" is a basic VAO that holds interleaved data in a single buffer.
self.vao = VAOFactory.create_vao(VAOType.SIMPLE, gl.GL_TRIANGLE_STRIP)
if radius < 0:
radius = -radius
precision = max(precision, 4)
vertex_data = []
for i in range(precision // 2):
theta1 = i * (2 * math.pi) / precision - (math.pi / 2)
theta2 = (i + 1) * (2 * math.pi) / precision - (math.pi / 2)
for j in range(precision + 1):
theta3 = j * (2 * math.pi) / precision
# Vertex 1 (for the top of the strip)
nx1 = math.cos(theta2) * math.cos(theta3)
ny1 = math.sin(theta2)
nz1 = math.cos(theta2) * math.sin(theta3)
x1 = radius * nx1
y1 = radius * ny1
z1 = radius * nz1
u1 = j / precision
v1 = 1.0 - (2 * (i + 1) / precision)
vertex_data.extend([x1, y1, z1, nx1, ny1, nz1, u1, v1])
# Vertex 2 (for the bottom of the strip)
nx2 = math.cos(theta1) * math.cos(theta3)
ny2 = math.sin(theta1)
nz2 = math.cos(theta1) * math.sin(theta3)
x2 = radius * nx2
y2 = radius * ny2
z2 = radius * nz2
u2 = j / precision
v2 = 1.0 - (2 * i / precision)
vertex_data.extend([x2, y2, z2, nx2, ny2, nz2, u2, v2])
num_verts = len(vertex_data) // 8
with self.vao:
data = VertexData(data=vertex_data, size=len(vertex_data))
self.vao.set_data(data)
# Stride is 8 floats * 4 bytes/float = 32 bytes
stride = 8 * 4
# Set attribute pointers for the interleaved data
# Attribute 0: Vertex (x, y, z)
self.vao.set_vertex_attribute_pointer(0, 3, gl.GL_FLOAT, stride, 0)
# Attribute 1: Normal (nx, ny, nz) - offset is 3 floats (12 bytes)
self.vao.set_vertex_attribute_pointer(1, 3, gl.GL_FLOAT, stride, 3 * 4)
# Attribute 2: UV (u, v) - offset is 6 floats (24 bytes)
self.vao.set_vertex_attribute_pointer(2, 2, gl.GL_FLOAT, stride, 6 * 4)
# Set the number of vertices to draw
self.vao.set_num_indices(num_verts)
def loadMatricesToShader(self) -> None:
"""
Load transformation matrices to the shader uniforms.
"""
mvp = self.project @ self.view @ self.mouse_global_tx
ShaderLib.set_uniform("MVP", mvp)
def paintGL(self) -> None:
"""
Render the scene. Called automatically by Qt.
"""
self.makeCurrent()
gl.glViewport(0, 0, self.window_width, self.window_height)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
ShaderLib.use(TEXTURE_SHADER)
# Apply rotation based on user input
rot_x = Mat4().rotate_x(self.spin_x_face)
rot_y = Mat4().rotate_y(self.spin_y_face)
self.mouse_global_tx = rot_y @ rot_x
# Update model position
self.mouse_global_tx[3, 0] = self.model_position.x
self.mouse_global_tx[3, 1] = self.model_position.y
self.mouse_global_tx[3, 2] = self.model_position.z
self.loadMatricesToShader()
# Draw geometry
with self.vao:
self.vao.draw()
def resizeGL(self, w: int, h: int) -> None:
"""
Handle window resizing and update the projection matrix.
Parameters
----------
w : int
New window width.
h : int
New window height.
"""
self.window_width = int(w * self.devicePixelRatio())
self.window_height = int(h * self.devicePixelRatio())
self.project = perspective(45.0, float(w) / h, 0.1, 350.0)
class DebugApplication(QApplication):
def __init__(self, argv):
super().__init__(argv)
def notify(self, receiver, event):
try:
return super().notify(receiver, event)
except Exception:
traceback.print_exc()
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--smoketest",
nargs="?",
const=200,
default=None,
type=int,
metavar="MS",
help="run for MS milliseconds (default 200), print SMOKETEST OK and exit",
)
parser.add_argument(
"--debug",
action="store_true",
help="run with DebugApplication (tracebacks from Qt event handlers)",
)
args = parser.parse_args()
# Set up Qt application and OpenGL format
format = QSurfaceFormat()
format.setSamples(4)
format.setMajorVersion(4)
format.setMinorVersion(1)
format.setProfile(QSurfaceFormat.CoreProfile)
format.setDepthBufferSize(24)
QSurfaceFormat.setDefaultFormat(format)
if args.debug:
app = DebugApplication(sys.argv)
else:
app = QApplication(sys.argv)
window = MainWindow()
window.setFormat(format)
window.resize(1024, 720)
window.show()
if args.smoketest is not None:
QTimer.singleShot(args.smoketest, lambda: (print("SMOKETEST OK"), app.quit()))
sys.exit(app.exec())