create-threenative 0.2.18 → 0.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/agent-docs/references/assertion-reference.md +1 -1
  2. package/agent-docs/references/capability-reference.md +792 -5
  3. package/agent-docs/references/kit-racing.md +4 -2
  4. package/agent-docs/references/performance-basics.md +2 -1
  5. package/agent-docs/references/terrain-authoring.md +25 -7
  6. package/agent-files/.agents/skills/prd-creator/SKILL.md +24 -0
  7. package/dist/index.js +268 -237
  8. package/dist/quality.d.ts +5 -1
  9. package/dist/quality.js +75 -6
  10. package/dist/terrain-kit.js +1 -1
  11. package/dist/threenative.js +7 -5
  12. package/dist/web-engine-post-effects.js +6 -0
  13. package/dist/web-engine-runtime.js +407 -38
  14. package/package.json +6 -6
  15. package/template-assets/assets/floor-fern-0.glb +0 -0
  16. package/template-assets/assets/floor-litter-0.glb +0 -0
  17. package/template-assets/assets/floor-log-0.glb +0 -0
  18. package/template-assets/assets/floor-log-1.glb +0 -0
  19. package/template-assets/assets/floor-stump-0.glb +0 -0
  20. package/template-assets/assets/floor-twig-0.glb +0 -0
  21. package/template-assets/patches/three@0.187.0.patch +108 -21
  22. package/template-assets/quality/eslint.config.js +1 -1
  23. package/templates/action-rpg/package.json +7 -7
  24. package/templates/action-rpg/src/loot/drops.ts +3 -7
  25. package/templates/action-rpg/src/render/camera.ts +2 -2
  26. package/templates/action-rpg/src/render/clouds.ts +3 -1
  27. package/templates/action-rpg/src/render/materials.ts +3 -2
  28. package/templates/action-rpg/src/render/touch-controls.ts +7 -6
  29. package/templates/action-rpg/src/scenes/Play.ts +1 -15
  30. package/templates/adventure/AGENTS.md +3 -3
  31. package/templates/adventure/CLAUDE.md +3 -3
  32. package/templates/adventure/native-playtests/survives.playtest.json +12 -0
  33. package/templates/adventure/native-playtests/woodland-floor.playtest.json +61 -0
  34. package/templates/adventure/package.json +7 -7
  35. package/templates/adventure/playtests/grass.playtest.json +61 -0
  36. package/templates/adventure/playtests/performance.playtest.json +1 -1
  37. package/templates/adventure/playtests/survives.playtest.json +2 -2
  38. package/templates/adventure/playtests/woodland-floor.playtest.json +61 -0
  39. package/templates/adventure/src/entities/LockOn.ts +42 -4
  40. package/templates/adventure/src/entities/Warden.ts +12 -3
  41. package/templates/adventure/src/level/Vale.ts +241 -16
  42. package/templates/adventure/src/render/camera.ts +2 -2
  43. package/templates/adventure/src/render/foliage.ts +64 -20
  44. package/templates/adventure/src/render/grass.ts +325 -0
  45. package/templates/adventure/src/render/materials.ts +3 -2
  46. package/templates/adventure/src/render/palette.ts +3 -0
  47. package/templates/adventure/src/render/touch-controls.ts +4 -1
  48. package/templates/adventure/src/scenes/Play.ts +96 -1
  49. package/templates/collectathon/package.json +7 -7
  50. package/templates/collectathon/src/level/Course.ts +2 -7
  51. package/templates/collectathon/src/level/terrain.ts +2 -1
  52. package/templates/collectathon/src/render/camera.ts +2 -2
  53. package/templates/collectathon/src/render/ground.ts +4 -4
  54. package/templates/collectathon/src/render/hero.ts +1 -1
  55. package/templates/collectathon/src/render/materials.ts +0 -1
  56. package/templates/collectathon/src/render/sky.ts +4 -3
  57. package/templates/kart/package.json +6 -6
  58. package/templates/kart/src/entities/Kart.ts +2 -1
  59. package/templates/kart/src/render/course.ts +2 -1
  60. package/templates/kart/src/track/Course.ts +3 -1
  61. package/templates/minimal/package.json +6 -6
  62. package/templates/minimal/src/render/camera.ts +2 -2
  63. package/templates/minimal/src/render/clouds.ts +3 -1
  64. package/templates/minimal/src/render/materials.ts +3 -2
  65. package/templates/minimal/src/render/touch-controls.ts +7 -6
  66. package/templates/platformer/package.json +7 -7
  67. package/templates/platformer/playtests/collect.playtest.json +4 -1
  68. package/templates/platformer/src/level/Stage.ts +2 -6
  69. package/templates/platformer/src/scenes/Play.ts +2 -1
  70. package/templates/puzzle/package.json +7 -7
  71. package/templates/puzzle/src/entities/Warden.ts +3 -3
  72. package/templates/puzzle/src/render/camera.ts +2 -2
  73. package/templates/puzzle/src/render/touch-controls.ts +7 -6
  74. package/templates/racing/AGENTS.md +2 -2
  75. package/templates/racing/CLAUDE.md +2 -2
  76. package/templates/racing/CREDITS.md +29 -0
  77. package/templates/racing/assets/engine-loop.wav +0 -0
  78. package/templates/racing/assets/grass/Grass004_color.jpg +0 -0
  79. package/templates/racing/assets/grass/Grass004_normal.jpg +0 -0
  80. package/templates/racing/assets/grass/Grass004_roughness.jpg +0 -0
  81. package/templates/racing/assets/nitro-burst.wav +0 -0
  82. package/templates/racing/assets/tyre-squeal.wav +0 -0
  83. package/templates/racing/package.json +7 -7
  84. package/templates/racing/playtests/drift-natural.playtest.json +68 -0
  85. package/templates/racing/playtests/drift.playtest.json +100 -0
  86. package/templates/racing/playtests/hud.playtest.json +117 -0
  87. package/templates/racing/playtests/launch-pose.playtest.json +34 -0
  88. package/templates/racing/playtests/nitro.playtest.json +158 -0
  89. package/templates/racing/playtests/outcome.playtest.json +4 -4
  90. package/templates/racing/playtests/performance.playtest.json +1 -1
  91. package/templates/racing/playtests/steady-camera.playtest.json +88 -0
  92. package/templates/racing/src/audio/engine.ts +138 -0
  93. package/templates/racing/src/entities/CarBody.ts +83 -10
  94. package/templates/racing/src/entities/Drift.ts +243 -0
  95. package/templates/racing/src/entities/LineDriver.ts +2 -2
  96. package/templates/racing/src/entities/Nitro.ts +72 -0
  97. package/templates/racing/src/entities/RacingCar.ts +86 -21
  98. package/templates/racing/src/entities/Rival.ts +35 -21
  99. package/templates/racing/src/game.ts +6 -0
  100. package/templates/racing/src/gauges.ts +74 -0
  101. package/templates/racing/src/render/camera.ts +29 -4
  102. package/templates/racing/src/render/clouds.ts +3 -1
  103. package/templates/racing/src/render/effects.ts +244 -0
  104. package/templates/racing/src/render/materials.ts +43 -8
  105. package/templates/racing/src/render/shapes.ts +37 -0
  106. package/templates/racing/src/render/skids.ts +84 -0
  107. package/templates/racing/src/render/touch-controls.ts +10 -10
  108. package/templates/racing/src/scenes/Race.ts +277 -25
  109. package/templates/racing/src/state.ts +35 -0
  110. package/templates/racing/src/style.css +3 -0
  111. package/templates/racing/src/track/Ranking.ts +8 -4
  112. package/templates/racing/src/track/Track.ts +132 -58
  113. package/templates/racing/src/track/TrackSector.ts +19 -1
  114. package/templates/racing/src/track/circuit.ts +21 -15
  115. package/templates/racing/src/ui/GameUi.tsx +0 -2
  116. package/templates/racing/src/ui/Hud.tsx +417 -50
  117. package/templates/racing/threenative.config.ts +15 -0
  118. package/templates/racing/tools/make-racing-audio.mjs +388 -0
  119. package/templates/rain/package.json +6 -6
  120. package/templates/rain/src/render/noise-volume.ts +2 -1
  121. package/templates/rain/src/state.ts +3 -1
  122. package/templates/rain/src/ui/GameUi.tsx +1 -1
  123. package/templates/rain/src/ui/automation.ts +10 -8
  124. package/templates/rain/src/ui/tempest.ts +3 -4
  125. package/templates/rts/package.json +6 -6
  126. package/templates/rts/src/sim/terrain.ts +1 -0
  127. package/templates/rts/src/sim/types.ts +1 -0
  128. package/templates/runner/package.json +7 -7
  129. package/templates/runner/src/render/clouds.ts +3 -1
  130. package/templates/runner/src/render/materials.ts +3 -2
  131. package/templates/runner/src/render/touch-controls.ts +7 -6
  132. package/templates/runner/src/scenes/Run.ts +4 -9
  133. package/templates/sailing/package.json +7 -7
  134. package/templates/sailing/src/render/touch-controls.ts +7 -6
  135. package/templates/shooter/package.json +7 -7
  136. package/templates/shooter/src/render/clouds.ts +3 -1
  137. package/templates/snow/package.json +7 -7
  138. package/templates/snow/src/entities/Explorer.ts +6 -12
  139. package/templates/snow/src/render/bootPrint.ts +3 -1
  140. package/templates/snow/src/render/camera.ts +3 -2
  141. package/templates/snow/src/render/scenery.ts +3 -3
  142. package/templates/snow/src/render/touch-controls.ts +7 -6
  143. package/templates/snow/src/render/weather.ts +3 -5
  144. package/templates/snow/src/terrain.ts +2 -1
  145. package/templates/starter/native-playtests/render-chain.playtest.json +9 -9
  146. package/templates/starter/package.json +7 -7
  147. package/templates/starter/src/entities/Player.ts +10 -2
  148. package/templates/starter/src/render/camera.ts +2 -2
  149. package/templates/starter/src/render/clouds.ts +3 -1
  150. package/templates/starter/src/render/materials.ts +3 -2
  151. package/templates/starter/src/render/touch-controls.ts +7 -6
  152. package/templates/starter/src/scenes/Play.ts +1 -14
  153. package/templates/tower-defense/package.json +7 -7
  154. package/templates/tower-defense/src/render/shapes.ts +1 -2
  155. package/templates/tower-defense/src/scenes/Battle.ts +3 -8
  156. package/template-assets/terrain/alpine/assets.json +0 -12
  157. package/template-assets/terrain/alpine/bake.mjs +0 -6
  158. package/template-assets/terrain/alpine/credits.json +0 -164
  159. package/template-assets/terrain/alpine/heightmap.r16 +0 -0
  160. package/template-assets/terrain/alpine/recipe.json +0 -119
  161. package/template-assets/terrain/alpine/surface.json +0 -53
  162. package/template-assets/terrain/coastal/assets.json +0 -11
  163. package/template-assets/terrain/coastal/bake.mjs +0 -6
  164. package/template-assets/terrain/coastal/credits.json +0 -117
  165. package/template-assets/terrain/coastal/heightmap.r16 +0 -0
  166. package/template-assets/terrain/coastal/recipe.json +0 -113
  167. package/template-assets/terrain/coastal/surface.json +0 -41
  168. package/template-assets/terrain/desert/assets.json +0 -12
  169. package/template-assets/terrain/desert/bake.mjs +0 -6
  170. package/template-assets/terrain/desert/credits.json +0 -164
  171. package/template-assets/terrain/desert/heightmap.r16 +0 -0
  172. package/template-assets/terrain/desert/recipe.json +0 -108
  173. package/template-assets/terrain/desert/surface.json +0 -54
  174. package/template-assets/terrain/forest/assets.json +0 -65
  175. package/template-assets/terrain/forest/bake.mjs +0 -8
  176. package/template-assets/terrain/forest/credits.json +0 -225
  177. package/template-assets/terrain/forest/heightmap.r16 +0 -0
  178. package/template-assets/terrain/forest/recipe.json +0 -350
  179. package/template-assets/terrain/forest/surface.json +0 -79
  180. package/template-assets/terrain/tundra/assets.json +0 -12
  181. package/template-assets/terrain/tundra/bake.mjs +0 -6
  182. package/template-assets/terrain/tundra/credits.json +0 -164
  183. package/template-assets/terrain/tundra/heightmap.r16 +0 -0
  184. package/template-assets/terrain/tundra/recipe.json +0 -277
  185. package/template-assets/terrain/tundra/surface.json +0 -54
  186. package/templates/racing/src/ui/Menu.tsx +0 -7
