Compare commits

...

304 commits
v0.5.3 ... main

Author SHA1 Message Date
Ukendio
07593a4b99 Removed some dead code
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-10-14 00:45:16 +02:00
Ukendio
3f47ea922e Simpler scheduler 2025-10-14 00:41:34 +02:00
Ukendio
57e653fa78 Update replication demo
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-10-04 19:06:27 +02:00
Ukendio
698854d11b Observers should handle non queried pairs in :with
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-29 23:05:50 +02:00
dai
9514fb758a
Fix line endings (#280)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-22 14:08:38 +02:00
dai
e2ab3be3e5
Make optionals not required in bulk_insert (#281)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
* Allow any amount of undefined in bulk_insert

* Also handle unknown
2025-09-21 19:11:14 +02:00
dai
35cb0bca4e
Make World.contains a number->Entity typeguard (#279)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-09-21 14:13:59 +02:00
Ukendio
7e1f43aff5 Fix without terms for ob::observer and also add bunch of tests
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-20 02:35:47 +02:00
Ukendio
690e9ec4d7 Add 0 term cached queries
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-18 13:15:05 +02:00
Ukendio
8ed8c2a0e0 Add granular testing
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-16 11:14:13 +02:00
Ukendio
23bf021f01 Handle wildcard pairs in observers 2025-09-16 10:36:02 +02:00
Ukendio
4ed2fb7a40 observers should use filter_with
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-09-16 00:28:08 +02:00
Ukendio
e16e4a04e4 Enlist starting archetypes 2025-09-15 23:15:12 +02:00
Ukendio
456713c2d5 Change Observers to support cleanups and :with/without
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-09-15 16:42:48 +02:00
Ukendio
3dacb2af80 Remove focus
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-09-14 19:59:38 +02:00
PepeElToro41
1eecaac96f
fix types (#275)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-09-09 13:12:15 +02:00
Axen
d8b2d36c52
Fix bulk_insert not ensuring that archetype ids are sorted (#277)
* Fix bulk_insert not ensuring archetype ids are sorted

* Add test case
2025-09-09 13:11:55 +02:00
Ukendio
af093713b4 Add examples
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-30 16:12:14 +02:00
Ukendio
549fe97622 Inline world_remove 2025-08-30 14:43:52 +02:00
Ukendio
b0e73857b9 Cleanup tests 2025-08-30 14:43:34 +02:00
Ukendio
917c951d55 Remove eagerly 2025-08-30 13:47:08 +02:00
Ukendio
037035a9a1 Revert :clear to previous behaviour 2025-08-29 17:01:36 +02:00
Ukendio
29a66d92c2 Add component trait lazily
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-26 23:15:48 +02:00
Ukendio
5de842d144 query should use internal world type
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-23 18:33:53 +02:00
Ukendio
9d1665944e world:added should not union the parameterized type with nil 2025-08-22 18:02:58 +02:00
Ukendio
8ace046470 Optimize queries 2025-08-22 17:54:35 +02:00
dai
0874e426af
Fix bulk_insert with moving archetypes (#272)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* Fix bulk_insert with moving archetypes

* Reword message
2025-08-21 21:32:11 +02:00
dai
51b09549db
Add record types (#271)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
* Add record typings

* Correct
2025-08-20 22:37:32 +02:00
dai
a6c2d7152e
Allow tags in bulk_insert (#269) 2025-08-20 22:30:43 +02:00
Ukendio
2d9432ab7a Bump package versions
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-08-20 01:17:24 +02:00
Ukendio
96446f4a31 Fix 9+ term queries and cascaded deletion bug with different archetype 2025-08-20 01:15:30 +02:00
dai
bd00edc8c0
Separate Iter from IterFn (#267)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* Separate Iter from IterFn

* Clean up
2025-08-17 21:59:06 +02:00
dai
0bc1848554
Correct Archetype field types (#268) 2025-08-17 21:58:41 +02:00
dai
65a27a798a
Separate undefined components and tags (#266)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-12 20:39:04 +02:00
Six
ac4441eb84
roblox-ts: Fix columns_map for easier lookups (#263)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* feat: retype archetype columns_map based on query

* feat: move InferComponents into Iter
2025-08-10 18:13:13 +02:00
Laptev Stanislav
f031dcee8d
docs(api): consolidate and clarify contains method documentation (#264)
Remove duplicate contains method section and update description to be more precise about checking both entities and components. Also fix example code references to use contains instead of has for consistency.
2025-08-10 18:12:50 +02:00
Ukendio
1d650d12e9 Fix backwards edge traversal for exclusive relationships 2025-08-10 16:52:08 +02:00
Ukendio
8f95309871 Improve relationship performance
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-07 18:53:50 +02:00
Ukendio
0b6bfea5c8 Return nil if nth is over count
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-08-02 23:57:50 +02:00
Ukendio
3cfce10a4a Increment component records after registering
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-08-02 18:58:19 +02:00
Ukendio
add9ad3939 Support setting signal on cached Relation
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-08-02 06:20:53 +02:00
Ukendio
4153a7cdfe Monitors and observers need to able to accept pair terms
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-29 21:08:23 +02:00
Ukendio
4230a0a797 Version 2025-07-29 21:07:59 +02:00
dai
499afc20cd
Add rbxts typings for signals (#260)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* Add rbxts typings for signals

* Correct arguments
2025-07-27 17:31:31 +02:00
Ukendio
f284de6ec1 Simplying 2025-07-27 17:07:41 +02:00
Ukendio
abc0b1ec22 Fix typos 2025-07-27 17:05:15 +02:00
Marcus
b521fe750a
Bump versions (#259) 2025-07-27 14:39:43 +02:00
EncodedVenom
998b1d3528
Update query.md - formatting
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-26 18:55:38 -04:00
EncodedVenom
0606bf70f0
Merge pull request #258 from daimond113/fix/remove-entity-type-generic
Remove data generic from entity in hooks
2025-07-26 18:48:23 -04:00
daimond113
f2a803c0d8
Remove data generic from entity in hooks 2025-07-27 00:13:14 +02:00
Ukendio
3e46b723e9 Clarify exists usage
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-26 02:50:24 +02:00
Ukendio
3ab1d970e2 Remove dead links 2025-07-26 02:45:13 +02:00
Ukendio
3e2d40e706 Make a table for cleanup 2025-07-26 02:41:40 +02:00
Ukendio
1c2dee57d3 Add some examples 2025-07-26 02:41:18 +02:00
Ukendio
3777585677 Address docs issues 2025-07-26 02:09:28 +02:00
Ukendio
f792c98585 Bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-24 04:57:06 +02:00
Ukendio
7b43748f18 Fix types issues 2025-07-24 02:25:56 +02:00
Ukendio
666a3ef6de Fix inner types 2025-07-24 02:04:36 +02:00
Ukendio
69911093a3 No need to check for 0 anymore
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-23 00:38:16 +02:00
Ukendio
59df0bf2a3 Bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-19 14:30:48 +02:00
Ukendio
3e995c9d7d Fix iterator not returning correct column for 8+ overloads 2025-07-19 14:29:36 +02:00
Ukendio
78fe5338cf index component record after archetype gets created
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-18 16:53:32 +02:00
Ukendio
ca0689c92b Bump 2025-07-18 15:14:39 +02:00
Ukendio
117a5e0ca7 Fix on_remove hook not called on cached edge 2025-07-18 15:13:59 +02:00
Ukendio
d99088ea1e Bump rc
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-18 00:38:39 +02:00
Ukendio
012b5e2bfa Make cleanup conditions 2025-07-18 00:37:58 +02:00
Ukendio
54b21001ab Bump versions 2025-07-17 23:45:56 +02:00
Ukendio
9c09686a69 always check OnDelete condition 2025-07-17 23:45:04 +02:00
Ukendio
ebc39c8b28 Remove debug msgs
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-17 19:38:24 +02:00
Ukendio
7b86084b94 Bump versions 2025-07-17 19:34:29 +02:00
Ukendio
25ceda5cee Remove alive count upvalue 2025-07-17 18:50:21 +02:00
Ukendio
fc56b6f716 Retrieve updated max_id 2025-07-17 18:47:05 +02:00
dai
c30328527a
Add typings for bulk operations (#257)
* Add typings for bulk operations

* Use Id
2025-07-17 18:25:37 +02:00
Ukendio
c3853023d0 Allow creating an entity with a non-zero generation below range 2025-07-17 18:24:44 +02:00
Ukendio
7b253e1c2a Remove archetype recycling 2025-07-17 18:07:11 +02:00
Ukendio
210d62d463 Add tests for archetype edges cleanup
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-14 15:58:14 +02:00
Ukendio
3f6f8c1739 Export jecs.record for retrieving entity records 2025-07-14 15:57:47 +02:00
Ukendio
7f66d21e6d Recycle component records 2025-07-14 14:17:18 +02:00
Ukendio
5334d8734d Export jecs.Component in roblox-ts types 2025-07-14 13:12:41 +02:00
Ukendio
a6ae67250c Use old interface
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-14 00:47:20 +02:00
Ukendio
9ae32bcce8 Update hook retrieval 2025-07-14 00:45:01 +02:00
Ukendio
f6731069aa Add backwards relation to edges
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-13 05:15:55 +02:00
Ukendio
c67dfcbd24 Bump versions
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-10 12:57:51 +02:00
Ukendio
e1545710db LF 2025-07-10 12:52:33 +02:00
Ukendio
aa178981dc Hotfix archetype not being marked dead 2025-07-10 12:51:04 +02:00
Ukendio
ad5ed3b5ea Increment alive count if under dense
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-06 19:42:10 +02:00
Ukendio
362490d25e Always swap entity 2025-07-06 18:49:28 +02:00
Ukendio
6c1793f853 Remove indirections to entity_index 2025-07-06 17:57:35 +02:00
Ukendio
6b6f6fb961 Bump versions 2025-07-06 17:52:59 +02:00
Ukendio
29350e6ec3 Fix bug to allow deletion outside partitioned range 2025-07-06 17:44:02 +02:00
Ukendio
eed1b6179e Export ArchetypeOnCreate and ArchetypeOnDelete events 2025-07-06 17:08:29 +02:00
Ukendio
cf94a48a40 Optimized observers 2025-07-06 17:07:43 +02:00
Ukendio
23540e5919 Make iterators simple functions
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-06 09:52:09 +02:00
Ukendio
169ec09ed5 Change monitor to be iterable 2025-07-06 09:48:13 +02:00
Ukendio
a9891abf6d Make callback optional 2025-07-06 09:42:49 +02:00
Ukendio
6dfb428296 Updated observers 2025-07-06 09:33:31 +02:00
Ukendio
b92cf9ab76 Bump versions 2025-07-06 08:52:17 +02:00
Ukendio
5aedb5e730 Bump wally 2025-07-06 08:51:10 +02:00
Ukendio
1c524f1587 Update TS types 2025-07-06 08:49:10 +02:00
Ukendio
6053038cc1 Move only once during removal of invalidated pair
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-06 08:45:19 +02:00
Ukendio
29305cac5d Remove second loop in archetype destroy 2025-07-06 07:50:03 +02:00
Ukendio
8fd32978b4 Fix changelog
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-07-04 22:00:23 +02:00
Ukendio
c9d888aeb9 Export try_get_fast
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-04 04:58:20 +02:00
Marcus
155d51a080 Add exclusive relations (#250)
* Add exclusive relationship

* Remove focus

* Remove whitespace

* Make ChildOf exclusive

* Test exclusive relation perf

* Inline into world:add

* Inline into world:set

* Fix benchmark of remove
2025-07-04 04:24:14 +02:00
Marcus
b425150b0c Add exclusive relations (#250)
* Add exclusive relationship

* Remove focus

* Remove whitespace

* Make ChildOf exclusive

* Test exclusive relation perf

* Inline into world:add

* Inline into world:set

* Fix benchmark of remove
2025-07-04 04:23:28 +02:00
Ukendio
13facc3719 Add inference for IDs in methods
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-03 01:41:06 +02:00
Ukendio
a6ba9f4bd5 Update networking example
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-07-02 20:26:57 +02:00
Ukendio
53f705ac2e Compare archetype move performance boost
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-30 23:11:05 +02:00
Ukendio
ff4b0bf612 Use btest instead of band 2025-06-30 22:53:40 +02:00
renyang19910211
9b57189c3a
Fix receive_replication.luau removed issue (#243)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-06-30 22:41:29 +02:00
Ukendio
4ff492ceaf Optimize moving archetype 2025-06-30 22:37:30 +02:00
Ukendio
7c8358656a unsafe get
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-06-30 01:44:25 +02:00
Marcus
d6e720f200
Optimize removal path (#248)
* Optimize removal path

* Replace eindex_get implementation
2025-06-30 01:06:31 +02:00
Marcus
3c7f3b4eb3
0.7.3 (#247)
* 0.7.3

* Remove print

* fix jecs.meta for adding values
2025-06-30 00:40:03 +02:00
Ukendio
bee92f489c fetch b
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-27 17:43:31 +02:00
Ukendio
c4d464e712 Bump 2025-06-27 17:36:45 +02:00
Ukendio
a753300129 Fix retrieving 2nd component in world:get 2025-06-27 17:35:45 +02:00
Ukendio
5171a77529 Cut release version in Changelog 2025-06-27 16:00:08 +02:00
Ukendio
8194a03304 bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
2025-06-27 15:58:33 +02:00
Ukendio
8058182d59 Update Changelog 2025-06-27 15:47:27 +02:00
Ukendio
ed5277391d Add bulk operations 2025-06-27 15:43:46 +02:00
Ukendio
1a7c22d2e6 Squash 2025-06-25 17:18:03 +02:00
Ukendio
1ee5790035 Optimize column access
Cleanup
2025-06-25 17:16:04 +02:00
Marcus
24dddee82e
Update README.md
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-21 23:43:46 +02:00
Magic
37f1e5be52
Add hammer to addons resources (#244)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-06-20 22:45:53 +02:00
Ukendio
d6e288555e Fix oopsies 2025-06-20 22:39:59 +02:00
dai
993d57741f
Re-add ECS_PAIR_* to typings (#241)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* Add ECS_PAIR_* functions to typings

* Return simple numbers
2025-06-16 15:12:14 +02:00
dai
150fccd2ce
Fix regression with set (#242) 2025-06-16 15:12:01 +02:00
Marcus
8420d8832b
period
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-13 01:33:54 +02:00
Marcus
01c12fccaa
Update release.yaml 2025-06-13 01:32:44 +02:00
Marcus
29512d4351
Bump upload-artifact ver 2025-06-13 01:30:18 +02:00
Ukendio
582a1c25ba Bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-10 19:42:52 +02:00
Ukendio
6f6cc3b514 Fix overloads 2025-06-10 16:35:09 +02:00
Ukendio
90c963c55d 0.6.1 2025-06-10 16:16:04 +02:00
Ukendio
3174e8d80b Handle removal of (*, R) pairs 2025-06-10 16:16:04 +02:00
Ukendio
0fea5a259d Union entity types with number 2025-06-10 16:10:41 +02:00
Ukendio
46d363ad5f Initial commit with union 2025-06-10 16:10:41 +02:00
Ukendio
dab260f733 Cast numbers to Entity
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-07 02:36:34 +02:00
Ukendio
56b52286b8 Rework observers addon interface 2025-06-07 02:11:38 +02:00
dai
35b5f04a7c
Hook typing improvements (#236)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
* Fix hook callback typings

* Update docs

* Add specialization

* Simplify overloads

* Remove generic
2025-06-06 15:14:23 +02:00
dai
6ce796e7fd
Fix missing parens (#235) 2025-06-06 15:13:54 +02:00
Ukendio
8490dfd294 Prevent partial matching of destroyed archetype
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-06-06 00:38:58 +02:00
Luka
d505a0a38d
fix line endings (#234) 2025-06-05 22:48:13 +02:00
Marcus
e74924ec07
Fix line endings (#233) 2025-06-05 22:00:29 +02:00
Marcus
803616a005
Fix line endings on demo (#232)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-06-01 16:19:48 +02:00
Ukendio
3be946db0c Merge 2025-06-01 16:15:16 +02:00
Ukendio
0308367964 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-06-01 16:15:01 +02:00
Ukendio
5b4f104dd4 Fix line endings 2025-06-01 16:11:32 +02:00
Ukendio
b73bb0daee Fix line endings 2025-06-01 16:11:32 +02:00
EncodedVenom
b669196a98
Change types for tag and is_tag fns
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-28 13:31:03 -04:00
EncodedVenom
c62db9f8c3
Cleanup README links and headers
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-27 14:39:48 -04:00
EncodedVenom
3b0ce599ef
Merge pull request #230 from Tazmondo/main
Fix typo in observers addon
2025-05-27 14:37:14 -04:00
Taran McVay
077030738a
fix typo, queyr -> query 2025-05-27 18:05:59 +01:00
EncodedVenom
740647104b
Merge pull request #229 from Ukendio/installation-guide
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
Add installation methods
2025-05-24 22:17:53 -04:00
EncodedVenom
93cbd2d287 Add installation methods 2025-05-24 16:38:53 -04:00
Ukendio
bb03e88d3d Fix contrived bug with observer
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-20 00:33:16 +02:00
Ukendio
5dba6e7bac Fix typescript example
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-18 23:05:26 +02:00
Ukendio
0541f80b5d Fix hyperlinks 2025-05-18 23:02:16 +02:00
Ukendio
fd685537ea Fix docs issues 2025-05-18 22:59:07 +02:00
Ukendio
8194b7db24 Update docs with new API
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-18 15:28:19 +02:00
Ukendio
457e4a270f Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-18 15:05:55 +02:00
Ukendio
00e7d87a1c Docs chernoboyl 2025-05-18 15:05:46 +02:00
EncodedVenom
f6f6cb569a
Link to workflow
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-17 20:30:52 -04:00
EncodedVenom
10110ac71c
Add unit test workflow status 2025-05-17 20:29:17 -04:00
EncodedVenom
6a5832db20
Merge pull request #228 from Ukendio/documentation-update
Add Guides
2025-05-17 20:07:02 -04:00
EncodedVenom
a9b45f13e5
Merge branch 'main' into documentation-update
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
2025-05-17 20:01:49 -04:00
EncodedVenom
8b8d5f715e ECS is foreign to everyone 2025-05-17 19:59:09 -04:00
EncodedVenom
27a00280fd The children yearn for the guides 2025-05-17 19:56:37 -04:00
Junjie
22877f3fc5
Allow world.add() to accept component, add world.entity overload (#225)
* fix: allow components for world.add in typescript

* fix: add overload for world.entity

* build: downgrade deps to v0.6.0

* fix: world.entity accepts entity instead of number

* fix: allow union undefined union to be passed in .add
2025-05-18 01:44:22 +02:00
EncodedVenom
c030d396af
docs: cleanup todo stubs, add code coverage reports, add examples, and pin introduction section (#227)
* Allow pre existing hooks for observer

* Cleanup some todo stubs

* move coverage reports

* use better link for addons

* code coverage page

* make Introduction sidebar visible on all pages and add a few relevant sections

---------

Co-authored-by: Ukendio <ukendio@gmail.com>
2025-05-17 22:35:00 +02:00
EncodedVenom
3866e1413f make Introduction sidebar visible on all pages and add a few relevant sections 2025-05-17 14:00:30 -04:00
EncodedVenom
296fe80987 code coverage page 2025-05-17 14:00:08 -04:00
EncodedVenom
39946609c7 use better link for addons 2025-05-17 13:59:58 -04:00
EncodedVenom
94a5c6f5e2 move coverage reports 2025-05-17 13:59:35 -04:00
EncodedVenom
ac4d9ade17 Cleanup some todo stubs 2025-05-17 13:59:19 -04:00
EncodedVenom
cbb4b84dc6 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-16 18:57:55 -04:00
PepeElToro41
378a9a45ff
Fix hooks types (#226)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* fix hooks types

* add generic types
2025-05-16 19:22:08 +02:00
Ukendio
a31db7b17b Cleanup changelog
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-05-10 23:27:35 +02:00
Ukendio
b179b649f3 Update changelog 2025-05-10 21:44:49 +02:00
Ukendio
62ac4da426 Bump versions 2025-05-10 21:38:47 +02:00
Ukendio
3d7968652d Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-10 21:38:04 +02:00
Ukendio
6ebac90fd9 Fix entity lookup 2025-05-10 21:37:53 +02:00
Ukendio
06aba5548f Bump versions 2025-05-10 21:37:39 +02:00
EncodedVenom
6881a27563
Merge pull request #223 from Ukendio/encodedvenom-update-types
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
Update TS types
2025-05-08 23:13:52 -04:00
EncodedVenom
4696fc980a
Update jecs.d.ts 2025-05-08 21:34:41 -04:00
Ukendio
4bb7e64edd Define behaviour for world:entity(id)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-08 23:21:38 +02:00
EncodedVenom
a19a422c17 Update exists comment 2025-05-08 17:09:37 -04:00
EncodedVenom
98ffef93df Change meta type 2025-05-08 17:04:48 -04:00
EncodedVenom
d37d0041d6 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-05-08 17:03:20 -04:00
EncodedVenom
45c12a842b
Update jecs.d.ts 2025-05-08 17:02:23 -04:00
Ukendio
150afd784a Allow pre existing hooks for observer 2025-05-08 17:00:45 -04:00
Ukendio
fd6883cfed Allow pre existing hooks for observer
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-07 19:21:12 +02:00
Ukendio
48a43d4ff8 Update outwards facing types
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-05-07 15:52:02 +02:00
Ukendio
6a8d991185 Networking example
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-28 23:40:03 +02:00
Ukendio
3ae84301f2 Recycle higher generation
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-27 20:42:55 +02:00
Ukendio
01821f0a7b Handle only make_alive behaviour in overload
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-27 05:03:49 +02:00
Ukendio
6922019ed9 Short circuit return for non zero generation entities 2025-04-27 04:13:49 +02:00
Ukendio
d0af80577b Add colon
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-26 15:44:33 +02:00
Ukendio
7d4d67f38b Add world_exists 2025-04-26 15:42:20 +02:00
Ukendio
1225f205a8 Should set tags after builtin components 2025-04-26 02:03:39 +02:00
Ukendio
fd2c57fe17 Should begin to allocate above current max_id
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-26 01:10:41 +02:00
Ukendio
52435e62a2 dense should be set at index 2025-04-26 00:55:03 +02:00
Marcus
d1d5b1f207
Add entity ranges (#221)
* Add component registration and metadata API

* Fix test case erroring

* Initial commit

* Simplify entity swap logic in world_entity function

* Allow to disconnect signals

* Remove appending to array

* Add ecs_assert and fix entity range handling

* Fix listener array indexing in observers

* Only max_id and alive_count if range_begin is larger than built in
ranges

* No nullable records

* Index is not a stable pointer
2025-04-25 23:53:39 +02:00
Ukendio
846722ba58 Initialize bundle after builtn components are set
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-25 15:47:51 +02:00
Ukendio
8822be58a9 Add assertion against existing idr
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-22 04:52:21 +02:00
Ukendio
ef0f69ac6d Set signal with hook 2025-04-22 04:49:52 +02:00
Marcus
42401f93ae
Add component registration and metadata API (#219)
* Add component registration and metadata API

* Fix test case erroring

* Fix type issues

* Add component to hook calls' arguments

* Add is_tag function

* Allow focus to capture a single Test

* Add test cases for preregistered tags
2025-04-22 04:38:30 +02:00
Axen
6835f91a09
Docs/hooks set order warning (#220)
* Add docs warning about hook set order

* Improve warning wording
2025-04-22 04:37:04 +02:00
Neon
e5a30f2bc7
Fix jecs addon repository links
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-17 21:08:32 +02:00
as8d
9163285f9e
Add a replication and input section and add feces and axis to addons.md (#217)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-14 17:47:39 +02:00
Ukendio
6ec8ed69e9 Pin luau version
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-13 05:27:13 +02:00
Ukendio
f9bacf3f54 Remove until end of range for relationship 2025-04-13 05:21:41 +02:00
Ukendio
765a7f9a36 Removed unnecessary tests 2025-04-13 02:37:58 +02:00
Ukendio
66636fd844 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-04-13 01:58:36 +02:00
Ukendio
fc4f4a6a3a Add type overloads for World.has method 2025-04-13 01:52:41 +02:00
Ukendio
447bb76bb8 Optimize world:has and improve type annotations 2025-04-13 01:51:21 +02:00
nidho
d85a182c76
Fix duplicated 'Luau/TypeScript' in documentation (#216)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-11 23:25:52 +02:00
Ukendio
4c958071e0 Change observers export value 2025-04-10 21:10:42 +02:00
Ukendio
ba31aa98ba Cleanup testing slightly 2025-04-10 19:52:07 +02:00
Ukendio
5c051eb737 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-04-06 20:38:53 +02:00
Marcus
d3830a1c2a
Replace linked list with bidirectional edges
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-06 19:24:10 +02:00
Ukendio
001431b836 Experiment: rip out linked lists from archetype graph 2025-04-05 06:04:48 +02:00
Ukendio
6bb36f281e Merge branch 'main' of https://github.com/Ukendio/jecs
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-04-05 04:55:21 +02:00
Ukendio
74ef525092 Fix dst clone 2025-04-05 04:55:11 +02:00
Ukendio
df6c568c6b 0.6.0-rc.1 2025-04-05 00:42:04 +02:00
Ukendio
d24ab71e4c Style fixes 2025-04-05 00:41:38 +02:00
Sivak
5e6b030fb4
Change OnSet to OnChange in type definitions for typescript (#214)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-04-05 00:36:04 +02:00
EncodedVenom
908d83a619
Fix typo
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-30 20:00:49 -04:00
Ukendio
41ebde415f OnChange should invoke after data has been set
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-30 22:49:11 +02:00
Ukendio
7bcd6bd220 Update docs 2025-03-30 22:29:43 +02:00
Ukendio
2b90fabec5 Add tests for addons 2025-03-30 22:14:22 +02:00
Ukendio
9c68218d5d Update changelog 2025-03-30 21:47:25 +02:00
Ukendio
cf88c259f8 Replace OnSet hook with OnChange 2025-03-30 21:31:18 +02:00
Ukendio
a466ab151b Move coverage under docs 2025-03-30 18:55:14 +02:00
Ukendio
3050ea1560 Add coverage to Nav 2025-03-30 18:42:16 +02:00
Ukendio
5a1424ee48 Merge branch 'main' of https://github.com/Ukendio/jecs 2025-03-30 18:41:59 +02:00
Ukendio
0455a55625 Remove duplicate .github folder 2025-03-30 18:38:14 +02:00
EncodedVenom
27b58e9745
Update jecs.md
Makes the sentence clearer
2025-03-30 12:24:24 -04:00
lolmanurfunny
0046dcdf1a
find_archetype_with shouldn't clone types unconditionally (#210)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-29 02:22:15 +01:00
Ukendio
9800355131 Styling on coverage reports
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-28 02:29:55 +01:00
Ukendio
dd9db448e3 New coverage reports 2025-03-28 01:53:19 +01:00
Ukendio
34777b51c4 Fix typos 2025-03-28 01:52:33 +01:00
Ukendio
4eb15bbb55 Update removal functions to handle more variants 2025-03-27 21:49:44 +01:00
Ukendio
b81bd6eea8 Make tests lazily evaluated 2025-03-27 17:37:36 +01:00
Ukendio
e6039caaaf Revert mirror back to pinned version
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-27 06:33:41 +01:00
Ukendio
5aec94cb5f Remove file
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-27 05:08:55 +01:00
Ukendio
75f2584bf4 Clear ID will remove ID from all entities 2025-03-27 05:08:38 +01:00
Ukendio
4d6c2ccbb8 Change generic to unknown 2025-03-27 04:17:23 +01:00
Ukendio
bf33748ecf Exclude html coverage reports from language stats 2025-03-27 04:09:09 +01:00
Ukendio
324f0fa9a2 Add html files to coverage folder 2025-03-27 03:55:43 +01:00
Ukendio
1561e446b8 Add html files to coverage folder 2025-03-27 03:55:16 +01:00
Ukendio
9a22b38bb3 Reorganize repo 2025-03-27 02:33:38 +01:00
unknown
58e67eda0d Target should return the entity with its generation
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-26 14:23:54 +01:00
Ukendio
045408af37 Rollback types
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-26 04:59:11 +01:00
Ukendio
59e7fd1f41 Fix nth count for target 2025-03-26 03:39:04 +01:00
Ukendio
f3befa3adb Add dual types 2025-03-25 23:13:53 +01:00
Ukendio
9d83c3bc13 Fix bits arrangement in IDs
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-24 17:36:13 +01:00
Ukendio
e073a570b7 Change invocation points for hooks 2025-03-24 14:31:56 +01:00
Ukendio
79a4a6a0c4 Update demo packages
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-20 00:39:37 +01:00
Ukendio
db1b29fa04 set hook before usage
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-13 16:56:02 +01:00
Ukendio
b26fc39fce Add options to lifetime tracker
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-12 18:49:18 +01:00
Ukendio
0e4f40ced7 Improved emit for devtools 2025-03-12 17:12:25 +01:00
Ukendio
de8e263828 Add entity visualiser
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-12 16:30:19 +01:00
Ukendio
d15266b6d5 Devtools initial commit 2025-03-12 15:30:56 +01:00
Ukendio
18019679d5 Alias for world consttructor 2025-03-12 15:29:24 +01:00
Ukendio
925864dd2b Merge branch 'main' of https://github.com/Ukendio/jecs 2025-03-12 13:10:51 +01:00
Ukendio
ac79638599 Prevent invalidation during removal of pairs with deleted target 2025-03-12 13:10:17 +01:00
Ukendio
f7573e8824 Removal being invalidated during removal of deleted target
Prevent invalidation during removal of pairs with deleted targe
2025-03-12 13:08:19 +01:00
Ukendio
263544d77c Merge branch 'main' of https://github.com/Ukendio/jecs
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-09 22:45:48 +01:00
Ukendio
77cfc9f817 Fix old benchmark code 2025-03-09 22:45:41 +01:00
lolmanurfunny
b29f6c5037
Remove unused EMPTY_QUERY table (#204)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-07 19:54:44 +01:00
lolmanurfunny
a703e2c361
Remove redundant check in entity_index_try_get_any (#203)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-03-07 02:16:49 +01:00
Ukendio
4435d718a7 Change TS types for Archetype
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-03-02 01:24:53 +01:00
Ukendio
62af051e7a Bump 2025-03-01 20:16:26 +01:00
Ukendio
a5dad9aa4d Fix entity deletion swap logic 2025-03-01 20:15:52 +01:00
Ukendio
1bfcba7422 Optimized queries for more than 4 components
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-26 17:26:11 +01:00
Ukendio
c9b07433aa Reduce memory usage for archetype records 2025-02-26 17:04:17 +01:00
Ukendio
af13ea9f5f Bump
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-25 02:41:27 +01:00
Ukendio
61e0df82ae Remove invoke_hook
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-02-25 02:39:41 +01:00
Nidoxs
1a7b1b02b6
Update Jecs version to latest in get-started.md (#199)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-02-23 18:34:53 +01:00
Clown
872e5c9cdb
Bump Jabby v0.2.0-rc.9 (#197)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
Fixes demo not running because of breaking changes in Jabby
2025-02-21 18:26:06 +01:00
lolmanurfunny
4c5e5e1968
Fix redundant checks in world_remove (#198) 2025-02-21 18:10:24 +01:00
Ukendio
3815c62442 Fix critical issue with deleted entity being swapped with the last
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-20 22:55:07 +01:00
Ukendio
1b96975b53 Merge branch 'main' of https://github.com/Ukendio/jecs
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-15 21:57:37 +01:00
Ukendio
11589f5aa8 Add stress test 2025-02-15 21:57:30 +01:00
Saber
19af753903
Fix docs for :parent (#192)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
* Update relationships.md

removed duplicate descrption for 'find first target of a relationship' and fixed the incorrect typescript (I hope) example of getting the parent of an entity

* Start work on #188
2025-02-15 00:07:07 +01:00
Ketasaja
7af6908781
Fix types (#190)
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-02-14 10:51:30 +01:00
Ukendio
0064f24924 Merge branch 'main' of https://github.com/Ukendio/jecs
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-09 20:38:08 +01:00
Ketasaja
6ec0b0bb8b
Change entity type (#189) 2025-02-09 20:37:20 +01:00
Saber
1d1b7b099a
Update relationships.md (#184)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
removed duplicate descrption for 'find first target of a relationship' and fixed the incorrect typescript (I hope) example of getting the parent of an entity
2025-02-07 11:01:54 +01:00
Clown
57fd564aa7
Add planck to addons page (#185) 2025-02-07 07:18:41 +01:00
Ukendio
1937529dcb Modify example 2025-02-05 22:26:12 +01:00
Saber
aac91bb8ff
Update relationships.md (#184)
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
removed duplicate descrption for 'find first target of a relationship' and fixed the incorrect typescript (I hope) example of getting the parent of an entity
2025-02-04 20:21:19 +01:00
EncodedVenom
f91ed9f24b
Bump analysis.yaml
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-02-02 19:06:11 -05:00
Ukendio
44534b7c81 Improve deletion 2025-02-01 13:07:55 +01:00
maeriil
5c19a3b595
Typescript Types for Archetypes
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
* resolves #182 - TS types for Archetypes

* description for archetype query

* updated archetype number type
2025-01-31 15:29:32 +01:00
Ukendio
cc7daa6a06 Cleanup codebase
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-01-29 08:28:08 +01:00
EncodedVenom
a39fc8d0a2
Merge pull request #181 from maeriil/ts-types-tag-fix
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
Typescript: Refine types to use proper values for tags commonly used in conjunction with pair
2025-01-20 21:15:32 -05:00
maeriil
a8570e89a7 fix ts types from Entity<unknown> to Tag for appropriate entities 2025-01-20 03:50:42 -05:00
Ukendio
b3ab540705 Merge addons
Some checks failed
analysis / Run Luau Analyze (push) Has been cancelled
deploy-docs / build (push) Has been cancelled
publish-npm / publish (push) Has been cancelled
unit-testing / Run Luau Tests (push) Has been cancelled
deploy-docs / Deploy (push) Has been cancelled
2025-01-18 00:14:26 +01:00
Ukendio
61a7acae55 Update documentation 2025-01-18 00:13:34 +01:00
Magic
a9bb87745c
docs: Remove sapphire-jecs, add rubine (#180)
- Sapphire, therefore also sapphire-jecs, is going away soon. It's currently unmaintained and will be archived as soon as I can do some final updates to it.

+ Rubine is nearing it's full v0.1.0 release, being stable so far but lacking unit tests. In it's current state it's ready to be added to the addons page.
2025-01-17 23:30:26 +01:00
Ukendio
f66961fc9b Add documentation on caching to concepts
Some checks are pending
analysis / Run Luau Analyze (push) Waiting to run
deploy-docs / build (push) Waiting to run
deploy-docs / Deploy (push) Blocked by required conditions
publish-npm / publish (push) Waiting to run
unit-testing / Run Luau Tests (push) Waiting to run
2025-01-17 11:17:26 +01:00
Ukendio
0cb7558fbb Fix types on idr 2025-01-17 11:17:07 +01:00
167 changed files with 24408 additions and 11247 deletions

2
.gitattributes vendored Executable file
View file

@ -0,0 +1,2 @@
*.luau text eol=lf
*.html linguist-vendored

47
.github/ISSUE_TEMPLATE/BUG-REPORT.md vendored Normal file → Executable file
View file

@ -1,22 +1,25 @@
---
name: Bug report
about: File a bug report for any behavior that you believe is unintentional or problematic
title: "[BUG]"
labels: bug
assignees: ''
---
## Describe the bug
Put a clear and concise description of what the bug is. This should be short and to the point, not to exceed more than a paragraph. Put the details inside your reproduction steps.
## Reproduction
Make an easy-to-follow guide on how to reproduce it. Does it happen all the time? Will specific features affect reproduction? All these questions should be answered for a good issue.
This is a good place to put rbxl files or scripts that help explain your reproduction steps.
## Expected Behavior
What you expect to happen
## Actual Behavior
What actually happens
---
name: Bug report
about: File a bug report for any behavior that you believe is unintentional or problematic
title: ""
labels: bug
assignees: ""
---
## Describe the bug
Put a clear and concise description of what the bug is. This should be short and to the point, not to exceed more than a paragraph. Put the details inside your reproduction steps.
## Reproduction
Make an easy-to-follow guide on how to reproduce it. Does it happen all the time? Will specific features affect reproduction? All these questions should be answered for a good issue.
This is a good place to put rbxl files or scripts that help explain your reproduction steps.
## Expected Behavior
What you expect to happen
## Actual Behavior
What actually happens

9
.github/ISSUE_TEMPLATE/DOCUMENTATION.md vendored Normal file → Executable file
View file

@ -1,14 +1,15 @@
---
name: Documentation
about: Open an issue to add, change, or otherwise modify any part of the documentation.
title: "[DOCS]"
title: ""
labels: documentation
assignees: ''
assignees: ""
---
## Which Sections Does This Issue Cover?
[Put sections (e.g. Query Concepts), page links, etc as necessary]
## What Needs To Change?
What specifically needs to change and what suggestions do you have to change it?
What specifically needs to change and what suggestions do you have to change it?

54
.github/ISSUE_TEMPLATE/FEATURE-REQUEST.md vendored Normal file → Executable file
View file

@ -1,27 +1,27 @@
---
name: Feature Request
about: File a feature request for something you believe should be added to Jecs
title: "[FEATURE]"
labels: enhancement
assignees: ''
---
## Describe your Feature
You should explain your feature here, and the motivation for why you want it.
## Implementation
Explain how you would implement your feature here. Provide relevant API examples and such here (if applicable).
## Alternatives
What other alternative implementations or otherwise relevant information is important to why you decided to go with this specific implementation?
## Considerations
Some questions that need to be answered include the following:
- Will old code break in response to this feature?
- What are the performance impacts with this feature (if any)?
- How is it useful to include?
---
name: Feature Request
about: File a feature request for something you believe should be added to Jecs
title: ""
labels: enhancement
assignees: ""
---
## Describe your Feature
You should explain your feature here, and the motivation for why you want it.
## Implementation
Explain how you would implement your feature here. Provide relevant API examples and such here (if applicable).
## Alternatives
What other alternative implementations or otherwise relevant information is important to why you decided to go with this specific implementation?
## Considerations
Some questions that need to be answered include the following:
- Will old code break in response to this feature?
- What are the performance impacts with this feature (if any)?
- How is it useful to include?

28
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file → Executable file
View file

@ -1,15 +1,15 @@
## Brief Description of your Changes.
Describe what you did here. Additionally, you should link any relevant issues within this section. If there is no corresponding issue, you should include relevant information (repro steps, motivation, etc) here.
## Impact of your Changes
What implications will this have on the project? Will there be altered behavior or performance with this change?
## Tests Performed
What have you done to ensure this change has the least possible impact on the project?
## Additional Comments
## Brief Description of your Changes.
Describe what you did here. Additionally, you should link any relevant issues within this section. If there is no corresponding issue, you should include relevant information (repro steps, motivation, etc) here.
## Impact of your Changes
What implications will this have on the project? Will there be altered behavior or performance with this change?
## Tests Performed
What have you done to ensure this change has the least possible impact on the project?
## Additional Comments
Anything else you feel is relevant.

2
.github/workflows/analysis.yaml vendored Normal file → Executable file
View file

@ -12,7 +12,7 @@ jobs:
uses: actions/checkout@v4
- name: Install Luau
uses: encodedvenom/install-luau@v2.1
uses: encodedvenom/install-luau@v4.3
- name: Analyze
run: |

0
.github/workflows/dependabot.yml vendored Normal file → Executable file
View file

0
.github/workflows/deploy-docs.yaml vendored Normal file → Executable file
View file

0
.github/workflows/publish-npm.yml vendored Normal file → Executable file
View file

6
.github/workflows/release.yaml vendored Normal file → Executable file
View file

@ -2,7 +2,7 @@ name: release
on:
push:
tags: ["v*"]
tags: ["v*", "workflow_dispatch"]
jobs:
build:
@ -22,7 +22,7 @@ jobs:
run: rojo build --output build.rbxm default.project.json
- name: Upload Build Artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: build
path: build.rbxm
@ -38,7 +38,7 @@ jobs:
uses: actions/checkout@v4
- name: Download Jecs Build
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: build
path: build

2
.github/workflows/unit-testing.yaml vendored Normal file → Executable file
View file

@ -15,7 +15,7 @@ jobs:
- name: Install Luau
uses: encodedvenom/install-luau@v4.3
with:
version: "latest"
version: "0.667"
verbose: "true"
- name: Run Unit Tests

141
.gitignore vendored Normal file → Executable file
View file

@ -1,68 +1,73 @@
# Compiled Lua sources
luac.out
# luarocks build files
*.src.rock
*.zip
*.tar.gz
*.rbxm
# Object files
*.o
*.os
*.ko
*.obj
*.elf
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
*.def
*.exp
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Wally files
DevPackages
Packages
wally.lock
WallyPatches
# Typescript
/node_modules
/include
# Misc
roblox.toml
sourcemap.json
drafts/
# Cached Vitepress (docs)
/docs/.vitepress/cache
/docs/.vitepress/dist
.vitepress/cache
.vitepress/dist
# Luau tools
/tools
profile.*
# Compiled Lua sources
luac.out
# luarocks build files
*.src.rock
*.zip
*.tar.gz
*.rbxm
# Object files
*.o
*.os
*.ko
*.obj
*.elf
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
*.def
*.exp
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Wally files
DevPackages
Packages
wally.lock
WallyPatches
# Typescript
/node_modules
/include
# Misc
roblox.toml
sourcemap.json
drafts/
# Cached Vitepress (docs)
/docs/.vitepress/cache
/docs/.vitepress/dist
.vitepress/cache
.vitepress/dist
# Luau tools
profile.*
# Patch files
*.patch
genhtml.perl

18
.luaurc Normal file → Executable file
View file

@ -1,8 +1,10 @@
{
"aliases": {
"jecs": "jecs",
"testkit": "test/testkit",
"mirror": "mirror"
},
"languageMode": "strict"
}
{
"aliases": {
"jecs": "jecs",
"testkit": "tools/testkit",
"mirror": "mirror",
"tools": "tools",
"addons": "addons"
},
"languageMode": "strict"
}

0
.prettierrc Normal file → Executable file
View file

8
stylua.toml → .stylua.toml Normal file → Executable file
View file

@ -1,11 +1,9 @@
syntax = "All"
column_width = 120
line_endings = "Unix"
indent_type = "Tabs"
indent_width = 4
quote_style = "ForceDouble"
quote_style = "AutoPreferDouble"
call_parentheses = "Always"
space_after_function_names = "Never"
collapse_simple_statement = "Never"
syntax = "Luau"
[sort_requires]
enabled = true

358
CHANGELOG.md Normal file → Executable file
View file

@ -1,204 +1,212 @@
# Jecs Changelog
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog][kac], and this project adheres to
[Semantic Versioning][semver].
[kac]: https://keepachangelog.com/en/1.1.0/
[semver]: https://semver.org/spec/v2.0.0.html
## [Unreleased]
- `[world]`:
- 16% faster `world:get`
- `[typescript]`
- Fixed Entity type to default to `undefined | unknown` instead of just `undefined`
- `[query]`:
- Fixed bug where `world:clear` did not invoke `jecs.OnRemove` hooks
- Changed `query.__iter` to drain on iteration
- It will initialize once wherever you left iteration off at last time
- Changed `query:iter` to restart the iterator
- Removed `query:drain` and `query:next`
- If you want to get individual results outside of a for-loop, you need to call `query:iter` to initialize the iterator and then call the iterator function manually
```lua
local it = world:query(A, B, C):iter()
local entity, a, b, c = it()
entity, a, b, c = it() -- get next results
```
- `[world`
- Fixed a bug with `world:clear` not invoking `jecs.OnRemove` hooks
- `[typescript]`:
- Changed pair to accept generics
- Improved handling of Tags
## [0.3.2] - 2024-10-01
- `[world]`:
- Changed `world:cleanup` to traverse a header type for graph edges. (Edit)
- Fixed a regression that occurred when you call `world:set` following a `world:remove` using the same component
- Remove explicit error in JECS_DEBUG for `world:target` when not applying an index parameter
- `[typescript]` :
- Fixed `world.set` with NoInfer<T>
## [0.3.1] - 2024-10-01
- `[world]`:
- Added an index parameter to `world:target`
- Added a way to change the components limit via `_G.JECS_HI_COMPONENT_ID`
- Set it to whatever number you want but try to make it as close to the number of components you will use as possible
- Make sure to set this before importing jecs or else it will not work
- Added debug mode, enable via setting `_G.JECS_DEBUG` to true
- Make sure to set this before importing jecs or else it will not work
- Added `world:cleanup` which is called to cleanup empty archetypes manually
- Changed `world:delete` to delete archetypes that are dependent on the passed entity
- Changed `world:delete` to delete entity's children before the entity to prevent cycles
- `[query]`:
- Fixed the iterator to not drain by default
- `[typescript]`
- Fixed entry point of the package.json file to be `src` rather than `src/init`
- Fixed `query.next` returning a query object whereas it would be expected to return a tuple containing the entity and the corresponding component values
- Exported `query.archetypes`
- Changed `pair` to return a number instead of an entity
- Preventing direct usage of a pair as an entity while still allowing it to be used as a component
- Exported built-in components `ChildOf` and `Name`
- Exported `world.parent`
## [0.2.10] - 2024-09-07
- `[world]`:
- Improved performance for hooks
- Changed `world:set` to be idempotent when setting tags
- `[traits]`:
- Added cleanup condition `jecs.OnDelete` for when the entity or component is deleted
- Added cleanup action `jecs.Remove` which removes instances of the specified (component) id from all entities
- This is the default cleanup action
- Added component trait `jecs.Tag` which allows for zero-cost components used as tags
- Setting data to a component with this trait will do nothing
- `[luau]`:
- Exported `world:contains()`
- Exported `query:drain()`
- Exported `Query`
- Improved types for the hook `OnAdd`, `OnSet`, `OnRemove`
- Changed functions to accept any ID including pairs in type parameters
- Applies to `world:add()`, `world:set()`, `world:remove()`, `world:get()`, `world:has()` and `world:query()`
- New exported type `Id<T = nil> = Entity<T> | Pair`
- Changed `world:contains()` to return a `boolean` instead of an entity which may or may not exist
- Fixed `world:has()` to take the correct parameters
## [0.2.2] - 2024-07-07
## Unreleased
### Added
- Added `query:replace(function(...T) return ...U end)` for replacing components in place
- Method is fast pathed to replace the data to the components for each corresponding entity
- Added signals that allow listening to relation part of pairs in signals.
### Changed
- `OnRemove` hooks so that they are allowed to move entity's archetype even during deletion.
- Iterator now goes backwards instead to prevent common cases of iterator invalidation
## [0.2.1] - 2024-07-06
## 0.8.0
### Added
- Added `jecs.Component` built-in component which will be added to ids created with `world:component()`.
- Used to find every component id with `query(jecs.Component)
## [0.2.0] - 2024-07-03
### Added
- Added `world:parent(entity)` and `jecs.ChildOf` respectively as first class citizen for building parent-child relationships.
- Give a parent to an entity with `world:add($source, pair(ChildOf, $target))`
- Use `world:parent(entity)` to find the target of the relationship
- Added user-facing Luau types
- `jecs.Exclusive` trait for making exclusive relationships.
### Changed
- `jecs.ChildOf` to be an exclusive relationship, which means you can only have one `ChildOf` pair on an entity.
- Improved iteration speeds 20-40% by manually indexing rather than using `next()` :scream:
## [0.1.1] - 2024-05-19
## 0.7.2
### Added
- Added `world:clear(entity)` for removing the components to the corresponding entity
- Added Typescript Types
## [0.1.0] - 2024-05-13
### Changed
- Optimized iterator
## [0.1.0-rc.6] - 2024-05-13
### Added
- Added a `jecs.Wildcard` term
- it lets you query any partially matched pairs
## [0.1.0-rc.5] - 2024-05-10
### Added
- Added Entity relationships for creating logical connections between entities
- Added `world:__iter method` which allows for iteration over the whole world to get every entity
- used for reconciling whole worlds such as via replication, saving/loading, etc
- Added `world:add(entity, component)` which adds a component to the entity
- it is an idempotent function, so calling it twice and in any order should be fine
- `jecs.entity_index_try_get_fast` back as to not break the observer addon.
### Fixed
- A linting problem with the types for `quer:with` and `query:without`.
- Fixed component overriding when in disorder
- Previously setting the components in different order results in it overriding component data because it incorrectly mapped the index of the column. So it took the index from the source archetype rather than the destination archetype
## [0.0.0-prototype.rc.3] - 2024-05-01
## 0.7.0
### Added
- Added observers
- Added an arm to query `query:without()` for chaining invariants.
- `jecs.component_record` for retrieving the component_record of a component.
- `Column<T>` and `ColumnsMap<T>` types for typescript.
- `bulk_insert` and `bulk_remove` respectively for moving an entity to an archetype without intermediate steps.
### Changed
- The fields `archetype.records[id]` and `archetype.counts[id]` have been removed from the archetype struct and been moved to the component record `component_index[id].records[archetype.id]` and `component_index[id].counts[archetype.id]` respectively.
- Removed the metatable `jecs.World`. Use `jecs.world()` to create your World.
- Archetypes will no longer be garbage collected when invalidated, allowing them to be recycled to save a lot of performance during frequent deletion.
- Removed `jecs.entity_index_try_get_fast`. Use `jecs.entity_index_try_get` instead.
- Separates ranges for components and entity IDs.
- IDs created with `world:component()` will promote array lookups rather than map lookups in the `componentIndex` which is a significant boost
- No longer caches the column pointers directly and instead the column indices which stay persistent even when data is reallocated during swap-removals
- This was an issue with the iterator being invalidated when you move an entity to a different archetype.
### Fixedhttps://github.com/Ukendio/jecs/releases/tag/v0.0.0-prototype.rc.3
- Fixed a bug where changing an existing component would be slow because it was always appending changing the row of the entity record
- The fix dramatically improves times where it is basically down to just the speed of setting a field in a table
## [0.0.0-prototype.rc.2] - 2024-04-26
## 0.6.1
### Changed
- Entity types now unions with numbers should allow for easier time casting while not causing regressing previous behaviours
- Optimized the creation of the query
- It will now finds the smallest archetype map to iterate over
- Optimized the query iterator
### Fixed
- Fixed a critical bug with `(*, R)` pairs not being removed when `R` is deleted
- It will now populates iterator with columns for faster indexing
## 0.6.0
- Renamed the insertion method from world:add to world:set to better reflect what it does.
### Added
- `World:range` to restrict entity range to allow for e.g. reserving ids `1000..5000` for clients and everything above that (5000+) for entities from the server. This makes it possible to receive ids from a server that don't have to be mapped to local ids.
- `jecs.component`, `jecs.tag` and `jecs.meta` for preregistering ids and their metadata before a world
- Overload to `World:entity` to create an entity at the desired id.
## [0.0.0-prototype.rc.2] - 2024-04-23
### Changed
- `World:clear` to remove the `ID` from every entity instead of the previous behaviour of removing all of the components on the entity. You should prefer deleting the entity instead for the previous behaviour.
- Entity ID layouts by putting the index in the lower bits, which should make every world function 15 nanoseconds faster.
- Hooks now pass the full component ID which is useful for pairs when you need both the relation and the target.
- Replaced `OnSet` with `OnChange`, which now only runs when the component ID was previously present on the entity.
- `OnAdd` now runs after the value has been set and also passes the component ID and the value.
- `OnRemove` now lazily looks up which archetype the entity will move to. This is meant to support interior structural changes within every hook.
- Optimized `world:has` for both single and multiple component presence. This comes at the cost that it cannot check the component presence for more than 4 components at a time. If this is important, consider calling this function multiple times.
- Initial release
### Fixed
- `World:delete` not removing every pair with an unalive target. Specifically happened when you had at least two pairs of different relations with multiple targets each.
[unreleased]: https://github.com/ukendio/jecs/compare/v0.0.0.0-prototype.rc.2...HEAD
[0.2.2]: https://github.com/ukendio/jecs/releases/tag/v0.2.2
[0.2.1]: https://github.com/ukendio/jecs/releases/tag/v0.2.1
[0.2.0]: https://github.com/ukendio/jecs/releases/tag/v0.2.0
[0.1.1]: https://github.com/ukendio/jecs/releases/tag/v0.1.1
[0.1.0]: https://github.com/ukendio/jecs/releases/tag/v0.1.0
[0.1.0-rc.6]: https://github.com/ukendio/jecs/releases/tag/v0.1.0-rc.6
[0.1.0-rc.5]: https://github.com/ukendio/jecs/releases/tag/v0.1.0-rc.5
[0.0.0-prototype-rc.3]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.3
[0.0.0-prototype.rc.2]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.2
[0.0.0-prototype-rc.1]: https://github.com/ukendio/jecs/releases/tag/v0.0.0-prototype.rc.1
## 0.5.0
### Added
- `World:each` to find entities with a specific Tag.
- `World:children` to find children of an entity.
- `Query:cached` to add a query cache that updates itself when an archetype matching the query gets created or deleted.
### Changed
- Inference of entities' types using user-defined type functions.
- `Pair<First, Second>` to return `Second` if `First` is a `Tag`; otherwise, returns `First`.
### Fixed
- `World:target` not giving adjacent pairs.
## 0.4.0
### Added
- Recycling support to `world:entity` so reused entity IDs now increment generation.
### Removed
- `Query:drain`
- `Query:next`
- `Query:replace`
### Changed
- `jecs.Pair` type in Luau now returns the first element's type to avoid manual typecasting.
### Fixed
- `Query:archetypes` now correctly takes `self`.
## 0.3.2 - 2024-10-01
### Changed
- `World:cleanup` to traverse a header type for graph edges.
### Fixed
- Regression when calling `World:set` after `World:remove` on the same component.
- Removed explicit error in `JECS_DEBUG` for `World:target` missing index.
- `World.set` type inference with `NoInfer<T>` in TypeScript.
## 0.3.1 - 2024-10-01
### Added
- Index parameter to `World:target`.
- Global config `_G.JECS_HI_COMPONENT_ID` to change component ID limit (must be set before importing JECS).
- Debug mode via `_G.JECS_DEBUG` (must be set before importing JECS).
- `world:cleanup` to manually clean up empty archetypes.
### Changed
- `world:delete` now also deletes dependent archetypes and child entities.
### Fixed
- `Query` iterator to not drain by default.
- TypeScript package entry to `src` instead of `src/init`.
- `Query.next` now returns expected result tuple in typescript.
- `pair` returns a number instead of entity to prevent misuse.
- Exported built-in components `ChildOf`, `Name`, and `world.parent`.
## 0.2.10
### Added
- Trait `jecs.Tag` for zero-cost tag components.
- Cleanup conditions: `jecs.OnDelete`, `jecs.Remove`.
### Changed
- `world:set` is now idempotent when setting tags.
### Fixed
- Improved performance for hooks.
- Exported types and functions: `world:contains()`, `query:drain()`, `Query`.
- Hook types: `OnAdd`, `OnSet`, `OnRemove`.
- ID flexibility for `add`, `set`, `remove`, `get`, `has`, `query`.
- `world:contains()` now returns `boolean`.
- `world:has()` parameters now correct.
## 0.2.2
### Added
- `query:replace(fn)` for in-place replacement of component values.
### Changed
- Iterator now goes backwards to avoid invalidation during iteration.
## 0.2.1
### Added
- Built-in `jecs.Component` used to find all component IDs.
## 0.2.0
### Added
- `world:parent(entity)` and `jecs.ChildOf` for parent-child relationships.
### Changed
- Iteration performance improved by 2040% through manual indexing.
## 0.1.1
### Added
- `world:clear(entity)` for removing all components from an entity.
- TypeScript types.
## 0.1.0
### Changed
- Optimized iterator.
## 0.1.0-rc.6
### Added
- `jecs.Wildcard` term to query partially matched pairs.
## 0.1.0-rc.5
### Added
- Entity relationships.
- `world:__iter()` for full world iteration.
- `world:add(entity, component)` (idempotent).
### Fixed
- Component overriding when set out of order.
## 0.0.0-prototype.rc.3
### Added
- Observers.
- `query:without()` for invariant queries.
### Changed
- Separate ID ranges for entities and components.
- Avoid caching pointers; cache stable column indices instead.
### Fixed
- Slow component updates due to unnecessary row changes.
## 0.0.0-prototype.rc.2 - 2024-04-26
### Changed
- Query now uses smallest archetype map.
- Optimized query iterator.
- Renamed `world:add` to `world:set`.
## 0.0.0-prototype.rc.1
### Added
- Initial release.

0
LICENSE Normal file → Executable file
View file

25
README.md Normal file → Executable file
View file

@ -2,7 +2,7 @@
<img src="assets/image-5.png" width=35%/>
</p>
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](LICENSE) [![Wally](https://img.shields.io/github/v/tag/ukendio/jecs?&style=for-the-badge)](https://wally.run/package/ukendio/jecs)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](LICENSE) [![Wally](https://img.shields.io/github/v/tag/ukendio/jecs?&style=for-the-badge)](https://wally.run/package/ukendio/jecs) [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/ukendio/jecs/unit-testing.yaml?&style=for-the-badge)](https://github.com/Ukendio/jecs/actions/workflows/unit-testing.yaml)
Just a stupidly fast Entity Component System
@ -12,7 +12,22 @@ Just a stupidly fast Entity Component System
- Zero-dependency package
- Optimized for column-major operations
- Cache friendly [archetype/SoA](https://ajmmertens.medium.com/building-an-ecs-2-archetypes-and-vectorization-fe21690805f9) storage
- Rigorously [unit tested](https://github.com/Ukendio/jecs/actions/workflows/ci.yaml) for stability
- Rigorously [unit tested](https://github.com/Ukendio/jecs/actions/workflows/unit-testing.yaml) for stability
### Installation
With [Wally](https://wally.run/):
```bash
jecs = "ukendio/jecs@0.6.0" # Inside wally.toml
```
With [pesde](https://pesde.dev/):
```bash
pesde add wally#ukendio/jecs@0.6.0
```
With [npm](https://www.npmjs.com/package/@rbxts/jecs) ([roblox-ts](https://roblox-ts.com/)):
```bash
npm i @rbxts/jecs
```
### Example
@ -45,8 +60,8 @@ world:set(sara, Name, "sara")
print(getName(parent(sara)))
for e in world:query(pair(ChildOf, alice)) do
print(getName(e), "is the child of alice")
for e, name in world:query(Name, pair(ChildOf, alice)) do
print(name, "is the child of alice")
end
-- Output
@ -55,6 +70,8 @@ end
-- sara is the child of alice
```
### Benchmarks
21,000 entities 125 archetypes 4 random components queried.
![Queries](assets/image-3.png)
Can be found under /benches/visual/query.luau

376
addons/ob.luau Executable file
View file

@ -0,0 +1,376 @@
--!strict
local jecs = require("@jecs")
type World = jecs.World
type Query<T...> = jecs.Query<T...>
type Id<T=any> = jecs.Id<T>
export type Iter<T...> = (Observer<T...>) -> () -> (jecs.Entity, T...)
export type Observer<T...> = {
disconnect: (Observer<T...>) -> (),
}
export type Monitor<T...> = {
disconnect: (Observer<T...>) -> (),
added: ((jecs.Entity) -> ()) -> (),
removed: ((jecs.Entity) -> ()) -> ()
}
local function observers_new<T...>(
query: Query<T...>,
callback: (jecs.Entity) -> ()
): Observer<T...>
query:cached()
local world = (query :: Query<T...> & { world: World }).world
callback = callback
local archetypes = {}
local terms = query.filter_with :: { jecs.Id }
local first = terms[1]
local observers_on_create = world.observable[jecs.ArchetypeCreate][first]
local observer_on_create = observers_on_create[#observers_on_create]
observer_on_create.callback = function(archetype)
archetypes[archetype.id] = true
end
local observers_on_delete = world.observable[jecs.ArchetypeDelete][first]
local observer_on_delete = observers_on_delete[#observers_on_delete]
observer_on_delete.callback = function(archetype)
archetypes[archetype.id] = nil
end
local entity_index = world.entity_index :: any
for _, archetype in query:archetypes() do
archetypes[archetype.id] = true
end
local function emplaced<a>(
entity: jecs.Entity,
id: jecs.Id<a>,
value: a
)
local r = entity_index.sparse_array[jecs.ECS_ID(entity)]
local archetype = r.archetype
if archetypes[archetype.id] then
callback(entity)
end
end
local cleanup = {}
for _, term in terms do
if jecs.IS_PAIR(term) then
local rel = jecs.ECS_PAIR_FIRST(term)
local tgt = jecs.ECS_PAIR_SECOND(term)
local wc = tgt == jecs.w
local onadded = world:added(rel, function(entity, id)
if not wc and id ~= term then
return
end
local r = jecs.record(world, entity)
if archetypes[r.archetype.id] then
callback(entity)
end
end)
table.insert(cleanup, onadded)
else
local onadded = world:added(term, emplaced)
local onchanged = world:changed(term, emplaced)
table.insert(cleanup, onadded)
table.insert(cleanup, onchanged)
end
end
local without = query.filter_without
if without then
for _, term in without do
if jecs.IS_PAIR(term) then
local rel = jecs.ECS_PAIR_FIRST(term)
local tgt = jecs.ECS_PAIR_SECOND(term)
local wc = tgt == jecs.w
local onremoved = world:removed(rel, function(entity, id)
if not wc and id ~= term then
return
end
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback(entity)
end
end
end)
table.insert(cleanup, onremoved)
else
local onremoved = world:removed(term, function(entity, id)
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback(entity)
end
end
end)
table.insert(cleanup, onremoved)
end
end
end
local function disconnect()
table.remove(observers_on_create, table.find(
observers_on_create,
observer_on_create
))
table.remove(observers_on_delete, table.find(
observers_on_delete,
observer_on_delete
))
table.clear(archetypes)
for _, disconnect in cleanup do
disconnect()
end
end
local observer = {
disconnect = disconnect,
}
return observer
end
local function monitors_new<T...>(query: Query<T...>): Monitor<T...>
query:cached()
local world = (query :: Query<T...> & { world: World }).world
local archetypes = {}
local terms = query.filter_with :: { jecs.Id<any> }
local first = terms[1]
local observers_on_create = world.observable[jecs.ArchetypeCreate][first]
local observer_on_create = observers_on_create[#observers_on_create]
observer_on_create.callback = function(archetype)
archetypes[archetype.id] = true
end
local observers_on_delete = world.observable[jecs.ArchetypeDelete][first]
local observer_on_delete = observers_on_delete[#observers_on_delete]
observer_on_delete.callback = function(archetype)
archetypes[archetype.id] = nil
end
for _, archetype in query:archetypes() do
archetypes[archetype.id] = true
end
local entity_index = world.entity_index :: any
local callback_added: ((jecs.Entity) -> ())?
local callback_removed: ((jecs.Entity) -> ())?
local function emplaced<a>(
entity: jecs.Entity,
id: jecs.Id<a>,
value: a
)
if callback_added == nil then
return
end
local r = jecs.entity_index_try_get_fast(
entity_index, entity :: any) :: jecs.Record
local archetype = r.archetype
if archetypes[archetype.id] then
callback_added(entity)
end
end
local function removed(entity: jecs.Entity, component: jecs.Id)
if callback_removed == nil then
return
end
local r = jecs.record(world, entity)
if not archetypes[r.archetype.id] then
return
end
callback_removed(entity)
end
local cleanup = {}
for _, term in terms do
if jecs.IS_PAIR(term) then
local rel = jecs.ECS_PAIR_FIRST(term)
local tgt = jecs.ECS_PAIR_SECOND(term)
local wc = tgt == jecs.w
local onadded = world:added(rel, function(entity, id)
if callback_added == nil then
return
end
if not wc and id ~= term then
return
end
local r = jecs.entity_index_try_get_fast(
entity_index, entity :: any) :: jecs.Record
local archetype = r.archetype
if archetypes[archetype.id] then
callback_added(entity)
end
end)
local onremoved = world:removed(rel, function(entity, id)
if callback_removed == nil then
return
end
if not wc and id ~= term then
return
end
local r = jecs.record(world, entity)
if not archetypes[r.archetype.id] then
return
end
callback_removed(entity)
end)
table.insert(cleanup, onadded)
table.insert(cleanup, onremoved)
else
local onadded = world:added(term, emplaced)
local onremoved = world:removed(term, removed)
table.insert(cleanup, onadded)
table.insert(cleanup, onremoved)
end
end
local without = query.filter_without
if without then
for _, term in without do
if jecs.IS_PAIR(term) then
local rel = jecs.ECS_PAIR_FIRST(term)
local tgt = jecs.ECS_PAIR_SECOND(term)
local wc = tgt == jecs.w
local onadded = world:added(rel, function(entity, id)
if callback_removed == nil then
return
end
if not wc and id ~= term then
return
end
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback_removed(entity)
end
end
end)
local onremoved = world:removed(rel, function(entity, id)
if callback_added == nil then
return
end
if not wc and id ~= term then
return
end
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback_added(entity)
end
end
end)
table.insert(cleanup, onadded)
table.insert(cleanup, onremoved)
else
local onadded = world:added(term, function(entity, id)
if callback_removed == nil then
return
end
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback_removed(entity)
end
end
end)
local onremoved = world:removed(term, function(entity, id)
if callback_added == nil then
return
end
local r = jecs.record(world, entity)
local archetype = r.archetype
if archetype then
local dst = jecs.archetype_traverse_remove(world, id, archetype)
if archetypes[dst.id] then
callback_added(entity)
end
end
end)
table.insert(cleanup, onadded)
table.insert(cleanup, onremoved)
end
end
end
local function disconnect()
table.remove(observers_on_create, table.find(
observers_on_create,
observer_on_create
))
table.remove(observers_on_delete, table.find(
observers_on_delete,
observer_on_delete
))
table.clear(archetypes)
for _, disconnect in cleanup do
disconnect()
end
end
local function monitor_added(callback)
callback_added = callback
end
local function monitor_removed(callback)
callback_removed = callback
end
local monitor = {
disconnect = disconnect,
added = monitor_added,
removed = monitor_removed
} :: Monitor<T...>
return monitor
end
return {
monitor = monitors_new,
observer = observers_new
}

0
assets/image-1.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 392 KiB

After

Width:  |  Height:  |  Size: 392 KiB

0
assets/image-2.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 391 KiB

After

Width:  |  Height:  |  Size: 391 KiB

0
assets/image-3.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB

0
assets/image-4.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 103 KiB

0
assets/image-5.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 8.7 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

12
assets/jecs_darkmode.svg Normal file → Executable file
View file

@ -1,6 +1,6 @@
<svg width="47" height="18" viewBox="0 0 47 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 14C5.8 14 6 13.3333 6 13V4H0V0H6H10V13C10 17 6.66667 18 5 18H0V14H5Z" fill="white"/>
<path d="M46.5 4V0H39C37.1667 0 33.5 1.1 33.5 5.5C33.5 9.9 36.8333 11 38.5 11H41C41.5 11 42.5 11.3 42.5 12.5C42.5 13.7 41.5 14 41 14H33.5V18H41.5C43.1667 18 46.5 16.9 46.5 12.5C46.5 8.1 43.1667 7 41.5 7H39C38.5 7 37.5 6.7 37.5 5.5C37.5 4.3 38.5 4 39 4H46.5Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M32.5 0V4H30.5C28.5 4 24.5 5 24.5 9C24.5 11.0835 25.5853 12.3531 26.9078 13.0914L22.4606 14.661C21.2893 13.3156 20.5 11.4775 20.5 9C20.5 1.8 27.1667 0 30.5 0H32.5ZM24.4656 16.3357C26.5037 17.5803 28.8905 18 30.5 18H32.5V14H31.0833L24.4656 16.3357Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M25.3793 0C24.766 0.241156 24.1568 0.53354 23.571 0.885014C22.1712 1.72492 20.9038 2.91123 20.0606 4.5H11V0H25.3793ZM25.5 4.39421C25.445 4.42876 25.3906 4.46402 25.3368 4.5H25.5V4.39421ZM20.0606 13.5C20.9038 15.0888 22.1712 16.2751 23.571 17.115C24.1568 17.4665 24.766 17.7588 25.3793 18H11V13.5H20.0606ZM19.1854 7C19.0649 7.62348 19 8.28956 19 9C19 9.71044 19.0649 10.3765 19.1854 11H11V7H19.1854Z" fill="white"/>
</svg>
<svg width="47" height="18" viewBox="0 0 47 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 14C5.8 14 6 13.3333 6 13V4H0V0H6H10V13C10 17 6.66667 18 5 18H0V14H5Z" fill="white"/>
<path d="M46.5 4V0H39C37.1667 0 33.5 1.1 33.5 5.5C33.5 9.9 36.8333 11 38.5 11H41C41.5 11 42.5 11.3 42.5 12.5C42.5 13.7 41.5 14 41 14H33.5V18H41.5C43.1667 18 46.5 16.9 46.5 12.5C46.5 8.1 43.1667 7 41.5 7H39C38.5 7 37.5 6.7 37.5 5.5C37.5 4.3 38.5 4 39 4H46.5Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M32.5 0V4H30.5C28.5 4 24.5 5 24.5 9C24.5 11.0835 25.5853 12.3531 26.9078 13.0914L22.4606 14.661C21.2893 13.3156 20.5 11.4775 20.5 9C20.5 1.8 27.1667 0 30.5 0H32.5ZM24.4656 16.3357C26.5037 17.5803 28.8905 18 30.5 18H32.5V14H31.0833L24.4656 16.3357Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M25.3793 0C24.766 0.241156 24.1568 0.53354 23.571 0.885014C22.1712 1.72492 20.9038 2.91123 20.0606 4.5H11V0H25.3793ZM25.5 4.39421C25.445 4.42876 25.3906 4.46402 25.3368 4.5H25.5V4.39421ZM20.0606 13.5C20.9038 15.0888 22.1712 16.2751 23.571 17.115C24.1568 17.4665 24.766 17.7588 25.3793 18H11V13.5H20.0606ZM19.1854 7C19.0649 7.62348 19 8.28956 19 9C19 9.71044 19.0649 10.3765 19.1854 11H11V7H19.1854Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

12
assets/jecs_lightmode.svg Normal file → Executable file
View file

@ -1,6 +1,6 @@
<svg width="47" height="18" viewBox="0 0 47 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 14C5.8 14 6 13.3333 6 13V4H0V0H6H10V13C10 17 6.66667 18 5 18H0V14H5Z" fill="black"/>
<path d="M46.5 4V0H39C37.1667 0 33.5 1.1 33.5 5.5C33.5 9.9 36.8333 11 38.5 11H41C41.5 11 42.5 11.3 42.5 12.5C42.5 13.7 41.5 14 41 14H33.5V18H41.5C43.1667 18 46.5 16.9 46.5 12.5C46.5 8.1 43.1667 7 41.5 7H39C38.5 7 37.5 6.7 37.5 5.5C37.5 4.3 38.5 4 39 4H46.5Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M32.5 0V4H30.5C28.5 4 24.5 5 24.5 9C24.5 11.0835 25.5853 12.3531 26.9078 13.0914L22.4606 14.661C21.2893 13.3156 20.5 11.4775 20.5 9C20.5 1.8 27.1667 0 30.5 0H32.5ZM24.4656 16.3357C26.5037 17.5803 28.8905 18 30.5 18H32.5V14H31.0833L24.4656 16.3357Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M25.3793 0C24.766 0.241156 24.1568 0.53354 23.571 0.885014C22.1712 1.72492 20.9038 2.91123 20.0606 4.5H11V0H25.3793ZM25.5 4.39421C25.445 4.42876 25.3906 4.46402 25.3368 4.5H25.5V4.39421ZM20.0606 13.5C20.9038 15.0888 22.1712 16.2751 23.571 17.115C24.1568 17.4665 24.766 17.7588 25.3793 18H11V13.5H20.0606ZM19.1854 7C19.0649 7.62348 19 8.28956 19 9C19 9.71044 19.0649 10.3765 19.1854 11H11V7H19.1854Z" fill="black"/>
</svg>
<svg width="47" height="18" viewBox="0 0 47 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 14C5.8 14 6 13.3333 6 13V4H0V0H6H10V13C10 17 6.66667 18 5 18H0V14H5Z" fill="black"/>
<path d="M46.5 4V0H39C37.1667 0 33.5 1.1 33.5 5.5C33.5 9.9 36.8333 11 38.5 11H41C41.5 11 42.5 11.3 42.5 12.5C42.5 13.7 41.5 14 41 14H33.5V18H41.5C43.1667 18 46.5 16.9 46.5 12.5C46.5 8.1 43.1667 7 41.5 7H39C38.5 7 37.5 6.7 37.5 5.5C37.5 4.3 38.5 4 39 4H46.5Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M32.5 0V4H30.5C28.5 4 24.5 5 24.5 9C24.5 11.0835 25.5853 12.3531 26.9078 13.0914L22.4606 14.661C21.2893 13.3156 20.5 11.4775 20.5 9C20.5 1.8 27.1667 0 30.5 0H32.5ZM24.4656 16.3357C26.5037 17.5803 28.8905 18 30.5 18H32.5V14H31.0833L24.4656 16.3357Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M25.3793 0C24.766 0.241156 24.1568 0.53354 23.571 0.885014C22.1712 1.72492 20.9038 2.91123 20.0606 4.5H11V0H25.3793ZM25.5 4.39421C25.445 4.42876 25.3906 4.46402 25.3368 4.5H25.5V4.39421ZM20.0606 13.5C20.9038 15.0888 22.1712 16.2751 23.571 17.115C24.1568 17.4665 24.766 17.7588 25.3793 18H11V13.5H20.0606ZM19.1854 7C19.0649 7.62348 19 8.28956 19 9C19 9.71044 19.0649 10.3765 19.1854 11H11V7H19.1854Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

0
assets/logo_old.png Normal file → Executable file
View file

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 68 KiB

0
bench.project.json Normal file → Executable file
View file

2
benches/cached.luau Normal file → Executable file
View file

@ -1,5 +1,5 @@
local jecs = require("@jecs")
local mirror = require("../mirror/init")
local mirror = require("@mirror")
type i53 = number

49
benches/general.luau Normal file → Executable file
View file

@ -14,7 +14,7 @@ local pair = jecs.pair
do
TITLE("create")
local world = jecs.World.new()
local world = jecs.world()
BENCH("entity", function()
for i = 1, START(N) do
@ -35,8 +35,8 @@ end
do
TITLE("set")
local world = jecs.World.new()
local A = world:entity()
local world = jecs.world()
local A = world:component()
local entities = table.create(N)
@ -69,8 +69,8 @@ end
do
TITLE("set relationship")
local world = jecs.World.new()
local A = world:entity()
local world = jecs.world()
local A = world:component()
local entities = table.create(N)
@ -103,7 +103,7 @@ end
do
TITLE("get")
local world = jecs.World.new()
local world = jecs.world()
local A = world:component()
local B = world:component()
local C = world:component()
@ -147,7 +147,7 @@ do
TITLE("target")
BENCH("1st target", function()
local world = jecs.World.new()
local world = jecs.world()
local A = world:component()
local B = world:component()
local C = world:component()
@ -179,7 +179,7 @@ do
local function view_bench(n: number)
BENCH(`{n} entities per archetype`, function()
local world = jecs.World.new()
local world = jecs.world()
local A = world:component()
local B = world:component()
@ -194,17 +194,19 @@ do
world:set(id, B, true)
world:set(id, C, true)
world:set(id, D, true)
world:set(id, ct, true)
world:add(id, ct)
end
end
local q = world:query(A, B, C, D)
q:archetypes()
START()
for id in world:query(A, B, C, D) do
for id in q do
end
end)
BENCH(`inlined query`, function()
local world = jecs.World.new()
local world = jecs.world()
local A = world:component()
local B = world:component()
local C = world:component()
@ -218,17 +220,28 @@ do
world:set(id, B, true)
world:set(id, C, true)
world:set(id, D, true)
world:set(id, ct, true)
world:add(id, ct)
end
end
local archetypes = world:query(A, B, C, D):archetypes()
START()
for _, archetype in world:query(A, B, C, D):archetypes() do
local columns, records = archetype.columns, archetype.records
local a = columns[records[A].column]
local b = columns[records[B].column]
local c = columns[records[C].column]
local d = columns[records[D].column]
-- for _, archetype in archetypes do
-- local columns, records = archetype.columns, archetype.records
-- local a = columns[records[A]]
-- local b = columns[records[B]]
-- local c = columns[records[C]]
-- local d = columns[records[D]]
-- for row in archetype.entities do
-- local _1, _2, _3, _4 = a[row], b[row], c[row], d[row]
-- end
-- end
for _, archetype in archetypes do
local columns_map = archetype.columns_map
local a = columns_map[A]
local b = columns_map[B]
local c = columns_map[C]
local d = columns_map[D]
for row in archetype.entities do
local _1, _2, _3, _4 = a[row], b[row], c[row], d[row]
end

29
benches/query.luau Normal file → Executable file
View file

@ -11,15 +11,22 @@ end
local jecs = require("@jecs")
local mirror = require("@mirror")
type i53 = number
do
TITLE(testkit.color.white_underline("Jecs query"))
local ecs = jecs.World.new()
local ecs = jecs.world() :: jecs.World
do
TITLE("one component in common")
local function view_bench(world: jecs.World, A: i53, B: i53, C: i53, D: i53, E: i53, F: i53, G: i53, H: i53)
local function view_bench(world: jecs.World,
A: jecs.Id,
B: jecs.Id,
C: jecs.Id,
D: jecs.Id,
E: jecs.Id,
F: jecs.Id,
G: jecs.Id,
H: jecs.Id
)
BENCH("1 component", function()
for _ in world:query(A) do
end
@ -131,11 +138,21 @@ end
do
TITLE(testkit.color.white_underline("Mirror query"))
local ecs = mirror.World.new()
local ecs = mirror.World.new() :: jecs.World
do
TITLE("one component in common")
local function view_bench(world: jecs.World, A: i53, B: i53, C: i53, D: i53, E: i53, F: i53, G: i53, H: i53)
local function view_bench(
world: mirror.World,
A: jecs.Id,
B: jecs.Id,
C: jecs.Id,
D: jecs.Id,
E: jecs.Id,
F: jecs.Id,
G: jecs.Id,
H: jecs.Id
)
BENCH("1 component", function()
for _ in world:query(A) do
end

74
benches/visual/despawn.bench.luau Normal file → Executable file
View file

@ -1,45 +1,65 @@
--!optimize 2
--!native
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Matter = require(ReplicatedStorage.DevPackages.Matter)
local ecr = require(ReplicatedStorage.DevPackages.ecr)
local jecs = require(ReplicatedStorage.Lib)
local newWorld = Matter.World.new()
local ecs = jecs.World.new()
local jecs = require(ReplicatedStorage.Lib:Clone())
local pair = jecs.pair
local ecs = jecs.world()
local mirror = require(ReplicatedStorage.mirror:Clone())
local mcs = mirror.world()
local A, B = Matter.component(), Matter.component()
local C, D = ecs:component(), ecs:component()
local C1 = ecs:component()
local C2 = ecs:entity()
local C3 = ecs:entity()
local C4 = ecs:entity()
local E1 = mcs:component()
local E2 = mcs:entity()
local E3 = mcs:entity()
local E4 = mcs:entity()
local m = mcs:entity()
local j = ecs:entity()
return {
ParameterGenerator = function()
local matter_entities = {}
local jecs_entities = {}
local entities = {
matter = matter_entities,
jecs = jecs_entities,
}
for i = 1, 1000 do
table.insert(matter_entities, newWorld:spawn(A(), B()))
local e = ecs:entity()
ecs:set(e, C, {})
ecs:set(e, D, {})
table.insert(jecs_entities, e)
end
return entities
end,
Functions = {
Matter = function(_, entities)
for _, entity in entities.matter do
newWorld:despawn(entity)
Mirror = function()
for i = 1, 10 do
local friend2 = mcs:entity()
mcs:add(friend2, pair(E2, m))
mcs:add(friend2, pair(E3, m))
mcs:add(friend2, pair(E4, m))
-- local r = mirror.entity_index_try_get_fast(mcs.entity_index, friend2)
-- local archetype = r.archetype
-- mirror.archetype_destroy(mcs, archetype)
mcs:delete(m)
m = mcs:entity(m)
end
end,
Jecs = function(_, entities)
for _, entity in entities.jecs do
ecs:delete(entity)
Jecs = function()
for i = 1, 10 do
local friend1 = ecs:entity()
ecs:add(friend1, pair(C2, j))
ecs:add(friend1, pair(C3, j))
ecs:add(friend1, pair(C4, j))
-- local r = jecs.entity_index_try_get_fast(ecs.entity_index, friend1)
-- local archetype = r.archetype
-- jecs.archetype_destroy(ecs, archetype)
ecs:delete(j)
j = ecs:entity()
end
end,
},
}

116
benches/visual/insertion.bench.luau Normal file → Executable file
View file

@ -2,98 +2,58 @@
--!native
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Matter = require(ReplicatedStorage.DevPackages.Matter)
local ecr = require(ReplicatedStorage.DevPackages.ecr)
local jecs = require(ReplicatedStorage.Lib)
local newWorld = Matter.World.new()
local ecs = jecs.World.new()
local mirror = require(ReplicatedStorage.mirror)
local mcs = mirror.World.new()
local jecs = require(ReplicatedStorage.Lib:Clone())
local ecs = jecs.world()
local mirror = require(ReplicatedStorage.mirror:Clone())
local mcs = mirror.world()
local A1 = Matter.component()
local A2 = Matter.component()
local A3 = Matter.component()
local A4 = Matter.component()
local A5 = Matter.component()
local A6 = Matter.component()
local A7 = Matter.component()
local A8 = Matter.component()
local C1 = ecs:component()
local C2 = ecs:component()
local C3 = ecs:component()
local C4 = ecs:component()
local C5 = ecs:component()
local C6 = ecs:component()
local C7 = ecs:component()
local C8 = ecs:component()
local E1 = mcs:component()
local E2 = mcs:component()
local E3 = mcs:component()
local E4 = mcs:component()
local E5 = mcs:component()
local E6 = mcs:component()
local E7 = mcs:component()
local E8 = mcs:component()
local B1 = ecr.component()
local B2 = ecr.component()
local B3 = ecr.component()
local B4 = ecr.component()
local B5 = ecr.component()
local B6 = ecr.component()
local B7 = ecr.component()
local B8 = ecr.component()
local C1 = ecs:entity()
local C2 = ecs:entity()
local C3 = ecs:entity()
local C4 = ecs:entity()
local C5 = ecs:entity()
local C6 = ecs:entity()
local C7 = ecs:entity()
local C8 = ecs:entity()
local E1 = mcs:entity()
local E2 = mcs:entity()
local E3 = mcs:entity()
local E4 = mcs:entity()
local E5 = mcs:entity()
local E6 = mcs:entity()
local E7 = mcs:entity()
local E8 = mcs:entity()
local registry2 = ecr.registry()
return {
ParameterGenerator = function()
return
end,
Functions = {
Matter = function()
local e = newWorld:spawn()
Mirror = function()
local e = mcs:entity()
for i = 1, 5000 do
newWorld:insert(
e,
A1({ value = true }),
A2({ value = true }),
A3({ value = true }),
A4({ value = true }),
A5({ value = true }),
A6({ value = true }),
A7({ value = true }),
A8({ value = true })
)
mcs:set(e, E1, false)
mcs:set(e, E2, false)
mcs:set(e, E3, false)
mcs:set(e, E4, false)
mcs:set(e, E5, false)
mcs:set(e, E6, false)
mcs:set(e, E7, false)
mcs:set(e, E8, false)
end
end,
ECR = function()
local e = registry2.create()
for i = 1, 5000 do
registry2:set(e, B1, { value = false })
registry2:set(e, B2, { value = false })
registry2:set(e, B3, { value = false })
registry2:set(e, B4, { value = false })
registry2:set(e, B5, { value = false })
registry2:set(e, B6, { value = false })
registry2:set(e, B7, { value = false })
registry2:set(e, B8, { value = false })
end
end,
Jecs = function()
local e = ecs:entity()
for i = 1, 5000 do
ecs:set(e, C1, { value = false })
ecs:set(e, C2, { value = false })
ecs:set(e, C3, { value = false })
ecs:set(e, C4, { value = false })
ecs:set(e, C5, { value = false })
ecs:set(e, C6, { value = false })
ecs:set(e, C7, { value = false })
ecs:set(e, C8, { value = false })
ecs:set(e, C1, false)
ecs:set(e, C2, false)
ecs:set(e, C3, false)
ecs:set(e, C4, false)
ecs:set(e, C5, false)
ecs:set(e, C6, false)
ecs:set(e, C7, false)
ecs:set(e, C8, false)
end
end,
},

147
benches/visual/query.bench.luau Normal file → Executable file
View file

@ -2,32 +2,11 @@
--!native
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Matter = require(ReplicatedStorage.DevPackages["_Index"]["matter-ecs_matter@0.8.1"].matter)
local ecr = require(ReplicatedStorage.DevPackages["_Index"]["centau_ecr@0.8.0"].ecr)
local newWorld = Matter.World.new()
local jecs = require(ReplicatedStorage.Lib)
local mirror = require(ReplicatedStorage.mirror)
local mcs = mirror.World.new()
local ecs = jecs.World.new()
local A1 = Matter.component()
local A2 = Matter.component()
local A3 = Matter.component()
local A4 = Matter.component()
local A5 = Matter.component()
local A6 = Matter.component()
local A7 = Matter.component()
local A8 = Matter.component()
local B1 = ecr.component()
local B2 = ecr.component()
local B3 = ecr.component()
local B4 = ecr.component()
local B5 = ecr.component()
local B6 = ecr.component()
local B7 = ecr.component()
local B8 = ecr.component()
local jecs = require(ReplicatedStorage.Lib:Clone())
local mirror = require(ReplicatedStorage.mirror:Clone())
local mcs = mirror.world()
local ecs = jecs.world()
local D1 = ecs:component()
local D2 = ecs:component()
@ -38,99 +17,62 @@ local D6 = ecs:component()
local D7 = ecs:component()
local D8 = ecs:component()
local E1 = mcs:entity()
local E2 = mcs:entity()
local E3 = mcs:entity()
local E4 = mcs:entity()
local E5 = mcs:entity()
local E6 = mcs:entity()
local E7 = mcs:entity()
local E8 = mcs:entity()
local registry2 = ecr.registry()
local E1 = mcs:component()
local E2 = mcs:component()
local E3 = mcs:component()
local E4 = mcs:component()
local E5 = mcs:component()
local E6 = mcs:component()
local E7 = mcs:component()
local E8 = mcs:component()
local function flip()
return math.random() >= 0.25
return math.random() >= 0.3
end
local N = 2 ^ 16 - 2
local archetypes = {}
local hm = 0
for i = 1, N do
local id = registry2.create()
local combination = ""
local n = newWorld:spawn()
local entity = ecs:entity()
local m = mcs:entity()
if flip() then
registry2:set(id, B1, { value = true })
ecs:set(entity, D1, { value = true })
newWorld:insert(n, A1({ value = true }))
mcs:set(m, E1, { value = 2 })
ecs:add(entity, entity)
mcs:add(m, m)
end
if flip() then
combination ..= "B"
registry2:set(id, B2, { value = true })
ecs:set(entity, D2, { value = true })
mcs:set(m, E2, { value = 2 })
newWorld:insert(n, A2({ value = true }))
ecs:set(entity, D1, true)
mcs:set(m, E1, true)
end
if flip() then
combination ..= "C"
registry2:set(id, B3, { value = true })
ecs:set(entity, D3, { value = true })
mcs:set(m, E3, { value = 2 })
newWorld:insert(n, A3({ value = true }))
ecs:set(entity, D2, true)
mcs:set(m, E2, true)
end
if flip() then
combination ..= "D"
registry2:set(id, B4, { value = true })
ecs:set(entity, D4, { value = true })
mcs:set(m, E4, { value = 2 })
newWorld:insert(n, A4({ value = true }))
ecs:set(entity, D3, true)
mcs:set(m, E3, true)
end
if flip() then
combination ..= "E"
registry2:set(id, B5, { value = true })
ecs:set(entity, D5, { value = true })
mcs:set(m, E5, { value = 2 })
newWorld:insert(n, A5({ value = true }))
ecs:set(entity, D4, true)
mcs:set(m, E4, true)
end
if flip() then
combination ..= "F"
registry2:set(id, B6, { value = true })
ecs:set(entity, D6, { value = true })
mcs:set(m, E6, { value = 2 })
newWorld:insert(n, A6({ value = true }))
ecs:set(entity, D5, true)
mcs:set(m, E5, true)
end
if flip() then
combination ..= "G"
registry2:set(id, B7, { value = true })
ecs:set(entity, D7, { value = true })
mcs:set(m, E7, { value = 2 })
newWorld:insert(n, A7({ value = true }))
ecs:set(entity, D6, true)
mcs:set(m, E6, true)
end
if flip() then
combination ..= "H"
registry2:set(id, B8, { value = true })
newWorld:insert(n, A8({ value = true }))
ecs:set(entity, D8, { value = true })
mcs:set(m, E8, { value = 2 })
ecs:set(entity, D7, true)
mcs:set(m, E7, true)
end
if combination:find("BCDF") then
if not archetypes[combination] then
print(combination)
end
hm += 1
if flip() then
ecs:set(entity, D8, true)
mcs:set(m, E8, true)
end
archetypes[combination] = true
end
print("TEST", hm)
local count = 0
@ -138,7 +80,11 @@ for _, archetype in ecs:query(D2, D4, D6, D8):archetypes() do
count += #archetype.entities
end
print(count)
local mq = mcs:query(E2, E4, E6, E8):cached()
local jq = ecs:query(D2, D4, D6, D8):cached()
print(count, #jq:archetypes())
return {
ParameterGenerator = function()
@ -146,18 +92,23 @@ return {
end,
Functions = {
Matter = function()
for entityId, firstComponent in newWorld:query(A2, A4, A6, A8) do
end
end,
-- Matter = function()
-- for entityId, firstComponent in newWorld:query(A2, A4, A6, A8) do
-- end
-- end,
ECR = function()
for entityId, firstComponent in registry2:view(B2, B4, B6, B8) do
-- ECR = function()
-- for entityId, firstComponent in registry2:view(B2, B4, B6, B8) do
-- end
-- end,
--
Mirror = function()
for entityId, firstComponent in mq do
end
end,
Jecs = function()
for entityId, firstComponent in ecs:query(D2, D4, D6, D8) do
for entityId, firstComponent in jq do
end
end,
},

View file

@ -0,0 +1,52 @@
--!optimize 2
--!native
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Matter = require(ReplicatedStorage.DevPackages.Matter)
local ecr = require(ReplicatedStorage.DevPackages.ecr)
local jecs = require(ReplicatedStorage.Lib:Clone())
local pair = jecs.pair
local ecs = jecs.world()
local mirror = require(ReplicatedStorage.mirror:Clone())
local mcs = mirror.world()
local C1 = ecs:component()
local C2 = ecs:entity()
ecs:add(C2, pair(jecs.OnDeleteTarget, jecs.Delete))
ecs:add(C2, jecs.Exclusive)
local C3 = ecs:entity()
ecs:add(C3, pair(jecs.OnDeleteTarget, jecs.Delete))
local C4 = ecs:entity()
ecs:add(C4, pair(jecs.OnDeleteTarget, jecs.Delete))
local E1 = mcs:component()
local E2 = mcs:entity()
mcs:add(E2, pair(jecs.OnDeleteTarget, jecs.Delete))
local E3 = mcs:entity()
mcs:add(E3, pair(jecs.OnDeleteTarget, jecs.Delete))
local E4 = mcs:entity()
mcs:add(E4, pair(jecs.OnDeleteTarget, jecs.Delete))
return {
ParameterGenerator = function()
end,
Functions = {
Mirror = function()
local m = mcs:entity()
for i = 1, 100 do
mcs:add(m, pair(E2, E3))
mcs:remove(m, pair(E2, E3))
mcs:add(m, pair(E2, E4))
end
end,
Jecs = function()
local j = ecs:entity()
for i = 1, 100 do
ecs:add(j, pair(C2, C3))
ecs:add(j, pair(C2, C4))
end
end,
},
}

34
benches/visual/spawn.bench.luau Normal file → Executable file
View file

@ -2,36 +2,32 @@
--!native
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Matter = require(ReplicatedStorage.DevPackages.Matter)
local ecr = require(ReplicatedStorage.DevPackages.ecr)
local jecs = require(ReplicatedStorage.Lib)
local newWorld = Matter.World.new()
local ecs = jecs.World.new()
local jecs = require(ReplicatedStorage.Lib:Clone())
local mirror = require(ReplicatedStorage.mirror:Clone())
return {
ParameterGenerator = function()
local registry2 = ecr.registry()
return registry2
local ecs = jecs.world()
ecs:range(1000, 20000)
local mcs = mirror.World.new()
return ecs, mcs
end,
Functions = {
Matter = function()
for i = 1, 1000 do
newWorld:spawn()
Mirror = function(_, ecs, mcs)
for i = 1, 100 do
mcs:entity()
end
end,
ECR = function(_, registry2)
for i = 1, 1000 do
registry2.create()
end
end,
Jecs = function(_, ecs, mcs)
for i = 1, 100 do
Jecs = function()
for i = 1, 1000 do
ecs:entity()
end
end,
},
},
}

0
benches/visual/wally.toml Normal file → Executable file
View file

0
default.project.json Normal file → Executable file
View file

BIN
demo.rbxl

Binary file not shown.

View file

@ -1,18 +0,0 @@
option ClientOutput = "../net/client.luau"
option ServerOutput = "../net/server.luau"
event UpdateTransform {
From: Server,
Type: Unreliable,
Call: SingleSync,
Poll: true,
Data: (f64, CFrame)
}
event SpawnMob {
From: Server,
Type: Reliable,
Call: SingleSync,
Poll: true,
Data: (f64, CFrame, u8)
}

0
demo/.gitignore vendored Normal file → Executable file
View file

0
demo/README.md Normal file → Executable file
View file

131
demo/default.project.json Normal file → Executable file
View file

@ -1,76 +1,55 @@
{
"name": "demo",
"tree": {
"$className": "DataModel",
"ReplicatedStorage": {
"$className": "ReplicatedStorage",
"$path": "src/ReplicatedStorage",
"ecs": {
"$path": "../jecs.luau"
},
"net": {
"$path": "net/client.luau"
},
"Packages": {
"$path": "Packages"
}
},
"ServerScriptService": {
"$className": "ServerScriptService",
"$path": "src/ServerScriptService",
"net": {
"$path": "net/server.luau"
}
},
"Workspace": {
"$properties": {
"FilteringEnabled": true
},
"Baseplate": {
"$className": "Part",
"$properties": {
"Anchored": true,
"Color": [
0.38823,
0.37254,
0.38823
],
"Locked": true,
"Position": [
0,
-10,
0
],
"Size": [
512,
20,
512
]
}
}
},
"Lighting": {
"$properties": {
"Ambient": [
0,
0,
0
],
"Brightness": 2,
"GlobalShadows": true,
"Outlines": false,
"Technology": "Voxel"
}
},
"SoundService": {
"$properties": {
"RespectFilteringEnabled": true
}
},
"StarterPlayer": {
"StarterPlayerScripts": {
"$path": "src/StarterPlayer/StarterPlayerScripts"
}
}
}
}
{
"name": "demo",
"emitLegacyScripts": false,
"tree": {
"$className": "DataModel",
"ReplicatedStorage": {
"$className": "ReplicatedStorage",
"$path": "src/ReplicatedStorage",
"ecs": {
"$path": "../jecs.luau"
},
"Packages": {
"$path": "Packages"
}
},
"ServerScriptService": {
"$className": "ServerScriptService",
"$path": "src/ServerScriptService"
},
"Workspace": {
"$properties": {
"FilteringEnabled": true
},
"Baseplate": {
"$className": "Part",
"$properties": {
"Anchored": true,
"Color": [0.38823, 0.37254, 0.38823],
"Locked": true,
"Position": [0, -10, 0],
"Size": [512, 20, 512]
}
}
},
"Lighting": {
"$properties": {
"Ambient": [0, 0, 0],
"Brightness": 2,
"GlobalShadows": true,
"Outlines": false,
"Technology": "Voxel"
}
},
"SoundService": {
"$properties": {
"RespectFilteringEnabled": true
}
},
"StarterPlayer": {
"StarterPlayerScripts": {
"$path": "src/StarterPlayer/StarterPlayerScripts"
}
}
}
}

View file

@ -1,336 +0,0 @@
--!strict
--!native
--!optimize 2
--!nolint LocalShadow
--#selene: allow(shadowing)
-- File generated by Blink v0.14.1 (https://github.com/1Axen/Blink)
-- This file is not meant to be edited
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
if not RunService:IsClient() then
error("Client network module can only be required from the client.")
end
local Reliable: RemoteEvent = ReplicatedStorage:WaitForChild("BLINK_RELIABLE_REMOTE") :: RemoteEvent
local Unreliable: UnreliableRemoteEvent =
ReplicatedStorage:WaitForChild("BLINK_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent
local Invocations = 0
local SendSize = 64
local SendOffset = 0
local SendCursor = 0
local SendBuffer = buffer.create(64)
local SendInstances = {}
local RecieveCursor = 0
local RecieveBuffer = buffer.create(64)
local RecieveInstances = {}
local RecieveInstanceCursor = 0
type Entry = {
value: any,
next: Entry?,
}
type Queue = {
head: Entry?,
tail: Entry?,
}
type BufferSave = {
Size: number,
Cursor: number,
Buffer: buffer,
Instances: { Instance },
}
local function Read(Bytes: number)
local Offset = RecieveCursor
RecieveCursor += Bytes
return Offset
end
local function Save(): BufferSave
return {
Size = SendSize,
Cursor = SendCursor,
Buffer = SendBuffer,
Instances = SendInstances,
}
end
local function Load(Save: BufferSave?)
if Save then
SendSize = Save.Size
SendCursor = Save.Cursor
SendOffset = Save.Cursor
SendBuffer = Save.Buffer
SendInstances = Save.Instances
return
end
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
SendInstances = {}
end
local function Invoke()
if Invocations == 255 then
Invocations = 0
end
local Invocation = Invocations
Invocations += 1
return Invocation
end
local function Allocate(Bytes: number)
local InUse = (SendCursor + Bytes)
if InUse > SendSize then
--> Avoid resizing the buffer for every write
while InUse > SendSize do
SendSize *= 1.5
end
local Buffer = buffer.create(SendSize)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
SendBuffer = Buffer
end
SendOffset = SendCursor
SendCursor += Bytes
return SendOffset
end
local function CreateQueue(): Queue
return {
head = nil,
tail = nil,
}
end
local function Pop(queue: Queue): any
local head = queue.head
if head == nil then
return
end
queue.head = head.next
return head.value
end
local function Push(queue: Queue, value: any)
local entry: Entry = {
value = value,
next = nil,
}
if queue.tail ~= nil then
queue.tail.next = entry
end
queue.tail = entry
if queue.head == nil then
queue.head = entry
end
end
local Types = {}
local Calls = table.create(256)
local Events: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
local Queue: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
Queue.Unreliable[0] = CreateQueue()
Queue.Reliable[0] = CreateQueue()
function Types.ReadEVENT_UpdateTransform(): (number, CFrame)
-- Read BLOCK: 32 bytes
local BLOCK_START = Read(32)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
return Value1, Value2
end
function Types.WriteEVENT_UpdateTransform(Value1: number, Value2: CFrame): ()
-- Allocate BLOCK: 33 bytes
local BLOCK_START = Allocate(33)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
end
function Types.ReadEVENT_SpawnMob(): (number, CFrame, number)
-- Read BLOCK: 33 bytes
local BLOCK_START = Read(33)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
local Value3 = buffer.readu8(RecieveBuffer, BLOCK_START + 32)
return Value1, Value2, Value3
end
function Types.WriteEVENT_SpawnMob(Value1: number, Value2: CFrame, Value3: number): ()
-- Allocate BLOCK: 34 bytes
local BLOCK_START = Allocate(34)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
buffer.writeu8(SendBuffer, BLOCK_START + 33, Value3)
end
local function StepReplication()
if SendCursor <= 0 then
return
end
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Reliable:FireServer(Buffer, SendInstances)
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
table.clear(SendInstances)
end
local Elapsed = 0
RunService.Heartbeat:Connect(function(DeltaTime: number)
Elapsed += DeltaTime
if Elapsed >= (1 / 61) then
Elapsed -= (1 / 61)
StepReplication()
end
end)
Reliable.OnClientEvent:Connect(function(Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
if Index == 0 then
Push(Queue.Reliable[0], table.pack(Types.ReadEVENT_SpawnMob()))
end
end
end)
Unreliable.OnClientEvent:Connect(function(Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
if Index == 0 then
Push(Queue.Unreliable[0], table.pack(Types.ReadEVENT_UpdateTransform()))
end
end
end)
return {
StepReplication = StepReplication,
UpdateTransform = {
Iter = function(): () -> (number, number, CFrame)
local index = 0
local queue = Queue.Unreliable[0]
return function(): (number, number, CFrame)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
Next = function(): () -> (number, number, CFrame)
local index = 0
local queue = Queue.Unreliable[0]
return function(): (number, number, CFrame)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
},
SpawnMob = {
Iter = function(): () -> (number, number, CFrame, number)
local index = 0
local queue = Queue.Reliable[0]
return function(): (number, number, CFrame, number)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
Next = function(): () -> (number, number, CFrame, number)
local index = 0
local queue = Queue.Reliable[0]
return function(): (number, number, CFrame, number)
index += 1
local arguments = Pop(queue)
if arguments ~= nil then
return index, unpack(arguments, 1, arguments.n)
end
return
end
end,
},
}

View file

@ -1,372 +0,0 @@
--!strict
--!native
--!optimize 2
--!nolint LocalShadow
--#selene: allow(shadowing)
-- File generated by Blink v0.14.1 (https://github.com/1Axen/Blink)
-- This file is not meant to be edited
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
if not RunService:IsServer() then
error("Server network module can only be required from the server.")
end
local Reliable: RemoteEvent = ReplicatedStorage:FindFirstChild("BLINK_RELIABLE_REMOTE") :: RemoteEvent
if not Reliable then
local RemoteEvent = Instance.new("RemoteEvent")
RemoteEvent.Name = "BLINK_RELIABLE_REMOTE"
RemoteEvent.Parent = ReplicatedStorage
Reliable = RemoteEvent
end
local Unreliable: UnreliableRemoteEvent =
ReplicatedStorage:FindFirstChild("BLINK_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent
if not Unreliable then
local UnreliableRemoteEvent = Instance.new("UnreliableRemoteEvent")
UnreliableRemoteEvent.Name = "BLINK_UNRELIABLE_REMOTE"
UnreliableRemoteEvent.Parent = ReplicatedStorage
Unreliable = UnreliableRemoteEvent
end
local Invocations = 0
local SendSize = 64
local SendOffset = 0
local SendCursor = 0
local SendBuffer = buffer.create(64)
local SendInstances = {}
local RecieveCursor = 0
local RecieveBuffer = buffer.create(64)
local RecieveInstances = {}
local RecieveInstanceCursor = 0
type Entry = {
value: any,
next: Entry?,
}
type Queue = {
head: Entry?,
tail: Entry?,
}
type BufferSave = {
Size: number,
Cursor: number,
Buffer: buffer,
Instances: { Instance },
}
local function Read(Bytes: number)
local Offset = RecieveCursor
RecieveCursor += Bytes
return Offset
end
local function Save(): BufferSave
return {
Size = SendSize,
Cursor = SendCursor,
Buffer = SendBuffer,
Instances = SendInstances,
}
end
local function Load(Save: BufferSave?)
if Save then
SendSize = Save.Size
SendCursor = Save.Cursor
SendOffset = Save.Cursor
SendBuffer = Save.Buffer
SendInstances = Save.Instances
return
end
SendSize = 64
SendCursor = 0
SendOffset = 0
SendBuffer = buffer.create(64)
SendInstances = {}
end
local function Invoke()
if Invocations == 255 then
Invocations = 0
end
local Invocation = Invocations
Invocations += 1
return Invocation
end
local function Allocate(Bytes: number)
local InUse = (SendCursor + Bytes)
if InUse > SendSize then
--> Avoid resizing the buffer for every write
while InUse > SendSize do
SendSize *= 1.5
end
local Buffer = buffer.create(SendSize)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
SendBuffer = Buffer
end
SendOffset = SendCursor
SendCursor += Bytes
return SendOffset
end
local function CreateQueue(): Queue
return {
head = nil,
tail = nil,
}
end
local function Pop(queue: Queue): any
local head = queue.head
if head == nil then
return
end
queue.head = head.next
return head.value
end
local function Push(queue: Queue, value: any)
local entry: Entry = {
value = value,
next = nil,
}
if queue.tail ~= nil then
queue.tail.next = entry
end
queue.tail = entry
if queue.head == nil then
queue.head = entry
end
end
local Types = {}
local Calls = table.create(256)
local Events: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
local Queue: any = {
Reliable = table.create(256),
Unreliable = table.create(256),
}
function Types.ReadEVENT_UpdateTransform(): (number, CFrame)
-- Read BLOCK: 32 bytes
local BLOCK_START = Read(32)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
return Value1, Value2
end
function Types.WriteEVENT_UpdateTransform(Value1: number, Value2: CFrame): ()
-- Allocate BLOCK: 33 bytes
local BLOCK_START = Allocate(33)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
end
function Types.ReadEVENT_SpawnMob(): (number, CFrame, number)
-- Read BLOCK: 33 bytes
local BLOCK_START = Read(33)
local Value1 = buffer.readf64(RecieveBuffer, BLOCK_START + 0)
local X = buffer.readf32(RecieveBuffer, BLOCK_START + 8)
local Y = buffer.readf32(RecieveBuffer, BLOCK_START + 12)
local Z = buffer.readf32(RecieveBuffer, BLOCK_START + 16)
local Position = Vector3.new(X, Y, Z)
local rX = buffer.readf32(RecieveBuffer, BLOCK_START + 20)
local rY = buffer.readf32(RecieveBuffer, BLOCK_START + 24)
local rZ = buffer.readf32(RecieveBuffer, BLOCK_START + 28)
local Value2 = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)
local Value3 = buffer.readu8(RecieveBuffer, BLOCK_START + 32)
return Value1, Value2, Value3
end
function Types.WriteEVENT_SpawnMob(Value1: number, Value2: CFrame, Value3: number): ()
-- Allocate BLOCK: 34 bytes
local BLOCK_START = Allocate(34)
buffer.writeu8(SendBuffer, BLOCK_START + 0, 0)
buffer.writef64(SendBuffer, BLOCK_START + 1, Value1)
local Vector = Value2.Position
buffer.writef32(SendBuffer, BLOCK_START + 9, Vector.X)
buffer.writef32(SendBuffer, BLOCK_START + 13, Vector.Y)
buffer.writef32(SendBuffer, BLOCK_START + 17, Vector.Z)
local rX, rY, rZ = Value2:ToOrientation()
buffer.writef32(SendBuffer, BLOCK_START + 21, rX)
buffer.writef32(SendBuffer, BLOCK_START + 25, rY)
buffer.writef32(SendBuffer, BLOCK_START + 29, rZ)
buffer.writeu8(SendBuffer, BLOCK_START + 33, Value3)
end
local PlayersMap: { [Player]: BufferSave } = {}
Players.PlayerRemoving:Connect(function(Player)
PlayersMap[Player] = nil
end)
local function StepReplication()
for Player, Send in PlayersMap do
if Send.Cursor <= 0 then
continue
end
local Buffer = buffer.create(Send.Cursor)
buffer.copy(Buffer, 0, Send.Buffer, 0, Send.Cursor)
Reliable:FireClient(Player, Buffer, Send.Instances)
Send.Size = 64
Send.Cursor = 0
Send.Buffer = buffer.create(64)
table.clear(Send.Instances)
end
end
RunService.Heartbeat:Connect(StepReplication)
Reliable.OnServerEvent:Connect(function(Player: Player, Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
end
end)
Unreliable.OnServerEvent:Connect(function(Player: Player, Buffer: buffer, Instances: { Instance })
RecieveCursor = 0
RecieveBuffer = Buffer
RecieveInstances = Instances
RecieveInstanceCursor = 0
local Size = buffer.len(RecieveBuffer)
while RecieveCursor < Size do
-- Read BLOCK: 1 bytes
local BLOCK_START = Read(1)
local Index = buffer.readu8(RecieveBuffer, BLOCK_START + 0)
end
end)
return {
StepReplication = StepReplication,
UpdateTransform = {
Fire = function(Player: Player, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Unreliable:FireClient(Player, Buffer, SendInstances)
end,
FireAll = function(Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
Unreliable:FireAllClients(Buffer, SendInstances)
end,
FireList = function(List: { Player }, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
for _, Player in List do
Unreliable:FireClient(Player, Buffer, SendInstances)
end
end,
FireExcept = function(Except: Player, Value1: number, Value2: CFrame): ()
Load()
Types.WriteEVENT_UpdateTransform(Value1, Value2)
local Buffer = buffer.create(SendCursor)
buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor)
for _, Player in Players:GetPlayers() do
if Player == Except then
continue
end
Unreliable:FireClient(Player, Buffer, SendInstances)
end
end,
},
SpawnMob = {
Fire = function(Player: Player, Value1: number, Value2: CFrame, Value3: number): ()
Load(PlayersMap[Player])
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
PlayersMap[Player] = Save()
end,
FireAll = function(Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in Players:GetPlayers() do
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
FireList = function(List: { Player }, Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in List do
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
FireExcept = function(Except: Player, Value1: number, Value2: CFrame, Value3: number): ()
Load()
Types.WriteEVENT_SpawnMob(Value1, Value2, Value3)
local Buffer, Size, Instances = SendBuffer, SendCursor, SendInstances
for _, Player in Players:GetPlayers() do
if Player == Except then
continue
end
Load(PlayersMap[Player])
local Position = Allocate(Size)
buffer.copy(SendBuffer, Position, Buffer, 0, Size)
table.move(Instances, 1, #Instances, #SendInstances + 1, SendInstances)
PlayersMap[Player] = Save()
end
end,
},
}

View file

@ -0,0 +1,33 @@
--!strict
local function collect(signal)
local enqueued = {}
local i = 0
local connection = signal:Connect(function(...)
table.insert(enqueued, { ... })
i += 1
end)
return function(): any
if i == 0 then
return
end
i -= 1
local args: any = table.remove(enqueued, 1)
return unpack(args)
end, connection
end
type Signal<T... = ...any> = {
Connect: (self: Signal<T...>, callback: (T...) -> ()) -> RBXScriptConnection,
ConnectParallel: (self: Signal<T...>, callback: (T...) -> ()) -> RBXScriptConnection,
Once: (self: Signal<T...>, callback: (T...) -> ()) -> RBXScriptConnection,
Wait: (self: Signal<T...>) -> (T...)
}
return collect :: <T...>(Signal<T...>) -> (() -> (T...), RBXScriptConnection)

View file

@ -0,0 +1,65 @@
--!strict
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local jecs = require(ReplicatedStorage.ecs)
local types = require("./types")
local Networked = jecs.tag()
local NetworkedPair = jecs.tag()
local InstanceMapping = jecs.component() :: jecs.Id<Instance>
jecs.meta(InstanceMapping, jecs.OnAdd, function(component)
jecs.meta(component, jecs.OnAdd, function(entity, _, instance)
if RunService:IsServer() then
instance:SetAttribute("entity_server")
else
instance:SetAttribute("entity_client")
end
end)
end)
local function networked_id(ct)
jecs.meta(ct, Networked)
return ct
end
local function networked_pair(ct)
jecs.meta(ct, NetworkedPair)
return ct
end
local function instance_mapping_id(ct)
jecs.meta(ct, InstanceMapping)
return ct
end
local Renderable = jecs.component() :: types.Id<Instance>
local Poison = jecs.component() :: types.Id<number>
local Health = jecs.component() :: types.Id<number>
local Player = jecs.component() :: types.Id<Player>
local Debuff = jecs.tag() :: types.Entity
local Lifetime = jecs.component() :: types.Id<{
duration: number,
created: number
}>
local Destroy = jecs.tag()
local components = {
Renderable = networked_id(instance_mapping_id(Renderable)),
Player = networked_id(Player),
Poison = networked_id(Poison),
Health = networked_id(Health),
Lifetime = networked_id(Lifetime),
Debuff = networked_id(Debuff),
Destroy = networked_id(Destroy),
-- We have to define that some builtin IDs can also be networked
ChildOf = networked_pair(jecs.ChildOf),
Networked = Networked,
NetworkedPair = NetworkedPair,
}
for name, component in components :: {[string]: types.Id<any> } do
jecs.meta(component, jecs.Name, name)
end
return components

View file

@ -1,4 +0,0 @@
_G.JECS_DEBUG = true
_G.JECS_HI_COMPONENT_ID = 32
require(game:GetService("ReplicatedStorage").ecs)
return

View file

@ -0,0 +1,10 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local jecs = require(ReplicatedStorage.ecs)
local schedule = require(ReplicatedStorage.schedule)
local heartbeat = schedule(world,
systems.entities_delete,
systems.replication
)
game:GetService("RunService").Heartbeat:Connect(heartbeat)

View file

@ -0,0 +1,42 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local types = require("../ReplicatedStorage/types")
type Remote<T...> = {
FireClient: (Remote<T...>, Player, T...) -> (),
FireAllClients: (Remote<T...>, T...) -> (),
FireServer: (Remote<T...>, T...) -> (),
OnServerEvent: RBXScriptSignal<(Player, T...)>,
OnClientEvent: RBXScriptSignal<T...>
}
local function stream_ensure(name)
local remote = ReplicatedStorage:FindFirstChild(name)
if not remote then
remote = Instance.new("RemoteEvent")
remote.Name = name
remote.Parent = ReplicatedStorage
end
return remote
end
local function datagram_ensure(name)
local remote = ReplicatedStorage:FindFirstChild(name)
if not remote then
remote = Instance.new("UnreliableRemoteEvent")
remote.Name = name
remote.Parent = ReplicatedStorage
end
return remote
end
return {
input = datagram_ensure("input") :: Remote<string>,
replication = stream_ensure("replication") :: Remote<{
[string]: {
set: { types.Entity }?,
values: { any }?,
removed: { types.Entity }?
}
}>,
}

View file

@ -0,0 +1,91 @@
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local jabby = require(ReplicatedStorage.Packages.jabby)
local ct = require(ReplicatedStorage.components)
local jecs = require(ReplicatedStorage.ecs)
jabby.set_check_function(function(player) return true end)
local scheduler = jabby.scheduler.create()
jabby.register({
applet = jabby.applets.scheduler,
name = "Scheduler",
configuration = {
scheduler = scheduler,
},
}::any)
local ContextActionService = game:GetService("ContextActionService")
local function create_widget(_, state: Enum.UserInputState): Enum.ContextActionResult
local client = jabby.obtain_client()
if state ~= Enum.UserInputState.Begin then
return Enum.ContextActionResult.Pass
end
client.spawn_app(client.apps.home::any, nil)
return Enum.ContextActionResult.Sink
end
local RunService = game:GetService("RunService")
local function schedule(world, ...)
local function get_entity_from_part(part: BasePart): (jecs.Entity<any>?, PVInstance?)
for id, model in world:query(ct.Renderable) do
if not part:IsDescendantOf(model) then continue end
return id, model
end
return nil, nil
end
jabby.register({
applet = jabby.applets.world,
name = "World",
configuration = {
world = world,
get_entity_from_part = get_entity_from_part,
},
}::any)
local systems = { ... }
local function systems_load(mod: ModuleScript, ...)
local fn = require(mod) :: (...any) -> ()
local system = fn(...) or fn
local system_id = scheduler:register_system({
name = mod.Name,
module = mod,
})
return {
system = system,
id = system_id
}
end
for i, mod in systems do
systems[i] = systems_load(mod, world, 0)
end
if RunService:IsClient() then
ContextActionService:BindAction(
"Open Jabby Home",
create_widget,
false,
Enum.KeyCode.F4
)
end
return function(dt: number, input: InputObject?)
for i, config in systems do
-- config.system(world, dt, input)
local system = config.system
local id = config.id
scheduler:run(id, system,
world, dt, input)
end
end
end
return schedule

View file

@ -1,34 +0,0 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local jabby = require(ReplicatedStorage.Packages.jabby)
local std = ReplicatedStorage.std
local scheduler = require(std.scheduler)
local world = require(std.world)
local function start(modules)
for _, module in modules do
require(module)
end
local events = scheduler.COLLECT()
scheduler.BEGIN(events)
jabby.set_check_function(function(player)
return true
end)
if RunService:IsClient() then
local player = game:GetService("Players").LocalPlayer
local playergui = player:WaitForChild("PlayerGui")
local client = jabby.obtain_client()
UserInputService.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.F4 then
local home = playergui:FindFirstChild("Home")
if home then
home:Destroy()
end
client.spawn_app(client.apps.home)
end
end)
end
end
return start

View file

@ -1,40 +0,0 @@
--!optimize 2
--!native
-- original author @centau
local FAILURE = -1
local RUNNING = 0
local SUCCESS = 1
local function SEQUENCE(nodes)
return function(...)
for _, node in nodes do
local status = node(...)
if status <= RUNNING then
return status
end
end
return SUCCESS
end
end
local function FALLBACK(nodes)
return function(...)
for _, node in nodes do
local status = node(...)
if status > FAILURE then
return status
end
end
return FAILURE
end
end
local bt = {
SEQUENCE = SEQUENCE,
FALLBACK = FALLBACK,
RUNNING = RUNNING,
}
return bt

View file

@ -1,67 +0,0 @@
--!nonstrict
--[[
local signal = Signal.new() :: Signal.Signal<string, string>
local events = collect(signal)
local function system(world)
for id, str1, str2 in events do
--
end
end
]]
--[[
original author by @memorycode
MIT License
Copyright (c) 2024 Michael
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
type Signal<T...> = { [any]: any }
local function collect<T...>(event: Signal<T...>)
local storage = {}
local mt = {}
local iter = function()
local n = #storage
return function()
if n <= 0 then
mt.__iter = nil
return nil
end
n -= 1
return n + 1, unpack(table.remove(storage, 1) :: any)
end
end
local disconnect = event:Connect(function(...)
table.insert(storage, { ... })
mt.__iter = iter
end)
setmetatable(storage, mt)
return (storage :: any) :: () -> (number, T...), function()
disconnect()
end
end
return collect

View file

@ -1,30 +0,0 @@
local jecs = require(game:GetService("ReplicatedStorage").ecs)
local world = require(script.Parent.world)
type Entity<T = nil> = jecs.Entity<T>
local components: {
Character: Entity<Model>,
Mob: Entity,
Model: Entity<Model>,
Player: Entity,
Target: Entity,
Transform: Entity<{ new: CFrame, old: CFrame }>,
Velocity: Entity<number>,
Previous: Entity,
} =
{
Character = world:component(),
Mob = world:component(),
Model = world:component(),
Player = world:component(),
Target = world:component(),
Transform = world:component(),
Velocity = world:component(),
Previous = world:component(),
}
for name, component in components :: {[string]: jecs.Entity} do
world:set(component, jecs.Name, name)
end
return table.freeze(components)

View file

@ -1,19 +0,0 @@
local function interval(s)
local pin
local function throttle()
if not pin then
pin = os.clock()
end
local elapsed = os.clock() - pin > s
if elapsed then
pin = os.clock()
end
return elapsed
end
return throttle
end
return interval

View file

@ -1,14 +0,0 @@
local std = game:GetService("ReplicatedStorage").std
local Players = game:GetService("Players")
local scheduler = require(std.scheduler)
local PHASE = scheduler.PHASE
return {
PlayerAdded = PHASE({
event = Players.PlayerAdded
}),
PlayerRemoved = PHASE({
event = Players.PlayerRemoving
})
}

View file

@ -1,26 +0,0 @@
local world = require(script.Parent.world)
local jecs = require(game:GetService("ReplicatedStorage").ecs)
local refs: {[any]: jecs.Entity} = {}
local function fini(key): () -> ()
return function()
refs[key] = nil
end
end
local function noop() end
local function ref(key): (jecs.Entity, () -> ())
if not key then
return world:entity(), noop
end
local e = refs[key]
if not e then
e = world:entity()
refs[key] = e
end
-- Cannot cache handles because they will get invalidated
return e, fini(key)
end
return ref

View file

@ -1,167 +0,0 @@
--!native
--!optimize 2
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local jabby = require(ReplicatedStorage.Packages.jabby)
local jecs = require(ReplicatedStorage.ecs)
local pair = jecs.pair
local Name = jecs.Name
type World = jecs.World
type Entity<T = nil> = jecs.Entity<T>
type Id<T = unknown> = jecs.Id<T>
type System = {
callback: (world: World) -> (),
id: number,
}
type Systems = { System }
type Events = {
RenderStepped: Systems,
Heartbeat: Systems,
}
local world = require(script.Parent.world)
local Disabled = world:entity()
local System = world:component() :: Id<{ callback: (any) -> (), name: string}>
local DependsOn = world:entity()
local Event = world:component() :: Id<RBXScriptSignal>
local Phase = world:entity()
local PreRender = world:entity()
local Heartbeat = world:entity()
local PreAnimation = world:entity()
local PreSimulation = world:entity()
local sys: System
local dt: number
local jabby_scheduler = jabby.scheduler.create("Scheduler")
local a, b, c, d
local function run()
local id = sys.id
jabby_scheduler:run(id, sys.callback, a, b, c, d)
return nil
end
world:add(Heartbeat, Phase)
world:set(Heartbeat, Event, RunService.Heartbeat)
world:add(PreSimulation, Phase)
world:set(PreSimulation, Event, RunService.PreSimulation)
world:add(PreAnimation, Phase)
world:set(PreAnimation, Event, RunService.PreAnimation)
table.insert(jabby.public, {
class_name = "World",
name = "MyWorld",
world = world,
debug = Name,
entities = {},
})
jabby.public.updated = true
table.insert(jabby.public, jabby_scheduler)
if RunService:IsClient() then
world:add(PreRender, Phase)
world:set(PreRender, Event, (RunService :: RunService).PreRender)
end
local function begin(events: { [RBXScriptSignal]: Systems })
local connections = {}
for event, systems in events do
if not event then
continue
end
local event_name = tostring(event)
connections[event] = event:Connect(function(...)
debug.profilebegin(event_name)
for _, s in systems do
sys = s
a, b, c, d = ...
for _ in run do
break
end
end
debug.profileend()
end)
end
return connections
end
local function scheduler_collect_systems_under_phase_recursive(systems, phase: Entity)
local phase_name = world:get(phase, Name)
for _, s in world:query(System):with(pair(DependsOn, phase)) do
table.insert(systems, {
id = jabby_scheduler:register_system({
name = s.name,
phase = phase_name,
} :: any),
callback = s.callback,
})
end
for after in world:query(Phase):with(pair(DependsOn, phase)):iter() do
scheduler_collect_systems_under_phase_recursive(systems, after)
end
end
local function scheduler_collect_systems_under_event(event)
local systems = {}
scheduler_collect_systems_under_phase_recursive(systems, event)
return systems
end
local function scheduler_collect_systems_all()
local events = {}
for phase, event in world:query(Event):with(Phase) do
events[event] = scheduler_collect_systems_under_event(phase)
end
return events
end
local function scheduler_phase_new(d: { after: Entity?, event: RBXScriptSignal? })
local phase = world:entity()
world:add(phase, Phase)
local after = d.after
if after then
local dependency = pair(DependsOn, after :: Entity)
world:add(phase, dependency)
end
local event = d.event
if event then
world:set(phase, Event, event)
end
return phase
end
local function scheduler_systems_new(callback: (any) -> (), phase: Entity?)
local system = world:entity()
world:set(system, System, { callback = callback, name = debug.info(callback, "n") })
local depends_on = DependsOn :: jecs.Entity
local p: Entity = phase or Heartbeat
world:add(system, pair(depends_on, p))
return system
end
return {
SYSTEM = scheduler_systems_new,
BEGIN = begin,
PHASE = scheduler_phase_new,
COLLECT = scheduler_collect_systems_all,
phases = {
Heartbeat = Heartbeat,
PreSimulation = PreSimulation,
PreAnimation = PreAnimation,
PreRender = PreRender
}
}

View file

@ -1,4 +0,0 @@
local jecs = require(game:GetService("ReplicatedStorage").ecs)
-- I like the idea of only having the world be a singleton.
return jecs.World.new() :: jecs.World

View file

@ -0,0 +1,13 @@
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local types = require(ReplicatedStorage.types)
local ct = require(ReplicatedStorage.components)
local function entities_delete(world: types.World, dt: number)
for e in world:each(ct.Destroy) do
world:delete(e)
end
end
return entities_delete

View file

@ -0,0 +1,121 @@
local types = require("../types")
local jecs = require(game:GetService("ReplicatedStorage").ecs)
local remotes = require("../remotes")
local collect = require("../collect")
local components = require("../components")
local client_ids: {[jecs.Entity]: jecs.Entity } = {}
local function ecs_ensure_entity(world: jecs.World, id: jecs.Entity)
local e = 0
local ser_id = id
local deser_id = client_ids[ser_id]
if deser_id then
if deser_id == 0 then
local new_id = world:entity()
client_ids[ser_id] = new_id
deser_id = new_id
end
else
if not world:exists(ser_id)
or (world:contains(ser_id) and not world:get(ser_id, jecs.Name))
then
deser_id = world:entity()
else
if world:contains(ser_id) and world:get(ser_id, jecs.Name) then
deser_id = ser_id
else
deser_id = world:entity()
end
end
client_ids[ser_id] = deser_id
end
e = deser_id
return e
end
-- local rel_render = `e{jecs.ECS_ID(rel)}v{jecs.ECS_GENERATION(rel)}`
-- local tgt_render = `e{jecs.ECS_ID(tgt)}v{jecs.ECS_GENERATION(tgt)}`
-- local function ecs_deser_pairs_str(world, token)
-- local tokens = string.split(token, ",")
-- local rel = tonumber(tokens[1]) :: jecs.Entity
-- local tgt = tonumber(tokens[2]) :: jecs.Entity
-- rel = ecs_ensure_entity(world, rel)
-- tgt = ecs_ensure_entity(world, tgt)
-- return jecs.pair(rel, tgt)
-- end
local function ecs_deser_pairs(world, rel, tgt)
rel = ecs_ensure_entity(world, rel)
tgt = ecs_ensure_entity(world, tgt)
return jecs.pair(rel, tgt)
end
local snapshots = collect(remotes.replication.OnClientEvent)
return function(world: jecs.World)
for entity in world:each(components.Destroy) do
client_ids[entity] = nil
end
for snapshot in snapshots do
for ser_id, map in snapshot do
local id = (tonumber(ser_id) :: any) :: jecs.Entity
if jecs.IS_PAIR(id) and map.pair then
id = ecs_deser_pairs(world, map.relation, map.target)
elseif id then
id = ecs_ensure_entity(world, id)
end
-- if not id then
-- id = ecs_deser_pairs_str(world, ser_id)
-- else
-- id = ecs_ensure_entity(world, id)
-- end
local members = world:get(id, components.NetworkedMembers)
local set = map.set
if set then
if jecs.is_tag(world, id) then
for _, entity in set do
entity = ecs_ensure_entity(world, entity)
world:add(entity, id)
end
else
local values = map.values :: { any }
for i, entity in set do
entity = ecs_ensure_entity(world, entity)
local value = values[i]
if members then
for _, member in members do
local data = value[member] :: {jecs.Entity} | jecs.Entity -- targets
if typeof(data) == "table" then
for pos, tgt in data :: { jecs.Entity } do
data[pos] = ecs_ensure_entity(world, tgt)
end
else
value[member] = ecs_ensure_entity(world, data :: any)
end
end
end
world:set(entity, id, value)
end
end
end
local removed = map.removed
if removed then
for _, entity in removed do
entity = ecs_ensure_entity(world, entity)
world:remove(entity, id)
end
end
end
end
end

View file

@ -0,0 +1,14 @@
local jecs = require(game:GetService("ReplicatedStorage").ecs)
export type World = typeof(jecs.world())
export type Entity = jecs.Entity
export type Id<T> = jecs.Id<T>
export type Snapshot = {
[string]: {
set: { jecs.Entity }?,
values: { any }?,
removed: { jecs.Entity }?
}
}
return {}

21
demo/src/ServerScriptService/main.server.luau Normal file → Executable file
View file

@ -1,4 +1,21 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local start = require(ReplicatedStorage.start)
local ServerScriptService = game:GetService("ServerScriptService")
local jecs = require(ReplicatedStorage.ecs)
local schedule = require(ReplicatedStorage.schedule)
start(script.Parent:WaitForChild("systems"):GetChildren())
require(ReplicatedStorage.components)
local world = jecs.world()
local systems = ServerScriptService.systems
local heartbeat = schedule(world,
systems.players_added,
systems.poison_hurts,
systems.health_regen,
systems.lifetimes_expire,
systems.life_is_painful,
systems.entities_delete,
systems.replication
)
game:GetService("RunService").Heartbeat:Connect(heartbeat)

View file

@ -0,0 +1,15 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ct = require(ReplicatedStorage.components)
local types = require(ReplicatedStorage.types)
return function(world: types.World, dt: number)
for e in world:query(ct.Player):without(ct.Health) do
world:set(e, ct.Health, 100)
end
for e, health in world:query(ct.Health) do
if math.random() < 1 / 60 / 30 then
world:set(e, ct.Health, 100)
end
end
end

View file

@ -0,0 +1,19 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ct = require(ReplicatedStorage.components)
local types = require(ReplicatedStorage.types)
local jecs = require(ReplicatedStorage.ecs)
return function(world: types.World, dt: number)
if math.random() < (1 / 60 / 7) then
for e in world:each(ct.Health) do
local poison = world:entity()
world:add(poison, ct.Debuff)
world:add(poison, jecs.pair(jecs.ChildOf, e))
world:set(poison, ct.Poison, 10)
world:set(poison, ct.Lifetime, {
duration = 3,
created = os.clock()
})
end
end
end

View file

@ -0,0 +1,12 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ct = require(ReplicatedStorage.components)
local types = require(ReplicatedStorage.types)
return function(world: types.World, dt: number)
for e, lifetime in world:query(ct.Lifetime) do
if os.clock() > lifetime.created + lifetime.duration then
world:add(e, ct.Destroy)
end
end
end

View file

@ -1,88 +0,0 @@
--!optimize 2
--!native
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local blink = require(game:GetService("ServerScriptService").net)
local jecs = require(ReplicatedStorage.ecs)
local __ = jecs.Wildcard
local std = ReplicatedStorage.std
local ref = require(std.ref)
local interval = require(std.interval)
local world = require(std.world)
local cts = require(std.components)
local Mob = cts.Mob
local Transform = cts.Transform
local Velocity = cts.Velocity
local Player = cts.Player
local Character = cts.Character
local characters = world
:query(Character)
:with(Player)
:cached()
local moving_mobs = world
:query(Transform, Velocity)
:with(Mob)
:cached()
local function mobsMove(dt: number)
local targets = {}
for _, character in characters do
table.insert(targets, (character.PrimaryPart :: Part).Position)
end
for mob, transform, v in moving_mobs do
local cf = transform.new
local p = cf.Position
local target
local closest
for _, pos in targets do
local distance = (p - pos).Magnitude
if not target or distance < closest then
target = pos
closest = distance
end
end
if not target then
continue
end
local moving = CFrame.new(p + (target - p).Unit * dt * v)
transform.new = moving
blink.UpdateTransform.FireAll(mob, moving)
end
end
local throttle = interval(5)
local function spawnMobs()
if throttle() then
local p = Vector3.new(0, 5, 0)
local cf = CFrame.new(p)
local v = 5
local e = world:entity()
world:set(e, Velocity, v)
world:set(e, Transform, { new = cf })
world:add(e, Mob)
blink.SpawnMob.FireAll(e, cf, v)
end
end
local scheduler = require(std.scheduler)
scheduler.SYSTEM(spawnMobs)
scheduler.SYSTEM(mobsMove)
return 0

View file

@ -1,40 +0,0 @@
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local std = ReplicatedStorage.std
local ref = require(std.ref)
local collect = require(std.collect)
local cts = require(std.components)
local world = require(std.world)
local Player = cts.Player
local Character = cts.Character
local conn = {}
local function playersAdded(player: Player)
local e = ref(player.UserId)
world:set(e, Player, player)
local characterAdd = player.CharacterAdded
conn[e] = characterAdd:Connect(function(rig)
while rig.Parent ~= workspace do
task.wait()
end
world:set(e, Character, rig)
end)
end
local function playersRemoved(player: Player)
local e = ref(player.UserId)
world:clear(e)
local connection = conn[e]
connection:Disconnect()
conn[e] = nil
end
local scheduler = require(std.scheduler)
local phases = require(std.phases)
scheduler.SYSTEM(playersAdded, phases.PlayerAdded)
scheduler.SYSTEM(playersRemoved, phases.PlayerRemoved)
return 0

View file

@ -0,0 +1,24 @@
local collect = require("../../ReplicatedStorage/collect")
local types = require("../../ReplicatedStorage/types")
local ct = require("../../ReplicatedStorage/components")
local Players = game:GetService("Players")
local player_added = collect(Players.PlayerAdded)
return function(world: types.World, dt: number)
for player in player_added do
local entity = world:entity()
world:set(entity, ct.Player, player)
end
for entity, player in world:query(ct.Player):without(ct.Renderable) do
local character = player.Character
if not character then
continue
end
if not character.Parent then
continue
end
world:set(entity, ct.Renderable, character)
end
end

View file

@ -0,0 +1,18 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ct = require(ReplicatedStorage.components)
local types = require(ReplicatedStorage.types)
local jecs = require(ReplicatedStorage.ecs)
return function(world: types.World, dt: number)
for e, poison_tick in world:query(ct.Poison, jecs.pair(jecs.ChildOf, jecs.w)) do
local tgt = world:target(e, jecs.ChildOf)
local health = world:get(tgt, ct.Health)
if not health then
continue
end
if math.random() < 1 / 60 / 1 and health > 1 then
world:set(tgt, ct.Health, health - 1)
end
end
end

View file

@ -0,0 +1,222 @@
--!strict
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ct = require(ReplicatedStorage.components)
local components = ct :: { [string]: jecs.Entity }
local remotes = require(ReplicatedStorage.remotes)
local jecs = require(ReplicatedStorage.ecs)
local collect = require(ReplicatedStorage.collect)
local ty = require(ReplicatedStorage.types)
return function(world: jecs.World)
local storages = {} :: { [jecs.Entity]: {[jecs.Entity]: any }}
local networked_components = {}
local networked_pairs = {}
for component in world:each(ct.Networked) do
local name = world:get(component, jecs.Name)
assert(name)
if components[name] == nil then
error("Invalid component:"..name)
end
storages[component] = {}
table.insert(networked_components, component)
end
for relation in world:each(ct.NetworkedPair) do
local name = world:get(relation, jecs.Name)
assert(name)
if not components[name] then
error("Invalid component")
end
table.insert(networked_pairs, relation)
end
for _, component in networked_components do
local name = world:get(component, jecs.Name)
if not name or not components[name] then
-- error("Invalid component")
error(`Networked Component (%id{component}%name{name})`)
end
local is_tag = jecs.is_tag(world, component)
local storage = storages[component]
if is_tag then
world:added(component, function(entity)
storage[entity] = true
end)
else
world:added(component, function(entity, _, value)
storage[entity] = value
end)
world:changed(component, function(entity, _, value)
storage[entity] = value
end)
end
world:removed(component, function(entity)
storage[entity] = "jecs.Remove"
end)
end
for _, relation in networked_pairs do
world:added(relation, function(entity: jecs.Entity, id: jecs.Id, value)
local is_tag = jecs.is_tag(world, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
if is_tag then
storage[entity] = true
else
storage[entity] = value
end
end)
world:changed(relation, function(entity: jecs.Id, id: jecs.Id, value)
local is_tag = jecs.is_tag(world, id)
if is_tag then
return
end
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
storage[entity] = value
end)
world:removed(relation, function(entity, id)
local storage = storages[id]
if not storage then
storage = {}
storages[id] = storage
end
storage[entity] = "jecs.Remove"
end)
end
-- local requested_snapshots = collect(remotes.request_snapshot.OnServerEvent)
local players_added = collect(Players.PlayerAdded)
return function(_, dt: number)
local snapshot_lazy: ty.snapshot
local set_ids_lazy: { jecs.Entity }
-- In the future maybe it should be requested by the player instead when they
-- are ready to receive the replication. Otherwise streaming could be complicated
-- with intances references being nil.
for player in players_added do
if not snapshot_lazy then
snapshot_lazy, set_ids_lazy = {}, {}
for component, storage in storages do
local set_values = {}
local set_n = 0
local q = world:query(component)
local is_tag = jecs.is_tag(world, component)
for _, archetype in q:archetypes() do
local entities = archetype.entities
local entities_len = #entities
table.move(entities, 1, entities_len, set_n + 1, set_ids_lazy)
if not is_tag then
local column = archetype.columns_map[component]
table.move(column, 1, entities_len, set_n + 1, set_values)
end
set_n += entities_len
end
local set = table.move(set_ids_lazy, 1, set_n, 1, {})
local map = {
set = if set_n > 0 then set else nil,
values = if set_n > 0 then set_values else nil,
}
if jecs.IS_PAIR(component) then
map.relation = jecs.pair_first(world, component)
map.target = jecs.pair_second(world, component)
map.pair = true
end
snapshot_lazy[tostring(component)] = map
end
end
remotes.replication:FireClient(player, snapshot_lazy)
end
-- accumulator += dt
-- Purposely sending less diffs of the world because doing it at 60hz
-- gets expensive. But this requires interpolated elements in the scene.
-- if accumulator > 1/60 then
-- accumulator = 0
local snapshot = {} :: ty.snapshot
local set_ids = {}
local removed_ids = {}
for component, storage in storages do
local set_values = {} :: { any }
local set_n = 0
local removed_n = 0
for e, v in storage do
if v ~= "jecs.Remove" then
set_n += 1
set_ids[set_n] = e
set_values[set_n] = v or true
elseif world:contains(e) then
removed_n += 1
removed_ids[removed_n] = e
end
end
table.clear(storage)
local dirty = false
if set_n > 0 or removed_n > 0 then
dirty = true
end
if dirty then
local removed = table.move(removed_ids, 1, removed_n, 1, {}) :: { jecs.Entity }
local set = table.move(set_ids, 1, set_n, 1, {}) :: { jecs.Entity }
-- local ser_id: string = nil :: any
-- if jecs.IS_PAIR(component) then
-- ser_id = `{jecs.pair_first(world, component)},{jecs.pair_second(world, component)}`
-- else
-- ser_id = tostring(component)
-- end
local map = {
set = if set_n > 0 then set else nil,
values = if set_n > 0 then set_values else nil,
removed = if removed_n > 0 then removed else nil,
}
if jecs.IS_PAIR(component) then
map.relation = jecs.pair_first(world, component)
map.target = jecs.pair_second(world, component)
map.pair = true
end
snapshot[tostring(component)] = map
end
end
if next(snapshot) ~= nil then
remotes.replication:FireAllClients(snapshot)
-- print(snapshot)
end
end
end

View file

@ -1,4 +0,0 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local start = require(ReplicatedStorage.start)
start(script.Parent:WaitForChild("systems"):GetChildren())

View file

@ -1,41 +0,0 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local blink = require(ReplicatedStorage.net)
local std = ReplicatedStorage.std
local world = require(std.world)
local ref = require(std.ref)
local cts = require(std.components)
local Model = cts.Model
local Transform = cts.Transform
local moving_models = world:query(Transform, Model):cached()
local function move(dt: number)
for _, transform, model in moving_models do
local cf = transform.new
if cf ~= transform.old then
local part = model.PrimaryPart :: BasePart
local origo = part.CFrame
part.CFrame = origo:Lerp(cf, 1)
transform.old = cf
end
end
end
local function syncTransforms()
for _, id, cf in blink.UpdateTransform.Iter() do
local e = ref("server-" .. tostring(id))
local transform = world:get(e, Transform)
if not transform then
continue
end
transform.new = cf
end
end
local scheduler = require(std.scheduler)
scheduler.SYSTEM(move)
scheduler.SYSTEM(syncTransforms)
return 0

View file

@ -1,31 +0,0 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local blink = require(ReplicatedStorage.net)
local std = ReplicatedStorage.std
local ref = require(std.ref)
local world = require(std.world)
local cts = require(std.components)
local function syncMobs()
for _, id, cf, vel in blink.SpawnMob.Iter() do
local part = Instance.new("Part")
part.Size = Vector3.one * 5
part.BrickColor = BrickColor.Red()
part.Anchored = true
local model = Instance.new("Model")
model.PrimaryPart = part
part.Parent = model
model.Parent = workspace
local e = ref("server-" .. tostring(id))
world:set(e, cts.Transform, { new = cf, old = cf })
world:set(e, cts.Velocity, vel)
world:set(e, cts.Model, model)
world:add(e, cts.Mob)
end
end
local scheduler = require(std.scheduler)
scheduler.SYSTEM(syncMobs)
return 0

View file

@ -1,44 +0,0 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local std = ReplicatedStorage.std
local world = require(std.world)
local A = world:component()
local B = world:component()
local C = world:component()
local D = world:component()
local function flip()
return math.random() >= 0.15
end
for i = 1, 2^8 do
local e = world:entity()
if flip() then
world:set(e, A, true)
end
if flip() then
world:set(e, B, true)
end
if flip() then
world:set(e, C, true)
end
if flip() then
world:set(e, D, true)
end
end
local function uncached()
for _ in world:query(A, B, C, D) do
end
end
local q = world:query(A, B, C, D):cached()
local function cached()
for _ in q do
end
end
local scheduler = require(std.scheduler)
scheduler.SYSTEM(uncached)
scheduler.SYSTEM(cached)
return 0

2
demo/wally.toml Normal file → Executable file
View file

@ -5,4 +5,4 @@ registry = "https://github.com/UpliftGames/wally-index"
realm = "shared"
[dependencies]
jabby = "alicesaidhi/jabby@0.2.0-rc.3"
jabby = "alicesaidhi/jabby@0.2.2"

119
docs/.vitepress/config.mts Normal file → Executable file
View file

@ -1,69 +1,50 @@
import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "Jecs",
base: "/jecs/",
description: "A VitePress Site",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Learn', link: '/' },
{ text: 'API', link: '/api/jecs.md' },
{ text: 'Examples', link: 'https://github.com/Ukendio/jecs/tree/main/examples' },
],
sidebar: {
"/api/": [
{
text: "API reference",
items: [
{ text: "jecs", link: "/api/jecs" },
{ text: "World", link: "/api/world" },
{ text: "Query", link: "/api/query" }
]
}
],
"/learn/": [
{
text: "Introduction",
items: [
{ text: 'Getting Started', link: '/learn/overview/get-started' },
{ text: 'First Jecs Project', link: '/learn/overview/first-jecs-project' }
]
},
{
text: 'Concepts',
items: [
{ text: 'Entities and Components', link: '/learn/concepts/entities-and-components' },
{ text: 'Queries', link: '/learn/concepts/queries' },
{ text: 'Relationships', link: '/learn/concepts/relationships' },
{ text: 'Component Traits', link: 'learn/concepts/component-traits' },
{ text: 'Addons', link: '/learn/concepts/addons' }
]
},
{
text: "FAQ",
items: [
{ text: 'How can I contribute?', link: '/learn/faq/contributing' }
]
},
],
"/contributing/": [
{
text: 'Contributing',
items: [
{ text: 'Contribution Guidelines', link: '/learn/contributing/guidelines' },
{ text: 'Submitting Issues', link: '/learn/contributing/issues' },
{ text: 'Submitting Pull Requests', link: '/learn/contributing/pull-requests' },
]
}
]
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/ukendio/jecs' }
]
}
})
import { defineConfig } from "vitepress";
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "Jecs",
base: "/jecs/",
description: "A VitePress Site",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: "Learn", link: "/learn/overview.md" },
{ text: "API", link: "/api/jecs.md" },
{ text: "Resources", link: "/resources" },
],
sidebar: {
"/api/": [
{
text: "Namespaces",
items: [
{ text: "jecs", link: "/api/jecs" },
{ text: "World", link: "/api/world" },
{ text: "Query", link: "/api/query" },
],
},
],
"/learn/": [
{
text: "API Reference",
items: [
{ text: "jecs", link: "/api/jecs" },
{ text: "World", link: "/api/world" },
{ text: "Query", link: "/api/query" },
],
},
{
text: "Contributing",
items: [
{ text: "Contribution Guidelines", link: "/learn/contributing/guidelines" },
{ text: "Submitting Issues", link: "/learn/contributing/issues" },
{ text: "Submitting Pull Requests", link: "/learn/contributing/pull-requests" },
{ text: "Code Coverage", link: "/learn/contributing/coverage" },
],
},
],
},
socialLinks: [{ icon: "github", link: "https://github.com/ukendio/jecs" }],
},
});

193
docs/api/jecs.md Normal file → Executable file
View file

@ -1,50 +1,143 @@
# Jecs
Jecs. Just an Entity Component System.
# Properties
## World
```luau
jecs.World: World
```
A world is a container of all ECS data. Games can have multiple worlds but component IDs may conflict between worlds. Ensure to register the same component IDs in the same order for each world.
## Wildcard
```luau
jecs.Wildcard: Entity
```
Builtin component type. This ID is used for wildcard queries.
## Component
```luau
jecs.Component: Entity
```
Builtin component type. Every ID created with [world:component()](world.md#component()) has this type added to it. This is meant for querying every component ID.
## ChildOf
```luau
jecs.ChildOf: Entity
```
Builtin component type. This ID is for creating parent-child hierarchies.
## Rest
```luau
jecs.Rest: Entity
```
# Functions
## pair()
```luau
function jecs.pair(
first: Entity, -- The first element of the pair, referred to as the relationship of the relationship pair.
object: Entity, -- The second element of the pair, referred to as the target of the relationship pair.
): number -- Returns the ID with those two elements
```
::: info
Note that while relationship pairs can be used as components, meaning you can add data with it as an ID, however they cannot be used as entities. Meaning you cannot add components to a pair as the source of a binding.
:::
# Jecs
Jecs. Just an Entity Component System.
# Members
## World
```luau
jecs.World: World
```
A world is a container of all ECS data. Games can have multiple worlds but component IDs may conflict between worlds. Ensure to register the same component IDs in the same order for each world.
## Wildcard
```luau
jecs.Wildcard: Id
```
Builtin component type. This ID is used for wildcard queries.
## Component
```luau
jecs.Component: Id
```
Builtin component type. Every ID created with [world:component()](world.md#component()) has this type added to it. This is meant for querying every component ID.
## ChildOf
```luau
jecs.ChildOf: Id
```
Builtin component type. This ID is for creating parent-child hierarchies.
## OnAdd
```luau
jecs.OnAdd: Id
```
Builtin component type. This ID is for setting up a callback that is invoked when an instance of a component is added.
## OnRemove
```luau
jecs.OnRemove: Id
```
Builtin component type. This ID is for setting up a callback that is invoked when an instance of a component is removed.
## OnChange
```luau
jecs.OnChange: Id
```
Builtin component type. This ID is for setting up a callback that is invoked when an instance of a component is changed.
## Exclusive
```lua
jecs.Exclusive: Id
```
Builtin component type. This ID is for encoding that an ID is Exclusive meaning that an entity can never have more than one target for that exclusive relation.
:::code-group
```luau [luau]
local ChildOf = world:entity()
world:add(ChildOf, jecs.Exclusive)
local pop = world:entity()
local dad = world:entity()
local kid = world:entity()
world:add(kid, pair(ChildOf, dad))
print(world:target(kid, ChildOf, 0) == dad)
world:add(kid, pair(ChildOf, pop))
print(world:target(kid, ChildOf, 1) == dad) -- If ChildOf was not exclusive this would have been true
print(world:target(kid, ChildOf, 0) == pop)
-- Output:
-- true
-- false
-- true
```
:::info
By default, jecs.ChildOf is already an exclusive relationship and this is just a demonstration of how to use it.
In some cases you can use Exclusive relationships as a performance optimization as you can guarantee there will only be one target, therefore
retrieving the data from a wildcard pair with that exclusive relationship can be deterministic.
:::
## Name
```luau
jecs.Name: Id
```
Builtin component type. This ID is for naming components, but realistically you could use any component to do that.
## Rest
```luau
jecs.Rest: Id
```
Builtin component type. This ID is simply for denoting the end of the range for builtin component IDs.
# Functions
## pair()
```luau
function jecs.pair(
first: Entity, -- The first element of the pair, referred to as the relationship of the relationship pair.
object: Entity, -- The second element of the pair, referred to as the target of the relationship pair.
): number -- Returns the ID with those two elements
```
::: info
While relationship pairs can be used as components and have data associated with an ID, they cannot be used as entities. Meaning you cannot add components to a pair as the source of a binding.
:::
## pair_first()
```luau
function jecs.pair_first(
pair: Id, -- A full pair ID encoded using a relation-target pair.
): Entity -- The ID of the first element. Returns 0 if the ID is not alive.
```
Returns the first element (the relation part) of a pair ID.
**Example:**
```luau
local Likes = world:component()
local alice = world:entity()
local bob = world:entity()
local pair_id = pair(Likes, alice)
local relation = jecs.pair_first(pair_id)
print(relation == Likes) -- true
```
## pair_second()
```luau
function jecs.pair_second(
pair: Id, -- A full pair ID encoded using a relation-target pair.
): Entity -- The ID of the second element. Returns 0 if the ID is not alive.
```
Returns the second element (the target part) of a pair ID.

196
docs/api/observers.md Executable file
View file

@ -0,0 +1,196 @@
# Observers
The observers addon extends the World with signal-based reactivity and query-based observers. This addon provides a more ergonomic way to handle component lifecycle events and query changes.
## Installation
The observers addon is included with jecs and can be imported directly:
```luau
local jecs = require(path/to/jecs)
local observers_add = require(path/to/jecs/addons/observers)
local world = observers_add(jecs.world())
```
## Methods
### added
Registers a callback that is invoked when a component is added to any entity.
```luau
function World:added<T>(
component: Id<T>,
callback: (entity: Entity, id: Id<T>, value: T?) -> ()
): () -> () -- Returns an unsubscribe function
```
**Parameters:**
- `component` - The component ID to listen for additions
- `callback` - Function called when component is added, receives entity, component ID, and value
**Returns:** An unsubscribe function that removes the listener when called
**Example:**
```luau
local Health = world:component() :: jecs.Entity<number>
local unsubscribe = world:added(Health, function(entity, id, value)
print("Health component added to entity", entity, "with value", value)
end)
-- Later, to stop listening:
unsubscribe()
```
### removed
Registers a callback that is invoked when a component is removed from any entity.
```luau
function World:removed<T>(
component: Id<T>,
callback: (entity: Entity, id: Id<T>) -> ()
): () -> () -- Returns an unsubscribe function
```
**Parameters:**
- `component` - The component ID to listen for removals
- `callback` - Function called when component is removed, receives entity and component ID
**Returns:** An unsubscribe function that removes the listener when called
**Example:**
```luau
local Health = world:component() :: jecs.Entity<number>
local unsubscribe = world:removed(Health, function(entity, id)
print("Health component removed from entity", entity)
end)
```
### changed
Registers a callback that is invoked when a component's value is changed on any entity.
```luau
function World:changed<T>(
component: Id<T>,
callback: (entity: Entity, id: Id<T>, value: T) -> ()
): () -> () -- Returns an unsubscribe function
```
**Parameters:**
- `component` - The component ID to listen for changes
- `callback` - Function called when component value changes, receives entity, component ID, and new value
**Returns:** An unsubscribe function that removes the listener when called
**Example:**
```luau
local Health = world:component() :: jecs.Entity<number>
local unsubscribe = world:changed(Health, function(entity, id, value)
print("Health changed to", value, "for entity", entity)
end)
```
### observer
Creates a query-based observer that triggers when entities match or stop matching a query.
```luau
function World:observer<T...>(
query: Query<T...>,
callback: ((entity: Entity, id: Id, value: any?) -> ())?
): () -> () -> Entity -- Returns an iterator function
```
**Parameters:**
- `query` - The query to observe for changes
- `callback` - Optional function called when entities match the query
**Returns:** An iterator function that returns entities that matched the query since last iteration
**Example:**
```luau
local Position = world:component() :: jecs.Id<Vector3>
local Velocity = world:component() :: jecs.Id<Vector3>
local moving_entities = world:observer(
world:query(Position, Velocity),
function(entity, id, value)
print("Entity", entity, "started moving")
end
)
-- In your game loop:
for entity in moving_entities() do
-- Process newly moving entities
end
```
### monitor
Creates a query-based monitor that triggers when entities are added to or removed from a query.
```luau
function World:monitor<T...>(
query: Query<T...>,
callback: ((entity: Entity, id: Id, value: any?) -> ())?
): () -> () -> Entity -- Returns an iterator function
```
**Parameters:**
- `query` - The query to monitor for additions/removals
- `callback` - Optional function called when entities are added or removed from the query
**Returns:** An iterator function that returns entities that were added or removed since last iteration
**Example:**
```luau
local Health = world:component() :: jecs.Id<number>
local health_changes = world:monitor(
world:query(Health),
function(entity, id, value)
print("Health component changed for entity", entity)
end
)
-- In your game loop:
for entity in health_changes() do
-- Process entities with health changes
end
```
## Usage Patterns
### Component Lifecycle Tracking
```luau
local Player = world:component()
local Health = world:component() :: jecs.Id<number>
-- Track when players are created
world:added(Player, function(entity, id, instance)
instance:SetAttribute("entityid", entity)
end)
world:removed(Player, function(entity, id)
world:add(entity, Destroy) -- process its deletion later!
end)
```
## Performance Considerations
- **Signal listeners** are called immediately when components are added/removed/changed
- **Query observers** cache the query for better performance
- **Multiple listeners** for the same component are supported and called in registration order
- **Unsubscribe functions** should be called when listeners are no longer needed to prevent memory leaks
- **Observer iterators** should be called regularly to clear the internal buffer
## Integration with Built-in Hooks
The observers addon integrates with the built-in component hooks (`OnAdd`, `OnRemove`, `OnChange`). If a component already has these hooks configured, the observers addon will preserve them and call both the original hook and any registered signal listeners.

68
docs/api/query.md Normal file → Executable file
View file

@ -4,13 +4,38 @@ A World contains entities which have components. The World is queryable and can
# Methods
## iter
## cached
Returns an iterator that can be used to iterate over the query.
Returns a cached version of the query. This is useful if you want to create a query that you can iterate multiple times.
```luau
function Query:iter(): () -> (Entity, ...)
function Query:cached(): Query -- Returns the cached Query
```
Example:
::: code-group
```luau [luau]
local lerps = world:query(Lerp):cached() -- Ensure that you cache this outside a system so you do not create a new cache for a query every frame
local function system(dt)
for entity, lerp in lerps do
-- Do something
end
end
```
```ts [typescript]
const lerps = world.query(Lerp).cached()
function system(dt) {
for (const [entity, lerp] of lerps) {
// Do something
}
}
```
:::
## with
@ -83,15 +108,13 @@ Example:
```luau [luau]
for i, archetype in world:query(Position, Velocity):archetypes() do
local columns = archetype.columns
local field = archetype.records
local P = field[Position]
local V = field[Velocity]
local field = archetype.columns_map
local positions = field[Position]
local velocities = field[Velocity]
for row, entity in archetype.entities do
local position = columns[P][row]
local velocity = columns[V][row]
local position = positions[row]
local velocity = velocities[row]
-- Do something
end
end
@ -101,10 +124,27 @@ end
This function is meant for people who want to really customize their query behaviour at the archetype-level
:::
## cached
Returns a cached version of the query. This is useful if you want to iterate over the same query multiple times.
## iter
In most cases, you can iterate over queries directly using `for entity, ... in query do`. The `:iter()` method is mainly useful if you are on the old solver, to get types for the returned values.
```luau
function Query:cached(): Query -- Returns the cached Query
function Query:iter(): () -> (Entity, ...)
```
Example:
::: code-group
```luau [luau]
local query = world:query(Position, Velocity)
-- Direct iteration (recommended)
for entity, position, velocity in query do
-- Process entity
end
-- Using explicit iterator (when needed for the old solver)
local iterator = query:iter()
for entity, position, velocity in iterator do
-- Process entity
end
```

261
docs/api/world.md Normal file → Executable file
View file

@ -6,7 +6,7 @@ A World contains entities which have components. The World is queryable and can
## new
`World` utilizes a class, meaning JECS allows you to create multiple worlds.
`World` utilizes a class, meaning jecs allows you to create multiple worlds.
```luau
function World.new(): World
@ -34,34 +34,33 @@ const myOtherWorld = new World();
## entity
Creates a new entity.
Creates a new entity. It accepts the overload to create an entity with a specific ID.
```luau
function World:entity(): Entity
function World:entity<T>(
id: Entity<T>? -- The desired id
): Entity<T>
```
Example:
::: code-group
```luau [luau]
local entity = world:entity()
```
```ts [typescript]
const entity = world.entity();
```
:::
## component
Creates a new component. Do note components are entities as well, meaning JECS allows you to add other components onto them.
Creates a new component. Do note components are entities as well, meaning jecs allows you to add other components onto them.
These are meant to be added onto other entities through `add` and `set`
```luau
function World:component<T>(): Entity<T> -- The new componen.
function World:component<T>(): Entity<T> -- The new component.
```
Example:
@ -242,7 +241,10 @@ print(world.get(Entity, Health));
// 100
// 50
```
:::
:::info
`world:set(entity, component, value)` propagates that a change has happened for thes component on this entity, while mutating a value directly would not.
:::
## query
@ -290,10 +292,52 @@ If the index is larger than the total number of instances the entity has for the
```luau
function World:target(
entity: Entity, -- The entity
relation: Entity, -- The relationship between the entity and the target
relation: Id, -- The relationship between the entity and the target
nth: number, -- The index
): Entity? -- The target for the relationship at the specified index.
): Id? -- The target for the relationship at the specified index.
```
Example:
::: code-group
```luau [luau]
local function timers_count(world: types.World)
local timers = world
:query(jecs.pair(ct.Timer, jecs.w))
:without(ct.Destroy)
:cached()
return function(_, dt: number)
for entity in timers do
local index = 0
local nth = world:target(entity, ct.Timer, index)
while nth do
local timer = world:get(entity, jecs.pair(ct.Timer, nth))
local elapsed = timer.elapsed + dt
if elapsed >= timer.duration then
world:add(entity, ct.Destroy)
end
timer.elapsed = elapsed
end
end
end
end
```
```ts [typescript]
const entity = world.entity();
print(world.contains(entity));
print(world.contains(1));
print(world.contains(2));
// Outputs:
// true
// true
// false
```
:::
## parent
@ -311,54 +355,17 @@ This operation is the same as calling:
world:target(entity, jecs.ChildOf, 0)
```
## contains
Checks if an entity or component (id) exists in the world.
```luau
function World:contains(
entity: Entity,
): boolean
```
Example:
::: code-group
```luau [luau]
local entity = world:entity()
print(world:contains(entity))
print(world:contains(1))
print(world:contains(2))
-- Outputs:
-- true
-- true
-- false
```
```ts [typescript]
const entity = world.entity();
print(world.contains(entity));
print(world.contains(1));
print(world.contains(2));
// Outputs:
// true
// true
// false
```
:::
## remove
Removes a component (ID) from an entity
```luau
function World:remove(
function World:remove<T>(
entity: Entity,
component: Entity<T>
component: Id<T>
): void
```
@ -416,11 +423,11 @@ Example:
```luau [luau]
local entity = world:entity()
print(world:has(entity))
print(world:contains(entity))
world:delete(entity)
print(world:has(entity))
print(world:contains(entity))
-- Outputs:
-- true
@ -459,28 +466,24 @@ Useful when you only need the entity for a specific ID and you want to avoid cre
```luau
function World:each(
id: Entity -- The component ID
component: Id -- The component ID
): () -> Entity
```
Example:
::: code-group
```luau [luau]
local id = world:entity()
local id = world:component()
for entity in world:each(id) do
-- Do something
end
```
```ts [typescript]
const id = world.entity();
const id = world.component();
for (const entity of world.each(id)) {
// Do something
}
```
:::
## children
@ -498,3 +501,143 @@ This is the same as calling:
```luau
world:each(pair(ChildOf, parent))
```
## range
Enforces a check for entities to be created within a desired range.
```luau
function World:range(
range_begin: number -- The starting point,
range_end: number? -- The end point (optional)
)
```
Example:
::: code-group
```luau [luau]
world:range(1000, 5000) -- Entities will be created with IDs 1000-5000
local entity = world:entity()
print(entity) -- Will be >= 1000 and < 5000
```
```ts [typescript]
world.range(1000, 5000) // Entities will be created with IDs 1000-5000
const entity = world.entity()
print(entity) // Will be >= 1000 and < 5000
```
:::
## parent
Gets the parent entity of the specified entity using the built-in `ChildOf` relationship.
```luau
function World:parent(
entity: Entity
): Entity? -- Returns the parent entity or nil if no parent
```
Example:
::: code-group
```luau [luau]
local parent = world:entity()
local child = world:entity()
world:add(child, pair(jecs.ChildOf, parent))
local retrieved_parent = world:parent(child)
print(retrieved_parent == parent) -- true
```
```ts [typescript]
const parent = world.entity()
const child = world.entity()
world.add(child, pair(jecs.ChildOf, parent))
const retrievedParent = world.parent(child)
print(retrievedParent === parent) // true
```
:::
## contains
Checks if an entity or component (id) exists and is alive in the world.
```luau
function World:contains(
entity: Entity
): boolean
```
Example:
::: code-group
```luau [luau]
local entity = world:entity()
print(world:contains(entity)) -- true
world:delete(entity)
print(world:contains(entity)) -- false
```
```ts [typescript]
const entity = world.entity()
print(world.contains(entity)) // true
world.delete(entity)
print(world.contains(entity)) // false
```
:::
## exists
Checks if the entity ID exists regardless of whether it is alive or not. Useful to know if the ID is occupied in the entity index.
```luau
function World:exists(
entity: Entity
): boolean
```
## cleanup
Cleans up empty archetypes.
```luau
function World:cleanup(): void
```
:::info
It is recommended to profile the optimal interval you should cleanup because it varies completely from game to game.
Here are a couple of reasons from Sander Mertens:
- some applications are memory constrained, so any wasted memory on empty
archetypes has to get cleaned up
- many archetypes can get created during game startup but aren't used later
on, so it would be wasteful to keep them around
- empty archetypes can slow queries down, especially if there are many more
empty ones than non-empty ones
- if the total number of component permutations (/relationships) is too
high, you have no choice but to periodically cleanup empty archetypes
:::
Example:
::: code-group
```luau [luau]
local entity = world:entity()
world:delete(entity)
-- Cleanup is usually automatic, but can be called manually
world:cleanup()
```
```ts [typescript]
const entity = world.entity()
world.delete(entity)
// Cleanup is usually automatic, but can be called manually
world.cleanup()
```
:::

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

6
docs/index.md Normal file → Executable file
View file

@ -10,8 +10,8 @@ hero:
alt: Jecs logo
actions:
- theme: brand
text: Get Started
link: learn/overview/get-started.md
text: Overview
link: learn/overview.md
- theme: alt
text: API References
link: /api/jecs.md
@ -19,7 +19,7 @@ hero:
features:
- title: Stupidly Fast
icon: 🔥
details: Iterates 500,000 entities at 60 frames per second.
details: Iterates 800,000 entities at 60 frames per second.
- title: Strictly Typed API
icon: 🔒
details: Has typings for both Luau and Typescript.

View file

@ -1,16 +0,0 @@
# Assets
A collection of third-party jecs assets made by the community. If you would like to share what you're working on, [submit a pull request](https://github.com/Ukendio/jecs)!
# Debuggers
## [jabby](https://github.com/alicesaidhi/jabby)
A jecs debugger with a string-based query language and entity editing capabilities.
# Schedulers
## [lockstep scheduler](https://gist.github.com/1Axen/6d4f78b3454cf455e93794505588354b)
A simple fixed step system scheduler.
## [sapphire-jecs](https://github.com/Mark-Marks/sapphire/tree/main/crates/sapphire-jecs)
A batteries-included [sapphire](https://github.com/mark-marks/sapphire) scheduler for jecs
## [jam](https://github.com/revvy02/Jam)
Provides hooks and a scheduler that implements jabby and a topographical runtime

View file

@ -1,150 +0,0 @@
# Component Traits
Component traits are IDs and pairs that can be added to components to modify their behavior. Although it is possible to create custom traits, this manual only contains an overview of all builtin component traits supported by Jecs.
# Component
Every (component) ID comes with a `Component` which helps with the distinction between normal entities and component IDs.
# Tag
A (component) ID can be marked with `Tag´ in which the component will never contain any data. This allows for zero-cost components which improves performance for structural changes.
# Hooks
Hooks are part of the "interface" of a component. You could consider hooks as the counterpart to OOP methods in ECS. They define the behavior of a component, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnSet` hook per component, just like you can only have a single constructor and destructor.
## Examples
::: code-group
```luau [luau]
local Transform= world:component()
world:set(Transform, OnAdd, function(entity)
-- A transform component has been added to an entity
end)
world:set(Transform, OnRemove, function(entity)
-- A transform component has been removed from the entity
end)
world:set(Transform, OnSet, function(entity, value)
-- A transform component has been assigned/changed to value on the entity
end)
```
```typescript [typescript]
const Transform = world.component()
world.set(Transform, OnAdd, (entity) => {
// A transform component has been added to an entity
})
world.set(Transform, OnRemove, (entity) => {
// A transform component has been removed from the entity
})
world.set(Transform, OnSet, (entity, value) => {
// A transform component has been assigned/changed to value on the entity
})
```
:::
# Cleanup Traits
When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references.
We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same.
This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it.
To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed.
There are two cleanup actions:
- `Remove`: removes instances of the specified (component) id from all entities (default)
- `Delete`: deletes all entities with specified id
There are two cleanup conditions:
- `OnDelete`: the component, tag or relationship is deleted
- `OnDeleteTarget`: a target used with the relationship is deleted
## Examples
The following examples show how to use cleanup traits
### (OnDelete, Remove)
::: code-group
```luau [luau]
local Archer = world:component()
world:add(Archer, pair(jecs.OnDelete, jecs.Remove))
local e = world:entity()
world:add(e, Archer)
-- This will remove Archer from e
world:delete(Archer)
```
```typescript [typescript]
const Archer = world.component()
world.add(Archer, pair(jecs.OnDelete, jecs.Remove))
const e = world:entity()
world.add(e, Archer)
// This will remove Archer from e
world.delete(Archer)
```
:::
### (OnDelete, Delete)
::: code-group
```luau [luau]
local Archer = world:component()
world:add(Archer, pair(jecs.OnDelete, jecs.Delete))
local e = world:entity()
world:add(e, Archer)
-- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
world:delete(Archer)
```
```typescript [typescript]
const Archer = world.component()
world.add(Archer, pair(jecs.OnDelete, jecs.Delete))
const e = world:entity()
world.add(e, Archer)
// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
world.delete(Archer)
```
:::
### (OnDeleteTarget, Delete)
::: code-group
```luau [luau]
local ChildOf = world:component()
world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete))
local parent = world:entity()
local child = world:entity()
world:add(child, pair(ChildOf, parent))
-- This will delete both parent and child
world:delete(parent)
```
```typescript [typescript]
const Archer = world.component()
world.add(Archer, pair(jecs.OnDelete, jecs.Remove))
const e = world:entity()
world.add(e, Archer)
// This will delete e
world.delete(Archer)
```
:::
This page takes wording and terminology directly from Flecs [documentation](https://www.flecs.dev/flecs/md_docs_2ComponentTraits.html)

View file

@ -1,113 +0,0 @@
# Entities and Components
## Entities
Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc.
By itself, an entity is just an unique identifier without any data
## Components
A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples").
### Operations
Operation | Description
----------|------------
`get` | Get a specific component or set of components from an entity.
`add` | Adds component to an entity. If entity already has the component, `add` does nothing.
`set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get`
`remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing.
`clear` | Remove all components from an entity. Clearing is more efficient than removing one by one.
### Components are entities
In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component. An example:
::: code-group
```luau [luau]
local Position = world:component() :: jecs.Entity<Vector3>
print(world:has(Position, Jecs.Component))
```
```typescript [typescript]
const Position = world.component<Vector3>();
print(world.has(Position, Jecs.Component))
```
:::
All of the APIs that apply to regular entities also apply to component entities. This means it is possible to contexualize components with logic by adding traits to components
::: code-group
```luau [luau]
local Networked = world:component()
local Type = world:component()
local Name = world:component()
local Position = world:component() :: jecs.Entity<Vector3>
world:add(Position, Networked)
world:set(Position, Name, "Position")
world:set(Position, Type, { size = 12, type = "Vector3" } ) -- 12 bytes to represent a Vector3
for id, ty, name in world:query(Type, Name):with(Networked) do
local batch = {}
for entity, data in world:query(id) do
table.insert(batch, { entity = entity, data = data })
end
-- entities are sized f64
local packet = buffer.create(#batch * (8 + ty.size))
local offset = 0
for _, entityData in batch do
offset+=8
buffer.writef64(packet, offset, entityData.entity)
if ty.type == "Vector3" then
local vec3 = entity.data :: Vector3
offset += 4
buffer.writei32(packet, offset, vec3.X)
offset += 4
buffer.writei32(packet, offset, vec3.Y)
offset += 4
buffer.writei32(packet, offset, vec3.Z)
end
end
updatePositions:FireServer(packet)
end
```
```typescript [typescript]
const Networked = world.component()
const Type = world.component()
const Name = world.component()
const Position = world.component<Vector3>();
world.add(Position, Networked)
world.set(Position, Name, "Position")
world.set(Position, Type, { size: 12, type: "Vector3" } ) // 12 bytes to represent a Vector3
for (const [id, ty, name] of world.query(Type, Name).with(Networked)) {
const batch = new Array<{ entity: Entity, data: unknown}>()
for (const [entity, data] of world.query(id)) {
batch.push({ entity, data })
}
// entities are sized f64
const packet = buffer.create(batch.size() * (8 + ty.size))
const offset = 0
for (const [_, entityData] of batch) {
offset+=8
buffer.writef64(packet, offset, entityData.entity)
if (ty.type == "Vector3") {
const vec3 = entity.data as Vector3
offset += 4
buffer.writei32(packet, offsetm, vec3.X)
offset += 4
buffer.writei32(packet, offset, vec3.Y)
offset += 4
buffer.writei32(packet, offset, vec3.Z)
}
}
updatePositions.FireServer(packet)
}
```
:::

View file

@ -1,106 +0,0 @@
# Queries
## Introductiuon
Queries enable games to quickly find entities that satifies provided conditions.
Jecs queries can do anything from returning entities that match a simple list of components, to matching against entity graphs.
This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are:
- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it.
- Queries support filters such as [`query:with(...)`](../../api/query.md#with) if entities are required to have the components but you dont actually care about components value. And [`query:without(...)`](../../api/query.md#without) which selects entities without the components.
- Queries can be drained or reset on when called, which lets you choose iterator behaviour.
- Queries can be called with any ID, including entities created dynamically, this is useful for pairs.
- Queries are already fast but can be futher inlined via [`query:archetypes()`](../../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 70-80% of the cost for iteration.
## Creating Queries
This section explains how to create queries in the different language bindings.
:::code-group
```luau [luau]
for _ in world:query(Position, Velocity) do end
```
```typescript [typescript]
for (const [_] of world.query(Position, Velocity)) {}
```
:::
### Components
A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example:
```luau
local e1 = world:entity()
world:add(e1, Position)
local e2 = world:entity()
world:add(e2, Position)
world:add(e2, Velocity)
local e3 = world:entity()
world:add(e3, Position)
world:add(e3, Velocity)
world:add(e3, Mass)
```
Only entities `e2` and `e3` match the query Position, Velocity.
### Wildcards
Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches.
When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result.
If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../../api/world.md#target)
Wildcards are particularly useful when used in combination with pairs (next section).
### Pairs
A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [Relationships](relationships.md).
The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity.
The following sections describe how to create queries for pairs in the different language bindings.
:::code-group
```luau [luau]
local Likes = world:entity()
local bob = world:entity()
for _ in world:query(pair(Likes, bob)) do end
```
```typescript [typescript]
const Likes = world.entity()
const bob = world.entity()
for (const [_] of world.query(pair(Likes, bob))) {}
```
:::
When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query:
:::code-group
```luau [luau]
for id in world:query(pair(Likes, jecs.Wildcard)) do
print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`)
end
```
```typescript [typescript]
const Likes = world.entity()
const bob = world.entity()
for (const [_] of world.query(pair(Likes, jecs.Wildcard))) {
print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`)
}
```
:::
### Filters
Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values.
The following filters are supported by queries:
Identifier | Description
---------- | -----------
With | Must match with all terms.
Without | Must not match with provided terms.
This page takes wording and terminology directly from Flecs [documentation](https://www.flecs.dev/flecs/md_docs_2Queries.html)

View file

@ -1,210 +0,0 @@
# Relationships
Relationships makes it possible to describe entity graphs natively in ECS.
Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples").
Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support.
## Definitions
Name | Description
----------|------------
Id | An id that can be added and removed
Component | Id with a single element (same as an entity id)
Relationship | Used to refer to first element of a pair
Target | Used to refer to second element of a pair
Source | Entity to which an id is added
## Relationship queries
There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time:
Test if entity has a relationship pair
:::code-group
```luau [luau]
world:has(bob, pair(Eats, Apples))
```
```typescript [typescript]
world.has(bob, pair(Eats, Apples))
```
:::
Test if entity has a relationship wildcard
:::code-group
```luau [luau]
world:has(bob, pair(Eats, jecs.Wildcard)
```
```typescript [typescript]
world.has(bob, pair(Eats, jecs.Wildcard)
```
:::
Get parent for entity
:::code-group
```luau [luau]
world:parent(bob)
```
```typescript [typescript]
world.parent(bob, pair(Eats, jecs.Wildcard)
```
:::
Find first target of a relationship for entity
:::code-group
```luau [luau]
world:target(bob, Eats)
```
```typescript [typescript]
world.target(bob, Eats)
```
:::
Find first target of a relationship for entity
:::code-group
```luau [luau]
world:target(bob, Eats)
```
```typescript [typescript]
world.target(bob, Eats)
```
:::
Find all entities with a pair
:::code-group
```luau [luau]
for id in world:query(pair(Eats, Apples)) do
-- ...
end
```
```typescript [typescript]
for (const [id] of world.query(pair(Eats, Apples)) {
// ...
}
```
:::
Find all entities with a pair wildcard
:::code-group
```luau [luau]
for id in world:query(pair(Eats, jecs.Wildcard)) do
local food = world:target(id, Eats) -- Apples, ...
end
```
```typescript [typescript]
for (const [id] of world.query(pair(Eats, jecs.Wildcard)) {
const food = world.target(id, Eats) // Apples, ...
}
```
:::
Iterate all children for a parent
:::code-group
```luau [luau]
for child in world:query(pair(jecs.ChildOf, parent)) do
-- ...
end
```
```typescript [typescript]
for (const [child] of world.query(pair(jecs.ChildOf, parent)) {
// ...
}
```
:::
Relationship components
Relationship pairs, just like regular component, can be associated with data.
:::code-group
```luau [luau]
local Position = world:component()
local Eats = world:component()
local Apples = world:entity()
local Begin = world:entity()
local End = world:entity()
local e = world:entity()
world:set(e, pair(Eats, Apples), { amount = 1 })
world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0))
world:set(e, pair(End, Position), Vector3.new(10, 20, 30))
world:add(e, jecs.ChildOf, Position)
```
```typescript [typescript]
const Position = world.component()
const Eats = world.component()
const Apples = world.entity()
const Begin = world.entity()
const End = world.entity()
const e = world.entity()
world.set(e, pair(Eats, Apples), { amount: 1 })
world.set(e, pair(Begin, Position), new Vector3(0, 0, 0))
world.set(e, pair(End, Position), new Vector3(10, 20, 30))
world.add(e, jecs.ChildOf, Position)
```
:::
## Relationship wildcards
When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions.
Wildcards may used for the relationship or target part of a pair
```luau
pair(Likes, jecs.Wildcard) -- Matches all Likes relationships
pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target
```
## Relationship performance
This section goes over the performance implications of using relationships.
### Introduction
The ECS storage needs to know two things in order to store components for entities:
- Which IDs are associated with an entity
- Which types are associated with those ids
Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component.
### Storing relationships
Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id.
Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair.
### Id ranges
Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. This low id range is used by the storage to more efficiently encode graph edges between archetypes. Graph edges for components with low ids use direct array indexing, whereas graph edges for high ids use a hashmap. Graph edges are used to find the next archetype when adding/removing component ids, and are a contributing factor to the performance overhead of add/remove operations.
Because of the way pair IDs are encoded, a pair will never be in the low id range. This means that adding/removing a pair ID always uses a hashmap to find the next archetype. This introduces a small overhead.
### Fragmentation
Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas:
- Archetype creation
- Queries (queries have to match & iterate more archetypes)
Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships.
Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships.
### Archetype Creation
When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities.
The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships.
### Indexing
To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs.
While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships.
This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html).

View file

@ -0,0 +1,17 @@
# Code Coverage Reports
All of the code coverage reports can be found here:
[Overview](/jecs/coverage/index.html){target="_self"}
[jecs.luau](/jecs/coverage/jecs.luau.html){target="_self"}
[ANSI](/jecs/coverage/ansi.luau.html){target="_self"}
[Entity Visualiser](/jecs/coverage/entity_visualiser.luau.html){target="_self"}
[Lifetime Tracker](/jecs/coverage/lifetime_tracker.luau.html){target="_self"}
[Testkit](/jecs/coverage/testkit.luau.html){target="_self"}
[Tests](/jecs/coverage/tests.luau.html){target="_self"}

View file

@ -0,0 +1,21 @@
# Contribution Guidelines
Whether you found an issue, or want to make a change to jecs, we'd love to hear back from the community on what features you want or bugs you've run into.
There's a few different ways you can go about this.
## Creating an Issue
This is what you should be filing if you have a bug you want to report.
[Click here](https://github.com/Ukendio/jecs/issues/new/choose) to file a bug report. We have a few templates ready for the most common issue types.
Additionally, see the [Submitting Issues](../contributing/issues) page for more information.
## Creating a Pull Request
This is what you should be filing if you have a change you want to merge into the main project.
[Click here](https://github.com/Ukendio/jecs/compare) to select the branch you want to merge from.
Additionally, see the [Submitting Pull Requests](../contributing/pull-requests) page for more information.

View file

@ -0,0 +1,24 @@
# Submitting Issues
When you're submitting an issue, generally they fall into a few categories:
## Bug
We need some information to figure out what's going wrong. At a minimum, you need to tell us:
(1) What's supposed to happen
(2) What actually happened
(3) Steps to reproduce
Stack traces and other useful information that you find make a bug report more likely to be fixed.
Consult the template for a bug report if you don't know or have questions about how to format this.
## Documentation
Depending on how you go about it, this can be done as a [Pull Request](../contributing/pull-requests) instead of an issue. Generally, we need to know what was wrong, what you changed, and how it improved the documentation if it isn't obvious.
We just need to know what's wrong. You should fill out a [PR](../contributing/pull-requests) if you know what should be there instead.

View file

@ -0,0 +1,77 @@
# Submitting Pull Requests
When submitting a Pull Request, there's a few reasons to do so:
## Documentation
If there's something to change with the documentation, you should follow a similar format to this example:
An example of an appropriate typo-fixing PR would be:
>**Brief Description of your Changes**
>
>I fixed a couple of typos found in the /contributing/issues.md file.
>
>**Impact of your Changes**
>
>- Documentation is more clear and readable for the users.
>
>**Tests Performed**
>
>Ran `vitepress dev docs` and verified it was built successfully.
>
>**Additional Comments**
>
>[At Discretion]
## Change in Behavior
An example of an appropriate PR that adds a new feature would be:
>
>**Brief Description of your Changes**
>
>I added `jecs.best_function`, which gives everyone who uses the module an immediate boost in concurrent player counts. (this is a joke)
>
>**Impact of your Changes**
>
>- jecs functionality is extended to better fit the needs of the community [explain why].
>
>**Tests Performed**
>
>Added a few test cases to ensure the function runs as expected [link to changes].
>
>**Additional Comments**
>
>[At Discretion]
## Addons
If you made something you think should be included into the [resources page](../../resources), let us know!
We have tons of examples of libraries and other tools which can be used in conjunction with jecs on this page.
One example of a PR that would be accepted is:
>**Brief Description of your Changes**
>
>I added `jecs observers` to the addons page.
>
>**Impact of your Changes**
>
>- jecs observers are a different and important way of handling queries which benefit the users of jecs by [explain why your tool benefits users here]
>
>- [talk about why you went with this design instead of maybe an alternative]
>
>**Tests Performed**
>
> I used this tool in conjunction with jecs and ensured it works as expected.
>
> [If you wrote unit tests for your tool, mention it here.]
>
>**Additional Comments**
>
>[At Discretion]
Keep in mind the list on the addons page is *not* exhaustive. If you came up with a tool that doesn't fit into any of the categories listed, we still want to hear from you!

View file

@ -1,3 +0,0 @@
## TODO
This is a TODO stub.

718
docs/learn/overview.md Executable file
View file

@ -0,0 +1,718 @@
# Introduction
Jecs is a standalone entity-component-system module written in Luau.
ECS ("entity-component-system") describes one way to write games in a more data oriented design.
## Installation
Jecs supports the following installation methods using package managers:
:::code-group
```bash [wally]
jecs = "ukendio/jecs@0.6.0" # Inside wally.toml
```
```bash [pesde]
pesde add wally#ukendio/jecs@0.6.0
```
```bash [npm]
npm i @rbxts/jecs
```
:::
Additionally an `rbxm` is published with [each release under the assets submenu](https://github.com/Ukendio/jecs/releases/latest).
## Hello World, Entity and Component
It all has to start somewhere. A world stores entities and their components, and manages them. This tour will reference it for every operation.
:::code-group
```luau [luau]
local jecs = require(path/to/jecs)
local world = jecs.world()
```
```typescript [typescript]
import * as jecs from "@rbxts/jecs"
const world = jecs.world()
// creates a new entity with no components and returns its identifier
const entity = world.entity()
// deletes an entity and all its components
world.delete(entity)
```
:::
## Entities
Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc.
By itself, an entity is just an unique entity identifier without any data. An entity identifier contains information about the entity itself and its generation.
:::code-group
```luau [luau]
-- creates a new entity with no components and returns its identifier
local entity = world:entity()
-- deletes an entity and all its components
world:delete(entity)
```
```typescript [typescript]
// creates a new entity with no components and returns its identifier
const entity = world.entity()
// deletes an entity and all its components
world.delete(entity)
```
:::
The `entity` member function also accepts an overload that allows you to create an entity with a desired id which bypasses the [`entity range`](#Entity-Ranges).
## Components
A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples").
## Operations
| Operation | Description |
| --------- | ---------------------------------------------------------------------------------------------- |
| `get` | Get a specific component or set of components from an entity. |
| `add` | Adds component to an entity. If entity already has the component, `add` does nothing. |
| `set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get` |
| `remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing. |
| `clear` | Remove all components from an entity. Clearing is more efficient than removing one by one. |
## Components are entities
In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. This means that everything is customizable. Components are no exception
and all of the APIs that apply to regular entities also apply to component entities.
If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component trait.
::: code-group
```luau [luau]
local Position = world:component() :: jecs.Entity<Vector3>
world:set(Position, jecs.Name, "Position") -- Using regular apis to set metadata on component entities!
print(`{world:get(Position, jecs.Name)} is a Component: {world:has(Position, jecs.Component)}`);
-- Output:
-- Position is a Component: true
```
```typescript [typescript]
const Position = world.component<Vector3>();
world.set(Position, jecs.Name, "Position") // Using regular apis to set metadata on component entities!
print(`${world.get(Position, jecs.Name)} is a Component: ${world.has(Position, jecs.Component)}`);
// Output:
// Position is a Component: true
```
:::
### Entity ranges
Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. That means that regular entities will start after this number. This number can be further specified via the `range` member function.
::: code-group
```luau [luau]
world:range(1000, 5000) -- Defines the lower and upper bounds of the entity range respectively
local e = world:entity()
print(e)
-- Output:
-- 1000
```
```typescript [typescript]
world.range(1000, 5000) // Defines the lower and upper bounds of the entity range respectively
const e = world.entity()
print(e)
// Output:
// 1000
```
:::
### Hooks
Component data generally need to adhere to a specific interface, and sometimes requires side effects to run upon certain lifetime cycles. In `jecs`, there are hooks which are `component traits`, that can define the behaviour of a component and enforce invariants, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnChange` hook per component, just like you can only have a single constructor and destructor.
::: code-group
```luau [luau]
local Transform = world:component()
world:set(Transform, OnAdd, function(entity, id, data)
-- A transform component `id` has been added with `data` to `entity`
end)
world:set(Transform, OnRemove, function(entity, id)
-- A transform component `id` has been removed from `entity`
end)
world:set(Transform, OnChange, function(entity, id, data)
-- A transform component `id` has been changed to `data` on `entity`
end)
```
```typescript [typescript]
const Transform = world.component();
world.set(Transform, OnAdd, (entity, id, data) => {
// A transform component `id` has been added with `data` to `entity`
});
world.set(Transform, OnRemove, (entity, id) => {
// A transform component `id` has been removed from `entity`
});
world.set(Transform, OnChange, (entity, id, data) => {
// A transform component `id` has been changed to `data` on `entity`
});
```
:::
:::info
Children are cleaned up before parents
When a parent and its children are deleted, OnRemove hooks will be invoked for children first, under the condition that there are no cycles in the relationship graph of the deleted entities. This order is maintained for any relationship that has the (OnDeleteTarget, Delete) trait (see Component Traits for more details).
When an entity graph contains cycles, order is undefined. This includes cycles that can be formed using different relationships.
:::
### Cleanup Traits
When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references.
We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same.
This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it.
To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed.
#### Cleanup Traits Summary
| Condition | Action | Description | Use Case |
|-----------|--------|-------------|----------|
| `OnDelete` | `Remove` | Removes the component from all entities when the component is deleted | Default behavior, safe cleanup |
| `OnDelete` | `Delete` | Deletes all entities that have the component when the component is deleted | Cascading deletion, dangerous |
| `OnDeleteTarget` | `Remove` | Removes the relationship from all entities when the target is deleted | Safe relationship cleanup |
| `OnDeleteTarget` | `Delete` | Deletes all entities that have the relationship when the target is deleted | Hierarchical deletion (e.g., parent-child) |
**Cleanup Actions:**
- `Remove`: removes instances of the specified (component) id from all entities (default)
- `Delete`: deletes all entities with specified id
**Cleanup Conditions:**
- `OnDelete`: the component, tag or relationship is deleted
- `OnDeleteTarget`: a target used with the relationship is deleted
#### (OnDelete, Remove)
::: code-group
```luau [luau]
local Archer = world:component()
world:add(Archer, pair(jecs.OnDelete, jecs.Remove))
local e = world:entity()
world:add(e, Archer)
-- This will remove Archer from e
world:delete(Archer)
```
```typescript [typescript]
const Archer = world.component();
world.add(Archer, pair(jecs.OnDelete, jecs.Remove));
const e = world.entity();
world.add(e, Archer);
// This will remove Archer from e
world.delete(Archer);
```
:::
#### (OnDelete, Delete)
::: code-group
```luau [luau]
local Archer = world:component()
world:add(Archer, pair(jecs.OnDelete, jecs.Delete))
local e = world:entity()
world:add(e, Archer)
-- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
world:delete(Archer)
```
```typescript [typescript]
const Archer = world.component();
world.add(Archer, pair(jecs.OnDelete, jecs.Delete));
const e = world.entity();
world.add(e, Archer);
// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait
world.delete(Archer);
```
:::
#### (OnDeleteTarget, Remove)
::: code-group
```luau [luau]
local OwnedBy = world:component()
world:add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove))
local loot = world:entity()
local player = world:entity()
world:add(loot, pair(OwnedBy, player))
-- This will remove (OwnedBy, player) from loot
world:delete(player)
```
```typescript [typescript]
const OwnedBy = world.component();
world.add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove));
const loot = world.entity();
const player = world.entity();
world.add(loot, pair(OwnedBy, player));
// This will remove (OwnedBy, player) from loot
world.delete(player);
```
:::
#### (OnDeleteTarget, Delete)
::: code-group
```luau [luau]
local ChildOf = world:component()
world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete))
local parent = world:entity()
local child = world:entity()
world:add(child, pair(ChildOf, parent))
-- This will delete both parent and child
world:delete(parent)
```
```typescript [typescript]
const ChildOf = world.component();
world.add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete));
const parent = world.entity();
const child = world.entity();
world.add(child, pair(ChildOf, parent));
// This will delete both parent and child
world.delete(parent);
```
:::
## Preregistration
By default, components being registered on runtime is useful for how dynamic it can be. But, sometimes being able to register components without having the world instance is useful.
::: code-group
```luau [luau]
local Position = jecs.component() :: jecs.Entity<Vector3>
jecs.world() -- Position gets registered here
```
```typescript [typescript]
import { world } from "@rbxts/jecs"
const Position = jecs.component<Vector3>();
world() // Position gets registered here
```
:::
However, if you try to set metadata, you will find that this doesn't work without the world instance. Instead, jecs offers a `meta` member function that can forward declare its metadata.
::: code-group
```luau [luau]
jecs.meta(Position, jecs.Name, "Position")
jecs.world() -- Position gets registered here with its name "Position"
```
```typescript [typescript]
import { world } from "@rbxts/jecs"
jecs.meta(Position, jecs.Name, "Position")
world() // Position gets registered here with its name "Position"
```
:::
### Singletons
Singletons are components for which only a single instance
exists on the world. They can be accessed on the
world directly and do not require providing an entity.
Singletons are useful for global game resources, such as
game state, a handle to a physics engine or a network socket. An example:
::: code-group
```luau [luau]
local TimeOfDay = world:component() :: jecs.Entity<number>
world:set(TimeOfDay, TimeOfDay, 0.5)
local t = world:get(TimeOfDay, TimeOfDay)
```
```typescript [typescript]
const TimeOfDay = world.component<number>();
world.set(TimeOfDay, TimeOfDay, 0.5);
const t = world.get(TimeOfDay, TimeOfDay);
```
:::
# Queries
Queries enable games to quickly find entities that satifies provided conditions.
:::code-group
```luau [luau]
for _ in world:query(Position, Velocity) do end
```
```typescript [typescript]
for (const [_] of world.query(Position, Velocity)) {
}
```
:::
In `jecs`, queries can do anything from returning entities that match a simple list of components, to matching against entity graphs.
This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are:
- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it.
- Queries support filters such as [`query:with(...)`](../api/query.md#with) if entities are required to have the components but you dont actually care about components value. And [`query:without(...)`](../api/query.md#without) which selects entities without the components.
- Queries can be drained or reset on when called, which lets you choose iterator behaviour.
- Queries can be called with any ID, including entities created dynamically, this is useful for pairs.
- Queries are already fast but can be futher inlined via [`query:archetypes()`](../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 60-80% of the cost for iteration.
## Performance and Caching
Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games.
The biggest impact on query performance is whether a query is cached or not.
This section goes over what caching is, how it can be used and when it makes sense to use it.
### Caching: what is it?
Jecs is an archetype ECS, which means that entities with exactly the same components are
grouped together in an "archetype". Archetypes are created on the fly
whenever a new component combination is created in the ECS. For example:
:::code-group
```luau [luau]
local e1 = world:entity()
world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position]
world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity]
local e2 = world:entity()
world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists
world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists
world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass]
-- e1 is now in archetype [Position, Velocity]
-- e2 is now in archetype [Position, Velocity, Mass]
```
```typescript [typescript]
const e1 = world.entity();
world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position]
world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity]
const e2 = world.entity();
world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists
world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists
world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass]
// e1 is now in archetype [Position, Velocity]
// e2 is now in archetype [Position, Velocity, Mass]
```
:::
Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast.
The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded.
This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable.
If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast.
### Tradeoffs
Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons:
- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first.
- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches.
- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached).
As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense.
Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent.
### Components
A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example:
```luau
local e1 = world:entity()
world:add(e1, Position)
local e2 = world:entity()
world:add(e2, Position)
world:add(e2, Velocity)
local e3 = world:entity()
world:add(e3, Position)
world:add(e3, Velocity)
world:add(e3, Mass)
```
Only entities `e2` and `e3` match the query Position, Velocity.
### Wildcards
Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches.
When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result.
If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../api/world.md#target)
Wildcards are particularly useful when used in combination with pairs (next section).
### Pairs
A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [`Relationships`](#relationships).
The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity.
The following sections describe how to create queries for pairs in the different language bindings.
:::code-group
```luau [luau]
local Likes = world:entity()
local bob = world:entity()
for _ in world:query(pair(Likes, bob)) do end
```
```typescript [typescript]
const Likes = world.entity();
const bob = world.entity();
for (const [_] of world.query(pair(Likes, bob))) {
}
```
:::
When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query:
:::code-group
```luau [luau]
for id in world:query(pair(Likes, jecs.Wildcard)) do
print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`)
end
```
```typescript [typescript]
const Likes = world.entity();
const bob = world.entity();
for (const [_] of world.query(pair(Likes, jecs.Wildcard))) {
print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`);
}
```
:::
### Filters
Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values.
The following filters are supported by queries:
| Identifier | Description |
| ---------- | ----------------------------------- |
| With | Must match with all terms. |
| Without | Must not match with provided terms. |
## Relationships
Relationships makes it possible to describe entity graphs natively in ECS.
Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples").
Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support.
### Definitions
Name | Description
----------|------------
Id | An id that can be added and removed
Component | Id with a single element (same as an entity id)
Relationship | Used to refer to first element of a pair
Target | Used to refer to second element of a pair
Source | Entity to which an id is added
### Relationship queries
There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time:
Test if entity has a relationship pair
:::code-group
```luau [luau]
world:has(bob, pair(Eats, Apples))
```
```typescript [typescript]
world.has(bob, pair(Eats, Apples))
```
:::
Test if entity has a relationship wildcard
:::code-group
```luau [luau]
world:has(bob, pair(Eats, jecs.Wildcard))
```
```typescript [typescript]
world.has(bob, pair(Eats, jecs.Wildcard))
```
:::
Get parent for entity
:::code-group
```luau [luau]
world:parent(bob)
```
```typescript [typescript]
world.parent(bob)
```
:::
Find first target of a relationship for entity
:::code-group
```luau [luau]
world:target(bob, Eats)
```
```typescript [typescript]
world.target(bob, Eats)
```
:::
Find all entities with a pair
:::code-group
```luau [luau]
for id in world:query(pair(Eats, Apples)) do
-- ...
end
```
```typescript [typescript]
for (const [id] of world.query(pair(Eats, Apples))) {
// ...
}
```
:::
Find all entities with a pair wildcard
:::code-group
```luau [luau]
for id in world:query(pair(Eats, jecs.Wildcard)) do
local food = world:target(id, Eats) -- Apples, ...
end
```
```typescript [typescript]
for (const [id] of world.query(pair(Eats, jecs.Wildcard))) {
const food = world.target(id, Eats) // Apples, ...
}
```
:::
Iterate all children for a parent
:::code-group
```luau [luau]
for child in world:query(pair(jecs.ChildOf, parent)) do
-- ...
end
```
```typescript [typescript]
for (const [child] of world.query(pair(jecs.ChildOf, parent))) {
// ...
}
```
:::
### Relationship components
Relationship pairs, just like regular component, can be associated with data.
:::code-group
```luau [luau]
local Position = world:component()
local Eats = world:component()
local Apples = world:entity()
local Begin = world:entity()
local End = world:entity()
local e = world:entity()
world:set(e, pair(Eats, Apples), { amount = 1 })
world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0))
world:set(e, pair(End, Position), Vector3.new(10, 20, 30))
world:add(e, pair(jecs.ChildOf, Position))
```
```typescript [typescript]
const Position = world.component()
const Eats = world.component()
const Apples = world.entity()
const Begin = world.entity()
const End = world.entity()
const e = world.entity()
world.set(e, pair(Eats, Apples), { amount: 1 })
world.set(e, pair(Begin, Position), new Vector3(0, 0, 0))
world.set(e, pair(End, Position), new Vector3(10, 20, 30))
world.add(e, pair(jecs.ChildOf, Position))
```
:::
### Relationship wildcards
When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions.
Wildcards may used for the relationship or target part of a pair
```luau
pair(Likes, jecs.Wildcard) -- Matches all Likes relationships
pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target
```
### Relationship performance
The ECS storage needs to know two things in order to store components for entities:
- Which IDs are associated with an entity
- Which types are associated with those ids
Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component.
### Storing relationships
Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id.
Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair.
### Fragmentation
Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas:
- Archetype creation
- Queries (queries have to match & iterate more archetypes)
Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships.
Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships.
### Archetype Creation
When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities.
The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships.
### Indexing
To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs.
While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships.
This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html).
## Next Steps
- [API Reference](../api/jecs.md) - Complete API documentation

View file

@ -1,71 +0,0 @@
# First Jecs project
Now that you have installed Jecs, you can create your [World](https://ukendio.github.io/jecs/api/world.html).
:::code-group
```luau [luau]
local jecs = require(path/to/jecs)
local world = jecs.World.new()
```
```typescript [typescript]
import { World } from "@rbxts/jecs"
const world = new World()
```
:::
Let's create a couple components.
:::code-group
```luau [luau]
local jecs = require(path/to/jecs)
local world = jecs.World.new()
local Position = world:component()
local Velocity = world:component()
```
```typescript [typescript]
import { World } from "@rbxts/jecs"
const world = new World()
const Position = world.component()
const Velocity = world.component()
```
:::
Systems can be as simple as a query in a function or a more contextualized construct. Let's make a system that moves an entity and decelerates over time.
:::code-group
```luau [luau]
local jecs = require(path/to/jecs)
local world = jecs.World.new()
local Position = world:component()
local Velocity = world:component()
for id, position, velocity in world:query(Position, Velocity) do
world:set(id, Position, position + velocity)
world:set(id, Velocity, velocity * 0.9)
end
```
```typescript [typescript]
import { World } from "@rbxts/jecs"
const world = new World()
const Position = world.component()
const Velocity = world.component()
for (const [id, position, velocity] of world.query(Position, Velocity)) {
world.set(id, Position, position.add(velocity))
world.set(id, Velocity, velocity.mul(0.9))
}
```
:::
## Where To Get Help
If you are encountering problems, there are resources for you to get help:
- [Roblox OSS Discord server](https://discord.gg/h2NV8PqhAD) has a [#jecs](https://discord.com/channels/385151591524597761/1248734074940559511) thread under the [#projects](https://discord.com/channels/385151591524597761/1019724676265676930) channel
- [Open an issue](https://github.com/ukendio/jecs/issues) if you run into bugs or have feature requests
- Dive into the nitty gritty in the [thesis paper](https://raw.githubusercontent.com/Ukendio/jecs/main/thesis/drafts/1/paper.pdf)

View file

@ -1,130 +0,0 @@
# Getting Started
## Installation
### Installing Standalone
Navigate to the [releases page](https://github.com/Ukendio/jecs/releases) and download `jecs.rbxm` from the assets.
![jecs.rbxm](rbxm.png)
### Using Wally
Add the following to your wally configuration:
::: code-group
```toml [wally.toml]
jecs = "ukendio/jecs@0.2.3"
```
:::
### Using npm (roblox-ts)
Use one of the following commands on your root project directory:
::: code-group
```bash [npm]
npm i https://github.com/Ukendio/jecs.git
```
```bash [yarn]
yarn add https://github.com/Ukendio/jecs.git
```
```bash [pnpm]
pnpm add https://github.com/Ukendio/jecs.git
```
:::
## Example Usage
::: code-group
```luau [Luau]
local world = jecs.World.new()
local pair = jecs.pair
local Wildcard = jecs.Wildcard
local Name = world:component()
local function getName(e)
return world:get(e, Name)
end
local Eats = world:component()
-- Relationship objects
local Apples = world:component()
-- components are entities, so you can add components to components
world:set(Apples, Name, "apples")
local Oranges = world:component()
world:set(Oranges, Name, "oranges")
local bob = world:entity()
-- Pairs can be constructed from two entities
world:set(bob, pair(Eats, Apples), 10)
world:set(bob, pair(Eats, Oranges), 5)
world:set(bob, Name, "bob")
local alice = world:entity()
world:set(alice, pair(Eats, Apples), 4)
world:set(alice, Name, "alice")
for id, amount in world:query(pair(Eats, Wildcard)) do
-- get the second target of the pair
local food = world:target(id, Eats)
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
end
-- Output:
-- bob eats 10 apples
-- bob eats 5 pears
-- alice eats 4 apples
```
```ts [Typescript]
import { Wildcard, pair, World } from "@rbxts/jecs"
const world = new World()
const Name = world.component()
function getName(e) {
return world.get(e, Name)
}
const Eats = world.component()
// Relationship objects
const Apples = world.component()
// components are entities, so you can add components to components
world.set(Apples, Name, "apples")
const Oranges = world.component()
world.set(Oranges, Name, "oranges")
const bob = world.entity()
// Pairs can be constructed from two entities
world.set(bob, pair(Eats, Apples), 10)
world.set(bob, pair(Eats, Oranges), 5)
world.set(bob, Name, "bob")
const alice = world.entity()
world.set(alice, pair(Eats, Apples), 4)
world.set(alice, Name, "alice")
for (const [id, amount] of world.query(pair(Eats, Wildcard))) {
// get the second target of the pair
const food = world:target(id, Eats)
print(string.format("%s eats %d %s", getName(id), amount, getName(food)))
}
// Output:
// bob eats 10 apples
// bob eats 5 pears
// alice eats 4 apples
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

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