simview 6.3.1__tar.gz → 6.4.1__tar.gz

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 (112) hide show
  1. {simview-6.3.1/simview.egg-info → simview-6.4.1}/PKG-INFO +1 -1
  2. {simview-6.3.1 → simview-6.4.1}/pyproject.toml +1 -1
  3. {simview-6.3.1 → simview-6.4.1}/simview/__main__.py +5 -5
  4. {simview-6.3.1 → simview-6.4.1}/simview/columnar.py +3 -2
  5. {simview-6.3.1 → simview-6.4.1}/simview/launcher.py +1 -0
  6. {simview-6.3.1 → simview-6.4.1}/simview/merge.py +22 -19
  7. {simview-6.3.1 → simview-6.4.1}/simview/model.py +15 -1
  8. {simview-6.3.1 → simview-6.4.1}/simview/remote.py +1 -1
  9. {simview-6.3.1 → simview-6.4.1}/simview/render.py +6 -0
  10. {simview-6.3.1 → simview-6.4.1}/simview/scene.py +24 -14
  11. {simview-6.3.1 → simview-6.4.1}/simview/server.py +58 -11
  12. {simview-6.3.1 → simview-6.4.1}/simview/static/js/SimView.js +73 -43
  13. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/AnimationController.js +7 -2
  14. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/InteractionController.js +38 -1
  15. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/WindowedField.js +12 -0
  16. {simview-6.3.1 → simview-6.4.1}/simview/static/js/config.js +2 -1
  17. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/Body.js +67 -25
  18. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/StaticObject.js +21 -4
  19. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/Terrain.js +88 -19
  20. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/utils.js +8 -0
  21. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/BodyStateWindow.js +3 -0
  22. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/Controls.js +78 -11
  23. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/Legend.js +4 -2
  24. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/ScalarPlotter.js +4 -4
  25. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/TerrainProfile.js +6 -0
  26. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/csv.js +4 -1
  27. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/liveFollow.js +10 -0
  28. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/terrainSample.js +4 -4
  29. {simview-6.3.1 → simview-6.4.1}/simview/terrain.py +7 -2
  30. {simview-6.3.1 → simview-6.4.1}/simview/utils.py +33 -0
  31. {simview-6.3.1 → simview-6.4.1/simview.egg-info}/PKG-INFO +1 -1
  32. {simview-6.3.1 → simview-6.4.1}/simview.egg-info/SOURCES.txt +1 -0
  33. {simview-6.3.1 → simview-6.4.1}/tests/test_launcher.py +19 -0
  34. {simview-6.3.1 → simview-6.4.1}/tests/test_merge.py +44 -0
  35. {simview-6.3.1 → simview-6.4.1}/tests/test_pointcloud_features.py +15 -0
  36. {simview-6.3.1 → simview-6.4.1}/tests/test_remote.py +2 -0
  37. {simview-6.3.1 → simview-6.4.1}/tests/test_server.py +20 -0
  38. {simview-6.3.1 → simview-6.4.1}/tests/test_show.py +11 -0
  39. simview-6.4.1/tests/test_strict_json.py +100 -0
  40. {simview-6.3.1 → simview-6.4.1}/tests/test_terrain_query.py +15 -0
  41. {simview-6.3.1 → simview-6.4.1}/LICENSE +0 -0
  42. {simview-6.3.1 → simview-6.4.1}/MANIFEST.in +0 -0
  43. {simview-6.3.1 → simview-6.4.1}/README.md +0 -0
  44. {simview-6.3.1 → simview-6.4.1}/setup.cfg +0 -0
  45. {simview-6.3.1 → simview-6.4.1}/simview/__init__.py +0 -0
  46. {simview-6.3.1 → simview-6.4.1}/simview/diff.py +0 -0
  47. {simview-6.3.1 → simview-6.4.1}/simview/info.py +0 -0
  48. {simview-6.3.1 → simview-6.4.1}/simview/live.py +0 -0
  49. {simview-6.3.1 → simview-6.4.1}/simview/preload.py +0 -0
  50. {simview-6.3.1 → simview-6.4.1}/simview/py.typed +0 -0
  51. {simview-6.3.1 → simview-6.4.1}/simview/state.py +0 -0
  52. {simview-6.3.1 → simview-6.4.1}/simview/static/css/controls.css +0 -0
  53. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/BatchManager.js +0 -0
  54. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/Scene.js +0 -0
  55. {simview-6.3.1 → simview-6.4.1}/simview/static/js/components/StateStore.js +0 -0
  56. {simview-6.3.1 → simview-6.4.1}/simview/static/js/main.js +0 -0
  57. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/Polyline.js +0 -0
  58. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/colormap.js +0 -0
  59. {simview-6.3.1 → simview-6.4.1}/simview/static/js/objects/similarity.js +0 -0
  60. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/AnalysisPanel.js +0 -0
  61. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/BatchLegend.js +0 -0
  62. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/ErrorMetrics.js +0 -0
  63. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/PlaybackControls.js +0 -0
  64. {simview-6.3.1 → simview-6.4.1}/simview/static/js/ui/chartControls.js +0 -0
  65. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/batchPresets.js +0 -0
  66. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/batchVisibility.js +0 -0
  67. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/blobCodec.js +0 -0
  68. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/blobWindow.js +0 -0
  69. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/bodyTransforms.js +0 -0
  70. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/cameraRange.js +0 -0
  71. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/episodes.js +0 -0
  72. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/errorMath.js +0 -0
  73. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/html.js +0 -0
  74. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/interpolate.js +0 -0
  75. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/keyboard.js +0 -0
  76. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/scalarSeries.js +0 -0
  77. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/uplot.js +0 -0
  78. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/viewState.js +0 -0
  79. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/viewerDefaults.js +0 -0
  80. {simview-6.3.1 → simview-6.4.1}/simview/static/js/utils/visibleRanges.js +0 -0
  81. {simview-6.3.1 → simview-6.4.1}/simview/static/js/vendor/js-colormaps.js +0 -0
  82. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/three-0.174.0/addons/controls/OrbitControls.js +0 -0
  83. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/three-0.174.0/addons/libs/lil-gui.module.min.js +0 -0
  84. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/three-0.174.0/three.core.js +0 -0
  85. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/three-0.174.0/three.module.js +0 -0
  86. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/uPlot-1.6.32/uPlot.esm.js +0 -0
  87. {simview-6.3.1 → simview-6.4.1}/simview/static/lib/uPlot-1.6.32/uPlot.min.css +0 -0
  88. {simview-6.3.1 → simview-6.4.1}/simview/static/textures/contacts/red-cross0.png +0 -0
  89. {simview-6.3.1 → simview-6.4.1}/simview/static/textures/points/ball1.png +0 -0
  90. {simview-6.3.1 → simview-6.4.1}/simview/templates/index.html +0 -0
  91. {simview-6.3.1 → simview-6.4.1}/simview/view.py +0 -0
  92. {simview-6.3.1 → simview-6.4.1}/simview.egg-info/dependency_links.txt +0 -0
  93. {simview-6.3.1 → simview-6.4.1}/simview.egg-info/entry_points.txt +0 -0
  94. {simview-6.3.1 → simview-6.4.1}/simview.egg-info/requires.txt +0 -0
  95. {simview-6.3.1 → simview-6.4.1}/simview.egg-info/top_level.txt +0 -0
  96. {simview-6.3.1 → simview-6.4.1}/tests/test_batch_selection.py +0 -0
  97. {simview-6.3.1 → simview-6.4.1}/tests/test_cli.py +0 -0
  98. {simview-6.3.1 → simview-6.4.1}/tests/test_columnar_ondisk.py +0 -0
  99. {simview-6.3.1 → simview-6.4.1}/tests/test_columnar_states.py +0 -0
  100. {simview-6.3.1 → simview-6.4.1}/tests/test_contacts.py +0 -0
  101. {simview-6.3.1 → simview-6.4.1}/tests/test_diff.py +0 -0
  102. {simview-6.3.1 → simview-6.4.1}/tests/test_embed_defaults.py +0 -0
  103. {simview-6.3.1 → simview-6.4.1}/tests/test_episodes.py +0 -0
  104. {simview-6.3.1 → simview-6.4.1}/tests/test_info.py +0 -0
  105. {simview-6.3.1 → simview-6.4.1}/tests/test_live.py +0 -0
  106. {simview-6.3.1 → simview-6.4.1}/tests/test_preload.py +0 -0
  107. {simview-6.3.1 → simview-6.4.1}/tests/test_roundtrip.py +0 -0
  108. {simview-6.3.1 → simview-6.4.1}/tests/test_scene.py +0 -0
  109. {simview-6.3.1 → simview-6.4.1}/tests/test_terrain.py +0 -0
  110. {simview-6.3.1 → simview-6.4.1}/tests/test_trajectory.py +0 -0
  111. {simview-6.3.1 → simview-6.4.1}/tests/test_utils.py +0 -0
  112. {simview-6.3.1 → simview-6.4.1}/tests/test_view.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simview
