This repository was archived by the owner on Jan 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2126 lines (1834 loc) · 75.3 KB
/
main.js
File metadata and controls
2126 lines (1834 loc) · 75.3 KB
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
let GL = null;
const { mat4, mat3, vec2, vec3, vec4, quat } = glMatrix;
const pyramidObj = `
# Blender OBJ File: /home/william/Documents/Blender/pyramid2.obj
# www.blender.org
#StarLogoCommand ComputeNormals
mtllib pyramid2.mtl
o o_Plane_Plane_o_Plane_Plane
v -2.79999995232 -2.10000014305 -2.7999997139
v -2.80000090599 -2.10000014305 2.79999923706
v 2.79999947548 -2.09999966621 2.79999995232
v 2.7999997139 -2.09999966621 -2.80000019073
v -5.51132018245e-07 2.87229824066 -1.66892974107e-07
v -2.79467940331 -2.09685015678 2.79822540283
v 2.79467797279 -2.09684967995 2.79822611809
v -5.51339951471e-07 2.86599826813 0.00354754924774
v -2.79909920692 -2.0984005928 -2.79729771614
v -2.7991001606 -2.0984005928 2.7972972393
v -0.00180196762085 2.86909937859 -1.66938988855e-07
v -2.78854846954 -2.09322142601 -2.79618263245
v 2.78854823112 -2.09322094917 -2.79618310928
v -5.49954393136e-07 2.858741045 -0.0076345205307
v 2.7947371006 -2.09065461159 2.78421282768
v 2.79473733902 -2.09065461159 -2.7842130661
v 0.0105241537094 2.85360813141 -1.66713732597e-07
v -2.78626155853 -2.10000014305 -2.78626132011
v -2.78626251221 -2.10000014305 2.78626084328
v 2.7862610817 -2.09999966621 2.78626155853
v 2.78626132011 -2.09999966621 -2.78626179695
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 1.0 0.0
vt 0.0 0.0 0.0
vt 1.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 1.0 0.0
vt 0.0 0.0 0.0
vt 1.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 1.0 0.0
vt 1.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 1.0 1.0 0.0
vt 0.0 1.0 0.0
vt 0.0 0.0 0.0
vt 1.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 0.0 0.0
vt 0.0 1.0 0.0
vt 0.0 0.0 0.0
vt 1.0 0.0 0.0
vt 1.0 1.0 0.0
vn -0.323962181807 -0.888874053955 -0.323962181807
vn 0.323962181807 -0.888874053955 -0.323962181807
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.707106769085 0.0 -0.707106769085
vn -0.323962181807 -0.888874053955 -0.323962181807
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.323962181807 -0.888874053955 -0.323962181807
vn 0.707106769085 0.0 -0.707106769085
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.0 -0.490656763315 -0.8713529706
vn 0.323962181807 -0.888874053955 -0.323962181807
vn 0.323958963156 -0.888865232468 0.323989480734
vn 0.8713529706 -0.490656763315 0.0
vn 0.8713529706 -0.490656763315 0.0
vn 0.323958963156 -0.888865232468 0.323989480734
vn 0.707106769085 0.0 -0.707106769085
vn 0.871339857578 -0.49067991972 0.0
vn 0.8713529706 -0.490656763315 0.0
vn 0.707106769085 0.0 -0.707106769085
vn 0.323962181807 -0.888874053955 -0.323962181807
vn 0.8713529706 -0.490656763315 0.0
vn 0.871339857578 -0.49067991972 0.0
vn 0.8713529706 -0.490656763315 0.0
vn 0.8713529706 -0.490656763315 0.0
vn 0.871339857578 -0.49067991972 0.0
vn 0.323958963156 -0.888865232468 0.323989480734
vn -0.323962181807 -0.888874053955 0.323962181807
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn -0.323962181807 -0.888874053955 0.323962181807
vn 0.707106769085 0.0 -0.707106769085
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn 0.707106769085 0.0 -0.707106769085
vn 0.323958963156 -0.888865232468 0.323989480734
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn 0.0 -0.490656763315 0.8713529706
vn -0.323962181807 -0.888874053955 0.323962181807
vn -0.323962181807 -0.888874053955 -0.323962181807
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn 0.707106769085 0.0 -0.707106769085
vn -0.323962181807 -0.888874053955 0.323962181807
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn -0.323962181807 -0.888874053955 -0.323962181807
vn 0.707106769085 0.0 -0.707106769085
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn -0.8713529706 -0.490656763315 0.0
vn 0.323958963156 -0.888865232468 0.323989480734
vn 0.323962181807 -0.888874053955 -0.323962181807
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn 0.323962181807 -0.888874053955 -0.323962181807
vn -0.323962181807 -0.888874053955 -0.323962181807
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn -0.323962181807 -0.888874053955 -0.323962181807
vn -0.323962181807 -0.888874053955 0.323962181807
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn -0.323962181807 -0.888874053955 0.323962181807
vn 0.323958963156 -0.888865232468 0.323989480734
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
vn 0.0 1.0 0.0
f 3/1/1 2/2/2 6/3/3 7/4/4
f 5/5/5 3/6/6 7/7/7 8/8/8
f 2/9/9 5/10/10 8/11/11 6/12/12
f 6/13/13 7/14/14 8/15/15
f 2/16/16 1/17/17 9/18/18 10/19/19
f 1/20/20 5/21/21 11/22/22 9/23/23
f 5/24/24 2/25/25 10/26/26 11/27/27
f 9/28/28 10/29/29 11/30/30
f 1/31/31 4/32/32 13/33/33 12/34/34
f 4/35/35 5/36/36 14/37/37 13/38/38
f 5/39/39 1/40/40 12/41/41 14/42/42
f 12/43/43 14/44/44 13/45/45
f 4/46/46 3/47/47 15/48/48 16/49/49
f 5/50/50 4/51/51 16/52/52 17/53/53
f 3/54/54 5/55/55 17/56/56 15/57/57
f 15/58/58 16/59/59 17/60/60
f 1/61/61 2/62/62 19/63/63 18/64/64
f 2/65/65 3/66/66 20/67/67 19/68/68
f 3/69/69 4/70/70 21/71/71 20/72/72
f 4/73/73 1/74/74 18/75/75 21/76/76
f 19/77/77 18/78/78 21/79/79 20/80/80
`
const _OPAQUE_VS = `#version 300 es
precision highp float;
uniform mat3 normalMatrix;
uniform mat4 modelMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
in vec3 position;
in vec3 normal;
in vec3 tangent;
in vec4 colour;
in vec2 uv0;
out vec2 vUV0;
out vec4 vColour;
void main(void) {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vColour = colour;
vUV0 = uv0;
}
`;
// фрагментный шейдер для окрашивания
// Cэмплирует буфер освещения и умножает его на текстуру диффузии
// (необработанный цветовой канал 3D-объекта)
const _OPAQUE_FS = `#version 300 es
precision highp float;
uniform sampler2D diffuseTexture;
uniform sampler2D normalTexture;
uniform sampler2D gBuffer_Light;
uniform vec4 resolution;
in vec4 vColour;
in vec2 vUV0;
layout(location = 0) out vec4 out_FragColour;
void main(void) {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec4 lightSample = texture(gBuffer_Light, uv);
vec4 albedo = texture(diffuseTexture, vUV0);
out_FragColour = (albedo * vec4(lightSample.xyz, 1.0) +
lightSample.w * vec4(0.3, 0.6, 0.1, 0.0));
}
`;
const _QUAD_VS = `#version 300 es
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
in vec3 position;
in vec2 uv0;
void main(void) {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
// фрагментный шейдер для освещения
// В зависимости от типа освещения (directional/point) мы берем текстуры нормали
// и позиции и вычисляем вклад света относительно типа источника света
// ---------------------------------------------------------------------------------
// В данном шейдере используется модель шейдинга Блинна-Фонга
// https://en.wikipedia.org/wiki/Blinn%E2%80%93Phong_reflection_model
const _QUAD_FS = `#version 300 es
precision highp float;
uniform sampler2D gBuffer_Normal;
uniform sampler2D gBuffer_Position;
uniform vec3 lightColour;
#define _LIGHT_TYPE_POINT
#ifdef _LIGHT_TYPE_DIRECTIONAL
uniform vec3 lightDirection;
#endif
uniform vec3 lightPosition;
uniform vec3 lightAttenuation;
uniform vec3 cameraPosition;
uniform vec4 resolution;
out vec4 out_FragColour;
#define saturate(a) clamp(a, 0.0, 1.0)
float _SmootherStep(float x, float a, float b) {
x = x * x * x * (x * (x * 6.0 - 15.0) + 10.0);
return x * (b - a) + a;
}
vec2 _CalculatePhong(vec3 lightDirection, vec3 cameraPosition, vec3 position, vec3 normal) {
vec3 viewDirection = normalize(cameraPosition - position);
vec3 H = normalize(lightDirection.xyz + viewDirection);
float NdotH = dot(normal.xyz, H);
float specular = saturate(pow(NdotH, 32.0));
float diffuse = saturate(dot(lightDirection.xyz, normal.xyz));
return vec2(diffuse, diffuse * specular);
}
vec4 _CalculateLight_Directional(
vec3 lightDirection, vec3 lightColour, vec3 position, vec3 normal) {
vec2 lightSample = _CalculatePhong(-lightDirection, cameraPosition, position, normal);
return vec4(lightSample.x * lightColour, lightSample.y);
}
vec4 _CalculateLight_Point(
vec3 lightPosition, vec3 lightAttenuation, vec3 lightColour, vec3 position, vec3 normal) {
vec3 dirToLight = lightPosition - position;
float lightDistance = length(dirToLight);
dirToLight = normalize(dirToLight);
vec2 lightSample = _CalculatePhong(dirToLight, cameraPosition, position, normal);
float falloff = saturate((lightDistance - lightAttenuation.x) / lightAttenuation.y);
lightSample *= _SmootherStep(falloff, 1.0, 0.0);
return vec4(lightSample.x * lightColour, lightSample.y);
}
void main(void) {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec4 normal = texture(gBuffer_Normal, uv);
vec4 position = texture(gBuffer_Position, uv);
#ifdef _LIGHT_TYPE_DIRECTIONAL
vec4 lightSample = _CalculateLight_Directional(
lightDirection, lightColour, position.xyz, normal.xyz);
#elif defined(_LIGHT_TYPE_POINT)
vec4 lightSample = _CalculateLight_Point(
lightPosition, lightAttenuation, lightColour, position.xyz, normal.xyz);
#endif
out_FragColour = lightSample;
}
`;
const _QUAD_COLOUR_VS = `#version 300 es
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
in vec3 position;
in vec2 uv0;
void main(void) {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const _QUAD_COLOUR_FS = `#version 300 es
precision highp float;
uniform sampler2D gQuadTexture;
uniform vec4 resolution;
out vec4 out_FragColour;
void main(void) {
vec2 uv = gl_FragCoord.xy / resolution.xy;
out_FragColour = texture(gQuadTexture, uv);
}
`;
// Вершинный шейдер
// ---------------------------------------------------------------------------------
// Каждый раз при рендеринге фигуры вершинный шейдер запускается
// для каждой вершины фигуры. Его задача - преобразовать входную
// вершину из исходной системы координат в систему координат
// "клипового пространства", используемую WebGL, в которой каждая
// ось имеет диапазон от -1,0 до 1,0, независимо от соотношения сторон,
// фактического размера или любых других факторов.
// ---------------------------------------------------------------------------------
// Здесь вершинный шейдер выполняет необходимые преобразования положения вершины -
// для этого мы определяем матрицы модели, вида и проекции с помощью униформ.
// Затем преобразованная вершина возвращается, сохраненная в специальной переменной,
// предоставляемой GLSL - gl_Position.
const _SIMPLE_VS = `#version 300 es
precision highp float;
uniform mat3 normalMatrix;
uniform mat4 modelMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
in vec3 position;
in vec3 normal;
in vec3 tangent;
in vec2 uv0;
out vec4 vWSPosition;
out vec3 vNormal;
out vec3 vTangent;
out vec2 vUV0;
void main(void) {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vNormal = normalize(normalMatrix * normal);
vTangent = normalize(normalMatrix * tangent);
vWSPosition = modelMatrix * vec4(position, 1.0);
vUV0 = uv0;
}
`;
// Фрагментный шейдер
// ---------------------------------------------------------------------------------
// Фрагментный шейдер вызывается один раз для каждого пикселя каждой рисуемой фигуры
// после того, как вершины фигуры были обработаны вершинным шейдером. Его задача -
// определить цвет этого пикселя, выясняя, какой тексель (то есть пиксель из текстуры формы)
// применить к пикселю, получая цвет этого текселя, а затем применяя соответствующее
// освещение к цвету. Затем цвет возвращается на слой WebGL, дополнительно сохраняясь
// в специальной переменной gl_FragColor. Затем этот цвет отображается на экране
// в правильном положении для соответствующего пикселя фигуры.
const _SIMPLE_FS = `#version 300 es
precision highp float;
uniform sampler2D normalTexture;
in vec4 vWSPosition;
in vec3 vNormal;
in vec3 vTangent;
in vec2 vUV0;
layout(location = 0) out vec4 out_Normals;
layout(location = 1) out vec4 out_Position;
void main(void) {
vec3 bitangent = normalize(cross(vTangent, vNormal));
mat3 tbn = mat3(vTangent, bitangent, vNormal);
vec3 normalSample = normalize(texture(normalTexture, vUV0).xyz * 2.0 - 1.0);
vec3 vsNormal = normalize(tbn * normalSample);
out_Normals = vec4(vsNormal, 1.0);
out_Position = vWSPosition;
}
`;
function* triangulate(elements) {
if (elements.length <= 3) {
yield elements;
}
else if (elements.length === 4) {
yield [elements[0], elements[1], elements[2]];
yield [elements[2], elements[3], elements[0]];
}
else {
for (let i = 1; i < elements.length - 1; i++) {
yield [elements[0], elements[i], elements[i + 1]];
}
}
}
class Shader {
constructor(vsrc, fsrc, defines) {
defines = defines || [];
this._Init(vsrc, fsrc, defines);
}
// инициализация вершинного и фрагментного шейдеров
_Init(vsrc, fsrc, defines) {
this._defines = defines;
vsrc = this._ModifySourceWithDefines(vsrc, defines);
fsrc = this._ModifySourceWithDefines(fsrc, defines);
this._vsSource = vsrc;
this._fsSource = fsrc;
this._vsProgram = this._Load(GL.VERTEX_SHADER, vsrc);
this._fsProgram = this._Load(GL.FRAGMENT_SHADER, fsrc);
this._shader = GL.createProgram();
GL.attachShader(this._shader, this._vsProgram);
GL.attachShader(this._shader, this._fsProgram);
GL.linkProgram(this._shader);
if (!GL.getProgramParameter(this._shader, GL.LINK_STATUS)) {
return null;
}
// атрибуты - получаемые значения
this.attribs = {
positions: GL.getAttribLocation(this._shader, 'position'),
normals: GL.getAttribLocation(this._shader, 'normal'),
tangents: GL.getAttribLocation(this._shader, 'tangent'),
uvs: GL.getAttribLocation(this._shader, 'uv0'),
colours: GL.getAttribLocation(this._shader, 'colour'),
};
// униформы - параметры, активно используемые в представлениях шейдеров с GLSL
this.uniforms = {
projectionMatrix: {
type: 'mat4',
location: GL.getUniformLocation(this._shader, 'projectionMatrix')
},
modelViewMatrix: {
type: 'mat4',
location: GL.getUniformLocation(this._shader, 'modelViewMatrix'),
},
modelMatrix: {
type: 'mat4',
location: GL.getUniformLocation(this._shader, 'modelMatrix'),
},
normalMatrix: {
type: 'mat3',
location: GL.getUniformLocation(this._shader, 'normalMatrix'),
},
resolution: {
type: 'vec4',
location: GL.getUniformLocation(this._shader, 'resolution'),
},
lightColour: {
type: 'vec3',
location: GL.getUniformLocation(this._shader, 'lightColour'),
},
lightDirection: {
type: 'vec3',
location: GL.getUniformLocation(this._shader, 'lightDirection'),
},
lightPosition: {
type: 'vec3',
location: GL.getUniformLocation(this._shader, 'lightPosition'),
},
lightAttenuation: {
type: 'vec3',
location: GL.getUniformLocation(this._shader, 'lightAttenuation'),
},
cameraPosition: {
type: 'vec3',
location: GL.getUniformLocation(this._shader, 'cameraPosition'),
},
diffuseTexture: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'diffuseTexture'),
},
normalTexture: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'normalTexture'),
},
gBuffer_Light: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'gBuffer_Light'),
},
gBuffer_Colour: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'gBuffer_Colour'),
},
gBuffer_Normal: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'gBuffer_Normal'),
},
gBuffer_Position: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'gBuffer_Position'),
},
gQuadTexture: {
type: 'texture',
location: GL.getUniformLocation(this._shader, 'gQuadTexture'),
}
};
}
// загрузка шейдера
_Load(type, source) {
const shader = GL.createShader(type);
GL.shaderSource(shader, source);
GL.compileShader(shader);
// если ошибка - не подгружаем
if (!GL.getShaderParameter(shader, GL.COMPILE_STATUS)) {
console.log(GL.getShaderInfoLog(shader));
console.log(source);
GL.deleteShader(shader);
return null;
}
return shader;
}
_ModifySourceWithDefines(src, defines) {
const lines = src.split('\n');
const defineStrings = defines.map(d => '#define ' + d);
lines.splice(3, 0, defineStrings);
return lines.join('\n');
}
// связывание используемого шейдера
Bind() {
GL.useProgram(this._shader);
}
}
class ShaderInstance {
constructor(shader) {
this._shaderData = shader;
this._uniforms = {};
// копируем все значения униформ из шейдера; оставляем пустым поле "значения", мы будем выставлять его позже
for (let k in shader.uniforms) {
this._uniforms[k] = {
location: shader.uniforms[k].location,
type: shader.uniforms[k].type,
value: null
};
}
this._attribs = { ...shader.attribs };
}
SetMat4(name, m) {
this._uniforms[name].value = m;
}
SetMat3(name, m) {
this._uniforms[name].value = m;
}
SetVec4(name, v) {
this._uniforms[name].value = v;
}
SetVec3(name, v) {
this._uniforms[name].value = v;
}
SetTexture(name, t) {
this._uniforms[name].value = t;
}
// в связывании проходимся по каждой униформе и выставляем им значения
Bind(constants) {
this._shaderData.Bind();
let textureIndex = 0;
for (let k in this._uniforms) {
const v = this._uniforms[k];
let value = constants[k];
if (v.value) {
value = v.value;
}
if (value && v.location) {
const t = v.type;
if (t == 'mat4') {
GL.uniformMatrix4fv(v.location, false, value);
} else if (t == 'mat3') {
GL.uniformMatrix3fv(v.location, false, value);
} else if (t == 'vec4') {
GL.uniform4fv(v.location, value);
} else if (t == 'vec3') {
GL.uniform3fv(v.location, value);
}
// состояние индекса нужно отслеживать мануально
else if (t == 'texture') {
value.Bind(textureIndex);
GL.uniform1i(v.location, textureIndex);
textureIndex++;
}
}
}
}
}
class Texture {
constructor() { }
Load(src) {
this._name = src;
this._Load(src);
return this;
}
_Load(src) {
// сначала инициализируем текстуру как простой синий пиксель, пока не загрузилась основная текстура из сорца
this._texture = GL.createTexture();
GL.bindTexture(GL.TEXTURE_2D, this._texture);
GL.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA,
1, 1, 0, GL.RGBA, GL.UNSIGNED_BYTE,
new Uint8Array([0, 0, 255, 255]));
// задаем сорц нашей картинке (текстуре); после того, как она загрузится, осуществляем MIP маппинг (для LOD)
const img = new Image();
img.src = src;
img.onload = () => {
GL.bindTexture(GL.TEXTURE_2D, this._texture);
GL.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, img);
GL.generateMipmap(GL.TEXTURE_2D);
GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_LINEAR);
GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.LINEAR);
GL.bindTexture(GL.TEXTURE_2D, null);
};
}
// применить текстуру
Bind(index) {
if (!this._texture) {
return;
}
GL.activeTexture(GL.TEXTURE0 + index);
GL.bindTexture(GL.TEXTURE_2D, this._texture);
}
// убрать текстуру
Unbind() {
GL.bindTexture(GL.TEXTURE_2D, null);
}
}
class Mesh {
// в конструкторе происходит вызов абстрактного метода OnInit
// этот метод варьируется в зависимости от меша, который мы хотим вывести в мир (кубик/шар и т.д.)
constructor(objectData, options) {
this._buffers = {};
this._OnInit(objectData, options);
}
// запись данных в буфер по названию буфера
_BufferData(info, name) {
if (name == 'index') {
info.buffer = GL.createBuffer();
GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, info.buffer);
GL.bufferData(GL.ELEMENT_ARRAY_BUFFER, new Uint16Array(info.data), GL.STATIC_DRAW);
} else {
info.buffer = GL.createBuffer();
GL.bindBuffer(GL.ARRAY_BUFFER, info.buffer);
GL.bufferData(GL.ARRAY_BUFFER, new Float32Array(info.data), GL.STATIC_DRAW);
}
this._buffers[name] = info;
}
// связывание
Bind(shader) {
for (let k in this._buffers) {
if (shader._attribs[k] == -1) {
continue;
}
const b = this._buffers[k];
if (k == 'index') {
GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, b.buffer);
} else {
GL.bindBuffer(GL.ARRAY_BUFFER, b.buffer);
GL.vertexAttribPointer(shader._attribs[k], b.size, GL.FLOAT, false, 0, 0);
GL.enableVertexAttribArray(shader._attribs[k]);
}
}
}
// выводим меш в мир
Draw() {
const vertexCount = this._buffers.index.data.length;
GL.drawElements(GL.TRIANGLES, vertexCount, GL.UNSIGNED_SHORT, 0);
}
}
// конкретный инстанс объекта (когда хотим создать кучу мешей со своими свойствами)
class MeshInstance {
constructor(mesh, shaders, shaderParams) {
this._mesh = mesh;
this._shaders = shaders; // нужен свой инстанс шейдеров (для униформ GLSL)
shaderParams = shaderParams || {};
for (let sk in shaders) {
const s = shaders[sk];
for (let k in shaderParams) {
s.SetTexture(k, shaderParams[k]);
}
}
this._position = vec3.create();
this._scale = vec3.fromValues(1, 1, 1);
this._rotation = quat.create();
}
SetPosition(x, y, z) {
vec3.set(this._position, x, y, z);
}
RotateX(rad) {
quat.rotateX(this._rotation, this._rotation, rad);
}
RotateY(rad) {
quat.rotateY(this._rotation, this._rotation, rad);
}
Scale(x, y, z) {
vec3.set(this._scale, x, y, z);
}
// связывание всех параметров и матриц с WebGL для отображения
Bind(constants, pass) {
const modelMatrix = mat4.create();
mat4.fromRotationTranslationScale(
modelMatrix, this._rotation, this._position, this._scale);
const viewMatrix = constants['viewMatrix'];
const modelViewMatrix = mat4.create();
mat4.multiply(modelViewMatrix, viewMatrix, modelMatrix);
const normalMatrix = mat3.create();
mat3.fromMat4(normalMatrix, modelMatrix);
mat3.invert(normalMatrix, normalMatrix);
mat3.transpose(normalMatrix, normalMatrix);
const s = this._shaders[pass];
s.SetMat4('modelViewMatrix', modelViewMatrix);
s.SetMat4('modelMatrix', modelMatrix);
s.SetMat3('normalMatrix', normalMatrix);
s.Bind(constants);
this._mesh.Bind(s);
}
Draw() {
this._mesh.Draw();
}
}
// собственно кубик
class Cube extends Mesh {
constructor(objectData, options) {
super(objectData, options);
}
_OnInit(objectData, options) {
const positions = [
// передняя сторона
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// задняя сторона
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// верхняя сторона
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// нижняя сторона
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// правая сторона
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// левая сторона
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
];
// координаты на текстуре ("UV mapping")
const uvs = [
// передняя сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// задняя сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// верхняя сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// нижняя сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// правая сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// левая сторона
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
];
// нормали
const normals = [
// передняя сторона
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
// задняя сторона
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
// верхняя сторона
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
// нижняя сторона
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
// правая сторона
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
// левая сторона
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
];
// тангенсы
const tangents = [
// передняя сторона
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
// задняя сторона
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
// верхняя сторона
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
// нижняя сторона
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
// правая сторона
0.0, 1.0, 0.0,