BlueGit

timfa raytracer

Files

raytracer / build / game.js

game.js

game.js 14.8 KiB Download Raw
1
2/*
3 * Start File:
4 * /workspace/raytracer-work/src/textureColumn.js
5 */
6/**
7 * Texture-column helpers for Wolfenstein-style wall strips.
8 * Each screen column samples exactly one source pixel column.
9 */
10function textureColumnIndex (tileX, texWidth)
11{
12 if (!(texWidth > 0))
13 { return 0; }
14
15 var sx = Math.floor(Number(tileX) * texWidth);
16 if (sx < 0)
17 { sx = 0; }
18 if (sx > texWidth - 1)
19 { sx = texWidth - 1; }
20 return sx;
21}
22
23function textureColumnUv (tileX, texWidth)
24{
25 var sx = textureColumnIndex(tileX, texWidth);
26 var w = texWidth > 0 ? texWidth : 1;
27 return {
28 sx: sx,
29 sw: 1,
30 u0: sx / w,
31 u1: (sx + 1) / w,
32 v0: 0,
33 v1: 1
34 };
35}
36
37/** Face U from hit position within a cell (no +1 bias). */
38function faceTileX (hitCoord, cellSize, face)
39{
40 var local = hitCoord % cellSize;
41 if (local < 0)
42 { local += cellSize; }
43 var t = local / cellSize;
44 switch (face)
45 {
46 case "north": return t;
47 case "south": return 1 - t;
48 case "east": return 1 - t;
49 case "west": return t;
50 default: return t;
51 }
52}
53
54if (typeof module !== "undefined" && module.exports)
55{
56 module.exports = {
57 textureColumnIndex: textureColumnIndex,
58 textureColumnUv: textureColumnUv,
59 faceTileX: faceTileX
60 };
61}
62
63/*
64 * End File:
65 * /workspace/raytracer-work/src/textureColumn.js
66 */
67
68/*
69 * Start File:
70 * /workspace/raytracer-work/src/levels.js
71 */
72var Levels =
73[
74 {
75 name: "Level 1",
76 width: 10,
77 height: 10,
78 spawnX: 1,
79 spawnY: 1,
80 tiles:
81 [
82 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
83 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
84 1, 0, 1, 1, 0, 0, 3, 3, 0, 1,
85 1, 0, 0, 1, 0, 0, 0, 0, 0, 1,
86 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
87 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
88 1, 0, 0, 0, 0, 1, 2, 1, 0, 1,
89 1, 0, 1, 0, 0, 1, 3, 1, 0, 1,
90 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
91 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
92 ]
93 }
94];
95
96/*
97 * End File:
98 * /workspace/raytracer-work/src/levels.js
99 */
100
101/*
102 * Start File:
103 * /workspace/raytracer-work/src/tiles.js
104 */
105/** Tile table; Image fields filled after preload. */
106var Tiles =
107{
108 Nothing:
109 {
110 ID: 0,
111 Color: { R: 255, G: 255, B: 255 },
112 Solid: false,
113 ImageName: null
114 },
115 Stone:
116 {
117 ID: 1,
118 Color: { R: 155, G: 155, B: 155 },
119 Solid: true,
120 ImageName: "stone"
121 },
122 Finish:
123 {
124 ID: 2,
125 Color: { R: 255, G: 255, B: 0 },
126 Solid: false,
127 ImageName: null
128 },
129 Wood:
130 {
131 ID: 3,
132 Color: { R: 168, G: 102, B: 50 },
133 Solid: true,
134 ImageName: "wood"
135 },
136 findByID: function (id)
137 {
138 for (var key in Tiles)
139 {
140 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
141 { continue; }
142 var value = Tiles[key];
143 if (value && value.ID === id)
144 { return value; }
145 }
146 return null;
147 },
148 bindImages: function (images)
149 {
150 for (var key in Tiles)
151 {
152 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
153 { continue; }
154 var tile = Tiles[key];
155 if (tile && tile.ImageName && images[tile.ImageName])
156 { tile.Image = images[tile.ImageName]; }
157 }
158 }
159};
160
161/*
162 * End File:
163 * /workspace/raytracer-work/src/tiles.js
164 */
165
166/*
167 * Start File:
168 * /workspace/raytracer-work/src/world.js
169 */
170var World =
171{
172 size: 32,
173 level: null,
174
175 loadLevel: function (index)
176 {
177 this.level = Levels[index];
178 },
179
180 spawnPoint: function ()
181 {
182 return {
183 x: this.level.spawnX * this.size + this.size / 2,
184 y: this.level.spawnY * this.size + this.size / 2
185 };
186 },
187
188 rayCast: function (x, y, radian)
189 {
190 var maxDist = this.level.width + this.level.height;
191 var cell = this.size;
192 var tileXpercentage = 0;
193 var tileXp = 0;
194 var tileYp = 0;
195
196 // --- horizontal grid lines ---
197 var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;
198 var hDir = "north";
199 distDone = 0;
200 var aTan = -1 / Math.tan(radian);
201
202 if (radian > Math.PI)
203 {
204 hrayY = Math.floor(y / cell) * cell - 0.01;
205 hrayX = (y - hrayY) * aTan + x;
206 hoffY = -cell;
207 hoffX = -hoffY * aTan;
208 }
209 else if (radian < Math.PI)
210 {
211 hrayY = Math.floor(y / cell) * cell + cell;
212 hrayX = (y - hrayY) * aTan + x;
213 hoffY = cell;
214 hoffX = -hoffY * aTan;
215 hDir = "south";
216 }
217 else
218 {
219 hrayX = x;
220 hrayY = y;
221 distDone = maxDist;
222 }
223
224 while (distDone < maxDist)
225 {
226 tileXp = ((hrayX % cell) + cell) % cell / cell;
227 tileYp = ((hrayY % cell) + cell) % cell / cell;
228 hmapX = Math.floor(hrayX / cell);
229 hmapY = Math.floor(hrayY / cell);
230 var htileHitId = this.level.tiles[hmapX + hmapY * this.level.width];
231 htileHit = Tiles.findByID(htileHitId);
232 if (htileHit && htileHit.Solid)
233 { distDone = maxDist; }
234 else
235 {
236 hrayX += hoffX;
237 hrayY += hoffY;
238 distDone += 1;
239 }
240 }
241
242 switch (hDir)
243 {
244 case "north": tileXpercentage = tileXp; break;
245 case "south": tileXpercentage = 1 - tileXp; break;
246 case "east": tileXpercentage = 1 - tileYp; break;
247 case "west": tileXpercentage = tileYp; break;
248 }
249
250 var hResult = {
251 tile: htileHit,
252 tileX: tileXpercentage,
253 endX: hrayX,
254 endY: hrayY,
255 dir: hDir
256 };
257
258 // --- vertical grid lines ---
259 var rayX, rayY, offX, offY, mapX, mapY, tileHit;
260 var vDir = "east";
261 var nTan = -Math.tan(radian);
262 distDone = 0;
263
264 if (radian > Math.PI / 2 && radian < Math.PI * 1.5)
265 {
266 rayX = Math.floor(x / cell) * cell - 0.01;
267 rayY = (x - rayX) * nTan + y;
268 offX = -cell;
269 offY = -offX * nTan;
270 }
271 else if (radian < Math.PI / 2 || radian > Math.PI * 1.5)
272 {
273 rayX = Math.floor(x / cell) * cell + cell;
274 rayY = (x - rayX) * nTan + y;
275 offX = cell;
276 offY = -offX * nTan;
277 vDir = "west";
278 }
279 else
280 {
281 rayX = x;
282 rayY = y;
283 distDone = maxDist;
284 }
285
286 while (distDone < maxDist)
287 {
288 tileXp = ((rayX % cell) + cell) % cell / cell;
289 tileYp = ((rayY % cell) + cell) % cell / cell;
290 mapX = Math.floor(rayX / cell);
291 mapY = Math.floor(rayY / cell);
292 var tileHitId = this.level.tiles[mapX + mapY * this.level.width];
293 tileHit = Tiles.findByID(tileHitId);
294 if (tileHit && tileHit.Solid)
295 { distDone = maxDist; }
296 else
297 {
298 rayX += offX;
299 rayY += offY;
300 distDone += 1;
301 }
302 }
303
304 switch (vDir)
305 {
306 case "north": tileXpercentage = tileXp; break;
307 case "south": tileXpercentage = 1 - tileXp; break;
308 case "east": tileXpercentage = 1 - tileYp; break;
309 case "west": tileXpercentage = tileYp; break;
310 }
311
312 var vResult = {
313 tile: tileHit,
314 tileX: tileXpercentage,
315 endX: rayX,
316 endY: rayY,
317 dir: vDir
318 };
319
320 var dxH = hResult.endX - x;
321 var dyH = hResult.endY - y;
322 var dxV = vResult.endX - x;
323 var dyV = vResult.endY - y;
324 hResult.distance = Math.sqrt(dxH * dxH + dyH * dyH);
325 vResult.distance = Math.sqrt(dxV * dxV + dyV * dyV);
326
327 if (hResult.distance < vResult.distance)
328 { return hResult; }
329 return vResult;
330 }
331};
332
333if (typeof module !== "undefined" && module.exports)
334{
335 module.exports = { World: World };
336}
337
338/*
339 * End File:
340 * /workspace/raytracer-work/src/world.js
341 */
342
343/*
344 * Start File:
345 * /workspace/raytracer-work/src/player.js
346 */
347var Player =
348{
349 x: 0,
350 y: 0,
351 rotation: 0,
352 pitch: 0,
353 /** Screen columns per frame. 240 is sharp on ~1080p and cheap (~240 drawSprite calls). */
354 horizontalResolution: 240,
355 gunX: 0.6,
356 gunY: 0.6,
357 currentGun: 0,
358 guns: 3,
359
360 resetToSpawn: function ()
361 {
362 var spawn = World.spawnPoint();
363 this.x = spawn.x;
364 this.y = spawn.y;
365 this.rotation = 0;
366 this.pitch = 0;
367 },
368
369 applyLookDelta: function (movementX, movementY)
370 {
371 this.pitch += movementY * 0.01;
372 this.rotation += movementX * 0.001;
373 if (this.pitch > Math.PI)
374 { this.pitch = Math.PI; }
375 if (this.pitch < -Math.PI)
376 { this.pitch = -Math.PI; }
377 if (this.rotation > Math.PI * 2)
378 { this.rotation -= Math.PI * 2; }
379 if (this.rotation < 0)
380 { this.rotation += Math.PI * 2; }
381 },
382
383 /** Legacy angles: 0 = +X (east), increases toward +Y. */
384 forwardVector: function (radian)
385 {
386 return { x: Math.cos(radian), y: Math.sin(radian) };
387 },
388
389 tryMove: function (rot, speed, deltaTime)
390 {
391 if (World.rayCast(this.x, this.y, rot).distance <= 5)
392 { return; }
393 var forward = this.forwardVector(rot);
394 this.x += forward.x * deltaTime * speed;
395 this.y += forward.y * deltaTime * speed;
396 },
397
398 update: function (deltaTime)
399 {
400 if (GameInput.isHeld(37) || GameInput.isHeld(65))
401 {
402 var rotL = this.rotation - Math.PI / 2;
403 if (rotL < 0) { rotL += Math.PI * 2; }
404 this.tryMove(rotL, 60, deltaTime);
405 }
406 if (GameInput.isHeld(39) || GameInput.isHeld(68))
407 {
408 var rotR = this.rotation + Math.PI / 2;
409 if (rotR > Math.PI * 2) { rotR -= Math.PI * 2; }
410 this.tryMove(rotR, 60, deltaTime);
411 }
412 if (GameInput.isHeld(38) || GameInput.isHeld(87))
413 { this.tryMove(this.rotation, 60, deltaTime); }
414 if (GameInput.isHeld(40) || GameInput.isHeld(83))
415 {
416 var rotB = this.rotation + Math.PI;
417 if (rotB > Math.PI * 2) { rotB -= Math.PI * 2; }
418 if (World.rayCast(this.x, this.y, rotB).distance > 5)
419 {
420 var forward = this.forwardVector(this.rotation);
421 this.x -= forward.x * deltaTime * 40;
422 this.y -= forward.y * deltaTime * 40;
423 }
424 }
425 if (GameInput.isHeld(188))
426 {
427 this.horizontalResolution -= this.horizontalResolution * 0.1 * deltaTime;
428 if (this.horizontalResolution < 30)
429 { this.horizontalResolution = 30; }
430 }
431 if (GameInput.isHeld(190))
432 {
433 this.horizontalResolution += this.horizontalResolution * 0.1 * deltaTime;
434 }
435 }
436};
437
438/*
439 * End File:
440 * /workspace/raytracer-work/src/player.js
441 */
442
443/*
444 * Start File:
445 * /workspace/raytracer-work/src/raycastScene.js
446 */
447/**
448 * Fullscreen WebGL raycast view on frameworkv3.
449 * Wall strips: one source texel column per screen column, NEAREST, tinted for shading.
450 */
451class RaycastScene extends Scene
452{
453 constructor (width, height)
454 {
455 super(0, 0, width, height, Scene.DisplayModes.absolute);
456 this.backgroundColor = { r: 0, g: 0, b: 0 };
457 this.tintShader = null;
458 this.solidTexture = null;
459 this.gunImages = null;
460 this._lookBound = false;
461 }
462
463 onLoad ()
464 {
465 const gl = this.glContext.gl;
466 this.glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
467
468 this.tintShader = new Shader(Shader.DEFAULT_VERT, [
469 "precision mediump float;",
470 "uniform sampler2D u_texture;",
471 "uniform float u_alpha;",
472 "uniform vec3 u_tint;",
473 "varying vec2 v_texCoord;",
474 "void main() {",
475 " vec4 color = texture2D(u_texture, v_texCoord);",
476 " gl_FragColor = vec4(color.rgb * u_tint, color.a * u_alpha);",
477 "}"
478 ].join("\n"));
479
480 // 1x1 white for solid (untextured) walls.
481 const c = document.createElement("canvas");
482 c.width = 1;
483 c.height = 1;
484 const ctx = c.getContext("2d");
485 ctx.fillStyle = "#ffffff";
486 ctx.fillRect(0, 0, 1, 1);
487 this.solidTexture = this.glContext.getTexture(c);
488
489 this.bindPointerLock();
490 }
491
492 bindPointerLock ()
493 {
494 if (this._lookBound)
495 { return; }
496 this._lookBound = true;
497 const canvas = this.cv_canvas;
498 canvas.addEventListener("click", function ()
499 {
500 if (canvas.requestPointerLock)
501 { canvas.requestPointerLock(); }
502 });
503 document.addEventListener("mousemove", function (e)
504 {
505 if (document.pointerLockElement === canvas)
506 { Player.applyLookDelta(e.movementX || 0, e.movementY || 0); }
507 });
508 }
509
510 update (deltaTime)
511 {
512 super.update(deltaTime);
513 Player.update(deltaTime);
514 if (Player.horizontalResolution > this.real_size.x)
515 { Player.horizontalResolution = this.real_size.x; }
516 }
517
518 draw ()
519 {
520 if (this.destroyed || !this.glContext)
521 { return; }
522
523 this.g_fixSize();
524 const glc = this.glContext;
525 glc.endOffscreenPass();
526 glc.clear(0, 0, 0, 1);
527
528 this.drawColumns();
529 this.drawGun();
530 }
531
532 faceLight (dir)
533 {
534 switch (dir)
535 {
536 case "east": return 0.9;
537 case "west": return 0.8;
538 case "south": return 0.7;
539 default: return 1.0;
540 }
541 }
542
543 drawColumns ()
544 {
545 const glc = this.glContext;
546 const w = this.real_size.x;
547 const h = this.real_size.y;
548 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
549 const rad = Math.PI / (cols * 2);
550 const widthLine = w / cols;
551
552 for (var i = 0; i < cols; i++)
553 {
554 var offsetP = -0.5 + (i / cols);
555 var offset = offsetP * cols;
556 var rotationalOffset = offset * rad;
557 var rot = Player.rotation + rotationalOffset;
558 if (rot < 0) { rot += Math.PI * 2; }
559 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
560
561 var rayHit = World.rayCast(Player.x, Player.y, rot);
562 if (!rayHit || !rayHit.tile)
563 { continue; }
564
565 var light = this.faceLight(rayHit.dir);
566 var deltaAngle = Player.rotation - rot;
567 var dist = rayHit.distance * Math.cos(deltaAngle);
568 if (dist < 0.0001)
569 { dist = 0.0001; }
570
571 var xLine = i * widthLine;
572 var wallH = (World.size * h) / dist;
573 var yCenter = (h / 2) + (-Player.pitch * (World.size * h - wallH) * 0.005);
574
575 var tint = [light, light, light];
576 var htmlImage = null;
577 var texW = 1;
578
579 if (rayHit.tile.Image && rayHit.tile.Image.g_image)
580 {
581 htmlImage = rayHit.tile.Image.g_image;
582 texW = htmlImage.width || 1;
583 var uv = textureColumnUv(rayHit.tileX, texW);
584 glc.drawSprite({
585 texture: glc.getTexture(htmlImage),
586 x: xLine + widthLine / 2,
587 y: yCenter,
588 w: widthLine,
589 h: wallH,
590 rotationDeg: 0,
591 alpha: 1,
592 uvRect: { u0: uv.u0, v0: uv.v0, u1: uv.u1, v1: uv.v1 },
593 shader: this.tintShader,
594 uniforms: { u_tint: tint }
595 });
596 }
597 else
598 {
599 var c = rayHit.tile.Color || { R: 255, G: 255, B: 255 };
600 tint = [(c.R / 255) * light, (c.G / 255) * light, (c.B / 255) * light];
601 glc.drawSprite({
602 texture: this.solidTexture,
603 x: xLine + widthLine / 2,
604 y: yCenter,
605 w: widthLine,
606 h: wallH,
607 rotationDeg: 0,
608 alpha: 1,
609 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
610 shader: this.tintShader,
611 uniforms: { u_tint: tint }
612 });
613 }
614 }
615 }
616
617 drawGun ()
618 {
619 const images = this.game && this.game.images;
620 if (!images)
621 { return; }
622 var gunImg = null;
623 switch (Player.currentGun)
624 {
625 case 0: gunImg = images.shotgun; break;
626 case 1: gunImg = images.machinegun; break;
627 case 2: gunImg = images.pulserifle; break;
628 }
629 if (!gunImg || !gunImg.g_image)
630 { return; }
631
632 var p = this.real_size.y / 1080;
633 var gw = p * gunImg.g_image.width;
634 var gh = p * gunImg.g_image.height;
635 var gx = this.real_size.x * Player.gunX + gw / 2;
636 var gy = this.real_size.y * Player.gunY + gh / 2;
637
638 gunImg.draw(
639 this,
640 gx,
641 gy,
642 gw,
643 gh,
644 0,
645 false,
646 false,
647 1,
648 0
649 );
650 }
651}
652
653/*
654 * End File:
655 * /workspace/raytracer-work/src/raycastScene.js
656 */
657
658/*
659 * Start File:
660 * /workspace/raytracer-work/src/main.js
661 */
662console.log("Raytracer (frameworkv3) starting");
663var game = new Game();
664
665window.onload = function ()
666{
667 game.preloadImagesThenStart(
668 [
669 { name: "stone", url: "images/stone.png" },
670 { name: "wood", url: "images/wood.png" },
671 { name: "shotgun", url: "images/shotgun.png" },
672 { name: "machinegun", url: "images/machinegun.png" },
673 { name: "pulserifle", url: "images/pulserifle.png" }
674 ],
675 function ()
676 {
677 Tiles.bindImages(game.images);
678 World.loadLevel(0);
679 Player.resetToSpawn();
680
681 var w = Math.max(320, window.innerWidth - 2);
682 var h = Math.max(240, window.innerHeight - 2);
683 var scene = new RaycastScene(w, h);
684 game.loadScene(scene);
685
686 window.addEventListener("resize", function ()
687 {
688 scene.size.x = Math.max(320, window.innerWidth - 2);
689 scene.size.y = Math.max(240, window.innerHeight - 2);
690 });
691 }
692 );
693};
694
695/*
696 * End File:
697 * /workspace/raytracer-work/src/main.js
698 */