-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSketch.py
392 lines (311 loc) · 13.1 KB
/
Sketch.py
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
This is the main entry of your program. Almost all things you need to implement are in this file.
The main class Sketch inherits from CanvasBase. For the parts you need to implement, they are all marked with TO DO.
First version Created on 09/28/2018
:author: micou(Zezhou Sun)
:version: 2021.1.1
Modified by Daniel Scrivener 07/2022
"""
import os
import math
import random
import time
import numpy as np
from Point import Point
from CanvasBase import CanvasBase
import ColorType
from GLProgram import GLProgram
from GLBuffer import VAO, VBO, EBO, Texture
from Vivarium import Vivarium
from Quaternion import Quaternion
import GLUtility
try:
import wx
from wx import glcanvas
except ImportError:
raise ImportError("Required dependency wxPython not present")
try:
# From pip package "Pillow"
from PIL import Image
except:
print("Need to install PIL package. Pip package name is Pillow")
raise ImportError
try:
import OpenGL
try:
import OpenGL.GL as gl
import OpenGL.GLU as glu
except ImportError:
from ctypes import util
orig_util_find_library = util.find_library
def new_util_find_library(name):
res = orig_util_find_library(name)
if res:
return res
return '/System/Library/Frameworks/' + name + '.framework/' + name
util.find_library = new_util_find_library
import OpenGL.GL as gl
import OpenGL.GLU as glu
except ImportError:
raise ImportError("Required dependency PyOpenGL not present")
class Sketch(CanvasBase):
"""
Drawing methods and interrupt methods will be implemented in this class.
Variable Instruction:
* debug(int): Define debug level for log printing
* 0 for stable version, minimum log is printed
* 1 will print general logs for lines and triangles
* 2 will print more details and do some type checking, which might be helpful in debugging
Method Instruction:
Here are the list of functions you need to override:
* Interrupt_MouseL: Used to deal with mouse click interruption. Canvas will be refreshed with updated buff
* Interrupt_MouseLeftDragging: Used to deal with mouse dragging interruption.
* Interrupt_Keyboard: Used to deal with keyboard press interruption. Use this to add new keys or new methods
Here are some public variables in parent class you might need:
"""
context = None
debug = 1
texture_file_path = "./assets/marble.jpg"
last_mouse_leftPosition = None
last_mouse_middlePosition = None
components = None
texture = None
shaderProg = None
glutility = None
frameCount = 0
lookAtPt = None
upVector = None
# use these three to control camera position, mainly used in mouse dragging
cameraDis = None
cameraTheta = None # theta on horizontal sphere cut, in range [0, 2pi]
cameraPhi = None # in range [-pi, pi], for smooth purpose
viewMat = None
perspMat = None
pauseScene = False
# models
basisAxes = None
scene = None
def __init__(self, parent):
"""
Init everything. You should set your model here.
"""
super(Sketch, self).__init__(parent)
# prepare OpenGL context
# Initialize context attributes, this is needed by MacOS!
contextAttrib = glcanvas.GLContextAttrs()
contextAttrib.PlatformDefaults().CoreProfile().MajorVersion(3).MinorVersion(3).EndList()
self.context = glcanvas.GLContext(self, ctxAttrs=contextAttrib)
# Initialize Parameters
self.last_mouse_leftPosition = [0, 0]
self.last_mouse_middlePosition = [0, 0]
self.components = []
# add components to top level
self.resetView()
self.glutility = GLUtility.GLUtility()
self.backgroundColor = ColorType.BLUEGREEN
def resetView(self):
self.lookAtPt = [0, 0, 0]
self.upVector = [0, 1, 0]
# self.cameraDis = 12
# self.cameraPhi = math.pi / 6
# self.cameraTheta = math.pi / 2
self.cameraDis = 7.8
self.cameraPhi = 0.013598775598303803
self.cameraTheta = 0.900796326794896
def InitGL(self):
# self.texture = Texture()
self.shaderProg = GLProgram()
self.shaderProg.compile()
# instantiate models, then can only be done with a compiled GL program
self.vivarium = Vivarium(self, self.shaderProg) # all things are here
self.topLevelComponent.clear()
self.topLevelComponent.addChild(self.vivarium)
self.topLevelComponent.initialize()
self.components = self.vivarium.components
gl.glClearColor(0.2, 0.3, 0.3, 1.0)
gl.glClearDepth(1.0)
gl.glViewport(0, 0, self.size[0], self.size[1])
# enable depth checking
gl.glEnable(gl.GL_DEPTH_TEST)
# set basic viewing matrix
self.perspMat = self.glutility.perspective(45, self.size.width, self.size.height, 0.01, 100)
self.shaderProg.setMat4("projectionMat", self.perspMat)
self.shaderProg.setMat4("viewMat", self.glutility.view(self.getCameraPos(), self.lookAtPt, self.upVector))
self.shaderProg.setMat4("modelMat", np.identity(4))
def getCameraPos(self):
ct = math.cos(self.cameraTheta)
st = math.sin(self.cameraTheta)
cp = math.cos(self.cameraPhi)
sp = math.sin(self.cameraPhi)
result = [self.lookAtPt[0] + self.cameraDis * ct * cp,
self.lookAtPt[1] + self.cameraDis * sp,
self.lookAtPt[2] + self.cameraDis * st * cp]
return result
def OnResize(self, event):
contextAttrib = glcanvas.GLContextAttrs()
contextAttrib.PlatformDefaults().CoreProfile().MajorVersion(3).MinorVersion(3).EndList()
self.context = glcanvas.GLContext(self, ctxAttrs=contextAttrib)
self.size = self.GetClientSize()
self.size[1] = max(1, self.size[1]) # avoid divided by 0
self.SetCurrent(self.context)
self.init = False
self.Refresh(eraseBackground=True)
self.Update()
def OnPaint(self, event=None):
"""
This will be called at every frame
"""
self.SetCurrent(self.context)
if not self.init:
# Init the OpenGL environment if not initialized
self.InitGL()
self.init = True
# the draw method
self.OnDraw()
def OnDraw(self):
gl.glClearColor(*self.backgroundColor, 1.0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
# These are per-frame updates to the shader! Update the viewing matrix and the joint transforms
self.viewMat = self.glutility.view(self.getCameraPos(), self.lookAtPt, self.upVector)
self.shaderProg.setMat4("viewMat", self.viewMat)
self.topLevelComponent.update(np.identity(4))
self.topLevelComponent.draw(self.shaderProg)
# perform the next step of the animation
self.vivarium.animationUpdate()
self.SwapBuffers()
def OnDestroy(self, event):
"""
Window destroy event binding
:param event: Window destroy event
:return: None
"""
if self.shaderProg is not None:
del self.shaderProg
super(Sketch, self).OnDestroy(event)
def Interrupt_Scroll(self, wheelRotation):
"""
When mouse wheel rotating detected, do following things
:param wheelRotation: mouse wheel changes, normally +120 or -120
:return: None
"""
if wheelRotation == 0:
return
wheelChange = wheelRotation / abs(wheelRotation)
self.cameraDis = max(self.cameraDis - wheelChange * 0.1, 0.01)
self.update()
def unprojectCanvas(self, x, y, u=0.5):
"""
unproject a canvas point to world coordiantes. 2D -> 3D
you need give an extra parameter u, to tell the method how far are you from znear
u is the proportion of distance to znear / zfar-znear
in the gluUnProject, the distribution of z is not linear when using perspective projection,
so z=0.5 is not in the middle,
that's why we compute out the ray and use linear interpolation and u to get the point
:param u: u is the proportion to the znear/, in range [0, 1]
:type u: float
"""
result1 = glu.gluUnProject(x, y, 0.0,
np.identity(4),
self.viewMat @ self.perspMat,
gl.glGetIntegerv(gl.GL_VIEWPORT))
result2 = glu.gluUnProject(x, y, 1.0,
np.identity(4),
self.viewMat @ self.perspMat,
# be careful, the concate of view and persp is called projection matrix in opengl
gl.glGetIntegerv(gl.GL_VIEWPORT))
result = Point([(1 - u) * r1 + u * r2 for r1, r2 in zip(result1, result2)])
return result
def Interrupt_MouseL(self, x, y):
"""
When mouse click detected, store current position in last_mouse_leftPosition
:param x: Mouse click's x coordinate
:type x: int
:param y: Mouse click's y coordinate
:type y: int
:return: None
"""
self.last_mouse_leftPosition[0] = x
self.last_mouse_leftPosition[1] = y
def Interrupt_MouseMiddleDragging(self, x, y):
"""
When mouse drag motion with middle key detected, interrupt with new mouse position
:param x: Mouse drag new position's x coordinate
:type x: int
:param y: Mouse drag new position's x coordinate
:type y: int
:return: None
"""
dx = x - self.last_mouse_middlePosition[0]
dy = y - self.last_mouse_middlePosition[1]
originalMidPt = self.unprojectCanvas(*self.last_mouse_middlePosition, 0.5)
# ignore sudden change
self.last_mouse_middlePosition[0] = x
self.last_mouse_middlePosition[1] = y
if dx * dx + dy * dy > 5:
return
currentMidPt = self.unprojectCanvas(x, y, 0.5)
changes = currentMidPt - originalMidPt
moveSpeed = 0.185 * self.cameraDis / 6
self.lookAtPt = [self.lookAtPt[0] - changes[0] * moveSpeed,
self.lookAtPt[1] - changes[1] * moveSpeed,
self.lookAtPt[2] - changes[2] * moveSpeed]
def Interrupt_MouseLeftDragging(self, x, y):
"""
When mouse drag motion detected, interrupt with new mouse position
:param x: Mouse drag new position's x coordinate
:type x: int
:param y: Mouse drag new position's x coordinate
:type y: int
:return: None
"""
# Change viewing angle when dragging happened
dx = x - self.last_mouse_leftPosition[0]
dy = y - self.last_mouse_leftPosition[1]
# ignore sudden change
if dx * dx + dy * dy > 5:
self.last_mouse_leftPosition[0] = x
self.last_mouse_leftPosition[1] = y
return
# restrict phi movement range, stop cameraphi changes at pole points
self.cameraPhi = min(math.pi / 2, max(-math.pi / 2, self.cameraPhi - dy / 100))
self.cameraTheta += dx / 100
self.cameraPhi = (self.cameraPhi + math.pi) % (2 * math.pi) - math.pi
self.cameraTheta = self.cameraTheta % (2 * math.pi)
self.last_mouse_leftPosition[0] = x
self.last_mouse_leftPosition[1] = y
def update(self):
"""
Update current canvas
:return: None
"""
self.topLevelComponent.update(np.identity(4))
def Interrupt_Keyboard(self, keycode):
"""
Keyboard interrupt bindings
:param keycode: wxpython keyboard event's keycode
:return: None
"""
if chr(keycode) in "rR":
# reset viewing angle
self.viewing_quaternion = Quaternion()
self.update()
elif chr(keycode) in "pP":
print(self.cameraPhi)
print(self.cameraTheta)
elif chr(keycode) in "aA":
self.vivarium.addFish()
self.update()
elif chr(keycode) in "fF":
self.vivarium.addFood()
self.update()
if __name__ == "__main__":
print("This is the main entry! ")
app = wx.App(False)
# Set FULL_REPAINT_ON_RESIZE will repaint everything when scaling the frame,
# here is the style setting for it: wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE
# Resize disabled in this one
frame = wx.Frame(None, size=(500, 500), title="3D Vivarium",
style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE) # Disable Resize: ^ wx.RESIZE_BORDER
canvas = Sketch(frame)
frame.Show()
app.MainLoop()