BLOB CUT PATTERN v1.0

Live ↗ZIP (lokal ausführbar)
Beschreibung

Web-based prototype for turning a sculpted blob form into flat sewing pattern pieces. The form is built from blended signed distance shapes (spheres, cubes, capsules, splines and pulled horns) that are polygonised into a mesh with surface nets. In a second stage the surface is cut along seams drawn on the form, and the resulting pieces are flattened with LSCM and ARAP so that the 2D pattern keeps the 3D lengths. Seam suggestions are derived from curvature and from the strain of the flat pieces against a material stretch limit. The output is a 1:1 mm SVG pattern with seam allowance, notches and seam numbers, plus a JSON project for an external inflate tool. The prototype is meant for design exploration, for testing how a form can be sewn from flat fabric, and as a starting point for further pattern tools.

  • Version: v1.0
  • Sculpting with blended positive and negative blobs, symmetry and deformers
  • Reference mesh import from .glb, used as guide, cutting shape or solid
  • Cut stage with pen, erase and select tools for seams on the surface
  • Piece analysis with curvature, strain and suggested seams
  • Flat pattern computed with LSCM and ARAP, shown in a 2D preview
  • Export of a 1:1 mm SVG pattern and an inflate JSON project
  • High resolution mesh render and .glb download
  • Tech: Three.js r170, WebGL, JavaScript modules, import map, CDN
  • Requires: WebGL-capable browser, internet connection for Three.js from a CDN, .glb file for the optional reference mesh
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>BLOB:CUTTER v1.0</title>
<style>
:root{--bg:#ececec;--ink:#151515;--mute:#8e8e8e;--line:#e6e6e6}
*{box-sizing:border-box;margin:0;padding:0}
[hidden]{display:none!important}
html,body{height:100%;overflow:hidden;background:var(--bg);color:var(--ink);
  font:500 9px/1.3 -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif;
  letter-spacing:.12em;text-transform:uppercase;user-select:none;-webkit-user-select:none}
#view{position:fixed;inset:0}
canvas{display:block;width:100%;height:100%;touch-action:none;outline:none}

.panel{position:fixed;background:#fff;border-radius:6px;padding:10px 11px;
  box-shadow:0 1px 2px rgba(0,0,0,.04),0 6px 24px rgba(0,0,0,.05)}
#brand{position:fixed;left:16px;top:14px;pointer-events:none}
#brand b{display:block;font-weight:600;letter-spacing:.2em}
#brand span{display:block;color:var(--mute);margin-top:4px;font-variant-numeric:tabular-nums}
#hint{position:fixed;left:50%;top:14px;transform:translateX(-50%);color:var(--mute);pointer-events:none;white-space:nowrap}

.tabs{display:flex;gap:3px;margin-bottom:12px}
.tabs button{flex:1;justify-content:center;padding:6px 0;color:var(--mute);letter-spacing:.06em}
.tabs button.on{color:var(--ink)}
body:not(.tab-form) .t-form,body:not(.tab-ref) .t-ref,body:not(.tab-cut) .t-cut,body:not(.tab-look) .t-look,body:not(.tab-file) .t-file{display:none!important}
body.cut .sc{display:none!important}
body:not(.cut) .ct{display:none!important}
#pat{left:14px;top:62px;bottom:16px;width:min(46vw,640px);padding:0;overflow:hidden}
#pat canvas{position:absolute;inset:0;width:100%;height:100%;cursor:grab}
#pat .ptag{position:absolute;left:12px;top:10px;color:var(--mute);pointer-events:none}
#pat .pbtn{position:absolute;right:8px;top:6px;display:flex;gap:4px}
#pat .pbtn button{padding:4px 7px}
#cutSel,#cutInfo{color:var(--ink);line-height:1.55;margin-top:8px;letter-spacing:.08em}
#cutSel .m,#cutInfo .m{color:var(--mute)}
#cutInfo .w{color:#c2453b}
.kv{display:flex;justify-content:space-between}
.kv b{font-weight:500;color:var(--mute);font-variant-numeric:tabular-nums}
body.cut #brand{display:none}
#btnCuts{position:fixed;left:14px;top:14px;z-index:5;background:#151515;color:#fff;border-color:#151515;font-weight:600;letter-spacing:.16em;padding:9px 14px}
#btnCuts:hover{background:#333;border-color:#333}
#btnCuts .dot{display:none;width:7px;height:7px;border-radius:50%;background:#ff7a00}
#btnCuts.stale .dot{display:inline-block}
#btnCuts:disabled{background:#8e8e8e;border-color:#8e8e8e;color:#fff}
#ctip{position:fixed;z-index:20;pointer-events:none;background:#fff;border-radius:4px;padding:6px 8px;box-shadow:0 2px 10px rgba(0,0,0,.08);white-space:nowrap}
#propList{margin-top:8px;line-height:1.55}
#propList .pr{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:3px 0;border-bottom:1px solid var(--line)}
#propList .pr button{padding:4px 7px}
#propList .pr.on span{color:#ff2d95}
#cbar{left:50%;bottom:16px;transform:translateX(-50%);display:flex;gap:5px;padding:6px;align-items:center}
select{font:inherit;letter-spacing:inherit;text-transform:inherit;width:100%;border:1px solid var(--line);border-radius:4px;background:#fff;padding:6px 5px;color:var(--ink);margin:0 0 7px;cursor:pointer}
#detNote,#dstatus{color:var(--mute);margin-top:8px;min-height:11px;line-height:1.5}
#views{left:50%;top:14px;transform:translateX(-50%);display:flex;gap:4px;padding:5px}
#views button{padding:5px 8px;color:var(--mute)}
#views button.on{color:var(--ink)}
#add{left:14px;top:50%;transform:translateY(-50%);width:116px;display:flex;flex-direction:column;gap:5px}
#side{right:14px;top:14px;width:244px;max-height:calc(100% - 28px);overflow:auto}
#bar{left:50%;bottom:16px;transform:translateX(-50%);display:flex;gap:5px;padding:6px}

.h{color:var(--mute);margin-bottom:9px;letter-spacing:.18em}
.sec{padding-bottom:12px;margin-bottom:12px;border-bottom:1px solid var(--line)}
.sec:last-child{border:0;margin:0;padding-bottom:0}
.row{display:flex;justify-content:space-between;align-items:center;margin:0 0 3px}
.row b{font-weight:500;color:var(--mute);font-variant-numeric:tabular-nums}
.gap{height:9px}

button{font:inherit;letter-spacing:inherit;text-transform:inherit;color:var(--ink);background:#fff;
  border:1px solid var(--line);border-radius:4px;padding:7px 9px;cursor:pointer;
  display:flex;align-items:center;gap:8px;transition:background .12s,border-color .12s,color .12s}
button:hover{background:#f6f6f6;border-color:#d6d6d6}
button:active{background:#efefef}
button.on{border-color:var(--ink)}
button:disabled{color:#c2c2c2;cursor:default;background:#fff;border-color:var(--line)}
button.del{color:#c2453b}
button svg{width:14px;height:14px;flex:none;fill:none;stroke:var(--ink);stroke-width:1.2}
input[type=color]{-webkit-appearance:none;appearance:none;width:38px;height:14px;border:1px solid #d8d8d8;border-radius:3px;padding:0;background:none;cursor:pointer}
input[type=color]::-webkit-color-swatch-wrapper{padding:0}
input[type=color]::-webkit-color-swatch{border:0;border-radius:2px}
input[type=color]::-moz-color-swatch{border:0;border-radius:2px}
.seg{display:flex;gap:4px}
.seg button{flex:1;justify-content:center;padding:6px 4px;color:var(--mute)}
.seg button.on{color:var(--ink)}
.full{width:100%;justify-content:center}
.stack{display:flex;flex-direction:column;gap:5px}
#status{color:var(--mute);margin-top:9px;min-height:11px;font-variant-numeric:tabular-nums}

input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:14px;background:transparent;margin:0 0 4px;cursor:pointer}
input[type=range]::-webkit-slider-runnable-track{height:1px;background:#d8d8d8}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:9px;height:9px;border-radius:50%;background:#fff;border:1px solid var(--ink);margin-top:-4px}
input[type=range]::-moz-range-track{height:1px;background:#d8d8d8}
input[type=range]::-moz-range-thumb{width:7px;height:7px;border-radius:50%;background:#fff;border:1px solid var(--ink)}
</style>
<script type="importmap">
{"imports":{
  "three":"https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/":"https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
}}
</script>
</head>
<body>

<div id="view"><canvas id="c"></canvas></div>

<div id="brand"><b>BLOB:CUTTER v1.0</b><span id="stats">—</span></div>

<div class="panel" id="views">
  <button data-view="top">TOP</button><button data-view="bottom">BOTTOM</button>
  <button data-view="front">FRONT</button><button data-view="back">BACK</button>
  <button data-view="left">LEFT</button><button data-view="right">RIGHT</button>
</div>

<div class="panel sc" id="add">
  <div class="h">LAYER</div>
  <button id="modePos" class="on"><svg viewBox="0 0 14 14"><circle cx="7" cy="7" r="4.6" fill="#fff"/></svg>POSITIVE</button>
  <button id="modeNeg"><svg viewBox="0 0 14 14"><circle cx="7" cy="7" r="4.6" fill="#151515"/></svg>NEGATIVE</button>
  <div class="h" style="margin:7px 0 4px">ADD</div>
  <button data-add="sphere"><svg viewBox="0 0 14 14"><circle cx="7" cy="7" r="5.2"/></svg>SPHERE</button>
  <button data-add="cube"><svg viewBox="0 0 14 14"><rect x="2" y="2" width="10" height="10" rx="3"/></svg>CUBE</button>
  <button data-add="capsule"><svg viewBox="0 0 14 14"><rect x="4.4" y="1.4" width="5.2" height="11.2" rx="2.6"/></svg>CAPSULE</button>
  <button data-add="spline"><svg viewBox="0 0 14 14"><path d="M1.5 10.5C4 10.5 4 3.5 7 3.5S10 10.5 12.5 10.5"/></svg>SPLINE</button>
  <button data-add="pull"><svg viewBox="0 0 14 14"><path d="M2 12.5C5 12.5 5.6 8 7 1.5 8.4 8 9 12.5 12 12.5"/></svg>PULL</button>
</div>

<div class="panel" id="side">
  <div class="sec">
    <div class="h">STAGE</div>
    <div class="seg"><button id="stSculpt" class="on">SCULPT</button><button id="stCut">CUT</button></div>
    <div id="detNote"></div>
  </div>

  <div class="tabs" id="tabs"><button data-tab="form" class="on">FORM</button><button data-tab="ref">REF</button><button data-tab="cut" class="ct">CUT</button><button data-tab="look">LOOK</button><button data-tab="file">FILE</button></div>

  <div class="sec sc t-form" id="selSec" hidden>
    <div class="h" id="selTitle">SELECTED</div>
    <div class="row"><span>RADIUS</span><b id="vR"></b></div>
    <input id="sR" type="range" min="0.03" max="1.2" step="0.005" value="0.3">
    <div id="rowRound" hidden>
      <div class="row"><span>ROUNDNESS</span><b id="vRound"></b></div>
      <input id="sRound" type="range" min="0" max="1" step="0.01" value="0.35">
    </div>
    <div id="rowDef" hidden style="margin-top:6px">
      <div class="row"><span>TAPER</span><b id="vDt"></b></div>
      <input id="sDt" type="range" min="-1" max="1" step="0.01" value="0">
      <div class="row"><span>BEND</span><b id="vDb"></b></div>
      <input id="sDb" type="range" min="-1" max="1" step="0.01" value="0">
      <div class="row"><span>TWIST</span><b id="vDw"></b></div>
      <input id="sDw" type="range" min="-1" max="1" step="0.01" value="0">
    </div>
    <div id="rowSpl" hidden style="margin-top:6px"><button class="full" id="btnAuto">AUTO-SMOOTH HANDLES</button></div>
    <div id="rowSplT" hidden style="margin-top:8px">
      <div class="row"><span>TAPER</span><b id="vSt"></b></div>
      <input id="sSt" type="range" min="-1" max="1" step="0.01" value="0">
    </div>
    <div id="rowNode" hidden>
      <div class="row"><span>NODE RADIUS · SHIFT+DRAG NODE</span><b id="vNr"></b></div>
      <input id="sNr" type="range" min="0.05" max="3" step="0.01" value="1">
    </div>
    <div id="rowLen" hidden>
      <div class="row"><span>LENGTH</span><b id="vLen"></b></div>
      <input id="sLen" type="range" min="0" max="1.5" step="0.01" value="0.4">
    </div>
  </div>


  <div class="sec t-ref">
    <div class="h">REFERENCE MESH</div>
    <div class="seg sc"><button id="refLoad">LOAD .GLB</button><button id="refClear" hidden>REMOVE</button></div>
    <input id="refFile" type="file" accept=".glb,.gltf,model/gltf-binary" hidden>
    <div id="refName" style="color:var(--mute);margin-top:6px">NO MESH LOADED</div>
    <div id="refCtl" hidden>
      <div class="sc">
        <div class="row" style="margin-top:8px"><span>USE AS</span></div>
        <div class="seg"><button id="rm_guide" class="on">GUIDE</button><button id="rm_cut">CUT</button><button id="rm_add">ADD</button></div>
      </div>
      <div class="row" style="margin-top:8px"><span>SHOW MESH</span></div>
      <div class="seg"><button id="rgOn" class="on">ON</button><button id="rgOff">OFF</button></div>
      <div class="h" style="margin:12px 0 7px">MESH MATERIAL</div>
      <div class="row" style="margin-bottom:8px"><span>COLOR</span><input id="rmColor" type="color" value="#9aa4b4"></div>
      <div class="row"><span>OPACITY</span><b id="vRmO"></b></div>
      <input id="sRmO" type="range" min="0.05" max="1" step="0.01" value="0.3">
      <div class="row"><span>SMOOTHNESS</span><b id="vRmS"></b></div>
      <input id="sRmS" type="range" min="0" max="1" step="0.01" value="0.4">
      <div class="row"><span>METALLIC</span><b id="vRmM"></b></div>
      <input id="sRmM" type="range" min="0" max="1" step="0.01" value="0">
      <div class="row"><span>DISPLAY</span></div>
      <div class="seg"><button id="rwSolid" class="on">SOLID</button><button id="rwWire">WIRE</button></div>
      <div class="sc">
        <div class="h" style="margin:12px 0 7px">PLACEMENT</div>
        <div class="row"><span>SCALE</span><b id="vRs"></b></div>
        <input id="sRs" type="range" min="0.1" max="4" step="0.01" value="1">
        <div class="row"><span>POS X</span><b id="vRx"></b></div>
        <input id="sRx" type="range" min="-3" max="3" step="0.01" value="0">
        <div class="row"><span>POS Y</span><b id="vRy"></b></div>
        <input id="sRy" type="range" min="-3" max="3" step="0.01" value="0">
        <div class="row"><span>POS Z</span><b id="vRz"></b></div>
        <input id="sRz" type="range" min="-3" max="3" step="0.01" value="0">
        <div class="row"><span>ROT X</span><b id="vRrx"></b></div>
        <input id="sRrx" type="range" min="-180" max="180" step="1" value="0">
        <div class="row"><span>ROT Y</span><b id="vRry"></b></div>
        <input id="sRry" type="range" min="-180" max="180" step="1" value="0">
        <div class="row"><span>ROT Z</span><b id="vRrz"></b></div>
        <input id="sRrz" type="range" min="-180" max="180" step="1" value="0">
        <div class="row"><span>OFFSET ( GAP / THICKEN )</span><b id="vRo"></b></div>
        <input id="sRo" type="range" min="-0.3" max="0.4" step="0.005" value="0">
        <div class="row"><span>SDF RES</span><b id="vRres"></b></div>
        <input id="sRres" type="range" min="48" max="180" step="2" value="100">
        <div class="stack" style="margin-top:8px"><button class="full" id="refReset">RESET FIT</button></div>
      </div>
    </div>
    <div id="refInfo" style="color:var(--mute);margin-top:7px;line-height:1.5"></div>
  </div>

  <div class="sec ct t-cut">
    <div class="h">SEAMS</div>
    <div class="seg"><button id="ctPen" class="on" title="P">PEN</button><button id="ctErase" title="E">ERASE</button><button id="ctSel" title="V">SELECT</button></div>
    <div class="row" style="margin-top:9px"><span>PREFER CREASES</span><b id="vCb"></b></div>
    <input id="sCb" type="range" min="0" max="1" step="0.01" value="0.6">
    <div class="row"><span>MESH RES</span><b id="vCr"></b></div>
    <input id="sCr" type="range" min="16" max="72" step="2" value="36">
    <div id="cutSel"></div>
  </div>

  <div class="sec ct t-cut">
    <div class="h">GUIDE</div>
    <div class="seg"><button id="cvParts" class="on">PIECES</button><button id="cvCurv">CURVATURE</button><button id="cvStrain">STRAIN</button></div>
    <div id="viewNote" class="m" style="color:var(--mute);margin-top:7px;line-height:1.5"></div>
    <div class="seg" style="margin-top:9px"><button id="btnSuggest" title="One round of proposals, drawn dashed on the form">SUGGEST SEAMS</button><button id="btnAuto" title="Repeat suggest + accept until every piece is within the stretch limit">AUTO PLAN</button></div>
    <div id="propList"></div>
  </div>

  <div class="sec ct t-cut">
    <div class="h">MATERIAL</div>
    <select id="matSel">
      <option value="tarp">TARP / PLANE · 1 %</option>
      <option value="denim">DENIM · 2 %</option>
      <option value="thick" selected>WOVEN THICK · CANVAS · 3 %</option>
      <option value="thin">WOVEN THIN · COTTON · 4 %</option>
      <option value="knit">KNIT · 10 %</option>
      <option value="jersey">JERSEY · 20 %</option>
      <option value="custom">CUSTOM</option>
    </select>
    <div class="row"><span>STRETCH LIMIT</span><b id="vCl"></b></div>
    <input id="sCl" type="range" min="0.5" max="30" step="0.5" value="3">
    <div class="row"><span>SEAM LENGTH FIDELITY</span><b id="vCf"></b></div>
    <input id="sCf" type="range" min="0" max="1" step="0.05" value="0.8">
    <div class="row"><span>EASE ( − SNUG / + ROOM )</span><b id="vCe"></b></div>
    <input id="sCe" type="range" min="-30" max="20" step="1" value="0">
  </div>

  <div class="sec ct t-cut">
    <div class="h">PATTERN</div>
    <div class="row"><span>SIZE · LONGEST SIDE</span><b id="vCs"></b></div>
    <input id="sCs" type="range" min="50" max="2000" step="10" value="400">
    <div class="row"><span>SEAM ALLOWANCE</span><b id="vCa"></b></div>
    <input id="sCa" type="range" min="0" max="25" step="1" value="10">
    <div class="row"><span>NOTCH SPACING</span><b id="vCn"></b></div>
    <input id="sCn" type="range" min="0" max="200" step="5" value="50">
    <div class="row"><span>NODE SPACING ( INFLATE )</span><b id="vCk"></b></div>
    <input id="sCk" type="range" min="20" max="400" step="5" value="120">
    <div class="row" style="margin-top:4px"><span>2D PREVIEW</span></div>
    <div class="seg"><button id="cpOn" class="on">ON</button><button id="cpOff">OFF</button></div>
    <div id="cutInfo"></div>
    <div class="stack" style="margin-top:10px">
      <button class="full" id="btnSvg">EXPORT .SVG ( 1:1 MM )</button>
      <button class="full" id="btnInf">EXPORT INFLATE .JSON</button>
    </div>
    <div id="dstatus"></div>
  </div>

  <div class="sec t-form">
    <div class="h">SETUP</div>
    <div class="sc">
    <div class="row"><span>BLEND</span><b id="vBlend"></b></div>
    <input id="sBlend" type="range" min="0" max="0.8" step="0.01" value="0.2">
    <div class="row"><span>BLEND SHAPE · ROUND → ANGULAR</span><b id="vFall"></b></div>
    <input id="sFall" type="range" min="0" max="1" step="0.01" value="0.5">
    <div class="row"><span>PREVIEW RES</span><b id="vPrev"></b></div>
    <input id="sPrev" type="range" min="6" max="40" step="1" value="14">
    </div>
    <div class="row"><span>SHADING</span></div>
    <div class="seg"><button id="shSmooth" class="on">SMOOTH</button><button id="shFlat">RAW</button></div>
    <div class="sc">
    <div class="gap"></div>
    <div class="row"><span id="symLbl">SYMMETRY</span></div>
    <div class="seg"><button id="symX">X</button><button id="symY">Y</button><button id="symZ">Z</button></div>
    </div>
    <div class="gap"></div>
    <div class="row"><span>GRID</span></div>
    <div class="seg"><button id="gridOn" class="on">ON</button><button id="gridOff">OFF</button></div>
    <div class="sc">
    <div class="gap"></div>
    <div class="row"><span>OUTLINES</span></div>
    <div class="seg"><button id="outOn" class="on">ON</button><button id="outOff">OFF</button></div>
    </div>
  </div>

  <div class="sec t-look">
    <div class="h">MATERIAL</div>
    <div class="row" style="margin-bottom:9px"><span>COLOR</span><input id="mColor" type="color" value="#dcdcdd"></div>
    <div class="row"><span>SMOOTHNESS</span><b id="vSm"></b></div>
    <input id="sSm" type="range" min="0" max="1" step="0.01" value="0.38">
    <div class="row"><span>METALLIC</span><b id="vMe"></b></div>
    <input id="sMe" type="range" min="0" max="1" step="0.01" value="0">
    <div class="row"><span>TRANSLUCENCE</span><b id="vTr"></b></div>
    <input id="sTr" type="range" min="0" max="1" step="0.01" value="0">
  </div>

  <div class="sec t-file">
    <div class="h">PROJECT</div>
    <div class="seg"><button id="pSave">SAVE</button><button id="pLoad">LOAD</button></div>
    <div class="stack">
      <button class="full" id="pExp">EXPORT .JSON</button>
      <button class="full" id="pImp">IMPORT .JSON</button>
    </div>
    <input id="pFile" type="file" accept=".json,application/json" hidden>
  </div>

  <div class="sec sc t-file">
    <div class="h">RENDER</div>
    <div class="row"><span>RENDER RES</span><b id="vRend"></b></div>
    <input id="sRend" type="range" min="24" max="160" step="2" value="64">
    <div class="stack">
      <button class="full" id="btnRender">RENDER MESH</button>
      <button class="full" id="btnGlb" disabled>DOWNLOAD .GLB</button>
    </div>
    <div id="status">READY</div>
  </div>
</div>

<div class="panel sc" id="bar" hidden>
  <div id="barSel" style="display:flex;gap:5px">
    <button data-mode="move">MOVE</button>
    <button data-mode="rotate">ROTATE</button>
    <button data-mode="scale">SCALE</button>
    <button class="del" id="btnDel">DELETE</button>
  </div>
  <div id="barPull" style="display:flex;gap:5px;align-items:center" hidden>
    <span style="color:#8e8e8e;padding:0 6px">DRAG OUT FROM THE SURFACE</span><button id="btnPullCancel">CANCEL</button>
  </div>
  <div id="barDraw" style="display:flex;gap:5px" hidden>
    <button id="btnFinish">FINISH <span id="drawN" style="color:#8e8e8e"></span></button>
    <button id="btnCancel">CANCEL</button>
  </div>
</div>

<button class="ct" id="btnCuts"><span id="cutsTxt">RENDER CUTS</span><span class="dot"></span></button>
<div id="ctip" hidden></div>
<div class="panel ct" id="pat">
  <canvas id="pc"></canvas>
  <div class="ptag" id="ptag">PATTERN · MM</div>
  <div class="pbtn"><button id="pFit">FIT</button></div>
</div>

<div class="panel ct" id="cbar" hidden>
  <span id="cbarTxt" style="color:#8e8e8e;padding:0 6px"></span>
  <button id="cbFinish">FINISH</button><button id="cbClose">CLOSE LOOP</button><button id="cbCancel">CANCEL</button>
</div>

<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';

const V3 = THREE.Vector3;
const $ = id => document.getElementById(id);
const BIG = 1e4;
const TYPES = ['sphere', 'cube', 'capsule', 'spline'];
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));

/* ============================================================
   STATE
============================================================ */
const S = {
  blobs: [], sel: null, mode: 'move',
  blend: 0.2, prevRes: 14, rendRes: 64, flat: false,
  dirty: true, hqFresh: false, shift: false, drawing: null, pulling: false,
  sym: [false, false, false],   // symmetry state used as default for new blobs (= last toggled state)
  outline: true,                // subtle outline shells around every blob
  mat: { color: '#dcdcdd', smooth: 0.38, metal: 0, trans: 0 },   // material of the whole blob
  fall: 0.5,                    // blend shape: 0 = very round, 0.5 = standard, 1 = angular (chamfer)
  neg: false,                   // active layer: false = positive, true = negative (cutting) blobs
  stage: 'sculpt', rev: 0,       // stage: 'sculpt' | 'cut'; rev counts sculpt edits (invalidates a bake)
  clip: null, pasteN: 0, node: null, sels: [], tab: 'form',   // node = selected spline node / handle {kind,i}
};
let uid = 1;

function makeBlob(type, pos) {
  const b = { id: uid++, type, pos: pos.clone(), quat: new THREE.Quaternion(),
              scale: new V3(1, 1, 1), r: 0.3, len: 0.4, round: 0.35, pts: null, samples: null,
              sym: S.sym.slice(), neg: S.neg, dt: 0, db: 0, dw: 0, rad: null, srad: null, taper: 0 };
  if (type === 'sphere')  b.r = 0.4;
  if (type === 'cube')    { b.r = 0.32; b.round = 0.4; }
  if (type === 'capsule') { b.r = 0.2;  b.len = 0.4; }
  if (type === 'spline')  b.r = 0.1;
  return b;
}
// splines are cubic Bezier chains: every node has an in- and out-handle (offsets, local space)
const SEG = 8;
function autoHandles(b) {
  const n = b.pts.length; b.hin = []; b.hout = [];
  for (let i = 0; i < n; i++) {
    const p = b.pts[i], prev = b.pts[i - 1], next = b.pts[i + 1];
    let o;
    if (prev && next) o = next.clone().sub(prev).divideScalar(6);
    else if (next) o = next.clone().sub(p).divideScalar(3);
    else o = p.clone().sub(prev).divideScalar(3);
    b.hout.push(o.clone()); b.hin.push(o.clone().negate());
  }
}
function updateSpline(b) {
  const s = [], rs = [], n = b.pts.length;
  if (!b.rad || b.rad.length !== n) b.rad = b.pts.map(() => 1);          // per-node radius multipliers
  const T = b.taper || 0, tf = u => T >= 0 ? 1 - 0.94 * T * u : 1 - 0.94 * -T * (1 - u);   // taper profile along the curve
  for (let i = 0; i < n - 1; i++) {
    const P0 = b.pts[i], P3 = b.pts[i + 1];
    const P1 = P0.clone().add(b.hout[i]), P2 = P3.clone().add(b.hin[i + 1]);
    for (let j = 0; j < SEG; j++) {
      const t = j / SEG, u = 1 - t;
      s.push(new V3().addScaledVector(P0, u * u * u).addScaledVector(P1, 3 * u * u * t)
                     .addScaledVector(P2, 3 * u * t * t).addScaledVector(P3, t * t * t));
      rs.push((b.rad[i] + (b.rad[i + 1] - b.rad[i]) * t * t * (3 - 2 * t)) * tf((i + t) / (n - 1)));
    }
  }
  s.push(b.pts[n - 1].clone()); rs.push(b.rad[n - 1] * tf(1));
  b.samples = s; b.srad = rs;
}
function cloneBlob(b) {
  const n = makeBlob(b.type, b.pos);
  n.quat.copy(b.quat); n.scale.copy(b.scale); n.r = b.r; n.len = b.len; n.round = b.round;
  n.sym = b.sym.slice(); n.neg = b.neg; n.dt = b.dt; n.db = b.db; n.dw = b.dw; n.taper = b.taper;
  if (b.pts) {
    n.rad = b.rad ? b.rad.slice() : null; n.pts = b.pts.map(p => p.clone()); n.hin = b.hin.map(p => p.clone()); n.hout = b.hout.map(p => p.clone());
    updateSpline(n);
  }
  return n;
}

/* ============================================================
   RENDERER / SCENE
============================================================ */
const canvas = $('c'), view = $('view');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xececec);
const persp = new THREE.PerspectiveCamera(40, 1, 0.05, 100);
persp.position.set(2.3, 1.7, 3.3);
scene.add(persp);
const ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.01, 1000);   // used by the orthographic helper views
scene.add(ortho);
let camera = persp;                                // the active camera (persp or ortho)

const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 0.5, 0);
controls.enableDamping = true; controls.dampingFactor = 0.12;
controls.update();

// sculpt lighting: lights ride with the camera, so the form is always lit from "the viewer's" side
scene.add(new THREE.HemisphereLight(0xffffff, 0xc4c4ca, 0.45));
// soft studio environment: needed so metallic / glossy / translucent materials have something to reflect
scene.environment = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture;
scene.environmentIntensity = 0.3;
const lightRig = new THREE.Object3D(); scene.add(lightRig);   // follows whichever camera is active
function camLight(color, intensity, pos, tgt) {
  const l = new THREE.DirectionalLight(color, intensity);
  l.position.set(...pos);
  const t = new THREE.Object3D(); t.position.set(...tgt);
  lightRig.add(l); lightRig.add(t); l.target = t;
}
camLight(0xffffff, 1.6, [-2.5, 3.5, 2.0], [0, 0, -4.5]);   // key, upper left
camLight(0xe4eaff, 0.65, [3.0, 0.4, 2.0], [0, 0, -4.5]);   // soft cool fill, right
camLight(0xffffff, 0.9, [1.5, 2.5, -12], [0, 0, -4.5]);    // rim from behind

const grid = new THREE.GridHelper(8, 32, 0xd0d0d0, 0xdcdcdc);
grid.material.transparent = true; grid.material.opacity = 0.8;
scene.add(grid);

const matPrev = new THREE.MeshPhysicalMaterial({ color: 0xffffff, vertexColors: true });
const matHQ   = new THREE.MeshPhysicalMaterial({ color: 0xffffff });
function applyMaterial() {                       // one material for the whole blob (preview + render)
  const m = S.mat;
  for (const mt of [matPrev, matHQ]) {
    mt.color.set(m.color); mt.roughness = 1 - m.smooth; mt.metalness = m.metal;
    mt.transmission = m.trans; mt.thickness = 0.6; mt.ior = 1.4;
    mt.attenuationColor.set(m.color); mt.attenuationDistance = 1.5;
    mt.needsUpdate = true;
  }
  applyLayerLook();
}
const prevMesh = new THREE.Mesh(new THREE.BufferGeometry(), matPrev);
scene.add(prevMesh);
let hqMesh = null, hqGeo = null, prevOwner = null, lastTris = 0, lastMs = 0;

/* ============================================================
   SDF
============================================================ */
// compiles all blobs + their mirror copies for the active symmetry planes (world x=0 / y=0 / z=0)
function compile(blobs) {
  const out = [];
  blobs.forEach((b, i) => {
    const c0 = compileOne(b); c0.src = i; out.push(c0);
    for (let m = 1; m < 8; m++) {
      if (((m & 1) && !b.sym[0]) || ((m & 2) && !b.sym[1]) || ((m & 4) && !b.sym[2])) continue;
      out.push(mirrorC(c0, (m & 1) ? -1 : 1, (m & 2) ? -1 : 1, (m & 4) ? -1 : 1));
    }
  });
  return out;
}
function mirrorC(c, sx, sy, sz) {
  const d = Object.assign({}, c);
  if (c.t === 3) {
    const w = new Float32Array(c.wpts.length);
    for (let i = 0; i < w.length; i += 3) { w[i] = c.wpts[i] * sx; w[i + 1] = c.wpts[i + 1] * sy; w[i + 2] = c.wpts[i + 2] * sz; }
    d.wpts = w;
  } else {
    d.fx = c.fx * sx; d.fy = c.fy * sy; d.fz = c.fz * sz;          // deformers see the locally mirrored shape
    d.px = c.px * sx; d.py = c.py * sy; d.pz = c.pz * sz;          // rotation R' = M R M
    d.m1 = c.m1 * sx * sy; d.m2 = c.m2 * sx * sz; d.m3 = c.m3 * sy * sx;
    d.m5 = c.m5 * sy * sz; d.m6 = c.m6 * sz * sx; d.m7 = c.m7 * sz * sy;
  }
  [d.x0, d.x1] = sx < 0 ? [-c.x1, -c.x0] : [c.x0, c.x1];
  [d.y0, d.y1] = sy < 0 ? [-c.y1, -c.y0] : [c.y0, c.y1];
  [d.z0, d.z1] = sz < 0 ? [-c.z1, -c.z0] : [c.z0, c.z1];
  return d;
}
function compileOne(b) {
  {
    const c = { t: TYPES.indexOf(b.type), neg: !!b.neg };
    const sx = b.scale.x, sy = b.scale.y, sz = b.scale.z;
    if (c.t === 3) {
      const n = b.samples.length, w = new Float32Array(n * 3), v = new V3();
      let x0 = 1e9, y0 = 1e9, z0 = 1e9, x1 = -1e9, y1 = -1e9, z1 = -1e9;
      for (let i = 0; i < n; i++) {
        v.copy(b.samples[i]).multiply(b.scale).applyQuaternion(b.quat).add(b.pos);
        w[i * 3] = v.x; w[i * 3 + 1] = v.y; w[i * 3 + 2] = v.z;
        x0 = Math.min(x0, v.x); y0 = Math.min(y0, v.y); z0 = Math.min(z0, v.z);
        x1 = Math.max(x1, v.x); y1 = Math.max(y1, v.y); z1 = Math.max(z1, v.z);
      }
      const wr = new Float32Array(n), avg = (sx + sy + sz) / 3; let rmax = 0;
      for (let i = 0; i < n; i++) { wr[i] = b.srad[i] * b.r * avg; if (wr[i] > rmax) rmax = wr[i]; }
      const cl = new Float32Array(n);
      for (let i = 1; i < n; i++) cl[i] = cl[i - 1] + Math.hypot(w[i * 3] - w[i * 3 - 3], w[i * 3 + 1] - w[i * 3 - 2], w[i * 3 + 2] - w[i * 3 - 1]);
      c.cl = cl;                                                    // cumulative arc length (flow coordinate for ribs)
      c.wpts = w; c.wr = wr; c.rw = rmax;                           // per-sample radius (variable-width tube), max radius for bounds
      c.x0 = x0 - rmax; c.y0 = y0 - rmax; c.z0 = z0 - rmax;
      c.x1 = x1 + rmax; c.y1 = y1 + rmax; c.z1 = z1 + rmax;
    } else {
      const e = new THREE.Matrix4().makeRotationFromQuaternion(b.quat).elements;
      c.px = b.pos.x; c.py = b.pos.y; c.pz = b.pos.z;
      c.m0 = e[0]; c.m1 = e[1]; c.m2 = e[2]; c.m3 = e[4]; c.m4 = e[5]; c.m5 = e[6]; c.m6 = e[8]; c.m7 = e[9]; c.m8 = e[10];
      c.isx = 1 / sx; c.isy = 1 / sy; c.isz = 1 / sz;
      c.ms = Math.min(sx, sy, sz);
      c.r = b.r; c.len = b.len; c.rr = Math.min(b.r * b.round, b.r * 0.98);
      // deformers (local Y axis): taper / bend / twist. fx,fy,fz = local reflection signs of mirrored copies
      c.dt = b.dt || 0; c.db = Math.abs(b.db || 0) < 0.002 ? 0 : b.db; c.dw = b.dw || 0;
      c.def = (c.dt || c.db || c.dw) ? 1 : 0; c.fx = c.fy = c.fz = 1;
      c.exs = c.t === 2 ? b.len + b.r : b.r;                      // taper / twist reference half-length
      c.exb = c.t === 2 ? Math.max(b.len + b.r, 2 * b.r) : 2 * b.r;   // bend reference half-length (keeps the arc radius > shape radius)
      let R = c.t === 0 ? b.r : c.t === 1 ? b.r * 1.75 : b.len + b.r;
      R *= Math.max(sx, sy, sz) * (1 + 0.9 * Math.abs(c.dt)) * (1 + 0.5 * Math.abs(c.db));
      c.x0 = c.px - R; c.y0 = c.py - R; c.z0 = c.pz - R;
      c.x1 = c.px + R; c.y1 = c.py + R; c.z1 = c.pz + R;
    }
    return c;
  }
}

function blobDist(c, x, y, z) {
  if (c.t === 4) return refDist(c, x, y, z);
  if (c.t === 3) {
    const w = c.wpts, wr = c.wr; let best = 1e18;
    for (let i = 0, si = 0; i < w.length - 3; i += 3, si++) {
      const ax = w[i], ay = w[i + 1], az = w[i + 2];
      const bx = w[i + 3] - ax, by = w[i + 4] - ay, bz = w[i + 5] - az;
      const px = x - ax, py = y - ay, pz = z - az;
      let t = (px * bx + py * by + pz * bz) / (bx * bx + by * by + bz * bz + 1e-12);
      t = t < 0 ? 0 : t > 1 ? 1 : t;
      const dx = px - bx * t, dy = py - by * t, dz = pz - bz * t;
      const d = Math.sqrt(dx * dx + dy * dy + dz * dz) - (wr[si] + (wr[si + 1] - wr[si]) * t);   // cone between two radii
      if (d < best) best = d;
    }
    return best;
  }
  const dx = x - c.px, dy = y - c.py, dz = z - c.pz;
  let qx = (c.m0 * dx + c.m1 * dy + c.m2 * dz) * c.isx;
  let qy = (c.m3 * dx + c.m4 * dy + c.m5 * dz) * c.isy;
  let qz = (c.m6 * dx + c.m7 * dy + c.m8 * dz) * c.isz;
  let ds = 1;
  if (c.def) {                                       // domain deformation = inverse of (taper -> twist -> bend), all along local Y
    qx *= c.fx; qy *= c.fy; qz *= c.fz;
    if (c.db) {                                      // circular-arc bend (exact inverse)
      const k = c.db * 1.5 / c.exb, a = 1 - k * qx, bb = k * qy;
      qx = (1 - Math.sqrt(a * a + bb * bb)) / k; qy = Math.atan2(bb, a) / k;
    }
    if (c.dw) {
      const ang = c.dw * 3.14159 * qy / c.exs, cs = Math.cos(ang), sn = Math.sin(ang), tx = cs * qx - sn * qz;
      qz = sn * qx + cs * qz; qx = tx;
    }
    if (c.dt) {
      const sc = Math.max(0.1, 1 + 0.9 * c.dt * qy / c.exs);
      qx /= sc; qz /= sc; ds = sc;
    }
  }
  let d;
  if (c.t === 0) d = Math.sqrt(qx * qx + qy * qy + qz * qz) - c.r;
  else if (c.t === 1) {
    const hb = c.r - c.rr;
    const ax = Math.abs(qx) - hb, ay = Math.abs(qy) - hb, az = Math.abs(qz) - hb;
    const ox = ax > 0 ? ax : 0, oy = ay > 0 ? ay : 0, oz = az > 0 ? az : 0;
    d = Math.sqrt(ox * ox + oy * oy + oz * oz) + Math.min(Math.max(ax, ay, az), 0) - c.rr;
  } else {
    const t = Math.max(-c.len, Math.min(c.len, qy)), ey = qy - t;
    d = Math.sqrt(qx * qx + ey * ey + qz * qz) - c.r;
  }
  return d * c.ms * ds;
}

// smooth minimum with adjustable blend shape (S.fall, 0..1):
//   0    very round  - quadratic blend mixed with a wide exponential tail
//   0.5  standard    - classic quadratic polynomial smooth-min
//   1    angular     - quadratic mixed into a 45-degree chamfer (hard crease, flat bevel)
// Every variant is "min(a,b) minus a bulge", so it stays a plain, cheap metaball blend.
function roundW() { return Math.max(0, 1 - 2 * S.fall); }     // weight of the round end (0..1)
function smin(a, b, k) {
  if (k <= 0) return a < b ? a : b;
  const m = a < b ? a : b, d = Math.abs(a - b), t = S.fall;
  const q = d < k ? (k - d) / k : 0, quad = k * q * q * 0.25;
  let c;
  if (t <= 0.5) {
    const u = 1 - 2 * t;
    c = (1 - u) * quad;
    if (u > 0) { const ke = k * (0.36 + 0.3 * u); if (d < 4 * ke) c += u * ke * Math.log(1 + Math.exp(-d / ke)); }
  } else {
    const v = 2 * t - 1;
    c = (1 - v) * quad;
    const ch = (a + b - 0.6 * k) * 0.70710678;                  // chamfer: flat 45-degree bevel between the shapes
    if (ch < m) c += v * (m - ch);
  }
  return m - c;
}

function ownerAt(cs, x, y, z) {
  let best = 1e18, bi = 0;
  for (let i = 0; i < cs.length; i++) {
    if (cs[i].t === 4) continue;
    const d = blobDist(cs[i], x, y, z);
    if (d < best) { best = d; bi = i; }
  }
  return cs[bi].src;
}

/* ============================================================
   POLYGONIZER  (smooth-union field -> naive surface nets)
============================================================ */
const CX = [0, 1, 0, 1, 0, 1, 0, 1], CY = [0, 0, 1, 1, 0, 0, 1, 1], CZ = [0, 0, 0, 0, 1, 1, 1, 1];
const EA = [0, 2, 4, 6, 0, 1, 4, 5, 0, 1, 2, 3], EB = [1, 3, 5, 7, 2, 3, 6, 7, 4, 5, 6, 7];

function polygonize(cs, k, h0, maxPts, wantOwner) {
  let x0 = 1e9, y0 = 1e9, z0 = 1e9, x1 = -1e9, y1 = -1e9, z1 = -1e9;
  const posCs = cs.filter(c => !c.neg);
  if (!posCs.length) return null;                      // nothing solid to build (negatives only carve)
  const kr = k * (1 + 2 * roundW());                      // reach of the blend kernel
  for (const c of posCs) {                              // grid only covers the solid blobs
    x0 = Math.min(x0, c.x0); y0 = Math.min(y0, c.y0); z0 = Math.min(z0, c.z0);
    x1 = Math.max(x1, c.x1); y1 = Math.max(y1, c.y1); z1 = Math.max(z1, c.z1);
  }
  let H = h0, ox, oy, oz, nx, ny, nz;
  for (let it = 0; it < 80; it++) {
    const pad = kr + 4 * H;
    ox = Math.floor((x0 - pad) / H) * H; oy = Math.floor((y0 - pad) / H) * H; oz = Math.floor((z0 - pad) / H) * H;
    nx = Math.ceil((x1 + pad - ox) / H) + 1; ny = Math.ceil((y1 + pad - oy) / H) + 1; nz = Math.ceil((z1 + pad - oz) / H) + 1;
    if (nx * ny * nz <= maxPts) break;
    H *= 1.06;
  }
  const F = new Float32Array(nx * ny * nz).fill(BIG);
  const m = kr + 3 * H;
  const rng = (lo, hi, o, n) => [Math.max(0, Math.floor((lo - m - o) / H)), Math.min(n - 1, Math.ceil((hi + m - o) / H))];

  /* --- field fill --- */
  // solids first (smooth union), then negatives carve them out (smooth subtraction)
  for (const c of [...posCs, ...cs.filter(c => c.neg)]) {
    const neg = !!c.neg;
    const [ia, ib] = rng(c.x0, c.x1, ox, nx), [ja, jb] = rng(c.y0, c.y1, oy, ny), [ka, kb] = rng(c.z0, c.z1, oz, nz);
    if (c.t !== 3) {
      for (let kz = ka; kz <= kb; kz++) {
        const z = oz + kz * H;
        for (let jy = ja; jy <= jb; jy++) {
          const y = oy + jy * H;
          let p = ia + nx * (jy + ny * kz);
          for (let ix = ia; ix <= ib; ix++, p++) {
            const d = blobDist(c, ox + ix * H, y, z);
            F[p] = neg ? -smin(-F[p], d, k) : smin(F[p], d, k);
          }
        }
      }
    } else {
      // splines: rasterise segment by segment into a scratch volume (plain min), then smooth-merge
      const sx = ib - ia + 1, sy = jb - ja + 1, sz = kb - ka + 1;
      const sc = new Float32Array(sx * sy * sz).fill(BIG);
      const w = c.wpts, wr = c.wr, mm = c.rw + m;
      for (let s = 0; s < w.length - 3; s += 3) {
        const ax = w[s], ay = w[s + 1], az = w[s + 2];
        const bx = w[s + 3] - ax, by = w[s + 4] - ay, bz = w[s + 5] - az;
        const L2 = bx * bx + by * by + bz * bz + 1e-12, r0 = wr[s / 3], dr = wr[s / 3 + 1] - r0;
        const qa = Math.max(ia, Math.floor((Math.min(ax, ax + bx) - mm - ox) / H)), qb = Math.min(ib, Math.ceil((Math.max(ax, ax + bx) + mm - ox) / H));
        const ra = Math.max(ja, Math.floor((Math.min(ay, ay + by) - mm - oy) / H)), rb = Math.min(jb, Math.ceil((Math.max(ay, ay + by) + mm - oy) / H));
        const ta = Math.max(ka, Math.floor((Math.min(az, az + bz) - mm - oz) / H)), tb = Math.min(kb, Math.ceil((Math.max(az, az + bz) + mm - oz) / H));
        for (let kz = ta; kz <= tb; kz++) {
          const pz = oz + kz * H - az;
          for (let jy = ra; jy <= rb; jy++) {
            const py = oy + jy * H - ay;
            let q = (qa - ia) + sx * ((jy - ja) + sy * (kz - ka));
            for (let ix = qa; ix <= qb; ix++, q++) {
              const px = ox + ix * H - ax;
              let t = (px * bx + py * by + pz * bz) / L2; t = t < 0 ? 0 : t > 1 ? 1 : t;
              const dx = px - bx * t, dy = py - by * t, dz = pz - bz * t;
              const d = Math.sqrt(dx * dx + dy * dy + dz * dz) - (r0 + dr * t);
              if (d < sc[q]) sc[q] = d;
            }
          }
        }
      }
      let q = 0;
      for (let kz = ka; kz <= kb; kz++) for (let jy = ja; jy <= jb; jy++) {
        let p = ia + nx * (jy + ny * kz);
        for (let ix = ia; ix <= ib; ix++, p++, q++) {
          const v = sc[q];
          if (v < BIG * 0.5) F[p] = neg ? -smin(-F[p], v, k) : smin(F[p], v, k);
        }
      }
    }
  }

  /* --- surface nets --- */
  const cx = nx - 1, cy = ny - 1, cz = nz - 1;
  const cell = new Int32Array(cx * cy * cz).fill(-1);
  let vpos = new Float32Array(3 * 4096), vc = 0;
  let idx = new Uint32Array(3 * 8192), ic = 0;
  const fv = new Float32Array(8), sz2 = nx * ny;

  for (let kz = 0; kz < cz; kz++) for (let jy = 0; jy < cy; jy++) {
    let p = nx * (jy + ny * kz), cb = cx * (jy + cy * kz);
    for (let ix = 0; ix < cx; ix++, p++, cb++) {
      fv[0] = F[p]; fv[1] = F[p + 1]; fv[2] = F[p + nx]; fv[3] = F[p + nx + 1];
      fv[4] = F[p + sz2]; fv[5] = F[p + sz2 + 1]; fv[6] = F[p + sz2 + nx]; fv[7] = F[p + sz2 + nx + 1];
      let neg = 0;
      for (let i = 0; i < 8; i++) if (fv[i] < 0) neg++;
      if (neg === 0 || neg === 8) continue;
      let n = 0, ax = 0, ay = 0, az = 0;
      for (let e = 0; e < 12; e++) {
        const a = EA[e], b = EB[e], fa = fv[a], fb = fv[b];
        if ((fa < 0) !== (fb < 0)) {
          const t = fa / (fa - fb);
          ax += CX[a] + (CX[b] - CX[a]) * t; ay += CY[a] + (CY[b] - CY[a]) * t; az += CZ[a] + (CZ[b] - CZ[a]) * t; n++;
        }
      }
      if (vc * 3 + 3 > vpos.length) { const nv = new Float32Array(vpos.length * 2); nv.set(vpos); vpos = nv; }
      vpos[vc * 3] = ox + (ix + ax / n) * H; vpos[vc * 3 + 1] = oy + (jy + ay / n) * H; vpos[vc * 3 + 2] = oz + (kz + az / n) * H;
      cell[cb] = vc++;
    }
  }

  const quad = (c0, c1, c2, c3, flip) => {
    const a = cell[c0], b = cell[c1], c = cell[c2], d = cell[c3];
    if ((a | b | c | d) < 0) return;
    if (ic + 6 > idx.length) { const ni = new Uint32Array(idx.length * 2); ni.set(idx); idx = ni; }
    if (!flip) { idx[ic++] = a; idx[ic++] = b; idx[ic++] = c; idx[ic++] = a; idx[ic++] = c; idx[ic++] = d; }
    else       { idx[ic++] = a; idx[ic++] = c; idx[ic++] = b; idx[ic++] = a; idx[ic++] = d; idx[ic++] = c; }
  };
  const sCy = cx, sCz = cx * cy;
  for (let kz = 0; kz < cz; kz++) for (let jy = 0; jy < cy; jy++) {
    let p = nx * (jy + ny * kz), cb = cx * (jy + cy * kz);
    for (let ix = 0; ix < cx; ix++, p++, cb++) {
      const f0 = F[p], in0 = f0 < 0;
      if (jy > 0 && kz > 0 && (F[p + 1] < 0) !== in0)       quad(cb - sCy - sCz, cb - sCz, cb, cb - sCy, !in0);          // x edge (u=y,v=z)
      if (ix > 0 && kz > 0 && (F[p + nx] < 0) !== in0)      quad(cb - sCz - 1, cb - 1, cb, cb - sCz, !in0);              // y edge (u=z,v=x)
      if (ix > 0 && jy > 0 && (F[p + sz2] < 0) !== in0)     quad(cb - 1 - sCy, cb - sCy, cb, cb - 1, !in0);              // z edge (u=x,v=y)
    }
  }

  /* --- smooth normals from the field gradient (trilinear over grid-point gradients) --- */
  const pos = vpos.slice(0, vc * 3), nor = new Float32Array(vc * 3);
  const g = new Float32Array(24);
  const gAt = (i, j, k, o) => {
    i = clamp(i, 1, nx - 2); j = clamp(j, 1, ny - 2); k = clamp(k, 1, nz - 2);
    const p = i + nx * (j + ny * k);
    g[o] = F[p + 1] - F[p - 1]; g[o + 1] = F[p + nx] - F[p - nx]; g[o + 2] = F[p + sz2] - F[p - sz2];
  };
  for (let v = 0; v < vc; v++) {
    const gx = (pos[v * 3] - ox) / H, gy = (pos[v * 3 + 1] - oy) / H, gz = (pos[v * 3 + 2] - oz) / H;
    const i = Math.floor(gx), j = Math.floor(gy), k = Math.floor(gz);
    const fx = gx - i, fy = gy - j, fz = gz - k;
    for (let c = 0; c < 8; c++) gAt(i + CX[c], j + CY[c], k + CZ[c], c * 3);
    let a = 0, b = 0, d = 0;
    for (let c = 0; c < 8; c++) {
      const w = (CX[c] ? fx : 1 - fx) * (CY[c] ? fy : 1 - fy) * (CZ[c] ? fz : 1 - fz);
      a += g[c * 3] * w; b += g[c * 3 + 1] * w; d += g[c * 3 + 2] * w;
    }
    const l = Math.hypot(a, b, d) || 1;
    nor[v * 3] = a / l; nor[v * 3 + 1] = b / l; nor[v * 3 + 2] = d / l;
  }

  const geo = new THREE.BufferGeometry();
  geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
  geo.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
  geo.setIndex(new THREE.BufferAttribute(idx.slice(0, ic), 1));
  geo.computeBoundingSphere();

  let owner = null;
  if (wantOwner) {
    owner = new Int16Array(vc);
    for (let v = 0; v < vc; v++) owner[v] = ownerAt(posCs, pos[v * 3], pos[v * 3 + 1], pos[v * 3 + 2]);
  }
  return { geo, owner, H, tris: ic / 3, verts: vc };
}

/* ============================================================
   PREVIEW MESH
============================================================ */
const TB = [1, 1, 1], TS = [0.55, 0.68, 1.0];                // positive: base / selected tint (multiplies the material colour)
const TBN = [0.04, 0.04, 0.045], TSN = [0.24, 0.30, 0.50];   // negative: black / selected tint

// positives = carved result (white); negatives are drawn separately as black "tool" shapes
const matNeg = new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: 0.45, metalness: 0 });
const negMesh = new THREE.Mesh(new THREE.BufferGeometry(), matNeg);
scene.add(negMesh);
let negOwner = null;

// active layer is opaque + editable, the other one is a faint, locked ghost
function applyLayerLook() {
  const n = S.neg;
  matPrev.transparent = n; matPrev.opacity = n ? 0.16 : 1; matPrev.depthWrite = !n;
  matPrev.transmission = n ? 0 : S.mat.trans;
  matNeg.transparent = !n; matNeg.opacity = n ? 1 : 0.16; matNeg.depthWrite = n;
  matPrev.needsUpdate = matNeg.needsUpdate = true;
}
function setGeo(mesh, geo) { const old = mesh.geometry; mesh.geometry = geo; old.dispose(); }

function remeshPreview() {
  const t0 = performance.now();
  const cs = withRef(compile(S.blobs));
  const negCs = cs.filter(c => c.neg && c.t !== 4).map(c => Object.assign({}, c, { neg: false }));
  const rp = polygonize(cs, S.blend, 1 / S.prevRes, 1.2e6, true);
  const rn = negCs.length ? polygonize(negCs, S.blend, 1 / S.prevRes, 1.2e6, true) : null;
  [[rp, prevMesh, false], [rn, negMesh, true]].forEach(([r, mesh, isNeg]) => {
    if (!r) { setGeo(mesh, new THREE.BufferGeometry()); if (isNeg) negOwner = null; else prevOwner = null; return; }
    r.geo.setAttribute('color', new THREE.BufferAttribute(new Float32Array(r.verts * 3), 3));
    setGeo(mesh, r.geo);
    if (isNeg) negOwner = r.owner; else prevOwner = r.owner;
  });
  lastTris = (rp ? rp.tris : 0) + (rn ? rn.tris : 0);
  applyTint();
  lastMs = performance.now() - t0;
}
function tintMesh(mesh, owner, base, sel, si) {
  const col = mesh.geometry.attributes.color;
  if (!col || !owner) return;
  const a = col.array;
  for (let i = 0; i < owner.length; i++) {
    const t = si.has(owner[i]) ? sel : base;
    a[i * 3] = t[0]; a[i * 3 + 1] = t[1]; a[i * 3 + 2] = t[2];
  }
  col.needsUpdate = true;
}
function applyTint() {
  const si = new Set(S.sels.map(b => S.blobs.indexOf(b)));
  tintMesh(prevMesh, prevOwner, TB, TS, si);
  tintMesh(negMesh, negOwner, TBN, TSN, si);
}
function markDirty() {
  S.dirty = true; S.hqFresh = false; S.rev++;
  if (hqMesh) hqMesh.visible = false;
  prevMesh.visible = true; negMesh.visible = true;
  if (hqGeo) setStatus('OUT OF DATE — RENDER AGAIN');
}

/* ============================================================
   OUTLINES  (subtle line shells, always a bit larger than the blob)
============================================================ */
const outMats = {
  act:   new THREE.LineBasicMaterial({ color: 0x151515, transparent: true, opacity: 0.2,  depthWrite: false }),
  ghost: new THREE.LineBasicMaterial({ color: 0x151515, transparent: true, opacity: 0.06, depthWrite: false }),
  sel:   new THREE.LineBasicMaterial({ color: 0x5a78d6, transparent: true, opacity: 0.8,  depthWrite: false }),
};
const outLines = {};
for (const k in outMats) {
  outLines[k] = new THREE.LineSegments(new THREE.BufferGeometry(), outMats[k]);
  outLines[k].frustumCulled = false; outLines[k].renderOrder = 5; scene.add(outLines[k]);
}
function circ(c, U, W, rad, n, a0 = 0, a1 = Math.PI * 2) {
  const p = [];
  for (let i = 0; i <= n; i++) { const a = a0 + (a1 - a0) * i / n; p.push(c.clone().addScaledVector(U, Math.cos(a) * rad).addScaledVector(W, Math.sin(a) * rad)); }
  return p;
}
// forward deformation (straight -> taper -> twist -> bend) of a local point, same maths as blobDist uses in reverse
function deformLocal(b, v) {
  const cap = b.type === 'capsule', exs = cap ? b.len + b.r : b.r, exb = cap ? Math.max(b.len + b.r, 2 * b.r) : 2 * b.r;
  let x = v.x, y = v.y, z = v.z;
  if (b.dt) { const sc = Math.max(0.1, 1 + 0.9 * b.dt * y / exs); x *= sc; z *= sc; }
  if (b.dw) { const a = -b.dw * 3.14159 * y / exs, cs = Math.cos(a), sn = Math.sin(a), tx = cs * x - sn * z; z = sn * x + cs * z; x = tx; }
  if (Math.abs(b.db || 0) >= 0.002) {
    const k = b.db * 1.5 / exb, th = k * y, rho = 1 / k;
    const nx = rho - (rho - x) * Math.cos(th), ny = (rho - x) * Math.sin(th); x = nx; y = ny;
  }
  return new V3(x, y, z);
}
function outlineOf(b) {
  const out = [], X = new V3(1, 0, 0), Y = new V3(0, 1, 0), Z = new V3(0, 0, 1), O = new V3();
  const pushSeg = (a, c) => out.push(a.x, a.y, a.z, c.x, c.y, c.z);
  const polyW = pts => { for (let i = 1; i < pts.length; i++) pushSeg(pts[i - 1], pts[i]); };   // world points
  const defd = b.type !== 'spline' && (b.dt || b.db || b.dw);                                   // deformed primitive: outline follows the deformation
  const poly = pts => polyW(pts.map(p => toWorld(b, defd ? deformLocal(b, p) : p)));            // local points
  const lerpLine = (a, c) => { const n = defd ? 18 : 1, o = []; for (let i = 0; i <= n; i++) o.push(a.clone().lerp(c, i / n)); return o; };
  if (b.type === 'sphere') {
    const R = b.r * 1.1 + 0.015;
    poly(circ(O, X, Y, R, 48)); poly(circ(O, Y, Z, R, 48)); poly(circ(O, X, Z, R, 48));
  } else if (b.type === 'cube') {
    const h = b.r * 1.08 + 0.015, c = [];
    for (let i = 0; i < 8; i++) c.push(new V3(i & 1 ? h : -h, i & 2 ? h : -h, i & 4 ? h : -h));
    for (let i = 0; i < 8; i++) for (const bit of [1, 2, 4]) if (!(i & bit)) poly(lerpLine(c[i], c[i | bit]));
  } else if (b.type === 'capsule') {
    const R = b.r * 1.1 + 0.015, L = b.len;
    poly(circ(new V3(0, L, 0), X, Z, R, 40)); poly(circ(new V3(0, -L, 0), X, Z, R, 40));
    for (const U of [X, Z]) {
      const top = circ(new V3(0, L, 0), U, Y, R, 24, 0, Math.PI), bot = circ(new V3(0, -L, 0), U, Y, R, 24, Math.PI, Math.PI * 2);
      poly(top.concat(bot, [top[0]]));
    }
  } else {
    const P = b.samples.map(p => toWorld(b, p)), n = P.length;
    const avg = (b.scale.x + b.scale.y + b.scale.z) / 3, rwAt = i => b.r * avg * (b.srad ? b.srad[i] : 1) * 1.1 + 0.015;   // follows the variable width
    const fr = []; let nrm = null, t = new V3(0, 1, 0);
    for (let i = 0; i < n; i++) {                                // parallel-transport frames along the curve
      const tt = P[Math.min(i + 1, n - 1)].clone().sub(P[Math.max(i - 1, 0)]);
      if (tt.lengthSq() > 1e-12) t = tt.normalize();
      if (!nrm) nrm = (Math.abs(t.y) < 0.9 ? Y : X).clone();
      nrm = nrm.sub(t.clone().multiplyScalar(nrm.dot(t))).normalize();
      fr.push([nrm.clone(), new V3().crossVectors(t, nrm)]);
    }
    for (let a = 0; a < 4; a++) {                                // 4 longitudinal lines
      const ang = a * Math.PI / 2, cs = Math.cos(ang), sn = Math.sin(ang);
      polyW(P.map((p, i) => p.clone().addScaledVector(fr[i][0], cs * rwAt(i)).addScaledVector(fr[i][1], sn * rwAt(i))));
    }
    for (let i = 0; i < n; i += 4) polyW(circ(P[i], fr[i][0], fr[i][1], rwAt(i), 20));   // rings
    if ((n - 1) % 4) polyW(circ(P[n - 1], fr[n - 1][0], fr[n - 1][1], rwAt(n - 1), 20));
  }
  const base = out.slice();                                      // symmetry copies are just reflected lines
  for (let m = 1; m < 8; m++) {
    if (((m & 1) && !b.sym[0]) || ((m & 2) && !b.sym[1]) || ((m & 4) && !b.sym[2])) continue;
    const sx = (m & 1) ? -1 : 1, sy = (m & 2) ? -1 : 1, sz = (m & 4) ? -1 : 1;
    for (let i = 0; i < base.length; i += 3) out.push(base[i] * sx, base[i + 1] * sy, base[i + 2] * sz);
  }
  return out;
}
function rebuildOutlines() {
  const arr = { act: [], ghost: [], sel: [] };
  S.blobs.forEach(b => {
    const k = S.sels.includes(b) ? 'sel' : (!!b.neg === S.neg ? 'act' : 'ghost');
    arr[k] = arr[k].concat(outlineOf(b));
  });
  for (const k in outLines) {
    const g = new THREE.BufferGeometry();
    g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(arr[k]), 3));
    outLines[k].geometry.dispose(); outLines[k].geometry = g; outLines[k].visible = S.outline && S.stage !== 'cut';
  }
}

