286 Commits

Author SHA1 Message Date
bbe7a14401 PlayerInventoryUI: autolistring equipments slots 2026-04-20 21:15:11 +03:00
ad521ce2b7 Update ide-helper 2026-04-19 21:41:02 +03:00
0d986dafd5 rocks: rocks update 2026-04-19 21:35:10 +03:00
f34c12c59f PlayerInventoryUI: add equipment slot overlay 2026-04-19 20:31:52 +03:00
89bc05d2cb equipment: add some armor 2026-04-19 20:31:26 +03:00
99093493c0 rocks: Change of registration of rocks 2026-04-19 19:48:04 +03:00
31d66277ae wood: Added registration of node segments for planks and timber 2026-04-18 22:41:33 +03:00
93d4b3145c Node: Added the ability to register slabs and stairs through a specific group. 2026-04-18 22:38:33 +03:00
ed9a80b2cf rocks: add chipped tautite 2026-04-18 21:44:47 +03:00
9fd665aaa5 PlayerInventoryUI: remove profiler string 2026-04-17 18:01:14 +03:00
8e09f8fa53 PlayerInventoryUI: Now you can only place items with a specific group in equipment slots. #34 2026-04-17 17:34:15 +03:00
97084c9060 equipment: create equipment mod, add test equip 2026-04-17 17:24:10 +03:00
7e46c858cc Update ide-helper 2026-04-17 17:10:44 +03:00
ac28f9e92b Update ide-helper 2026-04-17 16:55:52 +03:00
b62e19d10a Update ide-helper 2026-04-17 16:26:02 +03:00
6dba6f8c78 PlayerInventory & PlayerInventoryUI: create equip slots & draft equip tab. #34 2026-04-16 21:07:19 +03:00
0a97ef3a83 PlayerInventory & PlayerInventoryUI: Transferring inventory action handlers from Player to PlayerInventoryUI. #34 2026-04-16 20:30:10 +03:00
7661cacbfe Changing the format for writing chain-calls for FormSpecs. 2026-04-13 22:06:02 +03:00
c172198ff7 PlayerInventory & PlayerInventoryUI: adding explanatory annotations and comments to the code. #34 2026-04-13 22:00:27 +03:00
f1c82d9220 Tool: remove unnecessary code 2026-04-13 20:58:37 +03:00
b4290ad1f9 Update copyright year 2026-04-13 20:46:48 +03:00
f31277f8b0 update menu/background.png 2026-04-11 22:48:30 +03:00
0189b29257 wood: update wood blocks names, add timber textures, add log branch 2026-04-11 22:48:04 +03:00
b0aad2823a Fix merge items settings 2026-04-11 21:54:49 +03:00
76f74743ba PlayerInventory & PlayerInventoryUI: adding a compact inventory form and changing the tab switching system. #34 2026-04-10 21:44:23 +03:00
cc8f896d6e PlayerInventory & PlayerInventoryUI: rename pane -> tab. #34 2026-04-07 20:50:03 +03:00
b579418b9a wood: update sheet 2026-04-07 20:27:42 +03:00
bddcb4e36c PlayerInventory & PlayerInventoryUI: You can now specify groups as materials for primitive crafting in your inventory. #34 2026-04-04 18:00:24 +03:00
d5c6101c0f PlayerInventory & PlayerInventoryUI: remove group image animation. #34 2026-04-04 16:55:42 +03:00
b53753c6a5 HelperLib: delete Philosopher font 2026-04-04 16:54:54 +03:00
427c674103 PlayerInventory & PlayerInventoryUI: Completion of work on a sane version of the crafting menu. #34 2026-04-03 21:45:24 +03:00
91603e21f8 Table: Replacing the Voxrames version of table.join with ours 2026-04-03 21:43:43 +03:00
f5fba0b779 wood & rocks: changes to draft crafts for demonstration 2026-04-03 21:41:02 +03:00
d5b9504cc5 CraftSystem: small fix 2026-04-03 21:40:17 +03:00
a1e74978a5 BaseUI: Added support for tracking active forms 2026-04-03 21:39:19 +03:00
1dc6fb3f39 HelperLib: add Smc.getRegisteredItemByName() 2026-04-03 21:38:09 +03:00
89c52c80bc HelperLib: Smc.registerGlobalStepForEachPlayer fix 2026-04-03 21:37:39 +03:00
162f8d2639 HelperLib: events fixes 2026-04-03 21:36:55 +03:00
7af83a87d8 HelperLib: add active formspecs handler 2026-04-03 21:36:08 +03:00
0e59cf799a CraftSystem: change table.merge -> table.join 2026-04-03 19:26:16 +03:00
89de48b5a8 Table: add table.join from Voxrame 2026-04-03 19:18:54 +03:00
362d626f9b CraftSystem: add groupedCrafts 2026-04-03 18:42:18 +03:00
defd3531bc wood: add stiks, planks, bars 2026-03-30 21:25:19 +03:00
584e710d5c PlayerInventory & PlayerInventoryUI: Fixed inventory state saving 2026-03-30 21:06:09 +03:00
8a0b5785ab Added the ability to specify the number of items in primitive crafting recipes and results 2026-03-30 20:59:34 +03:00
9873e059cb Submodule: ide-helper update 2026-03-30 20:54:14 +03:00
d05af7dacc PlayerInventoryUI:Adding background textures to the crafting menu. #34 2026-03-28 18:14:01 +03:00
9ed2319b14 PlayerInventory & PlayerInventoryUI: Adding minimal functionality to the crafting pane. #34 2026-03-28 17:03:04 +03:00
d6cc39a0b2 rocks & wood: add draft crafts 2026-03-28 17:01:49 +03:00
2935c4d10b CraftSystem: minor fixes 2026-03-28 17:00:54 +03:00
Van
53801a56a8 Merge pull request 'mapgen-optimizations' (#39) from mapgen-optimizations into main
Reviewed-on: #39
2026-03-28 15:20:23 +03:00
f1610056cc Formspec: create Formspec:listNodeMetaLocation 2026-03-27 19:03:43 +03:00
914ea881a4 PlayerInventoryUI: update backgrounds textures. #34 2026-03-26 21:37:13 +03:00
cb87d16560 Remove docs directory 2026-03-21 21:28:35 +03:00
ceb35639b8 MapGen: minor refactoring 2026-03-21 21:26:27 +03:00
79df8f2f52 MapGen: a little bit more optimizations 2026-03-21 20:53:02 +03:00
44916bcd3b BaseUI: remove print() 2026-03-20 23:06:05 +03:00
3483cd650a Item: add optional rarity color in title. Close #35 2026-03-20 23:05:40 +03:00
c4104a1834 HelperLib: add craft system requires 2026-03-20 22:10:26 +03:00
e98935cf6f PlayerInventoryUI: Adding basic panes switching functionality. #34 2026-03-19 21:57:43 +03:00
338cc7a36b PlayerInventoryUI: Draft version of the player inventory and pane templates. #34 2026-03-18 22:12:01 +03:00
18f06d13d3 Formspec: minor fixes 2026-03-18 22:10:35 +03:00
e986a4c538 MapGen: There is now only one triangulation map instead of three. 2026-03-16 20:59:39 +03:00
93bda75727 Profiler: some changes 2026-03-16 20:57:37 +03:00
1531abc3e2 MapGen: Attempt to speed up generation. Some MapGen.Peak fields can now be accessed directly. Layers are now defined for the entire chunk, rather than per node. 2026-03-15 22:08:13 +03:00
a34822ed54 MapGen: find optimization. #37 2026-03-13 21:57:05 +03:00
145f65d4af Player: create PlayerInventoryUI class & change item count in hotbar (8->9). #34 2026-03-12 21:44:03 +03:00
e359c4be09 Profiler: create class and base functional. Close #36 2026-03-12 20:10:55 +03:00
c009493484 MapGen: remove space 2026-03-12 19:44:27 +03:00
fab86c0486 License fix 2 2026-03-12 19:29:24 +03:00
cb15f25d60 License fix 2026-03-12 19:11:41 +03:00
867238e11b MapGen: add large map, disable log profiler 2026-03-12 15:05:53 +03:00
df247108ef MapGen: fastgen? 2026-03-11 23:34:09 +03:00
e34fd29a4b MapGen: removing unnecessary code. Completion of work on a new triangulation method. Close #25 2026-03-10 21:14:31 +03:00
41cf4710da MapGen: small map test 2026-03-09 21:51:49 +03:00
c6573ae308 MapGen: fix patch 2026-03-09 21:16:53 +03:00
4ef2476771 MapGen: Moving triangulation outside of Lua scripts, using pre-triangulated JSON files 2026-03-09 20:07:00 +03:00
2c13e1697f Wood: some Russian localization has been added 2026-03-08 22:44:42 +03:00
7b4839e63b Item: minor item description changes 2026-03-08 22:44:06 +03:00
2813d9d5fe Add missing locale admin command. Remove auto-check missing locale` 2026-03-08 20:56:48 +03:00
652200f28c Update ide-helper 2026-03-08 20:55:06 +03:00
eeffae6852 Item: add missing localization check 2026-03-06 20:10:04 +03:00
fe3298d112 Change regular & mono fonts on Philosopher 2026-03-06 19:03:45 +03:00
7d49bbf535 MapGen: add post-processing generation in biomes. Close #30 2026-03-05 21:46:28 +03:00
efcbc909e0 CraftSystem: save counter in ModStorage. Close #32 2026-03-05 20:11:32 +03:00
17413df9c4 storages: create storages mod, move case wood -> storages, create draft chest 2026-03-05 19:47:27 +03:00
2eede05436 HelperLib: add regular & mono fonts - Stengazeta 2026-03-05 19:46:33 +03:00
b863c88838 wood: fix textures & add new wood - gi 2026-03-02 22:28:29 +03:00
692105abfa BaseUI: Clearing the context is now an optional parameter & edit /list command. close #33 2026-03-02 19:57:54 +03:00
1a6086190e wood: improved textures, adding stripped wood 2026-03-01 22:20:14 +03:00
e20c3b4ef4 rocks: add sylite pillars 2026-03-01 22:19:00 +03:00
8b55ccff72 adminCommands: update /list command 2026-02-27 21:55:34 +03:00
c7cfe26335 Tool: create tool class 2026-02-27 20:57:54 +03:00
51e6763457 HelperLib: add require methods 2026-02-27 20:34:37 +03:00
c47ab6ac3c soils: update textures 2026-02-27 20:23:35 +03:00
6fd8295500 Item: minor fixes & set default stack is 128 2026-02-27 20:23:15 +03:00
b12f890740 adminCommands: minor fixes & test shaders 2026-02-27 20:22:19 +03:00
4c90041c68 Add essences (rofl) 2026-02-27 20:21:26 +03:00
b50d642bcf Trees update 2026-02-24 21:48:42 +03:00
e0b9024458 Add leafs & fix list command 2026-02-22 22:01:22 +03:00
745eaa8569 CraftSystem: TappingStage can now require a tool with a specific group for crafting 2026-02-20 22:18:25 +03:00
b6051e5724 WorkStation add TODO 2026-02-20 22:01:53 +03:00
5c936025f1 Add craft abort support & fixes visual tappingCraftNode 2026-02-20 21:46:45 +03:00
Van
5be847bf58 Merge pull request 'CraftSystem: first working version' (#31) from craft-system into main 2026-02-18 22:30:38 +03:00
0198771c51 WorkStation: tidying up the code, adding comments 2026-02-18 22:20:27 +03:00
5272294aeb CraftSystem: end of work? 2026-02-18 22:19:42 +03:00
2eb7d04039 WorkStationUI: update 2026-02-18 22:18:30 +03:00
c70bf96734 BaseUI: add showForm & closeForm methods 2026-02-18 22:18:10 +03:00
b64c8e9350 WorkStation: update 2026-02-17 21:44:53 +03:00
319f155849 CraftSystem: ImmersiveCraftStage`: minor changes 2026-02-17 21:43:48 +03:00
ed4094d964 CraftSystem: add ImmersiveCraftCounter` 2026-02-17 21:43:00 +03:00
6b074c7a8c CraftSystem: PrimitiveCraft`: minor changes 2026-02-17 21:42:21 +03:00
00633226cf CraftSystem: TappingNode: add get_staticdata method, enable static_save` 2026-02-17 21:40:42 +03:00
6156a4bb6f rocks`: add some locale 2026-02-17 21:38:02 +03:00
b6f354f6fe Submodules: update ide-helper 2026-02-17 21:37:00 +03:00
cfc4502cb0 Item: minor chandes 2026-02-17 21:36:32 +03:00
bafe26983c BaseUI: add recive fields methods 2026-02-17 21:35:40 +03:00
7b43def5fb HelperLib: add receive fields methods 2026-02-17 21:34:56 +03:00
f4896b89ef HelperLib: minor changes immersive craft data 2026-02-17 21:34:25 +03:00
c58467f22b Submodules: update ide-helper 2026-02-14 19:27:17 +03:00
1d5f93c35a CraftSystem: minor annotation fix 2026-02-13 21:38:04 +03:00
46427f565f Submodules: update ide-helper 2026-02-13 21:35:47 +03:00
8fb4e4db00 Submodules: update ide-helper and fix mapgen annotations 2026-02-13 21:22:48 +03:00
9c56db6ac4 CtaftSystem: Bringing the system into order, adding annotations and comments, eliminating major bugs 2026-02-13 21:09:55 +03:00
15bb906df7 HelperLib: add getObjectByGUID & immersive craft data methods 2026-02-13 21:03:01 +03:00
e9818fba24 Events & Control: remove Events.registerCallback function 2026-02-13 21:01:44 +03:00
a6fa46bb96 Creature: minor annotation fixes 2026-02-13 20:58:44 +03:00
44adcf9535 Creature: create Creature.LuaEntity class 2026-02-12 21:12:27 +03:00
97292d6205 Creature: callback fixes 2026-02-12 21:11:52 +03:00
f2af5e725a Item & Node: corrections in the order of merging tables of parameters and default parameters 2026-02-12 21:10:18 +03:00
25f38d1acd BaseUI: create base UI class 2026-02-12 21:08:43 +03:00
1d43ae1255 CraftSystem: create ImmersiveCraftNode & add first immersive craft type Tapping 2026-02-09 22:35:05 +03:00
9426ac01dd Creature: minor fixes 2026-02-09 22:19:20 +03:00
21232bd1f7 Table: fix annotation table.merge 2026-02-09 22:13:41 +03:00
0c02c0045d Rename class: Entity -> Creature 2026-02-09 19:33:23 +03:00
205cbc10c2 Node: added missing empty lines at the end of files 2026-02-09 18:17:27 +03:00
660c96ab5c Entity: add getExtended method 2026-02-09 18:16:14 +03:00
ec8499ff76 Item & Node: add merge defaults defs to getExtended and getFactory 2026-02-09 18:15:22 +03:00
430ac78ea1 Submodules: update ide-helper 2026-02-08 20:38:59 +03:00
f7140fb3cc Entity: reating a wrapper class for an entity. Close #26 2026-02-08 20:26:17 +03:00
6153b053f6 Item: minor changes 2026-02-08 20:24:53 +03:00
bc03aa4ba6 Rename custom field use snake_case and _ 2026-02-08 18:42:07 +03:00
04f90a7b2d Submodules: update ide-helper 2026-02-08 16:46:44 +03:00
66380fb873 WorkStation: create WorkStation class, register test node & crafts, add work station UI 2026-02-07 22:14:07 +03:00
169dd64bce CraftSystem: minor fixes 2026-02-07 22:13:16 +03:00
613b7ead83 Submodules: update ide-helper 2026-02-07 20:35:59 +03:00
94dc3fa819 CraftSystem: rewrite system, completion of work on immersive craft 2026-02-06 18:19:38 +03:00
6c77b5a38c Class: minor fixes 2026-02-06 17:14:02 +03:00
c41ee05b55 CraftSystem: add lastline space 2026-02-06 16:53:32 +03:00
87c6e5f3f3 CraftSystem: Immersive craft part 2 2026-02-05 22:30:25 +03:00
e435b21b43 Item: Corrections to the design, added the last empty lines 2026-02-02 14:25:20 +03:00
0baa7af759 Entity: create dummy-class 2026-02-02 14:19:14 +03:00
83304bbfc1 CraftSystem: add dummy-class ImmersiveCraftStage 2026-02-02 13:59:12 +03:00
7dbd2f3be8 CraftSystem: add immersive craft handler (no realisation) 2026-02-02 13:46:06 +03:00
b41448da7b CraftSystem: add primitive craft handler 2026-02-02 13:33:12 +03:00
865f46b734 Add Item.Rarity 2026-02-01 20:51:23 +03:00
3dd28858f5 Add some rocks 2026-02-01 19:44:59 +03:00
Van
9119582ddd Обновить .gitea/pull_request_template.yml 2026-01-29 16:04:00 +03:00
Van
a12091fc93 Обновить .gitea/pull_request_template.yml 2026-01-29 16:03:28 +03:00
Van
cfadf47951 Обновить .gitea/pull_request_template.yml 2026-01-29 16:02:47 +03:00
b0fc925750 mapGenerator: lmao fix 2026-01-24 18:35:46 +03:00
e12b0d64e5 MapGen: Added check for points belonging to the triangulation area 2026-01-24 18:30:36 +03:00
efcee33a02 MapGen: Fixed map mirroring. Added an isometric grid map 2026-01-24 17:17:47 +03:00
ce778673c7 Formspec: add method chaining to elements registrations 2026-01-23 15:10:01 +03:00
5ec4bdd933 MapGen: Layer:get<Object>ByName() methods added. Add Layer:getPeakByPos(). close #20 2026-01-23 14:38:46 +03:00
6332f23bf3 Add new types rocks, add test gradient mapgen 2026-01-22 21:45:40 +03:00
966af2328a Update rocks 2026-01-22 19:26:48 +03:00
d08ee33400 Add water flowing texture 2026-01-22 17:34:59 +03:00
ba97a8f36f MapGen: minor changes 2026-01-22 14:26:18 +03:00
ef6c0d9fe6 MapGen: add getLayerByName(). close #19 2026-01-22 14:23:28 +03:00
c3bdb29852 Formspec: adding the remaining methods. close #8 2026-01-22 14:17:28 +03:00
6904090d19 Submodules: update ide-helper 2026-01-21 19:32:53 +03:00
f3c5beb341 MapGen: Moving checks for layer object uniqueness from mapgen methods to layer methods 2026-01-21 19:10:27 +03:00
fc90ae54c0 MapGen: Added the ability to limit cave generation regionally. close #15 2026-01-21 19:05:00 +03:00
0952e96452 Formspec: some fix 2026-01-21 16:23:32 +03:00
19d6637a29 Formspec: add some methods. #8 2026-01-21 16:17:32 +03:00
6fb06b7109 Table: add table.key_value_list() 2026-01-21 14:14:40 +03:00
d392414cb7 Changes in class constructors. close #18 2026-01-20 21:42:16 +03:00
8c7aaefe09 MapGen: add Region class and MapGen:pointInRegion2D. close #17 2026-01-20 21:08:34 +03:00
1d1591accc Minor start game fix 2026-01-20 19:14:41 +03:00
ec614e6080 Class: add getInstance(). MapGen: fixes :new() methods. #18 2026-01-20 19:06:53 +03:00
c32d324bfb MapGen: add getTriangleByPos2D() 2026-01-20 18:35:46 +03:00
37d759e48a MapGen: Zoning support 4/7. #17 2026-01-20 16:14:34 +03:00
4b9afcf97d Formspec: add some methods. #8 2026-01-20 14:11:22 +03:00
c9ce8e5f60 MapGenerator: canyon gen, xd 2026-01-18 21:09:52 +03:00
b7124419e7 BSubmodules update: ide-helper 2026-01-18 20:04:57 +03:00
8742b86a44 Formspec: add some methods. #8 2026-01-18 16:34:37 +03:00
79111b3cbd Fix emmylua warnings 2026-01-18 15:20:59 +03:00
087a8eee86 MapGen: remove unnecessary @diagnostic disable... 2026-01-18 12:14:07 +03:00
cb853778fe MapGen: rename some fields 2026-01-18 12:10:47 +03:00
bdd35af484 Submodules: utf8 update: fix emmylua warnings 2026-01-17 22:53:08 +03:00
882165c9e7 Test docs-parser x3 (another parser) 2026-01-17 22:11:11 +03:00
e294c34801 Test docs-parser x2 2026-01-17 21:44:29 +03:00
b6e07d04e3 Test docs-parser 2026-01-17 21:40:17 +03:00
3d03477467 Minor fixes 2026-01-16 19:37:53 +03:00
c75e06d274 Determination of triangulation. Close #16 2026-01-16 18:52:40 +03:00
6d3e9af2f8 Bump changes 2026-01-16 17:50:09 +03:00
cabe562dc4 HelperLib: add makeGradient function by ssdaniel24. #12 2026-01-15 15:18:21 +03:00
43bee3dae0 MapGen: Optimization: Added single-color triangles. Close #10 2026-01-15 14:03:37 +03:00
4f4b268d3c MapGen: Optimization: add Added detection of adjacent triangles. Close #14 2026-01-15 13:50:16 +03:00
c2b0c54236 MapGen: add load fixColor to mapgen async 2026-01-15 13:48:13 +03:00
907230e67d MapGen: fix annotations warnings 2026-01-14 17:16:18 +03:00
03ce7983eb Submodules: update submodule ide-helper 2026-01-14 17:15:15 +03:00
e81e2141a6 Math: fix annotations 2026-01-14 17:08:41 +03:00
3d0a906a59 HelperLib: create fixColorString method 2026-01-14 16:54:06 +03:00
18dbce95c0 Submodules: update submodules 2026-01-14 16:43:09 +03:00
b646a8e3e3 Edit .gitignore 2026-01-14 15:37:33 +03:00
7ec4f906c8 Submodules: update submodules 2026-01-14 15:28:35 +03:00
39dbf29ff6 Add Utf8 submodule 2026-01-14 15:25:27 +03:00
a4b1ff2ee5 Remove Utf8 submodule 2026-01-14 15:22:05 +03:00
0c5f508152 Rename API -> SYSTEM 2026-01-14 15:14:38 +03:00
50dd702e6e Move templates to .gitea directory 2026-01-14 14:44:10 +03:00
426fea3691 Add issues & prs templates 2026-01-13 21:25:23 +03:00
299dad5e11 Api: rename ApiLoader -> Api 2026-01-12 20:18:02 +03:00
0e8edc4f05 Submodules: edit url for utf8_api 2026-01-12 20:16:00 +03:00
f13a0b1273 MapGen: remove MultiNoise 2026-01-12 19:53:56 +03:00
57de1f4b42 MapGen: add annotations 2026-01-12 19:43:54 +03:00
d0eba35e8d MapGen: remove unnecessary code 2026-01-12 18:43:09 +03:00
8640e55415 MapGen: move ff2luat.lua Api->MapGen 2026-01-12 18:31:06 +03:00
84295c56c4 Added TODO: for gzip decompressing 2026-01-12 17:05:54 +03:00
eaf350e9ce Rewrote ff2luat func for using string:sub (not file:read) 2026-01-12 17:04:55 +03:00
dfd8021808 Rewrite mapgen 2026-01-10 17:12:06 +03:00
d9f9bd7a6c Separate peaks, add layer colors 2026-01-10 12:31:19 +03:00
Van
0ff45e4da1 Mapgen map from image (#3)
* Mapgen: add peaks register from image

* Fixed unsigned int bytes to number conversion

* Fixed uintb2num func for normal conversion...

* Add test map image parsing

---------

Co-authored-by: ssdaniel24 <bo7oaonteg2m@mail.ru>
2026-01-10 12:05:33 +03:00
395f45aeb9 Add stone generate on suraface 2026-01-08 12:41:47 +03:00
d9aa50fc91 Add draft /list command 2026-01-07 14:26:21 +03:00
876b24e1fe Formspec: add item image button 2026-01-07 14:26:01 +03:00
37ad60d348 Formspec: add scrollbar and minor fixes 2026-01-07 13:45:13 +03:00
bc50096293 Formspec: add scrollContainer 2026-01-07 12:53:27 +03:00
1c5038ff14 ItemFactory: change params for registerNodesByShortDef: remove titile & description params 2026-01-06 14:12:15 +03:00
562ff7d24c Submodules: update ide-helper 2026-01-06 13:23:33 +03:00
a08934c6e4 Item: add param addModName 2026-01-05 15:44:53 +03:00
6236a12ca9 Item: add titleColor & descriptionColor params 2026-01-05 15:18:12 +03:00
f7ec69bd54 minor fix 2026-01-05 15:15:42 +03:00
bf107cb167 Rename GlobalStep.lua -> globalStep.lua 2026-01-05 15:06:05 +03:00
cb49582a19 Api globalStep minor changes 2026-01-05 14:57:09 +03:00
cf4ca6f8dc Add test locale 2026-01-02 23:03:54 +03:00
2032082ba8 Added auto-completion of items title and description for localization 2026-01-02 22:31:32 +03:00
9557642805 MapGen: fix light 2026-01-02 21:36:53 +03:00
6db2e9f77a Autocomplete mod name prefix for items 2026-01-02 21:32:54 +03:00
275f54c7b7 Create empty adminCommands mod 2025-12-30 19:11:48 +03:00
47dc024b6c Create draft biome 2025-12-30 19:11:32 +03:00
efeb5c75cd Add draft plants 2025-12-30 19:10:46 +03:00
c0575e2c82 Tilesheet: minor fix 2025-12-30 19:10:04 +03:00
4e823bfee6 Math: add annotation to function 2025-12-30 18:13:11 +03:00
44ba5c7cfa Rename some mods 2025-12-30 17:53:26 +03:00
475b199ddb Create Plant class 2025-12-29 19:51:28 +03:00
96b51caaaf Fix game start 2025-12-29 19:12:48 +03:00
514e676e9a minor fix 2025-12-29 19:03:51 +03:00
7773e25a81 Callbacks -> Events. Fihish Control 2025-12-29 18:51:22 +03:00
96289375b1 CallbacksControl: add base logic 2025-12-29 15:29:44 +03:00
40c1d34124 ApiLoader: add GlobalStep.lua 2025-12-29 14:51:15 +03:00
2655127a22 ApiLoader: delete comment code 2025-12-29 14:00:55 +03:00
b1c3e50445 Add Callbacks API 2025-12-29 12:53:30 +03:00
9c919343cf Transfer Formspec mod from UI to CORE 2025-12-28 20:28:57 +03:00
13391b085e Delete Enum & VisualEnum classes 2025-12-28 20:27:16 +03:00
27004ebf45 Minor changes 2025-12-28 20:10:08 +03:00
7b951b64ac Formspec: create our api. Part 2 2025-12-28 15:02:29 +03:00
c57a7ceadd Formspec: create our api. Part 1 2025-12-26 20:28:04 +03:00
95084d5daf Formspec: create mod and basic class 2025-12-25 22:23:14 +03:00
3e9996e6a0 bump changes 25.12 2025-12-25 14:31:11 +03:00
3646ec78cd Update README.md and add last_title.png 2025-12-19 21:56:33 +03:00
cf141f9797 Update README.md 2025-12-19 21:54:24 +03:00
475b5fab0c Update heared_scale.png 2025-12-19 21:53:28 +03:00
6f742e7291 Update README.md & add heared_scale.png 2025-12-19 21:52:45 +03:00
b5994d7383 Update README.md 2025-12-19 21:51:28 +03:00
c5a71d5bdc Update icons & title 2025-12-19 21:49:21 +03:00
1ac87b464a CraftSystem: create base system 2025-12-16 21:49:54 +03:00
5b22c900d5 Create CraftSystem mod 2025-12-14 14:38:27 +03:00
0b749564af MapGen: move waterLevel MapGenDef -> LayerDef 2025-12-11 19:19:53 +03:00
a699367bf4 bruh commit 2025-12-11 19:08:49 +03:00
720b7edcdb Create Player class and Player.HUD, Player.GUI 2025-12-08 21:28:30 +03:00
bbd5c781e4 Create Sound class 2025-12-08 21:25:46 +03:00
0870ce37e9 Rename mod Log -> Wood, add base logs 2025-12-08 20:37:55 +03:00
a5c8846130 MapGen: fix biome scattering 2025-12-03 21:23:35 +03:00
745fdb8dd3 MapGen: add StaticLayer 2025-12-02 22:06:41 +03:00
a0a1db6179 MapGen & MapGenerator: update mod.confs 2025-12-01 19:16:24 +03:00
1d576dcaf5 Update README.md 2025-12-01 19:11:34 +03:00
414d5008d3 Update menu & README.md 2025-12-01 19:04:18 +03:00
7908f5fc9f Update game.conf 2025-12-01 18:45:50 +03:00
af87c2912c MapGen: updagrade biomes scattering 2025-12-01 18:36:09 +03:00
e44420d0ab Remove GlobalSpace, domains and extends methods in Mod 2025-12-01 17:08:56 +03:00
ace217832b Write Class lib 2025-12-01 17:07:44 +03:00
f9eccced09 Mapgen: write SuperUltraSigmaMapgen part 9 (FINAL) 2025-11-28 20:23:51 +03:00
d07b7c811f Mapgen: write SuperUltraSigmaMapgen part 8.3 2025-11-27 22:31:33 +03:00
f556e4349e Update README.md 2025-11-27 20:30:55 +03:00
242 changed files with 19038 additions and 1779 deletions

View File

@@ -24,13 +24,16 @@
"enables": [],
"globals": [
"core",
"Smc",
"table",
"Events",
"VoxelArea",
"VoxelManip",
"vector",
"Ensure",
"string",
"string_utf8"
"string_utf8",
"Profiler"
],
"globalsRegex": []
},

View File

@@ -0,0 +1,52 @@
name: Сообщение об ошибке
about: Сообщить о недоработке игры, которую необходимо исправить.
title: "[Bug]: "
labels:
- bug/need confirmed
body:
- type: textarea
id: bug-desc
attributes:
label: Описание ошибки
description: Опишите, что произошло, в чем по вашему мнению заключается ошибка и какое поведение игры вы ожидали.
validations:
required: true
- type: textarea
id: playback-order
attributes:
label: Как воспроизвести баг?
description: Опишите порядок действий, как воспроизвести описываемую ошибку.
validations:
required: false
- type: dropdown
id: game-version
attributes:
label: Версия игры
description: Сообщите на каких версиях клиента игры была замечена ошибка.
multiple: true
options:
- "5.15"
- "5.14"
- "5.13"
- "5.12"
- "5.11"
- "5.10"
- "< 5.10"
validations:
required: true
- type: dropdown
id: bug-server
attributes:
label: Где была замечена ошибка?
description: Сообщите, где была замечена ошибка.
multiple: true
options:
- Игровой сервер
- Локальный мир
- Тестовый сервер
validations:
required: true
- type: markdown
attributes:
value: |
Спасибо, что уделили время и заполнили этот отчет об ошибке!

View File

@@ -0,0 +1,19 @@
name: Предложение
about: Описать предложение для рассмотрения мейнтейнерами проекта.
labels:
- idea/need a maintainer
body:
- type: textarea
id: task-desc
attributes:
label: Описание
description: Подробно опишите в чем заключается ваша идея, а так же объясните необходимость её реализации.
validations:
required: true
- type: textarea
id: task-additions
attributes:
label: Дополнения
description: Приложите дополнительные сведенья, файлы или изображения.
validations:
required: false

View File

@@ -0,0 +1,19 @@
name: Задача
about: Сформировать и описать задачу, которую должен будет выполнить разработчик. Этот шаблон предназначен для мейнтейнеров проекта.
labels:
- task/need developer
body:
- type: textarea
id: task-desc
attributes:
label: Описание задачи
description: Подробно опишите в чем заключается задача для разработчика.
validations:
required: true
- type: textarea
id: task-additions
attributes:
label: Дополнения
description: Приложите дополнительные сведенья, файлы или изображения необходимые для выполнения задачи.
validations:
required: false

View File

@@ -0,0 +1,35 @@
name: PR-template
about: PR-template
labels:
- pr/wait review
- review/need a maintainer
body:
- type: textarea
id: pr-desc
attributes:
label: Описание изменений
description: Опишите, что было изменено в запросе на слияние и по какой причине.
validations:
required: true
- type: textarea
id: testing
attributes:
label: Тестирование
description: Опишите, в наличии каких объектов или в работоспособности каких систем необходимо убедиться.
validations:
required: false
- type: checkboxes
id: terms
attributes:
label: Требования
options:
- label: Я ознакомлен с соглашением по разработке и мои изменения следуют принятым стандартам.
required: true
- label: Я запускал игру и убедился в том, что она работает.
required: false
- label: Я указал в описании запроса метки (label) с префиксом `Edit:` в соответствии с теми изменениями, которые сделал.
required: false
- type: markdown
attributes:
value: |
Спасибо, что прислали это запрос на слияние и помогли нам в разработке игры!

1
.gitignore vendored
View File

@@ -1 +1,2 @@
IGNORE
/mods/IGNORE

7
.gitmodules vendored
View File

@@ -1,7 +1,6 @@
[submodule "mods/API/Utf8"]
path = mods/API/Utf8
url = https://github.com/ApancoreStudio/utf8_api.git
branch = main
[submodule "util/ide-helper"]
path = util/ide-helper
url = https://github.com/Voxrame/luanti-ide-helper.git
[submodule "mods/SYSTEM/Utf8"]
path = mods/SYSTEM/Utf8
url = https://git.apancore.ru/Apancore.Studio/utf8_api.git

View File

@@ -1,7 +1,8 @@
Source code licensing:
# Source code licensing
The MIT License (MIT)
Copyright (c) 2025 Apancore.Studio, Doloment
**The MIT License (MIT)**
Copyright (c) 2025-2026 Apancore.Studio, Van (varttist), Doloment
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
@@ -11,9 +12,13 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
------------------------
Sprites licensing:
# Sprites licensing
CC BY 4.0
Copyright (c) 2025 Apancore.Studio, Doloment and others (see list below)
**CC BY 4.0**
Copyright (c) 2025-2026 Apancore.Studio, Van (varttist) and others (see list below)
All textures except those listed here are copyrighted by Van (varttist) and are distributed under the CC BY 4.0.
List of all textures and authors:
- ...

View File

@@ -1,3 +1,12 @@
Simple Makes Complex is a Luanti engine-based game focused on the multiplayer gameplay
![image](/menu/header_scale.png)
![image](/menu/icon.png)
# Simple Makes Complex
Simple Makes Complex is a Luanti engine-based game focused on the multiplayer gameplay.
# Licensing
- The project's core code is licensed under [MIT](/LICENSE).
- Submodules may contain their own license.
- Media assets are used and distributed under [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/).
# Assets used
- Font used in the `/menu/last_header.png`: https://fontstruct.com/fontstructions/show/2722233/gbjve (danil_2461, [CC0](http://creativecommons.org/publicdomain/zero/1.0/))

View File

@@ -1 +1,4 @@
title = SMC
allowed_mapgens = singlenode
default_mapgen = singlenode

BIN
menu/background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 MiB

BIN
menu/header.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

BIN
menu/header_scale.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 770 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
menu/last_header.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@@ -1,91 +0,0 @@
Api = {}
---@alias Domain table<string,Mod|SubDomain> Global table for accessing public classes provided by mods.
---@alias SubDomain table<string,Mod>
---@type Domain
Core = {}
---@type Domain
Environment = {}
---@type Domain
Game = {}
---@type SubDomain
Game.Items = {}
---@type SubDomain
Game.Mobs = {}
---@type SubDomain
Game.Structures = {}
Ui = {}
local allowedDomains = {
Api = true,
Core = true,
Environment = true,
Game = true,
Ui = true
}
--- Adds a mod to the global space under specified domain structure
---@param mod Mod The mod table containing functionality to expose
---@param location string Dot-separated path within domain structure (e.g. "Items.Log")
---@param force boolean? Whether to overwrite the target location.
Api.addModToGlobalSpace = function(mod, location, force)
-- Ensure `mod` type and that it's not empty
Ensure.argType(mod, 'table', 1, 'Api.addModToGlobalSpace')
-- Ensure `location` type and that it's not empty
Ensure.argType(location, 'string', 2, 'Api.addModToGlobalSpace')
Ensure.stringArgNotEmpty(location, 2, 'Api.addModToGlobalSpace')
-- Ensure `location` matches this format: 'field.subfield.subsubfield.<...>'
-- TODO: баг: ликвидные имена не определяются шаблоном
--[[if not location:match('^[%a_][%w_]*([%.][%a_][%w_]*)*$') then
error('bad argument #2 to \'Api.addModToGlobalSpace\' (invalid format)')
end--]]
-- Split `location` into fields -- TODO: !!!Make a String function!!!
local fields = {}
local domain = nil
for field in string.gmatch(location, '[^.]+') do
if domain ~= nil then
table.insert(fields, field)
else
domain = field
end
end
-- Ensure the domain is allowed
Ensure.argIsAllowed(domain, allowedDomains , 2, 'Api.addModToGlobalSpace')
-- Handle case where we're modifying the domain root directly
if #fields == 0 then
error('Not allowed to directly write into the \''.. domain ..'\' domain')
end
-- Start traversing from the domain's table
local current = _G[domain]
assert(type(current) == 'table', 'The global domain is not a table')
-- Traverse each field of the location
local num_fields = #fields
for i = 1, num_fields - 1 do
local field = fields[i]
if current[field] == nil then
current[field] = {}
end
current = current[field]
assert(type(current) == 'table', 'intermediate field is not a table')
end
-- Assign mod to the final field
local last_field = fields[num_fields]
if force and current[last_field] ~= nil then
error(string.format('field \'%s\' already exists in \'%s\'', last_field, location))
end
current[last_field] = mod
end

View File

@@ -1,3 +0,0 @@
name = smc__api__api_loader
description = Include this mod in your `depends` to ensure all necessary APIs are loaded for your mod
depends = smc__api__ensure, smc__api__math, smc__api__mod, smc__api__require, smc__api__table, smc__api__string, smc__api__utf8,

View File

@@ -1 +0,0 @@
name = smc__api__ensure

View File

@@ -1 +0,0 @@
name = smc__api__logger

View File

@@ -1,9 +0,0 @@
local math = math
math.lerp = function (a, b, t)
return a + (b - a) * t
end
math.clamp = function(value, min, max)
return math.min(math.max(value, min), max)
end

View File

@@ -1 +0,0 @@
name = smc__api__math

View File

@@ -1 +0,0 @@
name = smc__api__mod

View File

@@ -1 +0,0 @@
name = smc__api__require

View File

@@ -1,2 +0,0 @@
name = smc__api__string
depends = smc__api__ensure

View File

@@ -1,2 +0,0 @@
name = smc__api__table
depends = smc__api__ensure

Submodule mods/API/Utf8 deleted from d612fc127f

View File

@@ -1 +0,0 @@
name = smc__api

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__base_ui')
local require = modInfo.require
return require('BaseUI')

View File

@@ -0,0 +1,2 @@
name = smc__core__base_ui
depends = smc__system__system_loader

View File

@@ -0,0 +1,134 @@
local getInstance = Class.getInstance
---@class BaseUI
---Context for transferring data between displaying
---the form spec to the player and handling callbacks.
---@field name string
---@field getFormSpecString fun(self:BaseUI,playerName:string,...):string
---@field contex table<string, table>
local BaseUI = {
contex = {}
}
---@param name string The name of the formspec that will be shown to the player. It is recommended that the name be unique.
---@param getFormSpecString fun(self:BaseUI,playerName:string,...):string
---@param clearContex boolean? Whether to clear the context stored for a player when that player closes the form. Default `true`.
function BaseUI:new(name, getFormSpecString, clearContex)
if clearContex == nil then
clearContex = true
end
---@type BaseUI
local instance = getInstance(self, {})
instance.name = name
instance.getFormSpecString = getFormSpecString
if clearContex then
-- Ensure that when the form is closed, the context is cleared.
instance:registerOnFormQuit(function(player)
instance:clearContex(player)
end)
end
instance:registerOnFormQuit(function(player)
Smc.clearActiveFormspec(player:get_player_name())
end)
return instance
end
---Set a value for a specific key.
---Recommended for use where `core.show_formspec` is used.
---
---In the future, the key value can be obtained in the formspec callback.
---@param player string|Player Player as an object (entity) or his name
---@param key string
---@param value any
function BaseUI:setContex(player, key, value)
if type(player) ~= 'string' then
player = player:get_player_name()
end
local contex = self.contex[player]
if contex == nil then
self.contex[player] = {[key]=value}
else
contex[key] = value
end
end
---Get the value of a specific key.
---Recommended for use in a formspec callback.
---@param player string|Player Player as an object (entity) or his name
---@param key string
---@return any?
function BaseUI:getContex(player, key)
if type(player) ~= 'string' then
player = player:get_player_name()
end
local contex = self.contex[player] or {}
return contex[key]
end
---Clear saved context data for a player.
---Recommended for use when closing formspec.
---@param player string|Player Player as an object (entity) or his name
function BaseUI:clearContex(player)
if type(player) ~= 'string' then
player = player:get_player_name()
end
self.contex[player] = {}
end
---Register a callback for a specific player action in FormSpec.
---
---The callback is guaranteed to be called only for the specified field.
---@param fieldName string the name of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called.
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldAction(fieldName, callback)
Smc.registerOnFormFieldAction(self.name, fieldName, callback)
end
---Register a callback function to close the FormSpec.
---
---The callback is guaranteed to be called only for the specified form.
---@param callback fun(player:Player) Callback to handle the close. Parameters:
--- * `player` - the player who closed the form.
function BaseUI:registerOnFormQuit(callback)
Smc.registerOnFormQuit(self.name, callback)
end
---Register a callback for a specific player action in FormSpec.
---
---The callback function is guaranteed to be called only for the specified form and
---for the field whose name matches the pattern.
---@param fieldNamePattern string the name pattern of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called (will match the pattern).
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldActionMatch( fieldNamePattern, callback)
Smc.registerOnFormFieldActionMatch(self.name, fieldNamePattern, callback)
end
---Shows the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:showForm(playerName, ...)
core.show_formspec(playerName, self.name, self:getFormSpecString(playerName, ...))
Smc.setActiveFormspec(playerName, self.name)
end
---Close the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:closeForm(playerName)
core.close_formspec(playerName, self.name)
end
return BaseUI

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__control')
local require = modInfo.require
return require('Control')

View File

@@ -0,0 +1,2 @@
name = smc__core__control
depends = smc__system__system_loader

View File

@@ -0,0 +1,136 @@
---@class Events.Control
local Control = {}
-- control.on_press
---@param callbackFunc fun(player:Player, controlName:string)
function Control.subcribeOnPress(callbackFunc)
Events.subscribe('control.on_press', callbackFunc)
end
-- control.on_release
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number)
function Control.subcribeOnRelease(callbackFunc)
Events.subscribe('control.on_release', callbackFunc)
end
-- control.on_hold
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number, dtime:number)
function Control.subcribeOnHold(callbackFunc)
Events.subscribe('control.on_hold', callbackFunc)
end
-- control.on_wield_change
---@param callbackFunc fun(player:Player, player_wield_index:number, player_last_wield_index:number)
function Control.subcribeOnWieldChange(callbackFunc)
Events.subscribe('control.on_wield_change', callbackFunc)
end
-- --- Call events ---
local ControlPressKeys = {
'up', 'down', 'left', 'right', 'jump', 'aux1', 'sneak', 'dig', 'place', 'zoom'
}
local ControlMovementKeys = {
'movement_x', 'movement_y'
}
local playersLastControl = {}
local playersControlTimer = {}
core.register_on_joinplayer(function(player, last_login)
local playerName = player:get_player_name()
if playerName == nil then
return
end
local nowControl = player:get_player_control()
if nowControl == nil then
return
end
local controlTimer = {}
for _, key in ipairs(ControlPressKeys) do
controlTimer[key] = 0.0
end
playersLastControl[playerName] = nowControl
playersControlTimer[playerName] = controlTimer
end)
core.register_on_leaveplayer(function(player, timed_out)
local playerName = player:get_player_name()
if playerName == nil then
return
end
playersLastControl[playerName] = nil
playersControlTimer[playerName] = nil
end)
Smc.registerGlobalStepForEachPlayer(0, function(deltaTime, player)
if player == nil then
return
end
local playerName = player:get_player_name()
if playerName == nil then
return
end
local lastControl = playersLastControl[playerName]
if lastControl == nil then
return
end
local controlTimer = playersControlTimer[playerName]
if controlTimer == nil then
return
end
local nowControl = player:get_player_control()
if nowControl == nil then
return
end
for _, key in ipairs(ControlPressKeys) do
local lastPressed = lastControl[key]
local nowPressed = nowControl[key]
-- on_press
if not lastPressed and nowPressed then
Events.call('control.on_press', key)
controlTimer[key] = 0
-- on_release
elseif lastPressed and not nowPressed then
Events.call('control.on_release', key, controlTimer[key])
controlTimer[key] = 0
-- on_hold
elseif lastPressed and nowPressed then
Events.call('control.on_hold', key, controlTimer[key], deltaTime)
controlTimer[key] = controlTimer[key] + deltaTime
end
end
--TODO: add player movement callbacks
--TODO: add mouse movement callbacks on dir
playersLastControl[playerName] = nowControl
playersControlTimer[playerName] = controlTimer
end)
return Control

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
return require('CraftSystem')

