~nch/gamelog

ref: fffd102a35945e0c5b096ecbe999d6c5290936e3 gamelog/df.nim -rw-r--r-- 18.9 KiB View raw
fffd102a — nc fixed game for amd card 3 months ago
                                                                                
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# set makeprg=nim\ c\ df.nim\ &&\ ./df
import glm
import opengl
import glfw
import gara
import tables
import strutils
import sugar
import sets
import macros
import stb_image/read as stbi
import math
import complex
import options
import bitops

const max_entities = 1024;

# TODO: soa this sucker
type
    Entity = tuple[id: uint16]
    Mesh = tuple[filepath: string, vao: uint32, nfaces: uint16, nverts: uint16]
    Texture = tuple[filepath: string, handle: uint64, width: uint16, height: uint16]
    Drawable = tuple[mesh_id: uint16, pos: Vec3f]
    TextureBinding = tuple[drawable_id: uint16, texture_handle: uint64, texture_name: string]

# TODO: use fixed allocation and fill in the values
var entities = newSeq[Entity]()
var meshes = newSeq[Mesh]()
var textures = newSeq[Texture]()
var drawables = newSeq[Drawable]()
var texture_bindings = newSeq[TextureBinding]()

# filter a list based on pattern matching
macro where(list: typed, bl: untyped): untyped =
    let T = list.get_type_inst()[1]

    result = quote do:
        var s = newSeq[`T`]()
        for d in `list`:
            if d.matches(`bl`):
                s.add(d)
        s

when isMainModule:
    assert(where(@[1,2,3], 1) == @[1])
    assert(where(@[(1, 2), (1, 2), (2, 3)], (1, @n)) == @[(1, 2), (1, 2)])


## math

type
    Plane = tuple[pos: Vec3f, normal: Vec3f]
    Ellipse = tuple[pos: Vec3f, radius: Vec3f]
    Triangle = array[3, Vec3f]

proc is_facing(p: Plane, dir: Vec3f): bool =
    return p.normal.dot(dir) <= 0

proc point_distance(p: Plane, point: Vec3f): float =
    let v = point - p.pos
    return v.dot(p.normal)

proc triangle_plane(t: Triangle): Plane =
    let n: Vec3f = (t[1] - t[0]).cross(t[2] - t[0]).normalize()
    return (pos: t[0], normal: n).Plane

proc get_lowest_root(a, b, c, max_r: float32): Option[float32] =
    let det = b * b - 4 * a * c
    if det < 0: return none(float32)

    let sqrt_d = sqrt(det)
    var r1 = (-b - sqrt_d) / (2 * a)
    var r2 = (-b + sqrt_d) / (2 * a)

    if r1 > r2: swap(r1, r2)
    if r1 > 0 and r1 < max_r:
        return some(r1)
    if r2 > 0 and r2 < max_r:
        return some(r2)



proc in_triangle(p: Vec3f, t: Triangle): bool =
    let e10 = t[1] - t[0]
    let e20 = t[2] - t[0]

    let a = e10.dot(e10)
    let b = e10.dot(e20)
    let c = e20.dot(e20)
    let ac_bb = (a * c) - (b * b)
    let vp = vec3f(p.x - t[0].x, p.y - t[0].y, p.z - t[0].z)

    let d = vp.dot(e10)
    let e = vp.dot(e20)

    let x = (d * c) - (e * b)
    let y = (e * a) - (d * b)
    let z = x + y - ac_bb

    return bitand(bitand(z.uint32, bitnot(bitor(x.uint32, y.uint32))), 0x80000000.uint32) != 0



proc make_program(shaders: varargs[(GLenum, string)]): uint32 =
    let program = gl_create_program()
    var shader_ids: seq[uint32] = @[]
    for (ty, source) in shaders:
        let shader = gl_create_shader(ty)
        let a = alloc_c_string_array([source])
        defer: dealloc_c_string_array(a)
        gl_shader_source(shader, 1, a, nil)
        gl_compile_shader(shader)
        gl_attach_shader(program, shader) # now attach to the main program
        shader_ids.add(shader)
    gl_link_program(program)
    for s in shader_ids:
        gl_delete_shader(s)
    return program

