From 977cf60d266872ec0aa8284f26f40a1f495808fa Mon Sep 17 00:00:00 2001 From: Leo Date: Thu, 26 Nov 2026 10:38:30 +0100 Subject: [PATCH 1/2] feat(graphic-3d): basics components --- AGENTS.md | 21 +- README.md | 1 + docs/default-packages.md | 4 +- package.json | 2 + packages/graphics-3d/README.md | 50 +++++ packages/graphics-3d/components/box-3d.ts | 27 +++ packages/graphics-3d/components/camera-3d.ts | 30 +++ packages/graphics-3d/components/light-3d.ts | 29 +++ .../components/object-3d-component.ts | 27 +++ packages/graphics-3d/components/plane-3d.ts | 25 +++ packages/graphics-3d/components/sphere-3d.ts | 20 ++ packages/graphics-3d/nanoforge.manifest.json | 18 ++ packages/graphics-3d/object-3d.ts | 174 +++++++++++++++ packages/graphics-3d/systems/draw-3d.ts | 118 ++++++++++ pnpm-lock.yaml | 77 +++++++ pnpm-workspace.yaml | 2 + test/graphics-3d.spec.ts | 206 ++++++++++++++++++ test/recipes.spec.ts | 33 +++ 18 files changed, 856 insertions(+), 8 deletions(-) create mode 100644 packages/graphics-3d/README.md create mode 100644 packages/graphics-3d/components/box-3d.ts create mode 100644 packages/graphics-3d/components/camera-3d.ts create mode 100644 packages/graphics-3d/components/light-3d.ts create mode 100644 packages/graphics-3d/components/object-3d-component.ts create mode 100644 packages/graphics-3d/components/plane-3d.ts create mode 100644 packages/graphics-3d/components/sphere-3d.ts create mode 100644 packages/graphics-3d/nanoforge.manifest.json create mode 100644 packages/graphics-3d/object-3d.ts create mode 100644 packages/graphics-3d/systems/draw-3d.ts create mode 100644 test/graphics-3d.spec.ts diff --git a/AGENTS.md b/AGENTS.md index 42436c0..1ba196d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,7 @@ packages: the root `package.json` is private and `pnpm-workspace.yaml` lists no | `@nanoforge/basics-2d` | shared | Position, velocity and `move2D`; tags, models, lifetimes, following another entity | | `@nanoforge/basics-3d` | shared | `Position3D`, `Rotation3D`, `Scale3D`, `Velocity3D`, `Acceleration3D` and `move3D` | | `@nanoforge/graphics-2d` | client | Shapes and texts with a color or an image, sprite animations, facing, a camera, a HUD, `draw2D` | +| `@nanoforge/graphics-3d` | client | Boxes, spheres and planes of a color, lights, a camera, any Three.js object, `draw3D` | | `@nanoforge/physics-2d` | shared | Hitboxes, collisions, gravity, walls, bounces and deflectors, walking, jumping, chasing and bounds | | `@nanoforge/controls-2d` | client | Keyboard, mouse and gamepad controls for walking, jumping and shooting; click, drag and follow the mouse | | `@nanoforge/combat-2d` | both | Health, damage, shooters fired by a player, a turret or the server; health bars | @@ -24,8 +25,8 @@ packages: the root `package.json` is private and `pnpm-workspace.yaml` lists no - TypeScript, strict, built with `tsc -b` (`tsconfig.json` includes `packages/**/*.ts`). - Engine libs from the `core` catalog of `pnpm-workspace.yaml`: `@nanoforge-dev/common`, `@nanoforge-dev/ecs`, `@nanoforge-dev/graphics-2d`, `@nanoforge-dev/input`, - `@nanoforge-dev/scene`, `@nanoforge-dev/sound`, `@nanoforge-dev/music`, `@nanoforge-dev/network` - (all `^3.0.0`). + `@nanoforge-dev/scene`, `@nanoforge-dev/sound`, `@nanoforge-dev/music`, `@nanoforge-dev/network`, + `@nanoforge-dev/graphics-3d` (all `^3.0.0`), and `three` (`^0.187.0`, graphics-3d's peer). `@nanoforge-dev/editor-lib` is there only for the typings of `scene`, `sound`, `music` and `network`, which import it. - Vitest with typechecking (`tsconfig.spec.json`) and v8 coverage on `packages/**/*.ts`. @@ -107,6 +108,11 @@ editor reads each item from its `.ts` file (NanoForge-dev/editor - `ctx.network` is the exception: `@nanoforge-dev/network/client` and `/server` both declare it, with other types, so one program can't import both. `network-2d` imports `PacketDefinition` from the root and types the part of `ctx.network` it uses (`sync-to-clients-2d.ts`). +- `ctx.graphics` in 3D too: the main entry of `@nanoforge-dev/graphics-3d` declares it with the 3D + type, and graphics-2d with the 2D one. `graphics-3d` imports only + `@nanoforge-dev/graphics-3d/three` (which declares nothing), types the part of `ctx.graphics` it + uses (`draw-3d.ts`), and tags the system `@uses graphics`. Every one of its component files + imports `/three` too, even a bare `import`, so the editor offers it only to 3D apps. - Mouse positions are on the screen: an item placed in the world converts them with `toWorld` or `pointFor` (`graphics-2d/world.ts`), so it works under a `Camera2D` and on `Hud2D` entities. - `nanoforge.manifest.json` mirrors the imports: each `@nanoforge/` used goes in `dependencies` @@ -184,11 +190,12 @@ release fails. skip models, so copies start fresh. - Runtime-only components, which the editor must not offer (`FromModel`), live in a helper file at the package root, not in `components/`. -- Only shape components (`Drawable*`, `Hitbox*`) take `width`, `height` or `radius`, and only - position and vector components (`Position2D`, `Velocity2D`, `Acceleration2D`, the 3D ones) take a - numeric `x`/`y`: the editor's Scene screen places an entity by its first numeric `x`/`y`, and - draws a shape for any `radius` or `width` and `height`. Name the others for what they are - (`offsetX`, `aimX`, `moveX`, `jumpHeight`, `barWidth`, `areaWidth`, `worldWidth`). +- Only shape components (`Drawable*`, `Hitbox*`, `Box3D`, `Sphere3D`, `Plane3D`) take `width`, + `height`, `depth` or `radius`, and only position and vector components (`Position2D`, + `Velocity2D`, `Acceleration2D`, the 3D ones) take a numeric `x`/`y`: the editor's Scene screen + places an entity by its first numeric `x`/`y`, and draws a shape for any `radius` or `width` and + `height`. Name the others for what they are (`offsetX`, `aimX`, `moveX`, `jumpHeight`, + `barWidth`, `areaWidth`, `worldWidth`). - Commits: conventional commits (`@commitlint/config-conventional`), lowercase subject, the package as scope when the change is in one (`feat(physics-2d): …`). The commit type sets the release bump. Never `--no-verify`. diff --git a/README.md b/README.md index 9ef8231..dc58885 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ package of the registry: | [`@nanoforge/basics-2d`](packages/basics-2d) | shared | Position, velocity and `move2D`; tags, models, lifetimes, following another entity | | [`@nanoforge/basics-3d`](packages/basics-3d) | shared | `Position3D`, `Rotation3D`, `Scale3D`, `Velocity3D`, `Acceleration3D` and `move3D` | | [`@nanoforge/graphics-2d`](packages/graphics-2d) | client | Shapes and texts with a color or an image, sprite animations, facing, a camera, a HUD, `draw2D` | +| [`@nanoforge/graphics-3d`](packages/graphics-3d) | client | Boxes, spheres and planes of a color, lights, a camera, any Three.js object, `draw3D` | | [`@nanoforge/physics-2d`](packages/physics-2d) | shared | Hitboxes, collisions, gravity, walls, bounces and deflectors, walking, jumping, chasing and bounds | | [`@nanoforge/controls-2d`](packages/controls-2d) | client | Keyboard, mouse and gamepad controls for walking, jumping and shooting; click, drag and follow the mouse | | [`@nanoforge/combat-2d`](packages/combat-2d) | both | Health, damage, shooters fired by a player, a turret or the server; health bars | diff --git a/docs/default-packages.md b/docs/default-packages.md index 9c129e4..fd7eab5 100644 --- a/docs/default-packages.md +++ b/docs/default-packages.md @@ -27,6 +27,7 @@ Not installed by default, so that a new project only shows what everyone needs: | Menus, scores, coins to pick | `@nanoforge/scenes-2d`, `@nanoforge/controls-2d` (`Clickable2D` buttons) | | Multiplayer (server + clients) | `@nanoforge/network-2d` | | Any game with sound or music | `@nanoforge/audio` | +| 3D game | `@nanoforge/basics-3d`, `@nanoforge/graphics-3d` (instead of the 2D ones) | ## Order of the systems @@ -46,7 +47,8 @@ Systems run in the order they are added. With every package: - **6. Once everything moved:** `follow2D`, `animateMoves2D`, `faceVelocity2D`, `faceTarget2D`, `faceAim2D`, `followCamera2D`, `animateSprites2D`, `colorOnHover2D`, `fadeOut2D`, `showSceneVars2D`. -- **7.** `draw2D`, so the screen shows where entities ended up, then `drawHealthBars2D`. +- **7.** `draw2D`, so the screen shows where entities ended up, then `drawHealthBars2D`; in 3D, + `draw3D`. - **8. Last:** `expireLifetimes`; on a network server, `syncToClients2D`. `loadSounds` and `playMusic` can go anywhere on the client. diff --git a/package.json b/package.json index 177b06f..eaf0eca 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "@nanoforge-dev/ecs": "catalog:core", "@nanoforge-dev/editor-lib": "catalog:core", "@nanoforge-dev/graphics-2d": "catalog:core", + "@nanoforge-dev/graphics-3d": "catalog:core", "@nanoforge-dev/input": "catalog:core", "@nanoforge-dev/music": "catalog:core", "@nanoforge-dev/network": "catalog:core", @@ -60,6 +61,7 @@ "husky": "catalog:ci", "lint-staged": "catalog:ci", "prettier": "catalog:lint", + "three": "catalog:core", "typescript": "catalog:core", "vitest": "catalog:test" }, diff --git a/packages/graphics-3d/README.md b/packages/graphics-3d/README.md new file mode 100644 index 0000000..59f06ac --- /dev/null +++ b/packages/graphics-3d/README.md @@ -0,0 +1,50 @@ +# @nanoforge/graphics-3d + +Shows entities in the 3D scene of `@nanoforge-dev/graphics-3d`, without writing Three.js: add +`draw3D` after the systems that move them. Place them with `Position3D`, `Rotation3D` (degrees) +and `Scale3D` from `@nanoforge/basics-3d`. The project needs `@nanoforge-dev/graphics-3d` and its +peer `three`, and registers `Graphics3DLibrary` in the client's `main.ts`. + +- `Box3D`, `Sphere3D`, `Plane3D`: lit shapes of one color. A `Plane3D` stands upright: lay it down + as a ground with `Rotation3D(-90, 0, 0)`. +- `Light3D`: an `ambient`, `directional` (the sun) or `point` (a bulb) light. Until the scene has + one, `draw3D` adds a default light, so shapes are never black. +- `Camera3D`: the point of view, looking along -z. The first active one is shown; with none, the + library's camera at `(0, 0, 5)` looking at the origin. +- `Object3DComponent`: any Three.js object you built, such as an `InstancedMesh` for many identical + objects. It moves with the transform components like the shapes. +- `draw3D`: gives each component its Three.js object and keeps it up to date. A removed component, + or a killed entity, loses its object, and its geometries, materials and textures are disposed. + +`toObject3D` (`object-3d.ts`) is the mapping from a component's params to its Three.js object. +`draw3D` uses it, and so can the editor, so both show the same thing. + +## Order + +`draw3D` last but one, after the systems that move entities (`move3D`), where `draw2D` goes in 2D. + +## Recipes + +- A cube, a ball, a light and a camera, in the client's `main.ts`: + + ```ts + const cube = registry.spawnEntity(); + registry.addComponent(cube, new Box3D(1, 1, 1, "#44aa88")); + registry.addComponent(cube, new Position3D(-1, 0, 0)); + registry.addComponent(cube, new Velocity3D(0, 0.5, 0)); + + const ball = registry.spawnEntity(); + registry.addComponent(ball, new Sphere3D(0.5, "#ff6b6b")); + registry.addComponent(ball, new Position3D(1, 0, 0)); + + const sun = registry.spawnEntity(); + registry.addComponent(sun, new Light3D("directional", "#ffffff", 3)); + registry.addComponent(sun, new Position3D(3, 5, 4)); + + const camera = registry.spawnEntity(); + registry.addComponent(camera, new Camera3D()); + registry.addComponent(camera, new Position3D(0, 1, 6)); + + registry.addSystem(move3D); + registry.addSystem(draw3D); + ``` diff --git a/packages/graphics-3d/components/box-3d.ts b/packages/graphics-3d/components/box-3d.ts new file mode 100644 index 0000000..2fa0a5e --- /dev/null +++ b/packages/graphics-3d/components/box-3d.ts @@ -0,0 +1,27 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * Shows the entity as a lit box. Add `draw3D` to show it, and `Position3D`, `Rotation3D` or + * `Scale3D` (basics-3d) to place it. + * + * @example + * `new Box3D(1, 1, 1, "#44aa88")` is a green cube of one unit. + * + * @component + * @side client + * @group Box color=#ff9f43 - Size and color. + */ +export class Box3D { + name = "Box3D"; + + constructor( + /** Units along the x axis. @group Box */ + public width = 1, + /** Units along the y axis (up). @group Box */ + public height = 1, + /** Units along the z axis. @group Box */ + public depth = 1, + /** Any CSS color. @group Box @preset color */ + public color = "#ffffff", + ) {} +} diff --git a/packages/graphics-3d/components/camera-3d.ts b/packages/graphics-3d/components/camera-3d.ts new file mode 100644 index 0000000..ef8151c --- /dev/null +++ b/packages/graphics-3d/components/camera-3d.ts @@ -0,0 +1,30 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * The point of view the game is shown from. Add `draw3D`; place it with `Position3D` and turn it + * with `Rotation3D` (basics-3d). + * + * @remarks + * It looks along -z, from `(0, 0, 5)` until it has a `Position3D`. The first active camera is the + * one shown; with none, the library's default camera is shown: at `(0, 0, 5)`, looking at the + * origin. + * + * @component + * @side client + * @group Camera color=#54a0ff - What the camera sees. + * @group Advanced hidden - What is too near or too far to be shown. + */ +export class Camera3D { + name = "Camera3D"; + + constructor( + /** Vertical field of view, in degrees. @group Camera */ + public fov = 50, + /** Units from the camera under which nothing is shown. @group Advanced */ + public near = 0.1, + /** Units from the camera past which nothing is shown. @group Advanced */ + public far = 1000, + /** Show the game from this camera. @group Camera */ + public active = true, + ) {} +} diff --git a/packages/graphics-3d/components/light-3d.ts b/packages/graphics-3d/components/light-3d.ts new file mode 100644 index 0000000..8911bbf --- /dev/null +++ b/packages/graphics-3d/components/light-3d.ts @@ -0,0 +1,29 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * Lights the scene. Add `draw3D`; place it with `Position3D` (basics-3d). + * + * @remarks + * Until the scene has a light, `draw3D` adds a default one, so shapes are never black. + * + * - `ambient`: lights everything evenly, from nowhere. + * - `directional`: parallel rays like the sun, from its position toward the origin; from + * `(5, 10, 7)` until it has a `Position3D`. + * - `point`: shines all around from its position, like a bulb; it fades with the distance. + * + * @component + * @side client + * @group Light color=#feca57 - Kind, color and strength. + */ +export class Light3D { + name = "Light3D"; + + constructor( + /** How it shines. @group Light */ + public kind: "ambient" | "directional" | "point" = "directional", + /** Any CSS color. @group Light @preset color */ + public color = "#ffffff", + /** How strong it is: about 1 for ambient, 3 for the sun, more for a point light. @group Light */ + public intensity = 3, + ) {} +} diff --git a/packages/graphics-3d/components/object-3d-component.ts b/packages/graphics-3d/components/object-3d-component.ts new file mode 100644 index 0000000..5096cec --- /dev/null +++ b/packages/graphics-3d/components/object-3d-component.ts @@ -0,0 +1,27 @@ +import { Object3D } from "@nanoforge-dev/graphics-3d/three"; + +/** + * Shows any Three.js object you built: a mesh with your own geometry or material, a group, an + * `InstancedMesh` for many identical objects. Add `draw3D`; `Position3D`, `Rotation3D` and `Scale3D` + * (basics-3d) move it like the shapes. + * + * @remarks + * Removing the component, or the entity, removes the object and disposes its geometries, + * materials and textures. + * + * @example + * `new Object3DComponent(new Mesh(new TorusGeometry(), new MeshStandardMaterial()))`, with the + * classes from `@nanoforge-dev/graphics-3d/three`. + * + * @component + * @side client + * @group Object color=#a29bfe - The Three.js object. + */ +export class Object3DComponent { + name = "Object3DComponent"; + + constructor( + /** The object to show. @group Object */ + public object = new Object3D(), + ) {} +} diff --git a/packages/graphics-3d/components/plane-3d.ts b/packages/graphics-3d/components/plane-3d.ts new file mode 100644 index 0000000..fa605a2 --- /dev/null +++ b/packages/graphics-3d/components/plane-3d.ts @@ -0,0 +1,25 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * Shows the entity as a flat lit rectangle, seen from both sides. Add `draw3D` to show it, and + * `Position3D`, `Rotation3D` or `Scale3D` (basics-3d) to place it. + * + * @remarks + * It stands upright, facing the z axis. Lay it down as a ground with `Rotation3D(-90, 0, 0)`. + * + * @component + * @side client + * @group Plane color=#ff9f43 - Size and color. + */ +export class Plane3D { + name = "Plane3D"; + + constructor( + /** Units along the x axis. @group Plane */ + public width = 1, + /** Units along the y axis, before any rotation. @group Plane */ + public height = 1, + /** Any CSS color. @group Plane @preset color */ + public color = "#ffffff", + ) {} +} diff --git a/packages/graphics-3d/components/sphere-3d.ts b/packages/graphics-3d/components/sphere-3d.ts new file mode 100644 index 0000000..cfe74eb --- /dev/null +++ b/packages/graphics-3d/components/sphere-3d.ts @@ -0,0 +1,20 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * Shows the entity as a lit ball. Add `draw3D` to show it, and `Position3D`, `Rotation3D` or + * `Scale3D` (basics-3d) to place it. + * + * @component + * @side client + * @group Sphere color=#ff9f43 - Size and color. + */ +export class Sphere3D { + name = "Sphere3D"; + + constructor( + /** Units from the center to the surface. @group Sphere */ + public radius = 0.5, + /** Any CSS color. @group Sphere @preset color */ + public color = "#ffffff", + ) {} +} diff --git a/packages/graphics-3d/nanoforge.manifest.json b/packages/graphics-3d/nanoforge.manifest.json new file mode 100644 index 0000000..e4a0bf9 --- /dev/null +++ b/packages/graphics-3d/nanoforge.manifest.json @@ -0,0 +1,18 @@ +{ + "type": "package", + "name": "@nanoforge/graphics-3d", + "description": "Show entities in 3D without Three.js: boxes, spheres and planes of a color, lights, a camera, or any Three.js object, placed by the 3D transform.", + "keywords": ["graphics", "3d", "three", "box", "sphere", "plane", "light", "camera", "draw"], + "license": "MIT", + "suggestedPlugins": ["@nanoforge/ecs"], + "dependencies": { "@nanoforge/basics-3d": "^1.0.0" }, + "libDependencies": { + "@nanoforge-dev/common": "^3.0.0", + "@nanoforge-dev/ecs": "^3.0.0", + "@nanoforge-dev/graphics-3d": "^3.0.0" + }, + "contents": [ + { "kind": "@nanoforge/ecs:component", "path": "components/" }, + { "kind": "@nanoforge/ecs:system", "path": "systems/" } + ] +} diff --git a/packages/graphics-3d/object-3d.ts b/packages/graphics-3d/object-3d.ts new file mode 100644 index 0000000..900265c --- /dev/null +++ b/packages/graphics-3d/object-3d.ts @@ -0,0 +1,174 @@ +import { + AmbientLight, + BoxGeometry, + type BufferGeometry, + type Color, + DirectionalLight, + DoubleSide, + Light, + MathUtils, + Mesh, + MeshStandardMaterial, + type Object3D, + PerspectiveCamera, + PlaneGeometry, + PointLight, + SphereGeometry, + Texture, +} from "@nanoforge-dev/graphics-3d/three"; + +import type { Box3D } from "./components/box-3d"; +import type { Camera3D } from "./components/camera-3d"; +import type { Light3D } from "./components/light-3d"; +import type { Object3DComponent } from "./components/object-3d-component"; +import type { Plane3D } from "./components/plane-3d"; +import type { Sphere3D } from "./components/sphere-3d"; + +type Params = Omit & { name: N }; +type ShapeParams = + Params | Params | Params; + +/** + * The params of a graphics-3d component, told apart by `name`: a component, or a plain object with + * the same fields (`{ name: "Box3D", width: 2, height: 1, depth: 1, color: "red" }`). + */ +export type Params3D = + | ShapeParams + | Params + | Params + | Params; + +/** A point or a vector on three axes, like `Position3D`. */ +export interface Xyz { + x: number; + y: number; + z: number; +} + +/** + * The Three.js object for a component's params: `draw3D` and the editor's 3D Scene screen both use + * it, so they show the same thing. + * + * @remarks + * Uses only Three.js, no ECS and no `ctx`. Pass the object it returned last time as `previous`: it + * comes back updated when it can be, and a new object when it can't (a light whose `kind` changed). + * The caller then removes and disposes the previous one ({@link disposeObject3D}). + */ +export const toObject3D = (params: Params3D, previous?: Object3D): Object3D => { + switch (params.name) { + case "Box3D": + case "Sphere3D": + case "Plane3D": + return meshFor(params, previous); + case "Light3D": + return lightFor(params, previous); + case "Camera3D": + return cameraFor(params, previous); + case "Object3DComponent": + return params.object; + } +}; + +/** Places an object: rotation in degrees, as in `Rotation3D`. Leaves out what isn't given. */ +export const applyTransform3D = (object: Object3D, position?: Xyz, rotation?: Xyz, scale?: Xyz) => { + if (position) object.position.set(position.x, position.y, position.z); + if (rotation) + object.rotation.set( + MathUtils.degToRad(rotation.x), + MathUtils.degToRad(rotation.y), + MathUtils.degToRad(rotation.z), + ); + if (scale) object.scale.set(scale.x, scale.y, scale.z); +}; + +/** Removes an object from its parent and frees the GPU memory of its geometries, materials and textures. */ +export const disposeObject3D = (object: Object3D) => { + object.removeFromParent(); + object.traverse((child) => { + const { geometry, material } = child as Object3D & { + geometry?: BufferGeometry; + material?: object | object[]; + }; + geometry?.dispose(); + for (const item of [material ?? []].flat()) { + for (const value of Object.values(item)) if (value instanceof Texture) value.dispose(); + (item as { dispose?(): void }).dispose?.(); + } + (child as { dispose?(): void }).dispose?.(); + }); +}; + +/** Sets a color only when its CSS string changed: parsing it every frame is wasted work. */ +const paint = (object: Object3D, color: Color, value: string) => { + if (object.userData.color === value) return; + color.set(value); + object.userData.color = value; +}; + +const geometryFor = (params: ShapeParams) => { + switch (params.name) { + case "Box3D": + return new BoxGeometry(params.width, params.height, params.depth); + case "Sphere3D": + return new SphereGeometry(params.radius, 32, 16); + case "Plane3D": + return new PlaneGeometry(params.width, params.height); + } +}; + +const meshFor = (params: ShapeParams, previous?: Object3D) => { + const mesh = + previous instanceof Mesh + ? (previous as Mesh) + : new Mesh(undefined, new MeshStandardMaterial()); + // The geometry is rebuilt only when a size changed. + const size = + params.name === "Sphere3D" + ? [params.radius] + : [params.width, params.height, params.name === "Box3D" ? params.depth : 0]; + const shape = `${params.name}:${size.join()}`; + if (mesh.userData.shape !== shape) { + mesh.geometry.dispose(); + mesh.geometry = geometryFor(params); + mesh.userData.shape = shape; + } + if (params.name === "Plane3D") mesh.material.side = DoubleSide; + paint(mesh, mesh.material.color, params.color); + return mesh; +}; + +const LIGHTS = { + ambient: () => new AmbientLight(), + directional: () => { + const light = new DirectionalLight(); + light.position.set(5, 10, 7); + return light; + }, + point: () => new PointLight(), +}; + +const lightFor = (params: Params, previous?: Object3D) => { + const light = + previous instanceof Light && previous.userData.kind === params.kind + ? previous + : LIGHTS[params.kind](); + light.userData.kind = params.kind; + paint(light, light.color, params.color); + light.intensity = params.intensity; + return light; +}; + +const cameraFor = (params: Params, previous?: Object3D) => { + let camera = previous as PerspectiveCamera; + if (!(previous instanceof PerspectiveCamera)) { + camera = new PerspectiveCamera(); + camera.position.set(0, 0, 5); + } + if (camera.fov !== params.fov || camera.near !== params.near || camera.far !== params.far) { + camera.fov = params.fov; + camera.near = params.near; + camera.far = params.far; + camera.updateProjectionMatrix(); + } + return camera; +}; diff --git a/packages/graphics-3d/systems/draw-3d.ts b/packages/graphics-3d/systems/draw-3d.ts new file mode 100644 index 0000000..9bb3d52 --- /dev/null +++ b/packages/graphics-3d/systems/draw-3d.ts @@ -0,0 +1,118 @@ +import type { Context } from "@nanoforge-dev/common"; +import type { Registry } from "@nanoforge-dev/ecs"; +import { + AmbientLight, + type Camera, + DirectionalLight, + Group, + type Object3D, + type Scene, +} from "@nanoforge-dev/graphics-3d/three"; +import { Position3D } from "@nanoforge/basics-3d/components/position-3d"; +import { Rotation3D } from "@nanoforge/basics-3d/components/rotation-3d"; +import { Scale3D } from "@nanoforge/basics-3d/components/scale-3d"; + +import { Box3D } from "../components/box-3d"; +import { Camera3D } from "../components/camera-3d"; +import { Light3D } from "../components/light-3d"; +import { Object3DComponent } from "../components/object-3d-component"; +import { Plane3D } from "../components/plane-3d"; +import { Sphere3D } from "../components/sphere-3d"; +import { type Params3D, applyTransform3D, disposeObject3D, toObject3D } from "../object-3d"; + +/** + * The 3D library's `ctx.graphics`, as far as this system uses it. The library's main entry types + * `Context.graphics` as the 3D API and graphics-2d as the 2D one, and every package here builds in + * one program: so only `@nanoforge-dev/graphics-3d/three` is imported. + */ +interface Graphics3D { + scene: Scene; + camera: Camera; +} + +/** What `draw3D` added to one app's scene. */ +interface Shown { + objects: Map; + defaultCamera: Camera; + defaultLight?: Object3D; +} + +/** Per scene, not per module: a restart makes a new scene. */ +const shownIn = new WeakMap(); + +/** The components `draw3D` shows, by the key the ECS gives them in a zipper. */ +const KINDS = { Box3D, Sphere3D, Plane3D, Light3D, Camera3D, Object3DComponent }; + +const defaultLight = () => { + const sun = new DirectionalLight(0xffffff, 2.5); + sun.position.set(5, 10, 7); + return new Group().add(new AmbientLight(0xffffff, 0.5), sun); +}; + +/** + * Shows the 3D components in the scene of `@nanoforge-dev/graphics-3d`: `Box3D`, `Sphere3D`, + * `Plane3D`, `Light3D`, `Camera3D` and `Object3DComponent`, placed by `Position3D`, `Rotation3D` + * and `Scale3D` (basics-3d). Add it after the systems that move entities. + * + * @remarks + * Each component gets its Three.js object the first frame it is seen, which follows its fields + * after that. A removed component, or a killed entity, loses its object, and its geometries, + * materials and textures are disposed. The first active `Camera3D` is the one shown. Until the + * scene has a light, it gets a default one (ambient and sun), so shapes are not black. + * + * @system + * @side client + * @uses graphics + */ +export const draw3D = (registry: Registry, ctx: Context) => { + const graphics = (ctx as unknown as { graphics?: Partial }).graphics; + if (!graphics?.scene || !graphics.camera) return; + const { scene } = graphics; + let shown = shownIn.get(scene); + if (!shown) shownIn.set(scene, (shown = { objects: new Map(), defaultCamera: graphics.camera })); + + const positions = new Map( + registry.getIndexedZipper([Position3D]).map(({ id, Position3D }) => [id, Position3D]), + ); + const rotations = new Map( + registry.getIndexedZipper([Rotation3D]).map(({ id, Rotation3D }) => [id, Rotation3D]), + ); + const scales = new Map( + registry.getIndexedZipper([Scale3D]).map(({ id, Scale3D }) => [id, Scale3D]), + ); + + const objects = new Map(); + let camera: Object3D | undefined; + for (const [key, Kind] of Object.entries(KINDS)) + registry + .getIndexedZipper([Kind]) + .forEach((row: { id: number } & Record) => { + const component = row[key]; + if (!component) return; + const previous = shown.objects.get(component); + const object = toObject3D(component, previous); + if (object !== previous) { + if (previous) disposeObject3D(previous); + scene.add(object); + } + applyTransform3D(object, positions.get(row.id), rotations.get(row.id), scales.get(row.id)); + objects.set(component, object); + if (component.name === "Camera3D" && component.active) camera ??= object; + }); + + // `killEntity` and `removeComponent` don't tell: an object whose component is gone goes here. + for (const [component, object] of shown.objects) + if (!objects.has(component)) disposeObject3D(object); + shown.objects = objects; + + const next = (camera as Camera | undefined) ?? shown.defaultCamera; + if (graphics.camera !== next) graphics.camera = next; + + // shortcut: only top-level lights count, not one inside an Object3DComponent's group; traverse if someone hits it. + const lit = scene.children.some((child) => "isLight" in child); + if (!lit && !shown.defaultLight) scene.add((shown.defaultLight = defaultLight())); + if (lit && shown.defaultLight) { + disposeObject3D(shown.defaultLight); + shown.defaultLight = undefined; + } +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 24e2c4c..933234a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,6 +31,9 @@ catalogs: '@nanoforge-dev/graphics-2d': specifier: ^3.0.0 version: 3.0.0 + '@nanoforge-dev/graphics-3d': + specifier: ^3.0.0 + version: 3.0.0 '@nanoforge-dev/input': specifier: ^3.0.0 version: 3.0.0 @@ -46,6 +49,9 @@ catalogs: '@nanoforge-dev/sound': specifier: ^3.0.0 version: 3.0.0 + three: + specifier: ^0.187.0 + version: 0.187.0 typescript: specifier: ^6.0.3 version: 6.0.3 @@ -99,6 +105,9 @@ importers: '@nanoforge-dev/graphics-2d': specifier: catalog:core version: 3.0.0 + '@nanoforge-dev/graphics-3d': + specifier: catalog:core + version: 3.0.0(@nanoforge-dev/editor-lib@3.0.0)(three@0.187.0) '@nanoforge-dev/input': specifier: catalog:core version: 3.0.0 @@ -138,6 +147,9 @@ importers: prettier: specifier: catalog:lint version: 3.10.1 + three: + specifier: catalog:core + version: 0.187.0 typescript: specifier: catalog:core version: 6.0.3 @@ -291,6 +303,9 @@ packages: resolution: {integrity: sha512-mHyyEL0eIEqJ6+aF24+AdZRo4bu4W5GdUiCiCx5X7kfDY51ye8GQJ264uOINObrRSKxtSRCOWPpl9hbOy4UzxQ==} engines: {node: '>=22'} + '@dimforge/rapier3d-compat@0.12.0': + resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==} + '@dprint/formatter@0.5.1': resolution: {integrity: sha512-cdZUrm0iv/FnnY3CKE2dEcVhNEzrC551aE2h2mTFwQCRBrqyARLDnb7D+3PlXTUVp3s34ftlnGOVCmhLT9DeKA==} @@ -416,6 +431,16 @@ packages: resolution: {integrity: sha512-0I0WUr5495jORdYR+HtyP4kmAfCMvixmG+EH/gE5bN33S8RO6/Ly4oMLZOLUywcDTAFuLn28BlHuVor2YfXrsg==} engines: {node: '26'} + '@nanoforge-dev/graphics-3d@3.0.0': + resolution: {integrity: sha512-yRY2ktlzgHQS0fdrdj+k5FjrBMGPQ3vFnw+Ag3vMv2mRRrFCwFBDzofpf1tSzluOyyTpJkgD2tmRpQZqC5CsLg==} + engines: {node: '26'} + peerDependencies: + '@nanoforge-dev/editor-lib': 3.0.0 + three: ^0.187.0 + peerDependenciesMeta: + '@nanoforge-dev/editor-lib': + optional: true + '@nanoforge-dev/input@3.0.0': resolution: {integrity: sha512-8pWU28c99VAvn37onNbVFfwXTgyQGxm5DVnTdBEzgrF3KPCzU77kEaexB1AWOlga+4qNGU7/XNm3hNZ+YS49Ig==} engines: {node: '26'} @@ -836,6 +861,9 @@ packages: svelte: optional: true + '@tweenjs/tween.js@23.1.3': + resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==} + '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -857,9 +885,18 @@ packages: '@types/node@26.0.1': resolution: {integrity: sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw==} + '@types/stats.js@0.17.4': + resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==} + + '@types/three@0.187.0': + resolution: {integrity: sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==} + '@types/validator@13.15.10': resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==} + '@types/webxr@0.5.24': + resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==} + '@typescript-eslint/eslint-plugin@8.72.1': resolution: {integrity: sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1263,6 +1300,9 @@ packages: picomatch: optional: true + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + figures@6.1.0: resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==} engines: {node: '>=18'} @@ -1601,6 +1641,9 @@ packages: resolution: {integrity: sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==} engines: {node: '>=18'} + meshoptimizer@1.1.1: + resolution: {integrity: sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==} + minimatch@10.2.6: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} @@ -1816,6 +1859,9 @@ packages: resolution: {integrity: sha512-U+/AXT6LWsxnj2vz9HeUuPWBNgdWxjyIEjEPdbJARC9txmgPzo2VEdqnFo4hHaNyMPtycyVJrSaQYeQv/PoyyA==} engines: {node: ^14.18.0 || >=16.0.0} + three@0.187.0: + resolution: {integrity: sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -2195,6 +2241,8 @@ snapshots: '@conventional-changelog/template@1.4.1': {} + '@dimforge/rapier3d-compat@0.12.0': {} + '@dprint/formatter@0.5.1': {} '@dprint/markdown@0.21.1': {} @@ -2321,6 +2369,14 @@ snapshots: - canvas - skia-canvas + '@nanoforge-dev/graphics-3d@3.0.0(@nanoforge-dev/editor-lib@3.0.0)(three@0.187.0)': + dependencies: + '@nanoforge-dev/common': 3.0.0 + '@types/three': 0.187.0 + three: 0.187.0 + optionalDependencies: + '@nanoforge-dev/editor-lib': 3.0.0 + '@nanoforge-dev/input@3.0.0': dependencies: '@nanoforge-dev/common': 3.0.0 @@ -2596,6 +2652,8 @@ snapshots: transitivePeerDependencies: - supports-color + '@tweenjs/tween.js@23.1.3': {} + '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -2619,8 +2677,21 @@ snapshots: undici-types: 8.3.0 optional: true + '@types/stats.js@0.17.4': {} + + '@types/three@0.187.0': + dependencies: + '@dimforge/rapier3d-compat': 0.12.0 + '@tweenjs/tween.js': 23.1.3 + '@types/stats.js': 0.17.4 + '@types/webxr': 0.5.24 + fflate: 0.8.3 + meshoptimizer: 1.1.1 + '@types/validator@13.15.10': {} + '@types/webxr@0.5.24': {} + '@typescript-eslint/eslint-plugin@8.72.1(@typescript-eslint/parser@8.72.1(eslint@10.14.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.14.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -3078,6 +3149,8 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fflate@0.8.3: {} + figures@6.1.0: dependencies: is-unicode-supported: 2.1.0 @@ -3335,6 +3408,8 @@ snapshots: meow@13.2.0: {} + meshoptimizer@1.1.1: {} + minimatch@10.2.6: dependencies: brace-expansion: 5.0.12 @@ -3558,6 +3633,8 @@ snapshots: '@dual-bundle/import-meta-resolve': 4.2.1 '@pkgr/core': 0.3.6 + three@0.187.0: {} + tinybench@2.9.0: {} tinyexec@1.3.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index fdb84f6..d37a46f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -12,11 +12,13 @@ catalogs: '@nanoforge-dev/ecs': ^3.0.0 '@nanoforge-dev/editor-lib': ^3.0.0 '@nanoforge-dev/graphics-2d': ^3.0.0 + '@nanoforge-dev/graphics-3d': ^3.0.0 '@nanoforge-dev/input': ^3.0.0 '@nanoforge-dev/music': ^3.0.0 '@nanoforge-dev/network': ^3.0.0 '@nanoforge-dev/scene': ^3.0.0 '@nanoforge-dev/sound': ^3.0.0 + three: ^0.187.0 typescript: ^6.0.3 lint: '@eslint/js': ^10.0.1 diff --git a/test/graphics-3d.spec.ts b/test/graphics-3d.spec.ts new file mode 100644 index 0000000..21b4990 --- /dev/null +++ b/test/graphics-3d.spec.ts @@ -0,0 +1,206 @@ +import type { Context } from "@nanoforge-dev/common"; +import { + AmbientLight, + type BoxGeometry, + type Camera, + DirectionalLight, + Group, + type Light, + Mesh, + MeshStandardMaterial, + type Object3D, + PerspectiveCamera, + PlaneGeometry, + PointLight, + Scene, + SphereGeometry, + Texture, + TorusGeometry, +} from "@nanoforge-dev/graphics-3d/three"; +import { Position3D } from "@nanoforge/basics-3d/components/position-3d"; +import { Rotation3D } from "@nanoforge/basics-3d/components/rotation-3d"; +import { Scale3D } from "@nanoforge/basics-3d/components/scale-3d"; +import { Box3D } from "@nanoforge/graphics-3d/components/box-3d"; +import { Camera3D } from "@nanoforge/graphics-3d/components/camera-3d"; +import { Light3D } from "@nanoforge/graphics-3d/components/light-3d"; +import { Object3DComponent } from "@nanoforge/graphics-3d/components/object-3d-component"; +import { Plane3D } from "@nanoforge/graphics-3d/components/plane-3d"; +import { Sphere3D } from "@nanoforge/graphics-3d/components/sphere-3d"; +import { toObject3D } from "@nanoforge/graphics-3d/object-3d"; +import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; +import { describe, expect, it, vi } from "vitest"; + +import { registry, run, spawn, useEcs } from "./helpers"; + +useEcs(); + +/** The part of graphics-3d's `ctx.graphics` that `draw3D` uses: a real scene and camera. */ +const graphics3D = () => { + const graphics = { scene: new Scene(), camera: new PerspectiveCamera() as Camera }; + return { graphics, ctx: { app: { delta: 16 }, graphics } as unknown as Context }; +}; + +/** What `draw3D` added for its components, without the default light. */ +const shown = (scene: Scene) => scene.children.filter((child) => !(child instanceof Group)); + +describe("graphics-3d", () => { + it("shows each shape, light, camera and object, placed by Position3D, Rotation3D and Scale3D", () => { + const { graphics, ctx } = graphics3D(); + const torus = new Mesh(new TorusGeometry(), new MeshStandardMaterial()); + spawn(new Box3D(2, 3, 4, "#ff0000"), new Position3D(1, 2, 3), new Rotation3D(90, 0, -180)); + spawn(new Sphere3D(0.75, "blue"), new Scale3D(2, 2, 2)); + spawn(new Plane3D(10, 6)); + spawn(new Light3D("point", "#ffffff", 20), new Position3D(0, 4, 0)); + spawn(new Camera3D(60)); + spawn(new Object3DComponent(torus), new Position3D(-5, 0, 0)); + registry.addSystem(draw3D); + + run(ctx); + + const [box, sphere, plane, light, camera, object] = shown(graphics.scene) as Mesh[]; + expect((box?.geometry as BoxGeometry).parameters).toMatchObject({ + width: 2, + height: 3, + depth: 4, + }); + expect((box?.material as MeshStandardMaterial).color.getHexString()).toBe("ff0000"); + expect(box?.position.toArray()).toEqual([1, 2, 3]); + expect(box?.rotation.x).toBeCloseTo(Math.PI / 2); + expect(box?.rotation.z).toBeCloseTo(-Math.PI); + expect(sphere?.geometry).toBeInstanceOf(SphereGeometry); + expect(sphere?.scale.toArray()).toEqual([2, 2, 2]); + expect(plane?.geometry).toBeInstanceOf(PlaneGeometry); + expect(light).toBeInstanceOf(PointLight); + expect((light as unknown as Light).intensity).toBe(20); + expect(light?.position.y).toBe(4); + expect(object).toBe(torus); + expect(torus.position.x).toBe(-5); + expect(graphics.camera).toBe(camera); + expect((camera as unknown as PerspectiveCamera).fov).toBe(60); + }); + + it("follows the fields: a new size rebuilds the geometry, a new color repaints, a new kind replaces the light", () => { + const { graphics, ctx } = graphics3D(); + const box = new Box3D(); + const light = new Light3D("directional"); + spawn(box); + spawn(light); + registry.addSystem(draw3D); + run(ctx); + const [mesh, sun] = shown(graphics.scene) as [Mesh, DirectionalLight]; + const oldGeometry = mesh.geometry; + const disposeGeometry = vi.spyOn(oldGeometry, "dispose"); + const disposeSun = vi.spyOn(sun, "dispose"); + + run(ctx); + expect(mesh.geometry).toBe(oldGeometry); + + box.width = 5; + box.color = "#00ff00"; + light.kind = "ambient"; + run(ctx); + + expect(shown(graphics.scene)[0]).toBe(mesh); + expect(mesh.geometry).not.toBe(oldGeometry); + expect((mesh.geometry as BoxGeometry).parameters).toMatchObject({ width: 5 }); + expect(disposeGeometry).toHaveBeenCalledOnce(); + expect((mesh.material as MeshStandardMaterial).color.getHexString()).toBe("00ff00"); + expect(shown(graphics.scene)[1]).toBeInstanceOf(AmbientLight); + expect(sun.parent).toBeNull(); + expect(disposeSun).toHaveBeenCalledOnce(); + }); + + it("removes and disposes the object of a killed entity or a removed component", () => { + const { graphics, ctx } = graphics3D(); + const texture = new Texture(); + const material = new MeshStandardMaterial({ map: texture }); + const torus = new Mesh(new TorusGeometry(), material); + const killed = spawn(new Box3D()); + const stripped = spawn(new Object3DComponent(torus)); + registry.addSystem(draw3D); + run(ctx); + const [box] = shown(graphics.scene) as [Mesh]; + const disposed = [ + vi.spyOn(box.geometry, "dispose"), + vi.spyOn(box.material as MeshStandardMaterial, "dispose"), + vi.spyOn(torus.geometry, "dispose"), + vi.spyOn(material, "dispose"), + vi.spyOn(texture, "dispose"), + ]; + + registry.killEntity(killed); + registry.removeComponent(stripped, Object3DComponent); + run(ctx); + + expect(shown(graphics.scene)).toEqual([]); + for (const dispose of disposed) expect(dispose).toHaveBeenCalledOnce(); + }); + + it("lights an unlit scene by default, until it has a light of its own", () => { + const { graphics, ctx } = graphics3D(); + registry.addSystem(draw3D); + run(ctx); + + const rig = graphics.scene.children.find((child) => child instanceof Group); + expect(rig?.children.map((light) => light.type)).toEqual(["AmbientLight", "DirectionalLight"]); + + const lamp = spawn(new Light3D()); + run(ctx); + expect(graphics.scene.children.some((child) => child instanceof Group)).toBe(false); + + registry.killEntity(lamp); + run(ctx); + expect(graphics.scene.children.some((child) => child instanceof Group)).toBe(true); + }); + + it("shows the first active camera, from (0, 0, 5) without a Position3D, and the library's one without any", () => { + const { graphics, ctx } = graphics3D(); + const libraryCamera = graphics.camera; + const off = new Camera3D(70, 0.1, 1000, false); + const on = new Camera3D(40); + spawn(off); + const entity = spawn(on); + registry.addSystem(draw3D); + run(ctx); + + expect((graphics.camera as PerspectiveCamera).fov).toBe(40); + expect(graphics.camera.position.toArray()).toEqual([0, 0, 5]); + + on.active = false; + run(ctx); + expect(graphics.camera).toBe(libraryCamera); + + on.active = true; + run(ctx); + registry.killEntity(entity); + run(ctx); + expect(graphics.camera).toBe(libraryCamera); + }); + + it("does nothing in an app without graphics-3d", () => { + spawn(new Box3D()); + registry.addSystem(draw3D); + + expect(() => run({ app: { delta: 16 } } as unknown as Context)).not.toThrow(); + }); + + it("toObject3D maps plain params, and updates the object it is given", () => { + const box = toObject3D({ name: "Box3D", width: 2, height: 1, depth: 1, color: "red" }) as Mesh; + const plane = toObject3D({ name: "Plane3D", width: 4, height: 4, color: "#888888" }) as Mesh; + const sun = toObject3D({ name: "Light3D", kind: "directional", color: "white", intensity: 3 }); + const camera = toObject3D({ name: "Camera3D", fov: 75, near: 1, far: 50, active: true }); + + expect((box.geometry as BoxGeometry).parameters).toMatchObject({ width: 2 }); + expect((plane.material as MeshStandardMaterial).side).toBe(2); // DoubleSide + expect(sun).toBeInstanceOf(DirectionalLight); + expect(sun.position.toArray()).toEqual([5, 10, 7]); + expect(camera).toMatchObject({ fov: 75, near: 1, far: 50 }); + + const same: Object3D = toObject3D( + { name: "Box3D", width: 3, height: 1, depth: 1, color: "red" }, + box, + ); + expect(same).toBe(box); + expect(((same as Mesh).geometry as BoxGeometry).parameters).toMatchObject({ width: 3 }); + }); +}); diff --git a/test/recipes.spec.ts b/test/recipes.spec.ts index 29a8ee6..1825507 100644 --- a/test/recipes.spec.ts +++ b/test/recipes.spec.ts @@ -1,4 +1,6 @@ +import type { Context } from "@nanoforge-dev/common"; import { Layer } from "@nanoforge-dev/graphics-2d"; +import { Mesh, PerspectiveCamera, Scene } from "@nanoforge-dev/graphics-3d/three"; import { InputEnum } from "@nanoforge-dev/input"; import { ControllerButton } from "@nanoforge-dev/input/controller"; import { MuteOnKey } from "@nanoforge/audio/components/mute-on-key"; @@ -12,6 +14,9 @@ import { Velocity2D } from "@nanoforge/basics-2d/components/velocity-2d"; import { FromModel } from "@nanoforge/basics-2d/models"; import { expireLifetimes } from "@nanoforge/basics-2d/systems/expire-lifetimes"; import { move2D } from "@nanoforge/basics-2d/systems/move-2d"; +import { Position3D } from "@nanoforge/basics-3d/components/position-3d"; +import { Velocity3D } from "@nanoforge/basics-3d/components/velocity-3d"; +import { move3D } from "@nanoforge/basics-3d/systems/move-3d"; import { DamageOnHit2D } from "@nanoforge/combat-2d/components/damage-on-hit-2d"; import { DestroyOnHit2D } from "@nanoforge/combat-2d/components/destroy-on-hit-2d"; import { FaceAim2D } from "@nanoforge/combat-2d/components/face-aim-2d"; @@ -55,6 +60,11 @@ import { faceTarget2D } from "@nanoforge/graphics-2d/systems/face-target-2d"; import { faceVelocity2D } from "@nanoforge/graphics-2d/systems/face-velocity-2d"; import { fadeOut2D } from "@nanoforge/graphics-2d/systems/fade-out-2d"; import { followCamera2D } from "@nanoforge/graphics-2d/systems/follow-camera-2d"; +import { Box3D } from "@nanoforge/graphics-3d/components/box-3d"; +import { Camera3D } from "@nanoforge/graphics-3d/components/camera-3d"; +import { Light3D } from "@nanoforge/graphics-3d/components/light-3d"; +import { Sphere3D } from "@nanoforge/graphics-3d/components/sphere-3d"; +import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; import { NetworkId } from "@nanoforge/network-2d/components/network-id"; import { Sync2DPacket, SyncRequestPacket } from "@nanoforge/network-2d/sync-packets"; import { syncFromServer2D } from "@nanoforge/network-2d/systems/sync-from-server-2d"; @@ -921,3 +931,26 @@ describe("recipes: multiplayer (movement only)", () => { expect(fake.network.sent).toContainEqual({ remove: 2 }); }); }); + +describe("recipes: 3D", () => { + it("a cube, a ball, a light and a camera: the cube rises, lit by the sun, seen from the camera", () => { + const graphics = { scene: new Scene(), camera: new PerspectiveCamera() }; + const ctx = { app: { delta: FRAME }, graphics } as unknown as Context; + spawn(new Box3D(1, 1, 1, "#44aa88"), new Position3D(-1, 0, 0), new Velocity3D(0, 0.5, 0)); + spawn(new Sphere3D(0.5, "#ff6b6b"), new Position3D(1, 0, 0)); + spawn(new Light3D("directional", "#ffffff", 3), new Position3D(3, 5, 4)); + spawn(new Camera3D(), new Position3D(0, 1, 6)); + add(move3D, draw3D); + + for (let i = 0; i < 60; i++) run(ctx); + + const [cube, ball, sun, camera] = graphics.scene.children; + expect(graphics.scene.children).toHaveLength(4); + expect(cube).toBeInstanceOf(Mesh); + expect(cube?.position.y).toBeCloseTo(0.5); + expect(ball?.position.x).toBe(1); + expect(sun?.position.toArray()).toEqual([3, 5, 4]); + expect(graphics.camera).toBe(camera); + expect(camera?.position.toArray()).toEqual([0, 1, 6]); + }); +}); From 1e0670d00f5b2f2adecdf761667302d25b84d7f3 Mon Sep 17 00:00:00 2001 From: Leo Date: Thu, 26 Nov 2026 11:24:24 +0100 Subject: [PATCH 2/2] fix(graphi-3d): graphic packages conflicts --- .claude/skills/new-ecs-package/SKILL.md | 8 ++++- AGENTS.md | 41 +++++++++++++-------- package.json | 5 +-- packages/graphics-3d/systems/draw-3d.ts | 23 ++++-------- test/{ => 3d}/graphics-3d.spec.ts | 32 ++++++++--------- test/3d/recipes.spec.ts | 44 +++++++++++++++++++++++ test/ecs.ts | 48 +++++++++++++++++++++++++ test/helpers.ts | 40 ++++----------------- test/recipes.spec.ts | 33 ----------------- tsconfig.3d.json | 9 +++++ tsconfig.json | 4 ++- tsconfig.spec.3d.json | 9 +++++ tsconfig.spec.json | 7 ++-- vitest.config.ts | 23 +++++++++--- 14 files changed, 202 insertions(+), 124 deletions(-) rename test/{ => 3d}/graphics-3d.spec.ts (95%) create mode 100644 test/3d/recipes.spec.ts create mode 100644 test/ecs.ts create mode 100644 tsconfig.3d.json create mode 100644 tsconfig.spec.3d.json diff --git a/.claude/skills/new-ecs-package/SKILL.md b/.claude/skills/new-ecs-package/SKILL.md index 23d128d..d57cb4f 100644 --- a/.claude/skills/new-ecs-package/SKILL.md +++ b/.claude/skills/new-ecs-package/SKILL.md @@ -101,7 +101,10 @@ export const myThing2D = (registry: Registry, ctx: Context) => { ## 3. Register it Nothing in code: the manifest's `contents` already points at `components/` and `systems/`, and -`tsconfig.json` builds `packages/**/*.ts`. Update by hand: +`tsconfig.json` builds `packages/**/*.ts`. A package that uses `@nanoforge-dev/graphics-3d` +builds in `tsconfig.3d.json` instead (add it to the `include` of `tsconfig.3d.json` and `tsconfig.spec.3d.json`, and to the +`exclude` of `tsconfig.json` and `tsconfig.spec.json`), and its +spec goes in `test/3d/`, importing `../ecs`: both graphics libs type `ctx.graphics`. Update by hand: - `packages//README.md`: one line for the item (and with which system it works); - a new system: its place in _Order of the systems_ in `docs/default-packages.md`, and the order @@ -154,6 +157,9 @@ The 70% coverage thresholds cover every `packages/**/*.ts`: a new item comes wit `fake.buttons`. - A graphics item: in the same file, which calls `stubDocument()` so Konva shapes run without a canvas; `fakeLayer()` records what is drawn. +- A graphics-3d item: in `test/3d/.spec.ts`, which imports `../ecs` (`useRegistry()`, + `spawn`, `runOn(ctx)`), not `test/helpers.ts`, and builds its ctx with a real `Scene` and + `PerspectiveCamera` from `@nanoforge-dev/graphics-3d/three`. - A recipe that crosses packages (a README's): in `test/recipes.spec.ts`. - Import with the alias: `@nanoforge//systems/`. diff --git a/AGENTS.md b/AGENTS.md index 1ba196d..b848de2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,14 +22,18 @@ packages: the root `package.json` is private and `pnpm-workspace.yaml` lists no ## Stack -- TypeScript, strict, built with `tsc -b` (`tsconfig.json` includes `packages/**/*.ts`). +- TypeScript, strict, built with `tsc -b` in two programs: `tsconfig.json` (`packages/**/*.ts` + but graphics-3d) and `tsconfig.3d.json` (the graphics-3d packages). - Engine libs from the `core` catalog of `pnpm-workspace.yaml`: `@nanoforge-dev/common`, `@nanoforge-dev/ecs`, `@nanoforge-dev/graphics-2d`, `@nanoforge-dev/input`, `@nanoforge-dev/scene`, `@nanoforge-dev/sound`, `@nanoforge-dev/music`, `@nanoforge-dev/network`, `@nanoforge-dev/graphics-3d` (all `^3.0.0`), and `three` (`^0.187.0`, graphics-3d's peer). `@nanoforge-dev/editor-lib` is there only for the typings of `scene`, `sound`, `music` and `network`, which import it. -- Vitest with typechecking (`tsconfig.spec.json`) and v8 coverage on `packages/**/*.ts`. +- Vitest, in a `2d` and a `3d` project, and v8 coverage on `packages/**/*.ts`. Vitest typechecks + nothing: `pnpm run typecheck` (in `lint`) runs `tsc` on `tsconfig.spec.json` and + `tsconfig.spec.3d.json`, which cover the packages and the specs of each program, libs included, + so a program that loads both graphics libs fails (TS2717). - ESLint and Prettier from the shared `@nanoforge-dev/utils-eslint-config` and `@nanoforge-dev/utils-prettier-config` (double quotes, trailing commas, 100 columns, sorted imports). @@ -47,17 +51,20 @@ packages// ├── systems/.ts # one system function per file └── .ts # shared code that is not an item (collisions.ts, image-fill.ts...) test/ -├── helpers.ts # the ECS registry, the fake ctx (`fake`, `frame`), `spawn`, `run` +├── ecs.ts # the ECS registry, `spawn`, `runOn`, `useRegistry`: no engine typings +├── helpers.ts # re-exports ecs.ts; the fake ctx (`fake`, `frame`), `run`, `useEcs` ├── .spec.ts # one per package: its items, on a real ECS registry -└── recipes.spec.ts # the READMEs' recipes end to end, across packages +├── recipes.spec.ts # the READMEs' recipes end to end, across packages +└── 3d/ # specs of the graphics-3d packages: they import ecs.ts, not helpers.ts docs/default-packages.md # packages a new project gets, and the order of every system ``` ## Commands ```sh -pnpm run build # tsc -b -pnpm run lint # prettier --check . && eslint --format=pretty packages +pnpm run build # tsc -b tsconfig.json tsconfig.3d.json +pnpm run lint # prettier --check . && eslint --format=pretty packages && typecheck +pnpm run typecheck # tsc --noEmit on tsconfig.spec.json and tsconfig.spec.3d.json pnpm run format # prettier --write . && eslint --fix --format=pretty packages pnpm run test # = test:unit: vitest, fails under 70% lines, functions, branches or statements ``` @@ -108,11 +115,13 @@ editor reads each item from its `.ts` file (NanoForge-dev/editor - `ctx.network` is the exception: `@nanoforge-dev/network/client` and `/server` both declare it, with other types, so one program can't import both. `network-2d` imports `PacketDefinition` from the root and types the part of `ctx.network` it uses (`sync-to-clients-2d.ts`). -- `ctx.graphics` in 3D too: the main entry of `@nanoforge-dev/graphics-3d` declares it with the 3D - type, and graphics-2d with the 2D one. `graphics-3d` imports only - `@nanoforge-dev/graphics-3d/three` (which declares nothing), types the part of `ctx.graphics` it - uses (`draw-3d.ts`), and tags the system `@uses graphics`. Every one of its component files - imports `/three` too, even a bare `import`, so the editor offers it only to 3D apps. +- `ctx.graphics` is declared by both graphics-2d and graphics-3d, with other types, so one program + can't load both (TS2717); a game never does. The packages that use graphics-3d build apart: they + are in `tsconfig.3d.json` and out of `tsconfig.json`, and their specs are in `test/3d/` + (`tsconfig.spec.3d.json`, the `3d` Vitest project). A package never imports both graphics libs. + `draw3D` imports `@nanoforge-dev/graphics-3d` like `draw2D` imports graphics-2d; every + graphics-3d component file imports `@nanoforge-dev/graphics-3d/three`, even a bare `import`, so + the editor offers it only to 3D apps. - Mouse positions are on the screen: an item placed in the world converts them with `toWorld` or `pointFor` (`graphics-2d/world.ts`), so it works under a `Camera2D` and on `Hud2D` entities. - `nanoforge.manifest.json` mirrors the imports: each `@nanoforge/` used goes in `dependencies` @@ -126,7 +135,9 @@ editor reads each item from its `.ts` file (NanoForge-dev/editor Nothing to register in code: every manifest's `contents` points at the folders (`{ "kind": "@nanoforge/ecs:component", "path": "components/" }` and `…:system` on `systems/`), and -`tsconfig.json` builds every `packages/**/*.ts`. By hand: +`tsconfig.json` builds every `packages/**/*.ts` but the graphics-3d ones, which `tsconfig.3d.json` +builds (a new 3D package goes in the `include` of `tsconfig.3d.json` and `tsconfig.spec.3d.json`, +and in the `exclude` of `tsconfig.json` and `tsconfig.spec.json`). By hand: - the package's `README.md`: one line for the item; - a new system: its place in _Order of the systems_ in `docs/default-packages.md`, and in its @@ -151,8 +162,10 @@ The skill `.claude/skills/new-ecs-package` walks through it. canvas. A system's module state (`click2D`'s buttons, `draw2D`'s shapes, a warning flag) lasts the whole spec file. - Import from the packages with the `@nanoforge/*` alias. The 70% thresholds apply to all of - `packages/**/*.ts`: a new item comes with its test. Vitest's typecheck misses some declaration - errors in `test/`: run `pnpm exec tsc --noEmit -p tsconfig.spec.json` too. + `packages/**/*.ts`: a new item comes with its test. Vitest typechecks nothing (only + `*.spec-d.ts` files, and there are none): `pnpm run typecheck` does. +- A graphics-3d spec goes in `test/3d/` and imports `../ecs`: `helpers.ts` loads graphics-2d's + typings (its fake Konva layers), which type `ctx.graphics` for 2D. ## Releases diff --git a/package.json b/package.json index eaf0eca..dcfcd92 100644 --- a/package.json +++ b/package.json @@ -32,8 +32,9 @@ }, "funding": "https://github.com/NanoForge-dev/components-systems?sponsor", "scripts": { - "build": "tsc -b", - "lint": "prettier --check . && eslint --format=pretty packages", + "build": "tsc -b tsconfig.json tsconfig.3d.json", + "lint": "prettier --check . && eslint --format=pretty packages && pnpm run typecheck", + "typecheck": "tsc --noEmit -p tsconfig.spec.json && tsc --noEmit -p tsconfig.spec.3d.json", "format": "prettier --write . && eslint --fix --format=pretty packages", "test:unit": "vitest run --config vitest.config.ts --coverage.thresholds.lines=70 --coverage.thresholds.functions=70 --coverage.thresholds.branches=70 --coverage.thresholds.statements=70", "test": "pnpm run test:unit", diff --git a/packages/graphics-3d/systems/draw-3d.ts b/packages/graphics-3d/systems/draw-3d.ts index 9bb3d52..6813713 100644 --- a/packages/graphics-3d/systems/draw-3d.ts +++ b/packages/graphics-3d/systems/draw-3d.ts @@ -1,5 +1,6 @@ import type { Context } from "@nanoforge-dev/common"; import type { Registry } from "@nanoforge-dev/ecs"; +import "@nanoforge-dev/graphics-3d"; import { AmbientLight, type Camera, @@ -20,16 +21,6 @@ import { Plane3D } from "../components/plane-3d"; import { Sphere3D } from "../components/sphere-3d"; import { type Params3D, applyTransform3D, disposeObject3D, toObject3D } from "../object-3d"; -/** - * The 3D library's `ctx.graphics`, as far as this system uses it. The library's main entry types - * `Context.graphics` as the 3D API and graphics-2d as the 2D one, and every package here builds in - * one program: so only `@nanoforge-dev/graphics-3d/three` is imported. - */ -interface Graphics3D { - scene: Scene; - camera: Camera; -} - /** What `draw3D` added to one app's scene. */ interface Shown { objects: Map; @@ -62,14 +53,14 @@ const defaultLight = () => { * * @system * @side client - * @uses graphics */ export const draw3D = (registry: Registry, ctx: Context) => { - const graphics = (ctx as unknown as { graphics?: Partial }).graphics; - if (!graphics?.scene || !graphics.camera) return; - const { scene } = graphics; + // An app without Graphics3DLibrary has no `ctx.graphics`, or graphics-2d's. + if (!ctx.graphics?.scene) return; + const { scene } = ctx.graphics; let shown = shownIn.get(scene); - if (!shown) shownIn.set(scene, (shown = { objects: new Map(), defaultCamera: graphics.camera })); + if (!shown) + shownIn.set(scene, (shown = { objects: new Map(), defaultCamera: ctx.graphics.camera })); const positions = new Map( registry.getIndexedZipper([Position3D]).map(({ id, Position3D }) => [id, Position3D]), @@ -106,7 +97,7 @@ export const draw3D = (registry: Registry, ctx: Context) => { shown.objects = objects; const next = (camera as Camera | undefined) ?? shown.defaultCamera; - if (graphics.camera !== next) graphics.camera = next; + if (ctx.graphics.camera !== next) ctx.graphics.camera = next; // shortcut: only top-level lights count, not one inside an Object3DComponent's group; traverse if someone hits it. const lit = scene.children.some((child) => "isLight" in child); diff --git a/test/graphics-3d.spec.ts b/test/3d/graphics-3d.spec.ts similarity index 95% rename from test/graphics-3d.spec.ts rename to test/3d/graphics-3d.spec.ts index 21b4990..2dcf227 100644 --- a/test/graphics-3d.spec.ts +++ b/test/3d/graphics-3d.spec.ts @@ -30,9 +30,9 @@ import { toObject3D } from "@nanoforge/graphics-3d/object-3d"; import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; import { describe, expect, it, vi } from "vitest"; -import { registry, run, spawn, useEcs } from "./helpers"; +import { registry, runOn, spawn, useRegistry } from "../ecs"; -useEcs(); +useRegistry(); /** The part of graphics-3d's `ctx.graphics` that `draw3D` uses: a real scene and camera. */ const graphics3D = () => { @@ -55,7 +55,7 @@ describe("graphics-3d", () => { spawn(new Object3DComponent(torus), new Position3D(-5, 0, 0)); registry.addSystem(draw3D); - run(ctx); + runOn(ctx); const [box, sphere, plane, light, camera, object] = shown(graphics.scene) as Mesh[]; expect((box?.geometry as BoxGeometry).parameters).toMatchObject({ @@ -86,19 +86,19 @@ describe("graphics-3d", () => { spawn(box); spawn(light); registry.addSystem(draw3D); - run(ctx); + runOn(ctx); const [mesh, sun] = shown(graphics.scene) as [Mesh, DirectionalLight]; const oldGeometry = mesh.geometry; const disposeGeometry = vi.spyOn(oldGeometry, "dispose"); const disposeSun = vi.spyOn(sun, "dispose"); - run(ctx); + runOn(ctx); expect(mesh.geometry).toBe(oldGeometry); box.width = 5; box.color = "#00ff00"; light.kind = "ambient"; - run(ctx); + runOn(ctx); expect(shown(graphics.scene)[0]).toBe(mesh); expect(mesh.geometry).not.toBe(oldGeometry); @@ -118,7 +118,7 @@ describe("graphics-3d", () => { const killed = spawn(new Box3D()); const stripped = spawn(new Object3DComponent(torus)); registry.addSystem(draw3D); - run(ctx); + runOn(ctx); const [box] = shown(graphics.scene) as [Mesh]; const disposed = [ vi.spyOn(box.geometry, "dispose"), @@ -130,7 +130,7 @@ describe("graphics-3d", () => { registry.killEntity(killed); registry.removeComponent(stripped, Object3DComponent); - run(ctx); + runOn(ctx); expect(shown(graphics.scene)).toEqual([]); for (const dispose of disposed) expect(dispose).toHaveBeenCalledOnce(); @@ -139,17 +139,17 @@ describe("graphics-3d", () => { it("lights an unlit scene by default, until it has a light of its own", () => { const { graphics, ctx } = graphics3D(); registry.addSystem(draw3D); - run(ctx); + runOn(ctx); const rig = graphics.scene.children.find((child) => child instanceof Group); expect(rig?.children.map((light) => light.type)).toEqual(["AmbientLight", "DirectionalLight"]); const lamp = spawn(new Light3D()); - run(ctx); + runOn(ctx); expect(graphics.scene.children.some((child) => child instanceof Group)).toBe(false); registry.killEntity(lamp); - run(ctx); + runOn(ctx); expect(graphics.scene.children.some((child) => child instanceof Group)).toBe(true); }); @@ -161,19 +161,19 @@ describe("graphics-3d", () => { spawn(off); const entity = spawn(on); registry.addSystem(draw3D); - run(ctx); + runOn(ctx); expect((graphics.camera as PerspectiveCamera).fov).toBe(40); expect(graphics.camera.position.toArray()).toEqual([0, 0, 5]); on.active = false; - run(ctx); + runOn(ctx); expect(graphics.camera).toBe(libraryCamera); on.active = true; - run(ctx); + runOn(ctx); registry.killEntity(entity); - run(ctx); + runOn(ctx); expect(graphics.camera).toBe(libraryCamera); }); @@ -181,7 +181,7 @@ describe("graphics-3d", () => { spawn(new Box3D()); registry.addSystem(draw3D); - expect(() => run({ app: { delta: 16 } } as unknown as Context)).not.toThrow(); + expect(() => runOn({ app: { delta: 16 } } as unknown as Context)).not.toThrow(); }); it("toObject3D maps plain params, and updates the object it is given", () => { diff --git a/test/3d/recipes.spec.ts b/test/3d/recipes.spec.ts new file mode 100644 index 0000000..cfb26ee --- /dev/null +++ b/test/3d/recipes.spec.ts @@ -0,0 +1,44 @@ +import type { Context } from "@nanoforge-dev/common"; +import { Mesh, PerspectiveCamera, Scene } from "@nanoforge-dev/graphics-3d/three"; +import { Position3D } from "@nanoforge/basics-3d/components/position-3d"; +import { Velocity3D } from "@nanoforge/basics-3d/components/velocity-3d"; +import { move3D } from "@nanoforge/basics-3d/systems/move-3d"; +import { Box3D } from "@nanoforge/graphics-3d/components/box-3d"; +import { Camera3D } from "@nanoforge/graphics-3d/components/camera-3d"; +import { Light3D } from "@nanoforge/graphics-3d/components/light-3d"; +import { Sphere3D } from "@nanoforge/graphics-3d/components/sphere-3d"; +import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; +import { describe, expect, it } from "vitest"; + +import { registry, runOn, spawn, useRegistry } from "../ecs"; + +/* + * The 3D recipes of the packages' READMEs, end to end, apart from `../recipes.spec.ts`: these + * build with graphics-3d's typings (tsconfig.spec.3d.json), the 2D ones with graphics-2d's. + */ + +useRegistry(); + +describe("recipes: 3D", () => { + it("a cube, a ball, a light and a camera: the cube rises, lit by the sun, seen from the camera", () => { + const graphics = { scene: new Scene(), camera: new PerspectiveCamera() }; + const ctx = { app: { delta: 1000 / 60 }, graphics } as unknown as Context; + spawn(new Box3D(1, 1, 1, "#44aa88"), new Position3D(-1, 0, 0), new Velocity3D(0, 0.5, 0)); + spawn(new Sphere3D(0.5, "#ff6b6b"), new Position3D(1, 0, 0)); + spawn(new Light3D("directional", "#ffffff", 3), new Position3D(3, 5, 4)); + spawn(new Camera3D(), new Position3D(0, 1, 6)); + registry.addSystem(move3D); + registry.addSystem(draw3D); + + for (let i = 0; i < 60; i++) runOn(ctx); + + const [cube, ball, sun, camera] = graphics.scene.children; + expect(graphics.scene.children).toHaveLength(4); + expect(cube).toBeInstanceOf(Mesh); + expect(cube?.position.y).toBeCloseTo(0.5); + expect(ball?.position.x).toBe(1); + expect(sun?.position.toArray()).toEqual([3, 5, 4]); + expect(graphics.camera).toBe(camera); + expect(camera?.position.toArray()).toEqual([0, 1, 6]); + }); +}); diff --git a/test/ecs.ts b/test/ecs.ts new file mode 100644 index 0000000..15eef1d --- /dev/null +++ b/test/ecs.ts @@ -0,0 +1,48 @@ +import type { Context, InitContext } from "@nanoforge-dev/common"; +import { EcsLibrary, type Registry } from "@nanoforge-dev/ecs/server"; +import { beforeAll, beforeEach } from "vitest"; + +/* + * The ECS part of the helpers, without any engine lib's typings: 3D specs (`test/3d/`) import it + * directly, since `helpers.ts` loads graphics-2d's, which type `ctx.graphics` for 2D. + */ + +/** The server ECS registry, booted by `useRegistry` before the first test of the file. */ +export let registry: Registry; + +/** Spawns an entity with `components`. */ +export const spawn = (...components: { name: string }[]) => { + const entity = registry.spawnEntity(); + for (const component of components) registry.addComponent(entity, component); + return entity; +}; + +/** Runs every system once, on `ctx`. */ +export const runOn = (ctx: Context) => registry.runSystems(ctx); + +/** Whether the entity still exists, by one of its components. */ +export const alive = ( + component: Parameters[0], + entity: { getId(): number }, +) => registry.getComponents(component).get(entity.getId()) !== undefined; + +/** + * Boots the server ECS (its wasm from `node_modules`) before the first test of the file, and + * clears its systems and entities before each test. Call it once, at the top of the file. + */ +export const useRegistry = () => { + beforeAll(async () => { + const ecs = new EcsLibrary(); + await ecs.__init({ + files: new Map([ + ["/libecs.wasm", "./node_modules/@nanoforge-dev/ecs/dist/server/libecs.wasm"], + ]), + } as unknown as InitContext); + registry = ecs.registry; + }); + + beforeEach(() => { + registry.clearSystems(); + registry.clearEntities(); + }); +}; diff --git a/test/helpers.ts b/test/helpers.ts index 9d141dc..8c7c616 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -1,10 +1,11 @@ -import type { Context, InitContext } from "@nanoforge-dev/common"; -import { EcsLibrary, type Registry } from "@nanoforge-dev/ecs/server"; +import type { Context } from "@nanoforge-dev/common"; import type { Layer, Shape } from "@nanoforge-dev/graphics-2d"; import type { DragState, InputEnum, MouseState } from "@nanoforge-dev/input"; import type { ControllerButton, StickPosition } from "@nanoforge-dev/input/controller"; import type { PacketDefinition } from "@nanoforge-dev/network"; -import { type Mock, afterEach, beforeAll, beforeEach, vi } from "vitest"; +import { type Mock, afterEach, beforeEach, vi } from "vitest"; + +import { registry, useRegistry } from "./ecs"; /* * What every spec file shares. At the top of a spec file, call `useEcs()`, and `stubDocument()` @@ -12,8 +13,7 @@ import { type Mock, afterEach, beforeAll, beforeEach, vi } from "vitest"; * (`registry.addSystem`), sets what the player does in `fake`, and runs frames (`run(frame(ms))`). */ -/** The server ECS registry, booted by `useEcs` before the first test of the file. */ -export let registry: Registry; +export { alive, registry, spawn } from "./ecs"; /** A Konva layer as the systems use it: see `fakeLayer`. */ export type FakeLayer = Layer & { at: { x: number; y: number; zoom: number }; shapes: Shape[] }; @@ -204,43 +204,17 @@ export const frame = (ms = 1000, without: string[] = []): Context => { return ctx as unknown as Context; }; -/** Spawns an entity with `components`. */ -export const spawn = (...components: { name: string }[]) => { - const entity = registry.spawnEntity(); - for (const component of components) registry.addComponent(entity, component); - return entity; -}; - /** Runs every system once, on `ctx` (a frame of 1 second by default). */ export const run = (ctx = frame()) => registry.runSystems(ctx); -/** Whether the entity still exists, by one of its components. */ -export const alive = ( - component: Parameters[0], - entity: { getId(): number }, -) => registry.getComponents(component).get(entity.getId()) !== undefined; - /** * Boots the server ECS (its wasm from `node_modules`) before the first test of the file, and * before each test clears its systems and entities and makes `fake` again. Call it once, at the * top of the file. */ export const useEcs = () => { - beforeAll(async () => { - const ecs = new EcsLibrary(); - await ecs.__init({ - files: new Map([ - ["/libecs.wasm", "./node_modules/@nanoforge-dev/ecs/dist/server/libecs.wasm"], - ]), - } as unknown as InitContext); - registry = ecs.registry; - }); - - beforeEach(() => { - registry.clearSystems(); - registry.clearEntities(); - Object.assign(fake, freshFakes()); - }); + useRegistry(); + beforeEach(() => Object.assign(fake, freshFakes())); }; /** A 2D context where everything does nothing and measures 0: Konva needs one. */ diff --git a/test/recipes.spec.ts b/test/recipes.spec.ts index 1825507..29a8ee6 100644 --- a/test/recipes.spec.ts +++ b/test/recipes.spec.ts @@ -1,6 +1,4 @@ -import type { Context } from "@nanoforge-dev/common"; import { Layer } from "@nanoforge-dev/graphics-2d"; -import { Mesh, PerspectiveCamera, Scene } from "@nanoforge-dev/graphics-3d/three"; import { InputEnum } from "@nanoforge-dev/input"; import { ControllerButton } from "@nanoforge-dev/input/controller"; import { MuteOnKey } from "@nanoforge/audio/components/mute-on-key"; @@ -14,9 +12,6 @@ import { Velocity2D } from "@nanoforge/basics-2d/components/velocity-2d"; import { FromModel } from "@nanoforge/basics-2d/models"; import { expireLifetimes } from "@nanoforge/basics-2d/systems/expire-lifetimes"; import { move2D } from "@nanoforge/basics-2d/systems/move-2d"; -import { Position3D } from "@nanoforge/basics-3d/components/position-3d"; -import { Velocity3D } from "@nanoforge/basics-3d/components/velocity-3d"; -import { move3D } from "@nanoforge/basics-3d/systems/move-3d"; import { DamageOnHit2D } from "@nanoforge/combat-2d/components/damage-on-hit-2d"; import { DestroyOnHit2D } from "@nanoforge/combat-2d/components/destroy-on-hit-2d"; import { FaceAim2D } from "@nanoforge/combat-2d/components/face-aim-2d"; @@ -60,11 +55,6 @@ import { faceTarget2D } from "@nanoforge/graphics-2d/systems/face-target-2d"; import { faceVelocity2D } from "@nanoforge/graphics-2d/systems/face-velocity-2d"; import { fadeOut2D } from "@nanoforge/graphics-2d/systems/fade-out-2d"; import { followCamera2D } from "@nanoforge/graphics-2d/systems/follow-camera-2d"; -import { Box3D } from "@nanoforge/graphics-3d/components/box-3d"; -import { Camera3D } from "@nanoforge/graphics-3d/components/camera-3d"; -import { Light3D } from "@nanoforge/graphics-3d/components/light-3d"; -import { Sphere3D } from "@nanoforge/graphics-3d/components/sphere-3d"; -import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; import { NetworkId } from "@nanoforge/network-2d/components/network-id"; import { Sync2DPacket, SyncRequestPacket } from "@nanoforge/network-2d/sync-packets"; import { syncFromServer2D } from "@nanoforge/network-2d/systems/sync-from-server-2d"; @@ -931,26 +921,3 @@ describe("recipes: multiplayer (movement only)", () => { expect(fake.network.sent).toContainEqual({ remove: 2 }); }); }); - -describe("recipes: 3D", () => { - it("a cube, a ball, a light and a camera: the cube rises, lit by the sun, seen from the camera", () => { - const graphics = { scene: new Scene(), camera: new PerspectiveCamera() }; - const ctx = { app: { delta: FRAME }, graphics } as unknown as Context; - spawn(new Box3D(1, 1, 1, "#44aa88"), new Position3D(-1, 0, 0), new Velocity3D(0, 0.5, 0)); - spawn(new Sphere3D(0.5, "#ff6b6b"), new Position3D(1, 0, 0)); - spawn(new Light3D("directional", "#ffffff", 3), new Position3D(3, 5, 4)); - spawn(new Camera3D(), new Position3D(0, 1, 6)); - add(move3D, draw3D); - - for (let i = 0; i < 60; i++) run(ctx); - - const [cube, ball, sun, camera] = graphics.scene.children; - expect(graphics.scene.children).toHaveLength(4); - expect(cube).toBeInstanceOf(Mesh); - expect(cube?.position.y).toBeCloseTo(0.5); - expect(ball?.position.x).toBe(1); - expect(sun?.position.toArray()).toEqual([3, 5, 4]); - expect(graphics.camera).toBe(camera); - expect(camera?.position.toArray()).toEqual([0, 1, 6]); - }); -}); diff --git a/tsconfig.3d.json b/tsconfig.3d.json new file mode 100644 index 0000000..f3c00ca --- /dev/null +++ b/tsconfig.3d.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + // The packages that use `@nanoforge-dev/graphics-3d`, which types `ctx.graphics` for 3D: they + // build apart from the 2D ones (tsconfig.json). A game loads graphics-2d or graphics-3d, never both. + "extends": "./tsconfig.json", + // With the packages they import, so an incremental build sees their changes. + "include": ["packages/graphics-3d/**/*.ts", "packages/basics-3d/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/tsconfig.json b/tsconfig.json index 94b406f..bf44bbb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -50,5 +50,7 @@ } }, "include": ["packages/**/*.ts"], - "exclude": ["node_modules", "dist"] + // Packages that use `@nanoforge-dev/graphics-3d` build in tsconfig.3d.json: it types `ctx.graphics` + // differently from graphics-2d, and one program can't load both. + "exclude": ["node_modules", "dist", "packages/graphics-3d"] } diff --git a/tsconfig.spec.3d.json b/tsconfig.spec.3d.json new file mode 100644 index 0000000..8a49df3 --- /dev/null +++ b/tsconfig.spec.3d.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "./tsconfig.3d.json", + "compilerOptions": { + "noEmit": true + }, + "include": ["test/3d/**/*.spec.ts", "packages/graphics-3d/**/*.ts", "packages/basics-3d/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/tsconfig.spec.json b/tsconfig.spec.json index 8270cab..5ac64fc 100644 --- a/tsconfig.spec.json +++ b/tsconfig.spec.json @@ -2,9 +2,8 @@ "$schema": "https://json.schemastore.org/tsconfig.json", "extends": "./tsconfig.json", "compilerOptions": { - "noEmit": true, - "skipLibCheck": true + "noEmit": true }, - "include": ["test/**/*.spec.ts"], - "exclude": ["node_modules"] + "include": ["test/**/*.spec.ts", "packages/**/*.ts"], + "exclude": ["node_modules", "test/3d", "packages/graphics-3d"] } diff --git a/vitest.config.ts b/vitest.config.ts index b87113b..9c1c216 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -25,10 +25,25 @@ export default defineConfig({ exclude: ["**/node_modules", "**/dist", ".idea", ".git", ".cache"], passWithNoTests: true, - typecheck: { - enabled: true, - tsconfig: "./tsconfig.spec.json", - }, + // Two programs, as in the build: graphics-2d and graphics-3d both type `ctx.graphics`. Vitest + // doesn't typecheck `.spec.ts` files: `pnpm run typecheck` does. + projects: [ + { + extends: true, + test: { + name: "2d", + include: ["test/**/*.spec.ts"], + exclude: ["test/3d/**"], + }, + }, + { + extends: true, + test: { + name: "3d", + include: ["test/3d/**/*.spec.ts"], + }, + }, + ], coverage: { enabled: true,