diff --git a/A00_Common/design/design_pipeline_page.ts b/A00_Common/design/design_pipeline_page.ts index 5db30c449..53974f7fe 100644 --- a/A00_Common/design/design_pipeline_page.ts +++ b/A00_Common/design/design_pipeline_page.ts @@ -22,6 +22,7 @@ * ========================================================================== */ import { createDesignPipeline, publishToStore, type DesignPipeline } from "./logic/design_pipeline"; +export { pipelineWork } from "./logic/design_pipeline"; import { pipelineCrossSource, type PipelineCrossSource } from "./design_pipeline_cross"; import { createStationsStage } from "./logic/design_pipeline_stations"; import type { @@ -353,7 +354,7 @@ function createPagePipeline( stationsShown = list; } if (!quiet) publish(event); - }); + }, "가게"); /** 노선 초안을 버린 차례 끝 — 초안 전 상세로 되돌림(열 때와 같은 상태 · 측점이 달라도 · 다른 자리는 * 기록에) · 그 상세가 저장 정본(다시 하기도 같은 기준). 차례 끝에서 판정 — ground 를 건너뛰어도 · 사진첩 * 되돌리기가 가게 초안을 먼저 비워도(349-0m). */ @@ -417,7 +418,7 @@ function createPagePipeline( : 0; options.onFacilitiesFollowed?.(far); }); - }); + }, "관 · 구조물"); pipe.subscribe((event) => { if (event.kind !== "stage" || (event.stage !== "profile" && event.stage !== "cross")) return; const draft = pipe.input("route") !== null; @@ -452,7 +453,7 @@ function createPagePipeline( else link.adoptPipeline(base, edits, draft); } drawnDraft = draft; - }); + }, "새 상세 · 종단도"); function facilitiesNow(): Facilities { return { pipes: store.get("pipes"), structures: store.get("structures") }; diff --git a/A00_Common/design/design_profile.ts b/A00_Common/design/design_profile.ts index 500027878..18ac1dcf6 100644 --- a/A00_Common/design/design_profile.ts +++ b/A00_Common/design/design_profile.ts @@ -355,6 +355,10 @@ export function createDesignProfile(ctx: DesignProfileContext) { // 캐시에 얹는다. 그래야 **횡단 기준** 유토곡선과 횡단 카드가 따라 움직인다 // (2026-08-03 사용자 보고: B05에서 계획선을 끌어도 횡단 곡선이 그대로였음). scheduleCrossPreview(); + drawSoon(); + } + /** 다음 틀에 한 번 그림 — 같은 차례 알림 · 갈아끼움 · 설정이 여러 번 불러도 한 번(349-0s). */ + function drawSoon(): void { if (redrawPending) return; redrawPending = true; frameOf(root, () => { @@ -366,13 +370,13 @@ export function createDesignProfile(ctx: DesignProfileContext) { /** 횡단 설계 프리뷰는 `_Profile_Preview` 몫(700줄 한계). */ const crossPreview = createCrossPreview({ projectId, - detail: () => detail, + detail: () => (pagePipeline.pagePipeline(projectId)?.input("route") ? null : detail), // 노선 초안 동안 안 셈(349-0s) routeId: () => routeId, edits: () => store.edits(), alignment: () => (store === preview ? null : alignment), debounceMs: () => (root.dataset.view === "cross" ? 120 : CROSS_PREVIEW_DEBOUNCE_MS), onApplied: (updated) => { - draw(); + drawSoon(); if (updated.length) callbacks?.onCrossDesignsUpdated?.(updated); }, }); @@ -404,51 +408,53 @@ export function createDesignProfile(ctx: DesignProfileContext) { const scheduleLightSync = (): void => heights.scheduleLightSync(); function draw(): void { - renderProfile({ - // 그린 뒤 생긴 낡음도 다시 셈(317-1) · 노선 초안 동안은 묶음 cross 를 기다림 - onStaleDesigns: (key) => crossPreview.scheduleIfStale(key, store === preview), - body, - callbacks, - massHaul, - tableOverlay, - store, - detail: () => pagePipeline.pipelineDetail(projectId) ?? detail, - alignment: () => alignment, - base: () => base, - stationInterval: () => stationInterval, - irregularStations: () => irregularStations, - minCoverTargets: () => minCoverTargets, - structures: () => structures, - structureTypes: () => structureTypes, - selectedStationId: () => selectedStationId, - setSelectedStationId: (value) => { - selectedStationId = value; - }, - selectedStructureId: () => selectedStructureId, - setSelectedStructureId: (value) => { - selectedStructureId = value; - }, - stationDisplay: () => stationDisplay, - setLastSize: (width, height) => { - lastWidth = width; - lastHeight = height; - }, - renderBalance, - applyHeightCascade, - clearMainDragCooldown: drag.clearMainDragCooldown, - selectStation, - applyEdits, - handleToolPick, - zoom: profileZoom.state, - holdElevationRange: elevationHold.hold, - toolActive: () => tools.mode() !== "none", - tools, - stationIdAtStructure, - redraw: draw, - setElevationWindowUpdater: (update) => { - updateElevationWindow = update; - }, - }); + pagePipeline.pipelineWork("종단도", () => + renderProfile({ + // 그린 뒤 생긴 낡음도 다시 셈(317-1) · 노선 초안 동안은 묶음 cross 를 기다림 + onStaleDesigns: (key) => crossPreview.scheduleIfStale(key, store === preview), + body, + callbacks, + massHaul, + tableOverlay, + store, + detail: () => pagePipeline.pipelineDetail(projectId) ?? detail, + alignment: () => alignment, + base: () => base, + stationInterval: () => stationInterval, + irregularStations: () => irregularStations, + minCoverTargets: () => minCoverTargets, + structures: () => structures, + structureTypes: () => structureTypes, + selectedStationId: () => selectedStationId, + setSelectedStationId: (value) => { + selectedStationId = value; + }, + selectedStructureId: () => selectedStructureId, + setSelectedStructureId: (value) => { + selectedStructureId = value; + }, + stationDisplay: () => stationDisplay, + setLastSize: (width, height) => { + lastWidth = width; + lastHeight = height; + }, + renderBalance, + applyHeightCascade, + clearMainDragCooldown: drag.clearMainDragCooldown, + selectStation, + applyEdits, + handleToolPick, + zoom: profileZoom.state, + holdElevationRange: elevationHold.hold, + toolActive: () => tools.mode() !== "none", + tools, + stationIdAtStructure, + redraw: draw, + setElevationWindowUpdater: (update) => { + updateElevationWindow = update; + }, + }), + ); } /** 다른 영역에서 고른 자리가 화면 밖이면 가운데로(칠한 뒤 · `design_profile_viewport`). */ @@ -511,15 +517,9 @@ export function createDesignProfile(ctx: DesignProfileContext) { `${projectId}:${routeId ?? "-"}`, nextDetail.balloon_offsets ?? undefined, ); - draw(); - frameOf(root, draw); - // 저장된 횡단 설계가 옛 계획고로 굳어 있으면 진입 즉시 한 번 맞춘다 — - // 지금까지는 B06에 들어가야만 고쳐져, B05의 횡단 기준 유토곡선과 3D - // 예상형상이 옛 설계선을 그대로 썼다(2026-08-23 사용자 보고 · 실측 확인). - // 비교 대상은 **편집이 반영된 계획선**이다. 저장분끼리 견주면, 세션에 미저장 편집이 - // 남은 채로 새로고침했을 때 「어긋남 없음」으로 나와 재계산이 예약되지 않고, 그리기 - // 쪽은 편집분 기준으로 어긋났다고 보아 유토곡선이 영영 빈 화면이 됐다 - // (2026-09-03 사용자 보고 — 편집 측점 2개가 세션에 남은 상태에서 재현). + drawSoon(); // 다음 틀 한 번(끌기 중 갈아끼움마다 두 번 그리던 것 · 349-0s) + // 저장 횡단이 옛 계획고로 굳어 있으면 진입 즉시 맞춤(08-23) — 비교 = 편집이 반영된 계획선 + // (저장분끼리 견주면 세션 편집이 남은 새로고침에서 유토곡선이 빈 채 · 09-03). if ( hasStaleDesigns({ longitudinal: { @@ -543,7 +543,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { setEarthworkContext(next: RouteMassHaulContext | null) { massHaul.setContext(next); pagePipeline.pipelineEarthwork(projectId, next); - draw(); + drawSoon(); }, setSelectedStation(stationId: string | null) { selectedStationId = stationId; @@ -571,7 +571,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { storedBase = { ...storedBase, policy }; base = { ...base, policy }; alignment = buildAlignment(base, store.edits()); - draw(); + drawSoon(); }, /** 확정된 노선 평면 선형을 우측 배수유역 지도에 겹친다(사업지 좌표계 m). */ setRoutePolyline(points: ReadonlyArray<{ x: number; y: number }>) { @@ -583,13 +583,13 @@ export function createDesignProfile(ctx: DesignProfileContext) { if (store !== preview) base = listed(); if (base) alignment = buildAlignment(base, store.edits()); pagePipeline.restartPagePipeline(projectId); - draw(); + drawSoon(); }, /** 구조물 타입 레지스트리를 받아 마크 색·약호에 쓴다(최초 1회 · 우클릭 목록은 사이드 패널 몫). */ setStructureTypes(types: StructureType[]) { structureTypes = types; syncDrainageSpans(); - draw(); + drawSoon(); }, /** 구조물 정본 목록을 반영해 그래프 서클마크를 다시 그린다. */ setStructures(next: StructureInstance[]) { @@ -598,7 +598,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { selectedStructureId = null; } syncDrainageSpans(); - draw(); + drawSoon(); }, /** 고른 구조물에 알약 · 측점선을 맞춤 — 그 자리면 선 그대로(53-2) · keepStation(B06 카드 = 선 주인) = 선 없는 구조물 · 풂도 카드 선 지킴(177-3). */ setSelectedStructure(structureId: string | null, keepStation = false) { @@ -612,7 +612,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { /** 이어 공사 시작 기준(측점번호·누가거리 오프셋)을 반영해 측점 라벨·누가거리 표시를 옮긴다. */ setStationDisplay(next: { station: number; cumulative: number }) { stationDisplay = next; - draw(); + drawSoon(); }, /** * 특정 chainage의 계획고 편집(station_offset·curve_radii)을 지운다. @@ -642,7 +642,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { if (store === preview) store = createProfileEditStore(routeId, savedEdits, () => rebuild()); [preview, base] = [null, listed()]; alignment = base && buildAlignment(base, store.edits()); // 그리기만 · 다시 셈 예약 없음(349-0l) - draw(); + drawSoon(); }, /** [확정] 직전에 호출한다. 편집이 없으면 아무 것도 하지 않는다. */ async save(): Promise { @@ -669,7 +669,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { body.replaceChildren(empty); }, /** 밖에서 바뀐 횡단 면적(카드 갱신)을 유토곡선 · 뱃지에 다시 싣는다. */ - redraw: () => draw(), + redraw: () => drawSoon(), /** 오른쪽 판(배수유역도) — 판 없이 만들었으면 null. */ side: drainagePanel, /** 그래프 영역 로딩 서클. 문구를 주면 켜고 null이면 끈다. */ @@ -683,7 +683,7 @@ export function createDesignProfile(ctx: DesignProfileContext) { setListening(active); if (!active) return; if (base) alignment = buildAlignment(base, store.edits()); - draw(); + drawSoon(); drainagePanel?.load(projectId); }, dispose() { diff --git a/A00_Common/design/logic/design_pipeline.ts b/A00_Common/design/logic/design_pipeline.ts index df3f19950..1dea2fe29 100644 --- a/A00_Common/design/logic/design_pipeline.ts +++ b/A00_Common/design/logic/design_pipeline.ts @@ -81,7 +81,8 @@ export interface DesignPipeline { value: unknown, part?: RangePart | null, ): Promise | null; - subscribe(fn: (event: PipelineEvent) => void): () => void; + /** `name` = 기록 `work` 칸 이름(알림 받는 쪽 몫 ms · 349-0s). */ + subscribe(fn: (event: PipelineEvent) => void, name?: string): () => void; output(name: K): PipelineOutputs[K] | null; /** 지금 입력(follow 가 고친 뒤 값 포함 · 읽기만). */ input(key: K): PipelineInputs[K]; @@ -126,6 +127,23 @@ function runLog(): { runs: PipelineRunRecord[] } { return root.__aisloPipeline; } +const addWork = (record: PipelineRunRecord | undefined, name: string, ms: number): void => { + if (!record) return; + const work = (record.work ??= {}); + work[name] = Math.round(((work[name] ?? 0) + ms) * 100) / 100; +}; + +/** 그리기 몫 재기(349-0s) — 마지막 차례 기록 `work[name]` 에 ms 를 더함(차례 뒤 늦은 그리기도 그 차례 몫). */ +export function pipelineWork(name: string, fn: () => T): T { + const t0 = now(); + try { + return fn(); + } finally { + const runs = runLog().runs; + addWork(runs[runs.length - 1], name, now() - t0); + } +} + export function createDesignPipeline(options: { stages: PipelineStages }): DesignPipeline { const stages = options.stages; const inputs: PipelineInputs = { @@ -151,7 +169,8 @@ export function createDesignPipeline(options: { stages: PipelineStages }): Desig outVer[name] = 0; pending[name] = null; }); - const listeners = new Set<(event: PipelineEvent) => void>(); + /** 알림 받는 쪽 → 기록 이름. */ + const listeners = new Map<(event: PipelineEvent) => void, string>(); const inFlight = new Set>(); let generation = 0; let controller = new AbortController(); @@ -159,10 +178,14 @@ export function createDesignPipeline(options: { stages: PipelineStages }): Desig let busy = false; let blockedWrites = 0; - const emit = (event: PipelineEvent): void => { + const emit = (event: PipelineEvent, record?: PipelineRunRecord): void => { busy = true; try { - listeners.forEach((fn) => fn(event)); + listeners.forEach((name, fn) => { + const t0 = now(); + fn(event); + addWork(record, name, now() - t0); + }); } finally { busy = false; } @@ -240,7 +263,7 @@ export function createDesignPipeline(options: { stages: PipelineStages }): Desig outVer[name] += 1; lastSig[name] = sig; delete pending[name]; - emit({ kind: "stage", stage: name, value, generation: gen }); + emit({ kind: "stage", stage: name, value, generation: gen }, record); return "ok"; } @@ -274,7 +297,9 @@ export function createDesignPipeline(options: { stages: PipelineStages }): Desig return record; } if (YIELD_AFTER.has(name) && record.stages[name] !== undefined) { + const t1 = now(); await new Promise((resolve) => setTimeout(resolve, 0)); + addWork(record, "쉼", now() - t1); // 그 사이 늦은 그리기 · 다른 일 if (gen !== generation) { record.outcome = "dropped"; return record; @@ -324,8 +349,8 @@ export function createDesignPipeline(options: { stages: PipelineStages }): Desig : { sources: [source], fromM: 0, toM: Infinity, keys: [] }; return begin(range); }, - subscribe(fn) { - listeners.add(fn); + subscribe(fn, name = "알림") { + listeners.set(fn, name); return () => listeners.delete(fn); }, output(name) { diff --git a/A00_Common/design/logic/design_pipeline_types.ts b/A00_Common/design/logic/design_pipeline_types.ts index 53abc1a96..b25e5a20c 100644 --- a/A00_Common/design/logic/design_pipeline_types.ts +++ b/A00_Common/design/logic/design_pipeline_types.ts @@ -289,4 +289,6 @@ export interface PipelineRunRecord { saved: number; pipeline: number; }; + /** 알림 받는 쪽 · 그리기 몫 ms(이름별 · 349-0s) — 쉼 = profile 뒤 한 번 쉬는 동안(늦은 그리기 등). */ + work?: Record; } diff --git a/B05_Profile/B05_Profile_UI_Profile_MassHaul.ts b/B05_Profile/B05_Profile_UI_Profile_MassHaul.ts index d04fbde36..f7349e98a 100644 --- a/B05_Profile/B05_Profile_UI_Profile_MassHaul.ts +++ b/B05_Profile/B05_Profile_UI_Profile_MassHaul.ts @@ -23,6 +23,7 @@ * ========================================================================== */ import { readStateRaw, stateKey, writeStateRaw } from "../A00_Common/b_page_state"; +import { pipelineWork } from "../A00_Common/design/logic/design_pipeline"; import type { EarthworkConversion, HaulEquipmentLimit, @@ -359,7 +360,12 @@ export function createRouteMassHaulPanel( ); } + /** 그리기 몫 기록(349-0s) — 묶음 마지막 차례 `work.유토곡선`. */ function draw(params: RouteMassHaulDrawParams): void { + pipelineWork("유토곡선", () => drawNow(params)); + } + + function drawNow(params: RouteMassHaulDrawParams): void { lastParams = params; overlay.hidden = !open; syncHandlePosition(); diff --git a/B05_Profile/B05_Profile_UI_Profile_Preview.ts b/B05_Profile/B05_Profile_UI_Profile_Preview.ts index e45450ddb..65b587ff7 100644 --- a/B05_Profile/B05_Profile_UI_Profile_Preview.ts +++ b/B05_Profile/B05_Profile_UI_Profile_Preview.ts @@ -73,7 +73,7 @@ export function createCrossPreview(ctx: CrossPreviewContext): CrossPreview { const stopGeneration = useDesignStore(ctx.projectId, null).subscribe("generation", (gen) => { const pipe = pagePipeline(ctx.projectId); if (!pipe || gen === null) return; - if (watched !== pipe) (watched = pipe).subscribe(onStage); + if (watched !== pipe) (watched = pipe).subscribe(onStage, "다시 셈 대기"); awaiting = gen; window.clearTimeout(waitTimer); waitTimer = window.setTimeout(() => { diff --git a/B06_Section/B06_Section_UI_Page_Station_Swap.ts b/B06_Section/B06_Section_UI_Page_Station_Swap.ts index b1fc9b5ef..9f9632cea 100644 --- a/B06_Section/B06_Section_UI_Page_Station_Swap.ts +++ b/B06_Section/B06_Section_UI_Page_Station_Swap.ts @@ -60,7 +60,7 @@ function followDraftDetail(projectId: string, changed: () => void): () => void { if (next === drawn) return; drawn = next; changed(); - }) ?? ((): void => undefined); + }, "횡단 카드") ?? ((): void => undefined); }; attach(); const stopStore = useDesignStore(projectId, null).subscribe("generation", attach); diff --git a/resources/tester/helper_230_2_popout_frames.cjs b/resources/tester/helper_230_2_popout_frames.cjs index c0a9c9e88..23a06bbd6 100644 --- a/resources/tester/helper_230_2_popout_frames.cjs +++ b/resources/tester/helper_230_2_popout_frames.cjs @@ -86,10 +86,12 @@ out.viewOf = { // ② 계획고 편집 뒤 다시 그리기(design_profile rebuild) — 두 번 불러도 한 번만 그림 { const s = { draws: 0, previews: 0 }; - const src = block( - read("A00_Common", "design", "design_profile.ts"), - "function rebuild(): void {", - ); + const profileSrc = read("A00_Common", "design", "design_profile.ts"); + // 다시 그림 예약 = drawSoon(349-0s · 같은 틀 한 번) + const src = [ + block(profileSrc, "function rebuild(): void {"), + block(profileSrc, "function drawSoon(): void {"), + ].join("\n"); run(`let redrawPending = false; ${src}\nrebuild(); rebuild(); s.rebuild = true;`, { s, base: null, diff --git a/resources/tester/helper_349_0s_draw_work.cjs b/resources/tester/helper_349_0s_draw_work.cjs new file mode 100644 index 000000000..d38f93d5c --- /dev/null +++ b/resources/tester/helper_349_0s_draw_work.cjs @@ -0,0 +1,412 @@ +/* PLAN 349-0s sub7 헬퍼 — 노선 꼭짓점 끌기 여러 걸음 · 되돌리기의 묶음 기록(단계 · 알림 받는 쪽 · 그리기 몫 ms)과 + * 걸음마다 종단도 그리기 수. 화면 틀(rAF)은 16 ms 뒤 부름으로 흉내 — 같은 틀 안 여러 번 그리기 요청은 한 번. + * 진짜 TS — 종단도 · 계산 묶음 · 상세 가게(그리기 본문 · 서버 창구만 가짜 · 종단 보기 renderSections 꼴 그대로). + * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0s_draw_work.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; + }, + }; +} +const windowBase = { + sessionStorage: memoryStorage(), + localStorage: memoryStorage(), + setTimeout, + clearTimeout, + addEventListener: () => undefined, + removeEventListener: () => undefined, +}; +globalThis.window = new Proxy(windowBase, { + get: (t, key) => (key in t ? t[key] : undefined), + set: (t, key, value) => ((t[key] = value), true), +}); + +// 흙 배분 서버 — 늦게 답함 · 끊기면 버림 +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("@ui/")) return anyModule(); + if (request.endsWith(".css")) return {}; + if (request.endsWith(".json")) return require(path.join(path.dirname(full), request)); + 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" }; + +/** 아무 화면 부품 — 무엇을 읽든 · 부르든 또 그것(DOM · 오버레이 · 도구줄 흉내). */ +function anyNode() { + const box = { dataset: {}, style: {}, classList: { add() {}, remove() {}, toggle() {} } }; + return new Proxy(function node() {}, { + get: (_t, key) => { + if (key in box) return box[key]; + if (key === "then" || typeof key === "symbol") return undefined; + return (box[key] = anyNode()); + }, + set: (_t, key, value) => ((box[key] = value), true), + apply: () => anyNode(), + }); +} +const anyModule = (own = {}) => + new Proxy(own, { + get: (t, key) => + key in t + ? t[key] + : key === "__esModule" + ? true + : typeof key === "symbol" + ? undefined + : anyNode(), + }); +globalThis.document = anyNode(); +globalThis.HTMLElement = function HTMLElement() {}; + +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"] = anyModule({ + fetchStructures: async () => ({ structures: job.structures }), + fetchStructureTypes: async () => job.types, + readPendingStructures: () => null, +}); +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, +}; +// 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음 +STUBS["B06_Section_Section_Drafts"] = { + withDraftStations: async () => undefined, + withDraftShapes: async () => undefined, + forgetDraftStations: () => undefined, +}; +STUBS["B06_Section_Api_Fetch"] = { + fetchSectionDetail: async () => JSON.parse(JSON.stringify(job.detail)), + saveSections: async () => undefined, +}; +// 횡단 다시 셈(브라우저 · B05 crossPreview · B06 카드 같은 창구) — 부른 횟수 · 면적은 서버와 달라짐(두 배) +let refreshCalls = 0; +const doubled = (detail) => + detail.cross_sections.forEach((section) => { + if (!section.design) return; + const design = { ...section.design }; + for (const [key, value] of Object.entries(design)) + if (key.endsWith("_m2") && typeof value === "number") design[key] = value * 2; + section.design = design; + }); +STUBS["B06_Section_Cross_Refresh"] = { + refreshCrossDesigns: async ({ detail }) => { + refreshCalls += 1; + doubled(detail); + return detail.cross_sections.map((s) => s.chainage_m); + }, + // 화면 선 맡김 · 낡음 판정 = 진짜 `staleAgainstScreen` 그대로(화면 선 → 없으면 상세 자기 선) + holdScreenAlignment: (line) => { + screenLine = line; + return () => undefined; + }, + staleAgainstScreen: (detail, routeId) => { + const screen = screenLine?.(routeId); + if (!screen) return common.hasStaleDesigns(detail); + return common.hasStaleDesigns({ + longitudinal: { + design_profiles: [ + profileData.toDesignProfile(screen, detail.longitudinal.design_profiles?.[0]), + ], + }, + cross_sections: detail.cross_sections, + }); + }, + USER_TOUCHED_KEYS: [], +}; +let screenLine = null; +STUBS["B06_Section_UI_Cross_Detail"] = anyModule(); +STUBS["B06_Section_UI_Page_Common"] = anyModule({ L: (key) => key }); +// 그리기 — 진짜 `renderProfile` 의 낡음 판정 줄만(같은 함수 · 같은 인자) · SVG 는 안 그림 +const draws = []; +let opened = null; +STUBS["B05_Profile_UI_Profile_Render"] = { + renderProfile: (ctx) => { + const detail = ctx.detail(); + if (!detail) return; + const alignment = ctx.alignment(); + const longitudinal = detail.longitudinal; + const designProfiles = alignment + ? [profileData.toDesignProfile(alignment, longitudinal.design_profiles?.[0])] + : (longitudinal.design_profiles ?? []); + const key = common.staleKey({ + longitudinal: { design_profiles: designProfiles }, + cross_sections: detail.cross_sections, + }); + // 저장 상세를 그림 = 묶음 새 노선 상세(preview)가 아님 · 그린 객체(가게 것인지 견줌) + draws.push({ key, saved: !detail.cross_sections.some((s) => s.preview), ref: detail }); + ctx.onStaleDesigns?.(key); + }, +}; +STUBS["common_util_view_window"] = { frameOf: (_root, fn) => setTimeout(() => fn(0), 16) }; +for (const name of [ + "B05_Profile_UI_Profile_Balance", + "B05_Profile_UI_Profile_Heights", + "B05_Profile_UI_Profile_Panel_Tools", + "B05_Profile_UI_Profile_Zoom", + "B05_Profile_UI_Profile_Drag", + "B05_Profile_UI_Profile_MassHaul", + "design_profile_overlays", + "design_profile_viewport", + "design_save", + "B05_Profile_Api_Fetch", + "common_util_mass_haul_balance_view", +]) + STUBS[name] = anyModule(); + +const pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); +const storeMod = load("A00_Common", "design", "design_store.ts"); +const sectionStore = load("B06_Section", "B06_Section_Section_Store.ts"); +const common = load("B06_Section", "B06_Section_UI_Section_Common.ts"); +const layouts = load("B06_Section", "B06_Section_Structure_Layouts.ts"); +const profileData = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Data.ts"); +const alignmentMod = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); +const baseMod = load("A00_Common", "design", "design_profile_base.ts"); +const pageState = load("A00_Common", "b_page_state.ts"); +const massHaul = load("common_util", "common_util_mass_haul.ts"); +const profileMod = load("A00_Common", "design", "design_profile.ts"); +const designSync = load("B06_Section", "B06_Section_UI_Page_Design_Sync.ts"); +const designSession = load("B06_Section", "B06_Section_Cross_Design_Session.ts"); +const stationKeys = load("B06_Section", "B06_Section_Station_Keys.ts"); +// 진짜 다시 셈 창구(묶음 새 노선 상세를 안 고치는지만 봄 · 다른 곳은 위 가짜를 부름) +const realRefresh = loadTs(path.join(ROOT, "B06_Section", "B06_Section_Cross_Refresh.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(30); + const last = runs()[runs().length - 1]; + const count = runs().length + refreshCalls * 1000 + draws.length * 1e6; + 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 sliceRuns = (mark) => + runs() + .slice(mark) + .map((r) => ({ + sources: r.sources, + outcome: r.outcome, + restored: r.restored ?? null, + why: r.restoreWhy ?? null, + })); +const finalOf = (detail) => { + const [series] = massHaul.computeMassHaulSeries( + detail.longitudinal, + detail.cross_sections, + job.conversion, + undefined, + ["cross"], + ); + const points = series?.result.points ?? []; + return points.length ? points[points.length - 1].cumulative_volume_m3 : null; +}; +const crossOf = (detail) => + JSON.stringify(detail.cross_sections.map((s) => [s.chainage_m, s.design, s.samples])); +/** 서버 정본 흉내 — 저장 횡단 계획고 = 열 때 종단도 계획선(낡음 0 · 서버가 낸 상세와 같음). */ +function settleDesigns(detail) { + const pa = detail.longitudinal.profile_alignment; + const base = baseMod.listedBase(alignmentMod.toAlignmentBase(pa), detail, []); + const samples = alignmentMod.buildAlignment(base, pa.edits).samples; + const at = (c) => { + const i = samples.findIndex((s) => s.chainage_m >= c); + if (i < 0) return samples[samples.length - 1].elevation_m; + if (i === 0) return samples[0].elevation_m; + const a = samples[i - 1]; + const b = samples[i]; + return ( + a.elevation_m + + ((b.elevation_m - a.elevation_m) * (c - a.chainage_m)) / (b.chainage_m - a.chainage_m) + ); + }; + detail.cross_sections.forEach((s) => (s.design.design_elevation_m = at(s.chainage_m))); +} + +async function run() { + const P = "proj-349s"; + const R = 7; + window.localStorage.setItem("frd_current_project_id", P); + opened = await sectionStore.loadSectionDetail(P, R); + settleDesigns(opened); + const profile = profileMod.createDesignProfile({ + projectId: P, + view: "profile", + onSelectStation: () => undefined, + }); + const live = () => sectionStore.loadSectionDetail(P, R); + pageMod.routeDraftBridge(P, profile, { + stationIntervalM: job.interval, + structureAreas: ({ cross_sections: rows }) => + layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)), + holdDraft: (routeId, saved) => { + const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); + return async (stations) => { + if (!hold) { + await sectionStore.swapSectionStations(P, routeId, stations); + return "no-saved"; + } + const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; + }, + }); + // 종단 보기 `renderSections` 그대로 — 새 상세 → render · 정책 · 이어 공사 기준 · 비정규 측점(각각 다시 그림 부름) + const show = (detail) => { + profile.render(detail, job.interval, R); + profile.setGradeLimit(12); + profile.setStationDisplay({ station: 0, cumulative: 0 }); + profile.setIrregularStations([]); + }; + const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => show(next)); + const swapMs = []; + const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => { + if (!stations?.length) return; + const t0 = performance.now(); + void sectionStore + .swapSectionStations(P, R, stations) + .then(() => swapMs.push(Math.round((performance.now() - t0) * 100) / 100)); + }); + show(opened); + profile.setEarthworkContext({ conversion: job.conversion }); + await quiet(); + const detailBytes = JSON.stringify(await live()).length; + + // 꼭짓점 끌기 — 마우스 움직임마다 한 번(놓기 전 여러 걸음) + const bridge = pageMod.routeDraftBridge(P, profile); + const steps = []; + for (let k = 1; k <= job.steps; k += 1) { + const mark = runs().length; + const drawMark = draws.length; + const swapMark = swapMs.length; + bridge.edited(draftOf(shift(1, 1.5 * k, -k))); + await quiet(); + const ran = runs().slice(mark); + steps.push({ + runs: ran.map((r) => ({ + outcome: r.outcome, + totalMs: r.totalMs, + stagesMs: Object.entries(r.stages) + .filter(([name]) => !["haul", "drainage", "corridor"].includes(name)) + .reduce((a, [, ms]) => a + ms, 0), + stages: r.stages, + work: r.work ?? {}, + })), + draws: draws.length - drawMark, + swapMs: swapMs.slice(swapMark), + }); + } + // 되돌리기 + const mark = runs().length; + const drawMark = draws.length; + pageState.writeState("route-draft", null, P); + bridge.edited(null); + bridge.edited(null); + await quiet(); + const undo = { + runs: runs() + .slice(mark) + .map((r) => ({ + outcome: r.outcome, + totalMs: r.totalMs, + work: r.work ?? {}, + why: r.restoreWhy, + })), + draws: draws.length - drawMark, + }; + stopListen(); + stopStore(); + pageMod.disposePagePipeline(P); + return { steps, undo, detailBytes, refresh: refreshCalls }; +} + +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_0s_draw_work.py b/resources/tester/test_349_0s_draw_work.py new file mode 100644 index 000000000..3b5d4c2d5 --- /dev/null +++ b/resources/tester/test_349_0s_draw_work.py @@ -0,0 +1,154 @@ +"""PLAN 349-0s sub7 — 끌기 한 걸음 = 종단도 한 번 그림 · 묶음 기록에 알림 받는 쪽 · 그리기 몫(ms). + +· 꼭짓점 끌기 다섯 걸음 · 되돌리기 — 걸음마다 종단도 그리기 ≤ 2(종단 먼저 · 횡단 · 유토곡선 다음 틀) + (옛 길 = 갈아끼움 · 정책 · 이어 공사 기준 · 비정규 측점 · 새 상세 알림마다 바로 그림) +· runs[].work — 가게 · 새 상세 · 종단도 · 쉼 이름별 ms(알림 받는 쪽 · 그리기 몫) +· 되돌리기 = 열기 값 규칙 그대로(restored) +짝: `helper_349_0s_draw_work.cjs`(실제 TS 를 Node 로 · 화면 부품 · 서버 창구만 가짜). +""" + +from __future__ import annotations + +import csv +import json +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 _between(sections: list[dict], index: int) -> dict: + """두 측점 사이 한 점(0.37) — 누가거리 · 좌표.""" + a, b = sections[index], sections[index + 1] + k = 0.37 + return { + "chainage_m": round(a["chainage_m"] + k * (b["chainage_m"] - a["chainage_m"]), 2), + "x": a["center_x"] + k * (b["center_x"] - a["center_x"]), + "y": a["center_y"] + k * (b["center_y"] - a["center_y"]), + } + + +@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"] + # 세월교 하나 더(측점 사이) — 저장 상세엔 그 측점이 없음 = 묶음 저장 노선 측점과 다름(검증_sub7 세월교 2 + 1) + pipes = [*pipes, {"source": "manual", "facility": "ford_bridge", **_between(sections, -6)}] + # 저장 횡단 면적 = 서버가 상세를 낼 때 셈(파일엔 없음) — 정본 대신 정한 값 + for i, section in enumerate(sections): + section["design"] = { + "ground_type": "soil", + "design_elevation_m": section["center_z"], + "cut_area_m2": 4.0 + (i % 5), + "fill_area_m2": 1.5 + (i % 3), + } + job = { + "line": _csv(ROUTE / "planned_route.csv"), + "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, + "standard": STANDARD_CROSS_SECTION, + "conversion": ONES, + # 구조물 하나 — 첫 관 자리 횡단배수(같은 측점을 덮음) + "structures": [ + { + "structure_id": "s-349o", + "type_id": "cross_drain_exposed", + "chainage_m": pipes[0]["chainage_m"], + "x": pipes[0]["x"], + "y": pipes[0]["y"], + } + ], + # 열기 전에 고친 카드 선택 — 끌면 밀리는 측점(뒤쪽) · 단면 유형은 노선이 바뀌면 안 넘기는 칸 + "touched": { + str(sections[-3]["chainage_m"]): { + "ground_type": "blasting_rock", + "section_mode": "right_cut", + } + }, + "steps": 5, + "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_0s_draw_work.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 test_걸음마다_종단도_한두_번(r): + for step in r["steps"]: + assert [x["outcome"] for x in step["runs"]][-1] == "done", step["runs"] + assert 1 <= step["draws"] <= 2, step + + +def test_그리기_몫_기록(r): + done = [x for step in r["steps"] for x in step["runs"] if x["outcome"] == "done"] + for x in done: + assert {"가게", "새 상세 · 종단도", "종단도", "쉼"} <= set(x["work"]), x["work"] + assert x["totalMs"] >= x["stagesMs"] * 0.99 + + +def test_되돌리기_그대로(r): + u = r["undo"] + assert [x["why"] for x in u["runs"]] == ["saved-diff"], u["runs"] # 세월교 하나 더(0o 꼴) + assert 1 <= u["draws"] <= 2, u + assert r["refresh"] == 0