3
- Version: 6.3.1
3
+ Version: 6.4.1
4
4
  Summary: THREE.js-based simulation visualization tool
5
5
  Author-email: Jan Vlk <vlkjan6@fel.cvut.cz>, Ales Kucera <kuceral4@fel.cvut.cz>, David Korcak <david.korcak@gmail.com>
6
6
  License-Expression: BSD-3-Clause
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "simview"
7
- version = "6.3.1"
7
+ version = "6.4.1"
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.12"
10
10
  license = "BSD-3-Clause"
@@ -10,7 +10,7 @@ from pathlib import Path
10
10
 
11
11
  from simview import CACHE_DIR, __version__, remote
12
12
  from simview.server import SimViewServer
13
- from simview.utils import human_bytes, load_scene, load_scene_model
13
+ from simview.utils import dumps_json, human_bytes, load_scene, load_scene_model
14
14
 
15
15
  logger = logging.getLogger("simview.cli")
16
16
 
@@ -104,7 +104,7 @@ def run_info(path: Path, as_json: bool) -> None:
104
104
  sys.exit(1)
105
105
 
106
106
  if as_json:
107
- print(json.dumps(summary, indent=2))
107
+ print(dumps_json(summary, indent=2))
108
108
  else:
109
109
  print(format_text(summary))
