-
Notifications
You must be signed in to change notification settings - Fork 0
/
dependencies.js
1562 lines (1305 loc) · 68.6 KB
/
dependencies.js
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SHADOW_DEPTH_TEXTURE_SIZE = 2048*2;
// Subclasses of Shader each store and manage a complete GPU program. This Shader is
// the simplest example of one. It samples pixels from colors that are directly assigned
// to the vertices. Materials here are minimal, without any settings.
window.Basic_Shader = window.classes.Basic_Shader = class Basic_Shader extends Shader {
material() {
return {
shader: this
}
}
// The shader will pull single entries out of the vertex arrays, by their data fields'
// names. Map those names onto the arrays we'll pull them from. This determines
// which kinds of Shapes this Shader is compatible with. Thanks to this function,
// Vertex buffers in the GPU can get their pointers matched up with pointers to
// attribute names in the GPU. Shapes and Shaders can still be compatible even
// if some vertex data feilds are unused.
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions",
color: "colors"
}[name];
}
// Define how to synchronize our JavaScript's letiables to the GPU's:
update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl) {
const PCM = g_state.projection_transform.times(g_state.camera_transform).times(model_transform);
gl.uniformMatrix4fv(gpu.projection_camera_model_transform_loc, false, Mat.flatten_2D_to_1D(PCM.transposed()));
}
// ********* SHARED CODE, INCLUDED IN BOTH SHADERS *********
shared_glsl_code() {
return `
precision mediump float;
varying vec4 VERTEX_COLOR;`;
}
// ********* VERTEX SHADER *********
vertex_glsl_code() {
return `
attribute vec4 color;
attribute vec3 object_space_pos;
uniform mat4 projection_camera_model_transform;
void main() {
// The vertex's final resting place (in NDCS).
gl_Position = projection_camera_model_transform * vec4(object_space_pos, 1.0);
// Use the hard-coded color of the vertex.
VERTEX_COLOR = color;
}`;
}
// ********* FRAGMENT SHADER *********
fragment_glsl_code() {
return `
void main() {
// The interpolation gets done directly on the per-vertex colors.
gl_FragColor = VERTEX_COLOR;
}`;
}
}
window.Physics_Shader = window.classes.Physics_Shader = class Physics_Shader extends Shader {
// Define an internal class "Material" that stores the standard settings found in Phong lighting.
material(color) {
// Possible properties: ambient, diffusivity, specularity, smoothness, texture.
return new class Material {
constructor(shader, color=Color.of(1, 0, 0, 1)) {
// Assign defaults.
Object.assign(this, {
shader,
color
});
}
}
(this,color);
}
// The shader will pull single entries out of the vertex arrays, by their data fields'
// names. Map those names onto the arrays we'll pull them from. This determines
// which kinds of Shapes this Shader is compatible with. Thanks to this function,
// Vertex buffers in the GPU can get their pointers matched up with pointers to
// attribute names in the GPU. Shapes and Shaders can still be compatible even
// if some vertex data feilds are unused.
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions"
}[name];
}
// Define how to synchronize our JavaScript's variables to the GPU's:
update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl) {
const PCM = g_state.projection_transform.times(g_state.camera_transform).times(model_transform);
gl.uniformMatrix4fv(gpu.projection_camera_model_transform_loc, false, Mat.flatten_2D_to_1D(PCM.transposed()));
gl.uniform4fv(gpu.shapeColor_loc, material.color);
}
// ********* SHARED CODE, INCLUDED IN BOTH SHADERS *********
shared_glsl_code() {
return `
precision mediump float;
varying vec4 VERTEX_COLOR;
uniform vec4 shapeColor;`;
}
// ********* VERTEX SHADER *********
vertex_glsl_code() {
return `
attribute vec4 color;
attribute vec3 object_space_pos;
uniform mat4 projection_camera_model_transform;
void main() {
// The vertex's final resting place (in NDCS).
gl_Position = projection_camera_model_transform * vec4(object_space_pos, 1.0);
gl_PointSize = 10.;
// gl_LineWidth = 10.;
// Use the hard-coded color of the vertex.
// VERTEX_COLOR = color;
VERTEX_COLOR = shapeColor;
}`;
}
// ********* FRAGMENT SHADER *********
fragment_glsl_code() {
return `
void main() {
// The interpolation gets done directly on the per-vertex colors.
gl_FragColor = VERTEX_COLOR;
}`;
}
}
window.Light_Shader = window.classes.Light_Shader = class Light_Shader extends Shader {
constructor(gl) {
super(gl);
this.shadowDepthTextureSize = SHADOW_DEPTH_TEXTURE_SIZE;
this.shadowFramebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, this.shadowFramebuffer);
this.shadowDepthTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.shadowDepthTexture)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.shadowDepthTextureSize,
this.shadowDepthTextureSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null)
this.renderBuffer = gl.createRenderbuffer()
gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer)
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
this.shadowDepthTextureSize, this.shadowDepthTextureSize)
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.shadowDepthTexture, 0)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer)
gl.bindTexture(gl.TEXTURE_2D, null)
gl.bindRenderbuffer(gl.RENDERBUFFER, null)
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
}
material(color) {
return new class Material {
constructor(shader, color=Color.of(1, 0, 0, 1)) {
// Assign defaults.
Object.assign(this, {
shader,
color
});
}
}
(this, color);
}
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions"
}[name];
}
vertex_glsl_code() {
return `
attribute vec3 object_space_pos;
// uniform mat4 projection_camera_model_transform;
// uniform mat4 LightMatrix;
uniform mat4 uPMatrix;
uniform mat4 uMVMatrix;
void main (void) {
gl_Position = uPMatrix * uMVMatrix * vec4(object_space_pos, 1.0);
}
`;
}
fragment_glsl_code() {
return `
precision mediump float;
vec4 encodeFloat (float depth) {
const vec4 bitShift = vec4(
256 * 256 * 256,
256 * 256,
256,
1.0
);
const vec4 bitMask = vec4(
0,
1.0 / 256.0,
1.0 / 256.0,
1.0 / 256.0
);
vec4 comp = fract(depth * bitShift);
comp -= comp.xxyz * bitMask;
return comp;
}
void main (void) {
gl_FragColor = encodeFloat(gl_FragCoord.z);
// gl_FragColor = vec4(0., 0., 1., 1.);
}
`
}
update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl) {
gl.uniformMatrix4fv(gpu.uPMatrix_loc, false, Mat.flatten_2D_to_1D(g_state.light_projection_transform.transposed()))
// gl.uniformMatrix4fv(gpu.uMVMatrix_loc, false, Mat.flatten_2D_to_1D(g_state.light_view_matrix))
gl.uniformMatrix4fv(gpu.uMVMatrix_loc, false,
Mat.flatten_2D_to_1D(g_state.light_view_matrix.times(model_transform).transposed()))
// let light_pos = g_state.lights[0].position,
// // model_pos = model_transform.times(Vec.of(0, 0, 0, 1)),
// model_pos = Vec.of(0, 0, 0),
// up_dir = light_pos.minus(model_pos).cross(model_pos);
// if (up_dir.dot(up_dir))
// gl.uniformMatrix4fv(gpu.lightMVMatrix_loc, false,
// Mat.flatten_2D_to_1D(Mat4.look_at(light_pos, model_pos, up_dir).transposed()));
// const PCM = g_state.projection_transform.times(g_state.camera_transform).times(model_transform);
// const PLM = g_state.light_projection_transform.times(g_state.light_transform).times(model_transform);
// gl.uniformMatrix4fv(gpu.projection_camera_model_transform_loc, false, Mat.flatten_2D_to_1D(PCM.transposed()));
// gl.uniformMatrix4fv(gpu.LightMatrix_loc, false, Mat.flatten_2D_to_1D(PLM.transposed()));
}
}
window.Camera_Shader = window.classes.Camera_Shader = class Camera_Shader extends Shader {
load_light_shader(light_shader) {
this.light_shader = light_shader;
}
get shadowDepthTexture() {
return this.light_shader.shadowDepthTexture;
}
get shadowDepthTextureSize() {
return SHADOW_DEPTH_TEXTURE_SIZE;
}
material(color) {
return new class Material {
constructor(shader, color=Color.of(1, 0, 0, 1)) {
// Assign defaults.
Object.assign(this, {
shader,
color
});
}
override(properties) {
const copied = new this.constructor();
Object.assign(copied, this);
Object.assign(copied, properties);
copied.color = copied.color.copy();
if (properties["opacity"] != undefined)
copied.color[3] = properties["opacity"];
return copied;
}
}
(this, color);
}
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions",
normal: "normals",
tex_coord: "texture_coords"
}[name];
}
vertex_glsl_code() {
return `
attribute vec3 object_space_pos;
attribute vec2 tex_coord;
// uniform mat4 projection_camera_model_transform;
// uniform mat4 LightMatrix;
uniform mat4 uPMatrix;
uniform mat4 uMVMatrix;
uniform mat4 lightPMatrix;
uniform mat4 lightMVMatrix;
varying vec2 f_tex_coord;
const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5,
0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
// const mat4 texUnitConverter = mat4(1., 0.0, 0.0, 0.0, 0.0, 1.,
// 0.0, 0.0, 0.0, 0.0, 1., 0.0, 1., 1., 1., 1.0);
varying vec4 shadowPos;
void main (void) {
gl_Position = uPMatrix * uMVMatrix * vec4(object_space_pos, 1.0);
// gl_Position = vec4(object_space_pos, 1.0);
shadowPos = texUnitConverter * lightPMatrix * lightMVMatrix * vec4(object_space_pos, 1.0);
f_tex_coord = tex_coord;
}
`;
}
fragment_glsl_code() {
return `
precision mediump float;
varying vec4 shadowPos;
varying vec2 f_tex_coord;
uniform sampler2D depthColorTexture;
uniform vec3 uColor;
float decodeFloat (vec4 color) {
const vec4 bitShift = vec4(
1.0 / (256.0 * 256.0 * 256.0),
1.0 / (256.0 * 256.0),
1.0 / 256.0,
1
);
return dot(color, bitShift);
}
void main(void) {
vec3 fragmentDepth = shadowPos.xyz;
float shadowAcneRemover = 0.007;
fragmentDepth.z -= shadowAcneRemover;
float texelSize = 1.0 / ${this.shadowDepthTextureSize}.0;
float amountInLight = 0.0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
float texelDepth = decodeFloat(texture2D(depthColorTexture,
fragmentDepth.xy + vec2(x, y) * texelSize));
if (fragmentDepth.z < texelDepth) {
amountInLight += 1.0;
}
}
}
amountInLight /= 9.0;
gl_FragColor = vec4(amountInLight * uColor, 1.0);
// gl_FragColor = shadowPos * .01;
// gl_FragColor = vec4(fragmentDepth*.008, 1.0);
// gl_FragColor = texture2D(depthColorTexture, f_tex_coord);
// gl_FragColor = vec4(uColor, 1.);
// gl_FragColor = vec4(decodeFloat(texture2D( depthColorTexture, f_tex_coord)) * vec3(1., 0., 1.), 1.0);
// vec4 tex_color = texture2D( depthColorTexture, shadowPos.xy * vec2(.01, .005) );
// gl_FragColor = vec4( ( tex_color.xyz ), tex_color.w );
}
`;
}
update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl) {
gl.uniformMatrix4fv(gpu.uPMatrix_loc, false,
Mat.flatten_2D_to_1D(g_state.projection_transform.transposed()));
gl.uniformMatrix4fv(gpu.uMVMatrix_loc, false,
Mat.flatten_2D_to_1D(g_state.camera_transform.times(model_transform).transposed()))
gl.uniformMatrix4fv(gpu.lightPMatrix_loc, false,
Mat.flatten_2D_to_1D(g_state.light_projection_transform.transposed()));
gl.uniformMatrix4fv(gpu.lightMVMatrix_loc, false,
Mat.flatten_2D_to_1D(g_state.light_view_matrix.times(model_transform).transposed()));
// console.log(g_state.light_projection_transform.times(g_state.light_view_matrix.times(model_transform)));
gl.uniform3fv(gpu.uColor_loc, material.color.to3())
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, this.shadowDepthTexture);
gl.uniform1i(gpu.depthColorTexture_loc, 0);
}
}
window.Phong_Shadow_Shader = window.classes.Phong_Shadow_Shader = class Phong_Shadow_Shader extends Camera_Shader {
material(color, properties) {
// Possible properties: ambient, diffusivity, specularity, smoothness, texture.
return new class Material {
constructor(shader, color=Color.of(0, 0, 0, 1), ambient=0, diffusivity=1, specularity=1, smoothness=40) {
// Assign defaults.
Object.assign(this, {
shader,
color,
ambient,
diffusivity,
specularity,
smoothness
});
// Optionally override defaults.
Object.assign(this, properties);
}
// Easily make temporary overridden versions of a base material, such as
// of a different color or diffusivity. Use "opacity" to override only that.
override(properties) {
const copied = new this.constructor();
Object.assign(copied, this);
Object.assign(copied, properties);
copied.color = copied.color.copy();
if (properties["opacity"] != undefined)
copied.color[3] = properties["opacity"];
return copied;
}
}
(this,color);
}
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions",
normal: "normals",
tex_coord: "texture_coords"
}[name];
}
shared_glsl_code()
{
return `
precision mediump float;
// We're limited to only so many inputs in hardware. Lights are costly (lots of sub-values).
const int N_LIGHTS = 2;
uniform float ambient, diffusivity, specularity, smoothness, animation_time, attenuation_factor[N_LIGHTS];
// Flags for alternate shading methods
uniform bool GOURAUD, COLOR_NORMALS, USE_TEXTURE;
uniform vec4 lightPosition[N_LIGHTS], lightColor[N_LIGHTS], shapeColor;
// Specifier "varying" means a variable's final value will be passed from the vertex shader
// on to the next phase (fragment shader), then interpolated per-fragment, weighted by the
// pixel fragment's proximity to each of the 3 vertices (barycentric interpolation).
varying vec3 N, E;
varying vec2 f_tex_coord;
varying vec4 VERTEX_COLOR;
varying vec3 L[N_LIGHTS];
varying float dist[N_LIGHTS];
vec3 phong_model_lights( vec3 N ) {
vec3 result = vec3(0.0);
for(int i = 0; i < N_LIGHTS; i++) {
vec3 H = normalize( L[i] + E );
float attenuation_multiplier = 1.0;// / (1.0 + attenuation_factor[i] * (dist[i] * dist[i]));
float diffuse = max( dot(N, L[i]), 0.0 );
float specular = pow( max( dot(N, H), 0.0 ), smoothness );
result += attenuation_multiplier * ( shapeColor.xyz * diffusivity * diffuse + lightColor[i].xyz * specularity * specular );
}
return result;
}`;
}
vertex_glsl_code() {
return `
attribute vec3 object_space_pos, normal;
attribute vec2 tex_coord;
uniform mat4 uPMatrix;
uniform mat4 uMVMatrix;
uniform mat4 lightPMatrix;
uniform mat4 lightMVMatrix;
const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5,
0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
varying vec4 shadowPos;
uniform mat4 camera_transform, camera_model_transform, projection_camera_model_transform;
uniform mat3 inverse_transpose_modelview;
void main() {
// The vertex's final resting place (in NDCS).
gl_Position = projection_camera_model_transform * vec4(object_space_pos, 1.0);
// The final normal vector in screen space.
N = normalize( inverse_transpose_modelview * normal );
// Directly use original texture coords and interpolate between.
f_tex_coord = tex_coord;
// Bypass all lighting code if we're lighting up vertices some other way.
if( COLOR_NORMALS ) {
// In "normals" mode, rgb color = xyz quantity. Flash if it's negative.
VERTEX_COLOR = vec4( N[0] > 0.0 ? N[0] : sin( animation_time * 3.0 ) * -N[0],
N[1] > 0.0 ? N[1] : sin( animation_time * 15.0 ) * -N[1],
N[2] > 0.0 ? N[2] : sin( animation_time * 45.0 ) * -N[2] , 1.0 );
return;
}
// The rest of this shader calculates some quantities that the Fragment shader will need:
vec3 camera_space_pos = ( camera_model_transform * vec4(object_space_pos, 1.0) ).xyz;
E = normalize( -camera_space_pos );
// Light positions use homogeneous coords. Use w = 0 for a directional light source -- a vector instead of a point.
for( int i = 0; i < N_LIGHTS; i++ ) {
L[i] = normalize( ( camera_transform * lightPosition[i] ).xyz - lightPosition[i].w * camera_space_pos );
// Is it a point light source? Calculate the distance to it from the object. Otherwise use some arbitrary distance.
dist[i] = lightPosition[i].w > 0.0 ? distance((camera_transform * lightPosition[i]).xyz, camera_space_pos)
: distance( attenuation_factor[i] * -lightPosition[i].xyz, object_space_pos.xyz );
}
// Gouraud shading mode? If so, finalize the whole color calculation here in the vertex shader,
// one per vertex, before we even break it down to pixels in the fragment shader. As opposed
// to Smooth "Phong" Shading, where we *do* wait to calculate final color until the next shader.
if( GOURAUD ) {
VERTEX_COLOR = vec4( shapeColor.xyz * ambient, shapeColor.w);
VERTEX_COLOR.xyz += phong_model_lights( N );
}
shadowPos = texUnitConverter * lightPMatrix * lightMVMatrix * vec4(object_space_pos, 1.0);
}`;
}
// ********* FRAGMENT SHADER *********
// A fragment is a pixel that's overlapped by the current triangle.
// Fragments affect the final image or get discarded due to depth.
fragment_glsl_code() {
return `
varying vec4 shadowPos;
uniform sampler2D depthColorTexture;
uniform vec3 uColor;
uniform sampler2D texture;
float decodeFloat (vec4 color) {
const vec4 bitShift = vec4(
1.0 / (256.0 * 256.0 * 256.0),
1.0 / (256.0 * 256.0),
1.0 / 256.0,
1
);
return dot(color, bitShift);
}
vec4 phong() {
vec4 color;
// Do smooth "Phong" shading unless options like "Gouraud mode" are wanted instead.
// Otherwise, we already have final colors to smear (interpolate) across vertices.
if( GOURAUD || COLOR_NORMALS ) {
color = VERTEX_COLOR;
return color;
}
// If we get this far, calculate Smooth "Phong" Shading as opposed to Gouraud Shading.
// Phong shading is not to be confused with the Phong Reflection Model.
// Sample the texture image in the correct place.
vec4 tex_color = texture2D( texture, f_tex_coord );
// Compute an initial (ambient) color:
if( USE_TEXTURE )
color = vec4( ( tex_color.xyz + shapeColor.xyz ) * ambient, shapeColor.w * tex_color.w );
else
color = vec4( shapeColor.xyz * ambient, shapeColor.w );
// Compute the final color with contributions from lights.
color.xyz += phong_model_lights( N );
return color;
}
void main(void) {
vec3 fragmentDepth = shadowPos.xyz;
float shadowAcneRemover = 0.007;
fragmentDepth.z -= shadowAcneRemover;
float texelSize = 1.0 / ${this.shadowDepthTextureSize}.0;
float amountInLight = 0.0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
float texelDepth = decodeFloat(texture2D(depthColorTexture,
fragmentDepth.xy + vec2(x, y) * texelSize));
if (fragmentDepth.z < texelDepth) {
amountInLight += 1.0;
}
}
}
amountInLight /= 9.0;
vec4 phong_color = phong();
gl_FragColor = vec4(amountInLight * phong_color.xyz, phong_color.w);
}
`;
}
update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl) {
super.update_GPU(g_state, model_transform, material, gpu=this.g_addrs, gl=this.gl)
// First, send the matrices to the GPU, additionally cache-ing some products of them we know we'll need:
this.update_matrices(g_state, model_transform, gpu, gl);
gl.uniform1f(gpu.animation_time_loc, g_state.animation_time / 1000);
if (g_state.gouraud === undefined) {
g_state.gouraud = g_state.color_normals = false;
}
// Keep the flags seen by the shader program up-to-date and make sure they are declared.
gl.uniform1i(gpu.GOURAUD_loc, g_state.gouraud);
gl.uniform1i(gpu.COLOR_NORMALS_loc, g_state.color_normals);
// Send the desired shape-wide material qualities to the graphics card, where they will
// tweak the Phong lighting formula.
gl.uniform4fv(gpu.shapeColor_loc, material.color);
gl.uniform1f( gpu.ambient_loc, material.ambient);
gl.uniform1f( gpu.diffusivity_loc, material.diffusivity);
gl.uniform1f( gpu.specularity_loc, material.specularity);
gl.uniform1f( gpu.smoothness_loc, material.smoothness);
// NOTE: To signal not to draw a texture, omit the texture parameter from Materials.
if (material.texture) {
gpu.shader_attributes["tex_coord"].enabled = true;
gl.uniform1f(gpu.USE_TEXTURE_loc, 1);
gl.bindTexture(gl.TEXTURE_2D, material.texture.id);
}
else {
gl.uniform1f(gpu.USE_TEXTURE_loc, 0);
gpu.shader_attributes["tex_coord"].enabled = false;
}
if (!g_state.lights.length)
return;
var lightPositions_flattened = [],
lightColors_flattened = [],
lightAttenuations_flattened = [];
for (var i = 0; i < 4 * g_state.lights.length; i++) {
lightPositions_flattened.push(g_state.lights[Math.floor(i / 4)].position[i % 4]);
lightColors_flattened.push(g_state.lights[Math.floor(i / 4)].color[i % 4]);
lightAttenuations_flattened[Math.floor(i / 4)] = g_state.lights[Math.floor(i / 4)].attenuation;
}
gl.uniform4fv(gpu.lightPosition_loc, lightPositions_flattened);
gl.uniform4fv(gpu.lightColor_loc, lightColors_flattened);
gl.uniform1fv(gpu.attenuation_factor_loc, lightAttenuations_flattened);
// let light_pos = g_state.lights[0].position,
// // model_pos = model_transform.times(Vec.of(0, 0, 0, 1)),
// model_pos = Vec.of(0, 0, 0),
// up_dir = light_pos.minus(model_pos).cross(model_pos);
// if (up_dir.dot(up_dir))
// gl.uniformMatrix4fv(gpu.lightMVMatrix_loc, false,
// Mat.flatten_2D_to_1D(Mat4.look_at(light_pos, model_pos, up_dir).transposed()));
}
// Helper function for sending matrices to GPU.
update_matrices(g_state, model_transform, gpu, gl) {
// (PCM will mean Projection * Camera * Model)
let [P,C,M] = [g_state.projection_transform, g_state.camera_transform, model_transform],
CM = C.times(M),
PCM = P.times(CM),
inv_CM = Mat4.inverse(CM).sub_block([0, 0], [3, 3]);
// Send the current matrices to the shader. Go ahead and pre-compute
// the products we'll need of the of the three special matrices and just
// cache and send those. They will be the same throughout this draw
// call, and thus across each instance of the vertex shader.
// Transpose them since the GPU expects matrices as column-major arrays.
gl.uniformMatrix4fv(gpu.camera_transform_loc, false, Mat.flatten_2D_to_1D(C.transposed()));
gl.uniformMatrix4fv(gpu.camera_model_transform_loc, false, Mat.flatten_2D_to_1D(CM.transposed()));
gl.uniformMatrix4fv(gpu.projection_camera_model_transform_loc, false, Mat.flatten_2D_to_1D(PCM.transposed()));
gl.uniformMatrix3fv(gpu.inverse_transpose_modelview_loc, false, Mat.flatten_2D_to_1D(inv_CM));
}
}
window.Perlin_Shader = window.classes.Perlin_Shader = class Perlin_Shader extends Camera_Shader {
material(color, properties) {
// Possible properties: ambient, diffusivity, specularity, smoothness, texture.
return new class Material {
constructor(shader, color=Color.of(0, 0, 0, 1), ambient=0, diffusivity=1, specularity=1, smoothness=40, shadows=true,
do_perlin = true, color1=Color.of(0, 0, 0, 1), scale1=0, freq1=1, color2=Color.of(0, 0, 0, 1), scale2=0,
freq2=1, scaleb=1, freq_global=1) {
// Assign defaults.
Object.assign(this, {
shader,
color,
ambient,
diffusivity,
specularity,
smoothness,
shadows,
do_perlin,
color1,
scale1,
freq1,
color2,
scale2,
freq2,
scaleb,
freq_global
});
// Optionally override defaults.
Object.assign(this, properties);
}
// Easily make temporary overridden versions of a base material, such as
// of a different color or diffusivity. Use "opacity" to override only that.
override(properties) {
const copied = new this.constructor();
Object.assign(copied, this);
Object.assign(copied, properties);
copied.color = copied.color.copy();
if (properties["opacity"] != undefined)
copied.color[3] = properties["opacity"];
return copied;
}
}
(this,color);
}
map_attribute_name_to_buffer_name(name) {
// Use a simple lookup table.
return {
object_space_pos: "positions",
normal: "normals",
tex_coord: "texture_coords"
}[name];
}
shared_glsl_code()
{
return `
precision mediump float;
// We're limited to only so many inputs in hardware. Lights are costly (lots of sub-values).
const int N_LIGHTS = 2;
uniform float ambient, diffusivity, specularity, smoothness, animation_time, attenuation_factor[N_LIGHTS];
// Flags for alternate shading methods
uniform bool GOURAUD, COLOR_NORMALS, USE_TEXTURE;
uniform vec4 lightPosition[N_LIGHTS], lightColor[N_LIGHTS], shapeColor;
// Specifier "varying" means a variable's final value will be passed from the vertex shader
// on to the next phase (fragment shader), then interpolated per-fragment, weighted by the
// pixel fragment's proximity to each of the 3 vertices (barycentric interpolation).
varying vec3 N, E;
varying vec2 f_tex_coord;
varying vec4 VERTEX_COLOR;
varying vec3 L[N_LIGHTS];
varying float dist[N_LIGHTS];
vec3 phong_model_lights( vec3 N ) {
vec3 result = vec3(0.0);
for(int i = 0; i < N_LIGHTS; i++) {
vec3 H = normalize( L[i] + E );
float attenuation_multiplier = 1.0;// / (1.0 + attenuation_factor[i] * (dist[i] * dist[i]));
float diffuse = max( dot(N, L[i]), 0.0 );
float specular = pow( max( dot(N, H), 0.0 ), smoothness );
result += attenuation_multiplier * ( shapeColor.xyz * diffusivity * diffuse + lightColor[i].xyz * specularity * specular );
}
return result;
}`;
}
vertex_glsl_code() {
return `
attribute vec3 object_space_pos, normal;
attribute vec2 tex_coord;
uniform mat4 uPMatrix;
uniform mat4 uMVMatrix;
uniform mat4 lightPMatrix;
uniform mat4 lightMVMatrix;
const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5,
0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
varying vec4 shadowPos;
uniform mat4 camera_transform, camera_model_transform, projection_camera_model_transform;
uniform mat3 inverse_transpose_modelview;
void main() {
// The vertex's final resting place (in NDCS).
gl_Position = projection_camera_model_transform * vec4(object_space_pos, 1.0);
// The final normal vector in screen space.
N = normalize( inverse_transpose_modelview * normal );
// Directly use original texture coords and interpolate between.
f_tex_coord = tex_coord;
// Bypass all lighting code if we're lighting up vertices some other way.
if( COLOR_NORMALS ) {
// In "normals" mode, rgb color = xyz quantity. Flash if it's negative.
VERTEX_COLOR = vec4( N[0] > 0.0 ? N[0] : sin( animation_time * 3.0 ) * -N[0],
N[1] > 0.0 ? N[1] : sin( animation_time * 15.0 ) * -N[1],
N[2] > 0.0 ? N[2] : sin( animation_time * 45.0 ) * -N[2] , 1.0 );
return;
}
// The rest of this shader calculates some quantities that the Fragment shader will need:
vec3 camera_space_pos = ( camera_model_transform * vec4(object_space_pos, 1.0) ).xyz;
E = normalize( -camera_space_pos );
// Light positions use homogeneous coords. Use w = 0 for a directional light source -- a vector instead of a point.
for( int i = 0; i < N_LIGHTS; i++ ) {
L[i] = normalize( ( camera_transform * lightPosition[i] ).xyz - lightPosition[i].w * camera_space_pos );
// Is it a point light source? Calculate the distance to it from the object. Otherwise use some arbitrary distance.
dist[i] = lightPosition[i].w > 0.0 ? distance((camera_transform * lightPosition[i]).xyz, camera_space_pos)
: distance( attenuation_factor[i] * -lightPosition[i].xyz, object_space_pos.xyz );
}
// Gouraud shading mode? If so, finalize the whole color calculation here in the vertex shader,
// one per vertex, before we even break it down to pixels in the fragment shader. As opposed
// to Smooth "Phong" Shading, where we *do* wait to calculate final color until the next shader.
if( GOURAUD ) {
VERTEX_COLOR = vec4( shapeColor.xyz * ambient, shapeColor.w);
VERTEX_COLOR.xyz += phong_model_lights( N );
}
shadowPos = texUnitConverter * lightPMatrix * lightMVMatrix * vec4(object_space_pos, 1.0);
}`;
}
// ********* FRAGMENT SHADER *********
// A fragment is a pixel that's overlapped by the current triangle.
// Fragments affect the final image or get discarded due to depth.
fragment_glsl_code() {
return `
varying vec4 shadowPos;
uniform sampler2D depthColorTexture;
uniform vec3 uColor;
uniform bool shadows, do_perlin;
uniform float scale1, scale2, scaleb, freq1, freq2, freq_global;
uniform vec4 color1, color2, backdrop;
uniform sampler2D texture;
float decodeFloat (vec4 color) {
const vec4 bitShift = vec4(
1.0 / (256.0 * 256.0 * 256.0),
1.0 / (256.0 * 256.0),
1.0 / 256.0,
1
);
return dot(color, bitShift);
}
vec4 phong(vec4 color) {
// Do smooth "Phong" shading unless options like "Gouraud mode" are wanted instead.
// Otherwise, we already have final colors to smear (interpolate) across vertices.
if( GOURAUD || COLOR_NORMALS ) {
color = VERTEX_COLOR;
return color;
}
// If we get this far, calculate Smooth "Phong" Shading as opposed to Gouraud Shading.
// Phong shading is not to be confused with the Phong Reflection Model.
// Sample the texture image in the correct place.
vec4 tex_color = texture2D( texture, f_tex_coord );
// Compute an initial (ambient) color:
if( USE_TEXTURE )
color = vec4( ( tex_color.xyz + color.xyz ) * ambient, tex_color.w * color.w );
else
color = vec4( color.xyz * ambient, color.w );
// Compute the final color with contributions from lights.
color.xyz += phong_model_lights( N );
return color;
}
#define NOISE_PASSES 6
float Hash(in float n)
{
return fract(sin(n)*43758.5453123);
}
float Noise(in vec2 x)
{
vec2 p = floor(x);
vec2 f = fract(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0;
float res = mix(mix( Hash(n+ 0.0), Hash(n+ 1.0),f.x),
mix( Hash(n+ 57.0), Hash(n+ 58.0),f.x),f.y);
return res;
}
void FAST32_hash_2D( vec2 gridcell, out vec4 hash_0, out vec4 hash_1 )
{
const vec2 OFFSET = vec2( 26.0, 61.0 );
const float DOMAIN = 71.0;
const vec2 SOMELARGEFLOATS = vec2( 2356.121616126, 982.126616 );
vec4 P = vec4( gridcell.xy, gridcell.xy + 1.0 );
P = P - floor(P * ( 1.0 / DOMAIN )) * DOMAIN;
P += OFFSET.xyxy;
P *= P;
P = P.xzxz * P.yyww;
hash_0 = fract( P * ( 1.0 / SOMELARGEFLOATS.x ) );
hash_1 = fract( P * ( 1.0 / SOMELARGEFLOATS.y ) );
}
vec2 Interpolation_C2( vec2 x ) { return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); }
float Perlin2D( vec2 P )
{
// establish our grid cell and unit position
vec2 Pi = floor(P);
vec4 Pf_Pfmin1 = P.xyxy - vec4( Pi, Pi + 1.0 );
// calculate the hash.
vec4 hash_x, hash_y;
FAST32_hash_2D( Pi, hash_x, hash_y );
// calculate the gradient results
vec4 grad_x = hash_x - 0.49999;
vec4 grad_y = hash_y - 0.49999;
vec4 grad_results = inversesqrt( grad_x * grad_x + grad_y * grad_y ) * ( grad_x * Pf_Pfmin1.xzxz + grad_y * Pf_Pfmin1.yyww );
// Classic Perlin Interpolation
grad_results *= 1.4128755925912787125195287;
vec2 blend = Interpolation_C2( Pf_Pfmin1.xy );
vec4 blend2 = vec4( blend, vec2( 1.0 - blend ) );
return dot( grad_results, blend2.zxzx * blend2.wwyy );
}
mat2 octave_m = mat2(1.8,1.2,-1.2,1.8);
float FractalNoise(in vec2 xy)
{
float m = 1.00;
float w = 0.6;
float f = 0.0;
float time = animation_time*1.0;
for (int i = 0; i < NOISE_PASSES; i++)
{
f += Noise(xy.xy+time*0.755) * m * 0.25;
if (i < 3)
{
f += Perlin2D(xy.yx-sin(time)*0.533) * w * 0.1;
}
else
{
// ridged turbulence at smaller scales - moves 4x faster
f += abs(Perlin2D(xy.yx-sin(time)*1.932) * w * 0.05)*1.75;
}
w *= 0.45;
m *= 0.35;
xy *= octave_m;