brep_render/metadata.rs
1//! The Properties-panel DATA layer (UI comes later): a name-keyed metadata
2//! store, per-entity measurements, and object provenance — all engine-native,
3//! all crossing the R3 boundary as plain JSON/scalars.
4//!
5//! # Metadata store ([`MetadataStore`])
6//!
7//! `object name → { attribute → value }`, keyed by the KERNEL OBJECT NAME (a
8//! solid / face / edge name), **not** a feature id. This loose coupling is the
9//! whole point: a record survives feature edits, rollback and re-tessellation as
10//! long as the object's name persists (edge/face names ARE propagated through
11//! booleans, splits and welds by the kernel). Values are strings; the well-known
12//! `density` attribute (mass units per mm³) drives a solid's weight. The store is
13//! persisted WITH the model — [`crate::engine_state::EngineState::history_request_json`]
14//! folds it in as a top-level `metadata` field and
15//! [`crate::engine_state::EngineState::set_history_json`] lifts it back out, so it
16//! round-trips through save/open.
17//!
18//! # Measurements + provenance
19//!
20//! The [`EngineState`] methods below resolve an object NAME to its kind (solid /
21//! face / edge, via the scene) and return the right measurements from the
22//! kernel's exact integrators (volume, surface area, arc length), plus the
23//! feature that produced the object (provenance, via the history's per-feature
24//! output solids). Units are millimetres (the kernel length convention).
25
26use crate::engine_state::EngineState;
27use brep_kernel::COLOR_METADATA_KEY;
28use crate::runner::{MeasureKind, MeasureQuery};
29use serde_json::Value;
30use std::collections::BTreeMap;
31
32/// The default density (mass per unit volume) when an object carries no
33/// `density` metadata: unit density, so `weight == volume`.
34pub const DEFAULT_DENSITY: f64 = 1.0;
35
36/// The name-keyed metadata store: `object name → { attribute → value }`, string
37/// values, deterministic iteration (a `BTreeMap` so the persisted JSON is
38/// stable). Empty records are never retained (removing the last attribute drops
39/// the whole record).
40#[derive(Debug, Clone, Default)]
41pub struct MetadataStore {
42 entries: BTreeMap<String, BTreeMap<String, String>>,
43}
44
45impl MetadataStore {
46 pub fn new() -> Self {
47 Self::default()
48 }
49
50 /// Whether the store holds no records at all.
51 pub fn is_empty(&self) -> bool {
52 self.entries.is_empty()
53 }
54
55 /// Set (or overwrite) one attribute of `name`'s record. An empty object name
56 /// or key is ignored (no phantom records).
57 pub fn set_attribute(&mut self, name: &str, key: &str, value: &str) {
58 if name.is_empty() || key.is_empty() {
59 return;
60 }
61 self.entries
62 .entry(name.to_string())
63 .or_default()
64 .insert(key.to_string(), value.to_string());
65 }
66
67 /// Remove one attribute of `name`'s record, dropping the record if it becomes
68 /// empty. Returns whether the attribute existed.
69 pub fn remove_attribute(&mut self, name: &str, key: &str) -> bool {
70 let Some(record) = self.entries.get_mut(name) else {
71 return false;
72 };
73 let existed = record.remove(key).is_some();
74 if record.is_empty() {
75 self.entries.remove(name);
76 }
77 existed
78 }
79
80 /// One attribute's value (`None` if the object or key is unknown).
81 pub fn attribute(&self, name: &str, key: &str) -> Option<&str> {
82 self.entries.get(name)?.get(key).map(String::as_str)
83 }
84
85 /// One object's whole record (empty map if the object has no metadata).
86 pub fn record(&self, name: &str) -> BTreeMap<String, String> {
87 self.entries.get(name).cloned().unwrap_or_default()
88 }
89
90 /// The whole store (all records), read-only.
91 pub fn all(&self) -> &BTreeMap<String, BTreeMap<String, String>> {
92 &self.entries
93 }
94
95 /// The resolved density (mass per mm³) for `name`: its `density` attribute
96 /// parsed as a positive finite number, else [`DEFAULT_DENSITY`].
97 pub fn density(&self, name: &str) -> f64 {
98 self.attribute(name, "density")
99 .and_then(|value| value.trim().parse::<f64>().ok())
100 .filter(|density| density.is_finite() && *density > 0.0)
101 .unwrap_or(DEFAULT_DENSITY)
102 }
103
104 /// Drop every record (a part load replaces the store wholesale).
105 pub fn clear(&mut self) {
106 self.entries.clear();
107 }
108
109 /// One object's record as a JSON object `{ key: value, ... }` (`{}` when the
110 /// object has no metadata).
111 pub fn record_json(&self, name: &str) -> String {
112 Value::Object(
113 self.record(name)
114 .into_iter()
115 .map(|(key, value)| (key, Value::String(value)))
116 .collect(),
117 )
118 .to_string()
119 }
120
121 /// The whole store as a JSON value `{ name: { key: value, ... }, ... }` — the
122 /// persisted shape and the whole-store getter.
123 pub fn to_json(&self) -> Value {
124 Value::Object(
125 self.entries
126 .iter()
127 .map(|(name, record)| {
128 let object = record
129 .iter()
130 .map(|(key, value)| (key.clone(), Value::String(value.clone())))
131 .collect();
132 (name.clone(), Value::Object(object))
133 })
134 .collect(),
135 )
136 }
137
138 /// The whole store as a JSON string (the whole-store getter's string form).
139 pub fn to_json_string(&self) -> String {
140 self.to_json().to_string()
141 }
142
143 /// Replace the whole store from a persisted `metadata` value (or `None`, which
144 /// clears it — loading a part with no metadata). Non-string leaf values are
145 /// coerced to their JSON text so a legacy document never fails the load.
146 pub fn load_json(&mut self, value: Option<&Value>) {
147 self.entries.clear();
148 let Some(Value::Object(objects)) = value else {
149 return;
150 };
151 for (name, record) in objects {
152 let Value::Object(attributes) = record else {
153 continue;
154 };
155 let map: BTreeMap<String, String> = attributes
156 .iter()
157 .map(|(key, value)| (key.clone(), value_to_string(value)))
158 .collect();
159 if !map.is_empty() {
160 self.entries.insert(name.clone(), map);
161 }
162 }
163 }
164}
165
166/// Coerce a persisted metadata leaf to a string value (strings verbatim, `null`
167/// to empty, everything else to its JSON text).
168fn value_to_string(value: &Value) -> String {
169 match value {
170 Value::String(text) => text.clone(),
171 Value::Null => String::new(),
172 other => other.to_string(),
173 }
174}
175
176/// The kind an object NAME resolves to in the current scene.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178enum ObjectKind {
179 Solid,
180 Face,
181 Edge,
182}
183
184// --- EngineState: metadata store API (a SEPARATE impl block, appended, so
185// concurrent edits to the primary block don't conflict) -------------------
186impl EngineState {
187 /// One object's metadata record as JSON `{ key: value, ... }` (`{}` if none).
188 pub fn object_metadata_json(&self, name: &str) -> String {
189 self.metadata.record_json(name)
190 }
191
192 /// Set (or overwrite) one metadata attribute of an object by NAME. String
193 /// value; the well-known `density` key drives the object's weight and the
194 /// well-known `color` key drives its shaded colour.
195 pub fn set_metadata_attribute(&mut self, name: &str, key: &str, value: &str) {
196 self.metadata.set_attribute(name, key, value);
197 // A metadata edit (notably `density`) feeds the object-info output but does
198 // NOT trigger a history rerun, so drop this object's cached info so a
199 // re-selection re-measures with the new attribute.
200 self.info_cache.remove(name);
201 // `color` is the one attribute the VIEWPORT reads, and there is no rerun
202 // to carry it through — push it to the display right here so recolouring
203 // a body is immediate.
204 if key == COLOR_METADATA_KEY {
205 self.sync_colors_from_metadata();
206 }
207 }
208
209 /// Remove one metadata attribute of an object. Returns whether it existed.
210 pub fn remove_metadata_attribute(&mut self, name: &str, key: &str) -> bool {
211 let existed = self.metadata.remove_attribute(name, key);
212 // Same rerun-less invalidation as `set_metadata_attribute`.
213 self.info_cache.remove(name);
214 if existed && key == COLOR_METADATA_KEY {
215 self.sync_colors_from_metadata();
216 }
217 existed
218 }
219
220 /// Re-derive the display scene's colours from the metadata store — the ONE
221 /// call that connects the durable `color` attribute to the renderer.
222 ///
223 /// Every colour the viewport shows comes from here: a STEP import's stamped
224 /// body/face colours, a colour typed or picked in the Info window, a colour
225 /// restored from a saved document. The store is the authority; the display's
226 /// `color_override` fields are a derived cache of it, rebuilt after every
227 /// history apply ([`EngineState::finish_apply`]), on every document load, on
228 /// a metadata edit, and whenever the display setting flips.
229 ///
230 /// [`crate::style::RenderSettings::override_model_colors`] is honoured HERE
231 /// rather than in the renderer, and it is deliberately a READ of the store,
232 /// never a write: ticking the box resolves every colour to `None` so the
233 /// viewport falls back to `faceColorMode`, while the stored attributes stay
234 /// exactly as they were. Unticking restores them from the same records.
235 ///
236 /// Returns whether anything changed, and marks the engine dirty only then —
237 /// the no-op case must stay free, since this runs after every single run.
238 pub fn sync_colors_from_metadata(&mut self) -> bool {
239 // Disjoint field borrows: the closure reads `self.metadata` while
240 // `self.scene` is borrowed mutably.
241 let ignore = self.settings.override_model_colors;
242 let metadata = &self.metadata;
243 let changed = self.scene.apply_metadata_colors(|name| {
244 if ignore {
245 return None;
246 }
247 metadata
248 .attribute(name, COLOR_METADATA_KEY)
249 .and_then(crate::style::parse_css_hex)
250 // A derived BOARD body has a colour of its own and no producing
251 // feature to have coloured it, so without this fallback the
252 // pass would resolve it to `None` and the board would draw in
253 // the name-hashed default — green substrate and copper traces
254 // are the whole point of drawing it. A stored attribute still
255 // wins, so a user may recolour the board like anything else.
256 .or_else(|| crate::engine_state::board_default_color(name))
257 });
258 if changed {
259 self.dirty = true;
260 }
261 changed
262 }
263
264 /// The whole metadata store as JSON `{ name: { key: value } }`.
265 pub fn metadata_json(&self) -> String {
266 self.metadata.to_json_string()
267 }
268}
269
270// --- EngineState: measurements + provenance (SEPARATE impl block) ------------
271impl EngineState {
272 /// Resolve an object NAME to `(kind, owning solid name)` via the display
273 /// scene: a solid resolves to itself; a face/edge resolves to its owning
274 /// solid. `None` for an empty or unknown name (vertices carry no kernel name).
275 fn resolve_object(&self, name: &str) -> Option<(ObjectKind, String)> {
276 if name.is_empty() {
277 return None;
278 }
279 if self.scene.solid(name).is_some() {
280 return Some((ObjectKind::Solid, name.to_string()));
281 }
282 for solid in self.scene.solids() {
283 if solid.faces.iter().any(|face| face.name == name) {
284 return Some((ObjectKind::Face, solid.name.clone()));
285 }
286 }
287 for solid in self.scene.solids() {
288 if solid.edges.iter().any(|edge| edge.name == name) {
289 return Some((ObjectKind::Edge, solid.name.clone()));
290 }
291 }
292 None
293 }
294
295 /// The feature that an object ORIGINATES from, as `(feature id, feature type)`.
296 /// For a FACE/EDGE this is the feature that first gave it its name (its true
297 /// origin, from the eager `entity_origin` first-writer map) — NOT the owning
298 /// solid's last producer — so "Edit owning feature" rolls back to where the
299 /// entity was born. For a SOLID it's the solid's producer (last writer, the
300 /// eager `provenance` map). `None` if the name is unknown or has no known
301 /// producer. Reads only the eager maps the last run shipped, so it never re-runs
302 /// the history — the freeze side-door `context_bar` hit every selected frame is
303 /// now O(1).
304 pub fn creating_feature(&self, name: &str) -> Option<(String, String)> {
305 let Some((kind, owner)) = self.resolve_object(name) else {
306 // A datum / construction PLANE (or one plane of a datum) is not a
307 // resident solid/face/edge — it's a named frame. Its producer is the
308 // D/P feature that emitted the frame (same fallback object_info_json
309 // uses), so "Edit owning feature" resolves for a lone plane pick too.
310 return self.datum_feature_for_name(name);
311 };
312 let id = match kind {
313 // A face/edge resolves to its ORIGIN. Fall back to the owning solid's
314 // producer when the name is somehow absent from `entity_origin` (keeps
315 // the "Edit owning feature" button from vanishing).
316 ObjectKind::Face | ObjectKind::Edge => self
317 .entity_origin
318 .get(name)
319 .cloned()
320 .or_else(|| self.provenance.get(&owner).cloned())?,
321 // A solid keeps its existing last-writer producer semantics.
322 ObjectKind::Solid => self.provenance.get(&owner)?.clone(),
323 };
324 Some((id.clone(), self.feature_type_of(&id)))
325 }
326
327 /// Whether the object `name` (a solid, or a face/edge owned by a solid) sits
328 /// on a SHEET-METAL body — its owning display solid carries the sheet-metal
329 /// marker the pipeline stamped from the resident handle's `SheetTree`. Reads
330 /// only the display scene, so it is O(1) and thread-safe (no `SheetTree`
331 /// thread-local touched on the UI thread — [`crate::scene::SolidDisplay::
332 /// is_sheet_metal`]). The gate for the sheet-metal edit features (SM Flange /
333 /// Fillet / Chamfer). `false` for an unknown name or a synthesized sketch
334 /// sheet (no resident handle, no tree).
335 pub fn is_sheet_metal_object(&self, name: &str) -> bool {
336 self.resolve_object(name)
337 .and_then(|(_, owner)| self.scene.solid(&owner))
338 .is_some_and(|solid| solid.is_sheet_metal)
339 }
340
341 /// A feature's type token by id (empty string if the id is not in the history).
342 fn feature_type_of(&self, id: &str) -> String {
343 self.history
344 .index_of(id)
345 .and_then(|index| self.history.feature_type(index))
346 .unwrap_or_default()
347 }
348
349 /// The `{ id, type }` provenance JSON for an object by NAME (or `null` if it has
350 /// no known producer). Delegates to [`creating_feature`](Self::creating_feature)
351 /// so a face/edge reports its ORIGIN (first-writer) and a solid its producer
352 /// (last-writer) — one resolver, so the Info tab and the context bar agree.
353 fn creating_feature_value(&self, name: &str) -> Value {
354 match self.creating_feature(name) {
355 Some((id, ty)) => serde_json::json!({ "id": id, "type": ty }),
356 None => Value::Null,
357 }
358 }
359
360 /// The full Properties-panel info for an object by NAME: its resolved kind,
361 /// the right measurements, and provenance. Units are millimetres.
362 ///
363 /// - **Solid** — `{ ok, name, kind:"solid", volume, surfaceArea,
364 /// edgeLengthTotal, density, weight, creatingFeature }`, where
365 /// `weight = density · volume` and `density` comes from the object's
366 /// metadata (default [`DEFAULT_DENSITY`]).
367 /// - **Face** — `{ ok, name, kind:"face", solid, surfaceType, area,
368 /// edgeLengthTotal, creatingFeature }` (`edgeLengthTotal` = its boundary
369 /// edges; `surfaceType` = the carrier-surface classification, e.g.
370 /// `"Plane"`/`"Cylinder"`/`"Cone"`/`"Sphere"`/`"Torus"`/`"NURBS"`).
371 /// - **Edge** — `{ ok, name, kind:"edge", solid, length, creatingFeature }`.
372 ///
373 /// `{ ok:false, name, message }` for an empty/unknown name, a non-resident
374 /// solid, or a kernel measurement failure.
375 ///
376 /// The real solid/face/edge MEASUREMENT is routed to the [`HistoryRunner`] (so
377 /// the warm-registry runner answers it, never the potentially-cold main side)
378 /// and CACHED here keyed by name — fired once per selection, served from the
379 /// cache every subsequent frame. For the synchronous
380 /// [`InlineRunner`](crate::runner::InlineRunner) the submit → `pump_queries`
381 /// resolves same-call, so this returns the merged JSON immediately and stays
382 /// byte-identical to the pre-seam in-process result; a background
383 /// [`ThreadRunner`](crate::runner::ThreadRunner) returns a `pending` placeholder
384 /// for the frame(s) until its reply lands (drained by `pump_queries`). The cache
385 /// is invalidated on any geometry change (`apply_run_output`) or metadata edit
386 /// (`set_metadata_attribute`).
387 ///
388 /// [`HistoryRunner`]: crate::runner::HistoryRunner
389 pub fn object_info_json(&mut self, name: &str) -> String {
390 let Some((kind, owner)) = self.resolve_object(name) else {
391 // A construction datum/plane carries no resident geometry (no volume /
392 // area / length), so it never resolves as a solid/face/edge. Return a
393 // graceful minimal record — name + kind + creating feature — rather than
394 // erroring, so the Properties Info tab renders for a selected datum and
395 // its name flows into the (name-keyed) Metadata tab.
396 if let Some((feature_id, feature_type)) = self.datum_feature_for_name(name) {
397 let kind_label = if feature_type == "P" { "plane" } else { "datum" };
398 return serde_json::json!({
399 "ok": true,
400 "name": name,
401 "kind": kind_label,
402 "creatingFeature": { "id": feature_id, "type": feature_type },
403 })
404 .to_string();
405 }
406 return serde_json::json!({
407 "ok": false, "name": name, "message": "unknown object",
408 })
409 .to_string();
410 };
411 // A committed-sketch SHEET is a scene solid with NO kernel handle, so the
412 // handle-based measurement path can't serve it. Measure straight off its
413 // synthesized display (planar-mesh triangle areas / edge polylines) and
414 // report `kind:"sketch"` — no volume. Handle-less ⇒ synchronous, no query.
415 if let Some(solid) = self.scene.solid(&owner) {
416 if solid.is_sketch {
417 return self.sketch_info_json(name, kind, solid);
418 }
419 }
420
421 // Real geometry: serve from the info cache, else fire a measurement query at
422 // the runner (deduped: never submit a second query for a name already in
423 // flight), pump, and return the resolved JSON — or a pending placeholder.
424 if let Some(cached) = self.info_cache.get(name) {
425 return cached.clone();
426 }
427 if !self.pending_query.values().any(|pending| pending == name) {
428 self.next_query_id += 1;
429 let id = self.next_query_id;
430 let measure_kind = match kind {
431 ObjectKind::Solid => MeasureKind::Solid,
432 ObjectKind::Face => MeasureKind::Face,
433 ObjectKind::Edge => MeasureKind::Edge,
434 };
435 let density = self.metadata.density(name);
436 self.pending_query.insert(id, name.to_string());
437 self.runner.submit_query(MeasureQuery {
438 id,
439 kind: measure_kind,
440 owner,
441 entity: name.to_string(),
442 density,
443 });
444 }
445 self.pump_queries();
446 match self.info_cache.get(name) {
447 Some(resolved) => resolved.clone(),
448 None => serde_json::json!({ "ok": false, "name": name, "pending": true }).to_string(),
449 }
450 }
451
452 /// Drain every completed measurement reply from the runner and fold it into the
453 /// name-keyed info cache — the query counterpart of [`EngineState::pump`]. Called
454 /// once per frame from `pump` AND synchronously from
455 /// [`Self::object_info_json`] (so the Inline runner resolves same-call). Each
456 /// reply is MERGED with the main-injected `name` + `creatingFeature` (from the
457 /// eager provenance) into the final object-info JSON.
458 pub fn pump_queries(&mut self) {
459 while let Some(reply) = self.runner.poll_query() {
460 let Some(name) = self.pending_query.remove(&reply.id) else {
461 // A reply whose request was invalidated (a rerun cleared the pending
462 // set) — drop it; the re-selection re-queries against fresh geometry.
463 continue;
464 };
465 let fragment: Value = serde_json::from_str(&reply.result).unwrap_or(Value::Null);
466 let merged = self.merge_info(&name, &fragment);
467 self.info_cache.insert(name, merged);
468 }
469 }
470
471 /// Merge a runner measurement FRAGMENT with the main-side `name` +
472 /// `creatingFeature` into the final object-info JSON, preserving the exact field
473 /// ORDER the pre-seam `object_info_json` emitted (so the output is
474 /// byte-identical): `ok`, then `name`, then the fragment's remaining fields in
475 /// order (`kind`, the measurements — or `message` on error), then
476 /// `creatingFeature` (only when `ok`, since an error record carries none).
477 fn merge_info(&self, name: &str, fragment: &Value) -> String {
478 let object = fragment.as_object();
479 let ok = object
480 .and_then(|map| map.get("ok"))
481 .and_then(Value::as_bool)
482 .unwrap_or(false);
483 let mut merged = serde_json::Map::new();
484 merged.insert("ok".to_string(), Value::Bool(ok));
485 merged.insert("name".to_string(), Value::String(name.to_string()));
486 if let Some(map) = object {
487 for (key, value) in map {
488 if key == "ok" {
489 continue;
490 }
491 merged.insert(key.clone(), value.clone());
492 }
493 }
494 if ok {
495 merged.insert(
496 "creatingFeature".to_string(),
497 // Resolve by ENTITY NAME (not `owner`): a face/edge reports its
498 // ORIGIN, a solid its producer — the same correction the context bar
499 // gets, so the Info tab's `creatingFeature` agrees.
500 self.creating_feature_value(name),
501 );
502 }
503 Value::Object(merged).to_string()
504 }
505
506 /// Properties info for a committed-sketch SHEET object (the sheet solid, its
507 /// planar face, or a boundary edge), measured off the synthesized display — a
508 /// sketch carries no resident kernel geometry. `kind:"sketch"` for the whole
509 /// sheet (area + total edge length, NO volume); `"face"` for its planar face;
510 /// `"edge"` for a boundary edge. Provenance is the sketch feature itself.
511 fn sketch_info_json(
512 &self,
513 name: &str,
514 kind: ObjectKind,
515 solid: &crate::scene::SolidDisplay,
516 ) -> String {
517 let creating = serde_json::json!({
518 "id": solid.name,
519 "type": self.feature_type_of(&solid.name),
520 });
521 let edge_total: f64 = solid.edges.iter().map(|e| polyline_length(&e.polyline)).sum();
522 match kind {
523 ObjectKind::Solid => serde_json::json!({
524 "ok": true,
525 "name": name,
526 "kind": "sketch",
527 "area": sheet_mesh_area(solid),
528 "edgeLengthTotal": edge_total,
529 "creatingFeature": creating,
530 })
531 .to_string(),
532 ObjectKind::Face => serde_json::json!({
533 "ok": true,
534 "name": name,
535 "kind": "face",
536 "solid": solid.name,
537 // A committed sketch's sheet face is planar by construction.
538 "surfaceType": "Plane",
539 "area": sheet_mesh_area(solid),
540 "edgeLengthTotal": edge_total,
541 "creatingFeature": creating,
542 })
543 .to_string(),
544 ObjectKind::Edge => {
545 let length = solid
546 .edges
547 .iter()
548 .find(|e| e.name == name)
549 .map(|e| polyline_length(&e.polyline))
550 .unwrap_or(0.0);
551 serde_json::json!({
552 "ok": true,
553 "name": name,
554 "kind": "edge",
555 "solid": solid.name,
556 "length": length,
557 "creatingFeature": creating,
558 })
559 .to_string()
560 }
561 }
562 }
563}
564
565/// Total surface area (mm²) of a synthesized sheet's planar display mesh — the
566/// sum of its triangle areas.
567fn sheet_mesh_area(solid: &crate::scene::SolidDisplay) -> f64 {
568 let p = &solid.mesh.positions;
569 solid
570 .mesh
571 .indices
572 .chunks_exact(3)
573 .map(|t| {
574 let a = p[t[0] as usize];
575 let b = p[t[1] as usize];
576 let c = p[t[2] as usize];
577 let ab = [
578 (b[0] - a[0]) as f64,
579 (b[1] - a[1]) as f64,
580 (b[2] - a[2]) as f64,
581 ];
582 let ac = [
583 (c[0] - a[0]) as f64,
584 (c[1] - a[1]) as f64,
585 (c[2] - a[2]) as f64,
586 ];
587 let cross = [
588 ab[1] * ac[2] - ab[2] * ac[1],
589 ab[2] * ac[0] - ab[0] * ac[2],
590 ab[0] * ac[1] - ab[1] * ac[0],
591 ];
592 (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5
593 })
594 .sum()
595}
596
597/// Arc length (mm) of a sampled edge polyline — the sum of its segment lengths.
598fn polyline_length(polyline: &[[f32; 3]]) -> f64 {
599 polyline
600 .windows(2)
601 .map(|w| {
602 let d = [
603 (w[1][0] - w[0][0]) as f64,
604 (w[1][1] - w[0][1]) as f64,
605 (w[1][2] - w[0][2]) as f64,
606 ];
607 (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
608 })
609 .sum()
610}
611