View File

@@ -0,0 +1,2 @@
name = smc__core__craft_system
depends = smc__system__system_loader, smc__core__creature

View File

@@ -0,0 +1,28 @@
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.PrimitiveCraftHandler
local PrimitiveCraftHandler = require('CraftSystem.PrimitiveCraftHandler')
---@type CraftSystem.ImmersiveCraftHandler
local ImmersiveCraftHandler= require('CraftSystem.ImmersiveCraftHandler')
---@alias CraftSystem.CraftGroup string
---@alias CraftSystem.CraftRecipe string[]
---@alias CraftSystem.CraftType 'primitive'|'immersive'
---@class CraftSystem
local CraftSystem = {}
---@param craftName string
---@param def CraftSystem.PrimitiveCraftDef
function CraftSystem.registerPrimitiveCraft(craftName, def)
PrimitiveCraftHandler:registerCraft(craftName, def)
end
---@param craftName string
---@param def CraftSystem.ImmersiveCraftDef
function CraftSystem.registerImmersiveCraft(craftName, def)
ImmersiveCraftHandler:registerCraft(craftName, def)
end
return CraftSystem

View File

@@ -0,0 +1,13 @@
---Abstract class for craft.
---@class CraftSystem.BaseCraft
---@field name string
---@field group CraftSystem.CraftGroup
local BaseCraft = {}
---Definition table for the `CraftSystem.BaseCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.BaseCraftDef
---@field group CraftSystem.CraftGroup?
return BaseCraft

View File

@@ -0,0 +1,57 @@
local PLAYERS_KNOW_ALL_RECIPES = true
---Abstract class for handling crafting.
---@class CraftSystem.BaseCraftHandler
---@field craftsByName table<string, CraftSystem.BaseCraft>
---@field craftsByGroup table<CraftSystem.CraftGroup, CraftSystem.BaseCraft[]>
---@field craftsList CraftSystem.BaseCraft[]
---@field groupedCrafts (CraftSystem.BaseCraft[]|CraftSystem.BaseCraft)[]
---@field learnedCrafts table<string, (CraftSystem.BaseCraft[]|CraftSystem.BaseCraft)[]>
local BaseCraftHandler = {
craftsByName = {},
craftsByGroup = {},
craftsList = {},
groupedCrafts = {},
learnedCrafts = {},
}
---@param craftName string
---@return CraftSystem.BaseCraft
function BaseCraftHandler:getCraftByName(craftName)
local craft = self.craftsByName[craftName]
assert(craft ~= nil, ('There is no primitive craft named `%s`.'):format(
craftName))
return craft
end
---@param craftGroup CraftSystem.CraftGroup
---@return CraftSystem.BaseCraft[]
function BaseCraftHandler:getCraftsByGroup(craftGroup)
local crafts = self.craftsByGroup[craftGroup]
assert(crafts ~= nil, ('There are no primitive crafts with `%s` group'):format(
craftGroup))
return crafts
end
---@param playerName string
---@return (CraftSystem.BaseCraft[]|CraftSystem.BaseCraft)[]
function BaseCraftHandler:getLearnedCrafts(playerName)
if PLAYERS_KNOW_ALL_RECIPES then
return self.groupedCrafts
end
local crafts = self.learnedCrafts[playerName]
if crafts == nil then
crafts = {}
self.learnedCrafts[playerName] = crafts
end
return crafts
end
return BaseCraftHandler

View File

@@ -0,0 +1,237 @@
local getInstance, extend = Class.getInstance, Class.extend
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraft
local BaseCraft = require('CraftSystem.BaseCraft')
---@type CraftSystem.ImmersiveCraftCounter
local ImmersiveCraftCounter = require('CraftSystem.ImmersiveCraftCounter')
---Types of immersive stages.
---@class CraftSystem.StagesTypes : table<CraftSystem.ImmersiveCraftStage.Type, CraftSystem.ImmersiveCraftStage>
local stageTypes = {
---@type CraftSystem.ImmersiveCraftStage.TappingStage
tapping = require('CraftSystem.ImmersiveCraftStage.TappingStage'),
}
---Immersive crafting aimed at a more logical process of crafting items.
---@class CraftSystem.ImmersiveCraft : CraftSystem.BaseCraft
---@field startStageName string
---@field triggerItem ItemStackString
---@field output ItemStackString
---@field stagesByName table<string, CraftSystem.ImmersiveCraftStage>
local ImmersiveCraft = extend(BaseCraft, {})
---Definition table for the `CraftSystem.ImmersiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftDef : CraftSystem.BaseCraftDef
---@field startStageName string
---@field triggerItem ItemStackString
---@field output ItemStackString
---@field stages CraftSystem.ImmersiveCraftStageDef[]
---@param name string
---@param def CraftSystem.ImmersiveCraftDef
---@return CraftSystem.ImmersiveCraft
function ImmersiveCraft:new(name, def)
-- We create a table of crafting stages that the player needs to complete.
---@type table<string, CraftSystem.ImmersiveCraftStage>
local stagesByName = {}
for _, stageDef in ipairs(def.stages) do
-- We get the stage class based on its type.
local StageClass = stageTypes[stageDef.type]
-- Create a stage and add the craft name to the instance.
stageDef.craftName = name
local stage = StageClass:new(stageDef)
-- We add an instance of the stage to the table by name.
stagesByName[stageDef.name] = stage
end
---@type CraftSystem.ImmersiveCraft
local instance = getInstance(self, {})
instance.name = name
instance.group = def.group
instance.startStageName = def.startStageName
instance.triggerItem = def.triggerItem
instance.output = def.output
instance.stagesByName = stagesByName
-- Subscribe to an event that will determine that the player has completed the crafting stage.
Events.subscribe('craft_system:next_immersive_stage:'..name,
---@param eventName string
---@param stage CraftSystem.ImmersiveCraftStage
---@param pos MapPosition
---@param Player Player
function(eventName, stage, pos, Player)
-- From the current stage (which has been completed) we get the name of the next one.
local nextStageName = stage.nextStage
-- If there is no next stage...
if nextStageName == nil then
-- ...we are finishing the craft.
instance:endCraft(pos, Player)
else
-- ...else we start the next stage.
local nextStage = instance.stagesByName[nextStageName]
-- We get a table of temporary data.
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We are updating the crafting stage in it.
craftData.stageName = nextStageName
-- We save it to the workstation metadata.
Smc.setCraftDataByPos(pos, craftData)
-- We are starting the next stage of crafting.
nextStage:startHandler(pos, Player)
end
end)
return instance
end
---Initialize the start of the immersive crafting process.
---
---Returns `true` if the crafting process was running.
---@param pos MapPosition
---@param player Player
---@param amount integer
---@return boolean
function ImmersiveCraft:startCraft(pos, player, amount)
-- Adding craft to the counter.
-- If crafting has not been added...
if not ImmersiveCraftCounter:addCraft(pos, player:get_player_name()) then
-- ...then we don't let the player start a new craft.
core.chat_send_player(player:get_player_name(),
'The limit of simultaneously active crafts has been reached: '..
'complete or cancel active crafts to start a new one')
return false
end
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We edit the amount of materials in accordance with the number of crafts being performed.
stack:set_count(stack:get_count() * amount)
-- We get the player's inventory, from where we must take the materials for crafting.
local playerInventory = player:get_inventory()
-- If the player does not have the necessary materials for crafting...
if not playerInventory:contains_item('main', stack) then
-- ...we inform him about this.
core.chat_send_player(player:get_player_name(),
'Not enough materials for crafting')
return false
end
-- If we have the materials, we take them and start initializing the craft.
playerInventory:remove_item('main', stack)
-- We get the first stage of crafting.
local stage = self.stagesByName[self.startStageName]
-- Create a temporary data table for crafting.
---@type ImmersiveCraftData
local craftData = {
playerName = player:get_player_name(), -- The name of the player who started the craft.
craftName = self.name,
stageName = stage.name,
amount = amount,
}
-- We save it to the workstation metadata.
Smc.setCraftDataByPos(pos, craftData)
-- We are starting the first stage of crafting.
stage:startHandler(pos, player)
return true
end
---Complete the immersive crafting process.
---@param pos MapPosition
---@param player Player
function ImmersiveCraft:endCraft(pos, player)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We drop the result of crafting.
local dropPos = vector.new(pos) + vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(self.output), nil, dropPos)
end
-- Remove craft from the counter.
ImmersiveCraftCounter:removeCraft(pos, craftData.playerName)
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos)
end
---Stop the crafting process and free up the workbench.
---@param pos MapPosition
function ImmersiveCraft:abortCraft(pos)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We get the current stage and start the abort process.
local stage = self.stagesByName[craftData.stageName]
stage:abortHandler(pos)
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos)
-- Remove craft from the counter.
ImmersiveCraftCounter:removeCraft(pos, craftData.playerName)
end
---Returns a human-readable description of the crafting process.
---@return string
function ImmersiveCraft:toString()
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We obtain a table of item parameters.
---@type ItemDefinition
local itemDef = stack:get_definition()
-- Let's start writing a description of the craft.
local craftDesc = ('Material: %s x%s\n\n'):format(itemDef._title, stack:get_count())..
'Crafting process:\n'
-- Let's start with the first crafting stage.
---@type string?
local stageName = self.startStageName
local stages = self.stagesByName
-- While we have a stage name...
local count = 1
while stageName ~= nil do
-- We get a crafting stage...
local stage = stages[stageName]
-- ...and we add its description to the list of actions for crafting.
craftDesc = craftDesc..tostring(count)..'. '..stage:toString()..'\n'
-- We also get the name of the next stage.
stageName = stage.nextStage
end
-- If the cycle is interrupted, it means we have processed all the stages.
-- Return the craft description.
return craftDesc
end
return ImmersiveCraft

