feat(mcp,editor): Option A+B storage + 10 agent deliverables (Phase 7)
Ships the combined filesystem/Supabase storage adapter + MCP scene lifecycle tools + Next.js API routes + editor /scene/[id] route, so an MCP save is directly openable at /scene/<id> without any injection hack. End-to-end verified: 10/10 e2e steps pass. Storage (A1/A2/A3): - SceneStore interface + error classes + slug helpers - FilesystemSceneStore at $PASCAL_DATA_DIR (defaults XDG/~/.pascal) with atomic writes, .index sidecar, optimistic locking - SupabaseSceneStore with scenes + scene_revisions tables, RLS migration SQL, mock-backed unit tests - createSceneStore(env) auto-selects based on SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY MCP tools (A4, A8, A9, A10): - save_scene / load_scene / list_scenes / delete_scene / rename_scene - list_templates / create_from_template (3 seed templates: empty-studio, two-bedroom, garden-house) - generate_variants (7 mutation kinds, seeded RNG, save=true|false) - photo_to_scene (vision sampling → scene graph → save) Editor (A5, A6): - /api/scenes + /api/scenes/[id] with RFC 7232 If-Match locking - /scene/[id] and /scenes route pages with save button, SceneLoader - Removed the window.__pascalScene dev injection hack Security + UX edges (A7, A8): - AssetUrl Zod validator: asset:// blob: data:image/ /path https: (http://localhost for dev) + PASCAL_ALLOWED_ASSET_ORIGINS env allowlist. Hardens scan.url, guide.url, item.asset.src, material.texture.url, MaterialMaps.*Map - Auto-frame camera on empty→non-empty scene transition (camera-controls:fit-scene emitter event) Shared utilities: - rehydrateSiteChildren() extracted to packages/mcp/src/lib/ and used by both create-from-template and generate-variants to work around the SiteNode.children-as-objects vs. ids inconsistency (CROSS_CUTTING §2) - Storage + MCP subpath exports added to packages/mcp/package.json (CROSS_CUTTING §4) Tests: 293 pass / 0 fail across 40 files (was 142 pre-Phase-7). Biome: clean. Phase-7 e2e script at packages/mcp/test-reports/phase7-e2e.ts: MCP HTTP + editor Next.js both point at $PASCAL_DATA_DIR = /tmp/pascal-e2e, save_scene from MCP, GET /api/scenes/<id> from editor server, /scenes list page renders all saved scenes, scene page renders SceneLoader, delete_scene works. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
42bd05db9c
commit
e8d0b13ff5
@@ -0,0 +1,295 @@
|
||||
import { beforeEach, describe, expect, test } from 'bun:test'
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
||||
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
|
||||
import { type AnyNodeId, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
|
||||
import { SceneBridge } from '../../bridge/scene-bridge'
|
||||
import {
|
||||
InMemorySceneStore,
|
||||
parseToolText,
|
||||
type StoredTextContent,
|
||||
} from '../scene-lifecycle/test-utils'
|
||||
import { registerGenerateVariants } from './generate-variants'
|
||||
|
||||
type Variant = {
|
||||
index: number
|
||||
description: string
|
||||
nodeCount: number
|
||||
sceneId?: string
|
||||
url?: string
|
||||
graph?: SceneGraph
|
||||
}
|
||||
|
||||
function emptyBase(): SceneGraph {
|
||||
return {
|
||||
nodes: {
|
||||
site_empty: {
|
||||
object: 'node',
|
||||
id: 'site_empty',
|
||||
type: 'site',
|
||||
parentId: null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
polygon: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[-5, -5],
|
||||
[5, -5],
|
||||
[5, 5],
|
||||
[-5, 5],
|
||||
],
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
} as unknown as SceneGraph['nodes'],
|
||||
rootNodeIds: ['site_empty'] as AnyNodeId[],
|
||||
}
|
||||
}
|
||||
|
||||
async function setup(): Promise<{
|
||||
client: Client
|
||||
bridge: SceneBridge
|
||||
store: InMemorySceneStore
|
||||
}> {
|
||||
const bridge = new SceneBridge()
|
||||
bridge.setScene({}, [])
|
||||
bridge.loadDefault()
|
||||
const store = new InMemorySceneStore()
|
||||
const server = new McpServer({ name: 'test', version: '0.0.0' })
|
||||
registerGenerateVariants(server, bridge, store)
|
||||
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
|
||||
const client = new Client({ name: 'test-client', version: '0.0.0' })
|
||||
await Promise.all([server.connect(srvT), client.connect(cliT)])
|
||||
return { client, bridge, store }
|
||||
}
|
||||
|
||||
describe('generate_variants', () => {
|
||||
let client: Client
|
||||
let bridge: SceneBridge
|
||||
let store: InMemorySceneStore
|
||||
|
||||
beforeEach(async () => {
|
||||
;({ client, bridge, store } = await setup())
|
||||
})
|
||||
|
||||
test('happy path: returns count variants that exercise the mutation', async () => {
|
||||
// Seed the bridge scene with some walls of known thickness.
|
||||
const base = bridge.exportJSON()
|
||||
// Find the level and add a couple of walls.
|
||||
const level = Object.values(base.nodes).find((n) => n.type === 'level')
|
||||
expect(level).toBeDefined()
|
||||
const withWalls: SceneGraph = {
|
||||
nodes: {
|
||||
...base.nodes,
|
||||
wall_1: {
|
||||
object: 'node',
|
||||
id: 'wall_1',
|
||||
type: 'wall',
|
||||
parentId: level?.id ?? null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [0, 0],
|
||||
end: [5, 0],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_2: {
|
||||
object: 'node',
|
||||
id: 'wall_2',
|
||||
type: 'wall',
|
||||
parentId: level?.id ?? null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [0, 5],
|
||||
end: [5, 5],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
} as unknown as SceneGraph['nodes'],
|
||||
rootNodeIds: base.rootNodeIds,
|
||||
}
|
||||
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
|
||||
|
||||
const result = await client.callTool({
|
||||
name: 'generate_variants',
|
||||
arguments: {
|
||||
count: 3,
|
||||
vary: ['wall-thickness'],
|
||||
seed: 42,
|
||||
},
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
expect(parsed.variants.length).toBe(3)
|
||||
for (const v of parsed.variants) {
|
||||
expect(v.graph).toBeDefined()
|
||||
// Every wall's thickness is in the allowed set.
|
||||
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
|
||||
for (const node of Object.values((v.graph as SceneGraph).nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('deterministic: same seed yields same mutation outputs', async () => {
|
||||
// Seed walls so the mutation has something to act on.
|
||||
const base = bridge.exportJSON()
|
||||
const level = Object.values(base.nodes).find((n) => n.type === 'level')
|
||||
const withWalls: SceneGraph = {
|
||||
nodes: {
|
||||
...base.nodes,
|
||||
wall_a: {
|
||||
object: 'node',
|
||||
id: 'wall_a',
|
||||
type: 'wall',
|
||||
parentId: level?.id ?? null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [0, 0],
|
||||
end: [4, 0],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_b: {
|
||||
object: 'node',
|
||||
id: 'wall_b',
|
||||
type: 'wall',
|
||||
parentId: level?.id ?? null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [0, 4],
|
||||
end: [4, 4],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
} as unknown as SceneGraph['nodes'],
|
||||
rootNodeIds: base.rootNodeIds,
|
||||
}
|
||||
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
|
||||
|
||||
const args = { count: 2, vary: ['wall-thickness'], seed: 123 }
|
||||
const r1 = await client.callTool({ name: 'generate_variants', arguments: args })
|
||||
const r2 = await client.callTool({ name: 'generate_variants', arguments: args })
|
||||
const p1 = parseToolText(r1.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
const p2 = parseToolText(r2.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
expect(p1.variants.length).toBe(p2.variants.length)
|
||||
// Compare the mutated fields (not the ids, which fresh-nanoid each time).
|
||||
function wallThicknesses(g: SceneGraph): number[] {
|
||||
return Object.values(g.nodes)
|
||||
.filter((n) => n.type === 'wall')
|
||||
.map((w) => (w as { thickness: number }).thickness)
|
||||
.sort()
|
||||
}
|
||||
for (let i = 0; i < p1.variants.length; i++) {
|
||||
const t1 = wallThicknesses(p1.variants[i]?.graph as SceneGraph)
|
||||
const t2 = wallThicknesses(p2.variants[i]?.graph as SceneGraph)
|
||||
expect(t1).toEqual(t2)
|
||||
}
|
||||
})
|
||||
|
||||
test('no-op: empty scene + wall-thickness still returns count graphs, unchanged', async () => {
|
||||
const graph = emptyBase()
|
||||
// Save, then reference by id.
|
||||
const meta = await store.save({ name: 'empty', graph })
|
||||
const result = await client.callTool({
|
||||
name: 'generate_variants',
|
||||
arguments: {
|
||||
baseSceneId: meta.id,
|
||||
count: 3,
|
||||
vary: ['wall-thickness'],
|
||||
seed: 99,
|
||||
},
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
expect(parsed.variants.length).toBe(3)
|
||||
for (const v of parsed.variants) {
|
||||
const g = v.graph as SceneGraph
|
||||
expect(g).toBeDefined()
|
||||
// No walls were present — so node counts should match the (forked) base.
|
||||
expect(Object.keys(g.nodes).length).toBe(Object.keys(graph.nodes).length)
|
||||
}
|
||||
})
|
||||
|
||||
test('save=true: each variant gets a sceneId and url', async () => {
|
||||
const result = await client.callTool({
|
||||
name: 'generate_variants',
|
||||
arguments: {
|
||||
count: 2,
|
||||
vary: ['wall-thickness'],
|
||||
seed: 55,
|
||||
save: true,
|
||||
},
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
expect(parsed.variants.length).toBe(2)
|
||||
for (const v of parsed.variants) {
|
||||
expect(typeof v.sceneId).toBe('string')
|
||||
expect(v.url).toBe(`/scene/${v.sceneId}`)
|
||||
// Inline graph should be omitted.
|
||||
expect(v.graph).toBeUndefined()
|
||||
}
|
||||
const listed = await store.list()
|
||||
expect(listed.length).toBe(2)
|
||||
})
|
||||
|
||||
test('baseSceneId not found returns an error', async () => {
|
||||
const result = await client.callTool({
|
||||
name: 'generate_variants',
|
||||
arguments: {
|
||||
baseSceneId: 'scene_does_not_exist',
|
||||
count: 2,
|
||||
vary: ['wall-thickness'],
|
||||
seed: 1,
|
||||
},
|
||||
})
|
||||
expect(result.isError).toBe(true)
|
||||
})
|
||||
|
||||
test('every returned variant validates against AnyNode', async () => {
|
||||
const result = await client.callTool({
|
||||
name: 'generate_variants',
|
||||
arguments: {
|
||||
count: 3,
|
||||
vary: ['wall-thickness', 'wall-height'],
|
||||
seed: 7,
|
||||
},
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
|
||||
variants: Variant[]
|
||||
}
|
||||
for (const v of parsed.variants) {
|
||||
const g = v.graph as SceneGraph
|
||||
for (const node of Object.values(g.nodes)) {
|
||||
const res = AnyNodeSchema.safeParse(node)
|
||||
expect(res.success).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
||||
import { forkSceneGraph, type SceneGraph } from '@pascal-app/core/clone-scene-graph'
|
||||
import { type AnyNode, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
|
||||
import { z } from 'zod'
|
||||
import type { SceneBridge } from '../../bridge/scene-bridge'
|
||||
import type { SceneStore } from '../../storage/types'
|
||||
import { ErrorCode, throwMcpError } from '../errors'
|
||||
import { applyMutation, describeVariant, type MutationKind, mulberry32 } from './mutations'
|
||||
|
||||
const MUTATION_KINDS = [
|
||||
'wall-thickness',
|
||||
'wall-height',
|
||||
'zone-labels',
|
||||
'room-proportions',
|
||||
'open-plan',
|
||||
'door-positions',
|
||||
'fence-style',
|
||||
] as const
|
||||
|
||||
export const generateVariantsInput = {
|
||||
baseSceneId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('If set, fork from this saved scene; else fork from current bridge state.'),
|
||||
count: z.number().int().min(1).max(10).default(3),
|
||||
vary: z.array(z.enum(MUTATION_KINDS)).min(1).default(['wall-thickness', 'wall-height']),
|
||||
seed: z.number().int().optional().describe('Deterministic RNG seed.'),
|
||||
save: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('If true, also save each variant via SceneStore and return ids.'),
|
||||
}
|
||||
|
||||
export const generateVariantsOutput = {
|
||||
variants: z.array(
|
||||
z.object({
|
||||
index: z.number(),
|
||||
description: z.string(),
|
||||
nodeCount: z.number(),
|
||||
sceneId: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
graph: z.any().optional(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
|
||||
/**
|
||||
* `forkSceneGraph` normalises `SiteNode.children` to string IDs, but the
|
||||
* `SiteNode` schema declares that field as an array of full `BuildingNode` /
|
||||
* `ItemNode` objects (see CROSS_CUTTING §2). To keep variants validating
|
||||
* against `AnyNode`, re-embed the site children from the flat dict.
|
||||
*
|
||||
* Pure: returns a new graph without mutating the input.
|
||||
*/
|
||||
function rehydrateSiteChildren(graph: SceneGraph): SceneGraph {
|
||||
const out: SceneGraph = {
|
||||
nodes: { ...graph.nodes },
|
||||
rootNodeIds: [...graph.rootNodeIds],
|
||||
...(graph.collections ? { collections: graph.collections } : {}),
|
||||
}
|
||||
for (const [id, node] of Object.entries(out.nodes)) {
|
||||
if (node.type !== 'site') continue
|
||||
const childrenField = (node as { children?: unknown[] }).children
|
||||
if (!Array.isArray(childrenField)) continue
|
||||
const rehydrated: AnyNode[] = []
|
||||
for (const child of childrenField) {
|
||||
if (typeof child === 'string') {
|
||||
const target = out.nodes[child as keyof typeof out.nodes]
|
||||
if (target && (target.type === 'building' || target.type === 'item')) {
|
||||
rehydrated.push(target)
|
||||
}
|
||||
} else if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
|
||||
rehydrated.push(child as AnyNode)
|
||||
}
|
||||
}
|
||||
out.nodes[id as keyof typeof out.nodes] = {
|
||||
...(node as AnyNode),
|
||||
children: rehydrated,
|
||||
} as AnyNode
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Count how many nodes in a graph fail `AnyNode` validation. Used to keep the
|
||||
* tool from returning silently corrupt variants.
|
||||
*/
|
||||
function countInvalidNodes(graph: SceneGraph): number {
|
||||
let invalid = 0
|
||||
for (const node of Object.values(graph.nodes)) {
|
||||
if (!AnyNodeSchema.safeParse(node).success) invalid++
|
||||
}
|
||||
return invalid
|
||||
}
|
||||
|
||||
export function registerGenerateVariants(
|
||||
server: McpServer,
|
||||
bridge: SceneBridge,
|
||||
store: SceneStore,
|
||||
): void {
|
||||
server.registerTool(
|
||||
'generate_variants',
|
||||
{
|
||||
title: 'Generate variants',
|
||||
description:
|
||||
'Generate N variations of a base scene by forking and applying seeded mutations. Example: "give me 5 variations of this kitchen". If `save=true`, each variant is persisted via the SceneStore and returned with an id + URL; otherwise the graph is returned inline.',
|
||||
inputSchema: generateVariantsInput,
|
||||
outputSchema: generateVariantsOutput,
|
||||
},
|
||||
async ({ baseSceneId, count, vary, seed, save }) => {
|
||||
// 1. Obtain the base SceneGraph.
|
||||
let base: SceneGraph
|
||||
let baseName = 'scene'
|
||||
if (baseSceneId) {
|
||||
const loaded = await store.load(baseSceneId)
|
||||
if (!loaded) {
|
||||
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id: baseSceneId })
|
||||
}
|
||||
base = loaded.graph
|
||||
baseName = loaded.name
|
||||
} else {
|
||||
const exported = bridge.exportJSON()
|
||||
base = {
|
||||
nodes: exported.nodes,
|
||||
rootNodeIds: exported.rootNodeIds,
|
||||
collections: exported.collections as SceneGraph['collections'],
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Seed the RNG. Default seed is a time-ish number so runs vary, but
|
||||
// tests always pass a fixed seed for determinism.
|
||||
const initialSeed = seed ?? Math.floor(Math.random() * 0xffffffff)
|
||||
|
||||
const mutations = vary as MutationKind[]
|
||||
const variants: Array<{
|
||||
index: number
|
||||
description: string
|
||||
nodeCount: number
|
||||
sceneId?: string
|
||||
url?: string
|
||||
graph?: SceneGraph
|
||||
}> = []
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
// Each variant gets its own RNG stream derived from (seed + i) so
|
||||
// results are deterministic per-index.
|
||||
const rng = mulberry32(initialSeed + i)
|
||||
|
||||
let forked: SceneGraph = forkSceneGraph(base)
|
||||
for (const kind of mutations) {
|
||||
forked = applyMutation(forked, rng, kind)
|
||||
}
|
||||
// Re-embed site children so variants match the SiteNode schema.
|
||||
forked = rehydrateSiteChildren(forked)
|
||||
|
||||
const invalidCount = countInvalidNodes(forked)
|
||||
if (invalidCount > 0) {
|
||||
throwMcpError(
|
||||
ErrorCode.InternalError,
|
||||
`variant_invalid: variant ${i} produced ${invalidCount} invalid node(s)`,
|
||||
{ index: i },
|
||||
)
|
||||
}
|
||||
|
||||
const nodeCount = Object.keys(forked.nodes).length
|
||||
const description = describeVariant(forked, mutations)
|
||||
|
||||
if (save) {
|
||||
try {
|
||||
const meta = await store.save({
|
||||
name: `${baseName}-variant-${i + 1}`,
|
||||
graph: forked,
|
||||
})
|
||||
variants.push({
|
||||
index: i,
|
||||
description,
|
||||
nodeCount,
|
||||
sceneId: meta.id,
|
||||
url: `/scene/${meta.id}`,
|
||||
})
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
throwMcpError(ErrorCode.InternalError, `save_failed: ${msg}`, { index: i })
|
||||
}
|
||||
} else {
|
||||
variants.push({ index: i, description, nodeCount, graph: forked })
|
||||
}
|
||||
}
|
||||
|
||||
const payload = { variants }
|
||||
return {
|
||||
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
|
||||
structuredContent: payload,
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
||||
import type { SceneBridge } from '../../bridge/scene-bridge'
|
||||
import type { SceneStore } from '../../storage/types'
|
||||
import { registerGenerateVariants } from './generate-variants'
|
||||
|
||||
/**
|
||||
* Register the variant-generation MCP tools against the given server. Uses the
|
||||
* supplied `SceneStore` both to load a `baseSceneId` (when provided) and to
|
||||
* persist variants when `save=true`.
|
||||
*/
|
||||
export function registerVariantTools(
|
||||
server: McpServer,
|
||||
bridge: SceneBridge,
|
||||
store: SceneStore,
|
||||
): void {
|
||||
registerGenerateVariants(server, bridge, store)
|
||||
}
|
||||
|
||||
export {
|
||||
generateVariantsInput,
|
||||
generateVariantsOutput,
|
||||
registerGenerateVariants,
|
||||
} from './generate-variants'
|
||||
export {
|
||||
applyMutation,
|
||||
describeVariant,
|
||||
type MutationKind,
|
||||
mulberry32,
|
||||
type Rng,
|
||||
} from './mutations'
|
||||
@@ -0,0 +1,409 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
|
||||
import type { AnyNodeId } from '@pascal-app/core/schema'
|
||||
import { applyMutation, mulberry32 } from './mutations'
|
||||
|
||||
function makeBaseGraph(): SceneGraph {
|
||||
const nodes: SceneGraph['nodes'] = {
|
||||
site_a: {
|
||||
object: 'node',
|
||||
id: 'site_a',
|
||||
type: 'site',
|
||||
parentId: null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
polygon: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[-10, -10],
|
||||
[10, -10],
|
||||
[10, 10],
|
||||
[-10, 10],
|
||||
],
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
building_a: {
|
||||
object: 'node',
|
||||
id: 'building_a',
|
||||
type: 'building',
|
||||
parentId: 'site_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
position: [0, 0, 0],
|
||||
rotation: [0, 0, 0],
|
||||
children: ['level_a'],
|
||||
},
|
||||
level_a: {
|
||||
object: 'node',
|
||||
id: 'level_a',
|
||||
type: 'level',
|
||||
parentId: 'building_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
children: ['wall_n', 'wall_s', 'wall_e', 'wall_w', 'wall_mid', 'zone_kitchen', 'zone_living'],
|
||||
},
|
||||
wall_n: {
|
||||
object: 'node',
|
||||
id: 'wall_n',
|
||||
type: 'wall',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-10, 10],
|
||||
end: [10, 10],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_s: {
|
||||
object: 'node',
|
||||
id: 'wall_s',
|
||||
type: 'wall',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-10, -10],
|
||||
end: [10, -10],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_e: {
|
||||
object: 'node',
|
||||
id: 'wall_e',
|
||||
type: 'wall',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [10, -10],
|
||||
end: [10, 10],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_w: {
|
||||
object: 'node',
|
||||
id: 'wall_w',
|
||||
type: 'wall',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-10, -10],
|
||||
end: [-10, 10],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
wall_mid: {
|
||||
object: 'node',
|
||||
id: 'wall_mid',
|
||||
type: 'wall',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-5, 0],
|
||||
end: [5, 0],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: ['door_mid'],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
door_mid: {
|
||||
object: 'node',
|
||||
id: 'door_mid',
|
||||
type: 'door',
|
||||
parentId: 'wall_mid',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
position: [0, 0, 0],
|
||||
rotation: [0, 0, 0],
|
||||
wallId: 'wall_mid',
|
||||
width: 0.9,
|
||||
height: 2.1,
|
||||
frameThickness: 0.05,
|
||||
frameDepth: 0.07,
|
||||
threshold: true,
|
||||
thresholdHeight: 0.02,
|
||||
hingesSide: 'left',
|
||||
swingDirection: 'inward',
|
||||
segments: [],
|
||||
handle: true,
|
||||
handleHeight: 1.05,
|
||||
handleSide: 'right',
|
||||
contentPadding: [0.04, 0.04],
|
||||
doorCloser: false,
|
||||
panicBar: false,
|
||||
panicBarHeight: 1.0,
|
||||
},
|
||||
zone_kitchen: {
|
||||
object: 'node',
|
||||
id: 'zone_kitchen',
|
||||
type: 'zone',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
name: 'Kitchen',
|
||||
polygon: [
|
||||
[-5, 0],
|
||||
[5, 0],
|
||||
[5, 10],
|
||||
[-5, 10],
|
||||
],
|
||||
color: '#ff0000',
|
||||
},
|
||||
zone_living: {
|
||||
object: 'node',
|
||||
id: 'zone_living',
|
||||
type: 'zone',
|
||||
parentId: 'level_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
name: 'Living',
|
||||
polygon: [
|
||||
[-5, -10],
|
||||
[5, -10],
|
||||
[5, 0],
|
||||
[-5, 0],
|
||||
],
|
||||
color: '#00ff00',
|
||||
},
|
||||
fence_1: {
|
||||
object: 'node',
|
||||
id: 'fence_1',
|
||||
type: 'fence',
|
||||
parentId: 'site_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-8, -8],
|
||||
end: [8, -8],
|
||||
height: 1.8,
|
||||
thickness: 0.08,
|
||||
baseHeight: 0.22,
|
||||
postSpacing: 2,
|
||||
postSize: 0.1,
|
||||
topRailHeight: 0.04,
|
||||
groundClearance: 0,
|
||||
edgeInset: 0.015,
|
||||
baseStyle: 'grounded',
|
||||
color: '#ffffff',
|
||||
style: 'slat',
|
||||
},
|
||||
} as unknown as SceneGraph['nodes']
|
||||
return {
|
||||
nodes,
|
||||
rootNodeIds: ['site_a'] as AnyNodeId[],
|
||||
}
|
||||
}
|
||||
|
||||
describe('mulberry32', () => {
|
||||
test('is deterministic for the same seed', () => {
|
||||
const a = mulberry32(42)
|
||||
const b = mulberry32(42)
|
||||
for (let i = 0; i < 10; i++) {
|
||||
expect(a()).toBe(b())
|
||||
}
|
||||
})
|
||||
test('produces values in [0, 1)', () => {
|
||||
const rng = mulberry32(7)
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const v = rng()
|
||||
expect(v).toBeGreaterThanOrEqual(0)
|
||||
expect(v).toBeLessThan(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: wall-thickness', () => {
|
||||
test('assigns every wall a thickness from the fixed set', () => {
|
||||
const rng = mulberry32(1)
|
||||
const out = applyMutation(makeBaseGraph(), rng, 'wall-thickness')
|
||||
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
|
||||
let walls = 0
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
walls++
|
||||
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
|
||||
}
|
||||
expect(walls).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test('does not mutate the input graph', () => {
|
||||
const base = makeBaseGraph()
|
||||
const before = JSON.stringify(base)
|
||||
applyMutation(base, mulberry32(5), 'wall-thickness')
|
||||
expect(JSON.stringify(base)).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: wall-height', () => {
|
||||
test('assigns every wall a height from the fixed set', () => {
|
||||
const rng = mulberry32(2)
|
||||
const out = applyMutation(makeBaseGraph(), rng, 'wall-height')
|
||||
const allowed = new Set([2.4, 2.6, 2.7, 3.0])
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
expect(allowed.has((node as { height: number }).height)).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: zone-labels', () => {
|
||||
test('shuffles labels but preserves the set', () => {
|
||||
const base = makeBaseGraph()
|
||||
const rng = mulberry32(3)
|
||||
const out = applyMutation(base, rng, 'zone-labels')
|
||||
const before = new Set<string>()
|
||||
for (const node of Object.values(base.nodes)) {
|
||||
if (node.type === 'zone') before.add((node as { name: string }).name)
|
||||
}
|
||||
const after = new Set<string>()
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type === 'zone') after.add((node as { name: string }).name)
|
||||
}
|
||||
expect(after).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: room-proportions', () => {
|
||||
test('only nudges interior walls, leaves perimeter alone', () => {
|
||||
const base = makeBaseGraph()
|
||||
const rng = mulberry32(4)
|
||||
const out = applyMutation(base, rng, 'room-proportions')
|
||||
// Perimeter wall should be unchanged.
|
||||
const n = out.nodes.wall_n as { start: [number, number]; end: [number, number] }
|
||||
expect(n.start).toEqual([-10, 10])
|
||||
expect(n.end).toEqual([10, 10])
|
||||
// Interior wall should (usually) be different.
|
||||
const mid = out.nodes.wall_mid as { start: [number, number]; end: [number, number] }
|
||||
const midBase = base.nodes.wall_mid as { start: [number, number]; end: [number, number] }
|
||||
const changed =
|
||||
mid.start[0] !== midBase.start[0] ||
|
||||
mid.start[1] !== midBase.start[1] ||
|
||||
mid.end[0] !== midBase.end[0] ||
|
||||
mid.end[1] !== midBase.end[1]
|
||||
expect(changed).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: open-plan', () => {
|
||||
test('removes exactly one interior wall and its attached openings', () => {
|
||||
const base = makeBaseGraph()
|
||||
const baseWallCount = Object.values(base.nodes).filter((n) => n.type === 'wall').length
|
||||
const rng = mulberry32(5)
|
||||
const out = applyMutation(base, rng, 'open-plan')
|
||||
const afterWallCount = Object.values(out.nodes).filter((n) => n.type === 'wall').length
|
||||
expect(afterWallCount).toBe(baseWallCount - 1)
|
||||
// Interior wall `wall_mid` had a door — both should be gone.
|
||||
expect(out.nodes.wall_mid).toBeUndefined()
|
||||
expect(out.nodes.door_mid).toBeUndefined()
|
||||
})
|
||||
|
||||
test('skips gracefully when there are no interior walls', () => {
|
||||
const graph: SceneGraph = {
|
||||
nodes: {
|
||||
site_a: {
|
||||
object: 'node',
|
||||
id: 'site_a',
|
||||
type: 'site',
|
||||
parentId: null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
polygon: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[-10, -10],
|
||||
[10, -10],
|
||||
[10, 10],
|
||||
[-10, 10],
|
||||
],
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
wall_n: {
|
||||
object: 'node',
|
||||
id: 'wall_n',
|
||||
type: 'wall',
|
||||
parentId: 'site_a',
|
||||
visible: true,
|
||||
metadata: {},
|
||||
start: [-10, 10],
|
||||
end: [10, 10],
|
||||
thickness: 0.1,
|
||||
height: 2.5,
|
||||
children: [],
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
},
|
||||
} as unknown as SceneGraph['nodes'],
|
||||
rootNodeIds: ['site_a'] as AnyNodeId[],
|
||||
}
|
||||
const out = applyMutation(graph, mulberry32(9), 'open-plan')
|
||||
expect(Object.keys(out.nodes)).toEqual(Object.keys(graph.nodes))
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: door-positions', () => {
|
||||
test('sets every door wallT in [0.2, 0.8]', () => {
|
||||
const rng = mulberry32(6)
|
||||
const out = applyMutation(makeBaseGraph(), rng, 'door-positions')
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'door') continue
|
||||
const t = (node as { wallT?: number }).wallT
|
||||
expect(typeof t).toBe('number')
|
||||
expect(t as number).toBeGreaterThanOrEqual(0.2)
|
||||
expect(t as number).toBeLessThanOrEqual(0.8)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: fence-style', () => {
|
||||
test('sets every fence style to one of privacy/slat/rail', () => {
|
||||
const rng = mulberry32(7)
|
||||
const out = applyMutation(makeBaseGraph(), rng, 'fence-style')
|
||||
const allowed = new Set(['privacy', 'slat', 'rail'])
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'fence') continue
|
||||
expect(allowed.has((node as { style: string }).style)).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyMutation: no-op behaviour', () => {
|
||||
test('wall-thickness on a graph with no walls leaves nodes unchanged', () => {
|
||||
const graph: SceneGraph = {
|
||||
nodes: {
|
||||
site_a: {
|
||||
object: 'node',
|
||||
id: 'site_a',
|
||||
type: 'site',
|
||||
parentId: null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
polygon: {
|
||||
type: 'polygon',
|
||||
points: [
|
||||
[-1, -1],
|
||||
[1, -1],
|
||||
[1, 1],
|
||||
[-1, 1],
|
||||
],
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
} as unknown as SceneGraph['nodes'],
|
||||
rootNodeIds: ['site_a'] as AnyNodeId[],
|
||||
}
|
||||
const out = applyMutation(graph, mulberry32(8), 'wall-thickness')
|
||||
expect(JSON.stringify(out.nodes)).toBe(JSON.stringify(graph.nodes))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,331 @@
|
||||
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
|
||||
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
|
||||
|
||||
/** Mutation kinds handled by `applyMutation`. */
|
||||
export type MutationKind =
|
||||
| 'wall-thickness'
|
||||
| 'wall-height'
|
||||
| 'zone-labels'
|
||||
| 'room-proportions'
|
||||
| 'open-plan'
|
||||
| 'door-positions'
|
||||
| 'fence-style'
|
||||
|
||||
/** Deterministic 32-bit RNG. */
|
||||
export type Rng = () => number
|
||||
|
||||
/**
|
||||
* Tiny PRNG. Returns a function that produces uniformly distributed floats in
|
||||
* [0, 1). Source: https://stackoverflow.com/a/47593316/17118
|
||||
*/
|
||||
export function mulberry32(seed: number): Rng {
|
||||
let state = seed | 0
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) | 0
|
||||
let t = state
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1)
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
/** Pick a random element from a non-empty array. */
|
||||
function pickFrom<T>(rng: Rng, values: readonly T[]): T {
|
||||
const idx = Math.floor(rng() * values.length)
|
||||
return values[Math.min(idx, values.length - 1)] as T
|
||||
}
|
||||
|
||||
/** Shallow clone a scene graph: nodes are copied one level deep, node dict is fresh. */
|
||||
function cloneGraph(graph: SceneGraph): SceneGraph {
|
||||
const clonedNodes: Record<AnyNodeId, AnyNode> = {} as Record<AnyNodeId, AnyNode>
|
||||
for (const [id, node] of Object.entries(graph.nodes)) {
|
||||
// structuredClone so sub-objects (arrays, tuples, metadata) are independent.
|
||||
clonedNodes[id as AnyNodeId] = structuredClone(node) as AnyNode
|
||||
}
|
||||
return {
|
||||
nodes: clonedNodes,
|
||||
rootNodeIds: [...graph.rootNodeIds],
|
||||
...(graph.collections ? { collections: structuredClone(graph.collections) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const WALL_THICKNESS_OPTIONS = [0.1, 0.15, 0.2, 0.25] as const
|
||||
const WALL_HEIGHT_OPTIONS = [2.4, 2.6, 2.7, 3.0] as const
|
||||
const FENCE_STYLES = ['privacy', 'slat', 'rail'] as const
|
||||
|
||||
/** Fisher–Yates shuffle in place using the provided RNG. */
|
||||
function shuffleInPlace<T>(arr: T[], rng: Rng): void {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rng() * (i + 1))
|
||||
const tmp = arr[i] as T
|
||||
arr[i] = arr[j] as T
|
||||
arr[j] = tmp
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute 2D bounds (min/max x/z) of the first `site` node's polygon points,
|
||||
* or `null` if no site is present.
|
||||
*/
|
||||
function siteBounds(
|
||||
graph: SceneGraph,
|
||||
): { minX: number; maxX: number; minZ: number; maxZ: number } | null {
|
||||
for (const node of Object.values(graph.nodes)) {
|
||||
if (node.type !== 'site') continue
|
||||
const pts = (node as { polygon?: { points?: Array<[number, number]> } }).polygon?.points
|
||||
if (!pts || pts.length === 0) continue
|
||||
let minX = Infinity
|
||||
let maxX = -Infinity
|
||||
let minZ = Infinity
|
||||
let maxZ = -Infinity
|
||||
for (const [x, z] of pts) {
|
||||
if (x < minX) minX = x
|
||||
if (x > maxX) maxX = x
|
||||
if (z < minZ) minZ = z
|
||||
if (z > maxZ) maxZ = z
|
||||
}
|
||||
if (!Number.isFinite(minX)) continue
|
||||
return { minX, maxX, minZ, maxZ }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Heuristic: a wall is a perimeter wall if either of its endpoints sits close
|
||||
* to the site polygon's bounding rectangle (within `epsilon`). Returns `false`
|
||||
* if there is no site polygon (treat everything as interior so the mutations
|
||||
* still exercise something on partial scenes).
|
||||
*/
|
||||
function isPerimeterWall(
|
||||
wall: AnyNode & { start?: [number, number]; end?: [number, number] },
|
||||
bounds: { minX: number; maxX: number; minZ: number; maxZ: number } | null,
|
||||
epsilon = 0.01,
|
||||
): boolean {
|
||||
if (!bounds || !wall.start || !wall.end) return false
|
||||
const onBound = (x: number, z: number): boolean =>
|
||||
Math.abs(x - bounds.minX) <= epsilon ||
|
||||
Math.abs(x - bounds.maxX) <= epsilon ||
|
||||
Math.abs(z - bounds.minZ) <= epsilon ||
|
||||
Math.abs(z - bounds.maxZ) <= epsilon
|
||||
const [sx, sz] = wall.start
|
||||
const [ex, ez] = wall.end
|
||||
return onBound(sx, sz) || onBound(ex, ez)
|
||||
}
|
||||
|
||||
function applyWallThickness(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
;(node as { thickness?: number }).thickness = pickFrom(rng, WALL_THICKNESS_OPTIONS)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyWallHeight(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
;(node as { height?: number }).height = pickFrom(rng, WALL_HEIGHT_OPTIONS)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyZoneLabels(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
const zoneNodes: Array<AnyNode & { name?: string }> = []
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type === 'zone') zoneNodes.push(node as AnyNode & { name?: string })
|
||||
}
|
||||
if (zoneNodes.length < 2) return out
|
||||
const labels = zoneNodes.map((z) => z.name ?? '')
|
||||
shuffleInPlace(labels, rng)
|
||||
for (let i = 0; i < zoneNodes.length; i++) {
|
||||
;(zoneNodes[i] as { name?: string }).name = labels[i]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyRoomProportions(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
const bounds = siteBounds(out)
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
const wall = node as AnyNode & {
|
||||
start?: [number, number]
|
||||
end?: [number, number]
|
||||
}
|
||||
if (!wall.start || !wall.end) continue
|
||||
if (isPerimeterWall(wall, bounds)) continue
|
||||
// Nudge each endpoint by ±10% of its current value.
|
||||
const nudge = (v: number): number => v * (1 + (rng() * 2 - 1) * 0.1)
|
||||
const clampX = (v: number): number =>
|
||||
bounds ? Math.min(bounds.maxX, Math.max(bounds.minX, v)) : v
|
||||
const clampZ = (v: number): number =>
|
||||
bounds ? Math.min(bounds.maxZ, Math.max(bounds.minZ, v)) : v
|
||||
const [sx, sz] = wall.start
|
||||
const [ex, ez] = wall.end
|
||||
wall.start = [clampX(nudge(sx)), clampZ(nudge(sz))]
|
||||
wall.end = [clampX(nudge(ex)), clampZ(nudge(ez))]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyOpenPlan(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
const bounds = siteBounds(out)
|
||||
const interiorWallIds: AnyNodeId[] = []
|
||||
for (const [id, node] of Object.entries(out.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
if (isPerimeterWall(node as AnyNode, bounds)) continue
|
||||
interiorWallIds.push(id as AnyNodeId)
|
||||
}
|
||||
if (interiorWallIds.length === 0) return out
|
||||
const targetId = interiorWallIds[Math.floor(rng() * interiorWallIds.length)] as AnyNodeId
|
||||
// Collect any openings attached to this wall so we can drop them too.
|
||||
const attached: AnyNodeId[] = []
|
||||
for (const [attId, node] of Object.entries(out.nodes)) {
|
||||
if ((node as { wallId?: string }).wallId === targetId) attached.push(attId as AnyNodeId)
|
||||
}
|
||||
const removal = new Set<AnyNodeId>([targetId, ...attached])
|
||||
// Drop from nodes.
|
||||
for (const id of removal) delete out.nodes[id]
|
||||
// Drop from rootNodeIds (unlikely for walls, but consistent).
|
||||
out.rootNodeIds = out.rootNodeIds.filter((id) => !removal.has(id))
|
||||
// Drop references from any parent's `children` array.
|
||||
for (const parent of Object.values(out.nodes)) {
|
||||
if (!('children' in parent) || !Array.isArray((parent as { children?: unknown[] }).children)) {
|
||||
continue
|
||||
}
|
||||
const children = (parent as { children: unknown[] }).children
|
||||
;(parent as { children: unknown[] }).children = children.filter((child) => {
|
||||
if (typeof child === 'string') return !removal.has(child as AnyNodeId)
|
||||
if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
|
||||
return !removal.has((child as { id: AnyNodeId }).id)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyDoorPositions(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
// Group doors by their parent wall so we can space them out and skip collisions.
|
||||
const doorsByWall = new Map<string, Array<AnyNode & { wallT?: number; wallId?: string }>>()
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'door') continue
|
||||
const wallId = (node as { wallId?: string }).wallId
|
||||
if (!wallId) continue
|
||||
let list = doorsByWall.get(wallId)
|
||||
if (!list) {
|
||||
list = []
|
||||
doorsByWall.set(wallId, list)
|
||||
}
|
||||
list.push(node as AnyNode & { wallT?: number; wallId?: string })
|
||||
}
|
||||
for (const [, doors] of doorsByWall) {
|
||||
// Minimum separation along the parametric wall axis — rough keep-away to
|
||||
// avoid obvious overlaps.
|
||||
const minGap = 0.15
|
||||
const usedTs: number[] = []
|
||||
for (const door of doors) {
|
||||
let attempts = 0
|
||||
let t = 0.5
|
||||
while (attempts < 8) {
|
||||
t = 0.2 + rng() * 0.6 // [0.2, 0.8]
|
||||
const collides = usedTs.some((u) => Math.abs(u - t) < minGap)
|
||||
if (!collides) break
|
||||
attempts++
|
||||
}
|
||||
// If we still collide after 8 attempts, skip this door (leave it alone).
|
||||
if (usedTs.some((u) => Math.abs(u - t) < minGap)) continue
|
||||
usedTs.push(t)
|
||||
;(door as { wallT?: number }).wallT = t
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function applyFenceStyle(graph: SceneGraph, rng: Rng): SceneGraph {
|
||||
const out = cloneGraph(graph)
|
||||
let i = 0
|
||||
for (const node of Object.values(out.nodes)) {
|
||||
if (node.type !== 'fence') continue
|
||||
// Use rng to choose a rotation offset so each call can produce a different
|
||||
// starting point even when called multiple times with the same base.
|
||||
const offset = Math.floor(rng() * FENCE_STYLES.length)
|
||||
const style = FENCE_STYLES[(i + offset) % FENCE_STYLES.length]
|
||||
;(node as { style?: string }).style = style
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Pure: apply a single mutation and return a fresh graph. */
|
||||
export function applyMutation(graph: SceneGraph, rng: Rng, kind: MutationKind): SceneGraph {
|
||||
switch (kind) {
|
||||
case 'wall-thickness':
|
||||
return applyWallThickness(graph, rng)
|
||||
case 'wall-height':
|
||||
return applyWallHeight(graph, rng)
|
||||
case 'zone-labels':
|
||||
return applyZoneLabels(graph, rng)
|
||||
case 'room-proportions':
|
||||
return applyRoomProportions(graph, rng)
|
||||
case 'open-plan':
|
||||
return applyOpenPlan(graph, rng)
|
||||
case 'door-positions':
|
||||
return applyDoorPositions(graph, rng)
|
||||
case 'fence-style':
|
||||
return applyFenceStyle(graph, rng)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable summary of the mutations applied to a variant. Reads the
|
||||
* interesting fields from the graph (e.g. first wall's thickness/height).
|
||||
*/
|
||||
export function describeVariant(graph: SceneGraph, mutations: readonly MutationKind[]): string {
|
||||
const parts: string[] = []
|
||||
if (mutations.includes('wall-thickness')) {
|
||||
const t = firstWallField(graph, 'thickness')
|
||||
if (t !== null) parts.push(`wall thickness ${t}m`)
|
||||
}
|
||||
if (mutations.includes('wall-height')) {
|
||||
const h = firstWallField(graph, 'height')
|
||||
if (h !== null) parts.push(`wall height ${h}m`)
|
||||
}
|
||||
if (mutations.includes('zone-labels')) {
|
||||
const names: string[] = []
|
||||
for (const node of Object.values(graph.nodes)) {
|
||||
if (node.type === 'zone') names.push((node as { name?: string }).name ?? '')
|
||||
}
|
||||
if (names.length > 0) parts.push(`zones [${names.join(', ')}]`)
|
||||
}
|
||||
if (mutations.includes('room-proportions')) parts.push('room proportions nudged')
|
||||
if (mutations.includes('open-plan')) parts.push('open-plan')
|
||||
if (mutations.includes('door-positions')) parts.push('doors repositioned')
|
||||
if (mutations.includes('fence-style')) {
|
||||
const s = firstFenceField(graph, 'style')
|
||||
if (s !== null) parts.push(`fence style ${s}`)
|
||||
}
|
||||
return parts.length > 0 ? parts.join(', ') : 'no-op'
|
||||
}
|
||||
|
||||
function firstWallField(graph: SceneGraph, field: 'thickness' | 'height'): number | null {
|
||||
for (const node of Object.values(graph.nodes)) {
|
||||
if (node.type !== 'wall') continue
|
||||
const v = (node as Record<string, unknown>)[field]
|
||||
if (typeof v === 'number') return v
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function firstFenceField(graph: SceneGraph, field: 'style'): string | null {
|
||||
for (const node of Object.values(graph.nodes)) {
|
||||
if (node.type !== 'fence') continue
|
||||
const v = (node as Record<string, unknown>)[field]
|
||||
if (typeof v === 'string') return v
|
||||
}
|
||||
return null
|
||||
}
|
||||
Reference in New Issue
Block a user