[K4] Zeichenbefehle im Kern: Elemente, Vorschauen, Gruppen-Zuordnung

Alle Erzeuge-Befehle bauen ihre Elemente im Kern: cmd_create.rs (Wand, Decke,
Raum, Treppe, Öffnung, Dach, Stütze, Extrusion), cmd_draw.rs (2D-Formen,
Texte, Bemassung, autodim), cmd_solid.rs (solid, solidbool, voidbox, terrain,
Deckenöffnung, Dachhof, Schnittlinie). Vorschauen über doc_create_preview(_again)
ohne JSON je Mausschritt, Abfragen über doc_create_query; Gruppen-Zuordnung als
`group` im Request ersetzt activeGroupOps. TS hält nur die Zustandsautomaten
(commands/createCore.ts). Ersetzte TS-Geometrie und alte Werkzeug-Commits in
tools/tools.ts gelöscht. Gleichheit alt/neu mit zeitweiligen Zufallstests
geprüft (s. TODO.md). Die drei Gruppen hängen über den gemeinsamen Dispatcher
zusammen und sind deshalb ein Commit.
This commit is contained in:
Claude committed 2026-10-29 15:21:04 +00:00
1 parent 23993e9607
commit 61263efe13
92 files changed
+4169 -4744

No files matched your search

