switch to raycast & bvh
[carveJwlIkooP6JGAAIwe30JlM.git] / scene.h
1 #ifndef SCENE_H
2 #define SCENE_H
3
4 #include "vg/vg.h"
5 #include "model.h"
6
7 typedef struct scene scene;
8 typedef struct bvh_node bvh_node;
9
10 struct scene
11 {
12 glmesh mesh;
13
14 model_vert *verts;
15 u32 *indices;
16
17 struct
18 {
19 bvh_node *nodes;
20 u32 node_count;
21 }
22 bvh;
23
24 u32 vertex_count,
25 indice_count,
26 vertex_cap,
27 indice_cap;
28
29 boxf bbx;
30
31 struct shadower
32 {
33 sdf_primative sdf;
34 esdf_type sdf_type;
35 }
36 *shadowers;
37
38 u32 shadower_count,
39 shadower_cap;
40
41 submodel submesh;
42 };
43
44 GLuint tex_dual_noise;
45
46 static void scene_init( scene *pscene )
47 {
48 pscene->verts = NULL;
49 pscene->indices = NULL;
50 pscene->vertex_count = 0;
51 pscene->indice_count = 0;
52 pscene->shadowers = NULL;
53 pscene->shadower_count = 0;
54 pscene->shadower_cap = 0;
55 pscene->submesh.indice_start = 0;
56 pscene->submesh.indice_count = 0;
57
58 v3_fill( pscene->bbx[0], 999999.9f );
59 v3_fill( pscene->bbx[1], -999999.9f );
60
61 static int noise_ready = 0;
62 if( !noise_ready )
63 {
64 noise_ready = 1;
65
66 u8 *buf = malloc( 256*256*2 );
67
68 for( int i=0; i<256*256; i++ )
69 {
70 u8 val = rand()&0xff;
71 buf[i*2] = val;
72 }
73
74 for( int y=0; y<256; y++ )
75 {
76 for( int x=0; x<256; x++ )
77 {
78 u8 *pr = &buf[(y*256+x)*2],
79 *pg = &buf[(((y+17)&0xff)*256+((x+37)&0xff))*2+1];
80 *pg = *pr;
81 }
82 }
83
84 /* TODO: This texture should be delted somewhere */
85 glGenTextures( 1, &tex_dual_noise );
86 glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
87 glTexImage2D( GL_TEXTURE_2D, 0, GL_RG, 256, 256, 0, GL_RG,
88 GL_UNSIGNED_BYTE, buf );
89
90 vg_tex2d_linear();
91 vg_tex2d_repeat();
92
93 free( buf );
94 }
95 }
96
97 /* https://www.shadertoy.com/view/4sfGzS */
98 #define SHADER_VALUE_NOISE_3D \
99 "uniform sampler2D uTexNoise;" \
100 "" \
101 "float noise( vec3 x )" \
102 "{" \
103 "vec3 i = floor(x);" \
104 "vec3 f = fract(x);" \
105 "f = f*f*(3.0-2.0*f);" \
106 "vec2 uv = (i.xy+vec2(37.0,17.0)*i.z) + f.xy;" \
107 "vec2 rg = texture( uTexNoise, (uv+0.5)/256.0).yx;"\
108 "return mix( rg.x, rg.y, f.z );" \
109 "}" \
110 "" \
111 "const mat3 m = mat3( 0.00, 0.80, 0.60," \
112 "-0.80, 0.36, -0.48," \
113 "-0.60, -0.48, 0.64 );" \
114 "" \
115 "float fractalNoise( vec3 x )" \
116 "{" \
117 "vec3 q = 8.0*x;" \
118 "float f;" \
119 "f = 0.5000*noise( q ); q = m*q*2.01;" \
120 "f += 0.2500*noise( q ); q = m*q*2.02;" \
121 "f += 0.1250*noise( q ); q = m*q*2.03;" \
122 "f += 0.0625*noise( q ); q = m*q*2.01;" \
123 "return f;" \
124 "}"
125
126 SHADER_DEFINE( shader_debug_vcol,
127
128 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
129
130 "uniform mat4 uPv;"
131 "uniform mat4x3 uMdl;"
132 "uniform float uTime;"
133 "uniform float uSwayAmt;"
134 ""
135 "out vec4 aColour;"
136 "out vec2 aUv;"
137 "out vec3 aNorm;"
138 "out vec3 aCo;"
139 ""
140 "vec3 compute_sway( vec3 pos )"
141 "{"
142 "vec4 sines = vec4( sin(uTime + pos.x)*1.0,"
143 "sin(uTime*1.2 + pos.z*2.0)*1.1,"
144 "sin(uTime*2.33)*0.5,"
145 "sin(uTime*0.6 + pos.x*0.3)*1.3 );"
146
147 "vec3 offset = vec3( sines.x+sines.y*sines.w, 0.0, sines.x+sines.z );"
148 "return pos + offset*a_colour.r*uSwayAmt;"
149 "}"
150 ""
151 "void main()"
152 "{"
153 "vec3 swaypos = compute_sway( a_co );"
154 "gl_Position = uPv * vec4(uMdl * vec4(swaypos,1.0), 1.0 );"
155 "aColour = a_colour;"
156 "aUv = a_uv;"
157 "aNorm = normalize(mat3(uMdl) * a_norm);"
158 "aCo = a_co;"
159 "}",
160 /* Fragment */
161 "out vec4 FragColor;"
162 ""
163 "uniform int uMode;"
164 "uniform sampler2D uTexMain;"
165 "uniform sampler2D uTexGradients;"
166 ""
167 /*Include*/ SHADER_VALUE_NOISE_3D
168 ""
169 "in vec4 aColour;"
170 "in vec2 aUv;"
171 "in vec3 aNorm;"
172 "in vec3 aCo;"
173 ""
174 "void main()"
175 "{"
176 "vec4 colour = vec4(1.0,0.0,0.5,1.0);"
177 "vec4 diffuse = texture( uTexMain, aUv );"
178
179 "if( uMode == 1 )"
180 "{"
181 "colour = vec4(aNorm * 0.5 + 0.5, 1.0);"
182 "}"
183 "if( uMode == 2 )"
184 "{"
185 "colour = aColour;"
186 "}"
187 "if( uMode == 3 )"
188 "{"
189 "float light = dot(aNorm, vec3(0.2,0.8,0.1));"
190 "vec3 grid3 = fract(aCo);"
191
192 "colour = vec4(vec3(light)*(1.0-grid3*0.3),1.0);"
193 "}"
194 "if( uMode == 4 )"
195 "{"
196 "colour = vec4( aUv, 0.0, 1.0 );"
197 "}"
198 "if( uMode == 5 )"
199 "{"
200 "if( diffuse.a < 0.45 ) discard;"
201 "colour = diffuse;"
202 "}"
203 "if( uMode == 6 )"
204 "{"
205 "float r1 = fractalNoise(aCo);"
206 "colour = vec4( vec3(r1), 1.0 );"
207 "}"
208 "if( uMode == 7 )"
209 "{"
210 "if( diffuse.a < 0.2 ) discard;"
211 "float lighting = 1.0 - aColour.g*0.8;"
212
213 "float light1 = max(0.0,dot(-vec3(0.5,-0.8,0.25), aNorm));"
214 "float light2 = max(0.0,dot(-vec3(-0.8,0.5,-0.25), aNorm));"
215 "vec3 lt = vec3(0.2,0.2,0.2 ) + "
216 "vec3(1.0,1.0,0.9)*light1 + "
217 "vec3(0.1,0.3,0.4 )*light2;"
218
219
220 "colour = vec4(vec3(pow(lighting,1.6)*(diffuse.r*0.7+0.5)),1.0);"
221 "colour = vec4(colour.rgb*lt,1.0);"
222
223 "vec2 gradUV = vec2(lighting*1.9,aColour.b*0.8);"
224 "vec4 gradient_sample = texture( uTexGradients, gradUV );"
225 "colour = colour*gradient_sample;"
226 "}"
227 "if( uMode == 8 )"
228 "{"
229 "if( diffuse.a < 0.45 ) discard;"
230 "float light = 1.0 - aColour.g;"
231 "light = pow(light,1.6)*(diffuse.r*0.7+0.5);"
232 "float r1 = fractalNoise(aCo*0.01);"
233
234 "vec2 gradUV = vec2(light*1.9,r1+aColour.b);"
235 "vec4 gradient_sample = texture( uTexGradients, gradUV );"
236 "colour = gradient_sample*light;"
237 "}"
238
239 "FragColor = colour;"
240 "}"
241 ,
242 UNIFORMS({ "uPv", "uMode", "uTexMain", "uTexGradients", "uTexNoise", \
243 "uTime", "uSwayAmt", "uMdl" })
244 )
245
246 SHADER_DEFINE( shader_standard_lit,
247
248 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
249
250 "uniform mat4 uPv;"
251 "uniform mat4x3 uMdl;"
252 ""
253 "out vec4 aColour;"
254 "out vec2 aUv;"
255 "out vec3 aNorm;"
256 "out vec3 aCo;"
257 ""
258 "void main()"
259 "{"
260 "gl_Position = uPv * vec4( uMdl * vec4(a_co,1.0), 1.0 );"
261 "aColour = a_colour;"
262 "aUv = a_uv;"
263 "aNorm = mat3(uMdl) * a_norm;"
264 "aCo = a_co;"
265 "}",
266 /* Fragment */
267 "out vec4 FragColor;"
268 ""
269 "uniform sampler2D uTexMain;"
270 "uniform vec4 uColour;"
271 ""
272 "in vec4 aColour;"
273 "in vec2 aUv;"
274 "in vec3 aNorm;"
275 "in vec3 aCo;"
276 ""
277 "void main()"
278 "{"
279 "vec3 diffuse = texture( uTexMain, aUv ).rgb;"
280
281 "float light1 = max(0.0,dot(-vec3(0.5,-0.8,0.25), aNorm));"
282 "float light2 = max(0.0,dot(-vec3(-0.8,0.5,-0.25), aNorm));"
283 "diffuse += vec3(0.2,0.2,0.2) + "
284 "vec3(1.0,1.0,0.9)*light1 + "
285 "vec3(0.1,0.3,0.4)*light2;"
286
287 "FragColor = vec4(diffuse*uColour.rgb, aColour.a*uColour.a);"
288 "}"
289 ,
290 UNIFORMS({ "uColour","uTexMain","uPv","uMdl" })
291 )
292
293 SHADER_DEFINE( shader_unlit,
294
295 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
296
297 "uniform mat4 uPv;"
298 "uniform mat4x3 uMdl;"
299 ""
300 "out vec4 aColour;"
301 "out vec2 aUv;"
302 "out vec3 aNorm;"
303 "out vec3 aCo;"
304 ""
305 "void main()"
306 "{"
307 "gl_Position = uPv * vec4(uMdl * vec4(a_co,1.0), 1.0);"
308 "aColour = a_colour;"
309 "aUv = a_uv;"
310 "aNorm = mat3(uMdl) * a_norm;"
311 "aCo = a_co;"
312 "}",
313 /* Fragment */
314 "out vec4 FragColor;"
315 ""
316 "uniform sampler2D uTexMain;"
317 "uniform vec4 uColour;"
318 ""
319 "in vec4 aColour;"
320 "in vec2 aUv;"
321 "in vec3 aNorm;"
322 "in vec3 aCo;"
323 ""
324 "void main()"
325 "{"
326 "vec3 diffuse = texture( uTexMain, aUv ).rgb;"
327 "FragColor = vec4(pow(diffuse,vec3(1.0)),1.0);"
328 "}"
329 ,
330 UNIFORMS({ "uTexMain", "uPv", "uMdl" })
331 )
332
333 static void *buffer_reserve( void *buffer, u32 count, u32 *cap, u32 amount,
334 size_t emsize )
335 {
336 if( count+amount > *cap )
337 {
338 *cap = VG_MAX( (*cap)*2, (*cap)+amount );
339
340 return realloc( buffer, (*cap) * emsize );
341 }
342
343 return buffer;
344 }
345
346 /*
347 * Append a model into the scene with a given transform
348 */
349 static void scene_add_model( scene *pscene, model *mdl, submodel *submodel,
350 v3f pos, float yaw, float scale )
351 {
352 pscene->verts = buffer_reserve( pscene->verts, pscene->vertex_count,
353 &pscene->vertex_cap, submodel->vertex_count, sizeof(model_vert) );
354 pscene->indices = buffer_reserve( pscene->indices, pscene->indice_count,
355 &pscene->indice_cap, submodel->indice_count, sizeof(u32) );
356
357 if( submodel->sdf_type )
358 {
359 pscene->shadowers = buffer_reserve( pscene->shadowers,
360 pscene->shadower_count, &pscene->shadower_cap, 1,
361 sizeof( struct shadower ));
362
363 struct shadower *shadower =
364 &pscene->shadowers[ pscene->shadower_count ++ ];
365
366 shadower->sdf = submodel->sdf;
367 shadower->sdf_type = submodel->sdf_type;
368
369 v2_muls( shadower->sdf.info, scale, shadower->sdf.info );
370 v3_muls( shadower->sdf.origin, scale, shadower->sdf.origin );
371 v3_add( pos, shadower->sdf.origin, shadower->sdf.origin );
372 }
373
374 /* Transform and place vertices */
375 model_vert *src_verts = submodel_vert_data( mdl, submodel );
376 u32 *src_indices = submodel_indice_data( mdl, submodel );
377
378 m4x3f mtx;
379 m4x3_identity( mtx );
380 m4x3_translate( mtx, pos );
381 m4x3_rotate_y( mtx, yaw );
382 m4x3_scale( mtx, scale );
383
384 boxf bbxnew;
385 box_copy( submodel->bbx, bbxnew );
386 m4x3_transform_aabb( mtx, bbxnew );
387 box_concat( pscene->bbx, bbxnew );
388
389 m3x3f rotation;
390 m4x3_to_3x3( mtx, rotation );
391
392 float rand_hue = vg_randf();
393
394 for( u32 i=0; i<submodel->vertex_count; i++ )
395 {
396 model_vert *pvert = &pscene->verts[ pscene->vertex_count+i ],
397 *src = &src_verts[ i ];
398
399 m4x3_mulv( mtx, src->co, pvert->co );
400 m3x3_mulv( rotation, src->norm, pvert->norm );
401
402 v4_copy( src->colour, pvert->colour );
403 v2_copy( src->uv, pvert->uv );
404
405 float rel_y = src->co[1] / submodel->bbx[1][1];
406 pvert->colour[0] = rel_y;
407 pvert->colour[2] = rand_hue;
408 }
409
410 for( u32 i=0; i<submodel->indice_count; i++ )
411 {
412 u32 *pidx = &pscene->indices[ pscene->indice_count+i ];
413 *pidx = src_indices[i] + pscene->vertex_count;
414 }
415
416 pscene->vertex_count += submodel->vertex_count;
417 pscene->indice_count += submodel->indice_count;
418 }
419
420 static void scene_copy_slice( scene *pscene, submodel *sm )
421 {
422 sm->indice_start = pscene->submesh.indice_start;
423 sm->indice_count = pscene->indice_count - sm->indice_start;
424
425 pscene->submesh.indice_start = pscene->indice_count;
426 }
427
428 static void scene_shadow_sphere( scene *pscene, v3f sphere,
429 v4f params, v3f lightdir )
430 {
431 for( int i=0; i<pscene->vertex_count; i++ )
432 {
433 model_vert *vert = &pscene->verts[i];
434
435 v3f delta;
436 v3_sub( sphere, vert->co, delta );
437
438 float d = v3_dot( lightdir, delta );
439 v3f closest;
440
441 v3_muls( lightdir, d, closest );
442 float dist = v3_dist( closest, delta ),
443 shading = vg_maxf( dist - params[0], 0.0f );
444
445 shading = vg_minf( shading * params[1], 1.0f );
446 vert->colour[1] *= shading;
447 }
448 }
449
450 static void scene_shadow_gradient( scene *pscene, int comp,
451 float start, float length )
452 {
453 float scale = 1.0f / length;
454
455 for( int i=0; i<pscene->vertex_count; i++ )
456 {
457 model_vert *vert = &pscene->verts[i];
458 float shading = start + vert->co[comp] * scale;
459
460 vert->colour[1] = shading;
461 }
462 }
463
464
465 /*
466 * Experimental SDF based shadows
467 *
468 * https://iquilezles.org/articles/distfunctions/
469 */
470 static float sd_cone( v3f co, sdf_primative *prim )
471 {
472 float bound = prim->info[1]*1.75f;
473 if( v3_dist2( prim->origin, co ) > bound*bound )
474 return 999999.9f;
475
476 v3f p;
477 v3_sub( co, prim->origin, p );
478
479 float h = prim->info[1];
480 v2f c = { prim->info[2], prim->info[3] };
481
482 v2f q, w, a, b;
483 v2_muls( (v2f){ c[0]/c[1], -1.0f }, h, q );
484
485 w[0] = v2_length( (v2f){ p[0], p[2] } );
486 w[1] = p[1];
487
488 v2_muladds( w, q, -vg_clampf( v2_dot(w,q)/v2_dot(q,q), 0.0f, 1.0f ), a );
489 v2_muladd( w, q, (v2f){ vg_clampf( w[0]/q[0], 0.0f, 1.0f ), 1.0f }, b );
490
491 float k = vg_signf( q[1] ),
492 d = vg_minf( v2_dot( a,a ), v2_dot( b,b ) ),
493 s = vg_maxf( k*(w[0]*q[1]-w[1]*q[0]), k*(w[1]-q[1]) );
494
495 return sqrtf(d)*vg_signf(s);
496 }
497
498 #define CACHE_AMBIENT_SHAPES
499
500 static float scene_ambient_sample( scene *pscene, v3f pos, v3f dir )
501 {
502 float accum = 0.0f;
503
504 #ifdef CACHE_AMBIENT_SHAPES
505 static struct shadower *local_shadowers[32];
506 static int local_shadower_count = 0;
507 static v3f local_shadower_last = { -99999.9f, -999999.9f, -9999999.9f };
508
509 if( v3_dist2( pos, local_shadower_last ) > 10.0f*10.0f )
510 {
511 local_shadower_count = 0;
512 v3_copy( pos, local_shadower_last );
513
514 for( int k=0; k<pscene->shadower_count; k++ )
515 {
516 struct shadower *shadower = &pscene->shadowers[k];
517
518 if( sd_cone( pos, &shadower->sdf ) <= 20.0f )
519 {
520 local_shadowers[ local_shadower_count ++ ] = shadower;
521 if( local_shadower_count == vg_list_size( local_shadowers ) )
522 break;
523 }
524 }
525 }
526 #endif
527
528 for( int j=0; j<5; j++ )
529 {
530 v3f tracepos;
531 v3_muladds( pos, dir, 1.5f*(float)j, tracepos );
532
533 float mindist = 99999.9f;
534
535 #ifndef CACHE_AMBIENT_SHAPES
536
537 for( int k=0; k<pscene->shadower_count; k++ ){
538 struct shadower *shadower = &pscene->shadowers[k];
539 #else
540
541 for( int k=0; k<local_shadower_count; k++ ){
542 struct shadower *shadower = local_shadowers[k];
543 #endif
544
545 float dist = vg_maxf( 0.0f, sd_cone( tracepos, &shadower->sdf ));
546 mindist = vg_minf( mindist, dist );
547 }
548
549
550 accum += vg_clampf( 1.0f - mindist, 0.0f, 1.0f )*0.2f;
551 }
552
553 return accum;
554 }
555
556 #define DYNAMIC_GRID
557 #define JUST_DO_EVERY_VERT
558
559 static void scene_compute_occlusion( scene *pscene )
560 {
561 v3f sundir = { 0.2f, 0.9f, 0.2f };
562 v3_normalize( sundir );
563
564 /* TODO: Make this sample grid be dynamically required.
565 *
566 * 1. Only resample the light grid (1x1x1), when a vertex is outside the
567 * current cube
568 *
569 * 2. Reorder all vertices so that each group of vertices that fit in a
570 * cube are next to eachother in the buffer. This will save cache
571 * misses.
572 *
573 * for the sorting algorithm, i think we can already assume that *most
574 * vertices will be quite close to eachother. so instead of doing an
575 * exhaustive search we can reorder 1k chunks at a time.
576 */
577
578 v3f sample_area;
579 v3_sub( pscene->bbx[1], pscene->bbx[0], sample_area );
580 v3_ceil( sample_area, sample_area );
581 int ax = sample_area[0],
582 ay = sample_area[1],
583 az = sample_area[2];
584
585 #ifndef DYNAMIC_GRID
586 float *samplegrid = malloc( ax*ay*az* sizeof(float) );
587
588 for( int x=0; x<ax; x++ ){
589 for( int y=0; y<ay; y++ ){
590 for( int z=0; z<az; z++ )
591 {
592 v3f sample_pos = { x,y,z };
593 v3_add( pscene->bbx[0], sample_pos, sample_pos );
594 float accum = scene_ambient_sample( pscene, sample_pos, sundir );
595
596 samplegrid[x + y*ax + z*ax*ay] = accum;
597 }}}
598 #else
599 v3i cube_pos = { -999999, -999999, -999999 };
600 int cube_resamples = 0, hits = 0, misses = 0;
601
602 float s0=0.0f,s1=0.0f,s2=0.0f,s3=0.0f,s4=0.0f,s5=0.0f,s6=0.0f,s7=0.0f;
603 #endif
604
605 for( int i=0; i<pscene->vertex_count; i++ )
606 {
607 model_vert *vert = &pscene->verts[i];
608 v3f rel, q;
609
610 #ifndef DYNAMIC_GRID
611 v3_sub( vert->co, pscene->bbx[0], q );
612 #else
613 v3_copy( vert->co, q );
614 #endif
615
616 v3_floor( q, rel );
617 v3_sub( q, rel, q );
618
619 int x=rel[0],
620 y=rel[1],
621 z=rel[2];
622
623 #ifndef JUST_DO_EVERY_VERT
624 #ifndef DYNAMIC_GRID
625 x = VG_MIN(x,ax-2);
626 y = VG_MIN(y,ay-2);
627 z = VG_MIN(z,az-2);
628 x = VG_MAX(x,0);
629 y = VG_MAX(y,0);
630 z = VG_MAX(z,0);
631
632 float
633 s0 = samplegrid[ x + y*ax + z*ax*ay],
634 s1 = samplegrid[(x+1) + y*ax + z*ax*ay],
635 s2 = samplegrid[ x + (y+1)*ax + z*ax*ay],
636 s3 = samplegrid[(x+1) + (y+1)*ax + z*ax*ay],
637 s4 = samplegrid[ x + y*ax + (z+1)*ax*ay],
638 s5 = samplegrid[(x+1) + y*ax + (z+1)*ax*ay],
639 s6 = samplegrid[ x + (y+1)*ax + (z+1)*ax*ay],
640 s7 = samplegrid[(x+1) + (y+1)*ax + (z+1)*ax*ay],
641 #else
642 if( x!=cube_pos[0] || y!=cube_pos[1] || z!=cube_pos[2] )
643 {
644 cube_pos[0] = x;
645 cube_pos[1] = y;
646 cube_pos[2] = z;
647
648 s0 = scene_ambient_sample( pscene, (v3f){ x,y,z }, sundir );
649 s1 = scene_ambient_sample( pscene, (v3f){ x+1,y,z }, sundir );
650 s2 = scene_ambient_sample( pscene, (v3f){ x,y+1,z }, sundir );
651 s3 = scene_ambient_sample( pscene, (v3f){ x+1,y+1,z }, sundir );
652 s4 = scene_ambient_sample( pscene, (v3f){ x,y,z+1 }, sundir );
653 s5 = scene_ambient_sample( pscene, (v3f){ x+1,y,z+1 }, sundir );
654 s6 = scene_ambient_sample( pscene, (v3f){ x,y+1,z+1 }, sundir );
655 s7 = scene_ambient_sample( pscene, (v3f){ x+1,y+1,z+1 }, sundir );
656
657 cube_resamples += 8;
658 misses ++;
659 }
660 else
661 hits ++;
662
663 float
664 #endif
665
666 s0_s1 = vg_lerpf( s0, s1, q[0] ),
667 s2_s3 = vg_lerpf( s2, s3, q[0] ),
668 s4_s5 = vg_lerpf( s4, s5, q[0] ),
669 s6_s7 = vg_lerpf( s6, s7, q[0] ),
670
671 s0s1_s2s3 = vg_lerpf( s0_s1, s2_s3, q[1] ),
672 s4s5_s6s7 = vg_lerpf( s4_s5, s6_s7, q[1] ),
673 s0s1s2s3_s4s5s6s7 = vg_lerpf( s0s1_s2s3, s4s5_s6s7, q[2] );
674
675 vert->colour[1] = s0s1s2s3_s4s5s6s7;
676 #else
677 vert->colour[1] = scene_ambient_sample( pscene, vert->co, sundir );
678 #endif
679 }
680
681 #ifndef DYNAMIC_GRID
682 int cube_resamples = -1, misses = 0, hits = 0;
683 #endif
684
685 int static_samples = ax*ay*az,
686 vertex_samples = pscene->vertex_count;
687
688 if( cube_resamples < static_samples )
689 vg_success( "Walking cube beat static grid (%d<%d. %d)!\n",
690 cube_resamples, static_samples, vertex_samples );
691 else
692 vg_warn( "Walking cube was worse than static grid (%d<%d. %d).\n",
693 cube_resamples, static_samples, vertex_samples );
694
695 vg_info( "Hits; %d, misses: %d\n", hits, misses );
696
697 #ifndef DYNAMIC_GRID
698 free( samplegrid );
699 #endif
700
701 return;
702
703 for( int i=0; i<pscene->vertex_count; i++ )
704 {
705 model_vert *vert = &pscene->verts[i];
706 float accum = 0.0f;
707
708 for( int j=0; j<5; j++ )
709 {
710 v3f tracepos;
711 v3_copy( vert->co, tracepos );
712 v3_muladds( tracepos, sundir, 1.5f*(float)j, tracepos );
713
714 float mindist = 99999.9f;
715
716 for( int k=0; k<pscene->shadower_count; k++ )
717 {
718 struct shadower *shadower = &pscene->shadowers[k];
719 float dist = vg_maxf( 0.0f, sd_cone( tracepos, &shadower->sdf ));
720 mindist = vg_minf( mindist, dist );
721 }
722
723 accum += vg_clampf( 1.0f - mindist, 0.0f, 1.0f )*0.2f;
724 }
725
726 vert->colour[1] = vg_minf( accum, 1.0f );
727 }
728 }
729
730 static void scene_upload( scene *pscene )
731 {
732 mesh_upload( &pscene->mesh,
733 pscene->verts, pscene->vertex_count,
734 pscene->indices, pscene->indice_count );
735
736 vg_info( "Scene upload\n" );
737 vg_info( " indices:%u\n", pscene->indice_count );
738 vg_info( " verts:%u\n", pscene->vertex_count );
739 }
740
741 float scene_tree_sway = 0.1f;
742
743 #if 0
744 static void scene_foliage_shader_use(void)
745 {
746 SHADER_USE( shader_debug_vcol );
747
748 glUniformMatrix4fv( SHADER_UNIFORM( shader_debug_vcol, "uPv" ),
749 1, GL_FALSE, (float *)vg_pv );
750
751 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uMode" ), debugview );
752 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexMain" ), 0 );
753
754 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexGradients" ), 1 );
755 vg_tex2d_bind( &tex_gradients, 1 );
756
757 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexNoise" ), 2 );
758 glActiveTexture( GL_TEXTURE2 );
759 glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
760
761 glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uTime" ), vg_time );
762 glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uSwayAmt" ),
763 scene_tree_sway );
764 }
765 #endif
766
767 static void scene_bind( scene *pscene )
768 {
769 mesh_bind( &pscene->mesh );
770 }
771
772 static void scene_draw( scene *pscene )
773 {
774 mesh_drawn( 0, pscene->indice_count );
775 }
776
777 static void scene_debugsdf( scene *pscene )
778 {
779 for( int i=0; i<pscene->shadower_count; i++ )
780 {
781 struct shadower *shadower = &pscene->shadowers[i];
782
783 v3f base, side;
784 v3_copy( shadower->sdf.origin, base );
785 base[1] -= shadower->sdf.info[1];
786 v3_copy( base, side );
787 side[0] += shadower->sdf.info[0];
788
789 vg_line2( shadower->sdf.origin, base, 0xff00ff00, 0xff0000ff );
790 vg_line2( side, base, 0xff00ff00, 0xff0000ff );
791 vg_line( side, shadower->sdf.origin, 0xff00ff00 );
792 }
793
794 v3f p0 = { pscene->bbx[0][0], pscene->bbx[0][1], pscene->bbx[0][2] },
795 p1 = { pscene->bbx[0][0], pscene->bbx[1][1], pscene->bbx[0][2] },
796 p2 = { pscene->bbx[1][0], pscene->bbx[1][1], pscene->bbx[0][2] },
797 p3 = { pscene->bbx[1][0], pscene->bbx[0][1], pscene->bbx[0][2] },
798
799 p4 = { pscene->bbx[0][0], pscene->bbx[0][1], pscene->bbx[1][2] },
800 p5 = { pscene->bbx[0][0], pscene->bbx[1][1], pscene->bbx[1][2] },
801 p6 = { pscene->bbx[1][0], pscene->bbx[1][1], pscene->bbx[1][2] },
802 p7 = { pscene->bbx[1][0], pscene->bbx[0][1], pscene->bbx[1][2] };
803
804 u32 col = 0xffff00c8;
805 vg_line( p0, p1, col );
806 vg_line( p1, p2, col );
807 vg_line( p2, p3, col );
808 vg_line( p3, p0, col );
809
810 vg_line( p4, p5, col );
811 vg_line( p5, p6, col );
812 vg_line( p6, p7, col );
813 vg_line( p7, p4, col );
814
815 vg_line( p0, p4, col );
816 vg_line( p1, p5, col );
817 vg_line( p2, p6, col );
818 vg_line( p3, p7, col );
819 }
820
821 static void scene_register(void)
822 {
823 SHADER_INIT( shader_debug_vcol );
824 SHADER_INIT( shader_standard_lit );
825 SHADER_INIT( shader_unlit );
826 }
827
828
829 /* Physics segment */
830
831 static int triangle_raycast2d( v3f pA, v3f pB, v3f pC, v3f ray, float *height )
832 {
833 v2f v0, v1, v2, vp, vp2;
834 float d, bca = 0.f, bcb = 0.f, bcc = 0.f;
835
836 v0[0] = pB[0] - pA[0];
837 v0[1] = pB[2] - pA[2];
838 v1[0] = pC[0] - pA[0];
839 v1[1] = pC[2] - pA[2];
840 v2[0] = pB[0] - pC[0];
841 v2[1] = pB[2] - pC[2];
842
843 d = 1.f / (v0[0]*v1[1] - v1[0]*v0[1]);
844
845 #if 0
846 /* Backface culling */
847 if( v2_cross( v0, v1 ) > 0.f )
848 return;
849 #endif
850
851 vp[0] = ray[0] - pA[0];
852 vp[1] = ray[2] - pA[2];
853
854 if( v2_cross( v0, vp ) > 0.f ) return 0;
855 if( v2_cross( vp, v1 ) > 0.f ) return 0;
856
857 vp2[0] = ray[0] - pB[0];
858 vp2[1] = ray[2] - pB[2];
859
860 if( v2_cross( vp2, v2 ) > 0.f ) return 0;
861
862 bcb = (vp[0]*v1[1] - v1[0]*vp[1]) * d;
863 bcc = (v0[0]*vp[1] - vp[0]*v0[1]) * d;
864 bca = 1.f - bcb - bcc;
865
866 *height = pA[1]*bca + pB[1]*bcb + pC[1]*bcc;
867 return 1;
868 }
869
870 /* Temporary */
871 static int sample_scene_height( scene *pscene, v3f pos, v3f norm )
872 {
873 for( int i=0; i<pscene->indice_count/3; i++ )
874 {
875 u32 *tri = &pscene->indices[i*3];
876
877 float *pA = pscene->verts[tri[0]].co,
878 *pB = pscene->verts[tri[1]].co,
879 *pC = pscene->verts[tri[2]].co;
880
881 float height;
882 if( triangle_raycast2d( pA, pB, pC, pos, &height ))
883 {
884 pos[1] = height;
885
886 if( norm )
887 {
888 v3f v0, v1;
889 v3_sub( pA, pB, v0 );
890 v3_sub( pC, pB, v1 );
891 v3_cross( v1, v0, norm );
892 v3_normalize( norm );
893 }
894
895 return 1;
896 }
897 }
898 return 0;
899 }
900
901 static void sample_scene_normal( scene *pscene, v3f pos, v3f normal )
902 {
903 for( int i=0; i<pscene->indice_count/3; i++ )
904 {
905 u32 *tri = &pscene->indices[i*3];
906
907 float height;
908 if( triangle_raycast2d(
909 pscene->verts[ tri[0] ].co,
910 pscene->verts[ tri[1] ].co,
911 pscene->verts[ tri[2] ].co, pos, &height ))
912 {
913 v3f v0, v1;
914
915 v3_sub( pscene->verts[ tri[1] ].co,
916 pscene->verts[ tri[0] ].co,
917 v0 );
918
919 v3_sub( pscene->verts[ tri[2] ].co,
920 pscene->verts[ tri[0] ].co,
921 v1 );
922
923 v3_cross( v0, v1, normal );
924 v3_normalize( normal );
925 return;
926 }
927 }
928
929 normal[0] = 0.0f;
930 normal[1] = 1.0f;
931 normal[2] = 0.0f;
932 }
933
934 struct bvh_node
935 {
936 boxf bbx;
937
938 /* if il is 0, this is a leaf */
939 u32 il, count;
940 union{ u32 ir, start; };
941 };
942
943 static void bvh_update_bounds( scene *s, u32 inode )
944 {
945 bvh_node *node = &s->bvh.nodes[ inode ];
946
947 box_init_inf( node->bbx );
948 for( u32 i=0; i<node->count; i++ )
949 {
950 u32 idx = node->start+i;
951 model_vert *pa = &s->verts[ s->indices[idx*3+0] ],
952 *pb = &s->verts[ s->indices[idx*3+1] ],
953 *pc = &s->verts[ s->indices[idx*3+2] ];
954
955 box_addpt( node->bbx, pa->co );
956 box_addpt( node->bbx, pb->co );
957 box_addpt( node->bbx, pc->co );
958 }
959 }
960
961 static void bvh_subdiv( scene *s, u32 inode )
962 {
963 bvh_node *node = &s->bvh.nodes[ inode ];
964
965 v3f extent;
966 v3_sub( node->bbx[1], node->bbx[0], extent );
967
968 int axis = 0;
969 if( extent[1] > extent[0] ) axis = 1;
970 if( extent[2] > extent[axis] ) axis = 2;
971
972 float split = node->bbx[0][axis] + extent[axis]*0.5f;
973
974 i32 i = node->start,
975 j = i + node->count-1;
976
977 while( i <= j )
978 {
979 u32 *ti = &s->indices[i*3];
980
981 float a = s->verts[ti[0]].co[axis],
982 b = s->verts[ti[1]].co[axis],
983 c = s->verts[ti[2]].co[axis];
984
985 if( ((a+b+c) / 3.0f) < split )
986 i ++;
987 else
988 {
989 /* Swap triangle indices */
990 u32 *tj = &s->indices[j*3];
991 u32 temp[3];
992 temp[0] = ti[0];
993 temp[1] = ti[1];
994 temp[2] = ti[2];
995
996 ti[0] = tj[0];
997 ti[1] = tj[1];
998 ti[2] = tj[2];
999
1000 tj[0] = temp[0];
1001 tj[1] = temp[1];
1002 tj[2] = temp[2];
1003
1004 j --;
1005 }
1006 }
1007
1008 u32 left_count = i - node->start;
1009 if( left_count == 0 || left_count == node->count ) return;
1010
1011 u32 il = s->bvh.node_count ++,
1012 ir = s->bvh.node_count ++;
1013
1014 struct bvh_node *lnode = &s->bvh.nodes[il],
1015 *rnode = &s->bvh.nodes[ir];
1016
1017 lnode->start = node->start;
1018 lnode->count = left_count;
1019 rnode->start = i;
1020 rnode->count = node->count - left_count;
1021
1022 node->il = il;
1023 node->ir = ir;
1024 node->count = 0;
1025
1026 bvh_update_bounds( s, il );
1027 bvh_update_bounds( s, ir );
1028 bvh_subdiv( s, il );
1029 bvh_subdiv( s, ir );
1030 }
1031
1032 static void bvh_create( scene *s )
1033 {
1034 u32 triangle_count = s->indice_count / 3;
1035 s->bvh.nodes = malloc( sizeof(struct bvh_node) * (triangle_count*2-1) );
1036
1037 bvh_node *root = &s->bvh.nodes[0];
1038 s->bvh.node_count = 1;
1039
1040 root->il = 0;
1041 root->ir = 0;
1042 root->count = triangle_count;
1043 root->start = 0;
1044
1045 bvh_update_bounds( s, 0 );
1046 bvh_subdiv( s, 0 );
1047
1048 s->bvh.nodes =
1049 realloc( s->bvh.nodes, sizeof(struct bvh_node) * s->bvh.node_count );
1050
1051 vg_success( "BVH done, size: %u/%u\n", s->bvh.node_count,
1052 (triangle_count*2-1) );
1053 }
1054
1055 static void bvh_debug_node( scene *s, u32 inode, v3f pos, u32 colour )
1056 {
1057 struct bvh_node *node = &s->bvh.nodes[ inode ];
1058
1059 if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
1060 (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
1061 {
1062 if( !node->count )
1063 {
1064 vg_line_boxf( node->bbx, colour );
1065
1066 bvh_debug_node( s, node->il, pos, colour );
1067 bvh_debug_node( s, node->ir, pos, colour );
1068 }
1069 else
1070 {
1071 vg_line_boxf( node->bbx, 0xff00ff00 );
1072 for( u32 i=0; i<node->count; i++ )
1073 {
1074 u32 idx = (node->start+i)*3;
1075
1076 model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
1077 *pb = &s->verts[ s->indices[ idx+1 ] ],
1078 *pc = &s->verts[ s->indices[ idx+2 ] ];
1079
1080 vg_line( pa->co, pb->co, 0xff0000ff );
1081 vg_line( pb->co, pc->co, 0xff0000ff );
1082 vg_line( pc->co, pa->co, 0xff0000ff );
1083 }
1084 }
1085 }
1086 }
1087
1088 static void bvh_debug( scene *s, v3f pos )
1089 {
1090 bvh_debug_node( s, 0, pos, 0x4000ffa8 );
1091 }
1092
1093 static int bvh_scene_sample_node( scene *s, u32 inode, v3f pos, v3f norm )
1094 {
1095 bvh_node *node = &s->bvh.nodes[ inode ];
1096
1097 if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
1098 (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
1099 {
1100 if( !node->count )
1101 {
1102 if( bvh_scene_sample_node( s, node->il, pos, norm )) return 1;
1103 if( bvh_scene_sample_node( s, node->ir, pos, norm )) return 1;
1104 }
1105 else
1106 {
1107 for( u32 i=0; i<node->count; i++ )
1108 {
1109 u32 idx = (node->start+i)*3;
1110 model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
1111 *pb = &s->verts[ s->indices[ idx+1 ] ],
1112 *pc = &s->verts[ s->indices[ idx+2 ] ];
1113
1114 float height;
1115 if( triangle_raycast2d( pa->co, pb->co, pc->co, pos, &height ))
1116 {
1117 pos[1] = height;
1118
1119 if( norm )
1120 {
1121 v3f v0, v1;
1122 v3_sub( pa->co, pb->co, v0 );
1123 v3_sub( pc->co, pb->co, v1 );
1124 v3_cross( v1, v0, norm );
1125 v3_normalize( norm );
1126 }
1127
1128 return 1;
1129 }
1130 }
1131 }
1132 }
1133
1134 return 0;
1135 }
1136
1137 static int bvh_scene_sample( scene *s, v3f pos, v3f norm)
1138 {
1139 return bvh_scene_sample_node( s, 0, pos, norm );
1140 }
1141
1142 typedef struct ray_hit ray_hit;
1143 struct ray_hit
1144 {
1145 float dist;
1146 u32 *tri;
1147 v3f pos, normal;
1148 };
1149
1150 int ray_aabb( boxf box, v3f co, v3f dir, float dist )
1151 {
1152 v3f v0, v1;
1153 float tmin, tmax;
1154
1155 v3_sub( box[0], co, v0 );
1156 v3_sub( box[1], co, v1 );
1157 v3_div( v0, dir, v0 );
1158 v3_div( v1, dir, v1 );
1159
1160 tmin = vg_minf( v0[0], v1[0] );
1161 tmax = vg_maxf( v0[0], v1[0] );
1162 tmin = vg_maxf( tmin, vg_minf( v0[1], v1[1] ));
1163 tmax = vg_minf( tmax, vg_maxf( v0[1], v1[1] ));
1164 tmin = vg_maxf( tmin, vg_minf( v0[2], v1[2] ));
1165 tmax = vg_minf( tmax, vg_maxf( v0[2], v1[2] ));
1166
1167 return tmax >= tmin && tmin < dist && tmax > 0;
1168 }
1169
1170 static int bvh_ray_tri( scene *sc, u32 *tri, v3f co, v3f dir, ray_hit *hit )
1171 {
1172 float const kEpsilon = 0.00001f;
1173
1174 v3f v0, v1, h, s, q, n;
1175 float a,f,u,v,t;
1176
1177 float *pa = sc->verts[tri[0]].co,
1178 *pb = sc->verts[tri[1]].co,
1179 *pc = sc->verts[tri[2]].co;
1180
1181 v3_sub( pb, pa, v0 );
1182 v3_sub( pc, pa, v1 );
1183 v3_cross( dir, v1, h );
1184 v3_cross( v0, v1, n );
1185
1186 if( v3_dot( n, dir ) > 0.0f ) /* Backface culling */
1187 return 0;
1188
1189 /* Parralel */
1190 a = v3_dot( v0, h );
1191 if( a > -kEpsilon && a < kEpsilon )
1192 return 0;
1193
1194 f = 1.0f/a;
1195 v3_sub( co, pa, s );
1196
1197 u = f * v3_dot(s, h);
1198 if( u < 0.0f || u > 1.0f )
1199 return 0;
1200
1201 v3_cross( s, v0, q );
1202 v = f * v3_dot( dir, q );
1203 if( v < 0.0f || u+v > 1.0f )
1204 return 0;
1205
1206 t = f * v3_dot(v1, q);
1207 if( t > kEpsilon && t < hit->dist )
1208 {
1209 hit->dist = t;
1210 hit->tri = tri;
1211 return 1;
1212 }
1213 else return 0;
1214 }
1215
1216 static int bvh_ray( scene *s, u32 inode, v3f co, v3f dir, ray_hit *hit )
1217 {
1218 bvh_node *node = &s->bvh.nodes[ inode ];
1219
1220 if( !ray_aabb( node->bbx, co, dir, hit->dist ))
1221 return 0;
1222
1223 int count = 0;
1224
1225 if( node->count )
1226 {
1227 for( u32 i=0; i<node->count; i++ )
1228 {
1229 u32 *indices = &s->indices[ (node->start+i)*3 ];
1230 count += bvh_ray_tri( s, indices, co, dir, hit );
1231 }
1232 }
1233 else
1234 {
1235 count += bvh_ray( s, node->il, co, dir, hit );
1236 count += bvh_ray( s, node->ir, co, dir, hit );
1237 }
1238
1239 return count;
1240 }
1241
1242 static int bvh_raycast( scene *s, v3f co, v3f dir, ray_hit *hit )
1243 {
1244 v3f pb;
1245 v3_muladds( co, dir, hit->dist, pb );
1246
1247 int count = bvh_ray( s, 0, co, dir, hit );
1248
1249 if( count )
1250 {
1251 vg_line( co, pb, 0xff00ffff );
1252
1253 v3f v0, v1;
1254
1255 float *pa = s->verts[hit->tri[0]].co,
1256 *pb = s->verts[hit->tri[1]].co,
1257 *pc = s->verts[hit->tri[2]].co;
1258
1259 v3_sub( pa, pb, v0 );
1260 v3_sub( pc, pb, v1 );
1261 v3_cross( v1, v0, hit->normal );
1262 v3_normalize( hit->normal );
1263 v3_muladds( co, dir, hit->dist, hit->pos );
1264 }
1265 else
1266 vg_line( co, pb, 0xff0000ff );
1267
1268 return count;
1269 }
1270
1271 #endif