View File

@@ -0,0 +1,78 @@
local posToString, getSize = core.pos_to_string, table.get_size
local CRAFT_LIMIT_PER_PLAYER = 2
local CRAFT_LIMIT_PER_SERVER = 10
local modStorage = core.get_mod_storage()
---@param key string
---@return table
local function getStorageTable(key)
return core.deserialize(modStorage:get_string(key)) or {}
end
---@param key string
---@param t table
local function setStorageTable(key, t)
modStorage:set_string(key, core.serialize(t))
end
---Designed to keep track of active immersive
---crafts so as not to overload the server.
---
---The counter is individual for each player,
---but the total number of active crafts is also tracked.
---@class CraftSystem.ImmersiveCraftCounter
---@field craftsCountForPlayers table<string, table<string, boolean>>
---@field craftsCountForServer table<string, boolean>
local ImmersiveCraftCounter = {
craftsCountForPlayers = getStorageTable('crafts_count_for_players'),
craftsCountForServer = getStorageTable('crafts_count_for_serves')
}
---Add craft to the counter.
---
---Returns `false` if the counter is already full.
---@param pos MapPosition
---@param playerName string
---@return boolean
function ImmersiveCraftCounter:addCraft(pos, playerName)
if self.craftsCountForPlayers[playerName] == nil then
self.craftsCountForPlayers[playerName] = {}
end
if getSize(self.craftsCountForPlayers[playerName]) >= CRAFT_LIMIT_PER_PLAYER then
return false
end
if getSize(self.craftsCountForServer) >= CRAFT_LIMIT_PER_SERVER then
return false
end
local posString = posToString(pos)
self.craftsCountForPlayers[playerName][posString] = true
self.craftsCountForServer[posString] = true
return true
end
---Remove craft from the counter.
---@param pos MapPosition
---@param playerName string
function ImmersiveCraftCounter:removeCraft(pos, playerName)
local playerCrafts = self.craftsCountForPlayers[playerName]
if playerCrafts == nil then
return
end
local posString = posToString(pos)
playerCrafts[posString] = nil
self.craftsCountForServer[posString] = nil
end
core.register_on_shutdown(function()
setStorageTable('crafts_count_for_players', ImmersiveCraftCounter.craftsCountForPlayers)
setStorageTable('crafts_count_for_server', ImmersiveCraftCounter.craftsCountForServer)
end)
return ImmersiveCraftCounter

View File

@@ -0,0 +1,72 @@
local extend = Class.extend
local tableInsert = table.insert
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraftHandler
local BaseCraftHandler = require('CraftSystem.BaseCraftHandler')
---@type CraftSystem.ImmersiveCraft
local ImmersiveCraft = require('CraftSystem.ImmersiveCraft')
---A handler for immersive crafting that requires the player to complete
---crafting stages and interact with entities (crafting nodes)
---@class CraftSystem.ImmersiveCraftHandler : CraftSystem.BaseCraftHandler
---@field craftsByTriggerItem table<string, CraftSystem.ImmersiveCraft[]>
---@field getCraftByName fun(self, craftName:string):CraftSystem.ImmersiveCraft
---@field getCraftsByGroup fun(self, craftGroup):CraftSystem.ImmersiveCraft[]
---@field getLearnedCrafts fun(self, playerName):table<string, CraftSystem.ImmersiveCraft>
local ImmersiveCraftHandler = extend(BaseCraftHandler, {
craftsByTriggerItem = {},
})
---Register an immersive crafting experience that requires the player to complete
---one or more crafting stages that involve interaction with entities (crafting nodes)
---@param craftName string
---@param def CraftSystem.ImmersiveCraftDef
function ImmersiveCraftHandler:registerCraft(craftName, def)
assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format(
craftName))
-- The craft group to which the craft belongs.
local group = 'craft_group:' .. (def.group or 'UNDEFINED')
def.group = group
-- We obtain a crafting instance according to the given parameters.
local craft = ImmersiveCraft:new(craftName, def)
-- If no craft with this group has been registered before...
if self.craftsByGroup[group] == nil then
-- ...then we create a list for this group.
self.craftsByGroup[group] = {}
end
-- The material from which crafting begins (also known as the starting item).
local triggerItem = def.triggerItem
-- If no crafting for such a starting item has been registered before...
if self.craftsByTriggerItem[triggerItem] == nil then
-- ...then we create a list for this item.
self.craftsByTriggerItem[triggerItem] = {}
end
-- Adding craft to the lists:
self.craftsByName[craftName] = craft
tableInsert(self.craftsByGroup[group], craft)
tableInsert(self.craftsByTriggerItem[triggerItem], craft)
tableInsert(self.craftsList, craft)
end
---Returns a list of crafts that use the given item as a starting material.
---
---Will return `nil` if the item is not used in any craft as a starting item.
---@param triggerItem string
---@return CraftSystem.ImmersiveCraft[]?
function ImmersiveCraftHandler:getCraftsByTriggerItem(triggerItem)
local crafts = self.craftsByTriggerItem[triggerItem]
return crafts
end
return ImmersiveCraftHandler