/* ============================================================
   GIZMOS
============================================================ */
const AX = [new V3(1, 0, 0), new V3(0, 1, 0), new V3(0, 0, 1)];
const COL = [0xe5484d, 0x30a46c, 0x3e63dd];
const Y_UP = new V3(0, 1, 0), Z_UP = new V3(0, 0, 1);
const gizmo = new THREE.Group(); gizmo.visible = false; scene.add(gizmo);
const hitMat = new THREE.MeshBasicMaterial({ visible: false });
const axisMats = COL.map(c => new THREE.MeshBasicMaterial({ color: c, depthTest: false, transparent: true, opacity: 0.8 }));
const centerMat = new THREE.MeshBasicMaterial({ color: 0x9a9a9a, depthTest: false, transparent: true, opacity: 0.9 });
const gm = { move: new THREE.Group(), rotate: new THREE.Group(), scale: new THREE.Group() };
for (const k in gm) gizmo.add(gm[k]);

function tag(mesh, kind, axis) { mesh.userData = { kind, axis }; mesh.renderOrder = 999; return mesh; }
for (let i = 0; i < 3; i++) {
  // move arrow
  let g = new THREE.Group(); g.quaternion.setFromUnitVectors(Y_UP, AX[i]);
  let s = tag(new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.72, 6), axisMats[i]), 'move', i); s.position.y = 0.36;
  let c = tag(new THREE.Mesh(new THREE.ConeGeometry(0.05, 0.2, 14), axisMats[i]), 'move', i); c.position.y = 0.82;
  let h = tag(new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.09, 1, 6), hitMat), 'move', i); h.position.y = 0.5;
  g.add(s, c, h); gm.move.add(g);
  // rotate ring
  g = new THREE.Group(); g.quaternion.setFromUnitVectors(Z_UP, AX[i]);
  g.add(tag(new THREE.Mesh(new THREE.TorusGeometry(0.85, 0.011, 6, 80), axisMats[i]), 'rotate', i));
  g.add(tag(new THREE.Mesh(new THREE.TorusGeometry(0.85, 0.06, 6, 40), hitMat), 'rotate', i));
  gm.rotate.add(g);
  // scale handle
  g = new THREE.Group(); g.quaternion.setFromUnitVectors(Y_UP, AX[i]);
  s = tag(new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.74, 6), axisMats[i]), 'scale', i); s.position.y = 0.37;
  c = tag(new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.1, 0.1), axisMats[i]), 'scale', i); c.position.y = 0.82;
  h = tag(new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.09, 0.7, 6), hitMat), 'scale', i); h.position.y = 0.65;
  g.add(s, c, h); gm.scale.add(g);
}
gm.scale.add(tag(new THREE.Mesh(new THREE.BoxGeometry(0.17, 0.17, 0.17), centerMat), 'scale', 'c'));

// camera-facing radius ring (visible while Shift is held)
const ringPts = []; for (let i = 0; i < 64; i++) { const a = i / 64 * Math.PI * 2; ringPts.push(new V3(Math.cos(a), Math.sin(a), 0)); }
const ring = new THREE.LineLoop(new THREE.BufferGeometry().setFromPoints(ringPts),
  new THREE.LineBasicMaterial({ color: 0x151515, transparent: true, opacity: 0.55, depthTest: false }));
ring.renderOrder = 998; ring.visible = false; scene.add(ring);

// round, outlined dots: spline control points + drawing preview
const dotTex = (() => {
  const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d');
  g.fillStyle = '#2a2a2a'; g.beginPath(); g.arc(32, 32, 30, 0, 7); g.fill();
  g.fillStyle = '#fff'; g.beginPath(); g.arc(32, 32, 22, 0, 7); g.fill();
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
})();
const dotMat = new THREE.PointsMaterial({ size: 11, sizeAttenuation: false, map: dotTex, alphaTest: 0.5, transparent: true, depthTest: false });
function makeDots(n) {
  const attr = new THREE.BufferAttribute(new Float32Array(n * 3), 3); attr.setUsage(THREE.DynamicDrawUsage);
  const geo = new THREE.BufferGeometry(); geo.setAttribute('position', attr); geo.setDrawRange(0, 0);
  const pts = new THREE.Points(geo, dotMat); pts.frustumCulled = false; pts.renderOrder = 998; pts.visible = false; scene.add(pts);
  return { pts, geo, attr };
}
const glowTex = (() => {
  const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d');
  const gr = g.createRadialGradient(32, 32, 2, 32, 32, 31);
  gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.45, 'rgba(255,255,255,0.55)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
  g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
})();
const glowDots = makeDots(1);              // hover glow on a spline node / handle
glowDots.pts.material = new THREE.PointsMaterial({ size: 30, sizeAttenuation: false, map: glowTex, color: 0x4f6df5, transparent: true, opacity: 0.7, depthTest: false });
glowDots.pts.renderOrder = 996;
const selDots = makeDots(1);               // marker for the selected node / handle
selDots.pts.material = dotMat.clone(); selDots.pts.material.size = 14; selDots.pts.material.color.set(0x4f6df5);
selDots.pts.renderOrder = 999;
let hoverNode = null;
const handleDots = makeDots(160);          // spline nodes
const MAXD = 150;
const bezDots = makeDots(320);             // bezier handles: smaller, tinted
bezDots.pts.material = dotMat.clone(); bezDots.pts.material.size = 8; bezDots.pts.material.color.set(0xa9bcff);
const bezLineAttr = new THREE.BufferAttribute(new Float32Array(640 * 3), 3); bezLineAttr.setUsage(THREE.DynamicDrawUsage);
const bezLines = new THREE.LineSegments(new THREE.BufferGeometry().setAttribute('position', bezLineAttr),
  new THREE.LineBasicMaterial({ color: 0x6b86e8, transparent: true, opacity: 0.7, depthTest: false }));
bezLines.frustumCulled = false; bezLines.renderOrder = 997; bezLines.visible = false; bezLines.geometry.setDrawRange(0, 0); scene.add(bezLines);
const draw = makeDots(MAXD + 2);
const drawLine = new THREE.Line(new THREE.BufferGeometry().setAttribute('position', draw.attr),
  new THREE.LineBasicMaterial({ color: 0x151515, transparent: true, opacity: 0.6, depthTest: false }));
drawLine.frustumCulled = false; drawLine.renderOrder = 997; drawLine.visible = false; drawLine.geometry.setDrawRange(0, 0); scene.add(drawLine);

function toWorld(b, v) { return v.clone().multiply(b.scale).applyQuaternion(b.quat).add(b.pos); }
function toLocal(b, w) { return w.clone().sub(b.pos).applyQuaternion(b.quat.clone().invert()).divide(b.scale); }
function splineCtrl(b) {
  return {
    nodes: b.pts.map(p => toWorld(b, p)),
    ins: b.pts.map((p, i) => toWorld(b, p.clone().add(b.hin[i]))),
    outs: b.pts.map((p, i) => toWorld(b, p.clone().add(b.hout[i]))),
  };
}

// distance used to size gizmos: in the orthographic view the equivalent perspective distance
function viewDist(p) {
  if (!camera.isOrthographicCamera) return camera.position.distanceTo(p);
  return (camera.top - camera.bottom) / camera.zoom / (2 * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)));
}

/* ---------- orthographic helper views (Blender-like) ---------- */
// TOP / BOTTOM / FRONT / BACK / LEFT / RIGHT look straight along an axis with an orthographic camera.
// As soon as the camera is rotated, the view falls back to the normal perspective camera.
const VIEWS = { top: [0, 1, 0], bottom: [0, -1, 0], front: [0, 0, 1], back: [0, 0, -1], right: [1, 0, 0], left: [-1, 0, 0] };
let snapQ = null, curView = null;
function useCamera(c) { camera = c; controls.object = c; }
function setView(name) {
  controls.enableDamping = false; controls.update(); controls.enableDamping = true;   // flush leftover orbit inertia so it cannot rotate the snapped view
  const dir = new V3(...VIEWS[name]), dist = viewDist(controls.target);
  if (camera !== ortho) {                           // size the ortho frustum so the target keeps its on-screen size
    const h = dist * 2 * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)), a = innerWidth / innerHeight;
    ortho.left = -h / 2 * a; ortho.right = h / 2 * a; ortho.top = h / 2; ortho.bottom = -h / 2; ortho.zoom = 1;
    ortho.updateProjectionMatrix();
  }
  const d0 = camera === ortho ? ortho.position.distanceTo(controls.target) : dist;
  ortho.position.copy(controls.target).addScaledVector(dir, d0);
  useCamera(ortho);
  controls.update();
  snapQ = ortho.quaternion.clone(); curView = name; syncViewUI();
}
function leavePerspective() {                       // ortho -> perspective, keeping the current look direction and size
  const dist = viewDist(controls.target), dir = new V3().subVectors(ortho.position, controls.target).normalize();
  persp.position.copy(controls.target).addScaledVector(dir, dist);
  useCamera(persp); controls.update();
  curView = null; snapQ = null; syncViewUI();
}
function syncViewUI() { document.querySelectorAll('[data-view]').forEach(b => b.classList.toggle('on', b.dataset.view === curView)); }

