import{lineLength as n,lineIntersection as t,doIntersect as o,isPointInPolygon as e}from"../geometry.js";import{polygonHachureLines as i}from"./scan-line-hachure.js";export class HachureFiller{constructor(n){this.helper=n}fillPolygon(n,t){return this._fillPolygon(n,t)}_fillPolygon(n,t,o=!1){let e=i(n,t);if(o){const t=this.connectingLines(n,e);e=e.concat(t)}return{type:"fillSketch",ops:this.renderLines(e,t)}}renderLines(n,t){const o=[];for(const e of n)o.push(...this.helper.doubleLineOps(e[0][0],e[0][1],e[1][0],e[1][1],t));return o}connectingLines(t,o){const e=[];if(o.length>1)for(let i=1;i<o.length;i++){const s=o[i-1];if(n(s)<3)continue;const r=[o[i][0],s[1]];if(n(r)>3){const n=this.splitOnIntersections(t,r);e.push(...n)}}return e}midPointInPolygon(n,t){return e(n,(t[0][0]+t[1][0])/2,(t[0][1]+t[1][1])/2)}splitOnIntersections(i,s){const r=Math.max(5,.1*n(s)),l=[];for(let e=0;e<i.length;e++){const c=i[e],h=i[(e+1)%i.length];if(o(c,h,...s)){const o=t(c,h,s[0],s[1]);if(o){const t=n([o,s[0]]),e=n([o,s[1]]);t>r&&e>r&&l.push({point:o,distance:t})}}}if(l.length>1){const n=l.sort(((n,t)=>n.distance-t.distance)).map((n=>n.point));if(e(i,...s[0])||n.shift(),e(i,...s[1])||n.pop(),n.length<=1)return this.midPointInPolygon(i,s)?[s]:[];const t=[s[0],...n,s[1]],o=[];for(let n=0;n<t.length-1;n+=2){const e=[t[n],t[n+1]];this.midPointInPolygon(i,e)&&o.push(e)}return o}return this.midPointInPolygon(i,s)?[s]:[]}}