@needle-tools/engine 4.11.5-beta → 4.11.5-next.57306ec

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 (129) hide show
  1. package/CHANGELOG.md +7 -5
  2. package/components.needle.json +1 -1
  3. package/dist/generateMeshBVH.worker-mO20N_b8.js +21 -0
  4. package/dist/{gltf-progressive-GwdQV1Qx.umd.cjs → gltf-progressive-DWcmTMCh.umd.cjs} +1 -1
  5. package/dist/{gltf-progressive-CftVUJy3.min.js → gltf-progressive-DZrY8VT6.min.js} +2 -2
  6. package/dist/{gltf-progressive-BvlZQAkt.js → gltf-progressive-DgYz5BYa.js} +19 -19
  7. package/dist/loader.worker-Dip-PthR.js +23 -0
  8. package/dist/{needle-engine.bundle-CtMdIm9E.umd.cjs → needle-engine.bundle-BJTol1Wh.umd.cjs} +141 -146
  9. package/dist/{needle-engine.bundle-78QepNU6.min.js → needle-engine.bundle-CcBhVcYC.min.js} +147 -152
  10. package/dist/{needle-engine.bundle-DLreKDiJ.js → needle-engine.bundle-D70EAuFo.js} +4837 -4721
  11. package/dist/needle-engine.d.ts +17848 -1
  12. package/dist/needle-engine.js +336 -335
  13. package/dist/needle-engine.min.js +1 -1
  14. package/dist/needle-engine.umd.cjs +1 -1
  15. package/dist/{postprocessing-CJC0Npcd.js → postprocessing-BTW9pD_s.js} +1822 -1723
  16. package/dist/{postprocessing-DrM4PWU3.umd.cjs → postprocessing-CMgoN5t5.umd.cjs} +229 -158
  17. package/dist/{postprocessing-l7zsdO_Q.min.js → postprocessing-DYDtB188.min.js} +227 -156
  18. package/dist/rapier-B3oL1ap-.js +5217 -0
  19. package/dist/rapier-DJ-luMxr.min.js +1 -0
  20. package/dist/rapier-DQltNJbN.umd.cjs +1 -0
  21. package/dist/{three-BDW9I486.min.js → three-B7CT31Bt.min.js} +1 -5
  22. package/dist/{three-MHVqtJYj.js → three-DfMvBzXi.js} +0 -5
  23. package/dist/{three-examples-CgwGHSgz.umd.cjs → three-examples-CsW4_6LI.umd.cjs} +2 -7
  24. package/dist/{three-examples-fvEPSC8L.min.js → three-examples-D1P7eEhn.min.js} +2 -7
  25. package/dist/{three-examples-C5Ht-QFN.js → three-examples-D1SK93ek.js} +1 -7
  26. package/dist/{three-mesh-ui-BjWTTk1R.js → three-mesh-ui-C_uSB5dD.js} +1 -1
  27. package/dist/{three-mesh-ui-Bm32sS2a.umd.cjs → three-mesh-ui-DpATDXwU.umd.cjs} +1 -1
  28. package/dist/{three-mesh-ui-CLdkp21K.min.js → three-mesh-ui-LQ44s0AL.min.js} +1 -1
  29. package/dist/{three-iFaDq9U3.umd.cjs → three-qj71I7J3.umd.cjs} +2 -6
  30. package/dist/{vendor-CsyK1CFs.min.js → vendor-BKGa4GE0.min.js} +34 -39
  31. package/dist/{vendor-petGQl0N.js → vendor-D0zoswDa.js} +1626 -1605
  32. package/dist/{vendor-6kAXU6fm.umd.cjs → vendor-UCpFAwt1.umd.cjs} +30 -35
  33. package/lib/engine/debug/debug_spector.d.ts +16 -0
  34. package/lib/engine/debug/debug_spector.js +28 -0
  35. package/lib/engine/debug/debug_spector.js.map +1 -0
  36. package/lib/engine/engine_application.d.ts +7 -0
  37. package/lib/engine/engine_application.js +8 -1
  38. package/lib/engine/engine_application.js.map +1 -1
  39. package/lib/engine/engine_context.d.ts +15 -5
  40. package/lib/engine/engine_context.js +29 -5
  41. package/lib/engine/engine_context.js.map +1 -1
  42. package/lib/engine/engine_loaders.d.ts +0 -6
  43. package/lib/engine/engine_loaders.js +5 -5
  44. package/lib/engine/engine_loaders.js.map +1 -1
  45. package/lib/engine/engine_physics.js +6 -2
  46. package/lib/engine/engine_physics.js.map +1 -1
  47. package/lib/engine/engine_physics_rapier.d.ts +11 -2
  48. package/lib/engine/engine_physics_rapier.js +9 -0
  49. package/lib/engine/engine_physics_rapier.js.map +1 -1
  50. package/lib/engine/engine_scenelighting.d.ts +12 -1
  51. package/lib/engine/engine_scenelighting.js +21 -1
  52. package/lib/engine/engine_scenelighting.js.map +1 -1
  53. package/lib/engine/engine_texture.d.ts +1 -1
  54. package/lib/engine/engine_tonemapping.d.ts +1 -1
  55. package/lib/engine/engine_types.d.ts +16 -0
  56. package/lib/engine/engine_typestore.d.ts +1 -0
  57. package/lib/engine/engine_typestore.js +5 -6
  58. package/lib/engine/engine_typestore.js.map +1 -1
  59. package/lib/engine/extensions/NEEDLE_lightmaps.js +2 -2
  60. package/lib/engine/extensions/NEEDLE_lightmaps.js.map +1 -1
  61. package/lib/engine/extensions/extensions.d.ts +2 -2
  62. package/lib/engine/extensions/extensions.js +11 -5
  63. package/lib/engine/extensions/extensions.js.map +1 -1
  64. package/lib/engine/webcomponents/needle-engine.attributes.d.ts +1 -0
  65. package/lib/engine/webcomponents/needle-engine.d.ts +1 -0
  66. package/lib/engine/webcomponents/needle-engine.js +3 -0
  67. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  68. package/lib/engine/xr/NeedleXRSession.js +2 -1
  69. package/lib/engine/xr/NeedleXRSession.js.map +1 -1
  70. package/lib/engine-components/Component.d.ts +5 -0
  71. package/lib/engine-components/Component.js +7 -0
  72. package/lib/engine-components/Component.js.map +1 -1
  73. package/lib/engine-components/ReflectionProbe.js +16 -10
  74. package/lib/engine-components/ReflectionProbe.js.map +1 -1
  75. package/lib/engine-components/Renderer.js +2 -2
  76. package/lib/engine-components/Renderer.js.map +1 -1
  77. package/lib/engine-components/RendererInstancing.d.ts +5 -3
  78. package/lib/engine-components/RendererInstancing.js +64 -31
  79. package/lib/engine-components/RendererInstancing.js.map +1 -1
  80. package/lib/engine-components/Skybox.d.ts +15 -5
  81. package/lib/engine-components/Skybox.js +37 -25
  82. package/lib/engine-components/Skybox.js.map +1 -1
  83. package/lib/engine-components/export/usdz/USDZExporter.d.ts +24 -3
  84. package/lib/engine-components/export/usdz/USDZExporter.js +36 -2
  85. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  86. package/lib/engine-components/web/CursorFollow.d.ts +1 -0
  87. package/lib/engine-components/web/CursorFollow.js +2 -0
  88. package/lib/engine-components/web/CursorFollow.js.map +1 -1
  89. package/lib/engine-components/webxr/WebXR.js +4 -0
  90. package/lib/engine-components/webxr/WebXR.js.map +1 -1
  91. package/lib/engine-components/webxr/controllers/XRControllerModel.js +1 -1
  92. package/lib/engine-components/webxr/controllers/XRControllerModel.js.map +1 -1
  93. package/lib/needle-engine.js +2 -1
  94. package/lib/needle-engine.js.map +1 -1
  95. package/package.json +16 -12
  96. package/plugins/types/needleConfig.d.ts +1 -1
  97. package/plugins/types/next.d.ts +1 -1
  98. package/plugins/types/userconfig.d.ts +1 -1
  99. package/src/engine/debug/debug_spector.ts +43 -0
  100. package/src/engine/engine_application.ts +16 -1
  101. package/src/engine/engine_context.ts +41 -7
  102. package/src/engine/engine_loaders.ts +6 -6
  103. package/src/engine/engine_physics.ts +6 -2
  104. package/src/engine/engine_physics_rapier.ts +11 -2
  105. package/src/engine/engine_scenelighting.ts +30 -8
  106. package/src/engine/engine_texture.ts +1 -1
  107. package/src/engine/engine_tonemapping.ts +1 -1
  108. package/src/engine/engine_types.ts +17 -0
  109. package/src/engine/engine_typestore.ts +5 -6
  110. package/src/engine/extensions/NEEDLE_lightmaps.ts +2 -2
  111. package/src/engine/extensions/extensions.ts +11 -5
  112. package/src/engine/webcomponents/needle-engine.attributes.ts +2 -1
  113. package/src/engine/webcomponents/needle-engine.ts +4 -0
  114. package/src/engine/xr/NeedleXRSession.ts +3 -1
  115. package/src/engine-components/Component.ts +9 -1
  116. package/src/engine-components/ReflectionProbe.ts +18 -10
  117. package/src/engine-components/Renderer.ts +2 -2
  118. package/src/engine-components/RendererInstancing.ts +69 -33
  119. package/src/engine-components/Skybox.ts +47 -36
  120. package/src/engine-components/export/usdz/USDZExporter.ts +52 -5
  121. package/src/engine-components/web/CursorFollow.ts +3 -0
  122. package/src/engine-components/webxr/WebXR.ts +4 -0
  123. package/src/engine-components/webxr/controllers/XRControllerModel.ts +1 -1
  124. package/src/needle-engine.ts +4 -2
  125. package/dist/generateMeshBVH.worker-B9bjdr6J.js +0 -25
  126. package/dist/loader.worker-CiTwpNPW.js +0 -27
  127. package/dist/rapier-BqdcSmKY.umd.cjs +0 -1
  128. package/dist/rapier-Cg3w3nFI.min.js +0 -1
  129. package/dist/rapier-sU12SWAs.js +0 -5217
