From 05327c3ddd2468de7cee2ef02c3a9e7d41c165c4 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sat, 14 Nov 2026 20:26:38 +0000 Subject: [PATCH] Add shared map boundaries with snapping and topological editing --- Docs/Maps/SharedBoundaries.md | 45 +++++++ PlotLine.Tests/Browser/maps-settlements.cjs | 2 +- .../Browser/maps-topology-development.cjs | 10 ++ .../Browser/maps-topology-engine.cjs | 31 +++++ .../Browser/maps-topology-fixture.cjs | 7 + PlotLine.Tests/Browser/maps-topology.cjs | 30 +++++ .../MapGeographicHierarchyDatabaseTests.cs | 14 +- PlotLine.Tests/MapTopologyTests.cs | 31 +++++ PlotLine.Tests/Program.cs | 3 + PlotLine.Tests/ToolbarBrowserHost.cs | 2 +- .../Services/MapAreaGeometryValidation.cs | 2 +- PlotLine/Services/MapTopologyValidation.cs | 56 ++++++++ PlotLine/Services/MapValidation.cs | 2 + PlotLine/Views/Maps/Index.cshtml | 3 + PlotLine/wwwroot/css/maps-workspace.css | 2 + PlotLine/wwwroot/js/maps-engine.js | 15 ++- PlotLine/wwwroot/js/maps-geography-engine.js | 2 + PlotLine/wwwroot/js/maps-story.js | 1 + PlotLine/wwwroot/js/maps-topology-engine.js | 127 ++++++++++++++++++ PlotLine/wwwroot/js/maps-workspace.js | 110 +++++++++------ 20 files changed, 437 insertions(+), 58 deletions(-) create mode 100644 Docs/Maps/SharedBoundaries.md create mode 100644 PlotLine.Tests/Browser/maps-topology-development.cjs create mode 100644 PlotLine.Tests/Browser/maps-topology-engine.cjs create mode 100644 PlotLine.Tests/Browser/maps-topology-fixture.cjs create mode 100644 PlotLine.Tests/Browser/maps-topology.cjs create mode 100644 PlotLine.Tests/MapTopologyTests.cs create mode 100644 PlotLine/Services/MapTopologyValidation.cs create mode 100644 PlotLine/wwwroot/js/maps-topology-engine.js diff --git a/Docs/Maps/SharedBoundaries.md b/Docs/Maps/SharedBoundaries.md new file mode 100644 index 00000000..eeaded19 --- /dev/null +++ b/Docs/Maps/SharedBoundaries.md @@ -0,0 +1,45 @@ +# Shared boundaries and snapping + +## Author workflow + +Select a geographical area, choose **Edit boundary** / **Edit shape**, and drag control points. **Snap to vertex** and **Snap to edge** default on, with a 10-screen-pixel tolerance and a visible snap ring. Hold Alt during a point drag to suppress snapping; Alt + click on ordinary map content continues cycling overlapping pieces. Creating a piece or converting a settlement uses the same editor. Snapping alone changes only the edited point; it never creates a relationship or inserts a point into the neighbour. + +Snap two endpoints to a neighbouring boundary, then choose **Join boundaries** in the boundary editor, Arrange group or piece context menu. The dialog identifies endpoints and the section on each area. Defaults use the shorter section; equally short alternatives require an explicit Forward/Backward choice. It retains the neighbour's existing curve by default, with an option to retain the selected area's geometry instead. Edge endpoints are inserted into the neighbour only at this deliberate join, preserving its visible curves. Different intermediate-point counts are supported. Existing shared sections cannot be overwritten; choose another section or unjoin first. + +Shared points use distinct handles. Shared edges have a generous invisible hit target, can be selected through the boundary dropdown, and list their participating areas. Right-click a point to mark a join endpoint. A shared edge is drawn once, using the retained edge's border style, after the highest participating fill in the normal drawing order. Labels, anchors, selection overlays and manual Arrange ordering retain their existing roles. + +Move, insert or remove shared control points from either area. Insertion subdivides the exact curve; deleting a degree-two intermediate vertex merges its curves. Junction endpoints cannot be deleted while unrelated segments meet there. Shared smoothing has one setting per shared edge; switching styles leaves its underlying curve controls intact. Unshared edges continue using their area treatment. Locks prevent shared edits affecting a locked participant. + +**Unjoin boundary** detaches the selected area from that edge. **Unjoin all boundaries** makes the selected area independent. Visible curves and border styles are baked into private edge geometry, including stroke direction so dashed borders remain aligned. Other participants retain their relationships. Undo/Redo restores the complete geometry and topology together. + +## Representation and integration + +No SQL migration is required. Optional additions to existing feature `GeometryJson` are: + +- Area geometry (root for Area, nested `boundary` for settlement Marker): `vertexRefs`, `edgeRefs`, `edgeShapes`, `edgeStyles`, each aligned with the existing control-point ring. +- Root `topologyStore: {version:1, vertices, edges}`: definitions owned by existing geographical feature records. Definitions can be distributed across owners, but each vertex/edge ID has exactly one definition within a map. +- A vertex definition contains one authoritative world position. A shared edge references two authoritative vertices and one immutable normalized cubic shape, plus current/base smoothing and retained style. Both rings resolve that definition, in either direction, rather than independently copying coordinates. Existing `points` entries at referenced vertices are fallback caches and are not rendering/editing authority. +- Three-way and higher junctions reuse one vertex ID across incident edges. Joining a third area preserves existing shared sections. No FeatureID, LocationID, Location parent or road anchor is replaced or introduced. + +Private `edgeShapes` retain subdivided/unjoined curves relative to their endpoints. This preserves the visible shape while returning them to independent editing. Ordinary maps without these additions keep their original renderer and storage. Filled areas with topology use the same SVG scene and editor, decomposing their strokes so a shared border is never painted twice. Containment and bounds resolve the same rendered geometry. + +Server validation checks version, unique definitions, same-map references, consistent edge orientation, at least two participants per shared edge, no orphan definitions, finite bounded curves and permitted styles. The existing 64-control-point and 64 KB-per-feature geometry limits apply. Client operations validate affected polygons, reject collapsed/self-intersecting/ambiguous sections and commit only a complete valid result. Failed edits leave the previous state intact. + +## Movement, deletion and compatibility + +Independent area movement is unchanged. Whole-area movement, rotation, resizing and Fit boundary are restricted while shared edges exist: explicitly unjoin first. Independent settlement anchor movement remains available because it leaves the boundary fixed. Ordinary vertex editing changes the authoritative geometry and updates all participating outlines without moving buildings or settlement anchors. + +Geographical positioning and relationship arrangement translate shared vertices once when all incident areas receive the same displacement. Incompatible displacements block the complete proposal and identify the areas to unjoin. Independent hierarchy-aware positioning, path transformation and its atomic Apply/Undo semantics remain intact. + +Duplicating an area bakes an independent copy of its current visible geometry, without references to the originals. Whole-map copies carry their complete graph scoped to the new map. Deleting an area removes only its participation, bakes singleton edges for survivors, transfers any surviving definitions it owned, and removes unreferenced definitions. Backup/restore and import/export retain the opaque geometry JSON and validate the complete graph. + +## Verification + +- Normal solution build and executable regression harness, including `MapTopologyTests`. +- `node PlotLine.Tests/Browser/maps-topology-engine.cjs`: vertex/curved-edge snapping and zoom tolerance, explicit authority, differing point counts, shared editing/insertion/removal/smoothing, junctions, exact unjoin, ownership transfer/deletion, duplication, invalid geometry, compatible/conflicting geographical movement, and spatial-index performance. +- `node PlotLine.Tests/Browser/maps-topology.cjs`: normal/PWA pointer interaction, join dialog, single border, shared control editing, Undo/Redo, movement restriction, Save/reopen, unjoin, three-way junction, duplication and deletion. +- Existing settlement, drawing-order, hierarchy-geography and Maps workflows are regression gates. +- `--map-topology-database /tmp/pd-dev-browser-/identity.json`: dedicated Development account/project, complete shared graph with a three-way junction, real Save/reload and full project backup/export/import/restore, unchanged canonical hierarchy and road references. +- `node PlotLine.Tests/Browser/maps-topology-development.cjs /tmp/pd-dev-browser-/identity.json`: authenticated Development controls and real Save/reload, followed by the normal disposable-account cleanup. + +Tests use isolated data and never open the author's actual Birmingham map. The model supports a single simple ring per area; holes, multipart polygons, snapping a whole edge in one gesture and dragging connected areas as a manual group are outside this change. Edit individual vertices, use explicit shared sections, and unjoin before independent whole-area movement. Existing shape/size limits may require simplifying a very detailed section before joining. diff --git a/PlotLine.Tests/Browser/maps-settlements.cjs b/PlotLine.Tests/Browser/maps-settlements.cjs index 7233b1ba..c27dbf8d 100644 --- a/PlotLine.Tests/Browser/maps-settlements.cjs +++ b/PlotLine.Tests/Browser/maps-settlements.cjs @@ -40,7 +40,7 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238'; const controls=JSON.stringify(JSON.parse((await feature(ids.town)).geometryJson).boundary.points); for(const value of ['Rugged','Gentle','Natural']){await page.locator('[data-geometry=coast]').selectOption(value);assert.equal(JSON.stringify(JSON.parse((await feature(ids.town)).geometryJson).boundary.points),controls);assert.equal(await route(),roadBefore);} await page.locator('[data-area-style=fillOpacity]').fill('0.4');await page.locator('[data-area-style=fillOpacity]').blur();await page.locator('[data-area-style=borderStyle]').selectOption('Dotted'); - assert.equal(await page.locator(`[data-boundary-feature-id="${ids.town}"] path`).getAttribute('fill-opacity'),'0.4'); + assert.equal(await page.locator(`[data-boundary-feature-id="${ids.town}"] [fill-opacity]`).getAttribute('fill-opacity'),'0.4'); await select(ids.house);const containment=page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Geographical containment")')});await containment.locator('summary').click();assert.match(await containment.innerText(),/Rubery/);assert.match(await containment.innerText(),/Lickey Hills/); await select(ids.town);await page.locator('[data-settlement-mode=anchor]').click();const worldBefore=await page.evaluate(id=>window.PlotDirectorMaps.outline(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),ids.town); await page.locator('[data-handle=anchor]').focus();await page.keyboard.press('ArrowRight');town=await feature(ids.town);assert.equal(town.x,original.x+5);assert.notEqual(await route(),roadBefore); diff --git a/PlotLine.Tests/Browser/maps-topology-development.cjs b/PlotLine.Tests/Browser/maps-topology-development.cjs new file mode 100644 index 00000000..f10a98e2 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-topology-development.cjs @@ -0,0 +1,10 @@ +// Authenticated Development-only acceptance on the disposable --map-topology-database fixture. +const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const identityPath=process.argv[2];if(!identityPath?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated Development identity required.');const identity=JSON.parse(fs.readFileSync(identityPath,'utf8')),fixture=JSON.parse(fs.readFileSync(path.join(path.dirname(identityPath),'topology-fixture.json'),'utf8'));if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Wrong identity scope.'); +(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1700,height:1150}}),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('https://dev.plotdirector.com/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('form[action="/Account/Login"] button[type=submit]').click()]);await page.goto('https://dev.plotdirector.com/Maps?projectId='+fixture.projectId+'&id='+fixture.mapId);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + const ids=await page.evaluate(()=>Object.fromEntries(window.PlotDirectorMapWorkspace.document.features.map(f=>[f.name,f.featureID]))),read=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),command=id=>page.evaluate(id=>document.getElementById(id).click(),id);const before=await read(),road=()=>page.locator(`[data-feature-id="${ids['Boundary road']}"] .map-shape`).getAttribute('d'),roadBefore=await road(); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),ids.Solihull);await page.locator('[data-settlement-mode=boundary]').click();await page.locator('#mapsDetailContent [data-topology=join]').click();const dialog=page.locator('dialog[open]');await dialog.locator('[name=neighborID]').selectOption(ids.Birmingham);await dialog.locator('[name=start]').selectOption('3');await dialog.locator('[name=end]').selectOption('0');await dialog.locator('[name=sourceDirection]').selectOption('forward');await dialog.locator('[name=neighborDirection]').selectOption('backward');await dialog.getByRole('button',{name:'Join boundaries',exact:true}).click();assert.equal(await dialog.count(),0);assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),1); + const joined=await read();await command('mapsUndo');assert.equal(await read(),before);await command('mapsRedo');assert.equal(await read(),joined);await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),ids.Solihull);await page.locator('[data-settlement-mode=boundary]').click();await page.locator('[data-topology=insert]').click();assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),2); + const index=await page.evaluate(id=>{const T=window.PlotDirectorTopology,c=T.context(window.PlotDirectorMapWorkspace.document.features);return c.area(id).vertexRefs.findIndex(v=>v&&Math.abs(c.vertices.get(v)[1])<80);},ids.Solihull);assert(index>=0);await page.locator(`[data-handle=point][data-index="${index}"]`).focus();await page.keyboard.press('ArrowRight');await page.locator('[data-shared-smoothing]').selectOption('Gentle');assert.equal(await road(),roadBefore,'boundary topology never changes road anchors or curves'); + await command('mapsSave');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');const saved=await read();await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await read(),saved,'actual server Save/reload retains authority, references and curves');assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),2); + await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),ids.Solihull);const outline=await page.evaluate(()=>{const W=window.PlotDirectorMapWorkspace,T=window.PlotDirectorTopology;return W.document.features.filter(window.PlotDirectorMaps.isArea).map(f=>T.outline(f,W.document.features));});await page.locator('#mapsDetailContent [data-topology=unjoin-all]').click();assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),0);const independent=await page.evaluate(()=>{const W=window.PlotDirectorMapWorkspace,T=window.PlotDirectorTopology;return W.document.features.filter(window.PlotDirectorMaps.isArea).map(f=>T.outline(f,W.document.features));});outline.forEach((ps,i)=>ps.forEach((p,j)=>assert(Math.hypot(p[0]-independent[i][j][0],p[1]-independent[i][j][1])<1e-7))); + await command('mapsSave');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),0);assert.deepEqual(errors,[]);console.log('PASS authenticated Development shared boundaries: deliberate join, canonical vertex insertion/edit/smoothing, single borders, Undo/Redo, real server Save/reload, exact unjoin, unchanged road anchors and independent persistence. Owned project '+fixture.projectId);await page.close();}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/maps-topology-engine.cjs b/PlotLine.Tests/Browser/maps-topology-engine.cjs new file mode 100644 index 00000000..0e53282e --- /dev/null +++ b/PlotLine.Tests/Browser/maps-topology-engine.cjs @@ -0,0 +1,31 @@ +const assert=require('node:assert/strict'),E=require('../../PlotLine/wwwroot/js/maps-engine.js'),T=require('../../PlotLine/wwwroot/js/maps-topology-engine.js'); +const area=(id,x,y,w=200,h=200)=>({...E.makeFeature('County',x,y,id),geometryJson:JSON.stringify({points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]],coast:'Natural'}),width:w,height:h,isProvisional:false}); +let fs=[area('A',0,0),area('B',200,0)],before=JSON.stringify(fs); +fs=T.join(fs,{areaID:'B',neighborID:'A',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'}); +assert.equal(JSON.stringify([area('A',0,0),area('B',200,0)]),before);let c=T.context(fs),edge=[...c.edges.keys()][0];assert.equal(c.edges.size,1);assert.equal(c.users(edge).length,2); +const a=T.paths(fs[0],c)[1],b=T.paths(fs[1],c).find(cs=>Math.abs(cs[0][0][0]-100)<1e-5&&Math.abs(cs.at(-1)[3][0]-100)<1e-5);assert(b);assert.deepEqual(a.map(q=>q.map(p=>p)),[...b].reverse().map(q=>[...q].reverse())); +let vi=c.area('B').vertexRefs.findIndex(Boolean);fs=T.movePoint(fs,'B',vi,[110,100]);c=T.context(fs);assert(T.controls(fs[0],c).some(p=>p[0]===110&&p[1]===100)); +const index=c.area('A').edgeRefs.indexOf(edge);fs=T.insert(fs,'A',index,0,.5);c=T.context(fs);assert.equal(c.edges.size,2);assert.equal(c.area('A').points.length,5);assert.equal(c.area('B').points.length,5); +const inserted=c.area('A').vertexRefs.findIndex(v=>v&&c.users(v,'vertex').length===2&&c.vertices.get(v)[1]>-90&&c.vertices.get(v)[1]<90);assert(inserted>=0);fs=T.removePoint(fs,'A',inserted);c=T.context(fs);assert.equal(c.edges.size,1);edge=[...c.edges.keys()][0]; +const natural=T.sharedCurves(edge,c);fs=T.smooth(fs,edge,'Gentle');assert.notDeepEqual(T.sharedCurves(edge,fs),natural);fs=T.smooth(fs,edge,'Natural');assert.deepEqual(T.sharedCurves(edge,fs),natural); +const shapeBefore=fs.map(f=>T.outline(f,fs));const detached=T.unjoin(fs,'B',edge);detached.forEach((f,i)=>{const now=T.outline(f,detached);assert.equal(now.length,shapeBefore[i].length);now.forEach((p,j)=>assert(Math.hypot(p[0]-shapeBefore[i][j][0],p[1]-shapeBefore[i][j][1])<1e-7));});assert.equal(T.context(detached).edges.size,0); +const removed=T.remove(fs,new Set(['A']));assert.equal(removed.length,1);assert.equal(T.context(removed).edges.size,0);assert(T.simple(T.outline(removed[0],removed))); +assert.throws(()=>T.reposition(fs,fs.map((f,i)=>({...f,x:f.x+i*10}))),/incompatible/);const shifted=T.reposition(fs,fs.map(f=>({...f,x:f.x+30,y:f.y-10})));assert.equal(T.context(shifted).vertices.size,T.context(fs).vertices.size); +for(const scale of [.2,1,5]){const idx=T.snapIndex(detached,scale),p=T.controls(detached[0],detached)[0],snap=T.snap(idx,[p[0]+5*scale,p[1]],10*scale,{areaID:'B'});assert.equal(snap.type,'vertex');assert.deepEqual(snap.point,p);assert.equal(T.snap(idx,p,10*scale,{disabled:true}),null);} +const idx=T.snapIndex(detached,1),curve=T.edgeCurves(detached[0],1,detached),p=T.point(curve[0],.5),hit=T.snap(idx,[p[0]+2,p[1]],10,{areaID:'B',vertex:false});assert.equal(hit.type,'edge');assert(hit.distance<3); +const copy=T.detachCopies(fs,[{...E.copy(fs[0]),featureID:'copy',x:fs[0].x+50}],new Map([['A','copy']]))[0];assert(!T.linked(copy));assert(!T.hasStore(copy)); +assert.deepEqual(T.context(JSON.parse(JSON.stringify(fs))).commit(),fs); +const withThird=T.movePoint([...fs,area('C',200,200)],'C',0,T.controls(fs[1],fs).find(p=>p[0]<150&&p[1]>0));const three=T.join(withThird,{areaID:'C',neighborID:'B',start:0,end:1,sourceDirection:'forward',neighborDirection:'backward'}),tc=T.context(three),junction=[...tc.vertices.keys()].find(id=>tc.users(id,'vertex').length===3);assert(junction,'three-way junction reuses one authoritative vertex');const ci=tc.area('C').vertexRefs.indexOf(junction),threeMoved=T.movePoint(three,'C',ci,[112,104]);assert.equal(T.context(threeMoved).users(junction,'vertex').length,3); +const reverseInserted=T.insert(fs,'B',T.context(fs).area('B').edgeRefs.indexOf(edge),0,.4);assert.equal(T.context(reverseInserted).edges.size,2);assert(T.simple(T.outline(reverseInserted[0],reverseInserted)));assert(T.simple(T.outline(reverseInserted[1],reverseInserted))); +let target=T.insert([area('D',0,0),area('E',200,0)],'D',1,0,.5);const different=T.join(target,{areaID:'E',neighborID:'D',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'});assert.equal(T.context(different).area('E').points.length,5,'joining adopts neighbour intermediate controls'); +const invalidBefore=JSON.stringify(fs);assert.throws(()=>T.movePoint(fs,'A',T.context(fs).area('A').vertexRefs.findIndex(Boolean),T.controls(fs[0],fs)[0]),/self-intersect|collapse/);assert.equal(JSON.stringify(fs),invalidBefore); +const afterOwnerDelete=T.remove(threeMoved,new Set(['A']));assert.equal(T.context(afterOwnerDelete).edges.size,1);assert(T.context(afterOwnerDelete).vertices.has(junction),'deleting a definition owner transfers surviving junction authority'); +const curvedTarget=[area('snapA',0,0),area('snapB',200,0)],cidx=T.snapIndex(curvedTarget,1),p1=T.point(T.edgeCurves(curvedTarget[0],1,curvedTarget)[0],.2),p2=T.point(T.edgeCurves(curvedTarget[0],1,curvedTarget)[0],.8);let snapped=T.movePoint(curvedTarget,'snapB',0,p1);snapped=T.movePoint(snapped,'snapB',3,p2);const edgeJoined=T.join(snapped,{areaID:'snapB',neighborID:'snapA',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'});assert.equal(T.context(edgeJoined).area('snapA').points.length,6,'joining inserts exact target curve endpoints'); +const G=require('../../PlotLine/wwwroot/js/maps-geography-engine.js'),geoAreas=[{...area('ga',50,390,1040),locationID:1},{...area('gb',1090,390,1040),locationID:2}],geoJoined=T.join(geoAreas,{areaID:'gb',neighborID:'ga',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'}),states=[{locationID:1,status:'Resolved',matchJson:JSON.stringify({Latitude:0,Longitude:0})},{locationID:2,status:'Resolved',matchJson:JSON.stringify({Latitude:0,Longitude:.01})}],compatible=G.position(geoJoined,states,{x:0,y:0,w:1200,h:800});assert(compatible.canApply);for(const[id,p]of T.context(geoJoined).vertices){const q=T.context(compatible.features).vertices.get(id);assert(Math.hypot(q[0]-p[0]-30,q[1]-p[1]-10)<1e-6);} +const conflict=G.position(geoJoined,[states[0],{...states[1],matchJson:JSON.stringify({Latitude:.01,Longitude:.01})}],{x:0,y:0,w:1200,h:800});assert(!conflict.canApply);assert.deepEqual(conflict.features,geoJoined); +const retainedSource=[area('keepA',0,0),area('keepB',200,0)],keepCurve=T.edgeCurves(retainedSource[1],3,retainedSource),kept=T.join(retainedSource,{areaID:'keepB',neighborID:'keepA',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward',retain:'selected'});assert.deepEqual(T.sharedCurves([...T.context(kept).edges.keys()][0],kept),keepCurve,'selected boundary can be retained explicitly'); +assert.throws(()=>T.join([area('tieA',0,0),area('tieB',0,0)],{areaID:'tieA',neighborID:'tieB',start:0,end:2}),/equally|explicit/); +const lock=fs.map(f=>f.featureID==='B'?{...f,isLocked:true}:f);assert.throws(()=>T.smooth(lock,[...T.context(lock).edges.keys()][0],'Rugged'),/Unlock/); +const dash=[area('dashA',0,0),area('dashB',200,0)];E.updateArea(dash[0],g=>g.appearance={borderStyle:'Dashed'});const dashed=T.join(dash,{areaID:'dashB',neighborID:'dashA',start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'}),dc=T.context(dashed),did=[...dc.edges.keys()][0],stroke=T.sharedCurves(did,dc),un=T.unjoin(dashed,'dashB');for(const f of un){const g=T.context(un).area(f.featureID),i=g.edgeStyles.findIndex(s=>s?.borderStyle==='Dashed'),cs=T.edgeCurves(f,i,un),oriented=g.edgeStyles[i].reverseStroke?T.reverse(cs):cs;oriented.forEach((q,j)=>q.forEach((p,k)=>assert(Math.hypot(p[0]-stroke[j][k][0],p[1]-stroke[j][k][1])<1e-7)));} +const many=Array.from({length:2000},(_,i)=>area('grid'+i,(i%50)*300,Math.floor(i/50)*300)),startTime=performance.now(),spatial=T.snapIndex(many,1),built=performance.now();for(let i=0;i<1000;i++){const p=[(i%50)*300-95,Math.floor(i/50)*300-100];assert(T.snap(spatial,p,10,{areaID:'outside'}));}const elapsed=performance.now()-built;assert(elapsed<1500);console.log('Snapping index: 2,000 areas in '+Math.round(built-startTime)+'ms; 1,000 queries in '+Math.round(elapsed)+'ms.'); +console.log('PASS topology join, shared authority/edit/insert/remove, reversible smoothing, exact unjoin, deletion/duplication, compatible/conflicting movement, zoom-independent vertex/curved-edge snapping and persistence.'); diff --git a/PlotLine.Tests/Browser/maps-topology-fixture.cjs b/PlotLine.Tests/Browser/maps-topology-fixture.cjs new file mode 100644 index 00000000..a7369c86 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-topology-fixture.cjs @@ -0,0 +1,7 @@ +// Owned test project only; used by the explicit Development database regression. +const fs=require('node:fs'),{randomUUID}=require('node:crypto'),E=require('../../PlotLine/wwwroot/js/maps-engine.js'),T=require('../../PlotLine/wwwroot/js/maps-topology-engine.js'); +const input=JSON.parse(fs.readFileSync(process.argv[2],'utf8')),places=new Map(input.locations.map(l=>[l.locationName,l.locationID])); +const area=(type,name,x,y)=>{const f={...E.makeFeature(type,x,y,randomUUID()),name,locationID:places.get(name)||null,isProvisional:false};if(E.hasBoundary(f))E.updateArea(f,g=>Object.assign(g,{width:200,height:200,points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]],coast:'Natural'}));else{f.width=200;f.height=200;f.geometryJson=JSON.stringify({points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]],coast:'Natural'});}return f;}; +const a=area('Town','Birmingham',0,0),b=area('Town','Solihull',200,0),c=area('County','Third area',100,200),house={...E.makeFeature('House',0,0,randomUUID()),name:'Boundary house',locationID:places.get('Boundary house'),isProvisional:false},road={...E.makeFeature('Road',100,0,randomUUID()),name:'Boundary road',startFeatureID:a.featureID,endFeatureID:b.featureID,isProvisional:false}; +c.width=400;c.geometryJson=JSON.stringify({points:[[-.5,-.5],[0,-.5],[.5,-.5],[.5,.5],[-.5,.5]],coast:'Natural'});const before=[a,b,c,house,road];let after=T.join(before,{areaID:b.featureID,neighborID:a.featureID,start:3,end:0,sourceDirection:'forward',neighborDirection:'backward'});after=T.join(after,{areaID:c.featureID,neighborID:b.featureID,start:1,end:2,sourceDirection:'forward',neighborDirection:'backward'});after=T.join(after,{areaID:c.featureID,neighborID:a.featureID,start:4,end:0,sourceDirection:'forward',neighborDirection:'backward'});let model=T.context(after),junction=[...model.vertices.keys()].find(id=>model.users(id,'vertex').length===3);after=T.movePoint(after,c.featureID,model.area(c.featureID).vertexRefs.indexOf(junction),[108,104]);model=T.context(after);const i=model.area(a.featureID).edgeRefs.findIndex(Boolean);after=T.insert(after,a.featureID,i,0,.5);model=T.context(after);after=T.smooth(after,[...model.edges.keys()][0],'Gentle'); +fs.writeFileSync(process.argv[3],JSON.stringify({...input,before,after}),{mode:0o600}); diff --git a/PlotLine.Tests/Browser/maps-topology.cjs b/PlotLine.Tests/Browser/maps-topology.cjs new file mode 100644 index 00000000..4fdae266 --- /dev/null +++ b/PlotLine.Tests/Browser/maps-topology.cjs @@ -0,0 +1,30 @@ +const{chromium}=require('playwright'),assert=require('node:assert/strict');const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true])for(const theme of ['modern-light','modern-dark']){ + const context=await browser.newContext({viewport:{width:1700,height:1150}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));let saved; + await page.route('**/Maps/Save',r=>{saved=r.request().postDataJSON();saved.map.revision++;return r.fulfill({json:saved});}); + await page.goto(base+'/fixture?page=maps&theme='+theme);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); + const ids=await page.evaluate(()=>{const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMaps,ids={a:crypto.randomUUID(),b:crypto.randomUUID()};W.edit(()=>{W.document.features=[['a','Birmingham',0],['b','Solihull',210]].map(([id,name,x])=>({...E.makeFeature('County',x,0,ids[id]),name,width:200,height:200,isProvisional:false,geometryJson:JSON.stringify({points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]],coast:'Natural',appearance:{fillColor:id==='a'?'#f3c96c':'#6ec1db',fillOpacity:.35,borderColor:id==='a'?'#634537':'#246e89',borderWidth:2,borderStyle:id==='a'?'Dashed':'Solid'}})}));});W.fit();return ids;}); + const data=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),select=id=>page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),id),command=id=>page.evaluate(id=>document.getElementById(id).click(),id); + await select(ids.b);await page.locator('[data-action=shape]').click(); + async function drag(index,p,alt=false){const target=page.locator(`[data-handle=point][data-index="${index}"]`),box=await target.boundingBox(),world=await page.evaluate(p=>new DOMPoint(...p).matrixTransform(document.getElementById('mapsCanvas').getScreenCTM()).toJSON(),p);if(alt)await page.keyboard.down('Alt');await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(world.x,world.y,{steps:5});if(!alt)assert(await page.locator('.maps-snap-indicator').count()||index!==0&&index!==3);await page.mouse.up();if(alt)await page.keyboard.up('Alt');} + await drag(3,[100,100]);await drag(0,[100,-100]);assert.equal(await page.evaluate(()=>window.PlotDirectorTopology.context(window.PlotDirectorMapWorkspace.document.features).edges.size),0,'snapping is not joining'); + const snapped=await data();await page.locator('#mapsDetailContent [data-topology=join]').click();const dialog=page.locator('dialog[open]');await dialog.locator('[name=start]').selectOption('3');await dialog.locator('[name=end]').selectOption('0');await dialog.getByRole('button',{name:'Join boundaries',exact:true}).click();assert(!await dialog.count()); + assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),1);assert.equal(await page.locator('#mapsScene [data-shared-edge-id] path:not(.maps-shared-hit)').count(),1,'one authoritative border stroke');const joined=await data();await command('mapsUndo');assert.equal(await data(),snapped);await command('mapsRedo');assert.equal(await data(),joined);await select(ids.b);await page.locator('[data-action=shape]').click(); + await page.locator('[data-topology=insert]').click();assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),2);const index=await page.evaluate(id=>{const T=window.PlotDirectorTopology,c=T.context(window.PlotDirectorMapWorkspace.document.features),g=c.area(id);return g.vertexRefs.findIndex(v=>v&&Math.abs(c.vertices.get(v)[1])<50);},ids.b);assert(index>=0); + await drag(index,[140,0],true);assert(await page.evaluate(()=>{const T=window.PlotDirectorTopology,c=T.context(window.PlotDirectorMapWorkspace.document.features);return [...c.vertices].some(([id,p])=>Math.abs(p[0]-140)<1e-4&&Math.abs(p[1])<1e-4&&c.users(id,'vertex').length===2);}),JSON.stringify(await page.evaluate(()=>({status:document.getElementById('mapsStatus').textContent,vertices:[...window.PlotDirectorTopology.context(window.PlotDirectorMapWorkspace.document.features).vertices]})))); + const natural=await page.locator('#mapsScene .maps-shared-edge').first().innerHTML();await page.locator('[data-shared-smoothing]').selectOption('Gentle');await page.locator('[data-shared-smoothing]').selectOption('Rugged');await page.locator('[data-shared-smoothing]').selectOption('Natural');assert.equal(await page.locator('#mapsScene .maps-shared-edge').first().innerHTML(),natural); + await page.locator(`[data-handle=point][data-index="${index}"]`).focus();await page.keyboard.press('Delete');assert.equal(await page.locator('#mapsScene [data-shared-edge-id]').count(),1); + const beforeMove=await data();await page.locator(`[data-feature-id="${ids.b}"]`).focus();await page.keyboard.press('ArrowRight');assert.equal(await data(),beforeMove);assert.match(await page.locator('#mapsStatus').innerText(),/Unjoin/); + await command('mapsSave');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');assert(saved.features.some(f=>f.geometryJson.includes('topologyStore'))); + await page.route('**/fixture?**',async route=>{const response=await route.fetch();let html=await response.text();html=html.replace(/("; + surface += ""; } if (context.Request.Query["page"] == "floorplans") { diff --git a/PlotLine/Services/MapAreaGeometryValidation.cs b/PlotLine/Services/MapAreaGeometryValidation.cs index 6d1f1084..5cbe224d 100644 --- a/PlotLine/Services/MapAreaGeometryValidation.cs +++ b/PlotLine/Services/MapAreaGeometryValidation.cs @@ -26,7 +26,7 @@ internal static class MapAreaGeometryValidation if(boundary.TryGetProperty("appearance",out var style)&&!ValidAppearance(style))return "Check boundary colours, opacity and border style."; return null; } - private static bool ValidAppearance(JsonElement style) + internal static bool ValidAppearance(JsonElement style) { if(style.ValueKind==JsonValueKind.Null)return true; if(style.ValueKind!=JsonValueKind.Object)return false; diff --git a/PlotLine/Services/MapTopologyValidation.cs b/PlotLine/Services/MapTopologyValidation.cs new file mode 100644 index 00000000..a0ac5bac --- /dev/null +++ b/PlotLine/Services/MapTopologyValidation.cs @@ -0,0 +1,56 @@ +using System.Text.Json; +using PlotLine.Models; +namespace PlotLine.Services; + +// Shared definitions are scoped to one map and carried by its existing feature GeometryJson records. +internal static class MapTopologyValidation +{ + static readonly string[] Coasts=["Natural","Gentle","Rugged","Cliffs","Fjords","Marsh/Delta"]; + static bool Id(string? id)=>Guid.TryParse(id,out var value)&&value!=Guid.Empty; + static bool Pair(JsonElement p,double max)=>p.ValueKind==JsonValueKind.Array&&p.GetArrayLength()==2&&p.EnumerateArray().All(v=>v.ValueKind==JsonValueKind.Number&&v.TryGetDouble(out var n)&&double.IsFinite(n)&&Math.Abs(n)<=max); + static bool Shape(JsonElement s)=>s.ValueKind==JsonValueKind.Array&&s.GetArrayLength() is >0 and <=320&&s.EnumerateArray().All(row=>row.ValueKind==JsonValueKind.Array&&row.GetArrayLength()==3&&row.EnumerateArray().All(p=>Pair(p,10000)))&&Math.Abs(s[s.GetArrayLength()-1][2][0].GetDouble()-1)<1e-6&&Math.Abs(s[s.GetArrayLength()-1][2][1].GetDouble())<1e-6; + static bool Coast(JsonElement obj,string key)=>obj.TryGetProperty(key,out var c)&&c.ValueKind==JsonValueKind.String&&Coasts.Contains(c.GetString()); + static bool Style(JsonElement s)=>s.ValueKind==JsonValueKind.Object&&s.TryGetProperty("theme",out var theme)&&theme.ValueKind==JsonValueKind.String&&new[]{"settlement","region","terrain"}.Contains(theme.GetString())&&(!s.TryGetProperty("reverseStroke",out var reverse)||reverse.ValueKind is JsonValueKind.True or JsonValueKind.False)&&MapAreaGeometryValidation.ValidAppearance(s); + static double Factor(string? coast)=>coast switch{"Gentle"=>.5,"Rugged"=>1.7,"Cliffs"=>1.3,"Fjords"=>2,"Marsh/Delta"=>1.2,_=>1}; + static bool WorldShape(JsonElement shape,double[] a,double[] b,string? coast,string? baseCoast) + { + var dx=b[0]-a[0];var dy=b[1]-a[1];var ratio=Factor(coast)/Factor(baseCoast); + foreach(var row in shape.EnumerateArray())foreach(var p in row.EnumerateArray()){var t=p[0].GetDouble();var u=p[1].GetDouble()*ratio+Math.Max(0,Factor(coast)-Factor(baseCoast))*.015*Math.Sin(t*Math.PI*2)*Math.Sin(t*Math.PI);var x=a[0]+dx*t-dy*u;var y=a[1]+dy*t+dx*u;if(!double.IsFinite(x)||!double.IsFinite(y)||Math.Abs(x)>100000||Math.Abs(y)>100000)return false;} + return true; + } + public static string? Validate(IReadOnlyList features) + { + var roots=new Dictionary();var vertices=new Dictionary();var edges=new Dictionary();var usedVertices=new HashSet();var edgeUsers=new Dictionary>(); + try + { + foreach(var f in features){using var parsed=JsonDocument.Parse(f.GeometryJson);var g=parsed.RootElement.Clone();roots[f.FeatureID]=g; + if(!g.TryGetProperty("topologyStore",out var store))continue; + if(!(f.GeometryClass=="Area"||f.GeometryClass=="Marker"&&g.TryGetProperty("boundary",out var boundaryValue)&&boundaryValue.ValueKind==JsonValueKind.Object))return "Shared definitions must belong to a geographical area."; + if(store.ValueKind!=JsonValueKind.Object||!store.TryGetProperty("version",out var version)||!version.TryGetInt32(out var number)||number!=1||!store.TryGetProperty("vertices",out var vs)||vs.ValueKind!=JsonValueKind.Object||!store.TryGetProperty("edges",out var es)||es.ValueKind!=JsonValueKind.Object)return "Invalid shared boundary definitions."; + foreach(var v in vs.EnumerateObject())if(!Id(v.Name)||!Pair(v.Value,100000)||!vertices.TryAdd(v.Name,v.Value))return "Invalid or duplicate shared vertex."; + foreach(var e in es.EnumerateObject())if(!Id(e.Name)||e.Value.ValueKind!=JsonValueKind.Object||!edges.TryAdd(e.Name,e.Value))return "Invalid or duplicate shared edge."; + } + foreach(var (id,e) in edges){if(!e.TryGetProperty("a",out var a)||a.ValueKind!=JsonValueKind.String||!e.TryGetProperty("b",out var b)||b.ValueKind!=JsonValueKind.String||a.GetString()==b.GetString()||!vertices.TryGetValue(a.GetString()??"",out var va)||!vertices.TryGetValue(b.GetString()??"",out var vb)||!e.TryGetProperty("shape",out var shape)||!Shape(shape)||!Coast(e,"coast")||!Coast(e,"baseCoast")||!e.TryGetProperty("style",out var style)||!Style(style))return "A shared edge has invalid vertices, smoothing or appearance."; + var dx=vb[0].GetDouble()-va[0].GetDouble();var dy=vb[1].GetDouble()-va[1].GetDouble();if(dx*dx+dy*dy<1e-10)return "A shared edge cannot collapse to one point."; + if(!WorldShape(shape,[va[0].GetDouble(),va[1].GetDouble()],[vb[0].GetDouble(),vb[1].GetDouble()],e.GetProperty("coast").GetString(),e.GetProperty("baseCoast").GetString()))return "Shared curves exceed safe canvas limits."; + edgeUsers[id]=[]; + } + foreach(var f in features){var g=roots[f.FeatureID];var boundary=g.TryGetProperty("boundary",out var value)&&value.ValueKind==JsonValueKind.Object;var area=boundary?value:g; + if(!area.TryGetProperty("vertexRefs",out var vr)&&!area.TryGetProperty("edgeRefs",out _)&&!area.TryGetProperty("edgeShapes",out _)&&!area.TryGetProperty("edgeStyles",out _))continue; + if(!(f.GeometryClass=="Area"||f.GeometryClass=="Marker"&&boundary&&MapAreaGeometryValidation.SettlementTypes.Contains(f.Type))||!area.TryGetProperty("points",out var points)||points.ValueKind!=JsonValueKind.Array||points.GetArrayLength() is <3 or >64)return "Shared geometry requires a valid geographical area."; + var n=points.GetArrayLength();var vrefs=new string?[n];var erefs=new string?[n]; + if(area.TryGetProperty("vertexRefs",out vr)){if(vr.ValueKind!=JsonValueKind.Array||vr.GetArrayLength()!=n)return "Shared vertex references do not match the boundary.";for(var i=0;iv is not null).Distinct().Count()!=vrefs.Count(v=>v is not null)||erefs.Where(e=>e is not null).Distinct().Count()!=erefs.Count(e=>e is not null))return "A simple boundary cannot repeat a shared vertex or edge."; + for(var i=0;is.ValueKind!=JsonValueKind.Null&&!Style(s)))return "Invalid boundary edge appearance.";} + } + if(vertices.Keys.Any(v=>!usedVertices.Contains(v))||edgeUsers.Values.Any(users=>users.Count<2))return "Remove unreferenced shared geometry before saving."; + return null; + } + catch(Exception ex) when(ex is JsonException or InvalidOperationException or KeyNotFoundException or ArgumentException){return "Invalid shared boundary data.";} + } +} diff --git a/PlotLine/Services/MapValidation.cs b/PlotLine/Services/MapValidation.cs index 323b8a03..60cb4cf1 100644 --- a/PlotLine/Services/MapValidation.cs +++ b/PlotLine/Services/MapValidation.cs @@ -47,6 +47,8 @@ public static class MapValidation } catch (JsonException) { return "Invalid shape data."; } } + var topologyError=MapTopologyValidation.Validate(d.Features); + if(topologyError is not null)return topologyError; if (d.Relationships.Select(x => x.RelationshipID).Distinct().Count() != d.Relationships.Count) return "Relationship identifiers must be unique."; foreach (var r in d.Relationships) if (!ids.Contains(r.SourceID) || !ids.Contains(r.TargetID) || r.SourceID == r.TargetID diff --git a/PlotLine/Views/Maps/Index.cshtml b/PlotLine/Views/Maps/Index.cshtml index 7e330c8e..74fce16d 100644 --- a/PlotLine/Views/Maps/Index.cshtml +++ b/PlotLine/Views/Maps/Index.cshtml @@ -25,6 +25,8 @@ + + @@ -87,6 +89,7 @@ + diff --git a/PlotLine/wwwroot/css/maps-workspace.css b/PlotLine/wwwroot/css/maps-workspace.css index afea0f9e..49c4c170 100644 --- a/PlotLine/wwwroot/css/maps-workspace.css +++ b/PlotLine/wwwroot/css/maps-workspace.css @@ -53,3 +53,5 @@ html[data-standalone=true]:has(#mapsApp) .pd-ribbon-panel:not([hidden]){min-heig .maps-details fieldset{border:0;padding:0;margin:0;min-width:0} .maps-details fieldset:disabled{opacity:.65} .maps-details [data-select-map-piece]{margin:2px;font-size:.82rem} +.maps-topology-tools{border-top:1px solid var(--map-line);margin-top:10px;padding-top:7px}.maps-topology-tools label:has([type=checkbox]){flex-direction:row;align-items:center}.maps-shared-edge{cursor:pointer}.maps-shared-edge.is-selected>path:not(.maps-shared-hit){stroke:var(--maps-selection,#136883);stroke-width:3}.maps-shared-vertex{fill:#d9bdee!important;stroke:var(--maps-selection,#136883)}.maps-snap-indicator{fill:none;stroke:var(--maps-selection,#136883);stroke-width:2;stroke-dasharray:3 2;vector-effect:non-scaling-stroke} +.maps-join-endpoint{stroke:#aa4f24!important;stroke-width:3} diff --git a/PlotLine/wwwroot/js/maps-engine.js b/PlotLine/wwwroot/js/maps-engine.js index 76856a85..a3665f5c 100644 --- a/PlotLine/wwwroot/js/maps-engine.js +++ b/PlotLine/wwwroot/js/maps-engine.js @@ -6,6 +6,7 @@ })(typeof globalThis !== 'undefined' ? globalThis : this, function () { 'use strict'; const library = []; + let topologyAdapter=null;const setTopologyAdapter=api=>topologyAdapter=api; function group(category, names, geometryClass = 'Marker', layer = 'Places', symbol = '◆') { names.split('|').forEach(type => library.push({ type, category, geometryClass, layer, symbol })); } @@ -49,7 +50,7 @@ for(const f of features){ if(f.geometryClass!=='Area'||f.layer==='Regions'||Number.isFinite(geometry(f).drawingOrder))continue; const size=Math.abs(f.width*f.height),possible=settlements.filter(s=>{const b=areaFrame(s);return size>Math.abs(b.width*b.height);}); - if(!possible.length)continue;const polygon=outline(f); + if(!possible.length)continue;const polygon=outline(f,features); if(possible.some(s=>{const b=areaFrame(s);return [[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]].every(p=>pointInPolygon(localToWorld(b,p),polygon));}))priorities.set(f.featureID,99999/(1+size/1000)); } return [...features].sort((a,b)=>priorities.get(a.featureID)-priorities.get(b.featureID)||(a.zOrder||0)-(b.zOrder||0)||a.featureID.localeCompare(b.featureID)); @@ -122,13 +123,14 @@ function translate(f,dx,dy){f.x+=dx;f.y+=dy;} function moveAnchor(f,x,y){if(f.isLocked)return false;const dx=x-f.x,dy=y-f.y;if(hasBoundary(f))updateArea(f,b=>{b.offsetX-=dx;b.offsetY-=dy;});f.x=x;f.y=y;return true;} function featureBounds(f,features=[]){ - const frame=areaFrame(f),pts=isArea(f)?coastline(frame).map(p=>localToWorld(frame,p)):f.geometryClass==='Path'?pathPoints(f,features):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]]; + const frame=areaFrame(f),pts=isArea(f)?(topologyAdapter&&features.length&&(topologyAdapter.linked(f)||areaGeometry(f).edgeShapes)?topologyAdapter.outline(f,features):coastline(frame).map(p=>localToWorld(frame,p))):f.geometryClass==='Path'?pathPoints(f,features):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]]; if(!pts.length)pts.push(localToWorld(frame,[-.5,-.5]),localToWorld(frame,[.5,.5])); if(hasBoundary(f))pts.push([f.x,f.y]); return {left:Math.min(...pts.map(p=>p[0])),right:Math.max(...pts.map(p=>p[0])),top:Math.min(...pts.map(p=>p[1])),bottom:Math.max(...pts.map(p=>p[1]))}; } // Sample the same cubic segments used by curve(); containment follows the rendered, smoothed outline. - function outline(f){ + function outline(f,features=[]){ + if(topologyAdapter&&features.length&&(topologyAdapter.linked(f)||areaGeometry(f).edgeShapes))return topologyAdapter.outline(f,features); const frame=areaFrame(f),p=coastline(frame).map(p=>localToWorld(frame,p)),result=[],n=p.length; for(let i=0;i[area.featureID,{area,bounds:null,polygon:null}])); for(const f of placed){const key=Math.floor(f.x/cell)+','+Math.floor(f.y/cell);if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(f);} function bounds(record){ - if(!record.bounds){const b=featureBounds(record.area),dx=(b.right-b.left)/6+1e-7,dy=(b.bottom-b.top)/6+1e-7;record.bounds={left:b.left-dx,right:b.right+dx,top:b.top-dy,bottom:b.bottom+dy};} + if(!record.bounds){const b=featureBounds(record.area,features),dx=(b.right-b.left)/6+1e-7,dy=(b.bottom-b.top)/6+1e-7;record.bounds={left:b.left-dx,right:b.right+dx,top:b.top-dy,bottom:b.bottom+dy};} return record.bounds; } function contains(record,f){ if(record.area===f)return false; const b=bounds(record);if(f.xb.right||f.yb.bottom)return false; - record.polygon||=outline(record.area); + record.polygon||=outline(record.area,features); return record.polygon.length>=3&&pointInPolygon([f.x,f.y],record.polygon); } // Lazy lists avoid materialising an O(n²) containment graph for heavily overlapping maps. @@ -231,6 +233,7 @@ if(!r.connection&&((r.direction&&suggestedDirection(a,b)!==r.direction)||(r.relativeDistance&&Math.abs(Math.hypot(a.x-b.x,a.y-b.y)-spacing(a,b,r))>spacing(a,b,r)*.5)))warnings.push(`${a.name} ${r.direction} of ${b.name}`); } result.forEach(f=>{if(movable(f)){f.isPlaced=true;if(!anchored.has(f.featureID)){f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}}}); + if(topologyAdapter&&features.some(topologyAdapter.hasStore)){const adjusted=topologyAdapter.reposition(features,result);result.splice(0,result.length,...adjusted);} return {features:result,warnings}; } // Shared endpoint similarity transform: proportional along-line and perpendicular offsets. @@ -263,5 +266,5 @@ f.width*=transform.ratio;f.height*=transform.ratio;f.rotation=normalAngle(f.rotation+transform.angle*180/Math.PI);return f; } const normalAngle=value=>((value+180)%360+360)%360-180; - return {connectionTransform,transformAnchoredPath,drawingPriority,drawingOrder,reorder,settlements,isSettlement,hasBoundary,isArea,convertToArea,areaGeometry,updateArea,areaFrame,worldToLocal,translate,moveAnchor,featureBounds,outline,pointInPolygon,containment,fitBoundary,transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange}; + return {setTopologyAdapter,connectionTransform,transformAnchoredPath,drawingPriority,drawingOrder,reorder,settlements,isSettlement,hasBoundary,isArea,convertToArea,areaGeometry,updateArea,areaFrame,worldToLocal,translate,moveAnchor,featureBounds,outline,pointInPolygon,containment,fitBoundary,transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange}; }); diff --git a/PlotLine/wwwroot/js/maps-geography-engine.js b/PlotLine/wwwroot/js/maps-geography-engine.js index c86fbaa2..786f4591 100644 --- a/PlotLine/wwwroot/js/maps-geography-engine.js +++ b/PlotLine/wwwroot/js/maps-geography-engine.js @@ -3,6 +3,7 @@ (function(root){ 'use strict'; const E=typeof module!=='undefined'&&module.exports?require('./maps-engine.js'):root.PlotDirectorMaps; + const T=typeof module!=='undefined'&&module.exports?require('./maps-topology-engine.js'):root.PlotDirectorTopology; function position(features,states,bounds,locations=[]){ const rad=Math.PI/180,R=6371008.8,wrap=a=>Math.atan2(Math.sin(a),Math.cos(a)); if(![bounds.x,bounds.y,bounds.w,bounds.h].every(Number.isFinite)||bounds.w<=0||bounds.h<=0)throw Error('Map area is unavailable.'); @@ -67,6 +68,7 @@ } for(const f of output)if(![f.x,f.y].every(n=>Number.isFinite(n)&&Math.abs(n)<=100000)){blocked=true;attention.push({featureID:f.featureID,name:f.name,reason:'Proposed position exceeds safe canvas limits'});} for(const f of output)if(f.geometryClass==='Path'&&JSON.stringify(f)!==JSON.stringify(original.get(f.featureID))&&!paths.some(p=>p.featureID===f.featureID))paths.push({name:f.name,featureID:f.featureID}); + if(T)try{const adjusted=T.reposition(features,output);output.splice(0,output.length,...adjusted);}catch(error){blocked=true;attention.push({featureID:'shared-geometry',name:'Shared boundaries',reason:error.message});} // Inherited pieces are no longer reported as pending objects that will stay behind. const following=new Set(inherited.map(p=>p.featureID)); const kept=skipped.filter(p=>!following.has(p.featureID)); diff --git a/PlotLine/wwwroot/js/maps-story.js b/PlotLine/wwwroot/js/maps-story.js index 817f3310..c205da58 100644 --- a/PlotLine/wwwroot/js/maps-story.js +++ b/PlotLine/wwwroot/js/maps-story.js @@ -111,6 +111,7 @@ ordered.forEach(([key],i)=>{const n=overlayNodes.get(key);if(layer.children[i]!==n)layer.insertBefore(n,layer.children[i]||null);}); const fade=['plot','chapter','character','scene'].includes(state.lens); document.querySelectorAll('#mapsScene [data-feature-id], #mapsScene [data-boundary-feature-id], #mapsLabels [data-label-feature-id]').forEach(n=>{const f=features.get(n.dataset.featureId||n.dataset.boundaryFeatureId||n.dataset.labelFeatureId);n.classList.toggle('map-story-muted',fade&&!!f?.locationID&&!inUse.has(f.featureID));}); + const shared=document.querySelectorAll('#mapsScene [data-shared-edge-id]');if(shared.length&&window.PlotDirectorTopology){const topology=window.PlotDirectorTopology.context(W.document.features);shared.forEach(n=>n.classList.toggle('map-story-muted',fade&&topology.users(n.dataset.sharedEdgeId).every(id=>!!features.get(id)?.locationID&&!inUse.has(id))));} } function locationLinks(p,scene){let html='';if(p.detailMapID)html+=`Open ${p.status==='On ancestor map'?'ancestor':'detailed'} map ↳`; const floor=scene?.floorPlanID||p.floorPlanID;if(floor)html+=`${scene?.floorPlanID===floor?'Open Floor Plan Story / occupancy':'Open linked Floor Plan'}`; diff --git a/PlotLine/wwwroot/js/maps-topology-engine.js b/PlotLine/wwwroot/js/maps-topology-engine.js new file mode 100644 index 00000000..e7785e1d --- /dev/null +++ b/PlotLine/wwwroot/js/maps-topology-engine.js @@ -0,0 +1,127 @@ +/* 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[((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;kedgeCurves(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(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])+EPSMath.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;i128){for(let j=0;jedgeId&&dist(c.vertices.get(c.edges.get(edgeId).a),c.vertices.get(c.edges.get(edgeId).b))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;ifreeze(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;iMath.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||ds.box.right+tolerance||p[1]s.box.bottom+tolerance)continue;const n=nearestOnCurves([s.q],p);if(n.distance<=tolerance&&(!best||n.distancen)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;kdist(p,q)=0)return i;let best=null;paths(c.byId.get(id),c).forEach((cs,index)=>{const hit=nearestOnCurves(cs,p,60);if(!best||hit.distanceEPS)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)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)dist(p,b)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(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}; +}); diff --git a/PlotLine/wwwroot/js/maps-workspace.js b/PlotLine/wwwroot/js/maps-workspace.js index 8da5426e..eaba6567 100644 --- a/PlotLine/wwwroot/js/maps-workspace.js +++ b/PlotLine/wwwroot/js/maps-workspace.js @@ -1,24 +1,25 @@ (() => { 'use strict'; - const E=window.PlotDirectorMaps, boot=JSON.parse(document.getElementById('mapsBootstrap').textContent); + const E=window.PlotDirectorMaps,T=window.PlotDirectorTopology, boot=JSON.parse(document.getElementById('mapsBootstrap').textContent); const $=id=>document.getElementById(id),app=$('mapsApp'),svg=$('mapsCanvas'),scene=$('mapsScene'),handles=$('mapsHandles'); const ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const guid=()=>crypto.randomUUID(), clone=E.copy;const windowParams=new URLSearchParams(location.search),detachedQuery=windowParams.get('detached')==='true'?'&detached=true'+(windowParams.get('workspace')?'&workspace='+encodeURIComponent(windowParams.get('workspace')):''):''; let savedDocument=clone(boot.document),leavePending=null,rotationEdit=null; let doc=boot.document,mode='create',selected=new Set(),pending=null,dirty=false,busy=false,history=[],future=[],preview=null,shapeEdit=false,parentFeature=null,settlementMode='whole'; let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null; - const hiddenLayers=new Set(),nodes=new Map(),boundaryNodes=new Map(),labelNodes=new Map(); + const hiddenLayers=new Set(),nodes=new Map(),boundaryNodes=new Map(),labelNodes=new Map(),sharedNodes=new Map(); + let selectedEdge=null,joinEnds=[],snapVertex=true,snapEdge=true,snapHint=null,renderOrder=[]; const labels=svgNode('g',{id:'mapsLabels','pointer-events':'none'});scene.after(labels); let containmentDirty=true,containmentCache=null; function containment(){if(containmentDirty||!containmentCache){containmentCache=E.containment(doc?.features||[]);containmentDirty=false;}return containmentCache;} - const targetID=node=>node?.dataset.featureId||node?.dataset.boundaryFeatureId; + const targetID=node=>node?.dataset.featureId||node?.dataset.boundaryFeatureId||node?.dataset.sharedAreaId; const token=document.querySelector('input[name="__RequestVerificationToken"]').value; function status(message,error=false){$('mapsStatus').textContent=message;$('mapsStatus').dataset.error=String(error);} function snapshot(){return JSON.stringify(doc);} function checkpoint(){if(!doc)return;history.push(snapshot());if(history.length>70)history.shift();future=[];} function changed(message='Unsaved changes'){containmentDirty=true;dirty=true;status(message);updateButtons();} - function edit(action){if(!doc||mode!=='create'||preview||busy)return;checkpoint();action();changed();render();details();locations();} - function updateButtons(){ document.querySelectorAll('[data-map-order]').forEach(b=>{b.hidden=mode!=='create';b.disabled=!doc||busy||!!preview||!doc.features.some(f=>selected.has(f.featureID)&&!f.isLocked);}); $('mapsUndo').disabled=!history.length||!!preview||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsRedo').disabled=!future.length||!!preview||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsSave').disabled=!doc||busy||!!preview||!!window.PlotDirectorMapAppearance?.adjusting||mode!=='create'; } + function edit(action){if(!doc||mode!=='create'||preview||busy)return;const before=snapshot(),redo=future.slice();checkpoint();try{action();changed();}catch(error){doc=JSON.parse(before);history.pop();future=redo;status(error.message,true);}render();details();locations();} + function updateButtons(){ const area=doc?.features.find(f=>selected.has(f.featureID));document.querySelectorAll('[data-topology][data-pwa-context]').forEach(b=>{b.hidden=mode!=='create';b.disabled=!area||!E.isArea(area)||selected.size!==1||area.isLocked||busy||!!preview||(b.dataset.topology==='unjoin'&&!T.linked(area));}); document.querySelectorAll('[data-map-order]').forEach(b=>{b.hidden=mode!=='create';b.disabled=!doc||busy||!!preview||!doc.features.some(f=>selected.has(f.featureID)&&!f.isLocked);}); $('mapsUndo').disabled=!history.length||!!preview||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsRedo').disabled=!future.length||!!preview||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsSave').disabled=!doc||busy||!!preview||!!window.PlotDirectorMapAppearance?.adjusting||mode!=='create'; } async function request(action,data,json=false){ const response=await fetch('/Maps/'+action,{method:'POST',headers:{'RequestVerificationToken':token,...(json?{'Content-Type':'application/json'}:{})},body:json?JSON.stringify(data):new URLSearchParams(data)}); if(response.redirected)throw new Error('Your session or subscription needs attention. Open your account in another tab; your edits remain here.'); @@ -74,6 +75,7 @@ },true); function svgNode(tag,attrs={}){const node=document.createElementNS(ns,tag);for(const[k,v]of Object.entries(attrs))node.setAttribute(k,v);return node;} function applyView(){svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);$('mapsZoom').textContent=Math.round(1200/view.w*100)+'%';render();} + function scaleForSnap(){const m=svg.getScreenCTM();return 1/Math.hypot(m.a,m.b);} function world(event){const p=new DOMPoint(event.clientX,event.clientY).matrixTransform(svg.getScreenCTM().inverse());return [p.x,p.y];} function fit(items=doc?.features||[]){const reference=arguments.length===0?window.PlotDirectorMapAppearanceEngine?.reference(doc?.map):null;if(reference?.isVisible)items=[...items,{...reference,geometryClass:'Area',geometryJson:JSON.stringify({points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]]})}];if(!items.length){view={x:-600,y:-400,w:1200,h:800};applyView();return;} let left=Infinity,top=Infinity,right=-Infinity,bottom=-Infinity; @@ -81,7 +83,7 @@ let w=Math.max(350,right-left+180),h=Math.max(250,bottom-top+180),ratio=svg.clientWidth/Math.max(1,svg.clientHeight);if(w/h/^#[0-9a-f]{6}$/i.test(value||'')?value:fallback; const fills={'Forest':'url(#map-forest)','Mountain Range':'url(#map-mountains)','Hills':'url(#map-hills)','Marsh':'url(#map-marsh)','Farmland':'url(#map-farmland)','Lake':'#91c0d0','Desert':'#e9d499','Plains':'#d8dcb1'}; @@ -91,16 +93,25 @@ const width=Number.isFinite(a.borderWidth)?Math.max(0,Math.min(30,a.borderWidth)):2; const dash=({'Solid':'','Dashed':'8 5','Dotted':'2 5'})[a.borderStyle]??(overlay?'8 5':''); const points=E.coastline(frame).map(p=>[p[0]*frame.width,p[1]*frame.height]); + if(topology&&(T.linked(f)||geometry.edgeShapes?.some(Boolean))){const edges=T.paths(f,topology),d=edges.map((q,i)=>T.path(q,i===0)).join(' ')+' Z';let result=``;edges.forEach((q,i)=>{if(geometry.edgeRefs?.[i])return;const style=geometry.edgeStyles?.[i];result+=``;});return result;} return ``; } + function borderStyle(a){const colour=/^#[0-9a-f]{6}$/i.test(a.borderColor||'')?a.borderColor:a.theme==='settlement'?'var(--maps-settlement-line,#62507c)':a.theme==='region'?'var(--maps-region-line,#80699b)':'var(--maps-terrain-line,#91a087)',width=Number.isFinite(a.borderWidth)?Math.max(0,Math.min(30,a.borderWidth)):2,dash=({'Solid':'','Dashed':'8 5','Dotted':'2 5'})[a.borderStyle]??(a.theme==='region'?'8 5':'');return `stroke="${colour}" stroke-width="${width}" ${dash?`stroke-dasharray="${dash}"`:''} stroke-linejoin="round"`;} + function topologyEdit(operation){if(!doc||busy||preview||mode!=='create')return;try{const features=operation(doc.features);safeEdit(()=>doc.features=features);return true;}catch(error){status(error.message,true);return false;}} + function movementBlocked(f){if(E.isArea(f)&&T.linked(f)){status('This area has shared boundaries. Unjoin them before moving, resizing or rotating it independently; shared vertices remain editable.',true);return true;}return false;} + function boundaryTools(f){const g=E.areaGeometry(f),ids=[...new Set((g.edgeRefs||[]).filter(Boolean))],c=T.context(doc.features);if(selectedEdge&&!ids.includes(selectedEdge))selectedEdge=null;selectedEdge||=ids[0]||null;return `

