@umituz/web-virtual 2.0.1 → 2.1.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.
- package/README.md +44 -1
- package/package.json +1 -1
- package/src/components/VirtualWorld.tsx +14 -0
- package/src/core/environment.test.ts +1 -1
- package/src/core/types.ts +24 -1
- package/src/engine/index.ts +1 -0
- package/src/engine/random.ts +25 -0
- package/src/engine/renderer.ts +30 -1
- package/src/entities/animals/AnimalBuilder.test.ts +82 -0
- package/src/entities/animals/AnimalBuilder.ts +219 -0
- package/src/entities/animals/index.ts +1 -0
- package/src/entities/architecture/FarmArchitectureBuilder.ts +370 -0
- package/src/entities/index.ts +4 -0
- package/src/entities/nature/CropFieldBuilder.test.ts +119 -0
- package/src/entities/nature/CropFieldBuilder.ts +123 -0
- package/src/entities/nature/FenceBuilder.ts +108 -0
- package/src/entities/nature/PondBuilder.ts +87 -0
- package/src/entities/nature/TreeBuilder.ts +176 -0
- package/src/entities/nature/index.ts +4 -0
- package/src/entities/vehicles/TractorBuilder.ts +132 -0
- package/src/entities/vehicles/index.ts +1 -0
- package/src/presets/farmPreset.ts +186 -66
- package/src/styles/virtual.css +4 -0
package/README.md
CHANGED
|
@@ -24,6 +24,8 @@ Entities without an explicit `position` are auto-placed onto preset slots — by
|
|
|
24
24
|
## Features
|
|
25
25
|
|
|
26
26
|
- **Universal Engine**: Agnostic to domain (Corporate Offices, Agriculture, Automation Factories, Campus, Healthcare).
|
|
27
|
+
- **Engine Tick Animations (2.1.0)**: Register per-frame scene motion (`registerTick`) on the engine's own render loop — wind sway, water ripples, spinning wheels, grazing herds. No separate `requestAnimationFrame` needed; pauses with the tab, cleared on dispose.
|
|
28
|
+
- **Nature / Farm / Animal Builders (2.1.0)**: Procedural, config-driven `createCropPlot` (growth 0–1), `createTree`/`createTreeRow` (+`applyWindSway`), `createFence`, `createPond`, `createAnimal`/`createHerd` (cow/sheep/goat/chicken), `createTractor`, plus farm architecture (barn, silo, greenhouse, machine shed, coop).
|
|
27
29
|
- **Hot-Synced Entities (1.2.0)**: When the `world` prop changes (e.g. a status poll), entities are diffed and updated **in place** — the scene, camera position, lights and cached GLB models are never rebuilt. No flicker, no reloads, no lost camera angle.
|
|
28
30
|
- **WebGL Resilience (1.2.0)**: Graceful fallback UI when WebGL is unavailable, and a one-click restore overlay if the GPU context is lost mid-session.
|
|
29
31
|
- **Battery Friendly (1.2.0)**: The render loop pauses automatically while the tab is hidden.
|
|
@@ -31,7 +33,7 @@ Entities without an explicit `position` are auto-placed onto preset slots — by
|
|
|
31
33
|
- **Interactive Entities & Raycasting**: Click and hover directly on 3D desks, monitors, robots, or avatars.
|
|
32
34
|
- **Architectural Presets** (occupant-free — slots only):
|
|
33
35
|
- `officePreset`: 17-desk architectural floorplan with executive suite, meeting room, and glass partitions (`OFFICE_SLOTS`).
|
|
34
|
-
- `farmPreset`:
|
|
36
|
+
- `farmPreset`: Staged crop plots, greenhouse benches, fenced pasture with animated herds, a rippling pond, barn + silo, machinery yard and poultry run (`FARM_SLOTS`).
|
|
35
37
|
- `factoryPreset`: Conveyor belts, robotic arms, storage racks (`FACTORY_SLOTS`).
|
|
36
38
|
- `schoolPreset`: Lecture halls, interactive smartboards, science labs (`SCHOOL_SLOTS`).
|
|
37
39
|
- `hospitalPreset`: Triage rooms, consultation suites, patient monitoring (`HOSPITAL_SLOTS`).
|
|
@@ -89,6 +91,47 @@ const world = useMemo(
|
|
|
89
91
|
return <VirtualWorld world={world} preset={officePreset} />
|
|
90
92
|
```
|
|
91
93
|
|
|
94
|
+
### Scene animations on the engine loop (2.1.0)
|
|
95
|
+
|
|
96
|
+
`buildScene` receives a `registerTick` hook — register any per-frame motion
|
|
97
|
+
there and the engine steps it inside its own loop (tab-hidden pause and
|
|
98
|
+
dispose cleanup included). The same hook is available on the component ref:
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
import type { WorldPreset } from '@umituz/web-virtual'
|
|
102
|
+
|
|
103
|
+
const myPreset: WorldPreset = {
|
|
104
|
+
/* …camera, lighting, theme, zones… */
|
|
105
|
+
buildScene: (scene, { registerTick }) => {
|
|
106
|
+
const herd = createHerd({ species: 'cow', count: 6, registerTick })
|
|
107
|
+
scene.add(herd)
|
|
108
|
+
applyWindSway(treeRow, registerTick, { intensity: 0.03 })
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Or from the page:
|
|
113
|
+
const onReady = (ref: VirtualWorldRef) =>
|
|
114
|
+
ref.registerTick((_delta, elapsed) => {
|
|
115
|
+
myMesh.rotation.y = elapsed * 0.4
|
|
116
|
+
})
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Procedural nature / farm builders (2.1.0)
|
|
120
|
+
|
|
121
|
+
All builders are pure config — no domain data, no fetching, nothing
|
|
122
|
+
project-specific:
|
|
123
|
+
|
|
124
|
+
| Builder | What it makes |
|
|
125
|
+
| --- | --- |
|
|
126
|
+
| `createCropPlot({ growth, rows, cropColor })` | Raised soil bed + instanced crop rows; `growth` 0→1 scales height and density |
|
|
127
|
+
| `createTree({ shape, season })` / `createTreeRow` | Low-poly trees (round/broad/conifer, spring→winter) |
|
|
128
|
+
| `applyWindSway(target, registerTick)` | Sine sway for foliage (or any group) |
|
|
129
|
+
| `createFence({ points })` | Ranch/picket fence along a polyline |
|
|
130
|
+
| `createPond({ radius, registerTick })` | Water disc with looping ripple rings |
|
|
131
|
+
| `createAnimal` / `createHerd` | Cow, sheep, goat, chicken — deterministic scatter, grazing animation |
|
|
132
|
+
| `createTractor({ status, implement })` | Wheels spin and engine shivers when `status: 'running'` |
|
|
133
|
+
| `createBarn`, `createSilo`, `createGreenhouse`, `createMachineShed`, `createCoop` | Farm architecture — every piece optional and parameterized |
|
|
134
|
+
|
|
92
135
|
### Your occupants, your language (any preset)
|
|
93
136
|
|
|
94
137
|
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:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-virtual",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
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",
|
|
@@ -14,6 +14,8 @@ import type {
|
|
|
14
14
|
WorldEntity,
|
|
15
15
|
WorldPreset,
|
|
16
16
|
PinDisplayMode,
|
|
17
|
+
WorldTickFn,
|
|
18
|
+
UnregisterTick,
|
|
17
19
|
} from '../core/types'
|
|
18
20
|
import { WorldEngine } from '../engine/renderer'
|
|
19
21
|
import { createStylizedAvatar, type CreatedAvatar } from '../entities/people/AvatarBuilder'
|
|
@@ -28,6 +30,11 @@ export interface VirtualWorldRef {
|
|
|
28
30
|
resetCamera: () => void
|
|
29
31
|
setNightMode: (isNight: boolean) => void
|
|
30
32
|
resize: () => void
|
|
33
|
+
/**
|
|
34
|
+
* Register a per-frame animation stepped by the engine's render loop —
|
|
35
|
+
* no separate requestAnimationFrame loop needed on the consumer side.
|
|
36
|
+
*/
|
|
37
|
+
registerTick: (fn: WorldTickFn) => UnregisterTick
|
|
31
38
|
}
|
|
32
39
|
|
|
33
40
|
export interface VirtualWorldProps {
|
|
@@ -177,6 +184,7 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
|
|
|
177
184
|
activePreset.buildScene(engine.scene, {
|
|
178
185
|
nightMode: nightModeRef.current,
|
|
179
186
|
theme: worldRef.current.theme,
|
|
187
|
+
registerTick: engine.registerTick.bind(engine),
|
|
180
188
|
})
|
|
181
189
|
}
|
|
182
190
|
|
|
@@ -331,6 +339,12 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
|
|
|
331
339
|
engineRef.current.resize(clientWidth, clientHeight)
|
|
332
340
|
}
|
|
333
341
|
},
|
|
342
|
+
registerTick: (fn: WorldTickFn) => {
|
|
343
|
+
if (engineRef.current) {
|
|
344
|
+
return engineRef.current.registerTick(fn)
|
|
345
|
+
}
|
|
346
|
+
return () => {}
|
|
347
|
+
},
|
|
334
348
|
}),
|
|
335
349
|
[],
|
|
336
350
|
)
|
|
@@ -96,7 +96,7 @@ describe('Environment Factory & Presets', () => {
|
|
|
96
96
|
it('keeps farm and factory presets slot-based and occupant-free', () => {
|
|
97
97
|
const farm = createEnvironment({ preset: farmPreset, name: 'Agromera Farm' })
|
|
98
98
|
expect(farm.type).toBe('farm')
|
|
99
|
-
expect(farm.zones.length).toBe(
|
|
99
|
+
expect(farm.zones.length).toBe(5)
|
|
100
100
|
expect(farm.entities).toEqual([])
|
|
101
101
|
|
|
102
102
|
const factory = createEnvironment({ preset: factoryPreset, name: 'Auto Plant 4' })
|
package/src/core/types.ts
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
export type Vector3Tuple = [number, number, number]
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Per-frame animation callback stepped by the engine's own render loop.
|
|
5
|
+
* Receives the frame delta (seconds) and total elapsed time (seconds).
|
|
6
|
+
* Registered callbacks pause with the tab (battery-aware) and are cleared
|
|
7
|
+
* automatically when the engine is disposed — consumers never need their
|
|
8
|
+
* own requestAnimationFrame loop for scene motion.
|
|
9
|
+
*/
|
|
10
|
+
export type WorldTickFn = (delta: number, elapsed: number) => void
|
|
11
|
+
|
|
12
|
+
/** Unregister function returned by tick registration. */
|
|
13
|
+
export type UnregisterTick = () => void
|
|
14
|
+
|
|
3
15
|
export type EntityType =
|
|
4
16
|
| 'person'
|
|
5
17
|
| 'actor'
|
|
@@ -191,6 +203,17 @@ export interface DepartmentInfo {
|
|
|
191
203
|
iconName?: 'briefcase' | 'palette' | 'megaphone' | 'shield' | 'globe'
|
|
192
204
|
}
|
|
193
205
|
|
|
206
|
+
/** Options handed to a preset's `buildScene` when the engine builds the world. */
|
|
207
|
+
export interface BuildSceneOptions {
|
|
208
|
+
nightMode?: boolean
|
|
209
|
+
theme?: WorldTheme
|
|
210
|
+
/**
|
|
211
|
+
* Engine per-frame hook — register scene animations here (wind sway, water
|
|
212
|
+
* ripples, machine motion…) instead of running a separate rAF loop.
|
|
213
|
+
*/
|
|
214
|
+
registerTick?: (fn: WorldTickFn) => UnregisterTick
|
|
215
|
+
}
|
|
216
|
+
|
|
194
217
|
export interface WorldPreset {
|
|
195
218
|
id: string
|
|
196
219
|
name: string
|
|
@@ -209,7 +232,7 @@ export interface WorldPreset {
|
|
|
209
232
|
slots?: WorldSlot[]
|
|
210
233
|
/** Optional demo occupants — shipped presets deliberately leave this empty. */
|
|
211
234
|
defaultEntities?: EntityDraft[]
|
|
212
|
-
buildScene?: (scene: import('three').Scene, options:
|
|
235
|
+
buildScene?: (scene: import('three').Scene, options: BuildSceneOptions) => void
|
|
213
236
|
}
|
|
214
237
|
|
|
215
238
|
export type PinDisplayMode = 'pins' | 'labels' | 'off'
|
package/src/engine/index.ts
CHANGED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic seeded pseudo-random numbers (mulberry32). Builders scatter
|
|
3
|
+
* vegetation, herds and props through this so a given seed always produces
|
|
4
|
+
* the exact same scene — stable across reloads, hot-syncs and screenshots.
|
|
5
|
+
*/
|
|
6
|
+
export function createRng(seed: number): () => number {
|
|
7
|
+
let a = seed >>> 0
|
|
8
|
+
return () => {
|
|
9
|
+
a |= 0
|
|
10
|
+
a = (a + 0x6d2b79f5) | 0
|
|
11
|
+
let t = Math.imul(a ^ (a >>> 15), 1 | a)
|
|
12
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
|
|
13
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Map a numeric seed and an index into a stable 0..2π phase offset. */
|
|
18
|
+
export function phaseFor(seed: number, index: number): number {
|
|
19
|
+
return (Math.imul(seed ^ index, 0x9e3779b1) >>> 0) / 4294967296 * Math.PI * 2
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Small deterministic jitter around a base value, in ±amount. */
|
|
23
|
+
export function jitter(rng: () => number, base: number, amount: number): number {
|
|
24
|
+
return base + (rng() * 2 - 1) * amount
|
|
25
|
+
}
|
package/src/engine/renderer.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import * as THREE from 'three'
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
WorldDefinition,
|
|
4
|
+
WorldEntity,
|
|
5
|
+
EntitySelectedEvent,
|
|
6
|
+
WorldTickFn,
|
|
7
|
+
UnregisterTick,
|
|
8
|
+
} from '../core/types'
|
|
3
9
|
import { MaterialPalette } from './materials'
|
|
4
10
|
import { WorldLighting } from './lighting'
|
|
5
11
|
import { WorldCamera, type CameraPresetName } from './camera'
|
|
@@ -29,6 +35,9 @@ export class WorldEngine {
|
|
|
29
35
|
public interactiveObjects: THREE.Object3D[] = []
|
|
30
36
|
public animators: Array<(delta: number, elapsed: number) => void> = []
|
|
31
37
|
|
|
38
|
+
/** Consumer-registered per-frame callbacks (wind, water, machinery…). */
|
|
39
|
+
private ticks = new Set<WorldTickFn>()
|
|
40
|
+
|
|
32
41
|
private isDisposed = false
|
|
33
42
|
private animationFrameId: number | null = null
|
|
34
43
|
private visibilityHandler: (() => void) | null = null
|
|
@@ -78,6 +87,18 @@ export class WorldEngine {
|
|
|
78
87
|
this.options.world = world
|
|
79
88
|
}
|
|
80
89
|
|
|
90
|
+
/**
|
|
91
|
+
* Register a per-frame animation callback stepped inside the engine's own
|
|
92
|
+
* render loop. Callbacks pause with the document (battery-aware) and are
|
|
93
|
+
* cleared when the engine is disposed. Returns an unregister function.
|
|
94
|
+
*/
|
|
95
|
+
public registerTick(fn: WorldTickFn): UnregisterTick {
|
|
96
|
+
this.ticks.add(fn)
|
|
97
|
+
return () => {
|
|
98
|
+
this.ticks.delete(fn)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
81
102
|
/** Pause rendering while the tab is hidden to save battery/CPU. */
|
|
82
103
|
private initContextLossHandling(canvas: HTMLCanvasElement): void {
|
|
83
104
|
canvas.addEventListener(
|
|
@@ -232,6 +253,13 @@ export class WorldEngine {
|
|
|
232
253
|
animator(delta, elapsed)
|
|
233
254
|
}
|
|
234
255
|
|
|
256
|
+
// Step consumer-registered scene animations (wind, water, machinery…)
|
|
257
|
+
if (this.ticks.size > 0) {
|
|
258
|
+
for (const tick of this.ticks) {
|
|
259
|
+
tick(delta, elapsed)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
235
263
|
// Render Three.js scene
|
|
236
264
|
this.renderer.render(this.scene, this.cameraSystem.camera)
|
|
237
265
|
|
|
@@ -269,6 +297,7 @@ export class WorldEngine {
|
|
|
269
297
|
public dispose(): void {
|
|
270
298
|
this.isDisposed = true
|
|
271
299
|
this.stopLoop()
|
|
300
|
+
this.ticks.clear()
|
|
272
301
|
if (this.visibilityHandler) {
|
|
273
302
|
document.removeEventListener('visibilitychange', this.visibilityHandler)
|
|
274
303
|
this.visibilityHandler = null
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import * as THREE from 'three'
|
|
3
|
+
import { createAnimal, createHerd } from './AnimalBuilder'
|
|
4
|
+
|
|
5
|
+
describe('createAnimal', () => {
|
|
6
|
+
it.each(['cow', 'sheep', 'goat', 'chicken'] as const)('builds a %s with a head pivot', (species) => {
|
|
7
|
+
const animal = createAnimal({ species })
|
|
8
|
+
expect(animal.getObjectByName('animal-neck')).toBeTruthy()
|
|
9
|
+
expect(animal.getObjectByName('animal-head')).toBeTruthy()
|
|
10
|
+
expect(animal.children.length).toBeGreaterThan(3)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('scales uniformly', () => {
|
|
14
|
+
const animal = createAnimal({ species: 'cow', scale: 2 })
|
|
15
|
+
expect(animal.scale.x).toBe(2)
|
|
16
|
+
expect(animal.scale.y).toBe(2)
|
|
17
|
+
expect(animal.scale.z).toBe(2)
|
|
18
|
+
})
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
describe('createHerd', () => {
|
|
22
|
+
it('creates exactly count animals inside the grazing area', () => {
|
|
23
|
+
const herd = createHerd({ species: 'cow', count: 9, area: { width: 8, depth: 6 }, center: [3, 0, 4] })
|
|
24
|
+
const animals = herd.children.filter((c) => c.name === 'animal-cow')
|
|
25
|
+
expect(animals).toHaveLength(9)
|
|
26
|
+
|
|
27
|
+
// local positions are inside the area box, world positions shifted by center
|
|
28
|
+
for (const a of animals) {
|
|
29
|
+
expect(Math.abs(a.position.x)).toBeLessThanOrEqual(8 / 2)
|
|
30
|
+
expect(Math.abs(a.position.z)).toBeLessThanOrEqual(6 / 2)
|
|
31
|
+
}
|
|
32
|
+
expect(herd.position.x).toBe(3)
|
|
33
|
+
expect(herd.position.z).toBe(4)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('is deterministic for the same seed', () => {
|
|
37
|
+
const a = createHerd({ species: 'sheep', count: 5, seed: 9 })
|
|
38
|
+
const b = createHerd({ species: 'sheep', count: 5, seed: 9 })
|
|
39
|
+
const c = createHerd({ species: 'sheep', count: 5, seed: 10 })
|
|
40
|
+
for (let i = 0; i < a.children.length; i++) {
|
|
41
|
+
const pa = a.children[i]
|
|
42
|
+
const pb = b.children[i]
|
|
43
|
+
if (!pa || !pb) throw new Error(`missing animal ${i}`)
|
|
44
|
+
expect(pb.position.x).toBeCloseTo(pa.position.x)
|
|
45
|
+
expect(pb.position.z).toBeCloseTo(pa.position.z)
|
|
46
|
+
}
|
|
47
|
+
const ca = a.children[0]
|
|
48
|
+
const cc = c.children[0]
|
|
49
|
+
if (!ca || !cc) throw new Error('missing first animal')
|
|
50
|
+
expect(cc.position.x).not.toBeCloseTo(ca.position.x)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('registers the grazing animation when a tick registry is given', () => {
|
|
54
|
+
const registered: Array<(d: number, e: number) => void> = []
|
|
55
|
+
const herd = createHerd({
|
|
56
|
+
species: 'cow',
|
|
57
|
+
count: 3,
|
|
58
|
+
registerTick: (fn) => {
|
|
59
|
+
registered.push(fn)
|
|
60
|
+
return () => {}
|
|
61
|
+
},
|
|
62
|
+
})
|
|
63
|
+
expect(registered).toHaveLength(1)
|
|
64
|
+
|
|
65
|
+
// Stepping the tick runs the graze cycle on every neck without throwing
|
|
66
|
+
const first = herd.children[0]
|
|
67
|
+
expect(first).toBeTruthy()
|
|
68
|
+
const neck = first!.getObjectByName('animal-neck') as THREE.Group
|
|
69
|
+
const tick = registered[0]
|
|
70
|
+
expect(tick).toBeTypeOf('function')
|
|
71
|
+
tick!(0.016, 10)
|
|
72
|
+
expect(typeof neck.rotation.x).toBe('number')
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('tags every animal with the entityId for raycast selection', () => {
|
|
76
|
+
const herd = createHerd({ species: 'chicken', count: 4, entityId: 'zone-poultry' })
|
|
77
|
+
expect(herd.userData.entityId).toBe('zone-poultry')
|
|
78
|
+
for (const child of herd.children) {
|
|
79
|
+
expect(child.userData.entityId).toBe('zone-poultry')
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
})
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import * as THREE from 'three'
|
|
2
|
+
import { createRng, phaseFor } from '../../engine/random'
|
|
3
|
+
import type { WorldTickFn, UnregisterTick } from '../../core/types'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Procedural low-poly farm animals and herds. Each animal pivots at the
|
|
7
|
+
* ground with a named `head` node so the grazing bob (head dips toward the
|
|
8
|
+
* grass and back up) animates without touching the body. Herds scatter
|
|
9
|
+
* deterministically from a seed — same seed, same scene, every time.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type AnimalSpecies = 'cow' | 'sheep' | 'goat' | 'chicken'
|
|
13
|
+
|
|
14
|
+
export interface AnimalOptions {
|
|
15
|
+
species?: AnimalSpecies
|
|
16
|
+
bodyColor?: string
|
|
17
|
+
/** Uniform scale multiplier. */
|
|
18
|
+
scale?: number
|
|
19
|
+
/** Deterministic silhouette seed. */
|
|
20
|
+
seed?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const SPECIES_DEFAULTS: Record<
|
|
24
|
+
AnimalSpecies,
|
|
25
|
+
{ body: string; accent: string; bodyW: number; bodyH: number; bodyD: number; legH: number; headScale: number }
|
|
26
|
+
> = {
|
|
27
|
+
cow: { body: '#f5f0e6', accent: '#3d3630', bodyW: 0.62, bodyH: 0.5, bodyD: 1.05, legH: 0.42, headScale: 1 },
|
|
28
|
+
sheep: { body: '#ece7db', accent: '#4a4038', bodyW: 0.46, bodyH: 0.44, bodyD: 0.72, legH: 0.3, headScale: 0.8 },
|
|
29
|
+
goat: { body: '#cbb8a0', accent: '#6b5a45', bodyW: 0.4, bodyH: 0.42, bodyD: 0.68, legH: 0.36, headScale: 0.75 },
|
|
30
|
+
chicken: { body: '#f8f4ec', accent: '#c2452d', bodyW: 0.2, bodyH: 0.22, bodyD: 0.28, legH: 0.12, headScale: 0.5 },
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function createAnimal(options: AnimalOptions = {}): THREE.Group {
|
|
34
|
+
const { species = 'cow', bodyColor, scale = 1, seed = 1 } = options
|
|
35
|
+
const d = SPECIES_DEFAULTS[species]
|
|
36
|
+
const rng = createRng(seed)
|
|
37
|
+
|
|
38
|
+
const group = new THREE.Group()
|
|
39
|
+
group.name = `animal-${species}`
|
|
40
|
+
|
|
41
|
+
const bodyMat = new THREE.MeshStandardMaterial({
|
|
42
|
+
color: bodyColor ?? d.body,
|
|
43
|
+
roughness: 0.95,
|
|
44
|
+
})
|
|
45
|
+
const accentMat = new THREE.MeshStandardMaterial({ color: d.accent, roughness: 0.9 })
|
|
46
|
+
|
|
47
|
+
// Body — box with slight per-animal size jitter
|
|
48
|
+
const bw = d.bodyW * (0.9 + rng() * 0.2)
|
|
49
|
+
const bh = d.bodyH * (0.9 + rng() * 0.2)
|
|
50
|
+
const bd = d.bodyD * (0.9 + rng() * 0.2)
|
|
51
|
+
const body = new THREE.Mesh(new THREE.BoxGeometry(bw, bh, bd), bodyMat)
|
|
52
|
+
body.position.y = d.legH + bh / 2
|
|
53
|
+
body.castShadow = true
|
|
54
|
+
group.add(body)
|
|
55
|
+
|
|
56
|
+
// Patch on cows / sheep (a darker back patch reads as a breed marker)
|
|
57
|
+
if (species === 'cow' || species === 'sheep') {
|
|
58
|
+
const patch = new THREE.Mesh(
|
|
59
|
+
new THREE.BoxGeometry(bw * 1.02, bh * 0.5, bd * (0.3 + rng() * 0.3)),
|
|
60
|
+
accentMat,
|
|
61
|
+
)
|
|
62
|
+
patch.position.set(0, d.legH + bh * 0.85, (rng() - 0.5) * bd * 0.4)
|
|
63
|
+
group.add(patch)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Head — child of a neck pivot at the front of the body so grazing rotates naturally
|
|
67
|
+
const neck = new THREE.Group()
|
|
68
|
+
neck.name = 'animal-neck'
|
|
69
|
+
neck.position.set(0, d.legH + bh * 0.75, bd / 2)
|
|
70
|
+
group.add(neck)
|
|
71
|
+
|
|
72
|
+
const head = new THREE.Mesh(
|
|
73
|
+
new THREE.BoxGeometry(bw * 0.45 * d.headScale, bh * 0.5 * d.headScale, bw * 0.5 * d.headScale),
|
|
74
|
+
species === 'chicken' ? accentMat : bodyMat,
|
|
75
|
+
)
|
|
76
|
+
head.name = 'animal-head'
|
|
77
|
+
head.position.set(0, bh * 0.15, bw * 0.28 * d.headScale)
|
|
78
|
+
head.castShadow = true
|
|
79
|
+
neck.add(head)
|
|
80
|
+
|
|
81
|
+
if (species === 'chicken') {
|
|
82
|
+
const comb = new THREE.Mesh(
|
|
83
|
+
new THREE.BoxGeometry(bw * 0.12, bh * 0.22, bw * 0.2),
|
|
84
|
+
accentMat,
|
|
85
|
+
)
|
|
86
|
+
comb.position.set(0, bh * 0.42, 0)
|
|
87
|
+
neck.add(comb)
|
|
88
|
+
const beak = new THREE.Mesh(
|
|
89
|
+
new THREE.ConeGeometry(bw * 0.07, bh * 0.22, 4),
|
|
90
|
+
new THREE.MeshStandardMaterial({ color: '#d9a441', roughness: 0.8 }),
|
|
91
|
+
)
|
|
92
|
+
beak.rotation.x = Math.PI / 2
|
|
93
|
+
beak.position.set(0, bh * 0.05, bw * 0.55 * d.headScale)
|
|
94
|
+
neck.add(beak)
|
|
95
|
+
} else {
|
|
96
|
+
// Ears / horns
|
|
97
|
+
for (const side of [-1, 1]) {
|
|
98
|
+
const ear = new THREE.Mesh(
|
|
99
|
+
new THREE.BoxGeometry(bw * 0.12, bh * 0.14, bw * 0.08),
|
|
100
|
+
accentMat,
|
|
101
|
+
)
|
|
102
|
+
ear.position.set(side * bw * 0.25 * d.headScale, bh * 0.28, -bw * 0.05)
|
|
103
|
+
neck.add(ear)
|
|
104
|
+
}
|
|
105
|
+
if (species === 'goat') {
|
|
106
|
+
for (const side of [-1, 1]) {
|
|
107
|
+
const horn = new THREE.Mesh(
|
|
108
|
+
new THREE.ConeGeometry(bw * 0.05, bh * 0.35, 4),
|
|
109
|
+
accentMat,
|
|
110
|
+
)
|
|
111
|
+
horn.position.set(side * bw * 0.14, bh * 0.45, -bw * 0.1)
|
|
112
|
+
horn.rotation.z = side * 0.35
|
|
113
|
+
neck.add(horn)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Legs (chickens get slim cylinder legs; others chunky boxes)
|
|
119
|
+
const legGeo =
|
|
120
|
+
species === 'chicken'
|
|
121
|
+
? new THREE.CylinderGeometry(0.015, 0.015, d.legH, 4)
|
|
122
|
+
: new THREE.BoxGeometry(bw * 0.16, d.legH, bw * 0.16)
|
|
123
|
+
for (const [lx, lz] of [
|
|
124
|
+
[-1, -1],
|
|
125
|
+
[1, -1],
|
|
126
|
+
[-1, 1],
|
|
127
|
+
[1, 1],
|
|
128
|
+
] as const) {
|
|
129
|
+
const leg = new THREE.Mesh(legGeo, accentMat)
|
|
130
|
+
leg.position.set((lx * bw) / 2.6, d.legH / 2, (lz * bd) / 2.25)
|
|
131
|
+
group.add(leg)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Tail
|
|
135
|
+
const tail = new THREE.Mesh(
|
|
136
|
+
new THREE.BoxGeometry(bw * 0.12, bh * 0.3, bw * 0.08),
|
|
137
|
+
species === 'chicken' ? bodyMat : accentMat,
|
|
138
|
+
)
|
|
139
|
+
tail.position.set(0, d.legH + bh * 0.9, -bd / 2 - bw * 0.02)
|
|
140
|
+
tail.name = 'animal-tail'
|
|
141
|
+
group.add(tail)
|
|
142
|
+
|
|
143
|
+
group.scale.setScalar(scale)
|
|
144
|
+
return group
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface HerdOptions {
|
|
148
|
+
species?: AnimalSpecies
|
|
149
|
+
count?: number
|
|
150
|
+
/** Rectangular grazing area in meters, centered on the group origin. */
|
|
151
|
+
area?: { width: number; depth: number }
|
|
152
|
+
center?: [number, number, number]
|
|
153
|
+
/** Coat variations cycled through the herd. */
|
|
154
|
+
bodyColors?: string[]
|
|
155
|
+
scale?: number
|
|
156
|
+
seed?: number
|
|
157
|
+
/** Grazing bob + occasional re-orientation, stepped by the engine loop. */
|
|
158
|
+
registerTick?: (fn: WorldTickFn) => UnregisterTick
|
|
159
|
+
/** Links every animal to one entity for raycast selection. */
|
|
160
|
+
entityId?: string
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function createHerd(options: HerdOptions = {}): THREE.Group {
|
|
164
|
+
const {
|
|
165
|
+
species = 'cow',
|
|
166
|
+
count = 5,
|
|
167
|
+
area = { width: 8, depth: 8 },
|
|
168
|
+
center = [0, 0, 0],
|
|
169
|
+
bodyColors,
|
|
170
|
+
scale = 1,
|
|
171
|
+
seed = 11,
|
|
172
|
+
registerTick,
|
|
173
|
+
entityId,
|
|
174
|
+
} = options
|
|
175
|
+
|
|
176
|
+
const group = new THREE.Group()
|
|
177
|
+
group.name = `herd-${species}`
|
|
178
|
+
group.position.set(center[0], center[1], center[2])
|
|
179
|
+
if (entityId) group.userData = { entityId }
|
|
180
|
+
|
|
181
|
+
const rng = createRng(seed)
|
|
182
|
+
const necks: Array<{ neck: THREE.Group; phase: number; base: number }> = []
|
|
183
|
+
|
|
184
|
+
for (let i = 0; i < count; i++) {
|
|
185
|
+
const animal = createAnimal({
|
|
186
|
+
species,
|
|
187
|
+
seed: seed + i * 17,
|
|
188
|
+
scale: scale * (0.92 + rng() * 0.16),
|
|
189
|
+
bodyColor: bodyColors?.[bodyColors.length > 0 ? i % bodyColors.length : 0],
|
|
190
|
+
})
|
|
191
|
+
animal.position.set(
|
|
192
|
+
(rng() - 0.5) * area.width * 0.86,
|
|
193
|
+
0,
|
|
194
|
+
(rng() - 0.5) * area.depth * 0.86,
|
|
195
|
+
)
|
|
196
|
+
animal.rotation.y = rng() * Math.PI * 2
|
|
197
|
+
if (entityId) animal.userData = { entityId }
|
|
198
|
+
group.add(animal)
|
|
199
|
+
|
|
200
|
+
const neck = animal.getObjectByName('animal-neck') as THREE.Group | null
|
|
201
|
+
if (neck) {
|
|
202
|
+
necks.push({ neck, phase: phaseFor(seed, i), base: neck.rotation.x })
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (registerTick && necks.length > 0) {
|
|
207
|
+
registerTick((_delta, elapsed) => {
|
|
208
|
+
for (const { neck, phase, base } of necks) {
|
|
209
|
+
// Slow graze cycle: head down into the grass, hold, lift, look around
|
|
210
|
+
const cycle = Math.sin(elapsed * 0.55 + phase)
|
|
211
|
+
const look = Math.sin(elapsed * 0.3 + phase * 1.7) * 0.22
|
|
212
|
+
neck.rotation.x = base + Math.max(0, cycle) * 0.75
|
|
213
|
+
neck.rotation.y = look
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return group
|
|
219
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './AnimalBuilder'
|