@needle-tools/engine 5.1.0-canary.c111c4f → 5.1.0-canary.d110b1f

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 (88) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/components.needle.json +1 -1
  3. package/dist/{needle-engine.bundle-BuaGvme0.js → needle-engine.bundle-CIeJZJtr.js} +7485 -7511
  4. package/dist/{needle-engine.bundle-CayCdkzK.min.js → needle-engine.bundle-DGxfYUoJ.min.js} +145 -144
  5. package/dist/{needle-engine.bundle-DVhVGqQR.umd.cjs → needle-engine.bundle-FP5jA2Rk.umd.cjs} +144 -143
  6. package/dist/needle-engine.d.ts +58 -83
  7. package/dist/needle-engine.js +188 -186
  8. package/dist/needle-engine.min.js +1 -1
  9. package/dist/needle-engine.umd.cjs +1 -1
  10. package/dist/three-examples.js +3778 -4289
  11. package/dist/three-examples.min.js +14 -301
  12. package/dist/three-examples.umd.cjs +14 -301
  13. package/lib/engine/debug/debug_spatial_console.d.ts +2 -0
  14. package/lib/engine/debug/debug_spatial_console.js +10 -7
  15. package/lib/engine/debug/debug_spatial_console.js.map +1 -1
  16. package/lib/engine/engine_addressables.d.ts +2 -0
  17. package/lib/engine/engine_addressables.js +6 -3
  18. package/lib/engine/engine_addressables.js.map +1 -1
  19. package/lib/engine/engine_context.d.ts +16 -19
  20. package/lib/engine/engine_context.js +12 -15
  21. package/lib/engine/engine_context.js.map +1 -1
  22. package/lib/engine/engine_gameobject.js +2 -2
  23. package/lib/engine/engine_gameobject.js.map +1 -1
  24. package/lib/engine/engine_init.js +10 -0
  25. package/lib/engine/engine_init.js.map +1 -1
  26. package/lib/engine/engine_scenedata.d.ts +5 -7
  27. package/lib/engine/engine_scenedata.js +14 -11
  28. package/lib/engine/engine_scenedata.js.map +1 -1
  29. package/lib/engine/engine_serialization_builtin_serializer.d.ts +10 -16
  30. package/lib/engine/engine_serialization_builtin_serializer.js +28 -41
  31. package/lib/engine/engine_serialization_builtin_serializer.js.map +1 -1
  32. package/lib/engine/webcomponents/jsx.d.ts +51 -0
  33. package/lib/engine/webcomponents/logo-element.js.map +1 -1
  34. package/lib/engine/webcomponents/needle menu/needle-menu.d.ts +2 -3
  35. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  36. package/lib/engine/webcomponents/needle-button.js.map +1 -1
  37. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  38. package/lib/engine/xr/NeedleXRSession.d.ts +2 -0
  39. package/lib/engine/xr/NeedleXRSession.js +47 -11
  40. package/lib/engine/xr/NeedleXRSession.js.map +1 -1
  41. package/lib/engine-components/AnimatorController.d.ts +2 -0
  42. package/lib/engine-components/AnimatorController.js +4 -1
  43. package/lib/engine-components/AnimatorController.js.map +1 -1
  44. package/lib/engine-components/Light.d.ts +0 -19
  45. package/lib/engine-components/Light.js +4 -96
  46. package/lib/engine-components/Light.js.map +1 -1
  47. package/lib/engine-components/Networking.d.ts +1 -1
  48. package/lib/engine-components/Networking.js +1 -1
  49. package/lib/engine-components/ReflectionProbe.js +2 -0
  50. package/lib/engine-components/ReflectionProbe.js.map +1 -1
  51. package/lib/engine-components/postprocessing/VolumeParameter.d.ts +2 -0
  52. package/lib/engine-components/postprocessing/VolumeParameter.js +4 -1
  53. package/lib/engine-components/postprocessing/VolumeParameter.js.map +1 -1
  54. package/lib/engine-components/ui/Canvas.d.ts +1 -1
  55. package/lib/engine-components/ui/Canvas.js +2 -8
  56. package/lib/engine-components/ui/Canvas.js.map +1 -1
  57. package/lib/needle-engine.d.ts +2 -0
  58. package/lib/needle-engine.js +1 -0
  59. package/lib/needle-engine.js.map +1 -1
  60. package/package.json +1 -1
  61. package/plugins/dts-generator/dts.codegen.js +12 -6
  62. package/plugins/dts-generator/dts.writer.js +1 -1
  63. package/plugins/dts-generator/glb.extractor.js +12 -1
  64. package/plugins/dts-generator/glb.reader.js +42 -33
  65. package/plugins/types/userconfig.d.ts +12 -0
  66. package/plugins/vite/dts-generator.d.ts +2 -2
  67. package/plugins/vite/dts-generator.js +6 -1
  68. package/plugins/vite/reload.js +18 -17
  69. package/src/engine/debug/debug_spatial_console.ts +10 -7
  70. package/src/engine/engine_addressables.ts +6 -3
  71. package/src/engine/engine_context.ts +18 -20
  72. package/src/engine/engine_gameobject.ts +2 -2
  73. package/src/engine/engine_init.ts +10 -0
  74. package/src/engine/engine_scenedata.ts +13 -10
  75. package/src/engine/engine_serialization_builtin_serializer.ts +32 -43
  76. package/src/engine/webcomponents/jsx.d.ts +51 -0
  77. package/src/engine/webcomponents/logo-element.ts +1 -0
  78. package/src/engine/webcomponents/needle menu/needle-menu.ts +2 -1
  79. package/src/engine/webcomponents/needle-button.ts +1 -0
  80. package/src/engine/webcomponents/needle-engine.ts +1 -0
  81. package/src/engine/xr/NeedleXRSession.ts +44 -10
  82. package/src/engine-components/AnimatorController.ts +4 -1
  83. package/src/engine-components/Light.ts +4 -95
  84. package/src/engine-components/Networking.ts +1 -1
  85. package/src/engine-components/ReflectionProbe.ts +2 -0
  86. package/src/engine-components/postprocessing/VolumeParameter.ts +4 -1
  87. package/src/engine-components/ui/Canvas.ts +2 -8
  88. package/src/needle-engine.ts +1 -0
