markuno_lib 1.2.18 → 1.2.19
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 +11 -5
- package/bin/markuno.js +1 -1
- package/package.json +1 -1
- package/types/markcad.d.ts +1 -0
package/bin/markcad.js
CHANGED
|
@@ -523,7 +523,7 @@ function shapeclip(){function toclipformat(pts){let tm=pts.map((e=>({X:Math.roun
|
|
|
523
523
|
* - dati: Array di oggetti con le posizioni elaborate dei tagli
|
|
524
524
|
* - punti: Array di oggetti {a,b} che definiscono inizio e fine di ogni segmento
|
|
525
525
|
*/
|
|
526
|
-
function calcoladivisioni(ff,notused,shape2,oggetti){return makedivisions(ff,shape2,oggetti)},check:check,checkoggetto:checkoggetto,creaprofiloesterno:creaprofiloesterno,create:function create(x,y,bordo,options){options||(options={});let{minvano:minvano,priority:priority,taglio:taglio,tipo:tipo,h1:h1,h2:h2,d1:d1,d2:d2,l1:l1,l2:l2,x1:x1,x2:x2,y1:y1,y2:y2,gvert:gvert,goriz:goriz,forma:forma,area:area}=options,ff=check({x:x,y:y,area:area,bordo:bordo,gvert:gvert,goriz:goriz,priority:priority,minvano:minvano,taglio:taglio,tipo:tipo,h1:h1,h2:h2,l1:l1,l2:l2,d1:d1,x1:x1,y1:y1,d2:d2,x2:x2,y2:y2});return ff.forma=forma,ff},elaborapercorso:elaborapercorso,getbordi:getbordi,makedivisions:makedivisions,makeshape:function makeshape(ff,oggetti){return creaprofiloesterno(ff,oggetti)},priorita:{v:"verticale",h:"orizzontale"},tagli:tagli,tipi:tipi,tipoalign:tipoalign,tipocut:tipocut});async function valutagrafica(amb,startmacro,rulespec,progetto,fnreload){let{getcolonne:getcolonne,muCalc:muCalc,muEval:muEval,tipifree:tipifree}=amb.muvalutatore;rulespec||(rulespec={});for(let x of["l","a","p"]){!amb.vari.var(x)&&startmacro.dims&&amb.vari.add(x,String(startmacro.dims[x].val||100))}let fnlist=new Set;const PARSGLOBAL=["sl","sa","sp","ul","ua","up","ax","ay","az","scx","scy","scz","scale"];let isdimreload,isfnreload=!1,oo=await muEval(amb,startmacro,startmacro.codice,{leveleval:0,checkheader:op=>{let{variante:variante}=op;if(Array.isArray(startmacro.head)){let ff=startmacro.head.find((e=>e.cod==variante));isfnreload=!!ff}},grafica:async _op=>{let p2,cadv,iscad,des,fatti,{id:id,pars:pars,parametri:parametri,macro:macro,options:options,vari:vari}=_op,isheader=!!(macro&¯o.head&¯o.head.length),sv={l:amb.vari.var("l"),a:amb.vari.var("a"),p:amb.vari.var("p")};const varcad=["l","a","p","#d",...PARSGLOBAL];for(let x of varcad){let tm=amb.vari.dictionary[x];tm&&(sv[x]=tm)}async function _parsepars(x,head){let k,v,r9=/^#(d|des|descrizione)\s*=\s*(.*)\s*$/im.exec(x);if(r9)k="#d",v=await amb.vari.valuta(r9[2]);else{let result=await vari.parametrokeyval(x);k=result.k,v=result.v}k&&!fatti[k]&&(fatti[k]=!0,varcad.includes(k)?"#d"==k?des=v:("string"==typeof v&&(v=muCalc(v)),["l","a","p"].includes(k)&&amb.vari.add(k,String(v)),cadv[k]=v,iscad=!0):"string"==typeof v?p2.push(`${k}=${v}`):amb.vari.add(k,v))}if(p2=[],cadv={},iscad=!1,des="",fatti={},progetto&&progetto.keys&&progetto.keys[id]){let px=progetto.keys[id].pars;if(px)for(let t in px){let t1=amb.vari.dictionary[t];t1&&(sv[t]=t1),await _parsepars(`${t}=${px[t]}`)}}if(pars&&pars.length)for(const par of pars)await _parsepars(par);if(parametri&¶metri.length)for(const param of parametri)await _parsepars(param);if(macro&¯o.head&¯o.head.length){let tm=macro.head.filter((e=>!["g"].includes(e.t)));for(const h of tm)await _parsepars(h.cod)}let out={iscad:iscad,isheader:isheader,name:macro.name,des:des,leveleval:options.leveleval};isheader&&id&&(out.id=id),iscad&&(cadv.l?amb.vari.add("l",String(cadv.l)):cadv.l=muCalc(amb.vari.var("l")),cadv.a?amb.vari.add("a",String(cadv.a)):cadv.a=muCalc(amb.vari.var("a")),cadv.p?amb.vari.add("p",String(cadv.p)):cadv.p=muCalc(amb.vari.var("p")),out.cadv=cadv),await macro.impostaparametri(parametri,p2,!0);let ruleid=rulespec[id];if(id&&isheader&&ruleid&&ruleid.pars&&(out.pars=ruleid.pars,options.leveleval++,await macro.setparametri(ruleid.pars)),out.rows=await muEval(amb,macro,macro.codice,options),id&&isheader&&(out.spars=macro.getparametri()),iscad)for(let x in sv)amb.vari.dictionary[x]=sv[x];return out},parsefnpunto:async _op=>{let{dati:dati,vari:vari,id:id,output:output}=_op;dati=dati.trim();let q=dati.indexOf(" "),q2=dati.indexOf(",");q2>0&&q>0&&q2<q&&(q=q2);let fn,pp,pars={},p2={};q>1?(fn=dati.slice(1,q),pp=getcolonne(dati.slice(q+1))):(fn=dati.slice(1),pp=[]),fnlist.has(fn)||fnlist.add(fn);for(let p of pp){let{k:k,v:v}=await vari.parametrokeyval(p);k&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(k)&&(pars[k]=v||"")}for(let l of["l","a","p"])pars[l]||(pars[l]=vari.var(l));let tm=Object.keys(pars);for(let l of PARSGLOBAL)tm.includes(l)&&(p2[l]=muCalc(pars[l]),delete pars[l]);output.push({t:"fn",fn:fn,id:id,pars:pars,p2:p2})}});for(let x of["l","a","p"])if(startmacro.dims&&startmacro.dims[x].val!=parseFloat(amb.vari.var(x))){isdimreload=!0;break}return(isfnreload||isdimreload&&"function"==typeof fnreload)&&await fnreload(isdimreload,isfnreload),{oo:oo,vari:amb.vari.dump(!0),fnlist:[...fnlist]}}function ismacro(row){return"object"==typeof row&&row?.name&&row.rows}function isfn(row){return"object"==typeof row&&"fn"==row?.t}function getnodebyid(id,nodocorrente){let res;return nodocorrente&&nodocorrente.rows&&function _getnode(rows){for(let x of rows){if(ismacro(x)){if(x.id==id)return void(res=x);x.rows&&_getnode(x.rows)}if(res)return}}(nodocorrente.rows),res}function getsubrules(nodocorrente){let res=[];return res.push({id:"",level:0,name:"home"}),function _xfiltrati(rr,level){if(rr.rows&&rr.rows.length)for(let x of rr.rows)ismacro(x)&&(x.id&&x.isheader?(res.push({id:x.id,name:x.name,des:x.des||"",spec:x.pars?1:0,level:level}),_xfiltrati(x,level+1)):_xfiltrati(x,level))}(nodocorrente,1),res}function getprojectkeys(project){return project.keys={},function _getkeys(node){if(node.rows&&node.rows.length)for(let x of node.rows)ismacro(x)&&(x.id&&x.isheader&&x.pars&&(project.keys[x.id]={name:x.name,des:x.des||"",pars:x.pars}),_getkeys(x))}(project),project}function getdumpmacro(nodo){let cl=[];return function _dumpnodo(node){if(node.rows&&node.rows.length)for(let x of node.rows)if(ismacro(x)){x.name;let c=[];if(x.iscad&&x.cadv)for(let k in x.cadv){let t=x.cadv[k];"number"==typeof t&&t&&c.push(`${k}=${t}`)}if(x.pars)for(let k in x.pars){let t=x.pars[k];c.push(`${k}=${t}`)}c.length&&cl.push(`--\x3e ${x.name} ${c.join(",")}`),_dumpnodo(x),c.length&&cl.push("<--")}else isfn(x)?cl.push(`FN: ${x.fn} ${JSON.stringify(x.pars)}`):"string"==typeof x&&x.length&&cl.push(x)}(nodo),cl.join("\n")}const mgreen$1=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:THREE.DoubleSide});function getorientate(ori,x,y,z){switch(x=x||0,y=y||0,z=z||0,ori.trim().toLowerCase()){case"alp":return{x:y,y:x,z:z};case"apl":return{x:y,y:z,z:x};case"pla":return{x:z,y:x,z:y};case"pal":return{x:z,y:y,z:x};case"lpa":return{x:x,y:z,z:y};default:return{x:x,y:y,z:z}}}function parselavs(ori,id,x=0,y=0,z=0,lavorazioni="",facce="",def=""){let lavcods=function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(rigaTrim.includes("//")&&(rigaTrim=rigaTrim.split("//")[0].trim()),0!==rigaTrim.length)if(rigaContinua.length>0&&(rigaTrim=rigaContinua+" "+rigaTrim,rigaContinua=""),rigaTrim.endsWith("\\")){rigaTrim=rigaTrim.slice(0,-1);const indiceCommento=rigaTrim.lastIndexOf("//");-1!==indiceCommento&&(rigaTrim=rigaTrim.slice(0,indiceCommento).trim()),rigaContinua=rigaTrim}else tm.push(rigaTrim)}return tm}(lavorazioni),rets=[];for(let lavcod of lavcods){var rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(lavcod);if(rr&&rr[1]){let lav={name:rr[1].trim().toLowerCase(),...getorientate(ori,x,y,z),id:id,facce:facce};if(rr[2]){let aa=getcolonne(rr[2]);for(let a of aa){let i=a.indexOf("=");i>0&&(lav[a.slice(0,i).trim()]=a.slice(i+1).trim())}}rets.push(lav)}}return!rets.length&&def&&rets.push({name:def,...getorientate(ori,x,y,z),id:id,facce:facce}),rets}function getemitter(data){let{d:d,name:name,x:x,y:y,z:z,lavs:lavs="",ids:ids="",faces:faces=null,size:size=5}=data;ids=getcolonne(clean(ids,!0));const emitter=new THREE.Object3D;if(emitter.position.set(x,y,z),emitter.userData={emitter:!0,lavs:lavs,ids:ids,faces:faces,size:size,name:name},d){const geometry=new THREE.SphereGeometry(size||5,8,8),material=new THREE.MeshBasicMaterial({color:16711680}),mesh=new THREE.Mesh(geometry,material);emitter.add(mesh)}return emitter}function getreceiver(gcad,data){gcad.gmats.__istask=1;let{d:d,ori:ori="LAP",x:x=0,y:y=0,z:z=0,tipo:tipo="",start:start="",end:end=""}=data;tipo=clean(tipo,!0);const receiver=new THREE.Object3D;if(receiver.position.set(x/2,y/2,z/2),receiver.userData={receiver:!0,ori:(ori||"").trim().toLowerCase(),x:x,y:y,z:z,tipo:tipo,start:start,end:end},d){const geometry=new THREE.BoxGeometry(x,y,z),mesh=new THREE.Mesh(geometry,mgreen$1);mesh.position.set(0,0,0),receiver.add(mesh)}return receiver}function calcolatasks(scena){const emitterWorldPosition=new WeakMap,receiverWorldMatrixInverse=new WeakMap;function boxBoxIntersects(pos,l,x,y,z){return pos.x+l>0&&pos.x-l<x&&pos.y+l>0&&pos.y-l<y&&pos.z+l>0&&pos.z-l<z}function getFacceToccate(pos,sogliafaccia,x,y,z,filtra){const facce=[];function addfaccia(f){filtra&&!filtra.includes(f)||facce.push(f)}return Math.abs(pos.x-0)<sogliafaccia&&addfaccia("s"),Math.abs(pos.x-x)<sogliafaccia&&addfaccia("d"),Math.abs(pos.y-0)<sogliafaccia&&addfaccia("b"),Math.abs(pos.y-y)<sogliafaccia&&addfaccia("a"),Math.abs(pos.z-0)<sogliafaccia&&addfaccia("z"),Math.abs(pos.z-z)<sogliafaccia&&addfaccia("f"),facce.join("")}function getEmitterWorldPosition(emitter){if(!emitterWorldPosition.has(emitter)){const pos=new THREE.Vector3;emitter.getWorldPosition(pos),emitterWorldPosition.set(emitter,pos)}return emitterWorldPosition.get(emitter)}function getReceiverWorldMatrixInverse(receiver){if(!receiverWorldMatrixInverse.has(receiver)){const inv=receiver.matrixWorld.clone().invert();receiverWorldMatrixInverse.set(receiver,inv)}return receiverWorldMatrixInverse.get(receiver)}scena.updateMatrixWorld(!0);const receivers=[],emitters=[];!function scan(obj){obj.userData?.receiver&&receivers.push(obj),obj.userData?.emitter&&emitters.push(obj),obj.children&&obj.children.forEach(scan)}(scena);let tasks=[];for(const receiver of receivers){const{mat:mat,ori:ori,x:x,y:y,z:z,start:start,end:end,tipo:tipo,size:size}=receiver.userData;let singletask={id:mat,...getorientate(ori,x,y,z),tipo:tipo,ori:ori,lavs:[]};start&&singletask.lavs.push(...parselavs(ori,"_start",0,0,0,start,"",""));const matrixInverse=getReceiverWorldMatrixInverse(receiver);for(const emitter of emitters){if("string"==typeof tipo&&""!==tipo){const idx=emitter.userData.ids;if(Array.isArray(idx)&&idx.length>0&&!idx.includes("*")&&!idx.includes(tipo))continue}const posLocalAdj=getEmitterWorldPosition(emitter).clone().applyMatrix4(matrixInverse).clone().add(new THREE.Vector3(x/2,y/2,z/2));if(!boxBoxIntersects(posLocalAdj,emitter.userData.size??0,x,y,z))continue;const facceToccate=getFacceToccate(posLocalAdj,emitter.userData.soglia??2,x,y,z,emitter.userData.faces);facceToccate&&facceToccate.length&&singletask.lavs.push(...parselavs(ori,emitter.userData.name,posLocalAdj.x,posLocalAdj.y,posLocalAdj.z,emitter.userData.lavs,facceToccate,"nd"))}end&&singletask.lavs.push(...parselavs(ori,"_end",0,0,0,end,"","")),singletask.lavs.length&&tasks.push(singletask)}return tasks}const SIDE=THREE.DoubleSide;let materialline1=new THREE.LineBasicMaterial({color:3158064}),materialline2=new THREE.LineBasicMaterial({color:5263440});const mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgray1=new THREE.MeshStandardMaterial({color:8421504,roughness:.5,metalness:.4,side:SIDE}),mgray2=new THREE.MeshStandardMaterial({color:11579568,roughness:.5,metalness:.4,side:SIDE}),mred=new THREE.MeshStandardMaterial({color:16711680,roughness:.5,metalness:.4,side:SIDE}),mblue=new THREE.MeshStandardMaterial({color:1982639,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE}),mblack=new THREE.MeshStandardMaterial({color:0,roughness:.5,metalness:.4,side:SIDE}),scaleunit=.001;function groupfromgeometry(geometry,material,x,y,z,name,layer){let child=new THREE.Group;child.position.set(x,y,z),child.name=name;const mesh=new THREE.Mesh(geometry,material);mesh.name=name,mesh.castShadow=!0,mesh.receiveShadow=!0,mesh.layers.set(layer);const edges=new THREE.EdgesGeometry(geometry),lineSegments=new THREE.LineSegments(edges,materialline1);return lineSegments.layers.set(30),child.add(mesh),child.add(lineSegments),child}function posiziona(grp,pos={}){let tm=new THREE.Group;if(grp){let g2=grp.clone(),tm2=g2,{sl:sl=0,sa:sa=0,sp:sp=0,ax:ax=0,ay:ay=0,az:az=0,ul:ul=0,ua:ua=0,up:up=0,scale:scale=1,scx:scx=scale,scy:scy=scale,scz:scz=scale,emitters:emitters,emittersname:emittersname}=pos;if(tm.position.set(sl,sa,sp),tm.rotation.set(ax*PIF,ay*PIF,az*PIF),(ul||ua||up)&&(tm2=new THREE.Group,tm2.add(g2),tm2.position.set(ul,ua,up)),tm.scale.set(scx,scy,scz),tm.add(tm2),emitters&&emitters.length)for(let e of emitters)e.name=e.name||emittersname,tm.add(getemitter(e))}return tm}function edgesfromgeometry(g1,layer=30){return getlinesgeom(new THREE.EdgesGeometry(g1,40),layer)}function getlinesgeom(edges,layer=30){const lineSegments=new THREE.LineSegments(edges,materialline1);return lineSegments.layers.set(layer),lineSegments}function getmesh(geom,material,layer=1,clone=!1){let m=new THREE.Mesh(geom,clone?material.clone():material);return m.castShadow=!0,m.receiveShadow=!0,m.layers.set(layer),m}function get3dshape(punti,material,layer){if(!punti||punti.length<3)return new THREE.BufferGeometry;const vertices=[];for(let i=0;i<punti.length;i++){const p1=punti[i],p2=punti[(i+1)%punti.length];vertices.push(p1.x,0,p1.y),vertices.push(p2.x,0,p2.y)}const geometry=new THREE.BufferGeometry;geometry.setAttribute("position",new THREE.Float32BufferAttribute(vertices,3));let m=new THREE.LineSegments(geometry,material);return m.layers.set(layer),m}function creategroup(name){let g=new THREE.Group;return g.name=name||"$$",g}function svuotanodo(n){!function _dispose(node){if(node.children.length){[...node.children].forEach((child=>{_dispose(child),node.remove(child)}))}node.geometry&&node.geometry.dispose(),node.material&&(Array.isArray(node.material)?node.material.forEach((m=>m.dispose())):node.material.dispose())}(n)}function deletegroup(grpbase,name){if(!grpbase?.children)return;let gr=grpbase.children.find((e=>e.name==name));if(gr){for(;gr.children.length>0;){const child=gr.children[0];gr.remove(child)}gr.parent&&gr.parent.remove(gr),gr=null}}function randombasemat(){const material=new THREE.LineBasicMaterial,color=new THREE.Color;return color.setHSL(Math.random(),.7,.4),material.color=color,material}
|
|
526
|
+
function calcoladivisioni(ff,notused,shape2,oggetti){return makedivisions(ff,shape2,oggetti)},check:check,checkoggetto:checkoggetto,creaprofiloesterno:creaprofiloesterno,create:function create(x,y,bordo,options){options||(options={});let{minvano:minvano,priority:priority,taglio:taglio,tipo:tipo,h1:h1,h2:h2,d1:d1,d2:d2,l1:l1,l2:l2,x1:x1,x2:x2,y1:y1,y2:y2,gvert:gvert,goriz:goriz,forma:forma,area:area}=options,ff=check({x:x,y:y,area:area,bordo:bordo,gvert:gvert,goriz:goriz,priority:priority,minvano:minvano,taglio:taglio,tipo:tipo,h1:h1,h2:h2,l1:l1,l2:l2,d1:d1,x1:x1,y1:y1,d2:d2,x2:x2,y2:y2});return ff.forma=forma,ff},elaborapercorso:elaborapercorso,getbordi:getbordi,makedivisions:makedivisions,makeshape:function makeshape(ff,oggetti){return creaprofiloesterno(ff,oggetti)},priorita:{v:"verticale",h:"orizzontale"},tagli:tagli,tipi:tipi,tipoalign:tipoalign,tipocut:tipocut});async function valutagrafica(amb,startmacro,rulespec,progetto,fnreload){let{getcolonne:getcolonne,muCalc:muCalc,muEval:muEval,tipifree:tipifree}=amb.muvalutatore;rulespec||(rulespec={});for(let x of["l","a","p"]){!amb.vari.var(x)&&startmacro.dims&&amb.vari.add(x,String(startmacro.dims[x].val||100))}let fnlist=new Set;const PARSGLOBAL=["sl","sa","sp","ul","ua","up","ax","ay","az","scx","scy","scz","scale"];let isdimreload,isfnreload=!1,oo=await muEval(amb,startmacro,startmacro.codice,{leveleval:0,checkheader:op=>{let{variante:variante}=op;if(Array.isArray(startmacro.head)){let ff=startmacro.head.find((e=>e.cod==variante));isfnreload=!!ff}},grafica:async _op=>{let p2,cadv,iscad,des,fatti,{id:id,pars:pars,parametri:parametri,macro:macro,options:options,vari:vari}=_op,isheader=!!(macro&¯o.head&¯o.head.length),sv={l:amb.vari.var("l"),a:amb.vari.var("a"),p:amb.vari.var("p")};const varcad=["l","a","p","#d",...PARSGLOBAL];for(let x of varcad){let tm=amb.vari.dictionary[x];tm&&(sv[x]=tm)}async function _parsepars(x,head){let k,v,r9=/^#(d|des|descrizione)\s*=\s*(.*)\s*$/im.exec(x);if(r9)k="#d",v=await amb.vari.valuta(r9[2]);else{let result=await vari.parametrokeyval(x);k=result.k,v=result.v}k&&!fatti[k]&&(fatti[k]=!0,varcad.includes(k)?"#d"==k?des=v:("string"==typeof v&&(v=muCalc(v)),["l","a","p"].includes(k)&&amb.vari.add(k,String(v)),cadv[k]=v,iscad=!0):"string"==typeof v?p2.push(`${k}=${v}`):amb.vari.add(k,v))}if(p2=[],cadv={},iscad=!1,des="",fatti={},progetto&&progetto.keys&&progetto.keys[id]){let px=progetto.keys[id].pars;if(px)for(let t in px){let t1=amb.vari.dictionary[t];t1&&(sv[t]=t1),await _parsepars(`${t}=${px[t]}`)}}if(pars&&pars.length)for(const par of pars)await _parsepars(par);if(parametri&¶metri.length)for(const param of parametri)await _parsepars(param);if(macro&¯o.head&¯o.head.length){let tm=macro.head.filter((e=>!["g"].includes(e.t)));for(const h of tm)await _parsepars(h.cod)}let out={iscad:iscad,isheader:isheader,name:macro.name,des:des,leveleval:options.leveleval};isheader&&id&&(out.id=id),iscad&&(cadv.l?amb.vari.add("l",String(cadv.l)):cadv.l=muCalc(amb.vari.var("l")),cadv.a?amb.vari.add("a",String(cadv.a)):cadv.a=muCalc(amb.vari.var("a")),cadv.p?amb.vari.add("p",String(cadv.p)):cadv.p=muCalc(amb.vari.var("p")),out.cadv=cadv),await macro.impostaparametri(parametri,p2,!0);let ruleid=rulespec[id];if(id&&isheader&&ruleid&&ruleid.pars&&(out.pars=ruleid.pars,options.leveleval++,await macro.setparametri(ruleid.pars)),out.rows=await muEval(amb,macro,macro.codice,options),id&&isheader&&(out.spars=macro.getparametri()),iscad)for(let x in sv)amb.vari.dictionary[x]=sv[x];return out},parsefnpunto:async _op=>{let{dati:dati,vari:vari,id:id,output:output}=_op;dati=dati.trim();let q=dati.indexOf(" "),q2=dati.indexOf(",");q2>0&&q>0&&q2<q&&(q=q2);let fn,pp,pars={},p2={};q>1?(fn=dati.slice(1,q),pp=getcolonne(dati.slice(q+1))):(fn=dati.slice(1),pp=[]),fnlist.has(fn)||fnlist.add(fn);for(let p of pp){let{k:k,v:v}=await vari.parametrokeyval(p);k&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(k)&&(pars[k]=v||"")}for(let l of["l","a","p"])pars[l]||(pars[l]=vari.var(l));let tm=Object.keys(pars);for(let l of PARSGLOBAL)tm.includes(l)&&(p2[l]=muCalc(pars[l]),delete pars[l]);output.push({t:"fn",fn:fn,id:id,pars:pars,p2:p2})}});for(let x of["l","a","p"])if(startmacro.dims&&startmacro.dims[x].val!=parseFloat(amb.vari.var(x))){isdimreload=!0;break}return(isfnreload||isdimreload&&"function"==typeof fnreload)&&await fnreload(isdimreload,isfnreload),{oo:oo,vari:amb.vari.dump(!0),fnlist:[...fnlist]}}function ismacro(row){return"object"==typeof row&&row?.name&&row.rows}function isfn(row){return"object"==typeof row&&"fn"==row?.t}function getnodebyid(id,nodocorrente){let res;return nodocorrente&&nodocorrente.rows&&function _getnode(rows){for(let x of rows){if(ismacro(x)){if(x.id==id)return void(res=x);x.rows&&_getnode(x.rows)}if(res)return}}(nodocorrente.rows),res}function getsubrules(nodocorrente){let res=[];return res.push({id:"",level:0,name:"home"}),function _xfiltrati(rr,level){if(rr.rows&&rr.rows.length)for(let x of rr.rows)ismacro(x)&&(x.id&&x.isheader?(res.push({id:x.id,name:x.name,des:x.des||"",spec:x.pars?1:0,level:level}),_xfiltrati(x,level+1)):_xfiltrati(x,level))}(nodocorrente,1),res}function getprojectkeys(project){return project.keys={},function _getkeys(node){if(node.rows&&node.rows.length)for(let x of node.rows)ismacro(x)&&(x.id&&x.isheader&&x.pars&&(project.keys[x.id]={name:x.name,des:x.des||"",pars:x.pars}),_getkeys(x))}(project),project}function getdumpmacro(nodo){let cl=[];return function _dumpnodo(node){if(node.rows&&node.rows.length)for(let x of node.rows)if(ismacro(x)){x.name;let c=[];if(x.iscad&&x.cadv)for(let k in x.cadv){let t=x.cadv[k];"number"==typeof t&&t&&c.push(`${k}=${t}`)}if(x.pars)for(let k in x.pars){let t=x.pars[k];c.push(`${k}=${t}`)}c.length&&cl.push(`--\x3e ${x.name} ${c.join(",")}`),_dumpnodo(x),c.length&&cl.push("<--")}else isfn(x)?cl.push(`FN: ${x.fn} ${JSON.stringify(x.pars)}`):"string"==typeof x&&x.length&&cl.push(x)}(nodo),cl.join("\n")}const mgreen$1=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:THREE.DoubleSide});function getorientate(ori,x,y,z){switch(x=x||0,y=y||0,z=z||0,ori.trim().toLowerCase()){case"alp":return{x:y,y:x,z:z};case"apl":return{x:y,y:z,z:x};case"pla":return{x:z,y:x,z:y};case"pal":return{x:z,y:y,z:x};case"lpa":return{x:x,y:z,z:y};default:return{x:x,y:y,z:z}}}function parselavs(ori,id,x=0,y=0,z=0,lavorazioni="",facce="",def=""){let lavcods=function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(rigaTrim.includes("//")&&(rigaTrim=rigaTrim.split("//")[0].trim()),0!==rigaTrim.length)if(rigaContinua.length>0&&(rigaTrim=rigaContinua+" "+rigaTrim,rigaContinua=""),rigaTrim.endsWith("\\")){rigaTrim=rigaTrim.slice(0,-1);const indiceCommento=rigaTrim.lastIndexOf("//");-1!==indiceCommento&&(rigaTrim=rigaTrim.slice(0,indiceCommento).trim()),rigaContinua=rigaTrim}else tm.push(rigaTrim)}return tm}(lavorazioni),rets=[];for(let lavcod of lavcods){var rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(lavcod);if(rr&&rr[1]){let lav={name:rr[1].trim().toLowerCase(),...getorientate(ori,x,y,z),id:id,facce:facce};if(rr[2]){let aa=getcolonne(rr[2]);for(let a of aa){let i=a.indexOf("=");i>0&&(lav[a.slice(0,i).trim()]=a.slice(i+1).trim())}}rets.push(lav)}}return!rets.length&&def&&rets.push({name:def,...getorientate(ori,x,y,z),id:id,facce:facce}),rets}function getemitter(data){let{d:d,name:name,x:x,y:y,z:z,lavs:lavs="",ids:ids="",faces:faces=null,size:size=5}=data;ids=getcolonne(clean(ids,!0));const emitter=new THREE.Object3D;if(emitter.position.set(x,y,z),emitter.userData={emitter:!0,lavs:lavs,ids:ids,faces:faces,size:size,name:name},d){const geometry=new THREE.SphereGeometry(size||5,8,8),material=new THREE.MeshBasicMaterial({color:16711680}),mesh=new THREE.Mesh(geometry,material);emitter.add(mesh)}return emitter}function getreceiver(gcad,data){gcad.gmats.__istask=1;let{d:d,ori:ori="LAP",x:x=0,y:y=0,z:z=0,tipo:tipo="",start:start="",end:end=""}=data;tipo=clean(tipo,!0);const receiver=new THREE.Object3D;if(receiver.position.set(x/2,y/2,z/2),receiver.userData={receiver:!0,ori:(ori||"").trim().toLowerCase(),x:x,y:y,z:z,tipo:tipo,start:start,end:end},d){const geometry=new THREE.BoxGeometry(x,y,z),mesh=new THREE.Mesh(geometry,mgreen$1);mesh.position.set(0,0,0),receiver.add(mesh)}return receiver}function calcolatasks(scena){const emitterWorldPosition=new WeakMap,receiverWorldMatrixInverse=new WeakMap;function boxBoxIntersects(pos,l,x,y,z){return pos.x+l>0&&pos.x-l<x&&pos.y+l>0&&pos.y-l<y&&pos.z+l>0&&pos.z-l<z}function getFacceToccate(pos,sogliafaccia,x,y,z,filtra){const facce=[];function addfaccia(f){filtra&&!filtra.includes(f)||facce.push(f)}return Math.abs(pos.x-0)<sogliafaccia&&addfaccia("s"),Math.abs(pos.x-x)<sogliafaccia&&addfaccia("d"),Math.abs(pos.y-0)<sogliafaccia&&addfaccia("b"),Math.abs(pos.y-y)<sogliafaccia&&addfaccia("a"),Math.abs(pos.z-0)<sogliafaccia&&addfaccia("z"),Math.abs(pos.z-z)<sogliafaccia&&addfaccia("f"),facce.join("")}function getEmitterWorldPosition(emitter){if(!emitterWorldPosition.has(emitter)){const pos=new THREE.Vector3;emitter.getWorldPosition(pos),emitterWorldPosition.set(emitter,pos)}return emitterWorldPosition.get(emitter)}function getReceiverWorldMatrixInverse(receiver){if(!receiverWorldMatrixInverse.has(receiver)){const inv=receiver.matrixWorld.clone().invert();receiverWorldMatrixInverse.set(receiver,inv)}return receiverWorldMatrixInverse.get(receiver)}scena.updateMatrixWorld(!0);const receivers=[],emitters=[];!function scan(obj){obj.userData?.receiver&&receivers.push(obj),obj.userData?.emitter&&emitters.push(obj),obj.children&&obj.children.forEach(scan)}(scena);let tasks=[];for(const receiver of receivers){const{mat:mat,ori:ori,x:x,y:y,z:z,start:start,end:end,tipo:tipo,size:size}=receiver.userData;let singletask={id:mat,...getorientate(ori,x,y,z),tipo:tipo,ori:ori,lavs:[]};start&&singletask.lavs.push(...parselavs(ori,"_start",0,0,0,start,"",""));const matrixInverse=getReceiverWorldMatrixInverse(receiver);for(const emitter of emitters){if("string"==typeof tipo&&""!==tipo){const idx=emitter.userData.ids;if(Array.isArray(idx)&&idx.length>0&&!idx.includes("*")&&!idx.includes(tipo))continue}const posLocalAdj=getEmitterWorldPosition(emitter).clone().applyMatrix4(matrixInverse).clone().add(new THREE.Vector3(x/2,y/2,z/2));if(!boxBoxIntersects(posLocalAdj,emitter.userData.size??0,x,y,z))continue;const facceToccate=getFacceToccate(posLocalAdj,emitter.userData.soglia??2,x,y,z,emitter.userData.faces);facceToccate&&facceToccate.length&&singletask.lavs.push(...parselavs(ori,emitter.userData.name,posLocalAdj.x,posLocalAdj.y,posLocalAdj.z,emitter.userData.lavs,facceToccate,"nd"))}end&&singletask.lavs.push(...parselavs(ori,"_end",0,0,0,end,"","")),singletask.lavs.length&&tasks.push(singletask)}return tasks}const SIDE=THREE.DoubleSide;let materialline1=new THREE.LineBasicMaterial({color:3158064}),materialline2=new THREE.LineBasicMaterial({color:5263440});const mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgray1=new THREE.MeshStandardMaterial({color:8421504,roughness:.5,metalness:.4,side:SIDE}),mgray2=new THREE.MeshStandardMaterial({color:11579568,roughness:.5,metalness:.4,side:SIDE}),mred=new THREE.MeshStandardMaterial({color:16711680,roughness:.5,metalness:.4,side:SIDE}),mblue=new THREE.MeshStandardMaterial({color:1982639,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE}),mblack=new THREE.MeshStandardMaterial({color:0,roughness:.5,metalness:.4,side:SIDE}),scaleunit=.001,suffissoMap={"":{prop:"map",extra:null},n:{prop:"normalMap",extra:null},h:{prop:"displacementMap",extra:"displacementScale"},a:{prop:"aoMap",extra:"aoMapIntensity"},r:{prop:"roughnessMap",extra:null},b:{prop:"bumpMap",extra:"bumpScale"},m:{prop:"metalnessMap",extra:null},e:{prop:"emissiveMap",extra:["emissive","emissiveIntensity"]}};function groupfromgeometry(geometry,material,x,y,z,name,layer){let child=new THREE.Group;child.position.set(x,y,z),child.name=name;const mesh=new THREE.Mesh(geometry,material);mesh.name=name,mesh.castShadow=!0,mesh.receiveShadow=!0,mesh.layers.set(layer);const edges=new THREE.EdgesGeometry(geometry),lineSegments=new THREE.LineSegments(edges,materialline1);return lineSegments.layers.set(30),child.add(mesh),child.add(lineSegments),child}function posiziona(grp,pos={}){let tm=new THREE.Group;if(grp){let g2=grp.clone(),tm2=g2,{sl:sl=0,sa:sa=0,sp:sp=0,ax:ax=0,ay:ay=0,az:az=0,ul:ul=0,ua:ua=0,up:up=0,scale:scale=1,scx:scx=scale,scy:scy=scale,scz:scz=scale,emitters:emitters,emittersname:emittersname}=pos;if(tm.position.set(sl,sa,sp),tm.rotation.set(ax*PIF,ay*PIF,az*PIF),(ul||ua||up)&&(tm2=new THREE.Group,tm2.add(g2),tm2.position.set(ul,ua,up)),tm.scale.set(scx,scy,scz),tm.add(tm2),emitters&&emitters.length)for(let e of emitters)e.name=e.name||emittersname,tm.add(getemitter(e))}return tm}function edgesfromgeometry(g1,layer=30){return getlinesgeom(new THREE.EdgesGeometry(g1,40),layer)}function getlinesgeom(edges,layer=30){const lineSegments=new THREE.LineSegments(edges,materialline1);return lineSegments.layers.set(layer),lineSegments}function getmesh(geom,material,layer=1,clone=!1){let m=new THREE.Mesh(geom,clone?material.clone():material);return m.castShadow=!0,m.receiveShadow=!0,m.layers.set(layer),m}function get3dshape(punti,material,layer){if(!punti||punti.length<3)return new THREE.BufferGeometry;const vertices=[];for(let i=0;i<punti.length;i++){const p1=punti[i],p2=punti[(i+1)%punti.length];vertices.push(p1.x,0,p1.y),vertices.push(p2.x,0,p2.y)}const geometry=new THREE.BufferGeometry;geometry.setAttribute("position",new THREE.Float32BufferAttribute(vertices,3));let m=new THREE.LineSegments(geometry,material);return m.layers.set(layer),m}function creategroup(name){let g=new THREE.Group;return g.name=name||"$$",g}function svuotanodo(n){!function _dispose(node){if(node.children.length){[...node.children].forEach((child=>{_dispose(child),node.remove(child)}))}node.geometry&&node.geometry.dispose(),node.material&&(Array.isArray(node.material)?node.material.forEach((m=>m.dispose())):node.material.dispose())}(n)}function deletegroup(grpbase,name){if(!grpbase?.children)return;let gr=grpbase.children.find((e=>e.name==name));if(gr){for(;gr.children.length>0;){const child=gr.children[0];gr.remove(child)}gr.parent&&gr.parent.remove(gr),gr=null}}function randombasemat(){const material=new THREE.LineBasicMaterial,color=new THREE.Color;return color.setHSL(Math.random(),.7,.4),material.color=color,material}
|
|
527
527
|
/**
|
|
528
528
|
* Crea una linea 3D
|
|
529
529
|
* @param {Object} l - Oggetto contenente punti p1 e p2
|
|
@@ -538,7 +538,13 @@ 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){const pointgeom=new THREE.SphereGeometry(size,8,8);let tm=new THREE.Mesh(pointgeom,mat||randombasemat());return tm.position.set(p.x,0,p.y),tm}
|
|
541
|
+
*/function getpoint(p,id,mat=null,size=5){const pointgeom=new THREE.SphereGeometry(size,8,8);let tm=new THREE.Mesh(pointgeom,mat||randombasemat());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 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&¶mstr.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):v:isNaN(parseFloat(v))?p[k]=v:p[k]=parseFloat(v))}));const mappaParam={s:["sx","sy"],sx:["sx"],sy:["sy"],rot:["rot"],r:["roughness"],m:["metalness"],h:["displacementScale"],d:["bumpScale"],b:["bumpScale"],e:["emissive"],ei:["emissiveIntensity"],ao:["aoMapIntensity"],env:["envMapIntensity"],o:["opacity"],t:["transparent"],at:["alphaTest"]};let optot={...op};for(let k in p)if(mappaParam[k])for(let t of mappaParam[k])optot[t]=p[k];let sx=(optot.sx??optot.s??1)*(p.sx??p.s??1),sy=(optot.sy??optot.s??1)*(p.sy??p.s??1),rot=((optot.rot??0)+(p.rot??0))*PIF;try{let tm={roughness:optot.roughness??.7,metalness:optot.metalness??.3,side:THREE.DoubleSide,envMapIntensity:optot.env??1};if(file.includes("(")||isColore){let{base:base,files:files}=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],mapalias=m[3]||base,suffstr=m[4]||m[5]||"";isColore||files.push({suff:"",file:`${base}.webp`});for(let s of suffstr)suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`});return{base:base,files:files}}(isColore,basefile);if(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,extra&&("displacementScale"===extra?tm.displacementScale=optot.displacementScale??.1:"bumpScale"===extra?tm.bumpScale=optot.bumpScale??.05:"aoMapIntensity"===extra?tm.aoMapIntensity=optot.aoMapIntensity??1:Array.isArray(extra)&&extra.includes("emissive")&&(tm.emissive=optot.emissive??16777215,tm.emissiveIntensity=optot.emissiveIntensity??1))}}isColore&&(tm.color=base)}else if(basefile.includes(".")){let tx=await gcad.tex(basefile,sx,sy,rot);if(!tx)return mwhite;tm.map=tx}return["opacity","alphaTest"].forEach((k=>{void 0!==optot[k]&&(tm[k]=optot[k])})),(void 0!==tm.opacity&&tm.opacity<1||optot.transparent)&&(tm.transparent=!0),new THREE.MeshStandardMaterial(tm)}catch(error){return mwhite}}
|
|
542
|
+
/**
|
|
543
|
+
* Estrae tutte le texture usate nella scena glb e le converte in file WEBP.
|
|
544
|
+
* @param {THREE.Object3D} root - nodo root (es: gltf.scene)
|
|
545
|
+
* @param {string} baseName - prefisso del nome file
|
|
546
|
+
* @returns {Promise<File[]>} array di File webp
|
|
547
|
+
*/(gcad,file,op)),gcad.smats[ky]}async function extractTextures(root,baseName){const counters={},out=[];function getName(suffix){counters[suffix]=(counters[suffix]||0)+1;let base=baseName;return suffix&&(base+=`_${suffix}`),counters[suffix]>1&&(base+=counters[suffix]),`${base}.webp`}return root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const[suffix,{prop:prop}]of Object.entries(suffissoMap)){const tex=mat[prop];if(tex&&tex.image&&!tex._extracted){tex._extracted=!0;let promise,img=tex.image;if(img.toBlob)promise=new Promise((res=>img.toBlob(res,"image/webp")));else if(img instanceof ImageBitmap){const canvas=document.createElement("canvas");canvas.width=img.width,canvas.height=img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}else{if(!(img instanceof HTMLImageElement))continue;{const canvas=document.createElement("canvas");canvas.width=img.naturalWidth||img.width,canvas.height=img.naturalHeight||img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}}out.push(promise.then((blob=>new File([blob],getName(suffix),{type:"image/webp"}))))}}}})),root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const{prop:prop}of Object.values(suffissoMap)){const tex=mat[prop];tex&&tex._extracted&&delete tex._extracted}}})),Promise.all(out)}function getfakeshadow(gcad,shape,alfa){let ky=`fk${shape.key}${alfa}`,{p1:p1,width:width,height:height}=shape.dims();gcad.texture||(gcad.texture={});let tm=gcad.texture[ky];tm||(tm=function createBlurredShadowTextureFromPoints(mshape,size=256,blurPx=32,alpha=.2,p1,width,height){if(!width||!height||!mshape.pt||mshape.pt.length<2)return;const minX=p1.x,minY=p1.y,shapeWidth=width,shapeHeight=height,points=mshape.pt,extra=2*blurPx,canvas=document.createElement("canvas");canvas.width=size+2*extra,canvas.height=size+2*extra;const ctx=canvas.getContext("2d");ctx.save(),ctx.translate(extra,extra),ctx.scale(size/shapeWidth,size/shapeHeight),ctx.translate(-minX,-minY),ctx.filter=`blur(${blurPx}px)`,ctx.beginPath(),ctx.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)ctx.lineTo(points[i].x,points[i].y);ctx.closePath(),ctx.fillStyle=`rgba(0,0,0,${alpha})`,ctx.fill(),ctx.restore();const texture=new THREE.CanvasTexture(canvas);return texture.needsUpdate=!0,texture}(shape,256,32,alfa,p1,width,height),gcad.texture[ky]=tm);const fakeShape=function pointsToShape(points){const fakeShape=new THREE.Shape;fakeShape.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)fakeShape.lineTo(points[i].x,points[i].y);return fakeShape}(shape.pt),shadowGeometry=new THREE.ShapeGeometry(fakeShape);!function applyUVtoShapeGeometry(geometry,minX,minY,width,height){const pos=geometry.attributes.position,uv=[];for(let i=0;i<pos.count;i++){const x=pos.getX(i),y=pos.getY(i);uv.push((x-minX)/width,(y-minY)/height)}geometry.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2))}(shadowGeometry,p1.x,p1.y,width,height);const shadowMaterial=new THREE.MeshBasicMaterial({map:tm,transparent:!0,depthWrite:!1,side:THREE.DoubleSide});let ms=new THREE.Mesh(shadowGeometry,shadowMaterial);return ms.layers.set(9),ms.rotation.x=Math.PI/2,ms}function addmovpivot(gcad,grp,movimento,op={},x=0,y=0,z=0){if(movimento=clean(movimento,!0),!gcad.movs[movimento])return grp;gcad.movs[movimento];const pivotLocal=new THREE.Vector3(x,y,z),isZeroPivot=0===pivotLocal.lengthSq(),pivotGroup=new THREE.Group;pivotGroup.name=`pivot_${movimento}`;const movimentoGroup=new THREE.Group;if(movimentoGroup.name=`mov_${movimento}`,isZeroPivot)pivotGroup.position.copy(grp.position),pivotGroup.quaternion.copy(grp.quaternion),grp.position.set(0,0,0),grp.rotation.set(0,0,0);else{const pivotWorld=pivotLocal.clone().applyMatrix4(grp.matrixWorld);pivotGroup.position.copy(pivotWorld);const offset=pivotLocal.clone().negate();grp.position.add(offset),pivotGroup.quaternion.copy(grp.getWorldQuaternion(new THREE.Quaternion)),grp.rotation.set(0,0,0)}return movimentoGroup.add(grp),pivotGroup.add(movimentoGroup),op||(op={}),op.inmov=!1,op.key=movimento,op.dt=0,op.dtstart=!1,movimentoGroup.userData.mov={...op},pivotGroup}
|
|
542
548
|
/**
|
|
543
549
|
* Crea un gestore di movimento per animare oggetti 3D.
|
|
544
550
|
* @param {string} key - Chiave identificativa del movimento
|
|
@@ -610,7 +616,7 @@ function getcilindro(gcad,ori,h,r1,r2,mats=mwhite,options){options||(options={})
|
|
|
610
616
|
* @param {THREE.Material} mat - Materiale da applicare
|
|
611
617
|
* @param {Object} options - Opzioni di configurazione
|
|
612
618
|
* @returns {Promise<THREE.Group>} Gruppo contenente il box
|
|
613
|
-
*/function getface(gcad,x,y,mat,scaled=!1){let ky=hash(`f:${x}|${y}|${scaled?1:0}`);if(!gcad.geo[ky]){const geometry=new THREE.PlaneGeometry(x,y),uvs=geometry.attributes.uv;if(!scaled)for(let i=0;i<uvs.count;i++)uvs.setXY(i,uvs.getX(i)*x,uvs.getY(i)*y);gcad.geo[ky]=geometry}const plane=new THREE.Mesh(gcad.geo[ky],mat);return plane.position.set(x/2,y/2,0),mat?.transparent&&plane.layers.set(2),plane}function getcyl(gcad,height,radius,mat,options){options||(options={});let{center:center=!1,nolines:nolines=!1,segments:segments=16,radiusBottom:radiusBottom=-1}=options;radiusBottom<0&&(radiusBottom=radius);let grp=new THREE.Group;const cylinder=new THREE.CylinderGeometry(radius,radiusBottom,height,segments);if(grp.position.set(0,center?0:height/2,0),!nolines){let segments=edgesfromgeometry(cylinder);grp.add(segments)}return grp.add(getmesh(cylinder,mat||mwhite)),grp}function getbox(gcad,x,y,z,mat,options){options||(options={});let{center:center,nolines:nolines}=options,grp=new THREE.Group;const box=function boxgeometry(gcad,x,y,z){let ky=hash(`b:${x}|${y}|${z}`);if(!gcad.geo[ky]){const bx=new THREE.BoxGeometry(x,y,z);gcad.geo[ky]=bx}return gcad.geo[ky]}(gcad,x,y,z);if(center||grp.position.set(x/2,y/2,z/2),!nolines){let segments=edgesfromgeometry(box);grp.add(segments)}return grp.add(getmesh(box,mat||mwhite)),grp}
|
|
619
|
+
*/function getface(gcad,x,y,mat,scaled=!1){let ky=hash(`f:${x}|${y}|${scaled?1:0}`);if(!gcad.geo[ky]){const geometry=new THREE.PlaneGeometry(x,y),uvs=geometry.attributes.uv;if(!scaled)for(let i=0;i<uvs.count;i++)uvs.setXY(i,uvs.getX(i)*x,uvs.getY(i)*y);gcad.geo[ky]=geometry}const plane=new THREE.Mesh(gcad.geo[ky],mat);return plane.position.set(x/2,y/2,0),mat?.transparent&&plane.layers.set(2),plane}function getcyl(gcad,height,radius,mat,options){options||(options={});let{center:center=!1,nolines:nolines=!1,segments:segments=16,radiusBottom:radiusBottom=-1}=options;radiusBottom<0&&(radiusBottom=radius);let grp=new THREE.Group;const cylinder=new THREE.CylinderGeometry(radius,radiusBottom,height,segments);if(grp.position.set(0,center?0:height/2,0),!nolines){let segments=edgesfromgeometry(cylinder);grp.add(segments)}return grp.add(getmesh(cylinder,mat||mwhite)),grp}function getbox(gcad,x,y,z,mat,options){options||(options={});let{center:center=!1,nolines:nolines,centerbase:centerbase=!1,px:px=0,py:py=0,pz:pz=0}=options,grp=new THREE.Group;const box=function boxgeometry(gcad,x,y,z){let ky=hash(`b:${x}|${y}|${z}`);if(!gcad.geo[ky]){const bx=new THREE.BoxGeometry(x,y,z);gcad.geo[ky]=bx}return gcad.geo[ky]}(gcad,x,y,z);if(centerbase?grp.position.set(0,y/2,0):px||py||pz?grp.position.set(px||0,py||0,pz||0):center||grp.position.set(x/2,y/2,z/2),!nolines){let segments=edgesfromgeometry(box);grp.add(segments)}return grp.add(getmesh(box,mat||mwhite)),grp}
|
|
614
620
|
/**
|
|
615
621
|
* Crea una sfera 3D come gruppo (mesh + edges opzionali).
|
|
616
622
|
* @param {object} gcad - riferimento (non usato ma coerente con getbox)
|
|
@@ -1093,7 +1099,7 @@ constructor(data,position,debugMessage){this.data=data,this.offset=position,this
|
|
|
1093
1099
|
/**
|
|
1094
1100
|
* Libera tutte le risorse caricate
|
|
1095
1101
|
*/
|
|
1096
|
-
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={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();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();for(const key in _meshes)if(_meshes[key]){destroymesh(await _meshes[key])}_movs={},_textures={},_meshes={},_geometries={},_smats={},_scripts={}},getScript:async function getScript(file){file.endsWith(".custom")?file=file.slice(-7):file.endsWith(".js")&&(file=file.slice(-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();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},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){sy||(sy=sx),rot||(rot=0);const key=hash(`${getcat()}|${file}|${sx}|${sy}|${rot}`);return _textures[key]||(_textures[key]=new Promise(((resolve,reject)=>{let url;if(url=P._cdn?`${P._cdn}${getcat()}/textures/${file}`:P.fullget("mufiles/getfile",{id:getcat(),subfolder:"textures",name:file,force:1}),textureCache.has(url)){const tex=textureCache.get(url).clone();return tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,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.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,callback,ky=""){file.endsWith(".3ds")&&(file=file.slice(0,-4));const modifierKey=callback?hash(callback.toString()):"nomod",key=hash(`${getcat()}|${file}.3ds|${modifierKey}|${ky}`);return _meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url,urlt="";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=>{callback&&object.traverse((child=>{child.isMesh&&(Array.isArray(child.material)?child.material=child.material.map((mat=>callback(mat,child))):child.material=callback(child.material,child))})),resolve(object)}),void 0,(error=>{delete _meshes[key],resolve(void 0)}))}))),_meshes[key]},async getglb(file,textures,callback=null,ky=""){const ext=".glb";file.endsWith(ext)&&(file=file.slice(0,-4));let elemento=(file=file.split("
|
|
1102
|
+
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={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();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();for(const key in _meshes)if(_meshes[key]){destroymesh(await _meshes[key])}_movs={},_textures={},_meshes={},_geometries={},_smats={},_scripts={}},getScript:async function getScript(file){file.endsWith(".custom")?file=file.slice(-7):file.endsWith(".js")&&(file=file.slice(-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();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},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){sy||(sy=sx),rot||(rot=0);const key=hash(`${getcat()}|${file}|${sx}|${sy}|${rot}`);return _textures[key]||(_textures[key]=new Promise(((resolve,reject)=>{let url;if(url=file.startsWith("https://")?file:P._cdn?`${P._cdn}${getcat()}/textures/${file}`:P.fullget("mufiles/getfile",{id:getcat(),subfolder:"textures",name:file,force:1}),textureCache.has(url)){const tex=textureCache.get(url).clone();return tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,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.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,callback,ky=""){file.endsWith(".3ds")&&(file=file.slice(0,-4));const modifierKey=callback?hash(callback.toString()):"nomod",key=hash(`${getcat()}|${file}.3ds|${modifierKey}|${ky}`);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=>{callback&&object.traverse((child=>{child.isMesh&&(Array.isArray(child.material)?child.material=child.material.map((mat=>callback(mat,child))):child.material=callback(child.material,child))})),resolve(object)}),void 0,(error=>{delete _meshes[key],resolve(void 0)}))}))),_meshes[key]},async getglb(file,textures,callback=null,ky=""){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],Array.isArray(textures)||(textures=[]);const modifierKey=callback?hash(callback.toString()):"nomod",texturesKey=textures.map((tex=>tex?.uuid||"null")).join("|"),key=hash(`${getcat()}|${file}${ext}|${texturesKey}|${modifierKey}|${ky}`);_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=>{gltf.scene.traverse((child=>{if(child.isMesh){child.frustumCulled=!0;(Array.isArray(child.material)?child.material:[child.material]).forEach((material=>{if(!material||!material.map)return;const originalTexName=material.map.source?.data?.src;if(!originalTexName)return;const match=originalTexName.match(/(\d{2})\.jpg$/);if(!match)return;const textureIndex=parseInt(match[1]);textures[textureIndex]&&(material.map=textures[textureIndex],material.needsUpdate=!0)})),callback&&(Array.isArray(child.material)?child.material=child.material.map((mat=>callback(mat,child))):child.material=callback(child.material,child))}})),resolve(gltf.scene)}),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}}}const originalMaterials=new Map;
|
|
1097
1103
|
/**
|
|
1098
1104
|
* Salva i materiali originali di tutti i mesh nel gruppo (solo layer <= 20)
|
|
1099
1105
|
* @param {THREE.Object3D} gruppo
|
|
@@ -1113,4 +1119,4 @@ async function clear(){function destroymesh(mesh){function disposeMaterial(mater
|
|
|
1113
1119
|
* @param {THREE.Object3D} gruppo - oggetto root
|
|
1114
1120
|
* @param {Array<{ mats: string[], name?: string }>} matricole - elenco da evidenziare
|
|
1115
1121
|
* @returns {Promise<File[]>}
|
|
1116
|
-
*/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){const sanitized=pars.map((p=>getOggetto(p)));console.log(...sanitized)},Math:Math,clean:clean,SP:SP,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){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,estruso,estrusopat,evalcustomfunction,evidenziaColli,get3dshape,getOggetto,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getface,getfakeshadow,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpoint,getprojectkeys,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,groupfromgeometry,hash,infoestrudi,isfn,ismacro,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scaleunit,setLineColorMode,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
|
|
1122
|
+
*/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){const sanitized=pars.map((p=>getOggetto(p)));console.log(...sanitized)},Math:Math,clean:clean,SP:SP,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){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getface,getfakeshadow,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpoint,getprojectkeys,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,groupfromgeometry,hash,infoestrudi,isfn,ismacro,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scaleunit,setLineColorMode,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
|
package/bin/markuno.js
CHANGED
|
@@ -161,7 +161,7 @@ var toNum=(n,dec=-1)=>{const num="string"==typeof n?parseFloat(n)||0:n;if(dec<0)
|
|
|
161
161
|
* @param {string} codice - Il codice sorgente da processare
|
|
162
162
|
* @param {boolean} tienivuoti - Se true mantiene le righe vuote
|
|
163
163
|
* @returns {string[]} Array di righe di codice senza commenti
|
|
164
|
-
*/function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(
|
|
164
|
+
*/function muClComments(codice,tienivuoti){const righe=(code=codice,code.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\/\*[\s\S]*?\*\//g,((match,quoted)=>quoted||""))).split(/\r?\n/);var code;const tm=[];let rigaContinua="";for(const riga of righe){let rigaTrim=riga.trim();if(/(^|[^:])\/\/.*/.test(rigaTrim)&&(rigaTrim=rigaTrim.replace(/(^|[^:])\/\/.*/,((match,p1)=>p1.trim()))),0!==rigaTrim.length||tienivuoti)if(rigaContinua.length>0&&(rigaTrim=rigaContinua+" "+rigaTrim,rigaContinua=""),rigaTrim.endsWith("\\")){rigaTrim=rigaTrim.slice(0,-1);const indiceCommento=rigaTrim.lastIndexOf("//");-1!==indiceCommento&&(rigaTrim=rigaTrim.slice(0,indiceCommento).trim()),rigaContinua=rigaTrim}else tm.push(rigaTrim)}return tm}
|
|
165
165
|
/**
|
|
166
166
|
* Analizza e organizza il codice in una struttura dati gerarchica
|
|
167
167
|
* @param {string[]} tt - Array di righe di codice da analizzare
|
package/package.json
CHANGED
package/types/markcad.d.ts
CHANGED
|
@@ -369,6 +369,7 @@ export function evalcustomfunction(amb: any, code: any, values: any, objects: an
|
|
|
369
369
|
mats: string[];
|
|
370
370
|
name?: string;
|
|
371
371
|
}>, callback: any): Promise<File[]>;
|
|
372
|
+
export function extractTextures(root: any, baseName: any): Promise<any[]>;
|
|
372
373
|
export function get3dshape(punti: any, material: any, layer: any): any;
|
|
373
374
|
export function getOggetto(obj: any, exclude?: any[]): any;
|
|
374
375
|
export function getbordi(oggetti: any, bordo: any): {
|