# Migrating from v19 to v20

TeiaViewer v20 draws with a new engine, `@stereograph/teiaviewer-engine` (WebGPU, WebGL2 as a
fallback), in place of the viewer's three.js render stack. The scene graph (`SceneObject`),
commands (undo/redo), settings and plugins stay in the viewer; what exposed the former render
internals changes. This guide lists what an application has to change.

## Packages

- `@stereograph/teiaviewer-engine` is new. The viewer depends on it: nothing to install. Import
  from it the settings classes (`Settings`, `NumberController`…), `Signal` and `logger`.
- The plugin `PathPlugin` and its UI (`NavigationWidget`, `NavigationGraphToolbarItem`) are not
  migrated yet: not exported in v20.

## Settings

The settings are classes of the engine (`Settings`, `BooleanController`, `NumberController`,
`TextController`, `ColorController`, `SelectController`). Removed: the viewer's controllers
(`ValueController`, `StringController`…), `SettingsRecord`, `SettingsBuilder`,
`createViewerSettings`, `LocalStorageManager`, `mergePluginSettingfunctions`.

- **The engine's settings are under `settings.engine`**: meshes (selection colour, x-ray opacity,
  edges), lighting, renderer (background, pixel ratio, backend), post-processing, culling,
  loading. They replace the v19 groups `ao`, `render`, `renderer`, `sprites`, `loading`, `objects`,
  `lights_legacy`, `scene_legacy`. `memory` and `snapping` are removed.
- **The viewer keeps `dev`** (`debug`, at the top level before; `logLevel`, `verbose` before),
  `loading`, `scene` (`doubleClickDelay`, at the top level before), `helpers` and `camera`.
- **Colours are numbers** (`0xRRGGBB`), no longer strings.
- **A value is validated**: clamped to its range, rounded to its step, refused outside a select's
  options; `onChange` is emitted only when it changes.
- **The config is the `Viewer`'s first argument, the options its second.** `backupName` is the
  option `settingsStorageKey`. Only the values changed from their default are saved; the settings
  saved by v19 are not read.
- **Storage**: the viewer's values under `TeiaViewerCfg` (the `settingsStorageKey`), a plugin's
  under `TeiaViewerCfg-<plugin name>`, the values changed only. A setting with `skipSave` is never
  saved (e.g. a token). The v19 keys (`PluginCfg-<name>`…) are left in the local storage.
- **Every group of settings has a `title` and an `icon`**, under which an interface (the developer
  tools) shows it; a `SelectController` takes `labels`, the names of its options.
- **Renamed**: `camera.centerCameraWhenLoading` is `loading.centerSceneOnLoading`; the engine's
  `meshes.showEdges` is `meshes.edgesPassEnabled`, hidden (the render mode hides the edges).
  Removed, read by nothing: `raycast.marginError`.
- **New**: `camera.smoothTime` / `camera.draggingSmoothTime` (the camera's inertia, in seconds, 0
  by default), `dev.panelTheme`, `engine.scene.maxCuttingPlanes`.
- `SetSettingCommand(viewer, setting, value)` sets a setting, undoable (its `update(value)` for a
  value changed continuously, one step in the history); `ResetSettingsCommand` resets them.

```ts
// v19
const viewer = new Viewer({ backupName: 'Default', objects: { highlightColor: '#fabd38' } });
viewer.settings.scene.backgroundColor.value = '#7090d0';

// v20
const viewer = new Viewer(
  { engine: { meshes: { selectionColor: 0xfabd38 } } },
  { settingsStorageKey: 'TeiaViewerCfg' },
);
viewer.settings.engine.renderer.background.value = 0x7090d0;
```

**A plugin's settings are a `Settings` class**, given to `ViewerPlugin.Create`; `EmptySettings`
for none. The plugin's name is the key of its saved settings.

```ts
// v19
const PluginBase = ViewerPlugin.Create('MyPlugin', () => ({
  size: new NumberController(5, { min: 0, max: 10 }),
}));

// v20
class MyPluginSettings extends Settings {
  readonly title = 'My plugin';
  readonly icon = 'general';
  readonly size = new NumberController(5, { description: 'Size.', min: 0, max: 10, step: 1 });
}
const PluginBase = ViewerPlugin.Create('MyPlugin', MyPluginSettings);
```