let hover = null;
function gizPos() {                                   // gizmo pivot: the blob itself, or the centre of a multi selection
  if (S.sels.length < 2) return S.sel.pos.clone();
  const c = new V3(); S.sels.forEach(b => c.add(b.pos)); return c.divideScalar(S.sels.length);
}
function updateGizmo() {
  const b = S.sel;
  const show = !!b && !S.drawing;
  gizmo.visible = show && !S.shift;
  for (const k in gm) gm[k].visible = (k === S.mode);
  if (show) {
    const gp = gizPos();
    gizmo.position.copy(gp);
    gizmo.scale.setScalar(viewDist(gp) * 0.15);
    gizmo.quaternion.copy(S.mode === 'scale' && S.sels.length < 2 ? b.quat : new THREE.Quaternion());
  }
  axisMats.forEach((m, i) => m.opacity = hover && hover.axis === i ? 1 : 0.78);
  centerMat.opacity = hover && hover.axis === 'c' ? 1 : 0.85;

  ring.visible = show && S.shift;
  if (ring.visible) {
    ring.position.copy(b.pos); ring.quaternion.copy(camera.quaternion);
    ring.scale.setScalar(Math.max(0.01, b.r * (b.scale.x + b.scale.y + b.scale.z) / 3));
  }
  // spline control points
  const showPts = show && b.type === 'spline' && S.sels.length === 1;
  handleDots.pts.visible = bezDots.pts.visible = bezLines.visible = showPts;
  if (showPts) {
    const { nodes, ins, outs } = splineCtrl(b), n = nodes.length, a = handleDots.attr.array;
    nodes.forEach((p, i) => { a[i * 3] = p.x; a[i * 3 + 1] = p.y; a[i * 3 + 2] = p.z; });
    handleDots.attr.needsUpdate = true; handleDots.geo.setDrawRange(0, n);
    const ba = bezDots.attr.array, la = bezLineAttr.array; let k = 0;
    const put = (i, h) => {
      ba[k * 3] = h.x; ba[k * 3 + 1] = h.y; ba[k * 3 + 2] = h.z;
      la[k * 6] = nodes[i].x; la[k * 6 + 1] = nodes[i].y; la[k * 6 + 2] = nodes[i].z;
      la[k * 6 + 3] = h.x; la[k * 6 + 4] = h.y; la[k * 6 + 5] = h.z; k++;
    };
    for (let i = 0; i < n; i++) { if (i > 0) put(i, ins[i]); if (i < n - 1) put(i, outs[i]); }
    bezDots.attr.needsUpdate = true; bezLineAttr.needsUpdate = true;
    bezDots.geo.setDrawRange(0, k); bezLines.geometry.setDrawRange(0, k * 2);
    // hover glow + selected-node marker
    const at = h => h && (h.kind === 'node' ? nodes[h.i] : h.kind === 'hin' ? ins[h.i] : outs[h.i]);
    const hp = at(hoverNode), sp = at(S.node);
    glowDots.pts.visible = !!hp; selDots.pts.visible = !!sp;
    if (hp) { glowDots.attr.array.set([hp.x, hp.y, hp.z]); glowDots.attr.needsUpdate = true; glowDots.geo.setDrawRange(0, 1); }
    if (sp) { selDots.attr.array.set([sp.x, sp.y, sp.z]); selDots.attr.needsUpdate = true; selDots.geo.setDrawRange(0, 1); }
  } else { glowDots.pts.visible = false; selDots.pts.visible = false; }
}

/* ============================================================
   INTERACTION
============================================================ */
const raycaster = new THREE.Raycaster();
const ndcv = new THREE.Vector2();
function ndc(e) {
  const r = canvas.getBoundingClientRect();
  return ndcv.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
}
function setRay(e) { raycaster.setFromCamera(ndc(e), camera); return raycaster.ray; }

function axisParam(ray, O, D) {
  const w0 = O.clone().sub(ray.origin);
  const b = D.dot(ray.direction), d = D.dot(w0), e = ray.direction.dot(w0);
  const den = 1 - b * b;
  return den < 1e-6 ? 0 : (b * e - d) / den;
}

function hitGizmo(e) {
  if (!S.sel || !gizmo.visible) return null;
  setRay(e);
  const hits = raycaster.intersectObjects(gm[S.mode].children, true).filter(h => h.object.userData.kind);
  if (!hits.length) return null;
  const c = hits.find(h => h.object.userData.axis === 'c');       // the centre cube (uniform scale) wins over the axis handles
  return (c || hits[0]).object.userData;
}
function hitSplineHandle(e) {
  const b = S.sel;
  if (!b || b.type !== 'spline' || S.drawing || S.sels.length > 1) return null;
  const r = canvas.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
  const { nodes, ins, outs } = splineCtrl(b), n = nodes.length;
  let best = null, bd = 150;
  const test = (p, kind, i, bias) => {
    const q = p.clone().project(camera);
    const d = ((q.x * .5 + .5) * r.width - mx) ** 2 + ((-q.y * .5 + .5) * r.height - my) ** 2 + bias;
    if (d < bd) { bd = d; best = { kind, i }; }
  };
  for (let i = 0; i < n; i++) {
    test(nodes[i], 'node', i, 0);
    if (i > 0) test(ins[i], 'hin', i, 20);
    if (i < n - 1) test(outs[i], 'hout', i, 20);
  }
  return best;
}
function deleteNode(b, i) {
  if (b.pts.length <= 2) return;
  b.pts.splice(i, 1); b.hin.splice(i, 1); b.hout.splice(i, 1); b.rad.splice(i, 1);
  updateSpline(b); markDirty();
}
function insertNodeAt(e) {                                   // double-click on the curve: split the bezier segment
  const b = S.sel;
  if (!b || b.type !== 'spline' || S.sels.length > 1 || b.pts.length >= 150 || hitSplineHandle(e)) return;
  const r = canvas.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
  let best = -1, bd = 225;
  b.samples.forEach((s, i) => {
    const q = toWorld(b, s).project(camera);
    const d = ((q.x * .5 + .5) * r.width - mx) ** 2 + ((-q.y * .5 + .5) * r.height - my) ** 2;
    if (d < bd) { bd = d; best = i; }
  });
  if (best < 0) return;
  const nseg = b.pts.length - 1, seg = Math.min(nseg - 1, Math.floor(best / SEG));
  const t = clamp((best - seg * SEG) / SEG, 0.15, 0.85);
  const P0 = b.pts[seg], P3 = b.pts[seg + 1], P1 = P0.clone().add(b.hout[seg]), P2 = P3.clone().add(b.hin[seg + 1]);
  const lp = (a, c) => a.clone().lerp(c, t);
  const Q0 = lp(P0, P1), Q1 = lp(P1, P2), Q2 = lp(P2, P3), R0 = lp(Q0, Q1), R1 = lp(Q1, Q2), Sp = lp(R0, R1);
  b.hout[seg] = Q0.clone().sub(P0); b.hin[seg + 1] = Q2.clone().sub(P3);
  b.pts.splice(seg + 1, 0, Sp); b.hin.splice(seg + 1, 0, R0.clone().sub(Sp)); b.hout.splice(seg + 1, 0, R1.clone().sub(Sp));
  b.rad.splice(seg + 1, 0, b.rad[seg] + (b.rad[seg + 1] - b.rad[seg]) * t);
  updateSpline(b); markDirty();
}
function pasteBlob() {
  S.pasteN++;
  const off = new V3().setFromMatrixColumn(camera.matrixWorld, 0).multiplyScalar(0.25 * S.pasteN);
  const nb = S.clip.map(c => { const b = cloneBlob(c); b.neg = S.neg; b.pos.add(off); return b; });   // pasting assigns the blobs to the active layer
  nb.forEach(b => S.blobs.push(b));
  S.sels = nb; S.sel = nb[nb.length - 1]; selChanged(); markDirty();
}
function pickBlob(e) {
  const mesh = layerMesh();                       // only the active layer can be picked
  if (!mesh.geometry.attributes.position) return null;
  setRay(e);
  const h = raycaster.intersectObject(mesh, false)[0];
  if (!h) return null;
  const cs = compile(S.blobs).filter(c => c.neg === S.neg);
  return cs.length ? S.blobs[ownerAt(cs, h.point.x, h.point.y, h.point.z)] : null;
}
function layerMesh() { return S.neg ? negMesh : prevMesh; }

let drag = null, downPos = null;

view.addEventListener('pointerdown', e => {
  if (e.button !== 0) return;
  if (S.stage === 'cut') { if (cutDown(e)) e.stopPropagation(); return; }
  if (S.drawing) { downPos = { x: e.clientX, y: e.clientY }; return; }   // drawing: points are placed on click only; drag orbits
  if (S.pulling) {                                                          // PULL: start on the surface, empty space still orbits
    const d = pullStart(e);
    if (d) { drag = d; e.stopPropagation(); }
    return;
  }
  const b = S.sel;
  if (b) {
    if (e.shiftKey) {                                         // SHIFT + drag = radius (on a spline node: that node's radius)
      const hn = b.type === 'spline' ? hitSplineHandle(e) : null;
      if (hn && hn.kind === 'node') {
        S.node = { kind: 'node', i: hn.i }; syncSelUI();
        drag = { kind: 'noderad', b, i: hn.i, r0: b.rad[hn.i], y0: e.clientY, cx: e.clientX, cy: e.clientY };
        e.stopPropagation(); return;
      }
      drag = { kind: 'radius', b, r0: b.r, y0: e.clientY, cx: e.clientX, cy: e.clientY };
      e.stopPropagation(); return;
    }
    const hp = hitSplineHandle(e);
    if (hp) {
      if (hp.kind === 'node' && e.altKey) { S.node = null; deleteNode(b, hp.i); e.stopPropagation(); return; }   // ALT + click node = delete
      S.node = { kind: hp.kind, i: hp.i }; hoverNode = S.node; syncSelUI(); updateGizmo();
      drag = { kind: hp.kind, b, i: hp.i }; e.stopPropagation(); return;
    }
    const hg = hitGizmo(e);
    if (hg) {
      const multi = S.sels.length > 1, ray = setRay(e);
      const d = { kind: hg.kind, axis: hg.axis, b, pos0: gizPos(), quat0: multi ? new THREE.Quaternion() : b.quat.clone(), scale0: b.scale.clone(), y0: e.clientY,
                  grp: multi ? S.sels.map(x => ({ b: x, pos0: x.pos.clone(), quat0: x.quat.clone(), scale0: x.scale.clone() })) : null };
      if (hg.kind === 'move') { d.D = AX[hg.axis]; d.t0 = axisParam(ray, d.pos0, d.D); }
      if (hg.kind === 'rotate') {
        const a = hg.axis, u = AX[(a + 1) % 3], v = AX[(a + 2) % 3];
        d.A = AX[a]; d.u = u; d.v = v;
        d.plane = new THREE.Plane().setFromNormalAndCoplanarPoint(d.A, d.pos0);
        const p = ray.intersectPlane(d.plane, new V3());
        if (!p) return;
        p.sub(d.pos0); d.a0 = Math.atan2(p.dot(v), p.dot(u));
      }
      if (hg.kind === 'scale' && hg.axis !== 'c') {
        d.D = AX[hg.axis].clone().applyQuaternion(d.quat0);
        const gs = viewDist(d.pos0) * 0.15;
        d.t0 = axisParam(ray, d.pos0, d.D);
        if (Math.abs(d.t0) < 0.25 * gs) d.t0 = 0.25 * gs * (d.t0 < 0 ? -1 : 1);
      }
      drag = d; e.stopPropagation(); return;
    }
  }
  downPos = { x: e.clientX, y: e.clientY };
}, true);

function groupDrag(d, ray, e) {                       // move / rotate / scale every selected blob around the shared pivot
  const pv = d.pos0;
  if (d.kind === 'move') {
    const dl = d.D.clone().multiplyScalar(axisParam(ray, pv, d.D) - d.t0);
    d.grp.forEach(g => g.b.pos.copy(g.pos0).add(dl));
  } else if (d.kind === 'rotate') {
    const p = ray.intersectPlane(d.plane, new V3()); if (!p) return;
    p.sub(pv);
    const Q = new THREE.Quaternion().setFromAxisAngle(d.A, Math.atan2(p.dot(d.v), p.dot(d.u)) - d.a0);
    d.grp.forEach(g => { g.b.pos.copy(g.pos0).sub(pv).applyQuaternion(Q).add(pv); g.b.quat.copy(Q).multiply(g.quat0); });
  } else if (d.axis === 'c') {
    const mn = Math.min(d.scale0.x, d.scale0.y, d.scale0.z), mx = Math.max(d.scale0.x, d.scale0.y, d.scale0.z);
    const f = clamp(Math.exp((d.y0 - e.clientY) * 0.008), 0.05 / mn, 20 / mx);
    d.grp.forEach(g => { g.b.pos.copy(g.pos0).sub(pv).multiplyScalar(f).add(pv); g.b.scale.copy(g.scale0).multiplyScalar(f).clampScalar(0.05, 20); });
  } else {
    const f = clamp(axisParam(ray, pv, d.D) / d.t0, 0.05, 20), a = d.axis;
    d.grp.forEach(g => {
      const rel = g.pos0.clone().sub(pv); rel.setComponent(a, rel.getComponent(a) * f); g.b.pos.copy(pv).add(rel);
      for (let i = 0; i < 3; i++) {                     // blob axes follow the world stretch in proportion to how well they line up with it
        const w = Math.abs(AX[i].clone().applyQuaternion(g.quat0).getComponent(a));
        g.b.scale.setComponent(i, clamp(g.scale0.getComponent(i) * Math.pow(f, w), 0.05, 20));
      }
    });
  }
}
window.addEventListener('pointermove', e => {
  if (S.stage === 'cut') { cutMove(e); return; }
  if (S.drawing) { drawMove(e); return; }
  if (drag && (drag.kind === 'node' || drag.kind === 'hin' || drag.kind === 'hout')) hoverNode = { kind: drag.kind, i: drag.i };
  if (!drag) {
    // hover feedback
    if (e.target === canvas && S.sel && !S.shift) {
      const hg = hitGizmo(e), hp = hitSplineHandle(e);
      hover = hg; canvas.style.cursor = (hg || hp) ? 'pointer' : '';
      const nh = hp ? { kind: hp.kind, i: hp.i } : null;
      if ((nh && nh.kind + nh.i) !== (hoverNode && hoverNode.kind + hoverNode.i)) { hoverNode = nh; updateGizmo(); }
    } else { hover = null; canvas.style.cursor = ''; if (hoverNode) { hoverNode = null; updateGizmo(); } }
    return;
  }
  if (drag.kind === 'pull') { pullMove(drag, e); markDirty(); return; }
  const d = drag, b = d.b, ray = setRay(e);
  if (d.grp && (d.kind === 'move' || d.kind === 'rotate' || d.kind === 'scale')) { groupDrag(d, ray, e); syncSelUI(); markDirty(); return; }
  if (d.kind === 'noderad') {
    b.rad[d.i] = clamp(d.r0 * Math.exp((d.y0 - e.clientY) * 0.008), 0.05, 4); updateSpline(b);
  } else if (d.kind === 'radius') {
    b.r = clamp(d.r0 * Math.exp((d.y0 - e.clientY) * 0.008), 0.02, 3);
  } else if (d.kind === 'node' || d.kind === 'hin' || d.kind === 'hout') {
    const c = splineCtrl(b), i = d.i;
    const cur = d.kind === 'node' ? c.nodes[i] : d.kind === 'hin' ? c.ins[i] : c.outs[i];
    const p = ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint(camera.getWorldDirection(new V3()), cur), new V3());
    if (p) {
      const l = toLocal(b, p);
      if (d.kind === 'node') b.pts[i].copy(l);
      else {
        const isIn = d.kind === 'hin', mine = isIn ? b.hin : b.hout, other = isIn ? b.hout : b.hin;
        mine[i].copy(l).sub(b.pts[i]);
        const hasOther = isIn ? i < b.pts.length - 1 : i > 0;
        if (hasOther && !e.altKey) {                         // smooth node: opposite handle mirrors direction (ALT = break)
          const len = other[i].length() || mine[i].length();
          other[i].copy(mine[i]).normalize().multiplyScalar(-len);
        }
      }
      updateSpline(b);
    }
  } else if (d.kind === 'move') {
    const t = axisParam(ray, d.pos0, d.D);
    b.pos.copy(d.pos0).addScaledVector(d.D, t - d.t0);
  } else if (d.kind === 'rotate') {
    const p = ray.intersectPlane(d.plane, new V3());
    if (!p) return;
    p.sub(d.pos0);
    const ang = Math.atan2(p.dot(d.v), p.dot(d.u)) - d.a0;
    b.quat.copy(new THREE.Quaternion().setFromAxisAngle(d.A, ang)).multiply(d.quat0);
  } else if (d.kind === 'scale') {
    if (d.axis === 'c') {
      const mn = Math.min(d.scale0.x, d.scale0.y, d.scale0.z), mx = Math.max(d.scale0.x, d.scale0.y, d.scale0.z);
      const f = clamp(Math.exp((d.y0 - e.clientY) * 0.008), 0.05 / mn, 20 / mx);   // uniform: proportions are always kept
      b.scale.copy(d.scale0).multiplyScalar(f);
    } else {
      const f = clamp(axisParam(ray, d.pos0, d.D) / d.t0, 0.05, 20);
      b.scale.copy(d.scale0); b.scale.setComponent(d.axis, d.scale0.getComponent(d.axis) * f);
    }
    if (d.axis !== 'c') b.scale.clampScalar(0.05, 20);
  }
  syncSelUI(); markDirty();
});

window.addEventListener('pointerup', e => {
  if (S.stage === 'cut') { cutUp(e); return; }
  if (S.drawing) {
    if (downPos && e.target === canvas && e.button === 0) {
      const moved = Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y);
      if (moved < 5) drawDown(e);
    }
    downPos = null; return;
  }
  if (drag && drag.kind === 'pull') {
    const d = drag; drag = null; downPos = null;
    if (d.b) {
      if (d.len < 0.06) S.blobs.splice(S.blobs.indexOf(d.b), 1);
      else { endPull(); S.mode = 'move'; select(d.b); }
      markDirty();
    }
    return;
  }
  if (drag) {
    const d = drag; drag = null; downPos = null;
    if ((d.kind === 'radius' || d.kind === 'noderad') && e.target === canvas && Math.hypot(e.clientX - d.cx, e.clientY - d.cy) < 4) toggleSel(pickBlob(e));   // SHIFT + click = add / remove
    return;
  }
  if (downPos) {
    const moved = Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y);
    downPos = null;
    if (moved < 5 && e.target === canvas) { const pb = pickBlob(e); if (e.shiftKey || e.ctrlKey || e.metaKey) toggleSel(pb); else select(pb); }
  }
});

canvas.addEventListener('wheel', e => {                       // SHIFT + wheel = radius
  if (!e.shiftKey || !S.sel || S.drawing || S.pulling) return;
  e.preventDefault(); e.stopImmediatePropagation();
  const d = e.deltaY || e.deltaX;
  const b = S.sel, f = d < 0 ? 1.06 : 0.94;
  if (b.type === 'spline' && S.node && S.node.kind === 'node' && b.rad[S.node.i] !== undefined) { b.rad[S.node.i] = clamp(b.rad[S.node.i] * f, 0.05, 4); updateSpline(b); }
  else b.r = clamp(b.r * f, 0.02, 3);
  syncSelUI(); markDirty();
}, { passive: false, capture: true });
canvas.addEventListener('contextmenu', e => e.preventDefault());

window.addEventListener('keydown', e => {
  if (e.key === 'Shift') { S.shift = true; controls.enableZoom = false; updateHint(); }
  if (e.target.tagName === 'INPUT' && e.target.type === 'text') return;
  const np = { Numpad7: ['top', 'bottom'], Numpad1: ['front', 'back'], Numpad3: ['right', 'left'] }[e.code];   // Blender numpad; Ctrl = opposite side
  if (np) { e.preventDefault(); setView(np[e.ctrlKey ? 1 : 0]); return; }
  if (S.stage === 'cut') { cutKey(e); return; }
  if (S.pulling && e.key === 'Escape') {
    if (drag && drag.kind === 'pull') { if (drag.b) S.blobs.splice(S.blobs.indexOf(drag.b), 1); drag = null; markDirty(); }
    endPull(); return;
  }
  if (S.drawing) {
    if (e.key === 'Enter') { e.preventDefault(); finishDraw(); }
    if (e.key === 'Escape') cancelDraw();
    return;
  }
  if ((e.ctrlKey || e.metaKey) && !e.shiftKey) {                // copy / paste
    const k = e.key.toLowerCase();
    if (k === 's') { e.preventDefault(); saveLocal(); return; }
    if (k === 'a') { e.preventDefault(); const all = S.blobs.filter(b => !!b.neg === S.neg); S.sels = all; S.sel = all[all.length - 1] || null; selChanged(); return; }
    if (k === 'c' && S.sel) { S.clip = S.sels.map(cloneBlob); S.pasteN = 0; e.preventDefault(); return; }
    if (k === 'v' && S.clip) { e.preventDefault(); pasteBlob(); return; }
  }
  if ((e.key === 'Delete' || e.key === 'Backspace') && S.sel) { e.preventDefault(); deleteSel(); }
  else if (e.key === 'Escape') select(null);
  else if (S.sel && !e.ctrlKey && !e.metaKey) {
    const k = e.key.toLowerCase();
    if (k === 'g' || k === 'w') setMode('move');
    if (k === 'r') setMode('rotate');
    if (k === 's') setMode('scale');
  }
});
window.addEventListener('keyup', e => { if (e.key === 'Shift') { S.shift = false; controls.enableZoom = true; updateHint(); } });
window.addEventListener('blur', () => { S.shift = false; controls.enableZoom = true; updateHint(); });

/* ---------- selection / modes / delete ---------- */
function selChanged() { hover = null; S.node = null; hoverNode = null; syncSelUI(); updateBar(); applyTint(); updateHint(); rebuildOutlines(); }
function select(b) { S.sel = b; S.sels = b ? [b] : []; selChanged(); }
function toggleSel(b) {                                // CTRL / SHIFT + click: add or remove a blob of the active layer
  if (!b) return;
  const i = S.sels.indexOf(b);
  if (i >= 0) S.sels.splice(i, 1); else S.sels.push(b);
  S.sel = S.sels[S.sels.length - 1] || null; selChanged();
}
function setMode(m) { S.mode = m; updateBar(); }
function deleteSel() {
  if (!S.sel) return;
  S.sels.forEach(b => { const i = S.blobs.indexOf(b); if (i >= 0) S.blobs.splice(i, 1); });
  select(null); markDirty();
}
function addBlob(type) {
  if (type === 'pull') { startPull(); return; }
  if (type === 'spline') { startDraw(); return; }
  const p = controls.target.clone().add(new V3((Math.random() - .5) * .7, (Math.random() - .3) * .5, (Math.random() - .5) * .7));
  const b = makeBlob(type, p);
  S.blobs.push(b); S.mode = 'move'; select(b); markDirty();
}

/* ---------- PULL tool: drag a tapered horn out of the surface (a normal, editable spline blob) ---------- */
function startPull() { select(null); if (S.drawing) endDrawMode(); S.pulling = true; canvas.style.cursor = 'crosshair'; updateBar(); }
function endPull() { S.pulling = false; canvas.style.cursor = ''; updateBar(); }
function pullStart(e) {
  const mesh = layerMesh();
  if (!mesh.geometry.attributes.position) return null;
  setRay(e);
  const h = raycaster.intersectObject(mesh, false)[0];
  if (!h) return null;
  const n = h.face.normal.clone().normalize();
  return { kind: 'pull', b: null, n, base: h.point.clone().addScaledVector(n, -0.05), len: 0,
           plane: new THREE.Plane().setFromNormalAndCoplanarPoint(camera.getWorldDirection(new V3()), h.point) };
}
function pullMove(d, e) {
  const p = setRay(e).intersectPlane(d.plane, new V3());
  if (!p) return;
  const v = p.sub(d.base), len = v.length(); d.len = len;
  if (!d.b) {
    if (len < 0.04) return;
    d.b = makeBlob('spline', d.base); d.b.taper = 0.85; S.blobs.push(d.b);
  }
  const b = d.b;
  b.r = clamp(0.2 * len, 0.04, 0.35);
  b.pts = [new V3(), v.clone().multiplyScalar(0.5).addScaledVector(d.n, 0.12 * len), v.clone()];
  b.rad = null; autoHandles(b); updateSpline(b);
}

/* ---------- spline drawing ---------- */
function drawPointFrom(e) {
  setRay(e);
  if (layerMesh().geometry.attributes.position) {
    const h = raycaster.intersectObject(layerMesh(), false)[0];
    if (h) return h.point.clone();
  }
  const n = camera.getWorldDirection(new V3());
  return raycaster.ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint(n, controls.target), new V3());
}
function screenOf(p, e) {
  const r = canvas.getBoundingClientRect(), q = p.clone().project(camera);
  return [(q.x * .5 + .5) * r.width + r.left, (-q.y * .5 + .5) * r.height + r.top];
}
function startDraw() {
  select(null);
  S.drawing = { pts: [], hover: null };
  canvas.style.cursor = 'crosshair';
  updateBar(); updateHint(); refreshDraw();
}
function endDrawMode() {
  S.drawing = null;
  canvas.style.cursor = '';
  draw.pts.visible = false; drawLine.visible = false;
  updateBar(); updateHint();
}
function cancelDraw() { endDrawMode(); }
function finishDraw() {
  const d = S.drawing; if (!d) return;
  if (d.pts.length < 2) { endDrawMode(); return; }
  const c = new V3(); d.pts.forEach(p => c.add(p)); c.divideScalar(d.pts.length);
  const b = makeBlob('spline', c);
  b.pts = d.pts.map(p => p.clone().sub(c)); autoHandles(b); b.rad = null; updateSpline(b);
  S.blobs.push(b); endDrawMode();
  S.mode = 'move'; select(b); markDirty();
}
function tooClose(e, p, px) {
  const [sx, sy] = screenOf(p, e);
  return Math.hypot(sx - e.clientX, sy - e.clientY) < px;
}
function drawDown(e) {
  const d = S.drawing, p = drawPointFrom(e);
  if (!p || d.pts.length >= MAXD) return;
  const last = d.pts[d.pts.length - 1];
  if (!last || !tooClose(e, last, 8)) d.pts.push(p);      // ignore the 2nd click of a double-click
  refreshDraw();
}
function drawMove(e) {
  const d = S.drawing; if (!d) return;
  d.hover = e.target === canvas ? drawPointFrom(e) : null;   // preview only, never adds points
  refreshDraw();
}
view.addEventListener('dblclick', e => { if (S.stage === 'cut') { cutDbl(e); return; } if (S.drawing) finishDraw(); else insertNodeAt(e); });
function refreshDraw() {
  const d = S.drawing; if (!d) return;
  const a = draw.attr.array, all = d.hover ? [...d.pts, d.hover] : d.pts;
  all.forEach((p, i) => { a[i * 3] = p.x; a[i * 3 + 1] = p.y; a[i * 3 + 2] = p.z; });
  draw.attr.needsUpdate = true;
  draw.geo.setDrawRange(0, d.pts.length);
  drawLine.geometry.setDrawRange(0, all.length);
  draw.pts.visible = d.pts.length > 0; drawLine.visible = all.length > 1;
  $('drawN').textContent = d.pts.length ? `· ${d.pts.length} PTS` : '';
}

/* ============================================================
   UI
============================================================ */
function setStatus(t) { $('status').textContent = t; $('dstatus').textContent = t; }
function updateBar() {
  const on = !!S.sel || !!S.drawing || !!S.pulling;
  $('bar').hidden = !on;
  $('barSel').hidden = !!S.drawing || !!S.pulling; $('barDraw').hidden = !S.drawing; $('barPull').hidden = !S.pulling;
  document.querySelectorAll('[data-mode]').forEach(b => b.classList.toggle('on', b.dataset.mode === S.mode));
}
function updateHint() {}
function syncSelUI() {
  const b = S.sel;
  syncSym();
  $('selSec').hidden = !b;
  if (!b) return;
  $('selTitle').textContent = 'SELECTED · ' + b.type.toUpperCase() + (S.sels.length > 1 ? ` · +${S.sels.length - 1} MORE` : '');
  $('sR').value = b.r; $('vR').textContent = b.r.toFixed(2);
  $('rowRound').hidden = b.type !== 'cube';
  $('rowLen').hidden = b.type !== 'capsule';
  $('rowSpl').hidden = b.type !== 'spline';
  const isSpl = b.type === 'spline';
  $('rowDef').hidden = isSpl; $('rowSplT').hidden = !isSpl;
  $('rowNode').hidden = !(isSpl && S.node && S.node.kind === 'node' && b.rad && b.rad[S.node.i] !== undefined);
  $('sDt').value = b.dt || 0; $('vDt').textContent = (b.dt || 0).toFixed(2);
  $('sDb').value = b.db || 0; $('vDb').textContent = (b.db || 0).toFixed(2);
  $('sDw').value = b.dw || 0; $('vDw').textContent = (b.dw || 0).toFixed(2);
  $('sSt').value = b.taper || 0; $('vSt').textContent = (b.taper || 0).toFixed(2);
  if (!$('rowNode').hidden) { const v = b.rad[S.node.i]; $('sNr').value = v; $('vNr').textContent = v.toFixed(2); }
  $('sRound').value = b.round; $('vRound').textContent = b.round.toFixed(2);
  $('sLen').value = b.len; $('vLen').textContent = b.len.toFixed(2);
}
function bind(id, vid, fmt, cb) {
  const el = $(id), v = $(vid);
  const upd = () => v.textContent = fmt(+el.value);
  el.addEventListener('input', () => { upd(); cb(+el.value); });
  upd();
}
bind('sFall', 'vFall', v => v.toFixed(2), v => { S.fall = v; markDirty(); });
bind('sDt', 'vDt', v => v.toFixed(2), v => { if (S.sel) { S.sel.dt = v; markDirty(); } });
bind('sDb', 'vDb', v => v.toFixed(2), v => { if (S.sel) { S.sel.db = v; markDirty(); } });
bind('sDw', 'vDw', v => v.toFixed(2), v => { if (S.sel) { S.sel.dw = v; markDirty(); } });
bind('sSt', 'vSt', v => v.toFixed(2), v => { const b = S.sel; if (b && b.type === 'spline') { b.taper = v; updateSpline(b); markDirty(); } });
bind('sNr', 'vNr', v => v.toFixed(2), v => { const b = S.sel; if (b && b.type === 'spline' && S.node && S.node.kind === 'node') { b.rad[S.node.i] = v; updateSpline(b); markDirty(); } });
bind('sBlend', 'vBlend', v => v.toFixed(2), v => { S.blend = v; markDirty(); });
bind('sPrev', 'vPrev', v => v + ' / UNIT', v => { S.prevRes = v; markDirty(); });
bind('sRend', 'vRend', v => v + ' / UNIT', v => { S.rendRes = v; });
bind('sR', 'vR', v => v.toFixed(2), v => { if (S.sel) { S.sel.r = v; markDirty(); } });
bind('sRound', 'vRound', v => v.toFixed(2), v => { if (S.sel) { S.sel.round = v; markDirty(); } });
bind('sLen', 'vLen', v => v.toFixed(2), v => { if (S.sel) { S.sel.len = v; markDirty(); } });

document.querySelectorAll('[data-add]').forEach(b => b.addEventListener('click', () => addBlob(b.dataset.add)));
document.querySelectorAll('[data-mode]').forEach(b => b.addEventListener('click', () => setMode(b.dataset.mode)));
$('btnDel').addEventListener('click', deleteSel);
// symmetry is stored per blob; the last toggled state is also the default for new blobs
['symX', 'symY', 'symZ'].forEach((id, i) => $(id).addEventListener('click', () => {
  const v = !(S.sel ? S.sel.sym[i] : S.sym[i]);
  S.sym[i] = v; S.sels.forEach(b => b.sym[i] = v);
  syncSym(); markDirty();
}));
function syncSym() {
  const s = S.sel ? S.sel.sym : S.sym;
  ['symX', 'symY', 'symZ'].forEach((id, i) => $(id).classList.toggle('on', !!s[i]));
  $('symLbl').textContent = S.sel ? 'SYMMETRY · SELECTED' : 'SYMMETRY · NEW BLOBS';
}
// positive / negative layer switch: the other layer turns into a faint, locked ghost
function setNegMode(v) {
  S.neg = v;
  $('modePos').classList.toggle('on', !v); $('modeNeg').classList.toggle('on', v);
  if (S.sels.some(b => !!b.neg !== v)) select(null);
  applyLayerLook(); applyTint(); updateHint(); rebuildOutlines();
}
$('modePos').addEventListener('click', () => setNegMode(false));
$('modeNeg').addEventListener('click', () => setNegMode(true));
$('btnAuto').addEventListener('click', () => { if (S.sel && S.sel.type === 'spline') { autoHandles(S.sel); updateSpline(S.sel); markDirty(); } });
document.querySelectorAll('[data-view]').forEach(b => b.addEventListener('click', () => setView(b.dataset.view)));
$('btnPullCancel').addEventListener('click', endPull);
$('btnFinish').addEventListener('click', finishDraw);
$('btnCancel').addEventListener('click', cancelDraw);
document.querySelectorAll('button').forEach(b => b.addEventListener('click', () => b.blur()));

function setShading(flat) {
  S.flat = flat;
  matPrev.flatShading = matHQ.flatShading = matNeg.flatShading = flat;
  matPrev.needsUpdate = matHQ.needsUpdate = matNeg.needsUpdate = true;
  $('shSmooth').classList.toggle('on', !flat); $('shFlat').classList.toggle('on', flat);
}
$('shSmooth').addEventListener('click', () => setShading(false));
$('shFlat').addEventListener('click', () => setShading(true));
function setGrid(on) { grid.visible = on; $('gridOn').classList.toggle('on', on); $('gridOff').classList.toggle('on', !on); }
function setOutline(on) {
  S.outline = on; $('outOn').classList.toggle('on', on); $('outOff').classList.toggle('on', !on);
  for (const k in outLines) outLines[k].visible = on && S.stage !== 'cut';
}
$('outOn').addEventListener('click', () => setOutline(true));
$('outOff').addEventListener('click', () => setOutline(false));
bind('sSm', 'vSm', v => v.toFixed(2), v => { S.mat.smooth = v; applyMaterial(); });
bind('sMe', 'vMe', v => v.toFixed(2), v => { S.mat.metal = v; applyMaterial(); });
bind('sTr', 'vTr', v => v.toFixed(2), v => { S.mat.trans = v; applyMaterial(); });
$('mColor').addEventListener('input', e => { S.mat.color = e.target.value; applyMaterial(); });
$('gridOn').addEventListener('click', () => setGrid(true));
$('gridOff').addEventListener('click', () => setGrid(false));

