Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

12.3 KB
Raw Blame
import { toLonLat, signedArea, pointIn, bounds } from './geo.mjs';
import { analyzeFlight } from './log.mjs';
import { ASSUMPTIONS } from './project.mjs';
export const escapeHTML = value => String(value).replace(/[&<>"']/g,c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
export const slug = value => String(value).normalize('NFKD').replace(/[\u0300-\u036f]/g,'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,70) || 'survey';
const csvCell = value => { const s = String(value ?? ''); return /[",\r\n]/.test(s) ? '"'+s.replace(/"/g,'""')+'"' : s; };
const csv = rows => rows.map(row => row.map(csvCell).join(',')).join('\r\n')+'\r\n';
const round = (n,d=3) => Number(n.toFixed(d));
export function regionGeometry(origin,rings) {
  const outers=rings.filter(r => signedArea(r)>0), holes=rings.filter(r => signedArea(r)<0);
  const closed=ring => [...ring,ring[0]].map(p => toLonLat(origin,p).map(n => round(n,9)));
  const owners=holes.map(hole=>outers.map((outer,i)=>({i,area:Math.abs(signedArea(outer)),contains:pointIn([outer],hole[0])})).filter(o=>o.contains).sort((a,b)=>a.area-b.area)[0]?.i);
  return {type:'MultiPolygon',coordinates:outers.map((outer,i) => [closed(outer),...holes.filter((_,j) => owners[j]===i).map(closed)])};
}
export function mapSVG(plan) {
  const b=bounds(plan.project.areas.map(a=>a.ring)),w=940,h=540,scale=Math.min((w-100)/b.size[0],(h-100)/b.size[1]),x=p=>50+(p[0]-b.min[0])*scale,y=p=>h-50-(p[1]-b.min[1])*scale;
  const path=points=>points.map((p,i)=>(i?'L':'M')+x(p).toFixed(2)+' '+y(p).toFixed(2)).join(' '),e=analyzeFlight(plan);
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" role="img" aria-label="Survey plan and recorded track" style="width:100%;height:auto;background:#f0f3e8;border-radius:8px"><title>${escapeHTML(plan.project.title)}</title>${plan.project.areas.map(a=>`<path d="${path(a.ring)}Z" fill="${a.kind==='exclusion'?'#e7d4c1':'#d8e3c7'}" stroke="${a.kind==='exclusion'?'#b78869':'#8fA579'}" stroke-width="1.5"/>`).join('')}${plan.sorties.map(s=>`<path d="${path(s.path)}" fill="none" stroke="#c26d43" stroke-width="1.25"/>`).join('')}${e?e.paths.map(points=>`<path d="${path(points)}" fill="none" stroke="#267d81" stroke-width="2.5"/>`).join(''):''}<circle cx="${x(plan.project.home)}" cy="${y(plan.project.home)}" r="7" fill="#28462e" stroke="white" stroke-width="2"/><text x="${x(plan.project.home)+12}" y="${y(plan.project.home)+4}" fill="#28462e" font-family="system-ui" font-size="11">Takeoff</text><text x="${w-40}" y="35" font-family="system-ui" font-size="17" fill="#7a8b6c">N ↑</text><text x="24" y="${h-16}" font-family="system-ui" font-size="11" fill="#68775a">Orange: planned routes${e?' · Teal: recorded track (gaps unconnected)':''} · Level-ground model</text></svg>`;
}
export function geoJSON(plan) {
  const p=plan.project, point=pnt => toLonLat(p.origin,pnt).map(n => round(n,9)), feature=(name,kind,geometry,extra={}) => ({type:'Feature',properties:{name,kind,...extra},geometry});
  const features=p.areas.map(area => feature(area.name,area.kind,{type:'Polygon',coordinates:[[...area.ring,area.ring[0]].map(point)]},{id:area.id,locked:area.locked}));
  features.push(feature('Takeoff','takeoff',{type:'Point',coordinates:point(p.home)}));
  features.push(feature('Inset flight region','flight-region',regionGeometry(p.origin,plan.region)));
  features.push(feature('Nominal image coverage','planned-footprints',regionGeometry(p.origin,plan.covered)));
  features.push(feature('Nominal coverage gaps','planned-gaps',regionGeometry(p.origin,plan.gaps)));
  for (const sortie of plan.sorties) features.push(feature('Sortie '+sortie.id,'planned-route',{type:'LineString',coordinates:sortie.path.map(point)},{sortie:sortie.id,heightAboveTakeoffM:p.settings.height,nominalSeconds:round(sortie.seconds)}));
  for (const photo of plan.photos) features.push(feature('Photo '+photo.id,'planned-photo',{type:'Point',coordinates:point(photo.point)},{photo:photo.id,sortie:photo.sortie,run:photo.run,secondsAfterTakeoff:round(photo.time),heightAboveTakeoffM:p.settings.height,headingDegreesFromNorth:round((90-photo.heading+360)%360)}));
  const evidence=analyzeFlight(plan);
  if(evidence){for(const [i,path] of evidence.paths.entries())if(path.length>1)features.push(feature('Recorded track '+(i+1),'recorded-track',{type:'LineString',coordinates:path.map(point)},{source:p.log.name,sha256:p.log.sha256}));if(evidence.covered.length)features.push(feature('Estimated recorded-event footprints','recorded-footprints',regionGeometry(p.origin,evidence.covered),{interpretation:evidence.interpretation}));}
  return {type:'FeatureCollection',name:p.title,assumptions:ASSUMPTIONS,features};
}
export function photoCSV(plan) {
  const p=plan.project;
  return csv([['photo','sortie','run','longitude_deg','latitude_deg','height_above_takeoff_m','heading_from_north_deg','nominal_elapsed_s'],...plan.photos.map(shot => [shot.id,shot.sortie,shot.run,...toLonLat(p.origin,shot.point).map(n => round(n,9)),p.settings.height,round((90-shot.heading+360)%360),round(shot.time)])]);
}
export function routeCSV(plan) {
  const p=plan.project,rows=[['sortie','sequence','phase','longitude_deg','latitude_deg','height_above_takeoff_m','nominal_elapsed_s']];
  for(const sortie of plan.sorties){let index=0;for(const leg of sortie.legs){let elapsed=leg.start;for(let i=0;i<leg.points.length;i++){if(i)elapsed+=Math.hypot(...leg.points[i].map((n,j)=>n-leg.points[i-1][j]))/p.settings.speed;rows.push([sortie.id,++index,leg.kind,...toLonLat(p.origin,leg.points[i]).map(n=>round(n,9)),p.settings.height,round(elapsed)]);}}}
  return csv(rows);
}
export function flightCSV(plan) {
  if(!plan.project.log)return null;
  return csv([['elapsed_s','longitude_deg','latitude_deg','height_above_takeoff_m','heading_from_north_deg','battery_percent','capture_event','break_before','source_row'],...plan.project.log.records.map(row=>[row.time,...toLonLat(plan.project.origin,row.point).map(n=>round(n,9)),row.altitude,row.heading,row.battery,row.capture===null?'':row.capture?1:0,row.breakBefore?1:0,row.sourceRow])]);
}
export function kml(plan) {
  const p=plan.project, coords=points=>points.map(point=>toLonLat(p.origin,point).map(n=>round(n,9)).join(',')+',0').join(' '), polygon=area=>`<Placemark><name>${escapeHTML(area.name)}</name><styleUrl>#${area.kind}</styleUrl><Polygon><altitudeMode>clampToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>${coords([...area.ring,area.ring[0]])}</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>`;
  return `<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>${escapeHTML(p.title)}</name><description>${escapeHTML(ASSUMPTIONS+' Map overlay only; all KML geometry is clamped to ground. Heights and photo timing are in the CSV files. This is not an aircraft mission file.')}</description><Style id="boundary"><LineStyle><color>ff5c794c</color><width>2</width></LineStyle><PolyStyle><color>334f7c5c</color></PolyStyle></Style><Style id="exclusion"><LineStyle><color>ff5353c2</color><width>2</width></LineStyle><PolyStyle><color>335353c2</color></PolyStyle></Style><Style id="route"><LineStyle><color>ff236cf0</color><width>2</width></LineStyle></Style>${p.areas.map(polygon).join('')}${plan.sorties.map(s=>`<Placemark><name>Sortie ${s.id} · ${(s.seconds/60).toFixed(1)} nominal minutes</name><styleUrl>#route</styleUrl><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>${coords(s.path)}</coordinates></LineString></Placemark>`).join('')}<Placemark><name>Takeoff</name><Point><coordinates>${coords([p.home])}</coordinates></Point></Placemark></Document></kml>`;
}
export function report(plan) {
  const evidence=analyzeFlight(plan);
  return {schema:'vector-report/2',project:plan.project.title,assumptions:ASSUMPTIONS,siteAreaM2:round(plan.area),camera:plan.camera,nominalCoveragePercent:round(plan.coverage*100),photos:plan.photos.length,flightLines:plan.runs.length,nominalDistanceM:round(plan.totalDistance),nominalSeconds:round(plan.totalSeconds),sortieBudgetSeconds:plan.budgetSeconds,sorties:plan.sorties.map(s=>({id:s.id,photos:s.photos.length,distanceM:round(s.distance),seconds:round(s.seconds),remainingBudgetSeconds:round(s.remainingSeconds)})),recorded:evidence?{...evidence,paths:undefined,covered:undefined,source:plan.project.log.name,sourceSHA256:plan.project.log.sha256,mapping:plan.project.log.mapping}:null};
}
export function reportHTML(plan) {
  const r=report(plan),p=plan.project,e=r.recorded,esc=escapeHTML;
  return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${esc(p.title)} · survey report</title><style>body{font:16px/1.6 system-ui;max-width:950px;padding:40px;margin:auto;color:#21362c}h1{font-size:42px;line-height:1.1}small{color:#57655c}table{border-collapse:collapse;width:100%}td,th{padding:10px;text-align:left;border-bottom:1px solid #dce4dc}section{margin:32px 0}.cards{display:flex;gap:30px;flex-wrap:wrap}.cards b{display:block;font-size:27px}pre{white-space:pre-wrap;word-break:break-word;font:12px monospace}button{padding:10px 15px}@media print{button{display:none}body{padding:0;font-size:13px;line-height:1.5}h1{font-size:32px}h2{font-size:19px;break-after:avoid}section{margin:18px 0}p,pre,tr,.cards,svg{break-inside:avoid}td,th{padding:7px 8px}.cards{gap:23px}.cards b{font-size:23px}pre{font-size:10px}svg{max-height:265px}table{break-inside:avoid}}@page{margin:18mm;@bottom-right{content:"Vector · " counter(page);font:9px system-ui;color:#60715e}}</style><small>VECTOR / FIELD SURVEY REPORT</small><h1>${esc(p.title)}</h1><p>${esc(p.brief)}</p><button onclick="print()">Print / Save PDF</button><section>${mapSVG(plan)}</section><section class="cards"><div><b>${(r.siteAreaM2/10000).toFixed(2)} ha</b>Supplied target area</div><div><b>${r.nominalCoveragePercent.toFixed(1)}%</b>Nominal footprint coverage</div><div><b>${r.photos}</b>Planned captures</div><div><b>${r.sorties.length}</b>Sorties</div></section><p>${esc(ASSUMPTIONS)}</p><p>GSD ${r.camera.gsdX.toFixed(2)} × ${r.camera.gsdY.toFixed(2)} cm/px; footprint ${r.camera.width.toFixed(1)} × ${r.camera.along.toFixed(1)} m. Height ${p.settings.height} m above takeoff; speed ${p.settings.speed} m/s. Requested front/side overlap ${(p.settings.frontOverlap*100).toFixed(0)}% / ${(p.settings.sideOverlap*100).toFixed(0)}%; overlaps apply along regular survey runs. Exclusions and boundaries can leave gaps.</p><p>Budget: ${p.settings.usableMinutes} measured usable minutes minus ${p.settings.reservePercent}% reserve. Nominal time includes climb, descent, survey, connected transits, configured turn allowance and a routed return to takeoff. No battery or flight-dynamics model is implied.</p><table><thead><tr><th>Sortie</th><th>Captures</th><th>Distance</th><th>Nominal duration</th><th>Unused budget</th></tr></thead><tbody>${r.sorties.map(s=>`<tr><td>${s.id}</td><td>${s.photos}</td><td>${s.distanceM.toFixed(0)} m</td><td>${(s.seconds/60).toFixed(1)} min</td><td>${s.remainingBudgetSeconds.toFixed(0)} s</td></tr>`).join('')}</tbody></table>${e?`<section><h2>Recorded evidence</h2><p>${esc(e.source)} · comparison: ${e.comparisonSortie?'sortie '+e.comparisonSortie:'all planned routes'}. ${esc(e.interpretation)}</p><p>${e.captureEvents} recorded capture events; ${e.modeledCaptures} footprint estimates; ${e.unmodeledCaptures} events lack height or heading. ${e.unknownCaptureSamples} samples have unknown capture state. Estimated event coverage of the whole target: ${e.coverage===null?'unavailable':(e.coverage*100).toFixed(1)+'%'}.</p><p>${e.outsideSamples} logged positions and ${e.outsideSegments} connected segments fall outside the inset flight area. ${e.discontinuities} track breaks; ${e.missingCoordinates} rows lack coordinates. Segments longer than ${e.maxGap} seconds are not connected. 95th-percentile distance from the nearest compared route: ${e.deviationP95.toFixed(1)} m.</p><pre>Source SHA-256: ${esc(e.sourceSHA256)}\nMapping: ${esc(JSON.stringify(e.mapping,null,2))}</pre></section>`:''}<section><h2>Files &amp; coordinates</h2><p>GeoJSON and KML support map review; CSVs retain coordinates, height above takeoff and nominal timing. Keep planner.html and project JSON to edit. Origin: ${p.origin[0]}, ${p.origin[1]} (WGS 84 longitude, latitude); local vertices use east/north meters. Coordinate precision does not establish survey accuracy. No aircraft mission is included.</p></section></html>`;
}