## Signals

`ViewerSignal` is removed: every signal is the engine's `Signal`. `subscribe` is removed (keep the
connection of `connect`); `getConnectionsCount()` is `listenerCount`; `connect` takes
`{ once, signal }` options. A listener that throws no longer stops `emit` (its error is logged).

```ts
// v19
const unsubscribe = viewer.signals.onSceneGraphChanged.subscribe(update);
unsubscribe();

// v20
const connection = viewer.signals.onSceneGraphChanged.connect(update);
connection.disconnect();
```

## Viewport

`viewer.viewport` always exists. `attachViewport(canvas)`, `detachViewport()` and
`signals.onViewportAdded` are removed: `mount(canvas)` draws on a canvas, **asynchronously** (it
resolves with the engine's `Renderer`), `unmount()` stops. `viewport.canvas` and
`viewport.renderer` are `null` while unmounted; `onViewportMounted` / `onViewportUnmounted` tell
the changes.

- The backend (`settings.engine.renderer.backend`: `auto`, `webgpu`, `webgl2`) is chosen at the
  mount; changing it reloads the page. Mounts made in a row wait for each other.
- `ViewportScreenshotCommand` / `DownloadViewportScreenshotCommand` need the viewport mounted.

```ts
// v19
const viewport = viewer.attachViewport(canvas);
viewer.detachViewport();

// v20
await viewer.viewport.mount(canvas);
viewer.viewport.unmount();
```

## Scene and objects

The scene's meshes and sprites are objects of the engine's scene (`viewer.scene.engineScene`),
which draws, bounds and picks them.

- **Objects are added and removed through their controller.** `scene.addObject` /
  `removeObject` are removed; `addController` / `removeController` are `addObjectController` /
  `removeObjectController`. An object knows its controller while in the scene
  (`object.controller`).
- **The scene's iterators are removed** (`getAllObjects`, `getAllVisibleObjects`, their uuids…):
  walk `scene.controllers`, or the controller concerned (e.g. `scene.bimMeshController` for the
  loaded objects). `getObjectByUUID`, `getObjectsByUUID` (now an array) and `hasObjectUUID` stay.
- **A controller's queries are no longer generators**: the filtered ones
  (`getAllVisibleObjects`, `getAllHiddenObjects`, their uuids, `getObjectsByUUID`) give an array;
  `getAllObjects` / `getAllObjectUuids` the iterator of its map. A `for…of` works as before.
- **A controller manages its objects' life**: `canAddObjects(count)` (the clipping planes'
  controller refuses past its maximum, `addObject` throws), `disposeObject(object)` frees one for
  good (`DeleteObjectsCommand` calls it once it leaves the history). An object removed (e.g.
  deleted, kept for an undo) is out of the engine's BoxTree: neither in the bounds nor picked.
- **Commands**: `DeleteObjectCommand(viewer, object)` is `DeleteObjectsCommand(viewer, uuids)`
  (several objects, the children before their parents; an `ObjectNotInSceneError` for a uuid out
  of the scene); `AddObjectCommand` takes the controller (`super(viewer, controller, options)`);
  `AddExistingObjectCommand` is removed.
- **Per-object signals are the controller's**: `object.signals.onVisibilityChanged` /
  `onSelectedChanged` are `controller.signals.onObjectVisibilityChanged(object)` /
  `onObjectSelectedChanged(object)`.
- **`transformConfig` is the controller's**: override `getTransformConfig(object)`.
- **The BoxTree is the engine's** (`engineScene.boxTree`, its helper `engineScene.boxTreeHelper`):
  the viewer's `BoxTree` and its scene methods (`addObjectIntoBoxTree`, `updateObjectInBoxTree`,
  `raycastBoxTree`, `getBoxTreeBoundingSphere`, `showBoxTreeHelper`…) are removed. The scene's
  bounds are `getBoundingBox` / `getBoundingSphere` (which returns its target), the engine's
  objects and those of `addObjectToBoundingBox` (call `updateObjectsBoundingBox()` once one of
  them moved); the camera frames `getFramingSphere()`, the engine's objects only (not a map far
  wider than the model).
- **Lights and background are the engine's**: `lightsController`, `ambientLight` and
  `scene.background` are removed (`settings.engine.lighting`,
  `settings.engine.renderer.background`).
