@umituz/web-virtual 1.2.0 → 2.0.1

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.
package/README.md CHANGED
@@ -6,6 +6,19 @@ Build realistic, high-performance, interactive 3D virtual offices, farms, indust
6
6
 
7
7
  All UI strings are **English** so the package drops into any product without locale friction. Consumer-supplied data (entity names, missions, roles) is rendered verbatim.
8
8
 
9
+ ## Architecture vs. data
10
+
11
+ The package ships **architecture only** — buildings, rooms (zones), lighting, and anchor **slots** (where someone *can* sit). All occupant and org data is **yours**, passed in as props:
12
+
13
+ | Package provides | Consumer provides |
14
+ |---|---|
15
+ | 3D engine, camera, raycasting, labels/pins | `entities` — who/what occupies the world |
16
+ | Presets: floorplan geometry, furniture, zones | `departments` — org grouping (else derived from zones) |
17
+ | Anchor `slots` (position, zone, pin number) | `zones` override — localized zone labels |
18
+ | Digital HQ chrome (roster, ops, command center) | Missions, projects, activities, metrics |
19
+
20
+ Entities without an explicit `position` are auto-placed onto preset slots — by `slotId`, by matching `id`, or the next free slot — inheriting position, rotation, zone and pin number from the architecture. You only ever describe **who**, never **where**.
21
+
9
22
  ---
10
23
 
11
24
  ## Features
@@ -16,13 +29,13 @@ All UI strings are **English** so the package drops into any product without loc
16
29
  - **Battery Friendly (1.2.0)**: The render loop pauses automatically while the tab is hidden.
17
30
  - **Locked 60 FPS Performance**: Direct GPU CSS `translate3d` projection for floating labels and pins without React state re-rendering overhead during orbit/zoom.
18
31
  - **Interactive Entities & Raycasting**: Click and hover directly on 3D desks, monitors, robots, or avatars.
19
- - **Architectural Presets**:
20
- - `officePreset`: 17-desk architectural floorplan with executive suite, meeting room, and glass partitions.
21
- - `farmPreset`: Greenhouses, crops, barns, tractors.
22
- - `factoryPreset`: Conveyor belts, robotic arms, storage racks.
23
- - `schoolPreset`: Lecture halls, interactive smartboards, science labs.
24
- - `hospitalPreset`: Triage rooms, consultation suites, patient monitoring.
25
- - **DigitalHQView**: A complete, embeddable "digital headquarters" screen — 3D office floor, operations dashboard, and an AI command center wired through a single `onDispatchMission` callback.
32
+ - **Architectural Presets** (occupant-free — slots only):
33
+ - `officePreset`: 17-desk architectural floorplan with executive suite, meeting room, and glass partitions (`OFFICE_SLOTS`).
34
+ - `farmPreset`: Greenhouses, crops, barns, tractors (`FARM_SLOTS`).
35
+ - `factoryPreset`: Conveyor belts, robotic arms, storage racks (`FACTORY_SLOTS`).
36
+ - `schoolPreset`: Lecture halls, interactive smartboards, science labs (`SCHOOL_SLOTS`).
37
+ - `hospitalPreset`: Triage rooms, consultation suites, patient monitoring (`HOSPITAL_SLOTS`).
38
+ - **DigitalHQView**: A complete, embeddable "digital headquarters" screen — 3D office floor, operations dashboard, and an AI command center wired through a single `onDispatchMission` callback. Departments default to a neutral zone-based grouping when the consumer passes none.
26
39
  - **Contextual Inspector & Profile Drawer**: Role, status, metrics, latest task, and custom application actions.
27
40
  - **Day & Night Simulation**: One-click smooth lighting transitions.
28
41
  - **Pin & Label Modes**: Minimal circular pins (`#1`..`#17`) with status indicators, expandable chips, or hidden mode.
