Commit Graph
2294 Commits
Author SHA1 Message Date
Hakan Seven 3385160493 Merge PR #1028: add document API with atomic edits
Add the typed document facade and plugin IPC adapter. Prepare bulk edits
before mutation, preserve undo and dirty state, keep profile elevations,
validate numeric inputs and session bindings, and generate Python constructors
with typed results.

Reuse existing entity transforms and profile conversion. Compute mass
properties and closed-surface bounds in cadkernel; pin its main revision
6a5e6fc2822f6af6b2611cd605b44437b35158f0. Keep plugin API metadata at version 6.

Validation: 646 native application tests, 597 kernel tests, 12 document API
tests, 91 plugin API tests, 3 Python tests, default/IPC feature builds and
wasm32 check passed.
2026-09-06 21:43:02 +03:00
Hakan Seven bf4614856c Merge PR #1023: preserve minified text strokes
Keep adaptive sampling in both text shaders with compact sampling loops. Validate shader derivatives and existing text rendering, including GPU pipeline creation.

Closes #964
2026-09-06 21:04:14 +03:00
Sebastian f79c8c59bb ocs_doc_api: dissolve src/app/doc_api_convert.rs shim into direct crate usage
Delete the thin re-export file; src/app/doc_api.rs now uses ocs_doc_api::convert
directly (use ocs_doc_api::convert + convert::* call sites). Remove the
mod doc_api_convert registration from src/app/mod.rs.

The conversion logic already lives in the crate (src/convert.rs) from the prior
move; the shim was redundant. 623 host lib + 38 doc_api tests green.
2026-09-06 17:14:48 +02:00
Sebastian d746d635fb ocs_doc_api: move doc_api_convert.rs into the crate (src/convert.rs)
Move the 503-line host-independent entity-conversion module (acadrust EntityType
<-> DTO conversions, transform_entity_geometry, entity_to_profile_curves,
bulge_arc_segment, entity_bounds, entity_kind_name, points_aabb) from
src/app/doc_api_convert.rs into crates/ocs_doc_api/src/convert.rs (host feature).

The host file is now a thin re-export (pub use ocs_doc_api::convert::*) so all
existing crate::app::doc_api_convert::* paths keep working unchanged. Zero
coupling risk (the module only touches acadrust + crate DTOs).

623 host lib + 8 crate + 3 consistency green.
2026-09-06 17:00:04 +02:00
Sebastian 919128e087 ocs_doc_api: fix branch-review findings (tab auth, bulge center, budget, caps, dead code)
CRITICAL:
- execute_doc_api: reject tab_id != bound tab (confused deputy); test
  doc_api_tab_mismatch_is_rejected.
- bulge_arc_segment: fix negative/CW bulge center (apothem magnitude + sign picks
  side; was double-sign-mirrored); test CW-vs-CCW center offset.
- cold-tess budget: move mass_cache/cold_tess_used to per-tab Scene so the budget
  persists across DocApi dispatches (was reset per request); budget-exhausted ->
  approximate meshes.metrics fallback instead of error.

WARNING:
- Loft: add BULK_ITEM_CAP (was uncapped -> unbounded kernel call from one request).
- CreateMany: pre-validate EntitySpec::Curve (ellipse ratio) in prepare phase ->
  all-or-nothing restored; regression test.
- Partial Ellipse: offset start/end_parameter by rot_z on rotation; regression test.
- resolve_body: add with_body borrow accessor (host overrides to borrow cache in
  place, O(1)); bounds() uses it instead of deep-cloning the B-rep per query.
- add_raster_image: validate file path (non-empty, image extension, reject
  UNC/traversal); regression test.

SUGGESTION:
- deploy: bump API_VERSION 5 -> 6 so DocApi plugins are gated at handshake on old
  hosts (append-only wire + defaulted method keep old V2-V5 plugins loading).
- dead code: wire query_name into apply_queries error labels; host uses crate's
  ObjectId::from_handle/to_handle (drop local duplicates); delete is_null/backend_mut.
- mock drift: test mock now stores curve specs + computes curve bounds (aligns with
  example mock); Spline/Dimension bounds delegate to points_aabb.

