@geode/opengeodeweb-front 10.44.0-rc.6 → 10.44.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.build/server/utils/scripts.js +34 -23
  2. package/app/components/BasemapAttribution.vue +28 -0
  3. package/app/components/MissingFilesSelector.vue +30 -17
  4. package/app/components/ObjectSelector.vue +34 -23
  5. package/app/components/Viewer/Basemap/CropOptions.vue +50 -0
  6. package/app/components/Viewer/Basemap/OpacityOptions.vue +52 -0
  7. package/app/components/Viewer/ContextMenu/ContextMenu.vue +5 -1
  8. package/app/components/Viewer/ContextMenu/ContextMenuItem.vue +6 -2
  9. package/app/components/Viewer/ObjectTree/Views/GlobalObjects.vue +49 -10
  10. package/app/components/Viewer/Ui.vue +6 -0
  11. package/app/composables/overlapping_picker_menu.ts +43 -0
  12. package/app/composables/project_manager_helpers/reset.ts +3 -0
  13. package/app/composables/project_manager_helpers/restore.ts +22 -10
  14. package/app/composables/project_manager_helpers/types.ts +2 -0
  15. package/app/composables/use_overlapping_picker.ts +23 -37
  16. package/app/composables/viewer_context_menu.ts +10 -0
  17. package/app/composables/virtual_tree_flatten.ts +66 -43
  18. package/app/stores/app_helpers/extension.ts +90 -51
  19. package/app/stores/basemap.ts +52 -0
  20. package/app/stores/basemap_detail.ts +51 -0
  21. package/app/stores/basemap_helpers/builds.ts +158 -0
  22. package/app/stores/basemap_helpers/detail_layers.ts +72 -0
  23. package/app/stores/basemap_helpers/detail_map.ts +62 -0
  24. package/app/stores/basemap_helpers/detail_refresh.ts +134 -0
  25. package/app/stores/basemap_helpers/detail_view.ts +94 -0
  26. package/app/stores/basemap_helpers/extent.ts +40 -0
  27. package/app/stores/basemap_helpers/georeferenced.ts +50 -0
  28. package/app/stores/basemap_helpers/layers.ts +66 -0
  29. package/app/stores/basemap_helpers/settings.ts +87 -0
  30. package/app/stores/basemap_helpers/viewer.ts +114 -0
  31. package/app/stores/infra.ts +26 -21
  32. package/app/stores/menu_helpers/basemap.ts +10 -0
  33. package/app/stores/menu_helpers/menus_data.ts +2 -0
  34. package/app/utils/basemap_tree.ts +76 -0
  35. package/app/utils/color_picker.ts +18 -15
  36. package/app/utils/treeview.ts +12 -1
  37. package/app/utils/visible_map_area.ts +129 -0
  38. package/internal/database/database.ts +47 -32
  39. package/internal/stores/data_style/mesh/base_style.ts +74 -0
  40. package/internal/stores/data_style/mesh/index.ts +2 -57
  41. package/internal/stores/data_style/model/blocks/color.ts +58 -57
  42. package/internal/stores/data_style/model/blocks/polyhedron.ts +88 -44
  43. package/internal/stores/data_style/model/blocks/vertex.ts +88 -44
  44. package/internal/stores/data_style/model/color.ts +25 -26
  45. package/internal/stores/data_style/model/corners/index.ts +85 -78
  46. package/internal/stores/data_style/model/corners/vertex.ts +83 -39
  47. package/internal/stores/data_style/model/lines/color.ts +53 -40
  48. package/internal/stores/data_style/model/lines/edge.ts +88 -44
  49. package/internal/stores/data_style/model/lines/vertex.ts +88 -44
  50. package/internal/stores/data_style/model/surfaces/color.ts +68 -56
  51. package/internal/stores/data_style/model/surfaces/polygon.ts +80 -36
  52. package/internal/stores/data_style/model/surfaces/vertex.ts +80 -36
  53. package/internal/stores/data_style/model/visibility_dispatch.ts +49 -99
  54. package/internal/stores/hybrid_viewer/highlight.ts +70 -54
  55. package/internal/stores/hybrid_viewer/scene.ts +31 -25
  56. package/internal/stores/hybrid_viewer/vtk_types.ts +2 -1
  57. package/package.json +1 -1
  58. package/server/api/local/extensions/upload.put.ts +47 -20
  59. package/server/utils/scripts.ts +35 -30