- **Meshes**: `SceneMesh` is concrete, holding its engine objects (`mesh.proxies`, `setProxy`; the
  proxy's `owner` is the mesh); `new SceneMesh(uuid)` replaces `EmptyMesh`. Its state and
  materials are set on its engine objects; `setMatrix` moves them, not its children. `BimMesh`
  holds one engine object per geometry type (3D, 2D: `getProxy(type)`, `setActiveType(type)`), no
  sub-meshes. The engine's `GeometryBuffersConverter` turns a three.js geometry into an engine part
  (`convertGeometry`, with its sharp edges; `convertLine`). Removed: `SceneMeshGroup`,
  `SceneMeshProxy`, `SceneLineProxy`, `RaycastableSceneObject`, `DrawableSceneObject`, the
  containers and `scene/geometry`, `MaterialFactory`, `MaterialLayer`, `TextureAtlas`,
  `SpriteContainer`, `SceneMesh.materialName`, `copyMaterials`, `MeshGroupStateController`,
  `ObjectSelection.getMeshesDeep`, `viewer.stats`.
- **`toJson()` is in ordered sections**: `identity`, `state`, `transform`, `material`, `edges`,
  `engine` (each engine object's flags, bounds and parts), `userData`, `children`. The infobox's
  3D data tab keeps this order. `showNormalsHelper` draws with the engine's `MeshNormalsHelper`.
- `ObjectStateHistory.getControllerFromObject(object)` gives the state controller an object's
  states are pushed to (`SceneObject.getStateController()` makes a new one at each call).
- **Layers**: an object's `layer` is the engine's `MeshLayer` (`Layer1` by default, a layer drawn
  over those below), set with `SetObjectsLayerCommand`. Three.js tools drawn over the scene take
  `TOOL_LAYER`. Three.js objects drawn outside the engine go through `scene.addInternalObject`.
- **Sprites**: a `SceneSprite` holds an engine sprite (`sprite.proxy`):
  `SpriteController.createSprite(position, size, onClick, layer)`, `new SceneSprite(proxy,
  imageDrawer, onClick, uuid)`, `setTexture({ imageUrl, text })` (an image drawn once, shared).
  `AddSpriteCommand`'s `depthTest` option is `layer` (`Layer4`, over every object, by default).
  `SceneSpriteLegacy` is removed.
- **Clipping planes**: a `ClippingPlane` is no longer a mesh (its `plane` and matrix, never
  scaled), cutting the scene through the engine (`ClippingPlane.proxy`); at most
  `settings.engine.scene.maxCuttingPlanes`. The engine draws the quads across the scene's bounds
  (the controller's `visible` shows them; a hidden plane still cuts; their bounds
  `getPlaneBoundingBox`). Removed: `mesh`, `setSize`, `opacity`, `raycast`, `planeSize`, the size
  of `createPlane`, `ResizeClippingPlanesBehavior`, `ViewerScene.updateClippingPlanes`.
- New per-object states: `facesVisible`, `ignoreCuttingPlanes`
  (`SetObjectsIgnoreCuttingPlanesCommand`). `edgesOpacity` and `hover` are kept but not drawn yet.

```ts
// v19
viewer.scene.addController(controller);
viewer.scene.addObject(object, parentUuid);
viewer.scene.removeObject(object);
for (const object of viewer.scene.getAllVisibleObjects()) { /* ... */ }
object.signals.onVisibilityChanged.connect(update);

// v20
viewer.scene.addObjectController(controller);
controller.addObject(object, parentUuid);
object.controller?.removeObject(object);
for (const object of viewer.scene.bimMeshController.getAllVisibleObjects()) { /* ... */ }
controller.signals.onObjectVisibilityChanged.connect(update);
```

## Loading

`SceneLoader` loads with the engine's readers, in workers: `.gltf`, `.glb`, `.mgeom` (no more
OBJ).

- **`File3DRequest` is the engine's `FileSource`** (`{ url, name?, headers? }`):
  `sceneLoader.addFileSource(source)`, `new LoadCommand(viewer, sources, options)`. Its `format`,
  `method`, `body` and `geometryType` are removed: the files give their objects' geometry type.
  `File3DRequestFactory` and `File3DLoader` are removed.
- **`ObjectImportController` is `BimMeshImportController`**, given each object read (`InputMesh`):
  override `updateObject(input)`, `shouldKeepObject(input)` (no longer given the uuids: the base
  leaves out the duplicates), `onObjectRead`, `onMeshAdded`. An object read before its parent
  (`parentUuid`) waits for it; those whose parent the loading did not bring are left out at its
  end. The geometry type comes from the input's `tag` (`getGeometryTypeFromTag`).
  `getInitialObjects()` gives `InputMesh`es without parts; `canProcessObject` and `getObject` are
  removed. `setObjectImportController` is `setImportController`.
- **`onMeshLoaded(mesh, input, proxy)`**, an option of `LoadCommand`, `LoadFilesCommand` and the
  Teia loading commands, sets an object's state before it is drawn (`proxy` null when the object
  is made, then the geometry linked). `LoadFilesCommand`'s options are `{ onMeshLoaded }` only.
