Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,9 @@ On the web, `<three-live>` supports the core HTML attributes used by
`rotation-per-second`, `ar`, `ar-modes`, `ar-scale`, `ar-placement`, `exposure`,
`shadow-intensity`, `shadow-softness`, `shadow-maps`, `tone-mapping`,
`environment-image`, `skybox-image`, `autoplay`, `animation-name`,
`variant-name`, and `slot="hotspot-*"`).
`variant-name`, and `slot="hotspot-*"`). It also accepts a CAD `section-plane`
cut (`"y:2.8"`, `"-z:0.5"`, `"none"`) that clips the color and shadow passes on
WebGL2 and WebGPU without requiring `<xr-live>`.

If you have existing `<model-viewer>` HTML markup and want to add procedural
Three.js scripts, native Android/iOS runtime targets, or CLI/MCP scene
Expand Down
129 changes: 62 additions & 67 deletions three-live/src/plugins/shadow-maps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
type ShadowMapsMode,
type ThreeLivePlugin,
} from '../plugin';
import {resolveSectionPlane, type ResolvedSectionPlane} from '../section-plane';

/** Maximum simultaneous shadow-casting lights in the depth array texture. */
export const MAX_SHADOW_LIGHTS = 4;
Expand Down Expand Up @@ -485,70 +486,14 @@ export function fitSpotShadowMatrix(
return mat4Multiply(out, _projMat, _lookView);
}

