-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwave.nim
376 lines (279 loc) · 9.27 KB
/
wave.nim
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
#------------------------------------------------------------------------
# Nim port of the GLFW example 'wave.c'
# https://github.com/glfw/glfw/blob/master/examples/wave.c
#
# Ported by John Novak <[email protected]>
#
# Requires nim-glm.
#------------------------------------------------------------------------
#****************************************************************************
# Wave Simulation in OpenGL
# (C) 2002 Jakob Thomsen
# http://home.in.tum.de/~thomsen
# Modified for GLFW by Sylvain Hellegouarch - [email protected]
# Modified for variable frame rate by Marcus Geelnard
# 2003-Jan-31: Minor cleanups and speedups / MG
# 2010-10-24: Formatting and cleanup - Camilla Berglund
#****************************************************************************/
import std/math
import glm
import glad/gl
import glfw
type Vertex = object
x, y, z: GLfloat
r, g, b: GLfloat
const
# Maximum delta T to allow for differential calculations
MAX_DELTA_T = 0.01
# Animation speed (10.0 looks good)
ANIMATION_SPEED = 10.0
GRIDW = 50
GRIDH = 50
VERTEXNUM = GRIDW * GRIDH
QUADW = GRIDW - 1
QUADH = GRIDH - 1
QUADNUM = QUADW * QUADH
var
alpha = 210.0
beta = -70.0
zoom = 2.0
cursorX: float64
cursorY: float64
quad: array[4 * QUADNUM, GLuint]
vertex: array[VERTEXNUM, Vertex]
dt: float64
# The grid will look like this:
#
# 3 4 5
# *---*---*
# | | |
# | 0 | 1 |
# | | |
# *---*---*
# 0 1 2
#
#========================================================================
# Initialize grid geometry
#========================================================================
proc initVertices() =
# Place the vertices in a grid
for y in 0..GRIDH-1:
for x in 0..GRIDW-1:
var p = y * GRIDW + x
vertex[p].x = (GLfloat(x) - GRIDW / 2) / (GRIDW / 2)
vertex[p].y = (GLfloat(y) - GRIDH / 2) / (GRIDH / 2)
vertex[p].z = 0
if (x mod 4 < 2) xor (y mod 4 < 2):
vertex[p].r = 0.0
else:
vertex[p].r = 1.0
vertex[p].g = y / GRIDH
vertex[p].b = 1.0 - (GLfloat(x) / GRIDW + GLfloat(y) / GRIDH) / 2
for y in 0..QUADH-1:
for x in 0..QUADW-1:
var p = 4 * (y * QUADW + x)
quad[p+0] = GLuint(y * GRIDW + x ) # Some point
quad[p+1] = GLuint(y * GRIDW + x+1) # Neighbor at the right side
quad[p+2] = GLuint((y+1) * GRIDW + x+1) # Upper right neighbor
quad[p+3] = GLuint((y+1) * GRIDW + x ) # Upper neighbor
#========================================================================
# Initialize grid
#========================================================================
var
p, vx, vy, ax, ay: array[GRIDW, array[GRIDH, float64]]
proc initGrid() =
for y in 0..GRIDH-1:
for x in 0..GRIDW-1:
var
dx = float64(x) - GRIDW / 2
dy = float64(y) - GRIDH / 2
d = sqrt(dx * dx + dy * dy)
if d < 0.1 * (GRIDW / 2):
d = d * 10.0
p[x][y] = -cos(d * (PI / (GRIDW * 4))) * 100.0
else:
p[x][y] = 0.0
vx[x][y] = 0.0
vy[x][y] = 0.0
#========================================================================
# Draw scene
#========================================================================
proc drawScene(win: Window) =
# Clear the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
# We don't want to modify the projection matrix
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# Move back
glTranslatef(0.0, 0.0, -zoom)
# Rotate the view
glRotatef(beta, 1.0, 0.0, 0.0)
glRotatef(alpha, 0.0, 0.0, 1.0)
glDrawElements(GL_QUADS, 4 * QUADNUM, GL_UNSIGNED_INT, quad.addr)
glfw.swapBuffers(win)
#========================================================================
# Initialize Miscellaneous OpenGL state
#========================================================================
proc initOpenGL() =
# Use Gouraud (smooth) shading
glShadeModel(GL_SMOOTH)
# Switch on the z-buffer
glEnable(GL_DEPTH_TEST)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glVertexPointer(3, cGL_FLOAT, GLsizei(sizeof(Vertex)), vertex.addr)
glColorPointer(3, cGL_FLOAT, GLsizei(sizeof(Vertex)),
vertex[0].r.addr) # Pointer to the first color
glPointSize(2.0)
# Background color is black
glClearColor(0, 0, 0, 0)
#========================================================================
# Modify the height of each vertex according to the pressure
#========================================================================
proc adjustGrid() =
for y in 0..GRIDH-1:
for x in 0..GRIDW-1:
var pos = y * GRIDW + x
vertex[pos].z = p[x][y] * (1.0 / 50.0)
#========================================================================
# Calculate wave propagation
#========================================================================
proc calcGrid() =
var
timeStep: float64 = dt * ANIMATION_SPEED
# Compute accelerations
for x in 0..GRIDW-1:
var x2 = (x + 1) mod GRIDW
for y in 0..GRIDH-1:
ax[x][y] = p[x][y] - p[x2][y]
for y in 0..GRIDH-1:
var y2 = (y + 1) mod GRIDH
for x in 0..GRIDW-1:
ay[x][y] = p[x][y] - p[x][y2]
# Compute speeds
for x in 0..GRIDW-1:
for y in 0..GRIDH-1:
vx[x][y] += ax[x][y] * timeStep
vy[x][y] += ay[x][y] * timeStep
#/ Compute pressure
for x in 1..GRIDW-1:
var x2 = x - 1
for y in 1..GRIDH-1:
var y2 = y - 1
p[x][y] += (vx[x2][y] - vx[x][y] + vy[x][y2] - vy[x][y]) * timeStep
#========================================================================
# Handle key strokes
#========================================================================
proc keyCb(win: Window, key: Key, scanCode: int32, action: KeyAction,
modKeys: set[ModifierKey]) =
if action != kaDown: return
case key
of keyEscape: win.shouldClose = true
of keySpace: initGrid()
of keyLeft: alpha += 5
of keyRight: alpha -= 5
of keyUp: beta -= 5
of keyDown: beta += 5
of keyPageUp:
zoom -= 0.25
if (zoom < 0.0): zoom = 0.0
of keyPageDown:
zoom += 0.25
else: return
#========================================================================
# Callback function for mouse button events
#========================================================================
proc mouseButtonCb(win: Window, btn: MouseButton, pressed: bool,
modKeys: set[ModifierKey]) =
if btn != mbLeft:
return
if pressed:
win.cursorMode = cmDisabled
(cursorx, cursory) = win.cursorPos
else:
win.cursorMode = cmNormal
#========================================================================
# Callback function for cursor motion events
#========================================================================
proc cursorPositionCb(win: Window, pos: tuple[x, y: float64]) =
if win.cursorMode == cmDisabled:
alpha += (pos.x - cursorX) / 10
beta += (pos.y - cursorY) / 10
cursorX = pos.x
cursorY = pos.y
#========================================================================
# Callback function for scroll events
#========================================================================
proc scrollCb(win: Window, pos: tuple[x, y: float64]) =
zoom += pos.y / 4
if zoom < 0:
zoom = 0
#========================================================================
# Callback function for framebuffer resize events
#========================================================================
proc reshape(win: Window, res: tuple[w, h: int32]) =
var ratio = 1.0
if res.h > 0:
ratio = res.w / res.h
# Setup viewport
glViewport(0, 0, GLsizei(res.w), GLsizei(res.h))
# Change to the projection matrix and set our viewing volume
glMatrixMode(GL_PROJECTION)
var projection = perspective[GLfloat](
fovy = 60.0 * PI / 180.0,
ratio,
zNear = 1.0, zFar = 1024.0)
glLoadMatrixf(projection.caddr)
#========================================================================
# main
#========================================================================
proc main() =
# Initialise GLFW
glfw.initialize()
# Open OpenGL window
var cfg = DefaultOpenglWindowConfig
cfg.size = (w: 640, h: 480)
cfg.title = "Wave Simulation"
cfg.resizable = true
cfg.version = glv20
var win = newWindow(cfg)
# Set callback functions
win.keyCb = keyCb
win.framebufferSizeCb = reshape
win.mouseButtonCb = mouseButtonCb
win.cursorPositionCb = cursorPositionCb
win.scrollCb = scrollCb
glfw.makeContextCurrent(win)
if not gladLoadGL(getProcAddress):
quit "Error initialising OpenGL"
glfw.swapInterval(1)
var width, height: int
(width, height) = framebufferSize(win)
win.reshape((width, height))
# Initialize OpenGL
initOpenGL()
# Initialize simulation
initVertices()
initGrid()
adjustGrid()
# Initialize timer
var
t, dtTotal: float64
tOld = getTime() - 0.01
while not win.shouldClose:
t = getTime()
dtTotal = t - tOld
tOld = t
# Safety - iterate if dtTotal is too large
while dtTotal > 0.0:
# Select iteration time step
dt = (if dtTotal > MAX_DELTA_T: MAX_DELTA_T else: dtTotal)
dtTotal -= dt
# Calculate wave propagation
calcGrid()
# Compute height of each vertex
adjustGrid()
# Draw wave grid to OpenGL display
drawScene(win)
glfw.pollEvents()
main()