BUILD FORGEWOOD · PLAY · MAKE
`; if(mode==='dl'){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([html],{type:'text/html'}));a.download=pl.g.n.replace(/\W+/g,'_')+'_build_plan.html';a.click();return html} const w=window.open('','_blank');if(w){w.document.open();w.document.write(html);w.document.close()}else{const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([html],{type:'text/html'}));a.download=pl.g.n.replace(/\W+/g,'_')+'_build_plan.html';a.click()}return html}; // ===== Room photo: set scale from a known object, mark the space, preview the build in the photo. // Rebuilt 2026-11-17 (swarm pass): explicit step state, adjustable + second reference with a // disagreement readout (FORM FORGE calibration pattern), wall/floor planes, one crash-proof // applySpace() entry, repaint on every visit, honest copy. Still client-side only. const Space=(()=>{const $=s=>document.querySelector(s); let img=null,pts=[],refIn=null,ppi=null,pts2=[],refIn2=null,ppi2=null,seg2=false,rect=null,plane='wall',drag=null,dragPt=null,showBuild=true,yawDeg=0,opacity=0.92,err=''; let corners=[],cornerMode=false,rectW=36,rectH=80,room=null,bpTool=null,bpDrag=null,bpView=null,lastFit=null; const REFS=[['Door height',80],['Door width 36"',36],['Door width 32"',32],['Door width 30"',30],['Door width 28"',28],['Outlet cover',4.5],['Letter paper (long side)',11],['Counter top height',36]]; const LOCAL=/^(localhost|127\.0\.0\.1)$/.test(location.hostname)||location.protocol==='file:'; const step=()=>!img?'photo':!ppi?'scale':!rect?'box':'ready'; const ppiEff=()=>ppi2?(ppi+ppi2)/2:ppi; // ---- perspective rectangle (homography): the user taps the 4 corners of a rectangle whose // real size they type in (a door is 36 x 80). One measurement model: when the rectangle is // marked, box inches come from the homography inverse; otherwise from the tapped segment. const orderQuad=q=>{const byY=[...q].sort((a,b)=>b[1]-a[1]);const bot=byY.slice(0,2).sort((a,b)=>a[0]-b[0]);const top=byY.slice(2).sort((a,b)=>a[0]-b[0]);return[bot[0],bot[1],top[1],top[0]]}; // BL,BR,TR,TL in photo coords function wallH(){if(corners.length!==4||!(rectW>0)||!(rectH>0))return null;const d=orderQuad(corners);return BF.H.solve([[0,0],[rectW,0],[rectW,rectH],[0,rectH]],d)} function boxInches(){if(!rect)return null;const H=wallH(); if(H){const Hi=BF.H.invert(H);if(Hi){const cs=[[rect.x,rect.y],[rect.x+rect.w,rect.y],[rect.x+rect.w,rect.y+rect.h],[rect.x,rect.y+rect.h]].map(p=>BF.H.apply(Hi,p)); if(cs.every(Boolean)){const xs=cs.map(c=>c[0]),ys=cs.map(c=>c[1]);const x0=Math.min(...xs),x1=Math.max(...xs),y0=Math.min(...ys),y1=Math.max(...ys);return{w:x1-x0,h:y1-y0,x:x0,y:y0,src:'perspective rectangle'}}}} const pe=ppiEff();if(!pe)return null;return{w:rect.w/pe,h:rect.h/pe,x:null,y:null,src:'tapped reference'}} function syncCornerPpi(){if(corners.length!==4||ppi||!(rectH>0))return;const d=orderQuad(corners); const l=Math.hypot(d[3][0]-d[0][0],d[3][1]-d[0][1]),r=Math.hypot(d[2][0]-d[1][0],d[2][1]-d[1][1]);if(l<40||r<40)return; ppi=(l+r)/2/rectH;refIn=rectH;const sc=$('#spScale');if(sc)sc.textContent=`Scale set: ${ppi.toFixed(2)} photo pixels per inch (from the marked rectangle's ${rectH}" height). Accurate on that wall.`; const rr=$('#spRefRow');if(rr)rr.style.display='';const rv=$('#spRefVal');if(rv)rv.value=rectH} // ---- room blueprint state (persisted in BF.UI.S.room via the app's own save) function roomGet(){if(room)return room;let r=null;try{r=BF.UI.S.room}catch(e){} room=r&&Array.isArray(r.walls)?JSON.parse(JSON.stringify(r)):{ceiling:96,targetWall:0,buildAt:null,walls:[]}; if(room.buildAt===undefined)room.buildAt=null;if(!room.ceiling)room.ceiling=96;return room} function roomSave(){try{BF.UI.S.room=JSON.parse(JSON.stringify(roomGet()));BF.UI.save()}catch(e){}} function planInfo(){const pl=BF.UI.plan;if(!pl)return null;const B=BF.r3d.bounds(pl.K.parts); return{pW:B.hi[0]-B.lo[0],pD:B.hi[2]-B.lo[2],pH:B.hi[1]-B.lo[1],zone:pl.K.zone?{w:pl.K.zone.w,d:pl.K.zone.d}:null,name:pl.g.n,gid:pl.gid}} const bpAtEff=info=>{const r=roomGet();if(r.buildAt!=null)return r.buildAt;const w=r.walls[r.targetWall||0];if(!w||!info)return 0;return Math.max(0,(w.len-info.pW)/2)}; const bpX=px=>bpView.ox+(px-bpView.lo0)*bpView.sc, bpY=py=>bpView.oyT+(bpView.hi1-py)*bpView.sc; const bpInv=(cx,cy)=>[(cx-bpView.ox)/bpView.sc+bpView.lo0, bpView.hi1-(cy-bpView.oyT)/bpView.sc]; function draw(){const box=$('#space');if(!box.dataset.done){box.dataset.done=1;box.innerHTML=`
room photo

Snap the space

Take a photo of the wall or floor where the build will go. Tap both ends of something you know the size of (most doors are 80" tall — and you can correct the number), then drag a box where the build should go. BUILD FORGE measures that marked area, sizes your plan to it, and previews the build in your photo at true scale.

No photo yet

The preview is a true-scale front view placed in your photo. It will not match your photo's angle exactly (nudge it with Preview angle), and it draws over furniture. Measure the final spot with a tape before cutting.

1 · Set the scale

Tap both ends of a known object — or drag straight across it — then pick what it is. Wrong door size? Correct the number; the scale updates live.

${REFS.map(([n,v])=>``).join('')}

2 · Mark the space

The box sits on one plane — tell the app which, then drag the box.

3 · Project

${LOCAL?`

Photo understanding (optional)

`:`

Photo understanding needs the optional desktop companion (a local Ollama model) — it is not available on iPad or on the hosted site. The measure-and-preview tools above work fully on this device.

`}

Accuracy: the measurement is right for things in the same plane and at the same distance as the reference object. Measure the final spot with a tape before cutting.

room blueprint

4 · Blueprint the room

Walk the room wall by wall. For each wall, the app proposes a length and height from your calibrated photo — then you confirm or correct every number. Nothing is measured that you didn't point at, and no number is final until you confirm it. Walls join at right angles, in the order you add them. The blueprint is saved on this device with your project and re-opens here.

Openings:Tap a wall in the plan to put the build on it; drag the build along its wall.
`; const load=f=>{if(!f)return;err='';const done=c=>{img=c;pts=[];pts2=[];refIn=null;ppi=null;refIn2=null;ppi2=null;rect=null;seg2=false;corners=[];cornerMode=false;$('#spE').style.display='none';$('#spErr').textContent='';paint();BF.UI.toast('Tap both ends of something you know the size of')}; const fail=()=>{err='That photo could not be read — try a JPEG or PNG, or a smaller photo.';const e=$('#spErr');if(e)e.textContent=err}; const shrink=src=>{const s=Math.min(1,2048/Math.max(src.width,src.height));const c=document.createElement('canvas');c.width=Math.round(src.width*s);c.height=Math.round(src.height*s);c.getContext('2d').drawImage(src,0,0,c.width,c.height);done(c)}; if(window.createImageBitmap){createImageBitmap(f,{imageOrientation:'from-image'}).then(b=>shrink(b)).catch(()=>{const u=URL.createObjectURL(f);const im=new Image();im.onload=()=>shrink(im);im.onerror=fail;im.src=u})} else{const u=URL.createObjectURL(f);const im=new Image();im.onload=()=>shrink(im);im.onerror=fail;im.src=u}}; $('#spCam').onchange=e=>load(e.target.files[0]);$('#spFile').onchange=e=>load(e.target.files[0]); const applyRef=(which,v)=>{const P=which===2?pts2:pts;if(P.length<2){BF.UI.toast('First tap two points on the photo');return}const d=Math.hypot(P[1][0]-P[0][0],P[1][1]-P[0][1]);if(d<40){BF.UI.toast('Those points are too close together to measure accurately — pick a bigger object');return} if(which===2){refIn2=v;ppi2=d/v;seg2=false;$('#spScale2').textContent=`Second scale: ${ppi2.toFixed(2)} px/in.`+disagree()}else{refIn=v;ppi=d/v;$('#spRefRow').style.display='';$('#spRefVal').value=v;$('#spScale').textContent=`Scale set: ${ppi.toFixed(2)} photo pixels per inch (from ${v}"). Accurate on that object's plane.`+disagree()}paint()}; const disagree=()=>{if(!ppi||!ppi2)return'';const m=(ppi+ppi2)/2,d=Math.abs(ppi-ppi2)/m*100;return d>10?` Warning: your two references disagree by ${d.toFixed(0)}% — they may not be on the same plane. The average is used.`:` References agree within ${d.toFixed(0)}%.`}; $('#spRefs').querySelectorAll('[data-r]').forEach(b=>b.onclick=()=>{if(b.dataset.r==='custom'){$('#spRefRow').style.display='';$('#spRefVal').value=24;$('#spRefVal').focus();if(pts.length===2)applyRef(1,24);return}applyRef(1,+b.dataset.r)}); $('#spRefs2').querySelectorAll('[data-r]').forEach(b=>b.onclick=()=>applyRef(2,+b.dataset.r)); $('#spRefVal').onchange=e=>{const v=+e.target.value;if(v>0&&pts.length===2)applyRef(1,v)}; $('#spRedoScale').onclick=()=>{pts=[];pts2=[];ppi=null;ppi2=null;refIn=null;refIn2=null;seg2=false;corners=[];cornerMode=false;$('#spScale').textContent='';$('#spScale2').textContent='';$('#spCornerState').textContent='';paint()}; $('#spAdd2').onclick=()=>{seg2=true;$('#spRef2').style.display='';paint()}; $('#spPlaneW').onclick=()=>{plane='wall';paint()};$('#spPlaneF').onclick=()=>{plane='floor';paint()}; $('#spRedoBox').onclick=()=>{rect=null;paint()}; $('#spYaw').oninput=e=>{yawDeg=+e.target.value;paint()};$('#spOp').oninput=e=>{opacity=+e.target.value/100;paint()};$('#spShow').onchange=e=>{showBuild=e.target.checked;paint()}; $('#spUse').onclick=()=>applySpace(true); $('#spBuild').onclick=buildFromPhoto; const gens=$('#spGens');gens.innerHTML=Object.entries(BF.GEN).map(([k,g])=>``).join('');gens.querySelectorAll('[data-g]').forEach(b=>b.onclick=()=>{BF.UI.setPlan(b.dataset.g,{});$('#spNoMatch').innerHTML='';paint();BF.UI.toast(BF.GEN[b.dataset.g].n+' — previewing in your photo')}); const aiB=$('#spAI');if(aiB)aiB.onclick=async()=>{if(!img){BF.UI.toast('Add a photo first');return}await BF.AI.probe();if(!BF.AI.AIS.on||!BF.AI.AIS.vision){$('#spDesc').textContent='No local vision model connected. Install Ollama and run "ollama pull llava" (see Settings). The scale-and-box method above works without it.';return}$('#spDesc').textContent='Looking…';const c=document.createElement('canvas');const s=Math.min(1,768/Math.max(img.width,img.height));c.width=img.width*s;c.height=img.height*s;c.getContext('2d').drawImage(img,0,0,c.width,c.height);const b64=c.toDataURL('image/jpeg',0.8).split(',')[1]; try{$('#spDesc').textContent=await BF.AI.chat([{role:'system',content:'You help plan DIY builds. Describe the space in this photo in 3 short sentences: indoor or outdoor, the surfaces (floor, wall, ground, slope), obstacles, and which simple builds would fit (bookshelf, workbench, wall shelf, raised bed, sandbox, swing set, play fort, planter, cat tree). Do not guess exact dimensions.'},{role:'user',content:'What do you see?'}],b64)}catch(e){$('#spDesc').textContent='Could not reach the local model.'}}; // ---- perspective corners wiring $('#spCornerMode').onclick=()=>{cornerMode=!cornerMode;$('#spCornerHint').style.display=cornerMode?'':'none';$('#spCornerRow').style.display=cornerMode||corners.length?'':'none';$('#spCornerMode').style.outline=cornerMode?'2px solid #e6a64c':'';paint()}; $('#spRectW').onchange=e=>{const v=+e.target.value;if(v>0){rectW=v;paint()}}; $('#spRectH').onchange=e=>{const v=+e.target.value;if(v>0){rectH=v;if(corners.length===4&&!pts.length)ppi=null;paint()}}; $('#spRedoCorners').onclick=()=>{corners=[];cornerMode=true;$('#spCornerHint').style.display='';$('#spCornerRow').style.display='';paint()}; // ---- blueprint wiring const r0=roomGet();$('#bpCeil').value=r0.ceiling; $('#bpCeil').onchange=e=>{const v=+e.target.value;if(v>=24&&v<=240){roomGet().ceiling=v;roomSave();paint()}}; $('#bpAddWall').onclick=()=>{const r=roomGet();const used=new Set(r.walls.map(w=>w.name));let L='A';for(const ch of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')if(!used.has('Wall '+ch)){L=ch;break} r.walls.push({name:'Wall '+L,len:120,h:r.ceiling,confirmed:false,openings:[]});if(r.walls.length===1)r.targetWall=0;roomSave();renderBpWalls();paint();BF.UI.toast('Wall added — propose its length from a photo, or type the number, then Confirm')}; $('#bpToolDoor').onclick=()=>{bpTool=bpTool==='door'?null:'door';$('#bpToolDoor').style.outline=bpTool==='door'?'2px solid #e6a64c':'';$('#bpToolWin').style.outline='';BF.UI.toast(bpTool?'Now tap the wall the door is in':'Door tool off')}; $('#bpToolWin').onclick=()=>{bpTool=bpTool==='window'?null:'window';$('#bpToolWin').style.outline=bpTool==='window'?'2px solid #e6a64c':'';$('#bpToolDoor').style.outline='';BF.UI.toast(bpTool?'Now tap the wall the window is in':'Window tool off')}; $('#bpSize').onclick=sizeToWall; const bpc=$('#bpC'); const bpPos=e=>{const rct=bpc.getBoundingClientRect();return[e.clientX-rct.left,e.clientY-rct.top]}; const bpNearest=(P,cx,cy)=>{const poly=BF.roomPoly(roomGet());let best=null;poly.segs.forEach(s=>{const vx=s.x1-s.x0,vy=s.y1-s.y0,L2=vx*vx+vy*vy;let t=L2?((P[0]-s.x0)*vx+(P[1]-s.y0)*vy)/L2:0;t=Math.max(0,Math.min(1,t));const q=[s.x0+vx*t,s.y0+vy*t];const dpx=Math.hypot(bpX(q[0])-cx,bpY(q[1])-cy);if(!best||dpx{if(!bpView)return;const[cx,cy]=bpPos(e);const P=bpInv(cx,cy);const r=roomGet(); const best=bpNearest(P,cx,cy); if(bpTool&&best&&best.dpx<28){const w=r.walls[best.i];w.openings=w.openings||[];const ow=bpTool==='door'?36:48; w.openings.push({kind:bpTool,at:Math.max(0,Math.min(w.len-ow,Math.round(best.at-ow/2))),w:ow,h:bpTool==='door'?80:48}); bpTool=null;$('#bpToolDoor').style.outline='';$('#bpToolWin').style.outline='';roomSave();renderBpWalls();paint();return} const info=planInfo(); if(info){const poly=BF.roomPoly(r);const s=poly.segs[r.targetWall||0]; if(s){const rel=[P[0]-s.x0,P[1]-s.y0],u=rel[0]*s.dx+rel[1]*s.dy,v=rel[0]*s.nx+rel[1]*s.ny,at=bpAtEff(info); if(u>=at-2&&u<=at+info.pW+2&&v>=-2&&v<=info.pD+2){bpDrag={grab:u-at};try{bpc.setPointerCapture(e.pointerId)}catch(err2){}return}}} if(best&&best.dpx<28&&best.i!==(r.targetWall||0)){r.targetWall=best.i;r.buildAt=null;roomSave();renderBpWalls();paint()}}; bpc.onpointermove=e=>{if(!bpDrag||!bpView)return;const[cx,cy]=bpPos(e);const P=bpInv(cx,cy);const r=roomGet();const poly=BF.roomPoly(r);const s=poly.segs[r.targetWall||0];if(!s)return; const rel=[P[0]-s.x0,P[1]-s.y0],u=rel[0]*s.dx+rel[1]*s.dy;const info=planInfo();const maxAt=Math.max(0,s.len-(info?info.pW:0)); r.buildAt=Math.max(0,Math.min(maxAt,u-bpDrag.grab));paintBlueprint()}; bpc.onpointerup=()=>{if(bpDrag){bpDrag=null;roomSave();paint()}}; renderBpWalls(); const cv=$('#spC'); cv.onpointerdown=e=>{if(!img)return;const p=pos(e);const P=seg2?pts2:pts;const thr=26*img.width/cv.getBoundingClientRect().width; const near=P.findIndex(q=>Math.hypot(q[0]-p[0],q[1]-p[1])Math.hypot(q[0]-p[0],q[1]-p[1])=0)dragPt={arr:'corners',i:Ci}; else if(corners.length<4)corners.push(p); else{let bi2=0,bd=1e18;corners.forEach((q,i)=>{const d=Math.hypot(q[0]-p[0],q[1]-p[1]);if(d=0){dragPt={arr:seg2?'pts2':'pts',i:near}}else if(P.length===0){P.push(p,p.slice());dragPt={arr:seg2?'pts2':'pts',i:1}}else if(P.length===1){P.push(p)}else{const i0=Math.hypot(P[0][0]-p[0],P[0][1]-p[1]){if(!img)return;const p=pos(e);if(dragPt){const A=dragPt.arr==='pts2'?pts2:dragPt.arr==='corners'?corners:pts;A[dragPt.i]=p;if(dragPt.arr==='pts'&&refIn&&pts.length===2)applyRef(1,refIn);if(dragPt.arr==='pts2'&&refIn2&&pts2.length===2)applyRef(2,refIn2);paint();return} if(!drag)return;rect={x:Math.min(drag[0],p[0]),y:Math.min(drag[1],p[1]),w:Math.abs(p[0]-drag[0]),h:Math.abs(p[1]-drag[1])};paint()}; cv.onpointerup=()=>{drag=null;dragPt=null;paint()}} paint()} function buildFromPhoto(){const t=($('#spIdea')||{}).value||'';const nm=$('#spNoMatch');if(!t.trim()){BF.UI.toast('Describe the project, or tap one of the project chips');return} const r=BF.AI.parse(t);if(!r.gid){const why=r.blocked==='pet'?`I heard a pet project — and I won't substitute an outdoor children's structure for it. The engineered pet design is the Indoor cat playground (tap its chip above).`:r.blocked==='indoor'?`That matched an outdoor design, and you described an indoor space — so I haven't substituted it. Pick a project chip above.`:`I can't engineer "${t.slice(0,50)}" yet — BUILD FORGE only produces plans it can verify. Pick the closest project chip above and customise it.`; nm.innerHTML=`
${why}
`;return} nm.innerHTML='';BF.UI.setPlan(r.gid,r.params);const ap=$('#spApplied'); if(ppi&&rect){applySpace(true)}else{ap.innerHTML=`

${BF.GEN[r.gid].n} created. Set the scale and mark a box and it will be sized to this photo.

`;paint()} if(r.unavail&&r.unavail.length)ap.innerHTML+=`

Note: ${r.unavail.join(', ')} isn't an option for this design — material left unchanged.

`} const clampP=(g,k,v)=>{if(k==null||v==null||!isFinite(v))return null;const q=g.params.find(z=>z.k===k);if(!q||q.min==null||q.t==='sel'||q.t==='bool')return null;return Math.max(q.min,Math.min(q.max,Math.round(v)))}; function applySpace(manual){const pl=BF.UI.plan;if(!rect||!ppiEff()){BF.UI.toast('Set the scale and mark a space first');return false}if(!pl){BF.UI.toast('Pick or describe a project first');return false} const g=pl.g,S=BF.UI.S,pe=ppiEff(),bi=boxInches(),boxW=bi?bi.w:rect.w/pe,boxH=bi?bi.h:rect.h/pe,lines=[];const set=(key,measured,label)=>{const v=clampP(g,key,measured);if(v==null){lines.push(`${label}: not sized by the photo for this design`);return}S.params[key]=v;lines.push(`${label}: measured ${BF.ftin(measured)} → set ${BF.ftin(v)}${Math.abs(v-measured)>0.51?" (clamped to this design's "+(v`

${l}

`).join('');paint();if(manual)BF.UI.toast('Plan sized to your photo');return true} function pos(e){const cv=$('#spC'),r=cv.getBoundingClientRect();return[(e.clientX-r.left)/r.width*img.width,(e.clientY-r.top)/r.height*img.height]} function seg(x,P,col){if(!P.length)return;x.strokeStyle=col;x.fillStyle=col;const lw=Math.max(2,img.width/400);x.lineWidth=lw;P.forEach((p,i)=>{x.beginPath();x.arc(p[0],p[1],lw*3,0,7);x.fill();x.font=`700 ${Math.max(13,img.width/44)}px Barlow,sans-serif`;x.fillText(String(i+1),p[0]+lw*4,p[1]-lw*3)});if(P.length===2){x.setLineDash([lw*4,lw*3]);x.beginPath();x.moveTo(...P[0]);x.lineTo(...P[1]);x.stroke();x.setLineDash([])}} function paint(){const cv=$('#spC');if(!cv)return;const st=$('#spStatus');if(st)st.textContent=!img?'Step 1 of 3 — add a photo of the wall or floor where the build will go.':seg2?'Setting the second reference — tap both ends of the second object, then pick what it is.':cornerMode?`Marking the rectangle — tap its 4 corners, going around it (${corners.length}/4 tapped).`:step()==='scale'?(pts.length<2?'Step 2 of 3 — tap both ends of something you know the size of (a door is usually 80" tall), or drag straight across it.':'Now pick what you tapped, or correct its real size.'):step()==='box'?'Step 3 of 3 — drag a box where the build should go.':'Ready — the preview shows your plan at true scale in the photo.'; const pw=$('#spPlaneW'),pf=$('#spPlaneF');if(pw){pw.style.outline=plane==='wall'?'2px solid #e6a64c':'';pf.style.outline=plane==='floor'?'2px solid #e6a64c':''} const rb=$('#spRedoBox');if(rb)rb.style.display=rect?'':'none'; if(!img){cv.width=10;cv.height=10;paintBlueprint();return} cv.width=img.width;cv.height=img.height;const x=cv.getContext('2d');x.drawImage(img,0,0); seg(x,pts,'#7fb7ff');seg(x,pts2,'#9fe6a6'); syncCornerPpi(); if(corners.length){const lw2=Math.max(2,img.width/400);x.strokeStyle='#e6a64c';x.fillStyle='#e6a64c';x.lineWidth=lw2; corners.forEach((p,i)=>{x.beginPath();x.arc(p[0],p[1],lw2*3,0,7);x.fill();x.font=`700 ${Math.max(13,img.width/44)}px Barlow,sans-serif`;x.fillText('C'+(i+1),p[0]+lw2*4,p[1]-lw2*3)}); if(corners.length===4){const dq=orderQuad(corners);x.beginPath();dq.forEach((p,i)=>i?x.lineTo(p[0],p[1]):x.moveTo(p[0],p[1]));x.closePath();x.stroke()}} const mn=$('#spModeNote');if(mn)mn.textContent=wallH()?"Perspective preview: the build is warped onto the wall through the rectangle you marked, so it follows your photo's angle on that wall. It still draws over furniture — use the fade slider where things stand in front. Measure the final spot with a tape before cutting.":"The preview is a true-scale front view placed in your photo. It will not match your photo's angle exactly (nudge it with Preview angle), and it draws over furniture. Measure the final spot with a tape before cutting."; const cst=$('#spCornerState');if(cst)cst.textContent=cornerMode?`Corner mode: ${corners.length} of 4 corners tapped.`:(corners.length===4?'Perspective preview is ON — warped through the rectangle you marked.':''); const pl=BF.UI.plan,pe=ppiEff(); if(rect&&rect.w>4){x.strokeStyle='#e6a64c';x.lineWidth=Math.max(2,img.width/400);x.setLineDash([img.width/80,img.width/130]);x.strokeRect(rect.x,rect.y,rect.w,rect.h);x.setLineDash([]); if(pe){const bi=boxInches()||{w:rect.w/pe,h:rect.h/pe,x:null};const W=bi.w,H=bi.h;x.font=`600 ${Math.max(14,img.width/40)}px "IBM Plex Mono",monospace`;const lab=plane==='floor'?`${BF.ftin(W)} wide × ${BF.ftin(H)} deep`:`${BF.ftin(W)} × ${BF.ftin(H)}`;const tw=x.measureText(lab).width;x.fillStyle='rgba(12,18,28,.78)';x.fillRect(rect.x,Math.max(0,rect.y-img.width/26),tw+20,img.width/30);x.fillStyle='#f4c77e';x.fillText(lab,rect.x+10,Math.max(0,rect.y-img.width/26)+img.width/40); const dl=$('#spDims');if(dl)dl.textContent='Marked space: '+lab+(pl?` · your ${pl.g.n}: ${pl.K.specs[0]?pl.K.specs[0][1]:''}`:' · no project picked yet'); const use=$('#spUse'),hint=$('#spUseHint');if(use){use.disabled=!(pl&&rect&&pe);if(hint)hint.textContent=!pl?'Pick a project (step 3) to size it to this space.':''} if(pl&&showBuild){const B=BF.r3d.bounds(pl.K.parts);const ctr=[(B.lo[0]+B.hi[0])/2,(B.lo[1]+B.hi[1])/2,(B.lo[2]+B.hi[2])/2];const sc=pe;const Hm=wallH(); if(Hm&&bi.x!=null){ // perspective mode: warp the front elevation onto the marked wall plane const ppm=10,Bw=B.hi[0]-B.lo[0],Bh=B.hi[1]-B.lo[1]; const elev=document.createElement('canvas');elev.width=Math.max(2,Math.round(Bw*ppm));elev.height=Math.max(2,Math.round(Bh*ppm)); BF.r3d.render(elev.getContext('2d'),elev.width,elev.height,pl.K,{bg:false,ground:false,zone:false,yaw:0,pitch:0,scale:ppm,center:ctr,bounds:B,panX:(ctr[0]-B.lo[0])*ppm-elev.width/2,panY:(B.lo[1]-ctr[1])*ppm+elev.height/2}); const bq=[[bi.x,bi.y],[bi.x+Bw,bi.y],[bi.x+Bw,bi.y-4],[bi.x,bi.y-4]].map(p=>BF.H.apply(Hm,p)); if(bq.every(Boolean)){x.fillStyle='rgba(0,0,0,0.28)';x.beginPath();bq.forEach((p,i)=>i?x.lineTo(p[0],p[1]):x.moveTo(p[0],p[1]));x.closePath();x.fill()} const Sm=[[1/ppm,0,bi.x],[0,-1/ppm,bi.y+elev.height/ppm],[0,0,1]]; x.globalAlpha=opacity;BF.H.warpDraw(x,elev,BF.H.mul3(Hm,Sm),14);x.globalAlpha=1; }else{const ox=rect.x-(B.lo[0]-ctr[0])*sc,oy=rect.y+rect.h+(B.lo[1]-ctr[1])*sc; const sh=x.createRadialGradient(rect.x+rect.w/2,rect.y+rect.h,4,rect.x+rect.w/2,rect.y+rect.h,rect.w*0.62);sh.addColorStop(0,'rgba(0,0,0,0.34)');sh.addColorStop(1,'rgba(0,0,0,0)');x.fillStyle=sh;x.fillRect(rect.x-rect.w*0.15,rect.y+rect.h-rect.w*0.16,rect.w*1.3,rect.w*0.2); x.globalAlpha=opacity;BF.r3d.render(x,img.width,img.height,pl.K,{bg:false,ground:false,zone:false,yaw:yawDeg*Math.PI/180,pitch:0.06,scale:sc,center:ctr,bounds:B,panX:ox-img.width/2,panY:oy-img.height/2});x.globalAlpha=1} const pW=B.hi[0]-B.lo[0],pH=B.hi[1]-B.lo[1],pD=B.hi[2]-B.lo[2];const fits=plane==='floor'?(pW<=W+0.5&&pD<=H+0.5):(pW<=W+0.5&&pH<=H+0.5);const dl2=$('#spDims');if(dl2)dl2.textContent+=' · '+(fits?'fits ✓':'does not fit yet ✗ (tap "Size my plan to this space")')}}} paintBlueprint()} function paintBlueprint(){const cv=$('#bpC');if(!cv)return;const r=roomGet();const poly=BF.roomPoly(r); const gapEl=$('#bpGap');if(gapEl)gapEl.textContent=!r.walls.length?'No walls yet — add the first wall.':r.walls.length<3?'Walls join in order around the room; the plan closes when the last corner meets the first.':poly.gap<=0.6?`Plan closes ✓ — the last corner lands within ${BF.ftin(Math.max(poly.gap,0.04))} of the first.`:`Plan doesn't close — the last corner misses the first by ${BF.ftin(poly.gap)}. Check the wall lengths.`; const dpr=Math.min(2,window.devicePixelRatio||1),cwCss=cv.clientWidth||920,chCss=520; const Wpx=Math.round(cwCss*dpr),Hpx=Math.round(chCss*dpr); if(cv.width!==Wpx||cv.height!==Hpx){cv.width=Wpx;cv.height=Hpx} const x=cv.getContext('2d');x.setTransform(dpr,0,0,dpr,0,0);x.clearRect(0,0,cwCss,chCss); x.fillStyle='rgba(200,154,82,.05)';x.fillRect(0,0,cwCss,chCss); const bf=$('#bpFit'); if(!r.walls.length){x.fillStyle='#9fb4c8';x.font='600 15px Barlow,sans-serif';x.fillText('Your floor plan appears here as you confirm each wall.',24,42);lastFit=null;bpView=null;if(bf)bf.innerHTML='';return} const info=planInfo();const at=info?bpAtEff(info):0; const fit=info?BF.roomFit(r,{pW:info.pW,pD:info.pD,pH:info.pH,zone:info.zone,buildAt:at,name:info.name}):null;lastFit=fit; const b=poly.bounds,mx=76,top=66,bot=68,vw=Math.max(b.w,1),vd=Math.max(b.d,1); const sc=Math.min((cwCss-2*mx)/vw,(chCss-top-bot)/vd); bpView={sc,ox:mx-b.lo[0]*sc+((cwCss-2*mx)-vw*sc)/2,oyT:top+((chCss-top-bot)-vd*sc)/2,lo0:b.lo[0],hi1:b.hi[1]}; const X=bpX,Y=bpY; x.font='600 13px "IBM Plex Mono",monospace';x.fillStyle='#9fb4c8'; x.fillText(`Ceiling ${BF.ftin(r.ceiling)} · walls at right angles, in the order added`,14,20); poly.segs.forEach(s=>{const w=r.walls[s.i];const tgt=s.i===(r.targetWall||0); const A=[X(s.x0),Y(s.y0)],Bp=[X(s.x1),Y(s.y1)]; x.strokeStyle=tgt?'#e6a64c':'#8a6f3e';x.lineWidth=7;x.beginPath();x.moveTo(A[0],A[1]);x.lineTo(Bp[0],Bp[1]);x.stroke(); (w.openings||[]).forEach(o=>{const p0=[s.x0+s.dx*o.at,s.y0+s.dy*o.at],p1=[s.x0+s.dx*(o.at+o.w),s.y0+s.dy*(o.at+o.w)]; const Q0=[X(p0[0]),Y(p0[1])],Q1=[X(p1[0]),Y(p1[1])]; if(o.kind==='door'){x.strokeStyle='#0c121c';x.lineWidth=9;x.beginPath();x.moveTo(Q0[0],Q0[1]);x.lineTo(Q1[0],Q1[1]);x.stroke(); x.strokeStyle='rgba(230,166,76,.85)';x.lineWidth=1.5;x.beginPath(); for(let a=0;a<=90;a+=6){const t=a*Math.PI/180;const px2=p0[0]+o.w*(s.dx*Math.cos(t)+s.nx*Math.sin(t)),py2=p0[1]+o.w*(s.dy*Math.cos(t)+s.ny*Math.sin(t));const Q=[X(px2),Y(py2)];a?x.lineTo(Q[0],Q[1]):x.moveTo(Q[0],Q[1])} const leaf=[p0[0]+o.w*s.nx,p0[1]+o.w*s.ny];x.moveTo(Q0[0],Q0[1]);x.lineTo(X(leaf[0]),Y(leaf[1]));x.stroke(); }else{const nc=[s.nx,-s.ny];x.strokeStyle='#7fb7ff';x.lineWidth=3;x.beginPath();x.moveTo(Q0[0],Q0[1]);x.lineTo(Q1[0],Q1[1]);x.stroke(); x.lineWidth=1;x.beginPath();x.moveTo(Q0[0]+nc[0]*4,Q0[1]+nc[1]*4);x.lineTo(Q1[0]+nc[0]*4,Q1[1]+nc[1]*4);x.moveTo(Q0[0]-nc[0]*4,Q0[1]-nc[1]*4);x.lineTo(Q1[0]-nc[0]*4,Q1[1]-nc[1]*4);x.stroke()}}); const outC=[-s.nx,s.ny],off=30; const D0=[A[0]+outC[0]*off,A[1]+outC[1]*off],D1=[Bp[0]+outC[0]*off,Bp[1]+outC[1]*off]; x.strokeStyle='rgba(127,183,255,.75)';x.lineWidth=1;x.beginPath();x.moveTo(D0[0],D0[1]);x.lineTo(D1[0],D1[1]); x.moveTo(A[0]+outC[0]*(off-5),A[1]+outC[1]*(off-5));x.lineTo(A[0]+outC[0]*(off+5),A[1]+outC[1]*(off+5)); x.moveTo(Bp[0]+outC[0]*(off-5),Bp[1]+outC[1]*(off-5));x.lineTo(Bp[0]+outC[0]*(off+5),Bp[1]+outC[1]*(off+5));x.stroke(); x.fillStyle='#bcd8f5';x.textAlign='center';x.fillText(BF.ftin(s.len),(D0[0]+D1[0])/2+outC[0]*16,(D0[1]+D1[1])/2+outC[1]*16+4); const inw=[s.nx,-s.ny],cen=[(A[0]+Bp[0])/2+inw[0]*18,(A[1]+Bp[1])/2+inw[1]*18]; x.fillStyle=tgt?'#f4c77e':'#9fb4c8';x.fillText(w.name,cen[0],cen[1]+4);x.textAlign='left'}); if(info&&fit){const s=poly.segs[r.targetWall||0]; if(s){const c0=[s.x0+s.dx*at,s.y0+s.dy*at]; const cs=[c0,[c0[0]+s.dx*info.pW,c0[1]+s.dy*info.pW],[c0[0]+s.dx*info.pW+s.nx*info.pD,c0[1]+s.dy*info.pW+s.ny*info.pD],[c0[0]+s.nx*info.pD,c0[1]+s.ny*info.pD]].map(p=>[X(p[0]),Y(p[1])]); x.fillStyle=fit.ok?'rgba(87,200,120,.16)':'rgba(224,90,76,.18)';x.strokeStyle=fit.ok?'#57c878':'#e05a4c';x.lineWidth=2; x.beginPath();cs.forEach((p,i)=>i?x.lineTo(p[0],p[1]):x.moveTo(p[0],p[1]));x.closePath();x.fill();x.stroke(); const cen=[(cs[0][0]+cs[2][0])/2,(cs[0][1]+cs[2][1])/2];x.fillStyle=fit.ok?'#8fd19a':'#f0a49c';x.textAlign='center'; x.fillText(info.name,cen[0],cen[1]-2);x.fillText(`${BF.ftin(info.pW)} × ${BF.ftin(info.pD)}`,cen[0],cen[1]+14);x.textAlign='left'}} if(bf){if(!info)bf.innerHTML='

Open or describe a project and it will be placed on the build wall and checked against this room.

'; else if(fit)bf.innerHTML=`

${info.name} on ${r.walls[r.targetWall||0].name}: ${fit.ok?'fits this room ✓':'does not fit yet ✗'}

`+fit.lines.map(l=>`

${l.st==='pass'?'✓':l.st==='warn'?'⚠':'✗'} ${l.text}

`).join('')}} function renderBpWalls(){const box=$('#bpWalls');if(!box)return;const r=roomGet(); box.innerHTML=r.walls.map((w,i)=>`
${w.confirmed?'Confirmed by you.':'Proposed — check the numbers, then Confirm.'}
`).join('')||'

No walls yet.

'; box.querySelectorAll('[data-bptarget]').forEach(b=>b.onclick=()=>{r.targetWall=+b.dataset.bptarget;r.buildAt=null;roomSave();renderBpWalls();paint()}); box.querySelectorAll('[data-bplen]').forEach(inp=>inp.onchange=()=>{const w=r.walls[+inp.dataset.bplen];const v=+inp.value;if(v>0){w.len=v;w.confirmed=false;roomSave();renderBpWalls();paint()}}); box.querySelectorAll('[data-bph]').forEach(inp=>inp.onchange=()=>{const w=r.walls[+inp.dataset.bph];const v=+inp.value;if(v>0){w.h=v;w.confirmed=false;roomSave();renderBpWalls();paint()}}); box.querySelectorAll('[data-bpprop]').forEach(b=>b.onclick=()=>{const i=+b.dataset.bpprop;const bi=boxInches(); if(!img){BF.UI.toast('Add a photo of this wall first');return} if(!bi){BF.UI.toast('Calibrate the photo and drag a box across the whole wall first');return} const w=r.walls[i];w.len=Math.round(bi.w*2)/2;if(bi.h>12)w.h=Math.round(bi.h*2)/2;w.confirmed=false;roomSave();renderBpWalls();paint(); BF.UI.toast(`${w.name}: proposed ${BF.ftin(w.len)} long × ${BF.ftin(w.h||r.ceiling)} high from your photo — confirm or correct it`)}); box.querySelectorAll('[data-bpconf]').forEach(b=>b.onclick=()=>{const w=r.walls[+b.dataset.bpconf];w.confirmed=true;roomSave();renderBpWalls();paint();BF.UI.toast(w.name+' confirmed at '+BF.ftin(w.len)+' long')}); box.querySelectorAll('[data-bpdel]').forEach(b=>b.onclick=()=>{r.walls.splice(+b.dataset.bpdel,1);if((r.targetWall||0)>=r.walls.length)r.targetWall=0;r.buildAt=null;roomSave();renderBpWalls();paint()}); renderBpOpenings()} function renderBpOpenings(){const el=$('#bpOpenings');if(!el)return;const r=roomGet();const rows=[]; r.walls.forEach((w,i)=>(w.openings||[]).forEach((o,j)=>rows.push(`${w.name}: ${o.kind} at ${BF.ftin(o.at)}, ${BF.ftin(o.w)} wide `))); el.innerHTML=rows.length?rows.join(''):'No doors or windows placed yet.'; el.querySelectorAll('[data-bpodel]').forEach(b=>b.onclick=()=>{const[i,j]=b.dataset.bpodel.split(':').map(Number);r.walls[i].openings.splice(j,1);roomSave();renderBpWalls();paint()})} function sizeToWall(){const pl=BF.UI.plan;if(!pl){BF.UI.toast('Open or describe a project first');return} const r=roomGet(),wi=r.targetWall||0,wall=r.walls[wi]; if(!wall){BF.UI.toast('Add a wall first');return} if(!wall.confirmed){BF.UI.toast('Confirm '+wall.name+"'s numbers first — the plan is only sized to numbers you confirmed");return} const g=pl.g,S=BF.UI.S,lines=[];const depth=BF.wallDepth(BF.roomPoly(r),wi);const ceil=Math.min(r.ceiling||96,wall.h||r.ceiling||96); const clampTo=(key,limit,label)=>{if(!key)return;const cur=S.params[key];if(cur==null)return; const v=clampP(g,key,Math.min(cur,Math.floor(limit))); if(v==null){lines.push(`${label}: not sized by the room for this design.`);return} if(v`

${l}

`).join('');paint()} return{draw,paint,applySpace, _room:()=>({room:JSON.parse(JSON.stringify(roomGet())),fit:lastFit,poly:BF.roomPoly(roomGet())}), _roomSet:r=>{room=r;roomSave();renderBpWalls();paint()}, _warp:()=>({mode:wallH()?'persp':'flat',corners:corners.map(c=>c.slice()),box:rect?boxInches():null, quad:rc=>{const H=wallH();if(!H||!rc)return null;const[x,y,w,h]=rc;return[[x,y],[x+w,y],[x+w,y+h],[x,y+h]].map(p=>BF.H.apply(H,p))}})}})(); // ===== BUILD FORGE app shell (()=>{const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)],esc=s=>String(s==null?'':s).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); const LS=(()=>{try{localStorage.setItem('_t','1');localStorage.removeItem('_t');return localStorage}catch(e){const m={};return{getItem:k=>m[k]??null,setItem:(k,v)=>m[k]=v,removeItem:k=>delete m[k]}}})(); const S=Object.assign({gid:null,params:{},tools:['tape','square','pencil','drill','bits','clamp','ppe'],have:[],budget:null,unit:'in',saved:[],prices:{},ai:{url:'http://localhost:11434'},voice:true},(()=>{try{return JSON.parse(LS.getItem('bf1')||'{}')}catch(e){return{}}})()); const save=()=>{try{LS.setItem('bf1',JSON.stringify(Object.assign({},S,{photo:undefined})))}catch(e){}};BF.PRICE_OVR=S.prices;BF.AI.AIS.url=S.ai.url||BF.AI.AIS.url; const ctx=()=>({tools:new Set(S.tools),have:new Set(S.have)});let PLAN=null; const toast=m=>{document.querySelectorAll('.toast').forEach(t=>t.remove());const d=document.createElement('div');d.className='toast';d.textContent=m;document.body.appendChild(d);setTimeout(()=>d.remove(),3200)}; // ---------- router const PAGES=[['studio','Studio'],['projects','Projects'],['plan','My plan'],['space','Room photo'],['ask','Shop Mind'],['library','Library'],['settings','Settings']]; function go(id){$$('section.page').forEach(s=>s.classList.toggle('on',s.id===id));$$('nav.tabs a').forEach(a=>a.classList.toggle('on',a.dataset.p===id));if(location.hash!=='#'+id)history.replaceState(null,'','#'+id);scrollTo(0,0);setTimeout(()=>scrollTo(0,0),30); if(id==='plan')drawPlan();if(id==='projects')drawProjects();if(id==='library')drawLib();if(id==='settings')drawSettings();if(id==='space')Space.draw();if(id==='ask')drawAsk()} BF.go=go; // ---------- STUDIO function drawStudio(){const box=$('#studio');const cats={};Object.entries(BF.TOOLS).forEach(([k,t])=>{(cats[t.cat]=cats[t.cat]||[]).push([k,t])}); box.innerHTML=`
offline build studio

Describe it. Snap the space. Build it right.

Tell Shop Mind what you want, what you have and what you can spend. You get a full plan: 3D model, step-by-step build animation, cut list, shopping list, tools explained, and the engineering math behind every board.

Tools I have

The plan picks methods that use your tools, and lists what you'd need to buy, borrow or have the store do.

${Object.entries(cats).map(([c,ts])=>`
${c.toUpperCase()}
${ts.map(([k,t])=>``).join('')}
`).join('')}

Materials I already have

${[['SPF2x4','2x4s'],['SPF2x6','2x6s'],['PT4x4','4x4 posts'],['PLY34B','3/4" plywood'],['PLY34P','pine plywood'],['CED2x6','cedar 2x6'],['PINE1x4','1x4 boards'],['PT54','deck boards']].map(([k,l])=>``).join('')}

Owned materials are left off the shopping total; check you have enough against the cut list.

Or start from a proven project

`; box.querySelectorAll('[data-tool]').forEach(b=>b.onclick=()=>{const k=b.dataset.tool;S.tools=S.tools.includes(k)?S.tools.filter(x=>x!==k):[...S.tools,k];b.classList.toggle('on');save();if(PLAN)rebuild()}); box.querySelectorAll('[data-have]').forEach(b=>b.onclick=()=>{const k=b.dataset.have;S.have=S.have.includes(k)?S.have.filter(x=>x!==k):[...S.have,k];b.classList.toggle('on');save();if(PLAN)rebuild()}); $('#budget').onchange=e=>{S.budget=e.target.value?+e.target.value:null;save()};$('#goBuild').onclick=()=>fromIdea($('#idea').value);$('#goPhoto').onclick=()=>go('space');$('#idea').onkeydown=e=>{if(e.key==='Enter'&&(e.metaKey||e.ctrlKey))fromIdea($('#idea').value)}; cards($('#miniGrid'),6);aiState()} async function aiState(){const el=$('#aiState');if(!el)return;await BF.AI.probe();const A=BF.AI.AIS;el.innerHTML=`${A.on?`Shop Mind + local model ${esc(A.model)}${A.vision?` · photo vision ${esc(A.vision)}`:''} (on this computer, offline)`:'Shop Mind built-in engine (offline). Optional: connect a local model in Settings for free-form chat and photo understanding.'}`} function fromIdea(text){S.lastIdea=text;save();const r=BF.AI.parse(text,PLAN&&PLAN.gid);const out=$('#ideaOut'); r.tools.forEach(k=>{if(!S.tools.includes(k))S.tools.push(k)});r.notools.forEach(k=>S.tools=S.tools.filter(x=>x!==k));r.have.forEach(k=>{if(!S.have.includes(k))S.have.push(k)});if(r.budget!=null){S.budget=r.budget;const b=$('#budget');if(b)b.value=r.budget}save(); if(r.clarify){const sug=Object.entries(BF.GEN).map(([k,g])=>``).join('');const opts=r.clarify.options.map(o=>``).join(''); out.innerHTML=`
One quick question, so I build the right thing: ${esc(r.clarify.q)}
${opts}
…or pick any proven design:
${sug}
`;out.querySelectorAll('[data-g]').forEach(b=>b.onclick=()=>openPlan(b.dataset.g,{}));return} if(!r.gid){const sug=Object.entries(BF.GEN).map(([k,g])=>``).join(''); const why=r.blocked==='pet'?`I heard a pet project — and I won't substitute an outdoor children's structure for it. "${esc(text.slice(0,60))}" points at the ${esc(BF.GEN[r.heard].n)}, which is engineered for children, not pets. The engineered pet design is the Indoor cat playground below; for anything else pet-shaped, pick the closest proven design and customise it.` :r.blocked==='indoor'?`That matched an outdoor design, and you described an indoor space — so I haven't substituted it. The ${esc(BF.GEN[r.heard].n)} is engineered for outdoors. Pick the closest proven design below and customise it.` :`I can't engineer that one yet. BUILD FORGE only produces plans it can verify with real strength and safety math, and "${esc(text.slice(0,60))}" isn't in its engineered set. Pick the closest proven design below and customise it${BF.AI.AIS.on?', or ask Shop Mind (your local model) to talk it through, clearly marked as unverified advice':''}.`; out.innerHTML=`
${why}
${sug}
`;out.querySelectorAll('[data-g]').forEach(b=>b.onclick=()=>openPlan(b.dataset.g,{}));if(BF.AI.AIS.on&&!r.blocked){Ask.push('u',text);go('ask');Ask.llm(text)}return} const msgs=[`Project: ${BF.GEN[r.gid].n}.`];if(r.heardFix)msgs.push(`Heard "${r.heardFix.from}" as ${r.heardFix.to}.`);if(r.said.length)msgs.push('I set: '+r.said.join(', ')+'.');if(r.unavail&&r.unavail.length)msgs.push(`Note: ${r.unavail.join(', ')} isn't an option for this design, so the material was left unchanged.`);if(r.avoid&&r.avoid.length)msgs.push(`Avoiding: ${r.avoid.join(', ')}.`);const cx=r.context;if(cx&&(cx.who.length||cx.where))msgs.push('Heard: '+[cx.who.length?'for '+cx.who.join(' and '):'',cx.where?'for the '+cx.where:''].filter(Boolean).join(' · ')+'.');if(r.tools.length)msgs.push('Tools noted: '+r.tools.map(k=>BF.TOOLS[k].n).join(', ')+'.');if(r.notools.length)msgs.push('Avoiding tools: '+r.notools.map(k=>BF.TOOLS[k].n).join(', ')+'.'); let keep=r.params; if(PLAN&&PLAN.gid===r.gid){keep=Object.assign({},S.params,r.params); if(r.relSize){(r.relApplied||[]).forEach(k=>{if(S.params[k]!=null)keep[k]=S.params[k]});const sc=BF.AI.scaleParams(r.gid,Object.assign({},PLAN.p),r.relSize);Object.assign(keep,sc.params);if(Object.keys(sc.params).length)msgs.push(`Scaled the open plan ${r.relSize.f>1?'up about 25%':'down about 20%'}.`)}} openPlan(r.gid,keep,msgs.join(' '))} // ---------- PROJECTS / mini cards function cards(el,limit){const list=Object.entries(BF.GEN).slice(0,limit||99);el.innerHTML=list.map(([k,g])=>`
${g.cat}
${esc(g.n)}

${esc(g.blurb)}

`).join('')+(limit?`
See all ${Object.keys(BF.GEN).length} projects →
`:''); el.querySelectorAll('[data-g]').forEach(c=>{c.onclick=()=>openPlan(c.dataset.g,{});const cv=c.querySelector('canvas');requestAnimationFrame(()=>{try{const pl=BF.makePlan(c.dataset.g,{},ctx());const x=cv.getContext('2d');BF.r3d.render(x,cv.width,cv.height,pl.K,{zone:false,zoom:0.86,bg:'#0e1520'})}catch(e){console.warn(e)}})});const a=el.querySelector('[data-all]');if(a)a.onclick=()=>go('projects')} function drawProjects(){const box=$('#projects');box.innerHTML=`
engineered designs

Projects

Every project is parametric: change any size or option and the structure, cut list, cost and steps re-compute.

`;cards($('#allGrid'))} // ---------- PLAN let tab='steps',view={yaw:-0.65,pitch:0.42,zoom:0.82,dims:true,zone:true},anim=null; function openPlan(gid,params,msg){S.gid=gid;S.params=Object.assign({},params);save();rebuild();go('plan');if(msg)setTimeout(()=>toast(msg),200)} function rebuild(){if(!S.gid)return;PLAN=BF.makePlan(S.gid,S.params,ctx());BF.CUR=PLAN;if($('#plan').classList.contains('on'))drawPlan();try{Space.paint()}catch(e){}} function setPlan(gid,params){S.gid=gid;S.params=Object.assign({},params);save();rebuild()} function drawPlan(){const box=$('#plan');if(!PLAN){box.innerHTML=`

No plan yet

Describe an idea in the Studio, or pick a project.

`;return} const pl=PLAN,g=pl.g,B=S.budget;const fails=pl.fails.length; box.innerHTML=`
${g.cat} · plan

${esc(g.n)}

${pl.K.specs.slice(0,2).map(s=>esc(s[0]+': '+s[1])).join(' · ')}
ENGINEERING${fails?fails+' issue'+(fails>1?'s':''):'All '+pl.K.checks.length+' checks pass'}
COST${BF.money(pl.cost)}${B!=null?`budget ${BF.money(B)}`:''}
TIME${BF.estHours(pl)}
PARTS${pl.cutlist.reduce((s,c)=>s+c.qty,0)} cuts
${pl.K.fixes.length?pl.K.fixes.map(f=>`
🔧 Engine adjusted your design: ${esc(f)}
`).join(''):''}

Your settings

${g.params.map(q=>paramHTML(q,pl.p[q.k])).join('')}
Drag to orbit · scroll/pinch to zoom
${pl.K.zone?``:''}
${[['steps','Steps'],['shop','Shopping list'],['cuts','Cut list'],['tools','Tools'],['eng','Engineering'],['safety','Safety'],['report','Report']].map(([k,l])=>``).join('')}
`; g.params.forEach(q=>{const el=box.querySelector(`[data-p="${q.k}"]`);if(!el)return;const fire=()=>{let v=q.t==='bool'?el.checked:q.t==='sel'?el.value:+el.value;S.params[q.k]=v;save();const lab=box.querySelector(`[data-pv="${q.k}"]`);if(lab)lab.textContent=q.u==='in'?BF.ftin(v,S.unit):v+(q.u?' '+q.u:'');};el.oninput=()=>{fire();if(q.t!=='bool'&&q.t!=='sel')livePlan()};el.onchange=()=>{fire();rebuild()}}); $('#savePlan').onclick=()=>{S.saved=S.saved.filter(x=>!(x.gid===S.gid&&JSON.stringify(x.params)===JSON.stringify(S.params)));S.saved.unshift({gid:S.gid,params:Object.assign({},pl.p),at:Date.now(),cost:pl.cost,name:g.n});S.saved=S.saved.slice(0,30);save();toast('Saved to this device')};$('#toAsk').onclick=()=>go('ask'); box.querySelectorAll('[data-tab]').forEach(b=>b.onclick=()=>{tab=b.dataset.tab;box.querySelectorAll('[data-tab]').forEach(x=>x.classList.toggle('on',x===b));drawTab()}); $('#tDims').onclick=()=>{view.dims=!view.dims;$('#tDims').textContent=(view.dims?'Hide':'Show')+' sizes';paint()};const tz=$('#tZone');if(tz)tz.onclick=()=>{view.zone=!view.zone;tz.textContent=(view.zone?'Hide':'Show')+' use zone';paint()}; $('#vFront').onclick=()=>{view.yaw=0;view.pitch=0.05;paint()};$('#vIso').onclick=()=>{view.yaw=-0.65;view.pitch=0.42;paint()};$('#vTop').onclick=()=>{view.yaw=0;view.pitch=1.45;paint()};$('#playA').onclick=playAnim;$('#player1').onclick=()=>Player.open(0); orbit($('#cv3'));paint();drawTab()} function paramHTML(q,v){if(q.t==='bool')return``;if(q.t==='sel')return`
`; return`
`} function fit(cv){const r=cv.getBoundingClientRect(),d=Math.min(2,devicePixelRatio||1);if(cv.width!==Math.round(r.width*d)||cv.height!==Math.round(r.height*d)){cv.width=Math.round(r.width*d);cv.height=Math.round(r.height*d)}const x=cv.getContext('2d');x.setTransform(d,0,0,d,0,0);return[x,r.width,r.height]} function paint(step,a,hl,fut){const cv=$('#cv3');if(!cv||!PLAN)return;const [x,W,H]=fit(cv);BF.r3d.render(x,W,H,PLAN.K,{yaw:view.yaw,pitch:view.pitch,zoom:view.zoom,dims:view.dims&&step==null,zone:view.zone,step,anim:a,hl,unit:S.unit,future:fut})} // while a slider is being dragged: recompute the plan and refresh badges + 3D at once (full page rebuild still happens on release) function livePlan(){if(!S.gid)return;PLAN=BF.makePlan(S.gid,S.params,ctx());BF.CUR=PLAN;const pl=PLAN,bs=$$('#plan .badge'); if(bs.length===4){bs[0].className='badge '+(pl.fails.length?'bad':'ok');bs[0].querySelector('b').textContent=pl.fails.length?pl.fails.length+' issue'+(pl.fails.length>1?'s':''):'All '+pl.K.checks.length+' checks pass';bs[1].querySelector('b').textContent=BF.money(pl.cost);bs[2].querySelector('b').textContent=BF.estHours(pl);bs[3].querySelector('b').textContent=pl.cutlist.reduce((s,c)=>s+c.qty,0)+' cuts'} const spec=document.querySelector('#plan .planHead>div:first-child .small');if(spec)spec.textContent=pl.K.specs.slice(0,2).map(s=>s[0]+': '+s[1]).join(' · ');paint()} function orbit(cv){let d=null,pinch=null;cv.onpointerdown=e=>{d=[e.clientX,e.clientY,view.yaw,view.pitch];try{cv.setPointerCapture(e.pointerId)}catch(err){}};cv.onpointermove=e=>{if(!d)return;view.yaw=d[2]+(e.clientX-d[0])*0.008;view.pitch=Math.max(-0.1,Math.min(1.5,d[3]+(e.clientY-d[1])*0.006));paint()};cv.onpointerup=()=>d=null; cv.onwheel=e=>{e.preventDefault();view.zoom=Math.max(0.3,Math.min(3,view.zoom*(e.deltaY>0?0.92:1.08)));paint()};cv.addEventListener('touchmove',e=>{if(e.touches.length===2){const dd=Math.hypot(e.touches[0].clientX-e.touches[1].clientX,e.touches[0].clientY-e.touches[1].clientY);if(pinch)view.zoom=Math.max(0.3,Math.min(3,view.zoom*dd/pinch));pinch=dd;d=null;paint();e.preventDefault()}},{passive:false});cv.addEventListener('touchend',()=>pinch=null)} function playAnim(){const cap=()=>{const c=$('#vcap');if(c)c.textContent='Drag to orbit · scroll/pinch to zoom'}; if(anim){cancelAnimationFrame(anim.r);anim=null;paint();$('#playA').textContent='▶ Build animation';cap();return}const steps=PLAN.K.steps,n=steps.length;let el=0,last=performance.now();const per=1500;$('#playA').textContent='■ Stop';const y0=view.yaw; const f=t=>{const dt=Math.max(0,Math.min(50,t-last));last=t;el+=dt;const i=Math.floor(el/per),a=Math.min(1,(el%per)/(per*0.7));if(i>=n){anim=null;$('#playA').textContent='▶ Build animation';view.yaw=y0;paint();cap();return}view.yaw=y0+el/9000;paint(i,a,true,0.1);$('#vcap').textContent=`STEP ${i+1}/${n} · ${steps[i].t.toUpperCase()}`;anim.r=requestAnimationFrame(f)};anim={r:requestAnimationFrame(f)}} function stepImg(cv,i){const r=cv.getBoundingClientRect(),d=Math.min(2,devicePixelRatio||1);cv.width=Math.round((r.width||260)*d);cv.height=Math.round((r.height||200)*d);const x=cv.getContext('2d');x.setTransform(d,0,0,d,0,0);BF.r3d.render(x,r.width||260,r.height||200,PLAN.K,{step:i,anim:1,hl:true,zone:false,labels:false,future:0.13})} function drawTab(){const el=$('#tabBody'),pl=PLAN,K=pl.K;const tn=k=>BF.TOOLS[k]?BF.TOOLS[k].n.replace(/ \(.*\)/,''):k; if(tab==='steps'){el.innerHTML=K.steps.map((s,i)=>`
STEP ${i+1} OF ${K.steps.length}

${esc(s.t)}

${esc(s.d)}

${s.tools.map(t=>`${esc(tn(t))}${S.tools.includes(t)||t==='pencil'?'':' · need'}`).join('')}${s.tip?`
💡 ${esc(s.tip)}
`:''}
`).join(''); el.querySelectorAll('canvas[data-si]').forEach(cv=>requestAnimationFrame(()=>stepImg(cv,+cv.dataset.si)));el.querySelectorAll('[data-play]').forEach(b=>b.onclick=()=>Player.open(+b.dataset.play))} else if(tab==='shop'){const B=S.budget;const rows=[];pl.lumber.forEach(l=>rows.push([l.n,Object.entries(l.byLen).map(([L,n])=>`${n} × ${BF.ftin(+L)}`).join(', '),l.owned?'you have it':BF.money(l.cost)]));pl.sheets.forEach(s=>rows.push([s.n,s.res.sheets.length+' sheet'+(s.res.sheets.length>1?'s':'')+` (${Math.round(s.res.yieldPct)}% used)`,s.owned?'you have it':BF.money(s.cost)])); el.innerHTML=`

Lumber & sheets

${rows.map(r=>``).join('')}
ItemBuyCost
${esc(r[0])}${r[1]}${r[2]}
Materials${BF.money(pl.matCost)}

Hardware & supplies

${pl.hw.map(h=>``).join('')}
${esc(h.n)}${h.note?`
${esc(h.note)}
`:''}
${h.qty}${BF.money(h.cost)}
Total${BF.money(pl.cost)}

Typical US big-box prices; set your store's prices in Settings. Buy 10% extra on boards if you are new to cutting.

Budget

${B!=null?`

${pl.cost<=B?`Under budget by ${BF.money(B-pl.cost)}.`:`Over budget by ${BF.money(pl.cost-B)}.`}

`:'

Set a budget in the Studio and BUILD FORGE will fit the design to it.

'}

Tools you're missing

${pl.tools.filter(t=>!t.have).length?`${pl.tools.filter(t=>!t.have).map(t=>``).join('')}
${esc(t.n)}~${BF.money(t.c)}

Rent, borrow, or ask the lumber yard to make the cuts. Mark tools you own in the Studio.

`:'

None. You have every tool this build needs.

'}
`; $('#fitB').onclick=()=>{const B2=S.budget??+prompt('Budget in dollars?','300');if(!B2)return;S.budget=B2;save();const f=BF.fitBudget(S.gid,pl.p,ctx(),B2);const o=$('#fitOut');if(!f){o.innerHTML='
No safe combination found.
';return} const ch=Object.keys(f.pr).filter(k=>f.pr[k]!==pl.p[k]).map(k=>{const q=pl.g.params.find(z=>z.k===k);return q.t==='bool'?(f.pr[k]?'add ':'drop ')+q.l.toLowerCase():q.l+': '+(q.opts?q.opts.find(o=>o[0]===f.pr[k])[1]:f.pr[k])}); o.innerHTML=f.under?`
✓ Fits at ${BF.money(f.pl.cost)}${ch.length?' by changing: '+esc(ch.join('; ')):''}. Sizes kept, every check still passes.
`:`
The lowest safe version of this size is ${BF.money(f.pl.cost)}${ch.length?' ('+esc(ch.join('; '))+')':''}. To go lower, make it smaller or pick a different project. Strength and safety items are never removed to save money.
${ch.length?'':''}`;const ap=$('#applyFit');if(ap)ap.onclick=()=>{S.params=f.pr;save();rebuild()}}} else if(tab==='cuts'){el.innerHTML=`

Cut list

${pl.cutlist.map(c=>``).join('')}
PartQtyFromSizeNote
${esc(c.name)}${c.qty}${esc((BF.STOCK[c.src]||BF.SHEETS[c.src]).n)}${c.sheet?BF.frac(c.w,S.unit)+' × '+BF.frac(c.L,S.unit):BF.frac(c.L,S.unit)+(c.w?' × '+BF.frac(c.w,S.unit)+' rip':'')}${esc(c.note)}

All sizes are actual (a 2x4 is 1-1/2" × 3-1/2"). 1/8" kerf allowed between cuts.

Cutting diagrams

${pl.lumber.map(l=>`
${esc(l.n)}
${l.boards.map(b=>`
${BF.ftin(b.L)} board
${(()=>{let x=0;return b.cuts.map(c=>{const w=c.L/b.L*100;const s=`${esc(c.name.replace(/ \(.*/,''))} ${BF.frac(c.L)}`;x+=w+BF.KERF/b.L*100;return s}).join('')})()}
`).join('')}`).join('')} ${pl.sheets.map(s=>s.res.sheets.map((sh,i)=>`
${esc(s.n)} · sheet ${i+1}
${sh.rows.flatMap(r=>r.items).map(it=>`${esc(it.name)} ${BF.frac(it.L)}×${BF.frac(it.w)}`).join('')}`).join('')).join('')}
`} else if(tab==='tools'){el.innerHTML=`
${pl.tools.map(t=>{const T=BF.TOOLS[t.k];return`
${T.cat}${t.have?' · you have it':' · needed'}

${esc(T.n)}

${esc(T.what)}

${T.tip?`
${esc(T.tip)}
`:''}
`}).join('')}

How each job gets done with your tools

${Object.keys(BF.METHODS).map(k=>{const K2=BF.kit(ctx());return``}).join('')}
${k}${esc(K2.mtxt(k))}
`} else if(tab==='eng'){el.innerHTML=`${K.fixes.map(f=>`
🔧 ${esc(f)}
`).join('')}${K.checks.map(c=>`

${c.ok?'PASS':'FAIL'}${esc(c.kind)}${esc(c.label)}

${c.ratio!=null?'Uses '+Math.round(c.ratio*100)+'% of the limit':''}
${esc(c.math)}
`).join('')} ${K.notes.map(n=>`
${esc(n)}
`).join('')}

Method: allowable stress design with NDS 2018 reference values and adjustment factors, USDA Wood Handbook stiffness for furniture, CPSC Pub. 324 for home playgrounds. Checks assume No.2 grade lumber in good condition, fasteners installed as described, and level, firm ground. BUILD FORGE is a careful calculator, not a licensed engineer: anything people climb on or sit under is worth a second look by someone qualified, and local codes and HOA rules may add requirements.

`} else if(tab==='safety'){const gen=['Safety glasses for every cut; hearing protection for saws and routers; a dust mask for sanding, MDF and treated lumber.','Keep blades sharp and guards on. Unplug or remove the battery to change blades and bits.','Clamp work instead of holding it; never reach across a running blade.','Pilot-drill near ends to prevent splits that weaken joints.','Call 811 before digging.']; el.innerHTML=`

For this build

    ${[...K.safety,...K.checks.filter(c=>/safety|Playground|Food|Wildlife|Garden/i.test(c.kind)).map(c=>(c.ok?'✓ ':'✗ ')+c.label)].map(s=>`
  • ${esc(s)}
  • `).join('')}

Every build

    ${gen.map(s=>`
  • ${esc(s)}
  • `).join('')}
`} else if(tab==='report'){el.innerHTML=`

Build report

A complete printable plan: cover render, specs, engineering checks with the math, shopping list, cut list and diagrams, tools, every step with its picture, and safety. Anyone can follow it in the shop.

`;$('#repOpen').onclick=()=>BF.report(PLAN,'open',S.unit);$('#repDl').onclick=()=>BF.report(PLAN,'dl',S.unit)}} // ---------- BUILD-ALONG PLAYER (animated, voiced) const Player={open(i){const pl=PLAN;const ov=document.createElement('div');ov.id='player';ov.innerHTML=`

`;document.body.appendChild(ov); let cur=i,t0=performance.now(),yaw=-0.65;const cv=$('#plC');const show=k=>{cur=Math.max(0,Math.min(pl.K.steps.length-1,k));t0=performance.now();const s=pl.K.steps[cur];$('#plH').textContent=pl.g.n.toUpperCase();$('#plN').textContent=`STEP ${cur+1} OF ${pl.K.steps.length}`;$('#plT').textContent=s.t;$('#plD').textContent=s.d+(s.tip?' Tip: '+s.tip:'');$('#plTools').innerHTML=s.tools.map(t=>`${esc(BF.TOOLS[t]?BF.TOOLS[t].n:t)}`).join('');$('#plNx').textContent=cur===pl.K.steps.length-1?'Finish ✓':'Next step ▶';say(s.t+'. '+s.d)}; const say=t=>{try{speechSynthesis.cancel();if(!S.voice)return;const u=new SpeechSynthesisUtterance(t);u.rate=0.98;speechSynthesis.speak(u)}catch(e){}}; const loop=t=>{if(!document.body.contains(ov))return;requestAnimationFrame(loop);const [x,W,H]=fit(cv);const a=Math.min(1,(t-t0)/1300);yaw+=0.0016;BF.r3d.render(x,W,H,pl.K,{step:cur,anim:a,hl:true,yaw,pitch:0.4,zoom:0.8,zone:false,labels:false,future:0.12})};requestAnimationFrame(loop); $('#plX').onclick=()=>{try{speechSynthesis.cancel()}catch(e){}ov.remove()};$('#plP').onclick=()=>show(cur-1);$('#plNx').onclick=()=>{if(cur===pl.K.steps.length-1){$('#plX').click();toast('Nice work. Check every bolt again after a week of use.');return}show(cur+1)};$('#plR').onclick=()=>show(cur);$('#plV').onclick=()=>{S.voice=!S.voice;save();$('#plV').textContent=S.voice?'🔊 Voice on':'🔇 Voice off';if(!S.voice)try{speechSynthesis.cancel()}catch(e){}};show(i)}}; // ---------- ASK (Shop Mind chat) const Ask={log:[],push(r,t,src){this.log.push({r,t,src});this.render()},render(){const c=$('#chatLog');if(!c)return;c.innerHTML=this.log.map(m=>`
${esc(m.t)}${m.src?`${esc(m.src)}`:''}
`).join('');c.scrollTop=c.scrollHeight}, async llm(q,img){if(!BF.AI.AIS.on){return false}this.push('a','…thinking (local model)');try{const msgs=[{role:'system',content:BF.AI.sys(PLAN)},...this.log.filter(m=>!m.t.startsWith('…')).slice(-8).map(m=>({role:m.r==='u'?'user':'assistant',content:m.t}))];const a=await BF.AI.chat(msgs,img);this.log.pop();this.push('a',a||'(no answer)','local model '+BF.AI.AIS.model+' · advice, not engineered; numbers come from the plan engine')}catch(e){this.log.pop();this.push('a','Could not reach the local model. In Settings, check the address and that Ollama was started with OLLAMA_ORIGINS=*.')}return true}, async send(q){if(!q.trim())return;this.push('u',q);const t=q.toLowerCase(); const edit=PLAN&&/(make it|change|wider|narrower|taller|shorter|longer|deeper|bigger|smaller|larger|add |remove|without|use |switch|cheaper|under \$|budget)/.test(t);if(edit){const r=BF.AI.parse(q,PLAN.gid); if(r.gid===PLAN.gid&&r.unavail&&r.unavail.length&&!Object.keys(r.params).length&&!r.budget){this.push('a',`${r.unavail.join(', ')} isn't an option for the ${PLAN.g.n} — it comes in ${PLAN.g.params.find(x=>x.k==='mat').opts.map(o=>o[1].split(' (')[0]).join(', ')}. Nothing was changed. Say "use ${PLAN.g.params.find(x=>x.k==='mat').opts[0][0]}" or pick the material in the plan panel.`,'plan unchanged');return} if((r.gid===PLAN.gid||(r.budget&&!r.gid))&&(Object.keys(r.params).length||r.budget||r.relSize)){const before=PLAN.cost;if(r.relSize){const sc=BF.AI.scaleParams(PLAN.gid,Object.assign({},PLAN.p),r.relSize);(r.relApplied||[]).forEach(k=>delete r.params[k]);Object.assign(S.params,sc.params);if(Object.keys(sc.params).length)r.said.push(r.relSize.f>1?'scaled up ~25% from before':'scaled down ~20% from before')}S.params=Object.assign({},S.params,r.params);if(r.budget){S.budget=r.budget;const f=BF.fitBudget(PLAN.gid,S.params,ctx(),r.budget);if(f)S.params=f.pr}save();rebuild();const pl=PLAN;this.push('a',`Updated: ${r.said.join(', ')||'budget fit'}. New cost ${BF.money(pl.cost)} (was ${BF.money(before)}). ${pl.ok?'All checks still pass.':pl.fails.length+' check(s) need attention: '+pl.fails.map(c=>c.label).join('; ')}${r.unavail&&r.unavail.length?'\nNot applied: '+r.unavail.join(', ')+' (not an option for this design).':''}${pl.K.fixes.length?'\nEngine: '+pl.K.fixes.join(' '):''}`,'plan updated');return}} if(/^(build|make|design|i want|can you make|plan)/.test(t)||(!PLAN&&BF.AI.parse(q).gid)){const r=BF.AI.parse(q);if(r.clarify){this.push('a',r.clarify.q+'\nOptions: '+r.clarify.options.map(o=>o.label).join(' · ')+'. Say which one — or tap its chip in the Studio.','one quick question');return}if(r.gid){openPlan(r.gid,r.params,'New plan from Shop Mind');go('ask');this.push('a',`Started a ${BF.GEN[r.gid].n} plan${r.said.length?' with '+r.said.join(', '):''}: ${BF.money(PLAN.cost)}, ${PLAN.ok?'all checks pass':PLAN.fails.length+' issue(s)'}. Open "My plan" to see the 3D build.`,'BUILD FORGE engine');return}} const rc=BF.AI.parse(q,PLAN&&PLAN.gid);if(rc.clarify){this.push('a',rc.clarify.q+'\nOptions: '+rc.clarify.options.map(o=>o.label).join(' · ')+'. Say which one — or tap its chip in the Studio.','one quick question');return} const a=BF.AI.answer(q,PLAN);if(a&&!(BF.AI.AIS.on&&a.src==='BUILD FORGE library'&&q.length>60)){this.push('a',a.a,a.src);return} if(await this.llm(q))return;this.push('a',`I don't have a solid answer for that offline. I can explain any tool, wood, joint or safety rule, answer "is it strong enough?", "what does step 3 mean?", "what will it cost?", or change the plan ("make it 48 wide", "add a lid", "under $300"). Connect a local model in Settings for open conversation.`,'built-in')}}; function drawAsk(){const box=$('#ask');if(box.dataset.done){Ask.render();return}box.dataset.done=1;box.innerHTML=`
shop mind

Ask anything while you build

Answers come from your plan, the engineering engine and the library. Edits like "make it 6 ft long" or "use cedar" update the plan live.

${['Is it strong enough?','What will it cost?','What tools do I need?','What does step 3 mean?','Make it cheaper','What is a pocket hole?','Which wood is best outdoors?','How do I find a stud?'].map(q=>``).join('')}
`; const send=()=>{const v=$('#askIn').value;$('#askIn').value='';Ask.send(v)};$('#askGo').onclick=send;$('#askIn').onkeydown=e=>{if(e.key==='Enter')send()};box.querySelectorAll('[data-q]').forEach(b=>b.onclick=()=>Ask.send(b.dataset.q));if(!Ask.log.length)Ask.push('a',PLAN?`Ready to help with your ${PLAN.g.n}.`:'Hi. Describe a build, or open a project and ask me about it.');else Ask.render()} // ---------- LIBRARY function drawLib(){const box=$('#library');if(box.dataset.done)return;box.dataset.done=1;const cats={};Object.entries(BF.TOOLS).forEach(([k,t])=>(cats[t.cat]=cats[t.cat]||[]).push(t)); box.innerHTML=`
reference

Library

${['Tools','Wood','Lumber sizes','Techniques','Playground rules','Birds'].map((l,i)=>``).join('')}
`; const views=[()=>`
${Object.values(BF.TOOLS).map(t=>`
${t.cat} · ~${BF.money(t.c)}

${esc(t.n)}

${esc(t.what)}

${t.tip?`
${esc(t.tip)}
`:''}
`).join('')}
`, ()=>`
${Object.values(BF.CLEAR).map(w=>``).join('')}
WoodJanka (hardness)Stiffness EStrength (MOR)Food safeNotes
${esc(w.n)}${w.janka} lbf${(w.E/1e6).toFixed(2)}M psi${w.MOR} psi${w.food?'yes':'no'}${esc(w.look)}

USDA Forest Products Laboratory, Wood Handbook (clear wood, 12% moisture). Structural lumber uses NDS design values:

${Object.values(BF.SPECIES).map(s=>``).join('')}
GradeFbFvFcE
${esc(s.n)}${s.Fb||'by width'}${s.Fv}${s.Fc||'by width'}${(s.E/1e6).toFixed(1)}M
`, ()=>`
${Object.values(BF.STOCK).map(s=>``).join('')}${Object.values(BF.SHEETS).map(s=>``).join('')}
CalledActuallyLengthsTypical price
${esc(s.n)}${BF.frac(s.t)} × ${BF.frac(s.w)}${s.len.map(l=>BF.ftin(l)).join(', ')}${BF.money(Object.values(s.pr)[0])}+
${esc(s.n)}${BF.frac(s.t)} thick${s.W}" × ${s.L}"${BF.money(s.pr)}
`, ()=>`
${BF.KB.map(([k,a])=>`

${esc(k)}

${esc(a)}

`).join('')}
`, ()=>`

Home playground essentials (CPSC Pub. 324)

    ${['Surfacing: 9" of wood chips, engineered wood fiber or shredded rubber for equipment up to 8 ft; sand or pea gravel 9" for up to 5 ft. Install 12" (it compacts). Never grass, dirt, concrete or asphalt.','Use zone: 6 ft in all directions; for swings 2× the pivot height in front and behind; tire swings: chain length + 6 ft radius.','Openings: under 3-1/2" or over 9" (head entrapment).','Platforms over 30": guardrails or barriers (30–48" rail ≥ 25"; 48–72" barrier ≥ 27"; over 72" ≥ 33").','Swings: at most 2 per bay; 24" apart; 30" from the frame; belt-swing pivot ≤ 8 ft; seats 12"–16" above surfacing.','No open S-hooks, protruding bolts, sharp edges or ropes tied on. Check monthly.','Keep equipment 6 ft from fences, houses, trees; place slides out of direct sun.'].map(s=>`
  • ${esc(s)}
  • `).join('')}
`, ()=>`
${Object.values(BF.BIRDS).map(b=>``).join('')}
BirdHoleFloorDepthHole above floorMount
${b.n}${BF.frac(b.hole)}${b.floor}" × ${b.floor}"${b.depth}"${BF.frac(b.holeH)}${esc(b.mount)}

NestWatch, Cornell Lab of Ornithology.

`]; const show=i=>{$('#libBody').innerHTML=views[i]();box.querySelectorAll('[data-l]').forEach(b=>b.classList.toggle('on',+b.dataset.l===i))};box.querySelectorAll('[data-l]').forEach(b=>b.onclick=()=>show(+b.dataset.l));show(0)} // ---------- SETTINGS function drawSettings(){const box=$('#settings');const A=BF.AI.AIS;box.innerHTML=`
preferences

Settings

Units

Lumber is still bought by its US names; sizes display in your unit.

Saved projects

${S.saved.length?`${S.saved.map((s,i)=>``).join('')}
${esc(s.name)}
${new Date(s.at).toLocaleDateString()}
${BF.money(s.cost)}
`:'

Nothing saved yet.

'}

Local AI (optional)

Shop Mind's built-in engine always works offline. For open-ended chat and photo understanding, run a free model on this computer with Ollama (ollama.com): ollama pull llama3.2 and, for photos, ollama pull llava. Start it with OLLAMA_ORIGINS=* so this file can talk to it. Nothing leaves your machine.

${A.on?'Connected: '+esc(A.models.join(', ')):'Not connected'}

${A.on?``:''}

Your store's prices

Change any price; every plan updates.

${Object.entries(BF.STOCK).map(([k,s])=>{const L=s.len[0];return``}).join('')}${Object.entries(BF.SHEETS).map(([k,s])=>``).join('')}${Object.entries(BF.HW).filter(([,h])=>h.pr>0).map(([k,h])=>``).join('')}
ItemLengthPrice
${esc(s.n)}${BF.ftin(L)}
${esc(s.n)}sheet
${esc(h.n)}each
`; box.querySelectorAll('[data-u]').forEach(b=>b.onclick=()=>{S.unit=b.dataset.u;save();drawSettings()}); box.querySelectorAll('[data-pk]').forEach(i=>i.onchange=()=>{const k=i.dataset.pk,L=+i.dataset.len,s=BF.STOCK[k];const f=(+i.value)/s.pr[L];S.prices[k]={};s.len.forEach(l=>S.prices[k][l]=+(s.pr[l]*f).toFixed(2));save();rebuild()}); box.querySelectorAll('[data-sk],[data-hk]').forEach(i=>i.onchange=()=>{S.prices[i.dataset.sk||i.dataset.hk]=+i.value;save();rebuild()}); box.querySelectorAll('[data-open]').forEach(a=>a.onclick=e=>{e.preventDefault();const s=S.saved[+a.dataset.open];openPlan(s.gid,s.params)});box.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{S.saved.splice(+b.dataset.del,1);save();drawSettings()}); $('#exp').onclick=()=>{const b=new Blob([JSON.stringify(S)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='build-forge-backup.json';a.click()};$('#imp').onchange=e=>{const r=new FileReader();r.onload=()=>{try{Object.assign(S,JSON.parse(r.result));BF.PRICE_OVR=S.prices;save();toast('Imported');drawSettings()}catch(x){toast('Not a BUILD FORGE backup')}};r.readAsText(e.target.files[0])}; $('#aiTest').onclick=async()=>{S.ai.url=$('#aiUrl').value.trim().replace(/\/$/,'');BF.AI.AIS.url=S.ai.url;save();await BF.AI.probe();drawSettings()};const m=$('#aiM');if(m)m.onchange=()=>{BF.AI.AIS.model=m.value}} BF.UI={S,save,go,openPlan,setPlan,rebuild,toast,fit,Ask,get plan(){return PLAN},ctx}; document.addEventListener('DOMContentLoaded',()=>{$('nav.tabs').innerHTML=PAGES.map(([k,l])=>`${l}`).join('');$$('nav.tabs a').forEach(a=>a.onclick=e=>{e.preventDefault();go(a.dataset.p)});$('.brand').onclick=()=>go('studio'); drawStudio();if(S.gid)PLAN=BF.makePlan(S.gid,S.params,ctx());const h=(location.hash||'#studio').slice(1);go(PAGES.find(p=>p[0]===h)?h:'studio');addEventListener('resize',()=>{if($('#plan').classList.contains('on'))paint()})}); })();