proc parse_obj(path: string): (seq[float32], seq[uint16]) =
    var
        vertices = newSeq[Vec3f]()
        normals = newSeq[Vec3f]()
        uvs = newSeq[Vec2f]()
        faces = newSeq[seq[seq[int]]]()

    for line in path.lines:
        let tokens = line.split(' ')
        match(tokens):
            @[@head, * @rest]:
                if head[0] == '#': # skip comments
                    continue
                case head:
                of "v":
                    let fs = rest.map(parse_float)
                    assert fs.len == 3
                    vertices.add(vec3f(fs[0], fs[1], fs[2]))
                of "vn":
                    let fs = rest.map(parse_float)
                    assert fs.len == 3
                    normals.add(vec3f(fs[0], fs[1], fs[2]))
                of "vt":
                    let fs = rest.map(parse_float)
                    assert fs.len == 2
                    # !!! opengl flips the y coordinates of UVs from what obj exports. which is fun.
                    uvs.add(vec2f(fs[0], 1 - fs[1]))
                of "f":
                    assert rest.len == 3, "only supports triangles for now"
                    faces.add(rest.map(x => x.split('/').map(y => y.parse_int)))
                else:
                    echo "unhandled obj directive: " & head
            _:
                echo "unable to handle line: " & tokens

    type
        VertData = array[8, float32] # (vx, vy, vz, vnx, vny, vnz, vu, vv)
    var
        element_indices = newSeq[uint16]()
        data = initOrderedSet[VertData]()


    for face in faces:
        for field in face:
            let vi = field[0] - 1
            let vt = field[1] - 1
            let vn = field[2] - 1
            let new_vert: VertData =  [vertices[vi].x, vertices[vi].y, vertices[vi].z,
                                       normals[vn].x, normals[vn].y, normals[vn].z,
                                       uvs[vt].x, uvs[vt].y]
            if new_vert in data:
                for i, v in data.pairs:
                    if new_vert == v:
                        element_indices.add(i.uint16)
                        break
            else:
                data.incl(new_vert)
                element_indices.add((data.len - 1).uint16)

    assert data.len > 0
    assert element_indices.len > 0

    var r = newSeq[float32]()
    for d in data.items:
        r.add(d)
    return (r, element_indices)

proc make_mesh(vertex_data: seq[float32], face_indices: seq[uint16]): uint =
    var vao_id: GLuint
    gl_gen_vertex_arrays(1, vao_id.addr)
    assert vao_id != 0
    gl_bind_vertex_array(vao_id)
    var vbo_id: GLuint
    gl_gen_buffers(1, vbo_id.addr)

    gl_bind_buffer(GL_ARRAY_BUFFER, vbo_id)
    gl_buffer_data(GL_ARRAY_BUFFER, vertex_data.len * float32.sizeof, vertex_data[0].unsafeAddr, GL_STATIC_DRAW)

    gl_vertex_attrib_pointer(0, 3, cGL_FLOAT, false, 8 * float32.sizeof, cast[ptr int](0)) # pos
    gl_enable_vertex_attrib_array(0)
    gl_vertex_attrib_pointer(1, 3, cGL_FLOAT, false, 8 * float32.sizeof, cast[ptr int](3 * float32.sizeof)) # normal
    gl_enable_vertex_attrib_array(1)
    gl_vertex_attrib_pointer(2, 2, cGL_FLOAT, false, 8 * float32.sizeof, cast[ptr int](6 * float32.sizeof)) # uv
    gl_enable_vertex_attrib_array(2)

    var ebo_id: GLuint
    gl_gen_buffers(1, ebo_id.addr)

    gl_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, ebo_id)
    gl_buffer_data(GL_ELEMENT_ARRAY_BUFFER, face_indices.len * uint16.sizeof, face_indices[0].unsafeAddr, GL_STATIC_DRAW)

    gl_bind_vertex_array(0)
    return vao_id

