diff --git a/app/app.config.ts b/app/app.config.ts index 74712233c..184886a13 100644 --- a/app/app.config.ts +++ b/app/app.config.ts @@ -1,4 +1,5 @@ import type { ChromeTheme } from "@ogw_front/composables/chrome_theme"; +import type { HighlightColors } from "@ogw_front/utils/highlight_colors"; import type { SceneColors } from "@ogw_front/utils/default_styles"; declare module "nuxt/schema" { @@ -10,6 +11,8 @@ declare module "nuxt/schema" { basemap?: boolean; // Colors ({ red, green, blue, alpha }) of a new or reset scene, see plugins/scene_colors.ts sceneColors?: SceneColors; + // Highlight colors ({ red, green, blue }) given to the viewer, see utils/highlight_colors.ts + highlightColors?: HighlightColors; }; } } @@ -28,5 +31,7 @@ export default defineAppConfig({ basemap: false, // Colors of a new or reset scene, the OpenGeodeWeb ones when not set (see utils/default_styles) sceneColors: {}, + // Highlight colors given to the viewer, its own (brand-neutral) ones when not set + highlightColors: undefined, }, }); diff --git a/app/components/ClippingPlanes.vue b/app/components/ClippingPlanes.vue index 13ea9f71b..44a61b634 100644 --- a/app/components/ClippingPlanes.vue +++ b/app/components/ClippingPlanes.vue @@ -212,7 +212,7 @@ watch(allItems, () => { }); watch( - () => Object.values(hybridViewerStore.hybridDb).filter((entry) => entry && entry.actor).length, + () => Object.values(hybridViewerStore.hybridDb).filter(Boolean).length, (actorCount) => { if (show.value && actorCount > 0) { updateWidgetPlacement({ isReset: true }); diff --git a/app/components/FactorFilterPanel.vue b/app/components/FactorFilterPanel.vue index 24b30757f..b4b28974c 100644 --- a/app/components/FactorFilterPanel.vue +++ b/app/components/FactorFilterPanel.vue @@ -114,7 +114,7 @@ watch(allItems, () => { }); watch( - () => Object.values(hybridViewerStore.hybridDb).filter((entry) => entry && entry.actor).length, + () => Object.values(hybridViewerStore.hybridDb).filter(Boolean).length, (actorCount) => { if (show.value && actorCount > 0) { applyFactor(); diff --git a/app/composables/clipping_planes_widget.ts b/app/composables/clipping_planes_widget.ts index 50ed71213..9cc9627d4 100644 --- a/app/composables/clipping_planes_widget.ts +++ b/app/composables/clipping_planes_widget.ts @@ -5,7 +5,7 @@ import { alignCameraToMainCamera, computeSceneBoundsInfo, followsSceneCenter, - resolveActiveActors, + resolveActiveEntries, } from "@ogw_front/utils/clipping_planes"; import { type ClippingPlane, @@ -19,6 +19,7 @@ import type { Coordinates } from "@ogw_front/types/geometry"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { DataIdentified } from "@ogw_front/types/identifiers"; import type { vtkGenericRenderWindow as GenericRenderWindowInstance } from "@ogw_internal/stores/hybrid_viewer/vtk_types"; +import { entrySceneBounds } from "@ogw_internal/stores/hybrid_viewer/parts"; import type { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; import type { vtkCamera } from "@kitware/vtk.js/Rendering/Core/Camera"; import { newInstance as vtkGenericRenderWindow } from "@kitware/vtk.js/Rendering/Misc/GenericRenderWindow"; @@ -58,12 +59,12 @@ function useClippingPlanesWidget({ function getSceneBoundsInfo(): SceneBoundsInfo { return computeSceneBoundsInfo( - resolveActiveActors( + resolveActiveEntries( targetAllVisible.value, allItems.value, selectedDatasetIds.value, hybridViewerStore.hybridDb, - ), + ).map((entry) => entrySceneBounds(entry)), ); } function getSceneCenter(): Readonly { diff --git a/app/composables/crs.ts b/app/composables/crs.ts index 4b55794f8..bc8adf504 100644 --- a/app/composables/crs.ts +++ b/app/composables/crs.ts @@ -6,6 +6,7 @@ import type { Coordinate } from "@ogw_front/types/geometry"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { LightViewable } from "@ogw_front/types/data"; import back_schemas from "@geode/opengeodeweb-back/opengeodeweb_back_typed_schemas.js"; +import { clearComponentLightViewables } from "@ogw_internal/stores/data/model/light_viewables"; import { reloadObject } from "@ogw_front/utils/reload_object"; import { useBackStore } from "@ogw_front/stores/back"; import { useCrsStore } from "@ogw_front/stores/crs"; @@ -66,16 +67,23 @@ async function refresh( { binary_light_viewable, crs }: MovedData, focus = true, ): Promise { - // The local actor is rebuilt from the stored light viewable: store the moved one first + // The local actor is rebuilt from the stored light viewable: store the moved one first. + // The previous detail no longer matches the geometry: dropped, then asked again const dataStore = useDataStore(); + const hybridViewerStore = useHybridViewerStore(); + hybridViewerStore.cancelRefine(item.data_id); + await clearComponentLightViewables(item.data_id); await dataStore.updateItem(item.data_id, { binary_light_viewable }); await reloadObject(item.data_id, { rebuildActor: true }); // Only then the CRS: a basemap built for the new CRS reads the data bounds from the actors, // Which must no longer hold the previous coordinates await dataStore.updateItem(item.data_id, { crs }); if (focus) { - await useHybridViewerStore().focusCameraOnObject(item.data_id); + await hybridViewerStore.focusCameraOnObject(item.data_id); } + // A failed detail leaves the bounding box shown; the back store reports the error + // oxlint-disable-next-line promise/prefer-await-to-then -- fire-and-forget: the CRS change does not wait for the detail. + hybridViewerStore.refineItem(item.data_id).catch(() => undefined); } // Each reload rebuilds an actor: one after another, then the camera moves once on the item diff --git a/app/composables/viewer_reset.ts b/app/composables/viewer_reset.ts index 7f76b98d9..8cb0846a7 100644 --- a/app/composables/viewer_reset.ts +++ b/app/composables/viewer_reset.ts @@ -10,6 +10,7 @@ import { hideViewerMarker, resetOrientationMarkerVisibility, } from "@ogw_front/composables/orientation_overlay"; +import { getHighlightColors } from "@ogw_front/utils/highlight_colors"; // The scene colors of the viewer have no alpha (the text one takes it as its opacity) function toViewerColor({ red, green, blue }: ColorRGBA): ColorRGB { @@ -39,6 +40,17 @@ async function applyAppSceneColors(request: ViewerRequest): Promise { } } +// A reset viewer highlights with its own colors: give it the app's (`ogwFront.highlightColors`), if any +async function applyAppHighlightColors(request: ViewerRequest): Promise { + const highlightColors = getHighlightColors(); + if (highlightColors) { + await request({ + schema: viewer_schemas.opengeodeweb_viewer.viewer.set_highlight_colors, + params: highlightColors, + }); + } +} + // To call after each viewer reset (reset_visualization), which brings back the viewer's own scene. Neither // Step fails the reset: the viewer stays usable with its own colors, and the marker is hidden either way async function afterViewerReset(request: ViewerRequest): Promise { @@ -48,6 +60,11 @@ async function afterViewerReset(request: ViewerRequest): Promise { } catch (error) { consola.warn("[SceneColors] The viewer kept its own scene colors:", error); } + try { + await applyAppHighlightColors(request); + } catch (error) { + consola.warn("[HighlightColors] The viewer kept its own highlight colors:", error); + } await hideViewerMarker(request); } diff --git a/app/plugins/scene_colors.ts b/app/plugins/scene_colors.ts index 0bfbf49aa..ff2f270b3 100644 --- a/app/plugins/scene_colors.ts +++ b/app/plugins/scene_colors.ts @@ -1,10 +1,13 @@ +import { setHighlightColors } from "@ogw_front/utils/highlight_colors"; import { setSceneColors } from "@ogw_front/utils/default_styles"; -// Hands `ogwFront.sceneColors` (app.config.ts) to the default scene style, before any data style store is created +// Hands `ogwFront.sceneColors` (app.config.ts) to the default scene style, before any data style store is created, +// And `ogwFront.highlightColors` to the viewer reset export default defineNuxtPlugin({ name: "ogw-scene-colors", enforce: "pre", setup() { setSceneColors(useAppConfig().ogwFront?.sceneColors ?? {}); + setHighlightColors(useAppConfig().ogwFront?.highlightColors); }, }); diff --git a/app/stores/basemap_helpers/georeferenced.ts b/app/stores/basemap_helpers/georeferenced.ts index 9edcca470..6cb1c9111 100644 --- a/app/stores/basemap_helpers/georeferenced.ts +++ b/app/stores/basemap_helpers/georeferenced.ts @@ -1,6 +1,7 @@ import { type Extent, boxesExtent } from "./extent.js"; import type { ComputedRef } from "vue"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; +import { entryBounds } from "@ogw_internal/stores/hybrid_viewer/parts"; import { sameCrs } from "@ogw_front/utils/crs"; import { useCrsStore } from "@ogw_front/stores/crs"; import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; @@ -38,7 +39,7 @@ function useGeoreferenced(): Georeferenced { return boxesExtent( Object.entries(hybridViewerStore.hybridDb) .filter(([id]) => georeferenced.has(id)) - .map(([, entry]) => entry.polydata.getBounds()), + .map(([, entry]) => entryBounds(entry)), ); } diff --git a/app/utils/clipping_planes.ts b/app/utils/clipping_planes.ts index 2464b0d45..1467d00fa 100644 --- a/app/utils/clipping_planes.ts +++ b/app/utils/clipping_planes.ts @@ -154,7 +154,7 @@ export { export { computeSceneBounds, computeSceneBoundsInfo, - resolveActiveActors, + resolveActiveEntries, alignCameraToMainCamera, } from "./clipping_planes_scene"; export type { SceneBoundsInfo, MainCameraOptions } from "./clipping_planes_scene"; diff --git a/app/utils/clipping_planes_scene.ts b/app/utils/clipping_planes_scene.ts index 64e5af5ee..d2700c8b7 100644 --- a/app/utils/clipping_planes_scene.ts +++ b/app/utils/clipping_planes_scene.ts @@ -1,14 +1,14 @@ +import type { HybridDb, HybridDbEntry } from "@ogw_internal/stores/hybrid_viewer/vtk_types"; import type { Bounds } from "@kitware/vtk.js/types"; import type { Coordinates } from "@ogw_front/types/geometry"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { DataIdentified } from "@ogw_front/types/identifiers"; -import type vtkActor from "@kitware/vtk.js/Rendering/Core/Actor"; import type { vtkCamera } from "@kitware/vtk.js/Rendering/Core/Camera"; -function computeSceneBounds(actors: readonly vtkActor[]): Bounds { +// Each box is the bounds of one data, all its parts together +function computeSceneBounds(boxes: readonly Bounds[]): Bounds { let bounds: Bounds = [Infinity, -Infinity, Infinity, -Infinity, Infinity, -Infinity]; - for (const actor of actors) { - const boundsOfActor = actor.getBounds(); + for (const boundsOfActor of boxes) { bounds = [ Math.min(bounds[0], boundsOfActor[0]), Math.max(bounds[1], boundsOfActor[1]), @@ -26,11 +26,11 @@ interface SceneBoundsInfo { readonly cubicBounds: readonly number[]; } -function computeSceneBoundsInfo(actors: readonly vtkActor[]): SceneBoundsInfo { - if (actors.length === 0) { +function computeSceneBoundsInfo(boxes: readonly Bounds[]): SceneBoundsInfo { + if (boxes.length === 0) { return { center: [0, 0, 0], cubicBounds: [-1, 1, -1, 1, -1, 1] }; } - const [xmin, xmax, ymin, ymax, zmin, zmax] = computeSceneBounds(actors); + const [xmin, xmax, ymin, ymax, zmin, zmax] = computeSceneBounds(boxes); const center = [ Number(((xmin + xmax) / 2).toFixed(4)), Number(((ymin + ymax) / 2).toFixed(4)), @@ -38,10 +38,9 @@ function computeSceneBoundsInfo(actors: readonly vtkActor[]): SceneBoundsInfo { ]; const maxActorExtent = Math.max( - ...actors.map((actor: vtkActor) => { - const bounds = actor.getBounds(); - return Math.max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]); - }), + ...boxes.map((bounds: Readonly) => + Math.max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]), + ), ); const halfExtent = maxActorExtent / 2; const [centerX = 0, centerY = 0, centerZ = 0] = center; @@ -56,35 +55,29 @@ function computeSceneBoundsInfo(actors: readonly vtkActor[]): SceneBoundsInfo { return { center, cubicBounds }; } -interface ActorEntry { - readonly actor: vtkActor; -} - interface MainCameraOptions { readonly focal_point?: readonly number[]; readonly position?: Readonly; readonly view_up?: readonly number[]; } -function resolveActiveActors( +function resolveActiveEntries( targetAllVisible: boolean, allItems: readonly Readonly[], selectedDatasetIds: readonly DataId[], - hybridDb: Record, -): vtkActor[] { + hybridDb: Readonly, +): HybridDbEntry[] { let targetIds: readonly DataId[] = selectedDatasetIds; if (targetAllVisible) { targetIds = allItems.map((item: Readonly) => item.data_id); } const targeted = targetIds - .map((dataId) => hybridDb[dataId]?.actor) - .filter((actor: vtkActor | undefined): actor is vtkActor => actor !== undefined); + .map((dataId) => hybridDb[dataId]) + .filter((entry): entry is HybridDbEntry => entry !== undefined); if (targeted.length > 0) { return targeted; } - return Object.values(hybridDb) - .filter((entry: ActorEntry | undefined): entry is ActorEntry => entry !== undefined) - .map((entry: ActorEntry) => entry.actor); + return Object.values(hybridDb).filter((entry): entry is HybridDbEntry => entry !== undefined); } function computeNormalizedViewDirection( @@ -130,5 +123,10 @@ function alignCameraToMainCamera( } } -export { alignCameraToMainCamera, computeSceneBounds, computeSceneBoundsInfo, resolveActiveActors }; +export { + alignCameraToMainCamera, + computeSceneBounds, + computeSceneBoundsInfo, + resolveActiveEntries, +}; export type { MainCameraOptions, SceneBoundsInfo }; diff --git a/app/utils/highlight_colors.ts b/app/utils/highlight_colors.ts new file mode 100644 index 000000000..1e6839c94 --- /dev/null +++ b/app/utils/highlight_colors.ts @@ -0,0 +1,22 @@ +import type { ParamsOf } from "@ogw_shared/utils/types.js"; +import type viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; + +// The highlight colors an app gives the viewer: some components or a picked element, the picked cell outline, +// And each component type of a whole model highlighted +type HighlightColors = ParamsOf< + typeof viewer_schemas.opengeodeweb_viewer.viewer.set_highlight_colors +>; + +// `ogwFront.highlightColors` of the app (app.config.ts), handed over by plugins/scene_colors.ts +let appHighlightColors: HighlightColors | undefined = undefined; + +function setHighlightColors(colors: HighlightColors | undefined): void { + appHighlightColors = colors; +} + +function getHighlightColors(): HighlightColors | undefined { + return appHighlightColors; +} + +export { getHighlightColors, setHighlightColors }; +export type { HighlightColors }; diff --git a/app/utils/import_item.ts b/app/utils/import_item.ts index 93440b0ce..caeddf41c 100644 --- a/app/utils/import_item.ts +++ b/app/utils/import_item.ts @@ -31,6 +31,15 @@ async function addToViewerWhenViewable( return useHybridViewerStore().addItem(item.data_id); } +// The simplified light viewable takes a while: the import does not wait for it +async function refineWhenShown(item: NewDataItem, shown: Promise): Promise { + await shown; + if (!(await useDataStore().fetchIsViewable(item.data_id))) { + return; + } + await useHybridViewerStore().refineItem(item.data_id); +} + async function applyStyleWhenReady(item: NewDataItem, ready: Promise): Promise { await ready; if (!(await useDataStore().fetchIsViewable(item.data_id))) { @@ -92,6 +101,10 @@ async function importDataItem(item: NewDataItem): Promise { addViewerTask, applyStyleTask, ]); + // The detail is stored on the component rows: they must exist first + // A failed detail leaves the bounding box shown; the back store reports the error + // oxlint-disable-next-line promise/prefer-await-to-then -- fire-and-forget: the import does not wait for the detail. + refineWhenShown(item, Promise.all([addViewerTask, addDataComponentsTask])).catch(() => undefined); return item.data_id; } // Every item comes through here: from the back-end, which still names its data id `id`, or from a project diff --git a/internal/database/tables/model_components.ts b/internal/database/tables/model_components.ts index 7089a2cf7..4bcb2bf6c 100644 --- a/internal/database/tables/model_components.ts +++ b/internal/database/tables/model_components.ts @@ -4,6 +4,7 @@ import type { ModelComponentType, ModelComponentViewerId, } from "@ogw_front/types/model"; +import type { LightViewable } from "@ogw_front/types/data"; import type { TableDefinition } from "./table_definition"; interface ModelComponentRecord extends DataIdentified, GeodeIdentified { @@ -11,6 +12,8 @@ interface ModelComponentRecord extends DataIdentified, GeodeIdentified { viewer_id: ModelComponentViewerId; name: ModelComponentName; is_active: boolean; + // The simplified light viewable of a mesh component, once the back computed it + binary_light_viewable?: LightViewable; } const modelComponentsTable: TableDefinition = { diff --git a/internal/stores/data/model/light_viewables.ts b/internal/stores/data/model/light_viewables.ts new file mode 100644 index 000000000..9b07bf90d --- /dev/null +++ b/internal/stores/data/model/light_viewables.ts @@ -0,0 +1,72 @@ +import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; +import type { LightViewable } from "@ogw_front/types/data"; +import type { ModelComponentRecord } from "@ogw_internal/database/tables/model_components"; +import type { ModelComponentType } from "@ogw_front/types/model"; +import { modelComponentsDb } from "@ogw_internal/database/accessors.js"; + +interface ComponentLightViewable { + geode_id: ModelComponentId; + binary_light_viewable: LightViewable; +} + +const modelComponentsTable = modelComponentsDb(); + +async function getComponentLightViewables( + modelId: ModelId, +): Promise> { + const components: ModelComponentRecord[] = await modelComponentsTable + .where("data_id") + .equals(modelId) + .toArray(); + const lightViewables: Record = {}; + for (const { geode_id: geodeId, binary_light_viewable: binaryLightViewable } of components) { + if (binaryLightViewable !== undefined) { + lightViewables[geodeId] = binaryLightViewable; + } + } + return lightViewables; +} + +// The type of each component of a model, to style its light viewable +async function getComponentTypes( + modelId: ModelId, +): Promise> { + const components: ModelComponentRecord[] = await modelComponentsTable + .where("data_id") + .equals(modelId) + .toArray(); + return Object.fromEntries(components.map((component) => [component.geode_id, component.type])); +} + +async function setComponentLightViewables( + modelId: ModelId, + lightViewables: readonly Readonly[], +): Promise { + await Promise.all( + lightViewables.map( + async ({ geode_id: geodeId, binary_light_viewable: binaryLightViewable }) => { + await modelComponentsTable + .where("[data_id+geode_id]") + .equals([modelId, geodeId]) + .modify({ binary_light_viewable: binaryLightViewable }); + }, + ), + ); +} + +async function clearComponentLightViewables(modelId: ModelId): Promise { + await modelComponentsTable + .where("data_id") + .equals(modelId) + .modify((component: ModelComponentRecord) => { + Reflect.deleteProperty(component, "binary_light_viewable"); + }); +} + +export { + clearComponentLightViewables, + getComponentLightViewables, + getComponentTypes, + setComponentLightViewables, +}; +export type { ComponentLightViewable }; diff --git a/internal/stores/data_style/mesh/base_style.ts b/internal/stores/data_style/mesh/base_style.ts index 2957a95dc..5c0e12654 100644 --- a/internal/stores/data_style/mesh/base_style.ts +++ b/internal/stores/data_style/mesh/base_style.ts @@ -7,6 +7,7 @@ import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; import { useViewerStore } from "@ogw_front/stores/viewer"; +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; // Local constants @@ -63,6 +64,7 @@ export function useMeshBaseStyle(): MeshBaseStyle { }, { response_function: async () => { + showMeshColorChange(meshId, "mesh", { color }); const mutatedId = await dataStyleState.mutateStyle(meshId, { color }); return mutatedId; }, diff --git a/internal/stores/data_style/mesh/cells/color.ts b/internal/stores/data_style/mesh/cells/color.ts index b91547f85..691416b25 100644 --- a/internal/stores/data_style/mesh/cells/color.ts +++ b/internal/stores/data_style/mesh/cells/color.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshCellsCommonStyle } from "./common"; import { useMeshCellsOpacityStyle } from "./opacity"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -31,6 +32,7 @@ export function useMeshCellsColorStyle(): ReturnType { + showMeshColorChange(meshId, "cells", { color }); const mutateResult = await meshCellsCommonStyle.mutateMeshCellsColoring(meshId, { constant: color, }); diff --git a/internal/stores/data_style/mesh/cells/opacity.ts b/internal/stores/data_style/mesh/cells/opacity.ts index eb0c210f1..3ed70dceb 100644 --- a/internal/stores/data_style/mesh/cells/opacity.ts +++ b/internal/stores/data_style/mesh/cells/opacity.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshCellsCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -34,6 +35,7 @@ export function useMeshCellsOpacityStyle(): { }, { response_function: async () => { + showMeshColorChange(meshId, "cells", { opacity }); const color = meshCellsConstantColor(meshId); if (color === undefined) { return undefined; diff --git a/internal/stores/data_style/mesh/edges/color.ts b/internal/stores/data_style/mesh/edges/color.ts index 9ceb3ebeb..77a772537 100644 --- a/internal/stores/data_style/mesh/edges/color.ts +++ b/internal/stores/data_style/mesh/edges/color.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshEdgesCommonStyle } from "./common"; import { useMeshEdgesOpacityStyle } from "./opacity"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -31,6 +32,7 @@ export function useMeshEdgesColorStyle(): ReturnType { + showMeshColorChange(meshId, "edges", { color }); const mutateResult = await meshEdgesCommonStyle.mutateMeshEdgesColoring(meshId, { constant: color, }); diff --git a/internal/stores/data_style/mesh/edges/opacity.ts b/internal/stores/data_style/mesh/edges/opacity.ts index 99e3580f7..7847e1758 100644 --- a/internal/stores/data_style/mesh/edges/opacity.ts +++ b/internal/stores/data_style/mesh/edges/opacity.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshEdgesCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -34,6 +35,7 @@ export function useMeshEdgesOpacityStyle(): { }, { response_function: async () => { + showMeshColorChange(meshId, "edges", { opacity }); const color = meshEdgesConstantColor(meshId); if (color === undefined) { return undefined; diff --git a/internal/stores/data_style/mesh/edges/width.ts b/internal/stores/data_style/mesh/edges/width.ts index 9d017be35..3f0244c1f 100644 --- a/internal/stores/data_style/mesh/edges/width.ts +++ b/internal/stores/data_style/mesh/edges/width.ts @@ -3,6 +3,7 @@ import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed import type { EdgeWidth } from "@geode/opengeodeweb-viewer/schema_types"; import type { MeshId } from "@ogw_front/types/identifiers"; +import { showMeshSizeChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshEdgesCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -29,6 +30,7 @@ export function useMeshEdgesWidthStyle(): { }, { response_function: async () => { + showMeshSizeChange(meshId, { lineWidth: width }); const mutateResult = await meshEdgesCommonStyle.mutateMeshEdgesStyle(meshId, { width }); return mutateResult; }, diff --git a/internal/stores/data_style/mesh/light_style.ts b/internal/stores/data_style/mesh/light_style.ts new file mode 100644 index 000000000..8020836a6 --- /dev/null +++ b/internal/stores/data_style/mesh/light_style.ts @@ -0,0 +1,55 @@ +import type { + ColorRGB, + EdgeWidth, + Opacity, + PointSize, +} from "@geode/opengeodeweb-viewer/schema_types"; +import { constantOf, rgbOf } from "@ogw_internal/stores/data_style/model/light_colors"; +import type { MeshId } from "@ogw_front/types/identifiers"; +import type { StyleValues } from "@ogw_internal/stores/data_style/types.js"; +import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; + +// The elements whose color the viewer gives a mesh's main actor, the first one present gives the mesh its look +const MAIN_ELEMENTS = ["polyhedra", "polygons", "cells", "edges", "points"] as const; + +type MeshMainElement = (typeof MAIN_ELEMENTS)[number]; + +interface MeshLightStyle { + color: ColorRGB; + opacity: Opacity; + pointSize: PointSize | undefined; + lineWidth: EdgeWidth | undefined; +} + +const WHITE: ColorRGB = { red: 255, green: 255, blue: 255 }; + +function meshMainElement(meshId: MeshId): MeshMainElement | undefined { + const style = useDataStyleState().getStyle(meshId); + return MAIN_ELEMENTS.find((element) => style[element] !== undefined); +} + +function numberOf(style: StyleValues | undefined, key: string): number | undefined { + const value = style?.[key]; + return typeof value === "number" ? value : undefined; +} + +// The light actor of a mesh: its main element's color, whose alpha is the opacity, its points size and edges width +function meshLightStyle(meshId: MeshId): MeshLightStyle { + const style = useDataStyleState().getStyle(meshId); + const element = meshMainElement(meshId); + const sizes = { + pointSize: numberOf(style.points, "size"), + lineWidth: numberOf(style.edges, "width"), + }; + if (element === undefined) { + return { color: WHITE, opacity: 1, ...sizes }; + } + const color = constantOf(style[element]); + if (!color) { + return { color: WHITE, opacity: 1, ...sizes }; + } + return { color: rgbOf(color), opacity: color.alpha, ...sizes }; +} + +export { meshLightStyle, meshMainElement }; +export type { MeshLightStyle, MeshMainElement }; diff --git a/internal/stores/data_style/mesh/light_view.ts b/internal/stores/data_style/mesh/light_view.ts new file mode 100644 index 000000000..46c62a071 --- /dev/null +++ b/internal/stores/data_style/mesh/light_view.ts @@ -0,0 +1,40 @@ +import { + type MeshMainElement, + meshMainElement, +} from "@ogw_internal/stores/data_style/mesh/light_style"; +import type { MeshId } from "@ogw_front/types/identifiers"; +import type { MeshStyleChange } from "@ogw_internal/stores/hybrid_viewer/scene_styles"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; + +// The element a mesh style setter styles; "mesh" for the mesh-wide color +type MeshStyledElement = "mesh" | MeshMainElement; + +// The viewer gives the mesh-wide, polyhedra, polygons and cells colors and opacities to the mesh's +// Main actor; points and edges ones only when they are the mesh's main element (a point set, a curve) +function stylesMainActor(meshId: MeshId, element: MeshStyledElement): boolean { + if (element === "points" || element === "edges") { + return meshMainElement(meshId) === element; + } + return true; +} + +// Called once the viewer applied the change, so the light view looks the same +function showMeshColorChange( + meshId: MeshId, + element: MeshStyledElement, + change: Pick, +): void { + if (stylesMainActor(meshId, element)) { + useHybridViewerStore().setMeshStyle(meshId, change); + } +} + +// The viewer gives the points size and edges width to the main actor of every mesh +function showMeshSizeChange( + meshId: MeshId, + change: Pick, +): void { + useHybridViewerStore().setMeshStyle(meshId, change); +} + +export { showMeshColorChange, showMeshSizeChange }; diff --git a/internal/stores/data_style/mesh/points/color.ts b/internal/stores/data_style/mesh/points/color.ts index e501d59d5..168a79be8 100644 --- a/internal/stores/data_style/mesh/points/color.ts +++ b/internal/stores/data_style/mesh/points/color.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPointsCommonStyle } from "./common"; import { useMeshPointsOpacityStyle } from "./opacity"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -31,6 +32,7 @@ export function useMeshPointsColorStyle(): ReturnType { + showMeshColorChange(meshId, "points", { color }); const mutateResult = await meshPointsCommonStyle.mutateMeshPointsColoring(meshId, { constant: color, }); diff --git a/internal/stores/data_style/mesh/points/opacity.ts b/internal/stores/data_style/mesh/points/opacity.ts index bcb146eb9..5ff3dd72f 100644 --- a/internal/stores/data_style/mesh/points/opacity.ts +++ b/internal/stores/data_style/mesh/points/opacity.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPointsCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -34,6 +35,7 @@ export function useMeshPointsOpacityStyle(): { }, { response_function: async () => { + showMeshColorChange(meshId, "points", { opacity }); const color = meshPointsConstantColor(meshId); if (color === undefined) { return undefined; diff --git a/internal/stores/data_style/mesh/points/size.ts b/internal/stores/data_style/mesh/points/size.ts index f98ce2b25..a25b4821a 100644 --- a/internal/stores/data_style/mesh/points/size.ts +++ b/internal/stores/data_style/mesh/points/size.ts @@ -4,6 +4,7 @@ import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed // Local imports import type { MeshId } from "@ogw_front/types/identifiers"; import type { PointSize } from "@geode/opengeodeweb-viewer/schema_types"; +import { showMeshSizeChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPointsCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -30,6 +31,7 @@ export function useMeshPointsSizeStyle(): { }, { response_function: async () => { + showMeshSizeChange(meshId, { pointSize: size }); const mutateResult = await meshPointsCommonStyle.mutateMeshPointsStyle(meshId, { size }); return mutateResult; }, diff --git a/internal/stores/data_style/mesh/polygons/color.ts b/internal/stores/data_style/mesh/polygons/color.ts index 47323e1b1..89a23b276 100644 --- a/internal/stores/data_style/mesh/polygons/color.ts +++ b/internal/stores/data_style/mesh/polygons/color.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPolygonsCommonStyle } from "./common"; import { useMeshPolygonsOpacityStyle } from "./opacity"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -31,6 +32,7 @@ export function useMeshPolygonsColorStyle(): ReturnType { + showMeshColorChange(meshId, "polygons", { color }); const mutateResult = await meshPolygonsCommonStyle.mutateMeshPolygonsColoring(meshId, { constant: color, }); diff --git a/internal/stores/data_style/mesh/polygons/opacity.ts b/internal/stores/data_style/mesh/polygons/opacity.ts index 0b38df6d4..04d6b77e2 100644 --- a/internal/stores/data_style/mesh/polygons/opacity.ts +++ b/internal/stores/data_style/mesh/polygons/opacity.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPolygonsCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -34,6 +35,7 @@ export function useMeshPolygonsOpacityStyle(): { }, { response_function: async () => { + showMeshColorChange(meshId, "polygons", { opacity }); const color = meshPolygonsConstantColor(meshId); if (color === undefined) { return undefined; diff --git a/internal/stores/data_style/mesh/polyhedra/color.ts b/internal/stores/data_style/mesh/polyhedra/color.ts index 590f7f417..d73b00c48 100644 --- a/internal/stores/data_style/mesh/polyhedra/color.ts +++ b/internal/stores/data_style/mesh/polyhedra/color.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPolyhedraCommonStyle } from "./common"; import { useMeshPolyhedraOpacityStyle } from "./opacity"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -31,6 +32,7 @@ export function useMeshPolyhedraColorStyle(): ReturnType { + showMeshColorChange(meshId, "polyhedra", { color }); const mutation_result = await meshPolyhedraCommonStyle.mutateMeshPolyhedraColoring( meshId, { diff --git a/internal/stores/data_style/mesh/polyhedra/opacity.ts b/internal/stores/data_style/mesh/polyhedra/opacity.ts index c1dfe1d7c..c04b81dbe 100644 --- a/internal/stores/data_style/mesh/polyhedra/opacity.ts +++ b/internal/stores/data_style/mesh/polyhedra/opacity.ts @@ -4,6 +4,7 @@ import type { MeshId } from "@ogw_front/types/identifiers"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; // Local imports +import { showMeshColorChange } from "@ogw_internal/stores/data_style/mesh/light_view"; import { useMeshPolyhedraCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -34,6 +35,7 @@ export function useMeshPolyhedraOpacityStyle(): { }, { response_function: async () => { + showMeshColorChange(meshId, "polyhedra", { opacity }); const color = meshPolyhedraConstantColor(meshId); if (color === undefined) { return undefined; diff --git a/internal/stores/data_style/model/common.ts b/internal/stores/data_style/model/common.ts index 89f40c8c0..68d541582 100644 --- a/internal/stores/data_style/model/common.ts +++ b/internal/stores/data_style/model/common.ts @@ -5,28 +5,14 @@ import { useModelComponentsPerComponentStyleMutation, useModelComponentsStyleMutation, } from "./common_mutations"; +import type { ModelColorSchema, ModelVisibilitySchema } from "./common_schemas"; import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; import type { ColoringType } from "@ogw_front/types/attribute"; import type { GeodeId } from "@geode/opengeodeweb-microservice/schema_types"; import type { ModelComponentType } from "@ogw_front/types/model"; -import type { ParamsOf } from "@ogw_shared/utils/types.js"; import type { StyleValues } from "@ogw_internal/stores/data_style/types.js"; -import { useDataStore } from "@ogw_front/stores/data"; -import { useViewerStore } from "@ogw_front/stores/viewer"; -import type viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; - -type ModelComponentSchemas = (typeof viewer_schemas)["opengeodeweb_viewer"]["model"][ - | "corners" - | "lines" - | "surfaces" - | "blocks"]; -type ModelColorSchema = ModelComponentSchemas["color"]; -type ModelVisibilitySchema = ModelComponentSchemas["visibility"]; -type ModelColorMode = ParamsOf["color_mode"]; - -function isModelColorMode(value: ColoringType): value is ModelColorMode { - return value === "constant" || value === "random"; -} +import { useModelTypeColor } from "./common_color"; +import { useModelTypeVisibility } from "./common_visibility"; interface UseModelCommonStyleReturn { mutateComponentStyle: ( @@ -64,107 +50,12 @@ interface UseModelCommonStyleReturn { ) => Promise; } -// oxlint-disable-next-line max-lines-per-function export function useModelCommonStyle(): UseModelCommonStyleReturn { - const dataStore = useDataStore(); - const viewerStore = useViewerStore(); const { mutateComponentStyle, mutateModelComponentTypeStyle } = useModelComponentStyleMutations(); const { mutateComponentStyles } = useModelComponentsStyleMutation(); const { bulkMutateComponentStylesPerComponent } = useModelComponentsPerComponentStyleMutation(); - async function setModelTypeColor( - modelId: ModelId, - componentIds: ModelComponentId[], - color: ColorRGBA | undefined, - schema: ModelColorSchema, - activeColoring = "constant", - collectionId?: GeodeId, - ): Promise { - if (!componentIds?.length) { - return undefined; - } - - const viewer_ids = await dataStore.getMeshComponentsViewerIds(modelId, componentIds); - if (!viewer_ids?.length) { - return undefined; - } - - if (activeColoring === "constant") { - await mutateComponentStyles(modelId, componentIds, { - coloring: { - constant: color, - }, - }); - } - if (!isModelColorMode(activeColoring)) { - throw new Error(`Unknown model color mode: ${activeColoring}`); - } - const params = { - id: modelId, - block_ids: viewer_ids, - color_mode: activeColoring, - collection_id: collectionId, - ...(activeColoring === "constant" && { color }), - }; - - return viewerStore.request( - { schema, params }, - { - response_function: async ({ colors }) => { - if (activeColoring === "constant") { - await mutateComponentStyles(modelId, componentIds, { - coloring: { - constant: color, - }, - }); - return; - } - - if (colors.length === 0) { - return; - } - - await bulkMutateComponentStylesPerComponent( - modelId, - colors.map(({ geode_id, color: color_value }) => ({ - id_component: geode_id, - values: { - coloring: { - constant: color_value, - }, - }, - })), - ); - }, - }, - ); - } - - async function setModelTypeVisibility( - modelId: ModelId, - componentIds: ModelComponentId[], - visibility: Visibility, - schema: ModelVisibilitySchema, - ): Promise { - if (!componentIds?.length) { - return undefined; - } - - const viewer_ids = await dataStore.getMeshComponentsViewerIds(modelId, componentIds); - if (!viewer_ids?.length) { - return undefined; - } - const params = { id: modelId, block_ids: viewer_ids, visibility }; - const result = await viewerStore.request( - { schema, params }, - { - response_function: async () => { - await mutateComponentStyles(modelId, componentIds, { visibility }); - }, - }, - ); - return result; - } - + const { setModelTypeColor } = useModelTypeColor(); + const { setModelTypeVisibility } = useModelTypeVisibility(); return { mutateComponentStyle, mutateModelComponentTypeStyle, diff --git a/internal/stores/data_style/model/common_color.ts b/internal/stores/data_style/model/common_color.ts new file mode 100644 index 000000000..38bd6ff03 --- /dev/null +++ b/internal/stores/data_style/model/common_color.ts @@ -0,0 +1,138 @@ +import type { ModelColorMode, ModelColorSchema } from "./common_schemas"; +import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; +import { + useModelComponentsPerComponentStyleMutation, + useModelComponentsStyleMutation, +} from "./common_mutations"; +import type { ColorRGBA } from "@geode/opengeodeweb-viewer/schema_types"; +import type { ColoringType } from "@ogw_front/types/attribute"; +import type { GeodeId } from "@geode/opengeodeweb-microservice/schema_types"; +import type { ResponseOf } from "@ogw_shared/utils/types.js"; +import type { StyleValues } from "@ogw_internal/stores/data_style/types.js"; +import { useDataStore } from "@ogw_front/stores/data"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; +import { useViewerStore } from "@ogw_front/stores/viewer"; + +function isModelColorMode(value: ColoringType): value is ModelColorMode { + return value === "constant" || value === "random"; +} + +interface UseModelTypeColorReturn { + setModelTypeColor: ( + modelId: ModelId, + componentIds: ModelComponentId[], + color: ColorRGBA | undefined, + schema: ModelColorSchema, + activeColoring?: ColoringType, + collectionId?: GeodeId, + ) => Promise; +} + +interface ColorMutations { + mutateComponentStyles: ReturnType< + typeof useModelComponentsStyleMutation + >["mutateComponentStyles"]; + bulkMutateComponentStylesPerComponent: ReturnType< + typeof useModelComponentsPerComponentStyleMutation + >["bulkMutateComponentStylesPerComponent"]; +} + +interface ColorRequest { + modelId: ModelId; + componentIds: ModelComponentId[]; + color: ColorRGBA | undefined; + activeColoring: ModelColorMode; +} + +function constantColoring(color: ColorRGBA | undefined): StyleValues { + return { coloring: { constant: color } }; +} + +// Stores the colors the viewer applied, the constant one or one per component otherwise, and shows them in the light view +function colorResponseFunction( + mutations: Readonly, + { modelId, componentIds, color, activeColoring }: Readonly, +): (response: ResponseOf) => Promise { + return async ({ colors }) => { + const hybridViewerStore = useHybridViewerStore(); + if (activeColoring === "constant") { + if (color) { + hybridViewerStore.setComponentsColors( + modelId, + Object.fromEntries(componentIds.map((componentId) => [componentId, color])), + ); + } + await mutations.mutateComponentStyles(modelId, componentIds, constantColoring(color)); + return; + } + if (colors.length === 0) { + return; + } + hybridViewerStore.setComponentsColors( + modelId, + Object.fromEntries( + colors.map((componentColor) => [componentColor.geode_id, componentColor.color]), + ), + ); + await mutations.bulkMutateComponentStylesPerComponent( + modelId, + colors.map((componentColor) => ({ + id_component: componentColor.geode_id, + values: constantColoring(componentColor.color), + })), + ); + }; +} + +function useModelTypeColor(): UseModelTypeColorReturn { + const dataStore = useDataStore(); + const viewerStore = useViewerStore(); + const mutations: ColorMutations = { + ...useModelComponentsStyleMutation(), + ...useModelComponentsPerComponentStyleMutation(), + }; + async function setModelTypeColor( + modelId: ModelId, + componentIds: ModelComponentId[], + color: ColorRGBA | undefined, + schema: ModelColorSchema, + activeColoring = "constant", + collectionId?: GeodeId, + ): Promise { + if (!componentIds?.length) { + return undefined; + } + const viewerIds = await dataStore.getMeshComponentsViewerIds(modelId, componentIds); + if (!viewerIds?.length) { + return undefined; + } + if (activeColoring === "constant") { + await mutations.mutateComponentStyles(modelId, componentIds, constantColoring(color)); + } + if (!isModelColorMode(activeColoring)) { + throw new Error(`Unknown model color mode: ${activeColoring}`); + } + const params = { + id: modelId, + block_ids: viewerIds, + color_mode: activeColoring, + collection_id: collectionId, + ...(activeColoring === "constant" && { color }), + }; + return viewerStore.request( + { schema, params }, + { + response_function: colorResponseFunction(mutations, { + modelId, + componentIds, + color, + activeColoring, + }), + }, + ); + } + + return { setModelTypeColor }; +} + +export { useModelTypeColor }; diff --git a/internal/stores/data_style/model/common_schemas.ts b/internal/stores/data_style/model/common_schemas.ts new file mode 100644 index 000000000..6e7b48848 --- /dev/null +++ b/internal/stores/data_style/model/common_schemas.ts @@ -0,0 +1,13 @@ +import type { ParamsOf } from "@ogw_shared/utils/types.js"; +import type viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; + +type ModelComponentSchemas = (typeof viewer_schemas)["opengeodeweb_viewer"]["model"][ + | "corners" + | "lines" + | "surfaces" + | "blocks"]; +type ModelColorSchema = ModelComponentSchemas["color"]; +type ModelVisibilitySchema = ModelComponentSchemas["visibility"]; +type ModelColorMode = ParamsOf["color_mode"]; + +export type { ModelColorMode, ModelColorSchema, ModelVisibilitySchema }; diff --git a/internal/stores/data_style/model/common_visibility.ts b/internal/stores/data_style/model/common_visibility.ts new file mode 100644 index 000000000..d2e5e1d87 --- /dev/null +++ b/internal/stores/data_style/model/common_visibility.ts @@ -0,0 +1,54 @@ +import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; +import type { ModelVisibilitySchema } from "./common_schemas"; +import type { Visibility } from "@geode/opengeodeweb-viewer/schema_types"; +import { useDataStore } from "@ogw_front/stores/data"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; +import { useModelComponentsStyleMutation } from "./common_mutations"; +import { useViewerStore } from "@ogw_front/stores/viewer"; + +interface UseModelTypeVisibilityReturn { + setModelTypeVisibility: ( + modelId: ModelId, + componentIds: ModelComponentId[], + visibility: Visibility, + schema: ModelVisibilitySchema, + ) => Promise; +} + +function useModelTypeVisibility(): UseModelTypeVisibilityReturn { + const dataStore = useDataStore(); + const viewerStore = useViewerStore(); + const { mutateComponentStyles } = useModelComponentsStyleMutation(); + + async function setModelTypeVisibility( + modelId: ModelId, + componentIds: ModelComponentId[], + visibility: Visibility, + schema: ModelVisibilitySchema, + ): Promise { + if (!componentIds?.length) { + return undefined; + } + + const viewerIds = await dataStore.getMeshComponentsViewerIds(modelId, componentIds); + if (!viewerIds?.length) { + return undefined; + } + const params = { id: modelId, block_ids: viewerIds, visibility }; + const result = await viewerStore.request( + { schema, params }, + { + response_function: async () => { + await mutateComponentStyles(modelId, componentIds, { visibility }); + // The light view shown while the camera moves follows the components too + useHybridViewerStore().setComponentsVisibility(modelId, componentIds, visibility); + }, + }, + ); + return result; + } + + return { setModelTypeVisibility }; +} + +export { useModelTypeVisibility }; diff --git a/internal/stores/data_style/model/hidden_components.ts b/internal/stores/data_style/model/hidden_components.ts new file mode 100644 index 000000000..b39912089 --- /dev/null +++ b/internal/stores/data_style/model/hidden_components.ts @@ -0,0 +1,16 @@ +import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; +import type { ModelComponentStyle } from "@ogw_internal/stores/data_style/types.js"; +import { componentDataStyleDb } from "@ogw_internal/database/accessors"; + +// The components of a model whose stored style hides them +async function hiddenComponentIds(modelId: ModelId): Promise> { + const styles: ModelComponentStyle[] = await componentDataStyleDb() + .where("id_model") + .equals(modelId) + .toArray(); + return new Set( + styles.filter((style) => style.visibility === false).map((style) => style.id_component), + ); +} + +export { hiddenComponentIds }; diff --git a/internal/stores/data_style/model/light_colors.ts b/internal/stores/data_style/model/light_colors.ts new file mode 100644 index 000000000..01a1ee211 --- /dev/null +++ b/internal/stores/data_style/model/light_colors.ts @@ -0,0 +1,62 @@ +import type { ColorRGB, ColorRGBA, PointSize } from "@geode/opengeodeweb-viewer/schema_types"; +import { + DEFAULT_MODEL_COMPONENT_TYPE_COLORS, + MODEL_DEFAULT_COLOR, + POINTS_DEFAULT_SIZE, + SURFACES_DEFAULT_COLOR, +} from "@ogw_front/utils/default_styles/constants"; +import type { ModelComponentId, ModelId } from "@ogw_front/types/identifiers"; +import type { ModelComponentType } from "@ogw_front/types/model"; +import type { StyleValues } from "@ogw_internal/stores/data_style/types.js"; +import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; + +// The light view draws opaque models: the alpha is dropped +function rgbOf({ red, green, blue }: ColorRGBA): ColorRGB { + return { red, green, blue }; +} + +function constantOf(style: StyleValues | undefined): ColorRGBA | undefined { + // oxlint-disable-next-line no-unsafe-type-assertion -- coloring shape is defined by the data style schema. + const coloring = style?.coloring as StyleValues | undefined; + // oxlint-disable-next-line no-unsafe-type-assertion -- a constant coloring is a ColorRGBA. + return coloring?.constant as ColorRGBA | undefined; +} + +// The model style of a component type, e.g. its "surfaces" for a Surface +function modelTypeStyle(modelId: ModelId, type: ModelComponentType): StyleValues | undefined { + // oxlint-disable-next-line no-unsafe-type-assertion -- style values are loosely-typed StyleValues records. + return useDataStyleState().getStyle(modelId)[`${type.toLowerCase()}s`] as StyleValues | undefined; +} + +// The color the viewer draws a component with: its own, else its type group's, else the model's +// Color of its type, else its type's default +function componentLightColors( + modelId: ModelId, + types: Readonly>, +): Record { + const dataStyleState = useDataStyleState(); + const colors: Record = {}; + for (const [componentId, type] of Object.entries(types)) { + const color = + constantOf(dataStyleState.getComponentStyle(modelId, componentId)) ?? + constantOf(dataStyleState.getModelComponentTypeStyle(modelId, type)) ?? + constantOf(modelTypeStyle(modelId, type)) ?? + DEFAULT_MODEL_COMPONENT_TYPE_COLORS[type] ?? + MODEL_DEFAULT_COLOR; + colors[componentId] = rgbOf(color); + } + return colors; +} + +// The bounding box shown before the detail stands for the model's surfaces +function modelBoxLightColor(modelId: ModelId): ColorRGB { + return rgbOf(constantOf(modelTypeStyle(modelId, "Surface")) ?? SURFACES_DEFAULT_COLOR); +} + +// The viewer draws a model's corners with the model's points size +function modelLightPointSize(modelId: ModelId): PointSize { + const size = useDataStyleState().getStyle(modelId).points?.size; + return typeof size === "number" ? size : POINTS_DEFAULT_SIZE; +} + +export { componentLightColors, constantOf, modelBoxLightColor, modelLightPointSize, rgbOf }; diff --git a/internal/stores/data_style/model/points/size.ts b/internal/stores/data_style/model/points/size.ts index 34ff48247..5b1b18c2d 100644 --- a/internal/stores/data_style/model/points/size.ts +++ b/internal/stores/data_style/model/points/size.ts @@ -8,6 +8,7 @@ import { } from "@ogw_internal/stores/data_style/model/points/component"; import type { ModelId } from "@ogw_front/types/identifiers"; import type { PointSize } from "@geode/opengeodeweb-viewer/schema_types"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; import { useModelPointsCommonStyle } from "./common"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -38,6 +39,7 @@ export function useModelPointsSizeStyle(): { }, { response_function: async () => { + useHybridViewerStore().setPointSize(modelId, size); const [mutateResult] = await Promise.all([ modelPointsCommonStyle.mutateModelPointsStyle(modelId, { size }), ...componentsPointsStyles.map(async (pointsStyle) => { diff --git a/internal/stores/hybrid_viewer/camera.ts b/internal/stores/hybrid_viewer/camera.ts index 146f5d198..3cd425794 100644 --- a/internal/stores/hybrid_viewer/camera.ts +++ b/internal/stores/hybrid_viewer/camera.ts @@ -12,6 +12,7 @@ import type { CameraOptions } from "./vtk_types"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { ZScale } from "@ogw_front/types/geometry"; import { animateCameraOrientation } from "./camera_orientation"; +import { entrySceneBounds } from "./parts"; import { useHybridViewerScene } from "./scene"; import { useViewerStore } from "@ogw_front/stores/viewer"; import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; @@ -99,8 +100,9 @@ const useHybridViewerCamera = createSharedComposable(() => { return; } const viewerStore = useViewerStore(); - let bounds: [number, number, number, number, number, number] = - hybridDb[dataId].actor.getBounds(); + let bounds: [number, number, number, number, number, number] = entrySceneBounds( + hybridDb[dataId], + ); if (block_ids.length > 0) { const response = await viewerStore.request({ schema: viewer_schemas.opengeodeweb_viewer.model.get_blocks_bounds, diff --git a/internal/stores/hybrid_viewer/cell_colors.ts b/internal/stores/hybrid_viewer/cell_colors.ts new file mode 100644 index 000000000..e48cb20e5 --- /dev/null +++ b/internal/stores/hybrid_viewer/cell_colors.ts @@ -0,0 +1,55 @@ +import type { ColorRGB } from "@geode/opengeodeweb-viewer/schema_types"; +import type { HybridPart } from "./vtk_types"; + +const CHANNELS = 3; + +// The cell ids [start, end) of one part in the merged polydata +type CellRange = [number, number]; + +type WritableColors = Record; + +// VTK numbers the cells of a polydata verts, lines, polys, then strips, each kind part by part +// As the merge concatenates them +const CELL_ID_ORDER = ["Verts", "Lines", "Polys", "Strips"] as const; + +function cellRanges(parts: readonly HybridPart[]): { ranges: CellRange[][]; cellCount: number } { + const ranges: CellRange[][] = parts.map(() => []); + let cellCount = 0; + for (const kind of CELL_ID_ORDER) { + for (const [index, part] of parts.entries()) { + const count = part.polydata[`get${kind}`]().getNumberOfCells(); + if (count > 0) { + ranges[index]?.push([cellCount, cellCount + count]); + } + cellCount += count; + } + } + return { ranges, cellCount }; +} + +function fillRanges(colors: WritableColors, ranges: readonly CellRange[], color: ColorRGB): void { + const channels = [color.red, color.green, color.blue]; + for (const [start, end] of ranges) { + for (let cell = start; cell < end; cell += 1) { + for (const [channel, value] of channels.entries()) { + colors[cell * CHANNELS + channel] = value; + } + } + } +} + +// One 0-255 RGB triple per cell of the merged parts, and the cell ranges of each part +function buildCellColors(parts: readonly HybridPart[]): { + colors: Uint8Array; + ranges: CellRange[][]; +} { + const { ranges, cellCount } = cellRanges(parts); + const colors = new Uint8Array(cellCount * CHANNELS); + for (const [index, part] of parts.entries()) { + fillRanges(colors, ranges[index] ?? [], part.color); + } + return { colors, ranges }; +} + +export { CHANNELS, buildCellColors, fillRanges }; +export type { CellRange }; diff --git a/internal/stores/hybrid_viewer/detail.ts b/internal/stores/hybrid_viewer/detail.ts new file mode 100644 index 000000000..666d0bda7 --- /dev/null +++ b/internal/stores/hybrid_viewer/detail.ts @@ -0,0 +1,119 @@ +import { + getComponentLightViewables, + getComponentTypes, + setComponentLightViewables, +} from "@ogw_internal/stores/data/model/light_viewables"; +import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; +import type { LightViewable } from "@ogw_front/types/data"; +import type { ModelComponentId } from "@ogw_front/types/identifiers"; +import type { ModelComponentType } from "@ogw_front/types/model"; +import type { PartId } from "./vtk_types"; +import back_schemas from "@geode/opengeodeweb-back/opengeodeweb_back_typed_schemas.js"; +import { hiddenComponentIds } from "@ogw_internal/stores/data_style/model/hidden_components"; +import { isModel } from "@ogw_front/utils/viewer_object_type"; +import { useBackStore } from "@ogw_front/stores/back"; +import { useDataStore } from "@ogw_front/stores/data"; + +interface RefineOptions { + isInScene: (dataId: DataId) => boolean; + rebuild: (dataId: DataId) => Promise; +} + +// The latest request of each data: an older answer must not replace a newer geometry +const requestTokens = new Map(); + +function nextToken(dataId: DataId): number { + const token = (requestTokens.get(dataId) ?? 0) + 1; + requestTokens.set(dataId, token); + return token; +} + +// A pending answer for dataId is ignored, e.g. once its geometry moved +function cancelRefine(dataId: DataId): void { + nextToken(dataId); +} + +// The light viewables to build the scene actor from: the stored detail, else the bounding box +async function lightViewablesOf(dataId: DataId): Promise> { + const item = await useDataStore().item(dataId); + if (isModel(item)) { + const components = await getComponentLightViewables(dataId); + if (Object.keys(components).length > 0) { + return components; + } + } + if (item.binary_light_viewable === undefined) { + return {}; + } + return { [dataId]: item.binary_light_viewable }; +} + +// A mesh has no components to type +async function componentTypesOf( + dataId: DataId, + isModelItem: boolean, +): Promise> { + if (!isModelItem) { + return {}; + } + const types = await getComponentTypes(dataId); + return types; +} + +interface EntrySources { + lightViewables: Record; + hidden: Set; + isModel: boolean; + // The type of each component of a model, to style its part + types: Record; +} + +// One light viewable per part (the stored detail of each model component, else the item's own), +// The components already hidden by their style, and the component types +async function entrySourcesOf(dataId: DataId): Promise { + const dataStore = useDataStore(); + const isViewable = await dataStore.fetchIsViewable(dataId); + if (!isViewable) { + return { lightViewables: {}, hidden: new Set(), isModel: false, types: {} }; + } + const isModelItem = isModel(await dataStore.item(dataId)); + const [lightViewables, hidden, types] = await Promise.all([ + lightViewablesOf(dataId), + hiddenComponentIds(dataId), + componentTypesOf(dataId, isModelItem), + ]); + return { lightViewables, hidden, isModel: isModelItem, types }; +} + +// Asks the back for the simplified light viewable, stores it and rebuilds the scene actor +async function refineSceneItem( + dataId: DataId, + { isInScene, rebuild }: RefineOptions, +): Promise { + const token = nextToken(dataId); + function isCurrent(): boolean { + return requestTokens.get(dataId) === token && isInScene(dataId); + } + const response = await useBackStore().request({ + schema: back_schemas.opengeodeweb_back.light_viewable, + params: { id: dataId }, + }); + if (!isCurrent()) { + return; + } + if (response.mesh_components) { + await setComponentLightViewables(dataId, response.mesh_components); + } else if (response.binary_light_viewable !== undefined) { + await useDataStore().updateItem(dataId, { + binary_light_viewable: response.binary_light_viewable, + }); + } + // Cancelled while stored, e.g. a CRS change started: its bounding box stays + if (!isCurrent()) { + return; + } + await rebuild(dataId); +} + +export { cancelRefine, entrySourcesOf, lightViewablesOf, refineSceneItem }; +export type { EntrySources }; diff --git a/internal/stores/hybrid_viewer/entry_styles.ts b/internal/stores/hybrid_viewer/entry_styles.ts new file mode 100644 index 000000000..3a4c64c25 --- /dev/null +++ b/internal/stores/hybrid_viewer/entry_styles.ts @@ -0,0 +1,46 @@ +import type { HybridDbEntry, PartId } from "./vtk_types"; +import { + componentLightColors, + modelBoxLightColor, + modelLightPointSize, +} from "@ogw_internal/stores/data_style/model/light_colors"; +import type { ColorRGB } from "@geode/opengeodeweb-viewer/schema_types"; +import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; +import type { EntrySources } from "./detail"; +import { meshLightStyle } from "@ogw_internal/stores/data_style/mesh/light_style"; + +// The color of each part as the viewer draws it: a model component's color (its bounding box takes +// The model's surfaces color), else the mesh's +function partColors( + dataId: DataId, + { lightViewables, isModel, types }: Readonly, +): Record { + const partIds = Object.keys(lightViewables); + if (!isModel) { + const { color } = meshLightStyle(dataId); + return Object.fromEntries(partIds.map((partId) => [partId, color])); + } + const colors = componentLightColors(dataId, types); + const boxColor = modelBoxLightColor(dataId); + return Object.fromEntries(partIds.map((partId) => [partId, colors[partId] ?? boxColor])); +} + +// A mesh actor takes the opacity, point size and line width the viewer gives the mesh +function applyMeshActorStyle(entry: HybridDbEntry, meshId: DataId): void { + const { opacity, pointSize, lineWidth } = meshLightStyle(meshId); + const property = entry.actor.getProperty(); + property.setOpacity(opacity); + if (pointSize !== undefined) { + property.setPointSize(pointSize); + } + if (lineWidth !== undefined) { + property.setLineWidth(lineWidth); + } +} + +// A model actor draws its corners with the model's points size; its lines stay one pixel wide +function applyModelActorStyle(entry: HybridDbEntry, modelId: DataId): void { + entry.actor.getProperty().setPointSize(modelLightPointSize(modelId)); +} + +export { applyMeshActorStyle, applyModelActorStyle, partColors }; diff --git a/internal/stores/hybrid_viewer/explode.ts b/internal/stores/hybrid_viewer/explode.ts index fb6ac4018..81c3c9471 100644 --- a/internal/stores/hybrid_viewer/explode.ts +++ b/internal/stores/hybrid_viewer/explode.ts @@ -13,17 +13,13 @@ interface WritablePoints { } // The light viewable shows the compact data: stretch it along z over the exploded data bounds, so the simplified view seen while the camera moves stays as tall and as high as the exploded data. +// The compact z range is the one of the whole data, so the parts of a model stretch as one object. function explodeAlongZ( - compactPoints: Float64Array, + compactPoints: ArrayLike, points: WritablePoints, explodedBounds: Bounds, + [compactZMin, compactZMax]: readonly [number, number], ): void { - let compactZMin = Infinity; - let compactZMax = -Infinity; - for (let index = Z_OFFSET; index < compactPoints.length; index += COORDINATES) { - compactZMin = Math.min(compactZMin, compactPoints[index] ?? compactZMin); - compactZMax = Math.max(compactZMax, compactPoints[index] ?? compactZMax); - } const explodedZMin = explodedBounds[Z_MIN_BOUND] ?? compactZMin; const explodedZMax = explodedBounds[Z_MAX_BOUND] ?? compactZMax; const ratio = diff --git a/internal/stores/hybrid_viewer/filters.ts b/internal/stores/hybrid_viewer/filters.ts index 0beeed0a6..dda5ab25d 100644 --- a/internal/stores/hybrid_viewer/filters.ts +++ b/internal/stores/hybrid_viewer/filters.ts @@ -7,7 +7,6 @@ import type { import type { FilterFactor, Index } from "@ogw_front/types/ui"; import type { JsonRpcSchema, ParamsOf, ResponseOf } from "@ogw_shared/utils/types.js"; import type { SliceLayer, SliceMaxLayers } from "@ogw_front/composables/clipping_slices"; -import { explodeAlongZ, followCenter } from "./explode"; import { requireRenderWindow, useHybridViewerCore } from "./core"; import viewer_schemas, { type ViewerClippingPlanesParams, @@ -15,6 +14,8 @@ import viewer_schemas, { import type { Bounds } from "@ogw_front/types/geometry"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { SliceAxis } from "@ogw_front/utils/slice"; +import { followCenter } from "./explode"; +import { setEntryExplodedBounds } from "./parts"; import { useHybridViewerCamera } from "./camera"; import { useHybridViewerScene } from "./scene"; import { useViewerStore } from "@ogw_front/stores/viewer"; @@ -57,10 +58,7 @@ function explodeLightViewables(explodedBounds: { id: DataId; bounds: Bounds }[]) for (const { id, bounds } of explodedBounds) { const entry = hybridDb[id]; if (entry) { - const points = entry.polydata.getPoints(); - explodeAlongZ(entry.compactPoints, points.getData(), bounds); - points.modified(); - entry.polydata.modified(); + setEntryExplodedBounds(entry, bounds); } } const camera = renderer.getActiveCamera(); diff --git a/internal/stores/hybrid_viewer/merge.ts b/internal/stores/hybrid_viewer/merge.ts new file mode 100644 index 000000000..9daedad5a --- /dev/null +++ b/internal/stores/hybrid_viewer/merge.ts @@ -0,0 +1,66 @@ +import { + newInstance as newPolyData, + type vtkPolyData, +} from "@kitware/vtk.js/Common/DataModel/PolyData"; + +const COORDINATES = 3; +const CELL_KINDS = ["Verts", "Lines", "Strips", "Polys"] as const; + +type CellKind = (typeof CELL_KINDS)[number]; + +function cellsOf(polydata: vtkPolyData, kind: CellKind): Uint32Array { + return Uint32Array.from(polydata[`get${kind}`]().getData()); +} + +// The cells of one polydata, their point ids shifted past the points merged before it +function shiftedCells(cells: Uint32Array, pointOffset: number): Uint32Array { + const shifted = Uint32Array.from(cells); + let index = 0; + while (index < shifted.length) { + const size = shifted[index] ?? 0; + for (let point = index + 1; point <= index + size; point += 1) { + shifted[point] = (shifted[point] ?? 0) + pointOffset; + } + index += size + 1; + } + return shifted; +} + +function concatenated(arrays: readonly Uint32Array[]): Uint32Array { + const result = new Uint32Array(arrays.reduce((total, array) => total + array.length, 0)); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} + +// One polydata with the points and cells of all the given ones, drawn by a single actor. +// Always a new polydata with its own points: stretching it leaves the sources untouched. +function mergePolydata(sources: readonly vtkPolyData[]): vtkPolyData { + const pointOffsets: number[] = []; + let pointCount = 0; + for (const source of sources) { + pointOffsets.push(pointCount); + pointCount += source.getPoints().getNumberOfPoints(); + } + const points = new Float64Array(pointCount * COORDINATES); + for (const [index, source] of sources.entries()) { + points.set(source.getPoints().getData(), (pointOffsets[index] ?? 0) * COORDINATES); + } + const merged = newPolyData(); + merged.getPoints().setData(points, COORDINATES); + for (const kind of CELL_KINDS) { + merged[`get${kind}`]().setData( + concatenated( + sources.map((source, index) => + shiftedCells(cellsOf(source, kind), pointOffsets[index] ?? 0), + ), + ), + ); + } + return merged; +} + +export { mergePolydata }; diff --git a/internal/stores/hybrid_viewer/parts.ts b/internal/stores/hybrid_viewer/parts.ts new file mode 100644 index 000000000..7113a0317 --- /dev/null +++ b/internal/stores/hybrid_viewer/parts.ts @@ -0,0 +1,178 @@ +import { CHANNELS, buildCellColors, fillRanges } from "./cell_colors"; +import type { HybridDbEntry, HybridPart, PartId } from "./vtk_types"; +import type { Bounds } from "@kitware/vtk.js/types"; +import type { ColorRGB } from "@geode/opengeodeweb-viewer/schema_types"; +import { Resolve } from "@kitware/vtk.js/Rendering/Core/Mapper/CoincidentTopologyHelper"; +import { explodeAlongZ } from "./explode"; +import { mergePolydata } from "./merge"; +import { newInstance as newActor } from "@kitware/vtk.js/Rendering/Core/Actor"; +import { newInstance as newDataArray } from "@kitware/vtk.js/Common/Core/DataArray"; +import { newInstance as newMapper } from "@kitware/vtk.js/Rendering/Core/Mapper"; + +const Z_MIN_BOUND = 4; +const Z_MAX_BOUND = 5; + +function entryParts(entry: HybridDbEntry): HybridPart[] { + return Object.values(entry.parts); +} + +function visibleParts(entry: HybridDbEntry): HybridPart[] { + return entryParts(entry).filter((part) => part.componentVisible); +} + +// The compact bounds of every part, hidden ones included +function partsBounds(entry: HybridDbEntry): Bounds { + let bounds: Bounds = [Infinity, -Infinity, Infinity, -Infinity, Infinity, -Infinity]; + for (const part of entryParts(entry)) { + const partBounds = part.polydata.getBounds(); + bounds = [ + Math.min(bounds[0], partBounds[0]), + Math.max(bounds[1], partBounds[1]), + Math.min(bounds[2], partBounds[2]), + Math.max(bounds[3], partBounds[3]), + Math.min(bounds[4], partBounds[4]), + Math.max(bounds[5], partBounds[5]), + ]; + } + return bounds; +} + +function compactZRange(entry: HybridDbEntry): [number, number] { + const bounds = partsBounds(entry); + return [bounds[Z_MIN_BOUND], bounds[Z_MAX_BOUND]]; +} + +// Hidden parts count, like a hidden actor's geometry; an exploded entry spans its exploded z +function entryBounds(entry: HybridDbEntry): Bounds { + const bounds = partsBounds(entry); + if (!entry.explodedBounds) { + return bounds; + } + return [ + bounds[0], + bounds[1], + bounds[2], + bounds[3], + entry.explodedBounds[Z_MIN_BOUND] ?? bounds[Z_MIN_BOUND], + entry.explodedBounds[Z_MAX_BOUND] ?? bounds[Z_MAX_BOUND], + ]; +} + +// The bounds as drawn in the scene: the entry's ones, stretched by the z-scaling of its actor +function entrySceneBounds(entry: HybridDbEntry): Bounds { + const bounds = entryBounds(entry); + const zScale = entry.actor.getScale()[2] ?? 1; + const zFirst = bounds[Z_MIN_BOUND] * zScale; + const zSecond = bounds[Z_MAX_BOUND] * zScale; + return [ + bounds[0], + bounds[1], + bounds[2], + bounds[3], + Math.min(zFirst, zSecond), + Math.max(zFirst, zSecond), + ]; +} + +function applyEntryVisibility(entry: HybridDbEntry): void { + entry.actor.setVisibility(entry.modelVisible && visibleParts(entry).length > 0); +} + +// The actor draws the visible parts merged, stretched along z while the data is exploded. +// The compact z range is the one of all the parts, so hiding one does not move the others. +function refreshEntryGeometry(entry: HybridDbEntry): void { + const visibleEntries = Object.entries(entry.parts).filter(([, part]) => part.componentVisible); + const merged = mergePolydata(visibleEntries.map(([, part]) => part.polydata)); + if (entry.explodedBounds) { + const points = merged.getPoints().getData(); + explodeAlongZ(points, points, entry.explodedBounds, compactZRange(entry)); + } + const { colors, ranges } = buildCellColors(visibleEntries.map(([, part]) => part)); + merged + .getCellData() + .setScalars(newDataArray({ name: "colors", numberOfComponents: CHANNELS, values: colors })); + entry.cellRanges = Object.fromEntries( + visibleEntries.map(([partId], index) => [partId, ranges[index] ?? []]), + ); + entry.polydata = merged; + entry.mapper.setInputData(merged); + applyEntryVisibility(entry); +} + +function newHybridEntry(parts: Record, modelVisible: boolean): HybridDbEntry { + const mapper = newMapper(); + // Each part is drawn in its own color, carried by the cells + mapper.setScalarModeToUseCellData(); + mapper.setColorModeToDirectScalars(); + // As the viewer does, corners and lines lying on surfaces are drawn in front of them instead of + // Fighting with them for depth (vtk.js leaves it off by default, VTK turns it on) + mapper.setResolveCoincidentTopology(Resolve.PolygonOffset); + const actor = newActor(); + actor.setMapper(mapper); + const entry: HybridDbEntry = { + actor, + mapper, + polydata: mergePolydata([]), + cellRanges: {}, + parts, + modelVisible, + explodedBounds: undefined, + }; + refreshEntryGeometry(entry); + return entry; +} + +function setEntryModelVisibility(entry: HybridDbEntry, visibility: boolean): void { + entry.modelVisible = visibility; + applyEntryVisibility(entry); +} + +// Ids without a part (blocks, collections) are ignored +function setPartsComponentVisibility( + entry: HybridDbEntry, + componentIds: Iterable, + visibility: boolean, +): void { + for (const componentId of componentIds) { + const part = entry.parts[componentId]; + if (part) { + part.componentVisible = visibility; + } + } + refreshEntryGeometry(entry); +} + +// The parts take color at once, without merging the geometry again; ids without a part are ignored +function setPartsColor(entry: HybridDbEntry, partIds: Iterable, color: ColorRGB): void { + const scalars = entry.polydata.getCellData().getScalars(); + for (const partId of partIds) { + const part = entry.parts[partId]; + if (part) { + part.color = color; + fillRanges(scalars.getData(), entry.cellRanges[partId] ?? [], color); + } + } + scalars.modified(); + // VTK uploads the colors again only when the polydata itself is modified, not its arrays + entry.polydata.modified(); +} + +// Undefined bounds make the entry compact again +function setEntryExplodedBounds( + entry: HybridDbEntry, + explodedBounds: Readonly, +): void { + entry.explodedBounds = explodedBounds && [...explodedBounds]; + refreshEntryGeometry(entry); +} + +export { + compactZRange, + entryBounds, + entrySceneBounds, + newHybridEntry, + setEntryExplodedBounds, + setEntryModelVisibility, + setPartsColor, + setPartsComponentVisibility, +}; diff --git a/internal/stores/hybrid_viewer/scene.ts b/internal/stores/hybrid_viewer/scene.ts index 3d086d1a3..ce6259abf 100644 --- a/internal/stores/hybrid_viewer/scene.ts +++ b/internal/stores/hybrid_viewer/scene.ts @@ -1,15 +1,19 @@ +import type { HybridDb, PartId } from "./vtk_types"; import { addSceneActor, clearSceneActors, + refineSceneActor, removeSceneActor, setSceneActorVisibility, + setSceneComponentsVisibility, } from "./scene_actors"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; -import type { HybridDb } from "./vtk_types"; import type { Visibility } from "@geode/opengeodeweb-viewer/schema_types"; import type { ZScale } from "@ogw_front/types/geometry"; import { applyZScaling } from "./scene_z_scaling"; +import { cancelRefine } from "./detail"; import { setBackgroundColor } from "./scene_background"; +import { useSceneStyles } from "./scene_styles"; // Shared via createSharedComposable (rather than merged into the parent hybridViewer store) so sibling slices, e.g. camera.ts and ruler.ts, can read hybridDb/setZScaling directly without importing the parent store and creating a cycle. A Pinia store would work too but its $id/$patch/... properties would leak into the composed store's spread and collapse its inferred type. const useHybridViewerScene = createSharedComposable(() => { @@ -17,7 +21,11 @@ const useHybridViewerScene = createSharedComposable(() => { const zScale = ref(1); async function addItem(dataId: DataId): Promise { - await addSceneActor(hybridDb, dataId, zScale.value); + await addSceneActor(hybridDb, dataId, { zScale }); + } + + async function refineItem(dataId: DataId): Promise { + await refineSceneActor(hybridDb, dataId, zScale); } function removeItem(dataId: DataId): void { @@ -28,6 +36,14 @@ const useHybridViewerScene = createSharedComposable(() => { setSceneActorVisibility(hybridDb, dataId, visibility); } + function setComponentsVisibility( + modelId: DataId, + componentIds: readonly PartId[], + visibility: Visibility, + ): void { + setSceneComponentsVisibility(hybridDb, modelId, componentIds, visibility); + } + async function setZScaling(z_scale: ZScale): Promise { const ratio = z_scale / zScale.value; zScale.value = z_scale; @@ -39,11 +55,15 @@ const useHybridViewerScene = createSharedComposable(() => { } return { + ...useSceneStyles(hybridDb), hybridDb, zScale, addItem, + refineItem, + cancelRefine, removeItem, setVisibility, + setComponentsVisibility, setZScaling, setBackgroundColor, clear, diff --git a/internal/stores/hybrid_viewer/scene_actors.ts b/internal/stores/hybrid_viewer/scene_actors.ts index e9c8fcfe1..e4a14d1d7 100644 --- a/internal/stores/hybrid_viewer/scene_actors.ts +++ b/internal/stores/hybrid_viewer/scene_actors.ts @@ -1,69 +1,134 @@ -import type { HybridDb, HybridDbEntry } from "./vtk_types"; +import type { ColorRGB, Visibility } from "@geode/opengeodeweb-viewer/schema_types"; +import { type EntrySources, cancelRefine, entrySourcesOf, refineSceneItem } from "./detail"; +import type { HybridDb, HybridDbEntry, HybridPart, PartId, vtkRenderer } from "./vtk_types"; +import { applyMeshActorStyle, applyModelActorStyle, partColors } from "./entry_styles"; +import { + newHybridEntry, + setEntryExplodedBounds, + setEntryModelVisibility, + setPartsComponentVisibility, +} from "./parts"; import { requireRenderWindow, useHybridViewerCore } from "./core"; -import { ACTOR_COLOR } from "./constants"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { LightViewable } from "@ogw_front/types/data"; -import type { Visibility } from "@geode/opengeodeweb-viewer/schema_types"; +import type { Ref } from "vue"; import type { ZScale } from "@ogw_front/types/geometry"; import { base64ToArrayBuffer } from "./base64"; -import { useDataStore } from "@ogw_front/stores/data"; -import { newInstance as vtkActor } from "@kitware/vtk.js/Rendering/Core/Actor"; -import { newInstance as vtkMapper } from "@kitware/vtk.js/Rendering/Core/Mapper"; import type vtkPolyData from "@kitware/vtk.js/Common/DataModel/PolyData"; import { newInstance as vtkXMLPolyDataReader } from "@kitware/vtk.js/IO/XML/XMLPolyDataReader"; -async function fetchBinaryLightViewable(dataId: DataId): Promise { - const dataStore = useDataStore(); - const isViewable = await dataStore.fetchIsViewable(dataId); - if (!isViewable) { - return undefined; - } - const value = await dataStore.item(dataId); - return value.binary_light_viewable; -} +const WHITE: ColorRGB = { red: 255, green: 255, blue: 255 }; -function createHybridDbEntry(binaryLightViewable: LightViewable, zScale: ZScale): HybridDbEntry { +function createHybridPart(binaryLightViewable: LightViewable, color: ColorRGB): HybridPart { const reader = vtkXMLPolyDataReader(); reader.parseAsArrayBuffer(base64ToArrayBuffer(binaryLightViewable)); - const actor = vtkActor(); - const mapper = vtkMapper(); // oxlint-disable-next-line no-unsafe-type-assertion -- vtk.js's algorithm interface types getOutputData as `any`; this reader always produces polydata. const polydata = reader.getOutputData(0) as unknown as vtkPolyData; - mapper.setInputData(polydata); - const property = actor.getProperty(); - property.setColor(ACTOR_COLOR); - actor.setMapper(mapper); - actor.setScale(1, 1, zScale); - const compactPoints = Float64Array.from(polydata.getPoints().getData()); - return { actor, polydata, mapper, compactPoints }; + return { polydata, componentVisible: true, color }; +} + +// Styles are read here, once the geometry has loaded, so a change made during the load is drawn. +function createHybridEntry( + dataId: DataId, + sources: Readonly, + zScale: ZScale, + previous: HybridDbEntry | undefined, +): HybridDbEntry { + const colors = partColors(dataId, sources); + const parts: Record = {}; + for (const [partId, lightViewable] of Object.entries(sources.lightViewables)) { + parts[partId] = createHybridPart(lightViewable, colors[partId] ?? WHITE); + } + // A rebuilt entry keeps the visibility of the data + const entry = newHybridEntry(parts, previous?.modelVisible ?? true); + if (sources.isModel) { + applyModelActorStyle(entry, dataId); + } else { + applyMeshActorStyle(entry, dataId); + } + entry.actor.setScale(1, 1, zScale); + setPartsComponentVisibility(entry, sources.hidden, false); + return entry; +} + +// The latest add or removal of each data. +// An add whose geometry loaded after a later add or removal of the same data is dropped. +const sceneGenerations = new Map(); +let lastGeneration = 0; + +function nextGeneration(dataId: DataId): number { + lastGeneration += 1; + sceneGenerations.set(dataId, lastGeneration); + return lastGeneration; +} + +// Replacing an actor keeps the camera where the user left it +function replaceActor( + renderer: vtkRenderer, + previous: HybridDbEntry | undefined, + entry: HybridDbEntry, +): void { + const isFirst = !previous && renderer.getActors().length === 0; + if (previous) { + renderer.removeActor(previous.actor); + } + renderer.addActor(entry.actor); + if (isFirst) { + renderer.resetCamera(); + } +} + +interface AddOptions { + // Read once the geometry is loaded, so a z-scaling set meanwhile applies + zScale: Readonly>; + // A rebuild of the same geometry (the detail replacing the bounding box) stays exploded + keepExplode?: boolean; } // The scene z-scaling also applies to actors added after it was set -async function addSceneActor(hybridDb: HybridDb, dataId: DataId, zScale: ZScale): Promise { +async function addSceneActor( + hybridDb: HybridDb, + dataId: DataId, + { zScale, keepExplode = false }: Readonly, +): Promise { const { genericRenderWindow } = useHybridViewerCore(); if (!genericRenderWindow.value) { return; } - const binaryLightViewable = await fetchBinaryLightViewable(dataId); - if (binaryLightViewable === undefined) { + const generation = nextGeneration(dataId); + const sources = await entrySourcesOf(dataId); + if (sceneGenerations.get(dataId) !== generation) { return; } - const entry = createHybridDbEntry(binaryLightViewable, zScale); - const renderer = genericRenderWindow.value.getRenderer(); - // Replacing an actor keeps the camera where the user left it - const isFirst = !hybridDb[dataId] && renderer.getActors().length === 0; - if (hybridDb[dataId]) { - renderer.removeActor(hybridDb[dataId].actor); + if (Object.keys(sources.lightViewables).length === 0) { + return; } - renderer.addActor(entry.actor); - if (isFirst) { - renderer.resetCamera(); + const previous = hybridDb[dataId]; + const entry = createHybridEntry(dataId, sources, zScale.value, previous); + if (keepExplode && previous?.explodedBounds) { + setEntryExplodedBounds(entry, previous.explodedBounds); } + replaceActor(requireRenderWindow(genericRenderWindow).getRenderer(), previous, entry); hybridDb[dataId] = entry; } +// The bounding box shown first is replaced by the simplified light viewable once computed. +// Same geometry, more detail: the data stays exploded. +async function refineSceneActor( + hybridDb: HybridDb, + dataId: DataId, + zScale: Readonly>, +): Promise { + async function rebuild(id: DataId): Promise { + await addSceneActor(hybridDb, id, { zScale, keepExplode: true }); + } + await refineSceneItem(dataId, { isInScene: (id) => hybridDb[id] !== undefined, rebuild }); +} + function removeSceneActor(hybridDb: HybridDb, dataId: DataId): void { const { genericRenderWindow } = useHybridViewerCore(); + nextGeneration(dataId); + cancelRefine(dataId); if (!hybridDb[dataId]) { return; } @@ -79,13 +144,33 @@ function setSceneActorVisibility(hybridDb: HybridDb, dataId: DataId, visibility: if (!hybridDb[dataId]) { return; } - hybridDb[dataId].actor.setVisibility(visibility); + setEntryModelVisibility(hybridDb[dataId], visibility); + const renderWindow = requireRenderWindow(genericRenderWindow).getRenderWindow(); + renderWindow.render(); +} + +function setSceneComponentsVisibility( + hybridDb: HybridDb, + modelId: DataId, + componentIds: readonly PartId[], + visibility: Visibility, +): void { + const { genericRenderWindow } = useHybridViewerCore(); + if (!hybridDb[modelId]) { + return; + } + setPartsComponentVisibility(hybridDb[modelId], componentIds, visibility); const renderWindow = requireRenderWindow(genericRenderWindow).getRenderWindow(); renderWindow.render(); } function clearSceneActors(hybridDb: HybridDb): void { const { genericRenderWindow } = useHybridViewerCore(); + // Pending adds no longer match any generation, pending details are ignored + sceneGenerations.clear(); + for (const dataId of Object.keys(hybridDb)) { + cancelRefine(dataId); + } const renderer = requireRenderWindow(genericRenderWindow).getRenderer(); for (const actor of renderer.getActors()) { renderer.removeActor(actor); @@ -97,4 +182,12 @@ function clearSceneActors(hybridDb: HybridDb): void { } } -export { addSceneActor, clearSceneActors, removeSceneActor, setSceneActorVisibility }; +export { + addSceneActor, + clearSceneActors, + createHybridPart, + refineSceneActor, + removeSceneActor, + setSceneActorVisibility, + setSceneComponentsVisibility, +}; diff --git a/internal/stores/hybrid_viewer/scene_styles.ts b/internal/stores/hybrid_viewer/scene_styles.ts new file mode 100644 index 000000000..1802aafd8 --- /dev/null +++ b/internal/stores/hybrid_viewer/scene_styles.ts @@ -0,0 +1,78 @@ +import type { ColorRGBA, PointSize } from "@geode/opengeodeweb-viewer/schema_types"; +import type { HybridDb, PartId } from "./vtk_types"; +import { requireRenderWindow, useHybridViewerCore } from "./core"; +import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; +import type { MeshLightStyle } from "@ogw_internal/stores/data_style/mesh/light_style"; +import { rgbOf } from "@ogw_internal/stores/data_style/model/light_colors"; +import { setPartsColor } from "./parts"; + +// A style the viewer applied to a mesh: the colour's alpha is its opacity +type MeshStyleChange = Readonly< + Partial> & { + color?: ColorRGBA; + } +>; + +function render(): void { + const { genericRenderWindow } = useHybridViewerCore(); + requireRenderWindow(genericRenderWindow).getRenderWindow().render(); +} + +// The styles the viewer applies follow in the light view; data out of it are ignored +function useSceneStyles(hybridDb: HybridDb): { + setComponentsColors: (modelId: DataId, colors: Readonly>) => void; + setMeshStyle: (meshId: DataId, style: MeshStyleChange) => void; + setPointSize: (dataId: DataId, size: PointSize) => void; +} { + // Every component recolored at once renders once; the light view draws opaque models: the alpha is dropped + function setComponentsColors(modelId: DataId, colors: Readonly>): void { + const entry = hybridDb[modelId]; + if (!entry) { + return; + } + for (const [componentId, color] of Object.entries(colors)) { + setPartsColor(entry, [componentId], rgbOf(color)); + } + render(); + } + + function setMeshStyle( + meshId: DataId, + { color, opacity, pointSize, lineWidth }: MeshStyleChange, + ): void { + const entry = hybridDb[meshId]; + if (!entry) { + return; + } + const property = entry.actor.getProperty(); + if (color) { + setPartsColor(entry, [meshId], rgbOf(color)); + property.setOpacity(color.alpha); + } + if (opacity !== undefined) { + property.setOpacity(opacity); + } + if (pointSize !== undefined) { + property.setPointSize(pointSize); + } + if (lineWidth !== undefined) { + property.setLineWidth(lineWidth); + } + render(); + } + + // A model's points size, which the viewer gives its corners + function setPointSize(dataId: DataId, size: PointSize): void { + const entry = hybridDb[dataId]; + if (!entry) { + return; + } + entry.actor.getProperty().setPointSize(size); + render(); + } + + return { setComponentsColors, setMeshStyle, setPointSize }; +} + +export { useSceneStyles }; +export type { MeshStyleChange }; diff --git a/internal/stores/hybrid_viewer/vtk_types.ts b/internal/stores/hybrid_viewer/vtk_types.ts index fa9a45bd5..fb5f00cb4 100644 --- a/internal/stores/hybrid_viewer/vtk_types.ts +++ b/internal/stores/hybrid_viewer/vtk_types.ts @@ -1,10 +1,12 @@ +import type { AttributeName, ColorRGB } from "@geode/opengeodeweb-viewer/schema_types"; import type { ModelComponentId, ModelIdentified } from "@ogw_front/types/identifiers"; import type { ModelComponentName, ModelComponentType } from "@ogw_front/types/model"; -import type { AttributeName } from "@geode/opengeodeweb-viewer/schema_types"; +import type { Bounds } from "@ogw_front/types/geometry"; import type { DataId } from "@geode/opengeodeweb-microservice/schema_types"; import type { DataName } from "@ogw_front/types/data"; import type { Vector3 } from "@kitware/vtk.js/types"; import type vtkActor from "@kitware/vtk.js/Rendering/Core/Actor"; +import type vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper"; import type vtkPolyData from "@kitware/vtk.js/Common/DataModel/PolyData"; // The camera state as exchanged with the viewer microservice (snake_case field names, plain arrays) - distinct from vtk.js's own vtkCamera object. @@ -17,12 +19,29 @@ interface CameraOptions { distance: number; } +// The geometry of a whole mesh, or of one mesh component of a model, as loaded, and its color +interface HybridPart { + polydata: vtkPolyData; + componentVisible: boolean; + color: ColorRGB; +} + +// The data id (DataId) for a mesh part, the component id (ModelComponentId) for a model one +type PartId = string; + +// One actor per data, drawing its visible parts merged in one polydata: one draw call per data. +// The actor is shown when the data is visible and at least one of its parts is. interface HybridDbEntry { actor: vtkActor; + mapper: vtkMapper; + // The merged visible parts the actor draws, one color per cell polydata: vtkPolyData; - mapper: unknown; - // The light viewable points as loaded, before the polydata is stretched over the exploded data - compactPoints: Float64Array; + // The cell id ranges [start, end) of each visible part in polydata + cellRanges: Record; + parts: Record; + modelVisible: boolean; + // The bounds of the exploded data in the viewer, undefined while compact + explodedBounds: Bounds | undefined; } type HybridDb = Record; @@ -59,6 +78,8 @@ export type { CameraOptions, HybridDbEntry, HybridDb, + HybridPart, + PartId, HoverComponentInfo, HoverData, ViewStreamLike, diff --git a/nuxt.config.ts b/nuxt.config.ts index 06425698b..e3f4404fc 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -157,7 +157,9 @@ export default defineNuxtConfig({ optimizeDeps: { include: [ "@kitware/vtk.js", + "@kitware/vtk.js/Common/Core/DataArray", "@kitware/vtk.js/Common/Core/Math", + "@kitware/vtk.js/Common/DataModel/PolyData", "@kitware/vtk.js/IO/Core/WSLinkClient", "@kitware/vtk.js/IO/XML/XMLPolyDataReader", "@kitware/vtk.js/Rendering/Core/Actor", @@ -165,6 +167,7 @@ export default defineNuxtConfig({ "@kitware/vtk.js/Rendering/Core/Camera", "@kitware/vtk.js/Rendering/Core/ColorTransferFunction", "@kitware/vtk.js/Rendering/Core/Mapper", + "@kitware/vtk.js/Rendering/Core/Mapper/CoincidentTopologyHelper", "@kitware/vtk.js/Rendering/Misc/GenericRenderWindow", "@kitware/vtk.js/Rendering/Misc/RemoteView", "@kitware/vtk.js/Rendering/OpenGL/Profiles/Geometry", diff --git a/tests/unit/composables/crs.nuxt.test.ts b/tests/unit/composables/crs.nuxt.test.ts index 64ea5bc84..5007b0b9c 100644 --- a/tests/unit/composables/crs.nuxt.test.ts +++ b/tests/unit/composables/crs.nuxt.test.ts @@ -17,6 +17,16 @@ vi.setConfig({ testTimeout: 10_000 }); // Hoisted with vi.mock, so the reloadObject mock can record its call order const { calls } = vi.hoisted(() => ({ calls: [] as string[] })); +// The stored detail of the moved data is dropped before its actor is rebuilt +vi.mock(import("@ogw_internal/stores/data/model/light_viewables"), () => ({ + clearComponentLightViewables: vi.fn<() => Promise>().mockImplementation(async () => { + calls.push("clear"); + await Promise.resolve(); + }), + getComponentLightViewables: vi.fn<() => Promise>>().mockResolvedValue({}), + setComponentLightViewables: vi.fn<() => Promise>().mockResolvedValue(), +})); + vi.mock(import("@ogw_front/utils/reload_object"), () => ({ reloadObject: vi.fn().mockImplementation(async () => { calls.push("reload"); @@ -41,7 +51,15 @@ describe("useCrs composable", () => { ); // The actor is rebuilt from the moved geometry before the CRS is stored: a basemap built // On the new CRS must never read the previous coordinates - expect(calls).toStrictEqual(["request", "update", "reload", "update", "focus"]); + expect(calls).toStrictEqual([ + "request", + "clear", + "update", + "reload", + "update", + "focus", + "refine", + ]); expect(vi.mocked(useDataStore().updateItem).mock.calls).toStrictEqual([ ["item-1", { binary_light_viewable: "light" }], ["item-1", { crs: LAMBERT }], @@ -54,7 +72,7 @@ describe("useCrs composable", () => { test("convertCrs without focus does not move the camera", async () => { await useCrs().convertCrs(item, LAMBERT, { focus: false }); - expect(calls).toStrictEqual(["request", "update", "reload", "update"]); + expect(calls).toStrictEqual(["request", "clear", "update", "reload", "update", "refine"]); expect(focusCameraOnObject).not.toHaveBeenCalled(); }); @@ -85,7 +103,15 @@ describe("useCrs composable", () => { }, }), ); - expect(calls).toStrictEqual(["request", "update", "reload", "update", "focus"]); + expect(calls).toStrictEqual([ + "request", + "clear", + "update", + "reload", + "update", + "focus", + "refine", + ]); }); test("alignCrs aligns the linked items in the same request", async () => { @@ -114,13 +140,17 @@ describe("useCrs composable", () => { // The camera focuses on the aligned item only, once every item is reloaded expect(calls).toStrictEqual([ "request", + "clear", "update", "reload", "update", + "refine", + "clear", "update", "reload", "update", "focus", + "refine", ]); }); @@ -145,13 +175,17 @@ describe("useCrs composable", () => { expect(useDataStore().updateItem).toHaveBeenCalledWith("item-2", { crs: LAMBERT }); expect(calls).toStrictEqual([ "request", + "clear", "update", "reload", "update", + "refine", + "clear", "update", "reload", "update", "focus", + "refine", ]); }); }); diff --git a/tests/unit/composables/viewer_reset.nuxt.test.ts b/tests/unit/composables/viewer_reset.nuxt.test.ts index d23689088..2634ebbe3 100644 --- a/tests/unit/composables/viewer_reset.nuxt.test.ts +++ b/tests/unit/composables/viewer_reset.nuxt.test.ts @@ -9,6 +9,7 @@ import { import { afterViewerReset } from "@ogw_front/composables/viewer_reset"; import { mockAs } from "@ogw_tests/utils"; import { recordRequests } from "@ogw_tests/unit/helpers/viewer_requests"; +import { setHighlightColors } from "@ogw_front/utils/highlight_colors"; import { setOrientationOverlay } from "@ogw_tests/unit/helpers/orientation_overlay"; import { setSceneColors } from "@ogw_front/utils/default_styles"; @@ -16,14 +17,24 @@ vi.setConfig({ testTimeout: 10_000 }); type ViewerRequest = Parameters[0]; -const { set_background_color, set_orientation_widget, set_text_style } = +const { set_background_color, set_highlight_colors, set_orientation_widget, set_text_style } = viewer_schemas.opengeodeweb_viewer.viewer; const BRAND_BACKGROUND = { red: 160, green: 180, blue: 187, alpha: 1 }; const BRAND_TEXT = { red: 31, green: 46, blue: 51, alpha: 1 }; +const ORANGE = { red: 244, green: 136, blue: 48 }; +const AUBURN = { red: 71, green: 37, blue: 10 }; +const BRAND_HIGHLIGHT = { + color: ORANGE, + outline_color: AUBURN, + surfaces_color: ORANGE, + lines_color: { red: 30, green: 30, blue: 30 }, + corners_color: AUBURN, +}; describe("after a viewer reset", () => { afterEach(() => { setSceneColors({}); + setHighlightColors(undefined); setOrientationOverlay(false); }); @@ -66,6 +77,30 @@ describe("after a viewer reset", () => { ]); }); + test("gives the viewer the app highlight colors", async () => { + setHighlightColors(BRAND_HIGHLIGHT); + const { request, schemas } = recordRequests(); + await afterViewerReset(request); + + expect(schemas).toStrictEqual([set_highlight_colors]); + expect(request).toHaveBeenCalledWith({ schema: set_highlight_colors, params: BRAND_HIGHLIGHT }); + }); + + test("hides the marker even when the viewer rejects the highlight colors", async () => { + setHighlightColors(BRAND_HIGHLIGHT); + setOrientationOverlay(true); + const request = vi + .fn<(args: { schema: unknown }) => Promise>() + .mockRejectedValueOnce(new Error("timeout")) + .mockResolvedValue({}); + + await expect(afterViewerReset(mockAs(request))).resolves.toBeUndefined(); + expect(request.mock.calls.map(([args]) => args.schema)).toStrictEqual([ + set_highlight_colors, + set_orientation_widget, + ]); + }); + test("shows the orientation marker again", async () => { const { request } = recordRequests(); await setOrientationMarkerVisibility(false, request); diff --git a/tests/unit/helpers/crs.ts b/tests/unit/helpers/crs.ts index 89d411f3e..017bae16d 100644 --- a/tests/unit/helpers/crs.ts +++ b/tests/unit/helpers/crs.ts @@ -52,6 +52,12 @@ function stubCrsStores(calls: string[]): CrsStubs { calls.push("update"); await Promise.resolve(); }); + // The simplified light viewable is asked again once the geometry moved + vi.spyOn(useHybridViewerStore(), "refineItem").mockImplementation(async () => { + calls.push("refine"); + await Promise.resolve(); + }); + vi.spyOn(useHybridViewerStore(), "cancelRefine").mockReturnValue(); const focusCameraOnObject = vi .spyOn(useHybridViewerStore(), "focusCameraOnObject") .mockImplementation(async () => { diff --git a/tests/unit/helpers/hybrid_detail.ts b/tests/unit/helpers/hybrid_detail.ts new file mode 100644 index 000000000..708937d91 --- /dev/null +++ b/tests/unit/helpers/hybrid_detail.ts @@ -0,0 +1,44 @@ +import type { ModelComponentInput, NewDataItem } from "@ogw_front/stores/data"; + +const MODEL_ID = "model-1"; +const MESH_ID = "mesh-1"; +const SURFACE = "00000000-0000-0000-0000-00000000000a"; +const LINE = "00000000-0000-0000-0000-00000000000b"; +const BLOCK = "00000000-0000-0000-0000-00000000000c"; + +function component(geodeId: string, type: string, viewerId: number): ModelComponentInput { + return { geode_id: geodeId, name: geodeId, type, viewer_id: viewerId, is_active: true }; +} + +const model: NewDataItem = { + data_id: MODEL_ID, + geode_id: "00000000-0000-0000-0000-000000000001", + name: "cube", + viewer_object_type: "model", + geode_object_type: "BRep", + binary_light_viewable: "box", + mesh_components: [ + component(SURFACE, "Surface", 1), + component(LINE, "Line", 2), + component(BLOCK, "Block", 3), + ], +}; + +const mesh: NewDataItem = { + data_id: MESH_ID, + geode_id: "00000000-0000-0000-0000-000000000002", + name: "surface", + viewer_object_type: "mesh", + geode_object_type: "TriangulatedSurface3D", + binary_light_viewable: "box", +}; + +// The detail answered by the back for the model: no entry for the block +const modelDetail = { + mesh_components: [ + { geode_id: SURFACE, binary_light_viewable: "surface light" }, + { geode_id: LINE, binary_light_viewable: "line light" }, + ], +}; + +export { BLOCK, LINE, MESH_ID, MODEL_ID, SURFACE, mesh, model, modelDetail }; diff --git a/tests/unit/helpers/hybrid_parts.ts b/tests/unit/helpers/hybrid_parts.ts new file mode 100644 index 000000000..fe748eb7c --- /dev/null +++ b/tests/unit/helpers/hybrid_parts.ts @@ -0,0 +1,79 @@ +import type { HybridDbEntry, HybridPart } from "@ogw_internal/stores/hybrid_viewer/vtk_types"; +import type { ColorRGB } from "@geode/opengeodeweb-viewer/schema_types"; +import { newHybridEntry } from "@ogw_internal/stores/hybrid_viewer/parts"; +import { newInstance as vtkPolyData } from "@kitware/vtk.js/Common/DataModel/PolyData"; + +const COORDINATES = 3; +const Z_OFFSET = 2; +const BLACK: ColorRGB = { red: 0, green: 0, blue: 0 }; +const RGB_MAX = 255; + +// A polydata whose points stand on the z axis at the given heights, joined by one line +function polydataAlongZ(heights: readonly number[]): ReturnType { + const polydata = vtkPolyData(); + polydata.getPoints().setData(Float64Array.from(heights.flatMap((height) => [0, 0, height])), 3); + polydata.getLines().setData(Uint32Array.from([heights.length, ...heights.keys()])); + return polydata; +} + +function partAlongZ( + heights: readonly number[], + componentVisible = true, + color: ColorRGB = BLACK, +): HybridPart { + return { polydata: polydataAlongZ(heights), componentVisible, color }; +} + +// A part with a corner (one vertex cell) at height 0, then a line from 0 to 1 +function partWithCorner(color: ColorRGB): HybridPart { + const polydata = polydataAlongZ([0, 1]); + polydata.getVerts().setData(Uint32Array.from([1, 0])); + return { polydata, componentVisible: true, color }; +} + +// A part made of one triangle strip, or of one polygon, over the same four points +function partWithFaces(kind: "Strips" | "Polys", color: ColorRGB): HybridPart { + const polydata = polydataAlongZ([0, 1, 2, 3]); + polydata.getLines().setData(new Uint32Array()); + polydata[`get${kind}`]().setData(Uint32Array.from([4, 0, 1, 2, 3])); + return { polydata, componentVisible: true, color }; +} + +// The 0-255 color of each cell the entry's actor draws, in cell order +function drawnCellColors(entry: HybridDbEntry): number[][] { + const colors = [...(entry.polydata.getCellData().getScalars()?.getData() ?? [])]; + return Array.from({ length: colors.length / COORDINATES }, (_cell, index) => + colors.slice(index * COORDINATES, (index + 1) * COORDINATES), + ); +} + +function entryOf(parts: Record, modelVisible = true): HybridDbEntry { + return newHybridEntry(parts, modelVisible); +} + +// The heights of the points the entry's actor draws, none without an entry +function drawnHeights(entry: HybridDbEntry | undefined): number[] { + return [...(entry?.polydata.getPoints().getData() ?? [])].filter( + (_coordinate, index) => index % COORDINATES === Z_OFFSET, + ); +} + +// The entry of a data expected in the scene +function requireEntry(entry: HybridDbEntry | undefined): HybridDbEntry { + if (!entry) { + throw new Error("The data has no entry in the scene"); + } + return entry; +} + +export { + RGB_MAX, + drawnCellColors, + drawnHeights, + entryOf, + partAlongZ, + partWithCorner, + partWithFaces, + polydataAlongZ, + requireEntry, +}; diff --git a/tests/unit/helpers/hybrid_scene.ts b/tests/unit/helpers/hybrid_scene.ts new file mode 100644 index 000000000..39bd4d280 --- /dev/null +++ b/tests/unit/helpers/hybrid_scene.ts @@ -0,0 +1,35 @@ +import { useHybridViewerCore } from "@ogw_internal/stores/hybrid_viewer/core"; +import type { vtkGenericRenderWindow } from "@kitware/vtk.js/Rendering/Misc/GenericRenderWindow"; +import { newInstance as vtkRenderer } from "@kitware/vtk.js/Rendering/Core/Renderer"; + +// A light viewable as the back sends it: a base64 .vtp of points on the z axis, joined by one line +function lightViewableAlongZ(heights: readonly number[]): string { + const points = heights.map((height) => `0 0 ${height}`).join(" "); + const connectivity = [...heights.keys()].join(" "); + return btoa( + `` + + `` + + `${points}` + + `${connectivity}` + + `${heights.length}` + + ``, + ); +} + +function asGenericRenderWindow(fake: object): vtkGenericRenderWindow { + // oxlint-disable-next-line no-unsafe-type-assertion -- the scene only calls getRenderer and getRenderWindow + return fake as vtkGenericRenderWindow; +} + +// The scene renders in a real vtk.js renderer, without a WebGL window +function useFakeRenderWindow(): ReturnType { + const renderer = vtkRenderer(); + const renderWindow = { render: (): void => undefined }; + useHybridViewerCore().genericRenderWindow.value = asGenericRenderWindow({ + getRenderer: () => renderer, + getRenderWindow: () => renderWindow, + }); + return renderer; +} + +export { lightViewableAlongZ, useFakeRenderWindow }; diff --git a/tests/unit/stores/basemap.nuxt.test.ts b/tests/unit/stores/basemap.nuxt.test.ts index 40f723700..8a8c9dbcc 100644 --- a/tests/unit/stores/basemap.nuxt.test.ts +++ b/tests/unit/stores/basemap.nuxt.test.ts @@ -29,7 +29,7 @@ const SECOND_DATA = "c"; const DELETE_ROUTE = back_schemas.opengeodeweb_back.basemap.delete.$id; function fakeActor(bounds: number[]): unknown { - return { polydata: { getBounds: () => bounds } }; + return { parts: { part: { polydata: { getBounds: () => bounds } } }, modelVisible: true }; } interface Request { diff --git a/tests/unit/stores/basemap_detail.nuxt.test.ts b/tests/unit/stores/basemap_detail.nuxt.test.ts index 7f64bf8e1..1e8fedf8f 100644 --- a/tests/unit/stores/basemap_detail.nuxt.test.ts +++ b/tests/unit/stores/basemap_detail.nuxt.test.ts @@ -214,7 +214,10 @@ describe("basemap detail store", () => { vi.fn().mockResolvedValue(undefined), ); Object.assign(hybridViewerStore.hybridDb, { - [FIRST_DATA]: { polydata: { getBounds: () => BASE_BOX } }, + [FIRST_DATA]: { + parts: { [FIRST_DATA]: { polydata: { getBounds: () => BASE_BOX } } }, + modelVisible: true, + }, }); Object.assign(hybridViewerStore.camera_options, TOP_VIEW); hybridViewerStore.is_moving = false; diff --git a/tests/unit/stores/data_style_mesh_light_view.nuxt.test.ts b/tests/unit/stores/data_style_mesh_light_view.nuxt.test.ts new file mode 100644 index 000000000..786c0d736 --- /dev/null +++ b/tests/unit/stores/data_style_mesh_light_view.nuxt.test.ts @@ -0,0 +1,82 @@ +import { MESH_ID, mesh } from "@ogw_tests/unit/helpers/hybrid_detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { RGB_MAX } from "@ogw_tests/unit/helpers/hybrid_parts"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useDataStore } from "@ogw_front/stores/data"; +import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; +import { useDataStyleStore } from "@ogw_front/stores/data_style"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; +import { useMeshEdgesWidthStyle } from "@ogw_internal/stores/data_style/mesh/edges/width"; +import { useMeshPointsColorStyle } from "@ogw_internal/stores/data_style/mesh/points/color"; +import { useMeshPointsSizeStyle } from "@ogw_internal/stores/data_style/mesh/points/size"; +import { useMeshPolygonsColorStyle } from "@ogw_internal/stores/data_style/mesh/polygons/color"; +import { useViewerStore } from "@ogw_front/stores/viewer"; + +vi.setConfig({ testTimeout: 10_000 }); + +const HALF = 0.5; +const POINT_SIZE = 4; +const LINE_WIDTH = 3; +const RED = { red: RGB_MAX, green: 0, blue: 0, alpha: 1 }; +// Each test styles its own data: the styles cache empties only once the database is observed cleared +const SURFACE_MESH = "surface-mesh"; +const POINT_SET = "point-set"; + +describe("mesh style changes reach the light view", () => { + setupActivePinia(); + + let viewerResponse: unknown = {}; + + beforeEach(async () => { + await useDataStore().clear(); + await useDataStyleStore().clear(); + await useDataStore().addItem(mesh); + viewerResponse = {}; + vi.spyOn(useViewerStore(), "request").mockImplementation(async (_request, callbacks) => { + await callbacks?.response_function?.(viewerResponse); + }); + }); + + test("a polygons color and opacity restyle the mesh's light actor", async () => { + const setMeshStyle = vi.spyOn(useHybridViewerStore(), "setMeshStyle").mockReturnValue(); + const polygonsStyle = useMeshPolygonsColorStyle(); + + await polygonsStyle.setMeshPolygonsColor(MESH_ID, RED); + await polygonsStyle.setMeshPolygonsOpacity(MESH_ID, HALF); + + expect(setMeshStyle.mock.calls).toStrictEqual([ + [MESH_ID, { color: RED }], + [MESH_ID, { opacity: HALF }], + ]); + }); + + test("a points size and an edges width restyle the mesh's light actor", async () => { + const setMeshStyle = vi.spyOn(useHybridViewerStore(), "setMeshStyle").mockReturnValue(); + + await useMeshPointsSizeStyle().setMeshPointsSize(MESH_ID, POINT_SIZE); + await useMeshEdgesWidthStyle().setMeshEdgesWidth(MESH_ID, LINE_WIDTH); + + expect(setMeshStyle.mock.calls).toStrictEqual([ + [MESH_ID, { pointSize: POINT_SIZE }], + [MESH_ID, { lineWidth: LINE_WIDTH }], + ]); + }); + + test("a points color leaves a surface's light actor alone", async () => { + await useDataStyleState().mutateStyle(SURFACE_MESH, { points: {}, edges: {}, polygons: {} }); + const setMeshStyle = vi.spyOn(useHybridViewerStore(), "setMeshStyle").mockReturnValue(); + + await useMeshPointsColorStyle().setMeshPointsColor(SURFACE_MESH, RED); + + expect(setMeshStyle).not.toHaveBeenCalled(); + }); + + test("a points color restyles a point set's light actor", async () => { + await useDataStyleState().mutateStyle(POINT_SET, { points: {} }); + const setMeshStyle = vi.spyOn(useHybridViewerStore(), "setMeshStyle").mockReturnValue(); + + await useMeshPointsColorStyle().setMeshPointsColor(POINT_SET, RED); + + expect(setMeshStyle.mock.calls).toStrictEqual([[POINT_SET, { color: RED }]]); + }); +}); diff --git a/tests/unit/stores/data_style_model_light_view.nuxt.test.ts b/tests/unit/stores/data_style_model_light_view.nuxt.test.ts new file mode 100644 index 000000000..39e1118fb --- /dev/null +++ b/tests/unit/stores/data_style_model_light_view.nuxt.test.ts @@ -0,0 +1,83 @@ +import { LINE, MODEL_ID, SURFACE, model } from "@ogw_tests/unit/helpers/hybrid_detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { RGB_MAX } from "@ogw_tests/unit/helpers/hybrid_parts"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useDataStore } from "@ogw_front/stores/data"; +import { useDataStyleStore } from "@ogw_front/stores/data_style"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; +import { useModelCommonStyle } from "@ogw_internal/stores/data_style/model/common"; +import { useModelPointsSizeStyle } from "@ogw_internal/stores/data_style/model/points/size"; +import { useViewerStore } from "@ogw_front/stores/viewer"; +import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; + +vi.setConfig({ testTimeout: 10_000 }); + +const POINT_SIZE = 4; +const RED = { red: RGB_MAX, green: 0, blue: 0, alpha: 1 }; +const GREEN = { red: 0, green: RGB_MAX, blue: 0, alpha: 1 }; + +describe("model style changes reach the light view", () => { + setupActivePinia(); + + let viewerResponse: unknown = {}; + + beforeEach(async () => { + await useDataStore().clear(); + await useDataStyleStore().clear(); + await useDataStore().addItem(model); + await useDataStore().addComponents(model); + viewerResponse = {}; + vi.spyOn(useViewerStore(), "request").mockImplementation(async (_request, callbacks) => { + await callbacks?.response_function?.(viewerResponse); + }); + }); + + test("a constant color of components recolors their light parts", async () => { + const setComponentsColors = vi + .spyOn(useHybridViewerStore(), "setComponentsColors") + .mockReturnValue(); + viewerResponse = { colors: [] }; + + await useModelCommonStyle().setModelTypeColor( + MODEL_ID, + [SURFACE], + RED, + viewer_schemas.opengeodeweb_viewer.model.surfaces.color, + ); + + expect(setComponentsColors.mock.calls).toStrictEqual([[MODEL_ID, { [SURFACE]: RED }]]); + }); + + test("random colors recolor each component with its own color", async () => { + const setComponentsColors = vi + .spyOn(useHybridViewerStore(), "setComponentsColors") + .mockReturnValue(); + viewerResponse = { + colors: [ + { geode_id: SURFACE, color: GREEN }, + { geode_id: LINE, color: RED }, + ], + }; + + await useModelCommonStyle().setModelTypeColor( + MODEL_ID, + [SURFACE, LINE], + undefined, + viewer_schemas.opengeodeweb_viewer.model.surfaces.color, + "random", + ); + + // One call for every component, so the light view renders once + expect(setComponentsColors.mock.calls).toStrictEqual([ + [MODEL_ID, { [SURFACE]: GREEN, [LINE]: RED }], + ]); + }); + + test("a model points size resizes the model's light corners", async () => { + const setPointSize = vi.spyOn(useHybridViewerStore(), "setPointSize").mockReturnValue(); + + await useModelPointsSizeStyle().setModelPointsSize(MODEL_ID, POINT_SIZE); + + expect(setPointSize.mock.calls).toStrictEqual([[MODEL_ID, POINT_SIZE]]); + }); +}); diff --git a/tests/unit/stores/data_style_model_type_visibility.nuxt.test.ts b/tests/unit/stores/data_style_model_type_visibility.nuxt.test.ts new file mode 100644 index 000000000..ce9ba0559 --- /dev/null +++ b/tests/unit/stores/data_style_model_type_visibility.nuxt.test.ts @@ -0,0 +1,54 @@ +import { MODEL_ID, SURFACE, model } from "@ogw_tests/unit/helpers/hybrid_detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { hiddenComponentIds } from "@ogw_internal/stores/data_style/model/hidden_components"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useDataStore } from "@ogw_front/stores/data"; +import { useDataStyleStore } from "@ogw_front/stores/data_style"; +import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer"; +import { useModelCommonStyle } from "@ogw_internal/stores/data_style/model/common"; +import { useViewerStore } from "@ogw_front/stores/viewer"; +import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js"; + +vi.setConfig({ testTimeout: 10_000 }); + +describe("model component visibility in the light view", () => { + setupActivePinia(); + + beforeEach(async () => { + await useDataStore().clear(); + await useDataStyleStore().clear(); + await useDataStore().addItem(model); + await useDataStore().addComponents(model); + vi.spyOn(useViewerStore(), "request").mockImplementation(async (_request, callbacks) => { + await callbacks?.response_function?.({}); + }); + }); + + test("hiding components hides their light actors too", async () => { + const setComponentsVisibility = vi + .spyOn(useHybridViewerStore(), "setComponentsVisibility") + .mockReturnValue(); + + await useModelCommonStyle().setModelTypeVisibility( + MODEL_ID, + [SURFACE], + false, + viewer_schemas.opengeodeweb_viewer.model.surfaces.visibility, + ); + + expect(setComponentsVisibility.mock.calls).toStrictEqual([[MODEL_ID, [SURFACE], false]]); + }); + + test("the hidden components are read from their stored style", async () => { + vi.spyOn(useHybridViewerStore(), "setComponentsVisibility").mockReturnValue(); + + await useModelCommonStyle().setModelTypeVisibility( + MODEL_ID, + [SURFACE], + false, + viewer_schemas.opengeodeweb_viewer.model.surfaces.visibility, + ); + + await expect(hiddenComponentIds(MODEL_ID)).resolves.toStrictEqual(new Set([SURFACE])); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_colors.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_colors.nuxt.test.ts new file mode 100644 index 000000000..c366f20dc --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_colors.nuxt.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, test, vi } from "vitest"; + +import { + RGB_MAX, + drawnCellColors, + entryOf, + partAlongZ, + partWithCorner, + partWithFaces, +} from "@ogw_tests/unit/helpers/hybrid_parts"; +import { + setPartsColor, + setPartsComponentVisibility, +} from "@ogw_internal/stores/hybrid_viewer/parts"; + +vi.setConfig({ testTimeout: 10_000 }); + +const LOW_TOP = 1; +const HIGH_BOTTOM = 5; +const HIGH_TOP = 7; +const RED_CELL = [RGB_MAX, 0, 0]; +const GREEN_CELL = [0, RGB_MAX, 0]; +const BLUE_CELL = [0, 0, RGB_MAX]; +const RED = { red: RGB_MAX, green: 0, blue: 0 }; +const GREEN = { red: 0, green: RGB_MAX, blue: 0 }; +const BLUE = { red: 0, green: 0, blue: RGB_MAX }; + +describe("hybrid entry colors", () => { + test("each part's cells are drawn in its color", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP], true, RED), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], true, BLUE), + }); + + expect(drawnCellColors(entry)).toStrictEqual([RED_CELL, BLUE_CELL]); + }); + + test("colors follow the cell order: vertices first, then lines", () => { + const entry = entryOf({ + corner: partWithCorner(RED), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], true, BLUE), + }); + + expect(drawnCellColors(entry)).toStrictEqual([RED_CELL, RED_CELL, BLUE_CELL]); + }); + + test("a part recolored in place keeps the color array", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP], true, RED), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], true, BLUE), + }); + const colors = entry.polydata.getCellData().getScalars(); + + setPartsColor(entry, ["high"], GREEN); + + expect(entry.polydata.getCellData().getScalars()).toBe(colors); + expect(drawnCellColors(entry)).toStrictEqual([RED_CELL, GREEN_CELL]); + }); + + test("a hidden part recolored shows its new color once shown", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP], true, RED), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], false, BLUE), + }); + + setPartsColor(entry, ["high"], GREEN); + setPartsComponentVisibility(entry, ["high"], true); + + expect(drawnCellColors(entry)).toStrictEqual([RED_CELL, GREEN_CELL]); + }); + + test("colors of unknown parts are ignored", () => { + const entry = entryOf({ low: partAlongZ([0, LOW_TOP], true, RED) }); + + setPartsColor(entry, ["block"], GREEN); + + expect(drawnCellColors(entry)).toStrictEqual([RED_CELL]); + }); + + test("colors follow the vtk.js cell order: polygons before strips", () => { + const entry = entryOf({ + strip: partWithFaces("Strips", RED), + polygon: partWithFaces("Polys", BLUE), + }); + + expect(drawnCellColors(entry)).toStrictEqual([BLUE_CELL, RED_CELL]); + }); + + test("a recolored part marks the drawn polydata modified, so vtk.js uploads the new colors", () => { + const entry = entryOf({ low: partAlongZ([0, LOW_TOP], true, RED) }); + const modifiedTime = entry.polydata.getMTime(); + + setPartsColor(entry, ["low"], GREEN); + + expect(entry.polydata.getMTime()).toBeGreaterThan(modifiedTime); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_detail.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_detail.nuxt.test.ts new file mode 100644 index 000000000..da6ca2f6e --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_detail.nuxt.test.ts @@ -0,0 +1,127 @@ +import { + LINE, + MESH_ID, + MODEL_ID, + SURFACE, + mesh, + model, + modelDetail, +} from "@ogw_tests/unit/helpers/hybrid_detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { + cancelRefine, + lightViewablesOf, + refineSceneItem, +} from "@ogw_internal/stores/hybrid_viewer/detail"; +import { getComponentLightViewables } from "@ogw_internal/stores/data/model/light_viewables"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useBackStore } from "@ogw_front/stores/back"; +import { useDataStore } from "@ogw_front/stores/data"; + +vi.setConfig({ testTimeout: 10_000 }); + +describe("detailed light viewables", () => { + setupActivePinia(); + + beforeEach(async () => { + const dataStore = useDataStore(); + await dataStore.clear(); + await dataStore.addItem(model); + await dataStore.addComponents(model); + await dataStore.addItem(mesh); + }); + + test("a model stores one light viewable per component, then is rebuilt", async () => { + vi.spyOn(useBackStore(), "request").mockResolvedValue(modelDetail); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + + await refineSceneItem(MODEL_ID, { isInScene: () => true, rebuild }); + + await expect(getComponentLightViewables(MODEL_ID)).resolves.toStrictEqual({ + [SURFACE]: "surface light", + [LINE]: "line light", + }); + expect(rebuild).toHaveBeenCalledWith(MODEL_ID); + await expect(lightViewablesOf(MODEL_ID)).resolves.toStrictEqual({ + [SURFACE]: "surface light", + [LINE]: "line light", + }); + }); + + test("a mesh replaces its light viewable, then is rebuilt", async () => { + vi.spyOn(useBackStore(), "request").mockResolvedValue({ binary_light_viewable: "detail" }); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + + await refineSceneItem(MESH_ID, { isInScene: () => true, rebuild }); + + const refined = await useDataStore().item(MESH_ID); + + expect(refined.binary_light_viewable).toBe("detail"); + await expect(lightViewablesOf(MESH_ID)).resolves.toStrictEqual({ [MESH_ID]: "detail" }); + expect(rebuild).toHaveBeenCalledWith(MESH_ID); + }); + + test("a model without stored detail shows its bounding box", async () => { + await expect(lightViewablesOf(MODEL_ID)).resolves.toStrictEqual({ [MODEL_ID]: "box" }); + }); + + test("a data removed during the request is left alone", async () => { + vi.spyOn(useBackStore(), "request").mockResolvedValue({ binary_light_viewable: "detail" }); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + + await refineSceneItem(MESH_ID, { isInScene: () => false, rebuild }); + + const untouched = await useDataStore().item(MESH_ID); + + expect(untouched.binary_light_viewable).toBe("box"); + expect(rebuild).not.toHaveBeenCalled(); + }); + + test("an answer overtaken by a newer request is ignored", async () => { + const firstAnswer = Promise.withResolvers(); + vi.spyOn(useBackStore(), "request") + .mockReturnValueOnce(firstAnswer.promise) + .mockResolvedValueOnce({ binary_light_viewable: "second" }); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + const options = { isInScene: (): boolean => true, rebuild }; + + const first = refineSceneItem(MESH_ID, options); + await refineSceneItem(MESH_ID, options); + firstAnswer.resolve({ binary_light_viewable: "first" }); + await first; + const refined = await useDataStore().item(MESH_ID); + + expect(refined.binary_light_viewable).toBe("second"); + expect(rebuild.mock.calls).toStrictEqual([[MESH_ID]]); + }); + + test("a cancelled request is ignored", async () => { + const answer = Promise.withResolvers(); + vi.spyOn(useBackStore(), "request").mockReturnValueOnce(answer.promise); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + + const pending = refineSceneItem(MESH_ID, { isInScene: () => true, rebuild }); + cancelRefine(MESH_ID); + answer.resolve({ binary_light_viewable: "stale" }); + await pending; + const untouched = await useDataStore().item(MESH_ID); + + expect(untouched.binary_light_viewable).toBe("box"); + expect(rebuild).not.toHaveBeenCalled(); + }); + + test("an answer cancelled while it is stored does not rebuild", async () => { + vi.spyOn(useBackStore(), "request").mockResolvedValue({ binary_light_viewable: "detail" }); + const dataStore = useDataStore(); + const updateItem = dataStore.updateItem.bind(dataStore); + vi.spyOn(dataStore, "updateItem").mockImplementation(async (...args) => { + cancelRefine(MESH_ID); + await updateItem(...args); + }); + const rebuild = vi.fn<(dataId: string) => Promise>().mockResolvedValue(); + + await refineSceneItem(MESH_ID, { isInScene: () => true, rebuild }); + + expect(rebuild).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_light_styles.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_light_styles.nuxt.test.ts new file mode 100644 index 000000000..bccbca510 --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_light_styles.nuxt.test.ts @@ -0,0 +1,129 @@ +import { LINE, SURFACE } from "@ogw_tests/unit/helpers/hybrid_detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { + componentLightColors, + modelBoxLightColor, +} from "@ogw_internal/stores/data_style/model/light_colors"; +import { meshLightStyle, meshMainElement } from "@ogw_internal/stores/data_style/mesh/light_style"; +import { LINES_DEFAULT_COLOR } from "@ogw_front/utils/default_styles/constants"; +import { RGB_MAX } from "@ogw_tests/unit/helpers/hybrid_parts"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; +import { useDataStyleStore } from "@ogw_front/stores/data_style"; +import { useModelComponentStyleMutations } from "@ogw_internal/stores/data_style/model/common_mutations"; + +vi.setConfig({ testTimeout: 10_000 }); + +// Each test styles its own data: the styles cache empties only once the database is observed cleared +const MODEL_1 = "model-1"; +const MODEL_2 = "model-2"; +const MODEL_3 = "model-3"; +const MODEL_4 = "model-4"; +const MODEL_5 = "model-5"; +const MESH_6 = "mesh-6"; +const MESH_7 = "mesh-7"; +const MESH_8 = "mesh-8"; +const MESH_9 = "mesh-9"; +const HALF = 0.5; +const POINT_SIZE = 4; +const LINE_WIDTH = 3; +const LINES_GREY = LINES_DEFAULT_COLOR.red; +const SEE_THROUGH_RED = { red: RGB_MAX, green: 0, blue: 0, alpha: HALF }; +const GREEN = { red: 0, green: RGB_MAX, blue: 0, alpha: 1 }; +const BLUE = { red: 0, green: 0, blue: RGB_MAX, alpha: 1 }; + +describe("light view styles", () => { + setupActivePinia(); + + beforeEach(async () => { + await useDataStyleStore().clear(); + }); + + test("a component takes its own color, without its alpha", async () => { + await useModelComponentStyleMutations().mutateComponentStyle(MODEL_1, SURFACE, { + coloring: { constant: SEE_THROUGH_RED }, + }); + + expect(componentLightColors(MODEL_1, { [SURFACE]: "Surface" })).toStrictEqual({ + [SURFACE]: { red: RGB_MAX, green: 0, blue: 0 }, + }); + }); + + test("a component without its own color takes its type group's", async () => { + await useModelComponentStyleMutations().mutateModelComponentTypeStyle(MODEL_2, "Surface", { + coloring: { constant: GREEN }, + }); + + expect(componentLightColors(MODEL_2, { [SURFACE]: "Surface" })).toStrictEqual({ + [SURFACE]: { red: 0, green: RGB_MAX, blue: 0 }, + }); + }); + + test("a component without group color takes the model's color of its type", async () => { + await useDataStyleState().mutateStyle(MODEL_3, { surfaces: { coloring: { constant: BLUE } } }); + + expect(componentLightColors(MODEL_3, { [SURFACE]: "Surface" })).toStrictEqual({ + [SURFACE]: { red: 0, green: 0, blue: RGB_MAX }, + }); + }); + + test("a component without any stored color takes its type's default", () => { + expect(componentLightColors(MODEL_4, { [SURFACE]: "Surface", [LINE]: "Line" })).toStrictEqual({ + [SURFACE]: { red: RGB_MAX, green: RGB_MAX, blue: RGB_MAX }, + [LINE]: { red: LINES_GREY, green: LINES_GREY, blue: LINES_GREY }, + }); + }); + + test("a model bounding box takes the model's surfaces color", async () => { + expect(modelBoxLightColor(MODEL_5)).toStrictEqual({ + red: RGB_MAX, + green: RGB_MAX, + blue: RGB_MAX, + }); + + await useDataStyleState().mutateStyle(MODEL_5, { surfaces: { coloring: { constant: BLUE } } }); + + expect(modelBoxLightColor(MODEL_5)).toStrictEqual({ red: 0, green: 0, blue: RGB_MAX }); + }); + + test("the main element of a mesh is the first of polyhedra, polygons, cells, edges, points", async () => { + const dataStyleState = useDataStyleState(); + await dataStyleState.mutateStyle(MESH_6, { points: {}, edges: {}, polygons: {} }); + + expect(meshMainElement(MESH_6)).toBe("polygons"); + + await dataStyleState.mutateStyle(MESH_6, { polyhedra: {} }); + + expect(meshMainElement(MESH_6)).toBe("polyhedra"); + }); + + test("a point set's main element is its points", async () => { + await useDataStyleState().mutateStyle(MESH_7, { points: {} }); + + expect(meshMainElement(MESH_7)).toBe("points"); + }); + + test("a mesh takes the color and opacity of its main element, its points size and edges width", async () => { + await useDataStyleState().mutateStyle(MESH_8, { + points: { size: POINT_SIZE }, + edges: { width: LINE_WIDTH }, + polygons: { coloring: { constant: SEE_THROUGH_RED } }, + }); + + expect(meshLightStyle(MESH_8)).toStrictEqual({ + color: { red: RGB_MAX, green: 0, blue: 0 }, + opacity: HALF, + pointSize: POINT_SIZE, + lineWidth: LINE_WIDTH, + }); + }); + + test("a mesh without stored style is opaque white", () => { + expect(meshLightStyle(MESH_9)).toStrictEqual({ + color: { red: RGB_MAX, green: RGB_MAX, blue: RGB_MAX }, + opacity: 1, + pointSize: undefined, + lineWidth: undefined, + }); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_parts.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_parts.nuxt.test.ts new file mode 100644 index 000000000..e0c29afcb --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_parts.nuxt.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, test, vi } from "vitest"; +import { Resolve } from "@kitware/vtk.js/Rendering/Core/Mapper/CoincidentTopologyHelper"; + +import { + compactZRange, + entryBounds, + entrySceneBounds, + setEntryExplodedBounds, + setEntryModelVisibility, + setPartsComponentVisibility, +} from "@ogw_internal/stores/hybrid_viewer/parts"; +import { + drawnHeights, + entryOf, + partAlongZ, + polydataAlongZ, +} from "@ogw_tests/unit/helpers/hybrid_parts"; +import { mergePolydata } from "@ogw_internal/stores/hybrid_viewer/merge"; + +vi.setConfig({ testTimeout: 10_000 }); + +const LOW_TOP = 1; +const HIGH_BOTTOM = 5; +const HIGH_TOP = 7; +const EXPLODED_TOP = 14; +const Z_MIN = 4; +const Z_MAX = 5; +const Z_SCALE = 3; + +describe("merged polydata", () => { + test("points follow each other and cells point to their own points", () => { + const merged = mergePolydata([ + polydataAlongZ([0, LOW_TOP]), + polydataAlongZ([HIGH_BOTTOM, HIGH_TOP]), + ]); + + expect([...merged.getPoints().getData()]).toStrictEqual([ + 0, + 0, + 0, + 0, + 0, + LOW_TOP, + 0, + 0, + HIGH_BOTTOM, + 0, + 0, + HIGH_TOP, + ]); + expect([...merged.getLines().getData()]).toStrictEqual([2, 0, 1, 2, 2, 3]); + }); + + test("a single polydata is copied, not shared", () => { + const source = polydataAlongZ([0, LOW_TOP]); + + const merged = mergePolydata([source]); + + expect(merged).not.toBe(source); + expect(merged.getPoints().getData()).not.toBe(source.getPoints().getData()); + }); + + test("no polydata gives an empty one", () => { + expect(mergePolydata([]).getPoints().getNumberOfPoints()).toBe(0); + }); +}); + +describe("hybrid entry parts", () => { + test("an entry draws all its parts with one actor", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP]), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP]), + }); + + expect(entry.actor.getMapper()?.getInputData()).toBe(entry.polydata); + expect(drawnHeights(entry)).toStrictEqual([0, LOW_TOP, HIGH_BOTTOM, HIGH_TOP]); + }); + + test("bounds of an entry span all its parts, hidden ones included", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP]), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], false), + }); + + const bounds = entryBounds(entry); + + expect([bounds[Z_MIN], bounds[Z_MAX]]).toStrictEqual([0, HIGH_TOP]); + }); + + test("scene bounds follow the z-scaling of the actor, hidden parts included", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP]), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP], false), + }); + entry.actor.setScale(1, 1, Z_SCALE); + + const bounds = entrySceneBounds(entry); + + expect([bounds[Z_MIN], bounds[Z_MAX]]).toStrictEqual([0, HIGH_TOP * Z_SCALE]); + }); + + test("scene bounds of a data flipped along z stay ordered", () => { + const entry = entryOf({ low: partAlongZ([LOW_TOP, HIGH_TOP]) }); + entry.actor.setScale(1, 1, -Z_SCALE); + + const bounds = entrySceneBounds(entry); + + expect([bounds[Z_MIN], bounds[Z_MAX]]).toStrictEqual([-HIGH_TOP * Z_SCALE, -LOW_TOP * Z_SCALE]); + }); + + test("compact z range spans all the parts", () => { + const entry = entryOf({ + low: partAlongZ([0, LOW_TOP]), + high: partAlongZ([HIGH_BOTTOM, HIGH_TOP]), + }); + + expect(compactZRange(entry)).toStrictEqual([0, HIGH_TOP]); + }); + + test("a hidden component is not drawn", () => { + const entry = entryOf({ low: partAlongZ([0]), high: partAlongZ([HIGH_TOP]) }); + + setPartsComponentVisibility(entry, ["high"], false); + + expect(drawnHeights(entry)).toStrictEqual([0]); + expect(entry.actor.getVisibility()).toBe(true); + }); + + test("hiding every component hides the actor", () => { + const entry = entryOf({ low: partAlongZ([0]) }); + + setPartsComponentVisibility(entry, ["low"], false); + + expect(entry.actor.getVisibility()).toBe(false); + }); + + test("a hidden model hides its actor", () => { + const entry = entryOf({ low: partAlongZ([0]) }); + + setEntryModelVisibility(entry, false); + + expect(entry.actor.getVisibility()).toBe(false); + }); + + test("showing the model keeps its hidden components hidden", () => { + const entry = entryOf({ low: partAlongZ([0]), high: partAlongZ([HIGH_TOP]) }); + + setPartsComponentVisibility(entry, ["low"], false); + setEntryModelVisibility(entry, false); + setEntryModelVisibility(entry, true); + + expect(drawnHeights(entry)).toStrictEqual([HIGH_TOP]); + expect(entry.actor.getVisibility()).toBe(true); + }); + + test("showing a component of a hidden model keeps it hidden", () => { + const entry = entryOf({ low: partAlongZ([0], false) }, false); + + setPartsComponentVisibility(entry, ["low"], true); + + expect(entry.actor.getVisibility()).toBe(false); + expect(entry.parts.low?.componentVisible).toBe(true); + }); + + test("components without a part are ignored", () => { + const entry = entryOf({ low: partAlongZ([0]) }); + + setPartsComponentVisibility(entry, ["block", "collection"], false); + + expect(drawnHeights(entry)).toStrictEqual([0]); + }); + + test("an exploded entry stretches over the z range of all its parts", () => { + const entry = entryOf({ low: partAlongZ([0, LOW_TOP]), high: partAlongZ([HIGH_TOP]) }); + + setEntryExplodedBounds(entry, [0, 0, 0, 0, 0, EXPLODED_TOP]); + setPartsComponentVisibility(entry, ["high"], false); + + expect(drawnHeights(entry)).toStrictEqual([0, LOW_TOP * 2]); + expect(entry.parts.low?.polydata.getPoints().getData()[2 + 3]).toBe(LOW_TOP); + }); + + test("an exploded entry is compact again without exploded bounds", () => { + const entry = entryOf({ low: partAlongZ([0, LOW_TOP]), high: partAlongZ([HIGH_TOP]) }); + + setEntryExplodedBounds(entry, [0, 0, 0, 0, 0, EXPLODED_TOP]); + setEntryExplodedBounds(entry, undefined); + + expect(drawnHeights(entry)).toStrictEqual([0, LOW_TOP, HIGH_TOP]); + }); + + test("lines and points lying on surfaces are drawn in front of them", () => { + const entry = entryOf({ low: partAlongZ([0, LOW_TOP]) }); + + expect(entry.mapper.getResolveCoincidentTopology()).toBe(Resolve.PolygonOffset); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_scene.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_scene.nuxt.test.ts index 0ac1f1f3b..1aa9e897d 100644 --- a/tests/unit/stores/hybrid_viewer_scene.nuxt.test.ts +++ b/tests/unit/stores/hybrid_viewer_scene.nuxt.test.ts @@ -11,6 +11,10 @@ const POSITION_X = 110; const POSITION_Y = 120; const POSITION_Z = 50; const Z_SCALE_RATIO = 3; +const PART_Z = 5; +const DATA_Z_MAX = 7; +const DATA_EXPLODED_Z_MAX = 14; +const PART_EXPLODED_Z = 10; describe("followZScaling helper", () => { test("keeps the focused point under the camera when the scene is stretched along z", () => { @@ -67,7 +71,12 @@ describe("explodeAlongZ helper", () => { ]); const points = new Float32Array(compactPoints.length); - explodeAlongZ(compactPoints, points, [0, 1, 0, 1, EXPLODED_Z_MIN, EXPLODED_Z_MAX]); + explodeAlongZ( + compactPoints, + points, + [0, 1, 0, 1, EXPLODED_Z_MIN, EXPLODED_Z_MAX], + [0, COMPACT_Z_MAX], + ); const middleZ = (EXPLODED_Z_MIN + EXPLODED_Z_MAX) / 2; @@ -88,10 +97,19 @@ describe("explodeAlongZ helper", () => { const compactPoints = Float64Array.from([1, 2, 0, 3, 4, COMPACT_Z_MAX]); const points = new Float64Array(compactPoints.length); - explodeAlongZ(compactPoints, points, [1, 3, 2, 4, 0, COMPACT_Z_MAX]); + explodeAlongZ(compactPoints, points, [1, 3, 2, 4, 0, COMPACT_Z_MAX], [0, COMPACT_Z_MAX]); expect([...points]).toStrictEqual([...compactPoints]); }); + + test("stretches a part over the z range of its whole data", () => { + const compactPoints = Float64Array.from([0, 0, PART_Z]); + const points = new Float64Array(compactPoints.length); + + explodeAlongZ(compactPoints, points, [0, 1, 0, 1, 0, DATA_EXPLODED_Z_MAX], [0, DATA_Z_MAX]); + + expect([...points]).toStrictEqual([0, 0, PART_EXPLODED_Z]); + }); }); const EXPLODED_TOP = 40; diff --git a/tests/unit/stores/hybrid_viewer_scene_actors.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_scene_actors.nuxt.test.ts new file mode 100644 index 000000000..6352f2930 --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_scene_actors.nuxt.test.ts @@ -0,0 +1,135 @@ +import { type EntrySources, entrySourcesOf } from "@ogw_internal/stores/hybrid_viewer/detail"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { drawnHeights, requireEntry } from "@ogw_tests/unit/helpers/hybrid_parts"; +import { lightViewableAlongZ, useFakeRenderWindow } from "@ogw_tests/unit/helpers/hybrid_scene"; +import { setEntryExplodedBounds } from "@ogw_internal/stores/hybrid_viewer/parts"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useBackStore } from "@ogw_front/stores/back"; +import { useHybridViewerScene } from "@ogw_internal/stores/hybrid_viewer/scene"; + +vi.mock(import("@ogw_internal/stores/hybrid_viewer/detail"), async (importOriginal) => ({ + ...(await importOriginal()), + entrySourcesOf: vi.fn(), +})); + +vi.setConfig({ testTimeout: 10_000 }); + +const DATA_ID = "data-1"; +const FIRST_TOP = 1; +const SECOND_TOP = 3; +const EXPLODED_TOP = 6; +const Z_SCALE = 4; + +describe("hybrid scene actors", () => { + setupActivePinia(); + + let renderer = useFakeRenderWindow(); + + beforeEach(() => { + renderer = useFakeRenderWindow(); + useHybridViewerScene().clear(); + useHybridViewerScene().zScale.value = 1; + vi.mocked(entrySourcesOf).mockReset(); + }); + + test("a data removed while its geometry loads is not added", async () => { + const sources = Promise.withResolvers(); + vi.mocked(entrySourcesOf).mockReturnValueOnce(sources.promise); + const scene = useHybridViewerScene(); + + const adding = scene.addItem(DATA_ID); + scene.removeItem(DATA_ID); + sources.resolve({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + await adding; + + expect(scene.hybridDb[DATA_ID]).toBeUndefined(); + expect(renderer.getActors()).toHaveLength(0); + }); + + test("of two rebuilds of a data, the last started wins", async () => { + const firstSources = Promise.withResolvers(); + vi.mocked(entrySourcesOf) + .mockReturnValueOnce(firstSources.promise) + .mockResolvedValueOnce({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0, SECOND_TOP]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + const scene = useHybridViewerScene(); + + const first = scene.addItem(DATA_ID); + await scene.addItem(DATA_ID); + firstSources.resolve({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0, FIRST_TOP]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + await first; + + expect(drawnHeights(scene.hybridDb[DATA_ID])).toStrictEqual([0, SECOND_TOP]); + expect(renderer.getActors()).toHaveLength(1); + }); + + test("the z-scaling set while the geometry loads applies to the new actor", async () => { + const sources = Promise.withResolvers(); + vi.mocked(entrySourcesOf).mockReturnValueOnce(sources.promise); + const scene = useHybridViewerScene(); + + const adding = scene.addItem(DATA_ID); + scene.zScale.value = Z_SCALE; + sources.resolve({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + await adding; + + expect(scene.hybridDb[DATA_ID]?.actor.getScale()[2]).toBe(Z_SCALE); + }); + + test("the detail replacing the bounding box keeps the explode", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0, FIRST_TOP]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + const scene = useHybridViewerScene(); + await scene.addItem(DATA_ID); + setEntryExplodedBounds(requireEntry(scene.hybridDb[DATA_ID]), [0, 0, 0, 0, 0, EXPLODED_TOP]); + + vi.spyOn(useBackStore(), "request").mockResolvedValueOnce({ mesh_components: [] }); + await scene.refineItem(DATA_ID); + + expect(drawnHeights(scene.hybridDb[DATA_ID])).toStrictEqual([0, EXPLODED_TOP]); + }); + + test("a data removed then added again ignores the detail asked before", async () => { + const answer = Promise.withResolvers(); + vi.spyOn(useBackStore(), "request").mockReturnValueOnce(answer.promise); + vi.mocked(entrySourcesOf).mockResolvedValue({ + lightViewables: { [DATA_ID]: lightViewableAlongZ([0]) }, + hidden: new Set(), + isModel: false, + types: {}, + }); + const scene = useHybridViewerScene(); + await scene.addItem(DATA_ID); + + const refining = scene.refineItem(DATA_ID); + scene.removeItem(DATA_ID); + await scene.addItem(DATA_ID); + answer.resolve({ binary_light_viewable: lightViewableAlongZ([0, FIRST_TOP]) }); + await refining; + + expect(vi.mocked(entrySourcesOf).mock.calls).toStrictEqual([[DATA_ID], [DATA_ID]]); + }); +}); diff --git a/tests/unit/stores/hybrid_viewer_scene_styles.nuxt.test.ts b/tests/unit/stores/hybrid_viewer_scene_styles.nuxt.test.ts new file mode 100644 index 000000000..6553e92b9 --- /dev/null +++ b/tests/unit/stores/hybrid_viewer_scene_styles.nuxt.test.ts @@ -0,0 +1,193 @@ +import { type EntrySources, entrySourcesOf } from "@ogw_internal/stores/hybrid_viewer/detail"; +import { LINE, MESH_ID, MODEL_ID, SURFACE } from "@ogw_tests/unit/helpers/hybrid_detail"; +import { + LINES_DEFAULT_COLOR, + POINTS_DEFAULT_SIZE, +} from "@ogw_front/utils/default_styles/constants"; +import { RGB_MAX, drawnCellColors, requireEntry } from "@ogw_tests/unit/helpers/hybrid_parts"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { lightViewableAlongZ, useFakeRenderWindow } from "@ogw_tests/unit/helpers/hybrid_scene"; +import { setupActivePinia } from "@ogw_tests/utils"; +import { useDataStyleState } from "@ogw_internal/stores/data_style/state"; +import { useDataStyleStore } from "@ogw_front/stores/data_style"; +import { useHybridViewerScene } from "@ogw_internal/stores/hybrid_viewer/scene"; +import { useModelComponentStyleMutations } from "@ogw_internal/stores/data_style/model/common_mutations"; + +vi.mock(import("@ogw_internal/stores/hybrid_viewer/detail"), async (importOriginal) => ({ + ...(await importOriginal()), + entrySourcesOf: vi.fn(), +})); + +vi.setConfig({ testTimeout: 10_000 }); + +const HALF = 0.5; +const LINES_GREY = LINES_DEFAULT_COLOR.red; +const RED = { red: RGB_MAX, green: 0, blue: 0, alpha: 1 }; +const SEE_THROUGH_RED = { red: RGB_MAX, green: 0, blue: 0, alpha: HALF }; + +const POINT_SIZE = 4; +// Its own id: the styles cache empties only once the database is observed cleared +const SIZED_MODEL = "sized-model"; +const LINE_WIDTH = 3; + +const meshSources: EntrySources = { + lightViewables: { [MESH_ID]: lightViewableAlongZ([0, 1]) }, + hidden: new Set(), + isModel: false, + types: {}, +}; + +const modelSources: EntrySources = { + lightViewables: { [SURFACE]: lightViewableAlongZ([0, 1]), [LINE]: lightViewableAlongZ([2, 3]) }, + hidden: new Set(), + isModel: true, + types: { [SURFACE]: "Surface", [LINE]: "Line" }, +}; + +describe("hybrid scene styles", () => { + setupActivePinia(); + + beforeEach(async () => { + useFakeRenderWindow(); + useHybridViewerScene().clear(); + await useDataStyleStore().clear(); + vi.mocked(entrySourcesOf).mockReset(); + }); + + test("a model is drawn with the colors of its components", async () => { + await useModelComponentStyleMutations().mutateComponentStyle(MODEL_ID, SURFACE, { + coloring: { constant: RED }, + }); + vi.mocked(entrySourcesOf).mockResolvedValue(modelSources); + const scene = useHybridViewerScene(); + + await scene.addItem(MODEL_ID); + + expect(drawnCellColors(requireEntry(scene.hybridDb[MODEL_ID]))).toStrictEqual([ + [RGB_MAX, 0, 0], + [LINES_GREY, LINES_GREY, LINES_GREY], + ]); + }); + + test("a color stored while the geometry loads is drawn", async () => { + const sources = Promise.withResolvers(); + vi.mocked(entrySourcesOf).mockReturnValueOnce(sources.promise); + const scene = useHybridViewerScene(); + + const adding = scene.addItem(MODEL_ID); + await useModelComponentStyleMutations().mutateComponentStyle(MODEL_ID, LINE, { + coloring: { constant: RED }, + }); + sources.resolve(modelSources); + await adding; + + expect(drawnCellColors(requireEntry(scene.hybridDb[MODEL_ID]))[1]).toStrictEqual([ + RGB_MAX, + 0, + 0, + ]); + }); + + test("a model's corners take its points size, its lines stay one pixel wide", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue(modelSources); + const scene = useHybridViewerScene(); + + await scene.addItem(MODEL_ID); + + const property = requireEntry(scene.hybridDb[MODEL_ID]).actor.getProperty(); + + expect([property.getPointSize(), property.getLineWidth()]).toStrictEqual([ + POINTS_DEFAULT_SIZE, + 1, + ]); + }); + + test("a model's stored points size is drawn", async () => { + await useDataStyleState().mutateStyle(SIZED_MODEL, { points: { size: POINT_SIZE } }); + vi.mocked(entrySourcesOf).mockResolvedValue(modelSources); + const scene = useHybridViewerScene(); + + await scene.addItem(SIZED_MODEL); + + expect(requireEntry(scene.hybridDb[SIZED_MODEL]).actor.getProperty().getPointSize()).toBe( + POINT_SIZE, + ); + }); + + test("a points size set in the viewer applies to the model actor", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue(modelSources); + const scene = useHybridViewerScene(); + await scene.addItem(MODEL_ID); + + scene.setPointSize(MODEL_ID, POINT_SIZE); + + expect(requireEntry(scene.hybridDb[MODEL_ID]).actor.getProperty().getPointSize()).toBe( + POINT_SIZE, + ); + }); + + test("a mesh is drawn with the color and opacity of its main element", async () => { + await useDataStyleState().mutateStyle(MESH_ID, { + polygons: { coloring: { constant: SEE_THROUGH_RED } }, + }); + vi.mocked(entrySourcesOf).mockResolvedValue(meshSources); + const scene = useHybridViewerScene(); + + await scene.addItem(MESH_ID); + + const entry = requireEntry(scene.hybridDb[MESH_ID]); + + expect(drawnCellColors(entry)).toStrictEqual([[RGB_MAX, 0, 0]]); + expect(entry.actor.getProperty().getOpacity()).toBe(HALF); + }); + + test("components recolored in the viewer are recolored in the light view", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue(modelSources); + const scene = useHybridViewerScene(); + await scene.addItem(MODEL_ID); + + scene.setComponentsColors(MODEL_ID, { [LINE]: RED }); + + expect(drawnCellColors(requireEntry(scene.hybridDb[MODEL_ID]))[1]).toStrictEqual([ + RGB_MAX, + 0, + 0, + ]); + }); + + test("a mesh takes the color, opacity, point size and line width set in the viewer", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue(meshSources); + const scene = useHybridViewerScene(); + await scene.addItem(MESH_ID); + + scene.setMeshStyle(MESH_ID, { color: SEE_THROUGH_RED }); + scene.setMeshStyle(MESH_ID, { pointSize: POINT_SIZE, lineWidth: LINE_WIDTH }); + + const entry = requireEntry(scene.hybridDb[MESH_ID]); + const property = entry.actor.getProperty(); + + expect(drawnCellColors(entry)).toStrictEqual([[RGB_MAX, 0, 0]]); + expect([property.getOpacity(), property.getPointSize(), property.getLineWidth()]).toStrictEqual( + [HALF, POINT_SIZE, LINE_WIDTH], + ); + }); + + test("an opacity set in the viewer applies to the mesh actor", async () => { + vi.mocked(entrySourcesOf).mockResolvedValue(meshSources); + const scene = useHybridViewerScene(); + await scene.addItem(MESH_ID); + + scene.setMeshStyle(MESH_ID, { opacity: HALF }); + + expect(requireEntry(scene.hybridDb[MESH_ID]).actor.getProperty().getOpacity()).toBe(HALF); + }); + + test("styles of data out of the light view are ignored", () => { + const scene = useHybridViewerScene(); + + scene.setComponentsColors(MODEL_ID, { [LINE]: RED }); + scene.setMeshStyle(MESH_ID, { opacity: HALF }); + + expect(scene.hybridDb).toStrictEqual({}); + }); +});