@dcl-regenesislabs/sdk 0.0.0-stage → 7.0.0-42707159203.commit-ff138cd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +119 -2
  3. package/composite-provider.d.ts +2 -0
  4. package/composite-provider.js +67 -0
  5. package/ecs.d.ts +16 -0
  6. package/ecs.js +17 -0
  7. package/ethereum-provider/index.d.ts +24 -0
  8. package/ethereum-provider/index.js +27 -0
  9. package/ethereum-provider/text-encoder.d.ts +1 -0
  10. package/ethereum-provider/text-encoder.js +5 -0
  11. package/explorer-ui/index.d.ts +118 -0
  12. package/explorer-ui/index.js +235 -0
  13. package/index.d.ts +1 -0
  14. package/index.js +45 -0
  15. package/internal/Observable.d.ts +192 -0
  16. package/internal/Observable.js +324 -0
  17. package/internal/language-events.d.ts +1 -0
  18. package/internal/language-events.js +8 -0
  19. package/internal/provider.d.ts +22 -0
  20. package/internal/provider.js +29 -0
  21. package/internal/transports/logger.d.ts +2 -0
  22. package/internal/transports/logger.js +38 -0
  23. package/internal/transports/rendererTransport.d.ts +7 -0
  24. package/internal/transports/rendererTransport.js +40 -0
  25. package/internal/utf8.d.ts +15 -0
  26. package/internal/utf8.js +172 -0
  27. package/math.d.ts +16 -0
  28. package/math.js +17 -0
  29. package/message-bus.d.ts +14 -0
  30. package/message-bus.js +49 -0
  31. package/network/binary-message-bus.d.ts +18 -0
  32. package/network/binary-message-bus.js +68 -0
  33. package/network/entities.d.ts +11 -0
  34. package/network/entities.js +121 -0
  35. package/network/filter.d.ts +2 -0
  36. package/network/filter.js +43 -0
  37. package/network/index.d.ts +2 -0
  38. package/network/index.js +8 -0
  39. package/network/message-bus-sync.d.ts +18 -0
  40. package/network/message-bus-sync.js +174 -0
  41. package/network/state.d.ts +7 -0
  42. package/network/state.js +84 -0
  43. package/network/utils.d.ts +4 -0
  44. package/network/utils.js +16 -0
  45. package/observables.d.ts +179 -0
  46. package/observables.js +259 -0
  47. package/package.json +35 -3
  48. package/platform/index.d.ts +21 -0
  49. package/platform/index.js +70 -0
  50. package/players/index.d.ts +34 -0
  51. package/players/index.js +81 -0
  52. package/react-ecs.d.ts +21 -0
  53. package/react-ecs.js +27 -0
  54. package/src/composite-provider.ts +67 -0
  55. package/src/ecs.ts +17 -0
  56. package/src/ethereum-provider/index.ts +30 -0
  57. package/src/ethereum-provider/text-encoder.ts +4 -0
  58. package/src/explorer-ui/index.ts +398 -0
  59. package/src/index.ts +49 -0
  60. package/src/internal/Observable.ts +394 -0
  61. package/src/internal/language-events.ts +8 -0
  62. package/src/internal/provider.ts +51 -0
  63. package/src/internal/transports/logger.ts +45 -0
  64. package/src/internal/transports/rendererTransport.ts +48 -0
  65. package/src/internal/utf8.ts +167 -0
  66. package/src/math.ts +17 -0
  67. package/src/message-bus.ts +56 -0
  68. package/src/network/README.md +122 -0
  69. package/src/network/binary-message-bus.ts +74 -0
  70. package/src/network/entities.ts +149 -0
  71. package/src/network/filter.ts +63 -0
  72. package/src/network/index.ts +10 -0
  73. package/src/network/message-bus-sync.ts +208 -0
  74. package/src/network/state.ts +136 -0
  75. package/src/network/utils.ts +22 -0
  76. package/src/observables.ts +386 -0
  77. package/src/platform/index.ts +82 -0
  78. package/src/players/index.ts +110 -0
  79. package/src/react-ecs.ts +29 -0
  80. package/src/testing/assert.ts +134 -0
  81. package/src/testing/index.ts +42 -0
  82. package/src/testing/runtime.ts +223 -0
  83. package/src/testing/types.ts +21 -0
  84. package/src/text-codec.ts +70 -0
  85. package/testing/assert.d.ts +11 -0
  86. package/testing/assert.js +126 -0
  87. package/testing/index.d.ts +7 -0
  88. package/testing/index.js +36 -0
  89. package/testing/runtime.d.ts +8 -0
  90. package/testing/runtime.js +197 -0
  91. package/testing/types.d.ts +18 -0
  92. package/testing/types.js +2 -0
  93. package/text-codec.d.ts +28 -0
  94. package/text-codec.js +65 -0
  95. package/tsconfig.json +12 -0
  96. package/types/tsconfig.ecs7.json +31 -0
  97. package/types/tsconfig.ecs7.strict.json +4 -0
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Self-contained UTF-8 codec implementing the WHATWG Encoding Standard
3
+ * algorithms (https://encoding.spec.whatwg.org/), so SDK code never depends
4
+ * on the host providing `TextEncoder` / `TextDecoder` globals.
5
+ */
6
+
7
+ const REPLACEMENT_CHARACTER = 0xfffd
8
+
9
+ export type DecodeUtf8Options = {
10
+ fatal?: boolean
11
+ ignoreBOM?: boolean
12
+ }
13
+
14
+ export function decodeUtf8(input: Uint8Array, options: DecodeUtf8Options = {}): string {
15
+ const fatal = options.fatal === true
16
+ const start =
17
+ !options.ignoreBOM && input.length >= 3 && input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf ? 3 : 0
18
+
19
+ let result = ''
20
+ let pending: number[] = []
21
+ let codePoint = 0
22
+ let bytesNeeded = 0
23
+ let bytesSeen = 0
24
+ let lowerBoundary = 0x80
25
+ let upperBoundary = 0xbf
26
+
27
+ function emit(value: number) {
28
+ if (value <= 0xffff) {
29
+ pending.push(value)
30
+ } else {
31
+ const offset = value - 0x10000
32
+ pending.push(0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff))
33
+ }
34
+ if (pending.length >= 4096) {
35
+ result += String.fromCharCode(...pending)
36
+ pending = []
37
+ }
38
+ }
39
+
40
+ function malformed() {
41
+ if (fatal) throw new TypeError('decodeUtf8: the encoded data is not valid utf-8')
42
+ emit(REPLACEMENT_CHARACTER)
43
+ }
44
+
45
+ for (let i = start; i < input.length; i++) {
46
+ const byte = input[i]
47
+ if (bytesNeeded === 0) {
48
+ if (byte <= 0x7f) {
49
+ emit(byte)
50
+ } else if (byte >= 0xc2 && byte <= 0xdf) {
51
+ bytesNeeded = 1
52
+ codePoint = byte & 0x1f
53
+ } else if (byte >= 0xe0 && byte <= 0xef) {
54
+ if (byte === 0xe0) lowerBoundary = 0xa0
55
+ if (byte === 0xed) upperBoundary = 0x9f
56
+ bytesNeeded = 2
57
+ codePoint = byte & 0xf
58
+ } else if (byte >= 0xf0 && byte <= 0xf4) {
59
+ if (byte === 0xf0) lowerBoundary = 0x90
60
+ if (byte === 0xf4) upperBoundary = 0x8f
61
+ bytesNeeded = 3
62
+ codePoint = byte & 0x7
63
+ } else {
64
+ malformed()
65
+ }
66
+ } else if (byte < lowerBoundary || byte > upperBoundary) {
67
+ codePoint = 0
68
+ bytesNeeded = 0
69
+ bytesSeen = 0
70
+ lowerBoundary = 0x80
71
+ upperBoundary = 0xbf
72
+ malformed()
73
+ // the spec prepends the byte back to the stream: it starts a new sequence
74
+ i--
75
+ } else {
76
+ lowerBoundary = 0x80
77
+ upperBoundary = 0xbf
78
+ codePoint = (codePoint << 6) | (byte & 0x3f)
79
+ if (++bytesSeen === bytesNeeded) {
80
+ emit(codePoint)
81
+ codePoint = 0
82
+ bytesNeeded = 0
83
+ bytesSeen = 0
84
+ }
85
+ }
86
+ }
87
+ if (bytesNeeded !== 0) malformed()
88
+
89
+ if (pending.length > 0) result += String.fromCharCode(...pending)
90
+ return result
91
+ }
92
+
93
+ export function encodeUtf8(input: string): Uint8Array {
94
+ const output = new Uint8Array(utf8ByteLength(input))
95
+ let offset = 0
96
+ for (let i = 0; i < input.length; i++) {
97
+ const codePoint = codePointAt(input, i)
98
+ if (codePoint > 0xffff) i++
99
+ offset = writeCodePoint(output, offset, codePoint)
100
+ }
101
+ return output
102
+ }
103
+
104
+ export function encodeUtf8Into(source: string, destination: Uint8Array): { read: number; written: number } {
105
+ let read = 0
106
+ let written = 0
107
+ for (let i = 0; i < source.length; i++) {
108
+ const codePoint = codePointAt(source, i)
109
+ const size = byteSize(codePoint)
110
+ if (written + size > destination.length) break
111
+ written = writeCodePoint(destination, written, codePoint)
112
+ if (codePoint > 0xffff) {
113
+ i++
114
+ read += 2
115
+ } else {
116
+ read += 1
117
+ }
118
+ }
119
+ return { read, written }
120
+ }
121
+
122
+ // Reads the code point at index, replacing unpaired surrogates with U+FFFD
123
+ // (the USVString conversion `TextEncoder` mandates).
124
+ function codePointAt(input: string, index: number): number {
125
+ const first = input.charCodeAt(index)
126
+ if (first >= 0xd800 && first <= 0xdbff) {
127
+ const second = index + 1 < input.length ? input.charCodeAt(index + 1) : 0
128
+ if (second >= 0xdc00 && second <= 0xdfff) return 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00)
129
+ return REPLACEMENT_CHARACTER
130
+ }
131
+ if (first >= 0xdc00 && first <= 0xdfff) return REPLACEMENT_CHARACTER
132
+ return first
133
+ }
134
+
135
+ function byteSize(codePoint: number): number {
136
+ return codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4
137
+ }
138
+
139
+ function utf8ByteLength(input: string): number {
140
+ let length = 0
141
+ for (let i = 0; i < input.length; i++) {
142
+ const codePoint = codePointAt(input, i)
143
+ if (codePoint > 0xffff) i++
144
+ length += byteSize(codePoint)
145
+ }
146
+ return length
147
+ }
148
+
149
+ function writeCodePoint(output: Uint8Array, offset: number, codePoint: number): number {
150
+ let next = offset
151
+ if (codePoint <= 0x7f) {
152
+ output[next++] = codePoint
153
+ } else if (codePoint <= 0x7ff) {
154
+ output[next++] = 0xc0 | (codePoint >> 6)
155
+ output[next++] = 0x80 | (codePoint & 0x3f)
156
+ } else if (codePoint <= 0xffff) {
157
+ output[next++] = 0xe0 | (codePoint >> 12)
158
+ output[next++] = 0x80 | ((codePoint >> 6) & 0x3f)
159
+ output[next++] = 0x80 | (codePoint & 0x3f)
160
+ } else {
161
+ output[next++] = 0xf0 | (codePoint >> 18)
162
+ output[next++] = 0x80 | ((codePoint >> 12) & 0x3f)
163
+ output[next++] = 0x80 | ((codePoint >> 6) & 0x3f)
164
+ output[next++] = 0x80 | (codePoint & 0x3f)
165
+ }
166
+ return next
167
+ }
package/src/math.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This module is exposed by the sdk via `@dcl/sdk/math`
3
+ *
4
+
5
+ * @example
6
+ * ```tsx
7
+ * import { Color3, Vector3 } from '@dcl/sdk/math'
8
+ * ```
9
+ *
10
+ * @module Math & Colors
11
+ *
12
+ */
13
+
14
+ export * from '@dcl/ecs-math'
15
+ export * from '@dcl/ecs-math/dist/Matrix'
16
+ export * from '@dcl/ecs-math/dist/Plane'
17
+ export { Vector3 } from '@dcl/ecs-math'
@@ -0,0 +1,56 @@
1
+ import { Observer } from './internal/Observable'
2
+ import { IEvents, onCommsMessage } from './observables'
3
+ import * as communicationsController from '~system/CommunicationsController'
4
+
5
+ /**
6
+ * @alpha
7
+ * @deprecated this will only exist for a few releases in ECS7
8
+ */
9
+ export class MessageBus {
10
+ private messageQueue: string[] = []
11
+ private flushing = false
12
+
13
+ constructor() {}
14
+
15
+ on(message: string, callback: (value: any, sender: string) => void): Observer<IEvents['comms']> {
16
+ return onCommsMessage.add((e) => {
17
+ try {
18
+ const m = JSON.parse(e.message)
19
+
20
+ if (m.message === message) {
21
+ callback(m.payload, e.sender)
22
+ }
23
+ } catch (_) {}
24
+ })!
25
+ }
26
+
27
+ // @internal
28
+ sendRaw(message: string) {
29
+ this.messageQueue.push(message)
30
+
31
+ this.flush()
32
+ }
33
+ emit(message: string, payload: Record<any, any>) {
34
+ const messageToSend = JSON.stringify({ message, payload })
35
+ this.sendRaw(messageToSend)
36
+ onCommsMessage.notifyObservers({ message: messageToSend, sender: 'self' })
37
+ }
38
+
39
+ private flush() {
40
+ if (!this.messageQueue.length) return
41
+ if (this.flushing) return
42
+
43
+ const message = this.messageQueue.shift()!
44
+ this.flushing = true
45
+ communicationsController.send({ message }).then(
46
+ (_) => {
47
+ this.flushing = false
48
+ this.flush()
49
+ },
50
+ (_) => {
51
+ this.flushing = false
52
+ this.flush()
53
+ }
54
+ )
55
+ }
56
+ }
@@ -0,0 +1,122 @@
1
+ ## Mapping syncronized Entities
2
+ How this works ?
3
+ We create a new component created NetworkEntity.
4
+ This network component consists in the id of the entity that was created in that client, and the networkId is the user address converted to a number. So its kind of the unique user id in a int64 format.
5
+
6
+ type NetwokEntity = { entityId: Entity; networkId: number }
7
+
8
+ We also introduce a new kind of messages that are going to be sent through the wire, and that the SDK knows how to read.
9
+ PutNetworkComponent message.
10
+ This message is the same as the PUT_COMPONENT BUT! with the difference that we are sending always the NetworkEntity mapping.
11
+ So this message will not have the local entityId, it will always send the NetworkEntity component associated to the entity.
12
+ PUT_NETWORK_MESSAGE = { networkId: networkEntity.networkId, entityId: networkEntity.entityId, data: Uint8Array }
13
+ So this way, every client has the internal mapping.
14
+ Once you receive a network message, you iterate the NetworkEntity component to find the one that has the same entityId and networkId. The entity with that component is the entity that the network is talking about.
15
+ When you change a component of that entity, we do the same. We look for the networkEntity and create a PutNetwork message with the NetworkEntity values.
16
+
17
+ ## Syncronize Entities that are created in every client (Main Function)
18
+
19
+ enum Entities {
20
+ HOUSE = 1,
21
+ DOOR = 2
22
+ }
23
+ Same entity for all clients.
24
+
25
+ This is usefull when you have static entities that are created on every client, and you want to syncronize something about them.
26
+ For example a door of a house. You want every client to create the same door.
27
+ We use the Entities enum to tag the entity with an unique identifier, so every client knows which entity you are modifying, no matter the order they are created
28
+ This is used for code that is being executed on every client, and you want to sync some component about it. If you dont tag them, you can't be sure that both clients are talking about the same entity.
29
+ Maybe for client A the door is the entity 512, but for client B its 513, and you will have some missmatch there.
30
+ i.e.
31
+ const houseEntity = engine.addEntity()
32
+ syncEntity(houseEntity, [Transform.componentId], Entities.HOUSE)
33
+
34
+ If we dont use the SyncStaticEntities for static models like the house. Then each client will create a new House, and that House will be replicated on every client. So if you have 10 clients, you will have 10 houses being syncronized.
35
+ That's why we use the SyncStaticEntities identifier for things that you want to be created only once, and can syncronized if some component changed.
36
+
37
+
38
+ ## Syncronize RUNTIME/DYNAMIC entities
39
+ This are entities that are created on a client after some interaction, and you want to replicate them on all the other clients.
40
+ The client that runs this code will create an UNIQUE entity and will be sent to the others.
41
+
42
+ For example bullets of a gun. Every client will have their own bullets, and every time they shot the gun a new entity (bullet) will be created and replicated on every client.
43
+ Another example could be the spawn cubes. Every client that spawns a cube, will spawn an unique cube, and will be replicated on the others.
44
+ All this examples have the same pattern, code that is being executed in only one client, and need to be syncronize on the other ones.
45
+
46
+ function onShoot() {
47
+ const bullet = engine.addEntity()
48
+ Transform.create(bullet, {})
49
+ Material.create(bullet, {})
50
+ syncEntity(bullet, [Transform.componentId, Material.componentId])
51
+ }
52
+
53
+ ## Syncronizing Transform Issue
54
+ Let me tell you a sad story about syncronizing Transforms with different entities ids in each client
55
+ Scene wants to sync a door. (SyncEntities.Door & SyncEntities.ParentDoor).
56
+ We have clients A & B, and both creates the door in the main function.
57
+ Both clients knows that are the same door because we use the SyncEntities enum to map this entity.
58
+
59
+ A creates sync entity 512 (parent)
60
+ const parent = engine.addEntity() // 512
61
+ syncEntity(parent, [Transform.componentId], SyncEntities.ParentDoor)
62
+ A creates sync entity 513 (child)
63
+ const child = engine.addEntity() // 513
64
+ Transform.create({ parent, position: {} })
65
+ syncEntity(child, [Transform.componentId], SyncEntities.ChildDoor)
66
+
67
+
68
+ Client B does the same but the entities, we dont know why, result in diff order. (Maybe a race condition)
69
+ B creates sync entity 513 (parent)
70
+ const parent = engine.addEntity() // 513
71
+ syncEntity(parent, [Transform.componentId], SyncEntities.ParentDoor)
72
+ B creates sync entity 514 (child)
73
+ const child = engine.addEntity() // 514
74
+ Transform.create({ parent, position: {} })
75
+ syncEntity(child, [Transform.componentId], SyncEntities.ChildDoor)
76
+
77
+ So now client A & B had different raw data for the Transform component, because they have different parents.
78
+ Meaning that we have an inconsistent CRDT State between two clients.
79
+ So if there is a new message comming from client C we could have conflicts for client A but maybe not for client B.
80
+
81
+ Same problem would happen if a client after some interaction (i.e. a bullet) creates an entity with a parent. For the client A this could be { parent: 515, child: 516 } but for another user those entities are not going to be the same ones.
82
+
83
+ Solution 1:
84
+ What if we introduce a new ParentNetwork component.
85
+ This ParentNetwork will be in charge of syncronizing the parenting. If we have ParentNetwork then we should always ignore the Transform.parent property.
86
+ The ParentNetwork will have both entityId and networkId such as the PutNetworkMessage so we can map the entity in every client.
87
+
88
+ ParentNetwork.Schema = { entityId: Entity; networkId: number }.
89
+
90
+ Being the networkId the id of the user that owns that parent entity, and the entityId the parent entityId of the user that creates that entity.
91
+ So with this two values, we cant map the real parent entity id on every client.
92
+
93
+ ```ts
94
+ import { syncEntity, parentEntity } from '@dcl/sdk/network'
95
+ const parentEntity = engine.addEntity()
96
+ Transform.create(parentEntity, { position: somePosition })
97
+ syncEntity(parent, Transform.componentId)
98
+ const childEntity: Entity = engine.addEntity()
99
+ syncEntity(childEntity, Transform.componentId)
100
+
101
+ // create parentNetwork component. This maybe could be done in a system and use the original parent. TBD
102
+ parentEntity(childEntity, parentEntity)
103
+ ```
104
+ Every client will know how to map this entity because the ParentNetwork has the pointers to the parent entity. But we are still having an issue, the parent is not defined. We need to tell the renderer that the child entity has a parent property.
105
+
106
+ So every time we send a Transform component to the renderer, we should update the transform.parent property with the mapped Entity that we fetch from the ParentNetwork.
107
+ if (isTransform(message) && isRendererTransport && ParentNetwork.getOrNull(message.entityId)) {
108
+ // Generate a new transform raw data with the parent property included
109
+ }
110
+
111
+ And every time we recieve a message from the renderer, we should remove the parent property to keep consistency in all CRDT state clients.
112
+ if (isTransform(message) && message.type === CrdtMessageType.PUT_COMPONENT && ParentNetwork.has(message.entityId)) {
113
+ transform.parent = null
114
+ // Generate a new transform raw data without the parent property included
115
+ }
116
+
117
+ With this approach, all the clients will have the same Transform, so we avoid the inconsistency of crdt's state.
118
+ And when some user wants to update the transform, it has to modify the ParentNetwork and will update both values, the parent & the network.
119
+
120
+ I think this will work but there are some developer experience issues, like using the `parentEntity(child, parent)` function instead of the transform.parent.
121
+ This could end up with a lot of unexepcted issues/bugs. Maybe we can have a system that iterates over every syncronized entity and when the transform.parent changes, add the parentEntity function automatically.
122
+ First I wanna try to implement all of this and then came up with this approach to avoid inconsistencies
@@ -0,0 +1,74 @@
1
+ import { ReadWriteByteBuffer } from '@dcl/ecs/dist/serialization/ByteBuffer'
2
+
3
+ export enum CommsMessage {
4
+ CRDT = 1,
5
+ REQ_CRDT_STATE = 2,
6
+ RES_CRDT_STATE = 3
7
+ }
8
+
9
+ export function BinaryMessageBus<T extends CommsMessage>(
10
+ send: (message: Uint8Array, toPeerAddress?: string[]) => void
11
+ ) {
12
+ const mapping: Map<T, (value: Uint8Array, sender: string) => void> = new Map()
13
+ return {
14
+ on: <K extends T>(message: K, callback: (value: Uint8Array, sender: string) => void) => {
15
+ mapping.set(message, callback)
16
+ },
17
+ emit: <K extends T>(message: K, value: Uint8Array, toPeerAddress?: string[]) => {
18
+ send(craftCommsMessage<T>(message, value), toPeerAddress)
19
+ },
20
+ __processMessages: (messages: Uint8Array[]) => {
21
+ for (const message of messages) {
22
+ const commsMsg = decodeCommsMessage<T>(message)
23
+ if (!commsMsg) continue
24
+ const { sender, messageType, data } = commsMsg
25
+ const fn = mapping.get(messageType)
26
+ if (fn) fn(data, sender)
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ export function craftCommsMessage<T extends CommsMessage>(messageType: T, payload: Uint8Array): Uint8Array {
33
+ const msg = new Uint8Array(payload.byteLength + 1)
34
+ msg.set([messageType])
35
+ msg.set(payload, 1)
36
+ return msg
37
+ }
38
+
39
+ export function decodeCommsMessage<T extends CommsMessage>(
40
+ data: Uint8Array
41
+ ): { sender: string; messageType: T; data: Uint8Array } | undefined {
42
+ try {
43
+ let offset = 0
44
+ const r = new Uint8Array(data)
45
+ const view = new DataView(r.buffer)
46
+ const senderLength = view.getUint8(offset)
47
+ offset += 1
48
+ const sender = decodeString(data.subarray(1, senderLength + 1))
49
+ offset += senderLength
50
+ const messageType = view.getUint8(offset) as T
51
+ offset += 1
52
+ const message = r.subarray(offset)
53
+
54
+ return {
55
+ sender,
56
+ messageType,
57
+ data: message
58
+ }
59
+ } catch (e) {
60
+ console.error('Invalid Comms message', e)
61
+ }
62
+ }
63
+
64
+ export function decodeString(data: Uint8Array): string {
65
+ const buffer = new ReadWriteByteBuffer()
66
+ buffer.writeBuffer(data, true)
67
+ return buffer.readUtf8String()
68
+ }
69
+
70
+ export function encodeString(s: string): Uint8Array {
71
+ const buffer = new ReadWriteByteBuffer()
72
+ buffer.writeUtf8String(s)
73
+ return buffer.readBuffer()
74
+ }
@@ -0,0 +1,149 @@
1
+ import {
2
+ Entity,
3
+ IEngine,
4
+ NetworkEntity as _NetworkEntity,
5
+ INetowrkEntity,
6
+ NetworkParent as _NetworkParent,
7
+ Transform as _Transform,
8
+ SyncComponents as _SyncComponents,
9
+ INetowrkParent,
10
+ TransformComponent,
11
+ ISyncComponents
12
+ } from '@dcl/ecs'
13
+ import { IProfile } from './message-bus-sync'
14
+ import { getDesyncedComponents } from './state'
15
+
16
+ export type SyncEntity = (entityId: Entity, componentIds: number[], entityEnumId?: number) => void
17
+
18
+ export function entityUtils(engine: IEngine, profile: IProfile) {
19
+ const NetworkEntity = engine.getComponent(_NetworkEntity.componentId) as INetowrkEntity
20
+ const NetworkParent = engine.getComponent(_NetworkParent.componentId) as INetowrkParent
21
+ const Transform = engine.getComponent(_Transform.componentId) as TransformComponent
22
+ const SyncComponents = engine.getComponent(_SyncComponents.componentId) as ISyncComponents
23
+
24
+ /**
25
+ * Create a network entity (sync) through comms, and sync the received components
26
+ */
27
+ function syncEntity(entityId: Entity, componentIds: number[], entityEnumId?: number) {
28
+ let componentsIdsMutable = [...componentIds]
29
+ // Profile not initialized
30
+ if (!profile?.networkId) {
31
+ throw new Error('Profile not initialized. Call syncEntity inside the main() function.')
32
+ }
33
+
34
+ // We use the networkId generated by the user address to identify this entity through the network
35
+ const networkValue = { entityId, networkId: profile.networkId }
36
+
37
+ // If there is an entityEnumId, it means is the same entity for all the clients created on the main funciton.
38
+ // So the networkId should be the same in all the clients to avoid re-creating this entity.
39
+ // For this case we use networkId = 0.
40
+ if (entityEnumId !== undefined) {
41
+ networkValue.networkId = 0
42
+ networkValue.entityId = entityEnumId as Entity
43
+
44
+ // Check if this enum is already used
45
+ for (const [_, network] of engine.getEntitiesWith(NetworkEntity)) {
46
+ if (network.networkId === networkValue.networkId && network.entityId === networkValue.entityId) {
47
+ throw new Error('syncEntity failed because the id provided is already in use')
48
+ }
49
+ }
50
+ }
51
+
52
+ for (const component of getDesyncedComponents(engine)) {
53
+ if (componentsIdsMutable.includes(component.componentId)) {
54
+ console.log(`⚠️ ${component.componentName} can't be sync through the network!`)
55
+ componentsIdsMutable = componentsIdsMutable.filter(($) => $ !== component.componentId)
56
+ }
57
+ }
58
+
59
+ // If is not defined, then is a entity created in runtime (what we called dynamic/runtime entities).
60
+ NetworkEntity.createOrReplace(entityId, networkValue)
61
+ SyncComponents.createOrReplace(entityId, { componentIds: componentsIdsMutable })
62
+ }
63
+
64
+ /**
65
+ * Returns an iterable of all the childrens of the given entity.
66
+ * for (const children of getChildren(parent)) { console.log(children) }
67
+ * or just => const childrens: Entity[] = Array.from(getChildren(parent))
68
+ */
69
+ function* getChildren(parent: Entity): Iterable<Entity> {
70
+ const network = NetworkEntity.getOrNull(parent)
71
+ if (network) {
72
+ for (const [entity, parent] of engine.getEntitiesWith(NetworkParent)) {
73
+ if (parent.entityId === network.entityId && parent.networkId === network.networkId) {
74
+ yield entity
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ function getFirstChild(entity: Entity) {
81
+ return Array.from(getChildren(entity))[0]
82
+ }
83
+
84
+ /**
85
+ * Returns the parent entity of the given entity.
86
+ */
87
+ function getParent(child: Entity): Entity | undefined {
88
+ const parent = NetworkParent.getOrNull(child)
89
+ if (!parent) return undefined
90
+ for (const [entity, network] of engine.getEntitiesWith(NetworkEntity)) {
91
+ if (parent.networkId === network.networkId && parent.entityId === network.entityId) {
92
+ return entity
93
+ }
94
+ }
95
+ return undefined
96
+ }
97
+
98
+ /**
99
+ * Adds the network parenting to sync entities.
100
+ * Equivalent to Transform.parent for local entities
101
+ */
102
+ function parentEntity(entity: Entity, parent: Entity) {
103
+ const network = NetworkEntity.getOrNull(parent)
104
+ if (!network) {
105
+ throw new Error('Entity is not sync. Call syncEntity on the parent.')
106
+ }
107
+
108
+ // Create network parent component
109
+ NetworkParent.createOrReplace(entity, network)
110
+
111
+ // If we dont have a transform for this entity, create an empty one to send it to the renderer
112
+ if (!Transform.getOrNull(entity)) {
113
+ Transform.create(entity)
114
+ } else {
115
+ // Force a tick update of the transform so the renderer receives the NEW parent.
116
+ // createOrReplace bypasses the CRDT unchanged-data suppression optimization,
117
+ // ensuring the renderer transport can inject the network parent into the message.
118
+ const t = Transform.get(entity)
119
+ Transform.createOrReplace(entity, {
120
+ position: { x: t.position.x, y: t.position.y, z: t.position.z },
121
+ rotation: { x: t.rotation.x, y: t.rotation.y, z: t.rotation.z, w: t.rotation.w },
122
+ scale: { x: t.scale.x, y: t.scale.y, z: t.scale.z },
123
+ parent: t.parent
124
+ })
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Removes the network parenting from an entity
130
+ */
131
+ function removeParent(entity: Entity) {
132
+ const network = NetworkEntity.getOrNull(entity)
133
+
134
+ if (!network) {
135
+ throw new Error('Entity is not sync')
136
+ }
137
+
138
+ NetworkParent.deleteFrom(entity)
139
+ }
140
+
141
+ return {
142
+ syncEntity,
143
+ getChildren,
144
+ getParent,
145
+ parentEntity,
146
+ removeParent,
147
+ getFirstChild
148
+ }
149
+ }
@@ -0,0 +1,63 @@
1
+ import {
2
+ TransportMessage,
3
+ EntityUtils,
4
+ RESERVED_STATIC_ENTITIES,
5
+ CrdtMessageType,
6
+ SyncComponents as _SyncComponents,
7
+ NetworkEntity as _NetworkEntity,
8
+ NetworkParent as _NetworkParent,
9
+ IEngine
10
+ } from '@dcl/ecs'
11
+ import { shouldSyncComponent } from './state'
12
+
13
+ export function syncFilter(engine: IEngine) {
14
+ const NetworkEntity = engine.getComponent(_NetworkEntity.componentId) as typeof _NetworkEntity
15
+ const SyncComponents = engine.getComponent(_SyncComponents.componentId) as typeof _SyncComponents
16
+
17
+ return function (message: Omit<TransportMessage, 'messageBuffer'>) {
18
+ const componentId = (message as any).componentId
19
+ const component = componentId ? engine.getComponentOrNull(componentId) : null
20
+ if (component && !shouldSyncComponent(component)) {
21
+ return false
22
+ }
23
+
24
+ const [entityId] = EntityUtils.fromEntityId(message.entityId)
25
+
26
+ // filter messages from reserved entities.
27
+ if (entityId < RESERVED_STATIC_ENTITIES) {
28
+ return false
29
+ }
30
+
31
+ const network = NetworkEntity.getOrNull(message.entityId)
32
+ // Delete Network Entity Always
33
+ if (
34
+ message.type === CrdtMessageType.DELETE_ENTITY_NETWORK ||
35
+ (network && message.type === CrdtMessageType.DELETE_ENTITY)
36
+ ) {
37
+ return true
38
+ }
39
+
40
+ const sync = SyncComponents.getOrNull(message.entityId)
41
+ if (!sync) return false
42
+
43
+ // First component
44
+ if ((message as any).timestamp <= 1) {
45
+ return true
46
+ }
47
+
48
+ if (componentId === NetworkEntity.componentId) {
49
+ return false
50
+ }
51
+
52
+ // If there is a change in the network parent or syncComponents we should always sync
53
+ if (componentId === _NetworkParent.componentId || componentId === SyncComponents.componentId) {
54
+ return true
55
+ }
56
+
57
+ if (componentId && sync.componentIds.includes(componentId)) {
58
+ return true
59
+ }
60
+
61
+ return false
62
+ }
63
+ }
@@ -0,0 +1,10 @@
1
+ import { sendBinary } from '~system/CommunicationsController'
2
+ import { engine } from '@dcl/ecs'
3
+ import { addSyncTransport } from './message-bus-sync'
4
+ import { getUserData } from '~system/UserIdentity'
5
+
6
+ // initialize sync transport for sdk engine
7
+ const { getChildren, syncEntity, parentEntity, getParent, myProfile, removeParent, getFirstChild, isStateSyncronized } =
8
+ addSyncTransport(engine, sendBinary, getUserData)
9
+
10
+ export { getFirstChild, getChildren, syncEntity, parentEntity, getParent, myProfile, removeParent, isStateSyncronized }