@umicat/three-sdk 1.3.0 → 1.4.0

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.
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { type Scene3D, type Manifest3D } from './scene3d.js';
2
+ import { type Scene3D, type Manifest3D, type Sky3D } from './scene3d.js';
3
3
  import { type WornMap } from './Attachments.js';
4
4
  export interface LoadSceneOptions {
5
5
  /** Base url assets resolve against (the project's asset host). */
@@ -9,6 +9,10 @@ export interface LoadSceneOptions {
9
9
  rapier?: RapierLike;
10
10
  /** Design view: spawn the authored scene, run no game logic, play no clips. */
11
11
  designMode?: boolean;
12
+ /** Needed only to PREFILTER a sky used for lighting (`Sky3D.lighting`).
13
+ * Optional because `loadScene3D` has never needed a renderer and a
14
+ * required one would break every caller; see `applySky`. */
15
+ renderer?: THREE.WebGLRenderer;
12
16
  }
13
17
  /** The slice of Rapier we use, typed structurally so this module needn't depend on it. */
14
18
  export interface RapierLike {
@@ -75,4 +79,25 @@ export declare function loadModelAsset(manifest: Manifest3D, modelAssetId: strin
75
79
  object: THREE.Object3D;
76
80
  clips: THREE.AnimationClip[];
77
81
  }>;
82
+ /**
83
+ * Paint the sky, and optionally light the scene from it.
84
+ *
85
+ * Three things here are easy to get wrong and silent when you do:
86
+ *
87
+ * 1. **Colour space.** A background texture has to be tagged
88
+ * `SRGBColorSpace`. Leave it linear and the sky comes out washed out —
89
+ * which reads as "the art is bad", not "the flag is wrong".
90
+ * 2. **Mapping.** An equirect image used as a background needs
91
+ * `EquirectangularReflectionMapping`; without it THREE treats it as a flat
92
+ * UV texture and you get a stretched smear.
93
+ * 3. **Prefiltering for lighting.** `scene.environment` wants a PMREM — a
94
+ * mip chain matched to roughness. Assigning the raw texture "works": shiny
95
+ * materials look right and rough ones reflect a sharp, wrong image. We warn
96
+ * rather than silently degrade, because the failure is subtle enough to
97
+ * ship.
98
+ */
99
+ export declare function applySky(scene: THREE.Scene, sky: Sky3D, opts?: {
100
+ assetBase?: string;
101
+ renderer?: THREE.WebGLRenderer;
102
+ }): Promise<THREE.Texture>;
78
103
  export declare function loadScene3D(scene3d: Scene3D, manifest: Manifest3D, opts?: LoadSceneOptions): Promise<LoadedScene3D>;
@@ -85,6 +85,56 @@ export async function loadModelAsset(manifest, modelAssetId, opts = {}) {
85
85
  object.userData.modelAssetId = modelAssetId;
86
86
  return { object, clips: gltf.animations };
87
87
  }
88
+ /**
89
+ * Paint the sky, and optionally light the scene from it.
90
+ *
91
+ * Three things here are easy to get wrong and silent when you do:
92
+ *
93
+ * 1. **Colour space.** A background texture has to be tagged
94
+ * `SRGBColorSpace`. Leave it linear and the sky comes out washed out —
95
+ * which reads as "the art is bad", not "the flag is wrong".
96
+ * 2. **Mapping.** An equirect image used as a background needs
97
+ * `EquirectangularReflectionMapping`; without it THREE treats it as a flat
98
+ * UV texture and you get a stretched smear.
99
+ * 3. **Prefiltering for lighting.** `scene.environment` wants a PMREM — a
100
+ * mip chain matched to roughness. Assigning the raw texture "works": shiny
101
+ * materials look right and rough ones reflect a sharp, wrong image. We warn
102
+ * rather than silently degrade, because the failure is subtle enough to
103
+ * ship.
104
+ */
105
+ export async function applySky(scene, sky, opts = {}) {
106
+ const base = opts.assetBase ?? '';
107
+ let texture;
108
+ if (sky.kind === 'cubemap') {
109
+ if (sky.paths?.length !== 6) {
110
+ throw new Error(`cubemap sky needs exactly 6 faces, got ${sky.paths?.length ?? 0} — use cubeFacesFromNames to order them`);
111
+ }
112
+ texture = await new THREE.CubeTextureLoader().loadAsync(sky.paths.map((p) => base + p));
113
+ }
114
+ else {
115
+ texture = await new THREE.TextureLoader().loadAsync(base + sky.path);
116
+ texture.mapping = THREE.EquirectangularReflectionMapping;
117
+ }
118
+ texture.colorSpace = THREE.SRGBColorSpace;
119
+ scene.background = texture;
120
+ if (sky.lighting) {
121
+ if (opts.renderer) {
122
+ const pmrem = new THREE.PMREMGenerator(opts.renderer);
123
+ scene.environment = pmrem.fromEquirectangular
124
+ ? (sky.kind === 'equirect'
125
+ ? pmrem.fromEquirectangular(texture).texture
126
+ : pmrem.fromCubemap(texture).texture)
127
+ : texture;
128
+ pmrem.dispose();
129
+ }
130
+ else {
131
+ console.warn('[three-sdk] sky lighting requested without a renderer — using the raw texture. '
132
+ + 'Rough materials will reflect a sharp image. Pass `renderer` to loadScene3D to prefilter it.');
133
+ scene.environment = texture;
134
+ }
135
+ }
136
+ return texture;
137
+ }
88
138
  export async function loadScene3D(scene3d, manifest, opts = {}) {
89
139
  const problems = validateScene(scene3d);
90
140
  if (problems.length) {
@@ -93,8 +143,11 @@ export async function loadScene3D(scene3d, manifest, opts = {}) {
93
143
  throw new Error(`scene3d '${scene3d.id}' is invalid:\n - ${problems.join('\n - ')}`);
94
144
  }
95
145
  const scene = new THREE.Scene();
96
- if (scene3d.environment?.background)
97
- scene.background = new THREE.Color(scene3d.environment.background);
146
+ const bg = scene3d.environment?.background;
147
+ if (typeof bg === 'string')
148
+ scene.background = new THREE.Color(bg);
149
+ else if (bg)
150
+ await applySky(scene, bg, opts);
98
151
  if (scene3d.environment?.fog) {
99
152
  const f = scene3d.environment.fog;
100
153
  scene.fog = new THREE.Fog(new THREE.Color(f.color), f.near, f.far);
@@ -983,7 +983,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
983
983
  try {
984
984
  manifest = await fetch('scenes3d/manifest.json').then((r) => r.json());
985
985
  sceneData = await fetch(`scenes3d/${sceneId}.json`).then((r) => r.json());
986
- const loaded = await loadScene3D(sceneData, manifest, { assetBase: '', designMode: true });
986
+ // `renderer` is passed only so a sky used for lighting gets prefiltered
987
+ // here too. Without it the design view would warn on every scene load and
988
+ // show rough materials reflecting a sharp sky — a difference from the game
989
+ // that the author would have to discover by publishing.
990
+ const loaded = await loadScene3D(sceneData, manifest, { assetBase: '', designMode: true, renderer });
987
991
  worn = loaded.attachments;
988
992
  scene = loaded.scene;
989
993
  // Atmospheric fog is a LOOK, and this view's job is to show where things
package/dist/scene3d.d.ts CHANGED
@@ -191,12 +191,56 @@ export interface Light3D {
191
191
  position?: Vec3;
192
192
  castShadow?: boolean;
193
193
  }
194
+ /**
195
+ * The six faces of a cube map, in THREE's `CubeTextureLoader` order:
196
+ * **+X, −X, +Y, −Y, +Z, −Z**.
197
+ *
198
+ * This is NOT the order skybox packs name their files in. The common
199
+ * convention is `rt lf up dn ft bk`, which maps to +X −X +Y −Y +Z −Z — so
200
+ * `ft` (front) is +Z and `bk` is −Z. Hand the array in the wrong order and
201
+ * nothing errors: you get a sky that is inside out, or whose horizon is on
202
+ * the ceiling. Use `cubeFacesFromNames` rather than ordering by hand.
203
+ */
204
+ export type CubeFaces = [string, string, string, string, string, string];
205
+ /**
206
+ * What fills the sky behind the scene.
207
+ *
208
+ * Two kinds, because those are the two a renderer can use directly. A
209
+ * cross-layout sheet (one 4:3 image holding all six faces) is deliberately
210
+ * NOT a kind — slicing it belongs at import time, once, not in every game's
211
+ * first frame. Cross layouts differ between packs (horizontal, vertical,
212
+ * strip) and getting it wrong is silent, so the knowledge lives in one place.
213
+ */
214
+ export type Sky3D = {
215
+ kind: 'equirect';
216
+ /** One 2:1 equirectangular image, resolved against `assetBase`. */
217
+ path: string;
218
+ /** Also light the scene from it (PBR reflections), not just paint the
219
+ * background. Needs `renderer` in the load options to be prefiltered;
220
+ * without one it still works but rough materials reflect badly. */
221
+ lighting?: boolean;
222
+ } | {
223
+ kind: 'cubemap';
224
+ paths: CubeFaces;
225
+ lighting?: boolean;
226
+ };
227
+ /**
228
+ * Order six faces named the way skybox packs name them.
229
+ *
230
+ * Accepts the usual suffixes (`rt/lf/up/dn/ft/bk`, `right/left/...`,
231
+ * `px/nx/py/ny/pz/nz`, `east/west/...`) case-insensitively and returns them
232
+ * in THREE's order. Throws when a face is missing or duplicated, because the
233
+ * alternative is a silently wrong sky.
234
+ */
235
+ export declare function cubeFacesFromNames(paths: string[]): CubeFaces;
194
236
  export interface Scene3D {
195
237
  schemaVersion: 1;
196
238
  id: string;
197
239
  name?: string;
198
240
  environment?: {
199
- background?: string;
241
+ /** A colour (any CSS string) or a sky texture. A bare string stays a
242
+ * colour, so every scene authored before skies keeps working. */
243
+ background?: string | Sky3D;
200
244
  fog?: {
201
245
  color: string;
202
246
  near: number;
package/dist/scene3d.js CHANGED
@@ -23,6 +23,46 @@
23
23
  * - **Colliders are explicit.** Using a render mesh as a dynamic collider is the
24
24
  * classic way to make a game that is correct and unplayably slow.
25
25
  */
26
+ /**
27
+ * Order six faces named the way skybox packs name them.
28
+ *
29
+ * Accepts the usual suffixes (`rt/lf/up/dn/ft/bk`, `right/left/...`,
30
+ * `px/nx/py/ny/pz/nz`, `east/west/...`) case-insensitively and returns them
31
+ * in THREE's order. Throws when a face is missing or duplicated, because the
32
+ * alternative is a silently wrong sky.
33
+ */
34
+ export function cubeFacesFromNames(paths) {
35
+ const ALIASES = {
36
+ px: ['px', 'rt', 'right', 'east', 'posx', 'x+'],
37
+ nx: ['nx', 'lf', 'left', 'west', 'negx', 'x-'],
38
+ py: ['py', 'up', 'top', 'posy', 'y+'],
39
+ ny: ['ny', 'dn', 'down', 'bottom', 'negy', 'y-'],
40
+ pz: ['pz', 'ft', 'front', 'north', 'posz', 'z+'],
41
+ nz: ['nz', 'bk', 'back', 'south', 'negz', 'z-'],
42
+ };
43
+ const found = {};
44
+ for (const p of paths) {
45
+ const stem = p.split('/').pop().replace(/\.[^.]+$/, '').toLowerCase();
46
+ let hit;
47
+ for (const [face, names] of Object.entries(ALIASES)) {
48
+ // Match a whole trailing segment, so `_front` wins and `frontier` does not.
49
+ if (names.some((n) => stem === n || stem.endsWith(`_${n}`) || stem.endsWith(`-${n}`))) {
50
+ hit = face;
51
+ break;
52
+ }
53
+ }
54
+ if (!hit)
55
+ throw new Error(`cube face not recognised from '${p}' — expected a name ending in rt/lf/up/dn/ft/bk (or px/nx/py/ny/pz/nz)`);
56
+ if (found[hit])
57
+ throw new Error(`two files claim the '${hit}' face: '${found[hit]}' and '${p}'`);
58
+ found[hit] = p;
59
+ }
60
+ const order = ['px', 'nx', 'py', 'ny', 'pz', 'nz'];
61
+ const missing = order.filter((f) => !found[f]);
62
+ if (missing.length)
63
+ throw new Error(`cube map is missing ${missing.length} face(s): ${missing.join(', ')}`);
64
+ return order.map((f) => found[f]);
65
+ }
26
66
  /** Identity quaternion, spelled out so callers don't have to remember the order. */
27
67
  export const IDENTITY_QUAT = [0, 0, 0, 1];
28
68
  export function vec3(x = 0, y = 0, z = 0) { return { x, y, z }; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Three.js runtime for Umicat games: the scene3d design format, its loader with physics, a kinematic character controller, and the Umicat platform via @umicat/platform-sdk.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",