/* ---------- project: save / load / JSON ---------- */
const LS_KEY = 'blob_cutter_v1';
const r4 = v => Math.round(v * 1e4) / 1e4;
const vArr = v => [r4(v.x), r4(v.y), r4(v.z)];
function serialize() {
  return {
    app: 'BLOB:CUTTER', version: '1.0',
    settings: { blend: S.blend, fall: S.fall, prevRes: S.prevRes, rendRes: S.rendRes, flat: S.flat, outline: S.outline,
                sym: S.sym.slice(), mat: { ...S.mat }, grid: grid.visible },
    cut: { ...S.cut },
    seams: S.seams.map(sm => ({ pts: sm.pts.map(p => p.map(r4)), closed: !!sm.closed })),
    ref: REF.buf ? { name: REF.name, params: { ...S.ref }, glb: b64(REF.buf) } : null,
    blobs: S.blobs.map(b => ({
      type: b.type, pos: vArr(b.pos), quat: [r4(b.quat.x), r4(b.quat.y), r4(b.quat.z), r4(b.quat.w)], scale: vArr(b.scale),
      r: b.r, len: b.len, round: b.round, sym: b.sym.slice(), neg: !!b.neg,
      ...(b.pts ? { pts: b.pts.map(vArr), hin: b.hin.map(vArr), hout: b.hout.map(vArr), rad: b.rad.slice(), taper: b.taper || 0 } : { dt: b.dt || 0, db: b.db || 0, dw: b.dw || 0 }),
    })),
  };
}
function loadProject(d) {
  if (!d || !Array.isArray(d.blobs)) throw new Error('not a blob project');
  const st = d.settings || {}, num = (v, def) => (typeof v === 'number' && isFinite(v) ? v : def);
  const setSlider = (id, v) => { if (typeof v === 'number') { $(id).value = v; $(id).dispatchEvent(new Event('input')); } };
  if (S.drawing) endDrawMode();
  if (S.pulling) endPull();
  if (S.stage === 'cut') setStage('sculpt');
  cutReset();
  S.blobs = []; S.sel = null; S.sels = []; S.clip = null;
  const keepNeg = S.neg; S.neg = false;
  for (const o of d.blobs) {
    if (!['sphere', 'cube', 'capsule', 'spline'].includes(o.type) || o.field) continue;   // (old force-field blobs are dropped)
    const b = makeBlob(o.type, new V3(...(o.pos || [0, 0, 0])));
    if (o.quat) b.quat.set(...o.quat);
    if (o.scale) b.scale.set(...o.scale);
    b.r = num(o.r, b.r); b.len = num(o.len, b.len); b.round = num(o.round, b.round);
    b.sym = Array.isArray(o.sym) ? o.sym.map(Boolean) : [false, false, false];
    b.neg = !!o.neg; b.dt = num(o.dt, 0); b.db = num(o.db, 0); b.dw = num(o.dw, 0); b.taper = num(o.taper, 0);
    if (o.type === 'spline') {
      if (!Array.isArray(o.pts) || o.pts.length < 2) continue;
      b.pts = o.pts.map(a => new V3(...a));
      if (o.hin && o.hout) { b.hin = o.hin.map(a => new V3(...a)); b.hout = o.hout.map(a => new V3(...a)); } else autoHandles(b);
      b.rad = Array.isArray(o.rad) && o.rad.length === b.pts.length ? o.rad.map(v => num(v, 1)) : null;
      updateSpline(b);
    }
    S.blobs.push(b);
  }
  S.neg = keepNeg;
  if (d.ref && d.ref.glb) loadRefBuffer(unb64(d.ref.glb), d.ref.name || 'reference.glb', d.ref.params).then(() => { refUI(); markDirty(); }).catch(console.error);
  else if (REF.geo) refClear();
  setSlider('sBlend', st.blend); setSlider('sFall', st.fall); setSlider('sPrev', st.prevRes); setSlider('sRend', st.rendRes);
  if (st.mat) {
    Object.assign(S.mat, st.mat); $('mColor').value = S.mat.color;
    setSlider('sSm', S.mat.smooth); setSlider('sMe', S.mat.metal); setSlider('sTr', S.mat.trans); applyMaterial();
  }
  S.seams = Array.isArray(d.seams) ? d.seams.filter(o => o && Array.isArray(o.pts) && o.pts.length >= 2).map(o => ({ pts: o.pts.map(p => [num(p[0], 0), num(p[1], 0), num(p[2], 0)]), closed: !!o.closed })) : [];
  if (d.cut) for (const [id, k] of [['sCb', 'bias'], ['sCr', 'res'], ['sCs', 'size'], ['sCe', 'ease'], ['sCa', 'allow'], ['sCn', 'notch'], ['sCk', 'knot']]) setSlider(id, d.cut[k]);
  if (typeof st.flat === 'boolean') setShading(st.flat);
  if (typeof st.outline === 'boolean') setOutline(st.outline);
  if (typeof st.grid === 'boolean') setGrid(st.grid);
  if (Array.isArray(st.sym)) S.sym = st.sym.map(Boolean);
  if (hqMesh) { scene.remove(hqMesh); hqMesh = null; }
  if (hqGeo) { hqGeo.dispose(); hqGeo = null; }
  $('btnGlb').disabled = true;
  select(null); setNegMode(S.neg); markDirty();
}
function downloadBlob(blob, name) {
  const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name;
  document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 2000);
}
function saveLocal() {
  try { localStorage.setItem(LS_KEY, JSON.stringify(serialize())); setStatus('PROJECT SAVED'); }
  catch (err) { setStatus('SAVE FAILED — USE EXPORT .JSON'); }
}
function loadLocal() {
  try {
    const t = localStorage.getItem(LS_KEY);
    if (!t) { setStatus('NO SAVED PROJECT'); return; }
    loadProject(JSON.parse(t)); setStatus('PROJECT LOADED');
  } catch (err) { console.error(err); setStatus('LOAD FAILED'); }
}
$('pSave').addEventListener('click', saveLocal);
$('pLoad').addEventListener('click', loadLocal);
$('pExp').addEventListener('click', () => {
  downloadBlob(new Blob([JSON.stringify(serialize(), null, 1)], { type: 'application/json' }), 'blob_cutter_project.json');
  setStatus('PROJECT EXPORTED');
});
$('pImp').addEventListener('click', () => $('pFile').click());
$('pFile').addEventListener('change', e => {
  const f = e.target.files[0]; if (!f) return;
  f.text().then(t => { loadProject(JSON.parse(t)); setStatus('PROJECT IMPORTED'); })
          .catch(err => { console.error(err); setStatus('IMPORT FAILED — INVALID JSON'); });
  e.target.value = '';
});

/* ---------- high quality render + GLB ---------- */
function renderHQ() {
  if (!S.blobs.some(b => !b.neg)) { setStatus('NOTHING SOLID TO RENDER'); return; }
  setStatus('BUILDING…'); $('btnRender').disabled = true;
  setTimeout(() => {
    try {
      const t0 = performance.now();
      const r = polygonize(withRef(compile(S.blobs)), S.blend, 1 / S.rendRes, 24e6, false);
      if (!r) { setStatus('NOTHING SOLID TO RENDER'); $('btnRender').disabled = false; return; }
      if (hqMesh) scene.remove(hqMesh);
      if (hqGeo) hqGeo.dispose();
      hqGeo = r.geo;
      hqMesh = new THREE.Mesh(hqGeo, matHQ); scene.add(hqMesh);
      prevMesh.visible = false; negMesh.visible = false; S.hqFresh = true;
      lastTris = r.tris; lastMs = performance.now() - t0;
      const capped = r.H > 1 / S.rendRes * 1.001 ? ` · CAPPED AT ${Math.round(1 / r.H)}` : '';
      setStatus(`DONE · ${fmtN(r.tris)} TRIS · ${(lastMs / 1000).toFixed(1)} S${capped}`);
      $('btnGlb').disabled = false;
    } catch (err) {
      console.error(err); setStatus('ERROR — LOWER THE RENDER RES');
    }
    $('btnRender').disabled = false;
  }, 40);
}
$('btnRender').addEventListener('click', renderHQ);

function exportGLB(srcGeo) {
  const base = srcGeo && srcGeo.isBufferGeometry ? srcGeo : hqGeo;      // detail stage passes its own geometry
  if (!base) return;
  let g = base;
  if (S.flat) { g = base.toNonIndexed(); g.computeVertexNormals(); }           // raw / faceted normals baked in
  const m = S.mat;
  const mesh = new THREE.Mesh(g, new THREE.MeshPhysicalMaterial({
    color: m.color, roughness: 1 - m.smooth, metalness: m.metal,
    transmission: m.trans, thickness: 0.6, ior: 1.4, attenuationColor: new THREE.Color(m.color), attenuationDistance: 1.5 }));
  mesh.name = 'blob_mesh';
  new GLTFExporter().parse(mesh, buf => {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([buf], { type: 'model/gltf-binary' }));
    a.download = 'blob_mesh.glb'; a.click();
    setTimeout(() => URL.revokeObjectURL(a.href), 3000);
  }, err => { console.error(err); setStatus('EXPORT FAILED'); }, { binary: true });
}
$('btnGlb').addEventListener('click', exportGLB);
const fmtN = n => n >= 1e6 ? (n / 1e6).toFixed(2) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'K' : String(n);