View File

@@ -0,0 +1,14 @@
---@type Creature
local Creature = Mod.getInfo('smc__core__creature').require('Creature')
---The entity the player interacts with during immersive crafting.
---@class CraftSystem.ImmersiveCraftNode : Creature
local ImmersiveCraftNode = Creature:getExtended({
settings = {
_name = 'craft_system:immersive_craft_node',
_add_mod_name = false,
initial_properties = {},
}
})
return ImmersiveCraftNode

View File

@@ -0,0 +1,95 @@
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.ImmersiveCraftNode
local ImmersiveCraftNode = require('CraftSystem.ImmersiveCraftNode')
---A class that extends `Creature.LuaEntity` to annotate custom fields needed for immersive crafting.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftNode.LuaTappingNode : Creature.LuaEntity
---The name of the item that the crafting node display.
---@field _item_name ItemStackString
---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used.
---@field _set_item fun(self:CraftSystem.ImmersiveCraftNode.LuaTappingNode, itemName:ItemStackString?)
---@field _craft_name string
---@field _stage_name string
---@field _work_station_pos MapPosition
-- A crafting node (entity) that is used in the tapping crafting stage.
local tappingNode = ImmersiveCraftNode:new({
settings = {
_name = 'craft_system:tapping_node',
_add_mod_name = false,
---@type ObjectProperties
initial_properties = {
visual = 'wielditem',
visual_size = {x=0.5, y=0.5, z=0.5},
collisionbox = {
-0.375, -0.375, -0.375,
0.375, 0.375, 0.375
},
},
_item_name = '',
_craft_name = '',
_stage_name = '',
_work_station_pos = {},
},
callbacks = {
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
on_activate = function(luaEntity, staticdata, dtime)
-- We obtain a table of initial parameters for the craft node entity.
---@type CraftSystem.ImmersiveCraftStage.TappingNode.InitParams?
local params = core.deserialize(staticdata)
-- We enter parameters into the entity's custom fields.
if params ~= nil then
luaEntity._item_name = params.targetItem
luaEntity._craft_name = params.craftName
luaEntity._stage_name = params.stageName
luaEntity._work_station_pos = params.WorkStationPos
end
-- we set the appearance of the item to be processed on the crafting node.
luaEntity:_set_item(luaEntity._item_name)
-- We add an immortal group to the entity so that it cannot be killed.
luaEntity.object:set_armor_groups({immortal = 1})
end,
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
on_punch = function(luaEntity, puncher, time_from_last_punch, tool_capabilities, dir, damage)
-- We simply trigger the event that the player hits the crafting node, bound to the work station with coordinates.
Events.call(('craft_system:punch_tapping_node:%s:%s'):format(
luaEntity._craft_name, luaEntity._stage_name), luaEntity._work_station_pos, puncher, luaEntity)
return false
end,
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
get_staticdata = function(luaEntity)
---@type CraftSystem.ImmersiveCraftStage.TappingNode.InitParams?
local params = {
targetItem = luaEntity._item_name,
craftName = luaEntity._craft_name,
stageName = luaEntity._stage_name,
WorkStationPos = luaEntity._work_station_pos
}
return core.serialize(params)
end,
---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used.
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
---@param itemName ItemStackString?
_set_item = function(luaEntity, itemName)
-- We change the entity field so that the engine itself displays it as a given item.
luaEntity.object:set_properties({
wield_item = itemName or luaEntity._item_name,
})
end,
}
})
return tappingNode

View File

@@ -0,0 +1,43 @@
local getInstance = Class.getInstance
---@alias CraftSystem.ImmersiveCraftStage.Type 'tapping'
---One of the stages of immersive crafting.
---@class CraftSystem.ImmersiveCraftStage
---@field name string
---@field type CraftSystem.ImmersiveCraftStage.Type
---@field craftName string
---@field startHandler fun(self, pos:Position, player:Player)
---@field processHandler fun(self, pos:Position, player:Player)
---@field endHandler fun(self, pos:Position, player:Player)
---@field abortHandler fun(self, pos:Position)
---@field toString fun(self):string
---@field nextStage string?
---@field returnItems ItemStackString[]?
local ImmersiveCraftStage = {}
---Definition table for the `CraftSystem.ImmersiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftStageDef
---@field name string
---@field type CraftSystem.ImmersiveCraftStage.Type
---@field craftName string?
---@field nextStage string?
---@field returnItems ItemStackString[]?
---@param def CraftSystem.ImmersiveCraftStageDef
---@return CraftSystem.ImmersiveCraftStage
function ImmersiveCraftStage:new(def)
---@type CraftSystem.ImmersiveCraftStage
local instance = getInstance(self, {})
instance.name = def.name
instance.type = def.type
instance.craftName = def.craftName
instance.nextStage = def.nextStage
instance.returnItems = def.returnItems
return instance
end
return ImmersiveCraftStage

View File

@@ -0,0 +1,202 @@
local extend = Class.extend
local getStageDataByPos, setStageDataByPos = Smc.getStageDataByPos, Smc.setStageDataByPos
local require = Mod.getInfo('smc__core__craft_system').require
---@type CraftSystem.ImmersiveCraftStage
local ImmersiveCraftStage = require('CraftSystem.ImmersiveCraftStage')
---A crafting step that requires the player to hit a crafting node (entity) a certain number of times.
---@class CraftSystem.ImmersiveCraftStage.TappingStage : CraftSystem.ImmersiveCraftStage
---@field targetItem string
---@field clicksNeed string
---@field toolGroup string?
---@field startHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field processHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field endHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field toString fun(self:CraftSystem.ImmersiveCraftStage.TappingStage):string
local TappingStage = extend(ImmersiveCraftStage, {})
---Definition table for the `CraftSystem.ImmersiveCraftStage.TappingStage`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftStage.TappingStageDef : CraftSystem.ImmersiveCraftStageDef
---@field targetItem string
---@field clicksNeed string
---@field toolGroup string?
---Data table for transferring various time parameters between calls.
---
---**Only for EmmyLua.**
---@class ImmersiveStageData.TappingStageData : ImmersiveStageData
---How many clicks were made by the player on the entity.
---@field clickCount integer
---Unique identifier of the entity (craft node).
---@field entityGUID string
---@param def CraftSystem.ImmersiveCraftStage.TappingStageDef
function TappingStage:new(def)
---@type CraftSystem.ImmersiveCraftStage.TappingStage
local instance = ImmersiveCraftStage:new(def)
instance.targetItem = def.targetItem
instance.clicksNeed = def.clicksNeed
instance.toolGroup = def.toolGroup
-- Registering the crafting stage start handler.
instance.startHandler = function(tappingStage , pos, player)
-- We determine the coordinate where we will create the crafting node (entity).
local entityPos = vector.new(pos) + vector.new(0,0.875,0)
-- We create a table of initial parameters that we will pass to the entity.
---@class CraftSystem.ImmersiveCraftStage.TappingNode.InitParams
local params = {
targetItem = tappingStage.targetItem,
craftName = tappingStage.craftName,
stageName = tappingStage.name,
WorkStationPos = pos,
}
-- Adding an entity to the world.
local obj = core.add_entity(entityPos, 'craft_system:tapping_node', core.serialize(params))
-- If the entity was not returned, something went wrong.
if obj == nil then
return
end
-- Create a temporary table of crafting stage data.
---@type ImmersiveStageData.TappingStageData
local stageData = {
clickCount = 0,
entityGUID = obj:get_guid()
}
-- Saving temporary data in work station metadata.
setStageDataByPos(pos, stageData)
end
-- Registering the crafting stage process handler.
-- Called when a player clicks on a crafting node (entity).
instance.processHandler = function(tappingStage, pos, player)
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos)
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- Increasing the click counter
local clickCount = stageData.clickCount
clickCount = clickCount + 1
-- If the number of clicks is greater than required to complete the step...
if clickCount >= tappingStage.clicksNeed then
-- ...we are completing the stage.
tappingStage:endHandler(pos, player)
else
-- ...else we save the number of clicks in the temporary data table.
stageData.clickCount = clickCount
Smc.setStageDataByPos(pos, stageData)
end
end
-- Registering the crafting stage end handler.
instance.endHandler = function(tappingStage, pos, player)
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos)
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- We get the entity object.
local entity = Smc.getObjectByGUID(stageData.entityGUID)
assert(entity ~= nil, 'The entity for immersive crafting is nil.')
-- Removing an entity from the world.
entity:remove()
-- We trigger an event that the crafting stage has been completed.
Events.call('craft_system:next_immersive_stage:'..tappingStage.craftName, tappingStage, pos, player)
end
-- Registering the aborting the crafting process handler.
---@param tappingStage CraftSystem.ImmersiveCraftStage.TappingStage
instance.abortHandler = function(tappingStage, pos)
-- We receive current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = craftData.stageData
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- We get the entity object.
local entity = Smc.getObjectByGUID(stageData.entityGUID)
assert(entity ~= nil, 'The entity for immersive crafting is nil.')
-- Removing an entity from the world.
entity:remove()
-- We drop the item as it was before processing.
local dropPos = vector.new(pos)+vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(tappingStage.targetItem), nil, dropPos)
end
end
-- Returns a human-readable description of the crafting stage.
instance.toString = function(tappingStage)
local stageDesc
if tappingStage.toolGroup ~= nil then
stageDesc = ('Tapping x%s tool with a group "%s"'):format(tappingStage.clicksNeed, tappingStage.toolGroup)
else
stageDesc = ('Tapping x%s'):format(tappingStage.clicksNeed)
end
return stageDesc
end
-- Subscribe to an event that means the player hit the entity.
Events.subscribe(('craft_system:punch_tapping_node:%s:%s'):format(instance.craftName, instance.name),
---@param craftNode LuaEntity
---@param player Player
function(eventName, pos, player, craftNode)
-- We get the item that the player clicked on the crafting node.
local toolDef = player:get_wielded_item():get_definition()
-- If a crafting stage requires a specific tool group and he doesn't have it...
if instance.toolGroup and (not toolDef.groups or not toolDef.groups[instance.toolGroup]) then
-- ...then we don't do anything.
return
end
-- DRAFT START:
-- Creating particles
for i=0, 10 do
core.add_particle({
pos = vector.new(pos)+vector.new(0,0.5,0),
velocity = {x=math.random(-1,1), y=4, z=math.random(-1,1)},
acceleration = {x=0, y=-9.8, z=0},
expirationtime = 2,
collision_removal = true,
node = {name=instance.targetItem}
})
end
-- Making the entity shake (silly method :P).
craftNode.object:set_rotation(vector.new(0.01,0.1,0.01))
core.after(0.1, function() craftNode.object:set_rotation(vector.new(-0.01,-0.1,-0.01))end)
core.after(0.2, function() craftNode.object:set_rotation(vector.new(0,0,0))end)
-- DRAFT END
-- Calling the crafting stage process handler.
instance:processHandler(pos, player)
end)
return instance
end
-- Registering an entity for immersive tapping crafting.
require('CraftSystem.ImmersiveCraftNode.tappingNode')
return TappingStage

View File

@@ -0,0 +1,39 @@
local getInstance, extend = Class.getInstance, Class.extend
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraft
local BaseCraft = require('CraftSystem.BaseCraft')
---@class CraftSystem.PrimitiveCraft : CraftSystem.BaseCraft
---@field output ItemStackString
---@field recipe CraftSystem.CraftRecipe
---@field returnItems ItemStackString[]
local PrimitiveCraft = extend(BaseCraft, {})
---Definition table for the `CraftSystem.PrimitiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.PrimitiveCraftDef : CraftSystem.BaseCraftDef
---@field output ItemStackString
---@field recipe CraftSystem.CraftRecipe
---@field returnItems ItemStackString[]?
---@param name string
---@param def CraftSystem.PrimitiveCraftDef
---@return CraftSystem.PrimitiveCraft
function PrimitiveCraft:new(name, def)
---@type CraftSystem.PrimitiveCraft
local instance = getInstance(self, {
name = name,
group = def.group,
output = def.output,
recipe = def.recipe,
returnItems = def.returnItems or {}
})
return instance
end
return PrimitiveCraft

View File

@@ -0,0 +1,70 @@
local extend = Class.extend
local tableInsert, tableSort, tableJoin = table.insert, table.sort, table.join
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraftHandler
local BaseCraftHandler = require('CraftSystem.BaseCraftHandler')
---@type CraftSystem.PrimitiveCraft
local PrimitiveCraft = require('CraftSystem.PrimitiveCraft')
---A primitive crafting processor that doesn't require much interaction and provides
---simple crafting based on a recipe-result scheme.
---@class CraftSystem.PrimitiveCraftHandler : CraftSystem.BaseCraftHandler
---@field craftsByGroup table<CraftSystem.CraftGroup, CraftSystem.PrimitiveCraft[]>
---@field groupedCrafts (CraftSystem.PrimitiveCraft[]|CraftSystem.PrimitiveCraft)[]
---@field getCraftByName fun(self, craftName:string):CraftSystem.PrimitiveCraft
---@field getCraftsByGroup fun(self, craftGroup:string):CraftSystem.PrimitiveCraft[]
---@field getLearnedCrafts fun(self, playerName:string):(CraftSystem.PrimitiveCraft[]|CraftSystem.PrimitiveCraft)[]
local PrimitiveCraftHandler = extend(BaseCraftHandler, {})
---Register a primitive craft that does not require special interaction.
---@param craftName string
---@param def CraftSystem.PrimitiveCraftDef
function PrimitiveCraftHandler:registerCraft(craftName, def)
assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format(
craftName))
local group = 'craft_group:' .. (def.group or 'UNDEFINED')
def.group = group
local craft = PrimitiveCraft:new(craftName, def)
if self.craftsByGroup[group] == nil then
self.craftsByGroup[group] = {}
end
self.craftsByName[craftName] = craft
tableInsert(self.craftsByGroup[group], craft)
tableInsert(self.craftsList, craft)
end
core.register_on_mods_loaded(function()
for groupName, crafts in pairs(PrimitiveCraftHandler.craftsByGroup) do
tableSort(crafts, function(a, b)
if a.output < b.output then
return true
end
end)
if groupName ~= 'craft_group:UNDEFINED' then
tableInsert(PrimitiveCraftHandler.groupedCrafts, crafts)
else
PrimitiveCraftHandler.groupedCrafts = tableJoin(PrimitiveCraftHandler.groupedCrafts, crafts)
end
end
tableSort(PrimitiveCraftHandler.groupedCrafts, function(a, b)
local outputA = (a[1] and a[1].output) or a.output
local outputB = (b[1] and b[1].output) or b.output
if outputA < outputB then
return true
end
end)
end)
return PrimitiveCraftHandler

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__creature')
local require = modInfo.require
return require('Creature')

View File

@@ -0,0 +1 @@
name = smc__core__creature

View File

@@ -0,0 +1,109 @@
local getInstance, extend = Class.getInstance, Class.extend
local tableCopy, tableMerge = table.copy, table.merge
---@class Creature
---@field entityDef Creature.CreatureDefinition
---@field luantiDef EntityDefinition
---@field defaultDef Creature.CreatureDefinition
local Creature = {
defaultDef = {
settings = {
_name = '',
_add_mod_name = true,
initial_properties = {},
},
callbacks = {}
}
}
---@param entityDef Creature.CreatureDefinition
---@return EntityDefinition
local function entityDefToLuantiDef(entityDef)
entityDef = tableCopy(entityDef)
local s = entityDef.settings
local c = entityDef.callbacks or {}
---@type EntityDefinition
local luantiDef = tableMerge(s, c)
return luantiDef
end
---@param entityDef Creature.CreatureDefinition
---@return Creature
function Creature:new(entityDef)
-- Adding default parameters.
---@type Creature.CreatureDefinition
entityDef = tableMerge(entityDef, self.defaultDef, true)
-- The callback table may not be specified.
if entityDef.callbacks == nil then
---@type Creature.Callbacks
entityDef.callbacks = {}
end
local s = entityDef.settings
local c = entityDef.callbacks
-- Add the short mod name prefix to the entity name.
if s._add_mod_name then
s._name = Mod.getInfo().shortName .. ':' .. s._name
end
local onActivate = c.on_activate or function() end
-- We rewrite the entity initialization function so that custom fields
-- can be passed to it directly via `core.add_entity(pos, name, [staticdata])`.
c.on_activate = function(luaEntity, staticdata, dtime)
local initCustomFields = {}
if staticdata and staticdata ~= '' then
initCustomFields = core.deserialize(staticdata) or {}
end
-- We reset the fields that should not be overwritten.
initCustomFields.name = nil
initCustomFields.object = nil
---@type LuaEntity
self = tableMerge(self, initCustomFields)
-- If an initialization callback was specified for the entity, then we call it.
if c.on_activate ~= nil then
onActivate(luaEntity, staticdata, dtime)
end
end
---@type Creature
local instance = getInstance(self, {})
local luantiDef = entityDefToLuantiDef(entityDef)
instance.entityDef = entityDef
instance.luantiDef = luantiDef
core.register_entity(':'..s._name, luantiDef)
return instance
end
---Allows you to create a child class of an entity by specifying
---default parameters that will be added to the entity's parameters
---when an instance is received.
---@param defaultDef Creature.CreatureDefinition
---@return Creature
function Creature:getExtended(defaultDef)
-- Adding default parameters.
---@type Creature.CreatureDefinition
defaultDef = tableMerge(self.defaultDef, defaultDef)
---@type Creature
local ChildClass = extend(self, {
defaultDef = defaultDef,
})
return ChildClass
end
return Creature

View File