10 pixel tolerance. Hold Alt while dragging a point to disable snapping; Alt + click still cycles overlapping pieces. Snapping does not join areas.

${ids.length?`${ids.length>1?'':''}

Shared curves use the retained area's border style. Edit their points from either area; locked neighbours must be unlocked first.

`:''}
`;} + function joinDialog(){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||!E.isArea(f)||f.isLocked)return;const others=doc.features.filter(x=>x.featureID!==f.featureID&&E.isArea(x)&&!x.isLocked);if(!others.length){status('Add another unlocked geographical area first.');return;}const points=T.controls(f,doc.features),dialog=document.createElement('dialog');dialog.innerHTML=`

Join boundaries

Snap two vertices to the neighbouring boundary first, then choose the sections to join. Existing shared sections are protected.

${[['start','First endpoint',joinEnds[0]??0],['end','Second endpoint',joinEnds[1]??1]].map(([key,label,current])=>``).join('')}${[['sourceDirection','Section on selected area'],['neighborDirection','Section on neighbour']].map(([key,label])=>``).join('')}

`;app.append(dialog);dialog.showModal();dialog.querySelector('[data-cancel]').onclick=()=>dialog.close();dialog.onclose=()=>dialog.remove();dialog.querySelector('form').onsubmit=e=>{e.preventDefault();const v=Object.fromEntries(new FormData(e.target));try{const features=T.join(doc.features,{...v,areaID:f.featureID,start:Number(v.start),end:Number(v.end)});safeEdit(()=>doc.features=features);shapeEdit=true;settlementMode='boundary';joinEnds=[];dialog.close();render();details();}catch(error){dialog.querySelector('[data-join-error]').textContent=error.message;}};} + function topologyAction(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||!E.isArea(f)||f.isLocked)return;if(name==='join'){joinDialog();return;}if(name==='unjoin'||name==='unjoin-all'){topologyEdit(features=>T.unjoin(features,f.featureID,name==='unjoin-all'?null:selectedEdge));selectedEdge=null;details();return;}if(name==='insert'){const c=T.context(doc.features),index=c.area(f.featureID).edgeRefs?.indexOf(selectedEdge);if(index>=0){const cs=T.edgeCurves(f,index,c),ci=Math.floor(cs.length/2);topologyEdit(features=>T.insert(features,f.featureID,index,ci,.5));shapeEdit=true;render();details();}}} + document.addEventListener('click',e=>{const b=e.target.closest('[data-topology]');if(b)topologyAction(b.dataset.topology);}); function render(affected=null){ if(!doc)return;window.PlotDirectorMapAppearance?.render(); - const visible=(preview?.features||doc.features).filter(f=>!hiddenLayers.has(f.layer)); + const rendering=preview?.features||doc.features,topology=T.context(rendering); + const visible=rendering.filter(f=>!hiddenLayers.has(f.layer)); const alive=new Set(visible.map(f=>f.featureID)),scale=view.w/Math.max(svg.clientWidth,1),labelBoxes=[]; for(const[id,node]of nodes)if(!alive.has(id)){node.remove();nodes.delete(id);} for(const[id,node]of boundaryNodes)if(!alive.has(id)||!E.hasBoundary(visible.find(f=>f.featureID===id))){node.remove();boundaryNodes.delete(id);} const childIDs=new Set(boot.maps.filter(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID).map(m=>m.parentFeatureID)); - const ordered=E.drawingOrder(visible); + const visibleByID=new Map(visible.map(f=>[f.featureID,f])),ordered=affected&&renderOrder.length===visible.length?renderOrder.map(id=>visibleByID.get(id)):E.drawingOrder(visible);if(!affected)renderOrder=ordered.map(f=>f.featureID); for(const[id,node]of labelNodes)if(!alive.has(id)){node.remove();labelNodes.delete(id);} for(const f of ordered){ if(affected&&!affected.has(f.featureID))continue; @@ -113,7 +124,7 @@ if(!boundary){boundary=svgNode('g',{'data-boundary-feature-id':f.featureID,tabindex:'0',role:'button'});boundaryNodes.set(f.featureID,boundary);scene.append(boundary);} boundary.setAttribute('class',`maps-boundary${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}`); boundary.setAttribute('aria-label',f.name+' boundary');boundary.setAttribute('aria-pressed',String(isSelected)); - const outline=areaMarkup(f,true);if(boundary.innerHTML!==outline)boundary.innerHTML=outline; + const outline=areaMarkup(f,true,topology);if(boundary.innerHTML!==outline)boundary.innerHTML=outline; } if(f.geometryClass==='Marker'){ const symbol=E.library.find(a=>a.type===f.type)?.symbol||'◆',size=Math.min(46,Math.max(26,f.width/Math.max(.7,scale)))*scale; @@ -126,9 +137,9 @@ if(rail)markup+=``; markup+=``; }else{ - markup=areaMarkup(f); + markup=areaMarkup(f,false,topology); } - let overlay=isSelected&&E.isArea(f)?areaMarkup(f,E.hasBoundary(f)).replace(/fill="[^"]*"/,'fill="none"').replace(/stroke="[^"]*"/,'stroke="var(--maps-selection,#136883)"'):''; + let overlay=isSelected&&E.isArea(f)?``.replace(/fill="[^"]*"/,'fill="none"').replace(/stroke="[^"]*"/,'stroke="var(--maps-selection,#136883)"'):''; if(isSelected&&E.isSettlement(f)){ const r=27*scale,gap=18*scale; overlay+=``; @@ -142,13 +153,16 @@ let label=labelNodes.get(f.featureID);if(!label){label=svgNode('g',{'data-label-feature-id':f.featureID});labelNodes.set(f.featureID,label);labels.append(label);}if(label.innerHTML!==overlay)label.innerHTML=overlay; // append only when ordering changes, preserving DOM focus on normal updates } + const edgeAfter=new Map(),aliveEdges=new Set(),edgeMembers=new Map();for(const f of ordered)if(E.isArea(f))for(const id of new Set(topology.area(f.featureID).edgeRefs||[])){if(!id)continue;if(!edgeMembers.has(id))edgeMembers.set(id,[]);edgeMembers.get(id).push(f);}for(const[id,edge]of topology.edges){const members=edgeMembers.get(id)||[];if(!members.length)continue;aliveEdges.add(id);let node=sharedNodes.get(id);if(!node){node=svgNode('g',{'data-shared-edge-id':id,tabindex:'0',role:'button'});sharedNodes.set(id,node);scene.append(node);}const owner=members.find(f=>selected.has(f.featureID))||members[0];node.dataset.sharedAreaId=owner.featureID;node.setAttribute('aria-label','Shared boundary: '+members.map(f=>f.name).join(' / '));node.setAttribute('class',selectedEdge===id&&selected.has(owner.featureID)?'maps-shared-edge is-selected':'maps-shared-edge');const sharedMarkup=``;if(node.__topologyMarkup!==sharedMarkup){node.innerHTML=sharedMarkup;node.__topologyMarkup=sharedMarkup;}const last=members.at(-1).featureID;if(!edgeAfter.has(last))edgeAfter.set(last,[]);edgeAfter.get(last).push(node);} + for(const[id,node]of sharedNodes)if(!aliveEdges.has(id)){node.remove();sharedNodes.delete(id);} if(!affected){ - const layers=ordered.map(f=>E.hasBoundary(f)?boundaryNodes.get(f.featureID):nodes.get(f.featureID)); + const layers=ordered.flatMap(f=>[E.hasBoundary(f)?boundaryNodes.get(f.featureID):nodes.get(f.featureID),...(edgeAfter.get(f.featureID)||[])]); // Settlement anchor symbols stay above ordinary content, independently of fill order. layers.push(...ordered.filter(E.hasBoundary).map(f=>nodes.get(f.featureID))); layers.forEach((node,i)=>{if(scene.children[i]!==node)scene.insertBefore(node,scene.children[i]||null);}); } updateButtons();renderHandles(scale); + if(snapHint){handles.append(svgNode('circle',{cx:snapHint.point[0],cy:snapHint.point[1],r:10*scale,class:'maps-snap-indicator','pointer-events':'none'}));} window.PlotDirectorStoryOverlay?.redraw(); } function renderHandles(scale){ @@ -162,12 +176,12 @@ const actual=E.pathPoints(f,doc.features);if(!f.startFeatureID)add(actual[0],'endpoint',0);if(!f.endFeatureID)add(actual.at(-1),'endpoint',pts.length-1); if(shapeEdit)pts.forEach((p,i)=>{if(i>0&&iadd(E.localToWorld(frame,p),'point',i)); - add(E.localToWorld(frame,[.5,.5]),'resize'); + if(shapeEdit)T.controls(f,doc.features).forEach((p,i)=>{add(p,'point',i);if(E.areaGeometry(f).vertexRefs?.[i])handles.lastElementChild.classList.add('maps-shared-vertex');if(joinEnds.includes(i))handles.lastElementChild.classList.add('maps-join-endpoint');}); + if(!T.linked(f))add(E.localToWorld(frame,[.5,.5]),'resize'); } if(active)handles.querySelector(`[data-handle="${active.type}"][data-index="${active.index}"]`)?.focus({preventScroll:true}); } - function select(id,extend=false){window.PlotDirectorMapAppearance?.clearSelection();if(!extend)selected.clear();if(extend&&selected.has(id))selected.delete(id);else selected.add(id);shapeEdit=false;settlementMode='whole';render();details();} + function select(id,extend=false){if(!selected.has(id)){selectedEdge=null;joinEnds=[];}window.PlotDirectorMapAppearance?.clearSelection();if(!extend)selected.clear();if(extend&&selected.has(id))selected.delete(id);else selected.add(id);shapeEdit=false;settlementMode='whole';render();details();} function place(type,point,locationID=null){if(!doc||busy||mode!=='create')return;window.PlotDirectorMapAppearance?.clearSelection();safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());settlementMode='whole';if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);shapeEdit=false;});pending=null;svg.classList.remove('placing');$('mapName')?.focus();} function library(){const categories=[...new Set(E.library.map(a=>a.category))];$('mapsCategory').innerHTML=''+categories.map(c=>``).join(''); for(const layer of ['Terrain','Water','Vegetation','Places','Routes','Regions','Labels']){const label=document.createElement('label');label.innerHTML=` ${layer}`;$('mapsLayers').append(label);}assets();} @@ -216,12 +230,13 @@ if(linked)html+=`Open ${esc(linked.locationName)}`; html+=''; if(E.isSettlement(f)&&!E.hasBoundary(f))html+=`

