Skip to content

Commit

Permalink
Enhance entity siblingIndex robustness (galacean#971)
Browse files Browse the repository at this point in the history
  • Loading branch information
GuoLei1990 authored Aug 22, 2022
1 parent 367758e commit be6afc3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 21 deletions.
38 changes: 19 additions & 19 deletions packages/core/src/Entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,7 @@ export class Entity extends EngineObject {
throw `The entity ${this.name} is not in the hierarchy`;
}

if (this._siblingIndex !== value) {
this._setSiblingIndex(this._isRoot ? this._scene._rootEntities : this._parent._children, value);
}
this._setSiblingIndex(this._isRoot ? this._scene._rootEntities : this._parent._children, value);
}

/**
Expand Down Expand Up @@ -568,22 +566,24 @@ export class Entity extends EngineObject {
}

private _setSiblingIndex(sibling: Entity[], target: number): void {
if (target < 0 || target > sibling.length) {
throw `The index ${target} is out of child list bounds ${sibling.length}`;
}

const oldIndex = this._siblingIndex;
if (target < oldIndex) {
for (let i = oldIndex; i >= target; i--) {
const child = i == target ? this : sibling[i - 1];
sibling[i] = child;
child._siblingIndex = i;
}
} else {
for (let i = oldIndex; i <= target; i++) {
const child = i == target ? this : sibling[i + 1];
sibling[i] = child;
child._siblingIndex = i;
target = Math.min(target, sibling.length - 1);
if (target < 0) {
throw `Sibling index ${target} should large than 0`;
}
if (this._siblingIndex !== target) {
const oldIndex = this._siblingIndex;
if (target < oldIndex) {
for (let i = oldIndex; i >= target; i--) {
const child = i == target ? this : sibling[i - 1];
sibling[i] = child;
child._siblingIndex = i;
}
} else {
for (let i = oldIndex; i <= target; i++) {
const child = i == target ? this : sibling[i + 1];
sibling[i] = child;
child._siblingIndex = i;
}
}
}
}
Expand Down
9 changes: 7 additions & 2 deletions tests/src/core/Entity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,12 +351,17 @@ describe("Entity", () => {
expect(child2.siblingIndex).eq(2);
expect(child1.siblingIndex).eq(-1);

// out of range
// project large index
child2.siblingIndex = 5;
expect(child2.siblingIndex).eq(2);

// thorw error whenless than 0 index
var siblingIndexBadFn = function () {
child2.siblingIndex = 5;
child2.siblingIndex = -1;
};
expect(siblingIndexBadFn).to.throw();

// thorw error when set lonely entity
const entityX = new Entity(engine, "entityX");
var lonelyBadFn = function () {
entityX.siblingIndex = 1;
Expand Down

0 comments on commit be6afc3

Please sign in to comment.