/** Parses CAD section-plane clipping state on `viewer` (shared with WebGPU). */
export function resolveShadowSectionPlane(viewerObj: unknown): {
enabled: boolean;
normal: [number, number, number];
constant: number;
} | null {
const viewer = (viewerObj || {}) as ShadowViewerLike;
for (const m of viewer.meshes ?? []) {
if (
m.name === '__xr_section_gizmo__' &&
m.visible !== false &&
m.worldMatrix &&
m.worldMatrix.length >= 16
) {
const wm = m.worldMatrix;
const nl = Math.hypot(wm[8], wm[9], wm[10]) || 1;
const nx = wm[8] / nl;
const ny = wm[9] / nl;
const nz = wm[10] / nl;
return {
enabled: true,
normal: [nx, ny, nz],
constant: nx * wm[12] + ny * wm[13] + nz * wm[14],
};
}
}
const raw = (viewer.container?.getAttribute?.('section-plane') ?? '')
.trim()
.toLowerCase();
if (!raw || raw === 'none' || raw === 'false') return null;
let localN: [number, number, number] = [1, 0, 0];
let localC = 0;
if (raw === 'interactive') {
localC = viewer.bounds?.center[0] ?? 0;
} else {
const match =
/^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/.exec(raw);
if (!match) return null;
const sign = match[1].startsWith('-') ? -1 : 1;
const axis = match[1].replace(/^[+-]/, '');
const val = Math.max(-1000, Math.min(1000, Number(match[2]) || 0));
localN =
axis === 'x' ? [sign, 0, 0] : axis === 'y' ? [0, sign, 0] : [0, 0, sign];
localC = val * sign;
}
const rm = viewer.modelRootMatrix ?? IDENTITY_MAT4;
const wnx = rm[0] * localN[0] + rm[4] * localN[1] + rm[8] * localN[2];
const wny = rm[1] * localN[0] + rm[5] * localN[1] + rm[9] * localN[2];
const wnz = rm[2] * localN[0] + rm[6] * localN[1] + rm[10] * localN[2];
const wnl = Math.hypot(wnx, wny, wnz) || 1;
const unx = wnx / wnl;
const uny = wny / wnl;
const unz = wnz / wnl;
const px = localN[0] * localC;
const py = localN[1] * localC;
const pz = localN[2] * localC;
const wpx = rm[0] * px + rm[4] * py + rm[8] * pz + rm[12];
const wpy = rm[1] * px + rm[5] * py + rm[9] * pz + rm[13];
const wpz = rm[2] * px + rm[6] * py + rm[10] * pz + rm[14];
return {
enabled: true,
normal: [unx, uny, unz],
constant: unx * wpx + uny * wpy + unz * wpz,
};
/**
* Parses CAD section-plane clipping state on `viewer` (shared with WebGPU and
* the core WebGL2 color pass via `../section-plane`).
*/
export function resolveShadowSectionPlane(
viewerObj: unknown,
): ResolvedSectionPlane | null {
return resolveSectionPlane(viewerObj);
}

function isShadowEligibleMesh(mesh: ShadowMeshLike): boolean {
Expand Down Expand Up @@ -857,7 +802,56 @@ export function getShadowMapStats(viewer: object): ShadowMapStats {
};
}

const VS_SHADOW_DEPTH = `#version 300 es
/**
* CPU reference for the caster normal-offset applied by the WebGL2
* (`VS_SHADOW_DEPTH`) and WebGPU (`vsShadowDepth`) shadow depth passes.
*
* Casters are shrunk *inward* along `-N` (never inflated along `+N`). The
* receiver already offsets its lookup outward along `+N` in `shdEval`, so
* inflating casters as well made upper-story walls stick out ~1.75 shadow
* texels past a flush lower wall and cast a fake horizontal "overhang" band
* just below the floor joint. Shrinking light-facing casters also moves them
* away from the light, which further suppresses self-shadow acne.
*
* Writes the biased world position into `out` and returns it.
*/
export function applyShadowCasterNormalBias(
out: number[] | Float32Array,
worldPos: ArrayLike<number>,
worldNormal: ArrayLike<number>,
rayDir: ArrayLike<number>,
normalBiasWorld: number,
): number[] | Float32Array {
out[0] = worldPos[0];
out[1] = worldPos[1];
out[2] = worldPos[2];
const nl = Math.hypot(worldNormal[0], worldNormal[1], worldNormal[2]);
if (nl > 1e-5 && normalBiasWorld > 0) {
const nx = worldNormal[0] / nl;
const ny = worldNormal[1] / nl;
const nz = worldNormal[2] / nl;
const d = nx * rayDir[0] + ny * rayDir[1] + nz * rayDir[2];
const k = normalBiasWorld * Math.max(1 - Math.abs(d), 0.15);
out[0] -= nx * k;
out[1] -= ny * k;
out[2] -= nz * k;
}
return out;
}

/**
* Receiver normal-offset scale applied to `normalBiasWorld` in `shdEval`
* (`uShadowParams[s].y`) and the WebGPU receiver (`writeSceneUniforms`).
*
* With casters shrunk inward, the receiver carries the full normal bias so
* PCF taps across light-facing convex edges (e.g. a wall's top face meeting
* its front face at a floor joint) and grazing sloped/curved surfaces stay
* acne-free.
*/
export const SHADOW_RECEIVER_NORMAL_BIAS_SCALE = 1.0;

/** WebGL2 shadow depth vertex shader (exported for shader parity tests). */
export const VS_SHADOW_DEPTH = `#version 300 es
layout(location=0) in vec3 aPos;
layout(location=1) in vec3 aNormal;
layout(location=3) in vec3 aOff;
Expand All @@ -876,7 +870,7 @@ vec3 wn=mat3(m)*aNormal;
float nl=length(wn);
if(nl>1e-5&&uBiasRay.w>0.0){
wn/=nl;
wp.xyz+=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15));
wp.xyz-=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15));
}
vWorldPos=wp.xyz;
gl_Position=uLightVP*wp;
Expand Down Expand Up @@ -1231,7 +1225,8 @@ export const shadowMapsPlugin: ThreeLivePlugin = {
st.vpFlat.set(s.viewProj, s.slot * 16);
const b = s.slot * 4;
st.paramsFlat[b] = s.depthBias;
st.paramsFlat[b + 1] = s.normalBiasWorld * 0.5;
st.paramsFlat[b + 1] =
s.normalBiasWorld * SHADOW_RECEIVER_NORMAL_BIAS_SCALE;
st.paramsFlat[b + 2] = s.uvRadius;
}

Expand Down
115 changes: 115 additions & 0 deletions three-live/src/section-plane.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @fileoverview Shared CAD `section-plane` resolution used by the core WebGL2
* color pass (`ThreeView.render`), the WebGPU scene accelerator, and the
* shadow-map depth pass so all three clip against the exact same plane.
*/