@@ -0,0 +1,87 @@
1
+ import { type MapStyle, sortedMaps } from "@ogw_front/utils/basemap_tree";
2
+ import type { BasemapLayers } from "./layers.js";
3
+ import type { Ref } from "vue";
4
+ import { coalesced } from "./viewer.js";
5
+ import { everyMap } from "./extent.js";
6
+ import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer";
7
+
8
+ interface BasemapSnapshot {
9
+ maps?: MapStyle[];
10
+ opacities?: Partial<Record<MapStyle, number>>;
11
+ crop?: Partial<Record<MapStyle, boolean>>;
12
+ }
13
+
14
+ interface BasemapSettings {
15
+ setMaps: (newMaps: readonly MapStyle[]) => Promise<void>;
16
+ setOpacity: (mapStyle: MapStyle, value: number) => Promise<void>;
17
+ setCrop: (value: boolean, mapStyles: readonly MapStyle[]) => Promise<void>;
18
+ exportStores: () => Required<BasemapSnapshot>;
19
+ importStores: (snapshot: BasemapSnapshot | undefined) => Promise<void>;
20
+ }
21
+
22
+ // The choices of the user: a change already built only recomposes, the others rebuild
23
+ function useBasemapSettings(
24
+ layers: BasemapLayers,
25
+ basemapId: Ref<string | undefined>,
26
+ rebuild: () => Promise<void>,
27
+ ): BasemapSettings {
28
+ const hybridViewerStore = useHybridViewerStore();
29
+ const { shown, hidden, maps, opacities, crop, built, applyLayers } = layers;
30
+
31
+ const recompose = coalesced(async () => {
32
+ const id = basemapId.value;
33
+ if (id !== undefined) {
34
+ await applyLayers(id);
35
+ await hybridViewerStore.remoteRender();
36
+ }
37
+ });
38
+
39
+ // No map hides the basemap and keeps the last maps, to show them again. Hidden, the built
40
+ // Basemap stays with every layer invisible: shown again, it only recomposes
41
+ async function setMaps(newMaps: readonly MapStyle[]): Promise<void> {
42
+ if (newMaps.length === 0) {
43
+ hidden.value = true;
44
+ } else {
45
+ shown.value = sortedMaps(newMaps);
46
+ hidden.value = false;
47
+ }
48
+ const allBuilt = maps.value.every((mapStyle) => built.value.includes(mapStyle));
49
+ if (basemapId.value !== undefined && allBuilt) {
50
+ await recompose();
51
+ return;
52
+ }
53
+ await rebuild();
54
+ }
55
+
56
+ // No rebuild: each map keeps its opacity
57
+ async function setOpacity(mapStyle: MapStyle, value: number): Promise<void> {
58
+ opacities.value = { ...opacities.value, [mapStyle]: value };
59
+ await recompose();
60
+ }
61
+
62
+ // No rebuild
63
+ async function setCrop(value: boolean, mapStyles: readonly MapStyle[]): Promise<void> {
64
+ crop.value = {
65
+ ...crop.value,
66
+ ...Object.fromEntries(mapStyles.map((mapStyle) => [mapStyle, value])),
67
+ };
68
+ await recompose();
69
+ }
70
+
71
+ function exportStores(): Required<BasemapSnapshot> {
72
+ return { maps: maps.value, opacities: opacities.value, crop: crop.value };
73
+ }
74
+
75
+ // Called once the project data is imported. When the data is not displayed yet,
76
+ // The rebuild finds no bounds and the store rebuilds once it is displayed.
77
+ async function importStores(snapshot: BasemapSnapshot | undefined): Promise<void> {
78
+ opacities.value = { ...everyMap(1), ...snapshot?.opacities };
79
+ crop.value = { ...everyMap(false), ...snapshot?.crop };
80
+ await setMaps(sortedMaps(snapshot?.maps ?? ["satellite"]));
81
+ }
82
+
83
+ return { setMaps, setOpacity, setCrop, exportStores, importStores };
84
+ }
85
+
86
+ export type { BasemapSnapshot };
87
+ export { useBasemapSettings };
@@ -0,0 +1,114 @@
1
+ import back_schemas, {
2
+ type BasemapBuildResponse,
3
+ } from "@geode/opengeodeweb-back/opengeodeweb_back_typed_schemas.js";
4
+ import type { MapStyle } from "@ogw_front/utils/basemap_tree";
5
+ import { useBackStore } from "@ogw_front/stores/back";
6
+ import { useDataStore } from "@ogw_front/stores/data";
7
+ import { useViewerStore } from "@ogw_front/stores/viewer";
8
+ import viewer_schemas from "@geode/opengeodeweb-viewer/opengeodeweb_viewer_typed_schemas.js";
9
+
10
+ interface Layer {
11
+ map: MapStyle;
12
+ visible: boolean;
13
+ opacity: number;
14
+ crop: boolean;
15
+ }
16
+
17
+ function ignoreError(): void {
18
+ // Already reported by the request feedback
19
+ }
20
+
21
+ interface MapToShow {
22
+ response: BasemapBuildResponse;
23
+ name: string;
24
+ layers: Layer[];
25
+ dataIds: string[];
26
+ }
27
+
28
+ interface BasemapViewer {
29
+ discardMap: (id: string, registered: boolean) => Promise<void>;
30
+ sendLayers: (id: string, layers: Layer[]) => Promise<void>;
31
+ showMap: (map: Readonly<MapToShow>, detailOf?: string) => Promise<void>;
32
+ }
33
+
34
+ // The stores are taken once: a call still running after a project reset reaches its own stores
35
+ function useBasemapViewer(): BasemapViewer {
36
+ const backStore = useBackStore();
37
+ const dataStore = useDataStore();
38
+ const viewerStore = useViewerStore();
39
+
40
+ // Best effort: a map left behind is only a leftover, never an error to show twice.
41
+ // A registered map leaves the viewer before the back deletes its files
42
+ async function discardMap(id: string, registered: boolean): Promise<void> {
43
+ if (registered) {
44
+ await dataStore.deregisterObject(id).catch(ignoreError);
45
+ }
46
+ await backStore
47
+ .request({ schema: back_schemas.opengeodeweb_back.basemap.delete, params: { id } })
48
+ .catch(ignoreError);
49
+ }
50
+
51
+ // The viewer recomposes its textures: no download, no new mesh
52
+ async function sendLayers(id: string, layers: Layer[]): Promise<void> {
53
+ await viewerStore.request({
54
+ schema: viewer_schemas.opengeodeweb_viewer.mesh.basemap_layers,
55
+ params: { id, layers },
56
+ });
57
+ }
58
+
59
+ // Registers a built map, shows it with the layers and drapes the top surfaces of the data
60
+ async function showMap(
61
+ { response, name, layers, dataIds }: Readonly<MapToShow>,
62
+ detailOf?: string,
63
+ ): Promise<void> {
64
+ await dataStore.registerObject(response.id, name);
65
+ await viewerStore.request({
66
+ schema: viewer_schemas.opengeodeweb_viewer.mesh.apply_basemap,
67
+ params: {
68
+ id: response.id,
69
+ columns: response.columns,
70
+ rows: response.rows,
71
+ maps: response.maps,
72
+ layers,
73
+ detail_of: detailOf,
74
+ },
75
+ });
76
+ await viewerStore.request({
77
+ schema: viewer_schemas.opengeodeweb_viewer.mesh.basemap_drape,
78
+ params: { id: response.id, data_ids: dataIds },
79
+ });
80
+ }
81
+
82
+ return { discardMap, sendLayers, showMap };
83
+ }
84
+
85
+ // At most one run at a time: calls made meanwhile (a slider dragged) run once more when it
86
+ // Returns, with the latest states
87
+ function coalesced(run: () => Promise<void>): () => Promise<void> {
88
+ let running: Promise<void> | undefined = undefined;
89
+ let again = false;
90
+ async function latest(): Promise<void> {
91
+ again = false;
92
+ await run();
93
+ if (again) {
94
+ await latest();
95
+ }
96
+ }
97
+ return async () => {
98
+ if (running !== undefined) {
99
+ again = true;
100
+ await running;
101
+ return;
102
+ }
103
+ running = latest();
104
+ try {
105
+ await running;
106
+ } finally {
107
+ running = undefined;
108
+ again = false;
109
+ }
110
+ };
111
+ }
112
+
113
+ export type { Layer };
114
+ export { coalesced, ignoreError, useBasemapViewer };
@@ -14,6 +14,31 @@ declare global {
14
14
  var electronAPI: ElectronApi["electronAPI"];
15
15
  }