@@ -79,10 +79,13 @@ export function parseContentDispositionFilename(header) {
79
79
  const _remoteGlbCache = new Map();
80
80
 
81
81
  /**
82
- * Fetch only the JSON chunk of a remote GLB using two HTTP Range requests.
82
+ * Fetch the JSON chunk of a remote GLB.
83
+ * Tries an initial Range request for the header bytes; if the server already returned
84
+ * enough data (200 + full body, or 206 with sufficient bytes) the JSON chunk is
85
+ * extracted directly. Otherwise a second Range request fetches the JSON chunk.
83
86
  * Uses `Last-Modified` header for caching — avoids re-parsing if unchanged.
84
87
  * Also captures `Content-Disposition` filename for friendly key generation.
85
- * Returns `null` on any network/parse error or if Range is not supported.
88
+ * Returns `null` on any network or parse error.
86
89
  *
87
90
  * @param {string} url
88
91
  * @returns {Promise<{ json: Record<string, unknown>, filename: string | null } | null>}
@@ -106,49 +109,55 @@ export async function readRemoteGlbJsonChunk(url) {
106
109
  return { json: cached.json, filename: cached.filename ?? filename };
107
110
  }
108
111
 
109
- const rangeSupported = headerRes.status === 206;
110
- const headerBytes = Buffer.from(await headerRes.arrayBuffer());
111
- if (headerBytes.length < 20) return null;
112
+ const firstBytes = Buffer.from(await headerRes.arrayBuffer());
113
+ if (firstBytes.length < 20) return null;
112
114
 
113
- const magic = headerBytes.readUInt32LE(0);
114
- const version = headerBytes.readUInt32LE(4);
115
- const chunkLength = headerBytes.readUInt32LE(12);
116
- const chunkType = headerBytes.readUInt32LE(16);
115
+ const magic = firstBytes.readUInt32LE(0);
116
+ const version = firstBytes.readUInt32LE(4);
117
+ const chunkLength = firstBytes.readUInt32LE(12);
118
+ const chunkType = firstBytes.readUInt32LE(16);
117
119
 
118
120
  if (magic !== 0x46546c67 || version !== 2) return null; // not a GLB
119
121
  if (chunkType !== 0x4E4F534A) return null; // chunk0 not JSON
120
122
 
121
- if (!rangeSupported) {
122
- needleLog(PLUGIN, `Remote GLB server does not support Range requests, skipping: ${url}`, "warn");
123
- return null;
124
- }
125
-
126
- const jsonEnd = 20 + chunkLength - 1;
127
- const jsonRes = await fetch(url, { headers: { Range: `bytes=20-${jsonEnd}` } });
128
- if (!jsonRes.ok) {
129
- needleLog(PLUGIN, `Remote GLB JSON chunk fetch failed (${jsonRes.status}): ${url}`, "warn");
130
- return null;
123
+ let jsonBytes;
124
+ let resolvedFilename = filename;
125
+
126
+ if (firstBytes.length >= 20 + chunkLength) {
127
+ // The first response already contained the full JSON chunk (server ignored Range or returned 200).
128
+ jsonBytes = firstBytes.slice(20, 20 + chunkLength);
129
+ } else {
130
+ // Try a second Range request for just the JSON chunk bytes.
131
+ const jsonEnd = 20 + chunkLength - 1;
132
+ const jsonRes = await fetch(url, { headers: { Range: `bytes=20-${jsonEnd}` } });
133
+ if (!jsonRes.ok) {
134
+ needleLog(PLUGIN, `Remote GLB JSON chunk fetch failed (${jsonRes.status}): ${url}`, "warn");
135
+ return null;
136
+ }
137
+ const jsonResBytes = Buffer.from(await jsonRes.arrayBuffer());
138
+ // Server may return 200 + full body even for a Range request — slice out our window.
139
+ if (jsonResBytes.length >= 20 + chunkLength) {
140
+ jsonBytes = jsonResBytes.slice(20, 20 + chunkLength);
141
+ } else if (jsonResBytes.length >= chunkLength) {
142
+ jsonBytes = jsonResBytes.slice(0, chunkLength);
143
+ } else {
144
+ needleLog(PLUGIN, `Remote GLB unexpected response (${jsonRes.status}, ${jsonResBytes.length} bytes, expected ${chunkLength}): ${url}`, "warn");
145
+ return null;
146
+ }
147
+
148
+ const filenameFromJsonRes = parseContentDispositionFilename(jsonRes.headers.get("Content-Disposition"));
149
+ resolvedFilename = filename ?? filenameFromJsonRes;
131
150
  }
132
151
 
133
- let jsonBytes = Buffer.from(await jsonRes.arrayBuffer());
134
- // CDN cold-cache: server returned the full binary instead of just the JSON chunk.
135
- // Extract the JSON slice from it rather than failing.
136
- if (jsonBytes.length > chunkLength + 4) {
137
- jsonBytes = jsonBytes.slice(20, 20 + chunkLength);
138
- }
139
- const json = /** @type {Record<string, unknown>} */ (
140
- JSON.parse(jsonBytes.toString("utf8").replace(/\u0000+$/g, ""))
141
- );
142
- // Cloudflare CDN sometimes omits Content-Disposition on Range requests when the cache is cold.
143
- // Check both Range responses; if still null, do a cheap HEAD request to get the real headers.
144
- const filenameFromJsonRes = parseContentDispositionFilename(jsonRes.headers.get("Content-Disposition"));
145
- let resolvedFilename = filename ?? filenameFromJsonRes;
146
152
  if (resolvedFilename === null) {
147
153
  try {
148
154
  const headRes = await fetch(url, { method: "HEAD" });
149
155
  resolvedFilename = parseContentDispositionFilename(headRes.headers.get("Content-Disposition"));
150
- } catch (_e) { /* ignore — we'll fall back to URL-based name */ }
156
+ } catch (_e) { /* ignore — fall back to URL-based name */ }
151
157
  }
