diff --git a/src/gateway/routes/routes-workshop.ts b/src/gateway/routes/routes-workshop.ts index defa630..a8cec38 100644 --- a/src/gateway/routes/routes-workshop.ts +++ b/src/gateway/routes/routes-workshop.ts @@ -285,6 +285,47 @@ export function registerWorkshopRoutes( res.status(404).json({ error: 'render failed' }); }); + // ── .scad → STL (3D 미리보기용) ─────────────────────────────────────────────── + // 뷰어(scad-viewer.html)가 돌려 볼 수 있게 OpenSCAD로 바이너리 STL을 뽑아 캐시한다(.scad 파일이 바뀌면 새로). + // 렌더가 무거워 한 번에 하나씩, 실패 사유는 404 본문의 detail로 돌려준다. + let scadStlQueue: Promise = Promise.resolve(); + app.get('/api/workshop/scad-stl', async (req, res) => { + const session = getSessionUser(req); + if (!session) return res.status(401).json({ error: 'Unauthorized' }); + const projectId = String(req.query.projectId || ''); + const relPath = String(req.query.relPath || ''); + const segments = relPath.split('/').filter(Boolean); + if (!/^[a-zA-Z0-9_-]+$/.test(projectId) || !segments.length || segments.some(s => s === '..' || s === '.') || !/\.scad$/i.test(relPath)) { + return res.status(400).json({ error: 'invalid' }); + } + const workspace = getUserWorkspace(session.username); + const dir = caseFilesDir(session.username, APP_TYPE, projectId); + const scadPath = path.join(dir, ...segments); + if (!isPathInsideDir(dir, scadPath) || !fs.existsSync(scadPath)) return res.status(404).json({ error: 'not found' }); + const st = fs.statSync(scadPath); + const key = crypto.createHash('sha1').update(`scadstl/${projectId}/${relPath}/${st.mtimeMs}/${st.size}`).digest('hex').slice(0, 24); + const cacheDir = path.join(workspace, '.smallclaw', 'workshop-thumbs'); + const stl = path.join(cacheDir, `${key}.stl`); + const send = () => { res.set('Cache-Control', 'private, no-cache'); res.type('application/octet-stream').sendFile(stl, { dotfiles: 'allow' }); }; + if (fs.existsSync(stl)) return send(); + fs.mkdirSync(cacheDir, { recursive: true }); + const job = scadStlQueue.then(async () => { + if (fs.existsSync(stl)) return { ok: true as const }; + const tmp = `${stl}.tmp-${process.pid}.stl`; + const r = await runOpenscad(['-o', tmp, '--export-format=binstl', scadPath], 120_000).catch(() => ({ ok: false as const, detail: 'exception' })); + if (!r.ok || !fs.existsSync(tmp) || fs.statSync(tmp).size < 100) { + try { fs.unlinkSync(tmp); } catch { /* noop */ } + return { ok: false as const, detail: r.ok ? '내보낸 모델이 비어 있습니다(2D 전용이거나 객체가 없음).' : r.detail }; + } + fs.renameSync(tmp, stl); + return { ok: true as const }; + }); + scadStlQueue = job.catch(() => undefined); + const r = await job; + if (r.ok && fs.existsSync(stl)) return send(); + res.status(404).json({ error: 'render failed', detail: (r as any).detail || '' }); + }); + // ── 조립 설명서 ─────────────────────────────────────────────────────────────── // 명세(부품/단계)는 프로젝트 저장 API로 저장되고(project.assembly), 여기는 조회/스캔/렌더만 한다. const assemblyUrl = (projectId: string, file: string, v: number) => diff --git a/web-ui/html/scad-viewer.html b/web-ui/html/scad-viewer.html new file mode 100644 index 0000000..f0971af --- /dev/null +++ b/web-ui/html/scad-viewer.html @@ -0,0 +1,98 @@ + + + + + +SCAD 3D 보기 + + + + + +
+ SCAD + + + + </> 소스 + ⬇ STL +
+
OpenSCAD로 모델을 만드는 중… (복잡하면 수십 초 걸립니다)
+
+
드래그: 회전 · 휠: 확대 · 우클릭 드래그: 이동
+ + + + + + diff --git a/web-ui/js/app/workshop-files.js b/web-ui/js/app/workshop-files.js index f3932ac..f2262ce 100644 --- a/web-ui/js/app/workshop-files.js +++ b/web-ui/js/app/workshop-files.js @@ -146,26 +146,19 @@ function renderFileCard(file){
${thumb}
${escAttr(file.name)}
-
${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}${isScad?' · 렌더 미리보기':''}
+
${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}${isScad?' · 3D로 보기':''}
`; } -// .scad 클릭 — 큰 렌더 이미지를 새 탭에서 연다(렌더는 서버가 OpenSCAD로, 첫 렌더는 수 초). 소스는 버튼. -async function openScadPreview(relPath){ +// .scad 클릭 — 3D 뷰어(scad-viewer.html)를 팝업으로 연다: 서버가 OpenSCAD로 STL을 뽑아 오면 돌려 볼 수 있다. +// 소스는 카드의 버튼. +function openScadPreview(relPath){ const proj=currentProject();if(!proj)return; - const url='/api/workshop/thumb?projectId='+encodeURIComponent(proj.id)+'&relPath='+encodeURIComponent(relPath)+'&size=large'; - const w=window.open('','_blank'); - try{ - const r=await fetch(url,{headers:authH()}); - if(!r.ok)throw new Error(r.status===404?'렌더에 실패했습니다(코드 오류이거나 너무 오래 걸림). 버튼으로 소스를 확인하세요.':'서버 오류 '+r.status); - const blobUrl=URL.createObjectURL(await r.blob()); - if(w)w.location.href=blobUrl;else window.open(blobUrl,'_blank'); - }catch(e){ - if(w)w.close(); - alert('미리보기 실패: '+e.message); - } + const w=1100,h=820; + const left=Math.max(0,(screen.width-w)/2), top=Math.max(0,(screen.height-h)/2); + window.open('/html/scad-viewer.html?projectId='+encodeURIComponent(proj.id)+'&relPath='+encodeURIComponent(relPath),'scad-viewer',`width=${w},height=${h},left=${left},top=${top},menubar=no,toolbar=no,location=no,status=no,resizable=yes`); } // 작업실 프로젝트 relPath → 워크스페이스 전체 기준 상대경로. K2 CAD/슬라이서 라우트