@umituz/web-virtual 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ export interface WorldEngineOptions {
13
13
  onSelectEntity?: (event: EntitySelectedEvent) => void
14
14
  onHoverEntity?: (entity: WorldEntity | null) => void
15
15
  onFpsUpdate?: (fps: number) => void
16
+ onContextLost?: () => void
16
17
  }
17
18
 
18
19
  export class WorldEngine {
@@ -30,6 +31,7 @@ export class WorldEngine {
30
31
 
31
32
  private isDisposed = false
32
33
  private animationFrameId: number | null = null
34
+ private visibilityHandler: (() => void) | null = null
33
35
  private clock = new THREE.Clock()
34
36
  private hoveredEntityId: string | null = null
35
37
 
@@ -64,9 +66,41 @@ export class WorldEngine {
64
66
  this.projector = new DirectDOMProjector()
65
67
 
66
68
  this.initEventListeners(canvas)
69
+ this.initContextLossHandling(canvas)
67
70
  this.startLoop()
68
71
  }
69
72
 
73
+ /**
74
+ * Hot-sync the world data (entities, theme, zones) without rebuilding the scene.
75
+ * Raycast lookups, label projection and camera focus immediately use the new data.
76
+ */
77
+ public updateWorld(world: WorldDefinition): void {
78
+ this.options.world = world
79
+ }
80
+
81
+ /** Pause rendering while the tab is hidden to save battery/CPU. */
82
+ private initContextLossHandling(canvas: HTMLCanvasElement): void {
83
+ canvas.addEventListener(
84
+ 'webglcontextlost',
85
+ (e) => {
86
+ e.preventDefault()
87
+ this.stopLoop()
88
+ if (this.options.onContextLost) this.options.onContextLost()
89
+ },
90
+ false,
91
+ )
92
+ }
93
+
94
+ /** Resume the render loop after a pause (tab visible again or context restored). */
95
+ public resumeLoop(): void {
96
+ if (this.isDisposed) return
97
+ if (this.animationFrameId === null) {
98
+ // Flush the accumulated delta so animations do not jump after the pause
99
+ this.clock.getDelta()
100
+ this.startLoop()
101
+ }
102
+ }
103
+
70
104
  private initEventListeners(canvas: HTMLCanvasElement): void {
71
105
  let pointerDownX = 0
72
106
  let pointerDownY = 0
@@ -171,6 +205,19 @@ export class WorldEngine {
171
205
  }
172
206
 
173
207
  private startLoop(): void {
208
+ // Pause the render loop while the document is hidden (saves battery/CPU)
209
+ if (this.visibilityHandler === null) {
210
+ this.visibilityHandler = () => {
211
+ if (this.isDisposed) return
212
+ if (document.hidden) {
213
+ this.stopLoop()
214
+ } else {
215
+ this.resumeLoop()
216
+ }
217
+ }
218
+ document.addEventListener('visibilitychange', this.visibilityHandler)
219
+ }
220
+
174
221
  const loop = () => {
175
222
  if (this.isDisposed) return
176
223
 
@@ -212,10 +259,19 @@ export class WorldEngine {
212
259
  this.animationFrameId = requestAnimationFrame(loop)
213
260
  }
214
261
 
215
- public dispose(): void {
216
- this.isDisposed = true
262
+ private stopLoop(): void {
217
263
  if (this.animationFrameId !== null) {
218
264
  cancelAnimationFrame(this.animationFrameId)
265
+ this.animationFrameId = null
266
+ }
267
+ }
268
+
269
+ public dispose(): void {
270
+ this.isDisposed = true
271
+ this.stopLoop()
272
+ if (this.visibilityHandler) {
273
+ document.removeEventListener('visibilitychange', this.visibilityHandler)
274
+ this.visibilityHandler = null
219
275
  }
220
276
 
221
277
  this.unbindEvents()
@@ -0,0 +1,75 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import * as THREE from 'three'
3
+ import { createStylizedAvatar } from './AvatarBuilder'
4
+ import { MaterialPalette } from '../../engine/materials'
5
+ import type { WorldEntity } from '../../core/types'
6
+
7
+ // GLB assets cannot be fetched in the Node test environment — resolve to null so
8
+ // the placeholder geometry path is exercised instead.
9
+ vi.mock('../../engine/modelLoader', () => ({
10
+ ModelLoader: {
11
+ getInstance: () => ({
12
+ load: async () => null,
13
+ }),
14
+ },
15
+ }))
16
+
17
+ const baseEntity: WorldEntity = {
18
+ id: 'test-1',
19
+ type: 'person',
20
+ name: 'Test worker',
21
+ position: [0, 0, 0],
22
+ status: 'idle',
23
+ pinNumber: 1,
24
+ }
25
+
26
+ function findStatusHalo(group: THREE.Group): THREE.Mesh {
27
+ let halo: THREE.Mesh | null = null
28
+ group.traverse((obj) => {
29
+ if (!halo && obj instanceof THREE.Mesh && (obj.geometry as THREE.BufferGeometry).type === 'RingGeometry') {
30
+ halo = obj
31
+ }
32
+ })
33
+ if (!halo) throw new Error('Status halo mesh not found on avatar')
34
+ return halo
35
+ }
36
+
37
+ describe('createStylizedAvatar hot-sync', () => {
38
+ it('updates the status halo color without rebuilding the avatar', () => {
39
+ const materials = new MaterialPalette()
40
+ const { group, update } = createStylizedAvatar(baseEntity, materials)
41
+
42
+ const halo = findStatusHalo(group)
43
+ const before = halo.material as THREE.MeshBasicMaterial
44
+ expect(before.color.getHex()).toBe(0x22c55e) // idle = green
45
+
46
+ update({ ...baseEntity, status: 'running' })
47
+ const after = halo.material as THREE.MeshBasicMaterial
48
+ expect(after.color.getHex()).toBe(0x3b82f6) // running = blue
49
+
50
+ update({ ...baseEntity, status: 'awaiting_approval' })
51
+ const awaiting = halo.material as THREE.MeshBasicMaterial
52
+ expect(awaiting.color.getHex()).toBe(0xf59e0b) // awaiting = amber
53
+ })
54
+
55
+ it('updates the avatar transform in place', () => {
56
+ const materials = new MaterialPalette()
57
+ const { group, update } = createStylizedAvatar(baseEntity, materials)
58
+
59
+ update({ ...baseEntity, position: [5, 0, -3], rotation: [0, Math.PI / 2, 0] })
60
+
61
+ expect(group.position.x).toBe(5)
62
+ expect(group.position.z).toBe(-3)
63
+ expect(group.rotation.y).toBeCloseTo(Math.PI / 2)
64
+ })
65
+
66
+ it('is a no-op material-wise when the status does not change', () => {
67
+ const materials = new MaterialPalette()
68
+ const { group, update } = createStylizedAvatar(baseEntity, materials)
69
+
70
+ const halo = findStatusHalo(group)
71
+ const materialBefore = halo.material
72
+ update({ ...baseEntity, status: 'idle' })
73
+ expect(halo.material).toBe(materialBefore)
74
+ })
75
+ })
@@ -6,6 +6,8 @@ import { ModelLoader } from '../../engine/modelLoader'
6
6
  export interface CreatedAvatar {
7
7
  group: THREE.Group
8
8
  animate: (delta: number, elapsed: number) => void
9
+ /** Hot-sync entity data (status / position / rotation) without rebuilding the avatar. */
10
+ update: (entity: WorldEntity) => void
9
11
  }
10
12
 
11
13
  export function createStylizedAvatar(
@@ -158,8 +160,10 @@ export function createStylizedAvatar(
158
160
 
159
161
  // 6. Realistic Procedural Animation Function
160
162
  const baseTorsoY = 0.6
161
- const isWorking = entity.status === 'running' || entity.status === 'working'
162
- const isAwaiting = entity.status === 'awaiting_approval'
163
+ // Mutable status flags so hot-synced updates can change animation behaviour live
164
+ let isWorking = entity.status === 'running' || entity.status === 'working'
165
+ let isAwaiting = entity.status === 'awaiting_approval'
166
+ let currentStatus = entity.status || 'idle'
163
167
  const breathFreq = 1.3 + (seed % 0.4)
164
168
  const glanceFreq = 0.22 + ((seed * 3) % 0.15)
165
169
 
@@ -227,5 +231,21 @@ export function createStylizedAvatar(
227
231
  group.rotation.set(entity.rotation[0], entity.rotation[1], entity.rotation[2])
228
232
  }
229
233
 
230
- return { group, animate }
234
+ // 7. Hot-sync: apply live entity data changes without rebuilding the avatar
235
+ const update = (next: WorldEntity) => {
236
+ const nextStatus = next.status || 'idle'
237
+ if (nextStatus !== currentStatus) {
238
+ currentStatus = nextStatus
239
+ isWorking = nextStatus === 'running' || nextStatus === 'working'
240
+ isAwaiting = nextStatus === 'awaiting_approval'
241
+ statusHalo.material = materials.getStatusGlow(nextStatus)
242
+ }
243
+
244
+ group.position.set(next.position[0], next.position[1], next.position[2])
245
+ if (next.rotation) {
246
+ group.rotation.set(next.rotation[0], next.rotation[1], next.rotation[2])
247
+ }
248
+ }
249
+
250
+ return { group, animate, update }
231
251
  }
@@ -5,23 +5,23 @@ import { MaterialPalette } from '../engine/materials'
5
5
  export const DEFAULT_FACTORY_ZONES: WorldZone[] = [
6
6
  {
7
7
  id: 'assembly_line',
8
- name: 'Robotik Montaj Hattı',
8
+ name: 'Robotic Assembly Line',
9
9
  color: '#0284c7',
10
- description: 'Yüksek hızlı robotik montaj ve parça birleştirme bandı.',
10
+ description: 'High-speed robotic assembly and part joining line.',
11
11
  cameraFocus: [-6, 1.2, 0],
12
12
  },
13
13
  {
14
14
  id: 'quality_control',
15
- name: 'Kalite Kontrol & Optik Test',
15
+ name: 'Quality Control & Optical Testing',
16
16
  color: '#10b981',
17
- description: 'Ürün tarama, hata tespiti ve paket onay istasyonu.',
17
+ description: 'Product scanning, defect detection and packaging approval station.',
18
18
  cameraFocus: [6, 1.0, -4],
19
19
  },
20
20
  {
21
21
  id: 'warehouse_racks',
22
- name: 'Lojistik & Raf Deposu',
22
+ name: 'Logistics & Rack Warehouse',
23
23
  color: '#f59e0b',
24
- description: 'Otomatik paletleme ve dikey depolama alanı.',
24
+ description: 'Automated palletizing and vertical storage area.',
25
25
  cameraFocus: [6, 2.0, 5],
26
26
  },
27
27
  ]
@@ -30,9 +30,9 @@ export const DEFAULT_FACTORY_ENTITIES: WorldEntity[] = [
30
30
  {
31
31
  id: 'factory-op-1',
32
32
  type: 'person',
33
- name: 'Serkan — Hat Şefi',
34
- role: 'Üretim Akış Gözetmeni',
35
- department: 'İmalat',
33
+ name: 'Serkan — Line Chief',
34
+ role: 'Production flow supervisor',
35
+ department: 'Manufacturing',
36
36
  zoneId: 'assembly_line',
37
37
  status: 'working',
38
38
  pinNumber: 1,
@@ -42,9 +42,9 @@ export const DEFAULT_FACTORY_ENTITIES: WorldEntity[] = [
42
42
  {
43
43
  id: 'robot-arm-1',
44
44
  type: 'equipment',
45
- name: 'Robot Kolu RX-4',
46
- role: 'Hassas Kaynak & Montaj',
47
- department: 'Robotik',
45
+ name: 'Robotic Arm RX-4',
46
+ role: 'Precision welding & assembly',
47
+ department: 'Robotics',
48
48
  zoneId: 'assembly_line',
49
49
  status: 'running',
50
50
  pinNumber: 2,
@@ -53,9 +53,9 @@ export const DEFAULT_FACTORY_ENTITIES: WorldEntity[] = [
53
53
  {
54
54
  id: 'factory-inspector',
55
55
  type: 'person',
56
- name: 'Ebru — Kalite Mühendisi',
57
- role: 'Tolerans Doğrulama',
58
- department: 'Kalite',
56
+ name: 'Ebru — Quality Engineer',
57
+ role: 'Tolerance verification',
58
+ department: 'Quality',
59
59
  zoneId: 'quality_control',
60
60
  status: 'idle',
61
61
  pinNumber: 3,
@@ -5,23 +5,23 @@ import { MaterialPalette } from '../engine/materials'
5
5
  export const DEFAULT_FARM_ZONES: WorldZone[] = [
6
6
  {
7
7
  id: 'greenhouse',
8
- name: 'Topraksız Tarım & Sera',
8
+ name: 'Hydroponics & Greenhouse',
9
9
  color: '#22c55e',
10
- description: 'Otomatik sulama ve iklim kontrollü sera alanı.',
10
+ description: 'Automated irrigation and climate-controlled greenhouse area.',
11
11
  cameraFocus: [-8, 1, -5],
12
12
  },
13
13
  {
14
14
  id: 'crop_fields',
15
- name: 'Açık Tarım Tarlaları',
15
+ name: 'Open Crop Fields',
16
16
  color: '#84cc16',
17
- description: 'Mevsimlik organik tarım ekim parseli.',
17
+ description: 'Seasonal organic crop plots.',
18
18
  cameraFocus: [6, 0.5, -4],
19
19
  },
20
20
  {
21
21
  id: 'barn_storage',
22
- name: 'Lojistik Hangar & Depo',
22
+ name: 'Logistics Hangar & Storage',
23
23
  color: '#b45309',
24
- description: 'Mahsul toplama, paketleme ve traktör park alanı.',
24
+ description: 'Harvest collection, packaging and tractor parking area.',
25
25
  cameraFocus: [0, 1.5, 6],
26
26
  },
27
27
  ]
@@ -30,9 +30,9 @@ export const DEFAULT_FARM_ENTITIES: WorldEntity[] = [
30
30
  {
31
31
  id: 'farm-worker-1',
32
32
  type: 'person',
33
- name: 'Ahmet — Sera Operatörü',
34
- role: 'İklim Kontrolü & Sulama',
35
- department: 'Sera Operasyonları',
33
+ name: 'Ahmet — Greenhouse Operator',
34
+ role: 'Climate control & irrigation',
35
+ department: 'Greenhouse Operations',
36
36
  zoneId: 'greenhouse',
37
37
  status: 'working',
38
38
  pinNumber: 1,
@@ -42,9 +42,9 @@ export const DEFAULT_FARM_ENTITIES: WorldEntity[] = [
42
42
  {
43
43
  id: 'farm-tractor-1',
44
44
  type: 'vehicle',
45
- name: 'Otonom Traktör Alpha',
46
- role: 'Parsel Sürüm & İlaçlama',
47
- department: 'Filo Yönetimi',
45
+ name: 'Autonomous Tractor Alpha',
46
+ role: 'Plot plowing & crop dusting',
47
+ department: 'Fleet Management',
48
48
  zoneId: 'crop_fields',
49
49
  status: 'running',
50
50
  pinNumber: 2,
@@ -53,9 +53,9 @@ export const DEFAULT_FARM_ENTITIES: WorldEntity[] = [
53
53
  {
54
54
  id: 'farm-worker-2',
55
55
  type: 'person',
56
- name: 'Mehmet — Hasat Sorumlusu',
57
- role: 'Paketleme & Depolama',
58
- department: 'Lojistik',
56
+ name: 'Mehmet — Harvest Supervisor',
57
+ role: 'Packaging & storage',
58
+ department: 'Logistics',
59
59
  zoneId: 'barn_storage',
60
60
  status: 'idle',
61
61
  pinNumber: 3,
@@ -5,23 +5,23 @@ import { MaterialPalette } from '../engine/materials'
5
5
  export const DEFAULT_HOSPITAL_ZONES: WorldZone[] = [
6
6
  {
7
7
  id: 'triage_er',
8
- name: 'Acil Müdahale & Triyaj',
8
+ name: 'Emergency Response & Triage',
9
9
  color: '#ef4444',
10
- description: 'İlk değerlendirme ve acil müdahale ünitesi.',
10
+ description: 'First assessment and emergency response unit.',
11
11
  cameraFocus: [-8, 1.2, 0],
12
12
  },
13
13
  {
14
14
  id: 'consultation',
15
- name: 'Poliklinik & Uzman Hekim Odası',
15
+ name: 'Outpatient & Specialist Rooms',
16
16
  color: '#06b6d4',
17
- description: 'Hasta muayene ve klinik tanı alanı.',
17
+ description: 'Patient examination and clinical diagnosis area.',
18
18
  cameraFocus: [4, 1.0, -4],
19
19
  },
20
20
  {
21
21
  id: 'icu_ward',
22
- name: 'Yoğun Bakım & İzleme Servisi',
22
+ name: 'Intensive Care & Monitoring Ward',
23
23
  color: '#3b82f6',
24
- description: 'Yaşamsal bulgu monitörleri ve hasta yatakları.',
24
+ description: 'Vital sign monitors and patient beds.',
25
25
  cameraFocus: [6, 1.0, 5],
26
26
  },
27
27
  ]
@@ -30,9 +30,9 @@ export const DEFAULT_HOSPITAL_ENTITIES: WorldEntity[] = [
30
30
  {
31
31
  id: 'doctor-1',
32
32
  type: 'person',
33
- name: 'Dr. Selin — Başhekim',
34
- role: 'Klinik Direktörü & Tıbbi Karar',
35
- department: 'Cerrahi',
33
+ name: 'Dr. Selin — Chief Physician',
34
+ role: 'Clinical director & medical decisions',
35
+ department: 'Surgery',
36
36
  zoneId: 'consultation',
37
37
  status: 'working',
38
38
  pinNumber: 1,
@@ -42,9 +42,9 @@ export const DEFAULT_HOSPITAL_ENTITIES: WorldEntity[] = [
42
42
  {
43
43
  id: 'nurse-1',
44
44
  type: 'person',
45
- name: 'Hemşire Burak — Triyaj Uzmanı',
46
- role: 'Hasta Karşılama & Vital İzlem',
47
- department: 'Acil',
45
+ name: 'Nurse Burak — Triage Specialist',
46
+ role: 'Patient intake & vitals monitoring',
47
+ department: 'Emergency',
48
48
  zoneId: 'triage_er',
49
49
  status: 'idle',
50
50
  pinNumber: 2,