A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Factory yard prototype, moved out of the game's scratch worktree
SandroMaglione85b41d3f18cd
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..f06235c--- /dev/null+++ b/.gitignore@@ -0,0 +1,2 @@+node_modules+distdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..4383b53--- /dev/null+++ b/README.md@@ -0,0 +1,20 @@+# Factory yard++A prototype: place line-drawn isometric factories on a grid, connect them+with conveyor belts, and watch crates flow. Game logic runs on the+[bevy-ts](../../bevy-ts) ECS; Pixi draws it.++```sh+pnpm install+pnpm dev --host --port 5232+pnpm typecheck+```++The bevy-ts packages are linked from `../../bevy-ts` and consumed as source.++- `src/iso.ts`: the grid and the unit everything is measured in (1/16 cell = 2×1 px).+- `src/kinds.ts`: the factory kinds and their sizes.+- `src/route.ts`: belt pathfinding.+- `src/schema.ts`, `src/systems.ts`: the ECS world and its systems.+- `src/art.ts`: all drawing.+- `src/host.ts`, `src/main.ts`: the page, camera, input, panel, and start-up.diff --git a/index.html b/index.htmlnew file mode 100644index 0000000..4989291--- /dev/null+++ b/index.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />+ <title>Factory · isometric belts</title>+ <link rel="stylesheet" href="/src/factory.css" />+ </head>+ <body>+ <div id="app"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..6a793be--- /dev/null+++ b/package.json@@ -0,0 +1,22 @@+{+ "name": "factory-yard",+ "private": true,+ "type": "module",+ "packageManager": "[email protected]",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "typecheck": "tsc -p tsconfig.json --pretty false"+ },+ "dependencies": {+ "@typeonce/bevy-ts": "link:../../bevy-ts/packages/core",+ "@typeonce/bevy-ts-pixi": "link:../../bevy-ts/packages/pixi",+ "@typeonce/bevy-ts-render": "link:../../bevy-ts/packages/render",+ "pixi.js": "^8.22.0"+ },+ "devDependencies": {+ "@types/node": "25.5.0",+ "typescript": "7.0.2",+ "vite": "8.3.1"+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlnew file mode 100644index 0000000..e73c9ae--- /dev/null+++ b/pnpm-lock.yaml@@ -0,0 +1,745 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@typeonce/bevy-ts':+ specifier: link:../../bevy-ts/packages/core+ version: link:../../bevy-ts/packages/core+ '@typeonce/bevy-ts-pixi':+ specifier: link:../../bevy-ts/packages/pixi+ version: link:../../bevy-ts/packages/pixi+ '@typeonce/bevy-ts-render':+ specifier: link:../../bevy-ts/packages/render+ version: link:../../bevy-ts/packages/render+ pixi.js:+ specifier: ^8.22.0+ version: 8.22.0+ devDependencies:+ '@types/node':+ specifier: 25.5.0+ version: 25.5.0+ typescript:+ specifier: 7.0.2+ version: 7.0.2+ vite:+ specifier: 8.3.1+ version: 8.3.1(@types/[email protected])++packages:++ '@oxc-project/[email protected]':+ resolution: {integrity: sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==}++ '@pixi/[email protected]':+ resolution: {integrity: sha512-nezytU2pw587fQstUu1AsJZDVEynjskwOL+kibwcdxsMBFqPsFFNA7xl0ii/gXuDi6M0xj3mfRJj8pBSc2jCfA==}++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [android]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [android]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [darwin]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [darwin]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [freebsd]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [ppc64]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [s390x]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [openharmony]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [win32]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [win32]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-k/9fOUGO39yd2sCjrbAJvGDEQvRwRnQIZlBz43roGwUZo5SHAmyVvSFyaVVZkicRVCaDXPKlbxrUcBuJoSWunQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==}++ '@typescript/[email protected]':+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [aix]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}+ engines: {node: '>=16.20.0'}+ cpu: [loong64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}+ engines: {node: '>=16.20.0'}+ cpu: [mips64el]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}+ engines: {node: '>=16.20.0'}+ cpu: [riscv64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}+ engines: {node: '>=16.20.0'}+ cpu: [s390x]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [sunos]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [win32]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [win32]++ '@webgpu/[email protected]':+ resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==}++ '@xmldom/[email protected]':+ resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==}+ engines: {node: '>=10.0.0'}++ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q==}++ resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-rI2asw77u0mGgwhV3qA+OEgYqaDn5UNqgs+Bx0FGwSpuqfYn+Ir6RQY5ENNQ8SbIiG/m5gVa7CD5RriO4f4Lsg==}++ resolution: {integrity: sha512-VaFW53yt8QO61k2WJui0dHf4SlL8lxBofUuUmwBo0ljPk0Drz2TiuDW4jo3wDcv41qy/SxrJ+VAzJ/qYqsmzRw==}++ resolution: {integrity: sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==}++ resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [android]++ resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [darwin]++ resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [darwin]++ resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [freebsd]++ resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm]+ os: [linux]++ resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]++ resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]++ resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]++ resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]++ resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [win32]++ resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-Tf7FFIrguPKQwzD4pWnYkR2VOv3raoHeKED80Bm+BYHI3KxC8KsgsGC5+fSMzAGDA6UEk4bHvmi+RsjmL3khpg==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-QbTANHMZ751MIjLiLSUSM8a7LNMWwMIf0KbRCqlW+SPS9hNLfSVS+cl1O2SEp9g1K/wyLzj/OJHv+1TUfiPr/w==}++ resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true++ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-w/Te7uMUVeH0CR8vZIjr+XiN41V+30lkDdK+NRIDCUYKKuL9VcmaUEmaPISuwGhLlrTGh5yu18lENtR9axSxYw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}+ engines: {node: '>=16.20.0'}+ hasBin: true++ resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}++ resolution: {integrity: sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ '@vitejs/devtools': ^0.7.1+ esbuild: ^0.27.0 || ^0.28.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ '@vitejs/devtools':+ optional: true+ esbuild:+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++snapshots:++ '@oxc-project/[email protected]': {}++ '@pixi/[email protected]': {}++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 7.18.2++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@webgpu/[email protected]': {}++ '@xmldom/[email protected]': {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optionalDependencies:+ picomatch: 4.0.7++ optional: true++ dependencies:+ js-binary-schema-parser: 2.0.3++ [email protected]: {}++ [email protected]: {}++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ dependencies:+ detect-libc: 2.1.2+ optionalDependencies:+ lightningcss-android-arm64: 1.33.0+ lightningcss-darwin-arm64: 1.33.0+ lightningcss-darwin-x64: 1.33.0+ lightningcss-freebsd-x64: 1.33.0+ lightningcss-linux-arm-gnueabihf: 1.33.0+ lightningcss-linux-arm64-gnu: 1.33.0+ lightningcss-linux-arm64-musl: 1.33.0+ lightningcss-linux-x64-gnu: 1.33.0+ lightningcss-linux-x64-musl: 1.33.0+ lightningcss-win32-arm64-msvc: 1.33.0+ lightningcss-win32-x64-msvc: 1.33.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@pixi/colord': 2.9.6+ '@types/earcut': 3.0.0+ '@webgpu/types': 0.1.74+ '@xmldom/xmldom': 0.8.15+ earcut: 3.2.3+ eventemitter3: 5.0.4+ gifuct-js: 2.1.2+ ismobilejs: 1.1.1+ parse-svg-path: 0.2.0+ tiny-lru: 11.4.7++ dependencies:+ nanoid: 3.3.20+ picocolors: 1.1.1+ source-map-js: 1.2.2++ dependencies:+ '@oxc-project/types': 0.153.0+ '@rolldown/pluginutils': 1.0.1+ optionalDependencies:+ '@rolldown/binding-android-arm-eabi': 1.2.13+ '@rolldown/binding-android-arm64': 1.2.13+ '@rolldown/binding-darwin-arm64': 1.2.13+ '@rolldown/binding-darwin-x64': 1.2.13+ '@rolldown/binding-freebsd-x64': 1.2.13+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.13+ '@rolldown/binding-linux-arm64-gnu': 1.2.13+ '@rolldown/binding-linux-arm64-musl': 1.2.13+ '@rolldown/binding-linux-ppc64-gnu': 1.2.13+ '@rolldown/binding-linux-s390x-gnu': 1.2.13+ '@rolldown/binding-linux-x64-gnu': 1.2.13+ '@rolldown/binding-linux-x64-musl': 1.2.13+ '@rolldown/binding-openharmony-arm64': 1.2.13+ '@rolldown/binding-win32-arm64-msvc': 1.2.13+ '@rolldown/binding-win32-x64-msvc': 1.2.13++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7++ optionalDependencies:+ '@typescript/typescript-aix-ppc64': 7.0.2+ '@typescript/typescript-darwin-arm64': 7.0.2+ '@typescript/typescript-darwin-x64': 7.0.2+ '@typescript/typescript-freebsd-arm64': 7.0.2+ '@typescript/typescript-freebsd-x64': 7.0.2+ '@typescript/typescript-linux-arm': 7.0.2+ '@typescript/typescript-linux-arm64': 7.0.2+ '@typescript/typescript-linux-loong64': 7.0.2+ '@typescript/typescript-linux-mips64el': 7.0.2+ '@typescript/typescript-linux-ppc64': 7.0.2+ '@typescript/typescript-linux-riscv64': 7.0.2+ '@typescript/typescript-linux-s390x': 7.0.2+ '@typescript/typescript-linux-x64': 7.0.2+ '@typescript/typescript-netbsd-arm64': 7.0.2+ '@typescript/typescript-netbsd-x64': 7.0.2+ '@typescript/typescript-openbsd-arm64': 7.0.2+ '@typescript/typescript-openbsd-x64': 7.0.2+ '@typescript/typescript-sunos-x64': 7.0.2+ '@typescript/typescript-win32-arm64': 7.0.2+ '@typescript/typescript-win32-x64': 7.0.2++ [email protected]: {}++ [email protected](@types/[email protected]):+ dependencies:+ lightningcss: 1.33.0+ picomatch: 4.0.7+ postcss: 8.5.29+ rolldown: 1.2.13+ tinyglobby: 0.2.17+ optionalDependencies:+ '@types/node': 25.5.0+ fsevents: 2.3.3diff --git a/src/art.ts b/src/art.tsnew file mode 100644index 0000000..33288cd--- /dev/null+++ b/src/art.ts@@ -0,0 +1,528 @@+/**+ * The yard's look: pale line-drawn buildings on plates, hatched conveyor+ * belts with square joints, cardboard crates with coloured labels, and+ * monospace name tags. Everything is drawn with Pixi graphics in world+ * pixels, measured in units (see `iso.ts`): floor lengths are whole units,+ * heights whole pixels, and lines one of two weights.+ *+ * The measures that have to agree:+ * - a belt is 8 units wide and runs down the middle of a cell;+ * - it meets a factory at the middle of a side, where a door 10 units wide+ * (the belt and a unit of frame either side) stands centred on it;+ * - a crate is 6 units wide: a unit of belt shows either side;+ * - a factory's 3×3 plate is a unit inside its footprint.+ */+import { Container, Graphics, Text, TextStyle } from "pixi.js"++import { flat, FOOTPRINT, GRID, toScreen, U, type Point } from "./iso.ts"+import { kinds, type Kind, type KindId } from "./kinds.ts"+import type { Status, WorkValue } from "./schema.ts"++export const ink = 0x3d4943+const plateFill = 0xf5f6f2+const roofFill = 0xf7f8f4+const leftFill = 0xe9ebe5+const rightFill = 0xdde0d9+const beltFill = 0xe6e8e2+const hatch = 0xb4b9b1++/** Outlines. */+const LINE = 1.5+/** Everything inside an outline: seams, slats, windows, hatching. */+const DETAIL = 1++const STORY = 32+const CHIMNEY = 24+const PLATE = 23 * U+const BELT = 4 * U+const JOINT = 5 * U+const JOINT_INNER = 2 * U+const DOOR = 5 * U+const DOOR_HEIGHT = 16+const AWNING = 6 * U+const AWNING_DEPTH = 3 * U+const CHIMNEY_HALF = 2 * U+const CRATE = 3 * U+const CRATE_HEIGHT = 12+const HATCH_GAP = 3 * U+export const BELT_SPEED = 2.2++/** The layers of the yard, back to front. */+export interface Stage {+ readonly world: Container+ readonly plates: Container+ readonly belts: Container+ readonly preview: Container+ readonly objects: Container+ readonly labels: Container+ readonly overlay: Graphics+ readonly ghost: Graphics+}++const clamp01 = (t: number) => Math.min(1, Math.max(0, t))+const smooth = (t: number) => {+ const u = clamp01(t)+ return u * u * (3 - 2 * u)+}++/**+ * How far along each stage of putting a building up is, from `build` 0 → 1:+ * the plate is marked out, a wire frame rises, the walls grow up inside it,+ * then the door, windows, and chimney are fitted.+ */+export const buildStages = (build: number) => ({+ plate: smooth(build / 0.12),+ frame: smooth((build - 0.1) / 0.25),+ walls: smooth((build - 0.38) / 0.37),+ fit: smooth((build - 0.78) / 0.22)+})++// ── Buildings ─────────────────────────────────────────────────────────────++/** Height of a kind's building at full size. */+export const heightOf = (kind: Kind) => kind.stories * STORY++/** A point of a building, around the centre of its footprint (u, v in cells, z in pixels). */+const at = (u: number, v: number, z: number): Point => toScreen(u, v, z)++const quad = (g: Graphics, points: ReadonlyArray<Point>, fill: number, alpha = 1) =>+ g.poly(flat(points)).fill({ color: fill, alpha }).stroke({ color: ink, width: LINE, join: "round" })++const outline = (g: Graphics, points: ReadonlyArray<Point>, width = LINE, color = ink, alpha = 1) =>+ g.poly(flat(points)).stroke({ color, width, alpha, join: "round" })++const line = (g: Graphics, a: Point, b: Point, width = LINE, color = ink, alpha = 1) =>+ g.moveTo(a.x, a.y).lineTo(b.x, b.y).stroke({ color, width, alpha, cap: "round" })++/** A square on the floor (or at height `z`), centred on (u, v). */+const square = (u: number, v: number, half: number, z = 0): Array<Point> => [+ at(u - half, v - half, z),+ at(u + half, v - half, z),+ at(u + half, v + half, z),+ at(u - half, v + half, z)+]++/** The plate a building stands on; while it is marked out, only its outline, growing. */+export const drawPlate = (g: Graphics, alpha = 1, marked = 1, filled = true) => {+ g.poly(flat(square(0, 0, PLATE * (0.8 + 0.2 * marked))))+ .fill({ color: plateFill, alpha: filled ? alpha : 0 })+ .stroke({ color: ink, width: LINE, alpha: alpha * marked, join: "round" })+}++/** The wire frame of a box, `h` pixels tall: every edge, the hidden ones too. */+const drawFrame = (g: Graphics, a: number, h: number) => {+ const base = square(0, 0, a)+ for (const c of base) line(g, c, { x: c.x, y: c.y - h }, DETAIL)+ outline(g, square(0, 0, a, h), DETAIL)+}++/** The centres of a roof's bays, back row first, in cells. */+const bays = (kind: Kind): Array<{ readonly u: number; readonly v: number; readonly index: number }> => {+ const pitch = (2 * kind.half) / kind.bays+ const out = []+ for (let row = 0; row < kind.bays; row++) {+ for (let col = 0; col < kind.bays; col++) {+ out.push({ u: (-kind.half + pitch * (col + 0.5)) * U, v: (-kind.half + pitch * (row + 0.5)) * U, index: row * kind.bays + col })+ }+ }+ return out+}++/** The chimney stands in the back bay; a depot's flag in the right-hand one. */+const chimneyBay = (kind: Kind) => bays(kind)[0]!+const flagBay = (kind: Kind) => bays(kind)[kind.bays - 1]!++/**+ * A loading door on a wall: `side` "right" is the wall facing down-right+ * (u = a), "left" the one facing down-left (v = a). Centred on the wall, as+ * the belt that meets it is.+ */+const drawDoor = (g: Graphics, side: "right" | "left", a: number, H: number, fit: number, door: number, color: number) => {+ // On the right wall, points run along v; on the left wall, along u.+ const p = (along: number, out: number, z: number) => (side === "right" ? at(a + out, along, z) : at(along, a + out, z))+ const top = Math.round(Math.min(DOOR_HEIGHT, H - 8) * smooth((fit - 0.15) / 0.35))+ if (top <= 0) return+ const open = Math.round(top * door * 0.75)+ const frame = [p(-DOOR, 0, 0), p(DOOR, 0, 0), p(DOOR, 0, top), p(-DOOR, 0, top)]+ g.poly(flat(frame)).fill({ color: 0x8f9891 })+ g.poly(flat([p(-DOOR, 0, open), p(DOOR, 0, open), p(DOOR, 0, top), p(-DOOR, 0, top)])).fill({ color: 0xeef0ea })+ for (let z = top - 3; z > open; z -= 3) line(g, p(-DOOR, 0, z), p(DOOR, 0, z), DETAIL, 0x9aa29b)+ outline(g, frame)+ // The awning above it, folding out as the door is fitted.+ if (fit > 0.5) {+ const out = AWNING_DEPTH * smooth((fit - 0.5) / 0.3)+ quad(g, [p(-AWNING, 0, top + 4), p(AWNING, 0, top + 4), p(AWNING, out, top + 2), p(-AWNING, out, top + 2)], color)+ }+}++/** Vertical seams on a wall: framing the door when it has one, else one down the middle. */+const drawSeams = (g: Graphics, side: "right" | "left", a: number, H: number, door: boolean) => {+ const p = (along: number, z: number) => (side === "right" ? at(a, along, z) : at(along, a, z))+ const seams = door ? [-(a - 4 * U), a - 4 * U] : [0]+ for (const s of seams) line(g, p(s, 0), p(s, H), DETAIL, ink, 0.5)+}++/**+ * A building, `build` 0 → 1 of the way up (see `buildStages`); `door` 0+ * (shut) → 1 (open), `color` its awning's, `leftDoor` whether a belt meets+ * its left wall too (the right wall always has one).+ */+export const drawBuilding = (g: Graphics, kind: Kind, color: number, build: number, door: number, wave: number, leftDoor = false) => {+ const a = kind.half * U+ const full = heightOf(kind)+ const stage = buildStages(build)+ if (stage.frame <= 0) return+ if (stage.walls < 1) drawFrame(g, a, Math.round(full * stage.frame))+ if (stage.walls <= 0) return+ const H = Math.max(2, Math.round(full * stage.walls))++ // Walls: the one facing down-left, then the one facing down-right.+ quad(g, [at(-a, a, 0), at(a, a, 0), at(a, a, H), at(-a, a, H)], leftFill)+ quad(g, [at(a, -a, 0), at(a, a, 0), at(a, a, H), at(a, -a, H)], rightFill)+ drawSeams(g, "left", a, H, leftDoor)+ drawSeams(g, "right", a, H, true)+ if (kind.stories === 2 && H > STORY) {+ line(g, at(-a, a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)+ line(g, at(a, -a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)+ }++ if (stage.fit > 0.15) {+ drawDoor(g, "right", a, H, stage.fit, door, color)+ if (leftDoor) drawDoor(g, "left", a, H, stage.fit, door, color)+ }++ // Roof (the top of the walls while they rise) and its windows, one by one.+ quad(g, square(0, 0, a, H), roofFill)+ if (stage.fit > 0.4) {+ const all = bays(kind).filter((bay) => bay.index !== 0 && !(kind.flag && bay.index === kind.bays - 1))+ const shown = Math.ceil(all.length * smooth((stage.fit - 0.4) / 0.4))+ for (const bay of all.slice(0, shown)) outline(g, square(bay.u, bay.v, (kind.window / 2) * U, H))+ }++ // The chimney, rising last.+ if (stage.fit > 0) {+ const { u, v } = chimneyBay(kind)+ const c = CHIMNEY_HALF+ const top = H + Math.round(CHIMNEY * stage.fit)+ quad(g, [at(u - c, v + c, H), at(u + c, v + c, H), at(u + c, v + c, top), at(u - c, v + c, top)], leftFill)+ quad(g, [at(u + c, v - c, H), at(u + c, v + c, H), at(u + c, v + c, top), at(u + c, v - c, top)], rightFill)+ quad(g, square(u, v, c, top), roofFill)+ }++ // A depot flies a flag in its right-hand bay.+ if (kind.flag && stage.fit > 0.9) {+ const { u, v } = flagBay(kind)+ const base = at(u, v, H)+ const tip = { x: base.x, y: base.y - 24 }+ line(g, base, tip, LINE)+ const flutter = Math.round(Math.sin(wave) * 2)+ g.poly([tip.x, tip.y, tip.x - 10, tip.y + 4 + flutter, tip.x, tip.y + 8]).fill({ color: ink })+ }+}++/** Where a building's chimney puffs from, around its footprint's centre. */+export const chimneyTop = (kind: Kind): Point => {+ const { u, v } = chimneyBay(kind)+ return at(u, v, heightOf(kind) + CHIMNEY + 4)+}++const statusColor: Readonly<Record<Status, number>> = {+ building: 0xb9beb5,+ idle: 0xb9beb5,+ working: 0x4f8a3e,+ starved: 0xd6ae2e,+ blocked: 0xc4523f+}++const labelStyle = new TextStyle({+ fontFamily: "ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, monospace",+ fontSize: 13,+ fill: ink+})++interface Ring {+ age: number+}++/**+ * A factory as drawn: its plate on the floor, its building among the other+ * objects (sorted by depth), and its name tag above everything.+ */+export class FactoryView extends Container {+ private readonly kind: Kind+ private readonly color: number+ private readonly plate = new Graphics()+ private readonly building = new Graphics()+ private readonly smoke = new Graphics()+ private readonly tag = new Container()+ private readonly tagBox = new Graphics()+ private readonly tagDot = new Graphics()+ private readonly tagText: Text+ private readonly rings: Array<Ring> = []+ private puff = 0+ private door = 0+ private drawn = ""+ private wave = 0++ constructor(kindId: KindId, name: string, color: number, stage: Stage) {+ super()+ this.color = color+ this.kind = kinds[kindId]+ this.addChild(this.building, this.smoke)+ this.tagText = new Text({ text: name, style: labelStyle, resolution: 3 })+ this.tagText.anchor.set(0, 0.5)+ this.tag.addChild(this.tagBox, this.tagDot, this.tagText)+ stage.plates.addChild(this.plate)+ stage.labels.addChild(this.tag)+ this.layoutTag()+ }++ /** The tag, in whole pixels: 8 px of padding, an 8 px status square, 6 px before the name. */+ private layoutTag() {+ const pad = 8+ const dot = 8+ const gap = 6+ const width = 2 * Math.ceil((pad + dot + gap + this.tagText.width + pad) / 2)+ const height = 22+ this.tagBox.clear()+ .roundRect(-width / 2 + 0.5, -height / 2 + 0.5, width - 1, height - 1, 3)+ .fill({ color: 0xf6f7f3 })+ .stroke({ color: 0xbfc5bc, width: 1 })+ this.tagDot.position.set(-width / 2 + pad + dot / 2, 0)+ this.tagText.position.set(-width / 2 + pad + dot + gap, 0)+ }++ /** Puts it on the grid by its footprint's top cell. */+ place(x: number, y: number) {+ const centre = toScreen(x + FOOTPRINT / 2, y + FOOTPRINT / 2)+ this.position.set(centre.x, centre.y)+ this.plate.position.set(centre.x, centre.y)+ this.zIndex = x + y + FOOTPRINT+ this.tag.position.set(centre.x, centre.y - heightOf(this.kind) - CHIMNEY - 24)+ }++ /** Follows the factory's work: rising, doors, smoke, bounce, and status. */+ update(work: WorkValue, dt: number, emphasis: "normal" | "dim" | "focus" | "danger", leftDoor: boolean) {+ const build = Math.min(1, work.built)+ const opening = work.status === "working" || work.pulse > 0.2 ? 1 : 0+ this.door += (opening - this.door) * Math.min(1, dt * 6)+ this.wave += dt * (this.kind.flag && work.status === "working" ? 9 : 3)++ // Redrawn only when something it shows moved by a whole pixel's worth.+ const key = `${build.toFixed(3)}|${Math.round(this.door * 12)}|${leftDoor}|${this.kind.flag ? Math.round(Math.sin(this.wave) * 2) : ""}`+ if (key !== this.drawn) {+ this.drawn = key+ this.building.clear()+ drawBuilding(this.building, this.kind, this.color, build, this.door, this.wave, leftDoor)+ const stage = buildStages(build)+ this.plate.clear()+ drawPlate(this.plate, 1, stage.plate, stage.walls > 0)+ }++ // A small bounce when a job finishes; at rest it is exactly its drawn size.+ const p = work.pulse+ this.building.scale.set(1 + p * 0.04, 1 - p * 0.06)++ // Smoke rings, while working.+ this.puff -= dt+ if (work.status === "working" && this.puff <= 0) {+ this.rings.push({ age: 0 })+ this.puff = 0.7+ }+ const top = chimneyTop(this.kind)+ this.smoke.clear()+ for (let i = this.rings.length - 1; i >= 0; i--) {+ const ring = this.rings[i]!+ ring.age += dt / 1.8+ if (ring.age >= 1) {+ this.rings.splice(i, 1)+ continue+ }+ const t = ring.age+ this.smoke.circle(top.x + Math.sin(t * 5) * 1.5, top.y - t * 34, 4 + t * 7)+ .stroke({ color: ink, width: DETAIL, alpha: (1 - t) * 0.55 })+ }++ // The tag's status square: filled while it has something to say, hollow when idle.+ const blink = work.status === "blocked" ? 0.55 + 0.45 * Math.sin(this.wave * 3) : 1+ this.tagDot.clear()+ if (work.status === "idle" || work.status === "building") this.tagDot.rect(-3.5, -3.5, 7, 7).stroke({ color: 0x9aa09a, width: 1 })+ else this.tagDot.rect(-4, -4, 8, 8).fill({ color: statusColor[work.status], alpha: blink })++ const alpha = emphasis === "dim" ? 0.28 : 1+ this.alpha = alpha+ this.plate.alpha = alpha+ this.tag.alpha = (emphasis === "dim" ? 0.4 : 1) * buildStages(build).walls+ this.building.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff+ this.tagBox.tint = emphasis === "focus" ? 0xdfe6dc : 0xffffff+ }++ override destroy(options?: Parameters<Container["destroy"]>[0]) {+ this.plate.destroy()+ this.tag.destroy({ children: true })+ super.destroy(options)+ }+}++// ── Belts ─────────────────────────────────────────────────────────────────++const along = (a: Point, b: Point) => {+ const length = Math.hypot(b.x - a.x, b.y - a.y)+ const d = length === 0 ? { x: 1, y: 0 } : { x: (b.x - a.x) / length, y: (b.y - a.y) / length }+ return { length, d, p: { x: -d.y, y: d.x } }+}++/** A straight run of belt from `a` to `b`, `half` either side of the centre line. */+const strip = (a: Point, b: Point, half: number): [Point, Point, Point, Point] => {+ const { p } = along(a, b)+ return [+ toScreen(a.x + p.x * half, a.y + p.y * half),+ toScreen(b.x + p.x * half, b.y + p.y * half),+ toScreen(b.x - p.x * half, b.y - p.y * half),+ toScreen(a.x - p.x * half, a.y - p.y * half)+ ]+}++/** A square on the floor in grid coordinates. */+const tile = (c: Point, half: number): Array<Point> => [+ toScreen(c.x - half, c.y - half),+ toScreen(c.x + half, c.y - half),+ toScreen(c.x + half, c.y + half),+ toScreen(c.x - half, c.y + half)+]++/** A belt's surface. */+export const drawBeltBase = (g: Graphics, points: ReadonlyArray<Point>, alpha = 1) => {+ for (let i = 1; i < points.length; i++) g.poly(flat(strip(points[i - 1]!, points[i]!, BELT))).fill({ color: beltFill, alpha })+}++/** A belt's rails, square ends, and square joints at the turns. */+export const drawBeltRails = (g: Graphics, points: ReadonlyArray<Point>, alpha = 1, color = ink) => {+ for (let i = 1; i < points.length; i++) {+ const [p0, p1, p2, p3] = strip(points[i - 1]!, points[i]!, BELT)+ line(g, p0, p1, LINE, color, alpha)+ line(g, p3, p2, LINE, color, alpha)+ }+ const first = strip(points[0]!, points[1]!, BELT)+ line(g, first[0], first[3], LINE, color, alpha)+ const last = strip(points[points.length - 2]!, points[points.length - 1]!, BELT)+ line(g, last[1], last[2], LINE, color, alpha)+ for (let i = 1; i < points.length - 1; i++) {+ const c = points[i]!+ g.poly(flat(tile(c, JOINT))).fill({ color: beltFill, alpha }).stroke({ color, width: LINE, alpha, join: "round" })+ g.poly(flat(tile(c, JOINT_INNER))).stroke({ color, width: DETAIL, alpha: alpha * 0.8, join: "round" })+ }+}++/** The hatching across a belt, rail to rail, scrolled by `offset` (cells) towards its end. */+export const drawBeltHatch = (g: Graphics, points: ReadonlyArray<Point>, offset: number, alpha = 1) => {+ let start = 0+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1]!+ const { length, d, p } = along(a, points[i]!)+ let s = (((offset - start) % HATCH_GAP) + HATCH_GAP) % HATCH_GAP+ for (; s < length; s += HATCH_GAP) {+ const c = { x: a.x + d.x * s, y: a.y + d.y * s }+ const l = toScreen(c.x + p.x * BELT, c.y + p.y * BELT)+ const r = toScreen(c.x - p.x * BELT, c.y - p.y * BELT)+ g.moveTo(l.x, l.y).lineTo(r.x, r.y)+ }+ start += length+ }+ g.stroke({ color: hatch, width: DETAIL, alpha })+}++export class BeltView extends Container {+ private readonly base = new Graphics()+ private readonly hatching = new Graphics()+ private readonly rails = new Graphics()+ private readonly points: ReadonlyArray<Point>++ constructor(points: ReadonlyArray<Point>) {+ super()+ this.points = points+ drawBeltBase(this.base, points)+ drawBeltRails(this.rails, points)+ this.addChild(this.base, this.hatching, this.rails)+ }++ update(time: number, emphasis: "normal" | "dim" | "focus" | "danger") {+ this.hatching.clear()+ drawBeltHatch(this.hatching, this.points, time * BELT_SPEED)+ this.alpha = emphasis === "dim" ? 0.25 : 1+ this.tint = emphasis === "danger" ? 0xf3b5aa : 0xffffff+ }+}++// ── Crates ────────────────────────────────────────────────────────────────++/** A crate, 6 units square and 12 px tall, sitting on its belt. */+export const drawCrate = (g: Graphics, label: number) => {+ const s = CRATE+ const h = CRATE_HEIGHT+ const edge = 0x7d6140+ const face = (points: ReadonlyArray<Point>, fill: number) =>+ g.poly(flat(points)).fill({ color: fill }).stroke({ color: edge, width: DETAIL, join: "round" })+ face([at(-s, s, 0), at(s, s, 0), at(s, s, h), at(-s, s, h)], 0xe9c48a)+ face([at(s, -s, 0), at(s, s, 0), at(s, s, h), at(s, -s, h)], 0xd5a86c)+ face(square(0, 0, s, h), 0xf4dcab)+ // Tape across the lid, a unit wide, and the label of the factory that made it.+ g.poly(flat([at(-s, -0.5 * U, h), at(s, -0.5 * U, h), at(s, 0.5 * U, h), at(-s, 0.5 * U, h)])).fill({ color: 0xc79a5b })+ g.poly(flat([at(-2 * U, s, 3), at(U, s, 3), at(U, s, 8), at(-2 * U, s, 8)])).fill({ color: label })+}++export class CrateView extends Graphics {+ constructor(label: number) {+ super()+ drawCrate(this, label)+ }++ place(x: number, y: number) {+ const s = toScreen(x, y)+ this.position.set(s.x, s.y)+ this.zIndex = x + y+ }+}++// ── The floor ─────────────────────────────────────────────────────────────++/** The grid: a faint line between every two cells, and the yard's edge. */+export const drawFloor = (g: Graphics) => {+ for (let i = 1; i < GRID; i++) {+ const a = toScreen(i, 0)+ const b = toScreen(i, GRID)+ const c = toScreen(0, i)+ const d = toScreen(GRID, i)+ g.moveTo(a.x, a.y).lineTo(b.x, b.y).moveTo(c.x, c.y).lineTo(d.x, d.y)+ }+ g.stroke({ color: 0xd9ddd3, width: DETAIL })+ outline(g, [toScreen(0, 0), toScreen(GRID, 0), toScreen(GRID, GRID), toScreen(0, GRID)], LINE, 0xb9bfb4)+}++/**+ * A plot on the floor: under the pointer (`hover`), picked for building+ * (`picked`, with corner ticks that breathe with `time`), or with no room+ * (`blocked`).+ */+export const drawPlot = (g: Graphics, x: number, y: number, look: "hover" | "picked" | "blocked", time = 0) => {+ const n = FOOTPRINT+ const corners = [toScreen(x, y), toScreen(x + n, y), toScreen(x + n, y + n), toScreen(x, y + n)]+ if (look === "hover") {+ g.poly(flat(corners)).fill({ color: ink, alpha: 0.04 }).stroke({ color: ink, width: DETAIL, alpha: 0.35 })+ return+ }+ const color = look === "blocked" ? 0xc4523f : ink+ g.poly(flat(corners)).fill({ color, alpha: 0.07 }).stroke({ color, width: LINE, alpha: 0.85 })+ // Corner ticks a unit outside the plot, 4 units long (breathing by a unit).+ const reach = (4 + Math.sin(time * 4)) * U+ const ticks: ReadonlyArray<readonly [number, number, number, number]> = [[x, y, 1, 1], [x + n, y, -1, 1], [x + n, y + n, -1, -1], [x, y + n, 1, -1]]+ for (const [cx, cy, sx, sy] of ticks) {+ const ox = cx - sx * U+ const oy = cy - sy * U+ const a = toScreen(ox + sx * reach, oy)+ const o = toScreen(ox, oy)+ const b = toScreen(ox, oy + sy * reach)+ g.moveTo(a.x, a.y).lineTo(o.x, o.y).lineTo(b.x, b.y)+ }+ g.stroke({ color, width: LINE, alpha: 0.9, join: "round" })+}diff --git a/src/factory.css b/src/factory.cssnew file mode 100644index 0000000..02aa940--- /dev/null+++ b/src/factory.css@@ -0,0 +1,82 @@+html, body { margin: 0; height: 100%; overflow: hidden; background: #f0f2ec; touch-action: none; }+body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace; color: #3d4943; -webkit-user-select: none; user-select: none; }+#app { position: fixed; inset: 0; }+#app canvas { display: block; }++.hud { position: fixed; top: 14px; left: 16px; pointer-events: none; font-size: 12px; line-height: 1.6; }+.hud h1 { margin: 0 0 2px; font-size: 13px; font-weight: 600; letter-spacing: 0.02em; }+.hud .stats { color: #6c766f; }++.toolbar {+ position: fixed; left: 16px; bottom: calc(14px + env(safe-area-inset-bottom));+ display: flex; gap: 6px; padding: 6px; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 6px;+ box-shadow: 0 2px 0 #dfe2db; max-width: calc(100vw - 24px); overflow-x: auto;+}+.toolbar button {+ font: inherit; font-size: 12px; color: #3d4943; background: transparent; border: 1px solid transparent;+ border-radius: 4px; padding: 6px 10px; display: flex; align-items: center; gap: 7px; cursor: pointer; white-space: nowrap;+}+.toolbar button:hover { background: #eceee8; }+.toolbar button.on { background: #3d4943; color: #f7f8f4; }+.toolbar button .swatch { width: 9px; height: 9px; border: 1px solid currentColor; display: inline-block; }+.toolbar button kbd { font: inherit; font-size: 10px; opacity: 0.55; }+.toolbar .sep { width: 1px; background: #d5d9d0; margin: 3px 2px; }++.tooltip {+ position: fixed; pointer-events: none; background: #2f4639; color: #f3f5ef; font-size: 13px;+ padding: 5px 10px; border-radius: 2px; white-space: pre; transform: translate(14px, 10px); display: none;+}+.toast {+ position: fixed; top: 14px; left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;+ font-size: 12px; padding: 6px 12px; border-radius: 3px; opacity: 0; transition: opacity 160ms ease; pointer-events: none;+}+.toast.show { opacity: 1; }+.hint { position: fixed; right: 16px; transition: opacity 200ms ease; top: 14px; font-size: 11px; color: #8a938c; text-align: right; line-height: 1.6; pointer-events: none; }+@media (max-width: 900px), (pointer: coarse) { .hint { display: none; } }++body:has(.panel.open) .hint { opacity: 0; }++.panel {+ position: fixed; top: 0; right: 0; bottom: 0; width: 360px; max-width: 46vw; box-sizing: border-box;+ background: #f1f3ed; border-left: 1px solid #c3c8bf; padding: 22px 24px calc(24px + env(safe-area-inset-bottom));+ overflow-y: auto; transform: translateX(100%); transition: transform 240ms cubic-bezier(.2,.8,.2,1);+ font-size: 14px; color: #3d4943; -webkit-user-select: none; user-select: none;+}+.panel.open { transform: none; }+.panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 18px; }+.panel h2 { margin: 6px 0 0; font-size: 16px; font-weight: 700; letter-spacing: 0.01em; word-break: break-all; }+.panel .sub { margin: 0 0 6px; color: #6c766f; }+.panel .sub.warn { color: #b04a39; }+.panel section { margin-top: 24px; }+.panel h3 {+ margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid #d3d7ce; font-size: 11px; font-weight: 400;+ letter-spacing: 0.12em; text-transform: uppercase; color: #77817a;+}+.panel .row { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; padding: 4px 0; }+.panel .count { color: #6c766f; white-space: nowrap; }+.panel .empty { margin: 4px 0; color: #8a938c; }+.panel button { font: inherit; color: inherit; cursor: pointer; }+.panel .link {+ background: none; border: 0; padding: 0; text-align: left; text-decoration: underline;+ text-decoration-color: #b5bbb2; text-underline-offset: 4px;+}+.panel .link:hover { text-decoration-color: #3d4943; }+.panel .frame { background: transparent; border: 1px solid #3d4943; border-radius: 2px; padding: 6px 12px; white-space: nowrap; }+.panel .frame:hover { background: #e6e9e2; }+.panel .frame.danger { border-color: #b04a39; color: #b04a39; }+.panel .actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 28px; }+.panel .option {+ display: block; width: 100%; text-align: left; background: none; border: 0; border-radius: 2px;+ padding: 8px 8px; margin: 0 -8px; width: calc(100% + 16px);+}+.panel .option:hover:not(:disabled) { background: #e6e9e2; }+.panel .option:disabled { opacity: 0.4; cursor: default; }+.panel .option .row { padding: 0; }+.panel .option .name { text-decoration: underline; text-decoration-color: #b5bbb2; text-underline-offset: 4px; }+.panel .option .blurb { display: block; margin-top: 4px; color: #77817a; }+@media (max-height: 500px) {+ .panel { padding: 14px 16px; width: 300px; }+ .panel header { margin-bottom: 8px; }+ .panel section { margin-top: 14px; }+ .panel .option { padding: 5px 8px; }+}diff --git a/src/host.ts b/src/host.tsnew file mode 100644index 0000000..399081a--- /dev/null+++ b/src/host.ts@@ -0,0 +1,425 @@+/**+ * The page around the yard: the Pixi stage and its layers, the camera (drag+ * to pan, wheel or pinch to zoom), the pointer turned into intents, and the+ * toolbar, stats, tooltip, and toasts.+ */+import { Application, Container, Graphics } from "pixi.js"++import { drawFloor, type Stage } from "./art.ts"+import { GRID, toScreen, type Point } from "./iso.ts"+import { kindOrder, kinds } from "./kinds.ts"+import type { Intent, Mode, PanelLink, UiValue } from "./schema.ts"++/** A small yard to start from, like a repository's packages feeding each other. */+const demo: ReadonlyArray<Intent> = [+ { type: "place", kind: "source", cell: { x: 2, y: 12 } },+ { type: "place", kind: "source", cell: { x: 3, y: 4 } },+ { type: "place", kind: "plant", cell: { x: 9, y: 9 } },+ { type: "place", kind: "workshop", cell: { x: 10, y: 2 } },+ { type: "place", kind: "workshop", cell: { x: 16, y: 7 } },+ { type: "place", kind: "workshop", cell: { x: 9, y: 16 } },+ { type: "place", kind: "depot", cell: { x: 20, y: 13 } },+ { type: "place", kind: "depot", cell: { x: 16, y: 19 } },+ { type: "link", from: { x: 2, y: 12 }, to: { x: 9, y: 9 } },+ { type: "link", from: { x: 3, y: 4 }, to: { x: 9, y: 9 } },+ { type: "link", from: { x: 3, y: 4 }, to: { x: 10, y: 2 } },+ { type: "link", from: { x: 10, y: 2 }, to: { x: 16, y: 7 } },+ { type: "link", from: { x: 9, y: 9 }, to: { x: 16, y: 7 } },+ { type: "link", from: { x: 9, y: 9 }, to: { x: 9, y: 16 } },+ { type: "link", from: { x: 16, y: 7 }, to: { x: 20, y: 13 } },+ { type: "link", from: { x: 9, y: 16 }, to: { x: 16, y: 19 } }+]++const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {+ const node = document.createElement(tag)+ node.className = className+ node.textContent = text+ return node+}++export const createHost = async (mount: HTMLElement) => {+ const app = new Application()+ await app.init({+ resizeTo: window,+ antialias: true,+ background: 0xf0f2ec,+ resolution: Math.min(window.devicePixelRatio || 1, 2),+ autoDensity: true+ })+ mount.appendChild(app.canvas)++ // ── Layers ──+ const world = new Container()+ const floor = new Graphics()+ drawFloor(floor)+ const plates = new Container()+ const belts = new Container()+ const preview = new Container()+ const overlay = new Graphics()+ preview.addChild(overlay)+ const objects = new Container({ sortableChildren: true })+ const ghost = new Graphics()+ objects.addChild(ghost)+ const labels = new Container()+ world.addChild(floor, plates, belts, preview, objects, labels)+ app.stage.addChild(world)+ const stage: Stage = { world, plates, belts, preview, objects, labels, overlay, ghost }++ // ── Camera ──+ const centre = toScreen(GRID / 2, GRID / 2)+ // Zoom steps at which a unit (2 × 1 px at 1×) is still a whole number of+ // device pixels on a 2× screen, so the drawing stays on its lattice.+ const zooms = [0.5, 1, 1.5, 2] as const+ let zoom: number = window.innerWidth >= 1200 && window.innerHeight >= 800 ? 1 : 0.5+ const look = { x: centre.x, y: centre.y }+ const placeCamera = () => {+ world.scale.set(zoom)+ // Whole device pixels, so lines land where the lattice puts them.+ const dpr = app.renderer.resolution+ world.position.set(+ Math.round((app.screen.width / 2 - look.x * zoom) * dpr) / dpr,+ Math.round((app.screen.height / 2 - look.y * zoom) * dpr) / dpr+ )+ }+ placeCamera()+ app.renderer.on("resize", placeCamera)+ const toWorld = (sx: number, sy: number): Point => ({ x: (sx - world.position.x) / zoom, y: (sy - world.position.y) / zoom })+ const zoomTo = (sx: number, sy: number, next: number) => {+ const before = toWorld(sx, sy)+ zoom = Math.min(2, Math.max(0.5, next))+ look.x = before.x - (sx - app.screen.width / 2) / zoom+ look.y = before.y - (sy - app.screen.height / 2) / zoom+ placeCamera()+ }++ /** Glides the camera to a world point, leaving room for the panel on the right. */+ let glide: Point | null = null+ const lookAt = (at: Point) => {+ glide = { x: at.x + panelWidth() / 2 / zoom, y: at.y - 30 }+ }++ // ── DOM ──+ const hud = el("div", "hud")+ const title = el("h1", "", "factory yard")+ const stats = el("div", "stats")+ hud.append(title, stats)+ const hint = el("div", "hint")+ hint.innerHTML = "tap the ground: build there<br>tap a factory: what it takes and feeds<br>drag factory → factory: belt<br>drag empty ground: pan · wheel: zoom<br>X bulldoze · Esc close"+ const tooltip = el("div", "tooltip")+ const toastBox = el("div", "toast")+ const toolbar = el("div", "toolbar")+ const panel = el("aside", "panel")+ document.body.append(hud, hint, tooltip, toastBox, toolbar, panel)+ const panelWidth = () => (panel.classList.contains("open") ? panel.offsetWidth : 0)++ let toastTimer = 0+ const ui: UiValue = {+ mode: "select",+ plot: null,+ plotKind: null,+ linkFrom: null,+ pointer: null,+ dragFrom: null,+ selected: null,+ intents: [...demo],+ preview: { ghost: null, plots: [], path: null, hoverFactory: null, hoverBelt: null, focus: null, danger: false, tooltip: null },+ hits: [],+ panel: null,+ centres: new Map(),+ stats: { factories: 0, belts: 0, crates: 0, shipped: 0 },+ toast: (message) => {+ toastBox.textContent = message+ toastBox.classList.add("show")+ window.clearTimeout(toastTimer)+ toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), 1600)+ }+ }++ const tools: ReadonlyArray<{ readonly mode: Mode; readonly label: string; readonly key: string }> = [+ { mode: "select", label: "select", key: "S" },+ { mode: "bulldoze", label: "bulldoze", key: "X" }+ ]+ const buttons = tools.map((tool) => {+ const button = el("button", "")+ const swatch = el("span", "swatch")+ if (tool.mode === "select") swatch.style.borderRadius = "50%"+ if (tool.mode === "bulldoze") swatch.style.background = "#c4523f"+ button.append(swatch, document.createTextNode(tool.label), el("kbd", "", tool.key))+ button.onclick = () => choose(tool.mode)+ toolbar.append(button)+ return { tool, button }+ })+ toolbar.append(el("span", "sep"))+ const demoButton = el("button", "", "demo")+ demoButton.onclick = () => ui.intents.push({ type: "clear" }, ...demo)+ const clearButton = el("button", "", "clear")+ clearButton.onclick = () => ui.intents.push({ type: "clear" })+ toolbar.append(demoButton, clearButton)++ const close = () => {+ ui.selected = null+ ui.plot = null+ ui.plotKind = null+ ui.linkFrom = null+ }++ const choose = (mode: Mode) => {+ ui.mode = mode+ ui.dragFrom = null+ if (mode === "bulldoze") close()+ for (const { tool, button } of buttons) button.classList.toggle("on", tool.mode === mode)+ }+ choose("select")++ window.addEventListener("keydown", (event) => {+ if (event.key === "Escape") {+ if (ui.linkFrom !== null) ui.linkFrom = null+ else if (ui.mode !== "select") choose("select")+ else close()+ }+ if (event.key === "s" || event.key === "S") choose("select")+ if (event.key === "x" || event.key === "X") choose("bulldoze")+ })++ // ── Panel ──+ /** Volatile numbers the panel shows, updated in place without rebuilding it. */+ let live: Array<() => void> = []+ let shape = ""++ const section = (heading: string) => {+ const box = el("section", "")+ box.append(el("h3", "", heading))+ return box+ }++ const openFactory = (id: number) => {+ ui.selected = id+ ui.plot = null+ ui.linkFrom = null+ const at = ui.centres.get(id)+ if (at) lookAt(at)+ }++ const factoryRows = (box: HTMLElement, links: ReadonlyArray<PanelLink>, which: "takes" | "feeds") => {+ links.forEach((link, index) => {+ const row = el("div", "row")+ const name = el("button", "link", `${kinds[link.kind].title.toLowerCase()}/${link.name}`)+ name.onclick = () => openFactory(link.id)+ const count = el("span", "count")+ row.append(name, count)+ box.append(row)+ live.push(() => {+ const p = ui.panel+ const now = p?.type === "factory" ? p[which][index] : undefined+ count.textContent = now ? `${now.crates} crate${now.crates === 1 ? "" : "s"}` : ""+ })+ })+ }++ const buildPanel = () => {+ const p = ui.panel+ live = []+ panel.replaceChildren()+ if (!p) return+ const head = el("header", "")+ const closeButton = el("button", "frame", "Close")+ closeButton.onclick = close+ if (p.type === "plot") {+ head.append(el("h2", "", `plot ${p.x},${p.y}`), closeButton)+ panel.append(head, el("p", p.free ? "sub" : "sub warn", p.reason))+ const box = section("build here")+ for (const id of kindOrder) {+ const kind = kinds[id]+ const row = el("button", "option")+ row.disabled = !p.free+ const top = el("span", "row")+ top.append(el("span", "name", kind.title.toLowerCase()), el("span", "count", kind.needs === 0 ? `makes ${kind.makes}` : kind.makes === 0 ? `ships ${kind.needs}` : `takes ${kind.needs}, makes ${kind.makes}`))+ row.append(top, el("span", "blurb", `${kind.blurb} · ${kind.period}s a job`))+ row.onmouseenter = () => (ui.plotKind = id)+ row.onmouseleave = () => {+ if (ui.plotKind === id) ui.plotKind = null+ }+ row.onclick = () => ui.intents.push({ type: "build", kind: id })+ box.append(row)+ }+ panel.append(box)+ return+ }++ const kind = kinds[p.kind]+ head.append(el("h2", "", `${kind.title.toLowerCase()}/${p.name}`), closeButton)+ const status = el("p", "sub")+ const numbers = el("p", "sub")+ panel.append(head, status, numbers)+ live.push(() => {+ const now = ui.panel+ if (now?.type !== "factory") return+ status.textContent = `${now.status} · ${kind.blurb}`+ numbers.textContent = now.kind === "depot"+ ? `${now.inputs} waiting · ${now.made} shipped`+ : now.kind === "source"+ ? `${now.outputs} ready · ${now.made} made`+ : `${now.inputs} in · ${now.outputs} out · ${now.made} jobs done`+ })++ const takes = section("takes from")+ if (kind.needs === 0) takes.append(el("p", "empty", "nothing: it makes crates from nothing"))+ else if (p.takes.length === 0) takes.append(el("p", "empty", "no belts in yet: drag one here from another factory"))+ factoryRows(takes, p.takes, "takes")+ const feeds = section("feeds")+ if (kind.makes === 0) feeds.append(el("p", "empty", "nothing: it ships crates out of the yard"))+ else if (p.feeds.length === 0) feeds.append(el("p", "empty", "no belts out yet: connect it to send its crates on"))+ factoryRows(feeds, p.feeds, "feeds")+ panel.append(takes, feeds)++ const actions = el("div", "actions")+ if (kind.makes > 0) {+ const connect = el("button", "frame", p.linking ? "Tap a factory… (cancel)" : "Connect to…")+ connect.onclick = () => {+ ui.linkFrom = p.linking ? null : p.id+ if (!p.linking) ui.toast("Tap the factory to send crates to")+ }+ actions.append(connect)+ }+ const remove = el("button", "frame danger", "Remove")+ remove.onclick = () => ui.intents.push({ type: "remove", factory: p.id })+ actions.append(remove)+ panel.append(actions)+ }++ /** Rebuilds the panel when what it lists changes, and refreshes its numbers every frame. */+ const syncPanel = () => {+ const p = ui.panel+ const next = p === null+ ? ""+ : p.type === "plot"+ ? `plot|${p.x},${p.y}|${p.free}|${p.reason}`+ : `factory|${p.id}|${p.linking}|${p.takes.map((l) => l.id).join(",")}|${p.feeds.map((l) => l.id).join(",")}`+ if (next !== shape) {+ shape = next+ // Keep the old contents while the closed panel slides away.+ if (p !== null) buildPanel()+ panel.classList.toggle("open", p !== null)+ }+ for (const update of live) update()+ }++ // ── Pointer ──+ const canvas = app.canvas+ const pointers = new Map<number, Point>()+ let press: { id: number; start: Point; last: Point; pan: boolean; panned: boolean } | null = null+ let pinch: { distance: number } | null = null+ let screenPointer: Point | null = null+ let wheel = 0++ const spread = () => {+ const [a, b] = [...pointers.values()]+ return a && b ? { distance: Math.hypot(a.x - b.x, a.y - b.y), mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } } : null+ }++ canvas.addEventListener("pointerdown", (event) => {+ canvas.setPointerCapture(event.pointerId)+ const at = { x: event.clientX, y: event.clientY }+ pointers.set(event.pointerId, at)+ screenPointer = at+ ui.pointer = toWorld(at.x, at.y)+ if (pointers.size === 2) {+ // A second finger: pinch, and forget what the first one was doing.+ pinch = { distance: spread()!.distance }+ press = null+ ui.dragFrom = null+ return+ }+ const world = toWorld(at.x, at.y)+ const onFactory = ui.hits.some((h) => h.contains(world))+ // Dragging from a factory draws a belt; dragging anywhere else pans.+ const pan = event.button === 1 || event.button === 2 || !(ui.mode === "select" && onFactory && ui.linkFrom === null)+ glide = null+ press = { id: event.pointerId, start: at, last: at, pan, panned: false }+ if (event.button === 0) ui.intents.push({ type: "press", at: world })+ })++ canvas.addEventListener("pointermove", (event) => {+ const at = { x: event.clientX, y: event.clientY }+ if (pointers.has(event.pointerId)) pointers.set(event.pointerId, at)+ if (pinch && pointers.size === 2) {+ const now = spread()!+ zoomTo(now.mid.x, now.mid.y, zoom * (now.distance / pinch.distance))+ pinch.distance = now.distance+ return+ }+ screenPointer = at+ ui.pointer = toWorld(at.x, at.y)+ if (press && press.id === event.pointerId && press.pan) {+ if (!press.panned && Math.hypot(at.x - press.start.x, at.y - press.start.y) > 6) press.panned = true+ if (press.panned) {+ look.x -= (at.x - press.last.x) / zoom+ look.y -= (at.y - press.last.y) / zoom+ placeCamera()+ }+ }+ if (press) press.last = at+ })++ const release = (event: PointerEvent, cancelled: boolean) => {+ pointers.delete(event.pointerId)+ if (pinch && pointers.size < 2) {+ // A pinch settles on the nearest zoom step.+ pinch = null+ const nearest = zooms.reduce((best, z) => (Math.abs(z - zoom) < Math.abs(best - zoom) ? z : best), zooms[0])+ zoomTo(event.clientX, event.clientY, nearest)+ }+ if (press && press.id === event.pointerId) {+ const at = toWorld(event.clientX, event.clientY)+ ui.intents.push({ type: "release", at, panned: press.panned || cancelled || event.button !== 0 })+ press = null+ }+ // Touch has no hover: clear it when the finger lifts.+ if (event.pointerType !== "mouse") {+ ui.pointer = null+ screenPointer = null+ }+ }+ canvas.addEventListener("pointerup", (event) => release(event, false))+ canvas.addEventListener("pointercancel", (event) => release(event, true))+ canvas.addEventListener("pointerleave", (event) => {+ if (event.pointerType === "mouse" && !press) {+ ui.pointer = null+ screenPointer = null+ }+ })+ canvas.addEventListener("contextmenu", (event) => event.preventDefault())+ canvas.addEventListener("wheel", (event) => {+ event.preventDefault()+ // One wheel notch (or a trackpad's worth of scrolling) is one zoom step.+ wheel += event.deltaY+ if (Math.abs(wheel) < 40) return+ const index = zooms.findIndex((z) => z >= zoom - 1e-6)+ const next = zooms[Math.min(zooms.length - 1, Math.max(0, index + (wheel > 0 ? -1 : 1)))]!+ wheel = 0+ zoomTo(event.clientX, event.clientY, next)+ }, { passive: false })++ /** Copies the yard's preview and numbers into the page, once a frame. */+ const syncPage = () => {+ syncPanel()+ if (glide) {+ look.x += (glide.x - look.x) * 0.14+ look.y += (glide.y - look.y) * 0.14+ if (Math.hypot(glide.x - look.x, glide.y - look.y) < 0.5) glide = null+ placeCamera()+ }+ const s = ui.stats+ stats.textContent = `${s.factories} factories · ${s.belts} belts · ${s.crates} in transit · ${s.shipped} shipped`+ const text = ui.preview.tooltip+ if (text && screenPointer) {+ tooltip.textContent = text+ tooltip.style.display = "block"+ tooltip.style.left = `${Math.min(screenPointer.x, window.innerWidth - tooltip.offsetWidth - 20)}px`+ tooltip.style.top = `${screenPointer.y}px`+ } else tooltip.style.display = "none"+ canvas.style.cursor = press?.panned ? "grabbing" : ui.preview.hoverFactory !== null || ui.mode !== "select" ? "pointer" : "default"+ }++ return { app, stage, ui, syncPage }+}diff --git a/src/iso.ts b/src/iso.tsnew file mode 100644index 0000000..0dc2bdf--- /dev/null+++ b/src/iso.ts@@ -0,0 +1,39 @@+/**+ * The isometric grid, and the one measure everything is drawn in.+ *+ * A cell is 1×1 in grid space and a 64×32 px diamond on screen: grid x runs+ * down-right, grid y down-left, z straight up (in pixels). Every length on+ * the floor is a whole number of units `U` (a sixteenth of a cell), so every+ * corner lands on a whole pixel: one unit along x is exactly (2, 1) px.+ * Heights are whole pixels.+ */+export const TILE_W = 64+export const TILE_H = 32+/** A sixteenth of a cell: the smallest length anything on the floor is measured in. */+export const U = 1 / 16+/** Cells along each side of the yard. */+export const GRID = 24+/** A factory stands on 3×3 cells; belts meet it at the middle cell of a side. */+export const FOOTPRINT = 3++export interface Point {+ readonly x: number+ readonly y: number+}++/** Grid point (and height in pixels) to world pixels. */+export const toScreen = (x: number, y: number, z = 0): Point => ({+ x: (x - y) * (TILE_W / 2),+ y: (x + y) * (TILE_H / 2) - z+})++/** World pixels (on the floor) to a grid point. */+export const toGrid = (sx: number, sy: number): Point => ({+ x: (sx / (TILE_W / 2) + sy / (TILE_H / 2)) / 2,+ y: (sy / (TILE_H / 2) - sx / (TILE_W / 2)) / 2+})++/** Flattens points to Pixi's `[x0, y0, x1, y1, …]`. */+export const flat = (points: ReadonlyArray<Point>): Array<number> => points.flatMap((p) => [p.x, p.y])++export const inside = (x: number, y: number): boolean => x >= 0 && y >= 0 && x < GRID && y < GRIDdiff --git a/src/kinds.ts b/src/kinds.tsnew file mode 100644index 0000000..ee90f55--- /dev/null+++ b/src/kinds.ts@@ -0,0 +1,74 @@+/** The factories the player can place, and how each one works. */+export type KindId = "source" | "workshop" | "plant" | "depot"++export interface Kind {+ readonly id: KindId+ readonly title: string+ readonly blurb: string+ /** Half the building's width, in units (see `iso.ts`): its walls stand this far from its centre. */+ readonly half: number+ readonly stories: 1 | 2+ /**+ * The roof is split into bays × bays squares: the back one holds the+ * chimney, a depot's flag stands in the right-hand one, and every other+ * one has a window `window` units across.+ */+ readonly bays: 2 | 3+ readonly window: number+ /** Crates taken per job (0: makes them from nothing). */+ readonly needs: number+ /** Crates made per job (0: ships them out of the yard). */+ readonly makes: number+ /** Seconds per job. */+ readonly period: number+ readonly inputCap: number+ readonly outputCap: number+ readonly flag: boolean+}++// Each kind's `half` splits evenly into its bays (2 × half / bays is whole),+// so every window and the chimney sit on whole units.+export const kinds: Readonly<Record<KindId, Kind>> = {+ source: {+ id: "source", title: "Source", blurb: "makes crates from nothing",+ half: 14, stories: 1, bays: 2, window: 6,+ needs: 0, makes: 1, period: 1.4, inputCap: 0, outputCap: 3, flag: false+ },+ workshop: {+ id: "workshop", title: "Workshop", blurb: "relabels one crate at a time",+ half: 16, stories: 1, bays: 2, window: 8,+ needs: 1, makes: 1, period: 1.2, inputCap: 4, outputCap: 3, flag: false+ },+ plant: {+ id: "plant", title: "Plant", blurb: "two crates in, two out, slowly",+ half: 18, stories: 2, bays: 3, window: 6,+ needs: 2, makes: 2, period: 2.6, inputCap: 6, outputCap: 4, flag: false+ },+ depot: {+ id: "depot", title: "Depot", blurb: "ships crates out of the yard",+ half: 14, stories: 1, bays: 2, window: 6,+ needs: 1, makes: 0, period: 0.45, inputCap: 4, outputCap: 0, flag: true+ }+}++/** How far a kind's walls stand in from the edge of its footprint, in cells. */+export const insetOf = (kind: Kind): number => 1.5 - kind.half / 16++export const kindOrder: ReadonlyArray<KindId> = ["source", "workshop", "plant", "depot"]++/** Names handed out in placing order, like packages in a repository. */+export const names = [+ "tokens", "shared", "ui", "db", "lib", "email", "auth", "payments", "components",+ "routes", "pages", "src", "api", "hooks", "store", "config", "core", "assets", "i18n", "utils"+] as const++/** Awning (and crate label) colours, handed out in placing order. */+export const awnings = [0x8a58a8, 0x3d6db5, 0x6e8f36, 0xc4523f, 0x2f8c87, 0xd6ae2e, 0x5a6479, 0xd27a34] as const++export const nameFor = (index: number): string => {+ const base = names[index % names.length] ?? "pkg"+ const round = Math.floor(index / names.length)+ return round === 0 ? base : `${base}-${round + 1}`+}++export const awningFor = (index: number): number => awnings[index % awnings.length] ?? 0x5a6479diff --git a/src/main.ts b/src/main.tsnew file mode 100644index 0000000..85c01db--- /dev/null+++ b/src/main.ts@@ -0,0 +1,42 @@+/**+ * An isometric yard of line-drawn factories joined by conveyor belts, on+ * the bevy-ts ECS with Pixi drawing it.+ */+import { PixiNodeRegistry } from "@typeonce/bevy-ts-pixi"++import type { BeltView, CrateView, FactoryView } from "./art.ts"+import { createHost } from "./host.ts"+import { BeltNodes, Clock, CrateNodes, FactoryNodes, Game, StageService, Ui } from "./schema.ts"+import { setup, update } from "./systems.ts"++const start = async () => {+ const mount = document.getElementById("app")!+ const { app, stage, ui, syncPage } = await createHost(mount)+ const clock = { deltaSeconds: 1 / 60 }++ const runtime = Game.Runtime.make({+ services: Game.Runtime.services(+ Game.Runtime.service(Ui, ui),+ Game.Runtime.service(Clock, clock),+ Game.Runtime.service(StageService, stage),+ Game.Runtime.service(FactoryNodes, PixiNodeRegistry.make<FactoryView>(stage.objects)),+ Game.Runtime.service(BeltNodes, PixiNodeRegistry.make<BeltView>(stage.belts)),+ Game.Runtime.service(CrateNodes, PixiNodeRegistry.make<CrateView>(stage.objects))+ ),+ resources: {+ DeltaTime: 0,+ Elapsed: 0,+ Counters: { nextId: 1, placed: 0 },+ Totals: { shipped: 0 },+ Flow: {}+ }+ })+ runtime.tick(setup)+ app.ticker.add((ticker) => {+ clock.deltaSeconds = Math.min(ticker.deltaMS / 1000, 0.05)+ runtime.tick(update)+ syncPage()+ })+}++void start()diff --git a/src/route.ts b/src/route.tsnew file mode 100644index 0000000..26690b1--- /dev/null+++ b/src/route.ts@@ -0,0 +1,228 @@+/**+ * Belt routing on the grid: the cheapest path of cells between two+ * factories, going straight where it can. Belts may cross other belts at a+ * right angle, never run along one, and turn only on a free cell.+ */+import { FOOTPRINT, GRID, inside, type Point } from "./iso.ts"++/** +x, +y, -x, -y. */+export type Dir = 0 | 1 | 2 | 3+const DX = [1, 0, -1, 0] as const+const DY = [0, 1, 0, -1] as const+const opposite = (dir: Dir): Dir => ((dir + 2) % 4) as Dir+const axisOf = (dir: Dir): "h" | "v" => (dir % 2 === 0 ? "h" : "v")++/** What the belts already on a cell use of it. */+export interface Usage {+ h: boolean+ v: boolean+ turn: boolean+}++/** A factory's footprint (see `FOOTPRINT`), by its top cell. */+export interface Footprint {+ readonly x: number+ readonly y: number+}++export interface Yard {+ /** A factory stands on the cell. */+ readonly blocked: (x: number, y: number) => boolean+ readonly usage: (x: number, y: number) => Usage | undefined+}++export interface Route {+ /** The cells the belt covers, in order. */+ readonly cells: ReadonlyArray<Point>+ /** How the belt uses each cell (see `Usage`). */+ readonly uses: ReadonlyArray<"h" | "v" | "turn">+ /** The belt's centre line: from the source's wall, through each turn, to the target's wall. */+ readonly points: ReadonlyArray<Point>+}++export const key = (x: number, y: number): number => y * GRID + x++/**+ * A factory's ports: the cell just outside the middle of each side, with the+ * direction pointing away from it. A belt meets the wall there, on its door.+ */+export const sideCells = (fp: Footprint): ReadonlyArray<{ readonly x: number; readonly y: number; readonly dir: Dir }> => {+ const mid = (FOOTPRINT - 1) / 2+ return [+ { x: fp.x + FOOTPRINT, y: fp.y + mid, dir: 0 },+ { x: fp.x + mid, y: fp.y + FOOTPRINT, dir: 1 },+ { x: fp.x - 1, y: fp.y + mid, dir: 2 },+ { x: fp.x + mid, y: fp.y - 1, dir: 3 }+ ]+}++const STEP = 1+const TURN = 1.6+const CROSS = 2.5++/** Whether a belt may enter a cell going `into` and leave it going `out`. */+const fits = (yard: Yard, x: number, y: number, into: Dir, out: Dir): boolean => {+ const usage = yard.usage(x, y)+ if (usage === undefined) return true+ if (into !== out) return false+ return !usage.turn && !usage[axisOf(into)]+}++/** A binary heap of state indices by cost. */+class Heap {+ private readonly items: Array<{ cost: number; state: number }> = []+ get size() {+ return this.items.length+ }+ push(cost: number, state: number) {+ const items = this.items+ items.push({ cost, state })+ let i = items.length - 1+ while (i > 0) {+ const parent = (i - 1) >> 1+ if (items[parent]!.cost <= items[i]!.cost) break+ ;[items[parent], items[i]] = [items[i]!, items[parent]!]+ i = parent+ }+ }+ pop() {+ const items = this.items+ const top = items[0]!+ const last = items.pop()!+ if (items.length > 0) {+ items[0] = last+ let i = 0+ for (;;) {+ const l = i * 2 + 1+ const r = l + 1+ let m = i+ if (l < items.length && items[l]!.cost < items[m]!.cost) m = l+ if (r < items.length && items[r]!.cost < items[m]!.cost) m = r+ if (m === i) break+ ;[items[m], items[i]] = [items[i]!, items[m]!]+ i = m+ }+ }+ return top+ }+}++/**+ * The cheapest belt from `from`'s walls to `to`'s walls, or to the free cell+ * `to` (a belt being dragged), or `null` when there is none.+ */+export const route = (yard: Yard, from: Footprint, to: Footprint | { readonly cell: Point }): Route | null => {+ const states = GRID * GRID * 4+ const GOAL = states+ const cost = new Float64Array(states + 1).fill(Infinity)+ const previous = new Int32Array(states + 1).fill(-1)+ const heap = new Heap()+ const stateOf = (x: number, y: number, dir: Dir) => key(x, y) * 4 + dir++ const free = (x: number, y: number) => inside(x, y) && !yard.blocked(x, y)++ // Where the belt may end: a cell beside the target and the direction into it.+ const goals = new Map<number, Dir>()+ if ("cell" in to) {+ if (!free(to.cell.x, to.cell.y)) return null+ } else {+ for (const side of sideCells(to)) if (free(side.x, side.y)) goals.set(key(side.x, side.y), opposite(side.dir))+ }+ const isGoal = (x: number, y: number) => ("cell" in to ? x === to.cell.x && y === to.cell.y : goals.has(key(x, y)))++ for (const side of sideCells(from)) {+ if (!free(side.x, side.y)) continue+ const state = stateOf(side.x, side.y, side.dir)+ cost[state] = 0+ heap.push(0, state)+ }++ while (heap.size > 0) {+ const { cost: at, state } = heap.pop()+ if (state === GOAL) break+ if (at > cost[state]!) continue+ const into = (state % 4) as Dir+ const cell = Math.floor(state / 4)+ const x = cell % GRID+ const y = Math.floor(cell / GRID)++ if (isGoal(x, y)) {+ const out = "cell" in to ? into : goals.get(key(x, y))!+ if (fits(yard, x, y, into, out)) {+ const total = at + (out === into ? 0 : TURN)+ if (total < cost[GOAL]!) {+ cost[GOAL] = total+ previous[GOAL] = state+ heap.push(total, GOAL)+ }+ }+ }++ for (const out of [0, 1, 2, 3] as const) {+ if (out === opposite(into)) continue+ if (!fits(yard, x, y, into, out)) continue+ const nx = x + DX[out]+ const ny = y + DY[out]+ if (!free(nx, ny)) continue+ const next = stateOf(nx, ny, out)+ const total = at + STEP + (out === into ? 0 : TURN) + (yard.usage(nx, ny) ? CROSS : 0)+ if (total < cost[next]!) {+ cost[next] = total+ previous[next] = state+ heap.push(total, next)+ }+ }+ }++ if (previous[GOAL] === -1) return null++ // Walk back from the goal: cells and the direction each was entered by.+ const trail: Array<{ x: number; y: number; dir: Dir }> = []+ for (let state = previous[GOAL]!; state !== -1; state = previous[state]!) {+ const cell = Math.floor(state / 4)+ trail.push({ x: cell % GRID, y: Math.floor(cell / GRID), dir: (state % 4) as Dir })+ }+ trail.reverse()+ const last = trail[trail.length - 1]!+ const exit: Dir = "cell" in to ? last.dir : goals.get(key(last.x, last.y))!++ const cells = trail.map(({ x, y }) => ({ x, y }))+ const uses = trail.map((step, i) => {+ const out = i + 1 < trail.length ? trail[i + 1]!.dir : exit+ return step.dir === out ? axisOf(out) : ("turn" as const)+ })++ const first = trail[0]!+ const points: Array<Point> = [{ x: first.x + 0.5 - DX[first.dir] * 0.5, y: first.y + 0.5 - DY[first.dir] * 0.5 }]+ trail.forEach((step, i) => {+ if (uses[i] === "turn") points.push({ x: step.x + 0.5, y: step.y + 0.5 })+ })+ points.push(+ "cell" in to+ ? { x: last.x + 0.5, y: last.y + 0.5 }+ : { x: last.x + 0.5 + DX[exit] * 0.5, y: last.y + 0.5 + DY[exit] * 0.5 }+ )+ return { cells, uses, points }+}++/** A polyline's length and the point at a distance along it. */+export const lengthOf = (points: ReadonlyArray<Point>): number => {+ let total = 0+ for (let i = 1; i < points.length; i++) total += Math.hypot(points[i]!.x - points[i - 1]!.x, points[i]!.y - points[i - 1]!.y)+ return total+}++export const pointAt = (points: ReadonlyArray<Point>, distance: number): Point => {+ let left = distance+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1]!+ const b = points[i]!+ const span = Math.hypot(b.x - a.x, b.y - a.y)+ if (left <= span || i === points.length - 1) {+ const t = span === 0 ? 0 : Math.min(1, Math.max(0, left / span))+ return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }+ }+ left -= span+ }+ return points[0] ?? { x: 0, y: 0 }+}diff --git a/src/schema.ts b/src/schema.tsnew file mode 100644index 0000000..b2bd48c--- /dev/null+++ b/src/schema.ts@@ -0,0 +1,173 @@+/** The factory yard's world: what is placed, what it is doing, and what moves. */+import { Descriptor, Schema } from "@typeonce/bevy-ts"+import type { NodeRegistry } from "@typeonce/bevy-ts-render"++import type { Point } from "./iso.ts"+import type { KindId } from "./kinds.ts"+import type { BeltView, CrateView, FactoryView, Stage } from "./art.ts"++export type Status = "building" | "idle" | "working" | "starved" | "blocked"++/** A placed factory: its own id (belts refer to it), kind, and 2×2 footprint by its top cell. */+export interface FactoryValue {+ readonly id: number+ readonly kind: KindId+ readonly name: string+ readonly color: number+ readonly x: number+ readonly y: number+}++/** What a factory is doing, and the numbers its animation follows. */+export interface WorkValue {+ readonly status: Status+ /** 0 → 1 while it rises from its plate. */+ readonly built: number+ /** 0 → 1 through the current job (0: no job). */+ readonly progress: number+ readonly inputs: number+ readonly outputs: number+ /** Crates a depot has shipped out of the yard. */+ readonly shipped: number+ /** Jobs finished. */+ readonly made: number+ /** Next outgoing belt to try. */+ readonly turn: number+ /** 1 when a job finishes, fading to 0: the building's bounce. */+ readonly pulse: number+}++/** A conveyor between two factories. */+export interface BeltValue {+ readonly id: number+ readonly from: number+ readonly to: number+ readonly cells: ReadonlyArray<Point>+ readonly uses: ReadonlyArray<"h" | "v" | "turn">+ readonly points: ReadonlyArray<Point>+ readonly length: number+}++/** A crate riding a belt: how far along it, and where that is on the grid. */+export interface CrateValue {+ readonly belt: number+ readonly distance: number+ readonly color: number+ readonly x: number+ readonly y: number+}++export type Mode = "select" | "bulldoze"++/** What the player did since the last tick, in world pixels. */+export type Intent =+ | { readonly type: "press"; readonly at: Point }+ | { readonly type: "release"; readonly at: Point; readonly panned: boolean }+ | { readonly type: "place"; readonly kind: KindId; readonly cell: Point }+ /** Builds on the picked plot (see `UiValue.plot`), and opens the new factory. */+ | { readonly type: "build"; readonly kind: KindId }+ | { readonly type: "remove"; readonly factory: number }+ /** Connects the factories standing on two cells. */+ | { readonly type: "link"; readonly from: Point; readonly to: Point }+ | { readonly type: "clear" }++/** What the yard shows besides its entities: the ghost, the belt being dragged, and what is in focus. */+export interface Preview {+ ghost: { readonly kind: KindId; readonly cell: Point; readonly valid: boolean } | null+ /** Plots outlined on the floor: under the pointer, or picked. */+ plots: Array<{ readonly x: number; readonly y: number; readonly look: "hover" | "picked" | "blocked" }>+ path: { readonly points: ReadonlyArray<Point>; readonly valid: boolean } | null+ hoverFactory: number | null+ hoverBelt: number | null+ /** Factories and belts in focus (the rest fade), or `null` for all. */+ focus: { readonly factories: ReadonlySet<number>; readonly belts: ReadonlySet<number> } | null+ danger: boolean+ tooltip: string | null+}++/** A factory a panel lists, with where it stands (world pixels) to look at it. */+export interface PanelLink {+ readonly id: number+ readonly name: string+ readonly kind: KindId+ readonly crates: number+}++/** The side panel: a picked plot and what can be built on it, or a factory and its belts. */+export type Panel =+ | {+ readonly type: "plot"+ readonly x: number+ readonly y: number+ readonly free: boolean+ readonly reason: string+ }+ | {+ readonly type: "factory"+ readonly id: number+ readonly name: string+ readonly kind: KindId+ readonly status: Status+ readonly inputs: number+ readonly outputs: number+ readonly made: number+ readonly takes: ReadonlyArray<PanelLink>+ readonly feeds: ReadonlyArray<PanelLink>+ readonly linking: boolean+ }++/** A factory's hit area for the pointer, written by the yard each tick. */+export interface HitBox {+ readonly id: number+ readonly depth: number+ readonly contains: (at: Point) => boolean+}++/** The bridge between the page and the yard: the host writes input, the yard writes the preview. */+export interface UiValue {+ mode: Mode+ /** The plot picked for building (its top cell), and the kind the panel is pointing at. */+ plot: Point | null+ plotKind: KindId | null+ /** A factory whose next belt the player is placing by tapping its target. */+ linkFrom: number | null+ /** The pointer in world pixels, or `null` off the canvas. */+ pointer: Point | null+ dragFrom: number | null+ selected: number | null+ intents: Array<Intent>+ preview: Preview+ hits: ReadonlyArray<HitBox>+ panel: Panel | null+ /** Where each factory stands (world pixels), for the camera to look at. */+ centres: ReadonlyMap<number, Point>+ stats: { readonly factories: number; readonly belts: number; readonly crates: number; readonly shipped: number }+ toast: (message: string) => void+}++export const Factory = Descriptor.Component<FactoryValue>()("Factory/Factory")+export const Work = Descriptor.Component<WorkValue>()("Factory/Work")+export const Belt = Descriptor.Component<BeltValue>()("Factory/Belt")+export const Crate = Descriptor.Component<CrateValue>()("Factory/Crate")++export const DeltaTime = Descriptor.Resource<number>()("Factory/DeltaTime")+export const Elapsed = Descriptor.Resource<number>()("Factory/Elapsed")+/** Ids for factories and belts, and how many factories were ever placed (for names and colours). */+export const Counters = Descriptor.Resource<{ readonly nextId: number; readonly placed: number }>()("Factory/Counters")+export const Totals = Descriptor.Resource<{ readonly shipped: number }>()("Factory/Totals")+/** Crates each belt has delivered, by belt id. */+export const Flow = Descriptor.Resource<Readonly<Record<number, number>>>()("Factory/Flow")++export const Ui = Descriptor.Service<UiValue>()("Factory/Ui")+export const Clock = Descriptor.Service<{ deltaSeconds: number }>()("Factory/Clock")+export const StageService = Descriptor.Service<Stage>()("Factory/Stage")+export const FactoryNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FactoryView>>()("Factory/FactoryNodes")+export const BeltNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BeltView>>()("Factory/BeltNodes")+export const CrateNodes = Descriptor.Service<NodeRegistry.NodeRegistry<CrateView>>()("Factory/CrateNodes")++export const Game = Schema.bind(+ Schema.fragment({+ components: { Factory, Work, Belt, Crate },+ resources: { DeltaTime, Elapsed, Counters, Totals, Flow }+ })+)diff --git a/src/systems.ts b/src/systems.tsnew file mode 100644index 0000000..1721fa2--- /dev/null+++ b/src/systems.ts@@ -0,0 +1,675 @@+/**+ * The yard's systems: the player's intents become factories and belts,+ * factories work through their jobs, crates ride the belts, and the views+ * follow.+ */+import { RenderSync } from "@typeonce/bevy-ts-render"++import { BELT_SPEED, BeltView, CrateView, drawBeltBase, drawBeltHatch, drawBeltRails, drawBuilding, drawPlate, drawPlot, FactoryView, heightOf } from "./art.ts"+import { FOOTPRINT, TILE_H, TILE_W, U, inside, toGrid, toScreen, type Point } from "./iso.ts"+import { kinds, insetOf, nameFor, awningFor, type KindId } from "./kinds.ts"+import { key, lengthOf, pointAt, route, type Usage, type Yard } from "./route.ts"+import {+ Belt, BeltNodes, Clock, Counters, Crate, CrateNodes, DeltaTime, Elapsed, Factory, FactoryNodes, Game,+ Flow, StageService, Totals, Ui, Work+} from "./schema.ts"+import type { BeltValue, FactoryValue, HitBox, Preview, WorkValue } from "./schema.ts"++/** Closest two crates may ride on a belt, in grid cells. */+const SPACING = 7 * U+const BUILD_SECONDS = 2.4++const FactoryRead = Game.Query({ selection: { factory: Game.Query.read(Factory), work: Game.Query.read(Work) } })+const FactoryWrite = Game.Query({ selection: { factory: Game.Query.read(Factory), work: Game.Query.write(Work) } })+const BeltRead = Game.Query({ selection: { belt: Game.Query.read(Belt) } })+const CrateRead = Game.Query({ selection: { crate: Game.Query.read(Crate) } })+const CrateWrite = Game.Query({ selection: { crate: Game.Query.write(Crate) } })++export const AdvanceClock = Game.System(+ "Factory/AdvanceClock",+ {+ resources: { dt: Game.System.writeResource(DeltaTime), elapsed: Game.System.writeResource(Elapsed) },+ services: { clock: Game.System.service(Clock) }+ },+ ({ resources, services }) => {+ resources.dt.set(services.clock.deltaSeconds)+ resources.elapsed.update((t) => t + services.clock.deltaSeconds)+ }+)++// ── Placing and connecting ────────────────────────────────────────────────++/** Moves a belt's ends from the plates' edges in to the buildings' walls. */+const toWalls = (points: ReadonlyArray<Point>, fromInset: number, toInset: number | null): Array<Point> => {+ const out = points.map((p) => ({ x: p.x, y: p.y }))+ const reach = (end: { x: number; y: number }, next: Point, inset: number) => {+ const length = Math.hypot(end.x - next.x, end.y - next.y) || 1+ end.x += ((end.x - next.x) / length) * inset+ end.y += ((end.y - next.y) / length) * inset+ }+ if (out.length >= 2) {+ reach(out[0]!, out[1]!, fromInset)+ if (toInset !== null) reach(out[out.length - 1]!, out[out.length - 2]!, toInset)+ }+ return out+}++interface Placed {+ readonly id: number+ readonly kind: KindId+ readonly x: number+ readonly y: number+}++/** What stands where, kept up to date while one tick's intents are applied. */+class Occupancy implements Yard {+ readonly factories = new Map<number, Placed>()+ readonly cells = new Map<number, number>()+ readonly uses = new Map<number, Usage>()+ readonly beltCells = new Map<number, Array<number>>()+ readonly belts = new Map<number, BeltValue>()++ addFactory(f: Placed) {+ this.factories.set(f.id, f)+ for (let dx = 0; dx < FOOTPRINT; dx++) for (let dy = 0; dy < FOOTPRINT; dy++) this.cells.set(key(f.x + dx, f.y + dy), f.id)+ }++ addBelt(b: BeltValue) {+ this.belts.set(b.id, b)+ b.cells.forEach((c, i) => {+ const k = key(c.x, c.y)+ const u = this.uses.get(k) ?? { h: false, v: false, turn: false }+ const use = b.uses[i]!+ if (use === "turn") u.turn = true+ else u[use] = true+ this.uses.set(k, u)+ this.beltCells.set(k, [...(this.beltCells.get(k) ?? []), b.id])+ })+ }++ blocked = (x: number, y: number) => this.cells.has(key(x, y))+ usage = (x: number, y: number) => this.uses.get(key(x, y))++ canPlace(x: number, y: number) {+ for (let dx = 0; dx < FOOTPRINT; dx++) {+ for (let dy = 0; dy < FOOTPRINT; dy++) {+ const cx = x + dx+ const cy = y + dy+ if (!inside(cx, cy) || this.cells.has(key(cx, cy)) || this.uses.has(key(cx, cy))) return false+ }+ }+ return true+ }+}++/** A building's hit area: its plate, or its walls and roof as drawn. */+const hitBox = (f: FactoryValue): HitBox => {+ const kind = kinds[f.kind]+ const centre = toScreen(f.x + FOOTPRINT / 2, f.y + FOOTPRINT / 2)+ const a = kind.half * U+ const top = centre.y - a * TILE_H - heightOf(kind) - 26+ return {+ id: f.id,+ depth: f.x + f.y + FOOTPRINT,+ contains: (at) => {+ const g = toGrid(at.x, at.y)+ if (g.x >= f.x && g.x <= f.x + FOOTPRINT && g.y >= f.y && g.y <= f.y + FOOTPRINT) return true+ return Math.abs(at.x - centre.x) <= a * TILE_W && at.y >= top && at.y <= centre.y+ }+ }+}++const factoryAt = (hits: ReadonlyArray<HitBox>, at: Point): number | null => hits.find((h) => h.contains(at))?.id ?? null++/** The footprint centred on a point, by its top cell. */+const footprintAt = (at: Point): Point => {+ const g = toGrid(at.x, at.y)+ return { x: Math.floor(g.x - (FOOTPRINT - 1) / 2), y: Math.floor(g.y - (FOOTPRINT - 1) / 2) }+}++const cellAt = (at: Point): Point => {+ const g = toGrid(at.x, at.y)+ return { x: Math.floor(g.x), y: Math.floor(g.y) }+}++const emptyPreview = (): Preview => ({ ghost: null, plots: [], path: null, hoverFactory: null, hoverBelt: null, focus: null, danger: false, tooltip: null })++export const Interact = Game.System(+ "Factory/Interact",+ {+ queries: { factories: FactoryRead, belts: BeltRead, crates: CrateRead },+ resources: { counters: Game.System.writeResource(Counters), totals: Game.System.readResource(Totals), flow: Game.System.readResource(Flow) },+ services: { ui: Game.System.service(Ui) }+ },+ ({ queries, resources, services, commands }) => {+ const ui = services.ui+ let yard = new Occupancy()+ const entities = { factories: new Map<number, unknown>(), belts: new Map<number, unknown>() }+ const works = new Map<number, WorkValue>()+ const names = new Map<number, FactoryValue>()+ for (const { entity, data } of queries.factories.each()) {+ const f = data.factory.get()+ yard.addFactory(f)+ entities.factories.set(f.id, entity.id)+ works.set(f.id, data.work.get())+ names.set(f.id, f)+ }+ for (const { entity, data } of queries.belts.each()) {+ const b = data.belt.get()+ yard.addBelt(b)+ entities.belts.set(b.id, entity.id)+ }+ let hits: Array<HitBox> = [...names.values()].map(hitBox).sort((l, r) => r.depth - l.depth)++ const despawnBelt = (id: number) => {+ const entity = entities.belts.get(id)+ if (entity === undefined) return+ commands.despawn(entity as never)+ for (const crate of queries.crates.each()) if (crate.data.crate.get().belt === id) commands.despawn(crate.entity.id)+ entities.belts.delete(id)+ }++ const removeFactory = (factory: number) => {+ const entity = entities.factories.get(factory)+ if (entity !== undefined) commands.despawn(entity as never)+ for (const b of yard.belts.values()) if (b.from === factory || b.to === factory) despawnBelt(b.id)+ if (ui.selected === factory) ui.selected = null+ }++ const remove = (at: Point) => {+ const factory = factoryAt(hits, at)+ if (factory !== null) return removeFactory(factory)+ const cell = cellAt(at)+ const belt = inside(cell.x, cell.y) ? yard.beltCells.get(key(cell.x, cell.y))?.at(-1) : undefined+ if (belt !== undefined) despawnBelt(belt)+ }++ /** Places a factory, returning its id (or `null` when there is no room). */+ const place = (kind: KindId, cell: Point): number | null => {+ if (!yard.canPlace(cell.x, cell.y)) {+ ui.toast("No room there")+ return null+ }+ const { nextId, placed } = resources.counters.get()+ const factory: FactoryValue = { id: nextId, kind, name: nameFor(placed), color: awningFor(placed), x: cell.x, y: cell.y }+ const work: WorkValue = { status: "building", built: 0, progress: 0, inputs: 0, outputs: 0, shipped: 0, made: 0, turn: 0, pulse: 0 }+ commands.spawn(Game.Command.spawn([Factory, factory], [Work, work]))+ resources.counters.set({ nextId: nextId + 1, placed: placed + 1 })+ yard.addFactory(factory)+ names.set(factory.id, factory)+ works.set(factory.id, work)+ hits = [...names.values()].map(hitBox).sort((l, r) => r.depth - l.depth)+ return factory.id+ }++ const connect = (fromId: number, toId: number) => {+ const from = yard.factories.get(fromId)+ const to = yard.factories.get(toId)+ if (!from || !to || fromId === toId) return+ if (kinds[from.kind].makes === 0) return ui.toast("A depot only takes crates in")+ if (kinds[to.kind].needs === 0) return ui.toast("A source takes nothing in")+ for (const b of yard.belts.values()) if (b.from === fromId && b.to === toId) return ui.toast("Already connected")+ const found = route(yard, from, to)+ if (!found) return ui.toast("No room for a belt")+ const { nextId } = resources.counters.get()+ const points = toWalls(found.points, insetOf(kinds[from.kind]), insetOf(kinds[to.kind]))+ const belt: BeltValue = { id: nextId, from: fromId, to: toId, cells: found.cells, uses: found.uses, points, length: lengthOf(points) }+ commands.spawn(Game.Command.spawn([Belt, belt]))+ resources.counters.update((c) => ({ ...c, nextId: c.nextId + 1 }))+ yard.addBelt(belt)+ }++ /** A plot's top cell lies wholly inside the yard. */+ const onYard = (cell: Point) => inside(cell.x, cell.y) && inside(cell.x + FOOTPRINT - 1, cell.y + FOOTPRINT - 1)++ for (const intent of ui.intents.splice(0)) {+ switch (intent.type) {+ case "place":+ place(intent.kind, intent.cell)+ break+ case "build": {+ if (!ui.plot) break+ const id = place(intent.kind, ui.plot)+ if (id !== null) {+ ui.plot = null+ ui.plotKind = null+ ui.selected = id+ }+ break+ }+ case "remove":+ removeFactory(intent.factory)+ break+ case "link": {+ const at = (cell: Point) => yard.cells.get(key(cell.x, cell.y))+ const from = at(intent.from)+ const to = at(intent.to)+ if (from !== undefined && to !== undefined) connect(from, to)+ break+ }+ case "clear":+ for (const entity of entities.factories.values()) commands.despawn(entity as never)+ for (const id of [...entities.belts.keys()]) despawnBelt(id)+ for (const crate of queries.crates.each()) commands.despawn(crate.entity.id)+ resources.counters.update((c) => ({ ...c, placed: 0 }))+ yard = new Occupancy()+ names.clear()+ hits = []+ ui.selected = null+ ui.dragFrom = null+ ui.linkFrom = null+ ui.plot = null+ break+ case "press":+ ui.dragFrom = ui.mode === "select" && ui.linkFrom === null ? factoryAt(hits, intent.at) : null+ break+ case "release": {+ if (ui.mode === "bulldoze") {+ if (!intent.panned) remove(intent.at)+ break+ }+ const target = factoryAt(hits, intent.at)+ if (ui.dragFrom !== null && target !== null && target !== ui.dragFrom) {+ // Dragged from one factory to another: a belt between them.+ connect(ui.dragFrom, target)+ ui.selected = ui.dragFrom+ ui.plot = null+ } else if (ui.linkFrom !== null) {+ if (!intent.panned) {+ if (target !== null && target !== ui.linkFrom) connect(ui.linkFrom, target)+ ui.linkFrom = null+ }+ } else if (target !== null && target === ui.dragFrom) {+ ui.selected = target+ ui.plot = null+ } else if (!intent.panned) {+ // A tap on the ground picks the plot there (or closes the panel off the yard).+ const cell = footprintAt(intent.at)+ ui.selected = null+ ui.plot = onYard(cell) ? cell : null+ ui.plotKind = null+ }+ ui.dragFrom = null+ break+ }+ }+ }+ if (ui.selected !== null && !yard.factories.has(ui.selected)) ui.selected = null+ if (ui.linkFrom !== null && !yard.factories.has(ui.linkFrom)) ui.linkFrom = null++ // What the pointer is over, and what that brings into focus.+ ui.hits = hits+ const preview = emptyPreview()+ const pointer = ui.pointer+ if (pointer) {+ preview.hoverFactory = factoryAt(hits, pointer)+ const cell = cellAt(pointer)+ preview.hoverBelt = preview.hoverFactory === null && inside(cell.x, cell.y) ? yard.beltCells.get(key(cell.x, cell.y))?.at(-1) ?? null : null+ }++ const around = (id: number) => {+ const factories = new Set([id])+ const belts = new Set<number>()+ for (const b of yard.belts.values()) {+ if (b.from === id || b.to === id) {+ belts.add(b.id)+ factories.add(b.from)+ factories.add(b.to)+ }+ }+ return { factories, belts }+ }++ if (ui.plot) {+ const free = yard.canPlace(ui.plot.x, ui.plot.y)+ preview.plots.push({ ...ui.plot, look: free ? "picked" : "blocked" })+ if (ui.plotKind) preview.ghost = { kind: ui.plotKind, cell: ui.plot, valid: free }+ }++ if (ui.mode === "bulldoze") {+ preview.danger = true+ if (preview.hoverFactory !== null) preview.focus = around(preview.hoverFactory)+ else if (preview.hoverBelt !== null) {+ const b = yard.belts.get(preview.hoverBelt)!+ preview.focus = { factories: new Set([b.from, b.to]), belts: new Set([b.id]) }+ }+ } else {+ const from = ui.dragFrom ?? ui.linkFrom+ const source = from !== null ? yard.factories.get(from) : undefined+ if (source && pointer && preview.hoverFactory !== from) {+ const target = preview.hoverFactory !== null ? yard.factories.get(preview.hoverFactory) : undefined+ const cell = cellAt(pointer)+ const found = target ? route(yard, source, target) : inside(cell.x, cell.y) ? route(yard, source, { cell }) : null+ const allowed = target !== undefined && kinds[source.kind].makes > 0 && kinds[target.kind].needs > 0+ if (found) {+ preview.path = {+ points: toWalls(found.points, insetOf(kinds[source.kind]), target ? insetOf(kinds[target.kind]) : null),+ valid: allowed+ }+ }+ }+ // The plot under the pointer, when a tap there would pick it.+ if (pointer && from === null && preview.hoverFactory === null) {+ const cell = footprintAt(pointer)+ const picked = ui.plot && ui.plot.x === cell.x && ui.plot.y === cell.y+ if (onYard(cell) && !picked) preview.plots.unshift({ ...cell, look: "hover" })+ }+ const focusOn = from ?? preview.hoverFactory ?? ui.selected+ if (focusOn !== null) {+ const focus = around(focusOn)+ if (preview.hoverFactory !== null) focus.factories.add(preview.hoverFactory)+ preview.focus = focus+ }+ }++ const shown = preview.hoverFactory+ const f = shown !== null ? names.get(shown) : undefined+ const w = shown !== null ? works.get(shown) : undefined+ if (f && w) {+ const kind = kinds[f.kind]+ const stock = kind.makes === 0 ? `${w.shipped} shipped` : kind.needs === 0 ? `${w.outputs} ready` : `${w.inputs} in · ${w.outputs} out`+ preview.tooltip = `${kind.title.toLowerCase()}/${f.name} ${w.status} · ${stock}`+ } else if (preview.hoverBelt !== null) {+ const b = yard.belts.get(preview.hoverBelt)!+ preview.tooltip = `belt ${names.get(b.from)?.name ?? "?"} → ${names.get(b.to)?.name ?? "?"} ${resources.flow.get()[b.id] ?? 0} crates`+ }+ ui.preview = preview++ // The side panel: the picked factory, or the picked plot.+ const flow = resources.flow.get()+ const link = (id: number, belt: number) => {+ const other = names.get(id)!+ return { id, name: other.name, kind: other.kind, crates: flow[belt] ?? 0 }+ }+ const picked = ui.selected !== null ? names.get(ui.selected) : undefined+ const pickedWork = ui.selected !== null ? works.get(ui.selected) : undefined+ if (picked && pickedWork) {+ const belts = [...yard.belts.values()]+ ui.panel = {+ type: "factory",+ id: picked.id,+ name: picked.name,+ kind: picked.kind,+ status: pickedWork.status,+ inputs: pickedWork.inputs,+ outputs: pickedWork.outputs,+ made: picked.kind === "depot" ? pickedWork.shipped : pickedWork.made,+ takes: belts.filter((b) => b.to === picked.id).map((b) => link(b.from, b.id)),+ feeds: belts.filter((b) => b.from === picked.id).map((b) => link(b.to, b.id)),+ linking: ui.linkFrom === picked.id+ }+ } else if (ui.plot) {+ const { x, y } = ui.plot+ let reason = `${FOOTPRINT} × ${FOOTPRINT} cells, free to build on`+ for (let dx = 0; dx < FOOTPRINT; dx++) {+ for (let dy = 0; dy < FOOTPRINT; dy++) {+ if (yard.cells.has(key(x + dx, y + dy))) reason = "a factory stands here"+ else if (yard.uses.has(key(x + dx, y + dy)) && reason.endsWith("on")) reason = "a belt runs across it"+ }+ }+ ui.panel = { type: "plot", x, y, free: yard.canPlace(x, y), reason }+ } else ui.panel = null++ const centres = new Map<number, Point>()+ for (const f of names.values()) centres.set(f.id, toScreen(f.x + FOOTPRINT / 2, f.y + FOOTPRINT / 2))+ ui.centres = centres++ let crates = 0+ for (const _ of queries.crates.each()) crates+++ ui.stats = { factories: yard.factories.size, belts: yard.belts.size, crates, shipped: resources.totals.get().shipped }+ }+)++// ── Work ──────────────────────────────────────────────────────────────────++export const RunFactories = Game.System(+ "Factory/RunFactories",+ {+ queries: { factories: FactoryWrite, belts: BeltRead, crates: CrateRead },+ resources: { dt: Game.System.readResource(DeltaTime), totals: Game.System.writeResource(Totals) }+ },+ ({ queries, resources, commands }) => {+ const dt = resources.dt.get()+ const outgoing = new Map<number, Array<BeltValue>>()+ const incoming = new Set<number>()+ for (const { data } of queries.belts.each()) {+ const b = data.belt.get()+ outgoing.set(b.from, [...(outgoing.get(b.from) ?? []), b])+ incoming.add(b.to)+ }+ // A belt takes a new crate once the last one has moved off its start.+ const nearest = new Map<number, number>()+ for (const { data } of queries.crates.each()) {+ const c = data.crate.get()+ nearest.set(c.belt, Math.min(nearest.get(c.belt) ?? Infinity, c.distance))+ }++ for (const { data } of queries.factories.each()) {+ const f = data.factory.get()+ const kind = kinds[f.kind]+ const w = { ...data.work.get() }+ w.pulse = Math.max(0, w.pulse - dt * 3)+ if (w.built < 1) {+ w.built = Math.min(1, w.built + dt / BUILD_SECONDS)+ w.status = "building"+ data.work.set(w)+ continue+ }+ const outs = outgoing.get(f.id) ?? []+ const fed = incoming.has(f.id)++ if (w.progress === 0 && w.inputs >= kind.needs && w.outputs + kind.makes <= kind.outputCap && (kind.makes > 0 || w.inputs > 0)) {+ w.inputs -= kind.needs+ w.progress = 1e-6+ }+ if (w.progress > 0) {+ w.progress += dt / kind.period+ if (w.progress >= 1) {+ w.progress = 0+ w.outputs += kind.makes+ w.made += 1+ w.pulse = 1+ if (kind.makes === 0) {+ w.shipped += 1+ resources.totals.update((t) => ({ shipped: t.shipped + 1 }))+ }+ }+ }++ // Send one crate a tick down the next belt with room at its start.+ if (w.outputs > 0) {+ for (let i = 0; i < outs.length; i++) {+ const belt = outs[(w.turn + i) % outs.length]!+ if ((nearest.get(belt.id) ?? Infinity) < SPACING) continue+ const start = belt.points[0]!+ commands.spawn(Game.Command.spawn([Crate, { belt: belt.id, distance: 0, color: f.color, x: start.x, y: start.y }]))+ nearest.set(belt.id, 0)+ w.outputs -= 1+ w.turn = (w.turn + i + 1) % outs.length+ break+ }+ }++ w.status = w.progress > 0+ ? "working"+ : w.outputs + kind.makes > kind.outputCap && kind.makes > 0+ ? outs.length > 0 ? "blocked" : "idle"+ : w.inputs < Math.max(1, kind.needs)+ ? fed ? "starved" : "idle"+ : "working"+ data.work.set(w)+ }+ }+)++export const MoveCrates = Game.System(+ "Factory/MoveCrates",+ {+ queries: { crates: CrateWrite, belts: BeltRead, factories: FactoryWrite },+ resources: { dt: Game.System.readResource(DeltaTime), flow: Game.System.writeResource(Flow) }+ },+ ({ queries, resources, commands }) => {+ const step = BELT_SPEED * resources.dt.get()+ const belts = new Map<number, BeltValue>()+ for (const { data } of queries.belts.each()) belts.set(data.belt.get().id, data.belt.get())+ const targets = new Map<number, { readonly cap: number; readonly ready: boolean; inputs: number; set: (inputs: number) => void }>()+ for (const { data } of queries.factories.each()) {+ const f = data.factory.get()+ const w = data.work.get()+ targets.set(f.id, {+ cap: kinds[f.kind].inputCap,+ ready: w.built >= 1,+ inputs: w.inputs,+ set: (inputs) => data.work.set({ ...data.work.get(), inputs })+ })+ }++ const rows = [...queries.crates.each()]+ const riding = new Map<number, typeof rows>()+ for (const row of rows) {+ const belt = row.data.crate.get().belt+ if (!belts.has(belt)) commands.despawn(row.entity.id)+ else riding.set(belt, [...(riding.get(belt) ?? []), row])+ }++ for (const [id, crates] of riding) {+ const belt = belts.get(id)!+ const target = targets.get(belt.to)+ crates.sort((l, r) => r.data.crate.get().distance - l.data.crate.get().distance)+ let limit = belt.length+ for (const row of crates) {+ const c = row.data.crate.get()+ const distance = Math.max(c.distance, Math.min(c.distance + step, limit))+ // At the end of the belt, the crate goes in if the building has room.+ if (distance >= belt.length - 1e-6 && target && target.ready && target.inputs < target.cap) {+ target.inputs += 1+ target.set(target.inputs)+ resources.flow.update((flow) => ({ ...flow, [id]: (flow[id] ?? 0) + 1 }))+ commands.despawn(row.entity.id)+ continue+ }+ if (distance !== c.distance) {+ const p = pointAt(belt.points, distance)+ row.data.crate.set({ ...c, distance, x: p.x, y: p.y })+ }+ limit = distance - SPACING+ }+ }+ }+)++// ── Views ─────────────────────────────────────────────────────────────────++export const RenderFactories = RenderSync.system(Game, {+ name: "Factory/RenderFactories",+ renderable: Factory,+ registry: FactoryNodes,+ services: { stage: StageService },+ create: ({ renderable, services }) => new FactoryView(renderable.kind, renderable.name, renderable.color, services.stage),+ apply: (node, { renderable }) => node.place(renderable.x, renderable.y)+})++export const RenderBelts = RenderSync.system(Game, {+ name: "Factory/RenderBelts",+ renderable: Belt,+ registry: BeltNodes,+ create: ({ renderable }) => new BeltView(renderable.points),+ apply: () => {}+})++export const RenderCrates = RenderSync.system(Game, {+ name: "Factory/RenderCrates",+ renderable: Crate,+ transform: Crate,+ registry: CrateNodes,+ create: ({ renderable }) => new CrateView(renderable.color),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})++type Emphasis = "normal" | "dim" | "focus" | "danger"++export const Animate = Game.System(+ "Factory/Animate",+ {+ queries: { factories: FactoryRead, belts: BeltRead, crates: CrateRead },+ resources: { dt: Game.System.readResource(DeltaTime), elapsed: Game.System.readResource(Elapsed) },+ services: { ui: Game.System.service(Ui), factoryNodes: Game.System.service(FactoryNodes), beltNodes: Game.System.service(BeltNodes), crateNodes: Game.System.service(CrateNodes) }+ },+ ({ queries, resources, services }) => {+ const { focus, danger } = services.ui.preview+ const emphasis = (inFocus: boolean): Emphasis => (focus === null ? "normal" : !inFocus ? "dim" : danger ? "danger" : "focus")+ const dt = resources.dt.get()+ // A factory gets a door on its left wall when a belt meets it there (its +y side).+ const leftDoors = new Set<number>()+ const centres = new Map<number, Point>()+ for (const { data } of queries.factories.each()) {+ const f = data.factory.get()+ centres.set(f.id, { x: f.x + FOOTPRINT / 2, y: f.y + FOOTPRINT / 2 })+ }+ for (const { data } of queries.belts.each()) {+ const b = data.belt.get()+ const ends: ReadonlyArray<readonly [number, Point]> = [[b.from, b.points[0]!], [b.to, b.points[b.points.length - 1]!]]+ for (const [id, end] of ends) {+ const c = centres.get(id)+ if (c && end.y - c.y > Math.abs(end.x - c.x)) leftDoors.add(id)+ }+ }+ for (const { entity, data } of queries.factories.each()) {+ const f = data.factory.get()+ services.factoryNodes.get(entity.id as never)?.update(data.work.get(), dt, emphasis(focus?.factories.has(f.id) ?? true), leftDoors.has(f.id))+ }+ for (const { entity, data } of queries.belts.each()) {+ services.beltNodes.get(entity.id as never)?.update(resources.elapsed.get(), emphasis(focus?.belts.has(data.belt.get().id) ?? true))+ }+ for (const { entity, data } of queries.crates.each()) {+ const node = services.crateNodes.get(entity.id as never)+ if (node) node.alpha = focus === null || focus.belts.has(data.crate.get().belt) ? 1 : 0.25+ }+ }+)++/** The ghost of the building being placed, and the belt being dragged. */+export const DrawPreview = Game.System(+ "Factory/DrawPreview",+ {+ resources: { elapsed: Game.System.readResource(Elapsed) },+ services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService) }+ },+ ({ resources, services }) => {+ const { ghost, path } = services.ui.preview+ const { overlay, ghost: shadow } = services.stage+ overlay.clear()+ shadow.clear()+ for (const plot of services.ui.preview.plots) drawPlot(overlay, plot.x, plot.y, plot.look, resources.elapsed.get())+ if (ghost) {+ const kind = kinds[ghost.kind]+ const centre = toScreen(ghost.cell.x + FOOTPRINT / 2, ghost.cell.y + FOOTPRINT / 2)+ shadow.position.set(centre.x, centre.y)+ shadow.zIndex = ghost.cell.x + ghost.cell.y + FOOTPRINT+ drawBuilding(shadow, kind, 0xb9beb5, 1, 0, 0)+ shadow.alpha = ghost.valid ? 0.45 : 0.25+ shadow.tint = ghost.valid ? 0xffffff : 0xf3b5aa+ }+ if (path && path.points.length >= 2) {+ drawBeltBase(overlay, path.points, 0.7)+ drawBeltHatch(overlay, path.points, resources.elapsed.get() * BELT_SPEED, 0.6)+ drawBeltRails(overlay, path.points, path.valid ? 0.9 : 0.45, path.valid ? 0x3d4943 : 0x8f9891)+ }+ }+)++export const setup = Game.Schedule(Interact, Game.Schedule.applyDeferred(), RenderFactories, RenderBelts)++export const update = Game.Schedule(+ AdvanceClock,+ Interact,+ RunFactories,+ Game.Schedule.applyDeferred(),+ MoveCrates,+ Game.Schedule.applyDeferred(),+ RenderFactories,+ RenderBelts,+ RenderCrates,+ Animate,+ DrawPreview+)diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 0000000..77a112d--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,19 @@+{+ "include": ["src/**/*.ts", "vite.config.ts"],+ "compilerOptions": {+ "noEmit": true,+ "target": "ES2022",+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "verbatimModuleSyntax": true,+ "allowImportingTsExtensions": true,+ "erasableSyntaxOnly": true,+ "strict": true,+ "exactOptionalPropertyTypes": true,+ "noUncheckedIndexedAccess": true,+ "noImplicitOverride": true,+ "skipLibCheck": true,+ "types": ["node", "vite/client"]+ }+}diff --git a/vite.config.ts b/vite.config.tsnew file mode 100644index 0000000..ef75805--- /dev/null+++ b/vite.config.ts@@ -0,0 +1,10 @@+import { fileURLToPath } from "node:url"+import { defineConfig } from "vite"++// The bevy-ts packages are linked from the sibling repository and consumed as+// TypeScript source, so Vite must be allowed to serve files from there.+const bevyTs = fileURLToPath(new URL("../../bevy-ts", import.meta.url))++export default defineConfig({+ server: { fs: { allow: [".", bevyTs] } }+})