diff --git a/.github/ISSUE_TEMPLATE/01-packages_bug_report.yml b/.github/ISSUE_TEMPLATE/01-packages_bug_report.yml index 7336f5b2..3b82901d 100644 --- a/.github/ISSUE_TEMPLATE/01-packages_bug_report.yml +++ b/.github/ISSUE_TEMPLATE/01-packages_bug_report.yml @@ -20,6 +20,7 @@ body: - editor - env - graphics-2d + - graphics-3d - input - music - network diff --git a/.github/ISSUE_TEMPLATE/03-feature_request.yml b/.github/ISSUE_TEMPLATE/03-feature_request.yml index b97897a0..5f5462be 100644 --- a/.github/ISSUE_TEMPLATE/03-feature_request.yml +++ b/.github/ISSUE_TEMPLATE/03-feature_request.yml @@ -18,6 +18,7 @@ body: - editor - env - graphics-2d + - graphics-3d - input - music - network diff --git a/.github/issue-labeler.yml b/.github/issue-labeler.yml index 9b6414e5..8ebde9b5 100644 --- a/.github/issue-labeler.yml +++ b/.github/issue-labeler.yml @@ -10,6 +10,10 @@ modules:graphics-2d: - "### Which (package|utils|package or utils) is this (bug report|feature request) for\\?\\n\\ngraphics-2d\\n" +modules:graphics-3d: + - "### Which (package|utils|package or utils) is this (bug + report|feature request) for\\?\\n\\ngraphics-3d\\n" + modules:input: - "### Which (package|utils|package or utils) is this (bug report|feature request) for\\?\\n\\ninput\\n" diff --git a/.github/labeler.yml b/.github/labeler.yml index f3320de3..db105ca6 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -24,6 +24,12 @@ modules:graphics-2d: - modules/graphics-2d/* - modules/graphics-2d/**/* +modules:graphics-3d: + - changed-files: + - any-glob-to-any-file: + - modules/graphics-3d/* + - modules/graphics-3d/**/* + modules:input: - changed-files: - any-glob-to-any-file: diff --git a/.github/labels.yml b/.github/labels.yml index 14d05454..5d80d01a 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -54,6 +54,10 @@ description: "Related to Graphics2D library" color: "1c3f78" +- name: "modules:graphics-3d" + description: "Related to Graphics3D library" + color: "1c3f78" + - name: "modules:input" description: "Related to Input library" color: "1c3f78" diff --git a/.github/workflows/alpha-release.yml b/.github/workflows/alpha-release.yml index 6b08137d..3abe0e82 100644 --- a/.github/workflows/alpha-release.yml +++ b/.github/workflows/alpha-release.yml @@ -15,6 +15,7 @@ on: - "@nanoforge-dev/editor-lib" - "@nanoforge-dev/env" - "@nanoforge-dev/graphics-2d" + - "@nanoforge-dev/graphics-3d" - "@nanoforge-dev/input" - "@nanoforge-dev/music" - "@nanoforge-dev/network" diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml index febd4578..e62023ac 100644 --- a/.github/workflows/pre-release.yml +++ b/.github/workflows/pre-release.yml @@ -34,7 +34,7 @@ jobs: - name: Create release PR uses: ./node_modules/@nanoforge-dev/actions/actions/create-packages-release-pr with: - packages: "@nanoforge-dev/asset,@nanoforge-dev/common,@nanoforge-dev/core,@nanoforge-dev/ecs,@nanoforge-dev/editor-lib,@nanoforge-dev/env,@nanoforge-dev/graphics-2d,@nanoforge-dev/input,@nanoforge-dev/music,@nanoforge-dev/network,@nanoforge-dev/scene,@nanoforge-dev/sound" + packages: "@nanoforge-dev/asset,@nanoforge-dev/common,@nanoforge-dev/core,@nanoforge-dev/ecs,@nanoforge-dev/editor-lib,@nanoforge-dev/env,@nanoforge-dev/graphics-2d,@nanoforge-dev/graphics-3d,@nanoforge-dev/input,@nanoforge-dev/music,@nanoforge-dev/network,@nanoforge-dev/scene,@nanoforge-dev/sound" version: ${{ inputs.version }} branch-format: "releases/nanoforge@{version}" commit-format: "chore: release @nanoforge-dev/engine@{version}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c754270b..9d1e733f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: - name: Release packages uses: ./node_modules/@nanoforge-dev/actions/actions/release-packages with: - packages: "@nanoforge-dev/asset,@nanoforge-dev/common,@nanoforge-dev/core,@nanoforge-dev/ecs,@nanoforge-dev/editor-lib,@nanoforge-dev/env,@nanoforge-dev/graphics-2d,@nanoforge-dev/input,@nanoforge-dev/music,@nanoforge-dev/network,@nanoforge-dev/scene,@nanoforge-dev/sound" + packages: "@nanoforge-dev/asset,@nanoforge-dev/common,@nanoforge-dev/core,@nanoforge-dev/ecs,@nanoforge-dev/editor-lib,@nanoforge-dev/env,@nanoforge-dev/graphics-2d,@nanoforge-dev/graphics-3d,@nanoforge-dev/input,@nanoforge-dev/music,@nanoforge-dev/network,@nanoforge-dev/scene,@nanoforge-dev/sound" tag-format: "{version}" latest: true env: diff --git a/docs/docs/getting-started/1-index.mdx b/docs/docs/getting-started/1-index.mdx index 14320133..3eac59cb 100644 --- a/docs/docs/getting-started/1-index.mdx +++ b/docs/docs/getting-started/1-index.mdx @@ -17,3 +17,4 @@ This documentation covers the engine, its packages, and the surrounding usage gu - [Registry](../registry) - [Network](../network) +- [Graphics 3D](../graphics-3d) diff --git a/docs/docs/graphics-3d/advanced.mdx b/docs/docs/graphics-3d/advanced.mdx new file mode 100644 index 00000000..688b519a --- /dev/null +++ b/docs/docs/graphics-3d/advanced.mdx @@ -0,0 +1,102 @@ +--- +title: "Graphics 3D: advanced" +icon: "wand-magic-sparkles" +description: "Full Three.js access, cameras, picking and editor events in @nanoforge-dev/graphics-3d" +--- + +# Graphics 3D: advanced + +The library adds no layer between you and Three.js. Everything below is plain Three.js on the objects of `Context.graphics`. + +## Importing Three.js + +| Import | Content | +| -------------------------------------- | ----------------------------------------------------------------- | +| `@nanoforge-dev/graphics-3d/three` | `three/webgpu`: the whole core, `WebGPURenderer`, node materials. | +| `@nanoforge-dev/graphics-3d/three/tsl` | `three/tsl`: the Three.js Shading Language. | +| `three/addons/...` | Add-ons (`GLTFLoader`, `OrbitControls`…), from `three` directly. | + +The subpaths only re-export `three`. `three` is a peer dependency that the app installs, so the library, the game and the add-ons resolve the same copy. Add-ons import `three`, which shares its core classes with `three/webgpu`. For add-on types, add `@types/three` at the same version. + +### Loading a model + +Load project files through `ctx.assets`. It returns the URL the game serves the file at. + +```ts +import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; + +const file = ctx.assets.getAsset("models/robot.glb"); +const gltf = await new GLTFLoader().loadAsync(file.path); +ctx.graphics.scene.add(gltf.scene); +``` + +Do not await asset loads in a library's `__init`: start them and add the objects when they arrive. + +### Node materials and TSL + +`WebGPURenderer` compiles node materials to WGSL (WebGPU) and GLSL (WebGL2) from one source. + +```ts +import { Mesh, MeshStandardNodeMaterial, SphereGeometry } from "@nanoforge-dev/graphics-3d/three"; +import { color, sin, time } from "@nanoforge-dev/graphics-3d/three/tsl"; + +const material = new MeshStandardNodeMaterial(); +material.colorNode = color("#ff6040").mul(sin(time).mul(0.5).add(0.5)); +ctx.graphics.scene.add(new Mesh(new SphereGeometry(), material)); +``` + +## Cameras + +Assign any camera to `graphics.camera`. The viewport is applied to it at once, and again on every change. For a `PerspectiveCamera`, the library sets `aspect`. For an `OrthographicCamera`, you choose `left`/`right`/`top`/`bottom` in design proportions. + +```ts +import { OrthographicCamera } from "@nanoforge-dev/graphics-3d/three"; + +graphics.camera = new OrthographicCamera(-16, 16, 9, -9, 0.1, 100); +``` + +After changing `fov`, `near` or `far`, call `camera.updateProjectionMatrix()`. + +## Picking + +`raycast` takes page coordinates, the ones pointer events give: + +```ts +canvas.addEventListener("pointerdown", (event) => { + const [hit] = ctx.graphics.raycast(event.clientX, event.clientY); + if (hit) console.log("clicked", hit.object.name, "at", hit.point); +}); +``` + +`worldToScreen` goes the other way, for example to place an HTML label over an object. + +## Render loop + +Never call `renderer.setAnimationLoop` or render from `requestAnimationFrame`. The engine renders once per tick, and the editor relies on this: pause freezes the image, and step draws exactly one frame. To draw something else than `scene` through `camera`, such as a post-processing pipeline, replace the library's render step. The library still calls it once per tick, and for editor screenshots: + +```ts +import { RenderPipeline } from "@nanoforge-dev/graphics-3d/three"; +import { pass, saturation } from "@nanoforge-dev/graphics-3d/three/tsl"; + +const { renderer, scene, camera } = ctx.graphics; +const postProcessing = new RenderPipeline(renderer); +const scenePass = pass(scene, camera); +postProcessing.outputNode = saturation(scenePass.getTextureNode(), 0.2); + +ctx.graphics.render = () => postProcessing.render(); +``` + +Assign `undefined` to go back to the default render. The custom render is reset when the game restarts. + +## Editor bridge + +When the editor starts the game, the library adds to the editor protocol: + +| Name | Direction | Payload | Purpose | +| ------------------ | --------------- | ---------------------- | -------------------------------------------------------------------------------------- | +| `graphicsCamera` | feature | `boolean` | Asked for in the editor's `welcome`. | +| `graphics-camera` | engine → editor | `{ view, projection }` | The active camera's matrices (16 numbers, column-major), on start and on every change. | +| `graphics-capture` | editor → engine | none | Renders a frame now, even while paused. | +| `graphics-capture` | engine → editor | PNG data URL | That frame. WebGL and WebGPU canvases are only readable right after a render. | + +The projection includes the viewport crop, so its normalized device coordinates span the canvas. The canvas is drawn `visibleWidth` × `visibleHeight` CSS px at (`contentLeft`, `contentTop`) of the container (see the `viewport` event). diff --git a/docs/docs/graphics-3d/editor-proposal.mdx b/docs/docs/graphics-3d/editor-proposal.mdx new file mode 100644 index 00000000..b780cdae --- /dev/null +++ b/docs/docs/graphics-3d/editor-proposal.mdx @@ -0,0 +1,97 @@ +--- +title: "Graphics 3D: editor proposal" +icon: "pen-ruler" +description: "Proposal for the editor's 3D Scene screen and plugin needs, for the editor's requirements session" +--- + +# Graphics 3D: editor proposal + +Input for the editor's requirements session on 3D (see `editor/CLAUDE.md`: a plugin starts with a requirements session and a spec in `docs/specs/.md`). Nothing here is built on the editor side yet. + +**Goal:** a beginner edits a 3D scene without code, in the same way the 2D Scene screen works today. + +## What the engine provides now + +`@nanoforge-dev/graphics-3d` ([docs](./index)) adds to the editor bridge: + +| Name | Kind | Payload | Use in the editor | +| ------------------ | ------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `graphicsCamera` | feature | `boolean` | Ask for it in `welcome` while a 3D tool over the running game is active, like `viewport` in `GameMoveOverlay`. | +| `graphics-camera` | event | `{ view, projection }` | Active camera matrices (column-major), sent once on start and then on every change. Together with `viewport` they map pointer ↔ world. | +| `graphics-capture` | command | none | Ask for a screenshot: the engine renders a frame, even while paused. | +| `graphics-capture` | event | PNG data URL | The frame. | + +The library also guarantees the following: + +- **Rendering:** it renders only from the engine tick, so pause freezes the image and step draws one frame. +- **Pop-out:** it creates its canvas in `container.ownerDocument`, so pop-out keeps working. A same-document iframe move was tested in the POC; a real `window.open` window was not. +- **Restarts:** `__init`/`__clear` survive repeated restarts, as tested with 10 cycles. Each clear disposes GPU objects, removes the canvas and deletes `window.__THREE__`. + +## Findings that change the brief + +- **Screenshot:** `plugins/viewport/src/game/screenshot.ts` draws every canvas with `drawImage` at an arbitrary time. A WebGL or WebGPU canvas may be blank then, which never happened with Konva. When the app has graphics-3d, use `graphics-capture` instead. +- **New feature flag:** `graphicsCamera` must be added to the editor's `mergeFeatures`, or it is silently dropped. +- **Telling 2D from 3D:** both libraries use the key `graphics`, so `hello.libraries` cannot tell them apart. The editor must look at the app's dependencies (`@nanoforge-dev/graphics-3d` vs `graphics-2d`). It could also look at the `graphics-camera` answer. +- **The viewport type is 2D:** `EngineViewport` (`packages/protocol`) maps game units to px in 2D. For 3D, it still gives the canvas rectangle, and `graphics-camera` gives the rest. +- **No hot reload today:** a source change while watching rebuilds the app, but nothing restarts the running game. Restart is the manual `runtime.restart`. Asset changes also trigger a rebuild, with no filter. "Hot reload" for 3D therefore means a rebuild plus a restart (manual, or automatic if the editor decides so). The engine side is ready for that. +- **Class names:** `build-scene.ts` matches shapes by class name only (`Rect`, `Circle`), and the bundler renames a component class whose name clashes with another bundled class (`Sphere` → `Sphere2`), which the ECS then fails to match. Three.js ships `Sphere`, `Plane`, `Box3`… That is why the 3D components are named with a `3D` suffix. +- **Vector preset:** `@preset vector` already supports `x`/`y`/`z` (slots `x, y, z, w`, minimum 2). A 3D position needs no new preset. + +## Components (not in the engine library) + +ECS components and systems for 3D are built in [components-systems](https://github.com/NanoForge-dev/components-systems), not in the library: + +- transform: `Position3D`, `Rotation3D` (degrees), `Scale3D`; +- shapes: `Box3D`, `Sphere3D`, `Plane3D`; +- `Model3D` (`@asset model .glb .gltf`), `Camera3D`, `Light3D`; +- the escape hatch `Object3DComponent`; +- a sync system; +- a pure function that maps component params to Three.js objects. + +The editor's Scene screen should import that same pure function, so the game and the Scene screen never drift. + +## Proposed editor work + +### 1. 3D Scene screen (`SCENE_EDITORS`) + +- **Building the scene:** build it from `main.ts` literals without running the game, as `build-scene.ts` does in 2D. Find the position by the `Position3D` component (numeric `x`/`y`/`z`), and turn component params into Three.js objects with the shared mapping function. +- **Rendering:** render with its own `WebGPURenderer`, its own scene and an editor `OrbitControls` camera that is not the game camera. +- **Picking and gizmos:** pick with `Raycaster`; move, rotate and scale with `TransformControls`. +- **Writing a gizmo edit, while stopped:** write `Position3D` / `Rotation3D` / `Scale3D` args to code with `ecs.apply({ kind: "setArgs", … })`, undoable, as `SceneView` does for `Position`. +- **Writing a gizmo edit, while playing:** apply it live with `live.setField` (`ecs-set-component`), then _Apply to code_. + +### 2. Move tool over the running game (`VIEWPORT_OVERLAYS`) + +While the tool is active, ask for `{ viewport: true, graphicsCamera: true }`. Then: + +1. Pointer → NDC on the canvas rectangle (`contentLeft`, `contentTop`, `visibleWidth`, `visibleHeight`). +2. Unproject with `inverse(projection)`, then `inverse(view)`, which gives a world ray. +3. Pick against the entities' bounds, or drag on a plane (the ground, or a plane facing the camera through the object). +4. Write with `live.setField`. + +### 3. Drag and drop + +- **Model file:** dropping a `.glb`/`.gltf` from the file manager onto the 3D Scene screen spawns an entity with `Position3D` at the drop point (a ray on the `y = 0` plane) and `Model3D("")`. +- **Component:** dropping a component from the catalog onto an object adds it to that entity. + +### 4. Inspector contributions + +| Extension point | Proposal | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | +| `ecs.paramPresets` | `euler`: slots `x, y, z`, all numbers in degrees, shown with a wrap at ±180 and a dial. Used by `Rotation3D`. | +| `ecs.paramPresets` | `vector` with a uniform-scale lock for `Scale3D` (like `size`'s ratio lock). | +| `ecs.fieldEditors` | `ref` editors for `@nanoforge-dev/graphics-3d/three#Color` and `#Vector3`, for user components that take Three.js objects as params. | +| `color` preset | Already fits the `color` string params of the shape components. | + +### 5. Toolbar + +- **Screenshot:** use `graphics-capture` for 3D apps. +- **Pop-out:** already works. +- **Zoom / pixel-perfect:** these are 2D-only. Hide them for 3D, or map zoom to camera zoom. + +## Questions for the session + +1. Should a source change restart the game automatically while playing, or stay manual? +2. Should the 3D Scene screen live in the ECS plugin (next to the 2D one) or in its own plugin? +3. Picking in the running game: are bounds-based picks on the editor side enough, or should we add a `graphics-pick` command answered by the engine (exact meshes)? +4. Should the editor camera be saved per project, and should there be a "view from game camera" toggle? diff --git a/docs/docs/graphics-3d/index.mdx b/docs/docs/graphics-3d/index.mdx new file mode 100644 index 00000000..2fc3a6da --- /dev/null +++ b/docs/docs/graphics-3d/index.mdx @@ -0,0 +1,129 @@ +--- +title: "Graphics 3D" +icon: "cube" +description: "Render a 3D scene with @nanoforge-dev/graphics-3d, built on Three.js" +--- + +# Graphics 3D + +`@nanoforge-dev/graphics-3d` renders a 3D scene in the game's container with [Three.js](https://threejs.org/). It was chosen in the [3D graphics library benchmark](../lib-graphic-3d). + +- **Client only.** `__init` throws on a server (no container). +- **One graphics library per app.** It uses the `graphics` key, like graphics-2d, so an app registers one or the other. +- **WebGPU first.** It uses WebGPU where the browser has it, and WebGL2 elsewhere. +- **Rendered by the engine.** One frame per tick, after the ECS systems. A paused game keeps its last image. + +## Your first 3D scene in 5 minutes + +The [`cube-3d` example](https://github.com/NanoForge-dev/Engine/tree/main/example/cube-3d) is this page as a complete app. + +### 1. Install + +```sh +pnpm add @nanoforge-dev/graphics-3d three +``` + +`three` is a peer dependency: the app installs it, so the game and Three.js add-ons share one copy. Also add `@types/three` (same version) if you import add-ons from `three/addons`. + +### 2. Register the library + +```ts +import { Graphics3DLibrary } from "@nanoforge-dev/graphics-3d"; + +const app = NanoforgeFactory.createClient({ + tickRate: 60, + viewport: { width: 1920, height: 1080, fit: "contain" }, +}); +const graphics = new Graphics3DLibrary(); +app.use(graphics); + +await app.init(options); +``` + +### 3. Add a light and an object + +Everything Three.js offers is imported from `@nanoforge-dev/graphics-3d/three`. Add objects to `graphics.scene` to show them. Without a light, `MeshStandardMaterial` objects are black. + +```ts +import { + BoxGeometry, + DirectionalLight, + HemisphereLight, + Mesh, + MeshStandardMaterial, +} from "@nanoforge-dev/graphics-3d/three"; + +const sun = new DirectionalLight("white", 3); +sun.position.set(3, 5, 4); +graphics.scene.add(new HemisphereLight("white", "#445566", 1), sun); + +const cube = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: "#44aa88" })); +graphics.scene.add(cube); +``` + +### 4. Place the camera + +The library starts with a perspective camera at `(0, 0, 5)`, looking at the origin. + +```ts +graphics.camera.position.set(0, 1.5, 4); +graphics.camera.lookAt(0, 0, 0); +``` + +### 5. Move things from a system + +The scene is drawn after the systems run, so a system changes objects and the next frame shows them. `ctx.app.delta` is in milliseconds. + +```ts +export function spin(registry: Registry, ctx: Context) { + registry.getZipper([Model]).forEach(({ Model }) => { + Model.object.rotation.y += ctx.app.delta / 1000; + }); +} +``` + +Systems reach the library through `ctx.graphics`. Do not keep the scene in a module-level variable. + +## Viewport + +The canvas follows `Context.viewport` like the 2D stage: + +- the camera's full frame is the design resolution (`width` × `height` in `createClient`); +- `contain` letterboxes it, `cover` crops it, `fill` stretches it; +- the canvas is resized on every window, fullscreen or pixel-ratio change. + +You never call `renderer.setSize`, and you never set a camera's `aspect` yourself. + +## `Context.graphics` + +| Member | What it is | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| `scene` | The Three.js `Scene` rendered every tick. | +| `camera` | The camera used for rendering. Assign another one to switch; the viewport is applied to it. | +| `renderer` | The `WebGPURenderer`. Never call `setAnimationLoop`: the engine drives rendering. | +| `render` | Draws one frame. Assign your own function for post-processing (see [Advanced](./advanced#render-loop)). | +| `backend` | `"webgpu"` or `"webgl"`. | +| `raycast(clientX, clientY, objects?)` | Objects under a page point (e.g. a `PointerEvent`), nearest first. | +| `worldToScreen(point)` | Where a world point is drawn in the page, in CSS px. | + +## Options + +```ts +new Graphics3DLibrary({ forceWebGL: true }); +``` + +| Option | Default | Effect | +| ------------ | ------- | ------------------------------------------------------ | +| `forceWebGL` | `false` | Use the WebGL2 backend even where WebGPU is available. | + +## Teardown + +When the game stops (or the editor restarts it), the library disposes everything in the scene: geometries, materials, their textures, and the scene's background and environment. It also disposes the renderer, removes the canvas and deletes `window.__THREE__`. + +Objects you removed from the scene yourself are not disposed by the library. Call their `dispose()` when you drop them. + +## Next + +- [Advanced](./advanced): Three.js add-ons, custom shaders, cameras, picking, editor events. +- [Performance](./performance): many objects, and `InstancedMesh`. +- [Editor proposal](./editor-proposal): what the editor needs for a 3D Scene screen. diff --git a/docs/docs/graphics-3d/performance.mdx b/docs/docs/graphics-3d/performance.mdx new file mode 100644 index 00000000..13cdbda2 --- /dev/null +++ b/docs/docs/graphics-3d/performance.mdx @@ -0,0 +1,56 @@ +--- +title: "Graphics 3D: performance" +icon: "gauge" +description: "Drawing many objects with @nanoforge-dev/graphics-3d" +--- + +# Graphics 3D: performance + +Each `Mesh` costs one draw call per frame. In the [benchmark POC](../lib-graphic-3d/poc), 2,000 meshes run at the display rate, while 20,000 run at about 12 FPS. + +When a frame has more than 2,000 draw calls, the library logs this warning once: + +``` +[graphics-3d] 2400 draw calls in one frame: the frame rate may drop. Draw many identical objects with one InstancedMesh (see the graphics-3d "Performance" docs page). +``` + +## Many identical objects: `InstancedMesh` + +An `InstancedMesh` draws many copies of one geometry and one material in a single draw call. Each copy has its own matrix (and optionally its own color). + +```ts +import { + BoxGeometry, + Color, + InstancedMesh, + MeshStandardMaterial, + Object3D, +} from "@nanoforge-dev/graphics-3d/three"; + +const count = 20_000; +const trees = new InstancedMesh(new BoxGeometry(0.2, 1, 0.2), new MeshStandardMaterial(), count); +const dummy = new Object3D(); + +for (let i = 0; i < count; i++) { + dummy.position.set((i % 200) - 100, 0.5, Math.floor(i / 200) - 50); + dummy.updateMatrix(); + trees.setMatrixAt(i, dummy.matrix); + trees.setColorAt(i, new Color().setHSL(0.3, 0.6, 0.3 + Math.random() * 0.2)); +} +ctx.graphics.scene.add(trees); +``` + +To move copies later, set their matrices again and flag the change: + +```ts +trees.setMatrixAt(index, dummy.matrix); +trees.instanceMatrix.needsUpdate = true; +``` + +With `raycast`, a hit on an instanced mesh carries `instanceId`, the index of the copy. + +## Other tips + +- Share geometries and materials between meshes instead of creating one per object. +- Merge static geometry that never moves (`mergeGeometries` from `three/addons/utils/BufferGeometryUtils.js`). +- Check `ctx.graphics.renderer.info.render.drawCalls` to see the cost of a frame. diff --git a/e2e/game/apps/server/.prettierignore b/e2e/game/apps/server/.prettierignore new file mode 100644 index 00000000..849ddff3 --- /dev/null +++ b/e2e/game/apps/server/.prettierignore @@ -0,0 +1 @@ +dist/ diff --git a/example/cube-3d/.gitignore b/example/cube-3d/.gitignore new file mode 100644 index 00000000..e69de29b diff --git a/example/cube-3d/.prettierignore b/example/cube-3d/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/example/cube-3d/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/example/cube-3d/apps/client/.prettierignore b/example/cube-3d/apps/client/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/example/cube-3d/apps/client/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/example/cube-3d/apps/client/assets/.gitkeep b/example/cube-3d/apps/client/assets/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/example/cube-3d/apps/client/eslint.config.js b/example/cube-3d/apps/client/eslint.config.js new file mode 100644 index 00000000..62ec06dc --- /dev/null +++ b/example/cube-3d/apps/client/eslint.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-eslint-config"; + +export default config; diff --git a/example/cube-3d/apps/client/nanoforge.config.ts b/example/cube-3d/apps/client/nanoforge.config.ts new file mode 100644 index 00000000..77607cbd --- /dev/null +++ b/example/cube-3d/apps/client/nanoforge.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "@nanoforge-dev/config"; + +export default defineConfig({ + type: "client", +}); diff --git a/example/cube-3d/apps/client/package.json b/example/cube-3d/apps/client/package.json new file mode 100644 index 00000000..86ccc4b6 --- /dev/null +++ b/example/cube-3d/apps/client/package.json @@ -0,0 +1,36 @@ +{ + "name": "cube-3d-client", + "version": "0.0.0", + "description": "", + "author": "", + "type": "module", + "scripts": { + "lint": "prettier --check . && eslint --format=pretty \"src/**/*.ts\"", + "format": "prettier --write . && eslint --fix --format=pretty \"src/**/*.ts\"" + }, + "devDependencies": { + "@nanoforge-dev/asset": "workspace:*", + "@nanoforge-dev/common": "workspace:*", + "@nanoforge-dev/core": "workspace:*", + "@nanoforge-dev/ecs": "workspace:*", + "@nanoforge-dev/graphics-3d": "workspace:*", + "@nanoforge-dev/utils-eslint-config": "workspace:*", + "@nanoforge-dev/utils-prettier-config": "workspace:*", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "@types/three": "catalog:graphics", + "eslint": "catalog:lint", + "lint-staged": "catalog:ci", + "prettier": "catalog:lint", + "three": "catalog:graphics", + "typescript": "catalog:core" + }, + "private": true, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ], + "src/**/*.ts": [ + "eslint --fix" + ] + } +} diff --git a/example/cube-3d/apps/client/prettier.config.js b/example/cube-3d/apps/client/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/example/cube-3d/apps/client/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/example/cube-3d/apps/client/src/components/components.ts b/example/cube-3d/apps/client/src/components/components.ts new file mode 100644 index 00000000..00c93430 --- /dev/null +++ b/example/cube-3d/apps/client/src/components/components.ts @@ -0,0 +1,19 @@ +import type { Object3D } from "@nanoforge-dev/graphics-3d/three"; + +/** The 3D object an entity shows. Add the object to `ctx.graphics.scene` to render it. */ +export class Model { + name = "Model"; + + constructor(public object: Object3D) {} +} + +/** Rotation speed around each axis, in degrees per second. */ +export class Spin { + name = "Spin"; + + constructor( + public x = 0, + public y = 0, + public z = 0, + ) {} +} diff --git a/example/cube-3d/apps/client/src/main.ts b/example/cube-3d/apps/client/src/main.ts new file mode 100644 index 00000000..c2e79f09 --- /dev/null +++ b/example/cube-3d/apps/client/src/main.ts @@ -0,0 +1,53 @@ +import type { ClientRunOptions } from "@nanoforge-dev/common"; +import { NanoforgeFactory } from "@nanoforge-dev/core"; +import { EcsLibrary } from "@nanoforge-dev/ecs/client"; +import { Graphics3DLibrary } from "@nanoforge-dev/graphics-3d"; +import { + BoxGeometry, + Color, + DirectionalLight, + HemisphereLight, + Mesh, + MeshStandardMaterial, +} from "@nanoforge-dev/graphics-3d/three"; + +import { Model, Spin } from "./components/components"; +import { spin } from "./systems/systems"; + +export const main = async (options: ClientRunOptions): Promise => { + // 1. Create the app and register the libraries it uses. + const app = NanoforgeFactory.createClient({ + tickRate: 60, + viewport: { width: 1920, height: 1080, fit: "contain" }, + }); + const graphics = new Graphics3DLibrary(); + const ecs = new EcsLibrary(); + app.use(graphics); + app.use(ecs); + + await app.init(options); + + // 2. Set up the scene: a background, a camera looking at the origin, and lights. + const { scene, camera } = graphics; + scene.background = new Color("#20232a"); + camera.position.set(0, 1.5, 4); + camera.lookAt(0, 0, 0); + + const sun = new DirectionalLight("white", 3); + sun.position.set(3, 5, 4); + scene.add(new HemisphereLight("white", "#445566", 1), sun); + + // 3. Add a cube to the scene, and an entity that spins it. + const mesh = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: "#44aa88" })); + scene.add(mesh); + + const registry = ecs.registry; + const cube = registry.spawnEntity(); + registry.addComponent(cube, new Model(mesh)); + registry.addComponent(cube, new Spin(20, 90, 0)); + + // 4. Run the systems every tick. graphics-3d renders the scene after them. + registry.addSystem(spin); + + await app.run(); +}; diff --git a/example/cube-3d/apps/client/src/systems/systems.ts b/example/cube-3d/apps/client/src/systems/systems.ts new file mode 100644 index 00000000..b359f32a --- /dev/null +++ b/example/cube-3d/apps/client/src/systems/systems.ts @@ -0,0 +1,16 @@ +import type { Context } from "@nanoforge-dev/common"; +import type { Registry } from "@nanoforge-dev/ecs/client"; +import { MathUtils } from "@nanoforge-dev/graphics-3d/three"; + +import { Model, Spin } from "../components/components"; + +/** Turns every model that has a `Spin`. */ +export function spin(registry: Registry, ctx: Context) { + const seconds = ctx.app.delta / 1000; + + registry.getZipper([Model, Spin]).forEach(({ Model, Spin }) => { + Model.object.rotation.x += MathUtils.degToRad(Spin.x) * seconds; + Model.object.rotation.y += MathUtils.degToRad(Spin.y) * seconds; + Model.object.rotation.z += MathUtils.degToRad(Spin.z) * seconds; + }); +} diff --git a/example/cube-3d/apps/client/tsconfig.json b/example/cube-3d/apps/client/tsconfig.json new file mode 100644 index 00000000..f90a806b --- /dev/null +++ b/example/cube-3d/apps/client/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", ".nanoforge"] +} diff --git a/example/cube-3d/nanoforge.config.ts b/example/cube-3d/nanoforge.config.ts new file mode 100644 index 00000000..99f24783 --- /dev/null +++ b/example/cube-3d/nanoforge.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "@nanoforge-dev/config"; + +export default defineConfig({ + type: "workspace", + packages: ["apps/*"], +}); diff --git a/example/cube-3d/package.json b/example/cube-3d/package.json new file mode 100644 index 00000000..31078482 --- /dev/null +++ b/example/cube-3d/package.json @@ -0,0 +1,26 @@ +{ + "name": "cube-3d", + "version": "0.0.0", + "description": "", + "author": "", + "type": "module", + "scripts": { + "start": "nf start", + "lint": "prettier --check .", + "format": "prettier --write ." + }, + "devDependencies": { + "@nanoforge-dev/cli": "^2.3.0", + "@nanoforge-dev/config": "catalog:config", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "lint-staged": "catalog:ci", + "prettier": "catalog:lint", + "typescript": "catalog:core" + }, + "private": true, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ] + } +} diff --git a/example/cube-3d/prettier.config.js b/example/cube-3d/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/example/cube-3d/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/example/cube-3d/tsconfig.json b/example/cube-3d/tsconfig.json new file mode 100644 index 00000000..b1528990 --- /dev/null +++ b/example/cube-3d/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["test/**/*.ts"], + "exclude": ["node_modules", "**/dist", "**/.nanoforge"] +} diff --git a/example/pong-3d/.gitignore b/example/pong-3d/.gitignore new file mode 100644 index 00000000..e69de29b diff --git a/example/pong-3d/.prettierignore b/example/pong-3d/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/example/pong-3d/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/example/pong-3d/apps/client/.prettierignore b/example/pong-3d/apps/client/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/example/pong-3d/apps/client/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/example/pong-3d/apps/client/assets/.gitkeep b/example/pong-3d/apps/client/assets/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/example/pong-3d/apps/client/eslint.config.js b/example/pong-3d/apps/client/eslint.config.js new file mode 100644 index 00000000..62ec06dc --- /dev/null +++ b/example/pong-3d/apps/client/eslint.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-eslint-config"; + +export default config; diff --git a/example/pong-3d/apps/client/nanoforge.config.ts b/example/pong-3d/apps/client/nanoforge.config.ts new file mode 100644 index 00000000..77607cbd --- /dev/null +++ b/example/pong-3d/apps/client/nanoforge.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "@nanoforge-dev/config"; + +export default defineConfig({ + type: "client", +}); diff --git a/example/pong-3d/apps/client/package.json b/example/pong-3d/apps/client/package.json new file mode 100644 index 00000000..86b61146 --- /dev/null +++ b/example/pong-3d/apps/client/package.json @@ -0,0 +1,38 @@ +{ + "name": "pong-3d-client", + "version": "0.0.0", + "description": "", + "author": "", + "type": "module", + "scripts": { + "lint": "prettier --check . && eslint --format=pretty \"src/**/*.ts\"", + "format": "prettier --write . && eslint --fix --format=pretty \"src/**/*.ts\"" + }, + "devDependencies": { + "@nanoforge-dev/asset": "workspace:*", + "@nanoforge-dev/common": "workspace:*", + "@nanoforge-dev/core": "workspace:*", + "@nanoforge-dev/ecs": "workspace:*", + "@nanoforge-dev/env": "workspace:*", + "@nanoforge-dev/graphics-3d": "workspace:*", + "@nanoforge-dev/input": "workspace:*", + "@nanoforge-dev/network": "workspace:*", + "@nanoforge-dev/utils-eslint-config": "workspace:*", + "@nanoforge-dev/utils-prettier-config": "workspace:*", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "eslint": "catalog:lint", + "lint-staged": "catalog:ci", + "prettier": "catalog:lint", + "three": "catalog:graphics", + "typescript": "catalog:core" + }, + "private": true, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ], + "src/**/*.ts": [ + "eslint --fix" + ] + } +} diff --git a/example/pong-3d/apps/client/prettier.config.js b/example/pong-3d/apps/client/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/example/pong-3d/apps/client/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/example/pong-3d/apps/client/src/arena.ts b/example/pong-3d/apps/client/src/arena.ts new file mode 100644 index 00000000..0ddb8ab5 --- /dev/null +++ b/example/pong-3d/apps/client/src/arena.ts @@ -0,0 +1,73 @@ +import { + BoxGeometry, + Color, + DirectionalLight, + HemisphereLight, + Mesh, + MeshStandardMaterial, + PlaneGeometry, + type Scene, + SphereGeometry, +} from "@nanoforge-dev/graphics-3d/three"; + +import { FIELD, PADDLE } from "../../../shared/protocol"; +import { SCALE } from "./field"; + +const WIDTH = FIELD.width * SCALE; +const DEPTH = FIELD.height * SCALE; + +/** Adds the table, its borders and the lights to the scene. */ +export const buildArena = (scene: Scene): void => { + scene.background = new Color("#10141c"); + + const table = new Mesh( + new PlaneGeometry(WIDTH, DEPTH), + new MeshStandardMaterial({ color: "#2f6b2a", roughness: 0.9 }), + ); + table.rotation.x = -Math.PI / 2; + table.receiveShadow = true; + + const centerLine = new Mesh( + new PlaneGeometry(0.1, DEPTH), + new MeshStandardMaterial({ color: "#94cc75" }), + ); + centerLine.rotation.x = -Math.PI / 2; + centerLine.position.y = 0.01; + + const borderMaterial = new MeshStandardMaterial({ color: "#c8d0dc" }); + const borderGeometry = new BoxGeometry(WIDTH + 0.4, 0.4, 0.2); + const top = new Mesh(borderGeometry, borderMaterial); + top.position.set(0, 0.2, -DEPTH / 2 - 0.1); + const bottom = new Mesh(borderGeometry, borderMaterial); + bottom.position.set(0, 0.2, DEPTH / 2 + 0.1); + for (const border of [top, bottom]) border.castShadow = border.receiveShadow = true; + + const sun = new DirectionalLight("white", 2.5); + sun.position.set(-4, 12, 6); + sun.castShadow = true; + sun.shadow.mapSize.set(2048, 2048); + Object.assign(sun.shadow.camera, { left: -12, right: 12, top: 8, bottom: -8 }); + + scene.add(table, centerLine, top, bottom, new HemisphereLight("#dfe8ff", "#20301c", 1.2), sun); +}; + +/** A paddle: a box as long as the 2D paddle is tall. */ +export const createPaddle = (color: string): Mesh => { + const paddle = new Mesh( + new BoxGeometry(PADDLE.width * SCALE, 0.4, PADDLE.height * SCALE), + new MeshStandardMaterial({ color, roughness: 0.4 }), + ); + paddle.castShadow = true; + return paddle; +}; + +export const BALL_RADIUS = 0.25; + +export const createBall = (): Mesh => { + const ball = new Mesh( + new SphereGeometry(BALL_RADIUS, 32, 16), + new MeshStandardMaterial({ color: "#ff4d3d", roughness: 0.3, emissive: "#401008" }), + ); + ball.castShadow = true; + return ball; +}; diff --git a/example/pong-3d/apps/client/src/components/components.ts b/example/pong-3d/apps/client/src/components/components.ts new file mode 100644 index 00000000..64c5bc80 --- /dev/null +++ b/example/pong-3d/apps/client/src/components/components.ts @@ -0,0 +1,59 @@ +import type { Object3D, Vector3 } from "@nanoforge-dev/graphics-3d/three"; +import type { InputEnum } from "@nanoforge-dev/input"; + +export class NetworkId { + constructor(public id: number) {} +} + +/** A paddle, tagged with the seat it belongs to. */ +export class Paddle { + constructor(public seat: 1 | 2) {} +} + +/** Position in server field units (1920 × 1080, y down). */ +export class Position { + constructor( + public x = 0, + public y = 0, + ) {} +} + +/** Speed in field units per millisecond. */ +export class Velocity { + constructor( + public x = 0, + public y = 0, + ) {} +} + +/** + * The 3D object drawn at the entity's `Position`. The offset goes from the + * position to the object's center, in field units (paddles are placed by + * their top-left corner). + */ +export class Model { + constructor( + public object: Object3D, + public offsetX = 0, + public offsetY = 0, + ) {} +} + +/** + * The local player: which paddle it controls (0 while spectating), and the + * keys that move it left and right on screen. + */ +export class Player { + seat: 0 | 1 | 2 = 0; + sent: "up" | "down" | "stop" = "stop"; + + constructor( + public left: InputEnum[], + public right: InputEnum[], + ) {} +} + +/** Where the camera looks, eased toward its goal every tick. */ +export class CameraRig { + look: Vector3 | undefined = undefined; +} diff --git a/example/pong-3d/apps/client/src/field.ts b/example/pong-3d/apps/client/src/field.ts new file mode 100644 index 00000000..e50e2a4b --- /dev/null +++ b/example/pong-3d/apps/client/src/field.ts @@ -0,0 +1,13 @@ +import { Vector3 } from "@nanoforge-dev/graphics-3d/three"; + +import { FIELD } from "../../../shared/protocol"; + +/** World units per field unit: the 1920 × 1080 field is 19.2 × 10.8 in 3D. */ +export const SCALE = 1 / 100; + +/** + * Field point → world point. The field lies on the ground (y = 0), centered + * on the origin: field x goes along world x, field y (down) along world z. + */ +export const fieldToWorld = (x: number, y: number, height = 0, target = new Vector3()): Vector3 => + target.set((x - FIELD.width / 2) * SCALE, height, (y - FIELD.height / 2) * SCALE); diff --git a/example/pong-3d/apps/client/src/main.ts b/example/pong-3d/apps/client/src/main.ts new file mode 100644 index 00000000..3d5e55b6 --- /dev/null +++ b/example/pong-3d/apps/client/src/main.ts @@ -0,0 +1,95 @@ +import type { ClientRunOptions } from "@nanoforge-dev/common"; +import { NanoforgeFactory } from "@nanoforge-dev/core"; +import { EcsLibrary } from "@nanoforge-dev/ecs/client"; +import { Graphics3DLibrary } from "@nanoforge-dev/graphics-3d"; +import { InputEnum, InputLibrary } from "@nanoforge-dev/input"; +import { ControllerLibrary } from "@nanoforge-dev/input/controller"; +import { NetworkClientLibrary } from "@nanoforge-dev/network/client"; + +import { AssignId, PADDLE, Play, Seat } from "../../../shared/protocol"; +import { BALL_RADIUS, buildArena, createBall, createPaddle } from "./arena"; +import { + CameraRig, + Model, + NetworkId, + Paddle, + Player, + Position, + Velocity, +} from "./components/components"; +import { applyMoves, controlPlayer, draw, followCamera, move } from "./systems/systems"; + +export const main = async (options: ClientRunOptions): Promise => { + const app = NanoforgeFactory.createClient({ + tickRate: 60, + viewport: { width: 1920, height: 1080, fit: "contain" }, + }); + const graphics = new Graphics3DLibrary(); + const ecs = new EcsLibrary(); + const network = new NetworkClientLibrary(); + const input = new InputLibrary(); + const controller = new ControllerLibrary(); + + app.use(graphics); + app.use(ecs); + app.use(network); + app.use(input); + app.use(controller); + + await app.init(options); + + graphics.renderer.shadowMap.enabled = true; + buildArena(graphics.scene); + + const registry = ecs.registry; + + const spawnModel = (model: Model) => { + const entity = registry.spawnEntity(); + registry.addComponent(entity, new Position()); + registry.addComponent(entity, new Velocity()); + registry.addComponent(entity, model); + graphics.scene.add(model.object); + return entity; + }; + + const ball = createBall(); + ball.position.y = BALL_RADIUS; + const paddle1 = createPaddle("#4d8dff"); + const paddle2 = createPaddle("#ff9f40"); + paddle1.position.y = paddle2.position.y = 0.2; + + // The server sends each entity's network id once we joined; game state follows in `Move` packets. + const entities = { + ball: spawnModel(new Model(ball)), + paddle1: spawnModel(new Model(paddle1, PADDLE.width / 2, PADDLE.height / 2)), + paddle2: spawnModel(new Model(paddle2, PADDLE.width / 2, PADDLE.height / 2)), + }; + registry.addComponent(entities.paddle1, new Paddle(1)); + registry.addComponent(entities.paddle2, new Paddle(2)); + + const me = registry.spawnEntity(); + registry.addComponent( + me, + new Player([InputEnum.ArrowLeft, InputEnum.KeyA], [InputEnum.ArrowRight, InputEnum.KeyD]), + ); + registry.addComponent(me, new CameraRig()); + + // Dispatched before the systems, so an entity gets its id before `applyMoves` reads its moves. + network.packets.on(AssignId, ({ assigned, id }) => { + registry.addComponent(entities[assigned], new NetworkId(id)); + }); + network.packets.on(Seat, ({ paddle }) => { + registry.getZipper([Player]).forEach(({ Player }) => (Player.seat = paddle)); + console.info(paddle === 0 ? "Spectating" : `Playing paddle ${paddle}`); + }); + + registry.addSystem(applyMoves); + registry.addSystem(move); + registry.addSystem(controlPlayer); + registry.addSystem(draw); + registry.addSystem(followCamera); + + network.packets.send(Play); + + await app.run(); +}; diff --git a/example/pong-3d/apps/client/src/scenes/.gitkeep b/example/pong-3d/apps/client/src/scenes/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/example/pong-3d/apps/client/src/systems/systems.ts b/example/pong-3d/apps/client/src/systems/systems.ts new file mode 100644 index 00000000..bc7f84b1 --- /dev/null +++ b/example/pong-3d/apps/client/src/systems/systems.ts @@ -0,0 +1,121 @@ +import { type Context } from "@nanoforge-dev/common"; +import { type Registry } from "@nanoforge-dev/ecs/client"; +import { Vector3 } from "@nanoforge-dev/graphics-3d/three"; +import type { InputEnum } from "@nanoforge-dev/input"; +import { ControllerAxis, ControllerButton } from "@nanoforge-dev/input/controller"; + +import { FIELD, Input, Move, PADDLE } from "../../../../shared/protocol"; +import { + CameraRig, + Model, + NetworkId, + Paddle, + Player, + Position, + Velocity, +} from "../components/components"; +import { fieldToWorld } from "../field"; + +/** Predicts movement between two server updates. */ +export function move(registry: Registry, ctx: Context) { + registry.getZipper([Position, Velocity]).forEach(({ Position, Velocity }) => { + Position.x += Velocity.x * ctx.app.delta; + Position.y += Velocity.y * ctx.app.delta; + }); +} + +/** Applies the server's positions and velocities. */ +export function applyMoves(registry: Registry, ctx: Context) { + const zipper = registry.getZipper([NetworkId, Position, Velocity]); + + for (const { data } of ctx.network.packets.read(Move)) { + const it = zipper.find((entity) => entity.NetworkId.id === data.id); + if (!it) continue; + it.Position.x = data.position.x; + it.Position.y = data.position.y; + it.Velocity.x = data.velocity.x; + it.Velocity.y = data.velocity.y; + } +} + +/** + * Sends the player's input. The camera looks down the table from behind the + * paddle, so "left" and "right" on screen are "up" and "down" on the field, + * swapped for the right paddle. + */ +export function controlPlayer(registry: Registry, ctx: Context) { + const input = ctx.input; + const pad = ctx.controller; + + registry.getZipper([Player]).forEach(({ Player }) => { + if (Player.seat === 0) return; + const stickX = pad.getAxis(ControllerAxis.LeftStickX); + const left = + Player.left.some((key: InputEnum) => input.isKeyPressed(key)) || + pad.isButtonPressed(ControllerButton.DPadLeft) || + stickX < -0.5; + const right = + Player.right.some((key: InputEnum) => input.isKeyPressed(key)) || + pad.isButtonPressed(ControllerButton.DPadRight) || + stickX > 0.5; + + let key: "up" | "down" | "stop" = "stop"; + if (left !== right) key = right === (Player.seat === 1) ? "down" : "up"; + if (key === Player.sent) return; + ctx.network.packets.send(Input, { key }); + Player.sent = key; + }); +} + +/** Places every model at its entity's position. */ +export function draw(registry: Registry) { + registry.getZipper([Model, Position]).forEach(({ Model, Position }) => { + const { object } = Model; + fieldToWorld( + Position.x + Model.offsetX, + Position.y + Model.offsetY, + object.position.y, + object.position, + ); + }); +} + +// Above and behind the right end of the table, framing both paddles. +const SPECTATOR_EYE = fieldToWorld(FIELD.width + 900, FIELD.height / 2, 12); +const SPECTATOR_LOOK = fieldToWorld(FIELD.width / 2 + 270, FIELD.height / 2); +const eye = new Vector3(); +const look = new Vector3(); + +/** + * Players see the table from just above and behind their own paddle, + * following it. Spectators see it from above its right end. + */ +export function followCamera(registry: Registry, ctx: Context) { + const players = registry.getZipper([Player, CameraRig]); + const paddles = registry.getZipper([Paddle, Position]); + + players.forEach(({ Player, CameraRig }) => { + const paddle = paddles.find((entity) => entity.Paddle.seat === Player.seat); + if (Player.seat !== 0 && paddle) { + const side = Player.seat === 1 ? 1 : -1; + const centerY = paddle.Position.y + PADDLE.height / 2; + // Behind and above the paddle, looking just short of the center line: the paddle stays in view. + fieldToWorld(paddle.Position.x + PADDLE.width / 2 - side * 400, centerY, 3, eye); + fieldToWorld(FIELD.width / 2 - side * 200, (centerY + FIELD.height / 2) / 2, 0, look); + } else { + eye.copy(SPECTATOR_EYE); + look.copy(SPECTATOR_LOOK); + } + + const camera = ctx.graphics.camera; + if (!CameraRig.look) { + CameraRig.look = look.clone(); + camera.position.copy(eye); + } + // Eases toward the goal in about a fifth of a second, whatever the frame rate. + const t = 1 - Math.exp(-ctx.app.delta / 120); + camera.position.lerp(eye, t); + CameraRig.look.lerp(look, t); + camera.lookAt(CameraRig.look); + }); +} diff --git a/example/pong-3d/apps/client/tsconfig.json b/example/pong-3d/apps/client/tsconfig.json new file mode 100644 index 00000000..f90a806b --- /dev/null +++ b/example/pong-3d/apps/client/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", ".nanoforge"] +} diff --git a/example/pong-3d/apps/server/.prettierignore b/example/pong-3d/apps/server/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/example/pong-3d/apps/server/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/example/pong-3d/apps/server/assets/.gitkeep b/example/pong-3d/apps/server/assets/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/example/pong-3d/apps/server/eslint.config.js b/example/pong-3d/apps/server/eslint.config.js new file mode 100644 index 00000000..62ec06dc --- /dev/null +++ b/example/pong-3d/apps/server/eslint.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-eslint-config"; + +export default config; diff --git a/example/pong-3d/apps/server/nanoforge.config.ts b/example/pong-3d/apps/server/nanoforge.config.ts new file mode 100644 index 00000000..43a3fef2 --- /dev/null +++ b/example/pong-3d/apps/server/nanoforge.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "@nanoforge-dev/config"; + +export default defineConfig({ + type: "server", +}); diff --git a/example/pong-3d/apps/server/package.json b/example/pong-3d/apps/server/package.json new file mode 100644 index 00000000..e7a86838 --- /dev/null +++ b/example/pong-3d/apps/server/package.json @@ -0,0 +1,35 @@ +{ + "name": "pong-3d-server", + "version": "0.0.0", + "description": "", + "author": "", + "type": "module", + "scripts": { + "lint": "prettier --check . && eslint --format=pretty \"src/**/*.ts\"", + "format": "prettier --write . && eslint --fix --format=pretty \"src/**/*.ts\"" + }, + "devDependencies": { + "@nanoforge-dev/asset": "workspace:*", + "@nanoforge-dev/common": "workspace:*", + "@nanoforge-dev/core": "workspace:*", + "@nanoforge-dev/env": "workspace:*", + "@nanoforge-dev/ecs": "workspace:*", + "@nanoforge-dev/network": "workspace:*", + "@nanoforge-dev/utils-eslint-config": "workspace:*", + "@nanoforge-dev/utils-prettier-config": "workspace:*", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "eslint": "catalog:lint", + "lint-staged": "catalog:ci", + "prettier": "catalog:lint", + "typescript": "catalog:core" + }, + "private": true, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ], + "src/**/*.ts": [ + "eslint --fix" + ] + } +} diff --git a/example/pong-3d/apps/server/prettier.config.js b/example/pong-3d/apps/server/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/example/pong-3d/apps/server/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/example/pong-3d/apps/server/src/components/components.ts b/example/pong-3d/apps/server/src/components/components.ts new file mode 100644 index 00000000..9bb8846e --- /dev/null +++ b/example/pong-3d/apps/server/src/components/components.ts @@ -0,0 +1,41 @@ +export class Velocity { + name = "Velocity"; + x: number; + y: number; + + constructor(x: number, y: number) { + this.x = x; + this.y = y; + } +} + +export class Position { + name = "Position"; + x: number; + y: number; + + constructor(x: number, y: number) { + this.x = x; + this.y = y; + } +} + +export class Circle { + name = "Circle"; + radius: number; + + constructor(radius: number) { + this.radius = radius; + } +} + +export class Rectangle { + name = "Rectangle"; + width: number; + height: number; + + constructor(width: number, height: number) { + this.width = width; + this.height = height; + } +} diff --git a/example/pong-3d/apps/server/src/main.ts b/example/pong-3d/apps/server/src/main.ts new file mode 100644 index 00000000..62ec77ea --- /dev/null +++ b/example/pong-3d/apps/server/src/main.ts @@ -0,0 +1,46 @@ +import type { RunOptions } from "@nanoforge-dev/common"; +import { NanoforgeFactory } from "@nanoforge-dev/core"; +import { EcsLibrary } from "@nanoforge-dev/ecs/server"; +import { NetworkServerLibrary } from "@nanoforge-dev/network/server"; + +import { Input, Play } from "../../../shared/protocol"; +import { Position, Velocity } from "./components/components"; +import { bounce, handleClientInput, handlePlay, move, onClientDisconnect } from "./systems/systems"; + +export const main = async (options: RunOptions): Promise => { + const app = NanoforgeFactory.createServer({ tickRate: 60 }); + const ecs = new EcsLibrary(); + const network = new NetworkServerLibrary(); + + app.use(ecs); + app.use(network); + + await app.init(options); + + network.clients.onDisconnect(onClientDisconnect); + + const registry = ecs.registry; + + const ball = registry.spawnEntity(); + registry.addComponent(ball, new Position(960, 540)); + registry.addComponent(ball, new Velocity(0, 0)); + + const paddle1 = registry.spawnEntity(); + registry.addComponent(paddle1, new Position(20, 390)); + registry.addComponent(paddle1, new Velocity(0, 0)); + + const paddle2 = registry.spawnEntity(); + registry.addComponent(paddle2, new Position(1850, 390)); + registry.addComponent(paddle2, new Velocity(0, 0)); + + const zip = () => registry.getZipper([Position, Velocity]); + network.packets.on(Play, (_, { clientId, ctx }) => handlePlay(clientId, ctx.network, zip())); + network.packets.on(Input, ({ key }, { clientId, ctx }) => + handleClientInput(clientId, key, ctx.network, zip()), + ); + + registry.addSystem(bounce); + registry.addSystem(move); + + await app.run(); +}; diff --git a/example/pong-3d/apps/server/src/scenes/.gitkeep b/example/pong-3d/apps/server/src/scenes/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/example/pong-3d/apps/server/src/systems/systems.ts b/example/pong-3d/apps/server/src/systems/systems.ts new file mode 100644 index 00000000..50de1c62 --- /dev/null +++ b/example/pong-3d/apps/server/src/systems/systems.ts @@ -0,0 +1,173 @@ +import { type Context } from "@nanoforge-dev/common"; +import { type Registry } from "@nanoforge-dev/ecs/server"; +import { + Channel, + type ClientId, + type ClientInfo, + type NetworkServerContextApi, +} from "@nanoforge-dev/network/server"; + +import { AssignId, Move, Seat } from "../../../../shared/protocol"; +import { Position, Velocity } from "../components/components"; + +let cli1: ClientId | null = null; +let cli2: ClientId | null = null; +const paddleSpeed = 1; + +let roundStart = 0; + +export function move(registry: Registry, ctx: Context) { + const entities = registry.getZipper([Position, Velocity]); + + entities.forEach(({ Position, Velocity }) => { + Position.x += Velocity.x * ctx.app.delta; + Position.y += Velocity.y * ctx.app.delta; + }); +} + +function sendMoveAll( + id: number, + vel: Velocity, + pos: Position, + network: NetworkServerContextApi, + channel: Channel, +) { + network.packets.sendToAll( + Move, + { id: id, position: { x: pos.x, y: pos.y }, velocity: { x: vel.x, y: vel.y } }, + { channel }, + ); +} + +/** Free the paddle of a player who left. */ +export function onClientDisconnect(info: ClientInfo) { + if (info.id === cli1) cli1 = null; + if (info.id === cli2) cli2 = null; +} + +function connectNewClient(newCli: ClientId, network: NetworkServerContextApi, zip: any) { + network.packets.sendToClient(newCli, AssignId, { assigned: "ball", id: 0 }); + network.packets.sendToClient(newCli, AssignId, { assigned: "paddle1", id: 1 }); + network.packets.sendToClient(newCli, AssignId, { assigned: "paddle2", id: 2 }); + sendMoveAll(0, zip[0].Velocity, zip[0].Position, network, Channel.ReliableOrdered); + sendMoveAll(1, zip[1].Velocity, zip[1].Position, network, Channel.ReliableOrdered); + sendMoveAll(2, zip[2].Velocity, zip[2].Position, network, Channel.ReliableOrdered); +} + +export function handleClientInput( + clientId: ClientId, + key: string, + network: NetworkServerContextApi, + zip: any, +) { + let id; + + if (clientId === cli1) { + id = 1; + } else if (clientId === cli2) { + id = 2; + } else { + return; + } + const paddle = zip[id]; + + if (key === "up") { + paddle.Velocity.y = -paddleSpeed; + if (paddle.Position.y < 0) { + paddle.Position.y = 0; + paddle.Velocity.y = 0; + } + } + if (key === "down") { + paddle.Velocity.y = paddleSpeed; + if (paddle.Position.y > 780) { + paddle.Position.y = 780; + paddle.Velocity.y = 0; + } + } + if (key === "stop") { + paddle.Velocity.y = 0; + } + sendMoveAll(id, paddle.Velocity, paddle.Position, network, Channel.UnreliableOrdered); +} + +/** Seats a new client on a free paddle, or as a spectator, and sends it the game state. */ +export function handlePlay(client: ClientId, network: NetworkServerContextApi, zip: any) { + if (client == cli1 || client == cli2) return; + let paddle: 0 | 1 | 2 = 0; + if (cli1 === null) { + cli1 = client; + paddle = 1; + } else if (cli2 === null) { + cli2 = client; + paddle = 2; + } + network.packets.sendToClient(client, Seat, { paddle }); + connectNewClient(client, network, zip); +} + +function checkOutOfTerrain(id: number, paddle: any, network: NetworkServerContextApi) { + if (paddle.Position.y < 0) { + paddle.Position.y = 0; + paddle.Velocity.y = 0; + sendMoveAll(id, paddle.Velocity, paddle.Position, network, Channel.UnreliableOrdered); + } + if (paddle.Position.y > 780) { + paddle.Position.y = 780; + paddle.Velocity.y = 0; + sendMoveAll(id, paddle.Velocity, paddle.Position, network, Channel.UnreliableOrdered); + } +} + +export const bounce = (registry: Registry, ctx: Context) => { + const network = ctx.network; + const zip = registry.getZipper([Position, Velocity]); + checkOutOfTerrain(1, zip[1], network); + checkOutOfTerrain(2, zip[2], network); + if (roundStart < 3000 && roundStart != -1) { + roundStart += ctx.app.delta; + return; + } + if (roundStart >= 3000) { + roundStart = -1; + zip[0].Velocity.x = 1; + sendMoveAll(0, zip[0].Velocity, zip[0].Position, network, Channel.UnreliableUnordered); + return; + } + let bounced = false; + if (zip[0].Position.y <= 0 || zip[0].Position.y >= 1080) { + zip[0].Velocity.y *= -1; + bounced = true; + } + if ( + (zip[0].Position.x <= 65 && + zip[1].Position.y - 15 <= zip[0].Position.y && + zip[0].Position.y - 15 <= zip[1].Position.y + 300) || + (zip[0].Position.x >= 1835 && + zip[2].Position.y - 15 <= zip[0].Position.y && + zip[0].Position.y - 15 <= zip[2].Position.y + 300) + ) { + let paddleTouched = 1; + if (zip[0].Position.x >= 1835) { + paddleTouched = 2; + } + const prevSpeed = Math.sqrt(zip[0].Velocity.x ** 2 + zip[0].Velocity.y ** 2); + const newSpeed = prevSpeed * 1.1; + const posOnPaddle = (zip[0].Position.y - zip[paddleTouched].Position.y + 15) / 330; + const baseAngle = posOnPaddle * ((6 * Math.PI) / 8) + Math.PI / 8 - Math.PI / 2; + const outAngle = zip[0].Position.x < 960 ? baseAngle : -baseAngle + Math.PI; + zip[0].Velocity.x = Math.cos(outAngle) * newSpeed; + zip[0].Velocity.y = Math.sin(outAngle) * newSpeed; + bounced = true; + } else if (zip[0].Position.x <= 15 || zip[0].Position.x >= 1905) { + zip[0].Position.x = 960; + zip[0].Position.y = 540; + zip[0].Velocity.x = 0; + zip[0].Velocity.y = 0; + roundStart = 0; + bounced = true; + } + if (bounced) { + sendMoveAll(0, zip[0].Velocity, zip[0].Position, network, Channel.UnreliableUnordered); + } +}; diff --git a/example/pong-3d/apps/server/tsconfig.json b/example/pong-3d/apps/server/tsconfig.json new file mode 100644 index 00000000..f90a806b --- /dev/null +++ b/example/pong-3d/apps/server/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", ".nanoforge"] +} diff --git a/example/pong-3d/nanoforge.config.ts b/example/pong-3d/nanoforge.config.ts new file mode 100644 index 00000000..af48def1 --- /dev/null +++ b/example/pong-3d/nanoforge.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "@nanoforge-dev/config"; + +export default defineConfig({ + type: "workspace", + packages: ["apps/*"], + network: "p2p", +}); diff --git a/example/pong-3d/package.json b/example/pong-3d/package.json new file mode 100644 index 00000000..174aeb9e --- /dev/null +++ b/example/pong-3d/package.json @@ -0,0 +1,31 @@ +{ + "name": "pong-3d", + "version": "0.0.0", + "description": "", + "author": "", + "type": "module", + "scripts": { + "start": "nf start", + "lint": "prettier --check .", + "format": "prettier --write ." + }, + "devDependencies": { + "@nanoforge-dev/asset": "workspace:*", + "@nanoforge-dev/cli": "^2.3.0", + "@nanoforge-dev/common": "workspace:*", + "@nanoforge-dev/config": "catalog:config", + "@nanoforge-dev/core": "workspace:*", + "@nanoforge-dev/env": "workspace:*", + "@nanoforge-dev/network": "workspace:*", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "lint-staged": "catalog:ci", + "prettier": "catalog:lint", + "typescript": "catalog:core" + }, + "private": true, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ] + } +} diff --git a/example/pong-3d/prettier.config.js b/example/pong-3d/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/example/pong-3d/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/example/pong-3d/shared/protocol.ts b/example/pong-3d/shared/protocol.ts new file mode 100644 index 00000000..8c81c411 --- /dev/null +++ b/example/pong-3d/shared/protocol.ts @@ -0,0 +1,23 @@ +import { Channel, definePacket } from "@nanoforge-dev/network"; + +type Vector = { x: number; y: number }; + +/** + * The game runs on the server in 2D field units: a 1920 × 1080 field, x to + * the right, y down. Clients draw it in 3D. + */ +export const FIELD = { width: 1920, height: 1080 } as const; +export const PADDLE = { width: 30, height: 300 } as const; + +export const Play = definePacket("play"); +export const Input = definePacket<{ key: "up" | "down" | "stop" }>("input"); + +/** Which paddle a client controls: 1 (left), 2 (right), or 0 when it spectates. */ +export const Seat = definePacket<{ paddle: 0 | 1 | 2 }>("seat"); + +export const AssignId = definePacket<{ assigned: "ball" | "paddle1" | "paddle2"; id: number }>( + "assignId", +); +export const Move = definePacket<{ id: number; position: Vector; velocity: Vector }>("move", { + channel: Channel.UnreliableOrdered, +}); diff --git a/example/pong-3d/tsconfig.json b/example/pong-3d/tsconfig.json new file mode 100644 index 00000000..b1528990 --- /dev/null +++ b/example/pong-3d/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["test/**/*.ts"], + "exclude": ["node_modules", "**/dist", "**/.nanoforge"] +} diff --git a/modules/graphics-3d/.cliff-jumperrc.json b/modules/graphics-3d/.cliff-jumperrc.json new file mode 100644 index 00000000..9333e427 --- /dev/null +++ b/modules/graphics-3d/.cliff-jumperrc.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/favware/cliff-jumper/main/assets/cliff-jumper.schema.json", + "name": "graphics-3d", + "org": "nanoforge-dev", + "packagePath": "modules/graphics-3d", + "tagTemplate": "{{new-version}}", + "identifierBase": false +} diff --git a/modules/graphics-3d/.gitignore b/modules/graphics-3d/.gitignore new file mode 100644 index 00000000..88ef62e8 --- /dev/null +++ b/modules/graphics-3d/.gitignore @@ -0,0 +1,234 @@ +### VisualStudioCode template +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Node template +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# Turbo +.turbo/ + +# Compiled files +src/**/*.js +src/**/*.d.ts + +# mint-tsdocs cache +docs/.tsdocs/ diff --git a/modules/graphics-3d/.prettierignore b/modules/graphics-3d/.prettierignore new file mode 100644 index 00000000..64b127c9 --- /dev/null +++ b/modules/graphics-3d/.prettierignore @@ -0,0 +1,11 @@ +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +bun.lock + +.turbo/ +node_modules/ +dist/ +coverage/ +CHANGELOG.md diff --git a/modules/graphics-3d/LICENSE b/modules/graphics-3d/LICENSE new file mode 100644 index 00000000..46724861 --- /dev/null +++ b/modules/graphics-3d/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2026 NanoForge + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/modules/graphics-3d/README.md b/modules/graphics-3d/README.md new file mode 100644 index 00000000..78805afb --- /dev/null +++ b/modules/graphics-3d/README.md @@ -0,0 +1,75 @@ +
+
+