+49 -103
View File
@@ -12,17 +12,17 @@
// 1) „Startpunkt:" → Punkt
// 2) „Durchgangspunkt:" → Punkt (nur Vorschau-Linie, noch kein Bogen)
// 3) „Endpunkt:" → Punkt → commit (Kreis durch alle drei Punkte,
// s. `geometry/bulge.ts` `arcThroughPoints`)
// s. `kernel2d::arc_through_points`, Kern `cmd_draw.rs`)
// • Start-Ende-Radius: Start + Ende + Radius (getippt ODER als Punkt — Abstand
// von der Sehnen-Mitte, wie bei `fillet.ts`s Radius-Schritt). Der Bogen
// wölbt sich zur Seite, auf der der Cursor/Radius-Punkt steht (immer der
// kleinere der beiden möglichen Bögen, s. `arcFromStartEndRadius`).
// kleinere der beiden möglichen Bögen, s. `kernel2d::arc_from_start_end_radius`).
// 1) „Startpunkt:" → Punkt
// 2) „Endpunkt:" → Punkt
// 3) „Radius:" → Punkt ODER Zahl → commit
// • Start-Ende-Richtung: Start + Ende + Tangentenrichtung bei Start (klassische
// dritte AutoCAD-ARC-Methode). Eindeutig bestimmt (kein Seiten-Wahl nötig),
// s. `arcFromStartEndDirection`.
// s. `kernel2d::arc_from_start_end_direction`.
// 1) „Startpunkt:" → Punkt
// 2) „Endpunkt:" → Punkt
// 3) „Richtung:" → Punkt (Tangentenrichtung bei Start) → commit
@@ -31,9 +31,6 @@
// Rendering in PlanView). In generatePlan/PlanView als glatter SVG-Bogen
// (`drawingArc`) gerendert.
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { arcFromStartEndDirection, arcFromStartEndRadius, arcThroughPoints } from "../../core";
import type {
Command,
CommandContext,
@@ -41,13 +38,11 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, type CreatePreview } from "../createCore";
const EPS = 1e-6;
@@ -83,8 +78,8 @@ interface ArcCenterPhase3 extends CommandState {
phase: "end";
method: "center";
center: Vec2;
r: number;
a0: number;
/** Startpunkt (setzt Radius und Startwinkel). */
start: Vec2;
cursor: Vec2 | null;
}
interface ArcThreePhase1 extends CommandState {
@@ -153,48 +148,24 @@ type ArcState =
| ArcThreePhase3;
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const angle = (c: Vec2, p: Vec2): number => Math.atan2(p.y - c.y, p.x - c.x);
const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
/** CCW-Spanne von a0 nach a1, normiert auf (0, 2π]. */
function sweepOf(a0: number, a1: number): number {
const TAU = Math.PI * 2;
const s = ((a1 - a0) % TAU + TAU) % TAU;
return s < EPS ? TAU : s;
}
/** Punkte eines Bogens (CCW a0→a1) für die Vorschau. */
function arcPts(center: Vec2, r: number, a0: number, a1: number): Vec2[] {
const sweep = sweepOf(a0, a1);
const N = Math.max(2, Math.ceil(sweep / (Math.PI / 32)));
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) });
}
return pts;
}
/** Punkte einer vollen Kreis-Approximation (Radius-Vorschau im „start"-Schritt). */
function circlePts(center: Vec2, r: number): Vec2[] {
const N = 48;
const pts: Vec2[] = [];
for (let i = 0; i < N; i++) {
const t = (i / N) * Math.PI * 2;
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
}
return pts;
}
/**
* Bogen im Kern (`cmd_draw.rs`) je Methode aus den Punkten: Mittelpunkt (Mitte, Start, Ende), 3-Punkt,
* Start-Ende-Radius (Radius = Abstand des dritten Punkts von der Sehnenmitte oder getippt),
* Start-Ende-Richtung; `ok` = bestimmt, `info = [cx, cy, r, Spanne°]`. `full`: voller Kreis um den
* Mittelpunkt durch den Cursor (Radius-Vorschau im „start"-Schritt).
*/
const arcAt = (ctx: CommandContext, req: Record<string, unknown>, pts: Vec2[]): CreatePreview =>
createPreview(ctx, { cmd: "arc", ...req }, pts);
/** Vorschau (offener Bogen) + HUD (Radius als L, Spanne als W — L/W-Kästchen). */
function arcDraft(center: Vec2, r: number, a0: number, a1: number, at: Vec2 | null): ToolDraft {
function arcDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft {
const [cx, cy, r, deg] = pv.info;
const center = { x: cx, y: cy };
if (r < EPS) return { preview: [], vertices: [center] };
const preview: DraftShape[] = [{ kind: "poly", pts: arcPts(center, r, a0, a1), closed: false }];
const draft: ToolDraft = { preview, vertices: [center] };
if (at) {
const deg = (sweepOf(a0, a1) * 180) / Math.PI;
draft.hud = { at, length: r, angleDeg: deg };
}
const draft: ToolDraft = { preview: pv.shapes, vertices: [center] };
if (at) draft.hud = { at, length: r, angleDeg: deg };
return draft;
}
@@ -203,17 +174,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft {
return { preview: [{ kind: "line", a, b }], vertices: [a] };
}
function appendArc(center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "arc", center, r, a0, a1 },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Bogen aus der Anfrage (entartet r < EPS → nichts). */
const appendArc = (ctx: CommandContext, req: Record<string, unknown>) => createMutation(ctx, { cmd: "arc", ...req });
const idle = (method: ArcMethod): [CommandState, CommandResult] => [
(method === "center" ? { phase: "center", method } : { phase: "p1", method }) as ArcState,
@@ -265,12 +227,9 @@ export const arcCommand: Command = {
// zuletzt bekannten Cursor (wie beim Tab-Feld-Controller sonst auch).
if (input.kind === "number" && s.method === "ser" && s.phase === "radius") {
const near = s.cursor ?? { x: s.b.x, y: s.b.y };
const arc = arcFromStartEndRadius(s.a, s.b, input.value, near);
if (!arc) return [s, { draft: null }];
return [
idle("ser")[0],
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
const req = { method: "ser", pts: [s.a, s.b, near], r: input.value };
if (!arcAt(ctx, req, [s.a, s.b, near]).ok) return [s, { draft: null }];
return [idle("ser")[0], { draft: null, done: true, commit: appendArc(ctx, req) }];
}
if (input.kind !== "point") return [s, { draft: null }];
const pt = input.point;
@@ -281,18 +240,15 @@ export const arcCommand: Command = {
return [ns, { draft: { preview: [], vertices: [pt] } }];
}
if (s.phase === "start") {
const r = dist(s.center, pt);
if (r < EPS) return [s, { draft: null }];
const a0 = angle(s.center, pt);
const ns: ArcCenterPhase3 = { phase: "end", method: "center", center: s.center, r, a0, cursor: pt, lastPoint: pt };
return [ns, { draft: arcDraft(s.center, r, a0, a0, pt) }];
const pv = arcAt(ctx, { method: "center" }, [s.center, pt, pt]);
if (pv.info[2] < EPS) return [s, { draft: null }];
const ns: ArcCenterPhase3 = { phase: "end", method: "center", center: s.center, start: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: arcDraft(pv, pt) }];
}
// Endpunkt: Endwinkel setzen, Bogen committen.
const a1 = angle(s.center, pt);
const { center, r, a0 } = s;
return [
idle("center")[0],
{ draft: null, done: true, commit: opsMutation(() => appendArc(center, r, a0, a1, ctx)) },
{ draft: null, done: true, commit: appendArc(ctx, { method: "center", pts: [s.center, s.start, pt] }) },
];
}
@@ -308,12 +264,9 @@ export const arcCommand: Command = {
return [ns, { draft: lineDraft(s.a, pt) }];
}
// phase "p3": Endpunkt → Kreis durch alle drei Punkte, committen.
const arc = arcThroughPoints(s.a, s.through, pt);
if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten
return [
idle("three")[0],
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
const req = { method: "three", pts: [s.a, s.through, pt] };
if (!arcAt(ctx, req, [s.a, s.through, pt]).ok) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten
return [idle("three")[0], { draft: null, done: true, commit: appendArc(ctx, req) }];
}
// Methode „ser" (Start-Ende-Radius).
@@ -328,12 +281,9 @@ export const arcCommand: Command = {
return [ns, { draft: lineDraft(s.a, pt) }];
}
// phase "radius": Radius-Punkt → committen (Seite = dieser Punkt).
const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), pt), pt);
if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten
return [
idle("ser")[0],
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
const req = { method: "ser", pts: [s.a, s.b, pt] };
if (!arcAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten
return [idle("ser")[0], { draft: null, done: true, commit: appendArc(ctx, req) }];
}
// Methode „sed" (Start-Ende-Richtung).
@@ -347,35 +297,31 @@ export const arcCommand: Command = {
return [ns, { draft: lineDraft(s.a, pt) }];
}
// phase "direction": Richtungspunkt → committen.
const sedArc = arcFromStartEndDirection(s.a, s.b, pt);
if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten
return [
idle("sed")[0],
{ draft: null, done: true, commit: opsMutation(() => appendArc(sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx)) },
];
const req = { method: "sed", pts: [s.a, s.b, pt] };
if (!arcAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten
return [idle("sed")[0], { draft: null, done: true, commit: appendArc(ctx, req) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as ArcState;
if (s.method === "center") {
if (s.phase === "start") {
const r = dist(s.center, point);
const pv = arcAt(ctx, { full: true }, [s.center, point]);
const ns: ArcCenterPhase2 = { ...s, cursor: point };
return [
ns,
{
draft: {
preview: [{ kind: "poly", pts: circlePts(s.center, r), closed: true }],
preview: pv.shapes,
vertices: [s.center],
hud: { at: point, text: `R: ${r.toFixed(3)}m` },
hud: { at: point, text: `R: ${pv.info[2].toFixed(3)}m` },
},
},
];
}
if (s.phase === "end") {
const a1 = angle(s.center, point);
const ns: ArcCenterPhase3 = { ...s, cursor: point };
return [ns, { draft: arcDraft(s.center, s.r, s.a0, a1, point) }];
return [ns, { draft: arcDraft(arcAt(ctx, { method: "center" }, [s.center, s.start, point]), point) }];
}
return [s, { draft: null }];
}
@@ -387,18 +333,18 @@ export const arcCommand: Command = {
}
if (s.phase === "p3") {
const ns: ArcThreePhase3 = { ...s, cursor: point };
const arc = arcThroughPoints(s.a, s.through, point);
return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, point) }];
const pv = arcAt(ctx, { method: "three" }, [s.a, s.through, point]);
return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, point) }];
}
if (s.phase === "radius") {
const ns: ArcSerPhase3 = { ...s, cursor: point };
const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), point), point);
return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }];
const pv = arcAt(ctx, { method: "ser" }, [s.a, s.b, point]);
return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, s.b) }];
}
if (s.phase === "direction") {
const ns: ArcSedPhase3 = { ...s, cursor: point };
const arc = arcFromStartEndDirection(s.a, s.b, point);
return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }];
const pv = arcAt(ctx, { method: "sed" }, [s.a, s.b, point]);
return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, s.b) }];
}
return [s, { draft: null }];
},
+5 -16
View File
@@ -1,12 +1,11 @@
// Aussenbemassung ([81]) — Sofort-Befehl ohne Punkt-Eingabe: erzeugt für das aktive Geschoss
// die Massketten (Öffnungen, Vor-/Rücksprünge, Gesamtmass) je Gebäudeseite
// (`geometry/autoDimensions.ts`). Ein erneuter Aufruf ersetzt die zuvor automatisch erzeugten
// (Kern: `auto_dimensions.rs`, Elemente `cmd_draw.rs`). Ein erneuter Aufruf ersetzt die zuvor automatisch erzeugten
// Ketten DIESES Geschosses (feste IDs), von Hand gezeichnete Bemassungen bleiben.
import { addItems, autoExteriorDimensions, opsMutation, removeItems } from "../../core";
import { createMutation, createPreview } from "../createCore";
import type { Command, CommandContext, CommandResult, CommandState } from "../types";
const PREFIX = "autodim";
const done = (): [CommandState, CommandResult] => [
{ phase: "idle", lastPoint: null },
@@ -23,19 +22,9 @@ export const autodimCommand: Command = {
autoRun: (ctx: CommandContext): CommandResult => {
if (ctx.level.kind !== "floor") return { draft: null, done: true };
const floorId = ctx.level.id;
const dims = autoExteriorDimensions(ctx.project, floorId, ctx.defaultCategoryCode, 100, PREFIX);
if (dims.length === 0) return { draft: null, done: true };
const own = `${PREFIX}-${floorId}-`;
return {
draft: null,
done: true,
// Frühere Ketten dieses Geschosses raus, neue hinten dran.
commit: opsMutation((p) => [
...removeItems(p, "drawings2d", (d) => d.id.startsWith(own)),
...addItems("drawings2d", dims.map((d) => d.drawing)),
]),
};
// Ketten im Kern (`cmd_draw.rs`, `auto_dimensions.rs`); ohne Ketten (keine Wände) kein Commit.
if (!createPreview(ctx, { cmd: "autodim" }, []).ok) return { draft: null, done: true };
return { draft: null, done: true, commit: createMutation(ctx, { cmd: "autodim" }) };
},
onInput: (): [CommandState, CommandResult] => done(),
+15 -28
View File
@@ -7,9 +7,6 @@
// Nach ≥1 fertigem Segment kann „Fertig" (Enter) den Zug abschliessen; jeder
// weitere Anker startet automatisch ein neues Segment (Schritte 2–4).
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { sampleBezierChain } from "../../core";
import type {
Command,
CommandContext,
@@ -20,8 +17,7 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
interface BezierStart extends CommandState {
phase: "start";
@@ -52,24 +48,15 @@ type BezierState = BezierStart | BezierC1 | BezierC2 | BezierEnd;
const FINISH: CmdOption = { id: "finish", labelKey: "cmd.bezier.finish" };
/** Vorschau: abgeschlossene Kurve (tessellierte Segmente) + Gummiband-Linien des laufenden Segments. */
function bezierDraft(pts: Vec2[], rubber: Vec2[]): ToolDraft {
const preview: DraftShape[] = [];
if (pts.length >= 4) preview.push({ kind: "poly", pts: sampleBezierChain(pts), closed: false });
function bezierDraft(ctx: CommandContext, pts: Vec2[], rubber: Vec2[]): ToolDraft {
// Bezier-Kette ab 4 Punkten im Kern (`cmd_draw.rs`, 24 Schritte je Kurve), Gummiband dazu.
const preview: DraftShape[] = pts.length >= 4 ? createPreview(ctx, { cmd: "bezier" }, pts).shapes : [];
for (let i = 0; i < rubber.length - 1; i++) preview.push({ kind: "line", a: rubber[i], b: rubber[i + 1] });
return { preview, vertices: pts.length > 0 ? [pts[0]] : [] };
}
function appendBezier(pts: Vec2[], ctx: CommandContext): CoreOp[] {
if (pts.length < 4) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "bezier", pts },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Bezier-Kette (mindestens 4 Punkte). */
const appendBezier = (pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "bezier", pts });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as BezierStart,
@@ -77,7 +64,7 @@ const idle = (): [CommandState, CommandResult] => [
];
const finish = (pts: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as BezierStart,
{ draft: null, done: true, commit: opsMutation(() => appendBezier(pts, ctx)) },
{ draft: null, done: true, commit: appendBezier(pts, ctx) },
];
export const bezierCommand: Command = {
@@ -109,11 +96,11 @@ export const bezierCommand: Command = {
if (s.phase === "start") {
const ns: BezierC1 = { phase: "c1", pts: [pt], anchor: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: bezierDraft(ns.pts, [pt]) }];
return [ns, { draft: bezierDraft(ctx, ns.pts, [pt]) }];
}
if (s.phase === "c1") {
const ns: BezierC2 = { phase: "c2", pts: s.pts, anchor: s.anchor, c1: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: bezierDraft(ns.pts, [s.anchor, pt]) }];
return [ns, { draft: bezierDraft(ctx, ns.pts, [s.anchor, pt]) }];
}
if (s.phase === "c2") {
const ns: BezierEnd = {
@@ -125,28 +112,28 @@ export const bezierCommand: Command = {
cursor: pt,
lastPoint: pt,
};
return [ns, { draft: bezierDraft(ns.pts, [s.anchor, s.c1, pt]) }];
return [ns, { draft: bezierDraft(ctx, ns.pts, [s.anchor, s.c1, pt]) }];
}
// phase "end": Segment abschliessen, direkt das nächste Segment beginnen.
const pts = [...s.pts, s.c1, s.c2, pt];
const ns: BezierC1 = { phase: "c1", pts, anchor: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: bezierDraft(pts, [pt]) }];
return [ns, { draft: bezierDraft(ctx, pts, [pt]) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as BezierState;
if (s.phase === "start") return [s, { draft: null }];
if (s.phase === "c1") {
const ns: BezierC1 = { ...s, cursor: point };
return [ns, { draft: bezierDraft(s.pts, [s.anchor, point]) }];
return [ns, { draft: bezierDraft(ctx, s.pts, [s.anchor, point]) }];
}
if (s.phase === "c2") {
const ns: BezierC2 = { ...s, cursor: point };
return [ns, { draft: bezierDraft(s.pts, [s.anchor, s.c1, point]) }];
return [ns, { draft: bezierDraft(ctx, s.pts, [s.anchor, s.c1, point]) }];
}
const ns: BezierEnd = { ...s, cursor: point };
// Endschritt: die tatsächliche Bezier-Kurve bis zum Cursor live anzeigen.
return [ns, { draft: bezierDraft([...s.pts, s.c1, s.c2, point], []) }];
return [ns, { draft: bezierDraft(ctx, [...s.pts, s.c1, s.c2, point], []) }];
},
onConfirm: (state, ctx): [CommandState, CommandResult] => {
+9 -31
View File
@@ -14,8 +14,7 @@
// wie bei `circle.ts`s Radius-Punkt). Kein separater dritter Klick-Schritt
// nötig — Nutzer-Wunsch „Skalierung beim Einfügen" bei minimaler UX-Änderung.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
CmdOption,
Command,
@@ -24,8 +23,7 @@ import type {
CommandState,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
const EPS = 1e-6;
@@ -52,28 +50,12 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } {
return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) };
}
function appendInstance(blockDefId: string,
at: Vec2,
rotation: number,
scale: number,
ctx: CommandContext,
): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "block", blockDefId, at, rotation, scale },
};
return addItems("drawings2d", [d]);
}
/** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */
function rotationAndScaleFrom(at: Vec2, pt: Vec2): { rotation: number; scale: number } {
const d = Math.hypot(pt.x - at.x, pt.y - at.y);
if (d < EPS) return { rotation: 0, scale: 1 };
return { rotation: Math.atan2(pt.y - at.y, pt.x - at.x), scale: d };
}
/**
* Commit (Kern, `cmd_draw.rs`): Block-Instanz am Einfügepunkt; der zweite Punkt gibt Drehung (Richtung)
* und Massstab (Abstand) — derselbe Punkt: unskaliert, ungedreht.
*/
const appendInstance = (blockDefId: string, at: Vec2, pt: Vec2, ctx: CommandContext) =>
createMutation(ctx, { cmd: "block", def: blockDefId, at, pt });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null, defIds: [], defNames: [] } as BlockPoint,
@@ -113,11 +95,7 @@ export const blockCommand: Command = {
const blockDefId = s.defIds[lastDefIndex % s.defIds.length];
const { at } = s;
const pt = input.point;
const { rotation, scale } = rotationAndScaleFrom(at, pt);
return [
idle()[0],
{ draft: null, done: true, commit: opsMutation(() => appendInstance(blockDefId, at, rotation, scale, ctx)) },
];
return [idle()[0], { draft: null, done: true, commit: appendInstance(blockDefId, at, pt, ctx) }];
},
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
+9 -47
View File
@@ -15,9 +15,6 @@
// • floorId ← ctx.level.id (aktives Geschoss)
// • categoryCode← "30" (Ebene „Decken"; Fallback ctx.defaultCategoryCode)
import type { Ceiling } from "../../model/types";
import { normalizeOutline, ceilingArea } from "../../core";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -29,14 +26,11 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, xy } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Umriss
/** Default-Ebene (Kategorie) für Decken. */
const CEILING_CATEGORY = "30";
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
@@ -61,29 +55,6 @@ function nextFromFields(
return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length };
}
/** Aktiver Aufbau-Typ-ID; Fallback auf den ersten Projekt-Wandtyp. */
function activeTypeId(ctx: CommandContext): string {
const wt =
ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ??
ctx.project.wallTypes[0];
return wt ? wt.id : ctx.activeWallTypeId;
}
/** Existiert die Decken-Kategorie („30")? Sonst Fallback auf die aktive Kategorie. */
function ceilingCategory(ctx: CommandContext): string {
const flat: { code: string }[] = [];
const walk = (list: { code: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push({ code: c.code });
if (c.children) walk(c.children as { code: string; children?: unknown[] }[]);
}
};
walk(ctx.project.layers as { code: string; children?: unknown[] }[]);
return flat.some((c) => c.code === CEILING_CATEGORY)
? CEILING_CATEGORY
: ctx.defaultCategoryCode;
}
interface CeilIdle extends CommandState {
phase: "start";
}
@@ -115,20 +86,11 @@ function ceilingDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
/** Hängt eine Decke ans Projekt (immutabel). Entartete Umrisse werden verworfen. */
function appendCeiling(pts: Vec2[], ctx: CommandContext): CoreOp[] {
const outline = normalizeOutline(pts);
if (!outline || ceilingArea(outline) < 1e-4) return [];
const ceiling: Ceiling = {
id: uniqueId("C"),
type: "ceiling",
floorId: ctx.level.id,
categoryCode: ceilingCategory(ctx),
outline,
wallTypeId: activeTypeId(ctx),
};
return addItems("ceilings", [ceiling]);
}
/**
* Commit: Decke aus dem Umriss (normalisiert, CCW; entartet → nichts), Typ = aktiver Aufbau, Ebene
* „30“ falls vorhanden — im Kern (`cmd_create.rs`).
*/
const appendCeiling = (pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "ceiling", pts: pts.map(xy) });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as CeilIdle,
@@ -175,7 +137,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
{ draft: null, done: true, commit: appendCeiling(pts, ctx) },
];
}
return [s, { draft: ceilingDraft(s.points, s.cursor) }];
@@ -197,7 +159,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
{ draft: null, done: true, commit: appendCeiling(pts, ctx) },
];
}
// Null-Strecke (Klick auf denselben Punkt) ignorieren.
@@ -224,7 +186,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
{ draft: null, done: true, commit: appendCeiling(pts, ctx) },
];
}
return idle();
+14 -38
View File
@@ -8,33 +8,18 @@
// 1) „Erste Ecke der Aussparung:" → Punkt
// 2) „Gegenecke:" → Live-Rechteck-Vorschau; Klick committet.
import { opsMutation, patchItem, pointInOutline } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
/** Vier Eckpunkte eines Rechtecks aus zwei Gegenecken (CCW). */
function rectCorners(a: Vec2, b: Vec2): Vec2[] {
const x0 = Math.min(a.x, b.x);
const x1 = Math.max(a.x, b.x);
const y0 = Math.min(a.y, b.y);
const y1 = Math.max(a.y, b.y);
return [
{ x: x0, y: y0 },
{ x: x1, y: y0 },
{ x: x1, y: y1 },
{ x: x0, y: y1 },
];
}
interface HoleIdle extends CommandState {
phase: "start";
}
@@ -46,9 +31,9 @@ interface HoleRect extends CommandState {
type HoleState = HoleIdle | HoleRect;
/** Vorschau: aufgezogenes Rechteck + Masse im HUD. */
function holeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
const pts = cursor ? rectCorners(a, cursor) : [a];
const preview: DraftShape[] = [{ kind: "poly", pts, closed: !!cursor }];
function holeDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
// Aufgezogenes Rechteck im Kern (`cmd_create.rs`).
const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "rect4" }, [a, cursor]).shapes : [{ kind: "poly", pts: [a], closed: false }];
const draft: ToolDraft = { preview, vertices: [a] };
if (cursor) {
draft.hud = {
@@ -64,20 +49,11 @@ function holeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
* Rechteck vollständig enthält (alle 4 Ecken im Umriss). Entartete Rechtecke
* und Rechtecke ausserhalb jeder Decke werden verworfen (Projekt unverändert).
*/
function ceilingOpeningOps(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const w = Math.abs(b.x - a.x);
const d = Math.abs(b.y - a.y);
if (w < 0.05 || d < 0.05) return [];
const corners = rectCorners(a, b);
const host = (p.ceilings ?? []).find(
(c) =>
c.floorId === ctx.level.id &&
c.outline.length >= 3 &&
corners.every((pt) => pointInOutline(pt, c.outline)),
);
if (!host) return [];
return patchItem(p, "ceilings", host.id, (c) => ({ ...c, openings: [...(c.openings ?? []), corners] }));
}
/**
* Commit (Kern, `cmd_solid.rs`): rechteckige Aussparung (≥ 5 cm je Seite) in die Decke des Geschosses,
* die alle vier Ecken enthält; keine solche Decke → nichts.
*/
const ceilingOpening = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "ceilingOpening", a, b });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as HoleIdle,
@@ -97,7 +73,7 @@ export const ceilingOpeningCommand: Command = {
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as HoleState;
if (input.kind !== "point") {
return [s, { draft: s.phase === "corner" ? holeDraft(s.a, s.cursor) : null }];
return [s, { draft: s.phase === "corner" ? holeDraft(ctx, s.a, s.cursor) : null }];
}
if (s.phase !== "corner") {
const ns: HoleRect = {
@@ -106,22 +82,22 @@ export const ceilingOpeningCommand: Command = {
cursor: input.point,
lastPoint: input.point,
};
return [ns, { draft: holeDraft(input.point, input.point) }];
return [ns, { draft: holeDraft(ctx, input.point, input.point) }];
}
// Zweite Ecke → committen.
const a = s.a;
const b = input.point;
return [
{ phase: "start", lastPoint: null } as HoleIdle,
{ draft: null, done: true, commit: opsMutation((p) => ceilingOpeningOps(p, a, b, ctx)) },
{ draft: null, done: true, commit: ceilingOpening(a, b, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as HoleState;
if (s.phase !== "corner") return [s, { draft: null }];
const ns: HoleRect = { ...s, cursor: point };
return [ns, { draft: holeDraft(s.a, point) }];
return [ns, { draft: holeDraft(ctx, s.a, point) }];
},
onConfirm: (): [CommandState, CommandResult] => idle(),
+50 -139
View File
@@ -23,7 +23,7 @@
// dasselbe Element wie Schritt 1 wird ignoriert)
// 3) „Radius:" → Punkt (Abstand zum ERSTEN Klickpunkt aus Schritt 1)
// ODER getippte Zahl → commit. Die eigentliche Geometrie steckt in
// `geometry/kernel2d.ts::tangentCircleCenters` (Apollonius-
// `kernel2d::tangent_circle_centers` (Kern, `cmd_draw.rs`) (Apollonius-
// Spezialfall mit bekanntem Radius): pro Tangentialobjekt wird der
// geometrische Ort aller passenden Mittelpunkte gebildet (Gerade:
// zwei Parallelen im Abstand r; Kreis: äussere/innere Berührung),
@@ -35,10 +35,6 @@
// Maus-Punkt (Abstand) als auch eine getippte nackte Zahl. Der Kreis wird in
// generatePlan als geschlossene Polygon-Approximation gerendert.
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { arcThroughPoints } from "../../core";
import { pointSegmentDistance, polylineEdges, tangentCircleCenters, type TangentTarget } from "../../core";
import type {
CmdOption,
Command,
@@ -46,14 +42,14 @@ import type {
CommandField,
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, createQuery, xy, type CreatePreview } from "../createCore";
/** Tangenten-Objekt (Gerade oder Kreis), wie der Kern es beim Picken liefert. */
type TangentTarget = Record<string, unknown>;
const EPS = 1e-6;
@@ -141,11 +137,8 @@ type CircleState =
| CircleTtrRadius;
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
// ── TTR: Hit-Testing auf bestehende Linien/Kreise ───────────────────────────
const TTR_HIT_TOL = 0.3; // Modell-Meter: Pick-Toleranz für die Tangentenobjekt-Wahl
// ── TTR: Hit-Testing auf bestehende Linien/Kreise (Kern) ─────────────────────
interface TangentPick {
target: TangentTarget;
@@ -153,75 +146,14 @@ interface TangentPick {
drawingId: string;
}
/** Winkel `ang` (rad) liegt innerhalb des Bogenspanns [a0, a1) (CCW, mit Wraparound). */
function inArcSpan(a0: number, a1: number, ang: number): boolean {
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
const sweep = norm(a1 - a0) || TAU;
return norm(ang - a0) <= sweep + 1e-6;
}
/** Gerade Kanten einer Form (line/polyline ohne Bogen-Segmente/rect) für den TTR-Hit-Test. */
function straightEdgesOf(g: Drawing2DGeom): [Vec2, Vec2][] {
if (g.shape === "line") return [[g.a, g.b]];
if (g.shape === "rect") {
const pts = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return polylineEdges(pts, true);
}
if (g.shape === "polyline") {
const edges = polylineEdges(g.pts, g.closed);
// Bogen-Segmente (bulge) sind hier keine Geraden — von der Tangenten-Wahl
// ausgenommen (dieselbe Vereinfachung wie bei fillet.ts::geomToCurve).
return edges.filter((_, i) => Math.abs(g.bulge?.[i] ?? 0) <= EPS);
}
return [];
}
/** Nächstes tangentenfähiges Element (Gerade ODER Kreis/Bogen) zum Klickpunkt, oder null. */
function pickTangentTarget(project: Project, levelId: string, pt: Vec2): TangentPick | null {
let best: TangentPick | null = null;
let bestD = TTR_HIT_TOL;
for (const d of project.drawings2d) {
if (d.levelId !== levelId) continue;
const g = d.geom;
if (g.shape === "circle") {
const dd = Math.abs(dist(pt, g.center) - g.r);
if (dd < bestD) {
bestD = dd;
best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id };
}
} else if (g.shape === "arc") {
const dd = Math.abs(dist(pt, g.center) - g.r);
const ang = Math.atan2(pt.y - g.center.y, pt.x - g.center.x);
if (dd < bestD && inArcSpan(g.a0, g.a1, ang)) {
bestD = dd;
best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id };
}
} else {
for (const [a, b] of straightEdgesOf(g)) {
const dd = pointSegmentDistance(pt, a, b);
if (dd < bestD) {
bestD = dd;
best = { target: { kind: "line", a, b }, near: pt, drawingId: d.id };
}
}
}
}
return best;
}
/** Von mehreren Mittelpunkt-Kandidaten den zu (near1, near2) nächstgelegenen wählen. */
function nearestCandidate(cands: Vec2[], near1: Vec2, near2: Vec2): Vec2 | null {
let best: Vec2 | null = null;
let bestD = Infinity;
for (const c of cands) {
const dd = dist(c, near1) + dist(c, near2);
if (dd < bestD) {
bestD = dd;
best = c;
}
}
return best;
/** Nächstes tangentenfähiges Element (Gerade ODER Kreis/Bogen) zum Klickpunkt (Toleranz 0.3 m), oder null. */
function pickTangentTarget(ctx: CommandContext, pt: Vec2): TangentPick | null {
const r = createQuery<{ hit: { target: TangentTarget; id: string } | null }>(ctx.project, {
q: "pickTangent",
level: ctx.level.id,
pt: xy(pt),
});
return r.hit ? { target: r.hit.target, near: pt, drawingId: r.hit.id } : null;
}
/** Tab-Feld des Radius-Schritts (nur Methode „center"): der Radius selbst. */
@@ -242,22 +174,19 @@ function circlePointFromFields(center: Vec2, locks: Record<string, number>, curs
return { x: center.x + r, y: center.y };
}
/** Punkte einer Kreis-Approximation (für die Vorschau). */
function circlePts(center: Vec2, r: number): Vec2[] {
const N = 48;
const pts: Vec2[] = [];
for (let i = 0; i < N; i++) {
const t = (i / N) * Math.PI * 2;
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
}
return pts;
}
/**
* Kreis im Kern (`cmd_draw.rs`): Mittelpunkt + Radius je Methode (2-Punkt: Durchmesser, 3-Punkt:
* Umkreis, TTR: tangential an zwei Objekte, nächster Kandidat zu den Klickpunkten); `ok` = bestimmt.
*/
const circleAt = (ctx: CommandContext, req: Record<string, unknown>, pts: Vec2[]): CreatePreview =>
createPreview(ctx, { cmd: "circle", ...req }, pts);
/** Vorschau (Kreis) + HUD (Radius). */
function circleDraft(center: Vec2, r: number, at: Vec2 | null): ToolDraft {
/** Vorschau (Kreis, 48-Eck) + HUD (Radius). */
function circleDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft {
const [cx, cy, r] = pv.info;
const center = { x: cx, y: cy };
if (r < EPS) return { preview: [], vertices: [center] };
const preview: DraftShape[] = [{ kind: "poly", pts: circlePts(center, r), closed: true }];
const draft: ToolDraft = { preview, vertices: [center] };
const draft: ToolDraft = { preview: pv.shapes, vertices: [center] };
if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m` };
return draft;
}
@@ -267,17 +196,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft {
return { preview: [{ kind: "line", a, b }], vertices: [a] };
}
function appendCircle(center: Vec2, r: number, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "circle", center, r },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Kreis aus der Anfrage (entartet r < EPS → nichts). */
const appendCircle = (ctx: CommandContext, req: Record<string, unknown>) => createMutation(ctx, { cmd: "circle", ...req });
const idle = (method: CircleMethod): [CommandState, CommandResult] => [
(method === "center"
@@ -331,27 +251,25 @@ export const circleCommand: Command = {
if (s.phase !== "radius") {
if (input.kind !== "point") return [s, { draft: null }];
const ns: CircleCenterP2 = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point };
return [ns, { draft: circleDraft(input.point, 0, null) }];
return [ns, { draft: { preview: [], vertices: [input.point] } }];
}
let r: number;
if (input.kind === "number") r = input.value;
else r = dist(s.center, input.point);
const center = s.center;
return [idle("center")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
const req =
input.kind === "number"
? { method: "center", pts: [s.center], r: input.value }
: { method: "center", pts: [s.center, input.point] };
return [idle("center")[0], { draft: null, done: true, commit: appendCircle(ctx, req) }];
}
if (s.method === "ttr") {
if (s.phase === "radius") {
let r: number;
if (input.kind === "number") r = input.value;
else r = dist(s.near1, input.point);
const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null;
const req = { method: "ttr", t1: s.t1, t2: s.t2, near1: s.near1, near2: s.near2 };
const full = input.kind === "number" ? { ...req, r: input.value } : { ...req, pts: [input.point] };
// Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten.
if (!center) return [s, { draft: null }];
return [idle("ttr")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
if (!circleAt(ctx, full, input.kind === "number" ? [] : [input.point]).ok) return [s, { draft: null }];
return [idle("ttr")[0], { draft: null, done: true, commit: appendCircle(ctx, full) }];
}
if (input.kind !== "point") return [s, { draft: null }];
const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point);
const pick = pickTangentTarget(ctx, input.point);
if (!pick) return [s, { draft: null }]; // kein Treffer auf Linie/Kreis — ignorieren, weiter warten
if (s.phase === "t1") {
const ns: CircleTtrT2 = {
@@ -387,9 +305,7 @@ export const circleCommand: Command = {
const ns: CircleTwoP2 = { phase: "p2", method: "twoPoint", a: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: { preview: [], vertices: [pt] } }];
}
const center = mid(s.a, pt);
const r = dist(s.a, pt) / 2;
return [idle("twoPoint")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
return [idle("twoPoint")[0], { draft: null, done: true, commit: appendCircle(ctx, { method: "twoPoint", pts: [s.a, pt] }) }];
}
// threePoint
@@ -403,26 +319,22 @@ export const circleCommand: Command = {
return [ns, { draft: lineDraft(s.a, pt) }];
}
// phase p3: dritter Punkt → Umkreis, committen.
const circ = arcThroughPoints(s.a, s.b, pt); // a0/a1 hier irrelevant, nur center+r zählen
if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten
return [
idle("threePoint")[0],
{ draft: null, done: true, commit: opsMutation(() => appendCircle(circ.center, circ.r, ctx)) },
];
const req = { method: "threePoint", pts: [s.a, s.b, pt] };
if (!circleAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten
return [idle("threePoint")[0], { draft: null, done: true, commit: appendCircle(ctx, req) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as CircleState;
if (s.method === "center") {
if (s.phase !== "radius") return [s, { draft: null }];
const r = dist(s.center, point);
const ns: CircleCenterP2 = { ...s, cursor: point };
return [ns, { draft: circleDraft(s.center, r, point) }];
return [ns, { draft: circleDraft(circleAt(ctx, { method: "center" }, [s.center, point]), point) }];
}
if (s.method === "twoPoint") {
if (s.phase !== "p2") return [s, { draft: null }];
const ns: CircleTwoP2 = { ...s, cursor: point };
return [ns, { draft: circleDraft(mid(s.a, point), dist(s.a, point) / 2, point) }];
return [ns, { draft: circleDraft(circleAt(ctx, { method: "twoPoint" }, [s.a, point]), point) }];
}
// threePoint
if (s.phase === "p2") {
@@ -431,15 +343,14 @@ export const circleCommand: Command = {
}
if (s.phase === "p3") {
const ns: CircleThreeP3 = { ...s, cursor: point };
const circ = arcThroughPoints(s.a, s.b, point);
return [ns, { draft: circ ? circleDraft(circ.center, circ.r, point) : lineDraft(s.a, point) }];
const pv = circleAt(ctx, { method: "threePoint" }, [s.a, s.b, point]);
return [ns, { draft: pv.ok ? circleDraft(pv, point) : lineDraft(s.a, point) }];
}
if (s.method === "ttr" && s.phase === "radius") {
const r = dist(s.near1, point);
const ns: CircleTtrRadius = { ...s, cursor: point };
if (r < EPS) return [ns, { draft: null }];
const center = nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2);
return [ns, { draft: center ? circleDraft(center, r, point) : lineDraft(s.near1, s.near2) }];
const pv = circleAt(ctx, { method: "ttr", t1: s.t1, t2: s.t2, near1: s.near1, near2: s.near2 }, [point]);
if (pv.info[2] < EPS) return [ns, { draft: null }];
return [ns, { draft: pv.ok ? circleDraft(pv, point) : lineDraft(s.near1, s.near2) }];
}
return [s, { draft: null }];
},
+15 -52
View File
@@ -13,9 +13,6 @@
//
// Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md).
import type { Column, ColumnProfile } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { columnFootprint } from "../../core";
import type {
Command,
CommandContext,
@@ -24,15 +21,10 @@ import type {
CmdOption,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, xy } from "../createCore";
/** Default-Ebene (Kategorie) für Stützen: „50" Tragwerk (Fallback: aktive). */
const COLUMN_CATEGORY = "50";
/** Default-Kantenlänge eines Rechteckprofils (Meter). */
const DEF_SIZE = 0.3;
/** Fallback-Höhe, falls das Geschoss keine floorHeight trägt (Meter). */
const DEF_HEIGHT = 2.6;
// ── Persistente Defaults (modulweit, leben über Befehls-Instanzen hinweg) ────
const columnDefaults: { kind: "rect" | "round"; size: number } = {
@@ -40,34 +32,15 @@ const columnDefaults: { kind: "rect" | "round"; size: number } = {
size: DEF_SIZE,
};
/** Baut das aktuelle Default-Profil aus `columnDefaults`. */
function currentProfile(): ColumnProfile {
if (columnDefaults.kind === "round") {
return { kind: "round", radius: columnDefaults.size / 2 };
}
return { kind: "rect", width: columnDefaults.size, depth: columnDefaults.size };
}
/** Profil-Optionen der Anfrage (Kern baut daraus das Profil: rund Ø `size`, sonst quadratisch). */
const profileReq = () => ({ kind: columnDefaults.kind, size: columnDefaults.size });
/** Fügt die Stütze immutabel an `project.columns` an. */
function appendColumn(position: Vec2,
ctx: CommandContext,
): CoreOp[] {
const height =
ctx.level.floorHeight != null && ctx.level.floorHeight > 0
? ctx.level.floorHeight
: DEF_HEIGHT;
const column: Column = {
id: uniqueId("column"),
type: "column",
floorId: ctx.level.id,
categoryCode: COLUMN_CATEGORY,
position,
profile: currentProfile(),
rotation: 0,
height,
};
return addItems("columns", [column]);
}
/**
* Commit (Kern, `cmd_create.rs`): Stütze am Punkt, Ebene „50“, Höhe = Geschosshöhe (sonst 2.6 m),
* Profil aus den Vorgaben.
*/
const appendColumn = (position: Vec2, ctx: CommandContext) =>
createMutation(ctx, { cmd: "column", at: xy(position), ...profileReq() });
interface ColState extends CommandState {
phase: "place" | "done";
@@ -78,25 +51,15 @@ const finish = (): [CommandState, CommandResult] => [
{ draft: null, done: true },
];
/** Footprint-Vorschau des aktuellen Default-Profils am Cursor. */
function previewAt(pt: Vec2): CommandResult {
const ghost: Column = {
id: "_preview",
type: "column",
floorId: "",
categoryCode: COLUMN_CATEGORY,
position: pt,
profile: currentProfile(),
rotation: 0,
height: 0,
};
/** Footprint-Vorschau des aktuellen Default-Profils am Cursor (Kern). */
function previewAt(pt: Vec2, ctx: CommandContext): CommandResult {
const size =
columnDefaults.kind === "round"
? `Ø${(columnDefaults.size * 100).toFixed(0)}`
: `${(columnDefaults.size * 100).toFixed(0)}×${(columnDefaults.size * 100).toFixed(0)}`;
return {
draft: {
preview: [{ kind: "poly", pts: columnFootprint(ghost), closed: true }],
preview: createPreview(ctx, { cmd: "column", ...profileReq() }, [pt]).shapes,
vertices: [],
hud: { at: pt, text: size },
},
@@ -134,16 +97,16 @@ export const columnCommand: Command = {
if (input.kind === "point") {
return [
{ phase: "done", lastPoint: null } as ColState,
{ draft: null, done: true, commit: opsMutation(() => appendColumn(input.point, ctx)) },
{ draft: null, done: true, commit: appendColumn(input.point, ctx) },
];
}
return [s, { draft: null }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as ColState;
if (s.phase !== "place") return [s, { draft: null }];
return [s, previewAt(point)];
return [s, previewAt(point, ctx)];
},
onConfirm: (): [CommandState, CommandResult] => finish(),
+4 -7
View File
@@ -10,9 +10,7 @@
// verschachtelten Blöcke, v1 — s. `BlockDef`-Kopfkommentar in model/types.ts).
// Leere/rein-block-Auswahl → No-Op (kein Commit).
import { opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { documentFor } from "../../core/document";
import { cmdMutation } from "../../core/document";
import { uniqueStamp } from "../../tools/types";
import type {
Command,
@@ -20,7 +18,6 @@ import type {
CommandResult,
CommandSelection,
CommandState,
Project,
Vec2,
} from "../types";
@@ -30,8 +27,8 @@ function selectedDrawingIds(sel: CommandSelection): string[] {
}
/** Definition anhängen, Quellen raus, Instanz hinten dran — rechnet der Kern (`cmd_transform::defblock_ops`). */
function defineOps(p: Project, ids: string[], at: Vec2, ctx: CommandContext): CoreOp[] {
return documentFor(p).cmdOps({
function defineMutation(ids: string[], at: Vec2, ctx: CommandContext) {
return cmdMutation({
cmd: "defblock",
ids,
at: [at.x, at.y],
@@ -63,7 +60,7 @@ export const defblockCommand: Command = {
const ids = selectedDrawingIds(ctx.selection);
if (ids.length === 0) return idle();
const at = input.point;
return [idle()[0], { draft: null, done: true, commit: opsMutation((p) => defineOps(p, ids, at, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: defineMutation(ids, at, ctx) }];
},
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
+8 -28
View File
@@ -6,22 +6,16 @@
// Position, Feinheiten hinterher) — kein Tipp-Schritt beim Platzieren
// nötig, das Symbol landet sofort selektiert-editierbar im Plan.
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (plan/drawings.rs)
const DEFAULT_LABEL = "A";
interface DetailRefIdle extends CommandState {
phase: "point";
@@ -29,27 +23,13 @@ interface DetailRefIdle extends CommandState {
type DetailRefState = DetailRefIdle;
/** Kreis-Vorschau (Vollkreis-Approximation, wie andere Symbol-Vorschauen). */
function pointDraft(at: Vec2): ToolDraft {
const N = 32;
const pts: Vec2[] = [];
for (let i = 0; i < N; i++) {
const t = (i / N) * Math.PI * 2;
pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) });
}
const preview: DraftShape[] = [{ kind: "poly", pts, closed: true }];
return { preview, vertices: [at] };
/** Vorschau (Kern, `cmd_draw.rs`): Verweisblase (Kreis r = 0.3 m) am Cursor. */
function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft {
return { preview: createPreview(ctx, { cmd: "detailref" }, [at]).shapes, vertices: [at] };
}
function appendDetailRef(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "detailref", at, label: DEFAULT_LABEL },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Verweis „A“ am Punkt (Label/Blatt danach im Attribut-Panel). */
const appendDetailRef = (at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "detailref", at });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null } as DetailRefIdle,
@@ -69,11 +49,11 @@ export const detailrefCommand: Command = {
if (input.kind !== "point") return [s, { draft: null }];
return [
{ phase: "point", lastPoint: null } as DetailRefIdle,
{ draft: null, done: true, commit: opsMutation(() => appendDetailRef(input.point, ctx)) },
{ draft: null, done: true, commit: appendDetailRef(input.point, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }],
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }],
onConfirm: (): [CommandState, CommandResult] => idle(),
onCancel: (): [CommandState, CommandResult] => idle(),
};
+38 -88
View File
@@ -22,8 +22,7 @@
// Die Masszahl wird beim Rendern aus dist(a,b) abgeleitet (nicht gespeichert)
// — bleibt beim späteren Griff-Ziehen automatisch korrekt.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -31,13 +30,10 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation, patchItem } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, createQuery, xy } from "../createCore";
const EPS = 1e-6;
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
@@ -51,44 +47,19 @@ function signedOffset(a: Vec2, b: Vec2, pt: Vec2): number {
return (pt.x - a.x) * nx + (pt.y - a.y) * ny;
}
/** Projiziert `pt` auf die Gerade durch `p0` in Richtung `p1` (Kette bleibt gerade ab Punkt 3). */
function projectOnLine(p0: Vec2, p1: Vec2, pt: Vec2): Vec2 {
const dx = p1.x - p0.x, dy = p1.y - p0.y;
const len2 = dx * dx + dy * dy;
if (len2 < EPS) return pt;
const t = ((pt.x - p0.x) * dx + (pt.y - p0.y) * dy) / len2;
return { x: p0.x + dx * t, y: p0.y + dy * t };
}
/**
* Sortiert `raw` (auf die Kettengerade projiziert) an die richtige Stelle in
* `pts` ein — VOR dem ersten (verlängert rückwärts), NACH dem letzten
* (verlängert vorwärts) oder ZWISCHEN zwei bestehenden Punkten (fügt ein).
* `pts` muss bereits kollinear sein (≥ 2 Punkte); die Skalarposition entlang
* der durch `pts[0]`/`pts[1]` festgelegten Geraden entscheidet die Reihenfolge.
* Neuen Punkt in die Kette einsortieren (Kern, `cmd_draw.rs`): auf die Masslinie pts[0]→pts[1]
* projiziert und nach Parameter einsortiert; unter 2 Punkten einfach angehängt.
*/
function insertIntoChain(pts: Vec2[], raw: Vec2): Vec2[] {
if (pts.length < 2) return [...pts, raw];
const p0 = pts[0], p1 = pts[1];
const dx = p1.x - p0.x, dy = p1.y - p0.y;
const len2 = dx * dx + dy * dy || 1;
const tOf = (p: Vec2): number => ((p.x - p0.x) * dx + (p.y - p0.y) * dy) / len2;
const placed = projectOnLine(p0, p1, raw);
const newT = tOf(placed);
let idx = pts.findIndex((p) => newT < tOf(p));
if (idx === -1) idx = pts.length;
const out = [...pts];
out.splice(idx, 0, placed);
return out;
function insertIntoChain(ctx: CommandContext, pts: Vec2[], raw: Vec2): Vec2[] {
return createQuery<{ pts: Vec2[] }>(ctx.project, { q: "dimInsert", pts, pt: xy(raw) }).pts;
}
/** Bestehende, selektierte Masskette (Rhino: erst selektieren, dann Befehl) oder null. */
/** Vorgewählte Bemassungskette (Kern), deren Punkte erweitert werden. */
function selectedChain(ctx: CommandContext): { id: string; pts: Vec2[]; offset: number } | null {
const id = ctx.selection.drawingId;
if (!id) return null;
const d = ctx.project.drawings2d.find((x) => x.id === id);
if (!d || d.geom.shape !== "dimension") return null;
return { id: d.id, pts: d.geom.pts, offset: d.geom.offset };
return createQuery<{ hit: { id: string; pts: Vec2[]; offset: number } | null }>(ctx.project, { q: "dimChain", id }).hit;
}
/** Endpunkte der um `offset` parallel verschobenen Masslinie (Strecke a-b). */
@@ -131,43 +102,23 @@ function chainDraft(pts: Vec2[], cursor: Vec2 | null): ToolDraft {
}
/** Vorschau: alle Masslinien-Segmente bei gegebenem Offset (grob — Massstriche/Text rendert generatePlan). */
function offsetDraft(pts: Vec2[], offset: number, at: Vec2 | null): ToolDraft {
const preview: DraftShape[] = [];
for (let i = 0; i < pts.length - 1; i++) {
const a = pts[i], b = pts[i + 1];
if (Math.abs(offset) > EPS) {
const off = offsetPoints(a, b, offset);
preview.push({ kind: "line", a, b: off.a });
preview.push({ kind: "line", a: b, b: off.b });
preview.push({ kind: "line", a: off.a, b: off.b });
} else {
preview.push({ kind: "line", a, b });
}
}
const draft: ToolDraft = { preview, vertices: pts };
/**
* Vorschau der Lage (Kern): Hilfs- und Masslinien im Abstand des Cursors (ohne Cursor: Abstand 0) + HUD
* (Gesamtlänge · Abstand).
*/
function offsetDraft(ctx: CommandContext, pts: Vec2[], at: Vec2 | null): ToolDraft {
const pv = createPreview(ctx, { cmd: "dimension", phase: "offset", cursor: !!at }, at ? [...pts, at] : pts);
const draft: ToolDraft = { preview: pv.shapes, vertices: pts };
if (at) {
const total = pts.reduce((sum, p, i) => (i === 0 ? 0 : sum + dist(pts[i - 1], p)), 0);
const [offset, total] = pv.info;
draft.hud = { at, text: `Σ${total.toFixed(3)}m · Δ${offset.toFixed(3)}m` };
}
return draft;
}
/** Committet eine Kette: neu anhängen (editId null) ODER dasselbe Element ersetzen. */
function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): CoreOp[] {
const cleaned = pts.filter((pt, i) => i === 0 || dist(pts[i - 1], pt) >= EPS);
if (cleaned.length < 2) return []; // zu wenig gültige Punkte → nichts committen/ändern
if (editId) {
return patchItem(p, "drawings2d", editId, (d): Drawing2D => ({ ...d, geom: { shape: "dimension", pts: cleaned, offset } }));
}
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "dimension", pts: cleaned, offset },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Kette (Nullstrecken entfernt) mit Abstand bzw. Seite eines Punkts; `editId` ändert eine bestehende. */
const commitChain = (ctx: CommandContext, pts: Vec2[], offset: number | null, side: Vec2 | null, editId: string | null) =>
createMutation(ctx, { cmd: "dimension", pts, offset, side, editId });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null },
@@ -201,7 +152,7 @@ export const dimensionCommand: Command = {
}
if (input.id === "finish" && s.pts.length >= 2) {
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint };
return [ns, { draft: offsetDraft(s.pts, 0, null) }];
return [ns, { draft: offsetDraft(ctx, s.pts, null) }];
}
return [s, { draft: chainDraft(s.pts, s.cursor) }];
}
@@ -213,43 +164,42 @@ export const dimensionCommand: Command = {
// Erster Klick: bei selektierter Kette wird er EINSORTIERT (Ergänzen);
// sonst startet er eine neue Kette.
const existing = selectedChain(ctx);
const pts = existing ? insertIntoChain(existing.pts, pt) : [pt];
const pts = existing ? insertIntoChain(ctx, existing.pts, pt) : [pt];
const editId = existing ? existing.id : null;
const ns: DimNext = { phase: "next", pts, cursor: pt, editId, lastPoint: pt };
return [ns, { draft: chainDraft(pts, pt) }];
}
// Ab dem dritten Punkt (bzw. jedem weiteren Klick im Ergänzen-Modus):
// auf die durch Punkt 1/2 festgelegte Gerade projizieren/einsortieren.
const pts = s.pts.length >= 2 ? insertIntoChain(s.pts, pt) : [...s.pts, pt];
const pts = s.pts.length >= 2 ? insertIntoChain(ctx, s.pts, pt) : [...s.pts, pt];
const ns: DimNext = { phase: "next", pts, cursor: pt, editId: s.editId, lastPoint: pt };
return [ns, { draft: chainDraft(pts, pt) }];
}
// Offset-Schritt: Zahl = direkter Abstand, Punkt = Abstand zum Cursor.
let offset: number;
if (input.kind === "number") offset = input.value;
else if (input.kind === "point") offset = signedOffset(s.pts[0], s.pts[1], input.point);
else return [s, { draft: offsetDraft(s.pts, 0, null) }];
const pts = s.pts;
const editId = s.editId;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: opsMutation((p) => commitChain(p, pts, offset, editId, ctx)) },
];
if (input.kind !== "number" && input.kind !== "point") return [s, { draft: offsetDraft(ctx, s.pts, null) }];
const commit =
input.kind === "number"
? commitChain(ctx, s.pts, input.value, null, s.editId)
: commitChain(ctx, s.pts, null, input.point, s.editId);
return [{ phase: "start", lastPoint: null }, { draft: null, done: true, commit }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as DimState;
if (s.phase === "next") {
const cursor = s.pts.length >= 2 ? projectOnLine(s.pts[0], s.pts[1], point) : point;
// Ab zwei Punkten folgt der Cursor der Masslinie (Projektion im Kern).
let cursor = point;
if (s.pts.length >= 2) {
const [cx, cy] = createPreview(ctx, { cmd: "dimension", phase: "next", cursor: true }, [...s.pts, point]).info;
cursor = { x: cx, y: cy };
}
const ns: DimNext = { ...s, cursor };
return [ns, { draft: chainDraft(s.pts, cursor) }];
}
if (s.phase === "offset") {
// Offset relativ zum ERSTEN Segment (repräsentativ für die ganze Kette).
const off = signedOffset(s.pts[0], s.pts[1], point);
const ns: DimOffset = { ...s, cursor: point };
return [ns, { draft: offsetDraft(s.pts, off, point) }];
return [ns, { draft: offsetDraft(ctx, s.pts, point) }];
}
return [s, { draft: null }];
},
@@ -257,11 +207,11 @@ export const dimensionCommand: Command = {
// Enter/Space/Rechtsklick: im "next"-Schritt (≥2 Punkte) wie Doppelklick →
// Punktreihe abschliessen; im "offset"-Schritt bricht es ab (kein sinnvoller
// Default-Abstand ohne Zeigegeste).
onConfirm: (state): [CommandState, CommandResult] => {
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as DimState;
if (s.phase === "next" && s.pts.length >= 2) {
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint };
return [ns, { draft: offsetDraft(s.pts, 0, null) }];
return [ns, { draft: offsetDraft(ctx, s.pts, null) }];
}
return idle();
},
+27 -56
View File
@@ -19,9 +19,7 @@
// dafür keine Felder (separate, grössere Erweiterung, analog wie circle/arc
// getrennte Shapes sind statt einer gemeinsamen mit optionaler Spanne).
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { ellipsePts } from "../../core";
import { segmentHud } from "../../tools/types";
import type {
CmdOption,
Command,
@@ -29,13 +27,11 @@ import type {
CommandField,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, type CreatePreview } from "../createCore";
const EPS = 1e-6;
@@ -100,29 +96,27 @@ type EllipseState =
| EllipseAxisMajor
| EllipseAxisMinor;
/** Zentrum + Halbachsen aus zwei gegenüberliegenden Bounding-Box-Ecken. */
function ellipseFromCorners(p0: Vec2, p1: Vec2): { center: Vec2; rx: number; ry: number } {
return {
center: { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 },
rx: Math.abs(p1.x - p0.x) / 2,
ry: Math.abs(p1.y - p0.y) / 2,
};
}
/**
* Ellipse im Kern (`cmd_draw.rs`): box (`[p0, p1]` → Mitte, Halbachsen achsparallel) oder axis
* (`[Mitte, Hauptachse, Nebenachsen-Punkt]`); `info = [cx, cy, rx, ry]`.
*/
const ellipseAt = (ctx: CommandContext, method: EllipseMethod, pts: Vec2[]): CreatePreview =>
createPreview(ctx, { cmd: "ellipse", method }, pts);
// ── Vorschau ─────────────────────────────────────────────────────────────────
function ellipseDraft(center: Vec2, rx: number, ry: number, rotation: number, at: Vec2 | null): ToolDraft {
function ellipseDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft {
const [cx, cy, rx, ry] = pv.info;
const center = { x: cx, y: cy };
if (rx < EPS || ry < EPS) return { preview: [], vertices: [center] };
const preview: DraftShape[] = [{ kind: "poly", pts: ellipsePts(center, rx, ry, rotation), closed: true }];
const draft: ToolDraft = { preview, vertices: [center] };
const draft: ToolDraft = { preview: pv.shapes, vertices: [center] };
if (at) draft.hud = { at, text: `${(rx * 2).toFixed(3)}×${(ry * 2).toFixed(3)}m` };
return draft;
}
function boxDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft {
function boxDraft(ctx: CommandContext, p0: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return { preview: [], vertices: [p0] };
const { center, rx, ry } = ellipseFromCorners(p0, cursor);
return ellipseDraft(center, rx, ry, 0, cursor);
return ellipseDraft(ellipseAt(ctx, "box", [p0, cursor]), cursor);
}
function axisMajorDraft(center: Vec2, cursor: Vec2 | null): ToolDraft {
@@ -130,31 +124,16 @@ function axisMajorDraft(center: Vec2, cursor: Vec2 | null): ToolDraft {
return { preview: [{ kind: "line", a: center, b: cursor }], vertices: [center], hud: segmentHud(center, cursor) };
}
function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDraft {
const rx = dist(center, major);
if (!cursor) return ellipseDraft(center, rx, 0, angleOf(center, major), null);
const ry = Math.abs(perpDist(center, major, cursor));
return ellipseDraft(center, rx, ry, angleOf(center, major), cursor);
function axisMinorDraft(ctx: CommandContext, center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return ellipseDraft(ellipseAt(ctx, "axis", [center, major]), null);
return ellipseDraft(ellipseAt(ctx, "axis", [center, major, cursor]), cursor);
}
// ── Commit ───────────────────────────────────────────────────────────────────
function appendEllipse(center: Vec2,
rx: number,
ry: number,
rotation: number,
ctx: CommandContext,
): CoreOp[] {
if (rx < EPS || ry < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "ellipse", center, rx, ry, rotation },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Ellipse aus den Punkten (entartet → nichts). */
const appendEllipse = (ctx: CommandContext, method: EllipseMethod, pts: Vec2[]) =>
createMutation(ctx, { cmd: "ellipse", method, pts });
const idle = (method: EllipseMethod): [CommandState, CommandResult] => [
(method === "box" ? { phase: "corner1", method } : { phase: "center", method }) as EllipseState,
@@ -197,10 +176,9 @@ export const ellipseCommand: Command = {
if (s.method === "box") {
if (s.phase !== "corner2") {
const ns: EllipseBoxP2 = { phase: "corner2", method: "box", p0: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: boxDraft(pt, pt) }];
return [ns, { draft: boxDraft(ctx, pt, pt) }];
}
const { center, rx, ry } = ellipseFromCorners(s.p0, pt);
return [idle("box")[0], { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, 0, ctx)) }];
return [idle("box")[0], { draft: null, done: true, commit: appendEllipse(ctx, "box", [s.p0, pt]) }];
}
// axis
@@ -211,25 +189,18 @@ export const ellipseCommand: Command = {
if (s.phase === "major") {
if (dist(s.center, pt) < EPS) return [s, { draft: null }];
const ns: EllipseAxisMinor = { phase: "minor", method: "axis", center: s.center, major: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: axisMinorDraft(s.center, pt, null) }];
return [ns, { draft: axisMinorDraft(ctx, s.center, pt, null) }];
}
// phase "minor" → committen.
const { center, major } = s;
const rx = dist(center, major);
const ry = Math.abs(perpDist(center, major, pt));
const rotation = angleOf(center, major);
return [
idle("axis")[0],
{ draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, rotation, ctx)) },
];
return [idle("axis")[0], { draft: null, done: true, commit: appendEllipse(ctx, "axis", [s.center, s.major, pt]) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as EllipseState;
if (s.method === "box") {
if (s.phase !== "corner2") return [s, { draft: null }];
const ns: EllipseBoxP2 = { ...s, cursor: point };
return [ns, { draft: boxDraft(s.p0, point) }];
return [ns, { draft: boxDraft(ctx, s.p0, point) }];
}
if (s.phase === "major") {
const ns: EllipseAxisMajor = { ...s, cursor: point };
@@ -237,7 +208,7 @@ export const ellipseCommand: Command = {
}
if (s.phase === "minor") {
const ns: EllipseAxisMinor = { ...s, cursor: point };
return [ns, { draft: axisMinorDraft(s.center, s.major, point) }];
return [ns, { draft: axisMinorDraft(ctx, s.center, s.major, point) }];
}
return [s, { draft: null }];
},
+22 -94
View File
@@ -13,9 +13,6 @@
// (emitExtrudedSolids); dieser Befehl legt nur die Rohdaten (Punkte + Höhe +
// Verjüngung) im Projekt ab.
import type { Drawing2D, ExtrudedSolid } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { polylineEdges, pointSegmentDistance } from "../../core";
import type {
Command,
CommandContext,
@@ -25,108 +22,40 @@ import type {
Project,
Vec2,
} from "../types";
import { addItems, opsMutation, removeItems } from "../../core";
import type { CoreOp } from "../../core";
const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Profil-Wahl
import { createMutation, createQuery, xy } from "../createCore";
/** Persistente Extrusionshöhe über Aufrufe hinweg (Default: Geschosshöhe). */
let lastHeight = 2.6;
/** Persistente Verjüngung über Aufrufe hinweg (Default: Prisma, kein Kegel/Pyramide). */
let lastTaper = 0;
// ── Profil-Abstraktion: geschlossene polyline/rect/circle → Punktliste ─────
// ── Profil (Kern, `cmd_create.rs`): geschlossene polyline/rect/circle → Punktliste ─
/** Kreis-Tessellierung für Footprint/Auswahl/bbox (48-Eck, wie circle.ts). */
function circlePts(center: Vec2, r: number): Vec2[] {
const N = 48;
const pts: Vec2[] = [];
for (let i = 0; i < N; i++) {
const t = (i / N) * Math.PI * 2;
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
}
return pts;
}
/** Ein extrudierfähiges Profil: Tessellierung + optional die echte Kreis-Geometrie. */
/** Profil eines extrudierbaren 2D-Elements (Kreis: 48-Eck + Mittelpunkt/Radius). */
interface Profile {
pts: Vec2[];
circle?: { center: Vec2; r: number };
}
/** Wandelt ein extrudierfähiges (geschlossenes) Drawing2D in ein Profil. */
function geomToProfile(d: Drawing2D): Profile | null {
const g = d.geom;
if (g.shape === "polyline" && g.closed && g.pts.length >= 3) return { pts: g.pts };
if (g.shape === "rect") {
return { pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }] };
}
if (g.shape === "circle") {
return { pts: circlePts(g.center, g.r), circle: { center: g.center, r: g.r } };
}
return null;
type ProfileHit = { id: string } & Profile;
function profileQuery(project: Project, req: { q: string } & Record<string, unknown>): ProfileHit | null {
return createQuery<{ hit: (ProfileHit & { circle: Profile["circle"] | null }) | null }>(project, req).hit ?? null;
}
/** Genau ein passendes Drawing2D vorselektiert? Dann liefere sein Profil. */
function singleSelectedProfile(
project: Project,
sel: CommandSelection,
): ({ d: Drawing2D } & Profile) | null {
/** Genau EIN geeignetes Profil vorgewählt (sonst null). */
function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null {
if (!sel.drawingId || sel.wallIds.length > 0) return null;
const d = project.drawings2d.find((x) => x.id === sel.drawingId);
if (!d) return null;
const profile = geomToProfile(d);
return profile ? { d, ...profile } : null;
return profileQuery(project, { q: "profile", id: sel.drawingId });
}
/** Nächstes extrudierfähige Drawing2D zum Klickpunkt (innerhalb Toleranz). */
function pickProfileAt(
project: Project,
levelId: string,
pt: Vec2,
): ({ d: Drawing2D } & Profile) | null {
let best: ({ d: Drawing2D } & Profile) | null = null;
let bestD = HIT_TOL;
for (const d of project.drawings2d) {
if (d.levelId !== levelId) continue;
const profile = geomToProfile(d);
if (!profile) continue;
for (const [a, b] of polylineEdges(profile.pts, true)) {
const dd = pointSegmentDistance(pt, a, b);
if (dd < bestD) {
bestD = dd;
best = { d, ...profile };
}
}
}
return best;
}
/** Nächstes Profil der Ebene am Klickpunkt (Kanten-Abstand < 0.25 m). */
const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null =>
profileQuery(project, { q: "pickProfile", level: levelId, pt: xy(pt) });
/**
* Hängt den neuen Körper an UND entfernt das Quell-Profil (`sourceId`) aus
* `drawings2d` — die Polylinie/das Rechteck WIRD zur Extrusion, sie bleibt
* nicht als unabhängiges Duplikat liegen (sonst zwei Objekte am selben Ort,
* eines davon im Grundriss unsichtbar verwaist).
*/
function appendExtrudedSolid(
p: Project,
profile: Profile,
height: number,
taper: number,
sourceId: string,
ctx: CommandContext,
): CoreOp[] {
const solid: ExtrudedSolid = {
id: uniqueId("extrude"),
type: "extrudedSolid",
levelId: ctx.level.id,
points: profile.pts,
height,
circle: profile.circle,
...(taper > 0 ? { taper } : {}),
};
return [...removeItems(p, "drawings2d", [sourceId]), ...addItems("extrudedSolids", [solid])];
}
/** Commit (Kern): Quelle entfernen, Körper (Punkte + Höhe + Verjüngung) anlegen. */
const appendExtrudedSolid = (height: number, taper: number, sourceId: string, ctx: CommandContext) =>
createMutation(ctx, { cmd: "extrude", source: sourceId, height, taper });
// ── Zustand ───────────────────────────────────────────────────────────────────
@@ -168,14 +97,13 @@ const enterTaperPhase = (
];
const commitTaper = (
profile: Profile,
height: number,
taper: number,
sourceId: string,
ctx: CommandContext,
): [CommandState, CommandResult] => [
{ phase: "done", lastPoint: null } as ExDone,
{ draft: null, done: true, commit: opsMutation((p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx)) },
{ draft: null, done: true, commit: appendExtrudedSolid(height, taper, sourceId, ctx) },
];
export const extrudeCommand: Command = {
@@ -207,16 +135,16 @@ export const extrudeCommand: Command = {
const h = Math.abs(input.value);
if (h < 1e-6) return [s, { draft: null }];
lastHeight = h;
return enterTaperPhase(pre, h, pre.d.id);
return enterTaperPhase(pre, h, pre.id);
}
// Punkt im vorselektierten Fall: Höhen-Schritt betreten (HUD zeigt Default).
const ns: ExHeight = { phase: "height", profile: pre, sourceId: pre.d.id, cursor: null, lastPoint: null };
const ns: ExHeight = { phase: "height", profile: pre, sourceId: pre.id, cursor: null, lastPoint: null };
return [ns, { draft: null }];
}
if (input.kind === "point") {
const hit = pickProfileAt(ctx.project, ctx.level.id, input.point);
if (!hit) return [s, { draft: null }];
const ns: ExHeight = { phase: "height", profile: hit, sourceId: hit.d.id, cursor: null, lastPoint: null };
const ns: ExHeight = { phase: "height", profile: hit, sourceId: hit.id, cursor: null, lastPoint: null };
return [ns, { draft: null }];
}
return [s, { draft: null }];
@@ -237,7 +165,7 @@ export const extrudeCommand: Command = {
if (input.kind === "number") {
const t = Math.min(1, Math.max(0, input.value));
lastTaper = t;
return commitTaper(ts.profile, ts.height, t, ts.sourceId, ctx);
return commitTaper(ts.height, t, ts.sourceId, ctx);
}
return [ts, { draft: null }];
},
@@ -278,7 +206,7 @@ export const extrudeCommand: Command = {
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as ExState;
if (s.phase === "height") return enterTaperPhase(s.profile, lastHeight, s.sourceId);
if (s.phase === "taper") return commitTaper(s.profile, s.height, lastTaper, s.sourceId, ctx);
if (s.phase === "taper") return commitTaper(s.height, lastTaper, s.sourceId, ctx);
return finish();
},
onCancel: (): [CommandState, CommandResult] => finish(),
+11 -35
View File
@@ -5,21 +5,17 @@
// commit. „Art" (Option, zyklisch: OK fertig/UK fertig/OK roh/UK roh)
// wechselt VOR dem Tippen die Dreieck-Variante (Default OK fertig).
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
type KoteKind = "okFertig" | "ukFertig" | "okRoh" | "ukRoh";
const KIND_ORDER: KoteKind[] = ["okFertig", "ukFertig", "okRoh", "ukRoh"];
@@ -31,19 +27,6 @@ const KIND_LABEL: Record<KoteKind, TranslationKey> = {
ukRoh: "cmd.kote.kind.ukRoh",
};
const TRI_SIZE = 0.15; // Modell-Meter, Vorschau-Grösse (Rendering: KOTE_… in plan/drawings.rs)
const HALF_W = TRI_SIZE * 0.6;
/** Dreieck-Punkte für die Vorschau: `at` = Spitze; OK zeigt nach unten, UK nach oben. */
function triPts(at: Vec2, kind: KoteKind): Vec2[] {
const up = kind === "okFertig" || kind === "okRoh" ? 1 : -1; // Basis liegt in +up-Richtung von `at`
return [
at,
{ x: at.x - HALF_W, y: at.y + up * TRI_SIZE },
{ x: at.x + HALF_W, y: at.y + up * TRI_SIZE },
];
}
interface KotePoint extends CommandState {
phase: "point";
}
@@ -58,21 +41,14 @@ function kindOption(kind: KoteKind): CmdOption {
return { id: "kind", labelKey: KIND_LABEL[kind], value: kind };
}
function valueDraft(at: Vec2, kind: KoteKind): ToolDraft {
const preview: DraftShape[] = [{ kind: "poly", pts: triPts(at, kind), closed: true }];
return { preview, vertices: [at] };
/** Vorschau (Kern, `cmd_draw.rs`): Kote-Dreieck (Spitze am Punkt, Basis oben für OK, unten für UK). */
function valueDraft(ctx: CommandContext, at: Vec2, kind: KoteKind): ToolDraft {
return { preview: createPreview(ctx, { cmd: "kote", kind }, [at]).shapes, vertices: [at] };
}
function appendKote(at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "kote", at, value, kind, rotation: 0 },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Höhenkote am Punkt mit getipptem Wert. */
const appendKote = (at: Vec2, value: number, kind: KoteKind, ctx: CommandContext) =>
createMutation(ctx, { cmd: "kote", at, value, kind });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null },
@@ -92,17 +68,17 @@ export const koteCommand: Command = {
if (s.phase === "point") {
if (input.kind !== "point") return [s, { draft: null }];
const ns: KoteValue = { phase: "value", at: input.point, kind: "okFertig", lastPoint: input.point };
return [ns, { draft: valueDraft(input.point, "okFertig") }];
return [ns, { draft: valueDraft(ctx, input.point, "okFertig") }];
}
if (input.kind === "option" && input.id === "kind") {
const ns: KoteValue = { ...s, kind: nextKind(s.kind) };
return [ns, { draft: valueDraft(s.at, ns.kind) }];
return [ns, { draft: valueDraft(ctx, s.at, ns.kind) }];
}
if (input.kind !== "number") return [s, { draft: valueDraft(s.at, s.kind) }];
if (input.kind !== "number") return [s, { draft: valueDraft(ctx, s.at, s.kind) }];
const { at, kind } = s;
return [
{ phase: "point", lastPoint: null },
{ draft: null, done: true, commit: opsMutation(() => appendKote(at, input.value, kind, ctx)) },
{ draft: null, done: true, commit: appendKote(at, input.value, kind, ctx) },
];
},
+5 -28
View File
@@ -13,7 +13,6 @@
// Inline-Editor-Infrastruktur wie beim `text`-Befehl (kein neuer Shape,
// s. `Drawing2DGeom["text"].leaderTarget`/`.leaderBendPoints`).
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
CmdOption,
@@ -26,10 +25,8 @@ import type {
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
const DEFAULT_TEXT_HEIGHT_M = 0.25;
const MAX_BENDS = 4;
/** Persistente Knick-Anzahl über Aufrufe hinweg (wie `lastCount` bei Array). */
@@ -54,29 +51,9 @@ interface LeaderAnchor extends CommandState {
}
type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor;
function appendLeaderText(id: string,
at: Vec2,
target: Vec2,
bends: Vec2[],
ctx: CommandContext,
): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: {
shape: "text",
at,
text: "",
height: DEFAULT_TEXT_HEIGHT_M,
angle: 0,
leaderTarget: target,
...(bends.length > 0 ? { leaderBendPoints: bends } : {}),
},
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): leerer Text am Anker mit Hinweislinie zum Ziel (Knickpunkte, falls gesetzt). */
const appendLeaderText = (id: string, at: Vec2, target: Vec2, bends: Vec2[], ctx: CommandContext) =>
createMutation(ctx, { cmd: "leader", id, at, target, bends });
const idle = (): [CommandState, CommandResult] => [
{ phase: "target", lastPoint: null } as LeaderTarget,
@@ -142,7 +119,7 @@ export const leaderCommand: Command = {
{
draft: null,
done: true,
commit: opsMutation(() => appendLeaderText(id, pt, target, bends, ctx)),
commit: appendLeaderText(id, pt, target, bends, ctx),
focusDrawingId: id,
},
];
+5 -16
View File
@@ -24,8 +24,7 @@
// getippte Koordinaten — das ist die Kern-Vereinheitlichung gegenüber dem alten
// Tool. Live-Vorschau + HUD (Länge/Winkel) wie die bestehenden Tools.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -36,8 +35,7 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -82,17 +80,8 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
return draft;
}
/** Hängt eine 2D-Linie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */
function appendLine(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "line", a, b },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): 2D-Linie a→b; Farbe/Strich erbt die Kategorie. */
const appendLine = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "line", a, b });
export const lineCommand: Command = {
name: "line",
@@ -119,7 +108,7 @@ export const lineCommand: Command = {
}
const a = s.a;
const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt };
return [next, { draft: lineDraft(pt, pt), commit: opsMutation(() => appendLine(a, pt, ctx)) }];
return [next, { draft: lineDraft(pt, pt), commit: appendLine(a, pt, ctx) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
+22 -47
View File
@@ -1,7 +1,7 @@
// Multiline — zeichnet in EINER Geste eine gerade Basislinie PLUS N−1 dazu
// parallel versetzte Kopien (gleicher Abstand, gleiche Seite), z. B. für
// Doppellinien/Leitungstrassen/Abstandslinien. Baut auf derselben Offset-
// Geometrie wie der bestehende `offset`-Befehl auf (`offsetSegment`), erzeugt
// Geometrie wie der bestehende `offset`-Befehl auf (`kernel2d::offset_segment`, Kern `cmd_draw.rs`), erzeugt
// aber alle Kopien auf einmal statt einzeln nacheinander offsetten zu müssen.
// Schritte:
// 1) „Startpunkt:" → Punkt
@@ -15,10 +15,7 @@
// Anwendungsfall ab (Grenzlinie+Abstand, Leitungspaar, Randlinien), ohne die
// Komplexität einer mehrsegmentigen Variante.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { leftNormal, normalize, sub } from "../../model/geometry";
import { offsetSegment } from "../../core";
import { segmentHud } from "../../tools/types";
import type {
CmdOption,
Command,
@@ -30,8 +27,7 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -60,35 +56,18 @@ function endFromFields(a: Vec2, locks: Record<string, number>, cursor: Vec2 | nu
}
/** Vorzeichen (+links / −rechts) für einen Klickpunkt relativ zur Basislinie a→b. */
function sideSign(a: Vec2, b: Vec2, pt: Vec2): number {
const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
const u = normalize(sub(b, a));
const n = leftNormal(u);
const rel = sub(pt, mid);
return rel.x * n.x + rel.y * n.y >= 0 ? 1 : -1;
/**
* Vorschau im Kern (`cmd_draw.rs`): Original a→b + (count−1) parallele Kopien im Abstand `spacing` auf
* der Seite `sign` (fehlt sie, die Seite des Cursors). `side` = Seite des Cursors (+1 links, −1 rechts).
*/
function multilineAt(ctx: CommandContext, a: Vec2, b: Vec2, cursor: Vec2 | null, sign: number | null) {
const pv = createPreview(ctx, { cmd: "multiline", spacing: lastSpacing, count: lastCount, sign }, cursor ? [a, b, cursor] : [a, b]);
return { shapes: pv.shapes, side: pv.info[0] };
}
/** Die `count` parallelen Linien (Index 0 = Basislinie) als Punktpaare. */
function multilinePairs(a: Vec2, b: Vec2, spacing: number, sign: number, count: number): [Vec2, Vec2][] {
const out: [Vec2, Vec2][] = [[a, b]];
for (let k = 1; k < count; k++) {
out.push(offsetSegment(a, b, sign * spacing * k));
}
return out;
}
function appendMultiline(a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): CoreOp[] {
if (segLen(a, b) < EPS) return [];
const pairs = multilinePairs(a, b, spacing, sign, count);
const copies: Drawing2D[] = pairs.map(([pa, pb]) => ({
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "line", a: pa, b: pb },
}));
return addItems("drawings2d", copies);
}
/** Commit (Kern): Original + parallele Kopien als einzelne Linien (Null-Strecke → nichts). */
const appendMultiline = (a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext) =>
createMutation(ctx, { cmd: "multiline", a, b, spacing, sign, count });
const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.multiline.count" };
@@ -115,10 +94,8 @@ const idle = (): [CommandState, CommandResult] => [
];
/** Vorschau aller `lastCount` Linien bei gegebenem Abstand+Seite. */
function spacingDraft(a: Vec2, b: Vec2, spacing: number, sign: number, at: Vec2 | null): ToolDraft {
const pairs = multilinePairs(a, b, spacing, sign, lastCount);
const preview: DraftShape[] = pairs.map(([pa, pb]) => ({ kind: "line", a: pa, b: pb }));
const draft: ToolDraft = { preview, vertices: [a, b] };
function spacingDraft(ctx: CommandContext, a: Vec2, b: Vec2, spacing: number, sign: number | null, at: Vec2 | null): ToolDraft {
const draft: ToolDraft = { preview: multilineAt(ctx, a, b, at, sign).shapes, vertices: [a, b] };
if (at) draft.hud = { at, text: `${spacing.toFixed(2)} m × ${lastCount}` };
return draft;
}
@@ -150,15 +127,14 @@ export const multilineCommand: Command = {
if (input.kind !== "point") return [s, { draft: spacingDraftForEnd(s) }];
if (segLen(s.a, input.point) < EPS) return idle();
const next: MlSpacing = { phase: "spacing", a: s.a, b: input.point, cursor: input.point, lastPoint: input.point };
return [next, { draft: spacingDraft(next.a, next.b, lastSpacing, lastSign, input.point) }];
return [next, { draft: spacingDraft(ctx, next.a, next.b, lastSpacing, lastSign, input.point) }];
}
// phase === "spacing"
if (input.kind === "option") {
if (input.id === "count") {
lastCount = lastCount >= MAX_COUNT ? MIN_COUNT : lastCount + 1;
const sign = s.cursor ? sideSign(s.a, s.b, s.cursor) : lastSign;
return [s, { draft: spacingDraft(s.a, s.b, lastSpacing, sign, s.cursor) }];
return [s, { draft: spacingDraft(ctx, s.a, s.b, lastSpacing, s.cursor ? null : lastSign, s.cursor) }];
}
return [s, { draft: null }];
}
@@ -170,21 +146,21 @@ export const multilineCommand: Command = {
const { a, b } = s;
return [
idle()[0],
{ draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) },
{ draft: null, done: true, commit: appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx) },
];
}
if (input.kind === "point") {
lastSign = sideSign(s.a, s.b, input.point);
lastSign = multilineAt(ctx, s.a, s.b, input.point, null).side;
const { a, b } = s;
return [
idle()[0],
{ draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) },
{ draft: null, done: true, commit: appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx) },
];
}
return [s, { draft: null }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as MlState;
if (s.phase === "end") {
const next: MlEnd = { ...s, cursor: point };
@@ -194,9 +170,8 @@ export const multilineCommand: Command = {
return [next, { draft }];
}
if (s.phase === "spacing") {
const sign = sideSign(s.a, s.b, point);
const next: MlSpacing = { ...s, cursor: point };
return [next, { draft: spacingDraft(s.a, s.b, lastSpacing, sign, point) }];
return [next, { draft: spacingDraft(ctx, s.a, s.b, lastSpacing, null, point) }];
}
return [s, { draft: null }];
},
+54 -131
View File
@@ -12,8 +12,6 @@
//
// Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md).
import type { Opening } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -21,69 +19,25 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, createQuery, xy } from "../createCore";
/** Default-Ebene (Kategorie) für Öffnungen: „21" Türen/Fenster (Fallback: aktive). */
const OPENING_CATEGORY = "21";
/** Toleranz (Modell-Meter) für das Picken einer Host-Wand per Klick. */
const WALL_PICK_DIST = 0.6;
/** Default-Maße (Meter). */
const DEF_WINDOW = { width: 1.2, height: 1.2, sill: 0.9 };
const DEF_DOOR = { width: 0.9, height: 2.1, sill: 0 };
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
const dot = (a: Vec2, b: Vec2): number => a.x * b.x + 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 });
/** Existiert die Öffnungs-Kategorie („21")? Sonst Fallback auf die aktive. */
function openingCategory(ctx: CommandContext): string {
const flat: { code: string }[] = [];
const walk = (list: { code: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push({ code: c.code });
if (c.children) walk(c.children as { code: string; children?: unknown[] }[]);
}
};
walk(ctx.project.layers as { code: string; children?: unknown[] }[]);
return flat.some((c) => c.code === OPENING_CATEGORY)
? OPENING_CATEGORY
: ctx.defaultCategoryCode;
}
/** Auf die Wandachse projizierter Fußpunkt + Parameter t (0..len) + Distanz. */
function projectOntoWall(
wall: { start: Vec2; end: Vec2 },
p: Vec2,
): { t: number; foot: Vec2; dist: number } {
const ax = sub(wall.end, wall.start);
const len2 = dot(ax, ax) || 1e-9;
const raw = dot(sub(p, wall.start), ax) / len2; // 0..1
const t = Math.max(0, Math.min(1, raw));
const foot = add(wall.start, scale(ax, t));
const dist = Math.hypot(p.x - foot.x, p.y - foot.y);
return { t: t * Math.sqrt(len2), foot, dist };
}
/** Nächste Wand auf dem aktiven Geschoss zum Klickpunkt (innerhalb Toleranz). */
function pickWall(
ctx: CommandContext,
p: Vec2,
): { id: string; start: Vec2; end: Vec2 } | null {
let best: { id: string; start: Vec2; end: Vec2; d: number } | null = null;
for (const w of ctx.project.walls) {
if (w.floorId !== ctx.level.id) continue;
const { dist } = projectOntoWall(w, p);
if (dist <= WALL_PICK_DIST && (!best || dist < best.d)) {
best = { id: w.id, start: w.start, end: w.end, d: dist };
}
}
return best ? { id: best.id, start: best.start, end: best.end } : null;
/** Nächste Wand des Geschosses zum Klickpunkt (Kern): id, Achse und Abstand des Fusspunkts vom Anfang. */
function pickWall(ctx: CommandContext, p: Vec2): { id: string; start: Vec2; end: Vec2; t: number } | null {
const r = createQuery<{ hit: { id: string; start: [number, number]; end: [number, number]; t: number } | null }>(ctx.project, {
q: "pickWall",
level: ctx.level.id,
pt: xy(p),
});
if (!r.hit) return null;
const { id, start, end, t } = r.hit;
return { id, start: { x: start[0], y: start[1] }, end: { x: end[0], y: end[1] }, t };
}
/** Tab-Felder im Positionsschritt: Breite/Höhe/Brüstung (+ Winkel bei Tür). */
@@ -144,73 +98,44 @@ function initState(kind: "window" | "door" = "window"): OpIdle {
};
}
/** Vorschau: Lücken-Balken entlang der Wand + Positionsmarke. */
function posDraft(s: OpPos): ToolDraft {
const ax = sub(s.end, s.start);
const len = Math.hypot(ax.x, ax.y) || 1e-9;
const u = { x: ax.x / len, y: ax.y / len };
const n = { x: -u.y, y: u.x };
const from = Math.max(0, Math.min(s.posAlong, len));
const to = Math.max(from, Math.min(from + s.width, len));
const a = add(s.start, scale(u, from));
const b = add(s.start, scale(u, to));
const half = 0.15; // Vorschau-Balken quer zur Wand
const quad: Vec2[] = [
add(a, scale(n, half)),
add(b, scale(n, half)),
add(b, scale(n, -half)),
add(a, scale(n, -half)),
];
const preview: DraftShape[] = [{ kind: "poly", pts: quad, closed: true }];
// Symbol-Andeutung: Fenster = Mittellinie, Tür = Blatt-Linie in Schwenkrichtung.
if (s.kind === "window") {
preview.push({ kind: "line", a, b });
} else {
const swingSign = s.side === "left" ? 1 : -1;
const dirSign = s.dir === "in" ? 1 : -1;
const hinge = s.hinge === "start" ? a : b;
const leafEnd = add(hinge, scale(n, swingSign * dirSign * s.width));
preview.push({ kind: "line", a: hinge, b: leafEnd });
}
const draft: ToolDraft = { preview, vertices: [a, b] };
const mid = add(a, scale(u, (to - from) / 2));
/** Anfrage an den Kern (`cmd_create.rs`); `pos` = null → Position aus dem Cursor projiziert. */
const openingReq = (s: OpPos, pos: number | null) => ({
cmd: "opening",
wall: s.wallId,
start: xy(s.start),
end: xy(s.end),
kind: s.kind,
hinge: s.hinge,
side: s.side,
dir: s.dir,
width: s.width,
height: s.height,
sill: s.sill,
swingAngle: s.swingAngle,
pos,
});
/**
* Vorschau (Kern): Lücken-Balken entlang der Wand + Symbol (Fenster = Mittellinie, Tür = Blatt in
* Schwenkrichtung); `pos` = null projiziert `at` auf die Achse. Liefert dazu die Position.
*/
function posDraftAt(s: OpPos, ctx: CommandContext, pos: number | null, at: Vec2 | null): { draft: ToolDraft; pos: number } {
const pv = createPreview(ctx, openingReq(s, pos), at ? [at] : []);
const [p, from, ax, ay, bx, by, mx, my] = pv.info;
const draft: ToolDraft = { preview: pv.shapes, vertices: [{ x: ax, y: ay }, { x: bx, y: by }] };
draft.hud = {
at: s.cursor ?? mid,
at: s.cursor ?? { x: mx, y: my },
text: `${from.toFixed(2)} m · ${s.kind === "door" ? "Tür" : "Fenster"} ${(
s.width * 100
).toFixed(0)}×${(s.height * 100).toFixed(0)}`,
};
return draft;
return { draft, pos: p };
}
/** Hängt eine Öffnung ans Projekt (immutabel). */
function appendOpening(s: OpPos, ctx: CommandContext): CoreOp[] {
const len = Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y);
const width = Math.max(0.1, Math.min(s.width, len));
const position = Math.max(0, Math.min(s.posAlong, Math.max(0, len - width)));
// Standard-Bauteiltyp zuweisen (erster Tür-/Fenstertyp der Bibliothek), damit
// frisch platzierte Öffnungen SOFORT die volle Rahmen-/Laibungs-Darstellung
// (2D + 3D) bekommen — ohne Typ blieben sie ein blosses Loch mit flacher
// Scheibe. Fehlt eine Bibliothek, bleibt es beim Inline-Verhalten (kein Typ).
const typeId =
s.kind === "door" ? ctx.project.doorTypes?.[0]?.id : ctx.project.windowTypes?.[0]?.id;
const opening: Opening = {
id: uniqueId("O"),
type: "opening",
hostWallId: s.wallId,
categoryCode: openingCategory(ctx),
kind: s.kind,
position,
width,
height: s.height,
sillHeight: s.kind === "door" ? 0 : s.sill,
...(typeId ? { typeId } : {}),
...(s.kind === "door"
? { hinge: s.hinge, swing: s.side, openingDir: s.dir, swingAngle: s.swingAngle }
: {}),
};
return addItems("openings", [opening]);
}
const posDraft = (s: OpPos, ctx: CommandContext): ToolDraft => posDraftAt(s, ctx, s.posAlong, null).draft;
/** Commit (Kern): Öffnung in die Host-Wand, Breite/Position auf die Wand geklemmt, Standard-Typ der Bibliothek. */
const appendOpening = (s: OpPos, ctx: CommandContext) => createMutation(ctx, openingReq(s, s.posAlong));
const idle = (from?: OpState): [CommandState, CommandResult] => [
initState(from?.kind ?? "window"),
@@ -261,27 +186,26 @@ export const openingCommand: Command = {
} else if (input.id === "dir") {
next.dir = s.dir === "in" ? "out" : "in";
}
return [next, { draft: next.phase === "pos" ? posDraft(next as OpPos) : null }];
return [next, { draft: next.phase === "pos" ? posDraft(next as OpPos, ctx) : null }];
}
if (input.kind === "number") {
// Im Positionsschritt: getippte Zahl = Abstand vom Wandanfang (Meter).
if (s.phase === "pos") {
const ns: OpPos = { ...s, posAlong: input.value };
return [ns, { draft: posDraft(ns) }];
return [ns, { draft: posDraft(ns, ctx) }];
}
return [s, { draft: null }];
}
if (input.kind !== "point") {
return [s, { draft: s.phase === "pos" ? posDraft(s as OpPos) : null }];
return [s, { draft: s.phase === "pos" ? posDraft(s as OpPos, ctx) : null }];
}
const pt = input.point;
if (s.phase === "wall") {
const w = pickWall(ctx, pt);
if (!w) return [s, { draft: null }]; // kein Treffer: Schritt wiederholen
const proj = projectOntoWall(w, pt);
const ns: OpPos = {
phase: "pos",
lastPoint: pt,
@@ -289,7 +213,7 @@ export const openingCommand: Command = {
start: w.start,
end: w.end,
cursor: pt,
posAlong: proj.t,
posAlong: w.t,
kind: s.kind,
hinge: s.hinge,
side: s.side,
@@ -299,24 +223,23 @@ export const openingCommand: Command = {
sill: s.sill,
swingAngle: s.swingAngle,
};
return [ns, { draft: posDraft(ns) }];
return [ns, { draft: posDraft(ns, ctx) }];
}
// Positionsschritt: Klick projiziert auf die Achse → committen.
const proj = projectOntoWall(s, pt);
const ns: OpPos = { ...s, posAlong: proj.t, cursor: pt };
const ns: OpPos = { ...s, posAlong: posDraftAt(s, ctx, null, pt).pos, cursor: pt };
return [
idle(s)[0],
{ draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) },
{ draft: null, done: true, commit: appendOpening(ns, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as OpState;
if (s.phase !== "pos") return [s, { draft: null }];
const proj = projectOntoWall(s, point);
const ns: OpPos = { ...s, posAlong: proj.t, cursor: point };
return [ns, { draft: posDraft(ns) }];
const at = posDraftAt({ ...s, cursor: point }, ctx, null, point);
const ns: OpPos = { ...s, posAlong: at.pos, cursor: point };
return [ns, { draft: at.draft }];
},
onConfirm: (state, ctx): [CommandState, CommandResult] => {
@@ -325,7 +248,7 @@ export const openingCommand: Command = {
const ns = s;
return [
idle(s)[0],
{ draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) },
{ draft: null, done: true, commit: appendOpening(ns, ctx) },
];
}
return idle(s);
+8 -32
View File
@@ -3,53 +3,29 @@
// Kreuz-in-Kreis-Symbol an genau dieser Stelle, keine weiteren Felder
// (analog `detailref.ts`, aber ohne Label/Blattverknüpfung).
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (plan/drawings.rs)
const PREVIEW_CROSS = 0.12;
interface PointMarkerIdle extends CommandState {
phase: "point";
}
type PointMarkerState = PointMarkerIdle;
function pointDraft(at: Vec2): ToolDraft {
const N = 32;
const pts: Vec2[] = [];
for (let i = 0; i < N; i++) {
const t = (i / N) * Math.PI * 2;
pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) });
}
const preview: DraftShape[] = [
{ kind: "poly", pts, closed: true },
{ kind: "line", a: { x: at.x - PREVIEW_CROSS, y: at.y }, b: { x: at.x + PREVIEW_CROSS, y: at.y } },
{ kind: "line", a: { x: at.x, y: at.y - PREVIEW_CROSS }, b: { x: at.x, y: at.y + PREVIEW_CROSS } },
];
return { preview, vertices: [at] };
/** Vorschau (Kern, `cmd_draw.rs`): Kreis (r = 0.08 m) mit Kreuz am Cursor. */
function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft {
return { preview: createPreview(ctx, { cmd: "pointmarker" }, [at]).shapes, vertices: [at] };
}
function appendPointMarker(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "pointmarker", at },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Punktmarker am Punkt. */
const appendPointMarker = (at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "pointmarker", at });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null } as PointMarkerIdle,
@@ -69,11 +45,11 @@ export const pointmarkerCommand: Command = {
if (input.kind !== "point") return [s, { draft: null }];
return [
{ phase: "point", lastPoint: null } as PointMarkerIdle,
{ draft: null, done: true, commit: opsMutation(() => appendPointMarker(input.point, ctx)) },
{ draft: null, done: true, commit: appendPointMarker(input.point, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }],
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }],
onConfirm: (): [CommandState, CommandResult] => idle(),
onCancel: (): [CommandState, CommandResult] => idle(),
};
+33 -89
View File
@@ -25,8 +25,7 @@
// 2) „Zweiter Kantenpunkt:" → Punkt → commit.
// Ecken-Zahl/Modus/Konstruktion per Option.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
CmdOption,
Command,
@@ -34,13 +33,11 @@ import type {
CommandField,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const MIN_SIDES = 3;
@@ -95,83 +92,34 @@ const MODE_OPTION: CmdOption = { id: "mode", labelKey: "cmd.polygon.mode" };
* eingegebene Radius das Apothema (Zentrum→Kantenmitte) — der tatsächliche
* Eckpunkt-Radius ist grösser, `apothem / cos(π/n)`.
*/
function vertexRadius(r: number, sides: number, mode: PolygonMode): number {
return mode === "circumscribed" ? r / Math.cos(Math.PI / sides) : r;
}
/** Eckpunkte des regelmässigen Vielecks (erste Ecke Richtung `dir`), `r` = eingegebener Radius (Modus-abhängig). */
function polygonPts(center: Vec2, r: number, sides: number, mode: PolygonMode, dir: Vec2 | null): Vec2[] {
const rv = vertexRadius(r, sides, mode);
const t0 = dir && dist(center, dir) > EPS ? Math.atan2(dir.y - center.y, dir.x - center.x) : 0;
const pts: Vec2[] = [];
for (let i = 0; i < sides; i++) {
const t = t0 + (i / sides) * Math.PI * 2;
pts.push({ x: center.x + rv * Math.cos(t), y: center.y + rv * Math.sin(t) });
}
return pts;
}
/** Optionen des Vielecks für den Kern (`cmd_draw.rs`). */
const polyReq = (method: PolygonMethod) => ({ cmd: "polygon", method, sides: lastSides, mode: lastMode });
/**
* Eckpunkte des regelmässigen Vielecks aus einer EINZELNEN Kante `a→b`: die
* Kantenlänge/Richtung legt die Grösse/Drehung eindeutig fest. Läuft von `b`
* aus nach LINKS abbiegend weiter (Aussenwinkel 2π/n je Ecke) — ein
* konvexes, CCW aufgebautes Vieleck auf der linken Seite von a→b.
* Vorschau (Kern): Vieleck um `center` durch den Cursor (Radius = Abstand, erste Ecke in Cursor-Richtung;
* umschrieben: Eckradius r / cos(π/n)) + HUD (Radius × Ecken).
*/
function polygonFromEdge(a: Vec2, b: Vec2, sides: number): Vec2[] {
const edgeLen = dist(a, b);
const ext = (2 * Math.PI) / sides;
const pts: Vec2[] = [a, b];
let cur = b;
let dir = Math.atan2(b.y - a.y, b.x - a.x);
for (let i = 2; i < sides; i++) {
dir += ext;
const next: Vec2 = { x: cur.x + edgeLen * Math.cos(dir), y: cur.y + edgeLen * Math.sin(dir) };
pts.push(next);
cur = next;
}
return pts;
}
function polygonDraft(center: Vec2, r: number, dir: Vec2 | null, at: Vec2 | null): ToolDraft {
function polygonDraft(ctx: CommandContext, center: Vec2, cursor: Vec2 | null): ToolDraft {
const pv = createPreview(ctx, polyReq("center"), cursor ? [center, cursor] : [center]);
const r = pv.info[0];
if (r < EPS) return { preview: [], vertices: [center] };
const preview: DraftShape[] = [
{ kind: "poly", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true },
];
const draft: ToolDraft = { preview, vertices: [center] };
if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m × ${lastSides}` };
const draft: ToolDraft = { preview: pv.shapes, vertices: [center] };
if (cursor) draft.hud = { at: cursor, text: `R: ${r.toFixed(3)}m × ${lastSides}` };
return draft;
}
/** Vorschau der Kanten-Konstruktion — zeigt das VOLLE Vieleck, sobald die Kante eine Länge hat. */
function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
/** Vorschau (Kern) des Vielecks über der Kante a→Cursor (gegen den Uhrzeigersinn). */
function edgeDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor || dist(a, cursor) < EPS) return { preview: [{ kind: "line", a, b: a }], vertices: [a] };
const pts = polygonFromEdge(a, cursor, lastSides);
return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) };
return { preview: createPreview(ctx, polyReq("edge"), [a, cursor]).shapes, vertices: [a], hud: segmentHud(a, cursor) };
}
function appendPolygon(center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Vieleck um `center`; Radius getippt oder Abstand zu `dir` (entartet → nichts). */
const appendPolygon = (center: Vec2, r: number | null, dir: Vec2 | null, ctx: CommandContext) =>
createMutation(ctx, { ...polyReq("center"), center, r, dir });
function appendPolygonFromEdge(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
if (dist(a, b) < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Vieleck über der Kante a→b. */
const appendPolygonFromEdge = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { ...polyReq("edge"), a, b });
const idle = (): [CommandState, CommandResult] => [
{ phase: "p1", method: lastMethod, lastPoint: null } as PolyP1,
@@ -218,16 +166,14 @@ export const polygonCommand: Command = {
if (input.id === "sides") {
lastSides = lastSides >= MAX_SIDES ? MIN_SIDES : lastSides + 1;
if (s.phase === "radius") {
const r = s.cursor ? dist(s.center, s.cursor) : 0;
return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }];
return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }];
}
if (s.phase === "edge2") return [s, { draft: edgeDraft(s.a, s.cursor) }];
if (s.phase === "edge2") return [s, { draft: edgeDraft(ctx, s.a, s.cursor) }];
return [s, { draft: null }];
}
if (input.id === "mode" && s.phase === "radius") {
lastMode = nextMode(lastMode);
const r = s.cursor ? dist(s.center, s.cursor) : 0;
return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }];
return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }];
}
return [s, { draft: null }];
}
@@ -236,51 +182,49 @@ export const polygonCommand: Command = {
if (input.kind !== "point") return [s, { draft: null }];
if (s.method === "edge") {
const ns: PolyEdge2 = { phase: "edge2", method: "edge", a: input.point, cursor: input.point, lastPoint: input.point };
return [ns, { draft: edgeDraft(input.point, input.point) }];
return [ns, { draft: edgeDraft(ctx, input.point, input.point) }];
}
const ns: PolyRadius = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point };
return [ns, { draft: polygonDraft(input.point, 0, null, null) }];
return [ns, { draft: polygonDraft(ctx, input.point, null) }];
}
if (s.phase === "edge2") {
if (input.kind !== "point" || dist(s.a, input.point) < EPS) {
return [s, { draft: edgeDraft(s.a, s.cursor) }];
return [s, { draft: edgeDraft(ctx, s.a, s.cursor) }];
}
const a = s.a;
const b = input.point;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendPolygonFromEdge(a, b, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendPolygonFromEdge(a, b, ctx) }];
}
// phase "radius"
let r: number;
let r: number | null;
let dir: Vec2 | null;
if (input.kind === "number") {
r = input.value;
dir = s.cursor;
} else if (input.kind === "point") {
r = dist(s.center, input.point);
r = null;
dir = input.point;
} else {
const rr = s.cursor ? dist(s.center, s.cursor) : 0;
return [s, { draft: polygonDraft(s.center, rr, s.cursor, s.cursor) }];
return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }];
}
const center = s.center;
return [
idle()[0],
{ draft: null, done: true, commit: opsMutation(() => appendPolygon(center, r, dir, ctx)) },
{ draft: null, done: true, commit: appendPolygon(center, r, dir, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as PolyState;
if (s.phase === "radius") {
const r = dist(s.center, point);
const ns: PolyRadius = { ...s, cursor: point };
return [ns, { draft: polygonDraft(s.center, r, point, point) }];
return [ns, { draft: polygonDraft(ctx, s.center, point) }];
}
if (s.phase === "edge2") {
const ns: PolyEdge2 = { ...s, cursor: point };
return [ns, { draft: edgeDraft(s.a, point) }];
return [ns, { draft: edgeDraft(ctx, s.a, point) }];
}
return [s, { draft: null }];
},
@@ -12,6 +12,7 @@ import { bulgeArc } from "../../geometry/bulge";
import type { CommandContext, CommandState, Project, Vec2 } from "../types";
const ctx = {
project: sampleProject,
level: sampleProject.drawingLevels[0],
defaultCategoryCode: sampleProject.layers[0].code,
} as CommandContext;
+51 -121
View File
@@ -18,9 +18,7 @@
// sich dann zwangsläufig aus dem Vorgänger. Das erste Segment hat keine
// Tangenten-Referenz und bleibt gerade.
import type { Drawing2D } from "../../model/types";
import { bulgePolylinePoints, bulgeThroughPoint } from "../../core";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -28,12 +26,10 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -58,43 +54,11 @@ function polyNextFromFields(last: Vec2, locks: Record<string, number>, cursor: V
}
/**
* Bulge eines Bogens, der in `a` TANGENTIAL an die Richtung `dir` anschliesst
* und in `b` endet. Nach dem Sehnen-Tangenten-Satz ist der Winkel θ VON DER
* SEHNE ZUR TANGENTE die halbe Zentriwinkel-Spanne (θ = Δ/2), und
* `bulge = tan(Δ/4)` — also `tan(θ/2)`. Die Richtung der Winkelmessung ist
* wesentlich: von der Sehne zur Tangente, passend zur Vorzeichenkonvention
* von `bulge` (positiv = Ausbauchung LINKS von a→b). Andersherum gemessen
* läge die Tangente am falschen Bogenende. Ohne Richtung (erstes Segment)
* oder bei entarteter Sehne bleibt es gerade (0).
* Art eines Segments (Index = Segment `points[i] → points[i+1]`): gerade (`0`), Bogen tangential an den
* Vorgänger (`1`) oder Drei-Punkt-Bogen durch einen Durchgangspunkt. Die Bulges (`tan(Δ/4)`, tangential
* aus der Endrichtung des Vorgängers) rechnet der Kern (`cmd_draw.rs`) der Reihe nach.
*/
function tangentBulge(a: Vec2, b: Vec2, dir: Vec2 | null): number {
if (!dir) return 0;
const cx = b.x - a.x, cy = b.y - a.y;
const len = Math.hypot(cx, cy);
const dl = Math.hypot(dir.x, dir.y);
if (len < EPS || dl < EPS) return 0;
const ux = cx / len, uy = cy / len;
const dx = dir.x / dl, dy = dir.y / dl;
const theta = Math.atan2(ux * dy - uy * dx, ux * dx + uy * dy);
return Math.tan(theta / 2);
}
/** Richtung, in der das zuletzt gelegte Segment endet (Tangente für den nächsten Bogen). */
function lastDirection(points: Vec2[], bulges: number[]): Vec2 | null {
const n = points.length;
if (n < 2) return null;
const a = points[n - 2];
const b = points[n - 1];
const bulge = bulges[n - 2] ?? 0;
const chord = { x: b.x - a.x, y: b.y - a.y };
if (Math.abs(bulge) < EPS) return chord;
// Austritts-Tangente eines Bogens: die Sehne um den halben Zentriwinkel
// gedreht (Δ/2 = 2·atan(bulge)) — am ENDE mit umgekehrtem Vorzeichen wie am
// Anfang (der Bogen ist symmetrisch zur Sehne).
const ang = -2 * Math.atan(bulge);
const c = Math.cos(ang), si = Math.sin(ang);
return { x: chord.x * c - chord.y * si, y: chord.x * si + chord.y * c };
}
type Seg = 0 | 1 | Vec2;
interface PolyIdle extends CommandState {
phase: "start";
@@ -108,8 +72,8 @@ interface PolyIdle extends CommandState {
interface PolyDrawing extends CommandState {
phase: "next";
points: Vec2[];
/** Bulge je Segment (Index = Segment `points[i] → points[i+1]`), 0 = gerade. */
bulges: number[];
/** Art je Segment (s. {@link Seg}). */
segs: Seg[];
cursor: Vec2 | null;
/** Soll der committete Zug als Ring (geschlossen) gelten? Default: offen. */
closed: boolean;
@@ -124,21 +88,12 @@ interface PolyDrawing extends CommandState {
type PolyState = PolyIdle | PolyDrawing;
/**
* Bulge des SCHLUSS-Segments (letzter Punkt → Start), wenn ein Ring ohne
* weiteren Klick geschlossen wird (Option „close" bzw. Ring-Toggle + Enter).
* Ein bereits gesetzter Drei-Punkt-Durchgangspunkt gilt dann für DIESES
* Segment; sonst tangential an den Vorgänger, wie bei jedem anderen Bogen.
* Ohne diesen Eintrag liest der Plan (`plan/drawings.rs`) dort einen fehlenden Bulge (Index
* ausserhalb des Arrays) und zeichnet die Schlusskante immer gerade.
* Art des SCHLUSS-Segments (letzter Punkt → Start), wenn ein Ring ohne weiteren Klick geschlossen wird
* (Option „close" bzw. Ring-Toggle + Enter): ein bereits gesetzter Drei-Punkt-Durchgangspunkt gilt dann
* für DIESES Segment; sonst im Bogen-Modus tangential an den Vorgänger. Ohne diesen Eintrag läse der
* Plan dort einen fehlenden Bulge und zeichnete die Schlusskante immer gerade.
*/
function closingBulge(s: PolyDrawing): number {
if (!s.arc) return 0;
const prev = s.points[s.points.length - 1];
const start = s.points[0];
return s.pendingThrough
? bulgeThroughPoint(prev, s.pendingThrough, start)
: tangentBulge(prev, start, lastDirection(s.points, s.bulges));
}
const closingSeg = (s: PolyDrawing): Seg => (!s.arc ? 0 : (s.pendingThrough ?? 1));
/** Sofort-schließen-Aktion (nur ≥3 Punkte): committet als Ring und beendet. */
const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" };
@@ -169,8 +124,9 @@ const tangentOption = (on: boolean): CmdOption => ({
* exakte `bulge` (s. `appendPolyline`).
*/
function polyDraft(
ctx: CommandContext,
points: Vec2[],
bulges: number[],
segs: Seg[],
cursor: Vec2 | null,
closed = false,
arcMode = false,
@@ -178,48 +134,26 @@ function polyDraft(
pendingThrough: Vec2 | null = null,
): ToolDraft {
const all = cursor ? [...points, cursor] : points;
const req = { cmd: "polyline", segs, closed, arc: arcMode, tangent, through: pendingThrough, cursor: !!cursor };
const draft: ToolDraft = { preview: createPreview(ctx, req, all).shapes, vertices: points };
const last = points[points.length - 1];
// Vorschau-Bulge des Gummiband-Segments: Drei-Punkt (sobald der
// Durchgangspunkt gesetzt ist), sonst tangential — oder gerade.
const previewBulge =
!cursor || !last || !arcMode
? 0
: pendingThrough
? bulgeThroughPoint(last, pendingThrough, cursor)
: tangent
? tangentBulge(last, cursor, lastDirection(points, bulges))
: 0;
const allBulges = cursor ? [...bulges, previewBulge] : bulges;
// Bogen-Segmente für die Vorschau ausrollen.
const pts = bulgePolylinePoints(all, allBulges, false);
// Ring nur ab 3 Punkten zeigen; darunter bleibt die Vorschau offen.
const showClosed = closed && all.length >= 3;
const preview: DraftShape[] = [{ kind: "poly", pts, closed: showClosed }];
const draft: ToolDraft = { preview, vertices: points };
if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor);
return draft;
}
/** Hängt eine 2D-Polylinie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */
function appendPolyline(pts: Vec2[],
bulges: number[],
/**
* Commit (Kern): 2D-Polylinie aus Punkten und Segment-Arten; `closing` = Art des Schluss-Segments
* (geschlossen), `closingEnd` = sein Endpunkt, falls ein Klick nahe dem Start schloss. Farbe/Strich erbt
* die Kategorie.
*/
const appendPolyline = (
pts: Vec2[],
segs: Seg[],
closing: Seg | null,
closed: boolean,
ctx: CommandContext,
): CoreOp[] {
// `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner
// Geradenzug bleibt damit bitgleich zu vorher (additives Feld).
const hasArc = bulges.some((b) => Math.abs(b) > EPS);
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: hasArc
? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) }
: { shape: "polyline", pts, closed },
};
return addItems("drawings2d", [d]);
}
closingEnd: Vec2 | null = null,
) => createMutation(ctx, { cmd: "polyline", pts, segs, closing, closingEnd, closed });
/** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */
const idle = (closed = false, arc = false, tangent = false): [CommandState, CommandResult] => [
@@ -273,7 +207,7 @@ export const polylineCommand: Command = {
{
draft:
s.phase === "next"
? polyDraft(s.points, s.bulges, s.cursor, ns.closed, ns.arc, ns.tangent, null)
? polyDraft(ctx, s.points, s.segs, s.cursor, ns.closed, ns.arc, ns.tangent, null)
: null,
},
];
@@ -283,10 +217,10 @@ export const polylineCommand: Command = {
// Wartet ein Durchgangspunkt, nimmt „Zurück" zuerst diesen zurück.
if (s.pendingThrough) {
const ns: PolyDrawing = { ...s, pendingThrough: null };
return [ns, { draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, null) }];
return [ns, { draft: polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, null) }];
}
const pts = s.points.slice(0, -1);
const bulges = s.bulges.slice(0, Math.max(0, pts.length - 1));
const segs = s.segs.slice(0, Math.max(0, pts.length - 1));
if (pts.length === 0)
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
@@ -295,7 +229,7 @@ export const polylineCommand: Command = {
const ns: PolyDrawing = {
phase: "next",
points: pts,
bulges,
segs,
cursor: s.cursor,
lastPoint: pts[pts.length - 1],
closed: s.closed,
@@ -303,20 +237,21 @@ export const polylineCommand: Command = {
tangent: s.tangent,
pendingThrough: null,
};
return [ns, { draft: polyDraft(pts, bulges, s.cursor, s.closed, s.arc, s.tangent, null) }];
return [ns, { draft: polyDraft(ctx, pts, segs, s.cursor, s.closed, s.arc, s.tangent, null) }];
}
// Sofort schließen: committet als Ring (unabhängig vom Toggle-Zustand).
if (input.id === "close" && s.points.length >= 3) {
const pts = s.points;
const bl = [...s.bulges, closingBulge(s)];
const segs = s.segs;
const closing = closingSeg(s);
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) },
{ draft: null, done: true, commit: appendPolyline(pts, segs, closing, true, ctx) },
];
}
return [
s,
{ draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) },
{ draft: polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) },
];
}
@@ -326,7 +261,7 @@ export const polylineCommand: Command = {
{
draft:
s.phase === "next"
? polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough)
? polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough)
: null,
},
];
@@ -336,7 +271,7 @@ export const polylineCommand: Command = {
const ns: PolyDrawing = {
phase: "next",
points: [pt],
bulges: [],
segs: [],
cursor: pt,
lastPoint: pt,
closed: s.closed,
@@ -344,22 +279,17 @@ export const polylineCommand: Command = {
tangent: s.tangent,
pendingThrough: null,
};
return [ns, { draft: polyDraft([pt], [], pt, s.closed, s.arc, s.tangent, null) }];
return [ns, { draft: polyDraft(ctx, [pt], [], pt, s.closed, s.arc, s.tangent, null) }];
}
// Drei-Punkt-Bogen: der ERSTE Klick setzt nur den Durchgangspunkt; das
// Segment entsteht erst mit dem zweiten Klick (Endpunkt).
if (s.arc && !s.tangent && !s.pendingThrough) {
const ns: PolyDrawing = { ...s, pendingThrough: pt, cursor: pt };
return [ns, { draft: polyDraft(s.points, s.bulges, pt, s.closed, s.arc, s.tangent, pt) }];
return [ns, { draft: polyDraft(ctx, s.points, s.segs, pt, s.closed, s.arc, s.tangent, pt) }];
}
// Bulge des neuen Segments: Drei-Punkt (über den gesetzten Durchgangspunkt)
// oder tangential an den Vorgänger.
const prev = s.points[s.points.length - 1];
const newBulge = !s.arc
? 0
: s.pendingThrough
? bulgeThroughPoint(prev, s.pendingThrough, pt)
: tangentBulge(prev, pt, lastDirection(s.points, s.bulges));
const newSeg: Seg = !s.arc ? 0 : (s.pendingThrough ?? 1);
// Klick nahe Startpunkt → schließen (committet als Ring). `newBulge` ist
// bereits die korrekte Krümmung des Schluss-Segments (prev→pt, genau wie
// die Vorschau in `polyDraft` sie zeigt) — MUSS mit angehängt werden,
@@ -367,18 +297,18 @@ export const polylineCommand: Command = {
// schliesst immer gerade, obwohl die Vorschau eben noch den Bogen zeigte.
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
const bl = [...s.bulges, newBulge];
const segs = s.segs;
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) },
{ draft: null, done: true, commit: appendPolyline(pts, segs, newSeg, true, ctx, pt) },
];
}
const points = [...s.points, pt];
const bulges = [...s.bulges, newBulge];
const segs = [...s.segs, newSeg];
const ns: PolyDrawing = {
phase: "next",
points,
bulges,
segs,
cursor: pt,
lastPoint: pt,
closed: s.closed,
@@ -386,16 +316,16 @@ export const polylineCommand: Command = {
tangent: s.tangent,
pendingThrough: null,
};
return [ns, { draft: polyDraft(points, bulges, pt, s.closed, s.arc, s.tangent, null) }];
return [ns, { draft: polyDraft(ctx, points, segs, pt, s.closed, s.arc, s.tangent, null) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as PolyState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: PolyDrawing = { ...s, cursor: point };
return [
ns,
{ draft: polyDraft(s.points, s.bulges, point, s.closed, s.arc, s.tangent, s.pendingThrough) },
{ draft: polyDraft(ctx, s.points, s.segs, point, s.closed, s.arc, s.tangent, s.pendingThrough) },
];
},
@@ -407,10 +337,10 @@ export const polylineCommand: Command = {
if (s.phase === "next" && s.points.length >= 2) {
const pts = s.points;
const close = s.closed && pts.length >= 3;
const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges;
const closing = close ? closingSeg(s) : null;
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, close, ctx)) },
{ draft: null, done: true, commit: appendPolyline(pts, s.segs, closing, close, ctx) },
];
}
return idle(s.closed, s.arc, s.tangent);
+12 -32
View File
@@ -5,8 +5,7 @@
// 1) „Anker:" → Punkt
// 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -17,12 +16,10 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const RAY_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
(Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
@@ -51,33 +48,16 @@ interface RayDrawing extends CommandState {
type RayState = RayIdle | RayDrawing;
/** Vorschau: kurzes Segment PLUS Verlängerung NUR über den Cursor hinaus (Anker bleibt fest). */
function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
const preview: DraftShape[] = [];
if (cursor && segLen(a, cursor) >= EPS) {
const len = segLen(a, cursor);
const ux = (cursor.x - a.x) / len;
const uy = (cursor.y - a.y) / len;
preview.push({
kind: "line",
a,
b: { x: cursor.x + ux * RAY_PREVIEW_EXT_M, y: cursor.y + uy * RAY_PREVIEW_EXT_M },
});
}
function rayDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
// Vorschau (Kern): einseitig um 30 m verlängert — die echte Länge kommt aus der Plan-Ableitung.
const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "ray" }, [a, cursor]).shapes : [];
const draft: ToolDraft = { preview, vertices: [a] };
if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor);
return draft;
}
function appendRay(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "ray", a, b },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): Strahl durch a, b. */
const appendRay = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "ray", a, b });
export const rayCommand: Command = {
name: "ray",
@@ -89,11 +69,11 @@ export const rayCommand: Command = {
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as RayState;
if (input.kind !== "point") return [s, { draft: s.phase === "end" ? rayDraft(s.a, s.cursor) : null }];
if (input.kind !== "point") return [s, { draft: s.phase === "end" ? rayDraft(ctx, s.a, s.cursor) : null }];
const pt = input.point;
if (s.phase !== "end") {
const next: RayDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt };
return [next, { draft: rayDraft(pt, pt) }];
return [next, { draft: rayDraft(ctx, pt, pt) }];
}
if (segLen(s.a, pt) < EPS) {
return [{ phase: "start", lastPoint: null }, { draft: null, done: true }];
@@ -101,15 +81,15 @@ export const rayCommand: Command = {
const a = s.a;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: opsMutation(() => appendRay(a, pt, ctx)) },
{ draft: null, done: true, commit: appendRay(a, pt, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as RayState;
if (s.phase !== "end") return [s, { draft: null }];
const next: RayDrawing = { ...s, cursor: point };
return [next, { draft: rayDraft(s.a, point) }];
return [next, { draft: rayDraft(ctx, s.a, point) }];
},
onConfirm: (): [CommandState, CommandResult] => [
+39 -180
View File
@@ -29,10 +29,7 @@
// s. `model/types.ts`). Radius wird auf die halbe kürzere Kantenlänge
// geklammert (sonst würden sich benachbarte Fillets überlappen).
import type { Drawing2D } from "../../model/types";
import { deltaHud, segmentHud, uniqueId } from "../../tools/types";
import { filletCorner } from "../../core";
import { bulgePolylinePoints, bulgeThroughPoint } from "../../core";
import { deltaHud, segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -40,13 +37,11 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
@@ -119,25 +114,6 @@ function baseFromFields(a: Vec2, locks: Record<string, number>, cursor: Vec2 | n
return { x: a.x + Math.cos(ang) * length, y: a.y + Math.sin(ang) * length };
}
/**
* Vier Ecken des gedrehten Rechtecks aus Basiskante (a→b) und einem dritten
* Punkt `p`: die Höhe ist der vorzeichenbehaftete senkrechte Abstand von `p` zur
* Basislinie; das Rechteck wird zu dieser Seite hin aufgespannt.
*/
function rotatedCorners(a: Vec2, b: Vec2, p: Vec2): Vec2[] {
const dx = b.x - a.x;
const dy = b.y - a.y;
const len = Math.hypot(dx, dy);
if (len < EPS) return [a, b, b, a];
// Einheits-Normale (links der Basisrichtung).
const nx = -dy / len;
const ny = dx / len;
const h = (p.x - a.x) * nx + (p.y - a.y) * ny; // signierte Höhe
const c3 = { x: b.x + nx * h, y: b.y + ny * h };
const c4 = { x: a.x + nx * h, y: a.y + ny * h };
return [a, b, c3, c4];
}
/** Senkrechter (signierter) Abstand eines Punktes zur Basislinie a→b. */
function riseFrom(a: Vec2, b: Vec2, p: Vec2): number {
const dx = b.x - a.x;
@@ -163,16 +139,6 @@ function riseToPoint(a: Vec2, b: Vec2, height: number, cursor: Vec2 | null): Vec
// ── Zentrum: Ecke aus Mittelpunkt ────────────────────────────────────────────
/** Achsparallele Ecken aus Zentrum + einer Ecke. */
function centerGeom(center: Vec2, corner: Vec2): { min: Vec2; max: Vec2 } {
const hx = Math.abs(corner.x - center.x);
const hy = Math.abs(corner.y - center.y);
return {
min: { x: center.x - hx, y: center.y - hy },
max: { x: center.x + hx, y: center.y + hy },
};
}
/** Ecke aus Zentrum + gelockten Halbmaßen (width/height als volle Kantenmaße). */
function centerCornerFromFields(
center: Vec2,
@@ -210,87 +176,36 @@ interface RectRise extends CommandState {
}
type RectState = RectIdle | RectCorner2 | RectRise;
function rectGeom(a: Vec2, b: Vec2): { min: Vec2; max: Vec2 } {
return {
min: { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) },
max: { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) },
};
}
// ── Eck-Radius ───────────────────────────────────────────────────────────────
/**
* Rundet die 4 Ecken eines Rechtecks (beliebige Umlaufreihenfolge/Ausrichtung
* — arbeitet rein über die tatsächliche Punkt-Geometrie, keine Achsparallel-
* Annahme) mit Radius `r`, geklammert auf die halbe kürzeste Kantenlänge
* (sonst würden sich benachbarte Fillets überlappen). `null` bei `r<=0` oder
* wenn selbst der geklammerte Radius nicht mehr passt (entartetes Rechteck).
*/
function roundedRectPts(corners: Vec2[], r: number): { pts: Vec2[]; bulge: number[] } | null {
if (r < EPS) return null;
const n = corners.length;
let maxR = Infinity;
for (let i = 0; i < n; i++) {
maxR = Math.min(maxR, segLen(corners[i], corners[(i + 1) % n]) / 2);
}
const rr = Math.min(r, maxR - EPS);
if (rr < EPS) return null;
const pts: Vec2[] = [];
const bulge: number[] = [];
for (let i = 0; i < n; i++) {
const prev = corners[(i - 1 + n) % n];
const cur = corners[i];
const next = corners[(i + 1) % n];
const f = filletCorner(cur, prev, next, rr);
if (!f) return null; // (nahezu) kollineare Ecke — sollte bei einem Rechteck nicht vorkommen
// Bogen-Mittelpunkt: auf dem Fillet-Kreis, in Richtung der ursprünglichen
// (jetzt weggerundeten) Ecke vom Bogen-Zentrum aus gesehen.
const dx = cur.x - f.center.x;
const dy = cur.y - f.center.y;
const dl = Math.hypot(dx, dy) || 1;
const mid: Vec2 = { x: f.center.x + (dx / dl) * rr, y: f.center.y + (dy / dl) * rr };
pts.push(f.tangentA, f.tangentB);
bulge.push(bulgeThroughPoint(f.tangentA, mid, f.tangentB), 0);
}
return { pts, bulge };
}
/** Tessellierte Punkte einer gerundeten geschlossenen Kontur — für die Live-Vorschau. */
function tessellateRounded(pts: Vec2[], bulge: number[]): Vec2[] {
return bulgePolylinePoints(pts, bulge, true);
}
// ── Vorschau ─────────────────────────────────────────────────────────────────
function corners4Draft(pts: Vec2[], hud: ToolDraft["hud"] | null): ToolDraft {
const rounded = roundedRectPts(pts, lastRadius);
const previewPts = rounded ? tessellateRounded(rounded.pts, rounded.bulge) : pts;
const preview: DraftShape[] = [{ kind: "poly", pts: previewPts, closed: true }];
const draft: ToolDraft = { preview, vertices: [pts[0]] };
/**
* Vorschau eines Rechtecks im Kern (`cmd_draw.rs`): Ecken (bei Eck-Radius > 0 gerundet tesselliert);
* der erste Stützpunkt ist die erste Ecke der Kontur.
*/
function cornersDraft(ctx: CommandContext, method: RectMethod, pts: Vec2[], hud: ToolDraft["hud"] | null): { draft: ToolDraft; height: number } {
const pv = createPreview(ctx, { cmd: "rect", method, radius: lastRadius }, pts);
const draft: ToolDraft = { preview: pv.shapes, vertices: [{ x: pv.info[0], y: pv.info[1] }] };
if (hud) draft.hud = hud;
return draft;
return { draft, height: pv.info[2] };
}
/** Vorschau des 2-Punkt-Rechtecks (achsparallel) — HUD zeigt die Diagonale a→cursor. */
function cornerDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
function cornerDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return { preview: [], vertices: [a] };
const g = rectGeom(a, cursor);
const pts: Vec2[] = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return corners4Draft(pts, segLen(a, cursor) >= EPS ? deltaHud(a, cursor) : null);
return cornersDraft(ctx, "corner", [a, cursor], segLen(a, cursor) >= EPS ? deltaHud(a, cursor) : null).draft;
}
/** Vorschau des Zentrum-Rechtecks (achsparallel) — HUD zeigt die Diagonale center→cursor. */
function centerDraft(center: Vec2, cursor: Vec2 | null): ToolDraft {
function centerDraft(ctx: CommandContext, center: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return { preview: [], vertices: [center] };
const g = centerGeom(center, cursor);
const pts: Vec2[] = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return corners4Draft(
pts,
return cornersDraft(
ctx,
"center",
[center, cursor],
segLen(center, cursor) >= EPS
? { at: cursor, dx: 2 * (cursor.x - center.x), dy: 2 * (cursor.y - center.y) }
: null,
);
).draft;
}
/** Vorschau der Basiskante (3-Punkt, erster Teil). */
@@ -300,69 +215,23 @@ function baseDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
}
/** Vorschau des gedrehten Rechtecks (3-Punkt, zweiter Teil) — HUD: Basisbreite + Höhe am Cursor. */
function riseDraft(a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft {
function riseDraft(ctx: CommandContext, a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return { preview: [{ kind: "line", a, b }], vertices: [a] };
const pts = rotatedCorners(a, b, cursor);
const r = cornersDraft(ctx, "three", [a, b, cursor], null);
const w = segLen(a, b);
const h = Math.abs(riseFrom(a, b, cursor));
return corners4Draft(pts, { at: cursor, text: `B: ${w.toFixed(3)}m H: ${h.toFixed(3)}m` });
r.draft.hud = { at: cursor, text: `B: ${w.toFixed(3)}m H: ${r.height.toFixed(3)}m` };
return r.draft;
}
// ── Commit ───────────────────────────────────────────────────────────────────
/** Achsparalleles Rechteck als `shape:"rect"` (geschlossen behandelt). */
function appendRect(min: Vec2, max: Vec2, ctx: CommandContext): CoreOp[] {
if (max.x - min.x < EPS || max.y - min.y < EPS) return []; // Null-Rechteck
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "rect", min, max },
};
return addItems("drawings2d", [d]);
}
/**
* Gedrehtes Rechteck als geschlossene Polylinie (`shape:"polyline", closed:true`)
* — `shape:"rect"` kann nur achsparallel, deshalb hier ein Ring aus vier Ecken.
* Downstream (Füllung/Offset) behandelt einen geschlossenen Polygonzug als Ring.
* Commit (Kern, `cmd_draw.rs`): 2-Punkt/Zentrum achsparallel als `shape:"rect"`, 3-Punkt als
* geschlossene Polylinie; mit Eck-Radius > 0 (geklammert auf die halbe kürzeste Kante) als geschlossene
* Polylinie mit Bögen. Entartete Rechtecke ergeben nichts.
*/
function appendRotated(pts: Vec2[], ctx: CommandContext): CoreOp[] {
// Fläche prüfen: entartete Rechtecke verwerfen.
const w = segLen(pts[0], pts[1]);
const h = segLen(pts[1], pts[2]);
if (w < EPS || h < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts, closed: true },
};
return addItems("drawings2d", [d]);
}
/**
* Gerundetes Rechteck (Eck-Radius > 0) als geschlossene `polyline` MIT
* `bulge` — ersetzt `appendRect`/`appendRotated`, wenn `lastRadius` > 0 ist,
* unabhängig von der Konstruktionsmethode (`corners` sind die 4 scharfen
* Ecken, egal ob achsparallel oder gedreht). No-Op, wenn der Radius nicht
* passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten
* Rechteck).
*/
function appendRectRounded(corners: Vec2[], ctx: CommandContext): CoreOp[] {
const rr = roundedRectPts(corners, lastRadius);
if (!rr) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge },
};
return addItems("drawings2d", [d]);
}
const appendRect = (ctx: CommandContext, method: RectMethod, a: Vec2, b: Vec2, c: Vec2 | null = null) =>
createMutation(ctx, { cmd: "rect", method, a, b, c, radius: lastRadius });
const idle = (method: RectMethod): [CommandState, CommandResult] => [
{ phase: "corner1", lastPoint: null, method } as RectIdle,
@@ -404,13 +273,13 @@ export const rectCommand: Command = {
// Konstruktion NICHT verworfen, nur die Vorschau aktualisiert (der
// Radius wirkt erst beim Commit, betrifft also keine Punkt-Historie).
lastRadius = nextRadius();
return [s, { draft: draftFor(s) }];
return [s, { draft: draftFor(ctx, s) }];
}
return [s, { draft: null }];
}
if (input.kind !== "point") {
return [s, { draft: draftFor(s) }];
return [s, { draft: draftFor(ctx, s) }];
}
const pt = input.point;
@@ -420,7 +289,7 @@ export const rectCommand: Command = {
return [ns, { draft: baseDraft(pt, pt) }];
}
const ns: RectCorner2 = { phase: "corner2", method: s.method, a: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: draftFor(ns) }];
return [ns, { draft: draftFor(ctx, ns) }];
}
if (s.phase === "corner2") {
@@ -428,7 +297,7 @@ export const rectCommand: Command = {
// Basiskante gesetzt → dritter Punkt bestimmt Höhe.
if (segLen(s.a, pt) < EPS) return [s, { draft: baseDraft(s.a, s.cursor) }];
const ns: RectRise = { phase: "rise", method: "three", a: s.a, b: pt, cursor: pt, lastPoint: pt };
return [ns, { draft: riseDraft(s.a, pt, pt) }];
return [ns, { draft: riseDraft(ctx, s.a, pt, pt) }];
}
const a = s.a;
const method = s.method;
@@ -437,14 +306,7 @@ export const rectCommand: Command = {
{
draft: null,
done: true,
commit: opsMutation(() => {
const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt);
if (lastRadius >= EPS) {
const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return appendRectRounded(corners, ctx);
}
return appendRect(g.min, g.max, ctx);
}),
commit: appendRect(ctx, method, a, pt),
},
];
}
@@ -457,19 +319,16 @@ export const rectCommand: Command = {
{
draft: null,
done: true,
commit: opsMutation(() => {
const corners = rotatedCorners(a, b, pt);
return lastRadius >= EPS ? appendRectRounded(corners, ctx) : appendRotated(corners, ctx);
}),
commit: appendRect(ctx, "three", a, b, pt),
},
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as RectState;
if (s.phase === "corner1") return [s, { draft: null }];
const ns = { ...s, cursor: point } as RectState;
return [ns, { draft: draftFor(ns) }];
return [ns, { draft: draftFor(ctx, ns) }];
},
onConfirm: (state): [CommandState, CommandResult] => idle((state as RectState).method),
@@ -514,12 +373,12 @@ export const rectCommand: Command = {
};
/** Vorschau passend zum Zustand. */
function draftFor(s: RectState): ToolDraft {
function draftFor(ctx: CommandContext, s: RectState): ToolDraft {
if (s.phase === "corner2") {
if (s.method === "three") return baseDraft(s.a, s.cursor);
if (s.method === "center") return centerDraft(s.a, s.cursor);
return cornerDraft(s.a, s.cursor);
if (s.method === "center") return centerDraft(ctx, s.a, s.cursor);
return cornerDraft(ctx, s.a, s.cursor);
}
if (s.phase === "rise") return riseDraft(s.a, s.b, s.cursor);
if (s.phase === "rise") return riseDraft(ctx, s.a, s.b, s.cursor);
return { preview: [], vertices: [] };
}
+18 -37
View File
@@ -1,6 +1,6 @@
// Revisionswolke (Nutzer-Wunsch: „Keine Revisionswolken/Markup-Werkzeuge").
// Schritte (wie `polyline.ts`, aber ohne dessen Bogen-/Tangenten-Unteroptionen
// — JEDES Segment wird automatisch zu Beulen, s. `geometry/revisionCloud.ts`):
// — JEDES Segment wird automatisch zu Beulen, s. `cmd_draw.rs::revision_cloud`):
// 1) „Startpunkt:" → Punkt
// 2) „Nächster Punkt ( Schliessen ):" → Punkt … Enter beendet OFFEN (≥2
// Punkte); Klick nahe dem Startpunkt ODER die Option „Schliessen"
@@ -8,22 +8,17 @@
// Beulengrösse (Ziel-Bogenlänge) per Option, zyklisch, persistiert über
// Aufrufe hinweg (wie `lastSides` bei `polygon.ts`).
import type { Drawing2D } from "../../model/types";
import { bulgePolylinePoints } from "../../core";
import { revisionCloudPts } from "../../core";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
CmdOption,
Command,
CommandContext,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug
@@ -49,32 +44,18 @@ interface RevcloudDrawing extends CommandState {
type RevcloudState = RevcloudIdle | RevcloudDrawing;
/** Vorschau: die tatsächliche Beulen-Kontur (tesselliert), inkl. Gummiband zum Cursor. */
function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
function revcloudDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null): ToolDraft {
// Beulen-Kontur im Kern (`cmd_draw.rs`): je Segment gleich lange Bögen der Ziel-Bogenlänge, tesselliert.
const all = cursor ? [...points, cursor] : points;
const expanded = revisionCloudPts(all, false, lastArcSize);
const pts: Vec2[] = [];
if (expanded) {
pts.push(...bulgePolylinePoints(expanded.pts, expanded.bulge, false));
}
const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }];
const draft: ToolDraft = { preview, vertices: points };
const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "revcloud", arcSize: lastArcSize }, all).shapes, vertices: points };
const last = points[points.length - 1];
if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor);
return draft;
}
function appendRevcloud(points: Vec2[], closed: boolean, ctx: CommandContext): CoreOp[] {
const expanded = revisionCloudPts(points, closed, lastArcSize);
if (!expanded) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Revisionswolke als Polylinie mit Bögen (weniger als 2 Punkte → nichts). */
const appendRevcloud = (points: Vec2[], closed: boolean, ctx: CommandContext) =>
createMutation(ctx, { cmd: "revcloud", pts: points, closed, arcSize: lastArcSize });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as RevcloudIdle,
@@ -101,41 +82,41 @@ export const revcloudCommand: Command = {
lastArcSize = nextArcSize();
return [
s,
{ draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null },
{ draft: s.phase === "next" ? revcloudDraft(ctx, s.points, s.cursor) : null },
];
}
if (input.id === "close" && s.phase === "next" && s.points.length >= 3) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, true, ctx) }];
}
return [s, { draft: null }];
}
if (input.kind !== "point") {
return [s, { draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null }];
return [s, { draft: s.phase === "next" ? revcloudDraft(ctx, s.points, s.cursor) : null }];
}
const pt = input.point;
if (s.phase !== "next") {
const ns: RevcloudDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt };
return [ns, { draft: revcloudDraft([pt], pt) }];
return [ns, { draft: revcloudDraft(ctx, [pt], pt) }];
}
// Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring).
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, true, ctx) }];
}
const points = [...s.points, pt];
const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
return [ns, { draft: revcloudDraft(points, pt) }];
return [ns, { draft: revcloudDraft(ctx, points, pt) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as RevcloudState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: RevcloudDrawing = { ...s, cursor: point };
return [ns, { draft: revcloudDraft(s.points, point) }];
return [ns, { draft: revcloudDraft(ctx, s.points, point) }];
},
// Enter/Space/Rechtsklick: Zug als OFFENE Wolke beenden (≥2 Punkte).
@@ -143,7 +124,7 @@ export const revcloudCommand: Command = {
const s = state as RevcloudState;
if (s.phase === "next" && s.points.length >= 2) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, false, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, false, ctx) }];
}
return idle();
},
+22 -74
View File
@@ -11,23 +11,17 @@
// • floorId ← ctx.level.id (aktives Geschoss)
// • categoryCode← "35" (Ebene „Dächer"; Fallback ctx.defaultCategoryCode)
import type { Roof, RoofShape } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type { RoofShape } from "../../model/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Ebene (Kategorie) für Dächer („31 Dächer"). */
const ROOF_CATEGORY = "31";
import { createMutation, createPreview, xy } from "../createCore";
/** Wählbare Dachformen (Inline-Optionen der Befehlszeile). */
const SHAPE_OPTIONS: CmdOption[] = [
@@ -40,33 +34,6 @@ const SHAPE_OPTIONS: CmdOption[] = [
];
const SHAPE_IDS = new Set(SHAPE_OPTIONS.map((o) => o.id));
/** Existiert die Dach-Kategorie („35")? Sonst Fallback auf die aktive Kategorie. */
function roofCategory(ctx: CommandContext): string {
const flat: string[] = [];
const walk = (list: { code: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push(c.code);
if (c.children) walk(c.children as { code: string; children?: unknown[] }[]);
}
};
walk(ctx.project.layers as { code: string; children?: unknown[] }[]);
return flat.includes(ROOF_CATEGORY) ? ROOF_CATEGORY : ctx.defaultCategoryCode;
}
/** Vier Eckpunkte eines Rechtecks aus zwei Gegenecken (CCW). */
function rectCorners(a: Vec2, b: Vec2): Vec2[] {
const x0 = Math.min(a.x, b.x);
const x1 = Math.max(a.x, b.x);
const y0 = Math.min(a.y, b.y);
const y1 = Math.max(a.y, b.y);
return [
{ x: x0, y: y0 },
{ x: x1, y: y0 },
{ x: x1, y: y1 },
{ x: x0, y: y1 },
];
}
interface RoofIdle extends CommandState {
phase: "start";
shape: RoofShape;
@@ -74,46 +41,27 @@ interface RoofIdle extends CommandState {
interface RoofRect extends CommandState {
phase: "corner";
a: Vec2;
cursor: Vec2 | null;
cursor: Vec2;
shape: RoofShape;
}
type RoofState = RoofIdle | RoofRect;
/** Vorschau: aufgezogenes Rechteck + Masse im HUD. */
function roofDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
const pts = cursor ? rectCorners(a, cursor) : [a];
const preview: DraftShape[] = [{ kind: "poly", pts, closed: !!cursor }];
const draft: ToolDraft = { preview, vertices: [a] };
if (cursor) {
draft.hud = {
at: cursor,
text: `${Math.abs(cursor.x - a.x).toFixed(2)} × ${Math.abs(cursor.y - a.y).toFixed(2)} m`,
};
}
/** Vorschau: aufgezogenes Rechteck (Kern) + Masse im HUD. */
function roofDraft(ctx: CommandContext, a: Vec2, cursor: Vec2): ToolDraft {
const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "rect4" }, [a, cursor]).shapes, vertices: [a] };
draft.hud = {
at: cursor,
text: `${Math.abs(cursor.x - a.x).toFixed(2)} × ${Math.abs(cursor.y - a.y).toFixed(2)} m`,
};
return draft;
}
/** Hängt ein Dach ans Projekt (immutabel). Entartete Rechtecke werden verworfen. */
function appendRoof(a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): CoreOp[] {
const w = Math.abs(b.x - a.x);
const d = Math.abs(b.y - a.y);
if (w < 0.1 || d < 0.1) return [];
const roof: Roof = {
id: uniqueId("RF"),
type: "roof",
floorId: ctx.level.id,
categoryCode: roofCategory(ctx),
outline: rectCorners(a, b),
shape,
// Flach/Pult brauchen keine „Firsthöhe"; Sattel/Walm/Mansarde/Zelt ~30°.
pitchDeg: shape === "flach" ? 0 : 30,
overhang: 0.4,
// First entlang der längeren Seite (Standard).
ridgeAxis: w >= d ? "x" : "y",
thickness: 0.2,
};
return addItems("roofs", [roof]);
}
/**
* Commit (Kern, `cmd_create.rs`): Dach über dem Rechteck (entartet < 0.1 m → nichts), Ebene „31“,
* Neigung 30° (flach 0°), Vorsprung 0.4 m, First entlang der längeren Seite, Dicke 0.2 m.
*/
const appendRoof = (a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext) =>
createMutation(ctx, { cmd: "roof", a: xy(a), b: xy(b), shape });
const idle = (shape: RoofShape = "sattel"): [CommandState, CommandResult] => [
{ phase: "start", shape, lastPoint: null } as RoofIdle,
@@ -135,11 +83,11 @@ export const roofCommand: Command = {
// Dachform-Option: aktualisiert die Form, Phase/Rechteck bleiben.
if (input.kind === "option" && SHAPE_IDS.has(input.id)) {
const ns = { ...s, shape: input.id as RoofShape } as RoofState;
const draft = ns.phase === "corner" ? roofDraft(ns.a, ns.cursor) : null;
const draft = ns.phase === "corner" ? roofDraft(ctx, ns.a, ns.cursor) : null;
return [ns, { draft }];
}
if (input.kind !== "point") {
return [s, { draft: s.phase === "corner" ? roofDraft(s.a, s.cursor) : null }];
return [s, { draft: s.phase === "corner" ? roofDraft(ctx, s.a, s.cursor) : null }];
}
if (s.phase !== "corner") {
const ns: RoofRect = {
@@ -149,7 +97,7 @@ export const roofCommand: Command = {
shape: s.shape,
lastPoint: input.point,
};
return [ns, { draft: roofDraft(input.point, input.point) }];
return [ns, { draft: roofDraft(ctx, input.point, input.point) }];
}
// Zweite Ecke → committen.
const a = s.a;
@@ -157,15 +105,15 @@ export const roofCommand: Command = {
const shape = s.shape;
return [
{ phase: "start", shape, lastPoint: null } as RoofIdle,
{ draft: null, done: true, commit: opsMutation(() => appendRoof(a, b, shape, ctx)) },
{ draft: null, done: true, commit: appendRoof(a, b, shape, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as RoofState;
if (s.phase !== "corner") return [s, { draft: null }];
const ns: RoofRect = { ...s, cursor: point };
return [ns, { draft: roofDraft(s.a, point) }];
return [ns, { draft: roofDraft(ctx, s.a, point) }];
},
onConfirm: (): [CommandState, CommandResult] => idle(),
+7 -37
View File
@@ -1,6 +1,6 @@
// Dachhof — Innenhof/Lichthof im Dach als Engine-Befehl: eine Kontur wird per Klicks gezeichnet und
// dem ERSTEN Dach des aktiven Geschosses hinzugefügt, in dem sie wirkt (ganz im Umriss, ohne
// Überschneidung, nicht bei Pultdach — das entscheidet der Rust-Kern, s. `roofHoleWorks`).
// Überschneidung, nicht bei Pultdach — das entscheidet der Rust-Kern, s. `cmd_solid.rs`).
//
// Warum Zeichnen statt „aus gewählter Kontur": die Auswahl kennt immer nur ein Objekt, mit dem
// Dach gewählt wäre keine zweite Kontur wählbar; gezeichnet gibt es Fang auf Wände und Umriss,
@@ -11,9 +11,8 @@
// 2) „Nächster Punkt ( Schliessen Zurück ):" → Punkt … Schliessen per Klick auf den Startpunkt,
// Option „Schliessen" oder Enter (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken).
import { addRoofHole, opsMutation, patchItem, pointInOutline, roofHoleWorks } from "../../core";
import type { CoreOp } from "../../core";
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, Project, ToolDraft, Vec2 } from "../types";
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, ToolDraft, Vec2 } from "../types";
import { createMutation } from "../createCore";
const EPS = 1e-6;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kontur
@@ -21,19 +20,6 @@ const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kon
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
/** Vier Ecken eines Rechtecks aus zwei Gegenecken. */
function rectCorners(a: Vec2, b: Vec2): Vec2[] {
const x0 = Math.min(a.x, b.x);
const x1 = Math.max(a.x, b.x);
const y0 = Math.min(a.y, b.y);
const y1 = Math.max(a.y, b.y);
return [
{ x: x0, y: y0 },
{ x: x1, y: y0 },
{ x: x1, y: y1 },
{ x: x0, y: y1 },
];
}
interface HoleIdle extends CommandState {
phase: "start";
}
@@ -58,33 +44,17 @@ function holeDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
}
/** Aus den Klickpunkten die Hof-Kontur: ≥ 3 Punkte = Polygon, genau 2 = Rechteck. */
function ringOf(points: Vec2[]): Vec2[] | null {
if (points.length >= 3) return points;
if (points.length === 2) {
const [a, b] = points;
if (Math.abs(a.x - b.x) < 0.05 || Math.abs(a.y - b.y) < 0.05) return null;
return rectCorners(a, b);
}
return null;
}
/**
* Hängt den Hof an das erste Dach des aktiven Geschosses, in dem er wirkt. Ohne passendes Dach
* (Hof ausserhalb, schneidet den Umriss, Pultdach) bleibt das Projekt unverändert.
* Commit (Kern, `cmd_solid.rs`): Hof-Ring (≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck) in das Dach
* des Geschosses, das ihn ganz enthält und dessen Skelett ihn zulässt; sonst nichts.
*/
function roofHoleOps(p: Project, points: Vec2[], ctx: CommandContext): CoreOp[] {
const ring = ringOf(points);
if (!ring) return [];
const host = (p.roofs ?? []).find((r) => r.floorId === ctx.level.id && r.outline.length >= 3 && ring.every((pt) => pointInOutline(pt, r.outline)) && roofHoleWorks(r, ring));
if (!host) return [];
return patchItem(p, "roofs", host.id, (r) => ({ ...r, ...addRoofHole(r, ring) }));
}
const roofHoleOps = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "roofHole", pts: points });
const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null, done: true }];
const finish = (points: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as HoleIdle,
{ draft: null, done: true, commit: opsMutation((p) => roofHoleOps(p, points, ctx)) },
{ draft: null, done: true, commit: roofHoleOps(points, ctx) },
];
export const roofHoleCommand: Command = {
+11 -109
View File
@@ -3,7 +3,7 @@
//
// 1) „innen" (Default) — EIN Klick IN einen von Wänden umschlossenen Bereich.
// Der Umriss wird über den reinen Rechenkern (geometry/roomBoundary,
// `roomFromPointInside`) aus den Wänden des aktiven Geschosses automatisch
// `room_from_point_inside`, Kern `cmd_create.rs`) aus den Wänden des aktiven Geschosses automatisch
// als lichte Innenkontur erkannt. Findet der Klick keine geschlossene Zelle,
// passiert nichts (der Nutzer kann in den Manuell-Modus wechseln).
//
@@ -17,12 +17,6 @@
//
// Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md). Einheit: METER.
import type { Room } from "../../model/types";
import { wallTypeThickness } from "../../model/types";
import { roomFromPointInside, type WallSegment } from "../../core";
import { polygonArea, centroid } from "../../core";
import { docFromText } from "../../text/richText";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -34,112 +28,21 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, xy } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Umriss
/** Default-Ebene (Kategorie) für Räume: „60" Räume (Fallback: aktive). */
const ROOM_CATEGORY = "60";
/** Default-Raumfarbe (falls Kategorie nicht auflösbar). */
const ROOM_COLOR = "#5a7a9a";
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
(Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
/** Existiert die Raum-Kategorie („45")? Sonst Fallback auf die aktive Kategorie. */
function roomCategory(ctx: CommandContext): string {
const flat: { code: string }[] = [];
const walk = (list: { code: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push({ code: c.code });
if (c.children) walk(c.children as { code: string; children?: unknown[] }[]);
}
};
walk(ctx.project.layers as { code: string; children?: unknown[] }[]);
return flat.some((c) => c.code === ROOM_CATEGORY)
? ROOM_CATEGORY
: ctx.defaultCategoryCode;
}
/** Farbe der Raum-Kategorie (Ebene) — sonst Default. */
function roomColor(ctx: CommandContext, code: string): string {
const flat: { code: string; color?: string; children?: unknown[] }[] = [];
const walk = (list: { code: string; color?: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push(c);
if (c.children)
walk(
c.children as {
code: string;
color?: string;
children?: unknown[];
}[],
);
}
};
walk(
ctx.project.layers as {
code: string;
color?: string;
children?: unknown[];
}[],
);
return flat.find((c) => c.code === code)?.color ?? ROOM_COLOR;
}
/**
* Wände des aktiven Geschosses in die vom Rechenkern erwartete Form bringen:
* Mittellinie (start→end) + Gesamtdicke des Wandtyps. Grafik-2D-Geometrie und
* andere Geschosse bleiben außen vor.
* Commit eines Raums (Kern, `cmd_create.rs`): Umriss `pts` (manuell) bzw. die lichte Zelle um `at`
* (innen, aus den Wänden des Geschosses); SIA HNF, Name „Raum N“, Ebene „60“ samt Farbe, Stempel-Anker
* im Schwerpunkt und zentrierter Stempel-Text. Entartete Umrisse ergeben nichts.
*/
function wallsOfFloor(ctx: CommandContext): WallSegment[] {
const { project, level } = ctx;
const out: WallSegment[] = [];
for (const w of project.walls) {
if (w.floorId !== level.id) continue;
const wt = project.wallTypes.find((t) => t.id === w.wallTypeId);
const thickness = wt ? wallTypeThickness(wt) : 0.2;
out.push({ a: w.start, b: w.end, thickness });
}
return out;
}
/** Baut einen Raum aus einem fertigen Umriss (immutabel; keine abgeleiteten Felder). */
function buildRoom(ctx: CommandContext, boundary: Vec2[]): Room {
const code = roomCategory(ctx);
const name = defaultRoomName(ctx);
return {
id: uniqueId("RM"),
type: "room",
floorId: ctx.level.id,
categoryCode: code,
siaCategory: "HNF",
name,
boundary,
color: roomColor(ctx, code),
// Stempel-Anker EINMALIG auf den Zentroid setzen (danach frei verschiebbar,
// bleibt beim Ändern der Kontur an seiner Stelle).
stampAnchor: centroid(boundary),
// Frei editierbarer Stempel-Text: ein zentrierter Absatz mit dem Raumnamen.
stampDoc: { ...docFromText(name), paragraphs: docFromText(name).paragraphs.map((p) => ({ ...p, align: "center" as const })) },
};
}
/** Fortlaufender Default-Name „Raum N" (N = Anzahl vorhandener Räume + 1). */
function defaultRoomName(ctx: CommandContext): string {
const n = (ctx.project.rooms ?? []).length + 1;
return `Raum ${n}`;
}
/** Hängt einen Raum ans Projekt (immutabel); entartete Umrisse werden verworfen. */
function appendRoom(boundary: Vec2[], ctx: CommandContext): CoreOp[] {
if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return [];
const room = buildRoom(ctx, boundary);
return addItems("rooms", [room]);
}
const appendRoom = (boundary: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "room", pts: boundary.map(xy) });
// ── Zustand ──────────────────────────────────────────────────────────────────
@@ -254,7 +157,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
{ draft: null, done: true, commit: appendRoom(pts, ctx) },
];
}
return [s, { draft: s.phase === "draw" ? manualDraft(s.points, s.cursor) : null }];
@@ -271,11 +174,10 @@ export const roomCommand: Command = {
// ── Modus „innen": ein Klick → Umriss automatisch erkennen + committen ──
if (s.mode === "inside" && s.phase !== "draw") {
const boundary = roomFromPointInside(pt, wallsOfFloor(ctx));
if (boundary && boundary.length >= 3) {
if (createPreview(ctx, { cmd: "roomInside" }, [pt]).ok) {
return [
{ phase: "start", lastPoint: null, mode: "inside" } as RoomIdle,
{ draft: null, done: true, commit: opsMutation(() => appendRoom(boundary, ctx)) },
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "room", at: xy(pt) }) },
];
}
// Kein umschlossener Bereich getroffen → im Werkzeug bleiben (kein Commit).
@@ -298,7 +200,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
{ draft: null, done: true, commit: appendRoom(pts, ctx) },
];
}
const last = s.points[s.points.length - 1];
@@ -329,7 +231,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
{ draft: null, done: true, commit: appendRoom(pts, ctx) },
];
}
return idle(s.mode);
+9 -35
View File
@@ -4,20 +4,16 @@
// `lastSides` bei `polygon.ts`).
// Segmentlänge + Anzahl per Option (zyklisch, tippbar als „l"/„n").
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
CmdOption,
Command,
CommandContext,
CommandResult,
CommandState,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50];
let lastLength = 1;
@@ -36,40 +32,18 @@ interface ScalebarIdle extends CommandState {
type ScalebarState = ScalebarIdle;
/** Vorschau: abwechselnd gefüllte/leere Rechtecke, wie das Rendering (grob, ohne Beschriftung). */
function pointDraft(at: Vec2): ToolDraft {
const h = lastLength * 0.06; // rein optische Balkenhöhe für die Vorschau
const preview: DraftShape[] = [];
for (let i = 0; i < lastSegments; i++) {
const x0 = at.x + i * lastLength;
const x1 = x0 + lastLength;
preview.push({
kind: "poly",
pts: [
{ x: x0, y: at.y },
{ x: x1, y: at.y },
{ x: x1, y: at.y + h },
{ x: x0, y: at.y + h },
],
closed: true,
});
}
/** Vorschau (Kern, `cmd_draw.rs`): Segment-Balken am Cursor + HUD (Länge × Anzahl). */
function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft {
return {
preview,
preview: createPreview(ctx, { cmd: "scalebar", length: lastLength, segments: lastSegments }, [at]).shapes,
vertices: [at],
hud: { at, text: `${lastLength}m × ${lastSegments} = ${(lastLength * lastSegments).toFixed(1)}m` },
};
}
function appendScalebar(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Massstabsbalken mit Segmentlänge und -anzahl. */
const appendScalebar = (at: Vec2, ctx: CommandContext) =>
createMutation(ctx, { cmd: "scalebar", at, length: lastLength, segments: lastSegments });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null } as ScalebarIdle,
@@ -97,10 +71,10 @@ export const scalebarCommand: Command = {
return [s, { draft: null }];
}
if (input.kind !== "point") return [s, { draft: null }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendScalebar(input.point, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendScalebar(input.point, ctx) }];
},
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }],
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }],
onConfirm: (): [CommandState, CommandResult] => idle(),
onCancel: (): [CommandState, CommandResult] => idle(),
};
+20 -7
View File
@@ -1,13 +1,26 @@
// Schnittlinien-Befehl: der reine Datenpfad (commitLine/nextLevelName) — setzt
// die Grundriss-Schnittlinie auf die richtige Ziel-Ebene bzw. legt eine neue an.
// Schnittlinien-Befehl: der Datenpfad über den Befehl (Kern, `cmd_solid.rs`) — setzt die
// Grundriss-Schnittlinie auf die richtige Ziel-Ebene bzw. legt eine neue an.
import { describe, it, expect } from "vitest";
import { _test } from "./sectionline";
import { sectionLineCommand } from "./sectionline";
import type { DrawingLevel, Project, Vec2 } from "../../model/types";
import type { CommandContext } from "../types";
import { applyOps } from "../../core/ops";
const { lineOps, nextLevelName } = _test;
const commitLine = (p: Project, a: Vec2, b: Vec2, kind: "section" | "elevation") => applyOps(p, lineOps(p, a, b, kind));
/** Linie a→b mit dem Befehl setzen (Art per Option), Ops auf `p` anwenden. */
function commitLine(p: Project, a: Vec2, b: Vec2, kind: "section" | "elevation"): Project {
const ctx = { project: p, level: { id: "eg", kind: "floor" }, defaultCategoryCode: "20", activeWallTypeId: "", selection: { wallIds: [], drawingId: null } } as unknown as CommandContext;
let s = sectionLineCommand.init();
[s] = sectionLineCommand.onInput(s, { kind: "option", id: kind }, ctx);
[s] = sectionLineCommand.onInput(s, { kind: "point", point: a }, ctx);
const [, res] = sectionLineCommand.onInput(s, { kind: "point", point: b }, ctx);
const ops = res.commit!.toOps(p);
return ops.length ? applyOps(p, ops) : p;
}
/** Name der Ebene, die eine neue Linie dieser Art anlegt. */
const nextLevelName = (p: Project, kind: "section" | "elevation"): string =>
commitLine(p, a, b, kind).drawingLevels.at(-1)!.name;
function projectWith(levels: DrawingLevel[]): Project {
return {
@@ -90,12 +103,12 @@ describe("sectionline — commitLine", () => {
});
});
describe("sectionline — nextLevelName", () => {
describe("sectionline — Name der neuen Ebene", () => {
it("zählt Buchstaben je Art hoch (A, B, C …)", () => {
const p0 = projectWith([]);
expect(nextLevelName(p0, "section")).toContain("A");
const p1 = projectWith([
{ id: "s1", name: "Schnitt A", kind: "section", visible: true, locked: false },
{ id: "s1", name: "Schnitt A", kind: "section", visible: true, locked: false, linePoints: [{ x: 0, y: 0 }, { x: 1, y: 0 }] },
]);
expect(nextLevelName(p1, "section")).toContain("B");
});
+18 -84
View File
@@ -16,17 +16,13 @@
// „elevation"). Bezeichner englisch, sichtbarer Text via t().
import { t } from "../../i18n";
import type { DrawingLevel, DrawingLevelKind } from "../../model/types";
import { leftNormal, normalize, sub } from "../../model/geometry";
import { addItems, opsMutation, patchItem } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
@@ -42,42 +38,12 @@ const KIND_OPTIONS: CmdOption[] = [
const KIND_IDS = new Set(KIND_OPTIONS.map((o) => o.id));
/**
* Richtungspfeil-Vorschau: kurze Linie vom Mittelpunkt der Schnittlinie entlang
* der Blicknormalen (leftNormal der Linie, per directionSign gedreht) plus zwei
* Flügel-Segmente — zeigt, wohin der Schnitt „blickt".
* Vorschau: Schnittlinie + Richtungspfeil (Kern, `cmd_solid.rs`: vom Mittelpunkt entlang der
* Blicknormalen, zwei Flügel) + Länge im HUD.
*/
function directionArrow(a: Vec2, b: Vec2, sign: 1 | -1): DraftShape[] {
const dir = sub(b, a);
const len = Math.hypot(dir.x, dir.y);
if (len < 1e-6) return [];
const u = normalize(dir);
const n = leftNormal(u); // (-uy, ux)
const nx = n.x * sign;
const ny = n.y * sign;
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
// Pfeillänge ~ min(1 m, Viertel der Linienlänge), damit die Vorschau lesbar bleibt.
const arrowLen = Math.min(1, len / 4);
const tip = { x: mid.x + nx * arrowLen, y: mid.y + ny * arrowLen };
const wing = arrowLen * 0.35;
// Flügel: vom Spitzenpunkt zurück, je halb entlang −u und +u geneigt.
const back = { x: tip.x - nx * wing * 2, y: tip.y - ny * wing * 2 };
const w1 = { x: back.x + u.x * wing, y: back.y + u.y * wing };
const w2 = { x: back.x - u.x * wing, y: back.y - u.y * wing };
return [
{ kind: "line", a: mid, b: tip },
{ kind: "line", a: tip, b: w1 },
{ kind: "line", a: tip, b: w2 },
];
}
/** Vorschau: Schnittlinie + Richtungspfeil + Länge im HUD. */
function lineDraft(a: Vec2, cursor: Vec2 | null, sign: 1 | -1): ToolDraft {
function lineDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
if (!cursor) return { preview: [{ kind: "poly", pts: [a] }], vertices: [a] };
const preview: DraftShape[] = [
{ kind: "line", a, b: cursor },
...directionArrow(a, cursor, sign),
];
const draft: ToolDraft = { preview, vertices: [a] };
const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "sectionline" }, [a, cursor]).shapes, vertices: [a] };
draft.hud = {
at: cursor,
text: `${Math.hypot(cursor.x - a.x, cursor.y - a.y).toFixed(2)} m`,
@@ -85,42 +51,13 @@ function lineDraft(a: Vec2, cursor: Vec2 | null, sign: 1 | -1): ToolDraft {
return draft;
}
/** Nächster freier Ebenen-Name der Art (A, B, C … über die Anzahl bestehender). */
function nextLevelName(p: Project, kind: LineKind): string {
const count = p.drawingLevels.filter((z) => z.kind === kind).length;
// Buchstaben-Suffix (A, B, …, Z, dann AA…) — klassische Schnitt-Benennung.
let n = count;
let letters = "";
do {
letters = String.fromCharCode(65 + (n % 26)) + letters;
n = Math.floor(n / 26) - 1;
} while (n >= 0);
const key = kind === "section" ? "cmd.sectionline.newSection" : "cmd.sectionline.newElevation";
return t(key, { letter: letters });
}
/**
* Setzt die Schnittlinie [a, b] auf die Ziel-Ebene (immutabel). Existiert GENAU
* EINE Ebene der Art ohne Linie, wird sie belegt; sonst wird eine neue angelegt.
* Entartete (zu kurze) Linien werden verworfen.
* Commit (Kern): Linie [a, b] auf die EINE Ebene der Art ohne Linie, sonst eine neue Ebene (Name aus der
* Vorlage, Buchstaben A, B, … nach Anzahl der Ebenen dieser Art); zu kurze Linien (< 0.1 m) → nichts.
*/
function lineOps(p: Project, a: Vec2, b: Vec2, kind: LineKind): CoreOp[] {
if (Math.hypot(b.x - a.x, b.y - a.y) < 0.1) return [];
const line: [Vec2, Vec2] = [a, b];
const orphans = p.drawingLevels.filter((z) => z.kind === kind && !z.linePoints);
if (orphans.length === 1) {
return patchItem(p, "drawingLevels", orphans[0].id, (z) => ({ ...z, linePoints: line, directionSign: z.directionSign ?? 1 }));
}
const level: DrawingLevel = {
id: `${kind}-${Date.now()}`,
name: nextLevelName(p, kind),
kind: kind as DrawingLevelKind,
visible: true,
locked: false,
linePoints: line,
directionSign: 1,
};
return addItems("drawingLevels", [level]);
function lineMutation(ctx: CommandContext, a: Vec2, b: Vec2, kind: LineKind) {
const key = kind === "section" ? "cmd.sectionline.newSection" : "cmd.sectionline.newElevation";
return createMutation(ctx, { cmd: "sectionline", a, b, kind, name: t(key, { letter: "\u0001" }) });
}
interface LineIdle extends CommandState {
@@ -135,8 +72,6 @@ interface LineEnd extends CommandState {
}
type LineState = LineIdle | LineEnd;
const DIRECTION_SIGN: 1 = 1;
function makeCommand(name: string, startKind: LineKind): Command {
const idle = (kind: LineKind): [CommandState, CommandResult] => [
{ phase: "start", kind, lastPoint: null } as LineIdle,
@@ -155,18 +90,18 @@ function makeCommand(name: string, startKind: LineKind): Command {
options: () => KIND_OPTIONS,
init: (): LineIdle => ({ phase: "start", kind: startKind, lastPoint: null }),
onInput: (state, input): [CommandState, CommandResult] => {
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as LineState;
if (input.kind === "option" && KIND_IDS.has(input.id)) {
const ns = { ...s, kind: input.id as LineKind } as LineState;
const draft =
ns.phase === "end" ? lineDraft(ns.a, ns.cursor, DIRECTION_SIGN) : null;
ns.phase === "end" ? lineDraft(ctx, ns.a, ns.cursor) : null;
return [ns, { draft }];
}
if (input.kind !== "point") {
return [
s,
{ draft: s.phase === "end" ? lineDraft(s.a, s.cursor, DIRECTION_SIGN) : null },
{ draft: s.phase === "end" ? lineDraft(ctx, s.a, s.cursor) : null },
];
}
if (s.phase !== "end") {
@@ -177,22 +112,22 @@ function makeCommand(name: string, startKind: LineKind): Command {
kind: s.kind,
lastPoint: input.point,
};
return [ns, { draft: lineDraft(input.point, input.point, DIRECTION_SIGN) }];
return [ns, { draft: lineDraft(ctx, input.point, input.point) }];
}
const a = s.a;
const b = input.point;
const kind = s.kind;
return [
{ phase: "start", kind, lastPoint: null } as LineIdle,
{ draft: null, done: true, commit: opsMutation((p) => lineOps(p, a, b, kind)) },
{ draft: null, done: true, commit: lineMutation(ctx, a, b, kind) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as LineState;
if (s.phase !== "end") return [s, { draft: null }];
const ns: LineEnd = { ...s, cursor: point };
return [ns, { draft: lineDraft(s.a, point, DIRECTION_SIGN) }];
return [ns, { draft: lineDraft(ctx, s.a, point) }];
},
onConfirm: (state): [CommandState, CommandResult] => idle((state as LineState).kind),
@@ -206,4 +141,3 @@ export const sectionLineCommand: Command = makeCommand("sectionline", "section")
export const viewLineCommand: Command = makeCommand("viewline", "elevation");
// Für Tests: die reinen Datenpfad-Helfer.
export const _test = { lineOps, nextLevelName, directionArrow };
+8 -7
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { CommandContext } from "../types";
import { solidCommand, solidFromInputs } from "./solid";
import { solidCommand } from "./solid";
const ctx = { project: sampleProject, level: { id: "eg" } } as unknown as CommandContext;
@@ -47,14 +47,15 @@ describe("solid-Befehl", () => {
{ kind: "number", value: 3 },
])!;
expect(q.extrudedSolids![0].brep!.spec).toMatchObject({ kind: "cuboid", min: [0, 0, 0], max: [4, 2, 3] });
expect(solidFromInputs("torus", { x: 0, y: 0 }, null, [0.3, 0.5])).toBeNull();
expect(solidFromInputs("torus", { x: 0, y: 0 }, null, [2, 0.5])?.height).toBeCloseTo(1, 9);
// Torus: Hauptradius ≤ Rohrradius ergibt keinen Körper.
expect(run("torus", [{ kind: "point", point: { x: 0, y: 0 } }, { kind: "number", value: 0.3 }, { kind: "number", value: 0.5 }])!.extrudedSolids).toHaveLength(0);
expect(run("torus", [{ kind: "point", point: { x: 0, y: 0 } }, { kind: "number", value: 2 }, { kind: "number", value: 0.5 }])!.extrudedSolids![0].height).toBeCloseTo(1, 9);
});
it("Kegelstumpf: Revolve-Profil aus Radius, Oberradius, Hoehe", () => {
const b = solidFromInputs("frustum", { x: 1, y: 2 }, null, [2, 1, 3]);
expect(b?.height).toBe(3);
expect(b?.spec).toMatchObject({ kind: "revolve", cx: 1, cy: 2, profile: [0, 0, 2, 0, 1, 3, 0, 3] });
expect(solidFromInputs("frustum", { x: 0, y: 0 }, null, [2, 0, 3])).toBeNull();
const p = run("frustum", [{ kind: "point", point: { x: 1, y: 2 } }, { kind: "number", value: 2 }, { kind: "number", value: 1 }, { kind: "number", value: 3 }])!;
const b = p.extrudedSolids![0];
expect(b.height).toBe(3);
expect(b.brep!.spec).toMatchObject({ kind: "revolve", cx: 1, cy: 2, profile: [0, 0, 2, 0, 1, 3, 0, 3] });
});
});
+21 -121
View File
@@ -12,18 +12,16 @@
// Quader Ecke → Gegenecke → Höhe
// Der Körper steht auf der Geschoss-UK (Z = 0 lokal).
import type { ExtrudedSolid } from "../../model/types";
import { addItems, opsMutation } from "../../core";
import { uniqueId } from "../../tools/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { createMutation, createPreview } from "../createCore";
export type SolidShape = "sphere" | "cylinder" | "cone" | "frustum" | "torus" | "cuboid";
@@ -75,104 +73,22 @@ interface SolidState extends CommandState {
/** Persistente Defaults über Aufrufe hinweg (Enter übernimmt sie). */
let lastShape: SolidShape = "sphere";
const circlePts = (c: Vec2, r: number): Vec2[] =>
Array.from({ length: 48 }, (_, i) => {
const t = (i / 48) * Math.PI * 2;
return { x: c.x + r * Math.cos(t), y: c.y + r * Math.sin(t) };
});
const rectPts = (a: Vec2, b: Vec2): Vec2[] => {
const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)];
const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)];
return [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }];
};
/** Grundriss-Fläche, Körperhöhe und B-Rep-Spezifikation (lokales Z ab 0) einer Form. */
export function solidFromInputs(
shape: SolidShape,
p0: Vec2,
p1: Vec2 | null,
nums: number[],
): { points: Vec2[]; height: number; spec: Record<string, unknown>; label: string } | null {
const fmt = (v: number) => v.toFixed(2);
switch (shape) {
case "sphere": {
const r = nums[0];
if (!(r > 1e-6)) return null;
return {
points: circlePts(p0, r),
height: 2 * r,
spec: { kind: "sphere", center: [p0.x, p0.y, r], r },
label: `Kugel r=${fmt(r)}`,
};
}
case "cylinder":
case "cone": {
const [r, h] = nums;
if (!(r > 1e-6) || !(h > 1e-6)) return null;
return {
points: circlePts(p0, r),
height: h,
spec: { kind: shape, cx: p0.x, cy: p0.y, z0: 0, r, height: h },
label: `${shape === "cone" ? "Kegel" : "Zylinder"} r=${fmt(r)} h=${fmt(h)}`,
};
}
case "frustum": {
const [r, rt, h] = nums;
if (!(r > 1e-6) || !(rt > 1e-6) || !(h > 1e-6)) return null;
return {
points: circlePts(p0, Math.max(r, rt)),
height: h,
spec: { kind: "revolve", cx: p0.x, cy: p0.y, profile: [0, 0, r, 0, rt, h, 0, h] },
label: `Kegelstumpf r=${fmt(r)}/${fmt(rt)} h=${fmt(h)}`,
};
}
case "torus": {
const [major, minor] = nums;
if (!(minor > 1e-6) || !(major > minor)) return null;
return {
points: circlePts(p0, major + minor),
height: 2 * minor,
spec: { kind: "torus", center: [p0.x, p0.y, minor], major, minor },
label: `Torus R=${fmt(major)} r=${fmt(minor)}`,
};
}
case "cuboid": {
const h = nums[0];
if (!p1 || !(h > 1e-6)) return null;
const pts = rectPts(p0, p1);
const [w, d] = [Math.abs(p1.x - p0.x), Math.abs(p1.y - p0.y)];
if (w < 1e-6 || d < 1e-6) return null;
return {
points: pts,
height: h,
spec: { kind: "cuboid", min: [pts[0].x, pts[0].y, 0], max: [pts[2].x, pts[2].y, h] },
label: `Quader ${fmt(w)}×${fmt(d)}×${fmt(h)}`,
};
}
}
}
function draftOf(s: SolidState): ToolDraft | null {
/**
* Vorschau (Kern, `cmd_draw.rs`/`cmd_solid.rs`): Grundriss des Körpers je Schritt (Kreise bzw. Rechteck)
* + HUD (aktuelles Mass).
*/
function draftOf(ctx: CommandContext, s: SolidState): ToolDraft | null {
if (!s.p0) return null;
const step = STEPS[s.shape][s.stepIdx];
const preview: DraftShape[] = [];
let hud: string | undefined;
const cur = s.cursor ?? s.p0;
const pts = [s.p0, ...(s.p1 ? [s.p1] : []), ...(s.cursor ? [s.cursor] : [])];
const preview = createPreview(ctx, { cmd: "solid", shape: s.shape, step, nums: s.nums, p1: !!s.p1, cursor: !!s.cursor }, pts).shapes;
const dist = Math.hypot(cur.x - s.p0.x, cur.y - s.p0.y);
let hud: string;
if (s.shape === "cuboid") {
const b = s.p1 ?? cur;
preview.push({ kind: "poly", pts: rectPts(s.p0, b), closed: true });
hud = s.p1 ? `h = ${(s.nums[0] ?? 0).toFixed(2)} m` : `${Math.abs(b.x - s.p0.x).toFixed(2)} × ${Math.abs(b.y - s.p0.y).toFixed(2)} m`;
} else {
const r = step === "radius" || step === "major" ? dist : (s.nums[0] ?? dist);
if (s.shape === "frustum" && step !== "radius") {
preview.push({ kind: "poly", pts: circlePts(s.p0, Math.max(step === "topRadius" ? dist : (s.nums[1] ?? dist), 0.01)), closed: true });
}
preview.push({ kind: "poly", pts: circlePts(s.p0, Math.max(r, 0.01)), closed: true });
if (s.shape === "torus" && step === "minor") {
preview.push({ kind: "poly", pts: circlePts(s.p0, (s.nums[0] ?? 0) + dist), closed: true });
}
hud = `${step === "height" ? "h" : step === "topRadius" ? "r2" : "r"} = ${dist.toFixed(2)} m`;
}
return { preview, vertices: [s.p0], hud: { at: cur, text: hud } };
@@ -207,16 +123,16 @@ export const solidCommand: Command = {
lastShape = input.id as SolidShape;
// Form-Wechsel setzt die Schritte zurück (der Mittelpunkt bleibt, falls schon gesetzt).
const ns: SolidState = { ...reset(lastShape), p0: s.p0, stepIdx: s.p0 ? 1 : 0, cursor: s.cursor };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
const steps = STEPS[s.shape];
const step = steps[s.stepIdx];
// 1) Mittelpunkt / erste Ecke
if (step === "center") {
if (input.kind !== "point") return [s, { draft: draftOf(s) }];
if (input.kind !== "point") return [s, { draft: draftOf(ctx, s) }];
const ns: SolidState = { ...s, p0: input.point, stepIdx: 1, cursor: input.point, lastPoint: input.point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
// Wert des aktuellen Schritts: getippte Zahl oder Klick-Abstand zum Mittelpunkt.
@@ -228,45 +144,29 @@ export const solidCommand: Command = {
// Quader: Gegenecke als Punkt
if (step === "corner2") {
if (input.kind !== "point") return [s, { draft: draftOf(s) }];
if (input.kind !== "point") return [s, { draft: draftOf(ctx, s) }];
const ns: SolidState = { ...s, p1: input.point, stepIdx: s.stepIdx + 1, cursor: input.point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
if (value === null || !(value > 1e-6)) return [s, { draft: draftOf(s) }];
if (value === null || !(value > 1e-6)) return [s, { draft: draftOf(ctx, s) }];
const nums = [...s.nums, value];
if (s.stepIdx + 1 < steps.length) {
const ns: SolidState = { ...s, nums, stepIdx: s.stepIdx + 1 };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
// Letzter Schritt → committen.
const built = solidFromInputs(s.shape, s.p0!, s.p1, nums);
const levelId = ctx.level.id;
// Körper im Kern (`cmd_solid.rs`): Grundriss, Höhe, B-Rep-Beschreibung (truck) und Label.
return [
reset(s.shape),
{
draft: null,
done: true,
commit: opsMutation(() => {
if (!built) return [];
const solid: ExtrudedSolid = {
id: uniqueId("body"),
type: "extrudedSolid",
levelId,
points: built.points,
height: built.height,
brep: { spec: built.spec, origin: built.points[0], label: built.label },
};
return addItems("extrudedSolids", [solid]);
}),
},
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "solid", shape: s.shape, p0: s.p0, p1: s.p1, nums }) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as SolidState;
const ns: SolidState = { ...s, cursor: point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
},
onConfirm: (state): [CommandState, CommandResult] => [reset((state as SolidState).shape), { draft: null, done: true }],
+9 -1
View File
@@ -1,7 +1,15 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { ExtrudedSolid } from "../../model/types";
import { combineSolids } from "./solidbool";
import { documentFor } from "../../core/document";
/** Boolesche Verknüpfung zweier Körper über den Befehl im Kern (`cmd_solid.rs`); null = kein Körper. */
function combineSolids(project: typeof sampleProject, a: ExtrudedSolid, b: ExtrudedSolid, op: string): ExtrudedSolid | null {
const p = { ...project, extrudedSolids: [a, b] };
const ops = documentFor(p).cmdOps({ cmd: "solidbool", a: a.id, b: b.id, op, stamp: "t", ctx: { level: "eg" } });
const add = ops.find((o) => o.kind === "add");
return add && add.kind === "add" ? (add.items[0] as unknown as ExtrudedSolid) : null;
}
const box = (id: string, x0: number, y0: number, x1: number, y1: number, h: number): ExtrudedSolid => ({
id,
+19 -121
View File
@@ -7,11 +7,8 @@
// fertig. Die Operation wählt man als Inline-Option (Default Vereinigung); bei Differenz wird
// der ZWEITE vom ERSTEN abgezogen. Beide Quellkörper werden durch das Ergebnis ersetzt.
import type { ExtrudedSolid, Vec2 } from "../../model/types";
import { getFloor } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { addItems, extrudedSolidSpec, opsMutation, removeItems } from "../../core";
import type { Command, CommandResult, CommandState, CmdOption, Project, ToolDraft } from "../types";
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, ToolDraft } from "../types";
import { createMutation, createPreview, createQuery, xy } from "../createCore";
export type SolidBoolOp = "union" | "difference" | "intersection";
@@ -30,110 +27,18 @@ interface BoolState extends CommandState {
firstId: string | null;
}
function pointInPolygon(p: Vec2, poly: Vec2[]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i];
const b = poly[j];
if (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) {
inside = !inside;
}
}
return inside;
}
function bbox(pts: Vec2[]): { x0: number; y0: number; x1: number; y1: number } {
return {
x0: Math.min(...pts.map((p) => p.x)),
y0: Math.min(...pts.map((p) => p.y)),
x1: Math.max(...pts.map((p) => p.x)),
y1: Math.max(...pts.map((p) => p.y)),
};
}
const rect = (b: { x0: number; y0: number; x1: number; y1: number }): Vec2[] => [
{ x: b.x0, y: b.y0 },
{ x: b.x1, y: b.y0 },
{ x: b.x1, y: b.y1 },
{ x: b.x0, y: b.y1 },
];
/** Körper auf der aktiven Ebene, dessen Grundfläche den Punkt enthält (der kleinste gewinnt). */
function pickSolid(project: Project, levelId: string, pt: Vec2): ExtrudedSolid | null {
let best: ExtrudedSolid | null = null;
let bestArea = Infinity;
for (const s of project.extrudedSolids ?? []) {
if (s.levelId !== levelId || !pointInPolygon(pt, s.points)) continue;
const b = bbox(s.points);
const area = (b.x1 - b.x0) * (b.y1 - b.y0);
if (area < bestArea) {
best = s;
bestArea = area;
}
}
return best;
}
/** Ergebnis-Körper aus zwei Operanden (reiner Kern, getestet). `null`, wenn ein Operand keine B-Rep-Beschreibung hat. */
export function combineSolids(
project: Project,
a: ExtrudedSolid,
b: ExtrudedSolid,
op: SolidBoolOp,
): ExtrudedSolid | null {
let baseZ = 0;
try {
baseZ = getFloor(project, a.levelId).baseElevation ?? 0;
} catch {
baseZ = 0;
}
// Operanden mit UK 0 beschreiben (lokales Z ab Geschoss-UK), Verschiebung ist eingebacken.
const sa = extrudedSolidSpec(a, 0);
const sb = extrudedSolidSpec(b, 0);
void baseZ;
if (!sa || !sb) return null;
const ba = bbox(a.points);
const bb = bbox(b.points);
let points: Vec2[];
let height: number;
let label: string;
if (op === "union") {
points = rect({ x0: Math.min(ba.x0, bb.x0), y0: Math.min(ba.y0, bb.y0), x1: Math.max(ba.x1, bb.x1), y1: Math.max(ba.y1, bb.y1) });
height = Math.max(a.height, b.height);
label = "Vereinigung";
} else if (op === "difference") {
points = a.points.map((p) => ({ ...p }));
height = a.height;
label = "Differenz";
} else {
const x0 = Math.max(ba.x0, bb.x0);
const y0 = Math.max(ba.y0, bb.y0);
const x1 = Math.min(ba.x1, bb.x1);
const y1 = Math.min(ba.y1, bb.y1);
if (x1 - x0 < 1e-6 || y1 - y0 < 1e-6) return null;
points = rect({ x0, y0, x1, y1 });
height = Math.min(a.height, b.height);
label = "Durchschnitt";
}
return {
id: uniqueId("body"),
type: "extrudedSolid",
levelId: a.levelId,
points,
height,
brep: {
spec: { kind: "boolean", op, a: sa, b: sb } as unknown as Record<string, unknown>,
origin: points[0],
label,
},
};
/** Kleinster Körper der Ebene, dessen Grundriss den Punkt enthält (Kern), oder null. */
function pickSolid(ctx: CommandContext, pt: { x: number; y: number }): string | null {
return createQuery<{ hit: string | null }>(ctx.project, { q: "pickSolid", level: ctx.level.id, pt: xy(pt) }).hit;
}
const reset = (op: SolidBoolOp): BoolState => ({ phase: "first", op, firstId: null, lastPoint: null });
function highlight(project: Project, id: string | null): ToolDraft | null {
const s = id ? (project.extrudedSolids ?? []).find((x) => x.id === id) : null;
return s ? { preview: [{ kind: "poly", pts: s.points, closed: true }], vertices: [] } : null;
/** Hervorhebung des ersten gewählten Körpers (Grundriss aus dem Kern). */
function highlight(ctx: CommandContext, id: string | null): ToolDraft | null {
if (!id) return null;
const pv = createPreview(ctx, { cmd: "solidOutline", id }, []);
return pv.ok ? { preview: pv.shapes, vertices: [] } : null;
}
export const solidBoolCommand: Command = {
@@ -150,16 +55,16 @@ export const solidBoolCommand: Command = {
if (input.kind === "option" && OP_IDS.has(input.id)) {
lastOp = input.id as SolidBoolOp;
const ns: BoolState = { ...s, op: lastOp };
return [ns, { draft: highlight(ctx.project, s.firstId) }];
return [ns, { draft: highlight(ctx, s.firstId) }];
}
if (input.kind !== "point") return [s, { draft: highlight(ctx.project, s.firstId) }];
const hit = pickSolid(ctx.project, ctx.level.id, input.point);
if (!hit) return [s, { draft: highlight(ctx.project, s.firstId) }];
if (input.kind !== "point") return [s, { draft: highlight(ctx, s.firstId) }];
const hit = pickSolid(ctx, input.point);
if (!hit) return [s, { draft: highlight(ctx, s.firstId) }];
if (s.phase === "first") {
const ns: BoolState = { ...s, phase: "second", firstId: hit.id, lastPoint: input.point };
return [ns, { draft: highlight(ctx.project, hit.id) }];
const ns: BoolState = { ...s, phase: "second", firstId: hit, lastPoint: input.point };
return [ns, { draft: highlight(ctx, hit) }];
}
if (hit.id === s.firstId) return [s, { draft: highlight(ctx.project, s.firstId) }];
if (hit === s.firstId) return [s, { draft: highlight(ctx, s.firstId) }];
const firstId = s.firstId!;
const op = s.op;
return [
@@ -167,15 +72,8 @@ export const solidBoolCommand: Command = {
{
draft: null,
done: true,
commit: opsMutation((p) => {
const a = (p.extrudedSolids ?? []).find((x) => x.id === firstId);
const b = (p.extrudedSolids ?? []).find((x) => x.id === hit.id);
if (!a || !b) return [];
const merged = combineSolids(p, a, b, op);
if (!merged) return [];
// Beide Körper raus, das Ergebnis hinten dran.
return [...removeItems(p, "extrudedSolids", [a.id, b.id]), ...addItems("extrudedSolids", [merged])];
}),
// Verknüpfung im Kern (`cmd_solid.rs`): Grundriss, Höhe, B-Rep `boolean` beider Körper.
commit: createMutation(ctx, { cmd: "solidbool", a: firstId, b: hit, op }),
},
];
},
+21 -38
View File
@@ -15,21 +15,17 @@
// Kein Gewicht pro Kontrollpunkt (NURBS) — bewusst auf den unbewichteten
// Fall beschränkt, s. PENDENZEN.md.
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { sampleCatmullRom, sampleUniformBSpline } from "../../core";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug
@@ -65,32 +61,19 @@ const curveModeOption = (mode: CurveMode): CmdOption => ({
});
/** Kurvenpunkte je nach Modus (fit = interpolierend, control = B-Spline-Kontrollnetz). */
function sampleCurve(pts: Vec2[], closed: boolean, mode: CurveMode): Vec2[] {
return mode === "control" ? sampleUniformBSpline(pts, closed) : sampleCatmullRom(pts, closed);
}
/** Vorschau (geglätteter Zug + Gummiband zum Cursor) + HUD. */
function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: CurveMode): ToolDraft {
function splineDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: CurveMode): ToolDraft {
// Kurve im Kern (`cmd_draw.rs`): Catmull-Rom durch die Punkte bzw. B-Spline über dem Kontrollnetz,
// geschlossen ab 3 Punkten.
const pts = cursor ? [...points, cursor] : points;
const showClosed = closed && pts.length >= 3;
const curve = sampleCurve(pts, showClosed, mode);
const preview: DraftShape[] = [{ kind: "poly", pts: curve, closed: showClosed }];
const draft: ToolDraft = { preview, vertices: points };
const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "spline", closed, mode }, pts).shapes, vertices: points };
const last = points[points.length - 1];
if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor);
return draft;
}
function appendSpline(pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "spline", pts, closed, mode },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): Spline-Zeichnung aus den Punkten. */
const appendSpline = (pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext) =>
createMutation(ctx, { cmd: "spline", pts, closed, mode });
const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null, closed, curveMode } as SplineIdle,
@@ -116,11 +99,11 @@ export const splineCommand: Command = {
if (input.kind === "option") {
if (input.id === "mode") {
const ns = { ...s, closed: !s.closed } as SplineState;
return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, ns.closed, s.curveMode) : null }];
return [ns, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, ns.closed, s.curveMode) : null }];
}
if (input.id === "curveMode") {
const ns = { ...s, curveMode: s.curveMode === "control" ? "fit" : "control" } as SplineState;
return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, ns.curveMode) : null }];
return [ns, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, s.closed, ns.curveMode) : null }];
}
if (s.phase !== "next") return [s, { draft: null }];
if (input.id === "undo") {
@@ -138,20 +121,20 @@ export const splineCommand: Command = {
closed: s.closed,
curveMode: s.curveMode,
};
return [ns, { draft: splineDraft(pts, s.cursor, s.closed, s.curveMode) }];
return [ns, { draft: splineDraft(ctx, pts, s.cursor, s.closed, s.curveMode) }];
}
if (input.id === "close" && s.points.length >= 3) {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) },
{ draft: null, done: true, commit: appendSpline(pts, true, s.curveMode, ctx) },
];
}
return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }];
return [s, { draft: splineDraft(ctx, s.points, s.cursor, s.closed, s.curveMode) }];
}
if (input.kind !== "point") {
return [s, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, s.curveMode) : null }];
return [s, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, s.closed, s.curveMode) : null }];
}
const pt = input.point;
if (s.phase !== "next") {
@@ -163,13 +146,13 @@ export const splineCommand: Command = {
closed: s.closed,
curveMode: s.curveMode,
};
return [ns, { draft: splineDraft([pt], pt, s.closed, s.curveMode) }];
return [ns, { draft: splineDraft(ctx, [pt], pt, s.closed, s.curveMode) }];
}
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) },
{ draft: null, done: true, commit: appendSpline(pts, true, s.curveMode, ctx) },
];
}
const points = [...s.points, pt];
@@ -181,14 +164,14 @@ export const splineCommand: Command = {
closed: s.closed,
curveMode: s.curveMode,
};
return [ns, { draft: splineDraft(points, pt, s.closed, s.curveMode) }];
return [ns, { draft: splineDraft(ctx, points, pt, s.closed, s.curveMode) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as SplineState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: SplineDrawing = { ...s, cursor: point };
return [ns, { draft: splineDraft(s.points, point, s.closed, s.curveMode) }];
return [ns, { draft: splineDraft(ctx, s.points, point, s.closed, s.curveMode) }];
},
onConfirm: (state, ctx): [CommandState, CommandResult] => {
@@ -198,7 +181,7 @@ export const splineCommand: Command = {
const close = s.closed && pts.length >= 3;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, close, s.curveMode, ctx)) },
{ draft: null, done: true, commit: appendSpline(pts, close, s.curveMode, ctx) },
];
}
return idle(s.closed, s.curveMode);
-85
View File
@@ -1,85 +0,0 @@
/**
* Unit-Tests für `stepsFromTread` — Stufenzahl-Ableitung aus Soll-Auftritt + Lauflänge.
*
* Entspricht dem `target_a`-Modus im Rhino-Plugin (_make_treppe_preview_handler,
* Variable `target_a` = Soll-Auftritt).
*/
import { describe, it, expect } from "vitest";
import { stepsFromTread } from "./stair";
import { MIN_STEPS, IDEAL_TREAD } from "../../geometry/stair";
describe("stepsFromTread — Grundfälle", () => {
it("ergibt das ideale Soll-Trittmass bei exakter Teilbarkeit", () => {
// 10 × 0.29 m = 2.9 m → 10 Stufen
const steps = stepsFromTread(IDEAL_TREAD, 10 * IDEAL_TREAD);
expect(steps).toBe(10);
});
it("rundet auf die nächste ganze Stufenzahl", () => {
// 3.0 / 0.29 ≈ 10.34 → 10
expect(stepsFromTread(0.29, 3.0)).toBe(10);
// 3.1 / 0.29 ≈ 10.69 → 11
expect(stepsFromTread(0.29, 3.1)).toBe(11);
});
it("bleibt mindestens bei MIN_STEPS", () => {
// Sehr kurze Lauflänge → immer MIN_STEPS (2)
expect(stepsFromTread(0.29, 0.01)).toBe(MIN_STEPS);
});
it("klemmt nach oben: Stufenzahl durch 0.24-m-Auftritts-Grenze begrenzt", () => {
// 10 m Lauflänge, Auftritt 0.01 m → raw = 1000, aber durch Clamp auf
// floor(10/0.24)+1 = 42 begrenzt. Der resultierende Auftritt (≈ 0.238 m)
// ist der Grenzwert der floor-Formel aus defaultStepCount — kein echter Bug,
// sondern die bewusste Clamp-Schwelle (≥ min ~ 0.24 m, off-by-one durch +1).
const steps = stepsFromTread(0.01, 10.0);
// Die Stufenzahl muss deutlich kleiner als 1000 sein (Clamp wirkt).
expect(steps).toBeLessThan(100);
expect(steps).toBeGreaterThanOrEqual(MIN_STEPS);
// Auftrittstiefe muss im vernünftigen Bereich liegen (nahe 0.24 m).
const treadDepth = 10.0 / steps;
expect(treadDepth).toBeGreaterThanOrEqual(0.23 - 1e-6);
expect(treadDepth).toBeLessThanOrEqual(0.30);
});
it("typische Nutzung: Lauflänge 3 m, Auftritt 0.29 m → ca. 10 Stufen", () => {
const steps = stepsFromTread(0.29, 3.0);
expect(steps).toBeGreaterThanOrEqual(MIN_STEPS);
// Auftrittstiefe nahe am Soll
const tread = 3.0 / steps;
expect(tread).toBeGreaterThan(0.20);
expect(tread).toBeLessThan(0.40);
});
it("nullartige Auftritt-Eingabe wird intern auf 0.05 m geklippt", () => {
// Sollte nicht abstürzen, Ergebnis durch 0.24-m-Clamp begrenzt.
const steps = stepsFromTread(0, 3.0);
expect(steps).toBeGreaterThanOrEqual(MIN_STEPS);
});
it("negative Lauflänge → MIN_STEPS", () => {
expect(stepsFromTread(0.29, -1)).toBe(MIN_STEPS);
});
it("Auftritt 0.25 m, Lauflänge 2.5 m → 10 Stufen (exakt)", () => {
expect(stepsFromTread(0.25, 2.5)).toBe(10);
});
});
describe("stepsFromTread — Grenzwerte / Konsistenz", () => {
it("liefert immer ganze Zahlen", () => {
for (const run of [1.0, 2.5, 3.14, 5.0, 10.0]) {
const steps = stepsFromTread(0.29, run);
expect(Number.isInteger(steps)).toBe(true);
}
});
it("resultierender Auftritt liegt stets im erlaubten Bereich (>= 0.24 m)", () => {
for (const run of [1.0, 2.0, 3.0, 5.0]) {
const steps = stepsFromTread(IDEAL_TREAD, run);
const tread = run / steps;
expect(tread).toBeGreaterThanOrEqual(0.24 - 1e-6);
}
});
});
+29 -113
View File
@@ -19,9 +19,8 @@
//
// Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md).
import type { Stair, StairShape, Vec2 as MVec2 } from "../../model/types";
import { stairGeometry, defaultStepCount, IDEAL_TREAD, MIN_STEPS } from "../../core";
import { uniqueId } from "../../tools/types";
import type { StairShape } from "../../model/types";
import { IDEAL_TREAD, MIN_STEPS } from "../../core";
import type {
Command,
CommandContext,
@@ -29,18 +28,13 @@ import type {
CommandResult,
CommandState,
CmdOption,
DraftShape,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, xy } from "../createCore";
/** Default-Ebene (Kategorie) für Treppen: „40" Treppen (Fallback: aktive). */
const STAIR_CATEGORY = "40";
/** Default-Laufbreite (Meter). */
const DEF_WIDTH = 1.0;
const EPS = 1e-6;
// ── Trittmass-Modus ──────────────────────────────────────────────────────────
/** Trittmass-Modus: „with" = Soll-Auftritt vorgegeben, Stufen abgeleitet;
@@ -73,44 +67,6 @@ const stairDefaults: {
// ── Vektor-Helfer ─────────────────────────────────────────────────────────────
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
const lenOf = (a: Vec2): number => Math.hypot(a.x, a.y);
const normv = (a: Vec2): Vec2 => {
const l = lenOf(a) || 1e-9;
return { x: a.x / l, y: a.y / l };
};
/** Existiert die Treppen-Kategorie („40")? Sonst Fallback auf die aktive. */
function stairCategory(ctx: CommandContext): string {
const flat: { code: string }[] = [];
const walk = (list: { code: string; children?: unknown[] }[]) => {
for (const c of list) {
flat.push({ code: c.code });
if (c.children) walk(c.children as { code: string; children?: unknown[] }[]);
}
};
walk(ctx.project.layers as { code: string; children?: unknown[] }[]);
return flat.some((c) => c.code === STAIR_CATEGORY)
? STAIR_CATEGORY
: ctx.defaultCategoryCode;
}
/** Geschosshöhe als Default-Steighöhe (Fallback 2.6 m). */
function floorRise(ctx: CommandContext): number {
return ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : 2.6;
}
// ── Trittmass-Ableitung ───────────────────────────────────────────────────────
/**
* Leitet die Stufenzahl aus Auftritt (Soll-Trittmass) + Lauflänge ab.
* Klemmt auf [MIN_STEPS, maxByRun] (mind. 0.24 m Auftrittstiefe).
* Entspricht dem `target_a`-Modus im Rhino-Plugin (_make_treppe_preview_handler).
*/
export function stepsFromTread(auftritt: number, runLength: number): number {
const a = Math.max(0.05, auftritt);
const raw = Math.round(runLength / a);
// Auftrittstiefe aus Stufenzahl darf nicht unter 0.24 m sinken.
const maxByRun = runLength > 0 ? Math.max(MIN_STEPS, Math.floor(runLength / 0.24) + 1) : raw;
return Math.max(MIN_STEPS, Math.min(raw, maxByRun));
}
// ── Felder (Tab-Zyklus) ───────────────────────────────────────────────────────
/** Tab-Feld: Breite (immer, ab idle). */
@@ -173,78 +129,38 @@ function initState(override?: Partial<typeof stairDefaults>): StairIdle {
}
/**
* Baut aus dem Laufzustand ein konkretes `Stair`-Objekt (aufgelöste Felder). Die
* Richtung/Länge folgen aus start→cursor; bei L bricht der zweite Lauf um 90°
* (links) ab, bei Wendel wird der Cursorabstand zum Radius.
*
* Im Trittmass-Modus „mit" wird die Stufenzahl aus dem Soll-Auftritt + der
* aktuellen Lauflänge abgeleitet (stepsFromTread), kein freies steps-Feld.
* Anfrage an den Kern (`cmd_create.rs`): aus dem Laufzustand entsteht dort die Treppe — Richtung/Länge
* aus start→cursor, bei L ein symmetrischer zweiter Lauf, bei Wendel der Cursorabstand als Radius;
* Stufenzahl im Trittmass-Modus „mit“ aus Soll-Auftritt + Lauflänge, sonst gesetzt oder Vorgabe;
* Steighöhe = Geschosshöhe, falls nicht gesetzt; Ebene „40“.
*/
function buildStair(s: StairRun, ctx: CommandContext): Stair {
const rise = s.rise ?? floorRise(ctx);
const d = sub(s.cursor, s.start);
const dist = Math.max(0.1, lenOf(d));
const dir = dist > EPS ? normv(d) : ({ x: 1, y: 0 } as MVec2);
const runLength = s.shape === "spiral" ? Math.max(0.5, dist) : dist;
const stairReq = (s: StairRun) => ({
cmd: "stair",
shape: s.shape,
up: s.up,
width: s.width,
referenz: s.referenz,
treadMode: s.treadMode,
auftritt: s.auftritt,
steps: s.steps,
rise: s.rise,
start: xy(s.start),
cursor: xy(s.cursor),
});
// Stufenzahl je Trittmass-Modus:
// „mit Trittmass" → aus Auftritt + Lauflänge ableiten (Soll-Schrittmass).
// „ohne Trittmass" → manuell oder defaultStepCount (heutiges Verhalten).
const steps =
s.treadMode === "with"
? stepsFromTread(s.auftritt, runLength)
: (s.steps ?? defaultStepCount(rise, runLength));
const base: Stair = {
id: uniqueId("ST"),
type: "stair",
floorId: ctx.level.id,
categoryCode: stairCategory(ctx),
shape: s.shape,
start: s.start,
dir,
runLength,
width: s.width,
referenz: s.referenz,
totalRise: rise,
stepCount: steps,
up: s.up,
};
if (s.shape === "L") {
base.run2Length = runLength; // symmetrischer zweiter Lauf
base.turn = 1;
} else if (s.shape === "spiral") {
base.center = s.start;
base.radius = dist;
base.sweep = 270;
// Startpunkt am äußeren Rand: Lauflinie beginnt hier.
base.start = s.cursor;
base.dir = dir;
}
return base;
}
/** Vorschau: Tritt-Linien + Lauflinie + HUD (Länge · Stufenanzahl). */
/** Vorschau: Tritt-Linien + Podest + Lauflinie (Kern) + HUD (Länge · Stufenanzahl). */
function runDraft(s: StairRun, ctx: CommandContext): ToolDraft {
const stair = buildStair(s, ctx);
const rise = stair.totalRise ?? floorRise(ctx);
const geo = stairGeometry(stair, rise);
const preview: DraftShape[] = [];
for (const tr of geo.treads) preview.push({ kind: "poly", pts: tr.pts, closed: true });
if (geo.landing) preview.push({ kind: "poly", pts: geo.landing, closed: true });
if (geo.runLine.length >= 2) preview.push({ kind: "poly", pts: geo.runLine, closed: false });
const draft: ToolDraft = { preview, vertices: [s.start] };
const pv = createPreview(ctx, stairReq(s), []);
const draft: ToolDraft = { preview: pv.shapes, vertices: [s.start] };
draft.hud = {
at: s.cursor,
text: `${lenOf(sub(s.cursor, s.start)).toFixed(2)} m · ${stair.stepCount} STG`,
text: `${lenOf(sub(s.cursor, s.start)).toFixed(2)} m · ${pv.info[0]} STG`,
};
return draft;
}
/** Hängt eine Treppe ans Projekt (immutabel) und aktualisiert die Defaults. */
function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] {
const stair = buildStair(s, ctx);
// Zuletzt genutzte Einstellungen für die nächste Treppe merken.
/** Commit der Treppe (Kern) und die Einstellungen für die nächste Treppe merken. */
function appendStair(s: StairRun, ctx: CommandContext) {
stairDefaults.shape = s.shape;
stairDefaults.up = s.up;
stairDefaults.width = s.width;
@@ -253,7 +169,7 @@ function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] {
stairDefaults.auftritt = s.auftritt;
stairDefaults.steps = s.steps;
stairDefaults.rise = s.rise;
return addItems("stairs", [stair]);
return createMutation(ctx, stairReq(s));
}
const idle = (from?: StairCmdState): [CommandState, CommandResult] => [
@@ -348,7 +264,7 @@ export const stairCommand: Command = {
const ns: StairRun = { ...s, cursor: pt };
return [
idle(s)[0],
{ draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) },
{ draft: null, done: true, commit: appendStair(ns, ctx) },
];
},
@@ -365,7 +281,7 @@ export const stairCommand: Command = {
const ns = s;
return [
idle(s)[0],
{ draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) },
{ draft: null, done: true, commit: appendStair(ns, ctx) },
];
}
return idle(s);
+9 -28
View File
@@ -11,33 +11,14 @@
//
// Bezeichner englisch, sichtbarer Text via t() (Namespace `cmd.terrain.*`).
import { generateTerrainFromContours } from "../../model/terrain";
import type { ContextObject } from "../../model/types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import type {
Command,
CommandResult,
CommandState,
Project,
} from "../types";
import { createMutation } from "../createCore";
import type { Command, CommandContext, CommandResult, CommandState } from "../types";
/** Ops: hängt ein aus dem ersten ContourSet abgeleitetes TIN an `context` an. */
function terrainOps(p: Project): CoreOp[] {
const context: ContextObject[] = p.context ?? [];
const set = context.find((o) => o.type === "contourSet");
if (!set || set.type !== "contourSet") return [];
const terrain = generateTerrainFromContours(set.contours);
if (terrain.indices.length === 0) return []; // kein sinnvolles TIN
return addItems("context", [terrain]);
}
/** Ergebnis, das den Befehl sofort beendet und das TIN committet. */
const COMMIT_DONE: CommandResult = {
draft: null,
done: true,
commit: opsMutation(terrainOps),
};
/**
* Ergebnis, das den Befehl sofort beendet und das TIN committet (Kern, `cmd_solid.rs`: erstes
* ContourSet aus `context` → Delaunay-TIN; ohne sinnvolles TIN nichts).
*/
const commitDone = (ctx: CommandContext): CommandResult => ({ draft: null, done: true, commit: createMutation(ctx, { cmd: "terrain" }) });
const IDLE: CommandState = { phase: "idle", lastPoint: null };
@@ -51,10 +32,10 @@ export const terrainCommand: Command = {
init: () => ({ ...IDLE }),
// Jeglicher Input beendet den Befehl mit dem Commit (es gibt keine Schritte).
onInput: (): [CommandState, CommandResult] => [{ ...IDLE }, COMMIT_DONE],
onInput: (_s, _i, ctx): [CommandState, CommandResult] => [{ ...IDLE }, commitDone(ctx)],
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
// Enter/Space/Rechtsklick: Gelände erzeugen + beenden.
onConfirm: (): [CommandState, CommandResult] => [{ ...IDLE }, COMMIT_DONE],
onConfirm: (_s, ctx): [CommandState, CommandResult] => [{ ...IDLE }, commitDone(ctx)],
onCancel: (): [CommandState, CommandResult] => [
{ ...IDLE },
{ draft: null, done: true },
+4 -16
View File
@@ -8,30 +8,18 @@
// Wortumbruch-Textfeld). Bleibt der Editor leer, verwirft `commitTextEdit`
// (App.tsx) das Element wieder.
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
/** Default-Schrifthöhe eines frei platzierten Texts in Modell-Metern. */
const DEFAULT_TEXT_HEIGHT_M = 0.25;
interface TextIdle extends CommandState {
phase: "point";
}
type TextState = TextIdle;
function appendEmptyText(id: string, at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0 },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): leere Textzeile am Anker (Höhe 0.25 m), mit vorab vergebener id. */
const appendEmptyText = (id: string, at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "text", id, at });
const idle = (): [CommandState, CommandResult] => [
{ phase: "point", lastPoint: null } as TextIdle,
@@ -56,7 +44,7 @@ export const textCommand: Command = {
{
draft: null,
done: true,
commit: opsMutation(() => appendEmptyText(id, at, ctx)),
commit: appendEmptyText(id, at, ctx),
focusDrawingId: id,
},
];
+16 -52
View File
@@ -19,7 +19,6 @@
// Wortumbruch) — die Höhe bleibt reine Editor-Startgrösse (PlanView-lokal,
// s. focusMinHeightM), die Textmenge bestimmt die tatsächliche Höhe.
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type {
Command,
@@ -29,13 +28,8 @@ import type {
DraftShape,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
/** Default-Schrifthöhe einer Textspalte in Modell-Metern (= Baseline-Versatz vom Rahmen-Top). */
const DEFAULT_TEXT_HEIGHT_M = 0.25;
/** Kleinste sinnvolle Rahmen-Breite/-Höhe (Meter). */
const MIN_SIZE_M = 0.2;
interface TbFirst extends CommandState {
phase: "first";
@@ -48,53 +42,23 @@ interface TbSecond extends CommandState {
type TbState = TbFirst | TbSecond;
/** Normalisiertes Rechteck aus zwei diagonalen Punkten (beliebige Zugrichtung). */
function rectOf(a: Vec2, b: Vec2): { minX: number; maxX: number; minY: number; maxY: number } {
/**
* Textrahmen im Kern (`cmd_draw.rs`): Rechteck aus zwei Ecken, Breite/Höhe mindestens 0.2 m
* (`info = [Breite, Höhe]`), Anker oben links eine Zeilenhöhe tief.
*/
function frameDraft(ctx: CommandContext, a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: Vec2[]; hud: { at: Vec2; text: string } } {
const pv = createPreview(ctx, { cmd: "textbox" }, [a, cursor]);
const [w, h] = pv.info;
return {
minX: Math.min(a.x, b.x),
maxX: Math.max(a.x, b.x),
minY: Math.min(a.y, b.y),
maxY: Math.max(a.y, b.y),
};
}
/** Breite/Höhe (geklemmt auf MIN_SIZE_M) + die Textanker-Position (oben-links, als Baseline). */
function frameOf(a: Vec2, b: Vec2): { at: Vec2; width: number; heightM: number } {
const r = rectOf(a, b);
const width = Math.max(MIN_SIZE_M, r.maxX - r.minX);
const heightM = Math.max(MIN_SIZE_M, r.maxY - r.minY);
// `at` ist die Baseline-links der ERSTEN Zeile (s. plan/drawings.rs/primitives.tsx);
// die Rahmen-Oberkante liegt eine Zeilenhöhe darüber → at.y = Rahmen-Top − Zeilenhöhe.
return { at: { x: r.minX, y: r.maxY - DEFAULT_TEXT_HEIGHT_M }, width, heightM };
}
/** Vorschau: Rahmen-Rechteck zwischen den beiden Ecken. */
function frameDraft(a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: Vec2[]; hud: { at: Vec2; text: string } } {
const r = rectOf(a, cursor);
const pts: Vec2[] = [
{ x: r.minX, y: r.minY },
{ x: r.maxX, y: r.minY },
{ x: r.maxX, y: r.maxY },
{ x: r.minX, y: r.maxY },
];
const w = Math.max(MIN_SIZE_M, r.maxX - r.minX);
const h = Math.max(MIN_SIZE_M, r.maxY - r.minY);
return {
preview: [{ kind: "poly", pts, closed: true }],
preview: pv.shapes,
vertices: [a, cursor],
hud: { at: cursor, text: `${w.toFixed(2)} × ${h.toFixed(2)} m` },
};
}
function appendEmptyTextbox(id: string, at: Vec2, width: number, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, width },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): leere Textspalte (Breite des Rahmens), mit vorab vergebener id. */
const appendEmptyTextbox = (id: string, a: Vec2, b: Vec2, ctx: CommandContext) =>
createMutation(ctx, { cmd: "textbox", id, a, b });
const idle = (): [CommandState, CommandResult] => [
{ phase: "first", lastPoint: null } as TbFirst,
@@ -117,25 +81,25 @@ export const textboxCommand: Command = {
return [ns, { draft: { preview: [], vertices: [input.point] } }];
}
// phase === "second"
const { at, width, heightM } = frameOf(s.a, input.point);
const heightM = createPreview(ctx, { cmd: "textbox" }, [s.a, input.point]).info[1];
const id = uniqueId("dr2d");
return [
{ phase: "first", lastPoint: null } as TbFirst,
{
draft: null,
done: true,
commit: opsMutation(() => appendEmptyTextbox(id, at, width, ctx)),
commit: appendEmptyTextbox(id, s.a, input.point, ctx),
focusDrawingId: id,
focusMinHeightM: heightM,
},
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as TbState;
if (s.phase !== "second") return [s, { draft: null }];
const ns: TbSecond = { ...s, cursor: point };
return [ns, { draft: frameDraft(s.a, point) }];
return [ns, { draft: frameDraft(ctx, s.a, point) }];
},
onConfirm: (): [CommandState, CommandResult] => idle(),
+4 -15
View File
@@ -6,7 +6,6 @@
// 1) „Pfadpunkt:" → Punkt
// 2) „Nächster Pfadpunkt ( Fertig ):" → Punkt … Enter beendet (≥2 Punkte nötig)
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import type {
Command,
@@ -18,12 +17,10 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const DEFAULT_TEXT_HEIGHT_M = 0.25;
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
(Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
@@ -60,16 +57,8 @@ function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendEmptyTextPath(id: string, pts: Vec2[], ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): leerer Text entlang des Pfads (Anker = erster Pfadpunkt), vorab vergebene id. */
const appendEmptyTextPath = (id: string, pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "textpath", id, pts });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as TpIdle,
@@ -78,7 +67,7 @@ const idle = (): [CommandState, CommandResult] => [
function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult {
const id = uniqueId("dr2d");
return { draft: null, done: true, commit: opsMutation(() => appendEmptyTextPath(id, pts, ctx)), focusDrawingId: id };
return { draft: null, done: true, commit: appendEmptyTextPath(id, pts, ctx), focusDrawingId: id };
}
export const textpathCommand: Command = {
+11 -3
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { CommandContext } from "../types";
import { voidBoxCommand, voidFromInputs } from "./voidbox";
import { voidBoxCommand } from "./voidbox";
const ctx = { project: sampleProject, level: { id: "eg" } } as unknown as CommandContext;
@@ -20,7 +20,15 @@ describe("Durchbruch", () => {
expect(v.points).toHaveLength(4);
});
it("entartete Eingaben ergeben nichts", () => {
expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 0, y: 1 }, 1, 0)).toBeNull();
expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 1, y: 1 }, 0, 0)).toBeNull();
const ops = (a: { x: number; y: number }, b: { x: number; y: number }, h: number) => {
let st = voidBoxCommand.init();
[st] = voidBoxCommand.onInput(st, { kind: "point", point: a }, ctx);
[st] = voidBoxCommand.onInput(st, { kind: "point", point: b }, ctx);
[st] = voidBoxCommand.onInput(st, { kind: "number", value: h }, ctx);
const [, res] = voidBoxCommand.onInput(st, { kind: "number", value: 0 }, ctx);
return res.commit!.toOps(sampleProject);
};
expect(ops({ x: 0, y: 0 }, { x: 0, y: 1 }, 1)).toEqual([]);
expect(ops({ x: 0, y: 0 }, { x: 1, y: 1 }, 1)).toHaveLength(1);
});
});
+18 -50
View File
@@ -5,10 +5,8 @@
// Schritte: Ecke → Gegenecke → Höhe → Abstand über Geschoss-UK (Zahl tippen; Enter = 0).
// Beliebige Profile: Polylinie extrudieren und im Objekt-Panel „Abzugskörper" setzen.
import type { ExtrudedSolid } from "../../model/types";
import { addItems, opsMutation } from "../../core";
import { uniqueId } from "../../tools/types";
import type { Command, CommandResult, CommandState, ToolDraft, Vec2 } from "../types";
import type { Command, CommandContext, CommandResult, CommandState, ToolDraft, Vec2 } from "../types";
import { createMutation, createPreview } from "../createCore";
type Step = "corner" | "corner2" | "height" | "offset";
@@ -24,36 +22,12 @@ interface VoidState extends CommandState {
let lastHeight = 0.3;
let lastOffset = 1.0;
const rectPts = (a: Vec2, b: Vec2): Vec2[] => {
const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)];
const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)];
return [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }];
};
/** Abzugskörper aus den Eingaben (reiner Kern, getestet). */
export function voidFromInputs(levelId: string, a: Vec2, b: Vec2, height: number, offset: number): ExtrudedSolid | null {
if (Math.abs(b.x - a.x) < 1e-6 || Math.abs(b.y - a.y) < 1e-6 || !(height > 1e-6)) return null;
return {
id: uniqueId("void"),
type: "extrudedSolid",
levelId,
points: rectPts(a, b),
height,
operation: "subtract",
...(Math.abs(offset) > 1e-9 ? { baseOffset: offset } : {}),
};
}
function draftOf(s: VoidState): ToolDraft | null {
/** Vorschau (Kern): Rechteck mit Diagonalen + HUD (Masse bzw. Höhe/Versatz). */
function draftOf(ctx: CommandContext, s: VoidState): ToolDraft | null {
if (!s.p0) return null;
const b = s.p1 ?? s.cursor ?? s.p0;
const pts = rectPts(s.p0, b);
return {
preview: [
{ kind: "poly", pts, closed: true },
{ kind: "line", a: pts[0], b: pts[2] },
{ kind: "line", a: pts[1], b: pts[3] },
],
preview: createPreview(ctx, { cmd: "voidbox" }, [s.p0, b]).shapes,
vertices: [s.p0],
hud: {
at: b,
@@ -76,17 +50,11 @@ const PROMPT: Record<Step, string> = {
offset: "cmd.void.offset",
};
function finish(s: VoidState, offset: number, levelId: string): [CommandState, CommandResult] {
/** Commit (Kern, `cmd_solid.rs`): Aussparungs-Quader (subtrahierender Körper) mit Versatz über der UK. */
function finish(s: VoidState, offset: number, ctx: CommandContext): [CommandState, CommandResult] {
lastOffset = offset;
const solid = s.p0 && s.p1 && s.height ? voidFromInputs(levelId, s.p0, s.p1, s.height, offset) : null;
return [
reset(),
{
draft: null,
done: true,
commit: opsMutation(() => (solid ? addItems("extrudedSolids", [solid]) : [])),
},
];
// Unvollständige Eingaben (ohne Ecken/Höhe) ergeben im Kern nichts.
return [reset(), { draft: null, done: true, commit: createMutation(ctx, { cmd: "voidbox", a: s.p0, b: s.p1, height: s.height, offset }) }];
}
export const voidBoxCommand: Command = {
@@ -102,25 +70,25 @@ export const voidBoxCommand: Command = {
const s = state as VoidState;
if (s.step === "corner" && input.kind === "point") {
const ns: VoidState = { ...s, step: "corner2", p0: input.point, cursor: input.point, lastPoint: input.point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
if (s.step === "corner2" && input.kind === "point") {
const ns: VoidState = { ...s, step: "height", p1: input.point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
if (s.step === "height" && input.kind === "number" && input.value > 0) {
lastHeight = input.value;
const ns: VoidState = { ...s, step: "offset", height: input.value };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
if (s.step === "offset" && input.kind === "number") return finish(s, input.value, ctx.level.id);
return [s, { draft: draftOf(s) }];
if (s.step === "offset" && input.kind === "number") return finish(s, input.value, ctx);
return [s, { draft: draftOf(ctx, s) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as VoidState;
const ns: VoidState = { ...s, cursor: point };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
},
// Enter übernimmt die letzten Werte (Höhe bzw. Abstand).
@@ -128,9 +96,9 @@ export const voidBoxCommand: Command = {
const s = state as VoidState;
if (s.step === "height") {
const ns: VoidState = { ...s, step: "offset", height: lastHeight };
return [ns, { draft: draftOf(ns) }];
return [ns, { draft: draftOf(ctx, ns) }];
}
if (s.step === "offset") return finish(s, lastOffset, ctx.level.id);
if (s.step === "offset") return finish(s, lastOffset, ctx);
return [reset(), { draft: null, done: true }];
},
onCancel: (): [CommandState, CommandResult] => [reset(), { draft: null, done: true }],
+37 -140
View File
@@ -15,10 +15,7 @@
// • floorId ← ctx.level.id (aktives Geschoss)
// • categoryCode← ctx.defaultCategoryCode (aktive Kategorie, i. d. R. „20")
import type { Wall, WallType } from "../../model/types";
import { wallTypeThickness } from "../../model/types";
import { wallCorners } from "../../model/geometry";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -27,17 +24,13 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview, xy } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const DEFAULT_HEIGHT = 2.6; // Fallback-Wandhöhe (Meter), wenn das Geschoss keine hat
const DEFAULT_THICKNESS = 0.2; // Fallback-Banddicke für die Vorschau (Meter)
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
(Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
@@ -61,74 +54,14 @@ function wallNextFromFields(last: Vec2, locks: Record<string, number>, cursor: V
return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length };
}
/**
* Dicke des aktiven Wandtyps (für die Band-Vorschau). Liest `ctx.activeWallTypeId`;
* fehlt der Typ, Fallback auf den ersten Projekt-Wandtyp bzw. DEFAULT_THICKNESS.
*/
function activeWallThickness(ctx: CommandContext): number {
/** Einschichtig? Nur dann ist das Dicke-Feld sinnvoll (überschreibt die Schicht). */
function isSingleLayer(ctx: CommandContext): boolean {
const wt =
ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ??
ctx.project.wallTypes[0];
return wt ? wallTypeThickness(wt) : DEFAULT_THICKNESS;
}
/** Aktives Wandtyp-Objekt (Fallback: erster Projekt-Wandtyp). */
function activeWallType(ctx: CommandContext): WallType | undefined {
return (
ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ??
ctx.project.wallTypes[0]
);
}
/** Aktiver Wandtyp-ID; Fallback auf den ersten Projekt-Wandtyp. */
function activeWallTypeId(ctx: CommandContext): string {
const wt = activeWallType(ctx);
return wt ? wt.id : ctx.activeWallTypeId;
}
/** Einschichtig? Nur dann ist das Dicke-Feld sinnvoll (überschreibt die Schicht). */
function isSingleLayer(ctx: CommandContext): boolean {
const wt = activeWallType(ctx);
return !!wt && wt.layers.length === 1;
}
/**
* Liefert die effektive Vorschau-/Commit-Dicke: eine gelockte `thick`-Eingabe
* (nur bei einschichtigen Typen) überschreibt die Wandtyp-Dicke.
*/
function effectiveThickness(ctx: CommandContext, override: number | null): number {
if (override != null && override >= MIN_THICKNESS && isSingleLayer(ctx)) return override;
return activeWallThickness(ctx);
}
/**
* Findet einen einschichtigen Wandtyp mit gegebener Dicke (gleiches Bauteil wie
* `base`) oder erzeugt ihn. Gibt das (evtl. erweiterte) Projekt + die Typ-ID
* zurück — so bleibt die Plan-/3D-Darstellung unverändert (sie liest die Dicke
* aus den Schichten des Wandtyps).
*/
function wallTypeForThickness(
p: Project,
base: WallType,
thickness: number,
): { ops: CoreOp[]; wallTypeId: string } {
const componentId = base.layers[0].componentId;
const near = (a: number, b: number) => Math.abs(a - b) < 1e-4;
const existing = p.wallTypes.find(
(t) =>
t.layers.length === 1 &&
t.layers[0].componentId === componentId &&
near(t.layers[0].thickness, thickness),
);
if (existing) return { ops: [], wallTypeId: existing.id };
const nt: WallType = {
id: uniqueId("WT"),
name: `${base.name} ${(thickness * 100).toFixed(0)} cm`,
layers: [{ componentId, thickness }],
};
return { ops: addItems("wallTypes", [nt]), wallTypeId: nt.id };
}
interface WallIdle extends CommandState {
phase: "start";
/** Sticky Dicke-Übersteuerung (nur einschichtig); null = Wandtyp-Dicke. */
@@ -150,75 +83,40 @@ type WallCmdState = WallIdle | WallDrawing;
const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" };
/**
* Vorschau: Achs-Polylinie + Band-Vorschau je Segment (Dicke = aktiver Wandtyp) +
* HUD (Länge·Winkel des lebenden Segments). Die FERTIGE Wand rendert über die
* Bänder der schon gesetzten Segmente: sie ändern sich je Mausschritt nicht und werden nur neu gerechnet,
* wenn sich Punkte, Dicke, Projekt oder Wandtyp ändern — je Mausschritt rechnet der Kern nur das lebende
* Segment (gleich schnell bei langen Wandzügen).
*/
let fixedCache: { points: Vec2[]; thick: number | null; project: unknown; wallType: string; shapes: DraftShape[] } | null = null;
function fixedShapes(ctx: CommandContext, points: Vec2[], thick: number | null): DraftShape[] {
const c = fixedCache;
if (c && c.points === points && c.thick === thick && c.project === ctx.project && c.wallType === ctx.activeWallTypeId) return c.shapes;
const shapes = points.length >= 2 ? createPreview(ctx, { cmd: "wall", thick }, points).shapes : [];
fixedCache = { points, thick, project: ctx.project, wallType: ctx.activeWallTypeId, shapes };
return shapes;
}
/**
* Vorschau: Band (Dicke = aktiver Wandtyp bzw. gelockte Dicke) + Achse je Segment, gerechnet im Kern
* (`cmd_create.rs`), dazu HUD (Länge·Winkel des lebenden Segments). Die FERTIGE Wand rendert über die
* bestehende Wand-Darstellung — hier ist nur der Rubber-Band-Entwurf.
*/
function wallDraft(points: Vec2[], cursor: Vec2 | null, thickness: number): ToolDraft {
const all = cursor ? [...points, cursor] : points;
const preview: DraftShape[] = [];
for (let i = 0; i < all.length - 1; i++) {
const a = all[i];
const b = all[i + 1];
if (segLen(a, b) < EPS) continue;
preview.push({ kind: "poly", pts: wallCorners(a, b, thickness), closed: true });
preview.push({ kind: "line", a, b }); // Achse
}
const draft: ToolDraft = { preview, vertices: points };
function wallDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null, thick: number | null): ToolDraft {
const fixed = fixedShapes(ctx, points, thick);
const live = cursor && points.length ? createPreview(ctx, { cmd: "wall", thick }, [points[points.length - 1], cursor]).shapes : [];
const draft: ToolDraft = { preview: live.length ? [...fixed, ...live] : fixed, vertices: points };
const last = points[points.length - 1];
if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor);
return draft;
}
/**
* Hängt je Achssegment ein `Wall` des aktiven Typs ans Projekt (immutabel). Höhe
* aus dem aktiven Geschoss (floorHeight), Geschoss + Kategorie + Wandtyp aus dem
* Context. Null-Strecken werden übersprungen. Gehrung an Ecken entsteht später
* automatisch aus der Verschneidung im Kern (`joins.rs`).
* Commit: je Achssegment eine Wand des aktiven Typs (Höhe aus dem Geschoss); eine gelockte Dicke
* (einschichtig) wählt/erzeugt den passenden Wandtyp — beides im Kern (`cmd_create.rs`).
*/
function appendWalls(
p: Project,
pts: Vec2[],
ctx: CommandContext,
thickOverride: number | null,
): CoreOp[] {
const height =
ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : DEFAULT_HEIGHT;
// Dicke-Übersteuerung (nur einschichtig): passenden Wandtyp finden/erzeugen,
// damit Plan/3D — die die Dicke aus dem Wandtyp lesen — korrekt darstellen.
let typeOps: CoreOp[] = [];
let wallTypeId = activeWallTypeId(ctx);
const base = activeWallType(ctx);
if (
base &&
base.layers.length === 1 &&
thickOverride != null &&
thickOverride >= MIN_THICKNESS &&
Math.abs(thickOverride - wallTypeThickness(base)) > 1e-4
) {
const r = wallTypeForThickness(p, base, thickOverride);
typeOps = r.ops;
wallTypeId = r.wallTypeId;
}
const newWalls: Wall[] = [];
for (let i = 0; i < pts.length - 1; i++) {
const a = pts[i];
const b = pts[i + 1];
if (segLen(a, b) < EPS) continue;
newWalls.push({
id: uniqueId("W"),
type: "wall",
floorId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
start: a,
end: b,
wallTypeId,
height,
});
}
if (newWalls.length === 0) return [];
return [...typeOps, ...addItems("walls", newWalls)];
}
const appendWalls = (pts: Vec2[], ctx: CommandContext, thick: number | null) =>
createMutation(ctx, { cmd: "wall", pts: pts.map(xy), thick });
const idle = (
thickOverride: number | null = null,
@@ -244,7 +142,6 @@ export const wallCommand: Command = {
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as WallCmdState;
const thickness = effectiveThickness(ctx, s.thickOverride);
const to = s.thickOverride;
const single = isSingleLayer(ctx);
@@ -262,35 +159,35 @@ export const wallCommand: Command = {
thickOverride: to,
single,
};
return [ns, { draft: wallDraft(pts, s.cursor, thickness) }];
return [ns, { draft: wallDraft(ctx, pts, s.cursor, to) }];
}
return [{ ...s, single } as WallCmdState, { draft: wallDraft(s.points, s.cursor, thickness) }];
return [{ ...s, single } as WallCmdState, { draft: wallDraft(ctx, s.points, s.cursor, to) }];
}
if (input.kind !== "point") {
return [{ ...s, single } as WallCmdState, { draft: s.phase === "next" ? wallDraft(s.points, s.cursor, thickness) : null }];
return [{ ...s, single } as WallCmdState, { draft: s.phase === "next" ? wallDraft(ctx, s.points, s.cursor, to) : null }];
}
const pt = input.point;
if (s.phase !== "next") {
const ns: WallDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt, thickOverride: to, single };
return [ns, { draft: wallDraft([pt], pt, thickness) }];
return [ns, { draft: wallDraft(ctx, [pt], pt, to) }];
}
// Chaining: jede weitere Wand beginnt am letzten Endpunkt. Null-Strecke
// (Klick auf denselben Punkt) ignorieren — nicht abbrechen.
const last = s.points[s.points.length - 1];
if (segLen(last, pt) < EPS) {
return [{ ...s, single } as WallCmdState, { draft: wallDraft(s.points, s.cursor, thickness) }];
return [{ ...s, single } as WallCmdState, { draft: wallDraft(ctx, s.points, s.cursor, to) }];
}
const points = [...s.points, pt];
const ns: WallDrawing = { phase: "next", points, cursor: pt, lastPoint: pt, thickOverride: to, single };
return [ns, { draft: wallDraft(points, pt, thickness) }];
return [ns, { draft: wallDraft(ctx, points, pt, to) }];
},
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as WallCmdState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: WallDrawing = { ...s, cursor: point, single: isSingleLayer(ctx) };
return [ns, { draft: wallDraft(s.points, point, effectiveThickness(ctx, s.thickOverride)) }];
return [ns, { draft: wallDraft(ctx, s.points, point, s.thickOverride) }];
},
// Enter/Space/Rechtsklick: offenen Zug beenden (≥2 Punkte) und committen.
@@ -301,7 +198,7 @@ export const wallCommand: Command = {
const to = s.thickOverride;
return [
{ phase: "start", lastPoint: null, thickOverride: to, single: s.single } as WallIdle,
{ draft: null, done: true, commit: opsMutation((p) => appendWalls(p, pts, ctx, to)) },
{ draft: null, done: true, commit: appendWalls(pts, ctx, to) },
];
}
return idle(s.thickOverride, s.single);
+6 -19
View File
@@ -21,8 +21,7 @@
// Attribute-Panel wie bei jeder anderen Fläche nachträglich änderbar (kein
// Sonderfall, nur ein sinnvoller Default).
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -32,12 +31,10 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation } from "../createCore";
const EPS = 1e-6;
const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug
const MASK_COLOR = "#ffffff"; // Deckt wie Papier ab — Fläche UND Rand (unsichtbare Kontur)
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
@@ -60,18 +57,8 @@ function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendWipeout(points: Vec2[], ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: points, closed: true },
background: MASK_COLOR,
color: MASK_COLOR,
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern): geschlossene Polylinie, Fläche und Rand weiss (deckt wie Papier ab). */
const appendWipeout = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "wipeout", pts: points });
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as WipeoutIdle,
@@ -101,7 +88,7 @@ export const wipeoutCommand: Command = {
// Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet).
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendWipeout(pts, ctx) }];
}
const points = [...s.points, pt];
const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
@@ -121,7 +108,7 @@ export const wipeoutCommand: Command = {
const s = state as WipeoutState;
if (s.phase === "next" && s.points.length >= 3) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }];
return [idle()[0], { draft: null, done: true, commit: appendWipeout(pts, ctx) }];
}
return idle();
},
+12 -31
View File
@@ -5,8 +5,7 @@
// 1) „Startpunkt:" → Punkt
// 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit
import type { Drawing2D } from "../../model/types";
import { segmentHud, uniqueId } from "../../tools/types";
import { segmentHud } from "../../tools/types";
import type {
Command,
CommandContext,
@@ -17,12 +16,10 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
import { createMutation, createPreview } from "../createCore";
const EPS = 1e-6;
const DEG = Math.PI / 180;
const XLINE_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan
const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
const segAngleDeg = (a: Vec2, b: Vec2): number =>
(Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
@@ -51,32 +48,16 @@ interface XlineDrawing extends CommandState {
type XlineState = XlineIdle | XlineDrawing;
/** Vorschau: kurzes Segment PLUS Verlängerung in beide Richtungen (deutet „unendlich" an). */
function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
const preview: DraftShape[] = [];
if (cursor && segLen(a, cursor) >= EPS) {
const ux = (cursor.x - a.x) / segLen(a, cursor);
const uy = (cursor.y - a.y) / segLen(a, cursor);
preview.push({
kind: "line",
a: { x: a.x - ux * XLINE_PREVIEW_EXT_M, y: a.y - uy * XLINE_PREVIEW_EXT_M },
b: { x: cursor.x + ux * XLINE_PREVIEW_EXT_M, y: cursor.y + uy * XLINE_PREVIEW_EXT_M },
});
}
function xlineDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft {
// Vorschau (Kern): beidseitig um 30 m verlängert — die echte Länge kommt aus der Plan-Ableitung.
const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "xline" }, [a, cursor]).shapes : [];
const draft: ToolDraft = { preview, vertices: [a] };
if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor);
return draft;
}
function appendXline(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId: ctx.level.id,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "xline", a, b },
};
return addItems("drawings2d", [d]);
}
/** Commit (Kern, `cmd_draw.rs`): Konstruktionslinie durch a, b. */
const appendXline = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "xline", a, b });
export const xlineCommand: Command = {
name: "xline",
@@ -88,11 +69,11 @@ export const xlineCommand: Command = {
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as XlineState;
if (input.kind !== "point") return [s, { draft: s.phase === "end" ? xlineDraft(s.a, s.cursor) : null }];
if (input.kind !== "point") return [s, { draft: s.phase === "end" ? xlineDraft(ctx, s.a, s.cursor) : null }];
const pt = input.point;
if (s.phase !== "end") {
const next: XlineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt };
return [next, { draft: xlineDraft(pt, pt) }];
return [next, { draft: xlineDraft(ctx, pt, pt) }];
}
if (segLen(s.a, pt) < EPS) {
return [{ phase: "start", lastPoint: null }, { draft: null, done: true }];
@@ -100,15 +81,15 @@ export const xlineCommand: Command = {
const a = s.a;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: opsMutation(() => appendXline(a, pt, ctx)) },
{ draft: null, done: true, commit: appendXline(a, pt, ctx) },
];
},
onMove: (state, point): [CommandState, CommandResult] => {
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as XlineState;
if (s.phase !== "end") return [s, { draft: null }];
const next: XlineDrawing = { ...s, cursor: point };
return [next, { draft: xlineDraft(s.a, point) }];
return [next, { draft: xlineDraft(ctx, s.a, point) }];
},
onConfirm: (): [CommandState, CommandResult] => [
+81
View File
@@ -0,0 +1,81 @@
// Brücke der Zeichenbefehle zum Kern ([K4] S3, `src-tauri/core/src/cmd_create.rs`): die Befehle halten
// nur noch ihre Zustandsautomaten (Klicks, Tasten, Optionen) und die gesetzten Punkte; die neuen
// Elemente (Vorgaben aus Typen/Stilen, abgeleitete Felder, ids), die Vorschau je Mausschritt und die
// Treffer zwischen den Schritten rechnet der Kern.
import type { Project, Vec2 } from "../model/types";
import type { CommandContext, DraftShape } from "./types";
import type { ProjectMutation } from "../core";
import { cmdMutation, documentFor } from "../core/document";
import { toMarkedJson } from "../core/ops";
import { uniqueStamp } from "../tools/types";
import { decodeShapes } from "../tools/coreCmd";
/** Vorschau eines Zeichenbefehls: Formen, ob ein Commit hier etwas erzeugte, Zusatzzahlen je Befehl. */
export interface CreatePreview {
shapes: DraftShape[];
ok: boolean;
info: number[];
}
/** Kontext der Anfrage: aktive Ebene/Geschoss, Kategorie, Wandtyp. */
function ctxReq(ctx: CommandContext): object {
return {
level: ctx.level.id,
floorHeight: ctx.level.floorHeight ?? null,
cat: ctx.defaultCategoryCode,
wallType: ctx.activeWallTypeId,
};
}
/** Commit eines Zeichenbefehls: `req` = `{cmd, …}`; der Kern baut die Elemente (ids aus dem Stempel). */
export function createMutation(ctx: CommandContext, req: { cmd: string } & Record<string, unknown>): ProjectMutation {
return cmdMutation({ ...req, ctx: ctxReq(ctx), stamp: uniqueStamp() });
}
/** Punkt als Paar (Anfragen an den Kern). */
export const xy = (p: Vec2): [number, number] => [p.x, p.y];
// Je Mausschritt ändern sich meist nur die Punkte: sind Optionen und Kontext (flach verglichen, Objekte und
// Listen per Referenz) dieselben wie beim letzten Aufruf, rechnet der Kern mit den gemerkten Optionen
// (kein JSON je Mausschritt). Punkte dürfen als Paar `[x, y]` oder als `{x, y}` reisen.
let lastReq: Record<string, unknown> | null = null;
let lastCtx: { level: string; floorHeight: unknown; cat: string; wallType: string } | null = null;
function sameReq(req: Record<string, unknown>, ctx: CommandContext): boolean {
const c = lastCtx;
if (!lastReq || !c) return false;
if (c.level !== ctx.level.id || !Object.is(c.floorHeight, ctx.level.floorHeight) || c.cat !== ctx.defaultCategoryCode || c.wallType !== ctx.activeWallTypeId) return false;
const ka = Object.keys(req);
if (ka.length !== Object.keys(lastReq).length) return false;
for (const k of ka) {
const v = req[k];
// Objekte/Listen per Referenz: die Zustände der Befehle sind unveränderlich (neue Liste je Klick).
if (!Object.is(v, lastReq[k])) return false;
}
return true;
}
/** Vorschau eines Zeichenbefehls: `req` = Optionen, `pts` = die Punkte (je Befehl, zuletzt der Cursor). */
export function createPreview(ctx: CommandContext, req: { cmd: string } & Record<string, unknown>, pts: readonly Vec2[]): CreatePreview {
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;
}
let json: string | null = null;
if (!sameReq(req, ctx)) {
json = toMarkedJson({ ...req, ctx: ctxReq(ctx) });
lastReq = req;
lastCtx = { level: ctx.level.id, floorHeight: ctx.level.floorHeight, cat: ctx.defaultCategoryCode, wallType: ctx.activeWallTypeId };
}
const f = documentFor(ctx.project).createPreview(json, flat);
if (f.length < 2) return { shapes: [], ok: false, info: [] };
const n = f[1];
return { ok: f[0] === 1, info: Array.from(f.subarray(2, 2 + n)), shapes: decodeShapes(f.subarray(2 + n)) };
}
/** Treffer-Abfrage eines Zeichenbefehls (`cmd_create::query`) auf dem Dokument von `project`. */
export function createQuery<T>(project: Project, req: { q: string } & Record<string, unknown>): T {
return documentFor(project).createQuery<T>(req);
}