@@ -1,4 +1,4 @@
1
- import { EquirectangularReflectionMapping, LightProbe, SphericalHarmonics3, SRGBColorSpace,Texture, Vector4, WebGLCubeRenderTarget } from "three";
1
+ import { EquirectangularReflectionMapping, LightProbe, Source, SphericalHarmonics3, SRGBColorSpace, Texture, Vector4, WebGLCubeRenderTarget } from "three";
2
2
 
3
3
  import { AssetReference } from "./engine_addressables.js";
4
4
  import { Context } from "./engine_setup.js";
@@ -44,9 +44,16 @@ export class RendererData {
44
44
  this.context.pre_update_callbacks.push(this.preUpdate.bind(this))
45
45
  }
46
46
 
47
+ /**
48
+ * The id of the currently active scene light settings (source identifier).
49
+ */
47
50
  private _currentLightSettingsId?: SourceIdentifier;
48
51
  private _sceneLightSettings?: Map<SourceIdentifier, SceneLightSettings>;
49
52
 
53
+ get currentLightSettingsId(): SourceIdentifier | undefined {
54
+ return this._currentLightSettingsId;
55
+ }
56
+
50
57
  private preUpdate() {
51
58
  const time = this.context.time;
52
59
  this._timevec4.x = time.time;
@@ -82,11 +89,11 @@ export class RendererData {
82
89
 
83
90
  /** set the scene lighting from a specific scene. Will disable any previously enabled lighting settings */
84
91
  enable(sourceId: SourceIdentifier | AssetReference) {
85
- if(sourceId instanceof AssetReference)
92
+ if (sourceId instanceof AssetReference)
86
93
  sourceId = sourceId.url;
87
94
  const settings = this._sceneLightSettings?.get(sourceId);
88
95
  if (!settings) {
89
- if(debug) console.warn("No light settings found for", sourceId);
96
+ if (debug) console.warn("No light settings found for", sourceId);
90
97
  return false;
91
98
  }
92
99
  if (debug) console.log("Enable scene light settings", sourceId, settings);
@@ -100,7 +107,7 @@ export class RendererData {
100
107
 
101
108
  /** disable the lighting of a specific scene, will only have any effect if it is currently active */
102
109
  disable(sourceId: SourceIdentifier | AssetReference) {
103
- if(sourceId instanceof AssetReference)
110
+ if (sourceId instanceof AssetReference)
104
111
  sourceId = sourceId.url;
105
112
  if (sourceId === null || sourceId === undefined) return false;
106
113
  const settings = this._sceneLightSettings?.get(sourceId);
@@ -112,8 +119,22 @@ export class RendererData {
112
119
  return true;
113
120
  }
114
121
 
115
- /** Disables the currently active scene lighting (if any), returns the id of the previously active lighting */
116
- disableCurrent() : SourceIdentifier | null {
122
+ /**
123
+ * Enables the currently active scene lighting (if any), returns the id of the enabled lighting.
124
+ * @returns The id of the enabled lighting, or null if no lighting is currently active.
125
+ */
126
+ enableCurrent(): SourceIdentifier | null {
127
+ if (this._currentLightSettingsId) {
128
+ this.enable(this._currentLightSettingsId);
129
+ return this._currentLightSettingsId ?? null;
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /** Disables the currently active scene lighting (if any), returns the id of the previously active lighting
135
+ * @returns The id of the previously active lighting, or null if no lighting was active.
136
+ */
137
+ disableCurrent(): SourceIdentifier | null {
117
138
  if (this._currentLightSettingsId) {
118
139
  const prev = this._currentLightSettingsId;
119
140
  this.disable(this._currentLightSettingsId);
@@ -162,7 +183,7 @@ export class RendererData {
162
183
  private __currentReflectionId: SourceIdentifier | null = null;
163
184
 
164
185
  /** @internal */
165
- internalEnableReflection(sourceId: SourceIdentifier) : Texture | null {
186
+ internalEnableReflection(sourceId: SourceIdentifier): Texture | null {
166
187
  this.__currentReflectionId = sourceId;
167
188
  const settings = this._sceneLightSettings?.get(sourceId);
168
189
 
@@ -181,6 +202,7 @@ export class RendererData {
181
202
  const tex = existing.Source;
182
203
  tex.mapping = EquirectangularReflectionMapping;
183
204
  scene.environment = tex;
205
+ scene.environmentIntensity = this.environmentIntensity || 1;
184
206
  return tex;
185
207
  }
186
208
  else if (debug) console.warn("Could not find reflection for source", sourceId);
@@ -216,7 +238,7 @@ export class RendererData {
216
238
  /** @internal */
217
239
  internalDisableReflection(sourceId?: SourceIdentifier) {
218
240
  if (sourceId && sourceId !== this.__currentReflectionId) {
219
- if(debug) console.log("Not disabling reflection for", sourceId, "because it is not the current light settings id", this.__currentReflectionId)
241
+ if (debug) console.log("Not disabling reflection for", sourceId, "because it is not the current light settings id", this.__currentReflectionId)
220
242
  return;
221
243
  }
222
244
  if (debug) console.log("Disable reflection", sourceId)
@@ -1,6 +1,6 @@
1
1
  import type { EffectComposer } from "postprocessing";
2
2
  import { Camera, Mesh, Object3D, Texture, WebGLRenderer, WebGLRenderTarget } from "three";
3
- import type { EffectComposer as ThreeEffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
3
+ import type { EffectComposer as ThreeEffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
4
4
 
5
5
  import { findResourceUsers } from "./engine_assetdatabase.js";
6
6
 
@@ -1,7 +1,7 @@
1
1
  import { ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, NoToneMapping, ShaderChunk, ToneMapping } from "three";
2
2
 
3
3
  import { isDevEnvironment } from "./debug/index.js";
4
- import type { Context } from "./engine_setup";
4
+ import type { Context } from "./engine_setup.js";
5
5
 
6
6
  let patchedTonemapping = false;
7
7
  export function patchTonemapping(_ctx?: Context) {
@@ -566,6 +566,23 @@ export interface IPhysicsEngine {
566
566
  */
567
567
  boxOverlap(point: Vector3, size: Vector3, rotation: Vector4Like | null): Array<ShapeOverlapResult>;
568
568
 
569
+ /**
570
+ * Creates a collider in the physics world.
571
+ *
572
+ * @param collider - The collider component.
573
+ * @param desc - The collider description.
574
+ * @returns The created collider.
575
+ *
576
+ * @throws Will throw an error if the physics world is not initialized. Make sure to call `initialize()` before creating colliders.
577
+ *
578
+ * @example
579
+ * ```typescript
580
+ * const boxColliderDesc = NEEDLE_ENGINE_MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(1, 1, 1);
581
+ * const collider = physicsEngine.createCollider(myBoxColliderComponent, boxColliderDesc);
582
+ * ```
583
+ */
584
+ createCollider(collider: ICollider, desc: any): any;
585
+
569
586
  // Collider methods
570
587
  /**
571
588
  * Adds a sphere collider to the physics world
@@ -7,6 +7,7 @@ declare type Type = new (...args: any[]) => any;
7
7
  class _TypeStore {
8
8
 
9
9
  private _types: Map<string, Type> = new Map();
10
+ private _reverseTypes: Map<Type, string> = new Map();
10
11
 
11
12
  constructor() {
12
13
  if (debug) console.warn("TypeStore: Created", this);
@@ -18,8 +19,10 @@ class _TypeStore {
18
19
  public add(key: string, type: Type) {
19
20
  if (debug) console.warn("ADD TYPE", key);
20
21
  const existing = this._types.get(key);
21
- if (!existing)
22
+ if (!existing) {
22
23
  this._types.set(key, type);
24
+ this._reverseTypes.set(type, key);
25
+ }
23
26
  else {
24
27
  if (debug) {
25
28
  if (existing !== type) {
@@ -40,11 +43,7 @@ class _TypeStore {
40
43
  * @returns the key/name for the given type if registered
41
44
  */
42
45
  public getKey(type: Type): string | null {
43
- for (const [key, value] of this._types) {
44
- if (value === type)
45
- return key;
46
- }
47
- return null;
46
+ return this._reverseTypes.get(type) || null;
48
47
  }
49
48
  }
50
49
 
@@ -95,8 +95,8 @@ export class NEEDLE_lightmaps implements GLTFLoaderPlugin {
95
95
  }
96
96
  const results = await PromiseAllWithErrors(dependencies);
97
97
  if (results?.anyFailed) {
98
- if (isDevEnvironment())
99
- console.error("Failed to load lightmap extension", results);
98
+ if (isDevEnvironment() || debug)
99
+ console.error("[NEEDLE_lightmaps]Error during extension loading:", results);
100
100
  }
101
101
  resolve();
102
102
  });
@@ -92,18 +92,24 @@ class PointerResolver {
92
92
  }
93
93
  }
94
94
 
95
- export async function registerExtensions(loader: GLTFLoader, context: Context, url: string) {
95
+ export async function registerExtensions(loader: GLTFLoader, context: Context, url: string, sourceId: SourceIdentifier) {
96
96
 
97
97
  // Make sure to remove any url parameters from the sourceId (because the source id in the renderer does not have a ?v=xxx so it will not be able to register the resolved lightmap otherwise)
98
98
  const idEnd = url.indexOf("?");
99
99
  if (idEnd >= 0) url = url.substring(0, idEnd);
100
+ if (!sourceId) {
101
+ sourceId = url;
102
+ }
103
+ if (sourceId.startsWith("blob:") || sourceId.startsWith("data:")) {
104
+ console.debug("[GLTFLoader] Suspicious sourceId detected");
105
+ }
100
106
 
101
107
  loader.register(p => new NEEDLE_gameobject_data(p));
102
108
  loader.register(p => new NEEDLE_persistent_assets(p));
103
- loader.register(p => new NEEDLE_lightmaps(p, context.lightmaps, url));
104
- loader.register(p => new NEEDLE_lighting_settings(p, url, context));
105
- loader.register(p => new NEEDLE_techniques_webgl(p, url));
106
- loader.register(p => new NEEDLE_render_objects(p, url));
109
+ loader.register(p => new NEEDLE_lightmaps(p, context.lightmaps, sourceId));
110
+ loader.register(p => new NEEDLE_lighting_settings(p, sourceId, context));
111
+ loader.register(p => new NEEDLE_techniques_webgl(p, sourceId));
112
+ loader.register(p => new NEEDLE_render_objects(p, sourceId));
107
113
  loader.register(p => new NEEDLE_progressive(p));
108
114
  loader.register(p => new EXT_texture_exr(p));
109
115
  if (isResourceTrackingEnabled()) loader.register(p => new InternalUsageTrackerPlugin(p))
@@ -47,7 +47,7 @@ type SkyboxAttributes = {
47
47
  /** @deprecated. Use background-image instead - URL to .exr, .hdr, .png, .jpg to be used as skybox */
48
48
  "skybox-image"?: string,
49
49
  /** URL to .exr, .hdr, .png, .jpg to be used as skybox */
50
- "background-image"?: string,
50
+ "background-image"?: string,
51
51
  /** Blurs the background image (if any) - value between 0 and 1
52
52
  * 0: no blur
53
53
  * 1: full blur
@@ -69,6 +69,7 @@ type RenderingAttributes = {
69
69
  "transparent"?: boolean,
70
70
  "contactshadows"?: boolean,
71
71
  "tone-mapping"?: TonemappingAttributeOptions,
72
+ "tonemapping"?: TonemappingAttributeOptions,
72
73
  "tone-mapping-exposure"?: number,
73
74
  }
74
75
 
@@ -296,6 +296,10 @@ export class NeedleEngineWebComponent extends HTMLElement implements INeedleEngi
296
296
  }
297
297
  }
298
298
 
299
+ connectedMoveCallback() {
300
+ // we dont want needle-engine to cleanup JUST because the element is moved in the DOM. See https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks
301
+ }
302
+
299
303
  /**
300
304
  * @internal
301
305
  */
@@ -527,7 +527,9 @@ export class NeedleXRSession implements INeedleXRSession {
527
527
  else
528
528
  console.log("%c" + `Requesting ${mode} session`, "font-weight:bold;");
529
529
  for (const script of scripts) {
530
- if (script.onBeforeXR) script.onBeforeXR(mode, init);
530
+ if (script.onBeforeXR && script.activeAndEnabled && !script.destroyed) {
531
+ script.onBeforeXR(mode, init);
532
+ }
531
533
  }
532
534
  for (const listener of this._sessionRequestStartListeners) {
533
535
  listener({ mode, init });
@@ -11,6 +11,7 @@ import { syncDestroy, syncInstantiate, SyncInstantiateOptions } from "../engine/
11
11
  import { Context, FrameEvent } from "../engine/engine_setup.js";
12
12
  import * as threeutils from "../engine/engine_three_utils.js";
13
13
  import type { Collision, ComponentInit, Constructor, ConstructorConcrete, GuidsMap, ICollider, IComponent, IGameObject, SourceIdentifier } from "../engine/engine_types.js";
14
+ import { TypeStore } from "../engine/engine_typestore.js";
14
15
  import type { INeedleXRSessionEventReceiver, NeedleXRControllerEventArgs, NeedleXREventArgs } from "../engine/engine_xr.js";
15
16
  import { type IPointerEventHandler, PointerEventData } from "./ui/PointerEvents.js";
16
17
 
@@ -540,7 +541,8 @@ export abstract class GameObject extends Object3D implements Object3D, IGameObje
540
541
  }
541
542
  }
542
543
 
543
-
544
+ // DO NOT CHANGE THE SYMBOL NAME
545
+ const $componentName = Symbol("component-name");
544
546
 
545
547
  /**
546
548
  * Needle Engine component's are the main building blocks of the Needle Engine.
@@ -581,6 +583,12 @@ export abstract class Component implements IComponent, EventTarget,
581
583
  */
582
584
  get isComponent(): boolean { return true; }
583
585
 
586
+ /**
587
+ * Get the original component type name before minification (available if the component is registered in the TypeStore)
588
+ */
589
+ get [$componentName]() { return TypeStore.getKey(this.constructor as any) || undefined; }
590
+
591
+
584
592
  private __context: Context | undefined;
585
593
 
586
594
  /**
@@ -1,4 +1,4 @@
1
- import { EquirectangularReflectionMapping, LinearSRGBColorSpace, Material, MeshBasicMaterial, Object3D, SRGBColorSpace, Texture, Vector3 } from "three";
1
+ import { CubeReflectionMapping, CubeTexture, EquirectangularReflectionMapping, LinearSRGBColorSpace, Material, MeshBasicMaterial, Object3D, SRGBColorSpace, Texture, Vector3 } from "three";
2
2
 
3
3
  import { isDevEnvironment, showBalloonWarning } from "../engine/debug/index.js";
4
4
  import { serializable } from "../engine/engine_serialization.js";
@@ -63,13 +63,19 @@ export class ReflectionProbe extends Behaviour {
63
63
 
64
64
  // @serializable(Texture)
65
65
  set texture(tex: Texture) {
66
- if (tex && !(tex instanceof Texture)) {
67
- console.error("ReflectionProbe.texture must be a Texture", tex);
68
- return;
69
- }
66
+
67
+ if (this._texture === tex) return;
70
68
  this._texture = tex;
69
+
70
+ if (debug) console.debug("[ReflectionProbe] Set reflection probe texture " + (tex?.name || "(removed)"));
71
+
71
72
  if (tex) {
72
- tex.mapping = EquirectangularReflectionMapping;
73
+ if (tex instanceof CubeTexture) {
74
+ // cube textures use CubeReflectionMapping by default
75
+ }
76
+ else if (tex.mapping !== EquirectangularReflectionMapping) {
77
+ tex.mapping = EquirectangularReflectionMapping;
78
+ }
73
79
  tex.colorSpace = LinearSRGBColorSpace;
74
80
  tex.needsUpdate = true;
75
81
  }
@@ -110,9 +116,8 @@ export class ReflectionProbe extends Behaviour {
110
116
  }
111
117
  }
112
118
  start(): void {
113
- if (!this._texture && isDevEnvironment()) {
119
+ if (!this._texture) {
114
120
  console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`);
115
- showBalloonWarning("ReflectionProbe configuration hint: See browser console for details")
116
121
  }
117
122
  }
118
123
 
@@ -206,8 +211,11 @@ export class ReflectionProbe extends Behaviour {
206
211
  /** this is the material that we copied and that has the reflection probe */
207
212
  const copy = cached?.copy;
208
213
 
209
- // make sure the reflection probe is assigned
210
- copy["envMap"] = this.texture;
214
+ if ("envMap" in copy) {
215
+ // make sure the reflection probe is assigned
216
+ copy.envMap = this.texture;
217
+ copy.needsUpdate = true;
218
+ }
211
219
 
212
220
  _rend.sharedMaterials[i] = copy;
213
221
  }
@@ -702,7 +702,6 @@ export class Renderer extends Behaviour implements IRenderer {
702
702
  // If the material has a envMap and is NOT using a reflection probe we set the envMap to the scene environment
703
703
  if (mat && "envMap" in mat && "envMapIntensity" in mat && !ReflectionProbe.isUsingReflectionProbe(mat)) {
704
704
  mat.envMap = this.context.scene.environment;
705
- mat.envMapIntensity = this.context.scene.environmentIntensity;
706
705
  mat.envMapRotation = this.context.scene.environmentRotation;
707
706
  }
708
707
  }
@@ -713,8 +712,9 @@ export class Renderer extends Behaviour implements IRenderer {
713
712
  private onBeforeRenderThree = (_renderer, _scene, _camera, _geometry, material, _group) => {
714
713
  if (material.envMapIntensity !== undefined) {
715
714
  const factor = this.hasLightmap ? Math.PI : 1;
716
- const environmentIntensity = this.context.mainCameraComponent?.environmentIntensity ?? 1;
715
+ const environmentIntensity = this.context.scene.environmentIntensity;
717
716
  material.envMapIntensity = Math.max(0, environmentIntensity * this.context.sceneLighting.environmentIntensity / factor);
717
+ // console.log(this.context.sceneLighting.environmentIntensity);
718
718
  }
719
719
  if (this._lightmaps) {
720
720
  for (const lm of this._lightmaps) {
@@ -29,8 +29,9 @@ export class InstancingHandler {
29
29
  * (The instancing mesh renderer will grow x2 if the max instance count is reached)
30
30
  * @default 4
31
31
  * @returns The initial instance count
32
- * */
33
- static getStartInstanceCount = (_obj: Object3D) => {
32
+ */
33
+ // @ts-ignore (ignore the unused parameter warning)
34
+ static getStartInstanceCount = (obj: Object3D) => {
34
35
  return 4;
35
36
  };
36
37
 
@@ -45,20 +46,24 @@ export class InstancingHandler {
45
46
  if (res) {
46
47
  if (handlesArray === null) handlesArray = [];
47
48
  handlesArray.push(res);
48
- // load texture lods
49
- NEEDLE_progressive.assignTextureLOD(res.renderer.material, 0);
50
-
51
- // Load mesh lods
52
- // TODO: technically for multi meshes we do this work multiple times (we search for meshes in children and then use the renderer sharedMeshes... that doesnt make sense)
53
- for (let i = 0; i < renderer.sharedMeshes.length; i++) {
54
- const mesh = renderer.sharedMeshes[i];
55
- const geometry = mesh.geometry;
56
- NEEDLE_progressive.assignMeshLOD(mesh, 0).then(lod => {
57
- if (lod && renderer.activeAndEnabled && geometry != lod) {
58
- res.setGeometry(lod);
59
- }
60
- });
49
+
50
+ // Load LOD for textures
51
+ const mat = res.object.material;
52
+ if(Array.isArray(mat)) {
53
+ mat.forEach(m => NEEDLE_progressive.assignTextureLOD(m, 0));
54
+ }
55
+ else {
56
+ NEEDLE_progressive.assignTextureLOD(mat, 0);
61
57
  }
58
+
59
+ // Load LOD for geometry
60
+ const mesh = res.object;
61
+ const geometry = mesh.geometry;
62
+ NEEDLE_progressive.assignMeshLOD(mesh, 0).then(lod => {
63
+ if (lod && geometry != lod) {
64
+ res.setGeometry(lod);
65
+ }
66
+ });
62
67
  }
63
68
 
64
69
  else if (level <= 0 && obj.type !== "Mesh") {
@@ -349,7 +354,7 @@ class InstancedMeshRenderer {
349
354
  private _context: Context;
350
355
  private _batchedMesh: BatchedMesh;
351
356
  private _handles: (InstanceHandle | null)[] = [];
352
- private readonly _geometryIds: Map<BufferGeometry, number> = new Map();
357
+ private _geometryIds = new WeakMap<BufferGeometry, number>();
353
358
  private _maxInstanceCount: number;
354
359
 
355
360
  private _currentInstanceCount = 0;
@@ -439,6 +444,10 @@ class InstancedMeshRenderer {
439
444
  private _needUpdateBounds: boolean = false;
440
445
  private _debugMaterial: MeshStandardMaterial | null = null;
441
446
 
447
+ private getBatchedMeshName() {
448
+ return this.name ? `${this.name} (BatchedMesh)` : "BatchedMesh";
449
+ }
450
+
442
451
  constructor(name: string, geo: BufferGeometry, material: Material, initialMaxCount: number, context: Context) {
443
452
  this.name = name;
444
453
  this.geometry = geo;
@@ -452,6 +461,7 @@ class InstancedMeshRenderer {
452
461
  this._maxVertexCount = estimate.vertexCount;
453
462
  this._maxIndexCount = estimate.indexCount;
454
463
  this._batchedMesh = new BatchedMesh(this._maxInstanceCount, this._maxVertexCount, this._maxIndexCount, this._debugMaterial ?? this.material);
464
+ this._batchedMesh.name = this.getBatchedMeshName();
455
465
  // this.inst = new InstancedMesh(geo, material, count);
456
466
  this._batchedMesh[$instancingAutoUpdateBounds] = true;
457
467
  // this.inst.count = 0;
@@ -475,7 +485,7 @@ class InstancedMeshRenderer {
475
485
  context.post_render_callbacks.push(this.onAfterRender);
476
486
 
477
487
  if (debugInstancing) {
478
- console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for \"${name}\"`)
488
+ console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for \"${name}\"`)
479
489
  }
480
490
  }
481
491
 
@@ -522,7 +532,8 @@ class InstancedMeshRenderer {
522
532
  return false;
523
533
  }
524
534
 
525
- if (this.mustGrow(geo)) {
535
+ const newInstanceCount = this._currentInstanceCount + 1;
536
+ if (newInstanceCount > this._maxInstanceCount || this.mustGrow(geo)) {
526
537
  if (this.allowResize) {
527
538
  this.grow(geo);
528
539
  }
@@ -644,34 +655,42 @@ class InstancedMeshRenderer {
644
655
  private mustGrow(geo?: BufferGeometry): boolean {
645
656
  if (this.count >= this._maxInstanceCount) return true;
646
657
  if (!geo || !geo.attributes) return false;
658
+
659
+ const isKnownGeometry = this._geometryIds.has(geo);
660
+ if (isKnownGeometry) return false;
661
+
647
662
  const meshInfo = getMeshInformation(geo);
648
663
  const newVertexCount = meshInfo.vertexCount;
649
664
  const newIndexCount = meshInfo.indexCount;
650
665
  return this._currentVertexCount + newVertexCount > this._maxVertexCount || this._currentIndexCount + newIndexCount > this._maxIndexCount;
651
666
  }
652
667
 
668
+ private _growId = 0;
653
669
  private grow(geometry: BufferGeometry) {
670
+ const id = ++this._growId;
654
671
  const growFactor = 2;
655
672
  const newSize = Math.ceil(this._maxInstanceCount * growFactor);
656
673
 
657
674
  // create a new BatchedMesh instance
675
+ // TODO: we should keep track of how many instances for each geometry we have and consider that when estimating new space
658
676
  const estimatedSpace = this.tryEstimateVertexCountSize(newSize, [geometry]);// geometry.attributes.position.count;
659
677
  // const indices = geometry.index ? geometry.index.count : 0;
660
678
  const newMaxVertexCount = Math.max(this._maxVertexCount, estimatedSpace.vertexCount);
661
- const newMaxIndexCount = Math.max(this._maxIndexCount, estimatedSpace.indexCount, Math.ceil(this._maxVertexCount * growFactor));
679
+ const newMaxIndexCount = Math.max(this._maxIndexCount, estimatedSpace.indexCount);//, Math.ceil(this._maxVertexCount * growFactor));
662
680
 
663
681
  if (debugInstancing) {
664
682
  const geometryInfo = getMeshInformation(geometry);
665
- console.warn(`[Instancing] Growing Buffer\nMesh: \"${this.name}${geometry.name?.length ? "/" + geometry.name : ""}\"\n${geometryInfo.vertexCount} vertices, ${geometryInfo.indexCount} indices\nMax count ${this._maxInstanceCount} → ${newSize}\nMax vertex count ${this._maxVertexCount} -> ${newMaxVertexCount}\nMax index count ${this._maxIndexCount} -> ${newMaxIndexCount}`);
683
+ console.warn(`[Instancing] Growing Buffer\nMesh: \"${this.name}${geometry.name?.length ? "/" + geometry.name : ""}\" (${geometryInfo.vertexCount.toLocaleString()} vertices, ${geometryInfo.indexCount.toLocaleString()} indices)\nMax count ${this._maxInstanceCount.toLocaleString()} → ${newSize.toLocaleString()}\nMax vertex count ${this._maxVertexCount.toLocaleString()} -> ${newMaxVertexCount.toLocaleString()}\nMax index count ${this._maxIndexCount.toLocaleString()} -> ${newMaxIndexCount.toLocaleString()}`);
666
684
  this._debugMaterial = createDebugMaterial();
667
685
  }
668
686
  else if (isDevEnvironment()) {
669
- console.debug(`[Instancing] Growing Buffer\nMesh: \"${this.name}${geometry.name?.length ? "/" + geometry.name : ""}\"\nMax count ${this._maxInstanceCount} → ${newSize}\nMax vertex count ${this._maxVertexCount} -> ${newMaxVertexCount}\nMax index count ${this._maxIndexCount} -> ${newMaxIndexCount}`);
687
+ console.debug(`[Instancing] Growing Buffer\nMesh: \"${this.name}${geometry.name?.length ? "/" + geometry.name : ""}\"\nMax count ${this._maxInstanceCount} → ${newSize}\nMax vertex count ${this._maxVertexCount.toLocaleString()} -> ${newMaxVertexCount.toLocaleString()}\nMax index count ${this._maxIndexCount.toLocaleString()} -> ${newMaxIndexCount.toLocaleString()}`);
670
688
  }
671
689
 
672
690
  this._maxVertexCount = newMaxVertexCount;
673
691
  this._maxIndexCount = newMaxIndexCount;
674
692
  const newInst = new BatchedMesh(newSize, this._maxVertexCount, this._maxIndexCount, this._debugMaterial ?? this.material);
693
+ newInst.name = this.getBatchedMeshName();
675
694
  newInst.layers = this._batchedMesh.layers;
676
695
  newInst.castShadow = this._batchedMesh.castShadow;
677
696
  newInst.receiveShadow = this._batchedMesh.receiveShadow;
@@ -686,7 +705,7 @@ class InstancedMeshRenderer {
686
705
  // dispose the old batched mesh
687
706
  this._batchedMesh.dispose();
688
707
  this._batchedMesh.removeFromParent();
689
- this._geometryIds.clear();
708
+ this._geometryIds = new WeakMap<BufferGeometry, number>();
690
709
 
691
710
  this._batchedMesh = newInst;
692
711
  this._maxInstanceCount = newSize;
@@ -698,6 +717,11 @@ class InstancedMeshRenderer {
698
717
  const original = [...this._handles];
699
718
  this._handles = [];
700
719
  for (const handle of original) {
720
+ if (id !== this._growId) {
721
+ // another grow happened in the meantime
722
+ if (debugInstancing) console.warn("[Instancing] Aborting grow since another grow happened in the meantime");
723
+ return;
724
+ }
701
725
  if (handle && handle.__instanceIndex >= 0) {
702
726
  this.addGeometry(handle);
703
727
  this._handles[handle.__instanceIndex] = handle;
@@ -722,23 +746,31 @@ class InstancedMeshRenderer {
722
746
  entry.count += 1;
723
747
  }
724
748
 
749
+ if (_newGeometries && _newGeometries?.length > 0) {
750
+ const index = _newGeometries.indexOf(handle.object.geometry as BufferGeometry);
751
+ if (index !== -1) {
752
+ _newGeometries.splice(index, 1);
753
+ }
754
+ }
725
755
  }
726
756
  }
727
757
 
728
758
  // then calculate the total vertex count
729
759
  let totalVertices = 0;
730
760
  let totalIndices = 0;
761
+ let totalGeometries = 0;
731
762
  // let maxVertices = 0;
732
763
  for (const [_geo, data] of usedGeometries) {
733
- totalVertices += data.vertexCount * data.count;
734
- totalIndices += data.indexCount * data.count;
764
+ totalGeometries += 1;
765
+ totalVertices += data.vertexCount;
766
+ totalIndices += data.indexCount;
735
767
  // maxVertices = Math.max(maxVertices, geo.attributes.position.count * count);
736
768
  }
737
769
  // we calculate the average to make an educated guess of how many vertices will be needed with the new buffer count
738
- const averageVerts = Math.ceil(totalVertices / Math.max(1, this._currentInstanceCount));
739
- let maxVertexCount = averageVerts * newMaxInstances;
740
- const averageIndices = Math.ceil(totalIndices / Math.max(1, this._currentInstanceCount));
741
- let maxIndexCount = averageIndices * newMaxInstances * 2;
770
+ const averageVerts = Math.ceil(totalVertices / Math.max(1, totalGeometries));
771
+ let maxVertexCount = averageVerts * totalGeometries;
772
+ const averageIndices = Math.ceil(totalIndices / Math.max(1, totalGeometries));
773
+ let maxIndexCount = averageIndices * totalGeometries;
742
774
 
743
775
  // if new geometries are provided we *know* that they will be added
744
776
  // so we make sure to include them in the calculation
@@ -753,6 +785,10 @@ class InstancedMeshRenderer {
753
785
  }
754
786
  }
755
787
 
788
+ if (debugInstancing) {
789
+ console.log(`[Instancing] Estimated size for new buffer ${this.name}\nGeometries: ${totalGeometries} (New: ${_newGeometries?.length || 0})\nInstances: ${newMaxInstances}\nEstimated Vertices: ${maxVertexCount.toLocaleString()}\nEstimated Indices: ${maxIndexCount.toLocaleString()}`);
790
+ }
791
+
756
792
  return { vertexCount: maxVertexCount, indexCount: maxIndexCount };
757
793
  }
758
794
 
@@ -770,16 +806,16 @@ class InstancedMeshRenderer {
770
806
  let geometryId = this._geometryIds.get(geo);
771
807
  if (geometryId === undefined || geometryId === null) {
772
808
  if (debugInstancing)
773
- console.debug(`[Instancing] > ADD NEW GEOMETRY \"${handle.name} (${geo.name}; ${geo.uuid})\"\n${this._currentInstanceCount} instances, ${handle.maxVertexCount} max vertices, ${handle.maxIndexCount} max indices`);
809
+ console.warn(`[Instancing] > ADD NEW GEOMETRY \"${handle.name} (${geo.name}; ${geo.uuid})\"\nCurrent Instances: ${this._currentInstanceCount}\nMax Vertices: ${handle.maxVertexCount.toLocaleString()}\nMax Indices: ${handle.maxIndexCount.toLocaleString()}\nMax Triangles: ${(handle.maxIndexCount / 3).toLocaleString()}`);
774
810
 
775
811
  geometryId = this._batchedMesh.addGeometry(geo, handle.maxVertexCount, handle.maxIndexCount);
776
812
  this._geometryIds.set(geo, geometryId);
813
+ this._currentVertexCount += handle.maxVertexCount;
814
+ this._currentIndexCount += handle.maxIndexCount;
777
815
  }
778
816
  else {
779
817
  if (debugInstancing === "verbose") console.log(`[Instancing] > ADD INSTANCE \"${handle.name}\"\nGEOMETRY_ID=${geometryId}\n${this._currentInstanceCount} instances`);
780
818
  }
781
- this._currentVertexCount += handle.maxVertexCount;
782
- this._currentIndexCount += handle.maxIndexCount;
783
819
  const i = this._batchedMesh.addInstance(geometryId);
784
820
  handle.__geometryIndex = geometryId;
785
821
  handle.__instanceIndex = i;
@@ -787,7 +823,7 @@ class InstancedMeshRenderer {
787
823
  handle.__reservedIndexRange = handle.maxIndexCount;
788
824
  this._batchedMesh.setMatrixAt(i, handle.object.matrixWorld);
789
825
  if (debugInstancing)
790
- console.debug(`[Instancing] > ADDED INSTANCE \"${handle.name}\"\nGEOMETRY_ID=${geometryId}\n${this._currentInstanceCount} instances\nIndex: ${handle.__instanceIndex}`);
826
+ console.debug(`[Instancing] > ADDED INSTANCE \"${handle.name}\"\nGEOMETRY_ID=${geometryId}\n${this._currentInstanceCount} instances\nIndex: ${handle.__instanceIndex}\nVertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()},\nIndices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()}`);
791
827
 
792
828
  }
793
829
 
@@ -803,7 +839,7 @@ class InstancedMeshRenderer {
803
839
  // this.inst.deleteGeometry(handle.__instanceIndex);
804
840
  // else
805
841
  // this._batchedMesh.setVisibleAt(handle.__instanceIndex, false);
806
- if(debugInstancing) {
842
+ if (debugInstancing) {
807
843
  console.debug(`[Instancing] < REMOVE INSTANCE \"${handle.name}\" at [${handle.__instanceIndex}]\nGEOMETRY_ID=${handle.__geometryIndex}\n${this._currentInstanceCount} instances\nIndex: ${handle.__instanceIndex}`);
808
844
  }
809
845
  this._batchedMesh.deleteInstance(handle.__instanceIndex);