@@ -0,0 +1,72 @@
---@class Creature.Callbacks
local Callbacks = {}
---Called when the object is instantiated.
--- * `dtime_s` is the time passed since the object was unloaded,
---which can be used for updating the entity state.
---@type fun(self:LuaEntity, staticdata:string, dtime_s:number)?
Callbacks.on_activate = nil
---Called when the object is about to get removed or unloaded.
--- * `removal`: boolean indicating whether the object is about to get removed.
--- Calling `object:remove()` on an active object will call this with `removal=true`.
--- The mapblock the entity resides in being unloaded will call this with `removal=false`.
---
---Note that this won't be called if the object hasn't been activated in the first place.
---In particular, `core.clear_objects({mode = "full"})` won't call this,
---whereas `core.clear_objects({mode = "quick"})` might call this.
---@type fun(self:LuaEntity, removal:boolean)?
Callbacks.on_deactivate = nil
---Called on every server tick, after movement and collision processing.
--- * `dtime`: elapsed time since last call
--- * `s`: table with collision info (only available if `physical=true`)
---@type fun(self:LuaEntity, dtime:number, moveresult:table)? -- TODO: дописать более точный тип moveresult
Callbacks.on_step = nil
---Called when somebody punches the object.
---Note that you probably want to handle most punches using the automatic armor group system.
--- * `puncher`: an `ObjectRef `(can be `nil`)
--- * `time_from_last_punch`: Meant for disallowing spamming of clicks (can be `nil`).
--- * `tool_capabilities`: capability table of used item
--- * `dir`: unit vector of direction of punch. Always defined. Points from the puncher to the punched.
--- * `damage``: damage that will be done to entity.
---
---Can return `true` to prevent the default damage mechanism.
---@type (fun(self:LuaEntity, puncher:ObjectRef|Player|nil, time_from_last_punch:number|nil, tool_capabilities:table|nil, dir:vector, damage:number):boolean)? -- TODO: дописать более точный тип для tool_capabilities
Callbacks.on_punch = nil
---Called when the object dies.
--- * `killer`: an `ObjectRef` (can be `nil`)
---@type fun(self:LuaEntity, killer:ObjectRef|Player|nil)?
Callbacks.on_death = nil
---Called when `clicker` pressed the 'place/use' key while
---pointing to the object (not necessarily an actual rightclick)
--- * `clicker`: an `ObjectRef` (may or may not be a player)
---@type fun(self:LuaEntity, clicker:ObjectRef|Player)?
Callbacks.on_rightclick = nil
---Called after another object is attached to this object.
--- * `child`: an `ObjectRef` of the child
---@type fun(self:LuaEntity, child:ObjectRef)?
Callbacks.on_attach_child = nil
---Called after another object has detached from this object.
--- * `child`: an `ObjectRef` of the child
---@type fun(self:LuaEntity, child:ObjectRef)?
Callbacks.on_detach_child = nil
---Called after detaching from another object.
--- * `parent`: an ObjectRef from where it got detached
---
---**Note**: this is also called before removal from the world.
---@type fun(self:LuaEntity, parent)?
Callbacks.on_detach = nil
---Should return a string that will be passed to `on_activate` when the object
---is instantiated the next time.
---@type (fun(self:LuaEntity):string)?
Callbacks.get_staticdata = nil
return Callbacks

View File

@@ -0,0 +1,6 @@
---@class Creature.CreatureDefinition
---@field settings Creature.Settings
---@field callbacks Creature.Callbacks?
local CreatureDefinition = {}
return CreatureDefinition

View File

@@ -0,0 +1,9 @@
---A class that extends `LuaEntity` to annotate custom fields.
---
---**Only for EmmyLua.**
---@class Creature.LuaEntity : LuaEntity
---@field _name string
---@field _add_mod_name boolean
local LuaEntity = {}
return LuaEntity

View File

@@ -0,0 +1,14 @@
---@class Creature.Settings
local Settings = {}
---Registration name for the entity. Must be unique.
---@type string
Settings._name = nil
---Whether to add the mod name to the settings._name. Default: `true`
Settings._add_mod_name = nil
---@type ObjectProperties
Settings.initial_properties = nil
return Settings

View File

@@ -1 +0,0 @@
name = smc__core__entity

View File

@@ -1,5 +0,0 @@
local Enum = Mod:new()
Enum.Class = Enum.require('Enum')
Api.addModToGlobalSpace(Enum, 'Core.Enum')

View File

@@ -1,2 +0,0 @@
name = smc__core__enum
depends = smc__api__api_loader

View File

@@ -1,30 +0,0 @@
---Abstract class implementing enumeration. It is a table<ENUM_KEY, ENUM_KEY>. Read-only table!
---@abstract
---@class Enum
local Enum = {}
---@param enum table[]
---@return Enum
function Enum:new(enum)
local metaEnum = {}
-- Create table<ENUM_KEY, ENUM_KEY>
for _, v in ipairs(enum) do
metaEnum[v] = v
end
---@type Enum
local instance = setmetatable({}, {
__index = metaEnum,
__newindex = function()
error('The Enum table is read only!')
end,
__metatable = false
})
return instance
end
---@alias Enum.EnumKey string Key from enumeration
return Enum

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__formspec')
local require = modInfo.require
return require('Formspec')

View File

@@ -0,0 +1,2 @@
name = smc__core__formspec
depends = smc__system__system_loader

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
local Item = Mod:new()
local modInfo = Mod.getInfo('smc__core__item')
local require = modInfo.require
Item.Class = Item.require('Item')
Api.addModToGlobalSpace(Item, 'Core.Item')
return require('Item')

View File

@@ -0,0 +1,9 @@
# textdomain: item
Rarity=Редкость
common=простой
uncommon=необычный
distinguished=выдающийся
eminent=исключительный
prime=Превосходный
unique=Уникальный

View File

@@ -1,2 +1,2 @@
name = smc__core__item
depends = smc__api__api_loader, smc__core__enum, smc__core__item_factory
depends = smc__system__system_loader, smc__core__item_factory

View File

@@ -1,98 +1,219 @@
local modInfo = Mod.getInfo()
local require = modInfo.require
local getInstance, extend = Class.getInstance, Class.extend
local VisualEnum = require('Item.VisualEnum')
local tableCopy, tableMerge, colorize = table.copy, table.merge, core.colorize
local ItemFactory = Smc.requireItemFactory()
---Colors the title according to the rarity of the item.
---
---Note: that if `true`, the `_title_color` will be ignored.
local TITLE_RARITY_COLOR = true
---Shows rarity on a separate line.
local SHOW_RARITY = false
---Determines whether common rarity will be shown in item descriptions or not.
local SHOW_COMMON_RARITY = true
---Colors corresponding to the rarity color in the item description.
---@type table<Item.Rarity, ColorString>
local RARITY_COLORS = {
['common'] = '#C0C0C0',
['uncommon'] = '#7cd2e2',
['distinguished'] = '#7ce2da',
['eminent'] = '#44d1a9',
['prime'] = '#9CF0B1',
['unique'] = '#f4c95a'
}
---Whether to show the numeric index in the rarity description.
local SHOW_RARITY_INDEX = true
---@type table<Item.Rarity, integer>
local RARITY_INDEX = {
['common'] = 1,
['uncommon'] = 2,
['distinguished'] = 3,
['eminent'] = 4,
['prime'] = 5,
['unique'] = 0
}
---@class Item
---@field itemDef Item.ItemDefinition
---@field luantiDef table
---@field getVisual fun(): string
---@field luantiDef ItemDefinition
---@field getType fun():string
---@field defaultDef Item.ItemDefinition
local Item = {
defaultDef = {
settings = {
name = "",
title = "",
description = "",
name = '',
_title = '',
_description = '',
_title_color = '#FFFFFF',
_description_color = '#838383',
_rarity = 'common',
_add_mod_name = true,
stack_max = 128,
},
callbacks = {}
}
}
---Adds an item's rarity tag to the description.
---@param rarity Item.Rarity
---@param desc string
---@return string
local function addRarityToDesc(rarity, desc)
if not SHOW_RARITY then
return desc
end
if not SHOW_COMMON_RARITY and rarity == 'common' then
return desc
end
local S = core.get_translator('item')
local color = RARITY_COLORS[rarity]
local rarityString = S('Rarity')..': '..S(rarity)
if SHOW_RARITY_INDEX then
rarityString = rarityString..' ['..RARITY_INDEX[rarity]..']'
end
return desc..'\n'..colorize(color, rarityString)
end
---The alias `table.merge` for EmmyLua
---@type fun(...):(NodeDefinition|ItemDefinition)
local defMerge = function(...)
return table.merge(...)
return tableMerge(...)
end
---@param itemDef Item.ItemDefinition
---@return NodeDefinition|ItemDefinition
local function itemDefToLuantiDef(itemDef)
itemDef = table.copy(itemDef)
local modName = Mod.getInfo().shortName
local S = core.get_translator(modName)
local s = itemDef.settings
local c = itemDef.callbacks
local description = s.title .. "\n" .. s.description
s.title, s.description = nil, description
local luantiDef = defMerge(s, c)
local title, description = s._title, s._description
if title == nil or title == '' then
title = string.match(s.name, '%S:(%S+)')..'-title'
end
if description == nil or description == '' then
description = string.match(s.name, '%S:(%S+)')..'-desc'
end
assert(s._rarity ~= nil, 'The rarity of an item cannot be empty.')
if s._title_color ~= nil and s._description_color ~= nil then
if TITLE_RARITY_COLOR then
title = colorize(RARITY_COLORS[s._rarity], S(title))
else
title = colorize(s._title_color, S(title))
end
description = colorize(s._description_color, S(description))
else
error('Item description color parameters cannot be empty.')
end
local luantiDescription = addRarityToDesc(s._rarity, title..'\n '..description)
s._title = title
s._description = description
s.description = luantiDescription..core.get_background_escape_sequence('#110F13')
local luantiDef = defMerge(s, c, true)
return luantiDef
end
---@param luantiDef NodeDefinition|ItemDefinition
local function register3dItem(luantiDef)
local ld = luantiDef
local name = ld.name
ld.name = nil
---@param luantiDef NodeDefinition
local function registerNode(luantiDef)
local name = luantiDef.name
luantiDef.name = nil
core.register_node(':'..name, luantiDef)
end
---@param luantiDef ItemDefinition
local function registerFlatItem(luantiDef)
local ld = luantiDef
local name = ld.name
ld.name = nil
local function registerCraftitem(luantiDef)
local name = luantiDef.name
luantiDef.name = nil
core.register_craftitem(':'..name, luantiDef)
end
---@param luantiDef ItemDefinition
local function registerTool(luantiDef)
local name = luantiDef.name
luantiDef.name = nil
core.register_tool(':'..name, luantiDef)
end
---The alias `table.merge` for EmmyLua
---@type fun(...):(Item.ItemDefinition)
local defMerge = function(...)
return table.merge(...)
return tableMerge(...)
end
---@param itemDef Item.ItemDefinition
---@param itemDef Item.ItemDefinition|Node.NodeDefinition
---@return Item
function Item:new(itemDef)
---Adding default parameters
assert(itemDef.settings.description == nil,
'The item description was specified using `description`, not `_description`. '..
'Please note that the `description` field should not be used when registering an item. '..
'Use `_title` and `_description` instead.')
itemDef = tableCopy(itemDef)
-- Adding default parameters
itemDef = defMerge(itemDef, self.defaultDef, true)
local s = itemDef.settings
local shortModName = Mod.getInfo().shortName
if s._add_mod_name then
s.name = shortModName .. ':' .. s.name
end
---@type Item
local instance = setmetatable({}, {__index = self})
local instance = getInstance(self, {})
local luantiDef = itemDefToLuantiDef(itemDef)
local visual = itemDef.settings.visual
local type = itemDef.settings._type
if visual == nil then
visual = VisualEnum.ITEM_2D
if type == nil then
type = 'craftitem'
end
itemDef.settings.visual = nil
itemDef.settings._type = nil
if visual == VisualEnum.ITEM_3D then
register3dItem(luantiDef)
if type == 'node' then
registerNode(luantiDef)
elseif type == 'craftitem' then
registerCraftitem(luantiDef)
elseif type == 'tool' then
registerTool(luantiDef)
else
visual = VisualEnum.ITEM_2D
registerFlatItem(luantiDef)
error(('Unknown item type: `%s`.'):format(type))
end
function instance:getVisual()
return visual
function instance:getType()
return type
end
instance.itemDef = itemDef
instance.luantiDef = luantiDef
Smc.addRegisteredItem(shortModName, instance)
return instance
end
@@ -102,8 +223,10 @@ end
---@param defaultDef Item.ItemDefinition
---@return Item
function Item:getExtended(defaultDef)
defaultDef = defMerge(defaultDef, self.defaultDef, true)
---@type Item
local ChildClass = Mod:getClassExtended(self, {
local ChildClass = extend(self, {
defaultDef = defaultDef,
})
@@ -116,10 +239,12 @@ end
function Item:getFactory(defaultDef)
if defaultDef == nil then
defaultDef = self.defaultDef
else
defaultDef = defMerge(self.defaultDef, defaultDef, true)
end
---@type ItemFactory
local instance = Core.ItemFactory():new(self, defaultDef)
local instance = ItemFactory:new(self, defaultDef)
return instance
end

View File

@@ -1,8 +1,6 @@
---@class Item.Callbacks
local Callbacks = {}
-- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---Called when the 'place' key was pressed with the item in hand
---and pointing at a node.
---Shall place item and return the leftover itemstack

View File

@@ -0,0 +1,8 @@
---Rarity of items:
--- * `common`
--- * `uncommon`
--- * `distinguished`
--- * `eminent`
--- * `prime`
--- * `unique`
---@alias Item.Rarity 'common'|'uncommon'|'distinguished'|'eminent'|'prime'|'unique'

View File

@@ -3,21 +3,42 @@ local Settings = {}
---Technical name of the item. Must be unique and have the format `mod_name:item_name`
---@type string
Settings.name = ""
Settings.name = ''
---Item description. 1st line of item description.
---@type string?
Settings.title = nil
---Item description. The rest of item description.
---@type string?
Settings.description = nil
---Visual node type.
---Values ​​are specified via an enumeration `Item.VisualEnum`.
---@type Enum.EnumKey?
Settings.visual = ""
---Whether to add the mod name to the settings.name. Default: `true`
---@type boolean?
Settings._add_mod_name = nil
---Item description. 1st line of item description.
---@type string?
Settings._title = nil
---Item description. The rest of item description.
---@type string?
Settings._description = nil
---Item title color in description.
---
---Default: `#FFFFFF`
---@type ColorString?
Settings._title_color = nil
---Item description color in description.
---
---Default: `#C0C0C0`
---@type ColorString?
Settings._description_color = nil
---Visual node type.
---@type Item.Type?
Settings._type = nil
---Formal (lore) rarity of an item. Default `common`.
---@type Item.Rarity?
Settings._rarity = nil
---Table of groups-characteristics of Item.

View File

@@ -0,0 +1 @@
---@alias Item.Type 'craftitem'|'node'|'tool'

View File

@@ -1,9 +0,0 @@
---@class Item.VisualEnum : Enum
---@field ITEM_2D Enum.EnumKey
---@field ITEM_3D Enum.EnumKey
local VisualEnum = Core.Enum:getModClassInstance({
'ITEM_2D',
'ITEM_3D',
})
return VisualEnum

View File

@@ -1,5 +1,4 @@
local ItemFactory = Mod:new()
local modInfo = Mod.getInfo('smc__core__item_factory')
local require = modInfo.require
ItemFactory.Class = ItemFactory.require('ItemFactory')
Api.addModToGlobalSpace(ItemFactory, 'Core.ItemFactory')
return require('ItemFactory')

View File

@@ -1,2 +1,2 @@
name = smc__core__item_factory
depends = smc__api__api_loader
depends = smc__system__system_loader

View File

@@ -1,3 +1,5 @@
local getInstance = Class.getInstance
---@class ItemFactory
---@field defaultDef Item.ItemDefinition|Node.NodeDefinition
---@field itemClass Item|Node
@@ -8,10 +10,10 @@ local ItemFactory = {}
---@return ItemFactory
function ItemFactory:new(itemClass, defaultDef)
---@type ItemFactory
local instance = setmetatable({
local instance =getInstance(self, {
defaultDef = defaultDef,
itemClass = itemClass,
}, {__index = self})
})
return instance
end
@@ -23,22 +25,11 @@ local defMerge = function(...)
end
---@param itemDefs Item.ItemDefinition[]|Node.NodeDefinition[] List of nodes with parameters unique to them.
---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true`
function ItemFactory:registerItems(itemDefs, addModName)
if addModName == nil then
addModName = true
end
local modName = Mod.getInfo().shortName
function ItemFactory:registerItems(itemDefs)
---@param nodeDef Item.ItemDefinition | Node.NodeDefinition
for _, itemDef in ipairs(itemDefs) do
itemDef = defMerge(itemDef, self.defaultDef, true)
if addModName then
itemDef.settings.name = modName .. ':' .. itemDef.settings.name
end
self.itemClass:new(itemDef)
end
@@ -50,34 +41,20 @@ local defMerge = function(...)
return table.merge(...)
end
---@param shortNodeDefs table Table of the form `{ {name, title, description, tiles}, {name, title, description, tiles}, ...}`
---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true`
function ItemFactory:registerNodesByShortDef(shortNodeDefs, addModName)
if addModName == nil then
addModName = true
end
local modName = Mod.getInfo().shortName
---@param shortNodeDefs [string, (string[]|TileDefinition[])?][] Format list {{name, tiles}, {name, tiles}, ...}
function ItemFactory:registerNodesByShortDef(shortNodeDefs)
for _, shortNodeDef in ipairs(shortNodeDefs) do
---@type Node.NodeDefinition
local nodeDef = {
settings = {
name = shortNodeDef[1],
title = shortNodeDef[2],
description = shortNodeDef[3],
tiles = shortNodeDef[4]
tiles = shortNodeDef[2]
}
}
nodeDef = defMerge(nodeDef, self.defaultDef, true)
if addModName then
nodeDef.settings.name = modName .. ':' .. nodeDef.settings.name
end
self.itemClass:new(nodeDef)
end
end

View File

@@ -1,5 +1,4 @@
local MapGen = Mod:new()
local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
MapGen.Class = MapGen.require('MapGen')
Api.addModToGlobalSpace(MapGen, 'Core.MapGen')
return require('MapGen')

View File

@@ -1,2 +1,2 @@
name = smc__core__map_gen
depends = smc__api__api_loader, smc__game__items__rocks, smc__game__items__liquids
depends = smc__system__system_loader

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,7 @@
local id = core.get_content_id
local getInstance = Class.getInstance
---@class MapGen.Biome
---@field name string
---@field tempPoint number
@@ -5,12 +9,20 @@
---@field minY number
---@field maxY number
---@field groundNodes MapGen.Biome.GroundNodes
---@field groundNodesIDs MapGen.Biome.GroundNodesIDs
---@field soilHeight number
---@field generateRock fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)
---@field generateSoil fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)
---@field generateBottom fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)
---@field generateAir generateFunc
---@field generateCavernAir generateFunc
---@field generateWater generateFunc
---@field generateRock generateFunc
---@field generateTurf generateFunc
---@field generateSoil generateFunc
---@field generateBottom generateFunc
---@field postProcessing fun(self, mapGenerator:MapGen, factors:MapGen.factors, data:number[], index:number, x:number, y:number, z:number, nodeType:MapGen.nodeType, area:VoxelArea)?
local Biome = {}
---@alias generateFunc fun(self, mapGenerator:MapGen, factors:MapGen.factors, data:number[], index:number, x:number, y:number, z:number)
---Definition table for the `MapGen.Biome`.
---
---**Only for EmmyLua.**
@@ -21,44 +33,99 @@ local Biome = {}
---@field maxY number
---@field groundNodes MapGen.Biome.GroundNodes
---@field soilHeight number
---@field generateRock fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)?
---@field generateSoil fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)?
---@field generateBottom fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)?
---@field generateAir generateFunc?
---@field generateCavernAir generateFunc?
---@field generateWater generateFunc?
---@field generateRock generateFunc?
---@field generateTurf generateFunc?
---@field generateSoil generateFunc?
---@field generateBottom generateFunc?
---@field postProcessing fun(self, mapGenerator:MapGen, factors:MapGen.factors, data:number[], index:number, x:number, y:number, z:number, nodeType:MapGen.nodeType, area:VoxelArea)?
-- Default generate functions
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateRock = function(mapGenerator, biome, data, index, x, y, z)
--TODO: минимальную логику генерации прописать
local defaultGenerateAir = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = mapGenerator.nodeIDs.air
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateSoil = function(mapGenerator, biome, data, index, x, y, z)
--TODO: минимальную логику генерации прописать
local defaultGenerateCavernAir = function(self, mapGenerator, factors, data, index, x, y, z)
self:generateAir(mapGenerator, factors, data, index, x, y, z)
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateBottom = function(mapGenerator, biome, data, index, x, y, z)
--TODO: минимальную логику генерации прописать
local defaultGenerateWater = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = mapGenerator.nodeIDs.water
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateRock = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = self.groundNodesIDs.rock
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateTurf = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = self.groundNodesIDs.turf
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateSoil = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = self.groundNodesIDs.soil
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param factors MapGen.factors
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateBottom = function(self, mapGenerator, factors, data, index, x, y, z)
data[index] = self.groundNodesIDs.bottom
end
@@ -66,34 +133,65 @@ end
---@param def MapGen.BiomeDef
---@return MapGen.Biome
function Biome:new(name, def)
if def.generateAir == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateAir()` function. The default function is used.', name)
def.generateAir = defaultGenerateAir
end
if def.generateCavernAir == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateCavernAir()` function. The default function is used.', name)
def.generateCavernAir = defaultGenerateCavernAir
end
if def.generateWater == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateWater()` function. The default function is used.', name)
def.generateWater = defaultGenerateWater
end
if def.generateRock == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateRock()` function. The default function is used.', name)
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateRock()` function. The default function is used.', name)
def.generateRock = defaultGenerateRock
end
if def.generateTurf == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateTurf()` function. The default function is used.', name)
def.generateTurf = defaultGenerateTurf
end
if def.generateSoil == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateSoil()` function. The default function is used.', name)
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateSoil()` function. The default function is used.', name)
def.generateSoil = defaultGenerateSoil
end
if def.generateBottom == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateBottom()` function. The default function is used.', name)
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateBottom()` function. The default function is used.', name)
def.generateBottom = defaultGenerateBottom
end
local groundNodesIDs = {}
-- Converting node names to IDs
for k, v in pairs(def.groundNodes) do
groundNodesIDs[k] = id(v)
end
---@type MapGen.Biome
local instance = setmetatable({
name = name,
tempPoint = def.tempPoint,
humidityPoint = def.humidityPoint,
minY = def.minY,
maxY = def.maxY,
groundNodes = def.groundNodes,
soilHeight = def.soilHeight,
generateRock = def.generateRock or defaultGenerateRock,
generateSoil = def.generateSoil or defaultGenerateSoil,
generateBottom = def.generateBottom or defaultGenerateBottom,
}, {__index = self})
local instance = getInstance(self, {})
instance.name = name
instance.tempPoint = def.tempPoint
instance.humidityPoint = def.humidityPoint
instance.minY = def.minY
instance.maxY = def.maxY
instance.groundNodes = def.groundNodes
instance.groundNodesIDs = groundNodesIDs
instance.soilHeight = def.soilHeight
instance.generateAir = def.generateAir
instance.generateCavernAir = def.generateCavernAir
instance.generateWater = def.generateWater
instance.generateRock = def.generateRock
instance.generateSoil = def.generateSoil
instance.generateTurf = def.generateTurf
instance.generateBottom = def.generateBottom
instance.postProcessing = def.postProcessing
return instance
end