16
16
 
17
+ async function launchLocalServices(
18
+ currentMode: string,
19
+ microservices: readonly Microservice[],
20
+ ): Promise<void> {
21
+ const { useAppStore } = await import("@ogw_front/stores/app");
22
+ const appStore = useAppStore();
23
+ await appStore.createProjectFolder();
24
+ if (currentMode === appMode.DESKTOP) {
25
+ globalThis.electronAPI.project_folder_path({
26
+ projectFolderPath: appStore.projectFolderPath,
27
+ });
28
+ }
29
+ await setAppBaseUrl(appStore.base_url);
30
+ const microservices_with_launch = microservices.filter((store: Microservice) => store.launch);
31
+ const launch_promises = microservices_with_launch.map(async (store: Microservice) => {
32
+ const result = await store.launch?.({
33
+ projectFolderPath: appStore.projectFolderPath,
34
+ });
35
+ return result;
36
+ });
37
+ const { registerRunningExtensions } = await import("@ogw_front/utils/extension");
38
+ launch_promises.push(registerRunningExtensions());
39
+ await Promise.all(launch_promises);
40
+ }
41
+
17
42
  export const useInfraStore = defineStore("infra", {
18
43
  state: () => ({
19
44
  app_mode: useRuntimeConfig().public.MODE,
@@ -63,27 +88,7 @@ export const useInfraStore = defineStore("infra", {
63
88
  throw error;
64
89
  }
65
90
  } else {
66
- const { useAppStore } = await import("@ogw_front/stores/app");
67
- const appStore = useAppStore();
68
- await appStore.createProjectFolder();
69
- if (this.app_mode === appMode.DESKTOP) {
70
- globalThis.electronAPI.project_folder_path({
71
- projectFolderPath: appStore.projectFolderPath,
72
- });
73
- }
74
- await setAppBaseUrl(appStore.base_url);
75
- const microservices_with_launch = this.microservices.filter(
76
- (store: Microservice) => store.launch,
77
- );
78
- const launch_promises = microservices_with_launch.map(async (store: Microservice) => {
79
- const result = await store.launch?.({
80
- projectFolderPath: appStore.projectFolderPath,
81
- });
82
- return result;
83
- });
84
- const { registerRunningExtensions } = await import("@ogw_front/utils/extension");
85
- launch_promises.push(registerRunningExtensions());
86
- await Promise.all(launch_promises);
91
+ await launchLocalServices(this.app_mode, this.microservices);
87
92
  }
88
93
  this.status = Status.CREATED;
89
94
  return this.create_connection();
@@ -0,0 +1,10 @@
1
+ import BasemapCropOptions from "@ogw_front/components/Viewer/Basemap/CropOptions.vue";
2
+ import BasemapOpacityOptions from "@ogw_front/components/Viewer/Basemap/OpacityOptions.vue";
3
+ import type { MenuItems } from "./types.js";
4
+
5
+ const basemapMenus: Record<string, MenuItems> = {
6
+ Basemap: [BasemapCropOptions],
7
+ Map: [BasemapOpacityOptions, BasemapCropOptions],
8
+ };
9
+
10
+ export { basemapMenus };
@@ -1,5 +1,6 @@
1
1
  import { modelComponentMenus, modelComponentTypeMenus, modelMenus } from "./model.js";
2
2
  import type { MenuItems } from "./types.js";
3
+ import { basemapMenus } from "./basemap.js";
3
4
  import { edgedCurveMenus } from "./mesh/edged_curve.js";
4
5
  import { gridMenus } from "./mesh/grid.js";
5
6
  import { pointSetMenus } from "./mesh/point_set.js";
@@ -17,6 +18,7 @@ const menusData: Record<string, Record<string, MenuItems>> = {
17
18
  model: modelMenus,
18
19
  model_component_type: modelComponentTypeMenus,
19
20
  model_component: modelComponentMenus,
21
+ basemap: basemapMenus,
20
22
  };
21
23
 
22
24
  export { menusData };
@@ -0,0 +1,76 @@
1
+ type MapStyle = "satellite" | "plan" | "routes";
2
+
3
+ interface BasemapTreeGroup {
4
+ id: string;
5
+ title: string;
6
+ children: { id: string; title: string }[];
7
+ }
8
+
9
+ // Tree order and stacking order: from the bottom up, the routes stay readable on top
10
+ const MAP_STYLES: readonly MapStyle[] = ["satellite", "plan", "routes"];
11
+ const MAP_TITLES: Record<MapStyle, string> = {
12
+ satellite: "Satellite",
13
+ plan: "Plan",
14
+ routes: "Routes",
15
+ };
16
+ const BASEMAP_GROUP_ID = "basemap";
17
+ const MAP_ID_PREFIX = `${BASEMAP_GROUP_ID}:`;
18
+
19
+ function mapId(style: MapStyle): string {
20
+ return `${MAP_ID_PREFIX}${style}`;
21
+ }
22
+
23
+ function mapStyleOf(id: string): MapStyle | undefined {
24
+ return MAP_STYLES.find((style) => mapId(style) === id);
25
+ }
26
+
27
+ function sortedMaps(maps: readonly string[]): MapStyle[] {
28
+ return MAP_STYLES.filter((style) => maps.includes(style));
29
+ }
30
+
31
+ // Tree ids of the basemap: never project data
32
+ function isBasemapId(id: string): boolean {
33
+ return id === BASEMAP_GROUP_ID || id.startsWith(MAP_ID_PREFIX);
34
+ }
35
+
36
+ function basemapGroup(): BasemapTreeGroup {
37
+ return {
38
+ id: BASEMAP_GROUP_ID,
39
+ title: "Basemap",
40
+ children: MAP_STYLES.map((style) => ({ id: mapId(style), title: MAP_TITLES[style] })),
41
+ };
42
+ }
43
+
44
+ // Each map eye shows or hides its map. The classic tree adds the group and every map on a
45
+ // Group click: that click hides the visible maps, or shows the last visible maps again
46
+ function nextBasemapMaps(
47
+ current: readonly MapStyle[],
48
+ last: readonly MapStyle[],
49
+ added: readonly string[],
50
+ removed: readonly string[],
51
+ ): MapStyle[] {
52
+ const addedMaps = added.flatMap((id) => mapStyleOf(id) ?? []);
53
+ if (added.includes(BASEMAP_GROUP_ID) || addedMaps.length > 1) {
54
+ if (current.length === 0) {
55
+ return [...last];
56
+ }
57
+ return [];
58
+ }
59
+ const removedMaps = removed.flatMap((id) => mapStyleOf(id) ?? []);
60
+ if (removed.includes(BASEMAP_GROUP_ID) && removedMaps.length === 0) {
61
+ return [];
62
+ }
63
+ return sortedMaps([...current, ...addedMaps].filter((style) => !removedMaps.includes(style)));
64
+ }
65
+
66
+ export type { MapStyle };
67
+ export {
68
+ BASEMAP_GROUP_ID,
69
+ MAP_STYLES,
70
+ basemapGroup,
71
+ isBasemapId,
72
+ mapId,
73
+ mapStyleOf,
74
+ nextBasemapMaps,
75
+ sortedMaps,
76
+ };
@@ -10,6 +10,20 @@ function parseComponent(val: string, max = RGB_MAX): number {
10
10
  return Number(val);
11
11
  }
12
12
 
13
+ function clampChannel(value: number): number {
14
+ return Math.min(RGB_MAX, Math.max(0, Math.round(value)));
15
+ }
16
+
17
+ function parseAlpha(alphaText: string | undefined): number {
18
+ if (alphaText === undefined) {
19
+ return 1;
20
+ }
21
+ const rawAlpha = parseComponent(alphaText, 1);
22
+ const calculatedAlpha = rawAlpha > 1 ? rawAlpha / RGB_MAX : rawAlpha;
23
+ const roundedAlpha = Number(calculatedAlpha.toFixed(2));
24
+ return Math.min(1, Math.max(0, roundedAlpha));
25
+ }
26
+
13
27
  function parseColorString(colorText: string): RGBAColor | undefined {
14
28
  if (colorText === "") {
15
29
  return undefined;
@@ -21,21 +35,10 @@ function parseColorString(colorText: string): RGBAColor | undefined {
21
35
  }
22
36
 
23
37
  const [redText = "", greenText = "", blueText = "", alphaText] = numbersMatch;
24
- const rawRed = parseComponent(redText);
25
- const rawGreen = parseComponent(greenText);
26
- const rawBlue = parseComponent(blueText);
27
-
28
- const red = Math.min(RGB_MAX, Math.max(0, Math.round(rawRed)));
29
- const green = Math.min(RGB_MAX, Math.max(0, Math.round(rawGreen)));
30
- const blue = Math.min(RGB_MAX, Math.max(0, Math.round(rawBlue)));
31
-
32
- let alpha = 1;
33
- if (alphaText !== undefined) {
34
- const rawAlpha = parseComponent(alphaText, 1);
35
- const calculatedAlpha = rawAlpha > 1 ? rawAlpha / RGB_MAX : rawAlpha;
36
- const roundedAlpha = Number(calculatedAlpha.toFixed(2));
37
- alpha = Math.min(1, Math.max(0, roundedAlpha));
38
- }
38
+ const red = clampChannel(parseComponent(redText));
39
+ const green = clampChannel(parseComponent(greenText));
40
+ const blue = clampChannel(parseComponent(blueText));
41
+ const alpha = parseAlpha(alphaText);
39
42
 
40
43
  if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue) || Number.isNaN(alpha)) {
41
44
  return undefined;
@@ -29,7 +29,18 @@ interface ModelComponentMenuPayload {
29
29
  targetComponentIds?: string[];
30
30
  }
31
31
 
32
- type TreeMenuPayload = DataMenuPayload | GeodeObjectTypeMenuPayload | ModelComponentMenuPayload;
32
+ // The basemap category and its maps: not project data
33
+ interface BasemapMenuPayload {
34
+ event: MouseEvent;
35
+ itemId: string;
36
+ context_type: "basemap";
37
+ }
38
+
39
+ type TreeMenuPayload =
40
+ | DataMenuPayload
41
+ | GeodeObjectTypeMenuPayload
42
+ | ModelComponentMenuPayload
43
+ | BasemapMenuPayload;
33
44
 
34
45
  export { compareSelections };
35
46
  export type {
@@ -0,0 +1,129 @@
1
+ import { cross, multiplyAccumulate, normalize, subtract } from "@kitware/vtk.js/Common/Core/Math";
2
+ import type { CameraOptions } from "@ogw_internal/stores/hybrid_viewer/vtk_types";
3
+ import type { Vector3 } from "@kitware/vtk.js/types";
4
+
5
+ interface MapBounds {
6
+ x_min: number;
7
+ y_min: number;
8
+ x_max: number;
9
+ y_max: number;
10
+ }
11
+
12
+ // A map built by the back: its area and its number of tile columns
13
+ interface MapGrid {
14
+ bounds: MapBounds;
15
+ columns: number;
16
+ }
17
+
18
+ type ViewCamera = Pick<
19
+ CameraOptions,
20
+ "position" | "focal_point" | "view_up" | "view_angle" | "distance"
21
+ >;
22
+
23
+ // About one tile level (x2): the map changes by steps, not at every small move
24
+ const DETAIL_RATIO = 1.5;
25
+ const TILE_SIZE = 256;
26
+ const DEGREES = 180;
27
+ const HALF = 2;
28
+
29
+ // The ground size of one pixel of the map
30
+ function mapResolution(grid: MapGrid): number {
31
+ return (grid.bounds.x_max - grid.bounds.x_min) / (grid.columns * TILE_SIZE);
32
+ }
33
+
34
+ // Where a corner ray meets the map plane, or, past the horizon, the base edge in its direction
35
+ function groundPoint(
36
+ origin: Vector3,
37
+ direction: Vector3,
38
+ planeZ: number,
39
+ reach: number,
40
+ ): [number, number] {
41
+ const distance = (planeZ - origin[2]) / direction[2];
42
+ if (direction[2] < 0 && distance > 0) {
43
+ return [origin[0] + direction[0] * distance, origin[1] + direction[1] * distance];
44
+ }
45
+ const flat = Math.hypot(direction[0], direction[1]) || 1;
46
+ return [origin[0] + (direction[0] / flat) * reach, origin[1] + (direction[1] / flat) * reach];
47
+ }
48
+
49
+ // The part of the base map the screen shows, from the rays of its 4 corners
50
+ function visibleMapArea(
51
+ camera: ViewCamera,
52
+ aspect: number,
53
+ planeZ: number,
54
+ base: MapBounds,
55
+ ): MapBounds | undefined {
56
+ const forward = subtract(camera.focal_point, camera.position, [0, 0, 0]);
57
+ normalize(forward);
58
+ const right = cross(forward, camera.view_up, [0, 0, 0]);
59
+ normalize(right);
60
+ const upward = cross(right, forward, [0, 0, 0]);
61
+ const halfHeight = Math.tan((camera.view_angle * Math.PI) / DEGREES / HALF);
62
+ const halfWidth = halfHeight * aspect;
63
+ const reach = Math.hypot(base.x_max - base.x_min, base.y_max - base.y_min);
64
+ const corners = [
65
+ [-1, -1],
66
+ [1, -1],
67
+ [1, 1],
68
+ [-1, 1],
69
+ ].map(([column = 0, row = 0]) => {
70
+ const direction = multiplyAccumulate(forward, right, column * halfWidth, [0, 0, 0]);
71
+ multiplyAccumulate(direction, upward, row * halfHeight, direction);
72
+ return groundPoint(camera.position, direction, planeZ, reach);
73
+ });
74
+ const xValues = corners.map((corner) => corner[0]);
75
+ const yValues = corners.map((corner) => corner[1]);
76
+ const visibleArea = {
77
+ x_min: Math.max(base.x_min, Math.min(...xValues)),
78
+ y_min: Math.max(base.y_min, Math.min(...yValues)),
79
+ x_max: Math.min(base.x_max, Math.max(...xValues)),
80
+ y_max: Math.min(base.y_max, Math.max(...yValues)),
81
+ };
82
+ if (visibleArea.x_min >= visibleArea.x_max || visibleArea.y_min >= visibleArea.y_max) {
83
+ return undefined;
84
+ }
85
+ return visibleArea;
86
+ }
87
+
88
+ // The ground size of one screen pixel at the focal point
89
+ function screenPixelGroundSize(camera: ViewCamera, viewportHeight: number): number {
90
+ return (
91
+ (HALF * camera.distance * Math.tan((camera.view_angle * Math.PI) / DEGREES / HALF)) /
92
+ viewportHeight
93
+ );
94
+ }
95
+
96
+ // Below this gain the detail would look the same as the base
97
+ function needsSharperMap(baseResolution: number, wanted: number): boolean {
98
+ return baseResolution > DETAIL_RATIO * wanted;
99
+ }
100
+
101
+ // Whether the map area covers the whole visible area
102
+ function covers(area: MapBounds, visible: MapBounds): boolean {
103
+ return (
104
+ visible.x_min >= area.x_min &&
105
+ visible.y_min >= area.y_min &&
106
+ visible.x_max <= area.x_max &&
107
+ visible.y_max <= area.y_max
108
+ );
109
+ }
110
+
111
+ // A detail map stays while the view keeps within its area and its step of resolution
112
+ function stillSharp(detail: MapGrid, visible: MapBounds, wanted: number): boolean {
113
+ const resolution = mapResolution(detail);
114
+ return (
115
+ covers(detail.bounds, visible) &&
116
+ resolution <= wanted * DETAIL_RATIO &&
117
+ resolution >= wanted / DETAIL_RATIO
118
+ );
119
+ }
120
+
121
+ export type { MapBounds, MapGrid, ViewCamera };
122
+ export {
123
+ covers,
124
+ mapResolution,
125
+ needsSharperMap,
126
+ screenPixelGroundSize,
127
+ stillSharp,
128
+ visibleMapArea,
129
+ };
@@ -8,6 +8,51 @@ interface DatabaseContainer {
8
8
 
9
9
  const databaseContainer: DatabaseContainer = { instance: undefined };
10
10
 
11
+ interface CurrentSchema {
12
+ currentVersion: number;
13
+ currentStores: Record<string, string>;
14
+ }
15
+
16
+ function tableStoreDefinition(table: Table): string {
17
+ const keyPath = table.schema.primKey.src;
18
+ const indexes = table.schema.indexes.map((index) => index.src);
19
+ if (keyPath) {
20
+ return [keyPath, ...indexes].join(",");
21
+ }
22
+ return indexes.join(",");
23
+ }
24
+
25
+ async function readCurrentSchema(): Promise<CurrentSchema> {
26
+ const currentStores: Record<string, string> = { ...BaseDatabase.initialStores };
27
+ if (!(await Dexie.exists("Database"))) {
28
+ return { currentVersion: 1, currentStores };
29
+ }
30
+ const tempDb = new Dexie("Database");
31
+ await tempDb.open();
32
+ const currentVersion = tempDb.verno;
33
+ for (const table of tempDb.tables) {
34
+ currentStores[table.name] = tableStoreDefinition(table);
35
+ }
36
+ tempDb.close();
37
+ return { currentVersion, currentStores };
38
+ }
39
+
40
+ async function openExistingDatabase(
41
+ currentVersion: number,
42
+ currentStores: Record<string, string>,
43
+ ): Promise<Dexie> {
44
+ const existingDb = new Dexie("Database");
45
+ for (let version = 1; version <= currentVersion; version += 1) {
46
+ if (version === 1) {
47
+ existingDb.version(1).stores(BaseDatabase.initialStores);
48
+ } else {
49
+ existingDb.version(version).stores(currentStores);
50
+ }
51
+ }
52
+ await existingDb.open();
53
+ return existingDb;
54
+ }
55
+
11
56
  class Database extends BaseDatabase {
12
57
  public constructor() {
13
58
  super("Database");
@@ -20,28 +65,7 @@ class Database extends BaseDatabase {
20
65
  }
21
66
 
22
67
  public static async addTables(newTables: Record<string, string>): Promise<void> {
23
- let currentVersion = 1;
24
- let currentStores: Record<string, string> = { ...BaseDatabase.initialStores };
25
-
26
- if (await Dexie.exists("Database")) {
27
- const tempDb = new Dexie("Database");
28
- await tempDb.open();
29
-
30
- currentVersion = tempDb.verno;
31
- currentStores = { ...BaseDatabase.initialStores };
32
-
33
- for (const table of tempDb.tables) {
34
- const keyPath = table.schema.primKey.src;
35
- const indexes = table.schema.indexes.map((index) => index.src);
36
- let parts = indexes;
37
- if (keyPath) {
38
- parts = [keyPath, ...indexes];
39
- }
40
- currentStores[table.name] = parts.join(",");
41
- }
42
-
43
- tempDb.close();
44
- }
68
+ const { currentVersion, currentStores } = await readCurrentSchema();
45
69
 
46
70
  const allExisting = Object.keys(newTables).every(
47
71
  (tableName) => currentStores[tableName] !== undefined,
@@ -51,16 +75,7 @@ class Database extends BaseDatabase {
51
75
  databaseContainer.instance?.close();
52
76
 
53
77
  if (allExisting) {
54
- const existingDb = new Dexie("Database");
55
- for (let version = 1; version <= currentVersion; version += 1) {
56
- if (version === 1) {
57
- existingDb.version(1).stores(BaseDatabase.initialStores);
58
- } else {
59
- existingDb.version(version).stores(currentStores);
60
- }
61
- }
62
- await existingDb.open();
63
- databaseContainer.instance = existingDb;
78
+ databaseContainer.instance = await openExistingDatabase(currentVersion, currentStores);
64
79
  } else {
65
80
  const newDb = new ExtendedDatabase(currentVersion, currentStores, newTables);
66
81
  await newDb.open();