/** World-space clipping plane: fragments with `dot(p, normal) > constant` are discarded. */
export interface ResolvedSectionPlane {
enabled: boolean;
normal: [number, number, number];
constant: number;
}

interface SectionViewerLike {
readonly container?: {
readonly getAttribute?: (name: string) => string | null;
} | null;
readonly meshes?: ReadonlyArray<{
readonly name?: string;
readonly visible?: boolean;
readonly worldMatrix?: ArrayLike<number>;
}>;
readonly bounds?: {readonly center: readonly number[]};
readonly modelRootMatrix?: ArrayLike<number>;
}

const IDENTITY: readonly number[] = [
1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
];

const SPEC_RE = /^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/;

/**
* Resolves the active world-space section plane for `viewerObj`.
*
* Priority: a visible `<xr-live>` interactive section gizmo
* (`__xr_section_gizmo__`) wins; otherwise the host element's
* `section-plane` attribute (authored in scene/model space, transformed by
* `modelRootMatrix`). Returns `null` when clipping is disabled.
*/
export function resolveSectionPlane(
viewerObj: unknown,
): ResolvedSectionPlane | null {
const viewer = (viewerObj || {}) as SectionViewerLike;
for (const m of viewer.meshes ?? []) {
if (
m.name === '__xr_section_gizmo__' &&
m.visible !== false &&
m.worldMatrix &&
m.worldMatrix.length >= 16
) {
const wm = m.worldMatrix;
const nl = Math.hypot(wm[8], wm[9], wm[10]) || 1;
const nx = wm[8] / nl;
const ny = wm[9] / nl;
const nz = wm[10] / nl;
return {
enabled: true,
normal: [nx, ny, nz],
constant: nx * wm[12] + ny * wm[13] + nz * wm[14],
};
}
}
const raw = (viewer.container?.getAttribute?.('section-plane') ?? '')
.trim()
.toLowerCase();
if (!raw || raw === 'none' || raw === 'false') return null;
let localN: [number, number, number] = [1, 0, 0];
let localC = 0;
if (raw === 'interactive') {
localC = viewer.bounds?.center[0] ?? 0;
} else {
const match = SPEC_RE.exec(raw);
if (!match) return null;
const sign = match[1].startsWith('-') ? -1 : 1;
const axis = match[1].replace(/^[+-]/, '');
const val = Math.max(-1000, Math.min(1000, Number(match[2]) || 0));
localN =
axis === 'x' ? [sign, 0, 0] : axis === 'y' ? [0, sign, 0] : [0, 0, sign];
localC = val * sign;
}
const rm = viewer.modelRootMatrix ?? IDENTITY;
const wnx = rm[0] * localN[0] + rm[4] * localN[1] + rm[8] * localN[2];
const wny = rm[1] * localN[0] + rm[5] * localN[1] + rm[9] * localN[2];
const wnz = rm[2] * localN[0] + rm[6] * localN[1] + rm[10] * localN[2];
const wnl = Math.hypot(wnx, wny, wnz) || 1;
const unx = wnx / wnl;
const uny = wny / wnl;
const unz = wnz / wnl;
const px = localN[0] * localC;
const py = localN[1] * localC;
const pz = localN[2] * localC;
const wpx = rm[0] * px + rm[4] * py + rm[8] * pz + rm[12];
const wpy = rm[1] * px + rm[5] * py + rm[9] * pz + rm[13];
const wpz = rm[2] * px + rm[6] * py + rm[10] * pz + rm[14];
return {
enabled: true,
normal: [unx, uny, unz],
constant: unx * wpx + uny * wpy + unz * wpz,
};
}
20 changes: 19 additions & 1 deletion three-live/src/three-live-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export interface ThreeLiveElement {
/** Custom `<three-live>` Web Component for declarative 3D/XR rendering. */
export class ThreeLiveElement extends BaseElement {
static readonly observedAttributes =
'src ios-src script-src sandbox capabilities allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps'.split(
'src ios-src script-src sandbox capabilities allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps section-plane'.split(
' ',
);

Expand Down Expand Up @@ -679,6 +679,12 @@ export class ThreeLiveElement extends BaseElement {
v?.render();
break;

case 'section-plane':
// Color, WebGPU, and shadow passes all read `section-plane` from the
// host element each frame; just schedule a redraw.
v?.render();
break;

case 'capabilities':
if (!this._syncingCapsAttr) {
this.__tlCapsOverride = null;
Expand Down Expand Up @@ -899,6 +905,18 @@ export class ThreeLiveElement extends BaseElement {
this.setAttr('shadow-maps', val);
}

/**
* CAD cross-section clipping plane, e.g. `"y:2.8"`, `"-z:0.5"`, `"x:0"`, or
* `"none"`. Geometry on the positive side of the plane is discarded in the
* color pass (WebGL2 + WebGPU) and the shadow-map depth pass.
*/
get sectionPlane(): string {
return this.getAttr('section-plane')?.trim() || 'none';
}
set sectionPlane(val: string | null) {
this.setAttr('section-plane', val);
}

protected fireEvent(type: string, detail?: unknown): void {
this.dispatchEvent(
new CustomEvent(type, {bubbles: true, composed: true, detail}),
Expand Down
22 changes: 21 additions & 1 deletion three-live/src/three-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ import {
type ShadowMapsMode,
type ThreeLivePlugin,
} from './plugin';
import {resolveSectionPlane} from './section-plane';
ensureCapabilityChecker();
export {getRegisteredPlugins, registerPlugin, type ThreeLivePlugin};

Expand Down Expand Up @@ -3977,6 +3978,7 @@ export class ThreeView {
}
let hasTransmissive = false;
let hasRefraction = false;
const sectionPlane = resolveSectionPlane(this);
const renderList =
numBackdrop > 0 ? [...this.backdropMeshes, ...this.meshes] : this.meshes;
const bindTex2D = (
Expand Down Expand Up @@ -4124,7 +4126,25 @@ export class ThreeView {
);

this.bindLights(u);
if (u.uSectionEnabled) gl.uniform1i(u.uSectionEnabled, 0);
if (u.uSectionEnabled) {
// Core `section-plane` clipping (`<three-live section-plane=...>`),
// matching the shadow pass. `<xr-live>`'s exploded-view plugin may
// still override these uniforms in `onBeforeDrawPrimitive` below.
const clip =
sectionPlane !== null &&
i >= numBackdrop &&
!(mesh as any).isPluginMesh;
gl.uniform1i(u.uSectionEnabled, clip ? 1 : 0);
if (clip && u.uSectionPlane) {
gl.uniform4f(
u.uSectionPlane,
sectionPlane.normal[0],
sectionPlane.normal[1],
sectionPlane.normal[2],
sectionPlane.constant,
);
}
}

for (const plugin of registeredPlugins) {
plugin.onBeforeDrawPrimitive?.(
Expand Down
7 changes: 5 additions & 2 deletions three-live/src/webgpu/shaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ export function writeSceneUniforms(
);
const pb = 180 + s.slot * 4;
f32[pb] = s.depthBias;
f32[pb + 1] = s.normalBiasWorld * 0.5;
// Full receiver normal bias (SHADOW_RECEIVER_NORMAL_BIAS_SCALE).
f32[pb + 1] = s.normalBiasWorld;
f32[pb + 2] = s.uvRadius;
}
i32[196] = input.shadowMap.dirSlots[0] | 0;
Expand Down Expand Up @@ -954,10 +955,12 @@ fn vsShadowDepth(
var wp = m * vec4<f32>(aPos, 1.0);
let wn = m[0].xyz * aNormal.x + m[1].xyz * aNormal.y + m[2].xyz * aNormal.z;
let nl = length(wn);
// Shrink casters inward along -N (see applyShadowCasterNormalBias in
// plugins/shadow-maps.ts); receivers already offset outward along +N.
if (nl > 1e-5 && shd.biasRay.w > 0.0) {
let un = wn / nl;
wp = vec4<f32>(
wp.xyz + un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)),
wp.xyz - un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)),
1.0,
);
}
Expand Down
Loading
Loading