View File

@@ -4,6 +4,8 @@
---@class MapGen.Biome.GroundNodes
---@field turf string The soil covering the surface of the biome
---@field soil string The soil beneath the turf. The height of this layer depends on `Biome.soilHeight`
---@field rock string The rock found beneath the soil of a biome.
---@field bottom string Covering the bottom of reservoirs.
local GroundNodes = {}
return GroundNodes

View File

@@ -0,0 +1,11 @@
--- Only for EmmyLua
---**Only for EmmyLua.**
---@class MapGen.Biome.GroundNodesIDs
---@field turf number The soil covering the surface of the biome
---@field soil number The soil beneath the turf. The height of this layer depends on `Biome.soilHeight`
---@field rock number The rock found beneath the soil of a biome.
---@field bottom number Covering the bottom of reservoirs.
local GroundNodes = {}
return GroundNodes

View File

@@ -1,8 +1,11 @@
local mathMin, mathMax, mathAbs
= math.min, math.max, math.abs
local mathMin, mathMax, mathAbs, mathClamp
= math.min, math.max, math.abs, math.clamp
local getInstance = Class.getInstance
---@class MapGen.Cavern
---@field name string
---@field isRegional boolean
---@field minY number
---@field maxY number
---@field smoothDistance number
@@ -16,6 +19,7 @@ local Cavern = {}
---
---**Only for EmmyLua.**
---@class MapGen.CavernDef
---@field isRegional boolean?
---@field minY number
---@field maxY number
---@field noiseParams NoiseParams
@@ -50,13 +54,14 @@ function Cavern:new(name, def)
end
---@type MapGen.Cavern
local instance = setmetatable({
local instance = getInstance(self, {
name = name,
minY = def.minY,
maxY = def.maxY,
smoothDistance = def.smoothDistance,
threshold = def.threshold,
}, {__index = self})
isRegional = def.isRegional or false,
})
function instance:getNoise()
return _noise
@@ -77,32 +82,49 @@ function Cavern:new(name, def)
return instance
end
---@param y number
---@param minY number
---@param maxY number
---@param smoothDistance number
---@param distance number
---@return number
local function calcCavernWeight(y, smoothDistance, minY, maxY)
local maxDist = maxY - y
local minDist = y - minY
return mathMax(0, mathMin(maxDist / smoothDistance, minDist / smoothDistance, 1))
function Cavern:calcCavernWeight(distance)
return mathClamp(distance / self.smoothDistance, 0, 1)
end
---Returns `true` if there is a cavern at the specified coordinates.
---@param x number
---@param y number
---@param z number
---@param x integer
---@param y integer
---@param z integer
---@param distance number
---@return boolean
function Cavern:isCavern(x, y, z)
function Cavern:isCavern(x, y, z, distance)
local minY, maxY = self.minY, self.maxY
if y >= maxY or y <= minY then
return false
end
distance = mathMin(maxY - y, y - minY, distance)
local noise = self:getNoise()
local weight = self:calcCavernWeight(distance)
return noise:get_3d({x = x, y = y, z = z}) * weight > self.threshold
end
---Returns `true` if there is a cavern at the specified coordinates.
---@param x integer
---@param y integer
---@param z integer
---@return boolean
function Cavern:isLayeredCavern(x, y, z)
local minY, maxY = self.minY, self.maxY
if y > maxY or y < minY then
return false
end
local distance = mathMin(maxY - y, y - minY)
local noise = self:getNoise()
local weight = calcCavernWeight(y, self.smoothDistance, minY, maxY)
local weight = self:calcCavernWeight(distance)
return noise:get_3d({x = x, y = y, z = z}) * weight > self.threshold
end

View File

@@ -1,3 +1,5 @@
local getInstance = Class.getInstance
---**NOT IMPLEMENTED**
---@class MapGen.Decoration
local Decoration = {}
@@ -5,9 +7,9 @@ local Decoration = {}
---@return MapGen.Decoration
function Decoration:new()
---@type MapGen.Decoration
local instance = setmetatable({
local instance = getInstance(self, {
}, {__index = self})
})
return instance
end

View File