@@ -1,4 +1,5 @@
1
1
  import {
2
+ GPUParticles3D,
2
3
  Scene,
3
4
  type SceneFrame,
4
5
  afterPhysics,
@@ -8,22 +9,35 @@ import {
8
9
  } from "@threenative/core";
9
10
  import { type IEnvironmentSample, sampleEnvironment } from "@threenative/core/render/environment";
10
11
  import type { IPhysicsContext } from "@threenative/physics";
11
- import { type PerspectiveCamera, type Texture, Vector3 } from "three";
12
+ import {
13
+ MathUtils,
14
+ type Object3D,
15
+ type PerspectiveCamera,
16
+ RepeatWrapping,
17
+ type Texture,
18
+ Vector3,
19
+ } from "three";
20
+ import { EngineAudio } from "../audio/engine.js";
12
21
  import { type CarCtx, FEEL } from "../entities/CarBody.js";
13
22
  import { RacingCar } from "../entities/RacingCar.js";
14
- import { Rival } from "../entities/Rival.js";
23
+ import { RIVALS, Rival } from "../entities/Rival.js";
24
+ import { Gauges } from "../gauges.js";
15
25
  import { emitPlaytestEvent } from "../playtest-events.js";
16
- import { cameraBank, chaseCamera, setupCamera } from "../render/camera.js";
26
+ import { BASE_FOV, cameraBank, chaseCamera, setupCamera } from "../render/camera.js";
17
27
  import { cloudTextures, primeCloudTextures } from "../render/clouds.js";
28
+ import { BURSTS, EFFECTS } from "../render/effects.js";
18
29
  import { setupLighting } from "../render/lighting.js";
19
30
  import { createLoadingScreen } from "../render/loading.js";
20
31
  import { createMaterialLighting } from "../render/materialLighting.js";
32
+ import type { IGrassMaps } from "../render/materials.js";
21
33
  import { setupPost } from "../render/postprocessing.js";
22
34
  import {
23
35
  type QualityTier,
24
36
  isWebGLFallbackRenderer,
25
37
  materialLightingEnabled,
26
38
  } from "../render/quality.js";
39
+ import { EXHAUST } from "../render/shapes.js";
40
+ import { SkidMarks } from "../render/skids.js";
27
41
  import { SKY_OPTIONS, SUN_DIRECTION, setupSky } from "../render/sky.js";
28
42
  import { TouchControls } from "../render/touch-controls.js";
29
43
  import { type GameState, type RaceStatus, resolveRaceStatus } from "../state.js";
@@ -36,15 +50,16 @@ import {
36
50
  gridPosition,
37
51
  intersectRay,
38
52
  roadRayProbe,
53
+ terrainHeight,
39
54
  } from "../track/Track.js";
40
55
  import { TrackSector } from "../track/TrackSector.js";
41
- import { CIRCUIT, GRID_DISTANCE } from "../track/circuit.js";
56
+ import { CIRCUIT, PLAYER_SLOT, gridSlot } from "../track/circuit.js";
42
57
 
43
58
  export type GameCtx = CarCtx;
44
59
 
45
60
  /** The player starts on the second grid slot, one ride height above the tarmac. */
46
- const SPAWN = gridPosition("player", new Vector3());
47
- SPAWN.y = CIRCUIT.at(GRID_DISTANCE.player, CIRCUIT.createSample()).point.y + 0.22;
61
+ const SPAWN = gridPosition(PLAYER_SLOT, new Vector3());
62
+ SPAWN.y = CIRCUIT.at(gridSlot(PLAYER_SLOT).distance, CIRCUIT.createSample()).point.y + 0.22;
48
63
  /**
49
64
  * The race is three laps of 55-60 s, so a time limit under four minutes is a limit nobody reaches
50
65
  * and one that only fires on a car that has already been rescued four times.
@@ -59,6 +74,55 @@ function playerRanking(ranked: readonly IRankedRacer[]): IRankedRacer | undefine
59
74
  return undefined;
60
75
  }
61
76
 
77
+ const DEG = 180 / Math.PI;
78
+
79
+ /**
80
+ * The shake meter: the worst tick-to-tick step of the camera's bank and of the body's lean, and
81
+ * the worst second difference of the camera's yaw. A steady turn has a steady yaw rate, so its
82
+ * second difference is near zero; a camera that twitches from tick to tick does not.
83
+ */
84
+ function createShakeMeter() {
85
+ let roll = 0;
86
+ let yaw = 0;
87
+ let yawRate = 0;
88
+ let lean = 0;
89
+ let samples = 0;
90
+ const dir = new Vector3();
91
+ const right = new Vector3();
92
+ const meter = {
93
+ cameraRollStep: 0,
94
+ cameraYawJerk: 0,
95
+ leanRollStep: 0,
96
+ /** The body's roll and pitch this tick, in degrees: + rolls toward the right, + lifts the nose. */
97
+ leanRoll: 0,
98
+ leanPitch: 0,
99
+ /** A camera cut is not a shake: the next two samples rebuild the history. */
100
+ reset(): void {
101
+ samples = 0;
102
+ },
103
+ sample(camera: PerspectiveCamera, body: Object3D): void {
104
+ camera.getWorldDirection(dir);
105
+ right.setFromMatrixColumn(camera.matrixWorld, 0);
106
+ const nextYaw = Math.atan2(dir.z, dir.x);
107
+ const rate = Math.atan2(Math.sin(nextYaw - yaw), Math.cos(nextYaw - yaw));
108
+ const nextRoll = Math.asin(MathUtils.clamp(right.y, -1, 1));
109
+ if (samples >= 2) {
110
+ meter.cameraRollStep = Math.max(meter.cameraRollStep, Math.abs(nextRoll - roll) * DEG);
111
+ meter.cameraYawJerk = Math.max(meter.cameraYawJerk, Math.abs(rate - yawRate) * DEG);
112
+ meter.leanRollStep = Math.max(meter.leanRollStep, Math.abs(body.rotation.x - lean) * DEG);
113
+ }
114
+ samples += 1;
115
+ roll = nextRoll;
116
+ yaw = nextYaw;
117
+ yawRate = rate;
118
+ lean = body.rotation.x;
119
+ meter.leanRoll = body.rotation.x * DEG;
120
+ meter.leanPitch = body.rotation.z * DEG;
121
+ },
122
+ };
123
+ return meter;
124
+ }
125
+
62
126
  function quantize(value: number, scale: number): number {
63
127
  return Math.round(value * scale) / scale;
64
128
  }
@@ -71,11 +135,30 @@ export class Race extends Scene<GameState, IPhysicsContext> {
71
135
  boostActive: false,
72
136
  boostPeakSpeed: 0,
73
137
  boostUses: 0,
138
+ drifting: false,
139
+ driftAngle: 0,
140
+ driftScore: 0,
141
+ driftsBanked: 0,
142
+ driftSpins: 0,
143
+ nitro: 1,
144
+ nitroActive: false,
145
+ nitroDriftGain: 0,
146
+ gear: 1,
147
+ rpm: 0,
148
+ driftLast: 0,
149
+ driftPopup: 0,
150
+ fov: BASE_FOV,
151
+ fovPeak: BASE_FOV,
152
+ engineRate: 0,
74
153
  completedLaps: 0,
75
154
  elapsed: 0,
76
155
  lastOnRoad: [SPAWN.x, SPAWN.y, SPAWN.z],
77
156
  place: 1,
157
+ racers: RIVALS.length + 1,
78
158
  position: "P1",
159
+ bestLap: 0,
160
+ lastLap: 0,
161
+ rankings: [],
79
162
  raceStatus: "RACING",
80
163
  rescueHeading: 0,
81
164
  // Before any rescue, both errors are the worst they could be: the car is facing the wrong way
@@ -95,6 +178,7 @@ export class Race extends Scene<GameState, IPhysicsContext> {
95
178
  };
96
179
 
97
180
  #sky: Texture | undefined;
181
+ #grass: IGrassMaps | undefined;
98
182
 
99
183
  /**
100
184
  * The sky photograph, **awaited** before the scene enters.
@@ -111,11 +195,13 @@ export class Race extends Scene<GameState, IPhysicsContext> {
111
195
  #environmentSample: IEnvironmentSample | undefined;
112
196
  #materialLighting: ReturnType<typeof createMaterialLighting> | undefined;
113
197
  #lightingGeneration = 0;
198
+ #audio: EngineAudio | undefined;
114
199
 
115
200
  override async load(ctx: GameCtx): Promise<void> {
116
201
  const generation = ++this.#lightingGeneration;
117
202
  // Only the photo-sky override reads the photograph; the atmosphere sky is computed.
118
203
  const texture = SKY_OPTIONS.sky === "photo" ? await ctx.assets.texture("sky.jpg") : undefined;
204
+ this.#grass = await loadGrassTextures(ctx);
119
205
  if (generation !== this.#lightingGeneration) return;
120
206
  this.#sky = texture;
121
207
  const scene = ctx.scene;
@@ -193,15 +279,18 @@ export class Race extends Scene<GameState, IPhysicsContext> {
193
279
  const touchControls = showTouchControls
194
280
  ? ctx.entities.add("touch-controls", new TouchControls(camera))
195
281
  : undefined;
196
- const track = buildTrack(ctx);
197
- const car = new RacingCar(ctx, SPAWN, gridHeading("player"));
198
- // The rival's own grid slot, projected onto the circuit it drives: on pole, four metres up the
199
- // road and 4.4 m to the other side, facing the same way. It used to be placed a whole lap
200
- // ahead and then copied onto the player's position, so the two cars were the same point in
201
- // space and the player drove through a rival that had no body.
202
- const rival = new Rival(ctx, GRID_DISTANCE.rival);
282
+ const track = buildTrack(ctx, this.#grass);
283
+ const car = new RacingCar(ctx, SPAWN, gridHeading(PLAYER_SLOT));
284
+ // Display only, both of them: the rev counter's needle and the engine note it pitches. Neither
285
+ // touches the chassis, so a wrong needle is a wrong gauge and never a wrong lap.
286
+ const gauges = new Gauges();
287
+ this.#audio = new EngineAudio(camera, (name) => ctx.assets.audio(name));
288
+ // The field, each car on its own grid slot projected onto the circuit it drives. The pole car
289
+ // is the entity `rival`, the car to beat; the others are `rival-2` to `rival-5`.
290
+ const rivals = RIVALS.map((_, index) => new Rival(ctx, index));
203
291
  ctx.entities.add("player", car);
204
- ctx.entities.add("rival", rival);
292
+ for (const [index, rival] of rivals.entries())
293
+ ctx.entities.add(index === 0 ? "rival" : `rival-${index + 1}`, rival);
205
294
  // The sun's aim as three reads it: the target's world matrix, which only a scene traversal refreshes.
206
295
  ctx.entities.add("sun", {
207
296
  get targetGap(): number {
@@ -214,19 +303,38 @@ export class Race extends Scene<GameState, IPhysicsContext> {
214
303
  // `travelDirection` is the car's **measured** velocity, not the heading it was asked for: a
215
304
  // car that is sliding through a corner is travelling somewhere other than where it points, and
216
305
  // a lap counted on the intent is a lap counted on a wish.
306
+ // Lap times read the same race clock the HUD's timer publishes.
307
+ let elapsed = 0;
308
+ let bestLap = 0;
309
+ let lastLap = 0;
310
+ let lapStartedAt = 0;
217
311
  const lap = new Lap(
218
312
  { body: car.body.body, forward: car.travelDirection },
219
313
  track.gates,
220
314
  TOTAL_LAPS,
221
- (completed) => emitPlaytestEvent({ entity: "player", lap: completed, name: "lap-completed" }),
315
+ (completed) => {
316
+ lastLap = elapsed - lapStartedAt;
317
+ lapStartedAt = elapsed;
318
+ if (bestLap === 0 || lastLap < bestLap) bestLap = lastLap;
319
+ emitPlaytestEvent({ entity: "player", lap: completed, name: "lap-completed" });
320
+ },
222
321
  );
223
322
  const playerRankingInput = { id: "player", lap: lap.completed, position: car.body.position };
224
- const rivalRankingInput = { id: "rival", lap: rival.lap, position: rival.mesh.position };
225
- const rankingInputs = [playerRankingInput, rivalRankingInput];
323
+ const rivalRankingInputs = rivals.map((rival, index) => ({
324
+ id: index === 0 ? "rival" : `rival-${index + 1}`,
325
+ lap: rival.lap,
326
+ position: rival.mesh.position,
327
+ }));
328
+ const rankingInputs = [playerRankingInput, ...rivalRankingInputs];
226
329
  const rankingBuffer: IRankedRacerScratch[] = [];
227
330
  const rankRace = () => {
228
331
  playerRankingInput.lap = lap.completed;
229
- rivalRankingInput.lap = rival.lap;
332
+ // Indexed loop, not `.entries()`: this runs every frame and the runtime-cost gate holds the
333
+ // scene to zero per-frame iterator allocations.
334
+ for (let index = 0; index < rivalRankingInputs.length; index += 1) {
335
+ const input = rivalRankingInputs[index];
336
+ if (input !== undefined) input.lap = rivals[index]?.lap ?? 0;
337
+ }
230
338
  return rankRacers(CIRCUIT, rankingInputs, undefined, rankingBuffer);
231
339
  };
232
340
  const initialRanked = rankRace();
@@ -236,6 +344,12 @@ export class Race extends Scene<GameState, IPhysicsContext> {
236
344
  const sector = new TrackSector({
237
345
  route: CIRCUIT,
238
346
  intersectRay: intersectRay(ctx.physics, fallbackProbe),
347
+ // The grass is a heightfield collider now; this stays as the last-resort net for a car that
348
+ // leaves the world another way (a jump over the armco, or a future gap). The rescue fires the
349
+ // tick the car is clearly below the surface it should be standing on.
350
+ groundAt: terrainHeight,
351
+ // A metre below the drawn ground is not a crest or a berm, it is a car with no world under it.
352
+ fallDepth: 1.2,
239
353
  });
240
354
  track.boostArea.on("bodyEntered", (body) => {
241
355
  if (body === car.body.body) {
@@ -244,7 +358,6 @@ export class Race extends Scene<GameState, IPhysicsContext> {
244
358
  }
245
359
  });
246
360
  car.boost.update(0);
247
- let elapsed = 0;
248
361
  let status: RaceStatus = "RACING";
249
362
  let rescues = 0;
250
363
  // Before any rescue, both are the worst they can be: a car facing the wrong way, a whole lap
@@ -256,6 +369,9 @@ export class Race extends Scene<GameState, IPhysicsContext> {
256
369
  let place = initialPlayer.place;
257
370
  let positionLabel = `P${place}`;
258
371
  const lastOnRoad: [number, number, number] = [SPAWN.x, SPAWN.y, SPAWN.z];
372
+ // A rescue or the autopilot's rejoin teleports the car, so the camera cuts to it instead of
373
+ // flying across the circuit.
374
+ let teleports = car.body.teleports;
259
375
  const observedPosition = SPAWN.clone();
260
376
  sector.update(SPAWN, car.forward, 0, 0);
261
377
  chaseCamera(camera, car.body.position, car.forward, 1, undefined);
@@ -269,7 +385,8 @@ export class Race extends Scene<GameState, IPhysicsContext> {
269
385
  dt,
270
386
  touchControls?.update(frameCtx.input.raw.pointers, frameCtx.viewport.size),
271
387
  );
272
- rival.update(dt);
388
+ for (let index = 0; index < rivals.length; index += 1) rivals[index]?.update(dt);
389
+ gauges.update(car.speed, dt);
273
390
  sector.update(car.body.position, car.forward, dt, car.speed, car.driving);
274
391
  if (sector.rescue(car)) {
275
392
  rescues += 1;
@@ -284,6 +401,68 @@ export class Race extends Scene<GameState, IPhysicsContext> {
284
401
  };
285
402
 
286
403
  const statePatch: Partial<GameState> = {};
404
+ const shake = ctx.entities.add("camera-rig", createShakeMeter());
405
+
406
+ // Effects: two pooled emitters and one instanced ring of skid marks, every look parameter in
407
+ // `render/effects.ts` and `render/skids.ts`.
408
+ const make = (name: keyof typeof EFFECTS): GPUParticles3D => {
409
+ const emitter = ctx.add(new GPUParticles3D(EFFECTS[name]()));
410
+ emitter.name = `effects-${name}`;
411
+ return emitter;
412
+ };
413
+ const emitters = { nitro: make("nitro"), smoke: make("smoke") };
414
+ const burstOrigin = { x: 0, y: 0, z: 0 };
415
+ const burstShape = { x: 0, y: 0, z: 0 };
416
+ const burst = (kind: keyof typeof BURSTS, at: Vector3): void => {
417
+ const { count, emitter, shape } = BURSTS[kind];
418
+ burstOrigin.x = at.x;
419
+ burstOrigin.y = at.y;
420
+ burstOrigin.z = at.z;
421
+ burstShape.x = shape[0];
422
+ burstShape.y = shape[1];
423
+ burstShape.z = shape[2];
424
+ emitters[emitter].emitParticle({ count, direction: burstShape, origin: burstOrigin });
425
+ };
426
+ const skids = new SkidMarks(ctx.scene);
427
+ // What the effects did, for a scenario: ticks a tyre smoked, ticks the flame burned.
428
+ const effects = ctx.entities.add("effects", {
429
+ flameTicks: 0,
430
+ skidMarks: 0,
431
+ smokeTicks: 0,
432
+ });
433
+ const REAR_WHEELS = [2, 3] as const;
434
+ const rearRadius = car.body.body.wheels[2]?.wheelRadius ?? 0.37;
435
+ const contact = new Vector3();
436
+ let effectTick = 0;
437
+ const emitEffects = (): void => {
438
+ effectTick += 1;
439
+ if (car.skidding) {
440
+ let smoked = false;
441
+ for (const index of REAR_WHEELS) {
442
+ const wheel = car.body.wheels[index];
443
+ if (wheel === undefined || !car.body.body.wheelContact(index)) continue;
444
+ wheel.getWorldPosition(contact);
445
+ contact.y -= rearRadius;
446
+ skids.lay(index === 2 ? "rear-a" : "rear-b", contact.x, contact.y, contact.z);
447
+ // Alternate tyres, one burst a tick: a puff a tick a wheel is a wall, not smoke.
448
+ if ((effectTick + index) % 2 === 0) {
449
+ contact.y += 0.12;
450
+ burst("smoke", contact);
451
+ smoked = true;
452
+ }
453
+ }
454
+ if (smoked) effects.smokeTicks += 1;
455
+ effects.skidMarks = skids.laid;
456
+ }
457
+ if (car.nitro.engaged) {
458
+ effects.flameTicks += 1;
459
+ for (const side of [-1, 1]) {
460
+ contact.set(EXHAUST.x - 0.5, EXHAUST.y, side * EXHAUST.z);
461
+ car.body.lean.localToWorld(contact);
462
+ burst("nitro", contact);
463
+ }
464
+ }
465
+ };
287
466
 
288
467
  // The suspension and the camera both read the **solved** chassis, so they run in the
289
468
  // afterPhysics phase rather than in the scene frame: a wheel's spin angle and a car's velocity
@@ -292,14 +471,43 @@ export class Race extends Scene<GameState, IPhysicsContext> {
292
471
  // The sun's shadow camera follows the car. It used to be a fixed 30 m box around the origin,
293
472
  // which on an 830 m circuit put every shadow on the grass and left the car's own shadow — the
294
473
  // speed cue a driver actually reads — somewhere else entirely.
474
+ // The lens's own reading: the nitro kick is measured on the camera, not restated from a
475
+ // constant, so a camera that stops widening fails the scenario that promises it does.
476
+ let fov = BASE_FOV;
477
+ let fovPeak = BASE_FOV;
478
+
295
479
  afterPhysics(ctx, (dt) => {
296
- car.body.settleVisuals();
297
- rival.car.settleVisuals();
480
+ car.body.settleVisuals(car.nitro.engaged, dt);
481
+ for (let index = 0; index < rivals.length; index += 1) rivals[index]?.car.settleVisuals();
482
+ if (status === "RACING") emitEffects();
298
483
  lighting.key.target.position.copy(car.body.position);
299
484
  lighting.key.position.copy(car.body.position).addScaledVector(SUN_DIRECTION, 90);
300
485
  const solved = car.body.body.linearVelocity;
301
- chaseCamera(camera, car.body.position, car.travelDirection, dt, solved);
486
+ const cut = car.body.teleports !== teleports;
487
+ teleports = car.body.teleports;
488
+ chaseCamera(
489
+ camera,
490
+ car.body.position,
491
+ car.travelDirection,
492
+ cut ? 1 : dt,
493
+ solved,
494
+ car.boosting,
495
+ );
302
496
  camera.rotateZ(cameraBank(car.lateralLoad, FEEL.lateral));
497
+ fov = camera.fov;
498
+ fovPeak = Math.max(fovPeak, fov);
499
+ this.#audio?.update({
500
+ running: status === "RACING",
501
+ rpm: gauges.rpm,
502
+ driftAngle: car.drift.angle,
503
+ sliding: car.skidding,
504
+ nitroActive: car.nitro.engaged,
505
+ });
506
+ if (cut) {
507
+ ctx.resetInterpolation(camera);
508
+ shake.reset();
509
+ }
510
+ shake.sample(camera, car.body.lean);
303
511
  });
304
512
 
305
513
  // Collect only after the loaded character and scene receivers are attached.
@@ -334,7 +542,7 @@ export class Race extends Scene<GameState, IPhysicsContext> {
334
542
  const ranked = rankRace();
335
543
  const player = playerRanking(ranked);
336
544
  if (player === undefined) throw new Error("Race ranking lost the player.");
337
- sameDistanceRanking = ranked[0]?.id === "rival" ? "lap-ahead" : "lap-behind";
545
+ sameDistanceRanking = ranked[0]?.id === "player" ? "lap-behind" : "lap-ahead";
338
546
  status = resolveRaceStatus(status, lap.completed, TOTAL_LAPS, player.place);
339
547
  if (player.place !== place) {
340
548
  place = player.place;
@@ -348,9 +556,27 @@ export class Race extends Scene<GameState, IPhysicsContext> {
348
556
  statePatch.autopilot = car.autopilotEngaged;
349
557
  statePatch.boostActive = car.boosting;
350
558
  statePatch.boostPeakSpeed = boostPeakSpeed;
351
- statePatch.boostUses = car.boost.uses;
559
+ statePatch.boostUses = car.boost.uses + car.nitro.uses;
560
+ statePatch.drifting = car.drift.drifting;
561
+ statePatch.driftAngle = quantize(car.drift.angle, 1000);
562
+ statePatch.driftScore = Math.round(car.drift.score);
563
+ statePatch.driftsBanked = car.drift.banked;
564
+ statePatch.driftSpins = car.drift.spins;
565
+ statePatch.nitro = quantize(car.nitro.tank, 1000);
566
+ statePatch.nitroActive = car.nitro.engaged;
567
+ statePatch.nitroDriftGain = quantize(car.nitro.driftGain, 1000);
568
+ statePatch.gear = gauges.gear;
569
+ statePatch.rpm = quantize(gauges.rpm, 1000);
570
+ statePatch.driftLast = Math.round(car.drift.lastBanked);
571
+ statePatch.driftPopup = quantize(car.drift.popup, 100);
572
+ statePatch.fov = quantize(fov, 100);
573
+ statePatch.fovPeak = quantize(fovPeak, 100);
574
+ statePatch.engineRate = quantize(this.#audio?.rate ?? 0, 1000);
352
575
  statePatch.completedLaps = lap.completed;
353
576
  statePatch.elapsed = elapsed;
577
+ statePatch.bestLap = bestLap;
578
+ statePatch.lastLap = lastLap;
579
+ statePatch.rankings = ranked;
354
580
  statePatch.lastOnRoad = lastOnRoad;
355
581
  statePatch.place = player.place;
356
582
  statePatch.position = positionLabel;
@@ -371,6 +597,8 @@ export class Race extends Scene<GameState, IPhysicsContext> {
371
597
  }
372
598
 
373
599
  override exit(ctx: GameCtx): void {
600
+ this.#audio?.dispose();
601
+ this.#audio = undefined;
374
602
  this.#materialLighting?.dispose();
375
603
  this.#materialLighting = undefined;
376
604
  this.#post?.dispose();
@@ -380,3 +608,27 @@ export class Race extends Scene<GameState, IPhysicsContext> {
380
608
  super.exit(ctx);
381
609
  }
382
610
  }
611
+
612
+ /** The real ground PBR set (Poly Haven/ambientCG Grass004, CC0), configured for the 9 m ground UVs. */
613
+ async function loadGrassTextures(ctx: GameCtx): Promise<IGrassMaps> {
614
+ const [color, normal, roughness] = await Promise.all([
615
+ ctx.assets.texture("grass/Grass004_color.jpg", {
616
+ anisotropy: 8,
617
+ repeat: 6.43,
618
+ wrap: RepeatWrapping,
619
+ }),
620
+ ctx.assets.texture("grass/Grass004_normal.jpg", {
621
+ anisotropy: 8,
622
+ data: true,
623
+ repeat: 6.43,
624
+ wrap: RepeatWrapping,
625
+ }),
626
+ ctx.assets.texture("grass/Grass004_roughness.jpg", {
627
+ anisotropy: 8,
628
+ data: true,
629
+ repeat: 6.43,
630
+ wrap: RepeatWrapping,
631
+ }),
632
+ ]);
633
+ return { color, normal, roughness };
634
+ }
@@ -1,3 +1,5 @@
1
+ import type { IRankedRacer } from "./track/Ranking.js";
2
+
1
3
  export type RaceStatus = "DNF" | "RACING" | "WON";
2
4
 
3
5
  export function resolveRaceStatus(
@@ -21,10 +23,43 @@ export type GameState = {
21
23
  boostPeakSpeed: number;
22
24
  speedAfterBoost: number;
23
25
  boostUses: number;
26
+ /** The handbrake drift: in a scored slide, its slip angle in radians, and the banked score. */
27
+ drifting: boolean;
28
+ driftAngle: number;
29
+ driftScore: number;
30
+ driftsBanked: number;
31
+ driftSpins: number;
32
+ /** The nitro tank, 0 to 1, and whether it is burning. */
33
+ nitro: number;
34
+ nitroActive: boolean;
35
+ /** Tank the drift path filled this race, which is what "drifting refills faster" is measured on. */
36
+ nitroDriftGain: number;
37
+ /** The gearbox: the gear engaged and the needle, 0 to 1 of that gear's band. Display only. */
38
+ gear: number;
39
+ rpm: number;
40
+ /** The last banked drift's score, which the HUD pops up for a moment after each one. */
41
+ driftLast: number;
42
+ /**
43
+ * Seconds that popup still shows, in game time: the drift owns the clock, so a pause freezes the
44
+ * popup instead of ageing it while the car is standing still.
45
+ */
46
+ driftPopup: number;
47
+ /** The camera's lens: its reading now, and the widest it has been — the nitro kick, measured. */
48
+ fov: number;
49
+ fovPeak: number;
50
+ /** The engine loop's playback rate: the sound follows the revs where the runtime allows it. */
51
+ engineRate: number;
24
52
  completedLaps: number;
25
53
  elapsed: number;
54
+ /** Best and last completed lap, in seconds; 0 until the first lap is banked. */
55
+ bestLap: number;
56
+ lastLap: number;
57
+ /** The field as ranked this frame, player included: the HUD's live leaderboard. */
58
+ rankings: readonly IRankedRacer[];
26
59
  lastOnRoad: [number, number, number];
27
60
  place: number;
61
+ /** Cars in the race, the player included: the HUD's "P3 / 6". */
62
+ racers: number;
28
63
  position: string;
29
64
  raceStatus: RaceStatus;
30
65
  rescueHeading: number;
@@ -16,7 +16,10 @@
16
16
  --color-danger: #ff6c6c;
17
17
  --color-text: #c2d6df;
18
18
  --color-muted: #6b8c9b;
19
+ --color-cyan: #38d7e7;
19
20
  --font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
21
+ --font-racing: "Arial Narrow", "Roboto Condensed", "Liberation Sans Narrow", "Helvetica Neue",
22
+ sans-serif;
20
23
  }
21
24
 
22
25
  html,
@@ -7,7 +7,13 @@ export interface IRacerProgress {
7
7
  readonly position: Vector3;
8
8
  }
9
9
 
10
- export interface IRankedRacer extends IRacerProgress {
10
+ /**
11
+ * A ranked row is game state, so it holds plain values only: hot reload throws on a class
12
+ * instance, and a `position: Vector3` here reloaded the whole page on every edit.
13
+ */
14
+ export interface IRankedRacer {
15
+ readonly id: string;
16
+ readonly lap: number;
11
17
  readonly place: number;
12
18
  readonly routeProgress: number;
13
19
  }
@@ -15,7 +21,6 @@ export interface IRankedRacer extends IRacerProgress {
15
21
  export interface IRankedRacerScratch {
16
22
  id: string;
17
23
  lap: number;
18
- position: Vector3;
19
24
  place: number;
20
25
  routeProgress: number;
21
26
  }
@@ -58,7 +63,7 @@ export function rankRacers(
58
63
  ): readonly IRankedRacer[] {
59
64
  if (buffer.length > racers.length) buffer.length = racers.length;
60
65
  for (let index = buffer.length; index < racers.length; index += 1) {
61
- buffer.push({ id: "", lap: 0, position: new Vector3(), place: 0, routeProgress: 0 });
66
+ buffer.push({ id: "", lap: 0, place: 0, routeProgress: 0 });
62
67
  }
63
68
  for (let index = 0; index < racers.length; index += 1) {
64
69
  const racer = racers[index];
@@ -67,7 +72,6 @@ export function rankRacers(
67
72
  if (ranked === undefined) throw new Error("Racing ranking buffer slot is missing.");
68
73
  ranked.id = racer.id;
69
74
  ranked.lap = racer.lap;
70
- ranked.position = racer.position;
71
75
  ranked.routeProgress = routeProgress(route, racer.position, racer.lap, target);
72
76
  ranked.place = 0;
73
77
  }