Compare commits
592 Commits
e31dfbc5cd
...
d9b6b3e7fc
| Author | SHA1 | Date | |
|---|---|---|---|
| d9b6b3e7fc | |||
| abda1bd1dd | |||
| 811b51bd6a | |||
| 8506b235db | |||
| cd11a779c5 | |||
| ace59ce8a0 | |||
| b3ff49d38c | |||
| 88047649f9 | |||
| b63071e815 | |||
| 747669aef5 | |||
| 920b9555a1 | |||
| 7dbb287dd6 | |||
| 203afa9079 | |||
| fb0ae99bf5 | |||
| c4e8410b20 | |||
| 0f0bfc853d | |||
| eabc9ab294 | |||
| a89a9ba58d | |||
| 478baed1b6 | |||
| 7aaebe9ee8 | |||
| 99482236d1 | |||
| d823fa5a39 | |||
| 324c10bdc0 | |||
| 0bd2a8ad22 | |||
| 4e7549bb5a | |||
| bf5c87f86d | |||
| 9355531c0c | |||
| 26e86baf98 | |||
| 5e1b865f56 | |||
| 0dafb0974b | |||
| c9c46ed7d7 | |||
| 8da57eddab | |||
| fc2e0818f4 | |||
| 8e335a5c42 | |||
| a4b9bf0dbb | |||
| f5408ee8a9 | |||
| 89caa179f2 | |||
| 6b1bb90062 | |||
| 4d682eed17 | |||
| c3b156040d | |||
| 190c696319 | |||
| ec1f04e5cc | |||
| bdae77bf80 | |||
| 04544a0e7c | |||
| 156ded4774 | |||
| 3b2e3326e8 | |||
| 119ca52b75 | |||
| 67738884ec | |||
| 1dddeaf0b8 | |||
| db8ef092a4 | |||
| d448063dd7 | |||
| 0b148b404b | |||
| 279084c7be | |||
| 43e9e7baa0 | |||
| 9026a34c72 | |||
| b9bed17a2f | |||
| 499fbcfec8 | |||
| c81c40f8ea | |||
| 04d7cbde08 | |||
| 9d3317066b | |||
| 3afa71396b | |||
| 0187d832b7 | |||
| af4c10130d | |||
| c1c79b5dc6 | |||
| 2113dffac0 | |||
| d36b40c333 | |||
| 1576282819 | |||
| 9b8aa3a00b | |||
| bf3e405a4f | |||
| bafee9809d | |||
| 7470b4472a | |||
| 337a2c08b8 | |||
| e7f32a36f6 | |||
| b563223c4c | |||
| 90f1c4c09d | |||
| 0a58329c88 | |||
| 4f35f2c06c | |||
| 414b1951c6 | |||
| 075a5de9b9 | |||
| 46cac5435f | |||
| 5cf600e601 | |||
| 650d3271c1 | |||
| 96754dfcf6 | |||
| 072bbdfcb6 | |||
| 9a48f514c2 | |||
| 74654c9c98 | |||
| e571b758f1 | |||
| aa812c4829 | |||
| ef628d90be | |||
| 007447d60b | |||
| c9fd7bcd62 | |||
| e2ec75aadc | |||
| 2422374fc4 | |||
| d6f2d6b68a | |||
| 07fbdd05ed | |||
| d968bd2ed2 | |||
| 6c8d7b506e | |||
| 27a948e4ab | |||
| 75d8723565 | |||
| 5dbd68e0ce | |||
| 6f329ed1c1 | |||
| 1960cf97ab | |||
| c892aa0f6c | |||
| d666295bc9 | |||
| 50977af4e0 | |||
| e01eb777b7 | |||
| 61d3bef338 | |||
| 9d0a3a6481 | |||
| 910f9c2ad3 | |||
| 08b91ae553 | |||
| d4f2e1a171 | |||
| 58c5428c2b | |||
| f3c715033e | |||
| 8d459c9791 | |||
| c6ef980604 | |||
| 8250d53078 | |||
| 2cfa8eedc3 | |||
| 491b96223c | |||
| 5f01ff050a | |||
| df091c201f | |||
| 51b4ac6cdf | |||
| 72301ef4bd | |||
| 977395bcc6 | |||
| 569d631ffd | |||
| 2dd1c30001 | |||
| 0436eff527 | |||
| 401413019a | |||
| d2eab58881 | |||
| ac736c0174 | |||
| 4d065cd666 | |||
| 21bcd3c5d1 | |||
| ed76bda2e3 | |||
| c83ccbb8c1 | |||
| 88aebbe639 | |||
| 8432562252 | |||
| bf501a6e38 | |||
| fa705f18bb | |||
| 5d06b73b12 | |||
| 9ac5cd5e46 | |||
| a74f0a1b2a | |||
| 062a771eab | |||
| f200d1043a | |||
| 8a1d41567e | |||
| cd3ea64e25 | |||
| 7131581703 | |||
| e205cea50c | |||
| 75986da19d | |||
| 8c112c88af | |||
| af6c7e00b1 | |||
| 57bc7716c3 | |||
| 002215fd3c | |||
| e6944f6c32 | |||
| d3d47abb98 | |||
| 9b1f135399 | |||
| 40824c6078 | |||
| c802652aae | |||
| 465de798a0 | |||
| bd67055696 | |||
| 75c89d0d00 | |||
| ee6d941014 | |||
| 825ca26c30 | |||
| 1aa8e55487 | |||
| e4ad280ea5 | |||
| 5e64f4db1e | |||
| a773c9f6e5 | |||
| ab2a6e09d1 | |||
| 9d7bc88596 | |||
| b8d6e30f84 | |||
| 7081d54c82 | |||
| 7500406efd | |||
| 3b8b115b3a | |||
| 876496a0d7 | |||
| ec0f4247ba | |||
| 3bf7dca99c | |||
| f439d2a873 | |||
| 4a9dea81cf | |||
| 158a5b8944 | |||
| 3c3723531a | |||
| 4200b4ea04 | |||
| 58b7be9f6b | |||
| 659485870a | |||
| d016c47803 | |||
| ca8dd5361d | |||
| 2f40bdc184 | |||
| 664fe443c2 | |||
| e35a06131c | |||
| cf47635ba6 | |||
| eab3e4511a | |||
| e80b75e7e0 | |||
| fe1d81b3a4 | |||
| ac5febcb11 | |||
| 9a1a8884e7 | |||
| 8c6e08d4ac | |||
| 37a37ef0a6 | |||
| b25be0d036 | |||
| de8360183c | |||
| af3af9c857 | |||
| 422b570749 | |||
| dd0048ff84 | |||
| 27060a97e1 | |||
| 5b454b91ea | |||
| 6a6462a368 | |||
| 1e6ea11e23 | |||
| cd5655b521 | |||
| a6bb276678 | |||
| f1ab5f8282 | |||
| 2b3e5858f4 | |||
| 69336d210b | |||
| 0f65009304 | |||
| d2c0066643 | |||
| 23eaeebb90 | |||
| 581da40993 | |||
| a1fc1fa2b7 | |||
| 3845934be7 | |||
| 3f9e89569f | |||
| e6e40246ce | |||
| 754eb60a25 | |||
| 0b48c6e931 | |||
| a6cff8b3b1 | |||
| 3d66f7ec5c | |||
| 8e5240a950 | |||
| 4a66cccd79 | |||
| 9950444027 | |||
| c991f41158 | |||
| 53f666d301 | |||
| a40089d956 | |||
| 5ed5cb25d3 | |||
| ff05e9c9cb | |||
| 528d29a4e0 | |||
| 1eddabb5f9 | |||
| ee30f04616 | |||
| d5d6e1f4bd | |||
| 031ce48aaa | |||
| 8786e4c12b | |||
| 3211bd2f7a | |||
| ab86208e63 | |||
| c51a396a82 | |||
| dad94d6ec9 | |||
| bb422a98f1 | |||
| 9e47af9bc6 | |||
| 40cf4ec240 | |||
| e38cb1358f | |||
| d0eca56c35 | |||
| 3cfa510379 | |||
| 822f870f07 | |||
| cf0c92585f | |||
| 7338e4a1eb | |||
| d28c23aa48 | |||
| 32e217d4ee | |||
| ebde30ab22 | |||
| 713b42e9b2 | |||
| 3816ad4b33 | |||
| 10dde354f7 | |||
| 1ecf4bbe78 | |||
| f98c32a7af | |||
| 19fb68b1ce | |||
| a57247a7a0 | |||
| df616188f4 | |||
| 5b8842b199 | |||
| faaa6775f2 | |||
| 63b9f29ef5 | |||
| 65bf168d3a | |||
| 72ca505a61 | |||
| 7ed2cf92f9 | |||
| 9dca4d3c2f | |||
| 2c5ee65291 | |||
| 6e28024097 | |||
| 486f0f3f3c | |||
| 56bf1c4e32 | |||
| d4587ebfcd | |||
| f6cb305243 | |||
| 1b16aacf93 | |||
| 4238bce5f5 | |||
| 55290572e0 | |||
| 014b157a35 | |||
| 7a62d8ed7b | |||
| 5c5aaff8b1 | |||
| edea9a6976 | |||
| cf48cabb11 | |||
| 40a53801a7 | |||
| 802d3e026c | |||
| 47cdebf7f8 | |||
| e993ff6116 | |||
| ee83c31f74 | |||
| cbed3c1503 | |||
| 09159a1e3f | |||
| 5a29c4a2c9 | |||
| 73fdff0167 | |||
| e22c899d63 | |||
| a171f26988 | |||
| 12fe38c268 | |||
| 05caaf888f | |||
| 7ea659e195 | |||
| ebafda0833 | |||
| 691b0ca645 | |||
| 372a5551aa | |||
| de8ceafb7f | |||
| 27071fc3f3 | |||
| f8e23bcb4e | |||
| 36b474c2aa | |||
| 79dac5911c | |||
| 578f316db7 | |||
| c82d547dd8 | |||
| 0b4c144090 | |||
| cb2b511cfc | |||
| 6881b3ae2f | |||
| 6a7ff5ba4a | |||
| 289369674d | |||
| 5ae932fdcc | |||
| c7797cdf9b | |||
| d12f6103fa | |||
| f65e00b94f | |||
| 49a64b2d9b | |||
| 2789859360 | |||
| bfb3eebd2c | |||
| 052b0a3bcb | |||
| d5d7219c57 | |||
| 0d5855171a | |||
| 85acd40fbc | |||
| 5d87c62754 | |||
| be7ccc93e8 | |||
| 4c0b429964 | |||
| 66bb99b5ac | |||
| e32c00e0ef | |||
| 90012d9499 | |||
| f9f0a4cfd1 | |||
| f4624d4bc1 | |||
| 238e8390a2 | |||
| e73aed9063 | |||
| 0241e076ba | |||
| 5ec9099a02 | |||
| 3be887d0aa | |||
| 32b50fe95e | |||
| 0609882a16 | |||
| 4fe105aa1b | |||
| 196bb6cef8 | |||
| 720a53c2f4 | |||
| 99716fbe30 | |||
| 047204bada | |||
| b206149c68 | |||
| f88ad88ff2 | |||
| a587b08a82 | |||
| 0a66233db7 | |||
| 80840536c8 | |||
| d810f96d10 | |||
| d7294e2de1 | |||
| fecd08b9ad | |||
| 2e5c86e274 | |||
| 445d0acf6b | |||
| c4739493d9 | |||
| a155291778 | |||
| e65e6b730e | |||
| 08c880ccf2 | |||
| 0624f2ae96 | |||
| a9ca100c3d | |||
| a6a7abfbdd | |||
| e28ca1bcd0 | |||
| 1b7b0d87c5 | |||
| 83475a72f9 | |||
| be2ccd8208 | |||
| a50793b268 | |||
| d28d7f3a47 | |||
| d8cb047eb2 | |||
| 83f76ed164 | |||
| 5fd02cdece | |||
| aa94c950e1 | |||
| d1f0957a7b | |||
| 5061ddbcb3 | |||
| 728dc02d72 | |||
| 7720b458ff | |||
| 018a6ad1c5 | |||
| 282c282f9c | |||
| d2bb70434b | |||
| 8bbdd634da | |||
| 8b76e1688c | |||
| 662369e6e3 | |||
| f4714e8c25 | |||
| b2ed3d7383 | |||
| 32cef4334d | |||
| b6f34a3604 | |||
| 7d61cd322d | |||
| 3e370591d3 | |||
| 786225b4b7 | |||
| bbf28f9590 | |||
| a1669a1d69 | |||
| acf82132ba | |||
| 76b7cf538a | |||
| 3c54ba00c9 | |||
| 0cb68e3737 | |||
| 47efbbfd43 | |||
| 8a774a8e7f | |||
| b62edd7e88 | |||
| b9bda55693 | |||
| b289a8d72c | |||
| a74a7c02f0 | |||
| a9567d3dc8 | |||
| 0826cc78bb | |||
| b062b2beea | |||
| 340ea8c3d3 | |||
| a8ad839ee2 | |||
| 867a20ab15 | |||
| de430fdda1 | |||
| 0e4bd01e69 | |||
| 30ddb565db | |||
| 6587f59cda | |||
| 0e86dd3d07 | |||
| a46640bfb6 | |||
| e4146ea35e | |||
| 7c26caa2e8 | |||
| 748273ff38 | |||
| 25c39e0507 | |||
| 47362036bf | |||
| 14bb36f7a6 | |||
| c3d28b11ab | |||
| c7433820a4 | |||
| ab44a2b9c5 | |||
| ff23723797 | |||
| 6da77e8495 | |||
| b89f30a5b6 | |||
| 4e455d4076 | |||
| 230a45e857 | |||
| 2f8d22640d | |||
| a157eefd1f | |||
| 7a134d8685 | |||
| fd5b8b2dad | |||
| df6d5936c0 | |||
| 94c423878e | |||
| ab4eb22662 | |||
| ab88923c85 | |||
| 592a062b32 | |||
| 4d32769fda | |||
| aa9a532ae9 | |||
| ee1b9f80e1 | |||
| cdfb401832 | |||
| 4caa673a1d | |||
| cef207de4a | |||
| 0529975ef7 | |||
| 4d59e00ac9 | |||
| f9f4d6a4a1 | |||
| 580eb7f856 | |||
| 46553a050d | |||
| 565e6e54a3 | |||
| ef1c7fa0df | |||
| 3191b2cefd | |||
| 41feeb463e | |||
| 8bfdcd5f9c | |||
| 163609fb02 | |||
| c76c42d5c6 | |||
| 9a5b48a02f | |||
| d6eba50dac | |||
| e6405fb3de | |||
| 18f69a7d20 | |||
| dc9daf0ce2 | |||
| 620e73d380 | |||
| e8e9dc61a4 | |||
| e284344f69 | |||
| 635ab33d4e | |||
| 1e1f781c2c | |||
| dfb9018e41 | |||
| 40fb0a0973 | |||
| c456b63204 | |||
| d7369da1c3 | |||
| 40bd7540e9 | |||
| 6cdb99e80e | |||
| f130bd0af9 | |||
| ae0838838d | |||
| 30b7b152c3 | |||
| df4064ba12 | |||
| 87651ee670 | |||
| 2b282ad01a | |||
| 55482624f1 | |||
| da6d6d1c2c | |||
| c8fe4125ec | |||
| c074f3e597 | |||
| 2f5fd46044 | |||
| b4cd57c5fa | |||
| 3a12826d6b | |||
| f42ca08334 | |||
| b6e0f57251 | |||
| ce27bc718a | |||
| f3abebeb17 | |||
| 720a182305 | |||
| d7bad93e67 | |||
| ce341494ef | |||
| 0d225e3f64 | |||
| 0eac272aaa | |||
| 71dc2ac75f | |||
| edf3552c5f | |||
| 104808b876 | |||
| 66e1b78ca1 | |||
| e17a4c3373 | |||
| 85f6b4d74a | |||
| c5d45fe51d | |||
| 7167b328af | |||
| af659a4646 | |||
| 439789e139 | |||
| b66a642234 | |||
| 39868b72b7 | |||
| 706edfddcd | |||
| 54d7ec7329 | |||
| 9e4a17a4a8 | |||
| 4abb93203c | |||
| 46f8310514 | |||
| d80a3c5627 | |||
| 8e04c4e7c3 | |||
| 693f039171 | |||
| b32c34ef47 | |||
| 892e142caa | |||
| f68d2b7aa4 | |||
| cc709509ff | |||
| 0d965bce29 | |||
| ebb4371e18 | |||
| 14e401c9fa | |||
| d846b4bb6f | |||
| 7790b6a895 | |||
| 986c606c14 | |||
| aa8abd2baf | |||
| 0581d49ecc | |||
| db1210831c | |||
| 30294442e9 | |||
| d3199fae5c | |||
| 70cd0369e7 | |||
| 8e9ca3252b | |||
| 7ff300fdc6 | |||
| 32f2b26035 | |||
| b0b5ef1027 | |||
| d7debe7280 | |||
| 70725fa989 | |||
| f195d2b0b5 | |||
| 5332d16d0a | |||
| fa440f2e33 | |||
| e7605511a3 | |||
| 28e361b85e | |||
| e85e953fb9 | |||
| 53c19deffb | |||
| 0876154ebc | |||
| acc225aea9 | |||
| eb07782253 | |||
| 733295b36c | |||
| f35cf82574 | |||
| 1f572cc7fe | |||
| b9b3759207 | |||
| 4cf85cecf5 | |||
| ab07a599cd | |||
| fbc725ee25 | |||
| 8caec6c0b4 | |||
| 95703fc5ec | |||
| 1903b29d65 | |||
| b83b11e75f | |||
| 667849750c | |||
| c5f4f99598 | |||
| 98bbc49d41 | |||
| faf0cfcf03 | |||
| a1d410d6d3 | |||
| 67b435e3e2 | |||
| 8c46b8991a | |||
| 82664df74d | |||
| cf65b02e8d | |||
| 8cc5804278 | |||
| 8f8f6894af | |||
| db72c4783f | |||
| d2de8c4793 | |||
| 2382ff0d79 | |||
| ac678bd732 | |||
| 8e55495285 | |||
| 2e29aa7ae2 | |||
| efc5d5b0cf | |||
| 67d87fe7dc | |||
| f47cc2606c | |||
| 6a081863c7 | |||
| 213cf5828a | |||
| 203aa93137 | |||
| 03465d1d84 | |||
| 0b54fa14c9 | |||
| b23cb0dd32 | |||
| ce5e18641b | |||
| 711289cc9e | |||
| c02acc32af | |||
| c25aa3f32b | |||
| 26844c5900 | |||
| 69b7864f40 | |||
| 759c84e5af | |||
| 3e6e343943 | |||
| 38c9d8a8c5 | |||
| 7262824e0f | |||
| 0845ac436c | |||
| 30f4a24571 | |||
| 5dce46904d | |||
| 086405f55b | |||
| 865f6ae859 | |||
| 924b0c93fe | |||
| f6ed103be3 |
677
AGENTS.md
677
AGENTS.md
@@ -1,562 +1,247 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Project identity
|
||||
## Purpose
|
||||
|
||||
This repository contains a browser-based engine/editor for creating interactive 3D environments, with a built-in browser runner for immediate playtesting.
|
||||
This is the mandatory high-signal brief for agents working in this repo.
|
||||
|
||||
The product goal is:
|
||||
Read this file first.
|
||||
Then read `CHAT_CONTEXT.md`.
|
||||
After that, inspect the code and open only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md`.
|
||||
|
||||
- intuitive whiteboxing and scene assembly for interactive 3D spaces
|
||||
- modern browser delivery
|
||||
- glTF asset import, with optional later interchange export
|
||||
- fast edit -> run iteration
|
||||
- lightweight interactive runtime with spatial audio, navigation modes, and simple entity-driven logic
|
||||
Do not read the large docs end-to-end by default.
|
||||
|
||||
This is not a general-purpose DCC.
|
||||
This is not an unlimited AAA engine platform.
|
||||
This is a focused engine/editor for browser-delivered interactive 3D environments.
|
||||
When docs and code disagree:
|
||||
|
||||
1. trust the code for current behavior
|
||||
2. trust `AGENTS.md` + `CHAT_CONTEXT.md` for current intent
|
||||
3. use the larger docs as selective reference
|
||||
4. update stale docs if your slice materially changes behavior
|
||||
|
||||
---
|
||||
|
||||
## Product pillars
|
||||
## Product
|
||||
|
||||
1. **Interactive environments come first**
|
||||
- The tool exists to build playable interactive 3D spaces for the web.
|
||||
- The editor and runner are one product, not separate concerns.
|
||||
- One-click edit -> run must remain central.
|
||||
This repo is a browser-based engine/editor for interactive 3D environments with a built-in runner.
|
||||
|
||||
2. **Whiteboxing is sacred**
|
||||
- Layout authoring must remain faster and more direct than using a general DCC for the same task.
|
||||
- Whiteboxing is a first-class workflow, not a temporary preproduction mode.
|
||||
- The editor must feel immediate and precise, with snapping available as a helper rather than a hard restriction.
|
||||
Core loop:
|
||||
|
||||
3. **Imported assets are first-class**
|
||||
- glTF / GLB import must feel native.
|
||||
- Imported meshes, materials, textures, and animations must coexist cleanly with whitebox-authored worlds.
|
||||
- Imported assets complement whiteboxing; they do not replace it.
|
||||
1. author
|
||||
2. save/load
|
||||
3. run immediately in-browser
|
||||
|
||||
4. **The runner is built in**
|
||||
- Every meaningful authoring step should be testable in-browser.
|
||||
- Switching from edit mode to play mode should be nearly instant.
|
||||
- The runner is part of the product, not a demo app.
|
||||
Primary product priorities:
|
||||
|
||||
5. **Web-native sharing matters**
|
||||
- Scenes should be easy to load, embed, preview, and eventually share by URL.
|
||||
- The browser is a target platform, not a secondary export target.
|
||||
- intuitive whiteboxing / level blocking
|
||||
- imported assets as first-class content
|
||||
- typed entities and simple interactions
|
||||
- very fast edit -> run iteration
|
||||
- web-native delivery and sharing
|
||||
|
||||
This is not:
|
||||
|
||||
- a Blender replacement
|
||||
- a general CAD tool
|
||||
- an unlimited engine platform
|
||||
- a full physics sandbox unless the roadmap explicitly says so
|
||||
|
||||
---
|
||||
|
||||
## Architectural stance
|
||||
## Hard Rules
|
||||
|
||||
When making design decisions, prefer:
|
||||
### Canonical state
|
||||
|
||||
- plain three.js over unnecessary abstraction
|
||||
- explicit data models over implicit scene graph state
|
||||
- deterministic rebuilds over hidden mutations
|
||||
- command-based editing over ad hoc state changes
|
||||
- typed scene entities over free-form JSON blobs
|
||||
- vertical slices over speculative infrastructure
|
||||
- boring, maintainable code over cleverness
|
||||
- The canonical `SceneDocument` / project state is the source of truth.
|
||||
- Do not store three.js objects in canonical document state.
|
||||
- Do not make the three.js scene graph the source of truth.
|
||||
- Editor-authored mutations should go through commands.
|
||||
|
||||
The project uses:
|
||||
### Layering
|
||||
|
||||
- React for application shell and editor UI
|
||||
- three.js for viewport and runtime rendering
|
||||
- a canonical editor document model independent of three.js
|
||||
- command pattern for undo/redo
|
||||
- runtime entity systems for navigation, triggers, audio, and interaction
|
||||
- glTF / GLB as the main imported 3D asset format
|
||||
- JSON as the canonical authoring format
|
||||
|
||||
Do not collapse editor state into raw three.js objects.
|
||||
Do not make the three.js scene the source of truth.
|
||||
Do not make glTF the canonical editor save format.
|
||||
|
||||
---
|
||||
|
||||
## Early binding decisions
|
||||
|
||||
These defaults are intentionally fixed for the early slices unless a later slice explicitly changes them.
|
||||
|
||||
### Coordinate system
|
||||
|
||||
- world space is right-handed and **Y-up**
|
||||
- `+X` is right, `+Y` is up
|
||||
- scene units are meter-like and should be used consistently for movement, collision, and audio distances
|
||||
|
||||
### Early repo shape
|
||||
|
||||
- start as a single Vite app
|
||||
- keep domain folders under `src/`
|
||||
- do not introduce `/apps` + `/packages` or a monorepo split until the current code actually needs it
|
||||
|
||||
### State ownership
|
||||
|
||||
- do not use the React tree as the canonical state container
|
||||
- keep canonical editor state in a thin external editor store/service
|
||||
- React renders and dispatches commands; it does not own the document
|
||||
- `document` owns canonical state
|
||||
- `commands` own undoable mutations
|
||||
- `geometry` owns derived solid/mesh/collider generation
|
||||
- `viewport-three` owns editor rendering and interaction helpers
|
||||
- `runtime-three` owns play-mode runtime behavior
|
||||
- `entities` own typed non-model scene objects
|
||||
- `assets` own imported external resources and adapters
|
||||
- `serialization` owns save/load/versioning/migrations
|
||||
|
||||
### Persistence
|
||||
|
||||
- the canonical scene document is versioned from day one
|
||||
- M0-M2 may use local draft persistence plus explicit JSON import/export
|
||||
- once binary assets matter, user-facing save/load must become a portable project package containing canonical scene JSON plus referenced assets
|
||||
- canonical scene JSON remains the source document format, but by itself is no longer a portable project once external assets exist
|
||||
- runner/deployment output is a separate downstream package, not the editable project format
|
||||
- when binary assets arrive, they must survive reloads via embedded data or project-scoped packaged storage
|
||||
- never rely on ephemeral Blob URLs as the only persisted asset reference
|
||||
- The document is versioned from day one.
|
||||
- If persisted schema changes, update version/migration/validation and add at least one compatibility test.
|
||||
- Canonical save format is project JSON.
|
||||
- Once binary assets matter, user-facing save/load must be a portable project package containing canonical JSON plus referenced assets.
|
||||
- Runner/deployment output is separate from editable save/load.
|
||||
- Never rely on Blob URLs as the only persisted asset reference.
|
||||
|
||||
### Current box-solid defaults
|
||||
### Models, entities, world
|
||||
|
||||
- early slices began with axis-aligned box brushes
|
||||
- canonical box face IDs are fixed and stable:
|
||||
- `posX`
|
||||
- `negX`
|
||||
- `posY`
|
||||
- `negY`
|
||||
- `posZ`
|
||||
- `negZ`
|
||||
- `posY` is the top face and `negY` is the bottom face
|
||||
- future geometry slices may evolve these box-authored solids into freely transformable whitebox solids while preserving stable face identity where practical
|
||||
- Imported assets live in the asset registry.
|
||||
- Placed imported models live in `modelInstances`.
|
||||
- `modelInstances` are not `entities`.
|
||||
- Typed runtime/editor objects such as `PlayerStart`, `TriggerVolume`, and lights live in `entities`.
|
||||
- Global ambient/sun/background/fog belong in `world` settings.
|
||||
- Local authored lights belong in typed entity schemas.
|
||||
|
||||
### Whitebox geometry direction
|
||||
### Imported model collision
|
||||
|
||||
- the product is moving from grid-bound brush thinking toward intuitive whitebox solids for level blocking
|
||||
- floating point position, rotation, and scale are allowed
|
||||
- the grid is a snap/reference aid, not a hard authoring law
|
||||
- whitebox boxes should support object, face, edge, and vertex interaction modes
|
||||
- non-planar quads are acceptable; rendering/build should triangulate them deterministically
|
||||
- whitebox solids do not need to stay convex
|
||||
- derived collision for whitebox solids should come from the solid-collider path, not from an assumption that all geometry is convex or axis-aligned
|
||||
|
||||
### Model placement
|
||||
|
||||
- placed imported models are **model instances**, not typed entities
|
||||
- keep model instances in a document collection separate from `entities`
|
||||
|
||||
### Imported model collision scope
|
||||
|
||||
- collision authoring for imported models belongs on `modelInstances`, not on asset records
|
||||
- the canonical source of truth is authored collision settings, not cooked collider bytes
|
||||
- generated collider data may be cached or rebuilt, but it is derived from:
|
||||
- imported model asset geometry
|
||||
- model instance transform
|
||||
- authored collision settings
|
||||
- for imported-model collider support beyond simple boxes, prefer integrating a real collision/query library such as Rapier over inventing custom broad-phase/narrow-phase code in-house
|
||||
- let the collision/query layer own broad-phase and narrow-phase pruning instead of re-implementing that manually in app code
|
||||
- do not turn this slice into a full physics sandbox or general rigidbody architecture rewrite unless the roadmap explicitly asks for that
|
||||
- near-term slices may adapt or replace the current handcrafted runner collision path where necessary so brush and imported-model colliders can participate in one coherent collision/query system
|
||||
|
||||
### Runtime interaction scope
|
||||
|
||||
- keep trigger/action/target links explicit and typed
|
||||
- do not activate actions for systems that do not exist yet
|
||||
- add sound and animation actions only when those runtime systems are implemented
|
||||
|
||||
### Whitebox editing scope
|
||||
|
||||
- object, face, edge, and vertex editing should converge on one coherent transform-driven interaction model
|
||||
- `G / R / S` style modal transforms with axis constraints are a good fit for whiteboxing
|
||||
- clipping/extrusion/other topology tools should come after the whitebox-solid interaction model is coherent
|
||||
- unsupported geometry edits must fail clearly instead of inventing hidden topology rules
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
Unless explicitly added to the roadmap, do not turn this project into:
|
||||
|
||||
- a general CAD package
|
||||
- a Blender replacement
|
||||
- a multiplayer MMO editor
|
||||
- a full node-based visual scripting environment
|
||||
- a full physics sandbox
|
||||
- a photoreal AAA renderer
|
||||
- a React Three Fiber showcase
|
||||
- an ECS research project
|
||||
|
||||
We may add optional scripting, plugins, collaboration, or advanced baking later.
|
||||
They are not v1 priorities.
|
||||
|
||||
---
|
||||
|
||||
## Core product vocabulary
|
||||
|
||||
Use these terms consistently:
|
||||
|
||||
- **Document**: canonical editor state
|
||||
- **Whitebox Solid**: author-authored blockout/level-shaping solid used for layout and gameplay space
|
||||
- **Box Solid**: the first whitebox solid shape; current code may still refer to this historically as a box brush
|
||||
- **Face**: one editable surface of a whitebox solid
|
||||
- **Edge**: one editable edge of a whitebox solid
|
||||
- **Vertex**: one editable point of a whitebox solid
|
||||
- **Material**: logical authoring material definition
|
||||
- **Texture**: image resource backing material channels
|
||||
- **Asset**: imported external resource, usually GLB/GLTF or audio and related media
|
||||
- **Model Instance**: placed scene instance of an imported asset
|
||||
- **Collider**: runtime collision representation derived from brushes or imported models
|
||||
- **Prefab**: reusable asset/entity package placeable in scenes
|
||||
- **Entity**: typed scene object with runtime/editor semantics
|
||||
- **Project Package**: portable editable bundle containing canonical scene JSON plus referenced assets
|
||||
- **Runner Package**: deployable playable output for the built-in runner
|
||||
- **Runner**: browser runtime that loads and plays scenes
|
||||
- **Viewport**: editor rendering surface
|
||||
- **Command**: undoable state transition
|
||||
- **Tool**: editor interaction mode such as select, create, transform, or face-edit
|
||||
- **Build**: deterministic transformation from document -> runtime scene data
|
||||
- **Export**: downstream transformation to deployable or interchange deliverables such as runner packages or optional later GLB
|
||||
|
||||
Avoid vague terms like “object”, “thing”, “item”, or “component” when a more precise domain term exists.
|
||||
|
||||
---
|
||||
|
||||
## Repo expectations for agents
|
||||
|
||||
When working in this repo:
|
||||
|
||||
1. Read:
|
||||
- `AGENTS.md`
|
||||
- `CHAT_CONTEXT.md`
|
||||
- then inspect the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md` for the active slice
|
||||
- if a slice touches persistence, runtime, or testing boundaries in a non-obvious way, read the relevant full doc sections before changing code
|
||||
|
||||
2. Respect the current vertical slice.
|
||||
- Do not “prepare for future flexibility” by adding unnecessary systems.
|
||||
- Implement the smallest coherent version that preserves the architecture.
|
||||
|
||||
3. Preserve layering.
|
||||
- `document` owns canonical state.
|
||||
- `commands` apply valid state changes.
|
||||
- `geometry` owns derived solid and collider generation.
|
||||
- `viewport-three` renders editor state.
|
||||
- `runtime-three` plays runtime state.
|
||||
- `entities` owns typed non-brush scene objects.
|
||||
- `assets` adapts external asset/audio/media formats.
|
||||
- `serialization` persists canonical state.
|
||||
|
||||
4. Do not bypass command infrastructure for editor mutations.
|
||||
- If the user can do it in the editor, it should usually be represented as a command.
|
||||
|
||||
5. If persisted schema changes, update compatibility explicitly.
|
||||
- bump the document schema version when required
|
||||
- add or update migrations
|
||||
- add at least one migration or compatibility test
|
||||
|
||||
6. Prefer explicit typing and explicit invariants.
|
||||
- Avoid permissive `any`, loose maps, or magic strings when a discriminated union or typed schema is appropriate.
|
||||
|
||||
7. Keep systems testable.
|
||||
- Geometry generation should be testable outside the browser UI.
|
||||
- Serialization should be round-trip tested.
|
||||
- Runtime interactions should be testable through deterministic fixtures where possible.
|
||||
|
||||
8. Keep browser concerns in mind.
|
||||
- Gracefully handle pointer lock failure, audio unlock requirements, missing gamepads, and asset load failures.
|
||||
- Avoid architecture that assumes native desktop privileges.
|
||||
|
||||
---
|
||||
|
||||
## Code quality rules
|
||||
|
||||
### General
|
||||
|
||||
- TypeScript only
|
||||
- strict typing enabled
|
||||
- prefer pure functions for transforms/build steps
|
||||
- isolate impure browser/three.js side effects
|
||||
- no silent catch-and-ignore
|
||||
- no dead feature flags without roadmap justification
|
||||
- no hidden singleton globals unless explicitly part of infrastructure
|
||||
|
||||
### Naming
|
||||
|
||||
- use descriptive names
|
||||
- prefer domain names over generic utility names
|
||||
- avoid abbreviations unless they are standard and obvious
|
||||
- function names should describe intent, not implementation detail
|
||||
|
||||
Good:
|
||||
- `buildRuntimeSceneFromDocument`
|
||||
- `applyMaterialToSelectedFaces`
|
||||
- `createBoxBrushCommand`
|
||||
|
||||
Bad:
|
||||
- `handleThing`
|
||||
- `updateData`
|
||||
- `doBuild`
|
||||
|
||||
### File organization
|
||||
|
||||
- small files where it helps clarity
|
||||
- split by domain, not by arbitrary technical categories
|
||||
- avoid giant “misc” or “utils” dumping grounds
|
||||
- every folder should have a clear reason to exist
|
||||
|
||||
### Comments
|
||||
|
||||
- explain *why*, not what the code obviously does
|
||||
- use comments to document invariants, constraints, and tricky browser behavior
|
||||
- remove stale comments promptly
|
||||
|
||||
### Error handling
|
||||
|
||||
- fail loudly in development
|
||||
- surface usable diagnostics in the editor UI
|
||||
- never corrupt the document silently
|
||||
- preserve previous valid state on failed builds where possible
|
||||
|
||||
---
|
||||
|
||||
## Data model rules
|
||||
|
||||
The canonical authoring state must remain independent from three.js scene graph objects.
|
||||
|
||||
### Required separation
|
||||
|
||||
Maintain these layers:
|
||||
|
||||
1. **Authoring model**
|
||||
- JSON-serializable
|
||||
- versioned
|
||||
- typed
|
||||
- stable across runtime/editor rebuilds
|
||||
|
||||
2. **Editor view model**
|
||||
- three.js meshes, helpers, overlays, gizmos
|
||||
- disposable and rebuildable
|
||||
|
||||
3. **Runtime model**
|
||||
- play-mode scene graph
|
||||
- controllers, triggers, emitters, colliders, animation mixers
|
||||
|
||||
Do not let editor-only helpers leak into the canonical document.
|
||||
Do not store raw three.js objects inside canonical document state.
|
||||
|
||||
### Whitebox geometry rules
|
||||
|
||||
- whitebox solids are canonical authoring objects, not raw renderer state
|
||||
- face material assignments are per-face
|
||||
- UV transforms are canonical editor data
|
||||
- render triangulation is derived data
|
||||
- collision generation is derived data
|
||||
- non-planar quad faces are acceptable if the derived mesh triangulates them deterministically
|
||||
- whitebox solids do not need to remain convex
|
||||
- current box solids still use stable face IDs, even if later slices relax earlier axis-aligned constraints
|
||||
|
||||
### Entity rules
|
||||
|
||||
- entities must be typed
|
||||
- entity schemas must be explicit
|
||||
- entity defaults must be centralized
|
||||
- entity validation must happen at document/build boundaries
|
||||
- model instances remain separate from entities
|
||||
|
||||
### Imported model collision rules
|
||||
|
||||
- collision settings for imported models live on `modelInstances`
|
||||
- supported collision modes must be explicit and typed
|
||||
- generated collision geometry is derived data, not the canonical source document
|
||||
- collision debug visibility is editor/runtime UI state driven by authored settings, not a hidden renderer-only toggle
|
||||
- avoid implicit “always collide with render mesh” behavior
|
||||
- if broad-phase/narrow-phase pruning or non-box collider support is needed, prefer Rapier over ad hoc custom collision math
|
||||
- collision modes mean:
|
||||
- Collision authoring for imported models belongs on `modelInstances`, not assets.
|
||||
- Supported imported-model collision modes must stay explicit and typed.
|
||||
- Generated collision data is derived data, not canonical source data.
|
||||
- If broad-phase/narrow-phase pruning or non-box collider support is needed, prefer Rapier over custom collision math.
|
||||
- Collision mode meanings are fixed unless deliberately changed:
|
||||
- `none` = no collider
|
||||
- `terrain` = heightfield collider, static only
|
||||
- `static` = triangle mesh collider, fixed only
|
||||
- `dynamic` = convex decomposition into compound collider, dynamic/kinematic capable
|
||||
- `simple` = one cheap primitive or one convex hull
|
||||
|
||||
---
|
||||
### Whiteboxing direction
|
||||
|
||||
## Performance rules
|
||||
|
||||
Performance matters, but premature micro-optimization does not.
|
||||
|
||||
Priorities:
|
||||
|
||||
1. editor responsiveness during common operations
|
||||
2. deterministic rebuild behavior
|
||||
3. predictable memory usage
|
||||
4. runtime smoothness for modest scenes
|
||||
5. export/build correctness
|
||||
|
||||
When optimizing:
|
||||
|
||||
- measure first
|
||||
- optimize hotspots, not aesthetics
|
||||
- document assumptions
|
||||
- prefer algorithmic improvements over clever hacks
|
||||
|
||||
Expected hotspots:
|
||||
|
||||
- picking/raycasting
|
||||
- whitebox mesh rebuilds / solid triangulation
|
||||
- face highlighting
|
||||
- large texture browser lists
|
||||
- imported asset previews
|
||||
- runtime trigger scanning if implemented naively
|
||||
- The product is moving away from grid-bound brush thinking toward whitebox solids.
|
||||
- Floating point position/rotation/scale are allowed.
|
||||
- The grid is a snap/reference helper, not a hard law.
|
||||
- Whiteboxing should converge on one coherent transform-driven interaction model.
|
||||
- Object / face / edge / vertex editing are valid goals.
|
||||
- Non-planar quads are acceptable if derived triangulation is deterministic.
|
||||
- Whitebox solids do not have to remain convex.
|
||||
- Collision should come from the solid collider path, not old axis-aligned assumptions.
|
||||
|
||||
---
|
||||
|
||||
## UX rules
|
||||
## Implementation Strategy
|
||||
|
||||
The editor should feel like a real authoring tool, not a tech demo.
|
||||
### Default workflow
|
||||
|
||||
1. Inspect the current repo first.
|
||||
2. Extend the existing implementation.
|
||||
3. Keep the slice as small and vertical as possible.
|
||||
4. Reuse existing paths instead of adding parallel architecture.
|
||||
5. Verify with the narrowest relevant checks.
|
||||
|
||||
### Vertical slices
|
||||
|
||||
Good slice:
|
||||
|
||||
- document changes
|
||||
- commands
|
||||
- viewport/editor behavior
|
||||
- UI
|
||||
- persistence
|
||||
- runner behavior if relevant
|
||||
- tests
|
||||
- brief manual QA notes
|
||||
|
||||
Bad slice:
|
||||
|
||||
- scaffolding with no user-facing payoff
|
||||
- duplicate systems
|
||||
- speculative abstractions
|
||||
|
||||
### Read selectively
|
||||
|
||||
Only open full reference sections when needed:
|
||||
|
||||
- `architecture.md` for non-trivial runtime/editor/data-model boundaries
|
||||
- `roadmap.md` for future direction and accepted scope
|
||||
- `testing.md` for which test layers to add
|
||||
|
||||
If the slice is local and obvious, do not reload half the repo’s docs.
|
||||
|
||||
---
|
||||
|
||||
## Code Rules
|
||||
|
||||
### Do
|
||||
|
||||
- use TypeScript only
|
||||
- keep types explicit
|
||||
- prefer pure functions for transforms/build steps
|
||||
- isolate browser/three.js side effects
|
||||
- fail loudly in development
|
||||
- surface useful diagnostics instead of silently ignoring errors
|
||||
- keep geometry/collision generation testable outside the browser where practical
|
||||
|
||||
### Don’t
|
||||
|
||||
- add R3F casually
|
||||
- add ECS casually
|
||||
- over-generalize the entity system
|
||||
- replace canonical whitebox data with hidden renderer-only mutations
|
||||
- invent hidden magic behavior without schema support
|
||||
- remove tests to get green CI
|
||||
- silently corrupt state on failure
|
||||
|
||||
---
|
||||
|
||||
## UX Rules
|
||||
|
||||
Prioritize:
|
||||
|
||||
- fast selection
|
||||
- trustworthy snapping when enabled
|
||||
- visible grid and transform feedback
|
||||
- obvious active tool state
|
||||
- low-friction material application
|
||||
- direct transforms
|
||||
- understandable tool state
|
||||
- visible feedback
|
||||
- quick play testing
|
||||
- understandable errors
|
||||
- clear failure modes
|
||||
|
||||
Every new feature should answer:
|
||||
- What does the user see?
|
||||
- What does the user click/drag/type?
|
||||
- How is failure communicated?
|
||||
- How is the action undone?
|
||||
- How is the result tested?
|
||||
Every meaningful feature should answer:
|
||||
|
||||
- what the user sees
|
||||
- what the user clicks/drags/types
|
||||
- how it is undone
|
||||
- how failure is shown
|
||||
- how it is tested
|
||||
|
||||
---
|
||||
|
||||
## Vertical slice policy
|
||||
## Testing Rules
|
||||
|
||||
We build in vertical slices.
|
||||
Each slice must deliver a complete, usable capability across all relevant layers.
|
||||
At minimum, match the slice:
|
||||
|
||||
A good slice includes:
|
||||
- document changes
|
||||
- commands
|
||||
- viewport behavior
|
||||
- UI panel updates
|
||||
- runner behavior if relevant
|
||||
- persistence
|
||||
- tests
|
||||
- manual QA notes
|
||||
- pure/domain tests for deterministic logic
|
||||
- serialization tests for persisted features
|
||||
- runtime/build tests where runtime behavior changes
|
||||
- browser/e2e only when real browser behavior matters
|
||||
|
||||
A bad slice is “just backend structure” or “just a partial UI”.
|
||||
If schema changes:
|
||||
|
||||
Do not land architectural scaffolding that has no immediate use in the current slice.
|
||||
- add round-trip coverage
|
||||
- add migration/compatibility coverage
|
||||
|
||||
If a roadmap item is too large for one pass, split it into smaller end-to-end sub-slices instead of landing half-systems.
|
||||
Prefer small explicit fixtures over giant snapshots.
|
||||
|
||||
---
|
||||
|
||||
## Typical slice shape
|
||||
## Vocabulary
|
||||
|
||||
For each slice, agents should aim to deliver:
|
||||
Use precise terms:
|
||||
|
||||
1. domain model changes
|
||||
2. command(s)
|
||||
3. viewport interaction/tooling
|
||||
4. UI affordance
|
||||
5. serialization support
|
||||
6. runtime/build support if needed
|
||||
7. tests
|
||||
8. docs update if behavior changed materially
|
||||
- `Document`: canonical editor state
|
||||
- `Whitebox Solid`: author-authored blockout / gameplay-space solid
|
||||
- `Box Solid`: the first whitebox solid shape; old code may still say “box brush”
|
||||
- `Face` / `Edge` / `Vertex`: editable parts of a whitebox solid
|
||||
- `Asset`: imported external resource
|
||||
- `Model Instance`: placed instance of an imported asset
|
||||
- `Entity`: typed scene object with editor/runtime semantics
|
||||
- `Collider`: derived runtime collision representation
|
||||
- `Project Package`: portable editable bundle
|
||||
- `Runner Package`: deployable playable output
|
||||
- `Build`: deterministic document -> runtime transformation
|
||||
|
||||
Avoid vague terms like “thing” or “object” when a domain term exists.
|
||||
|
||||
---
|
||||
|
||||
## Decision heuristics
|
||||
## Required Closeout
|
||||
|
||||
When uncertain:
|
||||
|
||||
### Prefer plain three.js over extra abstraction
|
||||
Unless abstraction clearly simplifies repeated patterns.
|
||||
|
||||
### Prefer canonical JSON over reusing runtime/export data structures
|
||||
The editor’s needs are different from export/runtime needs.
|
||||
|
||||
### Prefer typed entity schemas over generic script bags
|
||||
Especially in early versions.
|
||||
|
||||
### Prefer constrained capabilities that feel good over flexible capabilities that feel vague
|
||||
Example:
|
||||
- better to have one excellent whitebox-solid editing flow than five half-working primitive tools
|
||||
|
||||
### Prefer immediate usability over speculative extensibility
|
||||
But preserve clean seams for future extensions.
|
||||
|
||||
---
|
||||
|
||||
## What agents must not do
|
||||
|
||||
Do not:
|
||||
|
||||
- rewrite broad project structure without a strong reason
|
||||
- introduce new framework dependencies casually
|
||||
- add R3F because “we might want it later”
|
||||
- introduce ECS because “games use ECS”
|
||||
- over-generalize the entity system
|
||||
- replace canonical whitebox data with hidden renderer-only mesh mutations
|
||||
- implement hidden magic behaviors without schema support
|
||||
- remove tests to get green CI
|
||||
- make visual changes without noting them in the slice summary
|
||||
- ignore browser restrictions around input/audio
|
||||
|
||||
---
|
||||
|
||||
## Required deliverables in implementation responses
|
||||
|
||||
When making meaningful changes, include:
|
||||
For meaningful changes, report briefly:
|
||||
|
||||
1. what changed
|
||||
2. why it changed
|
||||
3. which files were added/updated
|
||||
4. how to run/test it
|
||||
2. why
|
||||
3. files touched
|
||||
4. how you verified it
|
||||
5. known limitations
|
||||
6. follow-up suggestions only if directly relevant
|
||||
|
||||
If the environment prevents verification, state exactly what was and was not verified.
|
||||
|
||||
---
|
||||
|
||||
## Definition of done for a slice
|
||||
|
||||
A slice is done when:
|
||||
|
||||
- the feature can be used end-to-end
|
||||
- the feature is represented in canonical document data
|
||||
- the feature can be saved and loaded
|
||||
- the feature is test-covered appropriately
|
||||
- the feature has manual verification notes
|
||||
- the feature does not violate the architecture
|
||||
- obvious failures produce usable diagnostics
|
||||
- undo/redo works if the feature is editor-authored
|
||||
|
||||
---
|
||||
|
||||
## Preferred stack unless changed deliberately
|
||||
|
||||
- TypeScript
|
||||
- React
|
||||
- Vite
|
||||
- three.js
|
||||
- Vitest
|
||||
- Playwright
|
||||
- ESLint
|
||||
- Prettier
|
||||
- a small state store if needed
|
||||
- minimal dependencies overall
|
||||
|
||||
Add dependencies only when they clearly save time and complexity over building in-house.
|
||||
|
||||
---
|
||||
|
||||
## Final instruction to agents
|
||||
|
||||
Build the smallest coherent thing that feels real.
|
||||
|
||||
The product should always trend toward:
|
||||
- spatial immediacy
|
||||
- authoring clarity
|
||||
- browser-native practicality
|
||||
- fast iteration
|
||||
- strong foundations for whiteboxing, assets, entities, and runner behavior
|
||||
|
||||
If forced to choose, preserve the integrity of:
|
||||
1. the canonical document model
|
||||
2. the whiteboxing workflow
|
||||
3. the edit -> run loop
|
||||
If you could not verify something, say so plainly.
|
||||
|
||||
255
CHAT_CONTEXT.md
255
CHAT_CONTEXT.md
@@ -1,198 +1,139 @@
|
||||
# CHAT_CONTEXT.md
|
||||
|
||||
This file is the lightweight startup context for new Codex chats.
|
||||
This file is the small startup brief for new implementation chats.
|
||||
|
||||
Read this after `AGENTS.md`.
|
||||
Then inspect only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md` for the active slice.
|
||||
Then inspect the code.
|
||||
Then open only the relevant sections of `architecture.md`, `roadmap.md`, and `testing.md`.
|
||||
|
||||
This file does not replace the full docs.
|
||||
It exists to keep new chats focused and to reduce repeated context load.
|
||||
The large docs are reference docs, not mandatory full reads.
|
||||
|
||||
---
|
||||
|
||||
## Product summary
|
||||
## Current Status
|
||||
|
||||
This repo is a browser-based 3D scene authoring tool with a built-in runner.
|
||||
As of now, the repo is no longer in the very early “empty skeleton” phase.
|
||||
|
||||
Core loop:
|
||||
Broadly implemented already:
|
||||
|
||||
1. author a scene
|
||||
2. save/load it reliably
|
||||
3. run it in-browser immediately
|
||||
- foundational document/command/persistence/test setup
|
||||
- box-based room authoring and per-face materials / UVs
|
||||
- built-in runner with edit -> run loop
|
||||
- world settings / lighting / environment basics
|
||||
- typed entities and trigger/action/target interaction flow
|
||||
- GLB/GLTF model import and model instances
|
||||
- local lights, animation playback, spatial audio
|
||||
- advanced rendering
|
||||
- better material-library workflow
|
||||
- runner package / embeddable runner work
|
||||
- multi-viewport editor foundations
|
||||
- unified creation/placement foundations
|
||||
- transform foundations
|
||||
|
||||
The product prioritizes:
|
||||
Important consequence:
|
||||
|
||||
- intuitive whiteboxing / level blocking for interactive 3D environments
|
||||
- imported assets as first-class additions
|
||||
- typed entities and simple interactions
|
||||
- browser-native delivery
|
||||
- many roadmap sections are now historical context, not literal todo items
|
||||
- do not assume Milestone 0-3 are untouched just because they are still documented
|
||||
|
||||
It is not:
|
||||
|
||||
- an unlimited general-purpose engine platform
|
||||
- a Blender replacement
|
||||
- a general CAD tool
|
||||
- an R3F showcase
|
||||
When in doubt, inspect the current code before trusting old milestone wording.
|
||||
|
||||
---
|
||||
|
||||
## Hard architectural rules
|
||||
## Current Product Direction
|
||||
|
||||
- The canonical `SceneDocument` is the source of truth.
|
||||
- The document must stay independent from three.js objects.
|
||||
- Editor-authored mutations should flow through commands.
|
||||
- The editor viewport is derived from the document.
|
||||
- The runner is a sibling system, not an editor hack.
|
||||
- Canonical document format is project JSON, not glTF/GLB.
|
||||
- Portable save/load for asset-bearing scenes should use a project package built around that JSON.
|
||||
- Runner/deployment output is downstream from the document/runtime build and is separate from editable project save/load.
|
||||
- Model instances are separate from typed entities.
|
||||
The product is a browser-native engine/editor for interactive 3D environments.
|
||||
|
||||
Key direction:
|
||||
|
||||
- intuitive whiteboxing / level blocking
|
||||
- imported assets as first-class content
|
||||
- typed entities and runtime interactions
|
||||
- fast built-in runner workflow
|
||||
|
||||
The geometry direction is shifting from old grid-bound “brush” thinking toward whitebox solids:
|
||||
|
||||
- floating point transforms allowed
|
||||
- free object rotation allowed
|
||||
- grid is optional snap/reference help
|
||||
- object / face / edge / vertex editing should converge on one transform-driven model
|
||||
- non-planar quads are acceptable if triangulated deterministically
|
||||
- non-convex whitebox solids are acceptable if the solid mesh/collider path supports them
|
||||
|
||||
Old code and docs may still say “brush” in places.
|
||||
Treat current box-brush structures as the starting point for whitebox solids unless the slice deliberately changes that.
|
||||
|
||||
---
|
||||
|
||||
## Early binding decisions
|
||||
## Hard Current Assumptions
|
||||
|
||||
These are fixed for the early milestones unless a later slice explicitly changes them.
|
||||
- world is right-handed and Y-up
|
||||
- canonical state lives outside the React tree
|
||||
- document/project state remains source of truth
|
||||
- editor changes should flow through commands
|
||||
- model instances remain separate from entities
|
||||
- world settings own global background / ambient / sun / fog
|
||||
- local authored lights stay in typed entities
|
||||
- project save/load and runner export are separate concerns
|
||||
|
||||
### Coordinates and units
|
||||
Imported model collision:
|
||||
|
||||
- world is right-handed and **Y-up**
|
||||
- `+X` is right
|
||||
- `+Y` is up
|
||||
- units are meter-like
|
||||
|
||||
### Repo shape
|
||||
|
||||
- keep the repo as a single Vite app
|
||||
- keep domain folders under `src/`
|
||||
- do not split into a monorepo early
|
||||
|
||||
### State ownership
|
||||
|
||||
- do not use the React tree as the canonical state container
|
||||
- keep canonical state in a thin external editor store/service
|
||||
|
||||
### Persistence
|
||||
|
||||
- version the document from day one
|
||||
- keep migrations explicit
|
||||
- early project persistence can be local draft storage plus JSON import/export
|
||||
- once binary assets exist, portable save/load should use a project package such as `scene.json` plus bundled assets
|
||||
- canonical JSON stays the source document format underneath that project package
|
||||
- runner package output is a separate deployable artifact
|
||||
- binary assets must survive reload via embedded or project-scoped persistent storage
|
||||
- never rely on Blob URLs as the only persisted asset reference
|
||||
|
||||
### Current box-solid foundation
|
||||
|
||||
- early slices began with an axis-aligned box shape and stable face IDs
|
||||
- stable box face IDs are:
|
||||
- `posX`
|
||||
- `negX`
|
||||
- `posY`
|
||||
- `negY`
|
||||
- `posZ`
|
||||
- `negZ`
|
||||
- `posY` is top and `negY` is bottom
|
||||
|
||||
### Whitebox direction
|
||||
|
||||
- move away from grid-bound brush thinking toward whitebox solids
|
||||
- allow floating point transforms
|
||||
- allow free object rotation
|
||||
- use the grid as optional snap/reference help, not as a hard restriction
|
||||
- unify object / face / edge / vertex editing around one transform-driven interaction model
|
||||
- non-planar quads are acceptable if triangulated deterministically in derived geometry
|
||||
- non-convex whitebox solids are acceptable if the solid mesh/collider pipeline can support them
|
||||
|
||||
### Early UV data
|
||||
|
||||
Per face, keep explicit UV transform values such as:
|
||||
|
||||
- `offset`
|
||||
- `scale`
|
||||
- `rotationQuarterTurns`
|
||||
- `flipU`
|
||||
- `flipV`
|
||||
|
||||
“Fit to face” should rewrite explicit values, not add a magical persistent flag.
|
||||
|
||||
### Model placement
|
||||
|
||||
- imported assets live in the asset registry
|
||||
- placed imported models live in `modelInstances`
|
||||
- typed scene objects like `PlayerStart`, `TriggerVolume`, or lights live in `entities`
|
||||
- collision authoring for imported models belongs on `modelInstances`, not asset records
|
||||
- generated imported-model collider data should be derived from asset geometry + instance transform + authored settings
|
||||
- for imported-model collider types beyond simple boxes, prefer a Rapier-backed collision/query layer over extending the handcrafted collision code indefinitely
|
||||
- broad-phase and narrow-phase pruning should come from that collision/query layer, not custom app code
|
||||
|
||||
### Interaction scope
|
||||
|
||||
- keep `Trigger -> Action -> Target` typed and explicit
|
||||
- do not add actions for systems that do not exist yet
|
||||
|
||||
### World environment vs local lights
|
||||
|
||||
- global background / ambient / sun / fog belong in `world` settings
|
||||
- local authored lights belong in typed entity schemas
|
||||
- true skyboxes or environment textures belong after persistent asset storage exists
|
||||
- authored collision settings belong on `modelInstances`
|
||||
- generated collider data is derived, not canonical
|
||||
- if non-box collider support needs broad-phase/narrow-phase pruning, prefer Rapier over custom app-side collision math
|
||||
|
||||
---
|
||||
|
||||
## What a good slice looks like
|
||||
## Reading Strategy
|
||||
|
||||
Each slice should land the smallest coherent end-to-end version of the feature across the layers it touches:
|
||||
Default:
|
||||
|
||||
- document data
|
||||
- commands
|
||||
- viewport behavior
|
||||
- runner behavior if relevant
|
||||
- persistence
|
||||
- UI
|
||||
- tests
|
||||
1. read `AGENTS.md`
|
||||
2. read this file
|
||||
3. inspect the code paths touched by the slice
|
||||
4. open only the relevant sections of:
|
||||
- `architecture.md`
|
||||
- `roadmap.md`
|
||||
- `testing.md`
|
||||
|
||||
Do not land speculative scaffolding with no immediate slice use.
|
||||
Open the larger docs only when needed:
|
||||
|
||||
If a roadmap item is too large, split it into smaller vertical slices.
|
||||
- `architecture.md`
|
||||
- data-model boundaries
|
||||
- runtime/editor integration
|
||||
- geometry/collision semantics
|
||||
- persistence/export/package architecture
|
||||
|
||||
- `roadmap.md`
|
||||
- whether a direction is already chosen
|
||||
- whether something is intentionally deferred
|
||||
- how a large topic should be split into slices
|
||||
|
||||
- `testing.md`
|
||||
- what test layers to add
|
||||
- schema/migration expectations
|
||||
- browser/e2e guidance
|
||||
|
||||
If the slice is small and local, do not reread unrelated doc sections.
|
||||
|
||||
---
|
||||
|
||||
## Required habits for implementation
|
||||
## What To Be Careful About
|
||||
|
||||
- Inspect the current repo first.
|
||||
- Extend the current implementation instead of restarting architecture.
|
||||
- If persisted schema changes, update versioning/migrations and add a compatibility test.
|
||||
- Run the narrowest relevant checks you can.
|
||||
- Report what was actually verified.
|
||||
- do not restart architecture just because the original docs were written earlier
|
||||
- extend existing paths instead of introducing parallel systems
|
||||
- if docs and code disagree on current behavior, trust the code and update docs if your slice changes direction materially
|
||||
- keep responses brief and verification scoped to the actual slice
|
||||
|
||||
---
|
||||
|
||||
## Early slice ordering to keep in mind
|
||||
## Likely Near-Term Themes
|
||||
|
||||
- M0: foundation, document, commands, persistence, test setup
|
||||
- M1: axis-aligned box brushes, face materials/UVs, runner, first-room polish, world lighting basics
|
||||
- M2: typed entities, simple trigger/action/target interactions, click interactions
|
||||
- M3: GLB/GLTF import, local lights + skyboxes, animation, spatial audio
|
||||
- M4+: whitebox-solid interaction model, component editing, derived solid triangulation/collision
|
||||
The next large topics are more likely to be things like:
|
||||
|
||||
That ordering matters because:
|
||||
- whitebox-solid editing model
|
||||
- multi-scene / project structure
|
||||
- richer runtime systems
|
||||
- remaining packaging / portability work
|
||||
- future primitives and topology tools after the whitebox direction is coherent
|
||||
|
||||
- world settings do not need entity or asset pipelines
|
||||
- local lights need the entity system
|
||||
- skyboxes need persistent asset storage
|
||||
- animation and audio actions should land only with those runtime systems
|
||||
|
||||
---
|
||||
|
||||
## When to open the full docs
|
||||
|
||||
Open the relevant full sections when:
|
||||
|
||||
- persistence schema changes
|
||||
- runtime/editor boundaries are being touched
|
||||
- a slice adds new tests or new failure modes
|
||||
- geometry semantics are non-trivial
|
||||
- import/export behavior changes
|
||||
|
||||
Otherwise, stay focused on the active slice and keep the implementation small.
|
||||
Do not assume the old prompt list is still the whole plan.
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# architecture.md
|
||||
|
||||
Use this as a selective reference doc.
|
||||
|
||||
Do not read this file end-to-end by default.
|
||||
Read only the headings relevant to the active slice after reading `AGENTS.md`, `CHAT_CONTEXT.md`, and inspecting the current code.
|
||||
|
||||
If examples in this file lag behind the code, trust the code for current behavior and update the docs when your slice materially changes direction.
|
||||
|
||||
## Overview
|
||||
|
||||
This project is a browser-based 3D scene authoring tool with a built-in runtime runner.
|
||||
@@ -365,15 +372,24 @@ Rules:
|
||||
- no three.js object references
|
||||
- should be testable in isolation
|
||||
|
||||
Example structure:
|
||||
Example persisted project structure:
|
||||
|
||||
```ts
|
||||
interface SceneDocument {
|
||||
interface ProjectDocument {
|
||||
version: number;
|
||||
world: WorldSettings;
|
||||
name: string;
|
||||
activeSceneId: string;
|
||||
scenes: Record<string, ProjectScene>;
|
||||
materials: Record<string, MaterialDef>;
|
||||
textures: Record<string, TextureDef>;
|
||||
assets: Record<string, AssetRecord>;
|
||||
}
|
||||
|
||||
interface ProjectScene {
|
||||
id: string;
|
||||
name: string;
|
||||
loadingScreen: SceneLoadingScreenSettings;
|
||||
world: WorldSettings;
|
||||
brushes: Record<string, Brush>;
|
||||
modelInstances: Record<string, ModelInstance>;
|
||||
entities: Record<string, EntityInstance>;
|
||||
@@ -575,7 +591,7 @@ Near-term runtime collision is intentionally narrower than a full game-engine ph
|
||||
Initial modes:
|
||||
|
||||
- first-person
|
||||
- orbit visitor
|
||||
- third-person
|
||||
|
||||
Later optional modes:
|
||||
|
||||
@@ -584,6 +600,8 @@ Later optional modes:
|
||||
- click-to-teleport
|
||||
- controller-supported variants where applicable
|
||||
|
||||
Every new movement mode or controller feature must ship with default keyboard and standard-gamepad bindings, even if the authored inspector UI stays simple.
|
||||
|
||||
These modes should share a common interface:
|
||||
|
||||
```ts
|
||||
@@ -831,6 +849,8 @@ At that point, the user-facing save/load format should be a **project package**
|
||||
- `scene.json`
|
||||
- referenced asset payloads
|
||||
|
||||
`scene.json` may still contain multiple authored scenes inside one project document; the file name does not imply a single loaded runtime scene.
|
||||
|
||||
Recommended logical shape:
|
||||
|
||||
```txt
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "^0.19.3",
|
||||
"fflate": "^0.8.2",
|
||||
"postprocessing": "^6.39.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
29
playwright.config.js
Normal file
29
playwright.config.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
export default defineConfig({
|
||||
testDir: "./tests/e2e",
|
||||
testMatch: ["**/*.e2e.ts"],
|
||||
timeout: 30_000,
|
||||
expect: {
|
||||
timeout: 5_000
|
||||
},
|
||||
use: {
|
||||
baseURL: "http://127.0.0.1:4173",
|
||||
trace: "on-first-retry"
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
launchOptions: {
|
||||
args: ["--enable-webgl", "--use-gl=angle", "--use-angle=swiftshader-webgl"]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
webServer: {
|
||||
command: "npm run dev -- --host 127.0.0.1 --port 4173",
|
||||
url: "http://127.0.0.1:4173",
|
||||
reuseExistingServer: !process.env.CI
|
||||
}
|
||||
});
|
||||
11
roadmap.md
11
roadmap.md
@@ -1,5 +1,12 @@
|
||||
# roadmap.md
|
||||
|
||||
Use this as a direction/scope doc, not as proof that every earlier slice is still unimplemented.
|
||||
|
||||
Do not read this file end-to-end by default.
|
||||
Read only the relevant milestone/slice headings after checking the current code.
|
||||
|
||||
Completed or partially completed historical slices may still be documented here for context.
|
||||
|
||||
## Overview
|
||||
|
||||
This roadmap is organized as vertical slices.
|
||||
@@ -180,7 +187,7 @@ This is the first proof that the product is real.
|
||||
|
||||
- runtime build from document
|
||||
- first-person navigation
|
||||
- orbit visitor mode
|
||||
- third-person mode
|
||||
- mode switch
|
||||
- minimal typed `PlayerStart` support
|
||||
- basic collision against axis-aligned box brush geometry
|
||||
@@ -190,7 +197,7 @@ This is the first proof that the product is real.
|
||||
|
||||
- user can press Run and navigate the scene
|
||||
- first-person works with keyboard/mouse
|
||||
- orbit visitor works
|
||||
- third-person works
|
||||
- leaving run mode returns to editor state safely
|
||||
- `PlayerStart` does not need to be rebuilt later as a separate foundation
|
||||
|
||||
|
||||
3615
src/app/App.js
Normal file
3615
src/app/App.js
Normal file
File diff suppressed because one or more lines are too long
9822
src/app/App.tsx
9822
src/app/App.tsx
File diff suppressed because it is too large
Load Diff
176
src/app/app.css
176
src/app/app.css
@@ -32,7 +32,11 @@ body {
|
||||
min-height: 100vh;
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(80, 96, 120, 0.35) 0%, rgba(23, 28, 37, 0) 42%),
|
||||
radial-gradient(
|
||||
circle at top,
|
||||
rgba(80, 96, 120, 0.35) 0%,
|
||||
rgba(23, 28, 37, 0) 42%
|
||||
),
|
||||
linear-gradient(180deg, #1b2029 0%, #101318 100%);
|
||||
color: var(--color-text);
|
||||
}
|
||||
@@ -74,6 +78,7 @@ button:disabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
padding: 8px 14px;
|
||||
background: rgba(18, 22, 28, 0.88);
|
||||
@@ -103,12 +108,37 @@ button:disabled {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.toolbar__scene-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
flex: 1 1 520px;
|
||||
min-width: 260px;
|
||||
}
|
||||
|
||||
.toolbar__project-name {
|
||||
flex: 1 1 240px;
|
||||
min-width: 180px;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.toolbar__scene-picker {
|
||||
flex: 0 1 220px;
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.toolbar__scene-name {
|
||||
flex: 1 1 320px;
|
||||
min-width: 220px;
|
||||
min-width: 180px;
|
||||
max-width: 460px;
|
||||
}
|
||||
|
||||
.toolbar__scene-select {
|
||||
min-height: 36px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.toolbar__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -176,6 +206,7 @@ button:disabled {
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 241, 213, 0.28);
|
||||
}
|
||||
|
||||
.toolbar__project-name-input,
|
||||
.toolbar__scene-name-input {
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
@@ -185,7 +216,10 @@ button:disabled {
|
||||
|
||||
.workspace {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(240px, 280px) minmax(0, 1fr) minmax(280px, 320px);
|
||||
grid-template-columns: minmax(240px, 280px) minmax(0, 1fr) minmax(
|
||||
280px,
|
||||
320px
|
||||
);
|
||||
gap: 12px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
@@ -278,7 +312,11 @@ button:disabled {
|
||||
|
||||
.stat-card {
|
||||
padding: 12px;
|
||||
background: linear-gradient(180deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.02) 100%);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
rgba(255, 255, 255, 0.04) 0%,
|
||||
rgba(255, 255, 255, 0.02) 100%
|
||||
);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 14px;
|
||||
}
|
||||
@@ -970,7 +1008,11 @@ button:disabled {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(130, 154, 188, 0.28) 0%, rgba(130, 154, 188, 0) 38%),
|
||||
radial-gradient(
|
||||
circle at top,
|
||||
rgba(130, 154, 188, 0.28) 0%,
|
||||
rgba(130, 154, 188, 0) 38%
|
||||
),
|
||||
linear-gradient(180deg, #55657c 0%, #2c3440 34%, #151920 100%);
|
||||
}
|
||||
|
||||
@@ -1127,7 +1169,11 @@ button:disabled {
|
||||
gap: 8px;
|
||||
padding: 18px;
|
||||
color: #f3e8da;
|
||||
background: linear-gradient(180deg, rgba(8, 10, 14, 0.12) 0%, rgba(8, 10, 14, 0.58) 100%);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
rgba(8, 10, 14, 0.12) 0%,
|
||||
rgba(8, 10, 14, 0.58) 100%
|
||||
);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 18px;
|
||||
pointer-events: auto;
|
||||
@@ -1141,6 +1187,78 @@ button:disabled {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition:
|
||||
opacity 240ms ease,
|
||||
visibility 240ms ease;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-overlay--hidden {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-card {
|
||||
width: min(480px, 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 20px 22px;
|
||||
color: #f6efe5;
|
||||
background: rgba(8, 10, 14, 0.68);
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 28px 52px rgba(0, 0, 0, 0.28);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.runner-canvas__loading-badge {
|
||||
color: var(--color-accent-strong);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-scene-name {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-headline {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-description {
|
||||
color: rgba(246, 239, 229, 0.78);
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.runner-canvas__loading-error {
|
||||
padding: 10px 12px;
|
||||
color: #ffd9cf;
|
||||
background: rgba(110, 18, 6, 0.34);
|
||||
border: 1px solid rgba(255, 170, 149, 0.18);
|
||||
border-radius: 12px;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.runner-canvas__crosshair {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
@@ -1163,6 +1281,26 @@ button:disabled {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.runner-canvas--underwater {
|
||||
box-shadow: inset 0 0 0 9999px rgba(9, 38, 62, 0.08);
|
||||
}
|
||||
|
||||
.runner-canvas__underwater {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
background:
|
||||
radial-gradient(
|
||||
circle at 50% 18%,
|
||||
rgba(146, 223, 255, 0.2),
|
||||
transparent 42%
|
||||
),
|
||||
linear-gradient(180deg, rgba(38, 113, 153, 0.16), rgba(8, 40, 63, 0.42));
|
||||
backdrop-filter: blur(1.5px) saturate(1.08);
|
||||
mix-blend-mode: screen;
|
||||
}
|
||||
|
||||
.runner-canvas__prompt {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
@@ -1206,9 +1344,10 @@ button:disabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: wrap;
|
||||
flex-wrap: nowrap;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
height: 36px;
|
||||
padding: 6px 12px;
|
||||
background: rgba(18, 22, 28, 0.88);
|
||||
border: 1px solid var(--color-border);
|
||||
@@ -1216,13 +1355,24 @@ button:disabled {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.2;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.status-bar__item {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 4px;
|
||||
flex: 0 0 auto;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.status-bar__item--message {
|
||||
flex: 1 1 320px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.status-bar__item--asset {
|
||||
@@ -1304,6 +1454,18 @@ button:disabled {
|
||||
.status-bar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
height: auto;
|
||||
padding: 12px 16px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.status-bar__item {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.status-bar__item--message,
|
||||
.status-bar__item--asset {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
}
|
||||
}
|
||||
|
||||
391
src/app/editor-store.js
Normal file
391
src/app/editor-store.js
Normal file
@@ -0,0 +1,391 @@
|
||||
import { CommandHistory } from "../commands/command-history";
|
||||
import { areEditorSelectionsEqual, normalizeSelectionForWhiteboxSelectionMode } from "../core/selection";
|
||||
import {} from "../core/whitebox-selection-mode";
|
||||
import { areTransformSessionsEqual, cloneTransformSession, createInactiveTransformSession } from "../core/transform-session";
|
||||
import { createEmptySceneDocument } from "../document/scene-document";
|
||||
import { DEFAULT_SCENE_DRAFT_STORAGE_KEY, loadSceneDocumentDraft, saveSceneDocumentDraft } from "../serialization/local-draft-storage";
|
||||
import { parseSceneDocumentJson, serializeSceneDocument } from "../serialization/scene-document-json";
|
||||
import { areViewportToolPreviewsEqual, cloneViewportToolPreview, createDefaultViewportTransientState, isViewportToolPreviewCompatible } from "../viewport-three/viewport-transient-state";
|
||||
import { areViewportPanelCameraStatesEqual, cloneViewportLayoutState, cloneViewportPanelCameraState, createDefaultViewportLayoutState } from "../viewport-three/viewport-layout";
|
||||
export class EditorStore {
|
||||
document;
|
||||
selection = { kind: "none" };
|
||||
whiteboxSelectionMode = "object";
|
||||
toolMode = "select";
|
||||
viewportLayoutMode;
|
||||
activeViewportPanelId;
|
||||
viewportPanels;
|
||||
viewportQuadSplit;
|
||||
viewportTransientState = createDefaultViewportTransientState();
|
||||
previousEditingToolMode = "select";
|
||||
history = new CommandHistory();
|
||||
listeners = new Set();
|
||||
storage;
|
||||
storageKey;
|
||||
lastCommandLabel = null;
|
||||
snapshot;
|
||||
commandContext = {
|
||||
getDocument: () => this.document,
|
||||
setDocument: (document) => {
|
||||
this.document = document;
|
||||
},
|
||||
getSelection: () => this.selection,
|
||||
setSelection: (selection) => {
|
||||
this.selection = selection;
|
||||
},
|
||||
getToolMode: () => this.toolMode,
|
||||
setToolMode: (toolMode) => {
|
||||
this.toolMode = toolMode;
|
||||
}
|
||||
};
|
||||
constructor(options = {}) {
|
||||
const initialViewportLayoutState = cloneViewportLayoutState(options.initialViewportLayoutState ?? createDefaultViewportLayoutState());
|
||||
this.document = options.initialDocument ?? createEmptySceneDocument();
|
||||
this.viewportLayoutMode = initialViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = initialViewportLayoutState.activePanelId;
|
||||
this.viewportPanels = initialViewportLayoutState.panels;
|
||||
this.viewportQuadSplit = initialViewportLayoutState.viewportQuadSplit;
|
||||
this.storage = options.storage ?? null;
|
||||
this.storageKey = options.storageKey ?? DEFAULT_SCENE_DRAFT_STORAGE_KEY;
|
||||
this.snapshot = this.createSnapshot();
|
||||
}
|
||||
subscribe = (listener) => {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
};
|
||||
getState = () => this.snapshot;
|
||||
setToolMode(toolMode) {
|
||||
if (this.toolMode === toolMode) {
|
||||
return;
|
||||
}
|
||||
if (toolMode !== "play") {
|
||||
this.previousEditingToolMode = toolMode;
|
||||
}
|
||||
this.toolMode = toolMode;
|
||||
if (!isViewportToolPreviewCompatible(toolMode, this.viewportTransientState.toolPreview)) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: createDefaultViewportTransientState().toolPreview
|
||||
};
|
||||
}
|
||||
if (toolMode !== "select" && this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
setViewportLayoutMode(viewportLayoutMode) {
|
||||
if (this.viewportLayoutMode === viewportLayoutMode) {
|
||||
return;
|
||||
}
|
||||
this.viewportLayoutMode = viewportLayoutMode;
|
||||
this.emit();
|
||||
}
|
||||
setActiveViewportPanel(panelId) {
|
||||
if (this.activeViewportPanelId === panelId) {
|
||||
return;
|
||||
}
|
||||
this.activeViewportPanelId = panelId;
|
||||
this.emit();
|
||||
}
|
||||
setViewportPanelViewMode(panelId, viewMode) {
|
||||
if (this.viewportPanels[panelId].viewMode === viewMode) {
|
||||
return;
|
||||
}
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
viewMode
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setViewportPanelDisplayMode(panelId, displayMode) {
|
||||
if (this.viewportPanels[panelId].displayMode === displayMode) {
|
||||
return;
|
||||
}
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
displayMode
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setViewportPanelCameraState(panelId, cameraState) {
|
||||
if (areViewportPanelCameraStatesEqual(this.viewportPanels[panelId].cameraState, cameraState)) {
|
||||
return;
|
||||
}
|
||||
this.viewportPanels = {
|
||||
...this.viewportPanels,
|
||||
[panelId]: {
|
||||
...this.viewportPanels[panelId],
|
||||
cameraState: cloneViewportPanelCameraState(cameraState)
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setViewportQuadSplit(viewportQuadSplit) {
|
||||
if (this.viewportQuadSplit.x === viewportQuadSplit.x && this.viewportQuadSplit.y === viewportQuadSplit.y) {
|
||||
return;
|
||||
}
|
||||
this.viewportQuadSplit = {
|
||||
x: viewportQuadSplit.x,
|
||||
y: viewportQuadSplit.y
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setViewportToolPreview(toolPreview) {
|
||||
const nextToolPreview = cloneViewportToolPreview(toolPreview);
|
||||
if (areViewportToolPreviewsEqual(this.viewportTransientState.toolPreview, nextToolPreview)) {
|
||||
return;
|
||||
}
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: nextToolPreview
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
clearViewportToolPreview(sourcePanelId) {
|
||||
const currentToolPreview = this.viewportTransientState.toolPreview;
|
||||
if (currentToolPreview.kind === "none") {
|
||||
return;
|
||||
}
|
||||
if (sourcePanelId !== undefined && currentToolPreview.sourcePanelId !== sourcePanelId) {
|
||||
return;
|
||||
}
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: createDefaultViewportTransientState().toolPreview
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setTransformSession(transformSession) {
|
||||
const nextTransformSession = cloneTransformSession(transformSession);
|
||||
if (areTransformSessionsEqual(this.viewportTransientState.transformSession, nextTransformSession)) {
|
||||
return;
|
||||
}
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: nextTransformSession
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
clearTransformSession() {
|
||||
if (this.viewportTransientState.transformSession.kind === "none") {
|
||||
return;
|
||||
}
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setTransformAxisConstraint(axisConstraint) {
|
||||
if (this.viewportTransientState.transformSession.kind !== "active") {
|
||||
return;
|
||||
}
|
||||
if (this.viewportTransientState.transformSession.axisConstraint === axisConstraint) {
|
||||
return;
|
||||
}
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: {
|
||||
...cloneTransformSession(this.viewportTransientState.transformSession),
|
||||
axisConstraint
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
}
|
||||
setViewportViewMode(viewportViewMode) {
|
||||
this.setViewportPanelViewMode(this.activeViewportPanelId, viewportViewMode);
|
||||
}
|
||||
enterPlayMode() {
|
||||
if (this.toolMode === "play") {
|
||||
return;
|
||||
}
|
||||
this.previousEditingToolMode = this.toolMode;
|
||||
this.toolMode = "play";
|
||||
if (this.viewportTransientState.toolPreview.kind !== "none") {
|
||||
this.viewportTransientState = createDefaultViewportTransientState();
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
exitPlayMode() {
|
||||
if (this.toolMode !== "play") {
|
||||
return;
|
||||
}
|
||||
this.toolMode = this.previousEditingToolMode;
|
||||
this.emit();
|
||||
}
|
||||
setSelection(selection) {
|
||||
if (this.viewportTransientState.transformSession.kind === "active" && !areEditorSelectionsEqual(this.selection, selection)) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
this.selection = selection;
|
||||
this.emit();
|
||||
}
|
||||
setWhiteboxSelectionMode(mode) {
|
||||
if (this.whiteboxSelectionMode === mode) {
|
||||
return;
|
||||
}
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
this.whiteboxSelectionMode = mode;
|
||||
this.selection = normalizeSelectionForWhiteboxSelectionMode(this.selection, mode);
|
||||
this.emit();
|
||||
}
|
||||
executeCommand(command) {
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
}
|
||||
this.history.execute(command, this.commandContext);
|
||||
this.lastCommandLabel = command.label;
|
||||
this.emit();
|
||||
}
|
||||
undo() {
|
||||
let clearedTransformSession = false;
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
clearedTransformSession = true;
|
||||
}
|
||||
const command = this.history.undo(this.commandContext);
|
||||
if (command === null) {
|
||||
if (clearedTransformSession) {
|
||||
this.emit();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
this.lastCommandLabel = `Undid ${command.label}`;
|
||||
this.emit();
|
||||
return true;
|
||||
}
|
||||
redo() {
|
||||
let clearedTransformSession = false;
|
||||
if (this.viewportTransientState.transformSession.kind !== "none") {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
};
|
||||
clearedTransformSession = true;
|
||||
}
|
||||
const command = this.history.redo(this.commandContext);
|
||||
if (command === null) {
|
||||
if (clearedTransformSession) {
|
||||
this.emit();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
this.lastCommandLabel = `Redid ${command.label}`;
|
||||
this.emit();
|
||||
return true;
|
||||
}
|
||||
replaceDocument(document, resetHistory = true) {
|
||||
this.document = document;
|
||||
this.selection = { kind: "none" };
|
||||
this.whiteboxSelectionMode = "object";
|
||||
this.toolMode = "select";
|
||||
this.previousEditingToolMode = "select";
|
||||
this.viewportTransientState = createDefaultViewportTransientState();
|
||||
if (resetHistory) {
|
||||
this.history.clear();
|
||||
this.lastCommandLabel = null;
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
saveDraft() {
|
||||
if (this.storage === null) {
|
||||
return {
|
||||
status: "error",
|
||||
message: "Browser local storage is unavailable."
|
||||
};
|
||||
}
|
||||
return saveSceneDocumentDraft(this.storage, this.document, this.createViewportLayoutState(), this.storageKey);
|
||||
}
|
||||
loadDraft() {
|
||||
if (this.storage === null) {
|
||||
return {
|
||||
status: "error",
|
||||
message: "Browser local storage is unavailable."
|
||||
};
|
||||
}
|
||||
const draftResult = loadSceneDocumentDraft(this.storage, this.storageKey);
|
||||
if (draftResult.status !== "loaded") {
|
||||
return draftResult;
|
||||
}
|
||||
this.replaceDocument(draftResult.document);
|
||||
if (draftResult.viewportLayoutState !== null) {
|
||||
this.applyViewportLayoutState(draftResult.viewportLayoutState);
|
||||
this.emit();
|
||||
}
|
||||
return draftResult;
|
||||
}
|
||||
exportDocumentJson() {
|
||||
return serializeSceneDocument(this.document);
|
||||
}
|
||||
importDocumentJson(source) {
|
||||
const document = parseSceneDocumentJson(source);
|
||||
this.replaceDocument(document);
|
||||
return document;
|
||||
}
|
||||
emit() {
|
||||
this.snapshot = this.createSnapshot();
|
||||
for (const listener of this.listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
createViewportLayoutState() {
|
||||
return cloneViewportLayoutState({
|
||||
layoutMode: this.viewportLayoutMode,
|
||||
activePanelId: this.activeViewportPanelId,
|
||||
panels: this.viewportPanels,
|
||||
viewportQuadSplit: this.viewportQuadSplit
|
||||
});
|
||||
}
|
||||
applyViewportLayoutState(viewportLayoutState) {
|
||||
const nextViewportLayoutState = cloneViewportLayoutState(viewportLayoutState);
|
||||
this.viewportLayoutMode = nextViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = nextViewportLayoutState.activePanelId;
|
||||
this.viewportPanels = nextViewportLayoutState.panels;
|
||||
this.viewportQuadSplit = nextViewportLayoutState.viewportQuadSplit;
|
||||
}
|
||||
createSnapshot() {
|
||||
return {
|
||||
document: this.document,
|
||||
selection: this.selection,
|
||||
whiteboxSelectionMode: this.whiteboxSelectionMode,
|
||||
toolMode: this.toolMode,
|
||||
viewportLayoutMode: this.viewportLayoutMode,
|
||||
activeViewportPanelId: this.activeViewportPanelId,
|
||||
viewportPanels: this.viewportPanels,
|
||||
viewportQuadSplit: this.viewportQuadSplit,
|
||||
viewportTransientState: this.viewportTransientState,
|
||||
canUndo: this.history.canUndo(),
|
||||
canRedo: this.history.canRedo(),
|
||||
lastCommandLabel: this.lastCommandLabel,
|
||||
storageAvailable: this.storage !== null
|
||||
};
|
||||
}
|
||||
}
|
||||
export function createEditorStore(options) {
|
||||
return new EditorStore(options);
|
||||
}
|
||||
@@ -12,9 +12,17 @@ import {
|
||||
cloneTransformSession,
|
||||
createInactiveTransformSession,
|
||||
type TransformAxis,
|
||||
type TransformAxisSpace,
|
||||
type TransformSessionState
|
||||
} from "../core/transform-session";
|
||||
import { createEmptySceneDocument, type SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
applySceneDocumentToProject,
|
||||
createEmptyProjectDocument,
|
||||
createProjectDocumentFromSceneDocument,
|
||||
createSceneDocumentFromProject,
|
||||
type ProjectDocument,
|
||||
type SceneDocument
|
||||
} from "../document/scene-document";
|
||||
import {
|
||||
DEFAULT_SCENE_DRAFT_STORAGE_KEY,
|
||||
type LoadSceneDocumentDraftResult,
|
||||
@@ -23,7 +31,10 @@ import {
|
||||
type SaveSceneDocumentDraftResult,
|
||||
saveSceneDocumentDraft
|
||||
} from "../serialization/local-draft-storage";
|
||||
import { parseSceneDocumentJson, serializeSceneDocument } from "../serialization/scene-document-json";
|
||||
import {
|
||||
parseProjectDocumentJson,
|
||||
serializeProjectDocument
|
||||
} from "../serialization/scene-document-json";
|
||||
import type { ViewportViewMode } from "../viewport-three/viewport-view-modes";
|
||||
import {
|
||||
areViewportToolPreviewsEqual,
|
||||
@@ -48,6 +59,8 @@ import {
|
||||
} from "../viewport-three/viewport-layout";
|
||||
|
||||
export interface EditorStoreState {
|
||||
projectDocument: ProjectDocument;
|
||||
activeSceneId: string;
|
||||
document: SceneDocument;
|
||||
selection: EditorSelection;
|
||||
whiteboxSelectionMode: WhiteboxSelectionMode;
|
||||
@@ -65,6 +78,7 @@ export interface EditorStoreState {
|
||||
|
||||
interface EditorStoreOptions {
|
||||
initialDocument?: SceneDocument;
|
||||
initialProjectDocument?: ProjectDocument;
|
||||
initialViewportLayoutState?: ViewportLayoutState;
|
||||
storage?: KeyValueStorage | null;
|
||||
storageKey?: string;
|
||||
@@ -76,7 +90,9 @@ export type EditorDraftSaveResult = SaveSceneDocumentDraftResult;
|
||||
export type EditorDraftLoadResult = LoadSceneDocumentDraftResult;
|
||||
|
||||
export class EditorStore {
|
||||
private projectDocument: ProjectDocument;
|
||||
private document: SceneDocument;
|
||||
private commandTargetSceneId: string | null = null;
|
||||
private selection: EditorSelection = { kind: "none" };
|
||||
private whiteboxSelectionMode: WhiteboxSelectionMode = "object";
|
||||
private toolMode: ToolMode = "select";
|
||||
@@ -94,9 +110,23 @@ export class EditorStore {
|
||||
private snapshot: EditorStoreState;
|
||||
|
||||
private readonly commandContext: CommandContext = {
|
||||
getDocument: () => this.document,
|
||||
getDocument: () =>
|
||||
createSceneDocumentFromProject(
|
||||
this.projectDocument,
|
||||
this.resolveCommandSceneId()
|
||||
),
|
||||
setDocument: (document) => {
|
||||
this.document = document;
|
||||
this.projectDocument = applySceneDocumentToProject(
|
||||
this.projectDocument,
|
||||
this.resolveCommandSceneId(),
|
||||
document
|
||||
);
|
||||
this.syncActiveSceneDocument();
|
||||
},
|
||||
getProjectDocument: () => this.projectDocument,
|
||||
setProjectDocument: (document) => {
|
||||
this.projectDocument = document;
|
||||
this.syncActiveSceneDocument();
|
||||
},
|
||||
getSelection: () => this.selection,
|
||||
setSelection: (selection) => {
|
||||
@@ -109,9 +139,16 @@ export class EditorStore {
|
||||
};
|
||||
|
||||
constructor(options: EditorStoreOptions = {}) {
|
||||
const initialViewportLayoutState = cloneViewportLayoutState(options.initialViewportLayoutState ?? createDefaultViewportLayoutState());
|
||||
const initialViewportLayoutState = cloneViewportLayoutState(
|
||||
options.initialViewportLayoutState ?? createDefaultViewportLayoutState()
|
||||
);
|
||||
|
||||
this.document = options.initialDocument ?? createEmptySceneDocument();
|
||||
this.projectDocument =
|
||||
options.initialProjectDocument ??
|
||||
(options.initialDocument !== undefined
|
||||
? createProjectDocumentFromSceneDocument(options.initialDocument)
|
||||
: createEmptyProjectDocument());
|
||||
this.document = createSceneDocumentFromProject(this.projectDocument);
|
||||
this.viewportLayoutMode = initialViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = initialViewportLayoutState.activePanelId;
|
||||
this.viewportPanels = initialViewportLayoutState.panels;
|
||||
@@ -142,14 +179,22 @@ export class EditorStore {
|
||||
|
||||
this.toolMode = toolMode;
|
||||
|
||||
if (!isViewportToolPreviewCompatible(toolMode, this.viewportTransientState.toolPreview)) {
|
||||
if (
|
||||
!isViewportToolPreviewCompatible(
|
||||
toolMode,
|
||||
this.viewportTransientState.toolPreview
|
||||
)
|
||||
) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
toolPreview: createDefaultViewportTransientState().toolPreview
|
||||
};
|
||||
}
|
||||
|
||||
if (toolMode !== "select" && this.viewportTransientState.transformSession.kind !== "none") {
|
||||
if (
|
||||
toolMode !== "select" &&
|
||||
this.viewportTransientState.transformSession.kind !== "none"
|
||||
) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
@@ -177,7 +222,10 @@ export class EditorStore {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelViewMode(panelId: ViewportPanelId, viewMode: ViewportViewMode) {
|
||||
setViewportPanelViewMode(
|
||||
panelId: ViewportPanelId,
|
||||
viewMode: ViewportViewMode
|
||||
) {
|
||||
if (this.viewportPanels[panelId].viewMode === viewMode) {
|
||||
return;
|
||||
}
|
||||
@@ -192,7 +240,10 @@ export class EditorStore {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelDisplayMode(panelId: ViewportPanelId, displayMode: ViewportDisplayMode) {
|
||||
setViewportPanelDisplayMode(
|
||||
panelId: ViewportPanelId,
|
||||
displayMode: ViewportDisplayMode
|
||||
) {
|
||||
if (this.viewportPanels[panelId].displayMode === displayMode) {
|
||||
return;
|
||||
}
|
||||
@@ -207,8 +258,16 @@ export class EditorStore {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setViewportPanelCameraState(panelId: ViewportPanelId, cameraState: ViewportPanelCameraState) {
|
||||
if (areViewportPanelCameraStatesEqual(this.viewportPanels[panelId].cameraState, cameraState)) {
|
||||
setViewportPanelCameraState(
|
||||
panelId: ViewportPanelId,
|
||||
cameraState: ViewportPanelCameraState
|
||||
) {
|
||||
if (
|
||||
areViewportPanelCameraStatesEqual(
|
||||
this.viewportPanels[panelId].cameraState,
|
||||
cameraState
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -223,7 +282,10 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
setViewportQuadSplit(viewportQuadSplit: ViewportQuadSplit) {
|
||||
if (this.viewportQuadSplit.x === viewportQuadSplit.x && this.viewportQuadSplit.y === viewportQuadSplit.y) {
|
||||
if (
|
||||
this.viewportQuadSplit.x === viewportQuadSplit.x &&
|
||||
this.viewportQuadSplit.y === viewportQuadSplit.y
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -237,7 +299,12 @@ export class EditorStore {
|
||||
setViewportToolPreview(toolPreview: ViewportToolPreview) {
|
||||
const nextToolPreview = cloneViewportToolPreview(toolPreview);
|
||||
|
||||
if (areViewportToolPreviewsEqual(this.viewportTransientState.toolPreview, nextToolPreview)) {
|
||||
if (
|
||||
areViewportToolPreviewsEqual(
|
||||
this.viewportTransientState.toolPreview,
|
||||
nextToolPreview
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -255,7 +322,10 @@ export class EditorStore {
|
||||
return;
|
||||
}
|
||||
|
||||
if (sourcePanelId !== undefined && currentToolPreview.sourcePanelId !== sourcePanelId) {
|
||||
if (
|
||||
sourcePanelId !== undefined &&
|
||||
currentToolPreview.sourcePanelId !== sourcePanelId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -269,7 +339,12 @@ export class EditorStore {
|
||||
setTransformSession(transformSession: TransformSessionState) {
|
||||
const nextTransformSession = cloneTransformSession(transformSession);
|
||||
|
||||
if (areTransformSessionsEqual(this.viewportTransientState.transformSession, nextTransformSession)) {
|
||||
if (
|
||||
areTransformSessionsEqual(
|
||||
this.viewportTransientState.transformSession,
|
||||
nextTransformSession
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -292,20 +367,31 @@ export class EditorStore {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
setTransformAxisConstraint(axisConstraint: TransformAxis | null) {
|
||||
setTransformAxisConstraint(
|
||||
axisConstraint: TransformAxis | null,
|
||||
axisConstraintSpace: TransformAxisSpace = "world"
|
||||
) {
|
||||
if (this.viewportTransientState.transformSession.kind !== "active") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.viewportTransientState.transformSession.axisConstraint === axisConstraint) {
|
||||
if (
|
||||
this.viewportTransientState.transformSession.axisConstraint ===
|
||||
axisConstraint &&
|
||||
this.viewportTransientState.transformSession.axisConstraintSpace ===
|
||||
axisConstraintSpace
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: {
|
||||
...(cloneTransformSession(this.viewportTransientState.transformSession) as Extract<TransformSessionState, { kind: "active" }>),
|
||||
axisConstraint
|
||||
...(cloneTransformSession(
|
||||
this.viewportTransientState.transformSession
|
||||
) as Extract<TransformSessionState, { kind: "active" }>),
|
||||
axisConstraint,
|
||||
axisConstraintSpace
|
||||
}
|
||||
};
|
||||
this.emit();
|
||||
@@ -340,7 +426,10 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
setSelection(selection: EditorSelection) {
|
||||
if (this.viewportTransientState.transformSession.kind === "active" && !areEditorSelectionsEqual(this.selection, selection)) {
|
||||
if (
|
||||
this.viewportTransientState.transformSession.kind === "active" &&
|
||||
!areEditorSelectionsEqual(this.selection, selection)
|
||||
) {
|
||||
this.viewportTransientState = {
|
||||
...this.viewportTransientState,
|
||||
transformSession: createInactiveTransformSession()
|
||||
@@ -364,7 +453,10 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
this.whiteboxSelectionMode = mode;
|
||||
this.selection = normalizeSelectionForWhiteboxSelectionMode(this.selection, mode);
|
||||
this.selection = normalizeSelectionForWhiteboxSelectionMode(
|
||||
this.selection,
|
||||
mode
|
||||
);
|
||||
this.emit();
|
||||
}
|
||||
|
||||
@@ -376,7 +468,7 @@ export class EditorStore {
|
||||
};
|
||||
}
|
||||
|
||||
this.history.execute(command, this.commandContext);
|
||||
this.history.execute(this.createScopedCommand(command), this.commandContext);
|
||||
this.lastCommandLabel = command.label;
|
||||
this.emit();
|
||||
}
|
||||
@@ -433,8 +525,15 @@ export class EditorStore {
|
||||
return true;
|
||||
}
|
||||
|
||||
replaceDocument(document: SceneDocument, resetHistory = true) {
|
||||
this.document = document;
|
||||
replaceDocument(
|
||||
document: SceneDocument | ProjectDocument,
|
||||
resetHistory = true
|
||||
) {
|
||||
this.projectDocument = isProjectDocument(document)
|
||||
? document
|
||||
: createProjectDocumentFromSceneDocument(document);
|
||||
this.syncActiveSceneDocument();
|
||||
this.commandTargetSceneId = null;
|
||||
this.selection = { kind: "none" };
|
||||
this.whiteboxSelectionMode = "object";
|
||||
this.toolMode = "select";
|
||||
@@ -457,7 +556,12 @@ export class EditorStore {
|
||||
};
|
||||
}
|
||||
|
||||
return saveSceneDocumentDraft(this.storage, this.document, this.createViewportLayoutState(), this.storageKey);
|
||||
return saveSceneDocumentDraft(
|
||||
this.storage,
|
||||
this.projectDocument,
|
||||
this.createViewportLayoutState(),
|
||||
this.storageKey
|
||||
);
|
||||
}
|
||||
|
||||
loadDraft(): EditorDraftLoadResult {
|
||||
@@ -485,11 +589,11 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
exportDocumentJson(): string {
|
||||
return serializeSceneDocument(this.document);
|
||||
return serializeProjectDocument(this.projectDocument);
|
||||
}
|
||||
|
||||
importDocumentJson(source: string): SceneDocument {
|
||||
const document = parseSceneDocumentJson(source);
|
||||
importDocumentJson(source: string): ProjectDocument {
|
||||
const document = parseProjectDocumentJson(source);
|
||||
this.replaceDocument(document);
|
||||
return document;
|
||||
}
|
||||
@@ -512,7 +616,8 @@ export class EditorStore {
|
||||
}
|
||||
|
||||
private applyViewportLayoutState(viewportLayoutState: ViewportLayoutState) {
|
||||
const nextViewportLayoutState = cloneViewportLayoutState(viewportLayoutState);
|
||||
const nextViewportLayoutState =
|
||||
cloneViewportLayoutState(viewportLayoutState);
|
||||
|
||||
this.viewportLayoutMode = nextViewportLayoutState.layoutMode;
|
||||
this.activeViewportPanelId = nextViewportLayoutState.activePanelId;
|
||||
@@ -522,6 +627,8 @@ export class EditorStore {
|
||||
|
||||
private createSnapshot(): EditorStoreState {
|
||||
return {
|
||||
projectDocument: this.projectDocument,
|
||||
activeSceneId: this.projectDocument.activeSceneId,
|
||||
document: this.document,
|
||||
selection: this.selection,
|
||||
whiteboxSelectionMode: this.whiteboxSelectionMode,
|
||||
@@ -537,8 +644,45 @@ export class EditorStore {
|
||||
storageAvailable: this.storage !== null
|
||||
};
|
||||
}
|
||||
|
||||
private syncActiveSceneDocument() {
|
||||
this.document = createSceneDocumentFromProject(this.projectDocument);
|
||||
}
|
||||
|
||||
private resolveCommandSceneId(): string {
|
||||
return this.commandTargetSceneId ?? this.projectDocument.activeSceneId;
|
||||
}
|
||||
|
||||
private withCommandSceneScope<T>(sceneId: string, run: () => T): T {
|
||||
const previousSceneId = this.commandTargetSceneId;
|
||||
this.commandTargetSceneId = sceneId;
|
||||
|
||||
try {
|
||||
return run();
|
||||
} finally {
|
||||
this.commandTargetSceneId = previousSceneId;
|
||||
}
|
||||
}
|
||||
|
||||
private createScopedCommand(command: EditorCommand): EditorCommand {
|
||||
const sceneId = this.projectDocument.activeSceneId;
|
||||
|
||||
return {
|
||||
...command,
|
||||
execute: (context) =>
|
||||
this.withCommandSceneScope(sceneId, () => command.execute(context)),
|
||||
undo: (context) =>
|
||||
this.withCommandSceneScope(sceneId, () => command.undo(context))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function createEditorStore(options?: EditorStoreOptions): EditorStore {
|
||||
return new EditorStore(options);
|
||||
}
|
||||
|
||||
function isProjectDocument(
|
||||
document: SceneDocument | ProjectDocument
|
||||
): document is ProjectDocument {
|
||||
return "scenes" in document && "activeSceneId" in document;
|
||||
}
|
||||
|
||||
4
src/app/use-editor-store.js
Normal file
4
src/app/use-editor-store.js
Normal file
@@ -0,0 +1,4 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
export function useEditorStoreState(store) {
|
||||
return useSyncExternalStore(store.subscribe, store.getState, store.getState);
|
||||
}
|
||||
166
src/assets/audio-assets.js
Normal file
166
src/assets/audio-assets.js
Normal file
@@ -0,0 +1,166 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { createProjectAssetStorageKey } from "./project-assets";
|
||||
function getErrorDetail(error) {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message.trim();
|
||||
}
|
||||
return "Unknown error.";
|
||||
}
|
||||
function getFileExtension(sourceName) {
|
||||
const match = /\.([^.]+)$/u.exec(sourceName.trim());
|
||||
return match === null ? "" : match[1].toLowerCase();
|
||||
}
|
||||
function inferAudioMimeType(sourceName, fallbackMimeType) {
|
||||
if (fallbackMimeType.trim().startsWith("audio/")) {
|
||||
return fallbackMimeType.trim();
|
||||
}
|
||||
switch (getFileExtension(sourceName)) {
|
||||
case "aac":
|
||||
return "audio/aac";
|
||||
case "flac":
|
||||
return "audio/flac";
|
||||
case "m4a":
|
||||
case "mp4":
|
||||
return "audio/mp4";
|
||||
case "mp3":
|
||||
return "audio/mpeg";
|
||||
case "oga":
|
||||
case "ogg":
|
||||
return "audio/ogg";
|
||||
case "wav":
|
||||
case "wave":
|
||||
return "audio/wav";
|
||||
case "webm":
|
||||
return "audio/webm";
|
||||
default:
|
||||
throw new Error(`Unsupported audio asset format for ${sourceName}. Use a browser-supported audio file.`);
|
||||
}
|
||||
}
|
||||
function getImportedFilePath(file) {
|
||||
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
|
||||
const sourcePath = relativePath.length > 0 ? relativePath : file.name.trim();
|
||||
return sourcePath.replace(/\\/gu, "/");
|
||||
}
|
||||
function createAudioContext() {
|
||||
const AudioContextConstructor = globalThis.AudioContext ??
|
||||
globalThis.webkitAudioContext;
|
||||
if (AudioContextConstructor === undefined) {
|
||||
throw new Error("Audio context is unavailable in this browser environment.");
|
||||
}
|
||||
return new AudioContextConstructor();
|
||||
}
|
||||
async function decodeAudioBuffer(bytes) {
|
||||
const audioContext = createAudioContext();
|
||||
try {
|
||||
return await audioContext.decodeAudioData(bytes.slice(0));
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(getErrorDetail(error));
|
||||
}
|
||||
finally {
|
||||
await audioContext.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
function extractAudioAssetMetadata(buffer) {
|
||||
if (!Number.isFinite(buffer.duration) || buffer.duration <= 0) {
|
||||
throw new Error("Imported audio assets must have measurable duration.");
|
||||
}
|
||||
return {
|
||||
kind: "audio",
|
||||
durationSeconds: buffer.duration,
|
||||
channelCount: buffer.numberOfChannels,
|
||||
sampleRateHz: buffer.sampleRate,
|
||||
warnings: []
|
||||
};
|
||||
}
|
||||
function createLoadedAudioAsset(asset, buffer) {
|
||||
return {
|
||||
assetId: asset.id,
|
||||
storageKey: asset.storageKey,
|
||||
metadata: asset.metadata,
|
||||
buffer
|
||||
};
|
||||
}
|
||||
function createAudioAssetRecord(sourceName, mimeType, byteLength, metadata) {
|
||||
const assetId = createOpaqueId("asset-audio");
|
||||
return {
|
||||
id: assetId,
|
||||
kind: "audio",
|
||||
sourceName,
|
||||
mimeType,
|
||||
storageKey: createProjectAssetStorageKey(assetId),
|
||||
byteLength,
|
||||
metadata
|
||||
};
|
||||
}
|
||||
async function loadAudioAssetFromFileRecord(asset, fileRecord) {
|
||||
try {
|
||||
const buffer = await decodeAudioBuffer(fileRecord.bytes);
|
||||
return createLoadedAudioAsset(asset, buffer);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Audio asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
}
|
||||
function getStoredAudioAssetFile(asset, storedAsset) {
|
||||
const directFile = storedAsset.files[asset.sourceName];
|
||||
if (directFile !== undefined) {
|
||||
return directFile;
|
||||
}
|
||||
const storedFiles = Object.values(storedAsset.files);
|
||||
if (storedFiles.length === 1) {
|
||||
return storedFiles[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export async function importAudioAssetFromFile(file, storage) {
|
||||
const sourceName = getImportedFilePath(file);
|
||||
const mimeType = inferAudioMimeType(sourceName, file.type);
|
||||
const bytes = await file.arrayBuffer();
|
||||
let buffer;
|
||||
try {
|
||||
buffer = await decodeAudioBuffer(bytes);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Audio import failed for ${sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
const metadata = extractAudioAssetMetadata(buffer);
|
||||
const asset = createAudioAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
|
||||
const loadedAsset = createLoadedAudioAsset(asset, buffer);
|
||||
const packageRecord = {
|
||||
files: {
|
||||
[sourceName]: {
|
||||
bytes,
|
||||
mimeType
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
await storage.putAsset(asset.storageKey, packageRecord);
|
||||
return {
|
||||
asset,
|
||||
loadedAsset
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function loadAudioAssetFromStorage(storage, asset) {
|
||||
let storedAsset;
|
||||
try {
|
||||
storedAsset = await storage.getAsset(asset.storageKey);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Audio asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
if (storedAsset === null) {
|
||||
throw new Error(`Missing stored binary data for imported audio asset ${asset.sourceName}.`);
|
||||
}
|
||||
const storedAudioFile = getStoredAudioAssetFile(asset, storedAsset);
|
||||
if (storedAudioFile === null) {
|
||||
throw new Error(`Missing stored audio file for imported audio asset ${asset.sourceName}.`);
|
||||
}
|
||||
return loadAudioAssetFromFileRecord(asset, storedAudioFile);
|
||||
}
|
||||
592
src/assets/gltf-model-import.js
Normal file
592
src/assets/gltf-model-import.js
Normal file
@@ -0,0 +1,592 @@
|
||||
import { Box3, Group, Mesh } from "three";
|
||||
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
|
||||
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
|
||||
import { clone as cloneSkeleton } from "three/examples/jsm/utils/SkeletonUtils.js";
|
||||
import { createModelInstance } from "./model-instances";
|
||||
import { createProjectAssetStorageKey } from "./project-assets";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
const DRACO_DECODER_PATH = "/draco/gltf/";
|
||||
let sharedDracoLoader = null;
|
||||
function getErrorDetail(error) {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message.trim();
|
||||
}
|
||||
return "Unknown error.";
|
||||
}
|
||||
function getFileExtension(sourceName) {
|
||||
const match = /\.([^.]+)$/u.exec(sourceName.trim());
|
||||
return match === null ? "" : match[1].toLowerCase();
|
||||
}
|
||||
function inferFileMimeType(sourceName, fallbackMimeType) {
|
||||
if (fallbackMimeType.trim().length > 0 && fallbackMimeType !== "application/octet-stream") {
|
||||
return fallbackMimeType;
|
||||
}
|
||||
switch (getFileExtension(sourceName)) {
|
||||
case "bin":
|
||||
return "application/octet-stream";
|
||||
case "png":
|
||||
return "image/png";
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
return "image/jpeg";
|
||||
case "gif":
|
||||
return "image/gif";
|
||||
case "webp":
|
||||
return "image/webp";
|
||||
case "avif":
|
||||
return "image/avif";
|
||||
case "ktx2":
|
||||
return "image/ktx2";
|
||||
case "wav":
|
||||
return "audio/wav";
|
||||
case "mp3":
|
||||
return "audio/mpeg";
|
||||
case "ogg":
|
||||
return "audio/ogg";
|
||||
case "glb":
|
||||
return "model/gltf-binary";
|
||||
case "gltf":
|
||||
return "model/gltf+json";
|
||||
default:
|
||||
return fallbackMimeType.trim().length > 0 ? fallbackMimeType : "application/octet-stream";
|
||||
}
|
||||
}
|
||||
function inferModelAssetFormat(sourceName, mimeType) {
|
||||
const extension = getFileExtension(sourceName);
|
||||
if (mimeType === "model/gltf-binary" || extension === "glb") {
|
||||
return "glb";
|
||||
}
|
||||
if (mimeType === "model/gltf+json" || mimeType === "application/json" || extension === "gltf") {
|
||||
return "gltf";
|
||||
}
|
||||
throw new Error(`Unsupported model asset format for ${sourceName}. Use .glb or .gltf.`);
|
||||
}
|
||||
function inferModelMimeType(format) {
|
||||
return format === "glb" ? "model/gltf-binary" : "model/gltf+json";
|
||||
}
|
||||
function stripUrlQueryAndHash(path) {
|
||||
const queryIndex = path.search(/[?#]/u);
|
||||
return queryIndex === -1 ? path : path.slice(0, queryIndex);
|
||||
}
|
||||
function normalizeRelativePath(path) {
|
||||
const normalizedPath = stripUrlQueryAndHash(path.trim()).replace(/\\/gu, "/");
|
||||
const segments = normalizedPath.split("/");
|
||||
const resolvedSegments = [];
|
||||
for (const segment of segments) {
|
||||
if (segment === "" || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
const previousSegment = resolvedSegments.at(-1);
|
||||
if (previousSegment !== undefined && previousSegment !== "..") {
|
||||
resolvedSegments.pop();
|
||||
}
|
||||
else {
|
||||
resolvedSegments.push("..");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
resolvedSegments.push(segment);
|
||||
}
|
||||
return resolvedSegments.join("/");
|
||||
}
|
||||
function getPathDirectory(path) {
|
||||
const normalizedPath = normalizeRelativePath(path);
|
||||
const lastSlashIndex = normalizedPath.lastIndexOf("/");
|
||||
return lastSlashIndex === -1 ? "" : normalizedPath.slice(0, lastSlashIndex);
|
||||
}
|
||||
function getRelativePath(fromDirectory, targetPath) {
|
||||
const normalizedFromSegments = normalizeRelativePath(fromDirectory).split("/").filter((segment) => segment.length > 0);
|
||||
const normalizedTargetSegments = normalizeRelativePath(targetPath).split("/").filter((segment) => segment.length > 0);
|
||||
while (normalizedFromSegments.length > 0 &&
|
||||
normalizedTargetSegments.length > 0 &&
|
||||
normalizedFromSegments[0] === normalizedTargetSegments[0]) {
|
||||
normalizedFromSegments.shift();
|
||||
normalizedTargetSegments.shift();
|
||||
}
|
||||
return [...new Array(normalizedFromSegments.length).fill(".."), ...normalizedTargetSegments].join("/");
|
||||
}
|
||||
function getImportedFilePath(file) {
|
||||
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
|
||||
return normalizeRelativePath(relativePath.length > 0 ? relativePath : file.name.trim());
|
||||
}
|
||||
function createBoundingBoxFromObject(object) {
|
||||
const box = new Box3().setFromObject(object);
|
||||
if (box.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
const min = {
|
||||
x: box.min.x,
|
||||
y: box.min.y,
|
||||
z: box.min.z
|
||||
};
|
||||
const max = {
|
||||
x: box.max.x,
|
||||
y: box.max.y,
|
||||
z: box.max.z
|
||||
};
|
||||
return {
|
||||
min,
|
||||
max,
|
||||
size: {
|
||||
x: max.x - min.x,
|
||||
y: max.y - min.y,
|
||||
z: max.z - min.z
|
||||
}
|
||||
};
|
||||
}
|
||||
function collectMaterialNames(scene) {
|
||||
const names = new Set();
|
||||
scene.traverse((object) => {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
const materials = Array.isArray(maybeMesh.material) ? maybeMesh.material : [maybeMesh.material];
|
||||
for (const material of materials) {
|
||||
if (material.name.trim().length > 0) {
|
||||
names.add(material.name);
|
||||
}
|
||||
}
|
||||
});
|
||||
return [...names].sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
function collectTextureNames(parserJson) {
|
||||
const textures = parserJson.textures ?? [];
|
||||
const names = new Set();
|
||||
for (const texture of textures) {
|
||||
if (texture.name !== undefined && texture.name.trim().length > 0) {
|
||||
names.add(texture.name);
|
||||
}
|
||||
}
|
||||
return [...names].sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
function collectAnimationNames(gltf) {
|
||||
return gltf.animations
|
||||
.map((animation, index) => (animation.name.trim().length > 0 ? animation.name : `Animation ${index + 1}`))
|
||||
.sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
function countNodes(scene) {
|
||||
let count = 0;
|
||||
scene.traverse(() => {
|
||||
count += 1;
|
||||
});
|
||||
return count;
|
||||
}
|
||||
export function extractModelAssetMetadata(gltf, format) {
|
||||
gltf.scene.updateMatrixWorld(true);
|
||||
const boundingBox = createBoundingBoxFromObject(gltf.scene);
|
||||
let actualMeshCount = 0;
|
||||
gltf.scene.traverse((object) => {
|
||||
if (object.isMesh === true) {
|
||||
actualMeshCount += 1;
|
||||
}
|
||||
});
|
||||
const parserJson = gltf.parser.json;
|
||||
const materialNames = collectMaterialNames(gltf.scene);
|
||||
const textureNames = collectTextureNames(parserJson);
|
||||
const animationNames = collectAnimationNames(gltf);
|
||||
const warnings = [];
|
||||
if (boundingBox === null) {
|
||||
warnings.push("The imported model does not contain measurable geometry.");
|
||||
}
|
||||
if (actualMeshCount === 0) {
|
||||
warnings.push("The imported model does not contain any meshes.");
|
||||
}
|
||||
if (materialNames.length === 0 && (parserJson.materials?.length ?? 0) > 0) {
|
||||
for (const material of parserJson.materials ?? []) {
|
||||
if (material.name !== undefined && material.name.trim().length > 0) {
|
||||
materialNames.push(material.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: "model",
|
||||
format,
|
||||
sceneName: gltf.scene.name.trim().length > 0 ? gltf.scene.name : null,
|
||||
nodeCount: countNodes(gltf.scene),
|
||||
meshCount: actualMeshCount,
|
||||
materialNames: [...new Set(materialNames)].sort((left, right) => left.localeCompare(right)),
|
||||
textureNames,
|
||||
animationNames,
|
||||
boundingBox,
|
||||
warnings
|
||||
};
|
||||
}
|
||||
function createLoadedModelAsset(asset, template, animations) {
|
||||
return {
|
||||
assetId: asset.id,
|
||||
storageKey: asset.storageKey,
|
||||
metadata: asset.metadata,
|
||||
template,
|
||||
animations
|
||||
};
|
||||
}
|
||||
function createModelAssetRecord(sourceName, mimeType, byteLength, metadata) {
|
||||
const assetId = createOpaqueId("asset-model");
|
||||
return {
|
||||
id: assetId,
|
||||
kind: "model",
|
||||
sourceName,
|
||||
mimeType,
|
||||
storageKey: createProjectAssetStorageKey(assetId),
|
||||
byteLength,
|
||||
metadata
|
||||
};
|
||||
}
|
||||
async function loadGltfFromArrayBuffer(arrayBuffer) {
|
||||
const loader = createConfiguredGltfLoader();
|
||||
return loader.parseAsync(arrayBuffer, "");
|
||||
}
|
||||
function createConfiguredGltfLoader() {
|
||||
const loader = new GLTFLoader();
|
||||
loader.setDRACOLoader(getSharedDracoLoader());
|
||||
return loader;
|
||||
}
|
||||
function getSharedDracoLoader() {
|
||||
if (sharedDracoLoader === null) {
|
||||
sharedDracoLoader = new DRACOLoader();
|
||||
sharedDracoLoader.setDecoderPath(DRACO_DECODER_PATH);
|
||||
}
|
||||
return sharedDracoLoader;
|
||||
}
|
||||
function createDataUrlForStoredFile(file) {
|
||||
const byteArray = new Uint8Array(file.bytes);
|
||||
let binary = "";
|
||||
const chunkSize = 0x8000;
|
||||
for (let index = 0; index < byteArray.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...byteArray.subarray(index, index + chunkSize));
|
||||
}
|
||||
const base64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(file.bytes).toString("base64");
|
||||
return `data:${file.mimeType};base64,${base64}`;
|
||||
}
|
||||
function createTransientResourceUrl(file) {
|
||||
if (typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
|
||||
const objectUrl = URL.createObjectURL(new Blob([file.bytes], { type: file.mimeType }));
|
||||
return {
|
||||
url: objectUrl,
|
||||
revoke: () => {
|
||||
if (typeof URL.revokeObjectURL === "function") {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
return {
|
||||
url: createDataUrlForStoredFile(file),
|
||||
revoke: () => undefined
|
||||
};
|
||||
}
|
||||
function rewriteGltfResourceUris(gltfJson, files) {
|
||||
const dataUrlsByPath = new Map();
|
||||
const revokeUrls = [];
|
||||
const missingUris = new Set();
|
||||
const resolveUri = (uri) => {
|
||||
if (uri.startsWith("data:") || uri.startsWith("blob:")) {
|
||||
return uri;
|
||||
}
|
||||
const normalizedUri = normalizeRelativePath(uri);
|
||||
const storedFile = files[normalizedUri];
|
||||
if (storedFile === undefined) {
|
||||
return null;
|
||||
}
|
||||
const cachedDataUrl = dataUrlsByPath.get(normalizedUri);
|
||||
if (cachedDataUrl !== undefined) {
|
||||
return cachedDataUrl;
|
||||
}
|
||||
const transientResourceUrl = createTransientResourceUrl(storedFile);
|
||||
dataUrlsByPath.set(normalizedUri, transientResourceUrl.url);
|
||||
revokeUrls.push(transientResourceUrl.revoke);
|
||||
return transientResourceUrl.url;
|
||||
};
|
||||
const rewriteUri = (value) => {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
const resolvedUri = resolveUri(stripUrlQueryAndHash(value));
|
||||
if (resolvedUri === null) {
|
||||
missingUris.add(normalizeRelativePath(value));
|
||||
return value;
|
||||
}
|
||||
return resolvedUri;
|
||||
};
|
||||
const buffers = Array.isArray(gltfJson.buffers) ? gltfJson.buffers : [];
|
||||
for (const buffer of buffers) {
|
||||
if (typeof buffer.uri === "string") {
|
||||
buffer.uri = rewriteUri(buffer.uri);
|
||||
}
|
||||
}
|
||||
const images = Array.isArray(gltfJson.images) ? gltfJson.images : [];
|
||||
for (const image of images) {
|
||||
if (typeof image.uri === "string") {
|
||||
image.uri = rewriteUri(image.uri);
|
||||
}
|
||||
}
|
||||
return {
|
||||
missingUris: [...missingUris],
|
||||
revokeUrls
|
||||
};
|
||||
}
|
||||
function cloneTemplateScene(scene) {
|
||||
// Use SkeletonUtils.clone so that SkinnedMesh.skeleton.bones are remapped
|
||||
// to the cloned hierarchy. A plain scene.clone(true) leaves the bones array
|
||||
// pointing at the original loader's nodes, which are gone after parsing,
|
||||
// making every skinned mesh invisible at runtime.
|
||||
return cloneSkeleton(scene);
|
||||
}
|
||||
function cloneMaterial(material) {
|
||||
return material.clone();
|
||||
}
|
||||
function cloneMeshResources(object) {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
maybeMesh.geometry = maybeMesh.geometry.clone();
|
||||
maybeMesh.material = Array.isArray(maybeMesh.material)
|
||||
? maybeMesh.material.map((material) => cloneMaterial(material))
|
||||
: cloneMaterial(maybeMesh.material);
|
||||
}
|
||||
function disposeTexture(texture, seenTextures) {
|
||||
if (seenTextures.has(texture)) {
|
||||
return;
|
||||
}
|
||||
seenTextures.add(texture);
|
||||
texture.dispose();
|
||||
}
|
||||
function disposeMaterialResources(material, disposeTextures, seenTextures) {
|
||||
if (disposeTextures) {
|
||||
for (const value of Object.values(material)) {
|
||||
if (value === null || value === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
if (entry !== null && typeof entry === "object" && "isTexture" in entry) {
|
||||
disposeTexture(entry, seenTextures);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (typeof value === "object" && "isTexture" in value) {
|
||||
disposeTexture(value, seenTextures);
|
||||
}
|
||||
}
|
||||
}
|
||||
material.dispose();
|
||||
}
|
||||
function disposeMeshResources(object, disposeTextures, seenTextures) {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
maybeMesh.geometry.dispose();
|
||||
if (Array.isArray(maybeMesh.material)) {
|
||||
for (const material of maybeMesh.material) {
|
||||
disposeMaterialResources(material, disposeTextures, seenTextures);
|
||||
}
|
||||
}
|
||||
else {
|
||||
disposeMaterialResources(maybeMesh.material, disposeTextures, seenTextures);
|
||||
}
|
||||
}
|
||||
export function instantiateModelTemplate(template) {
|
||||
const clone = cloneSkeleton(template);
|
||||
clone.traverse(cloneMeshResources);
|
||||
return clone;
|
||||
}
|
||||
export function disposeModelTemplate(template) {
|
||||
const seenTextures = new Set();
|
||||
template.traverse((object) => {
|
||||
disposeMeshResources(object, true, seenTextures);
|
||||
});
|
||||
}
|
||||
export function disposeModelInstance(instance) {
|
||||
const seenTextures = new Set();
|
||||
instance.traverse((object) => {
|
||||
disposeMeshResources(object, false, seenTextures);
|
||||
});
|
||||
}
|
||||
async function loadModelFileSet(files) {
|
||||
if (files.length === 0) {
|
||||
throw new Error("Select a .glb or .gltf file to import.");
|
||||
}
|
||||
const modelFiles = files.filter((file) => {
|
||||
try {
|
||||
inferModelAssetFormat(file.name, file.type);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (modelFiles.length === 0) {
|
||||
throw new Error("Select a .glb or .gltf file to import.");
|
||||
}
|
||||
if (modelFiles.length > 1) {
|
||||
throw new Error("Select exactly one .glb or .gltf file and any matching sidecar resources.");
|
||||
}
|
||||
const rootFile = modelFiles[0];
|
||||
const rootSourcePath = getImportedFilePath(rootFile);
|
||||
const rootDirectory = getPathDirectory(rootSourcePath);
|
||||
const importedFiles = await Promise.all(files.map(async (file) => ({
|
||||
file,
|
||||
bytes: await file.arrayBuffer()
|
||||
})));
|
||||
const fileEntries = [];
|
||||
const packageFiles = {};
|
||||
for (const { file, bytes } of importedFiles) {
|
||||
const sourcePath = file === rootFile ? normalizeRelativePath(rootFile.name.trim()) : getRelativePath(rootDirectory, getImportedFilePath(file));
|
||||
const mimeType = inferFileMimeType(file.name, file.type);
|
||||
if (packageFiles[sourcePath] !== undefined) {
|
||||
throw new Error(`Duplicate imported file path ${sourcePath}.`);
|
||||
}
|
||||
const entry = {
|
||||
bytes,
|
||||
mimeType,
|
||||
path: sourcePath
|
||||
};
|
||||
fileEntries.push(entry);
|
||||
packageFiles[sourcePath] = {
|
||||
bytes,
|
||||
mimeType
|
||||
};
|
||||
}
|
||||
const rootEntry = fileEntries.find((entry) => entry.path === normalizeRelativePath(rootFile.name.trim()));
|
||||
if (rootEntry === undefined) {
|
||||
throw new Error(`Unable to locate the root model file ${rootFile.name}.`);
|
||||
}
|
||||
// Keep the root file's canonical storage path equal to its source name so reloads can find it directly.
|
||||
const packageRecord = {
|
||||
files: packageFiles
|
||||
};
|
||||
return {
|
||||
fileEntries,
|
||||
packageRecord,
|
||||
rootFile: rootEntry,
|
||||
totalByteLength: fileEntries.reduce((total, entry) => total + entry.bytes.byteLength, 0)
|
||||
};
|
||||
}
|
||||
async function loadGltfFromImportedModelFileSet(fileSet) {
|
||||
const rootFormat = inferModelAssetFormat(fileSet.rootFile.path, fileSet.rootFile.mimeType);
|
||||
if (rootFormat === "glb") {
|
||||
return loadGltfFromArrayBuffer(fileSet.rootFile.bytes);
|
||||
}
|
||||
const text = new TextDecoder().decode(fileSet.rootFile.bytes);
|
||||
const gltfJson = JSON.parse(text);
|
||||
const { missingUris, revokeUrls } = rewriteGltfResourceUris(gltfJson, fileSet.packageRecord.files);
|
||||
if (missingUris.length > 0) {
|
||||
for (const revokeUrl of revokeUrls) {
|
||||
revokeUrl();
|
||||
}
|
||||
throw new Error(`Missing external model resource(s): ${missingUris.join(", ")}.`);
|
||||
}
|
||||
const loader = createConfiguredGltfLoader();
|
||||
try {
|
||||
return await loader.parseAsync(JSON.stringify(gltfJson), "");
|
||||
}
|
||||
finally {
|
||||
for (const revokeUrl of revokeUrls) {
|
||||
revokeUrl();
|
||||
}
|
||||
}
|
||||
}
|
||||
function createModelAssetRecordFromFileSet(sourceName, mimeType, byteLength, metadata) {
|
||||
return createModelAssetRecord(sourceName, mimeType, byteLength, metadata);
|
||||
}
|
||||
export async function importModelAssetFromFiles(files, storage) {
|
||||
let fileSet;
|
||||
try {
|
||||
fileSet = await loadModelFileSet(files);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Model import failed: ${getErrorDetail(error)}`);
|
||||
}
|
||||
const sourceName = fileSet.rootFile.path;
|
||||
const format = inferModelAssetFormat(sourceName, fileSet.rootFile.mimeType);
|
||||
const mimeType = inferModelMimeType(format);
|
||||
let gltf;
|
||||
try {
|
||||
gltf = await loadGltfFromImportedModelFileSet(fileSet);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Model import failed for ${sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
const metadata = extractModelAssetMetadata(gltf, format);
|
||||
const asset = createModelAssetRecordFromFileSet(sourceName, mimeType, fileSet.totalByteLength, metadata);
|
||||
try {
|
||||
await storage.putAsset(asset.storageKey, fileSet.packageRecord);
|
||||
const modelInstance = createModelInstance({
|
||||
assetId: asset.id,
|
||||
name: undefined
|
||||
});
|
||||
return {
|
||||
asset,
|
||||
modelInstance,
|
||||
loadedAsset: createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations)
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function importModelAssetFromFile(file, storage) {
|
||||
return importModelAssetFromFiles([file], storage);
|
||||
}
|
||||
function getStoredModelAssetFile(asset, storedAsset) {
|
||||
const directFile = storedAsset.files[asset.sourceName];
|
||||
if (directFile !== undefined) {
|
||||
return directFile;
|
||||
}
|
||||
const storedFiles = Object.values(storedAsset.files);
|
||||
if (storedFiles.length === 1) {
|
||||
return storedFiles[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export async function loadModelAssetFromStorage(storage, asset) {
|
||||
let storedAsset;
|
||||
try {
|
||||
storedAsset = await storage.getAsset(asset.storageKey);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Model asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
if (storedAsset === null) {
|
||||
throw new Error(`Missing stored binary data for imported model asset ${asset.sourceName}.`);
|
||||
}
|
||||
const storedModelFile = getStoredModelAssetFile(asset, storedAsset);
|
||||
if (storedModelFile === null) {
|
||||
throw new Error(`Missing stored root file for imported model asset ${asset.sourceName}.`);
|
||||
}
|
||||
if (asset.metadata.format === "glb") {
|
||||
try {
|
||||
const gltf = await loadGltfFromArrayBuffer(storedModelFile.bytes);
|
||||
return createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Model asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
}
|
||||
const fileEntries = storedAsset.files;
|
||||
const rootFileBytes = storedModelFile.bytes;
|
||||
const gltfJson = JSON.parse(new TextDecoder().decode(rootFileBytes));
|
||||
const { missingUris, revokeUrls } = rewriteGltfResourceUris(gltfJson, fileEntries);
|
||||
if (missingUris.length > 0) {
|
||||
for (const revokeUrl of revokeUrls) {
|
||||
revokeUrl();
|
||||
}
|
||||
throw new Error(`Missing stored external model resource(s): ${missingUris.join(", ")}.`);
|
||||
}
|
||||
const loader = createConfiguredGltfLoader();
|
||||
try {
|
||||
const gltf = await loader.parseAsync(JSON.stringify(gltfJson), "");
|
||||
return createLoadedModelAsset(asset, cloneTemplateScene(gltf.scene), gltf.animations);
|
||||
}
|
||||
finally {
|
||||
for (const revokeUrl of revokeUrls) {
|
||||
revokeUrl();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -453,7 +453,11 @@ function rewriteGltfResourceUris(
|
||||
}
|
||||
|
||||
function cloneTemplateScene(scene: Group): Group {
|
||||
return scene.clone(true);
|
||||
// Use SkeletonUtils.clone so that SkinnedMesh.skeleton.bones are remapped
|
||||
// to the cloned hierarchy. A plain scene.clone(true) leaves the bones array
|
||||
// pointing at the original loader's nodes, which are gone after parsing,
|
||||
// making every skinned mesh invisible at runtime.
|
||||
return cloneSkeleton(scene) as Group;
|
||||
}
|
||||
|
||||
function cloneMaterial(material: Material): Material {
|
||||
|
||||
306
src/assets/image-assets.js
Normal file
306
src/assets/image-assets.js
Normal file
@@ -0,0 +1,306 @@
|
||||
import { DataTexture, EquirectangularReflectionMapping, LinearSRGBColorSpace, SRGBColorSpace, Texture } from "three";
|
||||
import { EXRLoader } from "three/examples/jsm/loaders/EXRLoader.js";
|
||||
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { createProjectAssetStorageKey } from "./project-assets";
|
||||
import {} from "./project-asset-storage";
|
||||
function getErrorDetail(error) {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message.trim();
|
||||
}
|
||||
return "Unknown error.";
|
||||
}
|
||||
function getFileExtension(sourceName) {
|
||||
const match = /\.([^.]+)$/u.exec(sourceName.trim());
|
||||
return match === null ? "" : match[1].toLowerCase();
|
||||
}
|
||||
function inferImageMimeType(sourceName, fallbackMimeType) {
|
||||
if (fallbackMimeType.trim().startsWith("image/")) {
|
||||
return fallbackMimeType.trim();
|
||||
}
|
||||
switch (getFileExtension(sourceName)) {
|
||||
case "avif":
|
||||
return "image/avif";
|
||||
case "exr":
|
||||
return "image/x-exr";
|
||||
case "gif":
|
||||
return "image/gif";
|
||||
case "hdr":
|
||||
return "image/vnd.radiance";
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
return "image/jpeg";
|
||||
case "png":
|
||||
return "image/png";
|
||||
case "svg":
|
||||
return "image/svg+xml";
|
||||
case "webp":
|
||||
return "image/webp";
|
||||
default:
|
||||
throw new Error(`Unsupported image asset format for ${sourceName}. Use a browser-supported image file or .exr/.hdr.`);
|
||||
}
|
||||
}
|
||||
function isHdrFormat(sourceName) {
|
||||
const ext = getFileExtension(sourceName);
|
||||
return ext === "exr" || ext === "hdr";
|
||||
}
|
||||
function getImportedFilePath(file) {
|
||||
const relativePath = typeof file.webkitRelativePath === "string" ? file.webkitRelativePath.trim() : "";
|
||||
const sourcePath = relativePath.length > 0 ? relativePath : file.name.trim();
|
||||
return sourcePath.replace(/\\/gu, "/");
|
||||
}
|
||||
function createDataUrlForStoredFile(file) {
|
||||
const byteArray = new Uint8Array(file.bytes);
|
||||
let binary = "";
|
||||
const chunkSize = 0x8000;
|
||||
for (let index = 0; index < byteArray.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...byteArray.subarray(index, index + chunkSize));
|
||||
}
|
||||
const base64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(file.bytes).toString("base64");
|
||||
return `data:${file.mimeType};base64,${base64}`;
|
||||
}
|
||||
function createTransientResourceUrl(file) {
|
||||
if (typeof URL.createObjectURL === "function" && typeof Blob !== "undefined") {
|
||||
const objectUrl = URL.createObjectURL(new Blob([file.bytes], { type: file.mimeType }));
|
||||
return {
|
||||
url: objectUrl,
|
||||
revoke: () => {
|
||||
if (typeof URL.revokeObjectURL === "function") {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
return {
|
||||
url: createDataUrlForStoredFile(file),
|
||||
revoke: () => undefined
|
||||
};
|
||||
}
|
||||
function loadImageElement(sourceUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const image = new Image();
|
||||
image.decoding = "async";
|
||||
image.addEventListener("load", () => {
|
||||
resolve(image);
|
||||
});
|
||||
image.addEventListener("error", () => {
|
||||
reject(new Error(`Image could not be loaded from ${sourceUrl}.`));
|
||||
});
|
||||
image.src = sourceUrl;
|
||||
});
|
||||
}
|
||||
function detectImageHasAlpha(image) {
|
||||
const canvas = document.createElement("canvas");
|
||||
const sampleWidth = Math.max(1, Math.min(64, image.naturalWidth || image.width));
|
||||
const sampleHeight = Math.max(1, Math.min(64, image.naturalHeight || image.height));
|
||||
const context = canvas.getContext("2d", {
|
||||
willReadFrequently: true
|
||||
});
|
||||
if (context === null) {
|
||||
return false;
|
||||
}
|
||||
canvas.width = sampleWidth;
|
||||
canvas.height = sampleHeight;
|
||||
context.drawImage(image, 0, 0, sampleWidth, sampleHeight);
|
||||
try {
|
||||
const pixels = context.getImageData(0, 0, sampleWidth, sampleHeight).data;
|
||||
for (let index = 3; index < pixels.length; index += 4) {
|
||||
if (pixels[index] !== 255) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function extractImageAssetMetadata(image) {
|
||||
const width = image.naturalWidth || image.width;
|
||||
const height = image.naturalHeight || image.height;
|
||||
if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
|
||||
throw new Error("Imported image assets must have measurable dimensions.");
|
||||
}
|
||||
const warnings = [];
|
||||
const aspectRatio = width / height;
|
||||
if (Math.abs(aspectRatio - 2) > 0.15) {
|
||||
warnings.push("Background images work best as a 2:1 equirectangular panorama.");
|
||||
}
|
||||
return {
|
||||
kind: "image",
|
||||
width,
|
||||
height,
|
||||
hasAlpha: detectImageHasAlpha(image),
|
||||
warnings
|
||||
};
|
||||
}
|
||||
function extractHdrTextureMetadata(texture) {
|
||||
const width = texture.image.width;
|
||||
const height = texture.image.height;
|
||||
const warnings = [];
|
||||
if (Math.abs(width / height - 2) > 0.15) {
|
||||
warnings.push("Background images work best as a 2:1 equirectangular panorama.");
|
||||
}
|
||||
return { kind: "image", width, height, hasAlpha: false, warnings };
|
||||
}
|
||||
function createImageTexture(image) {
|
||||
const texture = new Texture(image);
|
||||
texture.colorSpace = SRGBColorSpace;
|
||||
texture.mapping = EquirectangularReflectionMapping;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
function configureHdrTexture(texture) {
|
||||
// HDR/EXR data is linear — do not apply sRGB color space
|
||||
texture.colorSpace = LinearSRGBColorSpace;
|
||||
texture.mapping = EquirectangularReflectionMapping;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
function loadHdrTexture(url, sourceName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (getFileExtension(sourceName) === "exr") {
|
||||
new EXRLoader().load(url, resolve, undefined, () => {
|
||||
reject(new Error(`EXR file could not be loaded: ${sourceName}.`));
|
||||
});
|
||||
}
|
||||
else {
|
||||
new RGBELoader().load(url, resolve, undefined, () => {
|
||||
reject(new Error(`HDR file could not be loaded: ${sourceName}.`));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
function createLoadedImageAsset(asset, image, sourceUrl, revokeSourceUrl) {
|
||||
return {
|
||||
assetId: asset.id,
|
||||
storageKey: asset.storageKey,
|
||||
metadata: asset.metadata,
|
||||
texture: createImageTexture(image),
|
||||
sourceUrl,
|
||||
revokeSourceUrl
|
||||
};
|
||||
}
|
||||
function createLoadedHdrImageAsset(asset, texture, sourceUrl, revokeSourceUrl) {
|
||||
return {
|
||||
assetId: asset.id,
|
||||
storageKey: asset.storageKey,
|
||||
metadata: asset.metadata,
|
||||
texture: configureHdrTexture(texture),
|
||||
sourceUrl,
|
||||
revokeSourceUrl
|
||||
};
|
||||
}
|
||||
function createImageAssetRecord(sourceName, mimeType, byteLength, metadata) {
|
||||
const assetId = createOpaqueId("asset-image");
|
||||
return {
|
||||
id: assetId,
|
||||
kind: "image",
|
||||
sourceName,
|
||||
mimeType,
|
||||
storageKey: createProjectAssetStorageKey(assetId),
|
||||
byteLength,
|
||||
metadata
|
||||
};
|
||||
}
|
||||
function getStoredImageAssetFile(asset, storedAsset) {
|
||||
const directFile = storedAsset.files[asset.sourceName];
|
||||
if (directFile !== undefined) {
|
||||
return directFile;
|
||||
}
|
||||
const storedFiles = Object.values(storedAsset.files);
|
||||
if (storedFiles.length === 1) {
|
||||
return storedFiles[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function loadImageAssetFromFileRecord(asset, fileRecord) {
|
||||
const transientResourceUrl = createTransientResourceUrl(fileRecord);
|
||||
if (isHdrFormat(asset.sourceName)) {
|
||||
try {
|
||||
const texture = await loadHdrTexture(transientResourceUrl.url, asset.sourceName);
|
||||
return createLoadedHdrImageAsset(asset, texture, transientResourceUrl.url, transientResourceUrl.revoke);
|
||||
}
|
||||
catch (error) {
|
||||
transientResourceUrl.revoke();
|
||||
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const image = await loadImageElement(transientResourceUrl.url);
|
||||
return createLoadedImageAsset(asset, image, transientResourceUrl.url, transientResourceUrl.revoke);
|
||||
}
|
||||
catch (error) {
|
||||
transientResourceUrl.revoke();
|
||||
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
}
|
||||
export async function importBackgroundImageAssetFromFile(file, storage) {
|
||||
const sourceName = getImportedFilePath(file);
|
||||
const mimeType = inferImageMimeType(sourceName, file.type);
|
||||
const bytes = await file.arrayBuffer();
|
||||
const fileRecord = { bytes, mimeType };
|
||||
let asset;
|
||||
let loadedAsset;
|
||||
if (isHdrFormat(sourceName)) {
|
||||
const transientResourceUrl = createTransientResourceUrl(fileRecord);
|
||||
let texture;
|
||||
try {
|
||||
texture = await loadHdrTexture(transientResourceUrl.url, sourceName);
|
||||
}
|
||||
catch (error) {
|
||||
transientResourceUrl.revoke();
|
||||
throw new Error(`Image import failed for ${sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
const metadata = extractHdrTextureMetadata(texture);
|
||||
asset = createImageAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
|
||||
loadedAsset = createLoadedHdrImageAsset(asset, texture, transientResourceUrl.url, transientResourceUrl.revoke);
|
||||
}
|
||||
else {
|
||||
const transientResourceUrl = createTransientResourceUrl(fileRecord);
|
||||
let image;
|
||||
try {
|
||||
image = await loadImageElement(transientResourceUrl.url);
|
||||
}
|
||||
catch (error) {
|
||||
transientResourceUrl.revoke();
|
||||
throw new Error(`Image import failed for ${sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
const metadata = extractImageAssetMetadata(image);
|
||||
asset = createImageAssetRecord(sourceName, mimeType, bytes.byteLength, metadata);
|
||||
loadedAsset = createLoadedImageAsset(asset, image, transientResourceUrl.url, transientResourceUrl.revoke);
|
||||
}
|
||||
const packageRecord = {
|
||||
files: { [sourceName]: fileRecord }
|
||||
};
|
||||
try {
|
||||
await storage.putAsset(asset.storageKey, packageRecord);
|
||||
return { asset, loadedAsset };
|
||||
}
|
||||
catch (error) {
|
||||
disposeLoadedImageAsset(loadedAsset);
|
||||
await storage.deleteAsset(asset.storageKey).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function loadImageAssetFromStorage(storage, asset) {
|
||||
let storedAsset;
|
||||
try {
|
||||
storedAsset = await storage.getAsset(asset.storageKey);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(`Image asset reload failed for ${asset.sourceName}: ${getErrorDetail(error)}`);
|
||||
}
|
||||
if (storedAsset === null) {
|
||||
throw new Error(`Missing stored binary data for imported image asset ${asset.sourceName}.`);
|
||||
}
|
||||
const storedImageFile = getStoredImageAssetFile(asset, storedAsset);
|
||||
if (storedImageFile === null) {
|
||||
throw new Error(`Missing stored image file for imported image asset ${asset.sourceName}.`);
|
||||
}
|
||||
return loadImageAssetFromFileRecord(asset, storedImageFile);
|
||||
}
|
||||
export function disposeLoadedImageAsset(asset) {
|
||||
asset.texture.dispose();
|
||||
asset.revokeSourceUrl();
|
||||
}
|
||||
27
src/assets/model-instance-labels.js
Normal file
27
src/assets/model-instance-labels.js
Normal file
@@ -0,0 +1,27 @@
|
||||
import { getModelInstances } from "./model-instances";
|
||||
function getModelInstanceBaseLabel(modelInstance, assets) {
|
||||
if (modelInstance.name !== undefined) {
|
||||
return modelInstance.name;
|
||||
}
|
||||
const asset = assets[modelInstance.assetId];
|
||||
if (asset === undefined) {
|
||||
return "Model Instance";
|
||||
}
|
||||
return asset.sourceName;
|
||||
}
|
||||
export function getModelInstanceDisplayLabel(modelInstance, assets) {
|
||||
return getModelInstanceBaseLabel(modelInstance, assets);
|
||||
}
|
||||
export function getModelInstanceDisplayLabelById(modelInstanceId, modelInstances, assets) {
|
||||
const modelInstance = modelInstances[modelInstanceId];
|
||||
if (modelInstance === undefined) {
|
||||
return "Model Instance";
|
||||
}
|
||||
return getModelInstanceDisplayLabel(modelInstance, assets);
|
||||
}
|
||||
export function getSortedModelInstanceDisplayLabels(modelInstances, assets) {
|
||||
return getModelInstances(modelInstances).map((modelInstance) => ({
|
||||
modelInstance,
|
||||
label: getModelInstanceDisplayLabel(modelInstance, assets)
|
||||
}));
|
||||
}
|
||||
157
src/assets/model-instance-rendering.js
Normal file
157
src/assets/model-instance-rendering.js
Normal file
@@ -0,0 +1,157 @@
|
||||
import { BoxGeometry, Group, Mesh, MeshBasicMaterial } from "three";
|
||||
import { instantiateModelTemplate } from "./gltf-model-import";
|
||||
const MODEL_PLACEHOLDER_COLOR = 0x89b6ff;
|
||||
const MODEL_SELECTION_COLOR = 0xf7d2aa;
|
||||
const MODEL_PREVIEW_SHELL_OPACITY = 0.5;
|
||||
function getLocalModelBounds(asset) {
|
||||
if (asset?.kind === "model" && asset.metadata.boundingBox !== null) {
|
||||
const boundingBox = asset.metadata.boundingBox;
|
||||
return {
|
||||
center: {
|
||||
x: (boundingBox.min.x + boundingBox.max.x) * 0.5,
|
||||
y: (boundingBox.min.y + boundingBox.max.y) * 0.5,
|
||||
z: (boundingBox.min.z + boundingBox.max.z) * 0.5
|
||||
},
|
||||
size: {
|
||||
x: Math.max(0.1, Math.abs(boundingBox.max.x - boundingBox.min.x)),
|
||||
y: Math.max(0.1, Math.abs(boundingBox.max.y - boundingBox.min.y)),
|
||||
z: Math.max(0.1, Math.abs(boundingBox.max.z - boundingBox.min.z))
|
||||
}
|
||||
};
|
||||
}
|
||||
return {
|
||||
center: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
size: {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
}
|
||||
};
|
||||
}
|
||||
function createWireframeBox(size, color, opacity) {
|
||||
return new Mesh(new BoxGeometry(size.x, size.y, size.z), new MeshBasicMaterial({
|
||||
color,
|
||||
wireframe: true,
|
||||
transparent: true,
|
||||
opacity,
|
||||
depthWrite: false
|
||||
}));
|
||||
}
|
||||
function createWireframeMaterial(material) {
|
||||
const source = material;
|
||||
const opacity = typeof source.opacity === "number" ? source.opacity : 1;
|
||||
return new MeshBasicMaterial({
|
||||
color: source.color?.getHex() ?? MODEL_PLACEHOLDER_COLOR,
|
||||
wireframe: true,
|
||||
transparent: source.transparent === true || opacity < 1,
|
||||
opacity,
|
||||
depthWrite: false
|
||||
});
|
||||
}
|
||||
function applyWireframeMaterialPresentation(group) {
|
||||
group.traverse((object) => {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(maybeMesh.material)) {
|
||||
const originalMaterials = maybeMesh.material;
|
||||
maybeMesh.material = originalMaterials.map((material) => createWireframeMaterial(material));
|
||||
for (const material of originalMaterials) {
|
||||
material.dispose();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const originalMaterial = maybeMesh.material;
|
||||
maybeMesh.material = createWireframeMaterial(originalMaterial);
|
||||
originalMaterial.dispose();
|
||||
});
|
||||
}
|
||||
function disposeTexture(texture, seenTextures) {
|
||||
if (seenTextures.has(texture)) {
|
||||
return;
|
||||
}
|
||||
seenTextures.add(texture);
|
||||
texture.dispose();
|
||||
}
|
||||
function disposeMaterialResources(material, disposeTextures, seenTextures) {
|
||||
if (disposeTextures) {
|
||||
for (const value of Object.values(material)) {
|
||||
if (value === null || value === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
if (entry !== null && typeof entry === "object" && "isTexture" in entry) {
|
||||
disposeTexture(entry, seenTextures);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (typeof value === "object" && "isTexture" in value) {
|
||||
disposeTexture(value, seenTextures);
|
||||
}
|
||||
}
|
||||
}
|
||||
material.dispose();
|
||||
}
|
||||
function disposeMeshResources(object, disposeTextures, seenTextures) {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
maybeMesh.geometry.dispose();
|
||||
if (Array.isArray(maybeMesh.material)) {
|
||||
for (const material of maybeMesh.material) {
|
||||
disposeMaterialResources(material, disposeTextures, seenTextures);
|
||||
}
|
||||
}
|
||||
else {
|
||||
disposeMaterialResources(maybeMesh.material, disposeTextures, seenTextures);
|
||||
}
|
||||
}
|
||||
export function createModelInstanceRenderGroup(modelInstance, asset, loadedAsset, selected = false, previewShellColor, renderMode = "normal") {
|
||||
const bounds = getLocalModelBounds(asset);
|
||||
const group = new Group();
|
||||
group.position.set(modelInstance.position.x, modelInstance.position.y, modelInstance.position.z);
|
||||
group.rotation.set((modelInstance.rotationDegrees.x * Math.PI) / 180, (modelInstance.rotationDegrees.y * Math.PI) / 180, (modelInstance.rotationDegrees.z * Math.PI) / 180);
|
||||
group.scale.set(modelInstance.scale.x, modelInstance.scale.y, modelInstance.scale.z);
|
||||
group.userData.modelInstanceId = modelInstance.id;
|
||||
group.userData.assetId = modelInstance.assetId;
|
||||
if (loadedAsset !== undefined) {
|
||||
const instantiatedModel = instantiateModelTemplate(loadedAsset.template);
|
||||
if (renderMode === "wireframe") {
|
||||
applyWireframeMaterialPresentation(instantiatedModel);
|
||||
}
|
||||
group.add(instantiatedModel);
|
||||
}
|
||||
else {
|
||||
const placeholder = createWireframeBox(bounds.size, previewShellColor ?? MODEL_PLACEHOLDER_COLOR, previewShellColor === undefined ? 0.28 : MODEL_PREVIEW_SHELL_OPACITY);
|
||||
placeholder.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
placeholder.userData.shadowIgnored = true;
|
||||
group.add(placeholder);
|
||||
}
|
||||
if (loadedAsset !== undefined && previewShellColor !== undefined) {
|
||||
const previewShell = createWireframeBox(bounds.size, previewShellColor, MODEL_PREVIEW_SHELL_OPACITY);
|
||||
previewShell.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
previewShell.userData.shadowIgnored = true;
|
||||
group.add(previewShell);
|
||||
}
|
||||
if (selected) {
|
||||
const selectionShell = createWireframeBox(bounds.size, MODEL_SELECTION_COLOR, 0.8);
|
||||
selectionShell.position.set(bounds.center.x, bounds.center.y, bounds.center.z);
|
||||
selectionShell.userData.shadowIgnored = true;
|
||||
group.add(selectionShell);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
export function disposeModelInstance(instance) {
|
||||
const seenTextures = new Set();
|
||||
instance.traverse((object) => {
|
||||
disposeMeshResources(object, false, seenTextures);
|
||||
});
|
||||
}
|
||||
144
src/assets/model-instances.js
Normal file
144
src/assets/model-instances.js
Normal file
@@ -0,0 +1,144 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
export const MODEL_INSTANCE_COLLISION_MODES = ["none", "terrain", "static", "dynamic", "simple"];
|
||||
export const DEFAULT_MODEL_INSTANCE_POSITION = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_MODEL_INSTANCE_ROTATION_DEGREES = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_MODEL_INSTANCE_SCALE = {
|
||||
x: 1,
|
||||
y: 1,
|
||||
z: 1
|
||||
};
|
||||
export const DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS = {
|
||||
mode: "none",
|
||||
visible: false
|
||||
};
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function areVec3Equal(left, right) {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
export function isModelInstanceCollisionMode(value) {
|
||||
return MODEL_INSTANCE_COLLISION_MODES.includes(value);
|
||||
}
|
||||
export function createModelInstanceCollisionSettings(overrides = {}) {
|
||||
const mode = overrides.mode ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS.mode;
|
||||
if (!isModelInstanceCollisionMode(mode)) {
|
||||
throw new Error("Model instance collision mode must be a supported value.");
|
||||
}
|
||||
const visible = overrides.visible ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS.visible;
|
||||
if (typeof visible !== "boolean") {
|
||||
throw new Error("Model instance collision visibility must be a boolean.");
|
||||
}
|
||||
return {
|
||||
mode,
|
||||
visible
|
||||
};
|
||||
}
|
||||
export function cloneModelInstanceCollisionSettings(settings) {
|
||||
return createModelInstanceCollisionSettings(settings);
|
||||
}
|
||||
export function areModelInstanceCollisionSettingsEqual(left, right) {
|
||||
return left.mode === right.mode && left.visible === right.visible;
|
||||
}
|
||||
export function normalizeModelInstanceName(name) {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
}
|
||||
const trimmedName = name.trim();
|
||||
return trimmedName.length === 0 ? undefined : trimmedName;
|
||||
}
|
||||
function assertFiniteVec3(vector, label) {
|
||||
if (!Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z)) {
|
||||
throw new Error(`${label} must be finite on every axis.`);
|
||||
}
|
||||
}
|
||||
function assertPositiveFiniteVec3(vector, label) {
|
||||
assertFiniteVec3(vector, label);
|
||||
if (vector.x <= 0 || vector.y <= 0 || vector.z <= 0) {
|
||||
throw new Error(`${label} must remain positive on every axis.`);
|
||||
}
|
||||
}
|
||||
export function createModelInstance(overrides) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_MODEL_INSTANCE_POSITION);
|
||||
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_MODEL_INSTANCE_ROTATION_DEGREES);
|
||||
const scale = cloneVec3(overrides.scale ?? DEFAULT_MODEL_INSTANCE_SCALE);
|
||||
const collision = cloneModelInstanceCollisionSettings(overrides.collision ?? DEFAULT_MODEL_INSTANCE_COLLISION_SETTINGS);
|
||||
if (overrides.assetId.trim().length === 0) {
|
||||
throw new Error("Model instance assetId must be a non-empty string.");
|
||||
}
|
||||
assertFiniteVec3(position, "Model instance position");
|
||||
assertFiniteVec3(rotationDegrees, "Model instance rotation");
|
||||
assertPositiveFiniteVec3(scale, "Model instance scale");
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("model-instance"),
|
||||
kind: "modelInstance",
|
||||
assetId: overrides.assetId,
|
||||
name: normalizeModelInstanceName(overrides.name),
|
||||
position,
|
||||
rotationDegrees,
|
||||
scale,
|
||||
collision,
|
||||
animationClipName: overrides.animationClipName,
|
||||
animationAutoplay: overrides.animationAutoplay
|
||||
};
|
||||
}
|
||||
export function createModelInstancePlacementPosition(asset, anchor) {
|
||||
const boundingBox = asset?.metadata.boundingBox;
|
||||
if (anchor !== null) {
|
||||
const floorOffset = boundingBox === null || boundingBox === undefined ? 0 : -boundingBox.min.y;
|
||||
return {
|
||||
x: anchor.x,
|
||||
y: anchor.y + floorOffset,
|
||||
z: anchor.z
|
||||
};
|
||||
}
|
||||
return {
|
||||
x: DEFAULT_MODEL_INSTANCE_POSITION.x,
|
||||
y: boundingBox === null || boundingBox === undefined ? DEFAULT_MODEL_INSTANCE_POSITION.y : Math.max(DEFAULT_MODEL_INSTANCE_POSITION.y, -boundingBox.min.y),
|
||||
z: DEFAULT_MODEL_INSTANCE_POSITION.z
|
||||
};
|
||||
}
|
||||
export function cloneModelInstance(instance) {
|
||||
return createModelInstance(instance);
|
||||
}
|
||||
export function areModelInstancesEqual(left, right) {
|
||||
return (left.id === right.id &&
|
||||
left.kind === right.kind &&
|
||||
left.assetId === right.assetId &&
|
||||
left.name === right.name &&
|
||||
areVec3Equal(left.position, right.position) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.scale, right.scale) &&
|
||||
areModelInstanceCollisionSettingsEqual(left.collision, right.collision) &&
|
||||
left.animationClipName === right.animationClipName &&
|
||||
left.animationAutoplay === right.animationAutoplay);
|
||||
}
|
||||
export function compareModelInstances(left, right) {
|
||||
if (left.assetId !== right.assetId) {
|
||||
return left.assetId.localeCompare(right.assetId);
|
||||
}
|
||||
const leftName = left.name ?? "";
|
||||
const rightName = right.name ?? "";
|
||||
if (leftName !== rightName) {
|
||||
return leftName.localeCompare(rightName);
|
||||
}
|
||||
return left.id.localeCompare(right.id);
|
||||
}
|
||||
export function getModelInstances(modelInstances) {
|
||||
return Object.values(modelInstances).sort(compareModelInstances);
|
||||
}
|
||||
export function getModelInstanceKindLabel() {
|
||||
return "Model Instance";
|
||||
}
|
||||
177
src/assets/project-asset-storage.js
Normal file
177
src/assets/project-asset-storage.js
Normal file
@@ -0,0 +1,177 @@
|
||||
const PROJECT_ASSET_DATABASE_NAME = "webeditor3d-project-assets";
|
||||
const PROJECT_ASSET_DATABASE_VERSION = 1;
|
||||
const PROJECT_ASSET_OBJECT_STORE_NAME = "assets";
|
||||
function cloneArrayBuffer(bytes) {
|
||||
return bytes.slice(0);
|
||||
}
|
||||
function cloneFileRecord(file) {
|
||||
return {
|
||||
bytes: cloneArrayBuffer(file.bytes),
|
||||
mimeType: file.mimeType
|
||||
};
|
||||
}
|
||||
export function cloneProjectAssetStorageRecord(record) {
|
||||
const files = {};
|
||||
for (const [path, file] of Object.entries(record.files)) {
|
||||
files[path] = cloneFileRecord(file);
|
||||
}
|
||||
return {
|
||||
files
|
||||
};
|
||||
}
|
||||
function isObject(value) {
|
||||
return value !== null && typeof value === "object";
|
||||
}
|
||||
function isLegacyProjectAssetStorageRecord(value) {
|
||||
return (isObject(value) &&
|
||||
value.bytes instanceof ArrayBuffer &&
|
||||
typeof value.mimeType === "string");
|
||||
}
|
||||
function isProjectAssetStoragePackageRecord(value) {
|
||||
if (!isObject(value) || !isObject(value.files)) {
|
||||
return false;
|
||||
}
|
||||
return Object.values(value.files).every((entry) => {
|
||||
return (isObject(entry) &&
|
||||
entry.bytes instanceof ArrayBuffer &&
|
||||
typeof entry.mimeType === "string");
|
||||
});
|
||||
}
|
||||
function normalizeStoredAssetRecord(storageKey, value) {
|
||||
if (isProjectAssetStoragePackageRecord(value)) {
|
||||
return cloneProjectAssetStorageRecord(value);
|
||||
}
|
||||
if (isLegacyProjectAssetStorageRecord(value)) {
|
||||
return {
|
||||
files: {
|
||||
[storageKey]: cloneFileRecord(value)
|
||||
}
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getErrorDetail(error) {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message.trim();
|
||||
}
|
||||
return "Unknown error.";
|
||||
}
|
||||
function formatDiagnostic(prefix, error) {
|
||||
return `${prefix} ${getErrorDetail(error)}`;
|
||||
}
|
||||
function promisifyRequest(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.addEventListener("success", () => {
|
||||
resolve(request.result);
|
||||
});
|
||||
request.addEventListener("error", () => {
|
||||
reject(request.error ?? new Error("IndexedDB request failed."));
|
||||
});
|
||||
});
|
||||
}
|
||||
function openIndexedDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(PROJECT_ASSET_DATABASE_NAME, PROJECT_ASSET_DATABASE_VERSION);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
const database = request.result;
|
||||
if (!database.objectStoreNames.contains(PROJECT_ASSET_OBJECT_STORE_NAME)) {
|
||||
database.createObjectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
|
||||
}
|
||||
});
|
||||
request.addEventListener("success", () => {
|
||||
resolve(request.result);
|
||||
});
|
||||
request.addEventListener("error", () => {
|
||||
reject(request.error ?? new Error("IndexedDB open failed."));
|
||||
});
|
||||
});
|
||||
}
|
||||
class IndexedDbProjectAssetStorage {
|
||||
databasePromise;
|
||||
constructor(databasePromise) {
|
||||
this.databasePromise = databasePromise;
|
||||
}
|
||||
async withStore(mode, callback) {
|
||||
const database = await this.databasePromise;
|
||||
const transaction = database.transaction(PROJECT_ASSET_OBJECT_STORE_NAME, mode);
|
||||
const store = transaction.objectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
|
||||
const result = await promisifyRequest(callback(store));
|
||||
await new Promise((resolve, reject) => {
|
||||
transaction.addEventListener("complete", () => resolve());
|
||||
transaction.addEventListener("error", () => reject(transaction.error ?? new Error("IndexedDB transaction failed.")));
|
||||
transaction.addEventListener("abort", () => reject(transaction.error ?? new Error("IndexedDB transaction aborted.")));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
async getAsset(storageKey) {
|
||||
const database = await this.databasePromise;
|
||||
const transaction = database.transaction(PROJECT_ASSET_OBJECT_STORE_NAME, "readonly");
|
||||
const store = transaction.objectStore(PROJECT_ASSET_OBJECT_STORE_NAME);
|
||||
const result = await promisifyRequest(store.get(storageKey));
|
||||
return normalizeStoredAssetRecord(storageKey, result);
|
||||
}
|
||||
async putAsset(storageKey, asset) {
|
||||
await this.withStore("readwrite", (store) => store.put(cloneProjectAssetStorageRecord(asset), storageKey));
|
||||
}
|
||||
async deleteAsset(storageKey) {
|
||||
await this.withStore("readwrite", (store) => store.delete(storageKey));
|
||||
}
|
||||
}
|
||||
class InMemoryProjectAssetStorage {
|
||||
values = new Map();
|
||||
constructor(initialValues = {}) {
|
||||
for (const [storageKey, asset] of Object.entries(initialValues)) {
|
||||
this.values.set(storageKey, cloneStoredAsset(asset));
|
||||
}
|
||||
}
|
||||
async getAsset(storageKey) {
|
||||
const asset = this.values.get(storageKey);
|
||||
if (asset === undefined) {
|
||||
return null;
|
||||
}
|
||||
return normalizeStoredAssetRecord(storageKey, asset);
|
||||
}
|
||||
async putAsset(storageKey, asset) {
|
||||
this.values.set(storageKey, cloneProjectAssetStorageRecord(asset));
|
||||
}
|
||||
async deleteAsset(storageKey) {
|
||||
this.values.delete(storageKey);
|
||||
}
|
||||
}
|
||||
function cloneStoredAsset(asset) {
|
||||
if (isLegacyProjectAssetStorageRecord(asset)) {
|
||||
return cloneFileRecord(asset);
|
||||
}
|
||||
return cloneProjectAssetStorageRecord(asset);
|
||||
}
|
||||
export function createInMemoryProjectAssetStorage(initialValues = {}) {
|
||||
return new InMemoryProjectAssetStorage(initialValues);
|
||||
}
|
||||
export async function getBrowserProjectAssetStorageAccess() {
|
||||
if (typeof window === "undefined") {
|
||||
return {
|
||||
storage: null,
|
||||
diagnostic: null
|
||||
};
|
||||
}
|
||||
if (typeof indexedDB === "undefined") {
|
||||
return {
|
||||
storage: null,
|
||||
diagnostic: "IndexedDB is unavailable in this browser environment."
|
||||
};
|
||||
}
|
||||
try {
|
||||
const databasePromise = openIndexedDb();
|
||||
await databasePromise;
|
||||
return {
|
||||
storage: new IndexedDbProjectAssetStorage(databasePromise),
|
||||
diagnostic: null
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
storage: null,
|
||||
diagnostic: formatDiagnostic("Project asset storage could not be opened.", error)
|
||||
};
|
||||
}
|
||||
}
|
||||
100
src/assets/project-assets.js
Normal file
100
src/assets/project-assets.js
Normal file
@@ -0,0 +1,100 @@
|
||||
export const PROJECT_ASSET_KINDS = ["model", "image", "audio"];
|
||||
export function createProjectAssetStorageKey(assetId) {
|
||||
return `project-asset:${assetId}`;
|
||||
}
|
||||
export function isProjectAssetKind(value) {
|
||||
return value === "model" || value === "image" || value === "audio";
|
||||
}
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function cloneBoundingBox(boundingBox) {
|
||||
if (boundingBox === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
min: cloneVec3(boundingBox.min),
|
||||
max: cloneVec3(boundingBox.max),
|
||||
size: cloneVec3(boundingBox.size)
|
||||
};
|
||||
}
|
||||
function cloneModelAssetMetadata(metadata) {
|
||||
return {
|
||||
kind: "model",
|
||||
format: metadata.format,
|
||||
sceneName: metadata.sceneName,
|
||||
nodeCount: metadata.nodeCount,
|
||||
meshCount: metadata.meshCount,
|
||||
materialNames: [...metadata.materialNames],
|
||||
textureNames: [...metadata.textureNames],
|
||||
animationNames: [...metadata.animationNames],
|
||||
boundingBox: cloneBoundingBox(metadata.boundingBox),
|
||||
warnings: [...metadata.warnings]
|
||||
};
|
||||
}
|
||||
function cloneImageAssetMetadata(metadata) {
|
||||
return {
|
||||
kind: "image",
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
hasAlpha: metadata.hasAlpha,
|
||||
warnings: [...metadata.warnings]
|
||||
};
|
||||
}
|
||||
function cloneAudioAssetMetadata(metadata) {
|
||||
return {
|
||||
kind: "audio",
|
||||
durationSeconds: metadata.durationSeconds,
|
||||
channelCount: metadata.channelCount,
|
||||
sampleRateHz: metadata.sampleRateHz,
|
||||
warnings: [...metadata.warnings]
|
||||
};
|
||||
}
|
||||
export function cloneProjectAssetRecord(asset) {
|
||||
switch (asset.kind) {
|
||||
case "model":
|
||||
return {
|
||||
id: asset.id,
|
||||
kind: "model",
|
||||
sourceName: asset.sourceName,
|
||||
mimeType: asset.mimeType,
|
||||
storageKey: asset.storageKey,
|
||||
byteLength: asset.byteLength,
|
||||
metadata: cloneModelAssetMetadata(asset.metadata)
|
||||
};
|
||||
case "image":
|
||||
return {
|
||||
id: asset.id,
|
||||
kind: "image",
|
||||
sourceName: asset.sourceName,
|
||||
mimeType: asset.mimeType,
|
||||
storageKey: asset.storageKey,
|
||||
byteLength: asset.byteLength,
|
||||
metadata: cloneImageAssetMetadata(asset.metadata)
|
||||
};
|
||||
case "audio":
|
||||
return {
|
||||
id: asset.id,
|
||||
kind: "audio",
|
||||
sourceName: asset.sourceName,
|
||||
mimeType: asset.mimeType,
|
||||
storageKey: asset.storageKey,
|
||||
byteLength: asset.byteLength,
|
||||
metadata: cloneAudioAssetMetadata(asset.metadata)
|
||||
};
|
||||
}
|
||||
}
|
||||
export function getProjectAssetKindLabel(kind) {
|
||||
switch (kind) {
|
||||
case "model":
|
||||
return "Model";
|
||||
case "image":
|
||||
return "Image";
|
||||
case "audio":
|
||||
return "Audio";
|
||||
}
|
||||
}
|
||||
82
src/commands/brush-command-helpers.js
Normal file
82
src/commands/brush-command-helpers.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneFaceUvState } from "../document/brushes";
|
||||
export function getBoxBrushOrThrow(document, brushId) {
|
||||
const brush = document.brushes[brushId];
|
||||
if (brush === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not exist.`);
|
||||
}
|
||||
if (brush.kind !== "box") {
|
||||
throw new Error(`Brush ${brushId} is not a supported box brush.`);
|
||||
}
|
||||
return brush;
|
||||
}
|
||||
export function setSingleBrushSelection(brushId) {
|
||||
return {
|
||||
kind: "brushes",
|
||||
ids: [brushId]
|
||||
};
|
||||
}
|
||||
export function setSingleBrushFaceSelection(brushId, faceId) {
|
||||
return {
|
||||
kind: "brushFace",
|
||||
brushId,
|
||||
faceId
|
||||
};
|
||||
}
|
||||
export function setSingleBrushEdgeSelection(brushId, edgeId) {
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId,
|
||||
edgeId
|
||||
};
|
||||
}
|
||||
export function setSingleBrushVertexSelection(brushId, vertexId) {
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId,
|
||||
vertexId
|
||||
};
|
||||
}
|
||||
export function cloneSelectionForCommand(selection) {
|
||||
return cloneEditorSelection(selection);
|
||||
}
|
||||
export function replaceBrush(document, brush) {
|
||||
return {
|
||||
...document,
|
||||
brushes: {
|
||||
...document.brushes,
|
||||
[brush.id]: brush
|
||||
}
|
||||
};
|
||||
}
|
||||
export function removeBrush(document, brushId) {
|
||||
const remainingBrushes = {
|
||||
...document.brushes
|
||||
};
|
||||
delete remainingBrushes[brushId];
|
||||
return {
|
||||
...document,
|
||||
brushes: remainingBrushes
|
||||
};
|
||||
}
|
||||
export function getBoxBrushFaceOrThrow(document, brushId, faceId) {
|
||||
const brush = getBoxBrushOrThrow(document, brushId);
|
||||
const face = brush.faces[faceId];
|
||||
if (face === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not contain face ${faceId}.`);
|
||||
}
|
||||
return face;
|
||||
}
|
||||
export function replaceBoxBrushFace(document, brushId, faceId, face) {
|
||||
const brush = getBoxBrushOrThrow(document, brushId);
|
||||
return replaceBrush(document, {
|
||||
...brush,
|
||||
faces: {
|
||||
...brush.faces,
|
||||
[faceId]: {
|
||||
materialId: face.materialId,
|
||||
uv: cloneFaceUvState(face.uv)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
37
src/commands/command-history.js
Normal file
37
src/commands/command-history.js
Normal file
@@ -0,0 +1,37 @@
|
||||
export class CommandHistory {
|
||||
undoStack = [];
|
||||
redoStack = [];
|
||||
execute(command, context) {
|
||||
command.execute(context);
|
||||
this.undoStack.push(command);
|
||||
this.redoStack.length = 0;
|
||||
}
|
||||
undo(context) {
|
||||
const command = this.undoStack.pop();
|
||||
if (command === undefined) {
|
||||
return null;
|
||||
}
|
||||
command.undo(context);
|
||||
this.redoStack.push(command);
|
||||
return command;
|
||||
}
|
||||
redo(context) {
|
||||
const command = this.redoStack.pop();
|
||||
if (command === undefined) {
|
||||
return null;
|
||||
}
|
||||
command.execute(context);
|
||||
this.undoStack.push(command);
|
||||
return command;
|
||||
}
|
||||
clear() {
|
||||
this.undoStack.length = 0;
|
||||
this.redoStack.length = 0;
|
||||
}
|
||||
canUndo() {
|
||||
return this.undoStack.length > 0;
|
||||
}
|
||||
canRedo() {
|
||||
return this.redoStack.length > 0;
|
||||
}
|
||||
}
|
||||
1
src/commands/command.js
Normal file
1
src/commands/command.js
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import type { ProjectDocument, SceneDocument } from "../document/scene-document";
|
||||
|
||||
export interface CommandContext {
|
||||
getDocument(): SceneDocument;
|
||||
setDocument(document: SceneDocument): void;
|
||||
getProjectDocument(): ProjectDocument;
|
||||
setProjectDocument(document: ProjectDocument): void;
|
||||
getSelection(): EditorSelection;
|
||||
setSelection(selection: EditorSelection): void;
|
||||
getToolMode(): ToolMode;
|
||||
|
||||
200
src/commands/commit-transform-session-command.js
Normal file
200
src/commands/commit-transform-session-command.js
Normal file
@@ -0,0 +1,200 @@
|
||||
import { createMoveBoxBrushCommand } from "./move-box-brush-command";
|
||||
import { createResizeBoxBrushCommand } from "./resize-box-brush-command";
|
||||
import { createRotateBoxBrushCommand } from "./rotate-box-brush-command";
|
||||
import { createSetBoxBrushTransformCommand } from "./set-box-brush-transform-command";
|
||||
import { createUpsertEntityCommand } from "./upsert-entity-command";
|
||||
import { createUpsertModelInstanceCommand } from "./upsert-model-instance-command";
|
||||
import { createModelInstance } from "../assets/model-instances";
|
||||
import { createInteractableEntity, createPlayerStartEntity, createPointLightEntity, createSoundEmitterEntity, createSpotLightEntity, createTeleportTargetEntity, createTriggerVolumeEntity } from "../entities/entity-instances";
|
||||
import { getTransformOperationLabel } from "../core/transform-session";
|
||||
function createTransformCommandLabel(session) {
|
||||
return `${getTransformOperationLabel(session.operation)} ${session.target.kind === "brush"
|
||||
? "whitebox box"
|
||||
: session.target.kind === "brushFace"
|
||||
? "whitebox face"
|
||||
: session.target.kind === "brushEdge"
|
||||
? "whitebox edge"
|
||||
: session.target.kind === "brushVertex"
|
||||
? "whitebox vertex"
|
||||
: session.target.kind === "entity"
|
||||
? session.target.entityKind === "playerStart"
|
||||
? "player start"
|
||||
: session.target.entityKind === "pointLight"
|
||||
? "point light"
|
||||
: session.target.entityKind === "spotLight"
|
||||
? "spot light"
|
||||
: session.target.entityKind === "soundEmitter"
|
||||
? "sound emitter"
|
||||
: session.target.entityKind === "triggerVolume"
|
||||
? "trigger volume"
|
||||
: session.target.entityKind === "teleportTarget"
|
||||
? "teleport target"
|
||||
: "interactable"
|
||||
: "model instance"}`;
|
||||
}
|
||||
export function createCommitTransformSessionCommand(document, session) {
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Brush transform preview is invalid.");
|
||||
}
|
||||
switch (session.operation) {
|
||||
case "translate":
|
||||
return createMoveBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
center: session.preview.center,
|
||||
snapToGrid: false,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "rotate":
|
||||
return createRotateBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "scale":
|
||||
return createResizeBoxBrushCommand({
|
||||
brushId: session.target.brushId,
|
||||
size: session.preview.size,
|
||||
snapToGrid: false,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
case "brushFace":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox face transform preview is invalid.");
|
||||
}
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushFace",
|
||||
brushId: session.target.brushId,
|
||||
faceId: session.target.faceId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "brushEdge":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox edge transform preview is invalid.");
|
||||
}
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushEdge",
|
||||
brushId: session.target.brushId,
|
||||
edgeId: session.target.edgeId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "brushVertex":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox vertex transform preview is invalid.");
|
||||
}
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushVertex",
|
||||
brushId: session.target.brushId,
|
||||
vertexId: session.target.vertexId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "modelInstance": {
|
||||
if (session.preview.kind !== "modelInstance") {
|
||||
throw new Error("Model instance transform preview is invalid.");
|
||||
}
|
||||
const modelInstance = document.modelInstances[session.target.modelInstanceId];
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${session.target.modelInstanceId} does not exist.`);
|
||||
}
|
||||
return createUpsertModelInstanceCommand({
|
||||
modelInstance: createModelInstance({
|
||||
...modelInstance,
|
||||
position: session.preview.position,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
scale: session.preview.scale
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
case "entity": {
|
||||
if (session.preview.kind !== "entity") {
|
||||
throw new Error("Entity transform preview is invalid.");
|
||||
}
|
||||
const entity = document.entities[session.target.entityId];
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${session.target.entityId} does not exist.`);
|
||||
}
|
||||
switch (entity.kind) {
|
||||
case "pointLight":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createPointLightEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "spotLight":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSpotLightEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
direction: session.preview.rotation.kind === "direction" ? session.preview.rotation.direction : entity.direction
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "playerStart":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createPlayerStartEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
yawDegrees: session.preview.rotation.kind === "yaw" ? session.preview.rotation.yawDegrees : entity.yawDegrees
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "soundEmitter":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSoundEmitterEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "triggerVolume":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createTriggerVolumeEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "teleportTarget":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createTeleportTargetEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
yawDegrees: session.preview.rotation.kind === "yaw" ? session.preview.rotation.yawDegrees : entity.yawDegrees
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "interactable":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createInteractableEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createMoveBoxBrushCommand } from "./move-box-brush-command";
|
||||
import { createResizeBoxBrushCommand } from "./resize-box-brush-command";
|
||||
import { createRotateBoxBrushCommand } from "./rotate-box-brush-command";
|
||||
import { createSetBoxBrushTransformCommand } from "./set-box-brush-transform-command";
|
||||
import { createUpsertEntityCommand } from "./upsert-entity-command";
|
||||
import { createUpsertModelInstanceCommand } from "./upsert-model-instance-command";
|
||||
import type { EditorCommand } from "./command";
|
||||
@@ -10,6 +11,8 @@ import {
|
||||
createInteractableEntity,
|
||||
createPlayerStartEntity,
|
||||
createPointLightEntity,
|
||||
createSceneEntryEntity,
|
||||
createSceneExitEntity,
|
||||
createSoundEmitterEntity,
|
||||
createSpotLightEntity,
|
||||
createTeleportTargetEntity,
|
||||
@@ -24,6 +27,12 @@ function createTransformCommandLabel(session: ActiveTransformSession): string {
|
||||
return `${getTransformOperationLabel(session.operation)} ${
|
||||
session.target.kind === "brush"
|
||||
? "whitebox box"
|
||||
: session.target.kind === "brushFace"
|
||||
? "whitebox face"
|
||||
: session.target.kind === "brushEdge"
|
||||
? "whitebox edge"
|
||||
: session.target.kind === "brushVertex"
|
||||
? "whitebox vertex"
|
||||
: session.target.kind === "entity"
|
||||
? session.target.entityKind === "playerStart"
|
||||
? "player start"
|
||||
@@ -35,9 +44,13 @@ function createTransformCommandLabel(session: ActiveTransformSession): string {
|
||||
? "sound emitter"
|
||||
: session.target.entityKind === "triggerVolume"
|
||||
? "trigger volume"
|
||||
: session.target.entityKind === "sceneEntry"
|
||||
? "scene entry"
|
||||
: session.target.entityKind === "teleportTarget"
|
||||
? "teleport target"
|
||||
: "interactable"
|
||||
: session.target.entityKind === "interactable"
|
||||
? "interactable"
|
||||
: "scene exit"
|
||||
: "model instance"
|
||||
}`;
|
||||
}
|
||||
@@ -71,6 +84,57 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
case "brushFace":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox face transform preview is invalid.");
|
||||
}
|
||||
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushFace",
|
||||
brushId: session.target.brushId,
|
||||
faceId: session.target.faceId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "brushEdge":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox edge transform preview is invalid.");
|
||||
}
|
||||
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushEdge",
|
||||
brushId: session.target.brushId,
|
||||
edgeId: session.target.edgeId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "brushVertex":
|
||||
if (session.preview.kind !== "brush") {
|
||||
throw new Error("Whitebox vertex transform preview is invalid.");
|
||||
}
|
||||
|
||||
return createSetBoxBrushTransformCommand({
|
||||
selection: {
|
||||
kind: "brushVertex",
|
||||
brushId: session.target.brushId,
|
||||
vertexId: session.target.vertexId
|
||||
},
|
||||
center: session.preview.center,
|
||||
rotationDegrees: session.preview.rotationDegrees,
|
||||
size: session.preview.size,
|
||||
geometry: session.preview.geometry,
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "modelInstance": {
|
||||
if (session.preview.kind !== "modelInstance") {
|
||||
throw new Error("Model instance transform preview is invalid.");
|
||||
@@ -130,6 +194,18 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "sceneEntry":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSceneEntryEntity({
|
||||
...entity,
|
||||
position: session.preview.position,
|
||||
yawDegrees:
|
||||
session.preview.rotation.kind === "yaw"
|
||||
? session.preview.rotation.yawDegrees
|
||||
: entity.yawDegrees
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "soundEmitter":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSoundEmitterEntity({
|
||||
@@ -163,6 +239,14 @@ export function createCommitTransformSessionCommand(document: SceneDocument, ses
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
case "sceneExit":
|
||||
return createUpsertEntityCommand({
|
||||
entity: createSceneExitEntity({
|
||||
...entity,
|
||||
position: session.preview.position
|
||||
}),
|
||||
label: createTransformCommandLabel(session)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
51
src/commands/create-box-brush-command.js
Normal file
51
src/commands/create-box-brush-command.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import { createBoxBrush, DEFAULT_BOX_BRUSH_CENTER, DEFAULT_BOX_BRUSH_SIZE } from "../document/brushes";
|
||||
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid, snapVec3ToGrid } from "../geometry/grid-snapping";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneSelectionForCommand, removeBrush, setSingleBrushSelection } from "./brush-command-helpers";
|
||||
export function createCreateBoxBrushCommand(options = {}) {
|
||||
const snapToGrid = options.snapToGrid ?? true;
|
||||
const brush = createBoxBrush({
|
||||
center: snapToGrid === false
|
||||
? options.center ?? DEFAULT_BOX_BRUSH_CENTER
|
||||
: snapVec3ToGrid(options.center ?? DEFAULT_BOX_BRUSH_CENTER, options.gridSize ?? DEFAULT_GRID_SIZE),
|
||||
size: snapToGrid === false
|
||||
? options.size ?? DEFAULT_BOX_BRUSH_SIZE
|
||||
: snapPositiveSizeToGrid(options.size ?? DEFAULT_BOX_BRUSH_SIZE, options.gridSize ?? DEFAULT_GRID_SIZE)
|
||||
});
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Create box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (currentDocument.brushes[brush.id] !== undefined) {
|
||||
throw new Error(`Box brush ${brush.id} already exists.`);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: {
|
||||
...currentDocument.brushes,
|
||||
[brush.id]: brush
|
||||
}
|
||||
});
|
||||
context.setSelection(setSingleBrushSelection(brush.id));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
context.setDocument(removeBrush(context.getDocument(), brush.id));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
69
src/commands/create-scene-command.ts
Normal file
69
src/commands/create-scene-command.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import {
|
||||
createEmptyProjectScene,
|
||||
type ProjectDocument
|
||||
} from "../document/scene-document";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
function createUniqueSceneName(existingNames: string[]): string {
|
||||
const normalizedNames = new Set(
|
||||
existingNames.map((name) => name.trim().toLowerCase())
|
||||
);
|
||||
let suffix = existingNames.length + 1;
|
||||
|
||||
while (normalizedNames.has(`scene ${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
return `Scene ${suffix}`;
|
||||
}
|
||||
|
||||
export function createCreateSceneCommand(): EditorCommand {
|
||||
const createdSceneId = createOpaqueId("scene");
|
||||
let createdSceneName: string | null = null;
|
||||
let previousProjectDocumentSerialized: string | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Create scene",
|
||||
execute(context) {
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
|
||||
if (previousProjectDocumentSerialized === null) {
|
||||
previousProjectDocumentSerialized = JSON.stringify(currentProjectDocument);
|
||||
}
|
||||
|
||||
if (createdSceneName === null) {
|
||||
createdSceneName = createUniqueSceneName(
|
||||
Object.values(currentProjectDocument.scenes).map((scene) => scene.name)
|
||||
);
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
activeSceneId: createdSceneId,
|
||||
scenes: {
|
||||
...currentProjectDocument.scenes,
|
||||
[createdSceneId]: createEmptyProjectScene({
|
||||
id: createdSceneId,
|
||||
name: createdSceneName
|
||||
})
|
||||
}
|
||||
});
|
||||
context.setSelection({ kind: "none" });
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousProjectDocumentSerialized === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.setProjectDocument(
|
||||
JSON.parse(previousProjectDocumentSerialized) as ProjectDocument
|
||||
);
|
||||
context.setSelection({ kind: "none" });
|
||||
context.setToolMode("select");
|
||||
}
|
||||
};
|
||||
}
|
||||
59
src/commands/delete-box-brush-command.js
Normal file
59
src/commands/delete-box-brush-command.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneBoxBrush } from "../document/brushes";
|
||||
import { cloneSelectionForCommand, removeBrush } from "./brush-command-helpers";
|
||||
function selectionIncludesBrush(selection, brushId) {
|
||||
return ((selection.kind === "brushes" && selection.ids.includes(brushId)) ||
|
||||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
|
||||
selection.brushId === brushId));
|
||||
}
|
||||
export function createDeleteBoxBrushCommand(brushId) {
|
||||
let previousBrush = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentBrush = currentDocument.brushes[brushId];
|
||||
if (currentBrush === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not exist.`);
|
||||
}
|
||||
if (previousBrush === null) {
|
||||
previousBrush = cloneBoxBrush(currentBrush);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument(removeBrush(currentDocument, brushId));
|
||||
if (selectionIncludesBrush(context.getSelection(), brushId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousBrush === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: {
|
||||
...currentDocument.brushes,
|
||||
[previousBrush.id]: cloneBoxBrush(previousBrush)
|
||||
}
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
64
src/commands/delete-entity-command.js
Normal file
64
src/commands/delete-entity-command.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneEntityInstance } from "../entities/entity-instances";
|
||||
function selectionIncludesEntity(selection, entityId) {
|
||||
return selection.kind === "entities" && selection.ids.includes(entityId);
|
||||
}
|
||||
export function createDeleteEntityCommand(entityId) {
|
||||
let previousEntity = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete entity",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentEntity = currentDocument.entities[entityId];
|
||||
if (currentEntity === undefined) {
|
||||
throw new Error(`Entity ${entityId} does not exist.`);
|
||||
}
|
||||
if (previousEntity === null) {
|
||||
previousEntity = cloneEntityInstance(currentEntity);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
const nextEntities = {
|
||||
...currentDocument.entities
|
||||
};
|
||||
delete nextEntities[entityId];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: nextEntities
|
||||
});
|
||||
if (selectionIncludesEntity(context.getSelection(), entityId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousEntity === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[previousEntity.id]: cloneEntityInstance(previousEntity)
|
||||
}
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
40
src/commands/delete-interaction-link-command.js
Normal file
40
src/commands/delete-interaction-link-command.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneInteractionLink } from "../interactions/interaction-links";
|
||||
export function createDeleteInteractionLinkCommand(linkId) {
|
||||
let previousLink = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete interaction link",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentLink = currentDocument.interactionLinks[linkId];
|
||||
if (currentLink === undefined) {
|
||||
throw new Error(`Interaction link ${linkId} does not exist.`);
|
||||
}
|
||||
if (previousLink === null) {
|
||||
previousLink = cloneInteractionLink(currentLink);
|
||||
}
|
||||
const nextInteractionLinks = {
|
||||
...currentDocument.interactionLinks
|
||||
};
|
||||
delete nextInteractionLinks[linkId];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
interactionLinks: nextInteractionLinks
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
if (previousLink === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
interactionLinks: {
|
||||
...currentDocument.interactionLinks,
|
||||
[previousLink.id]: cloneInteractionLink(previousLink)
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
64
src/commands/delete-model-instance-command.js
Normal file
64
src/commands/delete-model-instance-command.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneModelInstance } from "../assets/model-instances";
|
||||
function selectionIncludesModelInstance(selection, modelInstanceId) {
|
||||
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
|
||||
}
|
||||
export function createDeleteModelInstanceCommand(modelInstanceId) {
|
||||
let previousModelInstance = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Delete model instance",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentModelInstance = currentDocument.modelInstances[modelInstanceId];
|
||||
if (currentModelInstance === undefined) {
|
||||
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
|
||||
}
|
||||
if (previousModelInstance === null) {
|
||||
previousModelInstance = cloneModelInstance(currentModelInstance);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
delete nextModelInstances[modelInstanceId];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
if (selectionIncludesModelInstance(context.getSelection(), modelInstanceId)) {
|
||||
context.setSelection({
|
||||
kind: "none"
|
||||
});
|
||||
}
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousModelInstance === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[previousModelInstance.id]: cloneModelInstance(previousModelInstance)
|
||||
}
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
237
src/commands/duplicate-selection-command.js
Normal file
237
src/commands/duplicate-selection-command.js
Normal file
@@ -0,0 +1,237 @@
|
||||
import { cloneModelInstance } from "../assets/model-instances";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneBoxBrush } from "../document/brushes";
|
||||
import { cloneEntityInstance } from "../entities/entity-instances";
|
||||
|
||||
function duplicateBrush(brush) {
|
||||
const duplicatedBrush = cloneBoxBrush(brush);
|
||||
duplicatedBrush.id = createOpaqueId("brush");
|
||||
return duplicatedBrush;
|
||||
}
|
||||
|
||||
function duplicateEntity(entity) {
|
||||
const duplicatedEntity = cloneEntityInstance(entity);
|
||||
duplicatedEntity.id = createOpaqueId(`entity-${duplicatedEntity.kind}`);
|
||||
return duplicatedEntity;
|
||||
}
|
||||
|
||||
function duplicateModelInstance(modelInstance) {
|
||||
const duplicatedModelInstance = cloneModelInstance(modelInstance);
|
||||
duplicatedModelInstance.id = createOpaqueId("model-instance");
|
||||
return duplicatedModelInstance;
|
||||
}
|
||||
|
||||
function resolveDuplicatableBrushIds(selection) {
|
||||
switch (selection.kind) {
|
||||
case "brushes":
|
||||
return selection.ids;
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return [selection.brushId];
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function createDuplicateSelectionResult(currentDocument, selection) {
|
||||
const duplicatableBrushIds = resolveDuplicatableBrushIds(selection);
|
||||
|
||||
if (duplicatableBrushIds !== null) {
|
||||
if (duplicatableBrushIds.length === 0) {
|
||||
throw new Error("Select at least one whitebox solid to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedBrushes = duplicatableBrushIds.map((brushId) => {
|
||||
const sourceBrush = currentDocument.brushes[brushId];
|
||||
|
||||
if (sourceBrush === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not exist.`);
|
||||
}
|
||||
|
||||
if (sourceBrush.kind !== "box") {
|
||||
throw new Error(`Brush ${brushId} is not a supported box brush.`);
|
||||
}
|
||||
|
||||
return duplicateBrush(sourceBrush);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "brushes",
|
||||
ids: duplicatedBrushes.map((brush) => brush.id)
|
||||
},
|
||||
brushes: duplicatedBrushes,
|
||||
entities: null,
|
||||
modelInstances: null
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "entities") {
|
||||
if (selection.ids.length === 0) {
|
||||
throw new Error("Select at least one entity to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedEntities = selection.ids.map((entityId) => {
|
||||
const sourceEntity = currentDocument.entities[entityId];
|
||||
|
||||
if (sourceEntity === undefined) {
|
||||
throw new Error(`Entity ${entityId} does not exist.`);
|
||||
}
|
||||
|
||||
return duplicateEntity(sourceEntity);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "entities",
|
||||
ids: duplicatedEntities.map((entity) => entity.id)
|
||||
},
|
||||
brushes: null,
|
||||
entities: duplicatedEntities,
|
||||
modelInstances: null
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "modelInstances") {
|
||||
if (selection.ids.length === 0) {
|
||||
throw new Error("Select at least one model instance to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedModelInstances = selection.ids.map((modelInstanceId) => {
|
||||
const sourceModelInstance = currentDocument.modelInstances[modelInstanceId];
|
||||
|
||||
if (sourceModelInstance === undefined) {
|
||||
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
return duplicateModelInstance(sourceModelInstance);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "modelInstances",
|
||||
ids: duplicatedModelInstances.map((modelInstance) => modelInstance.id)
|
||||
},
|
||||
brushes: null,
|
||||
entities: null,
|
||||
modelInstances: duplicatedModelInstances
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("Selection must contain whitebox solids, entities, or model instances to duplicate.");
|
||||
}
|
||||
|
||||
export function createDuplicateSelectionCommand() {
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
let duplicateSelectionResult = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Duplicate selection",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
if (duplicateSelectionResult === null) {
|
||||
duplicateSelectionResult = createDuplicateSelectionResult(currentDocument, context.getSelection());
|
||||
}
|
||||
|
||||
if (duplicateSelectionResult.brushes !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: {
|
||||
...currentDocument.brushes,
|
||||
...Object.fromEntries(duplicateSelectionResult.brushes.map((brush) => [brush.id, cloneBoxBrush(brush)]))
|
||||
}
|
||||
});
|
||||
} else if (duplicateSelectionResult.entities !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
...Object.fromEntries(duplicateSelectionResult.entities.map((entity) => [entity.id, cloneEntityInstance(entity)]))
|
||||
}
|
||||
});
|
||||
} else if (duplicateSelectionResult.modelInstances !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
...Object.fromEntries(
|
||||
duplicateSelectionResult.modelInstances.map((modelInstance) => [modelInstance.id, cloneModelInstance(modelInstance)])
|
||||
)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
context.setSelection(cloneEditorSelection(duplicateSelectionResult.selection));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (duplicateSelectionResult === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
if (duplicateSelectionResult.brushes !== null) {
|
||||
const nextBrushes = {
|
||||
...currentDocument.brushes
|
||||
};
|
||||
|
||||
for (const duplicatedBrush of duplicateSelectionResult.brushes) {
|
||||
delete nextBrushes[duplicatedBrush.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: nextBrushes
|
||||
});
|
||||
} else if (duplicateSelectionResult.entities !== null) {
|
||||
const nextEntities = {
|
||||
...currentDocument.entities
|
||||
};
|
||||
|
||||
for (const duplicatedEntity of duplicateSelectionResult.entities) {
|
||||
delete nextEntities[duplicatedEntity.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: nextEntities
|
||||
});
|
||||
} else if (duplicateSelectionResult.modelInstances !== null) {
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
|
||||
for (const duplicatedModelInstance of duplicateSelectionResult.modelInstances) {
|
||||
delete nextModelInstances[duplicatedModelInstance.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
}
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
248
src/commands/duplicate-selection-command.ts
Normal file
248
src/commands/duplicate-selection-command.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
import { cloneModelInstance, type ModelInstance } from "../assets/model-instances";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection, type EditorSelection } from "../core/selection";
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { cloneBoxBrush, type BoxBrush } from "../document/brushes";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import { cloneEntityInstance, type EntityInstance } from "../entities/entity-instances";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface DuplicateSelectionResult {
|
||||
selection: EditorSelection;
|
||||
brushes: BoxBrush[] | null;
|
||||
entities: EntityInstance[] | null;
|
||||
modelInstances: ModelInstance[] | null;
|
||||
}
|
||||
|
||||
function duplicateBrush(brush: BoxBrush): BoxBrush {
|
||||
const duplicatedBrush = cloneBoxBrush(brush);
|
||||
duplicatedBrush.id = createOpaqueId("brush");
|
||||
return duplicatedBrush;
|
||||
}
|
||||
|
||||
function duplicateEntity(entity: EntityInstance): EntityInstance {
|
||||
const duplicatedEntity = cloneEntityInstance(entity);
|
||||
duplicatedEntity.id = createOpaqueId(`entity-${duplicatedEntity.kind}`);
|
||||
return duplicatedEntity;
|
||||
}
|
||||
|
||||
function duplicateModelInstance(modelInstance: ModelInstance): ModelInstance {
|
||||
const duplicatedModelInstance = cloneModelInstance(modelInstance);
|
||||
duplicatedModelInstance.id = createOpaqueId("model-instance");
|
||||
return duplicatedModelInstance;
|
||||
}
|
||||
|
||||
function resolveDuplicatableBrushIds(selection: EditorSelection): string[] | null {
|
||||
switch (selection.kind) {
|
||||
case "brushes":
|
||||
return selection.ids;
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return [selection.brushId];
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function createDuplicateSelectionResult(currentDocument: SceneDocument, selection: EditorSelection): DuplicateSelectionResult {
|
||||
const duplicatableBrushIds = resolveDuplicatableBrushIds(selection);
|
||||
|
||||
if (duplicatableBrushIds !== null) {
|
||||
if (duplicatableBrushIds.length === 0) {
|
||||
throw new Error("Select at least one whitebox solid to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedBrushes = duplicatableBrushIds.map((brushId) => {
|
||||
const sourceBrush = currentDocument.brushes[brushId];
|
||||
|
||||
if (sourceBrush === undefined) {
|
||||
throw new Error(`Box brush ${brushId} does not exist.`);
|
||||
}
|
||||
|
||||
if (sourceBrush.kind !== "box") {
|
||||
throw new Error(`Brush ${brushId} is not a supported box brush.`);
|
||||
}
|
||||
|
||||
return duplicateBrush(sourceBrush);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "brushes",
|
||||
ids: duplicatedBrushes.map((brush) => brush.id)
|
||||
},
|
||||
brushes: duplicatedBrushes,
|
||||
entities: null,
|
||||
modelInstances: null
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "entities") {
|
||||
if (selection.ids.length === 0) {
|
||||
throw new Error("Select at least one entity to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedEntities = selection.ids.map((entityId) => {
|
||||
const sourceEntity = currentDocument.entities[entityId];
|
||||
|
||||
if (sourceEntity === undefined) {
|
||||
throw new Error(`Entity ${entityId} does not exist.`);
|
||||
}
|
||||
|
||||
return duplicateEntity(sourceEntity);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "entities",
|
||||
ids: duplicatedEntities.map((entity) => entity.id)
|
||||
},
|
||||
brushes: null,
|
||||
entities: duplicatedEntities,
|
||||
modelInstances: null
|
||||
};
|
||||
}
|
||||
|
||||
if (selection.kind === "modelInstances") {
|
||||
if (selection.ids.length === 0) {
|
||||
throw new Error("Select at least one model instance to duplicate.");
|
||||
}
|
||||
|
||||
const duplicatedModelInstances = selection.ids.map((modelInstanceId) => {
|
||||
const sourceModelInstance = currentDocument.modelInstances[modelInstanceId];
|
||||
|
||||
if (sourceModelInstance === undefined) {
|
||||
throw new Error(`Model instance ${modelInstanceId} does not exist.`);
|
||||
}
|
||||
|
||||
return duplicateModelInstance(sourceModelInstance);
|
||||
});
|
||||
|
||||
return {
|
||||
selection: {
|
||||
kind: "modelInstances",
|
||||
ids: duplicatedModelInstances.map((modelInstance) => modelInstance.id)
|
||||
},
|
||||
brushes: null,
|
||||
entities: null,
|
||||
modelInstances: duplicatedModelInstances
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("Selection must contain whitebox solids, entities, or model instances to duplicate.");
|
||||
}
|
||||
|
||||
export function createDuplicateSelectionCommand(): EditorCommand {
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
let duplicateSelectionResult: DuplicateSelectionResult | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Duplicate selection",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
if (duplicateSelectionResult === null) {
|
||||
duplicateSelectionResult = createDuplicateSelectionResult(currentDocument, context.getSelection());
|
||||
}
|
||||
|
||||
if (duplicateSelectionResult.brushes !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: {
|
||||
...currentDocument.brushes,
|
||||
...Object.fromEntries(duplicateSelectionResult.brushes.map((brush) => [brush.id, cloneBoxBrush(brush)]))
|
||||
}
|
||||
});
|
||||
} else if (duplicateSelectionResult.entities !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
...Object.fromEntries(duplicateSelectionResult.entities.map((entity) => [entity.id, cloneEntityInstance(entity)]))
|
||||
}
|
||||
});
|
||||
} else if (duplicateSelectionResult.modelInstances !== null) {
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
...Object.fromEntries(
|
||||
duplicateSelectionResult.modelInstances.map((modelInstance) => [modelInstance.id, cloneModelInstance(modelInstance)])
|
||||
)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
context.setSelection(cloneEditorSelection(duplicateSelectionResult.selection));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (duplicateSelectionResult === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
|
||||
if (duplicateSelectionResult.brushes !== null) {
|
||||
const nextBrushes = {
|
||||
...currentDocument.brushes
|
||||
};
|
||||
|
||||
for (const duplicatedBrush of duplicateSelectionResult.brushes) {
|
||||
delete nextBrushes[duplicatedBrush.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
brushes: nextBrushes
|
||||
});
|
||||
} else if (duplicateSelectionResult.entities !== null) {
|
||||
const nextEntities = {
|
||||
...currentDocument.entities
|
||||
};
|
||||
|
||||
for (const duplicatedEntity of duplicateSelectionResult.entities) {
|
||||
delete nextEntities[duplicatedEntity.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: nextEntities
|
||||
});
|
||||
} else if (duplicateSelectionResult.modelInstances !== null) {
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
|
||||
for (const duplicatedModelInstance of duplicateSelectionResult.modelInstances) {
|
||||
delete nextModelInstances[duplicatedModelInstance.id];
|
||||
}
|
||||
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
}
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
33
src/commands/import-audio-asset-command.js
Normal file
33
src/commands/import-audio-asset-command.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneProjectAssetRecord } from "../assets/project-assets";
|
||||
export function createImportAudioAssetCommand(options) {
|
||||
const nextAsset = cloneProjectAssetRecord(options.asset);
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? `Import ${nextAsset.sourceName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (currentDocument.assets[nextAsset.id] !== undefined) {
|
||||
throw new Error(`Asset ${nextAsset.id} already exists.`);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: {
|
||||
...currentDocument.assets,
|
||||
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextAssets = {
|
||||
...currentDocument.assets
|
||||
};
|
||||
delete nextAssets[nextAsset.id];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: nextAssets
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
41
src/commands/import-background-image-asset-command.js
Normal file
41
src/commands/import-background-image-asset-command.js
Normal file
@@ -0,0 +1,41 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneWorldSettings } from "../document/world-settings";
|
||||
import { cloneProjectAssetRecord } from "../assets/project-assets";
|
||||
export function createImportBackgroundImageAssetCommand(options) {
|
||||
const nextAsset = cloneProjectAssetRecord(options.asset);
|
||||
const nextWorld = cloneWorldSettings(options.world);
|
||||
let previousWorld = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? `Import ${nextAsset.sourceName} as background`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (currentDocument.assets[nextAsset.id] !== undefined) {
|
||||
throw new Error(`Asset ${nextAsset.id} already exists.`);
|
||||
}
|
||||
if (previousWorld === null) {
|
||||
previousWorld = cloneWorldSettings(currentDocument.world);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: {
|
||||
...currentDocument.assets,
|
||||
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
|
||||
},
|
||||
world: cloneWorldSettings(nextWorld)
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextAssets = {
|
||||
...currentDocument.assets
|
||||
};
|
||||
delete nextAssets[nextAsset.id];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: nextAssets,
|
||||
world: previousWorld === null ? cloneWorldSettings(currentDocument.world) : cloneWorldSettings(previousWorld)
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
70
src/commands/import-model-asset-command.js
Normal file
70
src/commands/import-model-asset-command.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneModelInstance } from "../assets/model-instances";
|
||||
import { cloneProjectAssetRecord } from "../assets/project-assets";
|
||||
function setSingleModelInstanceSelection(modelInstanceId) {
|
||||
return {
|
||||
kind: "modelInstances",
|
||||
ids: [modelInstanceId]
|
||||
};
|
||||
}
|
||||
export function createImportModelAssetCommand(options) {
|
||||
const nextAsset = cloneProjectAssetRecord(options.asset);
|
||||
const nextModelInstance = cloneModelInstance(options.modelInstance);
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? `Import ${nextAsset.sourceName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (currentDocument.assets[nextAsset.id] !== undefined) {
|
||||
throw new Error(`Asset ${nextAsset.id} already exists.`);
|
||||
}
|
||||
if (currentDocument.modelInstances[nextModelInstance.id] !== undefined) {
|
||||
throw new Error(`Model instance ${nextModelInstance.id} already exists.`);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: {
|
||||
...currentDocument.assets,
|
||||
[nextAsset.id]: cloneProjectAssetRecord(nextAsset)
|
||||
},
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[nextModelInstance.id]: cloneModelInstance(nextModelInstance)
|
||||
}
|
||||
});
|
||||
context.setSelection(setSingleModelInstanceSelection(nextModelInstance.id));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextAssets = {
|
||||
...currentDocument.assets
|
||||
};
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
delete nextAssets[nextAsset.id];
|
||||
delete nextModelInstances[nextModelInstance.id];
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
assets: nextAssets,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
55
src/commands/move-box-brush-command.js
Normal file
55
src/commands/move-box-brush-command.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import { DEFAULT_GRID_SIZE, snapVec3ToGrid } from "../geometry/grid-snapping";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
|
||||
export function createMoveBoxBrushCommand(options) {
|
||||
const resolvedCenter = options.snapToGrid === false ? options.center : snapVec3ToGrid(options.center, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
let previousCenter = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Move box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
if (previousCenter === null) {
|
||||
previousCenter = {
|
||||
...brush.center
|
||||
};
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: {
|
||||
...resolvedCenter
|
||||
}
|
||||
}));
|
||||
context.setSelection(setSingleBrushSelection(options.brushId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousCenter === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: {
|
||||
...previousCenter
|
||||
}
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
61
src/commands/resize-box-brush-command.js
Normal file
61
src/commands/resize-box-brush-command.js
Normal file
@@ -0,0 +1,61 @@
|
||||
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid } from "../geometry/grid-snapping";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneBoxBrushGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
|
||||
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
|
||||
export function createResizeBoxBrushCommand(options) {
|
||||
const resolvedSize = options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
let previousSize = null;
|
||||
let previousGeometry = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Resize box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
if (previousSize === null) {
|
||||
previousSize = {
|
||||
...brush.size
|
||||
};
|
||||
previousGeometry = cloneBoxBrushGeometry(brush.geometry);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
const nextGeometry = scaleBoxBrushGeometryToSize(brush.geometry, resolvedSize);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
size: {
|
||||
...resolvedSize
|
||||
},
|
||||
geometry: nextGeometry
|
||||
}));
|
||||
context.setSelection(setSingleBrushSelection(options.brushId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousSize === null || previousGeometry === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
size: {
|
||||
...previousSize
|
||||
},
|
||||
geometry: cloneBoxBrushGeometry(previousGeometry)
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid } from "../geometry/grid-snapping";
|
||||
import { cloneBoxBrushGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
|
||||
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
@@ -21,6 +22,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);
|
||||
|
||||
let previousSize: Vec3 | null = null;
|
||||
let previousGeometry: ReturnType<typeof cloneBoxBrushGeometry> | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
@@ -35,6 +37,7 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
previousSize = {
|
||||
...brush.size
|
||||
};
|
||||
previousGeometry = cloneBoxBrushGeometry(brush.geometry);
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
@@ -45,19 +48,22 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
const nextGeometry = scaleBoxBrushGeometryToSize(brush.geometry, resolvedSize);
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
size: {
|
||||
...resolvedSize
|
||||
}
|
||||
},
|
||||
geometry: nextGeometry
|
||||
})
|
||||
);
|
||||
context.setSelection(setSingleBrushSelection(options.brushId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousSize === null) {
|
||||
if (previousSize === null || previousGeometry === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -69,7 +75,8 @@ export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOption
|
||||
...brush,
|
||||
size: {
|
||||
...previousSize
|
||||
}
|
||||
},
|
||||
geometry: cloneBoxBrushGeometry(previousGeometry)
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
53
src/commands/rotate-box-brush-command.js
Normal file
53
src/commands/rotate-box-brush-command.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
|
||||
export function createRotateBoxBrushCommand(options) {
|
||||
let previousRotationDegrees = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Rotate box brush",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
if (previousRotationDegrees === null) {
|
||||
previousRotationDegrees = {
|
||||
...brush.rotationDegrees
|
||||
};
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
rotationDegrees: {
|
||||
...options.rotationDegrees
|
||||
}
|
||||
}));
|
||||
context.setSelection(setSingleBrushSelection(options.brushId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousRotationDegrees === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
rotationDegrees: {
|
||||
...previousRotationDegrees
|
||||
}
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
48
src/commands/set-active-scene-command.ts
Normal file
48
src/commands/set-active-scene-command.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
export function createSetActiveSceneCommand(nextSceneId: string): EditorCommand {
|
||||
let previousSceneId: string | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: "Switch active scene",
|
||||
execute(context) {
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
|
||||
if (currentProjectDocument.scenes[nextSceneId] === undefined) {
|
||||
throw new Error(`Cannot activate missing scene ${nextSceneId}.`);
|
||||
}
|
||||
|
||||
if (previousSceneId === null) {
|
||||
previousSceneId = currentProjectDocument.activeSceneId;
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
activeSceneId: nextSceneId
|
||||
});
|
||||
context.setSelection({ kind: "none" });
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousSceneId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
|
||||
if (currentProjectDocument.scenes[previousSceneId] === undefined) {
|
||||
throw new Error(`Cannot restore missing scene ${previousSceneId}.`);
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
activeSceneId: previousSceneId
|
||||
});
|
||||
context.setSelection({ kind: "none" });
|
||||
context.setToolMode("select");
|
||||
}
|
||||
};
|
||||
}
|
||||
50
src/commands/set-box-brush-face-material-command.js
Normal file
50
src/commands/set-box-brush-face-material-command.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneSelectionForCommand, getBoxBrushFaceOrThrow, replaceBoxBrushFace, setSingleBrushFaceSelection } from "./brush-command-helpers";
|
||||
export function createSetBoxBrushFaceMaterialCommand(options) {
|
||||
let previousMaterialId;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.materialId === null ? `Clear ${options.faceId} face material` : `Apply material to ${options.faceId} face`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
|
||||
if (options.materialId !== null && currentDocument.materials[options.materialId] === undefined) {
|
||||
throw new Error(`Material ${options.materialId} does not exist in the document registry.`);
|
||||
}
|
||||
if (previousMaterialId === undefined) {
|
||||
previousMaterialId = currentFace.materialId;
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
|
||||
...currentFace,
|
||||
materialId: options.materialId
|
||||
}));
|
||||
context.setSelection(setSingleBrushFaceSelection(options.brushId, options.faceId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousMaterialId === undefined) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
|
||||
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
|
||||
...currentFace,
|
||||
materialId: previousMaterialId
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
48
src/commands/set-box-brush-face-uv-state-command.js
Normal file
48
src/commands/set-box-brush-face-uv-state-command.js
Normal file
@@ -0,0 +1,48 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneFaceUvState } from "../document/brushes";
|
||||
import { cloneSelectionForCommand, getBoxBrushFaceOrThrow, replaceBoxBrushFace, setSingleBrushFaceSelection } from "./brush-command-helpers";
|
||||
export function createSetBoxBrushFaceUvStateCommand(options) {
|
||||
let previousUvState = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? `Update ${options.faceId} face UVs`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
|
||||
if (previousUvState === null) {
|
||||
previousUvState = cloneFaceUvState(currentFace.uv);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
|
||||
...currentFace,
|
||||
uv: cloneFaceUvState(options.uvState)
|
||||
}));
|
||||
context.setSelection(setSingleBrushFaceSelection(options.brushId, options.faceId));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousUvState === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const currentFace = getBoxBrushFaceOrThrow(currentDocument, options.brushId, options.faceId);
|
||||
context.setDocument(replaceBoxBrushFace(currentDocument, options.brushId, options.faceId, {
|
||||
...currentFace,
|
||||
uv: cloneFaceUvState(previousUvState)
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
30
src/commands/set-box-brush-name-command.js
Normal file
30
src/commands/set-box-brush-name-command.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { normalizeBrushName } from "../document/brushes";
|
||||
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
|
||||
export function createSetBoxBrushNameCommand(options) {
|
||||
const normalizedName = normalizeBrushName(options.name);
|
||||
let previousName;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: normalizedName === undefined ? "Clear box brush name" : `Rename box brush to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
if (previousName === undefined) {
|
||||
previousName = brush.name;
|
||||
}
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
name: normalizedName
|
||||
}));
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
name: previousName
|
||||
}));
|
||||
}
|
||||
};
|
||||
}
|
||||
95
src/commands/set-box-brush-transform-command.js
Normal file
95
src/commands/set-box-brush-transform-command.js
Normal file
@@ -0,0 +1,95 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneBoxBrushGeometry, deriveBoxBrushSizeFromGeometry, scaleBoxBrushGeometryToSize } from "../document/brushes";
|
||||
import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushEdgeSelection, setSingleBrushFaceSelection, setSingleBrushSelection, setSingleBrushVertexSelection } from "./brush-command-helpers";
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function selectionToEditorSelection(selection) {
|
||||
switch (selection.kind) {
|
||||
case "brush":
|
||||
return setSingleBrushSelection(selection.brushId);
|
||||
case "brushFace":
|
||||
return setSingleBrushFaceSelection(selection.brushId, selection.faceId);
|
||||
case "brushEdge":
|
||||
return setSingleBrushEdgeSelection(selection.brushId, selection.edgeId);
|
||||
case "brushVertex":
|
||||
return setSingleBrushVertexSelection(selection.brushId, selection.vertexId);
|
||||
}
|
||||
}
|
||||
function getBrushId(selection) {
|
||||
return selection.brushId;
|
||||
}
|
||||
function assertPositiveSize(size) {
|
||||
if (!(size.x > 0 && size.y > 0 && size.z > 0)) {
|
||||
throw new Error("Whitebox box size must remain positive on every axis.");
|
||||
}
|
||||
if (!Number.isFinite(size.x) || !Number.isFinite(size.y) || !Number.isFinite(size.z)) {
|
||||
throw new Error("Whitebox box size values must be finite numbers.");
|
||||
}
|
||||
}
|
||||
export function createSetBoxBrushTransformCommand(options) {
|
||||
assertPositiveSize(options.size);
|
||||
let previousSnapshot = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Set box brush transform",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brushId = getBrushId(options.selection);
|
||||
const brush = getBoxBrushOrThrow(currentDocument, brushId);
|
||||
if (previousSnapshot === null) {
|
||||
previousSnapshot = {
|
||||
center: cloneVec3(brush.center),
|
||||
rotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
size: cloneVec3(brush.size),
|
||||
geometry: cloneBoxBrushGeometry(brush.geometry)
|
||||
};
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
const nextGeometry = options.geometry === undefined ? scaleBoxBrushGeometryToSize(brush.geometry, options.size) : cloneBoxBrushGeometry(options.geometry);
|
||||
const nextSize = deriveBoxBrushSizeFromGeometry(nextGeometry);
|
||||
assertPositiveSize(nextSize);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: cloneVec3(options.center),
|
||||
rotationDegrees: cloneVec3(options.rotationDegrees),
|
||||
size: nextSize,
|
||||
geometry: nextGeometry
|
||||
}));
|
||||
context.setSelection(selectionToEditorSelection(options.selection));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousSnapshot === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const brushId = getBrushId(options.selection);
|
||||
const brush = getBoxBrushOrThrow(currentDocument, brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: cloneVec3(previousSnapshot.center),
|
||||
rotationDegrees: cloneVec3(previousSnapshot.rotationDegrees),
|
||||
size: cloneVec3(previousSnapshot.size),
|
||||
geometry: cloneBoxBrushGeometry(previousSnapshot.geometry)
|
||||
}));
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
154
src/commands/set-box-brush-transform-command.ts
Normal file
154
src/commands/set-box-brush-transform-command.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import type { ToolMode } from "../core/tool-mode";
|
||||
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { EditorSelection } from "../core/selection";
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import { cloneBoxBrushGeometry, deriveBoxBrushSizeFromGeometry, scaleBoxBrushGeometryToSize, type BoxBrushGeometry } from "../document/brushes";
|
||||
|
||||
import {
|
||||
cloneSelectionForCommand,
|
||||
getBoxBrushOrThrow,
|
||||
replaceBrush,
|
||||
setSingleBrushEdgeSelection,
|
||||
setSingleBrushFaceSelection,
|
||||
setSingleBrushSelection,
|
||||
setSingleBrushVertexSelection
|
||||
} from "./brush-command-helpers";
|
||||
import type { EditorCommand } from "./command";
|
||||
import type { BoxEdgeId, BoxFaceId, BoxVertexId } from "../document/brushes";
|
||||
|
||||
type BrushTransformCommandSelection =
|
||||
| { kind: "brush"; brushId: string }
|
||||
| { kind: "brushFace"; brushId: string; faceId: BoxFaceId }
|
||||
| { kind: "brushEdge"; brushId: string; edgeId: BoxEdgeId }
|
||||
| { kind: "brushVertex"; brushId: string; vertexId: BoxVertexId };
|
||||
|
||||
interface SetBoxBrushTransformCommandOptions {
|
||||
selection: BrushTransformCommandSelection;
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
geometry?: BoxBrushGeometry;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
interface BrushTransformSnapshot {
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
geometry: ReturnType<typeof cloneBoxBrushGeometry>;
|
||||
}
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
|
||||
function selectionToEditorSelection(selection: BrushTransformCommandSelection): EditorSelection {
|
||||
switch (selection.kind) {
|
||||
case "brush":
|
||||
return setSingleBrushSelection(selection.brushId);
|
||||
case "brushFace":
|
||||
return setSingleBrushFaceSelection(selection.brushId, selection.faceId);
|
||||
case "brushEdge":
|
||||
return setSingleBrushEdgeSelection(selection.brushId, selection.edgeId);
|
||||
case "brushVertex":
|
||||
return setSingleBrushVertexSelection(selection.brushId, selection.vertexId);
|
||||
}
|
||||
}
|
||||
|
||||
function getBrushId(selection: BrushTransformCommandSelection): string {
|
||||
return selection.brushId;
|
||||
}
|
||||
|
||||
function assertPositiveSize(size: Vec3) {
|
||||
if (!(size.x > 0 && size.y > 0 && size.z > 0)) {
|
||||
throw new Error("Whitebox box size must remain positive on every axis.");
|
||||
}
|
||||
|
||||
if (!Number.isFinite(size.x) || !Number.isFinite(size.y) || !Number.isFinite(size.z)) {
|
||||
throw new Error("Whitebox box size values must be finite numbers.");
|
||||
}
|
||||
}
|
||||
|
||||
export function createSetBoxBrushTransformCommand(options: SetBoxBrushTransformCommandOptions): EditorCommand {
|
||||
assertPositiveSize(options.size);
|
||||
|
||||
let previousSnapshot: BrushTransformSnapshot | null = null;
|
||||
let previousSelection: EditorSelection | null = null;
|
||||
let previousToolMode: ToolMode | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Set box brush transform",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brushId = getBrushId(options.selection);
|
||||
const brush = getBoxBrushOrThrow(currentDocument, brushId);
|
||||
|
||||
if (previousSnapshot === null) {
|
||||
previousSnapshot = {
|
||||
center: cloneVec3(brush.center),
|
||||
rotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
size: cloneVec3(brush.size),
|
||||
geometry: cloneBoxBrushGeometry(brush.geometry)
|
||||
};
|
||||
}
|
||||
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneSelectionForCommand(context.getSelection());
|
||||
}
|
||||
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
|
||||
const nextGeometry = options.geometry === undefined ? scaleBoxBrushGeometryToSize(brush.geometry, options.size) : cloneBoxBrushGeometry(options.geometry);
|
||||
const nextSize = deriveBoxBrushSizeFromGeometry(nextGeometry);
|
||||
|
||||
assertPositiveSize(nextSize);
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: cloneVec3(options.center),
|
||||
rotationDegrees: cloneVec3(options.rotationDegrees),
|
||||
size: nextSize,
|
||||
geometry: nextGeometry
|
||||
})
|
||||
);
|
||||
context.setSelection(selectionToEditorSelection(options.selection));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
if (previousSnapshot === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
const brushId = getBrushId(options.selection);
|
||||
const brush = getBoxBrushOrThrow(currentDocument, brushId);
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
center: cloneVec3(previousSnapshot.center),
|
||||
rotationDegrees: cloneVec3(previousSnapshot.rotationDegrees),
|
||||
size: cloneVec3(previousSnapshot.size),
|
||||
geometry: cloneBoxBrushGeometry(previousSnapshot.geometry)
|
||||
})
|
||||
);
|
||||
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
33
src/commands/set-box-brush-volume-settings-command.js
Normal file
33
src/commands/set-box-brush-volume-settings-command.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneBoxBrushVolumeSettings } from "../document/brushes";
|
||||
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
|
||||
export function createSetBoxBrushVolumeSettingsCommand(options) {
|
||||
const nextVolume = cloneBoxBrushVolumeSettings(options.volume);
|
||||
let previousVolume = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Set box volume settings",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
if (previousVolume === null) {
|
||||
previousVolume = cloneBoxBrushVolumeSettings(brush.volume);
|
||||
}
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
volume: cloneBoxBrushVolumeSettings(nextVolume)
|
||||
}));
|
||||
},
|
||||
undo(context) {
|
||||
if (previousVolume === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
context.setDocument(replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
volume: cloneBoxBrushVolumeSettings(previousVolume)
|
||||
}));
|
||||
}
|
||||
};
|
||||
}
|
||||
51
src/commands/set-box-brush-volume-settings-command.ts
Normal file
51
src/commands/set-box-brush-volume-settings-command.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneBoxBrushVolumeSettings, type BoxBrushVolumeSettings } from "../document/brushes";
|
||||
|
||||
import { getBoxBrushOrThrow, replaceBrush } from "./brush-command-helpers";
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface SetBoxBrushVolumeSettingsCommandOptions {
|
||||
brushId: string;
|
||||
volume: BoxBrushVolumeSettings;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function createSetBoxBrushVolumeSettingsCommand(options: SetBoxBrushVolumeSettingsCommandOptions): EditorCommand {
|
||||
const nextVolume = cloneBoxBrushVolumeSettings(options.volume);
|
||||
let previousVolume: BoxBrushVolumeSettings | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Set box volume settings",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
|
||||
if (previousVolume === null) {
|
||||
previousVolume = cloneBoxBrushVolumeSettings(brush.volume);
|
||||
}
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
volume: cloneBoxBrushVolumeSettings(nextVolume)
|
||||
})
|
||||
);
|
||||
},
|
||||
undo(context) {
|
||||
if (previousVolume === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDocument = context.getDocument();
|
||||
const brush = getBoxBrushOrThrow(currentDocument, options.brushId);
|
||||
|
||||
context.setDocument(
|
||||
replaceBrush(currentDocument, {
|
||||
...brush,
|
||||
volume: cloneBoxBrushVolumeSettings(previousVolume)
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
47
src/commands/set-entity-name-command.js
Normal file
47
src/commands/set-entity-name-command.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEntityInstance, normalizeEntityName } from "../entities/entity-instances";
|
||||
export function createSetEntityNameCommand(options) {
|
||||
const normalizedName = normalizeEntityName(options.name);
|
||||
let previousName;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: normalizedName === undefined ? "Clear entity name" : `Rename entity to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const entity = currentDocument.entities[options.entityId];
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${options.entityId} does not exist.`);
|
||||
}
|
||||
if (previousName === undefined) {
|
||||
previousName = entity.name;
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[entity.id]: cloneEntityInstance({
|
||||
...entity,
|
||||
name: normalizedName
|
||||
})
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const entity = currentDocument.entities[options.entityId];
|
||||
if (entity === undefined) {
|
||||
throw new Error(`Entity ${options.entityId} does not exist.`);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[entity.id]: cloneEntityInstance({
|
||||
...entity,
|
||||
name: previousName
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
47
src/commands/set-model-instance-name-command.js
Normal file
47
src/commands/set-model-instance-name-command.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneModelInstance, normalizeModelInstanceName } from "../assets/model-instances";
|
||||
export function createSetModelInstanceNameCommand(options) {
|
||||
const normalizedName = normalizeModelInstanceName(options.name);
|
||||
let previousName;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: normalizedName === undefined ? "Clear model instance name" : `Rename model instance to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const modelInstance = currentDocument.modelInstances[options.modelInstanceId];
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${options.modelInstanceId} does not exist.`);
|
||||
}
|
||||
if (previousName === undefined) {
|
||||
previousName = modelInstance.name;
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[modelInstance.id]: cloneModelInstance({
|
||||
...modelInstance,
|
||||
name: normalizedName
|
||||
})
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const modelInstance = currentDocument.modelInstances[options.modelInstanceId];
|
||||
if (modelInstance === undefined) {
|
||||
throw new Error(`Model instance ${options.modelInstanceId} does not exist.`);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[modelInstance.id]: cloneModelInstance({
|
||||
...modelInstance,
|
||||
name: previousName
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
12
src/commands/set-player-start-command.js
Normal file
12
src/commands/set-player-start-command.js
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createPlayerStartEntity } from "../entities/entity-instances";
|
||||
import { createUpsertEntityCommand } from "./upsert-entity-command";
|
||||
export function createSetPlayerStartCommand(options) {
|
||||
return createUpsertEntityCommand({
|
||||
entity: createPlayerStartEntity({
|
||||
id: options.entityId,
|
||||
position: options.position,
|
||||
yawDegrees: options.yawDegrees
|
||||
}),
|
||||
label: options.entityId === undefined ? "Place player start" : "Move player start"
|
||||
});
|
||||
}
|
||||
37
src/commands/set-project-name-command.ts
Normal file
37
src/commands/set-project-name-command.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { DEFAULT_PROJECT_NAME } from "../document/scene-document";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
export function createSetProjectNameCommand(nextName: string): EditorCommand {
|
||||
const normalizedName = nextName.trim() || DEFAULT_PROJECT_NAME;
|
||||
let previousName: string | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: `Rename project to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
|
||||
if (previousName === null) {
|
||||
previousName = currentProjectDocument.name;
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
name: normalizedName
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
if (previousName === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
name: previousName
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
81
src/commands/set-scene-loading-screen-command.ts
Normal file
81
src/commands/set-scene-loading-screen-command.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import {
|
||||
cloneSceneLoadingScreenSettings,
|
||||
type SceneLoadingScreenSettings
|
||||
} from "../document/scene-document";
|
||||
|
||||
import type { EditorCommand } from "./command";
|
||||
|
||||
interface SetSceneLoadingScreenCommandOptions {
|
||||
sceneId: string;
|
||||
label: string;
|
||||
loadingScreen: SceneLoadingScreenSettings;
|
||||
}
|
||||
|
||||
export function createSetSceneLoadingScreenCommand(
|
||||
options: SetSceneLoadingScreenCommandOptions
|
||||
): EditorCommand {
|
||||
const nextLoadingScreen = cloneSceneLoadingScreenSettings(
|
||||
options.loadingScreen
|
||||
);
|
||||
let previousLoadingScreen: SceneLoadingScreenSettings | null = null;
|
||||
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label,
|
||||
execute(context) {
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
const currentScene = currentProjectDocument.scenes[options.sceneId];
|
||||
|
||||
if (currentScene === undefined) {
|
||||
throw new Error(
|
||||
`Cannot update loading overlay for missing scene ${options.sceneId}.`
|
||||
);
|
||||
}
|
||||
|
||||
if (previousLoadingScreen === null) {
|
||||
previousLoadingScreen = cloneSceneLoadingScreenSettings(
|
||||
currentScene.loadingScreen
|
||||
);
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
scenes: {
|
||||
...currentProjectDocument.scenes,
|
||||
[options.sceneId]: {
|
||||
...currentScene,
|
||||
loadingScreen: cloneSceneLoadingScreenSettings(nextLoadingScreen)
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
if (previousLoadingScreen === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentProjectDocument = context.getProjectDocument();
|
||||
const currentScene = currentProjectDocument.scenes[options.sceneId];
|
||||
|
||||
if (currentScene === undefined) {
|
||||
throw new Error(
|
||||
`Cannot restore loading overlay for missing scene ${options.sceneId}.`
|
||||
);
|
||||
}
|
||||
|
||||
context.setProjectDocument({
|
||||
...currentProjectDocument,
|
||||
scenes: {
|
||||
...currentProjectDocument.scenes,
|
||||
[options.sceneId]: {
|
||||
...currentScene,
|
||||
loadingScreen: cloneSceneLoadingScreenSettings(
|
||||
previousLoadingScreen
|
||||
)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
29
src/commands/set-scene-name-command.js
Normal file
29
src/commands/set-scene-name-command.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
export function createSetSceneNameCommand(nextName) {
|
||||
const normalizedName = nextName.trim() || "Untitled Scene";
|
||||
let previousName = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: `Rename scene to ${normalizedName}`,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (previousName === null) {
|
||||
previousName = currentDocument.name;
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
name: normalizedName
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
if (previousName === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
name: previousName
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
30
src/commands/set-world-settings-command.js
Normal file
30
src/commands/set-world-settings-command.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneWorldSettings } from "../document/world-settings";
|
||||
export function createSetWorldSettingsCommand(options) {
|
||||
const nextWorld = cloneWorldSettings(options.world);
|
||||
let previousWorld = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label,
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
if (previousWorld === null) {
|
||||
previousWorld = cloneWorldSettings(currentDocument.world);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
world: cloneWorldSettings(nextWorld)
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
if (previousWorld === null) {
|
||||
return;
|
||||
}
|
||||
const currentDocument = context.getDocument();
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
world: cloneWorldSettings(previousWorld)
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
70
src/commands/upsert-entity-command.js
Normal file
70
src/commands/upsert-entity-command.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEntityInstance, getEntityKindLabel } from "../entities/entity-instances";
|
||||
function setSingleEntitySelection(entityId) {
|
||||
return {
|
||||
kind: "entities",
|
||||
ids: [entityId]
|
||||
};
|
||||
}
|
||||
function createDefaultEntityCommandLabel(entity, isNewEntity) {
|
||||
const action = isNewEntity ? "Place" : "Update";
|
||||
return `${action} ${getEntityKindLabel(entity.kind).toLowerCase()}`;
|
||||
}
|
||||
export function createUpsertEntityCommand(options) {
|
||||
const nextEntity = cloneEntityInstance(options.entity);
|
||||
let previousEntity = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? createDefaultEntityCommandLabel(nextEntity, true),
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentEntity = currentDocument.entities[nextEntity.id];
|
||||
if (currentEntity !== undefined && currentEntity.kind !== nextEntity.kind) {
|
||||
throw new Error(`Entity ${nextEntity.id} is a ${currentEntity.kind}, not a ${nextEntity.kind}.`);
|
||||
}
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
if (previousEntity === null && currentEntity !== undefined) {
|
||||
previousEntity = cloneEntityInstance(currentEntity);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: {
|
||||
...currentDocument.entities,
|
||||
[nextEntity.id]: cloneEntityInstance(nextEntity)
|
||||
}
|
||||
});
|
||||
context.setSelection(setSingleEntitySelection(nextEntity.id));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextEntities = {
|
||||
...currentDocument.entities
|
||||
};
|
||||
if (previousEntity === null) {
|
||||
delete nextEntities[nextEntity.id];
|
||||
}
|
||||
else {
|
||||
nextEntities[nextEntity.id] = cloneEntityInstance(previousEntity);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
entities: nextEntities
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
40
src/commands/upsert-interaction-link-command.js
Normal file
40
src/commands/upsert-interaction-link-command.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import { cloneInteractionLink } from "../interactions/interaction-links";
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
export function createUpsertInteractionLinkCommand(options) {
|
||||
const nextLink = cloneInteractionLink(options.link);
|
||||
let previousLink = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? "Update interaction link",
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentLink = currentDocument.interactionLinks[nextLink.id];
|
||||
if (previousLink === null && currentLink !== undefined) {
|
||||
previousLink = cloneInteractionLink(currentLink);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
interactionLinks: {
|
||||
...currentDocument.interactionLinks,
|
||||
[nextLink.id]: cloneInteractionLink(nextLink)
|
||||
}
|
||||
});
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextInteractionLinks = {
|
||||
...currentDocument.interactionLinks
|
||||
};
|
||||
if (previousLink === null) {
|
||||
delete nextInteractionLinks[nextLink.id];
|
||||
}
|
||||
else {
|
||||
nextInteractionLinks[nextLink.id] = cloneInteractionLink(previousLink);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
interactionLinks: nextInteractionLinks
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
75
src/commands/upsert-model-instance-command.js
Normal file
75
src/commands/upsert-model-instance-command.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { cloneEditorSelection } from "../core/selection";
|
||||
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
|
||||
import { getProjectAssetKindLabel } from "../assets/project-assets";
|
||||
function setSingleModelInstanceSelection(modelInstanceId) {
|
||||
return {
|
||||
kind: "modelInstances",
|
||||
ids: [modelInstanceId]
|
||||
};
|
||||
}
|
||||
function createDefaultModelInstanceCommandLabel(isNewModelInstance) {
|
||||
const action = isNewModelInstance ? "Place" : "Update";
|
||||
return `${action} ${getModelInstanceKindLabel().toLowerCase()}`;
|
||||
}
|
||||
export function createUpsertModelInstanceCommand(options) {
|
||||
const nextModelInstance = cloneModelInstance(options.modelInstance);
|
||||
let previousModelInstance = null;
|
||||
let previousSelection = null;
|
||||
let previousToolMode = null;
|
||||
return {
|
||||
id: createOpaqueId("command"),
|
||||
label: options.label ?? createDefaultModelInstanceCommandLabel(true),
|
||||
execute(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const currentAsset = currentDocument.assets[nextModelInstance.assetId];
|
||||
if (currentAsset === undefined) {
|
||||
throw new Error(`Model instance ${nextModelInstance.id} cannot reference missing asset ${nextModelInstance.assetId}.`);
|
||||
}
|
||||
if (currentAsset.kind !== "model") {
|
||||
throw new Error(`Model instance ${nextModelInstance.id} must reference a model asset, not ${getProjectAssetKindLabel(currentAsset.kind).toLowerCase()}.`);
|
||||
}
|
||||
const currentModelInstance = currentDocument.modelInstances[nextModelInstance.id];
|
||||
if (previousSelection === null) {
|
||||
previousSelection = cloneEditorSelection(context.getSelection());
|
||||
}
|
||||
if (previousToolMode === null) {
|
||||
previousToolMode = context.getToolMode();
|
||||
}
|
||||
if (previousModelInstance === null && currentModelInstance !== undefined) {
|
||||
previousModelInstance = cloneModelInstance(currentModelInstance);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: {
|
||||
...currentDocument.modelInstances,
|
||||
[nextModelInstance.id]: cloneModelInstance(nextModelInstance)
|
||||
}
|
||||
});
|
||||
context.setSelection(setSingleModelInstanceSelection(nextModelInstance.id));
|
||||
context.setToolMode("select");
|
||||
},
|
||||
undo(context) {
|
||||
const currentDocument = context.getDocument();
|
||||
const nextModelInstances = {
|
||||
...currentDocument.modelInstances
|
||||
};
|
||||
if (previousModelInstance === null) {
|
||||
delete nextModelInstances[nextModelInstance.id];
|
||||
}
|
||||
else {
|
||||
nextModelInstances[nextModelInstance.id] = cloneModelInstance(previousModelInstance);
|
||||
}
|
||||
context.setDocument({
|
||||
...currentDocument,
|
||||
modelInstances: nextModelInstances
|
||||
});
|
||||
if (previousSelection !== null) {
|
||||
context.setSelection(previousSelection);
|
||||
}
|
||||
if (previousToolMode !== null) {
|
||||
context.setToolMode(previousToolMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
8
src/core/ids.js
Normal file
8
src/core/ids.js
Normal file
@@ -0,0 +1,8 @@
|
||||
let fallbackCounter = 0;
|
||||
export function createOpaqueId(prefix) {
|
||||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
||||
return `${prefix}-${crypto.randomUUID()}`;
|
||||
}
|
||||
fallbackCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${fallbackCounter}`;
|
||||
}
|
||||
134
src/core/selection.js
Normal file
134
src/core/selection.js
Normal file
@@ -0,0 +1,134 @@
|
||||
export function cloneEditorSelection(selection) {
|
||||
if (selection.kind === "none") {
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
if (selection.kind === "brushFace") {
|
||||
return {
|
||||
kind: "brushFace",
|
||||
brushId: selection.brushId,
|
||||
faceId: selection.faceId
|
||||
};
|
||||
}
|
||||
if (selection.kind === "brushEdge") {
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId: selection.brushId,
|
||||
edgeId: selection.edgeId
|
||||
};
|
||||
}
|
||||
if (selection.kind === "brushVertex") {
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId: selection.brushId,
|
||||
vertexId: selection.vertexId
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: selection.kind,
|
||||
ids: [...selection.ids]
|
||||
};
|
||||
}
|
||||
export function areEditorSelectionsEqual(left, right) {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
switch (left.kind) {
|
||||
case "none":
|
||||
return true;
|
||||
case "brushFace":
|
||||
return right.kind === "brushFace" && left.brushId === right.brushId && left.faceId === right.faceId;
|
||||
case "brushEdge":
|
||||
return right.kind === "brushEdge" && left.brushId === right.brushId && left.edgeId === right.edgeId;
|
||||
case "brushVertex":
|
||||
return right.kind === "brushVertex" && left.brushId === right.brushId && left.vertexId === right.vertexId;
|
||||
case "brushes":
|
||||
case "entities":
|
||||
case "modelInstances":
|
||||
return right.kind === left.kind && left.ids.length === right.ids.length && left.ids.every((id, index) => id === right.ids[index]);
|
||||
}
|
||||
}
|
||||
export function getSingleSelectedBrushId(selection) {
|
||||
if (selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") {
|
||||
return selection.brushId;
|
||||
}
|
||||
if (selection.kind !== "brushes" || selection.ids.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
return selection.ids[0];
|
||||
}
|
||||
export function getSelectedBrushFaceId(selection) {
|
||||
if (selection.kind !== "brushFace") {
|
||||
return null;
|
||||
}
|
||||
return selection.faceId;
|
||||
}
|
||||
export function getSelectedBrushEdgeId(selection) {
|
||||
if (selection.kind !== "brushEdge") {
|
||||
return null;
|
||||
}
|
||||
return selection.edgeId;
|
||||
}
|
||||
export function getSelectedBrushVertexId(selection) {
|
||||
if (selection.kind !== "brushVertex") {
|
||||
return null;
|
||||
}
|
||||
return selection.vertexId;
|
||||
}
|
||||
export function getSingleSelectedEntityId(selection) {
|
||||
if (selection.kind !== "entities" || selection.ids.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
return selection.ids[0];
|
||||
}
|
||||
export function getSingleSelectedModelInstanceId(selection) {
|
||||
if (selection.kind !== "modelInstances" || selection.ids.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
return selection.ids[0];
|
||||
}
|
||||
export function isBrushSelected(selection, brushId) {
|
||||
return ((selection.kind === "brushes" && selection.ids.includes(brushId)) ||
|
||||
((selection.kind === "brushFace" || selection.kind === "brushEdge" || selection.kind === "brushVertex") &&
|
||||
selection.brushId === brushId));
|
||||
}
|
||||
export function isBrushFaceSelected(selection, brushId, faceId) {
|
||||
return selection.kind === "brushFace" && selection.brushId === brushId && selection.faceId === faceId;
|
||||
}
|
||||
export function isBrushEdgeSelected(selection, brushId, edgeId) {
|
||||
return selection.kind === "brushEdge" && selection.brushId === brushId && selection.edgeId === edgeId;
|
||||
}
|
||||
export function isBrushVertexSelected(selection, brushId, vertexId) {
|
||||
return selection.kind === "brushVertex" && selection.brushId === brushId && selection.vertexId === vertexId;
|
||||
}
|
||||
export function isModelInstanceSelected(selection, modelInstanceId) {
|
||||
return selection.kind === "modelInstances" && selection.ids.includes(modelInstanceId);
|
||||
}
|
||||
export function normalizeSelectionForWhiteboxSelectionMode(selection, mode) {
|
||||
switch (selection.kind) {
|
||||
case "brushFace":
|
||||
return mode === "face"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
case "brushEdge":
|
||||
return mode === "edge"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
case "brushVertex":
|
||||
return mode === "vertex"
|
||||
? selection
|
||||
: {
|
||||
kind: "brushes",
|
||||
ids: [selection.brushId]
|
||||
};
|
||||
default:
|
||||
return selection;
|
||||
}
|
||||
}
|
||||
1
src/core/tool-mode.js
Normal file
1
src/core/tool-mode.js
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
596
src/core/transform-session.js
Normal file
596
src/core/transform-session.js
Normal file
@@ -0,0 +1,596 @@
|
||||
import { createOpaqueId } from "./ids";
|
||||
import { BOX_VERTEX_IDS, BOX_EDGE_LABELS, BOX_FACE_LABELS, BOX_VERTEX_LABELS, cloneBoxBrushGeometry } from "../document/brushes";
|
||||
import { cloneEntityInstance, getEntityKindLabel } from "../entities/entity-instances";
|
||||
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
|
||||
function areBrushGeometriesEqual(left, right) {
|
||||
return BOX_VERTEX_IDS.every((vertexId) => {
|
||||
const leftVertex = left.vertices[vertexId];
|
||||
const rightVertex = right.vertices[vertexId];
|
||||
return areVec3Equal(leftVertex, rightVertex);
|
||||
});
|
||||
}
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function areVec3Equal(left, right) {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
function cloneEntityTransformRotationState(rotation) {
|
||||
switch (rotation.kind) {
|
||||
case "none":
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
case "yaw":
|
||||
return {
|
||||
kind: "yaw",
|
||||
yawDegrees: rotation.yawDegrees
|
||||
};
|
||||
case "direction":
|
||||
return {
|
||||
kind: "direction",
|
||||
direction: cloneVec3(rotation.direction)
|
||||
};
|
||||
}
|
||||
}
|
||||
function areEntityTransformRotationsEqual(left, right) {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
switch (left.kind) {
|
||||
case "none":
|
||||
return true;
|
||||
case "yaw":
|
||||
return right.kind === "yaw" && left.yawDegrees === right.yawDegrees;
|
||||
case "direction":
|
||||
return right.kind === "direction" && areVec3Equal(left.direction, right.direction);
|
||||
}
|
||||
}
|
||||
export function createInactiveTransformSession() {
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
export function cloneTransformTarget(target) {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
brushId: target.brushId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushFace":
|
||||
return {
|
||||
kind: "brushFace",
|
||||
brushId: target.brushId,
|
||||
faceId: target.faceId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushEdge":
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId: target.brushId,
|
||||
edgeId: target.edgeId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushVertex":
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId: target.brushId,
|
||||
vertexId: target.vertexId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
modelInstanceId: target.modelInstanceId,
|
||||
assetId: target.assetId,
|
||||
initialPosition: cloneVec3(target.initialPosition),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialScale: cloneVec3(target.initialScale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
entityId: target.entityId,
|
||||
entityKind: target.entityKind,
|
||||
initialPosition: cloneVec3(target.initialPosition),
|
||||
initialRotation: cloneEntityTransformRotationState(target.initialRotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
export function cloneTransformPreview(preview) {
|
||||
switch (preview.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(preview.center),
|
||||
rotationDegrees: cloneVec3(preview.rotationDegrees),
|
||||
size: cloneVec3(preview.size),
|
||||
geometry: cloneBoxBrushGeometry(preview.geometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
position: cloneVec3(preview.position),
|
||||
rotationDegrees: cloneVec3(preview.rotationDegrees),
|
||||
scale: cloneVec3(preview.scale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
position: cloneVec3(preview.position),
|
||||
rotation: cloneEntityTransformRotationState(preview.rotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
export function cloneTransformSession(session) {
|
||||
if (session.kind === "none") {
|
||||
return session;
|
||||
}
|
||||
return {
|
||||
kind: "active",
|
||||
id: session.id,
|
||||
source: session.source,
|
||||
sourcePanelId: session.sourcePanelId,
|
||||
operation: session.operation,
|
||||
axisConstraint: session.axisConstraint,
|
||||
target: cloneTransformTarget(session.target),
|
||||
preview: cloneTransformPreview(session.preview)
|
||||
};
|
||||
}
|
||||
export function areTransformSessionsEqual(left, right) {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
if (left.kind === "none" || right.kind === "none") {
|
||||
return true;
|
||||
}
|
||||
return (left.id === right.id &&
|
||||
left.source === right.source &&
|
||||
left.sourcePanelId === right.sourcePanelId &&
|
||||
left.operation === right.operation &&
|
||||
left.axisConstraint === right.axisConstraint &&
|
||||
areTransformTargetsEqual(left.target, right.target) &&
|
||||
areTransformPreviewsEqual(left.preview, right.preview));
|
||||
}
|
||||
function areTransformTargetsEqual(left, right) {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
switch (left.kind) {
|
||||
case "brush":
|
||||
return (right.kind === "brush" &&
|
||||
left.brushId === right.brushId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
|
||||
case "brushFace":
|
||||
return (right.kind === "brushFace" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.faceId === right.faceId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
|
||||
case "brushEdge":
|
||||
return (right.kind === "brushEdge" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.edgeId === right.edgeId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
|
||||
case "brushVertex":
|
||||
return (right.kind === "brushVertex" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.vertexId === right.vertexId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry));
|
||||
case "modelInstance":
|
||||
return (right.kind === "modelInstance" &&
|
||||
left.modelInstanceId === right.modelInstanceId &&
|
||||
left.assetId === right.assetId &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialScale, right.initialScale));
|
||||
case "entity":
|
||||
return (right.kind === "entity" &&
|
||||
left.entityId === right.entityId &&
|
||||
left.entityKind === right.entityKind &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areEntityTransformRotationsEqual(left.initialRotation, right.initialRotation));
|
||||
}
|
||||
}
|
||||
function areTransformPreviewsEqual(left, right) {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
switch (left.kind) {
|
||||
case "brush":
|
||||
return (right.kind === "brush" &&
|
||||
areVec3Equal(left.center, right.center) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.size, right.size) &&
|
||||
areBrushGeometriesEqual(left.geometry, right.geometry));
|
||||
case "modelInstance":
|
||||
return (right.kind === "modelInstance" &&
|
||||
areVec3Equal(left.position, right.position) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.scale, right.scale));
|
||||
case "entity":
|
||||
return right.kind === "entity" && areVec3Equal(left.position, right.position) && areEntityTransformRotationsEqual(left.rotation, right.rotation);
|
||||
}
|
||||
}
|
||||
export function createTransformSession(options) {
|
||||
return {
|
||||
kind: "active",
|
||||
id: createOpaqueId("transform-session"),
|
||||
source: options.source,
|
||||
sourcePanelId: options.sourcePanelId,
|
||||
operation: options.operation,
|
||||
axisConstraint: options.axisConstraint ?? null,
|
||||
target: cloneTransformTarget(options.target),
|
||||
preview: createTransformPreviewFromTarget(options.target)
|
||||
};
|
||||
}
|
||||
export function createTransformPreviewFromTarget(target) {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(target.initialCenter),
|
||||
rotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
size: cloneVec3(target.initialSize),
|
||||
geometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
kind: "modelInstance",
|
||||
position: cloneVec3(target.initialPosition),
|
||||
rotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
scale: cloneVec3(target.initialScale)
|
||||
};
|
||||
case "entity":
|
||||
return {
|
||||
kind: "entity",
|
||||
position: cloneVec3(target.initialPosition),
|
||||
rotation: cloneEntityTransformRotationState(target.initialRotation)
|
||||
};
|
||||
}
|
||||
}
|
||||
export function doesTransformSessionChangeTarget(session) {
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return (session.preview.kind === "brush" &&
|
||||
(!areVec3Equal(session.preview.center, session.target.initialCenter) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
!areVec3Equal(session.preview.size, session.target.initialSize) ||
|
||||
!areBrushGeometriesEqual(session.preview.geometry, session.target.initialGeometry)));
|
||||
case "modelInstance":
|
||||
return (session.preview.kind === "modelInstance" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
!areVec3Equal(session.preview.scale, session.target.initialScale)));
|
||||
case "entity":
|
||||
return (session.preview.kind === "entity" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areEntityTransformRotationsEqual(session.preview.rotation, session.target.initialRotation)));
|
||||
}
|
||||
}
|
||||
export function getTransformOperationLabel(operation) {
|
||||
switch (operation) {
|
||||
case "translate":
|
||||
return "Move";
|
||||
case "rotate":
|
||||
return "Rotate";
|
||||
case "scale":
|
||||
return "Scale";
|
||||
}
|
||||
}
|
||||
export function getTransformAxisLabel(axis) {
|
||||
return axis.toUpperCase();
|
||||
}
|
||||
export function getTransformTargetLabel(target) {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return "Whitebox Box";
|
||||
case "brushFace":
|
||||
return `Whitebox Face (${BOX_FACE_LABELS[target.faceId]})`;
|
||||
case "brushEdge":
|
||||
return `Whitebox Edge (${BOX_EDGE_LABELS[target.edgeId]})`;
|
||||
case "brushVertex":
|
||||
return `Whitebox Vertex (${BOX_VERTEX_LABELS[target.vertexId]})`;
|
||||
case "modelInstance":
|
||||
return getModelInstanceKindLabel();
|
||||
case "entity":
|
||||
return getEntityKindLabel(target.entityKind);
|
||||
}
|
||||
}
|
||||
export function getSupportedTransformOperations(target) {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "brushVertex":
|
||||
return ["translate"];
|
||||
case "modelInstance":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "entity":
|
||||
return target.initialRotation.kind === "none" ? ["translate"] : ["translate", "rotate"];
|
||||
}
|
||||
}
|
||||
export function supportsTransformOperation(target, operation) {
|
||||
return getSupportedTransformOperations(target).includes(operation);
|
||||
}
|
||||
export function supportsTransformAxisConstraint(session, axis) {
|
||||
switch (session.operation) {
|
||||
case "translate":
|
||||
return true;
|
||||
case "scale":
|
||||
if (session.target.kind === "modelInstance" || session.target.kind === "brush" || session.target.kind === "brushVertex") {
|
||||
return session.target.kind !== "brushVertex";
|
||||
}
|
||||
if (session.target.kind === "brushFace") {
|
||||
const normalAxis = session.target.faceId === "posX" || session.target.faceId === "negX" ? "x" : session.target.faceId === "posY" || session.target.faceId === "negY" ? "y" : "z";
|
||||
return axis === normalAxis;
|
||||
}
|
||||
if (session.target.kind === "brushEdge") {
|
||||
if (session.target.edgeId.startsWith("edgeX_")) {
|
||||
return axis !== "x";
|
||||
}
|
||||
if (session.target.edgeId.startsWith("edgeY_")) {
|
||||
return axis !== "y";
|
||||
}
|
||||
return axis !== "z";
|
||||
}
|
||||
return false;
|
||||
case "rotate":
|
||||
if (session.target.kind === "entity" && session.target.initialRotation.kind === "yaw") {
|
||||
return axis === "y";
|
||||
}
|
||||
if (session.target.kind === "brushFace") {
|
||||
const normalAxis = session.target.faceId === "posX" || session.target.faceId === "negX" ? "x" : session.target.faceId === "posY" || session.target.faceId === "negY" ? "y" : "z";
|
||||
return axis === normalAxis;
|
||||
}
|
||||
if (session.target.kind === "brushEdge") {
|
||||
if (session.target.edgeId.startsWith("edgeX_")) {
|
||||
return axis === "x";
|
||||
}
|
||||
if (session.target.edgeId.startsWith("edgeY_")) {
|
||||
return axis === "y";
|
||||
}
|
||||
return axis === "z";
|
||||
}
|
||||
if (session.target.kind === "brushVertex") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
function resolveEntityRotation(entity) {
|
||||
switch (entity.kind) {
|
||||
case "playerStart":
|
||||
case "teleportTarget":
|
||||
return {
|
||||
kind: "yaw",
|
||||
yawDegrees: entity.yawDegrees
|
||||
};
|
||||
case "spotLight":
|
||||
return {
|
||||
kind: "direction",
|
||||
direction: cloneVec3(entity.direction)
|
||||
};
|
||||
case "pointLight":
|
||||
case "soundEmitter":
|
||||
case "triggerVolume":
|
||||
case "interactable":
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
}
|
||||
function createBrushTransformTarget(document, brushId) {
|
||||
const brush = document.brushes[brushId];
|
||||
if (brush === undefined || brush.kind !== "box") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a supported whitebox box before transforming it."
|
||||
};
|
||||
}
|
||||
return {
|
||||
target: {
|
||||
kind: "brush",
|
||||
brushId: brush.id,
|
||||
initialCenter: cloneVec3(brush.center),
|
||||
initialRotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
initialSize: cloneVec3(brush.size),
|
||||
initialGeometry: cloneBoxBrushGeometry(brush.geometry)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
function createBrushFaceTransformTarget(document, brushId, faceId) {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
|
||||
return brushResolution;
|
||||
}
|
||||
return {
|
||||
target: {
|
||||
kind: "brushFace",
|
||||
brushId,
|
||||
faceId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
function createBrushEdgeTransformTarget(document, brushId, edgeId) {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
|
||||
return brushResolution;
|
||||
}
|
||||
return {
|
||||
target: {
|
||||
kind: "brushEdge",
|
||||
brushId,
|
||||
edgeId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
function createBrushVertexTransformTarget(document, brushId, vertexId) {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
if (brushResolution.target === null || brushResolution.target.kind !== "brush") {
|
||||
return brushResolution;
|
||||
}
|
||||
return {
|
||||
target: {
|
||||
kind: "brushVertex",
|
||||
brushId,
|
||||
vertexId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(brushResolution.target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(brushResolution.target.initialGeometry)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
function createEntityTransformTarget(document, entityId) {
|
||||
const entity = document.entities[entityId];
|
||||
if (entity === undefined) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select an authored entity before transforming it."
|
||||
};
|
||||
}
|
||||
const clonedEntity = cloneEntityInstance(entity);
|
||||
return {
|
||||
target: {
|
||||
kind: "entity",
|
||||
entityId: clonedEntity.id,
|
||||
entityKind: clonedEntity.kind,
|
||||
initialPosition: cloneVec3(clonedEntity.position),
|
||||
initialRotation: resolveEntityRotation(clonedEntity)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
function createModelInstanceTransformTarget(document, modelInstanceId) {
|
||||
const modelInstance = document.modelInstances[modelInstanceId];
|
||||
if (modelInstance === undefined) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a model instance before transforming it."
|
||||
};
|
||||
}
|
||||
const clonedModelInstance = cloneModelInstance(modelInstance);
|
||||
return {
|
||||
target: {
|
||||
kind: "modelInstance",
|
||||
modelInstanceId: clonedModelInstance.id,
|
||||
assetId: clonedModelInstance.assetId,
|
||||
initialPosition: cloneVec3(clonedModelInstance.position),
|
||||
initialRotationDegrees: cloneVec3(clonedModelInstance.rotationDegrees),
|
||||
initialScale: cloneVec3(clonedModelInstance.scale)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
export function resolveTransformTarget(document, selection, whiteboxSelectionMode = "object") {
|
||||
switch (selection.kind) {
|
||||
case "none":
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single brush, entity, or model instance before transforming it."
|
||||
};
|
||||
case "brushFace":
|
||||
if (whiteboxSelectionMode !== "face") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Face mode to transform a selected whitebox face."
|
||||
};
|
||||
}
|
||||
return createBrushFaceTransformTarget(document, selection.brushId, selection.faceId);
|
||||
case "brushEdge":
|
||||
if (whiteboxSelectionMode !== "edge") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Edge mode to transform a selected whitebox edge."
|
||||
};
|
||||
}
|
||||
return createBrushEdgeTransformTarget(document, selection.brushId, selection.edgeId);
|
||||
case "brushVertex":
|
||||
if (whiteboxSelectionMode !== "vertex") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Vertex mode to transform a selected whitebox vertex."
|
||||
};
|
||||
}
|
||||
return createBrushVertexTransformTarget(document, selection.brushId, selection.vertexId);
|
||||
case "brushes":
|
||||
if (whiteboxSelectionMode !== "object") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
}
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single brush before transforming it."
|
||||
};
|
||||
}
|
||||
return createBrushTransformTarget(document, selection.ids[0]);
|
||||
case "entities":
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single entity before transforming it."
|
||||
};
|
||||
}
|
||||
return createEntityTransformTarget(document, selection.ids[0]);
|
||||
case "modelInstances":
|
||||
if (selection.ids.length !== 1) {
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single model instance before transforming it."
|
||||
};
|
||||
}
|
||||
return createModelInstanceTransformTarget(document, selection.ids[0]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,17 @@ import { createOpaqueId } from "./ids";
|
||||
import type { EditorSelection } from "./selection";
|
||||
import type { WhiteboxSelectionMode } from "./whitebox-selection-mode";
|
||||
import type { Vec3 } from "./vector";
|
||||
import {
|
||||
BOX_VERTEX_IDS,
|
||||
BOX_EDGE_LABELS,
|
||||
BOX_FACE_LABELS,
|
||||
BOX_VERTEX_LABELS,
|
||||
cloneBoxBrushGeometry,
|
||||
type BoxBrushGeometry,
|
||||
type BoxEdgeId,
|
||||
type BoxFaceId,
|
||||
type BoxVertexId
|
||||
} from "../document/brushes";
|
||||
import type { SceneDocument } from "../document/scene-document";
|
||||
import {
|
||||
cloneEntityInstance,
|
||||
@@ -9,11 +20,15 @@ import {
|
||||
type EntityInstance,
|
||||
type EntityKind
|
||||
} from "../entities/entity-instances";
|
||||
import { cloneModelInstance, getModelInstanceKindLabel } from "../assets/model-instances";
|
||||
import {
|
||||
cloneModelInstance,
|
||||
getModelInstanceKindLabel
|
||||
} from "../assets/model-instances";
|
||||
import type { ViewportPanelId } from "../viewport-three/viewport-layout";
|
||||
|
||||
export type TransformOperation = "translate" | "rotate" | "scale";
|
||||
export type TransformAxis = "x" | "y" | "z";
|
||||
export type TransformAxisSpace = "world" | "local";
|
||||
export type TransformSessionSource = "keyboard" | "gizmo" | "toolbar";
|
||||
|
||||
export interface YawEntityRotationState {
|
||||
@@ -30,7 +45,10 @@ export interface NoEntityRotationState {
|
||||
kind: "none";
|
||||
}
|
||||
|
||||
export type EntityTransformRotationState = NoEntityRotationState | YawEntityRotationState | DirectionEntityRotationState;
|
||||
export type EntityTransformRotationState =
|
||||
| NoEntityRotationState
|
||||
| YawEntityRotationState
|
||||
| DirectionEntityRotationState;
|
||||
|
||||
export interface BrushTransformTarget {
|
||||
kind: "brush";
|
||||
@@ -38,6 +56,37 @@ export interface BrushTransformTarget {
|
||||
initialCenter: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialSize: Vec3;
|
||||
initialGeometry: BoxBrushGeometry;
|
||||
}
|
||||
|
||||
export interface BrushFaceTransformTarget {
|
||||
kind: "brushFace";
|
||||
brushId: string;
|
||||
faceId: BoxFaceId;
|
||||
initialCenter: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialSize: Vec3;
|
||||
initialGeometry: BoxBrushGeometry;
|
||||
}
|
||||
|
||||
export interface BrushEdgeTransformTarget {
|
||||
kind: "brushEdge";
|
||||
brushId: string;
|
||||
edgeId: BoxEdgeId;
|
||||
initialCenter: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialSize: Vec3;
|
||||
initialGeometry: BoxBrushGeometry;
|
||||
}
|
||||
|
||||
export interface BrushVertexTransformTarget {
|
||||
kind: "brushVertex";
|
||||
brushId: string;
|
||||
vertexId: BoxVertexId;
|
||||
initialCenter: Vec3;
|
||||
initialRotationDegrees: Vec3;
|
||||
initialSize: Vec3;
|
||||
initialGeometry: BoxBrushGeometry;
|
||||
}
|
||||
|
||||
export interface ModelInstanceTransformTarget {
|
||||
@@ -57,13 +106,31 @@ export interface EntityTransformTarget {
|
||||
initialRotation: EntityTransformRotationState;
|
||||
}
|
||||
|
||||
export type TransformTarget = BrushTransformTarget | ModelInstanceTransformTarget | EntityTransformTarget;
|
||||
export type TransformTarget =
|
||||
| BrushTransformTarget
|
||||
| BrushFaceTransformTarget
|
||||
| BrushEdgeTransformTarget
|
||||
| BrushVertexTransformTarget
|
||||
| ModelInstanceTransformTarget
|
||||
| EntityTransformTarget;
|
||||
|
||||
export interface BrushTransformPreview {
|
||||
kind: "brush";
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
geometry: BoxBrushGeometry;
|
||||
}
|
||||
|
||||
function areBrushGeometriesEqual(
|
||||
left: BoxBrushGeometry,
|
||||
right: BoxBrushGeometry
|
||||
): boolean {
|
||||
return BOX_VERTEX_IDS.every((vertexId) => {
|
||||
const leftVertex = left.vertices[vertexId];
|
||||
const rightVertex = right.vertices[vertexId];
|
||||
return areVec3Equal(leftVertex, rightVertex);
|
||||
});
|
||||
}
|
||||
|
||||
export interface ModelInstanceTransformPreview {
|
||||
@@ -79,7 +146,10 @@ export interface EntityTransformPreview {
|
||||
rotation: EntityTransformRotationState;
|
||||
}
|
||||
|
||||
export type TransformPreview = BrushTransformPreview | ModelInstanceTransformPreview | EntityTransformPreview;
|
||||
export type TransformPreview =
|
||||
| BrushTransformPreview
|
||||
| ModelInstanceTransformPreview
|
||||
| EntityTransformPreview;
|
||||
|
||||
export interface ActiveTransformSession {
|
||||
kind: "active";
|
||||
@@ -88,6 +158,7 @@ export interface ActiveTransformSession {
|
||||
sourcePanelId: ViewportPanelId;
|
||||
operation: TransformOperation;
|
||||
axisConstraint: TransformAxis | null;
|
||||
axisConstraintSpace: TransformAxisSpace;
|
||||
target: TransformTarget;
|
||||
preview: TransformPreview;
|
||||
}
|
||||
@@ -111,7 +182,9 @@ function areVec3Equal(left: Vec3, right: Vec3): boolean {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
|
||||
function cloneEntityTransformRotationState(rotation: EntityTransformRotationState): EntityTransformRotationState {
|
||||
function cloneEntityTransformRotationState(
|
||||
rotation: EntityTransformRotationState
|
||||
): EntityTransformRotationState {
|
||||
switch (rotation.kind) {
|
||||
case "none":
|
||||
return {
|
||||
@@ -130,7 +203,10 @@ function cloneEntityTransformRotationState(rotation: EntityTransformRotationStat
|
||||
}
|
||||
}
|
||||
|
||||
function areEntityTransformRotationsEqual(left: EntityTransformRotationState, right: EntityTransformRotationState): boolean {
|
||||
function areEntityTransformRotationsEqual(
|
||||
left: EntityTransformRotationState,
|
||||
right: EntityTransformRotationState
|
||||
): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
@@ -141,7 +217,10 @@ function areEntityTransformRotationsEqual(left: EntityTransformRotationState, ri
|
||||
case "yaw":
|
||||
return right.kind === "yaw" && left.yawDegrees === right.yawDegrees;
|
||||
case "direction":
|
||||
return right.kind === "direction" && areVec3Equal(left.direction, right.direction);
|
||||
return (
|
||||
right.kind === "direction" &&
|
||||
areVec3Equal(left.direction, right.direction)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,7 +238,38 @@ export function cloneTransformTarget(target: TransformTarget): TransformTarget {
|
||||
brushId: target.brushId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize)
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushFace":
|
||||
return {
|
||||
kind: "brushFace",
|
||||
brushId: target.brushId,
|
||||
faceId: target.faceId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushEdge":
|
||||
return {
|
||||
kind: "brushEdge",
|
||||
brushId: target.brushId,
|
||||
edgeId: target.edgeId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "brushVertex":
|
||||
return {
|
||||
kind: "brushVertex",
|
||||
brushId: target.brushId,
|
||||
vertexId: target.vertexId,
|
||||
initialCenter: cloneVec3(target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
initialSize: cloneVec3(target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
@@ -176,19 +286,24 @@ export function cloneTransformTarget(target: TransformTarget): TransformTarget {
|
||||
entityId: target.entityId,
|
||||
entityKind: target.entityKind,
|
||||
initialPosition: cloneVec3(target.initialPosition),
|
||||
initialRotation: cloneEntityTransformRotationState(target.initialRotation)
|
||||
initialRotation: cloneEntityTransformRotationState(
|
||||
target.initialRotation
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function cloneTransformPreview(preview: TransformPreview): TransformPreview {
|
||||
export function cloneTransformPreview(
|
||||
preview: TransformPreview
|
||||
): TransformPreview {
|
||||
switch (preview.kind) {
|
||||
case "brush":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(preview.center),
|
||||
rotationDegrees: cloneVec3(preview.rotationDegrees),
|
||||
size: cloneVec3(preview.size)
|
||||
size: cloneVec3(preview.size),
|
||||
geometry: cloneBoxBrushGeometry(preview.geometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
@@ -206,7 +321,9 @@ export function cloneTransformPreview(preview: TransformPreview): TransformPrevi
|
||||
}
|
||||
}
|
||||
|
||||
export function cloneTransformSession(session: TransformSessionState): TransformSessionState {
|
||||
export function cloneTransformSession(
|
||||
session: TransformSessionState
|
||||
): TransformSessionState {
|
||||
if (session.kind === "none") {
|
||||
return session;
|
||||
}
|
||||
@@ -218,12 +335,16 @@ export function cloneTransformSession(session: TransformSessionState): Transform
|
||||
sourcePanelId: session.sourcePanelId,
|
||||
operation: session.operation,
|
||||
axisConstraint: session.axisConstraint,
|
||||
axisConstraintSpace: session.axisConstraintSpace,
|
||||
target: cloneTransformTarget(session.target),
|
||||
preview: cloneTransformPreview(session.preview)
|
||||
};
|
||||
}
|
||||
|
||||
export function areTransformSessionsEqual(left: TransformSessionState, right: TransformSessionState): boolean {
|
||||
export function areTransformSessionsEqual(
|
||||
left: TransformSessionState,
|
||||
right: TransformSessionState
|
||||
): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
@@ -238,12 +359,16 @@ export function areTransformSessionsEqual(left: TransformSessionState, right: Tr
|
||||
left.sourcePanelId === right.sourcePanelId &&
|
||||
left.operation === right.operation &&
|
||||
left.axisConstraint === right.axisConstraint &&
|
||||
left.axisConstraintSpace === right.axisConstraintSpace &&
|
||||
areTransformTargetsEqual(left.target, right.target) &&
|
||||
areTransformPreviewsEqual(left.preview, right.preview)
|
||||
);
|
||||
}
|
||||
|
||||
function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget): boolean {
|
||||
function areTransformTargetsEqual(
|
||||
left: TransformTarget,
|
||||
right: TransformTarget
|
||||
): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
@@ -254,8 +379,51 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
|
||||
right.kind === "brush" &&
|
||||
left.brushId === right.brushId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize)
|
||||
areVec3Equal(
|
||||
left.initialRotationDegrees,
|
||||
right.initialRotationDegrees
|
||||
) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
|
||||
);
|
||||
case "brushFace":
|
||||
return (
|
||||
right.kind === "brushFace" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.faceId === right.faceId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(
|
||||
left.initialRotationDegrees,
|
||||
right.initialRotationDegrees
|
||||
) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
|
||||
);
|
||||
case "brushEdge":
|
||||
return (
|
||||
right.kind === "brushEdge" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.edgeId === right.edgeId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(
|
||||
left.initialRotationDegrees,
|
||||
right.initialRotationDegrees
|
||||
) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
|
||||
);
|
||||
case "brushVertex":
|
||||
return (
|
||||
right.kind === "brushVertex" &&
|
||||
left.brushId === right.brushId &&
|
||||
left.vertexId === right.vertexId &&
|
||||
areVec3Equal(left.initialCenter, right.initialCenter) &&
|
||||
areVec3Equal(
|
||||
left.initialRotationDegrees,
|
||||
right.initialRotationDegrees
|
||||
) &&
|
||||
areVec3Equal(left.initialSize, right.initialSize) &&
|
||||
areBrushGeometriesEqual(left.initialGeometry, right.initialGeometry)
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
@@ -263,7 +431,10 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
|
||||
left.modelInstanceId === right.modelInstanceId &&
|
||||
left.assetId === right.assetId &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areVec3Equal(left.initialRotationDegrees, right.initialRotationDegrees) &&
|
||||
areVec3Equal(
|
||||
left.initialRotationDegrees,
|
||||
right.initialRotationDegrees
|
||||
) &&
|
||||
areVec3Equal(left.initialScale, right.initialScale)
|
||||
);
|
||||
case "entity":
|
||||
@@ -272,12 +443,18 @@ function areTransformTargetsEqual(left: TransformTarget, right: TransformTarget)
|
||||
left.entityId === right.entityId &&
|
||||
left.entityKind === right.entityKind &&
|
||||
areVec3Equal(left.initialPosition, right.initialPosition) &&
|
||||
areEntityTransformRotationsEqual(left.initialRotation, right.initialRotation)
|
||||
areEntityTransformRotationsEqual(
|
||||
left.initialRotation,
|
||||
right.initialRotation
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function areTransformPreviewsEqual(left: TransformPreview, right: TransformPreview): boolean {
|
||||
function areTransformPreviewsEqual(
|
||||
left: TransformPreview,
|
||||
right: TransformPreview
|
||||
): boolean {
|
||||
if (left.kind !== right.kind) {
|
||||
return false;
|
||||
}
|
||||
@@ -288,7 +465,8 @@ function areTransformPreviewsEqual(left: TransformPreview, right: TransformPrevi
|
||||
right.kind === "brush" &&
|
||||
areVec3Equal(left.center, right.center) &&
|
||||
areVec3Equal(left.rotationDegrees, right.rotationDegrees) &&
|
||||
areVec3Equal(left.size, right.size)
|
||||
areVec3Equal(left.size, right.size) &&
|
||||
areBrushGeometriesEqual(left.geometry, right.geometry)
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
@@ -298,7 +476,11 @@ function areTransformPreviewsEqual(left: TransformPreview, right: TransformPrevi
|
||||
areVec3Equal(left.scale, right.scale)
|
||||
);
|
||||
case "entity":
|
||||
return right.kind === "entity" && areVec3Equal(left.position, right.position) && areEntityTransformRotationsEqual(left.rotation, right.rotation);
|
||||
return (
|
||||
right.kind === "entity" &&
|
||||
areVec3Equal(left.position, right.position) &&
|
||||
areEntityTransformRotationsEqual(left.rotation, right.rotation)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +489,7 @@ export function createTransformSession(options: {
|
||||
sourcePanelId: ViewportPanelId;
|
||||
operation: TransformOperation;
|
||||
axisConstraint?: TransformAxis | null;
|
||||
axisConstraintSpace?: TransformAxisSpace;
|
||||
target: TransformTarget;
|
||||
}): ActiveTransformSession {
|
||||
return {
|
||||
@@ -316,19 +499,26 @@ export function createTransformSession(options: {
|
||||
sourcePanelId: options.sourcePanelId,
|
||||
operation: options.operation,
|
||||
axisConstraint: options.axisConstraint ?? null,
|
||||
axisConstraintSpace: options.axisConstraintSpace ?? "world",
|
||||
target: cloneTransformTarget(options.target),
|
||||
preview: createTransformPreviewFromTarget(options.target)
|
||||
};
|
||||
}
|
||||
|
||||
export function createTransformPreviewFromTarget(target: TransformTarget): TransformPreview {
|
||||
export function createTransformPreviewFromTarget(
|
||||
target: TransformTarget
|
||||
): TransformPreview {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return {
|
||||
kind: "brush",
|
||||
center: cloneVec3(target.initialCenter),
|
||||
rotationDegrees: cloneVec3(target.initialRotationDegrees),
|
||||
size: cloneVec3(target.initialSize)
|
||||
size: cloneVec3(target.initialSize),
|
||||
geometry: cloneBoxBrushGeometry(target.initialGeometry)
|
||||
};
|
||||
case "modelInstance":
|
||||
return {
|
||||
@@ -346,32 +536,58 @@ export function createTransformPreviewFromTarget(target: TransformTarget): Trans
|
||||
}
|
||||
}
|
||||
|
||||
export function doesTransformSessionChangeTarget(session: ActiveTransformSession): boolean {
|
||||
export function doesTransformSessionChangeTarget(
|
||||
session: ActiveTransformSession
|
||||
): boolean {
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return (
|
||||
session.preview.kind === "brush" &&
|
||||
(!areVec3Equal(session.preview.center, session.target.initialCenter) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
!areVec3Equal(session.preview.size, session.target.initialSize))
|
||||
!areVec3Equal(
|
||||
session.preview.rotationDegrees,
|
||||
session.target.initialRotationDegrees
|
||||
) ||
|
||||
!areVec3Equal(session.preview.size, session.target.initialSize) ||
|
||||
!areBrushGeometriesEqual(
|
||||
session.preview.geometry,
|
||||
session.target.initialGeometry
|
||||
))
|
||||
);
|
||||
case "modelInstance":
|
||||
return (
|
||||
session.preview.kind === "modelInstance" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areVec3Equal(session.preview.rotationDegrees, session.target.initialRotationDegrees) ||
|
||||
(!areVec3Equal(
|
||||
session.preview.position,
|
||||
session.target.initialPosition
|
||||
) ||
|
||||
!areVec3Equal(
|
||||
session.preview.rotationDegrees,
|
||||
session.target.initialRotationDegrees
|
||||
) ||
|
||||
!areVec3Equal(session.preview.scale, session.target.initialScale))
|
||||
);
|
||||
case "entity":
|
||||
return (
|
||||
session.preview.kind === "entity" &&
|
||||
(!areVec3Equal(session.preview.position, session.target.initialPosition) ||
|
||||
!areEntityTransformRotationsEqual(session.preview.rotation, session.target.initialRotation))
|
||||
(!areVec3Equal(
|
||||
session.preview.position,
|
||||
session.target.initialPosition
|
||||
) ||
|
||||
!areEntityTransformRotationsEqual(
|
||||
session.preview.rotation,
|
||||
session.target.initialRotation
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function getTransformOperationLabel(operation: TransformOperation): string {
|
||||
export function getTransformOperationLabel(
|
||||
operation: TransformOperation
|
||||
): string {
|
||||
switch (operation) {
|
||||
case "translate":
|
||||
return "Move";
|
||||
@@ -386,10 +602,27 @@ export function getTransformAxisLabel(axis: TransformAxis): string {
|
||||
return axis.toUpperCase();
|
||||
}
|
||||
|
||||
export function getTransformAxisSpaceLabel(
|
||||
axisSpace: TransformAxisSpace
|
||||
): string {
|
||||
switch (axisSpace) {
|
||||
case "world":
|
||||
return "World";
|
||||
case "local":
|
||||
return "Local";
|
||||
}
|
||||
}
|
||||
|
||||
export function getTransformTargetLabel(target: TransformTarget): string {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
return "Whitebox Box";
|
||||
case "brushFace":
|
||||
return `Whitebox Face (${BOX_FACE_LABELS[target.faceId]})`;
|
||||
case "brushEdge":
|
||||
return `Whitebox Edge (${BOX_EDGE_LABELS[target.edgeId]})`;
|
||||
case "brushVertex":
|
||||
return `Whitebox Vertex (${BOX_VERTEX_LABELS[target.vertexId]})`;
|
||||
case "modelInstance":
|
||||
return getModelInstanceKindLabel();
|
||||
case "entity":
|
||||
@@ -397,39 +630,142 @@ export function getTransformTargetLabel(target: TransformTarget): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function getSupportedTransformOperations(target: TransformTarget): TransformOperation[] {
|
||||
export function getSupportedTransformOperations(
|
||||
target: TransformTarget
|
||||
): TransformOperation[] {
|
||||
switch (target.kind) {
|
||||
case "brush":
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "brushVertex":
|
||||
return ["translate"];
|
||||
case "modelInstance":
|
||||
return ["translate", "rotate", "scale"];
|
||||
case "entity":
|
||||
return target.initialRotation.kind === "none" ? ["translate"] : ["translate", "rotate"];
|
||||
return target.initialRotation.kind === "none"
|
||||
? ["translate"]
|
||||
: ["translate", "rotate"];
|
||||
}
|
||||
}
|
||||
|
||||
export function supportsTransformOperation(target: TransformTarget, operation: TransformOperation): boolean {
|
||||
export function supportsTransformOperation(
|
||||
target: TransformTarget,
|
||||
operation: TransformOperation
|
||||
): boolean {
|
||||
return getSupportedTransformOperations(target).includes(operation);
|
||||
}
|
||||
|
||||
export function supportsTransformAxisConstraint(session: ActiveTransformSession, axis: TransformAxis): boolean {
|
||||
export function supportsTransformAxisConstraint(
|
||||
session: ActiveTransformSession,
|
||||
axis: TransformAxis
|
||||
): boolean {
|
||||
switch (session.operation) {
|
||||
case "translate":
|
||||
return true;
|
||||
case "scale":
|
||||
return session.target.kind === "modelInstance" || session.target.kind === "brush";
|
||||
if (
|
||||
session.target.kind === "modelInstance" ||
|
||||
session.target.kind === "brush" ||
|
||||
session.target.kind === "brushVertex"
|
||||
) {
|
||||
return session.target.kind !== "brushVertex";
|
||||
}
|
||||
|
||||
if (session.target.kind === "brushFace") {
|
||||
const normalAxis =
|
||||
session.target.faceId === "posX" || session.target.faceId === "negX"
|
||||
? "x"
|
||||
: session.target.faceId === "posY" ||
|
||||
session.target.faceId === "negY"
|
||||
? "y"
|
||||
: "z";
|
||||
return axis === normalAxis;
|
||||
}
|
||||
|
||||
if (session.target.kind === "brushEdge") {
|
||||
if (session.target.edgeId.startsWith("edgeX_")) {
|
||||
return axis !== "x";
|
||||
}
|
||||
|
||||
if (session.target.edgeId.startsWith("edgeY_")) {
|
||||
return axis !== "y";
|
||||
}
|
||||
|
||||
return axis !== "z";
|
||||
}
|
||||
|
||||
return false;
|
||||
case "rotate":
|
||||
if (session.target.kind === "entity" && session.target.initialRotation.kind === "yaw") {
|
||||
if (
|
||||
session.target.kind === "entity" &&
|
||||
session.target.initialRotation.kind === "yaw"
|
||||
) {
|
||||
return axis === "y";
|
||||
}
|
||||
|
||||
if (session.target.kind === "brushFace") {
|
||||
const normalAxis =
|
||||
session.target.faceId === "posX" || session.target.faceId === "negX"
|
||||
? "x"
|
||||
: session.target.faceId === "posY" ||
|
||||
session.target.faceId === "negY"
|
||||
? "y"
|
||||
: "z";
|
||||
return axis === normalAxis;
|
||||
}
|
||||
|
||||
if (session.target.kind === "brushEdge") {
|
||||
if (session.target.edgeId.startsWith("edgeX_")) {
|
||||
return axis === "x";
|
||||
}
|
||||
|
||||
if (session.target.edgeId.startsWith("edgeY_")) {
|
||||
return axis === "y";
|
||||
}
|
||||
|
||||
return axis === "z";
|
||||
}
|
||||
|
||||
if (session.target.kind === "brushVertex") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEntityRotation(entity: EntityInstance): EntityTransformRotationState {
|
||||
export function supportsLocalTransformAxisConstraint(
|
||||
session: ActiveTransformSession,
|
||||
axis: TransformAxis
|
||||
): boolean {
|
||||
if (!supportsTransformAxisConstraint(session, axis)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (session.operation === "scale") {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (session.target.kind) {
|
||||
case "brush":
|
||||
case "modelInstance":
|
||||
return true;
|
||||
case "entity":
|
||||
return session.target.initialRotation.kind !== "none";
|
||||
case "brushFace":
|
||||
case "brushEdge":
|
||||
case "brushVertex":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEntityRotation(
|
||||
entity: EntityInstance
|
||||
): EntityTransformRotationState {
|
||||
switch (entity.kind) {
|
||||
case "playerStart":
|
||||
case "sceneEntry":
|
||||
case "teleportTarget":
|
||||
return {
|
||||
kind: "yaw",
|
||||
@@ -444,13 +780,17 @@ function resolveEntityRotation(entity: EntityInstance): EntityTransformRotationS
|
||||
case "soundEmitter":
|
||||
case "triggerVolume":
|
||||
case "interactable":
|
||||
case "sceneExit":
|
||||
return {
|
||||
kind: "none"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function createBrushTransformTarget(document: SceneDocument, brushId: string): TransformTargetResolution {
|
||||
function createBrushTransformTarget(
|
||||
document: SceneDocument,
|
||||
brushId: string
|
||||
): TransformTargetResolution {
|
||||
const brush = document.brushes[brushId];
|
||||
|
||||
if (brush === undefined || brush.kind !== "box") {
|
||||
@@ -466,13 +806,113 @@ function createBrushTransformTarget(document: SceneDocument, brushId: string): T
|
||||
brushId: brush.id,
|
||||
initialCenter: cloneVec3(brush.center),
|
||||
initialRotationDegrees: cloneVec3(brush.rotationDegrees),
|
||||
initialSize: cloneVec3(brush.size)
|
||||
initialSize: cloneVec3(brush.size),
|
||||
initialGeometry: cloneBoxBrushGeometry(brush.geometry)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createEntityTransformTarget(document: SceneDocument, entityId: string): TransformTargetResolution {
|
||||
function createBrushFaceTransformTarget(
|
||||
document: SceneDocument,
|
||||
brushId: string,
|
||||
faceId: BoxFaceId
|
||||
): TransformTargetResolution {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
|
||||
if (
|
||||
brushResolution.target === null ||
|
||||
brushResolution.target.kind !== "brush"
|
||||
) {
|
||||
return brushResolution;
|
||||
}
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "brushFace",
|
||||
brushId,
|
||||
faceId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(
|
||||
brushResolution.target.initialRotationDegrees
|
||||
),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(
|
||||
brushResolution.target.initialGeometry
|
||||
)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createBrushEdgeTransformTarget(
|
||||
document: SceneDocument,
|
||||
brushId: string,
|
||||
edgeId: BoxEdgeId
|
||||
): TransformTargetResolution {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
|
||||
if (
|
||||
brushResolution.target === null ||
|
||||
brushResolution.target.kind !== "brush"
|
||||
) {
|
||||
return brushResolution;
|
||||
}
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "brushEdge",
|
||||
brushId,
|
||||
edgeId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(
|
||||
brushResolution.target.initialRotationDegrees
|
||||
),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(
|
||||
brushResolution.target.initialGeometry
|
||||
)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createBrushVertexTransformTarget(
|
||||
document: SceneDocument,
|
||||
brushId: string,
|
||||
vertexId: BoxVertexId
|
||||
): TransformTargetResolution {
|
||||
const brushResolution = createBrushTransformTarget(document, brushId);
|
||||
|
||||
if (
|
||||
brushResolution.target === null ||
|
||||
brushResolution.target.kind !== "brush"
|
||||
) {
|
||||
return brushResolution;
|
||||
}
|
||||
|
||||
return {
|
||||
target: {
|
||||
kind: "brushVertex",
|
||||
brushId,
|
||||
vertexId,
|
||||
initialCenter: cloneVec3(brushResolution.target.initialCenter),
|
||||
initialRotationDegrees: cloneVec3(
|
||||
brushResolution.target.initialRotationDegrees
|
||||
),
|
||||
initialSize: cloneVec3(brushResolution.target.initialSize),
|
||||
initialGeometry: cloneBoxBrushGeometry(
|
||||
brushResolution.target.initialGeometry
|
||||
)
|
||||
},
|
||||
message: null
|
||||
};
|
||||
}
|
||||
|
||||
function createEntityTransformTarget(
|
||||
document: SceneDocument,
|
||||
entityId: string
|
||||
): TransformTargetResolution {
|
||||
const entity = document.entities[entityId];
|
||||
|
||||
if (entity === undefined) {
|
||||
@@ -496,7 +936,10 @@ function createEntityTransformTarget(document: SceneDocument, entityId: string):
|
||||
};
|
||||
}
|
||||
|
||||
function createModelInstanceTransformTarget(document: SceneDocument, modelInstanceId: string): TransformTargetResolution {
|
||||
function createModelInstanceTransformTarget(
|
||||
document: SceneDocument,
|
||||
modelInstanceId: string
|
||||
): TransformTargetResolution {
|
||||
const modelInstance = document.modelInstances[modelInstanceId];
|
||||
|
||||
if (modelInstance === undefined) {
|
||||
@@ -530,23 +973,49 @@ export function resolveTransformTarget(
|
||||
case "none":
|
||||
return {
|
||||
target: null,
|
||||
message: "Select a single brush, entity, or model instance before transforming it."
|
||||
message:
|
||||
"Select a single brush, entity, or model instance before transforming it."
|
||||
};
|
||||
case "brushFace":
|
||||
return {
|
||||
target: null,
|
||||
message: "Face selection is component-only in this slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
if (whiteboxSelectionMode !== "face") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Face mode to transform a selected whitebox face."
|
||||
};
|
||||
}
|
||||
|
||||
return createBrushFaceTransformTarget(
|
||||
document,
|
||||
selection.brushId,
|
||||
selection.faceId
|
||||
);
|
||||
case "brushEdge":
|
||||
return {
|
||||
target: null,
|
||||
message: "Edge transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
if (whiteboxSelectionMode !== "edge") {
|
||||
return {
|
||||
target: null,
|
||||
message: "Switch to Edge mode to transform a selected whitebox edge."
|
||||
};
|
||||
}
|
||||
|
||||
return createBrushEdgeTransformTarget(
|
||||
document,
|
||||
selection.brushId,
|
||||
selection.edgeId
|
||||
);
|
||||
case "brushVertex":
|
||||
return {
|
||||
target: null,
|
||||
message: "Vertex transforms land in the next whitebox slice. Switch to Object mode to transform the whole whitebox box."
|
||||
};
|
||||
if (whiteboxSelectionMode !== "vertex") {
|
||||
return {
|
||||
target: null,
|
||||
message:
|
||||
"Switch to Vertex mode to transform a selected whitebox vertex."
|
||||
};
|
||||
}
|
||||
|
||||
return createBrushVertexTransformTarget(
|
||||
document,
|
||||
selection.brushId,
|
||||
selection.vertexId
|
||||
);
|
||||
case "brushes":
|
||||
if (whiteboxSelectionMode !== "object") {
|
||||
return {
|
||||
|
||||
5
src/core/vector.js
Normal file
5
src/core/vector.js
Normal file
@@ -0,0 +1,5 @@
|
||||
export const DEFAULT_SUN_DIRECTION = {
|
||||
x: -0.6,
|
||||
y: 1,
|
||||
z: 0.35
|
||||
};
|
||||
23
src/core/whitebox-selection-feedback.js
Normal file
23
src/core/whitebox-selection-feedback.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import { BOX_EDGE_LABELS, BOX_FACE_LABELS, BOX_VERTEX_LABELS } from "../document/brushes";
|
||||
function getBrushDisplayLabel(document, brushId) {
|
||||
const brushes = Object.values(document.brushes);
|
||||
const brushIndex = brushes.findIndex((brush) => brush.id === brushId);
|
||||
if (brushIndex === -1) {
|
||||
return "Whitebox Box";
|
||||
}
|
||||
return brushes[brushIndex].name ?? `Whitebox Box ${brushIndex + 1}`;
|
||||
}
|
||||
export function getWhiteboxSelectionFeedbackLabel(document, selection) {
|
||||
switch (selection.kind) {
|
||||
case "brushes":
|
||||
return selection.ids.length === 1 ? `Solid · ${getBrushDisplayLabel(document, selection.ids[0])}` : null;
|
||||
case "brushFace":
|
||||
return `Face · ${BOX_FACE_LABELS[selection.faceId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
case "brushEdge":
|
||||
return `Edge · ${BOX_EDGE_LABELS[selection.edgeId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
case "brushVertex":
|
||||
return `Vertex · ${BOX_VERTEX_LABELS[selection.vertexId]} · ${getBrushDisplayLabel(document, selection.brushId)}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
10
src/core/whitebox-selection-mode.js
Normal file
10
src/core/whitebox-selection-mode.js
Normal file
@@ -0,0 +1,10 @@
|
||||
export const WHITEBOX_SELECTION_MODES = ["object", "face", "edge", "vertex"];
|
||||
export const WHITEBOX_SELECTION_MODE_LABELS = {
|
||||
object: "Object",
|
||||
face: "Face",
|
||||
edge: "Edge",
|
||||
vertex: "Vertex"
|
||||
};
|
||||
export function getWhiteboxSelectionModeLabel(mode) {
|
||||
return WHITEBOX_SELECTION_MODE_LABELS[mode];
|
||||
}
|
||||
395
src/document/brushes.js
Normal file
395
src/document/brushes.js
Normal file
@@ -0,0 +1,395 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
export const BOX_FACE_IDS = ["posX", "negX", "posY", "negY", "posZ", "negZ"];
|
||||
export const BOX_EDGE_IDS = [
|
||||
"edgeX_negY_negZ",
|
||||
"edgeX_posY_negZ",
|
||||
"edgeX_negY_posZ",
|
||||
"edgeX_posY_posZ",
|
||||
"edgeY_negX_negZ",
|
||||
"edgeY_posX_negZ",
|
||||
"edgeY_negX_posZ",
|
||||
"edgeY_posX_posZ",
|
||||
"edgeZ_negX_negY",
|
||||
"edgeZ_posX_negY",
|
||||
"edgeZ_negX_posY",
|
||||
"edgeZ_posX_posY"
|
||||
];
|
||||
export const BOX_VERTEX_IDS = [
|
||||
"negX_negY_negZ",
|
||||
"posX_negY_negZ",
|
||||
"negX_posY_negZ",
|
||||
"posX_posY_negZ",
|
||||
"negX_negY_posZ",
|
||||
"posX_negY_posZ",
|
||||
"negX_posY_posZ",
|
||||
"posX_posY_posZ"
|
||||
];
|
||||
export const FACE_UV_ROTATION_QUARTER_TURNS = [0, 1, 2, 3];
|
||||
export const BOX_BRUSH_VOLUME_MODES = ["none", "water", "fog"];
|
||||
export const BOX_FACE_LABELS = {
|
||||
posX: "Right",
|
||||
negX: "Left",
|
||||
posY: "Top",
|
||||
negY: "Bottom",
|
||||
posZ: "Front",
|
||||
negZ: "Back"
|
||||
};
|
||||
export const BOX_EDGE_LABELS = {
|
||||
edgeX_negY_negZ: "X Edge (-Y, -Z)",
|
||||
edgeX_posY_negZ: "X Edge (+Y, -Z)",
|
||||
edgeX_negY_posZ: "X Edge (-Y, +Z)",
|
||||
edgeX_posY_posZ: "X Edge (+Y, +Z)",
|
||||
edgeY_negX_negZ: "Y Edge (-X, -Z)",
|
||||
edgeY_posX_negZ: "Y Edge (+X, -Z)",
|
||||
edgeY_negX_posZ: "Y Edge (-X, +Z)",
|
||||
edgeY_posX_posZ: "Y Edge (+X, +Z)",
|
||||
edgeZ_negX_negY: "Z Edge (-X, -Y)",
|
||||
edgeZ_posX_negY: "Z Edge (+X, -Y)",
|
||||
edgeZ_negX_posY: "Z Edge (-X, +Y)",
|
||||
edgeZ_posX_posY: "Z Edge (+X, +Y)"
|
||||
};
|
||||
export const BOX_VERTEX_LABELS = {
|
||||
negX_negY_negZ: "Vertex (-X, -Y, -Z)",
|
||||
posX_negY_negZ: "Vertex (+X, -Y, -Z)",
|
||||
negX_posY_negZ: "Vertex (-X, +Y, -Z)",
|
||||
posX_posY_negZ: "Vertex (+X, +Y, -Z)",
|
||||
negX_negY_posZ: "Vertex (-X, -Y, +Z)",
|
||||
posX_negY_posZ: "Vertex (+X, -Y, +Z)",
|
||||
negX_posY_posZ: "Vertex (-X, +Y, +Z)",
|
||||
posX_posY_posZ: "Vertex (+X, +Y, +Z)"
|
||||
};
|
||||
export const DEFAULT_BOX_BRUSH_CENTER = {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_BOX_BRUSH_SIZE = {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
};
|
||||
export const DEFAULT_BOX_BRUSH_ROTATION_DEGREES = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 6;
|
||||
export const MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 24;
|
||||
const DEFAULT_BOX_BRUSH_WATER_SETTINGS = {
|
||||
colorHex: "#4da6d9",
|
||||
surfaceOpacity: 0.55,
|
||||
waveStrength: 0.35,
|
||||
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT,
|
||||
surfaceDisplacementEnabled: false
|
||||
};
|
||||
const DEFAULT_BOX_BRUSH_FOG_SETTINGS = {
|
||||
colorHex: "#9cb7c7",
|
||||
density: 0.08,
|
||||
padding: 0.2
|
||||
};
|
||||
export function normalizeBrushName(name) {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
}
|
||||
const trimmedName = name.trim();
|
||||
return trimmedName.length === 0 ? undefined : trimmedName;
|
||||
}
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function cloneBrushFace(face) {
|
||||
return {
|
||||
materialId: face.materialId,
|
||||
uv: cloneFaceUvState(face.uv)
|
||||
};
|
||||
}
|
||||
function cloneBoxBrushGeometryVertex(vertex) {
|
||||
return {
|
||||
x: vertex.x,
|
||||
y: vertex.y,
|
||||
z: vertex.z
|
||||
};
|
||||
}
|
||||
export function cloneBoxBrushGeometry(geometry) {
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_negZ),
|
||||
posX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_negZ),
|
||||
negX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_negZ),
|
||||
posX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_negZ),
|
||||
negX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_posZ),
|
||||
posX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_posZ),
|
||||
negX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_posZ),
|
||||
posX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_posZ)
|
||||
}
|
||||
};
|
||||
}
|
||||
export function getBoxBrushGeometryLocalBounds(geometry) {
|
||||
const vertices = Object.values(geometry.vertices);
|
||||
const firstVertex = vertices[0];
|
||||
const min = { ...firstVertex };
|
||||
const max = { ...firstVertex };
|
||||
for (const vertex of vertices.slice(1)) {
|
||||
min.x = Math.min(min.x, vertex.x);
|
||||
min.y = Math.min(min.y, vertex.y);
|
||||
min.z = Math.min(min.z, vertex.z);
|
||||
max.x = Math.max(max.x, vertex.x);
|
||||
max.y = Math.max(max.y, vertex.y);
|
||||
max.z = Math.max(max.z, vertex.z);
|
||||
}
|
||||
return {
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
export function deriveBoxBrushSizeFromGeometry(geometry) {
|
||||
const bounds = getBoxBrushGeometryLocalBounds(geometry);
|
||||
return {
|
||||
x: bounds.max.x - bounds.min.x,
|
||||
y: bounds.max.y - bounds.min.y,
|
||||
z: bounds.max.z - bounds.min.z
|
||||
};
|
||||
}
|
||||
export function scaleBoxBrushGeometryToSize(geometry, size) {
|
||||
const bounds = getBoxBrushGeometryLocalBounds(geometry);
|
||||
const currentSize = deriveBoxBrushSizeFromGeometry(geometry);
|
||||
if (!hasPositiveBoxSize(currentSize) || !hasPositiveBoxSize(size)) {
|
||||
throw new Error("Box brush geometry size must remain positive on every axis.");
|
||||
}
|
||||
const center = {
|
||||
x: (bounds.min.x + bounds.max.x) * 0.5,
|
||||
y: (bounds.min.y + bounds.max.y) * 0.5,
|
||||
z: (bounds.min.z + bounds.max.z) * 0.5
|
||||
};
|
||||
const scale = {
|
||||
x: size.x / currentSize.x,
|
||||
y: size.y / currentSize.y,
|
||||
z: size.z / currentSize.z
|
||||
};
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: {
|
||||
x: center.x + (geometry.vertices.negX_negY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_negY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_negY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_negY_negZ: {
|
||||
x: center.x + (geometry.vertices.posX_negY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_negY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_negY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_posY_negZ: {
|
||||
x: center.x + (geometry.vertices.negX_posY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_posY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_posY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_posY_negZ: {
|
||||
x: center.x + (geometry.vertices.posX_posY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_posY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_posY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_negY_posZ: {
|
||||
x: center.x + (geometry.vertices.negX_negY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_negY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_negY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_negY_posZ: {
|
||||
x: center.x + (geometry.vertices.posX_negY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_negY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_negY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_posY_posZ: {
|
||||
x: center.x + (geometry.vertices.negX_posY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_posY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_posY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_posY_posZ: {
|
||||
x: center.x + (geometry.vertices.posX_posY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_posY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_posY_posZ.z - center.z) * scale.z
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createDefaultBoxBrushGeometry(size = DEFAULT_BOX_BRUSH_SIZE) {
|
||||
const halfSize = {
|
||||
x: size.x * 0.5,
|
||||
y: size.y * 0.5,
|
||||
z: size.z * 0.5
|
||||
};
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: { x: -halfSize.x, y: -halfSize.y, z: -halfSize.z },
|
||||
posX_negY_negZ: { x: halfSize.x, y: -halfSize.y, z: -halfSize.z },
|
||||
negX_posY_negZ: { x: -halfSize.x, y: halfSize.y, z: -halfSize.z },
|
||||
posX_posY_negZ: { x: halfSize.x, y: halfSize.y, z: -halfSize.z },
|
||||
negX_negY_posZ: { x: -halfSize.x, y: -halfSize.y, z: halfSize.z },
|
||||
posX_negY_posZ: { x: halfSize.x, y: -halfSize.y, z: halfSize.z },
|
||||
negX_posY_posZ: { x: -halfSize.x, y: halfSize.y, z: halfSize.z },
|
||||
posX_posY_posZ: { x: halfSize.x, y: halfSize.y, z: halfSize.z }
|
||||
}
|
||||
};
|
||||
}
|
||||
export function isBoxFaceId(value) {
|
||||
return typeof value === "string" && BOX_FACE_IDS.some((faceId) => faceId === value);
|
||||
}
|
||||
export function isBoxEdgeId(value) {
|
||||
return typeof value === "string" && BOX_EDGE_IDS.some((edgeId) => edgeId === value);
|
||||
}
|
||||
export function isBoxVertexId(value) {
|
||||
return typeof value === "string" && BOX_VERTEX_IDS.some((vertexId) => vertexId === value);
|
||||
}
|
||||
export function isFaceUvRotationQuarterTurns(value) {
|
||||
return typeof value === "number" && FACE_UV_ROTATION_QUARTER_TURNS.includes(value);
|
||||
}
|
||||
export function isBoxBrushVolumeMode(value) {
|
||||
return typeof value === "string" && BOX_BRUSH_VOLUME_MODES.includes(value);
|
||||
}
|
||||
export function hasPositiveBoxSize(size) {
|
||||
return size.x > 0 && size.y > 0 && size.z > 0;
|
||||
}
|
||||
export function createDefaultFaceUvState() {
|
||||
return {
|
||||
offset: {
|
||||
x: 0,
|
||||
y: 0
|
||||
},
|
||||
scale: {
|
||||
x: 1,
|
||||
y: 1
|
||||
},
|
||||
rotationQuarterTurns: 0,
|
||||
flipU: false,
|
||||
flipV: false
|
||||
};
|
||||
}
|
||||
export function cloneFaceUvState(uv) {
|
||||
return {
|
||||
offset: {
|
||||
...uv.offset
|
||||
},
|
||||
scale: {
|
||||
...uv.scale
|
||||
},
|
||||
rotationQuarterTurns: uv.rotationQuarterTurns,
|
||||
flipU: uv.flipU,
|
||||
flipV: uv.flipV
|
||||
};
|
||||
}
|
||||
export function cloneBoxBrushFaces(faces) {
|
||||
return {
|
||||
posX: cloneBrushFace(faces.posX),
|
||||
negX: cloneBrushFace(faces.negX),
|
||||
posY: cloneBrushFace(faces.posY),
|
||||
negY: cloneBrushFace(faces.negY),
|
||||
posZ: cloneBrushFace(faces.posZ),
|
||||
negZ: cloneBrushFace(faces.negZ)
|
||||
};
|
||||
}
|
||||
export function createDefaultBoxBrushFaces() {
|
||||
return {
|
||||
posX: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
},
|
||||
negX: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
},
|
||||
posY: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
},
|
||||
negY: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
},
|
||||
posZ: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
},
|
||||
negZ: {
|
||||
materialId: null,
|
||||
uv: createDefaultFaceUvState()
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createDefaultBoxBrushWaterSettings() {
|
||||
return {
|
||||
colorHex: DEFAULT_BOX_BRUSH_WATER_SETTINGS.colorHex,
|
||||
surfaceOpacity: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceOpacity,
|
||||
waveStrength: DEFAULT_BOX_BRUSH_WATER_SETTINGS.waveStrength,
|
||||
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_SETTINGS.foamContactLimit,
|
||||
surfaceDisplacementEnabled: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceDisplacementEnabled
|
||||
};
|
||||
}
|
||||
export function createDefaultBoxBrushFogSettings() {
|
||||
return {
|
||||
colorHex: DEFAULT_BOX_BRUSH_FOG_SETTINGS.colorHex,
|
||||
density: DEFAULT_BOX_BRUSH_FOG_SETTINGS.density,
|
||||
padding: DEFAULT_BOX_BRUSH_FOG_SETTINGS.padding
|
||||
};
|
||||
}
|
||||
export function createDefaultBoxBrushVolumeSettings() {
|
||||
return {
|
||||
mode: "none"
|
||||
};
|
||||
}
|
||||
export function cloneBoxBrushVolumeSettings(volume) {
|
||||
switch (volume.mode) {
|
||||
case "none":
|
||||
return {
|
||||
mode: "none"
|
||||
};
|
||||
case "water":
|
||||
return {
|
||||
mode: "water",
|
||||
water: {
|
||||
colorHex: volume.water.colorHex,
|
||||
surfaceOpacity: volume.water.surfaceOpacity,
|
||||
waveStrength: volume.water.waveStrength,
|
||||
foamContactLimit: volume.water.foamContactLimit,
|
||||
surfaceDisplacementEnabled: volume.water.surfaceDisplacementEnabled
|
||||
}
|
||||
};
|
||||
case "fog":
|
||||
return {
|
||||
mode: "fog",
|
||||
fog: {
|
||||
colorHex: volume.fog.colorHex,
|
||||
density: volume.fog.density,
|
||||
padding: volume.fog.padding
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
export function createBoxBrush(overrides = {}) {
|
||||
const center = cloneVec3(overrides.center ?? DEFAULT_BOX_BRUSH_CENTER);
|
||||
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_BOX_BRUSH_ROTATION_DEGREES);
|
||||
const fallbackSize = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
|
||||
const geometry = overrides.geometry === undefined ? createDefaultBoxBrushGeometry(fallbackSize) : cloneBoxBrushGeometry(overrides.geometry);
|
||||
const size = deriveBoxBrushSizeFromGeometry(geometry);
|
||||
if (!hasPositiveBoxSize(size)) {
|
||||
throw new Error("Box brush size must remain positive on every axis.");
|
||||
}
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("brush"),
|
||||
kind: "box",
|
||||
name: normalizeBrushName(overrides.name),
|
||||
center,
|
||||
rotationDegrees,
|
||||
size,
|
||||
geometry,
|
||||
faces: overrides.faces === undefined ? createDefaultBoxBrushFaces() : cloneBoxBrushFaces(overrides.faces),
|
||||
volume: overrides.volume === undefined ? createDefaultBoxBrushVolumeSettings() : cloneBoxBrushVolumeSettings(overrides.volume),
|
||||
layerId: overrides.layerId,
|
||||
groupId: overrides.groupId
|
||||
};
|
||||
}
|
||||
export function cloneBoxBrush(brush) {
|
||||
return createBoxBrush(brush);
|
||||
}
|
||||
@@ -27,11 +27,13 @@ export const BOX_VERTEX_IDS = [
|
||||
"posX_posY_posZ"
|
||||
] as const;
|
||||
export const FACE_UV_ROTATION_QUARTER_TURNS = [0, 1, 2, 3] as const;
|
||||
export const BOX_BRUSH_VOLUME_MODES = ["none", "water", "fog"] as const;
|
||||
|
||||
export type BoxFaceId = (typeof BOX_FACE_IDS)[number];
|
||||
export type BoxEdgeId = (typeof BOX_EDGE_IDS)[number];
|
||||
export type BoxVertexId = (typeof BOX_VERTEX_IDS)[number];
|
||||
export type FaceUvRotationQuarterTurns = (typeof FACE_UV_ROTATION_QUARTER_TURNS)[number];
|
||||
export type BoxBrushVolumeMode = (typeof BOX_BRUSH_VOLUME_MODES)[number];
|
||||
|
||||
export const BOX_FACE_LABELS: Record<BoxFaceId, string> = {
|
||||
posX: "Right",
|
||||
@@ -81,8 +83,41 @@ export interface BrushFace {
|
||||
uv: FaceUvState;
|
||||
}
|
||||
|
||||
export interface BoxBrushWaterSettings {
|
||||
colorHex: string;
|
||||
surfaceOpacity: number;
|
||||
waveStrength: number;
|
||||
foamContactLimit: number;
|
||||
surfaceDisplacementEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface BoxBrushFogSettings {
|
||||
colorHex: string;
|
||||
density: number;
|
||||
padding: number;
|
||||
}
|
||||
|
||||
export type BoxBrushVolumeSettings =
|
||||
| {
|
||||
mode: "none";
|
||||
}
|
||||
| {
|
||||
mode: "water";
|
||||
water: BoxBrushWaterSettings;
|
||||
}
|
||||
| {
|
||||
mode: "fog";
|
||||
fog: BoxBrushFogSettings;
|
||||
};
|
||||
|
||||
export type BoxBrushFaces = Record<BoxFaceId, BrushFace>;
|
||||
|
||||
export type BoxBrushGeometryVertices = Record<BoxVertexId, Vec3>;
|
||||
|
||||
export interface BoxBrushGeometry {
|
||||
vertices: BoxBrushGeometryVertices;
|
||||
}
|
||||
|
||||
export interface BoxBrush {
|
||||
id: string;
|
||||
kind: "box";
|
||||
@@ -90,7 +125,9 @@ export interface BoxBrush {
|
||||
center: Vec3;
|
||||
rotationDegrees: Vec3;
|
||||
size: Vec3;
|
||||
geometry: BoxBrushGeometry;
|
||||
faces: BoxBrushFaces;
|
||||
volume: BoxBrushVolumeSettings;
|
||||
layerId?: string;
|
||||
groupId?: string;
|
||||
}
|
||||
@@ -115,6 +152,23 @@ export const DEFAULT_BOX_BRUSH_ROTATION_DEGREES: Vec3 = {
|
||||
z: 0
|
||||
};
|
||||
|
||||
export const DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 6;
|
||||
export const MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT = 24;
|
||||
|
||||
const DEFAULT_BOX_BRUSH_WATER_SETTINGS: BoxBrushWaterSettings = {
|
||||
colorHex: "#4da6d9",
|
||||
surfaceOpacity: 0.55,
|
||||
waveStrength: 0.35,
|
||||
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT,
|
||||
surfaceDisplacementEnabled: false
|
||||
};
|
||||
|
||||
const DEFAULT_BOX_BRUSH_FOG_SETTINGS: BoxBrushFogSettings = {
|
||||
colorHex: "#9cb7c7",
|
||||
density: 0.08,
|
||||
padding: 0.2
|
||||
};
|
||||
|
||||
export function normalizeBrushName(name: string | null | undefined): string | undefined {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
@@ -139,6 +193,146 @@ function cloneBrushFace(face: BrushFace): BrushFace {
|
||||
};
|
||||
}
|
||||
|
||||
function cloneBoxBrushGeometryVertex(vertex: Vec3): Vec3 {
|
||||
return {
|
||||
x: vertex.x,
|
||||
y: vertex.y,
|
||||
z: vertex.z
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneBoxBrushGeometry(geometry: BoxBrushGeometry): BoxBrushGeometry {
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_negZ),
|
||||
posX_negY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_negZ),
|
||||
negX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_negZ),
|
||||
posX_posY_negZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_negZ),
|
||||
negX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_negY_posZ),
|
||||
posX_negY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_negY_posZ),
|
||||
negX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.negX_posY_posZ),
|
||||
posX_posY_posZ: cloneBoxBrushGeometryVertex(geometry.vertices.posX_posY_posZ)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function getBoxBrushGeometryLocalBounds(geometry: BoxBrushGeometry): { min: Vec3; max: Vec3 } {
|
||||
const vertices = Object.values(geometry.vertices);
|
||||
const firstVertex = vertices[0];
|
||||
const min = { ...firstVertex };
|
||||
const max = { ...firstVertex };
|
||||
|
||||
for (const vertex of vertices.slice(1)) {
|
||||
min.x = Math.min(min.x, vertex.x);
|
||||
min.y = Math.min(min.y, vertex.y);
|
||||
min.z = Math.min(min.z, vertex.z);
|
||||
max.x = Math.max(max.x, vertex.x);
|
||||
max.y = Math.max(max.y, vertex.y);
|
||||
max.z = Math.max(max.z, vertex.z);
|
||||
}
|
||||
|
||||
return {
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveBoxBrushSizeFromGeometry(geometry: BoxBrushGeometry): Vec3 {
|
||||
const bounds = getBoxBrushGeometryLocalBounds(geometry);
|
||||
|
||||
return {
|
||||
x: bounds.max.x - bounds.min.x,
|
||||
y: bounds.max.y - bounds.min.y,
|
||||
z: bounds.max.z - bounds.min.z
|
||||
};
|
||||
}
|
||||
|
||||
export function scaleBoxBrushGeometryToSize(geometry: BoxBrushGeometry, size: Vec3): BoxBrushGeometry {
|
||||
const bounds = getBoxBrushGeometryLocalBounds(geometry);
|
||||
const currentSize = deriveBoxBrushSizeFromGeometry(geometry);
|
||||
|
||||
if (!hasPositiveBoxSize(currentSize) || !hasPositiveBoxSize(size)) {
|
||||
throw new Error("Box brush geometry size must remain positive on every axis.");
|
||||
}
|
||||
|
||||
const center = {
|
||||
x: (bounds.min.x + bounds.max.x) * 0.5,
|
||||
y: (bounds.min.y + bounds.max.y) * 0.5,
|
||||
z: (bounds.min.z + bounds.max.z) * 0.5
|
||||
};
|
||||
const scale = {
|
||||
x: size.x / currentSize.x,
|
||||
y: size.y / currentSize.y,
|
||||
z: size.z / currentSize.z
|
||||
};
|
||||
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: {
|
||||
x: center.x + (geometry.vertices.negX_negY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_negY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_negY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_negY_negZ: {
|
||||
x: center.x + (geometry.vertices.posX_negY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_negY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_negY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_posY_negZ: {
|
||||
x: center.x + (geometry.vertices.negX_posY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_posY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_posY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_posY_negZ: {
|
||||
x: center.x + (geometry.vertices.posX_posY_negZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_posY_negZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_posY_negZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_negY_posZ: {
|
||||
x: center.x + (geometry.vertices.negX_negY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_negY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_negY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_negY_posZ: {
|
||||
x: center.x + (geometry.vertices.posX_negY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_negY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_negY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
negX_posY_posZ: {
|
||||
x: center.x + (geometry.vertices.negX_posY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.negX_posY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.negX_posY_posZ.z - center.z) * scale.z
|
||||
},
|
||||
posX_posY_posZ: {
|
||||
x: center.x + (geometry.vertices.posX_posY_posZ.x - center.x) * scale.x,
|
||||
y: center.y + (geometry.vertices.posX_posY_posZ.y - center.y) * scale.y,
|
||||
z: center.z + (geometry.vertices.posX_posY_posZ.z - center.z) * scale.z
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultBoxBrushGeometry(size: Vec3 = DEFAULT_BOX_BRUSH_SIZE): BoxBrushGeometry {
|
||||
const halfSize = {
|
||||
x: size.x * 0.5,
|
||||
y: size.y * 0.5,
|
||||
z: size.z * 0.5
|
||||
};
|
||||
|
||||
return {
|
||||
vertices: {
|
||||
negX_negY_negZ: { x: -halfSize.x, y: -halfSize.y, z: -halfSize.z },
|
||||
posX_negY_negZ: { x: halfSize.x, y: -halfSize.y, z: -halfSize.z },
|
||||
negX_posY_negZ: { x: -halfSize.x, y: halfSize.y, z: -halfSize.z },
|
||||
posX_posY_negZ: { x: halfSize.x, y: halfSize.y, z: -halfSize.z },
|
||||
negX_negY_posZ: { x: -halfSize.x, y: -halfSize.y, z: halfSize.z },
|
||||
posX_negY_posZ: { x: halfSize.x, y: -halfSize.y, z: halfSize.z },
|
||||
negX_posY_posZ: { x: -halfSize.x, y: halfSize.y, z: halfSize.z },
|
||||
posX_posY_posZ: { x: halfSize.x, y: halfSize.y, z: halfSize.z }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function isBoxFaceId(value: unknown): value is BoxFaceId {
|
||||
return typeof value === "string" && BOX_FACE_IDS.some((faceId) => faceId === value);
|
||||
}
|
||||
@@ -155,6 +349,10 @@ export function isFaceUvRotationQuarterTurns(value: unknown): value is FaceUvRot
|
||||
return typeof value === "number" && FACE_UV_ROTATION_QUARTER_TURNS.includes(value as FaceUvRotationQuarterTurns);
|
||||
}
|
||||
|
||||
export function isBoxBrushVolumeMode(value: unknown): value is BoxBrushVolumeMode {
|
||||
return typeof value === "string" && BOX_BRUSH_VOLUME_MODES.includes(value as BoxBrushVolumeMode);
|
||||
}
|
||||
|
||||
export function hasPositiveBoxSize(size: Vec3): boolean {
|
||||
return size.x > 0 && size.y > 0 && size.z > 0;
|
||||
}
|
||||
@@ -229,12 +427,69 @@ export function createDefaultBoxBrushFaces(): BoxBrushFaces {
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultBoxBrushWaterSettings(): BoxBrushWaterSettings {
|
||||
return {
|
||||
colorHex: DEFAULT_BOX_BRUSH_WATER_SETTINGS.colorHex,
|
||||
surfaceOpacity: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceOpacity,
|
||||
waveStrength: DEFAULT_BOX_BRUSH_WATER_SETTINGS.waveStrength,
|
||||
foamContactLimit: DEFAULT_BOX_BRUSH_WATER_SETTINGS.foamContactLimit,
|
||||
surfaceDisplacementEnabled: DEFAULT_BOX_BRUSH_WATER_SETTINGS.surfaceDisplacementEnabled
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultBoxBrushFogSettings(): BoxBrushFogSettings {
|
||||
return {
|
||||
colorHex: DEFAULT_BOX_BRUSH_FOG_SETTINGS.colorHex,
|
||||
density: DEFAULT_BOX_BRUSH_FOG_SETTINGS.density,
|
||||
padding: DEFAULT_BOX_BRUSH_FOG_SETTINGS.padding
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultBoxBrushVolumeSettings(): BoxBrushVolumeSettings {
|
||||
return {
|
||||
mode: "none"
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneBoxBrushVolumeSettings(volume: BoxBrushVolumeSettings): BoxBrushVolumeSettings {
|
||||
switch (volume.mode) {
|
||||
case "none":
|
||||
return {
|
||||
mode: "none"
|
||||
};
|
||||
case "water":
|
||||
return {
|
||||
mode: "water",
|
||||
water: {
|
||||
colorHex: volume.water.colorHex,
|
||||
surfaceOpacity: volume.water.surfaceOpacity,
|
||||
waveStrength: volume.water.waveStrength,
|
||||
foamContactLimit: volume.water.foamContactLimit,
|
||||
surfaceDisplacementEnabled: volume.water.surfaceDisplacementEnabled
|
||||
}
|
||||
};
|
||||
case "fog":
|
||||
return {
|
||||
mode: "fog",
|
||||
fog: {
|
||||
colorHex: volume.fog.colorHex,
|
||||
density: volume.fog.density,
|
||||
padding: volume.fog.padding
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function createBoxBrush(
|
||||
overrides: Partial<Pick<BoxBrush, "id" | "name" | "center" | "rotationDegrees" | "size" | "faces" | "layerId" | "groupId">> = {}
|
||||
overrides: Partial<
|
||||
Pick<BoxBrush, "id" | "name" | "center" | "rotationDegrees" | "size" | "geometry" | "faces" | "volume" | "layerId" | "groupId">
|
||||
> = {}
|
||||
): BoxBrush {
|
||||
const center = cloneVec3(overrides.center ?? DEFAULT_BOX_BRUSH_CENTER);
|
||||
const rotationDegrees = cloneVec3(overrides.rotationDegrees ?? DEFAULT_BOX_BRUSH_ROTATION_DEGREES);
|
||||
const size = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
|
||||
const fallbackSize = cloneVec3(overrides.size ?? DEFAULT_BOX_BRUSH_SIZE);
|
||||
const geometry = overrides.geometry === undefined ? createDefaultBoxBrushGeometry(fallbackSize) : cloneBoxBrushGeometry(overrides.geometry);
|
||||
const size = deriveBoxBrushSizeFromGeometry(geometry);
|
||||
|
||||
if (!hasPositiveBoxSize(size)) {
|
||||
throw new Error("Box brush size must remain positive on every axis.");
|
||||
@@ -247,7 +502,9 @@ export function createBoxBrush(
|
||||
center,
|
||||
rotationDegrees,
|
||||
size,
|
||||
geometry,
|
||||
faces: overrides.faces === undefined ? createDefaultBoxBrushFaces() : cloneBoxBrushFaces(overrides.faces),
|
||||
volume: overrides.volume === undefined ? createDefaultBoxBrushVolumeSettings() : cloneBoxBrushVolumeSettings(overrides.volume),
|
||||
layerId: overrides.layerId,
|
||||
groupId: overrides.groupId
|
||||
};
|
||||
|
||||
1303
src/document/migrate-scene-document.js
Normal file
1303
src/document/migrate-scene-document.js
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
690
src/document/scene-document-validation.js
Normal file
690
src/document/scene-document-validation.js
Normal file
@@ -0,0 +1,690 @@
|
||||
import {} from "../assets/project-assets";
|
||||
import { isModelInstanceCollisionMode } from "../assets/model-instances";
|
||||
import { isPlayerStartColliderMode, getPlayerStartColliderHeight } from "../entities/entity-instances";
|
||||
import {} from "../interactions/interaction-links";
|
||||
import { BOX_FACE_IDS, BOX_VERTEX_IDS, MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT, hasPositiveBoxSize, isBoxBrushVolumeMode } from "./brushes";
|
||||
import { isAdvancedRenderingShadowMapSize, isAdvancedRenderingShadowType, isBoxVolumeRenderPath, isAdvancedRenderingToneMappingMode, isHexColorString } from "./world-settings";
|
||||
export function createDiagnostic(severity, code, message, path, scope = "document") {
|
||||
return {
|
||||
code,
|
||||
severity,
|
||||
scope,
|
||||
message,
|
||||
path
|
||||
};
|
||||
}
|
||||
function isFiniteNumber(value) {
|
||||
return typeof value === "number" && Number.isFinite(value);
|
||||
}
|
||||
function isFiniteVec3(vector) {
|
||||
return isFiniteNumber(vector.x) && isFiniteNumber(vector.y) && isFiniteNumber(vector.z);
|
||||
}
|
||||
function hasPositiveFiniteVec3(vector) {
|
||||
return isFiniteVec3(vector) && vector.x > 0 && vector.y > 0 && vector.z > 0;
|
||||
}
|
||||
function isNonNegativeFiniteNumber(value) {
|
||||
return isFiniteNumber(value) && value >= 0;
|
||||
}
|
||||
function isPositiveFiniteNumber(value) {
|
||||
return isFiniteNumber(value) && value > 0;
|
||||
}
|
||||
function isPositiveInteger(value) {
|
||||
return isFiniteNumber(value) && Number.isInteger(value) && value > 0;
|
||||
}
|
||||
function isPositiveIntegerInRange(value, max) {
|
||||
return isPositiveInteger(value) && value <= max;
|
||||
}
|
||||
function isBoolean(value) {
|
||||
return typeof value === "boolean";
|
||||
}
|
||||
function hasNonZeroVectorLength(vector) {
|
||||
return vector.x !== 0 || vector.y !== 0 || vector.z !== 0;
|
||||
}
|
||||
function validateWorldSettings(world, document, diagnostics) {
|
||||
if (world.background.mode === "solid") {
|
||||
if (!isHexColorString(world.background.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-color", "Solid world backgrounds must use #RRGGBB colors.", "world.background.colorHex"));
|
||||
}
|
||||
}
|
||||
else if (world.background.mode === "verticalGradient") {
|
||||
if (!isHexColorString(world.background.topColorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-top-color", "Gradient world backgrounds must use #RRGGBB colors for the top color.", "world.background.topColorHex"));
|
||||
}
|
||||
if (!isHexColorString(world.background.bottomColorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-bottom-color", "Gradient world backgrounds must use #RRGGBB colors for the bottom color.", "world.background.bottomColorHex"));
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (typeof world.background.assetId !== "string" || world.background.assetId.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-asset-id", "World background images must reference a non-empty asset id.", "world.background.assetId"));
|
||||
}
|
||||
else {
|
||||
const backgroundAsset = document.assets[world.background.assetId];
|
||||
if (backgroundAsset === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-world-background-asset", `World background image asset ${world.background.assetId} does not exist.`, "world.background.assetId"));
|
||||
}
|
||||
else if (backgroundAsset.kind !== "image") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-asset-kind", "World background images must reference image assets.", "world.background.assetId"));
|
||||
}
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(world.background.environmentIntensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-background-environment-intensity", "World background environment intensity must be a non-negative finite number.", "world.background.environmentIntensity"));
|
||||
}
|
||||
}
|
||||
if (!isHexColorString(world.ambientLight.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-ambient-color", "World ambient light must use a #RRGGBB color.", "world.ambientLight.colorHex"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(world.ambientLight.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-ambient-intensity", "World ambient light intensity must remain finite and zero or greater.", "world.ambientLight.intensity"));
|
||||
}
|
||||
if (!isHexColorString(world.sunLight.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-sun-color", "World sun color must use a #RRGGBB color.", "world.sunLight.colorHex"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(world.sunLight.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-sun-intensity", "World sun intensity must remain finite and zero or greater.", "world.sunLight.intensity"));
|
||||
}
|
||||
if (!isFiniteVec3(world.sunLight.direction) || !hasNonZeroVectorLength(world.sunLight.direction)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-world-sun-direction", "World sun direction must remain finite and must not be the zero vector.", "world.sunLight.direction"));
|
||||
}
|
||||
const advancedRendering = world.advancedRendering;
|
||||
if (!isBoolean(advancedRendering.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-enabled", "Advanced rendering enabled must be a boolean.", "world.advancedRendering.enabled"));
|
||||
}
|
||||
if (!isBoolean(advancedRendering.shadows.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadows-enabled", "Advanced rendering shadow enabled must be a boolean.", "world.advancedRendering.shadows.enabled"));
|
||||
}
|
||||
if (!isAdvancedRenderingShadowMapSize(advancedRendering.shadows.mapSize)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-map-size", "Advanced rendering shadow map size must be one of 512, 1024, 2048, or 4096.", "world.advancedRendering.shadows.mapSize"));
|
||||
}
|
||||
if (!isAdvancedRenderingShadowType(advancedRendering.shadows.type)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-type", "Advanced rendering shadow type must be basic, pcf, or pcfSoft.", "world.advancedRendering.shadows.type"));
|
||||
}
|
||||
if (!isFiniteNumber(advancedRendering.shadows.bias)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-shadow-bias", "Advanced rendering shadow bias must be a finite number.", "world.advancedRendering.shadows.bias"));
|
||||
}
|
||||
if (!isBoolean(advancedRendering.ambientOcclusion.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-enabled", "Advanced rendering ambient occlusion enabled must be a boolean.", "world.advancedRendering.ambientOcclusion.enabled"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.ambientOcclusion.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-intensity", "Advanced rendering ambient occlusion intensity must be a non-negative finite number.", "world.advancedRendering.ambientOcclusion.intensity"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.ambientOcclusion.radius)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-radius", "Advanced rendering ambient occlusion radius must be a non-negative finite number.", "world.advancedRendering.ambientOcclusion.radius"));
|
||||
}
|
||||
if (!isPositiveInteger(advancedRendering.ambientOcclusion.samples)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-ao-samples", "Advanced rendering ambient occlusion samples must be a positive integer.", "world.advancedRendering.ambientOcclusion.samples"));
|
||||
}
|
||||
if (!isBoolean(advancedRendering.bloom.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-enabled", "Advanced rendering bloom enabled must be a boolean.", "world.advancedRendering.bloom.enabled"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-intensity", "Advanced rendering bloom intensity must be a non-negative finite number.", "world.advancedRendering.bloom.intensity"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.threshold)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-threshold", "Advanced rendering bloom threshold must be a non-negative finite number.", "world.advancedRendering.bloom.threshold"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.bloom.radius)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-bloom-radius", "Advanced rendering bloom radius must be a non-negative finite number.", "world.advancedRendering.bloom.radius"));
|
||||
}
|
||||
if (!isAdvancedRenderingToneMappingMode(advancedRendering.toneMapping.mode)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-tone-mapping-mode", "Advanced rendering tone mapping mode must be none, linear, reinhard, cineon, or acesFilmic.", "world.advancedRendering.toneMapping.mode"));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(advancedRendering.toneMapping.exposure)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-tone-mapping-exposure", "Advanced rendering tone mapping exposure must be a positive finite number.", "world.advancedRendering.toneMapping.exposure"));
|
||||
}
|
||||
if (!isBoolean(advancedRendering.depthOfField.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-enabled", "Advanced rendering depth of field enabled must be a boolean.", "world.advancedRendering.depthOfField.enabled"));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(advancedRendering.depthOfField.focusDistance)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-focus-distance", "Advanced rendering depth of field focus distance must be a non-negative finite number.", "world.advancedRendering.depthOfField.focusDistance"));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(advancedRendering.depthOfField.focalLength)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-focal-length", "Advanced rendering depth of field focal length must be a positive finite number.", "world.advancedRendering.depthOfField.focalLength"));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(advancedRendering.depthOfField.bokehScale)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-dof-bokeh-scale", "Advanced rendering depth of field bokeh scale must be a positive finite number.", "world.advancedRendering.depthOfField.bokehScale"));
|
||||
}
|
||||
if (!isBoxVolumeRenderPath(advancedRendering.fogPath)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-fog-path", "Advanced rendering fog path must be performance or quality.", "world.advancedRendering.fogPath"));
|
||||
}
|
||||
if (!isBoxVolumeRenderPath(advancedRendering.waterPath)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-water-path", "Advanced rendering water path must be performance or quality.", "world.advancedRendering.waterPath"));
|
||||
}
|
||||
if (!["none", "world", "all"].includes(advancedRendering.waterReflectionMode)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-advanced-rendering-water-reflection-mode", "Advanced rendering water reflection mode must be none, world, or all.", "world.advancedRendering.waterReflectionMode"));
|
||||
}
|
||||
}
|
||||
function validatePointLightEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-point-light-position", "Point Light position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isHexColorString(entity.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-point-light-color", "Point Light color must use a #RRGGBB color.", `${path}.colorHex`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(entity.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-point-light-intensity", "Point Light intensity must remain finite and zero or greater.", `${path}.intensity`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(entity.distance)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-point-light-distance", "Point Light distance must remain finite and greater than zero.", `${path}.distance`));
|
||||
}
|
||||
}
|
||||
function validateSpotLightEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-position", "Spot Light position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isFiniteVec3(entity.direction) || !hasNonZeroVectorLength(entity.direction)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-direction", "Spot Light direction must remain finite and must not be the zero vector.", `${path}.direction`));
|
||||
}
|
||||
if (!isHexColorString(entity.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-color", "Spot Light color must use a #RRGGBB color.", `${path}.colorHex`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(entity.intensity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-intensity", "Spot Light intensity must remain finite and zero or greater.", `${path}.intensity`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(entity.distance)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-distance", "Spot Light distance must remain finite and greater than zero.", `${path}.distance`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.angleDegrees) || entity.angleDegrees <= 0 || entity.angleDegrees >= 180) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-spot-light-angle", "Spot Light angle must remain a finite degree value between 0 and 180.", `${path}.angleDegrees`));
|
||||
}
|
||||
}
|
||||
function validateProjectAssetBoundingBox(boundingBox, path, diagnostics) {
|
||||
if (boundingBox === null) {
|
||||
return;
|
||||
}
|
||||
if (!isFiniteVec3(boundingBox.min)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-min", "Model asset bounding boxes must have finite minimum coordinates.", `${path}.min`));
|
||||
}
|
||||
if (!isFiniteVec3(boundingBox.max)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-max", "Model asset bounding boxes must have finite maximum coordinates.", `${path}.max`));
|
||||
}
|
||||
if (!isFiniteVec3(boundingBox.size) || boundingBox.size.x < 0 || boundingBox.size.y < 0 || boundingBox.size.z < 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-bounding-box-size", "Model asset bounding boxes must have finite, zero-or-greater size values.", `${path}.size`));
|
||||
}
|
||||
}
|
||||
function validateModelAssetMetadata(metadata, path, diagnostics) {
|
||||
if (metadata.format !== "glb" && metadata.format !== "gltf") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-format", "Model asset format must be glb or gltf.", `${path}.format`));
|
||||
}
|
||||
if (metadata.sceneName !== null && metadata.sceneName.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-scene-name", "Model asset scene names must be non-empty when authored.", `${path}.sceneName`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(metadata.nodeCount)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-node-count", "Model asset node counts must be finite and zero or greater.", `${path}.nodeCount`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(metadata.meshCount)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-mesh-count", "Model asset mesh counts must be finite and zero or greater.", `${path}.meshCount`));
|
||||
}
|
||||
if (!Array.isArray(metadata.materialNames) || metadata.materialNames.some((name) => typeof name !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-material-names", "Model asset material names must be string arrays.", `${path}.materialNames`));
|
||||
}
|
||||
if (!Array.isArray(metadata.textureNames) || metadata.textureNames.some((name) => typeof name !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-texture-names", "Model asset texture names must be string arrays.", `${path}.textureNames`));
|
||||
}
|
||||
if (!Array.isArray(metadata.animationNames) || metadata.animationNames.some((name) => typeof name !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-animation-names", "Model asset animation names must be string arrays.", `${path}.animationNames`));
|
||||
}
|
||||
validateProjectAssetBoundingBox(metadata.boundingBox, `${path}.boundingBox`, diagnostics);
|
||||
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-asset-warnings", "Model asset warnings must be string arrays.", `${path}.warnings`));
|
||||
}
|
||||
}
|
||||
function validateImageAssetMetadata(metadata, path, diagnostics) {
|
||||
if (!isPositiveFiniteNumber(metadata.width)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-image-asset-width", "Image asset width must be finite and greater than zero.", `${path}.width`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(metadata.height)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-image-asset-height", "Image asset height must be finite and greater than zero.", `${path}.height`));
|
||||
}
|
||||
if (!isBoolean(metadata.hasAlpha)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-image-asset-alpha", "Image asset alpha flags must be booleans.", `${path}.hasAlpha`));
|
||||
}
|
||||
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-image-asset-warnings", "Image asset warnings must be string arrays.", `${path}.warnings`));
|
||||
}
|
||||
}
|
||||
function validateAudioAssetMetadata(metadata, path, diagnostics) {
|
||||
if (metadata.durationSeconds !== null && !isNonNegativeFiniteNumber(metadata.durationSeconds)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-duration", "Audio asset durations must be finite and zero or greater when authored.", `${path}.durationSeconds`));
|
||||
}
|
||||
if (metadata.channelCount !== null && !isPositiveFiniteNumber(metadata.channelCount)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-channel-count", "Audio asset channel counts must be finite and greater than zero when authored.", `${path}.channelCount`));
|
||||
}
|
||||
if (metadata.sampleRateHz !== null && !isPositiveFiniteNumber(metadata.sampleRateHz)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-sample-rate", "Audio asset sample rates must be finite and greater than zero when authored.", `${path}.sampleRateHz`));
|
||||
}
|
||||
if (!Array.isArray(metadata.warnings) || metadata.warnings.some((warning) => typeof warning !== "string")) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-audio-asset-warnings", "Audio asset warnings must be string arrays.", `${path}.warnings`));
|
||||
}
|
||||
}
|
||||
function validateProjectAsset(asset, path, diagnostics) {
|
||||
if (asset.sourceName.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-source-name", "Asset source names must be non-empty strings.", `${path}.sourceName`));
|
||||
}
|
||||
if (asset.mimeType.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-mime-type", "Asset mime types must be non-empty strings.", `${path}.mimeType`));
|
||||
}
|
||||
if (asset.storageKey.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-storage-key", "Asset storage keys must be non-empty strings.", `${path}.storageKey`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(asset.byteLength)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-asset-byte-length", "Asset byte lengths must be finite and greater than zero.", `${path}.byteLength`));
|
||||
}
|
||||
switch (asset.kind) {
|
||||
case "model":
|
||||
validateModelAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
|
||||
break;
|
||||
case "image":
|
||||
validateImageAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
|
||||
break;
|
||||
case "audio":
|
||||
validateAudioAssetMetadata(asset.metadata, `${path}.metadata`, diagnostics);
|
||||
break;
|
||||
}
|
||||
}
|
||||
function validateModelInstance(modelInstance, path, document, diagnostics) {
|
||||
if (modelInstance.name !== undefined && modelInstance.name.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-name", "Model instance names must be non-empty when authored.", `${path}.name`));
|
||||
}
|
||||
if (!isFiniteVec3(modelInstance.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-position", "Model instance positions must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isFiniteVec3(modelInstance.rotationDegrees)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-rotation", "Model instance rotations must remain finite on every axis.", `${path}.rotationDegrees`));
|
||||
}
|
||||
if (!hasPositiveFiniteVec3(modelInstance.scale)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-scale", "Model instance scales must remain finite and positive on every axis.", `${path}.scale`));
|
||||
}
|
||||
if (!isModelInstanceCollisionMode(modelInstance.collision.mode)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-collision-mode", "Model instance collision mode must be one of none, terrain, static, dynamic, or simple.", `${path}.collision.mode`));
|
||||
}
|
||||
if (!isBoolean(modelInstance.collision.visible)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-collision-visibility", "Model instance collision visibility must be a boolean.", `${path}.collision.visible`));
|
||||
}
|
||||
const asset = document.assets[modelInstance.assetId];
|
||||
if (asset === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-model-instance-asset", `Model instance asset ${modelInstance.assetId} does not exist.`, `${path}.assetId`));
|
||||
return;
|
||||
}
|
||||
if (asset.kind !== "model") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-model-instance-asset-kind", "Model instances may only reference model assets.", `${path}.assetId`));
|
||||
}
|
||||
}
|
||||
function validateEntityName(name, path, diagnostics) {
|
||||
if (name !== undefined && name.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-entity-name", "Entity names must be non-empty when authored.", `${path}.name`));
|
||||
}
|
||||
}
|
||||
function validatePlayerStartEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-position", "Player Start position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.yawDegrees)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-yaw", "Player Start yaw must remain a finite number.", `${path}.yawDegrees`));
|
||||
}
|
||||
if (!isPlayerStartColliderMode(entity.collider.mode)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-collider-mode", "Player Start collider mode must be capsule, box, or none.", `${path}.collider.mode`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.collider.eyeHeight) || entity.collider.eyeHeight <= 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-eye-height", "Player Start eye height must remain a finite number greater than zero.", `${path}.collider.eyeHeight`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.collider.capsuleRadius) || entity.collider.capsuleRadius <= 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-capsule-radius", "Player Start capsule radius must remain a finite number greater than zero.", `${path}.collider.capsuleRadius`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.collider.capsuleHeight) || entity.collider.capsuleHeight <= 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-capsule-height", "Player Start capsule height must remain a finite number greater than zero.", `${path}.collider.capsuleHeight`));
|
||||
}
|
||||
if (!isFiniteVec3(entity.collider.boxSize) ||
|
||||
entity.collider.boxSize.x <= 0 ||
|
||||
entity.collider.boxSize.y <= 0 ||
|
||||
entity.collider.boxSize.z <= 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-box-size", "Player Start box size must remain finite and positive on every axis.", `${path}.collider.boxSize`));
|
||||
}
|
||||
if (entity.collider.capsuleHeight < entity.collider.capsuleRadius * 2) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-capsule-proportions", "Player Start capsule height must be at least twice the capsule radius.", `${path}.collider.capsuleHeight`));
|
||||
}
|
||||
const colliderHeight = getPlayerStartColliderHeight(entity.collider);
|
||||
if (colliderHeight !== null && entity.collider.eyeHeight > colliderHeight) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-player-start-eye-height", "Player Start eye height must fit within the authored collider height.", `${path}.collider.eyeHeight`));
|
||||
}
|
||||
}
|
||||
function validateSoundEmitterAudioAsset(entity, path, document, diagnostics, missingSeverity) {
|
||||
if (entity.audioAssetId === null) {
|
||||
diagnostics.push(createDiagnostic(missingSeverity, "missing-sound-emitter-audio-asset", entity.autoplay
|
||||
? "Sound Emitter autoplay requires an assigned audio asset."
|
||||
: "Sound Emitter has no audio asset assigned yet.", `${path}.audioAssetId`));
|
||||
return null;
|
||||
}
|
||||
const asset = document.assets[entity.audioAssetId];
|
||||
if (asset === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-audio-asset", `Sound Emitter audio asset ${entity.audioAssetId} does not exist.`, `${path}.audioAssetId`));
|
||||
return null;
|
||||
}
|
||||
if (asset.kind !== "audio") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-audio-asset-kind", "Sound Emitter audioAssetId must reference an audio asset.", `${path}.audioAssetId`));
|
||||
return null;
|
||||
}
|
||||
return asset;
|
||||
}
|
||||
function validateSoundEmitterEntity(entity, path, document, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-position", "Sound Emitter position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(entity.volume)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-volume", "Sound Emitter volume must remain finite and zero or greater.", `${path}.volume`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(entity.refDistance)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-ref-distance", "Sound Emitter ref distance must remain finite and greater than zero.", `${path}.refDistance`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(entity.maxDistance)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-max-distance", "Sound Emitter max distance must remain finite and greater than zero.", `${path}.maxDistance`));
|
||||
}
|
||||
if (isPositiveFiniteNumber(entity.refDistance) && isPositiveFiniteNumber(entity.maxDistance) && entity.maxDistance < entity.refDistance) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-distance-order", "Sound Emitter max distance must be greater than or equal to ref distance.", `${path}.maxDistance`));
|
||||
}
|
||||
if (!isBoolean(entity.autoplay)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-autoplay", "Sound Emitter autoplay must remain a boolean.", `${path}.autoplay`));
|
||||
}
|
||||
if (!isBoolean(entity.loop)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-loop", "Sound Emitter loop must remain a boolean.", `${path}.loop`));
|
||||
}
|
||||
validateSoundEmitterAudioAsset(entity, path, document, diagnostics, entity.autoplay ? "error" : "warning");
|
||||
}
|
||||
function validateTriggerVolumeEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-position", "Trigger Volume position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!hasPositiveFiniteVec3(entity.size)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-size", "Trigger Volume size must remain finite and positive on every axis.", `${path}.size`));
|
||||
}
|
||||
if (!isBoolean(entity.triggerOnEnter)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-enter-flag", "Trigger Volume triggerOnEnter must remain a boolean.", `${path}.triggerOnEnter`));
|
||||
}
|
||||
if (!isBoolean(entity.triggerOnExit)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-trigger-volume-exit-flag", "Trigger Volume triggerOnExit must remain a boolean.", `${path}.triggerOnExit`));
|
||||
}
|
||||
}
|
||||
function validateTeleportTargetEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-position", "Teleport Target position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isFiniteNumber(entity.yawDegrees)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-yaw", "Teleport Target yaw must remain a finite number.", `${path}.yawDegrees`));
|
||||
}
|
||||
}
|
||||
function validateInteractableEntity(entity, path, diagnostics) {
|
||||
if (!isFiniteVec3(entity.position)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-interactable-position", "Interactable position must remain finite on every axis.", `${path}.position`));
|
||||
}
|
||||
if (!isPositiveFiniteNumber(entity.radius)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-interactable-radius", "Interactable radius must remain finite and greater than zero.", `${path}.radius`));
|
||||
}
|
||||
if (typeof entity.prompt !== "string" || entity.prompt.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-interactable-prompt", "Interactable prompt must remain a non-empty string.", `${path}.prompt`));
|
||||
}
|
||||
if (!isBoolean(entity.enabled)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-interactable-enabled", "Interactable enabled must remain a boolean.", `${path}.enabled`));
|
||||
}
|
||||
}
|
||||
function validateInteractionLink(link, path, document, diagnostics) {
|
||||
const sourceEntity = document.entities[link.sourceEntityId];
|
||||
if (sourceEntity === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-interaction-source-entity", `Interaction source entity ${link.sourceEntityId} does not exist.`, `${path}.sourceEntityId`));
|
||||
return;
|
||||
}
|
||||
if (sourceEntity.kind !== "triggerVolume" && sourceEntity.kind !== "interactable") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-interaction-source-kind", "Interaction links may only source from Trigger Volume or Interactable entities in the current slice.", `${path}.sourceEntityId`));
|
||||
}
|
||||
if (sourceEntity.kind === "triggerVolume") {
|
||||
if (link.trigger !== "enter" && link.trigger !== "exit") {
|
||||
diagnostics.push(createDiagnostic("error", "unsupported-interaction-trigger", "Trigger Volume links may only use enter or exit triggers.", `${path}.trigger`));
|
||||
}
|
||||
}
|
||||
else if (sourceEntity.kind === "interactable") {
|
||||
if (link.trigger !== "click") {
|
||||
diagnostics.push(createDiagnostic("error", "unsupported-interaction-trigger", "Interactable links may only use the click trigger.", `${path}.trigger`));
|
||||
}
|
||||
}
|
||||
switch (link.action.type) {
|
||||
case "teleportPlayer": {
|
||||
const targetEntity = document.entities[link.action.targetEntityId];
|
||||
if (targetEntity === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-teleport-target-entity", `Teleport target entity ${link.action.targetEntityId} does not exist.`, `${path}.action.targetEntityId`));
|
||||
return;
|
||||
}
|
||||
if (targetEntity.kind !== "teleportTarget") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-teleport-target-kind", "Teleport player actions must target a Teleport Target entity.", `${path}.action.targetEntityId`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "toggleVisibility":
|
||||
if (document.brushes[link.action.targetBrushId] === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-visibility-target-brush", `Visibility target brush ${link.action.targetBrushId} does not exist.`, `${path}.action.targetBrushId`));
|
||||
}
|
||||
if (link.action.visible !== undefined && typeof link.action.visible !== "boolean") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-visibility-action-visible", "Visibility actions must use a boolean visible value when authored.", `${path}.action.visible`));
|
||||
}
|
||||
break;
|
||||
case "playAnimation":
|
||||
{
|
||||
const targetModelInstance = document.modelInstances[link.action.targetModelInstanceId];
|
||||
if (targetModelInstance === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-play-animation-target-instance", `Play animation target model instance ${link.action.targetModelInstanceId} does not exist.`, `${path}.action.targetModelInstanceId`));
|
||||
return;
|
||||
}
|
||||
if (link.action.clipName.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-play-animation-clip-name", "Play animation clip name must be non-empty.", `${path}.action.clipName`));
|
||||
return;
|
||||
}
|
||||
const targetAsset = document.assets[targetModelInstance.assetId];
|
||||
if (targetAsset === undefined || targetAsset.kind !== "model") {
|
||||
return;
|
||||
}
|
||||
if (!targetAsset.metadata.animationNames.includes(link.action.clipName)) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-play-animation-clip", `Play animation clip ${link.action.clipName} does not exist on model asset ${targetAsset.id}.`, `${path}.action.clipName`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "stopAnimation":
|
||||
// Validate that the target model instance exists in the document
|
||||
if (document.modelInstances[link.action.targetModelInstanceId] === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-stop-animation-target-instance", `Stop animation target model instance ${link.action.targetModelInstanceId} does not exist.`, `${path}.action.targetModelInstanceId`));
|
||||
}
|
||||
break;
|
||||
case "playSound":
|
||||
case "stopSound": {
|
||||
const targetEntity = document.entities[link.action.targetSoundEmitterId];
|
||||
if (targetEntity === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-entity", `Sound emitter entity ${link.action.targetSoundEmitterId} does not exist.`, `${path}.action.targetSoundEmitterId`));
|
||||
break;
|
||||
}
|
||||
if (targetEntity.kind !== "soundEmitter") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-sound-emitter-kind", "Sound playback actions must target a Sound Emitter entity.", `${path}.action.targetSoundEmitterId`));
|
||||
break;
|
||||
}
|
||||
if (targetEntity.audioAssetId === null) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-sound-emitter-audio-asset", "Sound playback actions require a Sound Emitter that references an audio asset.", `${path}.action.targetSoundEmitterId`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
diagnostics.push(createDiagnostic("error", "unsupported-interaction-action", `Unsupported interaction action ${link.action.type}.`, `${path}.action.type`));
|
||||
break;
|
||||
}
|
||||
}
|
||||
function registerAuthoredId(id, path, seenIds, diagnostics) {
|
||||
const previousPath = seenIds.get(id);
|
||||
if (previousPath !== undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "duplicate-authored-id", `Duplicate authored id ${id} is already used at ${previousPath}.`, path));
|
||||
return;
|
||||
}
|
||||
seenIds.set(id, path);
|
||||
}
|
||||
export function formatSceneDiagnostic(diagnostic) {
|
||||
return diagnostic.path === undefined ? diagnostic.message : `${diagnostic.path}: ${diagnostic.message}`;
|
||||
}
|
||||
export function formatSceneDiagnosticSummary(diagnostics, limit = 3) {
|
||||
if (diagnostics.length === 0) {
|
||||
return "No diagnostics.";
|
||||
}
|
||||
const visibleDiagnostics = diagnostics.slice(0, Math.max(1, limit));
|
||||
const summary = visibleDiagnostics.map((diagnostic) => formatSceneDiagnostic(diagnostic)).join("; ");
|
||||
const remainingCount = diagnostics.length - visibleDiagnostics.length;
|
||||
return remainingCount > 0 ? `${summary}; +${remainingCount} more` : summary;
|
||||
}
|
||||
export function validateSceneDocument(document) {
|
||||
const diagnostics = [];
|
||||
const seenIds = new Map();
|
||||
validateWorldSettings(document.world, document, diagnostics);
|
||||
for (const [materialKey, material] of Object.entries(document.materials)) {
|
||||
const path = `materials.${materialKey}`;
|
||||
if (material.id !== materialKey) {
|
||||
diagnostics.push(createDiagnostic("error", "material-id-mismatch", "Material ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(material.id, path, seenIds, diagnostics);
|
||||
}
|
||||
for (const [assetKey, asset] of Object.entries(document.assets)) {
|
||||
const path = `assets.${assetKey}`;
|
||||
if (asset.id !== assetKey) {
|
||||
diagnostics.push(createDiagnostic("error", "asset-id-mismatch", "Asset ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(asset.id, path, seenIds, diagnostics);
|
||||
validateProjectAsset(asset, path, diagnostics);
|
||||
}
|
||||
for (const [brushKey, brush] of Object.entries(document.brushes)) {
|
||||
const path = `brushes.${brushKey}`;
|
||||
if (brush.id !== brushKey) {
|
||||
diagnostics.push(createDiagnostic("error", "brush-id-mismatch", "Brush ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(brush.id, path, seenIds, diagnostics);
|
||||
if (brush.name !== undefined && brush.name.trim().length === 0) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-name", "Box brush names must be non-empty when authored.", `${path}.name`));
|
||||
}
|
||||
if (!isFiniteVec3(brush.center)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-center", "Box brush centers must remain finite on every axis.", `${path}.center`));
|
||||
}
|
||||
if (!isFiniteVec3(brush.rotationDegrees)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-rotation", "Box brush rotations must remain finite on every axis.", `${path}.rotationDegrees`));
|
||||
}
|
||||
if (!isFiniteVec3(brush.size) || !hasPositiveBoxSize(brush.size)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-size", "Box brush sizes must remain finite and positive on every axis.", `${path}.size`));
|
||||
}
|
||||
for (const vertexId of BOX_VERTEX_IDS) {
|
||||
if (!isFiniteVec3(brush.geometry.vertices[vertexId])) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-geometry-vertex", "Box brush geometry vertices must remain finite on every axis.", `${path}.geometry.vertices.${vertexId}`));
|
||||
}
|
||||
}
|
||||
for (const faceId of BOX_FACE_IDS) {
|
||||
const materialId = brush.faces[faceId].materialId;
|
||||
if (materialId !== null && document.materials[materialId] === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "missing-material-ref", `Face material reference ${materialId} does not exist in the document material registry.`, `${path}.faces.${faceId}.materialId`));
|
||||
}
|
||||
}
|
||||
const volume = brush.volume;
|
||||
if (!isBoxBrushVolumeMode(volume?.mode)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-volume-mode", "Box volume mode must be none, water, or fog.", `${path}.volume.mode`));
|
||||
continue;
|
||||
}
|
||||
if (volume.mode === "water") {
|
||||
const water = volume.water;
|
||||
if (water === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-settings", "Water volumes must define water settings.", `${path}.volume.water`));
|
||||
}
|
||||
else {
|
||||
if (typeof water.colorHex !== "string" || !isHexColorString(water.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-color", "Water volume color must use #RRGGBB format.", `${path}.volume.water.colorHex`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(water.surfaceOpacity)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-surface-opacity", "Water surface opacity must be a non-negative finite number.", `${path}.volume.water.surfaceOpacity`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(water.waveStrength)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-wave-strength", "Water wave strength must be a non-negative finite number.", `${path}.volume.water.waveStrength`));
|
||||
}
|
||||
if (!isPositiveIntegerInRange(water.foamContactLimit, MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-foam-contact-limit", `Water foam contact limit must be a positive integer between 1 and ${MAX_BOX_BRUSH_WATER_FOAM_CONTACT_LIMIT}.`, `${path}.volume.water.foamContactLimit`));
|
||||
}
|
||||
if (typeof water.surfaceDisplacementEnabled !== "boolean") {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-water-surface-displacement-enabled", "Water surface displacement must be enabled or disabled explicitly.", `${path}.volume.water.surfaceDisplacementEnabled`));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (volume.mode === "fog") {
|
||||
const fog = volume.fog;
|
||||
if (fog === undefined) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-fog-settings", "Fog volumes must define fog settings.", `${path}.volume.fog`));
|
||||
}
|
||||
else {
|
||||
if (typeof fog.colorHex !== "string" || !isHexColorString(fog.colorHex)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-fog-color", "Fog volume color must use #RRGGBB format.", `${path}.volume.fog.colorHex`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(fog.density)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-fog-density", "Fog volume density must be a non-negative finite number.", `${path}.volume.fog.density`));
|
||||
}
|
||||
if (!isNonNegativeFiniteNumber(fog.padding)) {
|
||||
diagnostics.push(createDiagnostic("error", "invalid-box-fog-padding", "Fog volume padding must be a non-negative finite number.", `${path}.volume.fog.padding`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [modelInstanceKey, modelInstance] of Object.entries(document.modelInstances)) {
|
||||
const path = `modelInstances.${modelInstanceKey}`;
|
||||
if (modelInstance.id !== modelInstanceKey) {
|
||||
diagnostics.push(createDiagnostic("error", "model-instance-id-mismatch", "Model instance ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(modelInstance.id, path, seenIds, diagnostics);
|
||||
validateModelInstance(modelInstance, path, document, diagnostics);
|
||||
}
|
||||
for (const [entityKey, entity] of Object.entries(document.entities)) {
|
||||
const path = `entities.${entityKey}`;
|
||||
if (entity.id !== entityKey) {
|
||||
diagnostics.push(createDiagnostic("error", "entity-id-mismatch", "Entity ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(entity.id, path, seenIds, diagnostics);
|
||||
validateEntityName(entity.name, path, diagnostics);
|
||||
switch (entity.kind) {
|
||||
case "pointLight":
|
||||
validatePointLightEntity(entity, path, diagnostics);
|
||||
break;
|
||||
case "spotLight":
|
||||
validateSpotLightEntity(entity, path, diagnostics);
|
||||
break;
|
||||
case "playerStart":
|
||||
validatePlayerStartEntity(entity, path, diagnostics);
|
||||
break;
|
||||
case "soundEmitter":
|
||||
validateSoundEmitterEntity(entity, path, document, diagnostics);
|
||||
break;
|
||||
case "triggerVolume":
|
||||
validateTriggerVolumeEntity(entity, path, diagnostics);
|
||||
break;
|
||||
case "teleportTarget":
|
||||
validateTeleportTargetEntity(entity, path, diagnostics);
|
||||
break;
|
||||
case "interactable":
|
||||
validateInteractableEntity(entity, path, diagnostics);
|
||||
break;
|
||||
default:
|
||||
diagnostics.push(createDiagnostic("error", "unsupported-entity-kind", `Unsupported entity kind ${entity.kind}.`, `${path}.kind`));
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (const [linkKey, link] of Object.entries(document.interactionLinks)) {
|
||||
const path = `interactionLinks.${linkKey}`;
|
||||
if (link.id !== linkKey) {
|
||||
diagnostics.push(createDiagnostic("error", "interaction-link-id-mismatch", "Interaction link ids must match their registry key.", `${path}.id`));
|
||||
}
|
||||
registerAuthoredId(link.id, path, seenIds, diagnostics);
|
||||
validateInteractionLink(link, path, document, diagnostics);
|
||||
}
|
||||
return {
|
||||
diagnostics,
|
||||
errors: diagnostics.filter((diagnostic) => diagnostic.severity === "error"),
|
||||
warnings: diagnostics.filter((diagnostic) => diagnostic.severity === "warning")
|
||||
};
|
||||
}
|
||||
export function assertSceneDocumentIsValid(document) {
|
||||
const validation = validateSceneDocument(document);
|
||||
if (validation.errors.length > 0) {
|
||||
throw new Error(`Scene document has ${validation.errors.length} validation error(s): ${formatSceneDiagnosticSummary(validation.errors)}`);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
36
src/document/scene-document.js
Normal file
36
src/document/scene-document.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { cloneMaterialRegistry, createStarterMaterialRegistry } from "../materials/starter-material-library";
|
||||
import { createDefaultWorldSettings } from "./world-settings";
|
||||
export const SCENE_DOCUMENT_VERSION = 21;
|
||||
export const WATER_SURFACE_DISPLACEMENT_SCENE_DOCUMENT_VERSION = 21;
|
||||
export const WHITEBOX_BOX_VOLUME_SCENE_DOCUMENT_VERSION = 20;
|
||||
export const WHITEBOX_GEOMETRY_SCENE_DOCUMENT_VERSION = 19;
|
||||
export const WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION = 18;
|
||||
export const PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION = 17;
|
||||
export const IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION = 16;
|
||||
export const ENTITY_NAMES_SCENE_DOCUMENT_VERSION = 15;
|
||||
export const SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION = 13;
|
||||
export const ANIMATION_PLAYBACK_SCENE_DOCUMENT_VERSION = 12;
|
||||
export const LOCAL_LIGHTS_AND_SKYBOX_SCENE_DOCUMENT_VERSION = 10;
|
||||
export const MODEL_ASSET_PIPELINE_SCENE_DOCUMENT_VERSION = 9;
|
||||
export const FOUNDATION_SCENE_DOCUMENT_VERSION = 1;
|
||||
export const BOX_BRUSH_SCENE_DOCUMENT_VERSION = 2;
|
||||
export const FACE_MATERIALS_SCENE_DOCUMENT_VERSION = 3;
|
||||
export const RUNNER_V1_SCENE_DOCUMENT_VERSION = 4;
|
||||
export const FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION = 5;
|
||||
export const WORLD_ENVIRONMENT_SCENE_DOCUMENT_VERSION = 6;
|
||||
export const ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION = 7;
|
||||
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION = 8;
|
||||
export function createEmptySceneDocument(overrides = {}) {
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: overrides.name ?? "Untitled Scene",
|
||||
world: overrides.world ?? createDefaultWorldSettings(),
|
||||
materials: cloneMaterialRegistry(overrides.materials ?? createStarterMaterialRegistry()),
|
||||
textures: {},
|
||||
assets: {},
|
||||
brushes: {},
|
||||
modelInstances: {},
|
||||
entities: {},
|
||||
interactionLinks: {}
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,32 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import type { Brush } from "./brushes";
|
||||
import type { ModelInstance } from "../assets/model-instances";
|
||||
import type { ProjectAssetRecord } from "../assets/project-assets";
|
||||
import type { EntityInstance } from "../entities/entity-instances";
|
||||
import type { InteractionLink } from "../interactions/interaction-links";
|
||||
import { cloneMaterialRegistry, createStarterMaterialRegistry, type MaterialDef } from "../materials/starter-material-library";
|
||||
import { createDefaultWorldSettings, type WorldSettings } from "./world-settings";
|
||||
import {
|
||||
cloneMaterialRegistry,
|
||||
createStarterMaterialRegistry,
|
||||
type MaterialDef
|
||||
} from "../materials/starter-material-library";
|
||||
import {
|
||||
createDefaultWorldSettings,
|
||||
type WorldSettings
|
||||
} from "./world-settings";
|
||||
|
||||
export const SCENE_DOCUMENT_VERSION = 18 as const;
|
||||
export const SCENE_DOCUMENT_VERSION = 28 as const;
|
||||
export const PROJECT_NAME_SCENE_DOCUMENT_VERSION = 28 as const;
|
||||
export const PLAYER_START_GAMEPAD_CAMERA_LOOK_SCENE_DOCUMENT_VERSION = 27 as const;
|
||||
export const PLAYER_START_INPUT_BINDINGS_SCENE_DOCUMENT_VERSION = 26 as const;
|
||||
export const PLAYER_START_NAVIGATION_MODE_SCENE_DOCUMENT_VERSION = 25 as const;
|
||||
export const SCENE_TRANSITION_ENTITIES_SCENE_DOCUMENT_VERSION = 24 as const;
|
||||
export const MULTI_SCENE_FOUNDATION_SCENE_DOCUMENT_VERSION = 22 as const;
|
||||
export const WATER_SURFACE_DISPLACEMENT_SCENE_DOCUMENT_VERSION = 21 as const;
|
||||
export const WHITEBOX_BOX_VOLUME_SCENE_DOCUMENT_VERSION = 20 as const;
|
||||
export const WHITEBOX_GEOMETRY_SCENE_DOCUMENT_VERSION = 19 as const;
|
||||
export const WHITEBOX_FLOAT_TRANSFORM_SCENE_DOCUMENT_VERSION = 18 as const;
|
||||
export const PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION = 17 as const;
|
||||
export const PLAYER_START_COLLIDER_SETTINGS_SCENE_DOCUMENT_VERSION =
|
||||
17 as const;
|
||||
export const IMPORTED_MODEL_COLLIDERS_SCENE_DOCUMENT_VERSION = 16 as const;
|
||||
export const ENTITY_NAMES_SCENE_DOCUMENT_VERSION = 15 as const;
|
||||
export const SPATIAL_AUDIO_SCENE_DOCUMENT_VERSION = 13 as const;
|
||||
@@ -22,7 +40,39 @@ export const RUNNER_V1_SCENE_DOCUMENT_VERSION = 4 as const;
|
||||
export const FIRST_ROOM_POLISH_SCENE_DOCUMENT_VERSION = 5 as const;
|
||||
export const WORLD_ENVIRONMENT_SCENE_DOCUMENT_VERSION = 6 as const;
|
||||
export const ENTITY_SYSTEM_FOUNDATION_SCENE_DOCUMENT_VERSION = 7 as const;
|
||||
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION = 8 as const;
|
||||
export const TRIGGER_ACTION_TARGET_FOUNDATION_SCENE_DOCUMENT_VERSION =
|
||||
8 as const;
|
||||
export const RUNNER_LOADING_SCREEN_SCENE_DOCUMENT_VERSION = 23 as const;
|
||||
|
||||
export const DEFAULT_PROJECT_NAME = "Untitled Project" as const;
|
||||
export const DEFAULT_PROJECT_SCENE_ID = "scene-main" as const;
|
||||
|
||||
export interface SceneLoadingScreenSettings {
|
||||
colorHex: string;
|
||||
headline: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export interface ProjectScene {
|
||||
id: string;
|
||||
name: string;
|
||||
loadingScreen: SceneLoadingScreenSettings;
|
||||
world: WorldSettings;
|
||||
brushes: Record<string, Brush>;
|
||||
modelInstances: Record<string, ModelInstance>;
|
||||
entities: Record<string, EntityInstance>;
|
||||
interactionLinks: Record<string, InteractionLink>;
|
||||
}
|
||||
|
||||
export interface ProjectDocument {
|
||||
version: typeof SCENE_DOCUMENT_VERSION;
|
||||
name: string;
|
||||
activeSceneId: string;
|
||||
scenes: Record<string, ProjectScene>;
|
||||
materials: Record<string, MaterialDef>;
|
||||
textures: Record<string, never>;
|
||||
assets: Record<string, ProjectAssetRecord>;
|
||||
}
|
||||
|
||||
export interface SceneDocument {
|
||||
version: typeof SCENE_DOCUMENT_VERSION;
|
||||
@@ -37,12 +87,16 @@ export interface SceneDocument {
|
||||
interactionLinks: Record<string, InteractionLink>;
|
||||
}
|
||||
|
||||
export function createEmptySceneDocument(overrides: Partial<Pick<SceneDocument, "name" | "world" | "materials">> = {}): SceneDocument {
|
||||
export function createEmptySceneDocument(
|
||||
overrides: Partial<Pick<SceneDocument, "name" | "world" | "materials">> = {}
|
||||
): SceneDocument {
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: overrides.name ?? "Untitled Scene",
|
||||
world: overrides.world ?? createDefaultWorldSettings(),
|
||||
materials: cloneMaterialRegistry(overrides.materials ?? createStarterMaterialRegistry()),
|
||||
materials: cloneMaterialRegistry(
|
||||
overrides.materials ?? createStarterMaterialRegistry()
|
||||
),
|
||||
textures: {},
|
||||
assets: {},
|
||||
brushes: {},
|
||||
@@ -51,3 +105,173 @@ export function createEmptySceneDocument(overrides: Partial<Pick<SceneDocument,
|
||||
interactionLinks: {}
|
||||
};
|
||||
}
|
||||
|
||||
export function createEmptyProjectScene(
|
||||
overrides: Partial<
|
||||
Pick<ProjectScene, "id" | "name" | "loadingScreen" | "world">
|
||||
> = {}
|
||||
): ProjectScene {
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("scene"),
|
||||
name: overrides.name ?? "Untitled Scene",
|
||||
loadingScreen: cloneSceneLoadingScreenSettings(
|
||||
overrides.loadingScreen ?? createDefaultSceneLoadingScreenSettings()
|
||||
),
|
||||
world: overrides.world ?? createDefaultWorldSettings(),
|
||||
brushes: {},
|
||||
modelInstances: {},
|
||||
entities: {},
|
||||
interactionLinks: {}
|
||||
};
|
||||
}
|
||||
|
||||
export function createEmptyProjectDocument(
|
||||
overrides: Partial<
|
||||
Pick<
|
||||
ProjectDocument,
|
||||
"name" | "activeSceneId" | "materials" | "textures" | "assets"
|
||||
>
|
||||
> & {
|
||||
sceneId?: string;
|
||||
sceneName?: string;
|
||||
world?: WorldSettings;
|
||||
} = {}
|
||||
): ProjectDocument {
|
||||
const initialScene = createEmptyProjectScene({
|
||||
id:
|
||||
overrides.sceneId ?? overrides.activeSceneId ?? DEFAULT_PROJECT_SCENE_ID,
|
||||
name: overrides.sceneName,
|
||||
world: overrides.world
|
||||
});
|
||||
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: overrides.name ?? DEFAULT_PROJECT_NAME,
|
||||
activeSceneId: initialScene.id,
|
||||
scenes: {
|
||||
[initialScene.id]: initialScene
|
||||
},
|
||||
materials: cloneMaterialRegistry(
|
||||
overrides.materials ?? createStarterMaterialRegistry()
|
||||
),
|
||||
textures: overrides.textures ?? {},
|
||||
assets: overrides.assets ?? {}
|
||||
};
|
||||
}
|
||||
|
||||
export function getProjectScene(
|
||||
projectDocument: ProjectDocument,
|
||||
sceneId = projectDocument.activeSceneId
|
||||
): ProjectScene {
|
||||
const scene = projectDocument.scenes[sceneId];
|
||||
|
||||
if (scene === undefined) {
|
||||
throw new Error(`Project scene ${sceneId} does not exist.`);
|
||||
}
|
||||
|
||||
return scene;
|
||||
}
|
||||
|
||||
export function createSceneDocumentFromProject(
|
||||
projectDocument: ProjectDocument,
|
||||
sceneId = projectDocument.activeSceneId
|
||||
): SceneDocument {
|
||||
const scene = getProjectScene(projectDocument, sceneId);
|
||||
|
||||
return {
|
||||
version: projectDocument.version,
|
||||
name: scene.name,
|
||||
world: scene.world,
|
||||
materials: projectDocument.materials,
|
||||
textures: projectDocument.textures,
|
||||
assets: projectDocument.assets,
|
||||
brushes: scene.brushes,
|
||||
modelInstances: scene.modelInstances,
|
||||
entities: scene.entities,
|
||||
interactionLinks: scene.interactionLinks
|
||||
};
|
||||
}
|
||||
|
||||
export function createProjectDocumentFromSceneDocument(
|
||||
sceneDocument: SceneDocument,
|
||||
sceneId = DEFAULT_PROJECT_SCENE_ID,
|
||||
projectName = DEFAULT_PROJECT_NAME
|
||||
): ProjectDocument {
|
||||
return {
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
name: projectName,
|
||||
activeSceneId: sceneId,
|
||||
scenes: {
|
||||
[sceneId]: {
|
||||
id: sceneId,
|
||||
name: sceneDocument.name,
|
||||
loadingScreen: createDefaultSceneLoadingScreenSettings(),
|
||||
world: sceneDocument.world,
|
||||
brushes: sceneDocument.brushes,
|
||||
modelInstances: sceneDocument.modelInstances,
|
||||
entities: sceneDocument.entities,
|
||||
interactionLinks: sceneDocument.interactionLinks
|
||||
}
|
||||
},
|
||||
materials: sceneDocument.materials,
|
||||
textures: sceneDocument.textures,
|
||||
assets: sceneDocument.assets
|
||||
};
|
||||
}
|
||||
|
||||
export function applySceneDocumentToProject(
|
||||
projectDocument: ProjectDocument,
|
||||
sceneId: string,
|
||||
sceneDocument: SceneDocument
|
||||
): ProjectDocument {
|
||||
const previousScene = getProjectScene(projectDocument, sceneId);
|
||||
|
||||
return {
|
||||
...projectDocument,
|
||||
version: SCENE_DOCUMENT_VERSION,
|
||||
materials: sceneDocument.materials,
|
||||
textures: sceneDocument.textures,
|
||||
assets: sceneDocument.assets,
|
||||
scenes: {
|
||||
...projectDocument.scenes,
|
||||
[sceneId]: {
|
||||
...previousScene,
|
||||
name: sceneDocument.name,
|
||||
world: sceneDocument.world,
|
||||
brushes: sceneDocument.brushes,
|
||||
modelInstances: sceneDocument.modelInstances,
|
||||
entities: sceneDocument.entities,
|
||||
interactionLinks: sceneDocument.interactionLinks
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createDefaultSceneLoadingScreenSettings(): SceneLoadingScreenSettings {
|
||||
return {
|
||||
colorHex: "#0d1117",
|
||||
headline: null,
|
||||
description: null
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneSceneLoadingScreenSettings(
|
||||
settings: SceneLoadingScreenSettings
|
||||
): SceneLoadingScreenSettings {
|
||||
return {
|
||||
colorHex: settings.colorHex,
|
||||
headline: settings.headline,
|
||||
description: settings.description
|
||||
};
|
||||
}
|
||||
|
||||
export function areSceneLoadingScreenSettingsEqual(
|
||||
left: SceneLoadingScreenSettings,
|
||||
right: SceneLoadingScreenSettings
|
||||
): boolean {
|
||||
return (
|
||||
left.colorHex === right.colorHex &&
|
||||
left.headline === right.headline &&
|
||||
left.description === right.description
|
||||
);
|
||||
}
|
||||
|
||||
254
src/document/world-settings.js
Normal file
254
src/document/world-settings.js
Normal file
@@ -0,0 +1,254 @@
|
||||
import { DEFAULT_SUN_DIRECTION } from "../core/vector";
|
||||
export const ADVANCED_RENDERING_SHADOW_MAP_SIZES = [512, 1024, 2048, 4096];
|
||||
export const ADVANCED_RENDERING_SHADOW_TYPES = ["basic", "pcf", "pcfSoft"];
|
||||
export const ADVANCED_RENDERING_TONE_MAPPING_MODES = ["none", "linear", "reinhard", "cineon", "acesFilmic"];
|
||||
export const BOX_VOLUME_RENDER_PATHS = ["performance", "quality"];
|
||||
export const ADVANCED_RENDERING_WATER_REFLECTION_MODES = ["none", "world", "all"];
|
||||
const DEFAULT_SOLID_BACKGROUND_COLOR = "#2f3947";
|
||||
const DEFAULT_GRADIENT_TOP_COLOR = DEFAULT_SOLID_BACKGROUND_COLOR;
|
||||
const DEFAULT_GRADIENT_BOTTOM_COLOR = "#141a22";
|
||||
const DEFAULT_ADVANCED_RENDERING_SHADOW_MAP_SIZE = 2048;
|
||||
const DEFAULT_ADVANCED_RENDERING_SHADOW_TYPE = "pcfSoft";
|
||||
const DEFAULT_ADVANCED_RENDERING_SHADOW_BIAS = -0.0005;
|
||||
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_INTENSITY = 1;
|
||||
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_RADIUS = 0.5;
|
||||
const DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_SAMPLES = 8;
|
||||
const DEFAULT_ADVANCED_RENDERING_BLOOM_INTENSITY = 0.75;
|
||||
const DEFAULT_ADVANCED_RENDERING_BLOOM_THRESHOLD = 0.85;
|
||||
const DEFAULT_ADVANCED_RENDERING_BLOOM_RADIUS = 0.35;
|
||||
const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_MODE = "acesFilmic";
|
||||
const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE = 1;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE = 10;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH = 0.03;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE = 1.5;
|
||||
const DEFAULT_BOX_VOLUME_RENDER_PATH = "performance";
|
||||
const DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE = "none";
|
||||
export function isAdvancedRenderingShadowMapSize(value) {
|
||||
return ADVANCED_RENDERING_SHADOW_MAP_SIZES.includes(value);
|
||||
}
|
||||
export function isAdvancedRenderingShadowType(value) {
|
||||
return ADVANCED_RENDERING_SHADOW_TYPES.includes(value);
|
||||
}
|
||||
export function isAdvancedRenderingToneMappingMode(value) {
|
||||
return ADVANCED_RENDERING_TONE_MAPPING_MODES.includes(value);
|
||||
}
|
||||
export function isBoxVolumeRenderPath(value) {
|
||||
return BOX_VOLUME_RENDER_PATHS.includes(value);
|
||||
}
|
||||
export function isAdvancedRenderingWaterReflectionMode(value) {
|
||||
return ADVANCED_RENDERING_WATER_REFLECTION_MODES.includes(value);
|
||||
}
|
||||
export function createDefaultAdvancedRenderingSettings() {
|
||||
return {
|
||||
enabled: false,
|
||||
shadows: {
|
||||
enabled: false,
|
||||
mapSize: DEFAULT_ADVANCED_RENDERING_SHADOW_MAP_SIZE,
|
||||
type: DEFAULT_ADVANCED_RENDERING_SHADOW_TYPE,
|
||||
bias: DEFAULT_ADVANCED_RENDERING_SHADOW_BIAS
|
||||
},
|
||||
ambientOcclusion: {
|
||||
enabled: false,
|
||||
intensity: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_INTENSITY,
|
||||
radius: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_RADIUS,
|
||||
samples: DEFAULT_ADVANCED_RENDERING_AMBIENT_OCCLUSION_SAMPLES
|
||||
},
|
||||
bloom: {
|
||||
enabled: false,
|
||||
intensity: DEFAULT_ADVANCED_RENDERING_BLOOM_INTENSITY,
|
||||
threshold: DEFAULT_ADVANCED_RENDERING_BLOOM_THRESHOLD,
|
||||
radius: DEFAULT_ADVANCED_RENDERING_BLOOM_RADIUS
|
||||
},
|
||||
toneMapping: {
|
||||
mode: DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_MODE,
|
||||
exposure: DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE
|
||||
},
|
||||
depthOfField: {
|
||||
enabled: false,
|
||||
focusDistance: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE,
|
||||
focalLength: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH,
|
||||
bokehScale: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE
|
||||
},
|
||||
fogPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
|
||||
waterPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
|
||||
waterReflectionMode: DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE
|
||||
};
|
||||
}
|
||||
export function createDefaultWorldSettings() {
|
||||
return {
|
||||
background: {
|
||||
mode: "solid",
|
||||
colorHex: DEFAULT_SOLID_BACKGROUND_COLOR
|
||||
},
|
||||
ambientLight: {
|
||||
colorHex: "#f7f1e8",
|
||||
intensity: 1
|
||||
},
|
||||
sunLight: {
|
||||
colorHex: "#fff1d5",
|
||||
intensity: 1.75,
|
||||
direction: {
|
||||
...DEFAULT_SUN_DIRECTION
|
||||
}
|
||||
},
|
||||
advancedRendering: createDefaultAdvancedRenderingSettings()
|
||||
};
|
||||
}
|
||||
export function isHexColorString(value) {
|
||||
return /^#[0-9a-f]{6}$/i.test(value);
|
||||
}
|
||||
export function isWorldBackgroundMode(value) {
|
||||
return value === "solid" || value === "verticalGradient" || value === "image";
|
||||
}
|
||||
export function cloneWorldBackgroundSettings(background) {
|
||||
if (background.mode === "solid") {
|
||||
return {
|
||||
mode: "solid",
|
||||
colorHex: background.colorHex
|
||||
};
|
||||
}
|
||||
if (background.mode === "verticalGradient") {
|
||||
return {
|
||||
mode: "verticalGradient",
|
||||
topColorHex: background.topColorHex,
|
||||
bottomColorHex: background.bottomColorHex
|
||||
};
|
||||
}
|
||||
return {
|
||||
mode: "image",
|
||||
assetId: background.assetId,
|
||||
environmentIntensity: background.environmentIntensity
|
||||
};
|
||||
}
|
||||
export function cloneWorldSettings(world) {
|
||||
return {
|
||||
background: cloneWorldBackgroundSettings(world.background),
|
||||
ambientLight: {
|
||||
...world.ambientLight
|
||||
},
|
||||
sunLight: {
|
||||
...world.sunLight,
|
||||
direction: {
|
||||
...world.sunLight.direction
|
||||
}
|
||||
},
|
||||
advancedRendering: cloneAdvancedRenderingSettings(world.advancedRendering)
|
||||
};
|
||||
}
|
||||
export function cloneAdvancedRenderingSettings(settings) {
|
||||
return {
|
||||
enabled: settings.enabled,
|
||||
shadows: {
|
||||
...settings.shadows
|
||||
},
|
||||
ambientOcclusion: {
|
||||
...settings.ambientOcclusion
|
||||
},
|
||||
bloom: {
|
||||
...settings.bloom
|
||||
},
|
||||
toneMapping: {
|
||||
...settings.toneMapping
|
||||
},
|
||||
depthOfField: {
|
||||
...settings.depthOfField
|
||||
},
|
||||
fogPath: settings.fogPath,
|
||||
waterPath: settings.waterPath,
|
||||
waterReflectionMode: settings.waterReflectionMode
|
||||
};
|
||||
}
|
||||
export function areWorldBackgroundSettingsEqual(left, right) {
|
||||
if (left.mode !== right.mode) {
|
||||
return false;
|
||||
}
|
||||
if (left.mode === "solid" && right.mode === "solid") {
|
||||
return left.colorHex === right.colorHex;
|
||||
}
|
||||
if (left.mode === "verticalGradient" && right.mode === "verticalGradient") {
|
||||
return left.topColorHex === right.topColorHex && left.bottomColorHex === right.bottomColorHex;
|
||||
}
|
||||
return left.mode === "image" && right.mode === "image" && left.assetId === right.assetId && left.environmentIntensity === right.environmentIntensity;
|
||||
}
|
||||
export function areWorldSettingsEqual(left, right) {
|
||||
return (areWorldBackgroundSettingsEqual(left.background, right.background) &&
|
||||
left.ambientLight.colorHex === right.ambientLight.colorHex &&
|
||||
left.ambientLight.intensity === right.ambientLight.intensity &&
|
||||
left.sunLight.colorHex === right.sunLight.colorHex &&
|
||||
left.sunLight.intensity === right.sunLight.intensity &&
|
||||
left.sunLight.direction.x === right.sunLight.direction.x &&
|
||||
left.sunLight.direction.y === right.sunLight.direction.y &&
|
||||
left.sunLight.direction.z === right.sunLight.direction.z &&
|
||||
areAdvancedRenderingSettingsEqual(left.advancedRendering, right.advancedRendering));
|
||||
}
|
||||
export function areAdvancedRenderingSettingsEqual(left, right) {
|
||||
return (left.enabled === right.enabled &&
|
||||
left.shadows.enabled === right.shadows.enabled &&
|
||||
left.shadows.mapSize === right.shadows.mapSize &&
|
||||
left.shadows.type === right.shadows.type &&
|
||||
left.shadows.bias === right.shadows.bias &&
|
||||
left.ambientOcclusion.enabled === right.ambientOcclusion.enabled &&
|
||||
left.ambientOcclusion.intensity === right.ambientOcclusion.intensity &&
|
||||
left.ambientOcclusion.radius === right.ambientOcclusion.radius &&
|
||||
left.ambientOcclusion.samples === right.ambientOcclusion.samples &&
|
||||
left.bloom.enabled === right.bloom.enabled &&
|
||||
left.bloom.intensity === right.bloom.intensity &&
|
||||
left.bloom.threshold === right.bloom.threshold &&
|
||||
left.bloom.radius === right.bloom.radius &&
|
||||
left.toneMapping.mode === right.toneMapping.mode &&
|
||||
left.toneMapping.exposure === right.toneMapping.exposure &&
|
||||
left.depthOfField.enabled === right.depthOfField.enabled &&
|
||||
left.depthOfField.focusDistance === right.depthOfField.focusDistance &&
|
||||
left.depthOfField.focalLength === right.depthOfField.focalLength &&
|
||||
left.depthOfField.bokehScale === right.depthOfField.bokehScale &&
|
||||
left.fogPath === right.fogPath &&
|
||||
left.waterPath === right.waterPath &&
|
||||
left.waterReflectionMode === right.waterReflectionMode);
|
||||
}
|
||||
export function changeWorldBackgroundMode(background, mode, imageAssetId) {
|
||||
if (mode === "image") {
|
||||
if (imageAssetId === undefined || imageAssetId.trim().length === 0) {
|
||||
if (background.mode === "image") {
|
||||
return cloneWorldBackgroundSettings(background);
|
||||
}
|
||||
throw new Error("An image asset must be selected to use an image background.");
|
||||
}
|
||||
return {
|
||||
mode: "image",
|
||||
assetId: imageAssetId,
|
||||
environmentIntensity: background.mode === "image" ? background.environmentIntensity : 0.5
|
||||
};
|
||||
}
|
||||
if (background.mode === mode) {
|
||||
return cloneWorldBackgroundSettings(background);
|
||||
}
|
||||
if (mode === "solid") {
|
||||
return {
|
||||
mode: "solid",
|
||||
colorHex: background.mode === "solid"
|
||||
? background.colorHex
|
||||
: background.mode === "verticalGradient"
|
||||
? background.topColorHex
|
||||
: DEFAULT_SOLID_BACKGROUND_COLOR
|
||||
};
|
||||
}
|
||||
if (background.mode === "solid") {
|
||||
return {
|
||||
mode: "verticalGradient",
|
||||
topColorHex: background.colorHex,
|
||||
bottomColorHex: DEFAULT_GRADIENT_BOTTOM_COLOR
|
||||
};
|
||||
}
|
||||
if (background.mode === "verticalGradient") {
|
||||
return {
|
||||
mode: "verticalGradient",
|
||||
topColorHex: background.topColorHex,
|
||||
bottomColorHex: background.bottomColorHex
|
||||
};
|
||||
}
|
||||
return {
|
||||
mode: "verticalGradient",
|
||||
topColorHex: DEFAULT_GRADIENT_TOP_COLOR,
|
||||
bottomColorHex: DEFAULT_GRADIENT_BOTTOM_COLOR
|
||||
};
|
||||
}
|
||||
@@ -5,10 +5,14 @@ export type WorldBackgroundMode = "solid" | "verticalGradient" | "image";
|
||||
export const ADVANCED_RENDERING_SHADOW_MAP_SIZES = [512, 1024, 2048, 4096] as const;
|
||||
export const ADVANCED_RENDERING_SHADOW_TYPES = ["basic", "pcf", "pcfSoft"] as const;
|
||||
export const ADVANCED_RENDERING_TONE_MAPPING_MODES = ["none", "linear", "reinhard", "cineon", "acesFilmic"] as const;
|
||||
export const BOX_VOLUME_RENDER_PATHS = ["performance", "quality"] as const;
|
||||
export const ADVANCED_RENDERING_WATER_REFLECTION_MODES = ["none", "world", "all"] as const;
|
||||
|
||||
export type AdvancedRenderingShadowMapSize = (typeof ADVANCED_RENDERING_SHADOW_MAP_SIZES)[number];
|
||||
export type AdvancedRenderingShadowType = (typeof ADVANCED_RENDERING_SHADOW_TYPES)[number];
|
||||
export type AdvancedRenderingToneMappingMode = (typeof ADVANCED_RENDERING_TONE_MAPPING_MODES)[number];
|
||||
export type BoxVolumeRenderPath = (typeof BOX_VOLUME_RENDER_PATHS)[number];
|
||||
export type AdvancedRenderingWaterReflectionMode = (typeof ADVANCED_RENDERING_WATER_REFLECTION_MODES)[number];
|
||||
|
||||
export interface WorldSolidBackgroundSettings {
|
||||
mode: "solid";
|
||||
@@ -83,6 +87,9 @@ export interface AdvancedRenderingSettings {
|
||||
bloom: AdvancedRenderingBloomSettings;
|
||||
toneMapping: AdvancedRenderingToneMappingSettings;
|
||||
depthOfField: AdvancedRenderingDepthOfFieldSettings;
|
||||
fogPath: BoxVolumeRenderPath;
|
||||
waterPath: BoxVolumeRenderPath;
|
||||
waterReflectionMode: AdvancedRenderingWaterReflectionMode;
|
||||
}
|
||||
|
||||
export interface WorldSettings {
|
||||
@@ -109,6 +116,8 @@ const DEFAULT_ADVANCED_RENDERING_TONE_MAPPING_EXPOSURE = 1;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE = 10;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH = 0.03;
|
||||
const DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE = 1.5;
|
||||
const DEFAULT_BOX_VOLUME_RENDER_PATH: BoxVolumeRenderPath = "performance";
|
||||
const DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE: AdvancedRenderingWaterReflectionMode = "none";
|
||||
|
||||
export function isAdvancedRenderingShadowMapSize(value: unknown): value is AdvancedRenderingShadowMapSize {
|
||||
return ADVANCED_RENDERING_SHADOW_MAP_SIZES.includes(value as AdvancedRenderingShadowMapSize);
|
||||
@@ -122,6 +131,14 @@ export function isAdvancedRenderingToneMappingMode(value: unknown): value is Adv
|
||||
return ADVANCED_RENDERING_TONE_MAPPING_MODES.includes(value as AdvancedRenderingToneMappingMode);
|
||||
}
|
||||
|
||||
export function isBoxVolumeRenderPath(value: unknown): value is BoxVolumeRenderPath {
|
||||
return BOX_VOLUME_RENDER_PATHS.includes(value as BoxVolumeRenderPath);
|
||||
}
|
||||
|
||||
export function isAdvancedRenderingWaterReflectionMode(value: unknown): value is AdvancedRenderingWaterReflectionMode {
|
||||
return ADVANCED_RENDERING_WATER_REFLECTION_MODES.includes(value as AdvancedRenderingWaterReflectionMode);
|
||||
}
|
||||
|
||||
export function createDefaultAdvancedRenderingSettings(): AdvancedRenderingSettings {
|
||||
return {
|
||||
enabled: false,
|
||||
@@ -152,7 +169,10 @@ export function createDefaultAdvancedRenderingSettings(): AdvancedRenderingSetti
|
||||
focusDistance: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCUS_DISTANCE,
|
||||
focalLength: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_FOCAL_LENGTH,
|
||||
bokehScale: DEFAULT_ADVANCED_RENDERING_DEPTH_OF_FIELD_BOKEH_SCALE
|
||||
}
|
||||
},
|
||||
fogPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
|
||||
waterPath: DEFAULT_BOX_VOLUME_RENDER_PATH,
|
||||
waterReflectionMode: DEFAULT_ADVANCED_RENDERING_WATER_REFLECTION_MODE
|
||||
};
|
||||
}
|
||||
|
||||
@@ -241,7 +261,10 @@ export function cloneAdvancedRenderingSettings(settings: AdvancedRenderingSettin
|
||||
},
|
||||
depthOfField: {
|
||||
...settings.depthOfField
|
||||
}
|
||||
},
|
||||
fogPath: settings.fogPath,
|
||||
waterPath: settings.waterPath,
|
||||
waterReflectionMode: settings.waterReflectionMode
|
||||
};
|
||||
}
|
||||
|
||||
@@ -295,7 +318,10 @@ export function areAdvancedRenderingSettingsEqual(left: AdvancedRenderingSetting
|
||||
left.depthOfField.enabled === right.depthOfField.enabled &&
|
||||
left.depthOfField.focusDistance === right.depthOfField.focusDistance &&
|
||||
left.depthOfField.focalLength === right.depthOfField.focalLength &&
|
||||
left.depthOfField.bokehScale === right.depthOfField.bokehScale
|
||||
left.depthOfField.bokehScale === right.depthOfField.bokehScale &&
|
||||
left.fogPath === right.fogPath &&
|
||||
left.waterPath === right.waterPath &&
|
||||
left.waterReflectionMode === right.waterReflectionMode
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
501
src/entities/entity-instances.js
Normal file
501
src/entities/entity-instances.js
Normal file
@@ -0,0 +1,501 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
import { isHexColorString } from "../document/world-settings";
|
||||
export const PLAYER_START_COLLIDER_MODES = ["capsule", "box", "none"];
|
||||
export const ENTITY_KIND_ORDER = [
|
||||
"pointLight",
|
||||
"spotLight",
|
||||
"playerStart",
|
||||
"soundEmitter",
|
||||
"triggerVolume",
|
||||
"teleportTarget",
|
||||
"interactable"
|
||||
];
|
||||
export const DEFAULT_POINT_LIGHT_POSITION = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_POINT_LIGHT_COLOR_HEX = "#ffffff";
|
||||
export const DEFAULT_POINT_LIGHT_INTENSITY = 1.25;
|
||||
export const DEFAULT_POINT_LIGHT_DISTANCE = 8;
|
||||
export const DEFAULT_SPOT_LIGHT_POSITION = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_SPOT_LIGHT_DIRECTION = {
|
||||
x: 0,
|
||||
y: -1,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_SPOT_LIGHT_COLOR_HEX = "#ffffff";
|
||||
export const DEFAULT_SPOT_LIGHT_INTENSITY = 1.5;
|
||||
export const DEFAULT_SPOT_LIGHT_DISTANCE = 12;
|
||||
export const DEFAULT_SPOT_LIGHT_ANGLE_DEGREES = 35;
|
||||
export const DEFAULT_ENTITY_POSITION = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
export const DEFAULT_PLAYER_START_POSITION = DEFAULT_ENTITY_POSITION;
|
||||
export const DEFAULT_PLAYER_START_YAW_DEGREES = 0;
|
||||
export const DEFAULT_PLAYER_START_COLLIDER_MODE = "capsule";
|
||||
export const DEFAULT_PLAYER_START_EYE_HEIGHT = 1.6;
|
||||
export const DEFAULT_PLAYER_START_CAPSULE_RADIUS = 0.3;
|
||||
export const DEFAULT_PLAYER_START_CAPSULE_HEIGHT = 1.8;
|
||||
export const DEFAULT_PLAYER_START_BOX_SIZE = {
|
||||
x: 0.6,
|
||||
y: 1.8,
|
||||
z: 0.6
|
||||
};
|
||||
export const DEFAULT_SOUND_EMITTER_AUDIO_ASSET_ID = null;
|
||||
export const DEFAULT_SOUND_EMITTER_VOLUME = 1;
|
||||
export const DEFAULT_SOUND_EMITTER_GAIN = DEFAULT_SOUND_EMITTER_VOLUME;
|
||||
export const DEFAULT_SOUND_EMITTER_REF_DISTANCE = 6;
|
||||
export const DEFAULT_SOUND_EMITTER_RADIUS = DEFAULT_SOUND_EMITTER_REF_DISTANCE;
|
||||
export const DEFAULT_SOUND_EMITTER_MAX_DISTANCE = 24;
|
||||
export const DEFAULT_TRIGGER_VOLUME_SIZE = {
|
||||
x: 2,
|
||||
y: 2,
|
||||
z: 2
|
||||
};
|
||||
export const DEFAULT_TELEPORT_TARGET_YAW_DEGREES = 0;
|
||||
export const DEFAULT_INTERACTABLE_RADIUS = 1.5;
|
||||
export const DEFAULT_INTERACTABLE_PROMPT = "Use";
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function areVec3Equal(left, right) {
|
||||
return left.x === right.x && left.y === right.y && left.z === right.z;
|
||||
}
|
||||
function assertFiniteVec3(vector, label) {
|
||||
if (!Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z)) {
|
||||
throw new Error(`${label} must be finite on every axis.`);
|
||||
}
|
||||
}
|
||||
function assertPositiveFiniteNumber(value, label) {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new Error(`${label} must be a finite number greater than zero.`);
|
||||
}
|
||||
}
|
||||
function assertPositiveFiniteVec3(vector, label) {
|
||||
assertFiniteVec3(vector, label);
|
||||
if (vector.x <= 0 || vector.y <= 0 || vector.z <= 0) {
|
||||
throw new Error(`${label} must remain positive on every axis.`);
|
||||
}
|
||||
}
|
||||
function assertNonNegativeFiniteNumber(value, label) {
|
||||
if (!Number.isFinite(value) || value < 0) {
|
||||
throw new Error(`${label} must be a finite number greater than or equal to zero.`);
|
||||
}
|
||||
}
|
||||
function assertHexColorString(value, label) {
|
||||
if (!isHexColorString(value)) {
|
||||
throw new Error(`${label} must use #RRGGBB format.`);
|
||||
}
|
||||
}
|
||||
function assertNonZeroVec3(vector, label) {
|
||||
if (vector.x === 0 && vector.y === 0 && vector.z === 0) {
|
||||
throw new Error(`${label} must not be the zero vector.`);
|
||||
}
|
||||
}
|
||||
function assertBoolean(value, label) {
|
||||
if (typeof value !== "boolean") {
|
||||
throw new Error(`${label} must be a boolean.`);
|
||||
}
|
||||
}
|
||||
export function isPlayerStartColliderMode(value) {
|
||||
return PLAYER_START_COLLIDER_MODES.includes(value);
|
||||
}
|
||||
export function clonePlayerStartColliderSettings(settings) {
|
||||
return {
|
||||
mode: settings.mode,
|
||||
eyeHeight: settings.eyeHeight,
|
||||
capsuleRadius: settings.capsuleRadius,
|
||||
capsuleHeight: settings.capsuleHeight,
|
||||
boxSize: cloneVec3(settings.boxSize)
|
||||
};
|
||||
}
|
||||
export function getPlayerStartColliderHeight(settings) {
|
||||
switch (settings.mode) {
|
||||
case "capsule":
|
||||
return settings.capsuleHeight;
|
||||
case "box":
|
||||
return settings.boxSize.y;
|
||||
case "none":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function createPlayerStartColliderSettings(overrides = {}) {
|
||||
const mode = overrides.mode ?? DEFAULT_PLAYER_START_COLLIDER_MODE;
|
||||
const eyeHeight = overrides.eyeHeight ?? DEFAULT_PLAYER_START_EYE_HEIGHT;
|
||||
const capsuleRadius = overrides.capsuleRadius ?? DEFAULT_PLAYER_START_CAPSULE_RADIUS;
|
||||
const capsuleHeight = overrides.capsuleHeight ?? DEFAULT_PLAYER_START_CAPSULE_HEIGHT;
|
||||
const boxSize = cloneVec3(overrides.boxSize ?? DEFAULT_PLAYER_START_BOX_SIZE);
|
||||
if (!isPlayerStartColliderMode(mode)) {
|
||||
throw new Error("Player Start collider mode must be capsule, box, or none.");
|
||||
}
|
||||
assertPositiveFiniteNumber(eyeHeight, "Player Start eye height");
|
||||
assertPositiveFiniteNumber(capsuleRadius, "Player Start capsule radius");
|
||||
assertPositiveFiniteNumber(capsuleHeight, "Player Start capsule height");
|
||||
assertPositiveFiniteVec3(boxSize, "Player Start box size");
|
||||
if (capsuleHeight < capsuleRadius * 2) {
|
||||
throw new Error("Player Start capsule height must be at least twice the capsule radius.");
|
||||
}
|
||||
if (mode === "capsule" && eyeHeight > capsuleHeight) {
|
||||
throw new Error("Player Start eye height must be less than or equal to the capsule height.");
|
||||
}
|
||||
if (mode === "box" && eyeHeight > boxSize.y) {
|
||||
throw new Error("Player Start eye height must be less than or equal to the box height.");
|
||||
}
|
||||
return {
|
||||
mode,
|
||||
eyeHeight,
|
||||
capsuleRadius,
|
||||
capsuleHeight,
|
||||
boxSize
|
||||
};
|
||||
}
|
||||
function normalizeSoundEmitterAudioAssetId(audioAssetId) {
|
||||
if (audioAssetId === undefined || audioAssetId === null) {
|
||||
return null;
|
||||
}
|
||||
const trimmedAudioAssetId = audioAssetId.trim();
|
||||
if (trimmedAudioAssetId.length === 0) {
|
||||
throw new Error("Sound Emitter audio asset id must be non-empty when authored.");
|
||||
}
|
||||
return trimmedAudioAssetId;
|
||||
}
|
||||
export function normalizeEntityName(name) {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
}
|
||||
const trimmedName = name.trim();
|
||||
return trimmedName.length === 0 ? undefined : trimmedName;
|
||||
}
|
||||
export function normalizeYawDegrees(yawDegrees) {
|
||||
const normalizedYaw = yawDegrees % 360;
|
||||
return normalizedYaw < 0 ? normalizedYaw + 360 : normalizedYaw;
|
||||
}
|
||||
export function normalizeInteractablePrompt(prompt) {
|
||||
const normalizedPrompt = prompt.trim();
|
||||
if (normalizedPrompt.length === 0) {
|
||||
throw new Error("Interactable prompt must be non-empty.");
|
||||
}
|
||||
return normalizedPrompt;
|
||||
}
|
||||
export function createPointLightEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_POINT_LIGHT_POSITION);
|
||||
const colorHex = overrides.colorHex ?? DEFAULT_POINT_LIGHT_COLOR_HEX;
|
||||
const intensity = overrides.intensity ?? DEFAULT_POINT_LIGHT_INTENSITY;
|
||||
const distance = overrides.distance ?? DEFAULT_POINT_LIGHT_DISTANCE;
|
||||
assertFiniteVec3(position, "Point Light position");
|
||||
assertHexColorString(colorHex, "Point Light color");
|
||||
assertNonNegativeFiniteNumber(intensity, "Point Light intensity");
|
||||
assertPositiveFiniteNumber(distance, "Point Light distance");
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-point-light"),
|
||||
kind: "pointLight",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
colorHex,
|
||||
intensity,
|
||||
distance
|
||||
};
|
||||
}
|
||||
export function createSpotLightEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_SPOT_LIGHT_POSITION);
|
||||
const direction = cloneVec3(overrides.direction ?? DEFAULT_SPOT_LIGHT_DIRECTION);
|
||||
const colorHex = overrides.colorHex ?? DEFAULT_SPOT_LIGHT_COLOR_HEX;
|
||||
const intensity = overrides.intensity ?? DEFAULT_SPOT_LIGHT_INTENSITY;
|
||||
const distance = overrides.distance ?? DEFAULT_SPOT_LIGHT_DISTANCE;
|
||||
const angleDegrees = overrides.angleDegrees ?? DEFAULT_SPOT_LIGHT_ANGLE_DEGREES;
|
||||
assertFiniteVec3(position, "Spot Light position");
|
||||
assertFiniteVec3(direction, "Spot Light direction");
|
||||
assertNonZeroVec3(direction, "Spot Light direction");
|
||||
assertHexColorString(colorHex, "Spot Light color");
|
||||
assertNonNegativeFiniteNumber(intensity, "Spot Light intensity");
|
||||
assertPositiveFiniteNumber(distance, "Spot Light distance");
|
||||
if (!Number.isFinite(angleDegrees) || angleDegrees <= 0 || angleDegrees >= 180) {
|
||||
throw new Error("Spot Light angle must be a finite degree value between 0 and 180.");
|
||||
}
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-spot-light"),
|
||||
kind: "spotLight",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
direction,
|
||||
colorHex,
|
||||
intensity,
|
||||
distance,
|
||||
angleDegrees
|
||||
};
|
||||
}
|
||||
export function createPlayerStartEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_PLAYER_START_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_PLAYER_START_YAW_DEGREES;
|
||||
const collider = createPlayerStartColliderSettings(overrides.collider);
|
||||
assertFiniteVec3(position, "Player Start position");
|
||||
if (!Number.isFinite(yawDegrees)) {
|
||||
throw new Error("Player Start yaw must be a finite number.");
|
||||
}
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-player-start"),
|
||||
kind: "playerStart",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees),
|
||||
collider
|
||||
};
|
||||
}
|
||||
export function createSoundEmitterEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const audioAssetId = normalizeSoundEmitterAudioAssetId(overrides.audioAssetId ?? DEFAULT_SOUND_EMITTER_AUDIO_ASSET_ID);
|
||||
const volume = overrides.volume ?? DEFAULT_SOUND_EMITTER_VOLUME;
|
||||
const refDistance = overrides.refDistance ?? DEFAULT_SOUND_EMITTER_REF_DISTANCE;
|
||||
const maxDistance = overrides.maxDistance ?? DEFAULT_SOUND_EMITTER_MAX_DISTANCE;
|
||||
const autoplay = overrides.autoplay ?? false;
|
||||
const loop = overrides.loop ?? false;
|
||||
assertFiniteVec3(position, "Sound Emitter position");
|
||||
assertNonNegativeFiniteNumber(volume, "Sound Emitter volume");
|
||||
assertPositiveFiniteNumber(refDistance, "Sound Emitter ref distance");
|
||||
assertPositiveFiniteNumber(maxDistance, "Sound Emitter max distance");
|
||||
if (maxDistance < refDistance) {
|
||||
throw new Error("Sound Emitter max distance must be greater than or equal to ref distance.");
|
||||
}
|
||||
assertBoolean(autoplay, "Sound Emitter autoplay");
|
||||
assertBoolean(loop, "Sound Emitter loop");
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-sound-emitter"),
|
||||
kind: "soundEmitter",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
audioAssetId,
|
||||
volume,
|
||||
refDistance,
|
||||
maxDistance,
|
||||
autoplay,
|
||||
loop
|
||||
};
|
||||
}
|
||||
export function createTriggerVolumeEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const size = cloneVec3(overrides.size ?? DEFAULT_TRIGGER_VOLUME_SIZE);
|
||||
const triggerOnEnter = overrides.triggerOnEnter ?? true;
|
||||
const triggerOnExit = overrides.triggerOnExit ?? false;
|
||||
assertFiniteVec3(position, "Trigger Volume position");
|
||||
assertPositiveFiniteVec3(size, "Trigger Volume size");
|
||||
assertBoolean(triggerOnEnter, "Trigger Volume triggerOnEnter");
|
||||
assertBoolean(triggerOnExit, "Trigger Volume triggerOnExit");
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-trigger-volume"),
|
||||
kind: "triggerVolume",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
size,
|
||||
triggerOnEnter,
|
||||
triggerOnExit
|
||||
};
|
||||
}
|
||||
export function createTeleportTargetEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_TELEPORT_TARGET_YAW_DEGREES;
|
||||
assertFiniteVec3(position, "Teleport Target position");
|
||||
if (!Number.isFinite(yawDegrees)) {
|
||||
throw new Error("Teleport Target yaw must be a finite number.");
|
||||
}
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-teleport-target"),
|
||||
kind: "teleportTarget",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees)
|
||||
};
|
||||
}
|
||||
export function createInteractableEntity(overrides = {}) {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const radius = overrides.radius ?? DEFAULT_INTERACTABLE_RADIUS;
|
||||
const prompt = normalizeInteractablePrompt(overrides.prompt ?? DEFAULT_INTERACTABLE_PROMPT);
|
||||
const enabled = overrides.enabled ?? true;
|
||||
assertFiniteVec3(position, "Interactable position");
|
||||
assertPositiveFiniteNumber(radius, "Interactable radius");
|
||||
assertBoolean(enabled, "Interactable enabled");
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-interactable"),
|
||||
kind: "interactable",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
radius,
|
||||
prompt,
|
||||
enabled
|
||||
};
|
||||
}
|
||||
export const ENTITY_REGISTRY = {
|
||||
pointLight: {
|
||||
kind: "pointLight",
|
||||
label: "Point Light",
|
||||
description: "Authored local point light that illuminates nearby geometry in a spherical radius.",
|
||||
createDefaultEntity: createPointLightEntity
|
||||
},
|
||||
spotLight: {
|
||||
kind: "spotLight",
|
||||
label: "Spot Light",
|
||||
description: "Authored local spotlight with an explicit direction and cone angle.",
|
||||
createDefaultEntity: createSpotLightEntity
|
||||
},
|
||||
playerStart: {
|
||||
kind: "playerStart",
|
||||
label: "Player Start",
|
||||
description: "Primary authored spawn point for first-person runtime navigation.",
|
||||
createDefaultEntity: createPlayerStartEntity
|
||||
},
|
||||
soundEmitter: {
|
||||
kind: "soundEmitter",
|
||||
label: "Sound Emitter",
|
||||
description: "Authored positional audio source wired to an audio asset and configurable for looping, volume, and distance falloff.",
|
||||
createDefaultEntity: createSoundEmitterEntity
|
||||
},
|
||||
triggerVolume: {
|
||||
kind: "triggerVolume",
|
||||
label: "Trigger Volume",
|
||||
description: "Axis-aligned authored trigger volume for enter and exit events.",
|
||||
createDefaultEntity: createTriggerVolumeEntity
|
||||
},
|
||||
teleportTarget: {
|
||||
kind: "teleportTarget",
|
||||
label: "Teleport Target",
|
||||
description: "Explicit authored teleport destination with a facing direction.",
|
||||
createDefaultEntity: createTeleportTargetEntity
|
||||
},
|
||||
interactable: {
|
||||
kind: "interactable",
|
||||
label: "Interactable",
|
||||
description: "Explicit authored interaction point for later click and use behavior.",
|
||||
createDefaultEntity: createInteractableEntity
|
||||
}
|
||||
};
|
||||
export function isEntityKind(value) {
|
||||
return typeof value === "string" && Object.prototype.hasOwnProperty.call(ENTITY_REGISTRY, value);
|
||||
}
|
||||
export function getEntityRegistryEntry(kind) {
|
||||
return ENTITY_REGISTRY[kind];
|
||||
}
|
||||
export function createDefaultEntityInstance(kind, overrides = {}) {
|
||||
switch (kind) {
|
||||
case "pointLight":
|
||||
return createPointLightEntity(overrides);
|
||||
case "spotLight":
|
||||
return createSpotLightEntity(overrides);
|
||||
case "playerStart":
|
||||
return createPlayerStartEntity(overrides);
|
||||
case "soundEmitter":
|
||||
return createSoundEmitterEntity(overrides);
|
||||
case "triggerVolume":
|
||||
return createTriggerVolumeEntity(overrides);
|
||||
case "teleportTarget":
|
||||
return createTeleportTargetEntity(overrides);
|
||||
case "interactable":
|
||||
return createInteractableEntity(overrides);
|
||||
}
|
||||
}
|
||||
export function cloneEntityInstance(entity) {
|
||||
switch (entity.kind) {
|
||||
case "pointLight":
|
||||
return createPointLightEntity(entity);
|
||||
case "spotLight":
|
||||
return createSpotLightEntity(entity);
|
||||
case "playerStart":
|
||||
return createPlayerStartEntity(entity);
|
||||
case "soundEmitter":
|
||||
return createSoundEmitterEntity(entity);
|
||||
case "triggerVolume":
|
||||
return createTriggerVolumeEntity(entity);
|
||||
case "teleportTarget":
|
||||
return createTeleportTargetEntity(entity);
|
||||
case "interactable":
|
||||
return createInteractableEntity(entity);
|
||||
}
|
||||
}
|
||||
export function cloneEntityRegistry(entities) {
|
||||
return Object.fromEntries(Object.entries(entities).map(([entityId, entity]) => [entityId, cloneEntityInstance(entity)]));
|
||||
}
|
||||
export function areEntityInstancesEqual(left, right) {
|
||||
if (left.kind !== right.kind || left.id !== right.id || left.name !== right.name || !areVec3Equal(left.position, right.position)) {
|
||||
return false;
|
||||
}
|
||||
switch (left.kind) {
|
||||
case "pointLight": {
|
||||
const typedRight = right;
|
||||
return (left.colorHex === typedRight.colorHex &&
|
||||
left.intensity === typedRight.intensity &&
|
||||
left.distance === typedRight.distance);
|
||||
}
|
||||
case "spotLight": {
|
||||
const typedRight = right;
|
||||
return (areVec3Equal(left.direction, typedRight.direction) &&
|
||||
left.colorHex === typedRight.colorHex &&
|
||||
left.intensity === typedRight.intensity &&
|
||||
left.distance === typedRight.distance &&
|
||||
left.angleDegrees === typedRight.angleDegrees);
|
||||
}
|
||||
case "playerStart": {
|
||||
const typedRight = right;
|
||||
return (left.yawDegrees === typedRight.yawDegrees &&
|
||||
left.collider.mode === typedRight.collider.mode &&
|
||||
left.collider.eyeHeight === typedRight.collider.eyeHeight &&
|
||||
left.collider.capsuleRadius === typedRight.collider.capsuleRadius &&
|
||||
left.collider.capsuleHeight === typedRight.collider.capsuleHeight &&
|
||||
areVec3Equal(left.collider.boxSize, typedRight.collider.boxSize));
|
||||
}
|
||||
case "soundEmitter": {
|
||||
const typedRight = right;
|
||||
return (left.audioAssetId === typedRight.audioAssetId &&
|
||||
left.volume === typedRight.volume &&
|
||||
left.refDistance === typedRight.refDistance &&
|
||||
left.maxDistance === typedRight.maxDistance &&
|
||||
left.autoplay === typedRight.autoplay &&
|
||||
left.loop === typedRight.loop);
|
||||
}
|
||||
case "triggerVolume": {
|
||||
const typedRight = right;
|
||||
return (areVec3Equal(left.size, typedRight.size) &&
|
||||
left.triggerOnEnter === typedRight.triggerOnEnter &&
|
||||
left.triggerOnExit === typedRight.triggerOnExit);
|
||||
}
|
||||
case "teleportTarget": {
|
||||
const typedRight = right;
|
||||
return left.yawDegrees === typedRight.yawDegrees;
|
||||
}
|
||||
case "interactable": {
|
||||
const typedRight = right;
|
||||
return left.radius === typedRight.radius && left.prompt === typedRight.prompt && left.enabled === typedRight.enabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
export function compareEntityInstances(left, right) {
|
||||
const leftOrder = ENTITY_KIND_ORDER.indexOf(left.kind);
|
||||
const rightOrder = ENTITY_KIND_ORDER.indexOf(right.kind);
|
||||
if (leftOrder !== rightOrder) {
|
||||
return leftOrder - rightOrder;
|
||||
}
|
||||
return left.id.localeCompare(right.id);
|
||||
}
|
||||
export function getEntityInstances(entities) {
|
||||
return Object.values(entities).sort(compareEntityInstances);
|
||||
}
|
||||
export function getEntitiesOfKind(entities, kind) {
|
||||
return getEntityInstances(entities).filter((entity) => entity.kind === kind);
|
||||
}
|
||||
export function getPlayerStartEntities(entities) {
|
||||
return getEntitiesOfKind(entities, "playerStart");
|
||||
}
|
||||
export function getPrimaryPlayerStartEntity(entities) {
|
||||
return getPlayerStartEntities(entities)[0] ?? null;
|
||||
}
|
||||
export function getEntityKindLabel(kind) {
|
||||
return getEntityRegistryEntry(kind).label;
|
||||
}
|
||||
@@ -27,11 +27,75 @@ export interface SpotLightEntity extends PositionedEntity {
|
||||
export interface PlayerStartEntity extends PositionedEntity {
|
||||
kind: "playerStart";
|
||||
yawDegrees: number;
|
||||
navigationMode: PlayerStartNavigationMode;
|
||||
inputBindings: PlayerStartInputBindings;
|
||||
collider: PlayerStartColliderSettings;
|
||||
}
|
||||
|
||||
export interface SceneEntryEntity extends PositionedEntity {
|
||||
kind: "sceneEntry";
|
||||
yawDegrees: number;
|
||||
}
|
||||
|
||||
export const PLAYER_START_COLLIDER_MODES = ["capsule", "box", "none"] as const;
|
||||
export type PlayerStartColliderMode = (typeof PLAYER_START_COLLIDER_MODES)[number];
|
||||
export const PLAYER_START_NAVIGATION_MODES = [
|
||||
"firstPerson",
|
||||
"thirdPerson"
|
||||
] as const;
|
||||
export type PlayerStartNavigationMode =
|
||||
(typeof PLAYER_START_NAVIGATION_MODES)[number];
|
||||
export const PLAYER_START_MOVEMENT_ACTIONS = [
|
||||
"moveForward",
|
||||
"moveBackward",
|
||||
"moveLeft",
|
||||
"moveRight"
|
||||
] as const;
|
||||
export type PlayerStartMovementAction =
|
||||
(typeof PLAYER_START_MOVEMENT_ACTIONS)[number];
|
||||
export type PlayerStartKeyboardBindingCode = string;
|
||||
export const PLAYER_START_GAMEPAD_BINDINGS = [
|
||||
"leftStickUp",
|
||||
"leftStickDown",
|
||||
"leftStickLeft",
|
||||
"leftStickRight",
|
||||
"dpadUp",
|
||||
"dpadDown",
|
||||
"dpadLeft",
|
||||
"dpadRight"
|
||||
] as const;
|
||||
export type PlayerStartGamepadBinding =
|
||||
(typeof PLAYER_START_GAMEPAD_BINDINGS)[number];
|
||||
export const PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS = [
|
||||
"rightStick"
|
||||
] as const;
|
||||
export type PlayerStartGamepadCameraLookBinding =
|
||||
(typeof PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS)[number];
|
||||
|
||||
export interface PlayerStartKeyboardBindings {
|
||||
moveForward: PlayerStartKeyboardBindingCode;
|
||||
moveBackward: PlayerStartKeyboardBindingCode;
|
||||
moveLeft: PlayerStartKeyboardBindingCode;
|
||||
moveRight: PlayerStartKeyboardBindingCode;
|
||||
}
|
||||
|
||||
export interface PlayerStartGamepadBindings {
|
||||
moveForward: PlayerStartGamepadBinding;
|
||||
moveBackward: PlayerStartGamepadBinding;
|
||||
moveLeft: PlayerStartGamepadBinding;
|
||||
moveRight: PlayerStartGamepadBinding;
|
||||
cameraLook: PlayerStartGamepadCameraLookBinding;
|
||||
}
|
||||
|
||||
export interface PlayerStartInputBindings {
|
||||
keyboard: PlayerStartKeyboardBindings;
|
||||
gamepad: PlayerStartGamepadBindings;
|
||||
}
|
||||
|
||||
export interface PlayerStartInputBindingOverrides {
|
||||
keyboard?: Partial<PlayerStartKeyboardBindings>;
|
||||
gamepad?: Partial<PlayerStartGamepadBindings>;
|
||||
}
|
||||
|
||||
export interface PlayerStartColliderSettings {
|
||||
mode: PlayerStartColliderMode;
|
||||
@@ -70,14 +134,25 @@ export interface InteractableEntity extends PositionedEntity {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SceneExitEntity extends PositionedEntity {
|
||||
kind: "sceneExit";
|
||||
radius: number;
|
||||
prompt: string;
|
||||
enabled: boolean;
|
||||
targetSceneId: string;
|
||||
targetEntryEntityId: string;
|
||||
}
|
||||
|
||||
export type EntityInstance =
|
||||
| PointLightEntity
|
||||
| SpotLightEntity
|
||||
| PlayerStartEntity
|
||||
| SceneEntryEntity
|
||||
| SoundEmitterEntity
|
||||
| TriggerVolumeEntity
|
||||
| TeleportTargetEntity
|
||||
| InteractableEntity;
|
||||
| InteractableEntity
|
||||
| SceneExitEntity;
|
||||
|
||||
export type EntityKind = EntityInstance["kind"];
|
||||
|
||||
@@ -92,10 +167,12 @@ export const ENTITY_KIND_ORDER = [
|
||||
"pointLight",
|
||||
"spotLight",
|
||||
"playerStart",
|
||||
"sceneEntry",
|
||||
"soundEmitter",
|
||||
"triggerVolume",
|
||||
"teleportTarget",
|
||||
"interactable"
|
||||
"interactable",
|
||||
"sceneExit"
|
||||
] as const;
|
||||
export const DEFAULT_POINT_LIGHT_POSITION: Vec3 = {
|
||||
x: 0,
|
||||
@@ -128,6 +205,24 @@ export const DEFAULT_ENTITY_POSITION: Vec3 = {
|
||||
|
||||
export const DEFAULT_PLAYER_START_POSITION = DEFAULT_ENTITY_POSITION;
|
||||
export const DEFAULT_PLAYER_START_YAW_DEGREES = 0;
|
||||
export const DEFAULT_PLAYER_START_NAVIGATION_MODE: PlayerStartNavigationMode =
|
||||
"firstPerson";
|
||||
export const DEFAULT_PLAYER_START_KEYBOARD_BINDINGS: PlayerStartKeyboardBindings =
|
||||
{
|
||||
moveForward: "KeyW",
|
||||
moveBackward: "KeyS",
|
||||
moveLeft: "KeyA",
|
||||
moveRight: "KeyD"
|
||||
};
|
||||
export const DEFAULT_PLAYER_START_GAMEPAD_BINDINGS: PlayerStartGamepadBindings =
|
||||
{
|
||||
moveForward: "leftStickUp",
|
||||
moveBackward: "leftStickDown",
|
||||
moveLeft: "leftStickLeft",
|
||||
moveRight: "leftStickRight",
|
||||
cameraLook: "rightStick"
|
||||
};
|
||||
export const DEFAULT_SCENE_ENTRY_YAW_DEGREES = 0;
|
||||
export const DEFAULT_PLAYER_START_COLLIDER_MODE: PlayerStartColliderMode = "capsule";
|
||||
export const DEFAULT_PLAYER_START_EYE_HEIGHT = 1.6;
|
||||
export const DEFAULT_PLAYER_START_CAPSULE_RADIUS = 0.3;
|
||||
@@ -151,6 +246,8 @@ export const DEFAULT_TRIGGER_VOLUME_SIZE: Vec3 = {
|
||||
export const DEFAULT_TELEPORT_TARGET_YAW_DEGREES = 0;
|
||||
export const DEFAULT_INTERACTABLE_RADIUS = 1.5;
|
||||
export const DEFAULT_INTERACTABLE_PROMPT = "Use";
|
||||
export const DEFAULT_SCENE_EXIT_RADIUS = 1.5;
|
||||
export const DEFAULT_SCENE_EXIT_PROMPT = "Enter";
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return {
|
||||
@@ -212,6 +309,36 @@ export function isPlayerStartColliderMode(value: string): value is PlayerStartCo
|
||||
return PLAYER_START_COLLIDER_MODES.includes(value as PlayerStartColliderMode);
|
||||
}
|
||||
|
||||
export function isPlayerStartNavigationMode(
|
||||
value: string
|
||||
): value is PlayerStartNavigationMode {
|
||||
return PLAYER_START_NAVIGATION_MODES.includes(
|
||||
value as PlayerStartNavigationMode
|
||||
);
|
||||
}
|
||||
|
||||
export function isPlayerStartKeyboardBindingCode(
|
||||
value: string
|
||||
): value is PlayerStartKeyboardBindingCode {
|
||||
return value.trim().length > 0;
|
||||
}
|
||||
|
||||
export function isPlayerStartGamepadBinding(
|
||||
value: string
|
||||
): value is PlayerStartGamepadBinding {
|
||||
return PLAYER_START_GAMEPAD_BINDINGS.includes(
|
||||
value as PlayerStartGamepadBinding
|
||||
);
|
||||
}
|
||||
|
||||
export function isPlayerStartGamepadCameraLookBinding(
|
||||
value: string
|
||||
): value is PlayerStartGamepadCameraLookBinding {
|
||||
return PLAYER_START_GAMEPAD_CAMERA_LOOK_BINDINGS.includes(
|
||||
value as PlayerStartGamepadCameraLookBinding
|
||||
);
|
||||
}
|
||||
|
||||
export function clonePlayerStartColliderSettings(settings: PlayerStartColliderSettings): PlayerStartColliderSettings {
|
||||
return {
|
||||
mode: settings.mode,
|
||||
@@ -222,6 +349,120 @@ export function clonePlayerStartColliderSettings(settings: PlayerStartColliderSe
|
||||
};
|
||||
}
|
||||
|
||||
export function clonePlayerStartInputBindings(
|
||||
bindings: PlayerStartInputBindings
|
||||
): PlayerStartInputBindings {
|
||||
return {
|
||||
keyboard: {
|
||||
moveForward: bindings.keyboard.moveForward,
|
||||
moveBackward: bindings.keyboard.moveBackward,
|
||||
moveLeft: bindings.keyboard.moveLeft,
|
||||
moveRight: bindings.keyboard.moveRight
|
||||
},
|
||||
gamepad: {
|
||||
moveForward: bindings.gamepad.moveForward,
|
||||
moveBackward: bindings.gamepad.moveBackward,
|
||||
moveLeft: bindings.gamepad.moveLeft,
|
||||
moveRight: bindings.gamepad.moveRight,
|
||||
cameraLook: bindings.gamepad.cameraLook
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createPlayerStartInputBindings(
|
||||
overrides: PlayerStartInputBindingOverrides = {}
|
||||
): PlayerStartInputBindings {
|
||||
const keyboard: PlayerStartKeyboardBindings = {
|
||||
moveForward:
|
||||
overrides.keyboard?.moveForward ??
|
||||
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveForward,
|
||||
moveBackward:
|
||||
overrides.keyboard?.moveBackward ??
|
||||
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveBackward,
|
||||
moveLeft:
|
||||
overrides.keyboard?.moveLeft ??
|
||||
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveLeft,
|
||||
moveRight:
|
||||
overrides.keyboard?.moveRight ??
|
||||
DEFAULT_PLAYER_START_KEYBOARD_BINDINGS.moveRight
|
||||
};
|
||||
const gamepad: PlayerStartGamepadBindings = {
|
||||
moveForward:
|
||||
overrides.gamepad?.moveForward ??
|
||||
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveForward,
|
||||
moveBackward:
|
||||
overrides.gamepad?.moveBackward ??
|
||||
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveBackward,
|
||||
moveLeft:
|
||||
overrides.gamepad?.moveLeft ??
|
||||
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveLeft,
|
||||
moveRight:
|
||||
overrides.gamepad?.moveRight ??
|
||||
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.moveRight,
|
||||
cameraLook:
|
||||
overrides.gamepad?.cameraLook ??
|
||||
DEFAULT_PLAYER_START_GAMEPAD_BINDINGS.cameraLook
|
||||
};
|
||||
|
||||
if (!isPlayerStartKeyboardBindingCode(keyboard.moveForward)) {
|
||||
throw new Error("Player Start move-forward keyboard binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartKeyboardBindingCode(keyboard.moveBackward)) {
|
||||
throw new Error("Player Start move-backward keyboard binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartKeyboardBindingCode(keyboard.moveLeft)) {
|
||||
throw new Error("Player Start move-left keyboard binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartKeyboardBindingCode(keyboard.moveRight)) {
|
||||
throw new Error("Player Start move-right keyboard binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartGamepadBinding(gamepad.moveForward)) {
|
||||
throw new Error("Player Start move-forward gamepad binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartGamepadBinding(gamepad.moveBackward)) {
|
||||
throw new Error("Player Start move-backward gamepad binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartGamepadBinding(gamepad.moveLeft)) {
|
||||
throw new Error("Player Start move-left gamepad binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartGamepadBinding(gamepad.moveRight)) {
|
||||
throw new Error("Player Start move-right gamepad binding must be supported.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartGamepadCameraLookBinding(gamepad.cameraLook)) {
|
||||
throw new Error("Player Start camera-look gamepad binding must be supported.");
|
||||
}
|
||||
|
||||
return {
|
||||
keyboard,
|
||||
gamepad
|
||||
};
|
||||
}
|
||||
|
||||
export function arePlayerStartInputBindingsEqual(
|
||||
left: PlayerStartInputBindings,
|
||||
right: PlayerStartInputBindings
|
||||
): boolean {
|
||||
return (
|
||||
left.keyboard.moveForward === right.keyboard.moveForward &&
|
||||
left.keyboard.moveBackward === right.keyboard.moveBackward &&
|
||||
left.keyboard.moveLeft === right.keyboard.moveLeft &&
|
||||
left.keyboard.moveRight === right.keyboard.moveRight &&
|
||||
left.gamepad.moveForward === right.gamepad.moveForward &&
|
||||
left.gamepad.moveBackward === right.gamepad.moveBackward &&
|
||||
left.gamepad.moveLeft === right.gamepad.moveLeft &&
|
||||
left.gamepad.moveRight === right.gamepad.moveRight &&
|
||||
left.gamepad.cameraLook === right.gamepad.cameraLook
|
||||
);
|
||||
}
|
||||
|
||||
export function getPlayerStartColliderHeight(settings: PlayerStartColliderSettings): number | null {
|
||||
switch (settings.mode) {
|
||||
case "capsule":
|
||||
@@ -286,6 +527,23 @@ function normalizeSoundEmitterAudioAssetId(audioAssetId: string | null | undefin
|
||||
return trimmedAudioAssetId;
|
||||
}
|
||||
|
||||
function normalizeSceneReferenceId(
|
||||
value: string | null | undefined,
|
||||
label: string
|
||||
): string {
|
||||
if (value === undefined || value === null) {
|
||||
throw new Error(`${label} must be authored.`);
|
||||
}
|
||||
|
||||
const normalizedValue = value.trim();
|
||||
|
||||
if (normalizedValue.length === 0) {
|
||||
throw new Error(`${label} must be non-empty.`);
|
||||
}
|
||||
|
||||
return normalizedValue;
|
||||
}
|
||||
|
||||
export function normalizeEntityName(name: string | null | undefined): string | undefined {
|
||||
if (name === undefined || name === null) {
|
||||
return undefined;
|
||||
@@ -369,10 +627,21 @@ export function createSpotLightEntity(
|
||||
}
|
||||
|
||||
export function createPlayerStartEntity(
|
||||
overrides: Partial<Pick<PlayerStartEntity, "id" | "name" | "position" | "yawDegrees" | "collider">> = {}
|
||||
overrides: Partial<
|
||||
Pick<
|
||||
PlayerStartEntity,
|
||||
"id" | "name" | "position" | "yawDegrees" | "navigationMode"
|
||||
>
|
||||
> & {
|
||||
inputBindings?: PlayerStartInputBindingOverrides;
|
||||
collider?: Partial<PlayerStartColliderSettings>;
|
||||
} = {}
|
||||
): PlayerStartEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_PLAYER_START_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_PLAYER_START_YAW_DEGREES;
|
||||
const navigationMode =
|
||||
overrides.navigationMode ?? DEFAULT_PLAYER_START_NAVIGATION_MODE;
|
||||
const inputBindings = createPlayerStartInputBindings(overrides.inputBindings);
|
||||
const collider = createPlayerStartColliderSettings(overrides.collider);
|
||||
|
||||
assertFiniteVec3(position, "Player Start position");
|
||||
@@ -381,16 +650,45 @@ export function createPlayerStartEntity(
|
||||
throw new Error("Player Start yaw must be a finite number.");
|
||||
}
|
||||
|
||||
if (!isPlayerStartNavigationMode(navigationMode)) {
|
||||
throw new Error(
|
||||
"Player Start navigation mode must be firstPerson or thirdPerson."
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-player-start"),
|
||||
kind: "playerStart",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees),
|
||||
navigationMode,
|
||||
inputBindings,
|
||||
collider
|
||||
};
|
||||
}
|
||||
|
||||
export function createSceneEntryEntity(
|
||||
overrides: Partial<Pick<SceneEntryEntity, "id" | "name" | "position" | "yawDegrees">> = {}
|
||||
): SceneEntryEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const yawDegrees = overrides.yawDegrees ?? DEFAULT_SCENE_ENTRY_YAW_DEGREES;
|
||||
|
||||
assertFiniteVec3(position, "Scene Entry position");
|
||||
|
||||
if (!Number.isFinite(yawDegrees)) {
|
||||
throw new Error("Scene Entry yaw must be a finite number.");
|
||||
}
|
||||
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-scene-entry"),
|
||||
kind: "sceneEntry",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
yawDegrees: normalizeYawDegrees(yawDegrees)
|
||||
};
|
||||
}
|
||||
|
||||
export function createSoundEmitterEntity(
|
||||
overrides: Partial<
|
||||
Pick<
|
||||
@@ -501,6 +799,53 @@ export function createInteractableEntity(
|
||||
};
|
||||
}
|
||||
|
||||
export function createSceneExitEntity(
|
||||
overrides: Partial<
|
||||
Pick<
|
||||
SceneExitEntity,
|
||||
| "id"
|
||||
| "name"
|
||||
| "position"
|
||||
| "radius"
|
||||
| "prompt"
|
||||
| "enabled"
|
||||
| "targetSceneId"
|
||||
| "targetEntryEntityId"
|
||||
>
|
||||
> = {}
|
||||
): SceneExitEntity {
|
||||
const position = cloneVec3(overrides.position ?? DEFAULT_ENTITY_POSITION);
|
||||
const radius = overrides.radius ?? DEFAULT_SCENE_EXIT_RADIUS;
|
||||
const prompt = normalizeInteractablePrompt(
|
||||
overrides.prompt ?? DEFAULT_SCENE_EXIT_PROMPT
|
||||
);
|
||||
const enabled = overrides.enabled ?? true;
|
||||
const targetSceneId = normalizeSceneReferenceId(
|
||||
overrides.targetSceneId,
|
||||
"Scene Exit target scene id"
|
||||
);
|
||||
const targetEntryEntityId = normalizeSceneReferenceId(
|
||||
overrides.targetEntryEntityId,
|
||||
"Scene Exit target entry id"
|
||||
);
|
||||
|
||||
assertFiniteVec3(position, "Scene Exit position");
|
||||
assertPositiveFiniteNumber(radius, "Scene Exit radius");
|
||||
assertBoolean(enabled, "Scene Exit enabled");
|
||||
|
||||
return {
|
||||
id: overrides.id ?? createOpaqueId("entity-scene-exit"),
|
||||
kind: "sceneExit",
|
||||
name: normalizeEntityName(overrides.name),
|
||||
position,
|
||||
radius,
|
||||
prompt,
|
||||
enabled,
|
||||
targetSceneId,
|
||||
targetEntryEntityId
|
||||
};
|
||||
}
|
||||
|
||||
export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<EntityInstance, { kind: K }>> } = {
|
||||
pointLight: {
|
||||
kind: "pointLight",
|
||||
@@ -517,9 +862,17 @@ export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<E
|
||||
playerStart: {
|
||||
kind: "playerStart",
|
||||
label: "Player Start",
|
||||
description: "Primary authored spawn point for first-person runtime navigation.",
|
||||
description:
|
||||
"Primary authored spawn point for first-person or third-person runtime navigation.",
|
||||
createDefaultEntity: createPlayerStartEntity
|
||||
},
|
||||
sceneEntry: {
|
||||
kind: "sceneEntry",
|
||||
label: "Scene Entry",
|
||||
description:
|
||||
"Explicit authored scene-transition arrival point with a facing direction.",
|
||||
createDefaultEntity: createSceneEntryEntity
|
||||
},
|
||||
soundEmitter: {
|
||||
kind: "soundEmitter",
|
||||
label: "Sound Emitter",
|
||||
@@ -543,6 +896,13 @@ export const ENTITY_REGISTRY: { [K in EntityKind]: EntityRegistryEntry<Extract<E
|
||||
label: "Interactable",
|
||||
description: "Explicit authored interaction point for later click and use behavior.",
|
||||
createDefaultEntity: createInteractableEntity
|
||||
},
|
||||
sceneExit: {
|
||||
kind: "sceneExit",
|
||||
label: "Scene Exit",
|
||||
description:
|
||||
"Explicit authored scene-transition exit that loads a target scene entry on demand.",
|
||||
createDefaultEntity: createSceneExitEntity
|
||||
}
|
||||
};
|
||||
|
||||
@@ -555,12 +915,14 @@ export function getEntityRegistryEntry<K extends EntityKind>(kind: K): EntityReg
|
||||
}
|
||||
|
||||
export function createDefaultEntityInstance(kind: "playerStart", overrides?: Partial<PlayerStartEntity>): PlayerStartEntity;
|
||||
export function createDefaultEntityInstance(kind: "sceneEntry", overrides?: Partial<SceneEntryEntity>): SceneEntryEntity;
|
||||
export function createDefaultEntityInstance(kind: "pointLight", overrides?: Partial<PointLightEntity>): PointLightEntity;
|
||||
export function createDefaultEntityInstance(kind: "spotLight", overrides?: Partial<SpotLightEntity>): SpotLightEntity;
|
||||
export function createDefaultEntityInstance(kind: "soundEmitter", overrides?: Partial<SoundEmitterEntity>): SoundEmitterEntity;
|
||||
export function createDefaultEntityInstance(kind: "triggerVolume", overrides?: Partial<TriggerVolumeEntity>): TriggerVolumeEntity;
|
||||
export function createDefaultEntityInstance(kind: "teleportTarget", overrides?: Partial<TeleportTargetEntity>): TeleportTargetEntity;
|
||||
export function createDefaultEntityInstance(kind: "interactable", overrides?: Partial<InteractableEntity>): InteractableEntity;
|
||||
export function createDefaultEntityInstance(kind: "sceneExit", overrides?: Partial<SceneExitEntity>): SceneExitEntity;
|
||||
export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial<EntityInstance> = {}): EntityInstance {
|
||||
switch (kind) {
|
||||
case "pointLight":
|
||||
@@ -569,6 +931,8 @@ export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial
|
||||
return createSpotLightEntity(overrides);
|
||||
case "playerStart":
|
||||
return createPlayerStartEntity(overrides);
|
||||
case "sceneEntry":
|
||||
return createSceneEntryEntity(overrides);
|
||||
case "soundEmitter":
|
||||
return createSoundEmitterEntity(overrides);
|
||||
case "triggerVolume":
|
||||
@@ -577,6 +941,8 @@ export function createDefaultEntityInstance(kind: EntityKind, overrides: Partial
|
||||
return createTeleportTargetEntity(overrides);
|
||||
case "interactable":
|
||||
return createInteractableEntity(overrides);
|
||||
case "sceneExit":
|
||||
return createSceneExitEntity(overrides);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -588,6 +954,8 @@ export function cloneEntityInstance(entity: EntityInstance): EntityInstance {
|
||||
return createSpotLightEntity(entity);
|
||||
case "playerStart":
|
||||
return createPlayerStartEntity(entity);
|
||||
case "sceneEntry":
|
||||
return createSceneEntryEntity(entity);
|
||||
case "soundEmitter":
|
||||
return createSoundEmitterEntity(entity);
|
||||
case "triggerVolume":
|
||||
@@ -596,6 +964,8 @@ export function cloneEntityInstance(entity: EntityInstance): EntityInstance {
|
||||
return createTeleportTargetEntity(entity);
|
||||
case "interactable":
|
||||
return createInteractableEntity(entity);
|
||||
case "sceneExit":
|
||||
return createSceneExitEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,6 +1001,11 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
|
||||
const typedRight = right as PlayerStartEntity;
|
||||
return (
|
||||
left.yawDegrees === typedRight.yawDegrees &&
|
||||
left.navigationMode === typedRight.navigationMode &&
|
||||
arePlayerStartInputBindingsEqual(
|
||||
left.inputBindings,
|
||||
typedRight.inputBindings
|
||||
) &&
|
||||
left.collider.mode === typedRight.collider.mode &&
|
||||
left.collider.eyeHeight === typedRight.collider.eyeHeight &&
|
||||
left.collider.capsuleRadius === typedRight.collider.capsuleRadius &&
|
||||
@@ -638,6 +1013,10 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
|
||||
areVec3Equal(left.collider.boxSize, typedRight.collider.boxSize)
|
||||
);
|
||||
}
|
||||
case "sceneEntry": {
|
||||
const typedRight = right as SceneEntryEntity;
|
||||
return left.yawDegrees === typedRight.yawDegrees;
|
||||
}
|
||||
case "soundEmitter": {
|
||||
const typedRight = right as SoundEmitterEntity;
|
||||
return (
|
||||
@@ -665,6 +1044,16 @@ export function areEntityInstancesEqual(left: EntityInstance, right: EntityInsta
|
||||
const typedRight = right as InteractableEntity;
|
||||
return left.radius === typedRight.radius && left.prompt === typedRight.prompt && left.enabled === typedRight.enabled;
|
||||
}
|
||||
case "sceneExit": {
|
||||
const typedRight = right as SceneExitEntity;
|
||||
return (
|
||||
left.radius === typedRight.radius &&
|
||||
left.prompt === typedRight.prompt &&
|
||||
left.enabled === typedRight.enabled &&
|
||||
left.targetSceneId === typedRight.targetSceneId &&
|
||||
left.targetEntryEntityId === typedRight.targetEntryEntityId
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
45
src/entities/entity-labels.js
Normal file
45
src/entities/entity-labels.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { compareEntityInstances, getEntityKindLabel, getEntityInstances } from "./entity-instances";
|
||||
function getSortedEntitiesByKind(entities, kind) {
|
||||
return Object.values(entities)
|
||||
.filter((entity) => entity.kind === kind)
|
||||
.sort(compareEntityInstances);
|
||||
}
|
||||
function getSoundEmitterLabelSuffix(entity, assets) {
|
||||
if (entity.audioAssetId === null) {
|
||||
return "No Audio Asset";
|
||||
}
|
||||
const asset = assets?.[entity.audioAssetId];
|
||||
if (asset === undefined) {
|
||||
return `Missing Audio Asset (${entity.audioAssetId})`;
|
||||
}
|
||||
if (asset.kind !== "audio") {
|
||||
return `Invalid Audio Asset (${asset.sourceName})`;
|
||||
}
|
||||
return asset.sourceName;
|
||||
}
|
||||
export function getEntityDisplayLabel(entity, entities, assets) {
|
||||
if (entity.name !== undefined) {
|
||||
return entity.name;
|
||||
}
|
||||
const typedEntities = getSortedEntitiesByKind(entities, entity.kind);
|
||||
const entityIndex = typedEntities.findIndex((candidate) => candidate.id === entity.id);
|
||||
const baseLabel = getEntityKindLabel(entity.kind);
|
||||
const numberedLabel = entityIndex <= 0 ? baseLabel : `${baseLabel} ${entityIndex + 1}`;
|
||||
if (entity.kind !== "soundEmitter" || assets === undefined) {
|
||||
return numberedLabel;
|
||||
}
|
||||
return `${numberedLabel} · ${getSoundEmitterLabelSuffix(entity, assets)}`;
|
||||
}
|
||||
export function getEntityDisplayLabelById(entityId, entities, assets) {
|
||||
const entity = entities[entityId];
|
||||
if (entity === undefined) {
|
||||
return "Entity";
|
||||
}
|
||||
return getEntityDisplayLabel(entity, entities, assets);
|
||||
}
|
||||
export function getSortedEntityDisplayLabels(entities, assets) {
|
||||
return getEntityInstances(entities).map((entity) => ({
|
||||
entity,
|
||||
label: getEntityDisplayLabel(entity, entities, assets)
|
||||
}));
|
||||
}
|
||||
168
src/geometry/box-brush-components.js
Normal file
168
src/geometry/box-brush-components.js
Normal file
@@ -0,0 +1,168 @@
|
||||
import { Euler, MathUtils, Quaternion, Vector3 } from "three";
|
||||
import { BOX_FACE_IDS } from "../document/brushes";
|
||||
import { getBoxBrushFaceVertexIds, getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
|
||||
const BOX_VERTEX_SIGNS = {
|
||||
negX_negY_negZ: { x: -1, y: -1, z: -1 },
|
||||
posX_negY_negZ: { x: 1, y: -1, z: -1 },
|
||||
negX_posY_negZ: { x: -1, y: 1, z: -1 },
|
||||
posX_posY_negZ: { x: 1, y: 1, z: -1 },
|
||||
negX_negY_posZ: { x: -1, y: -1, z: 1 },
|
||||
posX_negY_posZ: { x: 1, y: -1, z: 1 },
|
||||
negX_posY_posZ: { x: -1, y: 1, z: 1 },
|
||||
posX_posY_posZ: { x: 1, y: 1, z: 1 }
|
||||
};
|
||||
const BOX_FACE_TRANSFORM_META = {
|
||||
posX: { axis: "x", sign: 1 },
|
||||
negX: { axis: "x", sign: -1 },
|
||||
posY: { axis: "y", sign: 1 },
|
||||
negY: { axis: "y", sign: -1 },
|
||||
posZ: { axis: "z", sign: 1 },
|
||||
negZ: { axis: "z", sign: -1 }
|
||||
};
|
||||
const BOX_EDGE_TRANSFORM_META = {
|
||||
edgeX_negY_negZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: -1, z: -1 }
|
||||
},
|
||||
edgeX_posY_negZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: 1, z: -1 }
|
||||
},
|
||||
edgeX_negY_posZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: -1, z: 1 }
|
||||
},
|
||||
edgeX_posY_posZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: 1, z: 1 }
|
||||
},
|
||||
edgeY_negX_negZ: {
|
||||
axis: "y",
|
||||
signs: { x: -1, y: null, z: -1 }
|
||||
},
|
||||
edgeY_posX_negZ: {
|
||||
axis: "y",
|
||||
signs: { x: 1, y: null, z: -1 }
|
||||
},
|
||||
edgeY_negX_posZ: {
|
||||
axis: "y",
|
||||
signs: { x: -1, y: null, z: 1 }
|
||||
},
|
||||
edgeY_posX_posZ: {
|
||||
axis: "y",
|
||||
signs: { x: 1, y: null, z: 1 }
|
||||
},
|
||||
edgeZ_negX_negY: {
|
||||
axis: "z",
|
||||
signs: { x: -1, y: -1, z: null }
|
||||
},
|
||||
edgeZ_posX_negY: {
|
||||
axis: "z",
|
||||
signs: { x: 1, y: -1, z: null }
|
||||
},
|
||||
edgeZ_negX_posY: {
|
||||
axis: "z",
|
||||
signs: { x: -1, y: 1, z: null }
|
||||
},
|
||||
edgeZ_posX_posY: {
|
||||
axis: "z",
|
||||
signs: { x: 1, y: 1, z: null }
|
||||
}
|
||||
};
|
||||
const BOX_EDGE_VERTEX_IDS = {
|
||||
edgeX_negY_negZ: { start: "negX_negY_negZ", end: "posX_negY_negZ" },
|
||||
edgeX_posY_negZ: { start: "negX_posY_negZ", end: "posX_posY_negZ" },
|
||||
edgeX_negY_posZ: { start: "negX_negY_posZ", end: "posX_negY_posZ" },
|
||||
edgeX_posY_posZ: { start: "negX_posY_posZ", end: "posX_posY_posZ" },
|
||||
edgeY_negX_negZ: { start: "negX_negY_negZ", end: "negX_posY_negZ" },
|
||||
edgeY_posX_negZ: { start: "posX_negY_negZ", end: "posX_posY_negZ" },
|
||||
edgeY_negX_posZ: { start: "negX_negY_posZ", end: "negX_posY_posZ" },
|
||||
edgeY_posX_posZ: { start: "posX_negY_posZ", end: "posX_posY_posZ" },
|
||||
edgeZ_negX_negY: { start: "negX_negY_negZ", end: "negX_negY_posZ" },
|
||||
edgeZ_posX_negY: { start: "posX_negY_negZ", end: "posX_negY_posZ" },
|
||||
edgeZ_negX_posY: { start: "negX_posY_negZ", end: "negX_posY_posZ" },
|
||||
edgeZ_posX_posY: { start: "posX_posY_negZ", end: "posX_posY_posZ" }
|
||||
};
|
||||
function createBrushRotationEuler(brush) {
|
||||
return new Euler(MathUtils.degToRad(brush.rotationDegrees.x), MathUtils.degToRad(brush.rotationDegrees.y), MathUtils.degToRad(brush.rotationDegrees.z), "XYZ");
|
||||
}
|
||||
export function transformBoxBrushWorldVectorToLocal(brush, worldVector) {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
|
||||
const localVector = new Vector3(worldVector.x, worldVector.y, worldVector.z).applyQuaternion(inverseRotation);
|
||||
return {
|
||||
x: localVector.x,
|
||||
y: localVector.y,
|
||||
z: localVector.z
|
||||
};
|
||||
}
|
||||
export function transformBoxBrushWorldPointToLocal(brush, worldPoint) {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
|
||||
const localPoint = new Vector3(worldPoint.x - brush.center.x, worldPoint.y - brush.center.y, worldPoint.z - brush.center.z).applyQuaternion(inverseRotation);
|
||||
return {
|
||||
x: localPoint.x,
|
||||
y: localPoint.y,
|
||||
z: localPoint.z
|
||||
};
|
||||
}
|
||||
export function transformBoxBrushLocalPointToWorld(brush, localPoint) {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const rotatedOffset = new Vector3(localPoint.x, localPoint.y, localPoint.z).applyEuler(rotation);
|
||||
return {
|
||||
x: brush.center.x + rotatedOffset.x,
|
||||
y: brush.center.y + rotatedOffset.y,
|
||||
z: brush.center.z + rotatedOffset.z
|
||||
};
|
||||
}
|
||||
export function getBoxBrushFaceTransformMeta(faceId) {
|
||||
return BOX_FACE_TRANSFORM_META[faceId];
|
||||
}
|
||||
export function getBoxBrushEdgeTransformMeta(edgeId) {
|
||||
return BOX_EDGE_TRANSFORM_META[edgeId];
|
||||
}
|
||||
export function getBoxBrushVertexSigns(vertexId) {
|
||||
return BOX_VERTEX_SIGNS[vertexId];
|
||||
}
|
||||
export function getBoxBrushFaceWorldCenter(brush, faceId) {
|
||||
const faceVertexIds = getBoxBrushFaceVertexIds(faceId);
|
||||
const localCenter = faceVertexIds.reduce((accumulator, vertexId) => {
|
||||
const vertex = getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
return {
|
||||
x: accumulator.x + vertex.x * 0.25,
|
||||
y: accumulator.y + vertex.y * 0.25,
|
||||
z: accumulator.z + vertex.z * 0.25
|
||||
};
|
||||
}, { x: 0, y: 0, z: 0 });
|
||||
return transformBoxBrushLocalPointToWorld(brush, localCenter);
|
||||
}
|
||||
export function getBoxBrushFaceAxis(faceId) {
|
||||
return BOX_FACE_TRANSFORM_META[faceId].axis;
|
||||
}
|
||||
export function getBoxBrushEdgeAxis(edgeId) {
|
||||
return BOX_EDGE_TRANSFORM_META[edgeId].axis;
|
||||
}
|
||||
export function getBoxBrushFaceIdsForAxis(axis) {
|
||||
return BOX_FACE_IDS.filter((faceId) => BOX_FACE_TRANSFORM_META[faceId].axis === axis);
|
||||
}
|
||||
export function getBoxBrushVertexLocalPosition(brush, vertexId) {
|
||||
return getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
}
|
||||
export function getBoxBrushVertexWorldPosition(brush, vertexId) {
|
||||
return transformBoxBrushLocalPointToWorld(brush, getBoxBrushVertexLocalPosition(brush, vertexId));
|
||||
}
|
||||
export function getBoxBrushEdgeWorldSegment(brush, edgeId) {
|
||||
const vertexIds = BOX_EDGE_VERTEX_IDS[edgeId];
|
||||
const start = getBoxBrushVertexWorldPosition(brush, vertexIds.start);
|
||||
const end = getBoxBrushVertexWorldPosition(brush, vertexIds.end);
|
||||
return {
|
||||
id: edgeId,
|
||||
start,
|
||||
end,
|
||||
center: {
|
||||
x: (start.x + end.x) * 0.5,
|
||||
y: (start.y + end.y) * 0.5,
|
||||
z: (start.z + end.z) * 0.5
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Euler, MathUtils, Vector3 } from "three";
|
||||
import { Euler, MathUtils, Quaternion, Vector3 } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import {
|
||||
BOX_FACE_IDS,
|
||||
type BoxBrush,
|
||||
type BoxEdgeId,
|
||||
type BoxFaceId,
|
||||
type BoxVertexId
|
||||
} from "../document/brushes";
|
||||
import { getBoxBrushHalfSize } from "./box-brush";
|
||||
import { getBoxBrushFaceVertexIds, getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
|
||||
|
||||
type Sign = -1 | 1;
|
||||
|
||||
@@ -16,6 +18,22 @@ interface BoxVertexSigns {
|
||||
z: Sign;
|
||||
}
|
||||
|
||||
type BoxAxis = "x" | "y" | "z";
|
||||
|
||||
interface BoxFaceTransformMeta {
|
||||
axis: BoxAxis;
|
||||
sign: Sign;
|
||||
}
|
||||
|
||||
interface BoxEdgeTransformMeta {
|
||||
axis: BoxAxis;
|
||||
signs: {
|
||||
x: Sign | null;
|
||||
y: Sign | null;
|
||||
z: Sign | null;
|
||||
};
|
||||
}
|
||||
|
||||
const BOX_VERTEX_SIGNS: Record<BoxVertexId, BoxVertexSigns> = {
|
||||
negX_negY_negZ: { x: -1, y: -1, z: -1 },
|
||||
posX_negY_negZ: { x: 1, y: -1, z: -1 },
|
||||
@@ -27,6 +45,66 @@ const BOX_VERTEX_SIGNS: Record<BoxVertexId, BoxVertexSigns> = {
|
||||
posX_posY_posZ: { x: 1, y: 1, z: 1 }
|
||||
};
|
||||
|
||||
const BOX_FACE_TRANSFORM_META: Record<BoxFaceId, BoxFaceTransformMeta> = {
|
||||
posX: { axis: "x", sign: 1 },
|
||||
negX: { axis: "x", sign: -1 },
|
||||
posY: { axis: "y", sign: 1 },
|
||||
negY: { axis: "y", sign: -1 },
|
||||
posZ: { axis: "z", sign: 1 },
|
||||
negZ: { axis: "z", sign: -1 }
|
||||
};
|
||||
|
||||
const BOX_EDGE_TRANSFORM_META: Record<BoxEdgeId, BoxEdgeTransformMeta> = {
|
||||
edgeX_negY_negZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: -1, z: -1 }
|
||||
},
|
||||
edgeX_posY_negZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: 1, z: -1 }
|
||||
},
|
||||
edgeX_negY_posZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: -1, z: 1 }
|
||||
},
|
||||
edgeX_posY_posZ: {
|
||||
axis: "x",
|
||||
signs: { x: null, y: 1, z: 1 }
|
||||
},
|
||||
edgeY_negX_negZ: {
|
||||
axis: "y",
|
||||
signs: { x: -1, y: null, z: -1 }
|
||||
},
|
||||
edgeY_posX_negZ: {
|
||||
axis: "y",
|
||||
signs: { x: 1, y: null, z: -1 }
|
||||
},
|
||||
edgeY_negX_posZ: {
|
||||
axis: "y",
|
||||
signs: { x: -1, y: null, z: 1 }
|
||||
},
|
||||
edgeY_posX_posZ: {
|
||||
axis: "y",
|
||||
signs: { x: 1, y: null, z: 1 }
|
||||
},
|
||||
edgeZ_negX_negY: {
|
||||
axis: "z",
|
||||
signs: { x: -1, y: -1, z: null }
|
||||
},
|
||||
edgeZ_posX_negY: {
|
||||
axis: "z",
|
||||
signs: { x: 1, y: -1, z: null }
|
||||
},
|
||||
edgeZ_negX_posY: {
|
||||
axis: "z",
|
||||
signs: { x: -1, y: 1, z: null }
|
||||
},
|
||||
edgeZ_posX_posY: {
|
||||
axis: "z",
|
||||
signs: { x: 1, y: 1, z: null }
|
||||
}
|
||||
};
|
||||
|
||||
const BOX_EDGE_VERTEX_IDS: Record<BoxEdgeId, { start: BoxVertexId; end: BoxVertexId }> = {
|
||||
edgeX_negY_negZ: { start: "negX_negY_negZ", end: "posX_negY_negZ" },
|
||||
edgeX_posY_negZ: { start: "negX_posY_negZ", end: "posX_posY_negZ" },
|
||||
@@ -58,6 +136,32 @@ function createBrushRotationEuler(brush: BoxBrush): Euler {
|
||||
);
|
||||
}
|
||||
|
||||
export function transformBoxBrushWorldVectorToLocal(brush: BoxBrush, worldVector: Vec3): Vec3 {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
|
||||
const localVector = new Vector3(worldVector.x, worldVector.y, worldVector.z).applyQuaternion(inverseRotation);
|
||||
|
||||
return {
|
||||
x: localVector.x,
|
||||
y: localVector.y,
|
||||
z: localVector.z
|
||||
};
|
||||
}
|
||||
|
||||
export function transformBoxBrushWorldPointToLocal(brush: BoxBrush, worldPoint: Vec3): Vec3 {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const inverseRotation = new Quaternion().setFromEuler(rotation).invert();
|
||||
const localPoint = new Vector3(worldPoint.x - brush.center.x, worldPoint.y - brush.center.y, worldPoint.z - brush.center.z).applyQuaternion(
|
||||
inverseRotation
|
||||
);
|
||||
|
||||
return {
|
||||
x: localPoint.x,
|
||||
y: localPoint.y,
|
||||
z: localPoint.z
|
||||
};
|
||||
}
|
||||
|
||||
export function transformBoxBrushLocalPointToWorld(brush: BoxBrush, localPoint: Vec3): Vec3 {
|
||||
const rotation = createBrushRotationEuler(brush);
|
||||
const rotatedOffset = new Vector3(localPoint.x, localPoint.y, localPoint.z).applyEuler(rotation);
|
||||
@@ -69,15 +173,49 @@ export function transformBoxBrushLocalPointToWorld(brush: BoxBrush, localPoint:
|
||||
};
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexLocalPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
const signs = BOX_VERTEX_SIGNS[vertexId];
|
||||
export function getBoxBrushFaceTransformMeta(faceId: BoxFaceId): BoxFaceTransformMeta {
|
||||
return BOX_FACE_TRANSFORM_META[faceId];
|
||||
}
|
||||
|
||||
return {
|
||||
x: signs.x * halfSize.x,
|
||||
y: signs.y * halfSize.y,
|
||||
z: signs.z * halfSize.z
|
||||
};
|
||||
export function getBoxBrushEdgeTransformMeta(edgeId: BoxEdgeId): BoxEdgeTransformMeta {
|
||||
return BOX_EDGE_TRANSFORM_META[edgeId];
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexSigns(vertexId: BoxVertexId): BoxVertexSigns {
|
||||
return BOX_VERTEX_SIGNS[vertexId];
|
||||
}
|
||||
|
||||
export function getBoxBrushFaceWorldCenter(brush: BoxBrush, faceId: BoxFaceId): Vec3 {
|
||||
const faceVertexIds = getBoxBrushFaceVertexIds(faceId);
|
||||
const localCenter = faceVertexIds.reduce(
|
||||
(accumulator, vertexId) => {
|
||||
const vertex = getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
return {
|
||||
x: accumulator.x + vertex.x * 0.25,
|
||||
y: accumulator.y + vertex.y * 0.25,
|
||||
z: accumulator.z + vertex.z * 0.25
|
||||
};
|
||||
},
|
||||
{ x: 0, y: 0, z: 0 }
|
||||
);
|
||||
|
||||
return transformBoxBrushLocalPointToWorld(brush, localCenter);
|
||||
}
|
||||
|
||||
export function getBoxBrushFaceAxis(faceId: BoxFaceId): BoxAxis {
|
||||
return BOX_FACE_TRANSFORM_META[faceId].axis;
|
||||
}
|
||||
|
||||
export function getBoxBrushEdgeAxis(edgeId: BoxEdgeId): BoxAxis {
|
||||
return BOX_EDGE_TRANSFORM_META[edgeId].axis;
|
||||
}
|
||||
|
||||
export function getBoxBrushFaceIdsForAxis(axis: BoxAxis): BoxFaceId[] {
|
||||
return BOX_FACE_IDS.filter((faceId) => BOX_FACE_TRANSFORM_META[faceId].axis === axis);
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexLocalPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
return getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
}
|
||||
|
||||
export function getBoxBrushVertexWorldPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
|
||||
401
src/geometry/box-brush-mesh.js
Normal file
401
src/geometry/box-brush-mesh.js
Normal file
@@ -0,0 +1,401 @@
|
||||
import { BufferAttribute, BufferGeometry } from "three";
|
||||
import { BOX_EDGE_IDS, BOX_FACE_IDS } from "../document/brushes";
|
||||
import { transformProjectedFaceUv } from "./box-face-uvs";
|
||||
const FACE_VERTEX_IDS = {
|
||||
posX: ["posX_negY_posZ", "posX_negY_negZ", "posX_posY_negZ", "posX_posY_posZ"],
|
||||
negX: ["negX_negY_negZ", "negX_negY_posZ", "negX_posY_posZ", "negX_posY_negZ"],
|
||||
posY: ["negX_posY_posZ", "posX_posY_posZ", "posX_posY_negZ", "negX_posY_negZ"],
|
||||
negY: ["negX_negY_negZ", "posX_negY_negZ", "posX_negY_posZ", "negX_negY_posZ"],
|
||||
posZ: ["negX_negY_posZ", "posX_negY_posZ", "posX_posY_posZ", "negX_posY_posZ"],
|
||||
negZ: ["posX_negY_negZ", "negX_negY_negZ", "negX_posY_negZ", "posX_posY_negZ"]
|
||||
};
|
||||
const EDGE_VERTEX_IDS = {
|
||||
edgeX_negY_negZ: ["negX_negY_negZ", "posX_negY_negZ"],
|
||||
edgeX_posY_negZ: ["negX_posY_negZ", "posX_posY_negZ"],
|
||||
edgeX_negY_posZ: ["negX_negY_posZ", "posX_negY_posZ"],
|
||||
edgeX_posY_posZ: ["negX_posY_posZ", "posX_posY_posZ"],
|
||||
edgeY_negX_negZ: ["negX_negY_negZ", "negX_posY_negZ"],
|
||||
edgeY_posX_negZ: ["posX_negY_negZ", "posX_posY_negZ"],
|
||||
edgeY_negX_posZ: ["negX_negY_posZ", "negX_posY_posZ"],
|
||||
edgeY_posX_posZ: ["posX_negY_posZ", "posX_posY_posZ"],
|
||||
edgeZ_negX_negY: ["negX_negY_negZ", "negX_negY_posZ"],
|
||||
edgeZ_posX_negY: ["posX_negY_negZ", "posX_negY_posZ"],
|
||||
edgeZ_negX_posY: ["negX_posY_negZ", "negX_posY_posZ"],
|
||||
edgeZ_posX_posY: ["posX_posY_negZ", "posX_posY_posZ"]
|
||||
};
|
||||
const WATER_TOP_FACE_RENDER_SEGMENTS = 12;
|
||||
function cloneVec3(vector) {
|
||||
return { x: vector.x, y: vector.y, z: vector.z };
|
||||
}
|
||||
function subtractVec3(left, right) {
|
||||
return {
|
||||
x: left.x - right.x,
|
||||
y: left.y - right.y,
|
||||
z: left.z - right.z
|
||||
};
|
||||
}
|
||||
function crossVec3(left, right) {
|
||||
return {
|
||||
x: left.y * right.z - left.z * right.y,
|
||||
y: left.z * right.x - left.x * right.z,
|
||||
z: left.x * right.y - left.y * right.x
|
||||
};
|
||||
}
|
||||
function dotVec3(left, right) {
|
||||
return left.x * right.x + left.y * right.y + left.z * right.z;
|
||||
}
|
||||
function getVectorLength(vector) {
|
||||
return Math.sqrt(dotVec3(vector, vector));
|
||||
}
|
||||
function normalizeVec3(vector) {
|
||||
const length = getVectorLength(vector);
|
||||
if (length <= 1e-8) {
|
||||
return { x: 0, y: 0, z: 0 };
|
||||
}
|
||||
return {
|
||||
x: vector.x / length,
|
||||
y: vector.y / length,
|
||||
z: vector.z / length
|
||||
};
|
||||
}
|
||||
function computeNewellNormal(vertices) {
|
||||
let normal = { x: 0, y: 0, z: 0 };
|
||||
for (let index = 0; index < vertices.length; index += 1) {
|
||||
const current = vertices[index];
|
||||
const next = vertices[(index + 1) % vertices.length];
|
||||
normal.x += (current.y - next.y) * (current.z + next.z);
|
||||
normal.y += (current.z - next.z) * (current.x + next.x);
|
||||
normal.z += (current.x - next.x) * (current.y + next.y);
|
||||
}
|
||||
return normalizeVec3(normal);
|
||||
}
|
||||
function chooseProjectionAxes(normal) {
|
||||
const absoluteNormal = {
|
||||
x: Math.abs(normal.x),
|
||||
y: Math.abs(normal.y),
|
||||
z: Math.abs(normal.z)
|
||||
};
|
||||
if (absoluteNormal.x >= absoluteNormal.y && absoluteNormal.x >= absoluteNormal.z) {
|
||||
return ["y", "z"];
|
||||
}
|
||||
if (absoluteNormal.y >= absoluteNormal.z) {
|
||||
return ["x", "z"];
|
||||
}
|
||||
return ["x", "y"];
|
||||
}
|
||||
function projectVerticesTo2d(vertices, normal) {
|
||||
const [uAxis, vAxis] = chooseProjectionAxes(normal);
|
||||
return vertices.map((vertex) => ({
|
||||
x: vertex[uAxis],
|
||||
y: vertex[vAxis]
|
||||
}));
|
||||
}
|
||||
function computeSignedArea(points) {
|
||||
let area = 0;
|
||||
for (let index = 0; index < points.length; index += 1) {
|
||||
const current = points[index];
|
||||
const next = points[(index + 1) % points.length];
|
||||
area += current.x * next.y - next.x * current.y;
|
||||
}
|
||||
return area * 0.5;
|
||||
}
|
||||
function isPointInTriangle(point, triangle, orientation) {
|
||||
const [a, b, c] = triangle;
|
||||
const edges = [
|
||||
(b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x),
|
||||
(c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x),
|
||||
(a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)
|
||||
];
|
||||
return orientation > 0 ? edges.every((value) => value >= -1e-8) : edges.every((value) => value <= 1e-8);
|
||||
}
|
||||
function triangulateQuad(vertices) {
|
||||
const normal = computeNewellNormal(vertices);
|
||||
const projected = projectVerticesTo2d(vertices, normal);
|
||||
const orientation = computeSignedArea(projected);
|
||||
if (Math.abs(orientation) <= 1e-8) {
|
||||
throw new Error("Face projection is degenerate.");
|
||||
}
|
||||
const remaining = [0, 1, 2, 3];
|
||||
const triangles = [];
|
||||
while (remaining.length > 3) {
|
||||
let earFound = false;
|
||||
for (let offset = 0; offset < remaining.length; offset += 1) {
|
||||
const previousIndex = remaining[(offset + remaining.length - 1) % remaining.length];
|
||||
const currentIndex = remaining[offset];
|
||||
const nextIndex = remaining[(offset + 1) % remaining.length];
|
||||
const previousPoint = projected[previousIndex];
|
||||
const currentPoint = projected[currentIndex];
|
||||
const nextPoint = projected[nextIndex];
|
||||
const cross = (currentPoint.x - previousPoint.x) * (nextPoint.y - previousPoint.y) -
|
||||
(currentPoint.y - previousPoint.y) * (nextPoint.x - previousPoint.x);
|
||||
if ((orientation > 0 && cross <= 1e-8) || (orientation < 0 && cross >= -1e-8)) {
|
||||
continue;
|
||||
}
|
||||
const candidateTriangle = [previousPoint, currentPoint, nextPoint];
|
||||
const containsOtherPoint = remaining.some((candidateIndex) => {
|
||||
if (candidateIndex === previousIndex || candidateIndex === currentIndex || candidateIndex === nextIndex) {
|
||||
return false;
|
||||
}
|
||||
return isPointInTriangle(projected[candidateIndex], candidateTriangle, orientation);
|
||||
});
|
||||
if (containsOtherPoint) {
|
||||
continue;
|
||||
}
|
||||
triangles.push([previousIndex, currentIndex, nextIndex]);
|
||||
remaining.splice(offset, 1);
|
||||
earFound = true;
|
||||
break;
|
||||
}
|
||||
if (!earFound) {
|
||||
throw new Error("Face triangulation could not find a stable ear.");
|
||||
}
|
||||
}
|
||||
triangles.push([remaining[0], remaining[1], remaining[2]]);
|
||||
return triangles;
|
||||
}
|
||||
function projectLocalVertexToFaceUv(vertexPosition, faceId, faceBounds) {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
return {
|
||||
x: faceBounds.max.z - vertexPosition.z,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "negX":
|
||||
return {
|
||||
x: vertexPosition.z - faceBounds.min.z,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "posY":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: faceBounds.max.z - vertexPosition.z
|
||||
};
|
||||
case "negY":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: vertexPosition.z - faceBounds.min.z
|
||||
};
|
||||
case "posZ":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "negZ":
|
||||
return {
|
||||
x: faceBounds.max.x - vertexPosition.x,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
}
|
||||
}
|
||||
function getFaceUvSize(faceId, faceBounds) {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
case "negX":
|
||||
return {
|
||||
x: faceBounds.max.z - faceBounds.min.z,
|
||||
y: faceBounds.max.y - faceBounds.min.y
|
||||
};
|
||||
case "posY":
|
||||
case "negY":
|
||||
return {
|
||||
x: faceBounds.max.x - faceBounds.min.x,
|
||||
y: faceBounds.max.z - faceBounds.min.z
|
||||
};
|
||||
case "posZ":
|
||||
case "negZ":
|
||||
return {
|
||||
x: faceBounds.max.x - faceBounds.min.x,
|
||||
y: faceBounds.max.y - faceBounds.min.y
|
||||
};
|
||||
}
|
||||
}
|
||||
function computeFaceBounds(vertices) {
|
||||
const firstVertex = vertices[0];
|
||||
const min = { ...firstVertex };
|
||||
const max = { ...firstVertex };
|
||||
for (const vertex of vertices.slice(1)) {
|
||||
min.x = Math.min(min.x, vertex.x);
|
||||
min.y = Math.min(min.y, vertex.y);
|
||||
min.z = Math.min(min.z, vertex.z);
|
||||
max.x = Math.max(max.x, vertex.x);
|
||||
max.y = Math.max(max.y, vertex.y);
|
||||
max.z = Math.max(max.z, vertex.z);
|
||||
}
|
||||
return { min, max };
|
||||
}
|
||||
function lerpNumber(start, end, amount) {
|
||||
return start + (end - start) * amount;
|
||||
}
|
||||
function lerpVec3(start, end, amount) {
|
||||
return {
|
||||
x: lerpNumber(start.x, end.x, amount),
|
||||
y: lerpNumber(start.y, end.y, amount),
|
||||
z: lerpNumber(start.z, end.z, amount)
|
||||
};
|
||||
}
|
||||
function interpolateQuadSurfaceVertex(corners, u, v) {
|
||||
const topEdge = lerpVec3(corners[0], corners[1], u);
|
||||
const bottomEdge = lerpVec3(corners[3], corners[2], u);
|
||||
return lerpVec3(topEdge, bottomEdge, v);
|
||||
}
|
||||
function pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState) {
|
||||
const projectedUv = projectLocalVertexToFaceUv(vertex, faceId, faceBounds);
|
||||
const transformedUv = transformProjectedFaceUv(projectedUv, uvSize, uvState);
|
||||
positions.push(vertex.x, vertex.y, vertex.z);
|
||||
normals.push(normal.x, normal.y, normal.z);
|
||||
uvs.push(transformedUv.x, transformedUv.y);
|
||||
indices.push(indices.length);
|
||||
}
|
||||
export function getBoxBrushFaceVertexIds(faceId) {
|
||||
return FACE_VERTEX_IDS[faceId];
|
||||
}
|
||||
export function getBoxBrushEdgeVertexIds(edgeId) {
|
||||
return EDGE_VERTEX_IDS[edgeId];
|
||||
}
|
||||
export function getBoxBrushLocalVertexPosition(brush, vertexId) {
|
||||
return cloneVec3(brush.geometry.vertices[vertexId]);
|
||||
}
|
||||
export function buildBoxBrushDerivedMeshData(brush) {
|
||||
const diagnostics = validateBoxBrushGeometry(brush);
|
||||
if (diagnostics.length > 0) {
|
||||
throw new Error(diagnostics[0].message);
|
||||
}
|
||||
const positions = [];
|
||||
const normals = [];
|
||||
const uvs = [];
|
||||
const indices = [];
|
||||
const colliderVertices = [];
|
||||
const colliderIndices = [];
|
||||
const faceSurfaces = [];
|
||||
const groups = [];
|
||||
const vertexIndexMap = new Map();
|
||||
for (const vertexId of Object.keys(brush.geometry.vertices)) {
|
||||
const vertex = brush.geometry.vertices[vertexId];
|
||||
vertexIndexMap.set(vertexId, colliderVertices.length / 3);
|
||||
colliderVertices.push(vertex.x, vertex.y, vertex.z);
|
||||
}
|
||||
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
|
||||
const faceVertexIds = FACE_VERTEX_IDS[faceId];
|
||||
const faceVertices = faceVertexIds.map((vertexId) => getBoxBrushLocalVertexPosition(brush, vertexId));
|
||||
const triangles = triangulateQuad(faceVertices);
|
||||
const normal = computeNewellNormal(faceVertices);
|
||||
const faceBounds = computeFaceBounds(faceVertices);
|
||||
const uvSize = getFaceUvSize(faceId, faceBounds);
|
||||
const uvState = brush.faces[faceId].uv;
|
||||
const indexStart = indices.length;
|
||||
faceSurfaces.push({
|
||||
faceId,
|
||||
vertexIds: faceVertexIds,
|
||||
triangles,
|
||||
normal
|
||||
});
|
||||
const useSubdividedWaterTopFace = brush.volume.mode === "water" && faceId === "posY" && brush.volume.water.surfaceDisplacementEnabled;
|
||||
if (useSubdividedWaterTopFace) {
|
||||
const faceCorners = faceVertices;
|
||||
for (let row = 0; row < WATER_TOP_FACE_RENDER_SEGMENTS; row += 1) {
|
||||
const v0 = row / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const v1 = (row + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
for (let column = 0; column < WATER_TOP_FACE_RENDER_SEGMENTS; column += 1) {
|
||||
const u0 = column / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const u1 = (column + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const quadVertices = [
|
||||
interpolateQuadSurfaceVertex(faceCorners, u0, v0),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u1, v0),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u1, v1),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u0, v1)
|
||||
];
|
||||
for (const vertex of [quadVertices[0], quadVertices[1], quadVertices[2], quadVertices[0], quadVertices[2], quadVertices[3]]) {
|
||||
pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (const triangle of triangles) {
|
||||
for (const vertexOffset of triangle) {
|
||||
pushRenderedFaceVertex(positions, normals, uvs, indices, faceVertices[vertexOffset], normal, faceId, faceBounds, uvSize, uvState);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.push({
|
||||
start: indexStart,
|
||||
count: indices.length - indexStart,
|
||||
materialIndex
|
||||
});
|
||||
for (const triangle of triangles) {
|
||||
colliderIndices.push(vertexIndexMap.get(faceVertexIds[triangle[0]]) ?? 0, vertexIndexMap.get(faceVertexIds[triangle[1]]) ?? 0, vertexIndexMap.get(faceVertexIds[triangle[2]]) ?? 0);
|
||||
}
|
||||
}
|
||||
const geometry = new BufferGeometry();
|
||||
geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
|
||||
geometry.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
|
||||
geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));
|
||||
geometry.setIndex(indices);
|
||||
for (const group of groups) {
|
||||
geometry.addGroup(group.start, group.count, group.materialIndex);
|
||||
}
|
||||
geometry.computeBoundingBox();
|
||||
geometry.computeBoundingSphere();
|
||||
const firstVertex = brush.geometry.vertices.negX_negY_negZ;
|
||||
const localBounds = {
|
||||
min: cloneVec3(firstVertex),
|
||||
max: cloneVec3(firstVertex)
|
||||
};
|
||||
for (const vertex of Object.values(brush.geometry.vertices)) {
|
||||
localBounds.min.x = Math.min(localBounds.min.x, vertex.x);
|
||||
localBounds.min.y = Math.min(localBounds.min.y, vertex.y);
|
||||
localBounds.min.z = Math.min(localBounds.min.z, vertex.z);
|
||||
localBounds.max.x = Math.max(localBounds.max.x, vertex.x);
|
||||
localBounds.max.y = Math.max(localBounds.max.y, vertex.y);
|
||||
localBounds.max.z = Math.max(localBounds.max.z, vertex.z);
|
||||
}
|
||||
return {
|
||||
geometry,
|
||||
faceSurfaces,
|
||||
edgeSegments: BOX_EDGE_IDS.map((edgeId) => {
|
||||
const [startId, endId] = EDGE_VERTEX_IDS[edgeId];
|
||||
return {
|
||||
edgeId,
|
||||
start: getBoxBrushLocalVertexPosition(brush, startId),
|
||||
end: getBoxBrushLocalVertexPosition(brush, endId)
|
||||
};
|
||||
}),
|
||||
colliderVertices: new Float32Array(colliderVertices),
|
||||
colliderIndices: new Uint32Array(colliderIndices),
|
||||
localBounds
|
||||
};
|
||||
}
|
||||
export function validateBoxBrushGeometry(brush) {
|
||||
const diagnostics = [];
|
||||
for (const [vertexId, vertex] of Object.entries(brush.geometry.vertices)) {
|
||||
if (!Number.isFinite(vertex.x) || !Number.isFinite(vertex.y) || !Number.isFinite(vertex.z)) {
|
||||
diagnostics.push({
|
||||
code: "invalid-box-geometry-vertex",
|
||||
message: `Whitebox vertex ${vertexId} must remain finite.`
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const faceId of BOX_FACE_IDS) {
|
||||
const faceVertices = FACE_VERTEX_IDS[faceId].map((vertexId) => brush.geometry.vertices[vertexId]);
|
||||
const normal = computeNewellNormal(faceVertices);
|
||||
if (getVectorLength(normal) <= 1e-8) {
|
||||
diagnostics.push({
|
||||
code: "degenerate-box-face",
|
||||
message: `Whitebox face ${faceId} is degenerate and cannot be triangulated.`,
|
||||
faceId
|
||||
});
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
triangulateQuad(faceVertices);
|
||||
}
|
||||
catch (error) {
|
||||
diagnostics.push({
|
||||
code: "invalid-box-face-triangulation",
|
||||
message: error instanceof Error ? `Whitebox face ${faceId} could not be triangulated: ${error.message}` : `Whitebox face ${faceId} could not be triangulated.`,
|
||||
faceId
|
||||
});
|
||||
}
|
||||
}
|
||||
return diagnostics;
|
||||
}
|
||||
524
src/geometry/box-brush-mesh.ts
Normal file
524
src/geometry/box-brush-mesh.ts
Normal file
@@ -0,0 +1,524 @@
|
||||
import { BufferAttribute, BufferGeometry } from "three";
|
||||
|
||||
import type { Vec2, Vec3 } from "../core/vector";
|
||||
import {
|
||||
BOX_EDGE_IDS,
|
||||
BOX_FACE_IDS,
|
||||
type BoxBrush,
|
||||
type BoxEdgeId,
|
||||
type BoxFaceId,
|
||||
type BoxVertexId,
|
||||
type FaceUvState
|
||||
} from "../document/brushes";
|
||||
import { transformProjectedFaceUv } from "./box-face-uvs";
|
||||
|
||||
const FACE_VERTEX_IDS: Record<BoxFaceId, readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId]> = {
|
||||
posX: ["posX_negY_posZ", "posX_negY_negZ", "posX_posY_negZ", "posX_posY_posZ"],
|
||||
negX: ["negX_negY_negZ", "negX_negY_posZ", "negX_posY_posZ", "negX_posY_negZ"],
|
||||
posY: ["negX_posY_posZ", "posX_posY_posZ", "posX_posY_negZ", "negX_posY_negZ"],
|
||||
negY: ["negX_negY_negZ", "posX_negY_negZ", "posX_negY_posZ", "negX_negY_posZ"],
|
||||
posZ: ["negX_negY_posZ", "posX_negY_posZ", "posX_posY_posZ", "negX_posY_posZ"],
|
||||
negZ: ["posX_negY_negZ", "negX_negY_negZ", "negX_posY_negZ", "posX_posY_negZ"]
|
||||
};
|
||||
|
||||
const EDGE_VERTEX_IDS: Record<BoxEdgeId, readonly [BoxVertexId, BoxVertexId]> = {
|
||||
edgeX_negY_negZ: ["negX_negY_negZ", "posX_negY_negZ"],
|
||||
edgeX_posY_negZ: ["negX_posY_negZ", "posX_posY_negZ"],
|
||||
edgeX_negY_posZ: ["negX_negY_posZ", "posX_negY_posZ"],
|
||||
edgeX_posY_posZ: ["negX_posY_posZ", "posX_posY_posZ"],
|
||||
edgeY_negX_negZ: ["negX_negY_negZ", "negX_posY_negZ"],
|
||||
edgeY_posX_negZ: ["posX_negY_negZ", "posX_posY_negZ"],
|
||||
edgeY_negX_posZ: ["negX_negY_posZ", "negX_posY_posZ"],
|
||||
edgeY_posX_posZ: ["posX_negY_posZ", "posX_posY_posZ"],
|
||||
edgeZ_negX_negY: ["negX_negY_negZ", "negX_negY_posZ"],
|
||||
edgeZ_posX_negY: ["posX_negY_negZ", "posX_negY_posZ"],
|
||||
edgeZ_negX_posY: ["negX_posY_negZ", "negX_posY_posZ"],
|
||||
edgeZ_posX_posY: ["posX_posY_negZ", "posX_posY_posZ"]
|
||||
};
|
||||
|
||||
const WATER_TOP_FACE_RENDER_SEGMENTS = 12;
|
||||
|
||||
export interface BoxBrushGeometryDiagnostic {
|
||||
code: string;
|
||||
message: string;
|
||||
faceId?: BoxFaceId;
|
||||
}
|
||||
|
||||
export interface DerivedBoxBrushFaceSurface {
|
||||
faceId: BoxFaceId;
|
||||
vertexIds: readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId];
|
||||
triangles: Array<readonly [number, number, number]>;
|
||||
normal: Vec3;
|
||||
}
|
||||
|
||||
export interface DerivedBoxBrushMeshData {
|
||||
geometry: BufferGeometry;
|
||||
faceSurfaces: DerivedBoxBrushFaceSurface[];
|
||||
edgeSegments: Array<{ edgeId: BoxEdgeId; start: Vec3; end: Vec3 }>;
|
||||
colliderVertices: Float32Array;
|
||||
colliderIndices: Uint32Array;
|
||||
localBounds: { min: Vec3; max: Vec3 };
|
||||
}
|
||||
|
||||
function cloneVec3(vector: Vec3): Vec3 {
|
||||
return { x: vector.x, y: vector.y, z: vector.z };
|
||||
}
|
||||
|
||||
function dotVec3(left: Vec3, right: Vec3): number {
|
||||
return left.x * right.x + left.y * right.y + left.z * right.z;
|
||||
}
|
||||
|
||||
function getVectorLength(vector: Vec3): number {
|
||||
return Math.sqrt(dotVec3(vector, vector));
|
||||
}
|
||||
|
||||
function normalizeVec3(vector: Vec3): Vec3 {
|
||||
const length = getVectorLength(vector);
|
||||
|
||||
if (length <= 1e-8) {
|
||||
return { x: 0, y: 0, z: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
x: vector.x / length,
|
||||
y: vector.y / length,
|
||||
z: vector.z / length
|
||||
};
|
||||
}
|
||||
|
||||
function computeNewellNormal(vertices: Vec3[]): Vec3 {
|
||||
let normal = { x: 0, y: 0, z: 0 };
|
||||
|
||||
for (let index = 0; index < vertices.length; index += 1) {
|
||||
const current = vertices[index];
|
||||
const next = vertices[(index + 1) % vertices.length];
|
||||
normal.x += (current.y - next.y) * (current.z + next.z);
|
||||
normal.y += (current.z - next.z) * (current.x + next.x);
|
||||
normal.z += (current.x - next.x) * (current.y + next.y);
|
||||
}
|
||||
|
||||
return normalizeVec3(normal);
|
||||
}
|
||||
|
||||
function chooseProjectionAxes(normal: Vec3): [keyof Vec3, keyof Vec3] {
|
||||
const absoluteNormal = {
|
||||
x: Math.abs(normal.x),
|
||||
y: Math.abs(normal.y),
|
||||
z: Math.abs(normal.z)
|
||||
};
|
||||
|
||||
if (absoluteNormal.x >= absoluteNormal.y && absoluteNormal.x >= absoluteNormal.z) {
|
||||
return ["y", "z"];
|
||||
}
|
||||
|
||||
if (absoluteNormal.y >= absoluteNormal.z) {
|
||||
return ["x", "z"];
|
||||
}
|
||||
|
||||
return ["x", "y"];
|
||||
}
|
||||
|
||||
function projectVerticesTo2d(vertices: Vec3[], normal: Vec3): Vec2[] {
|
||||
const [uAxis, vAxis] = chooseProjectionAxes(normal);
|
||||
return vertices.map((vertex) => ({
|
||||
x: vertex[uAxis],
|
||||
y: vertex[vAxis]
|
||||
}));
|
||||
}
|
||||
|
||||
function computeSignedArea(points: Vec2[]): number {
|
||||
let area = 0;
|
||||
|
||||
for (let index = 0; index < points.length; index += 1) {
|
||||
const current = points[index];
|
||||
const next = points[(index + 1) % points.length];
|
||||
area += current.x * next.y - next.x * current.y;
|
||||
}
|
||||
|
||||
return area * 0.5;
|
||||
}
|
||||
|
||||
function isPointInTriangle(point: Vec2, triangle: [Vec2, Vec2, Vec2], orientation: number): boolean {
|
||||
const [a, b, c] = triangle;
|
||||
const edges = [
|
||||
(b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x),
|
||||
(c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x),
|
||||
(a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)
|
||||
];
|
||||
|
||||
return orientation > 0 ? edges.every((value) => value >= -1e-8) : edges.every((value) => value <= 1e-8);
|
||||
}
|
||||
|
||||
function triangulateQuad(vertices: Vec3[]): Array<readonly [number, number, number]> {
|
||||
const normal = computeNewellNormal(vertices);
|
||||
const projected = projectVerticesTo2d(vertices, normal);
|
||||
const orientation = computeSignedArea(projected);
|
||||
|
||||
if (Math.abs(orientation) <= 1e-8) {
|
||||
throw new Error("Face projection is degenerate.");
|
||||
}
|
||||
|
||||
const remaining = [0, 1, 2, 3];
|
||||
const triangles: Array<readonly [number, number, number]> = [];
|
||||
|
||||
while (remaining.length > 3) {
|
||||
let earFound = false;
|
||||
|
||||
for (let offset = 0; offset < remaining.length; offset += 1) {
|
||||
const previousIndex = remaining[(offset + remaining.length - 1) % remaining.length];
|
||||
const currentIndex = remaining[offset];
|
||||
const nextIndex = remaining[(offset + 1) % remaining.length];
|
||||
const previousPoint = projected[previousIndex];
|
||||
const currentPoint = projected[currentIndex];
|
||||
const nextPoint = projected[nextIndex];
|
||||
const cross =
|
||||
(currentPoint.x - previousPoint.x) * (nextPoint.y - previousPoint.y) -
|
||||
(currentPoint.y - previousPoint.y) * (nextPoint.x - previousPoint.x);
|
||||
|
||||
if ((orientation > 0 && cross <= 1e-8) || (orientation < 0 && cross >= -1e-8)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const candidateTriangle: [Vec2, Vec2, Vec2] = [previousPoint, currentPoint, nextPoint];
|
||||
const containsOtherPoint = remaining.some((candidateIndex) => {
|
||||
if (candidateIndex === previousIndex || candidateIndex === currentIndex || candidateIndex === nextIndex) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isPointInTriangle(projected[candidateIndex], candidateTriangle, orientation);
|
||||
});
|
||||
|
||||
if (containsOtherPoint) {
|
||||
continue;
|
||||
}
|
||||
|
||||
triangles.push([previousIndex, currentIndex, nextIndex]);
|
||||
remaining.splice(offset, 1);
|
||||
earFound = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!earFound) {
|
||||
throw new Error("Face triangulation could not find a stable ear.");
|
||||
}
|
||||
}
|
||||
|
||||
triangles.push([remaining[0], remaining[1], remaining[2]]);
|
||||
return triangles;
|
||||
}
|
||||
|
||||
function projectLocalVertexToFaceUv(vertexPosition: Vec3, faceId: BoxFaceId, faceBounds: { min: Vec3; max: Vec3 }): Vec2 {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
return {
|
||||
x: faceBounds.max.z - vertexPosition.z,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "negX":
|
||||
return {
|
||||
x: vertexPosition.z - faceBounds.min.z,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "posY":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: faceBounds.max.z - vertexPosition.z
|
||||
};
|
||||
case "negY":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: vertexPosition.z - faceBounds.min.z
|
||||
};
|
||||
case "posZ":
|
||||
return {
|
||||
x: vertexPosition.x - faceBounds.min.x,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
case "negZ":
|
||||
return {
|
||||
x: faceBounds.max.x - vertexPosition.x,
|
||||
y: vertexPosition.y - faceBounds.min.y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function getFaceUvSize(faceId: BoxFaceId, faceBounds: { min: Vec3; max: Vec3 }): Vec2 {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
case "negX":
|
||||
return {
|
||||
x: faceBounds.max.z - faceBounds.min.z,
|
||||
y: faceBounds.max.y - faceBounds.min.y
|
||||
};
|
||||
case "posY":
|
||||
case "negY":
|
||||
return {
|
||||
x: faceBounds.max.x - faceBounds.min.x,
|
||||
y: faceBounds.max.z - faceBounds.min.z
|
||||
};
|
||||
case "posZ":
|
||||
case "negZ":
|
||||
return {
|
||||
x: faceBounds.max.x - faceBounds.min.x,
|
||||
y: faceBounds.max.y - faceBounds.min.y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function computeFaceBounds(vertices: Vec3[]): { min: Vec3; max: Vec3 } {
|
||||
const firstVertex = vertices[0];
|
||||
const min = { ...firstVertex };
|
||||
const max = { ...firstVertex };
|
||||
|
||||
for (const vertex of vertices.slice(1)) {
|
||||
min.x = Math.min(min.x, vertex.x);
|
||||
min.y = Math.min(min.y, vertex.y);
|
||||
min.z = Math.min(min.z, vertex.z);
|
||||
max.x = Math.max(max.x, vertex.x);
|
||||
max.y = Math.max(max.y, vertex.y);
|
||||
max.z = Math.max(max.z, vertex.z);
|
||||
}
|
||||
|
||||
return { min, max };
|
||||
}
|
||||
|
||||
function lerpNumber(start: number, end: number, amount: number) {
|
||||
return start + (end - start) * amount;
|
||||
}
|
||||
|
||||
function lerpVec3(start: Vec3, end: Vec3, amount: number): Vec3 {
|
||||
return {
|
||||
x: lerpNumber(start.x, end.x, amount),
|
||||
y: lerpNumber(start.y, end.y, amount),
|
||||
z: lerpNumber(start.z, end.z, amount)
|
||||
};
|
||||
}
|
||||
|
||||
function interpolateQuadSurfaceVertex(
|
||||
corners: readonly [Vec3, Vec3, Vec3, Vec3],
|
||||
u: number,
|
||||
v: number
|
||||
): Vec3 {
|
||||
const topEdge = lerpVec3(corners[0], corners[1], u);
|
||||
const bottomEdge = lerpVec3(corners[3], corners[2], u);
|
||||
|
||||
return lerpVec3(topEdge, bottomEdge, v);
|
||||
}
|
||||
|
||||
function pushRenderedFaceVertex(
|
||||
positions: number[],
|
||||
normals: number[],
|
||||
uvs: number[],
|
||||
indices: number[],
|
||||
vertex: Vec3,
|
||||
normal: Vec3,
|
||||
faceId: BoxFaceId,
|
||||
faceBounds: { min: Vec3; max: Vec3 },
|
||||
uvSize: Vec2,
|
||||
uvState: FaceUvState
|
||||
) {
|
||||
const projectedUv = projectLocalVertexToFaceUv(vertex, faceId, faceBounds);
|
||||
const transformedUv = transformProjectedFaceUv(projectedUv, uvSize, uvState);
|
||||
|
||||
positions.push(vertex.x, vertex.y, vertex.z);
|
||||
normals.push(normal.x, normal.y, normal.z);
|
||||
uvs.push(transformedUv.x, transformedUv.y);
|
||||
indices.push(indices.length);
|
||||
}
|
||||
|
||||
export function getBoxBrushFaceVertexIds(faceId: BoxFaceId): readonly [BoxVertexId, BoxVertexId, BoxVertexId, BoxVertexId] {
|
||||
return FACE_VERTEX_IDS[faceId];
|
||||
}
|
||||
|
||||
export function getBoxBrushEdgeVertexIds(edgeId: BoxEdgeId): readonly [BoxVertexId, BoxVertexId] {
|
||||
return EDGE_VERTEX_IDS[edgeId];
|
||||
}
|
||||
|
||||
export function getBoxBrushLocalVertexPosition(brush: BoxBrush, vertexId: BoxVertexId): Vec3 {
|
||||
return cloneVec3(brush.geometry.vertices[vertexId]);
|
||||
}
|
||||
|
||||
export function buildBoxBrushDerivedMeshData(brush: BoxBrush): DerivedBoxBrushMeshData {
|
||||
const diagnostics = validateBoxBrushGeometry(brush);
|
||||
|
||||
if (diagnostics.length > 0) {
|
||||
throw new Error(diagnostics[0].message);
|
||||
}
|
||||
|
||||
const positions: number[] = [];
|
||||
const normals: number[] = [];
|
||||
const uvs: number[] = [];
|
||||
const indices: number[] = [];
|
||||
const colliderVertices: number[] = [];
|
||||
const colliderIndices: number[] = [];
|
||||
const faceSurfaces: DerivedBoxBrushFaceSurface[] = [];
|
||||
const groups: Array<{ start: number; count: number; materialIndex: number }> = [];
|
||||
const vertexIndexMap = new Map<BoxVertexId, number>();
|
||||
|
||||
for (const vertexId of Object.keys(brush.geometry.vertices) as BoxVertexId[]) {
|
||||
const vertex = brush.geometry.vertices[vertexId];
|
||||
vertexIndexMap.set(vertexId, colliderVertices.length / 3);
|
||||
colliderVertices.push(vertex.x, vertex.y, vertex.z);
|
||||
}
|
||||
|
||||
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
|
||||
const faceVertexIds = FACE_VERTEX_IDS[faceId];
|
||||
const faceVertices = faceVertexIds.map((vertexId) => getBoxBrushLocalVertexPosition(brush, vertexId));
|
||||
const triangles = triangulateQuad(faceVertices);
|
||||
const normal = computeNewellNormal(faceVertices);
|
||||
const faceBounds = computeFaceBounds(faceVertices);
|
||||
const uvSize = getFaceUvSize(faceId, faceBounds);
|
||||
const uvState = brush.faces[faceId].uv as FaceUvState;
|
||||
const indexStart = indices.length;
|
||||
|
||||
faceSurfaces.push({
|
||||
faceId,
|
||||
vertexIds: faceVertexIds,
|
||||
triangles,
|
||||
normal
|
||||
});
|
||||
|
||||
const useSubdividedWaterTopFace =
|
||||
brush.volume.mode === "water" &&
|
||||
faceId === "posY" &&
|
||||
brush.volume.water.surfaceDisplacementEnabled;
|
||||
|
||||
if (useSubdividedWaterTopFace) {
|
||||
const faceCorners = faceVertices as [Vec3, Vec3, Vec3, Vec3];
|
||||
|
||||
for (let row = 0; row < WATER_TOP_FACE_RENDER_SEGMENTS; row += 1) {
|
||||
const v0 = row / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const v1 = (row + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
|
||||
for (let column = 0; column < WATER_TOP_FACE_RENDER_SEGMENTS; column += 1) {
|
||||
const u0 = column / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const u1 = (column + 1) / WATER_TOP_FACE_RENDER_SEGMENTS;
|
||||
const quadVertices: [Vec3, Vec3, Vec3, Vec3] = [
|
||||
interpolateQuadSurfaceVertex(faceCorners, u0, v0),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u1, v0),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u1, v1),
|
||||
interpolateQuadSurfaceVertex(faceCorners, u0, v1)
|
||||
];
|
||||
|
||||
for (const vertex of [quadVertices[0], quadVertices[1], quadVertices[2], quadVertices[0], quadVertices[2], quadVertices[3]]) {
|
||||
pushRenderedFaceVertex(positions, normals, uvs, indices, vertex, normal, faceId, faceBounds, uvSize, uvState);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const triangle of triangles) {
|
||||
for (const vertexOffset of triangle) {
|
||||
pushRenderedFaceVertex(
|
||||
positions,
|
||||
normals,
|
||||
uvs,
|
||||
indices,
|
||||
faceVertices[vertexOffset],
|
||||
normal,
|
||||
faceId,
|
||||
faceBounds,
|
||||
uvSize,
|
||||
uvState
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
groups.push({
|
||||
start: indexStart,
|
||||
count: indices.length - indexStart,
|
||||
materialIndex
|
||||
});
|
||||
|
||||
for (const triangle of triangles) {
|
||||
colliderIndices.push(
|
||||
vertexIndexMap.get(faceVertexIds[triangle[0]]) ?? 0,
|
||||
vertexIndexMap.get(faceVertexIds[triangle[1]]) ?? 0,
|
||||
vertexIndexMap.get(faceVertexIds[triangle[2]]) ?? 0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const geometry = new BufferGeometry();
|
||||
geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
|
||||
geometry.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
|
||||
geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));
|
||||
geometry.setIndex(indices);
|
||||
|
||||
for (const group of groups) {
|
||||
geometry.addGroup(group.start, group.count, group.materialIndex);
|
||||
}
|
||||
|
||||
geometry.computeBoundingBox();
|
||||
geometry.computeBoundingSphere();
|
||||
|
||||
const firstVertex = brush.geometry.vertices.negX_negY_negZ;
|
||||
const localBounds = {
|
||||
min: cloneVec3(firstVertex),
|
||||
max: cloneVec3(firstVertex)
|
||||
};
|
||||
|
||||
for (const vertex of Object.values(brush.geometry.vertices)) {
|
||||
localBounds.min.x = Math.min(localBounds.min.x, vertex.x);
|
||||
localBounds.min.y = Math.min(localBounds.min.y, vertex.y);
|
||||
localBounds.min.z = Math.min(localBounds.min.z, vertex.z);
|
||||
localBounds.max.x = Math.max(localBounds.max.x, vertex.x);
|
||||
localBounds.max.y = Math.max(localBounds.max.y, vertex.y);
|
||||
localBounds.max.z = Math.max(localBounds.max.z, vertex.z);
|
||||
}
|
||||
|
||||
return {
|
||||
geometry,
|
||||
faceSurfaces,
|
||||
edgeSegments: BOX_EDGE_IDS.map((edgeId) => {
|
||||
const [startId, endId] = EDGE_VERTEX_IDS[edgeId];
|
||||
return {
|
||||
edgeId,
|
||||
start: getBoxBrushLocalVertexPosition(brush, startId),
|
||||
end: getBoxBrushLocalVertexPosition(brush, endId)
|
||||
};
|
||||
}),
|
||||
colliderVertices: new Float32Array(colliderVertices),
|
||||
colliderIndices: new Uint32Array(colliderIndices),
|
||||
localBounds
|
||||
};
|
||||
}
|
||||
|
||||
export function validateBoxBrushGeometry(brush: BoxBrush): BoxBrushGeometryDiagnostic[] {
|
||||
const diagnostics: BoxBrushGeometryDiagnostic[] = [];
|
||||
|
||||
for (const [vertexId, vertex] of Object.entries(brush.geometry.vertices) as Array<[BoxVertexId, Vec3]>) {
|
||||
if (!Number.isFinite(vertex.x) || !Number.isFinite(vertex.y) || !Number.isFinite(vertex.z)) {
|
||||
diagnostics.push({
|
||||
code: "invalid-box-geometry-vertex",
|
||||
message: `Whitebox vertex ${vertexId} must remain finite.`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const faceId of BOX_FACE_IDS) {
|
||||
const faceVertices = FACE_VERTEX_IDS[faceId].map((vertexId) => brush.geometry.vertices[vertexId]);
|
||||
const normal = computeNewellNormal(faceVertices);
|
||||
|
||||
if (getVectorLength(normal) <= 1e-8) {
|
||||
diagnostics.push({
|
||||
code: "degenerate-box-face",
|
||||
message: `Whitebox face ${faceId} is degenerate and cannot be triangulated.`,
|
||||
faceId
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
triangulateQuad(faceVertices);
|
||||
} catch (error) {
|
||||
diagnostics.push({
|
||||
code: "invalid-box-face-triangulation",
|
||||
message: error instanceof Error ? `Whitebox face ${faceId} could not be triangulated: ${error.message}` : `Whitebox face ${faceId} could not be triangulated.`,
|
||||
faceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
43
src/geometry/box-brush.js
Normal file
43
src/geometry/box-brush.js
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Euler, MathUtils, Vector3 } from "three";
|
||||
import { BOX_VERTEX_IDS } from "../document/brushes";
|
||||
import { getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
|
||||
export function getBoxBrushHalfSize(brush) {
|
||||
return {
|
||||
x: brush.size.x * 0.5,
|
||||
y: brush.size.y * 0.5,
|
||||
z: brush.size.z * 0.5
|
||||
};
|
||||
}
|
||||
export function getBoxBrushBounds(brush) {
|
||||
const corners = getBoxBrushCornerPositions(brush);
|
||||
const firstCorner = corners[0];
|
||||
const min = { ...firstCorner };
|
||||
const max = { ...firstCorner };
|
||||
for (const corner of corners.slice(1)) {
|
||||
min.x = Math.min(min.x, corner.x);
|
||||
min.y = Math.min(min.y, corner.y);
|
||||
min.z = Math.min(min.z, corner.z);
|
||||
max.x = Math.max(max.x, corner.x);
|
||||
max.y = Math.max(max.y, corner.y);
|
||||
max.z = Math.max(max.z, corner.z);
|
||||
}
|
||||
return {
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
export function getBoxBrushCornerPositions(brush) {
|
||||
const rotation = new Euler(MathUtils.degToRad(brush.rotationDegrees.x), MathUtils.degToRad(brush.rotationDegrees.y), MathUtils.degToRad(brush.rotationDegrees.z), "XYZ");
|
||||
const offsets = BOX_VERTEX_IDS.map((vertexId) => {
|
||||
const localVertex = getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
return new Vector3(localVertex.x, localVertex.y, localVertex.z);
|
||||
});
|
||||
return offsets.map((offset) => {
|
||||
const rotatedOffset = offset.clone().applyEuler(rotation);
|
||||
return {
|
||||
x: brush.center.x + rotatedOffset.x,
|
||||
y: brush.center.y + rotatedOffset.y,
|
||||
z: brush.center.z + rotatedOffset.z
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Euler, MathUtils, Vector3 } from "three";
|
||||
|
||||
import type { Vec3 } from "../core/vector";
|
||||
import type { BoxBrush } from "../document/brushes";
|
||||
import { BOX_VERTEX_IDS, type BoxBrush } from "../document/brushes";
|
||||
import { getBoxBrushLocalVertexPosition } from "./box-brush-mesh";
|
||||
|
||||
export interface BoxBrushBounds {
|
||||
min: Vec3;
|
||||
@@ -38,23 +39,16 @@ export function getBoxBrushBounds(brush: BoxBrush): BoxBrushBounds {
|
||||
}
|
||||
|
||||
export function getBoxBrushCornerPositions(brush: BoxBrush): Vec3[] {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
const rotation = new Euler(
|
||||
MathUtils.degToRad(brush.rotationDegrees.x),
|
||||
MathUtils.degToRad(brush.rotationDegrees.y),
|
||||
MathUtils.degToRad(brush.rotationDegrees.z),
|
||||
"XYZ"
|
||||
);
|
||||
const offsets = [
|
||||
new Vector3(-halfSize.x, -halfSize.y, -halfSize.z),
|
||||
new Vector3(halfSize.x, -halfSize.y, -halfSize.z),
|
||||
new Vector3(-halfSize.x, halfSize.y, -halfSize.z),
|
||||
new Vector3(halfSize.x, halfSize.y, -halfSize.z),
|
||||
new Vector3(-halfSize.x, -halfSize.y, halfSize.z),
|
||||
new Vector3(halfSize.x, -halfSize.y, halfSize.z),
|
||||
new Vector3(-halfSize.x, halfSize.y, halfSize.z),
|
||||
new Vector3(halfSize.x, halfSize.y, halfSize.z)
|
||||
];
|
||||
const offsets = BOX_VERTEX_IDS.map((vertexId) => {
|
||||
const localVertex = getBoxBrushLocalVertexPosition(brush, vertexId);
|
||||
return new Vector3(localVertex.x, localVertex.y, localVertex.z);
|
||||
});
|
||||
|
||||
return offsets.map((offset) => {
|
||||
const rotatedOffset = offset.clone().applyEuler(rotation);
|
||||
|
||||
133
src/geometry/box-face-uvs.js
Normal file
133
src/geometry/box-face-uvs.js
Normal file
@@ -0,0 +1,133 @@
|
||||
import { BoxGeometry } from "three";
|
||||
import { BOX_FACE_IDS, createDefaultFaceUvState } from "../document/brushes";
|
||||
import { getBoxBrushHalfSize } from "./box-brush";
|
||||
export function getBoxBrushFaceSize(brush, faceId) {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
case "negX":
|
||||
return {
|
||||
x: brush.size.z,
|
||||
y: brush.size.y
|
||||
};
|
||||
case "posY":
|
||||
case "negY":
|
||||
return {
|
||||
x: brush.size.x,
|
||||
y: brush.size.z
|
||||
};
|
||||
case "posZ":
|
||||
case "negZ":
|
||||
return {
|
||||
x: brush.size.x,
|
||||
y: brush.size.y
|
||||
};
|
||||
}
|
||||
}
|
||||
export function createFitToFaceBoxBrushFaceUvState(brush, faceId) {
|
||||
const faceSize = getBoxBrushFaceSize(brush, faceId);
|
||||
return {
|
||||
...createDefaultFaceUvState(),
|
||||
scale: {
|
||||
x: 1 / faceSize.x,
|
||||
y: 1 / faceSize.y
|
||||
}
|
||||
};
|
||||
}
|
||||
export function projectBoxFaceVertexToUv(vertexPosition, brush, faceId) {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
return {
|
||||
x: halfSize.z - vertexPosition.z,
|
||||
y: vertexPosition.y + halfSize.y
|
||||
};
|
||||
case "negX":
|
||||
return {
|
||||
x: vertexPosition.z + halfSize.z,
|
||||
y: vertexPosition.y + halfSize.y
|
||||
};
|
||||
case "posY":
|
||||
return {
|
||||
x: vertexPosition.x + halfSize.x,
|
||||
y: halfSize.z - vertexPosition.z
|
||||
};
|
||||
case "negY":
|
||||
return {
|
||||
x: vertexPosition.x + halfSize.x,
|
||||
y: vertexPosition.z + halfSize.z
|
||||
};
|
||||
case "posZ":
|
||||
return {
|
||||
x: vertexPosition.x + halfSize.x,
|
||||
y: vertexPosition.y + halfSize.y
|
||||
};
|
||||
case "negZ":
|
||||
return {
|
||||
x: halfSize.x - vertexPosition.x,
|
||||
y: vertexPosition.y + halfSize.y
|
||||
};
|
||||
}
|
||||
}
|
||||
export function transformProjectedFaceUv(baseUv, faceSize, uvState) {
|
||||
let u = (baseUv.x - faceSize.x * 0.5) * uvState.scale.x;
|
||||
let v = (baseUv.y - faceSize.y * 0.5) * uvState.scale.y;
|
||||
if (uvState.flipU) {
|
||||
u *= -1;
|
||||
}
|
||||
if (uvState.flipV) {
|
||||
v *= -1;
|
||||
}
|
||||
switch (uvState.rotationQuarterTurns) {
|
||||
case 1: {
|
||||
const nextU = -v;
|
||||
v = u;
|
||||
u = nextU;
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
u *= -1;
|
||||
v *= -1;
|
||||
break;
|
||||
case 3: {
|
||||
const nextU = v;
|
||||
v = -u;
|
||||
u = nextU;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
x: u + faceSize.x * 0.5 * uvState.scale.x + uvState.offset.x,
|
||||
y: v + faceSize.y * 0.5 * uvState.scale.y + uvState.offset.y
|
||||
};
|
||||
}
|
||||
export function applyBoxBrushFaceUvsToGeometry(geometry, brush) {
|
||||
const positionAttribute = geometry.getAttribute("position");
|
||||
const uvAttribute = geometry.getAttribute("uv");
|
||||
const indexAttribute = geometry.getIndex();
|
||||
if (indexAttribute === null) {
|
||||
throw new Error("BoxGeometry is expected to be indexed for face UV projection.");
|
||||
}
|
||||
// BoxGeometry groups follow the same px, nx, py, ny, pz, nz order as the canonical face ids.
|
||||
for (const [materialIndex, faceId] of BOX_FACE_IDS.entries()) {
|
||||
const group = geometry.groups.find((candidate) => candidate.materialIndex === materialIndex);
|
||||
if (group === undefined) {
|
||||
continue;
|
||||
}
|
||||
const faceSize = getBoxBrushFaceSize(brush, faceId);
|
||||
const vertexIndices = new Set();
|
||||
for (let indexOffset = group.start; indexOffset < group.start + group.count; indexOffset += 1) {
|
||||
vertexIndices.add(indexAttribute.getX(indexOffset));
|
||||
}
|
||||
for (const vertexIndex of vertexIndices) {
|
||||
const localVertexPosition = {
|
||||
x: positionAttribute.getX(vertexIndex),
|
||||
y: positionAttribute.getY(vertexIndex),
|
||||
z: positionAttribute.getZ(vertexIndex)
|
||||
};
|
||||
const projectedUv = projectBoxFaceVertexToUv(localVertexPosition, brush, faceId);
|
||||
const transformedUv = transformProjectedFaceUv(projectedUv, faceSize, brush.faces[faceId].uv);
|
||||
uvAttribute.setXY(vertexIndex, transformedUv.x, transformedUv.y);
|
||||
}
|
||||
}
|
||||
uvAttribute.needsUpdate = true;
|
||||
}
|
||||
@@ -2,9 +2,13 @@ import { BoxGeometry } from "three";
|
||||
|
||||
import type { Vec2, Vec3 } from "../core/vector";
|
||||
import { BOX_FACE_IDS, createDefaultFaceUvState, type BoxBrush, type BoxFaceId, type FaceUvState } from "../document/brushes";
|
||||
import { getBoxBrushHalfSize } from "./box-brush";
|
||||
|
||||
export function getBoxBrushFaceSize(brush: BoxBrush, faceId: BoxFaceId): Vec2 {
|
||||
interface BoxBrushUvProjectionSource {
|
||||
size: Vec3;
|
||||
faces: Record<BoxFaceId, { uv: FaceUvState }>;
|
||||
}
|
||||
|
||||
export function getBoxBrushFaceSize(brush: BoxBrushUvProjectionSource, faceId: BoxFaceId): Vec2 {
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
case "negX":
|
||||
@@ -39,8 +43,12 @@ export function createFitToFaceBoxBrushFaceUvState(brush: BoxBrush, faceId: BoxF
|
||||
};
|
||||
}
|
||||
|
||||
export function projectBoxFaceVertexToUv(vertexPosition: Vec3, brush: BoxBrush, faceId: BoxFaceId): Vec2 {
|
||||
const halfSize = getBoxBrushHalfSize(brush);
|
||||
export function projectBoxFaceVertexToUv(vertexPosition: Vec3, brush: BoxBrushUvProjectionSource, faceId: BoxFaceId): Vec2 {
|
||||
const halfSize = {
|
||||
x: brush.size.x * 0.5,
|
||||
y: brush.size.y * 0.5,
|
||||
z: brush.size.z * 0.5
|
||||
};
|
||||
|
||||
switch (faceId) {
|
||||
case "posX":
|
||||
@@ -113,7 +121,7 @@ export function transformProjectedFaceUv(baseUv: Vec2, faceSize: Vec2, uvState:
|
||||
};
|
||||
}
|
||||
|
||||
export function applyBoxBrushFaceUvsToGeometry(geometry: BoxGeometry, brush: BoxBrush): void {
|
||||
export function applyBoxBrushFaceUvsToGeometry(geometry: BoxGeometry, brush: BoxBrushUvProjectionSource): void {
|
||||
const positionAttribute = geometry.getAttribute("position");
|
||||
const uvAttribute = geometry.getAttribute("uv");
|
||||
const indexAttribute = geometry.getIndex();
|
||||
|
||||
36
src/geometry/grid-snapping.js
Normal file
36
src/geometry/grid-snapping.js
Normal file
@@ -0,0 +1,36 @@
|
||||
export const DEFAULT_GRID_SIZE = 1;
|
||||
function assertGridSize(gridSize) {
|
||||
if (!Number.isFinite(gridSize) || gridSize <= 0) {
|
||||
throw new Error("Grid size must be a positive finite number.");
|
||||
}
|
||||
return gridSize;
|
||||
}
|
||||
export function snapValueToGrid(value, gridSize = DEFAULT_GRID_SIZE) {
|
||||
const step = assertGridSize(gridSize);
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error("Grid-snapped values must be finite numbers.");
|
||||
}
|
||||
return Math.round(value / step) * step;
|
||||
}
|
||||
function snapPositiveSizeValue(value, gridSize) {
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error("Box brush size values must be finite numbers.");
|
||||
}
|
||||
const snappedSize = Math.round(Math.abs(value) / gridSize) * gridSize;
|
||||
return snappedSize > 0 ? snappedSize : gridSize;
|
||||
}
|
||||
export function snapVec3ToGrid(vector, gridSize = DEFAULT_GRID_SIZE) {
|
||||
return {
|
||||
x: snapValueToGrid(vector.x, gridSize),
|
||||
y: snapValueToGrid(vector.y, gridSize),
|
||||
z: snapValueToGrid(vector.z, gridSize)
|
||||
};
|
||||
}
|
||||
export function snapPositiveSizeToGrid(size, gridSize = DEFAULT_GRID_SIZE) {
|
||||
const step = assertGridSize(gridSize);
|
||||
return {
|
||||
x: snapPositiveSizeValue(size.x, step),
|
||||
y: snapPositiveSizeValue(size.y, step),
|
||||
z: snapPositiveSizeValue(size.z, step)
|
||||
};
|
||||
}
|
||||
119
src/geometry/model-instance-collider-debug-mesh.js
Normal file
119
src/geometry/model-instance-collider-debug-mesh.js
Normal file
@@ -0,0 +1,119 @@
|
||||
import { BoxGeometry, BufferGeometry, Float32BufferAttribute, Group, Mesh, MeshBasicMaterial, Vector3 } from "three";
|
||||
import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
|
||||
const DEBUG_COLLIDER_COLORS = {
|
||||
simple: 0x87d2ff,
|
||||
terrain: 0x7be7b4,
|
||||
static: 0xffc66d,
|
||||
dynamic: 0xff8b7a
|
||||
};
|
||||
function createWireframeMaterial(color) {
|
||||
return new MeshBasicMaterial({
|
||||
color,
|
||||
wireframe: true,
|
||||
transparent: true,
|
||||
opacity: 0.85,
|
||||
depthWrite: false,
|
||||
toneMapped: false
|
||||
});
|
||||
}
|
||||
function markDebugMesh(mesh) {
|
||||
mesh.userData.shadowIgnored = true;
|
||||
mesh.userData.nonPickable = true;
|
||||
mesh.renderOrder = 3_500;
|
||||
}
|
||||
function createBoxColliderDebugMesh(collider) {
|
||||
const mesh = new Mesh(new BoxGeometry(collider.size.x, collider.size.y, collider.size.z), createWireframeMaterial(DEBUG_COLLIDER_COLORS.simple));
|
||||
mesh.position.set(collider.center.x, collider.center.y, collider.center.z);
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
function createTriMeshColliderDebugMesh(collider) {
|
||||
const geometry = new BufferGeometry();
|
||||
geometry.setAttribute("position", new Float32BufferAttribute(collider.vertices, 3));
|
||||
geometry.setIndex(Array.from(collider.indices));
|
||||
const mesh = new Mesh(geometry, createWireframeMaterial(DEBUG_COLLIDER_COLORS.static));
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
function createHeightfieldColliderDebugMesh(collider) {
|
||||
const vertices = [];
|
||||
const indices = [];
|
||||
const width = collider.maxX - collider.minX;
|
||||
const depth = collider.maxZ - collider.minZ;
|
||||
for (let zIndex = 0; zIndex < collider.cols; zIndex += 1) {
|
||||
const zLerp = collider.cols === 1 ? 0 : zIndex / (collider.cols - 1);
|
||||
const z = collider.minZ + depth * zLerp;
|
||||
for (let xIndex = 0; xIndex < collider.rows; xIndex += 1) {
|
||||
const xLerp = collider.rows === 1 ? 0 : xIndex / (collider.rows - 1);
|
||||
const x = collider.minX + width * xLerp;
|
||||
const y = collider.heights[xIndex + zIndex * collider.rows];
|
||||
vertices.push(x, y, z);
|
||||
}
|
||||
}
|
||||
for (let zIndex = 0; zIndex < collider.cols - 1; zIndex += 1) {
|
||||
for (let xIndex = 0; xIndex < collider.rows - 1; xIndex += 1) {
|
||||
const topLeft = xIndex + zIndex * collider.rows;
|
||||
const topRight = topLeft + 1;
|
||||
const bottomLeft = topLeft + collider.rows;
|
||||
const bottomRight = bottomLeft + 1;
|
||||
indices.push(topLeft, bottomLeft, bottomRight, topLeft, bottomRight, topRight);
|
||||
}
|
||||
}
|
||||
const geometry = new BufferGeometry();
|
||||
geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
|
||||
geometry.setIndex(indices);
|
||||
const mesh = new Mesh(geometry, createWireframeMaterial(DEBUG_COLLIDER_COLORS.terrain));
|
||||
markDebugMesh(mesh);
|
||||
return mesh;
|
||||
}
|
||||
function createCompoundColliderDebugGroup(collider) {
|
||||
const group = new Group();
|
||||
for (const piece of collider.pieces) {
|
||||
const points = [];
|
||||
for (let index = 0; index < piece.points.length; index += 3) {
|
||||
points.push(new Vector3(piece.points[index], piece.points[index + 1], piece.points[index + 2]));
|
||||
}
|
||||
const mesh = new Mesh(new ConvexGeometry(points), createWireframeMaterial(DEBUG_COLLIDER_COLORS.dynamic));
|
||||
markDebugMesh(mesh);
|
||||
group.add(mesh);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
export function createModelColliderDebugGroup(collider) {
|
||||
const group = new Group();
|
||||
switch (collider.kind) {
|
||||
case "box":
|
||||
group.add(createBoxColliderDebugMesh(collider));
|
||||
break;
|
||||
case "trimesh":
|
||||
group.add(createTriMeshColliderDebugMesh(collider));
|
||||
break;
|
||||
case "heightfield":
|
||||
group.add(createHeightfieldColliderDebugMesh(collider));
|
||||
break;
|
||||
case "compound":
|
||||
group.add(createCompoundColliderDebugGroup(collider));
|
||||
break;
|
||||
}
|
||||
group.userData.nonPickable = true;
|
||||
return group;
|
||||
}
|
||||
function disposeMaterial(material) {
|
||||
if (Array.isArray(material)) {
|
||||
for (const item of material) {
|
||||
item.dispose();
|
||||
}
|
||||
return;
|
||||
}
|
||||
material.dispose();
|
||||
}
|
||||
export function disposeModelColliderDebugGroup(group) {
|
||||
group.traverse((object) => {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return;
|
||||
}
|
||||
maybeMesh.geometry.dispose();
|
||||
disposeMaterial(maybeMesh.material);
|
||||
});
|
||||
}
|
||||
419
src/geometry/model-instance-collider-generation.js
Normal file
419
src/geometry/model-instance-collider-generation.js
Normal file
@@ -0,0 +1,419 @@
|
||||
import { Euler, Group, MathUtils, Matrix4, Mesh, Quaternion, Vector3 } from "three";
|
||||
const TERRAIN_GRID_EPSILON = 1e-4;
|
||||
const DYNAMIC_TRIANGLE_TARGET = 48;
|
||||
const DYNAMIC_SPLIT_DEPTH_LIMIT = 3;
|
||||
export class ModelColliderGenerationError extends Error {
|
||||
code;
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.name = "ModelColliderGenerationError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
function cloneVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function vector3ToVec3(vector) {
|
||||
return {
|
||||
x: vector.x,
|
||||
y: vector.y,
|
||||
z: vector.z
|
||||
};
|
||||
}
|
||||
function createBounds(min, max) {
|
||||
return {
|
||||
min: vector3ToVec3(min),
|
||||
max: vector3ToVec3(max)
|
||||
};
|
||||
}
|
||||
function createModelTransform(modelInstance) {
|
||||
return {
|
||||
position: cloneVec3(modelInstance.position),
|
||||
rotationDegrees: cloneVec3(modelInstance.rotationDegrees),
|
||||
scale: cloneVec3(modelInstance.scale)
|
||||
};
|
||||
}
|
||||
function createModelTransformMatrix(modelInstance) {
|
||||
const rotation = new Euler(MathUtils.degToRad(modelInstance.rotationDegrees.x), MathUtils.degToRad(modelInstance.rotationDegrees.y), MathUtils.degToRad(modelInstance.rotationDegrees.z), "XYZ");
|
||||
const quaternion = new Quaternion().setFromEuler(rotation);
|
||||
return new Matrix4().compose(new Vector3(modelInstance.position.x, modelInstance.position.y, modelInstance.position.z), quaternion, new Vector3(modelInstance.scale.x, modelInstance.scale.y, modelInstance.scale.z));
|
||||
}
|
||||
function computeBoundsFromPoints(points) {
|
||||
const min = new Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||
const max = new Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||
let hasPoint = false;
|
||||
for (const point of points) {
|
||||
hasPoint = true;
|
||||
min.min(point);
|
||||
max.max(point);
|
||||
}
|
||||
if (!hasPoint) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", "The selected model does not contain any collision-capable geometry.");
|
||||
}
|
||||
return createBounds(min, max);
|
||||
}
|
||||
function computeBoundsFromFloat32Points(points) {
|
||||
if (points.length < 3) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", "The selected model does not contain any collision-capable geometry.");
|
||||
}
|
||||
const min = new Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||
const max = new Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||
for (let index = 0; index < points.length; index += 3) {
|
||||
min.x = Math.min(min.x, points[index]);
|
||||
min.y = Math.min(min.y, points[index + 1]);
|
||||
min.z = Math.min(min.z, points[index + 2]);
|
||||
max.x = Math.max(max.x, points[index]);
|
||||
max.y = Math.max(max.y, points[index + 1]);
|
||||
max.z = Math.max(max.z, points[index + 2]);
|
||||
}
|
||||
return createBounds(min, max);
|
||||
}
|
||||
function computeWorldBoundsFromLocalBox(localBounds, modelMatrix) {
|
||||
const min = localBounds.min;
|
||||
const max = localBounds.max;
|
||||
const corners = [
|
||||
new Vector3(min.x, min.y, min.z),
|
||||
new Vector3(min.x, min.y, max.z),
|
||||
new Vector3(min.x, max.y, min.z),
|
||||
new Vector3(min.x, max.y, max.z),
|
||||
new Vector3(max.x, min.y, min.z),
|
||||
new Vector3(max.x, min.y, max.z),
|
||||
new Vector3(max.x, max.y, min.z),
|
||||
new Vector3(max.x, max.y, max.z)
|
||||
];
|
||||
return computeBoundsFromPoints(corners.map((corner) => corner.applyMatrix4(modelMatrix)));
|
||||
}
|
||||
function readIndexedVertex(position, index, matrix) {
|
||||
return new Vector3(position.getX(index), position.getY(index), position.getZ(index)).applyMatrix4(matrix);
|
||||
}
|
||||
function getMeshGeometry(object) {
|
||||
const maybeMesh = object;
|
||||
if (maybeMesh.isMesh !== true) {
|
||||
return null;
|
||||
}
|
||||
return maybeMesh.geometry;
|
||||
}
|
||||
function collectMeshTriangleClusters(template) {
|
||||
template.updateMatrixWorld(true);
|
||||
const clusters = [];
|
||||
template.traverse((object) => {
|
||||
const geometry = getMeshGeometry(object);
|
||||
if (geometry === null) {
|
||||
return;
|
||||
}
|
||||
const position = geometry.getAttribute("position");
|
||||
if (position === undefined || position.itemSize < 3 || position.count < 3) {
|
||||
return;
|
||||
}
|
||||
const matrix = object.matrixWorld;
|
||||
const index = geometry.getIndex();
|
||||
const triangles = [];
|
||||
if (index === null) {
|
||||
for (let vertexIndex = 0; vertexIndex <= position.count - 3; vertexIndex += 3) {
|
||||
triangles.push({
|
||||
a: readIndexedVertex(position, vertexIndex, matrix),
|
||||
b: readIndexedVertex(position, vertexIndex + 1, matrix),
|
||||
c: readIndexedVertex(position, vertexIndex + 2, matrix)
|
||||
});
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (let triangleIndex = 0; triangleIndex <= index.count - 3; triangleIndex += 3) {
|
||||
triangles.push({
|
||||
a: readIndexedVertex(position, index.getX(triangleIndex), matrix),
|
||||
b: readIndexedVertex(position, index.getX(triangleIndex + 1), matrix),
|
||||
c: readIndexedVertex(position, index.getX(triangleIndex + 2), matrix)
|
||||
});
|
||||
}
|
||||
}
|
||||
if (triangles.length > 0) {
|
||||
clusters.push({
|
||||
triangles
|
||||
});
|
||||
}
|
||||
});
|
||||
return clusters;
|
||||
}
|
||||
function flattenTriangleClusters(clusters) {
|
||||
return clusters.flatMap((cluster) => cluster.triangles);
|
||||
}
|
||||
function buildTriMeshBuffers(triangles) {
|
||||
const vertices = new Float32Array(triangles.length * 9);
|
||||
const indices = new Uint32Array(triangles.length * 3);
|
||||
let vertexOffset = 0;
|
||||
for (let triangleIndex = 0; triangleIndex < triangles.length; triangleIndex += 1) {
|
||||
const triangle = triangles[triangleIndex];
|
||||
vertices[vertexOffset] = triangle.a.x;
|
||||
vertices[vertexOffset + 1] = triangle.a.y;
|
||||
vertices[vertexOffset + 2] = triangle.a.z;
|
||||
vertices[vertexOffset + 3] = triangle.b.x;
|
||||
vertices[vertexOffset + 4] = triangle.b.y;
|
||||
vertices[vertexOffset + 5] = triangle.b.z;
|
||||
vertices[vertexOffset + 6] = triangle.c.x;
|
||||
vertices[vertexOffset + 7] = triangle.c.y;
|
||||
vertices[vertexOffset + 8] = triangle.c.z;
|
||||
indices[triangleIndex * 3] = triangleIndex * 3;
|
||||
indices[triangleIndex * 3 + 1] = triangleIndex * 3 + 1;
|
||||
indices[triangleIndex * 3 + 2] = triangleIndex * 3 + 2;
|
||||
vertexOffset += 9;
|
||||
}
|
||||
return {
|
||||
vertices,
|
||||
indices
|
||||
};
|
||||
}
|
||||
function computeClusterCentroid(triangles) {
|
||||
const centroid = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
let pointCount = 0;
|
||||
for (const triangle of triangles) {
|
||||
centroid.x += triangle.a.x + triangle.b.x + triangle.c.x;
|
||||
centroid.y += triangle.a.y + triangle.b.y + triangle.c.y;
|
||||
centroid.z += triangle.a.z + triangle.b.z + triangle.c.z;
|
||||
pointCount += 3;
|
||||
}
|
||||
return {
|
||||
x: centroid.x / pointCount,
|
||||
y: centroid.y / pointCount,
|
||||
z: centroid.z / pointCount
|
||||
};
|
||||
}
|
||||
function getTriangleBounds(triangles) {
|
||||
return computeBoundsFromPoints(triangles.flatMap((triangle) => [triangle.a, triangle.b, triangle.c]));
|
||||
}
|
||||
function splitTriangleCluster(triangles, depth) {
|
||||
if (triangles.length <= DYNAMIC_TRIANGLE_TARGET || depth >= DYNAMIC_SPLIT_DEPTH_LIMIT) {
|
||||
return {
|
||||
kind: "leaf",
|
||||
triangles
|
||||
};
|
||||
}
|
||||
const bounds = getTriangleBounds(triangles);
|
||||
const size = {
|
||||
x: bounds.max.x - bounds.min.x,
|
||||
y: bounds.max.y - bounds.min.y,
|
||||
z: bounds.max.z - bounds.min.z
|
||||
};
|
||||
const splitAxis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
|
||||
const sortedTriangles = [...triangles].sort((left, right) => computeClusterCentroid([left])[splitAxis] - computeClusterCentroid([right])[splitAxis]);
|
||||
const splitIndex = Math.floor(sortedTriangles.length * 0.5);
|
||||
if (splitIndex <= 0 || splitIndex >= sortedTriangles.length) {
|
||||
return {
|
||||
kind: "leaf",
|
||||
triangles
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "split",
|
||||
left: sortedTriangles.slice(0, splitIndex),
|
||||
right: sortedTriangles.slice(splitIndex)
|
||||
};
|
||||
}
|
||||
function collectConvexHullPointClouds(cluster, depth = 0) {
|
||||
const split = splitTriangleCluster(cluster, depth);
|
||||
if (split.kind === "leaf") {
|
||||
return [dedupeTriangleClusterPoints(split.triangles)];
|
||||
}
|
||||
return [...collectConvexHullPointClouds(split.left, depth + 1), ...collectConvexHullPointClouds(split.right, depth + 1)];
|
||||
}
|
||||
function quantizeCoordinate(value) {
|
||||
return (Math.round(value / TERRAIN_GRID_EPSILON) * TERRAIN_GRID_EPSILON).toFixed(4);
|
||||
}
|
||||
function dedupeTriangleClusterPoints(triangles) {
|
||||
const pointLookup = new Map();
|
||||
for (const triangle of triangles) {
|
||||
for (const point of [triangle.a, triangle.b, triangle.c]) {
|
||||
const key = `${quantizeCoordinate(point.x)}:${quantizeCoordinate(point.y)}:${quantizeCoordinate(point.z)}`;
|
||||
if (!pointLookup.has(key)) {
|
||||
pointLookup.set(key, {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
z: point.z
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pointLookup.size < 4) {
|
||||
throw new ModelColliderGenerationError("unsupported-dynamic-model-collider", "Dynamic collision requires volumetric geometry that can form at least one convex hull.");
|
||||
}
|
||||
return new Float32Array(Array.from(pointLookup.values()).flatMap((point) => [point.x, point.y, point.z]));
|
||||
}
|
||||
function buildSimpleBoxCollider(modelInstance, asset) {
|
||||
const boundingBox = asset.metadata.boundingBox;
|
||||
if (boundingBox === null) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-bounds", `Model instance ${modelInstance.id} cannot use simple collision because the asset does not have a measurable bounding box.`);
|
||||
}
|
||||
const localBounds = createBounds(new Vector3(boundingBox.min.x, boundingBox.min.y, boundingBox.min.z), new Vector3(boundingBox.max.x, boundingBox.max.y, boundingBox.max.z));
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: modelInstance.assetId,
|
||||
mode: "simple",
|
||||
kind: "box",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
center: {
|
||||
x: (boundingBox.min.x + boundingBox.max.x) * 0.5,
|
||||
y: (boundingBox.min.y + boundingBox.max.y) * 0.5,
|
||||
z: (boundingBox.min.z + boundingBox.max.z) * 0.5
|
||||
},
|
||||
size: cloneVec3(boundingBox.size),
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
function buildTriMeshCollider(modelInstance, asset, loadedAsset) {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot build ${modelInstance.collision.mode} collision until asset geometry has loaded.`);
|
||||
}
|
||||
const triangles = flattenTriangleClusters(collectMeshTriangleClusters(loadedAsset.template));
|
||||
if (triangles.length === 0) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot use ${modelInstance.collision.mode} collision because the asset has no mesh triangles.`);
|
||||
}
|
||||
const buffers = buildTriMeshBuffers(triangles);
|
||||
const localBounds = computeBoundsFromFloat32Points(buffers.vertices);
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "static",
|
||||
kind: "trimesh",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
vertices: buffers.vertices,
|
||||
indices: buffers.indices,
|
||||
triangleCount: triangles.length,
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
function buildTerrainCollider(modelInstance, asset, loadedAsset) {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot build terrain collision until asset geometry has loaded.`);
|
||||
}
|
||||
const triangles = flattenTriangleClusters(collectMeshTriangleClusters(loadedAsset.template));
|
||||
if (triangles.length === 0) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot use terrain collision because the asset has no mesh triangles.`);
|
||||
}
|
||||
const heightLookup = new Map();
|
||||
const xValues = new Map();
|
||||
const zValues = new Map();
|
||||
for (const triangle of triangles) {
|
||||
for (const point of [triangle.a, triangle.b, triangle.c]) {
|
||||
const xKey = quantizeCoordinate(point.x);
|
||||
const zKey = quantizeCoordinate(point.z);
|
||||
const key = `${xKey}:${zKey}`;
|
||||
const previousPoint = heightLookup.get(key);
|
||||
if (previousPoint !== undefined && Math.abs(previousPoint.y - point.y) > TERRAIN_GRID_EPSILON) {
|
||||
throw new ModelColliderGenerationError("unsupported-terrain-model-collider", `Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is not a single-valued heightfield over X/Z.`);
|
||||
}
|
||||
heightLookup.set(key, {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
z: point.z
|
||||
});
|
||||
xValues.set(xKey, point.x);
|
||||
zValues.set(zKey, point.z);
|
||||
}
|
||||
}
|
||||
const sortedX = Array.from(xValues.values()).sort((left, right) => left - right);
|
||||
const sortedZ = Array.from(zValues.values()).sort((left, right) => left - right);
|
||||
if (sortedX.length < 2 || sortedZ.length < 2) {
|
||||
throw new ModelColliderGenerationError("unsupported-terrain-model-collider", `Model instance ${modelInstance.id} cannot use terrain collision because the source mesh does not form a regular X/Z grid.`);
|
||||
}
|
||||
const expectedTriangleCount = (sortedX.length - 1) * (sortedZ.length - 1) * 2;
|
||||
if (triangles.length !== expectedTriangleCount) {
|
||||
throw new ModelColliderGenerationError("unsupported-terrain-model-collider", `Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is not a clean regular-grid terrain surface.`);
|
||||
}
|
||||
const heights = new Float32Array(sortedX.length * sortedZ.length);
|
||||
for (let zIndex = 0; zIndex < sortedZ.length; zIndex += 1) {
|
||||
for (let xIndex = 0; xIndex < sortedX.length; xIndex += 1) {
|
||||
const key = `${quantizeCoordinate(sortedX[xIndex])}:${quantizeCoordinate(sortedZ[zIndex])}`;
|
||||
const point = heightLookup.get(key);
|
||||
if (point === undefined) {
|
||||
throw new ModelColliderGenerationError("unsupported-terrain-model-collider", `Model instance ${modelInstance.id} cannot use terrain collision because the source mesh is missing one or more regular-grid height samples.`);
|
||||
}
|
||||
heights[xIndex + zIndex * sortedX.length] = point.y;
|
||||
}
|
||||
}
|
||||
const localBounds = computeBoundsFromPoints(Array.from(heightLookup.values(), (point) => new Vector3(point.x, point.y, point.z)));
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "terrain",
|
||||
kind: "heightfield",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
rows: sortedX.length,
|
||||
cols: sortedZ.length,
|
||||
heights,
|
||||
minX: sortedX[0],
|
||||
maxX: sortedX.at(-1) ?? sortedX[0],
|
||||
minZ: sortedZ[0],
|
||||
maxZ: sortedZ.at(-1) ?? sortedZ[0],
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
function buildDynamicCollider(modelInstance, asset, loadedAsset) {
|
||||
if (loadedAsset === undefined) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot build dynamic collision until asset geometry has loaded.`);
|
||||
}
|
||||
const triangleClusters = collectMeshTriangleClusters(loadedAsset.template);
|
||||
if (triangleClusters.length === 0) {
|
||||
throw new ModelColliderGenerationError("missing-model-collider-geometry", `Model instance ${modelInstance.id} cannot use dynamic collision because the asset has no mesh triangles.`);
|
||||
}
|
||||
const pieces = triangleClusters
|
||||
.flatMap((cluster) => collectConvexHullPointClouds(cluster.triangles))
|
||||
.map((points, index) => ({
|
||||
id: `${modelInstance.id}-piece-${index + 1}`,
|
||||
points,
|
||||
localBounds: computeBoundsFromFloat32Points(points)
|
||||
}));
|
||||
if (pieces.length === 0) {
|
||||
throw new ModelColliderGenerationError("unsupported-dynamic-model-collider", `Model instance ${modelInstance.id} could not derive any convex pieces for dynamic collision.`);
|
||||
}
|
||||
const localBounds = computeBoundsFromPoints(pieces.flatMap((piece) => {
|
||||
const points = [];
|
||||
for (let pointIndex = 0; pointIndex < piece.points.length; pointIndex += 3) {
|
||||
points.push(new Vector3(piece.points[pointIndex], piece.points[pointIndex + 1], piece.points[pointIndex + 2]));
|
||||
}
|
||||
return points;
|
||||
}));
|
||||
return {
|
||||
source: "modelInstance",
|
||||
instanceId: modelInstance.id,
|
||||
assetId: asset.id,
|
||||
mode: "dynamic",
|
||||
kind: "compound",
|
||||
visible: modelInstance.collision.visible,
|
||||
transform: createModelTransform(modelInstance),
|
||||
pieces,
|
||||
decomposition: "spatial-bisect",
|
||||
runtimeBehavior: "fixedQueryOnly",
|
||||
localBounds,
|
||||
worldBounds: computeWorldBoundsFromLocalBox(localBounds, createModelTransformMatrix(modelInstance))
|
||||
};
|
||||
}
|
||||
export function buildGeneratedModelCollider(modelInstance, asset, loadedAsset) {
|
||||
switch (modelInstance.collision.mode) {
|
||||
case "none":
|
||||
return null;
|
||||
case "simple":
|
||||
return buildSimpleBoxCollider(modelInstance, asset);
|
||||
case "static":
|
||||
return buildTriMeshCollider(modelInstance, asset, loadedAsset);
|
||||
case "terrain":
|
||||
return buildTerrainCollider(modelInstance, asset, loadedAsset);
|
||||
case "dynamic":
|
||||
return buildDynamicCollider(modelInstance, asset, loadedAsset);
|
||||
}
|
||||
}
|
||||
189
src/interactions/interaction-links.js
Normal file
189
src/interactions/interaction-links.js
Normal file
@@ -0,0 +1,189 @@
|
||||
import { createOpaqueId } from "../core/ids";
|
||||
export const INTERACTION_TRIGGER_KINDS = ["enter", "exit", "click"];
|
||||
function assertNonEmptyString(value, label) {
|
||||
if (value.trim().length === 0) {
|
||||
throw new Error(`${label} must be non-empty.`);
|
||||
}
|
||||
}
|
||||
function cloneAction(action) {
|
||||
switch (action.type) {
|
||||
case "teleportPlayer":
|
||||
return {
|
||||
type: "teleportPlayer",
|
||||
targetEntityId: action.targetEntityId
|
||||
};
|
||||
case "toggleVisibility":
|
||||
return {
|
||||
type: "toggleVisibility",
|
||||
targetBrushId: action.targetBrushId,
|
||||
visible: action.visible
|
||||
};
|
||||
case "playAnimation":
|
||||
return {
|
||||
type: "playAnimation",
|
||||
targetModelInstanceId: action.targetModelInstanceId,
|
||||
clipName: action.clipName,
|
||||
loop: action.loop
|
||||
};
|
||||
case "stopAnimation":
|
||||
return {
|
||||
type: "stopAnimation",
|
||||
targetModelInstanceId: action.targetModelInstanceId
|
||||
};
|
||||
case "playSound":
|
||||
return {
|
||||
type: "playSound",
|
||||
targetSoundEmitterId: action.targetSoundEmitterId
|
||||
};
|
||||
case "stopSound":
|
||||
return {
|
||||
type: "stopSound",
|
||||
targetSoundEmitterId: action.targetSoundEmitterId
|
||||
};
|
||||
}
|
||||
}
|
||||
export function isInteractionTriggerKind(value) {
|
||||
return value === "enter" || value === "exit" || value === "click";
|
||||
}
|
||||
export function createTeleportPlayerInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetEntityId, "Teleport target entity id");
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "teleportPlayer",
|
||||
targetEntityId: options.targetEntityId
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createToggleVisibilityInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetBrushId, "Visibility target brush id");
|
||||
if (options.visible !== undefined && typeof options.visible !== "boolean") {
|
||||
throw new Error("Visibility action visible must be a boolean when authored.");
|
||||
}
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "toggleVisibility",
|
||||
targetBrushId: options.targetBrushId,
|
||||
visible: options.visible
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createPlayAnimationInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetModelInstanceId, "Play animation target model instance id");
|
||||
assertNonEmptyString(options.clipName, "Play animation clip name");
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "playAnimation",
|
||||
targetModelInstanceId: options.targetModelInstanceId,
|
||||
clipName: options.clipName,
|
||||
loop: options.loop
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createStopAnimationInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetModelInstanceId, "Stop animation target model instance id");
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "stopAnimation",
|
||||
targetModelInstanceId: options.targetModelInstanceId
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createPlaySoundInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetSoundEmitterId, "Play sound target sound emitter id");
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "playSound",
|
||||
targetSoundEmitterId: options.targetSoundEmitterId
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createStopSoundInteractionLink(options) {
|
||||
assertNonEmptyString(options.sourceEntityId, "Interaction source entity id");
|
||||
assertNonEmptyString(options.targetSoundEmitterId, "Stop sound target sound emitter id");
|
||||
return {
|
||||
id: options.id ?? createOpaqueId("interaction-link"),
|
||||
sourceEntityId: options.sourceEntityId,
|
||||
trigger: options.trigger ?? "enter",
|
||||
action: {
|
||||
type: "stopSound",
|
||||
targetSoundEmitterId: options.targetSoundEmitterId
|
||||
}
|
||||
};
|
||||
}
|
||||
export function cloneInteractionLink(link) {
|
||||
return {
|
||||
id: link.id,
|
||||
sourceEntityId: link.sourceEntityId,
|
||||
trigger: link.trigger,
|
||||
action: cloneAction(link.action)
|
||||
};
|
||||
}
|
||||
export function areInteractionLinksEqual(left, right) {
|
||||
if (left.id !== right.id || left.sourceEntityId !== right.sourceEntityId || left.trigger !== right.trigger) {
|
||||
return false;
|
||||
}
|
||||
if (left.action.type !== right.action.type) {
|
||||
return false;
|
||||
}
|
||||
switch (left.action.type) {
|
||||
case "teleportPlayer":
|
||||
return left.action.targetEntityId === right.action.targetEntityId;
|
||||
case "toggleVisibility":
|
||||
return (left.action.targetBrushId === right.action.targetBrushId &&
|
||||
left.action.visible === right.action.visible);
|
||||
case "playAnimation":
|
||||
return (left.action.targetModelInstanceId === right.action.targetModelInstanceId &&
|
||||
left.action.clipName === right.action.clipName &&
|
||||
left.action.loop === right.action.loop);
|
||||
case "stopAnimation":
|
||||
return left.action.targetModelInstanceId === right.action.targetModelInstanceId;
|
||||
case "playSound":
|
||||
return left.action.targetSoundEmitterId === right.action.targetSoundEmitterId;
|
||||
case "stopSound":
|
||||
return left.action.targetSoundEmitterId === right.action.targetSoundEmitterId;
|
||||
default: {
|
||||
// Exhaustive check — TypeScript should never reach here
|
||||
const _exhaustive = left.action;
|
||||
void _exhaustive;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
export function cloneInteractionLinkRegistry(links) {
|
||||
return Object.fromEntries(Object.entries(links).map(([linkId, link]) => [linkId, cloneInteractionLink(link)]));
|
||||
}
|
||||
export function compareInteractionLinks(left, right) {
|
||||
if (left.sourceEntityId !== right.sourceEntityId) {
|
||||
return left.sourceEntityId.localeCompare(right.sourceEntityId);
|
||||
}
|
||||
if (left.trigger !== right.trigger) {
|
||||
return left.trigger.localeCompare(right.trigger);
|
||||
}
|
||||
return left.id.localeCompare(right.id);
|
||||
}
|
||||
export function getInteractionLinks(links) {
|
||||
return Object.values(links).sort(compareInteractionLinks);
|
||||
}
|
||||
export function getInteractionLinksForSource(links, sourceEntityId) {
|
||||
return getInteractionLinks(links).filter((link) => link.sourceEntityId === sourceEntityId);
|
||||
}
|
||||
23
src/main.js
Normal file
23
src/main.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { App } from "./app/App";
|
||||
import "./app/app.css";
|
||||
import { createEditorStore } from "./app/editor-store";
|
||||
import { getBrowserStorageAccess, loadOrCreateSceneDocument } from "./serialization/local-draft-storage";
|
||||
const rootElement = document.getElementById("root");
|
||||
if (rootElement === null) {
|
||||
throw new Error("Expected #root element to bootstrap the editor.");
|
||||
}
|
||||
const storageAccess = getBrowserStorageAccess();
|
||||
const bootstrapResult = loadOrCreateSceneDocument(storageAccess.storage);
|
||||
const editorStore = createEditorStore({
|
||||
initialDocument: bootstrapResult.document,
|
||||
initialViewportLayoutState: bootstrapResult.viewportLayoutState ?? undefined,
|
||||
storage: storageAccess.storage
|
||||
});
|
||||
const initialStatusMessage = [storageAccess.diagnostic, bootstrapResult.diagnostic].filter(Boolean).join(" ") || undefined;
|
||||
if (import.meta.env.DEV) {
|
||||
window.__webeditor3dEditorStore = editorStore;
|
||||
}
|
||||
ReactDOM.createRoot(rootElement).render(_jsx(React.StrictMode, { children: _jsx(App, { store: editorStore, initialStatusMessage: initialStatusMessage }) }));
|
||||
@@ -15,7 +15,7 @@ if (rootElement === null) {
|
||||
const storageAccess = getBrowserStorageAccess();
|
||||
const bootstrapResult = loadOrCreateSceneDocument(storageAccess.storage);
|
||||
const editorStore = createEditorStore({
|
||||
initialDocument: bootstrapResult.document,
|
||||
initialProjectDocument: bootstrapResult.document,
|
||||
initialViewportLayoutState: bootstrapResult.viewportLayoutState ?? undefined,
|
||||
storage: storageAccess.storage
|
||||
});
|
||||
|
||||
46
src/materials/starter-material-library.js
Normal file
46
src/materials/starter-material-library.js
Normal file
@@ -0,0 +1,46 @@
|
||||
export const STARTER_MATERIAL_LIBRARY = [
|
||||
{
|
||||
id: "starter-amber-grid",
|
||||
name: "Amber Grid",
|
||||
baseColorHex: "#c79a63",
|
||||
accentColorHex: "#5f3820",
|
||||
pattern: "grid",
|
||||
tags: ["starter", "wall"]
|
||||
},
|
||||
{
|
||||
id: "starter-concrete-checker",
|
||||
name: "Concrete Checker",
|
||||
baseColorHex: "#7d838c",
|
||||
accentColorHex: "#5a616a",
|
||||
pattern: "checker",
|
||||
tags: ["starter", "floor"]
|
||||
},
|
||||
{
|
||||
id: "starter-hazard-stripe",
|
||||
name: "Hazard Stripe",
|
||||
baseColorHex: "#d1a245",
|
||||
accentColorHex: "#211b16",
|
||||
pattern: "stripes",
|
||||
tags: ["starter", "warning"]
|
||||
},
|
||||
{
|
||||
id: "starter-night-diamond",
|
||||
name: "Night Diamond",
|
||||
baseColorHex: "#5a6985",
|
||||
accentColorHex: "#1f2836",
|
||||
pattern: "diamond",
|
||||
tags: ["starter", "trim"]
|
||||
}
|
||||
];
|
||||
export function cloneMaterialDef(material) {
|
||||
return {
|
||||
...material,
|
||||
tags: [...material.tags]
|
||||
};
|
||||
}
|
||||
export function cloneMaterialRegistry(materials) {
|
||||
return Object.fromEntries(Object.entries(materials).map(([materialId, material]) => [materialId, cloneMaterialDef(material)]));
|
||||
}
|
||||
export function createStarterMaterialRegistry() {
|
||||
return Object.fromEntries(STARTER_MATERIAL_LIBRARY.map((material) => [material.id, cloneMaterialDef(material)]));
|
||||
}
|
||||
73
src/materials/starter-material-textures.js
Normal file
73
src/materials/starter-material-textures.js
Normal file
@@ -0,0 +1,73 @@
|
||||
import { CanvasTexture, RepeatWrapping, SRGBColorSpace } from "three";
|
||||
export function createStarterMaterialSignature(material) {
|
||||
return `${material.baseColorHex}|${material.accentColorHex}|${material.pattern}`;
|
||||
}
|
||||
function fillMaterialPattern(context, material, size) {
|
||||
context.fillStyle = material.baseColorHex;
|
||||
context.fillRect(0, 0, size, size);
|
||||
context.strokeStyle = material.accentColorHex;
|
||||
context.fillStyle = material.accentColorHex;
|
||||
switch (material.pattern) {
|
||||
case "grid":
|
||||
context.lineWidth = Math.max(2, size / 32);
|
||||
for (let offset = 0; offset <= size; offset += size / 4) {
|
||||
context.beginPath();
|
||||
context.moveTo(offset, 0);
|
||||
context.lineTo(offset, size);
|
||||
context.stroke();
|
||||
context.beginPath();
|
||||
context.moveTo(0, offset);
|
||||
context.lineTo(size, offset);
|
||||
context.stroke();
|
||||
}
|
||||
break;
|
||||
case "checker": {
|
||||
const checkerSize = size / 4;
|
||||
for (let row = 0; row < 4; row += 1) {
|
||||
for (let column = 0; column < 4; column += 1) {
|
||||
if ((row + column) % 2 === 0) {
|
||||
context.fillRect(column * checkerSize, row * checkerSize, checkerSize, checkerSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "stripes":
|
||||
context.lineWidth = size / 6;
|
||||
for (let offset = -size; offset <= size * 2; offset += size / 3) {
|
||||
context.beginPath();
|
||||
context.moveTo(offset, size);
|
||||
context.lineTo(offset + size, 0);
|
||||
context.stroke();
|
||||
}
|
||||
break;
|
||||
case "diamond":
|
||||
context.lineWidth = Math.max(2, size / 28);
|
||||
for (let offset = -size; offset <= size; offset += size / 3) {
|
||||
context.beginPath();
|
||||
context.moveTo(size * 0.5, offset);
|
||||
context.lineTo(size - offset, size * 0.5);
|
||||
context.lineTo(size * 0.5, size - offset);
|
||||
context.lineTo(-offset, size * 0.5);
|
||||
context.closePath();
|
||||
context.stroke();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
export function createStarterMaterialTexture(material, size = 128) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
const context = canvas.getContext("2d");
|
||||
if (context === null) {
|
||||
throw new Error("2D canvas context is unavailable for starter material texture generation.");
|
||||
}
|
||||
fillMaterialPattern(context, material, size);
|
||||
const texture = new CanvasTexture(canvas);
|
||||
texture.wrapS = RepeatWrapping;
|
||||
texture.wrapT = RepeatWrapping;
|
||||
texture.colorSpace = SRGBColorSpace;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
136
src/rendering/advanced-rendering.js
Normal file
136
src/rendering/advanced-rendering.js
Normal file
@@ -0,0 +1,136 @@
|
||||
import { BasicShadowMap, DirectionalLight, HalfFloatType, Mesh, NoToneMapping, PCFShadowMap, PCFSoftShadowMap, PointLight, SpotLight, UnsignedByteType } from "three";
|
||||
import { BloomEffect, DepthOfFieldEffect, EffectComposer, EffectPass, NormalPass, RenderPass, SMAAEffect, SMAAPreset, SSAOEffect, ToneMappingEffect, ToneMappingMode } from "postprocessing";
|
||||
const AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE = 0.15;
|
||||
const MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.02;
|
||||
const MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.2;
|
||||
const MIN_AMBIENT_OCCLUSION_SAMPLES = 12;
|
||||
const COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.5;
|
||||
const DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.75;
|
||||
const DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE = 0.35;
|
||||
const COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.45;
|
||||
const DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.35;
|
||||
export function resolveBoxVolumeRenderPaths(settings) {
|
||||
if (!settings.enabled) {
|
||||
return {
|
||||
fog: "performance",
|
||||
water: "performance"
|
||||
};
|
||||
}
|
||||
return {
|
||||
fog: settings.fogPath,
|
||||
water: settings.waterPath
|
||||
};
|
||||
}
|
||||
export function getAdvancedRenderingShadowMapType(shadowType) {
|
||||
switch (shadowType) {
|
||||
case "basic":
|
||||
return BasicShadowMap;
|
||||
case "pcf":
|
||||
return PCFShadowMap;
|
||||
case "pcfSoft":
|
||||
return PCFSoftShadowMap;
|
||||
}
|
||||
}
|
||||
export function getAdvancedRenderingToneMappingMode(mode) {
|
||||
switch (mode) {
|
||||
case "none":
|
||||
return ToneMappingMode.LINEAR;
|
||||
case "linear":
|
||||
return ToneMappingMode.LINEAR;
|
||||
case "reinhard":
|
||||
return ToneMappingMode.REINHARD;
|
||||
case "cineon":
|
||||
return ToneMappingMode.CINEON;
|
||||
case "acesFilmic":
|
||||
return ToneMappingMode.ACES_FILMIC;
|
||||
}
|
||||
}
|
||||
export function configureAdvancedRenderingRenderer(renderer, settings) {
|
||||
renderer.shadowMap.enabled = settings.enabled && settings.shadows.enabled;
|
||||
renderer.shadowMap.type = getAdvancedRenderingShadowMapType(settings.shadows.type);
|
||||
renderer.toneMapping = NoToneMapping;
|
||||
renderer.toneMappingExposure = settings.toneMapping.exposure;
|
||||
}
|
||||
function clampAmbientOcclusionEffectRadius(radius) {
|
||||
return Math.min(Math.max(radius, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS), MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS);
|
||||
}
|
||||
function getAmbientOcclusionSampleCount(samples) {
|
||||
return Math.max(samples, MIN_AMBIENT_OCCLUSION_SAMPLES);
|
||||
}
|
||||
export function createAdvancedRenderingComposer(renderer, scene, camera, settings) {
|
||||
// The scene is always rendered into the composer's offscreen targets first,
|
||||
// so those targets need depth for correct visibility even when no effect samples it.
|
||||
const composer = new EffectComposer(renderer, {
|
||||
depthBuffer: true,
|
||||
stencilBuffer: false,
|
||||
multisampling: 0,
|
||||
frameBufferType: renderer.capabilities.isWebGL2 ? HalfFloatType : UnsignedByteType
|
||||
});
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const effects = [];
|
||||
if (settings.ambientOcclusion.enabled) {
|
||||
// postprocessing's internal depth-downsampling path writes zero normals unless
|
||||
// a real normal buffer is supplied, which turns SSAO into speckled noise.
|
||||
const normalPass = new NormalPass(scene, camera);
|
||||
composer.addPass(normalPass);
|
||||
const ambientOcclusionRadius = clampAmbientOcclusionEffectRadius(settings.ambientOcclusion.radius);
|
||||
const ambientOcclusionSamples = getAmbientOcclusionSampleCount(settings.ambientOcclusion.samples);
|
||||
const detailAmbientOcclusionRadius = Math.max(ambientOcclusionRadius * DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS);
|
||||
composer.addPass(new EffectPass(camera, new SSAOEffect(camera, normalPass.texture, {
|
||||
depthAwareUpsampling: true,
|
||||
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
|
||||
resolutionScale: COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
|
||||
samples: ambientOcclusionSamples,
|
||||
radius: ambientOcclusionRadius,
|
||||
intensity: settings.ambientOcclusion.intensity * COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE
|
||||
}), new SSAOEffect(camera, normalPass.texture, {
|
||||
depthAwareUpsampling: true,
|
||||
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
|
||||
resolutionScale: DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
|
||||
samples: ambientOcclusionSamples,
|
||||
radius: detailAmbientOcclusionRadius,
|
||||
intensity: settings.ambientOcclusion.intensity * DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE
|
||||
})));
|
||||
}
|
||||
if (settings.bloom.enabled) {
|
||||
effects.push(new BloomEffect({
|
||||
intensity: settings.bloom.intensity,
|
||||
luminanceThreshold: settings.bloom.threshold,
|
||||
radius: settings.bloom.radius
|
||||
}));
|
||||
}
|
||||
if (settings.depthOfField.enabled) {
|
||||
effects.push(new DepthOfFieldEffect(camera, {
|
||||
focusDistance: settings.depthOfField.focusDistance,
|
||||
focalLength: settings.depthOfField.focalLength,
|
||||
bokehScale: settings.depthOfField.bokehScale
|
||||
}));
|
||||
}
|
||||
effects.push(new ToneMappingEffect({
|
||||
mode: getAdvancedRenderingToneMappingMode(settings.toneMapping.mode)
|
||||
}));
|
||||
effects.push(new SMAAEffect({
|
||||
preset: SMAAPreset.MEDIUM
|
||||
}));
|
||||
composer.addPass(new EffectPass(camera, ...effects));
|
||||
return composer;
|
||||
}
|
||||
export function applyAdvancedRenderingRenderableShadowFlags(root, enabled) {
|
||||
root.traverse((object) => {
|
||||
if (object.isMesh === true && object.userData.shadowIgnored !== true) {
|
||||
const mesh = object;
|
||||
mesh.castShadow = enabled;
|
||||
mesh.receiveShadow = enabled;
|
||||
}
|
||||
});
|
||||
}
|
||||
export function applyAdvancedRenderingLightShadowFlags(root, settings) {
|
||||
const shadowEnabled = settings.enabled && settings.shadows.enabled;
|
||||
root.traverse((object) => {
|
||||
if (object instanceof DirectionalLight || object instanceof PointLight || object instanceof SpotLight) {
|
||||
object.castShadow = shadowEnabled;
|
||||
object.shadow.bias = settings.shadows.bias;
|
||||
object.shadow.mapSize.set(settings.shadows.mapSize, settings.shadows.mapSize);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
DepthOfFieldEffect,
|
||||
EffectComposer,
|
||||
EffectPass,
|
||||
NormalPass,
|
||||
RenderPass,
|
||||
SMAAEffect,
|
||||
SMAAPreset,
|
||||
@@ -30,10 +31,40 @@ import {
|
||||
|
||||
import type {
|
||||
AdvancedRenderingSettings,
|
||||
BoxVolumeRenderPath,
|
||||
AdvancedRenderingShadowType,
|
||||
AdvancedRenderingToneMappingMode
|
||||
} from "../document/world-settings";
|
||||
|
||||
const AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE = 0.15;
|
||||
const MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.02;
|
||||
const MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS = 0.2;
|
||||
const MIN_AMBIENT_OCCLUSION_SAMPLES = 12;
|
||||
const COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.5;
|
||||
const DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE = 0.75;
|
||||
const DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE = 0.35;
|
||||
const COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.45;
|
||||
const DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE = 0.35;
|
||||
|
||||
export interface ResolvedBoxVolumeRenderPaths {
|
||||
fog: BoxVolumeRenderPath;
|
||||
water: BoxVolumeRenderPath;
|
||||
}
|
||||
|
||||
export function resolveBoxVolumeRenderPaths(settings: AdvancedRenderingSettings): ResolvedBoxVolumeRenderPaths {
|
||||
if (!settings.enabled) {
|
||||
return {
|
||||
fog: "performance",
|
||||
water: "performance"
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
fog: settings.fogPath,
|
||||
water: settings.waterPath
|
||||
};
|
||||
}
|
||||
|
||||
export function getAdvancedRenderingShadowMapType(shadowType: AdvancedRenderingShadowType) {
|
||||
switch (shadowType) {
|
||||
case "basic":
|
||||
@@ -67,28 +98,66 @@ export function configureAdvancedRenderingRenderer(renderer: WebGLRenderer, sett
|
||||
renderer.toneMappingExposure = settings.toneMapping.exposure;
|
||||
}
|
||||
|
||||
function clampAmbientOcclusionEffectRadius(radius: number) {
|
||||
return Math.min(Math.max(radius, MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS), MAX_AMBIENT_OCCLUSION_EFFECT_RADIUS);
|
||||
}
|
||||
|
||||
function getAmbientOcclusionSampleCount(samples: number) {
|
||||
return Math.max(samples, MIN_AMBIENT_OCCLUSION_SAMPLES);
|
||||
}
|
||||
|
||||
export function createAdvancedRenderingComposer(
|
||||
renderer: WebGLRenderer,
|
||||
scene: Scene,
|
||||
camera: PerspectiveCamera,
|
||||
settings: AdvancedRenderingSettings
|
||||
): EffectComposer {
|
||||
// The scene is always rendered into the composer's offscreen targets first,
|
||||
// so those targets need depth for correct visibility even when no effect samples it.
|
||||
const composer = new EffectComposer(renderer, {
|
||||
depthBuffer: true,
|
||||
stencilBuffer: false,
|
||||
multisampling: 0,
|
||||
frameBufferType: renderer.capabilities.isWebGL2 ? HalfFloatType : UnsignedByteType
|
||||
});
|
||||
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
|
||||
const effects: Array<SSAOEffect | BloomEffect | DepthOfFieldEffect | ToneMappingEffect | SMAAEffect> = [];
|
||||
const effects: Array<BloomEffect | DepthOfFieldEffect | ToneMappingEffect | SMAAEffect> = [];
|
||||
|
||||
if (settings.ambientOcclusion.enabled) {
|
||||
effects.push(
|
||||
new SSAOEffect(camera, undefined, {
|
||||
samples: settings.ambientOcclusion.samples,
|
||||
radius: settings.ambientOcclusion.radius,
|
||||
intensity: settings.ambientOcclusion.intensity
|
||||
})
|
||||
// postprocessing's internal depth-downsampling path writes zero normals unless
|
||||
// a real normal buffer is supplied, which turns SSAO into speckled noise.
|
||||
const normalPass = new NormalPass(scene, camera);
|
||||
composer.addPass(normalPass);
|
||||
|
||||
const ambientOcclusionRadius = clampAmbientOcclusionEffectRadius(settings.ambientOcclusion.radius);
|
||||
const ambientOcclusionSamples = getAmbientOcclusionSampleCount(settings.ambientOcclusion.samples);
|
||||
const detailAmbientOcclusionRadius = Math.max(
|
||||
ambientOcclusionRadius * DETAIL_AMBIENT_OCCLUSION_RADIUS_SCALE,
|
||||
MIN_AMBIENT_OCCLUSION_EFFECT_RADIUS
|
||||
);
|
||||
|
||||
composer.addPass(
|
||||
new EffectPass(
|
||||
camera,
|
||||
new SSAOEffect(camera, normalPass.texture, {
|
||||
depthAwareUpsampling: true,
|
||||
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
|
||||
resolutionScale: COARSE_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
|
||||
samples: ambientOcclusionSamples,
|
||||
radius: ambientOcclusionRadius,
|
||||
intensity: settings.ambientOcclusion.intensity * COARSE_AMBIENT_OCCLUSION_INTENSITY_SCALE
|
||||
}),
|
||||
new SSAOEffect(camera, normalPass.texture, {
|
||||
depthAwareUpsampling: true,
|
||||
luminanceInfluence: AMBIENT_OCCLUSION_LUMINANCE_INFLUENCE,
|
||||
resolutionScale: DETAIL_AMBIENT_OCCLUSION_RESOLUTION_SCALE,
|
||||
samples: ambientOcclusionSamples,
|
||||
radius: detailAmbientOcclusionRadius,
|
||||
intensity: settings.ambientOcclusion.intensity * DETAIL_AMBIENT_OCCLUSION_INTENSITY_SCALE
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
202
src/rendering/fog-material.js
Normal file
202
src/rendering/fog-material.js
Normal file
@@ -0,0 +1,202 @@
|
||||
import { BackSide, Color, ShaderMaterial, UniformsLib, UniformsUtils, Vector3 } from "three";
|
||||
const MIN_FOG_HALF_SIZE = 0.05;
|
||||
export function createFogQualityMaterial(options) {
|
||||
const halfSize = new Vector3(Math.max(MIN_FOG_HALF_SIZE, options.halfSize.x), Math.max(MIN_FOG_HALF_SIZE, options.halfSize.y), Math.max(MIN_FOG_HALF_SIZE, options.halfSize.z));
|
||||
const minHalfExtent = Math.min(halfSize.x, halfSize.y, halfSize.z);
|
||||
const padding = Math.max(0, Math.min(options.padding, minHalfExtent * 0.82));
|
||||
const animationUniform = { value: options.time };
|
||||
const uniforms = UniformsUtils.clone(UniformsLib.fog);
|
||||
uniforms["time"] = animationUniform;
|
||||
uniforms["volumeFogColor"] = { value: new Color(options.colorHex) };
|
||||
uniforms["volumeFogDensity"] = { value: Math.max(0, options.density) };
|
||||
uniforms["volumeHalfSize"] = { value: halfSize };
|
||||
uniforms["volumePadding"] = { value: padding };
|
||||
uniforms["opacityMultiplier"] = { value: Math.max(0.6, Math.min(1.5, options.opacityMultiplier ?? 1)) };
|
||||
uniforms["colorLift"] = { value: Math.max(0, Math.min(0.22, options.colorLift ?? 0)) };
|
||||
uniforms["localCameraPosition"] = { value: new Vector3() };
|
||||
const vertexShader = /* glsl */ `
|
||||
varying vec3 vLocalPosition;
|
||||
#include <fog_pars_vertex>
|
||||
|
||||
void main() {
|
||||
vLocalPosition = position;
|
||||
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
|
||||
vec4 mvPosition = viewMatrix * worldPosition;
|
||||
gl_Position = projectionMatrix * mvPosition;
|
||||
#include <fog_vertex>
|
||||
}
|
||||
`;
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform vec3 volumeFogColor;
|
||||
uniform float volumeFogDensity;
|
||||
uniform vec3 volumeHalfSize;
|
||||
uniform float volumePadding;
|
||||
uniform float opacityMultiplier;
|
||||
uniform float colorLift;
|
||||
uniform float time;
|
||||
uniform vec3 localCameraPosition;
|
||||
|
||||
varying vec3 vLocalPosition;
|
||||
#include <fog_pars_fragment>
|
||||
|
||||
#define FOG_STEPS 10
|
||||
|
||||
float hash13(vec3 point) {
|
||||
point = fract(point * 0.1031);
|
||||
point += dot(point, point.yzx + 33.33);
|
||||
return fract((point.x + point.y) * point.z);
|
||||
}
|
||||
|
||||
float noise3(vec3 point) {
|
||||
vec3 cell = floor(point);
|
||||
vec3 local = fract(point);
|
||||
vec3 smoothLocal = local * local * (3.0 - 2.0 * local);
|
||||
|
||||
float n000 = hash13(cell + vec3(0.0, 0.0, 0.0));
|
||||
float n100 = hash13(cell + vec3(1.0, 0.0, 0.0));
|
||||
float n010 = hash13(cell + vec3(0.0, 1.0, 0.0));
|
||||
float n110 = hash13(cell + vec3(1.0, 1.0, 0.0));
|
||||
float n001 = hash13(cell + vec3(0.0, 0.0, 1.0));
|
||||
float n101 = hash13(cell + vec3(1.0, 0.0, 1.0));
|
||||
float n011 = hash13(cell + vec3(0.0, 1.0, 1.0));
|
||||
float n111 = hash13(cell + vec3(1.0, 1.0, 1.0));
|
||||
|
||||
float nx00 = mix(n000, n100, smoothLocal.x);
|
||||
float nx10 = mix(n010, n110, smoothLocal.x);
|
||||
float nx01 = mix(n001, n101, smoothLocal.x);
|
||||
float nx11 = mix(n011, n111, smoothLocal.x);
|
||||
float nxy0 = mix(nx00, nx10, smoothLocal.y);
|
||||
float nxy1 = mix(nx01, nx11, smoothLocal.y);
|
||||
return mix(nxy0, nxy1, smoothLocal.z);
|
||||
}
|
||||
|
||||
float fbm(vec3 point) {
|
||||
float value = 0.0;
|
||||
float amplitude = 0.5;
|
||||
|
||||
for (int octave = 0; octave < 3; octave += 1) {
|
||||
value += amplitude * noise3(point);
|
||||
point = point * 2.04 + vec3(17.1, 31.7, 9.2);
|
||||
amplitude *= 0.5;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
vec2 intersectBox(vec3 rayOrigin, vec3 rayDirection, vec3 halfSize) {
|
||||
vec3 safeDirection = sign(rayDirection) * max(abs(rayDirection), vec3(1e-4));
|
||||
vec3 invDirection = 1.0 / safeDirection;
|
||||
vec3 t0 = (-halfSize - rayOrigin) * invDirection;
|
||||
vec3 t1 = (halfSize - rayOrigin) * invDirection;
|
||||
vec3 tMin = min(t0, t1);
|
||||
vec3 tMax = max(t0, t1);
|
||||
float nearHit = max(max(tMin.x, tMin.y), tMin.z);
|
||||
float farHit = min(min(tMax.x, tMax.y), tMax.z);
|
||||
return vec2(nearHit, farHit);
|
||||
}
|
||||
|
||||
float sampleShape(vec3 samplePosition) {
|
||||
float minHalfExtent = min(min(volumeHalfSize.x, volumeHalfSize.y), volumeHalfSize.z);
|
||||
float edgeSoftness = max(0.08, min(volumePadding + minHalfExtent * 0.16, minHalfExtent * 0.72));
|
||||
vec3 innerHalfSize = max(volumeHalfSize - vec3(edgeSoftness), vec3(minHalfExtent * 0.18));
|
||||
vec3 distanceToCore = abs(samplePosition) - innerHalfSize;
|
||||
float outsideDistance = length(max(distanceToCore, 0.0));
|
||||
float insideDistance = min(max(distanceToCore.x, max(distanceToCore.y, distanceToCore.z)), 0.0);
|
||||
float roundedBoxDistance = outsideDistance + insideDistance;
|
||||
float edgeMask = 1.0 - smoothstep(-edgeSoftness * 0.7, edgeSoftness * 1.35, roundedBoxDistance);
|
||||
|
||||
vec3 ellipsoidPosition = samplePosition / max(volumeHalfSize - vec3(edgeSoftness * 0.18), vec3(1e-3));
|
||||
float roundedMask = 1.0 - smoothstep(0.54, 1.03, length(ellipsoidPosition * vec3(0.96, 1.08, 0.96)));
|
||||
|
||||
return edgeMask * mix(0.42, 1.0, roundedMask);
|
||||
}
|
||||
|
||||
float sampleVolumeDensity(vec3 samplePosition) {
|
||||
vec3 normalizedPosition = samplePosition / max(volumeHalfSize, vec3(1e-3));
|
||||
float shape = sampleShape(samplePosition);
|
||||
|
||||
if (shape <= 1e-3) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
vec3 drift = vec3(time * 0.1, time * 0.04, -time * 0.065);
|
||||
float primary = fbm(samplePosition * 0.58 + drift);
|
||||
float secondary = fbm(samplePosition * 1.18 - drift * 1.45 + vec3(4.3, 9.7, 2.1));
|
||||
float wisps = noise3(samplePosition * 2.15 + vec3(0.0, time * 0.08, 0.0));
|
||||
float cloud = smoothstep(0.34, 0.92, primary * 0.68 + secondary * 0.24 + wisps * 0.08);
|
||||
float centerBias = 1.0 - smoothstep(0.18, 1.08, length(normalizedPosition * vec3(1.05, 0.92, 1.05)));
|
||||
float verticalBias = mix(0.9, 1.08, smoothstep(-0.75, 0.35, normalizedPosition.y));
|
||||
float carvedCloud = mix(0.42, 1.04, cloud) * mix(0.72, 1.0, centerBias);
|
||||
|
||||
return volumeFogDensity * shape * carvedCloud * verticalBias;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 rayDirection = normalize(vLocalPosition - localCameraPosition);
|
||||
vec2 hitRange = intersectBox(localCameraPosition, rayDirection, volumeHalfSize);
|
||||
float startDistance = max(hitRange.x, 0.0);
|
||||
float endDistance = hitRange.y;
|
||||
|
||||
if (endDistance <= startDistance) {
|
||||
discard;
|
||||
}
|
||||
|
||||
float rayLength = endDistance - startDistance;
|
||||
float stepLength = rayLength / float(FOG_STEPS);
|
||||
float jitter = hash13(vLocalPosition * 1.73 + vec3(time * 0.17)) - 0.5;
|
||||
float transmittance = 1.0;
|
||||
vec3 accumulatedColor = vec3(0.0);
|
||||
|
||||
for (int stepIndex = 0; stepIndex < FOG_STEPS; stepIndex += 1) {
|
||||
float sampleDistance = startDistance + (float(stepIndex) + 0.5 + jitter * 0.35) * stepLength;
|
||||
vec3 samplePosition = localCameraPosition + rayDirection * sampleDistance;
|
||||
float sampleDensity = sampleVolumeDensity(samplePosition);
|
||||
|
||||
if (sampleDensity <= 1e-4) {
|
||||
continue;
|
||||
}
|
||||
|
||||
vec3 normalizedPosition = samplePosition / max(volumeHalfSize, vec3(1e-3));
|
||||
float forwardScatter = 1.0 - abs(dot(rayDirection, normalize(samplePosition + vec3(1e-3, 2e-3, -1e-3))));
|
||||
float topLight = smoothstep(-0.2, 0.95, normalizedPosition.y);
|
||||
float coolShadow = smoothstep(0.18, 0.88, noise3(samplePosition * 0.88 - vec3(time * 0.08, 0.0, time * 0.05)));
|
||||
vec3 sampleColor = mix(volumeFogColor * 0.76, vec3(1.0), 0.06 + topLight * 0.12 + forwardScatter * 0.12);
|
||||
sampleColor = mix(sampleColor * 0.92, sampleColor, coolShadow);
|
||||
|
||||
float extinction = sampleDensity * stepLength * 1.5;
|
||||
float sampleAlpha = 1.0 - exp(-extinction);
|
||||
accumulatedColor += transmittance * sampleColor * sampleAlpha;
|
||||
transmittance *= 1.0 - sampleAlpha;
|
||||
|
||||
if (transmittance < 0.03) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
float baseAlpha = 1.0 - transmittance;
|
||||
float alpha = clamp(baseAlpha * opacityMultiplier, 0.0, 0.96);
|
||||
|
||||
if (alpha <= 0.01) {
|
||||
discard;
|
||||
}
|
||||
|
||||
vec3 color = accumulatedColor / max(baseAlpha, 1e-4);
|
||||
color = mix(color, vec3(1.0), colorLift);
|
||||
|
||||
gl_FragColor = vec4(color, alpha);
|
||||
#include <fog_fragment>
|
||||
}
|
||||
`;
|
||||
return {
|
||||
material: new ShaderMaterial({
|
||||
vertexShader,
|
||||
fragmentShader,
|
||||
uniforms,
|
||||
transparent: true,
|
||||
depthWrite: false,
|
||||
fog: true,
|
||||
side: BackSide
|
||||
}),
|
||||
animationUniform
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user