diff --git a/.github/workflows/github-actions-web-browser-smoke.yml b/.github/workflows/github-actions-web-browser-smoke.yml new file mode 100644 index 00000000000..c93f0206a95 --- /dev/null +++ b/.github/workflows/github-actions-web-browser-smoke.yml @@ -0,0 +1,65 @@ +name: web-browser-smoke +# The web viewer's unit tests draw against a stand-in for deck.gl; this one +# opens the live viewer and a saved report in Chrome and checks that a tile is +# drawn (//openroad/web/test:browser_smoke_test, tagged manual). +on: + pull_request: + branches: + - master + paths: + - openroad/web/** + - MODULE.bazel + - MODULE.bazel.lock + - .github/workflows/github-actions-web-browser-smoke.yml +permissions: + contents: read +# A new push to the PR cancels the run still building the last one. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + Web-Browser-Smoke: + runs-on: ${{ vars.USE_SELF_HOSTED == 'true' && 'self-hosted-ubuntu-26.04' || 'ubuntu-26.04' }} + steps: + - name: Check out repository code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: recursive + - name: Set up bazel + uses: bazel-contrib/setup-bazel@f34d6a05eae3c24acab7fa54587492daeaeffdab # 0.19.2 + with: + bazelisk-version: 1.x + bazelisk-cache: true + - name: Install Chrome when the runner has none + run: | + if ! command -v google-chrome >/dev/null; then + curl -fsSLo "${RUNNER_TEMP}/chrome.deb" \ + https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb + sudo apt-get update + sudo apt-get install -y "${RUNNER_TEMP}/chrome.deb" + fi + google-chrome --version + - name: Draw the layout in Chrome + env: + BAZEL_CACHE_LOGIN: ${{ secrets.BAZEL_CACHE_LOGIN }} + run: |- + # Same remote cache as github-actions-clang-tidy-bazel.yml: authed + # when the secret is there, the .bazelrc anonymous read otherwise. + LOGIN="${BAZEL_CACHE_LOGIN}" + REMOTE_FLAGS=() + if [ -n "${LOGIN}" ]; then + TOKEN_B64=$(printf '%s' "${LOGIN}" | base64 | tr -d '\n') + echo "::add-mask::${TOKEN_B64}" + REMOTE_FLAGS=( + --remote_cache=grpcs://bazel.precisioninno.com:443 + --experimental_remote_downloader=grpcs://bazel.precisioninno.com:443 + --remote_upload_local_results=true + --remote_header="Authorization=Basic ${TOKEN_B64}" + ) + fi + set -x + bazel test \ + "${REMOTE_FLAGS[@]}" \ + --test_output=errors \ + --test_env=CHROME="$(command -v google-chrome)" \ + //openroad/web/test:browser_smoke_test diff --git a/MODULE.bazel b/MODULE.bazel index cc208d596de..76783b9a2c3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -398,12 +398,17 @@ npm_web.npm_translate_lock( pnpm_lock = "//openroad/web:pnpm-lock.yaml", ) -# sax ships its licence as LICENSE.md, which the default "basic" preset strips -# with every other *.md; //openroad/web:third_party_licenses needs it. +# sax and gl-matrix ship their license as LICENSE.md, which the default "basic" +# preset strips with every other *.md; //openroad/web:third_party_licenses +# needs it. npm_web.npm_exclude_package_contents( package = "sax", presets = [], ) +npm_web.npm_exclude_package_contents( + package = "gl-matrix", + presets = [], +) use_repo(npm_web, "npm_web") # Regenerate //openroad/web:pnpm-lock.yaml after editing //openroad/web:package.json: diff --git a/openroad/web/BUILD b/openroad/web/BUILD index 52b88345e2d..79c7b19d57b 100644 --- a/openroad/web/BUILD +++ b/openroad/web/BUILD @@ -41,8 +41,10 @@ npm_link_all_packages(name = "node_modules") # What the bundle carries, with their dependencies, and so whose licences ship # with it. _BUNDLED_PACKAGES = [":node_modules/" + p for p in [ + "@deck.gl/core", + "@deck.gl/extensions", + "@deck.gl/layers", "golden-layout", - "leaflet", "lit", "netlistsvg", "three", @@ -57,13 +59,12 @@ js_library( deps = _BUNDLED_PACKAGES, ) -# The stylesheets import Golden Layout's and Leaflet's CSS. +# The stylesheets import Golden Layout's CSS. js_library( name = "css", srcs = glob(["src/*.css"]), deps = [ ":node_modules/golden-layout", - ":node_modules/leaflet", ], ) diff --git a/openroad/web/README.md b/openroad/web/README.md index 87a4d1b7c39..ee60ec0fba4 100644 --- a/openroad/web/README.md +++ b/openroad/web/README.md @@ -712,9 +712,17 @@ The module has two parts: Tiles are rendered from ODB geometry and encoded as PNG using lodepng. - **JavaScript frontend** (`src/main.js`, `src/index.html`, `src/style.css`) — - A single-page application using Leaflet.js for the map and GoldenLayout for - resizable panels. Communicates with the server over a binary WebSocket - protocol. + A single-page application using deck.gl (WebGL) for the layout view and lit + components for the panels. Communicates with the server over a binary + WebSocket protocol. + +## Browser requirements + +The layout view is drawn with WebGL 2, in the live viewer and in a saved +report alike. A browser without WebGL 2 shows the panels but no layout, and +says so; one that runs WebGL 2 in software, without the GPU, draws more slowly +and says that too. Current Chrome, Edge, Firefox, and Safari all have WebGL 2, +but may lose it when hardware acceleration is turned off in the browser. ## Browser libraries @@ -727,7 +735,7 @@ the result, so the browser only talks to the OpenROAD process. | Package | Used for | | --- | --- | -| `leaflet` | the tiled layout view | +| `@deck.gl/core`, `@deck.gl/layers`, `@deck.gl/extensions` | the layout view, drawn with WebGL through `deck-global.js` | | `golden-layout` | the dockable panel layout | | `netlistsvg` | the schematic, laid out by its own `elkjs` | | `three` | the 3D viewer, through `three-subset.js` | @@ -776,6 +784,16 @@ There are a set of regression tests in `./test`. bazelisk test //openroad/web/test/... ``` +`browser_smoke_test` opens the live viewer and a saved report, the report from +disk with the network off, in a real Chrome and checks that a tile is drawn. +It is tagged manual, since Chrome is not part of the build; CI runs it, and +locally it needs Chrome with WebGL 2 (software rendering is enough): + +```shell +bazelisk test //openroad/web/test:browser_smoke_test \ + --test_env=CHROME=$(command -v google-chrome) +``` + ## License BSD 3-Clause License. See [LICENSE](../../LICENSE) file. diff --git a/openroad/web/docs/server-api.md b/openroad/web/docs/server-api.md index 6a32a2c77f1..23f521bc2ac 100644 --- a/openroad/web/docs/server-api.md +++ b/openroad/web/docs/server-api.md @@ -154,8 +154,8 @@ canonical JSON type; sending any other type for a present field yields a on the wire, which the server tolerates for double-typed fields only. - Strings are JSON strings; arrays are JSON arrays. - Two narrow exceptions documented inline: - - `select.zoom` accepts `int` or `double` (Leaflet's `zoomSnap: 0` - permits fractional zoom values). + - `select.zoom` accepts `int` or `double` (a client may send a + fractional zoom value). - `set_heatmap.value` for `int`-typed settings accepts `int` or `double` and rounds (the JS frontend always uses `parseFloat`). @@ -171,13 +171,16 @@ simply listening on the WebSocket; there's no opt-in. | `type` field | Trigger | Body | | -------------- | ----------------------------------------------------------------------- | ------------------------------- | -| `refresh` | Initial spatial-index build finished after a connection / `web_server`. | `{"type":"refresh"}` | +| `config` | Once per connection, before any reply to a request. | `{"type":"config","max_in_flight":16}` | +| `refresh` | A connection's init finished, or the design was edited: redraw. | `{"type":"refresh"}` | | `log` | Buffered server log lines being flushed to clients. | `{"type":"log","text":""}` | | `debug_paused` | The graphics-debug pause hook entered (e.g. placer breakpoint). | `{"type":"debug_paused"}` | | `debug_resumed`| Pause hook exited. | `{"type":"debug_resumed"}` | | `debug_refresh`| Debug overlay needs a re-render. | `{"type":"debug_refresh"}` | | `shutdown` | Server is exiting; client should not auto-reconnect. | `{"type":"shutdown"}` | +`config.max_in_flight` is how many requests the client keeps on the wire. + --- ## Tile rendering @@ -204,30 +207,43 @@ Render a single 256×256 PNG tile of the layout. | Field | Type | Required | Description | | ---------------- | -------- | :------: | ----------- | -| `layer` | `string` | ✓ | Layer name (`metal1`, `metal2`, …) or one of the synthetic layers `_instances`, `_modules`, `_clusters`, `_pins`, or `_overlay`. | -| `z` | `int` | ✓ | Leaflet tile zoom level (0 = whole design). | +| `layer` | `string` | ✓ | Layer name (`metal1`, `metal2`, …) or a synthetic layer: `_instances`, `_pins`, `_modules`, `_clusters`, or one of the overlays the `tech` response lists. | +| `z` | `int` | ✓ | Tile zoom level (0 = whole design). | | `x` | `int` | ✓ | Tile column at zoom `z`. | | `y` | `int` | ✓ | Tile row at zoom `z`. | | `visible_layers` | `string[]` | ✓ | Tech layers currently visible, the union over the dies; an empty array hides them all. Read only by `_pins` and by the overlays whose `layers_by` group is on (see `tech`); every other tile ignores it, and it is left out of their cache key. | | `chiplet` | `string` | — | Chiplet path (as in the `tech` response's `chiplets[].path`) of the die a tech-layer tile draws. Two dies can share a layer name; omitted draws every visible chiplet. | | `chiplet_hidden_layers` | `object` | — | `{ "": ["", …] }`: layers hidden on that die only, while `visible_layers` still lists them. Read by the same tiles as `visible_layers`; a tech-layer tile names its die with `chiplet` instead. | +| `visible_chiplets` | `string[]` | — | Chiplet paths currently shown; a chiplet not listed is not drawn. Omitted draws every chiplet. | +| `renderer_host` | `bool` | — | Default `false`. On a tile that names its die with `chiplet`, also draw the debug renderers' pass for this layer name; the client sets it on one row per name. | | *visibility flags* | `bool` | per-flag default | See *TileVisibility flags* below. Any flag may be omitted to take the default. | | `site_` | `bool` | — | Per-row-site visibility. Only consulted when `rows == true`. | +| `pattern` | `int` | — | Fill pattern for the layer's shapes: `0` none, `1` solid (default), `2` diagonal, `3` cross, `4` dots. Out-of-range values mean solid. | **Response:** PNG image (frame type `1`), or frame type `3` with no body when the layer has nothing to draw in this tile. +**Caching:** the server caches the response under the tile, the rendered `dpr` +and `tile_px`, the design and chiplet revisions, and the parsed fields that can +change this layer's pixels. Selectability fields, keys the server does not +parse, and fields this layer does not read (for example `pin_markers` outside +`_pins`, the routing flags and `pattern` outside the tech layers, or +`visible_layers` outside `_pins`, `_access_points`, and, while pin names are +shown, `_inst_labels`) do not split the cache. Tiles that depend on per-session state (a session's own +module or group colors, focused nets, debug renderers) are not cached; the +default color palette is. + ### `overlay_tile` Render one tile of the highlight overlay — selection, hover, timing paths, DRC markers, route guides, flight lines and user labels — on a transparent background, on the same tile grid as `tile`. Kept separate from the layer -tiles so a selection change repaints one pane instead of re-rendering every +tiles so a selection change repaints the overlay instead of re-rendering every layer's geometry. | Field | Type | Required | Description | | --------------------- | ---------- | :------: | ----------- | -| `z` | `int` | ✓ | Leaflet tile zoom level, as for `tile`. | +| `z` | `int` | ✓ | Tile zoom level, as for `tile`. | | `x` | `int` | ✓ | Tile column at zoom `z`. | | `y` | `int` | ✓ | Tile row at zoom `z`. | | `visible_layers` | `string[]` | — | Tech layers currently visible. Consulted so route guides respect layer visibility; omitted means draw guides on every layer. | @@ -236,6 +252,7 @@ layer's geometry. | `focused_nets_guides` | `bool` | — | Default `false`. Draw route guides for the focused nets. | | `draw_labels` | `bool` | — | Default `true`. Draw user labels (`add_label`). | | `debug_renderers` | `bool` | — | Default `false`. Debug renderers are active, so the highlight must be re-derived every frame to track instances that move between them. | +| `poly_decomp` | `bool` | — | Default `false`. The Options > "Show polygon decomposition" setting, which changes the shapes an ITerm/MTerm highlight draws. A change re-derives the highlights, as with `flywires_only`. | **Response:** PNG image (frame type `1`), or frame type `3` with no body when nothing is highlighted in this tile — which is the usual case, since @@ -262,15 +279,17 @@ No request fields beyond the envelope. ```json { "bounds": [[yMin, xMin], [yMax, xMax]], + "fit_bounds": [[yMin, xMin], [yMax, xMax]], "shapes_ready": true, "pin_max_size": 200 } ``` -`bounds` is in DBU. `shapes_ready` indicates whether the spatial index -finished building (the `refresh` push fires when this flips to true). -`pin_max_size` is the largest BPin dimension in DBU, used by the client -to size the pin-marker overlay. +`bounds` is in DBU and georeferences the tile grid; `fit_bounds` is the +rect to zoom to fit, `bounds` without the pin-label margin. `shapes_ready` +indicates whether the spatial index finished building (the `refresh` push +fires when this flips to true). `pin_max_size` is the largest BPin dimension +in DBU, used by the client to size the pin-marker overlay. ### `layer_extents` @@ -377,7 +396,7 @@ No request fields. `overlays` lists the self-painting pseudo layers this design can draw (an overlay with nothing to draw, such as `_regions` in a design without regions, -is left out), each a `tile` layer of its own: `z_index` is its pane order +is left out), each a `tile` layer of its own: `z_index` is its draw order against the tech layers (`3` upwards), `_instances` (`0`) and `_pins` (`1`). `shown_by` and `layers_by` are groups of `tile` visibility keys, on when every key of any one group is on: the overlay draws anything when `shown_by` is on, @@ -397,7 +416,7 @@ overlapping objects on repeated calls at the same point. | ---------------- | -------- | :------: | ----------- | | `dbu_x` | `int` | ✓ | X coordinate in DBU. | | `dbu_y` | `int` | ✓ | Y coordinate in DBU. | -| `zoom` | `int` or `double` | ✓ | Current Leaflet zoom level. Server truncates fractional values. | +| `zoom` | `int` or `double` | ✓ | Current view zoom level. Server truncates fractional values. | | `visible_layers` | `string[]`| ✓ | Same semantics as `tile`. | | `chiplet_hidden_layers` | `object` | — | Same as `tile`: a layer hidden on one die is not picked there. | | `chiplet_nonselectable_layers` | `object` | — | `{ "": ["", …] }`: layers made unselectable on that die only, while `selectable_layers` still lists them. | @@ -1250,7 +1269,9 @@ request gets a `kError` response, the rest of the session continues. conversion failure, internal `runtime_error`, …): `kError` body `server error: `. -Every `kError` response logs a server-side warning: +Every `kError` response logs a server-side warning, except the routine ones: +the busy reply while a script runs and `cancelled` for a request the client +cancelled: ``` [WARNING WEB-0043] request id= type= failed: diff --git a/openroad/web/esbuild.config.mjs b/openroad/web/esbuild.config.mjs index 3130fba0b29..075124f196e 100644 --- a/openroad/web/esbuild.config.mjs +++ b/openroad/web/esbuild.config.mjs @@ -31,16 +31,41 @@ const elkBrowserBuild = { }, }; +// loaders.gl fetches worker scripts and codec libraries from unpkg when it has +// no copy of its own, so that fallback is pointed at nothing remote. Only a +// saved report's path overlay loads through it: a data: URL, decoded in page. +const kLoadersCdn = 'https://unpkg.com/@loaders.gl'; +const noLoadersCdn = { + name: 'no-loaders-cdn', + setup(build) { + build.onLoad({ filter: /[\\/]@loaders\.gl[\\/].*\.js$/ }, + async ({ path }) => { + const text = await readFile(path, 'utf8'); + if (!text.includes(kLoadersCdn)) { + return undefined; + } + return { + contents: text.replaceAll(kLoadersCdn, + 'loaders.gl-cdn-disabled'), + loader: 'js', + }; + }); + }, +}; + export default { // iife: one self-contained script whose top-level names stay out of the // page's global scope, however the page loads it. format: 'iife', platform: 'browser', target: ['es2022'], + // deck.gl's builds without WebGPU; the viewer draws with WebGL only. + // Custom conditions drop esbuild's default 'module', so it is listed too. + conditions: ['visgl:webgl-only', 'module'], loader: { - // leaflet.css and the golden-layout themes reach icons through relative + // The golden-layout stylesheets reach icons through relative // url(); inlined, the page needs no file besides the bundles. '.png': 'dataurl', }, - plugins: [compactSvg, elkBrowserBuild], + plugins: [compactSvg, elkBrowserBuild, noLoadersCdn], }; diff --git a/openroad/web/include/web/web.h b/openroad/web/include/web/web.h index 2ef8a5f993d..12520b295f3 100644 --- a/openroad/web/include/web/web.h +++ b/openroad/web/include/web/web.h @@ -176,7 +176,7 @@ bool tokenAllowed(const std::map& params, bool requestTokenAllowed(std::string_view target, std::string_view expected); // The redirect for a redeemed ticket: the request's raw query with `ticket` -// swapped for `token`, so viewer options like ?mergetiles=0 survive. +// swapped for `token`, so viewer options like ?preservebuffer=1 survive. std::string authRedirectTarget(std::string_view target, std::string_view token); // What presenting a launch ticket got. kReused is the right ticket after it diff --git a/openroad/web/package.json b/openroad/web/package.json index 892947a385a..dd8512e36bd 100644 --- a/openroad/web/package.json +++ b/openroad/web/package.json @@ -4,8 +4,10 @@ "type": "module", "description": "Browser libraries for the web viewer, bundled by esbuild into the assets embedded in the OpenROAD binary (issue #11065).", "dependencies": { + "@deck.gl/core": "9.4.0", + "@deck.gl/extensions": "9.4.0", + "@deck.gl/layers": "9.4.0", "golden-layout": "2.6.0", - "leaflet": "1.9.4", "lit": "^3.3.3", "netlistsvg": "1.0.2", "three": "0.160.0" @@ -13,6 +15,13 @@ "pnpm": { "onlyBuiltDependencies": [], "overrides": { + "@deck.gl/core>@types/offscreencanvas": "-", + "@deck.gl/layers>@types/geojson": "-", + "@loaders.gl/schema-utils>@types/geojson": "-", + "@loaders.gl/schema>@types/geojson": "-", + "@luma.gl/core>@types/offscreencanvas": "-", + "apache-arrow>@types/node": "-", + "lit-html>@types/trusted-types": "-", "netlistsvg>@types/clone": "-", "netlistsvg>@types/json5": "-", "netlistsvg>@types/lodash": "-", diff --git a/openroad/web/pnpm-lock.yaml b/openroad/web/pnpm-lock.yaml index d7e11d4f8f3..7c85d05aad7 100644 --- a/openroad/web/pnpm-lock.yaml +++ b/openroad/web/pnpm-lock.yaml @@ -5,6 +5,13 @@ settings: excludeLinksFromLockfile: false overrides: + '@deck.gl/core>@types/offscreencanvas': '-' + '@deck.gl/layers>@types/geojson': '-' + '@loaders.gl/schema-utils>@types/geojson': '-' + '@loaders.gl/schema>@types/geojson': '-' + '@luma.gl/core>@types/offscreencanvas': '-' + apache-arrow>@types/node: '-' + lit-html>@types/trusted-types: '-' netlistsvg>@types/clone: '-' netlistsvg>@types/json5: '-' netlistsvg>@types/lodash: '-' @@ -18,12 +25,18 @@ importers: .: dependencies: + '@deck.gl/core': + specifier: 9.4.0 + version: 9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) + '@deck.gl/extensions': + specifier: 9.4.0 + version: 9.4.0(@deck.gl/core@9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))))(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) + '@deck.gl/layers': + specifier: 9.4.0 + version: 9.4.0(@deck.gl/core@9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))))(@loaders.gl/core@4.5.4)(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) golden-layout: specifier: 2.6.0 version: 2.6.0 - leaflet: - specifier: 1.9.4 - version: 1.9.4 lit: specifier: ^3.3.3 version: 3.3.3 @@ -36,27 +49,142 @@ importers: packages: + '@deck.gl/core@9.4.0': + resolution: {integrity: sha512-0isP+x2eGNxteO7lT650lYO7oiAYXAu4aF1jG+BMi8aKYh38HtPugLq1TlQTravIXzBSi5Oe1oZNuVj8h4ZEjA==} + + '@deck.gl/extensions@9.4.0': + resolution: {integrity: sha512-KHtB0233PSVRac8oHTk0RDivOBORLRIvSQgMpteNxVUO1lRPEa3yoMj4AE2qcKa2w2jqwaT9zt881uyFEB0eSg==} + peerDependencies: + '@deck.gl/core': ~9.4.0 + '@luma.gl/core': ~9.4.0 + '@luma.gl/engine': ~9.4.0 + + '@deck.gl/layers@9.4.0': + resolution: {integrity: sha512-jSL/xje2Ez7DmnP8AAIdhhg6IAtfXMmnXiUAKNgpl/TTaEL+iL5TAnagCdt39H3azmKVcCG33kOlIoWFAuLuRg==} + peerDependencies: + '@deck.gl/core': ~9.4.0 + '@loaders.gl/core': ^4.4.3 + '@luma.gl/core': ~9.4.0 + '@luma.gl/engine': ~9.4.0 + '@lit-labs/ssr-dom-shim@1.6.0': resolution: {integrity: sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==} '@lit/reactive-element@2.1.2': resolution: {integrity: sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==} - '@types/trusted-types@2.0.7': - resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@loaders.gl/core@4.5.4': + resolution: {integrity: sha512-mhO2TT5KWU3GbFYSQ78nPAhoeCnoUfTYjzwxzhHAhd656U4MW/Rq5CxZxM6liKk0Jt11dCQ8VT4nXu8334CmqQ==} + + '@loaders.gl/images@4.5.4': + resolution: {integrity: sha512-Z/7SSC9v+iQdcpwkr7nSloCpgAREuO2/3yD4niAhk+ar7nrgRByaiBH16L51M5Juse8MG3oC67gaO85VuUb3jA==} + peerDependencies: + '@loaders.gl/core': ~4.5.0 + + '@loaders.gl/loader-utils@4.5.4': + resolution: {integrity: sha512-ZUNn/4+DEn8yTKGUKdjlbA7ok2JyNrica/Lvf1d8dwx7vCUSZ84PBB9cNtrx8VDXmVjkIClQzmnriz16QHjTMQ==} + + '@loaders.gl/schema-utils@4.5.4': + resolution: {integrity: sha512-vV52aT4RJiHzzbHlwdkX254d/ubdNzcxJuFfrfDeyUZkKDa//YPhVFjCxfNlxXgS+7pS0TGakfNB18vyYkk3FA==} + peerDependencies: + '@loaders.gl/core': ~4.5.0 + + '@loaders.gl/schema@4.5.4': + resolution: {integrity: sha512-5CO/TY2OkmM53+qfSvzMt17LwVJhBatqi/QaO45VOn8poTK1jqyZvnI0qvKFqOsMWzHh4yoQVUnxaWiV4CZ41w==} + + '@loaders.gl/worker-utils@4.5.4': + resolution: {integrity: sha512-OvVMMLh56QdBQgyMDxuho9doWq6oiz7paqP3rwidb+LqgJB5GvdqcoL+GbUcku2X8k0ZxCldvo+l46Yhpv0bfQ==} + peerDependencies: + '@loaders.gl/core': ~4.5.0 + + '@luma.gl/core@9.4.2': + resolution: {integrity: sha512-VFol6FUSHQeYR40NrkCM/mkP5DX7aI8pcDewxI8DBjtrcP4+ZJiJwnxWZnsMBzM4RuuvmDoHkPWCxj6Ob9yo+w==} + + '@luma.gl/engine@9.4.2': + resolution: {integrity: sha512-gBAcn+b1jOwE4pDF5zbuzMxCa/KGY3Q2Gq0gNUPU1AZHNk4aDgOEQaY2sqMsaoGHkDXB+pxneJQPw5c6Q5mnHA==} + peerDependencies: + '@luma.gl/core': ~9.4.0 + '@luma.gl/shadertools': ~9.4.0 + + '@luma.gl/gpgpu@9.4.2': + resolution: {integrity: sha512-LoEqoViPZqMHqQzvq/txFuOLsxI6sn8xmv+IZyovRFBqcWaV184PE/8Ieufww0pjVyJMfubhUCQmGuGrOME8oA==} + peerDependencies: + '@luma.gl/core': ~9.4.0 + '@luma.gl/engine': ~9.4.0 + '@luma.gl/shadertools': ~9.4.0 + '@luma.gl/webgpu': ~9.4.0 + + '@luma.gl/shadertools@9.4.2': + resolution: {integrity: sha512-0/6pLZSfnQnvcWdYePKKSwVet+gFtAAnKeGXNfxpgp3I8E3WsF/SbD6oEzgU7jdnRqONwGsoACWNpQHO0zZvIQ==} + peerDependencies: + '@luma.gl/core': ~9.4.0 + + '@luma.gl/webgl@9.4.2': + resolution: {integrity: sha512-D3GqnxTgQI+vsyH56hX5+jwqdVUhvhbpnPurTwbQOSlSQ8mshhNKcRdrZytTy10qiodDwrcjTnndPEAP6UgCzA==} + peerDependencies: + '@luma.gl/core': ~9.4.0 + + '@luma.gl/webgpu@9.4.2': + resolution: {integrity: sha512-24gDOmLyL81fVHxn+UXajnYN5jVln7XgB9fvobc1Yh3PAtXjlcAkmVTqYRvULVGeEamuqvqPDscAkaK/T+R1iQ==} + peerDependencies: + '@luma.gl/core': ~9.4.0 + '@luma.gl/shadertools': ~9.4.0 + + '@mapbox/tiny-sdf@2.3.0': + resolution: {integrity: sha512-gBvcNDBBB66bgQYvnaJ6Jk+VCaMmVq5+IZR2kWPisT88Z8s0kBQt6hfVi8QgRW8Vpg0UWZzBA4ZSyzHHC+VeRA==} + + '@math.gl/core@4.1.0': + resolution: {integrity: sha512-FrdHBCVG3QdrworwrUSzXIaK+/9OCRLscxI2OUy6sLOHyHgBMyfnEGs99/m3KNvs+95BsnQLWklVfpKfQzfwKA==} + + '@math.gl/polygon@4.1.0': + resolution: {integrity: sha512-YA/9PzaCRHbIP5/0E9uTYrqe+jsYTQoqoDWhf6/b0Ixz8bPZBaGDEafLg3z7ffBomZLacUty9U3TlPjqMtzPjA==} + + '@math.gl/sun@4.1.0': + resolution: {integrity: sha512-i3q6OCBLSZ5wgZVhXg+X7gsjY/TUtuFW/2KBiq/U1ypLso3S4sEykoU/MGjxUv1xiiGtr+v8TeMbO1OBIh/HmA==} + + '@math.gl/types@4.1.0': + resolution: {integrity: sha512-clYZdHcmRvMzVK5fjeDkQlHUzXQSNdZ7s4xOqC3nJPgz4C/TZkUecTo9YS4PruZqtDda/ag4erndP0MIn40dGA==} + + '@math.gl/web-mercator@4.1.0': + resolution: {integrity: sha512-HZo3vO5GCMkXJThxRJ5/QYUYRr3XumfT8CzNNCwoJfinxy5NtKUd7dusNTXn7yJ40UoB8FMIwkVwNlqaiRZZAw==} + + '@probe.gl/env@4.1.2': + resolution: {integrity: sha512-KIcdjrEiEZVIGX9nh7pZSmTMIKrd+wCb09gyXqpYYI4hs9WMqrQHvKZ7KD8ASutf6kwARwgd4WNQn8aucLSz3g==} + + '@probe.gl/log@4.1.2': + resolution: {integrity: sha512-2LqSq4CHhc/HJQasHMPOzA6c7rprlGz8CCREGebo19jxcuKdvXQo0DEmlfId076U6UldMp6jGhWvDHEFLX111Q==} + + '@probe.gl/stats@4.1.2': + resolution: {integrity: sha512-Hqc0UIHd0IZ2+JbovzTz7lYG7CY9D8yCB81zyP92Zl9UDSPcw2cLbTySW14keAQeAo1sjGjUw0+KHxr0Y2h/hA==} + + '@webgpu/types@0.1.74': + resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} + + apache-arrow@21.2.0: + resolution: {integrity: sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==} + hasBin: true clone@2.1.2: resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} engines: {node: '>=0.8'} + earcut@2.2.4: + resolution: {integrity: sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==} + elkjs@0.3.0: resolution: {integrity: sha512-bcO8RCIssdly316ou76QLsiuu1NCLbhhZwK/iuOdKTyQzKdCeX7sdIJOUdSsjlIDB203TN4NBpTiq4ugmLjR+Q==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + + gl-matrix@3.4.4: + resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==} + golden-layout@2.6.0: resolution: {integrity: sha512-sIVQCiRWOymHbVD1Aw/T9/ijbPYAVGBlgGYd1N9MRKfcyBNSpjr87Vg9nSHm+RCT8ELrvK8IJYJV0QRJuVUkCQ==} - leaflet@1.9.4: - resolution: {integrity: sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==} + json-with-bigint@3.5.12: + resolution: {integrity: sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==} lit-element@4.2.2: resolution: {integrity: sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==} @@ -70,6 +198,9 @@ packages: lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + mjolnir.js@3.1.1: + resolution: {integrity: sha512-Em3+0p6n2RamaiiDenHByvaWNolr+K0fWsFpgUgUXRssFI59ramCMdp0crU6V75clbA4fDJBVTBXfBF5rlPB9A==} + netlistsvg@1.0.2: resolution: {integrity: sha512-g6E7Q58HLevr+ls7FZTMf1xT3iXXxUVD+s7I4ijGKH+bhaobjnZbzKAi+Ex1AlNWK7fzujz3x4V3xMKOGiWfQw==} hasBin: true @@ -84,23 +215,192 @@ packages: three@0.160.0: resolution: {integrity: sha512-DLU8lc0zNIPkM7rH5/e1Ks1Z8tWCGRq6g8mPowdDJpw1CFBJMU7UoJjC6PefXW7z//SSl0b2+GCw14LB+uDhng==} + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + snapshots: + '@deck.gl/core@9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))': + dependencies: + '@loaders.gl/core': 4.5.4 + '@loaders.gl/images': 4.5.4(@loaders.gl/core@4.5.4) + '@luma.gl/core': 9.4.2 + '@luma.gl/engine': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)) + '@luma.gl/gpgpu': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@luma.gl/webgl': 9.4.2(@luma.gl/core@9.4.2) + '@math.gl/core': 4.1.0 + '@math.gl/sun': 4.1.0 + '@math.gl/types': 4.1.0 + '@math.gl/web-mercator': 4.1.0 + '@probe.gl/env': 4.1.2 + '@probe.gl/log': 4.1.2 + '@probe.gl/stats': 4.1.2 + gl-matrix: 3.4.4 + mjolnir.js: 3.1.1 + transitivePeerDependencies: + - '@luma.gl/webgpu' + + '@deck.gl/extensions@9.4.0(@deck.gl/core@9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))))(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))': + dependencies: + '@deck.gl/core': 9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) + '@luma.gl/core': 9.4.2 + '@luma.gl/engine': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)) + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@luma.gl/webgl': 9.4.2(@luma.gl/core@9.4.2) + '@math.gl/core': 4.1.0 + + '@deck.gl/layers@9.4.0(@deck.gl/core@9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))))(@loaders.gl/core@4.5.4)(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))': + dependencies: + '@deck.gl/core': 9.4.0(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))) + '@loaders.gl/core': 4.5.4 + '@loaders.gl/images': 4.5.4(@loaders.gl/core@4.5.4) + '@loaders.gl/schema': 4.5.4 + '@luma.gl/core': 9.4.2 + '@luma.gl/engine': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)) + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@mapbox/tiny-sdf': 2.3.0 + '@math.gl/core': 4.1.0 + '@math.gl/polygon': 4.1.0 + '@math.gl/web-mercator': 4.1.0 + earcut: 2.2.4 + '@lit-labs/ssr-dom-shim@1.6.0': {} '@lit/reactive-element@2.1.2': dependencies: '@lit-labs/ssr-dom-shim': 1.6.0 - '@types/trusted-types@2.0.7': {} + '@loaders.gl/core@4.5.4': + dependencies: + '@loaders.gl/loader-utils': 4.5.4(@loaders.gl/core@4.5.4) + '@loaders.gl/schema': 4.5.4 + '@loaders.gl/schema-utils': 4.5.4(@loaders.gl/core@4.5.4) + '@loaders.gl/worker-utils': 4.5.4(@loaders.gl/core@4.5.4) + '@probe.gl/log': 4.1.2 + + '@loaders.gl/images@4.5.4(@loaders.gl/core@4.5.4)': + dependencies: + '@loaders.gl/core': 4.5.4 + '@loaders.gl/loader-utils': 4.5.4(@loaders.gl/core@4.5.4) + + '@loaders.gl/loader-utils@4.5.4(@loaders.gl/core@4.5.4)': + dependencies: + '@loaders.gl/schema': 4.5.4 + '@loaders.gl/worker-utils': 4.5.4(@loaders.gl/core@4.5.4) + '@probe.gl/log': 4.1.2 + '@probe.gl/stats': 4.1.2 + transitivePeerDependencies: + - '@loaders.gl/core' + + '@loaders.gl/schema-utils@4.5.4(@loaders.gl/core@4.5.4)': + dependencies: + '@loaders.gl/core': 4.5.4 + '@loaders.gl/schema': 4.5.4 + '@math.gl/types': 4.1.0 + apache-arrow: 21.2.0 + + '@loaders.gl/schema@4.5.4': + dependencies: + apache-arrow: 21.2.0 + + '@loaders.gl/worker-utils@4.5.4(@loaders.gl/core@4.5.4)': + dependencies: + '@loaders.gl/core': 4.5.4 + + '@luma.gl/core@9.4.2': + dependencies: + '@math.gl/types': 4.1.0 + '@probe.gl/env': 4.1.2 + '@probe.gl/log': 4.1.2 + '@probe.gl/stats': 4.1.2 + + '@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))': + dependencies: + '@luma.gl/core': 9.4.2 + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@math.gl/core': 4.1.0 + '@math.gl/types': 4.1.0 + '@probe.gl/log': 4.1.2 + '@probe.gl/stats': 4.1.2 + + '@luma.gl/gpgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/engine@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))(@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)))': + dependencies: + '@luma.gl/core': 9.4.2 + '@luma.gl/engine': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)) + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@luma.gl/webgpu': 9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)) + '@math.gl/core': 4.1.0 + '@math.gl/types': 4.1.0 + '@probe.gl/log': 4.1.2 + '@probe.gl/stats': 4.1.2 + + '@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2)': + dependencies: + '@luma.gl/core': 9.4.2 + '@math.gl/core': 4.1.0 + '@math.gl/types': 4.1.0 + + '@luma.gl/webgl@9.4.2(@luma.gl/core@9.4.2)': + dependencies: + '@luma.gl/core': 9.4.2 + '@math.gl/types': 4.1.0 + '@probe.gl/env': 4.1.2 + + '@luma.gl/webgpu@9.4.2(@luma.gl/core@9.4.2)(@luma.gl/shadertools@9.4.2(@luma.gl/core@9.4.2))': + dependencies: + '@luma.gl/core': 9.4.2 + '@luma.gl/shadertools': 9.4.2(@luma.gl/core@9.4.2) + '@probe.gl/env': 4.1.2 + '@webgpu/types': 0.1.74 + + '@mapbox/tiny-sdf@2.3.0': {} + + '@math.gl/core@4.1.0': + dependencies: + '@math.gl/types': 4.1.0 + + '@math.gl/polygon@4.1.0': + dependencies: + '@math.gl/core': 4.1.0 + + '@math.gl/sun@4.1.0': {} + + '@math.gl/types@4.1.0': {} + + '@math.gl/web-mercator@4.1.0': + dependencies: + '@math.gl/core': 4.1.0 + + '@probe.gl/env@4.1.2': {} + + '@probe.gl/log@4.1.2': + dependencies: + '@probe.gl/env': 4.1.2 + + '@probe.gl/stats@4.1.2': {} + + '@webgpu/types@0.1.74': {} + + apache-arrow@21.2.0: + dependencies: + flatbuffers: 25.9.23 + json-with-bigint: 3.5.12 + tslib: 2.8.1 clone@2.1.2: {} + earcut@2.2.4: {} + elkjs@0.3.0: {} + flatbuffers@25.9.23: {} + + gl-matrix@3.4.4: {} + golden-layout@2.6.0: {} - leaflet@1.9.4: {} + json-with-bigint@3.5.12: {} lit-element@4.2.2: dependencies: @@ -108,9 +408,7 @@ snapshots: '@lit/reactive-element': 2.1.2 lit-html: 3.3.3 - lit-html@3.3.3: - dependencies: - '@types/trusted-types': 2.0.7 + lit-html@3.3.3: {} lit@3.3.3: dependencies: @@ -120,6 +418,8 @@ snapshots: lodash@4.18.1: {} + mjolnir.js@3.1.1: {} + netlistsvg@1.0.2: dependencies: clone: 2.1.2 @@ -134,3 +434,5 @@ snapshots: sax@1.6.1: {} three@0.160.0: {} + + tslib@2.8.1: {} diff --git a/openroad/web/src/capture.js b/openroad/web/src/capture.js index 1fc7316064d..b7bb0bc39d9 100644 --- a/openroad/web/src/capture.js +++ b/openroad/web/src/capture.js @@ -1,19 +1,13 @@ // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2026, The OpenROAD Authors -// WYSIWYG layout capture. Composites the currently rendered Leaflet layers -// (base tiles, the highlight/selection overlay, the active heatmap) plus the -// SVG overlays (rulers, selection outline, labels) into a PNG and downloads -// it — mirroring the Qt GUI's "Save image", which saves the displayed scene. -// -// All tiles are same-origin (blob: URLs), so the canvas is not tainted -// and toBlob() works. Tile positions are read from getBoundingClientRect so -// the composite is correct under fractional zoom / CSS transforms. +// WYSIWYG layout capture. Copies the view's canvas (tiles, overlays, +// heatmap, selection, rulers) and the ruler distance labels into a PNG and +// downloads it — mirroring the Qt GUI's "Save image", which saves the +// displayed scene. The PNG is in CSS pixels. // // entire=true first fits the whole design (no animation), waits for every -// layer's tiles to settle, then composites — capturing the full design exactly -// as the window shows it (layers + heatmap + highlights + rulers), and restores -// the previous view afterwards. +// layer's tiles to settle, then captures, and restores the previous view. function downloadBlob(blob, filename) { if (!blob) { @@ -30,108 +24,16 @@ function downloadBlob(blob, filename) { setTimeout(() => URL.revokeObjectURL(url), 0); } -// A layer's effective opacity (default 1 when unset). -function layerOpacity(layer) { - return (layer.options && layer.options.opacity != null) - ? layer.options.opacity : 1; -} - -// Draw one /element at its on-screen position relative to the map. Skips -// an that hasn't decoded yet, and swallows a not-yet-drawable element. -function drawElementAt(ctx, el, mapRect) { - if (!el) { - return; - } - if (el.tagName === 'IMG' && (!el.complete || !el.naturalWidth)) { - return; // still loading - } - const r = el.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) { - return; - } - try { - ctx.drawImage(el, r.left - mapRect.left, r.top - mapRect.top, - r.width, r.height); - } catch (err) { - // Skip an element that can't be drawn yet. - } -} - -// Draw every loaded GridLayer tile onto ctx, in z-index order, at its -// on-screen position relative to the map container. -function drawGridLayers(app, ctx, mapRect) { - const layers = []; - app.map.eachLayer((layer) => { - if (layer instanceof L.GridLayer && layer._tiles) { - layers.push(layer); - } - }); - layers.sort((a, b) => - ((a.options && a.options.zIndex) || 0) - - ((b.options && b.options.zIndex) || 0)); - - for (const layer of layers) { - const opacity = layerOpacity(layer); - if (opacity <= 0) { - continue; - } - ctx.globalAlpha = opacity; - for (const key of Object.keys(layer._tiles)) { - const t = layer._tiles[key]; - if (!t || !t.current) { - continue; - } - drawElementAt(ctx, t.el, mapRect); - } - } - ctx.globalAlpha = 1; -} - -// Rasterize the SVG overlay panes (rulers, selection outline, labels) on top. -// Async: each SVG is drawn through an data URL. -function drawSvgOverlays(app, ctx, mapRect) { - const svgs = app.map.getContainer().querySelectorAll('.leaflet-pane svg'); - const jobs = []; - svgs.forEach((svg) => { - const r = svg.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) { - return; - } - const clone = svg.cloneNode(true); - clone.setAttribute('width', r.width); - clone.setAttribute('height', r.height); - const xml = new XMLSerializer().serializeToString(clone); - const url = 'data:image/svg+xml;charset=utf-8,' - + encodeURIComponent(xml); - jobs.push(new Promise((resolve) => { - const img = new Image(); - img.onload = () => { - try { - ctx.drawImage(img, r.left - mapRect.left, - r.top - mapRect.top, r.width, r.height); - } catch (err) { /* ignore */ } - resolve(); - }; - img.onerror = () => resolve(); - img.src = url; - })); - }); - return Promise.all(jobs); -} - -// Rasterize the HTML marker labels — the ruler distance readouts, which are -// L.divIcon
s in a marker pane rather than SVG, so drawSvgOverlays cannot -// see them. Without this the capture keeps a ruler's line and ticks but drops -// the measurement the ruler exists to show. +// Rasterize the ruler distance labels, which are DOM markers over the canvas. // // Painted directly onto the canvas rather than serialized through an -// data URL like the SVG panes: a detached document does not inherit the app's -// stylesheet, so a foreignObject copy of the label would come out unstyled -// (no background, default font). Reading the computed style and drawing the -// box and text keeps it looking like what is on screen. +// data URL: a detached document does not inherit the app's stylesheet, so a +// foreignObject copy of the label would come out unstyled (no background, +// default font). Reading the computed style and drawing the box and text +// keeps it looking like what is on screen. function drawHtmlLabels(app, ctx, mapRect) { - const labels = app.map.getContainer() - .querySelectorAll('.leaflet-pane .ruler-label'); + const labels = app.view.getContainer() + .querySelectorAll('.or-view-markers .ruler-label'); labels.forEach((el) => { const r = el.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) { @@ -167,75 +69,8 @@ function drawHtmlLabels(app, ctx, mapRect) { }); } -// Count tiles that haven't finished loading across every GridLayer (base, -// overlay/highlights, heatmap, ...): a layer still marked _loading, or a -// current tile whose hasn't decoded yet. Zero => the scene is painted. -function tilesPending(app) { - let pending = 0; - app.map.eachLayer((layer) => { - if (!(layer instanceof L.GridLayer) || !layer._tiles) { - return; - } - if (layer._loading) { - pending++; - } - for (const key of Object.keys(layer._tiles)) { - const t = layer._tiles[key]; - const el = t && t.el; - if (t && t.current && el && el.tagName === 'IMG' - && (!el.complete || !el.naturalWidth)) { - pending++; - } - } - }); - return pending; -} - -// Resolve once all layers' tiles have settled (stable across a couple of polls) -// or a timeout elapses. Used after a fit so the capture waits for the newly -// requested tiles (base + overlay + heatmap) to arrive. -function whenTilesSettled(app, timeoutMs = 6000, intervalMs = 32) { - return new Promise((resolve) => { - const deadline = Date.now() + timeoutMs; - let stable = 0; - const check = () => { - if (tilesPending(app) === 0) { - if (++stable >= 2) { - resolve(); - return; - } - } else { - stable = 0; - } - if (Date.now() >= deadline) { - resolve(); - return; - } - setTimeout(check, intervalMs); - }; - setTimeout(check, intervalMs); - }); -} - -// Draw single-image overlays (e.g. the timing-path L.ImageOverlay) at their -// on-screen position, so they land in the capture like the tile layers. -function drawImageOverlays(app, ctx, mapRect) { - app.map.eachLayer((layer) => { - if (!(layer instanceof L.ImageOverlay)) { - return; - } - const opacity = layerOpacity(layer); - if (opacity <= 0) { - return; - } - ctx.globalAlpha = opacity; - drawElementAt(ctx, layer._image, mapRect); - ctx.globalAlpha = 1; - }); -} - async function renderToBlob(app) { - const container = app.map.getContainer(); + const container = app.view.getContainer(); const mapRect = container.getBoundingClientRect(); const w = Math.max(1, Math.round(mapRect.width)); const h = Math.max(1, Math.round(mapRect.height)); @@ -250,36 +85,43 @@ async function renderToBlob(app) { ctx.fillStyle = (bg && bg !== 'transparent' && bg !== 'rgba(0, 0, 0, 0)') ? bg : '#000'; ctx.fillRect(0, 0, w, h); - drawGridLayers(app, ctx, mapRect); - drawImageOverlays(app, ctx, mapRect); - await drawSvgOverlays(app, ctx, mapRect); + const scene = await app.view.captureCanvas(); + if (scene) { + const r = scene.rect; + try { + ctx.drawImage(scene.image, r.left - mapRect.left, + r.top - mapRect.top, r.width, r.height); + } catch (err) { + // A canvas that cannot be drawn yet leaves the background only. + } + } // Last, so the labels sit above the ruler lines they annotate. drawHtmlLabels(app, ctx, mapRect); return new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); } -// Public entry point. entire=false composites the current viewport; +// Public entry point. entire=false captures the current viewport; // entire=true fits the whole design first, waits for the newly requested tiles // to settle, captures, then restores the previous view. Both are WYSIWYG: // base layers + heatmap + highlights/selection + rulers, exactly as shown. export async function captureLayout(app, { entire = false } = {}) { - if (!app.map) { + if (!app.view) { return; } // Entire needs whole-design bounds; without them the capture would just be // the current viewport, so save it (honestly) as the visible layout. - if (!entire || !app.fitBounds) { + if (!entire || !app.fitRect) { downloadBlob(await renderToBlob(app), 'layout_visible.png'); return; } - const prevCenter = app.map.getCenter(); - const prevZoom = app.map.getZoom(); + const prevCenter = app.view.getCenter(); + const prevZoom = app.view.getZoom(); try { - app.map.fitBounds(app.fitBounds, { animate: false }); - await whenTilesSettled(app); + app.view.fitWorldRect(app.fitRect, { animate: false }); + await app.view.whenTilesSettled(); downloadBlob(await renderToBlob(app), 'layout_entire.png'); } finally { - app.map.setView(prevCenter, prevZoom, { animate: false }); + app.view.setView(prevCenter, prevZoom, { animate: false }); } } diff --git a/openroad/web/src/clusters-widget.js b/openroad/web/src/clusters-widget.js index 57a1e423d39..d0ef7a751e6 100644 --- a/openroad/web/src/clusters-widget.js +++ b/openroad/web/src/clusters-widget.js @@ -295,9 +295,8 @@ export class ClustersWidget { console.error('set_group_colors failed:', err); return; } - // Only the cluster overlay reads these colors, so refresh that layer - // instead of every mounted one — a full redraw re-requests every metal - // layer's grid for a color they ignore. + // Only the cluster overlay reads these colors, so refresh the slot + // that draws it instead of every slot. if (this._app.clustersLayer) { this._app.clustersLayer.refreshTiles(); } else { diff --git a/openroad/web/src/context-menu.js b/openroad/web/src/context-menu.js index 130d1e94dde..e4fb4b4ceee 100644 --- a/openroad/web/src/context-menu.js +++ b/openroad/web/src/context-menu.js @@ -73,9 +73,9 @@ export class ContextMenu { } }); - // Hide the menu when the map moves. - if (this._app.map) { - this._app.map.on('movestart', () => this.hide()); + // Hide the menu when the view moves. + if (this._app.view) { + this._app.view.on('movestart', () => this.hide()); } } @@ -134,9 +134,9 @@ export class ContextMenu { const maxLeft = window.innerWidth - rect.width - margin; const maxTop = window.innerHeight - rect.height - margin; const left = Math.max(margin, - Math.min(e.originalEvent.clientX, maxLeft)); + Math.min(e.clientX, maxLeft)); const top = Math.max(margin, - Math.min(e.originalEvent.clientY, maxTop)); + Math.min(e.clientY, maxTop)); this._el.style.left = left + 'px'; this._el.style.top = top + 'px'; } @@ -235,22 +235,26 @@ export class ContextMenu { } // Bring the client back in step with the selection/highlight state the - // action just changed server-side. - // - // redrawAllLayers is not enough on its own: focus nets and route guides - // feed the BASE tiles, so clearing them needs the full redraw, but that - // path calls the bare overlay refresh. The Selection Highlight panel and - // the Inspector are driven by app.refreshOverlay / app.refreshInspector — - // the same hooks the menu bar's "Clear Highlights" and the panel's own - // toolbar use — so without them the panel keeps listing objects the - // server no longer has selected or highlighted. + // action just changed server-side. Focus nets feed the base tiles and + // need the full redraw; the rest, route guides included, is overlay only. + // The Selection Highlight panel and the Inspector follow + // app.refreshOverlay / app.refreshInspector, the hooks the menu bar's + // "Clear Highlights" uses too. _syncAfterAction(action) { const app = this._app; - // Base tiles only carry focus nets and route guides; every other - // action lives entirely in the overlay. - if ((action === 'clear_focus_nets' || action === 'clear_route_guides' - || action === 'clear_all') - && typeof app.redrawAllLayers === 'function') { + // The Inspector's Focus and Route Guides buttons read these + // client-side copies of what the server just cleared. + if (action === 'clear_focus_nets' || action === 'clear_all') { + app.focusNets?.clear(); + } + if (action === 'clear_route_guides' || action === 'clear_all') { + app.routeGuideNets?.clear(); + } + // Of these, only focus nets reach the base tiles; route guides and + // every other action live entirely in the overlay. + const redrawn = (action === 'clear_focus_nets' || action === 'clear_all') + && typeof app.redrawAllLayers === 'function'; + if (redrawn) { app.redrawAllLayers(); } // The selection itself is gone: reset the client-side pieces of it @@ -259,18 +263,18 @@ export class ContextMenu { if (action === 'clear_selections' || action === 'clear_all') { app.updateInspector?.(null); app.stopSelectionAnimation?.(); - if (app.highlightRect && app.map) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } - app.lastSelectionBounds = null; + app.clearSelectionOutline?.(); } else { // Selection count/index and the highlight-group badge changed. app.refreshInspector?.(); } - // Refreshes the overlay tiles AND schedules the Selection Highlight - // panel refresh; must run last so it sees the cleanup above. - app.refreshOverlay?.(); + // Last, so it sees the cleanup above: the overlay hook also refreshes + // the Selection Highlight panel, and a full redraw already did the tiles. + if (redrawn) { + app.selectionBrowser?.scheduleRefresh(); + } else { + app.refreshOverlay?.(); + } } } diff --git a/openroad/web/src/coordinates.js b/openroad/web/src/coordinates.js index 61fdcc6b927..f702601d4e0 100644 --- a/openroad/web/src/coordinates.js +++ b/openroad/web/src/coordinates.js @@ -1,32 +1,27 @@ // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2026, The OpenROAD Authors -// DBU <-> Leaflet coordinate conversion. -// -// The tile renderer uses two Y-flips (tile index + pixel row), so the -// correct mapping is: -// lat = (dbu_y - originY - maxDXDY) * scale -// lng = (dbu_x - originX) * scale +// DBU <-> layout-view world coordinates: world = (dbu - origin) * scale, y up, +// so the tile grid is the square [0, tileSize] on both axes. // // `scale` = tileSize / max(designWidth, designHeight) (pixels-per-DBU) -// `maxDXDY` = max(designWidth, designHeight) in DBU // `originX` = bounds.xMin() in DBU (tile grid origin) // `originY` = bounds.yMin() in DBU (tile grid origin) -export function dbuToLatLng(dbuX, dbuY, scale, maxDXDY, originX = 0, originY = 0) { - return [(dbuY - originY - maxDXDY) * scale, (dbuX - originX) * scale]; -} - -export function dbuRectToBounds(x1, y1, x2, y2, scale, maxDXDY, originX = 0, originY = 0) { - return [ - [(y1 - originY - maxDXDY) * scale, (x1 - originX) * scale], - [(y2 - originY - maxDXDY) * scale, (x2 - originX) * scale], - ]; +export function dbuToWorld(dbuX, dbuY, scale, originX = 0, originY = 0) { + return [(dbuX - originX) * scale, (dbuY - originY) * scale]; } -export function latLngToDbu(lat, lng, scale, maxDXDY, originX = 0, originY = 0) { +export function worldToDbu(wx, wy, scale, originX = 0, originY = 0) { return { - dbuX: Math.round(originX + lng / scale), - dbuY: Math.round(originY + maxDXDY + lat / scale), + dbuX: Math.round(originX + wx / scale), + dbuY: Math.round(originY + wy / scale), }; } + +// World rect [minX, minY, maxX, maxY] of a DBU rect given by two corners. +export function dbuRectToWorldRect(x1, y1, x2, y2, scale, originX = 0, originY = 0) { + const [ax, ay] = dbuToWorld(x1, y1, scale, originX, originY); + const [bx, by] = dbuToWorld(x2, y2, scale, originX, originY); + return [Math.min(ax, bx), Math.min(ay, by), Math.max(ax, bx), Math.max(ay, by)]; +} diff --git a/openroad/web/src/deck-global.js b/openroad/web/src/deck-global.js new file mode 100644 index 00000000000..988ecea8fc7 --- /dev/null +++ b/openroad/web/src/deck-global.js @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// The parts of deck.gl the layout view draws with, handed over as window.deck; +// the entries import this module first. layout-view.js reads the global, so +// its unit tests can hand it a stand-in instead. + +import { Deck, OrthographicView } from '@deck.gl/core'; +import { PathStyleExtension } from '@deck.gl/extensions'; +import { BitmapLayer, PathLayer, ScatterplotLayer, SolidPolygonLayer } + from '@deck.gl/layers'; + +// Spread: @deck.gl/core put its version and logger on the global already. +window.deck = { + ...window.deck, + BitmapLayer, + Deck, + OrthographicView, + PathLayer, + PathStyleExtension, + ScatterplotLayer, + SolidPolygonLayer, +}; diff --git a/openroad/web/src/device-pixels.js b/openroad/web/src/device-pixels.js deleted file mode 100644 index 7ebe546b845..00000000000 --- a/openroad/web/src/device-pixels.js +++ /dev/null @@ -1,185 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// Copyright (c) 2026, The OpenROAD Authors - -// Keep the tile grid on whole device pixels. -// -// Leaflet lays everything out in whole CSS pixels: Map._getNewPixelOrigin and -// GridLayer._setZoomTransform both .round() their offsets. A whole CSS pixel is -// NOT a whole device pixel unless devicePixelRatio is an integer — at dpr 1.25 -// an odd CSS offset lands on a quarter of a pixel — so a tile's box gets its -// edges resampled into the device grid. Two neighbouring tiles then each paint -// partial coverage into the same device pixel column, and src-over compositing -// of two partial alphas does not add up to one: the pane background shows -// through. That is the dark hairline along every tile boundary. It explains why -// the seams come and go as you pan (at dpr 1.25 one offset in four is already -// exact) and why they reproduce on both the merged-canvas and the legacy -// path — this is the browser's layout, not anything either path draws. -// -// Overlapping the tiles instead would be worse: routing-layer pixels are -// semi-transparent, so an overlapping strip blends twice and a dark seam becomes -// a bright one. They have to abut exactly, which is what landing on the grid -// gives. -// -// Why this measures the DOM rather than patching Leaflet: leaflet-src.js keeps -// setTransform/setPosition as closure-local functions and only publishes -// references to them on L.DomUtil (`exports.DomUtil = DomUtil`, at the end of -// the bundle). GridLayer._setZoomTransform and the map's pan call the closure -// originals, so assigning to L.DomUtil.setTransform patches nothing that -// Leaflet itself goes through. The placement can be corrected, not intercepted. -// -// So: read where Leaflet actually put the tile container — .leaflet-tile-container, -// the element it transforms — and put the compensating offset on that container's -// parent, .leaflet-layer, which Leaflet only ever writes a z-index to. Neither -// side overwrites the other, and the correction survives every update Leaflet -// makes to the child. -// -// This removes the shared PHASE. The other half is the PITCH: tiles must also be -// a whole number of device pixels apart, or only every 1/frac-th boundary can be -// on the grid whatever the phase is — see TILE_SIZE_CSS in tile-request.js, -// which is why the tile size is 240 rather than 256. - -import { nativeDpr } from './tile-request.js'; - -// The element Leaflet positions, and the parent it leaves alone. -const TILE_CONTAINER = '.leaflet-tile-container'; -// What actually has to land on the grid. -const TILE = '.leaflet-tile'; - -// CSS pixels to subtract from `css_pos` to land it on a device pixel. Signed, -// and always less than half a device pixel. -export function deviceResidualCss(css_pos, dpr) { - if (!Number.isFinite(css_pos) || !(dpr > 0)) { - return 0; - } - const device = css_pos * dpr; - return (device - Math.round(device)) / dpr; -} - -// Correct one tile container by offsetting its parent. -// -// Measured on a TILE, not on the container. Leaflet's _getTilePos puts a tile at -// `coords*tileSize - level.origin`, and level.origin is an arbitrary rounded -// integer rather than a multiple of the tile size — so the container can sit -// exactly on the device grid while every tile inside it is a quarter pixel off. -// A tile's rect carries the whole chain: map pane, container transform, this -// correction, and that origin term. -// -// One tile per container is enough: tiles differ from each other by whole -// multiples of the tile size, and that size is chosen to be a whole number of -// device pixels at every real ratio (TILE_SIZE_CSS in tile-request.js). -// -// The measured rect already includes whatever correction is on the parent now, -// so the new correction is the old one minus what is still left over, with any -// whole device pixels dropped. That converges in one step. The dropping is what -// keeps it from drifting: a whole device pixel is never part of a correction -- -// the grid is the same one pixel further on -- but once one got in, every later -// step found the tiles on the grid and left it there, so a layer could wander -// off its neighbours by several pixels and stay. -// -// `rectOf` is injected so this is testable without a layout engine, and -// defaults to the real measurement for every other caller. -export function snapContainerToDeviceGrid(container, dpr, - rectOf = defaultRectOf) { - const holder = container && container.parentElement; - if (!holder) { - return null; - } - // An empty container has no seams to fix, and nothing to measure: a level - // gets its tiles during the same move/zoom that creates it, so the next - // event corrects it. - const tile = typeof container.querySelector === 'function' - ? container.querySelector(TILE) - : null; - if (!tile) { - return null; - } - const rect = rectOf(tile); - const dx = withinOneDevicePixel( - (holder._orSnapDx || 0) - deviceResidualCss(rect.left, dpr), dpr); - const dy = withinOneDevicePixel( - (holder._orSnapDy || 0) - deviceResidualCss(rect.top, dpr), dpr); - holder._orSnapDx = dx; - holder._orSnapDy = dy; - // Written on the PARENT: the container's own transform belongs to Leaflet, - // which rewrites it on every pan and zoom. - holder.style.transform - = (dx || dy) ? `translate3d(${dx}px, ${dy}px, 0)` : ''; - return { dx, dy }; -} - -// Correct every tile container under the map's tile pane. -// -// Rects are read for all of them before any style is written: interleaving -// reads and writes would force a layout flush per container, and this runs on -// every frame of a drag. -export function snapTileContainers(map, dpr, rectOf = defaultRectOf) { - // At an integer ratio a whole CSS pixel IS a whole device pixel, so every - // residual is zero and there is nothing to correct — skip the measuring - // entirely rather than pay for it on every move. - if (!map || typeof map.getPane !== 'function' || !(dpr > 0) - || Number.isInteger(dpr)) { - return 0; - } - const pane = map.getPane('tilePane'); - if (!pane || typeof pane.querySelectorAll !== 'function') { - return 0; - } - let snapped = 0; - // Read every rect before writing any style: interleaving them forces a - // layout flush per container, and this runs on every frame of a drag. - // - // Only the level at rest: a layer keeps one container per zoom level that - // Leaflet has not pruned yet, and they all share the .leaflet-layer the - // correction goes on. Snapping each of them into it made the levels take - // turns, leaving the one on screen off the grid on every other pass. - const measured = [...pane.querySelectorAll(TILE_CONTAINER)] - .filter(isLevelAtRest) - .map((container) => { - const tile = container.querySelector(TILE); - return { container, rect: tile ? rectOf(tile) : null }; - }); - for (const { container, rect } of measured) { - if (rect && snapContainerToDeviceGrid(container, dpr, () => rect)) { - snapped++; - } - } - return snapped; -} - -function defaultRectOf(el) { - return el.getBoundingClientRect(); -} - -// `css` less the whole device pixels in it, leaving less than half a device -// pixel either way. A value already that small comes back bit for bit, so a -// correction that has converged is written out unchanged. -function withinOneDevicePixel(css, dpr) { - return css - Math.round(css * dpr) / dpr; -} - -// Whether `container` is the zoom level Leaflet shows at rest. Leaflet writes -// `translate3d(...) scale(s)` on every level, and s is 1 only for the current -// one; the levels it is zooming away from, and every level mid-animation, are -// scaled. A container with no scale written yet counts as at rest. -function isLevelAtRest(container) { - const transform = (container.style && container.style.transform) || ''; - const scale = /scale\(([^)]*)\)/.exec(transform); - return !scale || Number(scale[1]) === 1; -} - -// Re-snap whenever Leaflet has moved the tiles. -// -// `zoomend` rather than `zoom`: during the zoom animation the container carries -// a CSS transition and a scale, and correcting mid-flight would fight it for no -// benefit — the frames are in motion and a quarter pixel is invisible there. -const SNAP_EVENTS = 'move zoomend viewreset resize load'; - -export function installDeviceGridSnapping(map, dprOf = nativeDpr) { - if (!map || typeof map.on !== 'function') { - return false; - } - const snap = () => snapTileContainers(map, dprOf()); - map.on(SNAP_EVENTS, snap); - snap(); - return true; -} diff --git a/openroad/web/src/display-controls.js b/openroad/web/src/display-controls.js index e5116d61db2..eb87186a210 100644 --- a/openroad/web/src/display-controls.js +++ b/openroad/web/src/display-controls.js @@ -14,6 +14,9 @@ import { getCookie, setCookie, setBackgroundColor, resetBackgroundColor, import { isStaticMode, makeGroupHeader, attachGroupCollapse, beginSelection, isCurrentSelection, onSelectionReset, isValidHexColor } from './ui-utils.js'; +import { setItemVisible } from './tile-merge.js'; +import { createCompositeSource } from './tile-sources.js'; +import { DRAW_ORDER } from './layout-view.js'; // Compute a Set of layer indices around `center` within [0, count). // `lower` layers below and `upper` layers above are included. @@ -85,6 +88,10 @@ export function buildChipletFlatNodes(chipletData, savedHidden) { }); } +// The server's paint order puts the routing layers from here up +// (TileGenerator::saveImageLayerOrder); an overlay below it goes under them. +const kTechLayerZBase = 3; + // Fallback color used when the server didn't supply a layer color. const fallbackLayerPalette = [ [70, 130, 210], // moderate blue @@ -97,153 +104,129 @@ const fallbackLayerPalette = [ [180, 70, 150], // magenta ]; -import { - computeGroupCount, estimateTilesPerPane, measureViewport, - partitionIntoGroups, reserveForUnmergedPanes, setItemVisible, tileBytes, - DEFAULT_BUDGET_BYTES, UNMERGED_PANE_COUNT, -} from './tile-merge.js'; -import { buildMergedPanes } from './merged-tile-layer.js'; -import { tileSizeCss } from './tile-request.js'; - // Populate display controls with layer checkboxes and visibility tree. export function populateDisplayControls(app, visibility, selectability, - WebSocketTileLayer, techData, redrawAllLayers, - HeatMapTileLayer) { + createHeatMapSlot) { if (!app.displayControlsEl) return; app.displayControlsEl.innerHTML = ''; - app.allLayers = []; // Column header (visibility / selectability icons), mirroring the Qt GUI's // QHeaderView. Added first so it is the panel's sticky top row. app.displayControlsEl.appendChild(makeColumnHeader()); - // ─── Tile grouping ─────────────────────────────────────────────────── - // - // Two modes. Legacy: one Leaflet pane per tech layer per chiplet, which on - // a multi-die design is ~97 panes holding ~582 MB of decoded tile images — - // past the browser's ~458 MB ceiling, where it starts discarding decodes and - // the discarded regions paint white. Merged: - // the routing layers are composited into N canvas panes, N chosen from a - // memory budget, so the total is bounded no matter how many layers or - // chiplets the design has. + // ─── Tile slots ────────────────────────────────────────────────────── // - // Only the routing layers are merged. The pseudo layers (_instances, - // _pins, _modules and the Misc overlays below) stay as their own panes: - // there is a fixed handful of them, they carry no meaningful memory, and - // they have their own add/remove rules driven by the Shapes, Module-view - // and Misc toggles which are not worth folding into the draw list. - const mergedLayerClass = app.mergeTiles ? app.MergedTileLayer : null; - // Panes whose draw list changed during one tree update, refreshed once at - // the end rather than per layer — a group toggle walks every node, and - // refreshing per node would re-request the same pane dozens of times. - const dirtyPanes = new Set(); - - function flushDirtyPanes() { - for (const pane of dirtyPanes) { - pane.refreshTiles(); + // Two slots, the layout and the layers over the highlight overlay, each + // composited into one image per tile: every drawn tile costs CPU a frame. + app.allLayers = []; + app.baseSlot = null; + app.topSlot = null; + const dirtySlots = new Set(); + + function flushDirtySlots() { + for (const slot of dirtySlots) { + slot.refresh(); + } + dirtySlots.clear(); + } + + function markBaseDirty() { + if (app.baseSlot) { + dirtySlots.add(app.baseSlot); } - dirtyPanes.clear(); } - // A routing layer, as the tree sees it. In legacy mode this IS the Leaflet - // layer; in merged mode it is an adapter over one entry of a pane's draw - // list, exposing the same three things the tree uses. + // A routing layer: its entry in the base slot's draw list. // - // Routing layers are drawn at full pane opacity. The layer transparency is + // Routing layers are drawn at full opacity. The layer transparency is // already baked into the tile: the server paints layer shapes with the // palette alpha of 180/255 (tile_generator.cpp buildLayerColorMap), the same - // alpha displayControls.cpp gives the Qt GUI's brush. Dimming the pane on + // alpha displayControls.cpp gives the Qt GUI's brush. Dimming the layer on // top of that would apply the transparency a second time and render the // layout darker than the Qt GUI. // - // `row` names the Display Controls row ({ chiplet, rowId, rendererHost }): - // its tiles draw only its die, so two dies sharing a layer name show, hide - // and stack independently. - function makeRoutingLayer(name, zIndex, row) { - if (!mergedLayerClass) { - const layer = new WebSocketTileLayer(app.websocketManager, name, { - opacity: 1, - zIndex, - row, - }); - layer._orShow = () => layer.addTo(app.map); - layer._orHide = () => app.map.removeLayer(layer); - layer._orRefresh = () => layer.refreshTiles(); - return layer; + // `row` is the Display Controls row ({ chiplet, rowId, rendererHost }) and + // becomes the draw item, so its tiles draw only its die: two dies sharing + // a layer name show, hide and stack independently. + function makeRoutingLayer(name, row) { + return Object.assign(row, { layer: name, opacity: 1, visible: false }); + } + + // Only a real change dirties the slot: the tree's onChange re-asserts the + // state of every node, not just the one toggled. + function setRoutingVisible(item, visible) { + if (setItemVisible(item, visible)) { + markBaseDirty(); } - // The row object is the draw item, so the request reads it directly. - const item = Object.assign(row, { layer: name, opacity: 1, - visible: false }); - return { - _orItem: item, - _orPane: null, - // Repaints with the next flush, like a visibility change. - _orRefresh() { - if (this._orPane) { - dirtyPanes.add(this._orPane); - } - }, - refreshTiles() { - this._orRefresh(); - flushDirtyPanes(); - }, - // setItemVisible reports whether the state actually changed, and - // only a real change dirties the pane. The tree's onChange walks - // EVERY node and asserts the desired state on each, so dirtying - // unconditionally made one checkbox re-request every tile in every - // pane. - _orShow() { - if (setItemVisible(item, true)) { - this._orRefresh(); - } - }, - _orHide() { - if (setItemVisible(item, false)) { - this._orRefresh(); - } - }, - }; } - // `appProp` names the app. slot (null = anonymous); `gate` is the - // visibility flag the layer is switched by -- a flag name, or a `shown_by` - // list of flag groups (null = no toggle). - function addPseudoLayer(name, appProp, zIndex, gate) { - const layer = new WebSocketTileLayer(app.websocketManager, name, { - zIndex, - gate, - }); - layer.addTo(app.map); - if (appProp) app[appProp] = layer; - app.allLayers.push(layer); - return layer; + // One refresh per slot, however many of its layers ask in the same turn. + let flushQueued = false; + function refreshSlotOf(item) { + const slot = app.allLayers.find( + (s) => s.items && s.items.includes(item)); + if (!slot) { + return; + } + dirtySlots.add(slot); + if (!flushQueued) { + flushQueued = true; + queueMicrotask(() => { + flushQueued = false; + flushDirtySlots(); + }); + } } - // Pseudo layers stay mounted and are switched by their `gate` flag, which - // travels in the tile payload (see _gatedOff). Mounting per toggle made the - // map's layer set a second record of the flag, and the two drifted. + // A pseudo layer: a draw-list entry that stays in its slot and is switched + // by `gate`, a visibility flag name or a `shown_by` list of flag groups + // (null = no toggle), read on every request (tile-sources.js). `appProp` + // names the app. it is published as. + function pseudoItem(name, appProp, gate) { + const item = { + layer: name, opacity: 1, visible: true, gate, + refreshTiles() { refreshSlotOf(item); }, + }; + if (appProp) { + app[appProp] = item; + } + return item; + } - // Instance borders layer (always below routing layers; no toggle) - addPseudoLayer('_instances', null, 0, null); - // IO pin markers layer (between instances and routing layers) - addPseudoLayer('_pins', 'pinsLayer', 1, 'pins'); - // Module coloring overlay (Module view) - addPseudoLayer('_modules', 'modulesLayer', 2, 'module_view'); + // Under the routing layers: instance borders (no toggle), IO pins and + // module coloring. + const underItems = [ + pseudoItem('_instances', null, null), + pseudoItem('_pins', null, 'pins'), + pseudoItem('_modules', 'modulesLayer', 'module_view'), + ]; + // Cluster coloring goes above the routing layers and below the heat map. + const clustersItem + = pseudoItem('_clusters', 'clustersLayer', 'cluster_view'); // The self-painting overlays (access points, regions, grids, instance and - // pin names), as the server lists them: name, pane order and when each + // pin names), as the server lists them: name, paint order and when each // shows. It leaves out those the design gives nothing to draw, such as // regions in a design without any. `shown_by` is the gate itself, so the - // server's rule for when an overlay shows is read in one place. - app.overlayLayers = ((techData && techData.overlays) || []).map((def) => ({ + // server's rule for when an overlay shows is read in one place. Those the + // server orders below the routing layers (the manufacturing grid) go under + // them; the rest go over the highlight overlay and the heat map, in the + // GUI paint order. + const topItems = []; + const overlayLayers = (techData?.overlays || []).map((def) => ({ def, - layer: addPseudoLayer(def.name, null, def.z_index, def.shown_by), + layer: pseudoItem(def.name, null, def.shown_by), + under: def.z_index < kTechLayerZBase, })); + for (const { layer, under } of [...overlayLayers].sort( + (a, b) => a.def.z_index - b.def.z_index)) { + (under ? underItems : topItems).push(layer); + } // --- Layers group (using CheckboxTreeModel) --- - // Create Leaflet layers and build a model spec. - const leafletLayers = []; // index → WebSocketTileLayer + // Routing layers, in slot (z) order, and the model spec. + const routingLayers = []; // index → draw-list entry const layerIds = []; // index → model node id // Forward declaration so the layerModel callback can mirror chiplet @@ -313,44 +296,37 @@ export function populateDisplayControls(app, visibility, selectability, return true; } - // One routing row: its pane or draw item, shown unless the session hid - // it, and its tree node with `data` added to the common fields. - function makeLayerRow(name, id, zIndex, chiplet, data) { + // One routing row: its draw item, shown unless the session hid it, and its + // tree node with `data` added to the common fields. + function makeLayerRow(name, id, chiplet, data) { adoptNamePattern(id, name); const visible = !savedHiddenLayers.has(id); const row = { chiplet, rowId: id, rendererHost: claimRendererHost(name, visible) }; - const layer = makeRoutingLayer(name, zIndex, row); - layer._nodeId = id; - + const layer = makeRoutingLayer(name, row); if (visible) { - layer._orShow(); + setRoutingVisible(layer, true); app.visibleLayers.add(id); app.visibleLayerNames.add(name); } - // In merged mode the panes go into allLayers instead, once the - // grouping is known — a draw-list entry is not something - // redrawAllLayers() can refresh. - if (!mergedLayerClass) { - app.allLayers.push(layer); - } - leafletLayers.push(layer); + routingLayers.push(layer); layerIds.push(id); return { id, data: { name, layer, row, nodeId: id, ...data }, checked: visible }; } - // Apply a fill pattern to one row and re-render just that row's tiles. - function setLayerPattern(rowId, layer, value) { + // Apply a fill pattern to one row and refresh the slot that draws it. + function setLayerPattern(rowId, value) { if (value === 1) { delete app.layerPatterns[rowId]; } else { app.layerPatterns[rowId] = value; } persistLayerPatterns(); - if (layer && typeof layer.refreshTiles === 'function') { - layer.refreshTiles(); - } + // or_layer_patterns is part of the saved display state. + app.syncDisplayState?.(); + markBaseDirty(); + flushDirtySlots(); } // Fill-pattern choices for the layer context menu (values match the @@ -368,11 +344,6 @@ export function populateDisplayControls(app, visibility, selectability, // the tech's own layer order, so a flipped chiplet keeps the colors an // upright one would get. let nextLayerSlot = 0; - // Draw order, which is what a flip reverses: the stack of a face-down - // chiplet reaches the viewer backside-first. Kept apart from the palette - // slot so reversing the stack cannot recolor it. Starts at 3, above the - // _instances/_pins/_modules pseudo-layers. - let nextZIndex = 3; // `ownerPath` is the chiplet whose dbTech owns the layers rendered at this // level. Category nodes (Backside/Implant/Other) are pure UI folders with @@ -437,8 +408,7 @@ export function populateDisplayControls(app, visibility, selectability, // node IS that chiplet" and drives the Chiplets panel sync, // which must only ever see group nodes. children.push(makeLayerRow( - layerObj.name || layerObj, techRows[idx], nextZIndex++, - chipletPath, + layerObj.name || layerObj, techRows[idx], chipletPath, { color: layerObj.color, colorIndex: paletteBase + idx, techRows, techIndex: idx, ownerChipletPath: chipletPath })); @@ -449,8 +419,7 @@ export function populateDisplayControls(app, visibility, selectability, // node's own layers. Flipped: this die's own content turns over, so // its layers come first and the category folders land on top of them. // Child chiplets keep the backend's world-z order either way. The - // visit order IS the draw order — nextZIndex and leafletLayers (the - // merged-pane draw list) both advance with it. + // visit order IS the draw order: the base slot draws its items in it. emitNodes(childChiplets, /*reversed=*/false); if (flipped) { emitLayers(); @@ -492,7 +461,7 @@ export function populateDisplayControls(app, visibility, selectability, layerSpec = { id: 'layers_parent', children: techData.layers.map((name, index) => makeLayerRow( - name, techRows[index], index + 3, undefined, + name, techRows[index], undefined, { colorIndex: index, techRows, techIndex: index })), }; } @@ -505,130 +474,19 @@ export function populateDisplayControls(app, visibility, selectability, persistLayerPatterns(); } - // Cluster coloring goes ABOVE the routing panes, which occupy zIndex - // 3..(row count + 2), and below the heat map. Counted off leafletLayers, - // not techData.layers: the latter is deduplicated by name across techs, - // while there is one row per (chiplet, layer). - addPseudoLayer('_clusters', 'clustersLayer', leafletLayers.length + 5, - 'cluster_view'); - - // ─── Build the merged panes ────────────────────────────────────────── - // - // leafletLayers is in slot order, which IS the z-order, so it can be - // partitioned directly. Runs must be contiguous: each group becomes one - // image, and interleaved groups have no stacking that reproduces the - // original (see partitionIntoGroups). - if (mergedLayerClass && leafletLayers.length > 0) { - const items = leafletLayers.map(l => l._orItem); - const budget = app.tileBudgetBytes || DEFAULT_BUDGET_BYTES; - - // How many groups fit right now. measureViewport falls back to the - // window when the container has not been laid out yet: a 0x0 container - // yields 1 tile per pane, which makes the budget look big enough for - // one pane per layer and silently disables the merging entirely. - function wantedGroupCount() { - const { width, height } = measureViewport(app.map.getContainer()); - // Both from the size the layers actually use: the tile count and - // the bytes per tile move in opposite directions with it, and - // reading it on one side only would leave the product wrong. - const tile = tileSizeCss(); - const tilesPerPane = estimateTilesPerPane(width, height, tile); - const perTile = tileBytes(tile, app.tileDpr ? app.tileDpr() : 1); - // The panes that are NOT merged still hold full tile grids, and - // they are not free: at dpr 3 each costs ~54 MB, so the four of - // them would put the real total over the ceiling while the budget - // reported it as fitting. Charge them first. - const count = app.mergeGroupCount || computeGroupCount({ - budgetBytes: reserveForUnmergedPanes(budget, tilesPerPane, - perTile), - tilesPerPane, - bytesPerTile: perTile, - paneCount: items.length, - }); - return { count, tilesPerPane, perTile }; - } - - function describe(paneCount, tilesPerPane, perTile) { - // estimatedMB counts the unmerged panes too, so the reported figure - // is the whole viewer's tile memory rather than just the part this - // grouping controls. - const total = (paneCount + UNMERGED_PANE_COUNT) * tilesPerPane - * perTile; - return { - layers: items.length, - groups: paneCount, - tilesPerPane, - unmergedPanes: UNMERGED_PANE_COUNT, - budgetMB: Math.round(budget / (1024 * 1024)), - estimatedMB: Math.round(total / (1024 * 1024)), - }; - } - - // Hand each group to a pane and point every tree entry at the pane that - // owns its draw item. - function assign(panes, groups) { - let at = 0; - groups.forEach((group, gi) => { - for (let i = 0; i < group.length; i++) { - leafletLayers[at++]._orPane = panes[gi]; - } - }); - } - - const initial = wantedGroupCount(); - const groups = partitionIntoGroups(items, initial.count); - // zIndex 3 upwards, matching the slots the per-layer panes used, so the - // routing stack still sits above _instances/_pins/_modules. - const panes = buildMergedPanes(mergedLayerClass, app.websocketManager, - groups, app.map, 3); - assign(panes, groups); - // These are what redrawAllLayers() refreshes — the design-changed push, - // pattern changes and visibility changes all arrive through it. - app.allLayers.push(...panes); - app.mergedPanes = panes; - app.mergeStats - = describe(panes.length, initial.tilesPerPane, initial.perTile); - console.log('[tiles] merged %d layers into %d panes ' - + '(~%d MB of %d MB budget, %d tiles/pane)', - app.mergeStats.layers, app.mergeStats.groups, - app.mergeStats.estimatedMB, app.mergeStats.budgetMB, - initial.tilesPerPane); - - // A pane holds a full grid of tiles, so enlarging the window raises the - // per-pane cost and a grouping that fitted the budget at startup no - // longer does — the same failure, arriving later. Recompute on resize. - // - // Shrink only. Growing N back when the window shrinks would churn - // panes on every drag of a splitter for no safety benefit, and leaves - // the merge coarser than strictly necessary, which is the harmless - // direction. A layer toggle then re-merges a slightly larger group. - app.map.on('resize', () => { - const want = wantedGroupCount(); - if (want.count >= app.mergedPanes.length) { - return; - } - const regrouped = partitionIntoGroups(items, want.count); - // Reuse the surviving panes and drop the surplus, so z-order and - // pane identity stay stable for the ones that remain. - const keep = app.mergedPanes.slice(0, regrouped.length); - for (const pane of app.mergedPanes.slice(regrouped.length)) { - app.map.removeLayer(pane); - const at = app.allLayers.indexOf(pane); - if (at >= 0) { - app.allLayers.splice(at, 1); - } - } - app.mergedPanes = keep; - assign(keep, regrouped); - keep.forEach((pane, i) => pane.setItems(regrouped[i])); - app.mergeStats - = describe(keep.length, want.tilesPerPane, want.perTile); - console.log('[tiles] window grew — regrouped %d layers into %d ' - + 'panes (~%d MB of %d MB budget, %d tiles/pane)', - app.mergeStats.layers, app.mergeStats.groups, - app.mergeStats.estimatedMB, app.mergeStats.budgetMB, - want.tilesPerPane); + // ─── The slots ─────────────────────────────────────────────────────── + function compositeSlot(id, order, items) { + const slot = app.view.addTileSlot(id, { + order, + source: createCompositeSource({ + wm: app.websocketManager, + ctx: app.tileCtx, + getItems: () => items, + isDoubleBuffer: () => app.doubleBuffer, + }), }); + slot.items = items; // the draw list, bottom-most first + return slot; } // Parallel selectability model with the same node ids as layerSpec so @@ -679,20 +537,25 @@ export function populateDisplayControls(app, visibility, selectability, const layerModel = new CheckboxTreeModel(() => { // Single pass over the tree: rebuild visibleLayerNames in place - // (the WebSocketTileLayer closure captured this Set by reference - // at startup, so we mutate rather than reassign), sync DOM and - // Leaflet, collect the cookie payload and accumulate any chiplet + // (app.tileCtx captured this Set by reference at startup, so we + // mutate rather than reassign), sync DOM and the draw lists, collect + // the cookie payload and accumulate any chiplet // toggles that need to mirror into the Chiplets panel. The // rebuild-from-scratch pattern avoids incrementally dropping a // layer name still owned by a checked sibling in multi-tech // designs. + // Route guides draw only on the layers shown, so with some on screen a + // change of names redraws the overlay. + const guides = app.routeGuideNets?.size > 0 + || (visibility.focused_nets_guides && app.focusNets?.size > 0); + const namesBefore = guides ? new Set(app.visibleLayerNames) : null; app.visibleLayerNames.clear(); const allLayerIds = []; // Two-tier chiplet propagation: stateUpdates carries every // tri-state change for the UI checkboxes; visibilityChangedAny // tracks whether any toggle also moved the chiplet in or out // of visibleChiplets. Splitting them lets us skip the - // chipletModel.onChange path (which redraws every Leaflet tile) + // chipletModel.onChange path (which redraws every tile) // when the visible set is unchanged. const stateUpdates = {}; let stateChangedAny = false; @@ -712,26 +575,19 @@ export function populateDisplayControls(app, visibility, selectability, if (node.data && node.data.layer) { const id = node.data.nodeId || node.data.name; allLayerIds.push(id); + setRoutingVisible(node.data.layer, node.checked); rows.push({ path: node.data.ownerChipletPath, name: node.data.name, on: node.checked }); if (node.checked) { - node.data.layer._orShow(); app.visibleLayers.add(id); app.visibleLayerNames.add(node.data.name); } else { - node.data.layer._orHide(); app.visibleLayers.delete(id); } - // A shown row that gains or loses the host role repaints - // while the renderers draw. - const { row } = node.data; - const host = claimRendererHost(node.data.name, node.checked); - if (row.rendererHost !== host) { - row.rendererHost = host; - if (node.checked && visibility.debug_renderers) { - node.data.layer._orRefresh(); - } - } + // The host only moves when a row of its name is shown or + // hidden, which already repaints the slot. + node.data.row.rendererHost + = claimRendererHost(node.data.name, node.checked); } if (trackChiplets && node.data && node.data.chipletPath) { const path = node.data.chipletPath; @@ -758,23 +614,32 @@ export function populateDisplayControls(app, visibility, selectability, }); app.chipletHiddenLayers = chipletLayerExceptions(rows, app.visibleLayerNames); - // One refresh per affected merged pane, after the whole walk: a group - // toggle touches many nodes that share a pane. - flushDirtyPanes(); - // Visibility off ⇒ selectability disabled — refresh selectability DOM. - syncLayerSelDom(); - // Refresh pins layer so it filters by the updated visible_layers and - // per-die exceptions. - if (app.pinsLayer && app.map.hasLayer(app.pinsLayer)) { - app.pinsLayer.refreshTiles(); - } - // And the overlays that draw by them under the current visibility. - for (const { def, layer } of app.overlayLayers || []) { - if (anyGroupOn(def.layers_by, visibility) - && app.map.hasLayer(layer)) { - layer.refreshTiles(); + // One refresh per affected slot, after the whole walk: a group + // toggle touches many nodes that share a slot. Pins filter by + // visible_layers and the per-die exceptions, which only change when + // some routing entry flips, and so do the overlays that draw by them + // under the current visibility. + if (app.baseSlot && dirtySlots.has(app.baseSlot)) { + for (const { def, under } of overlayLayers) { + if (anyGroupOn(def.layers_by, visibility)) { + dirtySlots.add(under ? app.baseSlot : app.topSlot); + } } } + if (namesBefore && app.overlayLayer + && (namesBefore.size !== app.visibleLayerNames.size + || [...namesBefore].some((n) => !app.visibleLayerNames.has(n)))) { + dirtySlots.add(app.overlayLayer); + } + // A die leaving the visible chiplets: the chiplet mirror below redraws + // every slot. + if (visibilityChangedAny) { + dirtySlots.clear(); + } else { + flushDirtySlots(); + } + // Visibility off ⇒ selectability disabled — refresh selectability DOM. + syncLayerSelDom(); const hiddenNodes = allLayerIds.filter(n => !app.visibleLayers.has(n)); try { @@ -784,7 +649,7 @@ export function populateDisplayControls(app, visibility, selectability, // or_hidden_layers is part of the saved display state; the chiplet // mirror below only reaches the sync (via redrawAllLayers) when the // visible-chiplet set changes, so push explicitly (rAF-coalesced). - app.syncDisplayState(); + app.syncDisplayState?.(); // Mirror chiplet toggles into the Chiplets panel. Toggling // wrapper_1 in the Layers tree must also remove its path from @@ -795,7 +660,7 @@ export function populateDisplayControls(app, visibility, selectability, // partially-selected chiplet keeps its tri-state checkbox AND // stays in visibleChiplets. When only the tri-state changed // (without entering/leaving the visible set) we take the quiet - // path so chipletModel.onChange — which redraws every Leaflet + // path so chipletModel.onChange — which redraws every // tile — is skipped; we sync the DOM checkboxes by hand instead. if (visibilityChangedAny) { // Every visibility flip is also a tri-state change, so @@ -830,7 +695,7 @@ export function populateDisplayControls(app, visibility, selectability, // share a layer name don't fall into last-writer-wins (an unchecked // M1 leaf in one subtree would otherwise delete the name even when // another M1 leaf is still checked). Mutate in place — the - // WebSocketTileLayer closure captured this Set by reference. + // tile request context (app.tileCtx) captured this Set by reference. app.selectableLayers.clear(); const rows = []; // Row ids, so one die's row does not carry the same name elsewhere. @@ -857,7 +722,7 @@ export function populateDisplayControls(app, visibility, selectability, } catch (_) { /* ignore */ } // Selectability changes the rendering of nothing, so no redraw runs; // push the saved display state explicitly. - app.syncDisplayState(); + app.syncDisplayState?.(); }); layerSelModel.addFromSpec(layerSelSpec); app.chipletNonselectableLayers @@ -1078,8 +943,8 @@ export function populateDisplayControls(app, visibility, selectability, .map(i => rows[i])))); } - // Fill-pattern submenu: choosing one re-renders only this - // row's tiles and persists the choice. + // Fill-pattern submenu: choosing one re-renders the base + // slot's tiles and persists the choice. const sep = document.createElement('div'); sep.className = 'context-menu-separator'; sep.style.borderTop = '1px solid #555'; @@ -1090,8 +955,7 @@ export function populateDisplayControls(app, visibility, selectability, const marker = current === opt.value ? '● ' : ' '; addContextMenuItem( marker + 'Fill: ' + opt.label, - () => setLayerPattern(node.id, node.data.layer, - opt.value)); + () => setLayerPattern(node.id, opt.value)); } contextMenu.style.left = e.clientX + 'px'; @@ -1173,7 +1037,7 @@ export function populateDisplayControls(app, visibility, selectability, // chip, it does not toggle per-chiplet visibility. Backend sends // one entry per dbChip / dbChipInst node with a unique `path` // ("top", "top/soc_inst", "top/soc_inst/sub_ip", …). Toggling a - // node refreshes every Leaflet tile so the server's chiplet + // node refreshes every tile so the server's chiplet // filter (`visible_chiplets`) takes effect on the next render. const chipletData = (techData && Array.isArray(techData.chiplets)) ? techData.chiplets : []; @@ -1278,7 +1142,7 @@ export function populateDisplayControls(app, visibility, selectability, encodeURIComponent(JSON.stringify(writeMap))); } - // Refresh every Leaflet tile so the server applies the + // Refresh every tile so the server applies the // updated `visible_chiplets` filter on the next request. redrawAllLayers(); }); @@ -1287,7 +1151,7 @@ export function populateDisplayControls(app, visibility, selectability, // Sanity check (debug aid): the two trees are expected to // describe the same set of chiplet paths because they share // origin in tile_generator.cpp's serializeTechResponse. If - // that invariant ever breaks, mirrorStates / mirrorChipletToLayers + // that invariant ever breaks, mirrorStates / checkChiplet // would silently drop the orphan paths — surfacing a warning // here makes the drift visible without breaking anything. if (typeof console !== 'undefined' && console.warn) { @@ -1332,16 +1196,15 @@ export function populateDisplayControls(app, visibility, selectability, } }); - // Cascade a chiplet toggle down into the layerModel so the - // Layers panel checkboxes (and the Leaflet tiles, and the - // or_hidden_layers cookie) follow. cascadeQuiet skips the - // layerModel's onChange; we fire it ourselves so the standard - // sync path runs exactly once. No loop with the chipletModel - // mirror logic — the layerModel callback observes that the - // chipletModel state already matches and emits nothing back. - function mirrorChipletToLayers(chipletPath, checked) { - const ln = layerNodeByChipletPath.get(chipletPath); - if (!ln) return; + // A chiplet toggle goes through the Layers tree, whose onChange + // mirrors it back here and redraws once. A chiplet with no node + // there is checked directly. + function checkChiplet(id, chipletPath, checked) { + const ln = chipletPath && layerNodeByChipletPath.get(chipletPath); + if (!ln) { + chipletModel.check(id, checked); + return; + } layerModel.cascadeQuiet(ln.id, checked); layerModel.onChange(); } @@ -1408,11 +1271,8 @@ export function populateDisplayControls(app, visibility, selectability, rootNode.cb = parentCb; parentCb.addEventListener('change', (e) => { e.stopPropagation(); - chipletModel.check(rootId, parentCb.checked); - if (rootNode.data && rootNode.data.path) { - mirrorChipletToLayers(rootNode.data.path, - parentCb.checked); - } + checkChiplet(rootId, rootNode.data && rootNode.data.path, + parentCb.checked); }); chipletHeader.appendChild(parentCb); } @@ -1441,8 +1301,7 @@ export function populateDisplayControls(app, visibility, selectability, checkbox.indeterminate = node.indeterminate; node.cb = checkbox; checkbox.addEventListener('change', () => { - chipletModel.check(node.id, checkbox.checked); - mirrorChipletToLayers(c.path, checkbox.checked); + checkChiplet(node.id, c.path, checkbox.checked); }); label.appendChild(checkbox); label.appendChild(makeSelSpacer()); @@ -1461,7 +1320,7 @@ export function populateDisplayControls(app, visibility, selectability, app.displayControlsEl.appendChild(chipletGroup); } else { // Single-chip designs render every chiplet (i.e. only the top). - // Clearing keeps WebSocketTileLayer's serializer from sending an + // Clearing keeps the tile request builder from sending an // empty array and accidentally enabling the filter. app.visibleChiplets = null; } @@ -1471,8 +1330,7 @@ export function populateDisplayControls(app, visibility, selectability, // the Qt GUI's selectability column (see displayControls.cpp). // The Hierarchy view checkbox governs two flags, and which one it turns on // depends on the tab's source. Derive only: redrawAllLayers repaints the - // two overlay layers along with everything else (they are in allLayers), - // and this runs on every checkbox in the tree, not just that one. + // base slot, which draws both overlays. const applyHierarchyOverlay = () => { // Only when a flag actually moved: this runs for every checkbox in the // tree, and the panel work below walks the whole tree of the view it @@ -1616,6 +1474,15 @@ export function populateDisplayControls(app, visibility, selectability, // so the restored Hierarchy view checkbox needs its flags derived once here. applyHierarchyOverlay(); + // A new slot requests its tiles at once, so it comes after every saved + // state that shapes them. + app.baseSlot = compositeSlot( + 'base', DRAW_ORDER.base, + [...underItems, ...routingLayers, clustersItem]); + app.topSlot = compositeSlot('top', DRAW_ORDER.top, topItems); + // What redrawAllLayers() refreshes. + app.allLayers = [app.baseSlot, app.topSlot]; + // ─── Per-renderer display controls ────────────────────────────────────── // The rows Qt's DisplayControls builds from Renderer::getDisplayControls() // (registerRenderer): one top-level group per renderer group name, with @@ -1732,8 +1599,8 @@ export function populateDisplayControls(app, visibility, selectability, // Background color control (Qt GUI "Background" parity): a swatch that // opens the native color picker + a reset-to-theme link. The layout - // background is the CSS var --bg-map on the Leaflet container, so this - // is purely client-side (tiles are transparent). + // background is the CSS var --bg-map on the layout view, so this is + // purely client-side (tiles are transparent). const bgRow = document.createElement('div'); bgRow.className = 'bg-color-row'; const bgLabel = document.createElement('span'); @@ -1769,11 +1636,8 @@ export function populateDisplayControls(app, visibility, selectability, // Appended after the heat maps group below: Background is the panel's // footer, so every group — heat maps included — sits above it. - if (!app.heatMapLayer) { - app.heatMapLayer = new HeatMapTileLayer(app.websocketManager, app, { - zIndex: leafletLayers.length + 10, - opacity: 1, - }); + if (!app.heatMapLayer && createHeatMapSlot) { + app.heatMapLayer = createHeatMapSlot(); } const heatMapGroup = document.createElement('div'); diff --git a/openroad/web/src/display-state.js b/openroad/web/src/display-state.js index b614f37c562..946158d8811 100644 --- a/openroad/web/src/display-state.js +++ b/openroad/web/src/display-state.js @@ -51,8 +51,28 @@ const DISPLAY_STATE_KEYS = [ { key: 'or_arrow_step', store: 'cookie' }, { key: 'or_font_family', store: 'cookie' }, { key: 'or_font_scale', store: 'cookie' }, + { key: 'or_control_smoothing', store: 'cookie' }, + { key: 'or_double_buffer', store: 'cookie' }, + { key: 'or_defer_tile_updates', store: 'cookie' }, ]; +// The rendering preferences from their cookies. +export function renderPrefs(getCookie) { + return { + // Animated zoom and pan, and drag inertia. Off by default, so + // navigation jumps the way Qt's does. + controlSmoothing: getCookie('or_control_smoothing') === '1', + // Show new content only once it is complete — a tile's whole + // composite, and on a zoom the whole view (zoom-swap.js) — Qt's + // draw_pixmap_ model. + doubleBuffer: getCookie('or_double_buffer') !== '0', + // Hold tile requests until a drag ends rather than issuing a fresh + // batch every updateInterval while the pointer is down. Opt-in: it + // leaves the area a drag exposes empty until the button is released. + deferTileUpdates: getCookie('or_defer_tile_updates') === '1', + }; +} + // Storage accessors, tolerant of a browser with Web Storage disabled (the // cookie helpers in theme.js already are). The store is resolved by NAME // inside the try: with storage blocked, reading `window.sessionStorage` throws diff --git a/openroad/web/src/drc-widget.js b/openroad/web/src/drc-widget.js index 7855d452b30..7c3f777918b 100644 --- a/openroad/web/src/drc-widget.js +++ b/openroad/web/src/drc-widget.js @@ -369,7 +369,7 @@ export class DrcWidget { } _zoomToBBox(bbox) { - if (!this._app.designScale || !this._app.map) return; + if (!this._app.designScale || !this._app.view) return; const [xMin, yMin, xMax, yMax] = bbox; const dx = xMax - xMin; @@ -384,7 +384,7 @@ export class DrcWidget { const zoomoutBox = 2 * Math.max(dx, dy); const margin = Math.min(zoomoutDist, zoomoutBox); - // The margin above is this widget's own zoom rule; the DBU→map + // The margin above is this widget's own zoom rule; the DBU→view // conversion is the shared one (ui-utils.zoomToBBox), with no extra // padding on top of it. zoomToBBox(this._app, @@ -412,15 +412,7 @@ export class DrcWidget { } _flashHighlight() { - const container = this._app.map?.getContainer(); - if (!container) return; - container.classList.remove('drc-flashing'); - // Force reflow so re-adding the class restarts the animation. - void container.offsetWidth; - container.classList.add('drc-flashing'); - container.addEventListener('animationend', () => { - container.classList.remove('drc-flashing'); - }, { once: true }); + this._app.view?.flashTiles(); } _update3DHighlights() { diff --git a/openroad/web/src/entry-app.js b/openroad/web/src/entry-app.js index f4b9d8844f4..609f004e82e 100644 --- a/openroad/web/src/entry-app.js +++ b/openroad/web/src/entry-app.js @@ -4,6 +4,6 @@ // The served page's bundle: the viewer and the libraries it is built on. // main.js builds the panels as it loads, after the globals they read. -import './leaflet-global.js'; +import './deck-global.js'; import './vendor-globals.js'; import './main.js'; diff --git a/openroad/web/src/entry-report.js b/openroad/web/src/entry-report.js index 36548fe7c00..5df1b84477c 100644 --- a/openroad/web/src/entry-report.js +++ b/openroad/web/src/entry-report.js @@ -4,5 +4,5 @@ // The saved report's bundle leaves out vendor-globals.js; the schematic and 3D // panels need a live server and say so when their libraries are missing. -import './leaflet-global.js'; +import './deck-global.js'; import './main.js'; diff --git a/openroad/web/src/grid-layout.js b/openroad/web/src/grid-layout.js index 7bb3bf22735..ddd1098b905 100644 --- a/openroad/web/src/grid-layout.js +++ b/openroad/web/src/grid-layout.js @@ -187,7 +187,7 @@ export class IdePaneElement extends LitElement { overflow: hidden; } - /* Above Leaflet's controls (z-index 1000), below .context-menu. */ + /* Above the view's zoom buttons (z-index 1000), below .context-menu. */ .ide-tab-menu { position: absolute; top: 28px; @@ -1373,9 +1373,6 @@ export class GridLayoutManager extends EventEmitter { comp.container.fire('resize'); } } - if (typeof app !== 'undefined' && app && app.map) { - app.map.invalidateSize({ animate: false }); - } // Internal changes notify components directly. Emitting a window // resize here would feed back through its updateSize() listener. }); diff --git a/openroad/web/src/hierarchy-browser.js b/openroad/web/src/hierarchy-browser.js index 2a63e7fbd56..538db130c7e 100644 --- a/openroad/web/src/hierarchy-browser.js +++ b/openroad/web/src/hierarchy-browser.js @@ -266,9 +266,8 @@ export class HierarchyBrowser { console.error('set_module_colors failed:', err); return; } - // Only the module overlay reads these colors, so refresh that layer - // instead of every mounted one — a full redraw re-requests every metal - // layer's grid for a color they ignore. + // Only the module overlay reads these colors, so refresh the slot that + // draws it instead of every slot. if (this._app.modulesLayer) { this._app.modulesLayer.refreshTiles(); } else { diff --git a/openroad/web/src/hierarchy-panel.js b/openroad/web/src/hierarchy-panel.js index 6cf4c46326f..98ae9cb6e85 100644 --- a/openroad/web/src/hierarchy-panel.js +++ b/openroad/web/src/hierarchy-panel.js @@ -173,11 +173,10 @@ export class HierarchyPanel { } } - // Move the overlay to the view now on screen. Repaints only the two - // pseudo-layers, and only when a flag actually moved: nothing else reads - // these flags, so a full redraw would re-request every metal layer's grid - // for a change they ignore. Display Controls does its own redraw, so it - // calls refreshActiveStatus() instead of this. + // Move the overlay to the view now on screen. Refreshes only the slot + // that draws the two pseudo-layers, and only when a flag actually moved. + // Display Controls does its own redraw, so it calls refreshActiveStatus() + // instead of this. syncOverlay() { const app = this._app; if (!app || !app.visibility) return; diff --git a/openroad/web/src/inspector.js b/openroad/web/src/inspector.js index 6ae90ba1790..e667b645092 100644 --- a/openroad/web/src/inspector.js +++ b/openroad/web/src/inspector.js @@ -4,10 +4,12 @@ // Inspector panel — property tree, hover highlights, bbox display, // property editing (server descriptor editors). -import { dbuRectToBounds } from './coordinates.js'; +import { dbuRectToWorldRect } from './coordinates.js'; +import { DRAW_ORDER, toRgba } from './layout-view.js'; +import { easeOutQuad } from './view-math.js'; import { - beginSelection, isCurrentSelection, isStaticMode, showConfirmModal, - showToast, zoomToBBox as sharedZoomToBBox, + beginSelection, isCurrentSelection, isStaticMode, prefersReducedMotion, + showConfirmModal, showToast, zoomToBBox as sharedZoomToBBox, } from './ui-utils.js'; // Delete: trash can (Material "delete") @@ -87,7 +89,6 @@ const BUFFER_SVG = ''; export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { - refreshOverlay = refreshOverlay || redrawAllLayers; let lastInspectData = null; let pendingInspectId = null; let pendingHoverId = null; @@ -183,9 +184,8 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { }); if (!resp.ok && resp.error) showToast(resp.error); updateInspector(resp.properties ? resp : null); - if (resp.deleted && app.highlightRect && app.map) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; + if (resp.deleted) { + clearSelectionOutline(); } clearClientHoverHighlight(); refreshOverlay(); @@ -329,78 +329,134 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { if (lastInspectData) updateInspector(lastInspectData); } - function clearClientHoverHighlight() { - if (app.hoverHighlightLayer) { - app.map.removeLayer(app.hoverHighlightLayer); - app.hoverHighlightLayer = null; - } + // ─── Client-side shapes on the layout view ────────────────────────── + // + // The hover boxes, the selection outline, the selection pulse and the + // Qt-style selection animation. Kept in DBU and turned into world shapes + // when drawn, so a zoom can recompute the minimum on-screen hover size. + + function worldRect(x1, y1, x2, y2) { + return dbuRectToWorldRect(x1, y1, x2, y2, app.designScale, + app.designOriginX, app.designOriginY); } - function clearHoverHighlight() { - clearClientHoverHighlight(); - app.websocketManager.request({ type: 'hover', select_id: -1 }) - .then(() => {}) - .catch(() => {}); + function lerp(a, b, t) { + return a + (b - a) * t; + } + + function lerpColor(a, b, t) { + return a.map((v, i) => Math.round(lerp(v, b[i], t))); } - function boundsWithMinimumScreenSize(x1, y1, x2, y2) { - const baseBounds = L.latLngBounds( - dbuRectToBounds(x1, y1, x2, y2, app.designScale, app.designMaxDXDY, app.designOriginX, app.designOriginY) - ); - if (!app.map) { - return baseBounds; + // Value of a CSS-like keyframe list at fraction `t` of one cycle. + // `frames` is [{at, ...numbers or rgb arrays}], at in 0..1. + function keyframeAt(frames, t) { + let i = 0; + while (i < frames.length - 2 && t > frames[i + 1].at) { + i++; + } + const a = frames[i]; + const b = frames[i + 1]; + const local = Math.max(0, Math.min(1, (t - a.at) / (b.at - a.at))); + const out = {}; + for (const key of Object.keys(a)) { + if (key === 'at') continue; + out[key] = Array.isArray(a[key]) ? lerpColor(a[key], b[key], local) + : lerp(a[key], b[key], local); } + return out; + } - const southWest = baseBounds.getSouthWest(); - const northEast = baseBounds.getNorthEast(); - const swPoint = app.map.latLngToContainerPoint(southWest); - const nePoint = app.map.latLngToContainerPoint(northEast); - - const minX = Math.min(swPoint.x, nePoint.x); - const maxX = Math.max(swPoint.x, nePoint.x); - const minY = Math.min(swPoint.y, nePoint.y); - const maxY = Math.max(swPoint.y, nePoint.y); - - let expandedMinX = minX; - let expandedMaxX = maxX; - let expandedMinY = minY; - let expandedMaxY = maxY; - - if ((maxX - minX) < kMinHoverBoxPixels) { - const pad = (kMinHoverBoxPixels - (maxX - minX)) / 2; - expandedMinX -= pad; - expandedMaxX += pad; + // Run `draw(t)` every frame for `cycles` of `cycleMs`, then `done()`. + // Reduced motion skips straight to the end. + function runKeyframes(cycleMs, cycles, draw, done) { + if (prefersReducedMotion() + || typeof requestAnimationFrame !== 'function') { + done(); + return () => {}; } - if ((maxY - minY) < kMinHoverBoxPixels) { - const pad = (kMinHoverBoxPixels - (maxY - minY)) / 2; - expandedMinY -= pad; - expandedMaxY += pad; + const start = performance.now(); + let stopped = false; + const step = () => { + if (stopped) return; + const elapsed = performance.now() - start; + if (elapsed >= cycleMs * cycles) { + done(); + return; + } + draw((elapsed % cycleMs) / cycleMs); + requestAnimationFrame(step); + }; + step(); + return () => { stopped = true; }; + } + + function setShapes(id, shapes, order = DRAW_ORDER.highlight) { + if (app.view) { + app.view.setOverlay(id, shapes, { order }); } + } - const topLeft = app.map.containerPointToLatLng(L.point(expandedMinX, expandedMinY)); - const bottomRight = app.map.containerPointToLatLng(L.point(expandedMaxX, expandedMaxY)); - return L.latLngBounds(topLeft, bottomRight); + // Hover boxes: at least kMinHoverBoxPixels on screen, so a tiny object + // still shows where it is. + let hoverRects = null; + let stopHoverPulse = () => {}; + const HOVER_FILL = [255, 242, 122]; + const HOVER_FRAMES = [ + { at: 0, stroke: [255, 246, 176], width: 7, alpha: 1, fill: 0.28 }, + { at: 0.55, stroke: [255, 255, 255], width: 5, alpha: 1, fill: 0.06 }, + { at: 1, stroke: [255, 232, 92], width: 3, alpha: 0.95, fill: 0.14 }, + ]; + const HOVER_REST = { stroke: [255, 232, 92], width: 3, alpha: 1, fill: 0.14 }; + + function hoverWorldRect(x1, y1, x2, y2) { + const [x0, y0, x3, y3] = worldRect(x1, y1, x2, y2); + // The view scales world units by 2^zoom on both axes. + const min = kMinHoverBoxPixels / 2 ** app.view.getZoom(); + const padX = Math.max(0, (min - (x3 - x0)) / 2); + const padY = Math.max(0, (min - (y3 - y0)) / 2); + return [x0 - padX, y0 - padY, x3 + padX, y3 + padY]; + } + + function drawHover(style) { + if (!hoverRects) return; + setShapes('hover', hoverRects.map(([x1, y1, x2, y2]) => ({ + kind: 'rect', + rect: hoverWorldRect(x1, y1, x2, y2), + stroke: toRgba(style.stroke, style.alpha), + width: style.width, + fill: toRgba(HOVER_FILL, style.fill), + }))); + } + + function redrawHoverOnZoom() { + drawHover(HOVER_REST); + } + + function clearClientHoverHighlight() { + stopHoverPulse(); + hoverRects = null; + setShapes('hover', null); + app.view?.off('zoom', redrawHoverOnZoom); + } + + function clearHoverHighlight() { + clearClientHoverHighlight(); + app.websocketManager.request({ type: 'hover', select_id: -1 }) + .then(() => {}) + .catch(() => {}); } function renderHoverRects(rects) { clearClientHoverHighlight(); - if (!app.map || !app.designScale || !rects || rects.length === 0) { + if (!app.view || !app.designScale || !rects || rects.length === 0) { return; } - - app.hoverHighlightLayer = L.layerGroup( - rects.map(([x1, y1, x2, y2]) => L.rectangle(boundsWithMinimumScreenSize(x1, y1, x2, y2), { - color: '#ffe85c', - weight: 3, - fill: true, - fillColor: '#fff27a', - fillOpacity: 0.14, - opacity: 1, - interactive: false, - className: 'hover-highlight', - pane: app.hoverHighlightPane, - })) - ).addTo(app.map); + hoverRects = rects; + app.view.on('zoom', redrawHoverOnZoom); + stopHoverPulse = runKeyframes(900, 3, + (t) => drawHover(keyframeAt(HOVER_FRAMES, easeOutQuad(t))), + () => drawHover(HOVER_REST)); } function makeClickable(el, selectId) { @@ -430,6 +486,11 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { }); }); el.addEventListener('mouseleave', () => { + // A reply still on its way would draw the hover after the leave. + if (pendingHoverId !== null) { + app.websocketManager.cancel(pendingHoverId); + pendingHoverId = null; + } clearHoverHighlight(); refreshOverlay(); }); @@ -465,15 +526,9 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { app.schematicWidget.refresh(); } } - if (app.map) { - app.map.closePopup(); - } clearClientHoverHighlight(); - if (app.highlightRect && app.map) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } - if (data.bbox && app.map && app.designScale) { + clearSelectionOutline(); + if (data.bbox && app.view && app.designScale) { const [x1, y1, x2, y2] = data.bbox; if (data.type !== 'Inst') { highlightBBox(x1, y1, x2, y2, data.type); @@ -484,8 +539,8 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { pulseHighlight(data.bbox, data.type); } } - // Redraw tiles to restore selection-set highlights. - redrawAllLayers(); + // The selection-set highlights are drawn on the overlay. + refreshOverlay(); }) .catch(err => { pendingInspectId = null; @@ -519,13 +574,9 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { } updateInspector(data); - app.map.closePopup(); clearClientHoverHighlight(); - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } - if (data.bbox && app.map && app.designScale) { + clearSelectionOutline(); + if (data.bbox && app.view && app.designScale) { const [x1, y1, x2, y2] = data.bbox; // For non-instance objects, show dashed bbox outline // (instances get the yellow tile-based highlight instead) @@ -565,13 +616,9 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { } updateInspector(data); - app.map.closePopup(); clearClientHoverHighlight(); - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } - if (data.bbox && app.map && app.designScale) { + clearSelectionOutline(); + if (data.bbox && app.view && app.designScale) { if (data.type !== 'Inst') { const [x1, y1, x2, y2] = data.bbox; highlightBBox(x1, y1, x2, y2, data.type); @@ -586,116 +633,112 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { }); } - function highlightBBox(x1, y1, x2, y2, type) { - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; + // The selection outline: kept in DBU, drawn while the "Highlight + // selected" toggle (Misc) is on, so turning it back on shows the current + // selection's outline again (redrawAllLayers -> renderSelectionOutline). + let selectionBBox = null; + // The toggle gates the outline, the pulse and the animation alike. + const highlightOff = () => app.visibility?.highlight_selected === false; + + function renderSelectionOutline() { + const show = selectionBBox && app.designScale && !highlightOff(); + setShapes('selection', show ? [{ + kind: 'rect', + rect: worldRect(...selectionBBox), + stroke: toRgba('#ff0'), width: 2, dash: [6, 4], + }] : null, DRAW_ORDER.selection); + if (highlightOff()) { + clearPulse(); + stopSelectionAnimation(); } + } + + function clearSelectionOutline() { + selectionBBox = null; + renderSelectionOutline(); + } + + function highlightBBox(x1, y1, x2, y2, type) { // A net's bbox spans its whole extent, which is distracting; the net's // trace is already highlighted via the overlay, so skip the rectangle. - if (type === 'Net') { - return; - } - const bounds = dbuRectToBounds(x1, y1, x2, y2, app.designScale, app.designMaxDXDY, app.designOriginX, app.designOriginY); - // Always build the outline; only attach it while the "Highlight - // selected" toggle (Misc) is on, so toggling it back on can - // re-attach the current selection's outline (redrawAllLayers). - app.highlightRect = L.rectangle(bounds, { - color: '#ff0', weight: 2, fill: false, dashArray: '6,4', - }); - if (!(app.visibility && app.visibility.highlight_selected === false)) { - app.highlightRect.addTo(app.map); - } + selectionBBox = type === 'Net' ? null : [x1, y1, x2, y2]; + renderSelectionOutline(); } // Briefly pulse the object's bbox so the user can see which object // the inspector is now showing — mirrors the Qt GUI's selection // animation. The pulse is a filled rectangle that fades in and out - // several times, then removes itself. - let pulseLayer = null; + // three times, then removes itself. + let stopPulse = null; + const PULSE_FRAMES = [ + { at: 0, alpha: 0, fill: 0 }, + { at: 0.5, alpha: 1, fill: 0.28 }, + { at: 1, alpha: 0, fill: 0 }, + ]; + function clearPulse() { + if (stopPulse) { + stopPulse(); + stopPulse = null; + } + setShapes('pulse', null); + } function pulseHighlight(bbox, type) { - if (!bbox || !app.map || !app.designScale) return; + if (!bbox || !app.view || !app.designScale) return; // Clear any pulse in flight before honoring the toggle, so a call // while highlighting is off doesn't leave a stale pulse behind. if (animTimer !== null) stopSelectionAnimation(); - if (pulseLayer) { - app.map.removeLayer(pulseLayer); - pulseLayer = null; - } - // Honor the "Highlight selected" toggle (Misc). - if (app.visibility && app.visibility.highlight_selected === false) { + clearPulse(); + if (highlightOff()) { return; } // A net's bbox spans the whole net; don't pulse a giant rectangle. if (type === 'Net') return; - const [x1, y1, x2, y2] = bbox; - const bounds = dbuRectToBounds( - x1, y1, x2, y2, app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY); - pulseLayer = L.rectangle(bounds, { - color: '#ff0', - weight: 3, - fill: true, - fillColor: '#ff0', - fillOpacity: 0.25, - opacity: 1, - interactive: false, - className: 'selection-pulse', - pane: app.hoverHighlightPane, - }).addTo(app.map); - // Remove after the animation finishes (3 cycles × 350ms = 1050ms). - const layerToRemove = pulseLayer; - setTimeout(() => { - if (layerToRemove && app.map && app.map.hasLayer(layerToRemove)) { - app.map.removeLayer(layerToRemove); - } - if (pulseLayer === layerToRemove) { - pulseLayer = null; - } - }, 1100); + const rect = worldRect(...bbox); + stopPulse = runKeyframes(350, 3, (t) => { + const k = keyframeAt(PULSE_FRAMES, + 0.5 - 0.5 * Math.cos(Math.PI * t)); + setShapes('pulse', [{ + kind: 'rect', rect, + stroke: toRgba('#ff0', k.alpha), width: 3, + fill: toRgba('#ff0', k.fill), + }]); + }, () => { + stopPulse = null; + setShapes('pulse', null); + }); } // Qt-style selection animation (layoutViewer.cpp selectionAnimation): // every tick the outline weight cycles 1→2→3 px with a yellow brush - // flash on the weight-1 tick. Unlike Qt, only this Leaflet path - // repaints — the layout tiles are untouched. repeats=0 animates - // until stopSelectionAnimation() or a new animation replaces it. - let animLayer = null; + // flash on the weight-1 tick. Unlike Qt, only this shape repaints — + // the layout tiles are untouched. repeats=0 animates until + // stopSelectionAnimation() or a new animation replaces it. let animTimer = null; + function drawAnim(rect, weight) { + setShapes('anim', [{ + kind: 'rect', rect, + stroke: toRgba('#ff0'), width: weight, + fill: toRgba('#ff0', weight === 1 ? 0.39 : 0), // ≈ Qt kHighlight 100/255 + }]); + } function stopSelectionAnimation() { if (animTimer !== null) { clearInterval(animTimer); animTimer = null; } - if (animLayer) { - if (app.map && app.map.hasLayer(animLayer)) { - app.map.removeLayer(animLayer); - } - animLayer = null; - } + setShapes('anim', null); } function animateSelection(bbox, { repeats = 6, intervalMs = 300 } = {}) { - if (!bbox || !app.map || !app.designScale) return; stopSelectionAnimation(); - if (typeof matchMedia === 'function' - && matchMedia('(prefers-reduced-motion: reduce)').matches) { + if (!bbox || !app.view || !app.designScale || highlightOff()) { + return; + } + if (prefersReducedMotion()) { pulseHighlight(bbox); return; } - const [x1, y1, x2, y2] = bbox; - const bounds = dbuRectToBounds( - x1, y1, x2, y2, app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY); - animLayer = L.rectangle(bounds, { - color: '#ff0', - weight: 1, - fill: true, - fillColor: '#ff0', - fillOpacity: 0.39, // ≈ Qt kHighlight brush alpha 100/255 - opacity: 1, - interactive: false, - pane: app.hoverHighlightPane, - }).addTo(app.map); + const rect = worldRect(...bbox); + drawAnim(rect, 1); let state = 0; const maxState = repeats > 0 ? repeats * 3 : Infinity; animTimer = setInterval(() => { @@ -704,22 +747,13 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { stopSelectionAnimation(); return; } - const weight = (state % 3) + 1; - animLayer.setStyle({ - weight, - fillOpacity: weight === 1 ? 0.39 : 0, - }); + drawAnim(rect, (state % 3) + 1); }, intervalMs); } - // Let redrawAllLayers cancel an in-flight pulse when the "Highlight - // selected" toggle is turned off (pulseLayer is private to this closure). - app.clearSelectionPulse = function() { - if (pulseLayer) { - app.map.removeLayer(pulseLayer); - pulseLayer = null; - } - }; + // redrawAllLayers keeps the outline, and what the toggle stops, in step. + app.renderSelectionOutline = renderSelectionOutline; + app.clearSelectionOutline = clearSelectionOutline; // Build the collapsible shell (header row + body) shared by the group and // table property renderers. `count` is the parenthesised badge after the @@ -1114,6 +1148,17 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { } } + // A client-side object (ruler, label) deletes itself, saved + // reports included. + if (data.onDelete) { + const btn = document.createElement('button'); + btn.className = 'or-btn or-btn-icon or-btn-danger-hover'; + btn.title = `Delete ${data.type.toLowerCase()}`; + btn.innerHTML = DELETE_SVG; + btn.addEventListener('click', () => data.onDelete()); + toolbar.appendChild(btn); + } + app.inspectorEl.appendChild(toolbar); } @@ -1169,12 +1214,18 @@ export function createInspectorPanel(app, redrawAllLayers, refreshOverlay) { // Re-request the currently inspected object from the server // (e.g. after toggling show-DBU so property formatting changes). - // Rulers are client-side so we re-select instead of re-requesting. + // Rulers are client-side, so they show themselves again instead. function refreshInspector() { if (!lastInspectData) return; if (lastInspectData.type === 'Ruler') { - if (app.rulerManager && app.rulerManager._selectedRulerId !== null) { - app.rulerManager._selectRuler(app.rulerManager._selectedRulerId); + app.rulerManager?.refreshInspector(); + return; + } + // So are labels, as far as the Inspector goes: the server's selection + // is something else. + if (lastInspectData.type === 'Label') { + if (lastInspectData.name) { + app.labelManager?.refreshInspector(lastInspectData.name); } return; } diff --git a/openroad/web/src/label-manager.js b/openroad/web/src/label-manager.js index 9dc1cc042dd..f3111306253 100644 --- a/openroad/web/src/label-manager.js +++ b/openroad/web/src/label-manager.js @@ -5,11 +5,16 @@ // the shared TileGenerator) so they render into the overlay tiles and into // save_image, matching the Qt GUI. This client module provides the // interactive layer the Qt GUI lacks: create-by-click, drag-to-reposition, -// and edit/delete via the Inspector. Each label gets a small draggable handle -// marker in a dedicated Leaflet pane; the label text itself is drawn by the -// server on the overlay. +// and edit/delete via the Inspector. Each label gets a small draggable DOM +// handle pinned over the view; the label text itself is drawn by the server +// on the overlay. -import { dbuToLatLng, latLngToDbu } from './coordinates.js'; +import { dbuToWorld, worldToDbu } from './coordinates.js'; +import { beginSelection, onSelectionReset } from './ui-utils.js'; + +const HANDLES = 'label-handles'; +// A press that moves further than this drags the handle instead of clicking. +const kDragTolerancePx = 3; export class LabelManager { constructor(app, visibility, updateInspector, focusComponent) { @@ -22,29 +27,33 @@ export class LabelManager { this._anchors = []; // anchor names the server accepts this._mode = false; // placement mode (next click creates a label) this._selectedName = null; - - this._pane = null; - this._handleGroup = null; - this._initLayers(); - } - - _initLayers() { - const map = this._app.map; - if (!map) return; - this._pane = map.createPane('label-pane'); - this._pane.style.zIndex = '690'; - this._pane.style.pointerEvents = 'auto'; - this._handleGroup = L.layerGroup([], { pane: 'label-pane' }).addTo(map); + this._placedFor = null; // [scale, originX, originY] of the handles + this._dragging = false; + // Another object taking the selection unmarks the label. + onSelectionReset(app, () => { + if (this._selectedName !== null) { + this._selectedName = null; + this._renderHandles(); + } + }); } isActive() { return this._mode; } + // Also re-places the handles if a resync moved the design's origin or + // scale, but not under a drag, which would lose the dragged element. updateVisibility() { - if (this._pane) { - this._pane.style.display = this._visibility.labels ? '' : 'none'; + const app = this._app; + const placed = this._placedFor; + if (!this._dragging && (!placed || placed[0] !== app.designScale + || placed[1] !== app.designOriginX + || placed[2] !== app.designOriginY)) { + this._renderHandles(); } + this._app.view?.setMarkerGroupVisible(HANDLES, + !!this._visibility.labels); } toggleLabelMode() { @@ -57,13 +66,8 @@ export class LabelManager { this._setCursor(false); } - // Toggled as a class, not an inline style: .leaflet-container carries - // `cursor: default !important`, which an inline declaration of normal - // priority cannot override. _setCursor(on) { - const c = this._app.map?.getContainer(); - if (!c) return; - c.classList.toggle('label-mode-cursor', on); + this._app.view?.setCursorMode('label', on); } _wm() { @@ -88,12 +92,15 @@ export class LabelManager { // selection if the label it pointed at is gone, or the Inspector would go // on showing a label that no longer exists. applyRemoteLabels(labels) { - this._applyLabels(labels); - if (this._selectedName - && !this._labels.some(l => l.name === this._selectedName)) { + // Dropped before the repaint, so the handles are drawn once. + const gone = this._selectedName + && !(labels || []).some(l => l.name === this._selectedName); + if (gone) { this._selectedName = null; + } + this._applyLabels(labels); + if (gone) { this._updateInspector(null); - this._renderHandles(); } this._app.refreshOverlay(); } @@ -136,41 +143,77 @@ export class LabelManager { } _renderHandles() { - if (!this._handleGroup) return; - this._handleGroup.clearLayers(); - const scale = this._app.designScale; - if (!scale) return; - const maxDXDY = this._app.designMaxDXDY; - const ox = this._app.designOriginX; - const oy = this._app.designOriginY; + const view = this._app.view; + if (!view) return; + view.clearMarkers(HANDLES); + const app = this._app; + if (!app.designScale) return; + this._placedFor = [app.designScale, app.designOriginX, + app.designOriginY]; for (const label of this._labels) { - const ll = dbuToLatLng(label.x, label.y, scale, maxDXDY, ox, oy); - const selected = label.name === this._selectedName; - const marker = L.marker(ll, { - pane: 'label-pane', - draggable: true, - keyboard: false, - icon: L.divIcon({ - className: 'label-handle' - + (selected ? ' label-handle-selected' : ''), - html: '', - iconSize: [10, 10], - }), - title: label.text, - }); - marker.on('click', (e) => { - L.DomEvent.stopPropagation(e); + const el = document.createElement('div'); + el.className = 'label-handle' + + (label.name === this._selectedName + ? ' label-handle-selected' : ''); + el.title = label.text; + this._installDrag(el, label); + view.addMarker(HANDLES, label.name, + dbuToWorld(label.x, label.y, app.designScale, + app.designOriginX, app.designOriginY), + el, { center: true }); + } + } + + // Press and release selects the label; a drag moves it. + _installDrag(el, label) { + const view = this._app.view; + const toWorld = (e) => { + const r = view.getContainer().getBoundingClientRect(); + return view.unproject([e.clientX - r.left, e.clientY - r.top]); + }; + let press = null; + el.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + e.stopPropagation(); + e.preventDefault(); + el.setPointerCapture?.(e.pointerId); + press = { x: e.clientX, y: e.clientY, moved: false }; + this._dragging = true; + }); + el.addEventListener('pointermove', (e) => { + if (!press) return; + if (Math.abs(e.clientX - press.x) > kDragTolerancePx + || Math.abs(e.clientY - press.y) > kDragTolerancePx) { + press.moved = true; + } + if (press.moved) { + view.moveMarker(HANDLES, label.name, toWorld(e)); + } + }); + const finish = (e, commit) => { + if (!press) return; + const p = press; + press = null; + this._dragging = false; + el.releasePointerCapture?.(e.pointerId); + if (!commit) { + this._renderHandles(); + } else if (!p.moved) { this._select(label.name); - }); - marker.on('dragend', (e) => { - const p = e.target.getLatLng(); - const { dbuX, dbuY } = latLngToDbu( - p.lat, p.lng, scale, maxDXDY, ox, oy); + } else { + const app = this._app; + const [wx, wy] = toWorld(e); + const { dbuX, dbuY } = worldToDbu( + wx, wy, app.designScale, + app.designOriginX, app.designOriginY); this._commitMove(label, Math.round(dbuX), Math.round(dbuY)); - }); - this._handleGroup.addLayer(marker); - } + } + }; + el.addEventListener('pointerup', (e) => finish(e, true)); + el.addEventListener('pointercancel', (e) => finish(e, false)); + // The view's own click and double-click handling skips markers. + el.addEventListener('click', (e) => e.stopPropagation()); } // Move the label to a new position with a single atomic update (no @@ -188,8 +231,21 @@ export class LabelManager { } _select(name) { + // Our own mark goes first, so the reset that unmarks every other panel + // does not redraw the handles a second time. + this._selectedName = null; + beginSelection(this._app); this._selectedName = name; this._renderHandles(); + this._inspect(name, { focus: true }); + } + + // Shows the label in the Inspector again without taking the selection. + refreshInspector(name) { + this._inspect(name, { focus: false }); + } + + _inspect(name, { focus }) { const label = this._labels.find(l => l.name === name); if (!label) return; const fmt = (dbu) => this._app.formatDbu(dbu, true); @@ -220,26 +276,12 @@ export class LabelManager { else if (propName === 'Anchor') patch.anchor = newValue.trim(); this._edit(label, patch); }, + onDelete: () => this.deleteLabel(name), }; this._updateInspector(data); - this._focusComponent('Inspector'); - - requestAnimationFrame(() => { - const toolbar - = this._app.inspectorEl?.querySelector('.inspector-toolbar'); - if (!toolbar) return; - // Avoid stacking duplicate delete buttons across re-selections. - if (toolbar.querySelector('.delete-label-btn')) return; - const btn = document.createElement('button'); - btn.className = 'or-btn or-btn-icon delete-label-btn'; - btn.title = 'Delete label'; - btn.innerHTML = - '' - + '' - + ''; - btn.addEventListener('click', () => this.deleteLabel(name)); - toolbar.appendChild(btn); - }); + if (focus) { + this._focusComponent('Inspector'); + } } // Apply an edit atomically, keeping the same name/position. @@ -250,7 +292,10 @@ export class LabelManager { anchor: patch.anchor, color: label.color, }); this._refresh(res); - this._select(label.name); + // Something else may have taken the selection while it was sent. + if (this._selectedName === label.name) { + this.refreshInspector(label.name); + } } catch (err) { console.error('edit label failed:', err); } diff --git a/openroad/web/src/layer-extents.js b/openroad/web/src/layer-extents.js index b2a4a874bf1..3da0c3aff96 100644 --- a/openroad/web/src/layer-extents.js +++ b/openroad/web/src/layer-extents.js @@ -212,8 +212,8 @@ export class LayerExtents { } } -// Whether a tile layer should request `layer` at `coords`. `ctx` is a tile -// layer's context ({ visibility, app }); app.layerExtents is absent until +// Whether a tile source should request `layer` at `coords`. `ctx` is the +// tile request context ({ visibility, app }); app.layerExtents is absent until // main.js installs it, and in that case everything is requested. `chiplet` // is the die a scoped row draws. export function tileMayHaveContent(ctx, layer, coords, chiplet) { diff --git a/openroad/web/src/layout-view.js b/openroad/web/src/layout-view.js new file mode 100644 index 00000000000..69da5b702e5 --- /dev/null +++ b/openroad/web/src/layout-view.js @@ -0,0 +1,1279 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// The 2D layout view, drawn with deck.gl. +// +// Owns the Deck, the view state and its animations, the tile slots (each a +// TileGrid over a tile source, all changing zoom level together through one +// ZoomSwap), the client-side shapes (selection outline, hover, rulers), DOM +// markers and image overlays. The rest of the app talks to it through the +// methods returned by createLayoutView; nothing outside reads deck directly. +// +// World coordinates are view-math's: CSS px at zoom 0, y up, tile grid [0, T]. + +import { + clampZoom, easeInOutCubic, easeOutCubic, fitView, flyPath, growRange, + growRect, project, rectsOverlap, snapTarget, + tileRange, tileWorldBounds, tileZoomFor, unproject, viewWorldRect, + zoomAround as zoomAroundTarget, +} from './view-math.js'; +import { TileGrid, tileKey } from './tile-grid.js'; +import { nativeDpr, tileSizeCss } from './tile-request.js'; +import { copyToCanvas2d } from './tile-sources.js'; +import { cssColorToHex, MAX_TILE_ZOOM, rafCoalesce } from './ui-utils.js'; +import { ZoomSwap } from './zoom-swap.js'; + +// Bottom to top. +export const DRAW_ORDER = Object.freeze({ + base: 10, overlay: 20, heatmap: 30, top: 40, pathImage: 50, + selection: 60, highlight: 70, ruler: 80, +}); + +// Layers stack in list order, never by depth. +const noDepth = { depthCompare: 'always', depthWriteEnabled: false }; + +const ANIMATION_MS = 250; // zoom and pan duration +const kSettleTimeoutMs = 6000; // whenTilesSettled gives up after +const kMaxAnimatedZoomDelta = 4; // larger jumps cut, or fly (curve) +const kInertiaMs = 300; +// The level above is kept loaded this many views around the view, so a zoom +// out around any point finds its tiles there. +const kPrefetchMargin = 1; +// Jumps further than this many views, or than kMaxAnimatedZoomDelta, fly. +const kFlightViews = 2; +const kFlightWaitMs = 300; // longest wait for the apex level +const kFlightMsPerS = 300; // per unit of flyPath length +const kFlightMinMs = 400; +const kFlightMaxMs = 1000; +const kInertiaWindowMs = 100; // drag samples that set the speed +const kInertiaMinSpeed = 0.05; // px/ms; slower releases just stop +const kFlashPulseMs = 400; +const kFlashMs = 3 * kFlashPulseMs; + +// '#rgb', '#rrggbb' or [r, g, b(, a)] to [r, g, b, a] with alpha 0..255. +export function toRgba(color, opacity = 1) { + if (Array.isArray(color)) { + const a = color.length > 3 ? color[3] : 255; + return [color[0], color[1], color[2], Math.round(a * opacity)]; + } + let hex = String(color || '#000').replace('#', ''); + if (hex.length === 3) { + hex = hex.split('').map((c) => c + c).join(''); + } + const n = parseInt(hex.slice(0, 6), 16) || 0; + return [(n >> 16) & 255, (n >> 8) & 255, n & 255, Math.round(255 * opacity)]; +} + +function makeEmitter() { + const handlers = new Map(); + return { + on(types, fn) { + for (const type of types.split(/\s+/)) { + if (!handlers.has(type)) { + handlers.set(type, new Set()); + } + handlers.get(type).add(fn); + } + }, + off(types, fn) { + for (const type of types.split(/\s+/)) { + handlers.get(type)?.delete(fn); + } + }, + emit(type, payload) { + for (const fn of [...(handlers.get(type) || [])]) { + fn(payload); + } + }, + }; +} + +// What draws the view: luma.gl reports a software renderer as gpuType 'cpu'. +function deviceInfo(d) { + const info = (d && d.device && d.device.info) || {}; + return { gpuType: info.gpuType || 'unknown', + renderer: info.renderer || '', vendor: info.vendor || '' }; +} + +// `opts`: +// deckApi the deck.gl namespace (window.deck); a missing one leaves a view +// that keeps its state but draws nothing +// prefs { smooth(), doubleBuffer(), defer() }, read live +// tileSize() CSS px of a tile; dpr() the device pixel ratio +// isStatic a saved report: no touch zoom +// preserveDrawingBuffer keep the canvas readable between frames (probes) +// raf, now, copyCanvas injectable for tests +export function createLayoutView(container, opts = {}) { + const deckApi = opts.deckApi !== undefined ? opts.deckApi : globalThis.deck; + const copyCanvas = opts.copyCanvas || copyToCanvas2d; + const prefs = { + smooth: () => false, doubleBuffer: () => true, defer: () => false, + ...(opts.prefs || {}), + }; + const tileSize = opts.tileSize || tileSizeCss; + const dpr = opts.dpr || nativeDpr; + const raf = opts.raf || ((fn) => requestAnimationFrame(fn)); + const now = opts.now || (() => performance.now()); + const events = makeEmitter(); + + const vs = { target: [0, 0], zoom: 0, width: 1, height: 1 }; + const limits = { minZoom: -Infinity, maxZoom: MAX_TILE_ZOOM }; + let anim = null; // the move in progress, see animateTo() + let interacting = false; // a drag or pinch from the controller + let gesturing = false; // a wheel or trackpad gesture (setGesture) + let afterFrame = []; // called once deck has drawn its next frame + let rendererInfo = null; // what draws, once deck's device is up + let restoring = false; // a lost context's new deck, until it is up + let dragSamples = []; // { t, target, zoom } while interacting + let prefetchZ = null; // level loaded in the background for a zoom out + let flightTrail = null; // a landed flight's pulled-out level, kept under + // the view until the destination level shows + let prefetchPending = false; + let moving = false; // between movestart and moveend + let flashUntil = 0; + const cursorModes = new Set(); // 'ruler', 'label' + + // ─── DOM ──────────────────────────────────────────────────────────── + container.classList.add('or-view'); + const canvasWrap = document.createElement('div'); + canvasWrap.className = 'or-view-canvas'; + container.appendChild(canvasWrap); + const markerLayer = document.createElement('div'); + markerLayer.className = 'or-view-markers'; + container.appendChild(markerLayer); + + // ─── Slots, shapes, markers ───────────────────────────────────────── + const slots = new Map(); // id -> slot + const overlays = new Map(); // id -> its layer specs + const images = new Map(); // id -> its layer spec + const markers = new Map(); // group -> { visible, items: Map id -> m } + let textures = new WeakMap(); // drawable -> texture on the current device + let doomedTextures = []; + + // One render per frame, however many changes ask for one. + const scheduleRender = rafCoalesce(render, raf); + + const swap = new ZoomSwap({ + isEnabled: () => prefs.doubleBuffer(), + isSmooth: () => prefs.smooth(), + now, + onChange: () => scheduleRender(), + }); + + // ─── Deck ─────────────────────────────────────────────────────────── + let deckgl = null; + function controllerProps() { + return { + dragPan: true, + dragRotate: false, + scrollZoom: false, + doubleClickZoom: false, + touchZoom: !opts.isStatic, + touchRotate: false, + keyboard: false, + // Inertia is startInertia's: deck's own only runs if its + // transition props come back through the controlled viewState. + inertia: false, + }; + } + function deckViewState() { + return { target: [vs.target[0], vs.target[1], 0], zoom: vs.zoom, + minZoom: limits.minZoom, maxZoom: limits.maxZoom }; + } + // An error before onLoad means the device was never created: the browser + // gave no WebGL, or a lost context could not be restored. + function deckError(error) { + console.error('Layout view:', error); + if (restoring) { + restoring = false; + events.emit('contextfailed', error); + } else if (!rendererInfo) { + rendererInfo = { gpuType: 'none', renderer: '', vendor: '' }; + events.emit('renderer', rendererInfo); + } + } + function createDeck() { + return new deckApi.Deck({ + parent: canvasWrap, + views: new deckApi.OrthographicView({ + id: 'main', flipY: false, controller: controllerProps(), + }), + viewState: deckViewState(), + layers: [], + useDevicePixels: true, + // Save image copies the frame as it is drawn; keeping the buffer + // readable outside it is for probes (?preservebuffer=1). + deviceProps: { webgl: { + preserveDrawingBuffer: !!opts.preserveDrawingBuffer } }, + getCursor: ({ isDragging }) => { + if (cursorModes.size) { + return 'crosshair'; + } + return isDragging ? 'grabbing' : 'default'; + }, + onViewStateChange: ({ viewState }) => { + anim = null; + setViewState(viewState.target, viewState.zoom); + if (interacting) { + const t = now(); + dragSamples.push({ t, target: [...vs.target], + zoom: vs.zoom }); + dragSamples = dragSamples.filter( + (d) => t - d.t <= kInertiaWindowMs); + } + return deckViewState(); + }, + onInteractionStateChange: (state) => { + const busy = !!(state.isDragging || state.isPanning + || state.isZooming || state.inTransition); + if (busy === interacting) { + return; + } + interacting = busy; + if (busy) { + dragSamples = []; + startMove(); + return; + } + // deck reports the end before the view state that goes with + // it, and that update would cancel the glide. + queueMicrotask(() => { + if (!interacting && !anim && !startInertia()) { + settleView(); + } + }); + }, + // The canvas only exists once the device is up. + onLoad: () => { + watchContext(); + rendererInfo = deviceInfo(deckgl); + events.emit('renderer', rendererInfo); + if (restoring) { + restoring = false; + events.emit('contextrestored'); + } + scheduleRender(); + }, + onError: deckError, + onAfterRender: () => { + const waiting = afterFrame; + afterFrame = []; + waiting.forEach((fn) => fn()); + }, + }); + } + + // A lost WebGL context takes every texture with it. A new Deck gets a + // new canvas and context; the tiles' images are still here, so their + // textures are rebuilt from them and nothing is re-requested. The new + // device comes up later: contextrestored or contextfailed tells which. + function watchContext() { + const canvas = deckgl.getCanvas && deckgl.getCanvas(); + canvas?.addEventListener('webglcontextlost', (e) => { + e.preventDefault(); + events.emit('contextlost'); + const old = deckgl; + deckgl = null; + textures = new WeakMap(); + doomedTextures = []; + try { + old.finalize?.(); + } catch (err) { + // The old device is already gone. + } + canvas.remove(); + try { + restoring = true; + deckgl = createDeck(); + } catch (err) { + deckError(err); + } + scheduleRender(); + }); + } + + if (deckApi && typeof deckApi.Deck === 'function') { + try { + deckgl = createDeck(); + } catch (err) { + // Once the caller is listening. + queueMicrotask(() => deckError(err)); + } + } + + // ─── Size ─────────────────────────────────────────────────────────── + // The canvas is sized to whole device pixels so tiles map 1:1 at rest. + function measure() { + const r = dpr(); + const w = Math.max(1, Math.floor(container.clientWidth * r) / r); + const h = Math.max(1, Math.floor(container.clientHeight * r) / r); + const changed = w !== vs.width || h !== vs.height; + vs.width = w; + vs.height = h; + canvasWrap.style.width = w + 'px'; + canvasWrap.style.height = h + 'px'; + return changed; + } + measure(); + if (typeof ResizeObserver === 'function') { + new ResizeObserver(() => invalidateSize()).observe(container); + } + + function invalidateSize() { + if (measure()) { + applyView(); + events.emit('resize', getSize()); + } else { + scheduleRender(); + } + } + + // ─── View state ───────────────────────────────────────────────────── + function setViewState(target, zoom, { tiles = true } = {}) { + const z = clampZoom(zoom, limits); + const zoomChanged = z !== vs.zoom; + vs.target = [target[0], target[1]]; + vs.zoom = z; + applyView(zoomChanged, tiles); + } + + function applyView(zoomChanged = false, tiles = true) { + if (deckgl) { + deckgl.setProps({ viewState: deckViewState() }); + } + if (zoomChanged) { + events.emit('zoom'); + } + if (tiles) { + updateTiles(); + } + scheduleRender(); + } + + function startMove() { + if (!moving) { + moving = true; + events.emit('movestart'); + } + } + + function settleView() { + if (anim || interacting) { + return; + } + // Touch zoom can leave a fractional level; rest on a whole one. + const whole = Math.round(vs.zoom); + if (Math.abs(whole - vs.zoom) > 1e-9) { + animateTo({ target: zoomAroundTarget(vs, [vs.width / 2, + vs.height / 2], whole), + zoom: whole }, { anchor: null }); + return; + } + vs.target = snapTarget(vs, dpr()); + const ended = moving; + moving = false; // at rest before the tile update: z-1 may load + applyView(); + if (ended) { + events.emit('moveend'); + events.emit('zoomend'); + } + } + + // A drag released while moving glides on, slowing to a stop. + function startInertia() { + const samples = dragSamples; + dragSamples = []; + if (!prefs.smooth() || samples.length < 2) { + return false; + } + const first = samples[0]; + const last = samples[samples.length - 1]; + const dt = last.t - first.t; + if (dt <= 0 || now() - last.t > kInertiaWindowMs + || first.zoom !== last.zoom) { + return false; + } + const vx = (last.target[0] - first.target[0]) / dt; + const vy = (last.target[1] - first.target[1]) / dt; + if (Math.hypot(vx, vy) * Math.pow(2, vs.zoom) < kInertiaMinSpeed) { + return false; + } + // Same reach as deck's inertia: half the release speed for its length. + animateTo({ target: [vs.target[0] + vx * kInertiaMs / 2, + vs.target[1] + vy * kInertiaMs / 2], + zoom: vs.zoom }, { ms: kInertiaMs }); + return true; + } + + function animationMs(to) { + if (!prefs.smooth()) { + return 0; + } + if (Math.abs(to.zoom - vs.zoom) > kMaxAnimatedZoomDelta) { + return 0; + } + return ANIMATION_MS; + } + + // Move to `to` = { target, zoom }, animated when smoothing is on. With + // `anchor` (a screen point) the world point under it stays still. + // `settle: false` leaves a jump unsettled, mid-gesture. `curve` lets a + // long jump fly (flyPath) instead of sliding or cutting. + function animateTo(to, { anchor = null, ms = undefined, settle = true, + curve = false } = {}) { + to = { target: to.target, zoom: clampZoom(to.zoom, limits) }; + const flight = curve && ms === undefined ? planFlight(to) : null; + if (ms === undefined) { + ms = flight ? flight.ms : animationMs(to); + } + startMove(); + if (ms <= 0) { + anim = null; + // settleView updates the tiles once, at rest: an update while + // moving would cancel the z-1 prefetch just to request it again. + const atRest = settle && !interacting; + setViewState(to.target, to.zoom, { tiles: !atRest }); + if (settle) { + settleView(); + } + return; + } + // A flight starts once the level it pulls out to has arrived. + flightTrail = null; + anim = { from: { ...vs, target: [...vs.target] }, to, anchor, + start: flight ? null : now(), created: now(), ms, flight }; + updateTiles(); + stepAnimation(); + } + + // The path, duration and pulled-out level of a jump far enough to fly, + // or null. + function planFlight(to) { + if (!prefs.smooth()) { + return null; + } + const dist = Math.hypot(to.target[0] - vs.target[0], + to.target[1] - vs.target[1]); + const far = dist * Math.pow(2, Math.min(vs.zoom, to.zoom)) + > kFlightViews * Math.max(vs.width, vs.height); + if (!far && Math.abs(to.zoom - vs.zoom) <= kMaxAnimatedZoomDelta) { + return null; + } + const path = flyPath(vs, { ...vs, ...to }); + let zMin = Infinity; + let rect = null; + for (let i = 0; i <= 16; i++) { + const p = path.at(i / 16); + zMin = Math.min(zMin, p.zoom); + const r = viewWorldRect({ ...vs, ...p }); + rect = rect ? [Math.min(rect[0], r[0]), Math.min(rect[1], r[1]), + Math.max(rect[2], r[2]), Math.max(rect[3], r[3])] + : r; + } + const z = Math.max(0, tileZoomFor(zMin)); + const range = tileRange(rect, z, tileSize()); + return { + path, + ms: Math.min(kFlightMaxMs, Math.max(kFlightMinMs, + kFlightMsPerS * path.S)), + apex: range ? { z, range } : null, + }; + } + + function apexReady(apex) { + return !apex || [...slots.values()].every( + (slot) => !slot.visible || slot.grid.settledIn(apex.z, apex.range)); + } + + function stepAnimation() { + if (!anim) { + return; + } + if (anim.start === null) { + if (!apexReady(anim.flight.apex) + && now() - anim.created < kFlightWaitMs) { + raf(stepAnimation); + return; + } + anim.start = now(); + } + const t = Math.min(1, (now() - anim.start) / anim.ms); + const e = easeOutCubic(t); + let zoom = anim.from.zoom + (anim.to.zoom - anim.from.zoom) * e; + let target; + if (anim.flight) { + ({ target, zoom } = anim.flight.path.at(easeInOutCubic(t))); + } else if (anim.anchor) { + target = zoomAroundTarget(anim.from, anim.anchor, zoom); + } else { + target = [anim.from.target[0] + (anim.to.target[0] + - anim.from.target[0]) * e, + anim.from.target[1] + (anim.to.target[1] + - anim.from.target[1]) * e]; + } + if (t >= 1) { + const to = anim.to; + flightTrail = anim.flight ? anim.flight.apex : null; + anim = null; + // settleView updates the tiles at rest, as animateTo's cut does. + setViewState(to.target, to.zoom, { tiles: interacting }); + settleView(); + return; + } + setViewState(target, zoom); + raf(stepAnimation); + } + + // ─── Tiles ────────────────────────────────────────────────────────── + // The view the tiles are for: the destination of an animation. + function tileView() { + if (!anim) { + return vs; + } + return { ...vs, target: anim.to.target, zoom: anim.to.zoom }; + } + + function updateTiles() { + if (slots.size === 0) { + return; + } + const hiding = prefs.doubleBuffer(); + const z = clampZoom(tileZoomFor(vs.zoom, { + targetZoom: anim ? anim.to.zoom : null, + hidingNewLevels: hiding, + }), { minZoom: 0, maxZoom: MAX_TILE_ZOOM }); + const dest = tileView(); + const range = tileRange(viewWorldRect(dest), z, tileSize()); + const ring = growRange(range); + const shown = swap.shownZ; + const frozen = prefs.defer() && (interacting || gesturing); + // Frozen, the grids keep their old level, so the swap must too. + if (!frozen) { + swap.setZoom(z, { + hasContent: [...slots.values()].some( + (s) => s.visible && shown !== null + && s.grid.hasContentAt(shown)), + }); + } + // At rest only: it is background work and must not compete with the + // view while it moves. + const extra = []; + const apex = flightApex(); + if (!anim && !interacting && !moving && swap.pendingZ === null) { + prefetchZ = z > 0 ? z - 1 : null; + // A landed flight's level already covers the view. + if (prefetchZ !== null && prefetchZ !== apex?.z) { + extra.push({ z: prefetchZ, range: tileRange( + growRect(viewWorldRect(dest), kPrefetchMargin), prefetchZ, + tileSize()) }); + } + } + if (apex) { + extra.push({ ...apex, background: false }); + } + // On screen now, which differs from `range` while animating. + const hold = anim ? tileRange(viewWorldRect(vs), z, tileSize()) : null; + for (const slot of slots.values()) { + if (slot.visible && !frozen) { + slot.grid.update({ z, range, ring, extra, hold }); + } + } + checkSwap(); + } + + // The level a flight pulls out to, while it flies and until it lands. + function flightApex() { + return (anim && anim.flight && anim.flight.apex) || flightTrail; + } + + // Levels drawn under the shown ones where those have no tile, coarsest + // first: a flight's pulled-out level, the level waiting to be revealed + // and, on a zoom out past it, the level above loaded at rest. + function underLevels(drawn) { + const changing = swap.pendingZ !== null || swap.under.length > 0; + const above = changing && prefetchZ !== null + && swap.wantedZ() < prefetchZ ? prefetchZ : null; + const out = []; + for (const z of [flightApex()?.z, swap.pendingZ, above]) { + if (z != null && !out.includes(z) + && !drawn.some((l) => l.z === z)) { + out.push(z); + } + } + return out.sort((a, b) => a - b); + } + + // Once a level change has landed, fetch the level above it too. + function schedulePrefetch() { + if (prefetchPending) { + return; + } + prefetchPending = true; + queueMicrotask(() => { + prefetchPending = false; + updateTiles(); + }); + } + + function allSettled() { + for (const slot of slots.values()) { + if (slot.visible && !slot.grid.isSettled()) { + return false; + } + } + return true; + } + + function checkSwap(tile) { + // Only a level on its way in or out needs the walk over every tile. + const settled = (swap.pendingZ !== null || swap.under.length > 0 + || flightTrail !== null) && allSettled(); + const changed = swap.check({ settled, animating: !!anim }); + if (changed && swap.pendingZ === null) { + schedulePrefetch(); + } + let landed = false; + if (flightTrail && !anim && swap.isIdle() && settled) { + flightTrail = null; + landed = true; + } + // A tile of a level not drawn (the prefetch) changes nothing on screen. + if (changed || landed || !tile || drawsLevel(tile.z)) { + scheduleRender(); + } + } + + function drawsLevel(z) { + const drawn = swap.plan(now()).draw; + return drawn.some((l) => l.z === z) || underLevels(drawn).includes(z); + } + + function addTileSlot(id, { order, source, visible = true }) { + const wrapped = { + load: (coords, o) => source.load(coords, o), + release: (drawable) => { + const tex = drawable && textures.get(drawable); + if (tex) { + textures.delete(drawable); + doomedTextures.push(tex); + } + source.release?.(drawable); + }, + }; + const slot = { + id, order, visible, + grid: new TileGrid({ source: wrapped, + onChange: (tile) => checkSwap(tile) }), + }; + slots.set(id, slot); + updateTiles(); + return { + setVisible(v) { + if (slot.visible === !!v) { + return; + } + slot.visible = !!v; + if (!slot.visible) { + slot.grid.clear(); + } + updateTiles(); + }, + isVisible: () => slot.visible, + refresh() { + if (slot.visible) { + slot.grid.refresh(); + scheduleRender(); + } + }, + }; + } + + function textureFor(drawable) { + if (!deckgl || !deckgl.device) { + return drawable.image; + } + let tex = textures.get(drawable); + if (!tex) { + try { + tex = deckgl.device.createTexture({ + data: drawable.image, + width: drawable.width, + height: drawable.height, + mipLevels: 1, + sampler: { minFilter: 'linear', magFilter: 'linear', + addressModeU: 'clamp-to-edge', + addressModeV: 'clamp-to-edge' }, + }); + } catch (e) { + return drawable.image; + } + textures.set(drawable, tex); + } + return tex; + } + + // ─── Rendering ────────────────────────────────────────────────────── + function flashFactor(t) { + if (t >= flashUntil) { + return 1; + } + const phase = ((kFlashMs - (flashUntil - t)) % kFlashPulseMs) / kFlashPulseMs; + return 1 - 0.7 * (0.5 - 0.5 * Math.cos(2 * Math.PI * phase)); + } + + // World bounds per tile object: a tile keeps its z, x and y. + let tileBounds = new WeakMap(); + let tileBoundsSize = null; + function boundsOf(tile) { + const T = tileSize(); + if (T !== tileBoundsSize) { + tileBounds = new WeakMap(); + tileBoundsSize = T; + } + let bounds = tileBounds.get(tile); + if (!bounds) { + bounds = tileWorldBounds(tile.z, tile.x, tile.y, T); + tileBounds.set(tile, bounds); + } + return bounds; + } + + // A layer for each drawn tile of `slot` at level z that overlaps `view`; + // `tag` keeps the ids of the tiles under the shown levels apart. + function pushTileLayers(out, slot, z, view, tag, opacity) { + for (const tile of slot.grid.drawableTilesAt(z)) { + const bounds = boundsOf(tile); + if (rectsOverlap(bounds, view)) { + out.push({ order: slot.order, props: { + id: `${slot.id}:${tag}${tile.key}`, + image: textureFor(tile.drawable), bounds, opacity, + parameters: noDepth, + } }); + } + } + } + + // The background, read once per tileLayers(): a style read per mask can + // force a recalc. + let maskFill = null; + function tileLayers(t, view) { + maskFill = null; + const out = []; + const plan = swap.plan(t); + if (!plan.fading && swap.pendingZ === null && plan.draw.length > 0) { + const keep = [...plan.draw.map((l) => l.z), prefetchZ, + flightApex()?.z].filter((z) => z != null); + for (const slot of slots.values()) { + slot.grid.prune(keep); + } + } + const flash = flashFactor(t); + const ordered = [...slots.values()].sort((a, b) => a.order - b.order); + const bottom = ordered.find((slot) => slot.visible); + const under = underLevels(plan.draw); + for (const slot of ordered) { + if (!slot.visible) { + continue; + } + if (slot === bottom && under.length > 0) { + out.push(...underlay(slot, under, plan.draw, view, flash)); + } + // Only the bottom slot can mask the older levels a reveal keeps + // under the shown one; the others would draw them twice. + const levels = slot === bottom || plan.fading + ? plan.draw : plan.draw.slice(-1); + levels.forEach((level, i) => { + if (i > 0 && slot === bottom && !plan.fading) { + out.push(...maskOver(slot, [level.z], view, + `${slot.id}:mask:draw:${level.z}`, + { settledOnly: true })); + } + pushTileLayers(out, slot, level.z, view, '', + level.opacity * flash); + }); + } + return { layers: out, animate: plan.fading || t < flashUntil }; + } + + // While hidden levels load, their tiles fill what the shown levels do not + // cover, such as the new edges of a zoom out. A mask in the background + // color keeps them from showing through the shown tiles' clear pixels. + function underlay(slot, zs, levels, view, flash) { + const out = []; + for (const z of zs) { + const tiles = []; + pushTileLayers(tiles, slot, z, view, 'under:', flash); + if (tiles.length === 0) { + continue; + } + // A finer level hides the coarser ones under it. + if (out.length > 0) { + out.push(...maskOver(slot, [z], view, `${slot.id}:mask:${z}`)); + } + out.push(...tiles); + } + if (out.length > 0) { + out.push(...maskOver(slot, levels.map((l) => l.z), view, + `${slot.id}:mask`)); + } + return out; + } + + // The mask over the tiles of levels `zs` in view, or nothing. + // `settledOnly` leaves out a tile still painting, whose partial image + // lacks layers the levels under it still show. + function maskOver(slot, zs, view, id, { settledOnly = false } = {}) { + // One CSS px of overlap, so no seam opens between two masks. + const pad = 1 / Math.pow(2, vs.zoom); + const masks = []; + for (const tile of slot.grid.tiles.values()) { + // A tile that failed with no image hides nothing under it. + if (!zs.includes(tile.z) + || (tile.loading && (settledOnly || !tile.drawable)) + || (tile.failed && !tile.drawable)) { + continue; + } + const bounds = boundsOf(tile); + if (rectsOverlap(bounds, view)) { + const [x0, y0, x1, y1] = bounds; + masks.push([[x0 - pad, y0 - pad], [x1 + pad, y0 - pad], + [x1 + pad, y1 + pad], [x0 - pad, y1 + pad]]); + } + } + if (masks.length === 0) { + return []; + } + return [{ order: slot.order, kind: 'SolidPolygonLayer', props: { + id, data: masks, getPolygon: (d) => d, + getFillColor: maskFill || (maskFill = backgroundRgba()), + parameters: noDepth, + } }]; + } + + function backgroundRgba() { + return toRgba(cssColorToHex(getComputedStyle(container).backgroundColor) + || '#000'); + } + + // The layer specs of one overlay, built when it is set so deck keeps the + // same data until the shapes change. + function overlaySpecs(id, shapes, order) { + const out = []; + const fills = []; + const strokes = []; + const circles = []; + for (const s of shapes) { + if (s.kind === 'circle') { + circles.push(s); + continue; + } + const pts = s.kind === 'rect' + ? [[s.rect[0], s.rect[1]], [s.rect[2], s.rect[1]], + [s.rect[2], s.rect[3]], [s.rect[0], s.rect[3]]] + : s.points; + if (s.fill) { + fills.push({ polygon: pts, color: s.fill }); + } + if (s.stroke) { + const closed = s.kind === 'rect'; + strokes.push({ path: closed ? [...pts, pts[0]] : pts, + color: s.stroke, width: s.width || 1, + dash: s.dash || null }); + } + } + if (fills.length) { + out.push({ order, kind: 'SolidPolygonLayer', props: { + id: `${id}:fill`, data: fills, + getPolygon: (d) => d.polygon, getFillColor: (d) => d.color, + parameters: noDepth, + } }); + } + const solid = strokes.filter((d) => !d.dash); + const dashed = strokes.filter((d) => d.dash); + if (solid.length) { + out.push({ order, kind: 'PathLayer', props: { + id: `${id}:stroke`, data: solid, widthUnits: 'pixels', + getPath: (d) => d.path, getColor: (d) => d.color, + getWidth: (d) => d.width, + parameters: noDepth, + } }); + } + if (dashed.length) { + const props = { + id: `${id}:dash`, data: dashed, widthUnits: 'pixels', + getPath: (d) => d.path, getColor: (d) => d.color, + getWidth: (d) => d.width, + // The extension counts dashes in line widths. + getDashArray: (d) => d.dash.map((v) => v / d.width), + dashJustified: true, + parameters: noDepth, + }; + if (deckApi?.PathStyleExtension) { + props.extensions = [ + new deckApi.PathStyleExtension({ dash: true })]; + } + out.push({ order, kind: 'PathLayer', props }); + } + if (circles.length) { + out.push({ order, kind: 'ScatterplotLayer', props: { + id: `${id}:circle`, data: circles, + radiusUnits: 'pixels', lineWidthUnits: 'pixels', + getPosition: (d) => d.center, getRadius: (d) => d.radius, + stroked: true, filled: true, + getLineColor: (d) => d.stroke || [0, 0, 0, 0], + getFillColor: (d) => d.fill || [0, 0, 0, 0], + getLineWidth: (d) => d.width || 1, + parameters: noDepth, + } }); + } + return out; + } + + function shapeLayers() { + const out = []; + for (const specs of overlays.values()) { + out.push(...specs); + } + out.push(...images.values()); + return out; + } + + function buildDeckLayers(specs) { + return specs.map( + (spec) => new deckApi[spec.kind || 'BitmapLayer'](spec.props)); + } + + let lastLayerCount = 0; + function render() { + const t = now(); + // deck may draw a new view state before this runs again, so tiles + // half a view off screen are kept: a pan or a one-level zoom out + // then finds them already there. + const tiles = tileLayers(t, growRect(viewWorldRect(vs), 0.5)); + const specs = [...tiles.layers, ...shapeLayers()] + .sort((a, b) => a.order - b.order); + lastLayerCount = specs.length; + if (deckgl) { + deckgl.setProps({ layers: buildDeckLayers(specs) }); + } + for (const tex of doomedTextures.splice(0)) { + tex.destroy?.(); + } + positionMarkers(); + if (tiles.animate) { + scheduleRender(); + } + } + + // Share of the view inside the tile grid that shows a settled base tile + // of a level being drawn: the browser probes' blank metric. + function coverage() { + const nx = 32; + const ny = 20; + const slot = slots.get('base'); + if (!slot) { + return null; + } + const T = tileSize(); + const drawn = swap.plan(now()).draw; + const levels = [...drawn, ...underLevels(drawn).map((z) => ({ z }))]; + let inGrid = 0; + let shown = 0; + for (let j = 0; j < ny; j++) { + for (let i = 0; i < nx; i++) { + const [wx, wy] = unproject([(i + 0.5) * vs.width / nx, + (j + 0.5) * vs.height / ny], vs); + if (wx < 0 || wy < 0 || wx >= T || wy >= T) { + continue; + } + inGrid++; + const hit = levels.some(({ z }) => { + const S = T / 2 ** z; + const tile = slot.grid.tiles.get(tileKey( + z, Math.floor(wx / S), Math.floor((T - wy) / S))); + return tile && (tile.drawable || !tile.loading); + }); + if (hit) { + shown++; + } + } + } + return inGrid ? shown / inGrid : null; + } + + // ─── Markers ──────────────────────────────────────────────────────── + function markerGroup(group) { + if (!markers.has(group)) { + markers.set(group, { visible: true, items: new Map() }); + } + return markers.get(group); + } + + function placeMarker(m, visible) { + const [x, y] = project(m.world, vs); + m.el.style.display = visible ? '' : 'none'; + m.el.style.transform = `translate(${x}px, ${y}px)` + + (m.center ? ' translate(-50%, -50%)' : ''); + } + + function placeGroup(g) { + for (const m of g.items.values()) { + placeMarker(m, g.visible); + } + } + + function positionMarkers() { + for (const g of markers.values()) { + placeGroup(g); + } + } + + // ─── Public API ───────────────────────────────────────────────────── + function getSize() { + return { width: vs.width, height: vs.height }; + } + + const view = { + getContainer: () => container, + getSize, + getZoom: () => vs.zoom, + // The zoom an animation in flight will end on. + getTargetZoom: () => (anim ? anim.to.zoom : vs.zoom), + getCenter: () => [...vs.target], + project: (w) => project(w, vs), + unproject: (p) => unproject(p, vs), + on: events.on, + off: events.off, + + setLimits({ minZoom, maxZoom } = {}) { + if (minZoom !== undefined) { + limits.minZoom = minZoom; + } + if (maxZoom !== undefined) { + limits.maxZoom = maxZoom; + } + const z = clampZoom(vs.zoom, limits); + if (z !== vs.zoom) { + setViewState(vs.target, z); + } else if (deckgl) { + deckgl.setProps({ viewState: deckViewState() }); + } + events.emit('limits'); + }, + getLimits: () => ({ ...limits }), + + setView(center, zoom = vs.zoom, { animate } = {}) { + const to = { target: [center[0], center[1]], zoom }; + animateTo(to, animate === false ? { ms: 0 } : { curve: true }); + }, + + fitWorldRect(rect, { padding = [0, 0], animate } = {}) { + const fit = fitView(rect, vs, { padding, ...limits }); + animateTo(fit, animate === false ? { ms: 0 } : { curve: true }); + }, + + // Zoom by `delta` levels from the level an animation is heading to, + // keeping the point under `screenPt` still (the center when null). + // `settle: false` (with `animate: false`) keeps a fractional zoom for + // a gesture still under way; a later call settles it. + zoomAround(screenPt, delta, { animate, settle = true } = {}) { + const zoom = clampZoom(view.getTargetZoom() + delta, limits); + // At rest on a zoom limit there is nothing to move. + if (!anim && !moving && zoom === vs.zoom) { + return; + } + // An anchor holds what is under it now, as stepAnimation does. + const base = screenPt ? vs : tileView(); + const pt = screenPt || [vs.width / 2, vs.height / 2]; + const target = zoomAroundTarget(base, pt, zoom); + animateTo({ target, zoom }, + animate === false ? { ms: 0, settle } : { anchor: screenPt + ? pt : null }); + }, + zoomIn: () => view.zoomAround(null, 1), + zoomOut: () => view.zoomAround(null, -1), + + // `settle: false` (with `animate: false`) leaves a gesture's + // fractional zoom for the gesture to settle. + panByPx(dx, dy, { animate, settle = true } = {}) { + const base = tileView(); + const s = Math.pow(2, base.zoom); + const target = [base.target[0] + dx / s, base.target[1] - dy / s]; + const ms = (animate === false || !prefs.smooth()) ? 0 : ANIMATION_MS; + animateTo({ target, zoom: base.zoom }, { ms, settle }); + }, + + invalidateSize, + // The preferences are read live; re-plan the tiles for defer and + // double buffering. + applyPrefs() { + updateTiles(); + }, + // view-input streams a wheel or trackpad gesture between these; + // deferred tile updates wait for its end, as they do for a drag. + setGesture(on) { + if (gesturing === !!on) { + return; + } + gesturing = !!on; + if (!gesturing) { + updateTiles(); + } + }, + + addTileSlot, + + setOverlay(id, shapes, { order = DRAW_ORDER.selection } = {}) { + if (!shapes || shapes.length === 0) { + // Clearing what is not there changes nothing on screen. + if (!overlays.delete(id)) { + return; + } + } else { + overlays.set(id, overlaySpecs(id, shapes, order)); + } + scheduleRender(); + }, + + setImageOverlay(id, spec, { order = DRAW_ORDER.pathImage } = {}) { + if (!spec) { + images.delete(id); + } else { + images.set(id, { order, kind: 'BitmapLayer', props: { + id: `image:${id}`, image: spec.image, bounds: spec.rect, + parameters: noDepth, + } }); + } + scheduleRender(); + }, + + // A DOM element pinned to a world point: its top-left corner, or its + // center with `center`. + addMarker(group, id, world, el, { center = false } = {}) { + const g = markerGroup(group); + const old = g.items.get(id); + if (old) { + old.el.remove(); + } + el.classList.add('or-view-marker'); + markerLayer.appendChild(el); + const m = { el, world: [world[0], world[1]], center }; + g.items.set(id, m); + placeMarker(m, g.visible); + return el; + }, + moveMarker(group, id, world) { + const g = markerGroup(group); + const m = g.items.get(id); + if (m) { + m.world = [world[0], world[1]]; + placeMarker(m, g.visible); + } + }, + clearMarkers(group) { + const g = markerGroup(group); + for (const m of g.items.values()) { + m.el.remove(); + } + g.items.clear(); + }, + setMarkerGroupVisible(group, visible) { + const g = markerGroup(group); + g.visible = !!visible; + placeGroup(g); + }, + + // The ruler and label tools each hold a crosshair mode. + setCursorMode(mode, on = true) { + if (on) { + cursorModes.add(mode); + } else { + cursorModes.delete(mode); + } + container.classList.toggle(`${mode}-mode-cursor`, !!on); + // deck sets the cursor on its canvas from getCursor, but only on + // the next pointer event; apply the change now. + const canvas = deckgl && deckgl.getCanvas && deckgl.getCanvas(); + if (canvas) { + canvas.style.cursor = cursorModes.size ? 'crosshair' : 'default'; + } + }, + + // The DRC widget's attention pulse on the tiles. + flashTiles() { + flashUntil = now() + kFlashMs; + scheduleRender(); + }, + + // Resolves once every visible slot has loaded what is on screen and + // no level change or animation is in progress, or after + // kSettleTimeoutMs. + whenTilesSettled() { + const deadline = now() + kSettleTimeoutMs; + return new Promise((resolve) => { + const poll = () => { + if ((allSettled() && swap.isIdle() && !anim && !moving) + || now() >= deadline) { + resolve(); + return; + } + setTimeout(poll, 32); + }; + poll(); + }); + }, + + // `{ image, rect }`: a copy of the frame with the current layers and + // where the canvas sits, for Save image. deck applies new layers in + // its own frame, so wait for one and copy it while it is drawn. + captureCanvas({ timeoutMs = 500 } = {}) { + if (!deckgl?.getCanvas()) { + return Promise.resolve(null); + } + return new Promise((resolve) => { + let finished = false; + // The timeout's redraw may itself run done() through + // onAfterRender; one copy is enough. + const done = () => { + if (finished) { + return; + } + finished = true; + clearTimeout(timer); + afterFrame = afterFrame.filter((fn) => fn !== done); + const canvas = deckgl?.getCanvas(); + resolve(canvas ? { image: copyCanvas(canvas), + rect: canvas.getBoundingClientRect() } + : null); + }; + // A hidden page gets no frames. + const timer = setTimeout(() => { + deckgl?.redraw('capture'); + done(); + }, timeoutMs); + afterFrame.push(done); + render(); + }); + }, + + debugSnapshot() { + const plan = swap.plan(); + return { + zoom: vs.zoom, target: [...vs.target], + width: vs.width, height: vs.height, + animating: !!anim, moving, interacting, + shownZ: swap.shownZ, pendingZ: swap.pendingZ, + fading: plan.fading, drawLevels: plan.draw, + layers: lastLayerCount, coverage: coverage(), + overlays: [...overlays.keys()], + markers: Object.fromEntries([...markers].map( + ([group, g]) => [group, g.items.size])), + slots: [...slots.values()].map((s) => ({ + id: s.id, visible: s.visible, settled: s.grid.isSettled(), + ...s.grid.stats(), + })), + }; + }, + }; + return view; +} diff --git a/openroad/web/src/leaflet-global.js b/openroad/web/src/leaflet-global.js deleted file mode 100644 index fc7949fe92c..00000000000 --- a/openroad/web/src/leaflet-global.js +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// Copyright (c) 2026, The OpenROAD Authors - -// Leaflet sets window.L as it loads; the entries import this module first. The -// modules using L read the global, so their unit tests can load them with no DOM. - -import 'leaflet'; diff --git a/openroad/web/src/main.js b/openroad/web/src/main.js index f30b4bffafd..14e7f213e6e 100644 --- a/openroad/web/src/main.js +++ b/openroad/web/src/main.js @@ -2,20 +2,16 @@ // Copyright (c) 2026, The OpenROAD Authors import { GridLayoutManager } from './grid-layout.js'; -import { latLngToDbu, dbuToLatLng, dbuRectToBounds } from './coordinates.js'; +import { dbuToWorld, dbuRectToWorldRect, worldToDbu } from './coordinates.js'; import { WebSocketManager } from './websocket-manager.js'; +import { createLayoutView, DRAW_ORDER } from './layout-view.js'; +import { installViewInput, placementClicks } from './view-input.js'; import { - createWebSocketTileLayer, - createOverlayTileLayer, - currentDpr, - floorClampZoom, -} from './websocket-tile-layer.js'; -import { createMergedTileLayer } from './merged-tile-layer.js'; -import { installDeviceGridSnapping } from './device-pixels.js'; + buildHeatmapRequest, buildOverlayRequest, createImageSource, +} from './tile-sources.js'; import { - BLANK_TILE, hasEntries, releaseTileBlob, setTileSrc, tileSizeCss, - useFittedTileSize, useStaticTileSize, withDeviceExactTileSize, - watchDevicePixelRatio, tileSizeFields, + hasEntries, tileSizeCss, useFittedTileSize, useStaticTileSize, + watchDevicePixelRatio, } from './tile-request.js'; import { TimingWidget } from './timing-widget.js'; import { ClockTreeWidget } from './clock-tree-widget.js'; @@ -23,12 +19,12 @@ import { ChartsWidget } from './charts-widget.js'; import { HierarchyPanel, resetHierarchyOverlay } from './hierarchy-panel.js'; import { createInspectorPanel } from './inspector.js'; import { SelectionBrowser } from './selection-browser.js'; -import { applyArrowStep, applySelectionFlags, beginSelection, boundsEqual, - buildMapOptions, buildVisibilityFlags, clampArrowStep, - computeBoundsTransforms, computeScaleBar, - fittedTileSizeCss, formatDbu, formatDistance, installWheelPanning, - isCurrentSelection, isStaticMode, maxUsefulZoom, parseDbu, - rafCoalesce, showToast, unitLabel, websocketUrlFrom } +import { applySelectionFlags, beginSelection, boundsEqual, + buildVisibilityFlags, clampArrowStep, computeBoundsTransforms, + computeScaleBar, fittedTileSizeCss, formatDbu, + formatDistance, isCurrentSelection, isStaticMode, maxUsefulZoom, + parseDbu, rafCoalesce, renderingWarning, showCornerWarning, + showToast, unitLabel, websocketUrlFrom } from './ui-utils.js'; import { clampFontScale, showAppFontDialog, showArrowStepDialog } from './options-dialogs.js'; @@ -43,7 +39,8 @@ import { SchematicWidget } from './schematic-widget.js'; import { DrcWidget } from './drc-widget.js'; import { TclCompleter } from './tcl-completer.js'; import { getCookie, setCookie, applyGLTheme, persistTheme } from './theme.js'; -import { serializeDisplayState, applyDisplayStateEntries } from './display-state.js'; +import { serializeDisplayState, applyDisplayStateEntries, renderPrefs } + from './display-state.js'; import { updateDocumentTitle } from './title.js'; import { ThreeDViewerWidget } from './3d-viewer-widget.js'; import { ContextMenu } from './context-menu.js'; @@ -98,8 +95,13 @@ function updateStatus() { // earns space on screen once the queue is long enough to be the // explanation for a viewer that feels stuck. if (pendingCount > PENDING_BACKLOG) { - statusDiv.innerHTML = '
pending: ${pendingCount}
`; + const text = `pending: ${pendingCount}`; + const shown = statusDiv.firstElementChild; + if (!shown?.classList.contains('pending-indicator') + || shown.textContent !== text) { + statusDiv.innerHTML = '
${text}
`; + } statusDiv.style.display = 'block'; } else { statusDiv.style.display = 'none'; @@ -108,17 +110,25 @@ function updateStatus() { setTileProgress(pendingCount); } -// Show the tile-request line while requests are outstanding. A no-op when the -// Layout panel is closed, which is the only place the line lives. +// Show the tile-request line while requests are outstanding. A no-op until +// the Layout panel, the only place the line lives, is built. function setTileProgress(pendingCount) { const el = app.tileProgressEl; if (!el) return; el.classList.toggle('active', pendingCount > 0); // The count is worth keeping for anyone diagnosing a slow server, just not // worth a chip on screen. - el.title = pendingCount > 0 ? `${pendingCount} tile requests pending` : ''; + const title = pendingCount > 0 + ? `${pendingCount} tile requests pending` : ''; + if (el.title !== title) { + el.title = title; + } } +// The manager reports every request, reply and cancel; the DOM needs one +// update per frame. +const scheduleUpdateStatus = rafCoalesce(updateStatus); + // ─── Component Factories ──────────────────────────────────────────────────── // Cookies hold values verbatim (their writers encode), and a CSS font stack @@ -140,18 +150,16 @@ function decodeCookie(value) { // Components receive this via closure now; when extracted to separate files // they'll receive it as an explicit parameter. const app = { - map: null, - // Zoom-to-fit box in latlng, Qt's 5% margin per dimension already added - // (computeBoundsTransforms). Anything wanting the design's own extent - // has to work from the DBU rects, not from this. - fitBounds: null, - lastSelectionBounds: null, // Leaflet bounds of the last selected object + view: null, // the layout view (layout-view.js) + // Zoom-to-fit rect in world units, Qt's 5% margin per dimension already + // added (computeBoundsTransforms). Anything wanting the design's own + // extent has to work from the DBU rects, not from this. + fitRect: null, selHasInst: false, // selection contains any instance selHasNet: false, // selection contains any net displayControlsEl: null, allLayers: [], designScale: null, // pixels-per-DBU for coordinate conversion - designMaxDXDY: null, // max(width, height) in DBU for Y-axis mapping designOriginX: 0, // bounds.xMin() in DBU (tile grid origin) designOriginY: 0, // bounds.yMin() in DBU (tile grid origin) websocketManager: null, // set after construction below @@ -160,14 +168,9 @@ const app = { techData: null, inspectorEl: null, tclOutputEl: null, - highlightRect: null, - hoverHighlightLayer: null, - hoverHighlightPane: 'hover-highlight-pane', + // Draw-list items of the pseudo layers (display-controls.js). modulesLayer: null, clustersLayer: null, - pinsLayer: null, - // [{ def, layer }] per overlay the tech response lists. - overlayLayers: [], focusNets: new Set(), routeGuideNets: new Set(), visibleLayers: new Set(), @@ -188,7 +191,7 @@ const app = { chipletNonselectableLayers: {}, // Per-row fill pattern, keyed by the Display Controls row id → int matching // the server's FillPattern enum (1 = solid). Populated/persisted by - // display-controls.js and read lazily by websocket-tile-layer.js. + // display-controls.js and read lazily by tile-request.js. layerPatterns: {}, useTrueZ: getCookie('or_use_true_z') === '1', showDbu: getCookie('or_show_dbu') === '1', @@ -201,6 +204,8 @@ const app = { wheelZoom: getCookie('or_wheel_zoom') !== '0', // Qt's "Arrow keys scroll step", in CSS px. arrowStep: clampArrowStep(getCookie('or_arrow_step')), + // Rendering preferences: smoothing, double buffering, defer. + ...renderPrefs(getCookie), // Qt's "Application font", split into the CSS family and a percentage // scale over the stylesheet's authored sizes. Empty family = the // stylesheet default. @@ -214,7 +219,7 @@ const app = { selectableLayers: new Set(), heatMapData: null, activeHeatMap: '', - heatMapLayer: null, + heatMapLayer: null, // the heat-map tile slot heatMapLegendEl: null, renderHeatMapControls: null, rulerManager: null, @@ -423,142 +428,49 @@ try { // Ignore malformed cookie. } -// `app` is forwarded so the tile layer can read app.visibleChiplets -// lazily on every request — the field is populated by display-controls -// once the server's tech metadata arrives. -const WebSocketTileLayer = createWebSocketTileLayer( - visibility, app.visibleLayerNames, selectability, app.selectableLayers, - app); - -// ─── Tile grouping ────────────────────────────────────────────────────────── -// -// One pane per tech layer per chiplet puts a multi-die design at ~97 panes and -// ~582 MB of decoded tile images, past the browser's ~458 MB ceiling, where -// Chrome discards decodes and the discarded regions paint white until something -// forces a full invalidation. Merging the routing layers into N canvas panes, -// N derived from a memory budget, bounds the total regardless of how many layers -// or chiplets the design has. -// -// ?mergetiles=0 legacy one-pane-per-layer, for A/B comparison -// ?tilebudget= override the budget (default 350 MB) -// ?mergegroups= pin N directly, bypassing the budget -(function configureTileMerging() { +// Debug switch for the view: +// ?preservebuffer=1 keep the canvas readable between frames (probes) +(function configureViewDebug() { let params = null; try { params = new URLSearchParams(window.location.search); } catch (_) { - params = null; - } - const param = (name) => (params ? params.get(name) : null); - - app.mergeTiles = param('mergetiles') !== '0'; - const budgetMB = Number(param('tilebudget')); - if (Number.isFinite(budgetMB) && budgetMB > 0) { - app.tileBudgetBytes = Math.round(budgetMB * 1024 * 1024); - } - const groups = Number(param('mergegroups')); - if (Number.isFinite(groups) && groups > 0) { - app.mergeGroupCount = Math.floor(groups); + return; } - // display-controls reads dpr through app so it does not have to import a - // layer module just to size the memory budget. - app.tileDpr = currentDpr; - app.MergedTileLayer = createMergedTileLayer({ - visibility, - selectability, - visibleLayers: app.visibleLayerNames, - selectableLayers: app.selectableLayers, - app, - }, { dpr: currentDpr }); + app.preserveBuffer = params.get('preservebuffer') === '1'; })(); -const HeatMapTileLayer = L.GridLayer.extend({ - initialize: function(websocketManager, appState, options) { - this._websocketManager = websocketManager; - this._appState = appState; - // Same grid as the layer tiles it is drawn over. - L.GridLayer.prototype.initialize.call( - this, withDeviceExactTileSize(options)); - }, - - // Upscale-only display, same as the layout tile layer: the map rests on - // integer zoom so heatmap tiles show 1:1 with no fractional rescaling. - _clampZoom: function(zoom) { - return L.GridLayer.prototype._clampZoom.call( - this, floorClampZoom(this, zoom)); - }, - - // Ask the server for one tile of the active heat map. A null payload is - // an empty response -- no populated bin here, or the tile is off the grid - // -- and the 1x1 BLANK_TILE stands in, so nothing is decoded and onload - // still fires to complete the tile. - _requestTile: function(tile, coords) { - const active = this._appState.activeHeatMap; - if (!active) { - setTileSrc(tile, BLANK_TILE); - return; - } - this._websocketManager.request({ - type: 'heatmap_tile', - name: active, - z: coords.z, - x: coords.x, - y: coords.y, - // Sized like the layer tiles beneath it; without this the heat map - // is a 256 px image stretched over crisp layers on any HiDPI - // display. - ...tileSizeFields(currentDpr(), this.getTileSize().x), - }).then(blob => { - setTileSrc(tile, blob ? URL.createObjectURL(blob) : BLANK_TILE); - }).catch(() => { - setTileSrc(tile, BLANK_TILE); - }); - }, - - createTile: function(coords, done) { - const tile = document.createElement('img'); - tile.alt = ''; - tile.setAttribute('role', 'presentation'); - tile._tileDone = false; - tile.onload = () => { - releaseTileBlob(tile); - if (!tile._tileDone) { - tile._tileDone = true; - done(null, tile); - } - }; - tile.onerror = () => { - if (!tile._tileDone) { - tile._tileDone = true; - done(new Error('heat map tile load error'), tile); - } - }; - this._requestTile(tile, coords); - return tile; - }, +// What every layout tile request reads lazily (tile-request.js): the +// visibility flags, visible layers and chiplets change after startup. +app.tileCtx = { + visibility, selectability, visibleLayers: app.visibleLayerNames, + selectableLayers: app.selectableLayers, app, +}; - refreshTiles: function() { - if (!this._map) return; - for (const key in this._tiles) { - const tileInfo = this._tiles[key]; - if (!tileInfo || !tileInfo.el) continue; - this._requestTile(tileInfo.el, tileInfo.coords); - } - }, -}); +// The heat map: one server image per tile, drawn over the layout and only +// while a heat map is active. +function createHeatMapSlot() { + return app.view.addTileSlot('heatmap', { + order: DRAW_ORDER.heatmap, + visible: !!app.activeHeatMap, + source: createImageSource({ + wm: app.websocketManager, + buildRequest: (c, dpr, t) => buildHeatmapRequest(c, dpr, t, app), + }), + }); +} function updateHeatMaps(data) { app.heatMapData = data; app.activeHeatMap = data.active || ''; if (app.heatMapLayer) { - if (app.activeHeatMap) { - if (!app.map.hasLayer(app.heatMapLayer)) { - app.heatMapLayer.addTo(app.map); - } - } else if (app.map.hasLayer(app.heatMapLayer)) { - app.map.removeLayer(app.heatMapLayer); + // Turning visible already requests the tiles; refresh only a map + // that was on screen and may have changed. + const wasVisible = app.heatMapLayer.isVisible(); + app.heatMapLayer.setVisible(!!app.activeHeatMap); + if (wasVisible) { + app.heatMapLayer.refresh(); } - app.heatMapLayer.refreshTiles(); } if (app.renderHeatMapControls) { app.renderHeatMapControls(data); @@ -571,7 +483,7 @@ app.updateHeatMaps = updateHeatMaps; // geometry tiles are not re-rendered. function refreshOverlay() { if (app.overlayLayer) { - app.overlayLayer.refreshTiles(); + app.overlayLayer.refresh(); } } // Every selection/highlight mutation refreshes the overlay, so this single @@ -592,29 +504,19 @@ function redrawAllLayers() { // Keep the server's saved-state snapshot current for save_display_controls. scheduleSyncDisplayState(); - // Pseudo layers included: they stay mounted and are gated on the visibility - // flag each request carries (`gate` in display-controls.js). - for (const layer of app.allLayers) { - layer.refreshTiles(); + // Pseudo layers included: they stay in their slots and are gated on the + // visibility flag each request reads (`gate` in display-controls.js). + for (const slot of app.allLayers) { + slot.refresh(); } if (app.heatMapLayer) { - app.heatMapLayer.refreshTiles(); - } - // Keep the client-side selection outline in sync with the "Highlight - // selected" toggle: detach it when off, re-attach it when back on (the - // rectangle object is preserved so the current selection survives an - // off→on round trip; the server-side highlight is gated by the overlay - // refresh below). An in-flight selection pulse is cancelled on off. - if (app.highlightRect) { - const showHighlight = visibility.highlight_selected !== false; - if (!showHighlight && app.map.hasLayer(app.highlightRect)) { - app.map.removeLayer(app.highlightRect); - } else if (showHighlight && !app.map.hasLayer(app.highlightRect)) { - app.highlightRect.addTo(app.map); - } + app.heatMapLayer.refresh(); } - if (!visibility.highlight_selected && app.clearSelectionPulse) { - app.clearSelectionPulse(); + // The client-side selection outline follows the "Highlight selected" + // toggle, and turning it off stops a pulse or animation in flight; the + // server-side highlight is gated by the overlay refresh below. + if (app.renderSelectionOutline) { + app.renderSelectionOutline(); } // Overlay layer must also refresh on structural changes (e.g. design // reload changes the coordinate space). @@ -655,13 +557,15 @@ function applyDisplayState(state) { const entries = state.entries; if (!entries || typeof entries !== 'object') return; applyDisplayStateEntries(entries); - // Preserve the current view so restoring controls doesn't move the map. + // Preserve the current view so restoring controls doesn't move the view. + // Kept in DBU: the world scale follows the tile size, which may change. try { - if (app.map && typeof sessionStorage !== 'undefined') { - const c = app.map.getCenter(); + if (app.view && app.designScale && typeof sessionStorage !== 'undefined') { + const [wx, wy] = app.view.getCenter(); + const { dbuX, dbuY } = worldToDbu(wx, wy, app.designScale, + app.designOriginX, app.designOriginY); sessionStorage.setItem('or_restore_view', - JSON.stringify({ lat: c.lat, lng: c.lng, - zoom: app.map.getZoom() })); + JSON.stringify({ dbuX, dbuY, zoom: app.view.getZoom() })); } } catch (_) { /* ignore */ } window.location.reload(); @@ -674,6 +578,23 @@ app.redrawAllLayers = redrawAllLayers; // Expose the WYSIWYG capture so the context menu "Save" can grab the scene. app.captureLayout = (opts = {}) => captureLayout(app, opts); +// Once per page load: the view reports its renderer again after a lost +// context or when reopened. Only the slow-but-working case can be silenced; +// without WebGL nothing is drawn. +let renderWarningShown = false; +function warnIfSoftwareRendering(info) { + const warning = renderingWarning(info); + if (!warning || renderWarningShown + || (warning.kind === 'software' + && getCookie('or_hide_software_warning') === '1')) { + return; + } + renderWarningShown = true; + showCornerWarning(warning.message, warning.kind !== 'software' ? {} : { + dontShowAgain: () => setCookie('or_hide_software_warning', '1'), + }); +} + function createLayoutViewer(container) { const mapDiv = document.createElement('div'); mapDiv.className = 'layout-viewer'; @@ -689,76 +610,73 @@ function createLayoutViewer(container) { // Tile requests in flight, as a line along the top of the canvas. Held on // app because updateStatus runs from the socket callbacks, which know - // nothing about this panel -- and the panel can be closed, so every write - // to it goes through setTileProgress below. + // nothing about this panel. const progress = document.createElement('div'); progress.className = 'or-progress'; mapDiv.appendChild(progress); app.tileProgressEl = progress; - // Closing the panel discards this DOM, so drop the references to it. Both - // readers null-check (setTileProgress here, updateHeatMapLegend in - // display-controls.js), and createLayoutViewer sets them again if the panel - // is reopened. - // - // app.map is deliberately left alone. Calling map.remove() and nulling it - // would be the matching cleanup, but ~140 call sites across eleven modules - // reach app.map, many of them unguarded -- the View menu's zoom items, the - // inspector's zoom-to, the rulers, the display controls -- so nulling it - // turns a detached-but-harmless map into a dozen ways to throw while the - // panel is closed. Guarding those is a lifecycle change, not a styling - // one. - container.on('destroy', () => { - app.tileProgressEl = null; - app.heatMapLegendEl = null; + app.view = createLayoutView(mapDiv, { + preserveDrawingBuffer: app.preserveBuffer, + prefs: { + smooth: () => app.controlSmoothing, + doubleBuffer: () => app.doubleBuffer, + defer: () => app.deferTileUpdates, + }, + isStatic: isStaticMode(app), }); - - app.map = L.map(mapDiv, buildMapOptions(undefined, { - wheelZoom: app.wheelZoom, - arrowStep: app.arrowStep, - })); - // Wheel pan/zoom per the Options preference (2.15). Skipped in a static - // report, which deliberately locks the zoom to the one pre-rendered level - // and turns Leaflet's own wheel zoom off. - if (!isStaticMode(app)) { - installWheelPanning(app.map, () => app.wheelZoom); - } - // On a fractional dpr, Leaflet's whole-CSS-pixel placement leaves tile - // boundaries mid-device-pixel and they show as dark hairlines; this nudges - // each tile container back onto the grid after every move. - installDeviceGridSnapping(app.map); + app.view.on('contextlost', () => { + console.warn('Layout view: WebGL context lost; rebuilding the view.'); + }); + app.view.on('contextfailed', () => { + showToast('The layout view lost its graphics context and could not ' + + 'get it back; reload the page.', 15000); + }); + app.view.on('renderer', warnIfSoftwareRendering); + // For the browser probes and debugging from the console. + window.__orView = app.view; // Tiles are rasterized for the ratio in force when they were requested and // are never revisited on their own, so a window moved to another monitor — // or a browser zoom change — leaves every tile stretched from the old ratio - // into the new box until something forces a refresh. Nothing did. - watchDevicePixelRatio(() => redrawAllLayers()); - const hoverPane = app.map.createPane(app.hoverHighlightPane); - hoverPane.style.zIndex = '650'; - hoverPane.style.pointerEvents = 'none'; - - // "Fit" button below the default zoom (+/-) control, top-left. - const FitControl = L.Control.extend({ - onAdd: function() { - const c = L.DomUtil.create( - 'div', 'leaflet-bar leaflet-control leaflet-control-fit'); - const a = L.DomUtil.create('a', '', c); - a.href = '#'; - a.title = 'Fit'; - a.setAttribute('role', 'button'); - a.setAttribute('aria-label', 'Fit'); - a.textContent = '⤢'; - L.DomEvent.on(a, 'click', L.DomEvent.stop) - .on(a, 'click', () => { - if (app.fitBounds) app.map.fitBounds(app.fitBounds); - }); - return c; - }, + // into the new box until something forces a refresh. + watchDevicePixelRatio(() => { + app.view.invalidateSize(); + redrawAllLayers(); }); - new FitControl({ position: 'topleft' }).addTo(app.map); - new ResizeObserver(() => { - app.map.invalidateSize({ animate: false }); - }).observe(mapDiv); + // Zoom in / out and Fit, top-left. + const zoomControl = document.createElement('div'); + zoomControl.className = 'or-zoom-control'; + const zoomButtons = []; + for (const [label, title, action] of [ + ['+', 'Zoom in', () => app.view.zoomIn()], + ['\u2212', 'Zoom out', () => app.view.zoomOut()], + ['\u2922', 'Fit', () => { + if (app.fitRect) app.view.fitWorldRect(app.fitRect); + }], + ]) { + const button = document.createElement('button'); + button.type = 'button'; + button.title = title; + button.setAttribute('aria-label', title); + button.textContent = label; + button.addEventListener('click', (e) => { + e.stopPropagation(); + action(); + }); + zoomControl.appendChild(button); + zoomButtons.push(button); + } + mapDiv.appendChild(zoomControl); + // Disabled at the zoom limits, so a press that cannot zoom says so. + const syncZoomButtons = () => { + const { minZoom, maxZoom } = app.view.getLimits(); + const z = app.view.getTargetZoom(); + zoomButtons[0].disabled = z >= maxZoom; + zoomButtons[1].disabled = z <= minZoom; + }; + app.view.on('zoom zoomend limits', syncZoomButtons); + syncZoomButtons(); // Scale bar and coordinate readout share one HUD at the bottom-left of // the viewer. The scale bar is a display option and hides on its own, so @@ -790,27 +708,38 @@ function createLayoutViewer(container) { } syncHud(); - app.map.on('mousemove', (e) => { - app.lastMouseLatLng = e.latlng; - if (!app.designScale) return; - const { dbuX, dbuY } = latLngToDbu( - e.latlng.lat, e.latlng.lng, app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY); - coordBar.textContent = `X: ${app.formatDbu(dbuX)} Y: ${app.formatDbu(dbuY)}`; - syncHud(); - }); - app.map.on('mouseout', (e) => { - // Leaflet raises mouseout for a move onto anything inside the - // container too -- a zoom control, a marker, the HUD itself -- and - // both the readout and the zoom anchor should hold their values for - // those. Only a move that actually leaves the viewer clears them. - const to = e.originalEvent && e.originalEvent.relatedTarget; - if (to && mapDiv.contains(to)) { - return; - } - app.lastMouseLatLng = null; - coordBar.textContent = ''; - syncHud(); + // Pointer input: wheel, keys, clicks, boxes. Drag-panning is the view's. + installViewInput(app.view, { + isStatic: () => isStaticMode(app), + wheelZoom: () => app.wheelZoom, + arrowStep: () => app.arrowStep, + ...placementClicks(app), + onContextClick: (world, e) => { + if (app.onMapContextClick) { + app.onMapContextClick(world, e); + } + }, + onMove: (world, e) => { + // The world point, not the screen one: the Z keys zoom around it + // even after the view has moved under a still pointer. + app.lastMouseWorld = world; + if (app.rulerManager && app.rulerManager.isActive()) { + app.rulerManager.handleMouseMove(world, e); + } + if (!app.designScale) return; + const { dbuX, dbuY } = worldToDbu( + world[0], world[1], app.designScale, + app.designOriginX, app.designOriginY); + coordBar.textContent = `X: ${app.formatDbu(dbuX)} Y: ${app.formatDbu(dbuY)}`; + syncHud(); + }, + // pointerleave does not fire for moves onto the zoom control or the + // HUD inside the viewer, so the readout holds for those. + onLeave: () => { + app.lastMouseWorld = null; + coordBar.textContent = ''; + syncHud(); + }, }); const SB_H = 22; // svg height @@ -854,9 +783,9 @@ function createLayoutViewer(container) { return; } // Pixels per DBU at current zoom: designScale * 2^zoom. - const pxPerDbu = app.designScale * Math.pow(2, app.map.getZoom()); - // Target bar width: ~15% of the map container width. - const containerWidth = app.map.getContainer().clientWidth || 400; + const pxPerDbu = app.designScale * Math.pow(2, app.view.getZoom()); + // Target bar width: ~15% of the view width. + const containerWidth = app.view.getSize().width || 400; const sb = computeScaleBar({ targetPx: containerWidth * 0.15, pxPerDbu, @@ -875,10 +804,9 @@ function createLayoutViewer(container) { // Coalesce updates during continuous zoom gestures so the bar tracks // the animation instead of only snapping at gesture end. Pan doesn't - // change the bar (geometry depends only on zoom and container width), - // so 'move'/'moveend' are deliberately not listened to. + // change the bar (geometry depends only on zoom and container width). const scheduleUpdateScaleBar = rafCoalesce(updateScaleBar); - app.map.on('zoom zoomend resize', scheduleUpdateScaleBar); + app.view.on('zoom zoomend resize', scheduleUpdateScaleBar); app.updateScaleBar = updateScaleBar; app.rulerManager = new RulerManager(app, visibility, updateInspector, focusComponent); @@ -1241,14 +1169,16 @@ app.goldenLayout.registerComponentFactoryFunction('SelectHighlight', createSelec const staticCache = window.__STATIC_CACHE__ || null; if (staticCache) { - // Before any layer or the map scale is built: a report's tiles are baked at - // a fixed size and cannot be re-rendered to fit a different box. + // Before any layer or the view scale is built: a report's tiles are baked + // at a fixed size and cannot be re-rendered to fit a different box. useStaticTileSize(); - app.websocketManager = WebSocketManager.fromCache(staticCache, updateStatus); + app.websocketManager = WebSocketManager.fromCache(staticCache, + scheduleUpdateStatus); } else { const websocketUrl = websocketUrlFrom(window.location); app.websocketManager = new WebSocketManager( - websocketUrl, updateStatus, { probeUrl: window.location.href }); + websocketUrl, scheduleUpdateStatus, + { probeUrl: window.location.href }); // Where each tech layer has shapes, so tiles that would come back empty // are never requested (see layer-extents.js). Static reports have no // server to ask and keep requesting everything. @@ -1309,7 +1239,7 @@ app.toggleShowDbu = function() { app.showDbu = !app.showDbu; setCookie('or_show_dbu', app.showDbu ? '1' : '0'); // Re-render rulers so their labels update. - if (app.rulerManager) app.rulerManager._rerenderAll(); + if (app.rulerManager) app.rulerManager._renderAll(); // Both views format area through fmtArea(app, ...), which reads showDbu. if (app.hierarchyPanel) app.hierarchyPanel.refresh(); // Update scale bar. @@ -1337,13 +1267,37 @@ app.toggleWheelZoom = function() { scheduleSyncDisplayState(); }; -// Qt's Options > "Arrow keys scroll step". Leaflet caches the pan distance in -// its keyboard handler's key map, so the new step has to be pushed into it: -// see applyArrowStep. +// ── Rendering preferences ── +// +// The view reads all three live; double buffering and defer also re-plan the +// tiles at once, so a level held back by them is not left waiting. + +app.toggleControlSmoothing = function() { + app.controlSmoothing = !app.controlSmoothing; + setCookie('or_control_smoothing', app.controlSmoothing ? '1' : '0'); + scheduleSyncDisplayState(); +}; + +// Read per tile by the composite source and per zoom by the view. +app.toggleDoubleBuffer = function() { + app.doubleBuffer = !app.doubleBuffer; + setCookie('or_double_buffer', app.doubleBuffer ? '1' : '0'); + app.view?.applyPrefs(); + scheduleSyncDisplayState(); +}; + +// Read by the view on every move. +app.toggleDeferTileUpdates = function() { + app.deferTileUpdates = !app.deferTileUpdates; + setCookie('or_defer_tile_updates', app.deferTileUpdates ? '1' : '0'); + app.view?.applyPrefs(); + scheduleSyncDisplayState(); +}; + +// Qt's Options > "Arrow keys scroll step", read by view-input on every key. app.setArrowStep = function(step) { app.arrowStep = clampArrowStep(step); setCookie('or_arrow_step', String(app.arrowStep)); - applyArrowStep(app.map, app.arrowStep); scheduleSyncDisplayState(); }; @@ -1482,21 +1436,19 @@ function ensureDebugContinueButton() { // `designBounds` georeferences the tile grid; `fitRect` is what Fit frames. // They differ by the pin-label margin the server adds to the former. function applyBounds(designBounds, fitRect) { - // The map's whole coordinate system is defined in units of one tile, so + // The view's whole coordinate system is defined in units of one tile, so // this must be the size the layers actually use. const t = computeBoundsTransforms(designBounds, tileSizeCss(), fitRect); if (!t) return false; app.currentBounds = designBounds; app.designScale = t.scale; - app.designMaxDXDY = t.maxDXDY; app.designOriginX = t.originX; app.designOriginY = t.originY; - app.fitBounds = t.fitBounds; - // Bound the zoom before the first fit: the tile layers are L.GridLayer, - // which contributes no maxZoom, so the map would otherwise let the user - // zoom until the tile math degenerates. Set per design, since the cap - // depends on this design's scale. - app.map.setMaxZoom(maxUsefulZoom(t.scale)); + app.fitRect = t.fitRect; + // Bound the zoom before the first fit, or it climbs until the tile math + // degenerates. Per design, since the cap depends on its scale. + // Zoom 0 shows the whole tile grid; there is nothing further out. + app.view.setLimits({ minZoom: 0, maxZoom: maxUsefulZoom(t.scale) }); return true; } @@ -1504,7 +1456,7 @@ async function resyncBounds(inlineBounds, inlineFitBounds, { reloadOnChange = false } = {}) { // Returns true when it already redrew the layers (bounds changed), so // callers can avoid a second redundant redraw. - if (isStaticMode(app) || !app.map) return false; + if (isStaticMode(app) || !app.view) return false; let designBounds = inlineBounds; let fitRect = inlineFitBounds; if (!designBounds) { @@ -1528,26 +1480,31 @@ async function resyncBounds(inlineBounds, inlineFitBounds, window.location.reload(); return true; } + // A page that booted with no design has no layer tree to redraw into; + // it reloads once there are bounds to place one on. + if (app.booted && !app.designScale) { + if (!computeBoundsTransforms(designBounds, tileSizeCss(), fitRect)) { + return false; + } + reloadKeepingConsole(); + return true; + } // Keep the DBU point at the center of the view where it is. const hadDesign = !!app.designScale; + const [cx, cy] = app.view.getCenter(); const center = hadDesign - ? latLngToDbu(app.map.getCenter().lat, app.map.getCenter().lng, - app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY) + ? worldToDbu(cx, cy, app.designScale, app.designOriginX, + app.designOriginY) : null; if (!applyBounds(designBounds, fitRect)) return false; if (center) { - const ll = dbuToLatLng(center.dbuX, center.dbuY, app.designScale, - app.designMaxDXDY, app.designOriginX, - app.designOriginY); - app.map.setView(ll, app.map.getZoom(), { animate: false }); - } - // Client-side rectangles hold latlngs from the old transforms. - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; + app.view.setView(dbuToWorld(center.dbuX, center.dbuY, app.designScale, + app.designOriginX, app.designOriginY), + app.view.getZoom(), { animate: false }); } + // Client-side shapes hold world coordinates from the old transforms. + if (app.clearSelectionOutline) app.clearSelectionOutline(); redrawAllLayers(); return true; } @@ -1669,10 +1626,7 @@ app.websocketManager.onPush = (msg) => { // inspector and stale highlights. if (app.updateInspector) app.updateInspector(null); if (app.stopSelectionAnimation) app.stopSelectionAnimation(); - if (app.highlightRect && app.map) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } + if (app.clearSelectionOutline) app.clearSelectionOutline(); scheduleRefreshOverlay(); } else if (msg.type === 'heatmaps_changed') { // A heat map was registered server-side after this client connected @@ -1722,12 +1676,9 @@ app.websocketManager.onPush = (msg) => { } else if (msg.type === 'debug_refresh') { // Tiles would be turned away until the next pause, which redraws. if (app.scriptRunning) return; - // Instance positions changed — clear the stale Leaflet highlight - // outline (the tile-based highlight updates automatically). - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } + // Instance positions changed — clear the stale client-side outline + // (the tile-based highlight updates automatically). + if (app.clearSelectionOutline) app.clearSelectionOutline(); scheduleRedrawAllLayers(); } else if (msg.type === 'log') { // Logger output from the main Tcl thread (e.g. global_placement). @@ -1790,14 +1741,15 @@ app.websocketManager.readyPromise.then(async () => { const fitRect = boundsData.fit_bounds; // Size the tiles so the fit below lands on an integer zoom level. - // Must precede applyBounds, which derives the map's coordinate scale + // Must precede applyBounds, which derives the view's coordinate scale // from the tile size, and populateDisplayControls, which builds the // layers with it. Static reports are pre-rasterized at a fixed size // (useStaticTileSize above), so they are not free to choose. if (!staticCache) { - const viewport = app.map.getSize(); + const viewport = app.view.getSize(); useFittedTileSize(fittedTileSizeCss({ - designBounds, fitRect, viewW: viewport.x, viewH: viewport.y, + designBounds, fitRect, viewW: viewport.width, + viewH: viewport.height, })); } @@ -1809,38 +1761,26 @@ app.websocketManager.readyPromise.then(async () => { // placed. if (app.labelManager) app.labelManager.reload(); - app.map.fitBounds(app.fitBounds); - if (staticCache) { - // Lock to the pre-rendered tile zoom level and fit. + // Lock to the pre-rendered tile zoom level; the fit honours it. const cacheZoom = staticCache.zoom; - app.map.setMinZoom(cacheZoom); - app.map.setMaxZoom(cacheZoom); - app.map.fitBounds(app.fitBounds); - app.map.scrollWheelZoom.disable(); - app.map.touchZoom.disable(); - app.map.boxZoom.disable(); - app.map.doubleClickZoom.disable(); - - // Path highlight overlay image. NOT app.fitBounds, which + app.view.setLimits({ minZoom: cacheZoom, maxZoom: cacheZoom }); + } + app.view.fitWorldRect(app.fitRect, { animate: false }); + + if (staticCache) { + // Path highlight overlay image. NOT app.fitRect, which // carries Qt's framing margin: renderOverlayPng frames these // on the GEOREFERENCE rect, the one the tile grid is built // on, so the image has to be stretched over that same rect or // it lands offset from the tiles under it. - app.pathOverlay = L.imageOverlay( - '', - dbuRectToBounds(designBounds[0][1], designBounds[0][0], - designBounds[1][1], designBounds[1][0], - app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY), - { opacity: 1, interactive: false, zIndex: 1000 }); + const pathRect = dbuRectToWorldRect( + designBounds[0][1], designBounds[0][0], + designBounds[1][1], designBounds[1][0], + app.designScale, app.designOriginX, app.designOriginY); staticCache.setPathOverlay = (src) => { - if (src) { - app.pathOverlay.setUrl(src); - app.pathOverlay.addTo(app.map); - } else { - app.map.removeLayer(app.pathOverlay); - } + app.view.setImageOverlay('timing-path', + src ? { image: src, rect: pathRect } : null); }; } @@ -1851,9 +1791,12 @@ app.websocketManager.readyPromise.then(async () => { if (raw) { sessionStorage.removeItem('or_restore_view'); const v = JSON.parse(raw); - if (v && isFinite(v.lat) && isFinite(v.lng) + if (v && isFinite(v.dbuX) && isFinite(v.dbuY) && isFinite(v.zoom)) { - app.map.setView([v.lat, v.lng], v.zoom); + app.view.setView( + dbuToWorld(v.dbuX, v.dbuY, app.designScale, + app.designOriginX, app.designOriginY), + v.zoom, { animate: false }); } } } catch (_) { /* ignore */ } @@ -1865,23 +1808,23 @@ app.websocketManager.readyPromise.then(async () => { document.getElementById('loading-overlay').style.display = 'none'; } // Shared select-at-point logic used by left-click and right-click. - // Returns the server response (or null). `focusInspector` switches the + // Resolves once the reply is handled. `focusInspector` switches the // panel to the Inspector (left-click); right-click keeps the current // panel and only updates the selection so the context menu can reflect // the object under the cursor. - function selectAtLatLng(latlng, opts = {}) { + function selectAtWorld(world, opts = {}) { const { addToSelection = false, focusInspector = true, context = false, showConnectivity = false } = opts; - if (!app.designScale) return Promise.resolve(null); - const { dbuX: dbu_x, dbuY: dbu_y } = latLngToDbu( - latlng.lat, latlng.lng, app.designScale, app.designMaxDXDY, + if (!app.designScale) return Promise.resolve(); + const { dbuX: dbu_x, dbuY: dbu_y } = worldToDbu( + world[0], world[1], app.designScale, app.designOriginX, app.designOriginY); // In label-placement mode, a click creates a text annotation // instead of selecting (2.12). if (app.labelManager && app.labelManager.isActive()) { app.labelManager.handleMapClick(dbu_x, dbu_y); - return; + return Promise.resolve(); } const vf = buildVisibilityFlags(visibility, selectability); @@ -1889,7 +1832,7 @@ app.websocketManager.readyPromise.then(async () => { type: 'select', dbu_x, dbu_y, - zoom: Math.round(app.map.getZoom()), + zoom: Math.round(app.view.getZoom()), visible_layers: [...app.visibleLayerNames], selectable_layers: [...app.selectableLayers], use_dbu: app.showDbu, @@ -1924,8 +1867,6 @@ app.websocketManager.readyPromise.then(async () => { // this response describes a selection that no longer // exists, so it must not drive the Inspector. if (!isCurrentSelection(app, token)) return; - console.log('Select response:', data, 'at dbu', dbu_x, dbu_y); - app.map.closePopup(); // Type flags so the context menu can enable items by type. applySelectionFlags(app, data); if (data.selected && data.selected.length > 0) { @@ -1954,12 +1895,6 @@ app.websocketManager.readyPromise.then(async () => { highlightBBox(data.bbox[0], data.bbox[1], data.bbox[2], data.bbox[3], data.type); pulseHighlight(data.bbox, data.type); - // Remember bounds for "Zoom to Selection". - app.lastSelectionBounds = dbuRectToBounds( - data.bbox[0], data.bbox[1], - data.bbox[2], data.bbox[3], - app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY); } if (selectRequest.show_connectivity && data.connected_added > 0) { @@ -1971,126 +1906,47 @@ app.websocketManager.readyPromise.then(async () => { // Empty left-click: clear inspector/highlight. An empty // right-click (context) keeps the current selection. updateInspector(null); - if (app.highlightRect) { - app.map.removeLayer(app.highlightRect); - app.highlightRect = null; - } - app.lastSelectionBounds = null; + if (app.clearSelectionOutline) app.clearSelectionOutline(); } - refreshOverlay(); - return data; + scheduleRefreshOverlay(); }) .catch(err => { console.error('Select failed:', err); - return null; }); } - app.selectAtLatLng = selectAtLatLng; - if (!staticCache) app.map.on('click', (e) => { - if (app.rulerManager && app.rulerManager.isActive()) return; - const ev = e.originalEvent; - selectAtLatLng(e.latlng, { - addToSelection: !!(ev && ev.shiftKey), + if (!staticCache) { + app.onMapClick = (world, e) => selectAtWorld(world, { + addToSelection: !!e.shiftKey, // Accept Cmd+click too: on macOS Ctrl+click is the // context-menu gesture, so metaKey is the reachable modifier. - showConnectivity: !!(ev && (ev.ctrlKey || ev.metaKey)), - }); - }); - - // ─── Right-click rubber-band zoom ────────────────────────────── - if (!staticCache) { - const container = app.map.getContainer(); - let rbStart = null; // {x, y} in client coords - let rbDiv = null; // overlay element - - container.addEventListener('contextmenu', (e) => { - e.preventDefault(); - }); - - container.addEventListener('mousedown', (e) => { - if (e.button !== 2) return; - rbStart = { x: e.clientX, y: e.clientY }; - app.map.dragging.disable(); - }); - - window.addEventListener('mousemove', (e) => { - if (!rbStart) return; - const dx = e.clientX - rbStart.x; - const dy = e.clientY - rbStart.y; - if (!rbDiv && Math.abs(dx) >= 4 && Math.abs(dy) >= 4) { - rbDiv = document.createElement('div'); - rbDiv.className = 'rubber-band'; - document.body.appendChild(rbDiv); - } - if (rbDiv) { - const left = Math.min(rbStart.x, e.clientX); - const top = Math.min(rbStart.y, e.clientY); - rbDiv.style.left = left + 'px'; - rbDiv.style.top = top + 'px'; - rbDiv.style.width = Math.abs(dx) + 'px'; - rbDiv.style.height = Math.abs(dy) + 'px'; - } - }); - - window.addEventListener('mouseup', (e) => { - if (!rbStart) return; - const wasShowing = !!rbDiv; - if (rbDiv) { - rbDiv.remove(); - rbDiv = null; - } - const start = rbStart; - rbStart = null; - app.map.dragging.enable(); - - const rect = container.getBoundingClientRect(); - - if (wasShowing) { - // Drag — rubber-band zoom. - const p1 = app.map.containerPointToLatLng([ - start.x - rect.left, start.y - rect.top]); - const p2 = app.map.containerPointToLatLng([ - e.clientX - rect.left, e.clientY - rect.top]); - app.map.fitBounds([ - [Math.min(p1.lat, p2.lat), Math.min(p1.lng, p2.lng)], - [Math.max(p1.lat, p2.lat), Math.max(p1.lng, p2.lng)], - ]); - return; - } - - // Pure click — select the object under the cursor, then show - // the context menu contextualized on it (Qt-like). Only over - // the map and not while a ruler is being placed. - const overMap = e.clientX >= rect.left && e.clientX <= rect.right - && e.clientY >= rect.top && e.clientY <= rect.bottom; - if (!overMap) return; - if (app.rulerManager && app.rulerManager.isActive()) return; - - const latlng = app.map.containerPointToLatLng([ - e.clientX - rect.left, e.clientY - rect.top]); - app.selectAtLatLng(latlng, { context: true, focusInspector: false }) - .then(() => app.contextMenu.show({ originalEvent: e })); + showConnectivity: !!(e.ctrlKey || e.metaKey), }); + // A right click selects the object under the cursor, then shows + // the context menu contextualized on it (Qt-like). A right drag + // is a rubber-band zoom (view-input.js). + app.onMapContextClick = (world, e) => { + selectAtWorld(world, { context: true, focusInspector: false }) + .then(() => app.contextMenu.show(e)); + }; } populateDisplayControls(app, visibility, selectability, - WebSocketTileLayer, - techData, redrawAllLayers, HeatMapTileLayer); - - // Create the highlight overlay layer — sits above all base/metal - // layers but below the heatmap. Only carries selection, hover, - // timing, DRC, and route-guide shapes on a transparent background, - // so base tiles stay cached when highlights change. - // Skip in static mode: there is no WebSocket server to serve - // overlay_tile requests. + techData, redrawAllLayers, createHeatMapSlot); + + // The highlight overlay: selection, hover, timing, DRC and route-guide + // shapes on a transparent background, above the layout and below the + // heat map, so base tiles stay cached when highlights change. Not in + // a saved report: there is no server to draw it. if (!app.overlayLayer && !staticCache) { - const OverlayTileLayer = createOverlayTileLayer(visibility, app); - app.overlayLayer = new OverlayTileLayer(app.websocketManager, { - zIndex: app.allLayers.length + 5, - opacity: 1, + app.overlayLayer = app.view.addTileSlot('overlay', { + order: DRAW_ORDER.overlay, + source: createImageSource({ + wm: app.websocketManager, + buildRequest: (c, dpr, t) => buildOverlayRequest( + c, dpr, t, visibility, app), + }), }); - app.overlayLayer.addTo(app.map); } updateHeatMaps(heatMapData); @@ -2155,20 +2011,14 @@ document.addEventListener('keydown', (e) => { if (app.rulerManager) app.rulerManager.clearAllRulers(); } else if (key === 'l' && !e.shiftKey && !e.ctrlKey && !e.metaKey) { if (app.labelManager) app.labelManager.toggleLabelMode(); - } else if (key === 'f' && !e.ctrlKey && !e.metaKey && app.fitBounds) { - app.map.fitBounds(app.fitBounds); - } else if (key === 'z' && !e.shiftKey && !e.ctrlKey && app.map) { - if (app.lastMouseLatLng) { - app.map.setZoomAround(app.lastMouseLatLng, app.map.getZoom() + 1); - } else { - app.map.zoomIn(); - } - } else if (key === 'z' && e.shiftKey && !e.ctrlKey && app.map) { - if (app.lastMouseLatLng) { - app.map.setZoomAround(app.lastMouseLatLng, app.map.getZoom() - 1); - } else { - app.map.zoomOut(); - } + } else if (key === 'f' && !e.ctrlKey && !e.metaKey && app.fitRect) { + app.view.fitWorldRect(app.fitRect); + } else if (key === 'z' && !e.ctrlKey && !e.metaKey && !e.altKey + && app.view) { + // Around the pointer when it is over the layout, else the center. + const delta = e.shiftKey ? -1 : 1; + app.view.zoomAround(app.lastMouseWorld + ? app.view.project(app.lastMouseWorld) : null, delta); } else if (key === 'g' && e.shiftKey && !e.ctrlKey && !e.metaKey) { // A dialog shortcut must preventDefault: the dialog focuses and // select()s its first field synchronously, so this keystroke's own diff --git a/openroad/web/src/menu-bar.js b/openroad/web/src/menu-bar.js index f05e8e68829..265e1dbb9a8 100644 --- a/openroad/web/src/menu-bar.js +++ b/openroad/web/src/menu-bar.js @@ -76,9 +76,9 @@ export function createMenuBar(app) { enabledWhen: () => !!app.designScale }, ]}, { label: 'View', items: [ - { label: 'Fit', shortcut: 'F', action: () => { if (app.fitBounds) app.map.fitBounds(app.fitBounds); } }, - { label: 'Zoom In', shortcut: 'Z', action: () => app.map.zoomIn() }, - { label: 'Zoom Out', shortcut: 'Shift+Z', action: () => app.map.zoomOut() }, + { label: 'Fit', shortcut: 'F', action: () => { if (app.fitRect) app.view.fitWorldRect(app.fitRect); } }, + { label: 'Zoom In', shortcut: 'Z', action: () => app.view.zoomIn() }, + { label: 'Zoom Out', shortcut: 'Shift+Z', action: () => app.view.zoomOut() }, { type: 'separator' }, { label: 'Toggle Theme', shortcut: 'T', action: () => app.toggleTheme() }, { type: 'separator' }, @@ -133,6 +133,18 @@ export function createMenuBar(app) { { label: 'Application font...', action: () => app.showAppFontDialog() }, { type: 'separator' }, + // Rendering preferences. Web-only: Qt has no smoothing + // to turn off and already draws off-screen. + { label: 'Smooth zoom and pan', + action: () => app.toggleControlSmoothing(), + checked: () => app.controlSmoothing }, + { label: 'Double buffering', + action: () => app.toggleDoubleBuffer(), + checked: () => app.doubleBuffer }, + { label: 'Defer tile updates while panning', + action: () => app.toggleDeferTileUpdates(), + checked: () => app.deferTileUpdates }, + { type: 'separator' }, { label: 'Show polygon decomposition', action: () => app.togglePolyDecomp(), checked: () => app.polyDecomp, diff --git a/openroad/web/src/merged-tile-layer.js b/openroad/web/src/merged-tile-layer.js deleted file mode 100644 index 1112e070039..00000000000 --- a/openroad/web/src/merged-tile-layer.js +++ /dev/null @@ -1,296 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// Copyright (c) 2026, The OpenROAD Authors - -// A Leaflet tile layer that composites several tech layers into ONE tile. -// -// The viewer's default is one pane per (tech layer x chiplet instance) — ~97 on -// a multi-die design — and every pane holds a full grid of tiles, each decoding -// to (256*dpr)^2 * 4 bytes. That measured 582 MB against a browser ceiling of -// ~458 MB, and over the ceiling Chrome discards decoded images: the discarded -// regions paint white and stay white until something forces a full -// invalidation. The symptom tracks decoded image bytes, not pane count: at a -// matched byte level, 86 and 97 content-bearing panes fail identically. -// -// This layer owns a contiguous run of the z-order and rasterizes it into a -// single per tile position, so N panes hold N grids instead of 97. -// See tile-merge.js for the budget arithmetic, why the run must be contiguous, -// and why the pane's own opacity must be 1. - -import { - closeAll, mergeOntoContext, mergedPaneOptions, renderMergedTile, -} from './tile-merge.js'; -import { - buildTileRequestFor, floorClampZoom, nativeDpr, tileDevicePx, - withDeviceExactTileSize, -} from './tile-request.js'; -import { tileMayHaveContent } from './layer-extents.js'; - -// Decode a websocket tile payload into something drawable. -// -// createImageBitmap is the point: an gives no control over when its -// decoded bitmap is released, and that is the whole problem this layer exists -// to solve. An ImageBitmap can be close()d the moment it has been drawn. -// -// A string payload is a data URI from the static-report cache, which has no -// Blob to hand to createImageBitmap — fall back to an there. Those -// reports are pre-rendered at one zoom and are not where the memory problem -// lives, so the weaker path is acceptable. -export function decodeTilePayload(payload) { - if (payload == null) { - return Promise.resolve(null); - } - if (typeof payload === 'string') { - return new Promise((resolve) => { - const img = document.createElement('img'); - img.onload = () => resolve(img); - img.onerror = () => resolve(null); - img.src = payload; - }); - } - if (typeof createImageBitmap === 'function') { - return createImageBitmap(payload).catch(() => null); - } - // No createImageBitmap (very old browser): fall back to a blob URL, and - // revoke it once the decode has happened. - return new Promise((resolve) => { - const url = URL.createObjectURL(payload); - const img = new Image(); - img.onload = () => { - URL.revokeObjectURL(url); - resolve(img); - }; - img.onerror = () => { - URL.revokeObjectURL(url); - resolve(null); - }; - img.src = url; - }); -} - -// `items` is the ordered draw list this pane owns: -// [{ layer, chiplet, rowId, rendererHost, opacity, visible }], bottom-most -// first; the item is the Display Controls row (see buildTileRequestFor). It is -// read live on every request, so a visibility toggle only has to flip -// `visible` and call refreshTiles() — no layer is added to or removed from the -// map, and the pane count never changes. -export function createMergedTileLayer(ctx, options = {}) { - const decode = options.decode || decodeTilePayload; - const dprOf = options.dpr || nativeDpr; - - return L.GridLayer.extend({ - // Force upscale-only display (see floorClampZoom) so the browser never - // downscales a band-limited tile back into a moiré beat. - _clampZoom: function(zoom) { - return L.GridLayer.prototype._clampZoom.call( - this, floorClampZoom(this, zoom)); - }, - - initialize: function(websocketManager, items, opts) { - this._websocketManager = websocketManager; - this._items = items || []; - // Bumped on every refresh so in-flight renders for the previous - // generation can tell they have been superseded and drop their work - // instead of painting it. - this._generation = 0; - L.GridLayer.prototype.initialize.call( - this, withDeviceExactTileSize(opts)); - }, - - // Swap the draw list (a layer toggled, reordered, or regrouped after a - // resize changed the budget) and repaint in place. - setItems: function(items) { - this._items = items || []; - this.refreshTiles(); - }, - - visibleItems: function() { - return this._items.filter(item => item && item.visible !== false); - }, - - createTile: function(coords, done) { - const canvas = document.createElement('canvas'); - canvas.setAttribute('role', 'presentation'); - const dpr = dprOf(); - // Stored on the element rather than held only by this render, so - // whichever render paints first can complete the handshake. A - // refresh that lands before the first paint replaces the render but - // not the tile, and Leaflet keeps the tile hidden until done() is - // called — so a done that belonged to the superseded render would - // leave a painted canvas invisible until the tile was recreated. - canvas._orDone = done; - this._renderTile(canvas, coords, dpr); - return canvas; - }, - - // Backing store in device pixels, CSS box in layout pixels, so the - // canvas maps 1:1 onto the device grid and drawImage does not resample - // — the same invariant the path relies on. - // - // Re-applied on every render, not just at creation: devicePixelRatio - // changes when the window moves between monitors or the browser zoom - // changes, and a refresh then requests images at the new dpr. A canvas - // still sized for the old one would scale every incoming tile into the - // wrong backing store, leaving existing tiles blurry and inconsistent - // with any created afterwards. - // - // `empty` releases the backing store instead, for a tile with nothing - // to draw (see _renderTile); the CSS box stays, so the grid is intact. - _sizeCanvas: function(canvas, dpr, { empty = false } = {}) { - const size = this.getTileSize(); - // The same count the request asks the server for, so the image - // arrives at exactly the backing store's size and drawImage is a - // straight blit. - const w = empty ? 0 : tileDevicePx(size.x, dpr); - const h = empty ? 0 : tileDevicePx(size.y, dpr); - if (canvas.width !== w || canvas.height !== h) { - // Assigning width/height also clears the canvas, which is what - // we want here — the caller is about to redraw it. - canvas.width = w; - canvas.height = h; - } - canvas.style.width = size.x + 'px'; - canvas.style.height = size.y + 'px'; - }, - - // Mark the tile loaded, once. Leaflet reveals it only here - // (.leaflet-tile { visibility: hidden } until done() adds - // leaflet-tile-loaded), so every exit from a render has to reach this. - _finishTile: function(canvas, err) { - if (canvas._orTileDone || !canvas._orDone) { - return; - } - canvas._orTileDone = true; - canvas._orDone(err || null, canvas); - }, - - _renderTile: function(canvas, coords, dpr) { - const generation = this._generation; - const items = this.visibleItems().filter( - item => tileMayHaveContent(ctx, item.layer, coords, - item.chiplet)); - // A tile none of whose layers can draw here keeps no backing store - // at all. A full-size canvas per tile position per pane is what the - // browser pays for on a zoom -- allocating, clearing and compositing - // it -- whether or not anything is drawn into it, and most panes are - // empty in most views. - this._sizeCanvas(canvas, dpr, { empty: items.length === 0 }); - const context = canvas.getContext('2d'); - // Request ids are tracked per tile so _removeTile can cancel the - // whole group's in-flight work when the tile is pruned. - canvas._orRequestIds = []; - - // Superseded by a later refresh, or the tile was pruned while the - // requests were in flight. Pruning is tracked with an explicit flag - // rather than canvas.isConnected: Leaflet appends the element AFTER - // createTile returns, so attachment state conflates "pruned" with - // "not yet attached" and would drop the very first paint of every - // tile. - const isStale = () => this._generation !== generation - || canvas._orRemoved === true; - - renderMergedTile({ - items, - request: (item) => { - const id = this._websocketManager.nextId; - canvas._orRequestIds.push(id); - return this._websocketManager.request( - buildTileRequestFor(coords, item.layer, ctx, dpr, - this.getTileSize().x, item)); - }, - decode, - draw: (sources) => mergeOntoContext(context, sources, - canvas.width), - release: closeAll, - isStale, - // Reported on the FIRST paint, not on completion: Leaflet keeps - // a tile hidden (.leaflet-tile { visibility: hidden }) until - // done() adds leaflet-tile-loaded, so deferring it would make - // every incremental paint invisible and the tile would still - // appear only once its slowest layer had landed. - onFirstDraw: () => this._finishTile(canvas), - }).then(() => { - // A superseded render must not finish the tile: it painted - // nothing, so revealing the canvas here would show the state it - // had before the refresh. The render that replaced it owns the - // handshake. - if (!isStale()) { - this._finishTile(canvas); - } - }).catch((err) => { - // Reported as a load error so Leaflet stops waiting on it; the - // canvas keeps whatever it managed to paint. - if (!isStale()) { - this._finishTile(canvas, err); - } - }); - }, - - // Re-request every tile in place (no removal, no flash). Used for - // visibility toggles, pattern changes and the server's design-changed - // refresh push — the same contract as the per-layer layer's method, so - // redrawAllLayers() drives both without knowing which it has. - refreshTiles: function() { - if (!this._map) { - return; - } - this._generation++; - for (const key in this._tiles) { - const info = this._tiles[key]; - if (!info || !info.el) { - continue; - } - this._cancelTile(info.el); - const dpr = dprOf(); - this._renderTile(info.el, info.coords, dpr); - } - }, - - _cancelTile: function(el) { - const ids = el._orRequestIds; - if (!ids || !ids.length) { - return; - } - for (const id of ids) { - this._websocketManager.cancel(id); - } - el._orRequestIds = []; - }, - - _removeTile: function(key) { - const tile = this._tiles[key]; - if (tile && tile.el) { - // Flagged before the cancel so an in-flight render that is - // already past its request phase still sees the tile as gone - // and declines to paint a detached canvas. - tile.el._orRemoved = true; - this._cancelTile(tile.el); - // Drop the backing store now rather than waiting for GC: a - // pruned tile that keeps its canvas is the same unbounded - // growth in a different costume. - tile.el.width = 0; - tile.el.height = 0; - } - L.GridLayer.prototype._removeTile.call(this, key); - }, - }); -} - -// Build the N merged panes for an ordered draw list and put them on the map. -// -// `groups` is the output of partitionIntoGroups(): contiguous runs of the -// z-order, bottom-most first. z-indices are assigned from the group index so -// the panes stack in the same order the individual layers used to. -export function buildMergedPanes(MergedLayer, websocketManager, groups, map, - baseZIndex = 0) { - const panes = []; - groups.forEach((items, i) => { - const layer = new MergedLayer( - websocketManager, items, - mergedPaneOptions({ zIndex: baseZIndex + i })); - if (map) { - layer.addTo(map); - } - panes.push(layer); - }); - return panes; -} diff --git a/openroad/web/src/request_handler.cpp b/openroad/web/src/request_handler.cpp index 685fe98d5ea..aed75122a25 100644 --- a/openroad/web/src/request_handler.cpp +++ b/openroad/web/src/request_handler.cpp @@ -921,8 +921,8 @@ bool parseTileCoords(const boost::json::object& json, error = "\"z\" is outside [0, " + std::to_string(kMaxTileZoom) + "]"; return false; } - // x and y are deliberately NOT range-checked against the 2^z grid. Leaflet - // routinely asks for tiles off the edge of the world -- whenever the design + // x and y are deliberately NOT range-checked against the 2^z grid. A client + // may ask for tiles off the edge of the world -- whenever the design // is smaller than the viewport, or while panning at the border -- and the // renderers answer those with a transparent tile. Rejecting them turns // ordinary panning into a stream of errors: a first cut of this check @@ -2273,7 +2273,7 @@ WebSocketResponse SelectHandler::handleSelect(const WebSocketRequest& req, consumeStaleSelection(state); TileVisibility vis; vis.parseFromJson(req.json); - // Leaflet allows fractional zoom (zoomSnap: 0); accept either int or + // A client may send a fractional zoom; accept either int or // double on the wire and truncate to selectAt's integer zoom level. const auto& zoom_v = req.json.at("zoom"); const int zoom = zoom_v.is_int64() ? static_cast(zoom_v.get_int64()) @@ -3740,7 +3740,8 @@ WebSocketResponse SelectHandler::handleSelectLayer(const WebSocketRequest& req, odb::dbTech* tech = nullptr; if (!chiplet_path.empty()) { - for (const ChipletNode& node : gen_->chiplets()) { + const auto nodes = gen_->chiplets(); + for (const ChipletNode& node : *nodes) { if (node.path == chiplet_path && node.chip != nullptr) { tech = node.chip->getTech(); break; @@ -4896,12 +4897,12 @@ WebSocketResponse SelectHandler::handleSchematicCone( = static_cast(req.json.at("fanin_depth").as_int64()); const int fanout_depth = static_cast(req.json.at("fanout_depth").as_int64()); - const auto& chiplets = gen_->chiplets(); + const auto chiplets = gen_->chiplets(); if (gen_->blocks().empty()) { throw std::runtime_error("No block loaded"); } - const auto [target_inst, chiplet] = findSchematicInst(chiplets, inst_name); + const auto [target_inst, chiplet] = findSchematicInst(*chiplets, inst_name); if (!target_inst) { throw std::runtime_error("Instance not found: " + inst_name); } @@ -5017,7 +5018,7 @@ WebSocketResponse SelectHandler::handleSchematicPath( static constexpr size_t kMaxPathInsts = 400; try { - const auto& chiplets = gen_->chiplets(); + const auto chiplets = gen_->chiplets(); if (gen_->blocks().empty()) { throw std::runtime_error("No block loaded"); } @@ -5029,7 +5030,7 @@ WebSocketResponse SelectHandler::handleSchematicPath( break; } const std::string name = std::string(name_val.as_string()); - const auto [inst, chiplet] = findSchematicInst(chiplets, name); + const auto [inst, chiplet] = findSchematicInst(*chiplets, name); if (inst && path_insts[chiplet].insert(inst).second) { ++inst_count; } @@ -5228,9 +5229,8 @@ WebSocketResponse SelectHandler::handleGet3DData(const WebSocketRequest& req) boost::json::object root; boost::json::array chiplets; std::map chiplet_indices; - // A copy: the cached list is replaced when another thread notices a chip - // placement edit, and the bump and net walks below take a while. - const std::vector nodes = gen_->chiplets(); + const auto node_list = gen_->chiplets(); + const std::vector& nodes = *node_list; // One box per leaf chiplet, placed by the same traversal the 2D viewer // uses. chiplets() carries each node's composed world transform (from @@ -5305,12 +5305,12 @@ WebSocketResponse SelectHandler::handleSchematicInspect( consumeStaleSelection(state); const std::string inst_name = std::string(req.json.at("inst_name").as_string()); - const auto& chiplets = gen_->chiplets(); + const auto chiplets = gen_->chiplets(); if (gen_->blocks().empty()) { throw std::runtime_error("No block loaded"); } - const auto [inst, chiplet] = findSchematicInst(chiplets, inst_name); + const auto [inst, chiplet] = findSchematicInst(*chiplets, inst_name); if (!inst) { throw std::runtime_error("Instance not found: " + inst_name); } @@ -5594,7 +5594,8 @@ WebSocketResponse TimingHandler::handleTimingHighlight( if (path != nullptr) { // chiplets() covers both cases: for a single-die design its root node // carries the top block with an identity transform. - const std::vector& chiplets = gen_->chiplets(); + const auto chiplet_list = gen_->chiplets(); + const std::vector& chiplets = *chiplet_list; collectTimingPathShapes(chiplets, *path, new_rects, new_lines); const std::string pin_name @@ -6226,12 +6227,7 @@ WebSocketResponse TileHandler::handleTile(const WebSocketRequest& req, z, x, y); - WebSocketResponse resp; - resp.id = req.id; - resp.type = WebSocketResponse::kError; - const std::string msg = "cancelled"; - resp.payload.assign(msg.begin(), msg.end()); - return resp; + return errorResponse(req.id, kCancelledMsg); } } @@ -6304,58 +6300,31 @@ WebSocketResponse TileHandler::handleTile(const WebSocketRequest& req, && !vis.debug_renderers && !vis.debug_live; std::string cache_key; + uint64_t cache_epoch = 0; if (cacheable) { - // Key = the full render determinant: the request JSON minus the per-call - // id, with dpr pinned to the quantized value actually rendered. - // Selectability (the s_* flags and selectable_layers) does NOT affect the - // rendered tile, so it is excluded — toggling "selectable" must not - // invalidate the cache. - boost::json::object key_obj = req.json; - key_obj.erase("id"); - key_obj.erase("selectable_layers"); + // Read before rendering: a design edit meanwhile makes the result stale. + cache_epoch = gen_->tileCacheEpoch(); + // Key = what the render reads: the tile, its dpr and pixel count, the + // design and chiplet revisions and the visibility this layer depends on. + boost::json::object tile_obj{ + {"layer", layer}, + {"z", z}, + {"x", x}, + {"y", y}, + {"dpr", dpr}, + {"tile_px", tile_px}, + {"rev", gen_->searchRevision()}, + {"chiplets", gen_->chipletsGeneration()}, + }; // Two cacheable states share everything else: painting the design's // default palette, and painting nothing because the session cleared every // row. Without this they collide on one key and the cleared view serves // the painted tile. if (modules_layer || clusters_layer) { - key_obj["owner_colors"] = default_colors ? "default" : "none"; - } - // The color-overlay flags only change what THEIR layer draws. Leaving them - // in every layer's key would make toggling one overlay a full cache miss - // for the whole screen — every metal layer re-rendered for a flag it - // ignores — and multiply the cache footprint per tile. - if (layer != "_modules") { - key_obj.erase("module_view"); - } - if (layer != "_clusters") { - key_obj.erase("cluster_view"); - } - std::vector sel_keys; - for (const auto& kv : key_obj) { - const std::string_view k = kv.key(); - if (k.size() >= 2 && k[0] == 's' && k[1] == '_') { - sel_keys.emplace_back(k); - } - } - for (const std::string& k : sel_keys) { - key_obj.erase(k); - } - // Only the tiles that filter by layer name read these; in every other key - // one layer toggle would miss the cache for all the rest. - if (!TileGenerator::readsLayerVisibility(layer, vis)) { - key_obj.erase("visible_layers"); - key_obj.erase("chiplet_hidden_layers"); - } - // A tile scoped to a die depends on that die being shown, not the others. - if (!vis.chiplet.empty()) { - key_obj.erase("visible_chiplets"); - key_obj["chiplet_visible"] = vis.isChipletVisible(vis.chiplet); - } - key_obj["dpr"] = dpr; - // Pinned like dpr: two clients on different displays ask for different - // pixel counts of the same tile, and they are different images. - key_obj["tile_px"] = tile_px; - cache_key = boost::json::serialize(key_obj); + tile_obj["owner_colors"] = default_colors ? "default" : "none"; + } + cache_key = boost::json::serialize(tile_obj) + + TileGenerator::tileCacheKey(vis, layer); std::vector cached; if (gen_->tileCacheGet(cache_key, cached)) { WebSocketResponse resp; @@ -6409,7 +6378,7 @@ WebSocketResponse TileHandler::handleTile(const WebSocketRequest& req, = resp.type == WebSocketResponse::kEmpty || (resp.type == WebSocketResponse::kPng && !resp.payload.empty()); if (cacheable && worth_caching) { - gen_->tileCachePut(std::move(cache_key), resp.payload); + gen_->tileCachePut(std::move(cache_key), resp.payload, cache_epoch); } debugPrint(gen_->getLogger(), diff --git a/openroad/web/src/request_handler.h b/openroad/web/src/request_handler.h index 1e5a3172985..3f769ef93f2 100644 --- a/openroad/web/src/request_handler.h +++ b/openroad/web/src/request_handler.h @@ -58,6 +58,9 @@ inline constexpr const char* kExitResultMsg = "_WEB_EXITING_"; inline constexpr const char* kScriptBusyMsg = "The script is running; try again when it pauses or finishes."; +// Error text for a request the client cancelled; routine during pan and zoom. +inline constexpr const char* kCancelledMsg = "cancelled"; + // Server push announcing that the script started or stopped running, i.e. // that the ScriptGate closed or opened. inline std::string scriptRunningJson(bool running) @@ -548,9 +551,9 @@ struct SessionState // Map an HTTP request target onto an embedded asset path. // // Strips the query string and fragment, which the asset lookup must not see: -// the viewer's options are passed as query parameters (?mergetiles=0 and -// friends), and matching "/?mergetiles=0" against the asset table simply fails, -// so the whole page 404s. Also maps "/" onto the index document. +// the viewer's options are passed as query parameters (?preservebuffer=1 and +// friends), and matching "/?preservebuffer=1" against the asset table simply +// fails, so the whole page 404s. Also maps "/" onto the index document. std::string assetPathFromTarget(std::string_view target); // Join `t`, or detach it when called from `t` itself, where a join throws @@ -653,8 +656,8 @@ constexpr int kMaxTileZoom = 30; // Read the z/x/y grid coordinates of a tile request into `z`/`x`/`y`. // Returns false, with `error` describing the offending field, when a // coordinate is missing, is not an integer, or the zoom is outside -// [0, kMaxTileZoom]. x and y are not bounded to the grid: Leaflet asks for -// off-grid tiles as a matter of course and the renderers answer with a +// [0, kMaxTileZoom]. x and y are not bounded to the grid: the client may +// ask for off-grid tiles and the renderers answer with a // transparent tile. // // The type check is not paranoia about hand-written clients: JSON.stringify diff --git a/openroad/web/src/ruler.js b/openroad/web/src/ruler.js index 17d51df21ee..13fd9178c76 100644 --- a/openroad/web/src/ruler.js +++ b/openroad/web/src/ruler.js @@ -10,13 +10,18 @@ // Escape : cancel → IDLE // Shift+K : clear all rulers -import { dbuToLatLng, latLngToDbu } from './coordinates.js'; -import { beginSelection, buildVisibilityFlags } from './ui-utils.js'; +import { dbuToWorld, worldToDbu } from './coordinates.js'; +import { DRAW_ORDER, toRgba } from './layout-view.js'; +import { beginSelection, buildVisibilityFlags, onSelectionReset } + from './ui-utils.js'; const RULER_COLOR = '#00ffff'; const RULER_SELECTED_COLOR = '#ffff00'; const SNAP_INDICATOR_COLOR = '#ffffff'; +// Screen distance within which a click picks a ruler line. +const kRulerHitPx = 4; + const IDLE = 0; const FIRST_POINT = 1; const MEASURING = 2; @@ -33,39 +38,27 @@ export class RulerManager { this._nextId = 0; this._pt0 = null; // {x, y} in DBU this._selectedRulerId = null; + // Another object taking the selection unmarks the ruler. + onSelectionReset(app, () => { + if (this._selectedRulerId !== null) { + this._selectedRulerId = null; + this._renderAll(); + } + }); // Modifier key state (updated on mousemove/click) this._ctrlHeld = false; this._shiftHeld = false; - // Leaflet layers - this._rulerPane = null; - this._rulerLayerGroup = null; - this._previewGroup = null; // rubber-band during MEASURING - this._snapGroup = null; // snap indicator - // Debounce state this._snapTimer = null; this._lastSnapResult = null; + this._snapShapes = null; + this._preview = null; // { shapes, label: { world, text } } - // Map event handlers (bound references for cleanup) - this._onMouseMove = this._handleMouseMove.bind(this); - this._onMapClick = this._handleMapClick.bind(this); - - this._initLayers(); - } - - _initLayers() { - const map = this._app.map; - if (!map) return; - - this._rulerPane = map.createPane('ruler-pane'); - this._rulerPane.style.zIndex = '700'; - this._rulerPane.style.pointerEvents = 'auto'; - - this._rulerLayerGroup = L.layerGroup([], { pane: 'ruler-pane' }).addTo(map); - this._previewGroup = L.layerGroup([], { pane: 'ruler-pane' }).addTo(map); - this._snapGroup = L.layerGroup([], { pane: 'ruler-pane' }).addTo(map); + // Tick lengths are in screen pixels, so a zoom redraws the rulers; + // the labels are world-anchored markers and follow on their own. + app.view?.on('zoom', () => this._renderRulerShapes()); } isActive() { @@ -73,9 +66,12 @@ export class RulerManager { } updateVisibility() { - if (this._rulerPane) { - this._rulerPane.style.display = this._visibility.rulers ? '' : 'none'; - } + this._renderAll(); + this._drawTransient(); + } + + _shown() { + return this._visibility.rulers !== false; } toggleRulerMode() { @@ -87,21 +83,20 @@ export class RulerManager { } cancelRulerBuild() { + clearTimeout(this._snapTimer); + this._snapTimer = null; this._state = IDLE; this._pt0 = null; this._lastSnapResult = null; - this._clearPreview(); - this._clearSnap(); + this._clearTransient(); this._setCursor(false); - this._removeMapListeners(); } clearAllRulers() { this._rulers = []; this._selectedRulerId = null; - this._rulerLayerGroup.clearLayers(); - this._clearPreview(); - this._clearSnap(); + this._renderAll(); + this._clearTransient(); if (this._state !== IDLE) { this.cancelRulerBuild(); } @@ -114,7 +109,6 @@ export class RulerManager { this._pt0 = null; this._lastSnapResult = null; this._setCursor(true); - this._addMapListeners(); } _enterMeasuring(pt0) { @@ -122,36 +116,25 @@ export class RulerManager { this._pt0 = pt0; } - // ─── Map event wiring ──────────────────────────────────────────── + // ─── Pointer input (from view-input via main.js) ───────────────── - _addMapListeners() { - const map = this._app.map; - if (!map) return; - map.getContainer().addEventListener('mousemove', this._onMouseMove); - map.on('click', this._onMapClick); + _toDbu(world) { + return worldToDbu(world[0], world[1], this._app.designScale, + this._app.designOriginX, this._app.designOriginY); } - _removeMapListeners() { - const map = this._app.map; - if (!map) return; - map.getContainer().removeEventListener('mousemove', this._onMouseMove); - map.off('click', this._onMapClick); + _toWorld(x, y) { + return dbuToWorld(x, y, this._app.designScale, + this._app.designOriginX, this._app.designOriginY); } - _handleMouseMove(e) { + handleMouseMove(world, e) { if (this._state === IDLE) return; this._ctrlHeld = e.ctrlKey || e.metaKey; this._shiftHeld = e.shiftKey; - const map = this._app.map; - const rect = map.getContainer().getBoundingClientRect(); - const pt = map.containerPointToLatLng([ - e.clientX - rect.left, e.clientY - rect.top - ]); - const dbu = latLngToDbu(pt.lat, pt.lng, - this._app.designScale, this._app.designMaxDXDY, - this._app.designOriginX, this._app.designOriginY); + const dbu = this._toDbu(world); // Debounce snap requests at ~50ms if (this._snapTimer) clearTimeout(this._snapTimer); @@ -160,21 +143,13 @@ export class RulerManager { }, 50); } - _handleMapClick(e) { + handleMapClick(world, e) { if (this._state === IDLE) return; - L.DomEvent.stopPropagation(e); - - // Read modifier keys from the native DOM event - const orig = e.originalEvent; - if (orig) { - this._ctrlHeld = orig.ctrlKey || orig.metaKey; - this._shiftHeld = orig.shiftKey; - } + this._ctrlHeld = e.ctrlKey || e.metaKey; + this._shiftHeld = e.shiftKey; - const dbu = latLngToDbu(e.latlng.lat, e.latlng.lng, - this._app.designScale, this._app.designMaxDXDY, - this._app.designOriginX, this._app.designOriginY); + const dbu = this._toDbu(world); // Use the last snap result if available, otherwise raw click const snapped = this._getSnappedPoint(dbu.dbuX, dbu.dbuY); @@ -187,8 +162,7 @@ export class RulerManager { // where you can keep placing rulers until pressing 'k' or Escape) this._state = FIRST_POINT; this._pt0 = null; - this._clearPreview(); - this._clearSnap(); + this._clearTransient(); this._lastSnapResult = null; } } @@ -202,7 +176,7 @@ export class RulerManager { // Ctrl held: skip snap entirely, use raw cursor position if (this._ctrlHeld) { this._lastSnapResult = null; - this._clearSnap(); + this._snapShapes = null; this._updatePreview(dbuX, dbuY); return; } @@ -212,10 +186,10 @@ export class RulerManager { const radius = dbuPerMicron; // 1 micron search radius // Point snap threshold: max(10 pixels in DBU, 10 DBU) - const zoom = app.map.getZoom(); + const zoom = app.view.getZoom(); const numTiles = Math.pow(2, Math.max(0, zoom)); // designScale is CSS px per DBU at zoom 0, so it already carries the - // tile size the map was built with -- which is not a constant. + // tile size the view was built with -- which is not a constant. const dbuPerPixel = 1 / (app.designScale * numTiles); const pointThreshold = Math.max(Math.round(10 * dbuPerPixel), 10); @@ -256,6 +230,10 @@ export class RulerManager { ...vf, }); + // Cancelled while the reply was on its way. + if (this._state === IDLE) { + return; + } this._lastSnapResult = result; this._updateSnapIndicator(result); this._updatePreview(dbuX, dbuY); @@ -307,75 +285,67 @@ export class RulerManager { } _updateSnapIndicator(snap) { - this._clearSnap(); - if (!snap?.found) return; - - const scale = this._app.designScale; - const maxDXDY = this._app.designMaxDXDY; - const originX = this._app.designOriginX; - const originY = this._app.designOriginY; - - if (snap.is_point) { - const ll = dbuToLatLng(snap.edge[0][0], snap.edge[0][1], scale, maxDXDY, originX, originY); - const marker = L.circleMarker(ll, { - radius: 5, - color: SNAP_INDICATOR_COLOR, - fillColor: SNAP_INDICATOR_COLOR, - fillOpacity: 0.5, - weight: 1, - pane: 'ruler-pane', - interactive: false, - }); - this._snapGroup.addLayer(marker); - } else { - const p1 = dbuToLatLng(snap.edge[0][0], snap.edge[0][1], scale, maxDXDY, originX, originY); - const p2 = dbuToLatLng(snap.edge[1][0], snap.edge[1][1], scale, maxDXDY, originX, originY); - const line = L.polyline([p1, p2], { - color: SNAP_INDICATOR_COLOR, - weight: 1, - pane: 'ruler-pane', - interactive: false, - }); - this._snapGroup.addLayer(line); + this._snapShapes = null; + if (snap?.found) { + const white = toRgba(SNAP_INDICATOR_COLOR); + if (snap.is_point) { + this._snapShapes = [{ + kind: 'circle', + center: this._toWorld(snap.edge[0][0], snap.edge[0][1]), + radius: 5, stroke: white, width: 1, + fill: toRgba(SNAP_INDICATOR_COLOR, 0.5), + }]; + } else { + this._snapShapes = [{ + kind: 'path', + points: [this._toWorld(snap.edge[0][0], snap.edge[0][1]), + this._toWorld(snap.edge[1][0], snap.edge[1][1])], + stroke: white, width: 1, + }]; + } } + this._drawTransient(); } _updatePreview(rawX, rawY) { - this._clearPreview(); - if (this._state !== MEASURING || !this._pt0) return; - - const scale = this._app.designScale; - const maxDXDY = this._app.designMaxDXDY; - const originX = this._app.designOriginX; - const originY = this._app.designOriginY; - const snapped = this._getSnappedPoint(rawX, rawY); - - const p0 = dbuToLatLng(this._pt0.x, this._pt0.y, scale, maxDXDY, originX, originY); - const p1 = dbuToLatLng(snapped.x, snapped.y, scale, maxDXDY, originX, originY); - - const line = L.polyline([p0, p1], { - color: RULER_COLOR, - weight: 2, - dashArray: '6,4', - pane: 'ruler-pane', - interactive: false, - }); - this._previewGroup.addLayer(line); - - // Show distance label - const dist = this._computeDistance(this._pt0, snapped); - const midLat = (p0[0] + p1[0]) / 2; - const midLng = (p0[1] + p1[1]) / 2; - const label = L.marker([midLat, midLng], { - icon: L.divIcon({ - className: 'ruler-label', - html: this._formatDistance(dist), - iconSize: null, - }), - pane: 'ruler-pane', - interactive: false, - }); - this._previewGroup.addLayer(label); + this._preview = null; + if (this._state === MEASURING && this._pt0) { + const snapped = this._getSnappedPoint(rawX, rawY); + const p0 = this._toWorld(this._pt0.x, this._pt0.y); + const p1 = this._toWorld(snapped.x, snapped.y); + const dist = this._computeDistance(this._pt0, snapped); + this._preview = { + shapes: [{ kind: 'path', points: [p0, p1], + stroke: toRgba(RULER_COLOR), width: 2, + dash: [6, 4] }], + label: { world: [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2], + text: this._formatDistance(dist) }, + }; + } + this._drawTransient(); + } + + // The snap indicator and the rubber-band preview. + _drawTransient() { + const view = this._app.view; + if (!view) return; + const shown = this._shown(); + view.setOverlay('ruler-snap', shown ? this._snapShapes : null, + { order: DRAW_ORDER.ruler }); + view.setOverlay('ruler-preview', shown && this._preview + ? this._preview.shapes : null, { order: DRAW_ORDER.ruler }); + view.clearMarkers('ruler-preview'); + if (shown && this._preview) { + view.addMarker('ruler-preview', 'label', this._preview.label.world, + this._labelElement(this._preview.label.text)); + } + } + + _labelElement(text) { + const el = document.createElement('div'); + el.className = 'ruler-label'; + el.textContent = text; + return el; } // ─── Ruler creation and rendering ──────────────────────────────── @@ -392,65 +362,40 @@ export class RulerManager { euclidian: this._app.rulerStyle !== 'manhattan', }; this._rulers.push(ruler); - this._renderRuler(ruler); this._selectRuler(id); return ruler; } - _renderRuler(ruler) { - const scale = this._app.designScale; - const maxDXDY = this._app.designMaxDXDY; - const originX = this._app.designOriginX; - const originY = this._app.designOriginY; - - const p0 = dbuToLatLng(ruler.pt0.x, ruler.pt0.y, scale, maxDXDY, originX, originY); - const p1 = dbuToLatLng(ruler.pt1.x, ruler.pt1.y, scale, maxDXDY, originX, originY); - const isSelected = ruler.id === this._selectedRulerId; - const color = isSelected ? RULER_SELECTED_COLOR : RULER_COLOR; - - const group = L.layerGroup([], { pane: 'ruler-pane' }); - - // Build path points: straight line (euclidian) or L-shape (Manhattan) + // World points of a ruler's path: straight, or the Manhattan L. + _rulerPath(ruler) { const joinPt = ruler.euclidian ? null : this._getManhattanJoinPt(ruler.pt0, ruler.pt1); - const pJoin = joinPt - ? dbuToLatLng(joinPt.x, joinPt.y, scale, maxDXDY, originX, originY) - : null; - const pathPoints = pJoin ? [p0, pJoin, p1] : [p0, p1]; - - // Main ruler line - const mainLine = L.polyline(pathPoints, { - color, - weight: 2, - pane: 'ruler-pane', - interactive: true, - }); - mainLine.on('click', (e) => { - L.DomEvent.stopPropagation(e); - this._selectRuler(ruler.id); - }); - group.addLayer(mainLine); + const pts = joinPt ? [ruler.pt0, joinPt, ruler.pt1] + : [ruler.pt0, ruler.pt1]; + return { joinPt, points: pts.map((p) => this._toWorld(p.x, p.y)) }; + } - // Endcap ticks — perpendicular to each segment direction - const zoom = this._app.map.getZoom(); + _rulerShapes(ruler) { + const isSelected = ruler.id === this._selectedRulerId; + const color = toRgba(isSelected ? RULER_SELECTED_COLOR : RULER_COLOR); + const { joinPt, points } = this._rulerPath(ruler); + const shapes = [{ kind: 'path', points, stroke: color, width: 2 }]; + + // Endcap ticks, 8 px either side, perpendicular to each segment. + const zoom = this._app.view.getZoom(); const numTiles = Math.pow(2, Math.max(0, zoom)); - const dbuPerPixel = 1 / (scale * numTiles); + const dbuPerPixel = 1 / (this._app.designScale * numTiles); const tickLen = 8 * dbuPerPixel; - const addTick = (pt, segDx, segDy) => { const segLen = Math.sqrt(segDx * segDx + segDy * segDy); if (segLen === 0) return; const px = -segDy / segLen; const py = segDx / segLen; - const t0 = dbuToLatLng(pt.x + px * tickLen, pt.y + py * tickLen, scale, maxDXDY, originX, originY); - const t1 = dbuToLatLng(pt.x - px * tickLen, pt.y - py * tickLen, scale, maxDXDY, originX, originY); - group.addLayer(L.polyline([t0, t1], { - color, weight: 2, pane: 'ruler-pane', interactive: false, - })); + shapes.push({ kind: 'path', stroke: color, width: 2, points: [ + this._toWorld(pt.x + px * tickLen, pt.y + py * tickLen), + this._toWorld(pt.x - px * tickLen, pt.y - py * tickLen)] }); }; - if (joinPt) { - // Manhattan: ticks perpendicular to each segment addTick(ruler.pt0, joinPt.x - ruler.pt0.x, joinPt.y - ruler.pt0.y); addTick(ruler.pt1, ruler.pt1.x - joinPt.x, ruler.pt1.y - joinPt.y); } else { @@ -459,47 +404,84 @@ export class RulerManager { addTick(ruler.pt0, dx, dy); addTick(ruler.pt1, dx, dy); } + return shapes; + } - // Distance label at midpoint (or join point for Manhattan) - const dist = this._computeDistance(ruler.pt0, ruler.pt1, ruler.euclidian); - const midLat = pJoin ? pJoin[0] : (p0[0] + p1[0]) / 2; - const midLng = pJoin ? pJoin[1] : (p0[1] + p1[1]) / 2; - const label = L.marker([midLat, midLng], { - icon: L.divIcon({ - className: 'ruler-label', - html: this._formatDistance(dist), - iconSize: null, - }), - pane: 'ruler-pane', - interactive: false, - }); - group.addLayer(label); + _renderAll() { + this._renderRulerShapes(); + this._renderRulerLabels(); + } - ruler._layerGroup = group; - this._rulerLayerGroup.addLayer(group); + _renderRulerShapes() { + const view = this._app.view; + if (!view || !this._app.designScale) return; + view.setOverlay('rulers', this._shown() + ? this._rulers.flatMap((r) => this._rulerShapes(r)) : null, + { order: DRAW_ORDER.ruler }); } - _rerenderAll() { - this._rulerLayerGroup.clearLayers(); + _renderRulerLabels() { + const view = this._app.view; + if (!view || !this._app.designScale) return; + view.clearMarkers('ruler-labels'); + if (!this._shown()) return; + // Distance label at the midpoint, or at the join for Manhattan. for (const ruler of this._rulers) { - this._renderRuler(ruler); + const { joinPt, points } = this._rulerPath(ruler); + const at = joinPt ? points[1] + : [(points[0][0] + points[1][0]) / 2, + (points[0][1] + points[1][1]) / 2]; + const dist = this._computeDistance(ruler.pt0, ruler.pt1, + ruler.euclidian); + view.addMarker('ruler-labels', ruler.id, at, + this._labelElement(this._formatDistance(dist))); } } + // Select the ruler whose line passes within a few pixels of `world`. + // Returns true when one did, so the click is not also a selection. + handleRulerClick(world) { + const view = this._app.view; + if (!view || !this._shown() || this._rulers.length === 0) { + return false; + } + const p = view.project(world); + for (const ruler of this._rulers) { + const pts = this._rulerPath(ruler).points.map((w) => view.project(w)); + for (let i = 0; i + 1 < pts.length; i++) { + if (segmentDistance(p, pts[i], pts[i + 1]) <= kRulerHitPx) { + this._selectRuler(ruler.id); + return true; + } + } + } + return false; + } + // ─── Selection and inspector ───────────────────────────────────── _selectRuler(rulerId) { + // A client-side object that still takes the selection from the other + // panels; ours is dropped first, so their reset does not redraw it. + this._selectedRulerId = null; + beginSelection(this._app); this._selectedRulerId = rulerId; - this._rerenderAll(); + this._renderAll(); + this._inspectRuler(rulerId, { focus: true }); + } + // Shows the selected ruler in the Inspector again without taking the + // selection. + refreshInspector() { + if (this._selectedRulerId !== null) { + this._inspectRuler(this._selectedRulerId, { focus: false }); + } + } + + _inspectRuler(rulerId, { focus }) { const ruler = this._rulers.find(r => r.id === rulerId); if (!ruler) return; - // A ruler is a client-side object, but it still takes over the - // Inspector, so other panels must drop the selection they painted and - // any of their responses still in flight must not overwrite it. - beginSelection(this._app); - const dx = Math.abs(ruler.pt1.x - ruler.pt0.x); const dy = Math.abs(ruler.pt1.y - ruler.pt0.y); const length = ruler.euclidian @@ -562,42 +544,24 @@ export class RulerManager { ruler.euclidian = newValue.trim().toLowerCase() === 'true'; break; } - this._rerenderAll(); - this._selectRuler(ruler.id); + this._renderAll(); + this.refreshInspector(); }, + onDelete: () => this.deleteRuler(rulerId), }; this._updateInspector(data); - this._focusComponent('Inspector'); - - // Add delete button after inspector renders - requestAnimationFrame(() => { - const toolbar = this._app.inspectorEl?.querySelector('.inspector-toolbar'); - if (!toolbar) return; - - const deleteBtn = document.createElement('button'); - deleteBtn.className = 'or-btn or-btn-icon'; - deleteBtn.title = 'Delete ruler'; - deleteBtn.innerHTML = - '' + - '' + - ''; - deleteBtn.addEventListener('click', () => { - this.deleteRuler(rulerId); - }); - toolbar.appendChild(deleteBtn); - }); + if (focus) { + this._focusComponent('Inspector'); + } } deleteRuler(rulerId) { const idx = this._rulers.findIndex(r => r.id === rulerId); if (idx === -1) return; - const ruler = this._rulers[idx]; - if (ruler._layerGroup) { - this._rulerLayerGroup.removeLayer(ruler._layerGroup); - } this._rulers.splice(idx, 1); + this._renderAll(); if (this._selectedRulerId === rulerId) { this._selectedRulerId = null; @@ -627,20 +591,27 @@ export class RulerManager { } _setCursor(crosshair) { - const container = this._app.map?.getContainer(); - if (!container) return; - if (crosshair) { - container.classList.add('ruler-mode-cursor'); - } else { - container.classList.remove('ruler-mode-cursor'); - } + this._app.view?.setCursorMode('ruler', crosshair); } - _clearPreview() { - this._previewGroup?.clearLayers(); + _clearTransient() { + this._preview = null; + this._snapShapes = null; + this._drawTransient(); } _clearSnap() { - this._snapGroup?.clearLayers(); + this._snapShapes = null; + this._drawTransient(); } } + +// Distance in px from point p to segment ab. +function segmentDistance(p, a, b) { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const len2 = dx * dx + dy * dy; + let t = len2 > 0 ? ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2 : 0; + t = Math.max(0, Math.min(1, t)); + return Math.hypot(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy)); +} diff --git a/openroad/web/src/search-nav.js b/openroad/web/src/search-nav.js index 6138fa7750b..f2a70800880 100644 --- a/openroad/web/src/search-nav.js +++ b/openroad/web/src/search-nav.js @@ -6,8 +6,9 @@ // - Go to position: jump the view to x,y in microns (mirrors Qt GotoDialog). // Both reuse the .modal-overlay/.modal-dialog pattern from menu-bar.js. -import { dbuToLatLng, dbuRectToBounds, latLngToDbu } from './coordinates.js'; -import { applySelectionFlags, buildModal } from './ui-utils.js'; +import { dbuToWorld, worldToDbu } from './coordinates.js'; +import { applySelectionFlags, beginSelection, buildModal, isCurrentSelection, + zoomToBBox } from './ui-utils.js'; // The .search-nav-dialog rules size these two dialogs' rows; every caller here // passes it so buildModal itself stays dialog-agnostic. @@ -57,6 +58,9 @@ export function showFindDialog(app) { return; } showError('Searching…', true); + // Find takes the selection only once it has matches, and not from a + // selection that started while it was searching. + const issued = app.selectionToken; app.websocketManager .request({ type: 'find', @@ -65,27 +69,30 @@ export function showFindDialog(app) { match_case: caseChk.checked, }) .then((resp) => { - applySelectionFlags(app, resp); const count = resp && resp.count ? resp.count : 0; if (!count) { showError('No objects found.'); return; } + if (!isCurrentSelection(app, issued)) { + showError(`${count} found.`, true); + return; + } + beginSelection(app); + // The outline is the last clicked object's; Find replaced it. + app.clearSelectionOutline?.(); + applySelectionFlags(app, resp); // Auto-zoom to the matched objects — an improvement over the Qt // Find dialog, which only selects without centering. if (Array.isArray(resp.bbox)) { - app.lastSelectionBounds = dbuRectToBounds( - resp.bbox[0], resp.bbox[1], resp.bbox[2], resp.bbox[3], - app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY); - app.map.fitBounds(app.lastSelectionBounds); + zoomToBBox(app, resp.bbox, 0); } if (typeof app.updateInspector === 'function') { app.updateInspector(resp); } - if (typeof app.redrawAllLayers === 'function') { - app.redrawAllLayers(); - } + // The selection is drawn on the overlay only; this also + // refreshes the Select Highlight panel. + app.refreshOverlay?.(); const shown = resp.selection_count || count; showError(resp.truncated ? `${count} found (showing first ${shown}).` @@ -104,7 +111,7 @@ export function showFindDialog(app) { // ── Go to position ────────────────────────────────────────────────────────── export function showGotoDialog(app) { - if (!app.designScale || !app.map) { + if (!app.designScale || !app.view) { return; } // Every field is read and written in whichever unit the "Show DBU" @@ -116,9 +123,9 @@ export function showGotoDialog(app) { // Prefill X/Y with the current view center, so "Go to" with no edits is // a no-op. - const c = app.map.getCenter(); - const centerDbu = latLngToDbu(c.lat, c.lng, app.designScale, - app.designMaxDXDY, app.designOriginX, app.designOriginY); + const c = app.view.getCenter(); + const centerDbu = worldToDbu(c[0], c[1], app.designScale, + app.designOriginX, app.designOriginY); const { overlay, close, okBtn, showError } = buildModal('Go to Position', `
@@ -142,20 +149,18 @@ export function showGotoDialog(app) { showError(`X and Y must be numbers (${unit}).`); return; } - const latlng = dbuToLatLng(dbuX, dbuY, app.designScale, - app.designMaxDXDY, app.designOriginX, app.designOriginY); // A size of 0 or less is not a window; fall through to the recentre. const sizeVal = sizeIn.value.trim(); const sizeDbu = sizeVal ? parse(sizeVal) : null; if (sizeDbu !== null && sizeDbu > 0) { const half = sizeDbu / 2; - app.map.fitBounds(dbuRectToBounds( - dbuX - half, dbuY - half, dbuX + half, dbuY + half, - app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY)); + zoomToBBox(app, [dbuX - half, dbuY - half, dbuX + half, dbuY + half], + 0); } else { - app.map.setView(latlng, app.map.getZoom()); + app.view.setView(dbuToWorld(dbuX, dbuY, app.designScale, + app.designOriginX, app.designOriginY), + app.view.getZoom()); } close(); } diff --git a/openroad/web/src/selection-browser.js b/openroad/web/src/selection-browser.js index f930d4234de..5a649f86f7d 100644 --- a/openroad/web/src/selection-browser.js +++ b/openroad/web/src/selection-browser.js @@ -7,7 +7,7 @@ // never acts on the wrong object (the Qt dock's context menus use proxy // rows without mapToSource and mis-target under sorting). -import { dbuRectToBounds } from './coordinates.js'; +import { dbuRectToWorldRect } from './coordinates.js'; import { ColumnWidths, isStaticMode, makeResizableHeaders } from './ui-utils.js'; @@ -187,16 +187,16 @@ export class SelectionBrowser { } _zoomToBBox(bbox) { - if (!bbox || !this._app.designScale || !this._app.map) return; + if (!bbox || !this._app.designScale || !this._app.view) return; const [xMin, yMin, xMax, yMax] = bbox; // Same margin rule as the DRC widget / Qt zoom-to handlers. const dbuPerMicron = this._app.getDbuPerMicron ? this._app.getDbuPerMicron() : 1000; const margin = Math.min(10 * dbuPerMicron, 2 * Math.max(xMax - xMin, yMax - yMin)); - this._app.map.fitBounds(dbuRectToBounds( + this._app.view.fitWorldRect(dbuRectToWorldRect( xMin - margin, yMin - margin, xMax + margin, yMax + margin, - this._app.designScale, this._app.designMaxDXDY, + this._app.designScale, this._app.designOriginX, this._app.designOriginY)); } diff --git a/openroad/web/src/style.css b/openroad/web/src/style.css index 4523fb87cae..3db9427ba39 100644 --- a/openroad/web/src/style.css +++ b/openroad/web/src/style.css @@ -42,7 +42,7 @@ --space-xl: 16px; /* Floating overlays on the layout canvas -- scale bar, coordinate - * readout, heat-map legend, Leaflet's zoom and Fit controls. These do + * readout, heat-map legend, the zoom and Fit buttons. These do * not flip with the theme: they sit on --bg-map, which is black in both * themes for Qt parity, so a light surface here would be a bright block * on black and light-theme ink on it would be unreadable. */ @@ -286,22 +286,18 @@ html[data-theme="light"] { /* ─── Ruler overlay ──────────────────────────────────────────────────────── */ -/* Placement-mode crosshair for the ruler and label tools. Qualified with - .leaflet-container so it outranks that element's own `cursor: default - !important` below on specificity; a bare .ruler-mode-cursor ties it and - loses the source-order tiebreak. .leaflet-dragging still wins over both, - so panning shows the grab cursor. */ -.leaflet-container.ruler-mode-cursor, -.leaflet-container.label-mode-cursor { - cursor: crosshair !important; +/* Placement-mode crosshair for the ruler and label tools. The canvas takes + its cursor from the view (setCursorMode); this covers the markers above it. */ +.or-view.ruler-mode-cursor, +.or-view.label-mode-cursor { + cursor: crosshair; } /* While a request the user waits on runs (withBusyCursor in ui-utils.js): - the progress cursor everywhere, the map included, whose own cursors are - !important and as specific as two classes. */ + the progress cursor everywhere, the layout view included, whose cursor the + view sets inline. */ body.op-busy, -body.op-busy *, -body.op-busy .leaflet-container.leaflet-container { +body.op-busy * { cursor: progress !important; } .ruler-label { @@ -1343,66 +1339,87 @@ body.is-resizing-h * { background: var(--line-2); } -/* Leaflet map cursor */ -.leaflet-container { - cursor: default !important; +/* ─── Layout view ─────────────────────────────────────────────────────────── */ + +/* The view's container (layout-view.js): the deck.gl canvas, sized to whole + device pixels from the top-left corner, and DOM markers pinned over it. */ +.or-view { + position: relative; + overflow: hidden; + cursor: default; + touch-action: none; +} +.or-view-canvas { + position: absolute; + left: 0; + top: 0; } -/* Leaflet draws its own control chrome (white background, dark border), which - is the app's theme only by coincidence. Restyle the bar rather than each - control, so the zoom buttons and the Fit button below them match. */ -.leaflet-bar { +.or-view-markers { + position: absolute; + inset: 0; + z-index: 700; + overflow: hidden; + pointer-events: none; +} +.or-view-marker { + position: absolute; + left: 0; + top: 0; +} +.or-view-marker.label-handle { + pointer-events: auto; +} + +/* Zoom in / out and Fit, top-left of the view. */ +.or-zoom-control { + position: absolute; + top: 10px; + left: 10px; + z-index: 1000; + display: flex; + flex-direction: column; border: 1px solid var(--border-hud); border-radius: var(--radius-sm); box-shadow: 0 4px 14px var(--shadow-strong); overflow: hidden; } -.leaflet-bar a, -.leaflet-bar a:hover { +.or-zoom-control button { + width: 30px; + height: 30px; + padding: 0; + border: none; + border-bottom: 1px solid var(--border-hud); background: var(--bg-hud); color: var(--fg-hud); - border-bottom-color: var(--border-hud); + font: bold 18px/30px var(--font-mono); + text-align: center; + cursor: pointer; backdrop-filter: blur(3px); transition: background-color 120ms ease, color 120ms ease; } -.leaflet-bar a:hover { +.or-zoom-control button:last-child { + border-bottom: none; +} +.or-zoom-control button:hover { background: rgba(255, 255, 255, 0.14); color: #fff; } -.leaflet-bar a.leaflet-disabled { +.or-zoom-control button:disabled { background: var(--bg-hud); color: rgba(238, 244, 248, 0.4); -} -/* "Fit" control button — inherits .leaflet-bar sizing from Leaflet's CSS. */ -.leaflet-control-fit a { - font-size: var(--fs-16); - font-weight: bold; - line-height: 26px; - text-align: center; -} -.leaflet-dragging .leaflet-container { - cursor: grabbing !important; -} - -/* Leaflet tiles. - Keep `auto` (bilinear): tiles are band-limited server-side and displayed - 1:1 at rest (integer zoom) and HiDPI-exact (256*dpr image in a 256 CSS-px - box), so the only resampling is benign upscaling during zoom animation, - where bilinear is correct. `pixelated` would block-up that upscale. */ -.leaflet-tile { - image-rendering: auto; + cursor: default; } .layout-viewer { position: relative; } /* Drawn as an overlay rather than a border, for two reasons: a border on this - element would change the size Leaflet measures for the map, and an inset - box-shadow would be painted under the tile panes and never seen. z-index - 800 puts it over the panes (Leaflet's go up to 700) but under the HUD (900) - and Leaflet's own controls (1000), so it frames the canvas without drawing - a line across either. The inner shadow is invisible against the default - black and does its work when the Background control is set to something - light. */ + element would change the size the view measures, and an inset box-shadow + would be painted under the canvas and never seen. z-index 800 puts it over + the canvas and markers (700) but under the HUD (900) and the zoom buttons + (1000), so it frames the canvas without drawing a line across either. The + inner shadow is invisible against the default black and does its work when + the Background control is set to something light. */ .layout-viewer::after { content: ''; position: absolute; @@ -1445,19 +1462,6 @@ body.is-resizing-h * { to { left: 100%; } } -/* Leaflet popups */ -.leaflet-popup-content-wrapper { - background: var(--bg-context); - color: var(--fg-bright); - border-radius: var(--radius-sm); -} -.leaflet-popup-content { - font-family: var(--font-mono); -} -.leaflet-popup-content strong { - color: var(--accent-text); -} - /* Status overlay */ #websocket-status { position: fixed; @@ -2257,6 +2261,49 @@ body.is-resizing-h * { #or-toast.visible { opacity: 1; } +/* A warning that stays in the page's bottom-right corner until closed. */ +.or-corner-warning { + position: fixed; + right: var(--space-md); + bottom: var(--space-md); + max-width: 360px; + display: flex; + align-items: flex-start; + gap: var(--space-sm); + padding: var(--space-md); + background: var(--bg-context); + color: var(--fg-primary); + border: 1px solid var(--border-strong); + border-left: 4px solid var(--sem-warn); + border-radius: var(--radius-md); + box-shadow: 0 6px 20px var(--shadow-strong); + font-size: var(--fs-12); + z-index: 3000; +} +.or-corner-warning-close { + flex: none; + padding: 0 var(--space-sm); + background: none; + border: none; + color: var(--fg-secondary); + font-size: var(--fs-16); + line-height: 1; + cursor: pointer; +} +.or-corner-warning-close:hover { + color: var(--fg-primary); +} +.or-corner-warning-never { + display: block; + margin-top: var(--space-sm); + padding: 0; + background: none; + border: none; + color: var(--accent-link); + font: inherit; + text-decoration: underline; + cursor: pointer; +} /* Holds the property rows so the column divider can be absolutely positioned * over their full height. */ .inspector-rows { @@ -2397,49 +2444,6 @@ body.is-resizing-h * { display: none; } -/* Hover highlight pulse animation */ -.hover-highlight { - stroke: #ffe85c; - stroke-width: 3px; - stroke-opacity: 1; - fill: #fff27a; - fill-opacity: 0.14; - vector-effect: non-scaling-stroke; - animation: hover-pulse 0.9s ease-out 3; -} -@keyframes hover-pulse { - 0% { - stroke: #fff6b0; - stroke-width: 7px; - stroke-opacity: 1; - fill-opacity: 0.28; - } - 55% { - stroke: #ffffff; - stroke-width: 5px; - stroke-opacity: 1; - fill-opacity: 0.06; - } - 100% { - stroke: #ffe85c; - stroke-width: 3px; - stroke-opacity: 0.95; - fill-opacity: 0.14; - } -} - -/* Selection pulse: brief flash when the inspector changes its target */ -.selection-pulse { - pointer-events: none; - animation: selection-pulse 350ms ease-in-out 3; - animation-fill-mode: forwards; -} -@keyframes selection-pulse { - 0% { stroke-opacity: 0; fill-opacity: 0; } - 50% { stroke-opacity: 1; fill-opacity: 0.28; } - 100% { stroke-opacity: 0; fill-opacity: 0; } -} - /* ─── Timing Widget ────────────────────────────────────────────────────── */ .timing-widget { @@ -3149,16 +3153,6 @@ html[data-theme="dark"] .schematic-svg-container svg .schematic-net-dot { color: var(--error); } -/* DRC highlight flash animation — pulses tile opacity to mimic - the Qt GUI's yellow blinking highlight on visible markers. */ -@keyframes drc-pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.3; } -} -.drc-flashing .leaflet-tile-pane { - animation: drc-pulse 0.4s ease-in-out 3; -} - /* ─── Focus and motion ────────────────────────────────────────────────────── */ /* :focus-visible rather than :focus, so the ring appears for keyboard diff --git a/openroad/web/src/tile-grid.js b/openroad/web/src/tile-grid.js new file mode 100644 index 00000000000..3533ecd7e05 --- /dev/null +++ b/openroad/web/src/tile-grid.js @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// The tiles of one slot of the layout view: which to load for the view, which +// to cancel and which to drop. Pure: loading goes through `source`, drawing +// is the view's business. +// +// `source.load({z, x, y}, {background, onPartial})` returns +// `{ promise, cancel, promote }`; the promise resolves to a drawable, to null +// for an empty tile, or to undefined to keep the last partial. +// `source.release(drawable)` frees one. + +import { growRange, inRange, rangeTiles } from './view-math.js'; + +export function tileKey(z, x, y) { + return `${z}/${x}/${y}`; +} + +export class TileGrid { + constructor({ source, onChange = () => {}, keepBuffer = 2 } = {}) { + this.source = source; + this.onChange = onChange; + this.keepBuffer = keepBuffer; + this.tiles = new Map(); + this.z = null; + this.range = null; // on screen + this.ring = null; // on screen plus the prefetch ring + this.extra = []; // other levels kept loaded: [{ z, range }] + this._generation = 0; + this._loads = 0; // for debugSnapshot + this._cancels = 0; + } + + // Bring level z in line with the view: load what `ring` covers, on-screen + // tiles first and the rest at background priority, and cancel what left. + // `extra` levels load over their own ranges, in the background unless + // they say `background: false`. Loaded tiles in `hold`, what is on + // screen now when `range` is where the view is heading, are kept. + update({ z, range, ring = range, extra = [], hold = null }) { + this.z = z; + this.range = range; + this.ring = ring; + this.extra = extra.filter((e) => e.z !== z && e.range); + const extraOf = new Map(this.extra.map((e) => [e.z, e])); + for (const tile of [...this.tiles.values()]) { + if (tile.z !== z) { + const e = extraOf.get(tile.z); + const r = e && e.range; + // An extra level keeps a buffer like level z; any other level + // is left to prune(), which knows what is drawn. + const drop = r + ? !inRange(r, tile.x, tile.y) + && (tile.loading || !this._inKeepBuffer(tile, r)) + : tile.loading && !tile.drawable; + if (drop) { + this._drop(tile); + } else if (r && this._stale(tile) + && inRange(r, tile.x, tile.y)) { + this._load(tile, e.background !== false); + } + continue; + } + if (inRange(ring, tile.x, tile.y)) { + // A stale load is replaced below, not promoted. + if (tile.loading && tile.background && !this._stale(tile) + && inRange(range, tile.x, tile.y)) { + tile.background = false; + tile.handle?.promote?.(); + } + continue; + } + // A view off the grid keeps what it had, for when it pans back. + if (tile.loading || !(range === null || this._inKeepBuffer(tile) + || (hold && inRange(hold, tile.x, tile.y)))) { + this._drop(tile); + } + } + // On-screen tiles go out first, nearest the center first. + const wanted = [...rangeTiles(range), + ...rangeTiles(ring).filter( + (t) => !inRange(range, t.x, t.y))]; + for (const { x, y } of wanted) { + const tile = this.tiles.get(tileKey(z, x, y)); + if (!tile) { + this._load(this._newTile(z, x, y), !inRange(range, x, y)); + } else if (this._stale(tile)) { + // Kept from before a refresh. + this._load(tile, !inRange(range, x, y)); + } + } + for (const e of this.extra) { + for (const { x, y } of rangeTiles(e.range)) { + if (!this.tiles.has(tileKey(e.z, x, y))) { + this._load(this._newTile(e.z, x, y), + e.background !== false); + } + } + } + } + + // Re-request the tiles of the ring and of the extra ranges in place: each + // keeps what it shows until its replacement arrives. The rest goes stale + // and is fetched when it is back in range; other levels wait for prune(). + refresh() { + this._generation++; + const extraOf = new Map(this.extra.map((e) => [e.z, e])); + for (const tile of [...this.tiles.values()]) { + const e = extraOf.get(tile.z); + const r = tile.z === this.z ? this.ring : e && e.range; + if (!r) { + continue; + } + if (inRange(r, tile.x, tile.y)) { + this._load(tile, e ? e.background !== false + : !inRange(this.range, tile.x, tile.y)); + } else if (tile.loading) { + this._drop(tile); + } + } + } + + // True when no on-screen tile of the current level is still loading. + // Ring tiles do not count: they are off screen. + isSettled() { + for (const tile of this.tiles.values()) { + if (tile.z === this.z && tile.loading + && inRange(this.range, tile.x, tile.y)) { + return false; + } + } + return true; + } + + // True when every tile of level z in `range` has arrived. + settledIn(z, range) { + for (const { x, y } of rangeTiles(range)) { + const tile = this.tiles.get(tileKey(z, x, y)); + if (!tile || tile.loading) { + return false; + } + } + return true; + } + + // True when level z has at least one tile with something to draw. + hasContentAt(z) { + for (const tile of this.tiles.values()) { + if (tile.z === z && tile.drawable) { + return true; + } + } + return false; + } + + // Tiles of level z that have something to draw. + drawableTilesAt(z) { + const out = []; + for (const tile of this.tiles.values()) { + if (tile.z === z && tile.drawable) { + out.push(tile); + } + } + return out; + } + + // Drop every tile whose level is not in `keepZs`. + prune(keepZs) { + const keep = new Set(keepZs); + for (const tile of [...this.tiles.values()]) { + if (!keep.has(tile.z)) { + this._drop(tile); + } + } + } + + clear() { + for (const tile of [...this.tiles.values()]) { + this._drop(tile); + } + this.z = null; + this.range = null; + this.ring = null; + this.extra = []; + } + + stats() { + let loading = 0; + let drawable = 0; + for (const tile of this.tiles.values()) { + if (tile.loading) { + loading++; + } + if (tile.drawable) { + drawable++; + } + } + return { tiles: this.tiles.size, loading, drawable, + loads: this._loads, cancels: this._cancels }; + } + + _newTile(z, x, y) { + const tile = { z, x, y, key: tileKey(z, x, y), drawable: null, + loading: false, failed: false, background: false, + handle: null, generation: -1 }; + this.tiles.set(tile.key, tile); + return tile; + } + + _load(tile, background) { + this._cancelLoad(tile); + const generation = this._generation; + const current = () => this.tiles.get(tile.key) === tile + && tile.generation === generation; + tile.generation = generation; + tile.loading = true; + tile.background = background; + this._loads++; + const handle = this.source.load( + { z: tile.z, x: tile.x, y: tile.y }, + { + background, + // Progressive paints while the tile is still loading. + onPartial: (drawable) => { + if (!current()) { + this.source.release?.(drawable); + return; + } + this._setDrawable(tile, drawable); + this.onChange(tile); + }, + }); + tile.handle = handle; + handle.promise.then((drawable) => { + if (!current()) { + this.source.release?.(drawable); + return; + } + if (drawable !== undefined) { + this._setDrawable(tile, drawable); + } + tile.loading = false; + tile.failed = false; + tile.handle = null; + this.onChange(tile); + }, () => { + // A failed tile counts as settled and keeps whatever it showed. + if (!current()) { + return; + } + tile.loading = false; + tile.failed = true; + tile.handle = null; + this.onChange(tile); + }); + } + + _setDrawable(tile, drawable) { + if (tile.drawable && tile.drawable !== drawable) { + this.source.release?.(tile.drawable); + } + tile.drawable = drawable || null; + } + + // From before a refresh, loading or not: a load still in flight asked for + // what the refresh replaced. + _stale(tile) { + return tile.generation !== this._generation; + } + + _inKeepBuffer(tile, r = this.range) { + return inRange(growRange(r, this.keepBuffer), tile.x, tile.y); + } + + _cancelLoad(tile) { + if (tile.loading) { + this._cancels++; + tile.handle?.cancel?.(); + } + } + + _drop(tile) { + this._cancelLoad(tile); + if (tile.drawable) { + this.source.release?.(tile.drawable); + } + tile.drawable = null; + tile.loading = false; + this.tiles.delete(tile.key); + } +} diff --git a/openroad/web/src/tile-merge.js b/openroad/web/src/tile-merge.js index c9db9765ccd..06b6be9b317 100644 --- a/openroad/web/src/tile-merge.js +++ b/openroad/web/src/tile-merge.js @@ -1,145 +1,19 @@ // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2026, The OpenROAD Authors -// Client-side tile merging: collapse many single-layer tile panes into N -// composited panes, chosen from a decoded-image-memory budget. +// Client-side tile merging: composite the visible layout layers of one tile +// into a single image, so the view holds and draws one texture per tile +// instead of one per layer. The server keeps one cached tile per layer, which +// a layer toggle reuses. // -// WHY -// -// The viewer keeps one Leaflet pane per (tech layer x chiplet instance). On a -// multi-die design that is ~97 panes, each holding a full grid of tiles, each -// tile decoding to (256*dpr)^2 * 4 bytes — 582 MB at dpr 1 in a 1240x999 -// window. Measured on that machine, Chrome starts discarding decoded images -// somewhere around 458 MB, and the discarded regions paint white and stay white -// until something forces a full invalidation. Established by measurement: the -// symptom is monotonic in decoded image bytes and indifferent to how they are -// distributed — at a matched 516 vs 517 MB, 86 and 97 content-bearing panes -// fail identically, which rules out pane count and stack depth. -// -// WHY THE MERGE IS ON THE CLIENT -// -// The client already knows the exact stacking order and per-pane opacity, so -// merging here reproduces precisely what the browser does today — one -// rasterization instead of K live layers — with no change to the renderer, no -// new wire format, and no decision about how chiplets should be ordered -// relative to each other. It also keeps the server's per-layer tile cache -// intact, which a server-side composite would coarsen. -// -// The mechanism that makes it work is `ImageBitmap.close()`: an gives no -// control over when its decoded bitmap is released, which is the whole problem. -// createImageBitmap + close() makes the lifetime explicit — decode K sources, -// draw them, release them immediately, and keep only the merged result. -// -// What it does NOT buy: bandwidth. The same K images are still fetched per -// tile. Only a server-side composite fixes that. - -// ─── Opacity ──────────────────────────────────────────────────────────────── -// -// Each layer's opacity is applied by Leaflet to the layer's CONTAINER div, not -// to the individual tile images: GridLayer._updateOpacity() calls -// setOpacity(this._container, this.options.opacity). Every layer is created at -// 1 — layer transparency lives in the tile pixels themselves, painted with the -// palette alpha the Qt GUI uses — but the merge still carries opacity per item -// rather than assuming one value, so a pane that does want partial opacity -// composites correctly. -// -// Group opacity on a container is NOT generally the same thing as per-image -// alpha: a group is rasterized at full alpha and then blended once, so anywhere -// two images inside the group overlap, group opacity blends the overlap once -// while per-image alpha blends it twice. It is safe here only because a -// layer's own tiles tile the plane without overlapping, which makes the two -// equivalent for a single layer — and that equivalence is what lets this module -// apply each source's opacity per-image with globalAlpha. -// -// (One transient exception: mid zoom-animation Leaflet keeps the outgoing zoom -// level's tiles alongside the incoming ones inside the same container, and those -// DO overlap. That is pre-existing behaviour at the layer level and applies -// equally to a merged pane, so it is not made worse here.) -// -// The trap: the merged result is itself a tile inside a pane. If that pane -// carried a source's opacity too, every source would be multiplied by it twice -// — 0.7 becomes 0.49 — and the view would wash out. The per-layer opacities -// live INSIDE the canvas, so the pane holding it must be fully opaque. -export const MERGED_PANE_OPACITY = 1; - -// Build the Leaflet options for a merged pane, so a caller cannot forget the -// above and silently double-apply opacity. -export function mergedPaneOptions({ zIndex = 0, tileSize } = {}) { - const opts = { opacity: MERGED_PANE_OPACITY, zIndex }; - if (tileSize !== undefined) { - opts.tileSize = tileSize; - } - return opts; -} - -// Bytes of decoded bitmap for one tile. Straight RGBA, which is what the -// browser holds regardless of the PNG's own bit depth — an 8-bit palette PNG -// still decodes to 32 bits per pixel, so compressing harder saves nothing here. -export const BYTES_PER_PIXEL = 4; - -// Default budget for decoded tile images. Chosen from the measurement, not from -// taste: ~458 MB was where the failure started on the machine that was profiled, -// 462 MB already showed flicker, and 456 MB was clean. 350 MB leaves ~23% margin -// under that, which matters because the real ceiling varies with the machine, the -// Chrome build and whatever else the renderer is holding. -// -// Deliberately not derived from `navigator.deviceMemory`: no API reports the -// image-cache budget, and the failure cannot be probed for without triggering -// it. A fixed conservative cap that is *enforced* beats a discovered number that -// might be wrong. Callers may scale this if they have better information. -export const DEFAULT_BUDGET_BYTES = 350 * 1024 * 1024; - -export function tileBytes(tileSizePx, dpr = 1) { - const side = Math.round(tileSizePx * Math.max(0, dpr)); - return side * side * BYTES_PER_PIXEL; -} - -// Tiles one pane holds for a viewport of this size. -// -// Leaflet covers the viewport and keeps a ring of tiles outside it, so this is -// (cols+1) x (rows+1) — deliberately an estimate, because the real count is only -// knowable once tiles exist and the budget has to be decided before then. It -// tracks window area, which is the factor that would otherwise make any fixed -// group count fail on a maximised 4K window. -export function estimateTilesPerPane(width, height, tileSizePx = 256) { - if (!(width > 0) || !(height > 0) || !(tileSizePx > 0)) { - return 1; - } - return (Math.ceil(width / tileSizePx) + 1) - * (Math.ceil(height / tileSizePx) + 1); -} - -// Viewport to size the budget against, with fallbacks. -// -// A container that is hidden or not yet laid out reports clientWidth 0, and a -// zero viewport is the dangerous direction: estimateTilesPerPane returns 1, -// computeGroupCount then divides the whole budget by one tile and comes back -// with groupCount == paneCount — one pane per layer, no merging at all, and the -// log cheerfully reports "merged 94 layers into 94 panes". The failure this -// exists to prevent then happens as soon as the panel is shown. -// -// Falling back to the window over-estimates (the map is a panel inside a -// layout, not the whole window), and over-estimating is safe: more tiles per -// pane means fewer panes, which is the conservative side of the budget. -export function measureViewport(container, win) { - const w = win || (typeof window !== 'undefined' ? window : null); - const width = (container && container.clientWidth > 0) - ? container.clientWidth - : ((w && w.innerWidth > 0) ? w.innerWidth : 1024); - const height = (container && container.clientHeight > 0) - ? container.clientHeight - : ((w && w.innerHeight > 0) ? w.innerHeight : 768); - return { width, height }; -} +// The sources are ImageBitmaps, closed as soon as the tile is complete: an +// gives no control over when its decoded bitmap is released. // Set a draw item's visibility, returning whether it actually changed. // // The return value is the point. The layer tree's onChange walks EVERY node -// and asserts the desired state on each one, so a caller that marks its pane -// dirty unconditionally re-requests every tile in every pane on any checkbox -// click — roughly 2300 requests on the 97-layer design that motivated this. -// The per-layer panes never had that problem because Leaflet's addTo() is a -// no-op for a layer already on the map; this restores the same property. +// and asserts the desired state on each one, so a caller that marks its tiles +// dirty unconditionally re-requests every tile on any checkbox click. export function setItemVisible(item, visible) { if (!item) { return false; @@ -152,109 +26,27 @@ export function setItemVisible(item, visible) { return true; } -// Panes that stay unmerged and so are not counted by the grouping, but do hold -// a full grid of tiles each: _instances, _pins, _inst_labels (on with the -// instance names, the default) and the always-on highlight overlay. The gated -// overlays stay mounted too (see display-controls.js), but while switched off -// their tiles are a shared 1x1 transparent PNG, so they hold no grid worth -// reserving for; switching one on pushes the total up by a pane. -// -// At dpr 1 these are ~6 MB each and hardly matter. At dpr 3 a tile is 2.25 MB, -// so a pane is ~54 MB and the four together are ~216 MB — enough that a budget -// which ignored them would report a comfortable fit while the real total sat -// above the ceiling. -export const UNMERGED_PANE_COUNT = 4; - -// Budget left for the merged panes once the unmerged ones are charged for. -// -// Never returns less than one group's worth: the viewer has to render -// something, and a budget so small that no group fits would be a blank map -// rather than a slow one. -export function reserveForUnmergedPanes(budgetBytes, tilesPerPane, - bytesPerTile, - unmergedPanes = UNMERGED_PANE_COUNT) { - const perPane = tilesPerPane * bytesPerTile; - if (!(perPane > 0)) { - return budgetBytes; - } - return Math.max(perPane, budgetBytes - unmergedPanes * perPane); -} - -// How many merged panes fit in the budget. -// -// `tilesPerPane` must come from what Leaflet actually holds, not from the -// viewport size, because it includes the retained ring outside the view and -// grows with window area — the factor that would otherwise make any fixed N -// fail on a maximised 4K window (97 panes at 2560x1440 is ~1.9 GB). -export function computeGroupCount({ - budgetBytes = DEFAULT_BUDGET_BYTES, - tilesPerPane, - bytesPerTile, - paneCount, -} = {}) { - if (!(tilesPerPane > 0) || !(bytesPerTile > 0) || !(paneCount > 0)) { - return 1; - } - const perGroup = tilesPerPane * bytesPerTile; - // Never more groups than there are panes to put in them: merging cannot - // help past one pane per group, and asking for more would just recreate the - // situation this exists to avoid. - return Math.max(1, Math.min(paneCount, Math.floor(budgetBytes / perGroup))); -} - -// Split z-ordered draw items into `n` groups. -// -// Groups MUST be contiguous runs of the z-order. Each group is rasterized into -// a single image, and two images can only be stacked to reproduce the original -// if neither interleaves with the other: given z-order [1,2,3,4], the grouping -// {1,3},{2,4} has no stacking that yields the original, whereas {1,2},{3,4} -// does. So this slices the ordered list rather than distributing round-robin, -// even though round-robin would balance sizes better. +// ─── Opacity ──────────────────────────────────────────────────────────────── // -// `items` must already be sorted by ascending z-index (bottom-most first). -export function partitionIntoGroups(items, n) { - if (!Array.isArray(items) || items.length === 0) { - return []; - } - const groups = Math.max(1, Math.min(Math.floor(n) || 1, items.length)); - const base = Math.floor(items.length / groups); - let remainder = items.length % groups; - const out = []; - let at = 0; - for (let g = 0; g < groups; g++) { - let size = base; - if (remainder > 0) { - size++; - remainder--; - } - out.push(items.slice(at, at + size)); - at += size; - } - return out; -} +// Each source carries its own opacity, applied per image with globalAlpha. A +// layer's own tiles never overlap, so that equals opacity on the whole layer. +// The merged tile already holds those opacities and must be drawn at 1, or +// every source would be multiplied twice. // Draw `sources` onto a 2D context in order, each at its own opacity. // -// Straight src-over at the given alpha, which is what stacking the panes does -// today. Not bit-identical to CSS compositing — colour-space and rounding +// Straight src-over at the given alpha, which is what stacking the layers +// would do. Not bit-identical to GPU compositing — color-space and rounding // details differ — so assert on visual equivalence, never on byte equality. // // `sources` is [{ image, opacity }], bottom-most first. A null image is skipped // rather than throwing: one layer failing to decode must not lose the whole // group, which would turn a single missing layer into a blank tile. export function mergeOntoContext(ctx, sources, size) { - if (!ctx || !(size > 0)) { - return 0; - } ctx.clearRect(0, 0, size, size); let drawn = 0; - for (const source of sources || []) { - const image = source ? source.image : null; - if (!image) { - continue; - } - const opacity = source.opacity === undefined ? 1 : source.opacity; - if (!(opacity > 0)) { + for (const { image, opacity = 1 } of sources) { + if (!image || !(opacity > 0)) { continue; } ctx.globalAlpha = Math.min(1, opacity); @@ -267,11 +59,11 @@ export function mergeOntoContext(ctx, sources, size) { // ─── Reference compositor ─────────────────────────────────────────────────── // -// Why grouping is exact at all: src-over is associative, so +// Why merging is exact at all: src-over is associative, so // (A over B) over C == A over (B over C). Rasterizing a contiguous run into one // image and compositing that image is therefore identical to compositing the run // member by member — PROVIDED the intermediate keeps its alpha (a transparent -// canvas does) and is composited at alpha 1 (hence MERGED_PANE_OPACITY). +// canvas does) and is composited at alpha 1. // // These helpers exist so that invariant is checked with numbers instead of // asserted in a comment. They are not used by the merge itself, which delegates @@ -319,56 +111,30 @@ export function closeAll(images) { // ─── Rendering one merged tile ────────────────────────────────────────────── // -// The orchestration, with every browser dependency injected so it can be tested -// without a DOM: `request` fetches one item's tile, `decode` turns a payload -// into something drawable, `draw` composites, `release` frees the decodes. -// -// Ordering: the K requests go out together, because they are independent and -// serialising them would multiply latency by K. The canvas is recomposited -// from scratch on every arrival, always walking the item list in order, so the -// stacking cannot depend on the order responses happen to land in. +// Every browser dependency is injected: `request` fetches one item's tile, +// `decode` turns a payload into something drawable and `draw` composites. +// `items` is never empty; the source skips such a tile. // -// Incremental: the tile paints as soon as anything arrives rather than waiting -// for the slowest of its K layers, and keeps repainting as the rest land. A -// request that never settles therefore costs one missing layer instead of a -// blank tile — with the per-layer panes a stuck request blanked one layer, and -// waiting for the whole group would have made that a whole group. +// The requests go out together, and every arrival recomposites the list in +// order, so the stacking does not depend on the order the replies land in. // -// Lifetime: every decoded image is released in a finally, including on a draw -// failure or a stale abort. Explicit release is the entire reason for -// ImageBitmap over ; leaking here would reintroduce exactly the unbounded -// decoded-image growth this exists to bound. That rests on `request` always -// settling: a cancelled request has to reject rather than stay pending, or the -// finally never runs and the group's decodes are stranded (see -// WebSocketManager.cancel, which rejects both the queued and the sent case). +// Incremental (the default) paints as soon as anything arrives, so a request +// that never settles costs one layer, not the tile. `incremental: false` +// (Options > "Double buffering") paints once, after every request settled. // -// Partial failure is survivable by design: one item that fails to arrive or -// decode is skipped and the rest of the group still paints. Blanking the whole -// tile because one layer failed would turn a single dropped request into the -// symptom being fixed. +// Every decode is closed in a finally, so `request` must always settle: a +// cancelled request rejects (WebSocketManager.cancel). An item that fails to +// arrive or decode is skipped and the rest still paints. export async function renderMergedTile({ items, request, decode, draw, - release = closeAll, isStale = () => false, - onFirstDraw, -} = {}) { - const list = Array.isArray(items) ? items : []; - const stats = { requested: list.length, arrived: 0, decoded: 0, drawn: 0, - paints: 0, stale: false }; - if (list.length === 0) { - // An empty group still has to paint: the canvas is reused across - // refreshes, so skipping the draw would leave the previous content. - // Guarded only so a no-argument call is harmless — a real caller that - // forgets `draw` with a non-empty group still fails loudly below, - // which is what you want for a missing required dependency. - if (typeof draw === 'function') { - draw([]); - } - return stats; - } + incremental = true, +}) { + const stats = { requested: items.length, arrived: 0, decoded: 0, drawn: 0, + failed: 0, stale: false }; // A slot that has not arrived yet is drawn as nothing. That is exact, not // an approximation: transparent is the identity for src-over, so @@ -377,36 +143,26 @@ export async function renderMergedTile({ // what lets the tile paint before every layer is in without any risk of // getting the stacking wrong — the list is still walked in order every // time, so there is no prefix pointer or gap handling to get wrong. - const images = new Array(list.length).fill(null); - let painted = false; + const images = new Array(items.length).fill(null); function paint() { if (isStale()) { stats.stale = true; return; } - stats.drawn = draw(list.map((item, i) => ({ + stats.drawn = draw(items.map((item, i) => ({ image: images[i], opacity: item.opacity, }))) || 0; - stats.paints++; - if (!painted) { - painted = true; - // Leaflet hides a tile until done() marks it loaded - // (.leaflet-tile { visibility: hidden }), so without this the - // incremental paints would not be visible at all. - if (onFirstDraw) { - onFirstDraw(); - } - } } try { - await Promise.all(list.map(async (item, i) => { + await Promise.all(items.map(async (item, i) => { let payload = null; try { payload = await request(item); } catch (e) { + stats.failed++; return; // cancelled or dropped: leave the slot transparent } if (payload == null) { @@ -426,41 +182,21 @@ export async function renderMergedTile({ // even when this render has been superseded. images[i] = image; stats.decoded++; - paint(); + if (incremental) { + paint(); + } })); - // Nothing arrived at all — paint the empty composite anyway, so the - // tile resolves as blank rather than staying invisible forever. - if (!painted) { + // Buffered: the one paint, once every request settled. + if (!incremental) { paint(); } } finally { // Held until the tile is complete rather than released per draw: a // later arrival belongs UNDERNEATH layers already drawn, so the canvas // is recomposited from scratch each time and every source has to still - // be available. Peak is the same K bitmaps the batch version held. - release(images); + // be available. + closeAll(images); } return stats; } - -// Summary of what a grouping costs, for logging and for the HUD. -export function describePlan({ paneCount, groupCount, tilesPerPane, - bytesPerTile }) { - const mb = (bytes) => Math.round(bytes / (1024 * 1024)); - const before = paneCount * tilesPerPane * bytesPerTile; - const after = groupCount * tilesPerPane * bytesPerTile; - return { - paneCount, - groupCount, - tilesPerPane, - beforeMB: mb(before), - afterMB: mb(after), - // Peak extra while a group is being merged: its sources are decoded - // together, then closed. Worth reporting because a very small - // groupCount means very large groups, and the transient is what would - // bite if the merge held every source at once. - transientMB: mb(Math.ceil(paneCount / Math.max(1, groupCount)) - * bytesPerTile), - }; -} diff --git a/openroad/web/src/tile-request.js b/openroad/web/src/tile-request.js index 5ba95f8439f..7fef691b4df 100644 --- a/openroad/web/src/tile-request.js +++ b/openroad/web/src/tile-request.js @@ -1,21 +1,18 @@ // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2026, The OpenROAD Authors -// Wire format for tile requests, shared by the per-layer tile layer and the -// merged (multi-layer) one. -// -// Split out of websocket-tile-layer.js so both layer types share one definition -// of the payload and cannot drift on the wire — a divergence would give the two -// paths different server-side tile-cache keys, and one of them would miss the -// cache entirely. The flag columns come from buildVisibilityFlags for the same -// reason, shared with click-select and the Save export. +// Wire format for tile requests, shared by every tile source so they cannot +// drift on the wire — a divergence would give two paths different server-side +// tile-cache keys, and one of them would miss the cache entirely. The flag +// columns come from buildVisibilityFlags for the same reason, shared with +// click-select and the Save export. import { buildVisibilityFlags } from './ui-utils.js'; // Normalize the display's device pixel ratio into the value sent on the wire. // // The pixel size of a tile no longer comes from this: `tile_px` carries the -// exact device-pixel square the tile will occupy (see buildTileRequestFor), so +// exact device-pixel square the tile will occupy (see tileRequestBuilder), so // the image maps 1:1 onto the device grid and the browser never resamples it — // which is what would otherwise reintroduce the moiré beat on HiDPI displays. // Rounding the ratio and multiplying by the tile size, as this once did, cannot @@ -41,65 +38,25 @@ export function quantizeDpr(raw) { // 256 is not such a number. At a 1.6667 display scale (166%, ordinary on // Windows and Linux) 256 CSS px is 426.67 device px, so the tile *pitch* is // fractional: boundaries land at 426.67k device px and only every third one can -// sit on the grid, whatever the pane offset is. The browser antialiases the +// sit on the grid, whatever the view offset is. The browser antialiases the // other two into their neighbours, src-over leaves the coverage short of 1, and -// the pane background shows through as a dark hairline on every seam. +// the background shows through as a dark hairline on every seam. // // 240 = 2^4 * 3 * 5 is divisible by the denominator of every real ratio — // 1.25 = 5/4, 1.5 = 3/2, 1.6667 = 5/3, 1.75 = 7/4, 1.375 = 11/8, 1.1 = 11/10, // 2.5 = 5/2 — so tileSize*dpr comes out whole and the pitch is exact. // // Total decoded bytes barely move: the tiles are 6% smaller on a side and there -// are ~14% more of them, so the pixel count is a wash (see tile-merge.js for the -// budget). The cost is the extra request per tile. +// are ~14% more of them, so the pixel count is a wash. The cost is the extra +// request per tile. export const TILE_SIZE_CSS = 240; // Static reports carry tiles pre-rasterized at 256 CSS px by whoever authored // them. Those are files, not requests, so that path keeps the old size. export const STATIC_TILE_SIZE_CSS = 256; -// What an tile holds when the server drew nothing into it: a 1x1 -// transparent GIF. -// -// It has to hold SOMETHING. An with no src attribute but a CSS width and -// height is not nothing to the browser -- Chrome paints the empty replaced -// element, and since most tiles in a viewport are empty that came out as a grey -// grid over the whole layout, one cell per tile. Clearing the attribute is the -// obvious way to say "no image" and it is the wrong one. -// -// This costs a 1x1 decode, 4 bytes, so it keeps what the empty response is for: -// the tile still does not decode a full-size transparent PNG or hold a bitmap -// the size of the tile. Its load event also fires, which is what completes the -// tile with Leaflet -- see the tile layers, which keep a tile hidden until then. -// -// It carries a Graphic Control Extension declaring colour 0 transparent. A 1x1 -// GIF without one is a common paste and is NOT transparent: an stretches -// its single opaque pixel over the whole tile, so a viewport of empty tiles -// comes out a solid wash instead of showing the layout underneath. This exact -// image is also the only blank a tile may hold: a 1x1 PNG in its place leaves a -// grey fringe per tile in Firefox, which lines up into a grid over the layout. -export const BLANK_TILE - = 'data:image/gif;base64,' - + 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; - -// Release the object URL a tile is holding, if that is what it holds. Every -// path that drops a tile image -- a new src, the load event, a pruned tile -- -// has to do this or the blob stays alive for the life of the document. -export function releaseTileBlob(tile) { - if (tile.src && tile.src.startsWith('blob:')) { - URL.revokeObjectURL(tile.src); - } -} - -// Point a tile at an image. Every src assignment in every tile layer goes -// through here, so there is one answer to what an empty tile holds. -export function setTileSrc(tile, src) { - releaseTileBlob(tile); - tile.src = src; -} - // The CSS tile size in force for this session. Resolved once rather than -// passed around: the map's coordinate scale, all three tile layers and the +// passed around: the view's coordinate scale, every tile slot and the // request payload must agree on it, and a value threaded through five call // sites is a value that eventually disagrees with itself. let tile_size_css = TILE_SIZE_CSS; @@ -133,7 +90,7 @@ const LAYOUT_UNIT = 1 / 64; // a size is whole in device pixels at ALL of them exactly when it is a // multiple of lcm(4,3,8,2,3,4,6,2,10) = 120. Sizes chosen for the current // ratio alone would come apart the moment devicePixelRatio changes -- browser -// zoom, or the window moving to another monitor -- and the tile panes are +// zoom, or the window moving to another monitor -- and the tile slots are // built once, so nothing re-picks the size. Keeping to the quantum makes the // choice independent of dpr and bounds the tile-cache key space the server // sees to two sizes instead of a continuum. @@ -153,7 +110,7 @@ export function isDeviceExactTileSize(size, dpr) { // Adopt a tile size picked to make zoom-to-fit land on an integer zoom level // (see fittedTileSizeCss). Like the two setters above this must run before any -// layer is built: the map's coordinate scale is derived from it. +// layer is built: the view's coordinate scale is derived from it. // // Safe because the tile grid is indexed by zoom alone — tile (z,x,y) covers // maxDXDY/2^z DBU whatever its pixel size — so this changes the resolution the @@ -163,16 +120,6 @@ export function useFittedTileSize(size) { tile_size_css = size; } -// Merge the device-exact tile size into a Leaflet options object without -// overriding an explicit choice (the static path passes its own). -export function withDeviceExactTileSize(options) { - const opts = { ...(options || {}) }; - if (opts.tileSize === undefined) { - opts.tileSize = tileSizeCss(); - } - return opts; -} - // Device pixels for one tile: what the server is asked to render, and what a // merged canvas sizes its backing store to. Sent explicitly rather than left to // the server to derive, so the image is exactly the box it will be drawn into. @@ -208,7 +155,7 @@ export function nativeDpr() { // browser, so all three have to be rendered at the same pixel count and land on // the same grid; an overlay half a pixel off, or an image the browser has to // rescale, shows up as a blurred or misregistered highlight. -export function tileSizeFields(dpr, tileSize = tileSizeCss()) { +export function tileSizeFields(dpr, tileSize) { return { // Rounded here and nowhere else: this field feeds the server's cache // key and its CSS-authored sizes (fonts, pen widths), both of which @@ -235,51 +182,56 @@ export function hasEntries(map) { // so the wire schema stays uniform with selectAt requests. // // `dpr` is passed in rather than read here so a caller can override it without -// this module knowing anything about why. +// this module knowing anything about why. Returns `(layerName, row) => +// request`, with the fields every layer shares built once. // // `row` is the Display Controls row asking: `chiplet` is the die it draws (two // dies can share a layer name), `rowId` keys its fill pattern and // `rendererHost` marks the row that carries the renderers' layer pass. -export function buildTileRequestFor(coords, layerName, ctx, dpr, - tileSize = tileSizeCss(), row = {}) { +export function tileRequestBuilder(coords, ctx, dpr, tileSize) { const { visibility, selectability, visibleLayers, selectableLayers, app } = ctx; - const vf = buildVisibilityFlags(visibility, selectability); - const req = { - type: 'tile', - layer: layerName, + const shared = { z: coords.z, x: coords.x, y: coords.y, ...tileSizeFields(dpr, tileSize), visible_layers: visibleLayers ? [...visibleLayers] : [], selectable_layers: selectableLayers ? [...selectableLayers] : [], - ...vf, + ...buildVisibilityFlags(visibility, selectability), }; if (app && app.visibleChiplets instanceof Set) { - req.visible_chiplets = [...app.visibleChiplets]; - } - // A row is only requested while it is checked, so a die's exceptions - // cannot change its pixels; leaving them out keeps its cache key stable. - if (row.chiplet) { - req.chiplet = row.chiplet; - } else if (app && hasEntries(app.chipletHiddenLayers)) { - req.chiplet_hidden_layers = app.chipletHiddenLayers; - } - // Debug tiles skip the cache, so this flag cannot fragment it. - if (row.rendererHost && vf.debug_renderers) { - req.renderer_host = true; + shared.visible_chiplets = [...app.visibleChiplets]; } - // Per-layer fill pattern (int matching the server's FillPattern enum; - // 1 = solid). Read lazily so a change via the layer context menu is picked - // up on the next refresh without rebuilding the layer. - if (app && app.layerPatterns) { - const p = app.layerPatterns[row.rowId ?? layerName]; - if (p !== undefined && p !== 1) { + const hiddenPerDie = app && hasEntries(app.chipletHiddenLayers) + ? app.chipletHiddenLayers : null; + return (layerName, row = {}) => { + const req = { type: 'tile', layer: layerName, ...shared }; + // A row is only requested while it is checked, so a die's exceptions + // cannot change its pixels; leaving them out keeps its cache key stable. + if (row.chiplet) { + req.chiplet = row.chiplet; + } else if (hiddenPerDie) { + req.chiplet_hidden_layers = hiddenPerDie; + } + // Debug tiles skip the cache, so this flag cannot fragment it. + if (row.rendererHost && shared.debug_renderers) { + req.renderer_host = true; + } + const p = layerPattern(app, row.rowId ?? layerName); + if (p !== 1) { req.pattern = p; } - } - return req; + return req; + }; +} + +// Fill pattern of a Display Controls row (int matching the server's +// FillPattern enum; 1 = solid), read on every request so a change via the +// layer context menu is picked up on the next refresh. +function layerPattern(app, rowId) { + const p = app && app.layerPatterns ? app.layerPatterns[rowId] : undefined; + return p === undefined ? 1 : p; } // Call `onChange` whenever devicePixelRatio changes — a window dragged to @@ -332,13 +284,3 @@ export function watchDevicePixelRatio(onChange) { handler = null; }; } - -// Floor the map's REAL (possibly fractional) zoom so the displayed tile pane is -// only ever UPSCALED (scale 2^(realZoom-floor) ∈ [1,2)), never downscaled. -// Upscaling a band-limited tile cannot reintroduce the moiré beat; downscaling -// can. Reading the live map zoom (not the passed arg) keeps this correct during -// zoom-animation frames and robust even if zoomSnap:0 is re-enabled. -export function floorClampZoom(layer, zoom) { - const real = (layer && layer._map) ? layer._map.getZoom() : zoom; - return Math.floor(real); -} diff --git a/openroad/web/src/tile-sources.js b/openroad/web/src/tile-sources.js new file mode 100644 index 00000000000..c8db5288244 --- /dev/null +++ b/openroad/web/src/tile-sources.js @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// Where the layout view's tiles come from. Each source turns a tile (z, x, y) +// in the server's grid into a drawable `{ image, width, height }`, or null for +// a tile with nothing in it, and implements the TileGrid source contract: +// `load(coords, {background, onPartial}) -> {promise, cancel, promote}` and +// `release(drawable)`. + +import { nativeDpr, tileDevicePx, tileRequestBuilder, tileSizeCss, tileSizeFields } + from './tile-request.js'; +import { closeAll, mergeOntoContext, renderMergedTile } from './tile-merge.js'; +import { tileMayHaveContent } from './layer-extents.js'; + +// Decode a tile payload: a Blob from the server, or a data URI from a saved +// report. Straight alpha and no color conversion, so the pixels reach the +// GPU as the server wrote them. +function decodeTilePayload(payload) { + if (payload == null) { + return Promise.resolve(null); + } + if (typeof payload === 'string') { + return new Promise((resolve) => { + const img = document.createElement('img'); + img.onload = () => resolve(img); + img.onerror = () => resolve(null); + img.src = payload; + }); + } + return createImageBitmap(payload, { premultiplyAlpha: 'none', + colorSpaceConversion: 'none' }) + .catch(() => null); +} + +export function releaseDrawable(drawable) { + closeAll([drawable && drawable.image]); +} + +function imageSize(image) { + return { + width: image.naturalWidth || image.width, + height: image.naturalHeight || image.height, + }; +} + +function asDrawable(image) { + return image ? { image, ...imageSize(image) } : null; +} + +function defaultCanvas(px) { + if (typeof OffscreenCanvas === 'function') { + return new OffscreenCanvas(px, px); + } + const canvas = document.createElement('canvas'); + canvas.width = px; + canvas.height = px; + return canvas; +} + +// A 2D canvas holding a copy of `src`. +export function copyToCanvas2d(src) { + const copy = document.createElement('canvas'); + copy.width = src.width; + copy.height = src.height; + copy.getContext('2d').drawImage(src, 0, 0); + return copy; +} + +// Snapshot of the composite. transferToImageBitmap empties the canvas, which +// is fine: every paint recomposites from scratch. +function defaultSnapshot(canvas) { + if (typeof canvas.transferToImageBitmap === 'function') { + return asDrawable(canvas.transferToImageBitmap()); + } + return asDrawable(copyToCanvas2d(canvas)); +} + +const NOTHING = Object.freeze({ + promise: Promise.resolve(null), cancel() {}, promote() {}, +}); + +// Whether an item's `gate` lets it draw: a visibility flag name, or a +// `shown_by` list of flag groups that shows when every flag of one group is +// on, as the server's anyGroupOn. An unknown name fails open, with a warning. +const warnedGates = new Set(); +export function gateOpen(gate, visibility) { + if (gate == null) { + return true; + } + if (Array.isArray(gate)) { + return gate.some((group) => group.every((key) => !!visibility[key])); + } + if (!(gate in visibility)) { + if (!warnedGates.has(gate)) { + warnedGates.add(gate); + console.warn(`tile item: unknown gate '${gate}', drawing ungated`); + } + return true; + } + return !!visibility[gate]; +} + +// Issue one request through `wm`, tracking its id for cancel and promote. +function tracked(wm, ids, msg, background) { + const promise = wm.request(msg, { background }); + if (promise.requestId != null) { + ids.push(promise.requestId); + } + return promise; +} + +// The load handle over the requests in `ids`; `onCancel` runs before they are +// cancelled. +function loadHandle(wm, ids, promise, onCancel) { + return { + promise, + cancel() { + onCancel(); + for (const id of ids) { + wm.cancel(id); + } + }, + promote() { + for (const id of ids) { + wm.promote(id); + } + }, + }; +} + +// The layout layers of a slot, composited into one image per tile in z-order +// (`getItems()` returns [{layer, opacity, visible, gate}], bottom-most +// first). With double buffering the tile is drawn once, complete; otherwise +// every layer that lands is published as a partial composite. +export function createCompositeSource({ + wm, ctx, getItems, dpr = nativeDpr, tileSize = tileSizeCss, + isDoubleBuffer = () => true, decode = decodeTilePayload, + makeCanvas = defaultCanvas, snapshot = defaultSnapshot, +}) { + return { + load({ z, x, y }, { background = false, onPartial } = {}) { + const all = getItems() || []; + const d = dpr(); + const t = tileSize(); + // One request per shown item, for its own die when it names one; + // layer-extents.js skips the empty ones. + const items = all.filter( + (item) => item && item.visible !== false + && gateOpen(item.gate, ctx.visibility || {}) + && tileMayHaveContent(ctx, item.layer, { z, x, y }, + item.chiplet)); + if (items.length === 0) { + return NOTHING; + } + const build = tileRequestBuilder({ z, x, y }, ctx, d, t); + const parts = items.map((item) => ({ opacity: item.opacity, + msg: build(item.layer, item) })); + const px = tileDevicePx(t, d); + // Made on the first draw with an image, so an empty or + // cancelled tile never allocates one. + let canvas = null; + let g = null; + const ids = []; + let cancelled = false; + const progressive = !isDoubleBuffer() + && typeof onPartial === 'function'; + const promise = renderMergedTile({ + items: parts, + request: (part) => tracked(wm, ids, part.msg, background), + decode, + draw: (sources) => { + if (!canvas) { + if (!sources.some((s) => s.image)) { + return 0; + } + canvas = makeCanvas(px); + g = canvas.getContext('2d'); + } + const drawn = mergeOntoContext(g, sources, px); + if (progressive && drawn > 0) { + onPartial(snapshot(canvas)); + } + return drawn; + }, + isStale: () => cancelled, + incremental: progressive, + }).then((stats) => { + if (cancelled) { + throw new Error('Tile cancelled'); + } + // Disconnected: keep what the tile showed, not a blank. + if (stats.failed === stats.requested) { + throw new Error('Tile requests failed'); + } + if (stats.drawn === 0) { + return null; + } + // Progressive: the last partial already holds every layer, + // and undefined tells the grid to keep it. + return progressive ? undefined : snapshot(canvas); + }); + return loadHandle(wm, ids, promise, () => { cancelled = true; }); + }, + release: releaseDrawable, + }; +} + +// One server image per tile: `buildRequest({z, x, y}, dpr, tileSize)` returns +// the request, or null for a tile that needs none. +export function createImageSource({ + wm, buildRequest, dpr = nativeDpr, tileSize = tileSizeCss, + decode = decodeTilePayload, +}) { + return { + load({ z, x, y }, { background = false } = {}) { + const msg = buildRequest({ z, x, y }, dpr(), tileSize()); + if (!msg) { + return NOTHING; + } + const ids = []; + let cancelled = false; + const promise = tracked(wm, ids, msg, background) + .then((payload) => decode(payload)) + .then((image) => { + if (cancelled) { + releaseDrawable(asDrawable(image)); + throw new Error('Tile cancelled'); + } + return asDrawable(image); + }); + return loadHandle(wm, ids, promise, () => { cancelled = true; }); + }, + release: releaseDrawable, + }; +} + +// The highlight overlay: selection, timing paths, DRC markers, route guides +// and label text, drawn by the server on a transparent tile. +export function buildOverlayRequest({ z, x, y }, dpr, tileSize, visibility, app) { + const req = { + type: 'overlay_tile', + z, x, y, + ...tileSizeFields(dpr, tileSize), + debug_renderers: !!visibility.debug_renderers, + debug_live: !!visibility.debug_live, + flywires_only: !!visibility.flywires_only, + poly_decomp: !!(app && app.polyDecomp), + focused_nets_guides: !!visibility.focused_nets_guides, + highlight_selected: visibility.highlight_selected !== false, + draw_labels: visibility.labels !== false, + }; + if (app && app.visibleLayerNames) { + req.visible_layers = [...app.visibleLayerNames]; + } + return req; +} + +// The active heat map, or no request at all when none is shown. +export function buildHeatmapRequest({ z, x, y }, dpr, tileSize, app) { + const name = app && app.activeHeatMap; + if (!name) { + return null; + } + return { type: 'heatmap_tile', name, z, x, y, + ...tileSizeFields(dpr, tileSize) }; +} diff --git a/openroad/web/src/tile_generator.cpp b/openroad/web/src/tile_generator.cpp index 3733cf8bbac..f0b4e228329 100644 --- a/openroad/web/src/tile_generator.cpp +++ b/openroad/web/src/tile_generator.cpp @@ -35,6 +35,8 @@ #include #include "boost/json/array.hpp" +#include "boost/json/object.hpp" +#include "boost/json/serialize.hpp" #include "color.h" #include "db_sta/dbSta.hh" #include "font_atlas.h" @@ -1064,88 +1066,138 @@ inline int hairlineCss(const TileFrame& frame) return std::max(1, static_cast(std::lround(frame.px_per_css))); } -} // namespace - -namespace { +// The tiles a flag can change: the tech layers and each pseudo layer. +enum TileBit : uint32_t +{ + kTechTiles = 1U << 0, + kInstancesTile = 1U << 1, + kPinsTile = 1U << 2, + kInstLabelsTile = 1U << 3, + kAccessPointsTile = 1U << 4, + kRegionsTile = 1U << 5, + kMfgGridTile = 1U << 6, + kGcellGridTile = 1U << 7, + kRudyTile = 1U << 8, + kCongestionTile = 1U << 9, + kModulesTile = 1U << 10, + kClustersTile = 1U << 11, +}; +constexpr uint32_t kAllTiles = ~0U; +// What isInstVisible and isNetVisible are read by. +constexpr uint32_t kInstTiles = kTechTiles | kInstancesTile | kInstLabelsTile + | kModulesTile | kClustersTile; +constexpr uint32_t kNetTiles = kTechTiles | kPinsTile | kAccessPointsTile; +constexpr uint32_t kBTermTiles = kTechTiles | kPinsTile; +constexpr uint32_t kITermTiles + = kTechTiles | kInstLabelsTile | kAccessPointsTile; + +// The bit of a tile's layer. A pseudo layer missing here gets every bit, so +// every flag counts for it. +uint32_t tileBitOf(const std::string_view layer) +{ + if (!layer.starts_with('_')) { + return kTechTiles; + } + static const std::map kPseudoLayers = { + {"_instances", kInstancesTile}, + {"_pins", kPinsTile}, + {kInstLabelsLayer, kInstLabelsTile}, + {"_access_points", kAccessPointsTile}, + {"_regions", kRegionsTile}, + {"_mfg_grid", kMfgGridTile}, + {"_gcell_grid", kGcellGridTile}, + {"_rudy", kRudyTile}, + {"_routing_congestion", kCongestionTile}, + {"_modules", kModulesTile}, + {"_clusters", kClustersTile}, + }; + if (const auto it = kPseudoLayers.find(layer); it != kPseudoLayers.end()) { + return it->second; + } + return kAllTiles; +} -// Every boolean TileVisibility field: its JSON key and the default an omitted -// key falls back to. struct BoolField { const char* key; bool TileVisibility::* field; bool default_val; + // The tiles whose pixels the flag can change. + uint32_t tiles = kAllTiles; }; +// Every visibility flag a tile render reads, with its default and the tiles it +// can change. +// Parsing and the tile-cache key walk the same list. // clang-format off // NOLINTBEGIN(modernize-use-designated-initializers) -const BoolField kBoolFields[] = { - {"stdcells", &TileVisibility::stdcells, true}, - {"macros", &TileVisibility::macros, true}, - {"pad_input", &TileVisibility::pad_input, true}, - {"pad_output", &TileVisibility::pad_output, true}, - {"pad_inout", &TileVisibility::pad_inout, true}, - {"pad_power", &TileVisibility::pad_power, true}, - {"pad_spacer", &TileVisibility::pad_spacer, true}, - {"pad_areaio", &TileVisibility::pad_areaio, true}, - {"pad_other", &TileVisibility::pad_other, true}, - {"phys_fill", &TileVisibility::phys_fill, true}, - {"phys_endcap", &TileVisibility::phys_endcap, true}, - {"phys_welltap", &TileVisibility::phys_welltap, true}, - {"phys_tie", &TileVisibility::phys_tie, true}, - {"phys_antenna", &TileVisibility::phys_antenna, true}, - {"phys_cover", &TileVisibility::phys_cover, true}, - {"phys_bump", &TileVisibility::phys_bump, true}, - {"phys_other", &TileVisibility::phys_other, true}, - {"std_bufinv", &TileVisibility::std_bufinv, true}, - {"std_bufinv_timing", &TileVisibility::std_bufinv_timing, true}, - {"std_clock_bufinv", &TileVisibility::std_clock_bufinv, true}, - {"std_clock_gate", &TileVisibility::std_clock_gate, true}, - {"std_level_shift", &TileVisibility::std_level_shift, true}, - {"std_sequential", &TileVisibility::std_sequential, true}, - {"std_combinational", &TileVisibility::std_combinational, true}, - {"std_physical", &TileVisibility::std_physical, true}, - {"std_other", &TileVisibility::std_other, true}, - {"net_signal", &TileVisibility::net_signal, true}, - {"net_power", &TileVisibility::net_power, true}, - {"net_ground", &TileVisibility::net_ground, true}, - {"net_clock", &TileVisibility::net_clock, true}, - {"net_reset", &TileVisibility::net_reset, true}, - {"net_tieoff", &TileVisibility::net_tieoff, true}, - {"net_scan", &TileVisibility::net_scan, true}, - {"net_analog", &TileVisibility::net_analog, true}, - {"routing", &TileVisibility::routing, true}, - {"routing_segments", &TileVisibility::routing_segments, true}, - {"routing_vias", &TileVisibility::routing_vias, true}, - {"special_nets", &TileVisibility::special_nets, true}, - {"srouting_segments", &TileVisibility::srouting_segments, true}, - {"srouting_vias", &TileVisibility::srouting_vias, true}, - {"labels", &TileVisibility::labels, true}, - {"pins", &TileVisibility::pins, true}, - {"pin_markers", &TileVisibility::pin_markers, true}, - {"pin_names", &TileVisibility::pin_names, true}, - {"access_points", &TileVisibility::access_points, false}, - {"regions", &TileVisibility::regions, true}, - {"mfg_grid", &TileVisibility::mfg_grid, false}, - {"gcell_grid", &TileVisibility::gcell_grid, false}, - {"rudy", &TileVisibility::rudy, false}, - {"routing_congestion", &TileVisibility::routing_congestion, false}, - {"inst_names", &TileVisibility::inst_names, true}, - {"inst_pins", &TileVisibility::inst_pins, true}, - {"inst_pin_names", &TileVisibility::inst_pin_names, false}, - {"blockages", &TileVisibility::blockages, true}, - {"placement_blockages", &TileVisibility::placement_blockages, true}, - {"routing_obstructions", &TileVisibility::routing_obstructions, true}, - {"fills", &TileVisibility::fills, false}, - {"rows", &TileVisibility::rows, false}, - {"tracks_pref", &TileVisibility::tracks_pref, false}, - {"tracks_non_pref", &TileVisibility::tracks_non_pref, false}, - {"detailed", &TileVisibility::detailed, false}, - {"module_view", &TileVisibility::module_view, false}, - {"cluster_view", &TileVisibility::cluster_view, false}, - {"debug", &TileVisibility::debug, false}, - {"debug_renderers", &TileVisibility::debug_renderers, false}, - {"debug_live", &TileVisibility::debug_live, false}, +const BoolField kVisibilityFields[] = { + {"stdcells", &TileVisibility::stdcells, true, kInstTiles}, + {"macros", &TileVisibility::macros, true, kInstTiles}, + {"pad_input", &TileVisibility::pad_input, true, kInstTiles}, + {"pad_output", &TileVisibility::pad_output, true, kInstTiles}, + {"pad_inout", &TileVisibility::pad_inout, true, kInstTiles}, + {"pad_power", &TileVisibility::pad_power, true, kInstTiles}, + {"pad_spacer", &TileVisibility::pad_spacer, true, kInstTiles}, + {"pad_areaio", &TileVisibility::pad_areaio, true, kInstTiles}, + {"pad_other", &TileVisibility::pad_other, true, kInstTiles}, + {"phys_fill", &TileVisibility::phys_fill, true, kInstTiles}, + {"phys_endcap", &TileVisibility::phys_endcap, true, kInstTiles}, + {"phys_welltap", &TileVisibility::phys_welltap, true, kInstTiles}, + {"phys_tie", &TileVisibility::phys_tie, true, kInstTiles}, + {"phys_antenna", &TileVisibility::phys_antenna, true, kInstTiles}, + {"phys_cover", &TileVisibility::phys_cover, true, kInstTiles}, + {"phys_bump", &TileVisibility::phys_bump, true, kInstTiles}, + {"phys_other", &TileVisibility::phys_other, true, kInstTiles}, + {"std_bufinv", &TileVisibility::std_bufinv, true, kInstTiles}, + {"std_bufinv_timing", &TileVisibility::std_bufinv_timing, true, kInstTiles}, + {"std_clock_bufinv", &TileVisibility::std_clock_bufinv, true, kInstTiles}, + {"std_clock_gate", &TileVisibility::std_clock_gate, true, kInstTiles}, + {"std_level_shift", &TileVisibility::std_level_shift, true, kInstTiles}, + {"std_sequential", &TileVisibility::std_sequential, true, kInstTiles}, + {"std_combinational", &TileVisibility::std_combinational, true, kInstTiles}, + {"std_physical", &TileVisibility::std_physical, true, kInstTiles}, + {"std_other", &TileVisibility::std_other, true, kInstTiles}, + {"net_signal", &TileVisibility::net_signal, true, kNetTiles}, + {"net_power", &TileVisibility::net_power, true, kNetTiles}, + {"net_ground", &TileVisibility::net_ground, true, kNetTiles}, + {"net_clock", &TileVisibility::net_clock, true, kNetTiles}, + {"net_reset", &TileVisibility::net_reset, true, kNetTiles}, + {"net_tieoff", &TileVisibility::net_tieoff, true, kNetTiles}, + {"net_scan", &TileVisibility::net_scan, true, kNetTiles}, + {"net_analog", &TileVisibility::net_analog, true, kNetTiles}, + {"routing", &TileVisibility::routing, true, kTechTiles}, + {"routing_segments", &TileVisibility::routing_segments, true, kTechTiles}, + {"routing_vias", &TileVisibility::routing_vias, true, kTechTiles}, + {"special_nets", &TileVisibility::special_nets, true, kTechTiles}, + {"srouting_segments", &TileVisibility::srouting_segments, true, kTechTiles}, + {"srouting_vias", &TileVisibility::srouting_vias, true, kTechTiles}, + {"labels", &TileVisibility::labels, true, 0}, // overlay tile + {"pins", &TileVisibility::pins, true, kBTermTiles}, + {"pin_markers", &TileVisibility::pin_markers, true, kPinsTile}, + {"pin_names", &TileVisibility::pin_names, true, kPinsTile}, + {"access_points", &TileVisibility::access_points, false, kAccessPointsTile}, + {"regions", &TileVisibility::regions, true, kRegionsTile}, + {"mfg_grid", &TileVisibility::mfg_grid, false, kMfgGridTile}, + {"gcell_grid", &TileVisibility::gcell_grid, false, kGcellGridTile}, + {"rudy", &TileVisibility::rudy, false, kRudyTile}, + {"routing_congestion", &TileVisibility::routing_congestion, false, kCongestionTile}, + {"inst_names", &TileVisibility::inst_names, true, kInstLabelsTile}, + {"inst_pins", &TileVisibility::inst_pins, true, kITermTiles}, + {"inst_pin_names", &TileVisibility::inst_pin_names, false, kInstLabelsTile}, + {"blockages", &TileVisibility::blockages, true, kTechTiles}, + {"placement_blockages", &TileVisibility::placement_blockages, true, kInstancesTile}, + {"routing_obstructions",&TileVisibility::routing_obstructions, true, kTechTiles}, + {"fills", &TileVisibility::fills, false, kTechTiles}, + {"rows", &TileVisibility::rows, false, kInstancesTile}, + {"tracks_pref", &TileVisibility::tracks_pref, false, kTechTiles}, + {"tracks_non_pref", &TileVisibility::tracks_non_pref, false, kTechTiles}, + {"detailed", &TileVisibility::detailed, false}, + {"module_view", &TileVisibility::module_view, false, kModulesTile}, + {"cluster_view", &TileVisibility::cluster_view, false, kClustersTile}, + {"debug", &TileVisibility::debug, false}, + {"debug_renderers", &TileVisibility::debug_renderers, false}, + {"debug_live", &TileVisibility::debug_live, false}, }; // NOLINTEND(modernize-use-designated-initializers) // clang-format on @@ -1154,7 +1206,7 @@ const BoolField kBoolFields[] = { std::optional TileVisibility::flag(const std::string_view key) const { - for (const BoolField& f : kBoolFields) { + for (const BoolField& f : kVisibilityFields) { if (key == f.key) { return this->*(f.field); } @@ -1162,10 +1214,21 @@ std::optional TileVisibility::flag(const std::string_view key) const return std::nullopt; } +/* static */ +std::vector TileVisibility::flagKeys() +{ + std::vector keys; + keys.reserve(std::size(kVisibilityFields)); + for (const BoolField& f : kVisibilityFields) { + keys.emplace_back(f.key); + } + return keys; +} + bool TileVisibility::isFlag(const std::string_view key) { return std::ranges::any_of( - kBoolFields, [key](const BoolField& f) { return key == f.key; }); + kVisibilityFields, [key](const BoolField& f) { return key == f.key; }); } bool TileVisibility::setFlag(const std::string_view key, const bool value) @@ -1175,7 +1238,7 @@ bool TileVisibility::setFlag(const std::string_view key, const bool value) std_physical = value; std_other = value; } - for (const BoolField& f : kBoolFields) { + for (const BoolField& f : kVisibilityFields) { if (key == f.key) { this->*f.field = value; return true; @@ -1211,7 +1274,7 @@ void TileVisibility::assignFromJson(const boost::json::object& json) // Visibility flags are nominally always sent by the web frontend, but // tests and the saveImage Tcl entry point can pass partial payloads; // fall back to the per-field default when a flag is omitted. - for (const auto& f : kBoolFields) { + for (const auto& f : kVisibilityFields) { this->*(f.field) = jsonOr(json, f.key, f.default_val); } std_physical = jsonOr(json, "std_physical", stdcells); @@ -1265,13 +1328,18 @@ void TileVisibility::assignFromJson(const boost::json::object& json) return; } --budget; - std::set& layers = out[std::string(path)]; + // Made on the first name: an empty list hides nothing, as no + // entry does. + std::set* layers = nullptr; for (const auto& name : names.as_array()) { if (budget == 0) { return; } --budget; - layers.emplace(name.as_string()); + if (!layers) { + layers = &out[std::string(path)]; + } + layers->emplace(name.as_string()); } } }; @@ -1741,10 +1809,34 @@ TileGenerator::TileGenerator(odb::dbDatabase* db, // invalidates a spatial index. eagerInit() suppresses this while it // rebuilds. search_->setOnModified([this] { onDesignChanged(); }); + db_->addObserver(&load_counter_); } TileGenerator::~TileGenerator() = default; +void TileGenerator::ensureInit(const bool fresh_cache) +{ + std::scoped_lock lock(init_mutex_); + // Read first: a load landing during the init brings on the next one. + const uint64_t loads = load_counter_.loads.load(); + // A chip made without a load hook (dbChip::create) counts as a load too. + if (init_loads_ != loads || init_chip_ != db_->getChip()) { + eagerInit(); + init_loads_ = loads; + init_chip_ = db_->getChip(); + return; + } + const int margin = pin_label_margin_dbu_; + computePinLabelMargin(); + if (pin_label_margin_dbu_ != margin) { + onDesignChanged(); // a new margin moves every tile + } else if (fresh_cache) { + // A new session starts clean: an edit ODB does not report leaves no + // stale tile behind. + clearTileCache(); + } +} + void TileGenerator::eagerInit() { // Reindexing clears every spatial index, which would otherwise fire @@ -1765,8 +1857,7 @@ void TileGenerator::eagerInit() // from the previous design's. { std::lock_guard lock(chiplets_mutex_); - chiplets_cache_.clear(); - chiplets_cache_valid_ = false; + chiplets_cache_.reset(); } // Overlay caches are keyed by dbBlock*, which may be stale after a // design swap. @@ -1780,7 +1871,8 @@ void TileGenerator::eagerInit() // so the recursive tile renderer can query searchInsts/searchBoxShapes // for any chiplet's master block. if (chip) { - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (node.block) { search_->eagerInit(node.block); } @@ -1807,11 +1899,7 @@ void TileGenerator::eagerInit() } // Tiles depend on the design geometry, so a reload invalidates every cached // PNG. Clearing here ties cache lifetime to design loading. - { - std::lock_guard lock(tile_cache_mutex_); - tile_cache_lru_.clear(); - tile_cache_index_.clear(); - } + clearTileCache(); // suppress_guard restores suppress_design_changed_ to false on return. } @@ -1830,11 +1918,7 @@ void TileGenerator::onDesignChanged() // A design edit invalidated a spatial index, so every cached PNG may now be // stale. Drop the whole cache; tiles re-render lazily on the next request. - { - std::lock_guard lock(tile_cache_mutex_); - tile_cache_lru_.clear(); - tile_cache_index_.clear(); - } + clearTileCache(); // The geometry cache is NOT dropped here. This hook is debounced (see // below), so an edit arriving while an index is already invalid never @@ -1860,7 +1944,7 @@ void TileGenerator::onDesignChanged() bool TileGenerator::tileCacheGet(const std::string& key, std::vector& out) const { - std::lock_guard lock(tile_cache_mutex_); + std::scoped_lock lock(tile_cache_mutex_); const auto it = tile_cache_index_.find(key); if (it == tile_cache_index_.end()) { return false; @@ -1871,32 +1955,122 @@ bool TileGenerator::tileCacheGet(const std::string& key, return true; } +uint64_t TileGenerator::tileCacheEpoch() const +{ + std::scoped_lock lock(tile_cache_mutex_); + return tile_cache_epoch_; +} + void TileGenerator::tileCachePut(std::string key, - std::vector png) const + std::vector png, + const uint64_t epoch) const { - std::lock_guard lock(tile_cache_mutex_); + // Keeping it would evict everything else. + if (png.size() > kTileCacheBytesCap) { + return; + } + std::scoped_lock lock(tile_cache_mutex_); + if (epoch != tile_cache_epoch_) { + return; + } const auto it = tile_cache_index_.find(key); if (it != tile_cache_index_.end()) { // Already present: refresh contents and promote to most-recent. + tile_cache_bytes_ -= it->second->second.size(); + tile_cache_bytes_ += png.size(); it->second->second = std::move(png); tile_cache_lru_.splice( tile_cache_lru_.begin(), tile_cache_lru_, it->second); - return; + } else { + tile_cache_bytes_ += png.size(); + tile_cache_lru_.emplace_front(key, std::move(png)); + tile_cache_index_[std::move(key)] = tile_cache_lru_.begin(); } - tile_cache_lru_.emplace_front(key, std::move(png)); - tile_cache_index_[std::move(key)] = tile_cache_lru_.begin(); - if (tile_cache_lru_.size() > kTileCacheCap) { + while (tile_cache_lru_.size() > kTileCacheCap + || tile_cache_bytes_ > kTileCacheBytesCap) { + tile_cache_bytes_ -= tile_cache_lru_.back().second.size(); tile_cache_index_.erase(tile_cache_lru_.back().first); tile_cache_lru_.pop_back(); } } +void TileGenerator::clearTileCache() +{ + std::scoped_lock lock(tile_cache_mutex_); + tile_cache_lru_.clear(); + tile_cache_index_.clear(); + tile_cache_bytes_ = 0; + ++tile_cache_epoch_; +} + size_t TileGenerator::tileCacheSize() const { - std::lock_guard lock(tile_cache_mutex_); + std::scoped_lock lock(tile_cache_mutex_); return tile_cache_lru_.size(); } +size_t TileGenerator::tileCacheBytes() const +{ + std::scoped_lock lock(tile_cache_mutex_); + return tile_cache_bytes_; +} + +/* static */ +std::string TileGenerator::tileCacheKey(const TileVisibility& vis, + const std::string_view layer) +{ + const uint32_t tile = tileBitOf(layer); + std::string flags; + flags.reserve(std::size(kVisibilityFields)); + for (const BoolField& f : kVisibilityFields) { + if ((f.tiles & tile) == 0) { + flags += '-'; + } else { + flags += vis.*f.field ? '1' : '0'; + } + } + + boost::json::object key; + key["v"] = flags; + // Only the tech layers fill shapes with the layer's pattern. + if ((tile & kTechTiles) != 0) { + key["p"] = static_cast(vis.fill_pattern); + } + // A tile scoped to a die depends on that die being shown, not the others. + if (!vis.chiplet.empty()) { + key["d"] = vis.chiplet; + key["dv"] = vis.isChipletVisible(vis.chiplet); + } else if (vis.has_visible_chiplets) { + key["c"] = boost::json::array(vis.visible_chiplets.begin(), + vis.visible_chiplets.end()); + } + if (readsLayerVisibility(layer, vis)) { + if (vis.has_visible_layers) { + key["l"] = boost::json::array(vis.visible_layers.begin(), + vis.visible_layers.end()); + } + boost::json::object hidden; + for (const auto& [path, names] : + std::map>( + vis.chiplet_hidden_layers.begin(), + vis.chiplet_hidden_layers.end())) { + hidden[path] = boost::json::array(names.begin(), names.end()); + } + if (!hidden.empty()) { + key["h"] = std::move(hidden); + } + } + if (vis.rows && layer == "_instances") { + boost::json::object site_flags; + for (const auto& [name, visible] : + std::map(vis.sites.begin(), vis.sites.end())) { + site_flags[name] = visible; + } + key["s"] = std::move(site_flags); + } + return boost::json::serialize(key); +} + namespace { // Cheap-to-compute fingerprint of the current chiplet hierarchy: every @@ -1935,48 +2109,37 @@ size_t hashChipInsts(odb::dbChip* root) } // namespace -const std::vector& TileGenerator::chiplets() const +std::shared_ptr> TileGenerator::chiplets() const { - // ODB itself is not thread-safe, so callers serialize web requests - // against design mutations. The fingerprint check (root pointer + - // chiplet placement hash) only needs to detect *sequential* Tcl mutations - // — taking the lock before reading root/hash keeps the fingerprint - // and the cached values consistent with each other. - // - // Lifetime contract: the returned reference is valid only as long as - // eagerInit() does not run. eagerInit() executes on design load / - // reload, which is gated upstream against tile/select requests. Hot- - // path callers (renderTileBuffer, selectAt) MUST NOT trigger - // eagerInit while iterating the returned vector. std::lock_guard lock(chiplets_mutex_); + refreshChipletsLocked(); + return chiplets_cache_; +} + +void TileGenerator::refreshChipletsLocked() const +{ + // ODB itself is not thread-safe, so callers serialize web requests against + // design mutations. odb::dbChip* root = db_->getChip(); const size_t inst_hash = hashChipInsts(root); - const bool fingerprint_changed - = chiplets_cache_root_ != root || chiplets_cache_inst_hash_ != inst_hash; - if (!chiplets_cache_valid_ || fingerprint_changed) { - // ODB builds the unfolded model at load and never refreshes it on edits - // (#10228, closed as not planned). Rebuilding it here is not an option: - // this is a read path — reached from the save_image thread pool and from - // handlers that do not hold tcl_eval_->mutex — and constructUnfoldedModel() - // would free objects a concurrent check_3dblox is iterating. An edited - // hierarchy is walked instead, which mutates nothing and yields the same - // nodes. Only a design load (eagerInit, which clears the cache) brings a - // fresh model, so "valid cache + changed fingerprint" is exactly "edited". - const bool model_stale = chiplets_cache_valid_ && fingerprint_changed; - chiplets_cache_ = collectChiplets(root, !model_stale); + if (!chiplets_cache_ || chiplets_cache_root_ != root + || chiplets_cache_inst_hash_ != inst_hash) { + // The unfolded model is a load-time snapshot that edits never update, so + // the hierarchy is walked; both give the same nodes. + chiplets_cache_ = std::make_shared>( + collectChiplets(root, /*use_unfolded_model=*/false)); chiplets_cache_root_ = root; chiplets_cache_inst_hash_ = inst_hash; - chiplets_cache_valid_ = true; ++chiplets_cache_generation_; } - return chiplets_cache_; } std::vector TileGenerator::blocks() const { std::vector out; std::unordered_set seen; - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (node.block && seen.insert(node.block).second) { out.push_back(node.block); } @@ -1988,8 +2151,8 @@ uint64_t TileGenerator::chipletsGeneration() const { // Refresh first so the counter reflects the live hierarchy rather than // whatever the last chiplets() caller saw. - chiplets(); std::lock_guard lock(chiplets_mutex_); + refreshChipletsLocked(); return chiplets_cache_generation_; } @@ -2348,7 +2511,8 @@ odb::Rect TileGenerator::getFitBounds() const odb::Rect bounds; bounds.mergeInit(); bool any = false; - const std::vector& nodes = chiplets(); + const auto chiplet_list = chiplets(); + const std::vector& nodes = *chiplet_list; for (const ChipletNode& node : nodes) { if (!node.block) { continue; @@ -2381,10 +2545,11 @@ odb::Rect TileGenerator::getBounds() const // the design in the viewport, and with the map resting on integer zoom levels // it can cost a whole level (issue #11338). The client fits getFitBounds(). odb::Rect bounds = getFitBounds(); - if (bounds == odb::Rect{} || pin_label_margin_dbu_ <= 0) { + const int margin = pin_label_margin_dbu_; + if (bounds == odb::Rect{} || margin <= 0) { return bounds; } - bounds.bloat(pin_label_margin_dbu_, bounds); + bounds.bloat(margin, bounds); return bounds; } @@ -2434,7 +2599,8 @@ std::vector TileGenerator::getLayers() const // In multi-tech (3DBlox) designs getTech() returns nullptr; the chiplets() // loop below contributes every layer through its own dbTech. collectFromTech(getTech()); - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (node.chip) { collectFromTech(node.chip->getTech()); } @@ -2489,7 +2655,8 @@ std::vector TileGenerator::paintOrderLayers() const std::unordered_map> children; const ChipletNode* root = nullptr; - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (node.parent_path.empty()) { root = &node; } else { @@ -2749,8 +2916,8 @@ TileGenerator::GridList TileGenerator::gcellGridY(odb::dbBlock* block) const }); } -const odb::PtrMap& TileGenerator::getLayerColorMap( - odb::dbTech* req_tech) const +std::shared_ptr> +TileGenerator::getLayerColorMap(odb::dbTech* req_tech) const { std::lock_guard lock(layer_colors_mutex_); // In multi-tech databases db_->getTech() throws ODB-0432, so resolve the @@ -2766,7 +2933,8 @@ const odb::PtrMap& TileGenerator::getLayerColorMap( } auto [it, inserted] = layer_colors_by_tech_.try_emplace(tech); if (inserted) { - it->second = buildLayerColorMap(tech); + it->second = std::make_shared>( + buildLayerColorMap(tech)); } return it->second; } @@ -2844,7 +3012,8 @@ std::shared_ptr TileGenerator::buildGeomCache() // instance would leave duplicates for the render pass to redraw, once per // instance of the chiplet. std::unordered_set seen_blocks; - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (!node.block || !seen_blocks.insert(node.block).second) { continue; } @@ -2883,7 +3052,8 @@ TileGenerator::buildLayerExtents() const { auto extents = std::make_shared(); extents->bounds = getBounds(); - const std::vector& nodes = chiplets(); + const auto chiplet_list = chiplets(); + const std::vector& nodes = *chiplet_list; // Several dies go in `chiplets`, outline included: the render pass draws // each die's outline on every layer only then. const bool multi_die = nodes.size() > 1; @@ -3244,7 +3414,7 @@ std::vector TileGenerator::selectAt( } // Compute a search margin of 2 pixels at the current zoom level. // This accounts for coordinate conversion rounding between the client's - // Leaflet CRS.Simple coordinates and the server's DBU space. + // view coordinates and the server's DBU space. const int num_tiles = 1 << std::max(0, zoom); const int margin = std::max(1, getBounds().maxDXDY() / (kTileSizeInPixel * num_tiles) * 2); @@ -3274,7 +3444,8 @@ std::vector TileGenerator::selectAt( // dbChipInst land on the right object. We map the world click into // the chiplet's local frame using the inverse of world_xfm so that // R90/R180/R270/mirrored chiplets work the same as R0 ones. - for (const ChipletNode& node : chiplets()) { + const auto nodes = chiplets(); + for (const ChipletNode& node : *nodes) { if (!vis.isChipletVisible(node.path)) { continue; } @@ -3818,15 +3989,15 @@ std::vector TileGenerator::generateOverlayTile( if (route_guide_net_ids && !route_guide_net_ids->empty()) { // Draw route guides only for visible tech layers. for (odb::dbTech* tech : db_->getTechs()) { - const auto& colors = getLayerColorMap(tech); + const auto colors = getLayerColorMap(tech); for (odb::dbTechLayer* layer : tech->getLayers()) { // Skip layers the user has hidden in Display Controls. // has_visible_layers=true with an empty set means all hidden. if (has_visible_layers && !visible_layers.contains(layer->getName())) { continue; } - const auto it = colors.find(layer); - if (it == colors.end()) { + const auto it = colors->find(layer); + if (it == colors->end()) { continue; } drawRouteGuides( @@ -4560,17 +4731,9 @@ std::vector TileGenerator::saveImageLayerOrder( const TileVisibility& vis, const std::vector& tech_layers) { - // Bottom to top, by the z order the client stacks the layers in on screen - // (addPseudoLayer / the layer loop in display-controls.js): Leaflet paints - // by zIndex, so a PNG composited in any other order is not the view the - // user saw. Compositing in registry order — every pseudo layer last — put - // the manufacturing grid over the routing and the pin markers over the tech - // layers. These three mirror the client's non-pseudo values; - // PseudoLayerDef::z_index carries the overlays'. - // - // `tech_layers` arrives already in the client's paint order — see - // paintOrderLayers(), which is where a face-down die's reversal happens. - // This function only interleaves the pseudo layers with it. + // Bottom to top in the client's draw order (display-controls.js), so the + // PNG is the view. `tech_layers` is already in it (paintOrderLayers()). + // The client's z values; PseudoLayerDef::z_index has the overlays'. constexpr int kInstancesZ = 0; constexpr int kPinsZ = 1; constexpr int kTechLayerZBase = 3; @@ -4583,7 +4746,7 @@ std::vector TileGenerator::saveImageLayerOrder( ordered.emplace_back(kPinsZ, PaintLayer{.layer = "_pins", .chiplet = ""}); } // One z for every row, which the stable sort keeps in order: however many - // rows there are, they stay under the overlays, as the merged panes do. + // rows there are, they stay under the overlays, as in the client's draw list. for (const PaintLayer& entry : tech_layers) { if (!vis.isLayerShown(entry.layer) || vis.isLayerHiddenOn(entry.chiplet, entry.layer)) { @@ -4598,8 +4761,8 @@ std::vector TileGenerator::saveImageLayerOrder( } } // The "color by owner" overlays stack by the same rule; saveImage() drops the - // ones whose color map comes out empty. _modules goes under the routing, - // like the client's zIndex 2; _clusters over it, so metal does not cover the + // ones whose color map comes out empty. _modules goes under the routing, as + // in the client's base slot; _clusters over it, so metal does not cover the // partition, but below the Misc overlays, which start at 1000. if (vis.module_view) { ordered.emplace_back(2, PaintLayer{.layer = "_modules", .chiplet = ""}); @@ -4620,10 +4783,10 @@ std::vector TileGenerator::saveImageLayerOrder( const std::array& TileGenerator::pseudoLayerDefs() { - // z_index follows the GUI's paint order (renderThread.cpp:1201-1298), where - // the manufacturing grid goes down before the routing layers, the instance - // names right after them, and access points, regions and the gcell grid on - // top. + // z_index mirrors the client's draw lists in display-controls.js (see + // saveImageLayerOrder), which follow the GUI's paint order: the + // manufacturing grid before the routing layers, the instance names right + // after them, and access points, regions and the gcell grid on top. static const std::array defs = {{ {.name = "_access_points", .shown_by = {{"access_points"}}, @@ -4676,7 +4839,7 @@ bool TileGenerator::anyGroupOn( }); } -bool TileGenerator::readsLayerVisibility(const std::string& layer, +bool TileGenerator::readsLayerVisibility(const std::string_view layer, const TileVisibility& vis) { if (layer == "_pins") { @@ -4863,7 +5026,7 @@ std::vector TileGenerator::renderTileBuffer( : size_limit_dbu; // The geometry the tile request resolves to: which slice of the design it // covers and at what resolution. `y` here is already flipped out of the - // client's Leaflet convention, so it will not match the requested y. The + // client's top-down convention, so it will not match the requested y. The // micron window depends only on the design bounds and z; tile_px/draw_px // and the cull limits are the dpr-derived part. const double dbu_per_micron = db_->getDbuPerMicron(); @@ -4908,7 +5071,8 @@ std::vector TileGenerator::renderTileBuffer( // image. The world tile rect is shifted into each chiplet's local // frame for translation-only transforms; non-R0 orientations log // and skip for v1 (followup work to support full transforms). - const std::vector& chiplet_nodes = chiplets(); + const auto chiplet_list = chiplets(); + const std::vector& chiplet_nodes = *chiplet_list; // Multi-die designs draw the die outline on EVERY layer pass (chiplet // demarcation). Single-die designs draw die+core outlines too (Qt // drawChip does it unconditionally), but only on the always-rendered @@ -4984,7 +5148,7 @@ std::vector TileGenerator::renderTileBuffer( // Per-layer colors mirror web::DisplayControls so the GUI and web // frontend agree on which color belongs to which layer. Resolved per // chiplet because each chiplet has its own dbTech in 3DBlox designs. - const auto& layer_colors = getLayerColorMap(tech); + const auto layer_colors = getLayerColorMap(tech); // Translation-only fast path: the local tile is the world tile // shifted by -offset, and pixel coordinates land in the same place @@ -5154,8 +5318,8 @@ std::vector TileGenerator::renderTileBuffer( Color color{.r = 200, .g = 200, .b = 200, .a = 180}; if (tech_layer) { - const auto it = layer_colors.find(tech_layer); - if (it != layer_colors.end()) { + const auto it = layer_colors->find(tech_layer); + if (it != layer_colors->end()) { color = it->second; } } @@ -5479,8 +5643,8 @@ std::vector TileGenerator::renderTileBuffer( Color marker_color{.r = 200, .g = 200, .b = 200, .a = 220}; odb::dbTechLayer* pin_layer = box->getTechLayer(); if (pin_layer) { - const auto it = layer_colors.find(pin_layer); - if (it != layer_colors.end()) { + const auto it = layer_colors->find(pin_layer); + if (it != layer_colors->end()) { marker_color = it->second; marker_color.a = 220; } @@ -6370,9 +6534,9 @@ std::vector TileGenerator::renderTileBuffer( continue; } world_layer = world_tech_layer; - const auto& world_layer_colors = getLayerColorMap(world_tech); - const auto it = world_layer_colors.find(world_tech_layer); - if (it != world_layer_colors.end()) { + const auto world_layer_colors = getLayerColorMap(world_tech); + const auto it = world_layer_colors->find(world_tech_layer); + if (it != world_layer_colors->end()) { world_color = it->second; } break; @@ -6813,8 +6977,8 @@ std::vector TileGenerator::renderImageBuffer( const int out_ox = (tx - tx_min) * kTileSizeInPixel; // Y is flipped: ty is bottom-up, output is top-down. const int out_oy = (ty_max - ty) * kTileSizeInPixel; - // Leaflet-style y coordinate (before the flip in renderTileBuffer). - const int leaflet_y = num_tiles - 1 - ty; + // Client (top-down) y coordinate, before the flip in renderTileBuffer. + const int top_down_y = num_tiles - 1 - ty; const odb::Rect tile_rect = tileWorldRect(bounds, z, tx, ty); hosted.clear(); @@ -6828,7 +6992,7 @@ std::vector TileGenerator::renderImageBuffer( const auto tile_buf = renderTileBuffer(entry.layer, z, tx, - leaflet_y, + top_down_y, scoped_vis, /*highlight_rects=*/{}, /*highlight_polys=*/{}, @@ -6847,7 +7011,7 @@ std::vector TileGenerator::renderImageBuffer( // User text labels go on top of all layers (Qt parity: labels appear // in save_image). if (!labels.empty()) { - const auto label_buf = renderLabelTile(z, tx, leaflet_y, labels); + const auto label_buf = renderLabelTile(z, tx, top_down_y, labels); if (!label_buf.empty()) { compositeTile(label_buf, kTileSizeInPixel, @@ -7157,10 +7321,10 @@ std::vector TileGenerator::renderOverlayPng( for (int tx = 0; tx <= tx_max; ++tx) { const int out_ox = tx * kTileSizeInPixel; const int out_oy = (ty_max - ty) * kTileSizeInPixel; - const int leaflet_y = num_tiles - 1 - ty; + const int top_down_y = num_tiles - 1 - ty; auto tile_buf = renderTileBuffer( - "_instances", z, tx, leaflet_y, vis, {}, {}, rects, lines); + "_instances", z, tx, top_down_y, vis, {}, {}, rects, lines); for (int py = 0; py < kTileSizeInPixel; ++py) { for (int px = 0; px < kTileSizeInPixel; ++px) { @@ -8774,7 +8938,7 @@ boost::json::object buildLayerHierarchy( boost::json::array other_layers_arr; if (node.chip) { if (odb::dbTech* tech = node.chip->getTech()) { - const auto& layer_colors = gen.getLayerColorMap(tech); + const auto layer_colors = gen.getLayerColorMap(tech); for (odb::dbTechLayer* layer : tech->getLayers()) { const LayerGroup group = classifyLayer(layer); if (group == LayerGroup::kSkip) { @@ -8783,8 +8947,8 @@ boost::json::object buildLayerHierarchy( boost::json::object layer_obj; layer_obj["name"] = layer->getName(); Color c{.r = 200, .g = 200, .b = 200, .a = 180}; - auto it = layer_colors.find(layer); - if (it != layer_colors.end()) { + auto it = layer_colors->find(layer); + if (it != layer_colors->end()) { c = it->second; } layer_obj["color"] = boost::json::array{static_cast(c.r), @@ -8871,9 +9035,9 @@ boost::json::object serializeTechResponse(const TileGenerator& gen) if (!layer) { continue; } - const auto& cmap = gen.getLayerColorMap(t); - auto it = cmap.find(layer); - if (it != cmap.end()) { + const auto cmap = gen.getLayerColorMap(t); + auto it = cmap->find(layer); + if (it != cmap->end()) { c = it->second; } break; @@ -8899,7 +9063,7 @@ boost::json::object serializeTechResponse(const TileGenerator& gen) out["has_liberty"] = gen.hasSta(); // The self-painting overlays this design can draw, from which the client - // builds its panes: name, pane order and when each shows. + // builds its draw lists: name, draw order and when each shows. const auto groups_json = [](const auto& groups) { boost::json::array arr; for (const auto& group : groups) { @@ -8949,7 +9113,8 @@ boost::json::object serializeTechResponse(const TileGenerator& gen) children_by_parent; const ChipletNode* root_node = nullptr; boost::json::array chiplets; - for (const ChipletNode& n : gen.chiplets()) { + const auto nodes = gen.chiplets(); + for (const ChipletNode& n : *nodes) { if (n.parent_path.empty()) { root_node = &n; } else { diff --git a/openroad/web/src/tile_generator.h b/openroad/web/src/tile_generator.h index c5da2640595..3b0319e7ea2 100644 --- a/openroad/web/src/tile_generator.h +++ b/openroad/web/src/tile_generator.h @@ -131,7 +131,7 @@ std::string dbuToMicronString(int dbu, double dbu_per_micron); // // The tile grid step is maxDXDY / 2^z — a FRACTIONAL number of DBU — so a // tile's lower-left corner is fractional too, and `origin_x/origin_y` keep it -// that way. The client lays the tiles out on that exact grid (the DBU↔latLng +// that way. The client lays the tiles out on that exact grid (the DBU↔world // transform in coordinates.js), so rounding the corner here would shift a // tile's content by its own fractional part, a different amount in each tile. // Neighbours then disagree about where the shared edge is and a hairline seam @@ -222,19 +222,12 @@ struct PaintLayer // Walk the chiplet hierarchy and return a flat list with each chiplet's // accumulated world transform. // -// Leaves come from ODB's unfolded model (dbUnfoldedChipInst), which already -// composes the dbChipInst transforms top-down — the web does not redo that -// arithmetic. The unfolded model holds leaves only: dbUnfoldedBuilder skips -// ChipType::HIER chips, which own no dbBlock and so have no geometry. Those -// intermediate nodes still group the UI trees, so they are synthesized here -// from the prefixes of each leaf's getChipInstPath(), as is the root (the -// unfolded model has no entry for the top chip). -// -// With use_unfolded_model=false, or when the model is empty (single-chip -// designs, load paths that never build it), the hierarchy is walked instead -// and the transforms composed here. Both routes produce the same nodes; the -// walk is what a caller uses when the model may be out of date, since ODB -// does not refresh it on edits and refreshing it from a read path is not safe. +// With use_unfolded_model=false, or when the model is empty, the hierarchy is +// walked and the transforms composed here; TileGenerator::chiplets() always +// walks, since ODB builds the unfolded model at load and never refreshes it. +// Otherwise leaves come from the model (dbUnfoldedChipInst), which holds leaves +// only, and the HIER nodes and the root are synthesized from the prefixes of +// each leaf's getChipInstPath(). Both routes produce the same nodes. // // Related Qt code: `LayoutViewer::getChips()` returns a flat // (dbChipInst → dbChip) PtrMap with no transform composition — this @@ -515,8 +508,13 @@ struct TileVisibility chiplet_nonselectable_layers; // Leaves *this unchanged when a value in json has the wrong type. + // A field read here that can change a tile's pixels must also reach + // TileGenerator::tileCacheKey(). void parseFromJson(const boost::json::object& json); + // JSON keys of every visibility flag parseFromJson reads; for tests. + static std::vector flagKeys(); + bool isNetVisible(odb::dbNet* net) const; bool isInstVisible(odb::dbInst* inst, sta::dbSta* sta) const; // Pin names show only together with the pins they name. @@ -553,6 +551,9 @@ class TileGenerator ~TileGenerator(); void eagerInit(); + // eagerInit() after a design load; otherwise the pin-label margin check, and + // with `fresh_cache` an empty tile cache. + void ensureInit(bool fresh_cache = false); bool shapesReady() const; bool hasSta() const { return sta_ != nullptr; } @@ -567,7 +568,6 @@ class TileGenerator OwnerColorMap defaultModuleColors() const; OwnerColorMap defaultGroupColors() const; - int getThreadCount() const { return num_threads_; } void setThreadCount(const int num_threads) { num_threads_ = num_threads; } // The tile grid's georeference: getFitBounds() grown by the pin-label @@ -591,10 +591,11 @@ class TileGenerator std::vector getSites() const; - // Per-layer colors matching web::DisplayControls layer palette. Computed - // lazily and cached; the cache is rebuilt only if the tech changes. - const odb::PtrMap& getLayerColorMap(odb::dbTech* tech - = nullptr) const; + // Per-layer colors matching web::DisplayControls layer palette, built per + // tech on first use and dropped by eagerInit(). Shared, so that reset can't + // free a map a renderer is still reading. + std::shared_ptr> getLayerColorMap( + odb::dbTech* tech = nullptr) const; // Geometry one dbMaster contributes to one tech layer, in master-local // coordinates; the render pass applies each instance's transform. Bucketing @@ -783,7 +784,9 @@ class TileGenerator // next call. Hot-path call-sites (renderTileBuffer, getBounds, // selectAt) read it on every tile / click; the free function // `collectChiplets` is kept for tests and one-shot callers. - const std::vector& chiplets() const; + // Shared, so a rebuild can't free a list a renderer is still walking. Hold + // it in a local: `for (... : *chiplets())` drops it before the loop body. + std::shared_ptr> chiplets() const; // The distinct blocks holding the design's geometry: every chiplet's block, // deduplicated (one node per dbChipInst, so a master placed N times reports @@ -931,11 +934,11 @@ class TileGenerator // -> painter -> paint order. Single source of truth for the // renderTileBuffer dispatch, the pseudo-layer guard, saveImage's // layers_to_render and the overlays the tech response publishes, from which - // the client builds its panes. + // the client builds its draw lists. // // `shown_by` and `layers_by` are TileVisibility JSON keys in groups, read by // anyGroupOn(): on when every key of any one group is. `z_index` is the - // client's pane order, which saveImageLayerOrder() composites in. + // client's draw order, which saveImageLayerOrder() composites in. struct PseudoLayerDef { const char* name; @@ -957,12 +960,12 @@ class TileGenerator const TileVisibility& vis); // Whether `layer`'s tiles read visible_layers and chiplet_hidden_layers: // the _pins pass and the overlays whose layers_by group is on. - static bool readsLayerVisibility(const std::string& layer, + static bool readsLayerVisibility(std::string_view layer, const TileVisibility& vis); // The layers saveImage composites, bottom to top, from `tech_layers` in // paintOrderLayers() order. Public so a test can pin the order down: - // it has to match the zIndex the client gives each layer in + // it has to match the draw order the client gives each layer in // display-controls.js, or the saved PNG is not the view on screen. static std::vector saveImageLayerOrder( const TileVisibility& vis, @@ -1025,18 +1028,36 @@ class TileGenerator // PNG-encoded "clean" tiles (no per-session overlays) keyed by a string // fingerprint of the full render determinant. Re-rendering tiles at // 256*dpr*S is expensive, so pan/zoom-back and visibility toggles reuse - // the cached bytes. LRU eviction at kTileCacheCap; cleared on design - // reload via eagerInit(). Thread-safe (mirrors chiplets_mutex_). + // the cached bytes. LRU eviction at kTileCacheCap entries or + // kTileCacheBytesCap bytes, whichever comes first; cleared on design + // reload via eagerInit(), on edits via onDesignChanged() and for a new + // session by ensureInit(true). Thread-safe (mirrors chiplets_mutex_). bool tileCacheGet(const std::string& key, std::vector& out) const; - void tileCachePut(std::string key, std::vector png) const; + // `epoch` is tileCacheEpoch() from before the render: a tile rendered + // across a clear is from the old design and is not kept. + void tileCachePut(std::string key, + std::vector png, + uint64_t epoch) const; + // Bumped whenever the cache is cleared. + uint64_t tileCacheEpoch() const; + + // Entries vary widely in size, so the bytes are bounded as well. + static constexpr size_t kTileCacheCap = 2048; + static constexpr size_t kTileCacheBytesCap = size_t{64} << 20; + + // The visibility part of `layer`'s tile-cache key: the parsed fields that + // can change its pixels, and none of the others. + static std::string tileCacheKey(const TileVisibility& vis, + std::string_view layer); // Install (or clear with `{}`) a callback invoked after a design edit has // invalidated the tile cache — WebServer wires this to broadcast a // {"type":"refresh"} push so clients re-request tiles (mirrors the Qt GUI's // Search::modified → LayoutViewer::fullRepaint). Set at serve() startup. void setDesignChangedCallback(std::function cb); - size_t tileCacheSize() const; // for tests + size_t tileCacheSize() const; // for tests + size_t tileCacheBytes() const; // for tests private: // Render a single tile into a raw RGBA buffer (pre-PNG-encoding). @@ -1145,10 +1166,10 @@ class TileGenerator const TileFrame& frame) const; // Raw (un-encoded) RGBA tile with only the user labels drawn on a - // transparent background, for the given Leaflet z/x/y. Used to composite - // labels into save_image. `labels` is passed in (snapshot once per image) - // so the mutex isn't locked and copied per tile. Returns empty if `labels` - // is empty. + // transparent background, for the given client z/x/y (y top-down). Used to + // composite labels into save_image. `labels` is passed in (snapshot once + // per image) so the mutex isn't locked and copied per tile. Returns empty + // if `labels` is empty. std::vector renderLabelTile( int z, int x, @@ -1245,13 +1266,16 @@ class TileGenerator utl::Logger* logger_; int num_threads_ = 0; std::unique_ptr search_; - int pin_label_margin_dbu_ = 0; // cached by computePinLabelMargin() + // Cached by computePinLabelMargin(), which eagerInit() and ensureInit() run + // under readers. + std::atomic pin_label_margin_dbu_{0}; // Cached layer-color map keyed by tech (see getLayerColorMap). Each tech is - // computed once and kept; std::map reference stability means a returned ref - // stays valid even if another tech is added later. + // computed once and kept until eagerInit() drops them all. mutable std::mutex layer_colors_mutex_; - mutable odb::PtrMap> + mutable odb::PtrMap< + odb::dbTech, + std::shared_ptr>> layer_colors_by_tech_; // Layer-bucketed master and via-master geometry. See geomCache(); built on @@ -1278,12 +1302,13 @@ class TileGenerator // setLoc/setOrient between eagerInit calls, which dbBlockCallBackObj // does not surface. mutable std::mutex chiplets_mutex_; - mutable std::vector chiplets_cache_; - mutable bool chiplets_cache_valid_ = false; + mutable std::shared_ptr> chiplets_cache_; mutable odb::dbChip* chiplets_cache_root_ = nullptr; mutable size_t chiplets_cache_inst_hash_ = 0; // See chipletsGeneration(). mutable uint64_t chiplets_cache_generation_ = 0; + // Rebuilds chiplets_cache_ if the hierarchy changed; chiplets_mutex_ held. + void refreshChipletsLocked() const; // The generation clients last heard about; see noticeChipletEdits(). std::atomic announced_chiplets_generation_{0}; @@ -1294,7 +1319,9 @@ class TileGenerator mutable std::list tile_cache_lru_; mutable std::unordered_map::iterator> tile_cache_index_; - static constexpr size_t kTileCacheCap = 512; + mutable size_t tile_cache_bytes_ = 0; // sum of the cached PNG sizes + mutable uint64_t tile_cache_epoch_ = 0; // see tileCacheEpoch() + void clearTileCache(); // Design-change → invalidation wiring. search_ fires on_modified (see // Search::setOnModified) on any geometry edit; onDesignChanged() drops the @@ -1307,6 +1334,22 @@ class TileGenerator mutable std::mutex design_changed_cb_mutex_; std::atomic_bool suppress_design_changed_{false}; + // Counts design loads, through the hooks Qt's MainWindow listens to. + struct LoadCounter : public odb::dbDatabaseObserver + { + std::atomic loads{0}; + void postReadLef(odb::dbTech*, odb::dbLib*) override { ++loads; } + void postReadDef(odb::dbBlock*) override { ++loads; } + void postReadFloorplanDef(odb::dbBlock*) override { ++loads; } + void postReadDb(odb::dbDatabase*) override { ++loads; } + void postRead3Dbx(odb::dbChip*) override { ++loads; } + }; + // Registered with db_, so this generator must not outlive it. + LoadCounter load_counter_; + std::mutex init_mutex_; + std::optional init_loads_; // loads seen by the last ensureInit() + odb::dbChip* init_chip_ = nullptr; // top chip at the last ensureInit() + // Per-block caches for the grid/access-point overlay layers, so tiles // don't rescan all BTerms / copy the full gcell vectors on every tile. // Dropped by clearOverlayCaches() from eagerInit() (design reload), and by diff --git a/openroad/web/src/ui-utils.js b/openroad/web/src/ui-utils.js index 9e7533b8171..57d89d5ff2c 100644 --- a/openroad/web/src/ui-utils.js +++ b/openroad/web/src/ui-utils.js @@ -3,7 +3,7 @@ // Shared UI utilities. -import { dbuRectToBounds } from './coordinates.js'; +import { dbuRectToWorldRect } from './coordinates.js'; import { TILE_SIZE_CSS, TILE_SIZE_QUANTUM } from './tile-request.js'; // True when the app was bootstrapped from a saved/static report @@ -13,11 +13,8 @@ export function isStaticMode(app) { } // Visibility keys that drive other keys here and never reach the wire, marked -// by name the way selectability keys are marked with `s_`. A list of them -// would be a fourth place to remember a new one, and forgetting is silent: -// the tile cache is keyed on the request JSON minus the flags the server -// recognizes (request_handler.cpp), so a key it has never heard of survives -// that subtraction and turns its own toggle into a full-screen cache miss. +// by name the way selectability keys are marked with `s_`, so a new one needs +// no list of its own. const CLIENT_ONLY_PREFIX = 'ui_'; // The one message both hierarchy views show when their overlay is switched @@ -79,6 +76,70 @@ export function showToast(message, durationMs = 4000) { return toast; } +// A warning in the bottom-right corner of the page that stays until closed. +// With `dontShowAgain`, a second button calls it and closes the warning. +export function showCornerWarning(message, { dontShowAgain } = {}) { + const box = document.createElement('div'); + box.className = 'or-corner-warning'; + box.setAttribute('role', 'alert'); + const body = document.createElement('div'); + const text = document.createElement('span'); + text.textContent = message; + body.append(text); + if (dontShowAgain) { + const never = document.createElement('button'); + never.type = 'button'; + never.className = 'or-corner-warning-never'; + never.textContent = "Don't show again"; + never.addEventListener('click', () => { + dontShowAgain(); + box.remove(); + }); + body.append(never); + } + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'or-corner-warning-close'; + close.title = 'Close'; + close.setAttribute('aria-label', 'Close'); + close.textContent = '×'; + close.addEventListener('click', () => box.remove()); + box.append(body, close); + document.body.appendChild(box); + return box; +} + +// Software rasterizers luma.gl does not flag: it reports only SwiftShader as +// gpuType 'cpu', so Mesa's (Firefox, remote desktops) and Windows' come back +// 'unknown'. +const kSoftwareRenderer = + /SwiftShader|llvmpipe|lavapipe|softpipe|Basic Render Driver/i; + +// A page cannot read the browser's setting, only that there is no GPU, so the +// advice is conditional: without a GPU in the machine, the setting is moot. +const kAccelerationHint = 'If hardware acceleration is turned off in your ' + + "browser settings ('Use graphics acceleration when available' or 'Use " + + "hardware acceleration when available'), turn it on and restart the " + + 'browser.'; + +// What to tell a user whose browser draws the layout view without the GPU: +// { kind: 'nowebgl' | 'software', message }, or null. +export function renderingWarning(info) { + if (!info) { + return null; + } + if (info.gpuType === 'none') { + return { kind: 'nowebgl', message: 'WebGL is not available, so the ' + + 'layout view cannot be drawn. ' + kAccelerationHint }; + } + const name = `${info.vendor || ''} ${info.renderer || ''}`; + if (info.gpuType !== 'cpu' && !kSoftwareRenderer.test(name)) { + return null; + } + return { kind: 'software', message: 'The layout view is being drawn in ' + + 'software, without the GPU, which is slower. ' + kAccelerationHint }; +} + // Themed confirmation dialog. Resolves true when confirmed, false when // cancelled (button, Escape, or clicking outside the box). Focus starts // on Cancel — the safe choice for destructive confirmations. @@ -151,7 +212,7 @@ function bloatRect([[yMin, xMin], [yMax, xMax]], fraction) { // ([[yMin, xMin], [yMax, xMax]], the tile-grid georeference). Pure so it // can be unit-tested; returns null when the design is empty. // -// `fitRect`, in the same wire order, is what the map zooms to fit: the design +// `fitRect`, in the same wire order, is what the view zooms to fit: the design // without the pin-label margin the georeference rect carries. Framing on the // georeference rect instead leaves that margin as dead space around the design // (issue #11338). Omitted, the georeference rect is fitted, as before. @@ -167,11 +228,11 @@ export function computeBoundsTransforms(designBounds, tileSize = 256, const [[fitYMin, fitXMin], [fitYMax, fitXMax]] = bloatRect(fit, kZoomMargin); return { scale, - maxDXDY, originX: minX, originY: minY, - fitBounds: dbuRectToBounds(fitXMin, fitYMin, fitXMax, fitYMax, - scale, maxDXDY, minX, minY), + // World rect [minX, minY, maxX, maxY] (layout-view.js). + fitRect: dbuRectToWorldRect(fitXMin, fitYMin, fitXMax, fitYMax, + scale, minX, minY), }; } @@ -221,14 +282,14 @@ export function onSelectionReset(app, fn) { app.selectionResetters.push(fn); } -// Fit the map to a DBU rectangle [xMin, yMin, xMax, yMax]. Shared by the +// Fit the view to a DBU rectangle [xMin, yMin, xMax, yMax]. Shared by the // Inspector's "Zoom to", the Clusters panel's double-click and the DRC widget. export function zoomToBBox(app, bbox, padding = 20) { - if (!bbox || !app || !app.map || !app.designScale) return; + if (!bbox || !app || !app.view || !app.designScale) return; const [x1, y1, x2, y2] = bbox; - app.map.fitBounds( - dbuRectToBounds(x1, y1, x2, y2, app.designScale, app.designMaxDXDY, - app.designOriginX, app.designOriginY), + app.view.fitWorldRect( + dbuRectToWorldRect(x1, y1, x2, y2, app.designScale, + app.designOriginX, app.designOriginY), { padding: [padding, padding] }); } @@ -253,50 +314,17 @@ export async function withBusyCursor(fn, root = document.body) { } } -// Leaflet map options for the 2D layout viewer. -// -// zoomSnap:1 + zoomDelta:1 force the map to rest only at INTEGER zoom levels, -// so server tiles are displayed 1:1 at rest with no fractional CSS rescaling -// of the tile pane. Downscaling a band-limited dense raster (bump arrays) -// re-introduces the moiré beat the server worked to remove; resting on integer -// zoom (combined with the floor _clampZoom override in the tile layers, which -// guarantees the pane is only ever upscaled) prevents that. -// -// `crs` is parameterized so this is unit-testable without the Leaflet global. -// `prefs` carries the two Options-menu preferences the map itself owns -// (see kArrowStepDefault and installWheelPanning). -export function buildMapOptions( - crs = (typeof L !== 'undefined' ? L.CRS.Simple : undefined), - prefs = {}) { - return { - crs, - zoom: 1, - zoomSnap: 1, - zoomDelta: 1, - fadeAnimation: false, - attributionControl: false, - // Qt Options > "Mouse wheel mapped to zoom by default". The live - // viewer never reads this: installWheelPanning turns Leaflet's own - // wheel handler off and implements both directions itself, because - // Leaflet cannot pan on the wheel. Kept so the option carries the - // preference for a consumer that does not install that handler, and - // absent preference keeps the wheel zooming, which is what shipped. - scrollWheelZoom: prefs.wheelZoom !== false, - keyboardPanDelta: clampArrowStep(prefs.arrowStep), - }; -} - // Qt Options > "Arrow keys scroll step": how far one arrow press pans, in CSS // px. Qt's dialog accepts 10..1000 with a default of 20; the default here -// stays at Leaflet's 80 because that is what the web viewer has always done -// and dropping to 20 would quietly make every arrow press a quarter as far. +// stays at 80 because that is what the web viewer has always done and +// dropping to 20 would quietly make every arrow press a quarter as far. export const kArrowStepDefault = 80; export const kArrowStepMin = 10; export const kArrowStepMax = 1000; // Coerce a stored or user-typed step to a usable number. Anything -// unparseable falls back to the default rather than to NaN, which Leaflet -// would turn into a map that ignores the arrow keys entirely. +// unparseable falls back to the default rather than to NaN, which would make +// the arrow keys move the view nowhere. export function clampArrowStep(value) { // Number('') and Number(null) are both 0, which would clamp to the // minimum; an unset cookie has to read as absent, not as "10 px". @@ -308,19 +336,6 @@ export function clampArrowStep(value) { return Math.min(kArrowStepMax, Math.max(kArrowStepMin, step)); } -// Push a new arrow-key step into an already-open map. -// -// Leaflet reads options.keyboardPanDelta once, in Keyboard.initialize, so -// assigning that option on a live map does nothing -- the distance lives in -// the handler's own key map, which _setPanDelta rebuilds from this argument -// (Leaflet 1.9.4, Map.Keyboard.js). Hence the push rather than an option -// write. _setPanDelta is private, so every hop is optional-chained: a static -// report has no keyboard handler, and setArrowStep can run before the map -// exists. buildMapOptions carries the value for the next map either way. -export function applyArrowStep(map, step) { - map?.keyboard?._setPanDelta?.(step); -} - // Build a display-controls group header row: an expand/collapse triangle and // a stretching name cell. Callers fill in `name.textContent` and append their // checkbox columns after it, which pins those columns to the row's right edge @@ -375,17 +390,16 @@ export function attachGroupCollapse(header, arrow, children, collapsed) { // Deepest zoom worth offering, given `designScale` (pixels per DBU at zoom 0). // -// Leaflet's default maxZoom is Infinity unless a layer supplies one, and -// L.GridLayer -- unlike L.TileLayer -- supplies none. Left unbounded the zoom -// keeps climbing past any useful magnification until the arithmetic gives out: +// Left unbounded the zoom keeps climbing past any useful magnification until +// the arithmetic gives out: // the server's tile span (maxDXDY / 2^z) underflows to zero, so tiles come back -// empty and the design appears to vanish, and the map's own 2^z factors reach +// empty and the design appears to vanish, and the view's own 2^z factors reach // Infinity, which JSON.stringify writes as `null` in the tile request. // // The cap is where one DBU already covers `maxPxPerDbu` screen pixels: a DBU is // the smallest distance the database can express, so magnifying it further // shows nothing that was not already visible. Returned as an integer because -// the map rests on integer zoom levels (see buildMapOptions). +// the view rests on integer zoom levels (layout-view.js). // Must match kMaxTileZoom in request_handler.h: the server refuses a deeper // tile, so asking for one would only trade blank tiles for error responses. export const MAX_TILE_ZOOM = 30; @@ -405,8 +419,8 @@ export function maxUsefulZoom(designScale, maxPxPerDbu = 8) { // The CSS tile size that makes zoom-to-fit land on an integer zoom level. // -// The map rests only on integer zoom (buildMapOptions), and Leaflet's -// fitBounds FLOORS the zoom it computes, so the design is displayed anywhere +// The view rests only on integer zoom, and fitting FLOORS the zoom it computes +// (view-math.js fitView), so the design is shown // between half and all of what would fit — 52% of the viewport in the case // reported as issue #11338, against 91% in the Qt GUI. // @@ -429,7 +443,7 @@ export function maxUsefulZoom(designScale, maxPxPerDbu = 8) { // today's one. That leaves two sizes to pick from, so the design fills at // least 2/3 of the framed box rather than the 1/2 the bare floor allows. // -// Only the zoom-to-fit rect gets this: every other fitBounds caller (zoom to +// Only the zoom-to-fit rect gets this: every other fit caller (zoom to // selection, the DRC widget, rubber-band zoom) still loses up to a level to // the same floor, and a size picked for this rect cannot help theirs. // @@ -437,20 +451,20 @@ export function maxUsefulZoom(designScale, maxPxPerDbu = 8) { // window resize detunes it until the next reload, which costs at worst the // level the fit loses today. export function fittedTileSizeCss({ designBounds, fitRect, viewW, viewH }) { - // The framed box, margin and fit-rect fallback included, in the map units - // TILE_SIZE_CSS defines -- so this cannot drift from what fitBounds sees. + // The framed box, margin and fit-rect fallback included, in the view's units + // TILE_SIZE_CSS defines -- so this cannot drift from what the fit sees. const t = computeBoundsTransforms(designBounds, TILE_SIZE_CSS, fitRect); const finitePositive = (v) => Number.isFinite(v) && v > 0; if (!t || !finitePositive(viewW) || !finitePositive(viewH)) { return TILE_SIZE_CSS; } - const framedW = t.fitBounds[1][1] - t.fitBounds[0][1]; - const framedH = t.fitBounds[1][0] - t.fitBounds[0][0]; + const framedW = t.fitRect[2] - t.fitRect[0]; + const framedH = t.fitRect[3] - t.fitRect[1]; // Pixels the framed box may grow by before it leaves the viewport, which - // is 2^(the zoom fitBounds wants) at tile size TILE_SIZE_CSS. + // is 2^(the zoom the fit wants) at tile size TILE_SIZE_CSS. const room = Math.min(viewW / framedW, viewH / framedH); const zStar = Math.log2(room); - // Below zoom 0 the map is already pinned at its minZoom and the fit has + // Below zoom 0 the view is already pinned at its minZoom and the fit has // nothing left to floor, so a bigger tile would only overflow the viewport. if (!Number.isFinite(zStar) || zStar < 0) { return TILE_SIZE_CSS; @@ -544,19 +558,27 @@ export function cssColorToHex(s) { // Wrap fn in a single-flight requestAnimationFrame scheduler: calls made // while a frame is already pending coalesce into one invocation of fn. -export function rafCoalesce(fn) { - let pending = null; +// `schedule` stands in for requestAnimationFrame (a view's injected one). +export function rafCoalesce(fn, schedule = (cb) => requestAnimationFrame(cb)) { + let pending = false; return () => { - if (pending !== null) { + if (pending) { return; } - pending = requestAnimationFrame(() => { - pending = null; + pending = true; + schedule(() => { + pending = false; fn(); }); }; } +// The user asked the system for less motion. +export function prefersReducedMotion() { + return typeof matchMedia === 'function' + && matchMedia('(prefers-reduced-motion: reduce)').matches; +} + // Round a positive value to the nearest 1/2/5/10 × 10^n, returning both the // rounded value and the chosen leading digit (used to pick tick subdivisions). export function niceRoundParts(value) { @@ -831,31 +853,6 @@ export function decorateTabIcons(root = document) { return 0; } -// Qt's LayoutScroll::wheelEvent, ported. The preference and the Ctrl modifier -// pick between panning and zooming, so Ctrl always does whichever one the -// preference did not: with the preference off (Qt's default) the wheel pans and -// Ctrl+wheel zooms, and with it on they swap. -// -// Both branches live here and Leaflet's own scrollWheelZoom is left disabled: -// Leaflet has no pan-on-wheel option, and leaving its handler on would zoom in -// addition to whatever this one did. Zooming goes through setZoomAround so the -// point under the cursor stays put, matching Qt's zoomIn(mouse_pos, true) and -// the viewer's own Z / Shift+Z keys. -export function installWheelPanning(map, wheelZoomEnabled) { - map.scrollWheelZoom.disable(); - map.getContainer().addEventListener('wheel', (e) => { - e.preventDefault(); - if (wheelZoomEnabled() === e.ctrlKey) { - const [dx, dy] = wheelDeltaPx(e, () => map.getContainer().clientHeight); - map.panBy([dx, dy], { animate: false }); - return; - } - // A wheel notch is one zoom level, like the Z / Shift+Z keys. - const step = e.deltaY < 0 ? 1 : -1; - map.setZoomAround(map.mouseEventToLatLng(e), map.getZoom() + step); - }, { passive: false }); -} - // A wheel event's scroll amount in CSS pixels. deltaMode is not always pixels: // Firefox reports lines, and a page-mode event (rare, but produced by some // remote-desktop stacks) means a viewport at a time. Treating either as pixels diff --git a/openroad/web/src/vendor.css b/openroad/web/src/vendor.css index 5d4f210a5d9..4ec1a35952d 100644 --- a/openroad/web/src/vendor.css +++ b/openroad/web/src/vendor.css @@ -3,5 +3,4 @@ /* Bundled so esbuild inlines the icons their url()s reach. */ -@import 'leaflet/dist/leaflet.css'; @import 'golden-layout/dist/css/goldenlayout-base.css'; diff --git a/openroad/web/src/view-input.js b/openroad/web/src/view-input.js new file mode 100644 index 00000000000..dbe20d1bd1f --- /dev/null +++ b/openroad/web/src/view-input.js @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// Mouse, wheel and keyboard on the layout view, as DOM listeners over the view +// API. Drag-panning is left to the renderer; everything that zooms, selects +// or draws a box is here. + +import { kArrowStepDefault, wheelDeltaPx } from './ui-utils.js'; + +const kClickTolerancePx = 3; // a press that moves less is a click +const kBandMinPx = 4; // a smaller right-drag is a click +const kShiftJitterPx = 12; // a Shift+click may move this far without a band +const kNotchMinPx = 50; // a mouse wheel step in pixels is at least this +const kPxPerLevel = 100; // trackpad scroll that zooms one level +const kGestureIdleMs = 200; // a pause this long ends a trackpad gesture +const kGestureMinLevels = 0.2; // a smaller gesture springs back +const kMacWheelStep = 4.000244140625; // Chrome on macOS: one mouse wheel step + +// Steps from a mouse wheel: lines or pages, whole pixel steps of at least +// kNotchMinPx, or multiples of kMacWheelStep, with no sideways part. A +// trackpad scroll or pinch is a stream of small deltas instead. +export function isWheelNotch(e) { + if (e.deltaMode !== 0) { + return true; + } + if (e.deltaX !== 0 || e.deltaY === 0) { + return false; + } + return (Number.isInteger(e.deltaY) && Math.abs(e.deltaY) >= kNotchMinPx) + || e.deltaY % kMacWheelStep === 0; +} + +// The whole levels a trackpad gesture of `d` levels ends on: at least one +// past kGestureMinLevels, the nearest after that. +export function gestureSteps(d) { + const a = Math.abs(d); + return a < kGestureMinLevels ? 0 : Math.sign(d) * Math.max(1, Math.round(a)); +} + +// Arrow key -> pan in screen px; Shift pans 3x. +export function arrowPanOffset(key, step, shift) { + const s = shift ? 3 * step : step; + switch (key) { + case 'ArrowLeft': return [-s, 0]; + case 'ArrowRight': return [s, 0]; + case 'ArrowUp': return [0, -s]; + case 'ArrowDown': return [0, s]; + default: return null; + } +} + +// `opts`: +// isStatic() a saved report: only drag and the arrow keys stay on +// wheelZoom() Options > "Mouse wheel mapped to zoom" +// arrowStep() Options > "Arrow keys scroll step", CSS px +// onClick(world, event), onContextClick(world, event) +// onMove(world, event), onLeave(event) +// contextEnabled() false while a ruler is being placed +// gestureIdleMs the pause that ends a trackpad gesture (tests) +// installViewInput's click options for the app: a ruler or a label being +// placed takes left clicks and turns off the context menu. +export function placementClicks(app) { + return { + contextEnabled: () => !(app.rulerManager?.isActive() + || app.labelManager?.isActive()), + onClick(world, e) { + if (app.rulerManager?.isActive()) { + app.rulerManager.handleMapClick(world, e); + } else if (app.labelManager?.isActive() + || !app.rulerManager?.handleRulerClick(world)) { + // In label mode this places the label. + app.onMapClick?.(world, e); + } + }, + }; +} + +export function installViewInput(view, opts = {}) { + const container = view.getContainer(); + const isStatic = opts.isStatic || (() => false); + const wheelZoom = opts.wheelZoom || (() => true); + const arrowStep = opts.arrowStep || (() => kArrowStepDefault); + const gestureIdleMs = opts.gestureIdleMs ?? kGestureIdleMs; + const contextEnabled = opts.contextEnabled || (() => true); + const listeners = []; + const on = (target, type, fn, options) => { + target.addEventListener(type, fn, options); + listeners.push(() => target.removeEventListener(type, fn, options)); + }; + const local = (e) => { + const r = container.getBoundingClientRect(); + return [e.clientX - r.left, e.clientY - r.top]; + }; + const worldAt = (e) => view.unproject(local(e)); + // On the layout itself: not on a control, HUD or marker over it, which + // handle their own input. + const onView = (e) => e.target === container + || !!e.target?.closest?.('.or-view-canvas'); + + if (container.tabIndex < 0) { + container.tabIndex = 0; + } + + // The view holds deferred tile updates while a gesture streams in. + let holding = false; + let panTimer = null; + function hold(on) { + if (holding !== on) { + holding = on; + view.setGesture(on); + } + } + + // A trackpad zoom follows the fingers at fractional levels, then rests on + // a whole level once they stop. + let gesture = null; // { z0, pt, timer } + function zoomGesture(pt, levels) { + hold(true); + if (!gesture) { + // Where an animation under way is heading, as zoomAround counts. + gesture = { z0: view.getTargetZoom() }; + } + gesture.pt = pt; + clearTimeout(gesture.timer); + gesture.timer = setTimeout(endGesture, gestureIdleMs); + view.zoomAround(pt, levels, { animate: false, settle: false }); + } + function endGesture() { + if (!gesture) { + return; + } + const g = gesture; + gesture = null; + clearTimeout(g.timer); + const z = view.getZoom(); + view.zoomAround(g.pt, g.z0 + gestureSteps(z - g.z0) - z); + // A scroll still under way keeps the view held until it pauses. + if (panTimer === null) { + hold(false); + } + } + listeners.push(() => { + clearTimeout(gesture?.timer); + gesture = null; + clearTimeout(panTimer); + hold(false); + }); + + // Wheel: the preference and Ctrl pick between panning and zooming around + // the cursor (Qt's LayoutScroll::wheelEvent), one level per mouse step. + // A pinch always zooms. + on(container, 'wheel', (e) => { + e.preventDefault(); + if (isStatic() || (e.deltaX === 0 && e.deltaY === 0)) { + return; + } + const notch = isWheelNotch(e); + if (!notch && e.ctrlKey && e.deltaY !== 0) { + // Chrome and Firefox send a pinch as ctrl+wheel with + // deltaY = -100 ln(scale). + zoomGesture(local(e), -e.deltaY / (100 * Math.LN2)); + return; + } + // A sideways scroll pans, Ctrl or not, whatever the wheel does. A + // zoom gesture under way keeps going and settles once the fingers stop. + if (wheelZoom() === e.ctrlKey || e.deltaY === 0) { + const [dx, dy] = wheelDeltaPx(e, () => container.clientHeight); + hold(true); + clearTimeout(panTimer); + panTimer = setTimeout(() => { + panTimer = null; + if (!gesture) { + hold(false); + } + }, gestureIdleMs); + view.panByPx(dx, dy, { animate: false, settle: !gesture }); + return; + } + if (!notch) { + zoomGesture(local(e), -e.deltaY / kPxPerLevel); + return; + } + endGesture(); + view.zoomAround(local(e), e.deltaY < 0 ? 1 : -1); + }, { passive: false }); + + on(container, 'keydown', (e) => { + if (e.altKey || e.ctrlKey || e.metaKey) { + return; + } + const offset = arrowPanOffset(e.key, arrowStep(), e.shiftKey); + if (offset) { + e.preventDefault(); + view.panByPx(offset[0], offset[1]); + return; + } + if (isStatic()) { + return; + } + const zoomKeys = { '+': 1, '=': 1, '-': -1, '_': -1 }; + if (e.key in zoomKeys) { + e.preventDefault(); + view.zoomAround(null, zoomKeys[e.key] * (e.shiftKey ? 3 : 1)); + } + }); + + // Left button: a press that moves no more than the tolerance is a click, + // however long it is held. Shift+drag draws a zoom box instead of panning. + let press = null; + let box = null; + on(container, 'pointerdown', (e) => { + // A second finger makes it no click, wherever it lands. + if (e.isPrimary === false) { + if (press) { + press.moved = true; + } + return; + } + if (e.button !== 0 || !onView(e)) { + return; + } + // A new first finger replaces a press whose release was lost, bands + // and all. + endDrags(); + container.focus({ preventScroll: true }); + press = { id: e.pointerId, x: e.clientX, y: e.clientY, moved: false, + box: e.shiftKey && !isStatic() }; + if (press.box) { + e.stopPropagation(); // keep the renderer from panning + } + }, { capture: true }); + + on(window, 'pointermove', (e) => { + if (!press || e.pointerId !== press.id) { + return; + } + const dx = e.clientX - press.x; + const dy = e.clientY - press.y; + if (Math.abs(dx) > kClickTolerancePx + || Math.abs(dy) > kClickTolerancePx) { + press.moved = true; + } + // As big as a right-drag band before it zooms: a Shift+click that + // jitters a few pixels still adds to the selection. + if (press.box && (box || (Math.abs(dx) >= kBandMinPx + && Math.abs(dy) >= kBandMinPx))) { + box = drawBand(box, press, e); + } + }); + + on(window, 'pointerup', (e) => { + if (!press || e.button !== 0 || e.pointerId !== press.id) { + return; + } + const p = press; + press = null; + const boxed = !!box; + if (box) { + box.remove(); + box = null; + } + if (boxed) { + fitScreenBox(p, e); + return; + } + // A Shift press that only jittered still clicks; a longer drag that + // drew no band does nothing. + const still = Math.abs(e.clientX - p.x) <= kShiftJitterPx + && Math.abs(e.clientY - p.y) <= kShiftJitterPx; + if ((!p.moved || (p.box && still)) && opts.onClick && isInside(e)) { + opts.onClick(worldAt(e), e); + } + }); + + on(container, 'dblclick', (e) => { + if (isStatic() || !onView(e)) { + return; + } + view.zoomAround(local(e), e.shiftKey ? -1 : 1); + }); + + // Right button: drag for a rubber-band zoom, click for the context menu. + let band = null; + let bandEl = null; + on(container, 'contextmenu', (e) => e.preventDefault()); + on(container, 'pointerdown', (e) => { + if (e.button !== 2 || isStatic() || !onView(e)) { + return; + } + e.stopPropagation(); + // A new press replaces a band whose release was lost. + bandEl?.remove(); + bandEl = null; + band = { x: e.clientX, y: e.clientY }; + }, { capture: true }); + on(window, 'pointermove', (e) => { + if (!band) { + return; + } + const dx = e.clientX - band.x; + const dy = e.clientY - band.y; + if (bandEl || (Math.abs(dx) >= kBandMinPx && Math.abs(dy) >= kBandMinPx)) { + bandEl = drawBand(bandEl, band, e); + } + }); + on(window, 'pointerup', (e) => { + if (!band || e.button !== 2) { + return; + } + const start = band; + band = null; + if (bandEl) { + bandEl.remove(); + bandEl = null; + fitScreenBox(start, e); + return; + } + if (isInside(e) && contextEnabled() && opts.onContextClick) { + opts.onContextClick(worldAt(e), e); + } + }); + + // A drag the browser takes away (a touch turned into a scroll, the window + // losing focus) gets no pointerup: drop its band too. + function endDrags() { + press = null; + band = null; + box?.remove(); + box = null; + bandEl?.remove(); + bandEl = null; + } + on(window, 'pointercancel', endDrags); + on(window, 'blur', endDrags); + + on(container, 'pointermove', (e) => { + if (opts.onMove) { + opts.onMove(worldAt(e), e); + } + }); + on(container, 'pointerleave', (e) => { + if (opts.onLeave) { + opts.onLeave(e); + } + }); + + function isInside(e) { + const r = container.getBoundingClientRect(); + return e.clientX >= r.left && e.clientX <= r.right + && e.clientY >= r.top && e.clientY <= r.bottom; + } + + function fitScreenBox(start, e) { + const r = container.getBoundingClientRect(); + const a = view.unproject([start.x - r.left, start.y - r.top]); + const b = view.unproject([e.clientX - r.left, e.clientY - r.top]); + view.fitWorldRect([Math.min(a[0], b[0]), Math.min(a[1], b[1]), + Math.max(a[0], b[0]), Math.max(a[1], b[1])]); + } + + return { + dispose() { + endDrags(); + for (const off of listeners.splice(0)) { + off(); + } + }, + }; +} + +// The rubber-band rectangle, in page coordinates. +function drawBand(el, start, e) { + if (!el) { + el = document.createElement('div'); + el.className = 'rubber-band'; + document.body.appendChild(el); + } + el.style.left = Math.min(start.x, e.clientX) + 'px'; + el.style.top = Math.min(start.y, e.clientY) + 'px'; + el.style.width = Math.abs(e.clientX - start.x) + 'px'; + el.style.height = Math.abs(e.clientY - start.y) + 'px'; + return el; +} diff --git a/openroad/web/src/view-math.js b/openroad/web/src/view-math.js new file mode 100644 index 00000000000..e1a02470692 --- /dev/null +++ b/openroad/web/src/view-math.js @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// Pure geometry of the 2D layout view. +// +// World units are CSS px at zoom 0 with y up, so the tile grid is the square +// [0, T] x [0, T] for a tile size of T. A view state is +// `{ target: [x, y], zoom, width, height }`, width and height in CSS px, and +// screen coordinates are CSS px from the view's top-left corner. Tile rows are +// the server's: y counts down from the top of the grid. + +const EPS = 1e-9; + +function scaleOf(zoom) { + return Math.pow(2, zoom); +} + +export function project([wx, wy], vs) { + const s = scaleOf(vs.zoom); + return [(wx - vs.target[0]) * s + vs.width / 2, + vs.height / 2 - (wy - vs.target[1]) * s]; +} + +export function unproject([px, py], vs) { + const s = scaleOf(vs.zoom); + return [vs.target[0] + (px - vs.width / 2) / s, + vs.target[1] - (py - vs.height / 2) / s]; +} + +// The world rect [minX, minY, maxX, maxY] the view shows. +export function viewWorldRect(vs) { + const [x0, y1] = unproject([0, 0], vs); + const [x1, y0] = unproject([vs.width, vs.height], vs); + return [x0, y0, x1, y1]; +} + +export function clampZoom(zoom, { minZoom = -Infinity, maxZoom = Infinity } = {}) { + return Math.max(minZoom, Math.min(maxZoom, zoom)); +} + +// The view that fits world `rect` with `padding` px on every side: the zoom is +// floored to a whole level after rounding to 1/100 of a level, and the rect is +// centered. +export function fitView(rect, vs, { padding = [0, 0], minZoom, maxZoom } = {}) { + const w = Math.max(1, vs.width - 2 * padding[0]); + const h = Math.max(1, vs.height - 2 * padding[1]); + const rw = Math.max(rect[2] - rect[0], EPS); + const rh = Math.max(rect[3] - rect[1], EPS); + const raw = Math.log2(Math.min(w / rw, h / rh)); + const zoom = clampZoom(Math.floor(Math.round(raw * 100) / 100), + { minZoom, maxZoom }); + return { target: [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2], zoom }; +} + +// The target that keeps the world point under `screenPt` still at `zoom`. +export function zoomAround(vs, screenPt, zoom) { + const [wx, wy] = unproject(screenPt, vs); + const s = scaleOf(zoom); + return [wx - (screenPt[0] - vs.width / 2) / s, + wy + (screenPt[1] - vs.height / 2) / s]; +} + +// Tile level for a view zoom: floored, so tiles are only ever shown upscaled +// (the moiré fix of #10463). While an animation heads for `targetZoom` and the +// new level stays hidden until it is complete, that level may load early. +export function tileZoomFor(zoom, { targetZoom = null, hidingNewLevels = false } = {}) { + const z = (hidingNewLevels && targetZoom !== null) ? targetZoom : zoom; + return Math.floor(z + EPS); +} + +// Inclusive tile range at level z covering world `rect`, clamped to the 2^z +// grid; null when the rect misses the grid. +export function tileRange(rect, z, tileSize) { + const n = Math.pow(2, z); + const s = tileSize / n; + const x0 = Math.max(0, Math.floor(rect[0] / s)); + const x1 = Math.min(n - 1, Math.ceil(rect[2] / s) - 1); + const y0 = Math.max(0, n - Math.ceil(rect[3] / s)); + const y1 = Math.min(n - 1, n - 1 - Math.floor(rect[1] / s)); + if (x0 > x1 || y0 > y1) { + return null; + } + return { z, x0, x1, y0, y1 }; +} + +// `rect` grown by `f` times its width and height on every side. +export function growRect([x0, y0, x1, y1], f) { + const dx = (x1 - x0) * f; + const dy = (y1 - y0) * f; + return [x0 - dx, y0 - dy, x1 + dx, y1 + dy]; +} + +export function growRange(range, by = 1) { + if (!range) { + return null; + } + const n = Math.pow(2, range.z); + return { + z: range.z, + x0: Math.max(0, range.x0 - by), + x1: Math.min(n - 1, range.x1 + by), + y0: Math.max(0, range.y0 - by), + y1: Math.min(n - 1, range.y1 + by), + }; +} + +export function inRange(range, x, y) { + return !!range && x >= range.x0 && x <= range.x1 + && y >= range.y0 && y <= range.y1; +} + +// Tiles of `range`, nearest the range center first. +export function rangeTiles(range) { + if (!range) { + return []; + } + const cx = (range.x0 + range.x1) / 2; + const cy = (range.y0 + range.y1) / 2; + const out = []; + for (let y = range.y0; y <= range.y1; y++) { + for (let x = range.x0; x <= range.x1; x++) { + out.push({ z: range.z, x, y, d: (x - cx) ** 2 + (y - cy) ** 2 }); + } + } + out.sort((a, b) => a.d - b.d); + return out.map(({ z, x, y }) => ({ z, x, y })); +} + +// World bounds [left, bottom, right, top] of tile (z, x, y). +export function tileWorldBounds(z, x, y, tileSize) { + const s = tileSize / Math.pow(2, z); + return [x * s, tileSize - (y + 1) * s, (x + 1) * s, tileSize - y * s]; +} + +export function rectsOverlap(a, b) { + return a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]; +} + +// The target nudged so world (0, 0) lands on a whole device pixel. Tile sizes +// are whole device pixels, so every tile edge then does too and a tile at rest +// maps 1:1 onto the device grid. +export function snapTarget(vs, dpr) { + const s = scaleOf(vs.zoom) * dpr; + const [px, py] = project([0, 0], vs); + const rx = px * dpr - Math.round(px * dpr); + const ry = py * dpr - Math.round(py * dpr); + return [vs.target[0] + rx / s, vs.target[1] - ry / s]; +} + +// The van Wijk & Nuij zoom-and-pan path from view `a` to view `b` (the one +// d3.interpolateZoom draws): it pulls out, travels and closes in at a constant +// apparent speed. Returns `at(t)` -> { target, zoom } for t in [0, 1] and the +// path length `S` (larger is a longer flight). +export function flyPath(a, b) { + const rho = Math.SQRT2; + const rho2 = 2; + const rho4 = 4; + const size = Math.max(a.width, a.height); + const [ux0, uy0] = a.target; + const [ux1, uy1] = b.target; + const w0 = size / scaleOf(a.zoom); // world units across the view + const w1 = size / scaleOf(b.zoom); + const dx = ux1 - ux0; + const dy = uy1 - uy0; + const d2 = dx * dx + dy * dy; + const zoomOf = (w) => Math.log2(size / w); + if (d2 < 1e-12) { + const S = Math.log(w1 / w0) / rho; + return { + S: Math.abs(S), + at: (t) => ({ target: [ux0 + t * dx, uy0 + t * dy], + zoom: zoomOf(w0 * Math.exp(rho * t * S)) }), + }; + } + const d1 = Math.sqrt(d2); + const b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1); + const b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1); + // ln(sqrt(b^2 + 1) - b), without the cancellation that makes it log(0). + const r0 = -Math.asinh(b0); + const r1 = -Math.asinh(b1); + const S = (r1 - r0) / rho; + const coshr0 = Math.cosh(r0); + return { + S, + at: (t) => { + if (t >= 1) { + return { target: [ux1, uy1], zoom: b.zoom }; + } + const s = t * S; + const u = w0 / (rho2 * d1) + * (coshr0 * Math.tanh(rho * s + r0) - Math.sinh(r0)); + return { target: [ux0 + u * dx, uy0 + u * dy], + zoom: zoomOf(w0 * coshr0 / Math.cosh(rho * s + r0)) }; + }, + }; +} + +// Animation curves, 0..1 to 0..1. +export function easeOutQuad(t) { + return 1 - (1 - t) * (1 - t); +} + +export function easeOutCubic(t) { + return 1 - Math.pow(1 - t, 3); +} + +export function easeInOutCubic(t) { + return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(2 - 2 * t, 3) / 2; +} diff --git a/openroad/web/src/web.cpp b/openroad/web/src/web.cpp index 531a9dbcd1b..c8096c28e1a 100644 --- a/openroad/web/src/web.cpp +++ b/openroad/web/src/web.cpp @@ -1033,6 +1033,9 @@ void WebSocketSession::run(http::request&& req) websocket::stream_base::decorator([](websocket::response_type& res) { res.set(http::field::server, "OpenROAD WebSocket Server"); })); + // One frame per reply: auto-fragmenting would split a tile into + // write-buffer-sized frames, each its own write. + websocket_.auto_fragment(false); websocket_.async_accept(req, [self = shared_from_this()](beast::error_code ec) { @@ -1135,22 +1138,18 @@ void WebSocketSession::on_accept(beast::error_code ec) queue_response(cfg); } - // Build search indices in the background; tiles render without shapes - // until ready, then a "refresh" push notification triggers a redraw. + // In the background: index a newly loaded design and empty the tile cache; + // a "refresh" push then redraws. init_thread_ = std::thread([self = shared_from_this()]() { { const ScriptGateScope gate(self->tcl_eval_->script_gate, /*wait=*/true); if (!gate.entered()) { return; } - self->generator_->eagerInit(); + self->generator_->ensureInit(/*fresh_cache=*/true); } - // Only send refresh if there's actually a design to render. - // Without this guard, eagerInit returns instantly when no block is - // loaded and the push races with async_accept (Beast soft_mutex crash). - // We gate on the dbChip (not dbBlock) so 3DBlox multi-tech designs - // — whose top chip is HIER and has no dbBlock — still register the - // chip observer and send the refresh notification. + // Refresh only when there is a design to draw. The check is on the + // dbChip, not the dbBlock: a 3DBlox top chip is HIER and has no block. if (!self->generator_->getChip()) { return; } @@ -1293,10 +1292,11 @@ void WebSocketSession::queue_response(const WebSocketResponse& resp, // (malformed payloads, missing fields, wrong field types) are visible to // the operator/developer and not silently swallowed by the client. // A busy reply (see ScriptGate) is not one, and goes out per tile while a - // script runs, so it is not logged. + // script runs, so it is not logged; nor is a cancelled one. const std::string_view err(reinterpret_cast(resp.payload.data()), resp.payload.size()); - if (resp.type == WebSocketResponse::kError && err != kScriptBusyMsg) { + if (resp.type == WebSocketResponse::kError && err != kScriptBusyMsg + && err != kCancelledMsg) { const std::string type_label = resp.request_type.empty() ? "unknown" : resp.request_type; logger_->warn(utl::WEB, @@ -1897,7 +1897,7 @@ void WebServer::saveReport(const std::string& filename, const int max_hold) { // Create/init the tile generator. - ensureGenerator().eagerInit(); + ensureGenerator().ensureInit(); odb::dbBlock* block = generator_->getBlock(); const std::vector design_blocks = generator_->blocks(); @@ -2008,7 +2008,7 @@ void WebServer::saveReport(const std::string& filename, // ── Render tiles at a fixed zoom level ── // Pick z so the design fits in a typical panel (~500px). - // In Leaflet CRS.Simple, the design spans 256 units = 256*2^z pixels. + // At zoom z the design spans 256*2^z pixels (256 px tiles). // z=1 → 512px, a good fit for most panel sizes. constexpr int kZ = 1; const int num_tiles = 1 << kZ; @@ -2045,7 +2045,8 @@ void WebServer::saveReport(const std::string& filename, std::vector> tile_entries; TileVisibility scoped_vis = vis; const auto extents = generator_->layerExtents(); - // World rect of each tile, indexed [ty][tx] with ty as Leaflet counts it. + // World rect of each tile, indexed [ty][tx] with ty counted top-down, as the + // client does. const odb::Rect bounds = generator_->getBounds(); std::vector> tile_rects(num_tiles); for (int ty = 0; ty < num_tiles; ++ty) { @@ -2090,7 +2091,8 @@ void WebServer::saveReport(const std::string& filename, // ── Render per-path overlay images ── - const std::vector& chiplets = generator_->chiplets(); + const auto chiplet_list = generator_->chiplets(); + const std::vector& chiplets = *chiplet_list; auto render_path_overlays = [&](const std::vector& paths) { std::vector overlays; for (const auto& path : paths) { @@ -2370,7 +2372,7 @@ void WebServer::saveImage(const std::string& filename, const std::map& display_settings) { // Create generator on demand (server may not be running). - ensureGenerator().eagerInit(); + ensureGenerator().ensureInit(); const odb::Rect region(x0, y0, x1, y1); const ScriptImage image @@ -2574,7 +2576,8 @@ std::string WebServer::loadChipletHeatMap(const std::string& file_path) // guaranteed unique when a master is placed more than once. const ChipletNode* node = nullptr; std::string known; - for (const ChipletNode& candidate : gen.chiplets()) { + const auto nodes = gen.chiplets(); + for (const ChipletNode& candidate : *nodes) { if (!known.empty()) { known += ", "; } @@ -2790,12 +2793,11 @@ void WebServer::gifAddFrame(std::optional key, return; } - // Create generator on demand (server may not be running). eagerInit() - // rebuilds the spatial index, so run it only once per stream (first frame); - // the design is static across a GIF's frames. + // Create generator on demand (server may not be running); the design is + // static across a GIF's frames, so init it on the first one only. ensureGenerator(); if (gif->frame_count == 0) { - generator_->eagerInit(); + generator_->ensureInit(); } const ScriptImage image diff --git a/openroad/web/src/websocket-manager.js b/openroad/web/src/websocket-manager.js index 4b638761d53..d6c81086608 100644 --- a/openroad/web/src/websocket-manager.js +++ b/openroad/web/src/websocket-manager.js @@ -18,9 +18,8 @@ // send rate to the server's actual response rate. // // The effective limit is announced by the server on connect (a {type:"config", -// max_in_flight} push, scaled to the machine size) so it isn't a magic client -// constant and can grow if the server becomes multi-threaded. This is only the -// fallback used until that message arrives. +// max_in_flight} push, scaled to the server's threads) so it isn't a magic +// client constant. This is only the fallback used until that message arrives. const DEFAULT_MAX_IN_FLIGHT = 48; // Hard backpressure cap: don't push more while this much is still unsent. With // the in-flight cap this should rarely bind. @@ -31,7 +30,8 @@ const MAX_BUFFERED_BYTES = 512 * 1024; // STUCK_MS — the browser can't even hand bytes to the OS. A slow render // keeps the buffer near 0. // 2. We are saturated (in-flight at the cap) with work still queued, yet have -// heard nothing back for DEAD_MS. A slow render is one slow reply among +// heard nothing back for DEAD_MS, counted from the later of the last reply +// and the start of the saturation. A slow render is one slow reply among // fast ones, so replies keep flowing; total silence while saturated and // backed up means the server stopped servicing us entirely. This only ever // arms during a request flood (the window is full with more queued) — a @@ -62,6 +62,12 @@ export class WebSocketManager { // Requests waiting for an in-flight slot (insertion-ordered = FIFO). // Not yet on the wire, so cancel() can drop them for free. this._queue = new Map(); // id -> {msg, resolve, reject} + // Background requests (tiles prefetched around the view): sent only + // while _queue is empty, and left out of pendingCount. + this._bgQueue = new Map(); + // Background requests sent and still awaited, which pendingCount + // leaves out. + this._bgSent = new Set(); // Requests sent but not yet answered by the server (the real wire // window). Incremented on send, decremented when a reply for that sent // id arrives — even a stale one for a cancelled request. @@ -73,6 +79,7 @@ export class WebSocketManager { this._maxInFlight = DEFAULT_MAX_IN_FLIGHT; // updated by server "config" this._lastRecvAt = 0; // perf.now() of the last message of any kind this._bufStuckSince = 0; // liveness: when bufferedAmount got stuck + this._saturatedSince = 0; // liveness: when the window filled with a queue this._lastBuffered = 0; this.reconnectDelay = 1000; this.readyPromise = null; @@ -94,7 +101,15 @@ export class WebSocketManager { // Total requests the user is still waiting on: those on the wire plus those // held back by the scheduler and not yet dispatched. get pendingCount() { - return this.pending.size + (this._queue ? this._queue.size : 0); + return this.pending.size - this._bgSent.size + + (this._queue ? this._queue.size : 0); + } + + // Next up is background work and the window is already half full: the + // other half is kept for tiles needed on screen. + _bgFull() { + return this._queue.size === 0 + && this._inFlight >= Math.max(1, Math.floor(this._maxInFlight / 2)); } // Create a cache-backed instance (no WebSocket connection). @@ -105,6 +120,8 @@ export class WebSocketManager { mgr.nextId = 1; mgr.pending = new Map(); mgr._queue = new Map(); // unused in cache mode, but keeps cancel() safe + mgr._bgQueue = new Map(); + mgr._bgSent = new Set(); mgr._inFlight = 0; mgr._inFlightIds = new Set(); mgr._unknownPayloadTypes = new Set(); @@ -171,17 +188,21 @@ export class WebSocketManager { this._inFlight = 0; this._inFlightIds.clear(); this._bufStuckSince = 0; + this._saturatedSince = 0; this.onStatusChange(); for (const [id, handler] of this.pending) { handler.reject(new Error('WebSocket closed')); } this.pending.clear(); + this._bgSent.clear(); // Drop anything still queued — it never reached the wire. Reject so - // callers settle; tile callers .catch() and re-request on reconnect. - for (const [id, entry] of this._queue) { - entry.reject(new Error('WebSocket closed')); + // callers settle; the server's refresh push redraws on reconnect. + for (const queue of [this._queue, this._bgQueue]) { + for (const [id, entry] of queue) { + entry.reject(new Error('WebSocket closed')); + } + queue.clear(); } - this._queue.clear(); if (this._shutdown) { console.log('WebSocket closed (server stopped)'); this._stopLivenessMonitor(); // no socket will reopen @@ -276,7 +297,7 @@ export class WebSocketManager { console.error('Failed to parse server push JSON:', e); return; } - // The server announces the in-flight window sized to its machine. + // The server announces the in-flight window, from its thread count. // Consume it here rather than forwarding to onPush. if (msg && msg.type === 'config') { if (Number.isFinite(msg.max_in_flight)) { @@ -299,6 +320,7 @@ export class WebSocketManager { if (this._inFlightIds.delete(id) && this._inFlight > 0) { this._inFlight--; } + this._bgSent.delete(id); const handler = this.pending.get(id); if (!handler) { @@ -328,8 +350,8 @@ export class WebSocketManager { // tile consumer already treats a null payload as "draw nothing". handler.resolve(null); } else { - // An unrecognised payload type must still settle the promise, or - // the tile it belongs to hangs unresolved forever and Leaflet + // An unrecognized payload type must still settle the promise, or + // the tile it belongs to hangs unresolved forever and the view // never reveals it. A server newer than this client lands here. // // Rejected rather than resolved with null: only type 3 carries @@ -353,7 +375,7 @@ export class WebSocketManager { } } - request(msg) { + request(msg, { background = false } = {}) { if (this._cache) { return this._cacheRequest(msg); } @@ -373,7 +395,8 @@ export class WebSocketManager { promise.requestId = id; // Enqueue rather than send directly; _pump() releases it onto the wire // once an in-flight slot is available. While queued it is cancellable. - this._queue.set(id, { msg, resolve: resolveFn, reject: rejectFn }); + (background ? this._bgQueue : this._queue) + .set(id, { msg, resolve: resolveFn, reject: rejectFn }); this._pump(); return promise; } @@ -386,14 +409,22 @@ export class WebSocketManager { return; } while (this._inFlight < this._maxInFlight - && this._queue.size > 0 + && (this._queue.size > 0 || this._bgQueue.size > 0) && this.socket.bufferedAmount < MAX_BUFFERED_BYTES) { - const [id, entry] = this._queue.entries().next().value; - this._queue.delete(id); + const background = this._queue.size === 0; + if (this._bgFull()) { + break; + } + const queue = background ? this._bgQueue : this._queue; + const [id, entry] = queue.entries().next().value; + queue.delete(id); this.pending.set(id, { resolve: entry.resolve, reject: entry.reject, }); + if (background) { + this._bgSent.add(id); + } this.socket.send(JSON.stringify(entry.msg)); this._inFlightIds.add(id); this._inFlight++; @@ -401,33 +432,40 @@ export class WebSocketManager { this.onStatusChange(); } + // A background request that is now needed on screen moves to the back of + // the foreground queue, or, if already sent, counts as pending again. + promote(id) { + const entry = this._bgQueue.get(id); + if (entry) { + this._bgQueue.delete(id); + this._queue.set(id, entry); + this._pump(); + } else if (this._bgSent.delete(id)) { + this.onStatusChange(); + } + } + cancel(id) { // If still queued it never hit the wire — drop it for free (no server // work, no buffered bytes). This is the cancellation that actually // matters; cancelling an already-sent request can't recall the bytes. // Settle the promise so callers don't leak a forever-pending request. - const queued = this._queue.get(id); + const queued = this._queue.get(id) || this._bgQueue.get(id); if (queued) { this._queue.delete(id); + this._bgQueue.delete(id); queued.reject(new Error('Request cancelled')); this.onStatusChange(); return; } - - // Already sent: stop tracking the reply, but do NOT free the wire slot - // or pump — the server still has to process those bytes, and the slot - // frees only when its (now stale) reply arrives. Freeing it here would - // let cancellation churn re-flood the socket. - // - // The promise is rejected as well, for the same reason as the queued - // branch: dropping the handler without settling leaves the caller - // awaiting forever, and a caller with a `finally` never runs it. The - // merged tile layer frees its decoded ImageBitmaps there, so a silent - // drop here means every pruned or refreshed tile keeps its decodes - // alive — the unbounded decoded-image growth the merge exists to bound. - // The stale reply is still ignored: the handler is gone from `pending`. + + // Already sent: stop tracking the reply, but keep the wire slot until + // the stale reply arrives, or cancellation churn would re-flood the + // socket. The promise is rejected, so a caller's `finally` (where + // renderMergedTile frees its decodes) still runs. const sent = this.pending.get(id); const had = this.pending.delete(id); + this._bgSent.delete(id); if (sent) { sent.reject(new Error('Request cancelled')); } @@ -479,6 +517,7 @@ export class WebSocketManager { const s = this.socket; if (!s || s.readyState !== WebSocket.OPEN) { this._bufStuckSince = 0; + this._saturatedSince = 0; this._lastBuffered = 0; return; } @@ -500,20 +539,29 @@ export class WebSocketManager { this._lastBuffered = buf; // Signature 2: saturated with work queued, yet silent for DEAD_MS. - if (!wedged - && this._inFlight >= this._maxInFlight - && this._queue.size > 0 - && this._lastRecvAt > 0 - && now - this._lastRecvAt > DEAD_MS) { + // Background work alone saturates at its share of the window. After a + // quiet spell the last reply is old, so the burst that ends it is timed + // from when it filled the window. + const saturated = (this._inFlight >= this._maxInFlight || this._bgFull()) + && this._queue.size + this._bgQueue.size > 0; + if (!saturated) { + this._saturatedSince = 0; + } else if (this._saturatedSince === 0) { + this._saturatedSince = now; + } + const silentFor = now - Math.max(this._lastRecvAt, this._saturatedSince); + if (!wedged && saturated && this._lastRecvAt > 0 && silentFor > DEAD_MS) { wedged = true; - why = `saturated (${this._inFlight} in flight, ${this._queue.size} ` - + `queued) but silent for ${Math.round(now - this._lastRecvAt)}ms`; + why = `saturated (${this._inFlight} in flight, ` + + `${this._queue.size + this._bgQueue.size} queued) but silent ` + + `for ${Math.round(silentFor)}ms`; } if (wedged) { console.warn(`WebSocket connection wedged — ${why}; ` + `reconnecting to recover`); this._bufStuckSince = 0; + this._saturatedSince = 0; // Don't depend on close()/onclose: a stuck send buffer can defer // the close handshake indefinitely. Reconnect immediately. this._forceReconnect(); @@ -530,10 +578,8 @@ export class WebSocketManager { const key = (msg.chiplet ? msg.chiplet + '|' : '') + msg.layer + '/' + msg.z + '/' + msg.x + '/' + msg.y; const b64 = this._cache.tiles && this._cache.tiles[key]; - if (b64) { - return Promise.resolve('data:image/png;base64,' + b64); - } - return Promise.reject(new Error('Tile not cached: ' + key)); + // The report saves only tiles with content: a missing one is empty. + return Promise.resolve(b64 ? 'data:image/png;base64,' + b64 : null); } // Timing highlight — drive the overlay image. diff --git a/openroad/web/src/websocket-tile-layer.js b/openroad/web/src/websocket-tile-layer.js deleted file mode 100644 index 6054ef95d9e..00000000000 --- a/openroad/web/src/websocket-tile-layer.js +++ /dev/null @@ -1,328 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// Copyright (c) 2026, The OpenROAD Authors - -// Leaflet tile layer that fetches tiles via WebSocket. - -import { - BLANK_TILE, buildTileRequestFor, floorClampZoom, nativeDpr, - releaseTileBlob, setTileSrc, tileSizeCss, tileSizeFields, - withDeviceExactTileSize, -} from './tile-request.js'; -import { tileMayHaveContent } from './layer-extents.js'; - -// Imported AND re-exported: `export { x } from '...'` alone re-exports without -// creating a local binding, so _clampZoom below would reference an undefined -// name at runtime while importers still resolved it fine. -export { floorClampZoom }; - -// The display's real device pixel ratio. Sizes are computed from this; -// the wire payload rounds it for its cache-key field (see tile-request.js). -export function currentDpr() { - return nativeDpr(); -} - -// Kept as a named export because main.js and the tests import it from here. -// Delegates so the per-layer and merged paths cannot drift on the wire format. -export function buildTileRequest(coords, layerName, ctx, row = {}) { - return buildTileRequestFor(coords, layerName, ctx, currentDpr(), - tileSizeCss(), row); -} - -// `app` (last arg) is read lazily on every request so that -// app.visibleChiplets, populated by display-controls.js after the tech -// metadata arrives, is reflected in tile requests without rebuilding -// the layer. When null or absent the field is omitted and the server -// renders every chiplet (default). -// Point an tile at a payload, or at the blank tile when the payload is -// null. -// -// Null is an empty tile (payload type 3): the server drew nothing there. The -// element keeps its place in the grid holding a 1x1 transparent GIF instead of -// a tile-sized transparent PNG, so the browser decodes 4 bytes and no bitmap -// worth the name counts against the budget tile-merge.js is bounding. See -// BLANK_TILE for why it is not simply left with no src. Reassigning matters on -// a refresh too -- a tile that had content before an edit removed it must drop -// the decode it is still holding. -function applyTilePayload(tile, data) { - if (data == null) { - setTileSrc(tile, BLANK_TILE); - return; - } - setTileSrc(tile, - (typeof data === 'string') ? data : URL.createObjectURL(data)); -} - -export function createWebSocketTileLayer(visibility, visibleLayers, - selectability, selectableLayers, - app) { - const ctx = { - visibility, selectability, visibleLayers, selectableLayers, app, - }; - return L.GridLayer.extend({ - // Force upscale-only display (see floorClampZoom) so the browser - // never downscales a band-limited tile back into a moiré beat. - _clampZoom: function(zoom) { - return L.GridLayer.prototype._clampZoom.call( - this, floorClampZoom(this, zoom)); - }, - - initialize: function(websocketManager, layerName, options) { - this._websocketManager = websocketManager; - this._layerName = layerName; - // The Display Controls row this pane draws (see buildTileRequestFor), - // shared with display-controls.js, which updates it in place. - this._row = (options && options.row) || {}; - L.GridLayer.prototype.initialize.call( - this, withDeviceExactTileSize(options)); - }, - - // A gated layer stays mounted and simply skips the request while it - // is off. `options.gate` is either one flag name or a `shown_by` list - // of flag groups, which shows when every flag of any one group is on - // -- the same rule the server applies (anyGroupOn). An unknown name - // would gate the layer off forever, so fail open and warn instead. - _gatedOff: function() { - const gate = this.options.gate; - if (gate == null) return false; - if (Array.isArray(gate)) { - return !gate.some( - (group) => group.every((key) => !!ctx.visibility[key])); - } - if (!(gate in ctx.visibility)) { - if (!this._gateWarned) { - this._gateWarned = true; - console.warn(`tile layer ${this._layerName}: unknown gate ` - + `'${gate}', rendering ungated`); - } - return false; - } - return !ctx.visibility[gate]; - }, - - // Ask the server for this tile and show whatever comes back. Shared by - // createTile and refreshTiles: the request, the id bookkeeping that lets - // it be cancelled, and the cache's data-URI-vs-blob answer are the same - // in both. - _requestTile: function(tile, coords) { - tile._websocketRequestId = this._websocketManager.nextId; - this._websocketManager.request( - buildTileRequest(coords, this._layerName, ctx, this._row) - ).then(data => { - applyTilePayload(tile, data); - }).catch(err => { - // Cancelled (by refreshTiles) or failed. `done` is never called - // and no retry is issued, so a tile that never loaded stays blank - // until Leaflet evicts it, and one that had an image keeps it. - }); - }, - - createTile: function(coords, done) { - const tile = document.createElement('img'); - tile.alt = ''; - tile.setAttribute('role', 'presentation'); - - // Set up onload/onerror BEFORE any src assignment so that - // refreshTiles() can set tile.src and still trigger done(). - tile._tileDone = false; - tile.onload = () => { - releaseTileBlob(tile); - if (!tile._tileDone) { - tile._tileDone = true; - done(null, tile); - } - }; - tile.onerror = () => { - if (!tile._tileDone) { - tile._tileDone = true; - done(new Error('tile image load error'), tile); - } - }; - - if (this._gatedOff()) { - setTileSrc(tile, BLANK_TILE); - return tile; - } - if (!tileMayHaveContent(ctx, this._layerName, coords, - this._row.chiplet)) { - applyTilePayload(tile, null); - return tile; - } - - // The request id stored by _requestTile is what lets _removeTile() - // cancel a tile discarded before it arrives (e.g. during zoom). - this._requestTile(tile, coords); - return tile; - }, - - // Re-request all existing tiles in place (no removal/flash). - // Use this instead of redraw() for visibility changes. - refreshTiles: function() { - if (!this._map) return; - - const gated = this._gatedOff(); - for (const key in this._tiles) { - const tileInfo = this._tiles[key]; - if (!tileInfo || !tileInfo.el) continue; - - const tile = tileInfo.el; - const coords = tileInfo.coords; - - // Cancel any pending request for this tile - if (tile._websocketRequestId !== undefined) { - this._websocketManager.cancel(tile._websocketRequestId); - tile._websocketRequestId = undefined; - } - - // Switched off: blank the tile in place rather than keep an - // overlay the user just turned off. Only if not already blank — - // redrawAllLayers walks every layer on any visibility change. - if (gated) { - if (tile.src !== BLANK_TILE) { - setTileSrc(tile, BLANK_TILE); - } - continue; - } - if (!tileMayHaveContent(ctx, this._layerName, coords, - this._row.chiplet)) { - applyTilePayload(tile, null); - continue; - } - - this._requestTile(tile, coords); - } - }, - - _removeTile: function(key) { - const tile = this._tiles[key]; - if (tile && tile.el) { - if (tile.el._websocketRequestId !== undefined) { - this._websocketManager.cancel(tile.el._websocketRequestId); - } - releaseTileBlob(tile.el); - } - L.GridLayer.prototype._removeTile.call(this, key); - } - }); -} - -// Lightweight tile layer that renders only highlight/overlay shapes -// (selection, hover, timing, DRC, route guides) on a transparent -// background. Separated from the base tile layers so that highlight -// changes don't trigger a full re-render of all geometry tiles. -export function createOverlayTileLayer(visibility, app) { - function buildOverlayRequest(coords, tileSize) { - const req = { - type: 'overlay_tile', - z: coords.z, - x: coords.x, - y: coords.y, - // Sized like the layer tiles it is drawn over: a highlight - // rendered at a different pixel count is rescaled by the browser - // and no longer sits exactly on the shape it highlights. - ...tileSizeFields(currentDpr(), tileSize), - debug_renderers: !!visibility.debug_renderers, - // The overlay tile carries the layer-independent - // Renderer::drawObjects pass, so it needs the same pause/live gate - // the layer tiles get through TileVisibility. - debug_live: !!visibility.debug_live, - flywires_only: !!visibility.flywires_only, - // Options > "Show polygon decomposition" (2.15). Not a display - // control: the server owns the value and hands it to every client, - // and echoing it back is how a session learns its highlight shapes - // were derived under the previous setting. - poly_decomp: !!(app && app.polyDecomp), - focused_nets_guides: !!visibility.focused_nets_guides, - highlight_selected: visibility.highlight_selected !== false, - // User labels (2.12) are server-drawn; honor the "Labels" toggle. - draw_labels: visibility.labels !== false, - }; - // Pass visible layers so route guides respect layer visibility. - if (app && app.visibleLayerNames) { - req.visible_layers = [...app.visibleLayerNames]; - } - return req; - } - return L.GridLayer.extend({ - initialize: function(websocketManager, options) { - this._websocketManager = websocketManager; - L.GridLayer.prototype.initialize.call( - this, withDeviceExactTileSize(options)); - }, - - createTile: function(coords, done) { - const tile = document.createElement('img'); - tile.alt = ''; - tile.setAttribute('role', 'presentation'); - - tile._tileDone = false; - tile.onload = () => { - releaseTileBlob(tile); - if (!tile._tileDone) { - tile._tileDone = true; - done(null, tile); - } - }; - tile.onerror = () => { - if (!tile._tileDone) { - tile._tileDone = true; - done(new Error('overlay tile load error'), tile); - } - }; - - const requestId = this._websocketManager.nextId; - tile._websocketRequestId = requestId; - - this._websocketManager.request( - buildOverlayRequest(coords, this.getTileSize().x) - ).then(data => { - if (tile._websocketRequestId !== requestId) { - return; // stale response; a newer request superseded this one - } - applyTilePayload(tile, data); - }).catch(err => { - }); - - return tile; - }, - - refreshTiles: function() { - if (!this._map) return; - - for (const key in this._tiles) { - const tileInfo = this._tiles[key]; - if (!tileInfo || !tileInfo.el) continue; - - const tile = tileInfo.el; - const coords = tileInfo.coords; - - if (tile._websocketRequestId !== undefined) { - this._websocketManager.cancel(tile._websocketRequestId); - } - - const requestId = this._websocketManager.nextId; - tile._websocketRequestId = requestId; - - this._websocketManager.request( - buildOverlayRequest(coords, this.getTileSize().x) - ).then(data => { - if (tile._websocketRequestId !== requestId) { - return; // stale response superseded by a newer refresh - } - applyTilePayload(tile, data); - }).catch(() => {}); - } - }, - - _removeTile: function(key) { - const tile = this._tiles[key]; - if (tile && tile.el) { - if (tile.el._websocketRequestId !== undefined) { - this._websocketManager.cancel(tile.el._websocketRequestId); - tile.el._websocketRequestId = undefined; - } - releaseTileBlob(tile.el); - } - L.GridLayer.prototype._removeTile.call(this, key); - } - }); -} diff --git a/openroad/web/src/zoom-swap.js b/openroad/web/src/zoom-swap.js new file mode 100644 index 00000000000..c659980a2c2 --- /dev/null +++ b/openroad/web/src/zoom-swap.js @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, The OpenROAD Authors + +// Which tile levels the layout view draws while the zoom changes. +// +// Shared by every tile slot so they all change level together. With double +// buffering the new level stays hidden, under the old one scaled, until every +// slot has loaded what is on screen; it is then shown in one frame, fading in +// over the old level when smoothing is on. Without it the new level paints +// tile by tile over the old one, which stays underneath until the new level +// has settled. + +import { prefersReducedMotion } from './ui-utils.js'; +import { easeOutQuad } from './view-math.js'; + +const ATOMIC_ZOOM_TIMEOUT_MS = 10000; +export const ZOOM_FADE_MS = 150; +const kMaxUnder = 3; // levels kept under a loading one + +export class ZoomSwap { + constructor({ + isEnabled = () => true, + isSmooth = () => false, + reducedMotion = prefersReducedMotion, + now = () => performance.now(), + setTimer = (fn, ms) => setTimeout(fn, ms), + clearTimer = (id) => clearTimeout(id), + timeoutMs = ATOMIC_ZOOM_TIMEOUT_MS, + onChange = () => {}, + } = {}) { + Object.assign(this, { isEnabled, isSmooth, reducedMotion, now, setTimer, + clearTimer, timeoutMs, onChange }); + this.shownZ = null; // level drawn as complete + this.pendingZ = null; // level loading behind it (double buffering) + this.under = []; // old levels kept under a progressive one + this.fade = null; // { fromZ, toZ, start } + this._timer = null; + } + + // The level the slots should be loading. + wantedZ() { + return this.pendingZ !== null ? this.pendingZ : this.shownZ; + } + + // The view moved to tile level z. `hasContent` says whether the level on + // screen still has tiles to keep showing. + setZoom(z, { hasContent = true } = {}) { + if (z === this.wantedZ()) { + return; + } + this.endFade(); + this._clearTimer(); + if (this.shownZ === null) { + this.shownZ = z; + this.pendingZ = null; + this.under = []; + } else if (!hasContent) { + // Nothing of the shown level to keep; what lies under it stays. + this.shownZ = z; + this.pendingZ = null; + this.under = this.under.filter((u) => u !== z); + } else if (z === this.shownZ) { + this.pendingZ = null; // zoomed back before the swap + } else if (this.isEnabled()) { + this.pendingZ = z; + this.under = this.under.filter((u) => u !== z); + this._timer = this.setTimer(() => this.reveal({ settled: false }), + this.timeoutMs); + } else { + // A level still loading covers only part of the view, so the + // ones under it stay too, as many as kMaxUnder. + this.under = [...this.under.filter((u) => u !== z), this.shownZ] + .slice(-kMaxUnder); + this.shownZ = z; + this.pendingZ = null; + } + this.onChange(); + } + + // Called whenever loading progresses. Returns true when it changed what + // is drawn. `animating` holds the reveal until the zoom animation ends. + check({ settled, animating = false }) { + if (this.pendingZ !== null) { + if (animating || (!settled && this.isEnabled())) { + return false; + } + this.reveal({ settled }); + return true; + } + if (this.under.length > 0 && settled && !animating) { + this.under = []; + this.onChange(); + return true; + } + return false; + } + + // Shown before it is complete, the new level keeps the old ones under it + // until check() sees it settled. + reveal({ settled = true } = {}) { + if (this.pendingZ === null) { + return; + } + this._clearTimer(); + const from = this.shownZ; + this.shownZ = this.pendingZ; + this.pendingZ = null; + if (settled) { + this.under = []; + } else if (from !== null) { + this.under = [...this.under.filter( + (u) => u !== from && u !== this.shownZ), from].slice(-kMaxUnder); + } + const fades = this.isSmooth() && !this.reducedMotion(); + this.fade = (fades && from !== null) + ? { fromZ: from, toZ: this.shownZ, start: this.now() } + : null; + this.onChange(); + } + + endFade() { + if (this.fade) { + this.fade = null; + this.onChange(); + } + } + + // What to draw now, bottom first. + plan(now = this.now()) { + if (this.fade) { + const t = (now - this.fade.start) / ZOOM_FADE_MS; + if (t < 1) { + return { + draw: [{ z: this.fade.fromZ, opacity: 1 }, + { z: this.fade.toZ, opacity: easeOutQuad(Math.max(0, t)) }], + fading: true, + }; + } + this.fade = null; + } + if (this.shownZ === null) { + return { draw: [], fading: false }; + } + if (this.under.length > 0) { + return { draw: [...this.under, this.shownZ].map( + (z) => ({ z, opacity: 1 })), + fading: false }; + } + return { draw: [{ z: this.shownZ, opacity: 1 }], fading: false }; + } + + // Nothing is waiting to be shown or fading in. + isIdle() { + return this.pendingZ === null && this.under.length === 0 + && !this.plan(this.now()).fading; + } + + _clearTimer() { + if (this._timer !== null) { + this.clearTimer(this._timer); + this._timer = null; + } + } +} diff --git a/openroad/web/test/BUILD b/openroad/web/test/BUILD index 0fbfc959424..fedf558c464 100644 --- a/openroad/web/test/BUILD +++ b/openroad/web/test/BUILD @@ -74,18 +74,56 @@ py_test( ], ) +# A real Chrome draws a tile in the live viewer and in a saved report. Manual: +# Chrome is not part of the build; pass it with --test_env=CHROME=. +py_test( + name = "browser_smoke_test", + size = "medium", + srcs = ["browser_smoke_test.py"], + args = [ + "$(rootpath //:openroad)", + "$(rootpath Nangate45/Nangate45_typ.lib)", + "$(rootpath Nangate45/Nangate45.lef)", + "$(rootpath gcd_nangate45.def)", + ], + data = [ + "Nangate45/Nangate45.lef", + "Nangate45/Nangate45_typ.lib", + "gcd_nangate45.def", + "//:openroad", + ], + tags = [ + "local", + "manual", + ], +) + +# Tests that drive a module against a stand-in for layout-view.js. +VIEW_TEST_DATA = DOM_TEST_DATA + ["js/fake-view.js"] + test_suite( name = "cpp_tests", tests = [ ":browser_launcher_test", + ":charts_test", + ":clock_tree_report_test", + ":debug_graphics_test", ":gif_test", + ":glyph_cache_test", ":heat_map_test", + ":hierarchy_report_test", ":interconnect3d_test", + ":labels_test", ":request_handler_test", ":save_display_controls_test", + ":save_image_test", + ":save_report_test", ":script_view_test", ":session_lifetime_test", + ":snap_test", ":tile_generator_test", + ":timing_cone_test", + ":timing_report_test", ":web_assets_test", ], ) @@ -97,6 +135,13 @@ js_test( no_copy_to_bin = JS_FILES, ) +js_test( + name = "ui_utils_test", + data = DOM_TEST_DATA, + entry_point = "js/test-ui-utils.js", + no_copy_to_bin = JS_FILES, +) + js_test( name = "table_columns_test", data = DOM_TEST_DATA, @@ -118,6 +163,13 @@ js_test( no_copy_to_bin = JS_FILES, ) +js_test( + name = "esbuild_config_test", + data = ["//openroad/web:esbuild.config.mjs"], + entry_point = "js/test-esbuild-config.js", + no_copy_to_bin = ["//openroad/web:esbuild.config.mjs"], +) + js_test( name = "schematic_pins_test", data = [ @@ -155,7 +207,7 @@ js_test( js_test( name = "context_menu_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-context-menu.js", no_copy_to_bin = JS_FILES, ) @@ -169,7 +221,7 @@ js_test( js_test( name = "capture_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-capture.js", no_copy_to_bin = JS_FILES, ) @@ -188,13 +240,6 @@ js_test( no_copy_to_bin = JS_FILES, ) -js_test( - name = "websocket_tile_layer_test", - data = DOM_TEST_DATA, - entry_point = "js/test-websocket-tile-layer.js", - no_copy_to_bin = JS_FILES, -) - js_test( name = "color_tree_test", data = JS_FILES, @@ -211,7 +256,7 @@ js_test( js_test( name = "display_controls_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-display-controls.js", no_copy_to_bin = JS_FILES, ) @@ -230,13 +275,6 @@ js_test( no_copy_to_bin = JS_FILES, ) -js_test( - name = "ui_utils_test", - data = JS_FILES, - entry_point = "js/test-ui-utils.js", - no_copy_to_bin = JS_FILES, -) - js_test( name = "clock_tree_widget_test", data = JS_FILES, @@ -267,21 +305,21 @@ js_test( js_test( name = "inspector_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-inspector.js", no_copy_to_bin = JS_FILES, ) js_test( name = "ruler_test", - data = JS_FILES, + data = VIEW_TEST_DATA, entry_point = "js/test-ruler.js", no_copy_to_bin = JS_FILES, ) js_test( name = "label_manager_test", - data = JS_FILES, + data = VIEW_TEST_DATA, entry_point = "js/test-label-manager.js", no_copy_to_bin = JS_FILES, ) @@ -295,21 +333,21 @@ js_test( js_test( name = "drc_widget_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-drc-widget.js", no_copy_to_bin = JS_FILES, ) js_test( name = "selection_browser_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-selection-browser.js", no_copy_to_bin = JS_FILES, ) js_test( name = "menu_bar_test", - data = DOM_TEST_DATA, + data = VIEW_TEST_DATA, entry_point = "js/test-menu-bar.js", no_copy_to_bin = JS_FILES, ) @@ -350,9 +388,51 @@ js_test( ) js_test( - name = "merged_tile_layer_test", + name = "view_math_test", + data = JS_FILES, + entry_point = "js/test-view-math.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "zoom_swap_test", + data = JS_FILES, + entry_point = "js/test-zoom-swap.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "tile_grid_test", + data = JS_FILES, + entry_point = "js/test-tile-grid.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "tile_sources_test", + data = JS_FILES, + entry_point = "js/test-tile-sources.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "view_input_test", + data = DOM_TEST_DATA, + entry_point = "js/test-view-input.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "layout_view_test", + data = DOM_TEST_DATA + ["js/fake-deck.js"], + entry_point = "js/test-layout-view.js", + no_copy_to_bin = JS_FILES, +) + +js_test( + name = "imports_without_globals_test", data = DOM_TEST_DATA, - entry_point = "js/test-merged-tile-layer.js", + entry_point = "js/test-imports-without-globals.js", no_copy_to_bin = JS_FILES, ) @@ -377,13 +457,6 @@ js_test( no_copy_to_bin = JS_FILES, ) -js_test( - name = "device_pixels_test", - data = JS_FILES, - entry_point = "js/test-device-pixels.js", - no_copy_to_bin = JS_FILES, -) - js_test( name = "theme_test", data = DOM_TEST_DATA, diff --git a/openroad/web/test/browser_smoke_test.py b/openroad/web/test/browser_smoke_test.py new file mode 100644 index 00000000000..0302c0e9fee --- /dev/null +++ b/openroad/web/test/browser_smoke_test.py @@ -0,0 +1,277 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, The OpenROAD Authors +# +# The layout view drawn by a real browser: the live viewer and a saved report +# opened from disk with the network off each show a tile. The unit tests run +# the view against a stand-in for deck.gl, so only this catches a bundle that +# loads but draws nothing. +# +# Needs Chrome with WebGL 2 (SwiftShader is enough), named by CHROME or found +# on PATH. Tagged manual: CI runs it from +# .github/workflows/github-actions-web-browser-smoke.yml. +# +# usage: browser_smoke_test.py OPENROAD LIBERTY LEF DEF + +import fcntl +import json +import os +import pathlib +import select +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import unittest + +_OPENROAD, _LIBERTY, _LEF, _DEF = (None,) * 4 +# Headless: nothing of the desktop session reaches Chrome. +_DESKTOP_VARS = ("DISPLAY", "WAYLAND_DISPLAY", "DBUS_SESSION_BUS_ADDRESS") + +# Pixels of the layout that differ from the view's background, once its tiles +# have settled, and the tiles each slot holds. +_DRAWN = """(async () => { + const v = window.__orView; + if (!v) { + return null; + } + await v.whenTilesSettled(); + const shot = await v.captureCanvas(); + if (!shot) { + return null; + } + const c = document.createElement('canvas'); + c.width = shot.image.width; + c.height = shot.image.height; + const g = c.getContext('2d'); + g.drawImage(shot.image, 0, 0); + const d = g.getImageData(0, 0, c.width, c.height).data; + const bg = getComputedStyle(v.getContainer()).backgroundColor + .match(/[\\d.]+/g).map(Number); + let drawn = 0; + for (let i = 0; i < d.length; i += 4) { + const diff = Math.abs(d[i] - bg[0]) + Math.abs(d[i + 1] - bg[1]) + + Math.abs(d[i + 2] - bg[2]); + if (d[i + 3] > 0 && diff > 24) { + drawn++; + } + } + return { drawn, tiles: v.debugSnapshot().slots.map((s) => s.drawable) }; +})()""" + + +def _chrome(): + path = os.environ.get("CHROME") or next( + filter(None, map(shutil.which, ["google-chrome", "chromium", "chrome"])), + None, + ) + if not path: + raise RuntimeError("no Chrome: set CHROME") + return path + + +class _Browser: + """Chrome driven over the DevTools protocol on a pipe (fds 3 and 4).""" + + def __init__(self, profile): + to_chrome_r, self._to_chrome = os.pipe() + self._from_chrome, from_chrome_w = os.pipe() + + def pipes(): + # Above 4 first: dup2 onto its own number keeps O_CLOEXEC, and one + # end may already sit on 3 or 4. + ends = [ + fcntl.fcntl(fd, fcntl.F_DUPFD, 5) for fd in (to_chrome_r, from_chrome_w) + ] + for target, fd in zip((3, 4), ends): + os.dup2(fd, target) + os.close(fd) + + flags = [ + "--headless=new", + "--remote-debugging-pipe", + f"--user-data-dir={profile}", + "--no-first-run", + "--no-default-browser-check", + "--disable-background-networking", + "--disable-component-update", + "--disable-extensions", + # WebGL 2 without a GPU. + "--use-angle=swiftshader", + "--enable-unsafe-swiftshader", + "--ignore-gpu-blocklist", + "--window-size=1280,800", + ] + if os.geteuid() == 0: + flags.append("--no-sandbox") + env = {k: v for k, v in os.environ.items() if k not in _DESKTOP_VARS} + env["HOME"] = profile + self._proc = subprocess.Popen( + [_chrome(), *flags, "about:blank"], + preexec_fn=pipes, + close_fds=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + os.close(to_chrome_r) + os.close(from_chrome_w) + self._buf = b"" + self._id = 0 + self.events = [] + target = self.send("Target.createTarget", url="about:blank")["targetId"] + self.session = self.send( + "Target.attachToTarget", targetId=target, flatten=True + )["sessionId"] + + def close(self): + # A clean exit takes the child processes and Chrome's own temp files + # with it; a killed Chrome leaves both behind. + try: + self.send("Browser.close", timeout=10) + except (OSError, RuntimeError, TimeoutError): + pass + try: + self._proc.wait(timeout=10) + except subprocess.TimeoutExpired: + self._proc.kill() + self._proc.wait() + os.close(self._to_chrome) + os.close(self._from_chrome) + + def _read(self, timeout): + while b"\0" not in self._buf: + ready, _, _ = select.select([self._from_chrome], [], [], max(0, timeout)) + if not ready: + raise TimeoutError("no reply from Chrome") + chunk = os.read(self._from_chrome, 1 << 16) + if not chunk: + raise RuntimeError("Chrome exited") + self._buf += chunk + msg, self._buf = self._buf.split(b"\0", 1) + return json.loads(msg) + + def send(self, method, session=None, timeout=60, **params): + self._id += 1 + msg = {"id": self._id, "method": method, "params": params} + if session: + msg["sessionId"] = session + os.write(self._to_chrome, json.dumps(msg).encode() + b"\0") + deadline = time.monotonic() + timeout + while True: + reply = self._read(deadline - time.monotonic()) + if reply.get("id") == self._id: + if "error" in reply: + raise RuntimeError(f"{method}: {reply['error']}") + return reply.get("result", {}) + self.events.append(reply) + + def page(self, method, **params): + return self.send(method, session=self.session, **params) + + def evaluate(self, expression, timeout=60): + result = self.send( + "Runtime.evaluate", + session=self.session, + timeout=timeout, + expression=expression, + awaitPromise=True, + returnByValue=True, + ) + if "exceptionDetails" in result: + raise RuntimeError(result["exceptionDetails"]) + return result["result"].get("value") + + def event_params(self, method): + return [e["params"] for e in self.events if e.get("method") == method] + + +def _load_design(tcl, then): + tcl.write_text( + f"read_liberty {_LIBERTY}\nread_lef {_LEF}\nread_def {_DEF}\n{then}\n" + ) + + +def _free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class LayoutViewDraws(unittest.TestCase): + def setUp(self): + self.tmp = pathlib.Path(tempfile.mkdtemp(dir=os.environ.get("TEST_TMPDIR"))) + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + self.browser = _Browser(str(self.tmp / "profile")) + self.addCleanup(self.browser.close) + self.browser.page("Runtime.enable") + self.browser.page("Network.enable") + has_webgl2 = self.browser.evaluate( + "!!document.createElement('canvas').getContext('webgl2')" + ) + self.assertTrue(has_webgl2, "this Chrome has no WebGL 2") + + def assertDrawsATile(self, url): + self.browser.page("Page.navigate", url=url) + drawn = None + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + drawn = self.browser.evaluate(_DRAWN) + if drawn and drawn["drawn"] > 0 and any(drawn["tiles"]): + break + time.sleep(1) + self.assertTrue(drawn and drawn["drawn"] > 0, f"nothing drawn: {drawn}") + self.assertTrue(any(drawn["tiles"]), f"no tile: {drawn}") + errors = self.browser.event_params("Runtime.exceptionThrown") + self.assertEqual(errors, []) + + def test_live_viewer(self): + port = _free_port() + token = os.urandom(16).hex() + tcl = self.tmp / "serve.tcl" + _load_design(tcl, f"web_server -port {port} -token {token} -no_browser") + log = self.tmp / "server.log" + with open(log, "w") as out: + server = subprocess.Popen( + [_OPENROAD, "-no_init", str(tcl)], + stdin=subprocess.PIPE, + stdout=out, + stderr=subprocess.STDOUT, + ) + self.addCleanup(server.stdin.close) + self.addCleanup(server.wait) + self.addCleanup(server.kill) + deadline = time.monotonic() + 120 + while "WEB-0001" not in log.read_text(): + self.assertIsNone(server.poll(), log.read_text()) + self.assertLess(time.monotonic(), deadline, log.read_text()) + time.sleep(0.2) + self.assertDrawsATile(f"http://127.0.0.1:{port}/?token={token}") + + def test_saved_report_offline(self): + report = self.tmp / "report.html" + tcl = self.tmp / "report.tcl" + _load_design(tcl, f"web_save_report {report}") + subprocess.run( + [_OPENROAD, "-no_init", "-exit", str(tcl)], check=True, timeout=300 + ) + self.browser.page( + "Network.emulateNetworkConditions", + offline=True, + latency=0, + downloadThroughput=-1, + uploadThroughput=-1, + ) + self.assertDrawsATile(report.as_uri()) + remote = [ + r["request"]["url"] + for r in self.browser.event_params("Network.requestWillBeSent") + if not r["request"]["url"].startswith(("file:", "data:", "blob:")) + ] + self.assertEqual(remote, []) + + +if __name__ == "__main__": + _OPENROAD, _LIBERTY, _LEF, _DEF = (os.path.abspath(a) for a in sys.argv[1:5]) + unittest.main(argv=sys.argv[:1]) diff --git a/openroad/web/test/bundle_test.py b/openroad/web/test/bundle_test.py index 80705a76d8f..ac57a9c9e7c 100644 --- a/openroad/web/test/bundle_test.py +++ b/openroad/web/test/bundle_test.py @@ -36,10 +36,12 @@ "https://lodash.com/license", "https://openjsf.org/", "https://npms.io/search?q=ponyfill", - "https://leafletjs.com", "https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733", # The namespace netlistsvg stamps into the SVG it produces. "https://github.com/nturley/netlistsvg", + # The bare schemes loaders.gl tests a path against. + "http://", + "https://", } _URL = r"[^\"'`) >,;\n]*" @@ -83,10 +85,10 @@ def test_finds_absolute_urls_in_any_case(self): self.assertEqual(external_urls('xmlns="http://www.w3.org/2000/svg"'), []) def test_allows_only_a_whole_identifier(self): - self.assertTrue(_is_identifier_url("https://leafletjs.com")) + self.assertTrue(_is_identifier_url("https://openjsf.org/")) self.assertTrue(_is_identifier_url("http://www.w3.org/2000/svg#x")) - self.assertFalse(_is_identifier_url("https://leafletjs.com/l.js")) - self.assertFalse(_is_identifier_url("https://leafletjs.com.example/l.js")) + self.assertFalse(_is_identifier_url("https://openjsf.org/l.js")) + self.assertFalse(_is_identifier_url("https://openjsf.org.example/l.js")) self.assertFalse(_is_identifier_url("https://lodash.com/lodash.js")) def test_finds_scheme_relative_fetches(self): @@ -139,10 +141,11 @@ def test_ships_the_bundled_licences(self): text = _read(_LICENSES) # netlistsvg's dependencies too: the bundle carries their code. for package in ( + "@deck.gl/core", + "@luma.gl/webgl", "clone", "elkjs", "golden-layout", - "leaflet", "lodash", "netlistsvg", "onml", @@ -153,6 +156,10 @@ def test_ships_the_bundled_licences(self): # EPL-1.0 asks where elkjs's source can be obtained; every entry says. self.assertEqual(text.count("\nSource: https://"), text.count("=" * 78) // 2) self.assertIn("\nSource: https://github.com/OpenKieler/elkjs\n", text) + # gl-matrix ships its license as LICENSE.md, which rules_js strips + # unless MODULE.bazel keeps it. + body = text.split("\ngl-matrix ", 1)[1].split("=" * 78)[1] + self.assertIn("Permission is hereby granted", body) class Entries(unittest.TestCase): diff --git a/openroad/web/test/cpp/TestRequestHandler.cpp b/openroad/web/test/cpp/TestRequestHandler.cpp index 7cb84933001..4b3523cc43f 100644 --- a/openroad/web/test/cpp/TestRequestHandler.cpp +++ b/openroad/web/test/cpp/TestRequestHandler.cpp @@ -707,6 +707,18 @@ TEST_F(TileHandlerTest, TechIncludesHighlightPalette) EXPECT_EQ(first[3].as_int64(), 100); } +// A new session's ensureInit(true) empties the tile cache; a non-session +// ensureInit() keeps it. +TEST_F(TileHandlerTest, OnlyANewSessionEmptiesTheTileCache) +{ + gen_->ensureInit(); + ASSERT_EQ(cachedAfterTile(R"({"layer":"metal1","z":0,"x":0,"y":0})"), 1u); + gen_->ensureInit(); + EXPECT_EQ(gen_->tileCacheSize(), 1u); + gen_->ensureInit(/*fresh_cache=*/true); + EXPECT_EQ(gen_->tileCacheSize(), 0u); +} + // PNG dimensions live in the IHDR chunk: 8-byte signature, 4-byte length, // 4-byte type, then width and height as big-endian uint32. Read directly so // this test needs no PNG decoder dependency. @@ -721,17 +733,8 @@ static uint32_t pngWidth(const std::vector& png) | static_cast(png[19]); } -// The device pixel ratio comes from the client — only the browser can know the -// display's ratio — and the server honours it rather than snapping it to a -// fixed ladder. A snapped ratio renders a tile of the wrong size that the -// browser then rescales, which is the moiré beat the tile pipeline exists to -// avoid, and 1.75 and 2.5 are ordinary Windows scale factors. -// -// The client mirrors this in quantizeDpr() in tile-request.js and sizes its -// merged canvas from its own copy, so a divergence here resamples every tile. // The viewer's options are query parameters, so the asset lookup must never -// see them. Without this the whole page 404s with "Resource not found." the -// moment any option is used -- which is how ?mergetiles=0 shipped unusable. +// see them; without this the page 404s with "Resource not found.". TEST(AssetPathFromTarget, StripsTheQueryString) { EXPECT_EQ(assetPathFromTarget("/?mergetiles=0"), "/index.html"); @@ -907,7 +910,7 @@ TEST_F(TileHandlerTest, DrawnTileIsStillAPngResponse) EXPECT_FALSE(resp.payload.empty()); } -// The highlight overlay is one of the panes that never merges, and it holds +// The highlight overlay is a slot of its own that never merges, and it holds // nothing at all until something is selected -- so it is the single tile layer // most worth not sending an image for. TEST_F(TileHandlerTest, OverlayTileWithNothingSelectedIsEmpty) @@ -1539,8 +1542,8 @@ TEST(AuthRedirectTarget, SwapsTheTicketForTheToken) TEST(AuthRedirectTarget, KeepsTheViewerOptionsAroundIt) { - // ?mergetiles=0 and friends are how the viewer is A/B tested; losing them - // in the redirect would silently ignore what the user asked for. + // The viewer's query options (e.g. ?preservebuffer=1); losing them in the + // redirect would silently ignore what the user asked for. EXPECT_EQ(authRedirectTarget("/?ticket=abc&mergetiles=0", "tok"), "/?token=tok&mergetiles=0"); EXPECT_EQ( @@ -1646,6 +1649,8 @@ TEST(UrlDecode, ASignIsNotAHexDigit) EXPECT_EQ(urlDecode("%-1x"), "%-1x"); } +// The server keeps the client's dpr rather than snapping it to a ladder the +// browser would rescale; quantizeDpr() in tile-request.js mirrors the rounding. TEST_F(TileHandlerTest, HonoursTheClientReportedDpr) { struct Case @@ -1839,6 +1844,56 @@ TEST_F(TileHandlerTest, ScopedTileCacheIgnoresOtherChiplets) << "the die's own visibility must stay in its key"; } +// Like visible_layers, the per-die exceptions key only the tiles that read +// them. +TEST_F(TileHandlerTest, HiddenLayersPerDieKeyOnlyTheTilesThatReadThem) +{ + const auto cached_after = [&](const std::string& layer, + const std::string& hidden) { + return cachedAfterTile( + R"({"layer":")" + layer + R"(","z":0,"x":0,"y":0,"visible_layers":)" + + R"(["metal1"],"chiplet_hidden_layers":)" + hidden + "}"); + }; + const std::string die0 = R"({"top/die0":["metal1"]})"; + const size_t after_metal1 = cached_after("metal1", "{}"); + EXPECT_EQ(cached_after("metal1", die0), after_metal1); + const size_t after_pins = cached_after("_pins", "{}"); + EXPECT_EQ(cached_after("_pins", die0), after_pins + 1); +} + +TEST_F(TileHandlerTest, AnEditOnAnUnbuiltIndexStillMissesTheCache) +{ + // No row index is built yet, so this edit clears no cache; the revision in + // the key is what keeps the old tile from being served. + const std::string metal1 = R"({"layer":"metal1","z":0,"x":0,"y":0})"; + const size_t first = cachedAfterTile(metal1); + odb::dbSite* site = lib_->findSite("FreePDK45_38x28_10R_NP_162NW_34O"); + ASSERT_NE(site, nullptr); + odb::dbRow::create(block_, + "row0", + site, + 0, + 0, + odb::dbOrientType::R0, + odb::dbRowDir::HORIZONTAL, + 20, + site->getWidth()); + EXPECT_EQ(cachedAfterTile(metal1), first + 1); +} + +TEST_F(TileHandlerTest, AMovedChipletMissesTheCache) +{ + odb::dbChip* root = odb::dbChip::create( + getDb(), nullptr, "root", odb::dbChip::ChipType::HIER); + getDb()->setTopChip(root); + odb::dbChipInst* die = odb::dbChipInst::create(root, chip_, "die0"); + const std::string metal1 = R"({"layer":"metal1","z":0,"x":0,"y":0})"; + const size_t first = cachedAfterTile(metal1); + // No ODB hook reports this. + die->setOrient(odb::dbOrientType3D("MZ")); + EXPECT_EQ(cachedAfterTile(metal1), first + 1); +} + TEST_F(TileHandlerTest, TileReturnsPng) { // _instances rather than a tech layer: the die outline puts content on it, so @@ -2667,7 +2722,7 @@ TEST_F(TileHandlerTest, TileRejectsNonIntegerZoomInsteadOfThrowing) } } -// Leaflet asks for tiles beyond the 2^z grid whenever the design is smaller +// A client may ask for tiles beyond the 2^z grid when the design is smaller // than the viewport or while panning at the border, and the renderers answer // those with a transparent tile. A range check here would turn ordinary // panning into a stream of errors, so off-grid coordinates must still render. @@ -3523,9 +3578,9 @@ TEST_F(SelectHandlerTest, SelectAtEmptyAreaReturnsEmptyList) EXPECT_NE(json.find("\"selected\":[]"), std::string::npos); } -// Leaflet's zoomSnap=0 lets the client send fractional zoom values; the -// handler must accept them without erroring out. Regression test for the -// click-to-select breakage after strict-typing the request fields. +// A client may send fractional zoom values; the handler must accept them +// without erroring out. Regression test for the click-to-select breakage +// after strict-typing the request fields. TEST_F(SelectHandlerTest, SelectAcceptsFractionalZoom) { WebSocketRequest req; @@ -6673,12 +6728,12 @@ TEST_F(TimingHighlightHandlerTest, HistogramWindowHighlightsTheReportedPath) std::vector expected_rects; std::vector expected_lines; collectTimingPathShapes( - gen_->chiplets(), filtered.front(), expected_rects, expected_lines); + *gen_->chiplets(), filtered.front(), expected_rects, expected_lines); ASSERT_FALSE(expected_lines.empty()); if (stage) { req.json["pin_name"] = filtered.front().end_pin; const size_t path_lines = expected_lines.size(); - collectTimingStageShapes(gen_->chiplets(), + collectTimingStageShapes(*gen_->chiplets(), filtered.front(), filtered.front().end_pin, kTimingStageColor, @@ -6717,7 +6772,7 @@ TEST_F(TimingHighlightHandlerTest, PinsSelectThePathWhenTheIndexIsStale) std::vector expected_rects; std::vector expected_lines; collectTimingPathShapes( - gen_->chiplets(), paths[1], expected_rects, expected_lines); + *gen_->chiplets(), paths[1], expected_rects, expected_lines); ASSERT_FALSE(expected_lines.empty()); // Index 0 is a different path in this report; the pins must win. @@ -6748,7 +6803,7 @@ TEST_F(TimingHighlightHandlerTest, ClocksMustMatchAsWellAsPins) std::vector expected_rects; std::vector expected_lines; collectTimingPathShapes( - gen_->chiplets(), paths[1], expected_rects, expected_lines); + *gen_->chiplets(), paths[1], expected_rects, expected_lines); ASSERT_FALSE(expected_lines.empty()); WebSocketRequest req; @@ -6940,7 +6995,8 @@ TEST_F(ChipletSchematicHandlerTest, ConeResolvesTheQualifiedInstance) // from the root, which is what the schematic then requests. TEST_F(ChipletSchematicHandlerTest, ConeResolvesTheLayoutsFullPathName) { - const std::vector& chiplets = gen_->chiplets(); + const auto chiplet_list = gen_->chiplets(); + const std::vector& chiplets = *chiplet_list; const auto die1 = std::ranges::find_if( chiplets, [](const ChipletNode& node) { return node.name == "die1"; }); ASSERT_NE(die1, chiplets.end()); @@ -7414,6 +7470,7 @@ TEST_F(TileHandlerTest, CancelSkipsQueuedTileRender) = parseObj(R"({"layer":"metal1","z":0,"x":0,"y":0,"visible_layers":[]})"); auto resp = handler_->handleTile(tile, state_); EXPECT_EQ(resp.type, WebSocketResponse::kError); + EXPECT_EQ(payloadStr(resp), kCancelledMsg); // The cancellation is consumed: re-issuing the same id now renders. metal1 // holds nothing in this fixture, so a completed render is an empty tile -- diff --git a/openroad/web/test/cpp/TestSaveImage.cpp b/openroad/web/test/cpp/TestSaveImage.cpp index ead0fe08149..f79641446e8 100644 --- a/openroad/web/test/cpp/TestSaveImage.cpp +++ b/openroad/web/test/cpp/TestSaveImage.cpp @@ -852,16 +852,16 @@ std::vector namesOf(const std::vector& order) return names; } -// saveImage must composite in the same z order Leaflet stacks the layers in on -// screen (display-controls.js addPseudoLayer), otherwise the saved PNG is not -// the view the user was looking at. Before the fix every pseudo layer was +// saveImage must composite in the same z order the view stacks the layers in +// on screen (the draw lists in display-controls.js), otherwise the saved PNG is +// not the view the user was looking at. Before the fix every pseudo layer was // appended after the tech layers, which put the manufacturing grid over the // routing and the pin markers over the tech layers (PR #10806 review). // // Asserted on the layer list rather than on pixels: every layer here is // semi-transparent, so a dot drawn over the routing still blends with it and no // pixel test can tell the two orders apart reliably. -TEST_F(SaveImageTest, LayerCompositionOrderMatchesClientZIndex) +TEST_F(SaveImageTest, LayerCompositionOrderMatchesClientDrawOrder) { const std::vector tech_layers = rowsOf({"metal1", "metal2"}); TileVisibility vis; @@ -873,7 +873,7 @@ TEST_F(SaveImageTest, LayerCompositionOrderMatchesClientZIndex) vis.rudy = true; vis.routing_congestion = true; - // zIndex on screen: _instances 0, _pins 1, _mfg_grid 2, tech layers 3.., then + // z on screen: _instances 0, _pins 1, _mfg_grid 2, tech layers 3.., then // _inst_labels 999, _access_points 1000, _regions 1001, _gcell_grid 1002, // _rudy 1003, _routing_congestion 1004. const std::vector expected = {"_instances", @@ -1113,7 +1113,7 @@ TEST_F(SaveImageTest, LayerCompositionOrderHonorsPerDieHiddenLayers) } // However many rows the dies bring, they all stay under the overlays, as the -// merged panes keep them on screen. +// client keeps them on screen. TEST_F(SaveImageTest, LayerCompositionOrderKeepsOverlaysAboveManyRows) { std::vector names; diff --git a/openroad/web/test/cpp/TestSaveReport.cpp b/openroad/web/test/cpp/TestSaveReport.cpp index 1b38c74b693..673ce3d554d 100644 --- a/openroad/web/test/cpp/TestSaveReport.cpp +++ b/openroad/web/test/cpp/TestSaveReport.cpp @@ -169,8 +169,6 @@ TEST_F(SaveReportTest, ContainsRequiredHTMLElements) // The golden-layout themes theme.js switches between, by id. EXPECT_TRUE(contains(html, "id=\"gl-theme-dark\"")); EXPECT_TRUE(contains(html, "id=\"gl-theme-light\"")); - // leaflet's stylesheet, bundled into the report's own