Merge [K1][K2] Boegen und Treppen nach Rust; Abkuerzung ohne WASM-Aufruf fuer gerade Segmente/Polylinien ohne Bogen

bulgeArc und bulgePolylinePoints rufen den Kern nur noch bei echten Boegen auf (gleiche Schwelle 1e-9 wie
kernel2d::bulge); sonst liefe die Plan-Erzeugung bei Katasterimporten fuer Millionen gerader Segmente
ueber die WASM-Grenze. Test prueft Gleichheit mit dem Rust-Pfad.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-27 21:44:50 +00:00
commit e3fa37e1ae
21 files changed
+1420 -734

No files matched your search

+52
View File
@@ -10,6 +10,7 @@ import {
arcThroughPoints,
bulgeArc,
bulgeArcPoints,
bulgePolylinePoints,
bulgeFromSagittaPoint,
bulgeThroughPoint,
} from "./bulge";
@@ -269,3 +270,54 @@ describe("arcFromStartEndDirection — Start/Ende/Tangentenrichtung (commands/cm
expect(arcFromStartEndDirection({ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 0 })).toBeNull();
});
});
describe("bulgePolylinePoints (ganze Polylinie auf einmal)", () => {
const sq: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }];
it("entspricht der Verkettung von bulgeArcPoints je Kante", () => {
const bulge = [1, 0, -0.5, 0];
const expected: Vec2[] = [sq[0]];
for (let i = 0; i < 3; i++) expected.push(...bulgeArcPoints(sq[i], sq[i + 1], bulge[i]).slice(1));
const got = bulgePolylinePoints(sq, bulge, false);
expect(got.length).toBe(expected.length);
got.forEach((p, i) => {
expect(p.x).toBeCloseTo(expected[i].x, 12);
expect(p.y).toBeCloseTo(expected[i].y, 12);
});
});
it("geschlossen: Schlusskante enthalten, Startpunkt nicht wiederholt", () => {
const got = bulgePolylinePoints(sq, [0, 0, 0, 1], true);
expect(got[0]).toEqual(sq[0]);
expect(got[got.length - 1]).not.toEqual(sq[0]);
// Schlusskante (0,2)→(0,0) läuft nach −y, links davon ist +x: Halbkreis nach x > 0
expect(got.some((p) => p.x > 0.5 && p.y > 0.5 && p.y < 1.5)).toBe(true);
});
it("Unsinn (leer, NaN) ohne Fehler", () => {
expect(bulgePolylinePoints([], undefined, true)).toEqual([]);
expect(bulgePolylinePoints([{ x: NaN, y: 0 }, { x: 1, y: 0 }], [1], false)).toEqual([]);
expect(bulgeArc({ x: NaN, y: 0 }, { x: 1, y: 0 }, 1)).toBeNull();
expect(bulgeThroughPoint({ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 2, y: 0 })).toBe(0);
expect(bulgeArcPoints({ x: 0, y: 0 }, { x: 1, y: 0 }, NaN)).toHaveLength(2);
});
});
describe("Abkürzung ohne Bögen (kein WASM-Aufruf)", () => {
it("bulgePolylinePoints: gleiches Ergebnis wie der Rust-Pfad, offen und geschlossen", async () => {
const { core } = await import("../engine/coreWasm");
const pts = [{ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 3, y: 2 }, { x: 0, y: 2 }];
const flat = Float64Array.from(pts.flatMap((p) => [p.x, p.y]));
for (const closed of [false, true]) {
const viaRust = Array.from(core().bulge_polyline_points(flat, Float64Array.from([0, 0, 0, 0]), closed));
const fast = bulgePolylinePoints(pts, [0, 0, 0, 0], closed).flatMap((p) => [p.x, p.y]);
expect(fast).toEqual(viaRust);
expect(bulgePolylinePoints(pts, undefined, closed)).toEqual(pts);
}
});
it("bulgeArc: gerade und NaN → null", () => {
expect(bulgeArc({ x: 0, y: 0 }, { x: 1, y: 0 }, 0)).toBeNull();
expect(bulgeArc({ x: 0, y: 0 }, { x: 1, y: 0 }, Number.NaN)).toBeNull();
expect(bulgeArc({ x: 0, y: 0 }, { x: 1, y: 0 }, 1)).not.toBeNull();
});
});
+82 -209
View File
@@ -1,17 +1,19 @@
// Bulge — DXF-Konvention für Bogen-Segmente in Polylinien: `bulge = tan(Δ/4)`
// (Δ = Öffnungswinkel des Kreisbogens von a nach b). Reine Geometrie, keine
// Abhängigkeit vom Modell — s. Kopfkommentar bei `Drawing2DGeom["polyline"].
// bulge` (model/types.ts) für die Feld-Semantik.
// (Δ = Öffnungswinkel des Kreisbogens von a nach b). Dünne Fassade über den Rust-Kern
// (`src-tauri/kernel2d/src/bulge.rs`, Bindungen `src-tauri/core/src/web/bulge.rs`); die
// Formeln (Sehnen-Pfeilhöhen-Beziehung `r = (h²+s²)/(2s)`, `s = h·bulge`) stehen nur dort.
// Feld-Semantik: s. Kopfkommentar bei `Drawing2DGeom["polyline"].bulge` (model/types.ts).
//
// Herleitung (Sehnen-Pfeilhöhen-Beziehung, exakt, ohne Kreisbogen-Trigonometrie
// im Radius): für eine Sehne der halben Länge h mit Pfeilhöhe (Sagitta) s gilt
// die Kreissegment-Identität r = (h²+s²) / (2s). Die Bulge-Definition liefert
// zusätzlich exakt s = h·bulge (Standard-Identität (1−cosX)/sinX = tan(X/2)
// mit X = Δ/2). Damit lässt sich der komplette Bogen (Zentrum/Radius) ohne
// eine einzige inverse Winkelfunktion aus bulge ableiten.
// Einzelaufrufe geben skalare Argumente, ganze Polylinien gehen auf einmal über
// `bulgePolylinePoints` (flache `Float64Array`s, Muster `coreFlat.ts`).
//
// Bewusst in TS geblieben (zwei Einzeiler, kein Rechenkern):
// • `hasRealBulge` — läuft pro Zeichnung/Befehl über das bulge-Array; ein WASM-Aufruf müsste das
// Array erst in eine `Float64Array` kopieren und wäre langsamer als `some` (Messung s. Commit).
// • `pointOnCircle` — zwei Multiplikationen je Punkt, in Schleifen aufgerufen.
import type { Vec2 } from "../model/types";
import { lineIntersect } from "../model/geometry";
import { core } from "../engine/coreWasm";
const EPS = 1e-9;
@@ -31,116 +33,69 @@ interface BulgeArc {
/** Kreisbogen-Parameter aus zwei Endpunkten + `bulge`, oder `null` bei (nahezu) 0 (Gerade). */
export function bulgeArc(a: Vec2, b: Vec2, bulge: number): BulgeArc | null {
if (Math.abs(bulge) < EPS) return null;
const dx = b.x - a.x, dy = b.y - a.y;
const chord = Math.hypot(dx, dy);
if (chord < EPS) return null;
const ux = dx / chord, uy = dy / chord;
const nx = -uy, ny = ux; // Links-Normale von a→b
const h = chord / 2;
const s = h * bulge; // Sagitta (Pfeilhöhe), Vorzeichen wie bulge
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
const rSigned = (h * h + s * s) / (2 * s);
const cx = mx + nx * (s - rSigned);
const cy = my + ny * (s - rSigned);
const r = Math.abs(rSigned);
const apexX = mx + nx * s, apexY = my + ny * s;
const a0 = Math.atan2(a.y - cy, a.x - cx);
const a1 = Math.atan2(b.y - cy, b.x - cx);
const aApex = Math.atan2(apexY - cy, apexX - cx);
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
// Die Sehnenmitte (Apex) liegt per Konstruktion auf dem Bogen — die Schwenk-
// richtung (CCW oder CW von a0 nach a1) ist genau die, die den Apex-Winkel
// unterwegs passiert. Robust gegen Vorzeichenfehler in der Herleitung oben:
// wird direkt gegen den bekannten Apex-Punkt geprüft statt abstrakt hergeleitet.
const ccwSweep = norm(a1 - a0);
const ccwPassesApex = norm(aApex - a0) <= ccwSweep + 1e-7;
const sweep = ccwPassesApex ? ccwSweep : -(TAU - ccwSweep);
return { center: { x: cx, y: cy }, r, a0, a1, sweep };
// Gerades Segment (der Normalfall, z. B. Millionen Katasterlinien): ohne WASM-Aufruf, gleiche
// Schwelle wie `kernel2d::bulge::bulge_arc`.
if (!(Math.abs(bulge) >= EPS)) return null;
const r = core().bulge_arc(a.x, a.y, b.x, b.y, bulge);
if (r.length < 6) return null;
return { center: { x: r[0], y: r[1] }, r: r[2], a0: r[3], a1: r[4], sweep: r[5] };
}
function toPoints(f: Float64Array): Vec2[] {
const out: Vec2[] = new Array(f.length >> 1);
for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] };
return out;
}
/**
* Tessellierte Bogenpunkte von a nach b (inkl. beider Endpunkte) — für
* Rendering/Fläche/Hit-Test/Export, die nur Geradensegmente kennen (analog
* `circlePts`/`ellipsePts`). `null`-Bulge (Gerade) liefert `[a, b]`.
* Rendering/Fläche/Hit-Test/Export, die nur Geradensegmente kennen. Gerade
* (bulge fehlt/0) liefert `[a, b]`. Gerade Segmentzahl, damit der Apex (t=0.5)
* ein echter Punkt in der Mitte ist (s. `bulgePointAt`).
*/
export function bulgeArcPoints(a: Vec2, b: Vec2, bulge: number | undefined): Vec2[] {
const arc = bulge !== undefined ? bulgeArc(a, b, bulge) : null;
if (!arc) return [a, b];
const { center, r, a0, sweep } = arc;
// Auflösung: ~1 Segment je 12° reicht für Plan-Massstäbe (analog `circlePts`
// N=48 bei vollem Kreis ⇒ 7.5°/Segment; hier etwas gröber, dafür adaptiv zur
// tatsächlichen Bogenlänge statt immer 48 Punkte für jedes kleine Bögchen).
// Gerade Segmentzahl erzwingen, damit der exakte Apex-Punkt (t=0.5) immer
// als echter Tessellations-Punkt in der Mitte des Arrays landet (wichtig
// für den Bulge-Griff, s. `bulgePointAt`).
let N = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 15)));
if (N % 2 !== 0) N += 1;
const pts: Vec2[] = [];
for (let i = 0; i <= N; i++) {
const t = a0 + sweep * (i / N);
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
if (bulge === undefined || bulge === 0) return [a, b];
return toPoints(core().bulge_arc_points(a.x, a.y, b.x, b.y, bulge));
}
/**
* Ganze Polylinie tessellieren (`bulge[i]` krümmt die Kante pts[i]→pts[i+1], geschlossen zusätzlich
* die Schlusskante). Kantenpunkte verkettet ohne doppelte Stösse; bei `closed` wird der Startpunkt
* am Ende nicht wiederholt.
*/
export function bulgePolylinePoints(pts: readonly Vec2[], bulge: readonly number[] | undefined, closed: boolean): Vec2[] {
// Ohne echten Bogen liefert Rust genau die Eingabepunkte (offen wie geschlossen) — dann ohne
// WASM-Aufruf und Kopie in Float64Arrays (Plan-Erzeugung ruft das für jede Polylinie).
if (!hasRealBulge(bulge as number[] | undefined)) return pts.slice();
const flat = new Float64Array(pts.length * 2);
for (let i = 0; i < pts.length; i++) {
flat[2 * i] = pts[i].x;
flat[2 * i + 1] = pts[i].y;
}
return pts;
return toPoints(core().bulge_polyline_points(flat, Float64Array.from(bulge ?? []), closed));
}
/**
* Bulge aus einem gezogenen Punkt `p` relativ zur Sehne a-b ableiten (Griff-
* Interaktion: Segment-Mitte senkrecht zur Sehne ziehen). Exakt die Umkehrung
* der `s = h·bulge`-Identität oben — kein Winkel involviert.
* Interaktion: Segment-Mitte senkrecht zur Sehne ziehen). Umkehrung von `s = h·bulge`.
*/
export function bulgeFromSagittaPoint(a: Vec2, b: Vec2, p: Vec2): number {
const dx = b.x - a.x, dy = b.y - a.y;
const chord = Math.hypot(dx, dy);
if (chord < EPS) return 0;
const ux = dx / chord, uy = dy / chord;
const nx = -uy, ny = ux;
const h = chord / 2;
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
const s = (p.x - mx) * nx + (p.y - my) * ny;
return s / h;
return core().bulge_from_sagitta_point(a.x, a.y, b.x, b.y, p.x, p.y);
}
/** Punkt auf dem aktuellen Bogen bei Parameter t∈[0,1] (0=a, 1=b, 0.5=Apex) — für den Bulge-Griff. */
export function bulgePointAt(a: Vec2, b: Vec2, bulge: number, t: number): Vec2 {
const pts = bulgeArcPoints(a, b, bulge);
if (pts.length <= 2) return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
const idx = Math.round(t * (pts.length - 1));
return pts[Math.max(0, Math.min(pts.length - 1, idx))];
const r = core().bulge_point_at(a.x, a.y, b.x, b.y, bulge, t);
return { x: r[0], y: r[1] };
}
/**
* Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der
* klassische Drei-Punkt-Bogen. Anders als die Tangenten-Variante hängt er NUR
* von diesen drei Punkten ab, nicht vom vorherigen Segment: Radius und
* Wölbung sind damit pro Segment frei wählbar (Nutzer-Anforderung).
*
* Liegen die drei Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis —
* dann 0 (gerade).
* Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der klassische
* Drei-Punkt-Bogen, nur von diesen drei Punkten abhängig (nicht vom vorherigen Segment).
* Liegen die Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis — dann 0.
*/
export function bulgeThroughPoint(a: Vec2, through: Vec2, b: Vec2): number {
// Umkreismittelpunkt über die Schnittpunkt-Formel der Mittelsenkrechten.
const d = 2 * (a.x * (through.y - b.y) + through.x * (b.y - a.y) + b.x * (a.y - through.y));
if (Math.abs(d) < EPS) return 0;
const a2 = a.x * a.x + a.y * a.y;
const t2 = through.x * through.x + through.y * through.y;
const b2 = b.x * b.x + b.y * b.y;
const center = {
x: (a2 * (through.y - b.y) + t2 * (b.y - a.y) + b2 * (a.y - through.y)) / d,
y: (a2 * (b.x - through.x) + t2 * (a.x - b.x) + b2 * (through.x - a.x)) / d,
};
const r = Math.hypot(a.x - center.x, a.y - center.y);
if (r < EPS) return 0;
const ang = (p: Vec2) => Math.atan2(p.y - center.y, p.x - center.x);
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
// Schwenkrichtung ist die, bei der `through` unterwegs passiert wird.
const aFrom = ang(a);
const ccwToThrough = norm(ang(through) - aFrom);
const ccwToB = norm(ang(b) - aFrom);
const sweepSign: 1 | -1 = ccwToThrough <= ccwToB ? 1 : -1;
return bulgeBetweenAngles(center, r, aFrom, ang(b), sweepSign);
return core().bulge_through_point(a.x, a.y, through.x, through.y, b.x, b.y);
}
/** Punkt auf einem Kreis (center, r) beim Winkel `a` (Radiant). */
@@ -148,38 +103,27 @@ export function pointOnCircle(center: Vec2, r: number, a: number): Vec2 {
return { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) };
}
/**
* Kreisbogen-Parameter (Mittelpunkt/Radius/Start-/Endwinkel) durch drei Punkte
* `a`→`through`→`b` — der klassische Drei-Punkt-Bogen, hier direkt als
* `{center,r,a0,a1}` statt als `bulge` (für Werkzeuge, die einen eigenständigen
* `{shape:"arc"}` erzeugen, z. B. `commands/cmds/arc.ts`, statt ein
* Polylinien-Segment). `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von
* a0 nach a1 läuft (Konvention von `{shape:"arc"}`, s. dort) — anders als
* `bulgeThroughPoint`, dessen Vorzeichen die Sehnen-Richtung a→b behält.
* `null` bei (nahezu) kollinearen Punkten (kein Kreis).
*/
export function arcThroughPoints(
a: Vec2,
through: Vec2,
b: Vec2,
): { center: Vec2; r: number; a0: number; a1: number } | null {
const bulge = bulgeThroughPoint(a, through, b);
if (Math.abs(bulge) < EPS) return null;
const arc = bulgeArc(a, b, bulge);
if (!arc) return null;
return arc.sweep < 0
? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 }
: { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 };
type ArcParams = { center: Vec2; r: number; a0: number; a1: number };
function toArcParams(r: Float64Array): ArcParams | null {
if (r.length < 5) return null;
return { center: { x: r[0], y: r[1] }, r: r[2], a0: r[3], a1: r[4] };
}
/**
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom`
* zu `aTo`, in der durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW,
* −1 = CW — dieselbe Richtung wie der Eltern-Bogen, aus dem dieser Teilbogen
* stammt, z. B. beim Zuschneiden/Offsetten eines Bogen-Segments). Statt die
* Vorzeichen-Herleitung erneut zu machen (fehleranfällig), wird ein echter
* Punkt AUF dem Teilbogen (bei der Winkel-Mitte) konstruiert und darüber
* `bulgeFromSagittaPoint` (bereits getestet, s. `bulgeArc`) wiederverwendet.
* Kreisbogen-Parameter durch drei Punkte `a`→`through`→`b`, direkt als `{center,r,a0,a1}`
* für Werkzeuge, die einen eigenständigen `{shape:"arc"}` erzeugen (`commands/cmds/arc.ts`).
* `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von a0 nach a1 läuft. `null` bei
* (nahezu) kollinearen Punkten.
*/
export function arcThroughPoints(a: Vec2, through: Vec2, b: Vec2): ArcParams | null {
return toArcParams(core().arc_through_points(a.x, a.y, through.x, through.y, b.x, b.y));
}
/**
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` zu `aTo`, in der
* durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, −1 = CW), z. B. beim Zuschneiden/
* Offsetten eines Bogen-Segments.
*/
export function bulgeBetweenAngles(
center: Vec2,
@@ -188,94 +132,23 @@ export function bulgeBetweenAngles(
aTo: number,
sweepSign: 1 | -1,
): number {
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
const delta = sweepSign > 0 ? norm(aTo - aFrom) : -norm(aFrom - aTo);
const mid = aFrom + delta / 2;
const P = pointOnCircle(center, r, aFrom);
const Q = pointOnCircle(center, r, aTo);
const M = pointOnCircle(center, r, mid);
return bulgeFromSagittaPoint(P, Q, M);
return core().bulge_between_angles(center.x, center.y, r, aFrom, aTo, sweepSign);
}
/**
* Kreisbogen-Parameter durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius
* `r` — die zweite fehlende Bogen-Konstruktionsmethode aus der Recherche
* „Grösster Hebel" (`commands/cmds/arc.ts`, Methode „Start-Ende-Radius").
* `near` (typischerweise der Cursor) entscheidet, auf welche Seite der Sehne
* sich der Bogen wölbt — analog zu einem gezogenen Bulge-Griff. Liefert
* immer den KLEINEREN der beiden möglichen Bögen (Sehnenwinkel ≤ 180°): der
* Radius allein legt zwei Kreise fest (Zentrum auf einer der beiden Seiten
* der Sehne), aber erst zusammen mit „welcher Bogen dieses Kreises" ergäbe
* sich sonst eine dritte, unnötige Mehrdeutigkeit — der kleinere Bogen ist
* die für eine Zieh-Geste erwartbare, stetige Wahl (grosser Radius ⇒ flacher
* Bogen, kleiner Radius (nahe der halben Sehnenlänge) ⇒ Halbkreis).
* `null`, wenn `r` kleiner als die halbe Sehnenlänge ist (kein Kreis möglich)
* oder die Sehne entartet (a≈b).
* Kreisbogen durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius `r` (Methode „Start-Ende-
* Radius"). `near` (typischerweise der Cursor) wählt die Seite der Sehne; es entsteht immer der
* KLEINERE der beiden möglichen Bögen (Sehnenwinkel ≤ 180°). `null`, wenn `r` kleiner als die
* halbe Sehnenlänge ist oder die Sehne entartet.
*/
export function arcFromStartEndRadius(
a: Vec2,
b: Vec2,
r: number,
near: Vec2,
): { center: Vec2; r: number; a0: number; a1: number } | null {
const dx = b.x - a.x, dy = b.y - a.y;
const chord = Math.hypot(dx, dy);
if (chord < EPS) return null;
const h = chord / 2;
if (r < h - EPS) return null;
const rr = Math.max(r, h);
const s = rr - Math.sqrt(Math.max(0, rr * rr - h * h)); // Sagitta des kleineren Bogens
const ux = dx / chord, uy = dy / chord;
const nx = -uy, ny = ux; // Links-Normale von a→b, wie `bulgeArc`
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
const sideSign = (near.x - mx) * nx + (near.y - my) * ny >= 0 ? 1 : -1;
const bulge = (sideSign * s) / h;
const arc = bulgeArc(a, b, bulge);
if (!arc) return null;
return arc.sweep < 0
? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 }
: { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 };
export function arcFromStartEndRadius(a: Vec2, b: Vec2, r: number, near: Vec2): ArcParams | null {
return toArcParams(core().arc_from_start_end_radius(a.x, a.y, b.x, b.y, r, near.x, near.y));
}
/**
* Kreisbogen-Parameter durch zwei Endpunkte `a`→`b`, tangential zu einer bei
* `a` vorgegebenen Richtung (`dir`, ein Punkt AUF dem Tangentenstrahl, nicht
* zwingend auf dem Bogen selbst) — dritte fehlende Bogen-Konstruktions-
* methode. Der Kreismittelpunkt steht per Definition senkrecht zur Tangente
* bei `a` UND auf der Mittelsenkrechten von a-b — beide Geraden geschnitten
* (`lineIntersect`) ergeben ihn eindeutig, ohne Fallunterscheidung. Die
* Schwenkrichtung (CCW/CW von a0 nach a1) wird so gewählt, dass die
* Bogen-Tangente bei a tatsächlich in Richtung `dir` zeigt (nicht rückwärts).
* `null` bei entarteter Tangente (`dir`≈`a`) oder wenn die Tangente exakt
* entlang der Sehne a-b zeigt (Mittelsenkrechte und Tangenten-Normale
* parallel — kein eindeutiger Kreis, Grenzfall „Gerade").
* Kreisbogen durch `a`→`b`, bei `a` tangential zur Richtung `dir` (ein Punkt AUF dem
* Tangentenstrahl). `null` bei entarteter Tangente oder wenn sie entlang der Sehne a-b zeigt.
*/
export function arcFromStartEndDirection(
a: Vec2,
b: Vec2,
dir: Vec2,
): { center: Vec2; r: number; a0: number; a1: number } | null {
const tx = dir.x - a.x, ty = dir.y - a.y;
const tLen = Math.hypot(tx, ty);
if (tLen < EPS) return null;
const ux = tx / tLen, uy = ty / tLen;
const tangentNormal = { x: -uy, y: ux }; // senkrecht zur Tangente bei a
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
const chordNormal = { x: -(b.y - a.y), y: b.x - a.x }; // senkrecht zur Sehne a-b
const center = lineIntersect(a, tangentNormal, mid, chordNormal);
if (!center) return null;
const r = Math.hypot(a.x - center.x, a.y - center.y);
if (r < EPS) return null;
const a0raw = Math.atan2(a.y - center.y, a.x - center.x);
const a1raw = Math.atan2(b.y - center.y, b.x - center.x);
// CCW-Tangentenrichtung bei a0raw ist die Ableitung von (cos,sin) nach
// wachsendem Winkel: (−sin,cos). Zeigt sie NICHT in Richtung (ux,uy), muss
// der Bogen stattdessen CW laufen (a0/a1 vertauscht, wie `arcThroughPoints`
// bei negativem `sweep`).
const tangentCCW = { x: -Math.sin(a0raw), y: Math.cos(a0raw) };
const matchesCCW = tangentCCW.x * ux + tangentCCW.y * uy >= 0;
return matchesCCW
? { center, r, a0: a0raw, a1: a1raw }
: { center, r, a0: a1raw, a1: a0raw };
export function arcFromStartEndDirection(a: Vec2, b: Vec2, dir: Vec2): ArcParams | null {
return toArcParams(core().arc_from_start_end_direction(a.x, a.y, b.x, b.y, dir.x, dir.y));
}
+80
View File
@@ -0,0 +1,80 @@
/**
* `geometry/stair.ts` — Fassade über den Rust-Kern: Form-Prüfungen für gerade/L/Wendel,
* Referenz, Schnitt, Rahmen und Unsinn-Eingaben (Rust-Tests decken die Mathematik je Fall ab).
*/
import { describe, it, expect } from "vitest";
import { defaultStepCount, stairBBox, stairCut, stairGeometry, stairOutline } from "./stair";
import type { Stair } from "../model/types";
const base: Stair = {
id: "s", type: "stair", floorId: "eg", categoryCode: "40", shape: "straight",
start: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, runLength: 3, width: 1.2, stepCount: 16,
};
describe("stairGeometry", () => {
it("gerade: 16 Tritte, Setzstufe, Lauflinie, Pfeil nach oben", () => {
const g = stairGeometry(base, 2.8);
expect(g.treads).toHaveLength(16);
expect(g.riserHeight).toBeCloseTo(0.175, 12);
expect(g.landing).toBeNull();
expect(g.treads[15].topRise).toBeCloseTo(2.8, 12);
expect(g.arrow.head[1]).toEqual(g.runLine[1]);
expect(stairGeometry({ ...base, up: false }, 2.8).arrow.head[1]).toEqual(g.runLine[0]);
});
it("L: Podest + zweiter Lauf, turn dreht die Richtung", () => {
const l: Stair = { ...base, shape: "L", run2Length: 2 };
const g = stairGeometry(l, 2.8);
expect(g.treads).toHaveLength(15);
expect(g.landing).toHaveLength(4);
expect(g.runLine[2].y).toBeGreaterThan(1);
expect(stairGeometry({ ...l, turn: -1 }, 2.8).runLine[2].y).toBeLessThan(-1);
});
it("Wendel: Keile, Auge mit 12 Punkten, Lauflinie als Bogen", () => {
const sp: Stair = { ...base, shape: "spiral", center: { x: 0, y: 0 }, start: { x: 1, y: 0 }, radius: 1, stepCount: 12 };
const g = stairGeometry(sp, 2.4);
expect(g.treads).toHaveLength(12);
expect(g.landing).toHaveLength(12);
expect(g.runLine).toHaveLength(13);
});
it("Referenz links versetzt die Achse eine halbe Breite auf die Mitte", () => {
const g = stairGeometry({ ...base, referenz: "links" }, 2.8);
expect(g.treads[0].pts[0].y).toBeCloseTo(0, 12);
expect(g.treads[0].pts[3].y).toBeCloseTo(-1.2, 12);
expect(stairOutline({ ...base, referenz: "rechts" }, 0).polygon![0].y).toBeCloseTo(1.2, 12);
});
it("Unsinn (NaN, 0 Stufen) liefert leere bzw. Mindest-Geometrie ohne Fehler", () => {
expect(stairGeometry({ ...base, width: NaN }, 2.8).treads).toEqual([]);
expect(stairGeometry(base, NaN).treads).toEqual([]);
expect(stairGeometry({ ...base, stepCount: 0 }, 2.8).treads).toHaveLength(2);
expect(stairOutline({ ...base, runLength: NaN }, 0)).toEqual({ polygon: null, spiral: null });
expect(stairBBox(stairGeometry(base, NaN))).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 });
});
});
describe("stairCut / stairBBox / defaultStepCount", () => {
it("Schnitt teilt die Tritte und legt eine Doppel-Bruchlinie", () => {
const g = stairGeometry(base, 2.8);
const c = stairCut(g, 1.0);
expect(c.belowIndices).toEqual([0, 1, 2, 3, 4]);
expect(c.aboveIndices).toHaveLength(11);
expect(c.breakLine).toHaveLength(2);
expect(stairCut(g, 99).breakLine).toBeNull();
expect(stairCut(stairGeometry(base, NaN), 1)).toEqual({ belowIndices: [], aboveIndices: [], breakLine: null });
});
it("BBox über Tritte", () => {
const b = stairBBox(stairGeometry(base, 2.8));
expect(b.maxX).toBeCloseTo(3, 12);
expect(b.minY).toBeCloseTo(-0.6, 12);
});
it("Vorgabe-Stufenzahl: Steighöhe 0.17, gedeckelt durch die Lauflänge, mind. 2", () => {
expect(defaultStepCount(2.8, 10)).toBe(16);
expect(defaultStepCount(2.8, 3)).toBe(13);
expect(defaultStepCount(0.1, 0)).toBe(2);
});
});
+126 -461
View File
@@ -1,57 +1,23 @@
// Geometrie-Helfer für Treppen (Stairs) — reine Funktionen über `Vec2`, kein
// externer Kernel. Aus einer `Stair` (gerade/L/Wendel) werden abgeleitet:
// Geometrie-Helfer für Treppen (Stairs) — Fassade über den Rust-Kern
// (`src-tauri/kernel2d/src/lib.rs`: `stair_geometry`, `stair_outline`, `stair_cut`, `stair_bbox`;
// Bindungen `src-tauri/core/src/web/stair.rs`, Kodierung `src-tauri/core/src/stair.rs`).
// Aus einer `Stair` (gerade/L/Wendel) werden abgeleitet:
// • die Tritt-Rechtecke im Grundriss (jeweils mit ihrer Z-Höhe der Setzstufe),
// • das Zwischenpodest-Polygon (L / Wendel-Auge),
// • die Lauflinie (Polyline) + der Auf-/Abpfeil,
// • die Schnittposition (welche Tritte unter/über der Grundriss-Schnitthöhe
// liegen → im Plan durchgezogen vs. gestrichelt) samt SIA-Bruchlinie.
// liegen → im Plan durchgezogen vs. gestrichelt) samt SIA-Bruchlinie,
// • die Plan-Aussenlinie (`stairOutline`).
//
// Die 3D-Darstellung baut aus denselben Tritt-Rechtecken + Setzstufen-Höhen die
// Stufenboxen (siehe Viewport3D). So bleiben Plan und 3D konsistent aus EINER
// Quelle abgeleitet.
// Stufenboxen (siehe `plan/toWalls3d/stairs.ts`). So bleiben Plan und 3D konsistent
// aus EINER Quelle abgeleitet. Referenz (links/mitte/rechts): die gespeicherte Achse wird im
// Kern auf die visuelle Treppen-MITTE versetzt, Lauflinie samt Pfeil liegen stets auf der Mitte.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
// Bezeichner englisch, Kommentare deutsch.
import type { Stair, Vec2 } from "../model/types";
const DEG = Math.PI / 180;
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
const add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });
const scale = (a: Vec2, s: number): Vec2 => ({ x: a.x * s, y: a.y * s });
const lenOf = (a: Vec2): number => Math.hypot(a.x, a.y);
const norm = (a: Vec2): Vec2 => {
const l = lenOf(a) || 1e-9;
return { x: a.x / l, y: a.y / l };
};
/** Linke Normale (n = (−u.y, u.x)) — quer zur Laufrichtung. */
const leftN = (u: Vec2): Vec2 => ({ x: -u.y, y: u.x });
/**
* Perp-Versatz von der Referenzkante zur visuellen Treppen-MITTE, entlang der
* linken Normale `n = leftN(u)`. Entspricht `mid_off` aus `_treppe_2d_side_offsets`
* im Rhino-Plugin (Konvention: `perp` = CCW-Normale = linke Normale):
* • referenz "links" → Achse ist die LINKE Kante; die Mitte liegt eine
* halbe Breite in −n-Richtung (rechts) → mid_off = −width/2.
* • referenz "rechts" → Achse ist die RECHTE Kante; die Mitte liegt eine
* halbe Breite in +n-Richtung (links) → mid_off = +width/2.
* • referenz "mitte"/undefined → Achse ist bereits die Mitte → 0.
*
* ANNAHME (selbstkritisch): „links" heisst „linke Kante in Laufrichtung", und die
* linke Kante liegt in +n (n = leftN(u), 90° links der Laufrichtung). Von der
* linken Kante zur Mitte geht es also nach −n, daher mid_off = −width/2. Das
* deckt sich mit `_treppe_2d_side_offsets` (referenz="links" → off_a=0, off_b=−b,
* Mitte = −b/2·perp). Wird die Richtung im UI als seitenverkehrt empfunden, ist
* hier das Vorzeichen zu drehen — die Geometrie bleibt in sich konsistent.
*/
function referenzMidShift(stair: Stair, u: Vec2): Vec2 {
const ref = stair.referenz ?? "mitte";
if (ref === "mitte") return { x: 0, y: 0 };
const n = leftN(u);
const halfW = Math.max(0.05, stair.width / 2);
const midOff = ref === "links" ? -halfW : halfW;
return scale(n, midOff);
}
import { core } from "../engine/coreWasm";
/** SIA-nahe Schrittregel: gute Steigungshöhe ≈ 0.17 m, Auftritt ≈ 0.29 m. */
export const IDEAL_RISER = 0.17;
@@ -64,10 +30,7 @@ export const MIN_STEPS = 2;
* Auftritt ~0.24 m). Immer ≥ MIN_STEPS.
*/
export function defaultStepCount(totalRise: number, runLength: number): number {
const byRise = Math.max(MIN_STEPS, Math.round(totalRise / IDEAL_RISER));
// Auftrittstiefe = runLength / (steps − 1); mind. 0.24 m halten.
const maxByRun = runLength > 0 ? Math.max(MIN_STEPS, Math.floor(runLength / 0.24) + 1) : byRise;
return Math.max(MIN_STEPS, Math.min(byRise, maxByRun));
return core().stair_default_step_count(totalRise, runLength);
}
/** Ein Tritt im Grundriss (Rechteck-Polygon) samt Setzstufen-Z (Oberkante). */
@@ -100,252 +63,100 @@ export interface StairGeometry {
totalRise: number;
}
/** Rechteck-Tritt zwischen Achsparametern a0..a1 entlang `dir`, Breite `width`. */
function treadRect(
origin: Vec2,
dir: Vec2,
n: Vec2,
a0: number,
a1: number,
halfW: number,
): Vec2[] {
const p0 = add(origin, scale(dir, a0));
const p1 = add(origin, scale(dir, a1));
return [
add(p0, scale(n, halfW)),
add(p1, scale(n, halfW)),
add(p1, scale(n, -halfW)),
add(p0, scale(n, -halfW)),
];
const FORM = { straight: 0, L: 1, spiral: 2 } as const;
const REFERENZ = { mitte: 0, links: 1, rechts: 2 } as const;
/** Treppen-Parameter als 16 Zahlen (Aufbau: `src-tauri/core/src/stair.rs`); fehlend = NaN. */
function encodeStair(s: Stair): Float64Array {
const n = (v: number | undefined) => (v === undefined ? Number.NaN : v);
return Float64Array.of(
FORM[s.shape] ?? 0,
s.start.x, s.start.y,
s.dir.x, s.dir.y,
s.runLength,
n(s.run2Length),
n(s.turn),
n(s.center?.x), n(s.center?.y),
n(s.radius),
n(s.sweep),
s.width,
s.stepCount,
s.up === undefined ? Number.NaN : s.up ? 1 : 0,
REFERENZ[s.referenz ?? "mitte"] ?? 0,
);
}
const pt = (f: Float64Array, i: number): Vec2 => ({ x: f[i], y: f[i + 1] });
function ptsAt(f: Float64Array, i: number, n: number): Vec2[] {
const out: Vec2[] = new Array(n);
for (let k = 0; k < n; k++) out[k] = pt(f, i + 2 * k);
return out;
}
/** Flache Treppengeometrie (Aufbau: `stair.rs`) → Objekt; leer (Unsinn-Eingabe) → leere Geometrie. */
function decodeGeometry(f: Float64Array): StairGeometry {
if (f.length < 4) {
const z = { x: 0, y: 0 };
return {
treads: [], landing: null, riserHeight: 0, treadDepth: 0, runLine: [],
arrow: { shaft: [z, z], head: [z, z, z] }, totalRise: 0,
};
}
const nTreads = f[3];
let i = 4;
const treads: TreadRect[] = [];
for (let t = 0; t < nTreads; t++, i += 11) {
treads.push({ index: f[i], topRise: f[i + 1], baseRise: f[i + 2], pts: ptsAt(f, i + 3, 4) });
}
const nl = f[i++];
let landing: Vec2[] | null = null;
if (nl >= 0) {
landing = ptsAt(f, i, nl);
i += 2 * nl;
}
const nRun = f[i++];
const runLine = ptsAt(f, i, nRun);
i += 2 * nRun;
const a = ptsAt(f, i, 5);
return {
treads,
landing,
riserHeight: f[0],
treadDepth: f[1],
runLine,
arrow: { shaft: [a[0], a[1]], head: [a[2], a[3], a[4]] },
totalRise: f[2],
};
}
/** Geometrie → flacher Puffer (gleicher Aufbau wie die Ausgabe von `stair_geometry_flat`). */
function encodeGeometry(g: StairGeometry): Float64Array {
const out: number[] = [g.riserHeight, g.treadDepth, g.totalRise, g.treads.length];
const push = (p: Vec2) => out.push(p.x, p.y);
for (const t of g.treads) {
out.push(t.index, t.topRise, t.baseRise);
t.pts.forEach(push);
}
if (g.landing) {
out.push(g.landing.length);
g.landing.forEach(push);
} else out.push(-1);
out.push(g.runLine.length);
g.runLine.forEach(push);
push(g.arrow.shaft[0]);
push(g.arrow.shaft[1]);
g.arrow.head.forEach(push);
return Float64Array.from(out);
}
/**
* Leitet die vollständige Geometrie einer Treppe ab. `totalRise` MUSS vom
* Aufrufer aufgelöst übergeben werden (Geschosshöhe-Default liegt in
* `stairVerticalExtent`), damit dieses Modul three-/projektfrei bleibt.
* `stairVerticalExtent`), damit dieses Modul modellfrei bleibt.
*/
export function stairGeometry(stair: Stair, totalRise: number): StairGeometry {
const steps = Math.max(MIN_STEPS, Math.round(stair.stepCount));
const riserHeight = totalRise / steps;
const halfW = Math.max(0.05, stair.width / 2);
const u = norm(stair.dir);
const n = leftN(u);
// Referenz (links/mitte/rechts): die gespeicherte Achse wird auf die visuelle
// Treppen-MITTE versetzt, danach greift die bestehende, um die Achse zentrierte
// Tritt-/Lauflinien-Logik unverändert. So bleibt die Lauflinie samt Pfeil stets
// auf der Mitte (nicht auf der Referenzkante). "mitte"/undefined ⇒ Nullversatz.
const c = referenzMidShift(stair, u);
const s = stair.referenz && stair.referenz !== "mitte"
? { ...stair, start: add(stair.start, c), center: stair.center ? add(stair.center, c) : stair.center }
: stair;
if (s.shape === "spiral") {
return spiralGeometry(s, totalRise, steps, riserHeight, halfW);
}
if (s.shape === "L") {
return lGeometry(s, totalRise, steps, riserHeight, halfW, u, n);
}
return straightGeometry(s, totalRise, steps, riserHeight, halfW, u, n);
}
/** Gerade Treppe: gleich breite Tritte über die Lauflänge. */
function straightGeometry(
stair: Stair,
totalRise: number,
steps: number,
riserHeight: number,
halfW: number,
u: Vec2,
n: Vec2,
): StairGeometry {
const runLength = Math.max(0.1, stair.runLength);
const treadDepth = runLength / steps;
const treads: TreadRect[] = [];
for (let i = 0; i < steps; i++) {
treads.push({
pts: treadRect(stair.start, u, n, i * treadDepth, (i + 1) * treadDepth, halfW),
index: i,
baseRise: i * riserHeight,
topRise: (i + 1) * riserHeight,
});
}
const runLine: Vec2[] = [
add(stair.start, scale(u, treadDepth * 0.5)),
add(stair.start, scale(u, runLength - treadDepth * 0.15)),
];
return {
treads,
landing: null,
riserHeight,
treadDepth,
runLine,
arrow: arrowFor(runLine, stair.up !== false),
totalRise,
};
}
/** L-Treppe: zwei Läufe + quadratisches Zwischenpodest an der Ecke. */
function lGeometry(
stair: Stair,
totalRise: number,
steps: number,
riserHeight: number,
halfW: number,
u: Vec2,
n: Vec2,
): StairGeometry {
const run1 = Math.max(0.1, stair.runLength);
const run2 = Math.max(0.1, stair.run2Length ?? stair.runLength);
const turn = stair.turn ?? 1;
// Podest quadratisch (Kantenlänge = Laufbreite) am Ende des ersten Laufs.
const podest = 2 * halfW;
// Stufen auf beide Läufe verteilen (grob proportional zur Lauflänge), ein Tritt
// fällt aufs Podest.
const bodySteps = steps - 1; // ein Tritt = Podest
const s1 = Math.max(1, Math.round((bodySteps * run1) / (run1 + run2)));
const s2 = Math.max(1, bodySteps - s1);
const td1 = run1 / s1;
const td2 = run2 / s2;
const treads: TreadRect[] = [];
let rise = 0;
for (let i = 0; i < s1; i++) {
treads.push({
pts: treadRect(stair.start, u, n, i * td1, (i + 1) * td1, halfW),
index: i,
baseRise: rise,
topRise: rise + riserHeight,
});
rise += riserHeight;
}
// Zweiter Lauf beginnt am Ende des Podests. Richtung um 90° gedreht (turn).
const cornerCenter = add(stair.start, scale(u, run1 + halfW));
const u2: Vec2 = turn > 0 ? n : scale(n, -1); // links/rechts abbiegen
const n2 = leftN(u2);
// Podest-Tritt (quadratisch um cornerCenter, an u/u2 ausgerichtet).
const landing: Vec2[] = [
add(add(cornerCenter, scale(u, -halfW)), scale(n, halfW)),
add(add(cornerCenter, scale(u, halfW)), scale(n, halfW)),
add(add(cornerCenter, scale(u, halfW)), scale(n, -halfW)),
add(add(cornerCenter, scale(u, -halfW)), scale(n, -halfW)),
];
const podestTopRise = rise + riserHeight;
rise += riserHeight;
// Startpunkt des zweiten Laufs: Podest-Kante in Richtung u2.
const run2Start = add(cornerCenter, scale(u2, halfW));
for (let i = 0; i < s2; i++) {
treads.push({
pts: treadRect(run2Start, u2, n2, i * td2, (i + 1) * td2, halfW),
index: s1 + 1 + i,
baseRise: rise,
topRise: rise + riserHeight,
});
rise += riserHeight;
}
void podest;
void podestTopRise;
const runLine: Vec2[] = [
add(stair.start, scale(u, td1 * 0.5)),
cornerCenter,
add(run2Start, scale(u2, run2 - td2 * 0.15)),
];
return {
treads,
landing,
riserHeight,
treadDepth: td1,
runLine,
arrow: arrowFor(runLine, stair.up !== false),
totalRise,
};
}
/** Wendeltreppe: keilförmige Tritte um ein Zentrum (vereinfachtes Modell). */
function spiralGeometry(
stair: Stair,
totalRise: number,
steps: number,
riserHeight: number,
halfW: number,
): StairGeometry {
const center = stair.center ?? stair.start;
const radius = Math.max(halfW + 0.1, stair.radius ?? stair.width);
const sweep = (stair.sweep ?? 270) * DEG;
// Startwinkel aus start→center (Lauflinie beginnt am Startpunkt).
const startVec = sub(stair.start, center);
const a0 = Math.atan2(startVec.y, startVec.x);
const dA = sweep / steps;
const rIn = Math.max(0.02, radius - halfW);
const rOut = radius + halfW;
const treads: TreadRect[] = [];
for (let i = 0; i < steps; i++) {
const t0 = a0 + i * dA;
const t1 = a0 + (i + 1) * dA;
// Keil-Viereck: innen(t0) → außen(t0) → außen(t1) → innen(t1).
const pts: Vec2[] = [
{ x: center.x + rIn * Math.cos(t0), y: center.y + rIn * Math.sin(t0) },
{ x: center.x + rOut * Math.cos(t0), y: center.y + rOut * Math.sin(t0) },
{ x: center.x + rOut * Math.cos(t1), y: center.y + rOut * Math.sin(t1) },
{ x: center.x + rIn * Math.cos(t1), y: center.y + rIn * Math.sin(t1) },
];
treads.push({
pts,
index: i,
baseRise: i * riserHeight,
topRise: (i + 1) * riserHeight,
});
}
// Lauflinie = Bogen auf Radius `radius` (mittlere Lauflinie).
const runLine: Vec2[] = [];
const N = Math.max(2, steps);
for (let i = 0; i <= N; i++) {
const tt = a0 + (sweep * i) / N;
runLine.push({ x: center.x + radius * Math.cos(tt), y: center.y + radius * Math.sin(tt) });
}
return {
treads,
// Wendel-Auge (Innenkreis) als „Podest"-Polygon.
landing: eyePolygon(center, rIn),
riserHeight,
treadDepth: (2 * Math.PI * radius * (sweep / (2 * Math.PI))) / steps,
runLine,
arrow: arrowFor(runLine, stair.up !== false),
totalRise,
};
}
/** Achteck-Approximation des Wendel-Auges (Innenkreis). */
function eyePolygon(center: Vec2, r: number): Vec2[] {
const pts: Vec2[] = [];
for (let i = 0; i < 12; i++) {
const t = (i / 12) * Math.PI * 2;
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
}
return pts;
}
/**
* Auf-/Abpfeil aus der Lauflinie: Schaft = erstes→letztes Segment, Spitze am
* oberen (bzw. bei `up=false` am unteren) Ende. `up` kehrt die Richtung um.
*/
function arrowFor(
runLine: Vec2[],
up: boolean,
): { shaft: [Vec2, Vec2]; head: [Vec2, Vec2, Vec2] } {
const a = runLine[0];
const b = runLine[runLine.length - 1];
const tip = up ? b : a;
const from = up ? runLine[runLine.length - 2] : runLine[1];
const dir = norm(sub(tip, from));
const n = leftN(dir);
const s = 0.22; // Flügellänge (Meter)
const back = add(tip, scale(dir, -s));
const w1 = add(back, scale(n, s * 0.55));
const w2 = add(back, scale(n, -s * 0.55));
return { shaft: [a, b], head: [w1, tip, w2] };
return decodeGeometry(core().stair_geometry_flat(encodeStair(stair), totalRise));
}
/**
@@ -370,34 +181,22 @@ export interface StairCut {
* legt dort die Bruchlinie quer über den Lauf.
*/
export function stairCut(geo: StairGeometry, cutRise: number): StairCut {
const below: number[] = [];
const above: number[] = [];
let breakIdx = -1;
for (const tr of geo.treads) {
if (tr.topRise <= cutRise + 1e-6) {
below.push(tr.index);
} else {
if (breakIdx < 0) breakIdx = tr.index;
above.push(tr.index);
}
}
const f = core().stair_cut_flat(encodeGeometry(geo), cutRise);
if (f.length < 3) return { belowIndices: [], aboveIndices: [], breakLine: null };
let i = 0;
const nBelow = f[i++];
const belowIndices = Array.from(f.subarray(i, i + nBelow));
i += nBelow;
const nAbove = f[i++];
const aboveIndices = Array.from(f.subarray(i, i + nAbove));
i += nAbove;
const nBreak = f[i++];
let breakLine: [Vec2, Vec2][] | null = null;
if (breakIdx >= 0) {
const tr = geo.treads.find((t) => t.index === breakIdx);
if (tr) {
// Diagonale Bruchlinie über den Tritt: von einer Ecke zur gegenüberliegenden,
// als Doppelstrich (leicht versetzt) — SIA-Treppen-Schnittsymbol.
const [c0, c1, c2, c3] = tr.pts;
const mid01 = scale(add(c0, c1), 0.5);
const mid23 = scale(add(c2, c3), 0.5);
const off = scale(norm(sub(c1, c0)), 0.06);
breakLine = [
[add(mid01, off), add(mid23, off)],
[sub(mid01, off), sub(mid23, off)],
];
}
if (nBreak > 0) {
breakLine = [];
for (let k = 0; k < nBreak; k++, i += 4) breakLine.push([pt(f, i), pt(f, i + 2)]);
}
return { belowIndices: below, aboveIndices: above, breakLine };
return { belowIndices, aboveIndices, breakLine };
}
/** Achsparallele Bounding-Box aller Tritte (+ Podest) einer Treppengeometrie. */
@@ -407,113 +206,13 @@ export function stairBBox(geo: StairGeometry): {
maxX: number;
maxY: number;
} {
let minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
const acc = (p: Vec2) => {
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
};
for (const tr of geo.treads) for (const p of tr.pts) acc(p);
if (geo.landing) for (const p of geo.landing) acc(p);
if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
return { minX, minY, maxX, maxY };
}
/** Punkt-in-Polygon (Ray-Casting) — für die Body-Auswahl im Grundriss/3D. */
export function pointInPolygon(p: Vec2, poly: Vec2[]): boolean {
let inside = false;
const nn = poly.length;
for (let i = 0, j = nn - 1; i < nn; j = i++) {
const a = poly[i];
const b = poly[j];
const intersect =
a.y > p.y !== b.y > p.y &&
p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x;
if (intersect) inside = !inside;
}
return inside;
}
/** Ob ein Modellpunkt IRGENDEINEN Tritt (oder das Podest) einer Treppe trifft. */
export function pointHitsStair(p: Vec2, geo: StairGeometry): boolean {
for (const tr of geo.treads) if (pointInPolygon(p, tr.pts)) return true;
if (geo.landing && pointInPolygon(p, geo.landing)) return true;
return false;
}
// ── Treppen-Aussenlinie (Plan-Outline) ───────────────────────────────────────
/**
* Schliessendes Umriss-Polygon einer geraden Treppe im Grundriss (4 Ecken CCW).
* Entspricht `_aussen_gerade` im Rhino-Plugin (Rechteck über Laufbreite + Lauflänge).
* Liefert null bei entarteter Geometrie.
*/
function straightOutlinePoints(stair: Stair, halfW: number): Vec2[] | null {
const u = norm({ x: stair.dir.x, y: stair.dir.y });
const n = leftN(u);
const L = Math.max(1e-4, stair.runLength);
const s = stair.start;
// Vier Ecken: Start-links → Start-rechts → End-rechts → End-links (CCW).
return [
add(s, scale(n, halfW)),
add(s, scale(n, -halfW)),
add(add(s, scale(u, L)), scale(n, -halfW)),
add(add(s, scale(u, L)), scale(n, halfW)),
];
}
/**
* 2D-Linien-Schnittpunkt. Liefert null bei Parallelität (det < ε).
* Entspricht `_line_intersect_xy` im Rhino-Plugin.
*/
function lineIntersect2d(p1: Vec2, d1: Vec2, p2: Vec2, d2: Vec2): Vec2 | null {
const det = d1.x * (-d2.y) - d1.y * (-d2.x);
if (Math.abs(det) < 1e-9) return null;
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const t = (dx * (-d2.y) - dy * (-d2.x)) / det;
return { x: p1.x + d1.x * t, y: p1.y + d1.y * t };
}
/**
* Umriss-Polygon einer L-Treppe im Grundriss. Entspricht `_aussen_l_polygon`
* im Rhino-Plugin: Linien-Schnittpunkte liefern die Ecken des L-Polygons.
* Liefert null bei entarteter Geometrie.
*/
function lOutlinePoints(stair: Stair, halfW: number): Vec2[] | null {
const u1 = norm(stair.dir);
const n1 = leftN(u1);
const L1 = Math.max(1e-4, stair.runLength);
const turn = stair.turn ?? 1;
const u2: Vec2 = turn > 0 ? n1 : scale(n1, -1);
const n2 = leftN(u2);
const L2 = Math.max(1e-4, stair.run2Length ?? stair.runLength);
// Podest-Zentrum am Ende des ersten Laufs (Mitte = halfW hinter dem Lauf-Ende).
const corner = add(stair.start, scale(u1, L1 + halfW));
const run2Start = add(corner, scale(u2, halfW));
// Lauf-1-Anfang je Seite
const p0l = add(stair.start, scale(n1, halfW));
const p0r = add(stair.start, scale(n1, -halfW));
// Lauf-2-Ende je Seite
const endRun2 = add(run2Start, scale(u2, L2));
const p3l = add(endRun2, scale(n2, halfW));
const p3r = add(endRun2, scale(n2, -halfW));
// Innere Eck-Punkte: Schnittpunkt der parallelen Seitenlinien je Seite.
const cornerL = lineIntersect2d(p0l, u1, p3l, scale(u2, -1)) ?? add(corner, scale(n1, halfW));
const cornerR = lineIntersect2d(p0r, u1, p3r, scale(u2, -1)) ?? add(corner, scale(n1, -halfW));
// CCW-Polygon: p0l → p0r → cornerR → p3r → p3l → cornerL
return [p0l, p0r, cornerR, p3r, p3l, cornerL];
const f = core().stair_bbox_flat(encodeGeometry(geo));
if (f.length < 4) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
return { minX: f[0], minY: f[1], maxX: f[2], maxY: f[3] };
}
/**
* Spiral-Outline: Innenbogen + Aussenbogen + zwei radiale Schliesslinien.
* Entspricht `_aussen_wendel` im Rhino-Plugin (immer vollständig, ohne Cut).
* Die Bögen werden als Kreisbogen-Parameter geliefert (cx/cy/r/a0/a1), die
* radialen Schliesslinien als Segment-Paare.
*/
@@ -524,60 +223,26 @@ export interface SpiralOutlineSegments {
arcs: { cx: number; cy: number; r: number; a0: number; a1: number }[];
}
function spiralOutline(stair: Stair, halfW: number): SpiralOutlineSegments | null {
const center = stair.center ?? stair.start;
const radius = Math.max(halfW + 0.1, stair.radius ?? stair.width);
const sweep = (stair.sweep ?? 270) * (Math.PI / 180);
const startVec = sub(stair.start, center);
const a0 = Math.atan2(startVec.y, startVec.x);
const a1 = a0 + sweep;
const rIn = Math.max(0.02, radius - halfW);
const rOut = radius + halfW;
const ptAt = (r: number, a: number): Vec2 => ({
x: center.x + r * Math.cos(a),
y: center.y + r * Math.sin(a),
});
return {
lines: [
[ptAt(rIn, a0), ptAt(rOut, a0)],
[ptAt(rIn, a1), ptAt(rOut, a1)],
],
arcs: [
{ cx: center.x, cy: center.y, r: rIn, a0, a1 },
{ cx: center.x, cy: center.y, r: rOut, a0, a1 },
],
};
}
/**
* Aussenlinie einer Treppe im Grundriss je nach Form:
* • gerade → geschlossenes Rechteck als Polygon-Punkte.
* • L → L-Polygon via Linien-Schnittpunkten.
* • Wendel → `SpiralOutlineSegments` (Bögen + radiale Linien).
*
* Genau einer von `polygon` / `spiral` ist nicht null.
* Genau einer von `polygon` / `spiral` ist nicht null (bei Unsinn-Eingabe beide null).
*/
export function stairOutline(
stair: Stair,
totalRise: number,
): { polygon: Vec2[] | null; spiral: SpiralOutlineSegments | null } {
void totalRise; // Signatur-Konsistenz mit stairGeometry; derzeit ungenutzt
const halfW = Math.max(0.05, stair.width / 2);
// Referenz (links/mitte/rechts): die gespeicherte Achse zuerst auf die
// visuelle Treppen-Mitte versetzen, danach die um die Mitte zentrierte
// Aussenlinien-Logik unverändert anwenden (identisch zu `stairGeometry`).
const u = norm(stair.dir);
const c = referenzMidShift(stair, u);
const s = stair.referenz && stair.referenz !== "mitte"
? { ...stair, start: add(stair.start, c), center: stair.center ? add(stair.center, c) : stair.center }
: stair;
if (s.shape === "spiral") {
return { polygon: null, spiral: spiralOutline(s, halfW) };
}
if (s.shape === "L") {
return { polygon: lOutlinePoints(s, halfW), spiral: null };
}
return { polygon: straightOutlinePoints(s, halfW), spiral: null };
const f = core().stair_outline_flat(encodeStair(stair));
if (f.length === 0) return { polygon: null, spiral: null };
if (f[0] === 0) return { polygon: ptsAt(f, 2, f[1]), spiral: null };
const l = ptsAt(f, 1, 4);
const arcs = [0, 1].map((k) => {
const j = 9 + 5 * k;
return { cx: f[j], cy: f[j + 1], r: f[j + 2], a0: f[j + 3], a1: f[j + 4] };
});
return { polygon: null, spiral: { lines: [[l[0], l[1]], [l[2], l[3]]], arcs } };
}