+ NanoForge +

+
+

+ npm version + npm downloads + Tests status + Last commit + Contributors +

+
+ +## About + +`@nanoforge-dev/graphics-3d` is NanoForge's built-in 3D rendering library, powered by [Three.js][three]. It renders a `Scene` with a camera on a WebGPU canvas (WebGL2 fallback), once per engine tick, and exposes them on `Context.graphics`. Client-only. An app uses either graphics-2d or graphics-3d, not both. + +## Installation + +**Node.js 26 or newer is required.** `three` is a peer dependency: install it next to the library, so the game and Three.js add-ons share one copy. + +```sh +npm install @nanoforge-dev/graphics-3d three +yarn add @nanoforge-dev/graphics-3d three +pnpm add @nanoforge-dev/graphics-3d three +bun add @nanoforge-dev/graphics-3d three +``` + +## Example usage + +Register `Graphics3DLibrary` on your client app: + +```ts +import { Graphics3DLibrary } from "@nanoforge-dev/graphics-3d"; + +app.use(new Graphics3DLibrary()); +``` + +Add Three.js objects to `Context.graphics.scene`. Three.js is re-exported from `@nanoforge-dev/graphics-3d/three`: + +```ts +import { + BoxGeometry, + DirectionalLight, + Mesh, + MeshStandardMaterial, +} from "@nanoforge-dev/graphics-3d/three"; + +const cube = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: "#44aa88" })); +graphics.scene.add(cube, new DirectionalLight("white", 3)); +``` + +## Links + +- [GitHub][source] +- [npm][npm] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to ask questions in [discussions][discussions]. + +[documentation]: https://github.com/NanoForge-dev/Engine +[discussions]: https://github.com/NanoForge-dev/Engine/discussions +[source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/graphics-3d +[npm]: https://www.npmjs.com/package/@nanoforge-dev/graphics-3d +[contributing]: https://github.com/NanoForge-dev/Engine/blob/main/.github/CONTRIBUTING.md +[three]: https://threejs.org/ diff --git a/modules/graphics-3d/cliff.toml b/modules/graphics-3d/cliff.toml new file mode 100644 index 00000000..5163767e --- /dev/null +++ b/modules/graphics-3d/cliff.toml @@ -0,0 +1,79 @@ +[changelog] +header = """ +# Changelog + +All notable changes to this project will be documented in this file.\n +""" +body = """ +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +{% if version %}\ + # [{{ version | trim_start_matches(pat="v") }}]\ + {% if previous %}\ + {% if previous.version %}\ + ({{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }})\ + {% else %}\ + ({{ self::remote_url() }}/tree/{{ version }})\ + {% endif %}\ + {% endif %} \ + - ({{ timestamp | date(format="%Y-%m-%d") }}) +{% else %}\ + # [unreleased] +{% endif %}\ +{% for group, commits in commits | group_by(attribute="group") %} + ## {{ group | upper_first }} + {% for commit in commits %} + - {% if commit.scope %}\ + **{{commit.scope}}:** \ + {% endif %}\ + {{ commit.message | upper_first }} ([{{ commit.id | truncate(length=7, end="") }}]({{ self::remote_url() }}/commit/{{ commit.id }}))\ + {% if commit.github.username %} by @{{ commit.github.username }}{%- endif %}\ + {% if commit.breaking %}\ + {% for footer in commit.footers %}\ + {% if footer.breaking %}\ + \n{% raw %} {% endraw %}- **{{ footer.token }}{{ footer.separator }}** {{ footer.value }}\ + {% endif %}\ + {% endfor %}\ + {% endif %}\ + {% endfor %} +{% endfor %}\ +{% if github.contributors | filter(attribute="is_first_time", value=true) | length %}\ + \n### New Contributors\n + {% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}\ + - @{{ contributor.username }} made their first contribution in #{{ contributor.pr_number }} + {% endfor %}\ +{% endif %}\n +""" +trim = true +footer = "" + +[git] +conventional_commits = true +filter_unconventional = true +commit_parsers = [ + { message = "^feat", group = "Features"}, + { message = "^fix", group = "Bug Fixes"}, + { message = "^docs", group = "Documentation"}, + { message = "^perf", group = "Performance"}, + { message = "^refactor", group = "Refactor"}, + { message = "^types", group = "Typings"}, + { message = ".*deprecated", body = ".*deprecated", group = "Deprecation"}, + { message = "^revert", skip = true}, + { message = "^style", group = "Styling"}, + { message = "^test", group = "Testing"}, + { message = "^chore", skip = true}, + { message = "^ci", skip = true}, + { message = "^build", skip = true}, + { body = ".*security", group = "Security"}, +] +filter_commits = true +protect_breaking_commits = true +tag_pattern = "^[0-9]+" +ignore_tags = "" +topo_order = false +sort_commits = "newest" + +[remote.github] +owner = "NanoForge-dev" +repo = "Engine" diff --git a/modules/graphics-3d/eslint.config.js b/modules/graphics-3d/eslint.config.js new file mode 100644 index 00000000..62ec06dc --- /dev/null +++ b/modules/graphics-3d/eslint.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-eslint-config"; + +export default config; diff --git a/modules/graphics-3d/mint-tsdocs.config.json b/modules/graphics-3d/mint-tsdocs.config.json new file mode 100644 index 00000000..b85d3620 --- /dev/null +++ b/modules/graphics-3d/mint-tsdocs.config.json @@ -0,0 +1,13 @@ +{ + "$schema": "./node_modules/mint-tsdocs/lib/schemas/config.schema.json", + "entryPoint": "dist/index.d.ts", + "outputFolder": "../../docs/references/graphics-3d", + "lint": { + "eslint": { + "enabled": true + } + }, + "templates": { + "userTemplateDir": "../../docs/templates" + } +} diff --git a/modules/graphics-3d/package.json b/modules/graphics-3d/package.json new file mode 100644 index 00000000..29efe3e9 --- /dev/null +++ b/modules/graphics-3d/package.json @@ -0,0 +1,122 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "name": "@nanoforge-dev/graphics-3d", + "version": "0.0.0", + "description": "NanoForge Engine - Graphics 3D", + "keywords": [ + "nanoforge", + "game", + "engine" + ], + "homepage": "https://github.com/NanoForge-dev/Engine#readme", + "bugs": "https://github.com/NanoForge-dev/Engine/issues", + "license": "MIT", + "contributors": [ + "Exelo ", + "Fexkoser ", + "Harper ", + "Josephine ", + "Leo " + ], + "files": [ + "dist" + ], + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + }, + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./three": { + "require": { + "types": "./dist/three.d.cts", + "default": "./dist/three.cjs" + }, + "import": { + "types": "./dist/three.d.ts", + "default": "./dist/three.js" + } + }, + "./three/tsl": { + "require": { + "types": "./dist/three-tsl.d.cts", + "default": "./dist/three-tsl.cjs" + }, + "import": { + "types": "./dist/three-tsl.d.ts", + "default": "./dist/three-tsl.js" + } + }, + "./package.json": "./package.json" + }, + "type": "module", + "directories": { + "lib": "src" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/NanoForge-dev/Engine.git", + "directory": "modules/graphics-3d" + }, + "funding": "https://github.com/NanoForge-dev/Engine?sponsor", + "scripts": { + "build": "tsc --noEmit && tsdown --config-loader unrun", + "lint": "prettier --check . && eslint --format=pretty src", + "format": "prettier --write . && eslint --fix --format=pretty src", + "test:unit": "vitest run --config ../../vitest.config.ts", + "prepack": "pnpm run build && pnpm run lint", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'modules/graphics-3d/*'", + "release": "cliff-jumper", + "docs": "mint-tsdocs generate" + }, + "dependencies": { + "@nanoforge-dev/common": "workspace:*", + "@types/three": "catalog:graphics" + }, + "peerDependencies": { + "@nanoforge-dev/editor-lib": "workspace:*", + "three": "catalog:graphics" + }, + "peerDependenciesMeta": { + "@nanoforge-dev/editor-lib": { + "optional": true + } + }, + "devDependencies": { + "@favware/cliff-jumper": "catalog:ci", + "@nanoforge-dev/editor-lib": "workspace:*", + "@nanoforge-dev/utils-eslint-config": "workspace:*", + "@nanoforge-dev/utils-prettier-config": "workspace:*", + "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "eslint": "catalog:lint", + "prettier": "catalog:lint", + "three": "catalog:graphics", + "tsdown": "catalog:build", + "typescript": "catalog:core", + "unrun": "catalog:build", + "vitest": "catalog:test" + }, + "packageManager": "pnpm@12.0.0", + "engines": { + "node": "26" + }, + "publishConfig": { + "access": "public" + }, + "lint-staged": { + "**": [ + "prettier --ignore-unknown --write" + ], + "src/**/*.ts": [ + "eslint --fix" + ] + } +} diff --git a/modules/graphics-3d/prettier.config.js b/modules/graphics-3d/prettier.config.js new file mode 100644 index 00000000..27d0e269 --- /dev/null +++ b/modules/graphics-3d/prettier.config.js @@ -0,0 +1,3 @@ +import config from "@nanoforge-dev/utils-prettier-config"; + +export default config; diff --git a/modules/graphics-3d/src/context-augmentation.ts b/modules/graphics-3d/src/context-augmentation.ts new file mode 100644 index 00000000..48b4cbe3 --- /dev/null +++ b/modules/graphics-3d/src/context-augmentation.ts @@ -0,0 +1,7 @@ +import type { Graphics3DContextApi } from "./graphics-context.type"; + +declare module "@nanoforge-dev/common" { + interface Context { + graphics: Graphics3DContextApi; + } +} diff --git a/modules/graphics-3d/src/editor-augmentation.ts b/modules/graphics-3d/src/editor-augmentation.ts new file mode 100644 index 00000000..3682ac5a --- /dev/null +++ b/modules/graphics-3d/src/editor-augmentation.ts @@ -0,0 +1,28 @@ +/** Payload of the `graphics-camera` event: the matrices of the active camera, column-major. */ +export interface EditorGraphicsCamera { + /** World → camera matrix (inverse of the camera's world matrix). */ + view: number[]; + /** + * Camera → clip matrix. It includes the viewport's crop, so its normalized + * device coordinates span the canvas, which is drawn `visibleWidth` × + * `visibleHeight` CSS px at (`contentLeft`, `contentTop`) of the container + * (see the `viewport` event). + */ + projection: number[]; +} + +declare module "@nanoforge-dev/editor-lib" { + interface EditorFeatures { + /** Emit `graphics-camera` events: the active 3D camera now, then on every change. */ + graphicsCamera?: boolean; + } + interface EditorEventMap { + "graphics-camera": [EditorGraphicsCamera]; + /** Answer to `graphics-capture`: the frame as a PNG data URL, or empty when there is no renderer. */ + "graphics-capture": [string]; + } + interface EditorCommandMap { + /** Renders a frame now, even while paused, and answers with a `graphics-capture` event. */ + "graphics-capture": []; + } +} diff --git a/modules/graphics-3d/src/graphics-3d.library.ts b/modules/graphics-3d/src/graphics-3d.library.ts new file mode 100644 index 00000000..f7fd5d7c --- /dev/null +++ b/modules/graphics-3d/src/graphics-3d.library.ts @@ -0,0 +1,367 @@ +import { + type Context, + type InitContext, + Library, + type ViewportState, + defineLibraryKey, +} from "@nanoforge-dev/common"; +import type { + EditorAwareLibrary, + EditorContextApi, + EditorInitContext, +} from "@nanoforge-dev/editor-lib"; +import { + type Camera, + type Intersection, + Matrix4, + type Object3D, + OrthographicCamera, + PerspectiveCamera, + Raycaster, + Scene, + Texture, + Vector2, + type Vector3, + WebGPURenderer, +} from "three/webgpu"; + +import "./editor-augmentation"; +import type { Graphics3DBackend, Graphics3DContextApi, ScreenPoint } from "./graphics-context.type"; + +/** Options of {@link Graphics3DLibrary}. */ +export interface Graphics3DOptions { + /** + * Uses the WebGL2 backend even where WebGPU is available. + * + * @default false + */ + forceWebGL?: boolean; +} + +/** Draw calls in one frame above which a one-time performance warning is logged. */ +export const DRAW_CALL_WARNING = 2000; + +/** + * Built-in 3D graphics library powered by [Three.js](https://threejs.org/). + * + * @remarks + * Creates a `WebGPURenderer` (WebGL2 fallback) on a canvas added to the + * container, a `Scene` and a default `PerspectiveCamera`. It renders once per + * tick, after the ECS systems, and never on its own: a paused game keeps its + * last image. The canvas follows every viewport change like graphics-2d's + * stage: the design resolution is the camera's full frame, letterboxed or + * cropped according to the viewport's fit. Client-only — `__init` throws if + * `InitContext.container` is missing. + */ +export class Graphics3DLibrary extends Library implements EditorAwareLibrary { + readonly key = defineLibraryKey("graphics"); + + private _renderer?: WebGPURenderer; + private _scene?: Scene; + private _camera?: Camera; + private _viewport?: ViewportState; + private _unsubscribeViewport?: () => void; + private _warnedDrawCalls = false; + private _editor?: EditorContextApi; + private _hasSent = false; + private readonly _view = new Matrix4(); + private readonly _sentView = new Matrix4(); + private readonly _sentProjection = new Matrix4(); + private readonly _raycaster = new Raycaster(); + private readonly _ndc = new Vector2(); + private _observer?: ResizeObserver; + private _customRender?: () => void; + + constructor(private readonly _options: Graphics3DOptions = {}) { + super(); + } + + public override async __init(ctx: InitContext): Promise { + if (!ctx.container) { + throw new Error( + "Graphics3DLibrary must be registered on the client (InitContext must contain a container element).", + ); + } + // From the container's document, not the global one: the game may live in a pop-out window. + const canvas = ctx.container.ownerDocument.createElement("canvas"); + canvas.style.position = "relative"; + canvas.style.display = "block"; + ctx.container.appendChild(canvas); + + const renderer = new WebGPURenderer({ + canvas, + antialias: true, + forceWebGL: this._options.forceWebGL ?? false, + }); + try { + await renderer.init(); + } catch (error) { + // The app's init fails here, so `__clear` never runs: release what we created. + canvas.remove(); + await renderer.dispose(); + throw error; + } + this._renderer = renderer; + // Three resets `info` from its own animation loop, which is not our tick: we reset it per frame. + renderer.info.autoReset = false; + this._scene = new Scene(); + const camera = new PerspectiveCamera(50, 16 / 9, 0.1, 1000); + camera.position.set(0, 0, 5); + this._camera = camera; + this._warnedDrawCalls = false; + + if (ctx.viewport) { + this._applyViewport(ctx.viewport.state); + this._unsubscribeViewport = ctx.viewport.onChange((state) => this._applyViewport(state)); + } else { + this._followContainer(ctx.container); + } + } + + /** Listens to the editor's `graphics-capture` command and keeps the editor for `graphics-camera`. */ + public async __editorInit(ctx: EditorInitContext): Promise { + this._editor = ctx.editor; + ctx.editor.on("graphics-capture", () => { + // No renderer between a clear and an init: answer empty so the editor does not wait. + if (!this._renderer) return ctx.editor.emit("graphics-capture", ""); + // A WebGL/WebGPU canvas is only readable right after a render. + this._draw(); + ctx.editor.emit("graphics-capture", this._renderer.domElement.toDataURL("image/png")); + }); + } + + /** Emits `graphics-camera` while the editor asks for it, paused ticks included. */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public override async __events(_ctx: Context): Promise { + if (!this._editor?.welcome?.features.graphicsCamera) { + this._hasSent = false; + return; + } + const camera = this._camera; + if (!camera) return; + // Also refreshes the parents: a camera attached to a moving object follows it. + camera.updateWorldMatrix(true, false); + const view = this._view.copy(camera.matrixWorld).invert(); + const projection = camera.projectionMatrix; + if (this._hasSent && this._sentView.equals(view) && this._sentProjection.equals(projection)) + return; + this._hasSent = true; + this._sentView.copy(view); + this._sentProjection.copy(projection); + this._editor.emit("graphics-camera", { + view: view.toArray(), + projection: projection.toArray(), + }); + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public override async __run(_ctx: Context): Promise { + this.renderer.info.reset(); + this._draw(); + const drawCalls = this.renderer.info.render.drawCalls; + if (drawCalls > DRAW_CALL_WARNING && !this._warnedDrawCalls) { + this._warnedDrawCalls = true; + console.warn( + `[graphics-3d] ${drawCalls} draw calls in one frame: the frame rate may drop. Draw many identical objects with one InstancedMesh (see the graphics-3d "Performance" docs page).`, + ); + } + } + + public override async __clear(): Promise { + this._unsubscribeViewport?.(); + this._unsubscribeViewport = undefined; + if (this._scene) disposeScene(this._scene); + if (this._renderer) { + await this._renderer.dispose(); + this._renderer.domElement.remove(); + } + this._renderer = this._scene = this._camera = this._viewport = undefined; + // `__editorInit` runs once per app, so the editor is kept across restarts. + this._hasSent = false; + this._customRender = undefined; + this._observer?.disconnect(); + this._observer = undefined; + delete (globalThis as { __THREE__?: unknown }).__THREE__; + } + + public get renderer(): WebGPURenderer { + if (!this._renderer) this.throwNotInitializedError(); + return this._renderer; + } + + public get scene(): Scene { + if (!this._scene) this.throwNotInitializedError(); + return this._scene; + } + + public get camera(): Camera { + if (!this._camera) this.throwNotInitializedError(); + return this._camera; + } + + public set camera(camera: Camera) { + if (!this._renderer) this.throwNotInitializedError(); + this._camera = camera; + this._applyCamera(); + } + + /** The render step in use now, so a custom render can wrap it without calling itself. */ + public get render(): () => void { + return this._customRender ?? (() => this._drawDefault()); + } + + public set render(render: (() => void) | undefined) { + this._customRender = render; + } + + public get backend(): Graphics3DBackend { + return (this.renderer.backend as { isWebGPUBackend?: boolean }).isWebGPUBackend + ? "webgpu" + : "webgl"; + } + + public raycast( + clientX: number, + clientY: number, + objects: Object3D[] = this.scene.children, + ): Intersection[] { + const rect = this.renderer.domElement.getBoundingClientRect(); + this._ndc.set( + ((clientX - rect.left) / rect.width) * 2 - 1, + -((clientY - rect.top) / rect.height) * 2 + 1, + ); + this._raycaster.setFromCamera(this._ndc, this.camera); + return this._raycaster.intersectObjects(objects, true); + } + + public worldToScreen(point: Vector3): ScreenPoint { + const rect = this.renderer.domElement.getBoundingClientRect(); + const ndc = point.clone().project(this.camera); + return { + x: rect.left + ((ndc.x + 1) / 2) * rect.width, + y: rect.top + ((1 - ndc.y) / 2) * rect.height, + }; + } + + public override expose(): Graphics3DContextApi { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const library = this; + return { + get renderer() { + return library.renderer; + }, + get scene() { + return library.scene; + }, + get camera() { + return library.camera; + }, + set camera(camera) { + library.camera = camera; + }, + get backend() { + return library.backend; + }, + get render() { + return library.render; + }, + set render(render) { + library.render = render; + }, + raycast: (clientX, clientY, objects) => library.raycast(clientX, clientY, objects), + worldToScreen: (point) => library.worldToScreen(point), + }; + } + + /** Draws one frame with the custom render function, or the scene through the camera. */ + private _draw(): void { + if (this._customRender) this._customRender(); + else this._drawDefault(); + } + + private _drawDefault(): void { + this.renderer.render(this.scene, this.camera); + } + + /** Sizes the canvas to the visible game area and letterboxes it inside the container. */ + private _applyViewport(state: ViewportState): void { + const renderer = this._renderer; + if (!renderer) return; + this._viewport = state; + renderer.setPixelRatio(state.pixelRatio); + renderer.setSize(state.visibleWidth, state.visibleHeight, false); + const style = renderer.domElement.style; + style.width = `${state.visibleWidth}px`; + style.height = `${state.visibleHeight}px`; + style.left = `${state.contentLeft}px`; + style.top = `${state.contentTop}px`; + this._applyCamera(); + // Resizing clears the canvas; a paused game has no tick to redraw it. + this._draw(); + } + + /** + * Without a viewport, sizes the canvas to the container and follows its + * resizes, at the device pixel ratio of the container's window. + */ + private _followContainer(container: HTMLElement): void { + const renderer = this.renderer; + const resize = () => { + renderer.setPixelRatio(container.ownerDocument.defaultView?.devicePixelRatio ?? 1); + renderer.setSize(container.offsetWidth, container.offsetHeight); + this._applyCamera(); + }; + resize(); + // Resizing clears the canvas: redraw, since a paused game has no tick to do it. + this._observer = new ResizeObserver(() => { + resize(); + this._draw(); + }); + this._observer.observe(container); + } + + /** + * Makes the camera's full frame the design resolution and shows only its + * visible part, so `cover` crops and `fill` stretches as in 2D. + */ + private _applyCamera(): void { + const camera = this._camera; + if (!(camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera)) return; + const state = this._viewport; + if (state) { + camera.setViewOffset( + state.designWidth * state.scaleX, + state.designHeight * state.scaleY, + Math.abs(state.originX), + Math.abs(state.originY), + state.visibleWidth, + state.visibleHeight, + ); + // After setViewOffset, which sets the aspect to the full frame's: `fill` stretches the design frame. + if (camera instanceof PerspectiveCamera) + camera.aspect = state.designWidth / state.designHeight; + } else if (camera instanceof PerspectiveCamera) { + const canvas = this.renderer.domElement; + camera.aspect = canvas.width / canvas.height || 1; + } + camera.updateProjectionMatrix(); + } +} + +/** Frees the GPU resources of everything in the scene: geometries, materials and their textures. */ +const disposeScene = (scene: Scene): void => { + scene.traverse((object) => { + const { geometry, material } = object as Object3D & { + geometry?: { dispose(): void }; + material?: object | object[]; + }; + geometry?.dispose(); + for (const item of Array.isArray(material) ? material : material ? [material] : []) { + for (const value of Object.values(item)) if (value instanceof Texture) value.dispose(); + (item as { dispose?(): void }).dispose?.(); + } + (object as { dispose?(): void }).dispose?.(); + }); + for (const value of [scene.background, scene.environment]) + if (value instanceof Texture) value.dispose(); +}; diff --git a/modules/graphics-3d/src/graphics-context.type.ts b/modules/graphics-3d/src/graphics-context.type.ts new file mode 100644 index 00000000..2a600467 --- /dev/null +++ b/modules/graphics-3d/src/graphics-context.type.ts @@ -0,0 +1,43 @@ +import type { Camera, Intersection, Object3D, Scene, Vector3, WebGPURenderer } from "three/webgpu"; + +/** Backend the renderer runs on: WebGPU, or its WebGL2 fallback. */ +export type Graphics3DBackend = "webgpu" | "webgl"; + +/** A point in the page, in CSS px (same frame as `PointerEvent.clientX`/`clientY`). */ +export interface ScreenPoint { + x: number; + y: number; +} + +/** Public surface of `Graphics3DLibrary`, exposed on `Context.graphics`. */ +export interface Graphics3DContextApi { + /** The Three.js renderer. Rendered by the library every tick; never call `setAnimationLoop`. */ + readonly renderer: WebGPURenderer; + /** The scene rendered every tick — add objects here to show them. */ + readonly scene: Scene; + /** + * The camera the scene is rendered with. A default `PerspectiveCamera` at + * `(0, 0, 5)` looking at the origin; assign another camera to switch. + */ + camera: Camera; + /** + * Draws one frame. The library calls it once per tick, after the systems, + * and for editor screenshots. By default it renders `scene` through + * `camera`. Assign your own function to render a post-processing pipeline + * instead. Assign `undefined` to go back to the default. Reset on restart. + */ + get render(): () => void; + set render(render: (() => void) | undefined); + /** Which backend runs. */ + readonly backend: Graphics3DBackend; + /** + * Objects under a point of the page, nearest first. + * + * @param clientX - Page x, in CSS px (`PointerEvent.clientX`). + * @param clientY - Page y, in CSS px (`PointerEvent.clientY`). + * @param objects - Objects to test, with their children. Defaults to the whole scene. + */ + raycast(clientX: number, clientY: number, objects?: Object3D[]): Intersection[]; + /** Where a world point is drawn in the page, in CSS px. */ + worldToScreen(point: Vector3): ScreenPoint; +} diff --git a/modules/graphics-3d/src/index.ts b/modules/graphics-3d/src/index.ts new file mode 100644 index 00000000..837abaaf --- /dev/null +++ b/modules/graphics-3d/src/index.ts @@ -0,0 +1,9 @@ +import "./context-augmentation"; + +export type { EditorGraphicsCamera } from "./editor-augmentation"; +export { + DRAW_CALL_WARNING, + Graphics3DLibrary, + type Graphics3DOptions, +} from "./graphics-3d.library"; +export type { Graphics3DBackend, Graphics3DContextApi, ScreenPoint } from "./graphics-context.type"; diff --git a/modules/graphics-3d/src/three-tsl.ts b/modules/graphics-3d/src/three-tsl.ts new file mode 100644 index 00000000..9a04793d --- /dev/null +++ b/modules/graphics-3d/src/three-tsl.ts @@ -0,0 +1 @@ +export * from "three/tsl"; diff --git a/modules/graphics-3d/src/three.ts b/modules/graphics-3d/src/three.ts new file mode 100644 index 00000000..0c285a6f --- /dev/null +++ b/modules/graphics-3d/src/three.ts @@ -0,0 +1 @@ +export * from "three/webgpu"; diff --git a/modules/graphics-3d/test/graphics-3d.library.spec.ts b/modules/graphics-3d/test/graphics-3d.library.spec.ts new file mode 100644 index 00000000..b2be12a3 --- /dev/null +++ b/modules/graphics-3d/test/graphics-3d.library.spec.ts @@ -0,0 +1,497 @@ +import { type InitContext, type ViewportState, computeViewport } from "@nanoforge-dev/common"; +import type { EditorInitContext } from "@nanoforge-dev/editor-lib"; +import { + BoxGeometry, + Mesh, + MeshStandardMaterial, + Object3D, + PerspectiveCamera, + Texture, + Vector3, +} from "three/webgpu"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { DRAW_CALL_WARNING, Graphics3DLibrary } from "../src"; + +const fake = vi.hoisted(() => { + const renderers: any[] = []; + const WebGPURenderer = vi.fn(function (this: any, params: any) { + this.params = params; + this.domElement = params.canvas; + this.backend = params.forceWebGL ? { isWebGLBackend: true } : { isWebGPUBackend: true }; + this.info = { autoReset: true, render: { drawCalls: 1 }, reset: vi.fn() }; + this.init = vi.fn(async () => this); + this.render = vi.fn(); + this.setSize = vi.fn(); + this.setPixelRatio = vi.fn(); + this.setAnimationLoop = vi.fn(); + this.dispose = vi.fn(async () => {}); + renderers.push(this); + }); + return { renderers, WebGPURenderer }; +}); + +vi.mock("three/webgpu", async (importOriginal) => ({ + ...(await importOriginal()), + WebGPURenderer: fake.WebGPURenderer, +})); + +const lastRenderer = () => fake.renderers.at(-1); + +const makeCanvas = () => ({ + style: {} as Record, + width: 800, + height: 600, + remove: vi.fn(), + toDataURL: vi.fn(() => "data:image/png;base64,AAAA"), + getBoundingClientRect: () => ({ left: 100, top: 50, width: 800, height: 450 }), +}); + +const makeContainer = () => { + const canvases: ReturnType[] = []; + return { + offsetWidth: 800, + offsetHeight: 600, + canvases, + appendChild: vi.fn(), + ownerDocument: { + createElement: vi.fn(() => { + const canvas = makeCanvas(); + canvases.push(canvas); + return canvas; + }), + }, + }; +}; + +const makeViewport = (initial: ViewportState) => { + const listeners = new Set<(state: ViewportState) => void>(); + return { + state: initial, + onChange: (listener: (state: ViewportState) => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + emit(state: ViewportState) { + this.state = state; + for (const listener of listeners) listener(state); + }, + listenerCount: () => listeners.size, + }; +}; + +const makeInitContext = ( + container: unknown = makeContainer(), + viewport?: ReturnType, +): InitContext => + ({ + vars: { get: () => undefined, set: () => {} }, + env: {}, + files: new Map(), + container, + viewport, + }) as unknown as InitContext; + +const close = (expected: Record) => + Object.fromEntries( + Object.entries(expected).map(([key, value]) => [key, expect.closeTo(value, 6)]), + ); + +const run = (library: Graphics3DLibrary) => library.__run({} as never); +const events = (library: Graphics3DLibrary) => library.__events({} as never); + +const makeEditor = (features: Record) => { + const listeners = new Map void>(); + const editor = { + welcome: { protocolVersion: 1, features }, + emit: vi.fn(), + on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { + listeners.set(event, listener); + }), + off: vi.fn(), + }; + return { editor, send: (command: string) => listeners.get(command)?.() }; +}; + +describe("Graphics3DLibrary", () => { + beforeEach(() => { + fake.renderers.length = 0; + // Node has no ResizeObserver; the tests that need one stub their own. + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + }); + + it("uses the reserved 'graphics' key", () => { + expect(new Graphics3DLibrary().key).toBe("graphics"); + }); + + it("throws before __init and without a container", async () => { + const library = new Graphics3DLibrary(); + expect(() => library.scene).toThrow(); + expect(() => library.expose().renderer).toThrow(); + await expect(library.__init(makeInitContext(null))).rejects.toThrow(/client/); + }); + + it("does not throw when cleared before __init", async () => { + await expect(new Graphics3DLibrary().__clear()).resolves.toBeUndefined(); + }); + + it("creates the canvas in the container's own document", async () => { + const container = makeContainer(); + await new Graphics3DLibrary().__init(makeInitContext(container)); + expect(container.ownerDocument.createElement).toHaveBeenCalledWith("canvas"); + expect(container.appendChild).toHaveBeenCalledWith(container.canvases[0]); + expect(lastRenderer().params.canvas).toBe(container.canvases[0]); + expect(lastRenderer().init).toHaveBeenCalled(); + }); + + describe("backend", () => { + it("lets the renderer pick WebGPU by default", async () => { + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + expect(lastRenderer().params.forceWebGL).toBe(false); + expect(library.expose().backend).toBe("webgpu"); + }); + + it("forces the WebGL fallback with forceWebGL", async () => { + const library = new Graphics3DLibrary({ forceWebGL: true }); + await library.__init(makeInitContext()); + expect(lastRenderer().params.forceWebGL).toBe(true); + expect(library.expose().backend).toBe("webgl"); + }); + }); + + describe("tick", () => { + it("renders the scene with the active camera on every run, never with its own loop", async () => { + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + await run(library); + const camera = new PerspectiveCamera(); + library.expose().camera = camera; + await run(library); + expect(lastRenderer().render.mock.calls).toEqual([ + [library.scene, expect.any(PerspectiveCamera)], + [library.scene, camera], + ]); + expect(lastRenderer().setAnimationLoop).not.toHaveBeenCalled(); + }); + + it("calls a custom render function instead, until it is reset or the game restarts", async () => { + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + const render = vi.fn(); + library.expose().render = render; + await run(library); + expect(render).toHaveBeenCalledOnce(); + expect(lastRenderer().render).not.toHaveBeenCalled(); + + library.expose().render = undefined; + await run(library); + expect(lastRenderer().render).toHaveBeenCalledOnce(); + + library.expose().render = render; + await library.__clear(); + await library.__init(makeInitContext()); + await run(library); + expect(render).toHaveBeenCalledOnce(); + expect(lastRenderer().render).toHaveBeenCalledOnce(); + }); + + it("lets a custom render wrap the previous one without calling itself", async () => { + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + const overlay = vi.fn(); + const base = library.expose().render; + library.expose().render = () => { + base(); + overlay(); + }; + await run(library); + expect(overlay).toHaveBeenCalledOnce(); + expect(lastRenderer().render).toHaveBeenCalledOnce(); + }); + + it("warns once when a frame has too many draw calls", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + const renderer = lastRenderer(); + expect(renderer.info.autoReset).toBe(false); + let callsPerFrame = 10; + renderer.render.mockImplementation(() => (renderer.info.render.drawCalls += callsPerFrame)); + renderer.info.reset.mockImplementation(() => (renderer.info.render.drawCalls = 0)); + // Counts must not pile up across ticks: Three only resets them from its own loop. + for (let tick = 0; tick < 300; tick++) await run(library); + expect(warn).not.toHaveBeenCalled(); + + callsPerFrame = DRAW_CALL_WARNING + 1; + await run(library); + await run(library); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toMatch(/InstancedMesh/); + warn.mockRestore(); + }); + }); + + describe("viewport", () => { + const state = (fit: "contain" | "cover" | "fill", width: number, height: number) => + computeViewport(width, height, { width: 1920, height: 1080, fit }, 2); + + const setup = async (initial: ViewportState) => { + const viewport = makeViewport(initial); + const container = makeContainer(); + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext(container, viewport)); + return { library, viewport, canvas: container.canvases[0]!, renderer: lastRenderer() }; + }; + + it("letterboxes the canvas with contain and frames the whole design resolution", async () => { + const { library, renderer, canvas } = await setup(state("contain", 1000, 1000)); + expect(renderer.setPixelRatio).toHaveBeenLastCalledWith(2); + expect(renderer.setSize).toHaveBeenLastCalledWith(1000, 562.5, false); + expect(canvas.style).toMatchObject({ + width: "1000px", + height: "562.5px", + left: "0px", + top: "218.75px", + }); + const camera = library.camera as PerspectiveCamera; + expect(camera.aspect).toBeCloseTo(1920 / 1080); + expect(camera.view).toMatchObject( + close({ + fullWidth: 1000, + fullHeight: 562.5, + offsetX: 0, + offsetY: 0, + width: 1000, + height: 562.5, + }), + ); + }); + + it("crops the design frame with cover", async () => { + const { library, renderer } = await setup(state("cover", 1000, 1000)); + expect(renderer.setSize).toHaveBeenLastCalledWith(1000, 1000, false); + expect((library.camera as PerspectiveCamera).view).toMatchObject( + close({ + fullWidth: 1920 * (1000 / 1080), + fullHeight: 1000, + offsetX: (1920 * (1000 / 1080) - 1000) / 2, + offsetY: 0, + width: 1000, + height: 1000, + }), + ); + }); + + it("stretches the design frame with fill", async () => { + const { library, renderer } = await setup(state("fill", 1000, 1000)); + expect(renderer.setSize).toHaveBeenLastCalledWith(1000, 1000, false); + const camera = library.camera as PerspectiveCamera; + expect(camera.aspect).toBeCloseTo(1920 / 1080); + expect(camera.view).toMatchObject(close({ fullWidth: 1000, fullHeight: 1000, offsetX: 0 })); + }); + + it("redraws right after a resize, so a paused game does not show a blank canvas", async () => { + const { viewport, renderer } = await setup(state("contain", 1000, 1000)); + renderer.render.mockClear(); + viewport.emit(state("contain", 1920, 1080)); + expect(renderer.render).toHaveBeenCalledOnce(); + }); + + it("follows viewport changes and applies them to a camera assigned later", async () => { + const { library, viewport, renderer, canvas } = await setup(state("contain", 1000, 1000)); + viewport.emit(state("contain", 1920, 1080)); + expect(renderer.setSize).toHaveBeenLastCalledWith(1920, 1080, false); + expect(canvas.style.top).toBe("0px"); + const camera = new PerspectiveCamera(); + library.camera = camera; + expect(camera.aspect).toBeCloseTo(1920 / 1080); + expect(camera.view?.fullWidth).toBe(1920); + }); + }); + + describe("without a viewport", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("follows container resizes at the window's pixel ratio, until cleared", async () => { + let onResize: () => void = () => {}; + const disconnected = vi.fn(); + vi.stubGlobal( + "ResizeObserver", + class { + constructor(callback: () => void) { + onResize = callback; + } + observe() {} + disconnect() { + disconnected(); + } + }, + ); + const container = makeContainer(); + Object.assign(container.ownerDocument, { defaultView: { devicePixelRatio: 2 } }); + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext(container)); + const renderer = lastRenderer(); + expect(renderer.setPixelRatio).toHaveBeenLastCalledWith(2); + + Object.assign(container, { offsetWidth: 1024, offsetHeight: 768 }); + onResize(); + expect(renderer.setSize).toHaveBeenLastCalledWith(1024, 768); + + await library.__clear(); + expect(disconnected).toHaveBeenCalledOnce(); + }); + }); + + describe("teardown", () => { + it("removes the canvas and disposes the renderer when init fails", async () => { + const original = fake.WebGPURenderer.getMockImplementation() ?? (() => {}); + fake.WebGPURenderer.mockImplementationOnce(function (this: any, params: any) { + original.call(this, params); + this.init = vi.fn(async () => { + throw new Error("no GPU"); + }); + }); + const container = makeContainer(); + const library = new Graphics3DLibrary(); + await expect(library.__init(makeInitContext(container))).rejects.toThrow("no GPU"); + const [canvas] = container.canvases; + expect(canvas?.remove).toHaveBeenCalledOnce(); + expect(lastRenderer().dispose).toHaveBeenCalledOnce(); + }); + + afterEach(() => { + delete (globalThis as { __THREE__?: unknown }).__THREE__; + }); + + it("survives 10 init/clear cycles without leaking", async () => { + const viewport = makeViewport(computeViewport(800, 600)); + const library = new Graphics3DLibrary(); + for (let cycle = 0; cycle < 10; cycle++) { + (globalThis as { __THREE__?: unknown }).__THREE__ = "187"; + const container = makeContainer(); + await library.__init(makeInitContext(container, viewport)); + const geometry = new BoxGeometry(); + const texture = new Texture(); + const material = new MeshStandardMaterial({ map: texture }); + const disposed = [ + vi.spyOn(geometry, "dispose"), + vi.spyOn(material, "dispose"), + vi.spyOn(texture, "dispose"), + ]; + library.scene.add(new Mesh(geometry, material)); + await run(library); + await library.__clear(); + + for (const spy of disposed) expect(spy).toHaveBeenCalledOnce(); + expect(fake.renderers[cycle].dispose).toHaveBeenCalledOnce(); + expect(container.canvases[0]!.remove).toHaveBeenCalledOnce(); + expect(viewport.listenerCount()).toBe(0); + expect("__THREE__" in globalThis).toBe(false); + expect(() => library.scene).toThrow(); + } + expect(fake.renderers).toHaveLength(10); + }); + }); + + describe("screen helpers", () => { + it("projects a world point to the page and picks the object under it", async () => { + const library = new Graphics3DLibrary(); + await library.__init( + makeInitContext(makeContainer(), makeViewport(computeViewport(800, 450))), + ); + const box = new Mesh(new BoxGeometry(), new MeshStandardMaterial()); + library.scene.add(box); + box.updateMatrixWorld(); + library.camera.updateMatrixWorld(); + + const center = library.worldToScreen(new Vector3(0, 0, 0)); + expect(center.x).toBeCloseTo(500); + expect(center.y).toBeCloseTo(275); + expect(library.raycast(center.x, center.y)[0]?.object).toBe(box); + expect(library.raycast(101, 51)).toHaveLength(0); + }); + }); + + describe("editor", () => { + const setup = async (features: Record) => { + const library = new Graphics3DLibrary(); + await library.__init(makeInitContext()); + const { editor, send } = makeEditor(features); + await library.__editorInit({ editor } as unknown as EditorInitContext); + return { library, editor, send }; + }; + + it("emits nothing about the camera unless the editor asked for it", async () => { + const { library, editor } = await setup({}); + await events(library); + expect(editor.emit).not.toHaveBeenCalled(); + }); + + it("emits the camera matrices once, then only when they change", async () => { + const { library, editor } = await setup({ graphicsCamera: true }); + await events(library); + await events(library); + expect(editor.emit).toHaveBeenCalledTimes(1); + const [event, payload] = editor.emit.mock.calls[0]!; + expect(event).toBe("graphics-camera"); + expect(payload.view).toHaveLength(16); + expect(payload.view[14]).toBeCloseTo(-5); + expect(payload.projection).toEqual(library.camera.projectionMatrix.toArray()); + + library.camera.position.x = 2; + await events(library); + expect(editor.emit).toHaveBeenCalledTimes(2); + }); + + it("keeps emitting the camera after a restart (__editorInit runs once per app)", async () => { + const { library, editor } = await setup({ graphicsCamera: true }); + await library.__clear(); + await library.__init(makeInitContext()); + await events(library); + expect(editor.emit).toHaveBeenCalledWith("graphics-camera", expect.anything()); + }); + + it("captures through the custom render function", async () => { + const { library, editor, send } = await setup({}); + const render = vi.fn(); + library.render = render; + send("graphics-capture"); + expect(render).toHaveBeenCalledOnce(); + expect(editor.emit).toHaveBeenCalledWith("graphics-capture", expect.any(String)); + }); + + it("answers graphics-capture with an empty string between a clear and an init", async () => { + const { library, editor, send } = await setup({}); + await library.__clear(); + send("graphics-capture"); + expect(editor.emit).toHaveBeenCalledWith("graphics-capture", ""); + }); + + it("sends the camera's world position, parents included", async () => { + const { library, editor } = await setup({ graphicsCamera: true }); + const parent = new Object3D(); + const camera = new PerspectiveCamera(); + parent.add(camera); + parent.position.x = 3; + library.expose().camera = camera; + await events(library); + const view = (editor.emit.mock.calls.at(-1)?.[1] as { view: number[] }).view; + expect(view[12]).toBeCloseTo(-3); + }); + + it("renders a frame and returns it as a PNG on graphics-capture", async () => { + const { library, editor, send } = await setup({}); + send("graphics-capture"); + expect(lastRenderer().render).toHaveBeenCalledWith(library.scene, library.camera); + expect(editor.emit).toHaveBeenCalledWith("graphics-capture", "data:image/png;base64,AAAA"); + }); + }); +}); diff --git a/modules/graphics-3d/tsconfig.json b/modules/graphics-3d/tsconfig.json new file mode 100644 index 00000000..1ada333c --- /dev/null +++ b/modules/graphics-3d/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "../../tsconfig.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"], + "compilerOptions": { + "declaration": true, + "paths": { + "/snippets/*": ["./docs/snippets/*"] + } + }, + "mdx": { + "checkMdx": true + } +} diff --git a/modules/graphics-3d/tsconfig.spec.json b/modules/graphics-3d/tsconfig.spec.json new file mode 100644 index 00000000..8270caba --- /dev/null +++ b/modules/graphics-3d/tsconfig.spec.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "skipLibCheck": true + }, + "include": ["test/**/*.spec.ts"], + "exclude": ["node_modules"] +} diff --git a/modules/graphics-3d/tsdoc.json b/modules/graphics-3d/tsdoc.json new file mode 100644 index 00000000..ae9ae564 --- /dev/null +++ b/modules/graphics-3d/tsdoc.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], + "tagDefinitions": [ + { + "tagName": "@default", + "syntaxKind": "block", + "allowMultiple": false + } + ], + "supportForTags": { + "@default": true + } +} diff --git a/modules/graphics-3d/tsdown.config.ts b/modules/graphics-3d/tsdown.config.ts new file mode 100644 index 00000000..bd5f7421 --- /dev/null +++ b/modules/graphics-3d/tsdown.config.ts @@ -0,0 +1,5 @@ +import { createTsdownConfig } from "../../tsdown.config"; + +export default [ + createTsdownConfig({ entry: ["src/index.ts", "src/three.ts", "src/three-tsl.ts"] }), +]; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3304fd76..c9de8ad1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -164,9 +164,15 @@ catalogs: specifier: ^0.14.3 version: 0.14.4 graphics: + '@types/three': + specifier: ^0.187.0 + version: 0.187.0 konva: specifier: ^10.2.3 version: 10.3.2 + three: + specifier: ^0.187.0 + version: 0.187.0 lint: '@eslint/js': specifier: ^10.0.1 @@ -353,6 +359,201 @@ importers: specifier: catalog:core version: 6.0.3 + example/cube-3d: + devDependencies: + '@nanoforge-dev/cli': + specifier: ^2.3.0 + version: 2.3.0(@types/node@26.4.0)(synckit@0.11.13) + '@nanoforge-dev/config': + specifier: catalog:config + version: 2.3.0(synckit@0.11.13) + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + lint-staged: + specifier: catalog:ci + version: 17.4.1 + prettier: + specifier: catalog:lint + version: 3.9.6 + typescript: + specifier: catalog:core + version: 6.0.3 + + example/cube-3d/apps/client: + devDependencies: + '@nanoforge-dev/asset': + specifier: workspace:* + version: link:../../../../packages/asset + '@nanoforge-dev/common': + specifier: workspace:* + version: link:../../../../packages/common + '@nanoforge-dev/core': + specifier: workspace:* + version: link:../../../../packages/core + '@nanoforge-dev/ecs': + specifier: workspace:* + version: link:../../../../modules/ecs + '@nanoforge-dev/graphics-3d': + specifier: workspace:* + version: link:../../../../modules/graphics-3d + '@nanoforge-dev/utils-eslint-config': + specifier: workspace:* + version: link:../../../../utils/eslint-config + '@nanoforge-dev/utils-prettier-config': + specifier: workspace:* + version: link:../../../../utils/prettier-config + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + '@types/three': + specifier: catalog:graphics + version: 0.187.0 + eslint: + specifier: catalog:lint + version: 10.9.1(jiti@2.6.1)(supports-color@10.2.2) + lint-staged: + specifier: catalog:ci + version: 17.4.1 + prettier: + specifier: catalog:lint + version: 3.9.6 + three: + specifier: catalog:graphics + version: 0.187.0 + typescript: + specifier: catalog:core + version: 6.0.3 + + example/pong-3d: + devDependencies: + '@nanoforge-dev/asset': + specifier: workspace:* + version: link:../../packages/asset + '@nanoforge-dev/cli': + specifier: ^2.3.0 + version: 2.3.0(@types/node@26.4.0)(synckit@0.11.13) + '@nanoforge-dev/common': + specifier: workspace:* + version: link:../../packages/common + '@nanoforge-dev/config': + specifier: catalog:config + version: 2.3.0(synckit@0.11.13) + '@nanoforge-dev/core': + specifier: workspace:* + version: link:../../packages/core + '@nanoforge-dev/env': + specifier: workspace:* + version: link:../../packages/env + '@nanoforge-dev/network': + specifier: workspace:* + version: link:../../modules/network + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + lint-staged: + specifier: catalog:ci + version: 17.4.1 + prettier: + specifier: catalog:lint + version: 3.9.6 + typescript: + specifier: catalog:core + version: 6.0.3 + + example/pong-3d/apps/client: + devDependencies: + '@nanoforge-dev/asset': + specifier: workspace:* + version: link:../../../../packages/asset + '@nanoforge-dev/common': + specifier: workspace:* + version: link:../../../../packages/common + '@nanoforge-dev/core': + specifier: workspace:* + version: link:../../../../packages/core + '@nanoforge-dev/ecs': + specifier: workspace:* + version: link:../../../../modules/ecs + '@nanoforge-dev/env': + specifier: workspace:* + version: link:../../../../packages/env + '@nanoforge-dev/graphics-3d': + specifier: workspace:* + version: link:../../../../modules/graphics-3d + '@nanoforge-dev/input': + specifier: workspace:* + version: link:../../../../modules/input + '@nanoforge-dev/network': + specifier: workspace:* + version: link:../../../../modules/network + '@nanoforge-dev/utils-eslint-config': + specifier: workspace:* + version: link:../../../../utils/eslint-config + '@nanoforge-dev/utils-prettier-config': + specifier: workspace:* + version: link:../../../../utils/prettier-config + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + eslint: + specifier: catalog:lint + version: 10.9.1(jiti@2.6.1)(supports-color@10.2.2) + lint-staged: + specifier: catalog:ci + version: 17.4.1 + prettier: + specifier: catalog:lint + version: 3.9.6 + three: + specifier: catalog:graphics + version: 0.187.0 + typescript: + specifier: catalog:core + version: 6.0.3 + + example/pong-3d/apps/server: + devDependencies: + '@nanoforge-dev/asset': + specifier: workspace:* + version: link:../../../../packages/asset + '@nanoforge-dev/common': + specifier: workspace:* + version: link:../../../../packages/common + '@nanoforge-dev/core': + specifier: workspace:* + version: link:../../../../packages/core + '@nanoforge-dev/ecs': + specifier: workspace:* + version: link:../../../../modules/ecs + '@nanoforge-dev/env': + specifier: workspace:* + version: link:../../../../packages/env + '@nanoforge-dev/network': + specifier: workspace:* + version: link:../../../../modules/network + '@nanoforge-dev/utils-eslint-config': + specifier: workspace:* + version: link:../../../../utils/eslint-config + '@nanoforge-dev/utils-prettier-config': + specifier: workspace:* + version: link:../../../../utils/prettier-config + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + eslint: + specifier: catalog:lint + version: 10.9.1(jiti@2.6.1)(supports-color@10.2.2) + lint-staged: + specifier: catalog:ci + version: 17.4.1 + prettier: + specifier: catalog:lint + version: 3.9.6 + typescript: + specifier: catalog:core + version: 6.0.3 + example/pong-network: devDependencies: '@nanoforge-dev/asset': @@ -605,6 +806,52 @@ importers: specifier: catalog:test version: 4.1.11(@types/node@26.4.0)(@vitest/coverage-v8@4.1.11)(vite@8.2.2(@types/node@26.4.0)(jiti@2.6.1)(yaml@2.9.0)) + modules/graphics-3d: + dependencies: + '@nanoforge-dev/common': + specifier: workspace:* + version: link:../../packages/common + '@types/three': + specifier: catalog:graphics + version: 0.187.0 + devDependencies: + '@favware/cliff-jumper': + specifier: catalog:ci + version: 6.1.0 + '@nanoforge-dev/editor-lib': + specifier: workspace:* + version: link:../editor + '@nanoforge-dev/utils-eslint-config': + specifier: workspace:* + version: link:../../utils/eslint-config + '@nanoforge-dev/utils-prettier-config': + specifier: workspace:* + version: link:../../utils/prettier-config + '@trivago/prettier-plugin-sort-imports': + specifier: catalog:lint + version: 6.0.2(prettier@3.9.6)(supports-color@10.2.2) + eslint: + specifier: catalog:lint + version: 10.9.1(jiti@2.6.1)(supports-color@10.2.2) + prettier: + specifier: catalog:lint + version: 3.9.6 + three: + specifier: catalog:graphics + version: 0.187.0 + tsdown: + specifier: catalog:build + version: 0.22.14(typescript@6.0.3)(unrun@0.3.1(synckit@0.11.13)) + typescript: + specifier: catalog:core + version: 6.0.3 + unrun: + specifier: catalog:build + version: 0.3.1(synckit@0.11.13) + vitest: + specifier: catalog:test + version: 4.1.11(@types/node@26.4.0)(@vitest/coverage-v8@4.1.11)(vite@8.2.2(@types/node@26.4.0)(jiti@2.6.1)(yaml@2.9.0)) + modules/input: dependencies: '@nanoforge-dev/common': @@ -1205,6 +1452,9 @@ packages: resolution: {integrity: sha512-aalGyl7dbB5PArRebDIX43ZvBlXrYm9uWzGJ26t+4SzJVPsOuvfILGGbw5X4yX7i50YEmJ8zvbiWnqH/AAnZqg==} 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==} @@ -2055,6 +2305,9 @@ packages: cpu: [arm64] os: [win32] + '@tweenjs/tween.js@23.1.3': + resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==} + '@types/argparse@1.0.38': resolution: {integrity: sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==} @@ -2082,9 +2335,18 @@ packages: '@types/node@26.4.0': resolution: {integrity: sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==} + '@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.68.0': resolution: {integrity: sha512-WASHDpCm6qO5jj9g1a+8NiW5+GCkAyLReR56/4VruYmNgfUmqpxOfZ2Yfb8xGfJPWv5Qi6LSD8sXdces3vbp/Q==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2849,6 +3111,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'} @@ -3355,6 +3620,9 @@ packages: resolution: {integrity: sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==} engines: {node: '>=18'} + meshoptimizer@1.1.1: + resolution: {integrity: sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==} + micromatch@4.0.8: resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} engines: {node: '>=8.6'} @@ -3783,6 +4051,9 @@ packages: resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} engines: {node: '>=18'} + three@0.187.0: + resolution: {integrity: sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -4339,6 +4610,8 @@ snapshots: '@conventional-changelog/template@1.4.0': {} + '@dimforge/rapier3d-compat@0.12.0': {} + '@dprint/formatter@0.5.1': {} '@dprint/markdown@0.21.1': {} @@ -5059,6 +5332,8 @@ snapshots: '@turbo/windows-arm64@2.10.12': optional: true + '@tweenjs/tween.js@23.1.3': {} + '@types/argparse@1.0.38': {} '@types/bun@1.4.2': @@ -5087,8 +5362,21 @@ snapshots: dependencies: undici-types: 8.3.0 + '@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.68.0(@typescript-eslint/parser@8.68.0(eslint@10.9.1(jiti@2.6.1)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@10.9.1(jiti@2.6.1)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -5828,6 +6116,8 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fflate@0.8.3: {} + figures@6.1.0: dependencies: is-unicode-supported: 2.1.0 @@ -6243,6 +6533,8 @@ snapshots: meow@13.2.0: {} + meshoptimizer@1.1.1: {} + micromatch@4.0.8: dependencies: braces: 3.0.3 @@ -6690,6 +6982,8 @@ snapshots: minizlib: 3.1.0 yallist: 5.0.0 + three@0.187.0: {} + tinybench@2.9.0: {} tinyexec@1.3.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a3c07ebf..56f30e61 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -38,7 +38,9 @@ catalogs: class-transformer: ^0.5.1 class-validator: ^0.14.3 graphics: + '@types/three': ^0.187.0 konva: ^10.2.3 + three: ^0.187.0 lint: '@eslint/js': ^10.0.1 '@trivago/prettier-plugin-sort-imports': ^6.0.2