fix(workshop): ASCII STL을 업로드·다운로드 시 바이너리로 변환 — 도구들이 바이너리만 읽어 썸네일·바닥 정렬이 안 되던 문제(3018 집진 슈 모델 전부 ASCII)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
444dd6ffc9
commit
881459f814
4 files changed
+151
-2
No files matched your search
@@ -20,7 +20,7 @@ import {
|
||||
listDeletedProjects, restoreFromHistory, readHistory, duplicateProject, genWorkshopId,
|
||||
} from './workshop-storage';
|
||||
import { searchDanawa } from '../../tools/danawa';
|
||||
import { renderStlPng, dropStlToFloor } from '../../tools/stl-cad-core';
|
||||
import { renderStlPng, dropStlToFloor, convertAsciiStlToBinary } from '../../tools/stl-cad-core';
|
||||
import { scanScadModules, unassignedParts } from './workshop-assembly';
|
||||
import { renderAssemblyManual, readManifest, resolveScadPath, currentAssemblyHash, assemblyOutDir, ASSEMBLY_DIR_NAME, draftAssembly } from '../../tools/workshop-assembly-render';
|
||||
import { clearHistory } from '../session';
|
||||
@@ -490,11 +490,15 @@ export function registerWorkshopRoutes(
|
||||
fs.writeFileSync(absPath, fileData);
|
||||
// 모든 STL은 기본적으로 바닥(z=0)에 붙인다(2026-09-29) — 업로드한 외부 STL도 z 평행이동만 적용.
|
||||
let zShift = 0;
|
||||
// ASCII STL은 썸네일·바닥 정렬·편집기가 못 읽는다 — 먼저 바이너리로 바꾼다(convertAsciiStlToBinary).
|
||||
let asciiConverted = false;
|
||||
if (/\.stl$/i.test(absPath)) { const cr = convertAsciiStlToBinary(absPath); if (cr.ok) asciiConverted = cr.converted; }
|
||||
if (/\.stl$/i.test(absPath)) { const zr = dropStlToFloor(absPath); if (zr.ok) zShift = zr.shifted; }
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
zAlignedMm: zShift ? Number(zShift.toFixed(3)) : 0,
|
||||
asciiConverted,
|
||||
name: path.basename(relPath),
|
||||
relPath,
|
||||
size: fileData.length,
|
||||
|
||||
@@ -7,7 +7,7 @@ import { getWorkspacePath } from '../config/paths.js';
|
||||
import { isPathInsideDir } from './image.js';
|
||||
import { findWorkshopProjectName } from './print3d.js';
|
||||
import { saveDirs } from '../gateway/routes/workshop-layout.js';
|
||||
import { analyzeStl, dropStlToFloor } from './stl-cad-core.js';
|
||||
import { analyzeStl, dropStlToFloor, convertAsciiStlToBinary } from './stl-cad-core.js';
|
||||
|
||||
// 3D 모델 저장소 검색+다운로드 (2026-09-23) — Printables / MakerWorld / Thingiverse.
|
||||
// 세 곳 모두 공식 API가 없거나(Printables/MakerWorld) 응용토큰이 필요한(Thingiverse) 사이라
|
||||
@@ -490,6 +490,7 @@ export const modelDownloadTool = {
|
||||
if (/\.stl$/i.test(outPath)) {
|
||||
try {
|
||||
// 기본 규칙: 모든 STL은 바닥(z=0)에 붙인다 — 미터 단위(<0.5)면 변환 뒤에 다시 맞춘다.
|
||||
convertAsciiStlToBinary(outPath); // 저장소 모델은 ASCII가 흔하다 — 바이너리로 바꿔야 z 정렬·썸네일이 된다
|
||||
const zr = dropStlToFloor(outPath);
|
||||
if (zr.ok && zr.shifted) unitNote += `\n- 바닥(z=0)에 맞춤: z ${zr.shifted > 0 ? '+' : ''}${zr.shifted.toFixed(2)}mm 이동`;
|
||||
const a = analyzeStl(outPath);
|
||||
|
||||
@@ -126,6 +126,49 @@ export function runOpenscad(args: string[], timeoutMs = 60_000): Promise<{ ok: t
|
||||
// 바이너리 STL(80바이트 헤더+삼각형수(4B)+삼각형마다 50B)만 지원 — 3D프린팅에서 압도적으로
|
||||
// 흔한 포맷. ASCII STL("solid ..."로 시작)은 파일 크기가 이 공식과 안 맞을 테니 감지해서
|
||||
// 에러로 안내한다.
|
||||
/**
|
||||
* ASCII STL을 바이너리 STL로 제자리 변환한다(2026-09-30).
|
||||
*
|
||||
* 왜 필요한가. 이 프로젝트의 STL 도구(bbox·바닥 정렬·편집기·썸네일 렌더러)는 전부 바이너리 STL만
|
||||
* 읽는다. 그런데 외부 저장소(Thingiverse·Printables 등)의 모델은 ASCII로 오는 일이 흔하다 —
|
||||
* 3018 집진 슈 모델 10개가 전부 ASCII라 업로드해도 썸네일이 없고 바닥 정렬도 안 됐다. 들어오는
|
||||
* 순간 바이너리로 바꿔 두면 아래 도구들이 그대로 동작한다. 기하 정보(삼각형·법선)는 그대로다.
|
||||
*
|
||||
* 판정 순서가 중요하다: 크기가 바이너리 공식(84 + 삼각형수*50)에 맞으면 헤더가 "solid"로
|
||||
* 시작해도(SolidWorks 등) 바이너리다 — 건드리지 않는다. 맞지 않고 "solid"로 시작할 때만 ASCII로 본다.
|
||||
*/
|
||||
export function convertAsciiStlToBinary(filePath: string): { ok: true; converted: boolean; triangles: number } | { ok: false; detail: string } {
|
||||
let buf: Buffer;
|
||||
try { buf = fs.readFileSync(filePath); } catch (e: any) { return { ok: false, detail: String(e?.message || e) }; }
|
||||
if (buf.length >= 84 && buf.length === 84 + buf.readUInt32LE(80) * 50) {
|
||||
return { ok: true, converted: false, triangles: buf.readUInt32LE(80) };
|
||||
}
|
||||
const head = buf.subarray(0, 256).toString('utf8').replace(/^\uFEFF/, '').trimStart().toLowerCase();
|
||||
if (!head.startsWith('solid')) return { ok: false, detail: 'ASCII도 바이너리도 아닌 파일입니다.' };
|
||||
|
||||
const text = buf.toString('utf8');
|
||||
const num = '([-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?)';
|
||||
const v = `vertex\\s+${num}\\s+${num}\\s+${num}`;
|
||||
const re = new RegExp(`facet\\s+normal\\s+${num}\\s+${num}\\s+${num}\\s+outer\\s+loop\\s+${v}\\s+${v}\\s+${v}\\s+endloop\\s+endfacet`, 'gi');
|
||||
const facets: number[][] = [];
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(text)) !== null) facets.push(m.slice(1, 13).map(Number));
|
||||
if (facets.length === 0) return { ok: false, detail: 'ASCII STL에서 삼각형을 찾지 못했습니다.' };
|
||||
|
||||
const out = Buffer.alloc(84 + facets.length * 50);
|
||||
out.write('Converted from ASCII STL', 0, 'latin1');
|
||||
out.writeUInt32LE(facets.length, 80);
|
||||
let off = 84;
|
||||
for (const f of facets) {
|
||||
for (let i = 0; i < 12; i++) { out.writeFloatLE(f[i], off); off += 4; }
|
||||
off += 2; // attribute byte count = 0
|
||||
}
|
||||
const tmp = `${filePath}.tmp-${process.pid}`;
|
||||
try { fs.writeFileSync(tmp, out); fs.renameSync(tmp, filePath); }
|
||||
catch (e: any) { try { fs.unlinkSync(tmp); } catch { /* noop */ } return { ok: false, detail: String(e?.message || e) }; }
|
||||
return { ok: true, converted: true, triangles: facets.length };
|
||||
}
|
||||
|
||||
export function readStlBBox(filePath: string): StlBBox {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
if (buf.length < 84) throw new Error('STL 파일이 너무 작거나 손상되었습니다.');
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* convertAsciiStlToBinary — ASCII STL을 바이너리로 제자리 변환
|
||||
*
|
||||
* 표본은 2026-09-30 3018 집진 슈 모델 10개(Printables 압축 파일): 전부 ASCII라 업로드해도
|
||||
* 썸네일이 안 뜨고 바닥(z=0) 정렬도 안 됐다. 도구들이 바이너리만 읽기 때문이다.
|
||||
* 고정하는 것: ASCII는 변환된다 / 바이너리는 (헤더가 "solid"여도) 손대지 않는다 / 쓰레기는 실패한다.
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { convertAsciiStlToBinary, readStlBBox, dropStlToFloor } from '../src/tools/stl-cad-core';
|
||||
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-ascii-'));
|
||||
const f = (name: string) => path.join(tmp, name);
|
||||
|
||||
function asciiTri(n: number[], v: number[][], eol = '\n'): string {
|
||||
const fmt = (a: number[]) => a.join(' ');
|
||||
return [`facet normal ${fmt(n)}`, ' outer loop', ...v.map((p) => ` vertex ${fmt(p)}`), ' endloop', 'endfacet'].join(eol) + eol;
|
||||
}
|
||||
|
||||
// 밑면이 z=5인 사각뿔 대용: 삼각형 2개짜리 사각형(z=5~7) — 바닥 정렬 검증용
|
||||
function asciiSquare(eol = '\n', z0 = 5): string {
|
||||
return `solid test${eol}`
|
||||
+ asciiTri([0, 0, 1], [[0, 0, z0], [10, 0, z0], [10, 10, z0 + 2]], eol)
|
||||
+ asciiTri([0, 0, 1], [[0, 0, z0], [10, 10, z0 + 2], [0, 10, z0]], eol)
|
||||
+ `endsolid test${eol}`;
|
||||
}
|
||||
|
||||
function binaryStl(tris: number[][][], header = 'binary header'): Buffer {
|
||||
const b = Buffer.alloc(84 + tris.length * 50);
|
||||
b.write(header, 0, 'latin1');
|
||||
b.writeUInt32LE(tris.length, 80);
|
||||
let off = 84;
|
||||
for (const t of tris) {
|
||||
off += 12;
|
||||
for (const p of t) { for (const c of p) { b.writeFloatLE(c, off); off += 4; } }
|
||||
off += 2;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
describe('convertAsciiStlToBinary', () => {
|
||||
test('ASCII STL을 바이너리로 바꾸고, 이후 bbox·바닥 정렬이 동작한다', () => {
|
||||
fs.writeFileSync(f('a.stl'), asciiSquare());
|
||||
assert.throws(() => readStlBBox(f('a.stl')), /바이너리 STL만/); // 변환 전에는 못 읽는다(원래 문제)
|
||||
const r = convertAsciiStlToBinary(f('a.stl'));
|
||||
assert.deepEqual(r, { ok: true, converted: true, triangles: 2 });
|
||||
const bb = readStlBBox(f('a.stl'));
|
||||
assert.deepEqual(bb.min, [0, 0, 5]);
|
||||
assert.deepEqual(bb.max, [10, 10, 7]);
|
||||
const drop = dropStlToFloor(f('a.stl'));
|
||||
assert.equal(drop.ok, true);
|
||||
assert.equal(readStlBBox(f('a.stl')).min[2], 0);
|
||||
});
|
||||
|
||||
test('CRLF 줄바꿈·탭·지수 표기(1e-3)도 읽는다', () => {
|
||||
const txt = `solid x\r\nfacet normal 0 0 1\r\n\touter loop\r\n\t\tvertex 1.5e1 -2E0 +3.\r\n\t\tvertex 0 0 0\r\n\t\tvertex .5 1e-3 2\r\n\tendloop\r\nendfacet\r\nendsolid x\r\n`;
|
||||
fs.writeFileSync(f('crlf.stl'), txt);
|
||||
const r = convertAsciiStlToBinary(f('crlf.stl'));
|
||||
assert.equal(r.ok && r.converted, true);
|
||||
const buf = fs.readFileSync(f('crlf.stl'));
|
||||
assert.equal(buf.length, 84 + 50);
|
||||
assert.equal(buf.readFloatLE(84 + 12), 15); // 첫 정점 x
|
||||
assert.equal(buf.readFloatLE(84 + 16), -2);
|
||||
});
|
||||
|
||||
test('solid 여러 개인 파일은 삼각형을 모두 모은다', () => {
|
||||
fs.writeFileSync(f('multi.stl'), asciiSquare() + asciiSquare('\n', 20));
|
||||
const r = convertAsciiStlToBinary(f('multi.stl'));
|
||||
assert.deepEqual(r, { ok: true, converted: true, triangles: 4 });
|
||||
});
|
||||
|
||||
test('바이너리는 손대지 않는다 — 헤더가 "solid"로 시작해도(SolidWorks 등)', () => {
|
||||
const b = binaryStl([[[0, 0, 0], [1, 0, 0], [0, 1, 0]]], 'solid exported by CAD');
|
||||
fs.writeFileSync(f('bin.stl'), b);
|
||||
const r = convertAsciiStlToBinary(f('bin.stl'));
|
||||
assert.deepEqual(r, { ok: true, converted: false, triangles: 1 });
|
||||
assert.deepEqual(fs.readFileSync(f('bin.stl')), b);
|
||||
});
|
||||
|
||||
test('ASCII도 바이너리도 아니면 실패하고 파일을 그대로 둔다', () => {
|
||||
fs.writeFileSync(f('junk.stl'), 'this is not an stl file at all, just some text.');
|
||||
const before = fs.readFileSync(f('junk.stl'));
|
||||
const r = convertAsciiStlToBinary(f('junk.stl'));
|
||||
assert.equal(r.ok, false);
|
||||
assert.deepEqual(fs.readFileSync(f('junk.stl')), before);
|
||||
});
|
||||
|
||||
test('solid로 시작하지만 삼각형이 없으면 실패하고 파일을 그대로 둔다', () => {
|
||||
fs.writeFileSync(f('empty.stl'), 'solid empty\nendsolid empty\n');
|
||||
const r = convertAsciiStlToBinary(f('empty.stl'));
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(fs.readFileSync(f('empty.stl'), 'utf8'), 'solid empty\nendsolid empty\n');
|
||||
});
|
||||
|
||||
test('없는 파일은 실패로 돌려준다(예외 아님)', () => {
|
||||
assert.equal(convertAsciiStlToBinary(f('nope.stl')).ok, false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user