PlotDirector/PlotLine/wwwroot/js/maps-topology-engine.js

128 lines
25 KiB
JavaScript

/* Optional shared geometry in the existing GeometryJson contract. Coordinates are canvas units. */
(function(root,factory){const E=typeof module==='object'&&module.exports?require('./maps-engine.js'):root.PlotDirectorMaps,api=factory(E);if(typeof module==='object'&&module.exports)module.exports=api;else root.PlotDirectorTopology=api;E.setTopologyAdapter(api);})(typeof globalThis!=='undefined'?globalThis:this,function(E){
'use strict';
const styles=['Natural','Gentle','Rugged','Cliffs','Fjords','Marsh/Delta'],factor={Gentle:.5,Natural:1,Rugged:1.7,Cliffs:1.3,Fjords:2,'Marsh/Delta':1.2},EPS=1e-5;
const parsedRoots=new WeakMap();
const uid=()=>globalThis.crypto.randomUUID(),dist=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]),copy=E.copy;
const linked=f=>!!E.areaGeometry(f).edgeRefs?.some(Boolean),hasStore=f=>f.geometryJson?.includes('"topologyStore"'),mix=(a,b,t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t];
function context(features){
const byId=new Map(features.map(f=>[f.featureID,f])),roots=new Map(),dirty=new Set(),vertices=new Map(),edges=new Map(),vo=new Map(),eo=new Map();
const root=(id,write=false)=>{if(!roots.has(id)){const f=byId.get(id);if(!f)throw Error('A shared area is missing.');let cached=parsedRoots.get(f);if(!cached||cached.json!==f.geometryJson){cached={json:f.geometryJson,value:E.geometry(f)};parsedRoots.set(f,cached);}roots.set(id,cached.value);}if(write&&!dirty.has(id)){roots.set(id,copy(roots.get(id)));dirty.add(id);}return roots.get(id);};
const area=(id,write=false)=>{const g=root(id,write);return byId.get(id).geometryClass==='Marker'&&g.boundary?g.boundary:g;};
for(const f of features)if(hasStore(f)){const s=root(f.featureID).topologyStore;for(const[id,p]of Object.entries(s.vertices||{})){if(vertices.has(id))throw Error('Duplicate shared vertex.');vertices.set(id,p);vo.set(id,f.featureID);}for(const[id,e]of Object.entries(s.edges||{})){if(edges.has(id))throw Error('Duplicate shared edge.');edges.set(id,e);eo.set(id,f.featureID);}}
const store=id=>{const g=root(id,true);return g.topologyStore||=( {version:1,vertices:{},edges:{}} );};
const members=(id,kind='edge')=>features.filter(f=>E.isArea(f)&&f.geometryJson?.includes(id)&&((kind==='edge'?area(f.featureID).edgeRefs:area(f.featureID).vertexRefs)||[]).includes(id)).map(f=>f.featureID);
// Dirty rings may have acquired a reference not yet serialized.
const users=(id,kind='edge')=>[...new Set([...members(id,kind),...[...dirty].filter(fid=>E.isArea(byId.get(fid))&&((kind==='edge'?area(fid).edgeRefs:area(fid).vertexRefs)||[]).includes(id))])].filter(fid=>((kind==='edge'?area(fid).edgeRefs:area(fid).vertexRefs)||[]).includes(id));
const vertex=(p,owner)=>{if(p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000))throw Error('Shared vertex exceeds safe canvas limits.');const id=uid();store(owner).vertices[id]=p;vertices.set(id,p);vo.set(id,owner);return id;};
const edge=(value,owner)=>{const id=uid();store(owner).edges[id]=value;edges.set(id,value);eo.set(id,owner);return id;};
const setVertex=(id,p)=>{if(p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000))throw Error('Shared vertex exceeds safe canvas limits.');if(!vo.has(id))throw Error('Missing shared vertex.');store(vo.get(id)).vertices[id]=p;vertices.set(id,p);};
const setEdge=(id,e)=>{store(eo.get(id)).edges[id]=e;edges.set(id,e);};
const frame=id=>{const f=byId.get(id),g=root(id);return f.geometryClass==='Marker'&&g.boundary?{x:f.x+g.boundary.offsetX,y:f.y+g.boundary.offsetY,width:g.boundary.width,height:g.boundary.height,rotation:g.boundary.rotation,type:f.type,geometryClass:'Area',settlementBoundary:true}:f;};
const commit=()=>features.map(f=>{if(!dirty.has(f.featureID))return f;const json=JSON.stringify(root(f.featureID));if(json.length>64000)throw Error('Shared geometry is too detailed for this area. Unjoin or simplify some segments first.');return {...f,geometryJson:json};});
return {features,byId,root,area,vertices,edges,vo,eo,dirty,frame,store,users,vertex,edge,setVertex,setEdge,commit};
}
const ctx=(features)=>features?.byId?features:context(features);
function controls(f,features){const c=ctx(features),g=c.area(f.featureID),frame=c.frame(f.featureID);return (g.points||[]).map((p,i)=>g.vertexRefs?.[i]?[...c.vertices.get(g.vertexRefs[i])]:E.localToWorld(frame,p));}
function refs(c,id){const g=c.area(id,true),n=g.points.length;g.vertexRefs||=Array(n).fill(null);g.edgeRefs||=Array(n).fill(null);g.edgeShapes||=Array(n).fill(null);g.edgeStyles||=Array(n).fill(null);return g;}
function cubic(points,i,closed=true){const n=points.length,p=points[i],q=points[(i+1)%n],a=closed?points[(i-1+n)%n]:points[Math.max(0,i-1)],b=closed?points[(i+2)%n]:points[Math.min(n-1,i+2)];return [p,[p[0]+(q[0]-a[0])/6,p[1]+(q[1]-a[1])/6],[q[0]-(b[0]-p[0])/6,q[1]-(b[1]-p[1])/6],q];}
function point(q,t){const u=1-t;return [u*u*u*q[0][0]+3*u*u*t*q[1][0]+3*u*t*t*q[2][0]+t*t*t*q[3][0],u*u*u*q[0][1]+3*u*u*t*q[1][1]+3*u*t*t*q[2][1]+t*t*t*q[3][1]];}
function encode(curves){const a=curves[0][0],b=curves.at(-1)[3],dx=b[0]-a[0],dy=b[1]-a[1],d=dx*dx+dy*dy;if(d<EPS*EPS)throw Error('A shared edge cannot have coincident endpoints.');const local=p=>[((p[0]-a[0])*dx+(p[1]-a[1])*dy)/d,((p[1]-a[1])*dx-(p[0]-a[0])*dy)/d];const shape=curves.map(q=>q.slice(1).map(local));if(shape.flat(2).some(n=>!Number.isFinite(n)||Math.abs(n)>10000))throw Error('This edge is too close to collapsing to share safely.');return shape;}
function decode(shape,a,b,coast,baseCoast){const dx=b[0]-a[0],dy=b[1]-a[1],ratio=(factor[coast]||1)/(factor[baseCoast]||1),world=p=>{const u=p[1]*ratio+Math.max(0,(factor[coast]||1)-(factor[baseCoast]||1))*.015*Math.sin(p[0]*Math.PI*2)*Math.sin(p[0]*Math.PI);return [a[0]+dx*p[0]-dy*u,a[1]+dy*p[0]+dx*u];};let p=a;return shape.map(row=>{const values=row.map(world),q=[p,...values];p=values[2];return q;});}
const reverse=curves=>[...curves].reverse().map(q=>[q[3],q[2],q[1],q[0]]);
function sharedCurves(id,features){const c=ctx(features),e=c.edges.get(id);if(!e)throw Error('A shared edge is missing.');return decode(e.shape,c.vertices.get(e.a),c.vertices.get(e.b),e.coast,e.baseCoast);}
function edgeCurves(f,index,features){
const c=ctx(features),g=c.area(f.featureID),points=controls(f,c),n=points.length,id=g.edgeRefs?.[index];
if(id){const e=c.edges.get(id),q=sharedCurves(id,c);return g.vertexRefs[index]===e.a?q:reverse(q);}
if(g.edgeShapes?.[index]){const s=g.edgeShapes[index];return decode(s.shape,points[index],points[(index+1)%n],g.coast||'Natural',s.baseCoast);}
const frame=c.frame(f.featureID),local=points.map(p=>E.worldToLocal(frame,p)),coast=E.coastline({...frame,geometryJson:JSON.stringify({...g,points:local})}),world=coast.map(p=>E.localToWorld(frame,p)),per=world.length/n,result=[];
for(let k=0;k<per;k++)result.push(cubic(world,index*per+k));return result;
}
function paths(f,features){const c=ctx(features);return controls(f,c).map((_,i)=>edgeCurves(f,i,c));}
function path(curves,start=true){return (start?`M ${curves[0][0][0]} ${curves[0][0][1]} `:'')+curves.map(q=>`C ${q[1][0]} ${q[1][1]} ${q[2][0]} ${q[2][1]} ${q[3][0]} ${q[3][1]}`).join(' ');}
function outline(f,features){return paths(f,features).flatMap(cs=>cs.flatMap(q=>Array.from({length:8},(_,i)=>point(q,i/8))));}
function simple(points){
if(points.length<3||points.some(p=>!p||p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))return false;
let area=0;for(let i=0;i<points.length;i++){const a=points[i],b=points[(i+1)%points.length];area+=a[0]*b[1]-b[0]*a[1];if(dist(a,b)<1e-9)return false;}
if(Math.abs(area)<1e-5)return false;
const cross=(a,b,p)=>(b[0]-a[0])*(p[1]-a[1])-(b[1]-a[1])*(p[0]-a[0]),xs=points.map(p=>p[0]),ys=points.map(p=>p[1]),cell=Math.max(EPS,Math.max(Math.max(...xs)-Math.min(...xs),Math.max(...ys)-Math.min(...ys))/Math.sqrt(points.length)),buckets=new Map(),long=[];
const intersect=(i,j)=>{if(Math.abs(i-j)===1||i===points.length-1&&j===0)return false;const a=points[i],b=points[(i+1)%points.length],c=points[j],d=points[(j+1)%points.length];if(Math.max(a[0],b[0])+EPS<Math.min(c[0],d[0])||Math.max(c[0],d[0])+EPS<Math.min(a[0],b[0])||Math.max(a[1],b[1])+EPS<Math.min(c[1],d[1])||Math.max(c[1],d[1])+EPS<Math.min(a[1],b[1]))return false;const x=cross(a,b,c),y=cross(a,b,d),z=cross(c,d,a),w=cross(c,d,b),on=(p,q,r,v)=>Math.abs(v)<1e-8&&r[0]>=Math.min(p[0],q[0])-1e-8&&r[0]<=Math.max(p[0],q[0])+1e-8&&r[1]>=Math.min(p[1],q[1])-1e-8&&r[1]<=Math.max(p[1],q[1])+1e-8;return x*y< -1e-10&&z*w< -1e-10||on(a,b,c,x)||on(a,b,d,y)||on(c,d,a,z)||on(c,d,b,w);};
for(let i=0;i<points.length;i++){const p=points[i],q=points[(i+1)%points.length],x0=Math.floor((Math.min(p[0],q[0])-1e-8)/cell),x1=Math.floor((Math.max(p[0],q[0])+1e-8)/cell),y0=Math.floor((Math.min(p[1],q[1])-1e-8)/cell),y1=Math.floor((Math.max(p[1],q[1])+1e-8)/cell),keys=[];if((x1-x0+1)*(y1-y0+1)>128){for(let j=0;j<i;j++)if(intersect(i,j))return false;long.push(i);continue;}const candidates=new Set(long);for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++){const key=x+','+y;keys.push(key);for(const j of buckets.get(key)||[])candidates.add(j);}for(const j of candidates)if(intersect(i,j))return false;for(const key of keys){if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(i);}}
return true;
}
function validate(c,ids){for(const id of new Set(ids)){const f=c.byId.get(id);if(!f||!E.isArea(f))continue;const g=c.area(id);if((g.edgeRefs||[]).some(edgeId=>edgeId&&dist(c.vertices.get(c.edges.get(edgeId).a),c.vertices.get(c.edges.get(edgeId).b))<EPS))throw Error('A shared edge cannot collapse. Unjoin it before removing an endpoint.');if(paths(f,c).flat(2).some(p=>p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))throw Error('Boundary curves exceed safe canvas limits.');if(g.points.length<3||g.points.length>64||g.points.some(p=>p.some(n=>!Number.isFinite(n)||Math.abs(n)>10))||!simple(controls(f,c))||!simple(outline(f,c)))throw Error('This edit would make an area self-intersect, collapse or exceed 64 vertices. Adjust the endpoints or choose the other boundary section.');}}
function unlocked(c,ids){if(ids.some(id=>c.byId.get(id)?.isLocked))throw Error('Unlock all participating areas before editing this shared geometry.');}
function style(f){return {theme:E.hasBoundary(f)?'settlement':f.layer==='Regions'?'region':'terrain',...(E.areaGeometry(f).appearance||{})};}
function clearVertexRefs(c,id){const g=refs(c,id),f=c.byId.get(id),points=controls(f,c);for(let i=0;i<g.points.length;i++)if(!g.edgeRefs[i]&&!g.edgeRefs[(i-1+g.points.length)%g.points.length]){g.points[i]=E.worldToLocal(c.frame(f.featureID),points[i]);g.vertexRefs[i]=null;}}
function bakeEdge(c,id,index){const f=c.byId.get(id),g=refs(c,id),edgeId=g.edgeRefs[index];if(!edgeId)return;const e=c.edges.get(edgeId),cs=edgeCurves(f,index,c);g.edgeShapes[index]={shape:encode(cs),baseCoast:g.coast||'Natural'};g.edgeStyles[index]={...copy(e.style),reverseStroke:Boolean(e.style.reverseStroke)!==(g.vertexRefs[index]!==e.a)};g.edgeRefs[index]=null;}
function gc(c){
for(const id of [...c.edges.keys()]){const users=c.users(id);if(users.length===1){const fid=users[0],g=refs(c,fid);for(let i=0;i<g.points.length;i++)if(g.edgeRefs[i]===id)bakeEdge(c,fid,i);clearVertexRefs(c,fid);}
if(!c.users(id).length){delete c.store(c.eo.get(id)).edges[id];c.edges.delete(id);c.eo.delete(id);}}
for(const id of [...c.vertices.keys()])if(!c.users(id,'vertex').length){delete c.store(c.vo.get(id)).vertices[id];c.vertices.delete(id);c.vo.delete(id);}
for(const id of c.dirty){const g=c.root(id);if(g.topologyStore&&!Object.keys(g.topologyStore.edges).length&&!Object.keys(g.topologyStore.vertices).length)delete g.topologyStore;}
}
function movePoint(features,id,index,p){const c=context(features),f=c.byId.get(id),g=refs(c,id),ref=g.vertexRefs[index];let affected=[id];if(ref){affected=c.users(ref,'vertex');unlocked(c,affected);c.setVertex(ref,p);}else{unlocked(c,[id]);g.points[index]=E.worldToLocal(c.frame(f.featureID),p);}validate(c,affected);return c.commit();}
function freeze(c,id){const f=c.byId.get(id),g=refs(c,id);for(let i=0;i<g.points.length;i++)if(!g.edgeRefs[i]&&!g.edgeShapes[i])g.edgeShapes[i]={shape:encode(edgeCurves(f,i,c)),baseCoast:g.coast||'Natural'};}
function splitCubic(q,t){const a=mix(q[0],q[1],t),b=mix(q[1],q[2],t),d=mix(q[2],q[3],t),e=mix(a,b,t),f=mix(b,d,t),p=mix(e,f,t);return [[q[0],a,e,p],[p,f,d,q[3]]];}
function insert(features,id,index,curveIndex,t){const c=context(features);insertIn(c,id,index,curveIndex,t);validate(c,[...c.dirty]);return c.commit();}
function insertIn(c,id,index,ci,t){
const f=c.byId.get(id),g=refs(c,id),cs=edgeCurves(f,index,c),split=splitCubic(cs[ci],t),left=[...cs.slice(0,ci),split[0]],right=[split[1],...cs.slice(ci+1)],p=split[0][3],old=g.edgeRefs[index];
if(dist(p,cs[0][0])<EPS||dist(p,cs.at(-1)[3])<EPS)throw Error('Choose a point away from the edge endpoints.');
const users=old?c.users(old):[id];unlocked(c,users);users.forEach(fid=>freeze(c,fid));if(users.some(fid=>c.area(fid).points.length>=64))throw Error('This boundary already has 64 control points.');
if(old){const e=c.edges.get(old),owner=c.eo.get(old),canonical=g.vertexRefs[index]===e.a,vid=c.vertex(p,owner),l=c.edge({a:e.a,b:vid,shape:encode(canonical?left:reverse(right)),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},owner),r=c.edge({a:vid,b:e.b,shape:encode(canonical?right:reverse(left)),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},owner);
for(const fid of users){const a=refs(c,fid),i=a.edgeRefs.indexOf(old),forward=a.vertexRefs[i]===e.a;const ids=forward?[l,r]:[r,l];a.points.splice(i+1,0,E.worldToLocal(c.frame(fid),p));a.vertexRefs.splice(i+1,0,vid);a.edgeRefs.splice(i,1,...ids);a.edgeShapes.splice(i,1,null,null);a.edgeStyles.splice(i,1,null,null);}
gc(c);
}else{g.points.splice(index+1,0,E.worldToLocal(c.frame(f.featureID),p));g.vertexRefs.splice(index+1,0,null);g.edgeRefs.splice(index,1,null,null);g.edgeShapes.splice(index,1,{shape:encode(left),baseCoast:g.coast||'Natural'},{shape:encode(right),baseCoast:g.coast||'Natural'});g.edgeStyles.splice(index,1,g.edgeStyles[index],g.edgeStyles[index]);}
}
function removePoint(features,id,index){
const c=context(features),f=c.byId.get(id),g=refs(c,id),n=g.points.length,prev=(index-1+n)%n,left=g.edgeRefs[prev],right=g.edgeRefs[index],v=g.vertexRefs[index];unlocked(c,[id]);if(n<=3)throw Error('An area needs at least three vertices.');
if(v){if(!left||!right||left===right)throw Error('Unjoin this junction before removing its endpoint.');const affected=c.users(v,'vertex');unlocked(c,affected);const lu=c.users(left).sort().join(),ru=c.users(right).sort().join();if(lu!==ru||affected.sort().join()!==lu)throw Error('A shared junction cannot be deleted while other segments meet there.');
const cs=[...edgeCurves(f,prev,c),...edgeCurves(f,index,c)],a=g.vertexRefs[prev],b=g.vertexRefs[(index+1)%n],e=c.edges.get(left),joined=c.edge({a,b,shape:encode(cs),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},c.eo.get(left));
for(const fid of affected){const q=refs(c,fid),i=q.vertexRefs.indexOf(v),p=(i-1+q.points.length)%q.points.length;q.edgeRefs[p]=joined;q.points.splice(i,1);q.vertexRefs.splice(i,1);q.edgeRefs.splice(i,1);q.edgeShapes.splice(i,1);q.edgeStyles.splice(i,1);}gc(c);validate(c,affected);
}else{g.points.splice(index,1);for(const key of ['vertexRefs','edgeRefs','edgeShapes','edgeStyles'])g[key].splice(index,1);g.edgeShapes[(index-1+g.points.length)%g.points.length]=null;validate(c,[id]);}
return c.commit();
}
function smooth(features,id,coast){if(!styles.includes(coast))throw Error('Choose an existing smoothing style.');const c=context(features),e=c.edges.get(id);if(!e)throw Error('Select a shared edge.');unlocked(c,c.users(id));c.setEdge(id,{...e,coast});validate(c,c.users(id));return c.commit();}
function unjoin(features,fid,edgeId=null){const c=context(features),g=refs(c,fid);unlocked(c,[fid]);for(let i=0;i<g.points.length;i++)if(g.edgeRefs[i]&&(!edgeId||g.edgeRefs[i]===edgeId))bakeEdge(c,fid,i);clearVertexRefs(c,fid);gc(c);return c.commit();}
function nearestOnCurves(curves,p,iterations=28){let best=null;for(let k=0;k<curves.length;k++){const q=curves[k];for(let j=0;j<12;j++){let lo=j/12,hi=(j+1)/12;for(let n=0;n<iterations;n++){const a=lo+(hi-lo)/3,b=hi-(hi-lo)/3;if(dist(point(q,a),p)<dist(point(q,b),p))hi=b;else lo=a;}const t=(lo+hi)/2,x=point(q,t),d=dist(x,p);if(!best||d<best.distance)best={point:x,distance:d,curveIndex:k,t};}}return best;}
function snapIndex(features,scale=1){
const c=context(features),cell=Math.max(32,scale*80),vertices=new Map(),segments=new Map(),long=[],key=(x,y)=>Math.floor(x/cell)+','+Math.floor(y/cell),put=(map,k,v)=>{if(!map.has(k))map.set(k,[]);map.get(k).push(v);};
for(const f of features.filter(E.isArea)){const ps=controls(f,c),g=c.area(f.featureID);ps.forEach((p,i)=>put(vertices,key(...p),{point:p,areaID:f.featureID,index:i,vertexID:g.vertexRefs?.[i]}));paths(f,c).forEach((cs,i)=>cs.forEach((q,k)=>{const xs=q.map(p=>p[0]),ys=q.map(p=>p[1]),box={left:Math.min(...xs),right:Math.max(...xs),top:Math.min(...ys),bottom:Math.max(...ys)},item={q,box,areaID:f.featureID,index:i,curveIndex:k,vertexIDs:[g.vertexRefs?.[i],g.vertexRefs?.[(i+1)%ps.length]]};const x0=Math.floor(box.left/cell),x1=Math.floor(box.right/cell),y0=Math.floor(box.top/cell),y1=Math.floor(box.bottom/cell);if((x1-x0+1)*(y1-y0+1)>64)long.push(item);else for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)put(segments,x+','+y,item);}));}
return {c,cell,vertices,segments,long,key};
}
function snap(index,p,tolerance,options={}){if(options.disabled)return null;const {cell,key}=index,candidates=(map)=>{const items=new Set();for(let x=p[0]-tolerance;x<=p[0]+tolerance+cell;x+=cell)for(let y=p[1]-tolerance;y<=p[1]+tolerance+cell;y+=cell)for(const item of map.get(key(x,y))||[])items.add(item);return [...items];};
const valid=v=>v.areaID!==options.areaID&&(!v.vertexID||v.vertexID!==options.vertexID);let best=null;
if(options.vertex!==false)for(const v of candidates(index.vertices))if(valid(v)){const d=dist(p,v.point);if(d<=tolerance&&(!best||d<best.distance))best={...v,distance:d,type:'vertex'};}if(best)return best;
if(options.edge!==false)for(const s of new Set([...candidates(index.segments),...index.long])){if(s.areaID===options.areaID||(options.vertexID&&s.vertexIDs?.includes(options.vertexID))||p[0]<s.box.left-tolerance||p[0]>s.box.right+tolerance||p[1]<s.box.top-tolerance||p[1]>s.box.bottom+tolerance)continue;const n=nearestOnCurves([s.q],p);if(n.distance<=tolerance&&(!best||n.distance<best.distance))best={...s,...n,curveIndex:s.curveIndex,type:'edge'};}return best;
}
function walk(a,b,n,d=1){const ids=[a];for(let i=a;i!==b;){i=(i+d+n)%n;ids.push(i);if(ids.length>n)throw Error('Ambiguous boundary section.');}return ids;}
function sectionLength(c,id,indices){const f=c.byId.get(id),n=c.area(id).points.length;let length=0;for(let k=0;k<indices.length-1;k++){const i=indices[k],j=indices[k+1],index=j===(i+1)%n?i:j;for(const q of edgeCurves(f,index,c)){let p=q[0];for(let s=1;s<=16;s++){const next=point(q,s/16);length+=dist(p,next);p=next;}}}return length;}
function choose(a,b,n,d,length){if(d==='forward')return walk(a,b,n,1);if(d==='backward')return walk(a,b,n,-1);const x=walk(a,b,n,1),y=walk(a,b,n,-1),lx=length(x),ly=length(y);if(Math.abs(lx-ly)<=Math.max(1e-6,Math.max(lx,ly)*1e-8))throw Error('Both boundary sections are equally short. Choose Forward or Backward explicitly.');return lx<ly?x:y;}
function endpoint(c,id,p){let ps=controls(c.byId.get(id),c),i=ps.findIndex(q=>dist(p,q)<EPS);if(i>=0)return i;let best=null;paths(c.byId.get(id),c).forEach((cs,index)=>{const hit=nearestOnCurves(cs,p,60);if(!best||hit.distance<best.distance)best={...hit,index};});if(!best||best.distance>EPS)throw Error('Snap both selected endpoints precisely to the neighbouring boundary first.');insertIn(c,id,best.index,best.curveIndex,best.t);ps=controls(c.byId.get(id),c);i=ps.findIndex(q=>dist(p,q)<EPS);if(i<0)throw Error('Could not insert the neighbouring endpoint safely.');return i;}
function mergeVertex(c,from,to){if(!from||from===to)return;const users=c.users(from,'vertex');unlocked(c,users);for(const id of users){const g=refs(c,id);g.vertexRefs=g.vertexRefs.map(v=>v===from?to:v);}for(const[id,e]of c.edges)if(e.a===from||e.b===from)c.setEdge(id,{...e,a:e.a===from?to:e.a,b:e.b===from?to:e.b});}
function join(features,options){
const c=context(features);let {areaID,neighborID,start,end,sourceDirection='shorter',neighborDirection='shorter',retain='neighbor'}=options;if(areaID===neighborID)throw Error('Choose a different adjoining area.');unlocked(c,[areaID,neighborID]);const source=c.byId.get(areaID),target=c.byId.get(neighborID);if(!source||!target||!E.isArea(source)||!E.isArea(target))throw Error('Choose two geographical areas.');
freeze(c,areaID);freeze(c,neighborID);const ps=controls(source,c);if(start===end||!ps[start]||!ps[end])throw Error('Select two different boundary vertices.');const a=ps[start],b=ps[end];endpoint(c,neighborID,a);endpoint(c,neighborID,b);let targetPoints=controls(target,c),ta=targetPoints.findIndex(p=>dist(p,a)<EPS),tb=targetPoints.findIndex(p=>dist(p,b)<EPS);
if(retain==='selected'){[areaID,neighborID]=[neighborID,areaID];[start,end,ta,tb]=[ta,tb,start,end];[sourceDirection,neighborDirection]=[neighborDirection,sourceDirection];}
let sg=refs(c,areaID),tg=refs(c,neighborID),src=choose(start,end,sg.points.length,sourceDirection,ids=>sectionLength(c,areaID,ids)),dst=choose(ta,tb,tg.points.length,neighborDirection,ids=>sectionLength(c,neighborID,ids));
// Replace only a forward slice of the joining ring, retaining its winding.
if(src[1]!==((src[0]+1)%sg.points.length)){src.reverse();dst.reverse();}
const sp=controls(c.byId.get(areaID),c),tp=controls(c.byId.get(neighborID),c);if(src.slice(0,-1).some(i=>sg.edgeRefs[i]))throw Error('That section is already shared. Unjoin it first; existing shared boundaries are preserved.');
for(const i of dst){tg.vertexRefs[i]||=c.vertex(tp[i],neighborID);}
mergeVertex(c,sg.vertexRefs[src[0]],tg.vertexRefs[dst[0]]);mergeVertex(c,sg.vertexRefs[src.at(-1)],tg.vertexRefs[dst.at(-1)]);
const vertices=dst.map(i=>tg.vertexRefs[i]),edges=[];
for(let k=0;k<dst.length-1;k++){const i=dst[k],j=dst[k+1],forward=j===(i+1)%tg.points.length,edgeIndex=forward?i:j;let edgeID=tg.edgeRefs[edgeIndex];if(!edgeID){const cs=edgeCurves(c.byId.get(neighborID),edgeIndex,c),v1=tg.vertexRefs[edgeIndex],v2=tg.vertexRefs[(edgeIndex+1)%tg.points.length];edgeID=c.edge({a:v1,b:v2,shape:encode(cs),coast:tg.coast||'Natural',baseCoast:tg.coast||'Natural',style:copy(tg.edgeStyles[edgeIndex]||style(c.byId.get(neighborID)))},neighborID);tg.edgeRefs[edgeIndex]=edgeID;}edges.push(edgeID);}
const n=sg.points.length,s=src[0],length=src.length-1,rot=Array.from({length:n},(_,i)=>(s+i)%n),privateIndices=rot.slice(length),newIndices=[...dst.slice(0,-1)],frame=c.frame(areaID);
sg.points=[...newIndices.map(i=>E.worldToLocal(frame,tp[i])),...privateIndices.map(i=>sg.points[i])];sg.vertexRefs=[...vertices.slice(0,-1),...privateIndices.map(i=>sg.vertexRefs[i])];sg.vertexRefs[vertices.length-1]=vertices.at(-1);
sg.edgeRefs=[...edges,...privateIndices.map(i=>sg.edgeRefs[i])];sg.edgeShapes=[...edges.map(()=>null),...privateIndices.map(i=>sg.edgeShapes[i])];sg.edgeStyles=[...edges.map(()=>null),...privateIndices.map(i=>sg.edgeStyles[i])];
gc(c);validate(c,[...new Set([...c.dirty,...vertices.flatMap(v=>c.users(v,'vertex'))])]);return c.commit();
}
function detachCopies(features,copies,mapping){const c=context(features);return copies.map(f=>{const original=features.find(x=>mapping.get(x.featureID)===f.featureID);if(!original||!E.isArea(original))return f;const g=E.geometry(f),a=E.hasBoundary(f)?g.boundary:g,old=c.area(original.featureID);delete g.topologyStore;if(old.edgeRefs?.some(Boolean)){a.points=controls(original,c).map(p=>E.worldToLocal(c.frame(original.featureID),p));a.edgeShapes=paths(original,c).map(cs=>({shape:encode(cs),baseCoast:a.coast||'Natural'}));a.edgeStyles=old.points.map((_,i)=>old.edgeRefs?.[i]?{...copy(c.edges.get(old.edgeRefs[i]).style),reverseStroke:Boolean(c.edges.get(old.edgeRefs[i]).style.reverseStroke)!==(old.vertexRefs[i]!==c.edges.get(old.edgeRefs[i]).a)}:old.edgeStyles?.[i]||null);delete a.vertexRefs;delete a.edgeRefs;}return {...f,geometryJson:JSON.stringify(g)};});}
function remove(features,ids){let output=features;for(const id of ids)if(output.some(f=>f.featureID===id&&E.isArea(f)))output=unjoin(output,id);const c=context(output),remaining=output.filter(f=>!ids.has(f.featureID)),survivors=new Set(remaining.map(f=>f.featureID));
for(const [kind,defs,owners]of [['vertices',c.vertices,c.vo],['edges',c.edges,c.eo]])for(const[id,value]of defs)if(!survivors.has(owners.get(id))){const users=c.users(id,kind==='vertices'?'vertex':'edge').filter(fid=>survivors.has(fid));if(!users.length)continue;const owner=users[0];c.store(owner)[kind][id]=copy(value);owners.set(id,owner);}
return c.commit().filter(f=>survivors.has(f.featureID));
}
function reposition(before,after){const c=context(after),old=new Map(before.map(f=>[f.featureID,f]));for(const[id,p]of c.vertices){const users=c.users(id,'vertex');if(!users.length)continue;const deltas=users.map(fid=>{const a=old.get(fid),b=c.byId.get(fid);return [b.x-a.x,b.y-a.y];}),delta=deltas[0];if(deltas.some(d=>dist(d,delta)>1e-6))throw Error('Shared areas '+users.map(fid=>c.byId.get(fid).name).join(', ')+' have incompatible geographical displacements. Unjoin their shared boundaries before repositioning.');if(Math.hypot(...delta)>1e-8)c.setVertex(id,[p[0]+delta[0],p[1]+delta[1]]);}return c.commit();}
return {reverse,context,linked,hasStore,controls,paths,path,outline,edgeCurves,sharedCurves,style,point,encode,simple,movePoint,insert,removePoint,smooth,unjoin,join,snapIndex,snap,detachCopies,remove,reposition};
});