@@ -76,6 +89,24 @@ const world = useMemo(
76
89
  return <VirtualWorld world={world} preset={officePreset} />
77
90
  ```
78
91
 
92
+ ### Your occupants, your language (any preset)
93
+
94
+ Occupants carry no positions — they are auto-placed onto the preset's slots. Pin someone to a specific desk with `slotId`, or let them fill slots in order. Same API for every preset:
95
+
96
+ ```tsx
97
+ import { createEnvironment, farmPreset } from '@umituz/web-virtual'
98
+
99
+ const world = createEnvironment({
100
+ preset: farmPreset,
101
+ name: 'Agromera Çiftlik',
102
+ zones: TurkishZoneLabels, // optional: localize room names
103
+ entities: [
104
+ { slotId: 'slot-1', type: 'person', name: 'Ahmet', role: 'Sera operatörü', status: 'working' },
105
+ { slotId: 'slot-2', type: 'vehicle', name: 'Traktör Alpha', status: 'running' },
106
+ ],
107
+ })
108
+ ```
109
+
79
110
  ### Full digital HQ screen
80
111
 
81
112
  ```tsx
@@ -113,7 +144,7 @@ Ref API (`VirtualWorldRef`): `focusOnEntity`, `setCameraPreset`, `resetCamera`,
113
144
 
114
145
  ### `DigitalHQView`
115
146
 
116
- Everything `VirtualWorld` renders plus an operations dashboard and AI command center. Notable props: `projects`, `activities`, `presetMissions`, `deskCapacity` (defaults to the world's entity count), `getEntityMetrics`, `getEntityLatestTask`, `onDispatchMission({ prompt, targetId, isDemo })`, `onSeedSquad`.
147
+ Everything `VirtualWorld` renders plus an operations dashboard and AI command center. Notable props: `departments` (consumer org data; neutral zone-based groups when omitted), `projects`, `activities`, `presetMissions`, `deskCapacity` (defaults to the world's entity count), `getEntityMetrics`, `getEntityLatestTask`, `onDispatchMission({ prompt, targetId, isDemo })`, `onSeedSquad`.
117
148
 
118
149
  ---
119
150
 
@@ -37,6 +37,8 @@ All 3D models integrated into `@umituz/web-virtual` comply with strict open-sour
37
37
  | **Characters** | `character-female-a.glb` | Skinned glTF | 273.4 KB | CC0 1.0 | Kenney | https://kenney.nl/assets/mini-characters |
38
38
  | **Characters** | `character-female-b.glb` | Skinned glTF | 252.1 KB | CC0 1.0 | Kenney | https://kenney.nl/assets/mini-characters |
39
39
 
40
+ > **Character texture note:** the Mini Characters kit ships its models with a shared external `Textures/colormap.png` atlas. That atlas (CC0, same kit) is now **embedded inside each character GLB**, making them fully self-contained — no sidecar files to lose between the package and consumer apps.
41
+
40
42
  ---
41
43
 
42
44
  ## 2. Integration Policy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-virtual",
3
- "version": "1.2.0",
3
+ "version": "2.0.1",
4
4
  "description": "Universal 3D Virtual Environment Engine for Web & React — Offices, Farms, Factories, Schools, Hospitals with 60fps performance, raycasting and interactive entities.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -30,14 +30,15 @@ import {
30
30
  Moon,
31
31
  Sun,
32
32
  RotateCcw,
33
+ Users,
33
34
  } from 'lucide-react'
34
- import type { WorldDefinition, WorldEntity, WorldPreset, PinDisplayMode } from '../core/types'
35
+ import type { WorldDefinition, WorldEntity, WorldPreset, PinDisplayMode, DepartmentInfo } from '../core/types'
36
+ import { deriveDepartmentsFromZones } from '../core/environment'
35
37
  import { VirtualWorld, type VirtualWorldRef } from './VirtualWorld'
36
38
  import { VirtualCommandBar, type PresetMission } from './VirtualCommandBar'
37
39
  import { VirtualRoster } from './VirtualRoster'
38
40
  import { VirtualEntityDrawer, type EntityRunMetrics, type EntityLatestTask } from './VirtualEntityDrawer'
39
41
  import { VirtualReportModal, type VirtualReportData } from './VirtualReportModal'
40
- import { DEFAULT_OFFICE_DEPARTMENTS, type DepartmentInfo } from '../presets/officePreset'
41
42
 
42
43
  export type OperationalMode = 'office' | 'operations' | 'command_center'
43
44
 
@@ -83,7 +84,7 @@ export interface DigitalHQViewProps {
83
84
  export function DigitalHQView({
84
85
  world,
85
86
  preset,
86
- departments = DEFAULT_OFFICE_DEPARTMENTS,
87
+ departments: departmentsProp,
87
88
  presetMissions = [],
88
89
  projects = [],
89
90
  activities = [],
@@ -193,6 +194,13 @@ export function DigitalHQView({
193
194
  return world.entities.filter((e) => e.status === 'running' || e.status === 'working').length
194
195
  }, [world.entities])
195
196
 
197
+ // Departments are consumer org data. When none are supplied, derive a
198
+ // neutral grouping from the preset's architectural zones instead.
199
+ const departments = useMemo<DepartmentInfo[]>(() => {
200
+ if (departmentsProp && departmentsProp.length > 0) return departmentsProp
201
+ return deriveDepartmentsFromZones(world.zones, preset?.slots ?? [])
202
+ }, [departmentsProp, world.zones, preset])
203
+
196
204
  const pendingApprovalsCount = useMemo(() => {
197
205
  return world.entities.filter((e) => e.status === 'awaiting_approval').length
198
206
  }, [world.entities])
@@ -435,6 +443,31 @@ export function DigitalHQView({
435
443
  showControls={false}
436
444
  showInspector={false}
437
445
  >
446
+ {/* Friendly empty state when no occupants are placed yet */}
447
+ {world.entities.length === 0 && (
448
+ <div className="wv-hq-empty-floor">
449
+ <div className="wv-hq-empty-floor-card">
450
+ <Users size={28} />
451
+ <h3>The floor is ready — nobody is in yet</h3>
452
+ <p>
453
+ All {capacity} desks are installed and waiting. Bring your team in and they
454
+ will take their seats here in 3D.
455
+ </p>
456
+ {onSeedSquad && (
457
+ <button
458
+ type="button"
459
+ onClick={onSeedSquad}
460
+ disabled={isSeeding}
461
+ className="wv-hq-empty-floor-btn"
462
+ >
463
+ {isSeeding ? <Loader2 size={14} className="wv-spin" /> : <Sparkles size={14} />}
464
+ <span>Build the squad ({capacity})</span>
465
+ </button>
466
+ )}
467
+ </div>
468
+ </div>
469
+ )}
470
+
438
471
  {/* Floating Bottom Command Bar Overlay */}
439
472
  <VirtualCommandBar
440
473
  presetMissions={presetMissions}
@@ -554,7 +587,7 @@ export function DigitalHQView({
554
587
 
555
588
  <div className="wv-hq-dept-cards-grid">
556
589
  {departments.map((dept) => {
557
- const deptEntities = world.entities.filter((e) => dept.slotIds.includes(e.id))
590
+ const deptEntities = world.entities.filter((e) => (dept.slotIds ?? []).includes(e.id))
558
591
  const isDeptBusy = deptEntities.some((e) => e.status === 'running' || e.status === 'working')
559
592
 
560
593
  return (
@@ -573,7 +606,7 @@ export function DigitalHQView({
573
606
  <button
574
607
  type="button"
575
608
  onClick={() => {
576
- setSelectedCategory(dept.slug)
609
+ setSelectedCategory(dept.slug ?? dept.id)
577
610
  setActiveMode('office')
578
611
  }}
579
612
  className="wv-dept-link-btn"
@@ -10,8 +10,7 @@ import {
10
10
  Globe,
11
11
  Shield,
12
12
  } from 'lucide-react'
13
- import type { WorldEntity } from '../core/types'
14
- import type { DepartmentInfo } from '../presets/officePreset'
13
+ import type { WorldEntity, DepartmentInfo } from '../core/types'
15
14
 
16
15
  export interface VirtualRosterProps {
17
16
  entities: WorldEntity[]
@@ -47,9 +46,9 @@ export function VirtualRoster({
47
46
  if (searchQuery && !nameMatch && !roleMatch) return false
48
47
 
49
48
  if (selectedCategory !== 'all') {
50
- const dept = departments.find((d) => d.slug === selectedCategory)
49
+ const dept = departments.find((d) => (d.slug ?? d.id) === selectedCategory)
51
50
  if (dept) {
52
- if (!dept.slotIds.includes(en.id)) return false
51
+ if (!(dept.slotIds ?? []).includes(en.id)) return false
53
52
  } else if (en.department !== selectedCategory && en.zoneId !== selectedCategory) {
54
53
  return false
55
54
  }
@@ -126,7 +125,7 @@ export function VirtualRoster({
126
125
  <button
127
126
  key={dept.id}
128
127
  type="button"
129
- onClick={() => onSelectCategory(dept.slug)}
128
+ onClick={() => onSelectCategory(dept.slug ?? dept.id)}
130
129
  className={`wv-roster-pill ${selectedCategory === dept.slug ? 'is-active' : ''}`}
131
130
  >
132
131
  {dept.name.split(' ')[0]}
@@ -1,9 +1,15 @@
1
- import { describe, it, expect } from 'vitest'
2
- import { createEnvironment, validateEnvironment } from './environment'
3
- import { officePreset, farmPreset, factoryPreset, schoolPreset, hospitalPreset } from '../presets/index'
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import {
3
+ createEnvironment,
4
+ validateEnvironment,
5
+ placeEntitiesOnSlots,
6
+ deriveDepartmentsFromZones,
7
+ } from './environment'
8
+ import type { EntityDraft } from './types'
9
+ import { officePreset, farmPreset, factoryPreset, OFFICE_SLOTS, FARM_SLOTS } from '../presets/index'
4
10
 
5
11
  describe('Environment Factory & Presets', () => {
6
- it('creates an environment using officePreset', () => {
12
+ it('creates an office environment with architecture but no occupants', () => {
7
13
  const world = createEnvironment({
8
14
  preset: officePreset,
9
15
  name: 'Nexora Agency HQ',
@@ -13,28 +19,106 @@ describe('Environment Factory & Presets', () => {
13
19
  expect(world.type).toBe('office')
14
20
  expect(world.dimensions.width).toBe(36)
15
21
  expect(world.zones.length).toBe(6)
16
- expect(world.entities.length).toBe(17)
22
+ expect(world.entities).toEqual([])
17
23
  })
18
24
 
19
- it('creates an environment using farmPreset', () => {
25
+ it('auto-places consumer occupants onto preset slots in order', () => {
26
+ const occupants: EntityDraft[] = [
27
+ { id: 'gm', type: 'person', name: 'Ayşe Yıldız', role: 'CEO', status: 'idle' },
28
+ { id: 'dev', type: 'person', name: 'Mehmet Kaya', role: 'Developer', status: 'running' },
29
+ ]
30
+
20
31
  const world = createEnvironment({
21
- preset: farmPreset,
22
- name: 'Organic Farm Valley',
32
+ preset: officePreset,
33
+ name: 'Team HQ',
34
+ entities: occupants,
23
35
  })
24
36
 
25
- expect(world.type).toBe('farm')
26
- expect(world.zones.length).toBe(3)
27
- expect(world.entities.length).toBe(3)
37
+ expect(world.entities).toHaveLength(2)
38
+ expect(world.entities[0]!.slotId).toBe('slot-1')
39
+ expect(world.entities[0]!.position).toEqual(OFFICE_SLOTS[0]!.position)
40
+ expect(world.entities[0]!.zoneId).toBe('executive')
41
+ expect(world.entities[0]!.pinNumber).toBe(1)
42
+ expect(world.entities[0]!.avatarColor).toBe(OFFICE_SLOTS[0]!.avatarColor)
43
+ expect(world.entities[1]!.slotId).toBe('slot-2')
44
+ expect(world.entities[1]!.position).toEqual(OFFICE_SLOTS[1]!.position)
45
+ // Omitted fields inherit the slot's architectural suggestion
46
+ expect(world.entities[1]!.avatarColor).toBe(OFFICE_SLOTS[1]!.avatarColor)
47
+ expect(world.entities[1]!.zoneId).toBe('growth')
28
48
  })
29
49
 
30
- it('creates an environment using factoryPreset', () => {
50
+ it('lets consumer fields override slot suggestions', () => {
31
51
  const world = createEnvironment({
32
- preset: factoryPreset,
33
- name: 'Auto Plant 4',
52
+ preset: officePreset,
53
+ name: 'HQ',
54
+ entities: [{ id: 'slot-1', type: 'person', name: 'GM', avatarColor: '#ff0055', zoneId: 'meeting' }],
34
55
  })
35
56
 
36
- expect(world.type).toBe('factory')
37
- expect(world.entities.length).toBe(3)
57
+ expect(world.entities[0]!.avatarColor).toBe('#ff0055')
58
+ expect(world.entities[0]!.zoneId).toBe('meeting')
59
+ expect(world.entities[0]!.position).toEqual(OFFICE_SLOTS[0]!.position)
60
+ })
61
+
62
+ it('pins an occupant to a specific slot via slotId and keeps explicit positions', () => {
63
+ const occupants: EntityDraft[] = [
64
+ { id: 'founder', slotId: 'slot-17', type: 'person', name: 'Founder' },
65
+ { id: 'visitor', type: 'person', name: 'Visitor', position: [0, 0, 0] },
66
+ ]
67
+
68
+ const world = createEnvironment({ preset: officePreset, name: 'HQ', entities: occupants })
69
+
70
+ expect(world.entities[0]!.slotId).toBe('slot-17')
71
+ expect(world.entities[0]!.position).toEqual(OFFICE_SLOTS[16]!.position)
72
+ // Explicit positions pass through untouched and do not consume a slot
73
+ expect(world.entities[1]!.position).toEqual([0, 0, 0])
74
+ expect(world.entities[1]!.slotId).toBeUndefined()
75
+ })
76
+
77
+ it('skips occupants when no free slot is left and warns', () => {
78
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
79
+ try {
80
+ const slots = FARM_SLOTS.slice(0, 1)
81
+ const placed = placeEntitiesOnSlots(
82
+ [
83
+ { id: 'a', type: 'person', name: 'A' },
84
+ { id: 'b', type: 'person', name: 'B' },
85
+ ],
86
+ slots,
87
+ )
88
+ expect(placed).toHaveLength(1)
89
+ expect(placed[0]!.slotId).toBe('slot-1')
90
+ expect(consoleWarn).toHaveBeenCalledTimes(1)
91
+ } finally {
92
+ consoleWarn.mockRestore()
93
+ }
94
+ })
95
+
96
+ it('keeps farm and factory presets slot-based and occupant-free', () => {
97
+ const farm = createEnvironment({ preset: farmPreset, name: 'Agromera Farm' })
98
+ expect(farm.type).toBe('farm')
99
+ expect(farm.zones.length).toBe(3)
100
+ expect(farm.entities).toEqual([])
101
+
102
+ const factory = createEnvironment({ preset: factoryPreset, name: 'Auto Plant 4' })
103
+ expect(factory.type).toBe('factory')
104
+ expect(factory.entities).toEqual([])
105
+ })
106
+
107
+ it('derives neutral departments from zones with their slots', () => {
108
+ const departments = deriveDepartmentsFromZones(
109
+ [
110
+ { id: 'greenhouse', name: 'Greenhouse', color: '#22c55e' },
111
+ { id: 'barn', name: 'Barn' },
112
+ ],
113
+ [
114
+ { id: 'slot-1', label: 'Greenhouse station', position: [0, 0, 0], zoneId: 'greenhouse' },
115
+ { id: 'slot-2', label: 'Barn station', position: [1, 0, 0], zoneId: 'barn' },
116
+ ],
117
+ )
118
+
119
+ expect(departments).toHaveLength(2)
120
+ expect(departments[0]).toMatchObject({ slug: 'greenhouse', name: 'Greenhouse', color: '#22c55e', slotIds: ['slot-1'] })
121
+ expect(departments[1]).toMatchObject({ slug: 'barn', slotIds: ['slot-2'] })
38
122
  })
39
123
 
40
124
  it('validates environment entity ids and positions', () => {
@@ -2,8 +2,93 @@ import type {
2
2
  WorldDefinition,
3
3
  CreateEnvironmentOptions,
4
4
  WorldEntity,
5
+ EntityDraft,
6
+ WorldSlot,
7
+ WorldZone,
8
+ DepartmentInfo,
5
9
  } from './types'
6
10
 
11
+ /**
12
+ * Place entities onto preset anchor slots. Entities that already carry an
13
+ * explicit `position` are kept as-is. Otherwise each entity is matched to a
14
+ * slot by `slotId` (or its own `id`), falling back to the next free slot in
15
+ * declaration order. Slot data (position, rotation, zoneId, pinNumber,
16
+ * avatarColor) fills in any fields the entity left empty, so consumers only
17
+ * describe WHO sits somewhere — never WHERE.
18
+ */
19
+ export function placeEntitiesOnSlots(
20
+ entities: EntityDraft[],
21
+ slots: WorldSlot[],
22
+ ): WorldEntity[] {
23
+ const placed: WorldEntity[] = []
24
+
25
+ if (slots.length === 0) {
26
+ for (const entity of entities) {
27
+ if (!entity.position) {
28
+ console.warn(
29
+ `[web-virtual] Entity "${entity.id}" has no position and the preset has no slots — it was skipped.`,
30
+ )
31
+ continue
32
+ }
33
+ placed.push(entity as WorldEntity)
34
+ }
35
+ return placed
36
+ }
37
+
38
+ const slotsById = new Map(slots.map((s) => [s.id, s]))
39
+ const used = new Set<string>()
40
+
41
+ for (const entity of entities) {
42
+ if (entity.position) {
43
+ placed.push(entity as WorldEntity)
44
+ continue
45
+ }
46
+
47
+ const slot = (entity.slotId && slotsById.get(entity.slotId)) || slotsById.get(entity.id)
48
+ const resolved = slot && !used.has(slot.id) ? slot : slots.find((s) => !used.has(s.id))
49
+
50
+ if (!resolved) {
51
+ console.warn(
52
+ `[web-virtual] No free slot left for entity "${entity.id}" — it was skipped. ` +
53
+ `Pass an explicit position or add more slots to the preset.`,
54
+ )
55
+ continue
56
+ }
57
+
58
+ used.add(resolved.id)
59
+ placed.push({
60
+ ...entity,
61
+ slotId: resolved.id,
62
+ position: resolved.position,
63
+ rotation: entity.rotation ?? resolved.rotation,
64
+ zoneId: entity.zoneId ?? resolved.zoneId,
65
+ pinNumber: entity.pinNumber ?? resolved.pinNumber,
66
+ avatarColor: entity.avatarColor ?? resolved.avatarColor,
67
+ })
68
+ }
69
+
70
+ return placed
71
+ }
72
+
73
+ /**
74
+ * Neutral department grouping derived from preset zones — used when the
75
+ * consumer passes no `departments`. One group per zone, keyed by zone id.
76
+ */
77
+ export function deriveDepartmentsFromZones(
78
+ zones: WorldZone[],
79
+ slots: WorldSlot[] = [],
80
+ ): DepartmentInfo[] {
81
+ return zones.map((zone) => ({
82
+ id: `zone-${zone.id}`,
83
+ name: zone.name,
84
+ slug: zone.id,
85
+ description: zone.description,
86
+ color: zone.color,
87
+ zoneId: zone.id,
88
+ slotIds: slots.filter((s) => s.zoneId === zone.id).map((s) => s.id),
89
+ }))
90
+ }
91
+
7
92
  export function createEnvironment(options: CreateEnvironmentOptions): WorldDefinition {
8
93
  const preset = options.preset
9
94
 
@@ -66,13 +151,14 @@ export function createEnvironment(options: CreateEnvironmentOptions): WorldDefin
66
151
 
67
152
  const zones = options.zones || preset?.zones || []
68
153
 
69
- // If user provided entities, use them; otherwise if preset has defaults, use those
70
- let entities: WorldEntity[] = []
71
- if (options.entities && options.entities.length > 0) {
72
- entities = options.entities
73
- } else if (preset?.defaultEntities) {
74
- entities = preset.defaultEntities
75
- }
154
+ // Occupants come from the consumer. If none are given, an optional preset
155
+ // default may supply demo occupants. Either way, entities without an
156
+ // explicit position are auto-placed onto the preset's architectural slots.
157
+ const sourceEntities: EntityDraft[] =
158
+ options.entities && options.entities.length > 0
159
+ ? options.entities
160
+ : (preset?.defaultEntities ?? [])
161
+ const entities = placeEntitiesOnSlots(sourceEntities, preset?.slots ?? [])
76
162
 
77
163
  const world: WorldDefinition = {
78
164
  id,
package/src/core/types.ts CHANGED
@@ -30,6 +30,10 @@ export interface WorldEntity {
30
30
  zoneId?: string
31
31
  description?: string
32
32
  status?: EntityStatus
33
+ /**
34
+ * Anchor slot this entity was placed on (mirrors `WorldPreset.slots` ids).
35
+ */
36
+ slotId?: string
33
37
  position: Vector3Tuple
34
38
  rotation?: Vector3Tuple
35
39
  scale?: Vector3Tuple
@@ -41,6 +45,34 @@ export interface WorldEntity {
41
45
  metadata?: Record<string, unknown>
42
46
  }
43
47
 
48
+ /**
49
+ * Occupant input accepted by `createEnvironment` — a full `WorldEntity` minus
50
+ * the required placement fields. If `position` is omitted the entity is
51
+ * auto-placed onto a preset slot (by `slotId`, by matching `id`, or the next
52
+ * free slot in order), inheriting the slot's position, rotation, zoneId,
53
+ * pinNumber and suggested avatarColor.
54
+ */
55
+ export type EntityDraft = Omit<WorldEntity, 'position'> & { position?: Vector3Tuple }
56
+
57
+ /**
58
+ * Architectural anchor point on a preset where a consumer entity can be
59
+ * placed — a desk, workstation, field station, machine bay, etc. Slots carry
60
+ * no occupant data: who (or what) sits there always comes from the consumer.
61
+ */
62
+ export interface WorldSlot {
63
+ id: string
64
+ /** Neutral architectural label, e.g. "Executive desk", "Workstation 4". */
65
+ label: string
66
+ position: Vector3Tuple
67
+ rotation?: Vector3Tuple
68
+ zoneId?: string
69
+ pinNumber?: number
70
+ /** Suggested avatar color — consumer entities may override. */
71
+ avatarColor?: string
72
+ /** Free-form architecture hints, e.g. `{ desk: 'workstation', dualMonitor: true }`. */
73
+ metadata?: Record<string, unknown>
74
+ }
75
+
44
76
  export interface WorldZone {
45
77
  id: string
46
78
  name: string
@@ -139,10 +171,26 @@ export interface CreateEnvironmentOptions {
139
171
  lighting?: Partial<LightingConfiguration>
140
172
  theme?: Partial<WorldTheme>
141
173
  zones?: WorldZone[]
142
- entities?: WorldEntity[]
174
+ entities?: EntityDraft[]
143
175
  metadata?: Record<string, unknown>
144
176
  }
145
177
 
178
+ /**
179
+ * Consumer-supplied grouping shown in the roster filter and the operations
180
+ * dashboard. Pure org data — the package never ships defaults; when the
181
+ * consumer passes none, groups are derived neutrally from preset zones.
182
+ */
183
+ export interface DepartmentInfo {
184
+ id: string
185
+ name: string
186
+ slug?: string
187
+ description?: string
188
+ color?: string
189
+ slotIds?: string[]
190
+ zoneId?: string
191
+ iconName?: 'briefcase' | 'palette' | 'megaphone' | 'shield' | 'globe'
192
+ }
193
+
146
194
  export interface WorldPreset {
147
195
  id: string
148
196
  name: string
@@ -157,7 +205,10 @@ export interface WorldPreset {
157
205
  lighting: LightingConfiguration
158
206
  theme: WorldTheme
159
207
  zones: WorldZone[]
160
- defaultEntities?: WorldEntity[]
208
+ /** Architectural anchor points for consumer entities (no occupant data). */
209
+ slots?: WorldSlot[]
210
+ /** Optional demo occupants — shipped presets deliberately leave this empty. */
211
+ defaultEntities?: EntityDraft[]
161
212
  buildScene?: (scene: import('three').Scene, options: { nightMode?: boolean; theme?: WorldTheme }) => void
162
213
  }
163
214
 
@@ -0,0 +1,79 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import * as THREE from 'three'
3
+ import { rebindSkinnedSkeletons } from './modelLoader'
4
+
5
+ /**
6
+ * Synthetic rigged asset: a Group with named bones and a SkinnedMesh bound
7
+ * to them — the same structure Kenney character GLBs produce.
8
+ */
9
+ function makeRiggedGroup(): { root: THREE.Group; mesh: THREE.SkinnedMesh; skeleton: THREE.Skeleton } {
10
+ const root = new THREE.Group()
11
+ root.name = 'character'
12
+
13
+ const boneRoot = new THREE.Bone()
14
+ boneRoot.name = 'root'
15
+ const boneHead = new THREE.Bone()
16
+ boneHead.name = 'head'
17
+ boneRoot.add(boneHead)
18
+ root.add(boneRoot)
19
+
20
+ const mesh = new THREE.SkinnedMesh(
21
+ new THREE.BoxGeometry(1, 1, 1),
22
+ new THREE.MeshStandardMaterial(),
23
+ )
24
+ mesh.name = 'body-mesh'
25
+ root.add(mesh)
26
+
27
+ const skeleton = new THREE.Skeleton([boneRoot, boneHead])
28
+ mesh.bind(skeleton, new THREE.Matrix4())
29
+
30
+ return { root, mesh, skeleton }
31
+ }
32
+
33
+ describe('rebindSkinnedSkeletons', () => {
34
+ it('leaves non-skinned hierarchies untouched', () => {
35
+ const group = new THREE.Group()
36
+ group.add(new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial()))
37
+ const clone = group.clone(true)
38
+ expect(() => rebindSkinnedSkeletons(clone)).not.toThrow()
39
+ expect(clone.children).toHaveLength(1)
40
+ })
41
+
42
+ it('clones share the source skeleton before rebinding (the bug)', () => {
43
+ const { root, mesh, skeleton } = makeRiggedGroup()
44
+ const clone = root.clone(true)
45
+ const cloneMesh = clone.getObjectByName('body-mesh') as THREE.SkinnedMesh
46
+ expect(cloneMesh.skeleton).toBe(skeleton)
47
+ expect(cloneMesh.skeleton.bones[0]).toBe(mesh.skeleton.bones[0])
48
+ })
49
+
50
+ it('rebinds a cloned skinned mesh to the bones inside its own hierarchy', () => {
51
+ const { root, skeleton } = makeRiggedGroup()
52
+ const clone = root.clone(true)
53
+ rebindSkinnedSkeletons(clone)
54
+
55
+ const cloneMesh = clone.getObjectByName('body-mesh') as THREE.SkinnedMesh
56
+ expect(cloneMesh.skeleton).not.toBe(skeleton)
57
+ expect(cloneMesh.skeleton.bones.map((b) => b.name)).toEqual(['root', 'head'])
58
+ for (const bone of cloneMesh.skeleton.bones) {
59
+ // every bound bone must live inside the clone, not the source
60
+ let cur: THREE.Object3D | null = bone
61
+ while (cur) {
62
+ if (cur === clone) break
63
+ cur = cur.parent
64
+ }
65
+ expect(cur).toBe(clone)
66
+ }
67
+ })
68
+
69
+ it('keeps the original bound when a joint is missing from the clone', () => {
70
+ const { root, skeleton } = makeRiggedGroup()
71
+ const clone = root.clone(true)
72
+ // rename a cloned bone so the joint cannot be resolved by name
73
+ clone.getObjectByName('head')!.name = 'renamed'
74
+ rebindSkinnedSkeletons(clone)
75
+
76
+ const cloneMesh = clone.getObjectByName('body-mesh') as THREE.SkinnedMesh
77
+ expect(cloneMesh.skeleton).toBe(skeleton)
78
+ })
79
+ })