Merge [245] Begehen mit Kollision

This commit is contained in:
Claude committed 2026-11-13 22:51:05 +00:00
commit 48a85c7565
12 files changed
+837 -10

No files matched your search

+3
View File
@@ -2141,6 +2141,9 @@ export const de = {
"walk.tip.on": "Begehen einschalten (Umschalt+F)",
"walk.tip.off": "Begehen beenden (Umschalt+F)",
"walk.help.move": "Gehen",
"walk.help.ghost": "Geist (Wände durchlaufen)",
"walk.tip.ghostOff": "Geist ausschalten: Wände und Böden gelten wieder (G)",
"walk.tip.ghostOn": "Geist einschalten: durch Wände gehen (G)",
"walk.help.updown": "Runter / hoch",
"walk.help.speed": "Schneller / langsamer",
"walk.help.mouseKey": "Maus ziehen",
+3
View File
@@ -2130,6 +2130,9 @@ export const en: Record<TranslationKey, string> = {
"walk.tip.on": "Start walking (Shift+F)",
"walk.tip.off": "Stop walking (Shift+F)",
"walk.help.move": "Move",
"walk.help.ghost": "Ghost (walk through walls)",
"walk.tip.ghostOff": "Turn ghost off: walls and floors apply again (G)",
"walk.tip.ghostOn": "Turn ghost on: walk through walls (G)",
"walk.help.updown": "Down / up",
"walk.help.speed": "Faster / slower",
"walk.help.mouseKey": "Drag mouse",
+4 -2
View File
@@ -301,6 +301,8 @@ export interface Model3dOptions {
* Cache, Umschalten rechnet keine Wand neu). [185] Auch als {@link Filter3d} mit Element-Auswahl.
*/
hide?: Hide3d;
/** [245] Begehen mit Kollision: ohne Öffnungs-Einbauteile (Türflügel, Rahmen, Glas; Löcher in den Wänden genügen) und ohne Handläufe. */
forWalk?: boolean;
}
/** Das volle 3D-Modell: Wände (mit Öffnungen) + Deckenplatten + Kontext-Meshes. */
@@ -319,9 +321,9 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R
const meshes: RMesh[] = [...parts.contextMeshes];
for (const m of parts.solidMeshes) meshes.push(m);
for (const m of parts.columnMeshes) meshes.push(m);
for (const m of parts.openingMeshes) meshes.push(m);
if (!opts.forWalk) for (const m of parts.openingMeshes) meshes.push(m);
for (const m of parts.stairMeshes) meshes.push(m);
for (const m of parts.stairRailings) meshes.push(m);
if (!opts.forWalk) for (const m of parts.stairRailings) meshes.push(m);
for (const m of parts.roofMeshes) meshes.push(m);
const model: RModel3d = {
walls: parts.walls,
+2 -1
View File
@@ -13,7 +13,8 @@ kommt als Teile aus dem Kern (`src/plan/toWalls3d.ts`). Weg eines Modells in den
| `Viewport3D.tsx` | Zugang zur Ansicht (`Viewport3D = Wasm3DViewport`) und die geteilten Typen (`RenderDisplay`, `DisplayResolver`) |
| `useWasm3dRenderer.ts` | Hook: lädt render3d, hält Modell, Kamera und Punktwolken, zeichnet; Typ `Camera3d` |
| `cameraView.ts` | [213] Kamera-Element (`Project.cameras`) ↔ Sicht des Viewports: `cameraToView`, `cameraFromView`, Brennweite, Geschoss zur Höhe |
| `walk.ts` | [213] Begehen (WASD): Bewegung und Umschauen als reine Funktionen auf dem Orbit-Zustand |
| `walk.ts` | [213] Begehen (WASD): Bewegung und Umschauen als reine Funktionen auf dem Orbit-Zustand; [245] `stepWalkCollide` (Kollision, Bodenfolge) |
| `walkCollision.ts` | [245] Raster aus Wänden, Decken/Tritten und Netzen: Gleiten an Hindernissen, Boden unter der Person |
| `imageExport.ts` | 3D-Bild in Abgabeauflösung; beim Pathtracing in Häppchen mit N Samples, Fortschritt und Abbruch ([212], [223]) |
| `imageExport.ts` | [223] Hilfen für den 3D-Bild-Export (Zielgrösse, transparenter Hintergrund); Samples je Pixel im Stil Pathtracing (`exportSamples`, [212]); gezeichnet wird in `useWasm3dRenderer.exportImage` |
| `cameraBridge.ts` | Kamera von aussen lesen und setzen, Bild-Schnappschuss, Live-Schnittebene (für BCF-Viewpoints) |
+14
View File
@@ -34,6 +34,20 @@ describe("ViewportToolbar3d", () => {
for (const k of ["W A S D", "Q / E", "Esc"]) expect(h).toContain(k);
});
it("[245] Geist: Knopf nur im Begehen und mit Handler, Taste G in der Tastenhilfe", () => {
setLanguage("de");
const withGhost = (walkMode: boolean, ghost: boolean) =>
renderToStaticMarkup(createElement(ViewportToolbar3d, { walkMode, onToggleWalk: noop, ghost, onToggleGhost: noop, onCreateCamera: noop, pathtrace: null }));
expect(withGhost(false, false)).not.toContain("walk-ghost");
expect(html(true)).not.toContain("walk-ghost");
const on = withGhost(true, true);
expect(on).toContain('data-testid="walk-ghost"');
expect(on).toContain(t("walk.tip.ghostOff"));
expect(withGhost(true, false)).toContain(t("walk.tip.ghostOn"));
expect(on).toContain(t("walk.help.ghost"));
expect(on).toContain("<kbd>G</kbd>");
});
it("Kamera-Knopf hat Label und Test-ID", () => {
const h = html(false);
expect(h).toContain('data-testid="camera-create-3d"');
+15 -1
View File
@@ -25,6 +25,9 @@ export const PT_STATUS_THROTTLE_MS = 250;
export interface ViewportToolbar3dProps {
walkMode: boolean;
onToggleWalk: () => void;
/** [245] Geist: Kollision und Bodenfolge im Begehen aus. Ohne `onToggleGhost` kein Knopf. */
ghost?: boolean;
onToggleGhost?: () => void;
onCreateCamera: () => void;
/** null = Pathtracing aus. */
pathtrace: PathtraceStatus3d | null;
@@ -114,6 +117,7 @@ function WalkHelp({ visible }: { visible: boolean }) {
const rows: Array<[string, string]> = [
["W A S D", t("walk.help.move")],
["Q / E", t("walk.help.updown")],
["G", t("walk.help.ghost")],
["⇧ / Alt", t("walk.help.speed")],
[t("walk.help.mouseKey"), t("walk.help.look")],
["Esc", t("walk.help.exit")],
@@ -131,7 +135,7 @@ function WalkHelp({ visible }: { visible: boolean }) {
);
}
export function ViewportToolbar3d({ walkMode, onToggleWalk, onCreateCamera, pathtrace }: ViewportToolbar3dProps) {
export function ViewportToolbar3d({ walkMode, onToggleWalk, ghost = false, onToggleGhost, onCreateCamera, pathtrace }: ViewportToolbar3dProps) {
// Tastenhilfe: beim Einschalten sichtbar, nach ein paar Sekunden aus.
const [helpOn, setHelpOn] = useState(false);
useEffect(() => {
@@ -156,6 +160,16 @@ export function ViewportToolbar3d({ walkMode, onToggleWalk, onCreateCamera, path
pressed={walkMode}
onClick={onToggleWalk}
/>
{walkMode && onToggleGhost && (
<ToolButton
icon="ghost"
label={ghost ? t("walk.tip.ghostOff") : t("walk.tip.ghostOn")}
testId="walk-ghost"
on={ghost}
pressed={ghost}
onClick={onToggleGhost}
/>
)}
</div>
<div className="vp3t-group" role="group" aria-label={t("viewport3d.toolbar.cameras")}>
<ToolButton icon="add_a_photo" label={t("viewport3d.camera.create")} testId="camera-create-3d" onClick={onCreateCamera} />
+67 -4
View File
@@ -82,7 +82,8 @@ import {
type OrbitState,
type V3 as CamV3,
} from "./cameraBridge";
import { NO_KEYS, WALK_SPEED, anyKey, lookAround, speedFactor, stepWalk, walkKeyAllowed, walkKeyOf, type WalkKeys } from "./walk";
import { NO_KEYS, WALK_SPEED, anyKey, bodySettling, initBody, lookAround, orbitEye, speedFactor, stepWalk, stepWalkCollide, walkKeyAllowed, walkKeyOf, type WalkBody, type WalkKeys } from "./walk";
import { WalkWorld } from "./walkCollision";
import { loadShortcutOverrides, matchesShortcut } from "../state/keyboardShortcuts";
import { createCameraFromView } from "../state/cameraActions";
import { ViewportToolbar3d } from "./ViewportToolbar3d";
@@ -603,6 +604,14 @@ export function Wasm3DViewport({
const [walkMode, setWalkMode] = useState(false);
const walkModeRef = useRef(false);
walkModeRef.current = walkMode;
// [245] Kollision und Bodenfolge im Begehen; G = Geist (ohne). Welt (Raster aus den 3D-Teilen) je Projektstand einmal gebaut.
const [walkGhost, setWalkGhost] = useState(false);
const walkGhostRef = useRef(false);
walkGhostRef.current = walkGhost;
const walkBodyRef = useRef<WalkBody | null>(null);
const walkSyncRef = useRef<[number, number, number] | null>(null);
const walkWorldRef = useRef<{ p: unknown; h: unknown; ex: unknown; w: WalkWorld | null } | null>(null);
const walkKickRef = useRef<(() => void) | null>(null);
const onWorkplanePointRef = useRef(onWorkplanePoint);
onWorkplanePointRef.current = onWorkplanePoint;
const onWorkplaneConfirmRef = useRef(onWorkplaneConfirm);
@@ -1472,17 +1481,51 @@ export function Wasm3DViewport({
};
redrawRef.current();
};
// [245] Welt für die Kollision: nur neu bauen, wenn sich Projekt, Ausblendung oder Explosion geändert haben.
const walkWorld = (): WalkWorld | null => {
const p = projectRef.current;
const h = hideRef.current;
const ex = explodeRef.current;
const c = walkWorldRef.current;
if (c && c.p === p && c.h === h && c.ex === ex) return c.w;
let w: WalkWorld | null = null;
try {
w = new WalkWorld(projectToModel3d(p, { hide: h, explode: ex, forWalk: true }));
} catch {
w = null; // Kollision nicht möglich: Begehen läuft wie im Geist-Modus weiter.
}
walkWorldRef.current = { p, h, ex, w };
return w;
};
const tick = (now: number) => {
raf = 0;
if (!walkModeRef.current || !anyKey(keys)) return;
if (!walkModeRef.current) return;
const world = walkGhostRef.current ? null : walkWorld();
const moving = anyKey(keys);
if (!moving && !world) return;
const o = orbitRef.current;
let settling = false;
if (o) {
const dt = last ? (now - last) / 1000 : 0;
orbitRef.current = stepWalk(o, keys, dt, WALK_SPEED * speedFactor(mods.shift, mods.alt));
const speed = WALK_SPEED * speedFactor(mods.shift, mods.alt);
if (world) {
// Wurde die Kamera sonst bewegt (Schwenk, Kamera öffnen), den Boden unter dem neuen Augpunkt neu suchen.
const eye = orbitEye(o);
const sync = walkSyncRef.current;
let body = walkBodyRef.current;
if (!body || !sync || Math.hypot(eye[0] - sync[0], eye[1] - sync[1], eye[2] - sync[2]) > 1e-6) body = initBody(o, world);
const r = stepWalkCollide(o, body, keys, dt, speed, world);
orbitRef.current = r.orbit;
walkBodyRef.current = r.body;
walkSyncRef.current = orbitEye(r.orbit);
settling = bodySettling(r.body);
} else {
orbitRef.current = stepWalk(o, keys, dt, speed);
}
redrawOrbit();
}
last = now;
raf = requestAnimationFrame(tick);
if (moving || settling) raf = requestAnimationFrame(tick);
};
const start = () => {
if (raf === 0) {
@@ -1490,6 +1533,7 @@ export function Wasm3DViewport({
raf = requestAnimationFrame(tick);
}
};
walkKickRef.current = start;
const release = () => {
Object.assign(keys, NO_KEYS);
};
@@ -1510,6 +1554,15 @@ export function Wasm3DViewport({
release();
return;
}
// [245] G: Geist (Kollision und Bodenfolge aus/an).
if (e.code === "KeyG" && !e.repeat && !e.shiftKey && !e.altKey) {
e.preventDefault();
e.stopPropagation();
walkBodyRef.current = null;
setWalkGhost((g) => !g);
start();
return;
}
const k = walkKeyOf(e.code);
if (!k) return;
e.preventDefault();
@@ -1534,9 +1587,17 @@ export function Wasm3DViewport({
window.removeEventListener("keyup", onKeyUp, true);
window.removeEventListener("blur", release);
cancelAnimationFrame(raf);
walkKickRef.current = null;
};
}, [ready, render]);
// [245] Beim Einschalten des Begehens (und beim Wechsel Geist ↔ Kollision) Boden neu suchen und gegebenenfalls absetzen.
useEffect(() => {
walkBodyRef.current = null;
walkSyncRef.current = null;
if (walkMode && !walkGhost) walkKickRef.current?.();
}, [walkMode, walkGhost]);
// Maus-Navigation (LINKS = Orbit, MITTE/RECHTS = Pan, RAD = Zoom, s.
// Datei-Kommentar MAUS-SCHEMA). Verlässt damit IMMER die Praeset-Kamera und
// wechselt auf die freie perspektivische Orbit-Kamera (Kontinuität über den
@@ -1922,6 +1983,8 @@ export function Wasm3DViewport({
<ViewportToolbar3d
walkMode={walkMode}
onToggleWalk={() => setWalkMode((w) => !w)}
ghost={walkGhost}
onToggleGhost={() => setWalkGhost((g) => !g)}
onCreateCamera={() => createCameraFromView()}
pathtrace={ptStatus}
/>
+76
View File
@@ -7,6 +7,7 @@
import { PITCH_LIMIT } from "./cameraBridge";
import type { OrbitState, V3 } from "./cameraBridge";
import { STEP_UP, type WalkWorld } from "./walkCollision";
/** Gedrückte Bewegungstasten. */
export interface WalkKeys {
@@ -115,3 +116,78 @@ export function walkKeyAllowed(e: { ctrlKey: boolean; metaKey: boolean }, active
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return false;
return !(active as HTMLElement).isContentEditable;
}
// ── [245] Kollision und Bodenfolge ─────────────────────────────────────────────────────────────────────────────
/** Standard-Augenhöhe über dem Boden (m) und erlaubter Bereich für Q/E. */
export const EYE_HEIGHT = 1.6;
export const EYE_MIN = 0.5;
export const EYE_MAX = 2.3;
/** Glättung der Fusshöhe (1/s): Aufstieg zügig, Abstieg sanfter; höchste Fallgeschwindigkeit (m/s). */
const RISE_RATE = 14;
const FALL_RATE = 6;
const MAX_FALL_SPEED = 5;
/** Unter dieser Restdifferenz (m) gilt die Fusshöhe als angekommen. */
const SETTLE = 0.002;
/** Zustand der Person im Begehen mit Kollision. */
export interface WalkBody {
/** Fusshöhe (geglättet, daraus ergibt sich die Augenhöhe). */
feetY: number;
/** Höhe des Bodens unter der Person (ungeglättet, Bezug für Stufen und Kollision). */
groundY: number;
/** Auge über den Füssen (Q/E ändern sie). */
eyeHeight: number;
}
/** Person aus dem aktuellen Augpunkt: Boden darunter suchen; ohne Boden bleibt die Höhe stehen. */
export function initBody(o: OrbitState, world: WalkWorld): WalkBody {
const eye = orbitEye(o);
const ground = world.groundAt(eye[0], eye[2], eye[1]);
const eyeHeight = ground !== null && eye[1] - ground >= EYE_MIN && eye[1] - ground <= EYE_MAX ? eye[1] - ground : EYE_HEIGHT;
const feetY = eye[1] - eyeHeight;
return { feetY, groundY: ground !== null ? ground : feetY, eyeHeight };
}
/** Ist die Fusshöhe noch unterwegs zum Boden (dann läuft der Takt auch ohne Taste weiter)? */
export const bodySettling = (b: WalkBody): boolean => Math.abs(b.feetY - b.groundY) > SETTLE;
/** Fusshöhe auf den Boden zu: nach oben schnell, nach unten sanft mit Fallgrenze; ohne Ruckeln bei Stufen. */
function smoothFeet(feet: number, ground: number, dt: number): number {
const diff = ground - feet;
if (Math.abs(diff) <= SETTLE) return ground;
if (diff > 0) return feet + diff * (1 - Math.exp(-RISE_RATE * dt));
const drop = Math.min(-diff * (1 - Math.exp(-FALL_RATE * dt)), MAX_FALL_SPEED * dt, -diff);
return feet - drop;
}
/**
* Ein Zeitschritt des Begehens mit Kollision: horizontal gleitend an Wänden, Fusshöhe folgt dem Boden (Stufen bis
* `STEP_UP` geglättet, Absturz sanft), Q/E ändern die Augenhöhe. Der Augpunkt wandert um denselben Vektor wie das Ziel
* (Blickrichtung bleibt). Ohne Taste und ohne offene Höhenanpassung derselbe Zustand.
*/
export function stepWalkCollide(
o: OrbitState,
body: WalkBody,
keys: WalkKeys,
dt: number,
speed: number,
world: WalkWorld,
): { orbit: OrbitState; body: WalkBody } {
if (!(dt > 0) || !Number.isFinite(dt) || !(speed > 0)) return { orbit: o, body };
const s = Math.min(dt, MAX_DT);
const eye = orbitEye(o);
const v = walkVelocity(keys, o.yaw, speed);
let x = eye[0];
let z = eye[2];
if (v[0] !== 0 || v[2] !== 0) [x, z] = world.move(x, z, v[0] * s, v[2] * s, body.groundY);
// Boden an der neuen Stelle: höchstens eine Stufe höher als bisher; fällt der Boden weg, der nächste darunter.
const g = world.groundAt(x, z, body.groundY + STEP_UP);
const groundY = g !== null ? g : body.groundY;
const eyeHeight = Math.max(EYE_MIN, Math.min(EYE_MAX, body.eyeHeight + v[1] * s));
const feetY = smoothFeet(body.feetY, groundY, s);
const ny = feetY + eyeHeight;
const d: V3 = [x - eye[0], ny - eye[1], z - eye[2]];
const orbit = d[0] === 0 && d[1] === 0 && d[2] === 0 ? o : { ...o, target: [o.target[0] + d[0], o.target[1] + d[1], o.target[2] + d[2]] as V3 };
return { orbit, body: { feetY, groundY, eyeHeight } };
}
+193
View File
@@ -0,0 +1,193 @@
// [245] Kollision und Bodenfolge mit einfachen synthetischen Modellen (keine Engine, kein Kern).
import { describe, expect, it } from "vitest";
import type { OrbitState } from "./cameraBridge";
import { EYE_HEIGHT, NO_KEYS, bodySettling, initBody, orbitEye, stepWalkCollide, type WalkKeys } from "./walk";
import { PERSON_RADIUS, STEP_UP, WalkWorld, type WalkModelInput, type WalkSlab, type WalkWall } from "./walkCollision";
/** Wand entlang der x-Achse bei z = 0, 10 m lang, 0.2 m dick, 2.6 m hoch. */
const wall = (holes: WalkWall["holes"] = []): WalkWall => ({ start: [-5, 0], end: [5, 0], thickness: 0.2, height: 2.6, baseElevation: 0, holes });
const floorSlab = (x0: number, x1: number, top: number, bottom = top - 0.3, z = 20): WalkSlab => ({
outline: [[x0, -z], [x1, -z], [x1, z], [x0, z]],
zBottom: bottom,
zTop: top,
});
const world = (m: Partial<WalkModelInput>) => new WalkWorld({ walls: [], slabs: [], meshes: [], ...m });
describe("Kollision", () => {
it("eine Wand blockiert: die Person bleibt mit ihrem Radius davor", () => {
const w = world({ walls: [wall()] });
let [x, z] = [0, -2];
for (let i = 0; i < 50; i++) [x, z] = w.move(x, z, 0, 0.1, 0);
expect(x).toBeCloseTo(0, 6);
expect(z).toBeCloseTo(-(0.1 + PERSON_RADIUS), 3);
expect(w.isFree(x, z, 0)).toBe(true);
});
it("schnelle Schritte tunneln nicht durch die Wand", () => {
const w = world({ walls: [wall()] });
const [, z] = w.move(0, -1, 0, 3, 0);
expect(z).toBeLessThan(0);
});
it("an der Wand schräg gehen gleitet entlang statt zu stoppen", () => {
const w = world({ walls: [wall()] });
let [x, z] = [-3, -(0.1 + PERSON_RADIUS)];
for (let i = 0; i < 20; i++) [x, z] = w.move(x, z, 0.1, 0.1, 0);
expect(x).toBeGreaterThan(-3 + 1.5);
expect(z).toBeLessThanOrEqual(-(0.1 + PERSON_RADIUS) + 1e-6);
});
it("Türöffnung (Loch bis zur Wand-UK) ist frei, daneben ist die Wand", () => {
const w = world({ walls: [wall([{ from: 6, to: 7, zBottom: 0, zTop: 2.1 }])] }); // x = 1 … 2
expect(w.move(1.5, -1, 0, 2, 0)[1]).toBeGreaterThan(0.5);
expect(w.move(0.2, -1, 0, 2, 0)[1]).toBeLessThan(0);
});
it("Fenster (Brüstung 0.9) sperrt, auch ein bodennahes Fenster mit Glasebene", () => {
const w = world({ walls: [wall([{ from: 8, to: 9, zBottom: 0.9, zTop: 2.1 }, { from: 1, to: 2, zBottom: 0.1, zTop: 2.4 }])] });
expect(w.move(3.5, -1, 0, 2, 0)[1]).toBeLessThan(0);
expect(w.move(-3.5, -1, 0, 2, 0)[1]).toBeLessThan(0);
});
it("Sturz über der Tür stört nicht (Körper 1.8 m, Sturz ab 2.1 m)", () => {
const w = world({ walls: [wall([{ from: 6, to: 7, zBottom: 0, zTop: 2.1 }])] });
expect(w.isFree(1.5, 0, 0)).toBe(true);
});
it("Hindernisse unter der Stufenhöhe oder über dem Kopf zählen nicht", () => {
const low = world({ walls: [{ ...wall(), height: 0.2 }] });
expect(low.move(0, -1, 0, 2, 0)[1]).toBeGreaterThan(0.5);
const high = world({ walls: [{ ...wall(), baseElevation: 2.2 }] });
expect(high.move(0, -1, 0, 2, 0)[1]).toBeGreaterThan(0.5);
});
it("Wand auf einem anderen Geschoss (Füsse oben) stört nicht", () => {
const w = world({ walls: [wall()] });
expect(w.move(0, -1, 0, 2, 3)[1]).toBeGreaterThan(0.5);
});
it("senkrechte Netzdreiecke (Stütze) blockieren", () => {
// Quadratische Stütze 0.4 m bei (0,0), Höhe 3 m: nur die vier Seiten (je zwei Dreiecke), Modell-Koordinaten (x, y, z=Höhe).
const q = (a: [number, number], b: [number, number]) => [a[0], a[1], 0, b[0], b[1], 0, b[0], b[1], 3, a[0], a[1], 3];
const pos = [...q([-0.2, -0.2], [0.2, -0.2]), ...q([0.2, -0.2], [0.2, 0.2]), ...q([0.2, 0.2], [-0.2, 0.2]), ...q([-0.2, 0.2], [-0.2, -0.2])];
const indices: number[] = [];
for (let i = 0; i < 4; i++) indices.push(i * 4, i * 4 + 1, i * 4 + 2, i * 4, i * 4 + 2, i * 4 + 3);
const w = world({ meshes: [{ positions: pos, indices }] });
expect(w.move(0.05, -2, 0, 4, 0)[1]).toBeLessThan(-0.4);
expect(w.move(1, -2, 0, 4, 0)[1]).toBeGreaterThan(1);
});
});
describe("Boden", () => {
it("Decken-Oberseite ist Boden, nichts darüber: Boden höchstens eine Stufe über den Füssen", () => {
const w = world({ slabs: [floorSlab(-10, 10, 0), floorSlab(-10, 10, 3)] });
expect(w.groundAt(0, 0, 0 + STEP_UP)).toBe(0);
expect(w.groundAt(0, 0, 3.1)).toBe(3);
expect(w.groundAt(30, 0, 5)).toBeNull();
});
it("Dreiecksnetz (Rampe) liefert die interpolierte Höhe", () => {
// Rampe in Modell-Koordinaten (x, y, z=Höhe): z = 0.5 * x über x in [0, 4].
const positions = [0, 0, 0, 4, 0, 2, 4, 4, 2, 0, 4, 0];
const w = world({ meshes: [{ positions, indices: [0, 1, 2, 0, 2, 3], kind: "extrusion" }] });
expect(w.groundAt(2, 1, 10)).toBeCloseTo(1, 6);
expect(w.groundAt(3, 3, 10)).toBeCloseTo(1.5, 6);
});
it("Gelände-Netze haben die Nord-Negation (world-z = −y)", () => {
const positions = [-5, -5, 0.5, 5, -5, 0.5, 5, 5, 0.5, -5, 5, 0.5];
const w = world({ meshes: [{ positions, indices: [0, 1, 2, 0, 2, 3], kind: "terrain" }] });
expect(w.groundAt(0, 3, 10)).toBeCloseTo(0.5, 6);
expect(w.groundAt(0, -3, 10)).toBeCloseTo(0.5, 6);
});
});
const orbitAt = (x: number, eyeY: number, z: number, yaw = Math.PI): OrbitState => {
// yaw = π: Blick nach +x (Vorwärts = (−cos yaw, 0, −sin yaw) = (1, 0, 0)).
const dist = 3;
return { yaw, pitch: 0, dist, target: [x - dist * Math.cos(yaw), eyeY, z - dist * Math.sin(yaw)], ortho: false, orthoHalfHeight: 5 };
};
const fwd: WalkKeys = { ...NO_KEYS, forward: true };
function run(w: WalkWorld, o: OrbitState, keys: WalkKeys, seconds: number, speed = 3) {
let body = initBody(o, w);
let orbit = o;
const dt = 1 / 60;
for (let t = 0; t < seconds; t += dt) ({ orbit, body } = stepWalkCollide(orbit, body, keys, dt, speed, w));
return { orbit, body, eye: orbitEye(orbit) };
}
const stairTreads = (): WalkSlab[] => {
// 12 Tritte als Decken-Prismen, Auftritt 0.3 m, ab x = 1, Steigung 0.18 m.
const treads: WalkSlab[] = [];
for (let i = 0; i < 12; i++) treads.push({ outline: [[1 + i * 0.3, -1], [1.3 + i * 0.3, -1], [1.3 + i * 0.3, 1], [1 + i * 0.3, 1]], zBottom: 0, zTop: 0.18 * (i + 1) });
return treads;
};
describe("Begehen mit Bodenfolge", () => {
it("auf einer Treppe steigt man mit, ohne hängenzubleiben", () => {
const w = world({ slabs: [floorSlab(-10, 1, 0), ...stairTreads(), floorSlab(4.6, 12, 2.16)] });
const r = run(w, orbitAt(-1, EYE_HEIGHT, 0), fwd, 3);
expect(r.eye[0]).toBeGreaterThan(5);
expect(r.body.feetY).toBeCloseTo(2.16, 2);
expect(r.eye[1]).toBeCloseTo(2.16 + EYE_HEIGHT, 2);
});
it("auf der Treppe ist die Augenhöhe stetig: pro Bild nur ein Bruchteil der Stufe", () => {
const w = world({ slabs: [floorSlab(-10, 1, 0), ...stairTreads()] });
let o = orbitAt(0, EYE_HEIGHT, 0);
let body = initBody(o, w);
let maxJump = 0;
for (let i = 0; i < 200; i++) {
const before = orbitEye(o)[1];
({ orbit: o, body } = stepWalkCollide(o, body, fwd, 1 / 60, 2, w));
maxJump = Math.max(maxJump, Math.abs(orbitEye(o)[1] - before));
}
expect(orbitEye(o)[1]).toBeGreaterThan(EYE_HEIGHT + 1);
expect(maxJump).toBeLessThan(0.1);
});
it("eine Stufe von 0.4 m blockiert, 0.2 m nicht", () => {
const high = world({ slabs: [floorSlab(-10, 2, 0), floorSlab(2, 10, 0.4)] });
const a = run(high, orbitAt(0, EYE_HEIGHT, 0), fwd, 3);
expect(a.eye[0]).toBeLessThan(2 - PERSON_RADIUS + 0.01);
expect(a.body.feetY).toBeCloseTo(0, 2);
const low = world({ slabs: [floorSlab(-10, 2, 0), floorSlab(2, 10, 0.2)] });
const b = run(low, orbitAt(0, EYE_HEIGHT, 0), fwd, 3);
expect(b.eye[0]).toBeGreaterThan(5);
expect(b.body.feetY).toBeCloseTo(0.2, 2);
});
it("fällt der Boden weg, sinkt man sanft bis zum nächsten Boden (nicht in einem Bild)", () => {
const w = world({ slabs: [floorSlab(-10, 2, 3), floorSlab(2, 12, 0)] });
let o = orbitAt(0, 3 + EYE_HEIGHT, 0);
let body = initBody(o, w);
expect(body.feetY).toBeCloseTo(3, 6);
let maxDrop = 0;
for (let i = 0; i < 300; i++) {
const before = orbitEye(o)[1];
({ orbit: o, body } = stepWalkCollide(o, body, fwd, 1 / 60, 3, w));
maxDrop = Math.max(maxDrop, before - orbitEye(o)[1]);
}
expect(orbitEye(o)[0]).toBeGreaterThan(3);
expect(body.feetY).toBeCloseTo(0, 2);
expect(maxDrop).toBeGreaterThan(0);
expect(maxDrop).toBeLessThanOrEqual(5 / 60 + 1e-9);
expect(bodySettling(body)).toBe(false);
});
it("Q/E ändern die Augenhöhe begrenzt; ohne Boden bleibt die Höhe stehen", () => {
const w = world({ slabs: [floorSlab(-10, 10, 0)] });
const up = run(w, orbitAt(0, EYE_HEIGHT, 0), { ...NO_KEYS, up: true }, 5);
expect(up.body.eyeHeight).toBeLessThanOrEqual(2.3);
expect(up.eye[1]).toBeCloseTo(up.body.eyeHeight, 3);
const empty = run(world({}), orbitAt(0, 4, 0), fwd, 1);
expect(empty.eye[1]).toBeCloseTo(4, 6);
});
it("läuft gegen eine Wand: Blickrichtung bleibt, Person steht davor", () => {
const w = world({ walls: [{ start: [3, -5], end: [3, 5], thickness: 0.2, height: 2.6, baseElevation: 0 }], slabs: [floorSlab(-10, 10, 0)] });
const r = run(w, orbitAt(0, EYE_HEIGHT, 0), fwd, 3);
expect(r.eye[0]).toBeCloseTo(3 - 0.1 - PERSON_RADIUS, 2);
expect(r.orbit.yaw).toBe(Math.PI);
});
});
+418
View File
@@ -0,0 +1,418 @@
// [245] Begehen mit Kollision und Bodenfolge: reine Rechnung auf einer einfachen räumlichen Struktur (Raster in der
// Grundrissebene) aus den 3D-Teilen, die der Viewer ohnehin hat (Wand-Quader mit Löchern, Decken-/Tritt-Prismen,
// Netze). Ohne React und Engine, damit testbar. Kein Ray-Test gegen das ganze Modell: je Schritt nur Rasterzellen
// im Umkreis der Person.
//
// KONVENTION wie render3d: Modell (x, y, z=Höhe) → world (x, Höhe, y); Gelände und Import-Netze mit Nord-Negation
// (x, Höhe, −y) wie in `model3d/pick.rs`. Alle Zahlen hier sind world-Meter.
//
// Hindernisse sind senkrechte „Kapseln": eine Strecke in der XZ-Ebene mit Halbdicke `h` und Höhenband [y0, y1].
// • Wand = Strecke entlang der Achse (Halbdicke = halbe Wandstärke), in Stücke ausserhalb der Löcher geteilt;
// über und unter einem Loch bleiben Sturz bzw. Brüstung. Ein Loch bis zur Wand-UK ist eine Tür (frei),
// ein Loch mit Brüstung ein Fenster: dort sperrt zusätzlich die Glasebene (nicht passierbar).
// • Decken-/Trittkante = Polygonkante über [zBottom, zTop]; senkrechte Dreiecke der Netze (Stützen, Körper) ebenso.
// Böden sind die Oberseiten der Decken/Tritte (Polygon, Höhe zTop) und alle Dreiecke mit nach oben zeigender Normale
// (Gelände, Dächer, Körper).
/** Person: Radius und Körperhöhe (m); Stufen bis `STEP_UP` steigt man ohne Hindernis. */
export const PERSON_RADIUS = 0.25;
export const PERSON_HEIGHT = 1.8;
export const STEP_UP = 0.25;
const CELL = 2;
/** Mehr Zellen als das → Eintrag kommt in die Liste „gross" (immer geprüft), statt Zehntausende Zellen zu füllen. */
const MAX_CELLS_PER_ENTRY = 1024;
const EPS = 1e-6;
type V2 = readonly [number, number];
type Tri3 = readonly [number, number, number, number, number, number, number, number, number];
/** Minimalformen der Eingabe (RModel3d erfüllt sie strukturell). */
export interface WalkWall {
start: V2;
end: V2;
thickness: number;
height: number;
baseElevation: number;
holes?: ReadonlyArray<{ from: number; to: number; zBottom: number; zTop: number }>;
}
export interface WalkSlab {
outline: ReadonlyArray<V2>;
zBottom: number;
zTop: number;
}
export interface WalkMesh {
/** Flach (x, y, z=Höhe) in Modell-Metern. */
positions: ReadonlyArray<number>;
indices: ReadonlyArray<number>;
/** `terrain`/`imported`: world-z = −y. */
kind?: string;
}
export interface WalkModelInput {
walls: ReadonlyArray<WalkWall>;
slabs: ReadonlyArray<WalkSlab>;
meshes: ReadonlyArray<WalkMesh>;
}
interface Obstacle {
x0: number;
z0: number;
x1: number;
z1: number;
/** Halbdicke. */
h: number;
y0: number;
y1: number;
}
interface Floor {
/** Dreieck (neun Zahlen, world) oder Polygon mit fester Höhe. */
tri?: Tri3;
poly?: ReadonlyArray<V2>;
y: number;
}
const key = (ix: number, iz: number): number => (ix + 5_000_000) * 10_000_000 + (iz + 5_000_000);
/** Obergrenze für Dreiecke aus Netzen (Speicher/Bauzeit); der Rest bleibt unberücksichtigt. */
export const MAX_MESH_TRIS = 600_000;
export class WalkWorld {
private obstacles: Obstacle[] = [];
private floors: Floor[] = [];
private obstacleCells = new Map<number, number[]>();
private floorCells = new Map<number, number[]>();
private bigObstacles: number[] = [];
private bigFloors: number[] = [];
/** Zahl der Dreiecke aus Netzen, die nicht mehr aufgenommen wurden. */
skippedTris = 0;
constructor(input: WalkModelInput) {
for (const w of input.walls) this.addWall(w);
for (const s of input.slabs) this.addSlab(s);
let budget = MAX_MESH_TRIS;
for (const m of input.meshes) {
const n = Math.floor(m.indices.length / 3);
if (n > budget) {
this.skippedTris += n;
continue;
}
budget -= n;
this.addMesh(m);
}
}
get obstacleCount(): number {
return this.obstacles.length;
}
get floorCount(): number {
return this.floors.length;
}
// ── Aufbau ─────────────────────────────────────────────────────────────────────────────────────────────────
private addObstacle(o: Obstacle): void {
if (!(o.y1 > o.y0) || ![o.x0, o.z0, o.x1, o.z1, o.h, o.y0, o.y1].every(Number.isFinite)) return;
const id = this.obstacles.length;
this.obstacles.push(o);
const r = o.h;
this.index(this.obstacleCells, this.bigObstacles, id, Math.min(o.x0, o.x1) - r, Math.min(o.z0, o.z1) - r, Math.max(o.x0, o.x1) + r, Math.max(o.z0, o.z1) + r);
}
private addFloor(f: Floor, x0: number, z0: number, x1: number, z1: number): void {
const id = this.floors.length;
this.floors.push(f);
this.index(this.floorCells, this.bigFloors, id, x0, z0, x1, z1);
}
private index(cells: Map<number, number[]>, big: number[], id: number, x0: number, z0: number, x1: number, z1: number): void {
const ix0 = Math.floor(x0 / CELL);
const ix1 = Math.floor(x1 / CELL);
const iz0 = Math.floor(z0 / CELL);
const iz1 = Math.floor(z1 / CELL);
if (!(Number.isFinite(ix0 + ix1 + iz0 + iz1)) || (ix1 - ix0 + 1) * (iz1 - iz0 + 1) > MAX_CELLS_PER_ENTRY) {
big.push(id);
return;
}
for (let ix = ix0; ix <= ix1; ix++) {
for (let iz = iz0; iz <= iz1; iz++) {
const k = key(ix, iz);
const l = cells.get(k);
if (l) l.push(id);
else cells.set(k, [id]);
}
}
}
private addWall(w: WalkWall): void {
const [sx, sz] = w.start;
const [ex, ez] = w.end;
const len = Math.hypot(ex - sx, ez - sz);
if (!(len > EPS) || !(w.height > 0)) return;
const ux = (ex - sx) / len;
const uz = (ez - sz) / len;
const h = Math.max(0, w.thickness) / 2;
const base = w.baseElevation;
const top = base + w.height;
const at = (s: number): V2 => [sx + ux * s, sz + uz * s];
const piece = (a: number, b: number, y0: number, y1: number) => {
if (b - a < EPS || y1 - y0 < EPS) return;
const p = at(a);
const q = at(b);
this.addObstacle({ x0: p[0], z0: p[1], x1: q[0], z1: q[1], h, y0, y1 });
};
const holes = [...(w.holes ?? [])]
.map((o) => ({ from: Math.max(0, Math.min(o.from, o.to)), to: Math.min(len, Math.max(o.from, o.to)), zBottom: o.zBottom, zTop: o.zTop }))
.filter((o) => o.to - o.from > EPS)
.sort((a, b) => a.from - b.from);
let cursor = 0;
for (const o of holes) {
piece(cursor, o.from, base, top);
// Brüstung unter und Sturz über dem Loch.
piece(o.from, o.to, base, Math.min(top, o.zBottom));
piece(o.from, o.to, Math.max(base, o.zTop), top);
// Fenster (Loch mit Brüstung): die Glasebene sperrt, auch wo die Brüstung niedriger als die Stufenhöhe ist.
if (o.zBottom > base + EPS) {
const m = (o.from + o.to) / 2;
const half = (o.to - o.from) / 2;
const p = at(m - half);
const q = at(m + half);
this.addObstacle({ x0: p[0], z0: p[1], x1: q[0], z1: q[1], h: 0.02, y0: Math.max(base, o.zBottom), y1: Math.min(top, o.zTop) });
}
cursor = Math.max(cursor, o.to);
}
piece(cursor, len, base, top);
}
private addSlab(s: WalkSlab): void {
const pts = s.outline.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));
if (pts.length < 3 || !(s.zTop >= s.zBottom)) return;
let minX = Infinity;
let minZ = Infinity;
let maxX = -Infinity;
let maxZ = -Infinity;
for (const p of pts) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
minZ = Math.min(minZ, p[1]);
maxZ = Math.max(maxZ, p[1]);
}
this.addFloor({ poly: pts, y: s.zTop }, minX, minZ, maxX, maxZ);
for (let i = 0; i < pts.length; i++) {
const a = pts[i];
const b = pts[(i + 1) % pts.length];
this.addObstacle({ x0: a[0], z0: a[1], x1: b[0], z1: b[1], h: 0, y0: s.zBottom, y1: s.zTop });
}
}
private addMesh(m: WalkMesh): void {
const flip = m.kind === "terrain" || m.kind === "imported" ? -1 : 1;
const p = m.positions;
const idx = m.indices;
const vx = (i: number) => p[i * 3];
const vy = (i: number) => p[i * 3 + 2];
const vz = (i: number) => p[i * 3 + 1] * flip;
for (let t = 0; t + 2 < idx.length; t += 3) {
const a = idx[t];
const b = idx[t + 1];
const c = idx[t + 2];
if (a * 3 + 2 >= p.length || b * 3 + 2 >= p.length || c * 3 + 2 >= p.length) continue;
const x = [vx(a), vx(b), vx(c)];
const y = [vy(a), vy(b), vy(c)];
const z = [vz(a), vz(b), vz(c)];
if (![...x, ...y, ...z].every(Number.isFinite)) continue;
// Normale (world), Y-Anteil entscheidet: Boden, Wand oder Decke/Unterseite.
const e1 = [x[1] - x[0], y[1] - y[0], z[1] - z[0]];
const e2 = [x[2] - x[0], y[2] - y[0], z[2] - z[0]];
const nx = e1[1] * e2[2] - e1[2] * e2[1];
const ny = e1[2] * e2[0] - e1[0] * e2[2];
const nz = e1[0] * e2[1] - e1[1] * e2[0];
const nl = Math.hypot(nx, ny, nz);
if (!(nl > 1e-12)) continue;
// Das Modell ist rechtshändig (x, y, z=Höhe); in world (x, z, y) kippt die Orientierung: Betrag zählt, nicht das Vorzeichen.
const upness = Math.abs(ny) / nl;
if (upness > 0.5) {
// Dreieck als Boden. Ohne Orientierung gilt jede flache Fläche als begehbar (auch Unterseiten): die Bodenabfrage
// nimmt ohnehin nur Flächen bis Fusshöhe + Stufe, Dächer und Decken darüber bleiben aussen vor.
this.addFloor(
{ tri: [x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2]], y: 0 },
Math.min(...x),
Math.min(...z),
Math.max(...x),
Math.max(...z),
);
} else {
// Senkrechtes Dreieck: die zwei am weitesten entfernten Punkte in der Grundrissebene bilden die Strecke.
let best = 0;
let bi = 0;
let bj = 1;
for (const [i, j] of [[0, 1], [1, 2], [0, 2]] as const) {
const d = Math.hypot(x[i] - x[j], z[i] - z[j]);
if (d > best) {
best = d;
bi = i;
bj = j;
}
}
if (best < 1e-3) continue;
this.addObstacle({ x0: x[bi], z0: z[bi], x1: x[bj], z1: z[bj], h: 0, y0: Math.min(...y), y1: Math.max(...y) });
}
}
}
// ── Abfragen ───────────────────────────────────────────────────────────────────────────────────────────────
/**
* Höhe des Bodens unter (x, z): die höchste begehbare Fläche mit Höhe ≤ `maxY`. `null`, wenn dort gar nichts liegt
* (ausserhalb des Modells). Genau ein Ray-Test nach unten, nur gegen die Rasterzelle.
*/
groundAt(x: number, z: number, maxY: number): number | null {
let best: number | null = null;
const test = (id: number) => {
const f = this.floors[id];
let y: number | null = null;
if (f.poly) {
if (pointInPoly(x, z, f.poly)) y = f.y;
} else if (f.tri) {
y = triHeight(f.tri, x, z);
}
if (y !== null && y <= maxY + EPS && (best === null || y > best)) best = y;
};
const cell = this.floorCells.get(key(Math.floor(x / CELL), Math.floor(z / CELL)));
if (cell) for (const id of cell) test(id);
for (const id of this.bigFloors) test(id);
return best;
}
/**
* Bewegung (x, z) → (x + dx, z + dz) einer Person mit den Füssen auf `feetY`. Teilschritte gegen Durchtunneln;
* Hindernisse werden herausgeschoben, die Person gleitet also an Wänden entlang. Gibt die neue Lage zurück.
*/
move(x: number, z: number, dx: number, dz: number, feetY: number, radius: number = PERSON_RADIUS): V2 {
const dist = Math.hypot(dx, dz);
if (!(dist > 0) || !Number.isFinite(dist)) return [x, z];
const steps = Math.max(1, Math.ceil(dist / (radius * 0.6)));
const sx = dx / steps;
const sz = dz / steps;
let px = x;
let pz = z;
for (let i = 0; i < steps; i++) {
const prevX = px;
const prevZ = pz;
px += sx;
pz += sz;
[px, pz] = this.pushOut(px, pz, prevX, prevZ, feetY, radius);
}
return [px, pz];
}
/** Ist die Person an dieser Stelle frei (kein Hindernis im Körperband)? */
isFree(x: number, z: number, feetY: number, radius: number = PERSON_RADIUS): boolean {
let free = true;
this.forNearby(x, z, radius, feetY, (o) => {
if (segDist(x, z, o) < o.h + radius - 1e-4) free = false;
});
return free;
}
private pushOut(px0: number, pz0: number, prevX: number, prevZ: number, feetY: number, radius: number): V2 {
let px = px0;
let pz = pz0;
// Mehrere Durchgänge: ein Schub kann in die nächste Wand führen (Ecke).
for (let pass = 0; pass < 4; pass++) {
let moved = false;
this.forNearby(px, pz, radius, feetY, (o) => {
const [cx, cz] = closestOnSeg(px, pz, o);
let nx = px - cx;
let nz = pz - cz;
const d = Math.hypot(nx, nz);
const need = o.h + radius;
if (d >= need - 1e-9) return;
if (d > 1e-9) {
nx /= d;
nz /= d;
} else {
// Genau auf der Achse: zur Seite schieben, von der die Person kam.
const ax = o.x1 - o.x0;
const az = o.z1 - o.z0;
const al = Math.hypot(ax, az) || 1;
nx = -az / al;
nz = ax / al;
if (nx * (prevX - cx) + nz * (prevZ - cz) < 0) {
nx = -nx;
nz = -nz;
}
}
px = cx + nx * need;
pz = cz + nz * need;
moved = true;
});
if (!moved) break;
}
return [px, pz];
}
/** Alle Hindernisse im Umkreis, deren Höhenband den Körper (Füsse + Stufe … Füsse + Körperhöhe) trifft. */
private forNearby(x: number, z: number, radius: number, feetY: number, fn: (o: Obstacle) => void): void {
const lo = feetY + STEP_UP + EPS;
const hi = feetY + PERSON_HEIGHT;
const seen = new Set<number>();
const visit = (id: number) => {
if (seen.has(id)) return;
seen.add(id);
const o = this.obstacles[id];
if (o.y1 <= lo || o.y0 >= hi) return;
fn(o);
};
const ix0 = Math.floor((x - radius - 1e-9) / CELL);
const ix1 = Math.floor((x + radius + 1e-9) / CELL);
const iz0 = Math.floor((z - radius - 1e-9) / CELL);
const iz1 = Math.floor((z + radius + 1e-9) / CELL);
for (let ix = ix0; ix <= ix1; ix++) {
for (let iz = iz0; iz <= iz1; iz++) {
const l = this.obstacleCells.get(key(ix, iz));
if (l) for (const id of l) visit(id);
}
}
for (const id of this.bigObstacles) visit(id);
}
}
// ── Geometrie ────────────────────────────────────────────────────────────────────────────────────────────────
function closestOnSeg(px: number, pz: number, o: Obstacle): V2 {
const ax = o.x1 - o.x0;
const az = o.z1 - o.z0;
const l2 = ax * ax + az * az;
const t = l2 > 0 ? Math.max(0, Math.min(1, ((px - o.x0) * ax + (pz - o.z0) * az) / l2)) : 0;
return [o.x0 + ax * t, o.z0 + az * t];
}
function segDist(px: number, pz: number, o: Obstacle): number {
const [cx, cz] = closestOnSeg(px, pz, o);
return Math.hypot(px - cx, pz - cz);
}
/** Punkt im Polygon (gerade/ungerade Regel). */
export function pointInPoly(x: number, z: number, poly: ReadonlyArray<V2>): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const [xi, zi] = poly[i];
const [xj, zj] = poly[j];
if (zi > z !== zj > z && x < ((xj - xi) * (z - zi)) / (zj - zi) + xi) inside = !inside;
}
return inside;
}
/** Höhe des Dreiecks (world) über (x, z); `null`, wenn der Punkt ausserhalb liegt (kleine Toleranz gegen Fugen). */
function triHeight(t: Tri3, x: number, z: number): number | null {
const [ax, ay, az, bx, by, bz, cx, cy, cz] = t;
const d = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);
if (Math.abs(d) < 1e-12) return null;
const l1 = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / d;
const l2 = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / d;
const l3 = 1 - l1 - l2;
const tol = -1e-6;
if (l1 < tol || l2 < tol || l3 < tol) return null;
return l1 * ay + l2 * by + l3 * cy;
}