Adds a boundary without moving this anchor or changing connections.

`; - if(E.hasBoundary(f))html+=`
Settlement editing
${[['whole','Move settlement'],['boundary','Edit boundary'],['anchor','Move anchor']].map(([value,label])=>``).join('')}

${settlementMode==='anchor'?'Drag the anchor handle; the boundary stays fixed and roads follow the anchor.':settlementMode==='boundary'?'Drag the outline to move only the boundary, or drag control points to reshape. The anchor and buildings stay fixed.':'Drag the settlement to translate its anchor and boundary together. Contained pieces remain independent.'}

Uses enclosed pieces and story-linked descendants with a margin; never moves them.

`; + if(E.hasBoundary(f))html+=`
Settlement editing
${[['whole','Move settlement'],['boundary','Edit boundary'],['anchor','Move anchor']].map(([value,label])=>``).join('')}

${T.linked(f)?'Shared boundaries: edit common vertices or unjoin before moving the boundary. The anchor can still move independently.':settlementMode==='anchor'?'Drag the anchor handle; the boundary stays fixed and roads follow the anchor.':settlementMode==='boundary'?'Drag the outline to move only the boundary, or drag control points to reshape. The anchor and buildings stay fixed.':'Drag the settlement to translate its anchor and boundary together. Contained pieces remain independent.'}

