Skip to content

Commit 6113bd2

Browse files
committed
StateView: fix 'refId not found' when using view.add() + view.remove() in the same patch.
1 parent 7b80e21 commit 6113bd2

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@colyseus/schema",
3-
"version": "3.0.41",
3+
"version": "3.0.42",
44
"description": "Binary state serializer with delta encoding for games",
55
"bin": {
66
"schema-codegen": "bin/schema-codegen",

src/encoder/StateView.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,15 @@ export class StateView {
233233
if (changes === undefined) {
234234
changes = {};
235235
this.changes.set(parentChangeTree.refId, changes);
236+
237+
} else if (changes[changeTree.parentIndex] === OPERATION.ADD) {
238+
//
239+
// SAME PATCH ADD + REMOVE:
240+
// The 'changes' of deleted structure should be ignored.
241+
//
242+
this.changes.delete(changeTree.refId);
236243
}
244+
237245
// DELETE / DELETE BY REF ID
238246
changes[changeTree.parentIndex] = OPERATION.DELETE;
239247

test/StateView.test.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,6 +1192,38 @@ describe("StateView", () => {
11921192
encodeAllMultiple(encoder, state, [client1]));
11931193
});
11941194

1195+
it("removing and re-adding multiple times", () => {
1196+
// Thanks @jcrowson for providing this scenario
1197+
1198+
class NPCState extends Schema {
1199+
@view() @type('number') x: number = 0;
1200+
@view() @type('number') y: number = 0;
1201+
}
1202+
1203+
class State extends Schema {
1204+
@view() @type({ map: NPCState }) npcs = new MapSchema<NPCState>();
1205+
}
1206+
1207+
const state = new State();
1208+
const encoder = getEncoder(state);
1209+
1210+
const ids = ['0', '1', '2', '3'];
1211+
ids.forEach(id => state.npcs.set(id, new NPCState().assign({ x: 1, y: 1 })));
1212+
1213+
const client1 = createClientWithView(state);
1214+
client1.view.add(state.npcs.get('0'));
1215+
client1.view.add(state.npcs.get('1'));
1216+
client1.view.add(state.npcs.get('2'));
1217+
1218+
encodeMultiple(encoder, state, [client1]);
1219+
1220+
client1.view.add(state.npcs.get('3'));
1221+
client1.view.remove(state.npcs.get('3'));
1222+
encodeMultiple(encoder, state, [client1]);
1223+
1224+
assertEncodeAllMultiple(encoder, state, [client1]);
1225+
})
1226+
11951227
});
11961228

11971229
describe("ArraySchema", () => {

0 commit comments

Comments
 (0)