chore: checkpoint premium 3d stages 0 and 1
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -120,6 +120,10 @@ export default function ProductDemoSection({
|
||||
setContextLost(true);
|
||||
setViewMode('2d');
|
||||
}}
|
||||
onUse2D={() => {
|
||||
setContextLost(true);
|
||||
setViewMode('2d');
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={<div className="three-loading">Загрузка 3D digital twin…</div>}>
|
||||
<SorterDigitalTwin
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { Suspense } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import * as THREE from 'three';
|
||||
import type { SimulatedItem, SimulationState } from '../../domain/types';
|
||||
import { itemPosition3D, ROUTE_COLORS } from './itemMotion';
|
||||
import { DIMENSION_LIMITS } from '../../domain/classifier';
|
||||
import { getModelAsset } from '../../data/modelAssets';
|
||||
import STLModel from './STLModel';
|
||||
import { getRenderedItemDimensions } from '../../domain/physicalLayout';
|
||||
import RealItemModel from './RealItemModel';
|
||||
|
||||
/**
|
||||
* Visual scale multiplier for 3D demo visibility.
|
||||
* Physical dimensions remain unchanged in data/proof panel.
|
||||
* This only affects the rendered mesh size so item is visible in scene.
|
||||
* Stage 1: VISUAL_SCALE_MULTIPLIER (2.5x) and the 0.12–0.45m clamps removed.
|
||||
* `/details` now renders the same true physical scale as `/` (1 unit = 1m),
|
||||
* with the shared manifest transform (bottom-center pivot, mm→m uniform).
|
||||
*/
|
||||
const VISUAL_SCALE_MULTIPLIER = 2.5;
|
||||
|
||||
interface Props {
|
||||
simulation: SimulationState;
|
||||
@@ -36,38 +36,20 @@ function FallbackPrimitive({
|
||||
roughness: number;
|
||||
emissiveIntensity?: number;
|
||||
}) {
|
||||
if (primitive === 'cylinder') {
|
||||
return (
|
||||
<mesh>
|
||||
<cylinderGeometry args={[Math.min(sx, sz) / 2, Math.min(sx, sz) / 2, sy, 24]} />
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
emissive={emissive}
|
||||
emissiveIntensity={emissiveIntensity}
|
||||
roughness={roughness}
|
||||
/>
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
const geometry = useMemo<THREE.BufferGeometry>(() => {
|
||||
if (primitive === 'cylinder') {
|
||||
return new THREE.CylinderGeometry(Math.min(sx, sz) / 2, Math.min(sx, sz) / 2, sy, 24);
|
||||
}
|
||||
if (primitive === 'sphere') {
|
||||
return new THREE.SphereGeometry(Math.max(sx, sy, sz) / 2, 24, 16);
|
||||
}
|
||||
return new THREE.BoxGeometry(sx, sy, sz);
|
||||
}, [primitive, sx, sy, sz]);
|
||||
useEffect(() => () => geometry.dispose(), [geometry]);
|
||||
|
||||
if (primitive === 'sphere') {
|
||||
return (
|
||||
<mesh>
|
||||
<sphereGeometry args={[Math.max(sx, sy, sz) / 2, 24, 16]} />
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
emissive={emissive}
|
||||
emissiveIntensity={emissiveIntensity}
|
||||
roughness={roughness}
|
||||
/>
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
// default: box
|
||||
// center-pivot primitives are lifted so their bottom touches the surface
|
||||
return (
|
||||
<mesh>
|
||||
<boxGeometry args={[sx, sy, sz]} />
|
||||
<mesh geometry={geometry} position={[0, sy / 2, 0]}>
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
emissive={emissive}
|
||||
@@ -86,90 +68,58 @@ export default function Item3D({ simulation, currentItem }: Props) {
|
||||
const [x, y, z] = itemPosition3D(simulation);
|
||||
const category = currentItem.classification.category;
|
||||
const color = ROUTE_COLORS[category] ?? '#38bdf8';
|
||||
const dims = currentItem.item.dimensionsMm;
|
||||
|
||||
// Physical scale to Three.js units (1 unit = 1 meter, dimensions in mm)
|
||||
const physicalSx = Math.max(0.12, Math.min(0.45, dims.width / 1000));
|
||||
const physicalSy = Math.max(0.1, Math.min(0.4, dims.height / 1000));
|
||||
const physicalSz = Math.max(0.12, Math.min(0.45, dims.depth / 1000));
|
||||
|
||||
// Apply visual multiplier for demo visibility (does not affect proof panel data)
|
||||
const sx = physicalSx * VISUAL_SCALE_MULTIPLIER;
|
||||
const sy = physicalSy * VISUAL_SCALE_MULTIPLIER;
|
||||
const sz = physicalSz * VISUAL_SCALE_MULTIPLIER;
|
||||
|
||||
const dims = getRenderedItemDimensions(currentItem.item.dimensionsMm);
|
||||
const sx = dims.width;
|
||||
const sy = dims.height;
|
||||
const sz = dims.depth;
|
||||
|
||||
const detecting = simulation.machineState === 'DETECTING';
|
||||
const moving = simulation.machineState.startsWith('ROUTE_TO_') ||
|
||||
const moving = simulation.machineState.startsWith('ROUTE_TO_') ||
|
||||
simulation.machineState === 'MOVING_TO_CAMERA' ||
|
||||
simulation.machineState === 'MOVING_TO_GATE';
|
||||
const fault = simulation.machineState === 'FAULT' || simulation.machineState === 'EMERGENCY_STOP';
|
||||
|
||||
// Get model asset for this item
|
||||
|
||||
const asset = getModelAsset(currentItem.item.id);
|
||||
const finalColor = fault ? '#fb3d4e' : color;
|
||||
const finalEmissive = fault ? '#fb3d4e' : color;
|
||||
const finalRoughness = asset?.loaderType === 'stl' ? 0.35 : 0.4;
|
||||
// Brighter emissive when moving for visibility
|
||||
const finalRoughness = asset?.defaultRealAsset ? 0.35 : 0.4;
|
||||
const emissiveBoost = moving ? 0.55 : 0.35;
|
||||
|
||||
// Fallback primitive
|
||||
|
||||
const fallbackPrimitive = asset?.fallbackPrimitive ?? 'box';
|
||||
|
||||
const useReal = Boolean(asset?.defaultRealAsset && asset?.runtimePath);
|
||||
|
||||
const fallback = (
|
||||
<FallbackPrimitive
|
||||
primitive={fallbackPrimitive}
|
||||
sx={sx}
|
||||
sy={sy}
|
||||
sz={sz}
|
||||
color={finalColor}
|
||||
emissive={finalEmissive}
|
||||
roughness={finalRoughness}
|
||||
emissiveIntensity={emissiveBoost}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<group position={[x, y, z]}>
|
||||
{asset && asset.loaderType === 'stl' && asset.frontendAssetPath ? (
|
||||
<Suspense
|
||||
fallback={
|
||||
<FallbackPrimitive
|
||||
primitive={fallbackPrimitive}
|
||||
sx={sx}
|
||||
sy={sy}
|
||||
sz={sz}
|
||||
color={finalColor}
|
||||
emissive={finalEmissive}
|
||||
roughness={finalRoughness}
|
||||
emissiveIntensity={emissiveBoost}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<STLModel
|
||||
path={asset.frontendAssetPath}
|
||||
scale={[sx, sy, sz]}
|
||||
rotation={[0, 0, 0]}
|
||||
position={[0, 0, 0]}
|
||||
color={finalColor}
|
||||
emissive={finalEmissive}
|
||||
emissiveIntensity={emissiveBoost}
|
||||
roughness={finalRoughness}
|
||||
fallback={
|
||||
<FallbackPrimitive
|
||||
primitive={fallbackPrimitive}
|
||||
sx={sx}
|
||||
sy={sy}
|
||||
sz={sz}
|
||||
color={finalColor}
|
||||
emissive={finalEmissive}
|
||||
roughness={finalRoughness}
|
||||
emissiveIntensity={emissiveBoost}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<FallbackPrimitive
|
||||
primitive={fallbackPrimitive}
|
||||
sx={sx}
|
||||
sy={sy}
|
||||
sz={sz}
|
||||
color={finalColor}
|
||||
emissive={finalEmissive}
|
||||
roughness={finalRoughness}
|
||||
emissiveIntensity={emissiveBoost}
|
||||
{useReal && asset ? (
|
||||
<RealItemModel
|
||||
asset={asset}
|
||||
material={{
|
||||
color: finalColor,
|
||||
emissive: finalEmissive,
|
||||
emissiveIntensity: emissiveBoost,
|
||||
roughness: finalRoughness,
|
||||
}}
|
||||
fallback={fallback}
|
||||
/>
|
||||
) : (
|
||||
fallback
|
||||
)}
|
||||
|
||||
{/* Glow ring under item for visibility */}
|
||||
<mesh position={[0, -sy / 2 + 0.01, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
{/* Glow ring at the contact plane under the item */}
|
||||
<mesh position={[0, 0.01, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
<ringGeometry args={[Math.max(sx, sz) * 0.4, Math.max(sx, sz) * 0.6, 32]} />
|
||||
<meshStandardMaterial
|
||||
color={finalColor}
|
||||
@@ -181,7 +131,7 @@ export default function Item3D({ simulation, currentItem }: Props) {
|
||||
</mesh>
|
||||
|
||||
{detecting ? (
|
||||
<mesh>
|
||||
<mesh position={[0, sy / 2, 0]}>
|
||||
<boxGeometry args={[sx + 0.12, sy + 0.12, sz + 0.12]} />
|
||||
<meshStandardMaterial color="#38bdf8" wireframe transparent opacity={0.9} />
|
||||
</mesh>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Suspense, memo, useEffect, useMemo } from 'react';
|
||||
import { memo, useEffect, useMemo } from 'react';
|
||||
import { getPhysicalItemPose } from '../../domain/physicalItemMotion';
|
||||
import { getModelAsset } from '../../data/modelAssets';
|
||||
import { resolveItem } from '../../data/resolveItem';
|
||||
@@ -6,8 +6,8 @@ import type { PlaylistCase } from '../../domain/demoPlaylist';
|
||||
import { classifyItem } from '../../domain/classifier';
|
||||
import { getRenderedItemDimensions } from '../../domain/physicalLayout';
|
||||
import * as THREE from 'three';
|
||||
import { useLoader } from '@react-three/fiber';
|
||||
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||
import RealItemModel from './RealItemModel';
|
||||
import { ItemVerificationOverlay } from './RealModelVerification';
|
||||
|
||||
const COLORS = {
|
||||
B: '#16a34a',
|
||||
@@ -16,14 +16,17 @@ const COLORS = {
|
||||
sensorAccent: '#3b82f6',
|
||||
};
|
||||
|
||||
/** Base real-model materials per SKU (Stage 1 §20 — basic, form-revealing). */
|
||||
const ITEM_MATERIALS: Record<string, { color: string; roughness: number; metalness?: number }> = {
|
||||
'SKU-001': { color: '#b68b58', roughness: 0.82 },
|
||||
'SKU-002': { color: '#e8eef6', roughness: 0.5 },
|
||||
'SKU-004': { color: '#c49a6c', roughness: 0.82 },
|
||||
'SKU-006': { color: '#f8fafc', roughness: 0.42 },
|
||||
'SKU-007': { color: '#7dd3fc', roughness: 0.28 },
|
||||
'SKU-001': { color: '#b68b58', roughness: 0.82 }, // cardboard
|
||||
'SKU-002': { color: '#e8eef6', roughness: 0.5 }, // lunchbox plastic
|
||||
'SKU-003': { color: '#93c5fd', roughness: 0.38 }, // detergent jug plastic
|
||||
'SKU-004': { color: '#c49a6c', roughness: 0.82 }, // cardboard
|
||||
'SKU-005': { color: '#a78bfa', roughness: 0.92 }, // soft pouf fabric
|
||||
'SKU-006': { color: '#f8fafc', roughness: 0.42 }, // plate ceramic
|
||||
'SKU-007': { color: '#7dd3fc', roughness: 0.28 }, // bottle plastic
|
||||
'SKU-008': { color: '#cbd5e1', roughness: 0.35, metalness: 0.15 },
|
||||
'SKU-011': { color: '#cbd5e1', roughness: 0.35, metalness: 0.15 },
|
||||
'SKU-009': { color: '#475569', roughness: 0.5 }, // pen body
|
||||
};
|
||||
|
||||
interface RenderProps {
|
||||
@@ -34,29 +37,10 @@ interface RenderProps {
|
||||
metalness: number;
|
||||
}
|
||||
|
||||
function STLGeometry({ path, scale, color, accentColor, emissiveIntensity, roughness, metalness }: RenderProps & {
|
||||
path: string;
|
||||
scale: [number, number, number];
|
||||
}) {
|
||||
const geometry = useLoader(STLLoader, path) as THREE.BufferGeometry;
|
||||
useMemo(() => {
|
||||
if (geometry) {
|
||||
geometry.center();
|
||||
geometry.computeVertexNormals();
|
||||
}
|
||||
}, [geometry]);
|
||||
return (
|
||||
<group scale={scale}>
|
||||
<mesh geometry={geometry}>
|
||||
<meshStandardMaterial color={color} emissive={accentColor} emissiveIntensity={emissiveIntensity} roughness={roughness} metalness={metalness} />
|
||||
</mesh>
|
||||
</group>
|
||||
);
|
||||
}
|
||||
|
||||
function FallbackPrimitive({ type, color, accentColor, emissiveIntensity, roughness, metalness, w, h, d }: RenderProps & {
|
||||
function FallbackPrimitive({ type, color, accentColor, emissiveIntensity, roughness, metalness, w, h, d, castShadow }: RenderProps & {
|
||||
type: 'box' | 'cylinder' | 'sphere';
|
||||
w: number; h: number; d: number;
|
||||
castShadow?: boolean;
|
||||
}) {
|
||||
const geometry = useMemo<THREE.BufferGeometry>(() => {
|
||||
if (type === 'cylinder' || type === 'sphere') {
|
||||
@@ -68,7 +52,7 @@ function FallbackPrimitive({ type, color, accentColor, emissiveIntensity, roughn
|
||||
useEffect(() => () => geometry.dispose(), [geometry]);
|
||||
|
||||
return (
|
||||
<mesh geometry={geometry}>
|
||||
<mesh geometry={geometry} castShadow={castShadow}>
|
||||
<meshStandardMaterial color={color} emissive={accentColor} emissiveIntensity={emissiveIntensity} roughness={roughness} metalness={metalness} />
|
||||
</mesh>
|
||||
);
|
||||
@@ -79,11 +63,16 @@ export const PhysicalPlaybackItem = memo(function PhysicalPlaybackItem({
|
||||
elapsedMs,
|
||||
slotIndex = 0,
|
||||
jitter,
|
||||
castShadow = false,
|
||||
verifySku = null,
|
||||
}: {
|
||||
caseData: PlaylistCase;
|
||||
elapsedMs: number;
|
||||
slotIndex?: number;
|
||||
jitter?: { x: number; z: number; yaw: number };
|
||||
castShadow?: boolean;
|
||||
/** Stage 1 verification: SKU to overlay (null = off, 'follow' handled by caller passing current SKU). */
|
||||
verifySku?: string | null;
|
||||
}) {
|
||||
const itemData = useMemo(() => resolveItem(caseData.itemId), [caseData.itemId]);
|
||||
const classification = useMemo(() => classifyItem(itemData), [itemData]);
|
||||
@@ -103,7 +92,6 @@ export const PhysicalPlaybackItem = memo(function PhysicalPlaybackItem({
|
||||
|
||||
const { position, rotation, phase, surface, isSettled } = pose;
|
||||
const isRouting = phase === 'routing';
|
||||
const useSimplifiedMesh = phase === 'settled' || isSettled;
|
||||
const onTransport = surface === 'main_belt'
|
||||
|| surface === 'inspection_station'
|
||||
|| surface === 'routing_junction'
|
||||
@@ -113,16 +101,24 @@ export const PhysicalPlaybackItem = memo(function PhysicalPlaybackItem({
|
||||
|
||||
const routeAccent = COLORS[classification.category] ?? COLORS.sensorAccent;
|
||||
const material = ITEM_MATERIALS[itemId] ?? { color: '#d8c3a5', roughness: 0.75 };
|
||||
const bodyColor = phase === 'fault' ? '#ef4444' : useSimplifiedMesh ? (material.color ?? '#b8b2a8') : material.color;
|
||||
const accentColor = useSimplifiedMesh ? '#94a3b8' : routeAccent;
|
||||
const emissiveIntensity = useSimplifiedMesh
|
||||
? 0.01
|
||||
: (phase === 'fault' ? 0.25 : isRouting ? 0.12 : 0.03);
|
||||
const bodyColor = phase === 'fault' ? '#ef4444' : material.color;
|
||||
const accentColor = isSettled ? '#94a3b8' : routeAccent;
|
||||
const emissiveIntensity = phase === 'fault' ? 0.25 : isRouting ? 0.12 : isSettled ? 0.01 : 0.03;
|
||||
const metalness = material.metalness ?? 0.05;
|
||||
const useSTL = !useSimplifiedMesh && asset?.loaderType === 'stl' && asset?.frontendAssetPath;
|
||||
const stlPath = asset?.frontendAssetPath ?? '';
|
||||
|
||||
// Real official model is the default when the manifest provides one;
|
||||
// procedural fallback only for missing assets or load failure (Stage 1 §15.1).
|
||||
const useReal = Boolean(asset?.defaultRealAsset && asset?.runtimePath);
|
||||
const fallbackType = asset?.fallbackPrimitive ?? 'box';
|
||||
|
||||
// Pose position is the EXPECTED bbox center (surfaceY + h/2). Real models use
|
||||
// a bottom-center pivot, so the mesh is offset down by half the model height.
|
||||
// Contact epsilon vs the surface is therefore exactly 0 mm by construction.
|
||||
const modelHeightM = asset?.worldExpectedMm
|
||||
? asset.worldExpectedMm.y / 1000
|
||||
: dims.height;
|
||||
const pivotOffsetY = -modelHeightM / 2;
|
||||
|
||||
const fallback = (
|
||||
<FallbackPrimitive
|
||||
type={fallbackType}
|
||||
@@ -134,28 +130,43 @@ export const PhysicalPlaybackItem = memo(function PhysicalPlaybackItem({
|
||||
w={dims.width}
|
||||
h={dims.height}
|
||||
d={dims.depth}
|
||||
castShadow={castShadow}
|
||||
/>
|
||||
);
|
||||
|
||||
const verifying = verifySku != null && verifySku === itemId && asset != null;
|
||||
|
||||
return (
|
||||
<group position={position} rotation={rotation}>
|
||||
{useSTL ? (
|
||||
<Suspense fallback={fallback}>
|
||||
<STLGeometry
|
||||
path={stlPath}
|
||||
scale={[0.001, 0.001, 0.001]}
|
||||
color={bodyColor}
|
||||
accentColor={accentColor}
|
||||
emissiveIntensity={emissiveIntensity}
|
||||
roughness={material.roughness}
|
||||
metalness={metalness}
|
||||
{useReal && asset ? (
|
||||
<group position={[0, pivotOffsetY, 0]}>
|
||||
<RealItemModel
|
||||
asset={asset}
|
||||
material={{
|
||||
color: bodyColor,
|
||||
emissive: accentColor,
|
||||
emissiveIntensity,
|
||||
roughness: material.roughness,
|
||||
metalness,
|
||||
}}
|
||||
castShadow={castShadow}
|
||||
fallback={fallback}
|
||||
/>
|
||||
</Suspense>
|
||||
</group>
|
||||
) : (
|
||||
fallback
|
||||
)}
|
||||
|
||||
{useSimplifiedMesh && (
|
||||
{verifying && asset && (
|
||||
<ItemVerificationOverlay
|
||||
asset={asset}
|
||||
pivotOffsetY={pivotOffsetY}
|
||||
cardY={modelHeightM + 0.3}
|
||||
fallbackSizeM={{ x: dims.width, y: dims.height, z: dims.depth }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isSettled && (
|
||||
<mesh position={[0, -dims.height / 2 + 0.003, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
<ringGeometry args={[Math.max(dims.width, dims.depth) * 0.35, Math.max(dims.width, dims.depth) * 0.42, 20]} />
|
||||
<meshBasicMaterial color={routeAccent} transparent opacity={0.5} />
|
||||
|
||||
22
src/components/ThreeD/PostProcessingSpike.tsx
Normal file
22
src/components/ThreeD/PostProcessingSpike.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* PostProcessingSpike — Stage 0 cost-measurement only.
|
||||
*
|
||||
* Loaded lazily (separate chunk) and mounted ONLY in stage0 prototype mode
|
||||
* with post=1. Default route never downloads @react-three/postprocessing.
|
||||
* Deliberately cheap set: Bloom + Vignette + Noise + SMAA. No DoF, no SSR,
|
||||
* no motion blur, no TAA, no volumetrics.
|
||||
*/
|
||||
|
||||
import { EffectComposer, Bloom, Vignette, Noise, SMAA } from '@react-three/postprocessing';
|
||||
import { BlendFunction } from 'postprocessing';
|
||||
|
||||
export default function PostProcessingSpike() {
|
||||
return (
|
||||
<EffectComposer multisampling={0}>
|
||||
<SMAA />
|
||||
<Bloom intensity={0.35} luminanceThreshold={0.75} luminanceSmoothing={0.2} mipmapBlur />
|
||||
<Noise premultiply blendFunction={BlendFunction.SCREEN} opacity={0.25} />
|
||||
<Vignette offset={0.25} darkness={0.55} eskil={false} />
|
||||
</EffectComposer>
|
||||
);
|
||||
}
|
||||
127
src/components/ThreeD/RealItemModel.tsx
Normal file
127
src/components/ThreeD/RealItemModel.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* RealItemModel — единый loader для официальных real-model ассетов.
|
||||
*
|
||||
* Контракт (одинаковый для STL сейчас и GLB позже):
|
||||
* manifest (modelAssets.ts) → нормализованная геометрия → mesh.
|
||||
*
|
||||
* Нормализация запекается в клон геометрии один раз при загрузке:
|
||||
* 1. rotation из manifest (в мм-пространстве источника);
|
||||
* 2. uniform scale 0.001 (mm → meters);
|
||||
* 3. pivot → bottom-center (центр footprint по X/Z, низ по Y);
|
||||
* 4. computeVertexNormals.
|
||||
*
|
||||
* Shared loader cache никогда не мутируется (clone перед transforms),
|
||||
* dispose вызывается только для локального клона.
|
||||
*/
|
||||
|
||||
import { Component, Suspense, useEffect, useMemo, type ReactNode } from 'react';
|
||||
import * as THREE from 'three';
|
||||
import { useLoader } from '@react-three/fiber';
|
||||
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||
import type { ModelAsset } from '../../data/modelAssets';
|
||||
|
||||
export interface RealItemMaterial {
|
||||
color: string;
|
||||
emissive?: string;
|
||||
emissiveIntensity?: number;
|
||||
roughness?: number;
|
||||
metalness?: number;
|
||||
}
|
||||
|
||||
interface InnerProps {
|
||||
asset: ModelAsset;
|
||||
material: RealItemMaterial;
|
||||
castShadow?: boolean;
|
||||
receiveShadow?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a freshly cloned geometry per manifest rules.
|
||||
* Returns the clone with transforms BAKED IN (pivot = bottom-center, meters).
|
||||
*/
|
||||
export function normalizeGeometryClone(source: THREE.BufferGeometry, asset: ModelAsset): THREE.BufferGeometry {
|
||||
const g = source.clone();
|
||||
const [rx, ry, rz] = asset.rotation;
|
||||
if (rx) g.rotateX(rx);
|
||||
if (ry) g.rotateY(ry);
|
||||
if (rz) g.rotateZ(rz);
|
||||
g.scale(0.001, 0.001, 0.001); // mm → m, uniform (scaleMode: 'uniform-mm-to-m')
|
||||
g.computeBoundingBox();
|
||||
const bb = g.boundingBox!;
|
||||
const cx = (bb.min.x + bb.max.x) / 2;
|
||||
const cz = (bb.min.z + bb.max.z) / 2;
|
||||
g.translate(-cx, -bb.min.y, -cz); // pivotMode: 'bottom-center'
|
||||
g.computeVertexNormals();
|
||||
g.computeBoundingBox();
|
||||
return g;
|
||||
}
|
||||
|
||||
function RealItemModelInner({ asset, material, castShadow, receiveShadow }: InnerProps) {
|
||||
const shared = useLoader(STLLoader, asset.runtimePath!) as THREE.BufferGeometry;
|
||||
const geometry = useMemo(() => normalizeGeometryClone(shared, asset), [shared, asset]);
|
||||
useEffect(() => () => geometry.dispose(), [geometry]);
|
||||
return (
|
||||
<mesh geometry={geometry} castShadow={castShadow} receiveShadow={receiveShadow}>
|
||||
<meshStandardMaterial
|
||||
color={material.color}
|
||||
emissive={material.emissive ?? material.color}
|
||||
emissiveIntensity={material.emissiveIntensity ?? 0.05}
|
||||
roughness={material.roughness ?? 0.6}
|
||||
metalness={material.metalness ?? 0.05}
|
||||
/>
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
interface BoundaryProps {
|
||||
fallback: ReactNode;
|
||||
children: ReactNode;
|
||||
onError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface BoundaryState {
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
/** Per-item error boundary: load failure → procedural fallback, no scene crash. */
|
||||
class ItemModelErrorBoundary extends Component<BoundaryProps, BoundaryState> {
|
||||
state: BoundaryState = { failed: false };
|
||||
|
||||
static getDerivedStateFromError(): BoundaryState {
|
||||
return { failed: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('[RealItemModel] asset load failed, procedural fallback engaged:', error.message);
|
||||
this.props.onError?.(error);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.state.failed ? this.props.fallback : this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RealItemModelProps extends InnerProps {
|
||||
/** Procedural fallback node (load failure AND suspense placeholder). */
|
||||
fallback: ReactNode;
|
||||
onError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
export default function RealItemModel({ fallback, ...inner }: RealItemModelProps) {
|
||||
if (!inner.asset.runtimePath) {
|
||||
return <>{fallback}</>;
|
||||
}
|
||||
return (
|
||||
<ItemModelErrorBoundary fallback={fallback} onError={inner.onError}>
|
||||
<Suspense fallback={fallback}>
|
||||
<RealItemModelInner {...inner} />
|
||||
</Suspense>
|
||||
</ItemModelErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
/** Preload a runtime asset into the shared loader cache (deduped by URL). */
|
||||
export function preloadRealItemModel(runtimePath: string): void {
|
||||
useLoader.preload(STLLoader, runtimePath);
|
||||
}
|
||||
168
src/components/ThreeD/RealModelVerification.tsx
Normal file
168
src/components/ThreeD/RealModelVerification.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* RealModelVerification — Stage 1 debug overlay (?stage1=1&verify=real-models).
|
||||
*
|
||||
* Read-only instrumentation: bounding box, axes, pivot marker, bottom contact
|
||||
* plane и информационная панель (источник, формат, размеры, статус валидации).
|
||||
* Рендерится только в verification mode; business state не изменяется.
|
||||
*
|
||||
* Использование: <ItemVerificationOverlay> внутри pose-группы товара
|
||||
* (PhysicalPlaybackItem) — следует за товаром по маршруту B/C/D.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import * as THREE from 'three';
|
||||
import { Html } from '@react-three/drei';
|
||||
import { useLoader } from '@react-three/fiber';
|
||||
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||
import type { ModelAsset } from '../../data/modelAssets';
|
||||
import { normalizeGeometryClone } from './RealItemModel';
|
||||
|
||||
export interface SizeM {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
const AXIS_COLORS = { x: '#ef4444', y: '#22c55e', z: '#3b82f6' } as const;
|
||||
|
||||
/** Wire bbox + axis tripod + pivot marker + bottom contact plane (bottom-center space). */
|
||||
function VerificationGizmos({ sizeM }: { sizeM: SizeM }) {
|
||||
const boxEdges = useMemo(() => {
|
||||
const box = new THREE.BoxGeometry(sizeM.x, sizeM.y, sizeM.z);
|
||||
const edges = new THREE.EdgesGeometry(box);
|
||||
box.dispose();
|
||||
return edges;
|
||||
}, [sizeM.x, sizeM.y, sizeM.z]);
|
||||
const axes = useMemo(() => ({
|
||||
x: new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0.15, 0, 0)]),
|
||||
y: new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0.15, 0)]),
|
||||
z: new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0.15)]),
|
||||
}), []);
|
||||
useEffect(() => () => {
|
||||
boxEdges.dispose();
|
||||
axes.x.dispose();
|
||||
axes.y.dispose();
|
||||
axes.z.dispose();
|
||||
}, [boxEdges, axes]);
|
||||
|
||||
return (
|
||||
<group>
|
||||
{/* bounding box of the normalized model (bottom-center pivot) */}
|
||||
<lineSegments geometry={boxEdges} position={[0, sizeM.y / 2, 0]}>
|
||||
<lineBasicMaterial color="#facc15" />
|
||||
</lineSegments>
|
||||
{/* axis tripod at pivot (footprint center, bottom point) */}
|
||||
<lineSegments geometry={axes.x}><lineBasicMaterial color={AXIS_COLORS.x} /></lineSegments>
|
||||
<lineSegments geometry={axes.y}><lineBasicMaterial color={AXIS_COLORS.y} /></lineSegments>
|
||||
<lineSegments geometry={axes.z}><lineBasicMaterial color={AXIS_COLORS.z} /></lineSegments>
|
||||
{/* pivot marker */}
|
||||
<mesh position={[0, 0.004, 0]}>
|
||||
<sphereGeometry args={[0.008, 12, 8]} />
|
||||
<meshBasicMaterial color="#facc15" depthTest={false} />
|
||||
</mesh>
|
||||
{/* bottom contact plane (item footprint on the surface) */}
|
||||
<mesh position={[0, 0.0005, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
<planeGeometry args={[sizeM.x, sizeM.z]} />
|
||||
<meshBasicMaterial color="#22c55e" transparent opacity={0.25} depthWrite={false} />
|
||||
</mesh>
|
||||
</group>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoCard({ asset, measuredM, y }: {
|
||||
asset: ModelAsset;
|
||||
measuredM: SizeM | null;
|
||||
y: number;
|
||||
}) {
|
||||
const mm = (m: number) => (m * 1000).toFixed(1);
|
||||
const expected = asset.worldExpectedMm;
|
||||
const rows: Array<[string, string]> = [
|
||||
['Model', asset.displayName],
|
||||
['Badge', asset.defaultRealAsset ? 'REAL (official)' : 'FALLBACK · NO_EXACT_OFFICIAL_MODEL'],
|
||||
['Source', asset.sourceFile ?? 'n/a'],
|
||||
['SHA-256', asset.sourceSha256 ? `${asset.sourceSha256.slice(0, 12)}…` : 'n/a'],
|
||||
['Format', asset.runtimeFormat ?? 'procedural'],
|
||||
['File size', asset.fileSizeBytes != null ? `${(asset.fileSizeBytes / 1024).toFixed(0)} KB` : 'n/a'],
|
||||
['Triangles', asset.triangleCount != null ? String(asset.triangleCount) : 'n/a'],
|
||||
['Conversion', asset.conversionStatus],
|
||||
['Pivot', asset.pivotMode],
|
||||
];
|
||||
if (expected) rows.push(['Expected x/y/z mm', `${expected.x} / ${expected.y} / ${expected.z}`]);
|
||||
if (measuredM) rows.push(['Measured x/y/z mm', `${mm(measuredM.x)} / ${mm(measuredM.y)} / ${mm(measuredM.z)}`]);
|
||||
rows.push(['Validation', asset.validationStatus]);
|
||||
|
||||
return (
|
||||
<Html position={[0, y, 0]} center style={{ pointerEvents: 'none' }}>
|
||||
<div style={{
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
fontSize: '10px',
|
||||
lineHeight: 1.45,
|
||||
color: '#e2e8f0',
|
||||
background: 'rgba(2, 6, 23, 0.88)',
|
||||
border: '1px solid #334155',
|
||||
borderRadius: '6px',
|
||||
padding: '8px 10px',
|
||||
whiteSpace: 'nowrap',
|
||||
transform: 'translateY(-100%)',
|
||||
}}>
|
||||
<div style={{ fontWeight: 700, color: '#facc15', marginBottom: 4 }}>
|
||||
STAGE1 VERIFY · {asset.itemId}
|
||||
</div>
|
||||
{rows.map(([k, v]) => (
|
||||
<div key={k}>
|
||||
<span style={{ color: '#64748b' }}>{k}: </span>
|
||||
<span>{v}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Html>
|
||||
);
|
||||
}
|
||||
|
||||
/** Real-asset branch: measures the actual runtime file via the shared loader cache. */
|
||||
function RealAssetVerification({ asset, cardY }: { asset: ModelAsset; cardY: number }) {
|
||||
const shared = useLoader(STLLoader, asset.runtimePath!) as THREE.BufferGeometry;
|
||||
const measuredM = useMemo<SizeM>(() => {
|
||||
const g = normalizeGeometryClone(shared, asset);
|
||||
g.computeBoundingBox();
|
||||
const bb = g.boundingBox!;
|
||||
const size = { x: bb.max.x - bb.min.x, y: bb.max.y - bb.min.y, z: bb.max.z - bb.min.z };
|
||||
g.dispose();
|
||||
return size;
|
||||
}, [shared, asset]);
|
||||
return (
|
||||
<group>
|
||||
<VerificationGizmos sizeM={measuredM} />
|
||||
<InfoCard asset={asset} measuredM={measuredM} y={cardY} />
|
||||
</group>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overlay for one item in its pose group. `pivotOffsetY` is the same local Y
|
||||
* offset used by the rendered mesh (bottom-center compensation), `cardY` the
|
||||
* height for the info card (item top + margin, in the same local space).
|
||||
*/
|
||||
export function ItemVerificationOverlay({ asset, pivotOffsetY, cardY, fallbackSizeM }: {
|
||||
asset: ModelAsset;
|
||||
pivotOffsetY: number;
|
||||
cardY: number;
|
||||
fallbackSizeM: SizeM;
|
||||
}) {
|
||||
return (
|
||||
<group position={[0, pivotOffsetY, 0]}>
|
||||
{asset.runtimePath ? (
|
||||
<RealAssetVerification asset={asset} cardY={cardY} />
|
||||
) : (
|
||||
<group>
|
||||
<VerificationGizmos sizeM={fallbackSizeM} />
|
||||
<InfoCard asset={asset} measuredM={null} y={cardY} />
|
||||
</group>
|
||||
)}
|
||||
</group>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RealModelVerification() {
|
||||
return null;
|
||||
}
|
||||
169
src/components/ThreeD/RollCageMesh.tsx
Normal file
169
src/components/ThreeD/RollCageMesh.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* RollCageMesh — честная сетчатая модель роллтейнера C/D по ground truth.
|
||||
*
|
||||
* Exterior bounding box: 1200 × 800 × 800 мм (включая колёса) — ROLL_CAGE.
|
||||
* Открытый верх, читаемая сетка стен (~100мм), пол-панель на CAGE_FLOOR_Y.
|
||||
*
|
||||
* Вся геометрия — 3 instanced draw call (трубы+прутья, колёса) + 1 mesh (пол).
|
||||
* Одна и та же модель используется обеими сценами (`/` и `/details`).
|
||||
*
|
||||
* Классификация узла (Stage 1 §13.4): PROCEDURAL_FALLBACK — официальной
|
||||
* CAD-модели роллтейнера в архивах нет; размеры соответствуют спецификации.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import * as THREE from 'three';
|
||||
import { ROLL_CAGE, CAGE_FLOOR_Y } from '../../domain/physicalLayout';
|
||||
|
||||
const { width: W, depth: D, height: H, wheelRadius: WR, frameThickness: FT } = ROLL_CAGE;
|
||||
const WHEEL_D = WR * 2; // 0.08m — cage floor height (CAGE_FLOOR_Y)
|
||||
const BODY_H = H - WHEEL_D; // frame body above wheels; total exterior = H exactly
|
||||
const ROD = 0.008; // grid rod thickness (8mm wire)
|
||||
const GRID_STEP = 0.1; // ~100mm grid pitch
|
||||
|
||||
interface CageInstances {
|
||||
boxes: THREE.Matrix4[];
|
||||
wheels: THREE.Matrix4[];
|
||||
}
|
||||
|
||||
function boxInstance(x: number, y: number, z: number, sx: number, sy: number, sz: number): THREE.Matrix4 {
|
||||
return new THREE.Matrix4().compose(
|
||||
new THREE.Vector3(x, y, z),
|
||||
new THREE.Quaternion(),
|
||||
new THREE.Vector3(sx, sy, sz),
|
||||
);
|
||||
}
|
||||
|
||||
/** Deterministic instance layout for the cage (built once). */
|
||||
function buildInstances(): CageInstances {
|
||||
const boxes: THREE.Matrix4[] = [];
|
||||
const yBot = WHEEL_D; // bottom of frame body
|
||||
const yTop = H; // top of frame body (exterior top)
|
||||
|
||||
// 4 corner posts
|
||||
for (const sx of [-1, 1]) {
|
||||
for (const sz of [-1, 1]) {
|
||||
boxes.push(boxInstance(sx * (W / 2 - FT / 2), yBot + BODY_H / 2, sz * (D / 2 - FT / 2), FT, BODY_H, FT));
|
||||
}
|
||||
}
|
||||
// bottom + top frame rectangles
|
||||
for (const y of [yBot + FT / 2, yTop - FT / 2]) {
|
||||
boxes.push(boxInstance(0, y, D / 2 - FT / 2, W, FT, FT));
|
||||
boxes.push(boxInstance(0, y, -(D / 2 - FT / 2), W, FT, FT));
|
||||
boxes.push(boxInstance(W / 2 - FT / 2, y, 0, FT, FT, D - FT * 2));
|
||||
boxes.push(boxInstance(-(W / 2 - FT / 2), y, 0, FT, FT, D - FT * 2));
|
||||
}
|
||||
|
||||
// grid walls between frames (interior span)
|
||||
const yGridBot = yBot + FT;
|
||||
const yGridTop = yTop - FT;
|
||||
const gridH = yGridTop - yGridBot;
|
||||
const yMid = yGridBot + gridH / 2;
|
||||
const xInner = W / 2 - FT; // inner half-width
|
||||
const zInner = D / 2 - FT;
|
||||
|
||||
// front/back walls (z = ±(D/2 − ROD/2)): vertical + horizontal rods
|
||||
const vCols = Math.floor((xInner * 2) / GRID_STEP) - 1; // exclude corners (posts)
|
||||
const hRows = Math.max(1, Math.round(gridH / GRID_STEP) - 1);
|
||||
for (const sz of [-1, 1]) {
|
||||
const z = sz * (D / 2 - ROD / 2);
|
||||
for (let i = 1; i <= vCols; i++) {
|
||||
const x = -xInner + (i * (xInner * 2)) / (vCols + 1);
|
||||
boxes.push(boxInstance(x, yMid, z, ROD, gridH, ROD));
|
||||
}
|
||||
for (let r = 1; r <= hRows; r++) {
|
||||
const y = yGridBot + (r * gridH) / (hRows + 1);
|
||||
boxes.push(boxInstance(0, y, z, W - FT * 2, ROD, ROD));
|
||||
}
|
||||
}
|
||||
// side walls (x = ±(W/2 − ROD/2))
|
||||
const sCols = Math.floor((zInner * 2) / GRID_STEP) - 1;
|
||||
for (const sx of [-1, 1]) {
|
||||
const x = sx * (W / 2 - ROD / 2);
|
||||
for (let i = 1; i <= sCols; i++) {
|
||||
const z = -zInner + (i * (zInner * 2)) / (sCols + 1);
|
||||
boxes.push(boxInstance(x, yMid, z, ROD, gridH, ROD));
|
||||
}
|
||||
for (let r = 1; r <= hRows; r++) {
|
||||
const y = yGridBot + (r * gridH) / (hRows + 1);
|
||||
boxes.push(boxInstance(x, y, 0, ROD, ROD, D - FT * 2));
|
||||
}
|
||||
}
|
||||
|
||||
// caster wheels (lying cylinders)
|
||||
const wheels: THREE.Matrix4[] = [];
|
||||
const wheelQuat = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, Math.PI / 2));
|
||||
for (const sx of [-1, 1]) {
|
||||
for (const sz of [-1, 1]) {
|
||||
wheels.push(new THREE.Matrix4().compose(
|
||||
new THREE.Vector3(sx * (W / 2 - 0.08), WR, sz * (D / 2 - 0.08)),
|
||||
wheelQuat,
|
||||
new THREE.Vector3(1, 1, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return { boxes, wheels };
|
||||
}
|
||||
|
||||
export default function RollCageMesh({ color, active = false, shadows = false }: {
|
||||
color: string;
|
||||
active?: boolean;
|
||||
shadows?: boolean;
|
||||
}) {
|
||||
const instances = useMemo(buildInstances, []);
|
||||
const boxGeo = useMemo(() => new THREE.BoxGeometry(1, 1, 1), []);
|
||||
const wheelGeo = useMemo(() => new THREE.CylinderGeometry(WR, WR, 0.03, 12), []);
|
||||
const boxesRef = useRef<THREE.InstancedMesh>(null);
|
||||
const wheelsRef = useRef<THREE.InstancedMesh>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const boxes = boxesRef.current;
|
||||
if (boxes) {
|
||||
instances.boxes.forEach((m, i) => boxes.setMatrixAt(i, m));
|
||||
boxes.instanceMatrix.needsUpdate = true;
|
||||
}
|
||||
const wheels = wheelsRef.current;
|
||||
if (wheels) {
|
||||
instances.wheels.forEach((m, i) => wheels.setMatrixAt(i, m));
|
||||
wheels.instanceMatrix.needsUpdate = true;
|
||||
}
|
||||
}, [instances]);
|
||||
|
||||
useEffect(() => () => {
|
||||
boxGeo.dispose();
|
||||
wheelGeo.dispose();
|
||||
}, [boxGeo, wheelGeo]);
|
||||
|
||||
const emissiveIntensity = active ? 0.35 : 0;
|
||||
|
||||
return (
|
||||
<group>
|
||||
{/* frame + grid walls: single instanced draw call */}
|
||||
<instancedMesh
|
||||
ref={boxesRef}
|
||||
args={[boxGeo, undefined, instances.boxes.length]}
|
||||
castShadow={shadows}
|
||||
>
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
metalness={0.6}
|
||||
roughness={0.35}
|
||||
emissive={color}
|
||||
emissiveIntensity={emissiveIntensity}
|
||||
/>
|
||||
</instancedMesh>
|
||||
|
||||
{/* caster wheels: single instanced draw call */}
|
||||
<instancedMesh ref={wheelsRef} args={[wheelGeo, undefined, instances.wheels.length]}>
|
||||
<meshStandardMaterial color="#475569" metalness={0.7} roughness={0.3} />
|
||||
</instancedMesh>
|
||||
|
||||
{/* interior floor pan where items rest (top at CAGE_FLOOR_Y) */}
|
||||
<mesh position={[0, CAGE_FLOOR_Y - 0.005, 0]} receiveShadow={shadows}>
|
||||
<boxGeometry args={[W - FT, 0.01, D - FT]} />
|
||||
<meshStandardMaterial color="#1e293b" metalness={0.3} roughness={0.7} />
|
||||
</mesh>
|
||||
</group>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { useLoader } from '@react-three/fiber';
|
||||
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
|
||||
import { Center } from '@react-three/drei';
|
||||
import type { BufferGeometry, Mesh as ThreeMesh } from 'three';
|
||||
import { useRef, useEffect } from 'react';
|
||||
import { Suspense, useRef, useEffect, useMemo } from 'react';
|
||||
|
||||
interface STLModelProps {
|
||||
/** Path to STL file in public folder */
|
||||
@@ -38,7 +38,19 @@ interface STLModelProps {
|
||||
fallback?: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function STLModel({
|
||||
/**
|
||||
* Outer wrapper: Suspense boundary around the loader. Load errors propagate
|
||||
* to the nearest ErrorBoundary (hooks must not live inside try/catch).
|
||||
*/
|
||||
export default function STLModel(props: STLModelProps) {
|
||||
return (
|
||||
<Suspense fallback={props.fallback ? <>{props.fallback}</> : null}>
|
||||
<STLModelInner {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function STLModelInner({
|
||||
path,
|
||||
scale,
|
||||
rotation = [0, 0, 0],
|
||||
@@ -47,34 +59,21 @@ export default function STLModel({
|
||||
emissive,
|
||||
emissiveIntensity = 0.2,
|
||||
roughness = 0.5,
|
||||
fallback,
|
||||
}: STLModelProps) {
|
||||
const meshRef = useRef<ThreeMesh>(null);
|
||||
|
||||
let geometry: BufferGeometry | null = null;
|
||||
|
||||
try {
|
||||
// Load STL geometry
|
||||
geometry = useLoader(STLLoader, path);
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to load STL model: ${path}`, error);
|
||||
}
|
||||
return fallback ? <>{fallback}</> : null;
|
||||
}
|
||||
|
||||
// Center the geometry on load
|
||||
useEffect(() => {
|
||||
if (meshRef.current && geometry) {
|
||||
geometry.center();
|
||||
geometry.computeVertexNormals();
|
||||
}
|
||||
}, [geometry]);
|
||||
|
||||
if (!geometry) {
|
||||
return fallback ? <>{fallback}</> : null;
|
||||
}
|
||||
|
||||
|
||||
const shared = useLoader(STLLoader, path) as BufferGeometry;
|
||||
|
||||
// Clone the loader-cached geometry before centering so the shared cache
|
||||
// entry is never mutated; dispose the clone on unmount.
|
||||
const geometry = useMemo(() => {
|
||||
const g = shared.clone();
|
||||
g.center();
|
||||
g.computeVertexNormals();
|
||||
return g;
|
||||
}, [shared]);
|
||||
useEffect(() => () => geometry.dispose(), [geometry]);
|
||||
|
||||
return (
|
||||
<Center position={position} rotation={rotation}>
|
||||
<mesh ref={meshRef} geometry={geometry} scale={scale}>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { Canvas, useFrame, useThree } from '@react-three/fiber';
|
||||
import { Grid, OrbitControls, Html, Line } from '@react-three/drei';
|
||||
import { Suspense, useRef, useMemo, useState, useEffect } from 'react';
|
||||
import { Suspense, lazy, useRef, useMemo, useState, useEffect } from 'react';
|
||||
import type { Mesh, Group } from 'three';
|
||||
import * as THREE from 'three';
|
||||
import type { ContinuousPlaybackState, CasePhase } from '../../domain/continuousPlayback';
|
||||
@@ -24,7 +24,7 @@ import { PhysicalPlaybackItem } from './PhysicalPlaybackItem';
|
||||
import { DEMO_PLAYLIST, PLAYLIST_LENGTH } from '../../domain/demoPlaylist';
|
||||
import { cumulativePlaylistDurationMs, getPlaylistCaseDurationMs } from '../../domain/continuousPlayback';
|
||||
import { INDUSTRIAL_PALETTE } from '../../domain/industrialTheme';
|
||||
import { detectQualityMode, getQualitySettings, type QualityMode } from '../../domain/qualityMode';
|
||||
import { detectQualityMode, getQualitySettings, adaptQuality, type QualityMode } from '../../domain/qualityMode';
|
||||
import {
|
||||
getCameraConfig,
|
||||
smoothCameraTransition,
|
||||
@@ -57,14 +57,26 @@ import {
|
||||
} from '../../domain/physicalLayout';
|
||||
import PerfCollector from './PerfCollector';
|
||||
import PerfOverlay from './PerfOverlay';
|
||||
import RollCageMesh from './RollCageMesh';
|
||||
import { getPreloadAssets } from '../../data/modelAssets';
|
||||
import { preloadRealItemModel } from './RealItemModel';
|
||||
import type { Stage0Config } from '../../domain/stage0';
|
||||
import { shotToPhaseCategory, describeAdaptiveSwitch } from '../../domain/stage0';
|
||||
import type { Stage1Config } from '../../domain/stage1';
|
||||
|
||||
/** Lazy chunk: post-processing spike is downloaded only when stage0 post=1. */
|
||||
const PostProcessingSpike = lazy(() => import('./PostProcessingSpike'));
|
||||
|
||||
export interface SorterDigitalTwinContinuousProps {
|
||||
playback: ContinuousPlaybackState;
|
||||
simplified?: boolean;
|
||||
onContextLost?: () => void;
|
||||
onContextRestored?: () => void;
|
||||
autoCameraEnabled?: boolean;
|
||||
viewportType?: ViewportType;
|
||||
qualityMode?: QualityMode;
|
||||
stage0?: Stage0Config;
|
||||
stage1?: Stage1Config;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,19 +134,24 @@ const CONVEYOR_LENGTH = CONVEYOR_END_X - CONVEYOR_START_X;
|
||||
const CONVEYOR_CENTER_X = (CONVEYOR_START_X + CONVEYOR_END_X) / 2;
|
||||
|
||||
/** Cinematic camera controller - smoothly transitions between camera angles */
|
||||
function CinematicCameraController({
|
||||
playback,
|
||||
enabled,
|
||||
viewportType = 'desktop'
|
||||
}: {
|
||||
playback: ContinuousPlaybackState;
|
||||
function CinematicCameraController({
|
||||
playback,
|
||||
enabled,
|
||||
viewportType = 'desktop',
|
||||
overridePhase = null,
|
||||
overrideCategory = null,
|
||||
}: {
|
||||
playback: ContinuousPlaybackState;
|
||||
enabled: boolean;
|
||||
viewportType: ViewportType;
|
||||
/** Manual shot override (stage0) — camera runs even while paused. */
|
||||
overridePhase?: CasePhase | null;
|
||||
overrideCategory?: Category | null;
|
||||
}) {
|
||||
const { camera } = useThree();
|
||||
const cameraStateRef = useRef<CameraConfig>(getInitialCameraConfig(viewportType));
|
||||
const isRunning = playback.status === 'running';
|
||||
|
||||
|
||||
// Get item position for camera following
|
||||
const itemPosition = useMemo(() => {
|
||||
if (playback.status === 'idle') return null;
|
||||
@@ -149,14 +166,15 @@ function CinematicCameraController({
|
||||
});
|
||||
return pose.position;
|
||||
}, [playback]);
|
||||
|
||||
|
||||
useFrame(() => {
|
||||
if (!enabled || !isRunning) return;
|
||||
|
||||
// Get target camera config for current phase
|
||||
if (!enabled) return;
|
||||
if (!isRunning && !overridePhase) return;
|
||||
|
||||
// Get target camera config for current phase (or manual shot override)
|
||||
const targetConfig = getCameraConfig(
|
||||
playback.currentPhase,
|
||||
playback.targetCategory,
|
||||
overridePhase ?? playback.currentPhase,
|
||||
overrideCategory ?? playback.targetCategory,
|
||||
itemPosition,
|
||||
viewportType
|
||||
);
|
||||
@@ -443,27 +461,28 @@ function PointCloud({ active, itemPosition, scale, isRound }: {
|
||||
}
|
||||
|
||||
/** Actuator/pusher animation during routing */
|
||||
function ActuatorPusher({ active, category }: { active: boolean; category: Category | null }) {
|
||||
function ActuatorPusher({ active, category, shadows = false }: { active: boolean; category: Category | null; shadows?: boolean }) {
|
||||
const pusherRef = useRef<Mesh>(null);
|
||||
const extendRef = useRef(0);
|
||||
|
||||
|
||||
useFrame((_, delta) => {
|
||||
if (pusherRef.current) {
|
||||
const target = active && (category === 'C' || category === 'D') ? 0.15 : 0;
|
||||
extendRef.current += (target - extendRef.current) * delta * 5;
|
||||
|
||||
|
||||
const direction = category === 'C' ? 1 : -1;
|
||||
pusherRef.current.position.z = direction * extendRef.current;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
const gateX = ZONES.GATE.x;
|
||||
const color = category === 'C' ? COLORS.routeC : category === 'D' ? COLORS.routeD : COLORS.gateFrame;
|
||||
|
||||
|
||||
return (
|
||||
<mesh
|
||||
<mesh
|
||||
ref={pusherRef}
|
||||
position={[gateX + 0.3, BELT_Y + 0.08, 0]}
|
||||
castShadow={shadows}
|
||||
>
|
||||
<boxGeometry args={[0.15, 0.08, 0.06]} />
|
||||
<meshStandardMaterial
|
||||
@@ -505,7 +524,7 @@ function SupportLeg({ x }: { x: number }) {
|
||||
* Conveyor belt - realistic roller conveyor
|
||||
* Belt top surface at 0.7m (BELT_TOP_Y)
|
||||
*/
|
||||
function ConveyorBelt({ pulseActive, elapsedMs, simplified }: { pulseActive: boolean; elapsedMs: number; simplified: boolean }) {
|
||||
function ConveyorBelt({ pulseActive, elapsedMs, simplified, shadows = false }: { pulseActive: boolean; elapsedMs: number; simplified: boolean; shadows?: boolean }) {
|
||||
const spacing = simplified ? ROLLER_SPACING_M * 2 : ROLLER_SPACING_M;
|
||||
const rollerCount = Math.floor(CONVEYOR_LENGTH / spacing);
|
||||
const stripeOffsets = simplified ? [-2, 0, 2] : [-3, -1, 0.5, 2];
|
||||
@@ -529,10 +548,10 @@ function ConveyorBelt({ pulseActive, elapsedMs, simplified }: { pulseActive: boo
|
||||
return (
|
||||
<group>
|
||||
{/* Main belt surface - matte PVC/tarpaulin look at 0.7m */}
|
||||
<mesh position={[CONVEYOR_CENTER_X, BELT_Y - BELT_THICKNESS_M / 2, 0]}>
|
||||
<mesh position={[CONVEYOR_CENTER_X, BELT_Y - BELT_THICKNESS_M / 2, 0]} receiveShadow={shadows}>
|
||||
<boxGeometry args={[CONVEYOR_LENGTH, BELT_THICKNESS_M, CONVEYOR_WIDTH_M]} />
|
||||
<meshStandardMaterial
|
||||
color={COLORS.belt}
|
||||
<meshStandardMaterial
|
||||
color={COLORS.belt}
|
||||
roughness={0.85}
|
||||
metalness={0.05}
|
||||
/>
|
||||
@@ -554,11 +573,11 @@ function ConveyorBelt({ pulseActive, elapsedMs, simplified }: { pulseActive: boo
|
||||
</mesh>
|
||||
|
||||
{/* Frame rails - industrial metal */}
|
||||
<mesh position={[CONVEYOR_CENTER_X, FRAME_TOP_Y + 0.025, CONVEYOR_WIDTH_M / 2 + 0.01]}>
|
||||
<mesh position={[CONVEYOR_CENTER_X, FRAME_TOP_Y + 0.025, CONVEYOR_WIDTH_M / 2 + 0.01]} castShadow={shadows}>
|
||||
<boxGeometry args={[CONVEYOR_LENGTH, 0.05, 0.04]} />
|
||||
<meshStandardMaterial color={COLORS.conveyorFrame} metalness={0.5} roughness={0.4} />
|
||||
</mesh>
|
||||
<mesh position={[CONVEYOR_CENTER_X, FRAME_TOP_Y + 0.025, -CONVEYOR_WIDTH_M / 2 - 0.01]}>
|
||||
<mesh position={[CONVEYOR_CENTER_X, FRAME_TOP_Y + 0.025, -CONVEYOR_WIDTH_M / 2 - 0.01]} castShadow={shadows}>
|
||||
<boxGeometry args={[CONVEYOR_LENGTH, 0.05, 0.04]} />
|
||||
<meshStandardMaterial color={COLORS.conveyorFrame} metalness={0.5} roughness={0.4} />
|
||||
</mesh>
|
||||
@@ -728,17 +747,16 @@ function BReceiverBin({ active }: { active: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Roll cage for C/D zones - realistic wireframe cage with wheels */
|
||||
function RollCage({ position, label, color, active }: {
|
||||
/** Roll cage for C/D zones — shared instanced mesh (exterior 1200×800×800 incl. wheels) */
|
||||
function RollCage({ position, label, color, active, shadows = false }: {
|
||||
position: [number, number, number];
|
||||
label: 'C' | 'D';
|
||||
color: string;
|
||||
active: boolean;
|
||||
shadows?: boolean;
|
||||
}) {
|
||||
const { width, depth, height, wheelRadius, frameThickness } = ROLL_CAGE;
|
||||
const ft = frameThickness;
|
||||
const emissiveIntensity = active ? 0.4 : 0;
|
||||
|
||||
const { width, depth, height } = ROLL_CAGE;
|
||||
|
||||
return (
|
||||
<group position={position}>
|
||||
{/* Floor marker */}
|
||||
@@ -747,78 +765,10 @@ function RollCage({ position, label, color, active }: {
|
||||
<meshStandardMaterial color={color} transparent opacity={active ? 0.25 : 0.08} />
|
||||
</mesh>
|
||||
|
||||
{/* Solid interior floor where items rest */}
|
||||
<mesh position={[0, CAGE_FLOOR_Y - 0.005, 0]}>
|
||||
<boxGeometry args={[width - frameThickness, 0.01, depth - frameThickness]} />
|
||||
<meshStandardMaterial color="#1e293b" metalness={0.3} roughness={0.7} />
|
||||
</mesh>
|
||||
|
||||
{/* Cage frame - bottom rectangle */}
|
||||
<mesh position={[0, wheelRadius * 2 + ft / 2, depth / 2 - ft / 2]}>
|
||||
<boxGeometry args={[width, ft, ft]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[0, wheelRadius * 2 + ft / 2, -depth / 2 + ft / 2]}>
|
||||
<boxGeometry args={[width, ft, ft]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[width / 2 - ft / 2, wheelRadius * 2 + ft / 2, 0]}>
|
||||
<boxGeometry args={[ft, ft, depth - ft * 2]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[-width / 2 + ft / 2, wheelRadius * 2 + ft / 2, 0]}>
|
||||
<boxGeometry args={[ft, ft, depth - ft * 2]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
|
||||
{/* Cage frame - top rectangle */}
|
||||
<mesh position={[0, wheelRadius * 2 + height - ft / 2, depth / 2 - ft / 2]}>
|
||||
<boxGeometry args={[width, ft, ft]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[0, wheelRadius * 2 + height - ft / 2, -depth / 2 + ft / 2]}>
|
||||
<boxGeometry args={[width, ft, ft]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[width / 2 - ft / 2, wheelRadius * 2 + height - ft / 2, 0]}>
|
||||
<boxGeometry args={[ft, ft, depth - ft * 2]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
<mesh position={[-width / 2 + ft / 2, wheelRadius * 2 + height - ft / 2, 0]}>
|
||||
<boxGeometry args={[ft, ft, depth - ft * 2]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
|
||||
{/* Vertical posts (corners) */}
|
||||
{[[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sz], i) => (
|
||||
<mesh key={i} position={[sx * (width / 2 - ft / 2), wheelRadius * 2 + height / 2, sz * (depth / 2 - ft / 2)]}>
|
||||
<boxGeometry args={[ft, height - ft, ft]} />
|
||||
<meshStandardMaterial color={color} metalness={0.6} roughness={0.3} emissive={color} emissiveIntensity={emissiveIntensity} />
|
||||
</mesh>
|
||||
))}
|
||||
|
||||
{/* Caster wheels */}
|
||||
{[[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sz], i) => (
|
||||
<mesh key={`wheel-${i}`} position={[sx * (width / 2 - 0.08), wheelRadius, sz * (depth / 2 - 0.08)]} rotation={[0, 0, Math.PI / 2]}>
|
||||
<cylinderGeometry args={[wheelRadius, wheelRadius, 0.03, 12]} />
|
||||
<meshStandardMaterial color="#475569" metalness={0.7} roughness={0.3} />
|
||||
</mesh>
|
||||
))}
|
||||
|
||||
{/* Wire mesh sides (simplified - just vertical lines) */}
|
||||
{[-1, 1].map((sz) => (
|
||||
<group key={`side-${sz}`}>
|
||||
{[0.2, 0.4, 0.6, 0.8].map((t, i) => (
|
||||
<mesh key={i} position={[-width / 2 + width * t, wheelRadius * 2 + height / 2, sz * (depth / 2 - 0.01)]}>
|
||||
<boxGeometry args={[0.008, height - ft * 2, 0.008]} />
|
||||
<meshStandardMaterial color={color} transparent opacity={0.6} />
|
||||
</mesh>
|
||||
))}
|
||||
</group>
|
||||
))}
|
||||
|
||||
<RollCageMesh color={color} active={active} shadows={shadows} />
|
||||
|
||||
{/* Label */}
|
||||
<Html position={[0, wheelRadius * 2 + height + 0.15, 0]} center>
|
||||
<Html position={[0, height + 0.15, 0]} center>
|
||||
<div style={{
|
||||
color: active ? color : '#64748b',
|
||||
fontSize: '18px',
|
||||
@@ -833,6 +783,7 @@ function RollCage({ position, label, color, active }: {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/** Chute/deflector for routing items to C/D */
|
||||
function RouteChute({ gateX, targetZ, color, active }: {
|
||||
gateX: number;
|
||||
@@ -1108,29 +1059,29 @@ function ShapeOutline({ position, scale, visible, isRound, category }: {
|
||||
}
|
||||
|
||||
/** Gate/accumulator zone - positioned at belt height */
|
||||
function GateZone({ category }: { category: Category | null }) {
|
||||
const gateColor = category === 'B' ? COLORS.routeB
|
||||
: category === 'C' ? COLORS.routeC
|
||||
: category === 'D' ? COLORS.routeD
|
||||
function GateZone({ category, shadows = false }: { category: Category | null; shadows?: boolean }) {
|
||||
const gateColor = category === 'B' ? COLORS.routeB
|
||||
: category === 'C' ? COLORS.routeC
|
||||
: category === 'D' ? COLORS.routeD
|
||||
: COLORS.gateFrame;
|
||||
|
||||
|
||||
const gateX = ZONES.GATE.x;
|
||||
const postSpacing = CONVEYOR_WIDTH_M / 2 + 0.08;
|
||||
const postHeight = 0.4;
|
||||
|
||||
|
||||
return (
|
||||
<group position={[gateX, 0, 0]}>
|
||||
{/* Gate posts from floor */}
|
||||
<mesh position={[0, BELT_Y + postHeight / 2, postSpacing]}>
|
||||
<mesh position={[0, BELT_Y + postHeight / 2, postSpacing]} castShadow={shadows}>
|
||||
<cylinderGeometry args={[0.035, 0.035, postHeight, 8]} />
|
||||
<meshStandardMaterial color={COLORS.gateFrame} metalness={0.4} roughness={0.5} />
|
||||
</mesh>
|
||||
<mesh position={[0, BELT_Y + postHeight / 2, -postSpacing]}>
|
||||
<mesh position={[0, BELT_Y + postHeight / 2, -postSpacing]} castShadow={shadows}>
|
||||
<cylinderGeometry args={[0.035, 0.035, postHeight, 8]} />
|
||||
<meshStandardMaterial color={COLORS.gateFrame} metalness={0.4} roughness={0.5} />
|
||||
</mesh>
|
||||
{/* Gate bar */}
|
||||
<mesh position={[0, BELT_Y + postHeight, 0]}>
|
||||
<mesh position={[0, BELT_Y + postHeight, 0]} castShadow={shadows}>
|
||||
<boxGeometry args={[0.05, 0.05, postSpacing * 2]} />
|
||||
<meshStandardMaterial color={gateColor} />
|
||||
</mesh>
|
||||
@@ -1189,21 +1140,34 @@ function RouteArrows({ activeRoute }: { activeRoute: Category | null }) {
|
||||
}
|
||||
|
||||
/** Main continuous scene - light warehouse style with correct physical dimensions */
|
||||
function ContinuousScene({
|
||||
playback,
|
||||
function ContinuousScene({
|
||||
playback,
|
||||
simplified,
|
||||
autoCameraEnabled,
|
||||
viewportType
|
||||
}: {
|
||||
playback: ContinuousPlaybackState;
|
||||
viewportType,
|
||||
stage0,
|
||||
stage1,
|
||||
maxVisibleItems = MAX_VISIBLE_ITEMS,
|
||||
}: {
|
||||
playback: ContinuousPlaybackState;
|
||||
simplified: boolean;
|
||||
autoCameraEnabled: boolean;
|
||||
viewportType: ViewportType;
|
||||
stage0?: Stage0Config;
|
||||
stage1?: Stage1Config;
|
||||
maxVisibleItems?: number;
|
||||
}) {
|
||||
const category = playback.targetCategory;
|
||||
const phase = playback.currentPhase;
|
||||
const liteScene = simplified || !ENABLE_DEMO_EFFECTS;
|
||||
const effectsEnabled = ENABLE_DEMO_EFFECTS && !simplified;
|
||||
|
||||
// Stage 0 prototype flags (inert when stage0 is absent — default route unchanged)
|
||||
const proto = stage0?.enabled ?? false;
|
||||
const protoShadows = proto && stage0!.shadows;
|
||||
const protoCamera = proto && stage0!.camera;
|
||||
const shotOverride = protoCamera && stage0!.shot ? shotToPhaseCategory(stage0!.shot) : null;
|
||||
const darkBg = proto && stage0!.darkBackground;
|
||||
|
||||
const cameraHighlight = shouldHighlightCamera(phase);
|
||||
const showScan = shouldShowScanEffect(phase);
|
||||
@@ -1220,7 +1184,7 @@ function ContinuousScene({
|
||||
// Use cumulative playlist durations (cases may differ: jam / e-stop).
|
||||
const { totalElapsedMs, currentCase, currentCaseIndex, caseElapsedMs, positionJitter } = playback;
|
||||
const casesSpawned = currentCaseIndex + 1;
|
||||
const startIndex = Math.max(0, casesSpawned - MAX_VISIBLE_ITEMS);
|
||||
const startIndex = Math.max(0, casesSpawned - maxVisibleItems);
|
||||
|
||||
const sceneItems = useMemo(() => {
|
||||
const items = [];
|
||||
@@ -1247,6 +1211,19 @@ function ContinuousScene({
|
||||
const itemData = ITEMS.find(i => i.id === itemId) ?? ITEMS[0];
|
||||
const isRound = itemData.roundness >= 0.7;
|
||||
const dims = getRenderedItemDimensions(itemData.dimensionsMm);
|
||||
|
||||
// Stage 1 real-model verification overlay (debug only, read-only)
|
||||
const verifySku = stage1?.enabled && stage1.verify === 'real-models'
|
||||
? (stage1.sku ?? itemId)
|
||||
: null;
|
||||
|
||||
// Preload the default playlist's real assets once per scene mount
|
||||
// (deduped by loader cache; rare SKUs stay lazy — Stage 1 §19 budget).
|
||||
useEffect(() => {
|
||||
for (const asset of getPreloadAssets()) {
|
||||
if (asset.runtimePath) preloadRealItemModel(asset.runtimePath);
|
||||
}
|
||||
}, []);
|
||||
const itemScale = Math.max(dims.width, dims.depth, dims.height);
|
||||
|
||||
// Get item position for measurement visualization using physical model
|
||||
@@ -1271,19 +1248,49 @@ function ContinuousScene({
|
||||
: 'x';
|
||||
const itemColor = category ? COLORS[`route${category}` as keyof typeof COLORS] : COLORS.sensorAccent;
|
||||
|
||||
// Cinematic camera active only when heavy effects enabled
|
||||
const cinematicActive = effectsEnabled && autoCameraEnabled && playback.status === 'running';
|
||||
// Cinematic camera: heavy effects (legacy flag) OR stage0 prototype camera.
|
||||
// Manual shot override keeps the camera driving even while paused.
|
||||
const cinematicActive = (effectsEnabled || protoCamera) && autoCameraEnabled
|
||||
&& (playback.status === 'running' || shotOverride !== null);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Light background */}
|
||||
<color attach="background" args={[COLORS.background]} />
|
||||
|
||||
{/* Soft natural lighting — no shadow maps (Canvas shadows=false for perf) */}
|
||||
<ambientLight intensity={0.7} />
|
||||
<hemisphereLight args={['#f8fafc', '#d0dae8', 0.5]} />
|
||||
<directionalLight position={[8, 12, 6]} intensity={0.9} />
|
||||
<directionalLight position={[-5, 8, -4]} intensity={0.35} />
|
||||
{/* Background: light warehouse by default; dark cinematic in prototype mode */}
|
||||
<color attach="background" args={[darkBg ? INDUSTRIAL_PALETTE.backgroundDark : COLORS.background]} />
|
||||
|
||||
{proto ? (
|
||||
<>
|
||||
{/* Cinematic rig: very low ambient, strong key, soft fill, cool rim */}
|
||||
<ambientLight intensity={stage0!.ambient} />
|
||||
<hemisphereLight args={['#223148', '#0b1220', 0.3]} />
|
||||
<directionalLight
|
||||
position={[6, 9, 4]}
|
||||
intensity={1.6}
|
||||
castShadow={protoShadows}
|
||||
shadow-mapSize-width={1024}
|
||||
shadow-mapSize-height={1024}
|
||||
shadow-camera-left={-7}
|
||||
shadow-camera-right={7}
|
||||
shadow-camera-top={7}
|
||||
shadow-camera-bottom={-7}
|
||||
shadow-camera-near={1}
|
||||
shadow-camera-far={25}
|
||||
shadow-bias={-0.0004}
|
||||
/>
|
||||
{/* Fill — keeps shadowed side readable */}
|
||||
{stage0!.fill && <directionalLight position={[-5, 6, -3]} intensity={0.35} />}
|
||||
{/* Rim — cheap back light for edge separation */}
|
||||
{stage0!.rim && <directionalLight position={[2, 5, -8]} intensity={0.7} color="#bcd7ff" />}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Soft natural lighting — no shadow maps (Canvas shadows=false for perf) */}
|
||||
<ambientLight intensity={0.7} />
|
||||
<hemisphereLight args={['#f8fafc', '#d0dae8', 0.5]} />
|
||||
<directionalLight position={[8, 12, 6]} intensity={0.9} />
|
||||
<directionalLight position={[-5, 8, -4]} intensity={0.35} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Grid */}
|
||||
<Grid
|
||||
@@ -1300,13 +1307,13 @@ function ContinuousScene({
|
||||
/>
|
||||
|
||||
{/* Floor */}
|
||||
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]}>
|
||||
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]} receiveShadow={protoShadows}>
|
||||
<planeGeometry args={[16, 12]} />
|
||||
<meshStandardMaterial color={COLORS.floor} roughness={0.9} metalness={0} />
|
||||
</mesh>
|
||||
|
||||
{/* Conveyor - belt top at 0.7m */}
|
||||
<ConveyorBelt pulseActive={showPulse} elapsedMs={totalElapsedMs} simplified={liteScene} />
|
||||
<ConveyorBelt pulseActive={showPulse} elapsedMs={totalElapsedMs} simplified={liteScene} shadows={protoShadows} />
|
||||
|
||||
{/* Zone A - spawn point */}
|
||||
<ZoneMarker
|
||||
@@ -1320,19 +1327,21 @@ function ContinuousScene({
|
||||
<BReceiverBin active={activeRoute === 'B'} />
|
||||
|
||||
{/* Zone C - roll cage for oversized items */}
|
||||
<RollCage
|
||||
position={[ZONES.C.x, 0, ZONES.C.z]}
|
||||
label="C"
|
||||
color={COLORS.routeC}
|
||||
<RollCage
|
||||
position={[ZONES.C.x, 0, ZONES.C.z]}
|
||||
label="C"
|
||||
color={COLORS.routeC}
|
||||
active={activeRoute === 'C'}
|
||||
shadows={protoShadows}
|
||||
/>
|
||||
|
||||
|
||||
{/* Zone D - roll cage for round items */}
|
||||
<RollCage
|
||||
position={[ZONES.D.x, 0, ZONES.D.z]}
|
||||
label="D"
|
||||
color={COLORS.routeD}
|
||||
<RollCage
|
||||
position={[ZONES.D.x, 0, ZONES.D.z]}
|
||||
label="D"
|
||||
color={COLORS.routeD}
|
||||
active={activeRoute === 'D'}
|
||||
shadows={protoShadows}
|
||||
/>
|
||||
|
||||
{/* Chutes for routing to C/D */}
|
||||
@@ -1375,22 +1384,24 @@ function ContinuousScene({
|
||||
{effectsEnabled && <ScanLine active={showScan} />}
|
||||
|
||||
{/* Gate/diverter */}
|
||||
<GateZone category={category} />
|
||||
|
||||
<GateZone category={category} shadows={protoShadows} />
|
||||
|
||||
{/* Actuator pusher for routing */}
|
||||
<ActuatorPusher active={showActuator} category={category} />
|
||||
<ActuatorPusher active={showActuator} category={category} shadows={protoShadows} />
|
||||
|
||||
{/* Route arrows on belt surface */}
|
||||
<RouteArrows activeRoute={activeRoute} />
|
||||
|
||||
{/* Physically simulated items */}
|
||||
{sceneItems.map(item => (
|
||||
<PhysicalPlaybackItem
|
||||
<PhysicalPlaybackItem
|
||||
key={item.id}
|
||||
caseData={item.caseData}
|
||||
elapsedMs={item.elapsedMs}
|
||||
slotIndex={item.slotIndex}
|
||||
verifySku={verifySku}
|
||||
jitter={item.slotIndex === currentCaseIndex ? positionJitter : undefined}
|
||||
castShadow={protoShadows}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -1419,12 +1430,14 @@ function ContinuousScene({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Cinematic camera controller — opt-in only */}
|
||||
{effectsEnabled && (
|
||||
{/* Cinematic camera controller — opt-in (legacy effects flag or stage0 prototype) */}
|
||||
{(effectsEnabled || protoCamera) && (
|
||||
<CinematicCameraController
|
||||
playback={playback}
|
||||
enabled={cinematicActive}
|
||||
viewportType={viewportType}
|
||||
overridePhase={shotOverride?.phase ?? null}
|
||||
overrideCategory={shotOverride?.category ?? null}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1443,54 +1456,135 @@ function ContinuousScene({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage 0 adaptive quality: rolling-average FPS, checks at most once per 4 s,
|
||||
* cooldown between switches, max 3 automatic steps. Only the DPR lever is
|
||||
* applied live (via R3F setDpr — no React state churn per frame); shadow/AA
|
||||
* changes require remount and are reported as not-live-switchable.
|
||||
*/
|
||||
function AdaptiveQualityController({ initialMode }: { initialMode: QualityMode }) {
|
||||
const setDpr = useThree((s) => s.setDpr);
|
||||
const stateRef = useRef({
|
||||
mode: initialMode as QualityMode,
|
||||
frames: 0,
|
||||
windowStart: 0,
|
||||
lastSwitchAt: 0,
|
||||
switches: 0,
|
||||
});
|
||||
|
||||
useFrame(({ clock }) => {
|
||||
const st = stateRef.current;
|
||||
st.frames += 1;
|
||||
const now = clock.elapsedTime;
|
||||
if (st.windowStart === 0) {
|
||||
st.windowStart = now;
|
||||
st.lastSwitchAt = now;
|
||||
return;
|
||||
}
|
||||
const windowLen = now - st.windowStart;
|
||||
if (windowLen < 4) return; // evaluate at most once per 4 s
|
||||
|
||||
const avgFps = st.frames / windowLen;
|
||||
st.frames = 0;
|
||||
st.windowStart = now;
|
||||
|
||||
const previous = st.mode;
|
||||
const next = adaptQuality(previous, avgFps);
|
||||
if (next === previous) return;
|
||||
if (st.switches >= 3) return; // cap automatic switches
|
||||
if (now - st.lastSwitchAt < 8) return; // cooldown / hysteresis
|
||||
|
||||
st.mode = next;
|
||||
st.switches += 1;
|
||||
st.lastSwitchAt = now;
|
||||
setDpr(Math.min(window.devicePixelRatio || 1, getQualitySettings(next).dprMax));
|
||||
if (typeof window !== 'undefined') {
|
||||
const message = describeAdaptiveSwitch(previous, next, avgFps);
|
||||
console.info(`[stage0] ${message}`);
|
||||
const w = window as unknown as { __STAGE0_ADAPT__?: string[] };
|
||||
w.__STAGE0_ADAPT__ ??= [];
|
||||
w.__STAGE0_ADAPT__.push(message);
|
||||
}
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function SorterDigitalTwinContinuous({
|
||||
playback,
|
||||
simplified = false,
|
||||
onContextLost,
|
||||
onContextRestored,
|
||||
autoCameraEnabled = true,
|
||||
viewportType = 'desktop',
|
||||
qualityMode,
|
||||
stage0,
|
||||
stage1,
|
||||
}: SorterDigitalTwinContinuousProps) {
|
||||
const mode = qualityMode ?? detectQualityMode(typeof window !== 'undefined' ? window.innerWidth : 1200);
|
||||
const quality = getQualitySettings(mode);
|
||||
const useSimplified = simplified || mode === 'low';
|
||||
const antialias = quality.antialias && !useSimplified;
|
||||
const proto = stage0?.enabled ?? false;
|
||||
const protoShadows = proto && stage0!.shadows;
|
||||
const shadowsEnabled = proto ? protoShadows : quality.shadows;
|
||||
const perfEnabled =
|
||||
typeof window !== 'undefined' &&
|
||||
new URLSearchParams(window.location.search).get('perf') === '1';
|
||||
(typeof window !== 'undefined' &&
|
||||
new URLSearchParams(window.location.search).get('perf') === '1') ||
|
||||
(proto && stage0!.perf);
|
||||
return (
|
||||
<div className="digital-twin-wrap continuous-twin">
|
||||
<div className="digital-twin-canvas continuous-canvas">
|
||||
<Canvas
|
||||
camera={{ position: [4.5, 3.5, 5.0], fov: 45 }}
|
||||
dpr={[1, quality.dprMax]}
|
||||
shadows={quality.shadows}
|
||||
shadows={shadowsEnabled ? 'soft' : false}
|
||||
gl={{ antialias, powerPreference: 'high-performance' }}
|
||||
onCreated={({ gl }) => {
|
||||
if (proto) {
|
||||
gl.outputColorSpace = THREE.SRGBColorSpace;
|
||||
gl.toneMapping = stage0!.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
|
||||
gl.toneMappingExposure = 1.0;
|
||||
gl.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||
}
|
||||
const canvas = gl.domElement;
|
||||
const handleLost = (event: Event) => {
|
||||
event.preventDefault();
|
||||
if (!canvas.isConnected) return;
|
||||
onContextLost?.();
|
||||
};
|
||||
const handleRestored = () => {
|
||||
if (!canvas.isConnected) return;
|
||||
onContextRestored?.();
|
||||
};
|
||||
canvas.addEventListener('webglcontextlost', handleLost, false);
|
||||
canvas.addEventListener('webglcontextrestored', handleRestored, false);
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<ContinuousScene
|
||||
playback={playback}
|
||||
<ContinuousScene
|
||||
playback={playback}
|
||||
simplified={useSimplified}
|
||||
autoCameraEnabled={autoCameraEnabled}
|
||||
viewportType={viewportType}
|
||||
stage0={stage0}
|
||||
stage1={stage1}
|
||||
maxVisibleItems={quality.maxVisibleItems}
|
||||
/>
|
||||
{perfEnabled ? (
|
||||
<PerfCollector
|
||||
enabled
|
||||
mode={mode}
|
||||
shadows={quality.shadows}
|
||||
shadows={shadowsEnabled}
|
||||
antialias={antialias}
|
||||
/>
|
||||
) : null}
|
||||
{proto && stage0!.adaptive ? <AdaptiveQualityController initialMode={mode} /> : null}
|
||||
{proto && stage0!.post ? (
|
||||
<Suspense fallback={null}>
|
||||
<PostProcessingSpike />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as THREE from 'three';
|
||||
import type { Category } from '../../domain/types';
|
||||
import { ROUTE_COLORS, TWIN_LAYOUT } from './itemMotion';
|
||||
import RollCageMesh from './RollCageMesh';
|
||||
|
||||
interface Props {
|
||||
activeCategory?: Category;
|
||||
@@ -48,7 +48,7 @@ function ZoneBox({
|
||||
);
|
||||
}
|
||||
|
||||
/** Roll-cage with wireframe edges for C/D zones */
|
||||
/** Roll-cage for C/D zones — shared instanced mesh (exterior 1200×800×800 incl. wheels), open top */
|
||||
function RollCage({
|
||||
position,
|
||||
size,
|
||||
@@ -62,46 +62,11 @@ function RollCage({
|
||||
}) {
|
||||
return (
|
||||
<group position={position}>
|
||||
{/* Cage body (transparent) */}
|
||||
<mesh>
|
||||
<boxGeometry args={size} />
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
transparent
|
||||
opacity={active ? 0.4 : 0.15}
|
||||
emissive={color}
|
||||
emissiveIntensity={active ? 0.6 : 0.1}
|
||||
/>
|
||||
</mesh>
|
||||
|
||||
{/* Cage wireframe edges (visible frame) */}
|
||||
<lineSegments>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(...size)]} />
|
||||
<lineBasicMaterial color={color} linewidth={active ? 3 : 1} opacity={active ? 1 : 0.5} transparent />
|
||||
</lineSegments>
|
||||
|
||||
{/* Vertical posts (corners) for visual emphasis - thicker */}
|
||||
{[
|
||||
[-size[0] / 2, 0, -size[2] / 2],
|
||||
[size[0] / 2, 0, -size[2] / 2],
|
||||
[-size[0] / 2, 0, size[2] / 2],
|
||||
[size[0] / 2, 0, size[2] / 2],
|
||||
].map((offset, i) => (
|
||||
<mesh key={i} position={offset as [number, number, number]}>
|
||||
<boxGeometry args={[0.06, size[1], 0.06]} />
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
metalness={0.4}
|
||||
roughness={0.6}
|
||||
emissive={active ? color : '#000000'}
|
||||
emissiveIntensity={active ? 0.3 : 0}
|
||||
/>
|
||||
</mesh>
|
||||
))}
|
||||
|
||||
<RollCageMesh color={color} active={active} />
|
||||
|
||||
{/* Floor highlight for active cage */}
|
||||
{active && (
|
||||
<mesh position={[0, -size[1] / 2 + 0.02, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
<mesh position={[0, 0.02, 0]} rotation={[-Math.PI / 2, 0, 0]}>
|
||||
<planeGeometry args={[size[0] * 0.9, size[2] * 0.9]} />
|
||||
<meshStandardMaterial
|
||||
color={color}
|
||||
@@ -139,17 +104,17 @@ export default function SortingZones3D({ activeCategory, activeRoute }: Props) {
|
||||
active={active === 'B'}
|
||||
/>
|
||||
|
||||
{/* Roll-cage C 1200×800×800 mm — orange with wireframe */}
|
||||
{/* Roll-cage C 1200×800×800 mm — orange, ground-origin shared mesh */}
|
||||
<RollCage
|
||||
position={[TWIN_LAYOUT.gateX + 0.4, cage.y / 2, TWIN_LAYOUT.zoneCZ]}
|
||||
position={[TWIN_LAYOUT.gateX + 0.4, 0, TWIN_LAYOUT.zoneCZ]}
|
||||
size={[cage.x, cage.y, cage.z]}
|
||||
color={ROUTE_COLORS.C}
|
||||
active={active === 'C'}
|
||||
/>
|
||||
|
||||
{/* Roll-cage D 1200×800×800 mm — purple with wireframe */}
|
||||
{/* Roll-cage D 1200×800×800 mm — purple, ground-origin shared mesh */}
|
||||
<RollCage
|
||||
position={[TWIN_LAYOUT.gateX + 0.4, cage.y / 2, TWIN_LAYOUT.zoneDZ]}
|
||||
position={[TWIN_LAYOUT.gateX + 0.4, 0, TWIN_LAYOUT.zoneDZ]}
|
||||
size={[cage.x, cage.y, cage.z]}
|
||||
color={ROUTE_COLORS.D}
|
||||
active={active === 'D'}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Component, ReactNode } from 'react';
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
onError?: (error: Error) => void;
|
||||
/** Explicit switch-to-2D action (replaces the old dead `use-2d-fallback` event). */
|
||||
onUse2D?: () => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
@@ -36,9 +38,7 @@ export default class ThreeErrorBoundary extends Component<Props, State> {
|
||||
|
||||
handleUse2D = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
// Trigger 2D fallback via parent component
|
||||
const event = new CustomEvent('use-2d-fallback');
|
||||
window.dispatchEvent(event);
|
||||
this.props.onUse2D?.();
|
||||
};
|
||||
|
||||
render() {
|
||||
@@ -115,22 +115,24 @@ export default class ThreeErrorBoundary extends Component<Props, State> {
|
||||
Reload 3D
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={this.handleUse2D}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
background: 'rgba(148, 163, 184, 0.15)',
|
||||
border: '1px solid rgba(148, 163, 184, 0.3)',
|
||||
borderRadius: '8px',
|
||||
color: '#94a3b8',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
Use 2D Fallback
|
||||
</button>
|
||||
{this.props.onUse2D && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={this.handleUse2D}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
background: 'rgba(148, 163, 184, 0.15)',
|
||||
border: '1px solid rgba(148, 163, 184, 0.3)',
|
||||
borderRadius: '8px',
|
||||
color: '#94a3b8',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
Use 2D Fallback
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -41,7 +41,9 @@ export function progressForState(state: MachineState, elapsedMs: number): number
|
||||
export function itemPosition3D(simulation: SimulationState): [number, number, number] {
|
||||
const progress = progressForState(simulation.machineState, simulation.elapsedInStateMs);
|
||||
const x = TWIN_LAYOUT.startX + progress * (TWIN_LAYOUT.endX - TWIN_LAYOUT.startX);
|
||||
const y = TWIN_LAYOUT.beltY + 0.12;
|
||||
// Stage 1: bottom-contact semantics — the item's bottom point rests on the
|
||||
// belt surface (was beltY + 0.12, a 12cm visual float).
|
||||
const y = TWIN_LAYOUT.beltY;
|
||||
let z = 0;
|
||||
|
||||
if (simulation.machineState === 'ROUTE_TO_C') {
|
||||
|
||||
@@ -1,82 +1,123 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
MODEL_ASSETS,
|
||||
ARCHIVE_ONLY_MODELS,
|
||||
getModelAsset,
|
||||
getSTLAssets,
|
||||
getRealAssets,
|
||||
getProceduralAssets,
|
||||
getManifestStats,
|
||||
} from './modelAssets';
|
||||
|
||||
describe('modelAssets', () => {
|
||||
// Runtime files under public/ (project convention: import.meta.glob instead of node:fs)
|
||||
const RUNTIME_MODEL_FILES = Object.keys(
|
||||
import.meta.glob('../../public/models/*.stl', { eager: true, query: '?url', import: 'default' }),
|
||||
).map((p) => p.replace(/^.*\/public/, ''));
|
||||
|
||||
describe('modelAssets (Stage 1 real-model manifest)', () => {
|
||||
describe('MODEL_ASSETS', () => {
|
||||
it('should contain assets for all scenario items', () => {
|
||||
const expectedIds = [
|
||||
'SKU-001',
|
||||
'SKU-002',
|
||||
'SKU-003',
|
||||
'SKU-004',
|
||||
'SKU-005',
|
||||
'SKU-006',
|
||||
'SKU-007',
|
||||
'SKU-008',
|
||||
'SKU-009',
|
||||
'SKU-010',
|
||||
'SKU-011',
|
||||
'SKU-001', 'SKU-002', 'SKU-003', 'SKU-004', 'SKU-005', 'SKU-006',
|
||||
'SKU-007', 'SKU-008', 'SKU-009', 'SKU-010', 'SKU-011',
|
||||
];
|
||||
|
||||
const actualIds = MODEL_ASSETS.map((asset) => asset.itemId);
|
||||
expectedIds.forEach((id) => {
|
||||
expect(actualIds).toContain(id);
|
||||
});
|
||||
});
|
||||
|
||||
it('should have fallback primitive for every asset', () => {
|
||||
it('should have a unique SKU per entry', () => {
|
||||
const ids = MODEL_ASSETS.map((asset) => asset.itemId);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it('should define a fallback primitive for every asset', () => {
|
||||
MODEL_ASSETS.forEach((asset) => {
|
||||
expect(asset.fallbackPrimitive).toMatch(/^(box|cylinder|sphere)$/);
|
||||
});
|
||||
});
|
||||
|
||||
it('should have valid loader type for every asset', () => {
|
||||
it('should have valid expected dimensions for every asset', () => {
|
||||
MODEL_ASSETS.forEach((asset) => {
|
||||
expect(asset.loaderType).toMatch(/^(stl|glb|procedural)$/);
|
||||
expect(asset.dimensions.width).toBeGreaterThan(0);
|
||||
expect(asset.dimensions.depth).toBeGreaterThan(0);
|
||||
expect(asset.dimensions.height).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('should have frontendAssetPath only for stl/glb loaders', () => {
|
||||
MODEL_ASSETS.forEach((asset) => {
|
||||
if (asset.loaderType === 'procedural') {
|
||||
expect(asset.frontendAssetPath).toBeUndefined();
|
||||
it('runtime paths must exist on disk for every real asset', () => {
|
||||
for (const asset of MODEL_ASSETS) {
|
||||
if (asset.defaultRealAsset) {
|
||||
expect(asset.runtimePath, `${asset.itemId} runtimePath`).toBeTruthy();
|
||||
expect(
|
||||
RUNTIME_MODEL_FILES,
|
||||
`${asset.itemId} → ${asset.runtimePath} must exist in public/models`,
|
||||
).toContain(asset.runtimePath);
|
||||
} else {
|
||||
expect(asset.frontendAssetPath).toBeTruthy();
|
||||
expect(asset.runtimePath).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('demo STL coverage', () => {
|
||||
it('uses real STL for every available demo model', () => {
|
||||
const stlMap: Record<string, string> = {
|
||||
'SKU-001': '/models/box-300.stl',
|
||||
'SKU-002': '/models/lunchbox.stl',
|
||||
'SKU-004': '/models/box-400.stl',
|
||||
'SKU-006': '/models/plate.stl',
|
||||
'SKU-007': '/models/bottle.stl',
|
||||
'SKU-008': '/models/cylinder.stl',
|
||||
'SKU-011': '/models/cylinder.stl', // c_priority round item
|
||||
};
|
||||
for (const [id, path] of Object.entries(stlMap)) {
|
||||
const asset = getModelAsset(id);
|
||||
expect(asset?.loaderType).toBe('stl');
|
||||
expect(asset?.frontendAssetPath).toBe(path);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps fallbacks explicit and only for heavy/missing STL', () => {
|
||||
const fallbackIds = ['SKU-003', 'SKU-005', 'SKU-009', 'SKU-010'];
|
||||
for (const id of fallbackIds) {
|
||||
it('real assets must declare provenance (archive, file, sha256)', () => {
|
||||
for (const asset of getRealAssets()) {
|
||||
expect(asset.sourceArchive).toBe('input_info/doc-1782987733.zip');
|
||||
expect(asset.sourceFile).toBeTruthy();
|
||||
expect(asset.sourceSha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(asset.runtimeSha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(asset.sourceBoundingBoxMm).not.toBeNull();
|
||||
expect(asset.worldExpectedMm).not.toBeNull();
|
||||
expect(asset.triangleCount).toBeGreaterThan(0);
|
||||
expect(asset.fileSizeBytes).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('real assets use bottom-center pivot and uniform mm→m scale only', () => {
|
||||
for (const asset of getRealAssets()) {
|
||||
expect(asset.pivotMode).toBe('bottom-center');
|
||||
expect(asset.scaleMode).toBe('uniform-mm-to-m');
|
||||
}
|
||||
});
|
||||
|
||||
it('must NOT silently substitute another model for a SKU', () => {
|
||||
// SKU-011 previously reused cylinder.stl — forbidden now.
|
||||
const sku011 = getModelAsset('SKU-011');
|
||||
expect(sku011?.defaultRealAsset).toBe(false);
|
||||
expect(sku011?.runtimePath).toBeNull();
|
||||
expect(sku011?.notes).toContain('NO_EXACT_OFFICIAL_MODEL');
|
||||
});
|
||||
});
|
||||
|
||||
describe('official test-set coverage', () => {
|
||||
it('integrates the 9 official models that have matching SKUs', () => {
|
||||
const realIds = getRealAssets().map((a) => a.itemId).sort();
|
||||
expect(realIds).toEqual([
|
||||
'SKU-001', 'SKU-002', 'SKU-003', 'SKU-004', 'SKU-005',
|
||||
'SKU-006', 'SKU-007', 'SKU-008', 'SKU-009',
|
||||
]);
|
||||
});
|
||||
|
||||
it('marks SKUs without an exact official model honestly', () => {
|
||||
for (const id of ['SKU-010', 'SKU-011']) {
|
||||
const asset = getModelAsset(id);
|
||||
expect(asset?.loaderType).toBe('procedural');
|
||||
expect(asset?.notes).toBeTruthy();
|
||||
expect(asset?.defaultRealAsset).toBe(false);
|
||||
expect(asset?.notes).toContain('NO_EXACT_OFFICIAL_MODEL');
|
||||
}
|
||||
});
|
||||
|
||||
it('documents archive-only official models (bag, helmet)', () => {
|
||||
const names = ARCHIVE_ONLY_MODELS.map((m) => m.displayName);
|
||||
expect(names).toContain('Мешок');
|
||||
expect(names).toContain('Шлем');
|
||||
ARCHIVE_ONLY_MODELS.forEach((m) => {
|
||||
expect(m.sourceSha256).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
});
|
||||
|
||||
it('respects runtime file budgets (<= 1.5MB hard, <= 100k tris acceptable)', () => {
|
||||
for (const asset of getRealAssets()) {
|
||||
expect(asset.fileSizeBytes!, `${asset.itemId} file size`).toBeLessThanOrEqual(1.5 * 1024 * 1024);
|
||||
expect(asset.triangleCount!, `${asset.itemId} triangles`).toBeLessThanOrEqual(100_000);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -95,43 +136,14 @@ describe('modelAssets', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSTLAssets', () => {
|
||||
it('should return only assets with loaderType stl', () => {
|
||||
const stlAssets = getSTLAssets();
|
||||
stlAssets.forEach((asset) => {
|
||||
expect(asset.loaderType).toBe('stl');
|
||||
});
|
||||
});
|
||||
|
||||
it('should contain at least some STL assets', () => {
|
||||
const stlAssets = getSTLAssets();
|
||||
expect(stlAssets.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProceduralAssets', () => {
|
||||
it('should return only assets with loaderType procedural', () => {
|
||||
const proceduralAssets = getProceduralAssets();
|
||||
proceduralAssets.forEach((asset) => {
|
||||
expect(asset.loaderType).toBe('procedural');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getManifestStats', () => {
|
||||
it('should return correct totals', () => {
|
||||
const stats = getManifestStats();
|
||||
expect(stats.total).toBe(MODEL_ASSETS.length);
|
||||
expect(stats.stl).toBe(getSTLAssets().length);
|
||||
expect(stats.real).toBe(getRealAssets().length);
|
||||
expect(stats.procedural).toBe(getProceduralAssets().length);
|
||||
expect(stats.stl + stats.procedural).toBe(stats.total);
|
||||
});
|
||||
|
||||
it('should calculate correct percentage', () => {
|
||||
const stats = getManifestStats();
|
||||
expect(stats.stlPercentage).toBeGreaterThanOrEqual(0);
|
||||
expect(stats.stlPercentage).toBeLessThanOrEqual(100);
|
||||
expect(stats.stlPercentage).toBe(Math.round((stats.stl / stats.total) * 100));
|
||||
expect(stats.real + stats.procedural).toBe(stats.total);
|
||||
expect(stats.realPercentage).toBe(Math.round((stats.real / stats.total) * 100));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,46 +1,95 @@
|
||||
/**
|
||||
* Model Assets Manifest — real 3D models for product items.
|
||||
* Maps simulation items to real STL/GLB models from input_info.
|
||||
* Model Assets Manifest — единый источник сведений о 3D-ассетах товаров.
|
||||
*
|
||||
* Stage 1 (real models): каждая запись фиксирует происхождение (архив OZON,
|
||||
* файл, SHA-256), измеренный исходный bounding box, transform нормализации
|
||||
* (rotation → uniform mm→m scale → bottom-center pivot) и бюджеты.
|
||||
*
|
||||
* Source measurements: scripts/stage1-analyze-stl.mjs (см. docs/stage1_real_models/).
|
||||
* Decimation: scripts/stage1-decimate-stl.mjs (vertex clustering, воспроизводимо).
|
||||
* Validation: scripts/validate-real-models.mjs (НЕ редактировать статусы вручную).
|
||||
*/
|
||||
|
||||
import type { Category, DimensionsMm } from '../domain/types';
|
||||
|
||||
export interface SourceBoundingBoxMm {
|
||||
min: [number, number, number];
|
||||
max: [number, number, number];
|
||||
size: [number, number, number];
|
||||
}
|
||||
|
||||
export interface ModelAsset {
|
||||
/** Item ID from items.ts (e.g. 'SKU-006') */
|
||||
itemId: string;
|
||||
|
||||
/** Display name (Russian) */
|
||||
|
||||
/** Display name (Russian, official test-set name) */
|
||||
displayName: string;
|
||||
|
||||
|
||||
/** Expected category scenario */
|
||||
categoryScenario: Category;
|
||||
|
||||
/** Dimensions in mm */
|
||||
|
||||
/** Expected physical dimensions in mm (domain truth, items.ts) */
|
||||
dimensions: DimensionsMm;
|
||||
|
||||
/** Source file from input_info (for reference) */
|
||||
sourceFile: string;
|
||||
|
||||
/** Frontend asset path (public/models or undefined if not used) */
|
||||
frontendAssetPath?: string;
|
||||
|
||||
/** Loader type: 'stl' = use STLLoader, 'glb' = use GLTFLoader, 'procedural' = fallback primitive */
|
||||
loaderType: 'stl' | 'glb' | 'procedural';
|
||||
|
||||
/** Fallback primitive shape if model fails to load */
|
||||
|
||||
// ---------------- Provenance ----------------
|
||||
/** 'official-stl' = byte-identical archive file; 'official-stl-decimated' = derived from archive STL by reproducible decimation; 'none' = no official model */
|
||||
sourceType: 'official-stl' | 'official-stl-decimated' | 'none';
|
||||
/** Archive the source file came from (repo-relative) */
|
||||
sourceArchive: string | null;
|
||||
/** File name inside the archive */
|
||||
sourceFile: string | null;
|
||||
/** SHA-256 of the source file inside the archive */
|
||||
sourceSha256: string | null;
|
||||
|
||||
// ---------------- Runtime asset ----------------
|
||||
/** Frontend asset path under public/ (null if no real asset) */
|
||||
runtimePath: string | null;
|
||||
/** SHA-256 of the runtime file */
|
||||
runtimeSha256: string | null;
|
||||
runtimeFormat: 'binary-stl' | null;
|
||||
/** Measured triangle count of the runtime file */
|
||||
triangleCount: number | null;
|
||||
/** Runtime file size */
|
||||
fileSizeBytes: number | null;
|
||||
|
||||
// ---------------- Normalization ----------------
|
||||
/** Measured source STL bounding box (mm, source axes) */
|
||||
sourceBoundingBoxMm: SourceBoundingBoxMm | null;
|
||||
/** Expected size along world X/Y/Z AFTER rotation (orientation-aware, mm) */
|
||||
worldExpectedMm: { x: number; y: number; z: number } | null;
|
||||
/** Euler rotation (radians) applied in source mm space before scaling */
|
||||
rotation: [number, number, number];
|
||||
/** Human-readable axis/orientation decision */
|
||||
axisMapping: string;
|
||||
/** Pivot convention after normalization */
|
||||
pivotMode: 'bottom-center';
|
||||
/** Scale convention: source mm → scene meters, uniform */
|
||||
scaleMode: 'uniform-mm-to-m';
|
||||
|
||||
// ---------------- Policy ----------------
|
||||
/** true = real model is the default; false = fallback is the default (honest marking) */
|
||||
defaultRealAsset: boolean;
|
||||
/** Fallback primitive for load failure / low mode */
|
||||
fallbackPrimitive: 'box' | 'cylinder' | 'sphere';
|
||||
|
||||
/** Notes about why model is used/not used */
|
||||
/** Provenance of the runtime geometry */
|
||||
conversionStatus: 'original' | 'decimated-cell-1mm' | 'decimated-cell-2mm' | 'not-applicable';
|
||||
/** Filled by validate-real-models.mjs — never hand-edited */
|
||||
validationStatus: 'pending' | 'pass' | 'fail';
|
||||
/** Preload with the default playlist scene (budget-controlled) */
|
||||
preload: boolean;
|
||||
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
const ARCHIVE_STL = 'input_info/doc-1782987733.zip';
|
||||
|
||||
/**
|
||||
* Model assets manifest.
|
||||
*
|
||||
* Strategy:
|
||||
* - Lightweight STL (< 700 KB): use directly with STLLoader.
|
||||
* - Heavy STL (> 1 MB): use procedural fallback, mark as "too heavy".
|
||||
* - Missing models: use procedural fallback.
|
||||
*
|
||||
* All runtime STLs are official OZON test-set models (or reproducible
|
||||
* decimations of them), units = mm, rendered with uniform 0.001 scale.
|
||||
* No silent substitutions: SKUs without an exact official model are marked
|
||||
* NO_EXACT_OFFICIAL_MODEL and use an honestly labelled procedural fallback.
|
||||
*/
|
||||
export const MODEL_ASSETS: ModelAsset[] = [
|
||||
{
|
||||
@@ -48,155 +97,353 @@ export const MODEL_ASSETS: ModelAsset[] = [
|
||||
displayName: 'Короб 300×200×200',
|
||||
categoryScenario: 'B',
|
||||
dimensions: { width: 300, depth: 200, height: 200 },
|
||||
sourceFile: 'input_info/extracted/Stl/Короб 300х200х200.stl',
|
||||
frontendAssetPath: '/models/box-300.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Короб 300х200х200.stl',
|
||||
sourceSha256: '4ac9046bdef5bad2e7e50062fea30ead9132ebb6bdf23edeceb1f61c276f6e38',
|
||||
runtimePath: '/models/box-300.stl',
|
||||
runtimeSha256: '4ac9046bdef5bad2e7e50062fea30ead9132ebb6bdf23edeceb1f61c276f6e38',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 592,
|
||||
fileSizeBytes: 29684,
|
||||
sourceBoundingBoxMm: { min: [-150.5, 0, -100], max: [150.5, 200.5, 100], size: [301, 200.5, 200] },
|
||||
worldExpectedMm: { x: 300, y: 200, z: 200 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; Y-up, bottom at y=0 in source',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'Lightweight STL (29 KB), used directly.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL, byte-identical to archive (checksum match).',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-002',
|
||||
displayName: 'ЛанчБокс',
|
||||
categoryScenario: 'B',
|
||||
dimensions: { width: 201, depth: 152, height: 62 },
|
||||
sourceFile: 'input_info/extracted/Stl/ЛанчБокс.stl',
|
||||
frontendAssetPath: '/models/lunchbox.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/ЛанчБокс.stl',
|
||||
sourceSha256: '3ad0f231777e7fe1ac55ac55e40074baffc3561c1fe082bb50dd47161f5c5c99',
|
||||
runtimePath: '/models/lunchbox.stl',
|
||||
runtimeSha256: '3ad0f231777e7fe1ac55ac55e40074baffc3561c1fe082bb50dd47161f5c5c99',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 11574,
|
||||
fileSizeBytes: 578784,
|
||||
sourceBoundingBoxMm: { min: [-100.499, -55.8, -76.2], max: [100.496, 6.5, 76.2], size: [200.995, 62.3, 152.4] },
|
||||
worldExpectedMm: { x: 201, y: 62, z: 152 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; source pivot below center — normalized to bottom-center',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'Medium STL (566 KB), acceptable for browser loading.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL. Lid-down container; bottom-center pivot baked at load.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-003',
|
||||
displayName: 'Моющее средство',
|
||||
categoryScenario: 'B',
|
||||
dimensions: { width: 259, depth: 179, height: 278 },
|
||||
sourceFile: 'input_info/extracted/Stl/Моющее средство.STL',
|
||||
frontendAssetPath: undefined,
|
||||
loaderType: 'procedural',
|
||||
sourceType: 'official-stl-decimated',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Моющее средство.STL',
|
||||
sourceSha256: '9a8239c0d079084ff45337f88a7169df75ef010c445a87ad3a5746d11ab154dd',
|
||||
runtimePath: '/models/detergent.stl',
|
||||
runtimeSha256: '1b93c69affe0a7b5fe67973d3c9ca2d7ca7f3daace9b26e386ce7cd89b78da92',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 29458,
|
||||
fileSizeBytes: 1472984,
|
||||
sourceBoundingBoxMm: { min: [28.316, 1.054, 0.019], max: [287.345, 279.218, 179.252], size: [259.029, 278.164, 179.232] },
|
||||
worldExpectedMm: { x: 259, y: 278, z: 179 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; source offset from origin — normalized to bottom-center',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'Heavy STL (3.5 MB), using fallback box to avoid performance impact.',
|
||||
conversionStatus: 'decimated-cell-2mm',
|
||||
validationStatus: 'pending',
|
||||
preload: false,
|
||||
notes: 'Official STL decimated 72,752→29,458 tris (vertex clustering, cell 2mm) to fit the 1.5MB budget; bbox preserved within 0.24mm.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-004',
|
||||
displayName: 'Короб 400×400×300 (негабарит)',
|
||||
categoryScenario: 'C',
|
||||
dimensions: { width: 401, depth: 300, height: 400 },
|
||||
sourceFile: 'input_info/extracted/Stl/Короб 400х400х300.stl',
|
||||
frontendAssetPath: '/models/box-400.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Короб 400х400х300.stl',
|
||||
sourceSha256: '05c4ec56883f085e1dafc9bd43fb87ce9993071122e19983192b72120daa9f68',
|
||||
runtimePath: '/models/box-400.stl',
|
||||
runtimeSha256: '05c4ec56883f085e1dafc9bd43fb87ce9993071122e19983192b72120daa9f68',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 536,
|
||||
fileSizeBytes: 26884,
|
||||
sourceBoundingBoxMm: { min: [-200.5, 0, -200], max: [200.5, 300.5, 200], size: [401, 300.5, 400] },
|
||||
worldExpectedMm: { x: 401, y: 300, z: 400 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; Y-up, bottom at y=0 in source',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'Lightweight STL (27 KB), used directly.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL, byte-identical to archive.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-005',
|
||||
displayName: 'Пуфик',
|
||||
categoryScenario: 'C',
|
||||
dimensions: { width: 489, depth: 264, height: 489 },
|
||||
sourceFile: 'input_info/extracted/Stl/Пуфик.stl',
|
||||
frontendAssetPath: undefined,
|
||||
loaderType: 'procedural',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Пуфик.stl',
|
||||
sourceSha256: '1761f3b2d9e5781a11f09e868d2c14e59d3c03bd5f0c19a006f28648de9f66d1',
|
||||
runtimePath: '/models/pouf.stl',
|
||||
runtimeSha256: '1761f3b2d9e5781a11f09e868d2c14e59d3c03bd5f0c19a006f28648de9f66d1',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 12880,
|
||||
fileSizeBytes: 644084,
|
||||
sourceBoundingBoxMm: { min: [-244.452, -126, -124.452], max: [244.452, 138, 364.452], size: [488.905, 264, 488.905] },
|
||||
worldExpectedMm: { x: 489, y: 264, z: 489 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; source center-offset pivot — normalized to bottom-center',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'cylinder',
|
||||
notes: 'Medium-heavy STL (629 KB), using fallback cylinder for soft bulky item representation.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: false,
|
||||
notes: 'Official STL, round soft pouf. 489mm width exceeds the 450mm gate limit on purpose (C scenario).',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-006',
|
||||
displayName: 'Тарелка',
|
||||
categoryScenario: 'D',
|
||||
dimensions: { width: 210, depth: 209, height: 27 },
|
||||
sourceFile: 'input_info/extracted/Stl/Тарелка.stl',
|
||||
frontendAssetPath: '/models/plate.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Тарелка.stl',
|
||||
sourceSha256: '9bd0fece5fca87951d9c05576f054d0f61da76b56f0ca1387ddcfce816b23f47',
|
||||
runtimePath: '/models/plate.stl',
|
||||
runtimeSha256: '9bd0fece5fca87951d9c05576f054d0f61da76b56f0ca1387ddcfce816b23f47',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 2504,
|
||||
fileSizeBytes: 125284,
|
||||
sourceBoundingBoxMm: { min: [-104.755, -4.56, -104.793], max: [104.755, 21.967, 104.644], size: [209.511, 26.527, 209.437] },
|
||||
worldExpectedMm: { x: 210, y: 27, z: 209 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; Y-up',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'cylinder',
|
||||
notes: 'Lightweight STL (123 KB), used directly. Round plate is visually distinctive.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL, round plate (D scenario).',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-007',
|
||||
displayName: 'Бутылка',
|
||||
categoryScenario: 'D',
|
||||
dimensions: { width: 91, depth: 91, height: 305 },
|
||||
sourceFile: 'input_info/extracted/Stl/Бутылка.stl',
|
||||
frontendAssetPath: '/models/bottle.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Бутылка.stl',
|
||||
sourceSha256: '9a8c64f1c26a2f2e2539b5e283b36ca78158cb8d2f0f66d3201dbcc784417375',
|
||||
runtimePath: '/models/bottle.stl',
|
||||
runtimeSha256: '9a8c64f1c26a2f2e2539b5e283b36ca78158cb8d2f0f66d3201dbcc784417375',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 6522,
|
||||
fileSizeBytes: 326184,
|
||||
sourceBoundingBoxMm: { min: [-45.7, 0, -45.659], max: [45.535, 305, 45.659], size: [91.235, 305, 91.318] },
|
||||
worldExpectedMm: { x: 91, y: 305, z: 91 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width, y→height, z→depth; Y-up, bottom at y=0 in source',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'cylinder',
|
||||
notes: 'Medium STL (319 KB), acceptable. Bottle is visually recognizable.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL, standing bottle (D scenario).',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-008',
|
||||
displayName: 'Цилиндр',
|
||||
categoryScenario: 'D',
|
||||
dimensions: { width: 435, depth: 50, height: 43 },
|
||||
sourceFile: 'input_info/extracted/Stl/Цилиндр.stl',
|
||||
frontendAssetPath: '/models/cylinder.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'official-stl',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Цилиндр.stl',
|
||||
sourceSha256: '7aab451e1fd2154e4a2301e12642d17ccee62fc950dddf7de5e54c89453254e5',
|
||||
runtimePath: '/models/cylinder.stl',
|
||||
runtimeSha256: '7aab451e1fd2154e4a2301e12642d17ccee62fc950dddf7de5e54c89453254e5',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 2152,
|
||||
fileSizeBytes: 107684,
|
||||
sourceBoundingBoxMm: { min: [-83, -19, -25], max: [352, 24, 25], size: [435, 43, 50] },
|
||||
worldExpectedMm: { x: 435, y: 43, z: 50 },
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'x→width (long axis, along travel), y→height, z→depth; source offset — normalized to bottom-center',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'cylinder',
|
||||
notes: 'Lightweight STL (106 KB), used directly.',
|
||||
conversionStatus: 'original',
|
||||
validationStatus: 'pending',
|
||||
preload: false,
|
||||
notes: 'Official STL, long cylinder lying along the belt.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-009',
|
||||
displayName: 'Ручка',
|
||||
categoryScenario: 'C',
|
||||
dimensions: { width: 9, depth: 13, height: 148 },
|
||||
sourceFile: 'input_info/extracted/Stl/Ручка.stl',
|
||||
frontendAssetPath: undefined,
|
||||
loaderType: 'procedural',
|
||||
sourceType: 'official-stl-decimated',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Ручка.stl',
|
||||
sourceSha256: '9c1d3b27b9a5e4f1e65a43ac953f74695bfa0d9550dd97963bfcb7bb39f38720',
|
||||
runtimePath: '/models/pen.stl',
|
||||
runtimeSha256: 'eb4baf50e4910c9be3eaa092da3720fe2d5dcfd0d9a056e4480af6b878561df5',
|
||||
runtimeFormat: 'binary-stl',
|
||||
triangleCount: 4800,
|
||||
fileSizeBytes: 240084,
|
||||
sourceBoundingBoxMm: { min: [36.143, 91.878, 53.556], max: [45.142, 105.031, 202.016], size: [8.999, 13.153, 148.46] },
|
||||
worldExpectedMm: { x: 148, y: 13, z: 9 },
|
||||
rotation: [0, Math.PI / 2, 0],
|
||||
axisMapping: 'DEMO ORIENTATION: lying. Source long axis Z(148) rotated to world X (along travel); world Y=13 (depth), world Z=9 (width). Domain height 148 is the pen LENGTH (standing interpretation in items.ts).',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: true,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'Heavy STL (2.0 MB), using fallback thin box for pen representation.',
|
||||
conversionStatus: 'decimated-cell-1mm',
|
||||
validationStatus: 'pending',
|
||||
preload: true,
|
||||
notes: 'Official STL decimated 40,926→4,800 tris (cell 1mm). Lying demo orientation: a 148mm pen cannot stand stably on a moving belt; documented per Stage 1 §12.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-010',
|
||||
displayName: 'Boundary box 450×320×320',
|
||||
categoryScenario: 'B',
|
||||
dimensions: { width: 450, depth: 320, height: 320 },
|
||||
sourceFile: 'N/A',
|
||||
frontendAssetPath: undefined,
|
||||
loaderType: 'procedural',
|
||||
sourceType: 'none',
|
||||
sourceArchive: null,
|
||||
sourceFile: null,
|
||||
sourceSha256: null,
|
||||
runtimePath: null,
|
||||
runtimeSha256: null,
|
||||
runtimeFormat: null,
|
||||
triangleCount: null,
|
||||
fileSizeBytes: null,
|
||||
sourceBoundingBoxMm: null,
|
||||
worldExpectedMm: null,
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'n/a',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: false,
|
||||
fallbackPrimitive: 'box',
|
||||
notes: 'No STL available for boundary box, using procedural box.',
|
||||
conversionStatus: 'not-applicable',
|
||||
validationStatus: 'pending',
|
||||
preload: false,
|
||||
notes: 'NO_EXACT_OFFICIAL_MODEL — synthetic boundary-limit test case (exactly at 450×320×320 gate limit); no official counterpart exists in the OZON archives. Honest procedural box, dimension-accurate.',
|
||||
},
|
||||
{
|
||||
itemId: 'SKU-011',
|
||||
displayName: 'Oversized round',
|
||||
displayName: 'Oversized round 500×300×300',
|
||||
categoryScenario: 'C',
|
||||
dimensions: { width: 500, depth: 300, height: 300 },
|
||||
sourceFile: 'input_info/extracted/Stl/Цилиндр.stl',
|
||||
frontendAssetPath: '/models/cylinder.stl',
|
||||
loaderType: 'stl',
|
||||
sourceType: 'none',
|
||||
sourceArchive: null,
|
||||
sourceFile: null,
|
||||
sourceSha256: null,
|
||||
runtimePath: null,
|
||||
runtimeSha256: null,
|
||||
runtimeFormat: null,
|
||||
triangleCount: null,
|
||||
fileSizeBytes: null,
|
||||
sourceBoundingBoxMm: null,
|
||||
worldExpectedMm: null,
|
||||
rotation: [0, 0, 0],
|
||||
axisMapping: 'n/a',
|
||||
pivotMode: 'bottom-center',
|
||||
scaleMode: 'uniform-mm-to-m',
|
||||
defaultRealAsset: false,
|
||||
fallbackPrimitive: 'cylinder',
|
||||
notes: 'Uses available round STL (cylinder.stl, 106 KB) for the oversized-round C-priority case.',
|
||||
conversionStatus: 'not-applicable',
|
||||
validationStatus: 'pending',
|
||||
preload: false,
|
||||
notes: 'NO_EXACT_OFFICIAL_MODEL — no 500×300×300 round item in the official set. Previously reused cylinder.stl (silent substitution, removed in Stage 1). Honest procedural cylinder, dimension-accurate.',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get model asset for item ID.
|
||||
* Archive-only official models with no matching SKU in the app scenario set.
|
||||
* Listed for inventory completeness (not loaded at runtime).
|
||||
*/
|
||||
export const ARCHIVE_ONLY_MODELS = [
|
||||
{
|
||||
displayName: 'Мешок',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Мешок.stl',
|
||||
sourceSha256: '74b3118643c0cd06ed639da1513b6db1b8d6d0a38e708cf2f8393d69263cd97b',
|
||||
triangleCount: 21228,
|
||||
fileSizeBytes: 5675429,
|
||||
notes: 'ASCII STL, ~183×175×199mm. No SKU in the app scenario set.',
|
||||
},
|
||||
{
|
||||
displayName: 'Шлем',
|
||||
sourceArchive: ARCHIVE_STL,
|
||||
sourceFile: 'Stl/Шлем.stl',
|
||||
sourceSha256: '660429b26d576771cd02ff275b489dcb134b17bf83b0cab969f589b4d6f6192d',
|
||||
triangleCount: 55159,
|
||||
fileSizeBytes: 2758034,
|
||||
notes: '~280×297×356mm. No SKU in the app scenario set.',
|
||||
},
|
||||
] as const;
|
||||
|
||||
/** Get model asset for item ID. */
|
||||
export function getModelAsset(itemId: string): ModelAsset | undefined {
|
||||
return MODEL_ASSETS.find((asset) => asset.itemId === itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all assets that use real STL models.
|
||||
*/
|
||||
export function getSTLAssets(): ModelAsset[] {
|
||||
return MODEL_ASSETS.filter((asset) => asset.loaderType === 'stl');
|
||||
/** Assets whose default is a real official model. */
|
||||
export function getRealAssets(): ModelAsset[] {
|
||||
return MODEL_ASSETS.filter((asset) => asset.defaultRealAsset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all assets that use procedural fallbacks.
|
||||
*/
|
||||
/** Assets whose default is the honest procedural fallback. */
|
||||
export function getProceduralAssets(): ModelAsset[] {
|
||||
return MODEL_ASSETS.filter((asset) => asset.loaderType === 'procedural');
|
||||
return MODEL_ASSETS.filter((asset) => !asset.defaultRealAsset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Summary stats for manifest.
|
||||
*/
|
||||
/** Assets to preload with the default playlist scene. */
|
||||
export function getPreloadAssets(): ModelAsset[] {
|
||||
return MODEL_ASSETS.filter((asset) => asset.preload && asset.runtimePath);
|
||||
}
|
||||
|
||||
/** Summary stats for manifest. */
|
||||
export function getManifestStats() {
|
||||
const stlCount = getSTLAssets().length;
|
||||
const proceduralCount = getProceduralAssets().length;
|
||||
const real = getRealAssets().length;
|
||||
const procedural = getProceduralAssets().length;
|
||||
return {
|
||||
total: MODEL_ASSETS.length,
|
||||
stl: stlCount,
|
||||
procedural: proceduralCount,
|
||||
stlPercentage: Math.round((stlCount / MODEL_ASSETS.length) * 100),
|
||||
real,
|
||||
procedural,
|
||||
realPercentage: Math.round((real / MODEL_ASSETS.length) * 100),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -23,8 +23,10 @@ describe('performance and production hygiene', () => {
|
||||
|
||||
it('disables heavy demo effects by default', () => {
|
||||
expect(sceneSource).toMatch(/ENABLE_DEMO_EFFECTS\s*=\s*false/);
|
||||
// Shadows controlled by quality presets; demo mode keeps shadows false in qualityMode.ts
|
||||
expect(sceneSource).toMatch(/shadows=\{quality\.shadows\}/);
|
||||
// Shadows stay preset-driven on the default route; stage0 prototype opt-in
|
||||
// is the only override and never turns shadows unconditionally on.
|
||||
expect(sceneSource).toMatch(/const shadowsEnabled = proto \? protoShadows : quality\.shadows/);
|
||||
expect(sceneSource).not.toMatch(/shadows=\{true\}/);
|
||||
});
|
||||
|
||||
it('keeps console.error only in error boundaries', () => {
|
||||
|
||||
@@ -83,8 +83,11 @@ export const MM_PER_STEP = (DRIVE_ROLLER_CIRCUMFERENCE_M * 1000) / STEPS_PER_REV
|
||||
|
||||
// =========================================================
|
||||
// Laser rangefinder (must be above max item)
|
||||
// Stage 1: aligned to official ground truth 1150mm (docs/MEASUREMENT_SYSTEM_REPORT.md,
|
||||
// OZON spec). Previously 1.4m. Measurement math is mount-height invariant
|
||||
// (measuredHeight ≡ itemTop), so this changes no business result.
|
||||
// =========================================================
|
||||
export const LASER_HEIGHT_M = 1.4; // Laser at 1.4m (above max item)
|
||||
export const LASER_HEIGHT_M = 1.15; // Laser at 1.15m (official mount height)
|
||||
export const LASER_POSITION_X = ZONES.CAMERA.x; // Co-located with camera
|
||||
|
||||
// =========================================================
|
||||
|
||||
173
src/domain/playbackAdapter.ts
Normal file
173
src/domain/playbackAdapter.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* playbackAdapter — pure projection of ContinuousPlaybackState (main page
|
||||
* engine) onto SimulationState (shape consumed by the SVG SorterScene).
|
||||
*
|
||||
* Used ONLY for the 2D fallback path (no WebGL / lightweight mobile mode /
|
||||
* context loss). Classification stays live: the same classifyItem() rule
|
||||
* engine produces the category shown in the fallback.
|
||||
*/
|
||||
|
||||
import type { ContinuousPlaybackState, CasePhase } from './continuousPlayback';
|
||||
import type {
|
||||
MachineState,
|
||||
SimulationState,
|
||||
SimulatedItem,
|
||||
Scenario,
|
||||
SystemStatus,
|
||||
Metrics,
|
||||
Category,
|
||||
} from './types';
|
||||
import { classifyItem } from './classifier';
|
||||
import { resolveItem } from '../data/resolveItem';
|
||||
import { SCENARIOS } from '../data/scenarios';
|
||||
|
||||
const DEFAULT_SCENARIO: Scenario = SCENARIOS[0];
|
||||
|
||||
function phaseToMachineState(phase: CasePhase, category: Category | null): MachineState {
|
||||
switch (phase) {
|
||||
case 'spawn':
|
||||
return 'IDLE';
|
||||
case 'move_to_detection':
|
||||
return 'MOVING_TO_CAMERA';
|
||||
case 'detection':
|
||||
case 'measurement':
|
||||
return 'DETECTING';
|
||||
case 'classification':
|
||||
return 'MOVING_TO_GATE';
|
||||
case 'command_sent':
|
||||
return 'WAITING_AT_GATE';
|
||||
case 'routing':
|
||||
return category === 'C' ? 'ROUTE_TO_C' : category === 'D' ? 'ROUTE_TO_D' : 'ROUTE_TO_B';
|
||||
case 'exit':
|
||||
case 'clear_gap':
|
||||
return category === 'C' ? 'ROUTE_TO_C' : category === 'D' ? 'ROUTE_TO_D' : 'ROUTE_TO_B';
|
||||
case 'fault_hold':
|
||||
return 'FAULT';
|
||||
case 'emergency_hold':
|
||||
return 'EMERGENCY_STOP';
|
||||
case 'recover':
|
||||
return 'RETURN_HOME';
|
||||
default:
|
||||
return 'IDLE';
|
||||
}
|
||||
}
|
||||
|
||||
function sensorActive(phase: CasePhase, kind: 'camera' | 'laser' | 'ultrasound'): boolean {
|
||||
switch (kind) {
|
||||
case 'camera':
|
||||
return phase === 'detection' || phase === 'measurement' || phase === 'classification';
|
||||
case 'laser':
|
||||
return phase === 'measurement';
|
||||
case 'ultrasound':
|
||||
return phase === 'classification' || phase === 'command_sent' || phase === 'routing';
|
||||
}
|
||||
}
|
||||
|
||||
function emptyMetrics(): Metrics {
|
||||
return {
|
||||
processedCount: 0,
|
||||
successCount: 0,
|
||||
errorCount: 0,
|
||||
avgCycleTimeMs: 0,
|
||||
throughputItemsPerMin: 0,
|
||||
cvLatencyMs: 0,
|
||||
actuatorLatencyMs: 0,
|
||||
queueLength: 0,
|
||||
queueDelayMs: 0,
|
||||
conveyorSpeedMps: 1,
|
||||
pidTargetSpeedMps: 1,
|
||||
pidActualSpeedMps: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Project continuous playback onto the SVG fallback scene state.
|
||||
* During 'recover' the item is hidden (line is being cleared).
|
||||
* During 'exit'/'clear_gap' the item is shown settled at its receiver
|
||||
* (elapsed pinned past the SorterScene route segment duration).
|
||||
*/
|
||||
export function playbackToSimulation(playback: ContinuousPlaybackState): SimulationState {
|
||||
const item = resolveItem(playback.currentCase.itemId);
|
||||
const classification = playback.classification ?? classifyItem(item);
|
||||
const category = classification.category;
|
||||
const phase = playback.currentPhase;
|
||||
const machineState = phaseToMachineState(phase, category);
|
||||
|
||||
const routingLike = phase === 'routing' || phase === 'exit' || phase === 'clear_gap';
|
||||
const settled = phase === 'exit' || phase === 'clear_gap';
|
||||
const hideItem = phase === 'recover' || playback.status === 'finished';
|
||||
// SorterScene caps route progress at 1200 ms — pin past it once settled.
|
||||
const elapsedInStateMs = settled ? 1300 : playback.phaseElapsedMs;
|
||||
|
||||
const currentItem: SimulatedItem | undefined = hideItem
|
||||
? undefined
|
||||
: {
|
||||
item,
|
||||
startedAtMs: playback.totalElapsedMs - playback.caseElapsedMs,
|
||||
classification,
|
||||
cycleTimeMs: playback.caseElapsedMs,
|
||||
};
|
||||
|
||||
const systemStatus: SystemStatus =
|
||||
machineState === 'FAULT'
|
||||
? 'FAULT'
|
||||
: machineState === 'EMERGENCY_STOP'
|
||||
? 'EMERGENCY_STOP'
|
||||
: playback.status === 'paused'
|
||||
? 'PAUSED'
|
||||
: 'RUNNING';
|
||||
|
||||
return {
|
||||
scenario: DEFAULT_SCENARIO,
|
||||
systemStatus,
|
||||
running: playback.status === 'running',
|
||||
machineState,
|
||||
itemIndex: playback.currentCaseIndex,
|
||||
elapsedInStateMs,
|
||||
simTimeMs: playback.totalElapsedMs,
|
||||
currentItem,
|
||||
metrics: emptyMetrics(),
|
||||
sensors: {
|
||||
camera: {
|
||||
kind: 'camera',
|
||||
label: 'Camera',
|
||||
active: sensorActive(phase, 'camera'),
|
||||
lastValue: '',
|
||||
latencyMs: 0,
|
||||
lastEventTimestampMs: playback.totalElapsedMs,
|
||||
cvLatencyMs: 0,
|
||||
},
|
||||
laser: {
|
||||
kind: 'laser',
|
||||
label: 'Laser',
|
||||
active: sensorActive(phase, 'laser'),
|
||||
lastValue: '',
|
||||
latencyMs: 0,
|
||||
lastEventTimestampMs: playback.totalElapsedMs,
|
||||
},
|
||||
ultrasound: {
|
||||
kind: 'ultrasound',
|
||||
label: 'Ultrasound',
|
||||
active: sensorActive(phase, 'ultrasound'),
|
||||
lastValue: '',
|
||||
latencyMs: 0,
|
||||
lastEventTimestampMs: playback.totalElapsedMs,
|
||||
objectAtGate: phase === 'command_sent',
|
||||
},
|
||||
},
|
||||
gate: { open: routingLike },
|
||||
actuators: {
|
||||
pusherC: routingLike && category === 'C' ? 'extended' : 'idle',
|
||||
pusherD: routingLike && category === 'D' ? 'extended' : 'idle',
|
||||
},
|
||||
pid: {
|
||||
targetSpeedMps: 1,
|
||||
actualSpeedMps: playback.status === 'running' ? playback.speed : 0,
|
||||
pidError: 0,
|
||||
correction: 0,
|
||||
speedHistoryMps: [],
|
||||
},
|
||||
events: playback.events,
|
||||
activeRoute: routingLike ? category : undefined,
|
||||
};
|
||||
}
|
||||
172
src/domain/stage0.ts
Normal file
172
src/domain/stage0.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Stage 0 — premium 3D technical feasibility prototype.
|
||||
* Pure query-string parsing + device classification. No React, no Three.js.
|
||||
*
|
||||
* Prototype mode is strictly opt-in via `?stage0=1` (or `?prototype=cinematic`).
|
||||
* The default route `/` keeps its previous behaviour except for the fixed
|
||||
* mobile fallback (handled in MainPage).
|
||||
*/
|
||||
|
||||
import type { QualityMode } from './qualityMode';
|
||||
import type { CasePhase } from './continuousPlayback';
|
||||
import type { Category } from './types';
|
||||
|
||||
export interface Stage0Config {
|
||||
/** Prototype mode master switch. */
|
||||
enabled: boolean;
|
||||
/** Enable real shadow maps (key light castShadow, PCFSoft 1024). */
|
||||
shadows: boolean;
|
||||
/** Enable the existing CinematicCameraController. */
|
||||
camera: boolean;
|
||||
/** Dark scene background (INDUSTRIAL_PALETTE.backgroundDark). */
|
||||
darkBackground: boolean;
|
||||
/** ACESFilmic tone mapping + sRGB output. */
|
||||
toneMapping: boolean;
|
||||
/** Lazy post-processing spike (Bloom + Vignette + Noise). */
|
||||
post: boolean;
|
||||
/** Adaptive quality via adaptQuality() wired to measured FPS. */
|
||||
adaptive: boolean;
|
||||
/** Fill light intensity multiplier gate. */
|
||||
fill: boolean;
|
||||
/** Rim (back) light gate. */
|
||||
rim: boolean;
|
||||
/** Show the compact technical HUD (hidden with hud=0). */
|
||||
hud: boolean;
|
||||
/** Manual shot override for the cinematic camera (null = phase-driven). */
|
||||
shot: Stage0Shot | null;
|
||||
/** Ambient light intensity in prototype mode. */
|
||||
ambient: number;
|
||||
/** Explicit quality preset override (null = auto device classification). */
|
||||
quality: QualityMode | null;
|
||||
/** Show PerfCollector + PerfOverlay. */
|
||||
perf: boolean;
|
||||
}
|
||||
|
||||
export type Stage0Shot = 'overview' | 'inspection' | 'route-b' | 'route-c' | 'route-d' | 'safety';
|
||||
|
||||
const SHOTS: readonly Stage0Shot[] = ['overview', 'inspection', 'route-b', 'route-c', 'route-d', 'safety'];
|
||||
|
||||
function flag(params: URLSearchParams, name: string, fallback: boolean): boolean {
|
||||
const raw = params.get(name);
|
||||
if (raw === null) return fallback;
|
||||
return raw === '1' || raw === 'true' || raw === 'on';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Stage 0 configuration from a query string.
|
||||
* Defaults (when stage0=1 without extra params): shadows on, camera on,
|
||||
* dark background on, tone mapping on, post OFF, adaptive OFF, fill/rim on,
|
||||
* HUD on, no manual shot, ambient 0.12.
|
||||
*/
|
||||
export function parseStage0Config(search: string): Stage0Config {
|
||||
const params = new URLSearchParams(search);
|
||||
const enabled =
|
||||
params.get('stage0') === '1' || params.get('prototype') === 'cinematic';
|
||||
|
||||
const shotRaw = params.get('shot');
|
||||
const shot = SHOTS.includes(shotRaw as Stage0Shot) ? (shotRaw as Stage0Shot) : null;
|
||||
|
||||
const ambientRaw = Number(params.get('ambient'));
|
||||
|
||||
const qualityRaw = params.get('quality');
|
||||
const quality: QualityMode | null =
|
||||
qualityRaw === 'low' || qualityRaw === 'medium' || qualityRaw === 'high' || qualityRaw === 'demo'
|
||||
? qualityRaw
|
||||
: null;
|
||||
|
||||
return {
|
||||
enabled,
|
||||
shadows: flag(params, 'shadows', true),
|
||||
camera: flag(params, 'camera', true),
|
||||
darkBackground: params.get('bg') !== 'light',
|
||||
toneMapping: flag(params, 'tone', true),
|
||||
post: flag(params, 'post', false),
|
||||
adaptive: flag(params, 'adaptive', false),
|
||||
fill: flag(params, 'fill', true),
|
||||
rim: flag(params, 'rim', true),
|
||||
hud: flag(params, 'hud', true),
|
||||
shot,
|
||||
ambient: Number.isFinite(ambientRaw) && ambientRaw > 0 && ambientRaw <= 1 ? ambientRaw : 0.12,
|
||||
quality,
|
||||
perf: flag(params, 'perf', false),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a manual shot id to an equivalent (phase, category) pair understood by
|
||||
* the existing getCameraConfig() — zero changes to cinematicCamera.ts.
|
||||
*/
|
||||
export function shotToPhaseCategory(shot: Stage0Shot): { phase: CasePhase; category: Category | null } {
|
||||
switch (shot) {
|
||||
case 'overview':
|
||||
return { phase: 'move_to_detection', category: null }; // -> 'overview' mode
|
||||
case 'inspection':
|
||||
return { phase: 'detection', category: null }; // -> 'inspectionTop'
|
||||
case 'route-b':
|
||||
return { phase: 'routing', category: 'B' };
|
||||
case 'route-c':
|
||||
return { phase: 'routing', category: 'C' };
|
||||
case 'route-d':
|
||||
return { phase: 'routing', category: 'D' };
|
||||
case 'safety':
|
||||
return { phase: 'fault_hold', category: null }; // -> 'routingWide'
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeviceSignals {
|
||||
hardwareConcurrency: number | null;
|
||||
deviceMemoryGb: number | null;
|
||||
devicePixelRatio: number;
|
||||
viewportWidth: number;
|
||||
renderer: string;
|
||||
softwareRenderer: boolean;
|
||||
userAgent: string;
|
||||
}
|
||||
|
||||
/** Collect best-effort device signals for quality selection (no fingerprinting). */
|
||||
export function collectDeviceSignals(renderer = 'unknown'): DeviceSignals {
|
||||
if (typeof navigator === 'undefined' || typeof window === 'undefined') {
|
||||
return {
|
||||
hardwareConcurrency: null,
|
||||
deviceMemoryGb: null,
|
||||
devicePixelRatio: 1,
|
||||
viewportWidth: 1200,
|
||||
renderer,
|
||||
softwareRenderer: false,
|
||||
userAgent: '',
|
||||
};
|
||||
}
|
||||
const nav = navigator as Navigator & { deviceMemory?: number };
|
||||
return {
|
||||
hardwareConcurrency: typeof navigator.hardwareConcurrency === 'number' ? navigator.hardwareConcurrency : null,
|
||||
deviceMemoryGb: typeof nav.deviceMemory === 'number' ? nav.deviceMemory : null,
|
||||
devicePixelRatio: window.devicePixelRatio || 1,
|
||||
viewportWidth: window.innerWidth,
|
||||
renderer,
|
||||
softwareRenderer: /swiftshader|llvmpipe|softpipe|software|mesa offscreen|microsoft basic render/i.test(renderer),
|
||||
userAgent: navigator.userAgent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the initial quality tier for prototype mode using device signals
|
||||
* instead of viewport width alone. Falls back to width when signals missing.
|
||||
*/
|
||||
export function choosePrototypeQuality(width: number, signals: DeviceSignals): QualityMode {
|
||||
if (signals.softwareRenderer) return 'low';
|
||||
const cores = signals.hardwareConcurrency ?? 4;
|
||||
const memory = signals.deviceMemoryGb ?? 4;
|
||||
|
||||
const weak = cores <= 4 || memory <= 4;
|
||||
const strong = cores >= 8 && memory >= 8;
|
||||
|
||||
if (width < 768) return 'low';
|
||||
if (weak) return width < 1100 ? 'low' : 'medium';
|
||||
if (width < 1100) return 'medium';
|
||||
return strong ? 'demo' : 'medium';
|
||||
}
|
||||
|
||||
/** Log a single adaptive-quality transition (reason tracing for Stage 0). */
|
||||
export function describeAdaptiveSwitch(from: QualityMode, to: QualityMode, fps: number): string {
|
||||
return `[stage0] adaptive quality ${from} -> ${to} (avg fps ${fps.toFixed(1)})`;
|
||||
}
|
||||
31
src/domain/stage1.ts
Normal file
31
src/domain/stage1.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Stage 1 — real-models verification mode (query-param config).
|
||||
*
|
||||
* ?stage1=1&verify=real-models → verification overlays for the current SKU
|
||||
* ?stage1=1&verify=real-models&sku=SKU-007 → pin verification to a specific SKU
|
||||
*
|
||||
* Read-only debug instrumentation: never touches business state or results.
|
||||
* Mirrors the Stage 0 prototype-mode pattern (stage0.ts).
|
||||
*/
|
||||
|
||||
export interface Stage1Config {
|
||||
/** Master switch for Stage 1 tooling */
|
||||
enabled: boolean;
|
||||
/** Verification overlay mode (null = off) */
|
||||
verify: 'real-models' | null;
|
||||
/** Pinned SKU (null = follow the currently playing case) */
|
||||
sku: string | null;
|
||||
}
|
||||
|
||||
const SKU_PATTERN = /^SKU-\d{3}$/;
|
||||
|
||||
export function parseStage1Config(search: string): Stage1Config {
|
||||
const params = new URLSearchParams(search);
|
||||
const enabled = params.get('stage1') === '1';
|
||||
const verify = params.get('verify') === 'real-models' ? 'real-models' : null;
|
||||
const skuRaw = params.get('sku');
|
||||
const sku = skuRaw && SKU_PATTERN.test(skuRaw) ? skuRaw : null;
|
||||
return { enabled, verify, sku };
|
||||
}
|
||||
|
||||
export const STAGE1_DISABLED: Stage1Config = { enabled: false, verify: null, sku: null };
|
||||
60
src/domain/stage1Contacts.test.ts
Normal file
60
src/domain/stage1Contacts.test.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Stage 1 — physical contact contracts.
|
||||
*
|
||||
* Verifies the bottom-contact guarantee for real models:
|
||||
* - continuous scene: pose center = surfaceY + h/2, mesh bottom-center pivot
|
||||
* offset −h/2 → model bottom touches the surface exactly (epsilon 0).
|
||||
* - details scene: itemPosition3D y == beltY (bottom-contact semantics,
|
||||
* no 12cm float, no 2.5x visual multiplier).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getPhysicalItemPose } from './physicalItemMotion';
|
||||
import { BELT_TOP_Y, CAGE_FLOOR_Y } from './physicalLayout';
|
||||
import { itemPosition3D, TWIN_LAYOUT } from '../components/ThreeD/itemMotion';
|
||||
import { ITEMS } from '../data/items';
|
||||
import type { SimulationState } from './types';
|
||||
|
||||
describe('Stage 1 belt/cage contact contracts', () => {
|
||||
const box = ITEMS.find((i) => i.id === 'SKU-001')!;
|
||||
|
||||
it('item center on main belt is surfaceY + h/2 (bottom touches with bottom-center pivot)', () => {
|
||||
const pose = getPhysicalItemPose({
|
||||
caseId: 'case-001',
|
||||
dimensionsMm: box.dimensionsMm,
|
||||
targetCategory: 'B',
|
||||
elapsedMs: 500, // feed phase
|
||||
});
|
||||
const itemHeightM = box.dimensionsMm.height / 1000;
|
||||
expect(pose.surface).toBe('main_belt');
|
||||
expect(pose.position[1]).toBeCloseTo(BELT_TOP_Y + itemHeightM / 2, 6);
|
||||
// bottom-center pivot at −h/2 → bottom at BELT_TOP_Y (contact epsilon = 0)
|
||||
expect(pose.position[1] - itemHeightM / 2).toBeCloseTo(BELT_TOP_Y, 6);
|
||||
});
|
||||
|
||||
it('settled item in C cage rests on the cage floor, not through it', () => {
|
||||
const pose = getPhysicalItemPose({
|
||||
caseId: 'case-004',
|
||||
slotIndex: 0,
|
||||
dimensionsMm: box.dimensionsMm,
|
||||
targetCategory: 'C',
|
||||
elapsedMs: Number.MAX_SAFE_INTEGER / 4, // settled
|
||||
});
|
||||
const itemHeightM = box.dimensionsMm.height / 1000;
|
||||
expect(pose.surface).toBe('c_cage_floor');
|
||||
expect(pose.position[1] - itemHeightM / 2).toBeCloseTo(CAGE_FLOOR_Y, 6);
|
||||
});
|
||||
|
||||
it('details scene uses bottom-contact belt height (no visual float)', () => {
|
||||
const sim = { machineState: 'IDLE', elapsedInStateMs: 0 } as SimulationState;
|
||||
const [, y] = itemPosition3D(sim);
|
||||
expect(y).toBeCloseTo(TWIN_LAYOUT.beltY, 6);
|
||||
expect(y).toBeCloseTo(BELT_TOP_Y, 6);
|
||||
});
|
||||
|
||||
it('details scene has no VISUAL_SCALE_MULTIPLIER distortion (true physical scale)', async () => {
|
||||
// Static guard: the multiplier must not be reintroduced.
|
||||
const source = await import('../components/ThreeD/Item3D.tsx?raw');
|
||||
expect(source.default).not.toMatch(/VISUAL_SCALE_MULTIPLIER\s*=/);
|
||||
expect(source.default).toMatch(/getRenderedItemDimensions/);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lazy, Suspense, useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import { lazy, Suspense, useEffect, useRef, useState, useMemo, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import ThreeErrorBoundary from '../components/ThreeD/ThreeErrorBoundary';
|
||||
import { prefer3DByDefault, useWebGLSupport } from '../components/ThreeD/useWebGL';
|
||||
@@ -8,6 +8,10 @@ import { getCaseProgress, getCurrentPhaseConfig, isFaultActive } from '../domain
|
||||
import { getMeasurementData, shouldShowMeasurement } from '../domain/measurementSystem';
|
||||
import { getViewportType, type ViewportType } from '../domain/cinematicCamera';
|
||||
import { detectQualityMode } from '../domain/qualityMode';
|
||||
import { parseStage0Config, collectDeviceSignals, choosePrototypeQuality } from '../domain/stage0';
|
||||
import { parseStage1Config } from '../domain/stage1';
|
||||
import { playbackToSimulation } from '../domain/playbackAdapter';
|
||||
import SorterScene from '../components/SorterScene';
|
||||
import { resolveItem } from '../data/resolveItem';
|
||||
import BuildIdentityBadge from '../components/BuildIdentityBadge';
|
||||
import CVInspectionOverlay from '../components/CVInspectionOverlay';
|
||||
@@ -107,14 +111,70 @@ export default function MainPage({
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [playback.status, onPlay, onPause, onStop, onSeekNext, onSeekPrev, onSeekCase]);
|
||||
|
||||
const show3D = prefer3DByDefault(width, webgl && !contextLost);
|
||||
// Stage 0 prototype config (inert on the default route unless ?stage0=1)
|
||||
const stage0 = useMemo(
|
||||
() => parseStage0Config(typeof window === 'undefined' ? '' : window.location.search),
|
||||
[],
|
||||
);
|
||||
|
||||
// Stage 1 real-models verification config (inert unless ?stage1=1&verify=real-models)
|
||||
const stage1 = useMemo(
|
||||
() => parseStage1Config(typeof window === 'undefined' ? '' : window.location.search),
|
||||
[],
|
||||
);
|
||||
|
||||
// NOTE: contextLost must NOT flip show3D — the canvas stays mounted (hidden)
|
||||
// during the recovery window so `webglcontextrestored` can actually arrive.
|
||||
// Default route: 3D only on >= 640px with WebGL (unchanged heuristic).
|
||||
// Prototype mode: 3D forced on any width so mobile GPU profiles can be measured.
|
||||
const show3D = stage0.enabled ? webgl : prefer3DByDefault(width, webgl);
|
||||
|
||||
// WebGL context recovery: on loss the canvas stays mounted (hidden) so a
|
||||
// real `webglcontextrestored` can arrive; exactly one safe retry is allowed,
|
||||
// after that the canvas is dropped and the SVG fallback stays forever.
|
||||
const [contextDead, setContextDead] = useState(false);
|
||||
const restoreUsedRef = useRef(false);
|
||||
|
||||
const handleContextLost = useCallback(() => {
|
||||
if (restoreUsedRef.current) {
|
||||
setContextDead(true);
|
||||
}
|
||||
setContextLost(true);
|
||||
}, []);
|
||||
|
||||
const handleContextRestored = useCallback(() => {
|
||||
if (restoreUsedRef.current) return;
|
||||
restoreUsedRef.current = true;
|
||||
setContextLost(false);
|
||||
}, []);
|
||||
|
||||
// If the context does not recover in time, unmount the dead canvas.
|
||||
useEffect(() => {
|
||||
if (!contextLost || contextDead) return;
|
||||
const timer = window.setTimeout(() => setContextDead(true), 12_000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [contextLost, contextDead]);
|
||||
|
||||
const render3D = show3D && !contextDead;
|
||||
const fallbackVisible = !render3D || contextLost;
|
||||
|
||||
// Why the 2D fallback is on screen — drives the honest badge text.
|
||||
const fallbackReason: 'webgl' | 'context' | 'mobile' =
|
||||
!webgl ? 'webgl' : contextLost || contextDead ? 'context' : 'mobile';
|
||||
|
||||
const fallbackSimulation = useMemo(() => playbackToSimulation(playback), [playback]);
|
||||
|
||||
const qualityOverride = useMemo(() => {
|
||||
if (stage0.quality) return stage0.quality;
|
||||
if (typeof window === 'undefined') return undefined;
|
||||
const q = new URLSearchParams(window.location.search).get('quality');
|
||||
if (q === 'low' || q === 'medium' || q === 'high' || q === 'demo') return q;
|
||||
return undefined;
|
||||
}, []);
|
||||
const qualityMode = qualityOverride ?? detectQualityMode(width);
|
||||
}, [stage0]);
|
||||
const deviceSignals = useMemo(() => collectDeviceSignals(), []);
|
||||
const qualityMode =
|
||||
qualityOverride ??
|
||||
(stage0.enabled ? choosePrototypeQuality(width, deviceSignals) : detectQualityMode(width));
|
||||
const simplified = width < 900 || qualityMode === 'low';
|
||||
const viewportType: ViewportType = getViewportType(width);
|
||||
|
||||
@@ -149,30 +209,45 @@ export default function MainPage({
|
||||
return (
|
||||
<div className={`main-page ${presentationMode ? 'presentation-mode' : ''} ${faultActive ? 'fault-active' : ''}`}>
|
||||
<div className="main-demo-viewport">
|
||||
{show3D ? (
|
||||
<ThreeErrorBoundary
|
||||
onError={(error) => {
|
||||
console.error('3D Canvas failed:', error);
|
||||
setContextLost(true);
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={<div className="three-loading">Loading 3D...</div>}>
|
||||
<SorterDigitalTwinContinuous
|
||||
playback={playback}
|
||||
simplified={simplified}
|
||||
onContextLost={() => setContextLost(true)}
|
||||
autoCameraEnabled={autoCameraEnabled}
|
||||
viewportType={viewportType}
|
||||
qualityMode={qualityMode}
|
||||
/>
|
||||
</Suspense>
|
||||
</ThreeErrorBoundary>
|
||||
) : (
|
||||
<div className="main-fallback">
|
||||
<div className="fallback-content">
|
||||
<h2>3D Demo</h2>
|
||||
<p>WebGL not available. Please use a modern browser.</p>
|
||||
<Link to="/details" className="btn-primary">View Details Page</Link>
|
||||
{render3D && (
|
||||
<div className="canvas-holder" style={contextLost ? { visibility: 'hidden', position: 'absolute', inset: 0 } : undefined}>
|
||||
<ThreeErrorBoundary
|
||||
onError={(error) => {
|
||||
console.error('3D Canvas failed:', error);
|
||||
handleContextLost();
|
||||
}}
|
||||
onUse2D={handleContextLost}
|
||||
>
|
||||
<Suspense fallback={<div className="three-loading">Loading 3D...</div>}>
|
||||
<SorterDigitalTwinContinuous
|
||||
playback={playback}
|
||||
simplified={simplified}
|
||||
onContextLost={handleContextLost}
|
||||
onContextRestored={handleContextRestored}
|
||||
autoCameraEnabled={autoCameraEnabled}
|
||||
viewportType={viewportType}
|
||||
qualityMode={qualityMode}
|
||||
stage0={stage0}
|
||||
stage1={stage1}
|
||||
/>
|
||||
</Suspense>
|
||||
</ThreeErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
{fallbackVisible && (
|
||||
<div className="main-fallback" data-testid="main-svg-fallback">
|
||||
<div className={`fallback-badge fallback-badge-${fallbackReason}`} data-testid="fallback-reason">
|
||||
{fallbackReason === 'webgl'
|
||||
? '3D недоступно в этом браузере — показана облегчённая версия'
|
||||
: fallbackReason === 'context'
|
||||
? '3D-сцена прервана — показана облегчённая версия'
|
||||
: 'Облегчённый режим — мобильное устройство'}
|
||||
</div>
|
||||
<Link to="/details" className="fallback-details-link" data-testid="fallback-details-link">
|
||||
Подробнее на странице Details →
|
||||
</Link>
|
||||
<div className="fallback-scene">
|
||||
<SorterScene simulation={fallbackSimulation} variant={width < 640 ? 'simple' : 'full'} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -182,7 +257,7 @@ export default function MainPage({
|
||||
<CVInspectionOverlay data={measurementData} visible={showMeasurement} />
|
||||
)}
|
||||
|
||||
{!presentationMode && (
|
||||
{!presentationMode && (!stage0.enabled || stage0.hud) && (
|
||||
<div className="main-hud" data-testid="demo-hud">
|
||||
<div className="hud-row">
|
||||
<span className="hud-label">Item</span>
|
||||
@@ -357,7 +432,7 @@ export default function MainPage({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{show3D && !presentationMode && (
|
||||
{render3D && !contextLost && !presentationMode && (
|
||||
<button
|
||||
type="button"
|
||||
className="auto-camera-toggle"
|
||||
|
||||
@@ -2323,6 +2323,12 @@ button:disabled {
|
||||
|
||||
/* Mobile responsive for main page */
|
||||
@media (max-width: 639px) {
|
||||
/* Full-width HUD (~3 wrapped rows, top:12) overlays the top band;
|
||||
keep fallback interactive content (badge, details link) below it. */
|
||||
.main-fallback {
|
||||
padding-top: 210px;
|
||||
}
|
||||
|
||||
.main-hud {
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
@@ -2466,24 +2472,62 @@ button:disabled {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
justify-content: flex-start;
|
||||
background: #07111d;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.fallback-badge {
|
||||
flex: 0 0 auto;
|
||||
align-self: flex-start;
|
||||
margin: 10px 0 0 12px;
|
||||
padding: 6px 14px;
|
||||
border-radius: 999px;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: #dbe7f3;
|
||||
background: rgba(36, 72, 99, 0.55);
|
||||
border: 1px solid rgba(96, 165, 250, 0.35);
|
||||
}
|
||||
|
||||
.fallback-badge-context {
|
||||
background: rgba(120, 53, 15, 0.55);
|
||||
border-color: rgba(245, 158, 11, 0.45);
|
||||
}
|
||||
|
||||
.fallback-scene {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.fallback-content {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
.fallback-scene .scene-wrap {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.fallback-content h2 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 1.5rem;
|
||||
.fallback-scene .sorter-svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.fallback-content p {
|
||||
margin: 0 0 24px;
|
||||
color: var(--muted);
|
||||
.fallback-details-link {
|
||||
flex: 0 0 auto;
|
||||
align-self: flex-start;
|
||||
margin: 8px 0 4px 12px;
|
||||
font-size: 0.85rem;
|
||||
color: #93c5fd;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.fallback-details-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Status colors for continuous playback */
|
||||
|
||||
Reference in New Issue
Block a user