@pacem/pacem-3d 2.0.0-abel → 2.0.0-cauchy

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @pacem/pacem-3d v2.0.0-abel (https://js.pacem.it)
2
+ * @pacem/pacem-3d v2.0.0-cauchy (https://js.pacem.it)
3
3
  * Pacem (https://pacem.it)
4
4
  * Licensed under Apache-2.0
5
5
  */
@@ -464,6 +464,8 @@
464
464
  StalePropertyFlag["Camera"] = "camera";
465
465
  /** The object's {@link Renderable.hide} visibility changed. */
466
466
  StalePropertyFlag["Visibility"] = "visibility";
467
+ /** The mesh's {@link Mesh.castShadow}/{@link Mesh.receiveShadow} changed. */
468
+ StalePropertyFlag["Shadow"] = "shadow";
467
469
  })(StalePropertyFlag || (StalePropertyFlag = {}));
468
470
  /** Type guard checking whether `object` implements the {@link Interaction} contract. */
469
471
  function isInteraction(object) {
@@ -659,6 +661,13 @@
659
661
  ], Pacem3DGroupElement);
660
662
  /** `<pacem-3d-mesh>`: a {@link Ui3DElement} that renders a {@link NodeGeometry} (mesh or line) with a front/back {@link Material}. */
661
663
  let Pacem3DMeshElement = class Pacem3DMeshElement extends Ui3DElement {
664
+ constructor() {
665
+ super(...arguments);
666
+ /** Gets or sets whether the mesh occludes shadow-casting lights. */
667
+ this.castShadow = true;
668
+ /** Gets or sets whether the mesh gets darkened by the shadows of the other meshes. */
669
+ this.receiveShadow = true;
670
+ }
662
671
  propertyChangedCallback(name, old, val, first) {
663
672
  super.propertyChangedCallback(name, old, val, first);
664
673
  switch (name) {
@@ -669,6 +678,10 @@
669
678
  case 'backMaterial':
670
679
  this.setAsDirty(StalePropertyFlag.Material);
671
680
  break;
681
+ case 'castShadow':
682
+ case 'receiveShadow':
683
+ this.setAsDirty(StalePropertyFlag.Shadow);
684
+ break;
672
685
  }
673
686
  }
674
687
  };
@@ -681,6 +694,12 @@
681
694
  __decorate$k([
682
695
  pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Json })
683
696
  ], Pacem3DMeshElement.prototype, "backMaterial", void 0);
697
+ __decorate$k([
698
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Boolean })
699
+ ], Pacem3DMeshElement.prototype, "castShadow", void 0);
700
+ __decorate$k([
701
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Boolean })
702
+ ], Pacem3DMeshElement.prototype, "receiveShadow", void 0);
684
703
  Pacem3DMeshElement = __decorate$k([
685
704
  pacemCore.CustomElement({ tagName: Constants.MESH_SELECTOR })
686
705
  ], Pacem3DMeshElement);
@@ -714,6 +733,12 @@
714
733
  this.color = '#fff';
715
734
  /** Gets or sets the kind of light source. */
716
735
  this.type = 'omni';
736
+ /** Gets or sets whether the light casts shadows (directional and omni lights, WebGPU adapter). */
737
+ this.castShadow = false;
738
+ /** Gets or sets the side, in texels, of the light's shadow map. */
739
+ this.shadowMapSize = 2048;
740
+ /** Gets or sets the normal offset applied to the shadow receivers, as a fraction of the shadow frustum radius: raise it against shadow acne, lower it against detached shadows. */
741
+ this.shadowBias = 0.002;
717
742
  }
718
743
  propertyChangedCallback(name, old, val, first) {
719
744
  super.propertyChangedCallback(name, old, val, first);
@@ -722,6 +747,9 @@
722
747
  case 'color':
723
748
  case 'intensity':
724
749
  case 'target':
750
+ case 'castShadow':
751
+ case 'shadowMapSize':
752
+ case 'shadowBias':
725
753
  this.setAsDirty(StalePropertyFlag.Light);
726
754
  break;
727
755
  }
@@ -739,6 +767,15 @@
739
767
  __decorate$k([
740
768
  pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.String })
741
769
  ], Pacem3DLightElement.prototype, "type", void 0);
770
+ __decorate$k([
771
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Boolean })
772
+ ], Pacem3DLightElement.prototype, "castShadow", void 0);
773
+ __decorate$k([
774
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Number })
775
+ ], Pacem3DLightElement.prototype, "shadowMapSize", void 0);
776
+ __decorate$k([
777
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Number })
778
+ ], Pacem3DLightElement.prototype, "shadowBias", void 0);
742
779
  Pacem3DLightElement = __decorate$k([
743
780
  pacemCore.CustomElement({ tagName: Constants.LIGHT_SELECTOR })
744
781
  ], Pacem3DLightElement);
@@ -2298,7 +2335,9 @@
2298
2335
  const nodes = [];
2299
2336
  const uv = [];
2300
2337
  const indices = [];
