Files
Aislo/resources/tester/helper_349_0s_draw_work.cjs
T
eomsangdonandClaude Opus 5.5 25eea13ab2 perf(계산묶음): 349-0s 끌기 한 걸음 = 종단도 한 번 그림 — 다시 그림 한 틀 모음 · 초안 동안 저장 횡단 다시 셈 없음 · 그리기 몫 기록
- 묶음 기록 runs[].work — 알림 받는 쪽 이름별 ms(가게 · 관 · 구조물 · 새 상세 · 종단도 · 다시 셈 대기 · 횡단 카드) · 그리기 몫(종단도 · 유토곡선) · 쉼(profile 뒤 쉬는 동안)
- 종단도 다시 그림 = 다음 틀 한 번(drawSoon) — 갈아끼움 render · 정책 · 이어 공사 기준 · 비정규 측점 · 새 상세 알림 · 다시 셈 뒤가 각각 바로 그리던 것(끌기 한 걸음 6~8 번 → 1 번 · 되돌리기 5 → 1)
- 노선 초안 동안 종단도 횡단 다시 셈(crossPreview)이 갈아끼운 초안 상세를 안 셈(첫 끌기 한 번 통째 다시 셈 없앰)
- 시험 test_349_0s_draw_work 4(다섯 걸음 · 걸음마다 그리기 1 · work 칸 · 되돌리기 그대로 · 다시 셈 0) · 230-2 도움이 drawSoon 도 읽음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TteK8mfYZetk5P3bEZkyVZ
2026-10-16 17:42:54 +09:00

413 lines
16 KiB
JavaScript

/* 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);
});