110
110
 
@@ -196,7 +196,7 @@ def run_terrain(path: Path, args: argparse.Namespace) -> None:
196
196
  if args.csv:
197
197
  print(csv_fn(result), end="")
198
198
  elif args.json:
199
- print(json.dumps(result, indent=2))
199
+ print(dumps_json(result, indent=2))
200
200
  else:
201
201
  print(text_fn(result))
202
202
 
@@ -246,7 +246,7 @@ def run_diff(path: Path, args: argparse.Namespace) -> None:
246
246
  if args.csv:
247
247
  print(diff_mod.format_diff_csv(result), end="")
248
248
  elif args.json:
249
- print(json.dumps(result, indent=2))
249
+ print(dumps_json(result, indent=2))
250
250
  else:
251
251
  print(diff_mod.format_diff_text(result))
252
252
 
@@ -315,7 +315,7 @@ def save_merged(
315
315
  columnar_states = columnarize_states(merged["states"], merged["model"], inline_blob)
316
316
  if columnar_states is not None:
317
317
  merged["states"] = columnar_states
318
- payload = json.dumps(merged).encode("utf-8")
318
+ payload = dumps_json(merged).encode("utf-8")
319
319
  if out_path.suffix == ".gz":
320
320
  payload = gzip.compress(payload, compresslevel=1)
321
321
  try:
@@ -466,9 +466,10 @@ def write_static_bundle(data: dict, directory) -> None:
466
466
  ``model.json``, ``states.json`` and raw ``blob/<id>`` files, with blob
467
467
  references rewritten to ``/blob/<id>`` (the viewer maps these to
468
468
  ``<base>/blob/<id>``). Stdlib-only."""
469
- import json
470
469
  from pathlib import Path
471
470
 
471
+ from simview.utils import dumps_json
472
+
472
473
  out = Path(directory)
473
474
  (out / "blob").mkdir(parents=True, exist_ok=True)
474
475
  count = 0
@@ -486,4 +487,4 @@ def write_static_bundle(data: dict, directory) -> None:
486
487
  if is_columnar(data["states"]):
487
488
  rewrite_blobs(data["states"], write_blob)
488
489
  for name in ("model", "states"):
489
- (out / f"{name}.json").write_text(json.dumps(data[name]))
490
+ (out / f"{name}.json").write_text(dumps_json(data[name]))
@@ -59,6 +59,7 @@ class SimViewLauncher:
59
59
  # Serialize the scene once and hand it to the server directly,
60
60
  # avoiding a temp-file write + read-back round-trip.
61
61
  logger.info("SimViewLauncher: Serving in-memory SimulationScene")
62
+ self._scene._prepare_for_output()
62
63
  data = {
63
64
  "model": self._scene.model.to_json(),
64
65
  "states": self._scene.states,
@@ -23,8 +23,6 @@ import re
23
23
  from pathlib import Path
24
24
  from typing import Sequence
25
25
 
26
- import orjson
27
-
28
26
  from .columnar import (
29
27
  STATE_FIELD_WIDTHS,
30
28
  batch_rows,
@@ -34,7 +32,7 @@ from .columnar import (
34
32
  is_blob,
35
33
  is_columnar,
36
34
  )
37
- from .utils import bodies_by_name, read_maybe_gzipped_bytes
35
+ from .utils import bodies_by_name, loads_json, read_maybe_gzipped_bytes
38
36
 
39
37
  logger = logging.getLogger("simview.merge")
40
38
 
@@ -230,7 +228,7 @@ def _decode_per_batch(
230
228
 
231
229
  def _load_json(path: Path) -> dict:
232
230
  raw = read_maybe_gzipped_bytes(path)
233
- doc = orjson.loads(raw)
231
+ doc = loads_json(raw)
234
232
  # Merging works frame by frame (resampling onto the first file's timeline),
235
233
  # so a columnar file is expanded to the per-frame layout up front rather
236
234
  # than teaching every step below a second shape. expand_columnar_states is
@@ -758,12 +756,11 @@ def _merge_states(
758
756
  )
759
757
  )
760
758
  if contacts is not None:
761
- if "contacts" not in body_state:
762
- raise ValueError(
763
- f"'{labels[file_idx]}' body '{name}' declares 'contacts' as "
764
- f"available but is missing it at t={states[state_idx]['time']}."
765
- )
766
- contacts.extend(_select(body_state["contacts"], selection))
759
+ # A frame may omit contacts (save/view treat that as none).
760
+ body_contacts = body_state.get("contacts")
761
+ if body_contacts is None:
762
+ body_contacts = [[] for _ in range(batch_size)]
763
+ contacts.extend(_select(body_contacts, selection))
767
764
 
768
765
  transform = field_values["bodyTransform"]
769
766
  if len(transform) != total_batches:
@@ -858,13 +855,13 @@ def merge_simulation_files(
858
855
  # file's batch count), so they only pass through unchanged when nothing
859
856
  # about the batch layout changes.
860
857
  polylines = models[0].get("polylines") or []
861
- if polylines and (
862
- len(models) > 1 or any(sel is not None for sel in batch_selections)
863
- ):
864
- raise ValueError(
865
- f"'{labels[0]}' has polylines, which cannot be merged across files "
866
- "or batch selections; drop them before merging."
867
- )
858
+ if len(models) > 1 or any(sel is not None for sel in batch_selections):
859
+ for model, label in zip(models, labels):
860
+ if model.get("polylines"):
861
+ raise ValueError(
862
+ f"'{label}' has polylines, which cannot be merged across "
863
+ "files or batch selections; drop them before merging."
864
+ )
868
865
  merged_states = _merge_states(
869
866
  states_list, batch_sizes, bodies, scalar_names, labels, batch_selections
870
867
  )
@@ -916,9 +913,15 @@ def merge_simulation_files(
916
913
  # Keep every input's run provenance (engine, checkpoint, git commit, ...)
917
914
  # instead of silently dropping it -- namespaced per source file since the
918
915
  # inputs may come from entirely different runs.
916
+ # Basenames can collide ('a/run.json', 'b/run.json'), so a duplicate is
917
+ # keyed by its path as given, then also by input position.
918
+ source_keys: list[str] = []
919
+ for i, (path, label) in enumerate(zip(resolved_paths, labels)):
920
+ key = label if labels.count(label) == 1 else str(path)
921
+ source_keys.append(key if key not in source_keys else f"{key} [{i}]")
919
922
  source_metadata = {
920
- label: model["metadata"]
921
- for model, label in zip(models, labels)
923
+ key: model["metadata"]
924
+ for model, key in zip(models, source_keys)
922
925
  if model.get("metadata") is not None
923
926
  }
924
927
  if source_metadata:
@@ -488,6 +488,7 @@ class SimViewBody:
488
488
  points: torch.Tensor,
489
489
  color: torch.Tensor | None = None,
490
490
  embedding: torch.Tensor | None = None,
491
+ color_layers: dict[str, torch.Tensor] | None = None,
491
492
  **kwargs,
492
493
  ) -> "SimViewBody":
493
494
  """Build a point-cloud body from `(N, 3)` `points`.
@@ -497,7 +498,10 @@ class SimViewBody:
497
498
  an optional per-point K-wide feature vector (e.g. a reduced-dim PCA
498
499
  projection of a learned backbone's features) enabling the viewer's
499
500
  click-to-similarity color mode: cosine similarity to a clicked point,
500
- computed entirely in-browser from this data. Both are stored as
501
+ computed entirely in-browser from this data. `color_layers` maps a
502
+ name to another (N, 3) RGB coloring (e.g. a class or session label);
503
+ each becomes an extra choice of the viewer's "Point Color Mode", shown
504
+ by every body that ships a layer of that name. All are stored as
501
505
  ``__b64__`` blobs."""
502
506
  if points.ndim != 2 or points.shape[1] != 3:
503
507
  raise ValueError(
@@ -517,6 +521,16 @@ class SimViewBody:
517
521
  f"embedding must have shape ({N}, K) matching points; got {tuple(embedding.shape)}."
518
522
  )
519
523
  shape_extra["embedding"] = embedding
524
+ if color_layers:
525
+ shape_extra["colorLayers"] = {}
526
+ for layer, rgb in color_layers.items():
527
+ if layer in ("pca", "similarity"):
528
+ raise ValueError(f"color layer name {layer!r} is reserved.")
529
+ if tuple(rgb.shape) != (N, 3):
530
+ raise ValueError(
531
+ f"color layer {layer!r} must have shape ({N}, 3); got {tuple(rgb.shape)}."
532
+ )
533
+ shape_extra["colorLayers"][layer] = _encode_blob(rgb.cpu().numpy())
520
534
  # Per-point `color` lives in the shape, so it can't go through
521
535
  # `create`'s kwargs (where `color` is the body-level tint).
522
536
  body = SimViewBody.create(
@@ -148,7 +148,7 @@ def quote_remote_path(path: str) -> str:
148
148
  user name) and only the remainder is quoted.
149
149
  """
150
150
  head, sep, tail = path.partition("/")
151
- if sep and _TILDE_RE.match(head):
151
+ if _TILDE_RE.match(head):
152
152
  return head + sep + (shlex.quote(tail) if tail else "")
153
153
  return shlex.quote(path)
154
154
 
@@ -92,6 +92,12 @@ def render_screenshot(
92
92
  "#loading-splash", state="detached", timeout=_LOAD_TIMEOUT_MS
93
93
  )
94
94
  page.wait_for_timeout(_SETTLE_DELAY_MS)
95
+ # A view in a terrain property color mode fetches that layer on
96
+ # demand (Terrain.loadProperty); let it land and repaint.
97
+ if page.evaluate(
98
+ "async () => (await window.__debugSimView?.terrain?.propertyLoadsSettled())?.length"
99
+ ):
100
+ page.wait_for_timeout(_SETTLE_DELAY_MS)
95
101
  output_path.parent.mkdir(parents=True, exist_ok=True)
96
102
  page.screenshot(path=str(output_path))
97
103
  finally:
@@ -36,7 +36,7 @@ from .state import (
36
36
  LocalTransformLike,
37
37
  SimViewBodyState,
38
38
  )
39
- from .utils import iter_names, read_maybe_gzipped_bytes
39
+ from .utils import dumps_json, iter_names, read_maybe_gzipped_bytes
40
40
 
41
41
  logger = logging.getLogger("simview.scene")
42
42
 
@@ -455,6 +455,13 @@ class SimulationScene:
455
455
  state[name] = arr[t].tolist()
456
456
  self.states.append(state)
457
457
 
458
+ def _prepare_for_output(self) -> None:
459
+ """Validate and reconcile the model against the states before it is
460
+ serialized: shared by `save()`, `show()` and `SimViewLauncher`."""
461
+ self._check_episodes_in_range()
462
+ self._check_polyline_frames()
463
+ self.reconcile_available_attributes()
464
+
458
465
  def _check_episodes_in_range(self) -> None:
459
466
  """Every episode must start at a frame this scene actually has."""
460
467
  for episode in self.model.episodes or []:
@@ -545,9 +552,7 @@ class SimulationScene:
545
552
  raise ValueError(
546
553
  "Cannot save data: The simulation model is not complete (e.g., terrain might be missing)."
547
554
  )
548
- self._check_episodes_in_range()
549
- self._check_polyline_frames()
550
- self.reconcile_available_attributes()
555
+ self._prepare_for_output()
551
556
 
552
557
  output_path = Path(filepath)
553
558
  if compress and output_path.suffix != ".gz":
@@ -571,11 +576,11 @@ class SimulationScene:
571
576
  with (gzip.open if compress else open)(output_path, "wt") as f:
572
577
  f.write("{\n")
573
578
  f.write(' "model": ')
574
- json.dump(model_json, f, indent=2)
579
+ f.write(dumps_json(model_json, indent=2))
575
580
  f.write(",\n")
576
581
  if columnar_states is not None:
577
582
  f.write(' "states": ')
578
- json.dump(columnar_states, f)
583
+ f.write(dumps_json(columnar_states))
579
584
  f.write("\n}")
580
585
  else:
581
586
  # Streamed frame by frame: the per-frame layout is only
@@ -586,7 +591,7 @@ class SimulationScene:
586
591
  if i > 0:
587
592
  f.write(",\n")
588
593
  f.write(" ")
589
- json.dump(state, f)
594
+ f.write(dumps_json(state))
590
595
  f.write("\n ]\n}")
591
596
  logger.info("Simulation data successfully saved to %s", output_path)
592
597
 
@@ -637,9 +642,7 @@ class SimulationScene:
637
642
  "Cannot show scene: the simulation model is not complete "
638
643
  "(e.g. terrain might be missing)."
639
644
  )
640
- self._check_episodes_in_range()
641
- self._check_polyline_frames()
642
- self.reconcile_available_attributes()
645
+ self._prepare_for_output()
643
646
 
644
647
  data = {"model": self.model.to_json(), "states": self.states}
645
648
  handle = ViewerHandle(
@@ -678,8 +681,7 @@ class SimulationScene:
678
681
  computed from the heightmap gradients, unless `compute_normals=False`,
679
682
  which stores no normals at all (three floats per cell less on disk and
680
683
  over the wire). The viewer then shades the surface from normals it
681
- computes itself, and the "normals" arrow visualization has nothing to
682
- draw.
684
+ computes itself, and draws the "normals" arrows from those too.
683
685
 
684
686
  `x_lim`/`y_lim` are the `(min, max)` coordinates of the X/Y axes.
685
687
  `grid_res` is the spacing between adjacent grid nodes; if `x_lim` and
@@ -794,6 +796,7 @@ class SimulationScene:
794
796
  points: torch.Tensor,
795
797
  color: torch.Tensor | None = None,
796
798
  embedding: torch.Tensor | None = None,
799
+ color_layers: dict[str, torch.Tensor] | None = None,
797
800
  **kwargs,
798
801
  ) -> None:
799
802
  """Add a point-cloud body named `body_name` to the model.
@@ -802,11 +805,18 @@ class SimulationScene:
802
805
  `(N, 3)` per-point RGB in [0, 1] for static vertex-colored rendering.
803
806
  `embedding` is an optional `(N, K)` per-point feature vector (e.g. a
804
807
  reduced-dim PCA projection) enabling the viewer's click-to-similarity
805
- color mode. Other `**kwargs` go to `SimViewBody.create`.
808
+ color mode. `color_layers` maps names to extra `(N, 3)` RGB colorings
809
+ selectable as "Point Color Mode" choices. Other `**kwargs` go to
810
+ `SimViewBody.create`.
806
811
  """
807
812
  self.model.add_body(
808
813
  SimViewBody.create_pointcloud(
809
- body_name, points, color=color, embedding=embedding, **kwargs
814
+ body_name,
815
+ points,
816
+ color=color,
817
+ embedding=embedding,
818
+ color_layers=color_layers,
819
+ **kwargs,
810
820
  )
811
821
  )
812
822
 
@@ -4,6 +4,7 @@ import asyncio
4
4
  import copy
5
5
  import gzip
6
6
  import hashlib
7
+ import html
7
8
  import json
8
9
  import logging
9
10
  import os
@@ -30,7 +31,13 @@ from starlette.types import Scope
30
31
 
31
32
  from simview.columnar import columnarize_states, is_columnar, rewrite_blobs
32
33
  from simview.preload import render_index
33
- from simview.utils import dialable_host, find_free_port, read_maybe_gzipped_bytes
34
+ from simview.utils import (
35
+ dialable_host,
36
+ dumps_json,
37
+ find_free_port,
38
+ loads_json,
39
+ read_maybe_gzipped_bytes,
40
+ )
34
41
 
35
42
  logger = logging.getLogger("simview.server")
36
43
 
@@ -187,10 +194,41 @@ def _ws_origin_allowed(websocket: WebSocket) -> bool:
187
194
  host_header = websocket.headers.get("host", "")
188
195
  if match.group(1) != host_header:
189
196
  return False
197
+ return _host_allowed(host_header)
198
+
199
+
200
+ def _host_allowed(host_header: str) -> bool:
201
+ """Whether a Host header names 'localhost' or an address -- anything else
202
+ may be an attacker's DNS-rebound name (see _ws_origin_allowed)."""
190
203
  host = _host_of(host_header)
191
204
  return host == "localhost" or _IP_LITERAL_RE.match(host) is not None
192
205
 
193
206
 
207
+ class _HostCheckMiddleware:
208
+ """Rejects HTTP requests whose Host isn't 'localhost' or an address.
209
+
210
+ The DNS-rebinding guard for the HTTP routes, the same Host rule
211
+ _ws_origin_allowed applies: after a rebind an attacker's page is
212
+ same-origin with the server, so CORS no longer stops it reading /model
213
+ (which carries the blob token) or POSTing /batch-names. A request with no
214
+ Host header (HTTP/1.0 tooling) is let through; browsers always send one.
215
+ """
216
+
217
+ def __init__(self, app):
218
+ self.app = app
219
+
220
+ async def __call__(self, scope: Scope, receive, send):
221
+ if scope["type"] == "http":
222
+ host_header = Headers(scope=scope).get("host")
223
+ if host_header is not None and not _host_allowed(host_header):
224
+ response = JSONResponse(
225
+ {"message": "Invalid Host header"}, status_code=400
226
+ )
227
+ await response(scope, receive, send)
228
+ return
229
+ await self.app(scope, receive, send)
230
+
231
+
194
232
  class _BodySizeLimitMiddleware:
195
233
  """Rejects requests whose declared body exceeds _MAX_REQUEST_BODY_BYTES.
196
234
 
@@ -317,6 +355,10 @@ class SimViewServer:
317
355
  self.sim_path = self.sim_paths[0] if self.sim_paths else None
318
356
  self._preloaded_data = data
319
357
  self.model_data = None
358
+ # Serializes model_data mutate+repack: the producer thread
359
+ # (set_episodes) and the event loop (/batch-names) both repack, and
360
+ # gzip releases the GIL, so an older snapshot could land last.
361
+ self._model_lock = threading.Lock()
320
362
 
321
363
  @asynccontextmanager
322
364
  async def lifespan(app: FastAPI):
@@ -343,6 +385,8 @@ class SimViewServer:
343
385
  # CORS above, so it wraps it and rejects oversized payloads before any
344
386
  # middleware or handler runs.
345
387
  self.app.add_middleware(_BodySizeLimitMiddleware)
388
+ # Outermost: refuse DNS-rebound requests before anything else runs.
389
+ self.app.add_middleware(_HostCheckMiddleware)
346
390
 
347
391
  # Mount static files. StaticFiles adds ETag/Last-Modified headers so
348
392
  # unchanged assets (vendored libs, textures, our own JS) are served
@@ -412,7 +456,7 @@ class SimViewServer:
412
456
  assert self.sim_path is not None
413
457
  logger.info("Loading simulation data from %s...", self.sim_path)
414
458
  raw = read_maybe_gzipped_bytes(self.sim_path)
415
- data = orjson.loads(raw)
459
+ data = loads_json(raw)
416
460
 
417
461
  model_data = data.get("model")
418
462
  states_data = data.get("states")
@@ -621,8 +665,9 @@ class SimViewServer:
621
665
  status_code=400,
622
666
  )
623
667
 
624
- self.model_data["batchNames"] = names
625
- self._pack_model()
668
+ with self._model_lock:
669
+ self.model_data["batchNames"] = names
670
+ self._pack_model()
626
671
 
627
672
  names_path = self._names_sidecar_path()
628
673
  persisted = False
@@ -703,7 +748,7 @@ class SimViewServer:
703
748
  for start in range(0, len(pending), _CATCHUP_CHUNK_SIZE):
704
749
  chunk = pending[start : start + _CATCHUP_CHUNK_SIZE]
705
750
  await websocket.send_text(
706
- json.dumps(
751
+ dumps_json(
707
752
  {
708
753
  "states": [frame for _, frame in chunk],
709
754
  "frameOffset": pending[start][0],
@@ -726,8 +771,9 @@ class SimViewServer:
726
771
  """
727
772
  if self.model_data is None:
728
773
  return
729
- self.model_data["episodes"] = episodes
730
- self._pack_model()
774
+ with self._model_lock:
775
+ self.model_data["episodes"] = episodes
776
+ self._pack_model()
731
777
 
732
778
  async def broadcast_episodes(self, episodes: list[dict]) -> None:
733
779
  """Push updated episode boundaries to every connected /ws/states client.
@@ -736,7 +782,7 @@ class SimViewServer:
736
782
  the model, not a frame, and arrive far more rarely. See the onmessage
737
783
  handler in SimView.js.
738
784
  """
739
- await self._broadcast_text(json.dumps({"episodes": episodes}))
785
+ await self._broadcast_text(dumps_json({"episodes": episodes}))
740
786
 
741
787
  async def _broadcast_text(self, message: str) -> None:
742
788
  """Send one already-serialized message to every connected client.
@@ -767,7 +813,7 @@ class SimViewServer:
767
813
  thread rather than calling it directly.
768
814
  """
769
815
  await self._broadcast_text(
770
- json.dumps({"states": [frame], "frameOffset": frame_index})
816
+ dumps_json({"states": [frame], "frameOffset": frame_index})
771
817
  )
772
818
 
773
819
  def run(
@@ -934,9 +980,10 @@ class ViewerHandle:
934
980
  """Jupyter calls this automatically when the handle is the result of
935
981
  a cell, embedding the viewer inline without the user having to open a
936
982
  separate browser tab."""
937
- src = self.url_for(self.view) if self.view else self.url
983
+ src = html.escape(self.url_for(self.view) if self.view else self.url)
984
+ height = html.escape(str(self.iframe_height))
938
985
  return (
939
- f'<iframe src="{src}" width="100%" height="{self.iframe_height}" '
986
+ f'<iframe src="{src}" width="100%" height="{height}" '
940
987
  f'style="border:none;" allow="fullscreen"></iframe>'
941
988
  )
942
989