-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebgl.js
1494 lines (1295 loc) · 54.6 KB
/
webgl.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
var VSHADER_SOURCE = `
attribute vec4 a_Position;
attribute vec4 a_Normal;
attribute vec2 a_TexCoord;
uniform mat4 u_MvpMatrix;
uniform mat4 u_modelMatrix;
uniform mat4 u_normalMatrix;
uniform mat4 u_MvpMatrixOfLight;
varying vec3 v_Normal;
varying vec3 v_PositionInWorld;
varying vec2 v_TexCoord;
uniform mat4 u_ProjMatrixFromLight;
varying vec4 v_PositionFromLight;
void main(){
gl_Position = u_MvpMatrix * a_Position;
v_PositionInWorld = (u_modelMatrix * a_Position).xyz;
v_Normal = normalize(vec3(u_normalMatrix * a_Normal));
v_PositionFromLight = u_MvpMatrixOfLight * a_Position; //for shadow
v_TexCoord = a_TexCoord;
}
`;
var FSHADER_SOURCE = `
precision mediump float;
uniform vec3 u_LightPosition;
uniform vec3 u_ViewPosition;
uniform float u_Ka;
uniform float u_Kd;
uniform float u_Ks;
uniform float u_Alpha;
uniform float u_shininess;
uniform sampler2D u_Sampler;
uniform vec3 u_Color;
uniform sampler2D u_ShadowMap;
varying vec3 v_Normal;
varying vec3 v_PositionInWorld;
varying vec2 v_TexCoord;
varying vec4 v_PositionFromLight;
const float deMachThreshold = 0.005; //0.001 if having high precision depth
// varying vec2 v_texcoord;
uniform sampler2D u_texture;
float unpackFloatFromVec4i(const vec4 value) {
const vec4 bitSh = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);
return(dot(value, bitSh));
}
void main(){
vec3 texColor = texture2D( u_Sampler, v_TexCoord ).rgb;
vec3 ambientLightColor = texColor;
vec3 diffuseLightColor = texColor;
vec3 specularLightColor = vec3(1.0, 1.0, 1.0);
vec3 ambient = ambientLightColor * u_Ka;
vec3 normal = normalize(v_Normal);
vec3 lightDirection = normalize(u_LightPosition - v_PositionInWorld);
float nDotL = max(dot(lightDirection, normal), 0.0);
vec3 diffuse = diffuseLightColor * u_Kd * nDotL;
vec3 specular = vec3(0.0, 0.0, 0.0);
if(nDotL > 0.0) {
vec3 R = reflect(-lightDirection, normal);
// V: the vector, point to viewer
vec3 V = normalize(u_ViewPosition - v_PositionInWorld);
float specAngle = clamp(dot(R, V), 0.0, 1.0);
specular = u_Ks * pow(specAngle, u_shininess) * specularLightColor;
}
//***** shadow
vec3 shadowCoord = (v_PositionFromLight.xyz/v_PositionFromLight.w)/2.0 + 0.5;
vec4 rgbaDepth = texture2D(u_ShadowMap, shadowCoord.xy);
/////////******** LOW precision depth implementation ********///////////
// float depth = rgbaDepth.r;
float depth = unpackFloatFromVec4i(rgbaDepth);
float visibility = (shadowCoord.z > depth + deMachThreshold) ? 0.3 : 1.0;
// gl_FragColor = texture2D(u_texture, v_TexCoord);
gl_FragColor = vec4( (ambient + diffuse + specular)*visibility, 1.0);
}
`;
var VSHADER_SHADOW_SOURCE = `
attribute vec4 a_Position;
uniform mat4 u_MvpMatrix;
void main(){
gl_Position = u_MvpMatrix * a_Position;
}
`;
var FSHADER_SHADOW_SOURCE = `
precision mediump float;
vec4 packFloatToVec4i(const float value) {
const vec4 bitSh = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);
const vec4 bitMsk = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);
vec4 res = fract(value * bitSh);
res -= res.xxyz * bitMsk;
return res;
}
void main(){
/////////** LOW precision depth implementation **/////
// gl_FragColor = vec4(gl_FragCoord.z,0.0,0.0, 1.0);
gl_FragColor = packFloatToVec4i(gl_FragCoord.z);
}
`;
var VSHADER_SOURCE_ENVCUBE = `
attribute vec4 a_Position;
varying vec4 v_Position;
void main() {
v_Position = a_Position;
gl_Position = a_Position;
}
`;
var FSHADER_SOURCE_ENVCUBE = `
precision mediump float;
uniform samplerCube u_envCubeMap;
uniform mat4 u_viewDirectionProjectionInverse;
varying vec4 v_Position;
void main() {
vec4 t = u_viewDirectionProjectionInverse * v_Position;
gl_FragColor = textureCube(u_envCubeMap, normalize(t.xyz / t.w));
}
`;
var VSHADER_SOURCE_TEXTURE_ON_CUBE = `
attribute vec4 a_Position;
attribute vec4 a_Normal;
uniform mat4 u_MvpMatrix;
uniform mat4 u_modelMatrix;
uniform mat4 u_normalMatrix;
varying vec4 v_TexCoord;
varying vec3 v_Normal;
varying vec3 v_PositionInWorld;
void main() {
gl_Position = u_MvpMatrix * a_Position;
v_TexCoord = a_Position;
v_PositionInWorld = (u_modelMatrix * a_Position).xyz;
v_Normal = normalize(vec3(u_normalMatrix * a_Normal));
}
`;
var FSHADER_SOURCE_TEXTURE_ON_CUBE = `
precision mediump float;
varying vec4 v_TexCoord;
uniform vec3 u_ViewPosition;
uniform vec3 u_Color;
uniform samplerCube u_envCubeMap;
varying vec3 v_Normal;
varying vec3 v_PositionInWorld;
void main() {
vec3 V = normalize(u_ViewPosition - v_PositionInWorld);
vec3 normal = normalize(v_Normal);
vec3 R = reflect(-V, normal);
gl_FragColor = vec4(0.78 * textureCube(u_envCubeMap, R).rgb + 0.3 * u_Color, 1.0);
}
`;
function compileShader(gl, vShaderText, fShaderText) {
//////Build vertex and fragment shader objects
var vertexShader = gl.createShader(gl.VERTEX_SHADER)
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
//The way to set up shader text source
gl.shaderSource(vertexShader, vShaderText)
gl.shaderSource(fragmentShader, fShaderText)
//compile vertex shader
gl.compileShader(vertexShader)
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
console.log('vertex shader ereror');
var message = gl.getShaderInfoLog(vertexShader);
console.log(message);//print shader compiling error message
}
//compile fragment shader
gl.compileShader(fragmentShader)
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
console.log('fragment shader ereror');
var message = gl.getShaderInfoLog(fragmentShader);
console.log(message);//print shader compiling error message
}
/////link shader to program (by a self-define function)
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
//if not success, log the program info, and delete it.
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
alert(gl.getProgramInfoLog(program) + "");
gl.deleteProgram(program);
}
return program;
}
var texture = {};
var cameraX = 0, cameraY = 15, cameraZ = 7;
cameraY = 20
var TcX = 0, TcY = 15, TcZ = 7;
var firstPersonView = true;
var cameraX2 = 0, cameraY2 = 0, cameraZ2 = 0;
var cameraDirX = 0, cameraDirY = 0, cameraDirZ = -1;
var imgNames = [];
var objCompImgIndex = [];
var gameover = false;
var camX = 0, camY = 0, camZ = 0;
var lightX = 0, lightY = 10, lightZ = 3;
var angleX = 0, angleY = 0;
var gl;
var fbo;
var quadObj;
var cubeObj = [];
var bushObj;
var rockObj;
var sphereObj;
//var offScreenWidth=2048,offScreenHeight=2048;
var offScreenWidth = 256, offScreenHeight = 256; //for cubemap render
var cubeMapTex;
var textures = {};
var texCount = 0;
var numTextures = 1;
var mvpMatrix;
var modelMatrix;
var normalMatrix;
var rotateMatrix;
var objScale = 0.3;
var mouseLastX, mouseLastY;
var playerObj = [];
var mouseDragging = false;
var angle = 0;
var radius = 5; // 光源繞圈的半徑
var lX, lZ;
var centerX = 0; // 繞圈的中心位置 X
var centerY = 0; // 繞圈的中心位置 Y
var speed = 0.01; // 光源轉動的速度
var fbo;
async function parseModel(file) {
try {
let response = await fetch(file);
let text = await response.text();
let obj = parseOBJ(text);
let O = [];
for (let i = 0; i < obj.geometries.length; i++) {
let o = initVertexBufferForLaterUse(gl,
obj.geometries[i].data.position,
obj.geometries[i].data.normal,
obj.geometries[i].data.texcoord);
O.push(o);
}
return O;
} catch (error) {
console.error('Error loading model:', error);
return null;
}
}
function onloadTexture(tex, file) {
var img = new Image();
img.onload = function () { initTexture(gl, img, tex); };
img.src = file;
}
function mouseDown(ev) {
var x = ev.clientX;
var y = ev.clientY;
var rect = ev.target.getBoundingClientRect();
if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
mouseLastX = x;
mouseLastY = y;
mouseDragging = true;
}
}
function initFrameBuffer(gl) {
//create and set up a texture object as the color buffer
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, offScreenWidth, offScreenHeight,
0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
//create and setup a render buffer as the depth buffer
var depthBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
offScreenWidth, offScreenHeight);
//create and setup framebuffer: linke the color and depth buffer to it
var frameBuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D, texture, 0);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
gl.RENDERBUFFER, depthBuffer);
frameBuffer.texture = texture;
return frameBuffer;
}
function initProgram(program) {
program.a_Position = gl.getAttribLocation(program, 'a_Position');
program.a_Normal = gl.getAttribLocation(program, 'a_Normal');
program.u_MvpMatrix = gl.getUniformLocation(program, 'u_MvpMatrix');
program.u_modelMatrix = gl.getUniformLocation(program, 'u_modelMatrix');
program.u_normalMatrix = gl.getUniformLocation(program, 'u_normalMatrix');
program.u_LightPosition = gl.getUniformLocation(program, 'u_LightPosition');
program.u_ViewPosition = gl.getUniformLocation(program, 'u_ViewPosition');
program.u_MvpMatrixOfLight = gl.getUniformLocation(program, 'u_MvpMatrixOfLight');
program.a_TexCoord = gl.getAttribLocation(program, 'a_TexCoord');
program.u_Ka = gl.getUniformLocation(program, 'u_Ka');
program.u_Kd = gl.getUniformLocation(program, 'u_Kd');
program.u_Ks = gl.getUniformLocation(program, 'u_Ks');
program.u_shininess = gl.getUniformLocation(program, 'u_shininess');
program.u_ShadowMap = gl.getUniformLocation(program, "u_ShadowMap");
program.u_Color = gl.getUniformLocation(program, 'u_Color');
program.u_Alpha = gl.getUniformLocation(program, 'u_Alpha');
program.u_Sampler = gl.getUniformLocation(program, "u_Sampler")
}
async function main() {
canvas = document.getElementById('webgl');
gl = canvas.getContext('webgl2');
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
program = compileShader(gl, VSHADER_SOURCE, FSHADER_SOURCE);
initProgram(program);
//setup shaders and prepare shader variables
shadowProgram = compileShader(gl, VSHADER_SHADOW_SOURCE, FSHADER_SHADOW_SOURCE);
shadowProgram.a_Position = gl.getAttribLocation(shadowProgram, 'a_Position');
shadowProgram.u_MvpMatrix = gl.getUniformLocation(shadowProgram, 'u_MvpMatrix');
programEnvCube = compileShader(gl, VSHADER_SOURCE_ENVCUBE, FSHADER_SOURCE_ENVCUBE);
programEnvCube.a_Position = gl.getAttribLocation(programEnvCube, 'a_Position');
programEnvCube.u_envCubeMap = gl.getUniformLocation(programEnvCube, 'u_envCubeMap');
programEnvCube.u_viewDirectionProjectionInverse =
gl.getUniformLocation(programEnvCube, 'u_viewDirectionProjectionInverse');
programTextureOnCube = compileShader(gl, VSHADER_SOURCE_TEXTURE_ON_CUBE, FSHADER_SOURCE_TEXTURE_ON_CUBE);
programTextureOnCube.a_Position = gl.getAttribLocation(programTextureOnCube, 'a_Position');
programTextureOnCube.a_Normal = gl.getAttribLocation(programTextureOnCube, 'a_Normal');
programTextureOnCube.u_MvpMatrix = gl.getUniformLocation(programTextureOnCube, 'u_MvpMatrix');
programTextureOnCube.u_modelMatrix = gl.getUniformLocation(programTextureOnCube, 'u_modelMatrix');
programTextureOnCube.u_normalMatrix = gl.getUniformLocation(programTextureOnCube, 'u_normalMatrix');
programTextureOnCube.u_ViewPosition = gl.getUniformLocation(programTextureOnCube, 'u_ViewPosition');
programTextureOnCube.u_envCubeMap = gl.getUniformLocation(programTextureOnCube, 'u_envCubeMap');
programTextureOnCube.u_Color = gl.getUniformLocation(programTextureOnCube, 'u_Color');
var quad = new Float32Array(
[
-1, -1, 1,
1, -1, 1,
-1, 1, 1,
-1, 1, 1,
1, -1, 1,
1, 1, 1
]); //just a quad
//load model;
quadObj = initVertexBufferForLaterUse(gl, quad);
// cubeMapTex = initCubeTexture("pos-x.jpg", "neg-x.jpg", "pos-y.jpg", "neg-y.jpg",
// "pos-z.jpg", "neg-z.jpg", 512, 512)
cubeMapTex = initCubeTexture("px.png", "nx.png", "py.png", "ny.png",
"pz.png", "nz.png", 256, 256);
// 調用parseModel函數來載入cube.obj
cubeObj = await parseModel('object/cube.obj');
//console.log(cubeObj);
bushObj = await parseModel('object/bushes/01/bush_01.obj');
rockObj = await parseModel('object/rocks/01/rock_01.obj');
sphereObj = await parseModel('object/sphere.obj');
enemyObj = await parseModel('object/Creeper.obj');
onloadTexture("enemy", "texture/creeper.png");
onloadTexture("brick", "texture/brick.jpg")
onloadTexture("stone", "texture/stone_wall.png")
onloadTexture("bush", "object/bushes/01/diffuse.png");
onloadTexture("rock", "object/rocks/01/diffuse.png");
fboShadow = initFrameBuffer(gl);
fbo = initFrameBufferForCubemapRendering(gl);
response = await fetch('object/sonic-the-hedgehog.mtl');
const mtlText = await response.text();
//console.log('mtlText'+mtlText)
mtl = parseMTL(mtlText);
imgNames = addTexturesToImgNames(mtl);
numTextures = imgNames.length
response = await fetch('object/sonic.obj');
text = await response.text();
var obj = parseOBJ(text);
objCompImgIndex = parsetexture(text, mtl);
for (let i = 0; i < obj.geometries.length; i++) {
let o = initVertexBufferForLaterUse(gl,
obj.geometries[i].data.position,
obj.geometries[i].data.normal,
obj.geometries[i].data.texcoord);
playerObj.push(o);
}
for (let i = 0; i < imgNames.length; i++) {
let image = new Image();
image.onload = function () { initTexture(gl, image, imgNames[i]); };
image.src = imgNames[i];
}
console.log(objCompImgIndex)
initGame();
gl.useProgram(program);
// putModel('location', objname);
// onloadTexture('tex', 'location')
//fboShadow = initFrameBuffer(gl);
//fbo = initFrameBuffer(gl);
//console.log("done")
//x,z,y
mvpMatrix = new Matrix4();
modelMatrix = new Matrix4();
normalMatrix = new Matrix4();
rotateMatrix = new Matrix4();
draw();//draw it once before mouse move
canvas.onmousedown = function (ev) { mouseDown(ev) };
canvas.onmousemove = function (ev) { mouseMove(ev) };
canvas.onmouseup = function (ev) { mouseUp(ev) };
//canvas.onwheel = function (ev) { scroll(ev) };
var menu = document.getElementById("menu");
document.addEventListener('keydown', function (event) {
// let rotateMatrix = new Matrix4();
// rotateMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
// rotateMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
// var viewDir = new Vector3([cameraDirX, cameraDirY, cameraDirZ]);
// var newViewDir = rotateMatrix.multiplyVector3(viewDir);
switch (event.key) {
case 'w':
case 'W':
move(1, 0);
player.direction = 1;
break;
case 's':
case 'S':
move(-1, 0);
player.direction = 3;
break;
case 'a':
case 'A':
move(0, -1);
player.direction = 4;
break;
case 'd':
case 'D':
move(0, 1);
player.direction = 2;
break;
case 'f':
case 'F':
firstPersonView = !firstPersonView;
if (firstPersonView) {
switchToFirstPersonView();
} else {
switchToOldCameraView();
}
break;
}
draw(); // Redraw the scene with the new camera position
//implment keydown event here
// let rotateMatrix = new Matrix4();
// rotateMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
// rotateMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
// var viewDir= new Vector3([cameraDirX, cameraDirY, cameraDirZ]);
// var newViewDir = rotateMatrix.multiplyVector3(viewDir);
// if(ev.key == 'w'){
// cameraX += (newViewDir.elements[0] * 0.1);
// cameraY += (newViewDir.elements[1] * 0.1);
// cameraZ += (newViewDir.elements[2] * 0.1);
// }
// else if(ev.key == 's'){
// cameraX -= (newViewDir.elements[0] * 0.1);
// cameraY -= (newViewDir.elements[1] * 0.1);
// cameraZ -= (newViewDir.elements[2] * 0.1);
// }
// draw();
});
var tick = function () {
angle += speed;
lX = centerX + radius * Math.cos(angle);
lZ = centerY + radius * Math.sin(angle);
draw();
requestAnimationFrame(tick);
}
tick();
}
function initTexture(gl, img, texKey) {
var tex = gl.createTexture();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
gl.bindTexture(gl.TEXTURE_2D, tex);
// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
textures[texKey] = tex;
texCount++;
//if (texCount == numTextures) draw();
}
function switchToFirstPersonView() {
// 設置第一人稱視角的相機位置和方向
let eyeX = player.location.x;
let eyeY = player.location.y;
let eyeZ = player.location.z + 1; // 視角稍微高於 Sonic 的位置
let centerX = eyeX + Math.cos(player.direction);
let centerY = eyeY + Math.sin(player.direction);
let centerZ = eyeZ;
Tcx = cameraX;
Tcy = cameraY;
Tcz = cameraZ;
cameraX = eyeX;
cameraY = eyeY;
cameraZ = eyeZ;
viewMatrix.setLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, 0, 0, 1);
}
function switchToOldCameraView() {
// 恢復舊的相機位置
cameraX = TcX;
cameraY = TcY;
cameraZ = TcZ;
viewMatrix.setLookAt(TcX, TcY, TcZ, player.location.x, player.location.y, player.location.z, 0, 0, 1);
}
function addTexturesToImgNames(mtl) {
let imgNames = []; // Initialize an array to store the texture file names
// Loop through each key in the mtl dictionary
for (const materialName in mtl) {
if (mtl.hasOwnProperty(materialName) && mtl[materialName].map_Kd) {
// Check if the material exists and has a map_Kd property
imgNames.push(mtl[materialName].map_Kd); // Add the map_Kd to the imgNames array
}
}
return imgNames; // Return the array containing all the map_Kd values
}
function draw_rock_off(objComponents, mx, my, mz, tex, vpMatrix) {
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate(mx * 0.605, my * 1.15, mz * 0.625);
modelMatrix.scale(0.005, 0.005, 0.005);
//modelMatrix.scale(0.01, 0.01, 0.01);
// modelMatrix.translate(0.0, 0.0, -1.0);
// modelMatrix.scale(1.0, 0.5, 2.0);
//mvp: projection * view * model matrix
mvpMatrix.set(vpMatrix);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.useProgram(program);
// gl.depthMask(false);
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.2);
gl.uniform1f(program.u_Kd, 0.7);
gl.uniform1f(program.u_Ks, 1.0);
gl.uniform1f(program.u_shininess, 15.0);
// gl.uniform1i(program.u_ShadowMap, 0);
gl.uniform1i(program.u_Sampler, 0);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
// gl.uniformMatrix4fv(program.u_MvpMatrixOfLight, false, mvpFromLight.elements);
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textures[tex]);
// gl.activeTexture(gl.TEXTURE0);
// gl.bindTexture(gl.TEXTURE_2D, fboShadow.texture);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
// gl.depthMask(true);
}
function draw_rock(objComponents, mx, my, mz, tex, cameraX, cameraY, cameraZ, mvpFromLight) {
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate(mx * 0.605, my * 1.15, mz * 0.625);
modelMatrix.scale(0.005, 0.005, 0.005);
//modelMatrix.scale(0.01, 0.01, 0.01);
// modelMatrix.translate(0.0, 0.0, -1.0);
// modelMatrix.scale(1.0, 0.5, 2.0);
//mvp: projection * view * model matrix
mvpMatrix.setPerspective(30, 1, 1, 100);
mvpMatrix.lookAt(cameraX, cameraY, cameraZ, 0, 0, 0, 0, 1, 0);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.useProgram(program);
// gl.depthMask(false);
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.2);
gl.uniform1f(program.u_Kd, 0.7);
gl.uniform1f(program.u_Ks, 1.0);
gl.uniform1f(program.u_shininess, 15.0);
gl.uniform1i(program.u_ShadowMap, 0);
gl.uniform1i(program.u_Sampler, 1);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
gl.uniformMatrix4fv(program.u_MvpMatrixOfLight, false, mvpFromLight.elements);
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textures[tex]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fboShadow.texture);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
// gl.depthMask(true);
}
function draw_Cube_offShadow(objComponents, mx, my, mz) {
//model Matrix (part of the mvp matrix)
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.scale(objScale, objScale, objScale);
modelMatrix.translate(mx * 2, my * 2, mz * 2);
var mvpFromLight = new Matrix4();
mvpFromLight.setPerspective(60, offScreenWidth / offScreenHeight, 1, 200);
mvpFromLight.lookAt(lightX, lightY, lightZ, 0, 0, -1 + 0.05, 0, 1, 0);
mvpFromLight.multiply(modelMatrix);
gl.uniformMatrix4fv(shadowProgram.u_MvpMatrix, false, mvpFromLight.elements);
//normal matrix
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, shadowProgram.a_Position, objComponents[i].vertexBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
return mvpFromLight;
}
function draw_player_offShadow(objComponents, mx, my, mz) {
//model Matrix (part of the mvp matrix)
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate((mx - 0.5) * 0.605, my * 0.6 - 0.9, (mz - 0.5) * 0.605);
modelMatrix.scale(0.05, 0.05, 0.05);
var mvpFromLight = new Matrix4();
mvpFromLight.setPerspective(60, offScreenWidth / offScreenHeight, 1, 200);
mvpFromLight.lookAt(lightX, lightY, lightZ, 0, 0, -1 + 0.05, 0, 1, 0);
mvpFromLight.multiply(modelMatrix);
gl.uniformMatrix4fv(shadowProgram.u_MvpMatrix, false, mvpFromLight.elements);
//normal matrix
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, shadowProgram.a_Position, objComponents[i].vertexBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
return mvpFromLight;
}
function draw_rock_offShadow(objComponents, mx, my, mz) {
//model Matrix (part of the mvp matrix)
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate(mx * 0.605, my * 1.15, mz * 0.625);
modelMatrix.scale(0.005, 0.005, 0.005);
var mvpFromLight = new Matrix4();
mvpFromLight.setPerspective(60, offScreenWidth / offScreenHeight, 1, 200);
mvpFromLight.lookAt(lightX, lightY, lightZ, 0, 0, -1 + 0.05, 0, 1, 0);
mvpFromLight.multiply(modelMatrix);
gl.uniformMatrix4fv(shadowProgram.u_MvpMatrix, false, mvpFromLight.elements);
//normal matrix
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, shadowProgram.a_Position, objComponents[i].vertexBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
return mvpFromLight;
}
function draw_Cube_off(objComponents, mx, my, mz, tex, vpMatrix) {
//model Matrix (part of the mvp matrix)
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.scale(objScale, objScale, objScale);
modelMatrix.translate(mx * 2, my * 2, mz * 2);
mvpMatrix.set(vpMatrix);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.useProgram(program);
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX2, cameraY2, cameraZ2);
gl.uniform1f(program.u_Ka, 0.5);
gl.uniform1f(program.u_Kd, 0.2);
gl.uniform1f(program.u_Ks, 0.5);
gl.uniform1f(program.u_shininess, 15.0);
// gl.uniform1i(program.u_ShadowMap, 0);
gl.uniform1i(program.u_Sampler, 0);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
// gl.uniformMatrix4fv(program.u_MvpMatrixOfLight, false, mvpFromLight.elements);
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, textures[tex]);
// gl.activeTexture(gl.TEXTURE1);
// gl.bindTexture(gl.TEXTURE_2D, fboShadow.texture);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
}
function draw_Cube(objComponents, mx, my, mz, tex, mvpFromLight) {
//model Matrix (part of the mvp matrix)
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.scale(objScale, objScale, objScale);
modelMatrix.translate(mx * 2, my * 2, mz * 2);
// modelMatrix.translate(0.0, 0.0, -1.0);
// modelMatrix.scale(1.0, 0.5, 2.0);
//mvp: projection * view * model matrix
mvpMatrix.setPerspective(30, 1, 1, 100);
mvpMatrix.lookAt(cameraX, cameraY, cameraZ, 0, 0, 0, 0, 1, 0);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.useProgram(program);
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.1);
gl.uniform1f(program.u_Kd, 0.2);
gl.uniform1f(program.u_Ks, 0.5);
gl.uniform1f(program.u_shininess, 15.0);
gl.uniform1i(program.u_ShadowMap, 0);
gl.uniform1i(program.u_Sampler, 1);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
gl.uniformMatrix4fv(program.u_MvpMatrixOfLight, false, mvpFromLight.elements);
//gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textures[tex]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fboShadow.texture);
for (let i = 0; i < objComponents.length; i++) {
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
}
function parsetexture(text, mtl) {
let objCompImgIndex = [];
const lines = text.split('\n'); // Split the text into lines
lines.forEach(line => {
const trimmedLine = line.trim(); // Trim whitespace from the line
if (trimmedLine.startsWith('usemtl')) { // Check if the line starts with "usemtl"
const materialName = trimmedLine.split(' ')[1]; // Extract the material name
if (mtl[materialName] && mtl[materialName].map_Kd) {
// Check if the material exists and has a map_Kd property
objCompImgIndex.push(mtl[materialName].map_Kd); // Add the map_Kd to the array
}
else {
//show error to the console
console.error('Material not found:', materialName);
}
}
});
return objCompImgIndex; // Return the array containing the map_Kd values
}
function draw_player(objComponents, mx, my, mz, cameraX, cameraY, cameraZ, mvpFromLight) {
gl.useProgram(program);
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate((mx - 0.5) * 0.605, my * 0.6 - 0.9, (mz - 0.5) * 0.605);
modelMatrix.scale(0.05, 0.05, 0.05);
mvpMatrix.setPerspective(30, 1, 1, 100);
mvpMatrix.lookAt(cameraX, cameraY, cameraZ, 0, 0, 0, 0, 1, 0);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.5);
gl.uniform1f(program.u_Kd, 0.7);
gl.uniform1f(program.u_Ks, 1.0);
gl.uniform1f(program.u_shininess, 15.0);
gl.uniform1i(program.u_ShadowMap, 0);
gl.uniform1i(program.u_Sampler, 1);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
gl.uniformMatrix4fv(program.u_MvpMatrixOfLight, false, mvpFromLight.elements);
for (let i = 0; i < objComponents.length; i++) {
//console.log('mtl:'+mtl)
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textures[objCompImgIndex[i]]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fboShadow.texture);
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
}
function draw_enemy(objComponents, mx, my, mz, cameraX, cameraY, cameraZ, tex, mvpFromLight) {
gl.useProgram(program);
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate(mx * 0.6, my * 0.6 - 1, mz * 0.6);
modelMatrix.scale(0.5, 0.5, 0.5);
mvpMatrix.setPerspective(30, 1, 1, 100);
mvpMatrix.lookAt(cameraX, cameraY, cameraZ, 0, 0, 0, 0, 1, 0);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.3);
gl.uniform1f(program.u_Kd, 0.7);
gl.uniform1f(program.u_Ks, 0.9);
gl.uniform1f(program.u_shininess, 15.0);
gl.uniform1i(program.u_Sampler, 0);
gl.uniform1f(program.u_Alpha, 1.0);
gl.uniformMatrix4fv(program.u_MvpMatrix, false, mvpMatrix.elements);
gl.uniformMatrix4fv(program.u_modelMatrix, false, modelMatrix.elements);
gl.uniformMatrix4fv(program.u_normalMatrix, false, normalMatrix.elements);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, textures[tex]);
for (let i = 0; i < objComponents.length; i++) {
//console.log('mtl:'+mtl)
gl.uniform1i(program.u_Sampler, 0);
initAttributeVariable(gl, program.a_Position, objComponents[i].vertexBuffer);
initAttributeVariable(gl, program.a_TexCoord, objComponents[i].texCoordBuffer);
initAttributeVariable(gl, program.a_Normal, objComponents[i].normalBuffer);
gl.drawArrays(gl.TRIANGLES, 0, objComponents[i].numVertices);
}
//console.log("draw enemy at"+map[idx].mobLocation.x+","+map[idx].mobLocation.y);
}
function drawoffscreen(vpMatrix) {
//gl.clearColor(0,0,0,1);
gl.enable(gl.DEPTH_TEST);
idx = player.nowRoom;
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
draw_Env_Cube(cameraX2, cameraY2, cameraZ2, null);
var offset = 2;
var xsz = map[idx].xSize / 2;
var ysz = map[idx].ySize / 2;
for (let i = 0; i < map[idx].xSize; i++) {
for (let j = 0; j < map[idx].ySize; j++) {
for (let k = 1; k <= map[idx].field[i][j]; ++k) {
draw_Cube_off(cubeObj, i - xsz, k - offset, j - ysz, "brick", vpMatrix);
}
}
}
for (let i = 0; i < map[idx].sightObj.length; ++i) {
draw_Cube_off(cubeObj, map[idx].sightObj[i].x - xsz, map[idx].sightObj[i].z - offset, map[idx].sightObj[i].y - ysz, "stone", vpMatrix);
}
draw_rock_off(rockObj, lX, 5, lZ, "rock", vpMatrix);
//console.log("x,y="+player.location.x+","+player.location.y)
draw_player_off(playerObj, player.location.x - 8, player.location.z, player.location.y - 8, vpMatrix);
}
function draw_player_off(objComponents, mx, my, mz, vpMatrix, mvpFromLight) {
gl.useProgram(program);
modelMatrix.setIdentity();
modelMatrix.setRotate(angleY, 1, 0, 0);//for mouse rotation
modelMatrix.rotate(angleX, 0, 1, 0);//for mouse rotation
modelMatrix.translate((mx - 0.5) * 0.605, my * 0.6 - 0.9, (mz - 0.5) * 0.605);
modelMatrix.scale(0.05, 0.05, 0.05);
mvpMatrix.set(vpMatrix);
mvpMatrix.multiply(modelMatrix);
//normal matrix
normalMatrix.setInverseOf(modelMatrix);
normalMatrix.transpose();
gl.uniform3f(program.u_LightPosition, lightX, lightY, lightZ);
gl.uniform3f(program.u_ViewPosition, cameraX, cameraY, cameraZ);
gl.uniform1f(program.u_Ka, 0.5);