623 host lib + 8 crate + 3 consistency + 34 plugin_api green.
2026-09-06 16:03:34 +02:00
Sebastian ac54d6079b ocs_doc_api: fix review findings (layouts, Helix bounds, points_aabb, mass-properties budget, docs)
- layouts.json: append the 6 missing ops (CreateDimensionRadius/Diameter/Angular,
  CreateAttributeDefinition, CreateTable, CreateDimensionAngular2Ln); regenerate
  binding_schema.json + api_reference.md wire vocabulary (all 28 ops).
- Helix bounds: bound the evaluated spline control polygon (was a degenerate
  single-start-point AABB).
- points_aabb: empty -> Geometry::Empty('entity has no points to bound'), not
  UnknownId (the entity exists; don't misclassify as stale/deleted).
- mass_properties: accuracy-first fine tessellation + graceful degradation to the
  approximate meshes.metrics value when the cold-tess budget is exhausted (large
  distinct-solid batches no longer hard-fail).
- IMPLEMENTATION.md: Volume/Centroid rows + accuracy paragraph + test count (618)
  consistent with the final design.
- 618 host lib + 8 crate + 3 consistency green.
2026-09-06 14:23:00 +02:00
Sebastian 28c8e0ef1a ocs_doc_api: read-mostly family bounds (Leader/Mesh/Face3D/MLine/Helix)
- entity_bounds: vertex/point-carrying read-mostly families (Leader.vertices,
  Mesh.vertices, Face3D 4 corners, MLine vertex positions, Helix start point)
  via a points-to-AABB helper. Region/Body/Surface/MultiLeader stay Unsupported.
- IMPLEMENTATION.md: read-mostly bounds done.
- Test read_mostly_family_bounds_leader_and_mesh -> 618 host lib green.
2026-09-06 13:46:41 +02:00
Sebastian 6997dfe618 ocs_doc_api: accurate GetVolume/GetCentroid via fine tessellation
- mass_properties: query path now uses fine mesh_body(0.1, 1e-4) for near-analytic
  volume/centroid; the render-mesh metrics cache (coarse display LOD) no longer
  shadows query accuracy. Memoized per (handle, epoch); cold-tess budget kept.
- IMPLEMENTATION.md: accuracy item done.
- Test accurate_volume_centroid_sphere_and_cube (sphere within 0.5% of 4/3*pi*r^3,
  centroid at centre, cube exact) -> 617 host lib green.
2026-09-06 13:40:07 +02:00
Sebastian 612e8e13e0 ocs_doc_api: Phase 2c-iii — 2-line angular dimension (all dimension sub-types done)
- CreateDimensionAngular2Ln(DimensionAngularSpec) op (append-only).
- backend add_dimension_angular2ln (DimensionAngular2Ln::new computes angle).
- facade create_dimension_angular2ln; spec constructor; api_reference + binding_schema
  regenerated; mocks + baseline.
- IMPLEMENTATION.md: fix stale Status line (all 5 phases complete, current test
  counts); mark all dimension sub-types done.
- Test phase2ciii_dimension_angular2ln (90-degree 2-line angle) -> 616 host lib +
  3 consistency green.
2026-09-06 13:24:25 +02:00
Sebastian 240831edcd ocs_doc_api: Phase 5-ii — typed Table create
- CreateTable(TableSpec{insertion_point, data[row][col]}) op (append-only).
- backend add_table via Table::new(insertion_point, rows, cols) + set_cell_text
  (Table::default() pre-creates 3x3, so use Table::new for exact dims).
- executor validates non-empty rectangular grid; facade create_table.
- spec Table constructor; api_reference + binding_schema regenerated; mocks + baseline.
- Test phase5ii_create_table_from_grid (3x2 grid, non-rectangular rejected)
  -> 615 host lib + 3 consistency green. Phase 5 complete.
2026-09-06 13:02:21 +02:00
Sebastian f8ae54a351 ocs_doc_api: Phase 3-ii — typed AttributeDefinition create (Phase 3 complete)
- CreateAttributeDefinition(AttributeDefinitionSpec) op (append-only).
- backend add_attribute_definition (ATTDEF tag/prompt/default/insertion/height/rotation).
- facade create_attribute_definition; entity_kind_name AttributeDefinition/AttributeEntity.
- spec AttributeDefinition family; api_reference + binding_schema regenerated; mocks + baseline.
- Test phase3ii_create_attribute_definition -> 614 host lib + 3 consistency green.
2026-09-06 12:43:34 +02:00
Sebastian 8d8c120880 ocs_doc_api: Phase 2c-ii — dimension sub-types (radius/diameter/angular)
- CreateDimensionRadius/CreateDimensionDiameter (DimensionRadialSpec) +
  CreateDimensionAngular (DimensionAngularSpec) ops (append-only).
- backend add_dimension_radius/diameter (DimensionRadius/DimensionDiameter::new)
  + add_dimension_angular (DimensionAngular3Pt::new computes angle);
  dimension_measurement returns degrees for angular sub-types.
- facade create_dimension_radius/diameter/angular; spec constructors; api_reference
  + binding_schema regenerated; mocks + baseline.
- Test phase2cii_dimension_radius_diameter_angular -> 613 host lib + 3 consistency green.
2026-09-06 12:31:23 +02:00
Hakan Seven 2ebad14586 fix(web): capture save previews from the browser canvas
Capture the rendered canvas during the clean frame instead of requesting synchronous GPU buffer readback. Preserve embedded previews and allow saving when canvas readback is denied. Add a browser save and reopen regression check.

Fixes #1021
2026-09-06 13:14:56 +03:00
Hakan Seven a16e0f4163 Remove theme-changing test cases 2026-09-06 12:26:10 +03:00
Hakan Seven 2c83ae2736 Show donation request once per app version 2026-09-06 11:44:38 +03:00
Sebastian e216a7bf94 ocs_doc_api: outstanding methods — loft + bulge-arc polyline profiles
- Loft{profiles} op (append-only); executor resolves each profile to curve sets
  all-or-nothing; backend loft() -> brep::loft on XY plane; facade solids().loft.
- entity_to_profile_curves: convert LwVertex.bulge to geom2d::Curve::Arc via
  bulge_arc_segment (theta = 4*atan(bulge)), so bulged polyline profiles sweep
  correctly instead of erroring Unsupported.
- spec loft; api_reference + binding_schema regenerated; mocks + baseline.
- Tests: loft_two_profiles_produces_solid, bulge_arc_polyline_profile_converts_to_arc
  (semicircle radius=5 for bulge=1) -> 612 host lib + 3 consistency green.
2026-09-06 10:44:37 +02:00
Sebastian 46a5922520 ocs_doc_api: Phase 5 typed raster image create
- CreateRasterImage(RasterImageSpec) op (append-only).
- backend add_raster_image (RasterImage with file_path/insertion/u/v/size; the
  scene auto-registers the ImageDefinition on add_entity).
- facade create_raster_image; spec RasterImage constructor; api_reference +
  binding_schema regenerated; mocks + baseline.
- Test phase5_create_raster_image_registers_definition (asserts definition_handle
  auto-registered + 4-corner bounds) -> 610 host lib + 3 consistency green.
- Phase 5 complete.
2026-09-06 10:28:51 +02:00
Sebastian e6c132e0eb ocs_doc_api: Phase 4 set_view + viewport-view query
- SetViewportView op + GetViewportView query (append-only).
- backend set_viewport_view (update Viewport.view_target/view_height) + viewport_view.
- facade Entity::set_view/viewport_view (Viewport returns Entity).
- spec Viewport methods; api_reference + binding_schema regenerated; mocks + baseline.
- Test phase4_set_view_and_view_query -> 609 host lib + 3 consistency green.
- Phase 4 complete.
2026-09-06 10:16:27 +02:00
Sebastian 67655add72 ocs_doc_api: Phase 3 attributes + nested block traversal
- SetAttribute op + GetAttributes/GetBlockEntities queries (append-only).
- backend set_attribute (add/update Insert attribute), attributes (tag,value pairs),
  block_entities (read-only traversal via BlockRecord.entity_handles -> id+kind+bounds).
- facade Entity::set_attribute/attributes, Document::block_entities.
- spec Insert methods; api_reference + binding_schema regenerated; mocks + baseline.
- Query enum: drop Copy (GetBlockEntities carries String).
- Test phase3_attributes_and_block_traversal -> 608 host lib + 3 consistency green.
2026-09-06 10:02:23 +02:00
Sebastian 2dba0158ca ocs_doc_api: Phase 2b-c (linear Dimension) — Phase 2 complete
- CreateDimensionLinear(DimensionSpec) op + GetDimensionMeasurement query (append-only).
- backend add_dimension_linear (Dimension::Linear via DimensionLinear::new) +
  dimension_measurement (linear/radius/diameter distance).
- Dimension bounds from measured + definition points; Dimension handle + measurement().
- spec Dimension family; api_reference + binding_schema regenerated; mocks + baseline.
- Test phase2c_dimension_linear_create_measurement_bounds -> 607 host lib + 8 crate
  + 3 consistency green. Phase 2 (full 2D + annotations) is now complete.
2026-09-06 09:43:37 +02:00
Sebastian ba8e5ed0cd ocs_doc_api: Phase 2b-b (Hatch)
- CreateHatch(HatchSpec) op + GetHatchBoundary query (append-only).
- HatchSpec{boundary: Vec<[f64;2]>, solid}; executor validates >= 3 boundary points.
- backend add_hatch (Line-edge BoundaryPath, solid/pattern) + hatch_boundary
  (reconstruct loops from Line edges; non-line edges -> Unsupported).
- Hatch bounds from boundary edges; facade create_hatch + Entity handle.
- spec Hatch family; api_reference + binding_schema regenerated; mocks + baseline.
- Test phase2b_hatch_create_boundary_bounds_delete -> 606 host lib + 8 crate + 3 consistency green.
2026-09-06 09:24:11 +02:00
Sebastian fc0e2c2c9d ocs_doc_api: Phase 2b-a (Text/MText annotations)
- CreateText/CreateMText/SetTextContent ops + GetTextContent query (append-only).
- backend add_text/add_mtext/set_text_content/text_content (Text.value/MText.value).
- facade create_text/create_mtext + Text/MText handles with content()/set_content().
- Text/MText coarse bounds + transform (insertion point); ensure_transformable.
- spec Text/MText families; api_reference + binding_schema regenerated; mocks.
- can_modify backend hook (exists + not-locked) for SetTextContent validation.
- consistency baseline extended with the appended variants.
- Test phase2b_text_mtext_create_content_transform -> 605 host lib + 3 consistency green.
2026-09-06 09:07:41 +02:00
Sebastian c74504f30c ocs_doc_api: fix review findings (scale/rotation/all-or-nothing/DoS/bounds/codegen)
CRITICAL:
- transform_entity_geometry: fix s^2 double-scale (axes already carry scale; drop
  the *s pre-multiply so 2D entities scale by s like solids), and handle rotation
  for direction/angle fields (apply_dir for Ray/XLine direction + Ellipse
  major_axis; offset Arc angles; compose Insert rotation).
- ensure_transformable: check layer-lock + resolve solid bodies (not just type),
  restoring TransformMany all-or-nothing; regression test with a locked layer.

WARNING:
- volume/centroid: memoize per (handle, geometry_epoch) + cap cold-cache
  tessellation budget (query-batch DoS).
- entity_to_profile_curves: fail Unsupported on polyline bulge (no silent
  chord-substituted sweep profile).
- Ellipse: validate minor_axis_ratio in (0,1] so bounds never under-bound.
- RasterImage bounds: bracket all four corners (rotated/flipped images).

SUGGESTION:
- binding_schema.json handles derived from spec families (includes ArcCurve/
  Ellipse/Spline/Ray/XLine).
- build.rs header: enums are hand-maintained (not 'GENERATED'); ops_gen/query_gen
  headers corrected to match.
- Dedupe divergence mesh_volume_centroid into the crate's geom module; host +
  both mocks delegate.

Tests: +3 regression tests (scale-once, rotation, locked-layer all-or-nothing)
-> 604 host lib green; 8 crate unit tests green.
2026-09-06 08:36:06 +02:00
codallos 995b25ae51 Fix SDF text minification artifacts 2026-09-05 22:30:16 -06:00
gianlucafiore 1b0a42a35c Merge pull request #1022 from gianlucafiore/feat/drawing-cursor-dot
feat(cursor): add point cursor for active commands
2026-09-05 22:52:00 -03:00
gianlucafiore 5bca05d913 feat(cursor): add point cursor for active commands 2026-09-05 22:39:34 -03:00
Karim Jerbi 0dab3ec54a feat: add COMMANDLINEFADETIME sysvar for overlay history fade
Controls how long command-line history lines stay visible, in ms (0-60000, default 3000). Bare form stays active until a value or Esc.
2026-09-06 02:13:09 +01:00
Sebastian f24c0b2d75 ocs_doc_api: Phase 5 (media & misc, read-mostly)
- entity_kind_name names the media/misc families (RasterImage, Table, Leader,
  MultiLeader, MLine, Mesh, Helix, Region, Body, Surface, Face3D, Dimension,
  Hatch) so GetEntity reports a real kind instead of 'Other'.
- RasterImage coarse bounds (insertion + u*width + v*height).
- Generic delete already works on these families; no typed create in v1
  (read-only EntityView per plan).
- spec RasterImage/Table read-mostly families; IMPLEMENTATION.md updated.
- Test phase5_media_entities_read_kind_and_bounds -> 601 host lib green.
2026-09-06 01:22:28 +02:00
Sebastian 7a481c6ce2 ocs_doc_api: Phase 4 (paper-space viewports)
- Operation::CreateViewport(ViewportSpec) appended to the wire enum (append-only).
- backend add_viewport (center/width/height/view_target/view_height).
- Viewport bounds (center +- w/2,h/2), transform (moves center), ensure_transformable.
- facade EntityCollection::create_viewport; spec Viewport family; api_reference +
  binding_schema regenerated; mocks updated.
- Test phase4_create_viewport_bounds_transform -> 600 host lib green.
- IMPLEMENTATION.md: Phase 4 done (set_view/view-query remaining).
2026-09-06 01:16:31 +02:00
Sebastian b03f68737e ocs_doc_api: Phase 3 (block references)
- Operation::CreateInsert(InsertSpec) appended to the wire enum (append-only).
- backend add_insert validates the BlockRecord exists (unknown block -> Validation,
  no mutation); host inserts acadrust::entities::Insert with scale+rotation.
- Insert transform moves insert_point (transform_entity_geometry) +
  ensure_transformable includes Insert.
- facade EntityCollection::create_insert; spec Insert family; api_reference +
  binding_schema regenerated; mocks updated.
- Test phase3_create_insert_and_transform -> 599 host lib green.
- IMPLEMENTATION.md: Phase 3 done (attributes/traversal remaining).
2026-09-06 01:05:51 +02:00
Sebastian d46351cdb3 ocs_doc_api: Phase 0 + Phase 2a (sweep profiles, non-solid transform, full 2D curves)
Phase 0 (outstanding supported-family methods):
- add_vertex on LwPolyline (insert vertex, out-of-range validation).
- extrude / revolve from profiles (entity_to_profile_curves: Line/Circle/Arc/
  LwPolyline straight-segment conversion -> geom2d::Curve -> brep::extrude/revolve).
- non-solid transform + transform_many via acadrust geometry
  (transform_entity_geometry for Line/Circle/Arc/Point/LwPolyline).
- ensure_transformable broadened accordingly (all-or-nothing pre-validation).

Phase 2a (full 2D curve families): ArcCurve/Ellipse/Spline/Ray/XLine.
- Curve2Spec extended (Arc/Ellipse/Spline/Ray/XLine) + create_arc/create_ellipse/
  create_spline/create_ray/create_xline facade constructors + handle types.
- entity_kind_name, entity_bounds (Arc coarse, Ellipse major-axis, Spline bbox;
  Ray/XLine unbounded), transform_entity_geometry, ensure_transformable extended.
- spec/entities.toml families; api_reference.md + binding_schema.json regenerated.

Tests: +6 doc_api integration tests (phase0_*, phase2_*) -> 598 host lib green.
IMPLEMENTATION.md updated (Phase 0 done, Phase 2a done / 2b remaining).
2026-09-06 00:51:39 +02:00
Sebastian e41086b058 Add ocs_doc_api: object-oriented CAD entity API (v2)
New crate crates/ocs_doc_api: object-centric facade (DocApi -> Document ->
collections -> typed handles), transport-agnostic wire layer (DocApiEnvelope =
single op | read-only query batch), per-op autocommit (no write transactions),
bulk ops with upfront-validation all-or-nothing, structured ApiError, and
build-time codegen (spec/entities.toml -> ops/query enums, api_reference.md,
binding_schema.json).

ocs_plugin_api: append-only PluginRequest::DocApiRequest / PluginResponse::
DocApiResponse (serde_bytes payload) + defaulted HostApi::doc_api_dispatch.

Host: DocApiBackend impl for HostSession (src/app/doc_api.rs) mapping to scene
primitives (solid_models lift-on-miss, register_prepared_solid_model, meshes
metrics), entity conversions (doc_api_convert.rs), HostSession accessors +
doc_api_dispatch override.

Tests: 592 host lib (incl. 7 DocApi integration tests: create/boolean/query,
unknown-id, transform-many all-or-nothing, query-batch cap, 2D/geometric/DWG
roundtrips), 8 crate unit tests. Examples + README/ARCHITECTURE/IMPLEMENTATION docs.
2026-09-06 00:15:27 +02:00
gianlucafiore 2ed09459c1 fix(images): refresh raster cache during grip edits 2026-09-05 16:09:40 -03:00
gianlucafiore 410624e4b3 feat(insert): add initial PDF underlay attachment 2026-09-05 15:39:22 -03:00
Hakan Seven ac8a545669 Fix layout cache correctness and GPU resource recovery 2026-09-05 19:56:49 +03:00
Hakan Seven 1a4b389b0e Merge pull request #1014: perf: let one tessellation serve every background 2026-09-05 19:28:34 +03:00
Hakan Seven a03973bc6e Merge pull request #1017: Pr/viewport slot memory - Give back the device memory of viewports nobody is drawing 2026-09-05 19:28:33 +03:00
Hakan Seven ed5b3d9276 Merge pull request #1016: Pr/gpu error recovery - Never cache a buffer the device rejected 2026-09-05 19:28:32 +03:00
Hakan Seven 99bb9889e1 Merge pull request #1013: perf: store block-wire segments once instead of six times 2026-09-05 19:28:31 +03:00
Hakan Seven faafdb14bf Merge pull request #1018: Pr/layout switch notice Draw a notice for one frame before rebuilding a layout 2026-09-05 19:28:31 +03:00
Hakan Seven 52d9c047d9 Merge pull request #1015: The grid overlay was rebuilding the whole drawing 2026-09-05 19:28:30 +03:00
Hakan Seven 9d9725f371 Merge pull request #1012: Pr/visible entity index 2026-09-05 19:28:29 +03:00
Hakan Seven cb88f2ded6 Accelerate native MCP workflows 2026-09-05 19:03:16 +03:00
PanosandClaude Opus 5 391a74a615 perf: let one tessellation serve every background
Switching to a Layout re-tessellated the whole model — `memo_miss=186455`,
2034 ms — to arrive at geometry identical to what was already in the memo.
The only thing that differed was colour.

`local_wires_for` already knows this: it stores the raw colour and drops
its background argument with `let _ = bg_color;`, noting that
`Batches::finalize` applies `adapt_to_bg` last, "so the cache no longer
has to rebuild on BACKGROUND / layout-switch". The tessellation memo's
guard had not been told, and still mixed the background in, so every
entry was discarded on a switch.

`finalize` now records what its colour resolution consumed — the raw
colour, the raw glyph colours, and the three flags it branches on — as
`WireModel::bg_adapt`, and `resolve_colors_for_bg` replays it for another
background. The guard drops the background, so a memo entry serves any
layout.

The resolution recomputes from the recorded raw colour rather than from
the resolved one, which makes it idempotent and therefore safe over a set
that mixes memo hits with freshly tessellated misses. Re-adapting the
resolved colour would not be safe: `adapt_to_bg` snaps a near-white colour
to pure black on a light background, and pure black comes back pure
*white* on a dark one, losing the tint. A test pins that asymmetry so the
raw colour is not optimised away later.

The contract is tested against the real `finalize` rather than a copy of
its logic: for every background pair, building under one and resolving for
the other lands exactly where building under the other would have.

`bg_adapt` is `None` for wires built anywhere else, and the resolution
skips them, so nothing outside the block cache changes colour. It is also
`None` when the resolution would be a no-op — a preserved colour with no
canvas fill looks the same under every background — which keeps the common
case at no cost.

Ordering is unchanged: the pass runs inside the builder, before
`append_scene_markers` and `apply_refedit_fade`, both of which have their
own separate background dependency.

`wires-build` gains `colors=` so the pass has a number of its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:16 +03:00
PanosandClaude Opus 5 49318a1c55 perf: allocate a shadow map only for viewports that cast shadows
`gpu-live` made this the obvious next one. Once idle slots started giving
their memory back, the shadow maps were the largest thing that never did:
128 MiB across eight slots, 37 % of the 341 MiB floor, and none of it
sampled — `shadow_enabled` defaults to false and most visual styles never
turn it on.

Every slot allocated `SHADOW_MAP_SIZE` squared at `Depth32Float` in
`Pipeline::new` and held it for the life of the slot, because the frame
bind group needs *something* at its shadow binding and the field was not
optional.

It is now `Option<(Texture, TextureView)>` alongside a 1x1 placeholder
that satisfies the binding while shadows are off — nothing samples it
then, so one texel is the whole requirement. `sync_shadow_target`
allocates on the transition into shadows and drops on the way out, and
only on the transition, so a viewport that keeps its setting does not
rebuild a bind group every frame.

The frame bind group had two inline builders — one in `Pipeline::new`, one
in `upload_background_images` — and this adds a third caller, so they are
now one `rebuild_frame_bind_group`. A shadow transition cannot forget the
background image the slot already had.

The shadow pass now tests for the target rather than the flag: wanting
shadows and having somewhere to put them are different questions, and
without the second one a failed 16 MiB allocation would have rendered the
pass into the 1x1 placeholder. Releasing a cold slot hands the target back
too, and `gpu-live` reports what is actually held rather than a constant.

Covered by a GPU test that toggles the setting off/on/off/on against a
real adapter with a validation scope armed, then releases the slot — the
transition is the risky path and the other GPU tests never take it.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00
PanosandClaude Opus 5 d9c998fa17 fix: never cache a buffer the device rejected
After an out-of-memory the viewport stopped updating for the rest of the
session — both Model and Layout frozen, the UI still responsive. The log
shows why: `block-wire-geometry` prints *after* the errors it provoked.
The failed uploads were cached.

A rejected allocation still yields a `Buffer`. It is invalid, every later
use reports again, and it is indistinguishable from a good one at the
cache key. So the entry keeps hitting, nothing ever rebuilds, and the
frame stays empty even once memory frees up. Sharing `block_geometry`
across slots in the previous commit made that worse, not better: one
poisoned entry now serves every viewport.

The device's uncaptured-error counter was already there, private to the
handler that throttles the log. It is now readable, and the three caches
that can retain a bad upload — block definition geometry, the shared wire
buffer cache, and the arena's content id — snapshot it across their build
and decline to record what it condemns. The degraded frame still draws;
the next frame tries again.

Best effort by construction: wgpu surfaces some errors asynchronously, so
a moved counter means something failed, while an unmoved one is not proof
that nothing did. That asymmetry is the right way round here — believing
a bad buffer costs a frozen viewport, rebuilding a good one costs a frame.

`block-wire-geometry` gains `poisoned=` so a run says whether this
happened rather than leaving it to be inferred.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00
PanosandClaude Opus 5 6599b82776 perf: store block-wire segments once instead of six times
The layout-switch OOM names its buffer: `Buffer with 'block_wire.vertices'
label is invalid`, right after `uncaptured wgpu error #1 … Out of Memory`.
That buffer is the largest thing this renderer allocates, and five sixths
of it is duplication.

A segment reaches the shader once per corner of its quad, and the packed
path satisfies that by writing the whole 60-byte record six times —
360 bytes a segment — with `vs_main` recovering the corner from
`vertex_index % 6`. Six identical copies, on a 2 GB card.

`block_wire_storage.wgsl` puts the segments in a read-only storage buffer
indexed by `vertex_index / 6` instead, so each record is stored once. The
geometry vertex buffer disappears; the placements move to slot 0 and the
segments arrive through the definition's bind group, which becomes
per-chunk because each chunk binds its own slice.

This is the pattern `wire_indexed.wgsl` already uses for per-wire
constants, down to the capability gate: `supports_wire_storage` asks for
exactly one vertex-stage storage binding, which is exactly what this
needs. Where it is false — WebGL, the forced compatibility renderer — the
packed shader and its vertex buffer are built as before.

`Segment` is declared with scalar members rather than `vec3<f32>`, which
would align to 16 in storage and reintroduce the padding this removes. A
test validates the shader through naga and asserts the struct's stride
equals `size_of::<BlockWireVertex>()`, because a layout mismatch would
otherwise surface only as garbage geometry on a real device.

`block-wire-geometry` reports the bytes uploaded and what the packed path
would have taken, so the saving is measured rather than assumed.

The cache value becomes `Arc<Vec<BlockGeometryChunk>>` while keeping the
translation-aware key from #1006 — both modes still have to invalidate
when the base instance moves, because the records hold its world
coordinates either way. `const_bgl` and the mode are decided together
when the pipeline is built, so they travel as one `BlockWireTarget`
rather than pushing `from_wires` past the argument limit.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00
PanosandClaude Opus 5 deebc14012 fix: a rejected upload must not latch the slot as up to date
The drawing vanished from Model and only came back with REGENALL. That is
this bug's exact signature, and the guard added two commits ago was
incomplete.

`cached_wire_id` gates the entire wire upload block — line 620 skips it
whenever the slot's id already matches the viewport's content id — and it
was stamped unconditionally at the end of that block, whether or not the
device had accepted what was uploaded. So a rejected allocation left the
slot holding invalid buffers *and* claiming to be current. Nothing
rebuilt it. REGENALL worked because it mints a new content id, which is
the one thing that makes the ids differ again.

`wire_buffer_cache` and `wire_arena_id` were guarded; this third latch,
the one that gates them both, was missed. Guarding it individually would
leave the same question for `cached_text_source`, `cached_hatch_source`
and the rest, each stamped after its own upload.

So the check moves to where it covers all of them: if the device reported
anything during this viewport's turn, the slot forgets every cache key it
holds and the next frame rebuilds it. The counter is device-wide, so an
error raised by one viewport also invalidates its neighbours in that
frame. That is deliberate — the cost is one slow frame, and the
alternative is the failure this fixes.

The narrower guards stay: `wire_buffer_cache` is shared across slots, so
keeping a bad entry out of it protects viewports that were healthy.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00
PanosandClaude Opus 5 0118b28d10 fix: give back the memory of viewports nobody is drawing
`MultiPipeline::inners` only ever grew. A slot that no viewport is using
still owned its wire arena, its render targets, its text atlas and every
category buffer — tens of megabytes each — and nothing ever asked for them
back. Zoom a paper layout out until five viewports are on screen, and the
memory the hidden ones are holding is exactly what the visible one cannot
get.

`Pipeline::release_heavy_resources` hands it back: arenas, wire and block
batches, the handle index, selection and preview buffers, wipeouts,
images, mesh batches, silhouettes, the text atlas, and the render targets,
which go through `ensure_depth_texture` at its smallest size rather than
being reached for directly so the blit bind group stays consistent with
the views it samples — about 0.6 MiB against the ~70 MiB a full-canvas
slot holds.

Everything released is derived state whose rebuild is guarded by a cache
key, and every one of those keys is reset. That reset was already written
once, inline, for slot reuse; both now call `forget_cached_keys` so they
cannot disagree about what "this slot holds nothing you can trust" means.
It gained two entries in the move — `cached_highlight_key` and
`silhouette_source_key` — which slot reuse had not been clearing, so a
recycled slot could keep a stale highlight or silhouette.

The policy is gradual while the device is healthy: a slot is released once
it has been idle for 64 prepare calls, so an ordinary session pays nothing
and a layout the user keeps returning to stays warm. It stops being
patient the moment the device refuses an allocation — at that point
holding an invisible viewport is what turns a degraded frame into a
session that cannot recover, and the operator needs the drawing to stay
usable long enough to close a viewport or two.

The cost of releasing a slot that is wanted again is one slow frame.

`slots-released n= urgent= slots=` reports when it happens, since the
alternative is inferring it from a memory number.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00
PanosandClaude Opus 5 d81a858040 perf: account for the device memory the renderer holds
Stage 0 of the roadmap asks for a memory baseline before any more
optimisation, and explicitly not from RSS: the allocator and the driver
both retain high-water memory that RSS cannot tell apart from live
resources.

`gpu-live` counts from the sizes this renderer allocated, in the
categories large enough to decide where the next fix goes:

    slots  total  shadow  targets  text_atlas  wire_arena  block_geometry

It is partial by construction and says so, rather than presenting itself
as a total. Hatches, images, meshes and Face3D are not counted yet.

Three of the numbers needed a size that was not reachable before: the
block-geometry chunk records its bytes at build because in storage mode
the buffer belongs to the bind group, the arena exposes its allocation
rather than its occupied prefix — headroom is what a budget has to answer
for — and the text atlas reports its `R8` texel count.

Emitted only when a number moves. `prepare` runs thousands of times in a
session and these change a handful of times, so a per-frame line would
bury the log it is meant to explain.

This answers the question the previous fix left open: whether the arena's
52 MiB per slot, the 16 MiB shadow map every slot allocates whether or not
shadows are on, or the render targets dominate once a paper layout has
four or five viewports on screen.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 18:53:09 +03:00