@@ -1,19 +1,22 @@
---@class MapGen.Triangulation.Edge
local getInstance = Class.getInstance
---@class MapGen.Edge
---@field p1 MapGen.Peak
---@field p2 MapGen.Peak
---@field vec vector
local Edge = {}
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@return MapGen.Triangulation.Edge
---@return MapGen.Edge
function Edge:new( p1, p2 )
---@type MapGen.Triangulation.Edge
local instance = setmetatable({
---@type MapGen.Edge
local instance = getInstance(self, {
p1 = p1,
p2 = p2
p2 = p2,
vec = p2.pos - p1.pos
},
{
__index = self,
__tostring = self.toString,
__eq = self.eq
})
@@ -28,14 +31,14 @@ function Edge:toString()
end
---Returns true if the edges are equivalent.
---@param other MapGen.Triangulation.Edge
---@param other MapGen.Edge
---@return boolean
function Edge:eq(other)
return self.p1 == other.p1 and self.p2 == other.p2
end
---Returns true if the edges are similar.
---@param other MapGen.Triangulation.Edge
---@param other MapGen.Edge
---@return boolean
function Edge:same(other)
return (self.p1 == other.p1 and self.p2 == other.p2)
@@ -45,14 +48,14 @@ end
---Returns the length of an edge.
---@return number
function Edge:length()
return (self.p1.getPeakPos() - self.p2.getPeakPos()):length()
return (self.p1.pos - self.p2.pos):length()
end
---Returns the vector of the point located in the middle of the edge.
---@return vector
function Edge:getMidPoint()
local pos1 = self.p1:getPeakPos()
local pos2 = self.p2:getPeakPos()
local pos1 = self.p1.pos
local pos2 = self.p2.pos
return (pos1 + pos2 )/2
end

View File

@@ -7,18 +7,17 @@ local Peak = require('MapGen.Peak')
---Allows you to create a `MapGen.Peak` without specifying a noise parameter.
---
---**WARNING: MUST NOT BE PARTICIPATED IN GENERATION**
---@class MapGen.Triangulation.FakePeak : MapGen.Peak
---@class MapGen.FakePeak : MapGen.Peak
---@field id number
---@field getPeakPos fun():vector
local FakePeak = Mod:getClassExtended(Peak, {})
local FakePeak = Class.extend(Peak, {})
---Returns a fake `MapGen.Peak` that has no noise parameters.
---Note that the initialized peak should not be used in generation.
---@param peakPos vector
---@param peakPos MapPosition|vector
---@return MapGen.Peak
function FakePeak:new(peakPos)
---@diagnostic disable-next-line: missing-fields, param-type-not-match
local instance = Peak:new(peakPos, {}, 1)
local instance = Peak:new({pos = peakPos, color = '#000000'})
return instance
end

View File

@@ -1,63 +1,350 @@
local getInstance = Class.getInstance
local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
---@type MapGen.Peak
local Peak = require('MapGen.Peak')
---@type MapGen.Triangle
local Triangle = require('MapGen.Triangle')
---@class MapGen.Layer
---@field name string
---@field minY number
---@field maxY number
---@field minY integer
---@field maxY integer
---@field minTemp integer
---@field maxTemp integer
---@field minHumidity integer
---@field maxHumidity integer
---@field waterLevel integer
---@field calcTemp fun(self:MapGen.Layer, value:number, height:number):number
---@field calcHumidity fun(self:MapGen.Layer, value:number, height:number):number
---@field peaksList MapGen.Peak[]
---@field peaksByPos table<string, MapGen.Peak>
---@field noisesByColor table<MapGen.Layer.Category, table<ColorString, ValueNoise>>
---@field noisesParamsByColor table<MapGen.Layer.Category, table<ColorString, NoiseParams>>
---@field biomesByName table<string, MapGen.Biome>
---@field biomesList MapGen.Biome[]
---@field biomesDiagram table
---@field biomesGorizontalScattering integer
---@field biomesVerticalScattering integer
---@field cavernsByName table<string, MapGen.Cavern>
---@field cavernsList MapGen.Cavern[]
---@field regionsByName table<string, MapGen.Region>
---@field trianglesList MapGen.Triangle[]
---@field tetrahedronsList MapGen.Tetrahedron[]
local Layer = {
peaksList = {},
peaksByPos = {},
noisesByColor = {
landscape = {},
temp = {},
humidity = {},
},
noisesParamsByColor = {
landscape = {},
temp = {},
humidity = {},
},
biomesByName = {},
biomesList = {},
biomesDiagram = {},
cavernsByName = {},
cavernsList = {},
regionsByName = {},
trianglesList = {},
tetrahedronsList = {},
}
---Definition table for the `MapGen.Layer`.
---
---**Only for EmmyLua.**
---@class MapGen.LayerDef
---@field minY integer
---@field maxY integer
---@field minTemp integer
---@field maxTemp integer
---@field minHumidity integer
---@field maxHumidity integer
---@field waterLevel? integer
---@field calcTemp (fun(self:MapGen.Layer, value:number, height:number):number)?
---@field calcHumidity (fun(self:MapGen.Layer, value:number, height:number):number)?
---@field biomesGorizontalScattering integer?
---@field biomesVerticalScattering integer?
---@field triangulationLandscapeFile string
---@field triangulationTempFile string
---@field triangulationHumidityFile string
---@field landscapeMapScale number
---@field tempMapScale number
---@field humidityMapScale number
---@param self MapGen.Layer
---@param value number
---@param height number
---@return number
local function defaultCalcFunc(self, value, height)
return value
end
---Checks `def` for compliance with `MapGen.PeakDef` and creates a new peak
---if a peak with such coordinates has not yet been registered or returns an existing one.
---
---**Note:** If the colors of the new peak and the existing one at the same coordinates
---are different, an error will be called.
---@param def MapGen.PeakDef
---@param scale number
---@return MapGen.Peak
function Layer:registerPeak(def, scale)
assert(def.pos ~= nil)
assert(def.pos.x ~= nil)
assert(def.pos.z ~= nil)
assert(def.color ~= nil)
assert(type(def.color) == 'string')
def.pos.x = def.pos.x * scale
def.pos.z = def.pos.z * scale
def.pos.y = 0
local positionStr = core.pos_to_string(def.pos)
local peak = self.peaksByPos[positionStr]
if peak == nil then
peak = Peak:new(def)
self.peaksByPos[positionStr] = peak
elseif peak.color ~= def.color then
error('There cannot be two peaks with the same coordinates but different colors.')
end
return peak
end
function Layer:initTrianglesNeighbours()
local triangles = self.trianglesList
for _, triangle in pairs(triangles) do
for _, id in ipairs(triangle.neighboursIDs) do
table.insert(triangle.neighbours, triangles[id])
end
end
end
---@param fileName string
---@param category MapGen.Layer.Category
---@param scale number
function Layer:getTriaglesFromFile(fileName, category, scale)
local file = io.open(core.get_modpath(core.get_current_modname())..'/maps/'..fileName, 'r')
assert(file ~= nil)
local json = core.parse_json(file:read('*a')) or {}
file:close()
local triangles = json.triangles
assert(triangles ~= nil)
for _, tr in ipairs(triangles) do
local p1 = self:registerPeak( tr.vertices[1], scale)
local p2 = self:registerPeak( tr.vertices[2], scale)
local p3 = self:registerPeak( tr.vertices[3], scale)
local triangle = Triangle:new(tr.id,p1, p2, p3, tr.adjacent_triangle_ids)
self:addTriangle(category, triangle)
end
end
---@param name string
---@param minY number
---@param maxY number
---@param def MapGen.LayerDef
---@return MapGen.Layer
function Layer:new(name, minY, maxY)
function Layer:new(name, def)
if def.calcTemp == nil then
Logger.infoLog('MapGen.Layer: The `%s` layer does not have a specified `calcTemp()` function. The default function is used.', name)
def.calcTemp = defaultCalcFunc
end
if def.calcHumidity == nil then
Logger.infoLog('MapGen.Layer: The `%s` layer does not have a specified `calcHumidity()` function. The default function is used.', name)
def.calcHumidity = defaultCalcFunc
end
---@type MapGen.Layer
local instance = setmetatable({
name = name,
minY = minY,
maxY = maxY,
}, {__index = self})
local instance = getInstance(self, {})
instance.name = name
instance.minY = def.minY
instance.maxY = def.maxY
instance.minTemp = def.minTemp
instance.maxTemp = def.maxTemp
instance.minHumidity = def.minHumidity
instance.maxHumidity = def.maxHumidity
instance.waterLevel = def.waterLevel or 0
instance.calcTemp = def.calcTemp
instance.calcHumidity = def.calcHumidity
instance.biomesGorizontalScattering = def.biomesGorizontalScattering or 0
instance.biomesVerticalScattering = def.biomesVerticalScattering or 0
instance:getTriaglesFromFile(
def.triangulationLandscapeFile,
'landscape',
def.landscapeMapScale)
instance:getTriaglesFromFile(
def.triangulationTempFile,
'temp',
def.tempMapScale)
instance:getTriaglesFromFile(
def.triangulationHumidityFile,
'humidity',
def.humidityMapScale)
instance:initTrianglesNeighbours()
return instance
end
---A category of noise that affects specific map generation objects.
---@alias MapGen.Layer.Category 'landscape'|'temp'|'humidity'
---Adds a triangle to the `Layer.trianglesList`
---@param category MapGen.Layer.Category
---@param triangle MapGen.Triangle
function Layer:addTriangle(category, triangle)
local triangles = self.trianglesList
if triangles ~= nil then
triangles[triangle.id] = triangle
else
error(('There is no peak category named %s.'):format(category))
end
end
---Adds a peak to the `Layer.peaksList`
---@param category MapGen.Layer.Category
---@param peak MapGen.Peak
function Layer:addPeak(peak)
function Layer:addPeak(category, peak)
table.insert(self.peaksList, peak)
end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param pos Position Coordinate of the desired peak.
---@return MapGen.Peak?
function Layer:getPeakByPos(pos)
local positionStr = core.pos_to_string(pos)
local peak = self.peaksByPos[positionStr]
return peak
end
---Adds a NoiseParams color to the `Layer.noisesParamsByColor`
---@param category MapGen.Layer.Category
---@param color ColorString
---@param noiseParams NoiseParams
function Layer:addNoiseParamsColor(category, color, noiseParams)
color = Smc.fixColorString(color)
local noisesParams = self.noisesParamsByColor
if category == 'landscape' then
assert(noisesParams.landscape[color] == nil, ('The color `%s` already exists.'):format(color))
noisesParams.landscape[color] = noiseParams
elseif category == 'temp' then
assert(noisesParams.temp[color] == nil, ('The color `%s` already exists.'):format(color))
noisesParams.temp[color] = noiseParams
elseif category == 'humidity' then
assert(noisesParams.humidity[color] == nil, ('The color `%s` already exists.'):format(color))
noisesParams.humidity[color] = noiseParams
else
error(('There is no color category named `%s`.'):format(category))
end
end
---Returns noise corresponding to a color.
---@param category MapGen.Layer.Category
---@param color ColorString
---@return ValueNoise
function Layer:getNoiseByColor(category, color)
color = Smc.fixColorString(color)
local noises = self.noisesByColor
if category == 'landscape' then
assert(noises.landscape[color] ~= nil, ('`%s` color does not exist.'):format(color))
return noises.landscape[color]
elseif category == 'temp' then
assert(noises.temp[color] ~= nil, ('`%s` color does not exist.'):format(color))
return noises.temp[color]
elseif category == 'humidity' then
assert(noises.humidity[color] ~= nil, ('`%s` color does not exist.'):format(color))
return noises.humidity[color]
else
error(('There is no color category named `%s`.'):format(category))
end
end
---Adds a biome to the `Layer.biomesByName` & `Layer.biomesList`
---@param biomeName string
---@param biome MapGen.Biome
function Layer:addBiome(biomeName, biome)
assert(self.biomesByName[biomeName] == nil,
('A biome named `%s` already exists in the `%s` layer.'):format(
biomeName, self.name))
self.biomesByName[biomeName] = biome
table.insert(self.biomesList, biome)
end
---Returns a biome by name, if there is no such biome, it will raise an error.
---@param biomeName string
---@return MapGen.Biome
function Layer:getBiomeByName(biomeName)
local biome = self.biomesByName[biomeName]
assert(biome ~= nil, ('Biome named `%s` does not exist in the `%s` layer.'):format(
biomeName, self.name))
return biome
end
---Adds a cavern to the `Layer.cavernsByName` & `Layer.cavernsList`
---@param cavernName string
---@param cavern MapGen.Cavern
function Layer:addCavern(cavernName, cavern)
assert(self.cavernsByName[cavernName] == nil,
('A cavern named `%s` already exists in the `%s` layer.'):format(
cavernName, self.name))
self.cavernsByName[cavernName] = cavern
table.insert(self.cavernsList, cavern)
end
---Returns a cavern by name, if there is no such cavern, it will raise an error.
---@param cavernName string
---@return MapGen.Cavern
function Layer:getCavernByName(cavernName)
local cavern = self.cavernsByName[cavernName]
assert(cavern ~= nil, ('Cavern named `%s` does not exist in the `%s` layer.'):format(
cavernName, self.name))
return cavern
end
function Layer:addRegion(regionName, region)
assert(self.regionsByName[regionName] == nil,
('A region named `%s` already exists in the `%s` layer.'):format(
regionName, self.name))
self.regionsByName[regionName] = region
--table.insert(self.regionsList, region)
end
---Returns a region by name, if there is no such region, it will raise an error.
---@param regionName string
---@return MapGen.Region
function Layer:getRegionByName(regionName)
local region = self.regionsByName[regionName]
assert(region ~= nil, ('Region named `%s` does not exist in the `%s` layer.'):format(
regionName, self.name))
return region
end
---@param height number
---@param biomesList MapGen.Biome[]
---@return string[], MapGen.Biome[]
@@ -77,6 +364,19 @@ local function getBiomesNamesByHeight(height, biomesList)
return biomesNames, biomes
end
---Initializes noise for generation.
---
---Should only be called after the mapgen object has been loaded.
function Layer:initNoises()
local noises = self.noisesByColor
for category, noisesParams in pairs(self.noisesParamsByColor) do
for color, noiseParams in pairs(noisesParams) do
noises[category][color] = core.get_value_noise(noiseParams)
end
end
end
---Initialization of the biome diagram using the Voronoi method.
function Layer:initBiomesDiagram()
local diagram = self.biomesDiagram
@@ -98,10 +398,10 @@ function Layer:initBiomesDiagram()
end
pastBiomesNames = newBiomesNames
for temp = 0, 100 do
for temp = self.minTemp, self.maxTemp do
diagram[height][temp] = {}
for humidity = 0, 100 do
for humidity = self.minHumidity, self.maxHumidity do
local minDistance = math.huge
local closestBiome = nil

View File

@@ -1,94 +1,56 @@
local getInstance = Class.getInstance
---@class MapGen.Peak
---@field id number
---@field getPeakPos fun():vector
---@field getMultinoiseParams fun():MapGen.Peak.MultinoiseParams
---@field getMultinoise fun():MapGen.Peak.Multinoise
---@field initMultinoise fun()
---@field getGroups fun():table<string, number>
---@field pos vector
---@field color ColorString
---@field getGroups fun(self):table<string, number>
---@field addGroups fun(self, groups:table<string, number>)
local Peak = {
id = 0,
}
-- --- Helpers functions ---
---@param multinoiseParams MapGen.Peak.MultinoiseParams
---@return MapGen.Peak.Multinoise
local function multinoiseParamsToMultinoise(multinoiseParams)
---@diagnostic disable-next-line: missing-fields
---@type MapGen.Peak.Multinoise
local multinoise = {}
for noiseName, noiseParams in pairs(multinoiseParams) do
multinoise[noiseName] = core.get_value_noise(noiseParams)
end
return multinoise
end
-- --- Class registration ---
---@param peakPos vector
---@param multinoiseParams MapGen.Peak.MultinoiseParams
---@param groups? table<string, number>
---@return MapGen.Peak
function Peak:new(peakPos, multinoiseParams, groups)
---@type vector
local _peakPos = peakPos
---@type MapGen.Peak.MultinoiseParams
local _multinoiseParams = multinoiseParams
---Definition table for the `MapGen.Peak`.
---
---**Only for EmmyLua.**
---@class MapGen.PeakDef
---@field pos MapPosition|vector
---@field color ColorString
---@field groups? table<string, number>
---@param def MapGen.PeakDef
---@return MapGen.Peak
function Peak:new(def)
local _color = def.color
local _groups
if groups == nil then
if def.groups == nil then
_groups = {}
else
_groups = groups
_groups = def.groups
end
---@diagnostic disable-next-line: missing-fields
---@type MapGen.Peak.Multinoise
local _multinoise = {} -- note: must be empty until luanti mapgen objects are loaded.
---@type MapGen.Peak
local instance = setmetatable({},
local instance = getInstance(self,{},
{
__index = self,
__tostring = self.toString,
__eq = self.eq
})
function instance:getPeakPos()
return vector.new(_peakPos.x, _peakPos.y, _peakPos.z)
end
function instance:getMultinoiseParams()
return _multinoiseParams
end
function instance:getMultinoise()
if table.is_empty(_multinoise) then
error('Attempt to get `MapGen.Triangulation.FakePeak` noise (empty noise).')
end
return _multinoise
end
function instance:initMultinoise()
if not table.is_empty(_multinoise) then
Logger.warningLog('Multinoise has already been initialized. Re-initialization is not recommended.')
end
if table.is_empty(_multinoiseParams) then
error('Attempt to initialize `MapGen.Triangulation.FakePeak` noise (noise parameter empty).')
end
_multinoise = multinoiseParamsToMultinoise(_multinoiseParams)
end
instance.pos = vector.new(def.pos)
instance.color = def.color
function instance:getGroups()
return _groups
return table.copy_with_metatables(_groups)
end
function instance:addGroups(groups)
-- Groups that cannot be overwritten
groups.is2d = nil
groups.is3d = nil
_groups = table.merge(_groups, groups, true)
end
return instance
@@ -97,7 +59,7 @@ end
---Returns a string describing the object in a readable form.
---@return string
function Peak:toString()
local pos = self:getPeakPos()
local pos = self.pos
return ('Peak (%s) x: %.2f y: %.2f z: %.2f'):format( self.id, pos.x, pos.y, pos.z)
end
@@ -105,8 +67,8 @@ end
---@param other MapGen.Peak
---@return boolean
function Peak:eq(other)
local pos1 = self:getPeakPos()
local pos2 = other:getPeakPos()
local pos1 = self.pos
local pos2 = other.pos
return pos1.x == pos2.x and pos1.z == pos2.z
end

View File

@@ -1,10 +0,0 @@
---For EmmyLua only
---**For EmmyLua only**
---@class MapGen.Peak.Multinoise
---@field landscapeNoise ValueNoise
---@field tempNoise ValueNoise
---@field humidityNoise ValueNoise
local Multinoise = {}
return Multinoise

View File

@@ -1,10 +0,0 @@
---For EmmyLua only
---**For EmmyLua only**
---@class MapGen.Peak.MultinoiseParams
---@field landscapeNoise NoiseParams
---@field tempNoise NoiseParams
---@field humidityNoise NoiseParams
local MultinoiseParams = {}
return MultinoiseParams

View File

@@ -0,0 +1,112 @@
local mathClamp, mathHuge, mathSqrt = math.clamp, math.huge, math.sqrt
local getInstance = Class.getInstance
---@class MapGen.Region
---@field name string
---@field vertices MapPosition[]
local Region = {}
---@class MapGen.RegionDef
---@field vertices MapPosition[]
---@param def MapGen.RegionDef
---@return MapGen.Region
function Region:new(name, def)
local instance = getInstance(self, {
name = name,
vertices = def.vertices
})
return instance
end
---Calculate squared distance from point to line segment.
---@param px integer
---@param pz integer
---@param x1 integer
---@param z1 integer
---@param x2 integer
---@param z2 integer
---@return number
local function calcDistanceSq(px, pz, x1, z1, x2, z2)
local dx = x2 - x1
local dz = z2 - z1
local len_sq = dx * dx + dz * dz
-- Degenerate segment (a single point):
if len_sq == 0 then
return (px - x1)^2 + (pz - z1)^2
end
-- Project point onto line, clamped to segment [0, 1]
local param = mathClamp(((px - x1) * dx + (pz - z1) * dz) / len_sq, 0, 1)
-- Closest point on segment
local closest_x = x1 + param * dx
local closest_z = z1 + param * dz
return (px - closest_x)^2 + (pz - closest_z)^2
end
---Checks if a point is inside a `MapGen.Region` (2D check using x and z coordinates).
---@param point MapPosition
---@return boolean, number?
function Region:pointInRegion(point)
local vertices = self.vertices
local px, pz = point.x, point.z
local n = #vertices
if n < 3 then
return false
end
-- Calculate minimum squared distance to any edge
local minDistanceSq = mathHuge
for i = 1, n do
local j = (i % n) + 1
local v1, v2 = vertices[i], vertices[j]
if v1 == nil or v2 == nil then error() end
local dist_sq = calcDistanceSq(px, pz, v1.x, v1.z, v2.x, v2.z)
if dist_sq < minDistanceSq then
minDistanceSq = dist_sq
end
end
local minDistance = mathSqrt(minDistanceSq)
-- Check if point is on edge (within small epsilon)
if minDistance <= 1e-9 then
return true, minDistance
end
-- Ray casting algorithm: count edge crossings
local inside = false
for i = 1, n do
local j = (i % n) + 1
local vi, vj = vertices[i], vertices[j]
if vi == nil or vj == nil then error() end
local xi, zi = vi.x, vi.z
local xj, zj = vj.x, vj.z
-- Check if horizontal ray from point (going +x) crosses this edge
if ((zi > pz) ~= (zj > pz)) and
(px < (xj - xi) * (pz - zi) / (zj - zi) + xi) then
inside = not inside
end
end
if inside then
return true, minDistance
else
return false
end
end
return Region

View File

@@ -0,0 +1,60 @@
local id = core.get_content_id
local getInstance = Class.getInstance
---@class MapGen.StaticLayer
---@field name string
---@field minY number
---@field maxY number
---@field staticNode string
---@field staticNodeID number
---@field generateStaticNode fun(self, mapGenerator:MapGen, data:number[], index:number, x:number, y:number, z:number)
local StaticLayer = {}
---Definition table for the `MapGen.StaticLayer`.
---
---**Only for EmmyLua.**
---@class MapGen.StaticLayerDef
---@field minY number
---@field maxY number
---@field staticNode string
---@field generateStaticNode fun(self, mapGenerator:MapGen, data:number[], index:number, x:number, y:number, z:number)
---@param self MapGen.StaticLayer
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateStaticNode = function(self, mapGenerator, data, index, x, y, z)
data[index] = self.staticNodeID
end
---@param name string
---@param def MapGen.StaticLayerDef
---@return MapGen.StaticLayer
function StaticLayer:new(name, def)
assert(def.maxY > def.minY, 'maxY there should be more minY')
if def.generateStaticNode == nil then
Logger.infoLog('MapGen.StaticLayer: The `%s` static layer does not have a specified `generateStaticNode()` function. The default function is used.', name)
def.generateStaticNode = defaultGenerateStaticNode
end
local staticNodeID = id(def.staticNode)
---@type MapGen.StaticLayer
local instance = getInstance(self, {
name = name,
minY = def.minY,
maxY = def.maxY,
staticNode = def.staticNode,
staticNodeID = staticNodeID,
generateStaticNode = def.generateStaticNode
})
return instance
end
return StaticLayer

View File

@@ -1,152 +0,0 @@
local mathAbs = math.abs
local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
---@type MapGen.Triangle
local Triangle = require('MapGen.Triangle')
---@type MapGen.Triangulation.Edge
local Edge = require('MapGen.Triangulation.Edge')
---@type MapGen.Triangulation.FakePeak
local FakePeak = require('MapGen.Triangulation.FakePeak')
---@class MapGen.Tetrahedron
---@field p1 MapGen.Peak
---@field p2 MapGen.Peak
---@field p3 MapGen.Peak
---@field p4 MapGen.Peak
---@field h1 MapGen.Triangulation.Edge
---@field h2 MapGen.Triangulation.Edge
---@field h3 MapGen.Triangulation.Edge
---@field h4 MapGen.Triangulation.Edge
---@field f1 MapGen.Triangle
---@field f2 MapGen.Triangle
---@field f3 MapGen.Triangle
---@field f4 MapGen.Triangle
local Tetrahedron = {}
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@param p3 MapGen.Peak
---@param p4 MapGen.Peak
---@return MapGen.Tetrahedron
function Tetrahedron:new(p1, p2, p3, p4)
local instance = setmetatable({
p1 = p1,
p2 = p2,
p3 = p3,
p4 = p4,
h1 = self:getHeight(p1, p2, p3, p4),
h2 = self:getHeight(p2, p3, p4, p1),
h3 = self:getHeight(p3, p4, p1, p2),
h4 = self:getHeight(p4, p1, p2, p3),
f1 = Triangle:new(p1, p2, p3),
f2 = Triangle:new(p1, p2, p4),
f3 = Triangle:new(p1, p3, p4),
f4 = Triangle:new(p2, p3, p4),
}, {
__index = self,
__tostring = self.toString
})
return instance
end
---Returns a string describing the object in a readable form.
---@return string
function Tetrahedron:toString()
return ('Tetrahedron: \n %s\n %s\n %s\n %s'):format(
tostring(self.p1.getPeakPos()),
tostring(self.p2.getPeakPos()),
tostring(self.p3.getPeakPos()),
tostring(self.p4.getPeakPos())
)
end
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@param p3 MapGen.Peak
---@param p4 MapGen.Peak
function Tetrahedron:getHeight(p1, p2, p3, p4)
local pos1 = p1:getPeakPos()
local pos2 = p2:getPeakPos()
local pos3 = p3:getPeakPos()
local pos4 = p4:getPeakPos()
-- Векторы, лежащие в плоскости
local AB = pos3 - pos2
local AC = pos4 - pos2
-- Нормаль к плоскости
local normal = AB:cross(AC)
local normal_length = normal:length()
-- Если плоскость вырождена (точки на одной прямой)
if normal_length < 1e-10 then
return nil -- или другая обработка ошибки
end
-- Вектор от точки на плоскости к нашей точке
local AP = pos1 - pos2
-- Расстояние от точки до плоскости
local distance = AP:dot(normal) / normal_length
-- Проекция точки на плоскость (вектор!)
local projection = pos1 - (normal * (distance / normal_length))
return Edge:new(p1, FakePeak:new(projection))
end
---Returns the center of the circumscribed sphere.
---@return vector
function Tetrahedron:getCircumSphereCenter()
local pos1 = self.p1.getPeakPos()
local pos2 = self.p2.getPeakPos()
local pos3 = self.p3.getPeakPos()
local pos4 = self.p4.getPeakPos()
local a = pos2 - pos1
local b = pos3 - pos1
local c = pos4 - pos1
local a2 = a:dot(a)
local b2 = b:dot(b)
local c2 = c:dot(c)
local cross_bc = b:cross(c)
local cross_ca = c:cross(a)
local cross_ab = a:cross(b)
local det = a:dot(b:cross(c)) * 2
if mathAbs(det) < 0 then
return (pos1 + pos2 + pos3 + pos4) / 4
end
local center = pos1 + (cross_bc * a2 + cross_ca * b2 + cross_ab * c2) / det
return center
end
---Returns the radius of the circumscribed sphere.
---@return number
function Tetrahedron:getCircumSphereRadius()
local center = self:getCircumSphereCenter()
local pos1 = self.p1.getPeakPos()
return (pos1 - center):length()
end
---Checks whether a given point lies within the circumscribed sphere of a tetrahedron.
---@param p MapGen.Peak
function Tetrahedron:inCircumSphere(p)
local pos = p.getPeakPos()
local c = self:getCircumSphereCenter()
local r = self:getCircumSphereRadius()
local distance = (pos - c):length()
return distance <= r
end
return Tetrahedron

View File

@@ -1,13 +1,15 @@
local mathSqrt, mathAbs
= math.sqrt, math.abs
local getInstance = Class.getInstance
local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
---@type MapGen.Triangulation.Edge
local Edge = require('MapGen.Triangulation.Edge')
---@type MapGen.Triangulation.FakePeak
local FakePeak = require('MapGen.Triangulation.FakePeak')
---@type MapGen.Edge
local Edge = require('MapGen.Edge')
---@type MapGen.FakePeak
local FakePeak = require('MapGen.FakePeak')
-- --- Helpers functions ---
@@ -27,9 +29,9 @@ end
---@param p3 MapGen.Peak
---@return boolean
local function isFlatAngle(p1, p2, p3)
local pos1 = p1:getPeakPos()
local pos2 = p2:getPeakPos()
local pos3 = p3:getPeakPos()
local pos1 = p1.pos
local pos2 = p2.pos
local pos3 = p3.pos
local vec1 = pos1 - pos2 -- Vector from p2 to p1
local vec2 = pos3 - pos2 -- Vector from p2 to p3
@@ -54,27 +56,49 @@ end
-- --- Class registration ---
---Adjacent triangles:
--- * `t1` with a common side p1-p2
--- * `t2` with a common side p2-p3
--- * `t3` with a common side p3-p1
---@alias MapGen.Triangle.Neighbours {t1:MapGen.Triangle?,t2:MapGen.Triangle?,t3:MapGen.Triangle?}
---@class MapGen.Triangle
---@field id integer
---@field p1 MapGen.Peak
---@field p2 MapGen.Peak
---@field p3 MapGen.Peak
---@field e1 MapGen.Triangulation.Edge
---@field e2 MapGen.Triangulation.Edge
---@field e3 MapGen.Triangulation.Edge
---@field h1 MapGen.Triangulation.Edge
---@field h2 MapGen.Triangulation.Edge
---@field h3 MapGen.Triangulation.Edge
local Triangle = {}
---@field e1 MapGen.Edge
---@field e2 MapGen.Edge
---@field e3 MapGen.Edge
---@field h1 MapGen.Edge
---@field h2 MapGen.Edge
---@field h3 MapGen.Edge
---@field neighboursIDs integer[]
---@field neighbours MapGen.Triangle[]
---@field color ColorString?
local Triangle = {
neighbours = {}
}
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@param p3 MapGen.Peak
---@return MapGen.Triangle
function Triangle:new( p1, p2, p3 )
function Triangle:new(id, p1, p2, p3, neighboursIDs)
assert(not isFlatAngle(p1, p2, p3), ("angle (p1, p2, p3) is flat:\n %s\n %s\n %s")
:format(tostring(p1), tostring(p2), tostring(p3)))
local instance = setmetatable({
---@type ColorString?
local color = nil
local c1, c2, c3 = p1.color, p2.color, p3.color
if c1 == c2 and c2 == c3 and c3 == c1 then
color = c1
end
local instance = getInstance(self, {
id = id,
p1 = p1,
p2 = p2,
p3 = p3,
@@ -83,10 +107,11 @@ function Triangle:new( p1, p2, p3 )
h3 = Triangle:getHeight(p3, p1, p2),
e1 = Edge:new(p1, p2),
e2 = Edge:new(p2, p3),
e3 = Edge:new(p3, p1)
e3 = Edge:new(p3, p1),
neighboursIDs = neighboursIDs,
color = color,
},
{
__index = self,
__tostring = self.toString,
__eq = self.eq
})
@@ -98,9 +123,9 @@ end
---@return string
function Triangle:toString()
return ('Triangle: \n %s\n %s\n %s'):format(
tostring(self.p1.getPeakPos()),
tostring(self.p2.getPeakPos()),
tostring(self.p3.getPeakPos())
tostring(self.p1.pos),
tostring(self.p2.pos),
tostring(self.p3.pos)
)
end
@@ -123,14 +148,14 @@ end
---Returns the coordinates of the triangle's center.
---@return vector
function Triangle:getCenter()
local pos1 = self.p1:getPeakPos()
local pos2 = self.p2:getPeakPos()
local pos3 = self.p3:getPeakPos()
local pos1 = self.p1.pos
local pos2 = self.p2.pos
local pos3 = self.p3.pos
return (pos1 + pos2 + pos3) / 3
end
---Returns the area of ​​a triangle.
---Returns the area of a triangle.
---@return number
function Triangle:getArea()
local a, b, c = self:getSidesLength()
@@ -142,11 +167,11 @@ end
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@param p3 MapGen.Peak
---@return MapGen.Triangulation.Edge
---@return MapGen.Edge
function Triangle:getHeight(p1, p2, p3)
local pos1 = p1:getPeakPos()
local pos2 = p2:getPeakPos()
local pos3 = p3:getPeakPos()
local pos1 = p1.pos
local pos2 = p2.pos
local pos3 = p3.pos
local v = pos3 - pos2
---@type vector
@@ -168,11 +193,11 @@ end
---@param p1 MapGen.Peak
---@param p2 MapGen.Peak
---@param p3 MapGen.Peak
---@return MapGen.Triangulation.Edge
---@return MapGen.Edge
function Triangle:getHeight2D(p1, p2, p3)
local pos1 = p1:getPeakPos()
local pos2 = p2:getPeakPos()
local pos3 = p3:getPeakPos()
local pos1 = p1.pos
local pos2 = p2.pos
local pos3 = p3.pos
pos1.y = 0
pos2.y = 0
@@ -203,9 +228,9 @@ end
---that is, the calculation is performed on the projection of the triangle XZ.
---@return number, number, number
function Triangle:getSidesLength2D()
local pos1 = self.p1:getPeakPos()
local pos2 = self.p2:getPeakPos()
local pos3 = self.p3:getPeakPos()
local pos1 = self.p1.pos
local pos2 = self.p2.pos
local pos3 = self.p3.pos
pos1.y = 0
pos2.y = 0
@@ -220,9 +245,9 @@ end
---that is, the calculation is performed on the projection of the triangle XZ.
---@return vector
function Triangle:getCircumCenter2D()
local pos1 = self.p1:getPeakPos()
local pos2 = self.p2:getPeakPos()
local pos3 = self.p3:getPeakPos()
local pos1 = self.p1.pos
local pos2 = self.p2.pos
local pos3 = self.p3.pos
local D = ( pos1.x * (pos2.z - pos3.z) +
pos2.x * (pos3.z - pos1.z) +
@@ -260,6 +285,8 @@ function Triangle:getCircumCircle2D()
return c, r
end
---@alias MapGen.Triangle.CircumCircleEnum 'IN'|'BEHIND'|'ON'
---Checks if a given point lies into the triangle circumcircle.
---
---Note: This function does not take into account the Y-coordinate,
@@ -267,12 +294,13 @@ end
---@param p MapGen.Peak
---@return boolean
function Triangle:inCircumCircle2D(p)
local pos = p:getPeakPos()
local pos = p.pos
local c, r = self:getCircumCircle2D()
local distance = (c - pos):length()
return distance <= r
end

View File

@@ -1,269 +0,0 @@
-- Tringulation lib
-- Original code: https://github.com/iskolbin/Triangulation/blob/master/Triangulation.lua
-- Date of copying: 07.11.2025
-- Commit: e8d26241767cd6af377b5eda0c1e27122b6afe8a
-- Main changes:
-- * refactoring code to our standard;
-- * splitting code into different files (classes);
-- * Adapting the code to the mapgen concept;
-- * Adding tetrahedralization;
local assert, mathMax, tableRemove
= assert, math.max, table.remove
local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
---@type MapGen.Triangle
local Triangle = require('MapGen.Triangle')
---@type MapGen.Tetrahedron
local Tetrahedron = require('MapGen.Tetrahedron')
---@type MapGen.Triangulation.FakePeak
local FakePeak = require('MapGen.Triangulation.FakePeak')
---@class MapGen.Triangulation
---@field convexMultiplier number
local Triangulation = {
convexMultiplier = 1e3,
}
---The Delaunay method divides a plane into triangles based on a list of their vertices.
---
---Doesn't take into account the Y coordinate of the vertices.
---That is, all triangles that don't lie in the XZ plane will be projected onto it.
---
---Vertices that do not have a `is2d` group will not participate in the triangulation.
---@param vertices table<integer, MapGen.Peak>
function Triangulation.triangulate( vertices )
vertices = table.copy_with_metatables(vertices)
-- Only peaks with a `is2d` group can be triangulated.
for i, vertex in ipairs(vertices) do
if vertex:getGroups().is2d == nil then
table.remove(vertices, i)
end
end
local nvertices = #vertices
assert( nvertices > 2, "Cannot triangulate, needs more than 3 vertices" )
if nvertices == 3 then
return {Triangle:new(vertices[1], vertices[2], vertices[3])}
end
local minPos = vertices[1].getPeakPos()
local minX, minY = minPos.x, minPos.z
local maxX, maxY = minX, minY
for i = 1, nvertices do
local vertex = vertices[i]
local vertexPos = vertex.getPeakPos()
vertex.id = i
if vertexPos.x < minX then
minX = vertexPos.x
end
if vertexPos.z < minY then
minY = vertexPos.z
end
if vertexPos.x > maxX then
maxX = vertexPos.x
end
if vertexPos.z > maxY then
maxY = vertexPos.z
end
end
---Finding the vertices of a supertriangle
local convex_mult = Triangulation.convexMultiplier
local dx, dy = (maxX - minX) * convex_mult, (maxY - minY) * convex_mult
local deltaMax = mathMax(dx, dy)
local midx, midy = (minX + maxX) * 0.5, (minY + maxY) * 0.5
local p1 = FakePeak:new(vector.new( midx - 2 * deltaMax,0, midy - deltaMax ))
local p2 = FakePeak:new(vector.new(midx,0, midy + 2 * deltaMax ))
local p3 = FakePeak:new( vector.new(midx + 2 * deltaMax,0, midy - deltaMax ))
p1.id, p2.id, p3.id = nvertices + 1, nvertices + 2, nvertices + 3
vertices[p1.id], vertices[p2.id], vertices[p3.id] = p1, p2, p3
---@type MapGen.Triangle[]
local triangles = {Triangle:new( vertices[nvertices + 1], vertices[nvertices + 2], vertices[nvertices + 3] )}
for i = 1, nvertices do
---@type MapGen.Triangulation.Edge[]
local edges = {}
-- Finding bad triangles.
for j = #triangles, 1, -1 do
local curTriangle = triangles[j]
if curTriangle:inCircumCircle2D(vertices[i]) then
edges[#edges + 1] = curTriangle.e1
edges[#edges + 1] = curTriangle.e2
edges[#edges + 1] = curTriangle.e3
tableRemove( triangles, j )
end
end
-- Removing duplicate edges.
for j = #edges - 1, 1, -1 do
for k = #edges, j + 1, -1 do
if edges[j] and edges[k] and edges[j]:same(edges[k]) then
tableRemove( edges, j )
tableRemove( edges, k-1 )
end
end
end
-- Create new triangles.
for j = 1, #edges do
triangles[#triangles + 1] = Triangle:new(edges[j].p1, edges[j].p2, vertices[i])
end
end
-- Remove tetrahedra associated with the vertices of a supertriangle.
for i = #triangles, 1, -1 do
local triangle = triangles[i]
if triangle.p1.id > nvertices or triangle.p2.id > nvertices or triangle.p3.id > nvertices then
tableRemove( triangles, i )
end
end
-- Removing the vertices of a super supertriangle.
for _ = 1,3 do
tableRemove( vertices )
end
return triangles
end
---The Delaunay method divides space into tetrahedra based on a list of their vertices.
---
---Vertices that do not have a `is3d` group will not participate in the triangulation.
---@param vertices table<integer, MapGen.Peak>
function Triangulation.tetrahedralize(vertices)
vertices = table.copy_with_metatables(vertices)
-- Only peaks with a `is3d` group can be triangulated.
for i, vertex in ipairs(vertices) do
if vertex:getGroups().is3d == nil then
table.remove(vertices, i)
end
end
local nvertices = #vertices
assert(nvertices > 3, "Cannot tetrahedralize, needs more than 4 vertices")
if nvertices == 4 then
return {Tetrahedron:new(vertices[1], vertices[2], vertices[3], vertices[4])}
end
local minPos = vertices[1].getPeakPos()
local minX, minY, minZ = minPos.x, minPos.y, minPos.z
local maxX, maxY, maxZ = minX, minY, minZ
for i = 1, nvertices do
local vertex = vertices[i]
local vertexPos = vertex.getPeakPos()
vertex.id = i
if vertexPos.x < minX then
minX = vertexPos.x
end
if vertexPos.y < minY then
minY = vertexPos.y
end
if vertexPos.z < minZ then
minZ = vertexPos.z
end
if vertexPos.x > maxX then
maxX = vertexPos.x
end
if vertexPos.y > maxY then
maxY = vertexPos.y
end
if vertexPos.z > maxZ then
maxZ = vertexPos.z
end
end
-- Finding the vertices of a supertetrahedron
local convex_mult = Triangulation.convexMultiplier
local dx, dy, dz = (maxX - minX) * convex_mult, (maxY - minY) * convex_mult, (maxZ - minZ) * convex_mult
local deltaMax = mathMax(dx, dy, dz)
local midx, midy, midz = (minX + maxX) * 0.5, (minY + maxY) * 0.5, (minZ + maxZ) * 0.5
local p1 = FakePeak:new(vector.new(midx - 2 * deltaMax, midy - deltaMax, midz - deltaMax))
local p2 = FakePeak:new(vector.new(midx + 2 * deltaMax, midy - deltaMax, midz - deltaMax))
local p3 = FakePeak:new(vector.new(midx, midy + 2 * deltaMax, midz - deltaMax))
local p4 = FakePeak:new(vector.new(midx, midy, midz + 2 * deltaMax))
p1.id, p2.id, p3.id, p4.id = nvertices + 1, nvertices + 2, nvertices + 3, nvertices + 4
vertices[p1.id], vertices[p2.id], vertices[p3.id], vertices[p4.id] = p1, p2, p3, p4
---@type MapGen.Tetrahedron[]
local tetrahedrons = {Tetrahedron:new(p1, p2, p3, p4)}
for i = 1, nvertices do
---@type MapGen.Triangle[]
local faces = {}
-- Finding bad tetrahedrons.
for j = #tetrahedrons, 1, -1 do
local curTetrahedron = tetrahedrons[j]
if curTetrahedron:inCircumSphere(vertices[i]) then
faces[#faces + 1] = curTetrahedron.f1
faces[#faces + 1] = curTetrahedron.f2
faces[#faces + 1] = curTetrahedron.f3
faces[#faces + 1] = curTetrahedron.f4
tableRemove(tetrahedrons, j)
end
end
-- Removing duplicate faces.
for j = #faces - 1, 1, -1 do
for k = #faces, j + 1, -1 do
if faces[j] and faces[k] and faces[j]:same(faces[k]) then
tableRemove( faces, j )
tableRemove( faces, k-1 )
end
end
end
-- Create new tetrahedrons.
for j = 1, #faces do
tetrahedrons[#tetrahedrons + 1] = Tetrahedron:new(faces[j].p1, faces[j].p2, faces[j].p3, vertices[i])
end
end
-- Remove tetrahedra associated with the vertices of a supertetrahedron.
for i = #tetrahedrons, 1, -1 do
local tetrahedron = tetrahedrons[i]
if tetrahedron.p1.id > nvertices or tetrahedron.p2.id > nvertices or tetrahedron.p3.id > nvertices or tetrahedron.p4.id > nvertices then
tableRemove( tetrahedrons, i )
end
end
-- Removing the vertices of a supertetrahedron.
for i = 1, 4 do
tableRemove( vertices )
end
return tetrahedrons
end
return Triangulation

View File

@@ -0,0 +1,101 @@
-- A method for converting an image with colored dots (pixels) into a Lua table grouped by color.
-- Author: @ssdaniel24 (github)
---Table with color as key and value is table with coordinates of dots. Note: coords begin from 1,1 (not 0,0).
---Example of table:
---```lua
---{
--- 'size': { h=256, w=256 },
--- '#fff': { {x=1,y=1}, {x=2,y=2}, ... },
--- '#ff0': { {x=3,y=3}, {x=4,y=4}, ... },
--- ...
---}
---```
---@alias ColoredDotsTable table<string,table>
---@param uintb string unsigned int bytes
---@return number
local function uintb2num(uintb)
local num = 0
local len = string.len(uintb)
for i = 1,len do
num = num*256 + string.byte(uintb, i)
end
return num
end
---Converts (scaling) 16-bit unsigned integer to 8-bit unsigned integer.
---Why? Because hex codes of colors are 8-bit: #ffffff -> ff = 256 (8 bit). Not 65536 (16 bit).
---@param num number 16-bit number
---@return number 8-bit number
local function uint16ToUint8(num)
return math.floor(num / 256)
end
---Converts given farbfeld image to ColoredDotsTable.
---Farbfeld format:
---```
---╔════════╤═════════════════════════════════════════════════════════╗
---║ Bytes │ Description ║
---╠════════╪═════════════════════════════════════════════════════════╣
---║ 8 │ 'farbfeld' magic value ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ 4 │ 32-Bit BE unsigned integer (width) ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ 4 │ 32-Bit BE unsigned integer (height) ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ [2222] │ 4x16-Bit BE unsigned integers [RGBA] / pixel, row-major ║
---╚════════╧═════════════════════════════════════════════════════════╝
---```
---[tools/farbfeld | suckless.org software that sucks less](https://tools.suckless.org/farbfeld/)
---@param filepath string image in farbfeld format
---@param backgroundColor string? ColorString, will be ignored while processing image. Default: `#000000FF`
---@return ColoredDotsTable
local function ff2luat(filepath, backgroundColor)
local file = io.open(filepath, 'rb')
if not file then error('Can\'t open farbfeld image: ' .. dump(filepath)) end
local ff = file:read('*a') -- binary!
file:close()
-- TODO: make it decompressing gzip format -> https://en.wikipedia.org/wiki/Gzip
-- I should skip 10 bytes in a beginning, read how many extra fields after it, skip them too, and skip last 8 bytes
-- (read wiki for information).
-- if filepath:sub(-3) == '.gz' then ff = core.decompress(ff, 'deflate') end
if not ff:sub(1,8) == 'farbfeld' then error('Not farbfeld image: ' .. dump(filepath)) end
if not backgroundColor then backgroundColor = '#000000FF' end
--HACK: normalizing colorstring for future string comparison ('#000' -> '#000000FF')
backgroundColor = Smc.fixColorString(backgroundColor)
---@type ColoredDotsTable
local dots = { size = { w = uintb2num(ff:sub(9,12)), h = uintb2num(ff:sub(13,16)) } }
local cursor
for i = 1,dots.size.h do
for j = 1,dots.size.w do
cursor = 16 + ((i-1)*dots.size.w + j-1)*8 + 1
local colorT = {
r = uint16ToUint8(uintb2num(ff:sub(cursor, cursor+1))),
g = uint16ToUint8(uintb2num(ff:sub(cursor+2,cursor+3))),
b = uint16ToUint8(uintb2num(ff:sub(cursor+4,cursor+5))),
a = uint16ToUint8(uintb2num(ff:sub(cursor+6,cursor+7)))
}
---@type string @ColorString
local color = core.colorspec_to_colorstring(colorT) or ''
if color ~= backgroundColor then
if not dots[color] then
dots[color] = {}
end
table.insert(dots[color], { x=j, y=i })
end
end
end
return dots
end
return ff2luat

View File

@@ -1,5 +1,4 @@
local Node = Mod:new()
local modInfo = Mod.getInfo('smc__core__node')
local require = modInfo.require
Node.Class = Node.require('Node')
Api.addModToGlobalSpace(Node, 'Core.Node')
return require('Node')

View File

@@ -1,18 +1,99 @@
---@type Item.VisualEnum
local VisualEnum = Core.Item.require('Item.VisualEnum')
local Item, ItemFactory = Smc.requireItem(), Smc.requireItemFactory()
---@class Node : Item
---@field defaultDef Node.NodeDefinition
local Node = Core.Item:getModClassExtended({})
local Node = Class.extend(Item, {})
---The alias `table.merge` for EmmyLua
---@type fun(...):(Node.NodeDefinition)
local defMerge = function(...)
return table.merge(...)
end
---@param nodeDef Node.NodeDefinition
local function registerSlab(nodeDef)
nodeDef = table.copy_with_metatables(nodeDef)
local settings = nodeDef.settings
assert(settings.groups ~= nil)
settings._title = nil
settings._description = nil
settings.name = settings.name..'_slab'
settings.node_box = {
type = 'fixed',
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
}
settings.drawtype = 'nodebox'
settings.paramtype = 'light'
settings.paramtype2 = 'facedir'
settings.groups['segments'] = nil
settings.groups['slabs'] = 1
if nodeDef.callbacks ~= nil then
nodeDef.callbacks.on_place = core.rotate_and_place
else
nodeDef.callbacks = {on_place = core.rotate_and_place}
end
Node:new(nodeDef)
end
---@param nodeDef Node.NodeDefinition
local function registerStair(nodeDef)
nodeDef = table.copy_with_metatables(nodeDef)
local settings = nodeDef.settings
assert(settings.groups ~= nil)
settings._title = nil
settings._description = nil
settings.name = settings.name..'_stair'
settings.node_box = {
type = 'fixed',
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.0, 0.5},
{-0.5, 0.0, 0.0, 0.5, 0.5, 0.5},
},
}
settings.drawtype = 'nodebox'
settings.paramtype = 'light'
settings.paramtype2 = 'facedir'
settings.groups['segments'] = nil
settings.groups['slabs'] = 1
if nodeDef.callbacks ~= nil then
nodeDef.callbacks.on_place = core.rotate_and_place
else
nodeDef.callbacks = {on_place = core.rotate_and_place}
end
Node:new(nodeDef)
end
---@param nodeDef Node.NodeDefinition
---@return Node
function Node:new(nodeDef)
nodeDef.settings.visual = VisualEnum.ITEM_3D
-- Adding default parameters.
nodeDef = defMerge(nodeDef, self.defaultDef, true)
local settings = nodeDef.settings
settings._type = 'node'
-- Registration of segmented blocks.
-- If you specify a specific group with a specific index for a node,
-- the slabs and stairs will be registered automatically.
local segmentsIndex = settings.groups and settings.groups['segments']
if segmentsIndex == 1 then
-- Only slabs
registerSlab(nodeDef)
elseif segmentsIndex == 2 then
-- Only stairs
registerStair(nodeDef)
elseif segmentsIndex == 3 then
-- Slabs & stairs
registerSlab(nodeDef)
registerStair(nodeDef)
end
---@type Node
local instance = Core.Item:getModClassInstance(nodeDef)
local instance = Item:new(nodeDef)
return instance
end
@@ -22,8 +103,10 @@ end
---@param defaultDef Node.NodeDefinition
---@return Node
function Node:getExtended(defaultDef)
defaultDef = defMerge(defaultDef, self.defaultDef, true)
---@type Node
local ChildClass = Mod:getClassExtended(self, {
local ChildClass = Class.extend(self, {
defaultDef = defaultDef,
})
@@ -36,10 +119,12 @@ end
function Node:getFactory(defaultDef)
if defaultDef == nil then
defaultDef = self.defaultDef
else
defaultDef = defMerge(self.defaultDef, defaultDef, true)
end
---@type ItemFactory
local instance = Core.ItemFactory:getModClassInstance(self, defaultDef)
local instance = ItemFactory:new(self, defaultDef)
return instance
end

View File

@@ -1,8 +1,8 @@
---@type Item.Callbacks
local ItemCallbacks = Core.Item.require('Item.Callbacks')
local ItemCallbacks = Mod.getInfo('smc__core__item').require('Item.Callbacks')
---@class Node.Callbacks : Item.Callbacks
local Callbacks = Mod:getClassExtended(ItemCallbacks, {})
local Callbacks = Class.extend(ItemCallbacks, {})
---Node constructor; called after adding node.
---Can set up metadata and stuff like that.

View File

@@ -1,8 +1,8 @@
---@type Item.Settings
local ItemSettings = Core.Item.require('Item.Settings')
local ItemSettings = Mod.getInfo('smc__core__item').require('Item.Settings')
---@class Node.Settings : Item.Settings
local Settings = Mod:getClassExtended(ItemSettings, {})
local Settings = Class.extend(ItemSettings, {})
---See "Node drawtypes"
---@type string?

4
mods/CORE/Plant/init.lua Normal file
View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__plant')
local require = modInfo.require
return require('Plant')

2
mods/CORE/Plant/mod.conf Normal file
View File

@@ -0,0 +1,2 @@
name = smc__core__plant
depends = smc__core__node

Some files were not shown because too many files have changed in this diff Show More