158
+ const json = /** @type {Record<string, unknown>} */ (
159
+ JSON.parse(jsonBytes.toString("utf8").replace(/\u0000+$/g, ""))
160
+ );
152
161
  _remoteGlbCache.set(url, { lastModified, json, filename: resolvedFilename });
153
162
  return { json, filename: resolvedFilename };
154
163
  } catch (e) {
@@ -176,4 +176,16 @@ export type userSettings = {
176
176
 
177
177
  /** Set to true to disable the plugin that ensures VSCode workspace settings for custom-elements.json data */
178
178
  noCustomElementData?: boolean;
179
+
180
+ /**
181
+ * Generate Typescript declaration files for references 3D assets in your project.
182
+ * These will be available via `context.sceneData` in your code.
183
+ * @default enabled
184
+ */
185
+ dts?: {
186
+ /** When set to false, disables the generation of TypeScript declaration files.
187
+ * @default true
188
+ */
189
+ enabled?: boolean;
190
+ }
179
191
  }
@@ -2,6 +2,6 @@
2
2
  * @param {"build" | "serve"} _command Vite command (unused — runs in both modes)
3
3
  * @param {import('../types/needleConfig').needleMeta | null | undefined} _config
4
4
  * @param {import('../types').userSettings} [_userSettings]
5
- * @returns {import('vite').Plugin}
5
+ * @returns {import('vite').Plugin | null}
6
6
  */
7
- export function needleDtsGenerator(_command: "build" | "serve", _config: import("../types/needleConfig").needleMeta | null | undefined, _userSettings?: import("../types").userSettings): import("vite").Plugin;
7
+ export function needleDtsGenerator(_command: "build" | "serve", _config: import("../types/needleConfig").needleMeta | null | undefined, _userSettings?: import("../types").userSettings): import("vite").Plugin | null;
@@ -72,9 +72,14 @@ function ensureVscodeHtmlCustomData(projectRoot, htmlDataPath) {
72
72
  * @param {"build" | "serve"} _command Vite command (unused — runs in both modes)
73
73
  * @param {import('../types/needleConfig').needleMeta | null | undefined} _config
74
74
  * @param {import('../types').userSettings} [_userSettings]
75
- * @returns {import('vite').Plugin}
75
+ * @returns {import('vite').Plugin | null}
76
76
  */
77
77
  export function needleDtsGenerator(_command, _config, _userSettings) {
78
+
79
+ if(_userSettings?.dts?.enabled === false) {
80
+ return null;
81
+ }
82
+
78
83
  let projectRoot = process.cwd();
79
84
 
80
85
  function resolveCodegenDir() {
@@ -7,6 +7,7 @@ import { existsSync, readFileSync, statSync } from 'fs';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { needleLog } from './logging.js';
9
9
 
10
+ const pluginName = "needle-reload";
10
11
  const __filename = fileURLToPath(import.meta.url);
11
12
  const __dirname = path.dirname(__filename);
12
13
 
@@ -39,7 +40,7 @@ export function needleReload(_command, config, userSettings) {
39
40
  const buildDirectory = projectConfig?.buildDirectory?.length ? process.cwd().replaceAll("\\", "/") + "/" + projectConfig?.buildDirectory : "";
40
41
  if (buildDirectory?.length) {
41
42
  const relativeBuildDirectory = path.relative(process.cwd(), buildDirectory).replaceAll("\\", "/") || ".";
42
- setTimeout(() => needleLog("needle-reload", "Build directory: " + relativeBuildDirectory), 100);
43
+ setTimeout(() => needleLog(pluginName, "Build directory: " + relativeBuildDirectory), 100);
43
44
  }
44
45
 
45
46
  // These ignore patterns will be injected into user config to better control vite reloading
@@ -59,7 +60,7 @@ export function needleReload(_command, config, userSettings) {
59
60
  // @ts-ignore - watch.ignored is guaranteed to be string[] by the guards above
60
61
  config.server.watch.ignored.push(pattern);
61
62
  if (userSettings?.debug === true)
62
- setTimeout(() => needleLog("needle-reload", "Updated server ignore patterns: " + JSON.stringify(config.server?.watch?.ignored)), 100);
63
+ setTimeout(() => needleLog(pluginName, "Updated server ignore patterns: " + JSON.stringify(config.server?.watch?.ignored)), 100);
63
64
  },
64
65
  /** @param {import('vite').HmrContext & {buildDirectory?: string}} args */
65
66
  handleHotUpdate(args) {
@@ -118,7 +119,7 @@ function getHot(server) {
118
119
 
119
120
  /** @param {import('vite').ViteDevServer} server @param {string} [file] */
120
121
  function notifyClientWillReload(server, file) {
121
- console.log("Send reload notification");
122
+ needleLog(pluginName, "Send reload notification");
122
123
  getHot(server).send('needle:reload', { type: 'will-reload', file: file });
123
124
  }
124
125
 
@@ -134,7 +135,7 @@ async function handleReload({ file, server, modules: _modules, read, buildDirect
134
135
 
135
136
  // Dont reload the whole server when a file that is using hot reload changes
136
137
  if (filesUsingHotReload.has(file)) {
137
- console.log("File is using hot reload: " + file);
138
+ needleLog(pluginName, "File is using hot reload: " + file);
138
139
  return null;
139
140
  }
140
141
 
@@ -153,7 +154,7 @@ async function handleReload({ file, server, modules: _modules, read, buildDirect
153
154
  // instead of relying on the vite server watch ignore array
154
155
  // we could here also match paths that we know we dont want to track
155
156
  if (ignorePatterns.length > 0 && ignoreRegex.test(file)) {
156
- console.log("Ignore change in file: " + getFileNameLog(file));
157
+ needleLog(pluginName, "Ignore change in file: " + getFileNameLog(file));
157
158
  return [];
158
159
  }
159
160
 
@@ -163,7 +164,7 @@ async function handleReload({ file, server, modules: _modules, read, buildDirect
163
164
  if (buildDirectory?.length) {
164
165
  const dir = path.dirname(file).replaceAll("\\", "/");
165
166
  if (dir.startsWith(buildDirectory)) {
166
- console.log("Ignore change in build directory: " + getFileNameLog(file));
167
+ needleLog(pluginName, "Ignore change in build directory: " + getFileNameLog(file));
167
168
  return [];
168
169
  }
169
170
  }
@@ -178,13 +179,13 @@ async function handleReload({ file, server, modules: _modules, read, buildDirect
178
179
  return [];
179
180
  }
180
181
  if (await testIfFileContentChanged(file, read) === false) {
181
- console.log("File content didnt change: " + getFileNameLog(file));
182
+ needleLog(pluginName, "File content didnt change: " + getFileNameLog(file));
182
183
  return [];
183
184
  }
184
185
  }
185
186
 
186
187
  // these are known file types we export from integrations
187
- const knownExportFileTypes = [ ".glb", ".gltf", ".bin", "exr", ".ktx2", ".mp3", ".ogg", ".mp4", ".webm" ];
188
+ const knownExportFileTypes = [".glb", ".gltf", ".bin", "exr", ".ktx2", ".mp3", ".ogg", ".mp4", ".webm"];
188
189
  if (!knownExportFileTypes.some((type) => file.endsWith(type)))
189
190
  return null;
190
191
 
@@ -208,7 +209,7 @@ async function handleReload({ file, server, modules: _modules, read, buildDirect
208
209
  }
209
210
  }
210
211
 
211
- console.log("> Detected file change: ", getFileNameLog(file) + " (" + ((fileSize / (1024 * 1024)).toFixed(1)) + " MB)");
212
+ needleLog(pluginName, "> Detected file change: " + getFileNameLog(file) + " (" + ((fileSize / (1024 * 1024)).toFixed(1)) + " MB)");
212
213
  notifyClientWillReload(server);
213
214
  scheduleReload(server);
214
215
  return [];
@@ -223,7 +224,7 @@ async function scheduleReload(server, level = 0) {
223
224
  const lockFile = path.join(process.cwd(), lockFileName);
224
225
  if (existsSync(lockFile)) {
225
226
  if (level === 0)
226
- console.log("Lock file exists, waiting for export to finish...");
227
+ needleLog(pluginName, "Lock file exists, waiting for export to finish...");
227
228
  setTimeout(() => scheduleReload(server, level += 1), 300);
228
229
  return;
229
230
  }
@@ -234,13 +235,13 @@ async function scheduleReload(server, level = 0) {
234
235
  if (timeDiff < 1000) {
235
236
  // Sometimes file changes happen immediately after triggering a reload
236
237
  // we dont want to reload again in that case
237
- console.log("Ignoring reload, last reload was too recent", timeDiff);
238
+ needleLog(pluginName, "Ignoring reload, last reload was too recent" + timeDiff + "ms ago");
238
239
  return;
239
240
  }
240
241
 
241
242
  lastReloadTime = Date.now();
242
243
  const readableTime = new Date(lastReloadTime).toLocaleTimeString();
243
- console.log("< Reloading... " + readableTime)
244
+ needleLog(pluginName, "< Reloading... " + readableTime);
244
245
  getHot(server).send({
245
246
  type: 'full-reload',
246
247
  path: '*'
@@ -299,10 +300,10 @@ function removeVersionQueryArgument(content) {
299
300
  function insertScriptRegisterHotReloadCode(src, filePath) {
300
301
 
301
302
  // We only want to inject the hot reload code in the needle-engine root file
302
- if(!filePath.includes("/src/needle-engine.ts")) {
303
+ if (!filePath.includes("/src/needle-engine.ts")) {
303
304
  return src;
304
305
  }
305
- console.log("[Needle HMR] Hot reload is enabled");
306
+ needleLog(pluginName, "[Needle HMR] Hot reload is enabled");
306
307
  // this code let's the engine know that we are in hot reload mode
307
308
  const code = `
308
309
  globalThis.NEEDLE_HOT_RELOAD_ENABLED = true;
@@ -338,12 +339,12 @@ function insertScriptHotReloadCode(src, filePath) {
338
339
  return undefined;
339
340
  // make import path from engine package
340
341
  const fullPathToHotReload = process.cwd() + "/node_modules/@needle-tools/engine/src/engine/engine_hot_reload.ts";
341
- // console.log(fullPathToHotReload);
342
+ // needleLog(pluginName, fullPathToHotReload);
342
343
  const fileDirectory = path.dirname(filePath);
343
- // console.log("DIR", fileDirectory)
344
+ // needleLog(pluginName, "DIR", fileDirectory)
344
345
  const relativePath = path.relative(fileDirectory, fullPathToHotReload);
345
346
  importPath = relativePath.replace(/\\/g, "/");
346
- // console.log("importPath: ", importPath);
347
+ // needleLog(pluginName, "importPath: ", importPath);
347
348
  }
348
349
 
349
350
  // console.log(importPath, ">", filePath);
@@ -12,13 +12,16 @@ import { onError } from "./debug_overlay.js";
12
12
 
13
13
  let _isActive = false;
14
14
 
15
- // enable the spatial console if we receive an error while in dev session and in XR
16
- onError((...args: any[]) => {
17
- if (isDevEnvironment() && ContextRegistry.Current?.isInXR) {
18
- enableSpatialConsole(true);
19
- onLog("error", ...args);
20
- }
21
- })
15
+ /** @internal */
16
+ export function initSpatialConsole() {
17
+ // enable the spatial console if we receive an error while in dev session and in XR
18
+ onError((...args: any[]) => {
19
+ if (isDevEnvironment() && ContextRegistry.Current?.isInXR) {
20
+ enableSpatialConsole(true);
21
+ onLog("error", ...args);
22
+ }
23
+ });
24
+ }
22
25
 
23
26
 
24
27
  /** Enable a spatial debug console that follows the camera */
@@ -567,7 +567,6 @@ class AddressableSerializer extends TypeSerializer {
567
567
  }
568
568
 
569
569
  }
570
- new AddressableSerializer();
571
570
 
572
571
 
573
572
 
@@ -703,7 +702,6 @@ export class ImageReferenceSerializer extends TypeSerializer {
703
702
  return undefined;
704
703
  }
705
704
  }
706
- new ImageReferenceSerializer();
707
705
 
708
706
 
709
707
 
@@ -772,4 +770,9 @@ export class FileReferenceSerializer extends TypeSerializer {
772
770
  return undefined;
773
771
  }
774
772
  }
775
- new FileReferenceSerializer();
773
+ /** @internal */
774
+ export function initAddressableSerializers() {
775
+ new AddressableSerializer();
776
+ new ImageReferenceSerializer();
777
+ new FileReferenceSerializer();
778
+ }
@@ -478,13 +478,14 @@ export class Context implements IContext {
478
478
  * Use `setCurrentCamera` for updating the main camera.
479
479
  */
480
480
  /**
481
- * Typed proxy providing direct access to scene components by node and component name.
482
- * Types are auto-generated from your GLB assets by the `needle:dts-generator` Vite plugin
483
- * and written to `src/generated/needle-bindings.d.ts` on every dev-server start and GLB change.
481
+ * Access your scene's full hierarchy, objects, and components directly by name — with full autocomplete.
482
+ * Types are generated automatically from your GLB files when the dev server starts.
484
483
  *
485
- * Each property access traverses the live scene graph on demand — no caching, always fresh.
486
- * This is a convenience shorthand for `getComponent` lookups; the same result can be
487
- * achieved manually via `scene.getObjectByName(name)` + `getComponent(node, Type)`.
484
+ * You can store references to objects or components for later use.
485
+ * Note that the scene hierarchy can change at runtime (e.g. when objects are added, removed, or re-parented),
486
+ * in which case stored references may become stale.
487
+ *
488
+ * @experimental This API may change in future versions.
488
489
  *
489
490
  * @example
490
491
  * // Toggle auto-rotate on the orbit camera
@@ -493,12 +494,6 @@ export class Context implements IContext {
493
494
  * @example
494
495
  * // Change the background color
495
496
  * ctx.sceneData.Camera.Camera.backgroundColor = new RGBAColor(1, 0, 0, 1);
496
- *
497
- * @example
498
- * // Equivalent manual approach (without sceneData)
499
- * const node = ctx.scene.getObjectByName("Camera");
500
- * const orbit = getComponent(node, OrbitControls);
501
- * if (orbit) orbit.autoRotate = true;
502
497
  */
503
498
  get sceneData(): SceneData {
504
499
  return getSceneData(this);
@@ -543,8 +538,10 @@ export class Context implements IContext {
543
538
  /** @deprecated AssetDatabase is deprecated */
544
539
  assets: AssetDatabase;
545
540
 
546
- /** All registered lights in the scene, maintained by the Light component */
547
- readonly lights: Set<ILight> = new Set();
541
+ /** All registered lights in the scene, maintained by the Light component.
542
+ * @see mainLight for accessing the main directional light in the scene
543
+ */
544
+ readonly lights = new Array<ILight>();
548
545
 
549
546
  /** The brightest registered directional light, or null if none are registered
550
547
  * @see lights
@@ -559,12 +556,13 @@ export class Context implements IContext {
559
556
  }
560
557
 
561
558
  /** @deprecated Use sceneLighting */
562
- get rendererData() { return this.sceneLighting }
559
+ private get rendererData() { return this.sceneLighting }
560
+
563
561
  /** Access the scene lighting manager to control lighting settings in the context */
564
- sceneLighting: SceneLighting;
565
- addressables: Addressables;
566
- lightmaps: ILightDataRegistry;
567
- players: PlayerViewManager;
562
+ readonly sceneLighting: SceneLighting;
563
+ readonly addressables: Addressables;
564
+ readonly lightmaps: ILightDataRegistry;
565
+ readonly players: PlayerViewManager;
568
566
 
569
567
  /** Access the LODs manager to control LOD behavior in the context */
570
568
  readonly lodsManager: LODsManager;
@@ -872,7 +870,7 @@ export class Context implements IContext {
872
870
  this._onBeforeRenderListeners.clear();
873
871
  this._onAfterRenderListeners.clear();
874
872
 
875
- this.lights.clear();
873
+ this.lights.length = 0;
876
874
 
877
875
  if (!this.isManagedExternally) {
878
876
  if (this.renderer) {
@@ -212,8 +212,8 @@ function internalDestroy(instance: Object3D | Component, recursive: boolean = tr
212
212
  if (comp[$isDontDestroy]) return;
213
213
  destroyed_components.push(comp);
214
214
  const go = comp.gameObject;
215
- comp.__internalDisable();
216
- comp.__internalDestroy();
215
+ comp.__internalDisable?.();
216
+ comp.__internalDestroy?.();
217
217
  comp.gameObject = go;
218
218
  return;
219
219
  }
@@ -1,10 +1,14 @@
1
+ import { initAnimatorControllerSerializer } from "../engine-components/AnimatorController.js";
1
2
  import { initAnimationAutoplay } from "../engine-components/AnimationUtilsAutoplay.js";
2
3
  import { initCameraUtils } from "../engine-components/CameraUtils.js";
4
+ import { initVolumeParameterSerializer } from "../engine-components/postprocessing/VolumeParameter.js";
3
5
  import { initSceneSwitcherAttributes } from "../engine-components/SceneSwitcher.js";
4
6
  import { initSkyboxAttributes } from "../engine-components/Skybox.js";
7
+ import { initAddressableSerializers } from "./engine_addressables.js";
5
8
  import { initBuiltinTypes } from "./codegen/register_types.js";
6
9
  import { ensureAudioContextIsResumed } from "./engine_audio.js";
7
10
  import { initNeedleLoader } from "./engine_loaders.js";
11
+ import { initBuiltinSerializers } from "./engine_serialization_builtin_serializer.js";
8
12
  import { initShims } from "./engine_shims.js";
9
13
  import { patchTonemapping } from "./engine_tonemapping.js";
10
14
  import { initCameraExtensions } from "./js-extensions/Camera.js";
@@ -15,6 +19,7 @@ import { SSR } from "./engine_ssr.js";
15
19
  import { initLicense } from "./engine_license.js";
16
20
  import { initWebComponents } from "./webcomponents/init.js";
17
21
  import { initPhysics } from "./engine_physics_rapier.js";
22
+ import { initSpatialConsole } from "./debug/debug_spatial_console.js";
18
23
  import { initXR } from "./xr/init.js";
19
24
 
20
25
  let initialized = false;
@@ -35,6 +40,10 @@ export function initEngine() {
35
40
 
36
41
  initWebComponents();
37
42
  initShims();
43
+ initBuiltinSerializers();
44
+ initAddressableSerializers();
45
+ initAnimatorControllerSerializer();
46
+ initVolumeParameterSerializer();
38
47
  patchTonemapping();
39
48
  patchLayers();
40
49
  initCameraExtensions();
@@ -49,5 +58,6 @@ export function initEngine() {
49
58
  initSceneSwitcherAttributes();
50
59
  initPhysics();
51
60
  initXR();
61
+ initSpatialConsole();
52
62
  initLicense();
53
63
  }
@@ -7,15 +7,13 @@ import { isDevEnvironment } from "./debug/index.js";
7
7
  import { ContextRegistry } from "./engine_context_registry.js";
8
8
 
9
9
  /**
10
- * Global proxy for the primary Needle Engine context.
11
- * Resolves lazily on property access via `ContextRegistry.Current` —
12
- * safe to import at module level, including in SSR environments
13
- * (returns a silent error proxy when no context is active).
10
+ * Quick access to the current Needle Engine context from anywhere — no need to pass `ctx` around.
11
+ * Use it in React/Svelte/Vue components, button handlers, or plain JavaScript.
14
12
  *
15
- * Use this outside of Needle component lifecycle (e.g. in Svelte/React/Vue
16
- * components, button handlers, or vanilla JS) instead of threading `ctx` around.
13
+ * Safe to import at module level, including in SSR environments.
14
+ * For pages with multiple `<needle-engine>` elements, use `ctx` directly instead.
17
15
  *
18
- * For multiple `<needle-engine>` elements on the same page, use `ctx` directly.
16
+ * @experimental This API may change in future releases.
19
17
  *
20
18
  * @example
21
19
  * import { needle } from "@needle-tools/engine";
@@ -29,7 +27,7 @@ export const needle: IContext = new Proxy({} as IContext, {
29
27
  const ctx = ContextRegistry.Current;
30
28
  if (!ctx) {
31
29
  const fn = isDevEnvironment() ? console.error : console.warn;
32
- fn(`[needle] needle.${prop} accessed before scene started`);
30
+ fn(`[needle] needle.${prop} was accessed before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`);
33
31
  return makeErrorProxy(`needle not ready — scene hasn't started yet`);
34
32
  }
35
33
  const val = (ctx as any)[prop];
@@ -39,7 +37,7 @@ export const needle: IContext = new Proxy({} as IContext, {
39
37
  const ctx = ContextRegistry.Current;
40
38
  if (!ctx) {
41
39
  const fn = isDevEnvironment() ? console.error : console.warn;
42
- fn(`[needle] needle.${prop} set before scene started`);
40
+ fn(`[needle] needle.${prop} was set before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`);
43
41
  return true;
44
42
  }
45
43
  (ctx as any)[prop] = value;
@@ -91,9 +89,14 @@ function makeNodeProxy(ctx: IContext, node: import("three").Object3D): object {
91
89
  }
92
90
  });
93
91
  }
92
+ if (prop === "then") return undefined; // not a Promise
94
93
  // Child node lookup by name
95
94
  const child = node.children.find(c => c.name === prop) ?? null;
96
- if (!child) return makeErrorProxy(`Child "${prop}" not found on node "${node.name}"`);
95
+ if (!child) {
96
+ const fn = isDevEnvironment() ? console.error : console.warn;
97
+ fn(`[SceneData] "${prop}" is not a child of "${node.name}". Use .$object to get the Three.js object or .$components.Name to access a component.`);
98
+ return makeErrorProxy(`"${prop}" not found on node "${node.name}"`);
99
+ }
97
100
  return makeNodeProxy(ctx, child);
98
101
  }
99
102
  });