Uses enclosed pieces and story-linked descendants with a margin; never moves them.

`; if(f.geometryClass!=='Marker'||E.hasBoundary(f)){ const frame=E.areaFrame(f),g=E.isArea(f)?E.areaGeometry(f):E.geometry(f); html+=`
${E.hasBoundary(f)?'Boundary':'Shape'}
${E.hasBoundary(f)?areaField('Boundary width','width',frame.width,'min="10" max="100000"')+areaField('Boundary height','height',frame.height,'min="10" max="100000"'):field('Width','width',f.width,'number','min="10" max="10000"')+field('Height','height',f.height,'number','min="10" max="10000"')}`; if(['Land Mass','Island'].includes(f.type)||E.hasBoundary(f))html+=``; - html+=`

Drag the corner to resize. Edit points to reshape; right-click a point or press Delete to remove it.

`; + html+=`

${T.linked(f)?'Shared boundaries: edit common vertices or unjoin before moving, resizing or rotating.':'Drag the corner to resize. Edit points to reshape; right-click a point or press Delete to remove it.'}

`; + if(E.isArea(f))html+=boundaryTools(f); if(E.isArea(f)){ const a=g.appearance||{},palette=window.PlotDirectorMapAppearanceEngine.palette(doc.map),fill=a.fillColor||(E.hasBoundary(f)?palette.settlement:palette.landColor),border=a.borderColor||(E.hasBoundary(f)?palette.settlementLine:f.layer==='Regions'?palette.region:palette.dark?'#8da18c':'#91a087'); html+=``; @@ -243,27 +258,29 @@ html+=`
${esc(a?.name)} ${esc(r.direction||'relative to')} ${esc(b?.name)} · ${esc(r.relativeDistance||'distance unspecified')}${r.measuredDistance!=null?` · ${esc(r.measuredDistance)} ${esc(r.unit)}`:''}${r.typicalTravelTime?` · travel: ${esc(r.typicalTravelTime)}`:''}${!readonly?` `:''}
`; } if(!readonly)html+=''; - html+='
';content.innerHTML=html; + html+='';content.innerHTML=html;if(T.linked(f))content.querySelectorAll('[data-area-frame],[data-field=width],[data-field=height],[data-rotate],[data-reset-rotation],[data-action=fit-boundary]').forEach(n=>n.disabled=true); } function relationEditor(id){const f=doc.features.find(f=>selected.has(f.featureID));if(!f)return;const old=doc.relationships.find(r=>r.relationshipID===id),other=doc.features.find(x=>x.featureID!==f.featureID);if(!old&&!other){status('Place a second item to define a relationship.');return;} const r=old||{relationshipID:guid(),sourceID:f.featureID,targetID:other.featureID,direction:E.suggestedDirection(f,other),relativeDistance:'Close',measuredDistance:null,unit:'',typicalTravelTime:'',notes:''}; const dialog=document.createElement('dialog');dialog.innerHTML=`