/*CORE-START*/
/* ============================================================
   CUT CORE  (pure geometry, no DOM / no three.js)
   mesh topology -> seam graph -> pieces (charts) -> flattening (LSCM + ARAP) -> pattern layout
============================================================ */
const CC = (() => {
  const sq = x => x * x;

  /* ---------- mesh topology + geometry ---------- */
  function mesh(P, T) {
    const nV = P.length / 3, nT = T.length / 3;
    const emap = new Map(), e0 = [], e1 = [], et0 = [], et1 = [], ec = [];
    const TE = new Int32Array(nT * 3);
    for (let t = 0; t < nT; t++) for (let k = 0; k < 3; k++) {
      const a = T[3 * t + k], b = T[3 * t + (k + 1) % 3], key = a < b ? a * nV + b : b * nV + a;
      let e = emap.get(key);
      if (e === undefined) { e = e0.length; emap.set(key, e); e0.push(Math.min(a, b)); e1.push(Math.max(a, b)); et0.push(t); et1.push(-1); ec.push(1); }
      else { if (ec[e] === 1) et1[e] = t; ec[e]++; }
      TE[3 * t + k] = e;
    }
    const nE = e0.length, deg = new Int32Array(nV + 1);
    for (let e = 0; e < nE; e++) { deg[e0[e] + 1]++; deg[e1[e] + 1]++; }
    for (let i = 0; i < nV; i++) deg[i + 1] += deg[i];
    const adjE = new Int32Array(2 * nE), fl = deg.slice(0, nV);
    for (let e = 0; e < nE; e++) { adjE[fl[e0[e]]++] = e; adjE[fl[e1[e]]++] = e; }
    const M = { P, T, nV, nT, nE, TE, e0: Int32Array.from(e0), e1: Int32Array.from(e1), et0: Int32Array.from(et0), et1: Int32Array.from(et1), ec: Int32Array.from(ec), adjS: deg, adjE,
      edge: (a, b) => emap.get(a < b ? a * nV + b : b * nV + a) };
    geom(M, P);
    let x0 = 1e9, y0 = 1e9, z0 = 1e9, x1 = -1e9, y1 = -1e9, z1 = -1e9;
    for (let i = 0; i < nV; i++) { x0 = Math.min(x0, P[3 * i]); x1 = Math.max(x1, P[3 * i]); y0 = Math.min(y0, P[3 * i + 1]); y1 = Math.max(y1, P[3 * i + 1]); z0 = Math.min(z0, P[3 * i + 2]); z1 = Math.max(z1, P[3 * i + 2]); }
    M.bb = [x0, y0, z0, x1, y1, z1]; M.ext = Math.max(x1 - x0, y1 - y0, z1 - z0, 1e-6);
    let L = 0; for (let e = 0; e < nE; e++) L += M.elen[e]; M.h = L / Math.max(1, nE);
    // spatial hash for nearest-vertex queries
    const CS = M.h * 2.5, grid = new Map();
    const ck = (x, y, z) => (x + 2048) * 16777216 + (y + 2048) * 4096 + (z + 2048);
    for (let i = 0; i < nV; i++) {
      const k = ck(Math.floor(P[3 * i] / CS), Math.floor(P[3 * i + 1] / CS), Math.floor(P[3 * i + 2] / CS));
      let a = grid.get(k); if (!a) grid.set(k, a = []); a.push(i);
    }
    M.nearest = (x, y, z) => {
      const cx = Math.floor(x / CS), cy = Math.floor(y / CS), cz = Math.floor(z / CS);
      let best = -1, bd = Infinity;
      for (let r = 0; r <= 3 && best < 0; r++)
        for (let a = -r; a <= r; a++) for (let b = -r; b <= r; b++) for (let c = -r; c <= r; c++) {
          if (Math.max(Math.abs(a), Math.abs(b), Math.abs(c)) !== r) continue;
          const l = grid.get(ck(cx + a, cy + b, cz + c)); if (!l) continue;
          for (const i of l) { const d = sq(P[3 * i] - x) + sq(P[3 * i + 1] - y) + sq(P[3 * i + 2] - z); if (d < bd) { bd = d; best = i; } }
        }
      if (best < 0) for (let i = 0; i < nV; i++) { const d = sq(P[3 * i] - x) + sq(P[3 * i + 1] - y) + sq(P[3 * i + 2] - z); if (d < bd) { bd = d; best = i; } }
      return best;
    };
    return M;
  }

  // normals, areas, local triangle frames (isometric 2D coords) + cotangents, edge lengths, crease measure
  function geom(M, P) {
    const { T, nT, nV, nE, e0, e1, et0, et1, ec } = M;
    const FN = new Float64Array(nT * 3), FA = new Float64Array(nT), VN = new Float64Array(nV * 3);
    const loc = new Float64Array(nT * 3), cot = new Float64Array(nT * 3);
    for (let t = 0; t < nT; t++) {
      const a = 3 * T[3 * t], b = 3 * T[3 * t + 1], c = 3 * T[3 * t + 2];
      const ux = P[b] - P[a], uy = P[b + 1] - P[a + 1], uz = P[b + 2] - P[a + 2];
      const vx = P[c] - P[a], vy = P[c + 1] - P[a + 1], vz = P[c + 2] - P[a + 2];
      let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
      const l = Math.hypot(nx, ny, nz) || 1e-30;
      FA[t] = l / 2;
      for (const q of [a, b, c]) { VN[q] += nx; VN[q + 1] += ny; VN[q + 2] += nz; }
      FN[3 * t] = nx / l; FN[3 * t + 1] = ny / l; FN[3 * t + 2] = nz / l;
      const lu = Math.hypot(ux, uy, uz) || 1e-30, x2 = (ux * vx + uy * vy + uz * vz) / lu, y2 = l / lu;
      loc[3 * t] = lu; loc[3 * t + 1] = x2; loc[3 * t + 2] = Math.max(y2, 1e-12);
      const pts = [[0, 0], [lu, 0], [x2, y2]];
      for (let k = 0; k < 3; k++) {
        const p = pts[k], q = pts[(k + 1) % 3], r = pts[(k + 2) % 3];
        const ax = q[0] - p[0], ay = q[1] - p[1], bx = r[0] - p[0], by = r[1] - p[1];
        cot[3 * t + k] = (ax * bx + ay * by) / (Math.abs(ax * by - ay * bx) || 1e-30);
      }
    }
    for (let i = 0; i < nV; i++) { const l = Math.hypot(VN[3 * i], VN[3 * i + 1], VN[3 * i + 2]) || 1; VN[3 * i] /= l; VN[3 * i + 1] /= l; VN[3 * i + 2] /= l; }
    const elen = new Float64Array(nE), crease = new Float64Array(nE);
    for (let e = 0; e < nE; e++) {
      const a = 3 * e0[e], b = 3 * e1[e];
      elen[e] = Math.hypot(P[a] - P[b], P[a + 1] - P[b + 1], P[a + 2] - P[b + 2]);
      if (ec[e] !== 2) continue;
      const t0 = et0[e], t1 = et1[e];
      const d = FN[3 * t0] * FN[3 * t1] + FN[3 * t0 + 1] * FN[3 * t1 + 1] + FN[3 * t0 + 2] * FN[3 * t1 + 2];
      const ang = Math.acos(Math.max(-1, Math.min(1, d)));
      let cx = 0, cy = 0, cz = 0;   // centroid difference
      for (let k = 0; k < 3; k++) { const q = 3 * T[3 * t1 + k], r = 3 * T[3 * t0 + k]; cx += P[q] - P[r]; cy += P[q + 1] - P[r + 1]; cz += P[q + 2] - P[r + 2]; }
      const concave = FN[3 * t0] * cx + FN[3 * t0 + 1] * cy + FN[3 * t0 + 2] * cz > 0;
      crease[e] = concave ? ang : -ang;
    }
    Object.assign(M, { FN, FA, VN, loc, cot, elen, crease });
  }

  // tangential relaxation + projection back onto the implicit surface: evens out the surface-nets triangles
  function relax(M, project, iters) {
    const { P, nV, adjS, adjE, e0, e1 } = M;
    for (let it = 0; it < iters; it++) {
      const Q = P.slice();
      for (let v = 0; v < nV; v++) {
        let sx = 0, sy = 0, sz = 0, n = 0;
        for (let j = adjS[v]; j < adjS[v + 1]; j++) { const e = adjE[j], o = 3 * (e0[e] === v ? e1[e] : e0[e]); sx += Q[o]; sy += Q[o + 1]; sz += Q[o + 2]; n++; }
        if (!n) continue;
        let dx = sx / n - Q[3 * v], dy = sy / n - Q[3 * v + 1], dz = sz / n - Q[3 * v + 2];
        const nx = M.VN[3 * v], ny = M.VN[3 * v + 1], nz = M.VN[3 * v + 2], dn = dx * nx + dy * ny + dz * nz;
        dx -= dn * nx; dy -= dn * ny; dz -= dn * nz;
        const p = project(Q[3 * v] + 0.5 * dx, Q[3 * v + 1] + 0.5 * dy, Q[3 * v + 2] + 0.5 * dz);
        P[3 * v] = p[0]; P[3 * v + 1] = p[1]; P[3 * v + 2] = p[2];
      }
      geom(M, P);
    }
  }

  /* ---------- shortest seam path along mesh edges (Dijkstra, creases are cheaper) ---------- */
  function weights(M, bias) {           // edge cost: creases (concave) cheap, convex ridges a bit more expensive
    const W = new Float64Array(M.nE);
    for (let e = 0; e < M.nE; e++) {
      const c = M.crease[e], a = Math.min(1, Math.abs(c) / 0.45);
      W[e] = M.elen[e] * (c > 0 ? Math.max(0.12, 1 - bias * 0.88 * a) : 1 + bias * 1.2 * a);
    }
    return W;
  }
  // multi-source shortest paths over allowed edges
  function spread(M, sources, edgeOK, W) {
    const n = M.nV, dist = new Float64Array(n).fill(Infinity), prev = new Int32Array(n).fill(-1), hk = [], hv = [];
    const push = (k, v) => { let i = hk.length; hk.push(k); hv.push(v); while (i > 0) { const p = (i - 1) >> 1; if (hk[p] <= k) break; hk[i] = hk[p]; hv[i] = hv[p]; i = p; } hk[i] = k; hv[i] = v; };
    const pop = () => { const v = hv[0], k = hk.pop(), x = hv.pop(), n2 = hk.length; if (n2) { let i = 0; for (;;) { let c = 2 * i + 1; if (c >= n2) break; if (c + 1 < n2 && hk[c + 1] < hk[c]) c++; if (hk[c] >= k) break; hk[i] = hk[c]; hv[i] = hv[c]; i = c; } hk[i] = k; hv[i] = x; } return v; };
    for (const s of sources) { dist[s] = 0; push(0, s); }
    const { adjS, adjE, e0, e1 } = M;
    while (hk.length) {
      const d = hk[0], v = pop(); if (d > dist[v]) continue;
      for (let j = adjS[v]; j < adjS[v + 1]; j++) {
        const e = adjE[j]; if (!edgeOK(e)) continue;
        const o = e0[e] === v ? e1[e] : e0[e], nd = d + W[e];
        if (nd < dist[o]) { dist[o] = nd; prev[o] = v; push(nd, o); }
      }
    }
    return { dist, prev };
  }
  // plane cut through a set of triangles -> closed / open polylines (world points)
  function section(P, M, tris, n, c) {
    const { T, TE } = M, sd = v => (P[3 * v] - c[0]) * n[0] + (P[3 * v + 1] - c[1]) * n[1] + (P[3 * v + 2] - c[2]) * n[2];
    const pt = new Map(), adj = new Map(), link = (a, b) => { (adj.get(a) || adj.set(a, []).get(a)).push(b); };
    for (const t of tris) {
      const cr = [];
      for (let k = 0; k < 3; k++) {
        const a = T[3 * t + k], b = T[3 * t + (k + 1) % 3], da = sd(a), db = sd(b);
        if ((da < 0) === (db < 0)) continue;
        const e = TE[3 * t + k];
        if (!pt.has(e)) { const u = da / (da - db); pt.set(e, [P[3 * a] + (P[3 * b] - P[3 * a]) * u, P[3 * a + 1] + (P[3 * b + 1] - P[3 * a + 1]) * u, P[3 * a + 2] + (P[3 * b + 2] - P[3 * a + 2]) * u]); }
        cr.push(e);
      }
      if (cr.length === 2) { link(cr[0], cr[1]); link(cr[1], cr[0]); }
    }
    const seen = new Set(), out = [];
    for (const s of adj.keys()) {
      if (seen.has(s)) continue;
      // walk to one end first (open chains), then collect
      let a = s, pr = -1, guard = 0;
      for (;;) { const nb = (adj.get(a) || []).filter(x => x !== pr); if (adj.get(a).length < 2 || !nb.length || nb[0] === s || guard++ > 1e6) break; pr = a; a = nb[0]; if (a === s) break; }
      const loop = []; let cur = a; pr = -1;
      for (;;) {
        seen.add(cur); loop.push(pt.get(cur));
        const nb = (adj.get(cur) || []).filter(x => x !== pr && !seen.has(x));
        if (!nb.length) break; pr = cur; cur = nb[0];
      }
      const l = adj.get(a) || [], closed = loop.length > 2 && l.length === 2 && (adj.get(cur) || []).includes(a);
      out.push({ pts: loop, closed });
    }
    return out;
  }
  // Gaussian curvature per vertex (angle defect / area), smoothed
  function curvature(M, smooth) {
    const { nV, nT, T, cot, FA, adjS, adjE, e0, e1 } = M, ang = new Float64Array(nV).fill(2 * Math.PI), ar = new Float64Array(nV);
    for (let t = 0; t < nT; t++) for (let k = 0; k < 3; k++) { const v = T[3 * t + k]; ang[v] -= Math.atan2(1, cot[3 * t + k]); ar[v] += FA[t] / 3; }
    let K = new Float64Array(nV); for (let v = 0; v < nV; v++) K[v] = ar[v] > 0 ? ang[v] / ar[v] : 0;
    for (let it = 0; it < (smooth || 0); it++) {
      const Q = new Float64Array(nV);
      for (let v = 0; v < nV; v++) {
        let s = K[v] * ar[v], w = ar[v];
        for (let j = adjS[v]; j < adjS[v + 1]; j++) { const e = adjE[j], o = e0[e] === v ? e1[e] : e0[e]; s += K[o] * ar[o]; w += ar[o]; }
        Q[v] = s / (w || 1);
      }
      K = Q;
    }
    return K;
  }

  function dijkstra(M) {
    const n = M.nV, dist = new Float64Array(n), prev = new Int32Array(n), stamp = new Int32Array(n), done = new Int32Array(n);
    let gen = 0, hk = new Float64Array(1024), hv = new Int32Array(1024), hn = 0;
    const push = (k, v) => {
      if (hn >= hk.length) { const a = new Float64Array(hk.length * 2), b = new Int32Array(hk.length * 2); a.set(hk); b.set(hv); hk = a; hv = b; }
      let i = hn++;
      while (i > 0) { const p = (i - 1) >> 1; if (hk[p] <= k) break; hk[i] = hk[p]; hv[i] = hv[p]; i = p; }
      hk[i] = k; hv[i] = v;
    };
    const pop = () => {
      const v = hv[0], k = hk[--hn], x = hv[hn];
      let i = 0;
      for (;;) { let c = 2 * i + 1; if (c >= hn) break; if (c + 1 < hn && hk[c + 1] < hk[c]) c++; if (hk[c] >= k) break; hk[i] = hk[c]; hv[i] = hv[c]; i = c; }
      hk[i] = k; hv[i] = x; return v;
    };
    let W = null, Wbias = -1;
    return (src, dst, bias) => {
      if (src === dst) return [src];
      if (bias !== Wbias || !W) { W = weights(M, bias); Wbias = bias; }
      gen++; hn = 0;
      stamp[src] = gen; dist[src] = 0; prev[src] = -1; push(0, src);
      const { adjS, adjE, e0, e1 } = M;
      while (hn) {
        const v = pop();
        if (done[v] === gen) continue; done[v] = gen;
        if (v === dst) break;
        const dv = dist[v];
        for (let j = adjS[v]; j < adjS[v + 1]; j++) {
          const e = adjE[j], o = e0[e] === v ? e1[e] : e0[e], nd = dv + W[e];
          if (stamp[o] !== gen || nd < dist[o]) { stamp[o] = gen; dist[o] = nd; prev[o] = v; push(nd, o); }
        }
      }
      if (done[dst] !== gen) return null;
      const out = []; for (let v = dst; v >= 0; v = prev[v]) out.push(v);
      return out.reverse();
    };
  }

  /* ---------- analysis: seams -> pieces, seam graph, boundary loops ---------- */
  function hashArr(a, h) { h = h || 2166136261; for (let i = 0; i < a.length; i++) { h ^= a[i]; h = Math.imul(h, 16777619); h ^= h >>> 13; } return h >>> 0; }

  function analyze(M, paths, knotLen, project, fixedIds, bias) {
    const { nV, nT, T, TE, e0, e1, et0, et1, ec, nE, adjS, adjE } = M;
    const seamE = new Uint8Array(nE);
    for (const p of paths) for (let i = 0; i + 1 < p.length; i++) { const e = M.edge(p[i], p[i + 1]); if (e !== undefined) seamE[e] = 1; }
    const cut = e => seamE[e] === 1 || ec[e] !== 2;

    /* seam graph: chains between nodes (junctions / ends), split into sub-chains by length */
    const sdeg = new Int32Array(nV);
    for (let e = 0; e < nE; e++) if (seamE[e]) { sdeg[e0[e]]++; sdeg[e1[e]]++; }
    const isNode = v => sdeg[v] !== 2, vis = new Uint8Array(nE), chains = [];
    const walk = (v, e) => {
      const verts = [v], edges = []; let cur = v, ce = e;
      for (;;) {
        vis[ce] = 1; edges.push(ce);
        const nx = e0[ce] === cur ? e1[ce] : e0[ce]; verts.push(nx);
        if (isNode(nx) || nx === verts[0]) break;
        let ne = -1;
        for (let j = adjS[nx]; j < adjS[nx + 1]; j++) { const x = adjE[j]; if (seamE[x] && !vis[x]) { ne = x; break; } }
        if (ne < 0) break;
        cur = nx; ce = ne;
      }
      return { verts, edges, closed: verts[0] === verts[verts.length - 1] && !isNode(verts[0]) };
    };
    for (let v = 0; v < nV; v++) if (sdeg[v] && isNode(v))
      for (let j = adjS[v]; j < adjS[v + 1]; j++) { const e = adjE[j]; if (seamE[e] && !vis[e]) chains.push(walk(v, e)); }
    for (let e = 0; e < nE; e++) if (seamE[e] && !vis[e]) chains.push(walk(e0[e], e));

    /* straighten the seam lines on the surface: edge paths zig-zag, so seam vertices slide towards the smooth
       curve between their fixed points (control points, junctions, ends). Vertices on creases stay put
       (prefer-creases), then the mesh around the seams is relaxed so no triangle folds. */
    const P = M.P.slice(), fixed = new Uint8Array(nV);
    const vlen0 = (a, b) => Math.hypot(M.P[3 * a] - M.P[3 * b], M.P[3 * a + 1] - M.P[3 * b + 1], M.P[3 * a + 2] - M.P[3 * b + 2]);
    if (fixedIds) for (const v of fixedIds) fixed[v] = 1;
    if (project) {
      const mob = new Float64Array(nV), ids = [];
      for (const ch of chains) {
        const vs = ch.verts, m = vs.length - 1;
        fixed[vs[0]] = 1; if (!ch.closed) fixed[vs[m]] = 1;
        for (let i = 1; i < m; i++) ids.push([vs[i - 1], vs[i], vs[i + 1]]);
        if (ch.closed && m >= 3) ids.push([vs[m - 1], vs[0], vs[1]]);
        for (let i = 0; i < m; i++) { const c = Math.max(0, M.crease[ch.edges[i]]), k = 1 - (bias || 0) * Math.min(1, c / 0.35); mob[vs[i]] = Math.max(mob[vs[i]] || 0, 0); mob[vs[i]] = i === 0 ? k : Math.min(mob[vs[i]] || k, k); mob[vs[i + 1]] = k; }
      }
      // 1) move each stretch between fixed vertices onto a surface curve built by geodesic bisection
      //    (midpoint of the chord, projected onto the surface, recursively) - converges where plain smoothing cannot
      const V3 = v => [P[3 * v], P[3 * v + 1], P[3 * v + 2]];
      for (const ch of chains) {
        const vs = ch.verts, m = vs.length - 1, fx = [];
        for (let i = 0; i <= m; i++) if (fixed[vs[i]] || i === 0 || i === m) fx.push(i);
        for (let s = 0; s + 1 < fx.length; s++) {
          const i0 = fx[s], i1 = fx[s + 1], n = i1 - i0; if (n < 2) continue;
          let pl = 0; for (let i = i0 + 1; i <= i1; i++) pl += vlen0(vs[i - 1], vs[i]);
          if (vlen0(vs[i0], vs[i1]) * 1.25 < pl) continue;          // arc too long for a stable bisection: leave it to the smoothing
          let crv = [V3(vs[i0]), V3(vs[i1])];
          while (crv.length - 1 < 2 * n) {
            const nx = [crv[0]];
            for (let i = 1; i < crv.length; i++) { const a = crv[i - 1], b = crv[i]; nx.push(project((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2), b); }
            crv = nx;
          }
          const cc = [0]; for (let i = 1; i < crv.length; i++) cc.push(cc[i - 1] + Math.hypot(crv[i][0] - crv[i - 1][0], crv[i][1] - crv[i - 1][1], crv[i][2] - crv[i - 1][2]));
          const pc = [0]; for (let i = i0 + 1; i <= i1; i++) pc.push(pc[pc.length - 1] + vlen0(vs[i - 1], vs[i]));
          for (let i = i0 + 1; i < i1; i++) {
            const v = vs[i], tt = pc[i - i0] / pc[n] * cc[cc.length - 1]; let j = 1;
            while (j < cc.length - 1 && cc[j] < tt) j++;
            const u = (tt - cc[j - 1]) / ((cc[j] - cc[j - 1]) || 1), w = mob[v];
            for (let q = 0; q < 3; q++) P[3 * v + q] += w * (crv[j - 1][q] + (crv[j][q] - crv[j - 1][q]) * u - P[3 * v + q]);
          }
        }
      }
      // 2) light smoothing on top
      const act = ids.filter(q => !fixed[q[1]]);
      for (let it = 0; it < 40; it++) {
        const Q = P.slice();
        for (const [a, v, b] of act) {
          const w = 0.5 * mob[v];
          P[3 * v] = Q[3 * v] + w * ((Q[3 * a] + Q[3 * b]) / 2 - Q[3 * v]);
          P[3 * v + 1] = Q[3 * v + 1] + w * ((Q[3 * a + 1] + Q[3 * b + 1]) / 2 - Q[3 * v + 1]);
          P[3 * v + 2] = Q[3 * v + 2] + w * ((Q[3 * a + 2] + Q[3 * b + 2]) / 2 - Q[3 * v + 2]);
        }
        if (it % 10 === 9) for (const [, v] of act) { const q = project(P[3 * v], P[3 * v + 1], P[3 * v + 2]); P[3 * v] = q[0]; P[3 * v + 1] = q[1]; P[3 * v + 2] = q[2]; }
      }
      // relax the rings around the seams (seam vertices fixed)
      const onSeam = new Uint8Array(nV); for (let e = 0; e < nE; e++) if (seamE[e]) onSeam[e0[e]] = onSeam[e1[e]] = 1;
      let ring = new Uint8Array(nV);
      for (let v = 0; v < nV; v++) if (onSeam[v]) ring[v] = 1;
      for (let r = 0; r < 3; r++) { const nx = ring.slice(); for (let e = 0; e < nE; e++) if (ring[e0[e]] || ring[e1[e]]) nx[e0[e]] = nx[e1[e]] = 1; ring = nx; }
      const free = []; for (let v = 0; v < nV; v++) if (ring[v] && !onSeam[v]) free.push(v);
      for (let it = 0; it < 8; it++) {
        const Q = P.slice();
        for (const v of free) {
          let sx = 0, sy = 0, sz = 0, n = 0;
          for (let j = adjS[v]; j < adjS[v + 1]; j++) { const e = adjE[j], o = 3 * (e0[e] === v ? e1[e] : e0[e]); sx += Q[o]; sy += Q[o + 1]; sz += Q[o + 2]; n++; }
          const q = project(Q[3 * v] + 0.6 * (sx / n - Q[3 * v]), Q[3 * v + 1] + 0.6 * (sy / n - Q[3 * v + 1]), Q[3 * v + 2] + 0.6 * (sz / n - Q[3 * v + 2]));
          P[3 * v] = q[0]; P[3 * v + 1] = q[1]; P[3 * v + 2] = q[2];
        }
      }
    }
    const G = { T, nT, nV, nE, e0, e1, et0, et1, ec };
    geom(G, P);

    const subs = [], edgeSub = new Int32Array(nE).fill(-1), edgeIdx = new Int32Array(nE);
    const vlen = (a, b) => Math.hypot(P[3 * a] - P[3 * b], P[3 * a + 1] - P[3 * b + 1], P[3 * a + 2] - P[3 * b + 2]);
    chains.forEach((ch, ci) => {
      const vs = ch.verts, m = ch.edges.length, cum = [0];
      for (let i = 0; i < m; i++) cum.push(cum[i] + vlen(vs[i], vs[i + 1]));
      ch.len3 = cum[m]; ch.subs = [];
      let n = Math.max(ch.closed ? 3 : 2, Math.round(cum[m] / knotLen));
      n = Math.max(1, Math.min(n, m));
      const cuts = [0];
      for (let i = 1; i < n; i++) {
        const target = cum[m] * i / n; let j = cuts[i - 1] + 1;
        while (j < m - (n - i) && cum[j + 1] <= target) j++;
        if (j < m - (n - i) && Math.abs(cum[j + 1] - target) < Math.abs(cum[j] - target)) j++;
        cuts.push(j);
      }
      cuts.push(m);
      for (let i = 0; i < n; i++) {
        const a = cuts[i], b = cuts[i + 1], id = subs.length;
        subs.push({ id, chain: ci, verts: vs.slice(a, b + 1), edges: ch.edges.slice(a, b), side: [null, null] });
        for (let q = a; q < b; q++) { edgeSub[ch.edges[q]] = id; edgeIdx[ch.edges[q]] = q - a; }
        ch.subs.push(id);
      }
    });

    /* pieces: triangles connected across uncut edges; wedges: vertex copies split by the cuts */
    const ufT = new Int32Array(nT), ufC = new Int32Array(3 * nT);
    for (let i = 0; i < nT; i++) ufT[i] = i;
    for (let i = 0; i < 3 * nT; i++) ufC[i] = i;
    const find = (a, x) => { while (a[x] !== x) { a[x] = a[a[x]]; x = a[x]; } return x; };
    const uni = (a, x, y) => { x = find(a, x); y = find(a, y); if (x !== y) a[x] = y; };
    const corner = (t, v) => 3 * t + (T[3 * t] === v ? 0 : T[3 * t + 1] === v ? 1 : 2);
    for (let e = 0; e < nE; e++) {
      if (cut(e)) continue;
      const t0 = et0[e], t1 = et1[e];
      uni(ufT, t0, t1); uni(ufC, corner(t0, e0[e]), corner(t1, e0[e])); uni(ufC, corner(t0, e1[e]), corner(t1, e1[e]));
    }
    const W = new Int32Array(3 * nT), wm = new Int32Array(3 * nT).fill(-1), wv = [];
    for (let c = 0; c < 3 * nT; c++) { const r = find(ufC, c); if (wm[r] < 0) { wm[r] = wv.length; wv.push(T[c]); } W[c] = wm[r]; }
    const chartOf = new Int32Array(nT), cm = new Map(), charts = [];
    for (let t = 0; t < nT; t++) {
      const r = find(ufT, t); let c = cm.get(r);
      if (c === undefined) { c = charts.length; cm.set(r, c); charts.push({ id: c, tris: [] }); }
      chartOf[t] = c; charts[c].tris.push(t);
    }

    /* boundary loops per piece (half-edges keep the triangle's winding: piece interior is on the left) */
    for (const ch of charts) {
      const he = [], ws = new Set(), outM = new Map();
      for (const t of ch.tris) for (let k = 0; k < 3; k++) {
        ws.add(W[3 * t + k]);
        const e = TE[3 * t + k]; if (!cut(e)) continue;
        const a = T[3 * t + k], s = edgeSub[e];
        const h = { a, from: W[3 * t + k], to: W[3 * t + (k + 1) % 3], e, sub: s, side: s >= 0 ? (subs[s].verts[edgeIdx[e]] === a ? 0 : 1) : -1, t };
        let l = outM.get(h.from); if (!l) outM.set(h.from, l = []); l.push(he.length); he.push(h);
      }
      const used = new Uint8Array(he.length), loops = []; let broken = false;
      for (let i = 0; i < he.length; i++) {
        if (used[i]) continue;
        const loop = []; let cur = i;
        while (cur >= 0 && !used[cur]) {
          used[cur] = 1; loop.push(he[cur]);
          const l = outM.get(he[cur].to); cur = -1;
          if (l) for (const j of l) if (!used[j]) { cur = j; break; }
        }
        if (loop[loop.length - 1].to !== loop[0].from) broken = true;
        loops.push(loop);
      }
      const V = ws.size, F = ch.tris.length, B = he.length, E = (3 * F + B) / 2, chi = V - E + F, g = (2 - chi - loops.length) / 2;
      ch.loops = loops; ch.genus = g; ch.nW = V;
      ch.status = broken || g !== Math.round(g) ? 'broken' : !loops.length ? 'closed' : g > 0 ? 'handle' : 'ok';
      let area = 0; for (const t of ch.tris) area += G.FA[t]; ch.area3 = area;
      ch.key = hashArr(Int32Array.from(he.filter(h => fixed[h.a]).map(h => h.a).sort((a, b) => a - b)), hashArr(Int32Array.from(he.map(h => h.e).sort((a, b) => a - b)), hashArr(Int32Array.from(ch.tris)))) + ':' + ch.tris.length;
      // groups: maximal runs of one sub-chain side along each loop
      ch.groups = loops.map((loop, li) => {
        const key = h => h.sub * 2 + h.side, n = loop.length;
        let s0 = 0;
        for (let i = 0; i < n; i++) if (key(loop[i]) !== key(loop[(i - 1 + n) % n])) { s0 = i; break; }
        const gs = []; let cur = null;
        for (let q = 0; q < n; q++) {
          const h = loop[(s0 + q) % n];
          if (!cur || key(h) !== key(cur.he[0])) { cur = { sub: h.sub, side: h.side, he: [], w: [] }; gs.push(cur); }
          cur.he.push(h); cur.w.push(h.from);
        }
        for (const g2 of gs) g2.w.push(g2.he[g2.he.length - 1].to);
        gs.forEach((g2, gi) => { if (g2.sub >= 0 && g2.side >= 0) subs[g2.sub].side[g2.side] = { chart: ch.id, loop: li, group: gi }; });
        return gs;
      });
    }
    // order pieces by size, names T1, T2, ...
    const order = charts.map(c => c.id).sort((a, b) => charts[b].area3 - charts[a].area3);
    order.forEach((c, i) => { charts[c].num = i + 1; });
    return { P, G, W, wv: Int32Array.from(wv), nW: wv.length, chartOf, charts, chains, subs, seamE, edgeSub };
  }

  /* ---------- flattening: LSCM (conformal start) -> ARAP (length preserving) ---------- */
  function cg(apply, x, b, diag, free, maxIt, tol) {
    const n = x.length, r = new Float64Array(n), z = new Float64Array(n), p = new Float64Array(n), Ap = new Float64Array(n);
    apply(x, Ap);
    let rr0 = 0;
    for (let i = 0; i < n; i++) { r[i] = free[i] ? (b ? b[i] : 0) - Ap[i] : 0; rr0 += r[i] * r[i]; }
    if (rr0 < 1e-30) return 0;
    let rz = 0;
    for (let i = 0; i < n; i++) { z[i] = r[i] / diag[i]; p[i] = z[i]; rz += r[i] * z[i]; }
    let it = 0;
    for (; it < maxIt; it++) {
      apply(p, Ap);
      let pAp = 0; for (let i = 0; i < n; i++) { if (!free[i]) Ap[i] = 0; pAp += p[i] * Ap[i]; }
      if (Math.abs(pAp) < 1e-300) break;
      const al = rz / pAp; let rr = 0;
      for (let i = 0; i < n; i++) { x[i] += al * p[i]; r[i] -= al * Ap[i]; rr += r[i] * r[i]; }
      if (rr < tol * tol * rr0) break;
      let rz2 = 0; for (let i = 0; i < n; i++) { z[i] = r[i] / diag[i]; rz2 += r[i] * z[i]; }
      const be = rz2 / rz; rz = rz2;
      for (let i = 0; i < n; i++) p[i] = z[i] + be * p[i];
    }
    return it;
  }

  function flatten(A, ch, opts) {
    opts = opts || {};
    const { G, W, wv } = A, P = A.P, tris = ch.tris, nt = tris.length;
    const lw = new Map(), wl = [], lt = new Int32Array(3 * nt);
    for (let i = 0; i < nt; i++) for (let k = 0; k < 3; k++) {
      const w = W[3 * tris[i] + k]; let j = lw.get(w);
      if (j === undefined) { j = wl.length; lw.set(w, j); wl.push(w); }
      lt[3 * i + k] = j;
    }
    const n = wl.length, X = new Float64Array(3 * n);
    for (let j = 0; j < n; j++) { const v = 3 * wv[wl[j]]; X[3 * j] = P[v]; X[3 * j + 1] = P[v + 1]; X[3 * j + 2] = P[v + 2]; }
    const loc = new Float64Array(3 * nt), cot = new Float64Array(3 * nt), ar = new Float64Array(nt);
    let A3 = 0;
    for (let i = 0; i < nt; i++) { const t = tris[i]; for (let k = 0; k < 3; k++) { loc[3 * i + k] = G.loc[3 * t + k]; cot[3 * i + k] = G.cot[3 * t + k]; } ar[i] = G.FA[t]; A3 += ar[i]; }

    // pins: two far apart boundary vertices
    const bv = []; for (const loop of ch.loops) for (const h of loop) bv.push(lw.get(h.from));
    const far = a => { let b = a, d = -1; for (const j of bv) { const q = sq(X[3 * j] - X[3 * a]) + sq(X[3 * j + 1] - X[3 * a + 1]) + sq(X[3 * j + 2] - X[3 * a + 2]); if (q > d) { d = q; b = j; } } return b; };
    const pB = far(bv[0]), pA = far(pB);

    // start: projection onto the best-fit plane, oriented so the outside faces the viewer
    let cx = 0, cy = 0, cz = 0;
    for (let j = 0; j < n; j++) { cx += X[3 * j]; cy += X[3 * j + 1]; cz += X[3 * j + 2]; }
    cx /= n; cy /= n; cz /= n;
    const C = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    for (let j = 0; j < n; j++) { const d = [X[3 * j] - cx, X[3 * j + 1] - cy, X[3 * j + 2] - cz]; for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) C[3 * a + b] += d[a] * d[b]; }
    const pow = (skip) => {
      let v = [0.57, 0.61, 0.55];
      for (let it = 0; it < 60; it++) {
        if (skip) { const d = v[0] * skip[0] + v[1] * skip[1] + v[2] * skip[2]; v = [v[0] - d * skip[0], v[1] - d * skip[1], v[2] - d * skip[2]]; }
        const w = [C[0] * v[0] + C[1] * v[1] + C[2] * v[2], C[3] * v[0] + C[4] * v[1] + C[5] * v[2], C[6] * v[0] + C[7] * v[1] + C[8] * v[2]];
        const l = Math.hypot(w[0], w[1], w[2]) || 1; v = [w[0] / l, w[1] / l, w[2] / l];
      }
      if (skip) { const d = v[0] * skip[0] + v[1] * skip[1] + v[2] * skip[2]; v = [v[0] - d * skip[0], v[1] - d * skip[1], v[2] - d * skip[2]]; const l = Math.hypot(v[0], v[1], v[2]) || 1; v = [v[0] / l, v[1] / l, v[2] / l]; }
      return v;
    };
    const ax1 = pow(null); let ax2 = pow(ax1);
    if (Math.abs(ax2[0] * ax1[0] + ax2[1] * ax1[1] + ax2[2] * ax1[2]) > 0.5 || !isFinite(ax2[0])) ax2 = Math.abs(ax1[0]) < 0.9 ? [0, -ax1[2], ax1[1]] : [-ax1[1], ax1[0], 0];
    let nx = 0, ny = 0, nz = 0;
    for (const t of tris) { nx += G.FN[3 * t] * G.FA[t]; ny += G.FN[3 * t + 1] * G.FA[t]; nz += G.FN[3 * t + 2] * G.FA[t]; }
    const c3 = [ax1[1] * ax2[2] - ax1[2] * ax2[1], ax1[2] * ax2[0] - ax1[0] * ax2[2], ax1[0] * ax2[1] - ax1[1] * ax2[0]];
    if (c3[0] * nx + c3[1] * ny + c3[2] * nz < 0) ax2 = [-ax2[0], -ax2[1], -ax2[2]];
    const uv = new Float64Array(2 * n);
    for (let j = 0; j < n; j++) {
      const d = [X[3 * j] - cx, X[3 * j + 1] - cy, X[3 * j + 2] - cz];
      uv[2 * j] = d[0] * ax1[0] + d[1] * ax1[1] + d[2] * ax1[2];
      uv[2 * j + 1] = d[0] * ax2[0] + d[1] * ax2[1] + d[2] * ax2[2];
    }
    {   // move pins to (0,0) and (d,0)
      const ox = uv[2 * pA], oy = uv[2 * pA + 1], dx = uv[2 * pB] - ox, dy = uv[2 * pB + 1] - oy, an = -Math.atan2(dy, dx), c = Math.cos(an), s = Math.sin(an);
      for (let j = 0; j < n; j++) { const x = uv[2 * j] - ox, y = uv[2 * j + 1] - oy; uv[2 * j] = c * x - s * y; uv[2 * j + 1] = s * x + c * y; }
      uv[2 * pA + 1] = 0; uv[2 * pB + 1] = 0; uv[2 * pA] = 0;
    }

    // LSCM (Lévy et al.): minimise | sum_j W_j (u_j + i v_j) |^2 per triangle
    const Wc = new Float64Array(6 * nt);
    for (let i = 0; i < nt; i++) {
      const x1 = loc[3 * i], x2 = loc[3 * i + 1], y2 = loc[3 * i + 2], s = 1 / Math.sqrt(2 * ar[i] + 1e-30);
      const xs = [0, x1, x2], ys = [0, 0, y2];
      for (let k = 0; k < 3; k++) { const a = (k + 1) % 3, b = (k + 2) % 3; Wc[6 * i + 2 * k] = (xs[b] - xs[a]) * s; Wc[6 * i + 2 * k + 1] = (ys[b] - ys[a]) * s; }
    }
    const free = new Uint8Array(2 * n).fill(1); free[2 * pA] = free[2 * pA + 1] = free[2 * pB] = free[2 * pB + 1] = 0;
    const dg = new Float64Array(2 * n).fill(1e-12);
    for (let i = 0; i < nt; i++) for (let k = 0; k < 3; k++) { const j = lt[3 * i + k], q = sq(Wc[6 * i + 2 * k]) + sq(Wc[6 * i + 2 * k + 1]); dg[2 * j] += q; dg[2 * j + 1] += q; }
    const lscm = (x, out) => {
      out.fill(0);
      for (let i = 0; i < nt; i++) {
        let R = 0, I = 0;
        for (let k = 0; k < 3; k++) { const j = lt[3 * i + k], wr = Wc[6 * i + 2 * k], wi = Wc[6 * i + 2 * k + 1]; R += wr * x[2 * j] - wi * x[2 * j + 1]; I += wi * x[2 * j] + wr * x[2 * j + 1]; }
        for (let k = 0; k < 3; k++) { const j = lt[3 * i + k], wr = Wc[6 * i + 2 * k], wi = Wc[6 * i + 2 * k + 1]; out[2 * j] += wr * R + wi * I; out[2 * j + 1] += -wi * R + wr * I; }
      }
    };
    const keep = uv.slice();
    cg(lscm, uv, null, dg, free, opts.lscmIt || 2500, 1e-7);
    let ok = true; for (let i = 0; i < 2 * n; i++) if (!isFinite(uv[i])) { ok = false; break; }
    if (!ok) uv.set(keep);

    const signedArea = () => { let s = 0; for (let i = 0; i < nt; i++) { const a = lt[3 * i], b = lt[3 * i + 1], c = lt[3 * i + 2]; s += (uv[2 * b] - uv[2 * a]) * (uv[2 * c + 1] - uv[2 * a + 1]) - (uv[2 * c] - uv[2 * a]) * (uv[2 * b + 1] - uv[2 * a + 1]); } return s / 2; };
    let A2 = signedArea();
    if (A2 < 0) { for (let j = 0; j < n; j++) uv[2 * j] = -uv[2 * j]; A2 = -A2; }
    const sc = Math.sqrt(A3 / Math.max(A2, 1e-30));
    for (let i = 0; i < 2 * n; i++) uv[i] *= sc;

    // ARAP (Liu et al. 2008): local best rotation per triangle, global cotangent-Laplacian solve
    const cw = new Float64Array(3 * nt);
    for (let i = 0; i < 3 * nt; i++) cw[i] = Math.min(20, Math.max(0.02, cot[i]));
    const em = new Map(), EA = [], EB = [], EW = [];
    for (let i = 0; i < nt; i++) for (let k = 0; k < 3; k++) {
      const a = lt[3 * i + (k + 1) % 3], b = lt[3 * i + (k + 2) % 3], key = a < b ? a * n + b : b * n + a;
      let e = em.get(key); if (e === undefined) { e = EA.length; em.set(key, e); EA.push(a); EB.push(b); EW.push(0); }
      EW[e] += cw[3 * i + k];
    }
    // seam-length term: boundary edges keep their 3D length (both sides of a seam then match), the inside absorbs the rest
    const bw = opts.seamW === undefined ? 60 : opts.seamW, BA = [], BB = [], BL = [];
    if (bw > 0) {
      let mw = 0; for (const w of EW) mw += w; mw /= Math.max(1, EW.length);
      for (const loop of ch.loops) for (const h of loop) {
        const a = lw.get(h.from), b = lw.get(h.to);
        BA.push(a); BB.push(b); BL.push(Math.hypot(X[3 * a] - X[3 * b], X[3 * a + 1] - X[3 * b + 1], X[3 * a + 2] - X[3 * b + 2]));
        const key = a < b ? a * n + b : b * n + a; let e = em.get(key);
        if (e === undefined) { e = EA.length; em.set(key, e); EA.push(a); EB.push(b); EW.push(0); }
        EW[e] += bw * mw;
      }
      var bwv = bw * mw;
    }
    const nEl = EA.length, Ld = new Float64Array(2 * n).fill(1e-12);
    for (let e = 0; e < nEl; e++) { Ld[2 * EA[e]] += EW[e]; Ld[2 * EA[e] + 1] += EW[e]; Ld[2 * EB[e]] += EW[e]; Ld[2 * EB[e] + 1] += EW[e]; }
    const lap = (x, out) => {
      out.fill(0);
      for (let e = 0; e < nEl; e++) {
        const a = EA[e], b = EB[e], w = EW[e], du = w * (x[2 * a] - x[2 * b]), dv = w * (x[2 * a + 1] - x[2 * b + 1]);
        out[2 * a] += du; out[2 * a + 1] += dv; out[2 * b] -= du; out[2 * b + 1] -= dv;
      }
    };
    const fr2 = new Uint8Array(2 * n).fill(1); fr2[0] = fr2[1] = 0;
    const rhs = new Float64Array(2 * n), pts = [0, 0, 0, 0, 0, 0];
    const iters = opts.arapIt || 24;
    for (let it = 0; it < iters; it++) {
      rhs.fill(0);
      for (let i = 0; i < nt; i++) {
        pts[2] = loc[3 * i]; pts[4] = loc[3 * i + 1]; pts[5] = loc[3 * i + 2];
        let s00 = 0, s01 = 0, s10 = 0, s11 = 0;
        for (let k = 0; k < 3; k++) {
          const ia = (k + 1) % 3, ib = (k + 2) % 3, a = lt[3 * i + ia], b = lt[3 * i + ib], w = cw[3 * i + k];
          const ux = uv[2 * a] - uv[2 * b], uy = uv[2 * a + 1] - uv[2 * b + 1], xx = pts[2 * ia] - pts[2 * ib], xy = pts[2 * ia + 1] - pts[2 * ib + 1];
          s00 += w * ux * xx; s01 += w * ux * xy; s10 += w * uy * xx; s11 += w * uy * xy;
        }
        const th = Math.atan2(s10 - s01, s00 + s11), c = Math.cos(th), s = Math.sin(th);
        for (let k = 0; k < 3; k++) {
          const ia = (k + 1) % 3, ib = (k + 2) % 3, a = lt[3 * i + ia], b = lt[3 * i + ib], w = cw[3 * i + k];
          const xx = pts[2 * ia] - pts[2 * ib], xy = pts[2 * ia + 1] - pts[2 * ib + 1], dx = w * (c * xx - s * xy), dy = w * (s * xx + c * xy);
          rhs[2 * a] += dx; rhs[2 * a + 1] += dy; rhs[2 * b] -= dx; rhs[2 * b + 1] -= dy;
        }
      }
      for (let q = 0; q < BA.length; q++) {
        const a = BA[q], b = BB[q], dx = uv[2 * a] - uv[2 * b], dy = uv[2 * a + 1] - uv[2 * b + 1], l = Math.hypot(dx, dy) || 1e-12, k = bwv * BL[q] / l;
        rhs[2 * a] += k * dx; rhs[2 * a + 1] += k * dy; rhs[2 * b] -= k * dx; rhs[2 * b + 1] -= k * dy;
      }
      cg(lap, uv, rhs, Ld, fr2, 90, 1e-6);
    }

    // quality: singular values of the 3D -> 2D map per triangle (1 = exact length)
    const sig = new Float32Array(2 * nt); let flips = 0;
    for (let i = 0; i < nt; i++) {
      const x1 = loc[3 * i], x2 = loc[3 * i + 1], y2 = loc[3 * i + 2], a0 = lt[3 * i], a1 = lt[3 * i + 1], a2 = lt[3 * i + 2];
      const du1 = uv[2 * a1] - uv[2 * a0], dv1 = uv[2 * a1 + 1] - uv[2 * a0 + 1], du2 = uv[2 * a2] - uv[2 * a0], dv2 = uv[2 * a2 + 1] - uv[2 * a0 + 1], D = x1 * y2;
      const a = du1 / x1, b = (du2 * x1 - du1 * x2) / D, c = dv1 / x1, d = (dv2 * x1 - dv1 * x2) / D;
      const TT = a * a + b * b + c * c + d * d, det = a * d - b * c, s1 = Math.sqrt((TT + Math.sqrt(Math.max(0, TT * TT - 4 * det * det))) / 2);
      sig[2 * i] = s1; sig[2 * i + 1] = s1 > 1e-12 ? det / s1 : 0;
      if (det <= 0) flips++;
    }
    // area-weighted 98th percentile of the deviation
    const dv = []; let mean = 0;
    for (let i = 0; i < nt; i++) { const s1 = sig[2 * i], s2 = sig[2 * i + 1], d = s1 - 1 > 1 - s2 ? s1 - 1 : s2 - 1; dv.push([Math.abs(d), d, ar[i]]); mean += Math.abs(d) * ar[i]; }
    dv.sort((a, b) => a[0] - b[0]);
    let acc = 0, p98 = 0, p98s = 0;
    for (const q of dv) { acc += q[2]; if (acc >= 0.98 * A3) { p98 = q[0]; p98s = q[1]; break; } }

    // boundary self-overlap
    const segs = [];
    for (const loop of ch.loops) for (const h of loop) segs.push([lw.get(h.from), lw.get(h.to)]);
    let overl = 0;
    {
      let L = 0; for (const [a, b] of segs) L += Math.hypot(uv[2 * a] - uv[2 * b], uv[2 * a + 1] - uv[2 * b + 1]);
      const cs = Math.max(1e-9, 2 * L / Math.max(1, segs.length)), gm = new Map();
      const kk = (x, y) => x * 73856093 ^ y * 19349663;
      segs.forEach(([a, b], i) => {
        const x0 = Math.floor(Math.min(uv[2 * a], uv[2 * b]) / cs), x1 = Math.floor(Math.max(uv[2 * a], uv[2 * b]) / cs);
        const y0 = Math.floor(Math.min(uv[2 * a + 1], uv[2 * b + 1]) / cs), y1 = Math.floor(Math.max(uv[2 * a + 1], uv[2 * b + 1]) / cs);
        for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) { const k = kk(x, y); let l = gm.get(k); if (!l) gm.set(k, l = []); l.push(i); }
      });
      const o = (p, q, r) => (uv[2 * q] - uv[2 * p]) * (uv[2 * r + 1] - uv[2 * p + 1]) - (uv[2 * q + 1] - uv[2 * p + 1]) * (uv[2 * r] - uv[2 * p]);
      const seen = new Set();
      for (const l of gm.values()) for (let i = 0; i < l.length; i++) for (let j = i + 1; j < l.length; j++) {
        const A = segs[l[i]], B = segs[l[j]];
        if (A[0] === B[0] || A[0] === B[1] || A[1] === B[0] || A[1] === B[1]) continue;
        const key = l[i] * 1e6 + l[j]; if (seen.has(key)) continue; seen.add(key);
        if ((o(A[0], A[1], B[0]) > 0) !== (o(A[0], A[1], B[1]) > 0) && (o(B[0], B[1], A[0]) > 0) !== (o(B[0], B[1], A[1]) > 0)) overl++;
      }
    }

    // turn the piece so its long axis is vertical (default grain line)
    {
      let mx = 0, my = 0; for (let j = 0; j < n; j++) { mx += uv[2 * j]; my += uv[2 * j + 1]; } mx /= n; my /= n;
      let sxx = 0, sxy = 0, syy = 0;
      for (let j = 0; j < n; j++) { const x = uv[2 * j] - mx, y = uv[2 * j + 1] - my; sxx += x * x; sxy += x * y; syy += y * y; }
      const th = 0.5 * Math.atan2(2 * sxy, sxx - syy), an = Math.PI / 2 - th, c = Math.cos(an), s = Math.sin(an);
      for (let j = 0; j < n; j++) { const x = uv[2 * j] - mx, y = uv[2 * j + 1] - my; uv[2 * j] = c * x - s * y; uv[2 * j + 1] = s * x + c * y; }
    }
    return { key: ch.key, n, lt, uv, sig, flips, overl, dev: p98, devSigned: p98s, mean: mean / A3, area3: A3 };
  }

  /* ---------- 2D helpers ---------- */
  function rdp(pts, tol, closed) {
    if (pts.length < 3) return pts.slice();
    const keep = new Uint8Array(pts.length); keep[0] = keep[pts.length - 1] = 1;
    const st = [[0, pts.length - 1]];
    while (st.length) {
      const [a, b] = st.pop(); let md = -1, mi = -1;
      const ax = pts[a][0], ay = pts[a][1], dx = pts[b][0] - ax, dy = pts[b][1] - ay, L2 = dx * dx + dy * dy || 1e-30;
      for (let i = a + 1; i < b; i++) {
        let t = ((pts[i][0] - ax) * dx + (pts[i][1] - ay) * dy) / L2; t = Math.max(0, Math.min(1, t));
        const d = Math.hypot(ax + t * dx - pts[i][0], ay + t * dy - pts[i][1]);
        if (d > md) { md = d; mi = i; }
      }
      if (md > tol) { keep[mi] = 1; st.push([a, mi], [mi, b]); }
    }
    return pts.filter((_, i) => keep[i]);
  }
  const plen = pts => { let L = 0; for (let i = 1; i < pts.length; i++) L += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); return L; };
  function at(pts, s) {   // point + tangent at arc length s
    let acc = 0;
    for (let i = 1; i < pts.length; i++) {
      const d = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
      if (acc + d >= s || i === pts.length - 1) {
        const u = d > 0 ? Math.max(0, Math.min(1, (s - acc) / d)) : 0, tx = (pts[i][0] - pts[i - 1][0]) / (d || 1), ty = (pts[i][1] - pts[i - 1][1]) / (d || 1);
        return [pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * u, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * u, tx, ty];
      }
      acc += d;
    }
    return [pts[0][0], pts[0][1], 1, 0];
  }
  const parea = p => { let a = 0; for (let i = 0; i < p.length; i++) { const q = p[(i + 1) % p.length]; a += p[i][0] * q[1] - q[0] * p[i][1]; } return a / 2; };
  // offset a closed loop to the right of its direction (= outside of the piece)
  function offset(pts, d) {
    if (d <= 0) return pts.slice();
    const n = pts.length, out = [];
    for (let i = 0; i < n; i++) {
      const p = pts[(i - 1 + n) % n], c = pts[i], q = pts[(i + 1) % n];
      let ax = c[0] - p[0], ay = c[1] - p[1], bx = q[0] - c[0], by = q[1] - c[1];
      const la = Math.hypot(ax, ay) || 1, lb = Math.hypot(bx, by) || 1; ax /= la; ay /= la; bx /= lb; by /= lb;
      const n1 = [ay, -ax], n2 = [by, -bx], mx = n1[0] + n2[0], my = n1[1] + n2[1], ml = Math.hypot(mx, my);
      const cosH = ml / 2, convex = ax * by - ay * bx < 0;
      if (ml < 1e-6 || (convex && cosH < 0.6)) { out.push([c[0] + n1[0] * d, c[1] + n1[1] * d], [c[0] + n2[0] * d, c[1] + n2[1] * d]); }
      else { const k = d / Math.max(cosH, 0.35); out.push([c[0] + mx / ml * k, c[1] + my / ml * k]); }
    }
    return out;
  }
  // single cubic bezier fit with fixed ends (Schneider)
  function fitBezier(pts) {
    const n = pts.length, P0 = pts[0], P3 = pts[n - 1];
    const chord = Math.hypot(P3[0] - P0[0], P3[1] - P0[1]);
    const L = plen(pts);
    if (n < 3 || L < 1e-9) return [P0, [P0[0] + (P3[0] - P0[0]) / 3, P0[1] + (P3[1] - P0[1]) / 3], [P3[0] - (P3[0] - P0[0]) / 3, P3[1] - (P3[1] - P0[1]) / 3], P3];
    const ta = at(pts, Math.min(L * 0.12, L)), tb = at(pts, L - Math.min(L * 0.12, L));
    let t1 = [ta[0] - P0[0], ta[1] - P0[1]], t2 = [tb[0] - P3[0], tb[1] - P3[1]];
    const l1 = Math.hypot(t1[0], t1[1]) || 1, l2 = Math.hypot(t2[0], t2[1]) || 1; t1 = [t1[0] / l1, t1[1] / l1]; t2 = [t2[0] / l2, t2[1] / l2];
    const u = [0]; for (let i = 1; i < n; i++) u.push(u[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
    let c00 = 0, c01 = 0, c11 = 0, x0 = 0, x1 = 0;
    for (let i = 0; i < n; i++) {
      const t = u[i] / L, s = 1 - t, b0 = s * s * s, b1 = 3 * s * s * t, b2 = 3 * s * t * t, b3 = t * t * t;
      const A1 = [t1[0] * b1, t1[1] * b1], A2 = [t2[0] * b2, t2[1] * b2];
      c00 += A1[0] * A1[0] + A1[1] * A1[1]; c01 += A1[0] * A2[0] + A1[1] * A2[1]; c11 += A2[0] * A2[0] + A2[1] * A2[1];
      const tx = pts[i][0] - (P0[0] * (b0 + b1) + P3[0] * (b2 + b3)), ty = pts[i][1] - (P0[1] * (b0 + b1) + P3[1] * (b2 + b3));
      x0 += tx * A1[0] + ty * A1[1]; x1 += tx * A2[0] + ty * A2[1];
    }
    const det = c00 * c11 - c01 * c01;
    let a1 = det ? (x0 * c11 - x1 * c01) / det : 0, a2 = det ? (c00 * x1 - c01 * x0) / det : 0;
    const eps = 1e-6 * chord;
    if (!(a1 > eps) || !(a2 > eps) || a1 > 2 * L || a2 > 2 * L) a1 = a2 = Math.max(chord, L * 0.5) / 3;
    return [P0, [P0[0] + t1[0] * a1, P0[1] + t1[1] * a1], [P3[0] + t2[0] * a2, P3[1] + t2[1] * a2], P3];
  }

  /* ---------- pattern layout (mm) ---------- */
  // o: {mmU, ease (%), allow (mm), notch (mm)}. Pattern space: x right, y up, seen from the outside.
  function layout(A, FR, o) {
    const s = o.mmU * (1 + o.ease / 100), pieces = [];
    A.charts.forEach((ch, ci) => {
      const r = FR[ci]; if (!r || ch.status !== 'ok') return;
      const lw = new Map();
      ch.tris.forEach((t, i) => { for (let k = 0; k < 3; k++) lw.set(A.W[3 * t + k], r.lt[3 * i + k]); });
      const pt = w => { const j = lw.get(w); return [r.uv[2 * j] * s, r.uv[2 * j + 1] * s]; };
      const loops = ch.loops.map(lp => lp.map(h => pt(h.from)));
      let oi = 0, ba = -1;
      loops.forEach((l, i) => { const a = Math.abs(parea(l)); if (a > ba) { ba = a; oi = i; } });
      const order = [oi, ...loops.map((_, i) => i).filter(i => i !== oi)];      // c=0 outer, then holes
      const groups = ch.groups.map(gs => gs.map(g => ({ sub: g.sub, side: g.side, pts: g.w.map(pt) })));
      pieces.push({ ci, num: ch.num, name: 'T' + ch.num, r, lw, pt, s, loops, order, groups,
        stitch: order.map(i => rdp(loops[i].concat([loops[i][0]]), 0.15).slice(0, -1)) });
    });
    pieces.sort((a, b) => a.num - b.num);
    // cut line (seam allowance), label point, bbox
    for (const p of pieces) {
      p.cut = p.stitch.map(l => o.allow > 0 ? offset(l, o.allow) : l);
      let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
      for (const l of p.cut) for (const q of l) { x0 = Math.min(x0, q[0]); x1 = Math.max(x1, q[0]); y0 = Math.min(y0, q[1]); y1 = Math.max(y1, q[1]); }
      p.bb = [x0, y0, x1, y1];
      // label: triangle centroid closest to the area centroid
      let ax = 0, ay = 0, aa = 0; const T = p.r.lt, uv = p.r.uv;
      for (let i = 0; i < T.length / 3; i++) {
        const a = T[3 * i], b = T[3 * i + 1], c = T[3 * i + 2], w = Math.abs((uv[2 * b] - uv[2 * a]) * (uv[2 * c + 1] - uv[2 * a + 1]) - (uv[2 * c] - uv[2 * a]) * (uv[2 * b + 1] - uv[2 * a + 1]));
        ax += (uv[2 * a] + uv[2 * b] + uv[2 * c]) / 3 * w; ay += (uv[2 * a + 1] + uv[2 * b + 1] + uv[2 * c + 1]) / 3 * w; aa += w;
      }
      ax /= aa || 1; ay /= aa || 1; let best = [ax * p.s, ay * p.s], bd = 1e18;
      for (let i = 0; i < T.length / 3; i++) {
        const a = T[3 * i], b = T[3 * i + 1], c = T[3 * i + 2], cx = (uv[2 * a] + uv[2 * b] + uv[2 * c]) / 3, cy = (uv[2 * a + 1] + uv[2 * b + 1] + uv[2 * c + 1]) / 3, d = sq(cx - ax) + sq(cy - ay);
        if (d < bd) { bd = d; best = [cx * p.s, cy * p.s]; }
      }
      p.label = best;
    }
    // chain sides (seam numbers, notches, length check) in chain order
    const byChart = new Map(pieces.map(p => [p.ci, p]));
    const seams = [];
    A.chains.forEach((chn, k) => {
      const sides = [0, 1].map(sd => {
        let pts = [], piece = null;
        for (const si of chn.subs) {
          const ref = A.subs[si].side[sd]; if (!ref) return null;
          const p = byChart.get(ref.chart); if (!p) return null;
          piece = p;
          let g = p.groups[ref.loop][ref.group].pts; if (sd === 1) g = g.slice().reverse();
          pts = pts.length ? pts.concat(g.slice(1)) : g.slice();
        }
        if (!piece || pts.length < 2) return null;
        // loop direction = chain order for side 0, reversed for side 1; outside = right of loop direction
        return { piece, pts, len: plen(pts), out: sd === 0 ? 1 : -1 };
      });
      const sm = { id: k, num: k + 1, sides, len3: chn.len3 * o.mmU };
      if (sides[0] && sides[1]) {
        sm.diff = Math.abs(sides[0].len - sides[1].len) / Math.max(1e-9, Math.min(sides[0].len, sides[1].len));
        const L = (sides[0].len + sides[1].len) / 2, nN = o.notch > 0 ? Math.floor(L / o.notch - 0.35) : 0;
        for (const sd of sides) {
          sd.notches = [];
          for (let i = 1; i <= nN; i++) { const q = at(sd.pts, sd.len * i * o.notch / L); sd.notches.push([q[0], q[1], q[3] * sd.out, -q[2] * sd.out]); }
          const m = at(sd.pts, sd.len / 2); sd.mid = [m[0], m[1], m[3] * sd.out, -m[2] * sd.out];
        }
      }
      seams.push(sm);
    });
    // shelf packing (screen space: y down), gap keeps the cut lines apart
    const gap = 12;
    let total = 0, maxW = 0; for (const p of pieces) { const w = p.bb[2] - p.bb[0], h = p.bb[3] - p.bb[1]; total += (w + gap) * (h + gap); maxW = Math.max(maxW, w); }
    const rowW = Math.max(maxW, Math.sqrt(total) * 1.5);
    const order = pieces.slice().sort((a, b) => (b.bb[3] - b.bb[1]) - (a.bb[3] - a.bb[1]));
    let x = 0, y = 0, rh = 0, W = 0, H = 0;
    for (const p of order) {
      const w = p.bb[2] - p.bb[0], h = p.bb[3] - p.bb[1];
      if (x > 0 && x + w > rowW) { x = 0; y += rh + gap; rh = 0; }
      p.ox = x - p.bb[0]; p.oy = y + p.bb[3];        // screen = (px + ox, oy - py)
      x += w + gap; rh = Math.max(rh, h); W = Math.max(W, x - gap); H = Math.max(H, y + h);
    }
    for (const p of pieces) p.S = q => [q[0] + p.ox, p.oy - q[1]];
    return { pieces, seams, W, H, s };
  }

  /* ---------- INFLATE project export ---------- */
  function inflate(A, LY, mmU, pastel) {
    const panels = [], seamsOut = [], byChart = new Map();
    const quat = (Q, Pp) => {          // Horn: rotation that maps local 2D frame (z = outside) onto the 3D piece
      const n = Q.length; let qc = [0, 0, 0], pc = [0, 0, 0];
      for (let i = 0; i < n; i++) for (let a = 0; a < 3; a++) { qc[a] += Q[i][a] / n; pc[a] += Pp[i][a] / n; }
      const S = [0, 0, 0, 0, 0, 0, 0, 0, 0];
      for (let i = 0; i < n; i++) for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) S[3 * a + b] += (Q[i][a] - qc[a]) * (Pp[i][b] - pc[b]);
      const [xx, xy, xz, yx, yy, yz, zx, zy, zz] = S;
      const N = [[xx + yy + zz, yz - zy, zx - xz, xy - yx], [yz - zy, xx - yy - zz, xy + yx, zx + xz], [zx - xz, xy + yx, -xx + yy - zz, yz + zy], [xy - yx, zx + xz, yz + zy, -xx - yy + zz]];
      let sh = 0; for (const r of N) for (const v of r) sh += Math.abs(v);
      let v = [1, 0.1, 0.1, 0.1];
      for (let it = 0; it < 300; it++) {
        const w = [0, 1, 2, 3].map(i => N[i][0] * v[0] + N[i][1] * v[1] + N[i][2] * v[2] + N[i][3] * v[3] + sh * v[i]);
        const l = Math.hypot(...w) || 1; v = w.map(x => x / l);
      }
      const q = [v[1], v[2], v[3], v[0]];          // [x,y,z,w]
      const rot = p => { const tx = 2 * (q[1] * p[2] - q[2] * p[1]), ty = 2 * (q[2] * p[0] - q[0] * p[2]), tz = 2 * (q[0] * p[1] - q[1] * p[0]); return [p[0] + q[3] * tx + (q[1] * tz - q[2] * ty), p[1] + q[3] * ty + (q[2] * tx - q[0] * tz), p[2] + q[3] * tz + (q[0] * ty - q[1] * tx)]; };
      const rq = rot(qc);
      return { q, pos: [pc[0] - rq[0], pc[1] - rq[1], pc[2] - rq[2]], rot };
    };
    LY.pieces.forEach((p, pi) => {
      const id = pi + 1; byChart.set(p.ci, { id, p });
      const curves = p.order.map(li => {
        const gs = p.groups[li], nodes = gs.map(g => { const q = p.S(g.pts[0]); return { x: q[0], y: q[1], hi: { x: 0, y: 0 }, ho: { x: 0, y: 0 }, type: 'smooth' }; });
        gs.forEach((g, gi) => {
          const bz = fitBezier(rdp(g.pts.map(p.S), 0.1)), a = nodes[gi], b = nodes[(gi + 1) % nodes.length];
          a.ho = { x: bz[1][0] - a.x, y: bz[1][1] - a.y }; b.hi = { x: bz[2][0] - b.x, y: bz[2][1] - b.y };
        });
        for (const nd of nodes) {
          const l1 = Math.hypot(nd.hi.x, nd.hi.y), l2 = Math.hypot(nd.ho.x, nd.ho.y);
          nd.type = l1 > 1e-6 && l2 > 1e-6 && (nd.hi.x * nd.ho.x + nd.hi.y * nd.ho.y) / (l1 * l2) < -0.97 ? 'smooth' : 'corner';
        }
        return nodes;
      });
      // start pose: best fit of the flat piece onto its place on the 3D form, pushed a little outwards
      let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
      for (const nd of curves[0]) { x0 = Math.min(x0, nd.x); x1 = Math.max(x1, nd.x); y0 = Math.min(y0, nd.y); y1 = Math.max(y1, nd.y); }
      const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, Q = [], Pp = [];
      for (const [w, j] of p.lw) {
        const sp = p.S([p.r.uv[2 * j] * p.s, p.r.uv[2 * j + 1] * p.s]), v = 3 * A.wv[w];
        Q.push([sp[0] - cx, -(sp[1] - cy), 0]); Pp.push([A.P[v] * mmU, A.P[v + 1] * mmU, A.P[v + 2] * mmU]);
      }
      const R = quat(Q, Pp), nn = R.rot([0, 0, 1]), push = 0.12 * Math.max(x1 - x0, y1 - y0);
      panels.push({ id, name: 'Teil ' + id + ' (' + p.name + ')', col: pastel(id), nodes: curves[0], inner: curves.slice(1).map(c => ({ nodes: c, closed: true })),
        pos: R.pos.map((v, i) => v + nn[i] * push), rot: R.q });
    });
    for (const sb of A.subs) {
      const r0 = sb.side[0], r1 = sb.side[1]; if (!r0 || !r1) continue;
      const a = byChart.get(r0.chart), b = byChart.get(r1.chart); if (!a || !b) continue;
      const c0 = a.p.order.indexOf(r0.loop), c1 = b.p.order.indexOf(r1.loop);
      seamsOut.push({ a: { p: a.id, c: c0, e: r0.group }, b: { p: b.id, c: c1, e: r1.group }, flip: false });
    }
    return { format: 'inflate-project', version: '2.0', saved: new Date().toISOString(), source: 'BLOB:CUTTER', panels, seams: seamsOut, nextId: panels.length + 1 };
  }

  /* ---------- SVG (1:1 mm) ---------- */
  function svg(LY, o) {
    const f = v => v.toFixed(2), m = 10, top = 14, W = LY.W + 2 * m, H = LY.H + 2 * m + top;
    const T = (p, q) => { const s = p.S(q); return [s[0] + m, s[1] + m + top]; };
    const path = (p, pts, closed) => pts.map((q, i) => (i ? 'L' : 'M') + T(p, q).map(f).join(' ')).join('') + (closed ? 'Z' : '');
    let cut = '', st = '', nt = '', tx = '';
    for (const p of LY.pieces) {
      cut += '    <path id="' + p.name + '" d="' + p.cut.map(l => path(p, l, true)).join('') + '"/>\n';
      if (o.allow > 0) st += '    <path d="' + p.stitch.map(l => path(p, l, true)).join('') + '"/>\n';
      const L = T(p, p.label), h = (p.bb[3] - p.bb[1]) * 0.28;
      tx += '    <text x="' + f(L[0]) + '" y="' + f(L[1] - 3) + '" font-size="8" text-anchor="middle">' + p.name + '</text>\n';
      tx += '    <path d="M' + f(L[0]) + ' ' + f(L[1] + 2) + 'v' + f(h) + 'M' + f(L[0] - 1.6) + ' ' + f(L[1] + 4.5) + 'l1.6 -2.5l1.6 2.5M' + f(L[0] - 1.6) + ' ' + f(L[1] + h - 0.5) + 'l1.6 2.5l1.6 -2.5" fill="none" stroke="#0070ff" stroke-width="0.3"/>\n';
    }
    for (const sm of LY.seams) for (const sd of sm.sides) {
      if (!sd || !sd.mid || sd.len < 25) continue;
      const p = sd.piece, nl = o.allow > 0 ? o.allow : -4;
      for (const q of sd.notches) { const a = T(p, [q[0], q[1]]), b = T(p, [q[0] + q[2] * nl, q[1] + q[3] * nl]); nt += 'M' + f(a[0]) + ' ' + f(a[1]) + 'L' + f(b[0]) + ' ' + f(b[1]); }
      const c = T(p, [sd.mid[0] - sd.mid[2] * 5, sd.mid[1] - sd.mid[3] * 5]);
      tx += '    <text x="' + f(c[0]) + '" y="' + f(c[1] + 1.4) + '" font-size="4" text-anchor="middle">N' + sm.num + '</text>\n';
    }
    return '<?xml version="1.0" encoding="UTF-8"?>\n' +
      '<svg xmlns="http://www.w3.org/2000/svg" width="' + f(W) + 'mm" height="' + f(H) + 'mm" viewBox="0 0 ' + f(W) + ' ' + f(H) + '">\n' +
      '  <!-- BLOB:CUTTER. schnitt: Schnittlinie inkl. Nahtzugabe. naht: Nahtlinie. passmarken: gleiche Anzahl auf beiden Seiten einer Naht. Teile von aussen gesehen. -->\n' +
      '  <text x="' + m + '" y="' + (m + 2) + '" font-size="4" font-family="Helvetica, Arial, sans-serif" fill="#0070ff">BLOB:CUTTER · 1:1 mm · ' + LY.pieces.length + ' Teile · Nahtzugabe ' + o.allow + ' mm · Mehrweite ' + o.ease + ' % · Teile von aussen gesehen, je 1x zuschneiden</text>\n' +
      '  <g id="schnitt" fill="none" stroke="#000000" stroke-width="0.35">\n' + cut + '  </g>\n' +
      (st ? '  <g id="naht" fill="none" stroke="#0070ff" stroke-width="0.25" stroke-dasharray="2 1.5">\n' + st + '  </g>\n' : '') +
      (nt ? '  <path id="passmarken" fill="none" stroke="#000000" stroke-width="0.35" d="' + nt + '"/>\n' : '') +
      '  <g id="beschriftung" fill="#0070ff" font-family="Helvetica, Arial, sans-serif">\n' + tx + '  </g>\n</svg>\n';
  }

  return { weights, spread, section, curvature, svg, mesh, geom, relax, dijkstra, analyze, flatten, layout, inflate, rdp, plen, at, parea, offset, fitBezier };
})();
/*CORE-END*/

