@protomaze/geometry 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/GeometryDemo.d.ts +1 -0
  2. package/GeometryDemo.js +1 -0
  3. package/README.md +294 -2
  4. package/common/Colors.d.ts +47 -0
  5. package/common/Colors.js +1 -0
  6. package/common/Disposables.d.ts +7 -0
  7. package/common/Disposables.js +1 -0
  8. package/data/Geometry.d.ts +62 -0
  9. package/data/Geometry.js +1 -0
  10. package/demo/DemoControls.d.ts +68 -0
  11. package/demo/DemoControls.js +1 -0
  12. package/demo/Town.d.ts +115 -0
  13. package/demo/Town.js +1 -0
  14. package/edit/CreateController.d.ts +101 -0
  15. package/edit/CreateController.js +1 -0
  16. package/edit/EditController.d.ts +121 -0
  17. package/edit/EditController.js +1 -0
  18. package/edit/EditHistory.d.ts +46 -0
  19. package/edit/EditHistory.js +1 -0
  20. package/edit/EditShape.d.ts +45 -0
  21. package/edit/EditShape.js +1 -0
  22. package/edit/GeometryController.d.ts +83 -0
  23. package/edit/GeometryController.js +1 -0
  24. package/edit/MeasureController.d.ts +102 -0
  25. package/edit/MeasureController.js +1 -0
  26. package/edit/Sketch.d.ts +73 -0
  27. package/edit/Sketch.js +1 -0
  28. package/edit/Snapper.d.ts +67 -0
  29. package/edit/Snapper.js +1 -0
  30. package/engine/GeometryEngine.d.ts +257 -0
  31. package/engine/GeometryEngine.js +1 -0
  32. package/engine/GeometryFrame.d.ts +91 -0
  33. package/engine/GeometryFrame.js +1 -0
  34. package/engine/GeometryOptions.d.ts +79 -0
  35. package/engine/GeometryOptions.js +1 -0
  36. package/engine/GeometryView.d.ts +192 -0
  37. package/engine/GeometryView.js +1 -0
  38. package/engine/Labels.d.ts +42 -0
  39. package/engine/Labels.js +1 -0
  40. package/engine/MapCamera.d.ts +78 -0
  41. package/engine/MapCamera.js +1 -0
  42. package/event/TypedEventEmitter.d.ts +13 -0
  43. package/event/TypedEventEmitter.js +1 -0
  44. package/index.d.ts +53 -0
  45. package/index.js +1 -0
  46. package/layers/AreaLayer.d.ts +36 -0
  47. package/layers/AreaLayer.js +1 -0
  48. package/layers/GeometryLayer.d.ts +312 -0
  49. package/layers/GeometryLayer.js +1 -0
  50. package/layers/LineLayer.d.ts +48 -0
  51. package/layers/LineLayer.js +1 -0
  52. package/layers/PointLayer.d.ts +42 -0
  53. package/layers/PointLayer.js +1 -0
  54. package/layers/SphereLayer.d.ts +25 -0
  55. package/layers/SphereLayer.js +1 -0
  56. package/layers/TubeLayer.d.ts +52 -0
  57. package/layers/TubeLayer.js +1 -0
  58. package/math/Boolean.d.ts +21 -0
  59. package/math/Boolean.js +1 -0
  60. package/math/FeatureIndex.d.ts +70 -0
  61. package/math/FeatureIndex.js +1 -0
  62. package/math/Geodesy.d.ts +29 -0
  63. package/math/Geodesy.js +1 -0
  64. package/math/Lines.d.ts +115 -0
  65. package/math/Lines.js +1 -0
  66. package/math/Measure.d.ts +71 -0
  67. package/math/Measure.js +1 -0
  68. package/math/Polygons.d.ts +59 -0
  69. package/math/Polygons.js +1 -0
  70. package/math/Projection.d.ts +25 -0
  71. package/math/Projection.js +1 -0
  72. package/math/Relations.d.ts +27 -0
  73. package/math/Relations.js +1 -0
  74. package/math/SpatialIndex.d.ts +36 -0
  75. package/math/SpatialIndex.js +1 -0
  76. package/math/Transform.d.ts +36 -0
  77. package/math/Transform.js +1 -0
  78. package/math/Triangulate.d.ts +19 -0
  79. package/math/Triangulate.js +1 -0
  80. package/math/Vector.d.ts +24 -0
  81. package/math/Vector.js +1 -0
  82. package/package.json +76 -4
  83. package/react/ReactGeometry.d.ts +35 -0
  84. package/react/ReactGeometry.js +1 -0
  85. package/three/CanvasGeometryEngine.d.ts +79 -0
  86. package/three/CanvasGeometryEngine.js +1 -0
  87. package/three/DensityMap.d.ts +31 -0
  88. package/three/DensityMap.js +1 -0
  89. package/three/FeatureLook.d.ts +191 -0
  90. package/three/FeatureLook.js +1 -0
  91. package/three/Ground.d.ts +54 -0
  92. package/three/Ground.js +1 -0
  93. package/three/Halo.d.ts +26 -0
  94. package/three/Halo.js +1 -0
  95. package/three/HostedGeometryEngine.d.ts +57 -0
  96. package/three/HostedGeometryEngine.js +1 -0
  97. package/three/RiaGeometryEngine.d.ts +48 -0
  98. package/three/RiaGeometryEngine.js +1 -0
  99. package/three/Shading.d.ts +42 -0
  100. package/three/Shading.js +1 -0
  101. package/three/Sky.d.ts +27 -0
  102. package/three/Sky.js +1 -0
  103. package/three/Tsl.d.ts +47 -0
  104. package/three/Tsl.js +1 -0
  105. package/three/primitives/Body.d.ts +82 -0
  106. package/three/primitives/Body.js +1 -0
  107. package/three/primitives/GpuAreas.d.ts +72 -0
  108. package/three/primitives/GpuAreas.js +1 -0
  109. package/three/primitives/GpuIcons.d.ts +112 -0
  110. package/three/primitives/GpuIcons.js +1 -0
  111. package/three/primitives/GpuLines.d.ts +198 -0
  112. package/three/primitives/GpuLines.js +1 -0
  113. package/three/primitives/GpuSpheres.d.ts +55 -0
  114. package/three/primitives/GpuSpheres.js +1 -0
  115. package/three/primitives/GpuTubes.d.ts +125 -0
  116. package/three/primitives/GpuTubes.js +1 -0
  117. package/three/primitives/IconAtlas.d.ts +12 -0
  118. package/three/primitives/IconAtlas.js +1 -0
