Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ced27d3400 | ||
|
|
90dd86b336 | ||
|
|
cbd662dc2a | ||
|
|
ed6f5fe0df | ||
|
|
25937f2c31 | ||
|
|
0d770c7bc4 | ||
|
|
a552883795 | ||
|
|
681d3afb4d | ||
|
|
527f2fb5a7 | ||
|
|
df7a1a94d6 | ||
|
|
a26d801f4e | ||
|
|
fe09e0cdd7 | ||
|
|
b9deda1a55 | ||
|
|
784bac7dd2 | ||
|
|
ac791b886e | ||
|
|
e751d22c6e | ||
|
|
dee07eaa0c | ||
|
|
c2e885f23a | ||
|
|
dfb110e0f8 | ||
|
|
8add5f852e | ||
|
|
487d5ae2a9 | ||
|
|
8a13854f39 | ||
|
|
5d374091cd | ||
|
|
d18fe19027 | ||
|
|
da44685f54 | ||
|
|
8e587f6446 | ||
|
|
47934b272c | ||
|
|
f308ab52f1 | ||
|
|
0c711b8163 | ||
|
|
69ad4b80d0 | ||
|
|
607be76ca6 | ||
|
|
4bdf5203d4 | ||
|
|
717d2cb766 | ||
|
|
94463b3cea | ||
|
|
2563ec3f69 | ||
|
|
b4f07272d8 | ||
|
|
357f8f2bd4 | ||
|
|
0f58a9cbfe | ||
|
|
dd53613758 | ||
|
|
277664d2d9 | ||
|
|
e72932456a | ||
|
|
edce5bac29 | ||
|
|
e1c2b13d1f | ||
|
|
60a7cae86e | ||
|
|
65865033c1 | ||
|
|
04c9511b6c | ||
|
|
c4eda256a1 | ||
|
|
f36176a872 | ||
|
|
c0c182490e | ||
|
|
00a679b053 | ||
|
|
38716ba8c3 | ||
|
|
6c38166325 | ||
|
|
c0c728c066 | ||
|
|
8c2364fa91 | ||
|
|
8230fe297d | ||
|
|
1b06fa29e1 | ||
|
|
188b05f598 | ||
|
|
eedaa955f6 | ||
|
|
94b0e3789c | ||
|
|
7369bf2e5f | ||
|
|
5301e0307c | ||
|
|
be0770f3cf | ||
|
|
7435a6bb7c | ||
|
|
17f39bfa4d | ||
|
|
b4adf85f03 | ||
|
|
a10748b5eb | ||
|
|
0564275f58 | ||
|
|
6bb2c87373 | ||
|
|
59bfed58bf | ||
|
|
2fa109026c | ||
|
|
afacd10a18 | ||
|
|
2282abc3bc | ||
|
|
95e058d659 | ||
|
|
a69db0cd2a | ||
|
|
313098892e | ||
|
|
605008f584 | ||
|
|
297d87164c | ||
|
|
6c6be61dd0 | ||
|
|
9bf6b98953 | ||
|
|
c74ddedd6e | ||
|
|
d48fa8cca5 | ||
|
|
51b5d148bd | ||
|
|
8b1ccb329a | ||
|
|
f95d036f72 | ||
|
|
e8ca9753f5 | ||
|
|
e013fbe550 | ||
|
|
76802ed430 | ||
|
|
e7fe663746 | ||
|
|
c639d1231b | ||
|
|
206cd38f26 | ||
|
|
22191d260c | ||
|
|
b726ce9695 | ||
|
|
71cbf901a5 | ||
|
|
8e14e9842a | ||
|
|
1fa47c027d | ||
|
|
818ce22dd6 | ||
|
|
7458a2d42a | ||
|
|
9bec0f3718 | ||
|
|
58b142cac3 | ||
|
|
4766c9a808 | ||
|
|
34f001285d | ||
|
|
9bc8fd992a | ||
|
|
0e2d8fdcac | ||
|
|
f449e081c6 | ||
|
|
4ff8821562 | ||
|
|
5baaf0239a | ||
|
|
fe0d857021 | ||
|
|
4683b09e10 | ||
|
|
ba4b2a8798 | ||
|
|
98fa45ebd1 | ||
|
|
68b78f053a | ||
|
|
c3394f69b6 | ||
|
|
577bec86b4 | ||
|
|
adf140eb6b | ||
|
|
569fb51d91 | ||
|
|
ef35e5e26b | ||
|
|
9e48a42c1f | ||
|
|
43bd4509ad | ||
|
|
b329a61d96 | ||
|
|
65113862f7 | ||
|
|
c8b5f2a3bd | ||
|
|
ad782839ec | ||
|
|
61693d611a | ||
|
|
4a713a85d1 | ||
|
|
2ad757eb44 | ||
|
|
151758b94f | ||
|
|
facbbb07da | ||
|
|
b08de6bf81 | ||
|
|
658a6453b7 | ||
|
|
65934d34a1 | ||
|
|
407ed77385 | ||
|
|
23d02c5229 | ||
|
|
3734f5707a | ||
|
|
43aa6b2551 | ||
|
|
4717e45a9a | ||
|
|
43521b3675 | ||
|
|
5d64b801a3 | ||
|
|
b8cccb86ff | ||
|
|
fa0748a9c5 | ||
|
|
872db88066 | ||
|
|
507e9aab24 | ||
|
|
a70375c9ad | ||
|
|
e525681328 | ||
|
|
3cc33ea10c | ||
|
|
1539cf6933 | ||
|
|
bcd0690ef5 | ||
|
|
8fc08ab41e | ||
|
|
e5221ba681 | ||
|
|
e729b92d20 | ||
|
|
f46058f9b5 | ||
|
|
c955d8d143 | ||
|
|
a28e0b9abb | ||
|
|
233c518def | ||
|
|
08df7f1b6b | ||
|
|
feb1ddd1f7 | ||
|
|
583cce88c1 | ||
|
|
436f68ce33 | ||
|
|
26b59a1899 | ||
|
|
fc27771a92 | ||
|
|
17d83acfc8 | ||
|
|
0cfa4d9b4a | ||
|
|
bcca8fa4a5 | ||
|
|
4fad43d9cc | ||
|
|
31ae2973d7 | ||
|
|
4cd29a17b3 | ||
|
|
1b30d71a47 | ||
|
|
20e6ac6fbb | ||
|
|
db0589d965 | ||
|
|
6af6c52673 | ||
|
|
0d80e85dec | ||
|
|
b5777c84d3 | ||
|
|
0bc66c21b9 | ||
|
|
987e7a0f9a | ||
|
|
2c1eaf5735 | ||
|
|
1c2dcd0dbc | ||
|
|
77cd327f94 | ||
|
|
0af35d1e17 | ||
|
|
c7a2392591 | ||
|
|
b43e8fe8b8 | ||
|
|
7faa070d83 | ||
|
|
74c315bdfc | ||
|
|
a0596ed0ef | ||
|
|
cedc7725b5 | ||
|
|
d7f1b91c0a | ||
|
|
6ad476ac18 | ||
|
|
55ad08266e | ||
|
|
a10b15a3fd | ||
|
|
b34e97e487 | ||
|
|
a18b099206 | ||
|
|
5165698fe3 | ||
|
|
dfc6a6d77b | ||
|
|
bea5f10a12 | ||
|
|
02cbeda0a0 | ||
|
|
c5ffc23bcd | ||
|
|
038b6d2caa | ||
|
|
99bdcaeffc | ||
|
|
d4eff11f3e | ||
|
|
e5baeab193 | ||
|
|
355e7a21ca | ||
|
|
48c6f0ec1d | ||
|
|
c1dd0e62a8 | ||
|
|
69c32e4d13 | ||
|
|
f5c65331ca | ||
|
|
a913e0c5ad | ||
|
|
6269f0306d | ||
|
|
8b0ce1a2a8 | ||
|
|
2ebcf55ad3 | ||
|
|
726a52b91a | ||
|
|
df26248f4a | ||
|
|
ff5fb971da | ||
|
|
4bd052e0c7 | ||
|
|
4a9ac423fe | ||
|
|
b507ad627b | ||
|
|
eb02f0a5f6 | ||
|
|
365819ef7f | ||
|
|
e1f3fda692 | ||
|
|
fbef1d96d2 | ||
|
|
935c0df7af | ||
|
|
3c80938e91 | ||
|
|
aa8257ad86 | ||
|
|
d4aa663836 | ||
|
|
7655d5a0ce | ||
|
|
67e8fe5c00 | ||
|
|
870235442b | ||
|
|
2cc5d4e013 | ||
|
|
c3bc1b3501 | ||
|
|
cd943246d0 | ||
|
|
42661d37ad | ||
|
|
99a7b0ad00 | ||
|
|
a63094213e | ||
|
|
ec34603b0a | ||
|
|
c71584eeea | ||
|
|
21442fb822 | ||
|
|
592659e57b | ||
|
|
e8387392fd | ||
|
|
fa969e0a96 | ||
|
|
1623b91ddf | ||
|
|
ab2b8e6545 | ||
|
|
5a59a63862 | ||
|
|
44a39bf8ec | ||
|
|
cd3b39c3d7 | ||
|
|
3d2b235f64 | ||
|
|
afe6e03d4c | ||
|
|
bf91450a9d | ||
|
|
f348734a41 | ||
|
|
be05f70fb5 | ||
|
|
f4cf1d8fa8 | ||
|
|
b03ad862e0 | ||
|
|
20c5e97599 | ||
|
|
0376b1ab1f | ||
|
|
88a3c9c92d | ||
|
|
48f5b80776 | ||
|
|
ceb1b1f0f0 | ||
|
|
6dc85ff17e | ||
|
|
373d9f83e5 | ||
|
|
588655e7df | ||
|
|
79ff6f9ad5 | ||
|
|
7fe9c15b67 | ||
|
|
4d5700f0bf | ||
|
|
9bc51b05ad | ||
|
|
344148f9b8 | ||
|
|
2cd19f9764 | ||
|
|
a82d3283e8 | ||
|
|
067fac270b | ||
|
|
aa0d2f73d0 | ||
|
|
9c5a15542a | ||
|
|
a2ed562817 | ||
|
|
807b38b0af | ||
|
|
dd66d6caa7 | ||
|
|
7e7ac8f6f4 | ||
|
|
9f0b049148 | ||
|
|
ec2b53c02a | ||
|
|
757ee74bc7 | ||
|
|
78117f65c9 | ||
|
|
d101fa2ef3 | ||
|
|
fbc9266936 | ||
|
|
b6b10e35e2 | ||
|
|
b128da0631 | ||
|
|
ff53d30a7e | ||
|
|
4f8fef6ca2 | ||
|
|
7767efab58 | ||
|
|
6fe5e0809e | ||
|
|
3ec25c1471 | ||
|
|
8f8030c02e | ||
|
|
40d5a4f5af | ||
|
|
b830196829 | ||
|
|
69c5c187db | ||
|
|
d13938550d | ||
|
|
5481ec94a4 | ||
|
|
4524cfe960 | ||
|
|
3cf4b10b8c | ||
|
|
c29f3be466 | ||
|
|
5d4b91b3a1 | ||
|
|
505a8598b1 | ||
|
|
33ba86fc76 | ||
|
|
4cdf48c9fb | ||
|
|
6a6abae0d5 | ||
|
|
67c84e3504 | ||
|
|
681692bdce | ||
|
|
721b6d6f3e | ||
|
|
2707cefe9d | ||
|
|
8e6b830ac2 | ||
|
|
f78bc374eb | ||
|
|
cb7d655f0c | ||
|
|
41fa75e864 | ||
|
|
7417bfd5f1 | ||
|
|
63e6248f9f | ||
|
|
91655c28c5 | ||
|
|
24fe7cdede | ||
|
|
ecc0295f6d | ||
|
|
50d47cedef | ||
|
|
4fb392adae | ||
|
|
dcaf878254 | ||
|
|
1511338a23 | ||
|
|
4397bf2c90 | ||
|
|
3202c18ab5 | ||
|
|
a4fec0681f | ||
|
|
043c526c9c | ||
|
|
9f637e6afb | ||
|
|
5a018a0470 | ||
|
|
d2dde8c14f | ||
|
|
7b3cdd925e | ||
|
|
cd07d441b2 | ||
|
|
f749f6be79 | ||
|
|
e560cb3928 | ||
|
|
e5dcb97643 | ||
|
|
4309c700d2 | ||
|
|
88d6de13d5 | ||
|
|
9ca717d2d0 | ||
|
|
d5015edfa1 | ||
|
|
6e5703a482 | ||
|
|
8396e8e895 | ||
|
|
f2c3cb8135 | ||
|
|
ea9f3f61bb | ||
|
|
1fc92a7b00 | ||
|
|
a7835261e1 | ||
|
|
3dc7d2adee | ||
|
|
deba36260e | ||
|
|
013a4fbb97 | ||
|
|
1c09466424 | ||
|
|
6fb7a423cb | ||
|
|
a6fd508529 | ||
|
|
0052faa24d | ||
|
|
cbc9edfd60 | ||
|
|
93382d3c97 | ||
|
|
5e2b415f5c | ||
|
|
3af5f6e54b | ||
|
|
342b45d593 | ||
|
|
dc70ada7c4 | ||
|
|
4fbcca6851 | ||
|
|
65f27d6099 | ||
|
|
9e580f175e | ||
|
|
88659bb7af | ||
|
|
7dc78aac76 | ||
|
|
5a938cf8ff | ||
|
|
69900f7007 | ||
|
|
d8d1ee4698 | ||
|
|
d859c6066c | ||
|
|
1ac7a5c943 | ||
|
|
f0cf4e4eeb | ||
|
|
f76cf2bf38 | ||
|
|
8fe581ea93 | ||
|
|
ad7f34a99e | ||
|
|
445148e812 | ||
|
|
a51adba46f | ||
|
|
a2de7eca7c | ||
|
|
ab57408c70 | ||
|
|
ad6adb49dc | ||
|
|
d606bc4b55 | ||
|
|
fe149bb9ad | ||
|
|
52ef4e5ca6 | ||
|
|
84a622c3f1 | ||
|
|
2488c6f8dc | ||
|
|
2e5af6b5a5 | ||
|
|
036f8075f5 | ||
|
|
ded9a7e5d0 | ||
|
|
677ad8115a | ||
|
|
a6869eeb59 | ||
|
|
c74ebcda4e | ||
|
|
2207eea1e1 | ||
|
|
966b517bbd | ||
|
|
0d513ab3f2 | ||
|
|
b7ded817d9 | ||
|
|
9f47c709f1 | ||
|
|
5298ff7cf3 | ||
|
|
29e61a235b | ||
|
|
d0cbec1846 | ||
|
|
d822267bd3 | ||
|
|
60188ff735 | ||
|
|
edf4b72dc4 | ||
|
|
eada67de13 | ||
|
|
7f4a8719de | ||
|
|
e4c9a2f7f4 | ||
|
|
52587aabf7 | ||
|
|
8c7ca92891 | ||
|
|
535bd36d91 | ||
|
|
a2cf590315 | ||
|
|
aef8836f15 | ||
|
|
7e5bcaa239 | ||
|
|
8d9c85d379 | ||
|
|
0fa6ec4ed3 | ||
|
|
e22f12c0b6 | ||
|
|
01a81b926e | ||
|
|
243ff52063 | ||
|
|
86d5c39eab | ||
|
|
b68fe3a19f | ||
|
|
58afaac821 | ||
|
|
8b549162c4 | ||
|
|
8f32a59bd6 | ||
|
|
9237152aa1 | ||
|
|
099811670f | ||
|
|
ef25e66f08 | ||
|
|
a469202959 | ||
|
|
e6f5db8a89 | ||
|
|
fdd236071e | ||
|
|
ea9d821047 | ||
|
|
05f80c81ad | ||
|
|
d07528bd0e | ||
|
|
c750321ced | ||
|
|
d107405f62 | ||
|
|
a254b96f65 | ||
|
|
5fb23cf404 | ||
|
|
213363d0be | ||
|
|
4539898c58 | ||
|
|
25f8c683bb | ||
|
|
f8d406dcf0 | ||
|
|
dfabe40e7a | ||
|
|
2a2ccae9ce | ||
|
|
6458bc0440 | ||
|
|
bb42dd662e | ||
|
|
79faa556de | ||
|
|
1bef94ce0c | ||
|
|
d12fa84b00 | ||
|
|
14aba6b129 | ||
|
|
a37ffd9127 | ||
|
|
a758037f20 |
@@ -1 +1,6 @@
|
|||||||
build/
|
build/
|
||||||
|
world/
|
||||||
|
server_mods/
|
||||||
|
dist/
|
||||||
|
ports/
|
||||||
|
/config/
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# bworld
|
||||||
|
|
||||||
|
A voxel game in TypeScript on Deno. The base game is itself a mod (`mods/bworld`), written against the same modding API
|
||||||
|
as any other mod.
|
||||||
|
|
||||||
|
**Never under any circumstance commit anything on your own**
|
||||||
|
|
||||||
|
**Never under any circumstance generate any textures or audio files**
|
||||||
|
|
||||||
|
Always ask before making even the simplest models, unless it's coming from ports/
|
||||||
|
|
||||||
|
## Names
|
||||||
|
|
||||||
|
- The engine is called `cubi`, all engine names should use the `cubi` namespace like `cubi:air`
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `server/`: the game server, world, saves and server-side game logic
|
||||||
|
- `client/`: the client: rendering, meshing and lighting workers, UI. `client/native/` runs it in the desktop app
|
||||||
|
- `desktop/`: the desktop app: its window, sound, singleplayer and client updates (see "Desktop first")
|
||||||
|
- `common/`: code shared by both, including world generation, the protocol and the modding API (`common/mod_api/`)
|
||||||
|
- `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts
|
||||||
|
- `docs/`: modding docs and `docs/modding_plan.md`
|
||||||
|
- `tests/`: Deno tests
|
||||||
|
- `tools/`: dev scripts (mod checking and packing, worldgen preview, benchmarks)
|
||||||
|
- `ports/`: reference source from other projects, not part of the game (see below)
|
||||||
|
- `build/`, `server_mods/`, `dist/`, `world/`: build output and the local world. Don't edit these by hand.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno task test # every test, takes about 3 minutes
|
||||||
|
deno test -A tests/door_test.ts # one test file, prefer this while working
|
||||||
|
deno task check-mods # validate and typecheck every mod in mods/
|
||||||
|
deno task build # pack mods and build the client, then keeps rebuilding on changes
|
||||||
|
deno task server # start a server with the mods from the last build
|
||||||
|
deno task desktop # run the desktop app with what the last build made
|
||||||
|
deno task compile [linux] [windows] # build the desktop app's executables into dist/
|
||||||
|
deno fmt # format (tabs, 120 columns), applies to JSON too
|
||||||
|
deno task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests load mods straight from `mods/` through `test_game` in `tests/helpers.ts`, so they don't need a build. Run
|
||||||
|
`deno task check-mods` after changing anything in a mod.
|
||||||
|
|
||||||
|
## Engine and base game
|
||||||
|
|
||||||
|
The engine is what any game built on it needs: rendering, physics, networking, saving, registries, the mod loader, GUI,
|
||||||
|
entities. Game content and rules belong in `mods/bworld` (data in its JSON folders, behavior in `mods/bworld/scripts/`).
|
||||||
|
If the base game can't do something as a mod, add what's missing to the modding API rather than special-casing it in the
|
||||||
|
engine, since other mods would hit the same wall. See "The Engine and the Base Game" in `docs/modding_plan.md`.
|
||||||
|
|
||||||
|
When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of
|
||||||
|
`ports/neoforge-docs`.
|
||||||
|
|
||||||
|
## Desktop first
|
||||||
|
|
||||||
|
The desktop app is the main target and the browser a secondary one, so build and try new features in the desktop app
|
||||||
|
first. The app (`desktop/`) is an SDL3 window that the client draws into with Deno's WebGPU, running in a Deno worker
|
||||||
|
(`client/native/`), with sound through OpenAL Soft and a singleplayer server of its own.
|
||||||
|
|
||||||
|
- The client keeps using web APIs: WebGPU, Web Audio, fetch, WebSocket. Where Deno doesn't have one, polyfill the part
|
||||||
|
the game uses, like `client/native/web_audio.ts` does over OpenAL, instead of writing engine code only the desktop app
|
||||||
|
can run.
|
||||||
|
- What has to differ between the two goes through `Platform` (`client/platform.ts`), which `client/browser_platform.ts`
|
||||||
|
and `client/native/main.ts` implement, rather than checks for the DOM in shared code.
|
||||||
|
- Keep the browser working, but a browser limitation doesn't block a feature: it can be missing or simpler there.
|
||||||
|
- The client worker runs servers' mods, so it only gets the network and reading its own files, and gives up FFI once the
|
||||||
|
window's surface exists. Don't widen its permissions.
|
||||||
|
- The Windows build ships SDL3 and OpenAL Soft from `desktop/windows/`: unmodified files from their tagged releases,
|
||||||
|
with their licenses and where they came from in `credits.txt` there, which the app shows in its credits. Update it
|
||||||
|
along with the DLLs.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids.
|
||||||
|
- Before writing something new, search the project for an existing feature that already does it or something close to
|
||||||
|
it, and reuse or extend that. Code duplication is a major problem here and should be avoided.
|
||||||
|
- Keep things simple. Don't add abstractions, options or generality the task doesn't need.
|
||||||
|
- Private class members use `#`, not the `private` keyword.
|
||||||
|
- Comments are lowercase and explain why or what something is for, not what the next line does.
|
||||||
|
- Don't mention Minecraft by name in comments, and don't paste or reference pieces of its code in them. Comments should
|
||||||
|
explain the code on its own terms.
|
||||||
|
- Mod data files start with `"format_version": 1`, and ids are namespaced by mod (`bworld:oak_log`). New content should
|
||||||
|
follow the files next to it, so look at a similar block, item or recipe first.
|
||||||
|
- Changing a message in `common/protocol.ts` means bumping `PROTOCOL_VERSION`.
|
||||||
|
- The game is in pre-alpha and backwards compatibility isn't a priority. Only test worlds exist. If supporting old saves
|
||||||
|
or old data takes a lot of code, it's fine to break them instead.
|
||||||
|
- Tests should check the behavior they're about, and shouldn't need changing when unrelated parts of the game change.
|
||||||
|
Avoid asserting on specific content (exact block lists, recipe counts, worldgen output, tuned numbers) unless that
|
||||||
|
content is what's being tested.
|
||||||
|
- Changing world generation (terrain, ores, features) on purpose makes the worldgen golden tests fail. Record them again
|
||||||
|
with `deno test -A tests/worldgen_golden_test.ts -- --update`.
|
||||||
|
- Commit messages are short and plain, like "Metal ingots and blocks", with no prefixes.
|
||||||
|
|
||||||
|
## Reference code in `ports/`
|
||||||
|
|
||||||
|
`ports/` holds source from other projects to consult, not to edit:
|
||||||
|
|
||||||
|
- `ports/horizon`: cleanroom implementation of minecraft, very useful for a lot of various things
|
||||||
|
- `ports/neoforge` and `ports/neoforge-docs`: check these whenever adding to the modding API. The API should often
|
||||||
|
resemble NeoForge's.
|
||||||
|
- `ports/justenoughitems`: check when working on the recipe viewer mod (`mods/recipe_viewer`).
|
||||||
|
- `ports/sodium`: check when looking for rendering optimizations.
|
||||||
|
- `ports/lithium`: check when looking for server optimizations.
|
||||||
@@ -0,0 +1,734 @@
|
|||||||
|
# Create
|
||||||
|
|
||||||
|
A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics, processing, logistics, fluids,
|
||||||
|
redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as
|
||||||
|
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||||
|
|
||||||
|
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed`, `rotating`, `fluid` and
|
||||||
|
items), R4, R5, R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts, cogwheels, gearboxes,
|
||||||
|
encased shafts and cogs, clutches, gearshifts and chain drives turned by a hand crank, creative motor or water wheel,
|
||||||
|
with stress and overstress), Create's pressing recipes, the mechanical press pressing items on the ground or compacting
|
||||||
|
in a basin, and the basin holding items and fluids. Facts about Create come from reading `ports/create1.21.1` and
|
||||||
|
`ports/create1.19.3`, and facts about bworld from its source.
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
| Copy | Version | Used for |
|
||||||
|
| -------------------- | ------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `ports/create1.21.1` | 6.0.11 | **All code and data**: mechanics, numbers, recipes, tags, worldgen, ponder scripts |
|
||||||
|
| `ports/create1.19.3` | 0.5.0.j | **Textures, models, blockstates, sounds and ponder scenes** from its `assets/` and `src/generated/resources/assets/` |
|
||||||
|
|
||||||
|
0.5.0.j shipped with only an MIT `LICENSE`, so its assets are used under that, with the MIT notice in
|
||||||
|
`mods/create/CREDITS.md`. 6.0.11's `assets/` folder isn't in the copy and isn't used.
|
||||||
|
|
||||||
|
**Keep the art removable.** Everything from 0.5.0.j's assets is written by the importer (below) into
|
||||||
|
`mods/create/textures/` and `mods/create/models/`, and nothing else in the mod depends on a specific file being there.
|
||||||
|
Removing the art is then deleting those two folders and re-running the importer with `--no-assets`. That writes
|
||||||
|
placeholder models (a plain cube, or the block's shape) and a placeholder texture, and the mod still loads and plays.
|
||||||
|
|
||||||
|
**Content newer than 0.5.0.j has no art to take**, so it needs new art either way. These are the blocks and items 6.0.11
|
||||||
|
registers that 0.5.0.j doesn't: the package logistics (`packager`, `repackager`, `package_frogport`, `stock_ticker`,
|
||||||
|
`stock_link`, `redstone_requester`, `factory_gauge`, `package_filter`, `item_hatch`, `chain_conveyor`, cardboard and its
|
||||||
|
blocks and armor, table cloths, `shopping_list`), `large_water_wheel`, `elevator_pulley`, `elevator_contact`,
|
||||||
|
`contraption_controls`, `mechanical_roller`, the copycats, `clipboard`, `desk_bell`, `pulse_timer`, metal doors and
|
||||||
|
scaffolding, `andesite_alloy_block`, `industrial_iron_block`, `weathered_iron_block`, `experience_block`, netherite
|
||||||
|
diving gear. The importer lists them in its report.
|
||||||
|
|
||||||
|
## How Big Create Is
|
||||||
|
|
||||||
|
6.0.11 is 2017 Java files, about 275,000 lines. By part:
|
||||||
|
|
||||||
|
| Part | Lines | What |
|
||||||
|
| --------------------------- | ------ | ------------------------------------------------------------------------------- |
|
||||||
|
| `content/kinetics` | 36,000 | Shafts, cogs, gearboxes, generators, belts, and the machines that use rotation |
|
||||||
|
| `infrastructure` | 33,000 | Config, datagen, ponder scenes, commands |
|
||||||
|
| `content/trains` | 30,000 | Tracks, the track graph, signals, stations, schedules, train entities |
|
||||||
|
| `content/logistics` | 30,000 | Funnels, tunnels, chutes, depots, vaults, filters, and 6.0's packages |
|
||||||
|
| `content/contraptions` | 27,000 | Moving block structures: bearings, pistons, pulleys, gantries, actors |
|
||||||
|
| `content/equipment` | 17,000 | Wrench, goggles, potato cannon, backtank, toolbox, symmetry wand |
|
||||||
|
| `content/redstone` | 12,000 | Links, nixie tubes, display links, threshold switch, diodes |
|
||||||
|
| `content/fluids` | 12,000 | Pipes, pumps, tanks, spouts, drains, hose pulley, boilers |
|
||||||
|
| `compat` | 10,000 | Other mods. Only the JEI part matters, for the recipe viewer |
|
||||||
|
| `content/decoration` | 7,000 | Palettes, copycats, girders, sliding doors, placards |
|
||||||
|
| `content/schematics` | 7,000 | Schematic table, schematicannon |
|
||||||
|
| `content/processing` | 5,000 | Basin, blaze burner, sequenced assembly, the processing recipe base |
|
||||||
|
| `foundation`, `api`, `impl` | 40,000 | Block entity behaviours, connected textures, GUI, networking, rendering helpers |
|
||||||
|
|
||||||
|
Data in 6.0.11: 188 blocks and 60 items registered one by one (plus generated families like palettes), and 1881 recipes
|
||||||
|
in 19 types. Art in 0.5.0.j: 1043 generated and 573 hand-made block models, 1006 textures, 92 connected texture sheets,
|
||||||
|
153 ponder scenes.
|
||||||
|
|
||||||
|
A straight line-by-line translation would be most of a year of work and would carry over things bworld doesn't need,
|
||||||
|
like datagen, mixins, compat and Forge plumbing. The plan below is built to avoid that.
|
||||||
|
|
||||||
|
## Strategy
|
||||||
|
|
||||||
|
Six rules that keep the work small:
|
||||||
|
|
||||||
|
1. **Import data, don't hand-write it.** One tool converts Create's models, textures, blockstates, recipes, tags, loot,
|
||||||
|
names and worldgen into bworld's formats, and reports what it couldn't convert. Hundreds of blocks then cost the same
|
||||||
|
as one. It's run once to start from, and what it made is edited by hand after. This replaces Create's datagen.
|
||||||
|
2. **Port Create's architecture onto bworld's, not its classes.** Create builds every machine from a few shared pieces
|
||||||
|
(block entity behaviours, a rotation network, processing recipes, instance types). Each piece becomes one bworld
|
||||||
|
piece, and then the machines are mostly data plus a little code (see [Architecture](#architecture)).
|
||||||
|
3. **Put general features in the engine, once.** Block capabilities, fluids, redstone, instanced rendering and moving
|
||||||
|
block structures are things any mod could use. They go in the engine shaped like NeoForge's (check `ports/neoforge`),
|
||||||
|
and Create is their first user.
|
||||||
|
4. **Change-driven server work.** Rotation, pipes and belts are networks that only recompute when something in them
|
||||||
|
changes. Blocks that have nothing to do don't tick.
|
||||||
|
5. **GPU-driven animation.** A turning part is uploaded once with its axis, speed and offset, and the vertex shader
|
||||||
|
turns it from the time, like Create's `rotating` instance type. Nothing is sent or computed per frame for something
|
||||||
|
that turns at a steady speed.
|
||||||
|
6. **Playable in phases.** Each phase ends with something to use in a world and tests passing, in an order where every
|
||||||
|
phase only needs the ones before it.
|
||||||
|
|
||||||
|
## The Importer
|
||||||
|
|
||||||
|
A generic tool for any Minecraft Java mod, `tools/importer.ts`, not one for Create. It converts one kind of resource at
|
||||||
|
a time, from a single file or a whole folder:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno run -A tools/importer.ts model MODEL.json --output PATH # one model, printed without --output
|
||||||
|
deno run -A tools/importer.ts model path/to/resources --output DIR # every assets/<namespace>/models in it
|
||||||
|
```
|
||||||
|
|
||||||
|
A folder can be a mod's whole resources, one `assets/<namespace>/models`, or a folder inside one, and the output keeps
|
||||||
|
the same folders. `--parents FOLDER` adds other resources to follow parents through (to tell sprites and OBJ models
|
||||||
|
apart), and `--remap FILE` renames locations before they become ids. Every kind reports what it converted, what it
|
||||||
|
skipped and why, and what's wrong, and exits with an error when anything is.
|
||||||
|
|
||||||
|
**Ids.** A resource location becomes a bworld id by joining its folders with `_`, the same rule `check-mods` uses for
|
||||||
|
textures in subfolders: `create:block/cogwheel` is `create:block_cogwheel`, for its model and its texture alike. It's a
|
||||||
|
pure function of the location, so every kind agrees on ids without sharing state: a blockstate pointing at a model
|
||||||
|
writes the same id the model was written with. Two locations that join to the same id are an error, fixed with
|
||||||
|
`--remap`.
|
||||||
|
|
||||||
|
**Remaps** are prefix rules, longest first, and a `skip` list of patterns for locations to leave out of every kind:
|
||||||
|
`{ "textures": { "minecraft:block/": "bworld:" }, "models": {}, "ids": {}, "tags": {} }`. The defaults map Minecraft's
|
||||||
|
block and item textures, its blocks and items (`ids`) and its tags to the base game's of the same name, and Forge's
|
||||||
|
shared tags to `c`, which is what bworld calls them. A mod's remap file is where its other vanilla ids go.
|
||||||
|
|
||||||
|
**Kinds:**
|
||||||
|
|
||||||
|
| Kind | Java | bworld | Status |
|
||||||
|
| ------------ | -------------------------------------------- | ----------------------------------------------------------------------- | ------ |
|
||||||
|
| `model` | `assets/*/models/**.json` | `models/`, parents kept, faces renamed, Blockbench extras dropped | Built |
|
||||||
|
| `texture` | `assets/*/textures/**.png` and `.png.mcmeta` | `textures/`, with animations | Built |
|
||||||
|
| `blockstate` | `assets/*/blockstates/*.json` | `blocks/*.json` with `variants` or `parts`, string states made numeric | Built |
|
||||||
|
| `item` | `assets/*/models/item/*.json` | `items/*.json` for items that aren't a block's, with their sprite | Built |
|
||||||
|
| `lang` | `assets/*/lang/en_us.json` | item and block names | |
|
||||||
|
| `recipe` | `data/*/recipe(s)/**.json` | `recipes/`: vanilla types to bworld's. Stonecutting and pressing so far | Built |
|
||||||
|
| `tag` | `data/*/tags/**.json` | `tags/`, Forge's shared tags as `c:`, missing entries optional | Built |
|
||||||
|
| `loot` | `data/*/loot_table(s)/**.json` | `drops`, or loot tables | |
|
||||||
|
| `worldgen` | `data/*/worldgen/**.json` | `worldgen/`: ores, and features where bworld has them | |
|
||||||
|
| `sound` | `assets/*/sounds.json`, `sounds/**.ogg` | sounds, once the engine has them (S8) | |
|
||||||
|
| `mod` | all of the above | a whole mod folder with a manifest, and one report | |
|
||||||
|
|
||||||
|
Block properties (shape, tool, toughness) aren't in any data file: Java mods set them in code. `blockstate` writes a
|
||||||
|
block for each blockstate with placeholder properties, and what a block really has, like its `components`, is written
|
||||||
|
into its file by hand after. The importer is a starting point, not something to run again over a mod that's been worked
|
||||||
|
on, since that would write over those changes.
|
||||||
|
|
||||||
|
**What `model` does today.** It keeps `parent`, since the engine merges parents in when it loads (see
|
||||||
|
[Parents](docs/modding/resources/models.md#parents)), and remaps it like any id. Minecraft's template parents (`cube`,
|
||||||
|
`cube_all`, `cube_column`, `orientable`, slabs, stairs, walls, glass panes) become the base game's models of the same
|
||||||
|
name in `mods/bworld/models/templates/`, and the default remap is read from that folder. A parent that holds nothing
|
||||||
|
bworld uses, like `block/block` (bworld has its own way of drawing blocks' items), is left out. It drops Blockbench's
|
||||||
|
extras and the `display` transforms of places bworld doesn't draw items (third person, the left hand, the head), keeps
|
||||||
|
every texture variable (some models draw faces with `#particle`), skips item sprites (`item/generated`) and `loader`
|
||||||
|
models (OBJ, composite) anywhere up a model's parents, and says why.
|
||||||
|
|
||||||
|
Run over Create 0.5.0.j's 2237 model files it converts 2091, and with its textures they make a mod `check-mods` accepts.
|
||||||
|
The rest are the 16 crimson and warped ones the remap file skips, 79 item sprites, 50 OBJ or composite models and one
|
||||||
|
with only third person transforms, and 3 name clashes were fixed with one remap line. Merged the way the game merges
|
||||||
|
them, the 2099 models with boxes come out identical to flattening them, and the files are 1.5 MB instead of 3.4 MB. 26
|
||||||
|
vanilla textures they use (pistons, redstone torches, rails) aren't in bworld yet.
|
||||||
|
|
||||||
|
**What `texture` does today.** It copies PNGs keeping their folders, since bworld already names a texture in a subfolder
|
||||||
|
by joining the folders with `_`, which is the same id the converted models use. A `.png.mcmeta` becomes the `.json` next
|
||||||
|
to the png, keeping only its `animation` section: bworld reads the same format. It checks every texture against the
|
||||||
|
limits a `.cubi` checks, skips Minecraft's own textures (the remap points at bworld's), and needs `--namespace` when a
|
||||||
|
folder holds textures of more than one mod, since a texture's namespace comes from the mod it ends up in. For Create
|
||||||
|
0.5.0.j it copies 989 textures and 11 animations, and skips the six 512×512 title screen panoramas. Its textures and
|
||||||
|
models together make a mod `check-mods` accepts, with warnings only for the 27 missing textures.
|
||||||
|
|
||||||
|
**What `blockstate` and `item` do today.** `blockstate` writes a block for each blockstate: each property becomes a
|
||||||
|
numbered state with the fewest bits that fit (booleans as false and true, facing as north, east, south, west, up and
|
||||||
|
down so a 2 bit facing still faces its placer), properties that never change the look (like `waterlogged`) are left out,
|
||||||
|
`variants` keep their models, `x` and `y` turns and `uvlock`, and a `multipart` becomes `parts`, one for each way a part
|
||||||
|
can be drawn. Blocks that aren't full cubes are `cutout`, or `translucent` when their model asks for it. A model that
|
||||||
|
can't be imported (OBJ, composite) is drawn as a placeholder cube. Every block gets the same placeholder mining (a
|
||||||
|
second, any tool) and drops itself, since Java mods set those in code. A block has an item when Java has an item model
|
||||||
|
for it, drawn with that model, or flat as its sprite. `item` writes the items that aren't a block's, with their sprite,
|
||||||
|
or with their model for the 9 Java draws in 3D from boxes (wrench, potato cannon, extendo grip), whose texture is the
|
||||||
|
model's `particle`. The empty blaze burner's model is OBJ, so it's flat.
|
||||||
|
|
||||||
|
`mods/create` is the result: 556 blocks and 81 items from 0.5.0.j (the crimson and warped windows are left out with the
|
||||||
|
remap file's `skip`) that can be placed and look like Create's, with no behavior. `check-mods` accepts it, warning only
|
||||||
|
about 31 vanilla textures bworld doesn't have yet. The 132 blockstates that use `uvlock` keep it.
|
||||||
|
|
||||||
|
**What `tag` and `recipe` do today.** Tags and recipes are checked against the mods next to `--output`, read the way
|
||||||
|
`check-mods` reads them. `tag` writes each item, block, entity and biome tag in bworld's format, which is Java's,
|
||||||
|
keeping folders in tag ids. An entry that doesn't exist here becomes optional (`required: false`), so the tag loads now
|
||||||
|
and picks it up once it's added, and what the remaps skip is left out. `recipe` converts each type bworld has an
|
||||||
|
equivalent for and reports the rest by type. A recipe naming an item or tag that doesn't exist here, or that only loads
|
||||||
|
under a condition (another mod installed), is skipped, since bworld's recipes have to be complete. So far
|
||||||
|
`minecraft:stonecutting` is converted to `bworld:stonecutting`, and `create:pressing` keeps its type in the shape in
|
||||||
|
[Recipes](#recipes), from 0.5's and 6.0's JSON alike.
|
||||||
|
|
||||||
|
Create 0.5.0.j's data gives 89 tags: 45 of Create's and 44 of Forge's shared ones, which are `c:` here. Fluid tags are
|
||||||
|
skipped. Of its 531 stonecutting recipes, 423 are converted. The other 108 cut granite, diorite, deepslate, calcite,
|
||||||
|
tuff and dripstone, which bworld doesn't have yet. Re-importing once it does brings them in. Of its 6 pressing recipes,
|
||||||
|
4 are converted, ingots into sheets. Sugar cane into paper and grass into dirt paths wait for those items.
|
||||||
|
|
||||||
|
**For Create**, `mods/create/import/` keeps the remap file, the block table and the commands. Re-running the import is
|
||||||
|
one command, and hand-written files are never in the folders it writes.
|
||||||
|
|
||||||
|
**Vanilla ids in recipes.** Create's recipes use 447 distinct Minecraft ids, like dyes, `minecraft:cobblestone` and
|
||||||
|
`minecraft:netherrack`. Each becomes the bworld id of the same name, or another with the remap file's `ids`. A recipe
|
||||||
|
using one bworld doesn't have is skipped and listed in the report, so the report always says how much of Create is
|
||||||
|
missing because bworld lacks something.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
How each of Create's shared pieces lands in bworld:
|
||||||
|
|
||||||
|
| Create | bworld |
|
||||||
|
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `SmartBlockEntity` and its `BlockEntityBehaviour`s | A block with several components. Each behaviour (filtering, scroll value, inventory, fluid tank, transported items) is one reusable `create:` component with params |
|
||||||
|
| `lazyTick` (every N ticks) | A counter in the component, or `on_second` |
|
||||||
|
| `sendData` / `getUpdateTag` | Client-visible tile data (R1) |
|
||||||
|
| `BlockEntityRenderer` and Flywheel `Visual`s | Block visuals (R2) drawing instances (R3) |
|
||||||
|
| `AllPartialModels` | Models in `models/` used by visuals, not blocks (R4) |
|
||||||
|
| `AllInstanceTypes`: rotating, scrolling, scrolling transformed, fluid | Engine instance types (R3) |
|
||||||
|
| `RotationPropagator`, `KineticNetwork` | `scripts/kinetics/` |
|
||||||
|
| NeoForge capabilities (`IItemHandler`, `IFluidHandler`) | Block capabilities (S1, S2) |
|
||||||
|
| `ProcessingRecipe` and its 19 types | Custom recipe types parsed in one place (`scripts/recipes/`) |
|
||||||
|
| `AbstractContraptionEntity`, `Contraption` | Engine block structure entities (S6) and the mod's assembly code |
|
||||||
|
| `AllPackets` | Mod channels |
|
||||||
|
| Menus and screens | Menus and screens, which bworld has |
|
||||||
|
| `AllConfigs` | `mods/create/config.json`, read in `setup` (S12) |
|
||||||
|
| Registrate, datagen | The importer |
|
||||||
|
| Mixins | Engine hooks, only where an engine feature isn't worth adding |
|
||||||
|
| Ponder | A scene player (P13) |
|
||||||
|
| `compat/jei` | Recipe viewer categories (R11) |
|
||||||
|
|
||||||
|
Server code is laid out by subsystem, each a folder with no `ctx` in its core logic so tests can call it directly:
|
||||||
|
|
||||||
|
```
|
||||||
|
mods/create/scripts/
|
||||||
|
server.ts shared.ts client.ts worldgen.ts
|
||||||
|
kinetics/ connections, spreading, stress, generators
|
||||||
|
processing/ press, mixer, millstone, crushing, saw, fan, deployer, crafter, basin, burner, sequenced assembly
|
||||||
|
logistics/ belts, funnels, tunnels, chutes, depots, arm, vaults, filters, packages
|
||||||
|
fluids/ pipes, pumps, tanks, spouts, drains, hose pulley, boilers
|
||||||
|
redstone/ links, nixie tubes, display links, diodes, observers
|
||||||
|
contraptions/ assembly, movement, actors, controls
|
||||||
|
trains/ track graph, signals, stations, schedules, train movement
|
||||||
|
equipment/ wrench, goggles, potato cannon, backtank, toolbox, symmetry wand
|
||||||
|
recipes/ parsing every Create recipe type
|
||||||
|
visuals/ client visuals for each block that moves
|
||||||
|
```
|
||||||
|
|
||||||
|
## Engine Work
|
||||||
|
|
||||||
|
Everything here is general, and none of it mentions Create. Each line says which phase first needs it.
|
||||||
|
|
||||||
|
### Rendering
|
||||||
|
|
||||||
|
**R1. Client-visible tile data** (P1, built). `block.set_client_data(field, value)` keeps a field of a block's data that
|
||||||
|
clients see too, apart from its server-only `data`. Players get every field with the chunk, then each field again when
|
||||||
|
it's set to something else, like NeoForge's `getUpdateTag` but per field, so a fast-changing field doesn't resend the
|
||||||
|
rest. It's saved, goes with the block, and client scripts read it with `ctx.world.get_client_data`. The display item is
|
||||||
|
its `item` field now, so there's one way to sync block data. R2's visuals will be told when a field changes.
|
||||||
|
|
||||||
|
**R2. Block visuals** (P1, built). `ctx.render.register_visual(block_id, create, { replaces_model })` in client scripts,
|
||||||
|
like Flywheel's `Visual`. The chunk mesher lists the blocks with visuals in each chunk it meshes, and leaves out the
|
||||||
|
models of the ones whose visual replaces it, like `ENTITYBLOCK_ANIMATED`. A visual is made from that list, `update`d
|
||||||
|
when a client data field changes, made again when the block's states change, and deleted with the block or chunk. It
|
||||||
|
draws `rotating` and `transformed` instances of its block's model or of any model in `models/` by id, turned like a
|
||||||
|
variant. A visual that has to move on the CPU (a crank easing in, a press head) gets `on_frame`, like `DynamicVisual`.
|
||||||
|
Visuals are kept per chunk, and only the ones in chunks in view get `on_frame`.
|
||||||
|
|
||||||
|
**R3. Instanced drawing** (P1, `transformed`, `rotating`, `fluid` and items built). A WebGPU pipeline that draws one
|
||||||
|
model many times from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The
|
||||||
|
instance types, matching Create's:
|
||||||
|
|
||||||
|
| Type | Per instance | Shader |
|
||||||
|
| ------------- | ------------------------------------------ | ----------------------------------------------------------------------- |
|
||||||
|
| `transformed` | a matrix, light, tint | moves the model |
|
||||||
|
| `rotating` | position, axis, rpm, offset, light, tint | turns the model around its axis by `ticks × rpm × 0.3 + offset` degrees |
|
||||||
|
| `scrolling` | position, rotation, uv scroll speed, light | scrolls the texture coordinates, for belts |
|
||||||
|
| `fluid` | box, fluid texture, fill, light | a box of a fluid's texture, for tanks and pipes |
|
||||||
|
|
||||||
|
Instances are grouped by model and type, and each group is one draw call. Light is packed per instance from the block's
|
||||||
|
light, updated when that light changes. `rotating` is the important one: thousands of shafts at a steady speed cost
|
||||||
|
nothing per frame. See `ports/sodium` for how to keep buffer updates cheap.
|
||||||
|
|
||||||
|
As built, `transformed` and `rotating` share one instance layout (a placement matrix, an axis, rpm, offset and light, 96
|
||||||
|
bytes): a rotating instance is placed at its block and spins, a transformed one is placed by its matrix and doesn't. So
|
||||||
|
instances are grouped by model alone. Each group keeps its instances on the CPU too, changes them there, and writes the
|
||||||
|
range from the first changed instance to the last once a frame. A deleted instance's place is taken by the last one, so
|
||||||
|
a group's instances are always its first ones. Light comes with each chunk mesh. Every instance is drawn each frame,
|
||||||
|
with no culling by chunk, since a draw call per model is cheaper than one per model per chunk until there are far more
|
||||||
|
instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts
|
||||||
|
(P4).
|
||||||
|
|
||||||
|
`fluid` is built apart from the table: each box is a model of its own, built on the CPU when its box is set, cut into a
|
||||||
|
piece per block it crosses so the texture is never stretched, like Create's `renderTiledFace`, and tinted in its fluid's
|
||||||
|
color. It's one draw call per box, drawn blended after the other instances and back to front. Items are transformed
|
||||||
|
instances too, of a model built once from what an item draws, one per way an item looks (its id, texture and layer
|
||||||
|
colors), so a belt of one item is one draw call.
|
||||||
|
|
||||||
|
**R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU
|
||||||
|
buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and
|
||||||
|
uploaded the first time it's drawn, once per level. Every model is packed and sent to clients whether a block uses it or
|
||||||
|
not, and the partials P1's visuals use are all imported with their textures: `shaft`, `shaft_half`, `cogwheel_shaft`,
|
||||||
|
`cogwheel_shaftless`, `large_cogwheel_shaftless`, `hand_crank/handle`, `gauge/dial`, `gauge/indicator`, both gauge heads
|
||||||
|
and `rotation_speed_controller/bracket` (as `create:block_shaft_half` and so on). 0.5.0.j's water wheel is its block's
|
||||||
|
own model. 6.0's wheels that take the wood they're made of swap the oak textures in their model, which needs their new
|
||||||
|
art and a texture override on a model reference, so it waits for that art.
|
||||||
|
|
||||||
|
**R5. The model format** (P0, built). Everything Create's static models use: `parent`, `x` turns, `uvlock` on variants
|
||||||
|
and parts, element `rotation` at any angle around one axis, and items drawn with models. An item's `model` draws it in
|
||||||
|
3D like a block's `item_model`, and a model's `display` places it in slots, in the hand, on the ground and on blocks
|
||||||
|
(`gui`, `firstperson_righthand`, `ground`, `fixed`) from the same starting places as Minecraft's, so Create's transforms
|
||||||
|
look the same. The wrench, potato cannon and extendo grip are drawn with theirs. Third person and left hand transforms
|
||||||
|
are dropped until bworld draws items there.
|
||||||
|
|
||||||
|
**R6. Connected textures** (P2). Create's casings, windows and vaults pick a tile from a sheet depending on which
|
||||||
|
neighbours are the same block (`foundation/block/connected/`: rectangle, horizontal, vertical and omni). It's done in
|
||||||
|
the chunk mesher, from a `connected` field on a block's textures that names the sheet and the kind. Generic: any mod's
|
||||||
|
glass can use it.
|
||||||
|
|
||||||
|
**R7. Block structure rendering** (P7). A contraption's blocks are meshed once by the chunk worker, as a small chunk of
|
||||||
|
their own, and drawn with the contraption's matrix each frame. Its moving parts (a drill on it, a bearing's shaft) are
|
||||||
|
instances drawn relative to it. A block change on it remeshes only it.
|
||||||
|
|
||||||
|
**R8. Render time** (P1, built). World ticks plus the partial tick, as a shader uniform and for client scripts. It's
|
||||||
|
`ClientLevel.ticks`, which doesn't jump with `/time`. Visuals get it in `on_frame`, and the shaders as `uniforms.time`
|
||||||
|
(`set_render_time`), wrapped every 24000 ticks so a 32 bit float stays precise. That's a whole number of turns at any
|
||||||
|
speed in steps of 0.05 rpm, so those don't jump when it wraps.
|
||||||
|
|
||||||
|
**R9. Particles** (P3). A simple GPU particle system: sprite, velocity, gravity, lifetime. Used for rotation indicators,
|
||||||
|
crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it can come late.
|
||||||
|
|
||||||
|
**R10. In-world text and boxes** (P3). Create's value boxes (the number on a scroll value, filter slots on a block's
|
||||||
|
side) and goggles' overlay. A small API for drawing a label or an item at a point in the world, and a HUD element API,
|
||||||
|
which is in bworld's types but throws today. Setting a scroll value is built, the way 0.5.0.j does it: a block with
|
||||||
|
`"scrollable": true` gets the mouse wheel as `on_scroll`, and `send_message(text, { overlay: true })` shows the value
|
||||||
|
above the hotbar until the box can show it (see [Scrolling](docs/modding/blocks/components.md#scrolling)).
|
||||||
|
|
||||||
|
**R11. 3D in GUIs** (P3). Drawing a model or block in a screen, turned and animated, for the recipe viewer's Create
|
||||||
|
categories (a press pressing over its recipe, like `compat/jei`), goggles and ponder.
|
||||||
|
|
||||||
|
### Server and Gameplay
|
||||||
|
|
||||||
|
**S0. Ticking only what ticks** (P1, built). `ServerWorld` keeps the tiles that tick per chunk, so `GameServer.tick`
|
||||||
|
only looks at the chunks near players instead of every tile in the world. A component turns ticking off and on for one
|
||||||
|
block with `block.set_ticking(false)`, or `ctx.world.set_block_ticking(x, y, z, true)` from elsewhere, like returning no
|
||||||
|
ticker in NeoForge, and it stays off through saving. A shaft has tile data and never ticks. A press only ticks while
|
||||||
|
pressing.
|
||||||
|
|
||||||
|
**S1. Block capabilities** (P3). `ctx.capabilities.register_block("items", block_id, (block, side) => handler)` and
|
||||||
|
`ctx.world.capability("items", x, y, z, side)`, like NeoForge's `BlockCapability`. Handlers insert, extract, report
|
||||||
|
slots, and simulate. Chests and furnaces get them in `mods/bworld`. Funnels, chutes, arms, deployers, belts and vaults
|
||||||
|
all move items only through this.
|
||||||
|
|
||||||
|
**S2. Fluids** (P5). A fluid registry (bworld's water and lava, plus mods' own like Create's honey and chocolate), fluid
|
||||||
|
stacks with amounts in millibuckets, a `"fluids"` capability, and fluid containers in items (buckets, bottles).
|
||||||
|
|
||||||
|
**S3. Redstone** (P6, or earlier for clutches). A signal API in the engine (each block side has a power level 0 to 15,
|
||||||
|
`get_signal`, `has_neighbor_signal`, updates to neighbours) and the basic blocks in `mods/bworld`: lever, button, dust,
|
||||||
|
torch, repeater, comparator, lamp. Create reads and makes signals in about 40 blocks, and bworld has no redstone at all
|
||||||
|
today.
|
||||||
|
|
||||||
|
**S4. Machines acting on the world** (P3, built).
|
||||||
|
|
||||||
|
- `fluid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans.
|
||||||
|
- Item entities in a box, which can be changed and removed, for the press, fans and belts picking items up.
|
||||||
|
- Pushing entities, for fans.
|
||||||
|
- Breaking a block over time with progress shown, and its drops, for drills and saws.
|
||||||
|
- A fake player using an item on a block, for the deployer (`DeployerFakePlayer`).
|
||||||
|
|
||||||
|
As built, all in `ctx.world` (see the modding docs for each): `fluid_flow`, `entities_in(from, to, type?)` with
|
||||||
|
`EntityRef.get_item`, `set_item`, `velocity` and `push`, `spawn_item` for an item lying still where it's put (the
|
||||||
|
press's extra results), and `player.push`, which is sent to their client since it moves them. `set_break_progress` shows
|
||||||
|
cracks to the players who have the chunk, sending only a change of stage, and `ctx.blocks.toughness` gives what breaking
|
||||||
|
time is measured against. `break_block` takes `harvest` (drops what the right tool would, like
|
||||||
|
`BlockHelper.destroyBlockAs` ignoring tool requirements) and `collect` (returns the drops without dropping them), and
|
||||||
|
returns the drops. `use_item_on(item, x, y, z, face)` runs a player's whole right click (the block's `on_interact`, the
|
||||||
|
item's `on_use`, placing) as one `[machine]` player that's never online, standing in front of the face, and returns what
|
||||||
|
it holds after and anything it was given. The deployer's left click (punching and breaking) isn't there yet, and neither
|
||||||
|
is a fan pushing players on their client every tick, which Create does on both sides.
|
||||||
|
|
||||||
|
**S5. Scripted entities** (P7). Mods can define an entity's behaviour in server scripts (tick, data, interaction) and
|
||||||
|
how it's drawn in client scripts. Needed for the contraption entity, seats, potato cannon projectiles, trains and
|
||||||
|
packages.
|
||||||
|
|
||||||
|
**S6. Block structure entities** (P7). An entity that carries a grid of blocks with their states and tile data, moved
|
||||||
|
and turned as a whole: assembled from the world and put back, saved, and synced. Players and mobs stand on it and bump
|
||||||
|
into it as it moves (Create's `ContraptionCollider`, about 1000 lines, is the hardest part), and they can point at and
|
||||||
|
use its blocks. Generic: boats with decks, falling structures and elevators would all use it.
|
||||||
|
|
||||||
|
**S7. Player API additions** (P1, built). `player.is_sneaking()` on the server and in client scripts, and `sneaking` in
|
||||||
|
placement and interaction rules, for blocks like `DirectionalKineticBlock` that sneaking places the other way round.
|
||||||
|
Like Minecraft's secondary use, sneaking with an item in hand skips the clicked block's interactions and uses or places
|
||||||
|
the item, and an item's `on_use` gets the block it was used on, for the wrench's pickup. Reach is the
|
||||||
|
`cubi:block_interaction_range` and `cubi:entity_interaction_range` attributes, which clients aim with, so the extendo
|
||||||
|
grip is a modifier while it's held. `player.start_using(ticks)` uses an item over time, with `on_use_tick`,
|
||||||
|
`on_release_using` and `on_finish_using`, for the sand paper, builder's tea and packages. The potato cannon and wands
|
||||||
|
are plain uses, but their reload needs item cooldowns (Minecraft's `getCooldowns`, shown on the hotbar), which aren't
|
||||||
|
built.
|
||||||
|
|
||||||
|
**S8. Sound** (P3). Web Audio, positional, with sound events defined in data. bworld has no sound at all yet. Create's
|
||||||
|
whistles, presses, cranks and trains want it, but nothing breaks without it.
|
||||||
|
|
||||||
|
**S9. More recipe types in bworld** (P0). `shapeless` crafting (Create's cogwheels and many others), stonecutting
|
||||||
|
(palettes have hundreds of stonecutting recipes, and the mechanical saw uses them), and smoking and blasting for fans.
|
||||||
|
Stonecutting is built, as `bworld:stonecutting` with the stonecutter, and the saw reads the same recipes with
|
||||||
|
`ctx.recipes.list("bworld:stonecutting")`.
|
||||||
|
|
||||||
|
**S10. Block shape families in bworld** (P10). Stairs, slabs and walls don't exist in bworld yet, and Create's palettes
|
||||||
|
are mostly those. They're components with placement rules in `mods/bworld`, like the fence and trapdoor.
|
||||||
|
|
||||||
|
**S11. Layered ore features** (P2). Create's striated ores are bands of stone types, not blobs. A worldgen feature in
|
||||||
|
`mods/create/scripts/worldgen.ts`, or a data feature if those exist by then. Zinc is a plain ore in `ores.json`.
|
||||||
|
|
||||||
|
**S12. Mod config** (P1, built). A mod's settings and their defaults in its `config.json`, which the server script reads
|
||||||
|
as `ctx.config` from `setup` on, like NeoForge's server configs. A server changes them in `config/<mod id>.json` next to
|
||||||
|
`server_mods/`, setting by setting, and a setting the mod doesn't have or a value of the wrong kind stops it from
|
||||||
|
starting. Players' copies of a mod leave the config out, so what clients need is sent like any other server data. Tests
|
||||||
|
change settings with `test_game`'s fourth argument. Create's stress values, speed limits and processing times go there
|
||||||
|
as the machines that use them are built.
|
||||||
|
|
||||||
|
**S13. NBT** (P11). Reading and writing structure NBT, for schematics and ponder scenes.
|
||||||
|
|
||||||
|
**S14. Uploading files** (P11). A client sending a file to the server in pieces over a mod channel, for schematics.
|
||||||
|
|
||||||
|
## Recipes
|
||||||
|
|
||||||
|
All 19 of Create's types, plus the vanilla types its data uses:
|
||||||
|
|
||||||
|
| Type | Count | Made by | Phase |
|
||||||
|
| ----------------------------------------------------- | ----- | ------------------------------------------- | ----------------------- |
|
||||||
|
| `crafting` (shaped/shapeless) | 369 | crafting grid | P0 |
|
||||||
|
| `stonecutting` | 327 | stonecutter (S9), mechanical saw | P3 |
|
||||||
|
| `smelting`, `blasting`, `smoking`, `campfire_cooking` | 64 | furnace, fans | P3 |
|
||||||
|
| `pressing` | 43 | mechanical press | P3 |
|
||||||
|
| `milling` | 246 | millstone | P3 |
|
||||||
|
| `crushing` | 211 | crushing wheels | P3 |
|
||||||
|
| `cutting` | 32 | mechanical saw | P3 |
|
||||||
|
| `splashing`, `haunting` | 73 | encased fan through water or soul fire | P3 |
|
||||||
|
| `deploying` | 167 | deployer | P3 |
|
||||||
|
| `item_application` | 8 | using an item on a block | P3 |
|
||||||
|
| `sandpaper_polishing` | 1 | sand paper | P3 |
|
||||||
|
| `mixing`, `compacting` | 21 | mixer and press over a basin | P3 (items), P5 (fluids) |
|
||||||
|
| `mechanical_crafting` | 4 | mechanical crafters | P3 |
|
||||||
|
| `sequenced_assembly` | 3 | belts with presses, deployers, spouts, saws | P4 |
|
||||||
|
| `filling`, `emptying` | 24 | spout, item drain | P5 |
|
||||||
|
| `toolbox_dyeing`, `item_copying`, `conversion` | — | built-in, special | P9 |
|
||||||
|
|
||||||
|
Create's own types keep Create's shape inside bworld's envelope, but with bworld's item choices (an id, a `#tag`, or a
|
||||||
|
list of those any of which fits) in place of Java's `{ item }` and `{ tag }`, like every other recipe here:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"format_version": 1,
|
||||||
|
"recipe": {
|
||||||
|
"type": "create:pressing",
|
||||||
|
"ingredients": ["#c:ingots/iron"],
|
||||||
|
"results": [{ "id": "create:iron_sheet", "count": 1 }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`scripts/recipes/` parses all of them in one place: ingredients as item choices, or sized fluid ingredients; results as
|
||||||
|
`{ id, count, chance }` or fluid stacks; `processing_time` and `heat_requirement`. Built for pressing and compacting,
|
||||||
|
with fluid results as `{ fluid, amount }` but no fluid ingredients, durations or heat yet, in
|
||||||
|
`scripts/recipes/processing.ts`, which the server script runs in `setup`. It checks each type's input and output limits,
|
||||||
|
which come from each recipe class's `getMaxInputCount` and `getMaxOutputCount`. The recipe viewer gets one reader for
|
||||||
|
this shape, so every Create type shows with no per-type code, and animated categories (R11) are added per machine on
|
||||||
|
top.
|
||||||
|
|
||||||
|
## Kinetics
|
||||||
|
|
||||||
|
The core of everything, so its rules are written out here.
|
||||||
|
|
||||||
|
**What turns.** One component, `create:kinetic`, with params for which state holds the axis (`axis`, `facing`,
|
||||||
|
`horizontal_facing`), which ends have an axle, whether it's a small or large cog, and its stress impact. Generators add
|
||||||
|
`create:generator` with a capacity. Special connections (gearbox, chain drive, belt, speed controller) are named
|
||||||
|
handlers in `kinetics/connections.ts`.
|
||||||
|
|
||||||
|
**Connections**, with the ratio speed is multiplied by on the way across:
|
||||||
|
|
||||||
|
| Pair | Where | Ratio |
|
||||||
|
| -------------------- | --------------------------------------------------------------------------------- | ------------------------ |
|
||||||
|
| Axle to axle | Face neighbours along the axis, both with an axle toward each other | 1 |
|
||||||
|
| Small cog, small cog | Face neighbours, same axis, not along it | −1 |
|
||||||
|
| Large cog to small | Same axis, level along it, ±1 on both other axes | −2 (−0.5 the other way) |
|
||||||
|
| Large cog, large cog | Different axes, ±1 along both their axes, 0 on the third | ±1 by the offsets' signs |
|
||||||
|
| Gearbox | Turns each side, reversing by side, see `getAxisModifier` in `RotationPropagator` | ±1 |
|
||||||
|
| Chain drive | Along a line of chain drives, with the adjustable one's ratio | per block |
|
||||||
|
| Belt | Every segment of a belt turns with its two ends | 1 |
|
||||||
|
|
||||||
|
A large cog also looks at the 12 blocks diagonal to it along an edge. Cog placement rules (no large cog face to face
|
||||||
|
with any cog off its axis) and the axis a cog picks when placed are in `CogWheelBlock`.
|
||||||
|
|
||||||
|
**Spreading.** When a kinetic block is placed or a generator's speed changes, its speed spreads to what it's connected
|
||||||
|
to. If a neighbour already turns the other way, or the speed passes 256 rpm, the changed block breaks. A faster
|
||||||
|
neighbour takes over this block, and a faster block takes over its neighbour's tree. In a loop, a speed that doesn't
|
||||||
|
match breaks the block. Removing a block clears the tree it was the source of and spreads again from what's left powered
|
||||||
|
at its edge. Both walks use a queue, not recursion. Rules from `RotationPropagator`.
|
||||||
|
|
||||||
|
**Stress.** A network's capacity is the sum of each generator's capacity × |rpm|, and its stress the sum of each block's
|
||||||
|
impact × |rpm|. When stress is more than capacity, every block in it acts still and is drawn still. The network is found
|
||||||
|
by walking connections when something changes, never per tick. Values come from `BlockStressValues` and config defaults,
|
||||||
|
into `config.json`.
|
||||||
|
|
||||||
|
**What the client gets.** Each kinetic block's rpm and whether its network is overstressed, in client data (R1). Its
|
||||||
|
visual makes a `rotating` instance with the axis, rpm and an offset that keeps cog teeth meshed. The offset is 22.5°
|
||||||
|
when the block's coordinates on the two axes that aren't its axis add up to an even number, otherwise 11.25° for large
|
||||||
|
cogs and 0 for the rest. A speed change updates one instance, and nothing else happens per frame.
|
||||||
|
|
||||||
|
**As built** (`scripts/kinetics/`: the shaft, both cogwheels and the hand crank). `create:kinetic` takes `axis` (the
|
||||||
|
state with x, y or z) or `facing` (the state with the 6 faces), `shaft` (`both`, `front` or `back`) and `cog` (`small`
|
||||||
|
or `large`), and its shared rules place blocks like `RotatedPillarKineticBlock`, `DirectionalKineticBlock` and
|
||||||
|
`CogWheelBlock`, lining up with an axle or cog beside them. A cog that would cut into another isn't placed, like
|
||||||
|
`isValidCogwheelPosition`, by `state_for_placement` returning `false`. Connections are the table's first four rows.
|
||||||
|
Spreading is `RotationPropagator`'s, with queues: a block's speed is its `speed` client data, and the block it gets it
|
||||||
|
from and the generator it comes from (`source` and `network`) are tile data. Two things differ: on_break runs while the
|
||||||
|
block is still there, so the walk after a removal treats its place as empty, and generators that stop with what turned
|
||||||
|
them start again right after the walk instead of a tick later (`reActivateSource`). Create's flicker score and its
|
||||||
|
periodic `validateKinetics` aren't ported, since shafts don't tick. `create:hand_crank` turns while it's clicked, for 10
|
||||||
|
ticks after each click, the other way while sneaking, and costs hunger by the config's `crank_hunger`. Its visual turns
|
||||||
|
the half shaft as a `rotating` instance and eases the handle in `on_frame`, like `HandCrankVisual`. A large cog is drawn
|
||||||
|
as its shaftless model and a separate shaft, offset apart, like `LargeCogVisual`. The crank doesn't pop off when its
|
||||||
|
block is taken away yet, and cogs have no placement helper (`CogwheelBlockItem`'s ghost offsets). It needed four engine
|
||||||
|
additions: `looking` in `state_for_placement` (`getNearestLookingDirection`), `false` from it to not place
|
||||||
|
(`getStateForPlacement` returning null), `ctx.blocks` in shared scripts, and `ctx.world.get_block_ref` for changing
|
||||||
|
another block's data (`getBlockEntity`).
|
||||||
|
|
||||||
|
**Stress as built** (`scripts/kinetics/stress.ts`). Impacts and capacities are the config's `stress.impact` and
|
||||||
|
`stress.capacity` by block id, like `CStress`, with Create's values for the blocks built so far, and 0 for a block that
|
||||||
|
isn't listed. A network is the blocks whose `network` is the same generator. Each change in `spreading.ts` notes the
|
||||||
|
networks it touched, and then each of them is walked from its generator and summed. Every block in one that's
|
||||||
|
overstressed gets `overstressed` client data, which `actual_speed` in `connections.ts` reads as still, for the press and
|
||||||
|
for visuals, like `getSpeed`. Speeds and spreading are unchanged by it. The totals aren't kept, since only the
|
||||||
|
stressometer will show them. Both a second generator joining a network and one in it stopping change its capacity
|
||||||
|
without changing any speed, so a generator's change always reworks its network.
|
||||||
|
|
||||||
|
**Generators as built** (`scripts/kinetics/generators.ts`). Each is a component with its speed in params, and a capacity
|
||||||
|
in the config. `create:creative_motor` turns from when it's placed, at a speed kept in its tile data. Scrolling the
|
||||||
|
mouse wheel at it (the block is `scrollable`, so it gets `on_scroll`) steps through speeds like 0.5's motor: by 1 near
|
||||||
|
0, then by 4, 16 and 64, by 1 while sneaking, skipping 0, within `max_speed`, and the speed shows above the hotbar.
|
||||||
|
Scrolling works anywhere on the block, not only on a value box, and there's no settings board like 6.0's. Its casing is
|
||||||
|
the block's model and its half shaft turns. `create:water_wheel` scores the fluid flowing past the 4 blocks around it
|
||||||
|
across its axis with `fluid_flow`, like `determineAndApplyFlowScore`, and turns at its speed whichever way the score
|
||||||
|
says. It scores again a tick after a neighbour changes, and every second for flow that changes without that (Create does
|
||||||
|
it every 3 seconds), so a wheel ticks once a second. It can't be placed beside another wheel unless they share an axle,
|
||||||
|
like `canSurvive`. The large water wheel isn't built, and neither is changing a wheel's planks.
|
||||||
|
|
||||||
|
**Transmission as built** (`connections.ts`, `chains.ts`). All of it is `create:kinetic` params, so the rules are data
|
||||||
|
and one function, `speed_ratio`, which takes the table's gearbox and chain drive rows now. `gearbox` puts an axle on the
|
||||||
|
4 sides around its axis, and `split` (`clutch` or `gearshift`) with `powered` names a 1 bit state. Both turn their axles
|
||||||
|
by `axis_modifier`, from the side their speed comes from (`getAxisModifier`), which the server keeps in their `source`
|
||||||
|
client data for their visuals' half shafts. A gearbox reverses what goes straight through it, like Create's. The clutch
|
||||||
|
and gearshift are powered by verdigris through `bworld:verdigris_input`, and any change to a kinetic block's states that
|
||||||
|
changes how it turns takes it out of its network and puts it back, like `areStatesKineticallyEquivalent` with
|
||||||
|
`detachKinetics` (straight away rather than a tick later). The vertical gearbox is an item that `places` the gearbox,
|
||||||
|
whose placing rule stands it on its side when `placement.item` is the vertical gearbox, and a loot table gives back the
|
||||||
|
item it was. Encased shafts are the shaft's rule with a casing model. Encased cogs are cogs with `shaft_states`, the 1
|
||||||
|
bit states for an axle out of each end. They have no item, like Create's: `create:encasable` on shafts and cogs turns
|
||||||
|
one right clicked with a casing into the encased one, keeping its axis, with an axle toward each axle beside it, and
|
||||||
|
both break into what was encased. Turning one back with a wrench waits for the wrench (P9). `chain` names a chain
|
||||||
|
drive's `part` and `axis_along_first` states, which `chain_update` keeps up to date on placing and on neighbour changes,
|
||||||
|
like `updateShape`. The adjustable chain gearshift also names a 4 bit `power` state, which the verdigris input fills
|
||||||
|
with how much power goes into it, for `chain_ratio`. The metal girder encased shaft waits for girders (P10).
|
||||||
|
|
||||||
|
**Chunk borders.** Tile data keeps speeds across unloading. bworld keeps every tile in memory and reloads a chunk when a
|
||||||
|
block in it is read, so the walk sees a whole network, and Create's separate count of unloaded members' stress
|
||||||
|
(`KineticNetwork`'s unloaded stress) isn't needed.
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
Each phase ends with every test passing and something to see and use in a world. Engine work (R and S) is listed where
|
||||||
|
it's first needed.
|
||||||
|
|
||||||
|
### P0: Importer and Skeleton
|
||||||
|
|
||||||
|
- S9 (`shapeless`), R5.
|
||||||
|
- The importer's other kinds, up to `mod`, and Create's remap file and block table in `mods/create/import/`.
|
||||||
|
- `mods/create` with every block and item imported, static models, names, recipes that only need crafting, tags.
|
||||||
|
|
||||||
|
Check: every Create block can be placed and looks right standing still, crafting recipes work, and the report lists
|
||||||
|
what's missing.
|
||||||
|
|
||||||
|
### P1: Kinetics
|
||||||
|
|
||||||
|
- S0, S7, S12, R1, R2, R3 (`transformed` and `rotating`), R4, R8.
|
||||||
|
- Shaft, cogwheel, large cogwheel, gearbox, vertical gearbox, encased shafts and cogs, clutch and gearshift (with a
|
||||||
|
placeholder signal until S3), chain drive and adjustable chain gearshift, rotation speed controller, speedometer and
|
||||||
|
stressometer.
|
||||||
|
- Generators: hand crank, valve handle, water wheel, large water wheel, creative motor.
|
||||||
|
- Kinetic network, stress and overstress.
|
||||||
|
|
||||||
|
Check: a water wheel drives a long shaft line through gearboxes and cog ratios, all turning smoothly on the GPU, and
|
||||||
|
1000 shafts cost nothing per frame and only a little per tick.
|
||||||
|
|
||||||
|
### P2: Materials and World
|
||||||
|
|
||||||
|
- S11, R6.
|
||||||
|
- Zinc ore, striated stone bands, andesite alloy, brass (made in P3's mixer), casings with connected textures.
|
||||||
|
|
||||||
|
Check: new worlds have zinc and Create's stones, and casings join up.
|
||||||
|
|
||||||
|
### P3: Processing
|
||||||
|
|
||||||
|
- S1, S4, S8, R9, R10, R11, and smoking and blasting from S9.
|
||||||
|
- Mechanical press, millstone, crushing wheels, mechanical saw, encased fan with its processing (washing, smoking,
|
||||||
|
blasting, haunting from `AllFanProcessingTypes`), deployer, mechanical crafters, item application, sand paper, depot,
|
||||||
|
basin, mixer and compacting (items only), blaze burner and its heat.
|
||||||
|
- Recipe viewer: Create's recipe format, catalysts, and animated categories.
|
||||||
|
|
||||||
|
Check: ores go through crushing, washing and smelting into more ingots than a furnace alone gives, and brass is mixed in
|
||||||
|
a heated basin.
|
||||||
|
|
||||||
|
As built so far: the mechanical press, pressing items lying on the ground under it (`PressingBehaviour`'s world mode, in
|
||||||
|
`scripts/processing/press.ts` and the server script). While it turns it looks for an item with a pressing recipe every
|
||||||
|
10 ticks, then runs its 240 step cycle at Create's speed for its rpm and presses at the bottom: a lone item turns into
|
||||||
|
its result, and from a stack one is pressed and its results land beside it, like `bulkPressing` off. It stops ticking
|
||||||
|
while it's still, and a kinetic block that starts turning ticks again. Clients get the step the cycle was at and its
|
||||||
|
rate as `press` client data whenever the rate changes, and the visual moves the head from those, so nothing is sent
|
||||||
|
while it runs at a steady speed. Pressing on belts, depots and basins, its stress impact, sound and particles come with
|
||||||
|
those.
|
||||||
|
|
||||||
|
The basin (`scripts/processing/basin.ts`) holds what Create's input inventory and tanks do: up to 9 kinds of item, a
|
||||||
|
stack of each, and 2 tanks of 1000 mB, a fluid each. An item that lands in it goes in through the engine's
|
||||||
|
`on_entity_stand`, like `updateEntityAfterFallOn`, so it doesn't tick. A full fluid container used on it empties into
|
||||||
|
it, an empty one fills from its first tank, and an empty hand takes every item out, like `BasinBlock.useItemOn`. What's
|
||||||
|
in it is only its `items` and `tanks` client data, and its visual draws them like `BasinRenderer`: the fluids side by
|
||||||
|
side, filling faster at first, and the items in a ring over them, bobbing while there's fluid. Water and lava buckets
|
||||||
|
aren't fluid containers in bworld, so they don't fill it yet. Its facing toward an output, and the item and fluid
|
||||||
|
capabilities (S1, S2), come with mixing and the logistics that move things in and out. For it the engine got
|
||||||
|
`on_entity_stand`, and an item inside a block only floats out of it when it's inside what it bumps into, like
|
||||||
|
Minecraft's `noCollision`, so items can lie in a hollow.
|
||||||
|
|
||||||
|
A press with a basin two blocks under it presses into the basin instead of on the ground, its head coming 22/16 of a
|
||||||
|
block down, like `PressingBehaviour`'s basin mode. Each cycle it makes the first `create:compacting` recipe that can be
|
||||||
|
made there, the ones with more ingredients first, like `BasinOperatingBlockEntity.getMatchingRecipes`, and it only
|
||||||
|
starts one when a recipe can be made. `apply_basin_recipe` in `processing/basin.ts` is `BasinRecipe.apply`: an item for
|
||||||
|
each ingredient from the basin's input items, item results into its outputs, which recipes don't take again, and fluid
|
||||||
|
results into its tanks, all or nothing. Outputs are its `outputs` client data, drawn and taken out by hand with the
|
||||||
|
rest. Unlike Create's, its input and output tanks are the same 2, since no recipe takes fluids yet. bworld's shared
|
||||||
|
script makes a compacting recipe for every juicing recipe while Create's press and basin are there, so the press makes
|
||||||
|
juice. Create's own 7 compacting recipes need fluid ingredients or Minecraft items, and aren't imported yet.
|
||||||
|
|
||||||
|
### P4: Logistics
|
||||||
|
|
||||||
|
- R3's `scrolling` type.
|
||||||
|
- Belts. A belt is a line of segments, and only its controller (its first segment) ticks, moving every item on it
|
||||||
|
(`BeltInventory`), like `BeltBlockEntity.isController`. Items on belts are instances drawn by the controller's visual.
|
||||||
|
- Funnels, brass and andesite tunnels, chutes and smart chutes, mechanical arm, item vaults (multiblock), filters and
|
||||||
|
attribute filters, sequenced assembly on belts.
|
||||||
|
|
||||||
|
Check: a sorting line with funnels, filters and an arm, and a precision mechanism made by sequenced assembly.
|
||||||
|
|
||||||
|
### P5: Fluids
|
||||||
|
|
||||||
|
- S2, R3's `fluid` type.
|
||||||
|
- Fluid pipes, encased and glass pipes, mechanical pump, fluid tanks (multiblock), spout, item drain, hose pulley,
|
||||||
|
portable fluid interface, basins with fluids, mixing and compacting with fluids, filling and emptying.
|
||||||
|
- Pipes are networks found by walking pipes from a pump when something changes (`FluidPropagator`, `FluidNetwork`).
|
||||||
|
Fluid only moves while a pump runs, and a network with no running pump doesn't tick.
|
||||||
|
- Steam engine and boilers on tanks (`BoilerData`), which are fluids plus heat plus kinetics.
|
||||||
|
|
||||||
|
Check: a steam engine on a tank boiler, fed by a pump from water and heated by blaze burners, drives a factory.
|
||||||
|
|
||||||
|
### P6: Redstone
|
||||||
|
|
||||||
|
- S3, in `mods/bworld` first.
|
||||||
|
- Redstone link, nixie tube, display link and display board, threshold switch, smart observer, analog lever, pulse
|
||||||
|
extender and timer, powered latch and toggle latch, contact, desk bell, sequenced gearshift. The pulse repeater is
|
||||||
|
bworld's now. Clutch and gearshift switch to real signals.
|
||||||
|
|
||||||
|
Check: a factory that stops when a vault is full and shows its count on a display board.
|
||||||
|
|
||||||
|
### P7: Contraptions
|
||||||
|
|
||||||
|
- S5, S6, R7.
|
||||||
|
- Mechanical bearing, windmill bearing with sails, clockwork bearing, mechanical piston, rope pulley, elevator pulley
|
||||||
|
and contacts, gantry carriage, linear and radial chassis, super glue, contraption controls.
|
||||||
|
- Actors, which act as their contraption moves (`AllMovementBehaviours`): drill, saw, harvester, plough, roller,
|
||||||
|
deployer, seats, storage, portable interfaces.
|
||||||
|
- Minecart contraptions need minecarts and rails, which bworld doesn't have. They wait until bworld has them, and the
|
||||||
|
cart assembler with them.
|
||||||
|
|
||||||
|
Check: a windmill turns, a drill on a piston mines a wall, and a player rides an elevator.
|
||||||
|
|
||||||
|
### P8: Trains
|
||||||
|
|
||||||
|
- Train tracks and curved tracks, which are drawn as meshes made along their curves, not blocks.
|
||||||
|
- The track graph (`TrackGraph`, `GlobalRailwayManager`), saved with the world, and train movement along it.
|
||||||
|
- Bogeys, stations, assembly, signals and edge groups, schedules, train controls and HUD, train observers, displays.
|
||||||
|
- A train is a block structure entity (S6) that follows the graph instead of moving freely.
|
||||||
|
|
||||||
|
Check: a scheduled train runs between two stations through signals.
|
||||||
|
|
||||||
|
### P9: Equipment
|
||||||
|
|
||||||
|
- Wrench (turning blocks, and picking them up with sneaking), goggles and the overlay (R10), extendo grip, potato
|
||||||
|
cannon, symmetry wand, toolbox, copper backtank and diving gear (air under water), clipboard, blueprint, worldshaper,
|
||||||
|
and Create's armor.
|
||||||
|
|
||||||
|
### P10: Decoration
|
||||||
|
|
||||||
|
- S10.
|
||||||
|
- Palettes (stone types in cut, polished, bricks, small bricks, layered and pillar, each as block, stairs, slab and
|
||||||
|
wall), windows and panes (connected glass), girders and brackets, scaffolding, ladders, bars, doors, sliding and
|
||||||
|
framed doors, placards, table cloths, copycats.
|
||||||
|
- Copycats show another block's texture in their own shape, which needs a model built from tile data. They come last.
|
||||||
|
|
||||||
|
### P11: Schematics
|
||||||
|
|
||||||
|
- S13, S14.
|
||||||
|
- Schematic and quill, schematic table with uploads, schematicannon placing from a schematic with its fuel and
|
||||||
|
materials.
|
||||||
|
|
||||||
|
### P12: Package Logistics (6.0)
|
||||||
|
|
||||||
|
- Packager, repackager, frogport, chain conveyor, stock link and ticker, redstone requester, factory gauge, shop table
|
||||||
|
cloths, cardboard.
|
||||||
|
- All new art, see [Sources](#sources).
|
||||||
|
|
||||||
|
### P13: Ponder
|
||||||
|
|
||||||
|
- A scene player: a small world from a scene's NBT, drawn in a screen (R11), with Create's scene scripts
|
||||||
|
(`infrastructure/ponder/scenes/`) ported to run its steps. 0.5.0.j has 153 scene files.
|
||||||
|
- The `W` key over an item opens its scenes.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tests/create/`, a file per subsystem, with `test_game` from `tests/helpers.ts`. Each phase's check becomes tests:
|
||||||
|
|
||||||
|
- **Rules from plain functions:** connection ratios, recipe parsing, belt item movement, pipe flow.
|
||||||
|
- **Machines in a world:** an input goes in, the right output comes out, and nothing happens without power.
|
||||||
|
- **Networks:** placing and breaking in the middle of a line; two generators fighting; overstress.
|
||||||
|
- **Performance:** a tick with 10,000 shafts, and a frame's instance updates, stay under a budget. These are benchmarks
|
||||||
|
(`deno bench`), not tests, so a slow machine doesn't fail CI.
|
||||||
|
|
||||||
|
Following CLAUDE.md, tests check behaviour and not tuned numbers, except where the number is the point, like a 2:1 cog
|
||||||
|
ratio. Recipes come from the imported data, so tests use Create's recipes instead of copying them.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
- **Minecraft content Create assumes:** blazes (the blaze burner captures one), soul fire (haunting), the Nether and the
|
||||||
|
End (crushing and haunting recipes), minecarts and rails (cart contraptions, controller rails), honey and chocolate as
|
||||||
|
fluids, dyes. Add them to bworld, substitute them in Create's remap file, or drop what needs them?
|
||||||
|
- **Unloaded chunks:** blocks only tick within 6 chunks of a player. Do factories need a way to stay loaded, like chunk
|
||||||
|
loaders, or is "near a player" fine for bworld?
|
||||||
|
- **Contraption collision:** port `ContraptionCollider`'s approach, or write a simpler one for bworld's physics
|
||||||
|
(`common/physics.ts`) that handles turning structures differently?
|
||||||
|
- **Trains before or after contraptions:** trains reuse S6, but they're also the most-loved part of Create. Is P8 worth
|
||||||
|
moving earlier?
|
||||||
|
- **6.0's package logistics:** new art for about 20 blocks. Port them, or leave Create at 0.5's logistics?
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# Making bworld Mods
|
||||||
|
|
||||||
|
Mods add blocks, items, entities, recipes, world generation, game logic and screens to bworld. A mod is installed **on
|
||||||
|
the server**. Players who join download its client code, data and textures from that server automatically, so they never
|
||||||
|
install anything themselves.
|
||||||
|
|
||||||
|
The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your
|
||||||
|
mod can do, and it's the best place to look for examples.
|
||||||
|
|
||||||
|
A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from one
|
||||||
|
TypeScript script, whose exports are its phases: `server` for game logic, `client` for what players see, and `worldgen`
|
||||||
|
for terrain features.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod
|
||||||
|
deno task check-mods # checks every mod in mods/
|
||||||
|
deno task build && deno task server # packs the mods and starts a server with them
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
**Getting started**
|
||||||
|
|
||||||
|
- [Getting Started](docs/modding/gettingstarted/index.md): making, checking, running and testing a mod
|
||||||
|
- [Mod Files](docs/modding/gettingstarted/modfiles.md): the folder layout, `manifest.json`, scripts and `.cubi` files
|
||||||
|
|
||||||
|
**Concepts**
|
||||||
|
|
||||||
|
- [Sides](docs/modding/concepts/sides.md): what runs on the server and what runs on players' clients
|
||||||
|
- [Registries](docs/modding/concepts/registries.md): ids, namespaces and how mods load
|
||||||
|
- [Events](docs/modding/concepts/events.md): reacting to and cancelling what players do
|
||||||
|
- [Security](docs/modding/concepts/security.md): what servers and players trust
|
||||||
|
|
||||||
|
**Blocks**
|
||||||
|
|
||||||
|
- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement
|
||||||
|
- [Block States](docs/modding/blocks/states.md): state bits, variants and facing
|
||||||
|
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from the server phase
|
||||||
|
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
|
||||||
|
show items
|
||||||
|
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
|
||||||
|
machine
|
||||||
|
- [Crops](docs/modding/blocks/crops.md): farming without writing code
|
||||||
|
- [Verdigris](docs/modding/blocks/verdigris.md): blocks that make and use signals, like levers, torches and doors
|
||||||
|
|
||||||
|
**Items**
|
||||||
|
|
||||||
|
- [Items](docs/modding/items/index.md): items, item stacks and item components
|
||||||
|
- [Tools](docs/modding/items/tools.md): tool types, tiers and durability
|
||||||
|
- [Food](docs/modding/items/food.md): hunger and saturation
|
||||||
|
|
||||||
|
**Entities**
|
||||||
|
|
||||||
|
- [Entities](docs/modding/entities/index.md): animals, monsters, custom behaviors and their goals, how mobs get around,
|
||||||
|
natural spawning, scripted entities, entity models and their animations
|
||||||
|
- [Players](docs/modding/entities/players.md): the player API, health and hunger
|
||||||
|
|
||||||
|
**Inventories**
|
||||||
|
|
||||||
|
- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves
|
||||||
|
- [Menus](docs/modding/inventories/menus.md): slots, data and buttons on the server, and their screens
|
||||||
|
|
||||||
|
**Resources**
|
||||||
|
|
||||||
|
- [Textures](docs/modding/resources/textures.md)
|
||||||
|
- [Sounds](docs/modding/resources/sounds.md): sound files, and playing them on a player's client
|
||||||
|
- [Block Models](docs/modding/resources/models.md)
|
||||||
|
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
|
||||||
|
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
|
||||||
|
- [Loot Tables](docs/modding/resources/loot_tables.md): what blocks, mobs, fishing and chests give
|
||||||
|
- [Fluids](docs/modding/resources/fluids.md): fluids that can be held, apart from blocks that flow, and the fluid
|
||||||
|
handlers that tanks and containers are filled and drained through
|
||||||
|
|
||||||
|
**Everything else**
|
||||||
|
|
||||||
|
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
||||||
|
- [Biomes](docs/modding/worldgen/biomes.md): surfaces, colors and seasons
|
||||||
|
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
|
||||||
|
- [HUD](docs/modding/gui/hud.md): layers drawn over the world, like the base game's hotbar and hearts
|
||||||
|
- [Networking](docs/modding/networking/index.md): how players get mods and the world
|
||||||
|
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
|
||||||
|
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
|
||||||
|
- [Commands](docs/modding/misc/commands.md)
|
||||||
|
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
|
||||||
|
- [Schematics](docs/modding/misc/schematics.md): saving a box of the world, blocks, data and entities, to a file
|
||||||
|
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
|
||||||
|
doesn't cover yet
|
||||||
|
|
||||||
|
## API Types
|
||||||
|
|
||||||
|
The API types are the reference for everything scripts can call. Scripts import them as `cubi/server`, `cubi/client`,
|
||||||
|
`cubi/shared`, `cubi/worldgen` and `cubi/content`, and they live in [`common/mod_api/`](common/mod_api/).
|
||||||
|
|
||||||
|
A few parts of those types aren't built yet and throw when used: forms, custom screens and keybinds.
|
||||||
|
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
|
||||||
@@ -1,64 +1,16 @@
|
|||||||
shout out to kenney
|
|
||||||
|
|
||||||
# Tiny town
|
|
||||||
|
|
||||||
https://kenney.nl/assets/tiny-town
|
|
||||||
|
|
||||||
license: [Creative Commons CC0](https://creativecommons.org/publicdomain/zero/1.0/)
|
|
||||||
|
|
||||||
# Roguelike
|
|
||||||
|
|
||||||
https://kenney.nl/assets/roguelike-rpg-pack
|
|
||||||
|
|
||||||
license: [Creative Commons CC0](https://creativecommons.org/publicdomain/zero/1.0/)
|
|
||||||
|
|
||||||
# UI
|
# UI
|
||||||
|
|
||||||
https://kenney.nl/assets/ui-pack-pixel-adventure
|
Catppuccin UI (Mocha, pink accent), with AppleSkin's saturation icons from the same pack. Packed into `sprites/gui.png`
|
||||||
|
by `tools/pack_gui.ts`
|
||||||
|
|
||||||
license: [Creative Commons CC0](https://creativecommons.org/publicdomain/zero/1.0/)
|
https://github.com/catppuccin/minecraft
|
||||||
|
|
||||||
# m6x11.ttf
|
|
||||||
|
|
||||||
Font by Daniel Linssen (https://managore.itch.io)
|
|
||||||
|
|
||||||
https://managore.itch.io/m6x11 (https://web.archive.org/web/20260217032856/https://managore.itch.io/m6x11)
|
|
||||||
|
|
||||||
license: `free to use with attribution`
|
|
||||||
|
|
||||||
# Tiny wonder farm
|
|
||||||
|
|
||||||
https://butterymilk.itch.io/tiny-wonder-farm-asset-pack
|
|
||||||
(https://web.archive.org/web/20260204234306/https://butterymilk.itch.io/tiny-wonder-farm-asset-pack)
|
|
||||||
|
|
||||||
license:
|
license:
|
||||||
|
|
||||||
```
|
|
||||||
There's two versions, free and paid (premium):
|
|
||||||
|
|
||||||
Free: It includes a limited number of items available for free.
|
|
||||||
|
|
||||||
You are free to use sprites included in the pack in any of your non-commercial projects as well as edit the sprites and
|
|
||||||
add something new!
|
|
||||||
|
|
||||||
Premium: It includes everything shown from the showcase, all tilemaps, sprites, characters and more!
|
|
||||||
|
|
||||||
You are free to use sprites included in the pack in any of your commercial or non-commercial projects as well as edit
|
|
||||||
the sprites and add something new!
|
|
||||||
|
|
||||||
You can't resell the sprites, even if changes were made. You cannot use it in any projects related to NFT."
|
|
||||||
```
|
|
||||||
|
|
||||||
# Farmer's delight
|
|
||||||
|
|
||||||
https://github.com/vectorwing/FarmersDelight
|
|
||||||
|
|
||||||
License:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2020 vectorwing
|
Copyright (c) 2022 Catppuccin
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -78,3 +30,44 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# Fluid slot
|
||||||
|
|
||||||
|
The droplet in the `fluid_slot` sprite of `sprites/gui.png` is Modern Industrialization's, from its fluid slots, drawn
|
||||||
|
over the UI's slot by hand.
|
||||||
|
|
||||||
|
https://github.com/AztechMC/Modern-Industrialization
|
||||||
|
|
||||||
|
license:
|
||||||
|
|
||||||
|
```
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2020 Azercoco & Technici4n
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
```
|
||||||
|
|
||||||
|
# m6x11.ttf
|
||||||
|
|
||||||
|
Font by Daniel Linssen (https://managore.itch.io)
|
||||||
|
|
||||||
|
https://managore.itch.io/m6x11 (https://web.archive.org/web/20260217032856/https://managore.itch.io/m6x11)
|
||||||
|
|
||||||
|
license: `free to use with attribution`
|
||||||
|
|||||||
|
After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 662 B |
|
Before Width: | Height: | Size: 232 B |
|
Before Width: | Height: | Size: 230 B |
|
Before Width: | Height: | Size: 251 B |
|
Before Width: | Height: | Size: 275 B |
|
Before Width: | Height: | Size: 416 B |
|
Before Width: | Height: | Size: 223 B |
|
Before Width: | Height: | Size: 221 B |
|
Before Width: | Height: | Size: 312 B |
|
Before Width: | Height: | Size: 257 B |
|
Before Width: | Height: | Size: 157 B |
|
Before Width: | Height: | Size: 156 B |
|
Before Width: | Height: | Size: 406 B |
|
Before Width: | Height: | Size: 175 B |
|
Before Width: | Height: | Size: 447 B |
|
Before Width: | Height: | Size: 317 B |
|
Before Width: | Height: | Size: 218 B |
|
Before Width: | Height: | Size: 177 B |
|
Before Width: | Height: | Size: 177 B |
|
Before Width: | Height: | Size: 215 B |
|
Before Width: | Height: | Size: 232 B |
|
Before Width: | Height: | Size: 199 B |
|
Before Width: | Height: | Size: 343 B |
|
Before Width: | Height: | Size: 208 B |
|
Before Width: | Height: | Size: 236 B |
|
Before Width: | Height: | Size: 215 B |
|
Before Width: | Height: | Size: 205 B |
|
Before Width: | Height: | Size: 266 B |
|
Before Width: | Height: | Size: 350 B |
|
Before Width: | Height: | Size: 340 B |
|
Before Width: | Height: | Size: 262 B |
|
Before Width: | Height: | Size: 241 B |
|
Before Width: | Height: | Size: 264 B |
|
Before Width: | Height: | Size: 466 B |
|
Before Width: | Height: | Size: 466 B |
|
Before Width: | Height: | Size: 504 B |
|
Before Width: | Height: | Size: 478 B |
|
Before Width: | Height: | Size: 215 B |
|
Before Width: | Height: | Size: 429 B |
|
Before Width: | Height: | Size: 376 B |
|
Before Width: | Height: | Size: 172 B |
|
Before Width: | Height: | Size: 428 B |
|
Before Width: | Height: | Size: 237 B |
|
Before Width: | Height: | Size: 119 B |
|
Before Width: | Height: | Size: 274 B |
|
Before Width: | Height: | Size: 269 B |
|
Before Width: | Height: | Size: 159 B |
|
Before Width: | Height: | Size: 216 B |
|
Before Width: | Height: | Size: 123 B |
|
Before Width: | Height: | Size: 170 B |
|
Before Width: | Height: | Size: 222 B |
|
Before Width: | Height: | Size: 251 B |
|
Before Width: | Height: | Size: 221 B |
|
Before Width: | Height: | Size: 3.6 KiB |
@@ -1,11 +1,30 @@
|
|||||||
import { copy } from "@std/fs";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { copy, walk } from "@std/fs";
|
||||||
|
import { relative } from "@std/path";
|
||||||
|
import { PROTOCOL_VERSION } from "./common/protocol.ts";
|
||||||
|
import { CLIENT_MANIFEST, client_manifest } from "./desktop/client_updates.ts";
|
||||||
|
import { sha256 } from "./common/utils.ts";
|
||||||
import { createCanvas, loadImage } from "@gfx/canvas-wasm";
|
import { createCanvas, loadImage } from "@gfx/canvas-wasm";
|
||||||
|
import { ENGINE_TEXTURE_DIR, load_and_check, load_order, LoadedMod } from "./tools/check_mods.ts";
|
||||||
|
import { pack_mod } from "./tools/pack_mod.ts";
|
||||||
|
import { MOD_EXTENSION } from "./common/mod.ts";
|
||||||
|
import { ENGINE_TEXTURES_INDEX } from "./server/host.ts";
|
||||||
|
|
||||||
const BUILD_FOLDER = "build";
|
// all overridable so tests can build somewhere else
|
||||||
|
const BUILD_FOLDER = Deno.env.get("BUILD_DIR") ?? "build";
|
||||||
|
const MODS_FOLDER = Deno.env.get("MODS_DIR") ?? "mods";
|
||||||
|
// where the server loads .cubi files from. the build puts every mod in mods/ there, next to any others
|
||||||
|
const SERVER_MODS_FOLDER = Deno.env.get("SERVER_MODS_DIR") ?? "server_mods";
|
||||||
|
|
||||||
function clear_folder() {
|
function clear_folder(folder: string) {
|
||||||
Deno.removeSync(BUILD_FOLDER, { recursive: true });
|
try {
|
||||||
Deno.mkdirSync(BUILD_FOLDER);
|
Deno.removeSync(folder, { recursive: true });
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof Deno.errors.NotFound)) throw e;
|
||||||
|
}
|
||||||
|
Deno.mkdirSync(folder, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function build_fonts() {
|
async function build_fonts() {
|
||||||
@@ -42,108 +61,129 @@ async function build_fonts() {
|
|||||||
await copy("assets/fonts/m6x11.fnt", `${BUILD_FOLDER}/assets/fonts/m6x11.fnt`);
|
await copy("assets/fonts/m6x11.fnt", `${BUILD_FOLDER}/assets/fonts/m6x11.fnt`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function next_power_of_two(value: number): number {
|
|
||||||
return Math.pow(2, Math.ceil(Math.log2(value)));
|
|
||||||
}
|
|
||||||
|
|
||||||
const SPRITE_SIZE = 16;
|
|
||||||
|
|
||||||
function calculate_atlas_size(count: number) {
|
|
||||||
const raw_sprites_per_side = Math.ceil(Math.sqrt(count));
|
|
||||||
const raw_size = raw_sprites_per_side * SPRITE_SIZE;
|
|
||||||
const size = next_power_of_two(raw_size);
|
|
||||||
|
|
||||||
return {
|
|
||||||
sprites_per_side: size / SPRITE_SIZE,
|
|
||||||
size,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function build_atlas_from_folder(folder: string) {
|
|
||||||
let sprite_count = 0;
|
|
||||||
for (const entry of Deno.readDirSync(folder)) {
|
|
||||||
console.assert(entry.isFile && entry.name.endsWith(".png"));
|
|
||||||
sprite_count += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const atlas = calculate_atlas_size(sprite_count);
|
|
||||||
|
|
||||||
const canvas = createCanvas(atlas.size, atlas.size);
|
|
||||||
const ctx = canvas.getContext("2d");
|
|
||||||
|
|
||||||
const atlas_info: Record<string, { x: number; y: number }> = {};
|
|
||||||
|
|
||||||
// purple and black missing texture at x:0 y:0 wow !
|
|
||||||
ctx.fillStyle = "magenta";
|
|
||||||
ctx.fillRect(0, 0, 8, 8);
|
|
||||||
ctx.fillRect(8, 8, 8, 8);
|
|
||||||
ctx.fillStyle = "black";
|
|
||||||
ctx.fillRect(8, 0, 8, 8);
|
|
||||||
ctx.fillRect(0, 8, 8, 8);
|
|
||||||
|
|
||||||
let index = 1;
|
|
||||||
for (const entry of Deno.readDirSync(folder)) {
|
|
||||||
const sprite = await loadImage(`${folder}/${entry.name}`);
|
|
||||||
const row = Math.floor(index / atlas.sprites_per_side);
|
|
||||||
const column = index % atlas.sprites_per_side;
|
|
||||||
ctx.drawImage(sprite, column * SPRITE_SIZE, row * SPRITE_SIZE);
|
|
||||||
index += 1;
|
|
||||||
|
|
||||||
const id = `bworld:${entry.name.replace(".png", "")}`;
|
|
||||||
atlas_info[id] = { x: column, y: row };
|
|
||||||
}
|
|
||||||
|
|
||||||
Deno.writeFileSync(`${BUILD_FOLDER}/${folder}.png`, canvas.toBuffer());
|
|
||||||
Deno.writeTextFileSync(`${BUILD_FOLDER}/${folder}.json`, JSON.stringify(atlas_info));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function build_sprites() {
|
async function build_sprites() {
|
||||||
for (const entry of Deno.readDirSync("assets/sprites")) {
|
for (const entry of Deno.readDirSync("assets/sprites")) {
|
||||||
if (entry.name.endsWith(".png")) {
|
if (entry.name.endsWith(".png")) {
|
||||||
await copy(`assets/sprites/${entry.name}`, `${BUILD_FOLDER}/assets/sprites/${entry.name}`);
|
await copy(`assets/sprites/${entry.name}`, `${BUILD_FOLDER}/assets/sprites/${entry.name}`);
|
||||||
} else if (entry.isDirectory) {
|
|
||||||
await build_atlas_from_folder(`assets/sprites/${entry.name}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the engine's textures (cubi:<file>), with a list of them. clients put them in the texture atlas with the mods'
|
||||||
|
function build_engine_textures() {
|
||||||
|
const folder = `${BUILD_FOLDER}/assets/textures`;
|
||||||
|
Deno.mkdirSync(folder, { recursive: true });
|
||||||
|
const names: string[] = [];
|
||||||
|
for (const entry of [...Deno.readDirSync(ENGINE_TEXTURE_DIR)].sort((a, b) => a.name.localeCompare(b.name))) {
|
||||||
|
if (entry.isFile && entry.name.endsWith(".png")) {
|
||||||
|
Deno.copyFileSync(`${ENGINE_TEXTURE_DIR}/${entry.name}`, `${folder}/${entry.name}`);
|
||||||
|
names.push(entry.name.replace(/\.png$/, ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Deno.writeTextFileSync(`${BUILD_FOLDER}/${ENGINE_TEXTURES_INDEX}`, JSON.stringify(names));
|
||||||
|
}
|
||||||
|
|
||||||
async function build_assets() {
|
async function build_assets() {
|
||||||
Deno.mkdirSync(`${BUILD_FOLDER}/assets`, { recursive: true });
|
Deno.mkdirSync(`${BUILD_FOLDER}/assets`, { recursive: true });
|
||||||
await copy("assets/ASSETS.md", `${BUILD_FOLDER}/assets/ASSETS.md`);
|
await copy("assets/ASSETS.md", `${BUILD_FOLDER}/assets/ASSETS.md`);
|
||||||
|
|
||||||
build_fonts();
|
await build_fonts();
|
||||||
Deno.mkdirSync(`${BUILD_FOLDER}/assets/sprites`, { recursive: true });
|
Deno.mkdirSync(`${BUILD_FOLDER}/assets/sprites`, { recursive: true });
|
||||||
await build_sprites();
|
await build_sprites();
|
||||||
|
build_engine_textures();
|
||||||
|
}
|
||||||
|
|
||||||
|
// every mod in mods/, checked and sorted so dependencies load first. a broken mod fails the whole build,
|
||||||
|
// the game never runs with some mods missing
|
||||||
|
async function load_mods(): Promise<LoadedMod[]> {
|
||||||
|
const mods = await load_and_check(MODS_FOLDER);
|
||||||
|
const problems = mods.flatMap((mod) => mod.report.errors.map((error) => ` ${mod.id}: ${error}`));
|
||||||
|
if (problems.length > 0) {
|
||||||
|
throw new Error(`Mods have errors (deno task check-mods for details):\n${problems.join("\n")}`);
|
||||||
|
}
|
||||||
|
return load_order(mods);
|
||||||
|
}
|
||||||
|
|
||||||
|
// every mod in mods/ into server_mods/<id>.cubi. other .cubi files there are left alone, they're other people's mods
|
||||||
|
async function build_mods(mods: LoadedMod[]) {
|
||||||
|
Deno.mkdirSync(SERVER_MODS_FOLDER, { recursive: true });
|
||||||
|
remove_old_format();
|
||||||
|
for (const mod of mods) {
|
||||||
|
Deno.writeFileSync(`${SERVER_MODS_FOLDER}/${mod.id}${MOD_EXTENSION}`, await pack_mod(mod));
|
||||||
|
}
|
||||||
|
console.log(`Mods: ${mods.map((m) => m.id).join(", ") || "none"}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// builds before .cubi files put each mod's server script in a folder here with an index.json
|
||||||
|
function remove_old_format() {
|
||||||
|
for (const entry of Deno.readDirSync(SERVER_MODS_FOLDER)) {
|
||||||
|
if (entry.isDirectory || entry.name === "index.json") {
|
||||||
|
Deno.removeSync(`${SERVER_MODS_FOLDER}/${entry.name}`, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function build_client() {
|
async function build_client() {
|
||||||
const _result = await Deno.bundle({
|
const _result = await Deno.bundle({
|
||||||
entrypoints: ["./client/main.ts", "./client/workers/chunk_mesh_worker.ts"],
|
entrypoints: ["./client/main.ts", "./client/workers/chunk_worker.ts"],
|
||||||
outputDir: `${BUILD_FOLDER}/client`,
|
outputDir: `${BUILD_FOLDER}/client`,
|
||||||
platform: "browser",
|
platform: "browser",
|
||||||
minify: false,
|
minify: false,
|
||||||
keepNames: true,
|
keepNames: true,
|
||||||
});
|
});
|
||||||
|
// the desktop app's client, a deno worker next to main.js so it finds the same chunk worker, see client/native/
|
||||||
|
await Deno.bundle({
|
||||||
|
entrypoints: ["./client/native/main.ts"],
|
||||||
|
outputPath: `${BUILD_FOLDER}/client/native.js`,
|
||||||
|
platform: "deno",
|
||||||
|
minify: false,
|
||||||
|
keepNames: true,
|
||||||
|
});
|
||||||
await copy("./client/index.html", `${BUILD_FOLDER}/client/index.html`);
|
await copy("./client/index.html", `${BUILD_FOLDER}/client/index.html`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// every file the client needs with its hash, and the protocol it speaks. the desktop app compares it with the site's
|
||||||
|
// to update its client, see desktop/client_updates.ts
|
||||||
|
async function write_client_manifest(build_dir: string) {
|
||||||
|
const files: Record<string, string> = {};
|
||||||
|
for (const top of ["client", "assets"]) {
|
||||||
|
for await (const entry of walk(`${build_dir}/${top}`, { includeDirs: false })) {
|
||||||
|
const path = relative(build_dir, entry.path).replaceAll("\\", "/");
|
||||||
|
if (path === CLIENT_MANIFEST) continue;
|
||||||
|
files[path] = await sha256(Deno.readFileSync(entry.path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const manifest = await client_manifest(files, PROTOCOL_VERSION);
|
||||||
|
Deno.writeTextFileSync(`${build_dir}/${CLIENT_MANIFEST}`, JSON.stringify(manifest, null, "\t"));
|
||||||
|
}
|
||||||
|
|
||||||
async function build() {
|
async function build() {
|
||||||
try {
|
try {
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
clear_folder();
|
clear_folder(BUILD_FOLDER);
|
||||||
|
// checked first: a mod with errors stops the build before any .cubi is written
|
||||||
|
const mods = await load_mods();
|
||||||
await build_assets();
|
await build_assets();
|
||||||
await build_client();
|
await build_client();
|
||||||
|
await write_client_manifest(BUILD_FOLDER);
|
||||||
|
await build_mods(mods);
|
||||||
console.log(`Built in ${(performance.now() - now).toFixed(2)}ms`);
|
console.log(`Built in ${(performance.now() - now).toFixed(2)}ms`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(e);
|
console.log(e instanceof Error ? e.message : e);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
let last_build = 0;
|
let last_build = 0;
|
||||||
|
|
||||||
if (import.meta.main) {
|
if (import.meta.main) {
|
||||||
await build();
|
const ok = await build();
|
||||||
const watcher = Deno.watchFs(["assets", "client", "common"], { recursive: true });
|
// deno task build --once, for scripts and ci
|
||||||
|
if (Deno.args.includes("--once")) {
|
||||||
|
Deno.exit(ok ? 0 : 1);
|
||||||
|
}
|
||||||
|
const watcher = Deno.watchFs(["assets", "client", "common", MODS_FOLDER], { recursive: true });
|
||||||
for await (const event of watcher) {
|
for await (const event of watcher) {
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
if (now - last_build < 500) {
|
if (now - last_build < 500) {
|
||||||
|
|||||||
@@ -1,97 +0,0 @@
|
|||||||
import { marked } from "marked";
|
|
||||||
import { AssetManager } from "./assets.ts";
|
|
||||||
|
|
||||||
export async function open_about() {
|
|
||||||
const popup = self.open(
|
|
||||||
"",
|
|
||||||
"popupWindow",
|
|
||||||
"width=500,height=400",
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!popup) {
|
|
||||||
alert("oh no");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
popup.document.body.innerHTML = await marked.parse(AssetManager.instance.get("bworld:assets_text"));
|
|
||||||
popup.document.head.innerHTML = `<style>
|
|
||||||
body {
|
|
||||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
||||||
line-height: 1.7;
|
|
||||||
color: #e5e7eb;
|
|
||||||
max-width: 800px;
|
|
||||||
margin: 2rem auto;
|
|
||||||
padding: 0 1rem;
|
|
||||||
}
|
|
||||||
h1, h2, h3, h4 {
|
|
||||||
font-weight: 600;
|
|
||||||
line-height: 1.3;
|
|
||||||
margin-top: 2rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 2rem;
|
|
||||||
border-bottom: 1px solid #e5e7eb;
|
|
||||||
padding-bottom: 0.3rem;
|
|
||||||
}
|
|
||||||
h2 {
|
|
||||||
font-size: 1.5rem;
|
|
||||||
border-bottom: 1px solid #e5e7eb;
|
|
||||||
padding-bottom: 0.3rem;
|
|
||||||
}
|
|
||||||
h3 {
|
|
||||||
font-size: 1.25rem;
|
|
||||||
}
|
|
||||||
p {
|
|
||||||
margin: 1rem 0;
|
|
||||||
}
|
|
||||||
a {
|
|
||||||
color: #2563eb;
|
|
||||||
text-decoration: none;
|
|
||||||
}
|
|
||||||
a:hover {
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
ul, ol {
|
|
||||||
padding-left: 2rem;
|
|
||||||
margin: 1rem 0;
|
|
||||||
}
|
|
||||||
code {
|
|
||||||
background: #1f2937;
|
|
||||||
padding: 0.2em 0.4em;
|
|
||||||
border-radius: 4px;
|
|
||||||
font-size: 0.9em;
|
|
||||||
}
|
|
||||||
pre {
|
|
||||||
background: #0f172a;
|
|
||||||
color: #f9fafb;
|
|
||||||
padding: 1rem;
|
|
||||||
border-radius: 8px;
|
|
||||||
overflow-x: auto;
|
|
||||||
}
|
|
||||||
pre code {
|
|
||||||
background: none;
|
|
||||||
padding: 0;
|
|
||||||
color: inherit;
|
|
||||||
}
|
|
||||||
blockquote {
|
|
||||||
border-left: 4px solid #d1d5db;
|
|
||||||
padding-left: 1rem;
|
|
||||||
color: #6b7280;
|
|
||||||
margin: 1rem 0;
|
|
||||||
}
|
|
||||||
table {
|
|
||||||
border-collapse: collapse;
|
|
||||||
width: 100%;
|
|
||||||
margin: 1rem 0;
|
|
||||||
}
|
|
||||||
th, td {
|
|
||||||
border: 1px solid #e5e7eb;
|
|
||||||
padding: 0.5rem;
|
|
||||||
}
|
|
||||||
th {
|
|
||||||
background: #f9fafb;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
</style>`;
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
import { load_texture, Texture } from "./renderer/mod.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
type Asset = Texture | HTMLAudioElement | string | Record<string, unknown>;
|
import { load_texture, Texture } from "./renderer/mod.ts";
|
||||||
|
import { decode_png } from "./png.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
|
type Asset = Texture | string | Record<string, unknown>;
|
||||||
|
|
||||||
export class AssetManager {
|
export class AssetManager {
|
||||||
static instance = new AssetManager();
|
static instance = new AssetManager();
|
||||||
@@ -15,45 +20,24 @@ export class AssetManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the client's own files are next to the page, see platform.page
|
||||||
|
const url = new URL(src, platform.page);
|
||||||
if (src.endsWith(".png")) {
|
if (src.endsWith(".png")) {
|
||||||
const img = new Image();
|
const promise = async () => {
|
||||||
const promise = new Promise<void>((resolve, reject) => {
|
const resp = await fetch(url);
|
||||||
img.onload = () => {
|
if (!resp.ok) throw new Error(`Failed to load image: ${src}`);
|
||||||
this.assets[key] = load_texture(img);
|
this.assets[key] = load_texture(decode_png(new Uint8Array(await resp.arrayBuffer())));
|
||||||
resolve();
|
};
|
||||||
};
|
this.loading_promises.push(promise());
|
||||||
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
|
|
||||||
});
|
|
||||||
img.src = src;
|
|
||||||
this.loading_promises.push(promise);
|
|
||||||
} else if (src.endsWith(".ogg")) {
|
|
||||||
const audio = new Audio();
|
|
||||||
const promise = new Promise<void>((resolve, reject) => {
|
|
||||||
audio.addEventListener(
|
|
||||||
"canplaythrough",
|
|
||||||
() => resolve(),
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
audio.addEventListener(
|
|
||||||
"error",
|
|
||||||
() => reject(new Error(`Failed to load audio: ${src}`)),
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
audio.src = src;
|
|
||||||
audio.load();
|
|
||||||
this.assets[key] = audio;
|
|
||||||
this.loading_promises.push(promise);
|
|
||||||
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
|
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
|
||||||
const promise = async () => {
|
const promise = async () => {
|
||||||
const resp = await fetch(src);
|
const resp = await fetch(url);
|
||||||
this.assets[key] = await resp.text();
|
this.assets[key] = await resp.text();
|
||||||
};
|
};
|
||||||
this.loading_promises.push(promise());
|
this.loading_promises.push(promise());
|
||||||
} else if (src.endsWith(".json")) {
|
} else if (src.endsWith(".json")) {
|
||||||
const promise = async () => {
|
const promise = async () => {
|
||||||
const resp = await fetch(src);
|
const resp = await fetch(url);
|
||||||
this.assets[key] = await resp.json();
|
this.assets[key] = await resp.json();
|
||||||
};
|
};
|
||||||
this.loading_promises.push(promise());
|
this.loading_promises.push(promise());
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the texture atlas: the engine's textures and every mod's in one image, built by the client when it joins a server
|
||||||
|
// from the textures in the server's .cubi files
|
||||||
|
import { TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
|
import { type Animation, texture_animation, type TextureJson } from "@/common/texture_animation.ts";
|
||||||
|
import { AnimatedTexture } from "./texture_animations.ts";
|
||||||
|
import { decode_png, type Pixels } from "./png.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
|
export interface AtlasLayout {
|
||||||
|
// in pixels, a power of two
|
||||||
|
size: number;
|
||||||
|
// by texture id
|
||||||
|
regions: Record<string, SpriteRegion>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TextureSize {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// pixels around each texture, copies of its edge, so a face whose uvs reach the texture's edge never shows a bit of
|
||||||
|
// the next texture over, however the lookup rounds. see extrude_borders
|
||||||
|
export const ATLAS_BORDER = 1;
|
||||||
|
|
||||||
|
// shelves, tallest first so each row wastes little, and by id when they're the same size so the same textures always
|
||||||
|
// give the same atlas. cubi:missing is 16×16 and always there
|
||||||
|
export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
|
||||||
|
const entries = [...sizes].filter(([id]) => id !== "cubi:missing");
|
||||||
|
entries.push(["cubi:missing", { width: TEXTURE_SIZE, height: TEXTURE_SIZE }]);
|
||||||
|
entries.sort(([a, sa], [b, sb]) => sb.height - sa.height || sb.width - sa.width || a.localeCompare(b));
|
||||||
|
|
||||||
|
const area = entries.reduce(
|
||||||
|
(sum, [, { width, height }]) => sum + (width + 2 * ATLAS_BORDER) * (height + 2 * ATLAS_BORDER),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const widest = Math.max(...entries.map(([, { width }]) => width + 2 * ATLAS_BORDER));
|
||||||
|
let size = 2 ** Math.ceil(Math.log2(Math.max(Math.sqrt(area), widest)));
|
||||||
|
while (true) {
|
||||||
|
const regions = pack_shelves(entries, size);
|
||||||
|
if (regions) return { size, regions };
|
||||||
|
size *= 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// undefined if they don't fit in a size × size square. regions are the textures themselves, inside their border
|
||||||
|
function pack_shelves(entries: [string, TextureSize][], size: number) {
|
||||||
|
const regions: Record<string, SpriteRegion> = {};
|
||||||
|
let x = 0;
|
||||||
|
let y = 0;
|
||||||
|
let shelf = 0;
|
||||||
|
for (const [id, { width, height }] of entries) {
|
||||||
|
const [outer_width, outer_height] = [width + 2 * ATLAS_BORDER, height + 2 * ATLAS_BORDER];
|
||||||
|
if (x + outer_width > size) {
|
||||||
|
x = 0;
|
||||||
|
y += shelf;
|
||||||
|
shelf = 0;
|
||||||
|
}
|
||||||
|
regions[id] = { x: x + ATLAS_BORDER, y: y + ATLAS_BORDER, width, height };
|
||||||
|
x += outer_width;
|
||||||
|
shelf = Math.max(shelf, outer_height);
|
||||||
|
}
|
||||||
|
return y + shelf <= size ? regions : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
|
||||||
|
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
|
||||||
|
// texture_animations.ts)
|
||||||
|
export function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||||
|
const images = new Map<string, Pixels>();
|
||||||
|
for (const [id, png] of textures) {
|
||||||
|
if (id === "cubi:missing") continue;
|
||||||
|
try {
|
||||||
|
images.set(id, decode_png(png));
|
||||||
|
} catch {
|
||||||
|
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const animations = new Map<string, Animation>();
|
||||||
|
for (const [id, image] of images) {
|
||||||
|
const json = texture_json.get(id);
|
||||||
|
const animation = json && texture_animation(json, image);
|
||||||
|
if (animation) animations.set(id, animation);
|
||||||
|
}
|
||||||
|
const sizes = new Map([...images].map(([id, image]) => {
|
||||||
|
const animation = animations.get(id);
|
||||||
|
return [id, animation ? { width: animation.frame_width, height: animation.frame_height } : image];
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { size, regions } = atlas_layout(sizes);
|
||||||
|
const pixels = new Uint8ClampedArray(size * size * 4);
|
||||||
|
const atlas = { width: size, height: size, data: pixels };
|
||||||
|
|
||||||
|
// magenta and black checker
|
||||||
|
const missing = regions["cubi:missing"];
|
||||||
|
const half = TEXTURE_SIZE / 2;
|
||||||
|
for (let py = 0; py < TEXTURE_SIZE; py++) {
|
||||||
|
for (let px = 0; px < TEXTURE_SIZE; px++) {
|
||||||
|
const i = ((missing.y + py) * size + missing.x + px) * 4;
|
||||||
|
const magenta = (px < half) === (py < half);
|
||||||
|
pixels.set(magenta ? [255, 0, 255, 255] : [0, 0, 0, 255], i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const animated: AnimatedTexture[] = [];
|
||||||
|
for (const [id, image] of images) {
|
||||||
|
const animation = animations.get(id);
|
||||||
|
const { x, y, width, height } = regions[id];
|
||||||
|
const first = animation?.frames[0] ?? { x: 0, y: 0 };
|
||||||
|
copy_pixels(image, first.x, first.y, width, height, atlas, x, y);
|
||||||
|
if (animation) animated.push(new AnimatedTexture(regions[id], animation, image.data, image.width));
|
||||||
|
}
|
||||||
|
for (const id of textures.keys()) {
|
||||||
|
regions[id] ??= missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
extrude_borders(pixels, size, regions);
|
||||||
|
|
||||||
|
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
|
||||||
|
built_atlas = atlas;
|
||||||
|
opaque.clear();
|
||||||
|
for (const [id, region] of Object.entries(regions)) {
|
||||||
|
const mask = new Uint8Array(region.width * region.height);
|
||||||
|
for (let py = 0; py < region.height; py++) {
|
||||||
|
for (let px = 0; px < region.width; px++) {
|
||||||
|
const i = ((region.y + py) * size + region.x + px) * 4;
|
||||||
|
mask[py * region.width + px] = pixels[i + 3] > 0 ? 1 : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
opaque.set(id, { width: region.width, height: region.height, mask });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { image: atlas, regions, animated };
|
||||||
|
}
|
||||||
|
|
||||||
|
// a width × height part of from, starting at from_x from_y, into to at to_x to_y
|
||||||
|
function copy_pixels(
|
||||||
|
from: Pixels,
|
||||||
|
from_x: number,
|
||||||
|
from_y: number,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
to: Pixels,
|
||||||
|
to_x: number,
|
||||||
|
to_y: number,
|
||||||
|
) {
|
||||||
|
for (let row = 0; row < height; row++) {
|
||||||
|
const start = ((from_y + row) * from.width + from_x) * 4;
|
||||||
|
to.data.set(from.data.subarray(start, start + width * 4), ((to_y + row) * to.width + to_x) * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fills each region's border with copies of its edge pixels, the corners with its corners. pixels is a size × size
|
||||||
|
// rgba atlas. an animated texture's border keeps its first frame's edge, only rounding ever shows it
|
||||||
|
export function extrude_borders(pixels: Uint8ClampedArray, size: number, regions: Record<string, SpriteRegion>) {
|
||||||
|
const copy = (from_x: number, from_y: number, to_x: number, to_y: number) => {
|
||||||
|
if (to_x < 0 || to_y < 0 || to_x >= size || to_y >= size) return;
|
||||||
|
const from = (from_y * size + from_x) * 4;
|
||||||
|
const to = (to_y * size + to_x) * 4;
|
||||||
|
for (let c = 0; c < 4; c++) pixels[to + c] = pixels[from + c];
|
||||||
|
};
|
||||||
|
// the missing texture fills in for unknown ids too, once is enough
|
||||||
|
for (const { x, y, width, height } of new Set(Object.values(regions))) {
|
||||||
|
for (let b = 1; b <= ATLAS_BORDER; b++) {
|
||||||
|
for (let px = -b; px < width + b; px++) {
|
||||||
|
const from_x = x + Math.min(Math.max(px, 0), width - 1);
|
||||||
|
copy(from_x, y, x + px, y - b);
|
||||||
|
copy(from_x, y + height - 1, x + px, y + height - 1 + b);
|
||||||
|
}
|
||||||
|
for (let py = -b; py < height + b; py++) {
|
||||||
|
const from_y = y + Math.min(Math.max(py, 0), height - 1);
|
||||||
|
copy(x, from_y, x - b, y + py);
|
||||||
|
copy(x + width - 1, from_y, x + width - 1 + b, y + py);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
|
||||||
|
export interface OpaqueMask {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
mask: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
// by texture id
|
||||||
|
const opaque = new Map<string, OpaqueMask>();
|
||||||
|
|
||||||
|
// which pixels of a texture aren't fully see-through, undefined before the atlas is built or for unknown textures
|
||||||
|
export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
|
||||||
|
return opaque.get(texture_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the last atlas built, before any animated texture moved on from its first frame
|
||||||
|
let built_atlas: Pixels | undefined;
|
||||||
|
|
||||||
|
// the atlas as a png, undefined before one is built or where there's no canvas to encode it (the desktop app). for
|
||||||
|
// the f3 screen's copy button
|
||||||
|
export function atlas_png(): Promise<Blob> | undefined {
|
||||||
|
if (!built_atlas || typeof document === "undefined") return undefined;
|
||||||
|
const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height);
|
||||||
|
canvas.getContext("2d")!.putImageData(new ImageData(built_atlas.data, built_atlas.width), 0, 0);
|
||||||
|
return canvas.convertToBlob({ type: "image/png" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts
|
||||||
|
export async function engine_textures(): Promise<Map<string, Uint8Array>> {
|
||||||
|
const names: string[] = await (await fetch(new URL("/assets/textures/index.json", platform.page))).json();
|
||||||
|
const textures = new Map<string, Uint8Array>();
|
||||||
|
await Promise.all(names.map(async (name) => {
|
||||||
|
const response = await fetch(new URL(`/assets/textures/${name}.png`, platform.page));
|
||||||
|
textures.set(`cubi:${name}`, new Uint8Array(await response.arrayBuffer()));
|
||||||
|
}));
|
||||||
|
return textures;
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// plays what client/sounds.ts decides on with web audio: a gain per category under master, and a panner for each
|
||||||
|
// sound that comes from somewhere, fading linearly to nothing at its range
|
||||||
|
import { SOUND_CATEGORIES, type SoundCategory } from "@/common/mod_data.ts";
|
||||||
|
import type { Position } from "@/common/mod_api/shared.ts";
|
||||||
|
import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "./sounds.ts";
|
||||||
|
|
||||||
|
export class WebAudioOutput implements SoundOutput {
|
||||||
|
#context: AudioContext | undefined;
|
||||||
|
#master: GainNode | undefined;
|
||||||
|
#categories = new Map<SoundCategory, GainNode>();
|
||||||
|
// decoded once, the first time anything plays them. by the bytes, so another server's files never mix in
|
||||||
|
#buffers = new WeakMap<Uint8Array, Promise<AudioBuffer | undefined>>();
|
||||||
|
#volumes: Volumes | undefined;
|
||||||
|
|
||||||
|
// browsers keep audio off until the player clicks or presses a key, so it starts then. the desktop app's web audio
|
||||||
|
// (client/native/web_audio.ts) has no such rule and starts right away
|
||||||
|
constructor(wait_for_input = true) {
|
||||||
|
if (!wait_for_input) {
|
||||||
|
this.#unlock();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const unlock = () => {
|
||||||
|
this.#unlock();
|
||||||
|
if (this.#context?.state === "running") {
|
||||||
|
removeEventListener("pointerdown", unlock);
|
||||||
|
removeEventListener("keydown", unlock);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
addEventListener("pointerdown", unlock);
|
||||||
|
addEventListener("keydown", unlock);
|
||||||
|
}
|
||||||
|
|
||||||
|
#unlock() {
|
||||||
|
if (!this.#context) {
|
||||||
|
const context = new AudioContext();
|
||||||
|
this.#master = context.createGain();
|
||||||
|
this.#master.connect(context.destination);
|
||||||
|
for (const category of SOUND_CATEGORIES) {
|
||||||
|
const gain = context.createGain();
|
||||||
|
gain.connect(this.#master);
|
||||||
|
this.#categories.set(category, gain);
|
||||||
|
}
|
||||||
|
this.#context = context;
|
||||||
|
if (this.#volumes) this.set_volumes(this.#volumes);
|
||||||
|
}
|
||||||
|
if (this.#context.state === "suspended") this.#context.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
start(file: SoundFile, settings: VoiceSettings): Voice | undefined {
|
||||||
|
const context = this.#context;
|
||||||
|
// sounds played while it's suspended would all come at once when it resumes
|
||||||
|
if (!context || context.state !== "running") return undefined;
|
||||||
|
const out = settings.category ? this.#categories.get(settings.category)! : this.#master!;
|
||||||
|
return new WebVoice(context, this.#buffer(context, file), out, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
#buffer(context: AudioContext, file: SoundFile) {
|
||||||
|
let buffer = this.#buffers.get(file.bytes);
|
||||||
|
if (!buffer) {
|
||||||
|
// decoding detaches what it's given
|
||||||
|
buffer = context.decodeAudioData(file.bytes.slice().buffer).catch((e) => {
|
||||||
|
console.error(`couldn't decode the sound file ${file.id}:`, e);
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
this.#buffers.set(file.bytes, buffer);
|
||||||
|
}
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
listen(x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||||
|
const listener = this.#context?.listener;
|
||||||
|
if (!listener) return;
|
||||||
|
// the camera's forward and up, see ClientLevel's pick
|
||||||
|
const forward = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
|
||||||
|
const up = [Math.sin(yaw) * Math.sin(pitch), Math.cos(pitch), Math.cos(yaw) * Math.sin(pitch)];
|
||||||
|
// firefox only has the old setters
|
||||||
|
if (listener.positionX) {
|
||||||
|
listener.positionX.value = x;
|
||||||
|
listener.positionY.value = y;
|
||||||
|
listener.positionZ.value = z;
|
||||||
|
listener.forwardX.value = forward[0];
|
||||||
|
listener.forwardY.value = forward[1];
|
||||||
|
listener.forwardZ.value = forward[2];
|
||||||
|
listener.upX.value = up[0];
|
||||||
|
listener.upY.value = up[1];
|
||||||
|
listener.upZ.value = up[2];
|
||||||
|
} else {
|
||||||
|
listener.setPosition(x, y, z);
|
||||||
|
listener.setOrientation(forward[0], forward[1], forward[2], up[0], up[1], up[2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
set_volumes(volumes: Volumes) {
|
||||||
|
this.#volumes = volumes;
|
||||||
|
if (!this.#master) return;
|
||||||
|
this.#master.gain.value = volumes.master;
|
||||||
|
for (const [category, gain] of this.#categories) gain.gain.value = volumes[category];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class WebVoice implements Voice {
|
||||||
|
ended = false;
|
||||||
|
#source: AudioBufferSourceNode | undefined;
|
||||||
|
#gain: GainNode;
|
||||||
|
#panner: PannerNode | undefined;
|
||||||
|
#stopped = false;
|
||||||
|
// set may come before the file is decoded
|
||||||
|
#pitch: number;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
context: AudioContext,
|
||||||
|
buffer: Promise<AudioBuffer | undefined>,
|
||||||
|
out: AudioNode,
|
||||||
|
settings: VoiceSettings,
|
||||||
|
) {
|
||||||
|
this.#pitch = settings.pitch;
|
||||||
|
this.#gain = new GainNode(context, { gain: Math.min(1, settings.volume) });
|
||||||
|
if (settings.at) {
|
||||||
|
this.#panner = new PannerNode(context, {
|
||||||
|
panningModel: "HRTF",
|
||||||
|
distanceModel: "linear",
|
||||||
|
refDistance: 1,
|
||||||
|
maxDistance: settings.range,
|
||||||
|
positionX: settings.at.x,
|
||||||
|
positionY: settings.at.y,
|
||||||
|
positionZ: settings.at.z,
|
||||||
|
});
|
||||||
|
this.#gain.connect(this.#panner).connect(out);
|
||||||
|
} else {
|
||||||
|
this.#gain.connect(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the first time a file plays it starts once it's decoded
|
||||||
|
buffer.then((buffer) => {
|
||||||
|
if (!buffer || this.#stopped) {
|
||||||
|
this.ended = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// played with an offset past its end, it would have finished already
|
||||||
|
if (!settings.loop && settings.offset >= buffer.duration) {
|
||||||
|
this.stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const source = new AudioBufferSourceNode(context, {
|
||||||
|
buffer,
|
||||||
|
loop: settings.loop,
|
||||||
|
playbackRate: this.#pitch,
|
||||||
|
});
|
||||||
|
source.connect(this.#gain);
|
||||||
|
source.onended = () => {
|
||||||
|
this.ended = true;
|
||||||
|
this.#disconnect();
|
||||||
|
};
|
||||||
|
source.start(0, settings.offset % buffer.duration);
|
||||||
|
this.#source = source;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
move(at: Position) {
|
||||||
|
if (!this.#panner) return;
|
||||||
|
this.#panner.positionX.value = at.x;
|
||||||
|
this.#panner.positionY.value = at.y;
|
||||||
|
this.#panner.positionZ.value = at.z;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(volume: number, pitch: number, range: number) {
|
||||||
|
this.#gain.gain.value = Math.min(1, volume);
|
||||||
|
this.#pitch = pitch;
|
||||||
|
if (this.#source) this.#source.playbackRate.value = pitch;
|
||||||
|
if (this.#panner) this.#panner.maxDistance = range;
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.#stopped = true;
|
||||||
|
this.ended = true;
|
||||||
|
this.#source?.stop();
|
||||||
|
this.#disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
#disconnect() {
|
||||||
|
this.#source?.disconnect();
|
||||||
|
this.#gain.disconnect();
|
||||||
|
this.#panner?.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark's level, made on the client from a fixed seed so every run draws the same thing whatever world
|
||||||
|
// the player is in: hills with caves, trees and plants, a lake with glass in it, and flat ground for the scenes with
|
||||||
|
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
|
||||||
|
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
|
||||||
|
import { Alea } from "@paulaboks/rng";
|
||||||
|
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||||
|
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||||
|
import { ChunkColumn } from "@/common/section.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { DEFAULT_MODEL } from "@/common/block_models.ts";
|
||||||
|
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.ts";
|
||||||
|
import { can_stand_on, default_block_value } from "@/common/utils.ts";
|
||||||
|
import type { Biome } from "@/common/worldgen/biomes.ts";
|
||||||
|
import type { NoiseSettingsJson } from "@/common/worldgen/data.ts";
|
||||||
|
|
||||||
|
const SEED = "benchmark";
|
||||||
|
// chunks go from -LEVEL_RADIUS to LEVEL_RADIUS - 1 each way. the outermost ring is only there so the ones inside it
|
||||||
|
// can be meshed, see ClientLevel.can_mesh
|
||||||
|
export const LEVEL_RADIUS = 13;
|
||||||
|
export const SEA_LEVEL = 62;
|
||||||
|
// 0 to 256 with sky light whatever the world's dimension is, so runs compare. y in its chunks counts from 0
|
||||||
|
export const LEVEL_SHAPE = DEFAULT_SHAPE;
|
||||||
|
const TOP = LEVEL_SHAPE.max_y;
|
||||||
|
|
||||||
|
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
|
||||||
|
export const ZONES = {
|
||||||
|
lake: { x: -96, z: -96, radius: 44, height: 46 },
|
||||||
|
arena: { x: 96, z: -96, radius: 26, height: 72 },
|
||||||
|
visuals: { x: -96, z: 96, radius: 22, height: 72 },
|
||||||
|
updates: { x: 96, z: 96, radius: 18, height: 72 },
|
||||||
|
};
|
||||||
|
const BLEND = 24;
|
||||||
|
// what the block update scene changes, a wall facing south
|
||||||
|
export const UPDATE_WALL = {
|
||||||
|
x: ZONES.updates.x - 8,
|
||||||
|
y: ZONES.updates.height + 1,
|
||||||
|
z: ZONES.updates.z,
|
||||||
|
width: 16,
|
||||||
|
height: 8,
|
||||||
|
};
|
||||||
|
// the field of blocks drawn with code, this many on a side
|
||||||
|
const VISUALS_SIZE = 20;
|
||||||
|
// pillars standing in the lake
|
||||||
|
const GLASS_PILLARS = 6;
|
||||||
|
|
||||||
|
// of the ground's top blocks
|
||||||
|
const PLANT_CHANCE = 0.12;
|
||||||
|
const LIGHT_CHANCE = 0.003;
|
||||||
|
// a tree grows in each TREE_CELL square with TREE_CHANCE
|
||||||
|
const TREE_CELL = 8;
|
||||||
|
const TREE_CHANCE = 0.5;
|
||||||
|
// how far leaves reach from the trunk
|
||||||
|
const LEAVES_REACH = 2;
|
||||||
|
// caves are where their noise is above this
|
||||||
|
const CAVE_THRESHOLD = 0.42;
|
||||||
|
|
||||||
|
// what the level is made of, as values with their default states. what the loaded mods have no block for is left out
|
||||||
|
export interface BenchBlocks {
|
||||||
|
// the level's biome, for its colors
|
||||||
|
biome: string;
|
||||||
|
stone: number;
|
||||||
|
// the ground's cover, see SurfaceJson in common/worldgen/biomes.ts
|
||||||
|
top: number;
|
||||||
|
filler: number;
|
||||||
|
filler_depth: number;
|
||||||
|
underwater: number;
|
||||||
|
log: number;
|
||||||
|
leaves?: number;
|
||||||
|
plants: number[];
|
||||||
|
glass?: number;
|
||||||
|
fluid?: number;
|
||||||
|
light?: number;
|
||||||
|
// blocks drawn with code, see client/rendering/visuals.ts
|
||||||
|
visuals: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// visual_blocks are the numeric ids of the blocks drawn with code. the same mods give the same blocks
|
||||||
|
export function bench_blocks(visual_blocks: ReadonlySet<number>): BenchBlocks {
|
||||||
|
const all = EverythingRegistry.get_registry<BlockRegistry>("blocks")
|
||||||
|
.map((block, nid) => ({ block, nid, value: default_block_value(nid, block) }))
|
||||||
|
.filter(({ block, nid }) => block && nid !== AIR)
|
||||||
|
.sort((a, b) => a.block.id.localeCompare(b.block.id));
|
||||||
|
type Entry = typeof all[number];
|
||||||
|
const layer = ({ block }: Entry) => block.render_layer ?? "solid";
|
||||||
|
const cube = ({ block }: Entry) => (block.model ?? DEFAULT_MODEL) === DEFAULT_MODEL && !block.parts;
|
||||||
|
// one look that nothing changes
|
||||||
|
const plain = ({ block, nid }: Entry) =>
|
||||||
|
!block.states?.length && !block.variants && !block.fluid && !block.light_emission && !visual_blocks.has(nid);
|
||||||
|
const tinted = ({ block }: Entry, color: string) => block.tint?.color === color;
|
||||||
|
const by_id = (id: string | undefined) => all.find((b) => b.block.id === id);
|
||||||
|
|
||||||
|
const solid = all.filter((b) => plain(b) && cube(b) && layer(b) === "solid" && b.block.has_collision);
|
||||||
|
if (solid.length === 0) throw new Error("The benchmark needs a solid block to build its level with");
|
||||||
|
// what the world generator fills the ground with, and a grassy biome for its cover
|
||||||
|
const by_key = ([a]: [string, unknown], [b]: [string, unknown]) => a.localeCompare(b);
|
||||||
|
const settings = EverythingRegistry.entries<NoiseSettingsJson>("noise_settings").sort(by_key)[0]?.[1];
|
||||||
|
const biomes = EverythingRegistry.entries<Biome>("biomes").sort(by_key).map(([, biome]) => biome);
|
||||||
|
const grassy = (biome: Biome) => {
|
||||||
|
const top = by_id(biome.surface.top);
|
||||||
|
return top !== undefined && tinted(top, "grass");
|
||||||
|
};
|
||||||
|
const biome = biomes.find(grassy) ?? biomes[0];
|
||||||
|
const stone = by_id(settings?.default_block) ?? solid[0];
|
||||||
|
const top = by_id(biome?.surface.top) ?? solid.find((b) => tinted(b, "grass")) ?? stone;
|
||||||
|
const filler = by_id(biome?.surface.filler) ?? stone;
|
||||||
|
const ground = [stone, top, filler];
|
||||||
|
const leaves = all.filter((b) => plain(b) && cube(b) && layer(b) === "cutout");
|
||||||
|
// what says it grows on the ground's top, with its default states
|
||||||
|
const plants = all.filter((b) =>
|
||||||
|
b.block.place_on && can_stand_on(b.block, top.block.id) && layer(b) === "cutout" && !cube(b) &&
|
||||||
|
!b.block.has_collision && !visual_blocks.has(b.nid)
|
||||||
|
);
|
||||||
|
// water rather than lava
|
||||||
|
const fluids = all.filter((b) => b.block.fluid && !b.block.light_emission);
|
||||||
|
return {
|
||||||
|
biome: biome?.id ?? "",
|
||||||
|
stone: stone.value,
|
||||||
|
top: top.value,
|
||||||
|
filler: filler.value,
|
||||||
|
filler_depth: biome?.surface.filler_depth ?? 3,
|
||||||
|
underwater: (by_id(biome?.surface.underwater_top) ?? filler).value,
|
||||||
|
log: (solid.find((b) => !ground.includes(b)) ?? stone).value,
|
||||||
|
leaves: (leaves.find((b) => tinted(b, "foliage")) ?? leaves[0])?.value,
|
||||||
|
plants: plants.map((b) => b.value),
|
||||||
|
glass: all.find((b) => plain(b) && cube(b) && layer(b) === "translucent")?.value,
|
||||||
|
fluid: (by_id(settings?.fluids[0]?.block) ?? fluids.find((b) => layer(b) === "translucent") ?? fluids[0])
|
||||||
|
?.value,
|
||||||
|
light: all.find((b) => (b.block.light_emission ?? 0) > 0 && !b.block.fluid)?.value,
|
||||||
|
visuals: all.filter((b) => visual_blocks.has(b.nid)).map((b) => b.value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// the level's terrain, a chunk at a time. a chunk always comes out the same
|
||||||
|
export class BenchTerrain {
|
||||||
|
#blocks: BenchBlocks;
|
||||||
|
#hills = new OctaveNoise2D(SEED, "hills", 160, [1, 0.5, 0.25, 0.125]);
|
||||||
|
#mountains = new OctaveNoise2D(SEED, "mountains", 320, [1, 0.5, 0.25]);
|
||||||
|
#caves = new OctaveNoise3D(SEED, "caves", 40, [1, 0.5], 0.75);
|
||||||
|
|
||||||
|
constructor(blocks: BenchBlocks) {
|
||||||
|
this.#blocks = blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the y of the top block
|
||||||
|
height(x: number, z: number): number {
|
||||||
|
const mountains = Math.max(0, this.#mountains.sample(x, z));
|
||||||
|
let height = 68 + this.#hills.sample(x, z) * 16 + mountains * mountains * 140;
|
||||||
|
for (const zone of Object.values(ZONES)) {
|
||||||
|
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
|
||||||
|
height = zone.height + (height - zone.height) * t;
|
||||||
|
}
|
||||||
|
return Math.min(TOP - 32, Math.round(height));
|
||||||
|
}
|
||||||
|
|
||||||
|
chunk(chunk_x: number, chunk_z: number): ChunkColumn {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
|
||||||
|
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
|
||||||
|
const x0 = chunk_x * CHUNK_SIZE;
|
||||||
|
const z0 = chunk_z * CHUNK_SIZE;
|
||||||
|
// in world coordinates, only what's in this chunk
|
||||||
|
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
|
||||||
|
const lx = x - x0;
|
||||||
|
const lz = z - z0;
|
||||||
|
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= TOP) return;
|
||||||
|
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||||
|
if (!only_air || blocks[index] === AIR) blocks[index] = value;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
|
||||||
|
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
|
||||||
|
const x = x0 + lx;
|
||||||
|
const z = z0 + lz;
|
||||||
|
const height = this.height(x, z);
|
||||||
|
const shore = height <= SEA_LEVEL + 1;
|
||||||
|
const cover = height <= SEA_LEVEL ? b.underwater : b.top;
|
||||||
|
const column = lz * CHUNK_SIZE + lx;
|
||||||
|
for (let y = 0; y <= height; y++) {
|
||||||
|
let value = y === height ? cover : y >= height - b.filler_depth ? b.filler : b.stone;
|
||||||
|
if (y > 4 && y < height - 4 && this.#caves.sample(x, y, z) > CAVE_THRESHOLD) value = AIR;
|
||||||
|
blocks[y * CHUNK_AREA + column] = value;
|
||||||
|
}
|
||||||
|
for (let y = height + 1; b.fluid !== undefined && y <= SEA_LEVEL; y++) {
|
||||||
|
blocks[y * CHUNK_AREA + column] = b.fluid;
|
||||||
|
}
|
||||||
|
if (shore || this.#in_zone(x, z, 4)) continue;
|
||||||
|
const above = (height + 1) * CHUNK_AREA + column;
|
||||||
|
const roll = random.next();
|
||||||
|
if (b.light !== undefined && roll < LIGHT_CHANCE) {
|
||||||
|
blocks[above] = b.light;
|
||||||
|
} else if (b.plants.length > 0 && roll < PLANT_CHANCE) {
|
||||||
|
blocks[above] = b.plants[Math.floor(random.next() * b.plants.length)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.#trees(chunk_x, chunk_z, set);
|
||||||
|
this.#features(set);
|
||||||
|
return ChunkColumn.from_flat(chunk_x, chunk_z, LEVEL_SHAPE, blocks, new Array(CHUNK_AREA).fill(b.biome));
|
||||||
|
}
|
||||||
|
|
||||||
|
#in_zone(x: number, z: number, margin: number) {
|
||||||
|
return Object.values(ZONES).some((zone) => Math.hypot(x - zone.x, z - zone.z) < zone.radius + margin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// every tree with blocks in this chunk, some grow from the chunks beside it
|
||||||
|
#trees(chunk_x: number, chunk_z: number, set: (x: number, y: number, z: number, v: number, air?: boolean) => void) {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const cells = (chunk: number) => [
|
||||||
|
Math.floor((chunk * CHUNK_SIZE - LEAVES_REACH) / TREE_CELL),
|
||||||
|
Math.floor((chunk * CHUNK_SIZE + CHUNK_SIZE - 1 + LEAVES_REACH) / TREE_CELL),
|
||||||
|
];
|
||||||
|
const [first_x, last_x] = cells(chunk_x);
|
||||||
|
const [first_z, last_z] = cells(chunk_z);
|
||||||
|
for (let cell_z = first_z; cell_z <= last_z; cell_z++) {
|
||||||
|
for (let cell_x = first_x; cell_x <= last_x; cell_x++) {
|
||||||
|
const random = new Alea(`${SEED}_tree_${cell_x}_${cell_z}`);
|
||||||
|
if (random.next() > TREE_CHANCE) continue;
|
||||||
|
// away from the cell's edges, so leaves don't run into the next cell's tree
|
||||||
|
const x = cell_x * TREE_CELL + LEAVES_REACH +
|
||||||
|
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
|
||||||
|
const z = cell_z * TREE_CELL + LEAVES_REACH +
|
||||||
|
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
|
||||||
|
const trunk = 4 + Math.floor(random.next() * 3);
|
||||||
|
const ground = this.height(x, z);
|
||||||
|
if (ground <= SEA_LEVEL + 1 || this.#in_zone(x, z, 6)) continue;
|
||||||
|
for (let dy = 0; dy < trunk; dy++) set(x, ground + 1 + dy, z, b.log);
|
||||||
|
if (b.leaves === undefined) continue;
|
||||||
|
for (let dy = trunk - 2; dy <= trunk + 1; dy++) {
|
||||||
|
const reach = dy < trunk ? LEAVES_REACH : 1;
|
||||||
|
for (let dz = -reach; dz <= reach; dz++) {
|
||||||
|
for (let dx = -reach; dx <= reach; dx++) {
|
||||||
|
// rounded off at the corners
|
||||||
|
if (Math.abs(dx) === reach && Math.abs(dz) === reach) continue;
|
||||||
|
set(x + dx, ground + 1 + dy, z + dz, b.leaves, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// glass standing in the lake, and the field of visuals
|
||||||
|
#features(set: (x: number, y: number, z: number, value: number) => void) {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const { lake, visuals } = ZONES;
|
||||||
|
for (let i = 0; b.glass !== undefined && i < GLASS_PILLARS; i++) {
|
||||||
|
const angle = (i / GLASS_PILLARS) * Math.PI * 2;
|
||||||
|
const x = lake.x + Math.round(Math.cos(angle) * lake.radius / 2);
|
||||||
|
const z = lake.z + Math.round(Math.sin(angle) * lake.radius / 2);
|
||||||
|
for (let y = lake.height + 1; y <= SEA_LEVEL + 12; y++) {
|
||||||
|
for (let dz = -1; dz <= 1; dz++) {
|
||||||
|
for (let dx = -1; dx <= 1; dx++) set(x + dx, y, z + dz, b.glass);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i = 0; b.visuals.length > 0 && i < VISUALS_SIZE * VISUALS_SIZE; i++) {
|
||||||
|
const x = visuals.x - VISUALS_SIZE / 2 + (i % VISUALS_SIZE);
|
||||||
|
const z = visuals.z - VISUALS_SIZE / 2 + Math.floor(i / VISUALS_SIZE);
|
||||||
|
set(x, visuals.height + 1, z, b.visuals[i % b.visuals.length]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,574 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark, run from the f3 performance window, for comparing browsers and systems. it draws a level of
|
||||||
|
// its own that's the same every time (see bench_level.ts) through scenes that each load a part of the renderer: the
|
||||||
|
// terrain from above, the lake, a crowd of entities, blocks changing every tick and so on. the world waits meanwhile,
|
||||||
|
// so what's around the player doesn't change the numbers. each scene is timed with frames paced by the display, then
|
||||||
|
// with frames back to back (see render_debug.uncapped), after a warmup. meshing the whole level is timed too, the
|
||||||
|
// first time and again. the report says what the computer and the browser are, see report.ts
|
||||||
|
import { Camera } from "@/client/camera.ts";
|
||||||
|
import { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
|
import type { GameRenderer } from "@/client/rendering/game_renderer.ts";
|
||||||
|
import { block_visuals } from "@/client/rendering/visuals.ts";
|
||||||
|
import { draw_item } from "@/client/rendering/render_utils.ts";
|
||||||
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
|
import { platform } from "@/client/platform.ts";
|
||||||
|
import { type FrameSample, profiler } from "@/client/profiler.ts";
|
||||||
|
import { RemotePlayer } from "@/client/entity/remote_player.ts";
|
||||||
|
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
|
import { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
|
import { tick_texture_animations } from "@/client/texture_animations.ts";
|
||||||
|
import {
|
||||||
|
adapter_info,
|
||||||
|
device,
|
||||||
|
draw_text,
|
||||||
|
gpu_timer,
|
||||||
|
render_debug,
|
||||||
|
render_stats,
|
||||||
|
set_canvas_size,
|
||||||
|
} from "@/client/renderer/mod.ts";
|
||||||
|
import { ID_MASK, SLOT_SIZE, STATE_SHIFT } from "@/common/constants.ts";
|
||||||
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
|
import { TIMES_OF_DAY } from "@/common/time.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry, RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
|
import type { ModListing } from "@/common/mod_loader.ts";
|
||||||
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { display_name } from "@/common/utils.ts";
|
||||||
|
import {
|
||||||
|
bench_blocks,
|
||||||
|
type BenchBlocks,
|
||||||
|
BenchTerrain,
|
||||||
|
LEVEL_RADIUS,
|
||||||
|
LEVEL_SHAPE,
|
||||||
|
SEA_LEVEL,
|
||||||
|
UPDATE_WALL,
|
||||||
|
ZONES,
|
||||||
|
} from "./bench_level.ts";
|
||||||
|
import {
|
||||||
|
BENCHMARK_VERSION,
|
||||||
|
type BenchmarkReport,
|
||||||
|
frame_stats,
|
||||||
|
type MeshingResult,
|
||||||
|
type SceneResult,
|
||||||
|
type SystemInfo,
|
||||||
|
time_stats,
|
||||||
|
} from "./report.ts";
|
||||||
|
|
||||||
|
// each scene's parts. warmup and settle aren't counted, settle is for the switch to uncapped frames
|
||||||
|
const PHASES = [
|
||||||
|
{ phase: "warmup", ms: 1500 },
|
||||||
|
{ phase: "paced", ms: 5000 },
|
||||||
|
{ phase: "settle", ms: 500 },
|
||||||
|
{ phase: "uncapped", ms: 4000 },
|
||||||
|
] as const;
|
||||||
|
// every run draws at this size, scaled to fit the window, so runs in different windows compare
|
||||||
|
const RESOLUTION = { width: 1920, height: 1080 };
|
||||||
|
// how long a frame spends building the level, it's built over many so the page keeps responding
|
||||||
|
const BUILD_MS_PER_FRAME = 30;
|
||||||
|
// meshing the level gives up after this
|
||||||
|
const MESHING_TIMEOUT_MS = 120_000;
|
||||||
|
// meshes each worker is given at once, see ClientLevel.max_meshes_in_flight
|
||||||
|
const MESHES_PER_WORKER = 8;
|
||||||
|
// walking round the arena
|
||||||
|
const PLAYERS = 40;
|
||||||
|
const MOBS = 80;
|
||||||
|
// in blocks per tick
|
||||||
|
const WALK_SPEED = 0.2;
|
||||||
|
// lying in the middle of it
|
||||||
|
const ITEMS = 160;
|
||||||
|
const ITEM_ROW = 16;
|
||||||
|
const ITEM_SPACING = 0.6;
|
||||||
|
// the gui scene's lines of item names, about as long as the screen is wide
|
||||||
|
const GUI_LINE_LENGTH = 160;
|
||||||
|
|
||||||
|
interface Scene {
|
||||||
|
name: string;
|
||||||
|
// where the camera is t of the way through each part of the scene, from 0 to 1
|
||||||
|
camera: (camera: Camera, t: number) => void;
|
||||||
|
msaa?: boolean;
|
||||||
|
// before and after it, for what only it has
|
||||||
|
start?: () => void;
|
||||||
|
end?: () => void;
|
||||||
|
// every tick
|
||||||
|
tick?: (ticks: number) => void;
|
||||||
|
// over the level, like a screen
|
||||||
|
draw?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// an entity going round the arena
|
||||||
|
interface Walker {
|
||||||
|
entity: RemotePlayer | RemoteEntity;
|
||||||
|
radius: number;
|
||||||
|
angle: number;
|
||||||
|
// radians per tick, negative is clockwise
|
||||||
|
speed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RenderBenchmark {
|
||||||
|
// what it's doing, shown while it runs
|
||||||
|
status = "Building the level";
|
||||||
|
|
||||||
|
#renderer: GameRenderer;
|
||||||
|
#mods: ModListing[];
|
||||||
|
// with the report, or why it stopped
|
||||||
|
#on_end: (result: BenchmarkReport | string) => void;
|
||||||
|
#ended = false;
|
||||||
|
#level: ClientLevel;
|
||||||
|
#blocks: BenchBlocks;
|
||||||
|
#camera = new Camera();
|
||||||
|
// what's drawn, nothing while the level is built
|
||||||
|
#scene: Scene | undefined;
|
||||||
|
// how far through the scene's part it is
|
||||||
|
#t = 0;
|
||||||
|
#flow: Generator<void, void>;
|
||||||
|
#build_ms = 0;
|
||||||
|
#walkers: Walker[] = [];
|
||||||
|
// every item, for the gui scene and the ones lying in the arena
|
||||||
|
#items: ItemStack[];
|
||||||
|
// a line of names for each row of the gui scene's slots
|
||||||
|
#gui_lines: string[];
|
||||||
|
#system: SystemInfo;
|
||||||
|
// the game was hidden, which held frames back
|
||||||
|
#hidden = false;
|
||||||
|
#stop_watching_shown: () => void;
|
||||||
|
#saved_debug = { ...render_debug };
|
||||||
|
#saved_draw: Record<string, boolean>;
|
||||||
|
|
||||||
|
constructor(renderer: GameRenderer, mods: ModListing[], on_end: (result: BenchmarkReport | string) => void) {
|
||||||
|
this.#blocks = bench_blocks(new Set(block_visuals.keys()));
|
||||||
|
this.#renderer = renderer;
|
||||||
|
this.#mods = mods;
|
||||||
|
this.#on_end = on_end;
|
||||||
|
this.#items = EverythingRegistry.entries("items").map(([id]) => id).sort().map((id) => new ItemStack(id));
|
||||||
|
const names = this.#items.map((item) => display_name(item.type_id)).join(" ");
|
||||||
|
this.#gui_lines = Array.from(
|
||||||
|
{ length: Math.floor(RESOLUTION.height / SLOT_SIZE) },
|
||||||
|
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
|
||||||
|
this.#level.time = TIMES_OF_DAY.noon;
|
||||||
|
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
|
||||||
|
this.#system = system_info(this.#level.workers.size);
|
||||||
|
|
||||||
|
// what the f3 window switched is put back after
|
||||||
|
const draw = renderer.level_renderer.draw;
|
||||||
|
this.#saved_draw = { ...draw };
|
||||||
|
for (const key of Object.keys(draw) as (keyof typeof draw)[]) draw[key] = true;
|
||||||
|
Object.assign(render_debug, { msaa: false, split_passes: false, uncapped: false });
|
||||||
|
set_canvas_size(RESOLUTION);
|
||||||
|
this.#stop_watching_shown = platform.on_shown(() => this.#hidden = true);
|
||||||
|
this.#flow = this.#run();
|
||||||
|
}
|
||||||
|
|
||||||
|
// at the start of the client's frame, before its ticks
|
||||||
|
frame() {
|
||||||
|
this.#guard(() => {
|
||||||
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
|
this.#end("The benchmark was stopped");
|
||||||
|
} else if (this.#hidden) {
|
||||||
|
this.#end("The benchmark stopped since the game was hidden, which holds frames back");
|
||||||
|
} else {
|
||||||
|
this.#flow.next();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// instead of the client's tick, which waits
|
||||||
|
tick() {
|
||||||
|
this.#guard(() => {
|
||||||
|
this.#scene?.tick?.(this.#level.ticks);
|
||||||
|
this.#level.tick();
|
||||||
|
this.#level.time = TIMES_OF_DAY.noon;
|
||||||
|
tick_texture_animations();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// instead of the client's drawing
|
||||||
|
render(partial_tick: number) {
|
||||||
|
this.#guard(() => {
|
||||||
|
const scene = this.#scene;
|
||||||
|
if (scene) {
|
||||||
|
scene.camera(this.#camera, Math.min(this.#t, 1));
|
||||||
|
this.#renderer.render_level(this.#level, this.#camera, partial_tick);
|
||||||
|
scene.draw?.();
|
||||||
|
}
|
||||||
|
draw_text(`Benchmark: ${this.status}. Escape stops it`, 8, 8);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// a benchmark that throws stops, so the game goes on
|
||||||
|
#guard(fn: () => void) {
|
||||||
|
if (this.#ended) return;
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
this.#end(`The benchmark failed: ${e instanceof Error ? e.message : e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#end(result: BenchmarkReport | string) {
|
||||||
|
this.#ended = true;
|
||||||
|
this.#level.dispose();
|
||||||
|
Object.assign(render_debug, this.#saved_debug);
|
||||||
|
Object.assign(this.#renderer.level_renderer.draw, this.#saved_draw);
|
||||||
|
set_canvas_size(undefined);
|
||||||
|
profiler.samples = undefined;
|
||||||
|
if (gpu_timer) gpu_timer.samples = undefined;
|
||||||
|
this.#stop_watching_shown();
|
||||||
|
this.#on_end(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the whole benchmark, a frame at each yield
|
||||||
|
*#run(): Generator<void, void> {
|
||||||
|
yield* this.#build();
|
||||||
|
const first_mesh = yield* this.#mesh(false);
|
||||||
|
const remesh = yield* this.#mesh(true);
|
||||||
|
const scenes: Record<string, SceneResult> = {};
|
||||||
|
const list = this.#scenes();
|
||||||
|
for (const [i, scene] of list.entries()) {
|
||||||
|
scenes[scene.name] = yield* this.#measure(scene, `${i + 1} of ${list.length}`);
|
||||||
|
}
|
||||||
|
// the mean, firefox's timer only counts whole ms
|
||||||
|
const sky = scenes.sky?.paced;
|
||||||
|
if (sky) this.#system.refresh_hz = Math.round(sky.fps);
|
||||||
|
this.#end({
|
||||||
|
version: BENCHMARK_VERSION,
|
||||||
|
date: new Date().toISOString(),
|
||||||
|
system: this.#system,
|
||||||
|
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
|
||||||
|
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
|
||||||
|
render_regions: render_debug.render_regions,
|
||||||
|
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
|
||||||
|
first_mesh,
|
||||||
|
remesh,
|
||||||
|
scenes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
*#build(): Generator<void, void> {
|
||||||
|
const terrain = new BenchTerrain(this.#blocks);
|
||||||
|
const chunks: [number, number][] = [];
|
||||||
|
for (let z = -LEVEL_RADIUS; z < LEVEL_RADIUS; z++) {
|
||||||
|
for (let x = -LEVEL_RADIUS; x < LEVEL_RADIUS; x++) chunks.push([x, z]);
|
||||||
|
}
|
||||||
|
let built = 0;
|
||||||
|
while (built < chunks.length) {
|
||||||
|
const start = performance.now();
|
||||||
|
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
|
||||||
|
const [x, z] = chunks[built++];
|
||||||
|
this.#level.set_chunk(terrain.chunk(x, z));
|
||||||
|
}
|
||||||
|
this.#build_ms += performance.now() - start;
|
||||||
|
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
|
||||||
|
yield;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// meshing every chunk that can be, the first time and again once the workers have warmed up
|
||||||
|
*#mesh(again: boolean): Generator<void, MeshingResult> {
|
||||||
|
const level = this.#level;
|
||||||
|
this.#scene = { name: "meshing", camera: overlook };
|
||||||
|
this.status = again ? "meshing the level again" : "meshing the level";
|
||||||
|
if (again) level.remesh_all();
|
||||||
|
const frames: FrameSample[] = [];
|
||||||
|
profiler.samples = frames;
|
||||||
|
const start = performance.now();
|
||||||
|
// this frame asks for the first meshes
|
||||||
|
do {
|
||||||
|
yield;
|
||||||
|
if (performance.now() - start > MESHING_TIMEOUT_MS) throw new Error("meshing the level took too long");
|
||||||
|
} while (level.meshes_pending > 0);
|
||||||
|
profiler.samples = undefined;
|
||||||
|
return {
|
||||||
|
chunks: [...level.chunks.values()].filter((chunk) => level.can_mesh(chunk)).length,
|
||||||
|
ms: performance.now() - start,
|
||||||
|
paced: frame_stats(frames.map((frame) => frame.interval)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
*#measure(scene: Scene, progress: string): Generator<void, SceneResult> {
|
||||||
|
this.#scene = scene;
|
||||||
|
scene.start?.();
|
||||||
|
render_debug.msaa = scene.msaa ?? false;
|
||||||
|
const timed: Partial<Record<"paced" | "uncapped", { frames: FrameSample[]; gpu: number[] }>> = {};
|
||||||
|
let drawn = this.#drawn();
|
||||||
|
for (const { phase, ms } of PHASES) {
|
||||||
|
this.status = `${scene.name}, ${progress}`;
|
||||||
|
render_debug.uncapped = phase === "settle" || phase === "uncapped";
|
||||||
|
const frames: FrameSample[] = [];
|
||||||
|
const gpu: number[] = [];
|
||||||
|
profiler.samples = frames;
|
||||||
|
if (gpu_timer) gpu_timer.samples = gpu;
|
||||||
|
const start = performance.now();
|
||||||
|
for (let frame = 0; (this.#t = (performance.now() - start) / ms) < 1; frame++) {
|
||||||
|
// the first frame's, where the camera always is in the same place
|
||||||
|
if (phase === "paced" && frame === 1) drawn = this.#drawn();
|
||||||
|
yield;
|
||||||
|
}
|
||||||
|
if (phase === "paced" || phase === "uncapped") timed[phase] = { frames, gpu };
|
||||||
|
}
|
||||||
|
render_debug.msaa = false;
|
||||||
|
render_debug.uncapped = false;
|
||||||
|
scene.end?.();
|
||||||
|
// the paced frames' gpu times have all come back by now
|
||||||
|
const { paced, uncapped } = timed;
|
||||||
|
return {
|
||||||
|
paced: frame_stats(paced?.frames.map((frame) => frame.interval) ?? []),
|
||||||
|
uncapped_fps: uncapped && uncapped.frames.length * 1000 /
|
||||||
|
uncapped.frames.reduce((sum, frame) => sum + frame.interval, 0),
|
||||||
|
cpu: time_stats(paced?.frames.map((frame) => frame.frame) ?? []),
|
||||||
|
gpu: time_stats(paced?.gpu ?? []),
|
||||||
|
...drawn,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the last frame drew
|
||||||
|
#drawn() {
|
||||||
|
const { draw_calls, quads } = render_stats;
|
||||||
|
const level_renderer = this.#renderer.level_renderer;
|
||||||
|
return {
|
||||||
|
draw_calls,
|
||||||
|
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
|
||||||
|
sections_in_view: level_renderer.visible_sections,
|
||||||
|
entities_in_view: level_renderer.drawn_entities,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#scenes(): Scene[] {
|
||||||
|
const sky = (camera: Camera) => place(camera, 0, 200, 0, 0, 1.5);
|
||||||
|
const { lake, arena, visuals } = ZONES;
|
||||||
|
const wall = UPDATE_WALL;
|
||||||
|
return [
|
||||||
|
// nothing in view: what every frame costs anyway, and the display's refresh
|
||||||
|
{ name: "sky", camera: sky },
|
||||||
|
// the whole level from above
|
||||||
|
{ name: "terrain", camera: overlook },
|
||||||
|
{ name: "msaa", camera: overlook, msaa: true },
|
||||||
|
// round the level, low and looking ahead, so what's in view keeps changing
|
||||||
|
{ name: "flyover", camera: flyover },
|
||||||
|
// across the lake, moving so its water is sorted again
|
||||||
|
{
|
||||||
|
name: "water",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(
|
||||||
|
camera,
|
||||||
|
lake.x + 40 + sway(t, 6),
|
||||||
|
SEA_LEVEL + 6,
|
||||||
|
lake.z + 40 - sway(t, 6),
|
||||||
|
Math.PI / 4 + sway(t, 0.3),
|
||||||
|
-0.12,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// only here, so the other scenes don't draw them
|
||||||
|
{
|
||||||
|
name: "entities",
|
||||||
|
camera: (camera, t) => place(camera, arena.x, arena.height + 8, arena.z + 30, sway(t, 0.3), -0.3),
|
||||||
|
start: () => this.#spawn_entities(),
|
||||||
|
end: () => this.#remove_entities(),
|
||||||
|
tick: () => this.#walk(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "visuals",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(camera, visuals.x, visuals.height + 10, visuals.z + 18, sway(t, 0.2), -0.5),
|
||||||
|
},
|
||||||
|
// a screen full of items over the sky
|
||||||
|
{ name: "gui", camera: sky, draw: () => this.#draw_gui() },
|
||||||
|
{
|
||||||
|
name: "block_updates",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(camera, wall.x + wall.width / 2, wall.y + 4, wall.z + 16, sway(t, 0.15), -0.1),
|
||||||
|
tick: (ticks) => this.#change_wall(ticks),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#spawn_entities() {
|
||||||
|
const level = this.#level;
|
||||||
|
const { x, z, height } = ZONES.arena;
|
||||||
|
const y = height + 1;
|
||||||
|
// four rings each way round, every other one the other way
|
||||||
|
const walk = (entity: RemotePlayer | RemoteEntity, i: number, count: number, radius: number) => {
|
||||||
|
const ring = i % 4;
|
||||||
|
const ring_radius = radius + ring * 4;
|
||||||
|
const speed = (ring % 2 === 0 ? 1 : -1) * WALK_SPEED / ring_radius;
|
||||||
|
this.#walkers.push({ entity, radius: ring_radius, angle: (i / count) * Math.PI * 2, speed });
|
||||||
|
level.add_entity(entity);
|
||||||
|
};
|
||||||
|
for (let i = 0; i < PLAYERS; i++) {
|
||||||
|
const info = { id: `benchmark_player_${i}`, name: `Player ${i + 1}`, x, y, z, yaw: 0, pitch: 0 };
|
||||||
|
walk(new RemotePlayer(level, info), i, PLAYERS, 6);
|
||||||
|
}
|
||||||
|
const types = EverythingRegistry.entries<EntityJson>("entities").map(([id]) => id).sort();
|
||||||
|
for (let i = 0; types.length > 0 && i < MOBS; i++) {
|
||||||
|
const type = types[i % types.length];
|
||||||
|
const info = {
|
||||||
|
kind: "entity" as const,
|
||||||
|
type,
|
||||||
|
id: `benchmark_mob_${i}`,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
yaw: 0,
|
||||||
|
pitch: 0,
|
||||||
|
data: {},
|
||||||
|
};
|
||||||
|
walk(new RemoteEntity(level, info), i, MOBS, 8);
|
||||||
|
}
|
||||||
|
for (let i = 0; this.#items.length > 0 && i < ITEMS; i++) {
|
||||||
|
level.add_entity(
|
||||||
|
new ItemEntity(level, {
|
||||||
|
kind: "item",
|
||||||
|
id: `benchmark_item_${i}`,
|
||||||
|
x: x + ((i % ITEM_ROW) - ITEM_ROW / 2) * ITEM_SPACING,
|
||||||
|
y,
|
||||||
|
z: z + (Math.floor(i / ITEM_ROW) - ITEMS / ITEM_ROW / 2) * ITEM_SPACING,
|
||||||
|
item: { id: this.#items[i % this.#items.length].type_id, count: 1 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#remove_entities() {
|
||||||
|
for (const id of [...this.#level.entities.keys()]) this.#level.remove_entity(id);
|
||||||
|
this.#walkers = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
#walk() {
|
||||||
|
const { x, z, height } = ZONES.arena;
|
||||||
|
for (const walker of this.#walkers) {
|
||||||
|
walker.angle += walker.speed;
|
||||||
|
const cos = Math.cos(walker.angle);
|
||||||
|
const sin = Math.sin(walker.angle);
|
||||||
|
// facing the way it goes, yaw 0 is north (-z)
|
||||||
|
const yaw = Math.atan2(sin * Math.sign(walker.speed), -cos * Math.sign(walker.speed));
|
||||||
|
walker.entity.lerp_to(x + cos * walker.radius, height + 1, z + sin * walker.radius, yaw, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every block of the wall changes every tick, between a light and stone, so the light around it changes too, the
|
||||||
|
// way the server's block changes come in
|
||||||
|
#change_wall(ticks: number) {
|
||||||
|
const { light, stone } = this.#blocks;
|
||||||
|
const [on, off] = light === undefined
|
||||||
|
? [block_id(stone), [AIR_ID, 0] as const]
|
||||||
|
: [block_id(light), block_id(stone)];
|
||||||
|
const wall = UPDATE_WALL;
|
||||||
|
for (let dy = 0; dy < wall.height; dy++) {
|
||||||
|
for (let dx = 0; dx < wall.width; dx++) {
|
||||||
|
const [id, state] = (dx + dy + ticks) % 2 === 0 ? on : off;
|
||||||
|
this.#level.apply_change(wall.x + dx, wall.y + dy, wall.z, id, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every item in slots filling the screen, with their names over them
|
||||||
|
#draw_gui() {
|
||||||
|
const items = this.#items;
|
||||||
|
if (items.length === 0) return;
|
||||||
|
const columns = Math.floor(RESOLUTION.width / SLOT_SIZE);
|
||||||
|
const rows = this.#gui_lines.length;
|
||||||
|
for (let i = 0; i < columns * rows; i++) {
|
||||||
|
const x = (i % columns) * SLOT_SIZE;
|
||||||
|
const y = Math.floor(i / columns) * SLOT_SIZE;
|
||||||
|
draw_item(items[i % items.length], x, y, false);
|
||||||
|
}
|
||||||
|
this.#gui_lines.forEach((line, row) => draw_text(line, 4, row * SLOT_SIZE + 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the camera at x y z, turned yaw from facing north (-z) and pitch up
|
||||||
|
function place(camera: Camera, x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||||
|
camera.x = x;
|
||||||
|
camera.y = y;
|
||||||
|
camera.z = z;
|
||||||
|
camera.yaw = yaw;
|
||||||
|
camera.pitch = pitch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// there and back once, from 0
|
||||||
|
function sway(t: number, amount: number) {
|
||||||
|
return Math.sin(t * Math.PI * 2) * amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the whole level from its south edge, looking a little to each side
|
||||||
|
function overlook(camera: Camera, t: number) {
|
||||||
|
place(camera, 0, 150, LEVEL_RADIUS * 16 - 8, sway(t, 0.25), -0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
// once round the level, looking ahead and a little in. yaw 0 faces north (-z)
|
||||||
|
function flyover(camera: Camera, t: number) {
|
||||||
|
const angle = t * Math.PI * 2;
|
||||||
|
const radius = LEVEL_RADIUS * 16 * 0.6;
|
||||||
|
place(camera, Math.cos(angle) * radius, 120, Math.sin(angle) * radius, Math.PI - angle - 0.3, -0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
// what apply_change takes for a block value
|
||||||
|
function block_id(value: number): readonly [string, number] {
|
||||||
|
return [EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK)!.id, value >>> STATE_SHIFT];
|
||||||
|
}
|
||||||
|
|
||||||
|
// navigator.userAgentData, chromium's client hints, which the dom typings don't have
|
||||||
|
interface UserAgentData {
|
||||||
|
getHighEntropyValues(hints: string[]): Promise<{
|
||||||
|
platform?: string;
|
||||||
|
platformVersion?: string;
|
||||||
|
architecture?: string;
|
||||||
|
fullVersionList?: { brand: string; version: string }[];
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the first that matches
|
||||||
|
const BROWSERS: [RegExp, string][] = [
|
||||||
|
[/Firefox\/([\d.]+)/, "Firefox"],
|
||||||
|
[/Edg\/([\d.]+)/, "Edge"],
|
||||||
|
[/OPR\/([\d.]+)/, "Opera"],
|
||||||
|
[/Chrome\/([\d.]+)/, "Chrome"],
|
||||||
|
[/Version\/([\d.]+).*Safari/, "Safari"],
|
||||||
|
];
|
||||||
|
const SYSTEMS: [RegExp, string][] = [
|
||||||
|
[/Windows/, "Windows"],
|
||||||
|
[/iPhone|iPad/, "iOS"],
|
||||||
|
[/Mac OS X/, "macOS"],
|
||||||
|
[/Android/, "Android"],
|
||||||
|
[/CrOS/, "ChromeOS"],
|
||||||
|
[/Linux/, "Linux"],
|
||||||
|
];
|
||||||
|
|
||||||
|
// what's running the benchmark. the browser and the system come from the user agent, then from the client hints in
|
||||||
|
// browsers that have them, which say more and come a moment later
|
||||||
|
function system_info(workers: number): SystemInfo {
|
||||||
|
const agent = navigator.userAgent;
|
||||||
|
const browser = BROWSERS.find(([pattern]) => pattern.test(agent));
|
||||||
|
const architecture = /x86_64|x64|Win64/.test(agent) ? " x86_64" : /aarch64|arm64/i.test(agent) ? " arm64" : "";
|
||||||
|
const { vendor = "", architecture: gpu_architecture = "", description = "" } = adapter_info ?? {};
|
||||||
|
const gpu = [vendor, gpu_architecture].filter(Boolean).join(" ") || "unknown gpu";
|
||||||
|
const info: SystemInfo = {
|
||||||
|
browser: browser ? `${browser[1]} ${agent.match(browser[0])![1]}` : "unknown browser",
|
||||||
|
os: (SYSTEMS.find(([pattern]) => pattern.test(agent))?.[1] ?? "unknown system") + architecture,
|
||||||
|
user_agent: agent,
|
||||||
|
cpu_threads: navigator.hardwareConcurrency,
|
||||||
|
memory_gb: (navigator as { deviceMemory?: number }).deviceMemory,
|
||||||
|
gpu: description ? `${gpu} (${description})` : gpu,
|
||||||
|
gpu_features: [...device.features].sort(),
|
||||||
|
timestamps: gpu_timer?.supported ?? false,
|
||||||
|
canvas_format: navigator.gpu.getPreferredCanvasFormat(),
|
||||||
|
// the desktop app's window is drawn a pixel to a pixel
|
||||||
|
device_pixel_ratio: globalThis.devicePixelRatio ?? 1,
|
||||||
|
screen: globalThis.screen && `${screen.width}x${screen.height}`,
|
||||||
|
workers,
|
||||||
|
};
|
||||||
|
const hints = (navigator as { userAgentData?: UserAgentData }).userAgentData;
|
||||||
|
hints?.getHighEntropyValues(["architecture", "platformVersion", "fullVersionList"]).then((values) => {
|
||||||
|
const brands = values.fullVersionList ?? [];
|
||||||
|
const brand = brands.find(({ brand }) => !/Not.A.Brand|Chromium/i.test(brand)) ??
|
||||||
|
brands.find(({ brand }) => brand === "Chromium");
|
||||||
|
if (brand) info.browser = `${brand.brand} ${brand.version}`;
|
||||||
|
info.os = [values.platform, values.platformVersion, values.architecture].filter(Boolean).join(" ");
|
||||||
|
}).catch(() => {});
|
||||||
|
return info;
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark's results and how they're written out: a table to read, then the same as json, which
|
||||||
|
// tools/compare_benchmarks.ts reads to put runs side by side
|
||||||
|
|
||||||
|
// changes when the scenes or the level change, since runs of different versions don't compare
|
||||||
|
export const BENCHMARK_VERSION = 2;
|
||||||
|
|
||||||
|
// how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and
|
||||||
|
// 99.9%) of the others were faster than
|
||||||
|
export interface FrameStats {
|
||||||
|
frames: number;
|
||||||
|
fps: number;
|
||||||
|
median_fps: number;
|
||||||
|
low_1_fps: number;
|
||||||
|
low_01_fps: number;
|
||||||
|
p99_ms: number;
|
||||||
|
max_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimeStats {
|
||||||
|
mean_ms: number;
|
||||||
|
p99_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SceneResult {
|
||||||
|
// frames as the display paces them
|
||||||
|
paced?: FrameStats;
|
||||||
|
// frames back to back, see render_debug.uncapped. only how many, the time between them says nothing since they
|
||||||
|
// come in bursts between the display's refreshes when the gpu is behind
|
||||||
|
uncapped_fps?: number;
|
||||||
|
// the main thread's and the gpu's time per frame while paced. the gpu's only with timestamp queries
|
||||||
|
cpu?: TimeStats;
|
||||||
|
gpu?: TimeStats;
|
||||||
|
// what the first paced frame drew, which runs of the same version should about agree on
|
||||||
|
draw_calls: number;
|
||||||
|
quads: number;
|
||||||
|
sections_in_view: number;
|
||||||
|
entities_in_view: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// meshing every chunk of the level that can be
|
||||||
|
export interface MeshingResult {
|
||||||
|
chunks: number;
|
||||||
|
ms: number;
|
||||||
|
paced?: FrameStats;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemInfo {
|
||||||
|
browser: string;
|
||||||
|
os: string;
|
||||||
|
user_agent: string;
|
||||||
|
cpu_threads: number;
|
||||||
|
// only chromium says, rounded down to a power of two and at most 8
|
||||||
|
memory_gb?: number;
|
||||||
|
gpu: string;
|
||||||
|
gpu_features: string[];
|
||||||
|
// whether the gpu times are there
|
||||||
|
timestamps: boolean;
|
||||||
|
canvas_format: string;
|
||||||
|
// the median fps where nothing is drawn, which is the display's refresh when the browser holds frames to it
|
||||||
|
refresh_hz?: number;
|
||||||
|
device_pixel_ratio: number;
|
||||||
|
// the browser's, the desktop app doesn't know it
|
||||||
|
screen?: string;
|
||||||
|
// meshing workers, see ChunkWorkerPool
|
||||||
|
workers: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BenchmarkReport {
|
||||||
|
version: number;
|
||||||
|
date: string;
|
||||||
|
system: SystemInfo;
|
||||||
|
// "id version"
|
||||||
|
mods: string[];
|
||||||
|
resolution: string;
|
||||||
|
// the f3 window's switch, see ClientLevel.use_render_regions
|
||||||
|
render_regions?: boolean;
|
||||||
|
level: { chunks: number; build_ms: number };
|
||||||
|
first_mesh: MeshingResult;
|
||||||
|
remesh: MeshingResult;
|
||||||
|
scenes: Record<string, SceneResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function frame_stats(intervals: number[]): FrameStats | undefined {
|
||||||
|
if (intervals.length === 0) return undefined;
|
||||||
|
const sorted = [...intervals].sort((a, b) => a - b);
|
||||||
|
const mean = sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length;
|
||||||
|
return {
|
||||||
|
frames: sorted.length,
|
||||||
|
fps: 1000 / mean,
|
||||||
|
median_fps: 1000 / percentile(sorted, 0.5),
|
||||||
|
low_1_fps: 1000 / percentile(sorted, 0.99),
|
||||||
|
low_01_fps: 1000 / percentile(sorted, 0.999),
|
||||||
|
p99_ms: percentile(sorted, 0.99),
|
||||||
|
max_ms: sorted[sorted.length - 1],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function time_stats(times: number[]): TimeStats | undefined {
|
||||||
|
if (times.length === 0) return undefined;
|
||||||
|
const sorted = [...times].sort((a, b) => a - b);
|
||||||
|
return { mean_ms: sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length, p99_ms: percentile(sorted, 0.99) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the smallest value that at least q of them are at or under
|
||||||
|
function percentile(sorted: number[], q: number) {
|
||||||
|
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];
|
||||||
|
}
|
||||||
|
|
||||||
|
// markdown, to paste where it's read, with the whole report as json at the end
|
||||||
|
export function format_report(report: BenchmarkReport): string {
|
||||||
|
const { system, first_mesh, remesh } = report;
|
||||||
|
const fps = (value?: number) => value === undefined ? "-" : value.toFixed(1);
|
||||||
|
const ms = (value?: number) => value === undefined ? "-" : value.toFixed(2);
|
||||||
|
const seconds = (ms: number) => `${(ms / 1000).toFixed(2)} s`;
|
||||||
|
const meshing = ({ chunks, ms }: MeshingResult) => `${seconds(ms)} (${Math.round(chunks / ms * 1000)} chunks/s)`;
|
||||||
|
const memory = system.memory_gb ? `, ${system.memory_gb} GB` : "";
|
||||||
|
const refresh = system.refresh_hz ? `, ${system.refresh_hz} Hz` : "";
|
||||||
|
const lines = [
|
||||||
|
`## cubi render benchmark ${report.version}`,
|
||||||
|
"",
|
||||||
|
`${system.browser} on ${system.os}, ${system.gpu}`,
|
||||||
|
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
|
||||||
|
(system.timestamps ? "" : ", no gpu timestamps") + (report.render_regions ? ", render regions" : ""),
|
||||||
|
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
|
||||||
|
"",
|
||||||
|
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
|
||||||
|
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
|
||||||
|
];
|
||||||
|
for (const [name, scene] of Object.entries(report.scenes)) {
|
||||||
|
const { paced } = scene;
|
||||||
|
lines.push(
|
||||||
|
`| ${name} | ${fps(paced?.fps)} | ${fps(paced?.low_1_fps)} | ${fps(paced?.low_01_fps)} | ` +
|
||||||
|
`${fps(scene.uncapped_fps)} | ${ms(scene.cpu?.mean_ms)} | ${ms(scene.gpu?.mean_ms)} | ` +
|
||||||
|
`${scene.draw_calls} | ${scene.quads.toLocaleString("en")} |`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
lines.push(
|
||||||
|
"",
|
||||||
|
`Meshing the level's ${first_mesh.chunks} chunks took ${meshing(first_mesh)} the first time and ` +
|
||||||
|
`${meshing(remesh)} again. Building it took ${seconds(report.level.build_ms)} of javascript.`,
|
||||||
|
"",
|
||||||
|
"```json",
|
||||||
|
JSON.stringify(report, (_, value) => typeof value === "number" ? Math.round(value * 100) / 100 : value),
|
||||||
|
"```",
|
||||||
|
);
|
||||||
|
return lines.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// the report in what format_report wrote, or json on its own
|
||||||
|
export function parse_report(text: string): BenchmarkReport {
|
||||||
|
const json = text.match(/```json\n([\s\S]*?)\n```/)?.[1] ?? text;
|
||||||
|
return JSON.parse(json);
|
||||||
|
}
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
import { Container, Inventory } from "../inventory.ts";
|
|
||||||
import { PlayerComponent } from "../player.ts";
|
|
||||||
import { GuiChest } from "$/client/gui/gui_chest.ts";
|
|
||||||
|
|
||||||
interface TileChestData {
|
|
||||||
inventory: Inventory;
|
|
||||||
}
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:chest", {
|
|
||||||
id: "bworld:chest",
|
|
||||||
textures: "bworld:planks",
|
|
||||||
toughness: 8,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "axe",
|
|
||||||
drop_table: "bworld:chest",
|
|
||||||
|
|
||||||
has_collision: false,
|
|
||||||
on_interact(dimension, block) {
|
|
||||||
const [player] = dimension.world.get_tag("player")!;
|
|
||||||
const player_component = player.get(PlayerComponent)!;
|
|
||||||
const block_data = dimension.get_block_data<TileChestData>(block.x, block.y, block.z);
|
|
||||||
if (block_data && block_data.data.inventory) {
|
|
||||||
const gui = new GuiChest(block_data.data.inventory, player_component.player_inventory);
|
|
||||||
player_component.screens.push(gui);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
on_create(dimension, block) {
|
|
||||||
dimension.add_block_data({
|
|
||||||
id: block.id,
|
|
||||||
x: block.x,
|
|
||||||
y: block.y,
|
|
||||||
z: block.z,
|
|
||||||
data: {
|
|
||||||
inventory: new Inventory(new Container(9 * 3)),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:coal_ore", {
|
|
||||||
id: "bworld:coal_ore",
|
|
||||||
textures: "bworld:stone_coal",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:coal_ore",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:copper_ore", {
|
|
||||||
id: "bworld:copper_ore",
|
|
||||||
textures: "bworld:stone_copper",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:copper_ore",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { ItemStack } from "../inventory.ts";
|
|
||||||
import { PlayerComponent } from "../player.ts";
|
|
||||||
|
|
||||||
interface CropsRegistry {
|
|
||||||
total_stages: number;
|
|
||||||
time_to_grow: number[];
|
|
||||||
item_drop: string;
|
|
||||||
sprite_ids: string[];
|
|
||||||
regrowable: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
EverythingRegistry.register<CropsRegistry>("crops", "bworld:carrot", {
|
|
||||||
total_stages: 5,
|
|
||||||
time_to_grow: [60, 60 * 3, 60 * 3, 60 * 3],
|
|
||||||
sprite_ids: [
|
|
||||||
"bworld:carrot_seeds",
|
|
||||||
"bworld:carrot_stage_1",
|
|
||||||
"bworld:carrot_stage_2",
|
|
||||||
"bworld:carrot_stage_3",
|
|
||||||
"bworld:carrot_stage_4",
|
|
||||||
],
|
|
||||||
item_drop: "bworld:carrot",
|
|
||||||
regrowable: false,
|
|
||||||
});
|
|
||||||
EverythingRegistry.register<CropsRegistry>("crops", "bworld:potato", {
|
|
||||||
total_stages: 5,
|
|
||||||
time_to_grow: [45, 60 * 2, 60 * 2, 60 * 2],
|
|
||||||
sprite_ids: [
|
|
||||||
"bworld:potato_seeds",
|
|
||||||
"bworld:potato_stage_1",
|
|
||||||
"bworld:potato_stage_2",
|
|
||||||
"bworld:potato_stage_3",
|
|
||||||
"bworld:potato_stage_4",
|
|
||||||
],
|
|
||||||
item_drop: "bworld:potato",
|
|
||||||
regrowable: false,
|
|
||||||
});
|
|
||||||
EverythingRegistry.register<CropsRegistry>("crops", "bworld:tomato", {
|
|
||||||
total_stages: 5,
|
|
||||||
time_to_grow: [90, 60 * 2, 60 * 2, 60 * 3],
|
|
||||||
sprite_ids: [
|
|
||||||
"bworld:tomato_seeds",
|
|
||||||
"bworld:tomato_stage_1",
|
|
||||||
"bworld:tomato_stage_2",
|
|
||||||
"bworld:tomato_stage_3",
|
|
||||||
"bworld:tomato_stage_4",
|
|
||||||
],
|
|
||||||
item_drop: "bworld:tomato",
|
|
||||||
regrowable: true,
|
|
||||||
});
|
|
||||||
EverythingRegistry.register<CropsRegistry>("crops", "bworld:pumpkin", {
|
|
||||||
total_stages: 5,
|
|
||||||
time_to_grow: [60 * 2, 60 * 4, 60 * 4, 60 * 4],
|
|
||||||
sprite_ids: [
|
|
||||||
"bworld:pumpkin_seeds",
|
|
||||||
"bworld:pumpkin_stage_1",
|
|
||||||
"bworld:pumpkin_stage_2",
|
|
||||||
"bworld:pumpkin_stage_3",
|
|
||||||
"bworld:pumpkin_stage_4",
|
|
||||||
],
|
|
||||||
item_drop: "bworld:pumpkin",
|
|
||||||
regrowable: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
interface TileCropData {
|
|
||||||
current_stage: number;
|
|
||||||
growth_time: number;
|
|
||||||
}
|
|
||||||
/*
|
|
||||||
function create_crop_tile(crop_id: string) {
|
|
||||||
const crop_info = EverythingRegistry.get<CropsRegistry>("crops", crop_id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
has_collision: false,
|
|
||||||
on_create(_, tile) {
|
|
||||||
tile.data = {
|
|
||||||
current_stage: 0,
|
|
||||||
growth_time: 0,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
texture_id(tile) {
|
|
||||||
return crop_info.sprite_ids[tile.data!.current_stage];
|
|
||||||
},
|
|
||||||
on_click(world, tile) {
|
|
||||||
const [player] = world.get_tag("player")!;
|
|
||||||
const player_inventory = player.get(PlayerComponent)!.player_inventory;
|
|
||||||
const item = player_inventory.container.get_item(player_inventory.hotbar_selected);
|
|
||||||
if (!item) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (item.type_id === "bworld:pickaxe") {
|
|
||||||
world.dimension.delete_tile(world, tile);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
on_interact(world, tile) {
|
|
||||||
if (tile.data!.current_stage + 1 !== crop_info.total_stages) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const [player] = world.get_tag("player")!;
|
|
||||||
const player_inventory = player.get(PlayerComponent)!.player_inventory;
|
|
||||||
player_inventory.container.add_item(new ItemStack(crop_info.item_drop));
|
|
||||||
if (crop_info.regrowable) {
|
|
||||||
tile.data!.current_stage -= 1;
|
|
||||||
} else {
|
|
||||||
world.dimension.delete_tile(world, tile);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
on_second(_, tile, delta) {
|
|
||||||
const crop = tile.data!;
|
|
||||||
// finished growing
|
|
||||||
if (crop.current_stage + 1 === crop_info.total_stages) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// grow !
|
|
||||||
crop.growth_time += delta;
|
|
||||||
if (crop.growth_time >= crop_info.time_to_grow[crop.current_stage]) {
|
|
||||||
crop.current_stage += 1;
|
|
||||||
crop.growth_time = 0;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
} as BlockRegistry<TileCropData>;
|
|
||||||
}
|
|
||||||
|
|
||||||
EverythingRegistry.register<BlockRegistry<TileCropData>>(
|
|
||||||
"blocks",
|
|
||||||
"bworld:tomato_crop",
|
|
||||||
create_crop_tile("bworld:tomato"),
|
|
||||||
);
|
|
||||||
EverythingRegistry.register<BlockRegistry<TileCropData>>(
|
|
||||||
"blocks",
|
|
||||||
"bworld:carrot_crop",
|
|
||||||
create_crop_tile("bworld:carrot"),
|
|
||||||
);
|
|
||||||
EverythingRegistry.register<BlockRegistry<TileCropData>>(
|
|
||||||
"blocks",
|
|
||||||
"bworld:potato_crop",
|
|
||||||
create_crop_tile("bworld:potato"),
|
|
||||||
);
|
|
||||||
EverythingRegistry.register<BlockRegistry<TileCropData>>(
|
|
||||||
"blocks",
|
|
||||||
"bworld:pumpkin_crop",
|
|
||||||
create_crop_tile("bworld:pumpkin"),
|
|
||||||
);
|
|
||||||
*/
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
import { PlayerComponent } from "../player.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:dirt", {
|
|
||||||
id: "bworld:dirt",
|
|
||||||
textures: "bworld:dirt",
|
|
||||||
has_collision: false,
|
|
||||||
drop_table: "bworld:dirt",
|
|
||||||
toughness: 2,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "shovel",
|
|
||||||
|
|
||||||
on_interact(dimension, block) {
|
|
||||||
const [player] = dimension.world.get_tag("player")!;
|
|
||||||
const player_inventory = player.get(PlayerComponent)!.player_inventory;
|
|
||||||
const maybe_item = player_inventory.container.get_item(player_inventory.hotbar_selected);
|
|
||||||
if (maybe_item && maybe_item.type_id === "bworld:hoe") {
|
|
||||||
dimension.add_block({ x: block.x, y: block.y, z: block.z, id: "bworld:hoed_dirt" });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { Container, Inventory, ItemStack } from "../inventory.ts";
|
|
||||||
import { PlayerComponent } from "../player.ts";
|
|
||||||
import { GuiFurnace } from "$/client/gui/gui_furnace.ts";
|
|
||||||
import { register_block_item } from "../../common/utils.ts";
|
|
||||||
|
|
||||||
interface FurnaceRecipe {
|
|
||||||
input: string;
|
|
||||||
output: ItemStack;
|
|
||||||
cook_time: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const FURNACE_RECIPES: FurnaceRecipe[] = [
|
|
||||||
{
|
|
||||||
input: "bworld:log",
|
|
||||||
output: new ItemStack("bworld:coal", 1),
|
|
||||||
cook_time: 100,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
input: "bworld:coal_ore",
|
|
||||||
output: new ItemStack("bworld:coal", 1),
|
|
||||||
cook_time: 100,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
input: "bworld:iron_ore",
|
|
||||||
output: new ItemStack("bworld:iron_ingot", 1),
|
|
||||||
cook_time: 200,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
input: "bworld:tin_ore",
|
|
||||||
output: new ItemStack("bworld:tin_ingot", 1),
|
|
||||||
cook_time: 200,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
input: "bworld:copper_ore",
|
|
||||||
output: new ItemStack("bworld:copper_ingot", 1),
|
|
||||||
cook_time: 200,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
input: "bworld:gold_ore",
|
|
||||||
output: new ItemStack("bworld:gold_ingot", 1),
|
|
||||||
cook_time: 200,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
function get_recipe(input?: ItemStack | undefined): FurnaceRecipe | undefined {
|
|
||||||
if (!input) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return FURNACE_RECIPES.find((r) => r.input === input.type_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function can_craft(container: Container, recipe?: FurnaceRecipe) {
|
|
||||||
if (!recipe) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const output = container.get_item(2);
|
|
||||||
|
|
||||||
if (!output) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (output.type_id !== recipe.output.type_id) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return output.amount < output.max_amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
const FUEL_VALUES: Record<string, number> = {
|
|
||||||
"bworld:coal": 1000,
|
|
||||||
"bworld:log": 100,
|
|
||||||
};
|
|
||||||
|
|
||||||
function get_fuel_value(item?: ItemStack | undefined): number {
|
|
||||||
if (!item) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return FUEL_VALUES[item.type_id] ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function has_fuel(container: Container) {
|
|
||||||
return get_fuel_value(container.get_item(1)) > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function consume_fuel(container: Container): number {
|
|
||||||
const fuel = container.get_slot(1)!;
|
|
||||||
const value = get_fuel_value(fuel.get_item());
|
|
||||||
|
|
||||||
if (fuel.has_item()) {
|
|
||||||
fuel.amount! -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function craft(container: Container, recipe: FurnaceRecipe) {
|
|
||||||
const input = container.get_item(0)!;
|
|
||||||
const output = container.get_item(2);
|
|
||||||
|
|
||||||
if (!output) {
|
|
||||||
container.set_item(2, recipe.output.clone());
|
|
||||||
} else {
|
|
||||||
output.amount += recipe.output.amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
input.amount -= 1;
|
|
||||||
container.set_item(0, input.amount > 0 ? input : undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TileChestData {
|
|
||||||
inventory: Inventory;
|
|
||||||
progress: number;
|
|
||||||
progress_max: number;
|
|
||||||
fuel: number;
|
|
||||||
fuel_max: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:furnace", {
|
|
||||||
id: "bworld:furnace",
|
|
||||||
textures: { front: "bworld:furnace", side: "bworld:stone" },
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:furnace",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
|
|
||||||
on_interact(dimension, block) {
|
|
||||||
const [player] = dimension.world.get_tag("player")!;
|
|
||||||
const player_component = player.get(PlayerComponent)!;
|
|
||||||
const block_data = dimension.get_block_data<TileChestData>(block.x, block.y, block.z);
|
|
||||||
if (block_data && block_data.data.inventory) {
|
|
||||||
const gui = new GuiFurnace(block_data.data.inventory, player_component.player_inventory, block_data.data);
|
|
||||||
player_component.screens.push(gui);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
on_create(dimension, block) {
|
|
||||||
dimension.add_block_data({
|
|
||||||
id: block.id,
|
|
||||||
x: block.x,
|
|
||||||
y: block.y,
|
|
||||||
z: block.z,
|
|
||||||
data: {
|
|
||||||
inventory: new Inventory(new Container(3)),
|
|
||||||
progress: 0,
|
|
||||||
progress_max: 0,
|
|
||||||
fuel: 0,
|
|
||||||
fuel_max: 0,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
on_break() {
|
|
||||||
// TODO: remove block data
|
|
||||||
},
|
|
||||||
on_tick(dimension, block) {
|
|
||||||
const block_data = dimension.get_block_data<TileChestData>(block.x, block.y, block.z);
|
|
||||||
if (!block_data) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = block_data.data;
|
|
||||||
const container = data.inventory.container;
|
|
||||||
|
|
||||||
const input = container.get_item(0);
|
|
||||||
const recipe = get_recipe(input);
|
|
||||||
|
|
||||||
// burn fuel
|
|
||||||
if (data.fuel > 0) {
|
|
||||||
data.fuel -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!can_craft(container, recipe)) {
|
|
||||||
data.progress = 0;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// refuel
|
|
||||||
if (data.fuel === 0 && has_fuel(container)) {
|
|
||||||
data.fuel = consume_fuel(container);
|
|
||||||
data.fuel_max = data.fuel;
|
|
||||||
}
|
|
||||||
|
|
||||||
// cook
|
|
||||||
if (data.fuel > 0 && recipe) {
|
|
||||||
data.progress_max = recipe.cook_time;
|
|
||||||
data.progress += 1;
|
|
||||||
|
|
||||||
if (data.progress >= recipe.cook_time) {
|
|
||||||
data.progress = 0;
|
|
||||||
craft(container, recipe);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:glass", {
|
|
||||||
id: "bworld:glass",
|
|
||||||
textures: "bworld:glass",
|
|
||||||
has_collision: true,
|
|
||||||
transparent: true,
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:gold_ore", {
|
|
||||||
id: "bworld:gold_ore",
|
|
||||||
textures: "bworld:stone_gold",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:gold_ore",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { PlayerComponent } from "../player.ts";
|
|
||||||
|
|
||||||
EverythingRegistry.register<BlockRegistry>("blocks", "bworld:grass", {
|
|
||||||
id: "bworld:grass",
|
|
||||||
textures: { top: "bworld:grass_top", bottom: "bworld:dirt", "side": "bworld:grass_side" },
|
|
||||||
has_collision: false,
|
|
||||||
drop_table: "bworld:dirt",
|
|
||||||
toughness: 2,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "shovel",
|
|
||||||
|
|
||||||
on_interact(dimension, block) {
|
|
||||||
const [player] = dimension.world.get_tag("player")!;
|
|
||||||
const player_inventory = player.get(PlayerComponent)!.player_inventory;
|
|
||||||
const item = player_inventory.container.get_item(player_inventory.hotbar_selected);
|
|
||||||
if (item?.type_id === "bworld:hoe") {
|
|
||||||
block.id = "bworld:hoed_dirt";
|
|
||||||
dimension.add_block(block);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
// TODO: watered state
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:hoed_dirt", {
|
|
||||||
id: "bworld:hoed_dirt",
|
|
||||||
textures: { side: "bworld:dirt", top: "bworld:hoed_dirt", bottom: "bworld:dirt" },
|
|
||||||
has_collision: false,
|
|
||||||
drop_table: "bworld:dirt",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "shovel",
|
|
||||||
states: [
|
|
||||||
{ name: "watered", bits: 1, default: 0 },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:iron_ore", {
|
|
||||||
id: "bworld:iron_ore",
|
|
||||||
textures: "bworld:stone_iron",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:iron_ore",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:leaves", {
|
|
||||||
id: "bworld:leaves",
|
|
||||||
textures: "bworld:leaves",
|
|
||||||
has_collision: true,
|
|
||||||
transparent: true,
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "hoe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:log", {
|
|
||||||
id: "bworld:log",
|
|
||||||
textures: { side: "bworld:log_side", top: "bworld:log_top", bottom: "bworld:log_top" },
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:log",
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "axe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import "./grass.ts";
|
|
||||||
import "./dirt.ts";
|
|
||||||
import "./crops.ts";
|
|
||||||
import "./water.ts";
|
|
||||||
import "./chest.ts";
|
|
||||||
import "./furnace.ts";
|
|
||||||
import "./stone.ts";
|
|
||||||
import "./log.ts";
|
|
||||||
import "./sand.ts";
|
|
||||||
import "./snow.ts";
|
|
||||||
import "./glass.ts";
|
|
||||||
import "./hoed_dirt.ts";
|
|
||||||
import "./leaves.ts";
|
|
||||||
import "./coal_ore.ts";
|
|
||||||
import "./copper_ore.ts";
|
|
||||||
import "./iron_ore.ts";
|
|
||||||
import "./tin_ore.ts";
|
|
||||||
import "./gold_ore.ts";
|
|
||||||
import "./planks.ts";
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:planks", {
|
|
||||||
id: "bworld:planks",
|
|
||||||
textures: "bworld:planks",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:log",
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "axe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:sand", {
|
|
||||||
id: "bworld:sand",
|
|
||||||
textures: "bworld:sand",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:sand",
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: false,
|
|
||||||
tool_to_break: "shovel",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:snow", {
|
|
||||||
id: "bworld:snow",
|
|
||||||
textures: "bworld:snow",
|
|
||||||
has_collision: true,
|
|
||||||
toughness: 2,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "shovel",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:stone", {
|
|
||||||
id: "bworld:stone",
|
|
||||||
textures: "bworld:stone",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:stone",
|
|
||||||
toughness: 3,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { register_block_item } from "$/common/utils.ts";
|
|
||||||
|
|
||||||
const block = EverythingRegistry.register<BlockRegistry>("blocks", "bworld:tin_ore", {
|
|
||||||
id: "bworld:tin_ore",
|
|
||||||
textures: "bworld:stone_tin",
|
|
||||||
has_collision: true,
|
|
||||||
drop_table: "bworld:tin_ore",
|
|
||||||
toughness: 5,
|
|
||||||
requires_tool: true,
|
|
||||||
tool_to_break: "pickaxe",
|
|
||||||
});
|
|
||||||
|
|
||||||
register_block_item(block);
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
|
|
||||||
EverythingRegistry.register<BlockRegistry>("blocks", "bworld:water", {
|
|
||||||
id: "bworld:water",
|
|
||||||
textures: "bworld:water",
|
|
||||||
has_collision: false,
|
|
||||||
transparent: true,
|
|
||||||
alpha: 0.8,
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the page's keys and mouse for InputManager, and grabbing the mouse with the browser's pointer lock
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
|
||||||
|
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
||||||
|
// can keep alt+tab and the windows key from the os too
|
||||||
|
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
||||||
|
|
||||||
|
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
||||||
|
interface KeyboardLock {
|
||||||
|
lock(codes?: string[]): Promise<void>;
|
||||||
|
unlock(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let canvas: HTMLCanvasElement;
|
||||||
|
|
||||||
|
let pointer_lock_flag = false;
|
||||||
|
let mouse_ungrab_timer = 0;
|
||||||
|
let mouse_ungrab_timeout = -1;
|
||||||
|
let pointer_lock_waiting = false;
|
||||||
|
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
||||||
|
let skip_look_event = false;
|
||||||
|
// the browser let go of the mouse while the game wanted it, like escape or switching windows
|
||||||
|
let lost_pointer_lock = false;
|
||||||
|
|
||||||
|
export function listen_to_page(page_canvas: HTMLCanvasElement) {
|
||||||
|
canvas = page_canvas;
|
||||||
|
|
||||||
|
self.addEventListener("keydown", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
InputManager.key_down(e.code, e.key, is_shortcut(e));
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("blur", () => InputManager.release_all());
|
||||||
|
|
||||||
|
self.addEventListener("keyup", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
InputManager.key_up(e.code);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("mousedown", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
||||||
|
set_mouse_grabbed(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
InputManager.mouse_down(e.button);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("mouseup", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
InputManager.mouse_up(e.button);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
||||||
|
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
||||||
|
self.addEventListener("wheel", (e) => {
|
||||||
|
if (e.ctrlKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
InputManager.scroll(e.deltaY);
|
||||||
|
}, { passive: false });
|
||||||
|
|
||||||
|
document.addEventListener("mousemove", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (document.pointerLockElement === canvas) {
|
||||||
|
if (skip_look_event) {
|
||||||
|
skip_look_event = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
InputManager.look(e.movementX, e.movementY);
|
||||||
|
} else {
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
InputManager.move_cursor(e.clientX - rect.left, e.clientY - rect.top);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("pointerlockchange", () => {
|
||||||
|
skip_look_event = document.pointerLockElement === canvas;
|
||||||
|
self.setTimeout(() => {
|
||||||
|
const grab = document.pointerLockElement === canvas;
|
||||||
|
if (!grab) {
|
||||||
|
if (pointer_lock_flag) {
|
||||||
|
mouse_ungrab_timer = performance.now();
|
||||||
|
lost_pointer_lock = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pointer_lock_flag = grab;
|
||||||
|
}, 60);
|
||||||
|
pointer_lock_waiting = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
||||||
|
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
||||||
|
document.addEventListener("fullscreenchange", () => {
|
||||||
|
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
||||||
|
if (!keyboard?.lock) return;
|
||||||
|
if (document.fullscreenElement) {
|
||||||
|
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
||||||
|
} else {
|
||||||
|
keyboard.unlock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("pointerlockerror", () => {
|
||||||
|
pointer_lock_waiting = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
||||||
|
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
||||||
|
function is_shortcut(e: KeyboardEvent) {
|
||||||
|
return e.metaKey || (e.ctrlKey && !e.altKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function set_mouse_grabbed(grab: boolean) {
|
||||||
|
pointer_lock_flag = grab;
|
||||||
|
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
||||||
|
if (!grab && mouse_ungrab_timeout !== -1) {
|
||||||
|
self.clearTimeout(mouse_ungrab_timeout);
|
||||||
|
mouse_ungrab_timeout = -1;
|
||||||
|
}
|
||||||
|
// already how it should be, the game calls this every frame
|
||||||
|
const locked = document.pointerLockElement === canvas;
|
||||||
|
if (grab ? locked : !locked && !pointer_lock_waiting) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = performance.now();
|
||||||
|
if (grab) {
|
||||||
|
InputManager.mouse_x = -1;
|
||||||
|
InputManager.mouse_y = -1;
|
||||||
|
pointer_lock_waiting = true;
|
||||||
|
try {
|
||||||
|
await canvas.requestPointerLock();
|
||||||
|
} catch (_) { /* */ }
|
||||||
|
if (mouse_ungrab_timeout !== -1) {
|
||||||
|
self.clearTimeout(mouse_ungrab_timeout);
|
||||||
|
}
|
||||||
|
mouse_ungrab_timeout = -1;
|
||||||
|
if (t - mouse_ungrab_timer < 3000) {
|
||||||
|
mouse_ungrab_timeout = self.setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await canvas.requestPointerLock();
|
||||||
|
} catch (_) { /* */ }
|
||||||
|
}, 3100 - (t - mouse_ungrab_timer));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!pointer_lock_waiting) {
|
||||||
|
document.exitPointerLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// whether the browser took the mouse away since the last call, it eats the escape that does it
|
||||||
|
export function take_lost_pointer_lock() {
|
||||||
|
const lost = lost_pointer_lock;
|
||||||
|
lost_pointer_lock = false;
|
||||||
|
return lost;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function is_mouse_grabbed() {
|
||||||
|
return document.hasFocus() && document.pointerLockElement === canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toggle_fullscreen() {
|
||||||
|
if (!document.fullscreenElement) {
|
||||||
|
canvas.requestFullscreen();
|
||||||
|
} else {
|
||||||
|
document.exitFullscreen();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the client in a browser page, see platform.ts
|
||||||
|
import type { Platform } from "./platform.ts";
|
||||||
|
import { render_debug } from "./renderer/mod.ts";
|
||||||
|
import { CreditsScreen } from "./gui/credits_screen.ts";
|
||||||
|
import { is_mouse_grabbed, set_mouse_grabbed, take_lost_pointer_lock, toggle_fullscreen } from "./browser_input.ts";
|
||||||
|
|
||||||
|
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
|
||||||
|
// 960 on a 60 hz display, and what the gpu can be behind by
|
||||||
|
const UNCAPPED_FRAMES_PER_REFRESH = 16;
|
||||||
|
|
||||||
|
// with render_debug.uncapped: frames since the display last refreshed, and the frame waiting for the next one
|
||||||
|
let frames_this_refresh = 0;
|
||||||
|
let waiting_for_refresh: ((time: number) => void) | undefined;
|
||||||
|
let refresh_requested = false;
|
||||||
|
let next_task: MessageChannel | undefined;
|
||||||
|
let next_task_frame: ((time: number) => void) | undefined;
|
||||||
|
|
||||||
|
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
|
||||||
|
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
|
||||||
|
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
|
||||||
|
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
|
||||||
|
function request_frame(frame: (time: number) => void) {
|
||||||
|
if (!render_debug.uncapped) {
|
||||||
|
requestAnimationFrame(frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!refresh_requested) {
|
||||||
|
refresh_requested = true;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
refresh_requested = false;
|
||||||
|
frames_this_refresh = 0;
|
||||||
|
const waiting = waiting_for_refresh;
|
||||||
|
waiting_for_refresh = undefined;
|
||||||
|
waiting?.(performance.now());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
frames_this_refresh += 1;
|
||||||
|
if (frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
|
||||||
|
// a task of its own, so input and the workers' messages get handled in between
|
||||||
|
if (!next_task) {
|
||||||
|
next_task = new MessageChannel();
|
||||||
|
next_task.port1.onmessage = () => next_task_frame?.(performance.now());
|
||||||
|
}
|
||||||
|
next_task_frame = frame;
|
||||||
|
next_task.port2.postMessage(null);
|
||||||
|
} else {
|
||||||
|
waiting_for_refresh = frame;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
|
||||||
|
// still copies from a click
|
||||||
|
function write_clipboard(text: string): Promise<void> {
|
||||||
|
if (navigator.clipboard) return navigator.clipboard.writeText(text);
|
||||||
|
const area = document.createElement("textarea");
|
||||||
|
area.value = text;
|
||||||
|
document.body.append(area);
|
||||||
|
area.select();
|
||||||
|
const copied = document.execCommand("copy");
|
||||||
|
area.remove();
|
||||||
|
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function show_fatal_error(message: string) {
|
||||||
|
document.exitPointerLock?.();
|
||||||
|
|
||||||
|
const overlay = document.createElement("div");
|
||||||
|
overlay.style.cssText =
|
||||||
|
"position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;" +
|
||||||
|
"gap:12px;background:rgba(0,0,0,0.85);color:white;font:20px system-ui,sans-serif;text-align:center;";
|
||||||
|
const text = document.createElement("div");
|
||||||
|
text.textContent = message;
|
||||||
|
const hint = document.createElement("div");
|
||||||
|
hint.textContent = "Reload the page to try again.";
|
||||||
|
hint.style.cssText = "font-size:14px;opacity:0.7;";
|
||||||
|
overlay.append(text, hint);
|
||||||
|
document.body.append(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const browser_platform: Platform = {
|
||||||
|
get page() {
|
||||||
|
return new URL(location.href);
|
||||||
|
},
|
||||||
|
restart(url) {
|
||||||
|
location.href = url.href;
|
||||||
|
},
|
||||||
|
request_frame,
|
||||||
|
get storage() {
|
||||||
|
return localStorage;
|
||||||
|
},
|
||||||
|
on_shown(shown) {
|
||||||
|
const listener = () => {
|
||||||
|
if (!document.hidden) shown();
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", listener);
|
||||||
|
return () => document.removeEventListener("visibilitychange", listener);
|
||||||
|
},
|
||||||
|
// sprinting is ctrl and walking is w, and ctrl+w closes the tab without the page getting a say. in fullscreen
|
||||||
|
// the keyboard lock catches it instead (see browser_input.ts)
|
||||||
|
confirm_leaving(confirm) {
|
||||||
|
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
||||||
|
},
|
||||||
|
show_fatal_error,
|
||||||
|
credits_screen: (on_back) => new CreditsScreen(on_back),
|
||||||
|
read_clipboard: () =>
|
||||||
|
navigator.clipboard ? navigator.clipboard.readText() : Promise.reject(new Error("No clipboard")),
|
||||||
|
write_clipboard,
|
||||||
|
set_mouse_grabbed,
|
||||||
|
is_mouse_grabbed,
|
||||||
|
take_lost_mouse: take_lost_pointer_lock,
|
||||||
|
toggle_fullscreen,
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { Entity } from "./entity/entity.ts";
|
||||||
|
|
||||||
|
// where the world is drawn from. like minecraft's Camera it isn't an entity, it's moved to one's eyes every frame
|
||||||
|
export class Camera {
|
||||||
|
x = 0;
|
||||||
|
y = 0;
|
||||||
|
z = 3;
|
||||||
|
|
||||||
|
pitch = 0;
|
||||||
|
yaw = 0;
|
||||||
|
roll = 0;
|
||||||
|
|
||||||
|
// vertical, minecraft's default 70 degrees. fov is that, widened by the entity it's on
|
||||||
|
base_fov = 70 * Math.PI / 180;
|
||||||
|
fov = this.base_fov;
|
||||||
|
near = 0.1;
|
||||||
|
far = 1000;
|
||||||
|
|
||||||
|
setup(entity: Entity, partial_tick: number) {
|
||||||
|
const { x, y, z } = entity.render_position(partial_tick);
|
||||||
|
this.x = x;
|
||||||
|
this.y = y + entity.render_eye_height(partial_tick);
|
||||||
|
this.z = z;
|
||||||
|
this.yaw = entity.yaw;
|
||||||
|
this.pitch = entity.pitch;
|
||||||
|
this.fov = this.base_fov * entity.render_fov_scale(partial_tick);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { FromChunkWorker, ToChunkWorker } from "./workers/chunk_messages.ts";
|
||||||
|
|
||||||
|
// leave a core for the main thread, more than 4 doesnt help much
|
||||||
|
const POOL_SIZE = Math.max(1, Math.min(4, (navigator.hardwareConcurrency ?? 4) - 1));
|
||||||
|
|
||||||
|
export class ChunkWorkerPool {
|
||||||
|
readonly size = POOL_SIZE;
|
||||||
|
#workers: Worker[] = [];
|
||||||
|
#next = 0;
|
||||||
|
|
||||||
|
constructor(on_message: (message: FromChunkWorker) => void) {
|
||||||
|
for (let i = 0; i < this.size; i += 1) {
|
||||||
|
const worker = new Worker(new URL("./workers/chunk_worker.js", import.meta.url), { type: "module" });
|
||||||
|
worker.onmessage = (event: MessageEvent<FromChunkWorker>) => on_message(event.data);
|
||||||
|
worker.onerror = (event) => console.error("Chunk worker error:", event.message);
|
||||||
|
this.#workers.push(worker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcast(message: ToChunkWorker) {
|
||||||
|
for (const worker of this.#workers) {
|
||||||
|
worker.postMessage(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// round robin, results can come back out of order
|
||||||
|
post(message: ToChunkWorker, transfer: Transferable[] = []) {
|
||||||
|
const worker = this.#workers[this.#next];
|
||||||
|
this.#next = (this.#next + 1) % this.#workers.length;
|
||||||
|
worker.postMessage(message, transfer);
|
||||||
|
}
|
||||||
|
|
||||||
|
terminate() {
|
||||||
|
for (const worker of this.#workers) {
|
||||||
|
worker.terminate();
|
||||||
|
}
|
||||||
|
this.#workers = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { ClientLevel } from "./level/client_level.ts";
|
||||||
|
import type { BlockHitResult } from "./level/client_level.ts";
|
||||||
|
import { LocalPlayer } from "./entity/local_player.ts";
|
||||||
|
import { RemotePlayer } from "./entity/remote_player.ts";
|
||||||
|
import { ItemEntity } from "./entity/item_entity.ts";
|
||||||
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
|
import type { Entity } from "./entity/entity.ts";
|
||||||
|
import { Camera } from "./camera.ts";
|
||||||
|
import { Options } from "./options.ts";
|
||||||
|
import { MultiPlayerGameMode } from "./game_mode.ts";
|
||||||
|
import { ClientPacketListener } from "./packet_listener.ts";
|
||||||
|
import { profiler } from "./profiler.ts";
|
||||||
|
import { GameRenderer } from "./rendering/game_renderer.ts";
|
||||||
|
import { ChatComponent } from "./gui/chat_component.ts";
|
||||||
|
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
|
||||||
|
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
|
||||||
|
import { GuiChat } from "./gui/gui_chat.ts";
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
import { Connection } from "./network.ts";
|
||||||
|
import { PauseScreen } from "./gui/pause_screen.ts";
|
||||||
|
import { back_to_title } from "./gui/title_screen.ts";
|
||||||
|
import { TICK_DELTA } from "@/common/constants.ts";
|
||||||
|
import { Container } from "@/common/inventory.ts";
|
||||||
|
import { PLAYER_MENU } from "@/common/protocol.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
|
import { tick_texture_animations } from "./texture_animations.ts";
|
||||||
|
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
|
||||||
|
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
|
||||||
|
const USE_REPEAT_MS = 200;
|
||||||
|
|
||||||
|
// after a long stall (a hidden tab, a debugger) the game skips ahead instead of running every missed tick at once
|
||||||
|
const MAX_TICKS_PER_FRAME = 10;
|
||||||
|
|
||||||
|
// the game client, like minecraft's Minecraft class: owns the level, the player, the screens and the renderer.
|
||||||
|
// the game runs in fixed ticks (TICKS_PER_SECOND), input and drawing happen every frame
|
||||||
|
export class Client {
|
||||||
|
connection: Connection;
|
||||||
|
options = new Options();
|
||||||
|
level: ClientLevel;
|
||||||
|
player: LocalPlayer;
|
||||||
|
camera = new Camera();
|
||||||
|
game_mode: MultiPlayerGameMode;
|
||||||
|
packet_listener: ClientPacketListener;
|
||||||
|
game_renderer = new GameRenderer();
|
||||||
|
chat = new ChatComponent();
|
||||||
|
|
||||||
|
// open screens, the last one is on top and gets the input
|
||||||
|
screens: GuiScreen[] = [];
|
||||||
|
// what the player is looking at, updated every frame
|
||||||
|
hit_result: BlockHitResult | undefined;
|
||||||
|
// the entity or other player being looked at, closer than any block. hit_result is undefined then
|
||||||
|
entity_hit: Entity | undefined;
|
||||||
|
debugging = false;
|
||||||
|
// started from the f3 performance window
|
||||||
|
benchmark: RenderBenchmark | undefined;
|
||||||
|
|
||||||
|
// seconds of game time not ticked yet
|
||||||
|
#pending_time = 0;
|
||||||
|
// whether the attack button is held on a block, breaking it advances every tick
|
||||||
|
#attacking = false;
|
||||||
|
// when holding the use button on a block uses it again, see USE_REPEAT_MS
|
||||||
|
#next_use = 0;
|
||||||
|
// a use was sent and the use button hasn't been let go of since, see #handle_block_interaction
|
||||||
|
#use_held = false;
|
||||||
|
#stopped = false;
|
||||||
|
// the render distance the server was last told, it sends chunks for it
|
||||||
|
#sent_view_distance: number;
|
||||||
|
// called once when the connection drops, with why
|
||||||
|
#on_disconnect: (message: string) => void;
|
||||||
|
|
||||||
|
constructor(connection: Connection, on_disconnect: (message: string) => void) {
|
||||||
|
this.connection = connection;
|
||||||
|
this.#on_disconnect = on_disconnect;
|
||||||
|
|
||||||
|
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
|
||||||
|
this.level.time = connection.time;
|
||||||
|
this.#sent_view_distance = this.options.render_distance;
|
||||||
|
|
||||||
|
const spawn = connection.spawn;
|
||||||
|
this.player = new LocalPlayer(this, connection.id, connection.name);
|
||||||
|
this.player.set_position(spawn.x, spawn.y, spawn.z);
|
||||||
|
this.player.yaw = spawn.yaw;
|
||||||
|
this.player.pitch = spawn.pitch;
|
||||||
|
this.player.inventories.hotbar_selected = connection.selected_slot;
|
||||||
|
this.player.inventories.extra_slots = connection.player_menu;
|
||||||
|
this.player.inventories.extra = new Container(connection.player_menu.length);
|
||||||
|
this.level.add_entity(this.player);
|
||||||
|
for (const info of connection.initial_players) {
|
||||||
|
this.level.add_entity(new RemotePlayer(this.level, info));
|
||||||
|
}
|
||||||
|
for (const info of connection.initial_entities) {
|
||||||
|
this.level.add_entity(
|
||||||
|
info.kind === "item" ? new ItemEntity(this.level, info) : new RemoteEntity(this.level, info),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.game_mode = new MultiPlayerGameMode(this);
|
||||||
|
this.packet_listener = new ClientPacketListener(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
get screen(): GuiScreen | undefined {
|
||||||
|
return this.screens.at(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
push_screen(screen: GuiScreen) {
|
||||||
|
this.screens.push(screen);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player closed the one on top
|
||||||
|
pop_screen() {
|
||||||
|
const screen = this.screens.pop();
|
||||||
|
screen?.on_close();
|
||||||
|
screen?.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player closed this one, wherever it is
|
||||||
|
close_screen(screen: GuiScreen) {
|
||||||
|
if (!this.screens.includes(screen)) return;
|
||||||
|
this.screens = this.screens.filter((s) => s !== screen);
|
||||||
|
screen.on_close();
|
||||||
|
screen.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// takes these off without closing them, like when the server opens a menu or closes it
|
||||||
|
remove_screens(which: (screen: GuiScreen) => boolean) {
|
||||||
|
const removed = this.screens.filter(which);
|
||||||
|
this.screens = this.screens.filter((s) => !which(s));
|
||||||
|
for (const screen of removed) screen.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// leaving on purpose, from the pause screen
|
||||||
|
disconnect() {
|
||||||
|
this.#stopped = true;
|
||||||
|
sounds.stop_all();
|
||||||
|
this.connection.close();
|
||||||
|
back_to_title();
|
||||||
|
}
|
||||||
|
|
||||||
|
#stop() {
|
||||||
|
this.#stopped = true;
|
||||||
|
sounds.stop_all();
|
||||||
|
this.level.dispose();
|
||||||
|
InputManager.set_mouse_grabbed(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// one frame: input, as many ticks as are due, then drawing between the last tick and the next. while the benchmark
|
||||||
|
// runs, it ticks and draws its own level instead and the world waits, so what's around the player doesn't change
|
||||||
|
// its numbers
|
||||||
|
run_frame(delta: number) {
|
||||||
|
if (this.#stopped) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.benchmark) {
|
||||||
|
this.benchmark.frame();
|
||||||
|
} else {
|
||||||
|
const screen = this.screen;
|
||||||
|
this.screen?.on_tick(delta);
|
||||||
|
// a screen that closed itself just now, like chat on enter, had this frame's keys
|
||||||
|
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.#pending_time += delta;
|
||||||
|
let ticks = 0;
|
||||||
|
const stopped = profiler.section("ticks", () => {
|
||||||
|
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
|
||||||
|
if (this.benchmark) this.benchmark.tick();
|
||||||
|
else this.tick();
|
||||||
|
if (this.#stopped) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
this.#pending_time -= TICK_DELTA;
|
||||||
|
ticks += 1;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
if (stopped) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ticks === MAX_TICKS_PER_FRAME) {
|
||||||
|
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
|
||||||
|
}
|
||||||
|
|
||||||
|
const partial_tick = this.#pending_time / TICK_DELTA;
|
||||||
|
if (this.benchmark) {
|
||||||
|
this.benchmark.render(partial_tick);
|
||||||
|
} else {
|
||||||
|
this.game_renderer.render(this, partial_tick);
|
||||||
|
// from where the camera was just put
|
||||||
|
sounds.frame(
|
||||||
|
this.camera,
|
||||||
|
(id) => this.level.entities.get(id)?.render_position(partial_tick),
|
||||||
|
this.options.volume,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// one step of the game: what the server sent (chunks included), breaking, then every entity
|
||||||
|
tick() {
|
||||||
|
this.packet_listener.handle_packets();
|
||||||
|
if (this.connection.closed) {
|
||||||
|
this.#stop();
|
||||||
|
this.#on_disconnect("Lost connection to the server");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.#attacking && this.hit_result) {
|
||||||
|
this.game_mode.continue_destroy_block(this.hit_result);
|
||||||
|
}
|
||||||
|
|
||||||
|
const view_distance = Math.round(this.options.render_distance);
|
||||||
|
if (view_distance !== this.#sent_view_distance) {
|
||||||
|
this.#sent_view_distance = view_distance;
|
||||||
|
this.level.view_distance = view_distance;
|
||||||
|
this.connection.send({ type: "view_distance", distance: view_distance });
|
||||||
|
}
|
||||||
|
this.level.tick();
|
||||||
|
tick_texture_animations();
|
||||||
|
}
|
||||||
|
|
||||||
|
// closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a
|
||||||
|
// hotbar slot. typing "/give pickaxe" and enter in the same slow frame would otherwise open the inventory
|
||||||
|
#handle_keybinds(closed_screen: boolean) {
|
||||||
|
const player = this.player;
|
||||||
|
|
||||||
|
// typing into a screen's text field, keys are letters, not keybinds
|
||||||
|
if (!closed_screen && !this.screen?.typing) {
|
||||||
|
this.#handle_keys();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (InputManager.is_mouse_grabbed()) {
|
||||||
|
const mouse = InputManager.get_look_delta();
|
||||||
|
player.turn(mouse.x, mouse.y);
|
||||||
|
}
|
||||||
|
InputManager.set_mouse_grabbed(!this.screen);
|
||||||
|
|
||||||
|
this.#pick();
|
||||||
|
this.#handle_block_interaction();
|
||||||
|
|
||||||
|
if (!this.screen && !closed_screen) {
|
||||||
|
this.#handle_hotbar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#handle_keys() {
|
||||||
|
const options = this.options;
|
||||||
|
const player = this.player;
|
||||||
|
|
||||||
|
if (InputManager.is_key_pressed(options.key_inventory)) {
|
||||||
|
if (!this.screen) {
|
||||||
|
this.push_screen(new GuiPlayerInventory(player, (m) => this.connection.send(m)));
|
||||||
|
} else if (this.screen instanceof GuiMenuScreen) {
|
||||||
|
this.pop_screen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (InputManager.is_key_pressed(options.key_drop)) {
|
||||||
|
this.#handle_drop();
|
||||||
|
}
|
||||||
|
if (InputManager.is_key_pressed(options.key_chat) && !this.screen) {
|
||||||
|
this.push_screen(new GuiChat(this));
|
||||||
|
}
|
||||||
|
// straight into a command, like minecraft
|
||||||
|
if (InputManager.is_key_pressed("Slash") && !this.screen) {
|
||||||
|
this.push_screen(new GuiChat(this, "/"));
|
||||||
|
}
|
||||||
|
// browsers eat the escape that lets go of the mouse, so losing the mouse pauses too
|
||||||
|
const lost_mouse = InputManager.take_lost_pointer_lock();
|
||||||
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
|
if (this.screen) {
|
||||||
|
if (this.screen.close_on_escape()) this.pop_screen();
|
||||||
|
} else {
|
||||||
|
this.push_screen(new PauseScreen(this));
|
||||||
|
}
|
||||||
|
} else if (lost_mouse && !this.screen) {
|
||||||
|
this.push_screen(new PauseScreen(this));
|
||||||
|
}
|
||||||
|
if (InputManager.is_key_pressed(options.key_debug)) {
|
||||||
|
this.debugging = !this.debugging;
|
||||||
|
}
|
||||||
|
if (InputManager.is_key_pressed(options.key_fullscreen)) {
|
||||||
|
InputManager.toggle_fullscreen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the held item while playing, the slot under the mouse in an inventory (only with nothing on the cursor)
|
||||||
|
#handle_drop() {
|
||||||
|
const all = InputManager.is_key_down("ControlLeft") || InputManager.is_key_down("ControlRight");
|
||||||
|
const inventories = this.player.inventories;
|
||||||
|
const screen = this.screen;
|
||||||
|
if (!screen) {
|
||||||
|
// the hotbar slot of menu 0, they're the same numbers
|
||||||
|
const slot = inventories.hotbar_selected;
|
||||||
|
this.game_mode.drop_item(inventories.inventory, slot, PLAYER_MENU, slot, all);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const slot = screen instanceof GuiMenuScreen ? screen.hovering : undefined;
|
||||||
|
if (screen instanceof GuiMenuScreen && slot && !slot.output && !inventories.cursor.item) {
|
||||||
|
const index = screen.menu.slots.indexOf(slot);
|
||||||
|
this.game_mode.drop_item(slot.container, slot.index, screen.menu.id, index, all);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// what's under the crosshair: an entity, or the first block in front of it
|
||||||
|
#pick() {
|
||||||
|
const player = this.player;
|
||||||
|
const eye_y = player.y + player.eye_height;
|
||||||
|
const picked = this.level.pick_entity(
|
||||||
|
player.x,
|
||||||
|
eye_y,
|
||||||
|
player.z,
|
||||||
|
player.yaw,
|
||||||
|
player.pitch,
|
||||||
|
player.entity_interaction_range,
|
||||||
|
(entity) =>
|
||||||
|
entity instanceof RemotePlayer ||
|
||||||
|
(entity instanceof RemoteEntity && !entity.dead && is_pickable(entity)),
|
||||||
|
);
|
||||||
|
// a block in front of the entity hides it
|
||||||
|
this.hit_result = this.level.pick(
|
||||||
|
player.x,
|
||||||
|
eye_y,
|
||||||
|
player.z,
|
||||||
|
player.yaw,
|
||||||
|
player.pitch,
|
||||||
|
picked?.distance ?? player.block_interaction_range,
|
||||||
|
this.game_mode.held_item()?.targets_fluids,
|
||||||
|
);
|
||||||
|
this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// clicks happen right away, holding to break advances in tick()
|
||||||
|
#handle_block_interaction() {
|
||||||
|
const hit = this.hit_result;
|
||||||
|
const attacking = !this.screen && InputManager.is_mouse_down(0);
|
||||||
|
this.#attacking = attacking;
|
||||||
|
|
||||||
|
if (!attacking || !hit) {
|
||||||
|
this.game_mode.stop_destroy_block();
|
||||||
|
}
|
||||||
|
// letting go stops using an item over time, like shooting a bow, even with a screen open by then. the server
|
||||||
|
// may not have said it's using one yet, so it's sent after every use
|
||||||
|
if (this.#use_held && !InputManager.is_mouse_down(2)) {
|
||||||
|
this.#use_held = false;
|
||||||
|
this.connection.send({ type: "release_use" });
|
||||||
|
}
|
||||||
|
if (this.screen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// middle click in creative gives the block under the crosshair, like minecraft's pick block
|
||||||
|
if (hit && this.player.creative && InputManager.is_mouse_pressed(1)) {
|
||||||
|
const block = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block);
|
||||||
|
if (block) this.connection.send({ type: "chat", text: `/give ${block.id}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS. not while it's using an item
|
||||||
|
const now = performance.now();
|
||||||
|
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
|
||||||
|
const using = use_pressed ||
|
||||||
|
(hit && InputManager.is_mouse_down(2) && now >= this.#next_use && !this.player.using_item);
|
||||||
|
if (using) {
|
||||||
|
this.#next_use = now + USE_REPEAT_MS;
|
||||||
|
this.#use_held = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the held item swings on every click and use, and keeps swinging while breaking, like minecraft
|
||||||
|
if (InputManager.is_mouse_pressed(0) || using || (attacking && hit)) {
|
||||||
|
this.game_renderer.hand.swing();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
||||||
|
this.game_mode.attack(this.entity_hit);
|
||||||
|
}
|
||||||
|
if (hit) {
|
||||||
|
if (InputManager.is_mouse_pressed(0)) {
|
||||||
|
this.game_mode.start_destroy_block(hit);
|
||||||
|
}
|
||||||
|
if (!attacking && using) {
|
||||||
|
this.game_mode.use_item_on(hit);
|
||||||
|
}
|
||||||
|
} else if (use_pressed && this.entity_hit) {
|
||||||
|
this.game_mode.interact(this.entity_hit);
|
||||||
|
} else if (use_pressed) {
|
||||||
|
this.game_mode.use_item();
|
||||||
|
} else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
||||||
|
this.game_mode.swing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#handle_hotbar() {
|
||||||
|
const inventories = this.player.inventories;
|
||||||
|
const previous = inventories.hotbar_selected;
|
||||||
|
|
||||||
|
const scroll = InputManager.get_wheel_delta();
|
||||||
|
// at a block that takes the mouse wheel, like a pulse repeater's delay, it goes to the block instead
|
||||||
|
const hit = this.hit_result;
|
||||||
|
if (scroll !== 0 && hit && EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)?.scrollable) {
|
||||||
|
const { x, y, z, face } = hit;
|
||||||
|
this.connection.send({ type: "scroll_block", x, y, z, face, hit: hit.hit, amount: scroll < 0 ? 1 : -1 });
|
||||||
|
} else if (scroll > 0) {
|
||||||
|
inventories.hotbar_selected = Math.min(8, inventories.hotbar_selected + 1);
|
||||||
|
} else if (scroll < 0) {
|
||||||
|
inventories.hotbar_selected = Math.max(0, inventories.hotbar_selected - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pressed = this.options.key_hotbar.findIndex((key) => InputManager.is_key_pressed(key));
|
||||||
|
if (pressed !== -1) {
|
||||||
|
inventories.hotbar_selected = pressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inventories.hotbar_selected !== previous) {
|
||||||
|
this.connection.send({ type: "select_slot", slot: inventories.hotbar_selected });
|
||||||
|
// the server starts the attack cooldown over too
|
||||||
|
this.player.last_attack = performance.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the crosshair can be on: mobs and objects, not scripted entities like the fishing hook. kinds the client doesn't
|
||||||
|
// know are left to the server
|
||||||
|
function is_pickable(entity: RemoteEntity) {
|
||||||
|
return EverythingRegistry.get<EntityJson>("entities", entity.type)?.behavior !== "scripted";
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { AssetManager } from "./assets.ts";
|
||||||
|
import { Client } from "./client.ts";
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
import { Connection } from "./network.ts";
|
||||||
|
import { Options } from "./options.ts";
|
||||||
|
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress, type Welcome } from "./handshake.ts";
|
||||||
|
import { build_atlas, engine_textures } from "./atlas.ts";
|
||||||
|
import { set_texture_animations } from "./texture_animations.ts";
|
||||||
|
import type { TextureJson } from "@/common/texture_animation.ts";
|
||||||
|
import { ModLoadError } from "@/common/mod_loader.ts";
|
||||||
|
import { begin_drawing, clear_background, device, end_drawing, init_font, load_texture } from "./renderer/mod.ts";
|
||||||
|
import { is_stopped } from "./fatal.ts";
|
||||||
|
import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
|
||||||
|
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||||
|
import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts";
|
||||||
|
import { MainMenuScreen } from "./gui/main_menu.ts";
|
||||||
|
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
|
||||||
|
import { ConfirmModsScreen } from "./gui/confirm_mods_screen.ts";
|
||||||
|
import { profiler } from "./profiler.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
|
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
||||||
|
class ClientLoop {
|
||||||
|
running = false;
|
||||||
|
last_time = 0;
|
||||||
|
client: Client | undefined;
|
||||||
|
screen: GuiScreen | undefined;
|
||||||
|
// over the screen, it gets the input while it's there
|
||||||
|
overlay: GuiScreen | undefined;
|
||||||
|
|
||||||
|
frame_count = 0;
|
||||||
|
last_fps_time = 0;
|
||||||
|
|
||||||
|
start() {
|
||||||
|
platform.on_shown(() => {
|
||||||
|
this.last_time = performance.now();
|
||||||
|
});
|
||||||
|
|
||||||
|
this.running = true;
|
||||||
|
const now = performance.now();
|
||||||
|
this.last_time = now;
|
||||||
|
this.frame_count = 0;
|
||||||
|
this.last_fps_time = this.last_time;
|
||||||
|
platform.request_frame((time) => this.loop(time));
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
show_screen(screen: GuiScreen) {
|
||||||
|
this.screen?.on_close();
|
||||||
|
this.client = undefined;
|
||||||
|
platform.confirm_leaving(false);
|
||||||
|
this.screen = screen;
|
||||||
|
InputManager.set_mouse_grabbed(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// shown over whatever screen is joining, see ConfirmModsScreen
|
||||||
|
confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.overlay = new ConfirmModsScreen(address, welcome, (join) => {
|
||||||
|
this.overlay = undefined;
|
||||||
|
resolve(join);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
play(connection: Connection) {
|
||||||
|
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
|
||||||
|
set_mods_client(client);
|
||||||
|
client.chat.add("Connected to the server");
|
||||||
|
this.screen?.on_close();
|
||||||
|
this.screen = undefined;
|
||||||
|
this.client = client;
|
||||||
|
platform.confirm_leaving(true);
|
||||||
|
console.log("Game started");
|
||||||
|
}
|
||||||
|
|
||||||
|
loop(time: number) {
|
||||||
|
if (!this.running || is_stopped()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const delta = (time - this.last_time) / 1000;
|
||||||
|
|
||||||
|
profiler.begin_frame();
|
||||||
|
profiler.section("begin frame", begin_drawing);
|
||||||
|
clear_background(0.69, 0.8, 1, 1.0);
|
||||||
|
if (this.client) {
|
||||||
|
this.client.run_frame(delta);
|
||||||
|
} else if (this.screen) {
|
||||||
|
(this.overlay ?? this.screen).on_tick(delta);
|
||||||
|
this.screen.on_render();
|
||||||
|
this.overlay?.on_render();
|
||||||
|
}
|
||||||
|
profiler.section("submit", end_drawing);
|
||||||
|
profiler.end_frame();
|
||||||
|
|
||||||
|
this.frame_count += 1;
|
||||||
|
const now = performance.now();
|
||||||
|
if (now - this.last_fps_time >= 1000) {
|
||||||
|
const fps = (this.frame_count * 1000) / (now - this.last_fps_time);
|
||||||
|
console.log(`FPS: ${fps.toFixed(2)}`);
|
||||||
|
this.frame_count = 0;
|
||||||
|
this.last_fps_time = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
InputManager.update();
|
||||||
|
|
||||||
|
this.last_time = time;
|
||||||
|
platform.request_frame((time) => this.loop(time));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point
|
||||||
|
// can't go back to the title screen to try again, the page has to start over
|
||||||
|
class FailedAfterLoadingMods extends Error {}
|
||||||
|
|
||||||
|
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
|
||||||
|
async function join_server(
|
||||||
|
address: ServerAddress,
|
||||||
|
name: string,
|
||||||
|
status: (text: string) => void,
|
||||||
|
confirm_mods: (address: ServerAddress, welcome: Welcome) => Promise<boolean>,
|
||||||
|
): Promise<Connection> {
|
||||||
|
const { socket, welcome } = await connect(address, name);
|
||||||
|
console.log(`Connected to ${address.ws_url}`);
|
||||||
|
|
||||||
|
let loaded_mods = false;
|
||||||
|
try {
|
||||||
|
if (address.cross_origin && !is_trusted(address, welcome)) {
|
||||||
|
status("Waiting for you to accept the server's mods...");
|
||||||
|
if (!await confirm_mods(address, welcome)) {
|
||||||
|
throw new HandshakeError(`You didn't join ${address.base.host}`);
|
||||||
|
}
|
||||||
|
remember_trust(address, welcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
// textures, blocks and items all come from the server's mods, so this happens before anything else
|
||||||
|
status("Downloading the server's mods...");
|
||||||
|
const mods = await download_mods(welcome.mods, address.base);
|
||||||
|
const textures = await engine_textures();
|
||||||
|
const texture_json = new Map<string, TextureJson>();
|
||||||
|
for (const mod of mods) {
|
||||||
|
for (const [id, png] of mod.textures) textures.set(id, png);
|
||||||
|
for (const [id, json] of mod.texture_json ?? []) texture_json.set(id, json);
|
||||||
|
}
|
||||||
|
const atlas = build_atlas(textures, texture_json);
|
||||||
|
loaded_mods = true;
|
||||||
|
const atlas_texture = load_texture(atlas.image);
|
||||||
|
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
|
||||||
|
AssetManager.instance.assets["cubi:textures"] = atlas_texture;
|
||||||
|
AssetManager.instance.assets["cubi:textures_info"] = atlas.regions;
|
||||||
|
await load_client_mods(welcome.mods, mods);
|
||||||
|
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
|
||||||
|
|
||||||
|
status("Joining...");
|
||||||
|
const joined = await join(socket, new Options().render_distance);
|
||||||
|
return new Connection(socket, welcome, joined);
|
||||||
|
} catch (e) {
|
||||||
|
socket.close();
|
||||||
|
const message = error_message(e);
|
||||||
|
throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function error_message(e: unknown) {
|
||||||
|
if (e instanceof HandshakeError) {
|
||||||
|
return e.message;
|
||||||
|
}
|
||||||
|
if (e instanceof ModLoadError) {
|
||||||
|
return `Couldn't load the server's mods: ${e.message}`;
|
||||||
|
}
|
||||||
|
return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the title screen (the main menu in the desktop app), and the game once it joins a server. the platform is set, the
|
||||||
|
// window was set up with init_window, and input comes in
|
||||||
|
export async function start_client() {
|
||||||
|
AssetManager.instance.load("cubi:assets_text", "/assets/ASSETS.md");
|
||||||
|
|
||||||
|
AssetManager.instance.load("cubi:skin", "/assets/sprites/skin_template.png");
|
||||||
|
AssetManager.instance.load("cubi:gui", "/assets/sprites/gui.png");
|
||||||
|
|
||||||
|
AssetManager.instance.load("cubi:m6x11", "/assets/fonts/m6x11.png");
|
||||||
|
AssetManager.instance.load("cubi:m6x11_fnt", "/assets/fonts/m6x11.fnt");
|
||||||
|
|
||||||
|
await AssetManager.instance.load_all();
|
||||||
|
|
||||||
|
init_font();
|
||||||
|
|
||||||
|
const loop = new ClientLoop();
|
||||||
|
const join_game: JoinServer = async (address, name, status) => {
|
||||||
|
let connection: Connection;
|
||||||
|
try {
|
||||||
|
connection = await join_server(
|
||||||
|
address,
|
||||||
|
name,
|
||||||
|
status,
|
||||||
|
(address, welcome) => loop.confirm_mods(address, welcome),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof FailedAfterLoadingMods) {
|
||||||
|
loop.show_screen(new DisconnectedScreen(e.message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
loop.play(connection);
|
||||||
|
};
|
||||||
|
loop.show_screen(
|
||||||
|
in_desktop_app()
|
||||||
|
? new MainMenuScreen((screen) => loop.show_screen(screen), join_game)
|
||||||
|
: new TitleScreen(join_game),
|
||||||
|
);
|
||||||
|
loop.start();
|
||||||
|
}
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import { World } from "$/common/ecs/mod.ts";
|
|
||||||
import { MovementSystem } from "$/common/systems/movement_system.ts";
|
|
||||||
import { RenderSystem } from "$/client/systems/render_system.ts";
|
|
||||||
import { PlayerControlsSystem } from "$/client/systems/player_controls.ts";
|
|
||||||
import { DebugSystem } from "$/client/systems/debug_system.ts";
|
|
||||||
import { UIInteractionSystem } from "$/client/systems/ui_interaction_system.ts";
|
|
||||||
import { UIRenderSystem } from "$/client/systems/ui_render_system.ts";
|
|
||||||
import { create_main_menu } from "./main_menu.ts";
|
|
||||||
import { start_game } from "./game.ts";
|
|
||||||
import { canvas, resize_canvas } from "./renderer/mod.ts";
|
|
||||||
import { DimensionLogicSystem } from "./systems/dimension_logic.ts";
|
|
||||||
import { Dimension } from "./components/dimension.ts";
|
|
||||||
import { GuiRenderSystem, GuiTickSystem } from "./gui/gui_systems.ts";
|
|
||||||
import { WorldGenerationSystem } from "./systems/world_generation_system.ts";
|
|
||||||
import { CollisionSystem } from "./systems/collision_system.ts";
|
|
||||||
|
|
||||||
export class ClientWorld extends World {
|
|
||||||
paused = false;
|
|
||||||
debugging = false;
|
|
||||||
|
|
||||||
dimension!: Dimension;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super("game");
|
|
||||||
|
|
||||||
this.add_state("main_menu");
|
|
||||||
this.add_state("paused");
|
|
||||||
this.add_state("game");
|
|
||||||
|
|
||||||
self.addEventListener("resize", resize_canvas);
|
|
||||||
resize_canvas();
|
|
||||||
|
|
||||||
canvas.addEventListener("contextmenu", function (event) {
|
|
||||||
event.preventDefault();
|
|
||||||
});
|
|
||||||
|
|
||||||
start_game(this);
|
|
||||||
|
|
||||||
// Logic systems
|
|
||||||
this.add_system(new UIInteractionSystem(), "main_menu");
|
|
||||||
this.add_system(new UIInteractionSystem(), "paused");
|
|
||||||
this.add_system(new GuiTickSystem(), "game");
|
|
||||||
this.add_system(new PlayerControlsSystem(), "game");
|
|
||||||
this.add_system(new WorldGenerationSystem(), "game");
|
|
||||||
this.add_system(new DimensionLogicSystem(), "game");
|
|
||||||
this.add_system(new CollisionSystem(), "game");
|
|
||||||
this.add_system(new MovementSystem(), "game");
|
|
||||||
|
|
||||||
// render systems
|
|
||||||
this.add_system(new RenderSystem(), "game");
|
|
||||||
this.add_system(new GuiRenderSystem(), "game");
|
|
||||||
this.add_system(new DebugSystem(), "game");
|
|
||||||
this.add_system(new UIRenderSystem(), "main_menu");
|
|
||||||
this.add_system(new UIRenderSystem(), "paused");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { Component } from "$/common/ecs/mod.ts";
|
|
||||||
|
|
||||||
export class Camera extends Component {
|
|
||||||
x = 0;
|
|
||||||
y = 0;
|
|
||||||
z = 3;
|
|
||||||
|
|
||||||
pitch = 0;
|
|
||||||
yaw = 0;
|
|
||||||
roll = 0;
|
|
||||||
|
|
||||||
fov = Math.PI / 3;
|
|
||||||
near = 0.1;
|
|
||||||
far = 1000;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { Component } from "$/common/ecs/mod.ts";
|
|
||||||
|
|
||||||
export class ClickableSprite extends Component {
|
|
||||||
clicked = false;
|
|
||||||
button: number;
|
|
||||||
access_range: number;
|
|
||||||
|
|
||||||
constructor(button: number = 0, access_range = 2) {
|
|
||||||
super();
|
|
||||||
this.button = button;
|
|
||||||
this.access_range = access_range;
|
|
||||||
}
|
|
||||||
}
|
|
||||||