- `sceneLoader.statistics` (`SceneLoadingStatistics`) counts what the loadings brought since the
  scene was cleared: files, seconds, objects left out.
- Removed: the file and batching workers, `SerializedMeshStore` and the `Serialized*` types,
  `BimMeshController`'s container factories; `createMesh(uuid, name)`.

## Picking

`viewer.scene.raycaster.raycast(ray, camera, options)` (a `ViewerRaycaster`) is the single entry
point: the engine's objects, then each controller's `raycast` for objects drawn outside the
engine. The hits are sorted as seen (highest layer first, then nearest); `SceneIntersection`
gains `layer`, `proxy` and `part`, and loses `rayDistance`.

- **Operators get the objects under the pointer**: `ViewportRaycaster`, `viewport.raycaster` and
  `raycastEvent` are removed; each pointer handler receives a `PointerIntersections`
  (`onPointerDown(event, intersections)`…), read with `getFirst(filter?)` / `getAll(filter?)`.
- **Options**: `onlyFirst` (default `true`), `viewportHeight` (the lines' tolerance,
  `settings.engine.scene.lineThresholdPixels`), `transparent` (default `true`; `false` goes
  through the objects drawn transparent, x-ray included), `filter(object)`, checked before an
  object is raycast (to pick only your objects: `object.controller === myController`).
- **Order**: a selected object, drawn over the others, is hit before those in front of it, as the
  always-visible sprites (top layer); the clipping planes' quads come last.
- **`PointerIntersections`** raycasts at its first read and keeps each result per filter
  reference: two handlers asking the same raycast once. Shift held hits the transparent objects.
- **A controller drawing objects outside the engine** overrides
  `SceneObjectController.raycast(ray, camera, options, target)`.
- **Snapping on an edge** is the engine's `MeshProxy.projectPointOnEdges(point, maxDistance,
  target, part)`: the nearest segment of the part hit (its sharp edges, or its lines).
- Removed: `RaycastSelectOperator.sortIntersects`.

```ts
// v19
const [hit] = viewport.raycaster.raycastEvent(event, { filterFunc, raycastTransparentMeshes });
mesh.projectPointOnEdges(hit.point, target, 0.3);

// v20 (in an operator's handler)
const hit = intersections.getFirst(filterFunc);
hit?.proxy?.projectPointOnEdges(hit.point, 0.3, target, hit.part ?? 0);
```

## Render modes

The render mode (`RenderModeController.renderMode`, `SetRenderModeCommand`) is each mesh
controller's `renderState`, combined with each object's own state when drawn.

- **It no longer writes the objects' own state**: in x-ray mode `mesh.xRay` stays `false`; read
  what is drawn on the engine objects (`mesh.proxies[0].xRay`).
- `Textured` is the normal mode; `Wireframe` draws the edges only.
- A mesh controller can be drawn on its own: `setRenderState({ xRay, facesVisible,
  edgesVisible })`, `ignoreViewportRenderMode`.

## Logging

`Debug` is removed: use the engine's `logger` (`debug`, `info`, `warn`, `error`), its level
`settings.dev.logLevel` (`verbose` before).

```ts
// v19
Debug.warn('Failed to load', error);

