Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"@nanoforge-dev/utils-eslint-config": "catalog:lint",
"@nanoforge-dev/utils-prettier-config": "catalog:lint",
"@trivago/prettier-plugin-sort-imports": "catalog:lint",
"@types/three": "catalog:core",
"@vitest/coverage-v8": "catalog:test",
"eslint": "catalog:lint",
"husky": "catalog:ci",
Expand Down
2 changes: 2 additions & 0 deletions packages/graphics-3d/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ peer `three`, and registers `Graphics3DLibrary` in the client's `main.ts`.
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.
- `Model3D`: a `.glb`/`.gltf` model, loaded in the background. A missing or broken file logs an
error and shows a magenta box.
- `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.

Expand Down
25 changes: 25 additions & 0 deletions packages/graphics-3d/components/model-3d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import "@nanoforge-dev/graphics-3d/three";

/**
* Shows a 3D model from a `.glb` or `.gltf` file. Needs the `draw3D` system.
*
* @remarks
* The model loads in the background: the game starts at once and the model appears when it is
* ready. A missing or broken file logs an error and shows a magenta box instead. Move, turn and
* resize it with `Position3D`, `Rotation3D` and `Scale3D`.
*
* @example
* `new Model3D("/models/duck.glb")` with a `Position3D`, and a `Light3D` to see its colors.
*
* @component
* @side client
* @group Model color=#ff8a3d - The model file.
*/
export class Model3D {
name = "Model3D";

constructor(
/** The model file. @group Model @asset .glb .gltf */
public path = "",
) {}
}
23 changes: 23 additions & 0 deletions packages/graphics-3d/model-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { Context } from "@nanoforge-dev/common";
import { BoxGeometry, type Group, Mesh, MeshBasicMaterial } from "@nanoforge-dev/graphics-3d/three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";

import { disposeObject3D } from "./object-3d";

/**
* Loads the `.glb`/`.gltf` model at `path` into `group`, in the background: it never blocks and
* never throws. A missing or broken file logs an error and puts a magenta box in the group.
*
* @remarks
* Call it after the group is in the scene: a load that ends once the group has no parent (its
* component was removed) adds nothing and disposes what it loaded.
*/
export const loadModel3D = (group: Group, path: string, assets: Context["assets"]) =>
Promise.resolve()
.then(() => new GLTFLoader().loadAsync(assets.getAsset(path).path))
.then(({ scene }) => (group.parent ? group.add(scene) : disposeObject3D(scene)))
.catch((error: unknown) => {
console.error(`No 3D model at "${path}":`, error);
if (group.parent)
group.add(new Mesh(new BoxGeometry(), new MeshBasicMaterial({ color: "#ff00ff" })));
});
16 changes: 14 additions & 2 deletions packages/graphics-3d/nanoforge.manifest.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
{
"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"],
"description": "Show entities in 3D without Three.js: boxes, spheres and planes of a color, lights, a camera, glTF models, or any Three.js object, placed by the 3D transform.",
"keywords": [
"graphics",
"3d",
"three",
"box",
"sphere",
"plane",
"light",
"camera",
"model",
"gltf",
"draw"
],
"license": "MIT",
"suggestedPlugins": ["@nanoforge/ecs"],
"dependencies": { "@nanoforge/basics-3d": "^1.0.0" },
Expand Down
9 changes: 8 additions & 1 deletion packages/graphics-3d/object-3d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type Color,
DirectionalLight,
DoubleSide,
Group,
Light,
MathUtils,
Mesh,
Expand All @@ -20,6 +21,7 @@ import {
import type { Box3D } from "./components/box-3d";
import type { Camera3D } from "./components/camera-3d";
import type { Light3D } from "./components/light-3d";
import type { Model3D } from "./components/model-3d";
import type { Object3DComponent } from "./components/object-3d-component";
import type { Plane3D } from "./components/plane-3d";
import type { Sphere3D } from "./components/sphere-3d";
Expand All @@ -36,7 +38,8 @@ export type Params3D =
| ShapeParams
| Params<Light3D, "Light3D">
| Params<Camera3D, "Camera3D">
| Params<Object3DComponent, "Object3DComponent">;
| Params<Object3DComponent, "Object3DComponent">
| Params<Model3D, "Model3D">;

/** A point or a vector on three axes, like `Position3D`. */
export interface Xyz {
Expand Down Expand Up @@ -66,6 +69,10 @@ export const toObject3D = (params: Params3D, previous?: Object3D): Object3D => {
return cameraFor(params, previous);
case "Object3DComponent":
return params.object;
case "Model3D": // an empty group that draw3D fills; a new path gets a new group, so it reloads
return previous?.userData.path === params.path
? previous
: Object.assign(new Group(), { userData: { path: params.path } });
}
};

Expand Down
11 changes: 8 additions & 3 deletions packages/graphics-3d/systems/draw-3d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ 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 { Model3D } from "../components/model-3d";
import { Object3DComponent } from "../components/object-3d-component";
import { Plane3D } from "../components/plane-3d";
import { Sphere3D } from "../components/sphere-3d";
import { loadModel3D } from "../model-loader";
import { type Params3D, applyTransform3D, disposeObject3D, toObject3D } from "../object-3d";

/** What `draw3D` added to one app's scene. */
Expand All @@ -32,7 +34,7 @@ interface Shown {
const shownIn = new WeakMap<Scene, Shown>();

/** The components `draw3D` shows, by the key the ECS gives them in a zipper. */
const KINDS = { Box3D, Sphere3D, Plane3D, Light3D, Camera3D, Object3DComponent };
const KINDS = { Box3D, Sphere3D, Plane3D, Light3D, Camera3D, Object3DComponent, Model3D };

const defaultLight = () => {
const sun = new DirectionalLight(0xffffff, 2.5);
Expand All @@ -42,8 +44,8 @@ const defaultLight = () => {

/**
* 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.
* `Plane3D`, `Light3D`, `Camera3D`, `Object3DComponent` and `Model3D`, 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
Expand Down Expand Up @@ -85,6 +87,9 @@ export const draw3D = (registry: Registry, ctx: Context) => {
if (object !== previous) {
if (previous) disposeObject3D(previous);
scene.add(object);
// After `scene.add`: a load that ends once the group has no parent is dropped.
if (component.name === "Model3D")
void loadModel3D(object as Group, component.path, ctx.assets);
}
applyTransform3D(object, positions.get(row.id), rotations.get(row.id), scales.get(row.id));
objects.set(component, object);
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ catalogs:
'@nanoforge-dev/network': ^3.0.0
'@nanoforge-dev/scene': ^3.0.0
'@nanoforge-dev/sound': ^3.0.0
'@types/three': ^0.187.0
three: ^0.187.0
typescript: ^6.0.3
lint:
Expand Down
129 changes: 127 additions & 2 deletions test/3d/graphics-3d.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,37 @@ 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 { Model3D } from "@nanoforge/graphics-3d/components/model-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 { beforeEach, describe, expect, it, vi } from "vitest";

import { registry, runOn, spawn, useRegistry } from "../ecs";

/** `ctx.assets`: a blob URL per path, and no asset at a path starting with `/missing`. */
const assets = {
getAsset: (path: string) => {
if (path.startsWith("/missing")) throw new Error("not found");
return { path: `blob:${path}` };
},
};

const gltf = vi.hoisted(() => ({ loadAsync: vi.fn() }));
vi.mock("three/addons/loaders/GLTFLoader.js", () => ({
GLTFLoader: class {
loadAsync = gltf.loadAsync;
},
}));

useRegistry();

/** 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 };
return { graphics, ctx: { app: { delta: 16 }, graphics, assets } as unknown as Context };
};

/** What `draw3D` added for its components, without the default light. */
Expand Down Expand Up @@ -203,4 +219,113 @@ describe("graphics-3d", () => {
expect(same).toBe(box);
expect(((same as Mesh).geometry as BoxGeometry).parameters).toMatchObject({ width: 3 });
});

describe("Model3D", () => {
/** A loaded glTF scene: one mesh with a textured material, its disposes spied. */
const model = () => {
const geometry = new SphereGeometry();
const map = new Texture();
const material = new MeshStandardMaterial({ map });
const scene = new Group().add(new Mesh(geometry, material));
return { scene, spies: [geometry, material, map].map((it) => vi.spyOn(it, "dispose")) };
};
/** The groups draw3D made for Model3Ds (the default light is a group too). */
const models = (scene: Scene) => scene.children.filter((child) => "path" in child.userData);
/** Lets the pending loads end. */
const settle = () => new Promise((resolve) => setTimeout(resolve));

beforeEach(() => {
gltf.loadAsync.mockReset();
});

it("shows the model once loaded, placed by the transform, without blocking the frame", async () => {
const { graphics, ctx } = graphics3D();
const { scene: loaded } = model();
gltf.loadAsync.mockResolvedValue({ scene: loaded });
spawn(new Model3D("/models/duck.glb"), new Position3D(1, 2, 3));
registry.addSystem(draw3D);

runOn(ctx);
const [group] = models(graphics.scene);
expect(group?.children).toHaveLength(0);

await settle();
expect(gltf.loadAsync).toHaveBeenCalledWith("blob:/models/duck.glb");
expect(group?.children).toEqual([loaded]);
expect(group?.position).toMatchObject({ x: 1, y: 2, z: 3 });
});

it("logs the path and shows a placeholder box for a missing or broken file", async () => {
const { graphics, ctx } = graphics3D();
const error = vi.spyOn(console, "error").mockImplementation(() => {});
gltf.loadAsync.mockRejectedValue(new Error("bad glb"));
spawn(new Model3D("/missing.glb"));
spawn(new Model3D("/models/broken.glb"));
registry.addSystem(draw3D);

expect(() => runOn(ctx)).not.toThrow();
await settle();

const groups = models(graphics.scene);
expect(groups).toHaveLength(2);
for (const group of groups) expect(group.children[0]).toBeInstanceOf(Mesh);
for (const path of ["/missing.glb", "/models/broken.glb"])
expect(error).toHaveBeenCalledWith(expect.stringContaining(path), expect.anything());
error.mockRestore();
});

it("disposes the model's geometries, materials and textures when removed", async () => {
const { graphics, ctx } = graphics3D();
const { scene: loaded, spies } = model();
gltf.loadAsync.mockResolvedValue({ scene: loaded });
const entity = spawn(new Model3D("/models/duck.glb"));
registry.addSystem(draw3D);
runOn(ctx);
await settle();

registry.killEntity(entity);
runOn(ctx);

expect(models(graphics.scene)).toHaveLength(0);
for (const spy of spies) expect(spy).toHaveBeenCalled();
});

it("drops and disposes a load that ends after the component was removed", async () => {
const { ctx } = graphics3D();
const { scene: loaded, spies } = model();
let finish = (_: unknown) => {};
gltf.loadAsync.mockReturnValue(new Promise((resolve) => (finish = resolve)));
const entity = spawn(new Model3D("/models/duck.glb"));
registry.addSystem(draw3D);
runOn(ctx);
registry.killEntity(entity);
runOn(ctx);

finish({ scene: loaded });
await settle();

expect(loaded.parent).toBeNull();
for (const spy of spies) expect(spy).toHaveBeenCalled();
});

it("loads the new file when the path changes", async () => {
const { graphics, ctx } = graphics3D();
gltf.loadAsync.mockReturnValue(new Promise(() => {}));
const component = new Model3D("/models/duck.glb");
spawn(component);
registry.addSystem(draw3D);
runOn(ctx);
const [first] = models(graphics.scene);

runOn(ctx);
component.path = "/models/fox.glb";
runOn(ctx);
await settle();

expect(models(graphics.scene)).not.toContain(first);
expect(models(graphics.scene)).toHaveLength(1);
expect(gltf.loadAsync).toHaveBeenCalledTimes(2);
expect(gltf.loadAsync).toHaveBeenLastCalledWith("blob:/models/fox.glb");
});
});
});
Loading