/* ============================================================
   CUT STAGE  (bake -> seams on the surface -> guide (curvature / strain / suggestions) -> RENDER CUTS -> SVG / INFLATE)
   SCULPT stays fully parametric. CUT polygonises the solid once at MESH RES, relaxes it onto the field,
   and the seams (control points stored in world space) are re-snapped after every sculpt change.
   Seam edits only re-analyse the pieces (fast); the flat pattern is computed on RENDER CUTS.
============================================================ */
const PASTEL = ['#ff6f9f', '#3fa9ff', '#ffbf2e', '#2fcf86', '#a173ff', '#ff8240', '#22c9c0', '#e55ff0', '#8fc93a', '#ff5757', '#5a82ff', '#d8a033'];
function pastel(i) {
  if (i >= 1 && i <= PASTEL.length) return PASTEL[i - 1];
  const h = (i * 137.508 + 200) % 360, s = 0.75, l = 0.64, k = n => (n + h / 30) % 12, a = s * Math.min(l, 1 - l);
  const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  return '#' + [f(0), f(8), f(4)].map(v => Math.round(v * 255).toString(16).padStart(2, '0')).join('');
}
const SEAMCOL = ['#2d7dff', '#18a058', '#f08c00', '#8a4dff', '#00a3a3', '#c2410c', '#4d7c0f', '#1d4ed8', '#b45309', '#0f766e', '#7c3aed', '#be123c'];
// materials: stretch limit (%) the fabric may take without visible strain, seam length fidelity
const MATS = { tarp: [1, 0.9], denim: [2, 0.85], thick: [3, 0.8], thin: [4, 0.75], knit: [10, 0.6], jersey: [20, 0.5] };
S.seams = [];
S.cut = { bias: 0.6, res: 36, size: 400, ease: 0, allow: 10, notch: 50, knot: 120, fid: 0.8, lim: 3, mat: 'thick' };
const CUT = { M: null, A: null, RA: null, cache: new Map(), FR: [], LY: null, gen: 0, tool: 'pen', sel: null, hover: -1, hoverV: -1,
  draw: null, drag: null, down: null, undo: [], view: 'parts', show2d: true, stale: true, busy: false, triDev: null, prop: [], propHover: -1, erase: null,
  obj: null, bakeId: 0, prevRaf: 0 };
const mmU = () => CUT.M ? S.cut.size / CUT.M.ext : 1;
const tol = () => S.cut.lim / 100;
const seamW = () => S.cut.fid <= 0 ? 0 : Math.round(Math.pow(400, S.cut.fid));
const patOpts = () => ({ mmU: mmU(), ease: S.cut.ease, allow: S.cut.allow, notch: S.cut.notch });

/* ---------- field + bake ---------- */
function fieldFn(cs, k) {
  const pos = cs.filter(c => !c.neg), neg = cs.filter(c => c.neg), m = k * (1 + 2 * roundW()) + 0.05;
  const out = (c, x, y, z) => x < c.x0 - m || x > c.x1 + m || y < c.y0 - m || y > c.y1 + m || z < c.z0 - m || z > c.z1 + m;
  return (x, y, z) => {
    let F = BIG;
    for (const c of pos) if (!out(c, x, y, z)) F = smin(F, blobDist(c, x, y, z), k);
    for (const c of neg) if (!out(c, x, y, z)) F = -smin(-F, blobDist(c, x, y, z), k);
    return F;
  };
}
function cutBake() {
  const cs = withRef(compile(S.blobs)), k = S.blend;
  const r = polygonize(cs, k, 1 / S.cut.res, 6e6, false);
  if (!r) throw new Error('nothing solid');
  const pa = r.geo.attributes.position.array, na = r.geo.attributes.normal.array, ia = r.geo.index.array;
  const remap = new Int32Array(pa.length / 3).fill(-1), tri = []; let nv = 0;
  for (let i = 0; i < ia.length; i += 3) { const a = ia[i], b = ia[i + 1], c = ia[i + 2]; if (a !== b && b !== c && a !== c) tri.push(a, b, c); }
  for (const v of tri) if (remap[v] < 0) remap[v] = nv++;
  const P = new Float64Array(nv * 3), Ng = new Float64Array(nv * 3);
  for (let i = 0; i < remap.length; i++) if (remap[i] >= 0) for (let q = 0; q < 3; q++) { P[remap[i] * 3 + q] = pa[i * 3 + q]; Ng[remap[i] * 3 + q] = na[i * 3 + q]; }
  const T = new Int32Array(tri.length); for (let i = 0; i < tri.length; i++) T[i] = remap[tri[i]];
  let agree = 0;                                       // winding must face outwards (= along the field gradient)
  for (let t = 0; t < T.length; t += 3) {
    const a = 3 * T[t], b = 3 * T[t + 1], c = 3 * T[t + 2];
    const ux = P[b] - P[a], uy = P[b + 1] - P[a + 1], uz = P[b + 2] - P[a + 2], vx = P[c] - P[a], vy = P[c + 1] - P[a + 1], vz = P[c + 2] - P[a + 2];
    const d = (uy * vz - uz * vy) * (Ng[a] + Ng[b] + Ng[c]) + (uz * vx - ux * vz) * (Ng[a + 1] + Ng[b + 1] + Ng[c + 1]) + (ux * vy - uy * vx) * (Ng[a + 2] + Ng[b + 2] + Ng[c + 2]);
    agree += d > 0 ? 1 : -1;
  }
  if (agree < 0) for (let t = 0; t < T.length; t += 3) { const x = T[t + 1]; T[t + 1] = T[t + 2]; T[t + 2] = x; }
  r.geo.dispose();
  const ff = fieldFn(cs, k), H = r.H, e = H * 0.2;
  const project = (x, y, z) => {
    for (let i = 0; i < 6; i++) {
      const f = ff(x, y, z); if (Math.abs(f) < H * 1e-3) break;
      const gx = (ff(x + e, y, z) - f) / e, gy = (ff(x, y + e, z) - f) / e, gz = (ff(x, y, z + e) - f) / e, g2 = gx * gx + gy * gy + gz * gz;
      if (g2 < 1e-12) break;
      let s = f / g2; const st = Math.abs(f) / Math.sqrt(g2); if (st > 4 * H) s *= 4 * H / st;
      x -= gx * s; y -= gy * s; z -= gz * s;
    }
    return [x, y, z];
  };
  const M0 = CC.mesh(P, T);
  CC.relax(M0, project, 3);
  const M = CC.mesh(M0.P, T);
  Object.assign(M, { project, rev: S.rev, res: S.cut.res, id: ++CUT.bakeId });
  M.K = CC.curvature(M, 6);
  CUT.M = M; CUT.dj = CC.dijkstra(M); CUT.cache.clear(); CUT.triDev = null; CUT.RA = null; CUT.LY = null; CUT.prop = [];
}

/* ---------- seams -> paths -> analysis ---------- */
function seamPath(sm) {
  const M = CUT.M;
  sm.vids = sm.pts.map(p => M.nearest(p[0], p[1], p[2]));
  const n = sm.vids.length, m = sm.closed ? n : n - 1; let path = []; sm.segStart = [];
  for (let i = 0; i < m; i++) {
    sm.segStart.push(Math.max(0, path.length - 1));
    const s = CUT.dj(sm.vids[i], sm.vids[(i + 1) % n], S.cut.bias) || [sm.vids[i]];
    path = path.length ? path.concat(s.slice(1)) : s;
  }
  sm.path = path.length ? path : [sm.vids[0]];
  return sm.path;
}
const vpos = v => [CUT.M.P[3 * v], CUT.M.P[3 * v + 1], CUT.M.P[3 * v + 2]];
function cutRun() {
  const M = CUT.M; if (!M) return;
  const t0 = performance.now();
  for (const sm of S.seams) seamPath(sm);
  const fixed = new Set(); for (const sm of S.seams) for (const v of sm.vids) fixed.add(v);
  CUT.A = CC.analyze(M, S.seams.map(s => s.path), S.cut.knot / mmU(), M.project, fixed, S.cut.bias);
  if (CUT.sel && CUT.sel.type === 'piece' && !CUT.A.charts[CUT.sel.c]) CUT.sel = null;
  if (CUT.sel && CUT.sel.type === 'seam' && !S.seams[CUT.sel.i]) CUT.sel = null;
  setStale(true);
  buildCutMesh(); updateSeamLines(); syncCutSel(); cutInfo(); draw2D();
  setStatus(`${CUT.A.charts.length} PIECES · ${Math.round(performance.now() - t0)} MS · RENDER CUTS FOR THE PATTERN`);
}
function setStale(v) {
  CUT.stale = v; $('btnCuts').classList.toggle('stale', v);
  $('btnCuts').title = v ? 'The seams changed — compute the flat pattern pieces' : 'Pattern is up to date';
}

/* ---------- RENDER CUTS: flatten every piece ---------- */
async function renderCuts() {
  if (!CUT.A || CUT.busy) return;
  CUT.busy = true; $('btnCuts').disabled = true;
  const gen = ++CUT.gen, A = CUT.A, w = seamW(), FR = new Array(A.charts.length).fill(null), used = new Set();
  const todo = A.charts.filter(c => c.status === 'ok'); let k = 0; const t0 = performance.now();
  try {
    for (const ch of todo) {
      const key = ch.key + '|' + w + '|' + CUT.M.id;
      let r = CUT.cache.get(key);
      if (!r) {
        $('cutsTxt').textContent = `RENDERING ${k + 1} / ${todo.length}`;
        await new Promise(res => setTimeout(res, 0));
        if (gen !== CUT.gen) return;
        try { r = CC.flatten(A, ch, { seamW: w }); } catch (err) { console.error(err); r = null; ch.status = 'broken'; }
        if (r) CUT.cache.set(key, r);
      }
      if (r) { used.add(key); FR[ch.id] = r; }
      k++;
    }
    if (gen !== CUT.gen) return;
    for (const key of [...CUT.cache.keys()]) if (!used.has(key)) CUT.cache.delete(key);
    CUT.RA = A; CUT.FR = FR;
    // strain per mesh triangle (signed: + loose / - tight), kept for the STRAIN view until the next render
    const td = new Float32Array(CUT.M.nT).fill(NaN);
    A.charts.forEach(ch => { const r = FR[ch.id]; if (r) ch.tris.forEach((t, i) => { const s1 = r.sig[2 * i], s2 = r.sig[2 * i + 1]; td[t] = s1 - 1 > 1 - s2 ? s1 - 1 : s2 - 1; }); });
    CUT.triDev = td; CUT.triDevId = CUT.M.id;
    setStale(false); CUT.patFitted = CUT.patFitted && CUT.LY && CUT.LY.pieces.length === todo.length;
    relayout(); recolor();
    setStatus(`${todo.length} PIECES RENDERED · ${Math.round(performance.now() - t0)} MS`);
  } finally {
    if (gen === CUT.gen) { CUT.busy = false; $('btnCuts').disabled = false; $('cutsTxt').textContent = 'RENDER CUTS'; }
  }
}
function relayout() {
  if (!CUT.RA) return;
  CUT.LY = CC.layout(CUT.RA, CUT.FR, patOpts());
  if (!CUT.patFitted && CUT.LY.pieces.length) patFit();
  syncCutSel(); cutInfo(); draw2D();
}
$('btnCuts').addEventListener('click', () => renderCuts());

/* ---------- 3D display ---------- */
const matCut = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.55, metalness: 0, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 });
const lineMat = new LineMaterial({ color: 0xffffff, linewidth: 2.4, vertexColors: true, worldUnits: false, transparent: true });
const overMat = new LineMaterial({ color: 0x4f6df5, linewidth: 4.5, worldUnits: false, depthTest: false, transparent: true, opacity: 0.9 });
const drawMat = new LineMaterial({ color: 0xff2d95, linewidth: 3, worldUnits: false, depthTest: false, transparent: true, opacity: 0.95 });
const eraseMat = new LineMaterial({ color: 0xff2d95, linewidth: 6, worldUnits: false, depthTest: false, transparent: true, opacity: 0.85 });
const propMat = new LineMaterial({ color: 0xff2d95, linewidth: 2.6, worldUnits: false, dashed: true, dashSize: 0.03, gapSize: 0.02, transparent: true, opacity: 0.95 });
const propHMat = new LineMaterial({ color: 0xff2d95, linewidth: 5, worldUnits: false, depthTest: false, transparent: true, opacity: 0.9 });
const cdotMat = new THREE.PointsMaterial({ size: 11, sizeAttenuation: false, map: dotTex, alphaTest: 0.5, transparent: true, depthTest: false });
const csDotMat = cdotMat.clone(); csDotMat.color.set(0x4f6df5); csDotMat.size = 13;
const hdotMat = new THREE.PointsMaterial({ size: 26, sizeAttenuation: false, map: glowTex, color: 0xff2d95, transparent: true, opacity: 0.85, depthTest: false });
function mkLines(mat, order) { const l = new LineSegments2(new LineSegmentsGeometry(), mat); l.frustumCulled = false; l.renderOrder = order; l.visible = false; scene.add(l); return l; }
function mkPts(mat, order) { const p = new THREE.Points(new THREE.BufferGeometry(), mat); p.frustumCulled = false; p.renderOrder = order; p.visible = false; scene.add(p); return p; }
CUT.lines = mkLines(lineMat, 6); CUT.over = mkLines(overMat, 990); CUT.drawL = mkLines(drawMat, 991); CUT.eraseL = mkLines(eraseMat, 992);
CUT.propL = mkLines(propMat, 7); CUT.propH = mkLines(propHMat, 989);
CUT.dots = mkPts(cdotMat, 993); CUT.sdots = mkPts(csDotMat, 994); CUT.hdot = mkPts(hdotMat, 995);
const CUT3D = () => [CUT.lines, CUT.over, CUT.drawL, CUT.eraseL, CUT.propL, CUT.propH, CUT.dots, CUT.sdots, CUT.hdot];
function cutResize() { for (const m of [lineMat, overMat, drawMat, eraseMat, propMat, propHMat]) m.resolution.set(innerWidth, innerHeight); viewShift(); if (S.stage === 'cut') patResize(); }
function viewShift() {                                // in CUT the 2D panel covers the left: centre the 3D view in the free space
  const w = innerWidth, h = innerHeight, on = S.stage === 'cut' && CUT.show2d;
  const d = on ? Math.round(($('pat').getBoundingClientRect().width + 14 - 258) / 2) : 0;
  for (const c of [persp, ortho]) { if (d) c.setViewOffset(w, h, -d, 0, w, h); else c.clearViewOffset(); }
}

const posOf = v => {                                  // display position of a mesh vertex (straightened seams) + tiny lift
  const P = CUT.A ? CUT.A.P : CUT.M.P, N = CUT.A ? CUT.A.G.VN : CUT.M.VN, o = CUT.M.h * 0.12;
  return [P[3 * v] + N[3 * v] * o, P[3 * v + 1] + N[3 * v + 1] * o, P[3 * v + 2] + N[3 * v + 2] * o];
};
function setLines(obj, segs, cols) {
  if (!segs.length) { obj.visible = false; return; }
  const g = new LineSegmentsGeometry(); g.setPositions(segs); if (cols) g.setColors(cols);
  obj.geometry.dispose(); obj.geometry = g; obj.visible = S.stage === 'cut';
  if (obj.material.dashed) obj.computeLineDistances();
}
function setPts(obj, list) {
  if (!list.length) { obj.visible = false; return; }
  const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(list.flat()), 3));
  obj.geometry.dispose(); obj.geometry = g; obj.visible = S.stage === 'cut';
}
function pathSegs(path, out, a, b) { a = a || 0; b = b === undefined ? path.length - 1 : b; for (let i = a; i < b; i++) out.push(...posOf(path[i]), ...posOf(path[i + 1])); return out; }
function updateSeamLines() {
  if (!CUT.M) return;
  const A = CUT.A, segs = [], cols = [], c = new THREE.Color();
  for (const sm of S.seams) for (let i = 0; i + 1 < sm.path.length; i++) {
    const a = sm.path[i], b = sm.path[i + 1], e = CUT.M.edge(a, b);
    const sb = A && e !== undefined && A.edgeSub[e] >= 0 ? A.subs[A.edgeSub[e]] : null;
    c.set(sb ? SEAMCOL[sb.chain % SEAMCOL.length] : '#151515');
    segs.push(...posOf(a), ...posOf(b)); cols.push(c.r, c.g, c.b, c.r, c.g, c.b);
  }
  setLines(CUT.lines, segs, cols);
  const sel = CUT.sel && CUT.sel.type === 'seam' ? S.seams[CUT.sel.i] : null;
  setLines(CUT.over, sel ? pathSegs(sel.path, []) : []);
  const all = [], sp = [];
  S.seams.forEach(sm => sm.vids.forEach(v => (sm === sel ? sp : all).push(posOf(v))));
  setPts(CUT.dots, all); setPts(CUT.sdots, sp);
  const ps = []; CUT.prop.forEach(p => pathSegs(p.path, ps));
  setLines(CUT.propL, ps);
  setLines(CUT.propH, CUT.propHover >= 0 && CUT.prop[CUT.propHover] ? pathSegs(CUT.prop[CUT.propHover].path, []) : []);
  propMat.dashSize = CUT.M.h * 1.6; propMat.gapSize = CUT.M.h * 1.1;
  updateDrawLines();
}
function updateDrawLines() {
  const d = CUT.draw, segs = [];
  if (d) {
    for (let i = 0; i + 1 < d.vids.length; i++) pathSegs(CUT.dj(d.vids[i], d.vids[i + 1], S.cut.bias) || [], segs);
    if (d.preview) pathSegs(d.preview, segs);
    setPts(CUT.sdots, d.vids.map(posOf));
  }
  setLines(CUT.drawL, segs);
  const er = CUT.erase; setLines(CUT.eraseL, er ? pathSegs(S.seams[er.si].path, [], er.a, er.b) : []);
  setPts(CUT.hdot, CUT.tool === 'pen' && CUT.hoverV >= 0 ? [posOf(CUT.hoverV)] : []);
}
function buildCutMesh() {
  const A = CUT.A, nW = A.nW, pos = new Float32Array(3 * nW), nor = new Float32Array(3 * nW);
  for (let w = 0; w < nW; w++) { const v = 3 * A.wv[w]; for (let q = 0; q < 3; q++) { pos[3 * w + q] = A.P[v + q]; nor[3 * w + q] = A.G.VN[v + q]; } }
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
  g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(3 * nW).fill(1), 3));
  g.setIndex(new THREE.BufferAttribute(Uint32Array.from(A.W), 1)); g.computeBoundingSphere();
  if (!CUT.obj) { CUT.obj = new THREE.Mesh(g, matCut); scene.add(CUT.obj); } else setGeo(CUT.obj, g);
  CUT.obj.visible = S.stage === 'cut';
  CUT.wc = new Int32Array(nW); for (let t = 0; t < A.chartOf.length; t++) for (let k = 0; k < 3; k++) CUT.wc[A.W[3 * t + k]] = A.chartOf[t];
  recolor();
}
// STRAIN colours, relative to the material limit: blue = tight (fabric must stretch), red = loose (too much fabric)
const strainRGB = d => {
  const t = Math.min(1, Math.abs(d) / (2 * tol())), a = [0.97, 0.97, 0.97], b = d > 0 ? [1, 0.3, 0.3] : [0.2, 0.55, 1];
  const k = t < 0.5 ? t * 0.7 : 0.35 + (t - 0.5) * 1.3;          // stays pale below the limit, saturates above it
  return a.map((v, i) => v + (b[i] - v) * Math.min(1, k));
};
// CURVATURE: how far apart seams may be here, for the chosen material (spacing ≈ 4·sqrt(limit / |K|))
const spacingAt = K => Math.abs(K) < 1e-9 ? Infinity : 4 * Math.sqrt(tol() / Math.abs(K)) * mmU();
const curvRGB = K => {
  const sp = spacingAt(K), big = S.cut.size, small = S.cut.size / 14;
  const t = sp >= big ? 0 : sp <= small ? 1 : Math.log(big / sp) / Math.log(big / small);
  const a = [0.97, 0.97, 0.97], b = K > 0 ? [1, 0.42, 0.18] : [0.55, 0.3, 1];
  return a.map((v, i) => v + (b[i] - v) * t);
};
function recolor() {
  if (!CUT.obj || !CUT.A) return;
  const A = CUT.A, col = CUT.obj.geometry.attributes.color.array, c = new THREE.Color(), sp = CUT.sel && CUT.sel.type === 'piece' ? CUT.sel.c : -1;
  const put = (w, rgb) => { c.setRGB(rgb[0], rgb[1], rgb[2], THREE.SRGBColorSpace); col[3 * w] = c.r; col[3 * w + 1] = c.g; col[3 * w + 2] = c.b; };
  if (CUT.view === 'strain' && CUT.triDev && CUT.triDevId === CUT.M.id) {
    const acc = new Float32Array(A.nW), cnt = new Float32Array(A.nW), td = CUT.triDev;
    for (let t = 0; t < CUT.M.nT; t++) { if (isNaN(td[t])) continue; for (let k = 0; k < 3; k++) { acc[A.W[3 * t + k]] += td[t]; cnt[A.W[3 * t + k]]++; } }
    for (let w = 0; w < A.nW; w++) put(w, cnt[w] ? strainRGB(acc[w] / cnt[w]) : [0.84, 0.84, 0.84]);
  } else if (CUT.view === 'curv') {
    for (let w = 0; w < A.nW; w++) put(w, curvRGB(CUT.M.K[A.wv[w]]));
  } else {
    const cc = A.charts.map(ch => {
      const x = new THREE.Color(ch.status === 'ok' ? pastel(ch.num) : '#d4d4d4');
      if ((sp >= 0 && ch.id !== sp) || (sp < 0 && CUT.hover >= 0 && ch.id !== CUT.hover)) x.lerp(new THREE.Color('#ffffff'), 0.6);
      return x;
    });
    for (let w = 0; w < A.nW; w++) { const x = cc[CUT.wc[w]]; col[3 * w] = x.r; col[3 * w + 1] = x.g; col[3 * w + 2] = x.b; }
  }
  CUT.obj.geometry.attributes.color.needsUpdate = true;
}
function setView3(v) {
  CUT.view = v;
  $('cvParts').classList.toggle('on', v === 'parts'); $('cvCurv').classList.toggle('on', v === 'curv'); $('cvStrain').classList.toggle('on', v === 'strain');
  $('viewNote').textContent = {
    parts: 'EVERY COLOUR IS ONE PIECE. GREY PIECES ARE STILL CLOSED AND NEED A SEAM.',
    curv: 'WHERE THE FORM CANNOT LIE FLAT. ORANGE = DOME (NEEDS SEAMS OR DARTS), VIOLET = SADDLE (NEEDS SEAMS OR GUSSETS). HOVER = MAX SEAM SPACING FOR THE MATERIAL. WHITE = NO SEAM NEEDED.',
    strain: 'AFTER RENDER CUTS: STRAIN OF THE FLAT PIECES AGAINST THE STRETCH LIMIT. BLUE = TIGHT (FABRIC WOULD HAVE TO STRETCH), RED = LOOSE (WRINKLES). STRONG COLOUR = OVER THE LIMIT.'
  }[v];
  if (v === 'strain' && CUT.stale && CUT.A && !CUT.busy) renderCuts();
  recolor(); draw2D();
}
$('cvParts').addEventListener('click', () => setView3('parts'));
$('cvCurv').addEventListener('click', () => setView3('curv'));
$('cvStrain').addEventListener('click', () => setView3('strain'));

/* ---------- picking ---------- */
function cutPick(e) {
  if (!CUT.obj) return null;
  setRay(e);
  const h = raycaster.intersectObject(CUT.obj, false)[0]; if (!h) return null;
  const t = h.faceIndex, T = CUT.M.T, p = h.point; let best = T[3 * t], bd = 1e18;
  for (let k = 0; k < 3; k++) { const v = T[3 * t + k], q = posOf(v), d = (q[0] - p.x) ** 2 + (q[1] - p.y) ** 2 + (q[2] - p.z) ** 2; if (d < bd) { bd = d; best = v; } }
  return { t, p, v: best };
}
const pxWorld = p => viewDist(p) * 2 * Math.tan(THREE.MathUtils.degToRad(persp.fov / 2)) / Math.max(1, canvas.clientHeight);
function nearVert(h, list, px) {                     // closest of the given vertices within px screen pixels (depth safe: measured at the hit)
  const r = px * pxWorld(h.p), r2 = r * r; let best = -1, bd = r2;
  for (const v of list) { const q = posOf(v), d = (q[0] - h.p.x) ** 2 + (q[1] - h.p.y) ** 2 + (q[2] - h.p.z) ** 2; if (d < bd) { bd = d; best = v; } }
  return best;
}
function snapVert(h) {
  const ctrl = [], path = [];
  for (const sm of S.seams) { ctrl.push(...sm.vids); path.push(...sm.path); }
  if (CUT.draw) ctrl.push(...CUT.draw.vids);
  const a = nearVert(h, ctrl, 13); if (a >= 0) return a;
  const b = nearVert(h, path, 9); return b >= 0 ? b : h.v;
}
function nearCtrl(h) {
  let best = null, bd = Infinity; const r = 12 * pxWorld(h.p);
  S.seams.forEach((sm, si) => sm.vids.forEach((v, pi) => { const q = posOf(v), d = Math.hypot(q[0] - h.p.x, q[1] - h.p.y, q[2] - h.p.z); if (d < r && d < bd) { bd = d; best = { si, pi }; } }));
  return best;
}
function nearPath(h, paths, px) {                     // -> {i (which path), k (index on it)}
  let best = null, bd = Infinity; const r = px * pxWorld(h.p);
  paths.forEach((path, i) => path.forEach((v, k) => { const q = posOf(v), d = Math.hypot(q[0] - h.p.x, q[1] - h.p.y, q[2] - h.p.z); if (d < r && d < bd) { bd = d; best = { i, k }; } }));
  return best;
}
const nearSeam = h => { const r = nearPath(h, S.seams.map(s => s.path), 9); return r ? r.i : -1; };

/* ---------- ERASE: remove the stretch of a seam between its stops (control points, crossings, ends) ---------- */
function seamStops(si) {
  const sm = S.seams[si], path = sm.path, n = path.length, stop = new Set([0, n - 1]), other = new Set(), seen = new Map();
  S.seams.forEach((o, i) => { if (i !== si) for (const v of o.path) other.add(v); });
  const ctrl = new Set(sm.vids);
  path.forEach((v, k) => { if (ctrl.has(v) || other.has(v)) stop.add(k); if (seen.has(v) && !(sm.closed && k === n - 1 && seen.get(v) === 0)) { stop.add(k); stop.add(seen.get(v)); } else if (!seen.has(v)) seen.set(v, k); });
  return [...stop].sort((a, b) => a - b);
}
function eraseRange(si, k) {
  const st = seamStops(si); let a = 0, b = st[st.length - 1];
  for (const s of st) { if (s <= k) a = s; }
  for (const s of st) { if (s > a) { b = s; break; } }
  if (a === b) return null;
  return { si, a, b };
}
function applyErase(er) {
  const sm = S.seams[er.si], path = sm.path, st = new Set(seamStops(er.si)), ctrl = new Set(sm.vids);
  const toSeam = idx => {                             // control points: original points + stops, so the route stays identical
    const vs = idx.map(i => path[i]);
    if (vs.length < 2 || (vs.length === 2 && vs[0] === vs[1])) return null;
    const keep = idx.filter((i, j) => j === 0 || j === idx.length - 1 || ctrl.has(path[i]) || st.has(i));
    const pts = []; let last = -1;
    for (const i of keep) { if (path[i] === last) continue; pts.push(vpos(path[i])); last = path[i]; }
    return pts.length >= 2 ? { pts, closed: false } : null;
  };
  const range = (x, y) => { const r = []; for (let i = x; i <= y; i++) r.push(i); return r; };
  const out = [];
  if (sm.closed) {
    const n = path.length - 1;                        // path[n] == path[0]
    const idx = range(er.b, n).concat(range(1, er.a));
    const s = toSeam(idx.map(i => i % n === 0 ? 0 : i)); if (s) out.push(s);
  } else {
    const l = toSeam(range(0, er.a)), r = toSeam(range(er.b, path.length - 1));
    if (l) out.push(l); if (r) out.push(r);
  }
  pushUndo();
  S.seams.splice(er.si, 1, ...out);
  CUT.erase = null; CUT.sel = null; cutRun();
}

