feat(workshop): .scad 3D 뷰어 — 카드 클릭 시 OpenSCAD로 STL을 뽑아(캐시) Three.js로 회전·확대·와이어·자동회전, 소스/STL 받기
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1e75730353
commit
d0ee3e16e7
3 files changed
+146
-14
No files matched your search
@@ -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<unknown> = 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) =>
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>SCAD 3D 보기</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="/homeclaw_logo.png">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--bg:#f2f4f7;--fg:#1b2430;--bar:#ffffff;--line:#d3dbe4;--muted:#5d6b7c;--btn:#e8edf3;--on:#2b7fd9}
|
||||
:root[data-theme="dark"]{--bg:#161b22;--fg:#e4eaf1;--bar:#1e252e;--line:#2c3744;--muted:#93a1b2;--btn:#2a3340;--on:#5aa2f0}
|
||||
html,body{height:100%;margin:0;background:var(--bg);color:var(--fg);font-family:'Noto Sans KR',system-ui,sans-serif;overflow:hidden}
|
||||
#bar{position:fixed;top:0;left:0;right:0;display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;padding:8px 12px;background:var(--bar);border-bottom:1px solid var(--line);z-index:2;font-size:13px}
|
||||
#bar b{font-size:14px}#bar .sp{flex:1}
|
||||
button,a.b{background:var(--btn);color:var(--fg);border:1px solid var(--line);border-radius:6px;padding:4px 10px;font-size:12px;cursor:pointer;text-decoration:none}
|
||||
button.on{background:var(--on);color:#fff;border-color:var(--on)}
|
||||
#c{position:fixed;inset:0;top:44px}
|
||||
#msg{position:fixed;inset:44px 0 0 0;display:flex;align-items:center;justify-content:center;text-align:center;padding:24px;color:var(--muted);line-height:1.7;z-index:1;white-space:pre-wrap}
|
||||
#info{position:fixed;left:12px;bottom:10px;font-size:12px;color:var(--muted);z-index:2;font-variant-numeric:tabular-nums}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="bar">
|
||||
<b id="ttl">SCAD</b><span id="sz" style="color:var(--muted)"></span><span class="sp"></span>
|
||||
<button id="bw" onclick="toggleWire()">와이어</button>
|
||||
<button onclick="resetView()">시점 초기화</button>
|
||||
<button id="bs" onclick="toggleSpin()">자동 회전</button>
|
||||
<a class="b" id="src" target="_blank" rel="noopener"></> 소스</a>
|
||||
<a class="b" id="dl" download>⬇ STL</a>
|
||||
</div>
|
||||
<div id="msg">OpenSCAD로 모델을 만드는 중… (복잡하면 수십 초 걸립니다)</div>
|
||||
<div id="c"></div>
|
||||
<div id="info">드래그: 회전 · 휠: 확대 · 우클릭 드래그: 이동</div>
|
||||
<script src="/vendor/three/three.min.js"></script>
|
||||
<script src="/vendor/three/STLLoader.js"></script>
|
||||
<script src="/vendor/three/OrbitControls.js"></script>
|
||||
<script>
|
||||
const q=new URLSearchParams(location.search), pid=q.get('projectId')||'', rel=q.get('relPath')||'';
|
||||
document.getElementById('ttl').textContent=rel.split('/').pop()||'SCAD';
|
||||
document.title=(rel.split('/').pop()||'SCAD')+' · 3D';
|
||||
function authH(){let t='';try{t=sessionStorage.getItem('smallclaw_token')||localStorage.getItem('smallclaw_token')||'';}catch(e){}return t?{Authorization:'Bearer '+t}:{};}
|
||||
let scene,camera,renderer,controls,mesh,wire=false,fit=null;
|
||||
function init(){
|
||||
const c=document.getElementById('c');
|
||||
scene=new THREE.Scene();
|
||||
scene.background=new THREE.Color(getComputedStyle(document.body).backgroundColor);
|
||||
camera=new THREE.PerspectiveCamera(40,c.clientWidth/c.clientHeight,0.1,100000);
|
||||
camera.up.set(0,0,1); // OpenSCAD는 Z가 위
|
||||
renderer=new THREE.WebGLRenderer({antialias:true});
|
||||
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
|
||||
renderer.setSize(c.clientWidth,c.clientHeight);
|
||||
c.appendChild(renderer.domElement);
|
||||
controls=new THREE.OrbitControls(camera,renderer.domElement);
|
||||
controls.enableDamping=true;
|
||||
scene.add(new THREE.HemisphereLight(0xffffff,0x445566,0.75));
|
||||
const d=new THREE.DirectionalLight(0xffffff,0.8); d.position.set(1,-1.5,2); scene.add(d);
|
||||
const d2=new THREE.DirectionalLight(0xffffff,0.35); d2.position.set(-1,1,-0.5); scene.add(d2);
|
||||
addEventListener('resize',()=>{camera.aspect=c.clientWidth/c.clientHeight;camera.updateProjectionMatrix();renderer.setSize(c.clientWidth,c.clientHeight);});
|
||||
(function loop(){requestAnimationFrame(loop);controls.update();renderer.render(scene,camera);})();
|
||||
}
|
||||
function resetView(){
|
||||
if(!fit)return;
|
||||
const {c,r}=fit; const dist=r/Math.sin(camera.fov*Math.PI/360)*1.1;
|
||||
camera.position.set(c.x+dist*0.6,c.y-dist*0.8,c.z+dist*0.55);
|
||||
camera.near=Math.max(0.01,dist/1000);camera.far=dist*20;camera.updateProjectionMatrix();
|
||||
controls.target.copy(c);controls.update();
|
||||
}
|
||||
function toggleWire(){wire=!wire;if(mesh)mesh.material.wireframe=wire;document.getElementById('bw').classList.toggle('on',wire);}
|
||||
function toggleSpin(){controls.autoRotate=!controls.autoRotate;controls.autoRotateSpeed=2.5;document.getElementById('bs').classList.toggle('on',controls.autoRotate);}
|
||||
async function load(){
|
||||
const msg=document.getElementById('msg');
|
||||
if(!pid||!rel){msg.textContent='프로젝트/파일이 지정되지 않았습니다.';return;}
|
||||
const base='/api/workshop/scad-stl?projectId='+encodeURIComponent(pid)+'&relPath='+encodeURIComponent(rel);
|
||||
document.getElementById('src').href='/api/files/workshop/'+encodeURIComponent(pid)+'/'+rel.split('/').map(encodeURIComponent).join('/');
|
||||
try{
|
||||
const r=await fetch(base,{credentials:'include',headers:authH()});
|
||||
if(!r.ok){let d={};try{d=await r.json();}catch(e){} throw new Error((d.detail||d.error||('서버 오류 '+r.status)));}
|
||||
const buf=await r.arrayBuffer();
|
||||
const dl=document.getElementById('dl'); dl.href=URL.createObjectURL(new Blob([buf],{type:'application/octet-stream'})); dl.download=(rel.split('/').pop()||'model').replace(/\.scad$/i,'')+'.stl';
|
||||
const geo=new THREE.STLLoader().parse(buf);
|
||||
geo.computeVertexNormals(); geo.computeBoundingBox();
|
||||
const bb=geo.boundingBox, size=new THREE.Vector3(); bb.getSize(size);
|
||||
mesh=new THREE.Mesh(geo,new THREE.MeshStandardMaterial({color:0x6aa5e8,metalness:0.1,roughness:0.55,side:THREE.DoubleSide,flatShading:false}));
|
||||
scene.add(mesh);
|
||||
const edges=new THREE.LineSegments(new THREE.EdgesGeometry(geo,35),new THREE.LineBasicMaterial({color:0x1d3552,transparent:true,opacity:0.35}));
|
||||
mesh.add(edges);
|
||||
const ctr=new THREE.Vector3(); bb.getCenter(ctr);
|
||||
const grid=new THREE.GridHelper(Math.max(size.x,size.y)*2.2||100,20,0x888888,0x444444); grid.rotation.x=Math.PI/2; grid.position.set(ctr.x,ctr.y,bb.min.z); grid.material.opacity=0.4; grid.material.transparent=true; scene.add(grid);
|
||||
fit={c:ctr,r:Math.max(size.length()/2,1)};
|
||||
resetView();
|
||||
document.getElementById('sz').textContent=' · '+size.x.toFixed(1)+' × '+size.y.toFixed(1)+' × '+size.z.toFixed(1)+' mm · 삼각형 '+(geo.attributes.position.count/3).toLocaleString();
|
||||
msg.remove();
|
||||
}catch(e){ msg.textContent='3D 모델을 만들지 못했습니다.\n'+e.message+'\n\n소스(</> 버튼)를 확인하세요.'; }
|
||||
}
|
||||
init(); load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -146,26 +146,19 @@ function renderFileCard(file){
|
||||
<div class="rb-file-thumb">${thumb}</div>
|
||||
<div class="rb-file-info">
|
||||
<div class="rb-file-name" title="${escAttr(file.name)}">${escAttr(file.name)}</div>
|
||||
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}${isScad?' · 렌더 미리보기':''}</div>
|
||||
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}${isScad?' · 3D로 보기':''}</div>
|
||||
</div>
|
||||
</a>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// .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/슬라이서 라우트
|
||||
|
||||
Reference in new issue
Block a user