维雷基亚建筑
- 作者仓库星标 29
- 许可证 MIT
- 作者仓库 r3f-gamedev
- 领域
- 通用
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 94 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @verekia · MIT
- 上下文用量评级
- 中等消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 命令执行
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# Architecture
The core principle of R3F game development is separating game logic from rendering. React components are views, not the source of truth.
## Systems vs Views
**Systems** contain all game logic:
- Movement, physics, collision detection
- Spawning and destroying entities
- State mutations (health, score, timers)
- AI and behavior
- Syncing Three.js objects with entity state
**Views** (React components) only render:
- `<PlayerEntity>`, `<EnemyEntity>` wrap models with `ModelContainer`, process any data needed and pass it as props to the model
- `<PlayerModel>`, `<EnemyModel>` are dumb and only render meshes via props
- They don't contain core game logic, just visuals logic
- No `useFrame` in view components unless it is purely visual and should not be part of the core logic
## Headless-First Mindset
Games should be capable of running entirely without a renderer:
```
┌─────────────────────────────────────────┐
│ Game Logic Layer │
│ (Systems, ECS, World State, Entities) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ View Layer (optional) │
│ React Three Fiber / DOM / Headless │
└─────────────────────────────────────────┘
```
This means:
- All state lives in the world/ECS, not in React components
- Systems iterate over entities and mutate state
- Views subscribe to state and render accordingly
- You could swap R3F for DOM elements or run tests headlessly
## Miniplex: What NOT to Use
**From miniplex-react:**
- `ECS.Entity` - Don't use this component
- `ECS.Component` - Don't use this component
- `ECS.world` - Don't access world through ECS, use direct import
- `useEntities` hook - Don't use this
- Render props pattern - Don't use this
**From miniplex core:**
- `onEntityAdded` / `onEntityRemoved` - Prefer using data and systems to trigger things (e.g., timers, flags)
- `.where()` - Don't use predicate-based filtering, prefer iterating over all entities that have the component no matter its value. For example iterate over all entities that have health and filter out entities that have health < 0 in the system rather than querying entities where health < 0 (which would require reindexing).
## Miniplex: Preferred Methods
Only use these:
- `world.add(entity)` - Add a new entity
- `world.remove(entity)` - Remove an entity
- `world.addComponent(entity, 'component', value)` - Add component to existing entity
- `world.removeComponent(entity, 'component')` - Remove component from entity
- `world.with('prop1', 'prop2')` - Create queries
- `createReactAPI(world)` - Get `Entities` component for rendering
## Entity Types and Queries
```tsx
// lib/ecs.ts
import { World } from 'miniplex'
import createReactAPI from 'miniplex-react'
type Entity = {
position?: { x: number; y: number; z: number }
velocity?: { x: number; y: number; z: number }
isCharacter?: true
isEnemy?: true
three?: Object3D | null
}
export const world = new World<Entity>()
export const characterQuery = world.with('position', 'isCharacter', 'three')
export type CharacterEntity = (typeof characterQuery)['entities'][number]
// Only destructure Entities from React API
export const { Entities } = createReactAPI(world)
```
## ModelContainer Pattern
Capture Three.js object references on entities using a wrapper component, allowing systems to manipulate objects directly.
Similar to the Redux container/component pattern:
- **`*Entity`** components are smart wrappers that connect entity data to the view
- **`*Model`** components are dumb and only responsible for rendering
```
┌─────────────────────────────────────────┐
│ PlayerEntity (smart) │
│ - Wraps with ModelContainer │
│ - Passes entity data as props │
│ │
│ ┌─────────────────────────────────┐ │
│ │ PlayerModel (dumb) │ │
│ │ - Pure rendering │ │
│ │ - Receives props │ │
│ │ - No knowledge of entities │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────────┘
```
- Ref callback stores the Three.js object on the entity
- Cleanup function removes the reference when unmounted
- Systems access `entity.three` directly in `useFrame`
- Models are reusable and testable in isolation
## Entity as Props Pattern
The component passed to `<Entities>` receives the entity directly as props:
```tsx
// Dumb component - only renders, no entity knowledge
const CharacterModel = () => (
<mesh>
<sphereGeometry />
<meshBasicMaterial color="blue" />
</mesh>
)
// Smart wrapper - connects entity to model via ModelContainer
const CharacterEntity = (entity: CharacterEntity) => (
<ModelContainer entity={entity}>
<CharacterModel />
</ModelContainer>
)
// entities/entities.tsx (contains <Entities> for all renderable entities)
const isCharacterQuery = world.with('isCharacter')
export const CharacterEntities = () => <Entities in={isCharacterQuery}>{CharacterEntity}</Entities>
```
## Systems and Queries
### Query Placement
Define queries **near where they are used** (in the system file), not in a central file. But define them **outside the loop** at module scope:
```tsx
import { world } from '@/lib/ecs'
// ✅ Query defined at module scope, near where it's used
const movingEntities = world.with('position', 'velocity')
type MovingEntity = (typeof movingEntities)['entities'][number]
```
### One + System Pattern
Split logic into a **"One" function** (operates on a single entity) and the **system** (iterates and calls One):
```tsx
import { world } from '@/lib/ecs'
// Query at module scope
const movingEntities = world.with('position', 'velocity')
type MovingEntity = (typeof movingEntities)['entities'][number]
// "One" function - single entity logic, easy to test
const velocityOne = (e: MovingEntity, dt: number) => {
e.position.x += e.velocity.x * dt
e.position.y += e.velocity.y * dt
e.position.z += e.velocity.z * dt
}
// System - just iteration
export const VelocitySystem = () => {
useFrame((_, dt) => {
for (const e of movingEntities) {
velocityOne(e, dt)
}
})
return null
}
```
### Query by Components, Not Types
Systems must iterate over queries tailored to their specific needs, not over entity types:
```tsx
// ✅ GOOD - Query targets entities with the components the system needs
const entitiesWithVelocity = world.with('position', 'velocity')
const VelocitySystem = () => {
useFrame((_, delta) => {
for (const entity of entitiesWithVelocity) {
entity.position.x += entity.velocity.x * delta
}
})
return null
}
// ❌ BAD - Iterating over specific entity types
const VelocitySystem = () => {
useFrame((_, delta) => {
for (const player of players) {
/* ... */
}
for (const enemy of enemies) {
/* ... */
}
for (const projectile of projectiles) {
/* ... */
}
})
return null
}
```
The point of an ECS is that systems operate on a subset of entities matching exactly what they need. A `VelocitySystem` targets entities with `velocity`, not "players + enemies + projectiles".
### ThreeSystem - Syncing Three.js
```tsx
const threeEntities = world.with('position', 'three')
type ThreeEntity = (typeof threeEntities)['entities'][number]
const threeOne = (e: ThreeEntity) => {
e.three.position.set(e.position.x, e.position.y, e.position.z)
}
export const ThreeSystem = () => {
useFrame(() => {
for (const e of threeEntities) {
threeOne(e)
}
})
return null
}
```
### Spawning Entities
```tsx
const SpawnSystem = () => {
useEffect(() => {
world.add({ position: { x: 0, y: 0, z: 0 }, isCharacter: true })
}, [])
return null
}
```
## Zustand Store Usage
Zustand stores are for state that doesn't belong in the ECS. Each store has a consistent API pattern:
```tsx
// In React components (reactive)
const areSettingsOpen = useUI('areSettingsOpen')
// Outside React / in systems (non-reactive)
const settings = getUI().areSettingsOpen
// Setting values
setUI('areSettingsOpen', true)
setUI({ areSettingsOpen: true, debug: { drawCalls: 100 } })
// Reset to defaults
resetUI()
```
- `use*` hooks for reactive access in React components
- `get*` for non-reactive access in systems or callbacks
- `set*` supports both single key-value and partial state updates
- `reset*` restores default state
- Attach `get*` to `window` for debugging in browser console
- Use `structuredClone(defaultState)` to avoid mutation issues
## Key Principles
- **R3F imports from WebGPU entry**: Always import from `@react-three/fiber/webgpu`, not `@react-three/fiber`
- **No `useFrame` in view components**: Most `useFrame` calls belong in systems
- **Entity/Model separation**: `*Entity` components are smart wrappers, `*Model` components are dumb renderers
- **Systems sync Three.js**: Systems update both entity state AND `entity.three` positions/rotations
- **Decouple completely**: The game should work if you delete all view components
- **Query by components, not types**: Systems iterate over queries based on required components
- **World and queries are plain module exports**: Not React context
- **`<Entities>` is the only React bridge**: Only use this from miniplex-react
- **Derive typed entities from queries**: `(typeof query)['entities'][number]`
- **Define queries near where they're used**: In the system file, at module scope
- **Split system logic**: "One" function for single entity, System for iteration
---
This skill is part of [verekia](https://x.com/verekia)'s [**r3f-gamedev**](https://github.com/verekia/r3f-gamedev).
章节与文件索引
按说明文件中的顺序排列。
系统与视图
无头第一的心态
Miniplex:不该使用什么
Miniplex:首选方法
模型容器模式
文件/命令 -> <PlayerEntity> · <EnemyEntity> · ModelContainer · <PlayerModel> · <EnemyModel> · useFrame · ECS.Entity · ECS.Component
内容校验值 -> 63915e5aa260
当前原文的自动摘译,尚未人工审校。
系统与视图
系统包含所有游戏逻辑: 运动、物理、碰撞检测 生成和摧毁实体 状态突变(生命值、分数、计时器) AI 和行为
无头第一的心态
游戏应该能够完全在没有渲染器的情况下运行:这意味着: 所有状态都存在于世界/ECS 中,而不是存在于 React 组件中 系统迭代实体并改变状态 视图订阅状态并相应地渲染
Miniplex:不该使用什么
来自 miniplex-react:
ECS.Entity- 不要使用这个组件ECS.Component- 不要使用这个组件ECS.world- 不要通过 ECS 访问世界,使用直接导入useEntities钩子 - 不要使用这个Miniplex:首选方法
仅使用这些:
world.add(entity)- 添加新实体world.remove(entity)- 删除实体world.addComponent(entity, 'component', value)- 将组件添加到现有实体world.removeComponent(entity, 'component')- 从实体中删除组件模型容器模式
使用包装器组件捕获实体上的 Three.js 对象引用,从而允许系统直接操作对象。与 Redux 容器/组件模式类似:
*Entity组件是将实体数据连接到视图的智能包装器*Model组件是哑的,只负责渲染 Ref 回调将 Three.js 对象存储在实体上