@onerjs/addons 8.27.3 → 8.27.5

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.
@@ -2,6 +2,7 @@
2
2
  // MIT License
3
3
  import { MaterialDefines } from "@onerjs/core/Materials/materialDefines.js";
4
4
  import { MaterialPluginBase } from "@onerjs/core/Materials/materialPluginBase.js";
5
+ import { Vector3FromFloatsToRef, Vector3ScaleToRef } from "@onerjs/core/Maths/math.vector.functions.js";
5
6
  class AtmospherePBRMaterialDefines extends MaterialDefines {
6
7
  /**
7
8
  * Constructs the {@link AtmospherePBRMaterialDefines}.
@@ -16,14 +17,21 @@ class AtmospherePBRMaterialDefines extends MaterialDefines {
16
17
  this.USE_AERIAL_PERSPECTIVE_LUT = useAerialPerspectiveLut;
17
18
  }
18
19
  }
19
- const UboArray = [{ name: "inverseViewportSize", size: 2, type: "vec2" }];
20
+ const OriginOffsetUniformName = "originOffsetKm";
21
+ const InverseViewportSizeUniformName = "inverseViewportSize";
22
+ const UboArray = [
23
+ { name: OriginOffsetUniformName, size: 3, type: "vec3" },
24
+ { name: "_atmoPbrPadding1", size: 1, type: "float" },
25
+ { name: InverseViewportSizeUniformName, size: 2, type: "vec2" },
26
+ ];
20
27
  const MakeUniforms = (atmosphere) => ({
21
28
  ubo: UboArray,
22
- fragment: "uniform vec2 inverseViewportSize;\n",
29
+ fragment: `uniform vec2 ${InverseViewportSizeUniformName};\nuniform vec3 ${OriginOffsetUniformName};\n`,
23
30
  externalUniforms: atmosphere.uniformBuffer.getUniformNames(),
24
31
  });
25
32
  const PluginName = "AtmospherePBRMaterialPlugin";
26
33
  const PluginPriority = 600;
34
+ const OriginOffsetKm = { x: 0, y: 0, z: 0 };
27
35
  /**
28
36
  * Adds shading logic to a PBRMaterial that provides radiance, diffuse sky irradiance, and aerial perspective from the atmosphere.
29
37
  */
@@ -106,15 +114,20 @@ export class AtmospherePBRMaterialPlugin extends MaterialPluginBase {
106
114
  */
107
115
  bindForSubMesh(uniformBuffer) {
108
116
  const atmosphere = this._atmosphere;
109
- const engine = atmosphere.scene.getEngine();
117
+ const scene = atmosphere.scene;
118
+ const engine = scene.getEngine();
110
119
  // Bind the atmosphere's uniform buffer to the effect.
111
120
  const effect = uniformBuffer.currentEffect;
112
121
  if (effect) {
113
122
  this._atmosphere.bindUniformBufferToEffect(effect);
114
123
  }
124
+ uniformBuffer.updateVector3(OriginOffsetUniformName, scene.floatingOriginMode
125
+ ? Vector3ScaleToRef(scene.floatingOriginOffset, 0.001, OriginOffsetKm) // Convert to kilometers
126
+ : Vector3FromFloatsToRef(0, atmosphere.physicalProperties.planetRadius, 0, OriginOffsetKm) // planetRadius is already in kilometers
127
+ );
115
128
  const width = engine.getRenderWidth();
116
129
  const height = engine.getRenderHeight();
117
- uniformBuffer.updateFloat2("inverseViewportSize", 1.0 / width, 1.0 / height);
130
+ uniformBuffer.updateFloat2(InverseViewportSizeUniformName, 1.0 / width, 1.0 / height);
118
131
  if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {
119
132
  const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;
120
133
  uniformBuffer.setTexture("aerialPerspectiveLut", aerialPerspectiveLutRenderTarget);
@@ -166,7 +179,7 @@ export class AtmospherePBRMaterialPlugin extends MaterialPluginBase {
166
179
  : `uniform sampler2D transmittanceLut;\r\n${atmosphereImportSnippet}\r\n#include<atmosphereFunctions>`,
167
180
  CUSTOM_LIGHT0_COLOR: `
168
181
  {
169
- vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);
182
+ vec3 positionGlobal = 0.001 * vPositionW + ${OriginOffsetUniformName};
170
183
  float positionRadius = length(positionGlobal);
171
184
  vec3 geocentricNormal = positionGlobal / positionRadius;
172
185
  vec3 directionToLight = ${directionToLightSnippet};
@@ -176,7 +189,7 @@ export class AtmospherePBRMaterialPlugin extends MaterialPluginBase {
176
189
  `,
177
190
  CUSTOM_REFLECTION: `
178
191
  {
179
- vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);
192
+ vec3 positionGlobal = 0.001 * vPositionW + ${OriginOffsetUniformName};
180
193
  float positionRadius = length(positionGlobal);
181
194
  vec3 geocentricNormal = positionGlobal / positionRadius;
182
195
 
@@ -207,14 +220,12 @@ export class AtmospherePBRMaterialPlugin extends MaterialPluginBase {
207
220
  CUSTOM_FRAGMENT_BEFORE_FOG: `
208
221
  #if USE_AERIAL_PERSPECTIVE_LUT
209
222
  {
210
- vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);
211
- float distanceFromCamera = distance(positionGlobal, cameraPositionGlobal);
212
-
223
+ float distanceFromCameraKm = 0.001 * distance(vEyePosition.xyz, vPositionW);
213
224
  vec4 aerialPerspective = vec4(0.);
214
225
  if (sampleAerialPerspectiveLut(
215
- gl_FragCoord.xy * inverseViewportSize,
226
+ gl_FragCoord.xy * ${InverseViewportSizeUniformName},
216
227
  true,
217
- distanceFromCamera,
228
+ distanceFromCameraKm,
218
229
  NumAerialPerspectiveLutLayers,
219
230
  AerialPerspectiveLutKMPerSlice,
220
231
  AerialPerspectiveLutRangeKM,
@@ -1 +1 @@
1
- {"version":3,"file":"atmospherePBRMaterialPlugin.js","sourceRoot":"","sources":["../../../../dev/addons/src/atmosphere/atmospherePBRMaterialPlugin.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,cAAc;AAKd,OAAO,EAAE,eAAe,EAAE,kDAAuC;AACjE,OAAO,EAAE,kBAAkB,EAAE,qDAA0C;AAIvE,MAAM,4BAA6B,SAAQ,eAAe;IAQtD;;;OAGG;IACH,YAAY,uBAAgC;QACxC,KAAK,EAAE,CAAC;QAVZ,gEAAgE;QACzD,uCAAkC,GAAG,KAAK,CAAC;QAClD,gEAAgE;QACzD,2CAAsC,GAAG,KAAK,CAAC;QAQlD,IAAI,CAAC,0BAA0B,GAAG,uBAAuB,CAAC;IAC9D,CAAC;CACJ;AAED,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,IAAI,CAAC,WAAW,CAAC,6BAA6B;gBAC9E,CAAC,CAAC,6HAA6H,uBAAuB,mCAAmC;gBACzL,CAAC,CAAC,0CAA0C,uBAAuB,mCAAmC;YAC9G,mBAAmB,EAAE;;;;;0CAKS,uBAAuB;;;;CAIhE;YACW,iBAAiB,EAAE;;;;;;0CAMW,uBAAuB;;;;;;;;;;;;;;;;;;;;;;CAsBhE;YACW,6EAA6E;YAC7E,0BAA0B,EAAE;;;;;;;;;;;;;;;;;;;CAmBvC;SACQ,CAAC;IACN,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// MIT License\r\n\r\nimport type { Atmosphere } from \"./atmosphere\";\r\nimport type { BaseTexture } from \"core/Materials/Textures/baseTexture\";\r\nimport type { Material } from \"core/Materials/material\";\r\nimport { MaterialDefines } from \"core/Materials/materialDefines\";\r\nimport { MaterialPluginBase } from \"core/Materials/materialPluginBase\";\r\nimport type { Nullable } from \"core/types\";\r\nimport type { UniformBuffer } from \"core/Materials/uniformBuffer\";\r\n\r\nclass AtmospherePBRMaterialDefines extends MaterialDefines {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public USE_AERIAL_PERSPECTIVE_LUT: boolean;\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public APPLY_AERIAL_PERSPECTIVE_INTENSITY = false;\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS = false;\r\n\r\n /**\r\n * Constructs the {@link AtmospherePBRMaterialDefines}.\r\n * @param useAerialPerspectiveLut - Whether to use the aerial perspective LUT.\r\n */\r\n constructor(useAerialPerspectiveLut: boolean) {\r\n super();\r\n this.USE_AERIAL_PERSPECTIVE_LUT = useAerialPerspectiveLut;\r\n }\r\n}\r\n\r\nconst UboArray = [{ name: \"inverseViewportSize\", size: 2, type: \"vec2\" }];\r\nconst MakeUniforms = (atmosphere: Atmosphere) => ({\r\n ubo: UboArray,\r\n fragment: \"uniform vec2 inverseViewportSize;\\n\",\r\n externalUniforms: atmosphere.uniformBuffer.getUniformNames(),\r\n});\r\n\r\nconst PluginName = \"AtmospherePBRMaterialPlugin\";\r\nconst PluginPriority = 600;\r\n\r\n/**\r\n * Adds shading logic to a PBRMaterial that provides radiance, diffuse sky irradiance, and aerial perspective from the atmosphere.\r\n */\r\nexport class AtmospherePBRMaterialPlugin extends MaterialPluginBase {\r\n /**\r\n * Constructs the {@link AtmospherePBRMaterialPlugin}.\r\n * @param material - The material to apply the plugin to.\r\n * @param _atmosphere - The atmosphere to use for shading.\r\n * @param _isAerialPerspectiveEnabled - Whether to apply aerial perspective.\r\n */\r\n constructor(\r\n material: Material,\r\n private readonly _atmosphere: Atmosphere,\r\n private readonly _isAerialPerspectiveEnabled = false\r\n ) {\r\n super(\r\n material,\r\n PluginName,\r\n PluginPriority,\r\n {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n USE_CUSTOM_REFLECTION: _atmosphere.diffuseSkyIrradianceLut !== null,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n CUSTOM_FRAGMENT_BEFORE_FOG: _isAerialPerspectiveEnabled,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n USE_AERIAL_PERSPECTIVE_LUT: _isAerialPerspectiveEnabled && _atmosphere.isAerialPerspectiveLutEnabled,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n APPLY_AERIAL_PERSPECTIVE_INTENSITY: _isAerialPerspectiveEnabled && _atmosphere.aerialPerspectiveIntensity !== 1.0,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS: _isAerialPerspectiveEnabled && _atmosphere.aerialPerspectiveRadianceBias !== 0.0,\r\n },\r\n false, // addPluginToList -- false because we need to control when this is added to the list\r\n true, // enable\r\n true // resolveIncludes\r\n );\r\n\r\n this.doNotSerialize = true;\r\n\r\n // This calls `getCode` so we need to do this after having initialized the class fields.\r\n this._pluginManager._addPlugin(this);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getUniformBuffersNames(_ubos: string[]): void {\r\n const uniformBuffer = this._atmosphere.uniformBuffer;\r\n if (uniformBuffer.useUbo) {\r\n _ubos.push(uniformBuffer.name);\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getUniforms() {\r\n return MakeUniforms(this._atmosphere);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override isReadyForSubMesh(): boolean {\r\n let isReady = true;\r\n const atmosphere = this._atmosphere;\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n isReady = isReady && !!aerialPerspectiveLutRenderTarget?.isReady();\r\n }\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n isReady = isReady && !!transmittanceLutRenderTarget?.isReady();\r\n return isReady;\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getActiveTextures(_activeTextures: BaseTexture[]): void {\r\n const atmosphere = this._atmosphere;\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n if (aerialPerspectiveLutRenderTarget) {\r\n _activeTextures.push(aerialPerspectiveLutRenderTarget);\r\n }\r\n }\r\n\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n if (transmittanceLutRenderTarget) {\r\n _activeTextures.push(transmittanceLutRenderTarget);\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override bindForSubMesh(uniformBuffer: UniformBuffer): void {\r\n const atmosphere = this._atmosphere;\r\n const engine = atmosphere.scene.getEngine();\r\n\r\n // Bind the atmosphere's uniform buffer to the effect.\r\n const effect = uniformBuffer.currentEffect;\r\n if (effect) {\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n }\r\n\r\n const width = engine.getRenderWidth();\r\n const height = engine.getRenderHeight();\r\n uniformBuffer.updateFloat2(\"inverseViewportSize\", 1.0 / width, 1.0 / height);\r\n\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n uniformBuffer.setTexture(\"aerialPerspectiveLut\", aerialPerspectiveLutRenderTarget);\r\n }\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n uniformBuffer.setTexture(\"transmittanceLut\", transmittanceLutRenderTarget);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override prepareDefines(defines: AtmospherePBRMaterialDefines): void {\r\n const lastUseAerialPerspectiveLut = defines.USE_AERIAL_PERSPECTIVE_LUT;\r\n const lastApplyAerialPerspectiveIntensity = defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY;\r\n const lastApplyAerialPerspectiveRadianceBias = defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS;\r\n defines.USE_AERIAL_PERSPECTIVE_LUT = this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled;\r\n defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY = this._isAerialPerspectiveEnabled && this._atmosphere.aerialPerspectiveIntensity !== 1.0;\r\n defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS = this._isAerialPerspectiveEnabled && this._atmosphere.aerialPerspectiveRadianceBias !== 0.0;\r\n if (\r\n lastUseAerialPerspectiveLut !== defines.USE_AERIAL_PERSPECTIVE_LUT ||\r\n lastApplyAerialPerspectiveIntensity !== defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY ||\r\n lastApplyAerialPerspectiveRadianceBias !== defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS\r\n ) {\r\n defines.markAllAsDirty();\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getSamplers(samplers: string[]): void {\r\n samplers.push(\"transmittanceLut\");\r\n if (this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled) {\r\n samplers.push(\"aerialPerspectiveLut\");\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getCustomCode(shaderType: string): Nullable<Record<string, string>> {\r\n // Assumed inputs are light0, vPositionW, normalW.\r\n // Only works for directional lights.\r\n if (shaderType !== \"fragment\") {\r\n return null;\r\n }\r\n\r\n const useUbo = this._atmosphere.scene.getEngine().supportsUniformBuffers;\r\n const directionToLightSnippet = useUbo ? \"-light0.vLightData.xyz\" : \"-vLightData0.xyz\";\r\n\r\n const useAtmosphereUbo = this._atmosphere.uniformBuffer.useUbo;\r\n const atmosphereImportSnippet = useAtmosphereUbo ? \"#include<atmosphereUboDeclaration>\" : \"#include<atmosphereFragmentDeclaration>\";\r\n\r\n return {\r\n CUSTOM_FRAGMENT_DEFINITIONS:\r\n this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled\r\n ? `uniform sampler2D transmittanceLut;\\r\\nprecision highp sampler2DArray;\\r\\nuniform sampler2DArray aerialPerspectiveLut;\\r\\n${atmosphereImportSnippet}\\r\\n#include<atmosphereFunctions>`\r\n : `uniform sampler2D transmittanceLut;\\r\\n${atmosphereImportSnippet}\\r\\n#include<atmosphereFunctions>`,\r\n CUSTOM_LIGHT0_COLOR: `\r\n {\r\n vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);\r\n float positionRadius = length(positionGlobal);\r\n vec3 geocentricNormal = positionGlobal / positionRadius;\r\n vec3 directionToLight = ${directionToLightSnippet};\r\n float cosAngleLightToZenith = dot(directionToLight, geocentricNormal);\r\n diffuse0 = lightIntensity * sampleTransmittanceLut(transmittanceLut, positionRadius, cosAngleLightToZenith);\r\n }\r\n`,\r\n CUSTOM_REFLECTION: `\r\n {\r\n vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);\r\n float positionRadius = length(positionGlobal);\r\n vec3 geocentricNormal = positionGlobal / positionRadius;\r\n\r\n vec3 directionToLight = ${directionToLightSnippet};\r\n float cosAngleLightToZenith = dot(directionToLight, geocentricNormal);\r\n\r\n vec2 uv = vec2(0.5 + 0.5 * cosAngleLightToZenith, (positionRadius - planetRadius) / atmosphereThickness);\r\n float irradianceScaleT = 0.5 * dot(normalW, geocentricNormal) + 0.5;\r\n float irradianceScale = ((-0.6652 * irradianceScaleT) + 1.5927) * irradianceScaleT + 0.1023;\r\n vec3 environmentIrradiance = lightIntensity * sampleReflection(irradianceSampler, uv).rgb;\r\n\r\n // Add a contribution here to estimate indirect lighting.\r\n const float r = 0.2;\r\n float indirect = getLuminance(environmentIrradiance) / max(0.00001, 1. - r);\r\n environmentIrradiance *= irradianceScale;\r\n environmentIrradiance += indirect;\r\n\r\n environmentIrradiance += additionalDiffuseSkyIrradiance;\r\n\r\n const float diffuseBrdf = 1. / PI;\r\n environmentIrradiance *= diffuseBrdf * diffuseSkyIrradianceIntensity;\r\n\r\n reflectionOut.environmentIrradiance = environmentIrradiance;\r\n reflectionOut.environmentRadiance.rgb = reflectionOut.environmentIrradiance;\r\n }\r\n`,\r\n // TODO: Support full ray marching if USE_AERIAL_PERSPECTIVE_LUT is disabled.\r\n CUSTOM_FRAGMENT_BEFORE_FOG: `\r\n #if USE_AERIAL_PERSPECTIVE_LUT\r\n {\r\n vec3 positionGlobal = 0.001 * vPositionW + vec3(0., planetRadius, 0.);\r\n float distanceFromCamera = distance(positionGlobal, cameraPositionGlobal);\r\n\r\n vec4 aerialPerspective = vec4(0.);\r\n if (sampleAerialPerspectiveLut(\r\n gl_FragCoord.xy * inverseViewportSize,\r\n true,\r\n distanceFromCamera,\r\n NumAerialPerspectiveLutLayers,\r\n AerialPerspectiveLutKMPerSlice,\r\n AerialPerspectiveLutRangeKM,\r\n aerialPerspective)) {\r\n finalColor = aerialPerspective + (1. - aerialPerspective.a) * finalColor;\r\n }\r\n }\r\n #endif\r\n`,\r\n };\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"atmospherePBRMaterialPlugin.js","sourceRoot":"","sources":["../../../../dev/addons/src/atmosphere/atmospherePBRMaterialPlugin.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,cAAc;AAKd,OAAO,EAAE,eAAe,EAAE,kDAAuC;AACjE,OAAO,EAAE,kBAAkB,EAAE,qDAA0C;AAGvE,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,oDAAyC;AAE7F,MAAM,4BAA6B,SAAQ,eAAe;IAQtD;;;OAGG;IACH,YAAY,uBAAgC;QACxC,KAAK,EAAE,CAAC;QAVZ,gEAAgE;QACzD,uCAAkC,GAAG,KAAK,CAAC;QAClD,gEAAgE;QACzD,2CAAsC,GAAG,KAAK,CAAC;QAQlD,IAAI,CAAC,0BAA0B,GAAG,uBAAuB,CAAC;IAC9D,CAAC;CACJ;AAED,MAAM,uBAAuB,GAAG,gBAAgB,CAAC;AACjD,MAAM,8BAA8B,GAAG,qBAAqB,CAAC;AAE7D,MAAM,QAAQ,GAAG;IACb,EAAE,IAAI,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;IACxD,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE;IACpD,EAAE,IAAI,EAAE,8BAA8B,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;CAClE,CAAC;AACF,MAAM,YAAY,GAAG,CAAC,UAAsB,EAAE,EAAE,CAAC,CAAC;IAC9C,GAAG,EAAE,QAAQ;IACb,QAAQ,EAAE,gBAAgB,8BAA8B,mBAAmB,uBAAuB,KAAK;IACvG,gBAAgB,EAAE,UAAU,CAAC,aAAa,CAAC,eAAe,EAAE;CAC/D,CAAC,CAAC;AAEH,MAAM,UAAU,GAAG,6BAA6B,CAAC;AAC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oC,CAAC,CAAC,CAAC,yCAAyC,CAAC;QAEpI,OAAO;YACH,2BAA2B,EACvB,IAAI,CAAC,2BAA2B,IAAI,IAAI,CAAC,WAAW,CAAC,6BAA6B;gBAC9E,CAAC,CAAC,6HAA6H,uBAAuB,mCAAmC;gBACzL,CAAC,CAAC,0CAA0C,uBAAuB,mCAAmC;YAC9G,mBAAmB,EAAE;;6DAE4B,uBAAuB;;;0CAG1C,uBAAuB;;;;CAIhE;YACW,iBAAiB,EAAE;;8DAE+B,uBAAuB;;;;0CAI3C,uBAAuB;;;;;;;;;;;;;;;;;;;;;;CAsBhE;YACW,6EAA6E;YAC7E,0BAA0B,EAAE;;;;;;4CAMI,8BAA8B;;;;;;;;;;;CAWzE;SACQ,CAAC;IACN,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// MIT License\r\n\r\nimport type { Atmosphere } from \"./atmosphere\";\r\nimport type { BaseTexture } from \"core/Materials/Textures/baseTexture\";\r\nimport type { Material } from \"core/Materials/material\";\r\nimport { MaterialDefines } from \"core/Materials/materialDefines\";\r\nimport { MaterialPluginBase } from \"core/Materials/materialPluginBase\";\r\nimport type { Nullable } from \"core/types\";\r\nimport type { UniformBuffer } from \"core/Materials/uniformBuffer\";\r\nimport { Vector3FromFloatsToRef, Vector3ScaleToRef } from \"core/Maths/math.vector.functions\";\r\n\r\nclass AtmospherePBRMaterialDefines extends MaterialDefines {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public USE_AERIAL_PERSPECTIVE_LUT: boolean;\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public APPLY_AERIAL_PERSPECTIVE_INTENSITY = false;\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n public APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS = false;\r\n\r\n /**\r\n * Constructs the {@link AtmospherePBRMaterialDefines}.\r\n * @param useAerialPerspectiveLut - Whether to use the aerial perspective LUT.\r\n */\r\n constructor(useAerialPerspectiveLut: boolean) {\r\n super();\r\n this.USE_AERIAL_PERSPECTIVE_LUT = useAerialPerspectiveLut;\r\n }\r\n}\r\n\r\nconst OriginOffsetUniformName = \"originOffsetKm\";\r\nconst InverseViewportSizeUniformName = \"inverseViewportSize\";\r\n\r\nconst UboArray = [\r\n { name: OriginOffsetUniformName, size: 3, type: \"vec3\" },\r\n { name: \"_atmoPbrPadding1\", size: 1, type: \"float\" },\r\n { name: InverseViewportSizeUniformName, size: 2, type: \"vec2\" },\r\n];\r\nconst MakeUniforms = (atmosphere: Atmosphere) => ({\r\n ubo: UboArray,\r\n fragment: `uniform vec2 ${InverseViewportSizeUniformName};\\nuniform vec3 ${OriginOffsetUniformName};\\n`,\r\n externalUniforms: atmosphere.uniformBuffer.getUniformNames(),\r\n});\r\n\r\nconst PluginName = \"AtmospherePBRMaterialPlugin\";\r\nconst PluginPriority = 600;\r\nconst OriginOffsetKm = { x: 0, y: 0, z: 0 };\r\n\r\n/**\r\n * Adds shading logic to a PBRMaterial that provides radiance, diffuse sky irradiance, and aerial perspective from the atmosphere.\r\n */\r\nexport class AtmospherePBRMaterialPlugin extends MaterialPluginBase {\r\n /**\r\n * Constructs the {@link AtmospherePBRMaterialPlugin}.\r\n * @param material - The material to apply the plugin to.\r\n * @param _atmosphere - The atmosphere to use for shading.\r\n * @param _isAerialPerspectiveEnabled - Whether to apply aerial perspective.\r\n */\r\n constructor(\r\n material: Material,\r\n private readonly _atmosphere: Atmosphere,\r\n private readonly _isAerialPerspectiveEnabled = false\r\n ) {\r\n super(\r\n material,\r\n PluginName,\r\n PluginPriority,\r\n {\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n USE_CUSTOM_REFLECTION: _atmosphere.diffuseSkyIrradianceLut !== null,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n CUSTOM_FRAGMENT_BEFORE_FOG: _isAerialPerspectiveEnabled,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n USE_AERIAL_PERSPECTIVE_LUT: _isAerialPerspectiveEnabled && _atmosphere.isAerialPerspectiveLutEnabled,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n APPLY_AERIAL_PERSPECTIVE_INTENSITY: _isAerialPerspectiveEnabled && _atmosphere.aerialPerspectiveIntensity !== 1.0,\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS: _isAerialPerspectiveEnabled && _atmosphere.aerialPerspectiveRadianceBias !== 0.0,\r\n },\r\n false, // addPluginToList -- false because we need to control when this is added to the list\r\n true, // enable\r\n true // resolveIncludes\r\n );\r\n\r\n this.doNotSerialize = true;\r\n\r\n // This calls `getCode` so we need to do this after having initialized the class fields.\r\n this._pluginManager._addPlugin(this);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getUniformBuffersNames(_ubos: string[]): void {\r\n const uniformBuffer = this._atmosphere.uniformBuffer;\r\n if (uniformBuffer.useUbo) {\r\n _ubos.push(uniformBuffer.name);\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getUniforms() {\r\n return MakeUniforms(this._atmosphere);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override isReadyForSubMesh(): boolean {\r\n let isReady = true;\r\n const atmosphere = this._atmosphere;\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n isReady = isReady && !!aerialPerspectiveLutRenderTarget?.isReady();\r\n }\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n isReady = isReady && !!transmittanceLutRenderTarget?.isReady();\r\n return isReady;\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getActiveTextures(_activeTextures: BaseTexture[]): void {\r\n const atmosphere = this._atmosphere;\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n if (aerialPerspectiveLutRenderTarget) {\r\n _activeTextures.push(aerialPerspectiveLutRenderTarget);\r\n }\r\n }\r\n\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n if (transmittanceLutRenderTarget) {\r\n _activeTextures.push(transmittanceLutRenderTarget);\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override bindForSubMesh(uniformBuffer: UniformBuffer): void {\r\n const atmosphere = this._atmosphere;\r\n const scene = atmosphere.scene;\r\n const engine = scene.getEngine();\r\n\r\n // Bind the atmosphere's uniform buffer to the effect.\r\n const effect = uniformBuffer.currentEffect;\r\n if (effect) {\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n }\r\n\r\n uniformBuffer.updateVector3(\r\n OriginOffsetUniformName,\r\n scene.floatingOriginMode\r\n ? Vector3ScaleToRef(scene.floatingOriginOffset, 0.001, OriginOffsetKm) // Convert to kilometers\r\n : Vector3FromFloatsToRef(0, atmosphere.physicalProperties.planetRadius, 0, OriginOffsetKm) // planetRadius is already in kilometers\r\n );\r\n\r\n const width = engine.getRenderWidth();\r\n const height = engine.getRenderHeight();\r\n uniformBuffer.updateFloat2(InverseViewportSizeUniformName, 1.0 / width, 1.0 / height);\r\n\r\n if (this._isAerialPerspectiveEnabled && atmosphere.isAerialPerspectiveLutEnabled) {\r\n const aerialPerspectiveLutRenderTarget = atmosphere.aerialPerspectiveLutRenderTarget;\r\n uniformBuffer.setTexture(\"aerialPerspectiveLut\", aerialPerspectiveLutRenderTarget);\r\n }\r\n const transmittanceLutRenderTarget = atmosphere.transmittanceLut?.renderTarget ?? null;\r\n uniformBuffer.setTexture(\"transmittanceLut\", transmittanceLutRenderTarget);\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override prepareDefines(defines: AtmospherePBRMaterialDefines): void {\r\n const lastUseAerialPerspectiveLut = defines.USE_AERIAL_PERSPECTIVE_LUT;\r\n const lastApplyAerialPerspectiveIntensity = defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY;\r\n const lastApplyAerialPerspectiveRadianceBias = defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS;\r\n defines.USE_AERIAL_PERSPECTIVE_LUT = this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled;\r\n defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY = this._isAerialPerspectiveEnabled && this._atmosphere.aerialPerspectiveIntensity !== 1.0;\r\n defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS = this._isAerialPerspectiveEnabled && this._atmosphere.aerialPerspectiveRadianceBias !== 0.0;\r\n if (\r\n lastUseAerialPerspectiveLut !== defines.USE_AERIAL_PERSPECTIVE_LUT ||\r\n lastApplyAerialPerspectiveIntensity !== defines.APPLY_AERIAL_PERSPECTIVE_INTENSITY ||\r\n lastApplyAerialPerspectiveRadianceBias !== defines.APPLY_AERIAL_PERSPECTIVE_RADIANCE_BIAS\r\n ) {\r\n defines.markAllAsDirty();\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getSamplers(samplers: string[]): void {\r\n samplers.push(\"transmittanceLut\");\r\n if (this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled) {\r\n samplers.push(\"aerialPerspectiveLut\");\r\n }\r\n }\r\n\r\n /**\r\n * @override\r\n */\r\n public override getCustomCode(shaderType: string): Nullable<Record<string, string>> {\r\n // Assumed inputs are light0, vPositionW, normalW.\r\n // Only works for directional lights.\r\n if (shaderType !== \"fragment\") {\r\n return null;\r\n }\r\n\r\n const useUbo = this._atmosphere.scene.getEngine().supportsUniformBuffers;\r\n const directionToLightSnippet = useUbo ? \"-light0.vLightData.xyz\" : \"-vLightData0.xyz\";\r\n\r\n const useAtmosphereUbo = this._atmosphere.uniformBuffer.useUbo;\r\n const atmosphereImportSnippet = useAtmosphereUbo ? \"#include<atmosphereUboDeclaration>\" : \"#include<atmosphereFragmentDeclaration>\";\r\n\r\n return {\r\n CUSTOM_FRAGMENT_DEFINITIONS:\r\n this._isAerialPerspectiveEnabled && this._atmosphere.isAerialPerspectiveLutEnabled\r\n ? `uniform sampler2D transmittanceLut;\\r\\nprecision highp sampler2DArray;\\r\\nuniform sampler2DArray aerialPerspectiveLut;\\r\\n${atmosphereImportSnippet}\\r\\n#include<atmosphereFunctions>`\r\n : `uniform sampler2D transmittanceLut;\\r\\n${atmosphereImportSnippet}\\r\\n#include<atmosphereFunctions>`,\r\n CUSTOM_LIGHT0_COLOR: `\r\n {\r\n vec3 positionGlobal = 0.001 * vPositionW + ${OriginOffsetUniformName};\r\n float positionRadius = length(positionGlobal);\r\n vec3 geocentricNormal = positionGlobal / positionRadius;\r\n vec3 directionToLight = ${directionToLightSnippet};\r\n float cosAngleLightToZenith = dot(directionToLight, geocentricNormal);\r\n diffuse0 = lightIntensity * sampleTransmittanceLut(transmittanceLut, positionRadius, cosAngleLightToZenith);\r\n }\r\n`,\r\n CUSTOM_REFLECTION: `\r\n {\r\n vec3 positionGlobal = 0.001 * vPositionW + ${OriginOffsetUniformName};\r\n float positionRadius = length(positionGlobal);\r\n vec3 geocentricNormal = positionGlobal / positionRadius;\r\n\r\n vec3 directionToLight = ${directionToLightSnippet};\r\n float cosAngleLightToZenith = dot(directionToLight, geocentricNormal);\r\n\r\n vec2 uv = vec2(0.5 + 0.5 * cosAngleLightToZenith, (positionRadius - planetRadius) / atmosphereThickness);\r\n float irradianceScaleT = 0.5 * dot(normalW, geocentricNormal) + 0.5;\r\n float irradianceScale = ((-0.6652 * irradianceScaleT) + 1.5927) * irradianceScaleT + 0.1023;\r\n vec3 environmentIrradiance = lightIntensity * sampleReflection(irradianceSampler, uv).rgb;\r\n\r\n // Add a contribution here to estimate indirect lighting.\r\n const float r = 0.2;\r\n float indirect = getLuminance(environmentIrradiance) / max(0.00001, 1. - r);\r\n environmentIrradiance *= irradianceScale;\r\n environmentIrradiance += indirect;\r\n\r\n environmentIrradiance += additionalDiffuseSkyIrradiance;\r\n\r\n const float diffuseBrdf = 1. / PI;\r\n environmentIrradiance *= diffuseBrdf * diffuseSkyIrradianceIntensity;\r\n\r\n reflectionOut.environmentIrradiance = environmentIrradiance;\r\n reflectionOut.environmentRadiance.rgb = reflectionOut.environmentIrradiance;\r\n }\r\n`,\r\n // TODO: Support full ray marching if USE_AERIAL_PERSPECTIVE_LUT is disabled.\r\n CUSTOM_FRAGMENT_BEFORE_FOG: `\r\n #if USE_AERIAL_PERSPECTIVE_LUT\r\n {\r\n float distanceFromCameraKm = 0.001 * distance(vEyePosition.xyz, vPositionW);\r\n vec4 aerialPerspective = vec4(0.);\r\n if (sampleAerialPerspectiveLut(\r\n gl_FragCoord.xy * ${InverseViewportSizeUniformName},\r\n true,\r\n distanceFromCameraKm,\r\n NumAerialPerspectiveLutLayers,\r\n AerialPerspectiveLutKMPerSlice,\r\n AerialPerspectiveLutRangeKM,\r\n aerialPerspective)) {\r\n finalColor = aerialPerspective + (1. - aerialPerspective.a) * finalColor;\r\n }\r\n }\r\n #endif\r\n`,\r\n };\r\n }\r\n}\r\n"]}
@@ -68,9 +68,11 @@ export class DiffuseSkyIrradianceLut {
68
68
  const scene = atmosphere.scene;
69
69
  const engine = scene.getEngine();
70
70
  const name = "atmo-diffuseSkyIrradiance";
71
+ const caps = engine.getCaps();
72
+ const textureType = caps.textureHalfFloatRender ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE;
71
73
  const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {
72
74
  generateMipMaps: false,
73
- type: Constants.TEXTURETYPE_HALF_FLOAT,
75
+ type: textureType,
74
76
  samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,
75
77
  generateDepthBuffer: false,
76
78
  gammaSpace: false,
@@ -1 +1 @@
1
- {"version":3,"file":"diffuseSkyIrradianceLut.js","sourceRoot":"","sources":["../../../../d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I,CAAC,aAAa,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC5C,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;QACjC,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,CAAC;QAChC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC5B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC5B,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// MIT License\r\n\r\nimport type { Atmosphere } from \"./atmosphere\";\r\nimport type { AtmospherePhysicalProperties } from \"./atmospherePhysicalProperties\";\r\nimport { Clamp } from \"core/Maths/math.scalar.functions\";\r\nimport { Constants } from \"core/Engines/constants\";\r\nimport { EffectRenderer, EffectWrapper } from \"core/Materials/effectRenderer\";\r\nimport { FromHalfFloat } from \"core/Misc/textureTools\";\r\nimport type { IColor3Like, IColor4Like, IVector2Like, IVector3Like } from \"core/Maths/math.like\";\r\nimport type { Nullable } from \"core/types\";\r\nimport { RenderTargetTexture } from \"core/Materials/Textures/renderTargetTexture\";\r\nimport { Sample2DRgbaToRef } from \"./sampling\";\r\nimport \"./Shaders/diffuseSkyIrradiance.fragment\";\r\nimport \"./Shaders/fullscreenTriangle.vertex\";\r\n\r\nconst RaySamples = 128;\r\nconst LutWidthPx = 64;\r\nconst LutHeightPx = 16;\r\nconst HalfTexelSize = { x: 0.5 / LutWidthPx, y: 0.5 / LutHeightPx };\r\nconst UnitToUVScale = { x: (LutWidthPx - 1.0) / LutWidthPx, y: (LutHeightPx - 1.0) / LutHeightPx };\r\nconst UvTemp = { x: Number.NaN, y: Number.NaN };\r\nconst Color4Temp = { r: Number.NaN, g: Number.NaN, b: Number.NaN, a: Number.NaN } as IColor4Like;\r\n\r\nconst ComputeLutUVToRef = (properties: AtmospherePhysicalProperties, radius: number, cosAngleLightToZenith: number, result: IVector2Like): void => {\r\n const unitX = Clamp(0.5 + 0.5 * cosAngleLightToZenith);\r\n const unitY = Clamp((radius - properties.planetRadius) / properties.atmosphereThickness);\r\n result.x = unitX * UnitToUVScale.x + HalfTexelSize.x;\r\n result.y = unitY * UnitToUVScale.y + HalfTexelSize.y;\r\n};\r\n\r\n/**\r\n * The diffuse sky irradiance LUT is used to query the diffuse irradiance at a specified position.\r\n */\r\nexport class DiffuseSkyIrradianceLut {\r\n private readonly _atmosphere: Atmosphere;\r\n private _renderTarget: Nullable<RenderTargetTexture> = null;\r\n private _effectWrapper: Nullable<EffectWrapper> = null;\r\n private _effectRenderer: Nullable<EffectRenderer> = null;\r\n private _isDirty = true;\r\n private _isDisposed = false;\r\n private _lutData: Uint8Array | Uint16Array = new Uint16Array(0);\r\n\r\n /**\r\n * True if the LUT needs to be rendered.\r\n */\r\n public get isDirty() {\r\n return this._isDirty;\r\n }\r\n\r\n /**\r\n * True if the LUT has been disposed.\r\n */\r\n public get isDisposed(): boolean {\r\n return this._isDisposed;\r\n }\r\n\r\n /**\r\n * The render target used for this LUT.\r\n * @throws if the LUT has been disposed.\r\n */\r\n public get renderTarget(): RenderTargetTexture {\r\n if (this._isDisposed || this._renderTarget === null) {\r\n throw new Error();\r\n }\r\n return this._renderTarget;\r\n }\r\n\r\n /**\r\n * True if the LUT data has been read back from the GPU.\r\n */\r\n public get hasLutData(): boolean {\r\n return this._lutData[0] !== undefined;\r\n }\r\n\r\n /**\r\n * Constructs the {@link DiffuseSkyIrradianceLut}.\r\n * @param atmosphere - The atmosphere to use.\r\n */\r\n constructor(atmosphere: Atmosphere) {\r\n this._atmosphere = atmosphere;\r\n const scene = atmosphere.scene;\r\n const engine = scene.getEngine();\r\n\r\n const name = \"atmo-diffuseSkyIrradiance\";\r\n const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {\r\n generateMipMaps: false,\r\n type: Constants.TEXTURETYPE_HALF_FLOAT,\r\n samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,\r\n generateDepthBuffer: false,\r\n gammaSpace: false,\r\n }));\r\n renderTarget.wrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.wrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.anisotropicFilteringLevel = 1;\r\n renderTarget.skipInitialClear = true;\r\n\r\n const useUbo = atmosphere.uniformBuffer.useUbo;\r\n\r\n this._effectWrapper = new EffectWrapper({\r\n engine,\r\n name,\r\n vertexShader: \"fullscreenTriangle\",\r\n fragmentShader: \"diffuseSkyIrradiance\",\r\n attributeNames: [\"position\"],\r\n uniformNames: [\"depth\", ...(useUbo ? [] : atmosphere.uniformBuffer.getUniformNames())],\r\n uniformBuffers: useUbo ? [atmosphere.uniformBuffer.name] : [],\r\n defines: [\r\n \"#define POSITION_VEC2\",\r\n `#define NUM_SAMPLES ${RaySamples}u`,\r\n \"#define CUSTOM_IRRADIANCE_FILTERING_INPUT /* empty */\", // empty, no input texture needed as the radiance is procedurally generated from ray marching.\r\n // The following ray marches the atmosphere to get the radiance.\r\n \"#define CUSTOM_IRRADIANCE_FILTERING_FUNCTION vec3 c = integrateForIrradiance(n, Ls, vec3(0., filteringInfo.x, 0.));\",\r\n ],\r\n samplers: [\"transmittanceLut\", \"multiScatteringLut\"],\r\n useShaderStore: true,\r\n });\r\n\r\n this._effectRenderer = new EffectRenderer(engine, {\r\n // Full screen triangle.\r\n indices: [0, 2, 1],\r\n positions: [-1, -1, -1, 3, 3, -1],\r\n });\r\n\r\n // The sky irradiance will also be used for the environment texture.\r\n scene.environmentTexture = renderTarget;\r\n scene.environmentTexture.irradianceTexture = renderTarget;\r\n scene.environmentIntensity = 1.0;\r\n\r\n // Prevent the irradiance LUT from being rendered redundantly at the beginning of the frame.\r\n scene.environmentTexture.isRenderTarget = false;\r\n }\r\n\r\n /**\r\n * Gets the diffuse sky irradiance for a surface oriented along the geocentric normal.\r\n * Resulting color is always in linear space.\r\n * @param directionToLight - The direction to the light in world space.\r\n * @param radius - The position's distance to the planet origin.\r\n * @param cameraGeocentricNormal - The geocentric normal of the camera.\r\n * @param lightIrradiance - The irradiance of the light.\r\n * @param result - The color to store the result in.\r\n * @returns The result color.\r\n */\r\n public getDiffuseSkyIrradianceToRef<T extends IColor3Like>(\r\n directionToLight: IVector3Like,\r\n radius: number,\r\n cameraGeocentricNormal: IVector3Like,\r\n lightIrradiance: number,\r\n result: T\r\n ): T {\r\n const atmosphere = this._atmosphere;\r\n const additionalDiffuseSkyIrradiance = atmosphere.additionalDiffuseSkyIrradiance;\r\n\r\n const properties = atmosphere.physicalProperties;\r\n if (this._lutData[0] === undefined || radius > properties.atmosphereRadius) {\r\n result.r = additionalDiffuseSkyIrradiance.r;\r\n result.g = additionalDiffuseSkyIrradiance.g;\r\n result.b = additionalDiffuseSkyIrradiance.b;\r\n return result;\r\n }\r\n\r\n const cosAngleLightToZenith = directionToLight.x * cameraGeocentricNormal.x + directionToLight.y * cameraGeocentricNormal.y + directionToLight.z * cameraGeocentricNormal.z;\r\n ComputeLutUVToRef(properties, radius, cosAngleLightToZenith, UvTemp);\r\n Sample2DRgbaToRef(UvTemp.x, UvTemp.y, LutWidthPx, LutHeightPx, this._lutData, Color4Temp, FromHalfFloat);\r\n\r\n const intensity = atmosphere.diffuseSkyIrradianceIntensity;\r\n result.r = intensity * (lightIrradiance * Color4Temp.r + additionalDiffuseSkyIrradiance.r);\r\n result.g = intensity * (lightIrradiance * Color4Temp.g + additionalDiffuseSkyIrradiance.g);\r\n result.b = intensity * (lightIrradiance * Color4Temp.b + additionalDiffuseSkyIrradiance.b);\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Renders the LUT.\r\n * @returns True if the LUT was rendered.\r\n */\r\n public render(): boolean {\r\n // Only need to render the LUT once.\r\n const effectWrapper = this._effectWrapper;\r\n if (!this._isDirty || !effectWrapper?.isReady() || !this._renderTarget?.isReady()) {\r\n return false;\r\n }\r\n\r\n const engine = this._atmosphere.scene.getEngine();\r\n\r\n engine.bindFramebuffer(this.renderTarget.renderTarget!, undefined, undefined, undefined, true);\r\n\r\n const effectRenderer = this._effectRenderer!;\r\n effectRenderer.applyEffectWrapper(effectWrapper);\r\n\r\n effectRenderer.saveStates();\r\n effectRenderer.setViewport();\r\n\r\n const effect = effectWrapper.effect;\r\n effectRenderer.bindBuffers(effect);\r\n\r\n effect.setTexture(\"transmittanceLut\", this._atmosphere.transmittanceLut!.renderTarget);\r\n effect.setTexture(\"multiScatteringLut\", this._atmosphere.multiScatteringLutRenderTarget);\r\n\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n\r\n effect.setFloat(\"depth\", 0.0);\r\n\r\n effectRenderer.draw();\r\n\r\n effectRenderer.restoreStates();\r\n engine.restoreDefaultFramebuffer();\r\n\r\n this._isDirty = false;\r\n\r\n // eslint-disable-next-line github/no-then\r\n void this.renderTarget.readPixels(0, 0, undefined, undefined, true /* noDataConversion */)?.then((value: ArrayBufferView) => {\r\n if (this._isDisposed) {\r\n return;\r\n }\r\n this._lutData = value as Uint8Array | Uint16Array;\r\n });\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Marks the LUT as needing to be rendered.\r\n */\r\n public markDirty(): void {\r\n this._isDirty = true;\r\n }\r\n\r\n /**\r\n * Disposes the LUT.\r\n */\r\n public dispose() {\r\n if (this._renderTarget) {\r\n this._renderTarget.irradianceTexture = null;\r\n this._renderTarget.dispose();\r\n }\r\n this._renderTarget = null;\r\n this._effectWrapper?.dispose();\r\n this._effectWrapper = null;\r\n this._effectRenderer?.dispose();\r\n this._effectRenderer = null;\r\n this._isDisposed = true;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"diffuseSkyIrradianceLut.js","sourceRoot":"","sources":["../../../../dev/addons/src/atmosphere/diffuseSkyIrradianceLut.ts"],"names":[],"mappings":"AAAA,uCAAuC;A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AG,IAAI,CAAC;IACzB,CAAC;IAED;;OAEG;IACI,OAAO;QACV,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC5C,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;QACjC,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,CAAC;QAChC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC5B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC5B,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// MIT License\r\n\r\nimport type { Atmosphere } from \"./atmosphere\";\r\nimport type { AtmospherePhysicalProperties } from \"./atmospherePhysicalProperties\";\r\nimport { Clamp } from \"core/Maths/math.scalar.functions\";\r\nimport { Constants } from \"core/Engines/constants\";\r\nimport { EffectRenderer, EffectWrapper } from \"core/Materials/effectRenderer\";\r\nimport { FromHalfFloat } from \"core/Misc/textureTools\";\r\nimport type { IColor3Like, IColor4Like, IVector2Like, IVector3Like } from \"core/Maths/math.like\";\r\nimport type { Nullable } from \"core/types\";\r\nimport { RenderTargetTexture } from \"core/Materials/Textures/renderTargetTexture\";\r\nimport { Sample2DRgbaToRef } from \"./sampling\";\r\nimport \"./Shaders/diffuseSkyIrradiance.fragment\";\r\nimport \"./Shaders/fullscreenTriangle.vertex\";\r\n\r\nconst RaySamples = 128;\r\nconst LutWidthPx = 64;\r\nconst LutHeightPx = 16;\r\nconst HalfTexelSize = { x: 0.5 / LutWidthPx, y: 0.5 / LutHeightPx };\r\nconst UnitToUVScale = { x: (LutWidthPx - 1.0) / LutWidthPx, y: (LutHeightPx - 1.0) / LutHeightPx };\r\nconst UvTemp = { x: Number.NaN, y: Number.NaN };\r\nconst Color4Temp = { r: Number.NaN, g: Number.NaN, b: Number.NaN, a: Number.NaN } as IColor4Like;\r\n\r\nconst ComputeLutUVToRef = (properties: AtmospherePhysicalProperties, radius: number, cosAngleLightToZenith: number, result: IVector2Like): void => {\r\n const unitX = Clamp(0.5 + 0.5 * cosAngleLightToZenith);\r\n const unitY = Clamp((radius - properties.planetRadius) / properties.atmosphereThickness);\r\n result.x = unitX * UnitToUVScale.x + HalfTexelSize.x;\r\n result.y = unitY * UnitToUVScale.y + HalfTexelSize.y;\r\n};\r\n\r\n/**\r\n * The diffuse sky irradiance LUT is used to query the diffuse irradiance at a specified position.\r\n */\r\nexport class DiffuseSkyIrradianceLut {\r\n private readonly _atmosphere: Atmosphere;\r\n private _renderTarget: Nullable<RenderTargetTexture> = null;\r\n private _effectWrapper: Nullable<EffectWrapper> = null;\r\n private _effectRenderer: Nullable<EffectRenderer> = null;\r\n private _isDirty = true;\r\n private _isDisposed = false;\r\n private _lutData: Uint8Array | Uint16Array = new Uint16Array(0);\r\n\r\n /**\r\n * True if the LUT needs to be rendered.\r\n */\r\n public get isDirty() {\r\n return this._isDirty;\r\n }\r\n\r\n /**\r\n * True if the LUT has been disposed.\r\n */\r\n public get isDisposed(): boolean {\r\n return this._isDisposed;\r\n }\r\n\r\n /**\r\n * The render target used for this LUT.\r\n * @throws if the LUT has been disposed.\r\n */\r\n public get renderTarget(): RenderTargetTexture {\r\n if (this._isDisposed || this._renderTarget === null) {\r\n throw new Error();\r\n }\r\n return this._renderTarget;\r\n }\r\n\r\n /**\r\n * True if the LUT data has been read back from the GPU.\r\n */\r\n public get hasLutData(): boolean {\r\n return this._lutData[0] !== undefined;\r\n }\r\n\r\n /**\r\n * Constructs the {@link DiffuseSkyIrradianceLut}.\r\n * @param atmosphere - The atmosphere to use.\r\n */\r\n constructor(atmosphere: Atmosphere) {\r\n this._atmosphere = atmosphere;\r\n const scene = atmosphere.scene;\r\n const engine = scene.getEngine();\r\n\r\n const name = \"atmo-diffuseSkyIrradiance\";\r\n const caps = engine.getCaps();\r\n const textureType = caps.textureHalfFloatRender ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE;\r\n const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {\r\n generateMipMaps: false,\r\n type: textureType,\r\n samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,\r\n generateDepthBuffer: false,\r\n gammaSpace: false,\r\n }));\r\n renderTarget.wrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.wrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.anisotropicFilteringLevel = 1;\r\n renderTarget.skipInitialClear = true;\r\n\r\n const useUbo = atmosphere.uniformBuffer.useUbo;\r\n\r\n this._effectWrapper = new EffectWrapper({\r\n engine,\r\n name,\r\n vertexShader: \"fullscreenTriangle\",\r\n fragmentShader: \"diffuseSkyIrradiance\",\r\n attributeNames: [\"position\"],\r\n uniformNames: [\"depth\", ...(useUbo ? [] : atmosphere.uniformBuffer.getUniformNames())],\r\n uniformBuffers: useUbo ? [atmosphere.uniformBuffer.name] : [],\r\n defines: [\r\n \"#define POSITION_VEC2\",\r\n `#define NUM_SAMPLES ${RaySamples}u`,\r\n \"#define CUSTOM_IRRADIANCE_FILTERING_INPUT /* empty */\", // empty, no input texture needed as the radiance is procedurally generated from ray marching.\r\n // The following ray marches the atmosphere to get the radiance.\r\n \"#define CUSTOM_IRRADIANCE_FILTERING_FUNCTION vec3 c = integrateForIrradiance(n, Ls, vec3(0., filteringInfo.x, 0.));\",\r\n ],\r\n samplers: [\"transmittanceLut\", \"multiScatteringLut\"],\r\n useShaderStore: true,\r\n });\r\n\r\n this._effectRenderer = new EffectRenderer(engine, {\r\n // Full screen triangle.\r\n indices: [0, 2, 1],\r\n positions: [-1, -1, -1, 3, 3, -1],\r\n });\r\n\r\n // The sky irradiance will also be used for the environment texture.\r\n scene.environmentTexture = renderTarget;\r\n scene.environmentTexture.irradianceTexture = renderTarget;\r\n scene.environmentIntensity = 1.0;\r\n\r\n // Prevent the irradiance LUT from being rendered redundantly at the beginning of the frame.\r\n scene.environmentTexture.isRenderTarget = false;\r\n }\r\n\r\n /**\r\n * Gets the diffuse sky irradiance for a surface oriented along the geocentric normal.\r\n * Resulting color is always in linear space.\r\n * @param directionToLight - The direction to the light in world space.\r\n * @param radius - The position's distance to the planet origin.\r\n * @param cameraGeocentricNormal - The geocentric normal of the camera.\r\n * @param lightIrradiance - The irradiance of the light.\r\n * @param result - The color to store the result in.\r\n * @returns The result color.\r\n */\r\n public getDiffuseSkyIrradianceToRef<T extends IColor3Like>(\r\n directionToLight: IVector3Like,\r\n radius: number,\r\n cameraGeocentricNormal: IVector3Like,\r\n lightIrradiance: number,\r\n result: T\r\n ): T {\r\n const atmosphere = this._atmosphere;\r\n const additionalDiffuseSkyIrradiance = atmosphere.additionalDiffuseSkyIrradiance;\r\n\r\n const properties = atmosphere.physicalProperties;\r\n if (this._lutData[0] === undefined || radius > properties.atmosphereRadius) {\r\n result.r = additionalDiffuseSkyIrradiance.r;\r\n result.g = additionalDiffuseSkyIrradiance.g;\r\n result.b = additionalDiffuseSkyIrradiance.b;\r\n return result;\r\n }\r\n\r\n const cosAngleLightToZenith = directionToLight.x * cameraGeocentricNormal.x + directionToLight.y * cameraGeocentricNormal.y + directionToLight.z * cameraGeocentricNormal.z;\r\n ComputeLutUVToRef(properties, radius, cosAngleLightToZenith, UvTemp);\r\n Sample2DRgbaToRef(UvTemp.x, UvTemp.y, LutWidthPx, LutHeightPx, this._lutData, Color4Temp, FromHalfFloat);\r\n\r\n const intensity = atmosphere.diffuseSkyIrradianceIntensity;\r\n result.r = intensity * (lightIrradiance * Color4Temp.r + additionalDiffuseSkyIrradiance.r);\r\n result.g = intensity * (lightIrradiance * Color4Temp.g + additionalDiffuseSkyIrradiance.g);\r\n result.b = intensity * (lightIrradiance * Color4Temp.b + additionalDiffuseSkyIrradiance.b);\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Renders the LUT.\r\n * @returns True if the LUT was rendered.\r\n */\r\n public render(): boolean {\r\n // Only need to render the LUT once.\r\n const effectWrapper = this._effectWrapper;\r\n if (!this._isDirty || !effectWrapper?.isReady() || !this._renderTarget?.isReady()) {\r\n return false;\r\n }\r\n\r\n const engine = this._atmosphere.scene.getEngine();\r\n\r\n engine.bindFramebuffer(this.renderTarget.renderTarget!, undefined, undefined, undefined, true);\r\n\r\n const effectRenderer = this._effectRenderer!;\r\n effectRenderer.applyEffectWrapper(effectWrapper);\r\n\r\n effectRenderer.saveStates();\r\n effectRenderer.setViewport();\r\n\r\n const effect = effectWrapper.effect;\r\n effectRenderer.bindBuffers(effect);\r\n\r\n effect.setTexture(\"transmittanceLut\", this._atmosphere.transmittanceLut!.renderTarget);\r\n effect.setTexture(\"multiScatteringLut\", this._atmosphere.multiScatteringLutRenderTarget);\r\n\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n\r\n effect.setFloat(\"depth\", 0.0);\r\n\r\n effectRenderer.draw();\r\n\r\n effectRenderer.restoreStates();\r\n engine.restoreDefaultFramebuffer();\r\n\r\n this._isDirty = false;\r\n\r\n // eslint-disable-next-line github/no-then\r\n void this.renderTarget.readPixels(0, 0, undefined, undefined, true /* noDataConversion */)?.then((value: ArrayBufferView) => {\r\n if (this._isDisposed) {\r\n return;\r\n }\r\n this._lutData = value as Uint8Array | Uint16Array;\r\n });\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Marks the LUT as needing to be rendered.\r\n */\r\n public markDirty(): void {\r\n this._isDirty = true;\r\n }\r\n\r\n /**\r\n * Disposes the LUT.\r\n */\r\n public dispose() {\r\n if (this._renderTarget) {\r\n this._renderTarget.irradianceTexture = null;\r\n this._renderTarget.dispose();\r\n }\r\n this._renderTarget = null;\r\n this._effectWrapper?.dispose();\r\n this._effectWrapper = null;\r\n this._effectRenderer?.dispose();\r\n this._effectRenderer = null;\r\n this._isDisposed = true;\r\n }\r\n}\r\n"]}
@@ -84,9 +84,10 @@ export class TransmittanceLut {
84
84
  this._atmosphere = atmosphere;
85
85
  const scene = this._atmosphere.scene;
86
86
  const engine = scene.getEngine();
87
+ const useHalfFloat = UseHalfFloat && engine.getCaps().textureHalfFloatRender;
87
88
  const name = "atmo-transmittance";
88
89
  const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {
89
- type: UseHalfFloat ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE,
90
+ type: useHalfFloat ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE,
90
91
  samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,
91
92
  generateDepthBuffer: false,
92
93
  gammaSpace: false,
@@ -1 +1 @@
1
- {"version":3,"file":"transmittanceLut.js","sourceRoot":"","sources":["../../../../dev/addons/src/atmosphere/transmittanceLut.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,cAAc;AAId,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,oDAAyC;AACrE,OAAO,EAAE,SAAS,EAAE,0CAA+B;AAEnD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,iDAAsC;AAC9E,OAAO,EAAE,aAAa,EAAE,0CAA+B;AAGvD,OAAO,EAAE,UAAU,EAAE,wCAA6B;AAClD,OAAO,EAAE,mBAAmB,EAAE,+DAAoD;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,qCAAqC,CAAC;AAC7C,OAAO,kCAAkC,CAAC;AAE1C,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,wBAAwB,GAAG,EAAE,CAAC,EAAE,CAAC,UAAU,GAAG,GAAG,CAAC,GAAG,UAAU,EAAE,CAAC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IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC5B,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// MIT License\r\n\r\nimport type { Atmosphere } from \"./atmosphere\";\r\nimport type { AtmospherePhysicalProperties } from \"./atmospherePhysicalProperties\";\r\nimport { Clamp, SmoothStep } from \"core/Maths/math.scalar.functions\";\r\nimport { Constants } from \"core/Engines/constants\";\r\nimport type { DirectionalLight } from \"core/Lights/directionalLight\";\r\nimport { EffectRenderer, EffectWrapper } from \"core/Materials/effectRenderer\";\r\nimport { FromHalfFloat } from \"core/Misc/textureTools\";\r\nimport type { IColor3Like, IColor4Like, IVector2Like, IVector3Like } from \"core/Maths/math.like\";\r\nimport type { Nullable } from \"core/types\";\r\nimport { Observable } from \"core/Misc/observable\";\r\nimport { RenderTargetTexture } from \"core/Materials/Textures/renderTargetTexture\";\r\nimport { Sample2DRgbaToRef } from \"./sampling\";\r\nimport \"./Shaders/fullscreenTriangle.vertex\";\r\nimport \"./Shaders/transmittance.fragment\";\r\n\r\nconst LutWidthPx = 256;\r\nconst LutHeightPx = 64;\r\nconst EffectiveDomainInUVSpace = { x: (LutWidthPx - 1.0) / LutWidthPx, y: (LutHeightPx - 1.0) / LutHeightPx };\r\nconst HalfTexelSize = { x: 0.5 / LutWidthPx, y: 0.5 / LutHeightPx };\r\nconst TransmittanceHorizonRange = 2.0 * HalfTexelSize.x;\r\nconst TransmittanceMaxUnoccludedU = 1.0 - 0.5 * TransmittanceHorizonRange;\r\n\r\nconst UseHalfFloat = false;\r\n\r\n// Temporary storage.\r\nconst Uv = { x: Number.NaN, y: Number.NaN } as IVector2Like;\r\nconst LightColorTemp = { r: Number.NaN, g: Number.NaN, b: Number.NaN } as IColor3Like;\r\nconst DirectionToLightTemp = { x: Number.NaN, y: Number.NaN, z: Number.NaN } as IVector3Like;\r\nconst Color4Temp = { r: Number.NaN, g: Number.NaN, b: Number.NaN, a: Number.NaN } as IColor4Like;\r\n\r\nconst ComputeLutUVToRef = (properties: AtmospherePhysicalProperties, radius: number, cosAngleLightToZenith: number, uv: IVector2Like): void => {\r\n const radiusSquared = radius * radius;\r\n const distanceToHorizon = Math.sqrt(Math.max(0.0, radiusSquared - properties.planetRadiusSquared));\r\n\r\n const cosAngleLightToZenithSq = cosAngleLightToZenith * cosAngleLightToZenith;\r\n const discriminant = radiusSquared * (cosAngleLightToZenithSq - 1.0) + properties.atmosphereRadiusSquared;\r\n const distanceToAtmosphereEdge = Math.max(0.0, -radius * cosAngleLightToZenith + Math.sqrt(Math.max(0.0, discriminant)));\r\n\r\n const minDistanceToAtmosphereEdge = Math.max(0.0, properties.atmosphereRadius - radius);\r\n const maxDistanceToAtmosphereEdge = distanceToHorizon + properties.horizonDistanceToAtmosphereEdge;\r\n const cosAngleLightToZenithCoordinate =\r\n (distanceToAtmosphereEdge - minDistanceToAtmosphereEdge) / Math.max(0.000001, maxDistanceToAtmosphereEdge - minDistanceToAtmosphereEdge);\r\n const distanceToHorizonCoordinate = distanceToHorizon / Math.max(0.000001, properties.horizonDistanceToAtmosphereEdge);\r\n\r\n // Unit to UV.\r\n uv.x = EffectiveDomainInUVSpace.x * cosAngleLightToZenithCoordinate + HalfTexelSize.x;\r\n uv.y = EffectiveDomainInUVSpace.y * distanceToHorizonCoordinate + HalfTexelSize.y;\r\n};\r\n\r\nconst SampleLutToRef = (\r\n properties: AtmospherePhysicalProperties,\r\n lutData: Uint8Array | Uint16Array,\r\n positionDistanceToOrigin: number,\r\n cosAngleLightToZenith: number,\r\n result: IColor4Like\r\n): void => {\r\n if (positionDistanceToOrigin > properties.atmosphereRadius) {\r\n result.r = result.g = result.b = result.a = 1.0;\r\n return;\r\n }\r\n\r\n ComputeLutUVToRef(properties, positionDistanceToOrigin, cosAngleLightToZenith, Uv);\r\n Sample2DRgbaToRef(Uv.x, Uv.y, LutWidthPx, LutHeightPx, lutData, result, UseHalfFloat ? FromHalfFloat : (value) => value / 255.0);\r\n\r\n const weight = Clamp(SmoothStep(1.0, 0.0, Clamp((Uv.x - TransmittanceMaxUnoccludedU) / TransmittanceHorizonRange)));\r\n result.r *= weight;\r\n result.g *= weight;\r\n result.b *= weight;\r\n result.a *= weight;\r\n};\r\n\r\n/**\r\n * The transmittance LUT can be used to get the radiance from an external light source arriving a given point, accounting for atmospheric scattering.\r\n */\r\nexport class TransmittanceLut {\r\n /**\r\n * Listen to this observer to know when the LUT data has been updated.\r\n * This is typically infrequent (once at startup), but also happens whenever the atmosphere's properties change.\r\n */\r\n public readonly onUpdatedObservable = new Observable<void>();\r\n\r\n private readonly _atmosphere: Atmosphere;\r\n private _lutData: Uint8Array | Uint16Array = new Uint8Array(0);\r\n private _renderTarget: Nullable<RenderTargetTexture>;\r\n private _effectWrapper: Nullable<EffectWrapper>;\r\n private _effectRenderer: Nullable<EffectRenderer>;\r\n private _isDirty = true;\r\n private _isDisposed = false;\r\n\r\n /**\r\n * True if the LUT has been rendered.\r\n */\r\n public get isDirty(): boolean {\r\n return this._isDirty;\r\n }\r\n\r\n /**\r\n * The render target that contains the transmittance LUT.\r\n * @throws if the LUT has been disposed.\r\n */\r\n public get renderTarget(): RenderTargetTexture {\r\n if (this._isDisposed || this._renderTarget === null) {\r\n throw new Error();\r\n }\r\n return this._renderTarget;\r\n }\r\n\r\n /**\r\n * Constructs the {@link TransmittanceLut}.\r\n * @param atmosphere - The atmosphere that owns this LUT.\r\n */\r\n constructor(atmosphere: Atmosphere) {\r\n this._atmosphere = atmosphere;\r\n\r\n const scene = this._atmosphere.scene;\r\n const engine = scene.getEngine();\r\n\r\n const name = \"atmo-transmittance\";\r\n const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {\r\n type: UseHalfFloat ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE,\r\n samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,\r\n generateDepthBuffer: false,\r\n gammaSpace: false,\r\n }));\r\n renderTarget.wrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.wrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.anisotropicFilteringLevel = 1;\r\n renderTarget.skipInitialClear = true;\r\n\r\n const useUbo = this._atmosphere.uniformBuffer.useUbo;\r\n this._effectWrapper = new EffectWrapper({\r\n engine,\r\n name,\r\n vertexShader: \"fullscreenTriangle\",\r\n fragmentShader: \"transmittance\",\r\n attributeNames: [\"position\"],\r\n uniformNames: [\"depth\", ...(useUbo ? [] : this._atmosphere.uniformBuffer.getUniformNames())],\r\n uniformBuffers: useUbo ? [this._atmosphere.uniformBuffer.name] : [],\r\n defines: [\"#define POSITION_VEC2\"],\r\n useShaderStore: true,\r\n });\r\n\r\n this._effectRenderer = new EffectRenderer(engine, {\r\n // Full screen triangle.\r\n indices: [0, 2, 1],\r\n positions: [-1, -1, -1, 3, 3, -1],\r\n });\r\n }\r\n\r\n /**\r\n * Gets the transmittance of an external light through the atmosphere to a point specified by its distance to the planet center and its geocentric normal.\r\n * The result is always a linear space color.\r\n * @param directionToLight - The direction to the light source.\r\n * @param pointRadius - The distance from the origin to the point.\r\n * @param pointGeocentricNormal - The normal of the point.\r\n * @param result - The color to write the result to.\r\n * @returns The result color.\r\n */\r\n public getTransmittedColorToRef<T extends IColor3Like>(directionToLight: IVector3Like, pointRadius: number, pointGeocentricNormal: IVector3Like, result: T): T {\r\n if (this._lutData[0] !== undefined) {\r\n const cosAngleLightToZenith =\r\n directionToLight.x * pointGeocentricNormal.x + directionToLight.y * pointGeocentricNormal.y + directionToLight.z * pointGeocentricNormal.z;\r\n SampleLutToRef(this._atmosphere.physicalProperties, this._lutData, pointRadius, cosAngleLightToZenith, Color4Temp);\r\n result.r = Color4Temp.r;\r\n result.g = Color4Temp.g;\r\n result.b = Color4Temp.b;\r\n } else {\r\n // Fallback.\r\n result.r = result.g = result.b = 1.0;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Derives light color from the transmittance at a point specified by its distance to the planet center and its geocentric normal.\r\n * @param light - The light to update.\r\n * @param pointRadius - The distance from the origin to the point.\r\n * @param pointGeocentricNormal - The normal of the point.\r\n */\r\n public updateLightParameters(light: DirectionalLight, pointRadius: number, pointGeocentricNormal: IVector3Like): void {\r\n const lightDirection = light.direction;\r\n DirectionToLightTemp.x = -lightDirection.x;\r\n DirectionToLightTemp.y = -lightDirection.y;\r\n DirectionToLightTemp.z = -lightDirection.z;\r\n this.getTransmittedColorToRef(DirectionToLightTemp, pointRadius, pointGeocentricNormal, LightColorTemp);\r\n\r\n light.diffuse.copyFromFloats(LightColorTemp.r, LightColorTemp.g, LightColorTemp.b);\r\n light.specular.copyFromFloats(LightColorTemp.r, LightColorTemp.g, LightColorTemp.b);\r\n }\r\n\r\n /**\r\n * Renders the LUT if needed.\r\n * @returns true if the LUT was rendered.\r\n */\r\n public render(): boolean {\r\n // Only need to render the LUT once.\r\n const effectWrapper = this._effectWrapper;\r\n if (!this._isDirty || !effectWrapper?.isReady() || !this._renderTarget?.isReady()) {\r\n return false;\r\n }\r\n\r\n const engine = this._atmosphere.scene.getEngine();\r\n\r\n engine.bindFramebuffer(this.renderTarget.renderTarget!, undefined, undefined, undefined, true);\r\n\r\n const effectRenderer = this._effectRenderer!;\r\n effectRenderer.applyEffectWrapper(effectWrapper);\r\n\r\n effectRenderer.saveStates();\r\n effectRenderer.setViewport();\r\n\r\n const effect = effectWrapper.effect;\r\n effectRenderer.bindBuffers(effect);\r\n\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n\r\n effect.setFloat(\"depth\", 0);\r\n\r\n effectRenderer.draw();\r\n\r\n effectRenderer.restoreStates();\r\n engine.restoreDefaultFramebuffer();\r\n\r\n this._isDirty = false;\r\n\r\n // eslint-disable-next-line github/no-then\r\n void this.renderTarget.readPixels(0, 0, undefined, undefined, UseHalfFloat /* noDataConversion */)?.then((value: ArrayBufferView) => {\r\n if (this._isDisposed) {\r\n return;\r\n }\r\n this._lutData = value as Uint8Array | Uint16Array;\r\n this.onUpdatedObservable.notifyObservers();\r\n });\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Marks the LUT as needing to be rendered.\r\n */\r\n public markDirty(): void {\r\n this._isDirty = true;\r\n }\r\n\r\n /**\r\n * Disposes the LUT and its resources.\r\n */\r\n public dispose(): void {\r\n this._renderTarget?.dispose();\r\n this._renderTarget = null;\r\n this._effectWrapper?.dispose();\r\n this._effectWrapper = null;\r\n this._effectRenderer?.dispose();\r\n this._effectRenderer = null;\r\n this._isDisposed = true;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"transmittanceLut.js","sourceRoot":"","sources":["../../../../dev/addons/src/atmosphere/transmittanceLut.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,cAAc;AAId,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,oDAAyC;AACrE,OAAO,EAAE,SAAS,EAAE,0CAA+B;AAEnD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,iDAAsC;AAC9E,OAAO,EAAE,aAAa,EAAE,0CAA+B;AAGvD,OAAO,EAAE,UAAU,EAAE,wCAA6B;AAClD,OAAO,EAAE,mBAAmB,EAAE,+DAAoD;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,qCAAqC,CAAC;AAC7C,OAAO,kCAAkC,CAAC;AAE1C,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,wBAAwB,GAAG,EAAE,CAAC,EAAE,CAAC,UAAU,GAAG,GAAG,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,CAAC,WAAW,GAAG,GAAG,CAAC,GAAG,WAAW,EAAE,CAAC;AAC9G,MAAM,aAAa,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,UAAU,EAAE,CAAC,EAAE,GAAG,GAAG,WAAW,EAAE,CAAC;AACpE,MAAM,yBAAyB,GAAG,GAAG,GAAG,aAA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";\r\nimport type { AtmospherePhysicalProperties } from \"./atmospherePhysicalProperties\";\r\nimport { Clamp, SmoothStep } from \"core/Maths/math.scalar.functions\";\r\nimport { Constants } from \"core/Engines/constants\";\r\nimport type { DirectionalLight } from \"core/Lights/directionalLight\";\r\nimport { EffectRenderer, EffectWrapper } from \"core/Materials/effectRenderer\";\r\nimport { FromHalfFloat } from \"core/Misc/textureTools\";\r\nimport type { IColor3Like, IColor4Like, IVector2Like, IVector3Like } from \"core/Maths/math.like\";\r\nimport type { Nullable } from \"core/types\";\r\nimport { Observable } from \"core/Misc/observable\";\r\nimport { RenderTargetTexture } from \"core/Materials/Textures/renderTargetTexture\";\r\nimport { Sample2DRgbaToRef } from \"./sampling\";\r\nimport \"./Shaders/fullscreenTriangle.vertex\";\r\nimport \"./Shaders/transmittance.fragment\";\r\n\r\nconst LutWidthPx = 256;\r\nconst LutHeightPx = 64;\r\nconst EffectiveDomainInUVSpace = { x: (LutWidthPx - 1.0) / LutWidthPx, y: (LutHeightPx - 1.0) / LutHeightPx };\r\nconst HalfTexelSize = { x: 0.5 / LutWidthPx, y: 0.5 / LutHeightPx };\r\nconst TransmittanceHorizonRange = 2.0 * HalfTexelSize.x;\r\nconst TransmittanceMaxUnoccludedU = 1.0 - 0.5 * TransmittanceHorizonRange;\r\n\r\nconst UseHalfFloat = false;\r\n\r\n// Temporary storage.\r\nconst Uv = { x: Number.NaN, y: Number.NaN } as IVector2Like;\r\nconst LightColorTemp = { r: Number.NaN, g: Number.NaN, b: Number.NaN } as IColor3Like;\r\nconst DirectionToLightTemp = { x: Number.NaN, y: Number.NaN, z: Number.NaN } as IVector3Like;\r\nconst Color4Temp = { r: Number.NaN, g: Number.NaN, b: Number.NaN, a: Number.NaN } as IColor4Like;\r\n\r\nconst ComputeLutUVToRef = (properties: AtmospherePhysicalProperties, radius: number, cosAngleLightToZenith: number, uv: IVector2Like): void => {\r\n const radiusSquared = radius * radius;\r\n const distanceToHorizon = Math.sqrt(Math.max(0.0, radiusSquared - properties.planetRadiusSquared));\r\n\r\n const cosAngleLightToZenithSq = cosAngleLightToZenith * cosAngleLightToZenith;\r\n const discriminant = radiusSquared * (cosAngleLightToZenithSq - 1.0) + properties.atmosphereRadiusSquared;\r\n const distanceToAtmosphereEdge = Math.max(0.0, -radius * cosAngleLightToZenith + Math.sqrt(Math.max(0.0, discriminant)));\r\n\r\n const minDistanceToAtmosphereEdge = Math.max(0.0, properties.atmosphereRadius - radius);\r\n const maxDistanceToAtmosphereEdge = distanceToHorizon + properties.horizonDistanceToAtmosphereEdge;\r\n const cosAngleLightToZenithCoordinate =\r\n (distanceToAtmosphereEdge - minDistanceToAtmosphereEdge) / Math.max(0.000001, maxDistanceToAtmosphereEdge - minDistanceToAtmosphereEdge);\r\n const distanceToHorizonCoordinate = distanceToHorizon / Math.max(0.000001, properties.horizonDistanceToAtmosphereEdge);\r\n\r\n // Unit to UV.\r\n uv.x = EffectiveDomainInUVSpace.x * cosAngleLightToZenithCoordinate + HalfTexelSize.x;\r\n uv.y = EffectiveDomainInUVSpace.y * distanceToHorizonCoordinate + HalfTexelSize.y;\r\n};\r\n\r\nconst SampleLutToRef = (\r\n properties: AtmospherePhysicalProperties,\r\n lutData: Uint8Array | Uint16Array,\r\n positionDistanceToOrigin: number,\r\n cosAngleLightToZenith: number,\r\n result: IColor4Like\r\n): void => {\r\n if (positionDistanceToOrigin > properties.atmosphereRadius) {\r\n result.r = result.g = result.b = result.a = 1.0;\r\n return;\r\n }\r\n\r\n ComputeLutUVToRef(properties, positionDistanceToOrigin, cosAngleLightToZenith, Uv);\r\n Sample2DRgbaToRef(Uv.x, Uv.y, LutWidthPx, LutHeightPx, lutData, result, UseHalfFloat ? FromHalfFloat : (value) => value / 255.0);\r\n\r\n const weight = Clamp(SmoothStep(1.0, 0.0, Clamp((Uv.x - TransmittanceMaxUnoccludedU) / TransmittanceHorizonRange)));\r\n result.r *= weight;\r\n result.g *= weight;\r\n result.b *= weight;\r\n result.a *= weight;\r\n};\r\n\r\n/**\r\n * The transmittance LUT can be used to get the radiance from an external light source arriving a given point, accounting for atmospheric scattering.\r\n */\r\nexport class TransmittanceLut {\r\n /**\r\n * Listen to this observer to know when the LUT data has been updated.\r\n * This is typically infrequent (once at startup), but also happens whenever the atmosphere's properties change.\r\n */\r\n public readonly onUpdatedObservable = new Observable<void>();\r\n\r\n private readonly _atmosphere: Atmosphere;\r\n private _lutData: Uint8Array | Uint16Array = new Uint8Array(0);\r\n private _renderTarget: Nullable<RenderTargetTexture>;\r\n private _effectWrapper: Nullable<EffectWrapper>;\r\n private _effectRenderer: Nullable<EffectRenderer>;\r\n private _isDirty = true;\r\n private _isDisposed = false;\r\n\r\n /**\r\n * True if the LUT has been rendered.\r\n */\r\n public get isDirty(): boolean {\r\n return this._isDirty;\r\n }\r\n\r\n /**\r\n * The render target that contains the transmittance LUT.\r\n * @throws if the LUT has been disposed.\r\n */\r\n public get renderTarget(): RenderTargetTexture {\r\n if (this._isDisposed || this._renderTarget === null) {\r\n throw new Error();\r\n }\r\n return this._renderTarget;\r\n }\r\n\r\n /**\r\n * Constructs the {@link TransmittanceLut}.\r\n * @param atmosphere - The atmosphere that owns this LUT.\r\n */\r\n constructor(atmosphere: Atmosphere) {\r\n this._atmosphere = atmosphere;\r\n\r\n const scene = this._atmosphere.scene;\r\n const engine = scene.getEngine();\r\n const useHalfFloat = UseHalfFloat && engine.getCaps().textureHalfFloatRender;\r\n\r\n const name = \"atmo-transmittance\";\r\n const renderTarget = (this._renderTarget = new RenderTargetTexture(name, { width: LutWidthPx, height: LutHeightPx }, scene, {\r\n type: useHalfFloat ? Constants.TEXTURETYPE_HALF_FLOAT : Constants.TEXTURETYPE_UNSIGNED_BYTE,\r\n samplingMode: Constants.TEXTURE_BILINEAR_SAMPLINGMODE,\r\n generateDepthBuffer: false,\r\n gammaSpace: false,\r\n }));\r\n renderTarget.wrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.wrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;\r\n renderTarget.anisotropicFilteringLevel = 1;\r\n renderTarget.skipInitialClear = true;\r\n\r\n const useUbo = this._atmosphere.uniformBuffer.useUbo;\r\n this._effectWrapper = new EffectWrapper({\r\n engine,\r\n name,\r\n vertexShader: \"fullscreenTriangle\",\r\n fragmentShader: \"transmittance\",\r\n attributeNames: [\"position\"],\r\n uniformNames: [\"depth\", ...(useUbo ? [] : this._atmosphere.uniformBuffer.getUniformNames())],\r\n uniformBuffers: useUbo ? [this._atmosphere.uniformBuffer.name] : [],\r\n defines: [\"#define POSITION_VEC2\"],\r\n useShaderStore: true,\r\n });\r\n\r\n this._effectRenderer = new EffectRenderer(engine, {\r\n // Full screen triangle.\r\n indices: [0, 2, 1],\r\n positions: [-1, -1, -1, 3, 3, -1],\r\n });\r\n }\r\n\r\n /**\r\n * Gets the transmittance of an external light through the atmosphere to a point specified by its distance to the planet center and its geocentric normal.\r\n * The result is always a linear space color.\r\n * @param directionToLight - The direction to the light source.\r\n * @param pointRadius - The distance from the origin to the point.\r\n * @param pointGeocentricNormal - The normal of the point.\r\n * @param result - The color to write the result to.\r\n * @returns The result color.\r\n */\r\n public getTransmittedColorToRef<T extends IColor3Like>(directionToLight: IVector3Like, pointRadius: number, pointGeocentricNormal: IVector3Like, result: T): T {\r\n if (this._lutData[0] !== undefined) {\r\n const cosAngleLightToZenith =\r\n directionToLight.x * pointGeocentricNormal.x + directionToLight.y * pointGeocentricNormal.y + directionToLight.z * pointGeocentricNormal.z;\r\n SampleLutToRef(this._atmosphere.physicalProperties, this._lutData, pointRadius, cosAngleLightToZenith, Color4Temp);\r\n result.r = Color4Temp.r;\r\n result.g = Color4Temp.g;\r\n result.b = Color4Temp.b;\r\n } else {\r\n // Fallback.\r\n result.r = result.g = result.b = 1.0;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Derives light color from the transmittance at a point specified by its distance to the planet center and its geocentric normal.\r\n * @param light - The light to update.\r\n * @param pointRadius - The distance from the origin to the point.\r\n * @param pointGeocentricNormal - The normal of the point.\r\n */\r\n public updateLightParameters(light: DirectionalLight, pointRadius: number, pointGeocentricNormal: IVector3Like): void {\r\n const lightDirection = light.direction;\r\n DirectionToLightTemp.x = -lightDirection.x;\r\n DirectionToLightTemp.y = -lightDirection.y;\r\n DirectionToLightTemp.z = -lightDirection.z;\r\n this.getTransmittedColorToRef(DirectionToLightTemp, pointRadius, pointGeocentricNormal, LightColorTemp);\r\n\r\n light.diffuse.copyFromFloats(LightColorTemp.r, LightColorTemp.g, LightColorTemp.b);\r\n light.specular.copyFromFloats(LightColorTemp.r, LightColorTemp.g, LightColorTemp.b);\r\n }\r\n\r\n /**\r\n * Renders the LUT if needed.\r\n * @returns true if the LUT was rendered.\r\n */\r\n public render(): boolean {\r\n // Only need to render the LUT once.\r\n const effectWrapper = this._effectWrapper;\r\n if (!this._isDirty || !effectWrapper?.isReady() || !this._renderTarget?.isReady()) {\r\n return false;\r\n }\r\n\r\n const engine = this._atmosphere.scene.getEngine();\r\n\r\n engine.bindFramebuffer(this.renderTarget.renderTarget!, undefined, undefined, undefined, true);\r\n\r\n const effectRenderer = this._effectRenderer!;\r\n effectRenderer.applyEffectWrapper(effectWrapper);\r\n\r\n effectRenderer.saveStates();\r\n effectRenderer.setViewport();\r\n\r\n const effect = effectWrapper.effect;\r\n effectRenderer.bindBuffers(effect);\r\n\r\n this._atmosphere.bindUniformBufferToEffect(effect);\r\n\r\n effect.setFloat(\"depth\", 0);\r\n\r\n effectRenderer.draw();\r\n\r\n effectRenderer.restoreStates();\r\n engine.restoreDefaultFramebuffer();\r\n\r\n this._isDirty = false;\r\n\r\n // eslint-disable-next-line github/no-then\r\n void this.renderTarget.readPixels(0, 0, undefined, undefined, UseHalfFloat /* noDataConversion */)?.then((value: ArrayBufferView) => {\r\n if (this._isDisposed) {\r\n return;\r\n }\r\n this._lutData = value as Uint8Array | Uint16Array;\r\n this.onUpdatedObservable.notifyObservers();\r\n });\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Marks the LUT as needing to be rendered.\r\n */\r\n public markDirty(): void {\r\n this._isDirty = true;\r\n }\r\n\r\n /**\r\n * Disposes the LUT and its resources.\r\n */\r\n public dispose(): void {\r\n this._renderTarget?.dispose();\r\n this._renderTarget = null;\r\n this._effectWrapper?.dispose();\r\n this._effectWrapper = null;\r\n this._effectRenderer?.dispose();\r\n this._effectRenderer = null;\r\n this._isDisposed = true;\r\n }\r\n}\r\n"]}
@@ -64,7 +64,7 @@ export function GetPositionsAndIndices(meshes) {
64
64
  * @returns Array of indices with reversed winding order.
65
65
  */
66
66
  export function GetReversedIndices(meshOrIndices) {
67
- const indices = meshOrIndices instanceof Mesh ? meshOrIndices.getIndices() : meshOrIndices;
67
+ const indices = meshOrIndices instanceof Mesh ? meshOrIndices.getIndices(false, true) : meshOrIndices;
68
68
  if (indices) {
69
69
  for (let i = 0; i < indices.length; i += 3) {
70
70
  // Swap the second and third index to reverse the winding order
@@ -1 +1 @@
1
- {"version":3,"file":"getters.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/common/getters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,uCAA4B;AACnD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,0CAA+B;AACzD,OAAO,EAAE,IAAI,EAAE,oCAAyB;AAExC;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAAc;IACjD,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,IAAI,KAAa,CAAC;IAClB,IAAI,GAAW,CAAC;IAChB,IAAI,EAAU,CAAC;IACf,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,OAAO,GAAa,EAAE,CAAC;IAE7B,KAAK,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAC7C,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAChB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC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C,CAAC,CAAC,CAAC;QACxE,CAAC;IACL,CAAC;IAED,OAAO,OAAO,CAAC;AACnB,CAAC","sourcesContent":["import { VertexBuffer } from \"core/Buffers/buffer\";\nimport { Matrix, Vector3 } from \"core/Maths/math.vector\";\nimport { Mesh } from \"core/Meshes/mesh\";\n\n/**\n * Extracts positions and indices from an array of meshes.\n * @param meshes The array of meshes from which to extract positions and indices.\n * @returns A tuple containing a Float32Array of positions and a Uint32Array of\n */\nexport function GetPositionsAndIndices(meshes: Mesh[]): [positions: Float32Array, indices: Uint32Array] {\n let offset = 0;\n let index: number;\n let tri: number;\n let pt: number;\n const positions: number[] = [];\n const indices: number[] = [];\n\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n const mesh = meshes[index];\n\n const meshIndices = GetReversedIndices(mesh);\n if (!meshIndices) {\n continue;\n }\n\n const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);\n if (!meshPositions) {\n continue;\n }\n\n const worldMatrices: Matrix[] = [];\n const worldMatrix = mesh.computeWorldMatrix(true);\n\n if (mesh.hasThinInstances) {\n const thinMatrices = (mesh as Mesh).thinInstanceGetWorldMatrices();\n for (let instanceIndex = 0; instanceIndex < thinMatrices.length; instanceIndex++) {\n const tmpMatrix = new Matrix();\n const thinMatrix = thinMatrices[instanceIndex];\n thinMatrix.multiplyToRef(worldMatrix, tmpMatrix);\n worldMatrices.push(tmpMatrix);\n }\n } else {\n worldMatrices.push(worldMatrix);\n }\n\n const transformed = Vector3.Zero();\n const position = Vector3.Zero();\n\n for (let matrixIndex = 0; matrixIndex < worldMatrices.length; matrixIndex++) {\n const wm = worldMatrices[matrixIndex];\n for (tri = 0; tri < meshIndices.length; tri++) {\n indices.push(meshIndices[tri] + offset);\n }\n\n for (pt = 0; pt < meshPositions.length; pt += 3) {\n Vector3.FromArrayToRef(meshPositions, pt, position);\n Vector3.TransformCoordinatesToRef(position, wm, transformed);\n positions.push(transformed.x, transformed.y, transformed.z);\n }\n\n offset += meshPositions.length / 3;\n }\n }\n }\n return [Float32Array.from(positions), Uint32Array.from(indices)];\n}\n\n/**\n * Reverses the order of vertices in each triangle (3 indices per face) to ensure\n * that the winding order is consistent with the Recast Navigation requirements.\n * This is necessary because Recast Navigation expects the indices to be in a specific winding order.\n * @param meshOrIndices The mesh from which to extract indices or the indices themselves.\n * @returns Array of indices with reversed winding order.\n */\nexport function GetReversedIndices(\n meshOrIndices: Mesh | Uint32Array | number[]\n): Uint32Array<ArrayBufferLike> | number[] | Int32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | null {\n const indices = meshOrIndices instanceof Mesh ? meshOrIndices.getIndices() : meshOrIndices;\n\n if (indices) {\n for (let i = 0; i < indices.length; i += 3) {\n // Swap the second and third index to reverse the winding order\n [indices[i + 1], indices[i + 2]] = [indices[i + 2], indices[i + 1]];\n }\n }\n\n return indices;\n}\n"]}
1
+ {"version":3,"file":"getters.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/common/getters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,uCAA4B;AACnD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,0CAA+B;AACzD,OAAO,EAAE,IAAI,EAAE,oCAAyB;AAExC;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAAc;IACjD,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,IAAI,KAAa,CAAC;IAClB,IAAI,GAAW,CAAC;IAChB,IAAI,EAAU,CAAC;IACf,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,OAAO,GAAa,EAAE,CAAC;IAE7B,KAAK,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAC7C,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAChB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;YAE3B,MAAM,WAAW,GAAG,kBAAkB,CAAC,IA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,CAAC;IACL,CAAC;IAED,OAAO,OAAO,CAAC;AACnB,CAAC","sourcesContent":["import { VertexBuffer } from \"core/Buffers/buffer\";\nimport { Matrix, Vector3 } from \"core/Maths/math.vector\";\nimport { Mesh } from \"core/Meshes/mesh\";\n\n/**\n * Extracts positions and indices from an array of meshes.\n * @param meshes The array of meshes from which to extract positions and indices.\n * @returns A tuple containing a Float32Array of positions and a Uint32Array of\n */\nexport function GetPositionsAndIndices(meshes: Mesh[]): [positions: Float32Array, indices: Uint32Array] {\n let offset = 0;\n let index: number;\n let tri: number;\n let pt: number;\n const positions: number[] = [];\n const indices: number[] = [];\n\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n const mesh = meshes[index];\n\n const meshIndices = GetReversedIndices(mesh);\n if (!meshIndices) {\n continue;\n }\n\n const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);\n if (!meshPositions) {\n continue;\n }\n\n const worldMatrices: Matrix[] = [];\n const worldMatrix = mesh.computeWorldMatrix(true);\n\n if (mesh.hasThinInstances) {\n const thinMatrices = (mesh as Mesh).thinInstanceGetWorldMatrices();\n for (let instanceIndex = 0; instanceIndex < thinMatrices.length; instanceIndex++) {\n const tmpMatrix = new Matrix();\n const thinMatrix = thinMatrices[instanceIndex];\n thinMatrix.multiplyToRef(worldMatrix, tmpMatrix);\n worldMatrices.push(tmpMatrix);\n }\n } else {\n worldMatrices.push(worldMatrix);\n }\n\n const transformed = Vector3.Zero();\n const position = Vector3.Zero();\n\n for (let matrixIndex = 0; matrixIndex < worldMatrices.length; matrixIndex++) {\n const wm = worldMatrices[matrixIndex];\n for (tri = 0; tri < meshIndices.length; tri++) {\n indices.push(meshIndices[tri] + offset);\n }\n\n for (pt = 0; pt < meshPositions.length; pt += 3) {\n Vector3.FromArrayToRef(meshPositions, pt, position);\n Vector3.TransformCoordinatesToRef(position, wm, transformed);\n positions.push(transformed.x, transformed.y, transformed.z);\n }\n\n offset += meshPositions.length / 3;\n }\n }\n }\n return [Float32Array.from(positions), Uint32Array.from(indices)];\n}\n\n/**\n * Reverses the order of vertices in each triangle (3 indices per face) to ensure\n * that the winding order is consistent with the Recast Navigation requirements.\n * This is necessary because Recast Navigation expects the indices to be in a specific winding order.\n * @param meshOrIndices The mesh from which to extract indices or the indices themselves.\n * @returns Array of indices with reversed winding order.\n */\nexport function GetReversedIndices(\n meshOrIndices: Mesh | Uint32Array | number[]\n): Uint32Array<ArrayBufferLike> | number[] | Int32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | null {\n const indices = meshOrIndices instanceof Mesh ? meshOrIndices.getIndices(false, true) : meshOrIndices;\n\n if (indices) {\n for (let i = 0; i < indices.length; i += 3) {\n // Swap the second and third index to reverse the winding order\n [indices[i + 1], indices[i + 2]] = [indices[i + 2], indices[i + 1]];\n }\n }\n\n return indices;\n}\n"]}
@@ -11,10 +11,12 @@ export declare function GetRecast(): RecastInjection;
11
11
  */
12
12
  export declare function SetRecast(recast: RecastInjection): void;
13
13
  /**
14
- * Initialize the Manifold library
15
- * @param version defines the version of the library to use, default is "0.43.0"
16
- * @param options defines the options to use to initialize the library
14
+ * Initializes the Recast navigation library.
15
+ *
16
+ * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.
17
+ * @returns A promise that resolves when initialization is complete.
17
18
  */
18
- export declare function InitRecast(version?: string, options?: {
19
- instance: RecastInjection;
19
+ export declare function InitRecast(options?: {
20
+ version?: string;
21
+ instance?: RecastInjection;
20
22
  }): Promise<void>;
@@ -27,11 +27,13 @@ let _Recast;
27
27
  // eslint-disable-next-line @typescript-eslint/naming-convention
28
28
  let _InitPromise = null;
29
29
  /**
30
- * Initialize the Manifold library
31
- * @param version defines the version of the library to use, default is "0.43.0"
32
- * @param options defines the options to use to initialize the library
30
+ * Initializes the Recast navigation library.
31
+ *
32
+ * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.
33
+ * @returns A promise that resolves when initialization is complete.
33
34
  */
34
- export async function InitRecast(version = "0.43.0", options) {
35
+ export async function InitRecast(options) {
36
+ const version = options?.version ?? "0.43.0";
35
37
  const localOptions = {
36
38
  url: "https://unpkg.com/@recast-navigation",
37
39
  version,
@@ -1 +1 @@
1
- {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/factory/common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,6CAAkC;AAKnE;;;;GAIG;AACH,MAAM,UAAU,SAAS;IACrB,IAAI,CAAC,OAAO,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,OAAO,CAAC;AACnB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,MAAuB;IAC7C,OAAO,GAAG,MAAM,CAAC;AACrB,CAAC;AAED;;GAEG;AACH,IAAI,OAAwB,CAAC;AAE7B;;GAEG;AACH,gEAAgE;AAChE,IAAI,YAAY,GAAsD,IAAI,CAAC;AAE3E;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC5B,OAAO,GAAG,QAAQ,EAClB,OAEC;IAED,MAAM,YAAY,GAAG;QACjB,GAAG,EAAE,sCAAsC;QAC3C,OAAO;QACP,GAAG,OAAO;KACb,CAAC;IAEF,IAAI,OAAO,EAAE,CAAC;QACV,OAAO,CAAC,sBAAsB;IAClC,CAAC;IAED,IAAI,YAAY,EAAE,CAAC;QACf,MAAM,YAAY,CAAC;QACnB,OAAO;IACX,CAAC;IAED,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;QACxB,OAAO,GAAG,YAAY,CAAC,QAAQ,CAAC;IACpC,CAAC;SAAM,CAAC;QACJ,YAAY,GAAG,YAAY,CAAC,YAAY,CAAC,GAAG,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QAEpE,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;QAClC,kDAAkD;QAClD,OAAO,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QAEnD,MAAM,OAAO,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC;AACL,CAAC;AAED,KAAK,UAAU,YAAY,CAAC,OAAe,EAAE,OAAe;IACxD,MAAM,SAAS,GAAG;QACd,OAAO,EAAE;YACL,gEAAgE;YAChE,yBAAyB,EAAE,GAAG,OAAO,SAAS,OAAO,iBAAiB;YACtE,gEAAgE;YAChE,yBAAyB,EAAE,GAAG,OAAO,SAAS,OAAO,wCAAwC;YAC7F,gEAAgE;YAChE,+BAA+B,EAAE,GAAG,OAAO,eAAe,OAAO,iBAAiB;SACrF;KACJ,CAAC;IAEF,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;IAC1B,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC/C,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IAElC,MAAM,MAAM,GAAG,MAAM,sBAAsB,CACvC;+CACuC,OAAO,SAAS,OAAO;qDACjB,OAAO,eAAe,OAAO;;aAErE,CACR,CAAC;IACF,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["import { _LoadScriptModuleAsync } from \"core/Misc/tools.internals\";\nimport type { Nullable } from \"core/types\";\n\nimport type { RecastInjection } from \"../types\";\n\n/**\n * Gets the RecastInjection instance (reference to the recast-navigation-js library).\n * @returns The RecastInjection instance\n * @throws Error if Recast is not initialized\n */\nexport function GetRecast(): RecastInjection {\n if (!_Recast) {\n throw new Error(\"Recast is not initialized. Please call InitRecast first.\");\n }\n return _Recast;\n}\n\n/**\n * Sets the RecastInjection instance (reference to the recast-navigation-js library).\n * @param recast The RecastInjection instance to set\n */\nexport function SetRecast(recast: RecastInjection) {\n _Recast = recast;\n}\n\n/**\n * Reference to the recast-navigation-js library\n */\nlet _Recast: RecastInjection;\n\n/**\n * Promise to wait for the recast-navigation-js library to be ready\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet _InitPromise: Nullable<Promise<{ core: any; generators: any }>> = null;\n\n/**\n * Initialize the Manifold library\n * @param version defines the version of the library to use, default is \"0.43.0\"\n * @param options defines the options to use to initialize the library\n */\nexport async function InitRecast(\n version = \"0.43.0\",\n options?: {\n instance: RecastInjection;\n }\n) {\n const localOptions = {\n url: \"https://unpkg.com/@recast-navigation\",\n version,\n ...options,\n };\n\n if (_Recast) {\n return; // Already initialized\n }\n\n if (_InitPromise) {\n await _InitPromise;\n return;\n }\n\n if (localOptions.instance) {\n _Recast = localOptions.instance;\n } else {\n _InitPromise = ImportRecast(localOptions.url, localOptions.version);\n\n const result = await _InitPromise;\n // eslint-disable-next-line require-atomic-updates\n _Recast = { ...result.core, ...result.generators };\n\n await _Recast.init();\n }\n}\n\nasync function ImportRecast(baseUrl: string, version: string) {\n const importMap = {\n imports: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/core\": `${baseUrl}/core@${version}/dist/index.mjs`,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/wasm\": `${baseUrl}/wasm@${version}/dist/recast-navigation.wasm-compat.js`,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/generators\": `${baseUrl}/generators@${version}/dist/index.mjs`,\n },\n };\n\n const script = document.createElement(\"script\");\n script.type = \"importmap\";\n script.textContent = JSON.stringify(importMap);\n document.body.appendChild(script);\n\n const result = await _LoadScriptModuleAsync(\n `\n import * as CoreModule from '${baseUrl}/core@${version}/dist/index.mjs';\n import * as GeneratorsModule from '${baseUrl}/generators@${version}/dist/index.mjs';\n const returnedValue = {core: CoreModule, generators: GeneratorsModule};\n `\n );\n return result;\n}\n"]}
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/factory/common.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E,OAAe;IACxD,MAAM,SAAS,GAAG;QACd,OAAO,EAAE;YACL,gEAAgE;YAChE,yBAAyB,EAAE,GAAG,OAAO,SAAS,OAAO,iBAAiB;YACtE,gEAAgE;YAChE,yBAAyB,EAAE,GAAG,OAAO,SAAS,OAAO,wCAAwC;YAC7F,gEAAgE;YAChE,+BAA+B,EAAE,GAAG,OAAO,eAAe,OAAO,iBAAiB;SACrF;KACJ,CAAC;IAEF,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;IAC1B,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IAC/C,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IAElC,MAAM,MAAM,GAAG,MAAM,sBAAsB,CACvC;+CACuC,OAAO,SAAS,OAAO;qDACjB,OAAO,eAAe,OAAO;;aAErE,CACR,CAAC;IACF,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["import { _LoadScriptModuleAsync } from \"core/Misc/tools.internals\";\nimport type { Nullable } from \"core/types\";\n\nimport type { RecastInjection } from \"../types\";\n\n/**\n * Gets the RecastInjection instance (reference to the recast-navigation-js library).\n * @returns The RecastInjection instance\n * @throws Error if Recast is not initialized\n */\nexport function GetRecast(): RecastInjection {\n if (!_Recast) {\n throw new Error(\"Recast is not initialized. Please call InitRecast first.\");\n }\n return _Recast;\n}\n\n/**\n * Sets the RecastInjection instance (reference to the recast-navigation-js library).\n * @param recast The RecastInjection instance to set\n */\nexport function SetRecast(recast: RecastInjection) {\n _Recast = recast;\n}\n\n/**\n * Reference to the recast-navigation-js library\n */\nlet _Recast: RecastInjection;\n\n/**\n * Promise to wait for the recast-navigation-js library to be ready\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet _InitPromise: Nullable<Promise<{ core: any; generators: any }>> = null;\n\n/**\n * Initializes the Recast navigation library.\n *\n * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.\n * @returns A promise that resolves when initialization is complete.\n */\nexport async function InitRecast(options?: { version?: string; instance?: RecastInjection }) {\n const version = options?.version ?? \"0.43.0\";\n const localOptions = {\n url: \"https://unpkg.com/@recast-navigation\",\n version,\n ...options,\n };\n\n if (_Recast) {\n return; // Already initialized\n }\n\n if (_InitPromise) {\n await _InitPromise;\n return;\n }\n\n if (localOptions.instance) {\n _Recast = localOptions.instance;\n } else {\n _InitPromise = ImportRecast(localOptions.url, localOptions.version);\n\n const result = await _InitPromise;\n // eslint-disable-next-line require-atomic-updates\n _Recast = { ...result.core, ...result.generators };\n\n await _Recast.init();\n }\n}\n\nasync function ImportRecast(baseUrl: string, version: string) {\n const importMap = {\n imports: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/core\": `${baseUrl}/core@${version}/dist/index.mjs`,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/wasm\": `${baseUrl}/wasm@${version}/dist/recast-navigation.wasm-compat.js`,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"@recast-navigation/generators\": `${baseUrl}/generators@${version}/dist/index.mjs`,\n },\n };\n\n const script = document.createElement(\"script\");\n script.type = \"importmap\";\n script.textContent = JSON.stringify(importMap);\n document.body.appendChild(script);\n\n const result = await _LoadScriptModuleAsync(\n `\n import * as CoreModule from '${baseUrl}/core@${version}/dist/index.mjs';\n import * as GeneratorsModule from '${baseUrl}/generators@${version}/dist/index.mjs';\n const returnedValue = {core: CoreModule, generators: GeneratorsModule};\n `\n );\n return result;\n}\n"]}
@@ -1,7 +1,12 @@
1
1
  import { RecastNavigationJSPluginV2 } from "../plugin/RecastNavigationJSPlugin.js";
2
+ import type { RecastInjection } from "../types.js";
2
3
  /**
3
4
  * Creates a navigation plugin for the given scene.
4
5
  * @returns A promise that resolves to the created navigation plugin.
6
+ * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.
5
7
  * @remarks This function initializes the Recast module and sets up the navigation plugin.
6
8
  */
7
- export declare function CreateNavigationPluginAsync(): Promise<RecastNavigationJSPluginV2>;
9
+ export declare function CreateNavigationPluginAsync(options?: {
10
+ version?: string;
11
+ instance?: RecastInjection;
12
+ }): Promise<RecastNavigationJSPluginV2>;
@@ -4,10 +4,11 @@ import { GetRecast, InitRecast } from "./common.js";
4
4
  /**
5
5
  * Creates a navigation plugin for the given scene.
6
6
  * @returns A promise that resolves to the created navigation plugin.
7
+ * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.
7
8
  * @remarks This function initializes the Recast module and sets up the navigation plugin.
8
9
  */
9
- export async function CreateNavigationPluginAsync() {
10
- await InitRecast();
10
+ export async function CreateNavigationPluginAsync(options) {
11
+ await InitRecast(options);
11
12
  const navigationPlugin = new RecastNavigationJSPluginV2(GetRecast());
12
13
  InjectGenerators(navigationPlugin);
13
14
  return navigationPlugin;
@@ -1 +1 @@
1
- {"version":3,"file":"factory.single-thread.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/factory/factory.single-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEjD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B;IAC7C,MAAM,UAAU,EAAE,CAAC;IAEnB,MAAM,gBAAgB,GAAG,IAAI,0BAA0B,CAAC,SAAS,EAAE,CAAC,CAAC;IACrE,gBAAgB,CAAC,gBAAgB,CAAC,CAAC;IAEnC,OAAO,gBAAgB,CAAC;AAC5B,CAAC","sourcesContent":["import { InjectGenerators } from \"../generator/injection\";\nimport { RecastNavigationJSPluginV2 } from \"../plugin/RecastNavigationJSPlugin\";\nimport { GetRecast, InitRecast } from \"./common\";\n\n/**\n * Creates a navigation plugin for the given scene.\n * @returns A promise that resolves to the created navigation plugin.\n * @remarks This function initializes the Recast module and sets up the navigation plugin.\n */\nexport async function CreateNavigationPluginAsync() {\n await InitRecast();\n\n const navigationPlugin = new RecastNavigationJSPluginV2(GetRecast());\n InjectGenerators(navigationPlugin);\n\n return navigationPlugin;\n}\n"]}
1
+ {"version":3,"file":"factory.single-thread.js","sourceRoot":"","sources":["../../../../../dev/addons/src/navigation/factory/factory.single-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAEhF,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEjD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,OAA0D;IACxG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;IAE1B,MAAM,gBAAgB,GAAG,IAAI,0BAA0B,CAAC,SAAS,EAAE,CAAC,CAAC;IACrE,gBAAgB,CAAC,gBAAgB,CAAC,CAAC;IAEnC,OAAO,gBAAgB,CAAC;AAC5B,CAAC","sourcesContent":["import { InjectGenerators } from \"../generator/injection\";\nimport { RecastNavigationJSPluginV2 } from \"../plugin/RecastNavigationJSPlugin\";\nimport type { RecastInjection } from \"../types\";\nimport { GetRecast, InitRecast } from \"./common\";\n\n/**\n * Creates a navigation plugin for the given scene.\n * @returns A promise that resolves to the created navigation plugin.\n * @param options Optional configuration. options.version: The version of Recast to use. options.instance: A custom Recast instance to inject instead of loading one.\n * @remarks This function initializes the Recast module and sets up the navigation plugin.\n */\nexport async function CreateNavigationPluginAsync(options?: { version?: string; instance?: RecastInjection }) {\n await InitRecast(options);\n\n const navigationPlugin = new RecastNavigationJSPluginV2(GetRecast());\n InjectGenerators(navigationPlugin);\n\n return navigationPlugin;\n}\n"]}
@@ -473,7 +473,9 @@ export class RecastNavigationJSPluginV2 {
473
473
  };
474
474
  }
475
475
  _preprocessParameters(parameters) {
476
- if ((parameters.tileSize ?? 0 > 0) && !!parameters.maxObstacles) {
476
+ // if maxObstacles is not defined, set it to a default value and set a default tile size if not defined
477
+ if (parameters.maxObstacles === undefined) {
478
+ parameters.tileSize = parameters.tileSize ?? 32; // maxObstacles will trigger tile cache creation, so we need a tile size
477
479
  parameters.maxObstacles = DefaultMaxObstacles;
478
480
  }
479
481
  parameters.walkableSlopeAngle = Math.max(0.1, parameters.walkableSlopeAngle ?? 60);