// v20
logger.warn('Failed to load', error);
```

## Developer tools

- `saveContainerPositions()` / `loadContainerPositions()` are `savePanelLayouts()` /
  `loadPanelLayouts()` (the panels' place and size).
- Their colours are `settings.dev.panelTheme` (`PanelThemeNames`, `light` by default).
- A "Selection" folder changes the selected objects (colour, opacity, x-ray, visibility, edges,
  cutting) with the viewer's commands; the stats add the loadings and the object clicked last.

## Viewport React package

- **`useSetting(setting)`** reads a setting, given the setting itself: `useViewerSettings`,
  `useViewerPluginSettings`, `useValueController` and their key types are removed.
- **`ViewportPlugin`'s settings** are `showObjectHierarchyBanner`, `showToolbar`,
  `treeViewPageSize`; `disableToolbar` is the plugin's `toolbarDisabled`.
- `useSignalSubscriber(...signals)` gives the `subscribe` of `useSyncExternalStore` on signals.
- `ViewportContainer` mounts `viewer.viewport` on its canvas. `BufferRangeTableCell` is removed.
- The notifications' toasts are at the top right of the viewport; a notification may give its
  task's `progress` (0 to 1), shown as a bar.

```tsx
// v19
const [debug] = useViewerSettings('debug');
const [pageSize] = useViewerPluginSettings('Viewport', 'treeViewPageSize');

