-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
361 lines (338 loc) · 17.7 KB
/
Copy pathindex.html
File metadata and controls
361 lines (338 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Morph Preview — convex cross-sections</title>
<style>
:root { --bg:#14171c; --panel:#1c2129; --line:#2b323d; --ink:#e6e9ee; --dim:#8b96a5; --x:#5db0ff; --y:#ffa95d; }
* { box-sizing:border-box; }
html,body { margin:0; height:100%; background:var(--bg); color:var(--ink);
font:13px/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; overflow:hidden; }
#app { display:flex; height:100%; }
#view { flex:1; position:relative; }
canvas { display:block; }
#panel { width:296px; background:var(--panel); border-left:1px solid var(--line);
padding:16px 18px 14px; overflow-y:auto; }
h1 { font-size:13px; letter-spacing:.04em; text-transform:uppercase; color:var(--dim); margin:0 0 6px; font-weight:600; }
.group { font-size:11px; letter-spacing:.03em; text-transform:uppercase; color:var(--dim);
margin:16px 0 8px; padding-bottom:4px; border-bottom:1px solid var(--line); }
select { width:100%; background:var(--bg); color:var(--ink); border:1px solid var(--line);
border-radius:4px; padding:6px 8px; font:inherit; margin-bottom:10px; }
.ctrl { margin-bottom:11px; }
.ctrl.dis { opacity:.35; }
.ctrl label { display:flex; justify-content:space-between; margin-bottom:5px; }
.ctrl.x label .val { color:var(--x); } .ctrl.y label .val { color:var(--y); } .ctrl label .val { color:var(--ink); }
input[type=range] { width:100%; }
.ctrl.x input { accent-color:var(--x); } .ctrl.y input { accent-color:var(--y); } .ctrl input { accent-color:var(--ink); }
.row { display:flex; align-items:center; gap:8px; margin:10px 0 4px; color:var(--dim); }
#profile { width:100%; background:var(--bg); border:1px solid var(--line); border-radius:4px; }
.cap { color:var(--dim); font-size:11px; margin:14px 0 2px; }
.legend { display:flex; gap:14px; font-size:11px; color:var(--dim); margin:6px 0 4px; }
.legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; }
.note { color:var(--dim); font-size:11px; line-height:1.6; margin-top:6px; }
.note b { color:var(--ink); font-weight:600; }
button#export { width:100%; margin-top:16px; padding:10px; background:var(--x); color:#0b1017;
border:none; border-radius:5px; font:inherit; font-weight:600; letter-spacing:.02em; cursor:pointer; }
button#export:hover { filter:brightness(1.08); }
#meshinfo { color:var(--dim); font-size:11px; margin-top:7px; text-align:center; }
</style>
<script type="importmap">
{ "imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}}
</script>
</head>
<body>
<div id="app">
<div id="view"></div>
<div id="panel">
<h1>Morph preview</h1>
<div class="group">Bottom cross-section</div>
<select id="bottom">
<option value="rect" selected>Rectangle</option>
<option value="oval">Oval</option>
<option value="tri">Triangle</option>
<option value="pent">Pentagon</option>
<option value="hex">Hexagon</option>
</select>
<div class="ctrl x" id="w-bX"><label>Size X <span class="val" id="v-bX">20</span></label><input type="range" id="bX" min="2" max="100" step="1" value="20"></div>
<div class="ctrl y" id="w-bY"><label>Size Y <span class="val" id="v-bY">20</span></label><input type="range" id="bY" min="2" max="100" step="1" value="20"></div>
<div class="ctrl" id="w-bRot"><label>Rotation° <span class="val" id="v-bRot">0</span></label><input type="range" id="bRot" min="-180" max="180" step="1" value="0"></div>
<div class="group">Top cross-section</div>
<select id="top">
<option value="oval" selected>Oval</option>
<option value="rect">Rectangle</option>
<option value="tri">Triangle</option>
<option value="pent">Pentagon</option>
<option value="hex">Hexagon</option>
</select>
<div class="ctrl x" id="w-tX"><label>Size X <span class="val" id="v-tX">20</span></label><input type="range" id="tX" min="2" max="100" step="1" value="20"></div>
<div class="ctrl y" id="w-tY"><label>Size Y <span class="val" id="v-tY">20</span></label><input type="range" id="tY" min="2" max="100" step="1" value="20"></div>
<div class="ctrl" id="w-tRot"><label>Rotation° <span class="val" id="v-tRot">0</span></label><input type="range" id="tRot" min="-180" max="180" step="1" value="0"></div>
<div class="group">Body</div>
<div class="ctrl"><label>Height <span class="val" id="v-height">40</span></label><input type="range" id="height" min="2" max="200" step="1" value="40"></div>
<div class="ctrl"><label>Segments <span class="val" id="v-segments">48</span></label><input type="range" id="segments" min="8" max="128" step="1" value="48"></div>
<div class="ctrl"><label>Layers <span class="val" id="v-layers">40</span></label><input type="range" id="layers" min="2" max="100" step="1" value="40"></div>
<div class="row"><input type="checkbox" id="wire"><label for="wire" style="margin:0;color:var(--dim)">Wireframe</label></div>
<button id="export">⬇ Export STL</button>
<div id="meshinfo"></div>
<div class="cap">Bounding half-extent vs height</div>
<div class="legend"><span><i style="background:var(--x)"></i>X</span><span><i style="background:var(--y)"></i>Y</span></div>
<canvas id="profile" width="260" height="140"></canvas>
<div class="note">Both ends blend with <b>smootherstep</b>, so the envelope leaves the base and meets the top with a flat tangent — no crease. Matching corner counts are auto-aligned to the least-twist rotation; unmatched corners fall back to a direct radial correspondence.</div>
</div>
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
/* ---- SHARED MATH (mirror of generate_morph_stl.py) ---- */
const NGON={tri:3,pent:5,hex:6};
function smootherstep(t){ if(t<0)t=0; else if(t>1)t=1; return t*t*t*(t*(t*6-15)+10); }
function rot2(x,y,r){ const c=Math.cos(r),s=Math.sin(r); return [x*c-y*s, x*s+y*c]; }
function basePoint(kind,a,X,Y){
if(kind==='oval') return [X*Math.cos(a), Y*Math.sin(a)];
if(kind==='rect'){ const c=Math.cos(a),d=Math.sin(a),m=Math.max(Math.abs(c)/X,Math.abs(d)/Y); return [c/m,d/m]; }
const n=NGON[kind], R=X, ap=R*Math.cos(Math.PI/n), step=2*Math.PI/n, alpha0=Math.PI/2+Math.PI/n;
let d=a-alpha0; d=((d+Math.PI/n)%step+step)%step - Math.PI/n;
const r=ap/Math.cos(d);
return [r*Math.cos(a), r*Math.sin(a)];
}
function baseCorners(kind,X,Y){
if(kind==='oval') return [];
if(kind==='rect'){ const a0=Math.atan2(Y,X); return [a0,Math.PI-a0,Math.PI+a0,2*Math.PI-a0]; }
const n=NGON[kind], out=[]; for(let k=0;k<n;k++) out.push(Math.PI/2+2*Math.PI*k/n); return out;
}
function shapePoint(kind,a,X,Y,rot){ const [x,y]=basePoint(kind,a-rot,X,Y); return rot2(x,y,rot); }
function shapeCorners(kind,X,Y,rot){ return baseCorners(kind,X,Y).map(c=>c+rot); }
// Best non-crossing correspondence between the two ends' corners: tries every
// rotational offset, picks the one minimizing total angular mismatch (DP over
// a circular subsequence alignment). Corners that can't be paired (unequal
// corner counts) fall back to the old shared-angle sampling for that corner.
function bestMatching(bc,tc){
const TWO=2*Math.PI;
const circDist=(a,b)=>{ let d=Math.abs(a-b)%TWO; if(d>Math.PI) d=TWO-d; return d; };
const nb=bc.length, nt=tc.length;
const swap=nb>nt;
const small=swap?tc:bc, large=swap?bc:tc;
const m=small.length, M=large.length;
if(M===0) return [];
let bestCost=Infinity, bestMatchOf=new Array(M).fill(-1);
for(let r=0;r<M;r++){
const largeR=Array.from({length:M},(_,k)=>large[(r+k)%M]);
const dp=Array.from({length:m+1},()=>new Array(M+1).fill(Infinity));
const choice=Array.from({length:m+1},()=>new Array(M+1).fill(0));
for(let j=0;j<=M;j++) dp[0][j]=0;
for(let i=1;i<=m;i++){
for(let j=1;j<=M;j++){
let val=dp[i][j-1], c=0;
const mv=dp[i-1][j-1]+circDist(small[i-1],largeR[j-1])**2;
if(mv<val){ val=mv; c=1; }
dp[i][j]=val; choice[i][j]=c;
}
}
const cost=dp[m][M];
if(cost<bestCost){
const matchOfR=new Array(M).fill(-1);
let i=m, j=M;
while(i>0 && j>0){ if(choice[i][j]===1){ matchOfR[j-1]=i-1; i--; j--; } else j--; }
const matchOf=new Array(M).fill(-1);
for(let k=0;k<M;k++) matchOf[(r+k)%M]=matchOfR[k];
bestCost=cost; bestMatchOf=matchOf;
}
}
const anchors=[];
for(let k=0;k<M;k++){
const largeAngle=large[k], si=bestMatchOf[k];
const smallAngle= si>=0 ? small[si] : largeAngle;
anchors.push(swap
? {aBottom:largeAngle, aTop:smallAngle, aKey:largeAngle}
: {aBottom:smallAngle, aTop:largeAngle, aKey:largeAngle});
}
return anchors;
}
function buildAngles(bottomC,topC,segments){
const TWO=2*Math.PI;
const norm=arr=>{
const a=arr.map(c=>((c%TWO)+TWO)%TWO).sort((p,q)=>p-q);
const eps=1e-6, out=[];
for(const v of a){ if(!out.length || Math.abs(v-out[out.length-1])>eps) out.push(v); }
if(out.length>=2 && Math.abs((out[0]+TWO)-out[out.length-1])<eps) out.pop();
return out;
};
const bc=norm(bottomC), tc=norm(topC);
const anchors=bestMatching(bc,tc);
if(!anchors.length){
const n=Math.max(3,Math.round(segments)), out=[];
for(let i=0;i<n;i++){ const a=TWO*i/n; out.push({aBottom:a,aTop:a}); }
return out;
}
const m=anchors.length, total=Math.max(Math.round(segments),m), fill=total-m;
const arcs=[]; let s=0;
for(let i=0;i<m;i++){ const lo=anchors[i].aKey, hi=(i===m-1)?anchors[0].aKey+TWO:anchors[i+1].aKey; arcs.push(hi-lo); s+=hi-lo; }
const base=[], frac=[]; let used=0;
for(let i=0;i<m;i++){ const ex=fill*arcs[i]/s, f=Math.floor(ex); base.push(f); frac.push(ex-f); used+=f; }
const order=[...Array(m).keys()].sort((p,q)=>frac[q]-frac[p]);
for(let i=0;i<fill-used;i++) base[order[i]]++;
const angles=[];
for(let i=0;i<m;i++){
const a0=anchors[i], nxt=anchors[(i+1)%m];
const loB=a0.aBottom, hiB=(i===m-1)?nxt.aBottom+TWO:nxt.aBottom;
const loT=a0.aTop, hiT=(i===m-1)?nxt.aTop+TWO:nxt.aTop;
angles.push({aBottom:loB, aTop:loT});
for(let k=1;k<=base[i];k++){
angles.push({ aBottom:loB+(hiB-loB)*k/(base[i]+1), aTop:loT+(hiT-loT)*k/(base[i]+1) });
}
}
return angles;
}
function ringAt(u,P,angles){
const b=smootherstep(u), z=P.height*u, ring=[];
for(const a of angles){
const [bx,by]=shapePoint(P.bottom,a.aBottom,P.bX,P.bY,P.bRot);
const [tx,ty]=shapePoint(P.top, a.aTop, P.tX,P.tY,P.tRot);
ring.push([bx*(1-b)+tx*b, by*(1-b)+ty*b, z]);
}
return ring;
}
/* ------------------------------------------------------- */
function buildGeometry(P){
const positions=[], indices=[];
const push=v=>{ positions.push(v[0],v[1],v[2]); return positions.length/3-1; };
const bc=shapeCorners(P.bottom,P.bX,P.bY,P.bRot), tc=shapeCorners(P.top,P.tX,P.tY,P.tRot);
const angles=buildAngles(bc,tc,P.segments);
const seg=angles.length, lay=Math.round(P.layers);
const grid=[];
for(let L=0;L<=lay;L++) grid.push(ringAt(L/lay,P,angles).map(push));
for(let L=0;L<lay;L++){
for(let i=0;i<seg;i++){
const j=(i+1)%seg;
const a=grid[L][i], b=grid[L][j], c=grid[L+1][j], d=grid[L+1][i];
indices.push(a,b,d, b,c,d);
}
}
const bottom=ringAt(0,P,angles).map(push), cBot=push([0,0,0]);
for(let i=0;i<seg;i++){ const j=(i+1)%seg; indices.push(cBot,bottom[j],bottom[i]); }
const top=ringAt(1,P,angles).map(push), cTop=push([0,0,P.height]);
for(let i=0;i<seg;i++){ const j=(i+1)%seg; indices.push(cTop,top[i],top[j]); }
const g=new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(positions,3));
g.setIndex(indices); g.computeVertexNormals();
return g;
}
const view=document.getElementById('view');
const scene=new THREE.Scene(); scene.background=new THREE.Color(0x14171c);
const camera=new THREE.PerspectiveCamera(45,1,0.1,5000); camera.up.set(0,0,1);
const renderer=new THREE.WebGLRenderer({antialias:true}); view.appendChild(renderer.domElement);
const controls=new OrbitControls(camera, renderer.domElement); controls.enableDamping=true;
scene.add(new THREE.HemisphereLight(0xffffff,0x30343c,0.9));
const key=new THREE.DirectionalLight(0xffffff,1.1); key.position.set(1,-1.4,2); scene.add(key);
const grid=new THREE.GridHelper(300,30,0x2b323d,0x22272f); grid.rotation.x=Math.PI/2; scene.add(grid);
const mat=new THREE.MeshStandardMaterial({color:0x9fb4c8, metalness:0.1, roughness:0.55, side:THREE.DoubleSide});
let mesh=new THREE.Mesh(new THREE.BufferGeometry(), mat); scene.add(mesh);
const P={bottom:'rect',bX:20,bY:20,bRot:0, top:'oval',tX:20,tY:20,tRot:0, height:40,segments:48,layers:40};
function syncEnabled(){
// Y is unused for polygons; grey it out.
const poly=k=>k==='tri'||k==='pent'||k==='hex';
document.getElementById('w-bY').classList.toggle('dis', poly(P.bottom));
document.getElementById('bY').disabled=poly(P.bottom);
document.getElementById('w-tY').classList.toggle('dis', poly(P.top));
document.getElementById('tY').disabled=poly(P.top);
}
function rebuild(){
mesh.geometry.dispose();
mesh.geometry=buildGeometry(P);
mesh.material.wireframe=document.getElementById('wire').checked;
controls.target.set(0,0,P.height/2);
drawProfile();
updateInfo();
}
function updateInfo(){
const g=mesh.geometry; g.computeBoundingBox(); const bb=g.boundingBox;
const tris=(g.index?g.index.count:g.attributes.position.count)/3;
const w=(bb.max.x-bb.min.x), d=(bb.max.y-bb.min.y), h=(bb.max.z-bb.min.z);
document.getElementById('meshinfo').textContent =
`${tris.toLocaleString()} triangles · ${w.toFixed(0)}×${d.toFixed(0)}×${h.toFixed(0)} mm`;
}
// Binary STL straight from the live geometry (same winding/normals as the Python exporter).
function geometryToSTL(geo){
const pos=geo.attributes.position, idx=geo.index;
const nTri=(idx?idx.count:pos.count)/3;
const buf=new ArrayBuffer(84+nTri*50), dv=new DataView(buf);
const label="morph preview STL"; for(let i=0;i<label.length;i++) dv.setUint8(i,label.charCodeAt(i));
dv.setUint32(80,nTri,true);
let off=84;
const V=i=>[pos.getX(i),pos.getY(i),pos.getZ(i)];
for(let t=0;t<nTri;t++){
const a=idx?idx.getX(t*3):t*3, b=idx?idx.getX(t*3+1):t*3+1, c=idx?idx.getX(t*3+2):t*3+2;
const va=V(a), vb=V(b), vc=V(c);
const ux=vb[0]-va[0],uy=vb[1]-va[1],uz=vb[2]-va[2], vx=vc[0]-va[0],vy=vc[1]-va[1],vz=vc[2]-va[2];
let nx=uy*vz-uz*vy, ny=uz*vx-ux*vz, nz=ux*vy-uy*vx; const L=Math.hypot(nx,ny,nz)||1;
dv.setFloat32(off,nx/L,true); dv.setFloat32(off+4,ny/L,true); dv.setFloat32(off+8,nz/L,true); off+=12;
for(const v of [va,vb,vc]){ dv.setFloat32(off,v[0],true); dv.setFloat32(off+4,v[1],true); dv.setFloat32(off+8,v[2],true); off+=12; }
dv.setUint16(off,0,true); off+=2;
}
return buf;
}
function exportSTL(){
const blob=new Blob([geometryToSTL(mesh.geometry)],{type:'model/stl'});
const url=URL.createObjectURL(blob), a=document.createElement('a');
a.href=url; a.download=`morph_${P.bottom}-${P.top}_h${Math.round(P.height)}.stl`;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(()=>URL.revokeObjectURL(url),1000);
}
function frameCamera(){
const d=Math.max(P.bX,P.bY,P.tX,P.tY,P.height)*2.6;
camera.position.set(d,-d,d*0.75); controls.target.set(0,0,P.height/2); controls.update();
}
const pc=document.getElementById('profile'), px=pc.getContext('2d');
function extentAt(u){
const b=smootherstep(u); let mx=0,my=0;
for(let k=0;k<120;k++){
const a=2*Math.PI*k/120;
const [bx,by]=shapePoint(P.bottom,a,P.bX,P.bY,P.bRot);
const [tx,ty]=shapePoint(P.top,a,P.tX,P.tY,P.tRot);
const x=Math.abs(bx*(1-b)+tx*b), y=Math.abs(by*(1-b)+ty*b);
if(x>mx)mx=x; if(y>my)my=y;
}
return [mx,my];
}
function drawProfile(){
const W=pc.width,H=pc.height,pad=14,cx=W/2;
px.clearRect(0,0,W,H);
const N=64; let maxExt=1;
const data=[]; for(let k=0;k<=N;k++){ const e=extentAt(k/N); data.push(e); maxExt=Math.max(maxExt,e[0],e[1]); }
const sx=(W/2-pad)/maxExt;
const X=e=>cx+e*sx, Y=u=>H-pad-u*(H-2*pad);
px.strokeStyle='#2b323d'; px.lineWidth=1; px.beginPath(); px.moveTo(cx,Y(0)); px.lineTo(cx,Y(1)); px.stroke();
function curve(ci,color){
px.strokeStyle=color; px.lineWidth=2;
for(const s of [1,-1]){ px.beginPath();
for(let k=0;k<=N;k++){ const x=X(s*data[k][ci]), y=Y(k/N); k?px.lineTo(x,y):px.moveTo(x,y); } px.stroke(); }
}
curve(0, getComputedStyle(document.body).getPropertyValue('--x').trim()||'#5db0ff');
curve(1, getComputedStyle(document.body).getPropertyValue('--y').trim()||'#ffa95d');
px.fillStyle='#8b96a5'; px.font='10px monospace';
px.fillText('top',cx+6,Y(1)+2); px.fillText('bottom',cx+6,Y(0)-4);
}
['bottom','top'].forEach(id=>{
document.getElementById(id).addEventListener('change',e=>{ P[id]=e.target.value; syncEnabled(); rebuild(); });
});
[['bX','bX'],['bY','bY'],['bRot','bRot'],['tX','tX'],['tY','tY'],['tRot','tRot'],['height','height'],['segments','segments'],['layers','layers']]
.forEach(([id,key])=>{
const el=document.getElementById(id), out=document.getElementById('v-'+id);
el.addEventListener('input',()=>{ out.textContent=el.value;
P[key] = (key==='bRot'||key==='tRot') ? (+el.value)*Math.PI/180 : +el.value;
rebuild();
});
});
document.getElementById('wire').addEventListener('change',()=>{ mesh.material.wireframe=document.getElementById('wire').checked; });
document.getElementById('export').addEventListener('click', exportSTL);
function resize(){ const w=view.clientWidth,h=view.clientHeight; renderer.setSize(w,h); renderer.setPixelRatio(devicePixelRatio); camera.aspect=w/h; camera.updateProjectionMatrix(); }
window.addEventListener('resize',resize);
syncEnabled(); resize(); frameCamera(); rebuild();
(function loop(){ requestAnimationFrame(loop); controls.update(); renderer.render(scene,camera); })();
</script>
</body>
</html>