Compare commits
59 Commits
9fdf065c1d
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 4e8a68b04a | |||
| b997f576c5 | |||
| 20142b7e5f | |||
| 2b6b045f4a | |||
| 29cd03fc21 | |||
| 7c5d7f3834 | |||
| 93744b15f7 | |||
| 359417ecd4 | |||
| 9ada4298c3 | |||
| 9b8bb1a182 | |||
| a8c6fafbcd | |||
| 14a55e8dd1 | |||
| 2dd5bfeda1 | |||
| e20ead88e1 | |||
| 7e99d455b4 | |||
| 8c6af0ed6d | |||
| 324aa9dc0f | |||
| 356bb5ef88 | |||
| ece9b1268f | |||
| d2735b72a0 | |||
| fc5e4acba4 | |||
| a3db0b2f0d | |||
| f9a0480121 | |||
| aa7db176e6 | |||
| 0f83f57e23 | |||
| d4e7edaa89 | |||
| ab21df18cb | |||
| 7e067ecccd | |||
| 3fac43d5f1 | |||
| abfbb284f5 | |||
| 7588f7f736 | |||
| 5ff5b89302 | |||
| af35150452 | |||
| 31a99902dd | |||
| a259c3d2e2 | |||
| e19cc72ad5 | |||
| e1d2bfdc75 | |||
| 8f40bb8133 | |||
| 7b38f04a0d | |||
| eade051241 | |||
| e868e72402 | |||
| 4783784fb3 | |||
| bfe8c49323 | |||
| 1a91fcaca0 | |||
| 055e7b2e63 | |||
| 21d91f1de1 | |||
| 68b0ceb593 | |||
| 868f7a1cfd | |||
| 7fd39f58d8 | |||
| 2001955625 | |||
| 3254291ba7 | |||
| 753a767662 | |||
| bcf3a63fc5 | |||
| ab8c84e006 | |||
| 8abc69ebc3 | |||
| b63412de13 | |||
| 6b8ba3d58d | |||
| d0cf876372 | |||
| fd7571fbe1 |
@@ -74,12 +74,12 @@ jobs:
|
||||
|
||||
- name: 📏 Check bundle size
|
||||
run: |
|
||||
# Get bundle size in KB
|
||||
SIZE=$(du -k dist | cut -f1)
|
||||
# Check generated app assets only; public/ model files are runtime assets copied to dist.
|
||||
SIZE=$(du -k dist/assets | cut -f1)
|
||||
echo "Bundle size: ${SIZE}KB"
|
||||
|
||||
# Threshold: 1000KB (configurable)
|
||||
THRESHOLD=1000
|
||||
# Threshold: 5000KB (configurable)
|
||||
THRESHOLD=5000
|
||||
|
||||
if [ "$SIZE" -gt "$THRESHOLD" ]; then
|
||||
echo "❌ Bundle size ${SIZE}KB exceeds threshold ${THRESHOLD}KB"
|
||||
|
||||
+6
-1
@@ -37,4 +37,9 @@ Thumbs.db
|
||||
|
||||
# 3D Assets Cache (drei, GLTFJSX)
|
||||
.drei/
|
||||
.glitchdrei-cache/
|
||||
.glitchdrei-cache/
|
||||
|
||||
# Temporaire
|
||||
.backend/
|
||||
backend/
|
||||
temp/
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
# Animation & 3D Model System
|
||||
|
||||
This document describes how to use the 3D model components and animation system in La-Fabrik.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Model Types Overview](#model-types-overview)
|
||||
2. [SimpleModel - Static Models](#simplemodel---static-models)
|
||||
3. [AnimatedModel - Animated Models](#animatedmodel---animated-models)
|
||||
4. [Animation Control](#animation-control)
|
||||
5. [Other 3D Components](#other-3d-components)
|
||||
6. [Technical Notes](#technical-notes)
|
||||
|
||||
---
|
||||
|
||||
## Model Types Overview
|
||||
|
||||
The project provides three main types of model instantiation:
|
||||
|
||||
| Type | Component | Use Case |
|
||||
| ----------- | -------------------------------------------------------- | -------------------------------------------- |
|
||||
| Static | `SimpleModel` | Props, decoration, objects without animation |
|
||||
| Animated | `AnimatedModel` | Characters, animated objects with skeleton |
|
||||
| Interactive | `GrabbableObject`, `TriggerObject`, `InteractableObject` | Objects player can interact with |
|
||||
|
||||
---
|
||||
|
||||
## SimpleModel - Static Models
|
||||
|
||||
Use for GLTF models **without** skeleton/armature and no animations.
|
||||
|
||||
```tsx
|
||||
import { SimpleModel } from "@/components/3d";
|
||||
|
||||
<SimpleModel
|
||||
modelPath="/models/elecsimple/model.gltf"
|
||||
position={[0, 0, -5]}
|
||||
rotation={[0, 45, 0]}
|
||||
scale={1}
|
||||
castShadow={true}
|
||||
receiveShadow={true}
|
||||
/>;
|
||||
```
|
||||
|
||||
### Props
|
||||
|
||||
| Prop | Type | Default | Description |
|
||||
| --------------- | ------------------------ | ----------- | --------------------------------- |
|
||||
| `modelPath` | `string` | required | Path to GLTF file in `/public` |
|
||||
| `position` | `Vector3Tuple` | `[0, 0, 0]` | World position [x, y, z] |
|
||||
| `rotation` | `Vector3Tuple` | `[0, 0, 0]` | Rotation in degrees [x, y, z] |
|
||||
| `scale` | `number \| Vector3Tuple` | `1` | Scale factor or [x, y, z] |
|
||||
| `castShadow` | `boolean` | `true` | Enable shadow casting |
|
||||
| `receiveShadow` | `boolean` | `true` | Enable shadow receiving |
|
||||
| `children` | `ReactNode` | - | Child components to render inside |
|
||||
|
||||
---
|
||||
|
||||
## AnimatedModel - Animated Models
|
||||
|
||||
Use for GLTF models **with** skeleton/armature and animations (like Mixamo characters).
|
||||
|
||||
```tsx
|
||||
import { AnimatedModel, useAnimatedModel } from "@/components/3d";
|
||||
|
||||
// Basic usage
|
||||
<AnimatedModel
|
||||
modelPath="/models/elec/model.gltf"
|
||||
defaultAnimation="Idle"
|
||||
position={[0, 0, -5]}
|
||||
rotation={[0, 0, 0]}
|
||||
scale={0.01}
|
||||
autoPlay={true}
|
||||
speed={1}
|
||||
fadeDuration={0.3}
|
||||
/>;
|
||||
```
|
||||
|
||||
### Props
|
||||
|
||||
| Prop | Type | Default | Description |
|
||||
| ------------------ | ------------------------ | ----------- | --------------------------------------------- |
|
||||
| `modelPath` | `string` | required | Path to GLTF file in `/public` |
|
||||
| `defaultAnimation` | `string` | `"Idle"` | Animation name to play by default |
|
||||
| `animations` | `string[]` | `[]` | List of animation names (optional) |
|
||||
| `position` | `Vector3Tuple` | `[0, 0, 0]` | World position [x, y, z] |
|
||||
| `rotation` | `Vector3Tuple` | `[0, 0, 0]` | Rotation in degrees [x, y, z] |
|
||||
| `scale` | `number \| Vector3Tuple` | `1` | Scale factor |
|
||||
| `autoPlay` | `boolean` | `true` | Auto-play default animation |
|
||||
| `speed` | `number` | `1` | Animation playback speed |
|
||||
| `fadeDuration` | `number` | `0.3` | Transition duration in seconds |
|
||||
| `onLoaded` | `() => void` | - | Callback when model loads |
|
||||
| `onAnimationEnd` | `(name: string) => void` | - | Callback when animation ends |
|
||||
| `children` | `ReactNode` | - | Child components (can use `useAnimatedModel`) |
|
||||
|
||||
### Important: Scale
|
||||
|
||||
Animated models (like Mixamo exports) often need a small scale (e.g., `0.01`) because they are exported in meters while Three.js uses different units. Adjust until the model appears at the right size.
|
||||
|
||||
---
|
||||
|
||||
## Animation Control
|
||||
|
||||
To control animations from inside or outside the `AnimatedModel`, use the `useAnimatedModel` hook.
|
||||
|
||||
### Basic Control
|
||||
|
||||
```tsx
|
||||
import { AnimatedModel, useAnimatedModel } from "@/components/3d";
|
||||
|
||||
// Create a controller component to use inside AnimatedModel
|
||||
function AnimationController() {
|
||||
const { play, stop, fadeTo, currentAnimation, names, setSpeed, isReady } =
|
||||
useAnimatedModel();
|
||||
|
||||
// names contains all available animation names
|
||||
// currentAnimation is the name of the currently playing animation
|
||||
// isReady is true when model and animations are loaded
|
||||
|
||||
return (
|
||||
<mesh onClick={() => play("Run", 0.5)}>
|
||||
<boxGeometry />
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
// Usage
|
||||
<AnimatedModel
|
||||
modelPath="/models/elec/model.gltf"
|
||||
defaultAnimation="Idle"
|
||||
position={[0, 0, -5]}
|
||||
scale={0.01}
|
||||
>
|
||||
<AnimationController />
|
||||
</AnimatedModel>;
|
||||
```
|
||||
|
||||
### Available Methods
|
||||
|
||||
| Method | Signature | Description |
|
||||
| ------------------ | --------------------------------------- | ------------------------------------ |
|
||||
| `play` | `(name: string, fade?: number) => void` | Play animation with optional fade |
|
||||
| `fadeTo` | `(name: string, fade?: number) => void` | Fade to another animation |
|
||||
| `stop` | `(fade?: number) => void` | Stop and return to default animation |
|
||||
| `setSpeed` | `(speed: number) => void` | Set animation speed |
|
||||
| `currentAnimation` | `string` | Current animation name (getter) |
|
||||
| `names` | `string[]` | Available animation names |
|
||||
| `isReady` | `boolean` | Whether model is loaded |
|
||||
|
||||
### Transition Example
|
||||
|
||||
```tsx
|
||||
function Character() {
|
||||
const { play, fadeTo, currentAnimation } = useAnimatedModel();
|
||||
|
||||
const handleWalk = () => fadeTo("Walk", 0.5); // 0.5s fade
|
||||
const handleRun = () => play("Run", 0.3); // 0.3s fade
|
||||
const handleIdle = () => play("Idle", 0.5); // return to idle
|
||||
|
||||
return (
|
||||
<group>
|
||||
<mesh onClick={handleWalk} position={[-1, 0, 0]}>
|
||||
<boxGeometry />
|
||||
</mesh>
|
||||
<mesh onClick={handleRun} position={[0, 0, 0]}>
|
||||
<boxGeometry />
|
||||
</mesh>
|
||||
<mesh onClick={handleIdle} position={[1, 0, 0]}>
|
||||
<boxGeometry />
|
||||
</mesh>
|
||||
</group>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Combined: GrabbableObject with Animation
|
||||
|
||||
You can combine `AnimatedModel` inside `GrabbableObject` to create animated objects that can be picked up:
|
||||
|
||||
```tsx
|
||||
import { AnimatedModel, GrabbableObject } from "@/components/3d";
|
||||
|
||||
// Animated weapon/tool that player can pick up
|
||||
<GrabbableObject position={[0, 1, 0]} colliders="cuboid">
|
||||
<AnimatedModel
|
||||
modelPath="/models/sword/model.gltf"
|
||||
defaultAnimation="Idle"
|
||||
position={[0, 0, 0]}
|
||||
scale={0.02}
|
||||
autoPlay={true}
|
||||
/>
|
||||
</GrabbableObject>;
|
||||
```
|
||||
|
||||
Or create an animated character that can be grabbed:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
AnimatedModel,
|
||||
GrabbableObject,
|
||||
useAnimatedModel,
|
||||
} from "@/components/3d";
|
||||
|
||||
// Controller that triggers animations when grabbed
|
||||
function AnimatedGrabber() {
|
||||
const { play, fadeTo } = useAnimatedModel();
|
||||
|
||||
return (
|
||||
<AnimatedModel
|
||||
modelPath="/models/elec/model.gltf"
|
||||
defaultAnimation="Idle"
|
||||
position={[0, 0, 0]}
|
||||
scale={0.01}
|
||||
autoPlay={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// When grabbed, play "Grab" animation
|
||||
<GrabbableObject
|
||||
position={[0, 1, 0]}
|
||||
colliders="cuboid"
|
||||
onGrab={() => {
|
||||
// This would require a context or store to trigger
|
||||
console.log("Object grabbed!");
|
||||
}}
|
||||
>
|
||||
<AnimatedGrabber />
|
||||
</GrabbableObject>;
|
||||
```
|
||||
|
||||
**Note:** For complex interactions (like playing specific animations when grabbing), you'll need to connect the grab events to animation controls via a state manager or context.
|
||||
|
||||
---
|
||||
|
||||
## Other 3D Components
|
||||
|
||||
### GrabbableObject
|
||||
|
||||
Objects that can be picked up by the player.
|
||||
|
||||
```tsx
|
||||
import { GrabbableObject } from "@/components/3d";
|
||||
|
||||
<GrabbableObject position={[0, 1, 0]} colliders="cuboid">
|
||||
<mesh>
|
||||
<boxGeometry args={[0.5, 0.5, 0.5]} />
|
||||
<meshStandardMaterial color="red" />
|
||||
</mesh>
|
||||
</GrabbableObject>;
|
||||
```
|
||||
|
||||
### TriggerObject
|
||||
|
||||
Objects that trigger events when interacted with.
|
||||
|
||||
```tsx
|
||||
import { TriggerObject } from "@/components/3d";
|
||||
|
||||
<TriggerObject
|
||||
position={[0, 1, 0]}
|
||||
soundPath="/sounds/click.mp3"
|
||||
onTrigger={() => console.log("Triggered!")}
|
||||
>
|
||||
<mesh>
|
||||
<sphereGeometry />
|
||||
<meshStandardMaterial color="blue" />
|
||||
</mesh>
|
||||
</TriggerObject>;
|
||||
```
|
||||
|
||||
### InteractableObject
|
||||
|
||||
Base object for interactions.
|
||||
|
||||
```tsx
|
||||
import { InteractableObject } from "@/components/3d";
|
||||
|
||||
<InteractableObject
|
||||
position={[0, 1, 0]}
|
||||
onInteract={() => console.log("Interacted!")}
|
||||
>
|
||||
<mesh>
|
||||
<cylinderGeometry />
|
||||
<meshStandardMaterial color="green" />
|
||||
</mesh>
|
||||
</InteractableObject>;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Technical Notes
|
||||
|
||||
### GLTF Models
|
||||
|
||||
- Models should be placed in `/public/models/`
|
||||
- Supported formats: `.gltf`, `.glb`
|
||||
- Animated models must have an Armature/skeleton for animations to work
|
||||
|
||||
### Model Scale Issue
|
||||
|
||||
If animated models don't appear, they may be too small or too large. Try:
|
||||
|
||||
- Scale `0.01` for Mixamo-exported models
|
||||
- Scale `1` for models in correct units
|
||||
|
||||
### Cloning
|
||||
|
||||
- `SimpleModel` uses `scene.clone()` for proper React lifecycle
|
||||
- `AnimatedModel` uses the original scene directly to preserve SkinnedMesh + Armature structure
|
||||
|
||||
### Animation System
|
||||
|
||||
The animation system uses:
|
||||
|
||||
- `@react-three/drei`: `useGLTF` for loading, `useAnimations` for animation control
|
||||
- Three.js: `AnimationMixer` for playback
|
||||
|
||||
### No State Machine
|
||||
|
||||
This system intentionally avoids complex state machines (like Unity's Animator). For simple animation transitions, use the `play`, `fadeTo`, and `stop` methods directly.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/3d/
|
||||
│ ├── AnimatedModel.tsx # Animated model component + context
|
||||
│ ├── SimpleModel.tsx # Static model component
|
||||
│ ├── GrabbableObject.tsx # Pickable object
|
||||
│ ├── TriggerObject.tsx # Trigger event object
|
||||
│ ├── InteractableObject.tsx
|
||||
│ └── index.ts # Central exports
|
||||
└── hooks/
|
||||
└── useCharacterAnimation.ts # Animation hook (legacy)
|
||||
```
|
||||
@@ -4,13 +4,16 @@ This document describes the code that exists today in the repository.
|
||||
|
||||
## Runtime Structure
|
||||
|
||||
- `src/App.tsx` mounts the `Canvas`, the 3D `World`, the debug perf overlay, and the HTML overlays.
|
||||
- `src/main.tsx` mounts React and wraps the app in `BrowserRouter`.
|
||||
- `src/App.tsx` declares the top-level routes:
|
||||
- `/` mounts the playable 3D scene, debug perf overlay, and HTML overlays.
|
||||
- `/editor` mounts the map editor page.
|
||||
- `src/world/World.tsx` composes the active scene, including:
|
||||
- environment and lighting
|
||||
- debug helpers and debug camera mode
|
||||
- either the map scene or the debug physics test scene
|
||||
- the player rig when the active camera mode is `player`
|
||||
- `src/world/Map.tsx` loads the main map model and builds the collision octree.
|
||||
- `src/world/GameMap.tsx` loads map nodes from `public/map.json`, resolves available models, and builds the collision octree.
|
||||
- `src/world/debug/TestScene.tsx` provides a debug-oriented interaction and physics scene.
|
||||
- `src/world/player/PlayerComponent.tsx` mounts the camera and controller.
|
||||
- `src/world/player/PlayerController.tsx` owns pointer lock movement, jump handling, and interaction input.
|
||||
@@ -38,10 +41,31 @@ This document describes the code that exists today in the repository.
|
||||
- `src/utils/debug/scene/DebugHelpers.tsx` mounts debug helpers.
|
||||
- `src/utils/debug/scene/DebugCameraControls.tsx` mounts the free debug camera.
|
||||
|
||||
## Editor System
|
||||
|
||||
- `src/pages/editor/EditorPage.tsx` is the route-level editor page for `/editor`.
|
||||
- `src/components/editor/EditorControls.tsx` renders the HTML editor control panel.
|
||||
- `src/components/editor/scene/EditorScene.tsx` composes the editor canvas scene, camera controls, lights, shortcuts, and map rendering.
|
||||
- `src/components/editor/scene/EditorMap.tsx` renders map nodes, fallback cubes, selection highlighting, and transform controls.
|
||||
- `src/controls/editor/FlyController.tsx` provides player-style editor navigation.
|
||||
- `src/hooks/editor/useEditorSceneData.ts` loads scene data and handles folder upload fallback.
|
||||
- `src/hooks/editor/useEditorHistory.ts` owns editor undo and redo state.
|
||||
- `src/utils/editor/loadEditorScene.ts` handles editor-only folder upload parsing.
|
||||
- `src/utils/loadMapSceneData.ts` is shared by the game scene and editor to load `public/map.json` and resolve model URLs.
|
||||
- `src/types/editor.ts` contains the shared `MapNode`, `SceneData`, and `TransformMode` types.
|
||||
|
||||
## Map Data
|
||||
|
||||
- `public/map.json` is expected to be a `MapNode[]`.
|
||||
- Each map node `name` maps to `public/models/{name}/model.gltf`.
|
||||
- The editor renders a fallback cube for missing models.
|
||||
- The game scene filters out nodes whose model cannot be resolved.
|
||||
|
||||
## Current Limitations
|
||||
|
||||
- The repository is still a prototype, not the full intended game runtime.
|
||||
- `src/world/debug/TestScene.tsx` is still part of the active scene composition.
|
||||
- There is no central gameplay orchestrator such as `GameManager` yet.
|
||||
- The repository is a prototype, not the full intended game runtime.
|
||||
- `src/world/debug/TestScene.tsx` is part of the active scene composition.
|
||||
- There is no central gameplay orchestrator such as `GameManager`.
|
||||
- Missions, zones, cinematics, and dialogue systems are not implemented.
|
||||
- The player uses octree collision and simple movement rules, not a complete gameplay physics stack.
|
||||
- Editor save-to-server is implemented as a Vite dev-server plugin, not a production backend API.
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# Editor Technical Notes
|
||||
|
||||
This document describes the map editor that exists in the current codebase.
|
||||
|
||||
## Purpose
|
||||
|
||||
The editor is a React route used to inspect and adjust the `public/map.json` scene data from inside the La-Fabrik app. It shares the same `MapNode` data format as the game scene and uses React Three Fiber for rendering.
|
||||
|
||||
## Routing
|
||||
|
||||
- `/` renders the playable La-Fabrik scene.
|
||||
- `/editor` renders the map editor.
|
||||
- `src/App.tsx` mounts TanStack Router through `RouterProvider`.
|
||||
- `src/router.tsx` defines the `/editor` route and imports `EditorPage` from `src/pages/editor/page.tsx`.
|
||||
|
||||
## File Structure
|
||||
|
||||
```txt
|
||||
src/
|
||||
├── pages/
|
||||
│ └── editor/
|
||||
│ └── page.tsx
|
||||
├── components/
|
||||
│ └── editor/
|
||||
│ ├── EditorControls.tsx
|
||||
│ └── scene/
|
||||
│ ├── EditorMap.tsx
|
||||
│ └── EditorScene.tsx
|
||||
├── controls/
|
||||
│ └── editor/
|
||||
│ └── FlyController.tsx
|
||||
├── hooks/
|
||||
│ └── editor/
|
||||
│ ├── useEditorHistory.ts
|
||||
│ └── useEditorSceneData.ts
|
||||
├── types/
|
||||
│ └── editor.ts
|
||||
└── utils/
|
||||
├── editor/
|
||||
│ └── loadEditorScene.ts
|
||||
└── loadMapSceneData.ts
|
||||
```
|
||||
|
||||
## Responsibilities
|
||||
|
||||
`src/pages/editor/page.tsx` is the route-level composition component. It owns route-specific state such as selected object, hovered object, transform mode, and player-mode toggle.
|
||||
|
||||
`src/hooks/editor/useEditorSceneData.ts` loads the default map data and handles folder uploads.
|
||||
|
||||
`src/hooks/editor/useEditorHistory.ts` owns editor undo and redo history.
|
||||
|
||||
`src/components/editor/scene/EditorScene.tsx` composes the editor canvas scene, camera controls, lights, keyboard shortcuts, and `EditorMap`.
|
||||
|
||||
`src/components/editor/scene/EditorMap.tsx` renders map nodes, fallback cubes, selection highlighting, and transform controls.
|
||||
|
||||
`src/components/editor/EditorControls.tsx` renders the HTML control panel outside the canvas.
|
||||
|
||||
`src/controls/editor/FlyController.tsx` provides editor movement controls for player-style navigation.
|
||||
|
||||
`src/utils/loadMapSceneData.ts` is shared by the game map and editor. It loads `/map.json` and resolves available `public/models/{name}/model.gltf` files.
|
||||
|
||||
`src/utils/editor/loadEditorScene.ts` contains editor-only upload handling for user-selected folders.
|
||||
|
||||
## Data Format
|
||||
|
||||
The shared editor type lives in `src/types/editor.ts`.
|
||||
|
||||
```ts
|
||||
interface MapNode {
|
||||
name: string;
|
||||
type: string;
|
||||
position: [number, number, number];
|
||||
rotation: [number, number, number];
|
||||
scale: [number, number, number];
|
||||
}
|
||||
```
|
||||
|
||||
`public/map.json` is expected to be a `MapNode[]`.
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "pylone",
|
||||
"type": "Mesh",
|
||||
"position": [0, 5, 0],
|
||||
"rotation": [0, 1.57, 0],
|
||||
"scale": [1, 1, 1]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Each node `name` maps to a model folder:
|
||||
|
||||
```txt
|
||||
public/
|
||||
├── map.json
|
||||
└── models/
|
||||
└── pylone/
|
||||
└── model.gltf
|
||||
```
|
||||
|
||||
If a model is missing, the editor renders a fallback cube so the node can still be selected and transformed.
|
||||
|
||||
## Editor Flow
|
||||
|
||||
1. `EditorPage` mounts on `/editor`.
|
||||
2. `useEditorSceneData` calls `loadMapSceneData()`.
|
||||
3. `loadMapSceneData()` loads `/map.json` and available model URLs.
|
||||
4. If `/map.json` is missing, the page displays a folder-upload flow.
|
||||
5. `EditorScene` renders the grid, lights, camera controls, and map nodes.
|
||||
6. `EditorControls` exposes transform mode, history actions, export, save, and selection info.
|
||||
|
||||
## Controls
|
||||
|
||||
- Click: select a node.
|
||||
- `Esc`: clear selection.
|
||||
- `T`: translate mode.
|
||||
- `R`: rotate mode.
|
||||
- `S`: scale mode.
|
||||
- `Ctrl+Z` or `Cmd+Z`: undo.
|
||||
- `Ctrl+Y` or `Cmd+Y`: redo.
|
||||
- `WASD`, `ZQSD`, or arrow keys: move in player-controller mode.
|
||||
- `Space`: move upward in player-controller mode.
|
||||
- `Shift`: move downward in player-controller mode.
|
||||
|
||||
## Saving And Exporting
|
||||
|
||||
The editor supports two output paths:
|
||||
|
||||
- Export JSON downloads the current `MapNode[]` as `map.json`.
|
||||
- Save to Server posts the current `MapNode[]` to `/api/save-map`.
|
||||
|
||||
The dev-only `/api/save-map` endpoint is implemented by the Vite plugin in `vite.config.ts`. It writes to `public/map.json` and enforces a maximum payload size.
|
||||
|
||||
## Styling
|
||||
|
||||
Editor styles are in `src/index.css` under the `/* Editor page */` section. Classes are prefixed with `editor-` to avoid collisions with the game UI.
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- Uploaded model object URLs are not currently revoked after replacement or unmount.
|
||||
- Large `map.json` files are not virtualized, culled, or LOD-managed.
|
||||
- There is no snap-to-grid, duplication, material editing, or object creation workflow.
|
||||
- Save to Server is a Vite dev-server helper, not a production backend API.
|
||||
@@ -5,7 +5,7 @@ This document describes the intended medium-term architecture for the project.
|
||||
## Relationship To The Current Code
|
||||
|
||||
- `docs/technical/architecture.md` is the source of truth for what exists now.
|
||||
- This document is intentionally aspirational.
|
||||
- This document describes intended direction, not implemented behavior.
|
||||
- If this document conflicts with the current implementation, the current implementation wins.
|
||||
|
||||
## Goals
|
||||
@@ -40,12 +40,12 @@ This document describes the intended medium-term architecture for the project.
|
||||
- performance overlay
|
||||
- scene helpers
|
||||
- free camera and calibration controls
|
||||
- temporary test scenes used during development
|
||||
- debug test scenes used during development
|
||||
|
||||
### UI Layer
|
||||
|
||||
- `src/components/ui/` should contain player-facing HTML overlays.
|
||||
- Expected future examples:
|
||||
- Candidate examples:
|
||||
- crosshair
|
||||
- loading flow
|
||||
- mission HUD
|
||||
@@ -54,7 +54,7 @@ This document describes the intended medium-term architecture for the project.
|
||||
### Gameplay Layer
|
||||
|
||||
- As the project grows, gameplay state can move toward a clearer orchestration layer.
|
||||
- Likely future concerns:
|
||||
- Likely concerns:
|
||||
- missions
|
||||
- zones
|
||||
- cinematics
|
||||
@@ -67,4 +67,4 @@ This document describes the intended medium-term architecture for the project.
|
||||
- Prefer direct, working code over speculative scaffolding.
|
||||
- Shared types should stay close to their domain until they have multiple real consumers.
|
||||
- Avoid creating new managers or service layers without an active runtime need.
|
||||
- Debug-only runtime paths should be clearly marked and easy to remove later.
|
||||
- Debug-only runtime paths should be clearly marked and easy to remove when obsolete.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Editor User Guide
|
||||
|
||||
The map editor is available at `/editor`. It is a browser-based tool for inspecting and adjusting the objects listed in `public/map.json`.
|
||||
|
||||
## Purpose
|
||||
|
||||
Use the editor when you need to move, rotate, or scale existing map objects without editing JSON by hand.
|
||||
|
||||
The editor reads the same map data as the runtime scene:
|
||||
|
||||
- `public/map.json` contains the object list.
|
||||
- `public/models/{name}/model.gltf` contains the matching 3D model for each object name.
|
||||
- Missing models are displayed as gray fallback cubes, so incomplete maps remain editable.
|
||||
|
||||
## Map Node Format
|
||||
|
||||
Each entry in `public/map.json` represents one object:
|
||||
|
||||
| Field | Description |
|
||||
| ---------- | ------------------------------------------------- |
|
||||
| `name` | Model folder name in `public/models/{name}` |
|
||||
| `type` | Object category |
|
||||
| `position` | Object position as `[x, y, z]` |
|
||||
| `rotation` | Object rotation as `[x, y, z]`, expressed radians |
|
||||
| `scale` | Object scale as `[x, y, z]` |
|
||||
|
||||
## Editing Workflow
|
||||
|
||||
1. Open `/editor` in the local app.
|
||||
2. Click an object in the scene to select it.
|
||||
3. Choose a transform mode: translate, rotate, or scale.
|
||||
4. Drag the transform gizmo in the 3D view.
|
||||
5. Check the JSON inspector if you need exact values.
|
||||
6. Use undo or redo if the transform is not correct.
|
||||
7. Export the JSON or save it to the dev server.
|
||||
|
||||
## Controls
|
||||
|
||||
| Action | Input |
|
||||
| -------------------- | -------------------------- |
|
||||
| Select object | Click object |
|
||||
| Deselect | `Esc` or click empty space |
|
||||
| Translate mode | `T` |
|
||||
| Rotate mode | `R` |
|
||||
| Scale mode | `S` |
|
||||
| Undo | `Ctrl+Z` |
|
||||
| Redo | `Ctrl+Y` |
|
||||
| Locked view movement | `WASD`, `ZQSD`, arrows |
|
||||
| Move up | `Space` |
|
||||
| Move down | `Shift` |
|
||||
|
||||
## View Mode
|
||||
|
||||
The `Lock view` action switches the editor into a movement mode closer to the runtime player camera. Use it to navigate larger scenes while keeping the transform tools available.
|
||||
|
||||
## JSON Inspector
|
||||
|
||||
The side panel includes a raw JSON inspector:
|
||||
|
||||
- When no object is selected, it shows the full map node list.
|
||||
- When an object is selected, it highlights the JSON lines for that object.
|
||||
|
||||
This is useful for checking numeric transform values before saving or exporting.
|
||||
|
||||
## Saving Changes
|
||||
|
||||
### Export JSON
|
||||
|
||||
`Export JSON` downloads the current map node list as `map.json`. Use this when you want to manually replace `public/map.json`.
|
||||
|
||||
### Save To Server
|
||||
|
||||
`Save to server` is available only during local development. It writes the edited map back to `public/map.json` through the Vite dev-server endpoint.
|
||||
|
||||
The button is hidden in production builds because production persistence is not implemented.
|
||||
|
||||
## Current Limitations
|
||||
|
||||
- The editor only modifies existing nodes.
|
||||
- It does not create or delete objects.
|
||||
- It does not edit model files or textures.
|
||||
- It does not provide production persistence.
|
||||
- Fallback cubes indicate missing models; they are editor placeholders, not exported assets.
|
||||
+16
-1
@@ -5,7 +5,7 @@ This document lists features that are implemented in the current codebase.
|
||||
## Scene
|
||||
|
||||
- Fullscreen React Three Fiber scene
|
||||
- Main map scene loaded from `public/models/map/model.gltf`
|
||||
- Main map scene loaded from `public/map.json` and matching `public/models/{name}/model.gltf` assets
|
||||
- Debug physics test scene selectable from the debug panel
|
||||
- Ambient and directional lighting
|
||||
- Environment background setup
|
||||
@@ -38,6 +38,20 @@ This document lists features that are implemented in the current codebase.
|
||||
- Free debug camera
|
||||
- `r3f-perf` overlay
|
||||
|
||||
## Map Editor
|
||||
|
||||
- `/editor` route for inspecting and editing `public/map.json`
|
||||
- Automatic loading of `public/map.json` when available
|
||||
- Folder upload fallback when `map.json` is missing
|
||||
- Rendering of available `public/models/{name}/model.gltf` assets
|
||||
- Fallback cubes for nodes whose model is missing
|
||||
- Object selection by click
|
||||
- Transform modes for translate, rotate, and scale
|
||||
- Keyboard shortcuts for `T`, `R`, `S`, `Esc`, undo, and redo
|
||||
- Player-style navigation mode with `WASD`, `ZQSD`, arrow keys, `Space`, and `Shift`
|
||||
- JSON export for downloading the edited map
|
||||
- Dev-server save endpoint for writing changes back to `public/map.json`
|
||||
|
||||
## Not Implemented Yet
|
||||
|
||||
- mission system
|
||||
@@ -47,3 +61,4 @@ This document lists features that are implemented in the current codebase.
|
||||
- loading flow
|
||||
- minimap and mission HUD
|
||||
- full production separation between gameplay and debug scenes
|
||||
- production backend persistence for editor saves
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
[phases.setup]
|
||||
nixPkgs = ["nodejs"]
|
||||
Generated
+1660
-299
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,9 @@
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20.19.0 || >=22.12.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
@@ -18,11 +21,15 @@
|
||||
"@react-three/fiber": "^9.6.0",
|
||||
"@react-three/postprocessing": "^3.0.4",
|
||||
"@react-three/rapier": "^2.2.0",
|
||||
"@tanstack/react-router": "^1.168.25",
|
||||
"gsap": "^3.15.0",
|
||||
"lil-gui": "^0.21.0",
|
||||
"lucide-react": "^1.11.0",
|
||||
"r3f-perf": "^7.2.3",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"three": "^0.183.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -41,5 +48,10 @@
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.0",
|
||||
"vite": "^8.0.4"
|
||||
},
|
||||
"overrides": {
|
||||
"r3f-perf": {
|
||||
"@react-three/drei": "$@react-three/drei"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4587
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
-18
@@ -1,23 +1,8 @@
|
||||
import { Suspense } from "react";
|
||||
import { Canvas } from "@react-three/fiber";
|
||||
import { Crosshair } from "@/components/ui/Crosshair";
|
||||
import { InteractPrompt } from "@/components/ui/InteractPrompt";
|
||||
import { DebugPerf } from "@/utils/debug/DebugPerf";
|
||||
import { World } from "@/world/World";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { router } from "@/router";
|
||||
|
||||
function App(): React.JSX.Element {
|
||||
return (
|
||||
<>
|
||||
<Canvas camera={{ position: [85, 60, 85], fov: 42 }} shadows>
|
||||
<Suspense fallback={null}>
|
||||
<World />
|
||||
<DebugPerf />
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
<Crosshair />
|
||||
<InteractPrompt />
|
||||
</>
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
+5
-4
@@ -3,17 +3,18 @@ import {
|
||||
DEBUG_CAMERA_DAMPING_FACTOR,
|
||||
DEBUG_CAMERA_MAX_DISTANCE,
|
||||
DEBUG_CAMERA_MIN_DISTANCE,
|
||||
} from "@/data/debugConfig";
|
||||
} from "@/data/debug/debugConfig";
|
||||
import {
|
||||
PLAYER_EYE_HEIGHT,
|
||||
PLAYER_SPAWN_POSITION_GAME,
|
||||
} from "@/data/playerConfig";
|
||||
} from "@/data/player/playerConfig";
|
||||
import type { Vector3Tuple } from "@/types/three";
|
||||
|
||||
const DEBUG_CAMERA_TARGET = [
|
||||
const DEBUG_CAMERA_TARGET: Vector3Tuple = [
|
||||
PLAYER_SPAWN_POSITION_GAME[0],
|
||||
PLAYER_EYE_HEIGHT,
|
||||
PLAYER_SPAWN_POSITION_GAME[2],
|
||||
] as const;
|
||||
];
|
||||
|
||||
export function DebugCameraControls(): React.JSX.Element {
|
||||
return (
|
||||
+1
-1
@@ -5,7 +5,7 @@ import {
|
||||
DEBUG_GRID_SECONDARY_COLOR,
|
||||
DEBUG_GRID_SIZE,
|
||||
DEBUG_GRID_Y,
|
||||
} from "@/data/debugConfig";
|
||||
} from "@/data/debug/debugConfig";
|
||||
import { Debug } from "@/utils/debug/Debug";
|
||||
|
||||
export function DebugHelpers(): React.JSX.Element | null {
|
||||
@@ -0,0 +1,51 @@
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { useDocsLanguage } from "@/hooks/docs/useDocsLanguage";
|
||||
|
||||
interface DocsDocumentProps {
|
||||
title: string;
|
||||
meta: string;
|
||||
content: string;
|
||||
frContent: string;
|
||||
}
|
||||
|
||||
export function DocsDocument({
|
||||
title,
|
||||
meta,
|
||||
content,
|
||||
frContent,
|
||||
}: DocsDocumentProps): React.JSX.Element {
|
||||
const { language, toggleLanguage } = useDocsLanguage();
|
||||
const translatedContent = language === "fr" ? frContent : content;
|
||||
|
||||
return (
|
||||
<div className="docs-content">
|
||||
<header className="docs-content__header">
|
||||
<span>{title}</span>
|
||||
<button
|
||||
className="docs-language-toggle"
|
||||
type="button"
|
||||
onClick={toggleLanguage}
|
||||
aria-label="Changer la langue de la documentation"
|
||||
>
|
||||
<span className={language === "fr" ? "is-active" : undefined}>
|
||||
FR
|
||||
</span>
|
||||
<span className={language === "en" ? "is-active" : undefined}>
|
||||
EN
|
||||
</span>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<article className="docs-section">
|
||||
<div className="docs-section__eyebrow">
|
||||
<span>{title}</span>
|
||||
<span>{meta}</span>
|
||||
</div>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>
|
||||
{translatedContent}
|
||||
</ReactMarkdown>
|
||||
</article>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Link, Outlet } from "@tanstack/react-router";
|
||||
import { Home } from "lucide-react";
|
||||
import { docGroups } from "@/data/docs/docsSections";
|
||||
import { DocsLanguageProvider } from "@/providers/docs/DocsLanguageProvider";
|
||||
|
||||
export function DocsLayout(): React.JSX.Element {
|
||||
return (
|
||||
<DocsLanguageProvider>
|
||||
<main className="docs-page">
|
||||
<aside className="docs-sidebar" aria-label="Documentation">
|
||||
<header className="docs-sidebar__header">
|
||||
<h1>Folders</h1>
|
||||
<Link
|
||||
className="docs-home-link"
|
||||
to="/"
|
||||
aria-label="Retour à l'accueil"
|
||||
>
|
||||
<Home size={18} strokeWidth={2.25} aria-hidden="true" />
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
{docGroups.map((group) => (
|
||||
<section className="docs-nav-group" key={group.label}>
|
||||
<h2>{group.label}</h2>
|
||||
|
||||
{group.sections.map((section) => (
|
||||
<Link
|
||||
activeProps={{
|
||||
className: "docs-nav-item docs-nav-item--active",
|
||||
}}
|
||||
activeOptions={{ exact: true }}
|
||||
className="docs-nav-item"
|
||||
key={section.path}
|
||||
to={section.path}
|
||||
>
|
||||
<span>
|
||||
<strong>{section.title}</strong>
|
||||
<small>{section.subtitle}</small>
|
||||
</span>
|
||||
<span className="docs-nav-item__meta">{section.meta}</span>
|
||||
</Link>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<Outlet />
|
||||
</main>
|
||||
</DocsLanguageProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import {
|
||||
Box,
|
||||
Braces,
|
||||
Download,
|
||||
Expand,
|
||||
Keyboard,
|
||||
Lock,
|
||||
MousePointer2,
|
||||
Move3D,
|
||||
Redo2,
|
||||
RotateCw,
|
||||
Save,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
import type { MapNode, TransformMode } from "@/types/editor";
|
||||
|
||||
interface EditorControlsProps {
|
||||
transformMode: TransformMode;
|
||||
onTransformModeChange: (mode: TransformMode) => void;
|
||||
selectedNodeIndex: number | null;
|
||||
mapNodes: MapNode[];
|
||||
nodesCount: number;
|
||||
selectedNodeName: string | null;
|
||||
undoCount: number;
|
||||
redoCount: number;
|
||||
onUndo: () => void;
|
||||
onRedo: () => void;
|
||||
onExportJson: () => void;
|
||||
onSaveToServer?: (() => void | Promise<void>) | undefined;
|
||||
onPlayerMode?: (() => void) | undefined;
|
||||
isPlayerMode?: boolean;
|
||||
}
|
||||
|
||||
const TRANSFORM_OPTIONS = [
|
||||
{ mode: "translate", label: "Translate", shortcut: "T", Icon: Move3D },
|
||||
{ mode: "rotate", label: "Rotate", shortcut: "R", Icon: RotateCw },
|
||||
{ mode: "scale", label: "Scale", shortcut: "S", Icon: Expand },
|
||||
] as const;
|
||||
|
||||
const EDITOR_SHORTCUTS = [
|
||||
["Click", "Select object"],
|
||||
["T / R / S", "Transform mode"],
|
||||
["Ctrl Z / Y", "Undo / redo"],
|
||||
["Esc", "Deselect"],
|
||||
["WASD", "Move when locked"],
|
||||
] as const;
|
||||
|
||||
export function EditorControls({
|
||||
transformMode,
|
||||
onTransformModeChange,
|
||||
selectedNodeIndex,
|
||||
mapNodes,
|
||||
nodesCount,
|
||||
selectedNodeName,
|
||||
undoCount,
|
||||
redoCount,
|
||||
onUndo,
|
||||
onRedo,
|
||||
onExportJson,
|
||||
onSaveToServer,
|
||||
onPlayerMode,
|
||||
isPlayerMode,
|
||||
}: EditorControlsProps): React.JSX.Element {
|
||||
const viewModeLabel = isPlayerMode ? "View locked" : "Lock view";
|
||||
const jsonPreview = getJsonPreview(mapNodes, selectedNodeIndex);
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside className="editor-controls-panel" aria-label="Editor controls">
|
||||
<header className="editor-panel-header">
|
||||
<span className="editor-panel-kicker">Map Editor</span>
|
||||
<h2>Scene controls</h2>
|
||||
<p>Select an object, choose a transform mode, then drag the gizmo.</p>
|
||||
</header>
|
||||
|
||||
<section
|
||||
className="editor-control-section"
|
||||
aria-labelledby="transform-heading"
|
||||
>
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="transform-heading">Transform</h3>
|
||||
<span>T / R / S</span>
|
||||
</div>
|
||||
|
||||
<div className="editor-transform-buttons">
|
||||
{TRANSFORM_OPTIONS.map(({ mode, label, shortcut, Icon }) => (
|
||||
<button
|
||||
key={mode}
|
||||
className={`editor-transform-button ${transformMode === mode ? "active" : ""}`}
|
||||
onClick={() => onTransformModeChange(mode)}
|
||||
aria-pressed={transformMode === mode}
|
||||
>
|
||||
<Icon size={16} aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
<kbd>{shortcut}</kbd>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="editor-history-buttons">
|
||||
<button
|
||||
className="editor-history-button"
|
||||
onClick={onUndo}
|
||||
disabled={undoCount === 0}
|
||||
>
|
||||
<Undo2 size={15} aria-hidden="true" />
|
||||
Undo
|
||||
<span>{undoCount}</span>
|
||||
</button>
|
||||
<button
|
||||
className="editor-history-button"
|
||||
onClick={onRedo}
|
||||
disabled={redoCount === 0}
|
||||
>
|
||||
<Redo2 size={15} aria-hidden="true" />
|
||||
Redo
|
||||
<span>{redoCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
className="editor-control-section"
|
||||
aria-labelledby="file-heading"
|
||||
>
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="file-heading">File</h3>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="editor-action-button editor-action-button-primary"
|
||||
onClick={onExportJson}
|
||||
>
|
||||
<Download size={16} aria-hidden="true" />
|
||||
Export JSON
|
||||
</button>
|
||||
|
||||
{onSaveToServer && (
|
||||
<button className="editor-action-button" onClick={onSaveToServer}>
|
||||
<Save size={16} aria-hidden="true" />
|
||||
Save to server
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section
|
||||
className="editor-control-section"
|
||||
aria-labelledby="view-heading"
|
||||
>
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="view-heading">View</h3>
|
||||
</div>
|
||||
|
||||
{onPlayerMode && (
|
||||
<button
|
||||
className={`editor-player-button ${isPlayerMode ? "active" : ""}`}
|
||||
onClick={onPlayerMode}
|
||||
aria-pressed={isPlayerMode}
|
||||
>
|
||||
<Lock size={16} aria-hidden="true" />
|
||||
{viewModeLabel}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section
|
||||
className="editor-control-section"
|
||||
aria-labelledby="selection-heading"
|
||||
>
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="selection-heading">Selection</h3>
|
||||
<span>{nodesCount} nodes</span>
|
||||
</div>
|
||||
|
||||
{selectedNodeIndex !== null ? (
|
||||
<div className="editor-selected-info">
|
||||
<Box size={17} aria-hidden="true" />
|
||||
<div>
|
||||
<strong>
|
||||
{selectedNodeName || `Node ${selectedNodeIndex + 1}`}
|
||||
</strong>
|
||||
<span>
|
||||
Index {selectedNodeIndex + 1} of {nodesCount}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="editor-no-selection">
|
||||
<MousePointer2 size={17} aria-hidden="true" />
|
||||
No object selected
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section
|
||||
className="editor-control-section"
|
||||
aria-labelledby="shortcuts-heading"
|
||||
>
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="shortcuts-heading">Shortcuts</h3>
|
||||
<Keyboard size={15} aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
<dl className="editor-shortcuts-list">
|
||||
{EDITOR_SHORTCUTS.map(([keys, description]) => (
|
||||
<div key={keys}>
|
||||
<dt>{keys}</dt>
|
||||
<dd>{description}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section className="editor-json-section" aria-labelledby="json-heading">
|
||||
<div className="editor-section-heading">
|
||||
<h3 id="json-heading">JSON</h3>
|
||||
<span>{jsonPreview.label}</span>
|
||||
</div>
|
||||
|
||||
<pre className="editor-json-view" aria-label={jsonPreview.label}>
|
||||
{jsonPreview.lines.map((line) => (
|
||||
<code
|
||||
key={line.number}
|
||||
className={line.isSelected ? "is-selected" : undefined}
|
||||
>
|
||||
<span>{line.number}</span>
|
||||
{line.content || " "}
|
||||
</code>
|
||||
))}
|
||||
</pre>
|
||||
|
||||
<div className="editor-json-hint">
|
||||
<Braces size={14} aria-hidden="true" />
|
||||
{selectedNodeIndex === null
|
||||
? "Raw map JSON"
|
||||
: `Selected node ${selectedNodeIndex + 1} raw lines`}
|
||||
</div>
|
||||
</section>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface JsonPreviewLine {
|
||||
number: number;
|
||||
content: string;
|
||||
isSelected: boolean;
|
||||
}
|
||||
|
||||
interface JsonPreview {
|
||||
label: string;
|
||||
lines: JsonPreviewLine[];
|
||||
}
|
||||
|
||||
function getJsonPreview(
|
||||
mapNodes: MapNode[],
|
||||
selectedNodeIndex: number | null,
|
||||
): JsonPreview {
|
||||
const { lines, ranges } = formatMapNodesWithRanges(mapNodes);
|
||||
|
||||
if (selectedNodeIndex === null || !ranges[selectedNodeIndex]) {
|
||||
return {
|
||||
label: `${lines.length} raw lines`,
|
||||
lines: lines.map((content, index) => ({
|
||||
number: index + 1,
|
||||
content,
|
||||
isSelected: false,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
const range = ranges[selectedNodeIndex];
|
||||
const selectedLines = lines.slice(range.start - 1, range.end);
|
||||
|
||||
return {
|
||||
label: `Lines ${range.start}-${range.end}`,
|
||||
lines: selectedLines.map((content, index) => ({
|
||||
number: range.start + index,
|
||||
content,
|
||||
isSelected: true,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function formatMapNodesWithRanges(mapNodes: MapNode[]): {
|
||||
lines: string[];
|
||||
ranges: Array<{ start: number; end: number }>;
|
||||
} {
|
||||
const lines = ["["];
|
||||
const ranges: Array<{ start: number; end: number }> = [];
|
||||
|
||||
mapNodes.forEach((node, index) => {
|
||||
const objectLines = JSON.stringify(node, null, 2)
|
||||
.split("\n")
|
||||
.map((line) => ` ${line}`);
|
||||
|
||||
if (index < mapNodes.length - 1) {
|
||||
objectLines[objectLines.length - 1] += ",";
|
||||
}
|
||||
|
||||
const start = lines.length + 1;
|
||||
lines.push(...objectLines);
|
||||
ranges.push({ start, end: lines.length });
|
||||
});
|
||||
|
||||
lines.push("]");
|
||||
|
||||
return { lines, ranges };
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import { useMemo, useRef, useEffect, useState } from "react";
|
||||
import { Grid, TransformControls, useGLTF } from "@react-three/drei";
|
||||
import type { ThreeEvent } from "@react-three/fiber";
|
||||
import * as THREE from "three";
|
||||
|
||||
import type { SceneData, MapNode, TransformMode } from "@/types/editor";
|
||||
|
||||
interface EditorMapProps {
|
||||
sceneData: SceneData;
|
||||
selectedNodeIndex: number | null;
|
||||
onSelectNode: (index: number | null) => void;
|
||||
hoveredNodeIndex: number | null;
|
||||
onHoverNode: (index: number | null) => void;
|
||||
transformMode: TransformMode;
|
||||
onTransformStart: () => void;
|
||||
onTransformEnd: () => void;
|
||||
onNodeTransform: (nodeIndex: number, transform: MapNode) => void;
|
||||
}
|
||||
|
||||
type EditorNodeObjectRef = React.RefObject<Map<number, THREE.Object3D>>;
|
||||
|
||||
interface EditorNodeCommonProps {
|
||||
index: number;
|
||||
node: MapNode;
|
||||
isSelected: boolean;
|
||||
isHovered: boolean;
|
||||
objectsMapRef: EditorNodeObjectRef;
|
||||
onSelectNode: (index: number | null) => void;
|
||||
onHoverNode: (index: number | null) => void;
|
||||
}
|
||||
|
||||
interface EditorNodePointerHandlers {
|
||||
onClick: (event: ThreeEvent<MouseEvent>) => void;
|
||||
onPointerEnter: (event: ThreeEvent<PointerEvent>) => void;
|
||||
onPointerLeave: (event: ThreeEvent<PointerEvent>) => void;
|
||||
}
|
||||
|
||||
function applyNodeTransform(object: THREE.Object3D, node: MapNode): void {
|
||||
object.position.set(...node.position);
|
||||
object.rotation.set(...node.rotation);
|
||||
object.scale.set(...node.scale);
|
||||
}
|
||||
|
||||
function useRegisteredEditorNode(
|
||||
objectRef: React.RefObject<THREE.Object3D | null>,
|
||||
index: number,
|
||||
node: MapNode,
|
||||
objectsMapRef: EditorNodeObjectRef,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const object = objectRef.current;
|
||||
if (object) {
|
||||
applyNodeTransform(object, node);
|
||||
object.userData = { nodeIndex: index, nodeName: node.name };
|
||||
objectsMapRef.current.set(index, object);
|
||||
}
|
||||
|
||||
const currentMap = objectsMapRef.current;
|
||||
const currentIndex = index;
|
||||
return () => {
|
||||
currentMap.delete(currentIndex);
|
||||
};
|
||||
}, [index, node, objectRef, objectsMapRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const object = objectRef.current;
|
||||
if (object) {
|
||||
applyNodeTransform(object, node);
|
||||
}
|
||||
}, [node, objectRef]);
|
||||
}
|
||||
|
||||
function disposeMaterial(material: THREE.Material | THREE.Material[]): void {
|
||||
if (Array.isArray(material)) {
|
||||
material.forEach((item) => item.dispose());
|
||||
return;
|
||||
}
|
||||
|
||||
material.dispose();
|
||||
}
|
||||
|
||||
function cloneHighlightedMaterial(
|
||||
material: THREE.Material | THREE.Material[],
|
||||
color: string,
|
||||
): THREE.Material | THREE.Material[] {
|
||||
if (Array.isArray(material)) {
|
||||
return material.map((item) => cloneHighlightedMaterial(item, color)).flat();
|
||||
}
|
||||
|
||||
const clone = material.clone();
|
||||
if (clone instanceof THREE.MeshStandardMaterial) {
|
||||
clone.color.set(color);
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
|
||||
function getNodeHighlightColor(
|
||||
isSelected: boolean,
|
||||
isHovered: boolean,
|
||||
): string | null {
|
||||
if (isSelected) return "#ffffff";
|
||||
if (isHovered) return "#b8b8b8";
|
||||
return null;
|
||||
}
|
||||
|
||||
function createEditorNodePointerHandlers(
|
||||
index: number,
|
||||
onSelectNode: (index: number | null) => void,
|
||||
onHoverNode: (index: number | null) => void,
|
||||
): EditorNodePointerHandlers {
|
||||
return {
|
||||
onClick: (event) => {
|
||||
event.stopPropagation();
|
||||
onSelectNode(index);
|
||||
},
|
||||
onPointerEnter: (event) => {
|
||||
event.stopPropagation();
|
||||
onHoverNode(index);
|
||||
},
|
||||
onPointerLeave: (event) => {
|
||||
event.stopPropagation();
|
||||
onHoverNode(null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function EditorMap({
|
||||
sceneData,
|
||||
selectedNodeIndex,
|
||||
onSelectNode,
|
||||
hoveredNodeIndex,
|
||||
onHoverNode,
|
||||
transformMode,
|
||||
onTransformStart,
|
||||
onTransformEnd,
|
||||
onNodeTransform,
|
||||
}: EditorMapProps): React.JSX.Element {
|
||||
const objectsMapRef = useRef<Map<number, THREE.Object3D>>(new Map());
|
||||
|
||||
const handleTransformMouseDown = () => {
|
||||
onTransformStart?.();
|
||||
};
|
||||
|
||||
const handleTransformMouseUp = () => {
|
||||
if (selectedNodeIndex !== null) {
|
||||
const obj = objectsMapRef.current.get(selectedNodeIndex);
|
||||
if (!obj) return;
|
||||
const node = sceneData.mapNodes[selectedNodeIndex];
|
||||
if (node) {
|
||||
const updatedNode: MapNode = {
|
||||
...node,
|
||||
position: [obj.position.x, obj.position.y, obj.position.z],
|
||||
rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
|
||||
scale: [obj.scale.x, obj.scale.y, obj.scale.z],
|
||||
};
|
||||
onNodeTransform?.(selectedNodeIndex, updatedNode);
|
||||
}
|
||||
}
|
||||
onTransformEnd?.();
|
||||
};
|
||||
|
||||
const [selectedObject, setSelectedObject] = useState<THREE.Object3D | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedNodeIndex !== null) {
|
||||
const obj = objectsMapRef.current.get(selectedNodeIndex);
|
||||
setSelectedObject(obj || null);
|
||||
} else {
|
||||
setSelectedObject(null);
|
||||
}
|
||||
}, [selectedNodeIndex]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Grid
|
||||
args={[100, 100]}
|
||||
cellSize={1}
|
||||
cellThickness={0.5}
|
||||
cellColor="#242424"
|
||||
sectionSize={5}
|
||||
sectionThickness={1}
|
||||
sectionColor="#3a3a3a"
|
||||
fadeDistance={50}
|
||||
fadeStrength={1}
|
||||
followCamera={false}
|
||||
infiniteGrid={false}
|
||||
/>
|
||||
<axesHelper args={[10]} />
|
||||
|
||||
<group
|
||||
onClick={(e: ThreeEvent<MouseEvent>) => {
|
||||
e.stopPropagation();
|
||||
onSelectNode(null);
|
||||
}}
|
||||
>
|
||||
{sceneData.mapNodes.map((node, index) => {
|
||||
const modelUrl = sceneData.models.get(node.name);
|
||||
|
||||
if (modelUrl) {
|
||||
return (
|
||||
<EditorModelNode
|
||||
key={index}
|
||||
index={index}
|
||||
node={node}
|
||||
modelUrl={modelUrl}
|
||||
isSelected={selectedNodeIndex === index}
|
||||
isHovered={hoveredNodeIndex === index}
|
||||
objectsMapRef={objectsMapRef}
|
||||
onSelectNode={onSelectNode}
|
||||
onHoverNode={onHoverNode}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<EditorFallbackNode
|
||||
key={index}
|
||||
index={index}
|
||||
node={node}
|
||||
isSelected={selectedNodeIndex === index}
|
||||
isHovered={hoveredNodeIndex === index}
|
||||
objectsMapRef={objectsMapRef}
|
||||
onSelectNode={onSelectNode}
|
||||
onHoverNode={onHoverNode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</group>
|
||||
|
||||
{selectedObject && (
|
||||
<TransformControls
|
||||
object={selectedObject}
|
||||
mode={transformMode}
|
||||
onMouseDown={handleTransformMouseDown}
|
||||
onMouseUp={handleTransformMouseUp}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EditorModelNode({
|
||||
index,
|
||||
node,
|
||||
modelUrl,
|
||||
isSelected,
|
||||
isHovered,
|
||||
objectsMapRef,
|
||||
onSelectNode,
|
||||
onHoverNode,
|
||||
}: EditorNodeCommonProps & {
|
||||
modelUrl: string;
|
||||
}) {
|
||||
const groupRef = useRef<THREE.Group>(null);
|
||||
const originalMaterialsRef = useRef(
|
||||
new Map<THREE.Mesh, THREE.Material | THREE.Material[]>(),
|
||||
);
|
||||
const { scene } = useGLTF(modelUrl);
|
||||
|
||||
const sceneInstance = useMemo(() => scene.clone(true), [scene]);
|
||||
const pointerHandlers = createEditorNodePointerHandlers(
|
||||
index,
|
||||
onSelectNode,
|
||||
onHoverNode,
|
||||
);
|
||||
useRegisteredEditorNode(groupRef, index, node, objectsMapRef);
|
||||
|
||||
useEffect(() => {
|
||||
if (!groupRef.current) return;
|
||||
const highlightColor = getNodeHighlightColor(isSelected, isHovered);
|
||||
|
||||
groupRef.current.traverse((child) => {
|
||||
if (!(child instanceof THREE.Mesh)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalMaterial = originalMaterialsRef.current.get(child);
|
||||
|
||||
if (!originalMaterial) {
|
||||
originalMaterialsRef.current.set(child, child.material);
|
||||
}
|
||||
|
||||
if (child.material !== originalMaterial && originalMaterial) {
|
||||
disposeMaterial(child.material);
|
||||
}
|
||||
|
||||
if (highlightColor) {
|
||||
child.material = cloneHighlightedMaterial(
|
||||
originalMaterial ?? child.material,
|
||||
highlightColor,
|
||||
);
|
||||
} else if (originalMaterial) {
|
||||
child.material = originalMaterial;
|
||||
}
|
||||
});
|
||||
}, [isSelected, isHovered]);
|
||||
|
||||
useEffect(() => {
|
||||
const group = groupRef.current;
|
||||
const originalMaterials = originalMaterialsRef.current;
|
||||
|
||||
return () => {
|
||||
if (!group) return;
|
||||
|
||||
group.traverse((child) => {
|
||||
if (!(child instanceof THREE.Mesh)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalMaterial = originalMaterials.get(child);
|
||||
if (originalMaterial && child.material !== originalMaterial) {
|
||||
disposeMaterial(child.material);
|
||||
child.material = originalMaterial;
|
||||
}
|
||||
});
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<primitive
|
||||
ref={groupRef}
|
||||
object={sceneInstance}
|
||||
position={node.position}
|
||||
rotation={node.rotation}
|
||||
scale={node.scale}
|
||||
{...pointerHandlers}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function EditorFallbackNode({
|
||||
index,
|
||||
node,
|
||||
isSelected,
|
||||
isHovered,
|
||||
objectsMapRef,
|
||||
onSelectNode,
|
||||
onHoverNode,
|
||||
}: EditorNodeCommonProps) {
|
||||
const meshRef = useRef<THREE.Mesh>(null);
|
||||
const pointerHandlers = createEditorNodePointerHandlers(
|
||||
index,
|
||||
onSelectNode,
|
||||
onHoverNode,
|
||||
);
|
||||
useRegisteredEditorNode(meshRef, index, node, objectsMapRef);
|
||||
|
||||
const color = getNodeHighlightColor(isSelected, isHovered) ?? "#6f6f6f";
|
||||
|
||||
return (
|
||||
<mesh
|
||||
ref={meshRef}
|
||||
position={node.position}
|
||||
rotation={node.rotation}
|
||||
scale={node.scale}
|
||||
{...pointerHandlers}
|
||||
>
|
||||
<boxGeometry args={[1, 1, 1]} />
|
||||
<meshStandardMaterial color={color} />
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect } from "react";
|
||||
import { OrbitControls } from "@react-three/drei";
|
||||
import { EditorMap } from "@/components/editor/scene/EditorMap";
|
||||
import { FlyController } from "@/controls/editor/FlyController";
|
||||
import type { MapNode, TransformMode, SceneData } from "@/types/editor";
|
||||
|
||||
interface EditorSceneProps {
|
||||
sceneData: SceneData;
|
||||
selectedNodeIndex: number | null;
|
||||
onSelectNode: (index: number | null) => void;
|
||||
hoveredNodeIndex: number | null;
|
||||
onHoverNode: (index: number | null) => void;
|
||||
transformMode: TransformMode;
|
||||
onTransformModeChange: (mode: TransformMode) => void;
|
||||
onTransformStart: () => void;
|
||||
onTransformEnd: () => void;
|
||||
onNodeTransform: (nodeIndex: number, transform: MapNode) => void;
|
||||
onUndo: () => void;
|
||||
onRedo: () => void;
|
||||
isPlayerMode?: boolean;
|
||||
}
|
||||
|
||||
export function EditorScene({
|
||||
sceneData,
|
||||
selectedNodeIndex,
|
||||
onSelectNode,
|
||||
hoveredNodeIndex,
|
||||
onHoverNode,
|
||||
transformMode,
|
||||
onTransformModeChange,
|
||||
onTransformStart,
|
||||
onTransformEnd,
|
||||
onNodeTransform,
|
||||
onUndo,
|
||||
onRedo,
|
||||
isPlayerMode = false,
|
||||
}: EditorSceneProps): React.JSX.Element {
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
if (e.key === "z" || e.key === "Z") {
|
||||
e.preventDefault();
|
||||
onUndo();
|
||||
return;
|
||||
}
|
||||
if (e.key === "y" || e.key === "Y") {
|
||||
e.preventDefault();
|
||||
onRedo();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedNodeIndex !== null) {
|
||||
switch (e.key.toLowerCase()) {
|
||||
case "escape":
|
||||
onSelectNode(null);
|
||||
break;
|
||||
case "t":
|
||||
onTransformModeChange("translate");
|
||||
break;
|
||||
case "r":
|
||||
onTransformModeChange("rotate");
|
||||
break;
|
||||
case "s":
|
||||
onTransformModeChange("scale");
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [selectedNodeIndex, onSelectNode, onTransformModeChange, onUndo, onRedo]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isPlayerMode ? (
|
||||
<FlyController disabled={false} />
|
||||
) : (
|
||||
<OrbitControls
|
||||
enableDamping
|
||||
dampingFactor={0.05}
|
||||
mouseButtons={{
|
||||
LEFT: 0,
|
||||
MIDDLE: 1,
|
||||
RIGHT: 2,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<EditorMap
|
||||
sceneData={sceneData}
|
||||
selectedNodeIndex={selectedNodeIndex}
|
||||
onSelectNode={onSelectNode}
|
||||
hoveredNodeIndex={hoveredNodeIndex}
|
||||
onHoverNode={onHoverNode}
|
||||
transformMode={transformMode}
|
||||
onTransformStart={onTransformStart}
|
||||
onTransformEnd={onTransformEnd}
|
||||
onNodeTransform={onNodeTransform}
|
||||
/>
|
||||
|
||||
<ambientLight intensity={0.6} />
|
||||
<directionalLight position={[10, 20, 10]} intensity={1.5} castShadow />
|
||||
<directionalLight position={[-10, 10, -10]} intensity={0.5} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/* eslint-disable react-hooks/immutability */
|
||||
import { createContext, useRef, useState, useEffect, useCallback } from "react";
|
||||
import { useGLTF, useAnimations } from "@react-three/drei";
|
||||
import type { AnimationAction } from "three";
|
||||
import * as THREE from "three";
|
||||
import type { Vector3Tuple } from "@/types/three";
|
||||
|
||||
export interface AnimatedModelConfig {
|
||||
modelPath: string;
|
||||
animations?: string[];
|
||||
defaultAnimation?: string;
|
||||
position?: Vector3Tuple;
|
||||
rotation?: Vector3Tuple;
|
||||
scale?: Vector3Tuple | number;
|
||||
fadeDuration?: number;
|
||||
speed?: number;
|
||||
autoPlay?: boolean;
|
||||
onLoaded?: () => void;
|
||||
onAnimationEnd?: (animationName: string) => void;
|
||||
}
|
||||
|
||||
export interface AnimatedModelContextValue {
|
||||
play: (name: string, fade?: number) => void;
|
||||
stop: (fade?: number) => void;
|
||||
fadeTo: (name: string, fade?: number) => void;
|
||||
currentAnimation: string;
|
||||
isReady: boolean;
|
||||
setSpeed: (speed: number) => void;
|
||||
names: string[];
|
||||
}
|
||||
|
||||
const AnimatedModelContext = createContext<AnimatedModelContextValue | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
export { AnimatedModelContext };
|
||||
|
||||
interface AnimatedModelProps extends AnimatedModelConfig {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AnimatedModel({
|
||||
modelPath,
|
||||
defaultAnimation = "Idle",
|
||||
position = [0, 0, 0],
|
||||
rotation = [0, 0, 0],
|
||||
scale = 1,
|
||||
fadeDuration = 0.3,
|
||||
speed = 1,
|
||||
autoPlay = true,
|
||||
onLoaded,
|
||||
onAnimationEnd,
|
||||
children,
|
||||
}: AnimatedModelProps): React.JSX.Element {
|
||||
const groupRef = useRef<THREE.Group>(null);
|
||||
|
||||
void groupRef;
|
||||
const { scene, animations } = useGLTF(modelPath);
|
||||
const { actions, names, mixer } = useAnimations(animations, scene);
|
||||
|
||||
const [currentAnim, setCurrentAnim] = useState(defaultAnimation);
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (mixer) {
|
||||
mixer.timeScale = speed;
|
||||
}
|
||||
}, [mixer, speed]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleFinished = (e: { action: AnimationAction }) => {
|
||||
const clipName = e.action.getClip().name;
|
||||
onAnimationEnd?.(clipName);
|
||||
};
|
||||
|
||||
if (mixer) {
|
||||
mixer.addEventListener("finished", handleFinished);
|
||||
return () => {
|
||||
mixer.removeEventListener("finished", handleFinished);
|
||||
};
|
||||
}
|
||||
}, [mixer, onAnimationEnd]);
|
||||
|
||||
const play = useCallback(
|
||||
(name: string, fade = fadeDuration) => {
|
||||
const action = actions[name];
|
||||
if (action) {
|
||||
Object.values(actions).forEach((a) => {
|
||||
if (a && a !== action) a.fadeOut(fade);
|
||||
});
|
||||
action.reset().fadeIn(fade).play();
|
||||
setCurrentAnim(name);
|
||||
}
|
||||
},
|
||||
[actions, fadeDuration],
|
||||
);
|
||||
|
||||
const stop = useCallback(
|
||||
(fade = fadeDuration) => {
|
||||
Object.values(actions).forEach((a) => a?.fadeOut(fade));
|
||||
const defaultAction = actions[defaultAnimation];
|
||||
if (defaultAction) {
|
||||
defaultAction.reset().fadeIn(fade).play();
|
||||
setCurrentAnim(defaultAnimation);
|
||||
}
|
||||
},
|
||||
[actions, defaultAnimation, fadeDuration],
|
||||
);
|
||||
|
||||
const fadeTo = useCallback(
|
||||
(name: string, fade = fadeDuration) => {
|
||||
const action = actions[name];
|
||||
if (action) {
|
||||
Object.values(actions).forEach((a) => {
|
||||
if (a && a !== action) a.fadeOut(fade);
|
||||
});
|
||||
action.reset().fadeIn(fade).play();
|
||||
setCurrentAnim(name);
|
||||
}
|
||||
},
|
||||
[actions, fadeDuration],
|
||||
);
|
||||
|
||||
const setSpeed = useCallback(
|
||||
(newSpeed: number) => {
|
||||
if (mixer) {
|
||||
mixer.timeScale = newSpeed;
|
||||
}
|
||||
},
|
||||
[mixer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoPlay || names.length === 0) {
|
||||
console.log("[AnimatedModel] No animation found in model");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[AnimatedModel] Available animations: ${names.join(", ")}`);
|
||||
|
||||
let defaultAction = actions[defaultAnimation as string];
|
||||
|
||||
if (!defaultAction && names.length > 0) {
|
||||
console.log(
|
||||
`[AnimatedModel] "${defaultAnimation}" not found, using: ${names[0]}`,
|
||||
);
|
||||
defaultAction = actions[names[0] as string];
|
||||
}
|
||||
|
||||
if (defaultAction) {
|
||||
defaultAction.play();
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setIsReady(true);
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setCurrentAnim(defaultAction.getClip().name);
|
||||
onLoaded?.();
|
||||
} else {
|
||||
console.log("[AnimatedModel] No available animation in actions");
|
||||
}
|
||||
}, [actions, defaultAnimation, names, autoPlay, onLoaded]);
|
||||
|
||||
const contextValue: AnimatedModelContextValue = {
|
||||
play,
|
||||
stop,
|
||||
fadeTo,
|
||||
currentAnimation: currentAnim,
|
||||
isReady,
|
||||
setSpeed,
|
||||
names,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
scene.position.set(...position);
|
||||
scene.rotation.set(
|
||||
(rotation[0] * Math.PI) / 180,
|
||||
(rotation[1] * Math.PI) / 180,
|
||||
(rotation[2] * Math.PI) / 180,
|
||||
);
|
||||
const s =
|
||||
typeof scale === "number" ? [scale, scale, scale] : (scale ?? [1, 1, 1]);
|
||||
scene.scale.set(s[0] ?? 1, s[1] ?? 1, s[2] ?? 1);
|
||||
}, [scene, position, rotation, scale]);
|
||||
|
||||
return (
|
||||
<AnimatedModelContext.Provider value={contextValue}>
|
||||
<primitive object={scene} />
|
||||
{children}
|
||||
</AnimatedModelContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useFrame, useThree } from "@react-three/fiber";
|
||||
import { RigidBody } from "@react-three/rapier";
|
||||
import type { RapierRigidBody } from "@react-three/rapier";
|
||||
import * as THREE from "three";
|
||||
import { InteractableObject } from "@/components/3d/InteractableObject";
|
||||
import { InteractableObject } from "@/components/three/InteractableObject";
|
||||
import {
|
||||
GRAB_DEFAULT_COLLIDERS,
|
||||
GRAB_DEFAULT_LABEL,
|
||||
@@ -19,9 +19,9 @@ import {
|
||||
GRAB_THROW_BOOST_MAX,
|
||||
GRAB_THROW_BOOST_MIN,
|
||||
GRAB_THROW_BOOST_STEP,
|
||||
} from "@/data/grabConfig";
|
||||
} from "@/data/interaction/grabConfig";
|
||||
import { useDebugFolder } from "@/hooks/debug/useDebugFolder";
|
||||
import type { ColliderShape, Vector3Tuple } from "@/types/3d";
|
||||
import type { ColliderShape, Vector3Tuple } from "@/types/three";
|
||||
|
||||
interface GrabbableObjectProps {
|
||||
position: Vector3Tuple;
|
||||
+47
-26
@@ -8,13 +8,13 @@ import {
|
||||
INTERACTION_DEBUG_SPHERE_COLOR,
|
||||
INTERACTION_DEBUG_SPHERE_OPACITY,
|
||||
INTERACTION_DEBUG_SPHERE_SEGMENTS,
|
||||
} from "@/data/debugConfig";
|
||||
} from "@/data/debug/debugConfig";
|
||||
import { Debug } from "@/utils/debug/Debug";
|
||||
import { useDebugFolder } from "@/hooks/debug/useDebugFolder";
|
||||
import { InteractionManager } from "@/stateManager/InteractionManager";
|
||||
import { INTERACTION_RADIUS } from "@/data/interactionConfig";
|
||||
import type { Vector3Tuple } from "@/types/3d";
|
||||
import type { InteractableHandle, InteractableKind } from "@/types/interaction";
|
||||
import { InteractionManager } from "@/managers/InteractionManager";
|
||||
import { INTERACTION_RADIUS } from "@/data/interaction/interactionConfig";
|
||||
import type { Vector3Tuple } from "@/types/three";
|
||||
import type { InteractableHandle } from "@/types/interaction";
|
||||
|
||||
interface InteractableObjectBaseProps {
|
||||
label: string;
|
||||
@@ -37,46 +37,67 @@ type InteractableObjectProps =
|
||||
| TriggerInteractableObjectProps
|
||||
| GrabInteractableObjectProps;
|
||||
|
||||
type MutableInteractableHandle = {
|
||||
kind: InteractableKind;
|
||||
label: string;
|
||||
onPress: () => void;
|
||||
onRelease?: () => void;
|
||||
};
|
||||
|
||||
const _cameraPos = new THREE.Vector3();
|
||||
const _cameraDir = new THREE.Vector3();
|
||||
const _objectPos = new THREE.Vector3();
|
||||
const _raycaster = new THREE.Raycaster();
|
||||
|
||||
function createInteractableHandle(
|
||||
props: InteractableObjectProps,
|
||||
): InteractableHandle {
|
||||
if (props.kind === "grab") {
|
||||
return {
|
||||
kind: props.kind,
|
||||
label: props.label,
|
||||
onPress: props.onPress,
|
||||
onRelease: props.onRelease,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: props.kind,
|
||||
label: props.label,
|
||||
onPress: props.onPress,
|
||||
};
|
||||
}
|
||||
|
||||
export function InteractableObject(
|
||||
props: InteractableObjectProps,
|
||||
): React.JSX.Element {
|
||||
const { kind, label, position, bodyRef, onPress, children } = props;
|
||||
const onRelease = props.kind === "grab" ? props.onRelease : undefined;
|
||||
const onRelease = props.kind === "grab" ? props.onRelease : null;
|
||||
const camera = useThree((state) => state.camera);
|
||||
const groupRef = useRef<THREE.Group>(null);
|
||||
const debugSphereRef = useRef<THREE.Mesh>(null);
|
||||
|
||||
const handle = useRef<InteractableHandle>(
|
||||
props.kind === "grab"
|
||||
? { kind: props.kind, label, onPress, onRelease: props.onRelease }
|
||||
: { kind: props.kind, label, onPress },
|
||||
);
|
||||
const handle = useRef<InteractableHandle>(createInteractableHandle(props));
|
||||
|
||||
useEffect(() => {
|
||||
const current = handle.current as MutableInteractableHandle;
|
||||
current.kind = kind;
|
||||
current.label = label;
|
||||
current.onPress = onPress;
|
||||
const currentHandle = handle.current;
|
||||
|
||||
if (currentHandle.kind === kind) {
|
||||
currentHandle.label = label;
|
||||
currentHandle.onPress = onPress;
|
||||
|
||||
if (currentHandle.kind === "grab") {
|
||||
if (!onRelease) return;
|
||||
currentHandle.onRelease = onRelease;
|
||||
}
|
||||
|
||||
if (kind === "grab" && onRelease) {
|
||||
current.onRelease = onRelease;
|
||||
return;
|
||||
}
|
||||
|
||||
delete current.onRelease;
|
||||
return undefined;
|
||||
if (kind === "grab") {
|
||||
if (!onRelease) return;
|
||||
handle.current = { kind, label, onPress, onRelease };
|
||||
} else {
|
||||
handle.current = { kind, label, onPress };
|
||||
}
|
||||
|
||||
const manager = InteractionManager.getInstance();
|
||||
if (manager.getState().focused === currentHandle) {
|
||||
manager.setFocused(handle.current);
|
||||
}
|
||||
}, [kind, label, onPress, onRelease]);
|
||||
|
||||
const setupInteractionDebugFolder = useCallback((folder: GUI) => {
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useGLTF } from "@react-three/drei";
|
||||
import type { Vector3Tuple } from "@/types/3d";
|
||||
|
||||
export interface SimpleModelConfig {
|
||||
modelPath: string;
|
||||
position?: Vector3Tuple;
|
||||
rotation?: Vector3Tuple;
|
||||
scale?: Vector3Tuple | number;
|
||||
castShadow?: boolean;
|
||||
receiveShadow?: boolean;
|
||||
}
|
||||
|
||||
interface SimpleModelProps extends SimpleModelConfig {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function SimpleModel({
|
||||
modelPath,
|
||||
position = [0, 0, 0],
|
||||
rotation = [0, 0, 0],
|
||||
scale = 1,
|
||||
castShadow = true,
|
||||
receiveShadow = true,
|
||||
children,
|
||||
}: SimpleModelProps): React.JSX.Element {
|
||||
const { scene } = useGLTF(modelPath);
|
||||
|
||||
const parsedScale =
|
||||
typeof scale === "number" ? ([scale, scale, scale] as Vector3Tuple) : scale;
|
||||
|
||||
return (
|
||||
<group position={position} rotation={rotation} scale={parsedScale}>
|
||||
{children ?? (
|
||||
<primitive
|
||||
object={scene.clone()}
|
||||
castShadow={castShadow}
|
||||
receiveShadow={receiveShadow}
|
||||
/>
|
||||
)}
|
||||
</group>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
import { useState } from "react";
|
||||
import { useGLTF } from "@react-three/drei";
|
||||
import { RigidBody } from "@react-three/rapier";
|
||||
import { InteractableObject } from "@/components/3d/InteractableObject";
|
||||
import { InteractableObject } from "@/components/three/InteractableObject";
|
||||
import {
|
||||
TRIGGER_DEFAULT_COLLIDERS,
|
||||
TRIGGER_DEFAULT_LABEL,
|
||||
TRIGGER_DEFAULT_SOUND_VOLUME,
|
||||
TRIGGER_DEFAULT_SPAWN_OFFSET,
|
||||
} from "@/data/triggerConfig";
|
||||
import { AudioManager } from "@/stateManager/AudioManager";
|
||||
import type { ColliderShape, Vector3Tuple } from "@/types/3d";
|
||||
} from "@/data/interaction/triggerConfig";
|
||||
import { AudioManager } from "@/managers/AudioManager";
|
||||
import type { ColliderShape, Vector3Tuple } from "@/types/three";
|
||||
|
||||
interface SpawnedModel {
|
||||
id: number;
|
||||
@@ -0,0 +1,8 @@
|
||||
export { AnimatedModel, useAnimatedModel } from "./AnimatedModel";
|
||||
export type { AnimatedModelConfig } from "./AnimatedModel";
|
||||
|
||||
export { SimpleModel } from "./SimpleModel";
|
||||
export type { SimpleModelConfig } from "./SimpleModel";
|
||||
|
||||
export { useCharacterAnimation } from "@/hooks/useCharacterAnimation";
|
||||
export type { CharacterAnimationConfig } from "@/hooks/useCharacterAnimation";
|
||||
@@ -1,4 +1,4 @@
|
||||
import { INTERACT_KEY } from "@/data/keybindings";
|
||||
import { INTERACT_KEY } from "@/data/input/keybindings";
|
||||
import { useCameraMode } from "@/hooks/debug/useCameraMode";
|
||||
import { useInteraction } from "@/hooks/useInteraction";
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
export type DocsLanguage = "en" | "fr";
|
||||
|
||||
interface DocsLanguageContextValue {
|
||||
language: DocsLanguage;
|
||||
toggleLanguage: () => void;
|
||||
}
|
||||
|
||||
export const DocsLanguageContext =
|
||||
createContext<DocsLanguageContextValue | null>(null);
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
useRef,
|
||||
useEffect,
|
||||
useCallback,
|
||||
forwardRef,
|
||||
useImperativeHandle,
|
||||
type ElementRef,
|
||||
} from "react";
|
||||
import { useFrame, useThree } from "@react-three/fiber";
|
||||
import { OrbitControls } from "@react-three/drei";
|
||||
import * as THREE from "three";
|
||||
|
||||
type OrbitControlsRef = ElementRef<typeof OrbitControls>;
|
||||
|
||||
interface FlyControllerProps {
|
||||
speed?: number;
|
||||
verticalSpeed?: number;
|
||||
onPositionChange?: (position: THREE.Vector3) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface FlyControllerRef {
|
||||
controls: OrbitControlsRef | null;
|
||||
}
|
||||
|
||||
export const FlyController = forwardRef<FlyControllerRef, FlyControllerProps>(
|
||||
(
|
||||
{ speed = 10, verticalSpeed = 5, onPositionChange, disabled = false },
|
||||
ref,
|
||||
) => {
|
||||
const { camera: rawCamera } = useThree();
|
||||
const cameraRef = useRef(rawCamera);
|
||||
const keys = useRef<{ [key: string]: boolean }>({});
|
||||
const controlsRef = useRef<OrbitControlsRef | null>(null);
|
||||
const lastPosition = useRef(new THREE.Vector3());
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
controls: controlsRef.current,
|
||||
}));
|
||||
|
||||
const handleKeyDown = useCallback((e: KeyboardEvent) => {
|
||||
keys.current[e.code] = true;
|
||||
}, []);
|
||||
|
||||
const handleKeyUp = useCallback((e: KeyboardEvent) => {
|
||||
keys.current[e.code] = false;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
window.addEventListener("keyup", handleKeyUp);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
window.removeEventListener("keyup", handleKeyUp);
|
||||
};
|
||||
}, [handleKeyDown, handleKeyUp]);
|
||||
|
||||
useFrame((_, delta) => {
|
||||
// Disabled mode keeps OrbitControls active without keyboard movement.
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Supports AZERTY, QWERTY, and arrow-key movement.
|
||||
const isForward =
|
||||
keys.current["KeyW"] || keys.current["KeyZ"] || keys.current["ArrowUp"];
|
||||
const isBackward = keys.current["KeyS"] || keys.current["ArrowDown"];
|
||||
const isLeft =
|
||||
keys.current["KeyQ"] ||
|
||||
keys.current["KeyA"] ||
|
||||
keys.current["ArrowLeft"];
|
||||
const isRight = keys.current["KeyD"] || keys.current["ArrowRight"];
|
||||
|
||||
const direction = new THREE.Vector3();
|
||||
const frontVector = new THREE.Vector3(
|
||||
0,
|
||||
0,
|
||||
Number(isBackward) - Number(isForward),
|
||||
);
|
||||
const sideVector = new THREE.Vector3(
|
||||
Number(isRight) - Number(isLeft),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
|
||||
direction.subVectors(frontVector, sideVector);
|
||||
if (direction.lengthSq() > 0) {
|
||||
direction.normalize().multiplyScalar(speed * delta);
|
||||
direction.applyQuaternion(cameraRef.current.quaternion);
|
||||
cameraRef.current.position.add(direction);
|
||||
}
|
||||
|
||||
// Space moves up; Shift moves down.
|
||||
if (keys.current["Space"]) {
|
||||
cameraRef.current.position.y += verticalSpeed * delta;
|
||||
}
|
||||
if (keys.current["ShiftLeft"] || keys.current["ShiftRight"]) {
|
||||
cameraRef.current.position.y -= verticalSpeed * delta;
|
||||
}
|
||||
|
||||
if (
|
||||
onPositionChange &&
|
||||
!cameraRef.current.position.equals(lastPosition.current)
|
||||
) {
|
||||
lastPosition.current.copy(cameraRef.current.position);
|
||||
onPositionChange(cameraRef.current.position);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<OrbitControls
|
||||
ref={controlsRef}
|
||||
makeDefault
|
||||
enableDamping
|
||||
dampingFactor={0.05}
|
||||
mouseButtons={{
|
||||
LEFT: THREE.MOUSE.ROTATE,
|
||||
MIDDLE: THREE.MOUSE.DOLLY,
|
||||
RIGHT: THREE.MOUSE.PAN,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
FlyController.displayName = "FlyController";
|
||||
@@ -2,8 +2,6 @@ export const INTERACTION_DEBUG_SPHERE_SEGMENTS = 16;
|
||||
export const INTERACTION_DEBUG_SPHERE_COLOR = "#facc15";
|
||||
export const INTERACTION_DEBUG_SPHERE_OPACITY = 0.25;
|
||||
|
||||
export const MAP_DEBUG_BOX_HELPER_COLOR = 0x00ff88;
|
||||
|
||||
export const DEBUG_CAMERA_DAMPING_FACTOR = 0.05;
|
||||
export const DEBUG_CAMERA_MIN_DISTANCE = 100;
|
||||
export const DEBUG_CAMERA_MAX_DISTANCE = 1000;
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Vector3Tuple } from "@/types/3d";
|
||||
import type { Vector3Tuple } from "@/types/three";
|
||||
|
||||
export const TEST_SCENE_FLOOR_POSITION: Vector3Tuple = [0, -0.5, 0];
|
||||
export const TEST_SCENE_FLOOR_SIZE: Vector3Tuple = [200, 1, 200];
|
||||
@@ -0,0 +1,66 @@
|
||||
interface DocSection {
|
||||
path: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
meta: string;
|
||||
}
|
||||
|
||||
interface DocGroup {
|
||||
label: string;
|
||||
sections: DocSection[];
|
||||
}
|
||||
|
||||
export const docGroups: DocGroup[] = [
|
||||
{
|
||||
label: "Technical",
|
||||
sections: [
|
||||
{
|
||||
path: "/docs",
|
||||
title: "README",
|
||||
subtitle: "Project overview",
|
||||
meta: "01",
|
||||
},
|
||||
{
|
||||
path: "/docs/architecture",
|
||||
title: "Current Architecture",
|
||||
subtitle: "Runtime structure",
|
||||
meta: "02",
|
||||
},
|
||||
{
|
||||
path: "/docs/target-architecture",
|
||||
title: "Target Architecture",
|
||||
subtitle: "Next direction",
|
||||
meta: "03",
|
||||
},
|
||||
{
|
||||
path: "/docs/technical-editor",
|
||||
title: "Editor Technical Notes",
|
||||
subtitle: "Implementation details",
|
||||
meta: "04",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "User",
|
||||
sections: [
|
||||
{
|
||||
path: "/docs/features",
|
||||
title: "Features",
|
||||
subtitle: "Implemented scope",
|
||||
meta: "05",
|
||||
},
|
||||
{
|
||||
path: "/docs/editor",
|
||||
title: "Editor User Guide",
|
||||
subtitle: "Editing workflow",
|
||||
meta: "06",
|
||||
},
|
||||
{
|
||||
path: "/docs/animation",
|
||||
title: "Animation & 3D Model System",
|
||||
subtitle: "Components and usage",
|
||||
meta: "07",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,329 @@
|
||||
export const readmeFr = `# La-Fabrik
|
||||
|
||||
Une expérience web 3D interactive pour La Fabrik Durable, un service low-tech de réparation et de transformation situé à Altera, une ville post-capitaliste reconstruite en 2039. Les joueurs incarnent un technicien fraîchement intégré et vivent une journée de service : réparer un vélo électrique, remettre en état un réseau d'énergie et améliorer le système d'irrigation d'une ferme verticale.
|
||||
|
||||
Construit avec React, Three.js et Vite. Fonctionne dans le navigateur, sans installation côté utilisateur.
|
||||
|
||||
## Stack technique
|
||||
|
||||
### Build et langage
|
||||
|
||||
| Package |
|
||||
| -------------------------------------------------- |
|
||||
| [TypeScript](https://www.typescriptlang.org/docs/) |
|
||||
| [React](https://react.dev/learn) |
|
||||
| [Vite](https://vite.dev/guide/) |
|
||||
| [ESLint](https://eslint.org/docs/latest/) |
|
||||
| [Prettier](https://prettier.io/docs/) |
|
||||
|
||||
### Moteur 3D
|
||||
|
||||
| Package |
|
||||
| ----------------------------------------------------------------------------------------- |
|
||||
| [Three.js](https://threejs.org/docs/) |
|
||||
| [@react-three/fiber](https://docs.pmnd.rs/react-three-fiber/getting-started/introduction) |
|
||||
| [@react-three/drei](https://pmndrs.github.io/drei) |
|
||||
| [@react-three/rapier](https://rapier.rs/docs/) |
|
||||
| [@react-three/postprocessing](https://github.com/pmndrs/postprocessing) |
|
||||
| [GSAP](https://gsap.com/docs/v3/Installation/) |
|
||||
|
||||
### Performance et effets
|
||||
|
||||
| Package |
|
||||
| --------------------------------------------------------------------------- |
|
||||
| [r3f-perf](https://github.com/utsuboco/r3f-perf) |
|
||||
| [AnimationMixer](https://threejs.org/docs/#api/en/animation/AnimationMixer) |
|
||||
|
||||
## Structure du projet
|
||||
|
||||
\`\`\`
|
||||
la-fabrik/
|
||||
├── public/
|
||||
│ ├── models/
|
||||
│ │ ├── map/ # Carte de base, chargée au démarrage
|
||||
│ │ ├── workshop/
|
||||
│ │ ├── powerGrid/
|
||||
│ │ └── farm/
|
||||
│ ├── textures/
|
||||
│ └── sounds/
|
||||
│
|
||||
└── src/
|
||||
├── world/ # Monde 3D persistant
|
||||
│ ├── World.tsx # Composition principale de la scène
|
||||
│ ├── Map.tsx # Carte de base, toujours montée
|
||||
│ ├── Lighting.tsx # Lumières ambiante, directionnelle et ponctuelles
|
||||
│ ├── Environment.tsx # HDRI, brouillard, ciel
|
||||
│ ├── PostFX.tsx # Bloom, SSAO, aberration chromatique
|
||||
│ ├── zones/ # Zones spatiales, LOD par zone
|
||||
│ └── player/ # Contrôleur joueur et caméra
|
||||
│
|
||||
├── components/
|
||||
│ ├── 3d/ # Éléments 3D réutilisables
|
||||
│ └── ui/ # Overlays HTML hors Canvas
|
||||
│
|
||||
├── managers/ # Logique, état et orchestration
|
||||
├── hooks/ # Hooks React autour des managers
|
||||
├── data/ # Configuration statique
|
||||
├── shaders/ # Shaders GLSL
|
||||
└── utils/ # Utilitaires partagés et debug
|
||||
\`\`\`
|
||||
|
||||
## Démarrage
|
||||
|
||||
\`\`\`bash
|
||||
git clone https://github.com/La-Fabrik-Durable/La-Fabrik.git
|
||||
cd La-Fabrik
|
||||
npm install
|
||||
npm run dev
|
||||
\`\`\`
|
||||
|
||||
- application : \`http://localhost:5173\`
|
||||
- mode debug : \`http://localhost:5173?debug\`
|
||||
|
||||
## Licence
|
||||
|
||||
Voir le fichier [LICENSE](./LICENSE).
|
||||
`;
|
||||
|
||||
export const architectureFr = `# Architecture actuelle
|
||||
|
||||
Ce document décrit le code réellement présent aujourd'hui dans le dépôt.
|
||||
|
||||
## Structure runtime
|
||||
|
||||
- \`src/App.tsx\` monte le \`RouterProvider\`, qui pilote l'affichage des vues de l'application.
|
||||
- \`src/pages/page.tsx\` monte le \`Canvas\`, le \`World\` 3D, l'overlay de performance debug et les overlays HTML.
|
||||
- \`src/world/World.tsx\` compose la scène active avec :
|
||||
- l'environnement et l'éclairage
|
||||
- les helpers debug et le mode caméra debug
|
||||
- soit la carte principale, soit la scène de test physique debug
|
||||
- le rig joueur quand le mode caméra actif est \`player\`
|
||||
- \`src/world/GameMap.tsx\` charge les modèles de carte disponibles et construit l'octree de collision.
|
||||
- \`src/world/debug/TestScene.tsx\` fournit une scène orientée debug pour les interactions et la physique.
|
||||
- \`src/world/player/Player.tsx\` monte la caméra et le contrôleur.
|
||||
- \`src/world/player/PlayerController.tsx\` gère le mouvement pointer lock, le saut et les inputs d'interaction.
|
||||
|
||||
## Modèle d'interaction
|
||||
|
||||
- \`src/managers/InteractionManager.ts\` est la source d'état actuelle des interactions.
|
||||
- \`src/components/three/InteractableObject.tsx\` gère la détection de focus par distance et raycasting.
|
||||
- \`src/components/three/TriggerObject.tsx\` implémente les interactions de type trigger.
|
||||
- \`src/components/three/GrabbableObject.tsx\` implémente les interactions saisir / relâcher.
|
||||
- \`src/hooks/useInteraction.ts\` expose un snapshot d'interaction à l'UI React.
|
||||
- \`src/components/ui/InteractPrompt.tsx\` affiche le prompt \`E\` pour les interactions trigger.
|
||||
|
||||
## Audio
|
||||
|
||||
- \`src/managers/AudioManager.ts\` fournit actuellement une lecture de sons one-shot avec pool.
|
||||
- Les interactions trigger peuvent lancer directement un son via \`AudioManager\`.
|
||||
|
||||
## Système debug
|
||||
|
||||
- Le mode debug est activé avec \`?debug\`.
|
||||
- \`src/utils/debug/Debug.ts\` possède l'instance \`lil-gui\` et les contrôles debug.
|
||||
- \`src/hooks/debug/useCameraMode.ts\` et \`src/hooks/debug/useSceneMode.ts\` s'abonnent à l'état debug.
|
||||
- \`src/components/debug/DebugPerf.tsx\` monte \`r3f-perf\` en lazy uniquement en mode debug.
|
||||
- \`src/components/debug/scene/DebugHelpers.tsx\` monte les helpers debug.
|
||||
- \`src/components/debug/scene/DebugCameraControls.tsx\` monte la caméra libre debug.
|
||||
|
||||
## Limites actuelles
|
||||
|
||||
- Le dépôt est encore un prototype, pas le runtime complet du jeu.
|
||||
- \`src/world/debug/TestScene.tsx\` fait encore partie de la composition active.
|
||||
- Il n'existe pas encore d'orchestrateur gameplay central comme \`GameManager\`.
|
||||
- Les systèmes de missions, zones, cinématiques et dialogues ne sont pas implémentés.
|
||||
- Le joueur utilise une collision octree et des règles simples, pas une pile physique gameplay complète.
|
||||
`;
|
||||
|
||||
export const targetArchitectureFr = `# Architecture cible
|
||||
|
||||
Ce document décrit l'architecture visée à moyen terme pour le projet.
|
||||
|
||||
## Relation avec le code actuel
|
||||
|
||||
- \`docs/technical/architecture.md\` reste la source de vérité de ce qui existe maintenant.
|
||||
- Ce document est volontairement aspirational.
|
||||
- Si ce document contredit l'implémentation actuelle, l'implémentation actuelle gagne.
|
||||
|
||||
## Objectifs
|
||||
|
||||
- Garder \`App.tsx\` petit et centré sur l'orchestration.
|
||||
- Séparer le code de production du monde des chemins runtime uniquement debug.
|
||||
- Garder une source de vérité claire par responsabilité.
|
||||
- Faire grandir les systèmes gameplay progressivement, sans préconstruire une architecture vide.
|
||||
|
||||
## Couches prévues
|
||||
|
||||
### Couche App
|
||||
|
||||
- \`App.tsx\` monte la scène canvas et les overlays HTML de premier niveau.
|
||||
- Il doit rester fin et éviter la logique gameplay.
|
||||
|
||||
### Couche World
|
||||
|
||||
- \`src/world/\` doit contenir la composition de scène de production et les objets de scène de production.
|
||||
- Responsabilités attendues :
|
||||
- composition du monde
|
||||
- carte, environnement, éclairage
|
||||
- contrôleur joueur
|
||||
- ancres d'interaction de production
|
||||
- post-processing de production si nécessaire
|
||||
|
||||
### Couche Debug
|
||||
|
||||
- Les scènes et outils uniquement debug doivent être isolés du chemin de production.
|
||||
- Responsabilités attendues :
|
||||
- \`lil-gui\`
|
||||
- overlay de performance
|
||||
- helpers de scène
|
||||
- caméra libre et contrôles de calibration
|
||||
- scènes temporaires de test utilisées pendant le développement
|
||||
|
||||
### Couche UI
|
||||
|
||||
- \`src/components/ui/\` doit contenir les overlays HTML visibles par le joueur.
|
||||
- Exemples futurs :
|
||||
- crosshair
|
||||
- flow de chargement
|
||||
- HUD de mission
|
||||
- overlays narratifs
|
||||
|
||||
### Couche Gameplay
|
||||
|
||||
- À mesure que le projet grandit, l'état gameplay peut évoluer vers une couche d'orchestration plus claire.
|
||||
- Sujets probables :
|
||||
- missions
|
||||
- zones
|
||||
- cinématiques
|
||||
- dialogues
|
||||
- audio
|
||||
- interactions
|
||||
|
||||
## Règles
|
||||
|
||||
- Préférer du code direct et fonctionnel plutôt qu'un échafaudage spéculatif.
|
||||
- Les types partagés doivent rester proches de leur domaine jusqu'à avoir plusieurs vrais consommateurs.
|
||||
- Éviter de créer de nouveaux managers ou services sans besoin runtime actif.
|
||||
- Les chemins runtime uniquement debug doivent être clairement marqués et faciles à retirer plus tard.
|
||||
`;
|
||||
|
||||
export const featuresFr = `# Fonctionnalités implémentées
|
||||
|
||||
Ce document liste les fonctionnalités présentes dans le code actuel.
|
||||
|
||||
## Scène
|
||||
|
||||
- Scène React Three Fiber plein écran
|
||||
- Carte principale chargée depuis \`public/models/map/model.gltf\`
|
||||
- Scène de test physique debug sélectionnable depuis le panneau debug
|
||||
- Éclairage ambiant et directionnel
|
||||
- Configuration de l'environnement de fond
|
||||
|
||||
## Joueur
|
||||
|
||||
- Mode caméra joueur
|
||||
- Orientation souris avec pointer lock
|
||||
- Déplacement avec \`ZQSD\`
|
||||
- Saut
|
||||
- Collision basée sur une octree contre la carte chargée
|
||||
|
||||
## Interactions
|
||||
|
||||
- Détection de focus par distance et raycast
|
||||
- Interactions trigger activées avec \`E\`
|
||||
- Interactions grab activées avec le bouton principal de la souris
|
||||
- Prompt d'interaction affiché pour les interactions trigger
|
||||
|
||||
## Audio
|
||||
|
||||
- Lecture de sons one-shot pour les interactions trigger
|
||||
- Pool simple par son via \`AudioManager\`
|
||||
|
||||
## Outils debug
|
||||
|
||||
- Le paramètre \`?debug\` active le panneau debug
|
||||
- Contrôles \`lil-gui\` pour le mode caméra, le mode scène et les sphères d'interaction
|
||||
- Helpers de scène debug
|
||||
- Caméra libre debug
|
||||
- Overlay \`r3f-perf\`
|
||||
|
||||
## Pas encore implémenté
|
||||
|
||||
- système de missions
|
||||
- système de zones
|
||||
- système de cinématiques
|
||||
- système de dialogues
|
||||
- flow de chargement
|
||||
- minimap et HUD de mission
|
||||
- séparation complète production / debug pour les scènes gameplay
|
||||
`;
|
||||
|
||||
export const editorFr = `# Éditeur de carte
|
||||
|
||||
L'éditeur de carte est disponible sur "/editor". Il permet d'inspecter et d'ajuster les objets déclarés dans "/public/map.json" directement depuis le navigateur.
|
||||
|
||||
## Ce qui est édité
|
||||
|
||||
L'éditeur travaille sur la liste de nodes stockée dans "/public/map.json".
|
||||
|
||||
Chaque node décrit un objet de la scène :
|
||||
|
||||
- "name" : nom du dossier modèle dans "/public/models/{name}/model.gltf"
|
||||
- "type" : catégorie de l'objet
|
||||
- "position" : "[x, y, z]"
|
||||
- "rotation" : "[x, y, z]"
|
||||
- "scale" : "[x, y, z]"
|
||||
|
||||
Les modèles sont chargés depuis "/public/models". Si un modèle manque, l'éditeur affiche un cube gris de remplacement pour que le node reste sélectionnable et déplaçable.
|
||||
|
||||
## Workflow de base
|
||||
|
||||
1. Ouvrir "/editor".
|
||||
2. Sélectionner un objet dans la vue 3D.
|
||||
3. Choisir un mode de transformation : translation, rotation ou scale.
|
||||
4. Déplacer la gizmo de transformation.
|
||||
5. Utiliser undo ou redo si nécessaire.
|
||||
6. Exporter le JSON mis à jour ou le sauvegarder sur le serveur de dev.
|
||||
|
||||
## Contrôles
|
||||
|
||||
| Action | Input |
|
||||
| --- | --- |
|
||||
| Sélectionner un objet | Clic sur l'objet |
|
||||
| Désélectionner | "Esc" ou clic dans le vide |
|
||||
| Mode translation | "T" |
|
||||
| Mode rotation | "R" |
|
||||
| Mode scale | "S" |
|
||||
| Undo | "Ctrl+Z" |
|
||||
| Redo | "Ctrl+Y" |
|
||||
| Déplacement en vue verrouillée | "WASD", "ZQSD", flèches |
|
||||
| Monter / descendre | "Space", "Shift" |
|
||||
|
||||
## Actions fichier
|
||||
|
||||
### Export JSON
|
||||
|
||||
"Export JSON" télécharge la liste actuelle des nodes sous le nom "map.json". À utiliser pour remplacer manuellement "/public/map.json".
|
||||
|
||||
### Save to server
|
||||
|
||||
"Save to server" est disponible uniquement en développement local. L'action écrit la carte modifiée dans "/public/map.json" via l'endpoint du serveur de dev Vite.
|
||||
|
||||
Cette action est masquée dans les builds de production car il n'existe pas encore d'API de persistance production.
|
||||
|
||||
## Inspecteur JSON
|
||||
|
||||
Le panneau latéral affiche le JSON brut de la carte :
|
||||
|
||||
- sans sélection, il affiche toute la liste des nodes
|
||||
- avec un objet sélectionné, il met en évidence les lignes du node sélectionné
|
||||
|
||||
Utilise-le pour vérifier les valeurs numériques exactes avant export ou sauvegarde.
|
||||
|
||||
## Limites actuelles
|
||||
|
||||
- L'éditeur modifie uniquement les nodes existants.
|
||||
- Il n'y a pas encore d'interface pour créer ou supprimer des objets.
|
||||
- La sauvegarde production n'est pas implémentée.
|
||||
- Les modèles manquants s'affichent comme cubes de fallback au lieu de bloquer tout l'éditeur.
|
||||
`;
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Vector3Tuple } from "@/types/3d";
|
||||
import type { Vector3Tuple } from "@/types/three";
|
||||
|
||||
export const TRIGGER_DEFAULT_COLLIDERS = "ball";
|
||||
export const TRIGGER_DEFAULT_LABEL = "Interagir";
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user