/* ---------- SUGGEST: proposed seams, drawn dashed on the form ---------- */
function principal(P, verts) {
  let c = [0, 0, 0]; for (const v of verts) for (let q = 0; q < 3; q++) c[q] += P[3 * v + q] / verts.length;
  const C = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  for (const v of verts) { const d = [P[3 * v] - c[0], P[3 * v + 1] - c[1], P[3 * v + 2] - c[2]]; for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) C[3 * a + b] += d[a] * d[b]; }
  const axes = [];
  // power iteration with deflation -> axes sorted by variance (largest first)
  let D = C.slice();
  for (let k = 0; k < 3; k++) {
    let v = [0.6, 0.5, 0.62].map((x, i) => x + 0.1 * k * i);
    for (let it = 0; it < 80; it++) {
      let w = [D[0] * v[0] + D[1] * v[1] + D[2] * v[2], D[3] * v[0] + D[4] * v[1] + D[5] * v[2], D[6] * v[0] + D[7] * v[1] + D[8] * v[2]];
      for (const a of axes) { const d = w[0] * a[0] + w[1] * a[1] + w[2] * a[2]; w = w.map((x, i) => x - d * a[i]); }
      const l = Math.hypot(...w) || 1; v = w.map(x => x / l);
    }
    axes.push(v);
  }
  return { c, axes };
}
function sampleLoop(pts, closed) {
  let L = 0; const cum = [0];
  for (let i = 1; i < pts.length + (closed ? 1 : 0); i++) { const a = pts[i - 1], b = pts[i % pts.length]; L += Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); cum.push(L); }
  const n = closed ? Math.max(6, Math.min(16, Math.round(L / (CUT.M.ext * 0.12)))) : Math.max(2, Math.min(10, Math.round(L / (CUT.M.ext * 0.12)) + 1));
  const out = [];
  for (let i = 0; i < n; i++) {
    const s = closed ? L * i / n : L * i / (n - 1); let j = 1; while (j < cum.length - 1 && cum[j] < s) j++;
    const a = pts[(j - 1) % pts.length], b = pts[j % pts.length], u = (s - cum[j - 1]) / ((cum[j] - cum[j - 1]) || 1);
    out.push(CUT.M.nearest(a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u));
  }
  return out.filter((v, i) => v !== out[(i - 1 + out.length) % out.length]);
}
function pathFromCtrl(vids, closed) {
  let path = []; const n = vids.length, m = closed ? n : n - 1;
  for (let i = 0; i < m; i++) { const s = CUT.dj(vids[i], vids[(i + 1) % n], S.cut.bias) || [vids[i]]; path = path.length ? path.concat(s.slice(1)) : s; }
  return path;
}
async function suggest() {
  if (!CUT.A) return;
  const A0 = CUT.A, needRender = A0.charts.some(c => c.status === 'ok') && CUT.stale;
  if (needRender) { await renderCuts(); if (CUT.stale) return; }
  const A = CUT.A, M = CUT.M, P = A.P, out = [], W = CC.weights(M, S.cut.bias), lim = tol();
  const symX = S.blobs.some(b => !b.neg && b.sym[0]), narrow = [];
  for (const ch of A.charts.slice().sort((a, b) => a.num - b.num)) {
    const verts = [...new Set(ch.tris.flatMap(t => [M.T[3 * t], M.T[3 * t + 1], M.T[3 * t + 2]]))];
    if (ch.status === 'closed' || ch.status === 'handle') {
      // plane section: the symmetry plane if the form is mirrored in X, otherwise the "pillow" plane (two largest axes)
      const pc = principal(P, verts);
      let n = ch.status === 'handle' ? pc.axes[0] : pc.axes[2], c = pc.c, why = ch.status === 'handle' ? 'CUTS THE TUNNEL' : 'OPENS THE CLOSED FORM';
      if (symX && ch.status === 'closed') { n = [1, 0, 0]; c = [0, 0, 0]; why = 'CENTRE SEAM ON THE SYMMETRY PLANE'; }
      let loops = CC.section(P, M, ch.tris, n, c);
      if (!loops.length) loops = CC.section(P, M, ch.tris, pc.axes[2], pc.c);
      const lenOf = l => { let s = 0; for (let i = 1; i < l.pts.length; i++) s += Math.hypot(...[0, 1, 2].map(q => l.pts[i][q] - l.pts[i - 1][q])); return s; };
      loops.sort((a, b) => lenOf(b) - lenOf(a));
      for (const l of loops.filter(l => lenOf(l) > 0.25 * lenOf(loops[0])).slice(0, 3)) {
        const vids = sampleLoop(l.pts, l.closed); if (vids.length < (l.closed ? 3 : 2)) continue;
        out.push({ vids, closed: l.closed, path: pathFromCtrl(vids, l.closed), label: `T${ch.num} · LOOP · ${why}` });
      }
      continue;
    }
    if (ch.status !== 'ok' || !CUT.triDev) continue;
    // strain of this piece against the material limit
    const triIn = new Uint8Array(M.nT), sv = new Float64Array(M.nV);
    for (const t of ch.tris) { triIn[t] = 1; for (let k = 0; k < 3; k++) { const v = M.T[3 * t + k], d = Math.abs(CUT.triDev[t]) || 0; if (d > sv[v]) sv[v] = d; } }
    let area = 0, over = 0, mx = 0;
    for (const t of ch.tris) { const d = Math.abs(CUT.triDev[t]) || 0; area += A.G.FA[t]; if (d > lim) over += A.G.FA[t]; }
    const r = CUT.FR[ch.id]; mx = r ? r.dev : 0;
    if (mx <= lim) continue;
    if (area * mmU() * mmU() < (2 * (2 * S.cut.allow + 25)) ** 2) { out.push({ note: true, label: `T${ch.num} · STRAIN ${(mx * 100).toFixed(1)} % · PIECE TOO SMALL TO CUT FURTHER` }); continue; }
    const bnd = [...new Set(ch.loops.flat().map(h => h.a))]; if (!bnd.length) continue;
    // seam ends: prefer an existing point / crossing nearby, so new seams meet the old ones in one spot
    const hubs = new Set(); for (const sm of S.seams) for (const v of sm.vids) hubs.add(v);
    for (const chn of A.chains) { hubs.add(chn.verts[0]); hubs.add(chn.verts[chn.verts.length - 1]); }
    const bset = new Set(bnd), hubR2 = (M.ext * 0.07) ** 2;
    const nearB = (x, y, z) => {
      let b = bnd[0], bd = Infinity, hb = -1, hd = hubR2;
      for (const v of bnd) { const d = (P[3 * v] - x) ** 2 + (P[3 * v + 1] - y) ** 2 + (P[3 * v + 2] - z) ** 2; if (d < bd) { bd = d; b = v; } if (hubs.has(v) && d < hd) { hd = d; hb = v; } }
      return hb >= 0 ? hb : b;
    };
    // piece frame: long axis + average outside normal
    const pc = principal(P, verts); let N = [0, 0, 0];
    for (const t of ch.tris) for (let q = 0; q < 3; q++) N[q] += A.G.FN[3 * t + q] * A.G.FA[t];
    const nl = Math.hypot(...N) || 1; N = N.map(x => x / nl);
    let ax = pc.axes[0]; if (Math.abs(ax[0] * N[0] + ax[1] * N[1] + ax[2] * N[2]) > 0.85) ax = pc.axes[1];
    let n = [ax[1] * N[2] - ax[2] * N[1], ax[2] * N[0] - ax[0] * N[2], ax[0] * N[1] - ax[1] * N[0]];
    const ln = Math.hypot(...n); if (ln < 1e-6) n = pc.axes[1]; else n = n.map(x => x / ln);
    let w0 = Infinity, w1 = -Infinity;
    for (const v of verts) { const d = (P[3 * v] - pc.c[0]) * n[0] + (P[3 * v + 1] - pc.c[1]) * n[1] + (P[3 * v + 2] - pc.c[2]) * n[2]; w0 = Math.min(w0, d); w1 = Math.max(w1, d); }
    const width = (w1 - w0) * mmU(), minW = 2 * (2 * S.cut.allow + 25);
    const local = over / area < 0.15 && mx < 2 * lim;
    if (!local && width >= minW) {
      // SPLIT lengthwise through the middle: halves the width of the piece (gores) with one long, calm seam
      const secs = CC.section(P, M, ch.tris, n, pc.c).map(l => { let L = 0; for (let i = 1; i < l.pts.length; i++) L += Math.hypot(...[0, 1, 2].map(q => l.pts[i][q] - l.pts[i - 1][q])); return { ...l, L }; }).sort((a, b) => b.L - a.L);
      const l = secs[0];
      if (l && l.pts.length > 3) {
        const vids = sampleLoop(l.pts, l.closed);
        if (!l.closed) { const p0 = l.pts[0], p1 = l.pts[l.pts.length - 1]; vids[0] = nearB(...p0); vids[vids.length - 1] = nearB(...p1); }
        const clean = vids.filter((v, i) => i === 0 || v !== vids[i - 1]);
        if (clean.length >= 2) { out.push({ vids: clean, closed: l.closed, path: pathFromCtrl(clean, l.closed), label: `T${ch.num} · SPLIT · STRAIN ${(mx * 100).toFixed(1)} % > ${S.cut.lim} %` }); continue; }
      }
    }
    if (!local) {                                     // too narrow to halve: remember the hot spot (gore tips -> cap)
      let hv = -1, hs = 0; for (const v of verts) if (sv[v] > hs) { hs = sv[v]; hv = v; }
      if (hv >= 0) narrow.push({ ch, v: hv, s: mx, ax, bnd, nearB });
      continue;
    }
    // DART: from the nearest edge into the strained area (local excess)
    const W2 = W, fromB = CC.spread(M, bnd, e => triIn[M.et0[e]] || (M.et1[e] >= 0 && triIn[M.et1[e]]), W2);
    let best = -1, bs = lim;
    for (const v of verts) if (fromB.dist[v] >= 3 * M.h && sv[v] > bs) { bs = sv[v]; best = v; }
    if (best < 0) continue;
    const leg = []; for (let v = best; v >= 0; v = fromB.prev[v]) leg.push(v);
    const path = leg.reverse(); if (path.length < 3) continue;
    const step = Math.max(4, Math.round(path.length / 5)), vids = [];
    for (let i = 0; i < path.length; i += step) vids.push(path[i]);
    if (vids[vids.length - 1] !== path[path.length - 1]) vids.push(path[path.length - 1]);
    out.push({ vids, closed: false, path: pathFromCtrl(vids, false), label: `T${ch.num} · DART · STRAIN ${(mx * 100).toFixed(1)} % > ${S.cut.lim} %` });
  }
  for (const nw of narrow) out.push({ note: true, label: `T${nw.ch.num} · STRAIN ${(nw.s * 100).toFixed(1)} % · TOO NARROW TO SPLIT — ADD A DART BY HAND, USE A SOFTER MATERIAL OR EASE` });
  CUT.notes = out.filter(p => p.note).map(p => p.label);
  CUT.prop = out.filter(p => !p.note); CUT.propHover = -1;
  syncProps(); updateSeamLines();
  setStatus(out.length ? `${out.length} SUGGESTIONS · CLICK A DASHED LINE OR ACCEPT` : 'NO SUGGESTIONS · ALL PIECES WITHIN THE STRETCH LIMIT');
}
function acceptProp(i) {
  const p = CUT.prop[i]; if (!p) return;
  pushUndo();
  S.seams.push({ pts: p.vids.map(vpos), closed: p.closed });
  CUT.prop.splice(i, 1); CUT.propHover = -1;
  syncProps(); cutRun();
}
function syncProps() {
  const el = $('propList');
  const notes = (CUT.notes || []).map(t => `<div class="w" style="color:#c2453b">${t}</div>`).join('');
  if (!CUT.prop.length) { el.innerHTML = notes; return; }
  el.innerHTML = notes + CUT.prop.map((p, i) => `<div class="pr${i === CUT.propHover ? ' on' : ''}"><span>${p.label}</span><button data-pa="${i}">ACCEPT</button></div>`).join('') +
    `<div class="seg" style="margin-top:7px"><button data-pa="all">ACCEPT ALL</button><button data-pa="clear">CLEAR</button></div>`;
}
$('propList').addEventListener('click', e => {
  const b = e.target.closest('button'); if (!b) return;
  const a = b.dataset.pa;
  if (a === 'clear') { CUT.prop = []; syncProps(); updateSeamLines(); return; }
  if (a === 'all') { pushUndo(); for (const p of CUT.prop) S.seams.push({ pts: p.vids.map(vpos), closed: p.closed }); CUT.prop = []; syncProps(); cutRun(); return; }
  acceptProp(+a);
});
$('propList').addEventListener('mouseover', e => { const r = e.target.closest('.pr'); const i = r ? +r.querySelector('button').dataset.pa : -1; if (i !== CUT.propHover) { CUT.propHover = i; updateSeamLines(); } });
$('btnSuggest').addEventListener('click', () => suggest());
async function autoPlan() {
  if (!CUT.A || CUT.busy) return;
  pushUndo();
  for (let round = 1; round <= 5; round++) {
    setStatus(`AUTO PLAN · ROUND ${round}`);
    await suggest();
    if (!CUT.prop.length) break;
    for (const p of CUT.prop) S.seams.push({ pts: p.vids.map(vpos), closed: p.closed });
    CUT.prop = []; syncProps(); cutRun();
    await new Promise(r => setTimeout(r, 0));
  }
  await renderCuts();
  const over = CUT.A.charts.filter(c => CUT.FR[c.id] && CUT.FR[c.id].dev > tol()).length;
  setStatus(over ? `AUTO PLAN · ${over} PIECES STILL OVER THE LIMIT (TOO NARROW TO SPLIT)` : 'AUTO PLAN · ALL PIECES WITHIN THE STRETCH LIMIT');
}
$('btnAuto').addEventListener('click', () => autoPlan());

/* ---------- interaction ---------- */
function pushUndo() { CUT.undo.push(JSON.stringify(S.seams.map(s => ({ pts: s.pts, closed: s.closed })))); if (CUT.undo.length > 80) CUT.undo.shift(); }
function cutUndo() {
  if (CUT.draw) { CUT.draw.vids.pop(); if (!CUT.draw.vids.length) CUT.draw = null; CUT.draw && (CUT.draw.preview = null); syncCbar(); updateSeamLines(); return; }
  if (!CUT.undo.length) return;
  S.seams = JSON.parse(CUT.undo.pop()); CUT.sel = null; cutRun();
}
function setTool(t) {
  CUT.tool = t; if (t !== 'pen') { CUT.draw = null; CUT.hoverV = -1; } if (t !== 'erase') CUT.erase = null;
  $('ctPen').classList.toggle('on', t === 'pen'); $('ctSel').classList.toggle('on', t === 'sel'); $('ctErase').classList.toggle('on', t === 'erase');
  canvas.style.cursor = t === 'pen' ? 'crosshair' : '';
  syncCbar(); syncCutSel(); updateSeamLines();
}
function showTip(e, txt) {
  const el = $('ctip');
  if (!txt) { el.hidden = true; return; }
  el.hidden = false; el.textContent = txt; el.style.left = (e.clientX + 16) + 'px'; el.style.top = (e.clientY + 14) + 'px';
}
function cutDown(e) {
  if (e.target !== canvas || !CUT.M) return false;
  CUT.down = { x: e.clientX, y: e.clientY };
  if (CUT.draw || CUT.tool === 'erase') return false;
  const h = cutPick(e); if (!h) return false;
  const cp = nearCtrl(h);
  if (cp) { pushUndo(); CUT.drag = { ...cp, moved: false, x: e.clientX, y: e.clientY }; return true; }
  return false;
}
function cutMove(e) {
  if (!CUT.M) return;
  if (CUT.drag) {
    const d = CUT.drag;
    if (!d.moved && Math.hypot(e.clientX - d.x, e.clientY - d.y) < 4) return;
    const h = cutPick(e); if (!h) return;
    d.moved = true; CUT.sel = { type: 'seam', i: d.si };
    const sm = S.seams[d.si], others = []; S.seams.forEach((o, i) => { if (i !== d.si) others.push(...o.vids); });
    const a = nearVert(h, others, 13), v = a >= 0 ? a : h.v;
    sm.pts[d.pi] = vpos(v); seamPath(sm); updateSeamLines();
    return;
  }
  if (e.target !== canvas) { showTip(e, null); if (CUT.hoverV >= 0 || CUT.erase) { CUT.hoverV = -1; CUT.erase = null; updateDrawLines(); } return; }
  if (CUT.prevRaf) return;                              // throttle: one pick + preview per frame
  CUT.prevRaf = requestAnimationFrame(() => {
    CUT.prevRaf = 0;
    const h = cutPick(e);
    // suggestions under the cursor (any tool)
    const pp = h && CUT.prop.length ? nearPath(h, CUT.prop.map(p => p.path), 10) : null, ph = pp ? pp.i : -1;
    if (ph !== CUT.propHover) { CUT.propHover = ph; syncProps(); updateSeamLines(); }
    let tip = null;
    if (ph >= 0) tip = 'CLICK TO ACCEPT · ' + CUT.prop[ph].label;
    else if (h && CUT.view === 'curv') {
      const K = CUT.M.K[h.v], sp = spacingAt(K);
      tip = sp > S.cut.size ? 'NEARLY FLAT · NO SEAM NEEDED' : `${K > 0 ? 'DOME' : 'SADDLE'} · SEAMS ≈ EVERY ${(sp / 10).toFixed(sp < 100 ? 1 : 0)} CM (${S.cut.lim} % LIMIT)`;
    } else if (h && CUT.view === 'strain' && CUT.triDev && CUT.triDevId === CUT.M.id) {
      const d = CUT.triDev[h.t];
      tip = isNaN(d) ? 'NOT RENDERED' : `${d < 0 ? 'TIGHT' : 'LOOSE'} ${(d * 100).toFixed(1)} % · LIMIT ${S.cut.lim} %${Math.abs(d) > tol() ? ' · OVER' : ''}`;
    }
    if (CUT.tool === 'pen') {
      CUT.hoverV = h && ph < 0 ? snapVert(h) : -1;
      if (CUT.draw) { const l = CUT.draw.vids[CUT.draw.vids.length - 1]; CUT.draw.preview = CUT.hoverV >= 0 ? CUT.dj(l, CUT.hoverV, S.cut.bias) : null; }
      updateDrawLines();
    } else if (CUT.tool === 'erase') {
      const np = h && ph < 0 ? nearPath(h, S.seams.map(s => s.path), 10) : null;
      CUT.erase = np ? eraseRange(np.i, np.k) : null;
      if (CUT.erase && !tip) tip = 'CLICK TO REMOVE THIS STRETCH';
      canvas.style.cursor = CUT.erase || ph >= 0 ? 'pointer' : '';
      updateDrawLines();
    } else {
      const hp = h && nearSeam(h) < 0 ? CUT.A.chartOf[h.t] : -1;
      canvas.style.cursor = h && (nearCtrl(h) || nearSeam(h) >= 0) || ph >= 0 ? 'pointer' : '';
      if (hp !== CUT.hover) { CUT.hover = hp; if (CUT.view === 'parts') recolor(); draw2D(); }
    }
    showTip(e, tip);
  });
}
function cutUp(e) {
  if (CUT.drag) {
    const d = CUT.drag; CUT.drag = null;
    if (d.moved) { CUT.down = null; cutRun(); return; }
    CUT.undo.pop();
  }
  if (!CUT.down) return;
  const moved = Math.hypot(e.clientX - CUT.down.x, e.clientY - CUT.down.y); CUT.down = null;
  if (moved >= 5 || e.target !== canvas) return;
  cutClick(e);
}
function cutClick(e) {
  const h = cutPick(e);
  if (h && CUT.prop.length) { const pp = nearPath(h, CUT.prop.map(p => p.path), 10); if (pp) { acceptProp(pp.i); return; } }
  if (CUT.tool === 'erase') {
    if (!h) return;
    const np = nearPath(h, S.seams.map(s => s.path), 10), er = np ? eraseRange(np.i, np.k) : null;
    if (er) applyErase(er);
    return;
  }
  if (CUT.tool === 'pen') {
    if (!h) return;
    const v = snapVert(h), d = CUT.draw;
    if (!d) CUT.draw = { vids: [v], preview: null };
    else {
      if (d.vids.length >= 3 && v === d.vids[0]) { finishSeam(true); return; }
      if (v === d.vids[d.vids.length - 1]) return;
      d.vids.push(v); d.preview = null;
    }
    syncCbar(); updateSeamLines(); return;
  }
  if (!h) { CUT.sel = null; }
  else {
    const cp = e.altKey ? nearCtrl(h) : null;
    if (cp) {                                          // ALT + click on a point = delete it
      const sm = S.seams[cp.si]; pushUndo();
      if (sm.pts.length <= (sm.closed ? 3 : 2)) S.seams.splice(cp.si, 1); else sm.pts.splice(cp.pi, 1);
      CUT.sel = null; cutRun(); return;
    }
    const si = nearSeam(h);
    CUT.sel = si >= 0 ? { type: 'seam', i: si } : { type: 'piece', c: CUT.A.chartOf[h.t] };
  }
  syncCutSel(); recolor(); updateSeamLines(); draw2D();
}
function finishSeam(closed) {
  const d = CUT.draw; if (!d) return;
  if (d.vids.length < (closed ? 3 : 2)) { CUT.draw = null; syncCbar(); updateSeamLines(); return; }
  pushUndo();
  S.seams.push({ pts: d.vids.map(vpos), closed: !!closed });
  CUT.draw = null; CUT.sel = { type: 'seam', i: S.seams.length - 1 };
  syncCbar(); cutRun();
}
function insertCtrl(e) {                              // double-click on the selected seam (SELECT tool) = new control point
  const sel = CUT.sel && CUT.sel.type === 'seam' ? S.seams[CUT.sel.i] : null; if (!sel) return;
  const h = cutPick(e); if (!h) return;
  const v = nearVert(h, sel.path, 9); if (v < 0) return;
  const pi = sel.path.indexOf(v); let seg = 0;
  for (let i = 0; i < sel.segStart.length; i++) if (sel.segStart[i] <= pi) seg = i;
  if (sel.vids.includes(v)) return;
  pushUndo(); sel.pts.splice(seg + 1, 0, vpos(v)); cutRun();
}
function cutDbl(e) {
  if (CUT.tool === 'pen' && CUT.draw) { finishSeam(false); return; }
  if (CUT.tool === 'sel') insertCtrl(e);
}
function cutKey(e) {
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') { e.preventDefault(); cutUndo(); return; }
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); saveLocal(); return; }
  if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); renderCuts(); return; }
  if (e.key === 'Enter' && CUT.draw) { e.preventDefault(); finishSeam(false); return; }
  if (e.key === 'Escape') { if (CUT.draw) CUT.draw = null; else if (CUT.prop.length) { CUT.prop = []; syncProps(); } else CUT.sel = null; syncCbar(); syncCutSel(); recolor(); updateSeamLines(); draw2D(); return; }
  if ((e.key === 'Delete' || e.key === 'Backspace') && !e.target.closest('input,select')) {
    e.preventDefault();
    if (CUT.draw) { cutUndo(); return; }
    if (CUT.sel && CUT.sel.type === 'seam') { pushUndo(); S.seams.splice(CUT.sel.i, 1); CUT.sel = null; cutRun(); }
    return;
  }
  if (e.ctrlKey || e.metaKey || e.altKey || e.target.closest('select')) return;
  const k = e.key.toLowerCase();
  if (k === 'p') setTool('pen');
  if (k === 'e') setTool('erase');
  if (k === 'v' || k === 'q') setTool('sel');
}
function syncCbar() {
  const d = CUT.draw;
  $('cbar').hidden = !d || S.stage !== 'cut';
  if (!d) return;
  $('cbarTxt').textContent = `${d.vids.length} PTS · CLICK FIRST POINT = LOOP · ENTER / DOUBLE-CLICK = FINISH`;
  $('cbClose').disabled = d.vids.length < 3; $('cbFinish').disabled = d.vids.length < 2;
}
$('cbFinish').addEventListener('click', () => finishSeam(false));
$('cbClose').addEventListener('click', () => finishSeam(true));
$('cbCancel').addEventListener('click', () => { CUT.draw = null; syncCbar(); updateSeamLines(); });
$('ctPen').addEventListener('click', () => setTool('pen'));
$('ctErase').addEventListener('click', () => setTool('erase'));
$('ctSel').addEventListener('click', () => setTool('sel'));

/* ---------- side panel ---------- */
const pct = v => (v * 100).toFixed(1) + ' %';
const fresh = () => !CUT.stale && CUT.RA === CUT.A;
function syncCutSel() {
  const el = $('cutSel'), sel = CUT.sel, A = CUT.A; let h = '';
  if (sel && sel.type === 'seam' && S.seams[sel.i]) {
    const sm = S.seams[sel.i]; let L = 0;
    for (let i = 0; i + 1 < sm.path.length; i++) { const a = posOf(sm.path[i]), b = posOf(sm.path[i + 1]); L += Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); }
    h += `<div class="kv"><span>SEAM ${sel.i + 1} · ${sm.closed ? 'LOOP' : 'OPEN'}</span><b>${sm.pts.length} PTS</b></div>`;
    h += `<div class="kv"><span>LENGTH ON FORM</span><b>${Math.round(L * mmU())} MM</b></div>`;
    h += `<div class="seg" style="margin-top:7px"><button data-ca="mirror">MIRROR X</button><button data-ca="loop">${sm.closed ? 'OPEN' : 'CLOSE'}</button><button data-ca="del" class="del">DELETE</button></div>`;
    h += `<div class="m" style="margin-top:6px">DRAG POINTS · ALT+CLICK POINT = REMOVE · DOUBLE-CLICK SEAM = ADD POINT · ERASE TOOL REMOVES SINGLE STRETCHES</div>`;
  } else if (sel && sel.type === 'piece' && A && A.charts[sel.c]) {
    const ch = A.charts[sel.c], r = fresh() ? CUT.FR[ch.id] : null, u = mmU();
    h += `<div class="kv"><span>PIECE T${ch.num}</span><b>${ch.status === 'ok' ? (r ? 'FLAT' : 'NOT RENDERED') : ch.status.toUpperCase()}</b></div>`;
    h += `<div class="kv"><span>AREA</span><b>${(ch.area3 * u * u / 100).toFixed(0)} CM²</b></div>`;
    if (r) {
      h += `<div class="kv"><span>STRAIN 98 % / MEAN</span><b>${pct(r.dev)} / ${pct(r.mean)}</b></div>`;
      if (r.flips || r.overl) h += `<div class="kv"><span>FOLDS / OVERLAPS</span><b>${r.flips} / ${r.overl}</b></div>`;
      if (CUT.LY) for (const s of CUT.LY.seams.filter(s => s.sides.some(sd => sd && sd.piece.ci === ch.id))) if (s.diff !== undefined) h += `<div class="kv"><span>N${s.num} · ${s.sides.map(sd => sd.piece.name).join(' ↔ ')}</span><b>${Math.round(s.sides[0].len)} / ${Math.round(s.sides[1].len)} MM</b></div>`;
    }
  } else {
    h += `<div class="m">${{
      pen: 'PEN: CLICK POINTS ON THE FORM — THE SEAM FOLLOWS THE SURFACE (AND ITS CREASES). CLICK THE FIRST POINT FOR A LOOP, ENTER OR DOUBLE-CLICK TO FINISH. A SEAM THAT ENDS INSIDE A PIECE BECOMES A DART. DRAG POINTS TO MOVE THEM.',
      erase: 'ERASE: HOVER A SEAM — THE STRETCH BETWEEN TWO STOPS (POINTS, CROSSINGS, ENDS) TURNS PINK. CLICK REMOVES ONLY THAT STRETCH.',
      sel: 'SELECT: CLICK A SEAM OR A PIECE. DRAG POINTS, ALT+CLICK REMOVES A POINT, DOUBLE-CLICK ON A SEAM ADDS ONE.' }[CUT.tool]}</div>`;
  }
  el.innerHTML = h;
}
$('cutSel').addEventListener('click', e => {
  const b = e.target.closest('button'); if (!b || !CUT.sel || CUT.sel.type !== 'seam') return;
  const sm = S.seams[CUT.sel.i]; if (!sm) return;
  const a = b.dataset.ca;
  pushUndo();
  if (a === 'del') { S.seams.splice(CUT.sel.i, 1); CUT.sel = null; }
  else if (a === 'loop') { if (!sm.closed && sm.pts.length < 3) { CUT.undo.pop(); return; } sm.closed = !sm.closed; }
  else if (a === 'mirror') { S.seams.push({ pts: sm.pts.map(p => [-p[0], p[1], p[2]]), closed: sm.closed }); CUT.sel = { type: 'seam', i: S.seams.length - 1 }; }
  cutRun();
});
function cutInfo() {
  const A = CUT.A, el = $('cutInfo'); if (!A) { el.innerHTML = ''; return; }
  const ok = A.charts.filter(c => c.status === 'ok').length, w = [], fr = fresh(), lim = tol();
  for (const ch of A.charts.slice().sort((a, b) => a.num - b.num)) {
    const n = 'T' + ch.num;
    if (ch.status === 'closed') w.push(`${n} IS CLOSED — DRAW A SEAM OR SUGGEST`);
    else if (ch.status === 'handle') w.push(`${n} HAS A TUNNEL / HANDLE — ADD A SEAM ACROSS IT`);
    else if (ch.status === 'broken') w.push(`${n} MESH DEFECT — CHANGE MESH RES`);
    else if (fr) {
      const r = CUT.FR[ch.id]; if (!r) continue;
      if (r.overl) w.push(`${n} OVERLAPS ITSELF FLAT — ADD A SEAM OR DART`);
      else if (r.flips > ch.tris.length * 0.002) w.push(`${n} FOLDS WHEN FLAT — ADD A SEAM OR DART`);
      if (r.dev > lim) w.push(`${n} STRAIN ${(r.dev * 100).toFixed(1)} % > ${S.cut.lim} % — SEE STRAIN / SUGGEST`);
    }
  }
  if (fr && CUT.LY) {
    for (const s of CUT.LY.seams) if (s.diff > Math.max(0.01, lim)) w.push(`N${s.num} SIDES DIFFER ${(s.diff * 100).toFixed(1)} %`);
    for (const p of CUT.LY.pieces) if ((p.bb[2] - p.bb[0]) < 4 * S.cut.allow + 20 || (p.bb[3] - p.bb[1]) < 4 * S.cut.allow + 20) w.push(`${p.name} IS VERY SMALL TO SEW`);
  }
  let h = `<div class="kv"><span>PIECES</span><b>${ok}${ok !== A.charts.length ? ' / ' + A.charts.length : ''}</b></div>`;
  h += `<div class="kv"><span>SEAMS · SECTIONS</span><b>${A.chains.length} · ${A.subs.length}</b></div>`;
  if (fr && CUT.LY && CUT.LY.pieces.length) h += `<div class="kv"><span>SHEET</span><b>${Math.round(CUT.LY.W)} × ${Math.round(CUT.LY.H)} MM</b></div>`;
  if (!fr && ok) h += `<div class="m">PATTERN NOT RENDERED FOR THE CURRENT SEAMS</div>`;
  h += w.map(x => `<div class="w">${x}</div>`).join('');
  el.innerHTML = h;
}