@@ -0,0 +1 @@
1
+ export declare function GeometryDemo(): JSX.Element;
@@ -0,0 +1 @@
1
+ import e,{useEffect as t,useMemo as r,useRef as o,useState as n}from"react";import{RAMPS as i,rampColor as a,toCss as l}from"./common/Colors.js";import{AreaLayer as s}from"./layers/AreaLayer.js";import{LineLayer as c}from"./layers/LineLayer.js";import{PointLayer as d}from"./layers/PointLayer.js";import{SphereLayer as p}from"./layers/SphereLayer.js";import{TubeLayer as m}from"./layers/TubeLayer.js";import{ReactGeometry as u}from"./react/ReactGeometry.js";import{boxProfile as h}from"./three/primitives/GpuTubes.js";import{ACCENT as f,Chip as g,DemoButton as y,DemoIconButton as w,DemoSelect as b,Divider as x,FullscreenButton as k,panelStyle as E,RangeSlider as v,Section as C,Slider as S}from"./demo/DemoControls.js";import{createTown as D,MATERIAL_COLORS as $,MATERIALS as L,ORIGIN_X as z,ORIGIN_Y as F,paintGround as R}from"./demo/Town.js";import{CreateController as j}from"./edit/CreateController.js";import{EditController as W}from"./edit/EditController.js";import{EditHistory as M}from"./edit/EditHistory.js";import{MeasureController as P}from"./edit/MeasureController.js";import{formatArea as A,formatLength as T,formatSlope as N}from"./engine/Labels.js";import{area as H,length as I}from"./math/Measure.js";const G=[{tool:"select",icon:"arrow_selector_tool",title:"Select (V): click to select, drag to pan",key:"v"},{tool:"point",icon:"add_location_alt",title:"Draw points (P)",key:"p"},{tool:"line",icon:"polyline",title:"Draw a line (L): click its points, double-click or Enter to finish",key:"l"},{tool:"polygon",icon:"pentagon",title:"Draw an area (A): click its corners, click the first to close it",key:"a"},{tool:"rectangle",icon:"rectangle",title:"Draw a rectangle (R): two corners",key:"r"},{tool:"circle",icon:"circle",title:"Draw a circle (C): its centre, then its edge",key:"c"},{tool:"edit",icon:"edit",title:"Edit (E): click a feature - drag vertices, Alt-drag heights, T to scale and turn, Del to delete",key:"e"},{tool:"distance",icon:"straighten",title:"Measure a distance (D): along points, on whatever is drawn there",key:"d"},{tool:"area",icon:"square_foot",title:"Measure an area (M)",key:"m"},{tool:"height",icon:"height",title:"Measure a height (H): between two points",key:"h"},{tool:"clearance",icon:"compare_arrows",title:"Clearance (K): click two features, the nearest they come in 3D",key:"k"}],U={point:"Click to place a point. Points snap to vertices and edges near the pointer.",line:"Click to place points; double-click or Enter to finish, Backspace to take one back. Shift: 15° steps.",polygon:"Click the corners; click the first again or double-click to close. Crossing edges are refused.",rectangle:"Click one corner, then the opposite one.",circle:"Click the centre, then a point on the edge.",edit:"Click a feature. Drag a vertex to move it, an edge's middle to add one; Alt-drag raises or lowers it (3D). Drag the shape to move it, T to scale or turn it. Double-click a vertex or Del to remove it; Del alone deletes the feature. Ctrl+Z / Ctrl+Y.",distance:"Click points along the way - on the ground, a pipe, a roof. Double-click to finish.",area:"Click the corners of the area. Double-click to finish.",height:"Click two points: their height difference, distance across and slope.",clearance:"Click two features - two pipes, a pipe and a cable - for the nearest they come, surface to surface."};let B=0;const _=[{value:1,text:"Town"},{value:2,text:"City"},{value:4,text:"Metro"},{value:6,text:"Region"}],V={age:{label:"Year laid",ramp:i.viridis.slice(1),domain:[1900,2024],value:e=>e.properties.year,format:e=>String(Math.round(e))},diameter:{label:"Diameter",ramp:i.magma.slice(1),domain:[150,1600],value:e=>e.properties.dn??NaN,format:e=>`DN ${Math.round(e)}`},condition:{label:"Condition class",ramp:i.condition,domain:[0,5],value:e=>e.properties.condition,format:e=>String(Math.round(e))},depth:{label:"Depth",ramp:i.ice,domain:[1,9],value:e=>"manhole"===e.properties.kind?e.properties.depth:(e.properties.depthFrom+e.properties.depthTo)/2,format:e=>`${e.toFixed(1)} m`}},O=[{key:"sewer",title:"Sewer & manholes",color:"#e07a3f"},{key:"laterals",title:"House laterals",color:"#4cc9f0"},{key:"connections",title:"Connections",color:"#ffd166"},{key:"water",title:"Water mains",color:"#3a86ff"},{key:"gas",title:"Gas mains",color:"#ffbe0b"},{key:"power",title:"Power ducts",color:"#ff006e"},{key:"buildings",title:"Buildings",color:"#7d8fa8"},{key:"zones",title:"Flood zones",color:"#ff4d6d"},{key:"trees",title:"Trees",color:"#52b788"},{key:"sensors",title:"Sensors",color:"#00f5d4"},{key:"trajectories",title:"Robot & drone",color:"#f72585"}],Y=e=>e.properties.year??NaN,q=e=>"manhole"===e.properties.kind?null:e.properties.material;export function GeometryDemo(){const[A,T]=n(1),[N,H]=n("3d"),[I,U]=n("dark"),[oe,ne]=n("glow"),[ie,ae]=n(!0),[le,se]=n(!0),[ce,de]=n(!1),[pe,me]=n(!1),[ue,he]=n("material"),[fe,ge]=n([1895,2024]),[ye,we]=n("fade"),[be,xe]=n(150),[ke,Ee]=n(new Set),[ve,Ce]=n(null),[Se,De]=n({}),[$e,Le]=n(null),[ze,Fe]=n(null),[Re,je]=n(null),[We,Me]=n("select"),[Pe,Ae]=n(!0),[Te,Ne]=n(null),[He,Ie]=n(null),[Ge,Ue]=n({canUndo:!1,canRedo:!1,undoLabel:null,redoLabel:null}),Be=o(null),_e=o(null),Ve=o({x:0,y:0}),Oe=o(null),Ye=o({flow:le,growth:0,xray:ce,dark:!0}),qe="dark"===I,Ke=r(()=>"undefined"!=typeof window&&window.innerWidth<J&&window.innerWidth<window.innerHeight?2.2:1,[]),Xe=r(()=>D(A),[A]),Ze=r(()=>function(e,t){const r={Residential:"#4c5a6d",Commercial:"#5f7189",Industrial:"#6e665a",Public:"#57716b"},o={Residential:"#d9dee5",Commercial:"#c9d3df",Industrial:"#ddd5c8",Public:"#cfe0da"},n=new m({id:"sewer",title:"Sewer",features:[...e.sewer,...e.manholes],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.7):e.properties.dn/2e3,stand:e=>"manhole"===e.properties.kind?{bottom:-e.properties.depth,top:0,radius:e.properties.diameter/2}:null,arrows:!0,style:e=>{const r=e.properties;return"manhole"===r.kind?{color:"#aab4bf",material:"Beton",width:2}:{color:$[r.material],material:r.material,width:1.4+Math.min(4.5,r.dn/280),flow:t.flow,weight:.4+.5*r.condition}}}),a=new m({id:"laterals",title:"House laterals",features:e.laterals,profile:()=>.075,reach:()=>1400,style:e=>({color:$[e.properties.material],material:e.properties.material,width:1,weight:.3})}),l=new p({id:"connections",title:"Connections",features:e.connections,radius:()=>.16,reach:()=>900,style:{color:"#ffd166",material:"pvc",width:2.5}}),u={water:"#3a86ff",gas:"#ffbe0b",power:"#ff006e"},g=new m({id:"utilities",title:"Utilities",features:[...e.water,...e.gas,...e.power],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.25):e.properties.dn/2e3,style:e=>({color:u[e.properties.kind],material:e.properties.material,width:"power"===e.properties.kind?1.5:1.2+e.properties.dn/300,flow:t.flow&&"power"!==e.properties.kind})});g.setCategories({of:e=>e.properties.kind,keys:["water","gas","power"]});const y=new s({id:"buildings",title:"Buildings",features:e.buildings,extrude:!0,style:e=>({color:(t.dark?r:o)[e.properties.use],height:e.properties.height*t.growth,material:"Commercial"===e.properties.use&&e.properties.floors>9?"glass":"concrete",opacity:t.xray?.16:1,outline:"#ffffff30",outlineWidth:1})}),w=new s({id:"zones",title:"Flood zones",features:e.zones,style:e=>{const t=e.properties.risk;return"High"===t?{color:"#ff4d6d40",pattern:"hatch",outline:"#ff4d6d",outlineWidth:2}:"Medium"===t?{color:"#ff9f1c1c",outline:"#ff9f1c",outlineWidth:1.5}:"Low"===t?{color:"#4cc9f014",outline:"#4cc9f0aa",outlineWidth:1.2,outlineDashed:!0}:{color:"#f9c74f30",pattern:"hatch",outline:"#f9c74f",outlineWidth:2.5,outlineDashed:!0}}}),b=["#2d6a4f","#40916c","#52b788","#3a7d44","#4f772d"],x=new p({id:"trees",title:"Trees",features:e.trees,radius:e=>e.properties.crown,reach:()=>3e3,ghost:!1,style:(e,t)=>({color:b[t%b.length],material:"default",width:2})}),k=new m({id:"trunks",title:"Trunks",features:e.trees,stand:e=>({bottom:0,top:e.properties.height-.5*e.properties.crown,radius:.18,open:!1}),reach:()=>1500,ghost:!1,covers:!1,pickable:!1,style:{color:"#6b4f3a",material:"default",width:1}}),E=new d({id:"sensors",title:"Sensors",features:e.sensors.map(e=>({...e,geometry:{type:"Point",coordinates:[...e.geometry.coordinates.slice(0,2),.3]}})),anchor:[0,-1],style:e=>({shape:"Quality"===e.properties.type?"hexagon":"pin",size:26,color:"#00f5d4"})});return E.colorBy({value:e=>e.properties.value,ramp:i.condition,domain:[0,100]}),{zones:w,sewer:n,laterals:a,connections:l,utilities:g,trunks:k,trees:x,buildings:y,sensors:E,trajectories:new c({id:"trajectories",title:"Robot & drone",features:e.trajectories,style:e=>"Robot"===e.properties.vehicle?{color:"#00f5d4",width:3.5,flow:!0}:{color:"#f72585",width:2.5,dashed:!0,flow:!0}}),defects:new d({id:"defects",title:"Defects",features:e.defects,visible:!1,pickable:!1,style:e=>({color:"#ff2d55",size:5,weight:.6*e.properties.severity})}),drawnAreas:new s({id:"drawn-areas",title:"Drawn areas",style:{color:"#ddff0026",outline:f,outlineWidth:2}}),drawnLines:new c({id:"drawn-lines",title:"Drawn lines",style:{color:f,width:3}}),drawnPoints:new d({id:"drawn-points",title:"Drawn points",depthTest:!1,border:1.5,style:{color:f,size:14,shape:"circle"}})}}(Xe,Ye.current),[Xe]),Qe=r(()=>Object.values(Ze),[Ze]),Je=r(()=>({bounds:Xe.bounds,image:R(Xe,qe),grid:{spacing:10,major:10,opacity:qe?.025:.05}}),[Xe,qe]),et=[Ze.sewer,Ze.laterals,Ze.utilities],tt=r(()=>new M,[Ze]);t(()=>tt.on("change",Ue),[tt]);const rt=r(()=>{const e=!!Pe&&{},t={stroke:f,fill:"#ddff0024",active:f},r=e=>t=>{const r=++B;return{id:`drawn-${r}`,geometry:t,properties:{name:`${e} ${r}`,kind:"drawn",shape:e}}};switch(We){case"point":return new j({shape:"point",layer:Ze.drawnPoints,feature:r("Point"),history:tt,snapping:e,theme:t});case"line":return new j({shape:"line",layer:Ze.drawnLines,feature:r("Line"),history:tt,snapping:e,theme:t});case"polygon":case"rectangle":case"circle":return new j({shape:We,layer:Ze.drawnAreas,feature:r(We[0].toUpperCase()+We.slice(1)),history:tt,snapping:e,theme:t});case"edit":return new W({layers:[Ze.drawnAreas,Ze.drawnLines,Ze.drawnPoints,Ze.zones,Ze.buildings,Ze.sewer,Ze.laterals,Ze.utilities,Ze.sensors,Ze.trajectories],history:tt,snapping:e,theme:t});case"distance":case"area":case"height":case"clearance":return new P({mode:We,snapping:e,theme:t,radius:(e,t)=>function(e){const t=e.properties??{};return"manhole"===t.kind?t.diameter/2:t.height?t.height/2e3:t.dn?t.dn/2e3:"lateral"===t.kind?.075:0}(t)});default:return null}},[We,Pe,Ze,tt]);t(()=>{if(Ne(null),Ie(null),rt instanceof P)return rt.on("change",Ne);if(rt instanceof W){const e=[rt.on("select",Ie),rt.on("commit",()=>Ie(rt.getTarget()))];return()=>e.forEach(e=>e())}},[rt]),t(()=>{const e=e=>{if(e.ctrlKey||e.metaKey||e.altKey||"INPUT"===e.target?.tagName)return;if(rt instanceof W&&rt.getTarget()&&"t"===e.key.toLowerCase())return;const t=G.find(t=>t.key===e.key.toLowerCase());t&&Me(t.tool)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[rt]),t(()=>{const e=performance.now();let t=0;const r=()=>{const o=Math.min(1,(performance.now()-e-250)/1600);Ye.current.growth=o<=0?0:1-Math.pow(1-o,3),Ze.buildings.restyle(),o<1&&(t=requestAnimationFrame(r))};return t=requestAnimationFrame(r),()=>cancelAnimationFrame(t)},[Ze]),t(()=>{const e=Be.current;e&&e.flyTo({target:[z,F,0],distance:1250*Ke*Math.sqrt(A)},1200)},[Xe]),t(()=>{Ye.current.flow=le,Ze.sewer.restyle(),Ze.utilities.restyle()},[Ze,le]),t(()=>{Ye.current.xray=ce,Ye.current.dark=qe,Ze.buildings.restyle()},[Ze,ce,qe]),t(()=>{const e="material"===ue?{by:"style"}:{value:V[ue].value,ramp:V[ue].ramp,domain:V[ue].domain};[Ze.sewer,Ze.laterals].forEach(t=>t.colorBy(e))},[Ze,ue]),t(()=>{[Ze.sewer,Ze.laterals].forEach(e=>e.setCategories({of:q,keys:L,colors:$}))},[Ze]),t(()=>{[Ze.sewer,Ze.laterals].forEach(e=>L.forEach(t=>e.setCategoryMode(t,ke.has(t)?"hidden":ve===t?"lit":"shown")))},[Ze,ke,ve]),t(()=>{[...et,Ze.buildings].forEach(e=>e.setRange({value:Y,low:fe[0],high:fe[1],outside:ye}))},[Ze,fe,ye]),t(()=>{Ze.sewer.setFilter(be<=150?null:e=>"manhole"===e.properties.kind||e.properties.dn>=be,"hide")},[Ze,be]),t(()=>{O.forEach(({key:e})=>{const t=Se[e]??!0;"water"===e||"gas"===e||"power"===e?Ze.utilities.setCategoryMode(e,t?"shown":"hidden"):Ze[e].setVisible(t)}),Ze.trunks.setVisible(Se.trees??!0)},[Ze,Se]),t(()=>{const e=Be.current;Ze.defects.setVisible(pe),e?.setDensity(pe?{layers:[Ze.defects,Ze.sewer],ramp:i.heat,top:4}:null)},[Ze,pe]),t(()=>{window.geometryDemo={view:()=>Be.current,layers:Ze,town:Xe,live:Ye.current,history:tt,setTool:Me,controller:()=>Be.current?.getController()??null,snapshot:async(e="snapshot")=>{const t=Be.current;if(!t)return null;t.engine.draw();const r=function(e){const t=e.engine.canvas,r=e.labels?.element;if(!r||0===r.childElementCount)return t.toDataURL("image/png");const o=document.createElement("canvas");o.width=t.width,o.height=t.height;const n=o.getContext("2d");n.drawImage(t,0,0);const i=t.width/Math.max(1,t.getBoundingClientRect().width),a=r.getBoundingClientRect();for(const e of Array.from(r.children)){if("none"===e.style.display)continue;const t=e.getBoundingClientRect(),r=getComputedStyle(e),o=(t.left-a.left)*i,l=(t.top-a.top)*i;n.fillStyle=r.backgroundColor,n.beginPath(),n.roundRect(o,l,t.width*i,t.height*i,4*i),n.fill(),n.fillStyle=r.color,n.font=`${r.fontWeight} ${parseFloat(r.fontSize)*i}px ${r.fontFamily}`,n.textBaseline="middle",n.fillText(e.textContent??"",o+parseFloat(r.paddingLeft)*i,l+t.height*i/2)}return o.toDataURL("image/png")}(t),o=await fetch(`/__snapshot?name=${encodeURIComponent(e)}`,{method:"POST",body:r});return(await o.json()).file}}},[Ze,Xe,tt]);const[ot,nt]=n(!1),[it,at]=n(!1);t(()=>{const e=_e.current;if(!e)return;const t=new ResizeObserver(()=>{const{clientWidth:t,clientHeight:r}=e;nt((t<J||r<ee)&&(t>r?"landscape":"portrait"))});return t.observe(e),()=>t.disconnect()},[]);const lt=r(()=>({look:oe,hoverFades:ie}),[oe,ie]),st={sewer:Xe.sewer.length,laterals:Xe.laterals.length,connections:Xe.connections.length,water:Xe.water.length,gas:Xe.gas.length,power:Xe.power.length,buildings:Xe.buildings.length,zones:Xe.zones.length,trees:Xe.trees.length,sensors:Xe.sensors.length,trajectories:Xe.trajectories.length},ct=Object.values(st).reduce((e,t)=>e+t,0)+Xe.manholes.length+Xe.defects.length,dt=qe?"#EBE8E0":"#1A1A1A",pt=E(qe),mt=$e?.layers[0],ut=mt?mt.layer.getFeature(mt.ids[0]):void 0,ht="material"!==ue?V[ue]:null,ft=_.map(t=>e.createElement(y,{key:t.value,text:t.text,active:A===t.value,onClick:()=>T(t.value),title:`A town ${t.value} times as wide`})),gt=e.createElement(e.Fragment,null,e.createElement(y,{text:"2D",active:"2d"===N,onClick:()=>H("2d"),title:"A flat map: lines and covers"}),e.createElement(y,{text:"3D",active:"3d"===N,onClick:()=>H("3d"),title:"In depth: pipes, shafts, buildings"})),yt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Glow",active:"glow"===oe,onClick:()=>ne("glow"),title:"What is lit glows (bloom)"}),e.createElement(y,{text:"Outline",active:"outline"===oe,onClick:()=>ne("outline"),title:"What is lit is outlined"}),e.createElement(y,{text:"Dim others",active:ie,onClick:()=>ae(!ie),title:"Pointing at something dims the rest"})),wt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Flow",active:le,onClick:()=>se(!le),title:"Light running along the networks, downstream (2D)"}),e.createElement(y,{text:"X-ray",active:ce,onClick:()=>de(!ce),title:"See through the buildings"}),e.createElement(y,{text:"Density",active:pe,onClick:()=>me(!pe),title:"A heatmap of the defects and the sewer in poor condition"})),bt=Re&&e.createElement("span",{style:{opacity:.7,fontSize:12,whiteSpace:ot?"normal":"nowrap",fontVariantNumeric:"tabular-nums"}},"webgpu"===Re.backend?"WebGPU":"WebGL 2"," · ",Re.fps," fps · ",Re.ms.toFixed(1)," ms · ",Re.drawCalls," draws · ",(Re.triangles/1e6).toFixed(1),"M triangles · ",ct.toLocaleString()," features"),xt=e.createElement(e.Fragment,null,e.createElement(w,{icon:"fit_screen",title:"Show everything",onClick:()=>Be.current?.fit()}),e.createElement(w,{icon:qe?"dark_mode":"light_mode",title:"Dark or light",onClick:()=>U(qe?"light":"dark")}),e.createElement(k,{target:()=>_e.current})),kt=e.createElement(e.Fragment,null,e.createElement(C,{title:"Layers"},e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},O.map(({key:t,title:r,color:o})=>{const n=Se[t]??!0;return e.createElement(X,{key:t,title:r,color:o,on:n,count:st[t],onClick:()=>De(e=>({...e,[t]:!n}))})}))),e.createElement(C,{title:"Colour the sewer by",right:e.createElement(b,{value:ue,onChange:he,options:[{value:"material",text:"Material"},{value:"age",text:"Age"},{value:"diameter",text:"Diameter"},{value:"condition",text:"Condition"},{value:"depth",text:"Depth"}]})},ht?e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4}},e.createElement("div",{style:{height:10,borderRadius:5,background:`linear-gradient(90deg, ${ht.ramp.join(", ")})`}}),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,opacity:.75}},e.createElement("span",null,ht.format(ht.domain[0])),e.createElement("span",null,ht.label),e.createElement("span",null,ht.format(ht.domain[1])))):null,e.createElement("div",{style:{display:"flex",flexWrap:"wrap",gap:5}},L.map(t=>e.createElement(g,{key:t,text:t,color:$[t],on:!ke.has(t),onHover:e=>Ce(e?t:null),onClick:()=>Ee(e=>{const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r})}))),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Point at a material to light it, click to hide it: one texel on the GPU.")),e.createElement(C,{title:"Year laid",right:e.createElement(e.Fragment,null,e.createElement(y,{text:"Fade",active:"fade"===ye,onClick:()=>we("fade"),title:"What falls outside is faded"}),e.createElement(y,{text:"Hide",active:"hide"===ye,onClick:()=>we("hide"),title:"What falls outside is hidden"}))},e.createElement(v,{min:1895,max:2024,value:fe,onChange:ge}),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Every pipe and building, filtered on the GPU: two uniforms per step.")),e.createElement(C,{title:"Smallest sewer"},e.createElement(S,{min:150,max:1400,step:50,value:be,onChange:xe,format:e=>e<=150?"All":`DN ${e}`})),e.createElement(C,{title:"Navigate"},e.createElement("span",{style:{fontSize:12,opacity:.7,lineHeight:1.5}},"Drag to pan, right-drag to turn and tilt, wheel to zoom where you point, double-click to dive in. Click to select; Ctrl or Shift to add; Esc to clear."))),Et={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},vt=e.createElement(C,{title:"View"},e.createElement("div",{style:Et},ft),e.createElement("div",{style:Et},yt),e.createElement("div",{style:Et},wt),bt),Ct=ot?e.createElement("div",{style:{width:1,margin:"0 2px",flex:"none",background:qe?"#ffffff22":"#00000022"}}):e.createElement("div",{style:{height:1,margin:"2px 0",background:qe?"#ffffff22":"#00000022"}}),St=ot?8:12;return e.createElement("div",{ref:_e,style:{position:"relative",width:"100%",height:"100%",boxSizing:"border-box",padding:ot?4:8,gap:ot?4:8,display:"flex",flexDirection:"column",overflow:"hidden",backgroundColor:"#000",backgroundImage:`url('${te}')`,backgroundPosition:"center",backgroundSize:"cover",color:dt,font:`13px ${re}`}},ot?e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:6,flex:"none",overflowX:"auto"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:2}},"Geometry"),gt,e.createElement("div",{style:{flexGrow:1}}),e.createElement(w,{icon:"tune",title:"Layers, colours, filters",active:it,onClick:()=>at(!it)}),xt):e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:8,flexWrap:"wrap",flex:"none"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:4}},"Geometry"),ft,e.createElement(x,null),gt,e.createElement(x,null),yt,e.createElement(x,null),wt,e.createElement(x,null),bt,e.createElement("div",{style:{flexGrow:1}}),xt),e.createElement("div",{style:{display:"flex",flex:1,minHeight:0,gap:8}},!ot&&e.createElement("div",{className:"demo-scroll",style:{...pt,width:292,flex:"none",overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:18,boxSizing:"border-box"}},kt),e.createElement("div",{style:{...pt,flex:1,minWidth:0,position:"relative",overflow:"hidden"},onMouseMove:e=>{const t=e.currentTarget.getBoundingClientRect();Ve.current={x:e.clientX-t.left,y:e.clientY-t.top},Oe.current&&(Oe.current.style.left=`${Ve.current.x+14}px`,Oe.current.style.top=`${Ve.current.y+14}px`)}},e.createElement(u,{mode:N,theme:I,forceWebGL:Q,highlight:lt,camera:{target:[z,F,0],distance:1250*Ke,heading:18,tilt:58},layers:Qe,ground:Je,controller:rt,viewRef:Be,onHover:Fe,onSelect:Le,onFrame:je}),e.createElement("div",{style:{position:"absolute",left:St,top:St,...Z(qe),padding:5,display:"flex",gap:4,...ot?{flexDirection:"row",maxWidth:`calc(100% - ${2*St}px)`,overflowX:"auto",scrollbarWidth:"none",boxSizing:"border-box"}:{flexDirection:"column"}}},G.map((t,r)=>e.createElement(e.Fragment,{key:t.tool},(1===r||6===r||7===r)&&Ct,e.createElement(w,{icon:t.icon,title:t.title,active:We===t.tool,onClick:()=>Me(t.tool)}))),Ct,e.createElement(w,{icon:"undo",title:Ge.undoLabel?`Undo ${Ge.undoLabel.toLowerCase()} (Ctrl+Z)`:"Nothing to undo",onClick:()=>tt.undo(),active:!1}),e.createElement(w,{icon:"redo",title:Ge.redoLabel?`Redo ${Ge.redoLabel.toLowerCase()} (Ctrl+Y)`:"Nothing to redo",onClick:()=>tt.redo(),active:!1}),e.createElement(w,{icon:"join",title:Pe?"Snapping on: to vertices and edges of what is drawn":"Snapping off",active:Pe,onClick:()=>Ae(!Pe)})),"select"!==We&&e.createElement(K,{tool:We,dark:qe,measurement:Te,editing:He,compact:!!ot}),ze&&"select"===We&&e.createElement("div",{ref:Oe,style:{position:"absolute",left:Ve.current.x+14,top:Ve.current.y+14,pointerEvents:"none",...Z(qe),padding:"6px 9px",fontSize:12,maxWidth:280,whiteSpace:"nowrap"}},e.createElement("b",null,ze.feature.properties?.name??ze.id),e.createElement("div",{style:{opacity:.7}},function(e){const t=e.properties??{};switch(t.kind){case"sewer":case"lateral":case"water":case"gas":case"power":return`${t.material} · DN ${t.dn}${t.height?`/${t.height}`:""} · ${t.year} · ${t.length?.toFixed(0)} m`;case"manhole":return`${t.depth.toFixed(1)} m deep · ${t.material} · ${t.year}`;case"building":return`${t.use} · ${t.floors} floors · ${t.height.toFixed(0)} m`;case"sensor":return`${t.type} · ${t.value} %`;case"zone":return`Risk: ${t.risk}`;case"tree":return`${t.height.toFixed(0)} m high`;case"connection":return`On ${t.pipe}`;case"trajectory":return t.vehicle;default:return""}}(ze.feature))),ut&&"select"===We&&e.createElement("div",{style:{position:"absolute",...Z(qe),padding:12,display:"flex",flexDirection:"column",gap:8,boxSizing:"border-box",...ot?{left:St,right:St,bottom:St,maxHeight:"45%",overflowY:"auto"}:{right:12,top:12,width:270}}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},e.createElement("span",{style:{width:10,height:10,borderRadius:5,background:f,boxShadow:`0 0 8px ${f}`}}),e.createElement("b",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},ut.properties?.name??ut.id)),$e.count>1&&e.createElement("span",{style:{fontSize:12,opacity:.7}},"and ",$e.count-1," more selected"),e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,function(e){const t=e.properties??{},r=[["Id",String(e.id)]],o=(e,t)=>{null!=t&&""!==t&&r.push([e,String(t)])};["sewer","lateral","water","gas","power"].includes(t.kind)?(o("Material",t.material),o("Profile",`DN ${t.dn}${t.height?` × ${t.height}`:""}`),o("Laid",t.year),o("Condition",`${t.condition} / 5`),o("Length",`${t.length.toFixed(1)} m`),o("Depth",`${t.depthFrom.toFixed(2)} → ${t.depthTo.toFixed(2)} m`),"sewer"===t.kind&&o("Slope",`${t.slope.toFixed(1)} ‰`),o("Upstream",t.upstream),o("Downstream",t.downstream)):Object.entries(t).forEach(([e,t])=>{"name"!==e&&"kind"!==e&&o(e[0].toUpperCase()+e.slice(1),"number"!=typeof t||Number.isInteger(t)?t:t.toFixed(1))});return r}(ut).map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"2px 10px 2px 0",verticalAlign:"top"}},t),e.createElement("td",{style:{padding:"2px 0",fontVariantNumeric:"tabular-nums"}},r))))),e.createElement("div",{style:{display:"flex",gap:6}},e.createElement(y,{text:"Fly to",onClick:()=>{const e=function(e){const t=e.geometry;return t?"Point"===t.type?t.coordinates:"LineString"===t.type?t.coordinates[Math.floor(t.coordinates.length/2)]:"Polygon"===t.type?t.coordinates[0][0]:null:null}(ut);e&&Be.current?.flyTo({target:[e[0],e[1],0],distance:70,tilt:62},1100)}}),e.createElement(y,{text:"Clear",onClick:()=>Be.current?.clearSelection()}))),pe&&e.createElement("div",{style:{position:"absolute",...ot?{right:St,top:St+44}:{left:12,bottom:12},...Z(qe),padding:"8px 10px",width:ot?160:200,display:"flex",flexDirection:"column",gap:4}},e.createElement("span",{style:{fontSize:11,opacity:.7}},"Defects and poor condition"),e.createElement("div",{style:{height:8,borderRadius:4,background:`linear-gradient(90deg, ${i.heat.slice(1).map(e=>l(a([e],0))).join(", ")})`}})),ot&&it&&e.createElement("div",{className:"demo-scroll",style:{position:"absolute",zIndex:2,...pt,...Z(qe),overflowY:"auto",padding:12,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:18,..."portrait"===ot?{left:0,right:0,bottom:0,maxHeight:"58%",borderRadius:"10px 10px 0 0"}:{top:0,right:0,bottom:0,width:"min(300px, 55%)",borderRadius:"10px 0 0 10px"}}},e.createElement("div",{style:{display:"flex",alignItems:"center"}},e.createElement("b",{style:{flex:1}},"Layers and filters"),e.createElement(w,{icon:"close",title:"Close",onClick:()=>at(!1)})),vt,kt))))}function K({tool:t,dark:r,measurement:o,editing:n,compact:i}){const a=[],l=o;if(l&&"clearance"===l.mode?(l.a&&a.push(["From",String(l.a.feature.properties?.name??l.a.feature.id)]),l.b&&a.push(["To",String(l.b.feature.properties?.name??l.b.feature.id)]),void 0!==l.clearance&&a.push(["Clearance",T(l.clearance)])):l&&("area"===l.mode&&void 0!==l.area?(a.push(["Area",A(l.area)]),a.push(["Perimeter",T(l.perimeter??0)])):l.points.length>=2&&(a.push(["Length",T(l.length??0)]),a.push(["Across the map",T(l.horizontal??0)]),a.push(["Height difference",`${(l.rise??0)>=0?"+":""}${T(l.rise??0)}`]),a.push(["Slope",N(l.slope??0)]))),n){const e=n.geometry;a.push(["Editing",String(n.feature.properties?.name??n.feature.id)]),a.push(["Layer",n.layer.title??n.layer.id]),e.type.includes("Polygon")?a.push(["Area",A(H(e))]):e.type.includes("Line")&&a.push(["Length",T(I(e))])}const s=G.find(e=>e.tool===t)?.title.split(":")[0].replace(/ \(.\)$/,"")??"";return e.createElement("div",{style:{position:"absolute",...i?{left:8,right:8,bottom:8}:{left:52,bottom:12,maxWidth:360},...Z(r),padding:"9px 11px",display:"flex",flexDirection:"column",gap:6,pointerEvents:"none"}},e.createElement("b",{style:{fontSize:12}},s),a.length>0&&e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,a.map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"1px 12px 1px 0"}},t),e.createElement("td",{style:{fontVariantNumeric:"tabular-nums",fontWeight:600}},r))))),e.createElement("span",{style:{fontSize:11,opacity:.65,lineHeight:1.45}},U[t]))}function X({title:t,color:r,on:o,count:i,onClick:a}){const[l,s]=n(!1);return e.createElement("button",{onClick:a,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 6px",borderRadius:4,border:"none",cursor:"pointer",background:l?"#ffffff10":"transparent",color:"inherit",font:"inherit",textAlign:"left",opacity:o?1:.45}},e.createElement("span",{style:{width:14,height:14,borderRadius:3,border:`1.5px solid ${o?r:"#ffffff40"}`,background:o?`${r}55`:"transparent",flex:"none",boxShadow:o?`0 0 6px ${r}88`:"none"}}),e.createElement("span",{style:{flex:1}},t),void 0!==i&&e.createElement("span",{style:{fontSize:11,opacity:.55,fontVariantNumeric:"tabular-nums"}},i.toLocaleString()))}function Z(e){return{borderRadius:6,background:e?"rgba(20, 24, 30, 0.82)":"rgba(250, 250, 250, 0.88)",border:"1px solid "+(e?"#ffffff18":"#00000018"),boxShadow:"0 8px 24px rgba(0,0,0,0.35)",backdropFilter:"blur(8px)"}}const Q="undefined"!=typeof location&&new URLSearchParams(location.search).has("webgl"),J=720,ee=520,te="https://www.protomaze.com/resources/img/mosaic_equirectangular.png",re="Roboto, sans-serif";
package/README.md CHANGED
@@ -1,3 +1,295 @@
1
- # Temporary Holding Version
1
+ # Protomaze Geometry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ GPU geometry for maps and scenes: points, lines, tubes, spheres and areas, in 2D and 3D, each layer
4
+ one instanced draw. Every feature's look - colour, width, state, material, category, value - lives
5
+ in float textures the shaders read, so a restyle, a filter, a hover or a selection costs a texture
6
+ upload or a uniform, never a rebuild. The Ing+ map's three.js network (pipes, manholes, laterals,
7
+ the flow arrows, the heatmap, the GPU pick) made general - with the geometry calculations, and the
8
+ controllers to draw, edit and measure, that go with it.
9
+
10
+ ```bash
11
+ npm run dev # the demo, on http://localhost:8091
12
+ npm test # the DOM-free parts: calculations, editing's shapes and history, the camera
13
+ npm run check # type-check everything, demo and the Ing+ compatibility check included
14
+ ```
15
+
16
+ Built on three.js's WebGPU renderer and TSL, so the same shaders run on WebGPU - where LuciadRIA
17
+ 2026 renders, which is WebGPU only - and on WebGL 2 where a browser has no WebGPU.
18
+
19
+ ## The model
20
+
21
+ ```
22
+ GeometryView / <ReactGeometry> ── a canvas, a camera that pans, zooms and orbits, hover and selection
23
+ │
24
+ ├─ layers: LineLayer, PointLayer, TubeLayer, SphereLayer, AreaLayer
25
+ │ features + style + filters + selection; each builds its primitives and owns their looks
26
+ │
27
+ ├─ a controller: CreateController, EditController, MeasureController ── the pointer and keys, for a while
28
+ │ a Sketch of overlay layers over everything, a Snapper, labels, an EditHistory
29
+ │
30
+ └─ CanvasGeometryEngine ── the engine: scenes per pass, origin, scene depth, bloom, halo, heatmap, pick
31
+ HostedGeometryEngine / RiaGeometryEngine ── the same engine inside someone else's WebGPU frame
32
+
33
+ primitives: GpuLines, GpuIcons, GpuTubes, GpuSpheres, GpuAreas ── one instanced draw per pass,
34
+ reading a FeatureLook: the per-feature textures plus the uniforms that filter, light and colour
35
+ ```
36
+
37
+ Three levels, each usable on its own: the **view** for an application that wants a map; the
38
+ **layers** for one that has features and styles; the **primitives and an engine** for a host that
39
+ draws its own frame - the Ing+ map.
40
+
41
+ ## A view
42
+
43
+ ```tsx
44
+ const pipes = new TubeLayer({
45
+ features, // GeoJSON-shaped, positions [x, y, z] in metres
46
+ profile: f => f.properties.dn / 2000, // radius, or [halfWidth, halfHeight, cornerRadius]
47
+ stand: f => f.properties.kind === 'manhole' // points as standing shafts, pipes cut to their walls
48
+ ? { bottom: -f.properties.depth, top: 0, radius: 0.5 } : null,
49
+ arrows: true,
50
+ style: f => ({ color: colorOf(f), material: f.properties.material, width: 2.5 }),
51
+ });
52
+
53
+ <ReactGeometry
54
+ mode='3d' // '2d': an orthographic map; '3d': perspective
55
+ layers={[zones, pipes, buildings, sensors]}
56
+ ground={{ bounds, image: basemapCanvas }} // its depth ghosts what lies under it
57
+ highlight={{ look: 'glow', hoverFades: true }} // or 'outline'
58
+ onHover={hit => ...} onSelect={selection => ...}
59
+ />
60
+ ```
61
+
62
+ Or without React: `const view = new GeometryView(options); await view.init(element); view.addLayer(...)`.
63
+ The view emits `hover`, `click`, `select`, `camera`, `mode` and `frame` (fps, draw calls, triangles).
64
+
65
+ | Layer | Geometry | Draws |
66
+ |---|---|---|
67
+ | `LineLayer` | lines | across the screen (2D), flat on the ground in perspective, or in space at their own depth (trajectories); round joints, flat ends, flow arrows, dashes, light flowing along them |
68
+ | `PointLayer` | points | icons from an atlas or shapes drawn in the shader - circle, ring, square, diamond, triangle, hexagon, pin, cross, star, the manhole cover - in pixels or metres, facing the screen or lying on the ground |
69
+ | `TubeLayer` | lines, points | pipes, cables and ducts at their real size and cross-section, mitred bends, joints cut to the shafts' walls, materials; points as shafts or columns with covers. A 2D map draws the same features as lines and covers |
70
+ | `SphereLayer` | points | lit spheres - connections, sensors, nodes, tree crowns |
71
+ | `AreaLayer` | polygons | flat fills, solid or hatched, with outlines; or extruded volumes, heights on the GPU, lit windows at night |
72
+
73
+ Every 3D body is ghosted where the scene's surface (the ground) is in front of it and outlined by a
74
+ dark halo, as the Ing+ map draws its buried pipes; never thinner on screen than its look's width in
75
+ pixels, so far off a pipe is a line, still at its depth.
76
+
77
+ ## Styling, filtering, lighting up
78
+
79
+ | What | How | Costs |
80
+ |---|---|---|
81
+ | A style | `layer.setStyle(f => ...)`, `layer.restyle(ids?)` | one write per feature into the look's textures, one upload at the next frame |
82
+ | A filter | `layer.setFilter(f => ..., 'hide' \| 'fade')` | as a style: decided on the CPU |
83
+ | A range | `layer.setRange({ value, low, high, outside })`, then `setRangeBounds(low, high)` | every value written once; a drag step is two uniforms |
84
+ | Categories | `layer.setCategories({ of, keys, colors })`, `setCategoryMode(key, 'hidden' \| 'faded' \| 'shown' \| 'lit')` | one texel per switch; 'lit' lights a whole category, a legend entry pointed at |
85
+ | Colour by | `layer.colorBy({ by: 'category' })`, `colorBy({ value, ramp, domain })` | a uniform and a 256-texel ramp |
86
+ | Hover | the view's pointer, or `layer.setHovered(id)` | one uniform |
87
+ | Selection | a click (Ctrl toggles, Shift adds, Esc clears), or `layer.select(ids, mode)` | a few texels |
88
+ | Emphasis | `layer.emphasize(ids)`: lit as the selection is, without selecting | a few texels |
89
+ | Density | `view.setDensity({ layers, ramp, top })` | the same geometry adding its weight into the heatmap instead |
90
+
91
+ What is lit glows - the bloom pass over the selected geometry alone - or is outlined (`highlight.look`),
92
+ and while the pointer rests on something the rest is shaded (`hoverFades`). Faded features go grey and
93
+ see-through, the same whether the CPU's filter or the GPU's faded them.
94
+
95
+ Several primitives can share one look (`FeatureLook`): an area's fill and its outline, a pipe drawn as
96
+ a tube in 3D and as a line in 2D. They light, filter and colour as one, from one texture upload.
97
+
98
+ Features change in place: `layer.addFeatures`, `updateFeatures` (by id) and `removeFeatures` - and
99
+ `setFeatures` once drawn - build the new geometry and hand it to the primitives already drawn, which
100
+ keep their compiled shaders (`GeometryPrimitive.adopt`). An edit to one pipe of 15,000 costs some
101
+ 50 ms of buffers, not a recompile. `layer.setOverride(ids, 'faded' | 'hidden' | 'selected')` forces a
102
+ state on features whatever their style says: what an editor fades while it works on them.
103
+
104
+ ## Calculations
105
+
106
+ Plain functions on GeoJSON-shaped geometry, in world units - metres in a projected or local
107
+ reference - DOM-free and tested (`npm test`). Lengths and distances count heights unless given
108
+ `dims` 2; areas are across the map, but for `area3D`.
109
+
110
+ | | |
111
+ |---|---|
112
+ | **Measuring** (`Measure.ts`) | `distance`, `distance2D`, `bearing` (clockwise from north), `slope`, `angleAt`, `turnAngle`, `length`, `pathLength`, `perimeter`, `area`, `ringArea` (signed), `area3D` (a roof's true area), `extrudedVolume`, `centroid` (by area, length or count), `pointOnSurface` (inside even a U), `geometryBounds`, `lineProfile` (a pipe's long section: distances, heights, falls) |
113
+ | **Lines** (`Lines.ts`) | `closestOnSegment`, `nearestPointOnLine`, `pointAlong`, `directionAlong`, `lineSlice`, `splitLine`, `splitLineAt`, `densify`, `resample`, `simplify` and `simplifyRing` (Douglas-Peucker), `smooth` (Chaikin), `offsetLine` (mitred), `segmentIntersection`, `lineIntersections` (with the height difference where they cross), `selfIntersections`, `segmentApproach` and `lineApproach` (the clearance between two pipes in 3D) |
114
+ | **Polygons** (`Polygons.ts`) | `pointInRing`, `pointInPolygon`, `pointInGeometry`, `isClockwise`, `orientPolygon`, `convexHull`, `circle`, `ellipse`, `rectangle`, `orientedRectangle`, `regularPolygon`, `arc`, `sector`, `polygonKinks`, `polygonProblems`, `isValidPolygon`, `clipLine` and `clipRing` to a box |
115
+ | **Combining** (`Boolean.ts`) | `union`, `intersection`, `difference`, `xor` ([polygon-clipping](https://github.com/mfogel/polygon-clipping)), and `buffer` round points, lines (a protection strip, round or flat ends) and polygons, grown or shrunk |
116
+ | **Relations** (`Relations.ts`) | `nearestPointOnGeometry`, `distanceToGeometry`, `geometryDistance` (in 3D: a pipe 2 m under another crosses it on the map, not in space), `intersects`, `contains`, `within` |
117
+ | **Transforms** (`Transform.ts`) | `mapPositions`, `translate`, `rotate`, `scale`, `affine`, `applyMatrix`, `withZ`, `dropZ`, `explode`, `combine`, `cloneGeometry` |
118
+ | **Geodesy** (`Geodesy.ts`) | for longitude and latitude: `geodesicDistance` and `geodesicInverse` (Vincenty, to the millimetre), `haversineDistance`, `initialBearing`, `destination`, `interpolateGreatCircle`, `geodesicLength`, `geodesicArea`; and `Projection.ts`'s Web Mercator, geocentric and local frames |
119
+ | **Finding by place** | `SpatialIndex`: a packed R-tree over boxes, `search` and `neighbors` nearest first. `FeatureIndex`: features' points and segments in one, for `nearestVertex`, `nearestEdge`, `featureAt`, `inBox`, `nearestFeatures` - 100,000 features indexed in under 200 ms, a query in a fraction of a millisecond |
120
+ | **Triangulation** (`Triangulate.ts`) | `triangulate` (earcut, in a polygon's own plane, so walls and roofs cut as well as floors) |
121
+
122
+ ## Drawing, editing, measuring
123
+
124
+ A controller takes over the view's pointer and keys for a while, as LuciadRIA's controllers do on
125
+ its map: `view.setController(controller)`, or `<ReactGeometry controller={controller}>`; null gives
126
+ the view its own ways back. It sees every event first and leaves what it does not handle - a drag
127
+ on empty ground still pans, the wheel still zooms.
128
+
129
+ ```ts
130
+ const history = new EditHistory(); // shared: drawing and editing undo in one order
131
+ const draw = new CreateController({ shape: 'polygon', layer: parcels, history });
132
+ draw.on('finish', ({ feature }) => save(feature));
133
+ view.setController(draw);
134
+
135
+ const edit = new EditController({ layers: [parcels, pipes], history });
136
+ edit.on('commit', ({ before, after }) => save(after));
137
+
138
+ const measure = new MeasureController({ mode: 'clearance', radius: (layer, f) => f.properties.dn / 2000 });
139
+ measure.on('change', m => show(m?.clearance));
140
+ ```
141
+
142
+ - **`CreateController`**: points, lines, polygons, rectangles and circles. Click to place, the line
143
+ to the pointer drawn as it moves; double-click, Enter, or a click on the first point (a polygon)
144
+ or the last (a line) finishes. Backspace takes a point back, Escape lets go, Shift turns the way
145
+ from the last point to 15° steps. Lengths of every segment, the total, the area and a circle's
146
+ radius are written beside the shape; a polygon whose edges cross is refused, or whatever
147
+ `validate` says. Finished shapes go into `layer` as features (`feature` makes their id and
148
+ properties).
149
+ - **`EditController`**: click a feature of `layers` to edit it - its shape drawn over it with a
150
+ handle on every vertex, the feature faded under it while it is dragged. Drag a vertex; Alt-drag it up or down (3D: a pipe's
151
+ invert); drag an edge's middle to pull out a new one; double-click a vertex to remove it, an edge
152
+ to add one; drag the shape to move it; T for the transform handles, to scale it from a corner or
153
+ turn it round its middle. Delete removes a selected vertex, else the feature. Each drag is drawn
154
+ on screen only and committed to the layer when let go, into the history: Ctrl+Z, Ctrl+Y.
155
+ - **`MeasureController`**: `distance` along points, `area` inside them, `height` between two
156
+ (the rise, the distance across, the slope), or the `clearance` between two features - the
157
+ nearest their geometries come in 3D, less their radii. Points land on what is drawn under the
158
+ pointer (picked on the GPU: a roof, a pipe), or snap to a vertex or an edge in view.
159
+
160
+ Snapping (`Snapper`) is in the view's own terms: what is within so many pixels of the pointer on
161
+ screen, however deep it lies - the shape's own vertices first, then other features' vertices, then
162
+ their edges, then a grid, if any. A pipe three metres down snaps where it is seen, not where the
163
+ ground under the pointer is. Each layer is indexed once (`FeatureIndex`), in idle time as a
164
+ controller starts, and again when its features change.
165
+
166
+ What a controller draws - the shape, the rubber band, handles, what was snapped to - is a `Sketch`:
167
+ three overlay layers (`view.addOverlay`) drawn over everything, never picked, changed in place every
168
+ pointer move. Measurements are `view.labels`: page elements on world positions, moved every frame.
169
+ The controllers ask the view only for what `ControllerHost` lists - screen and world positions,
170
+ picking, overlays, labels - so a host that draws the engine into its own map can offer the same.
171
+
172
+ ## Engines
173
+
174
+ An engine owns the scenes each pass draws (`scene`, `underlay`, `bloom`, `pick`, `density`,
175
+ `halo`), the camera - the frame's whole view-projection, relative to an origin so float32 vertices
176
+ keep millimetres in UTM or geocentric coordinates - and the scene's depth, `1 - near / w`, which the
177
+ bodies read to tell what lies behind the ground.
178
+
179
+ - **`CanvasGeometryEngine`**: a canvas of its own. It draws `baseScene` (the sky, the ground) into a
180
+ frame of colour and depth, puts that on the canvas, and draws the geometry over it, as a host would.
181
+ Frames on demand, continuously only while something moves (flow, a flight).
182
+ - **`HostedGeometryEngine`**: inside a frame someone else draws with WebGPU. The host gives a device,
183
+ and every frame its colour texture, its depth texture and its camera; three draws into that colour
184
+ texture with the host's device.
185
+ - **`RiaGeometryEngine`**: the hosted engine on a LuciadRIA map, typed by shape (no RIA import):
186
+ `RiaGeometryEngine.of(map)` hooks `PostRender` and `WebGPUDeviceChanged`.
187
+
188
+ A primitive is attached with `engine.attach(primitive)`, or its meshes put into the scenes by hand,
189
+ as the Ing+ map does; every frame it gets `setFrame(frame)`.
190
+
191
+ ## In the Ing+ map
192
+
193
+ The package's primitives and its RIA engine are the map's `layers/three` classes, with the same
194
+ constructors, members and meanings; the map's call sites work unchanged
195
+ ([`src/compat/IngPlusCompat.ts`](src/compat/IngPlusCompat.ts) is exactly those calls, type-checked
196
+ on every `npm run check`).
197
+
198
+ | Ing+ map | Package | Notes |
199
+ |---|---|---|
200
+ | `RiaThreeRenderer.of(map)` / `existing(map)` | `RiaGeometryEngine.of(map)` / `existing(map)` | `scene`, `underlayScene`, `bloomScene`, `pickScene`, `pickPass`, `density`, `frame`, `setOrigin`, `getOrigin`, `depthTexture`, `onBeforeRender`, `onBeforeDraw`, `requestRepaint`, `renderToTarget`, `addPickSource`, `lastRenderMs` |
201
+ | `renderer.pick(x, y)` → `{ layer, feature, point }` | `engine.pick(x, y)` → `{ hit, point: [x, y, z] }` | `hit` is what the pick source returned; make the RIA `Point` with `createPoint(map.reference, pick.point)` |
202
+ | `GpuLines` | `GpuLines` | same options (`ground`, `occluder`, `pick`, `ends`), meshes, uniforms, `setStyle`/`commit`, `setDragStyle`/`commitDrag`; adds `space`, `arrows`, dashes and flow |
203
+ | `GpuIcons` | `GpuIcons` | same constructor (`pick` as the fourth argument, or an options object), `setState`/`commit`, `outlineMode`, `rimRgb`, `othersShade`; adds shapes, pixel sizes, ground icons, depth |
204
+ | `DensityMap` | `DensityMap` | `setColorMap` takes RIA's `ColorMap` as it is, or a list of colours |
205
+ | `iconAtlas`, `ICON_CELL`, `COVER_CELL`, `MANHOLE_COVER`, `OUTLINE_RGB`, `additive`, `LineOccluder`, `LineState`, `ThreeFrame` | the same names (`ThreeFrame` is `GeometryFrame`) | |
206
+ | `ThreePipes`' cylinders, spheres, covers, arrows, halo | `GpuTubes` (+ `joinTubeEnds`), `GpuSpheres`, `GpuIcons` with `orientation: 'ground'`, the engine's `Halo` | the domain stays in the map: which features, their profiles, `pipeCourse`, the painters' looks |
207
+
208
+ Two things to know when moving over:
209
+
210
+ - **Depth.** The map's `ThreePipes` remaps RIA's OpenGL depth (-1..1) to WebGPU's (0..1) in each of
211
+ its shaders. The package's engine folds that into the camera (`glDepth: true`), so the package's
212
+ primitives use clip space as it is. Move `ThreePipes`' shaders to `GpuTubes` and friends together
213
+ with the engine, not one without the other.
214
+ - **What stands in front.** The map's `StandingMask` is a `GeometryOccluder` as it is: pass it as
215
+ `occluder` to `GpuLines`, `GpuTubes`, `GpuSpheres`.
216
+
217
+ Styles stay the painters': where the map calls `lines.setStyle(i, spec)` it still does. The
218
+ package's own `FeatureLook` adds the GPU's category table, colour ramps and hover uniform on top,
219
+ for whoever wants them.
220
+
221
+ ## How it draws
222
+
223
+ - **One draw per pass per layer.** Lines are a quad per segment, tubes a unit cylinder per segment
224
+ turned onto its course, icons a quad each, areas one triangle list - all instanced, all shaped in
225
+ the vertex shader. A town of 100,000 features is about 50 draw calls.
226
+ - **Looks in textures.** Six float textures per look, 1024 texels wide, indexed by feature; a
227
+ category table and a ramp. Uploads are per texture written, batched to one per frame.
228
+ - **Uniforms for what moves.** Hover, range bounds, colour mode, the others' shade, the camera.
229
+ - **Picking on the GPU.** The pick scene is drawn into 7x7 pixels round the pointer, each fragment
230
+ writing its source, its feature and its distance, and read back: what is drawn is what is hit,
231
+ mitres, ghosting and all, never what is hidden or filtered away.
232
+ - **Shaders that compile fast.** The look's values are made variables once (`toVar`); a TSL `select`
233
+ otherwise builds an if/else and rebuilds whatever it holds where it is used again. A view builds
234
+ one layer a frame, so a page of layers shows up layer by layer, and keeps what it built for 2D and
235
+ for 3D, so switching between them is instant after the first time.
236
+
237
+ ## The demo
238
+
239
+ `npm run dev` opens a made-up town: an organic street grid; a gravity sewer flowing to an outfall by
240
+ the river, deeper and wider downstream, with egg profiles, manhole shafts and every building's
241
+ lateral; water, gas and power under the pavements; buildings growing up out of the ground, lit at
242
+ night; flood zones; sensors; a sewer robot's run and a drone's survey flight. Town, City, Metro and
243
+ Region sizes run from 6,000 to some 200,000 features. Colour by material, age, diameter, condition
244
+ or depth; filter by year on the GPU, by diameter on the CPU; hide or light a material from its chip;
245
+ X-ray the buildings; switch to a 2D map; draw the defects' heatmap. The tool bar over the map draws
246
+ points, lines, areas, rectangles and circles, edits anything - a drawn shape, a flood zone, a
247
+ building's footprint, a sewer pipe's course and depth - and measures distances, areas, heights and
248
+ the clearance between two pipes; undo and redo, snapping on or off. Keys: V, P, L, A, R, C, E, D, M,
249
+ H, K.
250
+
251
+ On a phone - under 720 px across or 520 px high - the map fills the screen: the top bar keeps 2D,
252
+ 3D and the view's buttons, the side panel opens over the map from the tune button (a sheet from the
253
+ bottom upright, a drawer from the right on its side), and the tools run along the map's top.
254
+ `?webgl` in the address draws with WebGL 2, as where WebGPU is missing.
255
+
256
+ The demo ships in the package, for an app to show as it is:
257
+
258
+ ```tsx
259
+ import { GeometryDemo } from '@protomaze/geometry/GeometryDemo';
260
+ import { createTown, paintGround, ORIGIN_X, ORIGIN_Y, MATERIALS, MATERIAL_COLORS } from '@protomaze/geometry/demo/Town';
261
+ ```
262
+
263
+ `geometryDemo` in the console has the view, the layers, the data, the history and `setTool`;
264
+ `geometryDemo.snapshot(name)` writes the canvas, labels and all, to `.snapshots/<name>.png` through
265
+ the dev server.
266
+
267
+ ## Publishing
268
+
269
+ Releases go out via [`.github/workflows/publish.yml`](.github/workflows/publish.yml) using npm's
270
+ **Trusted Publishing**: no npm token lives anywhere, in CI or on any laptop. GitHub Actions proves
271
+ its identity to npm with a short-lived OIDC credential scoped to this exact repo and workflow file.
272
+ The workflow type-checks and compiles the sources and publishes `build/`, which is the package.
273
+
274
+ One-time setup (needs the npm account owner, see [Trusted
275
+ Publishers](https://docs.npmjs.com/trusted-publishers)):
276
+
277
+ 1. On npmjs.com, under the package's settings, add a Trusted Publisher: GitHub Actions, repository
278
+ `protomaze/geometry`, workflow file `.github/workflows/publish.yml`. A new configuration must see
279
+ its first successful publish within two days, so push a release tag soon after saving it.
280
+ 2. The package's settings exist only once the package does. If npmjs.com offers no way to add the
281
+ publisher to a package not yet published, publish the very first version by hand, once:
282
+ `npm login --auth-type=web` (a security key works there), then `npm run deploy`.
283
+
284
+ npm checks `repository.url` in `package.json` against the repository the workflow runs in, so it
285
+ must stay `git+https://github.com/protomaze/geometry.git`.
286
+
287
+ After that, a release is:
288
+
289
+ ```bash
290
+ npm version patch # or minor / major - bumps package.json and tags it
291
+ git push --follow-tags
292
+ ```
293
+
294
+ `npm run deploy` and `npm run pub` remain for emergencies and for a local
295
+ [Verdaccio](https://verdaccio.org) on port 4873 respectively, as for `@protomaze/charts`.
@@ -0,0 +1,47 @@
1
+ /** A colour as four floats, 0 to 1, in sRGB as written: what the shaders draw. */
2
+ export type Rgba = [number, number, number, number];
3
+ /** A colour given to the package: any CSS colour, or straight RGBA floats. */
4
+ export type ColorLike = string | Rgba | readonly number[];
5
+ /**
6
+ * Reads a CSS colour: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(), rgba() directly, anything else
7
+ * (names, hsl) through a canvas. Kept in sRGB as written - no conversion to linear - so the
8
+ * geometry's colours are exactly the ones the application gives it.
9
+ */
10
+ export declare function parseColor(color: ColorLike | undefined | null, fallback?: Rgba): Rgba;
11
+ export declare function toCss([r, g, b, a]: Rgba): string;
12
+ /** A colour moved towards its own grey by `amount` (0 keeps it, 1 is the grey). */
13
+ export declare function desaturate([r, g, b, a]: Rgba, amount: number): Rgba;
14
+ /** A colour with another alpha. */
15
+ export declare function withAlpha(color: ColorLike, alpha: number): Rgba;
16
+ /**
17
+ * Something that gives a colour for a level: a list of colours spread evenly from 0 to 1, or an
18
+ * object with `retrieveColor` - LuciadRIA's `ColorMap` is one, so a painter's density colour map
19
+ * can be handed over as it is.
20
+ */
21
+ export type ColorRamp = readonly ColorLike[] | {
22
+ retrieveColor(level: number): string;
23
+ };
24
+ /**
25
+ * A ramp sampled at `steps` levels from `low` to `high`, as straight RGBA floats, four a step:
26
+ * what the ramp textures hold.
27
+ */
28
+ export declare function sampleRamp(ramp: ColorRamp, steps: number, low?: number, high?: number): Float32Array;
29
+ /** The ramp's colour at `level`, between `low` and `high`. */
30
+ export declare function rampColor(ramp: ColorRamp, level: number, low?: number, high?: number): Rgba;
31
+ /** Ramps that read well over a dark map, low to high. */
32
+ export declare const RAMPS: {
33
+ /** Cool blue to hot yellow, perceptually even (after viridis). */
34
+ readonly viridis: readonly ["#440154", "#3b528b", "#21918c", "#5ec962", "#fde725"];
35
+ /** Black through purple and orange to pale yellow (after magma). */
36
+ readonly magma: readonly ["#000004", "#3b0f70", "#8c2981", "#de4968", "#fe9f6d", "#fcfdbf"];
37
+ /** Deep blue to red through cyan, green and yellow (after turbo). */
38
+ readonly turbo: readonly ["#30123b", "#4686fb", "#1be5b5", "#a4fc3c", "#fbb938", "#e4460a", "#7a0403"];
39
+ /** Good to bad: green, yellow, orange, red. */
40
+ readonly condition: readonly ["#1a9850", "#91cf60", "#fee08b", "#fc8d59", "#d73027"];
41
+ /** The heatmap: transparent blue to white hot. */
42
+ readonly heat: readonly ["#00000000", "#1b2a8c", "#2a7fff", "#2ee6c8", "#f4f86a", "#ff8c3a", "#ff2d55", "#ffffff"];
43
+ /** Ice: dark teal to white. */
44
+ readonly ice: readonly ["#04232b", "#0b5563", "#1fa3b5", "#7fe3f0", "#f2feff"];
45
+ };
46
+ /** Twelve distinct colours for categories, bright enough over a dark map. */
47
+ export declare const CATEGORY_COLORS: string[];
@@ -0,0 +1 @@
1
+ const t=new Map;let e;export function parseColor(n,f=[.5,.5,.5,1]){if(!n)return f;if("string"!=typeof n)return[n[0]??0,n[1]??0,n[2]??0,n[3]??1];const o=t.get(n);if(o)return o;const a=r(n.trim())??function(t){return"undefined"==typeof document?void 0:(e??(e=document.createElement("canvas").getContext("2d")),e?(e.fillStyle="#000",e.fillStyle=t,r(String(e.fillStyle))):void 0)}(n)??f;return t.size>4096&&t.clear(),t.set(n,a),a}function r(t){if(t.startsWith("#")){const e=t.slice(1),r=(t,r)=>parseInt(e.slice(t*r,t*r+r).repeat(3-r),16)/255;if(!/^[0-9a-fA-F]+$/.test(e))return;return 3===e.length||4===e.length?[r(0,1),r(1,1),r(2,1),4===e.length?r(3,1):1]:6===e.length||8===e.length?[r(0,2),r(1,2),r(2,2),8===e.length?r(3,2):1]:void 0}const e=/^rgba?\(([^)]+)\)$/i.exec(t);if(e){const t=e[1].split(/[\s,/]+/).filter(Boolean);if(t.length<3)return;const r=t=>t.endsWith("%")?parseFloat(t)/100:parseFloat(t)/255,n=void 0===t[3]?1:t[3].endsWith("%")?parseFloat(t[3])/100:parseFloat(t[3]);return[r(t[0]),r(t[1]),r(t[2]),n]}}export function toCss([t,e,r,n]){const f=t=>Math.round(255*Math.min(1,Math.max(0,t)));return`rgba(${f(t)}, ${f(e)}, ${f(r)}, ${Math.round(1e3*n)/1e3})`}export function desaturate([t,e,r,n],f){const o=(t+e+r)/3;return[t+(o-t)*f,e+(o-e)*f,r+(o-r)*f,n]}export function withAlpha(t,e){const[r,n,f]=parseColor(t);return[r,n,f,e]}export function sampleRamp(t,e,r=0,n=1){const f=new Float32Array(4*e);for(let o=0;o<e;o++){const a=1===e?0:o/(e-1);f.set(rampColor(t,r+(n-r)*a,r,n),4*o)}return f}export function rampColor(t,e,r=0,n=1){if(!Array.isArray(t))return parseColor(t.retrieveColor(e));const f=t;if(0===f.length)return[0,0,0,0];if(1===f.length)return parseColor(f[0]);const o=Math.min(1,Math.max(0,(e-r)/(n-r||1)))*(f.length-1),a=Math.min(f.length-2,Math.floor(o)),i=parseColor(f[a]),c=parseColor(f[a+1]),s=o-a;return[i[0]+(c[0]-i[0])*s,i[1]+(c[1]-i[1])*s,i[2]+(c[2]-i[2])*s,i[3]+(c[3]-i[3])*s]}export const RAMPS={viridis:["#440154","#3b528b","#21918c","#5ec962","#fde725"],magma:["#000004","#3b0f70","#8c2981","#de4968","#fe9f6d","#fcfdbf"],turbo:["#30123b","#4686fb","#1be5b5","#a4fc3c","#fbb938","#e4460a","#7a0403"],condition:["#1a9850","#91cf60","#fee08b","#fc8d59","#d73027"],heat:["#00000000","#1b2a8c","#2a7fff","#2ee6c8","#f4f86a","#ff8c3a","#ff2d55","#ffffff"],ice:["#04232b","#0b5563","#1fa3b5","#7fe3f0","#f2feff"]};export const CATEGORY_COLORS=["#4cc9f0","#f72585","#b5e48c","#ffb703","#9b5de5","#00f5d4","#fb8500","#e9ff70","#ff70a6","#70d6ff","#ff9770","#c0fdff"];
@@ -0,0 +1,7 @@
1
+ export declare class Disposables {
2
+ private disposables;
3
+ private disposed;
4
+ add(disposable: () => void): void;
5
+ dispose(): void;
6
+ disposeLater(): () => void;
7
+ }
@@ -0,0 +1 @@
1
+ export class Disposables{constructor(){this.disposables=[],this.disposed=!1}add(s){this.disposed?s():this.disposables.push(s)}dispose(){this.disposed=!0,this.disposables.forEach(s=>s())}disposeLater(){return()=>{this.dispose()}}}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The geometry a layer draws, GeoJSON-shaped but in any world reference the application likes:
3
+ * positions are `[x, y]` or `[x, y, z]` in world units - metres in a projected reference, a
4
+ * local frame, or geocentric (ECEF) on a globe. Nothing here projects; `Projection.ts` has the
5
+ * helpers for longitude and latitude.
6
+ */
7
+ export type Position = readonly number[];
8
+ export type PointGeometry = {
9
+ type: 'Point';
10
+ coordinates: Position;
11
+ };
12
+ export type MultiPointGeometry = {
13
+ type: 'MultiPoint';
14
+ coordinates: readonly Position[];
15
+ };
16
+ export type LineStringGeometry = {
17
+ type: 'LineString';
18
+ coordinates: readonly Position[];
19
+ };
20
+ export type MultiLineStringGeometry = {
21
+ type: 'MultiLineString';
22
+ coordinates: readonly (readonly Position[])[];
23
+ };
24
+ /** Rings, the outer first, holes after it. */
25
+ export type PolygonGeometry = {
26
+ type: 'Polygon';
27
+ coordinates: readonly (readonly Position[])[];
28
+ };
29
+ export type MultiPolygonGeometry = {
30
+ type: 'MultiPolygon';
31
+ coordinates: readonly (readonly (readonly Position[])[])[];
32
+ };
33
+ export type Geometry = PointGeometry | MultiPointGeometry | LineStringGeometry | MultiLineStringGeometry | PolygonGeometry | MultiPolygonGeometry;
34
+ export type GeometryId = string | number;
35
+ /** One thing on the map: its id, its shape and whatever the application keeps with it. */
36
+ export interface GeometryFeature<P = Record<string, any>> {
37
+ id: GeometryId;
38
+ geometry: Geometry | null;
39
+ properties: P;
40
+ }
41
+ /** An axis-aligned box in world units. */
42
+ export interface Bounds3 {
43
+ min: [number, number, number];
44
+ max: [number, number, number];
45
+ }
46
+ export declare function emptyBounds(): Bounds3;
47
+ export declare function isEmptyBounds(bounds: Bounds3): boolean;
48
+ export declare function extendBounds(bounds: Bounds3, p: Position): Bounds3;
49
+ export declare function unionBounds(a: Bounds3, b: Bounds3): Bounds3;
50
+ /** Every position of a geometry, in order. */
51
+ export declare function forEachPosition(geometry: Geometry | null | undefined, visit: (p: Position) => void): void;
52
+ export declare function boundsOf(features: Iterable<GeometryFeature<any>>): Bounds3;
53
+ /** The lines of a line geometry - one, or a multi-line's parts - or none for another kind. */
54
+ export declare function linesOf(geometry: Geometry | null | undefined): readonly (readonly Position[])[];
55
+ /** The points of a point geometry - one, or a multi-point's - or none for another kind. */
56
+ export declare function pointsOf(geometry: Geometry | null | undefined): readonly Position[];
57
+ /** The polygons of an area geometry, each its rings; none for another kind. */
58
+ export declare function polygonsOf(geometry: Geometry | null | undefined): readonly (readonly (readonly Position[])[])[];
59
+ /** A line's length in world units, along all its segments. */
60
+ export declare function lineLength(line: readonly Position[]): number;
61
+ /** The point halfway along a line, by length. */
62
+ export declare function lineMiddle(line: readonly Position[]): [number, number, number];
@@ -0,0 +1 @@
1
+ export function emptyBounds(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}export function isEmptyBounds(n){return!(n.min[0]<=n.max[0])}export function extendBounds(n,t){const o=t[2]??0;return t[0]<n.min[0]&&(n.min[0]=t[0]),t[1]<n.min[1]&&(n.min[1]=t[1]),o<n.min[2]&&(n.min[2]=o),t[0]>n.max[0]&&(n.max[0]=t[0]),t[1]>n.max[1]&&(n.max[1]=t[1]),o>n.max[2]&&(n.max[2]=o),n}export function unionBounds(n,t){return{min:[Math.min(n.min[0],t.min[0]),Math.min(n.min[1],t.min[1]),Math.min(n.min[2],t.min[2])],max:[Math.max(n.max[0],t.max[0]),Math.max(n.max[1],t.max[1]),Math.max(n.max[2],t.max[2])]}}export function forEachPosition(n,t){if(n)switch(n.type){case"Point":t(n.coordinates);break;case"MultiPoint":case"LineString":n.coordinates.forEach(t);break;case"MultiLineString":case"Polygon":n.coordinates.forEach(n=>n.forEach(t));break;case"MultiPolygon":n.coordinates.forEach(n=>n.forEach(n=>n.forEach(t)))}}export function boundsOf(n){const t=emptyBounds();for(const o of n)forEachPosition(o.geometry,n=>extendBounds(t,n));return t}export function linesOf(n){return n?"LineString"===n.type?[n.coordinates]:"MultiLineString"===n.type?n.coordinates:[]:[]}export function pointsOf(n){return n?"Point"===n.type?[n.coordinates]:"MultiPoint"===n.type?n.coordinates:[]:[]}export function polygonsOf(n){return n?"Polygon"===n.type?[n.coordinates]:"MultiPolygon"===n.type?n.coordinates:[]:[]}export function lineLength(n){let t=0;for(let o=1;o<n.length;o++){const e=n[o-1],i=n[o];t+=Math.hypot(i[0]-e[0],i[1]-e[1],(i[2]??0)-(e[2]??0))}return t}export function lineMiddle(n){const t=lineLength(n)/2;let o=0;for(let e=1;e<n.length;e++){const i=n[e-1],r=n[e],a=Math.hypot(r[0]-i[0],r[1]-i[1],(r[2]??0)-(i[2]??0));if(o+a>=t&&a>0){const n=(t-o)/a;return[i[0]+(r[0]-i[0])*n,i[1]+(r[1]-i[1])*n,(i[2]??0)+((r[2]??0)-(i[2]??0))*n]}o+=a}const e=n[0]??[0,0,0];return[e[0],e[1],e[2]??0]}
@@ -0,0 +1,68 @@
1
+ import { CSSProperties, ReactNode } from 'react';
2
+ /** The Protomaze demos' accent: lime under the pointer, olive for what is on. */
3
+ export declare const ACCENT = "#df0";
4
+ /** Panels as @protomaze/time's demo has them: rounded, near black or near white. */
5
+ export declare function panelStyle(dark: boolean): CSSProperties;
6
+ /** A text button, lit while `active`: a choice of a group, or a switch that is on. */
7
+ export declare function DemoButton({ text, active, onClick, disabled, title }: {
8
+ text: ReactNode;
9
+ active?: boolean;
10
+ onClick?: () => void;
11
+ disabled?: boolean;
12
+ title?: string;
13
+ }): JSX.Element;
14
+ /** A Material Symbols icon as a button, as the time slider's demo has them. */
15
+ export declare function DemoIconButton({ icon, active, onClick, title }: {
16
+ icon: string;
17
+ active?: boolean;
18
+ onClick?: () => void;
19
+ title?: string;
20
+ }): JSX.Element;
21
+ /** A select in the buttons' look. */
22
+ export declare function DemoSelect<T extends string | number>({ value, options, onChange, label }: {
23
+ value: T;
24
+ options: {
25
+ value: T;
26
+ text: string;
27
+ }[];
28
+ onChange: (value: T) => void;
29
+ label?: string;
30
+ }): JSX.Element;
31
+ /** Full screen for the element the demo fills, and back. */
32
+ export declare function FullscreenButton({ target }: {
33
+ target: () => HTMLElement | null;
34
+ }): JSX.Element;
35
+ /** A thin upright line between groups of buttons. */
36
+ export declare function Divider(): JSX.Element;
37
+ /** A section of a side panel: a small heading and what goes under it. */
38
+ export declare function Section({ title, right, children }: {
39
+ title: string;
40
+ right?: ReactNode;
41
+ children: ReactNode;
42
+ }): JSX.Element;
43
+ /** Two thumbs on one track: a range of whole numbers. */
44
+ export declare function RangeSlider({ min, max, value, onChange, format }: {
45
+ min: number;
46
+ max: number;
47
+ value: [number, number];
48
+ onChange: (value: [number, number]) => void;
49
+ format?: (value: number) => string;
50
+ }): JSX.Element;
51
+ /** One thumb on a track. */
52
+ export declare function Slider({ min, max, step, value, onChange, format }: {
53
+ min: number;
54
+ max: number;
55
+ step?: number;
56
+ value: number;
57
+ onChange: (value: number) => void;
58
+ format?: (value: number) => string;
59
+ }): JSX.Element;
60
+ /** A coloured chip: a legend entry that can be switched off, lit while pointed at. */
61
+ export declare function Chip({ color, text, on, onClick, onHover, count }: {
62
+ color: string;
63
+ text: string;
64
+ on: boolean;
65
+ onClick: () => void;
66
+ onHover?: (hovered: boolean) => void;
67
+ count?: number;
68
+ }): JSX.Element;
@@ -0,0 +1 @@
1
+ import e,{useEffect as t,useState as n}from"react";export const ACCENT="#df0";export function panelStyle(e){return{borderRadius:4,backgroundColor:e?"#222":"#ddd"}}function o(e,t,n){return{height:22,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,backgroundColor:t?"#df0":e?"#780":"#0008",color:e||t?"#000":"#fff",fontFamily:"Roboto, sans-serif",fontWeight:500,fontSize:12,letterSpacing:"0.5px",padding:"2px 6px",border:"none",borderRadius:4,cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.2)",transition:"background-color 0.2s, box-shadow 0.2s",whiteSpace:"nowrap",...n}}function r(){const[e,t]=n(!1);return{hovered:e,bind:{onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1)}}}export function DemoButton({text:t,active:n=!1,onClick:a,disabled:i,title:l}){const{hovered:c,bind:s}=r();return e.createElement("button",{...s,onClick:a,disabled:i,title:l,style:o(n,c&&!i,i?{opacity:.4,cursor:"default"}:void 0)},t)}export function DemoIconButton({icon:n,active:a=!1,onClick:i,title:l}){const{hovered:c,bind:s}=r();return t(()=>{const e="protomaze-material-symbols";if(document.getElementById(e))return;const t=document.createElement("link");t.id=e,t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200",document.head.appendChild(t)},[]),e.createElement("button",{...s,onClick:i,title:l,style:o(a,c,{width:22,padding:2})},e.createElement("span",{className:"material-symbols-outlined",style:{fontSize:18,lineHeight:1,fontVariationSettings:"'FILL' 1"}},n))}export function DemoSelect({value:t,options:n,onChange:a,label:i}){const{hovered:l,bind:c}=r();return e.createElement("select",{...c,value:t,"aria-label":i,onChange:e=>a(n.find(t=>String(t.value)===e.target.value).value),style:o(!1,l,{appearance:"auto",padding:"0 4px",outline:"none"})},n.map(t=>e.createElement("option",{key:String(t.value),value:t.value,style:{background:"#222",color:"#fff"}},t.text)))}export function FullscreenButton({target:o}){const[r,a]=n(!1);return t(()=>{const e=()=>a(null!==document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]),e.createElement(DemoIconButton,{icon:r?"fullscreen_exit":"fullscreen",title:"Full screen",onClick:()=>{document.fullscreenElement?document.exitFullscreen():o()?.requestFullscreen?.()}})}export function Divider(){return e.createElement("div",{style:{width:1,height:16,background:"#fff3",flex:"none"}})}export function Section({title:t,right:n,children:o}){return e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:6}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:6}},e.createElement("span",{style:{fontSize:11,letterSpacing:"0.8px",textTransform:"uppercase",opacity:.6,flex:1}},t),n),o)}export function RangeSlider({min:t,max:n,value:o,onChange:r,format:a=String}){const[i,l]=o,c=e=>(e-t)/(n-t)*100,s={position:"absolute",inset:0,width:"100%",margin:0,background:"none",pointerEvents:"none",appearance:"none",WebkitAppearance:"none",accentColor:"#df0",height:18};return e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},e.createElement("div",{style:{position:"relative",height:18}},e.createElement("div",{style:{position:"absolute",left:0,right:0,top:8,height:2,background:"#fff2",borderRadius:1}}),e.createElement("div",{style:{position:"absolute",left:`${c(i)}%`,right:100-c(l)+"%",top:7,height:4,background:"#df0",borderRadius:2}}),e.createElement("input",{type:"range",className:"demo-thumb",min:t,max:n,value:i,style:s,onChange:e=>r([Math.min(Number(e.target.value),l),l])}),e.createElement("input",{type:"range",className:"demo-thumb",min:t,max:n,value:l,style:s,onChange:e=>r([i,Math.max(Number(e.target.value),i)])})),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,opacity:.75}},e.createElement("span",null,a(i)),e.createElement("span",null,a(l))))}export function Slider({min:t,max:n,step:o=1,value:r,onChange:a,format:i=String}){return e.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},e.createElement("input",{type:"range",min:t,max:n,step:o,value:r,onChange:e=>a(Number(e.target.value)),style:{flex:1,accentColor:"#df0",margin:0}}),e.createElement("span",{style:{fontSize:11,opacity:.75,minWidth:54,textAlign:"right"}},i(r)))}export function Chip({color:t,text:n,on:o,onClick:a,onHover:i,count:l}){const{hovered:c,bind:s}=r();return e.createElement("button",{onClick:a,onMouseEnter:()=>{s.onMouseEnter(),i?.(!0)},onMouseLeave:()=>{s.onMouseLeave(),i?.(!1)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 8px 3px 6px",borderRadius:11,border:"1px solid "+(c?"#df0":"#ffffff22"),background:o?"#ffffff10":"transparent",color:"inherit",font:"inherit",fontSize:12,cursor:"pointer",opacity:o?1:.45,transition:"opacity 0.2s, border-color 0.2s"}},e.createElement("span",{style:{width:10,height:10,borderRadius:5,background:t,boxShadow:o?`0 0 6px ${t}`:"none"}}),n,void 0!==l&&e.createElement("span",{style:{opacity:.55,fontSize:11}},l.toLocaleString()))}