Files
worldwideview/src/core/globe/ModelManager.ts
SilvertakanaandCopilot Autofix powered by AI 16c82c9184 refactor(lint): address React 19 hook purity and immutability violations (#136)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-16 13:03:05 +12:00

118 lines
3.6 KiB
TypeScript

/**
* Manages 3D glTF model primitives on the Cesium viewer.
* Models are loaded asynchronously and cached by URL to avoid re-downloading.
*/
import {
Cartesian3,
Color,
HeadingPitchRoll,
Math as CesiumMath,
Model,
Transforms,
Matrix4,
} from "cesium";
import type { Scene } from "cesium";
import type { GeoEntity, CesiumEntityOptions } from "@/core/plugins/PluginTypes";
import type { AnimatableItem } from "./EntityRenderer";
/** Track pending model loads to prevent duplicate async loads for the same entity */
const pendingLoads = new Set<string>();
/** Scratch objects reused every frame to avoid heap allocations */
const scratchHPR = new HeadingPitchRoll();
const scratchMatrix = new Matrix4();
/**
* Create a 3D model primitive for an entity and attach it to the scene.
* This is async because Model.fromGltfAsync needs to download/parse the glTF.
*/
export async function createModelPrimitive(
scene: Scene,
item: AnimatableItem
): Promise<void> {
const { entity, options, posRef } = item;
if (!options.modelUrl || pendingLoads.has(entity.id)) return;
pendingLoads.add(entity.id);
try {
const offset = options.modelHeadingOffset || 0;
const headingRad = CesiumMath.toRadians((entity.heading || 0) + offset);
const hpr = new HeadingPitchRoll(headingRad, 0, 0);
const modelMatrix = Transforms.headingPitchRollToFixedFrame(posRef, hpr);
const scale = options.modelScale || 1.0;
Matrix4.multiplyByUniformScale(modelMatrix, scale, modelMatrix);
const model = await Model.fromGltfAsync({
url: options.modelUrl,
modelMatrix,
scale: 1.0, // Scale is baked into the modelMatrix
minimumPixelSize: options.modelMinPixelSize ?? 24,
maximumScale: scale * 5,
color: options.color ? Color.fromCssColorString(options.color) : undefined,
silhouetteColor: Color.CYAN,
silhouetteSize: 0,
id: { _wwvEntity: entity },
});
if (scene.isDestroyed()) return;
scene.primitives.add(model);
item.primitive = model;
} catch (err) {
console.warn(`[ModelManager] Failed to load model for ${entity.id}:`, err);
} finally {
pendingLoads.delete(entity.id);
}
}
/**
* Update the position and heading of an existing model primitive.
* Uses scratch allocations to avoid per-frame heap pressure.
*/
export function updateModelTransform(
item: AnimatableItem,
position: Cartesian3,
heading?: number
): void {
const modelsToUpdate: any[] = [];
if (item.primitive && item.primitive.modelMatrix) {
modelsToUpdate.push(item.primitive);
}
if (item.promotedModel && item.promotedModel.modelMatrix) {
modelsToUpdate.push(item.promotedModel);
}
if (modelsToUpdate.length === 0) return;
const offset = item.options.modelHeadingOffset || 0;
scratchHPR.heading = CesiumMath.toRadians((heading || 0) + offset);
scratchHPR.pitch = 0;
scratchHPR.roll = 0;
Transforms.headingPitchRollToFixedFrame(
position,
scratchHPR,
undefined,
undefined,
scratchMatrix
);
const scale = item.options.modelScale || 1.0;
Matrix4.multiplyByUniformScale(scratchMatrix, scale, scratchMatrix);
for (const model of modelsToUpdate) {
Matrix4.clone(scratchMatrix, model.modelMatrix);
}
}
/**
* Remove a model primitive from the scene.
*/
export function removeModelPrimitive(scene: Scene, item: AnimatableItem): void {
if (!item.primitive) return;
try {
scene.primitives.remove(item.primitive);
} catch { /* Already removed or destroyed */ }
}