// v20
const { viewer } = useViewerContext();
const [debug] = useSetting(viewer.settings.dev.debug);
const [pageSize] = useSetting(viewer.getPlugin('Viewport').settings.treeViewPageSize);
```

## Plugins

For every plugin of `@stereograph/teiaviewer-plugins` and `-legacy-plugins`:

- **Its name has no `Plugin` suffix** (`ViewerPlugin.Create('Map', …)`, `'MapPlugin'` before):
  its settings saved under the former name are not read. The registry keys do not change.
- **Its settings are a class**, the config the constructor's second argument
  (`new MapPlugin(viewer, { opacity: 0.5 })`).
- **Its signals are engine `Signal`s.**
- Unregistering Zone, FloorPlan or MeasureLine clears the commands history.

### TeiaPlugin

- **Settings** `TeiaPluginSettings`, flat: `twinApiUrl`, `tiaApiUrl`, `token` (never saved).
  `settings.api.token` is `settings.token`; `objectsPerRequest` and `objectCountWarningLimit` are
  removed (the page size is the loading commands' `gltfObjectsPerRequest` /
  `mgeomObjectsPerRequest`). `TeiaPluginSettingsCtor` and `TeiaViewerPluginSettings` are removed.
- **The loading commands load `FileSource`s**: `TeiaLoadCommand.getFileRequests` is
  `getPageSources` (`twin-<id>-<page>.glb`, `model-<id>-v<version>-<page>.glb`, the token in their
  headers). The objects take their Teia guid as uuid and their geometry type from their
  Stereograph data (3D without: a DWG model's no longer defaults to 2D); a twin's objects get their
  ancestors from its tree; an object missing from the tree is left out, with an error.
- **A project in FlatBuffers loads as `.mgeom`** (`ProjectApi.getFlatBuffers`): the twin whole
  (`filter`, `fieldSelectionRules`, `endpoint` left out), its 3D or its 2D along `axis`
  (`geometryType`; `Original` asks its 3D).
- The developer tools: `TeiaAuthController`'s signals are engine `Signal`s; the request tool's
  local files give their geometry type and may be `.mgeom`.
- `LoadCustomUrlCommand` is removed: use `LoadCommand` or `LoadFilesCommand`.
- `onSettingsMapSaved` is the MapPlugin's.

```ts
// v20: the objects' state set as they load, before they are drawn
new LoadTwinCommand(viewer, twin, {
  onMeshLoaded: (mesh, _input, proxy) => {
    if (proxy === null) {
      mesh.visible = mesh.userData.stereograph?.objectType !== 'IfcSpace';
    }
  },
}).execute();
```

### ZonePlugin

- A zone is a `Zone` (a `SceneMesh`, `isZone`, its `shape`) of `zoneController`, no longer a
  `BimMesh` marked `userData.type === 'CustomTeiaZone'`.
- `AddZoneCommand(viewer, selection, shape, color, options?)` takes the colour; the plugin's
  `settings.color`, `getBatchedMesh` and `getBatchedEdgeGeometry` are removed. An `object` zone
  shares the selected object's geometries; without one with geometry, it is refused.

### FloorPlanPlugin

- A plan is a `FloorPlan` of `floorPlanController`: `SceneFloorPlan`, `SceneFloorPlanLayer` and
  `SceneFloorPlanController` are removed. `SceneFloorPlan.id` is `configurationId`;
  `getSceneFloorPlanWithConfigurationId` is `getFloorPlanFromConfigurationId`.
- A plan is one engine object, a part per shape of every layer; its texts are three.js planes
  (`annotations`). `FloorPlanController.createFloorPlan(description, layers)` makes a plan without
  adding it.
- A layer's `lineWidth` is its outline width in CSS pixels (0: none); a dashed layer draws 8 px
  dashes and 5 px gaps.
- The context menu removes a plan with `DeleteObjectsCommand` (undoable).
- `FloorPlanPluginConfig` and `objectCountWarningLevel` are removed;
  `AddFloorPlanCommand(viewer, twin, planConfig, { gltfObjectsPerRequest })`.

### MapPlugin

- `MapContainer` is a `SceneObject` drawn outside the engine (three.js planes, its `container`),
  not picked: `raycast`, `projectPointOnEdges` and `signals.onSelectedChanged` are removed. Its
  shape and size cut the planes through a mask, the same on WebGL2 and WebGPU.
- The map is placed once the loaded objects are in the BoxTree; it counts in the scene's bounds
  once placed and while shown, not in the camera's framing.
- `SetMapCenterCommand` restores the former centre on undo; `SetMapElevationCommand` redoes the
  elevation last given to `update` (two v19 bugs).

### MeasureLinePlugin

- The lines are drawn by the engine, over the objects (`MeshLayer.Layer3`), their sprites over
  them (`Layer4`). `MeasureLineAnchor` is a `SceneMesh`: part 0 its head (`ANCHOR_HEAD_PART`, a
  box, a cone at the ends), part 1 the segment from the anchor before it (`ANCHOR_SEGMENT_PART`, 3
  CSS pixels wide). `MeasureLineAnchorLine` is removed: a segment hit is
  `isMeasureLineSegmentHit(hit)`.
- `MeasureLineSprite` holds an engine sprite (its label drawn on a canvas, of a constant size on
  the screen); `MeasureLineController` is a `SceneMeshController`.
- `MeasureLineRaycastSelectOperator` is removed. The operator's handlers take the
  `PointerIntersections`; deleting an anchor uses `DeleteObjectsCommand`.
- The context menu removes the line of a segment or a sprite right-clicked too. In
  `plugins-ui`, `MeasureLineToolbarItem` is back.

### PluginsUIPlugin

- It depends on `Teia` and `Viewport` only: the floor plans widget and the map's settings tab
  (`MapSettingsTab`) are added while their plugin is registered, removed with it; the toolbar items
  of a plugin missing are disabled.
- Its settings are `PluginsUIPluginSettings` (`search`: `enableJsonEditor`, `enableAI`);
  `PluginsUIPluginConfig` is `SettingsConfig<PluginsUIPluginSettings>`.
- `ValidationDisplayModal` (the warning before showing a large plan) is removed.

### ProjectionPlugin (removed)

Removed with `TwinProjectionApi` and its widget, toolbar item and hooks.

### Legacy plugins

- `AnomalyPluginSettings`, `ChatBotPluginSettings`, `OpenDataPluginSettings`,
  `QuantityTakeoffPluginSettings`; the others take `EmptySettings`.
- An anomaly's scene is its BIM objects (`scene.bimMeshController`). Its snapshot needs the
  viewport mounted. `getAnomalyCamera` gives the default camera for an orthographic one.

## Removed with the former render core

- `JsHeapMemoryTracker`, `JsHeapSizeObserverBehavior` and the memory warnings.
- `WorkerController`: the engine's `WorkerPool` replaces it, exported with the Path plugin.
- Test utilities: `setupTestViewer`'s `withViewport` (use `mountTestViewport`),
  `createSerializedMesh`, `createSerializedMeshProxy`.
- The dependencies `typed-signals`, `heap-js` and `deepmerge`.
