diff --git a/A00_Common/design/design_pipeline_page.ts b/A00_Common/design/design_pipeline_page.ts index 53974f7fe..976fd250e 100644 --- a/A00_Common/design/design_pipeline_page.ts +++ b/A00_Common/design/design_pipeline_page.ts @@ -38,6 +38,7 @@ import type { import { useDesignStore, type DesignStoreValues } from "./design_store"; import { followStructures, + placeOnLine, type FollowingStructure, } from "../../common_util/common_util_route_follow"; import { fetchDetailPipePoints } from "../../B04_PreProcess/B04_PreProcess_Api_Fetch"; @@ -291,23 +292,42 @@ function createPagePipeline( const groundDeps = groundStageDeps(projectId); const crossStage = createCrossStage({ grid: groundDeps.grid }); // 미교차 넓힘 = 같은 지형 격자(349-0j) const haulStage = createHaulStage(projectId, () => savedSource().routeId ?? undefined); + const followStage = createFollowStage({ + savedLine, + saved: () => { + const before = beforeDraft ?? facilitiesNow(); + return { + pipes: before.pipes ?? savedPipes, + structures: before.structures ?? savedStructures, + alignment: savedEdits(), + }; + }, + }); + /** 좌표 없는 관 · 구조물(세션 초안 — 배수유역도 · 구조물 목록이 정본 PUT 꼴로 씀)은 앞 노선 위 그 누가거리 + * 자리에서 따라감 — 안 붙이면 측점이 그대로 남음(349-0u). */ + const placed = (list: unknown, line: Vertex[]): unknown => + Array.isArray(list) + ? placeOnLine( + list as FollowingStructure[], + line.map(([x, y]) => ({ x, y })), + ) + : list; const pipe = createDesignPipeline({ stages: { route: createRouteStage({ minRadiusM: () => plan?.min_radius_m ?? 0, savedLine: () => plan && { line: savedLine()!, curves: savedCurves() }, }), - follow: createFollowStage({ - savedLine, - saved: () => { - const before = beforeDraft ?? facilitiesNow(); - return { - pipes: before.pipes ?? savedPipes, - structures: before.structures ?? savedStructures, - alignment: savedEdits(), - }; - }, - }), + follow: (ctx) => { + const line = ctx.before.route?.line ?? savedLine() ?? []; + const { pipes, structures } = ctx.inputs; + const inputs = { + ...ctx.inputs, + pipes: placed(pipes, line), + structures: placed(structures, line), + }; + return followStage({ ...ctx, inputs }); + }, stations: createStationsStage({ intervalM: options.stationIntervalM, types: () => types }), ground: createGroundStage(groundDeps), planline: createPlanlineStage({ savedBase: () => savedSource().base, savedLine }), diff --git a/common_util/common_util_route_follow.ts b/common_util/common_util_route_follow.ts index 3736d9f2d..6cbb10665 100644 --- a/common_util/common_util_route_follow.ts +++ b/common_util/common_util_route_follow.ts @@ -9,6 +9,7 @@ * - `followStructures` ↔ 파이썬 `common_util_route_follow.follow_structures`(+ 0 ~ 연장 자름 · * 노선과 거리 · `STRUCTURE_ROUTE_DRIFT_MAX_M` 넘으면 「노선에서 멀어짐」 · 버리지 않음). * - `projectOnPolyline` = shapely `LineString.project`(가장 가까운 첫 선분) · `distance`. + * - `placeOnLine` 은 TS 만 — 좌표 없는 세션 초안(정본 PUT 꼴)을 따라가기 전 노선 위 자리로(349-0u). * 거울 시험 = resources/tester/test_344_2_route_pairs.py. * ========================================================================== */ @@ -46,6 +47,29 @@ export function projectOnPolyline( return best && walked > 0 ? { ...best, length_m: walked } : null; } +/** 좌표 없는 관 · 구조물(세션 초안 = 정본 PUT 꼴 · 좌표 뺌)에 그 누가거리의 `line` 위 자리를 붙인 사본 — + * 좌표가 있거나 누가거리가 없으면 그대로(같은 객체). 연장 밖 누가거리는 끝 선분 위로 자름. */ +export function placeOnLine( + items: ReadonlyArray, + line: ReadonlyArray, +): S[] { + return items.map((item) => { + if ((item.x != null && item.y != null) || item.chainage_m == null) return item; + let walked = 0; + for (let index = 1; index < line.length; index += 1) { + const a = line[index - 1]; + const b = line[index]; + const span = Math.hypot(b.x - a.x, b.y - a.y); + if (span > 0 && (walked + span >= item.chainage_m || index === line.length - 1)) { + const t = Math.min(1, Math.max(0, (item.chainage_m - walked) / span)); + return { ...item, x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; + } + walked += span; + } + return item; + }); +} + export interface FollowingPoint { chainage_m: number; x?: number | null; diff --git a/resources/tester/helper_349_0u_follow_draft_xy.cjs b/resources/tester/helper_349_0u_follow_draft_xy.cjs new file mode 100644 index 000000000..4b0d4e7ef --- /dev/null +++ b/resources/tester/helper_349_0u_follow_draft_xy.cjs @@ -0,0 +1,232 @@ +/* PLAN 349-0u sub7 헬퍼 — 세션 관 · 구조물 초안에 좌표가 없어도(배수유역도 · 구조물 목록이 정본 PUT 꼴로 씀) + * 앞쪽 꺾임점을 끌면 follow 가 새 측점을 가게에 바로 · 되돌리기 = 초안 값 · 다시하기 = 다시 밂 · 조작 하나 = + * 묶음 한 번. 나머지 틀 = `helper_349_0d_follow_store.cjs` 그대로. 짝 = `test_349_0u_follow_draft_xy.py`. */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); +const CATALOG = require("./helper_322_catalog_module.cjs"); + +const ROOT = path.join(__dirname, "..", ".."); +const job = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); + +function memoryStorage() { + const map = new Map(); + return { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => map.set(key, String(value)), + removeItem: (key) => map.delete(key), + key: (index) => [...map.keys()][index] ?? null, + get length() { + return map.size; + }, + }; +} +globalThis.window = { + sessionStorage: memoryStorage(), + localStorage: memoryStorage(), + setTimeout, + clearTimeout, +}; + +// 흙 배분 서버 — 늦게 답함 · 끊기면 버림 +globalThis.fetch = (url, init) => + new Promise((resolve, reject) => { + const timer = setTimeout( + () => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }), + 20, + ); + init.signal.addEventListener("abort", () => { + clearTimeout(timer); + reject(new Error("aborted")); + }); + }); + +const STUBS = {}; +const cache = new Map(); +function loadTs(full) { + if (cache.has(full)) return cache.get(full); + const js = ts.transpileModule(fs.readFileSync(full, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const box = { exports: {} }; + cache.set(full, box.exports); + const localRequire = (request) => { + if (CATALOG.isCatalogRequest(request)) return CATALOG; + const key = Object.keys(STUBS).find((name) => request.endsWith(name)); + if (key) return STUBS[key]; + if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" }; + if (request.startsWith("@util/")) + return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`)); + if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`)); + return require(request); + }; + new Function("exports", "module", "require", js)(box.exports, box, localRequire); + return box.exports; +} +const load = (...parts) => loadTs(path.join(ROOT, ...parts)); + +const sampler = load("common_util", "common_util_surface_sampler.ts"); +const bytes = fs.readFileSync(process.argv[3]); +const grid = sampler.parseDtmGrid( + bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), +); +const local = { grid, design: "las" }; + +STUBS["B05_Profile_Api_Replan"] = { + analysisTerrain: () => "las", + fetchRoutePlan: async () => ({ + planned: job.line, + curves: job.curves, + min_radius_m: job.minRadius, + station_snap: job.stationSnap, + }), +}; +STUBS["B05_Profile_Api_Structures"] = { + fetchStructures: async () => ({ structures: job.structures }), + fetchStructureTypes: async () => job.types, +}; +STUBS["B05_Profile_Api_TerrainGrid"] = { + loadDesignTerrainGrid: async () => local, + groundStageDeps: () => ({ grid: () => local, remote: async () => [] }), +}; +STUBS["B04_PreProcess_Api_Fetch"] = { + fetchDetailPipePoints: async () => ({ + pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })), + }), +}; +STUBS["B06_Section_UI_Standard_Panel"] = { + effectiveStandardCross: () => job.standard, + readRockBoundaryDefault: () => -0.5, +}; + +const pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); +const storeMod = load("A00_Common", "design", "design_store.ts"); +const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); +const page = load("A00_Common", "b_page_state.ts"); + +const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); +const runs = () => globalThis.__aisloPipeline?.runs ?? []; +/** 묶음이 조용해질 때까지 — 마지막 기록이 끝나고 새 기록이 더 안 생김(고리면 계속 생김). */ +async function quiet() { + let seen = -1; + for (let i = 0; i < 400; i += 1) { + await tick(15); + const last = runs()[runs().length - 1]; + const count = runs().length; + if (count === seen && (!last || last.outcome !== "running")) return; + seen = count; + } + throw new Error("묶음이 조용해지지 않음"); +} +const n = job.nodes.length; +const draftOf = (nodes) => ({ + nodes, + curveOn: Array(n).fill(true), + curveRadius: Array(n).fill(null), + curveLock: Array(n).fill(null), + curveArc: Array(n).fill(null), + stationSnap: job.stationSnap, +}); +const shift = (index, dx, dy) => + job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node)); +const chainagesOf = (stations) => (stations ?? []).map((s) => s.chainageM); + +const P = "proj-3490u"; +const ids = (list) => (list ?? []).map((item) => [item.id ?? item.structure_id, item.chainage_m]); +const lengthOf = (line) => + (line ?? []).reduce( + (sum, p, i) => (i ? sum + Math.hypot(p[0] - line[i - 1][0], p[1] - line[i - 1][1]) : 0), + 0, + ); + +async function run() { + window.localStorage.setItem("frd_current_project_id", P); + const savedAlignment = job.detail.longitudinal.profile_alignment; + const savedBase = alignment.toAlignmentBase(savedAlignment); + const followed = []; + const link = { + pipelineSource: () => ({ + base: savedBase, + edits: savedAlignment.edits, + detail: job.detail, + routeId: 7, + }), + adoptPipeline: (base, edits, draft) => + pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits), + redraw: () => undefined, + side: null, + }; + const store = storeMod.useDesignStore(P, null); + // 세션 초안 = 정본 PUT 꼴(좌표 뺌) — 배수유역도 · 구조물 목록이 열 때 · 고칠 때 씀 + const draftPipes = job.pipes.map(({ x: _x, y: _y, ...pipe }) => pipe); + const draftStructures = job.structures.map(({ x: _x, y: _y, ...item }) => item); + store.set("pipes", draftPipes); + store.set("structures", draftStructures); + const bridge = pageMod.routeDraftBridge(P, link, { + stationIntervalM: job.interval, + onFacilitiesFollowed: (far) => followed.push(far), + }); + pageMod.pipelineEarthwork(P, { conversion: job.conversion }); + await quiet(); + const pipe = pageMod.pagePipeline(P); + const savedLength = lengthOf(pipe.output("route")?.line); + const open = { + pipes: ids(store.get("pipes")), + structures: ids(store.get("structures")), + followed: [...followed], + }; + const snapshot = {}; + for (let i = 0; i < window.sessionStorage.length; i += 1) { + const key = window.sessionStorage.key(i); + snapshot[key] = window.sessionStorage.getItem(key); + } + const step = async (edit) => { + const mark = runs().length; + const before = followed.length; + bridge.edited(edit); + await quiet(); + return { + runs: runs() + .slice(mark) + .map((r) => r.sources), + pipes: ids(store.get("pipes")), + structures: ids(store.get("structures")), + length: lengthOf(pipe.output("route")?.line), + followed: followed.slice(before), + blocked: pipe.blockedWrites, + }; + }; + // 앞쪽(시작 쪽) 꺾임점을 크게 끌어 놓음 — 그 뒤 관 · 구조물은 길이가 는 만큼 뒤로 + const dragged = draftOf(shift(1, job.dx, job.dy)); + const drag = await step(dragged); + // 되돌리기 — 사진첩이 세션을 되쓴 뒤 초안 없음 + for (const key of Object.keys(snapshot)) window.sessionStorage.setItem(key, snapshot[key]); + for (let i = window.sessionStorage.length - 1; i >= 0; i -= 1) { + const key = window.sessionStorage.key(i); + if (!(key in snapshot)) window.sessionStorage.removeItem(key); + } + const undo = await step(null); + const redo = await step(dragged); + const undo2 = await step(null); + pageMod.disposePagePipeline(P); + return { + savedLength, + open, + drag, + undo, + redo, + undo2, + draftPipes: ids(draftPipes), + draftStructures: ids(draftStructures), + }; +} + +run() + .then((out) => { + process.stdout.write(JSON.stringify(out)); + process.exit(0); + }) + .catch((error) => { + process.stderr.write(String(error && error.stack ? error.stack : error)); + process.exit(1); + }); diff --git a/resources/tester/test_349_0u_follow_draft_xy.py b/resources/tester/test_349_0u_follow_draft_xy.py new file mode 100644 index 000000000..a7a9219b0 --- /dev/null +++ b/resources/tester/test_349_0u_follow_draft_xy.py @@ -0,0 +1,167 @@ +"""PLAN 349-0u sub7 — 세션 관 · 구조물 초안에 좌표가 없어도 노선 따라 측점이 밀림(349-0d 되살림). + +· 세션 초안 = 정본 PUT 꼴(좌표 뺌) — 앞쪽 꺾임점을 크게 끌면 그 뒤 관 · 구조물 측점이 + 길이 는 만큼 뒤로 +· 되돌리기 = 초안 값 그대로 · 다시하기 = 다시 밂 · 조작 하나 = 묶음 한 번 · 입력 쓰기 막음 0 +짝: `helper_349_0u_follow_draft_xy.cjs`(실제 TS 를 Node 로 · 서버 창구만 가짜 · 검증_sub7). +""" + +from __future__ import annotations + +import csv +import json +import math +import subprocess +import sys +import tempfile +from pathlib import Path + +import pytest + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from B05_Profile.B05_Profile_Structures_Schema import structure_type_map # noqa: E402 +from common_util.common_util_surface_sampler import dtm_grid_bytes # noqa: E402 +from config.config_system_design import STANDARD_CROSS_SECTION # noqa: E402 + +pytestmark = pytest.mark.skipif( + not (ROOT / "config" / "node_modules" / "typescript").is_dir(), + reason="프론트엔드 의존성 미설치", +) + +PROJECT = ROOT / "storage/1/3/6d3b2812-6d5a-4168-a932-40e4ae303d5a" # 검증_sub7 +ROUTE = PROJECT / "B05_Profile/route" +SECTION = PROJECT / "B06_Section" +GRID = PROJECT / "B04_PreProcess/models/dtm_classification_smooth.npz" +ONES = {g: {"loose": 1.0, "compacted": 1.0} for g in ("soil", "ripping_rock", "blasting_rock")} + + +def _csv(path: Path) -> list[list[float]]: + with path.open(encoding="utf-8") as handle: + return [[float(r["x"]), float(r["y"])] for r in csv.DictReader(handle)] + + +def _json(path: Path): + return json.loads(path.read_text(encoding="utf-8")) + + +def _structure(sid: str, line: list[list[float]], ratio: float, off: float) -> dict: + """노선 위(off 0) · 옆(off m) 점 구조물 — 저장 노선 누가거리 · 좌표.""" + lengths = [math.dist(a, b) for a, b in zip(line, line[1:])] + at = sum(lengths) * ratio + walked = 0.0 + for (a, b), length in zip(zip(line, line[1:]), lengths): + if walked + length >= at: + t = (at - walked) / length + dx, dy = (b[0] - a[0]) / length, (b[1] - a[1]) / length + x, y = a[0] + dx * length * t - dy * off, a[1] + dy * length * t + dx * off + break + walked += length + return { + "structure_id": sid, + "type_id": "erosion_check", + "placement": "point", + "chainage_m": round(at, 2), + "start_m": None, + "end_m": None, + "x": x, + "y": y, + "options": {}, + } + + +@pytest.fixture(scope="module") +def r() -> dict: + if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()): + pytest.skip("검증_sub7 없음") + curves = _json(ROUTE / "planned_route_curves.json") + sections = sorted( + (_json(p) for p in (SECTION / "cross_sections").glob("cross_*.json")), + key=lambda s: s["chainage_m"], + ) + pipes = _json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"] + line = _csv(ROUTE / "planned_route.csv") + structures = [_structure("s-near", line, 0.5, 0.0), _structure("s-far", line, 0.7, 30.0)] + job = { + "line": line, + "structures": structures, + "nodes": _csv(ROUTE / "planned_route_nodes.csv"), + "curves": [ + {k: c[k] for k in ("start", "apex", "end", "radius_m")} for c in curves["curves"] + ], + "stationSnap": bool(curves.get("station_snap")), + "minRadius": curves["min_radius_m"], + "interval": 20.0, + "types": [ + {"type_id": t.type_id, "group": t.group, "placement": t.placement} + for t in structure_type_map().values() + ], + "pipes": pipes, + "dx": -60.0, + "dy": 0.0, + "standard": STANDARD_CROSS_SECTION, + "conversion": ONES, + "detail": { + "longitudinal": _json(SECTION / "longitudinal/longitudinal.json"), + "cross_sections": sections, + }, + } + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "job.json" + path.write_text(json.dumps(job), encoding="utf-8") + grid = Path(folder) / "grid.bin" + grid.write_bytes(dtm_grid_bytes(GRID)) + proc = subprocess.run( # noqa: S603 — 고정 실행 파일 + ["node", str(HERE / "helper_349_0u_follow_draft_xy.cjs"), str(path), str(grid)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=300, + ) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout) + + +def _moved(before: list, after: list) -> list[float]: + return [b[1] - a[1] for a, b in zip(before, after)] + + +def test_앞쪽_꺾임점_끌기_측점_밀림(r): + d = r["drag"] + assert d["runs"] == [["route"]], d["runs"] + assert d["blocked"] == 0 + grow = d["length"] - r["savedLength"] + assert grow > 5, grow # 앞쪽 길이 늚 + pipes = _moved(r["draftPipes"], d["pipes"]) + assert len(d["pipes"]) == len(r["draftPipes"]) + # 끈 꼭짓점 뒤 관 = 길이 는 만큼(정수 m 맞춤 · 1 m 안) — 대부분 그 뒤 + tail = [m for (_, c), m in zip(r["draftPipes"], pipes) if c > r["draftPipes"][2][1]] + assert tail and all(abs(m - grow) <= 1.0 for m in tail), (grow, pipes) + s = _moved(r["draftStructures"], d["structures"]) + assert all(abs(m - grow) <= 1.0 for m in s), (grow, s) + assert len(d["followed"]) == 1 + + +def test_되돌리기_초안_값(r): + for u in (r["undo"], r["undo2"]): + assert u["runs"] == [["route"]], u["runs"] + assert u["pipes"] == r["draftPipes"] + assert u["structures"] == r["draftStructures"] + assert abs(u["length"] - r["savedLength"]) < 1e-6 + assert u["blocked"] == 0 + + +def test_다시하기_다시_밂(r): + d, again = r["drag"], r["redo"] + assert again["runs"] == [["route"]], again["runs"] + assert again["pipes"] == d["pipes"] and again["structures"] == d["structures"] + assert again["blocked"] == 0 + + +def test_열기만_가게_그대로(r): + o = r["open"] + assert o["pipes"] == r["draftPipes"] and o["structures"] == r["draftStructures"] + assert o["followed"] == []