markuno_lib 1.2.72 → 1.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/markcad.js CHANGED
@@ -538,7 +538,7 @@ function calcoladivisioni(ff,notused,shape2,oggetti){return makedivisions(ff,sha
538
538
  * @param {THREE.Material} [mat=null] - Materiale da applicare
539
539
  * @param {number} [size=5] - Dimensione della sfera
540
540
  * @returns {THREE.Mesh} Punto 3D
541
- */function getpoint(p,id,mat=null,size=5){let tm;const pointgeom=new THREE.SphereGeometry(size,8,8);if(tm=new THREE.Mesh(pointgeom,mat||randombasemat()),id){let sp=getspriteid(id||"",size);sp.position.set(1.2*size,0,1.2*size),tm.add(sp)}return tm.position.set(p.x,0,p.y),tm}async function smat(gcad,file,op={}){op||(op={});let ky=hash(file+JSON.stringify(op));return gcad.smats[ky]||(gcad.smats[ky]=await async function smat0(gcad,file,op={}){let fileini=file,paramstr="",isColore=!1;file.startsWith("#")&&(isColore=!0,/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?=$|[[(])/.test(file)||(file=file.slice(1)));let basefile=file;const paramMatch=file.match(/^(.*)\[([^\]]+)\]$/);paramMatch&&(basefile=paramMatch[1],paramstr=paramMatch[2]);const p={};paramstr&&paramstr.split(/[,;]/).forEach((kv=>{let[k,v]=kv.split("=").map((x=>x.trim()));void 0!==v&&(["e"].includes(k)?p[k]=v.startsWith("0x")?parseInt(v):parseFloat(v):isNaN(parseFloat(v))?p[k]=v:p[k]=parseFloat(v))}));const mappaParam={s:["sx","sy"],sx:["sx"],sy:["sy"],rot:["rot"],br:["brightness"],r:["roughness"],m:["metalness"],h:["bumpScale"],n:["normalScale"],d:["bumpScale"],b:["bumpScale"],e:["emissiveIntensity"],ec:["emissive"],env:["envMapIntensity"],o:["opacity"],t:["transparent"],at:["alphaTest"]};let rot0=op.rot,scale0=parseFloat(op.s)||1;delete op.s;let optot={...op};for(let k in p)if(mappaParam[k])for(let t of mappaParam[k])optot[t]=p[k];let transparent=!!optot?.transparent,sx=(optot.sx??optot.s??p.sx??p.s??1)*scale0,sy=(optot.sy??optot.s??p.sy??p.s??1)*scale0,rot=Number((optot.rot??0)+(rot0??0))*PIF;try{let tm={roughness:optot.roughness??.5,metalness:optot.metalness??0,side:THREE.DoubleSide,envMapIntensity:optot.env??.6};if(void 0!==optot.normalScale){let ns=Number(optot.normalScale);isNaN(ns)||0===ns||(tm.normalScale=new THREE.Vector2(ns,ns))}let hasNormal=!1,hasBump=!1;if(file.includes("(")||isColore){let{base:base,files:files,transparent:t2}=function getFilesToLoad(isColore,basefile){let files=[],m=basefile.match(/^([^(]+)\((([a-zA-Z0-9_\-/]+)_([a-z]+)|([a-z]+))\)$/);if(!m)return{base:basefile,files:files};let base=m[1],transparent=!1,mapalias=m[3]||base,suffstr=m[4]||m[5]||"";isColore||files.push({suff:"",file:`${base}.webp`});for(let s of suffstr)"t"==s?(transparent=!0,m[3]&&suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`})):suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`});return{base:base,files:files,transparent:transparent}}(isColore,basefile);if(transparent=t2,files.some((f=>"n"===f.suff))&&(files=files.filter((f=>"h"!==f.suff))),0===optot.roughness&&(files=files.filter((f=>"r"!==f.suff))),0===optot.metalness&&(files=files.filter((f=>"m"!==f.suff))),0===optot.emissiveIntensity&&(files=files.filter((f=>"e"!==f.suff))),files&&files.length){let textures=await Promise.all(files.map((f=>gcad.tex(f.file,sx,sy,rot).catch((()=>null)))));for(let i=0;i<files.length;i++){let t=textures[i];if(!t)continue;let suff=files[i].suff,{prop:prop,extra:extra}=suffissoMap[suff];tm[prop]=t,"normalMap"===extra?(hasNormal=!0,tm.normalMap=t,tm.normalScale=tm.normalScale??new THREE.Vector2(1,1)):"bumpScale"===extra?(hasBump=!0,tm.bumpMap=t):Array.isArray(extra)&&extra.includes("emissive")&&void 0!==optot.emissiveIntensity&&0!==optot.emissiveIntensity&&(tm.emissive=optot.emissive||16777215,tm.emissiveIntensity=optot.emissiveIntensity??1)}}isColore&&(tm.color=new THREE.Color(base))}else if(basefile.includes(".")){let tx=await gcad.tex(basefile,sx,sy,rot);if(!tx)return mwhite;tm.map=tx}if(hasNormal&&hasBump?delete tm.bumpMap:hasBump&&(tm.bumpScale=optot.bumpScale??.03),tm.transparent=!!transparent,tm.transparent&&(tm.depthWrite=!1,tm.opacity=optot?.opacity??1),void 0!==optot.brightness){let bf=Number(optot.brightness);!isNaN(bf)&&bf>0&&1!==bf&&(tm.color||(tm.color=new THREE.Color(1,1,1)),tm.color.multiplyScalar(bf))}return new THREE.MeshStandardMaterial(tm)}catch(error){return console.log("errore mat:",error.message,fileini),mwhite}}
541
+ */function getpoint(p,id,mat=null,size=5){let tm;const pointgeom=new THREE.SphereGeometry(size,8,8);if(tm=new THREE.Mesh(pointgeom,mat||randombasemat()),id){let sp=getspriteid(id||"",size);sp.position.set(1.2*size,0,1.2*size),tm.add(sp)}return tm.position.set(p.x,0,p.y),tm}async function smat(gcad,file,op={}){op||(op={});let ky=hash(file+JSON.stringify(op));return gcad.smats[ky]||(gcad.smats[ky]=await async function smat0(gcad,file,op={}){let fileini=file,paramstr="",isColore=!1;file.startsWith("#")&&(isColore=!0,/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?=$|[[(])/.test(file)||(file=file.slice(1)));let basefile=file;const paramMatch=file.match(/^(.*)\[([^\]]+)\]$/);paramMatch&&(basefile=paramMatch[1],paramstr=paramMatch[2]);const p={};paramstr&&paramstr.split(/[,;]/).forEach((kv=>{let[k,v]=kv.split("=").map((x=>x.trim()));void 0!==v&&(["e"].includes(k)?p[k]=v.startsWith("0x")?parseInt(v):parseFloat(v):isNaN(parseFloat(v))?p[k]=v:p[k]=parseFloat(v))}));const mappaParam={s:["sx","sy"],sx:["sx"],sy:["sy"],rot:["rot"],br:["brightness"],r:["roughness"],m:["metalness"],h:["bumpScale"],n:["normalScale"],d:["bumpScale"],b:["bumpScale"],e:["emissiveIntensity"],ec:["emissive"],env:["envMapIntensity"],o:["opacity"],t:["transparent"],at:["alphaTest"]};let rot0=op.rot,scale0=parseFloat(op.s)||1;delete op.s;let optot={...op};for(let k in p)if(mappaParam[k])for(let t of mappaParam[k])optot[t]=p[k];let transparent=!!optot?.transparent,sx=(optot.sx??optot.s??p.sx??p.s??1)*scale0,sy=(optot.sy??optot.s??p.sy??p.s??1)*scale0,rot=Number((optot.rot??0)+(rot0??0))*PIF;try{let tm={roughness:optot.roughness??.5,metalness:optot.metalness??0,side:THREE.DoubleSide,envMapIntensity:optot.env??.6};if(void 0!==optot.normalScale){let ns=Number(optot.normalScale);isNaN(ns)||0===ns||(tm.normalScale=new THREE.Vector2(ns,ns))}let hasNormal=!1,hasBump=!1;if(file.includes("(")||isColore){let{base:base,files:files,transparent:t2}=function getFilesToLoad(isColore,basefile){let files=[],m=basefile.match(/^([^(]+)\((([a-zA-Z0-9_\-/]+)_([a-z]+)|([a-z]+))\)$/);if(!m)return{base:basefile,files:files};let base=m[1],transparent=!1,mapalias=m[3]||base,suffstr=m[4]||m[5]||"";isColore||files.push({suff:"",file:`${base}.webp`,cs:!0});for(let s of suffstr)"t"==s?(transparent=!0,m[3]&&suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`,cs:!1})):suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`,cs:!!["","n","e"].includes(s)});return{base:base,files:files,transparent:transparent}}(isColore,basefile);if(transparent=t2,files.some((f=>"n"===f.suff))&&(files=files.filter((f=>"h"!==f.suff))),0===optot.roughness&&(files=files.filter((f=>"r"!==f.suff))),0===optot.metalness&&(files=files.filter((f=>"m"!==f.suff))),0===optot.emissiveIntensity&&(files=files.filter((f=>"e"!==f.suff))),files&&files.length){let textures=await Promise.all(files.map((f=>gcad.tex(f.file,sx,sy,rot).catch((()=>null)))));for(let i=0;i<files.length;i++){let t=textures[i];if(!t)continue;t&&t.isTexture&&(t.colorSpace=files[i].cs?THREE.SRGBColorSpace:THREE.LinearSRGBColorSpace);let suff=files[i].suff,{prop:prop,extra:extra}=suffissoMap[suff];tm[prop]=t,"normalMap"===extra?(hasNormal=!0,tm.normalMap=t,tm.normalScale=tm.normalScale??new THREE.Vector2(1,1)):"bumpScale"===extra?(hasBump=!0,tm.bumpMap=t):Array.isArray(extra)&&extra.includes("emissive")&&void 0!==optot.emissiveIntensity&&0!==optot.emissiveIntensity&&(tm.emissive=optot.emissive||16777215,tm.emissiveIntensity=optot.emissiveIntensity??1)}}isColore&&(tm.color=new THREE.Color(base))}else if(basefile.includes(".")){let tx=await gcad.tex(basefile,sx,sy,rot);if(!tx)return mwhite;tm.map=tx}if(hasNormal&&hasBump?delete tm.bumpMap:hasBump&&(tm.bumpScale=optot.bumpScale??.03),tm.transparent=!!transparent,tm.transparent&&(tm.depthWrite=!1,tm.opacity=optot?.opacity??1),void 0!==optot.brightness){let bf=Number(optot.brightness);!isNaN(bf)&&bf>0&&1!==bf&&(tm.color||(tm.color=new THREE.Color(1,1,1)),tm.color.multiplyScalar(bf))}return console.log("tm",tm),new THREE.MeshStandardMaterial(tm)}catch(error){return console.log("errore mat:",error.message,fileini),mwhite}}
542
542
  /**
543
543
  * Estrae tutte le texture usate nella scena glb e le converte in file WEBP.
544
544
  * @param {THREE.Object3D} root - nodo root (es: gltf.scene)
@@ -1095,7 +1095,7 @@ constructor(data,position,debugMessage){this.data=data,this.offset=position,this
1095
1095
  /**
1096
1096
  * Libera tutte le risorse caricate
1097
1097
  */
1098
- async function clearmat(){for(const key in _textures)if(_textures[key]){const texture=await _textures[key];texture?.dispose()}for(const key in _smats)_smats[key]&&_smats[key]?.dispose();for(const[key,texOrPromise]of textureCache.entries()){const texture=texOrPromise instanceof Promise?await texOrPromise:texOrPromise;texture?.dispose&&texture.dispose()}textureCache.clear(),_textures={},_smats={}}return{clearmatricole:()=>{_gmatricole={}},islog:islog,clear:async function clear(){function destroymesh(mesh){function disposeMaterial(material){material.map&&material.map.dispose(),material.lightMap&&material.lightMap.dispose(),material.bumpMap&&material.bumpMap.dispose(),material.normalMap&&material.normalMap.dispose(),material.specularMap&&material.specularMap.dispose(),material.dispose()}mesh&&mesh.traverse((child=>{child.isMesh&&(child.geometry.dispose(),child.material&&(Array.isArray(child.material)?child.material.forEach(disposeMaterial):disposeMaterial(child.material)))}))}_gmatricole={},_cachefn={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();for(const key in _meshes)if(_meshes[key]){destroymesh(await _meshes[key])}await clearmat(),_movs={},_textures={},_meshes={},_geometries={},_smats={},_scripts={}},clearmat:clearmat,getScript:async function getScript(file){file.endsWith(".custom")?file=file.slice(0,-7):file.endsWith(".js")&&(file=file.slice(0,-3));let key=hash(`${getcat()}|${file}`);if(!_scripts[key]){let script;try{script=await P.fetch("mufiles/customfn",{id:getcat(),name:file,ispar:1})}catch(error){script=`log('undefined ${getcat()}/${file}: ${error.message}');`}_scripts[key]=script}return _scripts[key]},checkScripts:async function checkScripts(files){let cl=[];if(!files||!Array.isArray(files))return;let ct=getcat();files=[...files,"_ricalcolatop","_ricalcolaaltri","_ricalcolalinee"];for(let f of files){let key=hash(`${ct}|${f}`);_scripts[key]||cl.push(f)}if(cl?.length){let scripts=await P.fetch("mufiles/customfn",{id:ct,name:cl,ispar:1});if(scripts)for(let s of scripts){let key=hash(`${ct}|${s.n}`);_scripts[key]=s.v}}},get loaderGLTF(){return _loaderGLTF},get gmats(){return _gmatricole},scripts:()=>Object.keys(_scripts),get geo(){return _geometries},get movs(){return _movs},get textures(){return _textures},get smats(){return _smats},get meshes(){return _meshes},get cacheFns(){return _cachefn},dump(){console.log(`SMATS:\n${Object.keys(_smats).join(" - ")};\nGEOMS:\n${Object.keys(_geometries).join(" - ")};\nTEX:\n${Object.keys(_textures).join(" - ")};\nMESH:\n${Object.keys(_meshes).join(" - ")};\n`)},get cat(){return getcat()},pushcat(cat){cats.push(cat)},popcat:()=>(cats.length>1&&cats.length--,getcat()),async tex(file,sx=1,sy,rot){let key;return sy||(sy=sx),rot||(rot=0),"__alpha"==file?(key=file,_textures[key]||(_textures[key]=function getfortransparent(){const texture=new THREE.CanvasTexture(function generateTexture(){const canvas=document.createElement("canvas");canvas.width=2,canvas.height=2;const context=canvas.getContext("2d");return context.fillStyle="white",context.fillRect(0,1,2,1),canvas}());return texture.magFilter=THREE.NearestFilter,texture.wrapT=THREE.RepeatWrapping,texture.wrapS=THREE.RepeatWrapping,texture.repeat.set(1,3.5),texture}()),_textures[key]):(key=hash(`${getcat()}|${file}|${sx}|${sy}|${rot}`),_textures[key]||(_textures[key]=new Promise(((resolve,reject)=>{let url;if(file.startsWith("https://"))url=file;else if(P._cdn)if(file.includes("/")){let v=file.split("/");url=`${P._cdn}${v[0]}/textures/${v[1]}`}else url=`${P._cdn}${getcat()}/textures/${file}`;else url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"textures",name:file,force:1});if(textureCache.has(url)){const tex=textureCache.get(url).clone();return tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.center.set(.5,.5),tex.repeat.set(.001*sx,.001*sy),tex.rotation=rot,void resolve(tex)}_loadertex.load(url,(tex=>{textureCache.set(url,tex),tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.repeat.set(.001*sx,.001*sy),tex.center.set(.5,.5),tex.rotation=rot,resolve(tex)}),void 0,(error=>{console.log(`Manca Texture ${file}!. questo rallenta molto il processo`),delete _textures[key],resolve(void 0)}))}))),_textures[key])},async get3ds(file){file.endsWith(".3ds")&&(file=file.slice(0,-4));const key=hash(`${getcat()}|${file}.3ds`);return _meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url,urlt="";file.startsWith("https://")?(url=`${file}.3ds`,urlt=url):P._cdn?(url=`${P._cdn}${getcat()}/3d/${file}.3ds`,urlt=`${P._cdn}${getcat()}/3d/${file}/`):(url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:".3ds"}),urlt=url+"&tex="),_loader3DS.setResourcePath(urlt),_loader3DS.load(url,(object=>{const cache=new WeakMap;object.traverse((n=>{n.isMesh&&n.material&&(n.material=Array.isArray(n.material)?n.material.map((e=>to_std(e,cache))):to_std(n.material,cache))})),object.userData||(object.userData={}),object.userData._ky=key,resolve(object)}),void 0,(error=>{console.log(error),delete _meshes[key],resolve(void 0)}))}))),_meshes[key]},async getglb(file){const ext=".glb";file.endsWith(ext)&&(file=file.slice(0,-4)),file.startsWith("https://")||(file=file.replace(/\//g,"+"));let elemento=(file=file.split("+"))[1];file=file[0];const key=hash(`${getcat()}|${file}${ext}`);_meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url;url=file.startsWith("https://")?`${file}.glb`:P._cdn?`${P._cdn}${getcat()}/3d/${file}.glb`:P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:ext}),_loaderGLTF.setPath(""),_loaderGLTF.setResourcePath((resource=>(console.log("risorsa",resource),`${url}&tex=${resource}`))),_loaderGLTF.load(url,(async gltf=>{const object=gltf.scene;object.userData||(object.userData={}),object.userData._ky=key,resolve(object)}),void 0,(error=>{console.log(error),delete _meshes[key],resolve(void 0)}))})));let tm=_meshes[key];if(elemento){let n=tm?.getObjectByName(elemento);n&&(tm=n)}return tm},replacemats(bb,mats,callback){if(!Array.isArray(mats)||0==mats.length)return bb;const leggi_slot=mat=>{if(!mat)return-1;let s=(mat?.map?.name||mat?.name||mat?.map?.userData?.name||"").toString().trim();if(callback){const s1=callback(s);void 0!==s1&&(s=s1)}if(s.includes("_")&&(s=s.split("_").pop()),!s)return-1;const n=parseInt(s,10);return n>=1&&n<=9?n:-1};let serve_clone=!1,ky=String(bb.userData?._ky||"");if(bb.traverse((n=>{if(!n.isMesh)return;const ms=Array.isArray(n.material)?n.material:[n.material];for(const m of ms){const k=leggi_slot(m);k>0&&mats[k-1]&&(serve_clone=!0,ky+="|"+(mats[k-1].name||mats[k-1].uuid))}})),serve_clone){if(ky=hash(ky),_meshes[ky])return _meshes[ky];const cc=bb.clone(!0);cc.traverse((n=>{if(n.isMesh)if(Array.isArray(n.material))n.material=n.material.map((m=>{if(!m)return m;const k=leggi_slot(m);if(k>0&&mats[k-1]){const t=mats[k-1];return t.needsUpdate=!0,t}return m}));else{const m=n.material,k=leggi_slot(m);n.material=k>0&&mats[k-1]?(mats[k-1].needsUpdate=!0,mats[k-1]):m}})),cc.userData=cc.userData||{},cc.userData._ky=ky,_meshes[ky]=cc,bb=cc}return bb}}}const originalMaterials=new Map;
1098
+ async function clearmat(){for(const key in _textures)if(_textures[key]){const texture=await _textures[key];texture?.dispose()}for(const key in _smats)_smats[key]&&_smats[key]?.dispose();for(const[key,texOrPromise]of textureCache.entries()){const texture=texOrPromise instanceof Promise?await texOrPromise:texOrPromise;texture?.dispose&&texture.dispose()}textureCache.clear(),_textures={},_smats={}}function getdims(obj){let box=(new THREE.Box3).setFromObject(obj),n2=n=>Math.round(100*n)/100;return{zero:{x:n2(-box.min.x),y:n2(-box.min.y),z:n2(-box.min.z)},dim:{x:n2(box.max.x-box.min.x),y:n2(box.max.y-box.min.y),z:n2(box.max.z-box.min.z)},position:obj.position,rotation:{x:obj.rotation.x,y:obj.rotation.y,z:obj.rotation.z},scale:obj.scale}}async function get3ds(file){file.endsWith(".3ds")&&(file=file.slice(0,-4));const key=hash(`${getcat()}|${file}.3ds`);return _meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url,urlt="";file.startsWith("https://")?(url=`${file}.3ds`,urlt=url):P._cdn?(url=`${P._cdn}${getcat()}/3d/${file}.3ds`,urlt=`${P._cdn}${getcat()}/3d/${file}/`):(url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:".3ds"}),urlt=url+"&tex="),_loader3DS.setResourcePath(urlt),_loader3DS.load(url,(object=>{const cache=new WeakMap;object.traverse((n=>{n.isMesh&&n.material&&(n.material=Array.isArray(n.material)?n.material.map((e=>to_std(e,cache))):to_std(n.material,cache))})),object.userData||(object.userData={}),object.userData._ky=key,resolve(object)}),void 0,(error=>{console.log(error),delete _meshes[key],resolve(void 0)}))}))),_meshes[key]}async function getglb(file){const ext=".glb";file.endsWith(ext)&&(file=file.slice(0,-4)),file.startsWith("https://")||(file=file.replace(/\//g,"+"));let elemento=(file=file.split("+"))[1];file=file[0];const key=hash(`${getcat()}|${file}${ext}`);_meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url;url=file.startsWith("https://")?`${file}.glb`:P._cdn?`${P._cdn}${getcat()}/3d/${file}.glb`:P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:ext}),_loaderGLTF.setPath(""),_loaderGLTF.setResourcePath((resource=>(console.log("risorsa",resource),`${url}&tex=${resource}`))),_loaderGLTF.load(url,(async gltf=>{const object=gltf.scene;object.userData||(object.userData={}),object.userData._ky=key,resolve(object)}),void 0,(error=>{console.log(error),delete _meshes[key],resolve(void 0)}))})));let tm=_meshes[key];if(elemento){let n=tm?.getObjectByName(elemento);n&&(tm=n)}return tm}return{clearmatricole:()=>{_gmatricole={}},tex:async function tex(file,sx=1,sy,rot){let key;return sy||(sy=sx),rot||(rot=0),"__alpha"==file?(key=file,_textures[key]||(_textures[key]=function getfortransparent(){const texture=new THREE.CanvasTexture(function generateTexture(){const canvas=document.createElement("canvas");canvas.width=2,canvas.height=2;const context=canvas.getContext("2d");return context.fillStyle="white",context.fillRect(0,1,2,1),canvas}());return texture.magFilter=THREE.NearestFilter,texture.wrapT=THREE.RepeatWrapping,texture.wrapS=THREE.RepeatWrapping,texture.repeat.set(1,3.5),texture}()),_textures[key]):(key=hash(`${getcat()}|${file}|${sx}|${sy}|${rot}`),_textures[key]||(_textures[key]=new Promise(((resolve,reject)=>{let url;if(file.startsWith("https://"))url=file;else if(P._cdn)if(file.includes("/")){let v=file.split("/");url=`${P._cdn}${v[0]}/textures/${v[1]}`}else url=`${P._cdn}${getcat()}/textures/${file}`;else url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"textures",name:file,force:1});if(textureCache.has(url)){const tex=textureCache.get(url).clone();return tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.center.set(.5,.5),tex.repeat.set(.001*sx,.001*sy),tex.rotation=rot,void resolve(tex)}_loadertex.load(url,(tex=>{textureCache.set(url,tex),tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.repeat.set(.001*sx,.001*sy),tex.center.set(.5,.5),tex.rotation=rot,resolve(tex)}),void 0,(error=>{console.log(`Manca Texture ${file}!. questo rallenta molto il processo`),delete _textures[key],resolve(void 0)}))}))),_textures[key])},getglb:getglb,get3ds:get3ds,replacemats:function replacemats(bb,mats,callback){if(!Array.isArray(mats)||0==mats.length)return bb;const leggi_slot=mat=>{if(!mat)return-1;let s=(mat?.map?.name||mat?.name||mat?.map?.userData?.name||"").toString().trim();if(callback){const s1=callback(s);void 0!==s1&&(s=s1)}if(s.includes("_")&&(s=s.split("_").pop()),!s)return-1;const n=parseInt(s,10);return n>=1&&n<=9?n:-1};let serve_clone=!1,ky=String(bb.userData?._ky||"");if(bb.traverse((n=>{if(!n.isMesh)return;const ms=Array.isArray(n.material)?n.material:[n.material];for(const m of ms){const k=leggi_slot(m);k>0&&mats[k-1]&&(serve_clone=!0,ky+="|"+(mats[k-1].name||mats[k-1].uuid))}})),serve_clone){if(ky=hash(ky),_meshes[ky])return _meshes[ky];const cc=bb.clone(!0);cc.traverse((n=>{if(n.isMesh)if(Array.isArray(n.material))n.material=n.material.map((m=>{if(!m)return m;const k=leggi_slot(m);if(k>0&&mats[k-1]){const t=mats[k-1];return t.needsUpdate=!0,t}return m}));else{const m=n.material,k=leggi_slot(m);n.material=k>0&&mats[k-1]?(mats[k-1].needsUpdate=!0,mats[k-1]):m}})),cc.userData=cc.userData||{},cc.userData._ky=ky,_meshes[ky]=cc,bb=cc}return bb},islog:islog,clear:async function clear(){function destroymesh(mesh){function disposeMaterial(material){material.map&&material.map.dispose(),material.lightMap&&material.lightMap.dispose(),material.bumpMap&&material.bumpMap.dispose(),material.normalMap&&material.normalMap.dispose(),material.specularMap&&material.specularMap.dispose(),material.dispose()}mesh&&mesh.traverse((child=>{child.isMesh&&(child.geometry.dispose(),child.material&&(Array.isArray(child.material)?child.material.forEach(disposeMaterial):disposeMaterial(child.material)))}))}_gmatricole={},_cachefn={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();for(const key in _meshes)if(_meshes[key]){destroymesh(await _meshes[key])}await clearmat(),_movs={},_textures={},_meshes={},_geometries={},_smats={},_scripts={}},clearmat:clearmat,getdims:getdims,info3d:async function info3d(file,scale=1,scaley=0,scalez=0){let tm=(file||"").endsWith(".3ds")?await get3ds(file):await getglb(file);if(tm)return scale&&1!=scale&&(tm.scale.set(scale||1,scaley||scale||1,scalez||scale||1),tm.needsUpdate=!0),getdims(tm)},getScript:async function getScript(file){file.endsWith(".custom")?file=file.slice(0,-7):file.endsWith(".js")&&(file=file.slice(0,-3));let key=hash(`${getcat()}|${file}`);if(!_scripts[key]){let script;try{script=await P.fetch("mufiles/customfn",{id:getcat(),name:file,ispar:1})}catch(error){script=`log('undefined ${getcat()}/${file}: ${error.message}');`}_scripts[key]=script}return _scripts[key]},checkScripts:async function checkScripts(files){let cl=[];if(!files||!Array.isArray(files))return;let ct=getcat();files=[...files,"_ricalcolatop","_ricalcolaaltri","_ricalcolalinee"];for(let f of files){let key=hash(`${ct}|${f}`);_scripts[key]||cl.push(f)}if(cl?.length){let scripts=await P.fetch("mufiles/customfn",{id:ct,name:cl,ispar:1});if(scripts)for(let s of scripts){let key=hash(`${ct}|${s.n}`);_scripts[key]=s.v}}},get loaderGLTF(){return _loaderGLTF},get gmats(){return _gmatricole},scripts:()=>Object.keys(_scripts),get geo(){return _geometries},get movs(){return _movs},get textures(){return _textures},get smats(){return _smats},get meshes(){return _meshes},get cacheFns(){return _cachefn},dump(){console.log(`SMATS:\n${Object.keys(_smats).join(" - ")};\nGEOMS:\n${Object.keys(_geometries).join(" - ")};\nTEX:\n${Object.keys(_textures).join(" - ")};\nMESH:\n${Object.keys(_meshes).join(" - ")};\n`)},get cat(){return getcat()},pushcat(cat){cats.push(cat)},popcat:()=>(cats.length>1&&cats.length--,getcat())}}const originalMaterials=new Map;
1099
1099
  /**
1100
1100
  * Salva i materiali originali di tutti i mesh nel gruppo (solo layer <= 20)
1101
1101
  * @param {THREE.Object3D} gruppo
@@ -1115,4 +1115,4 @@ async function clearmat(){for(const key in _textures)if(_textures[key]){const te
1115
1115
  * @param {THREE.Object3D} gruppo - oggetto root
1116
1116
  * @param {Array<{ mats: string[], name?: string }>} matricole - elenco da evidenziare
1117
1117
  * @returns {Promise<File[]>}
1118
- */async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:function addlog(...pars){pars.map((p=>getOggetto(p)))},Math:Math,getcolonne:getcolonne,clean:clean,SP:SP,seeder:seeder,seedarray:seedarray,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white,isdark){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):isdark?(materialline1.color.set(7368816),materialline2.color.set(6316128)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,Vobject,Vscene,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,errorescript,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbb,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getextrude,getface,getfakeshadow,getfakeshadow2,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpannello2,getpoint,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,getthorus,groupfromgeometry,hash,infoestrudi,isfn,ismacro,joinlinestoshapes,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scalaoggetto,scaleunit,seedarray,seeder,setLineColorMode,setorigine,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
1118
+ */async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,info3d:async function info3d(file,scale=1,scaley=0,scalez=0){if(amb.gcad)return await amb.gcad.info3d(file,scale,scaley,scalez)},gcad:amb.gcad,log:function addlog(...pars){pars.map((p=>getOggetto(p)))},Math:Math,getcolonne:getcolonne,clean:clean,SP:SP,seeder:seeder,seedarray:seedarray,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white,isdark){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):isdark?(materialline1.color.set(7368816),materialline2.color.set(6316128)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,Vobject,Vscene,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,errorescript,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbb,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getextrude,getface,getfakeshadow,getfakeshadow2,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpannello2,getpoint,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,getthorus,groupfromgeometry,hash,infoestrudi,isfn,ismacro,joinlinestoshapes,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scalaoggetto,scaleunit,seedarray,seeder,setLineColorMode,setorigine,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
package/bin/markuno.js CHANGED
@@ -253,7 +253,7 @@ this.amb=amb}
253
253
  */async loadContentExtended(content){if("object"==typeof content){for(const x in content)["rows","des","h","alias","obbligo"].includes(x)&&(this[x]=content[x]);"string"==typeof content.def&&content.def.length&&(this.vdef=getcolonne(content.def.trim().toLowerCase())),content.filter&&content.filter.length&&(this.limits=parselimitifromdb(content.filter))}else await this._loadContent(muClComments(content,!1))}todata(){return{name:this.name,des:this.des,alias:this.alias,obbligo:this.obbligo,h:this.h,rows:this.rows,limits:this.limits,key:this.key}}}const _nofunc={};async function getcbfunc(tm,cmd,pars,vari,amb,output){if(cbFunc){if(_nofunc[cmd])return"";let a=await cbFunc(cmd,pars,vari,amb,output);return isObject(a)||(a=(a||"").trim(),"!"==a&&(_nofunc[cmd]=!0,a="")),a}return tm}async function intvaluta(amb,mac,str){return await amb.vari.valuta(str,(async(fun,pars)=>{switch(fun){case"dim":{let dm=muCalc(pars[1]),vv=await dammivariante(amb,mac,pars[2]),col=parseInt(pars[3])||2;return vv&&vv.fromdim?vv.fromdim(dm,col):dm}case"seed":{let n1=pars[1],cl=getcolonne(pars[2]);return cl[seeder(cl.length,n1)]||""}case"seedvar":{let vv=await dammivariante(amb,mac,pars[2]),n1=pars[1],cl=vv.validkeys();if(pars[3]&&pars[4]){let idcol=muCalc(pars[3])-1;if(idcol>=0){let pcol=getcolonne(pars[4]);cl=cl.filter((e=>{let t=vv.rows[e];if(t&&t.v&&t.v[idcol]){let v=getcolonne(t.v[idcol]);if(v)for(let p of pcol)if(v.includes(p))return!0}return!1}))}}let id=seeder(cl.length,n1);return id>=0&&vv.tovar(cl[id])||""}default:return await getcbfunc(`**fun:${fun}**`,fun,pars,amb.vari,amb)}}))}async function dammivariante(amb,macro,ky){let tm;return tm=macro&&macro?.localvar&&macro.localvar[ky]?macro.localvar[ky]:await amb.getvariante(ky),tm}async function impostavariante(amb,macro,a,b,head){let tm,ky=a;if((b=b||"")&&"string"==typeof b){const k=b.indexOf(":");k>=0&&(k>0&&(ky=clean(b.slice(0,k))),b=b.slice(k+1))}
254
254
  /** @type {Variante} */if(head&&head.alias&&(ky=head.alias),macro&&macro.paralias&&macro.paralias[a]&&(ky=macro.paralias[a]),tm=await dammivariante(amb,macro,ky),tm)if(head&&head.t){head.des||(head.des=tm.des);let x8=head?.filtra||"";if(x8.includes("$")&&(x8=await amb.vari.valuta(x8)),"m"===head.t){let col=2;if(b.includes(":")){const xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);const b1=tm.firstvalid(b,getcolonne(head.def));b=tm.tovar(b1)}}else tm.resetfilter(),b=tm.firstvalid(b),b=tm.tovar(b);else head&&head.t&&head.t;return amb.vari.add(a,b),b}async function pushpars(amb,macro,parsfunzione,parsinit){const fatti={},vals=[];if(parsfunzione)for(const x of parsfunzione){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}if(parsinit)for(const x of parsinit){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}return vals}function poppars(amb,tm){if(tm)for(const x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("object"==typeof a?output.push(JSON.stringify(a,null,2)):"string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]?output[output.length-1]+=a.slice(2):output.push(...a.split("\n")))};async function muEval(amb,mac,codice,options){if(!Array.isArray(codice))return errori.add("codice is not a valid parsed array"),[];options||(options={}),options.id||(options.id="_"),options._stackmacro||(options._stackmacro=0),options.limited||(options.limited=!1),amb||errori.add("amb deve essere definito");const vari=amb.vari;amb.maxdelays,amb.cat;const output=[];let macro,pars,xid;tk();for(let ii=0;ii<codice.length;){let riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":{const tm="IF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"IFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);riga.next?(codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)):errori.add("Troppo tempo",riga)}break;case"SELECT":riga.next?(codice[riga.next].t1=await intvaluta(amb,mac,riga.contenuto),ii=riga.next-1):errori.add("manca endselect",riga);break;case"CASE":case"CASES":case"DEFAULT":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{let vv,tm=1;const _getvv=async()=>{let vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv),vv};if("CASE"==riga.tipo){tm=0,vv=await _getvv();const tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();const tmx=riga.t1||"";vv.find((v=>v==tmx))&&(tm=1)}codice[riga.next].jlast=tm?1:0,codice[riga.next].t1=riga.t1,tm||(ii=riga.next-1)}else errori.add("manca select",riga);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{const tm="ELSE"==riga.tipo?1:"ELSEIF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"ELSEIFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)}else errori.add("manca endif",riga);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":vari.push();break;case"POP":vari.pop();break;case"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else if(({macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{}),macro){options._inc=!0,options._stackmacro++;const saved={},parametri=macro.parametri?._;if(parametri&&parametri.length)for(const x of parametri){const x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);const rs1=await muEval(amb,macro,macro.codice,options);for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}break;case"RET":{const a=await intvaluta(amb,mac,riga.contenuto);amb.vari.savevars(a)}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{let{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){const ismacro=!!options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(const x of macro.head)saved[x.cod]=amb.vari.var(x.cod);if(parametri&&parametri.length)for(const x of parametri){const x1=(x.split("=")[0]||"").trim().toLowerCase();x1&&(saved[x1]=vari.dictionary[x1])}}if(macro.codice.length){if(options._stackmacro++,options.grafica&&"function"==typeof options.grafica){let f="",xid="";pars&&pars.length?(f=pars.find((e=>e.startsWith("#id"))),f?(f=await vari.valuta(f.slice(4)),f.startsWith("#")?options.id=f:options.id=hash(`${ii}${macro.name}${optid}${f}`),pars=pars.filter((e=>!e.startsWith("#id"))),xid=options.id):options.id=hash(`z${optid}${ii}`)):options.id=hash(`z${optid}${ii}`);let tm=amb.pick.key;amb.pick.key=options.id;const out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});amb.pick.key=tm,output.push(out)}else{await macro.impostaparametri(parametri,pars);let tm=amb.vari.var("_rootnode");amb.vari.add("_rootnode","0");const rs1=await muEval(amb,macro,macro.codice,options);amb.vari.add("_rootnode",tm),output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];options.id=optid}else errori.add("Macro non trovata!",riga)}break;case"SETDEF":{let cl=getcolonne(riga.contenuto.toLowerCase()),tm=await dammivariante(amb,macro,cl[0]),prf=cl[1]||"def_",filtra=cl[2];if(prf.endsWith("_")||(prf+="_"),tm&&tm.rows){cl=Object.keys(tm.rows),filtra&&(cl=cl.filter((e=>e.startsWith(filtra))));for(let c of cl){let ky=`${prf}${c}`;if(!vari.dictionary[ky]){function torow(tm){const cl=[];if(tm)for(const t of tm.v.slice(1))"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}vari.add(ky,await intvaluta(amb,mac,torow(tm.rows[c])))}}}}break;case"LET":case"LETS":{let i=riga.contenuto.indexOf("="),j=-1;if(i>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){const v=riga.contenuto;if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i).trim());let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}else{const vv=getcolonne(riga.contenuto);for(const v of vv)if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i));let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}}break;case"LETT":{const i=riga.contenuto.indexOf("=");if(i>0){const a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=await intvaluta(amb,mac,riga.contenuto.slice(i+1).trim());vari.add(a,b)}}break;case"LOOK":case"LOOKB":{const cc=getcolonne(await intvaluta(amb,mac,riga.contenuto)),base=muCalc(cc[1]),col=muCalc(cc[3]),ww=await dammivariante(amb,macro,cc[2]);if(ww&&ww.rows){const rr=Object.values(ww.rows).reduce(((t,e)=>{const val=parseInt(e.v[col?col-1:0]);return val&&("LOOKB"==riga.tipo?val<=base&&val>t.v&&(t.v=val,t.c=e.v[0]):val>=base&&val<t.v&&(t.v=val,t.c=e.v[0])),t}),{v:"LOOKB"==riga.tipo?0:1/0,c:""});rr&&rr.c&&(amb.vari.add(cc[0],ww.tovar(rr.c)),options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:cc[0],valore:ww.tovar(rr.c),riga:riga}))}else amb.vari.add(cc[0],`${base},no,no`)}break;case"LETV":case"LETM":case"DEF":{const tm=getcolonne(riga.contenuto);if(tm)for(const x of tm){let{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);const valore=await impostavariante(amb,mac,v.trim().toLowerCase(),o.trim().toLowerCase(),"LETM"==riga.tipo?{t:"m"}:{t:"v"});options._stackmacro<=0&&options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:v,valore:valore,riga:riga})}}}break;case"DO":{const valido=(riga.contenuto||"").trim();let fl=!0;valido&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let vv,valido,elenco,v;if(options.oldstyle?(vv=riga.contenuto.split(","),v=vv[2]||"i",elenco=vv[0],valido=vv[1]):(vv=getcolonne(riga.contenuto||""),v=vv[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||""),v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){const tm=await intvaluta(amb,mac,elenco),xx=tm?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{const txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];const nc=0;if(riga.next){codice[riga.next].for={v:v,elenco:elenco,nc:nc,valido:valido};let voce,fl=!0;v&&elenco.length>0?nc>=elenco.length?fl=!1:(voce=elenco[nc],vari.add(v,voce),valido&&(fl=!muCalc(await intvaluta(amb,mac,valido)))):fl=!1,fl||(ii=riga.next-1)}else errori.add("manca endfor/loop",riga)}break;case"LOOP":{let fl=!0;riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))&&(fl=!1),fl&&(ii=riga.prev-1);break}case"ENDFOR":if(!riga.contenuto||muCalc(await intvaluta(amb,mac,riga.contenuto)))if(riga.for){const{v:v,elenco:elenco,valido:valido}=riga.for;if(v&&elenco.length>0&&riga.for.nc<500)for(;;){if(riga.for.nc++,riga.for.nc<elenco.length){if(vari.add(v,elenco[riga.for.nc]),valido&&muCalc(await intvaluta(amb,mac,valido)))continue;ii=riga.prev;break}break}}else errori.add("manca istruzione for",riga);break;case"BREAK":case"EXIT":case"EXITFOR":riga.next?riga.contenuto.trim()?muCalc(await intvaluta(amb,mac,riga.contenuto))&&(ii=riga.next):ii=riga.next:errori.add("break outside loop",riga);break;case"CONTINUE":riga.next?riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))||(ii=riga.next-1):errori.add("continue outside loop",riga);break;case"MSG":case"LOG":{const tm99=await intvaluta(amb,mac,riga.contenuto);logga(tm99),errori.add(tm99)}break;default:{let tm;if(riga.contenuto.startsWith("!")){tm=await intvaluta(amb,mac,riga.contenuto);let a="";const rr=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(tm);if(rr)if(rr[1].startsWith("."))await getcbfunc(tm,tm.slice(1),[],vari,amb),a="";else{const cmd=rr[1].toLowerCase(),pars=getcolonne(rr[2]||"");a=await getcbfunc(tm,cmd,pars,vari,amb)}a&&outpush(output,a)}else options.parsefnpunto&&"function"==typeof options.parsefnpunto&&riga.contenuto.startsWith(".")?await options.parsefnpunto({dati:riga.contenuto,output:output,id:options.id,vari:amb.vari,amb:amb}):(tm=await intvaluta(amb,mac,riga.contenuto),outpush(output,tm))}}ii++}return output}async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){const output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(const gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){const xgen=mac.genera[genera];if(xgen){output.counter2=0;const working_variant={};async function processavariante(liv){if(output.isTestmode&&output.counter>output.isTestmode)return;if(liv<xgen.vars.length){const xx=xgen.vars[liv];if(!working_variant[xx]){const xvar=await dammivariante(amb,mac,xx),keys=xvar?Object.keys(xvar.rows):void 0;if(keys&&keys.length>0){for(const k of keys)amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1;return}logga("manca la variante",xx)}}for(const x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(const x of xgen.exclude)if(mac.formula[x]){const vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});if(vvv)for(const v of vvv){if(muCalc(v))return}}const out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(const x of xgen.bom)if(mac.formula[x]){let vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});vvv=vvv.join("\n").split("\n");for(const v of vvv)if(v){const tm=getcolonne(v);bb[x]||(bb[x]=[]);const t={};for(let i=0;i<tm.length;i++)t[`c${i}`]=tm[i];bb[x].push(t)}}await async function docallback(callback,out1,bom,xgen,genera,output){let fl=!0;for(const x of out1){const tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;const o={__id:output.counter};for(let i=0;i<tm.length;i++){let key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?(key=key.substr(1),o[key]=Math.round(1e3*muCalc(tm[i]))/1e3):o[key]=tm[i]}await callback(genera,o,fl?bom:void 0,output.counter,output.counter2),fl=!1}}}(callback,out1,bb,xgen,genera,output)}await processavariante(0)}}const DIMS=["l","a","p"],rx1=/^\{(:?(var|valid|formula|genera|header|v|f|g|h))[\s|}]/im,tipifree=["s","g","h","p","q"],tipiheader=[{cod:"t",des:"Variante"},{cod:"q",des:"V.Query"},{cod:"f",des:"Valore Fisso"},{cod:"g",des:"Gruppo"},{cod:"s",des:"Libero"},{cod:"m",des:"Misura"},{cod:"c",des:"Check (no/si)"},{cod:"z",des:"Check (si/no)"},{cod:"h",des:"Hidden"},{cod:"p",des:"Programmato"}],tipicolonna=[{cod:"",des:"Libero"},{cod:"a",des:"Area"},{cod:"t",des:"Thumb",folder:"thumbs"},{cod:"i",des:"Image",folder:"textures"},{cod:"x",des:"3D file",folder:"3d"},{cod:"f",des:"Funzione",folder:"script"}];function valutaCondizioniTestata(vari,str){const vv=str.split("\n");for(const v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,_name){const{name:name,cat:cat}=checkmu(_name,amb.cat||"");this.name=name,this.cat=cat,
255
255
  /** @type {Ambiente} */
256
- this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){const cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(op={}){const{noderiva:noderiva}=op,s={};if(this.dims&&DIMS.forEach((k=>{const t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(const x of this.head)if(!x._h){if(noderiva&&x._d&&x._d.cod)continue;let tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(const x of this.parametri._){const x1=(x.split("=")[0]||"").trim().toLowerCase();let tm=this.amb.vari.var[x1];tm=(tm||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){const ff={},ruleset=this.amb.ruleset||{};pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)}));for(const x of this.head){const tm=ruleset[x.cod];tm&&(tm.islock?(x.visible="0",pars[x.cod]=tm.opz,x._islock=!0):pars[x.cod]||(pars[x.cod]=tm.opz)),"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod]||"",ff[x.cod]=!0)}for(const x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0,pars),this.getparametri()}async setparametro(name,value,propaga=!1,pars={}){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),pars||(pars={}),this.head){const _imposta=async(riga,vv,id,propaga)=>{const nn=riga?.cod;if(riga.valid&&!riga._h1){const t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){const t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";"thlm".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0]);let txold=tx;if("z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){const vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}const tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);if(riga._v=void 0,tx=this.amb.vari.var(nn)||"","thl".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const t2=this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==tx))))));t2.length&&t2.forEach((e=>{let t=this.head.find((h=>h.cod==e.tocod));if(t){let t1=this.amb.vari.var(t.cod);pars&&pars[t.cod]&&(t1=pars[t.cod]),"string"==typeof t1&&(t1=t1.split(",")[0],t1&&t1!=txold&&t1!=tx?delete t._d:(t._v=e.toopz||tx,t._d={cod:riga.cod,opz:e.toopz}))}}))}return tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;const hh=this.head[i0];tm=await _imposta(hh,value,i0),propaga&&delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}isderivato(hd){return"string"==typeof hd&&(hd=this.head.find((e=>e.cod==hd))),!!(hd&&hd._d&&hd._d.cod)}async impostaparametri(parimposta,parcall,ismacro=!1,progettokeys){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const i of this.head)i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias)}progettokeys||(progettokeys={}),parimposta||(parimposta=[]),parcall||(parcall=[]);for(const x of[...parimposta,...parcall]){const i=x.indexOf("=");if(i>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(const h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,progettokeys[h.cod]||h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(const x in this.localvar){const vv=new Variante;setOggetto(vv,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){let name,cat;try{let tm;if(({name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"")),this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&(tm=await cbGetMacro(cat,name),"string"==typeof tm&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),this.amb.checkscript(tm.linkscript),delete tm.linkscript,tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(const x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,_cat,acapo=!1){let res;const{name:name,cat:cat}=checkmu(file,this.cat||_cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){let res;const{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(let i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);let tm=muClComments(res);const t2=[];flin&&(tm=tm.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);const t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;const t2=[];let tm=muClComments(res),flin=!1;const lochead=[];for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;let out=this.codice;for(const t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":{let r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else out=this.errori,out.push(t)}break;case"valid":out=this.valid;break;case"var":case"v":{const r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(r2){const nn=getcolonne(r2[2]),name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else out=this.errori,out.push(t)}break;case"formula":case"f":{const r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else out=this.errori,out.push(t)}break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo);for(const f in this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(const f in this.localvar){const vv=new Variante,v=this.localvar[f];vv.setheader(f,this.cat),vv.rows={};for(const x of v.rows){const c=getcolonne(x),k=c[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid,this.valid=[];for(const t of tm){let p=getcouple(t,",");p={v:p.v,msg:p.o},p.v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;const head=[];for(const t of tm){const rr=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(rr){const pp=getcolonne(rr[2]),c=clean(rr[1]);let ht;if(c){ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht));for(const tp of pp){const p=getcouple(tp);switch(p.v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}}this.head=head,tm=this.genera;const genera={};for(const kk in tm)if(Array.isArray(tm[kk])){const gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const k2 of tm[kk]){const rr=regx.exec(clean(k2));if(rr)switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){let fl=!1;const getparalias=dati=>{const cl=[],co=getcolonne(dati);for(const c of co)if(c.includes(":")){const v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(let i=0;i<codice.length;i++){const rr=/^:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{const rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){let fl=!1;const tk=[];for(;;){const m=/\$([{[(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}{fl=!0;const classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});const{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");let fl=!1;const tk=[];for(;;){const m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}
256
+ this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){const cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(op={}){const{noderiva:noderiva}=op,s={};if(this.dims&&DIMS.forEach((k=>{const t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(const x of this.head)if(!x._h){if(noderiva&&x._d&&x._d.cod)continue;let tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(const x of this.parametri._){const x1=(x.split("=")[0]||"").trim().toLowerCase();let tm=this.amb.vari.var[x1];tm=(tm||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){const ff={},ruleset=this.amb.ruleset||{};pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)}));for(const x of this.head){const tm=ruleset[x.cod];tm&&(tm.islock?(x.visible="0",pars[x.cod]=tm.opz,x._islock=!0):pars[x.cod]||(pars[x.cod]=tm.opz)),"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod]||"",ff[x.cod]=!0)}for(const x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0,pars),this.getparametri()}async setparametro(name,value,propaga=!1,pars={}){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),pars||(pars={}),this.head){const _imposta=async(riga,vv,id,propaga)=>{const nn=riga?.cod;if(riga.valid&&!riga._h1){const t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){const t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";"thlm".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0]);let txold=tx;if("z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){const vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}const tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);if(riga._v=void 0,tx=this.amb.vari.var(nn)||"","thl".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const t2=this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==tx))))));t2.length&&t2.forEach((e=>{let t=this.head.find((h=>h.cod==e.tocod));if(t){let t1=this.amb.vari.var(t.cod);pars&&pars[t.cod]&&(t1=pars[t.cod]),"string"==typeof t1&&(t1=t1.split(",")[0],t1&&t1!=txold&&t1!=tx?delete t._d:(t._v=e.toopz||tx,t._d={cod:riga.cod,opz:e.toopz}))}}))}return tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;const hh=this.head[i0];tm=await _imposta(hh,value,i0),propaga&&delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}isderivato(hd){return"string"==typeof hd&&(hd=this.head.find((e=>e.cod==hd))),!!(hd&&hd._d&&hd._d.cod)}async impostaparametri(parimposta,parcall,ismacro=!1,progettokeys){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const i of this.head)i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias)}progettokeys||(progettokeys={}),parimposta||(parimposta=[]),parcall||(parcall=[]);for(const x of[...parimposta,...parcall]){const i=x.indexOf("=");if(i>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(const h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,progettokeys[h.cod]||h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(const x in this.localvar){const vv=new Variante;setOggetto(vv,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){let name,cat;try{let tm;if(({name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"")),this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&(tm=await cbGetMacro(cat,name),"string"==typeof tm&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),this.amb.checkscripts(tm.linkscript),delete tm.linkscript,tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(const x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,_cat,acapo=!1){let res;const{name:name,cat:cat}=checkmu(file,this.cat||_cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){let res;const{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(let i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);let tm=muClComments(res);const t2=[];flin&&(tm=tm.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);const t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;const t2=[];let tm=muClComments(res),flin=!1;const lochead=[];for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;let out=this.codice;for(const t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":{let r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else out=this.errori,out.push(t)}break;case"valid":out=this.valid;break;case"var":case"v":{const r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(r2){const nn=getcolonne(r2[2]),name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else out=this.errori,out.push(t)}break;case"formula":case"f":{const r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else out=this.errori,out.push(t)}break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo);for(const f in this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(const f in this.localvar){const vv=new Variante,v=this.localvar[f];vv.setheader(f,this.cat),vv.rows={};for(const x of v.rows){const c=getcolonne(x),k=c[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid,this.valid=[];for(const t of tm){let p=getcouple(t,",");p={v:p.v,msg:p.o},p.v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;const head=[];for(const t of tm){const rr=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(rr){const pp=getcolonne(rr[2]),c=clean(rr[1]);let ht;if(c){ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht));for(const tp of pp){const p=getcouple(tp);switch(p.v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}}this.head=head,tm=this.genera;const genera={};for(const kk in tm)if(Array.isArray(tm[kk])){const gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const k2 of tm[kk]){const rr=regx.exec(clean(k2));if(rr)switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){let fl=!1;const getparalias=dati=>{const cl=[],co=getcolonne(dati);for(const c of co)if(c.includes(":")){const v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(let i=0;i<codice.length;i++){const rr=/^:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{const rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){let fl=!1;const tk=[];for(;;){const m=/\$([{[(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}{fl=!0;const classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});const{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");let fl=!1;const tk=[];for(;;){const m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}
257
257
  /**
258
258
  * Analizza il codice sorgente e restituisce un array di token con classi CSS
259
259
  * @param {string} tt - Il codice sorgente da analizzare
@@ -265,4 +265,4 @@ this.imgpreview={},this.vari=new Variabile,this.ruleset={},this.fndotcallback&&t
265
265
  /** @type {Object.<string, Macro>} */
266
266
  this.macro={},
267
267
  /** @type {Object.<string, Variante>} */
268
- this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setimgpreview(cod,img){img?this.imgpreview[cod]=img:delete this.imgpreview[cod]}getimgpreview(cod){return this?.imgpreview[cod||""]}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){const tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(const t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){const tips=fromjson(t.value);for(const tp in tips){const tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;let ct=riga.contenuto;ct.startsWith("$")&&(ct=await this.vari.valuta(ct));const rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(ct);if(!rr)return void errori.add("Macro non valida:"+ct,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));const pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;const ky=`${cat}/${name}`;if(!this.macro[ky]){const tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){const{name:name,cat:cat}=checkmu(cod,this.cat);let n2=name,altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;const key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){const xx=new Variante(this);if(await xx.load(v,this.cat,!0),xx.alias){(await this.getalias())[v]=xx.alias}callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){const mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);const t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){const cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(const x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(const v of info.var)await this.varcompila(v,callback);for(const v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){const tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);const t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);const nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&cbGetVariante){const xv=await cbGetVariante(cat,vn);if(xv&&xv.length)for(const x of xv){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}}async getheaderfromdb(name){const totale=await cbInfo("header",this.cat,name,!this.#deriva);let{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(const r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(const r of rows)if("p"==r.tipo);else{const nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];const vn=[],t=this.varelenco[this.cat];for(const nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){const vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(const x of vars){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){const getkey=n=>n.includes("/")?n:`${this.cat}/${n}`,cl=[];let k;if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){const vv=macros.split(";");for(const v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){const tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(const x of tm){this.checkscripts(x.content?.linkscript),delete x.content?.linkscript;const m=new Macro(this,x.name);for(const t in x.content){const contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}checkscripts(vv){if(vv&&vv.length)for(let v of vv)this.scripts[v.name]||(this.scripts[v.name]=v.value)}async setruleheader(rule,pars,ruleset){const{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));const ky=`${cat}/${name}`;if(!this.macro[ky]){const totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);const tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){const k2=this.macro[`${cat}/${head.rule}`];if(k2)for(const x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;const mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}async splitteroggetti(name){let data=await this.getvariante(name),cl=[];return data?.rows&&Object.values(data.rows).forEach((v=>{cl.push({tipo:v.v[2]||"",cod:v.v[0]||"",des:v.v[1]||"",macro:v.v[4]||"",sps:parseInt(v.v[3])||0,isshape:parseInt(v.v[5])})})),cl.length||cl.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),cl}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){const xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){azzera&&mu.azzera();return mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(const p of pars){const{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){const x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seedarray,seeder,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
268
+ this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setimgpreview(cod,img){img?this.imgpreview[cod]=img:delete this.imgpreview[cod]}getimgpreview(cod){return this?.imgpreview[cod||""]}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){const tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(const t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){const tips=fromjson(t.value);for(const tp in tips){const tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;let ct=riga.contenuto;ct.startsWith("$")&&(ct=await this.vari.valuta(ct));const rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(ct);if(!rr)return void errori.add("Macro non valida:"+ct,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));const pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;const ky=`${cat}/${name}`;if(!this.macro[ky]){const tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){const{name:name,cat:cat}=checkmu(cod,this.cat);let n2=name,altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;const key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){const xx=new Variante(this);if(await xx.load(v,this.cat,!0),xx.alias){(await this.getalias())[v]=xx.alias}callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){const mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);const t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){const cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(const x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(const v of info.var)await this.varcompila(v,callback);for(const v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){const tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);const t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);const nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&cbGetVariante){const xv=await cbGetVariante(cat,vn);if(xv&&xv.length)for(const x of xv){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}}async getheaderfromdb(name){const totale=await cbInfo("header",this.cat,name,!this.#deriva);let{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(const r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(const r of rows)if("p"==r.tipo);else{const nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];const vn=[],t=this.varelenco[this.cat];for(const nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){const vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(const x of vars){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){const getkey=n=>n.includes("/")?n:`${this.cat}/${n}`,cl=[];let k;if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){const vv=macros.split(";");for(const v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){const tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(const x of tm){this.checkscripts(x.content?.linkscript),delete x.content?.linkscript;const m=new Macro(this,x.name);for(const t in x.content){const contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}checkscripts(vv){if(Array.isArray(vv)&&vv.length)for(let v of vv)this.scripts[v.name]||(this.scripts[v.name]=v.value)}async setruleheader(rule,pars,ruleset){const{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));const ky=`${cat}/${name}`;if(!this.macro[ky]){const totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);const tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){const k2=this.macro[`${cat}/${head.rule}`];if(k2)for(const x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;const mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}async splitteroggetti(name){let data=await this.getvariante(name),cl=[];return data?.rows&&Object.values(data.rows).forEach((v=>{cl.push({tipo:v.v[2]||"",cod:v.v[0]||"",des:v.v[1]||"",macro:v.v[4]||"",sps:parseInt(v.v[3])||0,isshape:parseInt(v.v[5])})})),cl.length||cl.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),cl}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){const xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){azzera&&mu.azzera();return mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(const p of pars){const{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){const x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seedarray,seeder,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markuno_lib",
3
- "version": "1.2.72",
3
+ "version": "1.2.74",
4
4
  "description": "Croswil Markuno Language Lib",
5
5
  "author": "Croswil SRL",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -623,9 +623,51 @@ export const mred: any;
623
623
  export const mwhite: any;
624
624
  export function newgcad(P: any, _cat: any, islog?: boolean): {
625
625
  clearmatricole: () => void;
626
+ tex: (file: any, sx: number, sy: any, rot: any) => Promise<any>;
627
+ getglb: (file: any) => Promise<any>;
628
+ get3ds: (file: any) => Promise<any>;
629
+ replacemats: (bb: any, mats: any, callback: any) => any;
626
630
  islog: boolean;
627
631
  clear: () => Promise<void>;
628
632
  clearmat: () => Promise<void>;
633
+ getdims: (obj: any) => {
634
+ zero: {
635
+ x: number;
636
+ y: number;
637
+ z: number;
638
+ };
639
+ dim: {
640
+ x: number;
641
+ y: number;
642
+ z: number;
643
+ };
644
+ position: any;
645
+ rotation: {
646
+ x: any;
647
+ y: any;
648
+ z: any;
649
+ };
650
+ scale: any;
651
+ };
652
+ info3d: (file: any, scale?: number, scaley?: number, scalez?: number) => Promise<{
653
+ zero: {
654
+ x: number;
655
+ y: number;
656
+ z: number;
657
+ };
658
+ dim: {
659
+ x: number;
660
+ y: number;
661
+ z: number;
662
+ };
663
+ position: any;
664
+ rotation: {
665
+ x: any;
666
+ y: any;
667
+ z: any;
668
+ };
669
+ scale: any;
670
+ }>;
629
671
  getScript: (file: any) => Promise<any>;
630
672
  checkScripts: (files: any) => Promise<void>;
631
673
  readonly loaderGLTF: GLTFLoader;
@@ -641,10 +683,6 @@ export function newgcad(P: any, _cat: any, islog?: boolean): {
641
683
  readonly cat: any;
642
684
  pushcat(cat: any): void;
643
685
  popcat: () => any;
644
- tex(file: any, sx: number, sy: any, rot: any): Promise<any>;
645
- get3ds(file: any): Promise<any>;
646
- getglb(file: any): Promise<any>;
647
- replacemats(bb: any, mats: any, callback: any): any;
648
686
  };
649
687
  /**
650
688
  * Calcola il vettore normale unitario di un segmento di linea.