Spatial relationship

Known distance / typical travel time
`;app.append(dialog);dialog.showModal();dialog.querySelector('[data-cancel]').onclick=()=>dialog.close();dialog.onclose=()=>dialog.remove();dialog.querySelector('form').onsubmit=e=>{e.preventDefault();const values=Object.fromEntries(new FormData(e.target));if(values.sourceID===values.targetID){status('Choose two different places.',true);return;}safeEdit(()=>{Object.assign(r,values,{direction:values.direction||null,relativeDistance:values.relativeDistance||null,measuredDistance:values.measuredDistance===''?null:Number(values.measuredDistance)});if(!old)doc.relationships.push(r);});dialog.close();};} - function remove(){safeEdit(()=>{const ids=new Set([...selected].filter(id=>!doc.features.find(f=>f.featureID===id)?.isLocked));doc.features=doc.features.filter(f=>!ids.has(f.featureID));doc.relationships=doc.relationships.filter(r=>!ids.has(r.sourceID)&&!ids.has(r.targetID));for(const f of doc.features){if(ids.has(f.startFeatureID))f.startFeatureID=null;if(ids.has(f.endFeatureID))f.endFeatureID=null;}selected.clear();});} - function duplicate(items){safeEdit(()=>{const mapping=new Map(items.map(f=>[f.featureID,guid()]));const copies=clone(items).map(f=>({...f,featureID:mapping.get(f.featureID),name:f.name+' copy',x:f.x+50,y:f.y+50,isLocked:false,createLocation:false,startFeatureID:mapping.get(f.startFeatureID)||f.startFeatureID,endFeatureID:mapping.get(f.endFeatureID)||f.endFeatureID}));doc.features.push(...copies);selected=new Set(copies.map(f=>f.featureID));settlementMode='whole';shapeEdit=false;});} + function remove(){safeEdit(()=>{const ids=new Set([...selected].filter(id=>!doc.features.find(f=>f.featureID===id)?.isLocked));doc.features=T.remove(doc.features,ids);doc.relationships=doc.relationships.filter(r=>!ids.has(r.sourceID)&&!ids.has(r.targetID));for(const f of doc.features){if(ids.has(f.startFeatureID))f.startFeatureID=null;if(ids.has(f.endFeatureID))f.endFeatureID=null;}selected.clear();});} + function duplicate(items){safeEdit(()=>{const mapping=new Map(items.map(f=>[f.featureID,guid()]));let copies=clone(items).map(f=>({...f,featureID:mapping.get(f.featureID),name:f.name+' copy',x:f.x+50,y:f.y+50,isLocked:false,createLocation:false,startFeatureID:mapping.get(f.startFeatureID)||f.startFeatureID,endFeatureID:mapping.get(f.endFeatureID)||f.endFeatureID}));copies=T.detachCopies(doc.features,copies,mapping);doc.features.push(...copies);selected=new Set(copies.map(f=>f.featureID));settlementMode='whole';shapeEdit=false;});} function removePoint(f,index){ const points=E.isArea(f)?E.areaGeometry(f).points:E.geometry(f).points; if(f.isLocked||!points||!Number.isInteger(index)||index<0||index>=points.length||points.length<=(f.geometryClass==='Path'?2:3))return; if(f.geometryClass==='Path'&&(index===0||index===points.length-1))return; + if(E.isArea(f)){topologyEdit(features=>T.removePoint(features,f.featureID,index));return;} safeEdit(()=>{if(E.isArea(f))E.updateArea(f,g=>g.points.splice(index,1));else{const g=E.geometry(f);g.points.splice(index,1);f.geometryJson=JSON.stringify(g);}}); } function action(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f)return; if(f.isLocked&&['convert-area','fit-boundary','shape','bend','area-style-reset','unplace'].includes(name))return; if(name==='convert-area'&&E.isSettlement(f)&&!E.hasBoundary(f)){safeEdit(()=>E.convertToArea(f));shapeEdit=true;settlementMode='boundary';render();details();return;} - if(name==='fit-boundary'){const items=fitContents(f);if(!items.length){status('No enclosed or story-linked pieces to fit.');return;}safeEdit(()=>E.fitBoundary(f,items,doc.features));return;} + if(name==='fit-boundary'){if(movementBlocked(f))return;const items=fitContents(f);if(!items.length){status('No enclosed or story-linked pieces to fit.');return;}safeEdit(()=>E.fitBoundary(f,items,doc.features));return;} if(name==='area-style-reset')safeEdit(()=>E.updateArea(f,g=>delete g.appearance)); if(name==='remove')remove();if(name==='duplicate')duplicate(doc.features.filter(f=>selected.has(f.featureID))); if(name==='relationship')relationEditor();if(name==='child')newMap(f);if(name==='shape'){shapeEdit=!shapeEdit;if(E.hasBoundary(f))settlementMode=shapeEdit?'boundary':'whole';render();details();} if(name==='unplace')safeEdit(()=>{f.isPlaced=false;}); + if(name==='bend'&&E.isArea(f)){const c=T.context(doc.features),g=c.area(f.featureID),i=selectedEdge&&g.edgeRefs?g.edgeRefs.indexOf(selectedEdge):-1,idx=i>=0?i:Math.max(0,joinEnds.at(-1)??0),curves=T.edgeCurves(f,idx,c);if(topologyEdit(features=>T.insert(features,f.featureID,idx,Math.floor(curves.length/2),.5))){shapeEdit=true;render();details();}return;} if(name==='bend')safeEdit(()=>{const g=E.isArea(f)?E.areaGeometry(f):E.geometry(f),pts=g.points||[];if(pts.length>=64)return;let index=0,longest=0;for(let i=0;ilongest){longest=len;index=i;}}const next=pts[(index+1)%pts.length];pts.splice(index+1,0,[(pts[index][0]+next[0])/2,(pts[index][1]+next[1])/2]);g.points=pts;if(E.isArea(f))E.updateArea(f,target=>target.points=pts);else f.geometryJson=JSON.stringify(g);shapeEdit=true;if(E.hasBoundary(f))settlementMode='boundary';}); } function definePlace(){ @@ -296,7 +313,7 @@ safeEdit(()=>{doc.features=trial;});status(orderCommands[command]+'. Unsaved changes.'); } document.addEventListener('click',e=>{const button=e.target.closest('[data-map-order]');if(button)changeDrawingOrder(button.dataset.mapOrder);}); - function previewArrange(){if(!doc||mode!=='create')return;preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();} + function previewArrange(){if(!doc||mode!=='create')return false;try{preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();return true;}catch(error){preview=null;status(error.message,true);render();updateButtons();return false;}} // Delegated interaction continues to work after the PWA shell moves controls into its ribbon. document.addEventListener('click',e=>{ const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;window.PlotDirectorMapAppearance?.completeAdjustment();if(modeButton.dataset.mode==='story'&&dirty){requestLeave(()=>modeButton.click());return;}mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange','mapsGeographic'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;} @@ -309,11 +326,15 @@ const result=e.target.closest('[data-search-feature]');if(result){const f=doc.features.find(f=>f.featureID===result.dataset.searchFeature);select(f.featureID);fit([f]);$('mapsSearchResults').replaceChildren();} }); document.addEventListener('change',e=>{ - if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;if(f.isLocked&&['width','height','rotation','type'].includes(key))return;if(e.target.dataset.initialDisplay===e.target.value)return;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;if(key==='type'&&E.hasBoundary(f)&&!E.settlements.includes(value))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});} + if(e.target.matches('[data-snap]')){if(e.target.dataset.snap==='vertex')snapVertex=e.target.checked;else snapEdge=e.target.checked;return;} + if(e.target.matches('[data-shared-selection]')){selectedEdge=e.target.value;render();details();return;} + if(e.target.matches('[data-shared-smoothing]')){topologyEdit(features=>T.smooth(features,selectedEdge,e.target.value));return;} + + if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;if(['width','height','rotation','type'].includes(key)&&movementBlocked(f))return;if(f.isLocked&&['width','height','rotation','type'].includes(key))return;if(e.target.dataset.initialDisplay===e.target.value)return;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;if(key==='type'&&E.hasBoundary(f)&&!E.settlements.includes(value))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});} if(e.target.matches('[data-geometry]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(f&&!f.isLocked)safeEdit(()=>E.updateArea(f,g=>g[e.target.dataset.geometry]=e.target.value));} if(e.target.matches('[data-area-frame],[data-area-style]')){ const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||!E.isArea(f))return; - const key=e.target.dataset.areaFrame||e.target.dataset.areaStyle,value=e.target.type==='number'?Number(e.target.value):e.target.value; + if(e.target.dataset.areaFrame&&movementBlocked(f))return;const key=e.target.dataset.areaFrame||e.target.dataset.areaStyle,value=e.target.type==='number'?Number(e.target.value):e.target.value; if(typeof value==='number'&&(!Number.isFinite(value)||(['width','height'].includes(key)&&value<10)||(['fillOpacity'].includes(key)&&(value<0||value>1))||(key==='borderWidth'&&(value<0||value>30))))return; safeEdit(()=>{if(e.target.dataset.areaFrame)E.updateArea(f,b=>b[key]=value);else E.updateArea(f,g=>{g.appearance||={};g.appearance[key]=value;});}); } @@ -324,15 +345,16 @@ app.addEventListener('dragstart',e=>{const target=e.target.closest('[data-asset],[data-location]');if(!target)return;e.dataTransfer.setData('application/plotdirector-map',JSON.stringify({type:target.dataset.asset||'Settlement',locationID:Number(target.dataset.location)||null}));e.dataTransfer.effectAllowed='copy';}); svg.addEventListener('dragover',e=>e.preventDefault());svg.addEventListener('drop',e=>{e.preventDefault();try{const data=JSON.parse(e.dataTransfer.getData('application/plotdirector-map'));place(data.type,world(e),data.locationID);}catch{status('Choose a map piece from the library.');}}); svg.addEventListener('pointerdown',e=>{ - if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id],[data-boundary-feature-id]'),handle=e.target.closest('[data-handle]'); + if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'),handle=e.target.closest('[data-handle]'); e.preventDefault();window.getSelection()?.removeAllRanges(); if(e.altKey&&!handle&&!pending){ - const hits=[...new Set(document.elementsFromPoint(e.clientX,e.clientY).map(n=>targetID(n.closest('[data-feature-id],[data-boundary-feature-id]'))).filter(Boolean))]; + const hits=[...new Set(document.elementsFromPoint(e.clientX,e.clientY).map(n=>targetID(n.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'))).filter(Boolean))]; if(hits.length){const current=hits.findIndex(id=>selected.has(id));select(hits[(current+1)%hits.length]);status('Selected '+doc.features.find(f=>selected.has(f.featureID)).name+'. Alt + click again to cycle overlapping pieces.');}return; } + const shared=e.target.closest('[data-shared-edge-id]');if(shared){select(shared.dataset.sharedAreaId);selectedEdge=shared.dataset.sharedEdgeId;shapeEdit=true;settlementMode='boundary';render();details();return;} if(pending){place(pending.type,p,pending.locationID);return;} - if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||mode!=='create')return;const redo=future.slice();checkpoint();drag={redo,kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};} - else if(target){const id=targetID(target);if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){const redo=future.slice();checkpoint();drag={redo,kind:E.hasBoundary(f)&&selected.size===1&&settlementMode==='anchor'?'anchor':E.hasBoundary(f)&&selected.size===1&&settlementMode==='boundary'?'boundary':'move',id:f.featureID,original:clone(f),start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}else drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};} + if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||mode!=='create')return;if(handle.dataset.handle==='resize'&&movementBlocked(f))return;const redo=future.slice();checkpoint();drag={redo,kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};if(handle.dataset.handle==='point'&&E.isArea(f)){const i=Number(handle.dataset.index);joinEnds=[...joinEnds.filter(x=>x!==i),i].slice(-2);drag.snapIndex=T.snapIndex(doc.features.filter(x=>!hiddenLayers.has(x.layer)),scaleForSnap());drag.vertexID=E.areaGeometry(f).vertexRefs?.[i];}} + else if(target){const id=targetID(target);if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){if(!(E.hasBoundary(f)&&settlementMode==='anchor')&&doc.features.some(x=>selected.has(x.featureID)&&movementBlocked(x)))return;const redo=future.slice();checkpoint();drag={redo,kind:E.hasBoundary(f)&&selected.size===1&&settlementMode==='anchor'?'anchor':E.hasBoundary(f)&&selected.size===1&&settlementMode==='boundary'?'boundary':'move',id:f.featureID,original:clone(f),start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}else drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};} else{if(!e.shiftKey){selected.clear();shapeEdit=false;render();details();}drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};} if(drag){svg.classList.add('manipulating');svg.setPointerCapture(e.pointerId);} }); @@ -341,20 +363,20 @@ if(drag.kind==='anchor'){const f=doc.features.find(f=>f.featureID===drag.id);Object.assign(f,clone(drag.original));E.moveAnchor(f,drag.original.x+dx,drag.original.y+dy);} else if(drag.kind==='boundary'){const f=doc.features.find(f=>f.featureID===drag.id);Object.assign(f,clone(drag.original));E.updateArea(f,b=>{b.offsetX+=dx;b.offsetY+=dy;});} else if(drag.kind==='move'){for(const o of drag.originals){const f=doc.features.find(f=>f.featureID===o.featureID);f.x=o.x+dx;f.y=o.y+dy;f.isPlaced=true;}} - else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,frame=E.areaFrame(o),a=-frame.rotation*Math.PI/180,lx=(p[0]-frame.x)*Math.cos(a)-(p[1]-frame.y)*Math.sin(a),ly=(p[0]-frame.x)*Math.sin(a)+(p[1]-frame.y)*Math.cos(a);if(drag.kind==='endpoint'){Object.assign(f,E.transformEndpoint(o,drag.index,p,doc.features));}else if(drag.kind==='resize'){if(E.hasBoundary(f))E.updateArea(f,b=>{b.width=Math.max(20,Math.abs(lx)*2);b.height=Math.max(20,Math.abs(ly)*2);});else{f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}}else{const point=[Math.max(-5,Math.min(5,lx/frame.width)),Math.max(-5,Math.min(5,ly/frame.height))];if(E.isArea(f))E.updateArea(f,g=>g.points[drag.index]=point);else{const g=E.geometry(f);g.points[drag.index]=point;f.geometryJson=JSON.stringify(g);}}} - if(!drag.frame)drag.frame=requestAnimationFrame(()=>{if(!drag)return;drag.frame=null;const moved=new Set(drag.originals?.map(f=>f.featureID)||[drag.id]);for(const f of doc.features)if(moved.has(f.startFeatureID)||moved.has(f.endFeatureID))moved.add(f.featureID);render(moved);}); + else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,frame=E.areaFrame(o),a=-frame.rotation*Math.PI/180,lx=(p[0]-frame.x)*Math.cos(a)-(p[1]-frame.y)*Math.sin(a),ly=(p[0]-frame.x)*Math.sin(a)+(p[1]-frame.y)*Math.cos(a);if(drag.kind==='endpoint'){Object.assign(f,E.transformEndpoint(o,drag.index,p,doc.features));}else if(drag.kind==='resize'){if(E.hasBoundary(f))E.updateArea(f,b=>{b.width=Math.max(20,Math.abs(lx)*2);b.height=Math.max(20,Math.abs(ly)*2);});else{f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}}else{const point=[Math.max(-5,Math.min(5,lx/frame.width)),Math.max(-5,Math.min(5,ly/frame.height))];if(E.isArea(f)){snapHint=T.snap(drag.snapIndex,p,10*scaleForSnap(),{areaID:f.featureID,vertexID:drag.vertexID,vertex:snapVertex,edge:snapEdge,disabled:e.altKey});try{doc.features=T.movePoint(doc.features,f.featureID,drag.index,snapHint?.point||p);drag.affected=drag.vertexID?T.context(doc.features).users(drag.vertexID,'vertex'):[f.featureID];}catch(error){status(error.message,true);}}else{const g=E.geometry(f);g.points[drag.index]=point;f.geometryJson=JSON.stringify(g);}}} + if(!drag.frame)drag.frame=requestAnimationFrame(()=>{if(!drag)return;drag.frame=null;const moved=new Set(drag.affected||drag.originals?.map(f=>f.featureID)||[drag.id]);for(const f of doc.features)if(moved.has(f.startFeatureID)||moved.has(f.endFeatureID))moved.add(f.featureID);render(moved);}); }); - svg.addEventListener('pointerup',e=>{if(!drag)return;const d=drag;drag=null;svg.classList.remove('manipulating');if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);if(d.kind!=='pan'){if(d.moved){changed();render();details();}else{history.pop();future=d.redo;}updateButtons();}}); - function cancelDrag(){svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());future=drag.redo;render();details();}drag=null;} + svg.addEventListener('pointerup',e=>{if(!drag)return;const d=drag;drag=null;svg.classList.remove('manipulating');if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);snapHint=null;if(d.kind!=='pan'){if(d.moved&&snapshot()!==history.at(-1)){changed();render();details();}else{history.pop();future=d.redo;}updateButtons();}}); + function cancelDrag(){snapHint=null;svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());future=drag.redo;render();details();}drag=null;} svg.addEventListener('pointercancel',cancelDrag);svg.addEventListener('lostpointercapture',cancelDrag); - svg.addEventListener('dblclick',e=>{if(e.altKey)return;const id=targetID(e.target.closest('[data-feature-id],[data-boundary-feature-id]'));if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID){const destination=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;requestLeave(()=>{location.href=destination;});}}}); + svg.addEventListener('dblclick',e=>{if(e.altKey)return;const id=targetID(e.target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'));if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID){const destination=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;requestLeave(()=>{location.href=destination;});}}}); svg.addEventListener('wheel',e=>{e.preventDefault();zoom(e.deltaY>0?1.12:1/1.12,world(e));},{passive:false}); (window.PlotDirectorContextMenus?.register||((selector,provider)=>{(window.PlotDirectorContextProviders||=[]).push({selector,provider});}))('#mapsCanvas',target=>{ const point=target.closest('[data-handle="point"]'); - if(point){const f=doc.features.find(f=>f.featureID===point.dataset.handleFeatureId);if(f)return {invoker:point,commands:[{label:'Remove control point',icon:'remove',disabled:f.isLocked||(E.isArea(f)?E.areaGeometry(f):E.geometry(f)).points.length<=(f.geometryClass==='Path'?2:3),run:()=>removePoint(f,Number(point.dataset.index))}]};} + if(point){const f=doc.features.find(f=>f.featureID===point.dataset.handleFeatureId);if(f)return {invoker:point,commands:[...(E.isArea(f)?[{label:'Use as join endpoint',icon:'point',run:()=>{const i=Number(point.dataset.index);joinEnds=[...joinEnds.filter(x=>x!==i),i].slice(-2);status('Join endpoint '+(i+1)+' selected.');render();details();}}]:[]),{label:'Remove control point',icon:'remove',disabled:f.isLocked||(E.isArea(f)?E.areaGeometry(f):E.geometry(f)).points.length<=(f.geometryClass==='Path'?2:3),run:()=>removePoint(f,Number(point.dataset.index))}]};} const referenceMenu=window.PlotDirectorMapAppearance?.context(target);if(referenceMenu)return referenceMenu; - const id=targetID(target.closest('[data-feature-id],[data-boundary-feature-id]')); - if(id&&!selected.has(id))select(id); + const id=targetID(target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]')); + if(id&&!selected.has(id))select(id);const sharedTarget=target.closest('[data-shared-edge-id]');if(sharedTarget)selectedEdge=sharedTarget.dataset.sharedEdgeId; const f=doc?.features.find(f=>f.featureID===id),items=doc?.features.filter(f=>selected.has(f.featureID))||[],commands=[]; const add=(label,icon,run,disabled=false)=>commands.push({label,icon,run,disabled}); if(!f){add('Fit map','focus',()=>fit());if(mode==='create')add('Paste','paste',()=>duplicate(clipboard),!clipboard?.length);} @@ -368,6 +390,7 @@ if(mode==='create'){if(E.isSettlement(f)&&!E.hasBoundary(f))add('Convert to area','auto-arrange',()=>action('convert-area'),f.isLocked);if(E.hasBoundary(f))add('Fit boundary to contents','auto-arrange',()=>action('fit-boundary'),f.isLocked||!fitContents(f).length);add('Add relationship','relationships',()=>action('relationship'));if(f.geometryClass!=='Marker'||E.hasBoundary(f))add('Edit shape / bends','writer',()=>action('shape'),f.isLocked);} } if(mode==='create'){ + if(items.length===1&&E.isArea(f)){add('Snap to vertex'+(snapVertex?' (on)':' (off)'),'point',()=>{snapVertex=!snapVertex;details();});add('Snap to edge'+(snapEdge?' (on)':' (off)'),'point',()=>{snapEdge=!snapEdge;details();});add('Join boundaries','auto-arrange',()=>topologyAction('join'),f.isLocked);add('Unjoin boundary','separate-window',()=>topologyAction('unjoin'),f.isLocked||!T.linked(f));} for(const[key,label]of Object.entries(orderCommands))add(label,'auto-arrange',()=>changeDrawingOrder(key),items.every(f=>f.isLocked)); add('Copy','copy',()=>{clipboard=clone(items);});add('Duplicate','copy',()=>duplicate(items)); add(items.every(f=>f.isLocked)?'Unlock position':'Lock position',items.every(f=>f.isLocked)?'unlock':'lock',()=>safeEdit(()=>{const locked=items.every(f=>f.isLocked);items.forEach(f=>f.isLocked=!locked);})); @@ -375,7 +398,7 @@ add('Delete','remove',remove,items.every(f=>f.isLocked)); } } - return {invoker:target.closest('[data-feature-id],[data-boundary-feature-id]')||svg,commands}; + return {invoker:target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]')||svg,commands}; }); $('mapsDetach').hidden=!window.PlotDirectorWorkspaceBridge; $('mapsDetach').onclick=()=>{const destination=new URL(url(doc?.map.mapID),location.href);destination.searchParams.set('mode',mode);if(!window.PlotDirectorWorkspaceBridge?.detach(destination.href))status('The separate window could not open. Allow pop-ups for PlotDirector and try again.',true);}; @@ -384,7 +407,7 @@ if(e.defaultPrevented||document.querySelector('.modal.show'))return; if(e.key==='Escape'&&$('mapsGeographicDialog').open){e.preventDefault();cancelGeographic();return;} if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&!e.target.closest('dialog')){e.preventDefault();if(e.target.matches('[data-field]'))e.target.dispatchEvent(new Event('change',{bubbles:true}));save();return;} - if(e.target.matches('input,textarea,select')||e.target.isContentEditable)return; + if(e.target.closest('dialog')||e.target.matches('input,textarea,select')||e.target.isContentEditable)return; if(e.key==='Escape'){if(!drag&&!pending&&app.classList.contains('maps-maximised'))return;e.preventDefault();svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());future=drag.redo;drag=null;}pending=null;selected.clear();shapeEdit=false;svg.classList.remove('placing');render();details();return;} if(e.target.closest('dialog'))return; if(mode!=='create'||busy||preview)return; @@ -394,11 +417,12 @@ if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='v'&&clipboard?.length){e.preventDefault();duplicate(clipboard);} const point=e.target.closest('[data-handle=point]');if(point&&(e.key==='Delete'||e.key==='Backspace')){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));if(f)removePoint(f,Number(point.dataset.index));return;} if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove();} + const areaHandle=e.target.closest('[data-handle=point]');if(areaHandle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){const f=doc.features.find(f=>selected.has(f.featureID));if(f&&E.isArea(f)){e.preventDefault();const index=Number(areaHandle.dataset.index),p=T.controls(f,doc.features)[index],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;topologyEdit(features=>T.movePoint(features,f.featureID,index,p));return;}} const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='endpoint'){const i=Number(handle.dataset.index),p=E.pathPoints(f,doc.features)[i],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;Object.assign(f,E.transformEndpoint(f,i,p,doc.features));}else if(handle.dataset.handle==='point'){const g=E.isArea(f)?E.areaGeometry(f):E.geometry(f),p=g.points[Number(handle.dataset.index)],step=e.shiftKey?.05:.01;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;if(E.isArea(f))E.updateArea(f,target=>target.points=g.points);else f.geometryJson=JSON.stringify(g);}else if(handle.dataset.handle==='anchor'){const step=e.shiftKey?20:5;E.moveAnchor(f,f.x+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),f.y+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0));}else{if(E.hasBoundary(f))E.updateArea(f,b=>{b.width=Math.max(20,b.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));b.height=Math.max(20,b.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));});else{f.width=Math.max(20,f.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));f.height=Math.max(20,f.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));}}});return;} - const focused=e.target.closest('[data-feature-id],[data-boundary-feature-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(targetID(focused),e.shiftKey);} - if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const step=e.shiftKey?20:5;safeEdit(()=>doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked).forEach(f=>{const dx=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0,dy=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;if(E.hasBoundary(f)&&settlementMode==='anchor')E.moveAnchor(f,f.x+dx,f.y+dy);else if(E.hasBoundary(f)&&settlementMode==='boundary')E.updateArea(f,b=>{b.offsetX+=dx;b.offsetY+=dy;});else E.translate(f,dx,dy);}));} + const focused=e.target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(targetID(focused),e.shiftKey);if(focused.dataset.sharedEdgeId){selectedEdge=focused.dataset.sharedEdgeId;shapeEdit=true;settlementMode='boundary';render();details();}} + if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();if(!(selected.size===1&&settlementMode==='anchor')&&doc.features.some(f=>selected.has(f.featureID)&&movementBlocked(f)))return;const step=e.shiftKey?20:5;safeEdit(()=>doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked).forEach(f=>{const dx=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0,dy=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;if(E.hasBoundary(f)&&settlementMode==='anchor')E.moveAnchor(f,f.x+dx,f.y+dy);else if(E.hasBoundary(f)&&settlementMode==='boundary')E.updateArea(f,b=>{b.offsetX+=dx;b.offsetY+=dy;});else E.translate(f,dx,dy);}));} }); - function rotate(value,commit=false){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||busy||mode!=='create'||f.startFeatureID||f.endFeatureID)return;if(!Number.isFinite(value))return; + function rotate(value,commit=false){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||busy||mode!=='create'||f.startFeatureID||f.endFeatureID)return;if(!Number.isFinite(value)||movementBlocked(f))return; if(!rotationEdit&&E.areaFrame(f).rotation===E.normalAngle(value))return;if(!rotationEdit){checkpoint();rotationEdit=f.featureID;}if(E.hasBoundary(f))E.updateArea(f,b=>b.rotation=E.normalAngle(value));else f.rotation=E.normalAngle(value);changed();render();document.querySelectorAll('[data-rotate]').forEach(n=>n.value=String(n.type==='range'?Math.round(E.areaFrame(f).rotation):Math.round(E.areaFrame(f).rotation*10)/10));if(commit){const active=document.activeElement,focus=active?.matches('[data-rotate]')?'input[data-rotate][type="'+active.type+'"]':active?.matches('[data-reset-rotation]')?'[data-reset-rotation]':null;rotationEdit=null;details();if(focus)document.querySelector(focus)?.focus({preventScroll:true});}} document.addEventListener('input',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value));}); document.addEventListener('change',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value),true);}); @@ -435,7 +459,7 @@ const drawing=svg.cloneNode(true),ids=new Map(); for(const node of [drawing,...drawing.querySelectorAll('[id]')])if(node.id){ids.set(node.id,'geographic-preview-'+node.id);node.id='geographic-preview-'+node.id;} for(const node of [drawing,...drawing.querySelectorAll('*')]){ - node.removeAttribute('tabindex');node.removeAttribute('data-feature-id');node.removeAttribute('data-boundary-feature-id');node.removeAttribute('data-label-feature-id'); + node.removeAttribute('tabindex');node.removeAttribute('data-feature-id');node.removeAttribute('data-boundary-feature-id');node.removeAttribute('data-label-feature-id');node.removeAttribute('data-shared-edge-id');node.removeAttribute('data-shared-area-id'); for(const attribute of [...node.attributes]){ let value=attribute.value; for(const [id,replacement]of ids){value=value.replaceAll('url(#'+id+')','url(#'+replacement+')');if(value==='#'+id)value='#'+replacement;} @@ -473,7 +497,7 @@ changed('Geographical positions applied. Save to persist; Undo restores previous positions.'); $('mapsGeographicDialog').close();$('mapsGeographicPreview').replaceChildren();render();details();updateButtons(); }; - $('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;previewArrange();$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange; + $('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;if(previewArrange())$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange; function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();} $('mapsArrangeCancel').onclick=cancelArrange;$('mapsArrangeDialog').oncancel=e=>{e.preventDefault();cancelArrange();}; $('mapsArrangeApply').onclick=()=>{const result=preview;preview=null;checkpoint();doc.features=result.features;changed(result.warnings.length?'Arrangement applied with observations; you can adjust manually.':'Arrangement applied. You can move any piece afterwards.');$('mapsArrangeDialog').close();render();details();updateButtons();};