2301
- const normals = [], normal = pacemNumerical.Geometry.LinearAlgebra.Vector3D.from(0, 0, 1);
2338
+ const normals = [],
2339
+ // the plane lies on xz and its triangles wind counter-clockwise as seen from +y
2340
+ normal = pacemNumerical.Geometry.LinearAlgebra.Vector3D.from(0, 1, 0);
2302
2341
  for (let j = 0; j <= lengthSegments; j++) {
2303
2342
  for (let i = 0; i <= widthSegments; i++) {
2304
2343
  const x = -halfWidth + i * width / (1.0 * widthSegments);
@@ -3707,6 +3746,20 @@
3707
3746
  const ABUFFER_BINDING_INDEX_INFO = 4;
3708
3747
  /** `@binding` index (within {@link UNIFORM_GROUP_INDEX_CAMERA}) of the opaque (multisampled) depth texture, used for the manual depth test. */
3709
3748
  const ABUFFER_BINDING_INDEX_DEPTH = 5;
3749
+ /** Name of the WGSL pipeline-overridable `bool` telling the A-buffer shaders whether depth is reversed (near → 1), flipping their depth comparisons. */
3750
+ const ABUFFER_REVERSED_Z_CONSTANT = 'REVERSED_Z';
3751
+ // #region shadows
3752
+ /** Maximum number of shadow map layers: a directional light takes one, an omni light six (a cube). */
3753
+ const MAX_SHADOW_LAYERS = 12;
3754
+ /** `@binding` index (within {@link UNIFORM_GROUP_INDEX_LIGHTING}) of the shadow maps (`texture_depth_2d_array`, one layer per directional light, six per omni light). Kept far from the light bindings (`0..n-1`). */
3755
+ const SHADOW_BINDING_MAP = 100;
3756
+ /** `@binding` index (within {@link UNIFORM_GROUP_INDEX_LIGHTING}) of the shadow maps' comparison sampler. */
3757
+ const SHADOW_BINDING_SAMPLER = 101;
3758
+ /** `@binding` index (within {@link UNIFORM_GROUP_INDEX_LIGHTING}) of the shadow map layers' uniform array (light-space matrix, normal offset, texel size). */
3759
+ const SHADOW_BINDING_LIGHTS = 102;
3760
+ /** Depth format of the shadow maps. */
3761
+ const SHADOW_MAP_FORMAT = 'depth32float';
3762
+ // #endregion
3710
3763
  /** Average translucent layers per pixel the A-buffer fragment list is sized for: fragments beyond capacity are dropped. */
3711
3764
  const ABUFFER_AVERAGE_LAYERS = 4;
3712
3765
  /** Maximum translucent layers per pixel sorted and composited: deeper ones are dropped. */
@@ -3871,6 +3924,9 @@
3871
3924
  * the global fragment counter; cleared (zeroed) every frame;
3872
3925
  * - list: `{ color (rgba8 packed), depth, next }` fragments;
3873
3926
  * - info: render target width/height and list capacity.
3927
+ *
3928
+ * Depth comparisons go through `aBufferCloser`, which follows the depth direction set by the pipeline-overridable
3929
+ * {@link ABUFFER_REVERSED_Z_CONSTANT} (reversed-Z: near → 1).
3874
3930
  */
3875
3931
  const FRAGMENT_STRUCT = `struct ABufferFragment {
3876
3932
  color: u32,
@@ -3882,6 +3938,14 @@
3882
3938
  height: u32,
3883
3939
  capacity: u32,
3884
3940
  padding: u32,
3941
+ }`;
3942
+ const DEPTH_DIRECTION = `override ${ABUFFER_REVERSED_Z_CONSTANT}: bool = false;
3943
+
3944
+ fn aBufferCloser(depth: f32, other: f32) -> bool {
3945
+ if (${ABUFFER_REVERSED_Z_CONSTANT}) {
3946
+ return depth > other;
3947
+ }
3948
+ return depth < other;
3885
3949
  }`;
3886
3950
  /**
3887
3951
  * Builds the {@link WGSLFragmentExtra} letting a material fragment shader push its output into the A-buffer via
@@ -3892,7 +3956,7 @@
3892
3956
  */
3893
3957
  function aBufferFragmentExtra(group = UNIFORM_GROUP_INDEX_CAMERA) {
3894
3958
  return {
3895
- definitions: [FRAGMENT_STRUCT, INFO_STRUCT, `struct ABufferHeads {
3959
+ definitions: [FRAGMENT_STRUCT, INFO_STRUCT, DEPTH_DIRECTION, `struct ABufferHeads {
3896
3960
  count: atomic<u32>,
3897
3961
  data: array<atomic<u32>>,
3898
3962
  }`],
@@ -3914,7 +3978,7 @@
3914
3978
  }
3915
3979
  // manual depth test against the opaque geometry
3916
3980
  let opaqueDepth = textureLoad(aBufferOpaqueDepth, pixel, 0);
3917
- if (position.z >= opaqueDepth) {
3981
+ if (!aBufferCloser(position.z, opaqueDepth)) {
3918
3982
  return;
3919
3983
  }
3920
3984
  let slot = atomicAdd(&aBufferHeads.count, 1u);
@@ -3941,6 +4005,8 @@
3941
4005
 
3942
4006
  ${INFO_STRUCT}
3943
4007
 
4008
+ ${DEPTH_DIRECTION}
4009
+
3944
4010
  struct ABufferHeads {
3945
4011
  count: u32,
3946
4012
  data: array<u32>,
@@ -3976,7 +4042,7 @@ const MAX_LAYERS = ${ABUFFER_MAX_SORTED_LAYERS}u;
3976
4042
  for (var i = 1u; i < count; i++) {
3977
4043
  let item = layers[i];
3978
4044
  var j = i;
3979
- while (j > 0u && layers[j - 1u].depth < item.depth) {
4045
+ while (j > 0u && aBufferCloser(layers[j - 1u].depth, item.depth)) {
3980
4046
  layers[j] = layers[j - 1u];
3981
4047
  j--;
3982
4048
  }
@@ -4808,7 +4874,11 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4808
4874
  * `references.outputColor` (`+=`) when provided, or a bare expression otherwise (for single-light use sites that
4809
4875
  * assign it directly).
4810
4876
  *
4811
- * @param references WGSL identifiers for the surface normal (`normal`), the base color to shade (`inputColor`) and, optionally, the color variable to accumulate into (`outputColor`).
4877
+ * A shadow-casting light (`references.shadowLayer`) scales only the lit half of the (half-Lambert) diffuse term by the
4878
+ * shadow visibility, so that shadowed surfaces get as dark as the ones at the terminator and the surfaces facing away
4879
+ * from the light stay untouched: `.5 * (1 + min(n·l, 0) + visibility * max(n·l, 0))`.
4880
+ *
4881
+ * @param references WGSL identifiers for the surface normal (`normal`), the base color to shade (`inputColor`), optionally the color variable to accumulate into (`outputColor`) and, for shadows, the world-space position (`position`) and the light's shadow map layer (`shadowLayer`).
4812
4882
  * @param group `@group` index at which the generated `DirectionalLight` uniform is bound.
4813
4883
  * @param binding `@binding` index (within `group`) at which the generated `DirectionalLight` uniform is bound.
4814
4884
  * @returns Fragment-shader `definitions`/`bindings`/`modifiers` meant to be spliced into a material fragment shader (see {@link getBasicMaterialFragmentWgsl}/{@link getStandardMaterialFragmentWgsl}).
@@ -4817,27 +4887,35 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4817
4887
  const key = pacemCore.Utils.uniqueCode();
4818
4888
  const lightReference = `directional_${key}`;
4819
4889
  const ref = pacemCore.Utils.extend({}, DefaultDirectionalLightReferences, references);
4820
- const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal ?? 'normal';
4890
+ const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal ?? 'normal', shadowLayer = ref.shadowLayer;
4821
4891
  if (pacemCore.Utils.isNullOrEmpty(inputColor)) {
4822
4892
  throw new Error('Must provide input vertex color parameter name.');
4823
4893
  }
4894
+ const casting = Number.isInteger(shadowLayer);
4895
+ if (casting && pacemCore.Utils.isNullOrEmpty(ref.position)) {
4896
+ throw new Error('Must provide the world position parameter name of a shadow-casting light.');
4897
+ }
4898
+ const visibility = casting ? `shadowVisibility(${shadowLayer}u, ${ref.position}, ${normal})` : '1.0';
4899
+ const contribution = `computeDirectional(${normal}, ${inputColor}, ${lightReference}, ${visibility})`;
4824
4900
  return {
4825
4901
  // type definitions
4826
4902
  definitions: [`struct DirectionalLight {
4827
4903
  color: vec4f,
4828
4904
  direction: vec3f,
4829
4905
  intensity: f32
4830
- }`, `fn computeDirectional(normal: vec3f, color: vec4f, light: DirectionalLight) -> vec4f {
4906
+ }`, `fn computeDirectional(normal: vec3f, color: vec4f, light: DirectionalLight, visibility: f32) -> vec4f {
4831
4907
  let n = normalize(normal);
4832
4908
  let d = normalize(light.direction);
4833
- let factor = light.intensity * .5 * (1.0 + dot(n, -d));
4909
+ let ndl = dot(n, -d);
4910
+ // half-Lambert: the shadow (visibility < 1) only dims the lit half
4911
+ let factor = light.intensity * .5 * (1.0 + min(ndl, 0.0) + visibility * max(ndl, 0.0));
4834
4912
  let output = color.rgb * light.color.rgb * factor;
4835
4913
  return vec4f(output, color.a);
4836
4914
  }`],
4837
4915
  // bindings
4838
4916
  bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: DirectionalLight;`],
4839
4917
  // modifiers
4840
- modifiers: outputColor ? [`${outputColor} += computeDirectional(${normal}, ${inputColor}, ${lightReference});`] : [`computeDirectional(${normal}, ${inputColor}, ${lightReference})`]
4918
+ modifiers: outputColor ? [`${outputColor} += ${contribution};`] : [contribution]
4841
4919
  };
4842
4920
  }
4843
4921
 
@@ -4866,27 +4944,31 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4866
4944
  const key = pacemCore.Utils.uniqueCode();
4867
4945
  const lightReference = `omni_${key}`;
4868
4946
  const ref = pacemCore.Utils.extend({}, DefaultOmniLightReferences, references);
4869
- const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal, ray = ref.ray, vertex = ref.position, shininess = ref.shininess, specularColor = ref.specularColor;
4947
+ const inputColor = ref.inputColor, outputColor = ref.outputColor, normal = ref.normal, ray = ref.ray, vertex = ref.position, shininess = ref.shininess, specularColor = ref.specularColor, shadowLayer = ref.shadowLayer;
4870
4948
  if (pacemCore.Utils.isNullOrEmpty(inputColor)) {
4871
4949
  throw new Error('Must provide input vertex color parameter name.');
4872
4950
  }
4951
+ const casting = Number.isInteger(shadowLayer);
4952
+ const visibility = casting ? `shadowVisibilityOmni(${shadowLayer}u, ${lightReference}.position, ${vertex}, ${normal})` : '1.0';
4953
+ const contribution = `computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference}, ${visibility})`;
4873
4954
  return {
4874
4955
  // type definitions
4875
4956
  definitions: [`struct OmniLight {
4876
4957
  color: vec4f,
4877
4958
  position: vec3f,
4878
4959
  intensity: f32
4879
- }`, `fn computeOmni(position: vec3f, normal: vec3f, ray: vec3f, color: vec4f, specularColor: vec4f, shininess: f32, light: OmniLight) -> vec4f {
4960
+ }`, `fn computeOmni(position: vec3f, normal: vec3f, ray: vec3f, color: vec4f, specularColor: vec4f, shininess: f32, light: OmniLight, visibility: f32) -> vec4f {
4880
4961
 
4881
- // color
4962
+ // color (half-Lambert: the shadow, visibility < 1, only dims the lit half)
4882
4963
  let n = normalize(normal);
4883
4964
  let d = normalize(position - light.position);
4884
- let factor = light.intensity * .5 * (1.0 + dot(n, -d));
4965
+ let ndl = dot(n, -d);
4966
+ let factor = light.intensity * .5 * (1.0 + min(ndl, 0.0) + visibility * max(ndl, 0.0));
4885
4967
 
4886
- // specular
4968
+ // specular (no highlight in the shadow)
4887
4969
  let r = normalize(ray);
4888
4970
  let halfVector = normalize(d + r);
4889
- let specular = specularColor.rgb * shininess * dot(n, -halfVector);
4971
+ let specular = specularColor.rgb * shininess * dot(n, -halfVector) * visibility;
4890
4972
 
4891
4973
  let output = color.rgb * light.color.rgb * factor + specular;
4892
4974
  return vec4f(output, color.a);
@@ -4894,7 +4976,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4894
4976
  // bindings
4895
4977
  bindings: [`@group(${group}) @binding(${binding}) var<uniform> ${lightReference}: OmniLight;`],
4896
4978
  // modifiers
4897
- modifiers: outputColor ? [`${outputColor} += computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference});`] : [`computeOmni(${vertex}, ${normal}, ${ray}, ${inputColor}, ${specularColor}, ${shininess}, ${lightReference})`]
4979
+ modifiers: outputColor ? [`${outputColor} += ${contribution};`] : [contribution]
4898
4980
  };
4899
4981
  }
4900
4982
 
@@ -4937,8 +5019,80 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4937
5019
  }
4938
5020
 
4939
5021
  //namespace Pacem.Drawing3D.WebGPU {
4940
- const Vector3D$3 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
4941
- const Matrix3D$2 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
5022
+ /*
5023
+ * Shadow mapping (receiver side), after https://webgpu.github.io/webgpu-samples/?sample=shadowMapping
5024
+ *
5025
+ * Each casting light owns layers of a depth texture array, holding the depth of the closest occluders as seen from
5026
+ * the light (see `shadows.ts`): one layer for a directional light, six (the faces of a cube) for an omni light.
5027
+ * A fragment is lit when its own light-space depth isn't farther than that.
5028
+ */
5029
+ /** WGSL layout of one casting light (80 bytes, a multiple of 16 as uniform arrays require): mirrored by `shadows.ts`. */
5030
+ const SHADOW_LIGHT_STRUCT = `struct ShadowLight {
5031
+ viewProjection: mat4x4f,
5032
+ normalOffset: f32,
5033
+ texelSize: f32,
5034
+ padding0: f32,
5035
+ padding1: f32,
5036
+ }`;
5037
+ const SHADOW_VISIBILITY_FUNCTION = `fn shadowVisibility(layer: u32, position: vec3f, normal: vec3f) -> f32 {
5038
+ let light = shadowLights[layer];
5039
+
5040
+ // normal offset: the receiver is pushed off its surface along the normal before being projected (fights acne)
5041
+ let offsetPosition = position + normalize(normal) * light.normalOffset;
5042
+ let clip = light.viewProjection * vec4f(offsetPosition, 1.0);
5043
+ let ndc = clip.xyz / clip.w;
5044
+
5045
+ // NDC (y up) to texture coordinates (v down)
5046
+ let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
5047
+ let outside = any(uv < vec2f(0.0)) || any(uv > vec2f(1.0)) || ndc.z > 1.0;
5048
+ if (outside) {
5049
+ return 1.0;
5050
+ }
5051
+
5052
+ // 3x3 percentage-closer filtering: each tap compares in hardware, bilinearly weighted
5053
+ var lit = 0.0;
5054
+ for (var y = -1; y <= 1; y++) {
5055
+ for (var x = -1; x <= 1; x++) {
5056
+ let offset = vec2f(f32(x), f32(y)) * light.texelSize;
5057
+ lit += textureSampleCompareLevel(shadowMap, shadowSampler, uv + offset, layer, ndc.z);
5058
+ }
5059
+ }
5060
+ return lit / 9.0;
5061
+ }`;
5062
+ const SHADOW_VISIBILITY_OMNI_FUNCTION = `fn shadowVisibilityOmni(firstLayer: u32, lightPosition: vec3f, position: vec3f, normal: vec3f) -> f32 {
5063
+ // the cube face along the major axis of the light-to-fragment vector (+x, -x, +y, -y, +z, -z: see shadows.ts)
5064
+ let v = position - lightPosition;
5065
+ let a = abs(v);
5066
+ var face = select(1u, 0u, v.x > 0.0);
5067
+ if (a.y >= a.x && a.y >= a.z) {
5068
+ face = select(3u, 2u, v.y > 0.0);
5069
+ }
5070
+ if (a.z >= a.x && a.z >= a.y) {
5071
+ face = select(5u, 4u, v.z > 0.0);
5072
+ }
5073
+ return shadowVisibility(firstLayer + face, position, normal);
5074
+ }`;
5075
+ /**
5076
+ * Builds the {@link WGSLFragmentExtra} letting a material fragment shader test a world-space position against the
5077
+ * shadow maps via `shadowVisibility(layer, position, normal)` (directional lights) or
5078
+ * `shadowVisibilityOmni(firstLayer, lightPosition, position, normal)` (omni lights), which return the lit fraction in `[0, 1]`.
5079
+ * @param group `@group` index of the shadow bindings (the lighting group).
5080
+ */
5081
+ function shadowFragmentExtra(group) {
5082
+ return {
5083
+ definitions: [SHADOW_LIGHT_STRUCT, SHADOW_VISIBILITY_FUNCTION, SHADOW_VISIBILITY_OMNI_FUNCTION],
5084
+ bindings: [
5085
+ `@group(${group}) @binding(${SHADOW_BINDING_MAP}) var shadowMap: texture_depth_2d_array;`,
5086
+ `@group(${group}) @binding(${SHADOW_BINDING_SAMPLER}) var shadowSampler: sampler_comparison;`,
5087
+ `@group(${group}) @binding(${SHADOW_BINDING_LIGHTS}) var<uniform> shadowLights: array<ShadowLight, ${MAX_SHADOW_LAYERS}>;`
5088
+ ],
5089
+ modifiers: []
5090
+ };
5091
+ }
5092
+
5093
+ //namespace Pacem.Drawing3D.WebGPU {
5094
+ const Vector3D$4 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
5095
+ const Matrix3D$4 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
4942
5096
  const DEFAULT_SIZE = { width: 1, height: 1 };
4943
5097
  /**
4944
5098
  * Factory that converts a scene-facing {@link Camera3D} (`../../types.ts`) into its WebGPU-side counterpart
@@ -4969,16 +5123,16 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
4969
5123
  * @returns
4970
5124
  */
4971
5125
  function view(eye, target, up) {
4972
- const z = /* inverse forward is eye -> target */ Vector3D$3.subtract(target, eye);
4973
- const x = Vector3D$3.cross(up, z);
4974
- const y = Vector3D$3.cross(z, x);
4975
- Vector3D$3.normalize(x);
4976
- Vector3D$3.normalize(z);
4977
- Vector3D$3.normalize(y);
4978
- const offsetX = -Vector3D$3.dot(x, eye);
4979
- const offsetY = -Vector3D$3.dot(y, eye);
4980
- const offsetZ = -Vector3D$3.dot(z, eye);
4981
- return Matrix3D$2.from(x.x, y.x, z.x, 0, x.y, y.y, z.y, 0, x.z, y.z, z.z, 0, offsetX, offsetY, offsetZ, 1);
5126
+ const z = /* inverse forward is eye -> target */ Vector3D$4.subtract(target, eye);
5127
+ const x = Vector3D$4.cross(up, z);
5128
+ const y = Vector3D$4.cross(z, x);
5129
+ Vector3D$4.normalize(x);
5130
+ Vector3D$4.normalize(z);
5131
+ Vector3D$4.normalize(y);
5132
+ const offsetX = -Vector3D$4.dot(x, eye);
5133
+ const offsetY = -Vector3D$4.dot(y, eye);
5134
+ const offsetZ = -Vector3D$4.dot(z, eye);
5135
+ return Matrix3D$4.from(x.x, y.x, z.x, 0, x.y, y.y, z.y, 0, x.z, y.z, z.z, 0, offsetX, offsetY, offsetZ, 1);
4982
5136
  }
4983
5137
  function assertNearFarCorrectness(near, far) {
4984
5138
  if (near <= 0) {
@@ -5003,7 +5157,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
5003
5157
  const finitelyFar = Number.isFinite(far);
5004
5158
  const m33 = finitelyFar ? (far / (near - far)) : -1;
5005
5159
  const offsetZ = finitelyFar ? (far * near / (near - far)) : -near;
5006
- return Matrix3D$2.from(m11, 0, 0, 0, 0, scale, 0, 0, 0, 0, m33, -1, 0, 0, offsetZ, 0);
5160
+ return Matrix3D$4.from(m11, 0, 0, 0, 0, scale, 0, 0, 0, 0, m33, -1, 0, 0, offsetZ, 0);
5007
5161
  }
5008
5162
  /**
5009
5163
  * Othographic transformation 4x4 matrix.
@@ -5016,7 +5170,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
5016
5170
  */
5017
5171
  function orthographic(left, right, top, bottom, near = .1, far = 1000) {
5018
5172
  assertNearFarCorrectness(near, far);
5019
- return Matrix3D$2.from(2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, 1 / (near - far), 0, (left + right) / (left - right), (top + bottom) / (bottom - top), near / (near - far), 1);
5173
+ return Matrix3D$4.from(2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, 1 / (near - far), 0, (left + right) / (left - right), (top + bottom) / (bottom - top), near / (near - far), 1);
5020
5174
  }
5021
5175
  /**
5022
5176
  * WebGPU-side counterpart of an {@link OrthographicCamera3D}: computes the view matrix from `position`/`lookAt`/`up`,
@@ -5038,9 +5192,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
5038
5192
  */
5039
5193
  static projection(camera, size = DEFAULT_SIZE) {
5040
5194
  const eye = camera.position, target = camera.lookAt;
5041
- const z = Vector3D$3.subtract(target, eye);
5042
- Vector3D$3.normalize(z);
5043
- const zoom = Vector3D$3.dot(z, eye);
5195
+ const z = Vector3D$4.subtract(target, eye);
5196
+ Vector3D$4.normalize(z);
5197
+ const zoom = Vector3D$4.dot(z, eye);
5044
5198
  const { height, width } = size;
5045
5199
  const ratio = width / height;
5046
5200
  const factor = .5 * zoom;
@@ -5090,6 +5244,398 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
5090
5244
  }
5091
5245
  }
5092
5246
 
5247
+ //namespace Pacem.Drawing3D.WebGPU {
5248
+ const Vector3D$3 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
5249
+ const Matrix3D$3 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
5250
+ /** Floats of one `ShadowLight` (see `wgsl/shadow-fragment.ts`): `viewProjection` (16), `normalOffset`, `texelSize` and 2 paddings. */
5251
+ const SHADOW_LIGHT_FLOATS = 20;
5252
+ /** Floats of the camera uniform (see `wgsl/mesh-vertex.ts`): `view` (16), `projection` (16, view-projection), `position` (3 + padding). */
5253
+ const CAMERA_FLOATS = 36;
5254
+ const MIN_MAP_SIZE = 256;
5255
+ /**
5256
+ * Field of view, in degrees, of each cube face of an omni light: a bit wider than 90° so that neighboring faces
5257
+ * overlap and the filtering taps near a face edge still land on rendered depth.
5258
+ */
5259
+ const CUBE_FACE_FOV = 95;
5260
+ /**
5261
+ * The 6 faces of an omni light's shadow cube, in layer order (`+x, -x, +y, -y, +z, -z`): the receivers pick the face
5262
+ * along the major axis of the light-to-fragment vector in the very same order (see `wgsl/shadow-fragment.ts`).
5263
+ */
5264
+ const CUBE_FACES = [
5265
+ { axis: { x: 1, y: 0, z: 0 }, up: { x: 0, y: 1, z: 0 } },
5266
+ { axis: { x: -1, y: 0, z: 0 }, up: { x: 0, y: 1, z: 0 } },
5267
+ { axis: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
5268
+ { axis: { x: 0, y: -1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
5269
+ { axis: { x: 0, y: 0, z: 1 }, up: { x: 0, y: 1, z: 0 } },
5270
+ { axis: { x: 0, y: 0, z: -1 }, up: { x: 0, y: 1, z: 0 } }
5271
+ ];
5272
+ /** Whether a light casts shadows: directional and omni lights only. */
5273
+ function isShadowCaster(light) {
5274
+ if (light.castShadow !== true) {
5275
+ return false;
5276
+ }
5277
+ return light.type === 'direction' || light.type === 'omni';
5278
+ }
5279
+ /** Number of shadow map layers a casting light needs: one for a directional light, a cube (6 faces) for an omni light. */
5280
+ function shadowLayerCount(light) {
5281
+ return light.type === 'omni' ? CUBE_FACES.length : 1;
5282
+ }
5283
+ /**
5284
+ * Assigns each shadow-casting item (in order) its first shadow map layer, skipping the casters that wouldn't fit in
5285
+ * the {@link MAX_SHADOW_LAYERS} available. Shared by the shader builder and the renderer, so that both agree on the layout.
5286
+ * @param items Lights, or anything wrapping one.
5287
+ * @param lightOf Gets the light of an item.
5288
+ */
5289
+ function allocateShadowLayers(items, lightOf) {
5290
+ const layers = new Map();
5291
+ let next = 0;
5292
+ for (let item of items) {
5293
+ const light = lightOf(item);
5294
+ if (!isShadowCaster(light)) {
5295
+ continue;
5296
+ }
5297
+ const count = shadowLayerCount(light);
5298
+ if (next + count > MAX_SHADOW_LAYERS) {
5299
+ continue;
5300
+ }
5301
+ layers.set(item, next);
5302
+ next += count;
5303
+ }
5304
+ return layers;
5305
+ }
5306
+ /** Whether a mesh gets drawn into the shadow maps. */
5307
+ function castsShadow(mesh) {
5308
+ return mesh.castShadow !== false;
5309
+ }
5310
+ /** Whether a mesh's lighting reads the shadow maps. */
5311
+ function receivesShadow(mesh) {
5312
+ return mesh.receiveShadow !== false;
5313
+ }
5314
+ /** Transforms a (local) point by a row-major world matrix, laid out as `Matrix3D.toArray` (row vectors, translation in the last row). */
5315
+ function transformPoint(m, x, y, z) {
5316
+ return {
5317
+ x: x * m[0] + y * m[4] + z * m[8] + m[12],
5318
+ y: x * m[1] + y * m[5] + z * m[9] + m[13],
5319
+ z: x * m[2] + y * m[6] + z * m[10] + m[14]
5320
+ };
5321
+ }
5322
+ /** Grows `box` so that it encloses `point`. */
5323
+ function enclose(box, point) {
5324
+ box.minX = Math.min(box.minX, point.x);
5325
+ box.minY = Math.min(box.minY, point.y);
5326
+ box.minZ = Math.min(box.minZ, point.z);
5327
+ box.maxX = Math.max(box.maxX, point.x);
5328
+ box.maxY = Math.max(box.maxY, point.y);
5329
+ box.maxZ = Math.max(box.maxZ, point.z);
5330
+ }
5331
+ /** `origin + scale * direction`. */
5332
+ function along(origin, direction, scale) {
5333
+ return { x: origin.x + scale * direction.x, y: origin.y + scale * direction.y, z: origin.z + scale * direction.z };
5334
+ }
5335
+ /**
5336
+ * The "camera" a shadow map layer is rendered from: a {@link ManagedBuffer} exposing the same `cameraViewTransform`
5337
+ * uniform layout as a real camera, so that the mesh vertex shader works unchanged.
5338
+ */
5339
+ class ShadowCamera {
5340
+ #buffer;
5341
+ #disposed = false;
5342
+ constructor(_device, _index) {
5343
+ this._device = _device;
5344
+ this._index = _index;
5345
+ }
5346
+ /** Uploads the layer's view and view-projection matrices (and its eye position). */
5347
+ write(light, viewMatrix, viewProjection, eye) {
5348
+ this.item = light;
5349
+ const viewArray = Matrix3D$3.toArray(viewMatrix), viewProjectionArray = Matrix3D$3.toArray(viewProjection);
5350
+ const value = new Float32Array(CAMERA_FLOATS);
5351
+ value.set(viewArray, 0);
5352
+ value.set(viewProjectionArray, 16);
5353
+ value.set([eye.x, eye.y, eye.z], 32);
5354
+ const current = this.#buffer;
5355
+ if (!pacemCore.Utils.isNull(current)) {
5356
+ Buffers.write(this._device, current.buffer, value);
5357
+ current.value = value;
5358
+ current.version = performance.now();
5359
+ return;
5360
+ }
5361
+ const buffer = Buffers.createUniform(this._device, value, LABEL_PREFIX + 'shadow-camera-' + this._index + '-buffer');
5362
+ this.#buffer = { buffer, value, version: performance.now() };
5363
+ }
5364
+ buffer(_, key) {
5365
+ if (key !== 'cameraViewTransform') {
5366
+ throw new Error(`Buffer "${key}" not available on a shadow camera.`);
5367
+ }
5368
+ return this.#buffer;
5369
+ }
5370
+ texture(_) {
5371
+ throw new Error('Method not implemented.');
5372
+ }
5373
+ lock() {
5374
+ }
5375
+ unlock() {
5376
+ }
5377
+ destroy() {
5378
+ this.#buffer?.buffer.destroy();
5379
+ this.#buffer = null;
5380
+ this.#disposed = true;
5381
+ }
5382
+ get disposed() {
5383
+ return this.#disposed;
5384
+ }
5385
+ }
5386
+ /**
5387
+ * Shadow maps of the shadow-casting lights, one set per renderer ({@link Context}): a depth texture array (one layer
5388
+ * per directional light, six per omni light, at most {@link MAX_SHADOW_LAYERS}), its comparison sampler, the uniform
5389
+ * array of the per-layer light-space matrices read by the receivers, and the "cameras" the depth-only passes render from.
5390
+ *
5391
+ * A directional light renders through an orthographic projection fitted to the bounding sphere of the visible meshes,
5392
+ * looking along the light direction (from `position` to `target`). An omni light renders a cube: six perspective
5393
+ * projections from its position, one per axis, reaching the far side of that same sphere.
5394
+ */
5395
+ class Shadows {
5396
+ static { this._instances = new WeakMap(); }
5397
+ /** Gets the shadow resources of `ctx`, creating them on first use. */
5398
+ static ensure(ctx) {
5399
+ const existing = this._instances.get(ctx);
5400
+ if (!pacemCore.Utils.isNull(existing)) {
5401
+ return existing;
5402
+ }
5403
+ const created = new Shadows(ctx);
5404
+ this._instances.set(ctx, created);
5405
+ return created;
5406
+ }
5407
+ /** Gets the shadow resources of `ctx`, if any. */
5408
+ static of(ctx) {
5409
+ return this._instances.get(ctx) ?? null;
5410
+ }
5411
+ /** Destroys the shadow resources of `ctx`, if any. */
5412
+ static dispose(ctx) {
5413
+ const existing = this._instances.get(ctx);
5414
+ this._instances.delete(ctx);
5415
+ existing?.destroy();
5416
+ }
5417
+ #sampler;
5418
+ #lights;
5419
+ #texture;
5420
+ #map;
5421
+ #layers = [];
5422
+ #cameras = [];
5423
+ #layerCount = 0;
5424
+ constructor(_context) {
5425
+ this._context = _context;
5426
+ const { device } = _context;
5427
+ this.#sampler = device.createSampler({
5428
+ label: LABEL_PREFIX + 'shadow-sampler',
5429
+ compare: 'less',
5430
+ magFilter: 'linear',
5431
+ minFilter: 'linear',
5432
+ addressModeU: 'clamp-to-edge',
5433
+ addressModeV: 'clamp-to-edge'
5434
+ });
5435
+ const lights = new Float32Array(SHADOW_LIGHT_FLOATS * MAX_SHADOW_LAYERS);
5436
+ this.#lights = Buffers.createUniform(device, lights, LABEL_PREFIX + 'shadow-lights-buffer');
5437
+ }
5438
+ /** View of all the shadow map layers (`texture_depth_2d_array`), bound to the receivers. */
5439
+ get map() {
5440
+ return this.#map;
5441
+ }
5442
+ /** Comparison sampler of the shadow maps. */
5443
+ get sampler() {
5444
+ return this.#sampler;
5445
+ }
5446
+ /** Uniform array of the shadow map layers (`array<ShadowLight, MAX_SHADOW_LAYERS>`). */
5447
+ get lights() {
5448
+ return this.#lights;
5449
+ }
5450
+ /** Number of shadow map layers rendered by the last {@link update}. */
5451
+ get layerCount() {
5452
+ return this.#layerCount;
5453
+ }
5454
+ /** Render target (depth attachment) of the `index`-th shadow map layer. */
5455
+ layer(index) {
5456
+ return this.#layers.at(index);
5457
+ }
5458
+ /** Camera-like buffer the `index`-th shadow map layer renders from. */
5459
+ camera(index) {
5460
+ return this.#cameras.at(index);
5461
+ }
5462
+ /**
5463
+ * Fits the light-space projections of `casters` (as laid out by {@link allocateShadowLayers}) to the visible
5464
+ * `meshes` and uploads them, (re)creating the shadow maps when their size or layer count changes.
5465
+ */
5466
+ update(casters, meshes) {
5467
+ const counts = casters.map(c => c.firstLayer + shadowLayerCount(c.light));
5468
+ const layerCount = Math.max(0, ...counts);
5469
+ const lights = casters.map(c => c.light);
5470
+ const size = this._mapSize(lights);
5471
+ this._ensureTexture(size, Math.max(1, layerCount));
5472
+ this._ensureCameras(layerCount);
5473
+ this.#layerCount = layerCount;
5474
+ const sphere = this._boundingSphere(meshes);
5475
+ const values = new Float32Array(SHADOW_LIGHT_FLOATS * MAX_SHADOW_LAYERS);
5476
+ for (let { light, firstLayer } of casters) {
5477
+ if (light.type === 'omni') {
5478
+ this._updateOmniLight(light, sphere, size, firstLayer, values);
5479
+ }
5480
+ else {
5481
+ this._updateDirectionalLight(light, sphere, size, firstLayer, values);
5482
+ }
5483
+ }
5484
+ Buffers.write(this._context.device, this.#lights, values);
5485
+ }
5486
+ /** Writes the `layer`-th camera and its `ShadowLight` uniform entry. */
5487
+ _writeLayer(light, layer, viewMatrix, projection, eye, normalOffset, size, values) {
5488
+ const viewProjection = Matrix3D$3.multiply(viewMatrix, projection);
5489
+ this.#cameras.at(layer).write(light, viewMatrix, viewProjection, eye);
5490
+ const offset = SHADOW_LIGHT_FLOATS * layer;
5491
+ const viewProjectionArray = Matrix3D$3.toArray(viewProjection);
5492
+ values.set(viewProjectionArray, offset);
5493
+ values.set([normalOffset, 1 / size], offset + 16);
5494
+ }
5495
+ _updateDirectionalLight(light, sphere, size, layer, values) {
5496
+ const { center, radius } = sphere;
5497
+ // rays travel from the light's position toward its target
5498
+ const position = light.position ?? Vector3D$3.zero();
5499
+ const target = light.target ?? Vector3D$3.zero();
5500
+ const direction = { x: target.x - position.x, y: target.y - position.y, z: target.z - position.z };
5501
+ const length = Vector3D$3.mag(direction);
5502
+ const dir = length > 0 ? { x: direction.x / length, y: direction.y / length, z: direction.z / length } : { x: 0, y: -1, z: 0 };
5503
+ // the eye sits upstream, two radii from the center: the sphere spans [r, 3r] along the view direction
5504
+ const eye = along(center, dir, -2 * radius);
5505
+ const up = Math.abs(dir.y) > .99 ? { x: 0, y: 0, z: 1 } : { x: 0, y: 1, z: 0 };
5506
+ const viewMatrix = view(eye, center, up);
5507
+ const projection = orthographic(-radius, radius, radius, -radius, .5 * radius, 3.5 * radius);
5508
+ const bias = light.shadowBias ?? .002;
5509
+ this._writeLayer(light, layer, viewMatrix, projection, eye, bias * radius, size, values);
5510
+ }
5511
+ _updateOmniLight(light, sphere, size, firstLayer, values) {
5512
+ const { center, radius } = sphere;
5513
+ const eye = light.position ?? Vector3D$3.zero();
5514
+ // the cube reaches the far side of the scene sphere; the near plane trades reach for depth precision
5515
+ const toCenter = { x: center.x - eye.x, y: center.y - eye.y, z: center.z - eye.z };
5516
+ const distance = Vector3D$3.mag(toCenter);
5517
+ const far = distance + radius;
5518
+ const near = Math.max(.002 * far, .01);
5519
+ const projection = perspective(CUBE_FACE_FOV, 1, near, far);
5520
+ const bias = light.shadowBias ?? .002;
5521
+ for (let i = 0; i < CUBE_FACES.length; i++) {
5522
+ const { axis, up } = CUBE_FACES[i];
5523
+ const target = along(eye, axis, 1);
5524
+ const viewMatrix = view(eye, target, up);
5525
+ this._writeLayer(light, firstLayer + i, viewMatrix, projection, eye, bias * far, size, values);
5526
+ }
5527
+ }
5528
+ /** World-space bounding sphere of the visible meshes (the one enclosing their world-space bounding box). */
5529
+ _boundingSphere(meshes) {
5530
+ const ctx = this._context;
5531
+ const box = { minX: +Infinity, minY: +Infinity, minZ: +Infinity, maxX: -Infinity, maxY: -Infinity, maxZ: -Infinity };
5532
+ for (let buffer of meshes) {
5533
+ const mesh = buffer.item;
5534
+ const local = mesh.geometry?.boundingBox;
5535
+ if (buffer.disposed || mesh.hide || pacemCore.Utils.isNull(local) || !Number.isFinite(local.minX)) {
5536
+ continue;
5537
+ }
5538
+ // the world matrix as uploaded for the vertex shader (refreshed if stale)
5539
+ const { value: world } = buffer.buffer(ctx, 'objectWorldTransform');
5540
+ for (let x of [local.minX, local.maxX]) {
5541
+ for (let y of [local.minY, local.maxY]) {
5542
+ for (let z of [local.minZ, local.maxZ]) {
5543
+ const corner = transformPoint(world, x, y, z);
5544
+ enclose(box, corner);
5545
+ }
5546
+ }
5547
+ }
5548
+ }
5549
+ if (!Number.isFinite(box.minX)) {
5550
+ return { center: Vector3D$3.zero(), radius: 1 };
5551
+ }
5552
+ const center = { x: (box.minX + box.maxX) / 2, y: (box.minY + box.maxY) / 2, z: (box.minZ + box.maxZ) / 2 };
5553
+ const halfDiagonal = { x: (box.maxX - box.minX) / 2, y: (box.maxY - box.minY) / 2, z: (box.maxZ - box.minZ) / 2 };
5554
+ const radius = Vector3D$3.mag(halfDiagonal);
5555
+ return { center, radius: radius > 0 ? radius : 1 };
5556
+ }
5557
+ /** Side of the shadow maps: the largest requested one, within the device limits. */
5558
+ _mapSize(casters) {
5559
+ const sizes = casters.map(l => l.shadowMapSize || 0);
5560
+ const requested = Math.max(MIN_MAP_SIZE, ...sizes);
5561
+ const rounded = Math.round(requested);
5562
+ const limit = this._context.device.limits.maxTextureDimension2D;
5563
+ return Math.min(rounded, limit);
5564
+ }
5565
+ _ensureTexture(size, layers) {
5566
+ const current = this.#texture;
5567
+ if (!pacemCore.Utils.isNull(current) && current.width === size && current.depthOrArrayLayers === layers) {
5568
+ return;
5569
+ }
5570
+ current?.destroy();
5571
+ const texture = this.#texture = this._context.device.createTexture({
5572
+ label: LABEL_PREFIX + 'shadow-map',
5573
+ format: SHADOW_MAP_FORMAT,
5574
+ size: [size, size, layers],
5575
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
5576
+ });
5577
+ this.#map = texture.createView({ label: LABEL_PREFIX + 'shadow-map-view', dimension: '2d-array' });
5578
+ this.#layers = Array.from({ length: layers }, (_, i) => texture.createView({
5579
+ label: LABEL_PREFIX + 'shadow-map-layer-' + i, dimension: '2d', baseArrayLayer: i, arrayLayerCount: 1
5580
+ }));
5581
+ }
5582
+ _ensureCameras(count) {
5583
+ const cameras = this.#cameras;
5584
+ const { device } = this._context;
5585
+ while (cameras.length < count) {
5586
+ const camera = new ShadowCamera(device, cameras.length);
5587
+ cameras.push(camera);
5588
+ }
5589
+ }
5590
+ destroy() {
5591
+ this.#texture?.destroy();
5592
+ this.#texture = null;
5593
+ this.#lights.destroy();
5594
+ for (let camera of this.#cameras) {
5595
+ camera.destroy();
5596
+ }
5597
+ this.#cameras = [];
5598
+ }
5599
+ }
5600
+
5601
+ //namespace Pacem.Drawing3D.WebGPU {
5602
+ const Matrix3D$2 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
5603
+ /** Standard depth: near → 0, far → 1, closer fragments have a lower depth. */
5604
+ const STANDARD_DEPTH = Object.freeze({
5605
+ reversed: false,
5606
+ format: 'depth24plus',
5607
+ compare: 'less',
5608
+ clearValue: 1
5609
+ });
5610
+ /**
5611
+ * Reversed-Z depth: near → 1, far → 0, closer fragments have a greater depth. Paired with a floating point depth
5612
+ * buffer, the float precision (dense around 0) compensates the perspective one (dense around the near plane),
5613
+ * spreading the depth resolution evenly over distance.
5614
+ */
5615
+ const REVERSED_DEPTH = Object.freeze({
5616
+ reversed: true,
5617
+ format: 'depth32float',
5618
+ compare: 'greater',
5619
+ clearValue: 0
5620
+ });
5621
+ /**
5622
+ * Maps a standard (near → 0, far → 1) projection matrix onto the depth range of `depth`.
5623
+ * Reversed-Z replaces the clip-space `z` with `w - z`, i.e. the projection gets post-multiplied by the depth-range remap matrix.
5624
+ * @param projection Standard projection matrix (perspective or orthographic).
5625
+ * @param depth Depth setup of the renderer.
5626
+ */
5627
+ function toDepthRange(projection, depth) {
5628
+ if (!depth.reversed) {
5629
+ return projection;
5630
+ }
5631
+ const m = Matrix3D$2.clone(projection);
5632
+ m.m13 = projection.m14 - projection.m13;
5633
+ m.m23 = projection.m24 - projection.m23;
5634
+ m.m33 = projection.m34 - projection.m33;
5635
+ m.offsetZ = projection.m44 - projection.offsetZ;
5636
+ return m;
5637
+ }
5638
+
5093
5639
  //namespace Pacem.Drawing3D.WebGPU {
5094
5640
  const Vector3D$2 = pacemNumerical.Geometry.LinearAlgebra.Vector3D;
5095
5641
  const Matrix3D$1 = pacemNumerical.Geometry.LinearAlgebra.Matrix3D;
@@ -5487,12 +6033,14 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
5487
6033
  const size = this.#size;
5488
6034
  return size.width !== canvas.width || size.height !== canvas.height;
5489
6035
  }
5490
- _rebuildMatrices({ device, canvas }) {
6036
+ _rebuildMatrices({ device, canvas, depth }) {
5491
6037
  const cam = this.item;
5492
6038
  const camera = Cameras.create(cam);
5493
6039
  const { x, y, z } = cam.position;
5494
6040
  const view = camera.view();
5495
- const projection = camera.projection(canvas);
6041
+ // cameras project onto the standard depth range: the renderer's depth setup decides the actual one
6042
+ const standardProjection = camera.projection(canvas);
6043
+ const projection = toDepthRange(standardProjection, depth);
5496
6044
  const viewProjection = Matrix3D$1.multiply(view, projection);
5497
6045
  const viewArray = Matrix3D$1.toArray(view);
5498
6046
  const viewProjectionArray = Matrix3D$1.toArray(viewProjection);
@@ -6292,11 +6840,14 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6292
6840
  #camera;
6293
6841
  #bindgroups = new Map();
6294
6842
  #key = { shader: 'basic', lights: '' };
6843
+ /** First shadow map layer of each casting light buffer that fits (see `allocateShadowLayers`). */
6844
+ #shadowLayers = new Map();
6295
6845
  constructor(...objects) {
6296
6846
  this.add(...objects);
6297
6847
  }
6298
6848
  reset() {
6299
6849
  this.#lights.splice(0);
6850
+ this.#shadowLayers.clear();
6300
6851
  this.#mesh = null;
6301
6852
  this.#bindgroups.clear();
6302
6853
  this.#key = { shader: 'basic', lights: '' };
@@ -6318,6 +6869,11 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6318
6869
  const lights = this.#lights;
6319
6870
  lights.push(obj);
6320
6871
  this.#key.lights += ('-' + obj.item.type);
6872
+ // the layout depends on all the lights before: recompute it
6873
+ this.#shadowLayers = allocateShadowLayers(lights, l => l.item);
6874
+ if (this.#shadowLayers.has(obj)) {
6875
+ this.#key.lights += '+shadow';
6876
+ }
6321
6877
  }
6322
6878
  else if (isCamera(obj.item)) {
6323
6879
  this.#camera ??= obj;
@@ -6333,7 +6889,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6333
6889
  const key = this.key, vertex = this.vertex({ inputModifier: modifiers?.vertexInput, outputModifier: modifiers?.vertexOutput }), fragment = this.fragment(data, { modifier: modifiers?.fragment }), bindings = (...args) => MeshWGSLBuilder.prototype.bindgroup.apply(this, args);
6334
6890
  const metadata = {
6335
6891
  lightCount: this.#lights.length,
6336
- mapCount: data.hasTexture ? 1 : 0
6892
+ mapCount: data.hasTexture ? 1 : 0,
6893
+ shadows: this._receivesShadows()
6337
6894
  };
6338
6895
  return {
6339
6896
  vertex,
@@ -6345,8 +6902,17 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6345
6902
  }
6346
6903
  get key() {
6347
6904
  const { shader, lights } = this.#key;
6905
+ const shadows = this._receivesShadows() ? '|receiver' : '';
6348
6906
  // TODO: consider backMap
6349
- return `mesh-` + shader + lights;
6907
+ return `mesh-` + shader + lights + shadows;
6908
+ }
6909
+ /** Whether the mesh reads the shadow maps: it receives shadows and at least one light casts them. */
6910
+ _receivesShadows() {
6911
+ const mesh = this.#mesh?.item;
6912
+ if (pacemCore.Utils.isNull(mesh) || this.#shadowLayers.size === 0) {
6913
+ return false;
6914
+ }
6915
+ return receivesShadow(mesh);
6350
6916
  }
6351
6917
  bindgroup(type, key, index) {
6352
6918
  const set = this.#bindgroups;
@@ -6432,6 +6998,12 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6432
6998
  const wgslTex = textureMap({ inputColor: VERTEX_COLOR_REFERENCE, outputColors: [VERTEX_COLOR_REFERENCE], uv: 'uv' }, materialGroupIndex);
6433
6999
  merge(wgslTex);
6434
7000
  }
7001
+ // shadows
7002
+ const receiver = this._receivesShadows();
7003
+ if (receiver) {
7004
+ const shadowExtra = shadowFragmentExtra(data.lightingBindGroupIndex);
7005
+ merge(shadowExtra);
7006
+ }
6435
7007
  // lights
6436
7008
  let lightIndex = 0;
6437
7009
  const lights = this.#lights;
@@ -6439,11 +7011,13 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6439
7011
  const light = lightBuffer.item; // TODO: consider implementing Pacem.Drawing3D.WebGPU.Light interface (as of Materials)
6440
7012
  switch (light.type) {
6441
7013
  case 'direction':
6442
- const dirLightExtra = directionalLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: 'normal' }, data.lightingBindGroupIndex, lightIndex);
7014
+ const shadowLayer = receiver ? this.#shadowLayers.get(lightBuffer) : undefined;
7015
+ const dirLightExtra = directionalLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: 'normal', position: 'vertex', shadowLayer }, data.lightingBindGroupIndex, lightIndex);
6443
7016
  merge(dirLightExtra);
6444
7017
  break;
6445
7018
  case 'omni':
6446
- const omniLightExtra = omniLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: 'normal', position: 'vertex', /*specularColor: MATERIAL_REFERENCE + '.specularColor', shininess: MATERIAL_REFERENCE + '.shininess'*/ }, data.lightingBindGroupIndex, lightIndex);
7019
+ const omniShadowLayer = receiver ? this.#shadowLayers.get(lightBuffer) : undefined;
7020
+ const omniLightExtra = omniLight({ outputColor: LIGHTING_COLOR_REFERENCE, normal: 'normal', position: 'vertex', shadowLayer: omniShadowLayer, /*specularColor: MATERIAL_REFERENCE + '.specularColor', shininess: MATERIAL_REFERENCE + '.shininess'*/ }, data.lightingBindGroupIndex, lightIndex);
6447
7021
  merge(omniLightExtra);
6448
7022
  break;
6449
7023
  case 'ambient':
@@ -6531,6 +7105,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6531
7105
  const builder = this._builder, wgsl = builder.build(options.modifiers);
6532
7106
  const ctx = this._context;
6533
7107
  const device = ctx.device;
7108
+ const depth = ctx.depth;
6534
7109
  const cache = this._cache;
6535
7110
  // #region VERTEX
6536
7111
  // build vertex state
@@ -6635,7 +7210,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6635
7210
  }) : null;
6636
7211
  // lighting
6637
7212
  const lightingGroupIndex = bindGroupLayouts.length;
6638
- const { lightCount } = wgsl.metadata, hasLighting = lightCount > 0;
7213
+ const { lightCount, shadows: receivesShadows } = wgsl.metadata, hasLighting = lightCount > 0;
6639
7214
  let lightingBindGroupLayout = null;
6640
7215
  if (hasLighting) {
6641
7216
  const lightingEntries = mapIndices(lightCount, index => {
@@ -6646,6 +7221,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6646
7221
  };
6647
7222
  return entry;
6648
7223
  });
7224
+ if (receivesShadows) {
7225
+ lightingEntries.push({ visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_MAP, texture: { sampleType: 'depth', viewDimension: '2d-array' } }, { visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_SAMPLER, sampler: { type: 'comparison' } }, { visibility: GPUShaderStage.FRAGMENT, binding: SHADOW_BINDING_LIGHTS, buffer: { type: 'uniform' } });
7226
+ }
6649
7227
  lightingBindGroupLayout = device.createBindGroupLayout({
6650
7228
  entries: lightingEntries,
6651
7229
  label: labelPrefix + 'lighting-bind-group-layout'
@@ -6669,8 +7247,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6669
7247
  if (options.multisample) {
6670
7248
  descriptor.multisample = { count: 4 };
6671
7249
  descriptor.depthStencil = {
6672
- depthCompare: 'less',
6673
- format: 'depth24plus',
7250
+ depthCompare: depth.compare,
7251
+ format: depth.format,
6674
7252
  depthWriteEnabled: true
6675
7253
  };
6676
7254
  }
@@ -6706,11 +7284,31 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6706
7284
  primitive: options.primitive,
6707
7285
  depthStencil: {
6708
7286
  depthWriteEnabled: true,
6709
- depthCompare: 'less',
6710
- format: 'depth24plus',
7287
+ depthCompare: depth.compare,
7288
+ format: depth.format,
6711
7289
  },
6712
7290
  };
6713
7291
  this._pickPipeline = device.createRenderPipeline(pickDescriptor);
7292
+ // shadow (depth-only) pipeline, built on first use: same vertex stage, the light acting as the camera
7293
+ let shadowPipeline = null;
7294
+ const ensureShadowPipeline = () => {
7295
+ if (!pacemCore.Utils.isNull(shadowPipeline)) {
7296
+ return shadowPipeline;
7297
+ }
7298
+ const shadowLayout = device.createPipelineLayout({
7299
+ label: labelPrefix + 'mesh-shadow-pipeline-layout',
7300
+ bindGroupLayouts: [viewBindGroupLayout, worldBindGroupLayout]
7301
+ });
7302
+ shadowPipeline = device.createRenderPipeline({
7303
+ label: labelPrefix + 'mesh-shadow-pipeline',
7304
+ vertex,
7305
+ layout: shadowLayout,
7306
+ primitive: options.primitive,
7307
+ // slope-scaled bias: the steeper the surface (as seen from the light), the farther its stored depth
7308
+ depthStencil: { format: SHADOW_MAP_FORMAT, depthCompare: 'less', depthWriteEnabled: true, depthBias: 2, depthBiasSlopeScale: 2 }
7309
+ });
7310
+ return shadowPipeline;
7311
+ };
6714
7312
  // #endregion
6715
7313
  // #region bind delegates (binding coordinates are resolved once, here)
6716
7314
  const { group: worldGroup } = wgsl.bindings(WGSLBindingType.Mesh, 'objectWorldTransform', 0);
@@ -6797,7 +7395,14 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6797
7395
  const entry = { binding: index, buffer };
6798
7396
  return entry;
6799
7397
  });
6800
- const bindGroup = cache.ensureBindGroup(ctx, owner, labelPrefix + 'mesh-lighting-bind-group', lightingBindGroupLayout, entries);
7398
+ let label = labelPrefix + 'mesh-lighting-bind-group';
7399
+ if (receivesShadows) {
7400
+ const shadows = Shadows.of(ctx);
7401
+ entries.push({ binding: SHADOW_BINDING_MAP, resource: shadows.map }, { binding: SHADOW_BINDING_SAMPLER, resource: shadows.sampler }, { binding: SHADOW_BINDING_LIGHTS, buffer: shadows.lights });
7402
+ // receivers and non-receivers sharing the same lights keep a bind group each
7403
+ label += '-shadows';
7404
+ }
7405
+ const bindGroup = cache.ensureBindGroup(ctx, owner, label, lightingBindGroupLayout, entries);
6801
7406
  PassUtils.setBindGroup(pass, lightingGroupIndex, bindGroup);
6802
7407
  };
6803
7408
  // picker
@@ -6812,6 +7417,20 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6812
7417
  ]);
6813
7418
  PassUtils.setBindGroup(pass, UNIFORM_GROUP_INDEX_COLORPICKING, bindGroup);
6814
7419
  };
7420
+ this.shadow = (pass, interactionBuffer, meshBuffer, lightCamera) => {
7421
+ try {
7422
+ const pipeline = ensureShadowPipeline();
7423
+ PassUtils.setPipeline(pass, pipeline);
7424
+ this._bindVertex(pass, meshBuffer);
7425
+ this._bindWorldTransform(pass, meshBuffer);
7426
+ this._bindCameraProjectionAndInteractionData(pass, lightCamera, interactionBuffer);
7427
+ const vertexCount = this._vertexCount(meshBuffer);
7428
+ pass.draw(vertexCount);
7429
+ }
7430
+ catch (e) {
7431
+ logFrameException(e);
7432
+ }
7433
+ };
6815
7434
  // #region translucent (A-buffer) variant, built on first use
6816
7435
  // the A-buffer tests fragments against the (multisampled) opaque depth
6817
7436
  if (!options.multisample) {
@@ -6851,13 +7470,15 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
6851
7470
  fragment: {
6852
7471
  module: translucentFragmentModule,
6853
7472
  // fragments are pushed into storage buffers, nothing is written to color targets
6854
- targets: []
7473
+ targets: [],
7474
+ // the manual depth test follows the depth direction
7475
+ constants: { [ABUFFER_REVERSED_Z_CONSTANT]: depth.reversed ? 1 : 0 }
6855
7476
  },
6856
7477
  layout: translucentLayout,
6857
7478
  primitive: options.primitive,
6858
7479
  multisample: { count: 4 },
6859
7480
  // tested against the opaque depth (read-only), never written
6860
- depthStencil: { format: 'depth24plus', depthCompare: 'less', depthWriteEnabled: false }
7481
+ depthStencil: { format: depth.format, depthCompare: depth.compare, depthWriteEnabled: false }
6861
7482
  });
6862
7483
  };
6863
7484
  this.translucent = (pass, interactionBuffer, aBuffer, meshBuffer, cameraBuffer, ...lightBuffers) => {
@@ -7065,6 +7686,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7065
7686
  const builder = this._lineBuilder, wgsl = builder.build();
7066
7687
  const ctx = this.#context;
7067
7688
  const device = ctx.device;
7689
+ const depth = ctx.depth;
7068
7690
  const cache = this._cache;
7069
7691
  // TODO: switch topology based on this flag
7070
7692
  const fatLines = wgsl.metadata.thickness > 1;
@@ -7184,8 +7806,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7184
7806
  if (options.multisample) {
7185
7807
  descriptor.multisample = { count: 4 };
7186
7808
  descriptor.depthStencil = {
7187
- depthCompare: 'less',
7188
- format: 'depth24plus',
7809
+ depthCompare: depth.compare,
7810
+ format: depth.format,
7189
7811
  depthWriteEnabled: true
7190
7812
  };
7191
7813
  }
@@ -7222,8 +7844,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7222
7844
  primitive,
7223
7845
  depthStencil: {
7224
7846
  depthWriteEnabled: true,
7225
- depthCompare: 'less',
7226
- format: 'depth24plus',
7847
+ depthCompare: depth.compare,
7848
+ format: depth.format,
7227
7849
  },
7228
7850
  };
7229
7851
  this._pickLinePipeline = device.createRenderPipeline(pickDescriptor);
@@ -7479,7 +8101,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7479
8101
  if (!pacemCore.Utils.isNull(textures)) {
7480
8102
  return textures;
7481
8103
  }
7482
- const renderTex = this._createTexture('r32uint'), depthTex = this._createTexture('depth24plus');
8104
+ const depthFormat = this._context.depth.format;
8105
+ const renderTex = this._createTexture('r32uint'), depthTex = this._createTexture(depthFormat);
7483
8106
  const render = { texture: renderTex, view: renderTex.createView() };
7484
8107
  const depth = { texture: depthTex, view: depthTex.createView() };
7485
8108
  return this._textures = { render, depth };
@@ -7508,7 +8131,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7508
8131
  return this._handle ?? null;
7509
8132
  }
7510
8133
  begin(pixel) {
7511
- const { device } = this._context;
8134
+ const { device, depth: depthState } = this._context;
7512
8135
  this._encoder = device.createCommandEncoder({ label: LABEL_PREFIX + 'colorpick-raycaster' });
7513
8136
  const { render, depth } = this._ensureTextures();
7514
8137
  const { width, height } = render.texture;
@@ -7526,7 +8149,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7526
8149
  ],
7527
8150
  depthStencilAttachment: {
7528
8151
  view: depth.view, // Assigned later
7529
- depthClearValue: 1,
8152
+ depthClearValue: depthState.clearValue,
7530
8153
  depthLoadOp: 'clear',
7531
8154
  depthStoreOp: 'store',
7532
8155
  },
@@ -7574,6 +8197,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7574
8197
  vertex: { module, entryPoint: 'vertexMain' },
7575
8198
  fragment: {
7576
8199
  module, entryPoint: 'fragmentMain',
8200
+ // the far-to-near sort follows the depth direction
8201
+ constants: { [ABUFFER_REVERSED_Z_CONSTANT]: ctx.depth.reversed ? 1 : 0 },
7577
8202
  targets: [{
7578
8203
  format,
7579
8204
  // the composite outputs premultiplied colors
@@ -7706,14 +8331,17 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7706
8331
  tex?.destroy();
7707
8332
  }
7708
8333
  }
7709
- /** Whether `resolved` was resolved against the very same material (and texture), geometry and lights. */
7710
- function isResolvedFor(resolved, material, texture, geometry, lightsSignature) {
8334
+ /** Whether `resolved` was resolved against the very same material (and texture), geometry, lights and shadow receiving. */
8335
+ function isResolvedFor(resolved, material, texture, geometry, lightsSignature, receiveShadow) {
7711
8336
  if (pacemCore.Utils.isNull(resolved)) {
7712
8337
  return false;
7713
8338
  }
7714
8339
  if (resolved.material !== material || resolved.texture !== texture) {
7715
8340
  return false;
7716
8341
  }
8342
+ if (resolved.receiveShadow !== receiveShadow) {
8343
+ return false;
8344
+ }
7717
8345
  return resolved.geometry === geometry && resolved.lights === lightsSignature;
7718
8346
  }
7719
8347
  /** Whether `aBuffer` matches the current render targets. */
@@ -7859,6 +8487,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7859
8487
  * When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
7860
8488
  */
7861
8489
  this.#hasModifiers = false;
8490
+ /** Whether the "too many shadow-casting lights" warning was already logged. */
8491
+ this.#shadowLimitLogged = false;
7862
8492
  const wrapper = (this.#stage = stage).stage;
7863
8493
  const canvas = document.createElement('canvas');
7864
8494
  canvas.id = pacemCore.P + '_3d_stage_' + pacemCore.Utils.uniqueCode();
@@ -7871,7 +8501,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7871
8501
  });
7872
8502
  }
7873
8503
  _buildPassDescriptor({ multisample, format }) {
7874
- const { context, device } = this.#context;
8504
+ const { context, device, depth } = this.#context;
7875
8505
  const canvasTexture = context.getCurrentTexture();
7876
8506
  let textures = this.#textures;
7877
8507
  if (pacemCore.Utils.isNull(textures)) {
@@ -7889,7 +8519,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7889
8519
  };
7890
8520
  const depthTex = device.createTexture({
7891
8521
  label: LABEL_PREFIX + 'depth-texture',
7892
- format: 'depth24plus',
8522
+ format: depth.format,
7893
8523
  // also read by the A-buffer translucent pass (manual depth test)
7894
8524
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
7895
8525
  size: [canvasTexture.width, canvasTexture.height],
@@ -7919,7 +8549,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7919
8549
  const depthTexView = textures.depth.view;
7920
8550
  passDescriptor.depthStencilAttachment = {
7921
8551
  view: depthTexView,
7922
- depthClearValue: 1,
8552
+ depthClearValue: depth.clearValue,
7923
8553
  depthLoadOp: 'clear',
7924
8554
  depthStoreOp: 'store',
7925
8555
  };
@@ -7959,7 +8589,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7959
8589
  device,
7960
8590
  format,
7961
8591
  });
7962
- this.#context = { device, adapter, canvas: this.#canvas, context, format };
8592
+ const depth = this.#config.reversedZ ? REVERSED_DEPTH : STANDARD_DEPTH;
8593
+ this.#context = { device, adapter, canvas: this.#canvas, context, format, depth };
7963
8594
  this.#rebuildingContext = false;
7964
8595
  }
7965
8596
  _log(message) {
@@ -7994,9 +8625,13 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
7994
8625
  * When true, the renderer must provide updated time, cursor position and canvas size to the pipeline's bind groups.
7995
8626
  */
7996
8627
  #hasModifiers;
7997
- /** Light types signature, part of the cache key of the pipelines resolved per mesh. */
8628
+ /** Light types (and shadow casting) signature, part of the cache key of the pipelines resolved per mesh. */
7998
8629
  _lightsSignature(lights) {
7999
- return lights.map(l => l.item.type).join('-');
8630
+ const signatures = lights.map(l => {
8631
+ const light = l.item;
8632
+ return isShadowCaster(light) ? light.type + '+shadow' : light.type;
8633
+ });
8634
+ return signatures.join('-');
8000
8635
  }
8001
8636
  /**
8002
8637
  * Returns the {@link RenderPipeline} drawing `mesh`, reusing the one resolved in previous frames as long as its
@@ -8004,10 +8639,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8004
8639
  * (which memoizes the built pipelines by recipe).
8005
8640
  */
8006
8641
  _resolvePipeline(mesh, camera, lights, lightsSignature) {
8007
- const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry;
8642
+ const item = mesh.item, material = item.material, texture = material?.texture, geometry = item.geometry, receiveShadow = receivesShadow(item);
8008
8643
  const pipelines = this.#pipelines;
8009
8644
  const existing = pipelines.get(mesh);
8010
- const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature);
8645
+ const reusable = isResolvedFor(existing, material, texture, geometry, lightsSignature, receiveShadow);
8011
8646
  if (reusable) {
8012
8647
  // in-place material changes (flagged) may affect the opacity
8013
8648
  if (material?.flags?.length > 0) {
@@ -8017,11 +8652,59 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8017
8652
  }
8018
8653
  const pipeline = RenderPipelines.create(this.#context, [mesh, camera, ...lights], this.#pipelineOptions);
8019
8654
  const translucent = isTranslucent(item, pipeline);
8020
- const resolved = { material, texture, geometry, lights: lightsSignature, pipeline, translucent };
8655
+ const resolved = { material, texture, geometry, lights: lightsSignature, receiveShadow, pipeline, translucent };
8021
8656
  pipelines.set(mesh, resolved);
8022
8657
  return resolved;
8023
8658
  }
8024
8659
  #aBuffer;
8660
+ /** Whether the "too many shadow-casting lights" warning was already logged. */
8661
+ #shadowLimitLogged;
8662
+ /**
8663
+ * Renders the depth of the shadow-casting meshes into the shadow map layers of the shadow-casting lights (one
8664
+ * depth-only pass per layer: one per directional light, six per omni light, see `shadows.ts`). Translucent
8665
+ * meshes and lines don't cast.
8666
+ */
8667
+ _renderShadows(encoder, lightsSignature) {
8668
+ const looper = this.#looper, { meshes, cameras, lights } = looper.items;
8669
+ const allocation = allocateShadowLayers(lights, l => l.item);
8670
+ if (allocation.size === 0) {
8671
+ return;
8672
+ }
8673
+ const requested = lights.filter(l => isShadowCaster(l.item));
8674
+ if (requested.length > allocation.size && !this.#shadowLimitLogged) {
8675
+ this.#shadowLimitLogged = true;
8676
+ this._log(`Not enough shadow map layers: ${requested.length - allocation.size} light(s) won't cast shadows.`);
8677
+ }
8678
+ const ctx = this.#context;
8679
+ const shadows = Shadows.ensure(ctx);
8680
+ const casters = [];
8681
+ for (let [buffer, firstLayer] of allocation) {
8682
+ casters.push({ light: buffer.item, firstLayer });
8683
+ }
8684
+ shadows.update(casters, meshes);
8685
+ const camera = cameras[0];
8686
+ const count = shadows.layerCount;
8687
+ for (let i = 0; i < count; i++) {
8688
+ const pass = encoder.beginRenderPass({
8689
+ label: LABEL_PREFIX + 'shadow-pass-' + i,
8690
+ colorAttachments: [],
8691
+ depthStencilAttachment: { view: shadows.layer(i), depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'store' }
8692
+ });
8693
+ const lightCamera = shadows.camera(i);
8694
+ for (let mesh of meshes) {
8695
+ const item = mesh.item;
8696
+ if (mesh.disposed || item.hide || !castsShadow(item)) {
8697
+ continue;
8698
+ }
8699
+ const resolved = this._resolvePipeline(mesh, camera, lights, lightsSignature);
8700
+ if (resolved.translucent || pacemCore.Utils.isNull(resolved.pipeline.shadow)) {
8701
+ continue;
8702
+ }
8703
+ resolved.pipeline.shadow(pass, this.#interactionBuffer, mesh, lightCamera);
8704
+ }
8705
+ pass.end();
8706
+ }
8707
+ }
8025
8708
  /** Returns the A-buffer matching the current render targets, (re)creating it when needed. */
8026
8709
  _ensureABuffer(depthView, width, height) {
8027
8710
  const current = this.#aBuffer;
@@ -8085,8 +8768,10 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8085
8768
  const aBufferMode = transparency === 'a-buffer' && !pacemCore.Utils.isNull(depthView);
8086
8769
  // rendering zone
8087
8770
  const commandEncoder = device.createCommandEncoder({ label: LABEL_PREFIX + 'renderer' });
8088
- const pass = commandEncoder.beginRenderPass(passDescriptor);
8089
8771
  const lightsSignature = this._lightsSignature(looper.items.lights);
8772
+ // shadow maps first: the main pass samples them
8773
+ this._renderShadows(commandEncoder, lightsSignature);
8774
+ const pass = commandEncoder.beginRenderPass(passDescriptor);
8090
8775
  // A-buffer (order-independent transparency): a second encoder, lazily started at the first translucent mesh
8091
8776
  // (so that its buffers refresh while the stale flags are still there), submitted after the opaque one
8092
8777
  let translucent = null;
@@ -8326,6 +9011,8 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8326
9011
  }
8327
9012
  // dispose associated raycasters, if any
8328
9013
  Raycasters.dispose(ctx);
9014
+ // dispose associated shadow maps, if any
9015
+ Shadows.dispose(ctx);
8329
9016
  // dispose associated pipelines, if any
8330
9017
  RenderPipelines.dispose(ctx);
8331
9018
  ABuffers.dispose(ctx);
@@ -8506,7 +9193,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8506
9193
  scenes.add(scene);
8507
9194
  }
