import {applyMatchedFabricFinish} from './matched-fabric-finish.mjs'; import {replaceIndexedFringeWeave} from './indexed-weave.mjs'; import { createLiveEdit } from './live-edit.mjs'; import { DEFAULT_SURFACE } from './renderer.mjs'; import{applyLibraryWeave,transformWeave,paintWeave,replaceDraft,weaveBMP,weaveStatistics,weaveTwill,weaveFace,resizeFullWeave}from'./native-workspace-tools.mjs'; import{projectForSave}from'./project-serialization.mjs'; import{setDoubleCloth,makeDoubleCloth,layerSummary,detectDoubleCloth}from'./double-cloth.mjs'; import{applyDemoYarn,setDemoMaterial}from'./demo-yarns.mjs'; import{resizeStudioWeave,clearStudioWeave,addStudioYarn}from'./studio-actions.mjs'; import{sameNativeGeometry}from'./native-save-geometry.mjs'; import{wheelZoom}from'./view-zoom.mjs'; import{textureRequest}from'./original-texture.mjs'; import{isIndexed}from'./indexed-document.mjs';import{importNativeInWorker,cancelNativeImport}from'./native-file-client.mjs'; import{withPhysicalDPI}from'./png-metadata.mjs'; import{newDocument,validateDocument,toRenderModel,documentWeave,parseSequence,sequenceText,plain,twill}from'./document.mjs'; import{rulerTicks,coordinateAt,zoomAt,calibratePPI,referenceScaleBar,pixelRulerTicks}from'./measurement.mjs'; import{normaliseYarnAppearance}from'./yarn-appearance.mjs';import{openBytes,formatCapabilities}from'./importers.mjs'; const $=id=>document.getElementById(id),worker=new Worker('./worker.mjs',{type:'module'});let libraryWeaveBase=null,doc=newDocument(),view={ppi:96,zoom:1,origin:[0,0],unit:'in'},calibrated=false,seq=0,active=0,busy=false,raster=false,previewURL,past=[],future=[],allColours,lastDPI=96,freshPixels=false,docRevision=0,asyncIntent=0,savedFabric=null,importedColourways=[],pendingOpen=false,textureMetadata=null,textureEpoch=0,textureWorker=null,changedTexture=null,decodedTexture=null,textureView=null,textureCancel=null,nativeSource=null,sourceTextureFallback=null,nativeSaveJob=null,structuralSource=null;let plainPreviewZoomBase=1,dobAuthorJob=null; const sourcePreviews = new WeakMap(); function snapshotProject(project) { const snapshot = structuredClone(project); const source = sourcePreviews.get(project); if (source) sourcePreviews.set(snapshot, source); return snapshot; } let lastPreviewMode = $('mode').value; const previewMode = () => $('mode').value === 'graphical' ? lastPreviewMode : $('mode').value; const previewDocument = () => previewMode() === 'simulation' ? sourcePreviews.get(doc) || doc : doc; const slots=d=>isIndexed(d)?d.palette:d.yarns; const rgbHex=rgb=>'#'+rgb.map(v=>v.toString(16).padStart(2,'0')).join(''),hexRGB=s=>[1,3,5].map(i=>parseInt(s.slice(i,i+2),16)); function status(s,error=false){$('status').textContent=s;$('status').classList.toggle('error',error);} function download(blob,name){const a=document.createElement('a'),url=URL.createObjectURL(blob);a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function viewport(){const r=$('viewport').getBoundingClientRect();return {w:r.width,h:r.height};} function setBusy(b){busy=b;$('png').disabled=b||raster||!freshPixels;$('renderOverlay').hidden=!b;} function paint(rgb,w,h){const c=$('fabric');c.width=w;c.height=h;const rgba=new Uint8ClampedArray(w*h*4);for(let i=0,j=0;i{if(r.id!==active||frameRequest)return;if(!r.ok){freshPixels=false;setBusy(false);$('renderInfo').textContent='Render failed';if(!r.cancelled){status(r.error,true);$('renderOverlay').textContent='Render failed · no current image';$('renderOverlay').hidden=false;}return;}const box=viewport(),sampling=Math.min(devicePixelRatio||1,3400/Math.max(box.w,box.h),Math.sqrt(4900000/(box.w*box.h)));if(r.width!==Math.round(box.w*sampling)||r.height!==Math.round(box.h*sampling)){render();return;}lastDPI=r.dpi;paint(r.rgb,r.width,r.height);freshPixels=true;$('fabric').style.visibility='visible';setBusy(false);$('renderInfo').textContent=r.width+' × '+r.height+' px · '+(r.qualityApplied===2?'2×supersampled':r.qualityBudgetFallback?'1×sample budget':'ready');status(doc.provenance?.scaleRecovery?(isIndexed(doc)?'Saved bitmap ready · physical scale unverified':'Yarn CAD ready · bitmap scale unverified'):isIndexed(previewDocument())?(isIndexed(doc)?'Source repeat ready · palette colour editing':'Source repeat ready · editable yarn CAD'):doc.provenance?.format==='DOB'?'DOB ready · editable yarn colours · independent simulation':'Local render ready · estimated yarn material');};worker.onerror=e=>{setBusy(false);status(e.message,true);}; let frameRequest=0;function render(){if(raster)return;active=++seq;freshPixels=false;$('png').disabled=true;$('renderInfo').textContent='Rendering…';if(frameRequest)cancelAnimationFrame(frameRequest);frameRequest=requestAnimationFrame(()=>{frameRequest=0;renderNow();});} let repeatInches; function drawRepeatFrame() { const frame = $('repeatFrame'); frame.hidden = raster || !repeatInches || !document.body.classList.contains('show-repeat') || !['cad','graphical'].includes($('mode').value); if (frame.hidden) return; const pixelScale = view.ppi * view.zoom; const [width,height] = repeatInches.map(length => length * pixelScale); const offset = (phase, period) => -(((phase * pixelScale) % period + period) % period); Object.assign(frame.style, { left: offset(view.origin[0],width) + 'px', top: offset(view.origin[1],height) + 'px', width: width + 'px', height: height + 'px' }); } window.addEventListener('cad:repeat-frame', drawRepeatFrame); function renderNow() { if (raster) return; freshPixels = false; $('png').disabled = true; $('fabric').style.visibility = 'hidden'; $('renderOverlay').textContent = 'Rendering…'; const {w, h} = viewport(); if (w < 1 || h < 1) return; const project = previewDocument(); const indexed = isIndexed(project); let model; try { model = indexed ? project : toRenderModel(project); } catch (error) { status(error.message, true); return; } if ($('mode').value !== 'fabric' && model.webEffects?.overprint) { const {overprint,...otherEffects}=model.webEffects; model={...model,webEffects:otherEffects}; } repeatInches = indexed ? model.tile.repeatInches : model.repeatInches; const scale = Math.min(devicePixelRatio || 1, 3400 / Math.max(w, h), Math.sqrt(4900000 / (w * h))); const mode = previewMode(); const surface = mode === 'cad' ? {...model.surface, lighting: false, hairiness: 0} : mode === 'simulation' ? DEFAULT_SURFACE : model.surface; const options = { dpi: view.ppi * view.zoom * scale, widthPixels: Math.max(1, Math.round(w * scale)), heightPixels: Math.max(1, Math.round(h * scale)), originInches: view.origin, swatchOrientation: doc.previewOrientation, surface, fillThreadCells: mode === 'cad', wovenBacking: mode !== 'cad' && Boolean(project.provenance?.structuralTDW || project.provenance?.structuralTCW), }; active = ++seq; setBusy(true); $('renderInfo').textContent = 'Rendering…'; worker.postMessage({id: active, model, options}); drawRulers(); } function scaleCanvas(c,w,h){const dpr=devicePixelRatio||1;c.width=Math.max(1,Math.round(w*dpr));c.height=Math.max(1,Math.round(h*dpr));const ctx=c.getContext('2d');ctx.setTransform(dpr,0,0,dpr,0,0);ctx.fillStyle='#f2f1ec';ctx.fillRect(0,0,w,h);return ctx;} function drawRulers(){drawRepeatFrame();const{w,h}=viewport(),cx=scaleCanvas($('topRuler'),w,24),cy=scaleCanvas($('leftRuler'),25,h);$('unitCorner').textContent=view.unit;if(raster&&!textureView){const img=$('preview'),image=img.getBoundingClientRect(),box=$('viewport').getBoundingClientRect();$('unitCorner').textContent='px';if(!img.naturalWidth||!image.width){$('bar').hidden=true;return;}const scale=image.width/img.naturalWidth;for(const[ctx,length,offset,extent,vertical]of[[cx,w,image.left-box.left,img.naturalWidth,false],[cy,h,image.top-box.top,img.naturalHeight,true]]){ctx.strokeStyle='#606b76';ctx.fillStyle='#344352';ctx.font='9px Tahoma';for(const t of pixelRulerTicks({scale,offset,length,extent})){ctx.beginPath();if(vertical){ctx.moveTo(25,t.pixel+.5);ctx.lineTo(t.major?14:20,t.pixel+.5);}else{ctx.moveTo(t.pixel+.5,24);ctx.lineTo(t.pixel+.5,t.major?13:19);}ctx.stroke();if(t.label){if(vertical){ctx.save();ctx.translate(9,t.pixel+3);ctx.rotate(-Math.PI/2);ctx.fillText(t.label,0,0);ctx.restore();}else ctx.fillText(t.label,t.pixel+3,9);}}}$('bar').hidden=false;$('barLine').style.width=(100*scale)+'px';$('barText').textContent='100 source px'+(100*scale>w-60?' · exceeds view':'');$('physical').textContent='Source pixels · physical scale unconfirmed';$('scaleState').textContent='Pixel ruler · physical scale unconfirmed';return;}$('bar').hidden=false;for(const [ctx,length,origin,vertical]of[[cx,w,view.origin[0],false],[cy,h,view.origin[1],true]]){ctx.strokeStyle='#606b76';ctx.fillStyle='#344352';ctx.font='9px Tahoma';ctx.lineWidth=1;for(const t of rulerTicks({unit:view.unit,ppi:view.ppi,zoom:view.zoom,origin,length})){const tick=t.major?11:5;ctx.beginPath();if(vertical){ctx.moveTo(25,t.pixel+.5);ctx.lineTo(25-tick,t.pixel+.5);}else{ctx.moveTo(t.pixel+.5,24);ctx.lineTo(t.pixel+.5,24-tick);}ctx.stroke();if(t.label){if(vertical){ctx.save();ctx.translate(9,t.pixel+3);ctx.rotate(-Math.PI/2);ctx.fillText(t.label,0,0);ctx.restore();}else ctx.fillText(t.label,t.pixel+3,9);}}}const b=referenceScaleBar(view);$('barLine').style.width=b.pixels+'px';$('barText').textContent=b.label+(b.pixels>w-60?' · exceeds view':'');const f={in:1,cm:2.54,mm:25.4}[view.unit];$('physical').textContent=(w/view.ppi/view.zoom*f).toFixed(3)+' × '+(h/view.ppi/view.zoom*f).toFixed(3)+' '+view.unit+(doc.provenance?.scaleVerified===false?' · estimate':'');$('scaleState').textContent=doc.provenance?.scaleVerified===false?'Source scale uncertain · estimate':calibrated?'User-calibrated screen · design units':'Design scale · screen uncalibrated';} function drawWeave(){const c=$('weave'),ctx=c.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,c.width,c.height);if(isIndexed(doc)){$('weaveInfo').textContent='Source indexed repeat '+doc.tile.width+' × '+doc.tile.height+' pixels. Palette editing only; no invented draft.';ctx.fillStyle='#65717d';ctx.font='12px Tahoma';ctx.fillText('Source raster / palette',20,90);return;}const info=documentWeave(doc),g=info.grid,rows=g.length,cols=g[0].length;for(let y=0;y32||info.width>32?'32×32 inspection crop; complete source interlacement renders.':'Black = warp up; white = weft up. Click cell to edit.');} function yarnFields(){const y=slots(doc).find(y=>y.id===$('yarn').value);$('colour').value=rgbHex(y.rgb);$('hex').value=rgbHex(y.rgb).toUpperCase();if(isIndexed(doc)){for(const id of ['count','ply','tpm','haze','noise','shadow'])$(id).value='';return;}const a=normaliseYarnAppearance(y.appearance);$('count').parentElement.firstChild.textContent=(y.sourceCountUnitCode===5?'Width-equivalent count (source unit5) · ':doc.provenance?.countInferred?'Inferred effective count · ':doc.provenance?.structuralTDW?'Effective count · ':'Count · ')+y.unit;$('count').value=y.count;$('ply').value=y.ply;$('tpm').value=a.twistTPM;$('direction').value=a.direction;for(const [id,key]of[['haze','haze'],['noise','noise'],['shadow','shadow']])$(id).value=Math.round(a[key]*100);} function hasWebFeatures(){return !!doc.referenceCalibration||Object.keys(doc.webEffects||{}).length||Object.keys(doc.webGeometry||{}).length;} function rejectWebNative(){if(doc.provenance?.scaleRecovery){status('Native export requires verified TDW scale. Save editable CAD to keep your changes.',true);return true;}if(!hasWebFeatures())return false;status('Web spacing/finishing must be saved as editable CAD; native export cannot preserve it',true);return true;} function editorState(){const direction=$('previewOrientation');direction.disabled=raster;direction.value=doc.previewOrientation==='source'?'':doc.previewOrientation??'';const nativeWeaveMode=!!nativeSource&&!isIndexed(doc)&&!raster&&(doc.provenance?.structuralTDW||doc.provenance?.structuralTCW);$('nativeWeaveSave').hidden=!nativeWeaveMode;$('nativeWeaveSave').disabled=!!doc.provenance?.scaleRecovery||!nativeWeaveMode||!!nativeSaveJob||!!dobAuthorJob;$('nativeWeaveSave').textContent='Save '+(doc.provenance?.structuralTCW?'TCW':'TDW')+' weave (test)';$('exportDOBTest').title='Experimental DOB: Textronic compatibility and finishing unverified.'+((doc.provenance?.countInferred||structuralSource?.provenance?.countInferred)?' TCW effective yarn counts are inferred.':'');$('exportDOBTest').disabled=!!doc.provenance?.scaleRecovery||!!dobAuthorJob||raster||(isIndexed(doc)&&!structuralSource)||!!doc.provenance?.sourceYarnStateUnresolved||!!doc.provenance?.draftSpacingUnresolved||!!doc.provenance?.nativeCountEquivalent||(!isIndexed(doc)&&doc.yarns.some(y=>y.unit!=='Ne'));$('editYarnCAD').hidden=!structuralSource||!isIndexed(doc);$('editYarnCAD').textContent=structuralSource?.provenance?.countInferred?'Edit yarn & weave (inferred count)':'Edit yarn & weave';const nativeExt=nativeSource?.name.toLowerCase().split('.').at(-1);const legacyWriterBlocked=nativeExt==='dob'&&nativeSource&&String.fromCharCode(...nativeSource.bytes.subarray(0,3))!=='NEW';const sourceBaseline=nativeSource&&((doc.provenance?.structuralTDW||doc.provenance?.structuralTCW?nativeSource.structuralDocument:null)||nativeSource.colourways.find(c=>c.sourceIndex===(doc.provenance?.sourceColourwayIndex??0))?.document||nativeSource.document),nativeGeometryChanged=!!sourceBaseline&&!sameNativeGeometry(sourceBaseline,doc);$('nativeSave').disabled=!!doc.provenance?.scaleRecovery||!nativeSource||legacyWriterBlocked||doc.provenance?.sourceYarnStateUnresolved===true||doc.provenance?.sourceColourBanksUnresolved===true||nativeGeometryChanged||!!nativeSaveJob;$('nativeSave').title=doc.provenance?.sourceColourBanksUnresolved?'Some source colour tables conflict; native source writing is blocked. Save CAD or export a validated current bank as test DOB.':nativeGeometryChanged?'Construction/yarn/weave/finishing changed. Save CAD or Export DOB (test); source-format structural saving is not verified.':doc.provenance?.sourceColourBanksUnresolved?'Only validated source colourways are editable. Other source colour records conflict; native source-format writing is blocked.':doc.provenance?.sourceYarnStateUnresolved?'Native yarn state flag unresolved; native colour writing is blocked.':legacyWriterBlocked?'Legacy DOB native writer is unverified; Save CAD preserves editable colours.':'Experimental source-format colour save; vendor application compatibility unverified.';for(const option of $('nativeFormat').options)option.disabled=option.value!==nativeExt;if(nativeExt)$('nativeFormat').value=nativeExt;$('nativeFormat').disabled=!nativeSource;const indexed=isIndexed(doc),locked=raster;for(const id of ['name','epi','ppi','warp','weft','applyDesign','count','ply','tpm','direction','haze','noise','shadow','applyFinish','finish','fiber','relief','roughness','hairiness','plain','twill','invert'])$(id).disabled=locked||indexed;for(const id of ['colour','hex','yarn','applyYarn','save','inspect'])$(id).disabled=locked;$('applyYarn').textContent=indexed?'Apply Colour':'Set Yarn';for(const b of $('yarnPalette').querySelectorAll('button'))b.disabled=locked;$('sourceColourway').disabled=locked;$('mode').disabled=indexed&&!raster&&!structuralSource;if(indexed&&!raster)lastPreviewMode=$('mode').value='simulation';$('weave').style.cursor=locked||indexed?'not-allowed':'crosshair';$('undo').disabled=locked||!past.length;$('redo').disabled=locked||!future.length;$('textureActions').hidden=!savedFabric;$('downloadChanged').disabled=!changedTexture;$('applyTexture').disabled=!changedTexture;$('savedPreview').hidden=!savedFabric;$('savedPreview').textContent=raster?'Return to edited':'Saved original';const layered=!!doc.cloth;const demoMaterial=!indexed&&doc.yarns.some(y=>y.appearance?.demoYarn||y.textronicDrawing);if(layered){for(const id of ['nativeSave','nativeWeaveSave','exportDOBTest','applyTexture'])$(id).disabled=true;$('exportDOBTest').title='Save CAD preserves layers. Native double-cloth settings still require a verified corrected reference.';$('textureNote').textContent='Layer geometry changed. Saved original remains available for comparison; use Fabric simulation for face/back.';}if(demoMaterial){$('nativeWeaveSave').disabled=true;$('nativeSave').disabled=true;$('exportDOBTest').disabled=true;$('exportDOBTest').title='Demo yarn shape is saved in editable CAD; native export cannot preserve this material';$('applyTexture').disabled=true;$('textureNote').textContent='New yarn material uses Fabric simulation. Saved original texture cannot represent a changed yarn shape.';}if(hasWebFeatures()){for(const id of['nativeSave','nativeWeaveSave','exportDOBTest','applyTexture']){$(id).disabled=true;$(id).title='Save editable CAD to preserve web spacing/finishing. Native export / saved original cannot represent these edits.';}$('textureNote').textContent='Web spacing/finishing uses independent Fabric simulation; original saved texture remains unchanged.';}refreshTextureMenu();refreshPantoneTarget();} function refreshTextureMenu(){ const controls={applyTexture:$('applyTexture').disabled,downloadChanged:$('downloadChanged').disabled,downloadOriginal:!savedFabric}; for(const [id,disabled] of Object.entries(controls)){ for(const button of document.querySelectorAll(`#mainMenus [data-click="${id}"]`))button.disabled=disabled; } for(const button of document.querySelectorAll('#mainMenus [data-interface-target="apply-original"]'))button.disabled=controls.applyTexture; const note=$('savedTextureMenuStatus'); if(note){ note.hidden=!savedFabric; note.textContent=savedFabric?$('textureNote').textContent:''; } } function fields(){const texture=importedColourways.find(c=>c.sourceIndex===(doc.provenance?.sourceColourwayIndex??0))?.texture||sourceTextureFallback;if(texture&&texture.preview!==savedFabric){savedFabric=texture.preview;textureMetadata=texture.metadata;decodedTexture=null;}$('importMode').hidden=!isIndexed(doc)&&doc.provenance?.format!=='DOB'&&!doc.provenance?.structuralTDW&&!doc.provenance?.structuralTCW;$('importMode').textContent=isIndexed(doc)?'Source palette colour editing. Grey construction controls are not supplied by this converter mode.':doc.provenance?.sourceColourBanksUnresolved?'Only validated source colourways are editable. Other source colour records conflict; native source-format writing is blocked.':doc.provenance?.sourceYarnStateUnresolved?'Native yarn state flag1 unresolved. Single-face colour CAD only; native export and original texture blocked.':doc.provenance?.draftSpacingUnresolved?'Source X draft symbols retained. Saved binary interlacement verified; gap spacing and physical scale are unresolved.':doc.provenance?.nativeCountEquivalent?'Source unit5 count is retained; displayed Ne is count/2.8 for native default-width equivalence. Source unit name/alternate finishing are unverified.':doc.provenance?.appearanceUnresolved?'Source colour CAD · special yarn appearance/finishing not rendered.':doc.provenance?.structuralTCW?'TCW source plans / weave. Effective Ne inferred from calibrated native width; original ply split is unverified.':doc.provenance?.structuralTDW?'TDW source plans / full shaft control · effective Ne; native ply split unverified.':'DOB source yarn/weave data · finishing remains an independent simulation.';$('yarnHeading').textContent=isIndexed(doc)?'Source palette colours':'Edit Yarn / Yarn Effect';$('inspect').textContent=isIndexed(doc)?'Zoom repeat':'Inspect yarn';$('sourceColourway').value=String(doc.provenance?.sourceColourwayIndex??0);const selected=$('yarn').value;$('article').textContent=doc.article;$('name').value=doc.article;for(const id of ['epi','ppi'])$(id).value=isIndexed(doc)?'':doc.construction[id];$('warp').value=isIndexed(doc)?'':sequenceText(doc.warp);$('weft').value=isIndexed(doc)?'':sequenceText(doc.weft);$('yarn').replaceChildren();$('yarnPalette').replaceChildren();for(const y of slots(doc)){$('yarn').add(new Option(isIndexed(doc)?y.id+' · '+(y.label||'Source colour'):y.id+' · '+(y.axis?'Weft':'Warp')+' · '+(y.sourceCountUnitCode===5?y.sourceCount+'/'+y.ply+' source unit5 (width-equiv. '+Number(y.count.toFixed(3))+' Ne)':Number(y.count.toFixed(3))+'/'+y.ply+' '+y.unit),y.id));const b=document.createElement('button');b.style.background=rgbHex(y.rgb);b.title=isIndexed(doc)?y.label:y.id+' · '+y.count+'/'+y.ply;const t=document.createElement('span');t.textContent=y.id;b.append(t);b.onclick=()=>{if(raster)return;asyncIntent++;$('yarn').value=y.id;$('yarn').onchange();pane('design');};$('yarnPalette').append(b);}if(slots(doc).some(y=>y.id===selected))$('yarn').value=selected;yarnFields();for(const k of ['roughness','relief','fiber','hairiness'])$(k).value=doc.surface?.[k]??{roughness:.76,relief:.52,fiber:.42,hairiness:.22}[k];$('finish').value=doc.surface?.finish||'natural';drawWeave();editorState();publishStudioState();} function leavePreview(){textureView=null;raster=false;$('preview').hidden=true;$('fabric').hidden=false;$('bar').hidden=false;if(previewURL){URL.revokeObjectURL(previewURL);previewURL=null;}} function commit(next,{sourcePreview}={}){validateDocument(next);cancelNativeSave();invalidateTexture();cancelNativeImport();docRevision++;asyncIntent++;if(JSON.stringify(next)===JSON.stringify(doc)){leavePreview();fields();render();return;}past.push(snapshotProject(doc));if(past.length>40)past.shift();future.length=0;doc=structuredClone(next);if(sourcePreview)sourcePreviews.set(doc,sourcePreview);leavePreview();fields();render();queueTexture();} $('previewOrientation').onchange=()=>handle(()=>{ if(raster)return; const next=structuredClone(doc); const direction=$('previewOrientation').value; if(direction)next.previewOrientation=direction; else delete next.previewOrientation; commit(next,{sourcePreview:sourcePreviews.get(doc)}); }); function handle(fn){try{fn();}catch(e){status(e.message,true);}} $('new').onclick=()=>{scopedColourIds=undefined;scopedColourBlocked=false;window.dispatchEvent(new Event('cad:reset-pantone'));libraryWeaveBase=null;structuralSource=null;nativeSource=null;sourceTextureFallback=null;savedFabric=null;decodedTexture=null;textureMetadata=null;importedColourways=[];$('sourceColourway').hidden=true;commit(newDocument());past.length=0;future.length=0;fields();view.origin=[0,0];view.zoom=1;$('zoom').value='1';render();pane('design');window.dispatchEvent(new CustomEvent('cad:show-inspector',{detail:'construction'}));status('New independent design created. Enter construction and yarn pattern.');}; $('applyDesign').onclick=()=>handle(()=>{if(isIndexed(doc)||raster)return;const next=structuredClone(doc);next.article=$('name').value.trim();const construction={epi:Number($('epi').value),ppi:Number($('ppi').value)}; if(next.construction.epi!==construction.epi||next.construction.ppi!==construction.ppi){ delete next.sourceRepeatInches; next.construction={...next.construction,...construction}; } if(JSON.stringify(next)!==JSON.stringify(doc))commit(next);}); $('applyYarn').onclick=()=>handle(()=>{if(raster)return;const next=structuredClone(doc),y=slots(next).find(y=>y.id===$('yarn').value);if(isIndexed(next)){y.rgb=hexRGB($('colour').value);commit(next);return;}const changedCount=y.count!==Number($('count').value)||y.ply!==Number($('ply').value);y.count=Number($('count').value);y.ply=Number($('ply').value);const newRGB=hexRGB($('colour').value);if(y.appearance?.demoYarn&&y.rgb.some((v,i)=>v!==newRGB[i]))y.appearance.demoYarn.colourMode='tint';y.rgb=newRGB;if(changedCount){if(y.appearance?.demoYarn){const tex=y.unit==='Ne'?590.541/y.count:y.unit==='Denier'?y.count/9:y.count;y.diameterMm=Math.sqrt(tex*y.ply)/y.appearance.demoYarn.dimensionFactor;}else delete y.diameterMm;}y.appearance=normaliseYarnAppearance({...y.appearance,twistTPM:Number($('tpm').value),direction:$('direction').value,haze:Number($('haze').value)/100,noise:Number($('noise').value)/100,shadow:Number($('shadow').value)/100});if(JSON.stringify(next)!==JSON.stringify(doc))commit(next);}); $('applyFinish').onclick=()=>handle(()=>{if(isIndexed(doc)||raster)return;const next=structuredClone(doc);next.surface={...next.surface,lighting:true,finish:$('finish').value,finishStrength:.65,...Object.fromEntries(['roughness','relief','fiber','hairiness'].map(k=>[k,Number($(k).value)]))};if(JSON.stringify(next)!==JSON.stringify(doc))commit(next);}); let scopedColourIds,scopedColourBlocked=false; $('yarn').onchange=()=>{ scopedColourIds=undefined; scopedColourBlocked=false; asyncIntent++; yarnFields(); publishStudioState(); refreshPantoneTarget(); }; function applyYarnColours(ids,rgb){ const selected=ids.map(id=>slots(doc).find(yarn=>yarn.id===id)); if(raster||!selected.length||selected.some(yarn=>!yarn))return; if(selected.every(yarn=>yarn.rgb.every((value,index)=>value===rgb[index])))return; const next=structuredClone(doc); for(const yarn of slots(next)){ if(!ids.includes(yarn.id)||yarn.rgb.every((value,index)=>value===rgb[index]))continue; yarn.rgb=[...rgb]; if(yarn.appearance?.demoYarn)yarn.appearance.demoYarn.colourMode='tint'; } commit(next); } function announcePantone(ids,item){ for(const id of ids)window.dispatchEvent(new CustomEvent('cad:pantone-chosen',{detail:{id,item}})); } window.addEventListener('cad:scoped-colours',event=>{ scopedColourIds=event.detail.ids; scopedColourBlocked=event.detail.blocked; refreshPantoneTarget(); }); async function applyHex(id,hex,ids=[id]){ if(raster||id!==$('yarn').value)return; if(!/^#[a-f0-9]{6}$/i.test(hex)){ status('Enter a six-digit HEX colour, for example #22B377.',true); return; } const intent=++asyncIntent,revision=docRevision; let rgb=hexRGB(hex),match; try{ if($('nearest').checked){ if(!allColours){ const response=await fetch('/api/palette/all'); if(!response.ok)throw Error('Could not load the local Pantone palette.'); allColours=await response.json(); } match=allColours.reduce((best,entry)=>{ const distance=entry.rgb.reduce((sum,value,index)=>sum+(value-rgb[index])**2,0); return !best||distance{ const {id,item,ids}=event.detail; choosePantone(id,item,ids); }); window.addEventListener('cad:pick-colour',event=>{ const {id,hex,ids}=event.detail; applyHex(id,hex,ids); }); $('hex').onchange=()=>applyHex($('yarn').value,$('hex').value.trim()); // Commit completed field edits without a separate Apply click. function commitOnChange(ids, handler){ let revision,selected; const valid=()=>ids.every(id=>$(id).type!=='number'||$(id).value.trim()); const live=createLiveEdit(()=>{ if(revision===docRevision&&selected===$('yarn').value&&valid())handler(); }); for(const id of ids){ const element=$(id); element.addEventListener('change',()=>{ if(!valid())return; live.cancel(); handler(); }); if(element.type==='number'||element.type==='range'){ element.addEventListener('input',()=>{ live.cancel(); if(!element.value.trim())return; revision=docRevision; selected=$('yarn').value; live.schedule(); }); } if(element.matches('input:not([type=range]):not([type=color])')){ element.addEventListener('keydown',event=>{ if(event.key==='Enter'){event.preventDefault();element.blur();} }); } } } commitOnChange(['name','epi','ppi'],()=>$('applyDesign').click()); commitOnChange(['count','ply','tpm','direction','haze','noise','shadow'],()=>$('applyYarn').click()); commitOnChange(['finish','fiber','relief','roughness','hairiness'],()=>$('applyFinish').click()); const liveHex=createLiveEdit(()=>{ if(/^#[a-f0-9]{6}$/i.test($('hex').value.trim()))$('hex').onchange(); }); $('colour').addEventListener('input',()=>{ $('hex').value=$('colour').value.toUpperCase(); liveHex.schedule(); }); $('colour').addEventListener('change',()=>{ $('hex').value=$('colour').value.toUpperCase(); liveHex.flush(); }); $('hex').addEventListener('input',liveHex.schedule); $('hex').addEventListener('change',liveHex.cancel); $('hex').addEventListener('keydown',event=>{ if(event.key==='Enter'){event.preventDefault();liveHex.flush();} }); $('yarn').addEventListener('change',liveHex.cancel); $('weave').onclick=e=>handle(()=>{if(isIndexed(doc)||raster)return;const info=documentWeave(doc);if(info.width>32||info.height>32){status('Large source weave is inspection-only; choose a smaller weave to edit.');return;}const r=e.currentTarget.getBoundingClientRect(),x=Math.min(info.width-1,Math.floor((e.clientX-r.left)/r.width*info.width)),y=Math.min(info.height-1,Math.floor((e.clientY-r.top)/r.height*info.height)),next=structuredClone(doc);next.weave=info.grid;next.weave[y][x]=1-next.weave[y][x];delete next.interlacement;delete next.sourceRepeatInches;commit(next);}); for(const [id,grid]of[['plain',plain],['twill',twill]])$(id).onclick=()=>{if(isIndexed(doc)||raster)return;const next=structuredClone(doc);next.weave=grid.map(r=>[...r]);delete next.interlacement;delete next.sourceRepeatInches;commit(next);};$('invert').onclick=()=>{if(isIndexed(doc)||raster)return;const next=structuredClone(doc);if(next.interlacement){next.interlacement.lifting=next.interlacement.lifting.map(r=>r.map(n=>1-n));next.weave=next.interlacement.lifting.map(r=>[...r]);}else next.weave=next.weave.map(r=>r.map(n=>1-n));commit(next);}; for(const [id,from,to]of[['undo',past,future],['redo',future,past]])$(id).onclick=()=>{if(!from.length)return;cancelNativeSave();invalidateTexture();docRevision++;asyncIntent++;to.push(snapshotProject(doc));doc=from.pop();leavePreview();fields();render();queueTexture();}; $('unit').onchange=()=>{view.unit=$('unit').value;drawRulers();};function applyView(next){view=next;const zoom=$('zoom');let custom=zoom.querySelector('[data-custom]');if(![...zoom.options].some(q=>Number(q.value)===view.zoom)){if(!custom){custom=new Option();custom.dataset.custom='true';zoom.add(custom);}custom.value=String(view.zoom);custom.textContent=Number((view.zoom*100).toFixed(1))+'%';}zoom.value=String(view.zoom);drawRulers();if(textureView){redrawTexture();return;}if(raster){$('preview').style.transform='scale('+(view.zoom/plainPreviewZoomBase)+')';drawRulers();$('renderInfo').textContent='Saved pixels · '+Number((view.zoom/plainPreviewZoomBase*100).toFixed(1))+'% · physical scale unconfirmed';return;}leavePreview();fields();render();} $('zoom').onchange=()=>{const{w,h}=viewport();applyView(zoomAt(view,Number($('zoom').value),[w/2,h/2]));}; $('viewport').addEventListener('wheel',e=>{e.preventDefault();if(!e.deltaY)return;const rect=$('viewport').getBoundingClientRect(),delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);applyView(wheelZoom(view,delta,[e.clientX-rect.left,e.clientY-rect.top]));},{passive:false});$('mode').onchange=()=>{ const mode = $('mode').value; if (mode !== 'graphical') lastPreviewMode = mode; if (isIndexed(doc) && structuralSource && mode !== 'simulation') { const sourcePreview = doc; openStructuralCAD(); sourcePreviews.set(doc, sourcePreview); return; } asyncIntent++; leavePreview(); fields(); render(); }; $('inspect').onclick=()=>{if(isIndexed(doc)){view.zoom=32;$('zoom').value='32';view.origin=[0,0];leavePreview();fields();render();return;}const y=doc.yarns.find(y=>y.id===$('yarn').value),plan=y.axis?doc.weft:doc.warp,density=y.axis?doc.construction.ppi:doc.construction.epi;view.zoom=32;view.origin[y.axis]=Math.max(0,(plan.indexOf(y.id)+.5)/density-.02);$('zoom').value='32';leavePreview();render();}; let drag;$('viewport').onpointerdown=e=>{if(raster&&!textureView)return;drag={x:e.clientX,y:e.clientY,origin:[...view.origin]};$('viewport').setPointerCapture(e.pointerId);};$('viewport').onpointerup=e=>{if(!drag)return;view.origin=drag.origin.map((v,i)=>Math.max(0,v-((i?e.clientY-drag.y:e.clientX-drag.x)/(view.ppi*view.zoom))));drag=null;if(textureView)redrawTexture();else render();};$('viewport').onpointercancel=()=>drag=null; let fabricColourTarget; const fabricPickPrompt='Click the fabric to pick a colour. Esc cancels.'; function stopFabricColourPick(){ if(fabricColourTarget&&$('status').textContent===fabricPickPrompt){ status(fabricColourTarget.previousStatus,fabricColourTarget.previousError); } fabricColourTarget=null; $('viewport').classList.remove('picking-colour'); $('pickFabricColour').setAttribute('aria-pressed','false'); } $('pickFabricColour').onclick=()=>{ if(fabricColourTarget){stopFabricColourPick();return;} if(scopedColourBlocked)return; if(raster||!freshPixels){status('Wait for the editable fabric to finish rendering.',true);return;} fabricColourTarget={id:$('yarn').value,revision:docRevision, ids:scopedColourIds,previousStatus:$('status').textContent,previousError:$('status').classList.contains('error')}; $('viewport').classList.add('picking-colour'); $('pickFabricColour').setAttribute('aria-pressed','true'); status(fabricPickPrompt); }; $('viewport').addEventListener('pointerdown',event=>{ if(!fabricColourTarget||event.button!==0)return; if($('coloursWindow').hidden||$('coloursWindow').classList.contains('minimized')){ stopFabricColourPick(); return; } event.preventDefault(); event.stopImmediatePropagation(); const {id,revision,ids}=fabricColourTarget; stopFabricColourPick(); if(raster||!freshPixels||docRevision!==revision||$('yarn').value!==id)return; const canvas=$('fabric'),rect=canvas.getBoundingClientRect(); const x=Math.floor((event.clientX-rect.left)*canvas.width/rect.width); const y=Math.floor((event.clientY-rect.top)*canvas.height/rect.height); if(x<0||y<0||x>=canvas.width||y>=canvas.height)return; const rgb=[...canvas.getContext('2d').getImageData(x,y,1,1).data].slice(0,3); const hex=rgbHex(rgb).toUpperCase(); status('Picked '+hex+' for '+id+'.'); applyHex(id,hex,ids); },true); window.addEventListener('cad:document',event=>{ if(fabricColourTarget&&(event.detail.raster||fabricColourTarget.id!==event.detail.selectedYarn|| fabricColourTarget.revision!==event.detail.revision))stopFabricColourPick(); }); document.addEventListener('keydown',event=>{ if(event.key!=='Escape'||!fabricColourTarget)return; event.preventDefault(); event.stopImmediatePropagation(); stopFabricColourPick(); },true); document.querySelector('[data-close=colours]').addEventListener('click',stopFabricColourPick); $('viewport').onpointermove=e=>{if(raster&&!textureView){const img=$('preview'),r=img.getBoundingClientRect();$('position').textContent='X '+((e.clientX-r.left)*img.naturalWidth/r.width).toFixed(1)+' / Y '+((e.clientY-r.top)*img.naturalHeight/r.height).toFixed(1)+' px';return;}const r=$('viewport').getBoundingClientRect(),f={in:1,cm:2.54,mm:25.4}[view.unit],x=coordinateAt(e.clientX-r.left,{...view,origin:view.origin[0]}),y=coordinateAt(e.clientY-r.top,{...view,origin:view.origin[1]});$('position').textContent='X '+(x*f).toFixed(3)+' / Y '+(y*f).toFixed(3)+' '+view.unit;}; const scaleCalibrationKey = () => `paramount.scale.v1.${screen.width}x${screen.height}.${devicePixelRatio}`; function restoreScreenCalibration() { let saved; try { saved = Number(localStorage.getItem(scaleCalibrationKey())); } catch {} calibrated = Number.isFinite(saved) && saved >= 30 && saved <= 1000; view.ppi = calibrated ? saved : 96; } restoreScreenCalibration(); $('calibrate').onclick = () => { $('calibrationError').textContent = ''; $('measuredMm').value = ''; $('calibrationLine').style.width = referenceScaleBar({unit:'in',ppi:view.ppi,zoom:1}).pixels + 'px'; $('calibration').showModal(); }; $('closeCalibration').onclick = () => $('calibration').close(); $('calibrationForm').onsubmit = event => { event.preventDefault(); try { const line = $('calibrationLine').getBoundingClientRect(); const ppi = calibratePPI(line.width, $('measuredMm').valueAsNumber); let saved = true; try { localStorage.setItem(scaleCalibrationKey(), String(ppi)); } catch { saved = false; } view.ppi = ppi; calibrated = true; $('calibration').close(); applyView({...view,zoom:1}); status(saved ? 'Screen calibration saved for this display and browser zoom.' : 'Screen calibrated for this session.'); } catch (error) { $('calibrationError').textContent = error.message; } }; let activeCalibrationKey = scaleCalibrationKey(); window.addEventListener('resize', () => { const key = scaleCalibrationKey(); if (key === activeCalibrationKey) return; activeCalibrationKey = key; restoreScreenCalibration(); if (textureView) redrawTexture(); else if (!raster) render(); drawRulers(); }); $('save').onclick=()=>download(new Blob([JSON.stringify(projectForSave(doc),null,2)],{type:'application/json'}),doc.article+'.json');$('png').onclick=()=>{if(busy||raster||!freshPixels)return;const outputName=doc.article+'-simulation.png',outputDPI=lastDPI;$('fabric').toBlob(async blob=>{if(blob)download(new Blob([withPhysicalDPI(new Uint8Array(await blob.arrayBuffer()),outputDPI)],{type:'image/png'}),outputName);},'image/png');}; async function showPreview(preview,title){if(!preview?.bytes)throw Error('No supported saved image available');const encoding=String(preview.encoding||'JPEG').toUpperCase(),blob=new Blob([preview.bytes],{type:encoding==='PNG'?'image/png':encoding==='BMP'?'image/bmp':'image/jpeg'}),url=URL.createObjectURL(blob),image=new Image();image.src=url;try{await image.decode();}catch(e){URL.revokeObjectURL(url);throw Error('Saved image cannot be displayed: '+e.message);}return {url,title};} $('preview').onload=()=>{if(raster)drawRulers();}; function usePreview(p){leavePreview();plainPreviewZoomBase=view.zoom;$('preview').style.transform='';textureView=p.texture||null;previewURL=p.url;$('preview').src=p.url;raster=true;active=++seq;setBusy(false);$('preview').hidden=false;$('fabric').hidden=true;$('article').textContent=p.title+(textureView?'':' · saved preview only');drawRulers();if(!textureView){$('physical').textContent='Saved pixels · physical scale unconfirmed';$('scaleState').textContent='Image preview · not recoloured';}else $('scaleState').textContent=doc.provenance?.scaleVerified===false?'Legacy normalized texture · physical scale unverified':textureView.approximate?'Saved texture · approximate recolour':'Original saved texture · source repeat';$('renderInfo').textContent='Saved texture ready · native pixels';editorState();publishStudioState();} let matchedFinishCatalog; let matchedYarnCatalog; async function applyLocalMatchedFinish(document, source) { try { matchedFinishCatalog ??= fetch('./matched-hanger-finishes.json').then(response => response.ok ? response.json() : {}); const catalog = await matchedFinishCatalog; if (!Object.values(catalog).some(entry => entry.name === source.name.toLowerCase())) return document; const hash = await crypto.subtle.digest('SHA-256', source.bytes); const key = Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2,'0')).join(''); if (!catalog[key]) return document; matchedYarnCatalog ??= fetch('./api/paramount-yarns').then(response => response.ok ? response.json() : {records:[]}); const {records} = await matchedYarnCatalog; return applyMatchedFabricFinish(document,catalog[key].finish,records); } catch { return document; } } async function adoptImport(r,name,intent,revision,source=null){if(intent!==asyncIntent||revision!==docRevision)return;let preview=null;if(r.preview?.bytes){try{preview={...r.preview,bytes:new Uint8Array(r.preview.bytes)};}catch{preview=null;}}if(r.kind==='preview-only'){libraryWeaveBase=null;structuralSource=null;nativeSource=null;sourceTextureFallback=null;if(!preview)throw Error(r.reason||'No saved preview');const shown=await showPreview(preview,r.article||name);if(intent!==asyncIntent||revision!==docRevision){URL.revokeObjectURL(shown.url);return;}savedFabric=null;decodedTexture=null;textureMetadata=null;importedColourways=[];$('sourceColourway').hidden=true;usePreview(shown);status(name+': saved-preview only; '+r.reason,true);return;}if(r.kind!=='editable')throw Error(r.reason||'No editable document');validateDocument(r.document); const structure = r.structuralDocument || (!isIndexed(r.document) ? r.document : null); const matchedStructure = source && structure ? await applyLocalMatchedFinish(structure,source) : structure; const matchedDocument = isIndexed(r.document) ? r.document : matchedStructure; if(intent!==asyncIntent||revision!==docRevision)return; libraryWeaveBase=r.libraryWeaveBase||null;structuralSource=r.structuralDocument ? matchedStructure : null;nativeSource=source?{...source,document:structuredClone(r.document),structuralDocument:r.structuralDocument,colourways:r.colourways||[]}:null;savedFabric=preview;decodedTexture=null;textureMetadata=r.textureMetadata||null;sourceTextureFallback=preview?{preview,metadata:textureMetadata}:null;importedColourways=r.colourways||[];for(const bank of importedColourways)if(bank.texture?.preview?.bytes)bank.texture.preview.bytes=new Uint8Array(bank.texture.preview.bytes);$('sourceColourway').replaceChildren();for(const c of importedColourways)$('sourceColourway').add(new Option('Colourway '+c.label,String(c.sourceIndex)));$('sourceColourway').value=String(r.selectedColourway??0);$('sourceColourway').hidden=importedColourways.length<2;view.origin=[0,0];view.zoom=1;$('zoom').value='1';scopedColourIds=undefined;scopedColourBlocked=false;window.dispatchEvent(new Event('cad:reset-pantone'));commit(matchedDocument);past.length=0;future.length=0;fields();status('Opened '+name+' · '+(isIndexed(doc)?'source palette editable':'yarn colours editable')+(r.sourceColourwayConfirmed===false?' · choose source colourway explicitly':'')+(r.warnings?.length?' · '+r.warnings.join(' '):''));} $('sourceColourway').onchange=()=>{const c=importedColourways.find(c=>String(c.sourceIndex)===$('sourceColourway').value);if(c)commit(doc.previewOrientation?{...c.document,previewOrientation:doc.previewOrientation}:c.document);}; $('savedPreview').onclick=async()=>{if(raster){leavePreview();fields();render();return;}if(!savedFabric)return;const intent=++asyncIntent,revision=docRevision;try{const p=await showPreview(savedFabric,doc.provenance?.source||doc.article);if(textureMetadata?.nativePreviewRepeatVerified===true){p.texture={blob:new Blob([savedFabric.bytes]),repeat:doc.sourceRepeatInches,title:doc.article+' · original saved texture',approximate:false};p.url=await tileTextureURL(p.url,doc.sourceRepeatInches);}if(intent!==asyncIntent||revision!==docRevision){URL.revokeObjectURL(p.url);return;}usePreview(p);status('Unchanged original saved fabric. Edit colours in simulation, then Apply colours to fabric below.');}catch(e){status(e.message,true);}}; function invalidateTexture(){liveTexture.cancel();textureEpoch++;if(textureCancel){textureCancel();textureCancel=null;}if(textureWorker){textureWorker.terminate();textureWorker=null;}changedTexture=null;if($('downloadChanged'))$('downloadChanged').disabled=true;if($('textureNote'))$('textureNote').textContent='Saved original is available for comparison';} async function decodeTexture(){if(decodedTexture)return decodedTexture;const p=await showPreview(savedFabric,doc.article);try{const img=new Image();img.src=p.url;await img.decode();const width=img.naturalWidth,height=img.naturalHeight;if(width*height>16000000)throw Error('Saved texture exceeds16millionpixels');const c=document.createElement('canvas');c.width=width;c.height=height;const ctx=c.getContext('2d',{willReadFrequently:true});ctx.fillStyle='white';ctx.fillRect(0,0,width,height);ctx.drawImage(img,0,0);const rgba=ctx.getImageData(0,0,width,height).data,rgb=new Uint8Array(width*height*3);for(let i=0,j=0;iNumber.isFinite(v)&&v>0))return url;try{const img=new Image();img.src=url;await img.decode();const c=document.createElement('canvas'),box=viewport(),sample=Math.min(devicePixelRatio||1,2);c.width=Math.round(box.w*sample);c.height=Math.round(box.h*sample);const ctx=c.getContext('2d'),pattern=ctx.createPattern(img,'repeat'),dpi=view.ppi*view.zoom*sample;pattern.setTransform(new DOMMatrix().translate(-view.origin[0]*dpi,-view.origin[1]*dpi).scale(repeat[0]*dpi/img.naturalWidth,repeat[1]*dpi/img.naturalHeight));ctx.fillStyle=pattern;ctx.fillRect(0,0,c.width,c.height);const blob=await new Promise(resolve=>c.toBlob(resolve,'image/png'));return URL.createObjectURL(blob);}finally{URL.revokeObjectURL(url);}} async function redrawTexture(){const state=textureView;if(!state)return;const intent=++asyncIntent,revision=docRevision;$('renderInfo').textContent='Drawing native texture…';const url=await tileTextureURL(URL.createObjectURL(state.blob),state.repeat);if(intent!==asyncIntent||revision!==docRevision||textureView!==state){URL.revokeObjectURL(url);return;}usePreview({url,title:state.title,texture:state});} function texturePNG(image){const c=document.createElement('canvas');c.width=image.width;c.height=image.height;const a=new Uint8ClampedArray(image.width*image.height*4);for(let i=0,j=0;ic.toBlob(resolve,'image/png'));} const textureSource=()=>importedColourways.find(c=>c.sourceIndex===(doc.provenance?.sourceColourwayIndex??0))?.document; const liveTexture=createLiveEdit(updateChangedTexture,260); function queueTexture() { const source=textureSource(); if(!source||!savedFabric||!textureMetadata||doc.cloth||hasWebFeatures())return; const original=new Map(slots(source).map(yarn=>[yarn.id,yarn.rgb])); if(!slots(doc).some(yarn=>original.get(yarn.id)?.some((value,index)=>value!==yarn.rgb[index])))return; if(!sameNativeGeometry(source,doc)){ $('textureNote').textContent='This construction or material uses the editable simulation.'; return; } $('textureNote').textContent='Updating the saved fabric with the new colours…'; refreshTextureMenu(); liveTexture.schedule(); } async function updateChangedTexture(){ const epoch=textureEpoch; let textureJob; try { const request=textureRequest(textureSource(),doc,{...textureMetadata,colourwayCount:importedColourways.length}); const image=await decodeTexture(); if(epoch!==textureEpoch)return; decodedTexture=image; textureJob=new Worker('./original-texture-worker.mjs',{type:'module'}); textureWorker=textureJob; const result=await new Promise((resolve,reject)=>{ const timer=setTimeout(()=>reject(Error('Saved fabric recolour timed out')),60000); const cancel=()=>{clearTimeout(timer);reject(Error('Saved fabric recolour cancelled'));}; cancel.worker=textureJob; textureCancel=cancel; textureJob.onmessage=({data})=>{clearTimeout(timer);data.ok?resolve(data.result):reject(Error(data.error));}; textureJob.onerror=event=>{clearTimeout(timer);reject(Error(event.message));}; textureJob.postMessage({request,image}); }); if(epoch!==textureEpoch)return; if(!result.allowed)throw Error(result.capability?.message||'Texture placement is unverified for this source'); const blob=await texturePNG(result); if(epoch!==textureEpoch)return; if(!blob)throw Error('Could not create the changed fabric image'); changedTexture={blob,repeat:result.mapping.repeatInches,article:doc.article}; $('textureNote').textContent='Changed fabric ready · saved texture with approximate colours'; } catch(error) { if(epoch===textureEpoch)$('textureNote').textContent=error.message; } finally { textureJob?.terminate(); if(textureCancel?.worker===textureJob)textureCancel=null; if(textureWorker===textureJob)textureWorker=null; if(epoch===textureEpoch)editorState(); } } $('applyTexture').onclick=async()=>{ const result=changedTexture; if(!result)return; const intent=++asyncIntent; const title=result.article+' · recoloured saved fabric'; const texture={blob:result.blob,repeat:result.repeat,title,approximate:true}; const url=await tileTextureURL(URL.createObjectURL(texture.blob),texture.repeat); if(result!==changedTexture||intent!==asyncIntent){ URL.revokeObjectURL(url); return; } usePreview({url,title,texture}); }; $('downloadOriginal').onclick=()=>{if(!savedFabric)return;const ext=String(savedFabric.encoding||'JPEG').toLowerCase().replace('jpeg','jpg');download(new Blob([savedFabric.bytes],{type:'image/'+ext}),doc.article+'-original.'+ext);}; $('downloadChanged').onclick=()=>{if(changedTexture)download(changedTexture.blob,changedTexture.article+'-original-recoloured.png');}; function cancelNativeSave(){cancelDOBAuthor();const job=nativeSaveJob;if(job){nativeSaveJob=null;clearTimeout(job.timer);job.worker.terminate();job.reject(Error('Native save cancelled'));}} $('nativeSave').onclick=async()=>{if(rejectWebNative())return;if(!nativeSource)return;cancelNativeSave();const revision=docRevision,intent=++asyncIntent,source=nativeSource,baseline=(doc.provenance?.structuralTDW||doc.provenance?.structuralTCW?source.structuralDocument:null)||source.colourways.find(c=>c.sourceIndex===(doc.provenance?.sourceColourwayIndex??0))?.document||source.document,w=new Worker('./native-save-worker.mjs',{type:'module'});$('nativeSave').disabled=true;try{const result=await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{w.terminate();reject(Error('Native save timed out; original unchanged'));},60000);nativeSaveJob={worker:w,reject,timer};w.onmessage=({data})=>{clearTimeout(timer);data.ok?resolve(data.result):reject(Error(data.error));};w.onerror=e=>{clearTimeout(timer);reject(Error(e.message));};const buffer=source.bytes.slice().buffer;w.postMessage({filename:source.name,buffer,baseline,document:doc,targetFormat:$('nativeFormat').value,previewImage:changedTexture?{width:changedTexture.width,height:changedTexture.height,rgb:changedTexture.rgb}:undefined},[buffer]);});if(revision!==docRevision||intent!==asyncIntent||nativeSource!==source)return;download(new Blob([result.bytes],{type:'application/octet-stream'}),doc.article+'-edited.'+result.extension);status(result.warning);}catch(e){if(revision===docRevision&&intent===asyncIntent)status(e.message,true);}finally{w.terminate();if(nativeSaveJob?.worker===w)nativeSaveJob=null;editorState();}}; function structuralFabricProject(){if(!structuralSource||!isIndexed(doc))return null;const next=structuredClone(structuralSource);if(doc.webEffects)next.webEffects=structuredClone(doc.webEffects);if(doc.printLibrary){next.printLibrary=structuredClone(doc.printLibrary);next.activePrintId=doc.activePrintId;}if(doc.previewOrientation)next.previewOrientation=doc.previewOrientation;for(const y of next.yarns){const colour=doc.palette.find(p=>p.sourceIndex===y.sourcePaletteIndex);if(colour)y.rgb=[...colour.rgb];}return next;} function openStructuralCAD(){const next=structuralFabricProject();if(!next)return;commit(next);status(doc.provenance?.structuralTCW?'TCW yarn CAD · source plans/weave; effective Ne is inferred, not a recovered ply split.':'TDW source yarn CAD · source effective Ne, full plans and weave. Independent finishing; native ply split not recovered.');} $('editYarnCAD').onclick=openStructuralCAD; $('open').onclick=()=>$('file').click();$('file').onchange=async()=>{const intent=++asyncIntent,revision=docRevision,file=$('file').files[0];if(!file)return;try{const ext=file.name.toLowerCase().split('.').at(-1),native=['dob','tdw','tcw'].includes(ext);if(file.size>(native?128*1048576:ext==='json'?96000000:20000000))throw Error('File exceeds this input type safety limit');status('Opening '+file.name+'…');const buffer=await file.arrayBuffer();if(intent!==asyncIntent||revision!==docRevision)return;if(ext==='jc5'){window.dispatchEvent(new CustomEvent('cad:load-jc5',{detail:{name:file.name,bytes:new Uint8Array(buffer)}}));status('JC5 opened in experimental raw-card workbench; physical hook mapping unverified');return;}if(native){const source={name:file.name,bytes:new Uint8Array(buffer.slice(0))};const r=await importNativeInWorker(file.name,buffer);await adoptImport(r,file.name,intent,revision,source);return;}const r=openBytes(file.name,new Uint8Array(buffer));if(intent!==asyncIntent||revision!==docRevision)return;if(r.kind==='editable'){await adoptImport(r,file.name,intent,revision);}else if(r.kind==='weave'){if(isIndexed(doc))throw Error('Create a new yarn design before applying a weave-only BMP');const next=structuredClone(doc);next.weave=r.matrix;delete next.interlacement;delete next.sourceRepeatInches;commit(next);status('Opened standard BMP weave: '+file.name);}else if(r.kind==='preview'){const p=await showPreview({bytes:r.bytes,encoding:ext},file.name);if(intent!==asyncIntent||revision!==docRevision){URL.revokeObjectURL(p.url);return;}usePreview(p);status(file.name+': image preview only; no construction inferred.');}else status(r.reason,true);}catch(e){if(intent===asyncIntent&&revision===docRevision&&!/cancelled/i.test(e.message))status(e.message,true);}finally{$('file').value='';}}; $('localSample').onchange=async()=>{const key=$('localSample').value;if(!key)return;const intent=++asyncIntent,revision=docRevision;status('Opening read-only local sample…');try{const response=await fetch('/api/local-open?sample='+encodeURIComponent(key)),r=await response.json();if(!response.ok)throw Error(r.error||'Cannot open local sample');const sourceResponse=await fetch('/api/local-source?sample='+encodeURIComponent(key));if(!sourceResponse.ok)throw Error('Cannot retain local native source for save');const filename=r.document?.provenance?.source||key+'.'+r.format.toLowerCase();await adoptImport(r,key,intent,revision,{name:filename,bytes:new Uint8Array(await sourceResponse.arrayBuffer())});}catch(e){if(intent===asyncIntent&&revision===docRevision)status(e.message,true);}finally{$('localSample').value='';}}; function pane(name){window.dispatchEvent(new CustomEvent(name==='design'?'cad:show-inspector':'cad:show-library',{detail:name==='design'?'yarns':name}));for(const el of document.querySelectorAll('[data-pane]'))el.classList.toggle('active',el.dataset.pane===name);for(const p of ['weaves','arahweaves','pantone'])$(p+'Pane').hidden=p!==name;if(name==='arahweaves')window.dispatchEvent(new Event('cad:arahweave-pane'));if(name==='weaves'&&!states.weave.started)load('weave',true);if(name==='pantone'&&!states.pantone.started)load('pantone',true);} for(const b of document.querySelectorAll('[data-pane]'))b.onclick=()=>pane(b.dataset.pane); function refreshPantoneTarget(){ const yarn=slots(doc).find(entry=>entry.id===$('yarn').value); const axis=yarn?.axis===0?'Warp':yarn?.axis===1?'Weft':'Palette slot'; $('pantoneTarget').textContent=raster?'Return to the editable view to change colours.':scopedColourBlocked?'No matching row for the selected scope.':`Apply to ${scopedColourIds?.length>1?scopedColourIds.join(' + '):axis+' '+(yarn?.id??'')}`; for(const button of $('pantoneList').children)button.disabled=raster||scopedColourBlocked; } const states={weave:{list:'weaveList',search:'weaveSearch',more:'moreWeaves',next:0},pantone:{list:'pantoneList',search:'pantoneSearch',more:'morePantone',next:0}}; async function load(kind,reset=false){const s=states[kind];if(s.loading){if(reset)s.resetPending=true;return;}if(reset){s.next=0;$(s.list).replaceChildren();}if(s.next===null)return;s.loading=true;s.started=true;try{const query=$(s.search).value,q=encodeURIComponent(query),url=kind==='pantone'?'/api/palette?':'/api/resources?kind='+kind+'&',r=await(await fetch(url+'q='+q+'&offset='+s.next)).json();if(query!==$(s.search).value){s.resetPending=true;return;}s.next=r.next;for(const item of r.items){const el=document.createElement(kind==='pantone'?'button':'div');if(kind==='pantone'){el.className='swatch';const sw=document.createElement('i');sw.style.background=item.hex;const text=document.createElement('div'),b=document.createElement('b'),small=document.createElement('small');b.textContent=item.colourName?item.code+' · '+item.colourName:item.name;small.textContent=item.hex;text.append(b,small);el.append(sw,text);el.disabled=raster||scopedColourBlocked;el.onclick=()=>{if(!scopedColourBlocked)choosePantone($('yarn').value,item,scopedColourIds);};}else{el.className='asset';const img=document.createElement('img');img.loading='lazy';img.src='/api/resource/'+item.id+'/thumb';img.alt=item.name;const b=document.createElement('b');b.textContent=item.name;const small=document.createElement('small');small.textContent=item.dimensions.join(' × ');const button=document.createElement('button');button.textContent='Use weave';button.disabled=!item.editable;button.title=item.editable?'Use full weave matrix':'Preview only or outside editable limits';button.onclick=async()=>{try{const intent=++asyncIntent,revision=docRevision;const response=await fetch('/api/resource/'+item.id);const r=await response.json();if(intent!==asyncIntent||revision!==docRevision)return;if(!response.ok||!r.editable)throw Error(r.reason||'Unable to load the full BMP weave.');await applyWeaveFromLibrary(r,{keepMatrix:true});status('Weave updated: '+item.name);}catch(error){status(error.message,true);}};el.append(img,b,small,button);}$(s.list).append(el);}$(s.more).hidden=s.next===null;if(kind==='weave')$('weaveTotal').textContent=r.total+' local weave entries · full list, no file-count cap';if(kind==='pantone')$('pantoneTotal').textContent=r.total+' colours · scroll to load more';}catch(e){status(e.message,true);}finally{s.loading=false;if(s.resetPending){s.resetPending=false;load(kind,true);}}} for(const kind of Object.keys(states)){const s=states[kind];$(s.more).onclick=()=>load(kind);let timer;$(s.search).oninput=()=>{clearTimeout(timer);timer=setTimeout(()=>load(kind,true),250);};const parent=$(s.list).parentElement;parent.addEventListener('scroll',()=>{if(parent.scrollTop+parent.clientHeight>=parent.scrollHeight-180)load(kind);});} for(const f of formatCapabilities()){const p=document.createElement('p');p.textContent=f.extension.toUpperCase()+' — '+f.status;$('capabilities').append(p);}$('fileInfo').onclick=()=>$('formatDialog').showModal();$('closeFormats').onclick=()=>$('formatDialog').close();$('full').onclick=()=>document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen(); let resize;new ResizeObserver(()=>{clearTimeout(resize);resize=setTimeout(()=>{drawRulers();if(textureView)redrawTexture();else if(!raster)render();},150);}).observe($('viewport')); fields();render();fetch('/api/status').then(r=>r.json()).then(s=>{const info=document.createElement('p');info.className='note';info.textContent='Catalog: '+s.installedFileCount+' installed files; '+s.catalogOnly+' opaque/runtime records not loaded. '+s.editableWeaveEntries+' editable weaves and '+s.pantoneColours+' local TCX colours.';$('capabilities').prepend(info);status('Local catalog: '+s.editableWeaveEntries+' editable BMP weaves · '+s.pantoneColours+' TCX colours.');}); function cancelDOBAuthor(){const job=dobAuthorJob;if(job){dobAuthorJob=null;clearTimeout(job.timer);job.worker.terminate();job.reject(Error('DOB test export cancelled'));}} $('exportDOBTest').onclick=async()=>{if(rejectWebNative())return;cancelNativeSave();const revision=docRevision,intent=++asyncIntent;let input=structuredClone(doc);if(isIndexed(input)){if(!structuralSource){status('Source yarn/weave data unavailable for DOB export',true);return;}input=structuredClone(structuralSource);for(const y of input.yarns){const c=doc.palette.find(p=>p.sourceIndex===y.sourcePaletteIndex);if(c)y.rgb=[...c.rgb];}}const worker=new Worker('./experimental-dob-worker.mjs',{type:'module'});try{const result=await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{worker.terminate();reject(Error('DOB test export timed out; original unchanged'));},60000);dobAuthorJob={worker,reject,timer};editorState();status('Creating local test DOB…');worker.onmessage=({data})=>{clearTimeout(timer);data.ok?resolve(data.result):reject(Error(data.error));};worker.onerror=e=>{clearTimeout(timer);reject(Error(e.message));};worker.postMessage({document:input,allowInferredCounts:true});});if(revision!==docRevision||intent!==asyncIntent)return;download(new Blob([result.bytes],{type:'application/octet-stream'}),input.article+'-experimental.dob');status('Test DOB saved and locally reopened. Textronic compatibility / finishing unverified.'+(input.provenance?.countInferred?' TCW effective yarn count is inferred.':''));}catch(e){if(revision===docRevision&&intent===asyncIntent)status(e.message,true);}finally{worker.terminate();if(dobAuthorJob?.worker===worker)dobAuthorJob=null;editorState();}}; $('nativeWeaveSave').onclick=async()=>{if(rejectWebNative())return;if(!nativeSource||isIndexed(doc)||raster)return;cancelNativeSave();const revision=docRevision,intent=++asyncIntent,source=nativeSource,w=new Worker('./native-weave-worker.mjs',{type:'module'});try{const result=await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{w.terminate();reject(Error('Native weave test timed out; original unchanged'));},60000);nativeSaveJob={worker:w,reject,timer};editorState();status('Creating local source-format weave test…');w.onmessage=({data})=>{clearTimeout(timer);data.ok?resolve(data.result):reject(Error(data.error));};w.onerror=e=>{clearTimeout(timer);reject(Error(e.message));};const buffer=source.bytes.slice().buffer;w.postMessage({filename:source.name,buffer,document:doc},[buffer]);});if(revision!==docRevision||intent!==asyncIntent||nativeSource!==source)return;download(new Blob([result.bytes],{type:'application/octet-stream'}),doc.article+'-weave-edited.'+result.extension);status('Test '+result.extension.toUpperCase()+' weave saved and locally reopened. Original software compatibility / finishing unverified.');}catch(e){if(revision===docRevision&&intent===asyncIntent)status(e.message,true);}finally{w.terminate();if(nativeSaveJob?.worker===w)nativeSaveJob=null;editorState();}}; function publishStudioState(){const indexed=isIndexed(doc),sample=a=>Array.from({length:Math.min(520,a.length)},(_,i)=>a[Math.floor(i*a.length/Math.min(520,a.length))]);window.dispatchEvent(new CustomEvent('cad:document',{detail:{project:doc,garmentProject:document.getElementById('garmentViewerDialog')?.open?structuralFabricProject():null,screenPpi:view.ppi,revision:docRevision,article:doc.article,indexed,previewMode:previewMode(),yarns:slots(doc),construction:doc.construction,cloth:doc.cloth,selectedYarn:$('yarn').value,raster,warp:indexed?[]:sample(doc.warp),weft:indexed?[]:sample(doc.weft),warpCount:doc.warp?.length||0,weftCount:doc.weft?.length||0,weave:indexed?null:documentWeave(doc)}}));} window.addEventListener('cad:request-state',publishStudioState); window.addEventListener('cad:request-pane',e=>{if(['design','weaves','pantone'].includes(e.detail))pane(e.detail);}); window.addEventListener('cad:open-library-fabric',async event=>{ const {document:project,weaveBase}=event.detail,intent=++asyncIntent,revision=docRevision; try{await adoptImport({kind:'editable',document:project,libraryWeaveBase:weaveBase},project.article,intent,revision);} catch(error){if(intent===asyncIntent)status(error.message,true);} }); async function applyWeaveFromLibrary(binding,options){ if(raster&&!textureView)throw Error('Open an editable yarn design to apply a weave to this preview.'); if(isIndexed(doc)&&doc.provenance?.fringeWeavePlans){ const revision=docRevision,intent=++asyncIntent; const changed=await replaceIndexedFringeWeave(doc,binding); if(revision!==docRevision||intent!==asyncIntent)throw Error('Design changed while applying the weave.'); commit(changed); return; } let base=doc; if(isIndexed(doc)){ const source=libraryWeaveBase||structuralSource; if(!source)throw Error('This design only has editable palette colours. Open an editable yarn design to use this weave.'); base=structuredClone(source); base.article=doc.article; if(doc.previewOrientation)base.previewOrientation=doc.previewOrientation; for(const yarn of base.yarns){ const colour=doc.palette.find(entry=>entry.sourceIndex===yarn.sourcePaletteIndex); if(colour)yarn.rgb=[...colour.rgb]; } } const next=applyLibraryWeave(base,binding,options); if(Object.keys(binding.layout||{}).length){ next.provenance??={}; next.provenance.arahweaveBindingLayout=binding.layout; }else if(next.provenance)delete next.provenance.arahweaveBindingLayout; toRenderModel(next); commit(next); } window.addEventListener('cad:edit',async e=>{const r=e.detail;try{if(r.revision!==undefined&&r.revision!==docRevision)throw Error('Design changed; try the edit again');if(r.type==='apply-library-weave')await applyWeaveFromLibrary(r.binding);else if(r.type==='reset-view')applyView({...view,zoom:1,origin:[0,0]});else{if((raster||isIndexed(doc))&&!(['replace-project','rename-project'].includes(r.type)&&!raster))throw Error('Open editable yarn CAD first');if(r.type==='resize-full-weave')commit(resizeFullWeave(doc,r.width,r.height,{clear:r.clear}));else if(r.type==='resize-weave')commit(resizeStudioWeave(doc,r.width,r.height,{clear:r.clear}));else if(r.type==='clear-weave')commit(clearStudioWeave(doc));else if(r.type==='weave-op'){commit(transformWeave(doc,r.operation,r.amount??1));}else if(r.type==='paint-weave'){commit(paintWeave(doc,r.cells,{lockDraft:r.lockDraft}));}else if(r.type==='set-draft'){commit(replaceDraft(doc,r.draft));}else if(r.type==='weave-twill'){commit(weaveTwill(doc));}else if(r.type==='save-weave-bmp'){download(new Blob([weaveBMP(doc)],{type:'image/bmp'}),doc.article+'-weave.bmp');}else if(r.type==='weave-stats'){window.dispatchEvent(new CustomEvent('cad:weave-stats',{detail:weaveStatistics(doc)}));}else if(r.type==='set-thread-pattern'){const next=structuredClone(doc);next.warp=parseSequence(r.warp,next.yarns.filter(y=>y.axis===0).map(y=>y.id));next.weft=parseSequence(r.weft,next.yarns.filter(y=>y.axis===1).map(y=>y.id));delete next.sourceRepeatInches;commit(next);}else if(r.type==='set-density'){const next=structuredClone(doc);next.construction={epi:r.epi,ppi:r.ppi};delete next.sourceRepeatInches;commit(next);}else if(r.type==='rename-project'){const next=structuredClone(doc);next.article=r.article;commit(next);}else if(r.type==='replace-project'){commit(r.project);}else if(r.type==='redraw'){render();}else if(r.type==='set-cloth'){let next;if(r.mode==='single'){next=structuredClone(doc);delete next.cloth;}else next=setDoubleCloth(doc,r.cloth);toRenderModel(next);commit(next);}else if(r.type==='double-plain'){commit(makeDoubleCloth(doc));}else if(r.type==='analyse-cloth'){const analysis=detectDoubleCloth(toRenderModel(doc));window.dispatchEvent(new CustomEvent('cad:cloth-analysis',{detail:analysis}));}else if(r.type==='apply-demo-yarn'){commit(applyDemoYarn(doc,$('yarn').value,r.record,r.options));}else if(r.type==='set-demo-material'){commit(setDemoMaterial(doc,$('yarn').value,r.parameters));}else if(r.type==='simple-yarn'){const next=structuredClone(doc),y=next.yarns.find(y=>y.id===$('yarn').value);delete y.appearance?.demoYarn;delete y.demoSource;delete y.textronicDrawing;delete y.diameterMm;commit(next);}else if(r.type==='set-yarn-diameter'){const next=structuredClone(doc),y=next.yarns.find(y=>y.id===$('yarn').value),tex=y.unit==='Ne'?590.541/y.count:y.unit==='Denier'?y.count/9:y.count;if(!Number.isFinite(r.factor)||r.factor<1||r.factor>100)throw Error('Dimension factor must be1–100');y.diameterMm=Math.sqrt(tex*y.ply)/r.factor;if(y.appearance?.demoYarn)y.appearance.demoYarn.dimensionFactor=r.factor;commit(next);}else if(r.type==='set-yarn-unit'){if(!['Ne','Tex','Denier'].includes(r.unit))throw Error('Invalid yarn count unit');const next=structuredClone(doc),y=next.yarns.find(y=>y.id===$('yarn').value),tex=y.unit==='Ne'?590.541/y.count:y.unit==='Denier'?y.count/9:y.count;y.count=r.unit==='Ne'?590.541/tex:r.unit==='Denier'?tex*9:tex;y.unit=r.unit;commit(next);}else if(r.type==='add-yarn'){commit(addStudioYarn(doc,r.yarn));$('yarn').value=r.yarn.id;yarnFields();publishStudioState();}else throw Error('Unknown edit');}window.dispatchEvent(new CustomEvent('cad:edit-result',{detail:{id:r.id,ok:true}}));}catch(error){status(error.message,true);window.dispatchEvent(new CustomEvent('cad:edit-result',{detail:{id:r.id,ok:false,error:error.message}}));}});