/* ---------- 2D pattern preview ---------- */
const pc = $('pc'), pctx = pc.getContext('2d'), PV = { s: 1, ox: 0, oy: 0 };
let pcw = 1, pch = 1, pdpr = 1, pdrag = null;
function patResize() {
  const r = $('pat').getBoundingClientRect(); pdpr = Math.min(devicePixelRatio || 1, 2);
  pcw = Math.max(1, r.width); pch = Math.max(1, r.height);
  pc.width = Math.round(pcw * pdpr); pc.height = Math.round(pch * pdpr);
  draw2D();
}
function patFit() {
  const L = CUT.LY; if (!L || !L.pieces.length) return;
  const m = 30, top = 40;
  PV.s = Math.max(0.02, Math.min((pcw - 2 * m) / Math.max(L.W, 1), (pch - top - m) / Math.max(L.H, 1)));
  PV.ox = (pcw - L.W * PV.s) / 2; PV.oy = top + (pch - top - m - L.H * PV.s) / 2; CUT.patFitted = true;
  draw2D();
}
const P2 = (p, q) => { const s = p.S(q); return [s[0] * PV.s + PV.ox, s[1] * PV.s + PV.oy]; };
function polyPath(c, p, pts) { pts.forEach((q, i) => { const a = P2(p, q); i ? c.lineTo(a[0], a[1]) : c.moveTo(a[0], a[1]); }); c.closePath(); }
function inPiece(p, x, y) {
  const q = [(x - PV.ox) / PV.s - p.ox, p.oy - (y - PV.oy) / PV.s];
  const inside = l => { let c = false; for (let i = 0, j = l.length - 1; i < l.length; j = i++) { const a = l[i], b = l[j]; if ((a[1] > q[1]) !== (b[1] > q[1]) && q[0] < (b[0] - a[0]) * (q[1] - a[1]) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
  return inside(p.stitch[0]) && !p.stitch.slice(1).some(inside);
}
const rgbStr = rgb => `rgb(${rgb.map(v => Math.round(v * 255)).join(',')})`;
function draw2D() {
  if (S.stage !== 'cut' || $('pat').hidden) return;
  const c = pctx; c.setTransform(pdpr, 0, 0, pdpr, 0, 0); c.clearRect(0, 0, pcw, pch);
  c.font = '500 9px -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif'; c.textBaseline = 'middle';
  const L = CUT.LY, A = CUT.A, fr = fresh();
  if (!L || !L.pieces.length) {
    c.fillStyle = '#8e8e8e'; c.textAlign = 'center';
    const anyOk = A && A.charts.some(ch => ch.status === 'ok');
    c.fillText(!A ? 'BUILDING…' : anyOk ? 'PRESS RENDER CUTS TO LAY THE PIECES FLAT' : 'DRAW SEAMS ON THE FORM (OR SUGGEST SEAMS) — EVERY PIECE MUST BE CUT OPEN', pcw / 2, pch / 2); return;
  }
  const sp = fr && CUT.sel && CUT.sel.type === 'piece' ? CUT.sel.c : -1, hv = fr ? CUT.hover : -1;
  const g = PV.s * 10 >= 6 ? 10 : 100;
  c.lineWidth = 1;
  for (let x = PV.ox % (g * PV.s); x < pcw; x += g * PV.s) { const major = Math.round((x - PV.ox) / PV.s) % 100 === 0; c.strokeStyle = major ? '#ececec' : '#f7f7f7'; c.beginPath(); c.moveTo(x, 0); c.lineTo(x, pch); c.stroke(); }
  for (let y = PV.oy % (g * PV.s); y < pch; y += g * PV.s) { const major = Math.round((y - PV.oy) / PV.s) % 100 === 0; c.strokeStyle = major ? '#ececec' : '#f7f7f7'; c.beginPath(); c.moveTo(0, y); c.lineTo(pcw, y); c.stroke(); }
  for (const p of L.pieces) {
    const dim = (sp >= 0 && p.ci !== sp) || (sp < 0 && hv >= 0 && p.ci !== hv);
    if (CUT.view === 'strain') {
      const T = p.r.lt, uv = p.r.uv;
      for (let i = 0; i < T.length / 3; i++) {
        const s1 = p.r.sig[2 * i], s2 = p.r.sig[2 * i + 1], d = s1 - 1 > 1 - s2 ? s1 - 1 : s2 - 1;
        c.fillStyle = rgbStr(strainRGB(d)); c.beginPath();
        for (let k = 0; k < 3; k++) { const j = T[3 * i + k], a = P2(p, [uv[2 * j] * p.s, uv[2 * j + 1] * p.s]); k ? c.lineTo(a[0], a[1]) : c.moveTo(a[0], a[1]); }
        c.closePath(); c.fill(); c.strokeStyle = c.fillStyle; c.lineWidth = 0.5; c.stroke();
      }
    } else {
      c.beginPath(); for (const l of p.stitch) polyPath(c, p, l);
      c.globalAlpha = dim ? 0.22 : 0.62; c.fillStyle = pastel(p.num); c.fill('evenodd'); c.globalAlpha = 1;
    }
    c.beginPath(); for (const l of p.cut) polyPath(c, p, l);
    c.strokeStyle = '#151515'; c.lineWidth = p.ci === sp ? 1.6 : 1; c.stroke();
    if (S.cut.allow > 0) { c.beginPath(); for (const l of p.stitch) polyPath(c, p, l); c.setLineDash([4, 3]); c.strokeStyle = '#4f6df5'; c.lineWidth = 0.8; c.stroke(); c.setLineDash([]); }
  }
  for (const s of L.seams) s.sides.forEach(sd => {
    if (!sd) return;
    const p = sd.piece, col = SEAMCOL[s.id % SEAMCOL.length];
    c.beginPath(); sd.pts.forEach((q, i) => { const a = P2(p, q); i ? c.lineTo(a[0], a[1]) : c.moveTo(a[0], a[1]); });
    c.strokeStyle = col; c.lineWidth = 2; c.stroke();
    if (!sd.mid || sd.len < 25) return;
    const nl = S.cut.allow > 0 ? S.cut.allow : -4;
    c.beginPath();
    for (const q of sd.notches) { const a = P2(p, [q[0], q[1]]), b = P2(p, [q[0] + q[2] * nl, q[1] + q[3] * nl]); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); }
    c.strokeStyle = '#151515'; c.lineWidth = 1; c.stroke();
    const m = P2(p, [sd.mid[0] - sd.mid[2] * 7, sd.mid[1] - sd.mid[3] * 7]);
    c.beginPath(); c.arc(m[0], m[1], 7.5, 0, 6.2832); c.fillStyle = col; c.fill();
    c.fillStyle = '#fff'; c.textAlign = 'center'; c.fillText(String(s.num), m[0], m[1] + 0.5);
  });
  c.font = '600 10px -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif';
  for (const p of L.pieces) { const a = P2(p, p.label); c.fillStyle = '#151515'; c.textAlign = 'center'; c.fillText(p.name, a[0], a[1]); }
  c.font = '500 9px -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif';
  if (!fr) {                                            // seams changed since the render: veil + hint
    c.fillStyle = 'rgba(255,255,255,0.72)'; c.fillRect(0, 0, pcw, pch);
    c.fillStyle = '#151515'; c.textAlign = 'center'; c.fillText('OUT OF DATE — PRESS RENDER CUTS', pcw / 2, 46);
  }
  const L100 = 100 * PV.s, bx = pcw - 14, by = pch - 16;
  c.strokeStyle = '#8e8e8e'; c.fillStyle = '#8e8e8e'; c.lineWidth = 1;
  c.beginPath(); c.moveTo(bx - L100, by); c.lineTo(bx, by); c.moveTo(bx - L100, by - 4); c.lineTo(bx - L100, by + 4); c.moveTo(bx, by - 4); c.lineTo(bx, by + 4); c.stroke();
  c.textAlign = 'right'; c.fillText('100 MM', bx, by - 9);
  if (CUT.view === 'strain') {
    const l = tol();
    for (let i = 0; i < 80; i++) { c.fillStyle = rgbStr(strainRGB((i / 79 - 0.5) * 4 * l)); c.fillRect(14 + i * 2, by - 3, 2, 6); }
    c.fillStyle = '#8e8e8e'; c.textAlign = 'left'; c.fillText('TIGHT', 14, by - 11); c.textAlign = 'right'; c.fillText('LOOSE', 174, by - 11);
    c.textAlign = 'center'; c.fillText(`±${S.cut.lim} % LIMIT`, 94, by - 11);
    c.fillStyle = '#151515'; c.fillRect(14 + 40 - 1, by - 5, 1, 10); c.fillRect(14 + 120 - 1, by - 5, 1, 10);
  }
}
pc.addEventListener('wheel', e => {
  e.preventDefault();
  const r = pc.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top, f = Math.exp(-e.deltaY * 0.0015);
  const ns = Math.max(0.01, Math.min(20, PV.s * f)); PV.ox = x - (x - PV.ox) * ns / PV.s; PV.oy = y - (y - PV.oy) * ns / PV.s; PV.s = ns; draw2D();
}, { passive: false });
pc.addEventListener('pointerdown', e => { pc.setPointerCapture(e.pointerId); pdrag = { x: e.clientX, y: e.clientY, sx: e.clientX, sy: e.clientY }; pc.style.cursor = 'grabbing'; });
pc.addEventListener('pointermove', e => {
  if (pdrag) { PV.ox += e.clientX - pdrag.x; PV.oy += e.clientY - pdrag.y; pdrag.x = e.clientX; pdrag.y = e.clientY; draw2D(); return; }
  if (!CUT.LY || !fresh()) return;
  const r = pc.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;
  const p = CUT.LY.pieces.find(q => inPiece(q, x, y)), hv = p ? p.ci : -1;
  if (hv !== CUT.hover) { CUT.hover = hv; if (CUT.view === 'parts') recolor(); draw2D(); }
});
pc.addEventListener('pointerup', e => {
  pc.style.cursor = 'grab';
  const d = pdrag; pdrag = null; if (!d || Math.hypot(e.clientX - d.sx, e.clientY - d.sy) > 4 || !CUT.LY || !fresh()) return;
  const r = pc.getBoundingClientRect(), p = CUT.LY.pieces.find(q => inPiece(q, e.clientX - r.left, e.clientY - r.top));
  CUT.sel = p ? { type: 'piece', c: p.ci } : null;
  syncCutSel(); recolor(); updateSeamLines(); draw2D();
});
pc.addEventListener('pointerleave', () => { if (CUT.hover >= 0) { CUT.hover = -1; recolor(); draw2D(); } });
$('pFit').addEventListener('click', patFit);
new ResizeObserver(() => { if (S.stage === 'cut') patResize(); }).observe($('pat'));

/* ---------- export (renders first if the seams changed) ---------- */
async function readyPattern() {
  if (CUT.stale || !CUT.LY) await renderCuts();
  if (!CUT.LY || !CUT.LY.pieces.length) { setStatus('NO FLAT PIECES TO EXPORT'); return false; }
  return true;
}
$('btnSvg').addEventListener('click', async () => {
  if (!(await readyPattern())) return;
  downloadBlob(new Blob([CC.svg(CUT.LY, patOpts())], { type: 'image/svg+xml' }), 'blob_cutter_pattern.svg');
  setStatus('SVG EXPORTED · 1:1 MM');
});
$('btnInf').addEventListener('click', async () => {
  if (!(await readyPattern())) return;
  const j = CC.inflate(CUT.RA, CUT.LY, mmU(), pastel);
  downloadBlob(new Blob([JSON.stringify(j, null, 1)], { type: 'application/json' }), 'blob_cutter_inflate.json');
  setStatus(`INFLATE PROJECT · ${j.panels.length} PIECES · ${j.seams.length} SEAMS`);
});

/* ---------- settings ---------- */
const later = (() => { let t = 0; return fn => { clearTimeout(t); t = setTimeout(fn, 160); }; })();
bind('sCb', 'vCb', v => v.toFixed(2), v => { S.cut.bias = v; if (S.stage === 'cut') later(cutRun); });
bind('sCr', 'vCr', v => v + ' / UNIT', v => { S.cut.res = v; });
$('sCr').addEventListener('change', () => { if (S.stage !== 'cut') return; setStatus('REBUILDING MESH…'); setTimeout(() => { try { cutBake(); cutRun(); } catch (err) { console.error(err); setStatus('MESH BUILD FAILED'); } }, 30); });
bind('sCs', 'vCs', v => v + ' MM', v => { S.cut.size = v; if (CUT.RA) relayout(); if (CUT.view === 'curv') recolor(); });
bind('sCe', 'vCe', v => (v > 0 ? '+' : '') + v + ' %', v => { S.cut.ease = v; if (CUT.RA) relayout(); });
bind('sCf', 'vCf', v => v.toFixed(2), v => { S.cut.fid = v; if (CUT.A) { setStale(true); draw2D(); cutInfo(); } });
bind('sCl', 'vCl', v => v + ' %', v => { S.cut.lim = v; recolor(); cutInfo(); draw2D(); });
bind('sCa', 'vCa', v => v + ' MM', v => { S.cut.allow = v; if (CUT.RA) relayout(); });
bind('sCn', 'vCn', v => v ? v + ' MM' : 'OFF', v => { S.cut.notch = v; if (CUT.RA) relayout(); });
bind('sCk', 'vCk', v => v + ' MM', v => { S.cut.knot = v; if (S.stage === 'cut') later(cutRun); });
$('matSel').addEventListener('change', e => {
  S.cut.mat = e.target.value; const m = MATS[S.cut.mat]; if (!m) return;
  for (const [id, v] of [['sCl', m[0]], ['sCf', m[1]]]) { $(id).value = v; $(id).dispatchEvent(new Event('input')); }
});
$('sCl').addEventListener('input', () => { const m = MATS[S.cut.mat]; if (m && m[0] !== S.cut.lim) { S.cut.mat = 'custom'; $('matSel').value = 'custom'; } });
function set2D(on) { CUT.show2d = on; $('pat').hidden = !on; viewShift(); $('cpOn').classList.toggle('on', on); $('cpOff').classList.toggle('on', !on); if (on) patResize(); }
$('cpOn').addEventListener('click', () => set2D(true));
$('cpOff').addEventListener('click', () => set2D(false));

/* ---------- stage switching ---------- */
function cutReset() {
  CUT.M = null; CUT.A = null; CUT.RA = null; CUT.LY = null; CUT.FR = []; CUT.cache.clear(); CUT.gen++; CUT.busy = false; CUT.draw = null; CUT.sel = null; CUT.undo = []; CUT.patFitted = false; CUT.prop = []; CUT.triDev = null;
  $('btnCuts').disabled = false; $('cutsTxt').textContent = 'RENDER CUTS'; syncProps();
  if (CUT.obj) CUT.obj.visible = false;
  for (const o of CUT3D()) o.visible = false;
}
function setStage(st) {
  S.stage = st; document.body.classList.toggle('cut', st === 'cut');
  $('stSculpt').classList.toggle('on', st === 'sculpt'); $('stCut').classList.toggle('on', st === 'cut');
  const cut = st === 'cut', hq = !!hqMesh && S.hqFresh;
  if (CUT.obj) CUT.obj.visible = cut;
  if (!cut) { for (const o of CUT3D()) o.visible = false; $('ctip').hidden = true; }
  prevMesh.visible = negMesh.visible = !cut && !hq;
  if (hqMesh) hqMesh.visible = !cut && hq;
  for (const k in outLines) outLines[k].visible = S.outline && !cut;
  $('pat').hidden = !cut || !CUT.show2d;
  canvas.style.cursor = cut && CUT.tool === 'pen' ? 'crosshair' : '';
  $('detNote').textContent = cut ? 'Back in SCULPT, every change rebuilds the cut mesh — seams are kept and re-snapped.' : '';
  syncCbar(); refApply();
  setTab(cut ? 'cut' : S.tab === 'cut' ? 'form' : S.tab);
  cutResize();
}
function enterCut() {
  if (S.stage === 'cut') return;
  if (!S.blobs.some(b => !b.neg)) { setStatus('NOTHING SOLID TO CUT'); $('detNote').textContent = 'Nothing solid to cut.'; return; }
  if (S.drawing) endDrawMode();
  if (S.pulling) endPull();
  select(null);
  $('detNote').textContent = 'BUILDING CUT MESH…';
  setTimeout(() => {
    try {
      const freshMesh = !CUT.M || CUT.M.rev !== S.rev || CUT.M.res !== S.cut.res;
      if (freshMesh) { cutBake(); CUT.patFitted = false; }
      setStage('cut'); cutRun(); syncProps();
    } catch (err) { console.error(err); $('detNote').textContent = 'MESH BUILD FAILED — LOWER MESH RES'; }
  }, 30);
}
$('stCut').addEventListener('click', enterCut);
$('stSculpt').addEventListener('click', () => { if (S.stage === 'cut') { CUT.draw = null; CUT.prop = []; syncProps(); setStage('sculpt'); } });
setView3('parts');

/* ============================================================
   REFERENCE MESH  (uploaded .glb -> signed distance grid -> behaves like a blob)
   GUIDE = ghost only, CUT = negative shape (carves the blobs), ADD = solid that blobs merge into
============================================================ */
const REF = { geo: null, name: '', buf: null, grid: null, ghost: null };
S.ref = { mode: 'guide', ghost: true, x: 0, y: 0, z: 0, s: 1, rx: 0, ry: 0, rz: 0, off: 0, res: 100, mat: { color: '#9aa4b4', op: 0.3, sm: 0.4, me: 0, wire: false } };

// closest point on a triangle (Ericson) -> writes CP
const CP = [0, 0, 0];
function cpTri(px, py, pz, ax, ay, az, bx, by, bz, cx, cy, cz) {
  const abx = bx - ax, aby = by - ay, abz = bz - az, acx = cx - ax, acy = cy - ay, acz = cz - az;
  const apx = px - ax, apy = py - ay, apz = pz - az;
  const d1 = abx * apx + aby * apy + abz * apz, d2 = acx * apx + acy * apy + acz * apz;
  if (d1 <= 0 && d2 <= 0) { CP[0] = ax; CP[1] = ay; CP[2] = az; return; }
  const bpx = px - bx, bpy = py - by, bpz = pz - bz;
  const d3 = abx * bpx + aby * bpy + abz * bpz, d4 = acx * bpx + acy * bpy + acz * bpz;
  if (d3 >= 0 && d4 <= d3) { CP[0] = bx; CP[1] = by; CP[2] = bz; return; }
  const vc = d1 * d4 - d3 * d2;
  if (vc <= 0 && d1 >= 0 && d3 <= 0) { const v = d1 / (d1 - d3); CP[0] = ax + abx * v; CP[1] = ay + aby * v; CP[2] = az + abz * v; return; }
  const cpx = px - cx, cpy = py - cy, cpz = pz - cz;
  const d5 = abx * cpx + aby * cpy + abz * cpz, d6 = acx * cpx + acy * cpy + acz * cpz;
  if (d6 >= 0 && d5 <= d6) { CP[0] = cx; CP[1] = cy; CP[2] = cz; return; }
  const vb = d5 * d2 - d1 * d6;
  if (vb <= 0 && d2 >= 0 && d6 <= 0) { const w = d2 / (d2 - d6); CP[0] = ax + acx * w; CP[1] = ay + acy * w; CP[2] = az + acz * w; return; }
  const va = d3 * d6 - d5 * d4;
  if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
    const w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
    CP[0] = bx + (cx - bx) * w; CP[1] = by + (cy - by) * w; CP[2] = bz + (cz - bz) * w; return;
  }
  const den = 1 / (va + vb + vc), v = vb * den, w = vc * den;
  CP[0] = ax + abx * v + acx * w; CP[1] = ay + aby * v + acy * w; CP[2] = az + abz * v + acz * w;
}

// mesh -> signed distance grid. Open boundaries (neck, wrist ...) are capped with a fan, so the mesh counts as a solid.
function buildRefSDF(geo, res) {
  const P = geo.attributes.position.array, I = geo.index ? geo.index.array : null, nT = (I ? I.length : P.length / 3) / 3;
  geo.computeBoundingBox();
  const bb = geo.boundingBox, ext = Math.max(bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z);
  const eps = ext * 1e-5, wmap = new Map(), W = [], wid = new Int32Array(P.length / 3);
  for (let i = 0; i < wid.length; i++) {                             // weld vertices by position (UV seams split them)
    const k = Math.round(P[i * 3] / eps) + ',' + Math.round(P[i * 3 + 1] / eps) + ',' + Math.round(P[i * 3 + 2] / eps);
    let id = wmap.get(k); if (id === undefined) { id = W.length / 3; wmap.set(k, id); W.push(P[i * 3], P[i * 3 + 1], P[i * 3 + 2]); }
    wid[i] = id;
  }
  const tri = [];
  for (let t = 0; t < nT; t++) {
    const a = wid[I ? I[t * 3] : t * 3], b = wid[I ? I[t * 3 + 1] : t * 3 + 1], c = wid[I ? I[t * 3 + 2] : t * 3 + 2];
    if (a !== b && b !== c && a !== c) tri.push(a, b, c);
  }
  const nV = W.length / 3, ec = new Map();                           // boundary edges -> cap fans
  const ek = (a, b) => a < b ? a * nV + b : b * nV + a;
  for (let t = 0; t < tri.length; t += 3) for (let e = 0; e < 3; e++) {
    const k = ek(tri[t + e], tri[t + (e + 1) % 3]); ec.set(k, (ec.get(k) || 0) + 1);
  }
  const par = new Int32Array(nV).map((_, i) => i), find = x => { while (par[x] !== x) x = par[x] = par[par[x]]; return x; };
  const bnd = [];
  for (let t = 0; t < tri.length; t += 3) for (let e = 0; e < 3; e++) {
    const a = tri[t + e], b = tri[t + (e + 1) % 3];
    if (ec.get(ek(a, b)) === 1) { bnd.push(a, b); par[find(a)] = find(b); }
  }
  const cen = new Map(), seen = new Set();
  for (let i = 0; i < bnd.length; i++) {
    const v = bnd[i]; if (seen.has(v)) continue; seen.add(v);
    const r = find(v); let c = cen.get(r); if (!c) cen.set(r, c = [0, 0, 0, 0]);
    c[0] += W[v * 3]; c[1] += W[v * 3 + 1]; c[2] += W[v * 3 + 2]; c[3]++;
  }
  const cidx = new Map(); let capN = 0;
  for (const [r, c] of cen) { cidx.set(r, W.length / 3); W.push(c[0] / c[3], c[1] / c[3], c[2] / c[3]); }
  for (let i = 0; i < bnd.length; i += 2) { tri.push(bnd[i + 1], bnd[i], cidx.get(find(bnd[i]))); capN++; }

  const h = ext / res, pad = 8 * h;
  const ox = bb.min.x - pad, oy = bb.min.y - pad, oz = bb.min.z - pad;
  const nx = Math.ceil((bb.max.x - bb.min.x + 2 * pad) / h) + 1, ny = Math.ceil((bb.max.y - bb.min.y + 2 * pad) / h) + 1, nz = Math.ceil((bb.max.z - bb.min.z + 2 * pad) / h) + 1;
  const N = nx * ny * nz, D2 = new Float32Array(N).fill(1e12), neg = new Uint8Array(N), BAND = 2;
  for (let t = 0; t < tri.length; t += 3) {
    const a = tri[t] * 3, b = tri[t + 1] * 3, c = tri[t + 2] * 3;
    const ax = W[a], ay = W[a + 1], az = W[a + 2], bx = W[b], by = W[b + 1], bz = W[b + 2], cx = W[c], cy = W[c + 1], cz = W[c + 2];
    let nxx = (by - ay) * (cz - az) - (bz - az) * (cy - ay), nyy = (bz - az) * (cx - ax) - (bx - ax) * (cz - az), nzz = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
    const nl = Math.hypot(nxx, nyy, nzz); if (nl < 1e-14) continue; nxx /= nl; nyy /= nl; nzz /= nl;
    const i0 = Math.max(0, Math.floor((Math.min(ax, bx, cx) - ox) / h) - BAND), i1 = Math.min(nx - 1, Math.ceil((Math.max(ax, bx, cx) - ox) / h) + BAND);
    const j0 = Math.max(0, Math.floor((Math.min(ay, by, cy) - oy) / h) - BAND), j1 = Math.min(ny - 1, Math.ceil((Math.max(ay, by, cy) - oy) / h) + BAND);
    const k0 = Math.max(0, Math.floor((Math.min(az, bz, cz) - oz) / h) - BAND), k1 = Math.min(nz - 1, Math.ceil((Math.max(az, bz, cz) - oz) / h) + BAND);
    for (let k = k0; k <= k1; k++) for (let j = j0; j <= j1; j++) {
      let p = i0 + nx * (j + ny * k);
      for (let i = i0; i <= i1; i++, p++) {
        const px = ox + i * h, py = oy + j * h, pz = oz + k * h;
        cpTri(px, py, pz, ax, ay, az, bx, by, bz, cx, cy, cz);
        const dx = px - CP[0], dy = py - CP[1], dz = pz - CP[2], d2 = dx * dx + dy * dy + dz * dz;
        if (d2 < D2[p]) { D2[p] = d2; neg[p] = (dx * nxx + dy * nyy + dz * nzz) < 0 ? 1 : 0; }
      }
    }
  }
  const D = new Float32Array(N);
  for (let p = 0; p < N; p++) D[p] = D2[p] > 1e11 ? 1e9 : Math.sqrt(D2[p]);
  // fill the far field (chamfer propagation) - only the band is exact, which is all the blend ever needs
  const w1 = h, w2 = h * 1.4142, w3 = h * 1.7321, sy = nx, sz = nx * ny;
  const offs = [];
  for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
    if (!dx && !dy && !dz) continue;
    const q = dx + dy * sy + dz * sz, w = [0, w1, w2, w3][Math.abs(dx) + Math.abs(dy) + Math.abs(dz)];
    offs.push([dx, dy, dz, q, w, (dz < 0 || (dz === 0 && (dy < 0 || (dy === 0 && dx < 0))))]);
  }
  for (const fwd of [true, false]) {
    const zs = fwd ? [0, nz, 1] : [nz - 1, -1, -1], ys = fwd ? [0, ny, 1] : [ny - 1, -1, -1], xs = fwd ? [0, nx, 1] : [nx - 1, -1, -1];
    const use = offs.filter(o => o[5] === fwd);
    for (let k = zs[0]; k !== zs[1]; k += zs[2]) for (let j = ys[0]; j !== ys[1]; j += ys[2]) for (let i = xs[0]; i !== xs[1]; i += xs[2]) {
      const p = i + nx * (j + ny * k); let best = D[p];
      for (let u = 0; u < use.length; u++) {
        const o = use[u], ii = i + o[0], jj = j + o[1], kk = k + o[2];
        if (ii < 0 || jj < 0 || kk < 0 || ii >= nx || jj >= ny || kk >= nz) continue;
        const v = D[p + o[3]] + o[4]; if (v < best) best = v;
      }
      D[p] = best;
    }
  }
  // inside / outside: flood fill from the corner, voxels touching the surface are walls
  const wall = 0.75 * h, out = new Uint8Array(N), st = new Int32Array(N); let sp = 0;
  out[0] = 1; st[sp++] = 0;
  while (sp) {
    const p = st[--sp], i = p % nx, j = ((p / nx) | 0) % ny, k = (p / sz) | 0;
    const tryP = q => { if (!out[q] && D[q] >= wall) { out[q] = 1; st[sp++] = q; } };
    if (i > 0) tryP(p - 1); if (i < nx - 1) tryP(p + 1); if (j > 0) tryP(p - sy); if (j < ny - 1) tryP(p + sy); if (k > 0) tryP(p - sz); if (k < nz - 1) tryP(p + sz);
  }
  const F = new Float32Array(N); let inside = 0;
  for (let p = 0; p < N; p++) {
    const isNeg = D[p] < wall ? neg[p] === 1 : !out[p];
    if (isNeg) inside++;
    F[p] = isNeg ? -D[p] : D[p];
  }
  return { nx, ny, nz, ox, oy, oz, h, F, inside: inside / N, capN };
}

function compileRef() {
  const g = REF.grid, r = S.ref;
  if (!g || r.mode === 'guide') return null;
  const q = new THREE.Quaternion().setFromEuler(new THREE.Euler(r.rx * Math.PI / 180, r.ry * Math.PI / 180, r.rz * Math.PI / 180, 'XYZ'));
  const e = new THREE.Matrix4().makeRotationFromQuaternion(q).elements, s = r.s;
  const c = { t: 4, neg: r.mode === 'cut', src: -1, px: r.x, py: r.y, pz: r.z,
    m0: e[0], m1: e[1], m2: e[2], m3: e[4], m4: e[5], m5: e[6], m6: e[8], m7: e[9], m8: e[10],
    isx: 1 / s, rs: s, off: r.off, g: g.F, nx: g.nx, ny: g.ny, nz: g.nz, ox: g.ox, oy: g.oy, oz: g.oz, ih: 1 / g.h, gh: g.h };
  const R = new THREE.Matrix4().makeRotationFromQuaternion(q), v = new THREE.Vector3();
  let x0 = 1e9, y0 = 1e9, z0 = 1e9, x1 = -1e9, y1 = -1e9, z1 = -1e9;
  for (let m = 0; m < 8; m++) {
    v.set(m & 1 ? g.ox + (g.nx - 1) * g.h : g.ox, m & 2 ? g.oy + (g.ny - 1) * g.h : g.oy, m & 4 ? g.oz + (g.nz - 1) * g.h : g.oz).multiplyScalar(s).applyMatrix4(R);
    x0 = Math.min(x0, v.x); y0 = Math.min(y0, v.y); z0 = Math.min(z0, v.z); x1 = Math.max(x1, v.x); y1 = Math.max(y1, v.y); z1 = Math.max(z1, v.z);
  }
  const o = Math.max(0, r.off);
  c.x0 = x0 + r.x - o; c.y0 = y0 + r.y - o; c.z0 = z0 + r.z - o; c.x1 = x1 + r.x + o; c.y1 = y1 + r.y + o; c.z1 = z1 + r.z + o;
  return c;
}
const withRef = cs => { const r = compileRef(); return r ? cs.concat([r]) : cs; };

// trilinear lookup, called from blobDist (t === 4)
function refDist(c, x, y, z) {
  const dx = x - c.px, dy = y - c.py, dz = z - c.pz;
  let gx = ((c.m0 * dx + c.m1 * dy + c.m2 * dz) * c.isx - c.ox) * c.ih;
  let gy = ((c.m3 * dx + c.m4 * dy + c.m5 * dz) * c.isx - c.oy) * c.ih;
  let gz = ((c.m6 * dx + c.m7 * dy + c.m8 * dz) * c.isx - c.oz) * c.ih;
  let e = 0; const mx = c.nx - 1, my = c.ny - 1, mz = c.nz - 1;
  if (gx < 0) { e += gx * gx; gx = 0; } else if (gx > mx) { e += (gx - mx) * (gx - mx); gx = mx; }
  if (gy < 0) { e += gy * gy; gy = 0; } else if (gy > my) { e += (gy - my) * (gy - my); gy = my; }
  if (gz < 0) { e += gz * gz; gz = 0; } else if (gz > mz) { e += (gz - mz) * (gz - mz); gz = mz; }
  let i = gx | 0, j = gy | 0, k = gz | 0;
  if (i > mx - 1) i = mx - 1; if (j > my - 1) j = my - 1; if (k > mz - 1) k = mz - 1;
  const fx = gx - i, fy = gy - j, fz = gz - k, G = c.g, sy = c.nx, sz = c.nx * c.ny, p = i + sy * j + sz * k;
  const a = G[p] + (G[p + 1] - G[p]) * fx, b = G[p + sy] + (G[p + sy + 1] - G[p + sy]) * fx;
  const a2 = G[p + sz] + (G[p + sz + 1] - G[p + sz]) * fx, b2 = G[p + sz + sy] + (G[p + sz + sy + 1] - G[p + sz + sy]) * fx;
  const v = (a + (b - a) * fy) * (1 - fz) + (a2 + (b2 - a2) * fy) * fz;
  return (v + Math.sqrt(e) * c.gh) * c.rs - c.off;
}

/* ---------- loading, ghost display, UI ---------- */
const gltfLoader = new GLTFLoader();
function refApply() {
  const r = S.ref, g = REF.ghost;
  if (!g) return;
  g.visible = !!REF.geo && r.ghost;
  g.position.set(r.x, r.y, r.z); g.scale.setScalar(r.s);
  g.rotation.set(r.rx * Math.PI / 180, r.ry * Math.PI / 180, r.rz * Math.PI / 180);
  const m = r.mat, mt = g.material, tr = m.op < 0.999;
  mt.color.set(m.color); mt.opacity = m.op; mt.roughness = 1 - m.sm; mt.metalness = m.me; mt.wireframe = !!m.wire;
  if (mt.transparent !== tr) { mt.transparent = tr; mt.needsUpdate = true; }
  mt.depthWrite = !tr;
}
function refUI() {
  const has = !!REF.geo;
  $('refCtl').hidden = !has; $('refClear').hidden = !has;
  $('refName').textContent = has ? REF.name : 'NO MESH LOADED';
  ['guide', 'cut', 'add'].forEach(m => $('rm_' + m).classList.toggle('on', S.ref.mode === m));
  const mm = S.ref.mat; $('rmColor').value = mm.color;
  for (const [id, key] of [['sRmO', 'op'], ['sRmS', 'sm'], ['sRmM', 'me']]) { $(id).value = mm[key]; $(id).dispatchEvent(new Event('input')); }
  $('rwSolid').classList.toggle('on', !mm.wire); $('rwWire').classList.toggle('on', !!mm.wire);
  $('rgOn').classList.toggle('on', S.ref.ghost); $('rgOff').classList.toggle('on', !S.ref.ghost);
  for (const [id, key] of [['sRs', 's'], ['sRx', 'x'], ['sRy', 'y'], ['sRz', 'z'], ['sRrx', 'rx'], ['sRry', 'ry'], ['sRrz', 'rz'], ['sRo', 'off'], ['sRres', 'res']]) {
    $(id).value = S.ref[key]; $(id).dispatchEvent(new Event('input'));
  }
}
function refSet(geo, name, buf, params) {
  if (REF.ghost) { scene.remove(REF.ghost); REF.ghost.material.dispose(); }
  REF.geo = geo; REF.name = name; REF.buf = buf; REF.grid = null;
  geo.computeBoundingBox(); geo.computeVertexNormals();
  REF.ghost = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x9aa4b4, roughness: 0.6, metalness: 0, transparent: true, opacity: 0.3, depthWrite: false, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: 3, polygonOffsetUnits: 3 }));
  REF.ghost.raycast = () => {}; REF.ghost.renderOrder = 4; scene.add(REF.ghost);
  if (params) { Object.assign(S.ref, params); S.ref.mat = Object.assign({ color: '#9aa4b4', op: 0.3, sm: 0.4, me: 0, wire: false }, params.mat); }
  refApply(); refUI(); refBuild();
}
function refBuild() {
  if (!REF.geo) return;
  $('refInfo').textContent = 'BUILDING DISTANCE FIELD…';
  setTimeout(() => {
    try {
      const t0 = performance.now();
      REF.grid = buildRefSDF(REF.geo, S.ref.res);
      const g = REF.grid;
      $('refInfo').textContent = (g.inside < 0.0005 ? 'OPEN MESH — ACTS AS THIN SHELL (USE OFFSET)' : 'SOLID' + (g.capN ? ` · ${g.capN} HOLE EDGES CLOSED` : '')) + ` · ${Math.round(performance.now() - t0)} MS`;
      markDirty();
    } catch (err) { console.error(err); $('refInfo').textContent = 'FIELD BUILD FAILED — LOWER SDF RES'; }
  }, 30);
}
function loadRefBuffer(buf, name, params) {
  return new Promise((res, rej) => gltfLoader.parse(buf.slice(0), '', gltf => {
    gltf.scene.updateMatrixWorld(true);
    const P = [], I = []; let off = 0;
    gltf.scene.traverse(o => {
      if (!o.isMesh || !o.geometry.attributes.position) return;
      const g = o.geometry, pa = g.attributes.position, v = new THREE.Vector3();
      for (let i = 0; i < pa.count; i++) { v.fromBufferAttribute(pa, i).applyMatrix4(o.matrixWorld); P.push(v.x, v.y, v.z); }
      if (g.index) for (let i = 0; i < g.index.count; i++) I.push(g.index.getX(i) + off);
      else for (let i = 0; i < pa.count; i++) I.push(i + off);
      off += pa.count;
    });
    if (!I.length) { rej(new Error('no mesh')); return; }
    const geo = new THREE.BufferGeometry();
    geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(P), 3));
    geo.setIndex(new THREE.BufferAttribute(new Uint32Array(I), 1));
    geo.computeBoundingBox();
    const bb = geo.boundingBox, c = bb.getCenter(new THREE.Vector3()), md = Math.max(bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z);
    geo.translate(-c.x, -c.y, -c.z);                                 // centred; initial scale fits it into ~2 units
    refSet(geo, name, buf, params || { s: 2 / md, x: 0, y: 0, z: 0, rx: 0, ry: 0, rz: 0, off: 0 });
    res();
  }, rej));
}
function refClear() {
  if (REF.ghost) { scene.remove(REF.ghost); REF.ghost.material.dispose(); }
  REF.geo = REF.ghost = REF.grid = REF.buf = null; REF.name = '';
  $('refInfo').textContent = ''; refUI(); markDirty();
}
$('refFile').addEventListener('change', e => {
  const f = e.target.files[0]; if (!f) return;
  f.arrayBuffer().then(b => loadRefBuffer(b, f.name)).then(() => { if (S.ref.mode === 'guide') { S.ref.mode = 'cut'; refUI(); } markDirty(); })
    .catch(err => { console.error(err); $('refInfo').textContent = 'COULD NOT READ MESH — USE .GLB'; });
  e.target.value = '';
});
$('refLoad').addEventListener('click', () => $('refFile').click());
$('refClear').addEventListener('click', refClear);
$('refReset').addEventListener('click', () => {
  if (!REF.geo) return; const bb = REF.geo.boundingBox, md = Math.max(bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z);
  Object.assign(S.ref, { s: 2 / md, x: 0, y: 0, z: 0, rx: 0, ry: 0, rz: 0, off: 0 }); refApply(); refUI(); markDirty();
});
['guide', 'cut', 'add'].forEach(m => $('rm_' + m).addEventListener('click', () => { S.ref.mode = m; refUI(); markDirty(); }));
$('rgOn').addEventListener('click', () => { S.ref.ghost = true; refApply(); refUI(); });
$('rgOff').addEventListener('click', () => { S.ref.ghost = false; refApply(); refUI(); });
const refSlider = (id, vid, key, fmt) => bind(id, vid, fmt, v => { S.ref[key] = v; refApply(); if (REF.grid) markDirty(); });
const refMat = (id, vid, key) => bind(id, vid, v => v.toFixed(2), v => { S.ref.mat[key] = v; refApply(); });
refMat('sRmO', 'vRmO', 'op'); refMat('sRmS', 'vRmS', 'sm'); refMat('sRmM', 'vRmM', 'me');
$('rmColor').addEventListener('input', e => { S.ref.mat.color = e.target.value; refApply(); });
$('rwSolid').addEventListener('click', () => { S.ref.mat.wire = false; refApply(); refUI(); });
$('rwWire').addEventListener('click', () => { S.ref.mat.wire = true; refApply(); refUI(); });
refSlider('sRs', 'vRs', 's', v => v.toFixed(2));
refSlider('sRx', 'vRx', 'x', v => v.toFixed(2)); refSlider('sRy', 'vRy', 'y', v => v.toFixed(2)); refSlider('sRz', 'vRz', 'z', v => v.toFixed(2));
refSlider('sRrx', 'vRrx', 'rx', v => v + '°'); refSlider('sRry', 'vRry', 'ry', v => v + '°'); refSlider('sRrz', 'vRrz', 'rz', v => v + '°');
refSlider('sRo', 'vRo', 'off', v => v.toFixed(3));
bind('sRres', 'vRres', v => v + ' / LONGEST SIDE', v => { S.ref.res = v; });
$('sRres').addEventListener('change', refBuild);
const b64 = buf => { let s = ''; const u = new Uint8Array(buf); for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode.apply(null, u.subarray(i, i + 0x8000)); return btoa(s); };
const unb64 = s => { const b = atob(s), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u.buffer; };
refUI();
function setTab(t) {
  S.tab = t;
  ['form', 'ref', 'cut', 'look', 'file'].forEach(n => document.body.classList.toggle('tab-' + n, n === t));
  document.querySelectorAll('[data-tab]').forEach(b => b.classList.toggle('on', b.dataset.tab === t));
}
document.querySelectorAll('[data-tab]').forEach(b => b.addEventListener('click', () => setTab(b.dataset.tab)));
setTab('form');

/* ============================================================
   LOOP
============================================================ */
function resize() {
  const w = innerWidth, h = innerHeight;
  renderer.setSize(w, h, false); persp.aspect = w / h; persp.updateProjectionMatrix();
  const hh = ortho.top; ortho.left = -hh * w / h; ortho.right = hh * w / h; ortho.updateProjectionMatrix();
  cutResize();
}
addEventListener('resize', resize); resize();

let frames = 0, tFps = performance.now(), fps = 0;
function loop() {
  requestAnimationFrame(loop);
  controls.update();
  if (camera === ortho && snapQ && camera.quaternion.angleTo(snapQ) > 0.002) leavePerspective();   // rotating = back to perspective
  lightRig.position.copy(camera.position); lightRig.quaternion.copy(camera.quaternion);
  if (S.dirty) { remeshPreview(); rebuildOutlines(); S.dirty = false; }
  updateGizmo();
  renderer.render(scene, camera);
  frames++;
  const now = performance.now();
  if (now - tFps > 500) {
    fps = Math.round(frames * 1000 / (now - tFps)); frames = 0; tFps = now;
    $('stats').textContent = `${fps} FPS · ${fmtN(lastTris)} TRIS · ${lastMs.toFixed(0)} MS`;
  }
}

/* start with one sphere */
const first = makeBlob('sphere', new V3(0, 0.5, 0));
S.blobs.push(first);
setShading(false); setGrid(true); applyMaterial(); syncSym(); updateBar(); updateHint();
loop();

// handy for debugging from the console
window.__blob = { S, makeBlob, updateSpline, select, markDirty, renderHQ, THREE, get REF() { return REF; }, get camera() { return camera; }, persp, ortho, setView, get M() { return CUT.M; }, CUT, cutRun, enterCut, setView3, setTool, renderCuts, suggest, autoPlan, gizmo, controls };
</script>
</body>
</html>