8508
9195
  const transparency = this.transparency === 'blend' ? 'blend' : 'a-buffer';
8509
- const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency };
9196
+ const config = { enableValidation: this.enableValidation ?? false, modifiers: this.modifiers, transparency, reversedZ: this.reversedZ ?? false };
8510
9197
  const creation = Renderers.create(scene, config);
8511
9198
  return creation
8512
9199
  .then(renderer => {
@@ -8540,6 +9227,7 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8540
9227
  case 'modifiers':
8541
9228
  case 'enableValidation':
8542
9229
  case 'transparency':
9230
+ case 'reversedZ':
8543
9231
  // reinitialize
8544
9232
  this._reinitialize();
8545
9233
  break;
@@ -8693,6 +9381,9 @@ fn computeOffsetPosition(p0: vec4f, p1: vec4f, index: u32) -> vec4f {
8693
9381
  __decorate$1([
8694
9382
  pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.String })
8695
9383
  ], Pacem3DWebgpuAdapterElement.prototype, "transparency", void 0);
9384
+ __decorate$1([
9385
+ pacemCore.Watch({ emit: false, converter: pacemCore.PropertyConverters.Boolean })
9386
+ ], Pacem3DWebgpuAdapterElement.prototype, "reversedZ", void 0);
8696
9387
  Pacem3DWebgpuAdapterElement = __decorate$1([
8697
9388
  pacemCore.CustomElement({ tagName: pacemCore.P + '-3d-webgpu-adapter' })
8698
9389
  ], Pacem3DWebgpuAdapterElement);