markuno_lib 1.1.33 → 1.1.35
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 -10
- package/bin/markcad3d.js +4 -4
- package/package.json +1 -1
- package/types/markcad.d.ts +8 -3
- package/types/markcad3d.d.ts +17 -0
package/bin/markcad.js
CHANGED
|
@@ -61,7 +61,7 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
|
|
|
61
61
|
/**
|
|
62
62
|
* Calcola la lunghezza della linea
|
|
63
63
|
* @returns {number} Lunghezza
|
|
64
|
-
*/get len(){return Math.sqrt(this.len2)}
|
|
64
|
+
*/get len(){return Math.sqrt(this.len2)}get angle(){return this.angolo()}
|
|
65
65
|
/**
|
|
66
66
|
* Estende la linea di una certa lunghezza o fino all'intersezione con un'altra linea
|
|
67
67
|
* @param {number|Linea2} l - Lunghezza di estensione o linea da intersecare
|
|
@@ -79,9 +79,10 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
|
|
|
79
79
|
* Crea una nuova linea ruotata di un certo angolo
|
|
80
80
|
* @param {number} [angle=Math.PI/2] - Angolo di rotazione in radianti
|
|
81
81
|
* @param {number} [length=0] - Lunghezza della nuova linea
|
|
82
|
-
* @param {boolean} [fine=false] - Se
|
|
82
|
+
* @param {boolean/Punto2} [fine=false] - Se fine è un punto allora crea un segmento che passa per quel punto
|
|
83
|
+
* Se true ruota attorno al primo punto, altrimenti al secondo
|
|
83
84
|
* @returns {Linea2} Nuova linea ruotata
|
|
84
|
-
*/ruotata(angle=Math.PI/2,length=0,fine=!1){const{p1:p1,p2:p2,direzione:direzione,len:len}=this;length=length||len;const sx=(direzione.x*Math.cos(angle)-direzione.y*Math.sin(angle))*length,sy=(direzione.x*Math.sin(angle)+direzione.y*Math.cos(angle))*length;return fine?new Linea2(p1,new Punto2(p1.x+sx,p1.y+sy)):new Linea2(p2,new Punto2(p2.x+sx,p2.y+sy))}
|
|
85
|
+
*/ruotata(angle=Math.PI/2,length=0,fine=!1){const{p1:p1,p2:p2,direzione:direzione,len:len}=this;if(length=length||len,len<1e-9)return;const a=Math.abs(angle%(2*Math.PI));if(!(a<1e-9||Math.abs(a-Math.PI)<1e-9)){if("boolean"==typeof fine){const sx=(direzione.x*Math.cos(angle)-direzione.y*Math.sin(angle))*length,sy=(direzione.x*Math.sin(angle)+direzione.y*Math.cos(angle))*length;return fine?new Linea2(p1,new Punto2(p1.x+sx,p1.y+sy)):new Linea2(p2,new Punto2(p2.x+sx,p2.y+sy))}{let p3=new Punto2(fine);const dx=direzione.x*Math.cos(angle)-direzione.y*Math.sin(angle),dy=direzione.x*Math.sin(angle)+direzione.y*Math.cos(angle);new Punto2(dx,dy);const rettaRuotata=new Linea2(p3,new Punto2(p3.x+dx,p3.y+dy)),puntoIntersezione=this.interseca(rettaRuotata);if(!puntoIntersezione)return;const pFine=new Punto2(puntoIntersezione.x+dx*length,puntoIntersezione.y+dy*length);return new Linea2(puntoIntersezione,pFine)}}}
|
|
85
86
|
/**
|
|
86
87
|
* Calcola un punto sulla direzione della linea a una certa distanza
|
|
87
88
|
* @param {Punto2} p1 - Punto di partenza
|
|
@@ -98,7 +99,7 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
|
|
|
98
99
|
* Calcola il punto di intersezione con un'altra linea
|
|
99
100
|
* @param {Linea2} line2 - Seconda linea
|
|
100
101
|
* @returns {Punto2|null} Punto di intersezione o null se parallele
|
|
101
|
-
*/intersezione(line2){const{p1:p1_1,p2:p2_1}=this,{p1:p1_2,p2:p2_2}=line2,det=(p2_1.x-p1_1.x)*(p2_2.y-p1_2.y)-(p2_1.y-p1_1.y)*(p2_2.x-p1_2.x);if(Math.abs(det)<.001)return null;const t=((p1_2.x-p1_1.x)*(p2_2.y-p1_2.y)-(p1_2.y-p1_1.y)*(p2_2.x-p1_2.x))/det;return new Punto2(p1_1.x+t*(p2_1.x-p1_1.x),p1_1.y+t*(p2_1.y-p1_1.y))}onsegment(p,eps=1e-9){const{p1:p1,p2:p2}=this,minX=Math.min(p1.x,p2.x)-eps,maxX=Math.max(p1.x,p2.x)+eps,minY=Math.min(p1.y,p2.y)-eps,maxY=Math.max(p1.y,p2.y)+eps;return p.x>=minX&&p.x<=maxX&&p.y>=minY&&p.y<=maxY}
|
|
102
|
+
*/intersezione(line2){return this.interseca(line2)}interseca(line2){const{p1:p1_1,p2:p2_1}=this,{p1:p1_2,p2:p2_2}=line2,det=(p2_1.x-p1_1.x)*(p2_2.y-p1_2.y)-(p2_1.y-p1_1.y)*(p2_2.x-p1_2.x);if(Math.abs(det)<.001)return null;const t=((p1_2.x-p1_1.x)*(p2_2.y-p1_2.y)-(p1_2.y-p1_1.y)*(p2_2.x-p1_2.x))/det;return new Punto2(p1_1.x+t*(p2_1.x-p1_1.x),p1_1.y+t*(p2_1.y-p1_1.y))}onsegment(p,eps=1e-9){const{p1:p1,p2:p2}=this,minX=Math.min(p1.x,p2.x)-eps,maxX=Math.max(p1.x,p2.x)+eps,minY=Math.min(p1.y,p2.y)-eps,maxY=Math.max(p1.y,p2.y)+eps;return p.x>=minX&&p.x<=maxX&&p.y>=minY&&p.y<=maxY}
|
|
102
103
|
/**
|
|
103
104
|
* Verifica se la linea è parallela a un'altra
|
|
104
105
|
* @param {Linea2} line2 - Seconda linea
|
|
@@ -122,10 +123,10 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
|
|
|
122
123
|
* @returns {Linea2} Nuova linea parallela
|
|
123
124
|
*/offset(delta){const normale=this.normale,p1_offset=new Punto2(this.p1.x+normale.x*delta,this.p1.y+normale.y*delta),p2_offset=new Punto2(this.p2.x+normale.x*delta,this.p2.y+normale.y*delta);return new Linea2(p1_offset,p2_offset)}
|
|
124
125
|
/**
|
|
125
|
-
* Calcola l'angolo tra questa linea e un'altra
|
|
126
|
+
* Calcola l'angolo tra questa linea e un'altra o l'angolo assoluto d
|
|
126
127
|
* @param {Linea2} line2 - Seconda linea
|
|
127
128
|
* @returns {number} Angolo in radianti
|
|
128
|
-
*/angolo(line2){const{dx:dx1,dy:dy1}=this
|
|
129
|
+
*/angolo(line2){const{dx:dx1,dy:dy1}=this;let delta;if(line2){const{dx:dx2,dy:dy2}=line2,a1=Math.atan2(dy1,dx1);delta=Math.atan2(dy2,dx2)-a1}else delta=Math.atan2(dy1,dx1);return delta>Math.PI?delta-=2*Math.PI:delta<-Math.PI&&(delta+=2*Math.PI),delta}ortopt(l){let{p1:p1,dx:dx,dy:dy}=this;const len=Math.hypot(dx,dy);if(len<.001)return;const ux=-dy/len,uy=dx/len;return{x:p1.x+ux*l,y:p1.y+uy*l}}offsetline(l){let{p1:p1,p2:p2,dx:dx,dy:dy}=this;const len=Math.hypot(dx,dy);if(len<.001)return;const ux=-dy/len,uy=dx/len;return new Linea2({x:p1.x+ux*l,y:p1.y+uy*l},{x:p2.x+ux*l,y:p2.y+uy*l})}
|
|
129
130
|
/**
|
|
130
131
|
* Calcola la distanza tra due segmenti paralleli
|
|
131
132
|
* @param {Linea2} line2 - Seconda linea
|
|
@@ -268,7 +269,7 @@ function getshape(){let pt=[];
|
|
|
268
269
|
* Aggiunge punti da array di coordinate
|
|
269
270
|
* @param {Array<number>} aa - Array [x1,y1,x2,y2,...]
|
|
270
271
|
*/
|
|
271
|
-
function _addvec(aa){for(let i=0;i<aa.length;i+=2)pt.push({x:aa[i],y:aa[i+1]})}function dims(pts){let{p1:p1,p2:p2}=pts.reduce(((m,p)=>(m.p1.x=Math.min(m.p1.x,p.x),m.p2.x=Math.max(m.p2.x,p.x),m.p1.y=Math.min(m.p1.y,p.y),m.p2.y=Math.max(m.p2.y,p.y),m)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)}),isrect=!1;if(4==pts.length){const TOLL=.001;function findpunto(x,y){return!!pts.find((p=>Math.abs(p.x-x)<TOLL&&Math.abs(p.y-y)<TOLL))}findpunto(p1.x,p1.y)&&findpunto(p1.x,p2.y)&&findpunto(p2.x,p1.y)&&findpunto(p2.x,p2.y)&&(isrect=!0)}return{p1:p1,p2:p2,isrect:isrect,width:p2.x-p1.x,height:p2.y-p1.y}}return{get key(){return hash(tovec().join("\t"))},orienta:function orienta(p0,p1){if(!p0||!p1)return null;const dx=p1.x-p0.x,dy=p1.y-p0.y,angolo=180*Math.atan2(dy,dx)/Math.PI,matrix=new Matrix3D;matrix.rotateZ(-angolo),matrix.translate(-p0.x,-p0.y,0);const ptTrasformati=pt.map((p=>matrix.transform(p.x,p.y)));let mm=ptTrasformati.reduce(((m,p)=>(m.p1.x=Math.min(m.p1.x,p.x),m.p2.x=Math.max(m.p2.x,p.x),m.p1.y=Math.min(m.p1.y,p.y),m.p2.y=Math.max(m.p2.y,p.y),m)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)});return{shape:getshape().frompt(ptTrasformati),origine:new Punto2(p0.x,p0.y),angolo:angolo,mm:mm,width:mm.p2.x-mm.p1.x,height:mm.p2.y-mm.p1.y}},rebase:function rebase(angolo,forceorigin=!1,ox=0,oy=0){const matrix=new Matrix3D;matrix.rotateZ(-angolo);let ptTrasformati=pt.map((p=>matrix.transform(p.x,p.y))),{p1:p1,p2:p2,width:width,height:height}=dims(ptTrasformati);return forceorigin||(ox=p1.x,oy=p1.y),ptTrasformati=ptTrasformati.map((p=>new Punto2(p.x-ox,p.y-oy))),{shape:getshape().frompt(ptTrasformati),origine:new Punto2(ox,oy),angolo:angolo,width:width,height:height}},get pt(){return pt},get vec(){return tovec()},toJSON:()=>({vec:tovec(),orient:orientation()}),get orient(){return orientation()},clone:()=>getshape().frompt(pt),dims:()=>dims(pt),rotate(deg){if(!deg)return this;const r=deg*Math.PI/180,cosTheta=Math.cos(r),sinTheta=Math.sin(r);for(let p of pt){const xNew=p.x*cosTheta-p.y*sinTheta,yNew=p.x*sinTheta+p.y*cosTheta;p.x=xNew,p.y=yNew}return this},selezionaprimo:function selezionaprimo(idprimopunto){return(idprimopunto%=pt.length)>0&&(pt=[...pt.slice(idprimopunto),...pt.slice(0,idprimopunto)]),this},segment(i,inverse=!1){let n=pt.length;return new Linea2(pt[i%n],pt[(i+(inverse?-1:1))%n])},lineoffset(i1,i2,offset){if((i1=(i1||0)%pt.length)!=(i2=(i2||0)%pt.length)){let l2=new Linea2(pt[i1],pt[i2]);if(l2){return l2=l2.offsetline(-offset),this.intersectline(l2)}}},move(x=0,y=0){for(let p of pt)p.x+=x,p.y+=y;return this},mirrorx(value=0){for(let p of pt)p.x=2*value-p.x;return this},mirrory(value=0){for(let p of pt)p.y=2*value-p.y;return this},simplify(tolerance,hq){return pt=function simplify(points,tolerance,highestQuality){if(points.length<=2)return points;var sqTolerance=void 0!==tolerance?tolerance*tolerance:1;return simplifyDouglasPeucker(points=highestQuality?points:function simplifyRadialDist(points,sqTolerance){for(var point,p1,p2,dx,dy,prevPoint=points[0],newPoints=[prevPoint],i=1,len=points.length;i<len;i++)p2=prevPoint,dx=void 0,dy=void 0,(dx=(p1=point=points[i]).x-p2.x)*dx+(dy=p1.y-p2.y)*dy>sqTolerance&&(newPoints.push(point),prevPoint=point);return prevPoint!==point&&newPoints.push(point),newPoints}(points,sqTolerance),sqTolerance)}(pt,tolerance,hq),this},fromclip(vv){pt=[];for(let p of vv)pt.push({x:p.x/1e3,y:p.y/1e3});return this},infosegmento(i,open=!1){const n=pt.length;function clampIndex(idx){return(idx+n)%n}function angle(p1,p2){return Math.atan2(p2.y-p1.y,p2.x-p1.x)}function angleDiff(a,b){let diff=a-b;for(;diff>Math.PI;)diff-=2*Math.PI;for(;diff<-Math.PI;)diff+=2*Math.PI;return diff}const p1=pt[i];let p0,p2,p3;if(open)if(0===i){const dx=pt[1].x-pt[0].x,dy=pt[1].y-pt[0].y;p0={x:pt[0].x-dx,y:pt[0].y-dy},p2=pt[1],p3=pt[2]}else if(i===n-1){const dx=pt[n-1].x-pt[n-2].x,dy=pt[n-1].y-pt[n-2].y;p0=pt[n-2],p2={x:pt[n-1].x+dx,y:pt[n-1].y+dy},p3={x:p2.x+dx,y:p2.y+dy}}else p0=pt[i-1],p2=pt[i+1],p3=i+2<n?pt[i+2]:{x:pt[i+1].x+(pt[i+1].x-pt[i].x),y:pt[i+1].y+(pt[i+1].y-pt[i].y)};else{const i0=clampIndex(i-1),i2=clampIndex(i+1),i3=clampIndex(i+2);p0=pt[i0],p2=pt[i2],p3=pt[i3]}const ang12=angle(p1,p2),ang01=angle(p0,p1),ang23=angle(p2,p3);return{x:p1.x,y:p1.y,l:function length(p1,p2){const dx=p2.x-p1.x,dy=p2.y-p1.y;return Math.sqrt(dx*dx+dy*dy)}(p1,p2),ang:ang12/PIF,a1:angleDiff(ang12,ang01)/PIF,a2:angleDiff(ang23,ang12)/PIF}},fromvec(aa){return pt=[],_addvec(aa),this},addvec(vec){return _addvec(vec),this},frompt(pts){return pt=[...pts],pt=removeduplicate(pt),this},fromstr(str){return pt=removeduplicate(function processTokens(tokens){const points=[];for(let i=0;i<tokens.length;i++){const token=tokens[i];if("point"===token.type)points.push(token.point);else if("command"===token.type)switch(token.cmd){case"b":{if(points.length<2)continue;const npt=parseInt(token.params[0])||5,p1=points[points.length-2],p2=points[points.length-1];let p3="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p4="point"===tokens[i+2]?.type?tokens[i+2].point:void 0;p3?p4||(p4=points[0]):(p3=points[0],p4=points[1]);const raccordo=raccordabezier(p1,p2,p3,p4,npt);points.push(...raccordo),i+=1;break}case"r":{if(points.length<1)continue;const dist=parseFloat(token.params[0])||5,npt=parseInt(token.params[1])||10,p1=points[points.length-1];let p2="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p3="point"===tokens[i+2]?.type?tokens[i+2].point:"point"===tokens[i+3]?.type?tokens[i+3].point:void 0;p2?p3||(p3=points[0]):(p2=points[0],p3=points[1],points.splice(0,1));const raccordo=raccordabezier3(p1,p2,p3,dist,npt);points.push(...raccordo),i+=1;break}case"c":{const radius=parseFloat(token.params[0])||50,segments=parseInt(token.params[1])||12,center="point"===tokens[i+1]?.type?tokens[i+1].point:new Punto2(0,0);for(let j=0;j<segments;j++)points.push(new Punto2(center.x+radius*Math.cos(j/segments*Math.PI*2),center.y+radius*Math.sin(j/segments*Math.PI*2)));i+=1;break}case"a":{let npt,p1="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p2="point"===tokens[i+2]?.type?tokens[i+2].point:void 0,p3="point"===tokens[i+3]?.type?tokens[i+3].point:void 0;if(!p1||!p3)continue;if(p2)if(token.params[0])npt=clamp(parseInt(token.params[0]),1,24);else{const chord=Math.hypot(p3.x-p1.x,p3.y-p1.y),sagitta=Math.abs((p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y))/(2*chord);npt=Math.round(chord*Math.sqrt(sagitta/(chord+.1))*10),npt=clamp(npt,1,24),npt=1}else p2=p3,npt=0;const arcoPoints=arcfrom3point(npt,p1,p2,p3);points.push(...arcoPoints),i+=3;break}}}return points}(function tokenize(str){const tokens=[],values=str.toLowerCase().replace(/[\n\s]+/gm," ").split(/[,;]/).map((s=>s.trim()));for(let i=0;i<values.length;){const current=values[i];["b","r","c","a"].includes(current[0])?(tokens.push({type:"command",cmd:current[0],params:current.slice(1).split(":")}),i++):/[a-zA-Z]/.test(current[0])||(i<values.length-1?(tokens.push({type:"point",point:new Punto2(parseFloat(values[i]),parseFloat(values[i+1]))}),i+=2):i++)}return tokens}(str))),this},fromrect(w,h,sx,sy,bordo){w||(w=10),h||(h=10),bordo||(bordo=0),bordo=Math.min(Math.abs(bordo),Math.abs(.4*w),Math.abs(.4*h));let b1=w>0?bordo:-bordo,b2=h>0?bordo:-bordo;return pt=bordo?[{x:b1,y:0},{x:w-b1,y:0},{x:w,y:b2},{x:w,y:h-b2},{x:w-b1,y:h},{x:b1,y:h},{x:0,y:h-b2},{x:0,y:b2}]:[{x:0,y:0},{x:w,y:0},{x:w,y:h},{x:0,y:h}],this},intersectline:l=>function _intersectline(shape,p3,p4){let n=shape.length,l=new Linea2(p3,p4);const intersezioni=[];for(let i=0;i<shape.length;i++){let l2=new Linea2(shape[i],shape[(i+1)%n]),p=l2.intersezione(l);p&&l2.onsegment(p)&&intersezioni.push(p)}if(intersezioni.length<2)return null;const{dx:dx,dy:dy}=l;intersezioni.sort(((a,b)=>(a.x-p3.x)*dx+(a.y-p3.y)*dy-((b.x-p3.x)*dx+(b.y-p3.y)*dy)));let pstart=new Punto2(intersezioni[0].x,intersezioni[0].y),pend=new Punto2(intersezioni[intersezioni.length-1].x,intersezioni[intersezioni.length-1].y);const vx1=pend.x-pstart.x,vy1=pend.y-pstart.y;return vx1*dx+vy1*dy<0&&([pstart,pend]=[pend,pstart]),new Linea2(pstart,pend)}(pt,l.p1,l.p2),addpt(pts){return pts?(Array.isArray(pts)||(pts=[pts]),pt=removeduplicate([...pt,...pts]),this):this},addracc(v1,v2,suddivisioni=2,addv1v2=!0){if(Array.isArray(v1)&&(v2={x:v1[2]||0,y:v1[3]||0},v1={x:v1[0]||0,y:v1[1]||0}),pt.length>=2){let tm=raccordabezier(pt[pt.length-2],pt[pt.length-1],v1,v2,suddivisioni);pt=[...pt,...tm],addv1v2&&(pt.push(v1),pt.push(v2))}return pt=removeduplicate(pt),this},setorient(mode){let p=orientation();return(1==p&&-1==mode||-1==p&&1==mode)&&pt.reverse(),this},reverse(){return pt.reverse(),this},pointinshape:p=>function isPointInPolygon(P){let x=P.x,y=P.y,inside=!1;for(let i=0,j=pt.length-1;i<pt.length;j=i++){let xi=pt[i].x,yi=pt[i].y,xj=pt[j].x,yj=pt[j].y;yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi&&(inside=!inside)}return inside}(p),azzera(){return pt=[],this},removeduplicate(delta=.005){return pt=removeduplicate(pt,delta),this},to3d(u0,alt=0,coeffa=0,coeffb=0,open=!1){pt=removeduplicate(pt);let tm=function genuvnormal(path,options){let{currentU:currentU=0,c:c=0,a:a=0,b:b=0,anglemin:anglemin=30,open:open=!1}=options;const pointsWithNormals=[],n=path.length;for(let i=0;i<n;i++){const prev=path[(i-1+n)%n],current=path[i],next=path[(i+1)%n],vPrev={x:current.x-prev.x,y:current.y-prev.y},vNext={x:next.x-current.x,y:next.y-current.y},normalPrev=normal2(prev,current),normalNext=normal2(current,next),angle=angle2vec(vPrev,vNext);let z=a*current.x+b*current.y+c;Math.abs(angle-180)<=anglemin?(normalPrev.nx,normalNext.nx,normalPrev.ny,normalNext.ny,pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z})):(pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z}),pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z}));const dx=next.x-current.x,dy=next.y-current.y;currentU+=Math.sqrt(dx*dx+dy*dy)}if(!open){let p=pointsWithNormals[0],pf=pointsWithNormals[pointsWithNormals.length-1];p.x==pf.x&&p.y==pf.y||pointsWithNormals.push({x:p.x,y:p.y,z:p.z,nx:p.nx,ny:p.ny,nz:p.nz,u:currentU,v:p.z})}return pointsWithNormals}(pt,{open:open,currentU:u0,c:alt,a:coeffa,b:coeffb,anglemin:30});return tm},getboundbox:()=>pt.length?pt.reduce(((box,p)=>(box.p1.x=Math.min(box.p1.x,p.x),box.p1.y=Math.min(box.p1.y,p.y),box.p2.x=Math.max(box.p2.x,p.x),box.p2.y=Math.max(box.p2.y,p.y),box)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)}):{p1:new Punto2(0,0),p2:new Punto2(0,0)},fittobox(p1,p2){if(!pt.length)return this;const currentBox=this.getboundbox(),currentWidth=currentBox.p2.x-currentBox.p1.x,currentHeight=currentBox.p2.y-currentBox.p1.y,targetWidth=p2.x-p1.x,targetHeight=p2.y-p1.y,scale=Math.min(targetWidth/(currentWidth||1),targetHeight/(currentHeight||1));for(let p of pt)p.x=(p.x-currentBox.p1.x)*scale,p.y=(p.y-currentBox.p1.y)*scale,p.x+=p1.x,p.y+=p1.y;return this}}}
|
|
272
|
+
function _addvec(aa){for(let i=0;i<aa.length;i+=2)pt.push({x:aa[i],y:aa[i+1]})}function dims(pts){let{p1:p1,p2:p2}=pts.reduce(((m,p)=>(m.p1.x=Math.min(m.p1.x,p.x),m.p2.x=Math.max(m.p2.x,p.x),m.p1.y=Math.min(m.p1.y,p.y),m.p2.y=Math.max(m.p2.y,p.y),m)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)}),isrect=!1;if(4==pts.length){const TOLL=.001;function findpunto(x,y){return!!pts.find((p=>Math.abs(p.x-x)<TOLL&&Math.abs(p.y-y)<TOLL))}findpunto(p1.x,p1.y)&&findpunto(p1.x,p2.y)&&findpunto(p2.x,p1.y)&&findpunto(p2.x,p2.y)&&(isrect=!0)}return{p1:p1,p2:p2,isrect:isrect,width:p2.x-p1.x,height:p2.y-p1.y}}return{get key(){return hash(tovec().join("\t"))},orienta:function orienta(p0,p1){if(!p0||!p1)return null;const dx=p1.x-p0.x,dy=p1.y-p0.y,angolo=180*Math.atan2(dy,dx)/Math.PI,matrix=new Matrix3D;matrix.rotateZ(-angolo),matrix.translate(-p0.x,-p0.y,0);const ptTrasformati=pt.map((p=>matrix.transform(p.x,p.y)));let mm=ptTrasformati.reduce(((m,p)=>(m.p1.x=Math.min(m.p1.x,p.x),m.p2.x=Math.max(m.p2.x,p.x),m.p1.y=Math.min(m.p1.y,p.y),m.p2.y=Math.max(m.p2.y,p.y),m)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)});return{shape:getshape().frompt(ptTrasformati),origine:new Punto2(p0.x,p0.y),angolo:angolo,mm:mm,width:mm.p2.x-mm.p1.x,height:mm.p2.y-mm.p1.y}},rebase:function rebase(angolo,forceorigin=!1,ox=0,oy=0){const matrix=new Matrix3D;matrix.rotateZ(-angolo);let ptTrasformati=pt.map((p=>matrix.transform(p.x,p.y))),{p1:p1,p2:p2,width:width,height:height}=dims(ptTrasformati);return forceorigin||(ox=p1.x,oy=p1.y),ptTrasformati=ptTrasformati.map((p=>new Punto2(p.x-ox,p.y-oy))),{shape:getshape().frompt(ptTrasformati),origine:new Punto2(ox,oy),angolo:angolo,width:width,height:height}},get pt(){return pt},get vec(){return tovec()},toJSON:()=>({vec:tovec(),orient:orientation()}),get orient(){return orientation()},clone:()=>getshape().frompt(pt),dims:()=>dims(pt),rotate(deg){if(!deg)return this;const r=deg*Math.PI/180,cosTheta=Math.cos(r),sinTheta=Math.sin(r);for(let p of pt){const xNew=p.x*cosTheta-p.y*sinTheta,yNew=p.x*sinTheta+p.y*cosTheta;p.x=xNew,p.y=yNew}return this},selezionaprimo:function selezionaprimo(idprimopunto){return(idprimopunto%=pt.length)>0&&(pt=[...pt.slice(idprimopunto),...pt.slice(0,idprimopunto)]),this},segment(i,inverse=!1){let n=pt.length;return i<0&&(i+=n),new Linea2(pt[i%n],pt[(i+(inverse?-1:1))%n])},lineoffset(i1,i2,offset){if((i1=(i1||0)%pt.length)!=(i2=(i2||0)%pt.length)){let l2=new Linea2(pt[i1],pt[i2]);if(l2){return l2=l2.offsetline(-offset),this.intersectline(l2)}}},move(x=0,y=0){for(let p of pt)p.x+=x,p.y+=y;return this},mirrorx(value=0){for(let p of pt)p.x=2*value-p.x;return this},mirrory(value=0){for(let p of pt)p.y=2*value-p.y;return this},simplify(tolerance,hq){return pt=function simplify(points,tolerance,highestQuality){if(points.length<=2)return points;var sqTolerance=void 0!==tolerance?tolerance*tolerance:1;return simplifyDouglasPeucker(points=highestQuality?points:function simplifyRadialDist(points,sqTolerance){for(var point,p1,p2,dx,dy,prevPoint=points[0],newPoints=[prevPoint],i=1,len=points.length;i<len;i++)p2=prevPoint,dx=void 0,dy=void 0,(dx=(p1=point=points[i]).x-p2.x)*dx+(dy=p1.y-p2.y)*dy>sqTolerance&&(newPoints.push(point),prevPoint=point);return prevPoint!==point&&newPoints.push(point),newPoints}(points,sqTolerance),sqTolerance)}(pt,tolerance,hq),this},fromclip(vv){pt=[];for(let p of vv)pt.push({x:p.x/1e3,y:p.y/1e3});return this},infosegmento(i,open=!1){const n=pt.length;function clampIndex(idx){return(idx+n)%n}function angle(p1,p2){return Math.atan2(p2.y-p1.y,p2.x-p1.x)}function angleDiff(a,b){let diff=a-b;for(;diff>Math.PI;)diff-=2*Math.PI;for(;diff<-Math.PI;)diff+=2*Math.PI;return diff}const p1=pt[i];let p0,p2,p3;if(open)if(0===i){const dx=pt[1].x-pt[0].x,dy=pt[1].y-pt[0].y;p0={x:pt[0].x-dx,y:pt[0].y-dy},p2=pt[1],p3=pt[2]}else if(i===n-1){const dx=pt[n-1].x-pt[n-2].x,dy=pt[n-1].y-pt[n-2].y;p0=pt[n-2],p2={x:pt[n-1].x+dx,y:pt[n-1].y+dy},p3={x:p2.x+dx,y:p2.y+dy}}else p0=pt[i-1],p2=pt[i+1],p3=i+2<n?pt[i+2]:{x:pt[i+1].x+(pt[i+1].x-pt[i].x),y:pt[i+1].y+(pt[i+1].y-pt[i].y)};else{const i0=clampIndex(i-1),i2=clampIndex(i+1),i3=clampIndex(i+2);p0=pt[i0],p2=pt[i2],p3=pt[i3]}const ang12=angle(p1,p2),ang01=angle(p0,p1),ang23=angle(p2,p3);return{x:p1.x,y:p1.y,l:function length(p1,p2){const dx=p2.x-p1.x,dy=p2.y-p1.y;return Math.sqrt(dx*dx+dy*dy)}(p1,p2),ang:ang12/PIF,a1:angleDiff(ang12,ang01)/PIF,a2:angleDiff(ang23,ang12)/PIF}},fromvec(aa){return pt=[],_addvec(aa),this},addvec(vec){return _addvec(vec),this},frompt(pts){return pt=[...pts],pt=removeduplicate(pt),this},fromstr(str){return pt=removeduplicate(function processTokens(tokens){const points=[];for(let i=0;i<tokens.length;i++){const token=tokens[i];if("point"===token.type)points.push(token.point);else if("command"===token.type)switch(token.cmd){case"b":{if(points.length<2)continue;const npt=parseInt(token.params[0])||5,p1=points[points.length-2],p2=points[points.length-1];let p3="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p4="point"===tokens[i+2]?.type?tokens[i+2].point:void 0;p3?p4||(p4=points[0]):(p3=points[0],p4=points[1]);const raccordo=raccordabezier(p1,p2,p3,p4,npt);points.push(...raccordo),i+=1;break}case"r":{if(points.length<1)continue;const dist=parseFloat(token.params[0])||5,npt=parseInt(token.params[1])||10,p1=points[points.length-1];let p2="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p3="point"===tokens[i+2]?.type?tokens[i+2].point:"point"===tokens[i+3]?.type?tokens[i+3].point:void 0;p2?p3||(p3=points[0]):(p2=points[0],p3=points[1],points.splice(0,1));const raccordo=raccordabezier3(p1,p2,p3,dist,npt);points.push(...raccordo),i+=1;break}case"c":{const radius=parseFloat(token.params[0])||50,segments=parseInt(token.params[1])||12,center="point"===tokens[i+1]?.type?tokens[i+1].point:new Punto2(0,0);for(let j=0;j<segments;j++)points.push(new Punto2(center.x+radius*Math.cos(j/segments*Math.PI*2),center.y+radius*Math.sin(j/segments*Math.PI*2)));i+=1;break}case"a":{let npt,p1="point"===tokens[i+1]?.type?tokens[i+1].point:void 0,p2="point"===tokens[i+2]?.type?tokens[i+2].point:void 0,p3="point"===tokens[i+3]?.type?tokens[i+3].point:void 0;if(!p1||!p3)continue;if(p2)if(token.params[0])npt=clamp(parseInt(token.params[0]),1,24);else{const chord=Math.hypot(p3.x-p1.x,p3.y-p1.y),sagitta=Math.abs((p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y))/(2*chord);npt=Math.round(chord*Math.sqrt(sagitta/(chord+.1))*10),npt=clamp(npt,1,24),npt=1}else p2=p3,npt=0;const arcoPoints=arcfrom3point(npt,p1,p2,p3);points.push(...arcoPoints),i+=3;break}}}return points}(function tokenize(str){const tokens=[],values=str.toLowerCase().replace(/[\n\s]+/gm," ").split(/[,;]/).map((s=>s.trim()));for(let i=0;i<values.length;){const current=values[i];["b","r","c","a"].includes(current[0])?(tokens.push({type:"command",cmd:current[0],params:current.slice(1).split(":")}),i++):/[a-zA-Z]/.test(current[0])||(i<values.length-1?(tokens.push({type:"point",point:new Punto2(parseFloat(values[i]),parseFloat(values[i+1]))}),i+=2):i++)}return tokens}(str))),this},fromrect(w,h,sx,sy,bordo){w||(w=10),h||(h=10),bordo||(bordo=0),bordo=Math.min(Math.abs(bordo),Math.abs(.4*w),Math.abs(.4*h));let b1=w>0?bordo:-bordo,b2=h>0?bordo:-bordo;return pt=bordo?[{x:b1,y:0},{x:w-b1,y:0},{x:w,y:b2},{x:w,y:h-b2},{x:w-b1,y:h},{x:b1,y:h},{x:0,y:h-b2},{x:0,y:b2}]:[{x:0,y:0},{x:w,y:0},{x:w,y:h},{x:0,y:h}],this},intersectline:l=>function _intersectline(shape,p3,p4){let n=shape.length,l=new Linea2(p3,p4);const intersezioni=[];for(let i=0;i<shape.length;i++){let l2=new Linea2(shape[i],shape[(i+1)%n]),p=l2.interseca(l);p&&l2.onsegment(p)&&intersezioni.push(p)}if(intersezioni.length<2)return null;const{dx:dx,dy:dy}=l;intersezioni.sort(((a,b)=>(a.x-p3.x)*dx+(a.y-p3.y)*dy-((b.x-p3.x)*dx+(b.y-p3.y)*dy)));let pstart=new Punto2(intersezioni[0].x,intersezioni[0].y),pend=new Punto2(intersezioni[intersezioni.length-1].x,intersezioni[intersezioni.length-1].y);const vx1=pend.x-pstart.x,vy1=pend.y-pstart.y;return vx1*dx+vy1*dy<0&&([pstart,pend]=[pend,pstart]),new Linea2(pstart,pend)}(pt,l.p1,l.p2),addpt(pts){return pts?(Array.isArray(pts)||(pts=[pts]),pt=removeduplicate([...pt,...pts]),this):this},addracc(v1,v2,suddivisioni=2,addv1v2=!0){if(Array.isArray(v1)&&(v2={x:v1[2]||0,y:v1[3]||0},v1={x:v1[0]||0,y:v1[1]||0}),pt.length>=2){let tm=raccordabezier(pt[pt.length-2],pt[pt.length-1],v1,v2,suddivisioni);pt=[...pt,...tm],addv1v2&&(pt.push(v1),pt.push(v2))}return pt=removeduplicate(pt),this},setorient(mode){let p=orientation();return(1==p&&-1==mode||-1==p&&1==mode)&&pt.reverse(),this},reverse(){return pt.reverse(),this},pointinshape:p=>function isPointInPolygon(P){let x=P.x,y=P.y,inside=!1;for(let i=0,j=pt.length-1;i<pt.length;j=i++){let xi=pt[i].x,yi=pt[i].y,xj=pt[j].x,yj=pt[j].y;yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi&&(inside=!inside)}return inside}(p),azzera(){return pt=[],this},removeduplicate(delta=.005){return pt=removeduplicate(pt,delta),this},to3d(u0,alt=0,coeffa=0,coeffb=0,open=!1){pt=removeduplicate(pt);let tm=function genuvnormal(path,options){let{currentU:currentU=0,c:c=0,a:a=0,b:b=0,anglemin:anglemin=30,open:open=!1}=options;const pointsWithNormals=[],n=path.length;for(let i=0;i<n;i++){const prev=path[(i-1+n)%n],current=path[i],next=path[(i+1)%n],vPrev={x:current.x-prev.x,y:current.y-prev.y},vNext={x:next.x-current.x,y:next.y-current.y},normalPrev=normal2(prev,current),normalNext=normal2(current,next),angle=angle2vec(vPrev,vNext);let z=a*current.x+b*current.y+c;Math.abs(angle-180)<=anglemin?(normalPrev.nx,normalNext.nx,normalPrev.ny,normalNext.ny,pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z})):(pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z}),pointsWithNormals.push({x:current.x,y:-current.y,z:z,u:currentU,v:z}));const dx=next.x-current.x,dy=next.y-current.y;currentU+=Math.sqrt(dx*dx+dy*dy)}if(!open){let p=pointsWithNormals[0],pf=pointsWithNormals[pointsWithNormals.length-1];p.x==pf.x&&p.y==pf.y||pointsWithNormals.push({x:p.x,y:p.y,z:p.z,nx:p.nx,ny:p.ny,nz:p.nz,u:currentU,v:p.z})}return pointsWithNormals}(pt,{open:open,currentU:u0,c:alt,a:coeffa,b:coeffb,anglemin:30});return tm},getboundbox:()=>pt.length?pt.reduce(((box,p)=>(box.p1.x=Math.min(box.p1.x,p.x),box.p1.y=Math.min(box.p1.y,p.y),box.p2.x=Math.max(box.p2.x,p.x),box.p2.y=Math.max(box.p2.y,p.y),box)),{p1:new Punto2(1/0,1/0),p2:new Punto2(-1/0,-1/0)}):{p1:new Punto2(0,0),p2:new Punto2(0,0)},fittobox(p1,p2){if(!pt.length)return this;const currentBox=this.getboundbox(),currentWidth=currentBox.p2.x-currentBox.p1.x,currentHeight=currentBox.p2.y-currentBox.p1.y,targetWidth=p2.x-p1.x,targetHeight=p2.y-p1.y,scale=Math.min(targetWidth/(currentWidth||1),targetHeight/(currentHeight||1));for(let p of pt)p.x=(p.x-currentBox.p1.x)*scale,p.y=(p.y-currentBox.p1.y)*scale,p.x+=p1.x,p.y+=p1.y;return this}}}
|
|
272
273
|
/**
|
|
273
274
|
* Calcola i punti di un arco passante per tre punti
|
|
274
275
|
* @param {number} segments - Numero di segmenti (punti-1)
|
|
@@ -486,7 +487,7 @@ ClipperLib.ExPolygon=function(){this.outer=null,this.holes=null},ClipperLib.JS.A
|
|
|
486
487
|
* @property {Function} inflate - Espande o contrae una forma
|
|
487
488
|
* @property {Function} unisci - Unisce più forme con gestione di fori e tagli
|
|
488
489
|
*/
|
|
489
|
-
function shapeclip(){function toclipformat(pts){let tm=pts.map((e=>({X:Math.round(1e4*e.x),Y:Math.round(1e4*e.y)})));return ensureOrientation(tm)}function fromclipformat(pts){return pts.map((e=>({x:e.X/1e4,y:e.Y/1e4})))}const ensureOrientation=poly=>ClipperLib.Clipper.Orientation(poly)?poly:poly.slice().reverse();function orientation(pt){if(!pt.length)return 0;let area=0;const n=pt.length;for(let i=0;i<n;i++){const current=pt[i],next=pt[(i+1)%n];area+=current.X*next.Y-next.X*current.Y}return area>0?1:area<0?-1:0}const _inflate=(pt,delta,cut=!1)=>{const co=new ClipperLib.ClipperOffset;co.MiterLimit=4,co.AddPath(pt,ClipperLib.JoinType.jtMiter,cut||2==pt.length?ClipperLib.EndType.etOpenButt:ClipperLib.EndType.etClosedPolygon);const solution=new ClipperLib.Paths;return co.Execute(solution,delta),solution};return{offset(shape,delta,full=!1){const co=new ClipperLib.ClipperOffset;co.MiterLimit=4,co.ArcTolerance=.25;const DD=1e4*Math.abs(delta),pshape=toclipformat(shape.pt);co.AddPath(pshape,ClipperLib.JoinType.jtMiter,ClipperLib.EndType.etOpenButt);const solution=new ClipperLib.Paths;co.Execute(solution,DD);let tm=fromclipformat(solution[0]);return full?getshape().frompt(tm):getshape().frompt(getptsoffset(shape.pt,tm,delta))},inflate(shape,delta=2,mantainorder=!1){let pshape=toclipformat(shape.pt),tm=_inflate(pshape,1e4*delta);let p2=getshape().frompt(fromclipformat(tm[0]));if(mantainorder&&shape.pt.length==p2.pt.length){p2.orient!=shape.orient&&p2.reverse();let p3=function alignByMinDist(sag1,sag2){const N=sag1.length;let bestOffset=0,minSum=1/0;for(let k=0;k<N;k++){let sum=0;for(let i=0;i<N;i++){const p=sag1[i],q=sag2[(i+k)%N],dx=p.x-q.x,dy=p.y-q.y;sum+=dx*dx+dy*dy}sum<minSum&&(minSum=sum,bestOffset=k)}return[...sag2.slice(bestOffset),...sag2.slice(0,bestOffset)]}(shape.pt,p2.pt);p2.frompt(p3)}return p2},intersecasplitter(areabase,forma1){const clipper=new ClipperLib.Clipper,pt1=[toclipformat(forma1.pt)],pt2=[toclipformat(areabase.pt)];clipper.AddPaths(pt1,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(pt2,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;let res;if(clipper.Execute(ClipperLib.ClipType.ctIntersection,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero)&&solution.length>0){const path=solution[0];if(1===orientation(path)){res=getshape().frompt(fromclipformat(path)),res.orient!=forma1.orient&&res.reverse();for(let iu=0;iu<forma1.pt.length;iu++){let p2=forma1.pt[iu],id=res.pt.findIndex((p=>Math.abs(p.x-p2.x)<.01&&Math.abs(p.y-p2.y)<.01));if(id>0){id-=iu,0!=id&&res.selezionaprimo(id);break}}}}return res},offsetpts(pts,delta=.01){const DELTA=1e4*delta;let tm=_inflate(toclipformat(pts),DELTA);if(tm&&tm.length)return fromclipformat(tm[0])},areesplitter(shapept,clipspt,useInflatedClipping=!0){if(!Array.isArray(shapept)||shapept.length<3)return;if(!clipspt||0==clipspt.length)return[shapept];const subj=new ClipperLib.Paths,clip=new ClipperLib.Paths;let shape_in=useInflatedClipping?_inflate(toclipformat(shapept),-100):[toclipformat(shapept)],clips_in=useInflatedClipping?clipspt.flatMap((c=>_inflate(toclipformat(c),100))):clipspt.map((c=>toclipformat(c)));for(let s of shape_in)subj.push(s);for(let c of clips_in)clip.push(c);const clipper=new ClipperLib.Clipper;clipper.AddPaths(subj,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clip,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;if(!clipper.Execute(ClipperLib.ClipType.ctDifference,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero))return;let res=[];for(let x of solution)if(useInflatedClipping){const restored=_inflate(x,100);for(const r of restored)1===orientation(r)&&res.push(fromclipformat(r))}else if(x.length>4&&1==orientation(x)){const cleaned=_inflate(x,-100);if(cleaned.length>0)for(let cc of cleaned){const restored=_inflate(cc,100);for(const rr of restored)1===orientation(rr)&&res.push(fromclipformat(rr))}}else 1==orientation(x)&&res.push(fromclipformat(x));return res},unisci(shapes,holes,cuts){const subj=new ClipperLib.Paths,clip=new ClipperLib.Paths;for(let hh of shapes){let h2=[toclipformat(hh.pt)];for(let h of h2)subj.push(h)}if(holes&&holes.length)for(let hh of holes){let h1=toclipformat(hh.pt);clip.push(h1)}if(cuts&&cuts.length)for(let hh of cuts){let h1=toclipformat(hh.pt),h2=_inflate(h1,1,!0);for(let h of h2)clip.push(h)}const clipper=new ClipperLib.Clipper;clipper.AddPaths(subj,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clip,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;if(clipper.Execute(ClipperLib.ClipType.ctDifference,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero)){let res=[],holes=[];for(let x of solution)if(1==orientation(x)){let yy=[x];for(let y of yy)res.push({shape:getshape().frompt(fromclipformat(y)),holes:[]})}else holes.push(getshape().frompt(fromclipformat(x)));for(let h of holes)for(let s of res)if(s.shape.pointinshape(h.pt[0])){s.holes.push(h);break}return res}return[]}}}class Vis2d{constructor(name,p1,p2){this.name=name,this.clear(p1,p2)}clear(p1,p2){return this.vec=[],this.xp1=p1||new Punto2(-10,-10),this.xp2=p2||new Punto2(100,100),this}push(x,y,rot=0){this.vec.push({type:"push",x:x,y:y,rot:rot})}pop(){this.vec.push({type:"pop"})}randomcolor(transp="100%"){return`hsl(${Math.floor(360*Math.random())}, 50%, 40%,${transp})`}addpoint(p,id=-1,color=
|
|
490
|
+
function shapeclip(){function toclipformat(pts){let tm=pts.map((e=>({X:Math.round(1e4*e.x),Y:Math.round(1e4*e.y)})));return ensureOrientation(tm)}function fromclipformat(pts){return pts.map((e=>({x:e.X/1e4,y:e.Y/1e4})))}const ensureOrientation=poly=>ClipperLib.Clipper.Orientation(poly)?poly:poly.slice().reverse();function orientation(pt){if(!pt.length)return 0;let area=0;const n=pt.length;for(let i=0;i<n;i++){const current=pt[i],next=pt[(i+1)%n];area+=current.X*next.Y-next.X*current.Y}return area>0?1:area<0?-1:0}const _inflate=(pt,delta,cut=!1)=>{const co=new ClipperLib.ClipperOffset;co.MiterLimit=4,co.AddPath(pt,ClipperLib.JoinType.jtMiter,cut||2==pt.length?ClipperLib.EndType.etOpenButt:ClipperLib.EndType.etClosedPolygon);const solution=new ClipperLib.Paths;return co.Execute(solution,delta),solution};return{offset(shape,delta,full=!1){const co=new ClipperLib.ClipperOffset;co.MiterLimit=4,co.ArcTolerance=.25;const DD=1e4*Math.abs(delta),pshape=toclipformat(shape.pt);co.AddPath(pshape,ClipperLib.JoinType.jtMiter,ClipperLib.EndType.etOpenButt);const solution=new ClipperLib.Paths;co.Execute(solution,DD);let tm=fromclipformat(solution[0]);return full?getshape().frompt(tm):getshape().frompt(getptsoffset(shape.pt,tm,delta))},inflate(shape,delta=2,mantainorder=!1,isopen=0){let pshape=toclipformat(shape.pt),tm=_inflate(pshape,1e4*delta);let p2=getshape().frompt(fromclipformat(tm[0]));if(mantainorder&&shape.pt.length==p2.pt.length){p2.orient!=shape.orient&&p2.reverse();let p3=function alignByMinDist(sag1,sag2){const N=sag1.length;let bestOffset=0,minSum=1/0;for(let k=0;k<N;k++){let sum=0;for(let i=0;i<N;i++){const p=sag1[i],q=sag2[(i+k)%N],dx=p.x-q.x,dy=p.y-q.y;sum+=dx*dx+dy*dy}sum<minSum&&(minSum=sum,bestOffset=k)}return[...sag2.slice(bestOffset),...sag2.slice(0,bestOffset)]}(shape.pt,p2.pt);if(p2.frompt(p3),isopen>0&&shape.pt.length>=3){function estendi1(sh1,sh2){let l1=sh1.segment(0).ruotata(-Math.PI/2,200,!0),l2=sh1.segment(-2).ruotata(-Math.PI/2,200),p2=sh2.segment(-2).interseca(l2),p1=sh2.segment(0).interseca(l1);p1&&(sh2.pt[0]=p1),p2&&(sh2.pt[sh2.pt.length-1]=p2)}function estendi2(sh1,sh2){let lfin=sh1.segment(-1),l2=sh2.segment(0),p1=lfin.interseca(l2);p1&&(sh2.pt[0]=p1),l2=sh2.segment(-2);let p2=lfin.interseca(l2);p2&&(sh2.pt[sh2.pt.length-1]=p2)}1==isopen?estendi1(shape,p2):estendi2(shape,p2)}}return p2},intersecasplitter(areabase,forma1){const clipper=new ClipperLib.Clipper,pt1=[toclipformat(forma1.pt)],pt2=[toclipformat(areabase.pt)];clipper.AddPaths(pt1,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(pt2,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;let res;if(clipper.Execute(ClipperLib.ClipType.ctIntersection,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero)&&solution.length>0){const path=solution[0];if(1===orientation(path)){res=getshape().frompt(fromclipformat(path)),res.orient!=forma1.orient&&res.reverse();for(let iu=0;iu<forma1.pt.length;iu++){let p2=forma1.pt[iu],id=res.pt.findIndex((p=>Math.abs(p.x-p2.x)<.01&&Math.abs(p.y-p2.y)<.01));if(id>0){id-=iu,0!=id&&res.selezionaprimo(id);break}}}}return res},offsetpts(pts,delta=.01){const DELTA=1e4*delta;let tm=_inflate(toclipformat(pts),DELTA);if(tm&&tm.length)return fromclipformat(tm[0])},areesplitter(shapept,clipspt,useInflatedClipping=!0){if(!Array.isArray(shapept)||shapept.length<3)return;if(!clipspt||0==clipspt.length)return[shapept];const subj=new ClipperLib.Paths,clip=new ClipperLib.Paths;let shape_in=useInflatedClipping?_inflate(toclipformat(shapept),-100):[toclipformat(shapept)],clips_in=useInflatedClipping?clipspt.flatMap((c=>_inflate(toclipformat(c),100))):clipspt.map((c=>toclipformat(c)));for(let s of shape_in)subj.push(s);for(let c of clips_in)clip.push(c);const clipper=new ClipperLib.Clipper;clipper.AddPaths(subj,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clip,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;if(!clipper.Execute(ClipperLib.ClipType.ctDifference,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero))return;let res=[];for(let x of solution)if(useInflatedClipping){const restored=_inflate(x,100);for(const r of restored)1===orientation(r)&&res.push(fromclipformat(r))}else if(x.length>4&&1==orientation(x)){const cleaned=_inflate(x,-100);if(cleaned.length>0)for(let cc of cleaned){const restored=_inflate(cc,100);for(const rr of restored)1===orientation(rr)&&res.push(fromclipformat(rr))}}else 1==orientation(x)&&res.push(fromclipformat(x));return res},unisci(shapes,holes,cuts){const subj=new ClipperLib.Paths,clip=new ClipperLib.Paths;for(let hh of shapes){let h2=[toclipformat(hh.pt)];for(let h of h2)subj.push(h)}if(holes&&holes.length)for(let hh of holes){let h1=toclipformat(hh.pt);clip.push(h1)}if(cuts&&cuts.length)for(let hh of cuts){let h1=toclipformat(hh.pt),h2=_inflate(h1,1,!0);for(let h of h2)clip.push(h)}const clipper=new ClipperLib.Clipper;clipper.AddPaths(subj,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clip,ClipperLib.PolyType.ptClip,!0);const solution=new ClipperLib.Paths;if(clipper.Execute(ClipperLib.ClipType.ctDifference,solution,ClipperLib.PolyFillType.pftNonZero,ClipperLib.PolyFillType.pftNonZero)){let res=[],holes=[];for(let x of solution)if(1==orientation(x)){let yy=[x];for(let y of yy)res.push({shape:getshape().frompt(fromclipformat(y)),holes:[]})}else holes.push(getshape().frompt(fromclipformat(x)));for(let h of holes)for(let s of res)if(s.shape.pointinshape(h.pt[0])){s.holes.push(h);break}return res}return[]}}}class Vis2d{constructor(name,p1,p2){this.name=name,this.clear(p1,p2)}clear(p1,p2){return this.vec=[],this.xp1=p1||new Punto2(-10,-10),this.xp2=p2||new Punto2(100,100),this}push(x,y,rot=0){this.vec.push({type:"push",x:x,y:y,rot:rot})}pop(){this.vec.push({type:"pop"})}randomcolor(transp="100%"){return`hsl(${Math.floor(360*Math.random())}, 50%, 40%,${transp})`}addpoint(p,id=-1,color="red",spessore=8){return p&&this.vec.push({type:"point",p:p,id:id,color:color,spessore:spessore}),this}addline(l,id=-1,color=void 0,spessore=1){return l&&this.vec.push({type:"line",l:l,id:id,color:color,spessore:spessore}),this}addrect(l,id=-1,color=void 0,spessore=1){return l&&this.vec.push({type:"rect",l:l,id:id,color:color,spessore:spessore}),this}addrecta(l,id=-1,color=void 0){return l&&this.vec.push({type:"recta",l:l,id:id,color:color,spessore:0}),this}addshape(s,color=void 0,spessore=1){return s&&this.vec.push({type:"shape",s:s,color:color||this.randomcolor(),spessore:spessore}),this}addshapelin(s,color=void 0,spessore=1){return s&&this.vec.push({type:"shapelin",s:s,color:color||this.randomcolor(),spessore:spessore}),this}addarea(s,color=void 0){return s&&this.vec.push({type:"area",s:s,color:color||this.randomcolor()}),this}addoffset(x,y){return this.vec.push({type:"offset",x:x||0,y:y||0}),this}}
|
|
490
491
|
/**
|
|
491
492
|
* Genera segmenti basati su intervalli e punti di interruzione
|
|
492
493
|
* @param {Array<{a: number, b: number}>} t1 - Array di oggetti che rappresentano intervalli con coordinate a e b
|
|
@@ -494,7 +495,7 @@ function shapeclip(){function toclipformat(pts){let tm=pts.map((e=>({X:Math.roun
|
|
|
494
495
|
* @param {boolean} [interna=false] - Se true, usa i bordi interni degli intervalli
|
|
495
496
|
* @param {boolean} [allbreak=false] - Se true, considera ogni punto degli intervalli come una rottura
|
|
496
497
|
* @returns {Array<{a: number, b: number}>} Array di segmenti generati
|
|
497
|
-
*/function generatesegments(t1,t2,interna=!1,allbreak=!1){let t3=[];if(t1?.length>=2){if(allbreak){let tm=[];for(let t of t1)tm.push({a:t.a,b:t.a}),t.a!=t.b&&tm.push({a:t.b,b:t.b});t1=tm}if(t1=t1.sort(((a,b)=>a.a-b.a)),t2?.length){let j=0;for(let i=1;i<t1.length;i++){const ε=1e-6;t2.find((e=>e>t1[i-1].b+ε&&e<t1[i].a-ε))&&(i-1>j&&(interna?t3.push({a:t1[j].b,b:t1[i-1].a}):t3.push({a:t1[j].a,b:t1[i-1].b})),j=i)}j<t1.length-1&&(interna?t3.push({a:t1[j].b,b:t1[t1.length-1].a}):t3.push({a:t1[j].a,b:t1[t1.length-1].b}))}else t3.push({a:t1[0].b,b:t1[t1.length-1].a})}return t3}function bordi(ff){function getbordo(b1,b2){let b=b1??b2??{s:0};return"number"==typeof b?{s:b}:"number"==typeof b?.s?b:{s:0}}let bt,bb,bl,br;return"a"==ff.tipo?bt=bb=bl=br=getbordo(ff.bordo,ff.bordo):(bt=getbordo(ff.bt,ff.bordo),bb=getbordo(ff.bb,ff.bordo),bl=getbordo(ff.bl,ff.bordo),br=getbordo(ff.br,ff.bordo)),{bt:bt,bb:bb,bl:bl,br:br}}function internalshape(ff,shape){let shape2,CLP=shapeclip(),{bt:bt,bb:bb,bl:bl,br:br}=bordi(ff);if(bt==br&&bb==br&&bl==br||"a"==ff.tipo)shape2=CLP.inflate(shape,-bt.s,!0);else{let n=shape.pt.length,ll=[];for(let i=0;i<n;i++){let ofs=0==i?bl.s:i==n-2?br.s:i==n-1?bb.s:bt.s;ll.push(shape.segment(i).offset(-ofs))}let pts=[];for(let i=0;i<n;i++){let j=(i+n-1)%n,p=ll[i].
|
|
498
|
+
*/function generatesegments(t1,t2,interna=!1,allbreak=!1){let t3=[];if(t1?.length>=2){if(allbreak){let tm=[];for(let t of t1)tm.push({a:t.a,b:t.a}),t.a!=t.b&&tm.push({a:t.b,b:t.b});t1=tm}if(t1=t1.sort(((a,b)=>a.a-b.a)),t2?.length){let j=0;for(let i=1;i<t1.length;i++){const ε=1e-6;t2.find((e=>e>t1[i-1].b+ε&&e<t1[i].a-ε))&&(i-1>j&&(interna?t3.push({a:t1[j].b,b:t1[i-1].a}):t3.push({a:t1[j].a,b:t1[i-1].b})),j=i)}j<t1.length-1&&(interna?t3.push({a:t1[j].b,b:t1[t1.length-1].a}):t3.push({a:t1[j].a,b:t1[t1.length-1].b}))}else t3.push({a:t1[0].b,b:t1[t1.length-1].a})}return t3}function bordi(ff){function getbordo(b1,b2){let b=b1??b2??{s:0};return"number"==typeof b?{s:b}:"number"==typeof b?.s?b:{s:0}}let bt,bb,bl,br;return"a"==ff.tipo?bt=bb=bl=br=getbordo(ff.bordo,ff.bordo):(bt=getbordo(ff.bt,ff.bordo),bb=getbordo(ff.bb,ff.bordo),bl=getbordo(ff.bl,ff.bordo),br=getbordo(ff.br,ff.bordo)),{bt:bt,bb:bb,bl:bl,br:br}}function internalshape(ff,shape){let shape2,CLP=shapeclip(),{bt:bt,bb:bb,bl:bl,br:br}=bordi(ff);if(bt==br&&bb==br&&bl==br||"a"==ff.tipo)shape2=CLP.inflate(shape,-bt.s,!0);else{let n=shape.pt.length,ll=[];for(let i=0;i<n;i++){let ofs=0==i?bl.s:i==n-2?br.s:i==n-1?bb.s:bt.s;ll.push(shape.segment(i).offset(-ofs))}let pts=[];for(let i=0;i<n;i++){let j=(i+n-1)%n,p=ll[i].interseca(ll[j]);p||(p=shape.pt[i]),pts.push(p)}shape2=getshape().frompt(pts)}return shape2}const tipi={i:"inclinato",a:"arco",d:"diagonali",s:"smussato",x:"normale"},priorita={v:"verticale",h:"orizzontale"},tagli={d:"diagonale",v:"verticale",h:"orizzontale",o:"orizzontale"};function ordinabase(hh,dd,minvano,b1,b2,tipo){let d1=[];if(hh){for(var h of hh){let x=0;switch(h.tipo){case"d-":x=dd-h.p;break;case"p":x=dd*h.p/100;break;case"p-":x=dd*(100-h.p)/100;break;default:x=h.p}let sp=h.sps||0;if(sp&&"c"==h.align?x-=sp/2:sp&&"r"==h.align&&(x-=sp),x=Math.round(10*x)/10,x>b1&&x<dd-b2){let cuts=[];h.cuttings&&h.cuttings.length&&h.cuttings.forEach((c=>{cuts.push(c<0?dd+c:c)})),d1.push({id:h.id,x:x,sp:sp,cuts:cuts,des:h.des})}}d1.sort(((a,b)=>a.x-b.x))}let d2=[],p0=b1;"a"==tipo&&(dd*=1.3);for(let i=0;i<d1.length;i++){let d=d1[i];d.x>=p0+minvano&&d.x+d.sp<=dd-b2-minvano&&(d.min=p0+minvano,d.max=dd-b2-minvano,d2.length>0&&(d2[d2.length-1].max=d.x-minvano),d2.push(d),p0=d.x+d.sp)}let d3=[];d3.push({a:b1,b:b1});for(let d of d2)d3.push({a:d.x,b:d.x+d.sp});return d3.push({a:dd-b2,b:dd-b2}),{dati:d2,punti:d3}}const tipocut={d:"dist. positiva","d-":"dist. negativa",p:"perc. positiva","p-":"perc negativa"},tipoalign={l:"left",c:"center",r:"right"};function newcount(ff){return ff.countid++,ff.countid}function addtaglio(ff,dir,tipodim,dim,sps,des,align="c",cuts=[]){return{dir:dir,id:newcount(ff),tipo:tipocut[tipodim]?tipodim:"d",align:tipoalign[align]?align:"c",p:dim,sps:sps,des:des,cuttings:cuts||[]}}function pushlineare(ff,type,des,l0,l1,id=-1,shapecontorno=void 0,areas){let tm;if(id<0&&(id=newcount(ff)),"l"==type)Array.isArray(areas)&&areas.push([l0.p1,l0.p2]);else{let ptx=[l0.p1,l0.p2,l1.p2,l1.p1];Array.isArray(areas)&&areas.push(ptx);let s1=getshape().frompt(ptx);if(shapecontorno?.pt&&"x"!=ff.tipo&&(s1.orient!=shapecontorno.orient&&s1.reverse(),s1=shapeclip().intersecasplitter(shapecontorno,s1)),s1){4==s1.pt.length&&(l0.p1=s1.pt[0],l0.p2=s1.pt[1],l1.p1=s1.pt[3],l1.p2=s1.pt[2]);let info=l0.infoquad(l1);if(info&&info.distanza){let s2=s1.clone();(info.sx||info.sy)&&s2.move(-info.sx||0,-info.sy||0),info.angle&&s2.rotate(-info.angle||0),tm={id:id,type:type,des:des,shape:s2.pt,info:info},ff.dati.push(tm)}}}return tm}function pushshape(ff,type,des,shape,info,id=-1){let tm;return id<0&&(id=newcount(ff)),info||(info={}),info={isshape:!0},shape?.pt&&(tm={id:id,type:type,des:des,shape:shape.pt,info:info},ff.dati.push(tm)),tm}function creabordi(ff,shape,shape2){let l1,n=shape.pt.length,draws=[];function addlineare(type,des,l0,l1){let tm=pushlineare(ff,type,des,l0,l1);tm?.shape&&draws.push({pt:tm.shape,type:type,sx:tm.info.sx,sy:tm.info.sy,rot:tm.info.angle})}if("a"!=ff.tipo)for(let i=1;i<n-2;i++)addlineare("bt","sopra",shape.segment(i),shape2.segment(i));else{let p1=[...shape.pt].slice(1,-1),p2=[...shape2.pt].slice(1,-1).reverse(),sa=getshape().frompt([...p1,...p2]);pushshape(ff,"bt","sopra",sa,{isarco:!0}),draws.push({pt:sa.pt,type:"bs"})}switch(ff.taglio){case"o":case"h":{let p1=shape2.segment(n-1).interseca(shape.segment(0)),p2=shape2.segment(n-1).interseca(shape.segment(n-2));l1=new Linea2(p1,shape.pt[1]),addlineare("bl","sx",l1,shape2.segment(0)),l1=new Linea2(shape.pt[n-2],p2),addlineare("br","dx",l1,shape2.segment(n-2)),l1=new Linea2(p2,p1),addlineare("bb","sotto",shape.segment(n-1),l1);break}case"v":{let p1=shape2.segment(0).interseca(shape.segment(n-1)),p2=shape2.segment(n-2).interseca(shape.segment(n-1));l1=new Linea2(p1,shape2.pt[1]),addlineare("bl","sx",shape.segment(0),l1),l1=new Linea2(shape2.pt[n-2],p2),addlineare("br","sx",shape.segment(n-2),l1),l1=new Linea2(p2,p1),addlineare("bb","sotto",l1,shape2.segment(n-1));break}default:addlineare("bl","sx",shape.segment(0),shape2.segment(0)),addlineare("br","dx",shape.segment(n-2),shape2.segment(n-2)),addlineare("bb","sotto",shape.segment(n-1),shape2.segment(n-1))}return draws}var SP=Object.freeze({__proto__:null,addhoriz:function addhoriz(ff,tipodim,dim,sps,des,align,cuts){Array.isArray(align)&&(cuts=align,align="c");let tm=addtaglio(ff,"h",tipodim,dim,sps,des,align,cuts);ff.horiz.push(tm)},addvert:function addvert(ff,tipodim,dim,sps,des,align,cuts){Array.isArray(align)&&(cuts=align,align="c");let tm=addtaglio(ff,"v",tipodim,dim,sps,des,align,cuts);ff.vert.push(tm)},bordi:bordi,calcoladivisioni:
|
|
498
499
|
/**
|
|
499
500
|
* Ordina e calcola le posizioni di taglio lungo una dimensione, gestendo bordi e spazi minimi
|
|
500
501
|
* @param {Array<Object>} hh - Array di oggetti che definiscono i tagli
|
|
@@ -505,4 +506,4 @@ function shapeclip(){function toclipformat(pts){let tm=pts.map((e=>({X:Math.roun
|
|
|
505
506
|
* - dati: Array di oggetti con le posizioni elaborate dei tagli
|
|
506
507
|
* - punti: Array di oggetti {a,b} che definiscono inizio e fine di ogni segmento
|
|
507
508
|
*/
|
|
508
|
-
function calcoladivisioni(ff,shape,shape2){let draws=creabordi(ff,shape,shape2)||[],areas=[],{x:dx,y:dy,horiz:horiz,vert:vert,tipo:tipo,priority:priority,minvano:minvano,minvanox:minvanox,minvanoy:minvanoy}=ff,{bl:bl,br:br,bt:bt,bb:bb}=bordi(ff);minvanox=minvanox||minvano||50,minvanoy=minvanoy||minvano||50;let{dati:h1,punti:ph}=ordinabase(horiz,dy,minvanoy,bb.s,bt.s,tipo),{dati:v1,punti:pv}=ordinabase(vert,dx,minvanox,bl.s,br.s);function adddatilin(type,des,l0,l1,id){let tm=pushlineare(ff,type,des,l0,l1,id,shape2,areas);tm?.shape&&draws.push({pt:tm.shape,type:type,sx:tm.info.sx,sy:tm.info.sy,rot:tm.info.angle})}function isinseg(segs,v){return!!segs.find((e=>e.a<=v&&e.b>=v))}for(var h of(v1.forEach(((v,i)=>{v.segs=generatesegments(ph,v.cuts,!0),v.segs.forEach(((s,j)=>{let l0=new Linea2({x:v.x,y:s.a},{x:v.x,y:s.b}),l1=new Linea2({x:v.x+v.sp,y:s.a},{x:v.x+v.sp,y:s.b});adddatilin(v.sp?"v":"l","vert",l0,l1,v.id)}))})),h1)){let cuts=[...h.cuts],pv1=[...pv];for(var v of v1)pv1.push({a:v.x,b:v.x+v.sp}),isinseg(v.segs,h.x+h.sp/2)&&cuts.push(v.x+v.sp/2);h.segs=generatesegments(pv1,cuts,!0,!0);for(let s of h.segs){let l1=new Linea2({x:s.b,y:h.x+h.sp},{x:s.a,y:h.x+h.sp}),l0=new Linea2({x:s.b,y:h.x},{x:s.a,y:h.x});adddatilin(h.sp?"h":"l","oriz",l0,l1,h.id)}}let res=shapeclip().areesplitter(shape2.pt,areas);for(let d of res){let s=getshape().frompt(d),{p1:p1,width:width,height:height,isrect:isrect}=s.dims(),ix=s.pt.findIndex((p=>Math.abs(p.x-p1.x)<.001&&Math.abs(p.y-p1.y)<.001));ix>0&&s.selezionaprimo(ix),s.pt.length&&(s.move(-p1.x,-p1.y),1==s.orient&&s.reverse()),ff.dati.push({id:-1,type:"a",des:"_",shape:isrect?null:s.pt,info:{isrect:isrect?1:0,sx:p1.x,sy:p1.y,rot:0,width:width,height:height}}),draws.push({pt:s.pt,sx:p1.x,sy:p1.y,rot:0,type:isrect?"a":"as"})}return{ff:ff,h1:h1,ph:ph,v1:v1,pv:pv,draws:draws,areas:areas}},creabordi:creabordi,create:function create(x,y,bordo,options){options||(options={});let{minvano:minvano,priority:priority,taglio:taglio,tagliov:tagliov,tipo:tipo,h1:h1,h2:h2,d1:d1,d2:d2,l1:l1,l2:l2,x1:x1,x2:x2,y1:y1,y2:y2}=options;minvano||(minvano=50);let ff={x:x||1e3,y:y||1e3,bordo:bordo||0,minvano:minvano||50,priority:priorita[priority]?priority:"v",taglio:tagli[taglio]?taglio:"d",tagliov:tagli[tagliov]?tagliov:"d",tipo:tipi[tipo]?tipo:"x",h1:h1||y1||0,h2:h2||y2||0,l1:l1||d1||x1||0,l2:l2||d2||x2||0,vert:[],horiz:[],dati:[],countid:1e3};return delete options.x1,delete options.x2,delete options.d1,delete options.d2,delete options.y1,delete options.y2,ff={...options,...ff},ff},findid:function findid(ff,id){let f=ff.vert.find((e=>e.id==id));return f||(f=ff.horiz.find((e=>e.id==id))),{f:f}},generatesegments:generatesegments,internalshape:internalshape,makeshape:function makeshape(ff){let shape,{x:x,y:y,tipo:tipo,h1:h1,h2:h2,l1:l1,l2:l2}=ff;if(x>0&&y>0){let pts=[0,0];switch(tipo){case"i":pts.push(0,h1>0&&h1<y?y-h1:y),pts.push(x,h2>0&&h2<y&&h2!=h1?y-h2:y),pts.push(x,0),shape=getshape().fromvec(pts);break;case"a":if(h2=h2||h1||0,y-h1>=y-x/2&&y-h1<=y&&y-h2>=y-x/2&&y-h2<=y){let str=`0;0;a30;0;${y-h1};${x/2};${y};${x};${y-h2};${x};0`.replaceAll(",",".");shape=getshape().fromstr(str)}else pts.push(x,y,0,y),shape=getshape().fromvec(pts);break;case"s":case"d":l1=l1||0,l2=l2||0,l1&&l1<x&&h1>0&&h1<y?pts.push(0,y-h1,l1,y):pts.push(0,y),l2&&l2+l1<x&&h2>0&&h2<y?pts.push(x-l2,y,x,y-h2):0==l2&&l1>0&&l1<x&&h2>0&&h2<y?pts.push(x,y-h2):(l2=0,pts.push(x,y)),pts.push(x,0),shape=getshape().fromvec(pts);break;default:pts.push(0,y,x,y,x,0),shape=getshape().fromvec(pts)}}return ff.dati=[],{shape:shape,internalshape:internalshape(ff,shape)}},priorita:priorita,pushlineare:pushlineare,pushshape:pushshape,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 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})}});return isfnreload&&"function"==typeof fnreload&&await fnreload(),{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")}function clean(k,locase=!1){return locase?(k||"").trim().toLowerCase():(k||"").trim()}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});let params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:console.log,Math:Math,clean:clean,SP:SP,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects};const fn=new Function(...Object.keys(params),`try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...Object.values(params))}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}export{Linea2,Matrix3D,PIF,Punto2,SP,Vis2d,angle2vec,angle3point,clamp,clean,evalcustomfunction,getdumpmacro,getnodebyid,getprojectkeys,getptsoffset,getshape,getsubrules,hash,isfn,ismacro,normal2,raccordabezier,shapeclip,valutagrafica};
|
|
509
|
+
function calcoladivisioni(ff,shape,shape2){let draws=creabordi(ff,shape,shape2)||[],areas=[],{x:dx,y:dy,horiz:horiz,vert:vert,tipo:tipo,priority:priority,minvano:minvano,minvanox:minvanox,minvanoy:minvanoy}=ff,{bl:bl,br:br,bt:bt,bb:bb}=bordi(ff);minvanox=minvanox||minvano||50,minvanoy=minvanoy||minvano||50;let{dati:h1,punti:ph}=ordinabase(horiz,dy,minvanoy,bb.s,bt.s,tipo),{dati:v1,punti:pv}=ordinabase(vert,dx,minvanox,bl.s,br.s);function adddatilin(type,des,l0,l1,id){let tm=pushlineare(ff,type,des,l0,l1,id,shape2,areas);tm?.shape&&draws.push({pt:tm.shape,type:type,sx:tm.info.sx,sy:tm.info.sy,rot:tm.info.angle})}function isinseg(segs,v){return!!segs.find((e=>e.a<=v&&e.b>=v))}for(var h of(v1.forEach(((v,i)=>{v.segs=generatesegments(ph,v.cuts,!0),v.segs.forEach(((s,j)=>{let l0=new Linea2({x:v.x,y:s.a},{x:v.x,y:s.b}),l1=new Linea2({x:v.x+v.sp,y:s.a},{x:v.x+v.sp,y:s.b});adddatilin(v.sp?"v":"l","vert",l0,l1,v.id)}))})),h1)){let cuts=[...h.cuts],pv1=[...pv];for(var v of v1)pv1.push({a:v.x,b:v.x+v.sp}),isinseg(v.segs,h.x+h.sp/2)&&cuts.push(v.x+v.sp/2);h.segs=generatesegments(pv1,cuts,!0,!0);for(let s of h.segs){let l1=new Linea2({x:s.b,y:h.x+h.sp},{x:s.a,y:h.x+h.sp}),l0=new Linea2({x:s.b,y:h.x},{x:s.a,y:h.x});adddatilin(h.sp?"h":"l","oriz",l0,l1,h.id)}}let res=shapeclip().areesplitter(shape2.pt,areas);for(let d of res){let s=getshape().frompt(d),{p1:p1,width:width,height:height,isrect:isrect}=s.dims(),ix=s.pt.findIndex((p=>Math.abs(p.x-p1.x)<.001&&Math.abs(p.y-p1.y)<.001));ix>0&&s.selezionaprimo(ix),s.pt.length&&(s.move(-p1.x,-p1.y),1==s.orient&&s.reverse()),ff.dati.push({id:-1,type:"a",des:"_",shape:isrect?null:s.pt,info:{isrect:isrect?1:0,sx:p1.x,sy:p1.y,rot:0,width:width,height:height}}),draws.push({pt:s.pt,sx:p1.x,sy:p1.y,rot:0,type:isrect?"a":"as"})}return{ff:ff,h1:h1,ph:ph,v1:v1,pv:pv,draws:draws,areas:areas}},creabordi:creabordi,create:function create(x,y,bordo,options){options||(options={});let{minvano:minvano,priority:priority,taglio:taglio,tagliov:tagliov,tipo:tipo,h1:h1,h2:h2,d1:d1,d2:d2,l1:l1,l2:l2,x1:x1,x2:x2,y1:y1,y2:y2}=options;minvano||(minvano=50);let ff={x:x||1e3,y:y||1e3,bordo:bordo||0,minvano:minvano||50,priority:priorita[priority]?priority:"v",taglio:tagli[taglio]?taglio:"d",tagliov:tagli[tagliov]?tagliov:"d",tipo:tipi[tipo]?tipo:"x",h1:h1||y1||0,h2:h2||y2||0,l1:l1||d1||x1||0,l2:l2||d2||x2||0,vert:[],horiz:[],dati:[],countid:1e3};return delete options.x1,delete options.x2,delete options.d1,delete options.d2,delete options.y1,delete options.y2,ff={...options,...ff},ff},findid:function findid(ff,id){let f=ff.vert.find((e=>e.id==id));return f||(f=ff.horiz.find((e=>e.id==id))),{f:f}},generatesegments:generatesegments,internalshape:internalshape,makeshape:function makeshape(ff){let shape,{x:x,y:y,tipo:tipo,h1:h1,h2:h2,l1:l1,l2:l2}=ff;if(x>0&&y>0){let pts=[0,0];switch(tipo){case"i":pts.push(0,h1>0&&h1<y?y-h1:y),pts.push(x,h2>0&&h2<y&&h2!=h1?y-h2:y),pts.push(x,0),shape=getshape().fromvec(pts);break;case"a":if(h2=h2||h1||0,y-h1>=y-x/2&&y-h1<=y&&y-h2>=y-x/2&&y-h2<=y){let str=`0;0;a30;0;${y-h1};${x/2};${y};${x};${y-h2};${x};0`.replaceAll(",",".");shape=getshape().fromstr(str)}else pts.push(x,y,0,y),shape=getshape().fromvec(pts);break;case"s":case"d":l1=l1||0,l2=l2||0,l1&&l1<x&&h1>0&&h1<y?pts.push(0,y-h1,l1,y):pts.push(0,y),l2&&l2+l1<x&&h2>0&&h2<y?pts.push(x-l2,y,x,y-h2):0==l2&&l1>0&&l1<x&&h2>0&&h2<y?pts.push(x,y-h2):(l2=0,pts.push(x,y)),pts.push(x,0),shape=getshape().fromvec(pts);break;default:pts.push(0,y,x,y,x,0),shape=getshape().fromvec(pts)}}return ff.dati=[],{shape:shape,internalshape:internalshape(ff,shape)}},priorita:priorita,pushlineare:pushlineare,pushshape:pushshape,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 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})}});return isfnreload&&"function"==typeof fnreload&&await fnreload(),{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")}function clean(k,locase=!1){return locase?(k||"").trim().toLowerCase():(k||"").trim()}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}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});let params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:console.log,Math:Math,clean:clean,SP:SP,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects};const fn=new Function(...Object.keys(params),`try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...Object.values(params))}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}export{Linea2,Matrix3D,PIF,Punto2,SP,TODEG,TORAD,Vis2d,angle2vec,angle3point,clamp,clean,evalcustomfunction,getdumpmacro,getnodebyid,getprojectkeys,getptsoffset,getshape,getsubrules,hash,isfn,ismacro,normal2,raccordabezier,shapeclip,valutagrafica};
|
package/bin/markcad3d.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as THREE from"three";import{PIF,clean,hash,getshape,raccordabezier}from"#markuno_cad";export{clamp}from"#markuno_cad";const SIDE=THREE.FrontSide;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}=pos;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)}return tm}function edgesfromgeometry(g1,layer=30){return getlinesgeom(new THREE.EdgesGeometry(g1,20),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}
|
|
1
|
+
import*as THREE from"three";import{PIF,clean as clean$1,hash,getshape,raccordabezier}from"#markuno_cad";export{clamp}from"#markuno_cad";const SIDE=THREE.FrontSide;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}=pos;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)}return tm}function edgesfromgeometry(g1,layer=30){return getlinesgeom(new THREE.EdgesGeometry(g1,20),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}
|
|
2
2
|
/**
|
|
3
3
|
* Crea una linea 3D
|
|
4
4
|
* @param {Object} l - Oggetto contenente punti p1 e p2
|
|
@@ -21,7 +21,7 @@ import*as THREE from"three";import{PIF,clean,hash,getshape,raccordabezier}from"#
|
|
|
21
21
|
* @param {Object} movimento - Istanza della classe MovimentoBase o derivata.
|
|
22
22
|
* @returns {THREE.Group} - Nuovo gruppo contenitore con pivot.
|
|
23
23
|
*/
|
|
24
|
-
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}
|
|
24
|
+
function addmovpivot(gcad,grp,movimento,op={},x=0,y=0,z=0){if(movimento=clean$1(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}
|
|
25
25
|
/**
|
|
26
26
|
* Crea un gestore di movimento per animare oggetti 3D.
|
|
27
27
|
* @param {string} key - Chiave identificativa del movimento
|
|
@@ -45,7 +45,7 @@ function addmovpivot(gcad,grp,movimento,op={},x=0,y=0,z=0){if(movimento=clean(mo
|
|
|
45
45
|
* @property {string} key - Chiave del movimento
|
|
46
46
|
* @property {function} step - Esegue un passo dell'animazione
|
|
47
47
|
* @property {function} reset - Resetta l'oggetto alla posizione iniziale
|
|
48
|
-
*/function getmovimento(key,gtimeline=[]){let totale=0,timeline=[];const _cleartimeline=()=>{timeline=[],totale=0},_add=(t,op={})=>{t&&timeline.push({...op,time:t}),totale=timeline.reduce(((t,e)=>t+(e.time||0)),0)};_cleartimeline(),gtimeline&>imeline.length&>imeline.forEach((e=>_add(e.time,e)));const _resetmov=grp=>{const{mov:mov}=grp?.userData||{};mov&&(mov.inmov=!1,grp.position.set(0,0,0),grp.scale.set(1,1,1),grp.rotation.set(0,0,0))};return{get tline(){return totale},clear:_cleartimeline,add:_add,key:key,step:(grp,callback)=>{if(!grp||!grp.userData?.mov||!totale)return;const{mov:mov}=grp.userData;if(!mov.inmov)return;let dt=mov.dt-mov.dtstart;if(mov.ripeti)dt%=totale;else if(dt>totale)return void _resetmov(grp);let x=0,y=0,z=0,ax=0,ay=0,az=0,sx=1,sy=1,sz=1,t=null,accumTime=0;for(let step of timeline){if(accumTime+=step.time,dt<accumTime){const c=step.time>0?(dt-(accumTime-step.time))/step.time:1,_calc=(f,def=0)=>"function"==typeof f?f(mov)*c:(f||def)*c;x+=_calc(step.x),y+=_calc(step.y),z+=_calc(step.z),sx*=1+_calc(step.sx??step.s,0),sy*=1+_calc(step.sy??step.s,0),sz*=1+_calc(step.sz??step.s,0),ax+=_calc(step.ax)*PIF,ay+=_calc(step.ay)*PIF,az+=_calc(step.az)*PIF,void 0!==step.t&&(t="function"==typeof step.t?step.t(mov)*c:step.t*c);break}{const _calc=(f,def=0)=>"function"==typeof f?f(mov):f||def;x+=_calc(step.x),y+=_calc(step.y),z+=_calc(step.z),sx*=1+_calc(step.sx??step.s,0),sy*=1+_calc(step.sy??step.s,0),sz*=1+_calc(step.sz??step.s,0),ax+=_calc(step.ax)*PIF,ay+=_calc(step.ay)*PIF,az+=_calc(step.az)*PIF,void 0!==step.t&&(t="function"==typeof step.t?step.t(mov):step.t)}}grp.position.set(x,y,z),grp.scale.set(sx,sy,sz),grp.rotation.set(ax,ay,az),null!==t&&grp.traverse((obj=>{if(obj.material){(Array.isArray(obj.material)?obj.material:[obj.material]).forEach((mat=>{mat.transparent&&(mat.opacity=1-t)}))}})),callback&&callback(grp,dt)},reset:_resetmov}}let globalLabelCanvas=null,globalLabelContext=null;
|
|
48
|
+
*/function getmovimento(key,gtimeline=[]){let totale=0,timeline=[];const _cleartimeline=()=>{timeline=[],totale=0},_add=(t,op={})=>{t&&timeline.push({...op,time:t}),totale=timeline.reduce(((t,e)=>t+(e.time||0)),0)};_cleartimeline(),gtimeline&>imeline.length&>imeline.forEach((e=>_add(e.time,e)));const _resetmov=grp=>{const{mov:mov}=grp?.userData||{};mov&&(mov.inmov=!1,grp.position.set(0,0,0),grp.scale.set(1,1,1),grp.rotation.set(0,0,0))};return{get tline(){return totale},clear:_cleartimeline,add:_add,key:key,step:(grp,callback)=>{if(!grp||!grp.userData?.mov||!totale)return;const{mov:mov}=grp.userData;if(!mov.inmov)return;let dt=mov.dt-mov.dtstart;if(mov.ripeti)dt%=totale;else if(dt>totale)return void _resetmov(grp);let x=0,y=0,z=0,ax=0,ay=0,az=0,sx=1,sy=1,sz=1,t=null,accumTime=0;for(let step of timeline){if(accumTime+=step.time,dt<accumTime){const c=step.time>0?(dt-(accumTime-step.time))/step.time:1,_calc=(f,def=0)=>"function"==typeof f?f(mov)*c:(f||def)*c;x+=_calc(step.x),y+=_calc(step.y),z+=_calc(step.z),sx*=1+_calc(step.sx??step.s,0),sy*=1+_calc(step.sy??step.s,0),sz*=1+_calc(step.sz??step.s,0),ax+=_calc(step.ax)*PIF,ay+=_calc(step.ay)*PIF,az+=_calc(step.az)*PIF,void 0!==step.t&&(t="function"==typeof step.t?step.t(mov)*c:step.t*c);break}{const _calc=(f,def=0)=>"function"==typeof f?f(mov):f||def;x+=_calc(step.x),y+=_calc(step.y),z+=_calc(step.z),sx*=1+_calc(step.sx??step.s,0),sy*=1+_calc(step.sy??step.s,0),sz*=1+_calc(step.sz??step.s,0),ax+=_calc(step.ax)*PIF,ay+=_calc(step.ay)*PIF,az+=_calc(step.az)*PIF,void 0!==step.t&&(t="function"==typeof step.t?step.t(mov):step.t)}}grp.position.set(x,y,z),grp.scale.set(sx,sy,sz),grp.rotation.set(ax,ay,az),null!==t&&grp.traverse((obj=>{if(obj.material){(Array.isArray(obj.material)?obj.material:[obj.material]).forEach((mat=>{mat.transparent&&(mat.opacity=1-t)}))}})),callback&&callback(grp,dt)},reset:_resetmov}}function tasklav(x,y,z,op,ids,faces){"string"==typeof ids?ids=getcolonne(clean(ids)):Array.isArray(ids)||(ids=null),"string"==typeof faces?faces=getcolonne(clean(faces)):Array.isArray(faces)||(faces=null),ids&&ids.lentgh&&(ids=ids.map((e=>clean(e,!0))));const emitter=new THREE.Object3D;return emitter.position.set(x,y,z),emitter.userData={emitter:!0,op:op||{},ids:ids,faces:faces},emitter}function taskpannello(px,py,pz,x,y,z,op={},tipo){tipo=clean(tipo,!0),"object"==typeof op&&null!==op||(op={});const receiver=new THREE.Object3D;return receiver.position.set(px+x/2,py+y/2,pz+z/2),receiver.userData={receiver:!0,x:x,y:y,z:z,op:op,tipo:tipo},receiver}function calcolatasks(scena){function boxBoxIntersects(pos,l,x,y,z){return pos.x+l>-x/2&&pos.x-l<x/2&&pos.y+l>-y/2&&pos.y-l<y/2&&pos.z+l>-z/2&&pos.z-l<z/2}function getFacceToccate(pos,sogliafaccia,x,y,z){const facce=[];return Math.abs(pos.x- -x/2)<sogliafaccia&&facce.push("left"),Math.abs(pos.x-x/2)<sogliafaccia&&facce.push("right"),Math.abs(pos.y- -y/2)<sogliafaccia&&facce.push("bottom"),Math.abs(pos.y-y/2)<sogliafaccia&&facce.push("top"),Math.abs(pos.z- -z/2)<sogliafaccia&&facce.push("back"),Math.abs(pos.z-z/2)<sogliafaccia&&facce.push("front"),facce}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);const tasks=[];for(const receiver of receivers){const{x:x,y:y,z:z,op:op,tipo:tipo}=receiver.userData,id=op?.id??null,lavs=[];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 posWorld=new THREE.Vector3;emitter.getWorldPosition(posWorld);const posLocal=receiver.worldToLocal(posWorld.clone());if(!boxBoxIntersects(posLocal,emitter.userData.op?.l??0,x,y,z))continue;const facceToccate=getFacceToccate(posLocal,emitter.userData.op?.soglia??2,x,y,z),facesValid=emitter.userData.faces;Array.isArray(facesValid)&&facesValid.length>0&&!facesValid.some((f=>facceToccate.includes(f)))||lavs.push({facce:facceToccate,px:posLocal.x,py:posLocal.y,pz:posLocal.z,op:emitter.userData.op})}tasks.push({id:id,op:op,tipo:tipo,x:x,y:y,z:z,lavs:lavs})}return tasks}let globalLabelCanvas=null,globalLabelContext=null;
|
|
49
49
|
/**
|
|
50
50
|
* Crea un punto di riferimento invisibile nell'albero 3D
|
|
51
51
|
* @param {number} x - Coordinata X
|
|
@@ -118,4 +118,4 @@ function getcilindro(gcad,ori,h,r1,r2,mats=mwhite,options){options||(options={})
|
|
|
118
118
|
* @param {Array} mats - Array di materiali
|
|
119
119
|
* @param {Object} options - Opzioni di configurazione
|
|
120
120
|
* @returns {THREE.Group} Gruppo contenente la geometria estrusa
|
|
121
|
-
*/function estrusopat(gcad,orient,pat,shape,mats,options){options||(options={});let invert=options.invert;mats||(mats=[]);let open=options.open;if(!pat.pt?.length)return;let pbase=shape.to3d(0,0,0,0,open),grp=new THREE.Group;if(!options.nobase){let gb=new THREE.Group,g1=bottomgeomfromshape(gcad,!1,shape,[],0,0,0);gb.add(getmesh(g1,mats[0]||mwhite)),gb.add(edgesfromgeometry(g1));let seg1=pat.infosegmento(0,!0);grp.add(posiziona(gb,{sl:seg1.x,sp:seg1.y,sa:0,ay:90-seg1.ang}))}if(!options.notop){let gt=new THREE.Group,g2=bottomgeomfromshape(gcad,!0,shape,[],0,0,0);gt.add(getmesh(g2,mats[1]||mats[0]||mwhite)),gt.add(edgesfromgeometry(g2));let seg1=pat.infosegmento(pat.pt.length-1,!0);grp.add(posiziona(gt,{sl:seg1.x,sp:seg1.y,sa:0,ay:90-seg1.ang}))}const geo1=function sidegeomfrompat(gcad,pbase,pat,invert){let ky=`bsg:${pbase.key}|${pat.key}|${invert}`;if(ky=hash(ky),!gcad.geo[ky]){const positions=[],uvs=[],indices=[],np=pbase.length,lp=pat.pt.length,equalpos=(p1,p2)=>p1.x===p2.x&&p1.y===p2.y&&p1.z===p2.z;let l0=0;for(let ii=0;ii<lp;ii++){const addpts=(ss,mat,deltav)=>{for(const s of ss){let p=new THREE.Vector3(s.x,s.y,s.z);p.applyMatrix4(mat),positions.push(p.x,p.y,p.z),uvs.push(s.u,s.v+deltav)}};let seg1=pat.infosegmento(ii,!0),obj=new THREE.Object3D;obj.position.set(seg1.x,0,seg1.y),obj.rotation.set(0,(90-seg1.ang)*PIF,0),obj.updateMatrix(),addpts(pbase,obj.matrix,l0),l0+=seg1.l}for(let li=0;li<lp-1;li++)for(let i=0;i<np-1;i++){const addindexquad=(i1,i2,i3,i4)=>{invert?indices.push(i1,i3,i2,i3,i4,i2):indices.push(i1,i2,i3,i3,i2,i4)},j=i+1;equalpos(pbase[i],pbase[j])||addindexquad(i+li*np,j+li*np,i+(li+1)*np,j+(li+1)*np)}const geometry=new THREE.BufferGeometry;geometry.setAttribute("position",new THREE.Float32BufferAttribute(positions,3)),geometry.setAttribute("uv",new THREE.Float32BufferAttribute(uvs,2)),geometry.setIndex(indices),geometry.computeVertexNormals(),gcad[ky]=geometry}return gcad[ky]}(gcad,pbase,pat,invert);return options.nolines||options.nosidelines||grp.add(edgesfromgeometry(geo1)),grp.add(getmesh(geo1,mats[2]||mats[0]||mwhite)),estrusorotate(orient,grp,0)}async function spritemat(gcad,file){try{let tm={transparent:!0,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1};if(file.startsWith("#"))tm.color=file;else{let tx=await gcad.tex(file,1e3,1e3);tx?tm.map=tx:tm.color="black"}return new THREE.SpriteMaterial(tm)}catch(error){return mwhite}}function getsprite0(ispunto,x,y,z,mat,options={}){options||(options={});let{size:size=50,pick:pick=!1,screen:screen=!1,sizex:sizex,sizey:sizey}=options;const sprite=new THREE.Sprite(mat);sprite.position.set(0,0,0),sprite.userData.issprite=!0,sprite.userData.ispunto=ispunto,sprite.userData.ispick=pick,sprite.userData.isScreen=screen,sprite.renderOrder=999,sprite.layers.set(29),sprite.name=ispunto?"_punto":"_sprite";let gr=new THREE.Group;return gr.position.set(x,y,z),gr.scale.set(sizex||size,sizey||sizex||size,1),gr.add(sprite),gr.traverse((obj=>{obj.material&&(obj.material.depthTest=!1,obj.material.depthWrite=!1)})),gr.renderOrder=999,gr}async function getpunto(gcad,x,y,z,color="yellow",options){options||(options={size:20}),options.screen=!0;const texture=await function createCircleTexture(gcad,size=64,color="rgba(255,0,0,1)"){const ky=`ct|${size}|${color}`;if(!gcad.textures[ky]){const canvas=document.createElement("canvas");canvas.width=canvas.height=size;const ctx=canvas.getContext("2d"),radius=size/2;ctx.clearRect(0,0,size,size),ctx.fillStyle=color,ctx.beginPath(),ctx.arc(radius,radius,radius,0,2*Math.PI),ctx.fill();const texture=new THREE.CanvasTexture(canvas);texture.needsUpdate=!0,gcad.textures[ky]=texture}return gcad.textures[ky]}(gcad,64,color);return getsprite0(!0,x,y,z,new THREE.SpriteMaterial({map:texture,transparent:!0,fog:!1,toneMapped:!1}),options)}function getsprite(gcad,x,y,z,mat,options={}){return getsprite0(!1,x,y,z,mat,options)}export{SIDE,addmovpivot,creategroup,deletegroup,edgesfromgeometry,estruso,estrusopat,get3dshape,getbox,getcilindro,getcyl,getface,getline,getlinesgeom,getmesh,getmovimento,getpannello,getpoint,getpunto,getquota,getriferimento,getsprite,gettarghetta,groupfromgeometry,infoestrudi,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,posiziona,randombasemat,revolve,scaleunit,spritemat,svuotanodo};
|
|
121
|
+
*/function estrusopat(gcad,orient,pat,shape,mats,options){options||(options={});let invert=options.invert;mats||(mats=[]);let open=options.open;if(!pat.pt?.length)return;let pbase=shape.to3d(0,0,0,0,open),grp=new THREE.Group;if(!options.nobase){let gb=new THREE.Group,g1=bottomgeomfromshape(gcad,!1,shape,[],0,0,0);gb.add(getmesh(g1,mats[0]||mwhite)),gb.add(edgesfromgeometry(g1));let seg1=pat.infosegmento(0,!0);grp.add(posiziona(gb,{sl:seg1.x,sp:seg1.y,sa:0,ay:90-seg1.ang}))}if(!options.notop){let gt=new THREE.Group,g2=bottomgeomfromshape(gcad,!0,shape,[],0,0,0);gt.add(getmesh(g2,mats[1]||mats[0]||mwhite)),gt.add(edgesfromgeometry(g2));let seg1=pat.infosegmento(pat.pt.length-1,!0);grp.add(posiziona(gt,{sl:seg1.x,sp:seg1.y,sa:0,ay:90-seg1.ang}))}const geo1=function sidegeomfrompat(gcad,pbase,pat,invert){let ky=`bsg:${pbase.key}|${pat.key}|${invert}`;if(ky=hash(ky),!gcad.geo[ky]){const positions=[],uvs=[],indices=[],np=pbase.length,lp=pat.pt.length,equalpos=(p1,p2)=>p1.x===p2.x&&p1.y===p2.y&&p1.z===p2.z;let l0=0;for(let ii=0;ii<lp;ii++){const addpts=(ss,mat,deltav)=>{for(const s of ss){let p=new THREE.Vector3(s.x,s.y,s.z);p.applyMatrix4(mat),positions.push(p.x,p.y,p.z),uvs.push(s.u,s.v+deltav)}};let seg1=pat.infosegmento(ii,!0),obj=new THREE.Object3D;obj.position.set(seg1.x,0,seg1.y),obj.rotation.set(0,(90-seg1.ang)*PIF,0),obj.updateMatrix(),addpts(pbase,obj.matrix,l0),l0+=seg1.l}for(let li=0;li<lp-1;li++)for(let i=0;i<np-1;i++){const addindexquad=(i1,i2,i3,i4)=>{invert?indices.push(i1,i3,i2,i3,i4,i2):indices.push(i1,i2,i3,i3,i2,i4)},j=i+1;equalpos(pbase[i],pbase[j])||addindexquad(i+li*np,j+li*np,i+(li+1)*np,j+(li+1)*np)}const geometry=new THREE.BufferGeometry;geometry.setAttribute("position",new THREE.Float32BufferAttribute(positions,3)),geometry.setAttribute("uv",new THREE.Float32BufferAttribute(uvs,2)),geometry.setIndex(indices),geometry.computeVertexNormals(),gcad[ky]=geometry}return gcad[ky]}(gcad,pbase,pat,invert);return options.nolines||options.nosidelines||grp.add(edgesfromgeometry(geo1)),grp.add(getmesh(geo1,mats[2]||mats[0]||mwhite)),estrusorotate(orient,grp,0)}async function spritemat(gcad,file){try{let tm={transparent:!0,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1};if(file.startsWith("#"))tm.color=file;else{let tx=await gcad.tex(file,1e3,1e3);tx?tm.map=tx:tm.color="black"}return new THREE.SpriteMaterial(tm)}catch(error){return mwhite}}function getsprite0(ispunto,x,y,z,mat,options={}){options||(options={});let{size:size=50,pick:pick=!1,screen:screen=!1,sizex:sizex,sizey:sizey}=options;const sprite=new THREE.Sprite(mat);sprite.position.set(0,0,0),sprite.userData.issprite=!0,sprite.userData.ispunto=ispunto,sprite.userData.ispick=pick,sprite.userData.isScreen=screen,sprite.renderOrder=999,sprite.layers.set(29),sprite.name=ispunto?"_punto":"_sprite";let gr=new THREE.Group;return gr.position.set(x,y,z),gr.scale.set(sizex||size,sizey||sizex||size,1),gr.add(sprite),gr.traverse((obj=>{obj.material&&(obj.material.depthTest=!1,obj.material.depthWrite=!1)})),gr.renderOrder=999,gr}async function getpunto(gcad,x,y,z,color="yellow",options){options||(options={size:20}),options.screen=!0;const texture=await function createCircleTexture(gcad,size=64,color="rgba(255,0,0,1)"){const ky=`ct|${size}|${color}`;if(!gcad.textures[ky]){const canvas=document.createElement("canvas");canvas.width=canvas.height=size;const ctx=canvas.getContext("2d"),radius=size/2;ctx.clearRect(0,0,size,size),ctx.fillStyle=color,ctx.beginPath(),ctx.arc(radius,radius,radius,0,2*Math.PI),ctx.fill();const texture=new THREE.CanvasTexture(canvas);texture.needsUpdate=!0,gcad.textures[ky]=texture}return gcad.textures[ky]}(gcad,64,color);return getsprite0(!0,x,y,z,new THREE.SpriteMaterial({map:texture,transparent:!0,fog:!1,toneMapped:!1}),options)}function getsprite(gcad,x,y,z,mat,options={}){return getsprite0(!1,x,y,z,mat,options)}export{SIDE,addmovpivot,calcolatasks,creategroup,deletegroup,edgesfromgeometry,estruso,estrusopat,get3dshape,getbox,getcilindro,getcyl,getface,getline,getlinesgeom,getmesh,getmovimento,getpannello,getpoint,getpunto,getquota,getriferimento,getsprite,gettarghetta,groupfromgeometry,infoestrudi,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,posiziona,randombasemat,revolve,scaleunit,spritemat,svuotanodo,tasklav,taskpannello};
|
package/package.json
CHANGED
package/types/markcad.d.ts
CHANGED
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
* Calcola la lunghezza della linea
|
|
32
32
|
* @returns {number} Lunghezza
|
|
33
33
|
*/ get len(): number;
|
|
34
|
+
get angle(): number;
|
|
34
35
|
/**
|
|
35
36
|
* Estende la linea di una certa lunghezza o fino all'intersezione con un'altra linea
|
|
36
37
|
* @param {number|Linea2} l - Lunghezza di estensione o linea da intersecare
|
|
@@ -48,7 +49,8 @@
|
|
|
48
49
|
* Crea una nuova linea ruotata di un certo angolo
|
|
49
50
|
* @param {number} [angle=Math.PI/2] - Angolo di rotazione in radianti
|
|
50
51
|
* @param {number} [length=0] - Lunghezza della nuova linea
|
|
51
|
-
* @param {boolean} [fine=false] - Se
|
|
52
|
+
* @param {boolean/Punto2} [fine=false] - Se fine è un punto allora crea un segmento che passa per quel punto
|
|
53
|
+
* Se true ruota attorno al primo punto, altrimenti al secondo
|
|
52
54
|
* @returns {Linea2} Nuova linea ruotata
|
|
53
55
|
*/ ruotata(angle?: number, length?: number, fine?: boolean): Linea2;
|
|
54
56
|
/**
|
|
@@ -68,6 +70,7 @@
|
|
|
68
70
|
* @param {Linea2} line2 - Seconda linea
|
|
69
71
|
* @returns {Punto2|null} Punto di intersezione o null se parallele
|
|
70
72
|
*/ intersezione(line2: Linea2): Punto2 | null;
|
|
73
|
+
interseca(line2: any): Punto2;
|
|
71
74
|
onsegment(p: any, eps?: number): boolean;
|
|
72
75
|
/**
|
|
73
76
|
* Verifica se la linea è parallela a un'altra
|
|
@@ -92,7 +95,7 @@
|
|
|
92
95
|
* @returns {Linea2} Nuova linea parallela
|
|
93
96
|
*/ offset(delta: number): Linea2;
|
|
94
97
|
/**
|
|
95
|
-
* Calcola l'angolo tra questa linea e un'altra
|
|
98
|
+
* Calcola l'angolo tra questa linea e un'altra o l'angolo assoluto d
|
|
96
99
|
* @param {Linea2} line2 - Seconda linea
|
|
97
100
|
* @returns {number} Angolo in radianti
|
|
98
101
|
*/ angolo(line2: Linea2): number;
|
|
@@ -236,6 +239,8 @@ export var SP: Readonly<{
|
|
|
236
239
|
"p-": string;
|
|
237
240
|
};
|
|
238
241
|
}>;
|
|
242
|
+
export function TODEG(a: any, dec?: number): number;
|
|
243
|
+
export function TORAD(a: any, dec?: number): number;
|
|
239
244
|
export class Vis2d {
|
|
240
245
|
constructor(name: any, p1: any, p2: any);
|
|
241
246
|
name: any;
|
|
@@ -246,7 +251,7 @@ export class Vis2d {
|
|
|
246
251
|
push(x: any, y: any, rot?: number): void;
|
|
247
252
|
pop(): void;
|
|
248
253
|
randomcolor(transp?: string): string;
|
|
249
|
-
addpoint(p: any, id?: number, color?:
|
|
254
|
+
addpoint(p: any, id?: number, color?: string, spessore?: number): this;
|
|
250
255
|
addline(l: any, id?: number, color?: any, spessore?: number): this;
|
|
251
256
|
addrect(l: any, id?: number, color?: any, spessore?: number): this;
|
|
252
257
|
addrecta(l: any, id?: number, color?: any): this;
|
package/types/markcad3d.d.ts
CHANGED
|
@@ -7,6 +7,21 @@ export const SIDE: any;
|
|
|
7
7
|
* @returns {THREE.Group} - Nuovo gruppo contenitore con pivot.
|
|
8
8
|
*/
|
|
9
9
|
export function addmovpivot(gcad: any, grp: THREE.Object3D, movimento: any, op?: {}, x?: number, y?: number, z?: number): THREE.Group;
|
|
10
|
+
export function calcolatasks(scena: any): {
|
|
11
|
+
id: any;
|
|
12
|
+
op: any;
|
|
13
|
+
tipo: any;
|
|
14
|
+
x: any;
|
|
15
|
+
y: any;
|
|
16
|
+
z: any;
|
|
17
|
+
lavs: {
|
|
18
|
+
facce: string[];
|
|
19
|
+
px: any;
|
|
20
|
+
py: any;
|
|
21
|
+
pz: any;
|
|
22
|
+
op: any;
|
|
23
|
+
}[];
|
|
24
|
+
}[];
|
|
10
25
|
export function creategroup(name: any): any;
|
|
11
26
|
export function deletegroup(grpbase: any, name: any): void;
|
|
12
27
|
export function edgesfromgeometry(g1: any, layer?: number): any;
|
|
@@ -160,3 +175,5 @@ export function revolve(gcad: any, shape: any, orient: any, mat: any, options: a
|
|
|
160
175
|
export const scaleunit: 0.001;
|
|
161
176
|
export function spritemat(gcad: any, file: any): Promise<any>;
|
|
162
177
|
export function svuotanodo(n: any): void;
|
|
178
|
+
export function tasklav(x: any, y: any, z: any, op: any, ids: any, faces: any): any;
|
|
179
|
+
export function taskpannello(px: any, py: any, pz: any, x: any, y: any, z: any, op: {}, tipo: any): any;
|