proc load_mesh(path: string): uint16 =
    let (vert_data, face_indices) = parse_obj(path)
    let vao = make_mesh(vert_data, face_indices)
    meshes.add((filepath: path, vao: vao.uint32, nfaces: face_indices.len.uint16, nverts: (face_indices.len * 3).uint16).Mesh)
    return (meshes.len - 1).uint16

proc load_texture(file: string): uint64 =
    # TODO: check if the file existed first
    #let q = textures.where((file: file, id: _,
    var tex_id: GLuint
    var w, h, nchannels: int
    let data = stbi.load(file, w, h, nchannels, stbi.Default)

    gl_create_textures(GL_TEXTURE_2D, 1, tex_id.addr)
    gl_texture_parameteri(tex_id, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    gl_texture_parameteri(tex_id, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    gl_texture_parameteri(tex_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    gl_texture_parameteri(tex_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    let num_mipmaps = (log2(float(max(w, h) + 1))).GLsizei;
    gl_texture_storage_2d(tex_id, num_mipmaps, GL_RGB8, w.GLsizei, h.GLsizei);
    gl_texture_subimage_2d(tex_id, 0, 0, 0, w.GLsizei, h.GLsizei, GL_RGBA, GL_UNSIGNED_BYTE, data[0].unsafeAddr)
    gl_generate_texture_mipmap(tex_id)

    let handle = gl_get_texture_handle_arb(tex_id)
    gl_make_texture_handle_resident_arb(handle)
    textures.insert((filepath: file, handle: handle, width: w.uint16, height: h.uint16).Texture)
    return handle

var debug_mesh = newSeq[Vec3f]()

proc debug_edge(vs: varargs[Vec3f]) =
    for (a, b) in zip(vs, vs[1..^1]):
        debug_mesh.add(a)
        debug_mesh.add(b)


proc debug_sphere(pos: Vec3f, radius: float32, np: uint = 8, nm: uint = 16) =
    for j in 0..< np:
        let pp = PI * (j).float / np.float
        let p = PI * (j + 1).float / np.float
        let
            spp = sin(pp)
            cpp = cos(pp)
        let
            sp = sin(p)
            cp = cos(p)
        for i in 1.. nm:
            let pm = 2.0 * PI * (i - 1).float / nm.float
            let m = 2.0 * PI * i.float / nm.float
            # ring
            debug_edge(
                pos + radius * vec3f(sp * cos(pm), cp, sp * sin(pm)),
                pos + radius * vec3f(sp * cos(m), cp, sp * sin(m)))
            # connecting edge
            debug_edge(
                pos + radius * vec3f(spp * cos(m), cpp, spp * sin(m)),
                pos + radius * vec3f(sp * cos(m), cp, sp * sin(m)))

proc debug_sphere(e: Ellipse) = debug_sphere(e.pos, e.radius.x)

proc debug_AABB(a, b: Vec3f) =
    debug_edge(a, vec3f(a.x, b.y, a.z), vec3f(b.x, b.y, a.z), vec3f(b.x, a.y, a.z), a)
    debug_edge(vec3f(a.x, a.y, b.z), vec3f(a.x, b.y, b.z), vec3f(b.x, b.y, b.z), vec3f(b.x, a.y, b.z), vec3f(a.x, a.y, b.z))

    debug_edge(vec3f(a.x, a.y, a.z), vec3f(a.x, a.y, b.z))
    debug_edge(vec3f(b.x, a.y, a.z), vec3f(b.x, a.y, b.z))
    debug_edge(vec3f(b.x, b.y, a.z), vec3f(b.x, b.y, b.z))
    debug_edge(vec3f(a.x, b.y, a.z), vec3f(a.x, b.y, b.z))

proc check_collision(e: Ellipse, vel: Vec3f, tri: Triangle): Option[Vec3f] =
    let tp = triangle_plane(tri)
    if not tp.is_facing(-vel):
        return

    let dist = tp.point_distance(e.pos)
    let norm_dot_vel = tp.normal.dot(vel)
    var embedded = false
    var t0, t1: float # time of start/stop intersection

    if norm_dot_vel == 0: # parallel
        if abs(dist) >= 1:
            return
        else:
            embedded = true
            t0 = 0
            t1 = 1
    else: # not parallel
        t0 = (-1 - dist) / norm_dot_vel
        t1 = ( 1 - dist) / norm_dot_vel

        if t0 > t1:
            swap(t0, t1)

        if t0 > 1 or t1 < 0:
            return

        t0 = t0.clamp(0, 1)
        t1 = t1.clamp(0, 1)

    var found_col = false
    var t = 1.0
    var col_point: Vec3f

    if not embedded:
        let plane_intersection = (e.pos - tp.normal) + (t0.float32 * vel)
        if plane_intersection.in_triangle(tri):
            found_col = true
            t = t0
            col_point = plane_intersection

    let vel_length2 = vel.length2()

    if not found_col:
        # check points
        for p in tri:
            {.unroll: 3.}
            let a = vel_length2
            let b = 2.float32 * vel.dot(e.pos - p)
            let c = (p - e.pos).length2() - 1.float32
            let r = get_lowest_root(a, b, c, t)
            if r.is_some():
                t = r.get()
                found_col = true
                col_point = p


        # check edges
        for pair in [(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])]:
            {.unroll: 3.}
            let edge = pair[1] - pair[0]
            let pos_to_vert = pair[0] - e.pos
            let edge_len2 = edge.length2()
            let edge_dot_vel = edge.dot(vel)
            let edge_dot_pos_to_vert = edge.dot(pos_to_vert)

            let a = edge_len2 * -vel_length2 + edge_dot_vel * edge_dot_vel
            let b = edge_len2 * (2 * vel.dot(pos_to_vert)) - 2 * edge_dot_vel * edge_dot_pos_to_vert
            let c = edge_len2 * (1 - pos_to_vert.length2()) + edge_dot_pos_to_vert * edge_dot_pos_to_vert

            let r = get_lowest_root(a, b, c, t)
            if r.is_some():
                let f = (edge_dot_vel * r.get() - edge_dot_pos_to_vert) / edge_len2
                if f >= 0 and f <= 1:
                    t = r.get()
                    found_col = true
                    col_point = pair[0] + f * edge

    if found_col:
        return some(col_point)

var cam_pos = vec3f(0, 1, 2)
var cam_look = vec3f(0, 0, 1)
let cam_up = vec3f(0, 1, 0)
var cam_yaw: float = radians(0.0)
var cam_pitch: float = radians(90.0)

let width = 800
let height = 600

var last_x = (width/2).float64
var last_y = (height/2).float64

proc cursor_pos_callback(w: Window, pos: tuple[x, y: float64]) =
    let dx = last_x - pos.x
    let dy = last_y - pos.y
    last_x = pos.x
    last_y = pos.y
    cam_pitch += (dy * 0.1)
    cam_yaw -= (dx * 0.1)
    cam_look.x = cos(radians(cam_pitch)) * cos(radians(cam_yaw))
    cam_look.y = sin(radians(cam_pitch))
    cam_look.z = cos(radians(cam_pitch)) * sin(radians(cam_yaw))
    cam_look = cam_look.normalize()

###

glfw.initialize()

load_extensions()

var c = DefaultOpenglWindowConfig
c.title = "game"
var w = new_window(c)
w.cursor_position_cb = cursor_pos_callback
w.cursor_mode = cm_disabled

glfw.make_context_current(w)

var debug_buffer: GLuint
var debug_buffer_vao: GLuint
let debug_prog = make_program((GL_VERTEX_SHADER, """
#version 450 core
layout(location = 0) in vec3 vpos;
uniform mat4 MVP;
void main() {
   gl_Position = MVP * vec4(vpos, 1.0);
}
"""),
(GL_FRAGMENT_SHADER, """
#version 450 core

out vec3 color;
uniform sampler2D diffuse;

void main() {
    color = vec3(1, 1, 0);
}
"""))

block: # setup debug draw buffer
    gl_create_vertex_arrays(1, debug_buffer_vao.addr)
    gl_create_buffers(1, debug_buffer.addr)
    gl_enable_vertex_array_attrib(debug_buffer_vao, 0)
    gl_vertex_array_vertex_buffer(debug_buffer_vao, 0, debug_buffer, 0, Vec3f.sizeof.GLsizei)
    gl_vertex_array_attrib_format(debug_buffer_vao, 0, 3, cGL_FLOAT, false, 0) # pos
    gl_named_buffer_data(debug_buffer, Vec3f.sizeof * 1024, nil, GL_DYNAMIC_DRAW)

###

let prog = make_program((GL_VERTEX_SHADER, """
#version 450 core
#extension GL_ARB_bindless_texture : require
layout(location = 0) in vec3 vpos;
layout(location = 1) in vec3 norm;
layout(location = 2) in vec2 iuv;
uniform mat4 M;
uniform mat4 MVP;

uniform mat4 lightSpaceMatrix;

out vec3 normal;
out vec3 worldPos;
out vec4 fragPosLightSpace;
out vec2 uv;
void main() {
    gl_Position = MVP * vec4(vpos, 1.0);
    uv = iuv;
    worldPos = (M * vec4(vpos, 1.0)).xyz;
    fragPosLightSpace = lightSpaceMatrix * vec4(worldPos, 1.0);
    normal = norm;
}
"""),
(GL_FRAGMENT_SHADER, """
#version 450 core
#extension GL_ARB_bindless_texture : require
in vec3 normal;
in vec3 worldPos;
in vec4 fragPosLightSpace;
in vec2 uv;
out vec3 color;
layout(bindless_sampler, location=1) uniform sampler2D diffuse;

void main() {
    vec3 lightPos = vec3(4, 4, 4);
    vec3 n = normalize(normal);
    vec3 lightDir = normalize(lightPos - worldPos);
    float diff = max(dot(n, lightDir), 0.0);
    color = diff * texture(diffuse, uv).xyz;
}
"""
))

let wireframe_prog = make_program((GL_VERTEX_SHADER, """
#version 450 core
layout(location = 0) in vec3 vpos;
layout(location = 1) in vec3 norm;
layout(location = 2) in vec2 iuv;
uniform mat4 MVP;

void main() {
   gl_Position = MVP * vec4(vpos, 1.0);
}
"""),
(GL_GEOMETRY_SHADER, """
#version 450

layout (triangles) in;
layout (line_strip /*for lines, use "points" for points*/, max_vertices=3) out;

void main(void)
{
    int i;
    for (i = 0; i < gl_in.length(); i++)
    {
        gl_Position = gl_in[i].gl_Position; //Pass through
        EmitVertex();
    }
    EndPrimitive();
}
"""
),
(GL_FRAGMENT_SHADER, """
#version 450 core

out vec3 color;
uniform sampler2D diffuse;

void main() {
    color = vec3(0, 1, 1);
}
"""
))

let player_mesh = load_mesh("ninja.obj")
drawables.add((mesh_id: player_mesh, pos: vec3f(0, 0, 0)).Drawable)
let ninja_tex = load_texture("ninja_mask.png")
let test_tex = load_texture("test.png")
texture_bindings.insert((player_mesh, ninja_tex, "diffuse").TextureBinding)

let terrain_id = load_mesh("terrain.obj")
drawables.add((mesh_id: terrain_id, pos: vec3f(0, 0, 0)).Drawable)
texture_bindings.insert((terrain_id, test_tex, "diffuse").TextureBinding)

gl_clear_color(0, 0, 0, 1)
gl_clear_depth(1)
gl_enable(GL_DEPTH_TEST)
gl_depth_func(GL_LEQUAL)

var ell = (pos: vec3f(0, 0, 0), radius: vec3f(1, 1, 1)).Ellipse

let proj: Mat4[float32] = perspective[float32](Pi / 4, width.float32 / height.float32, 0.1, 100)

let use_progs = [prog, wireframe_prog]
var use_prog_i = 0
var use_prog = use_progs[use_prog_i]

proc keyboard_callback(w: Window, key: Key, scancode: int32, action: KeyAction, modKeys: set[ModifierKey]) =
    if key == Key.keyV and action == KeyAction.kaDown:
        use_prog_i = (use_prog_i + 1) mod len(use_progs)
        use_prog = use_progs[use_prog_i]
w.key_cb = keyboard_callback

while true:
    let move_speed = if w.is_key_down(Key.keyLeftShift): 0.2 else: 0.05
    if w.is_key_down(Key.keyW): cam_pos += move_speed.float32 * cam_look
    if w.is_key_down(Key.keyS): cam_pos -= move_speed.float32 * cam_look
    if w.is_key_down(Key.keyA): cam_pos -= move_speed.float32 * cam_look.cross(cam_up).normalize
    if w.is_key_down(Key.keyD): cam_pos += move_speed.float32 * cam_look.cross(cam_up).normalize
    ####
    if w.is_key_down(Key.keyI): ell.pos.y += 0.1
    if w.is_key_down(Key.keyK): ell.pos.y -= 0.1
    if w.is_key_down(Key.keyJ): ell.pos.x += 0.1
    if w.is_key_down(Key.keyL): ell.pos.x -= 0.1

    let view: Mat4[float32] = look_at(cam_pos, cam_pos + cam_look, cam_up)
    gl_clear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) # Clear color and depth buffers
    gl_use_program(use_prog)
    debug_mesh = @[]
    for id, d in drawables:
        let mesh = meshes[d.mesh_id]

        for i, b in texture_bindings.where((drawable_id: id.uint16, texture_id: _, texture_name: _)):
            gl_uniform_handle_ui64ARB(gl_get_uniform_location(use_prog, b.texture_name), b.texture_handle)

        var m = translate(mat4f(), d.pos) # model matrix
        var mvp: Mat4[float32] = proj * view * m

        gl_uniform_matrix4fv(gl_get_uniform_location(use_prog, "MVP"), 1, false, mvp.caddr)
        gl_uniform_matrix4fv(gl_get_uniform_location(use_prog, "M"), 1, false, m.caddr)

        gl_bind_vertex_array(mesh.vao)
        gl_draw_elements(GL_TRIANGLES, mesh.nfaces.GLsizei, cGL_UNSIGNED_SHORT, cast[ptr int](0))

    #debug_edge(vec3f(0, 0, 0), vec3f(0.1,0.1,0.1))
    #debug_edge(vec3f(0.1,0.1,0.1), vec3f(-0.3,0.1,0.1))
    debug_AABB(vec3f(0, 0, 2), vec3f(1, 1, 3))
    debug_sphere(ell)

    block: # draw debug
        gl_use_program(debug_prog)
        let p = gl_map_named_buffer(debug_buffer, GL_WRITE_ONLY)
        copy_mem(p, debug_mesh[0].unsafeAddr, Vec3f.sizeof * len(debug_mesh))
        discard gl_unmap_named_buffer(debug_buffer)

        gl_bind_vertex_array(debug_buffer_vao)
        gl_bind_buffer(GL_ARRAY_BUFFER, debug_buffer)
        var mvp: Mat4[float32] = proj * view
        gl_uniform_matrix4fv(gl_get_uniform_location(debug_prog, "MVP"), 1, false, mvp.caddr)
        gl_point_size(5)
        gl_draw_arrays(GL_LINES, 0, (len(debug_mesh)).GLsizei)
        gl_draw_arrays(GL_POINTS, 0, (len(debug_mesh)).GLsizei)

    w.swap_buffers
    poll_events()
    if w.should_close == true or w.is_key_down(keyEscape):
        break

w.destroy()
glfw.terminate()