-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add globalPosition
getter/setter to Transform
#1032
Open
leanmendoza
wants to merge
8
commits into
main
Choose a base branch
from
feat/add-global-position-to-transform
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
73753a5
wip
leanmendoza 42260da
fix unexistent files
leanmendoza 347c20d
working
leanmendoza ac14c2d
put back snapshot tests
leanmendoza a64919e
Merge remote-tracking branch 'origin/main' into feat/add-global-posit…
leanmendoza 70931ea
add more tests
leanmendoza e1c1290
update snapshots
leanmendoza dda9a4f
fix tests
leanmendoza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,7 +13,7 @@ | |
"--async-stack-traces" | ||
], | ||
"args": [ | ||
"${fileBasename}", | ||
"${file}", | ||
"--verbose", | ||
"--no-cache", | ||
"-i" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import { DeepReadonly, IEngine, LastWriteWinElementSetComponentDefinition } from '../../engine' | ||
import { Entity } from '../../engine/entity' | ||
import { Vector3Type } from '../../schemas' | ||
import { TransformSchema, TransformType } from '../manual/TransformSchema' | ||
import { getGlobalPositionHelper } from './transform-utils/globalPosition' | ||
|
||
/** | ||
* @public | ||
*/ | ||
export type TransformComponent = LastWriteWinElementSetComponentDefinition<TransformType> | ||
|
||
/** | ||
* @public | ||
*/ | ||
export type MutableTransform = TransformType & { | ||
// Get calculated global position or set local position by passing the resultant one | ||
// Log and error in case of failing. Cyclic parenting, invalid scales or rotations could raise undefined behavior | ||
// Warning: this property usage might be expensive, use it wisely | ||
globalPosition: Vector3Type | ||
} | ||
|
||
/** | ||
* @public | ||
*/ | ||
export type ReadonlyTransform = DeepReadonly<TransformType> & { | ||
// Get calculated global position | ||
// Log and error in case of failing. Cyclic parenting, invalid scales or rotations could raise undefined behavior | ||
// Warning: this property usage might be expensive, use it wisely | ||
globalPosition: Readonly<Vector3Type> | ||
} | ||
|
||
/** | ||
* @public | ||
*/ | ||
export interface TransformComponentExtended extends TransformComponent { | ||
create(entity: Entity, val?: TransformTypeWithOptionals): MutableTransform | ||
createOrReplace(entity: Entity, val?: TransformTypeWithOptionals): MutableTransform | ||
get(entity: Entity): ReadonlyTransform | ||
getOrNull(entity: Entity): ReadonlyTransform | null | ||
getMutable(entity: Entity): MutableTransform | ||
getMutableOrNull(entity: Entity): MutableTransform | null | ||
getOrCreateMutable(entity: Entity, initialValue?: TransformTypeWithOptionals): MutableTransform | ||
} | ||
|
||
/** | ||
* @public | ||
*/ | ||
export type TransformTypeWithOptionals = Partial<TransformType> | ||
|
||
export function defineTransformComponent( | ||
engine: Pick<IEngine, 'defineComponentFromSchema'> | ||
): TransformComponentExtended { | ||
const transformDef = engine.defineComponentFromSchema('core::Transform', TransformSchema) | ||
const definePropertiesIfNotSet = getGlobalPositionHelper(transformDef) | ||
|
||
return { | ||
...transformDef, | ||
create(entity: Entity, val?: TransformTypeWithOptionals) { | ||
const value = transformDef.create(entity, TransformSchema.extend!(val)) | ||
definePropertiesIfNotSet(value) | ||
return value as MutableTransform | ||
}, | ||
createOrReplace(entity: Entity, val?: TransformTypeWithOptionals) { | ||
const value = transformDef.createOrReplace(entity, TransformSchema.extend!(val)) | ||
definePropertiesIfNotSet(value) | ||
return value as MutableTransform | ||
}, | ||
getOrNull(entity: Entity): ReadonlyTransform | null { | ||
const component = transformDef.__data.get(entity) | ||
if (component) { | ||
definePropertiesIfNotSet(component) | ||
} | ||
return component ? (component as ReadonlyTransform) : null | ||
}, | ||
|
||
// Functions below depend on the funtiosn above, the functions above are in charge of call `definePropertiesIfNotSet` | ||
|
||
getOrCreateMutable(entity: Entity, initialValue?: TransformTypeWithOptionals) { | ||
let value = transformDef.getMutableOrNull(entity) | ||
if (value === null) { | ||
value = this.createOrReplace(entity, initialValue) | ||
} else { | ||
transformDef.__dirtyIterator.add(entity) | ||
} | ||
return value as MutableTransform | ||
}, | ||
get(entity: Entity): ReadonlyTransform { | ||
const component = this.getOrNull(entity) | ||
if (component === null) { | ||
throw new Error(`[getFrom] Component ${transformDef.componentName} for entity #${entity} not found`) | ||
} | ||
return component as ReadonlyTransform | ||
}, | ||
getMutable(entity: Entity): MutableTransform { | ||
const component = this.get(entity) | ||
if (component) { | ||
transformDef.__dirtyIterator.add(entity) | ||
} | ||
return component as MutableTransform | ||
}, | ||
getMutableOrNull(entity: Entity): MutableTransform { | ||
const component = this.getOrNull(entity) | ||
if (component) { | ||
transformDef.__dirtyIterator.add(entity) | ||
} | ||
return component as MutableTransform | ||
} | ||
} | ||
} |
114 changes: 114 additions & 0 deletions
114
packages/@dcl/ecs/src/components/extended/transform-utils/globalPosition.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
import { LastWriteWinElementSetComponentDefinition } from '../..' | ||
import { Entity } from '../../../engine' | ||
import { Vector3Type } from '../../../schemas' | ||
import { Vector3 } from '../../generated/pb/decentraland/common/vectors.gen' | ||
import { TransformType } from '../../manual/TransformSchema' | ||
import { MutableTransform } from '../Transform' | ||
import { applyQuaternionToVector3, multiplyQuaternionToRef, vector3AddToRef, vector3MultiplyToRef } from './math' | ||
|
||
export function getGlobalPositionHelper(transformDef: LastWriteWinElementSetComponentDefinition<TransformType>) { | ||
const helperArray: Entity[] = [] | ||
function getGlobalTransform(transform: TransformType): TransformType { | ||
const position = { ...transform.position } | ||
const scale = { ...transform.scale } | ||
const rotation = { ...transform.rotation } | ||
|
||
helperArray.length = 0 | ||
let currentTransform = null | ||
if (transform.parent !== undefined) { | ||
currentTransform = transformDef.getMutableOrNull(transform.parent) | ||
helperArray.push(transform.parent) | ||
} | ||
while (currentTransform !== null) { | ||
// calculate position | ||
vector3MultiplyToRef(currentTransform.scale, position) | ||
applyQuaternionToVector3(currentTransform.rotation, position) | ||
vector3AddToRef(currentTransform.position, position) | ||
|
||
// calculate rotation | ||
multiplyQuaternionToRef(currentTransform.rotation, rotation) | ||
|
||
// calculate scale | ||
vector3MultiplyToRef(currentTransform.scale, scale) | ||
|
||
const nextTransform: TransformType | null = | ||
currentTransform.parent !== undefined ? transformDef.getMutableOrNull(currentTransform.parent) : null | ||
if (nextTransform !== null) { | ||
// We early return if we find a cyclic parent | ||
if (helperArray.includes(currentTransform.parent!)) { | ||
// TODO: should we throw an error instead? | ||
console.error(`There is a cyclic parent with entity ${currentTransform.parent}`) | ||
return { | ||
position, | ||
scale, | ||
rotation | ||
} | ||
} | ||
helperArray.push(currentTransform.parent!) | ||
} | ||
|
||
currentTransform = nextTransform | ||
} | ||
|
||
return { | ||
position, | ||
scale, | ||
rotation | ||
} | ||
} | ||
|
||
function getLocalPosition(transform: TransformType, globalPosition: Vector3) { | ||
const value = { ...globalPosition } | ||
const parentTransform = transform.parent !== undefined ? transformDef.getMutable(transform.parent) : null | ||
if (parentTransform !== null) { | ||
const parentGlobalTransform = getGlobalTransform(parentTransform) | ||
|
||
// Subtract parent position | ||
value.x -= parentGlobalTransform.position.x | ||
value.y -= parentGlobalTransform.position.y | ||
value.z -= parentGlobalTransform.position.z | ||
|
||
// Apply inverse rotation of the parent's global rotation | ||
const inverseParentRotation = { ...parentGlobalTransform.rotation } | ||
inverseParentRotation.x *= -1 | ||
inverseParentRotation.y *= -1 | ||
inverseParentRotation.z *= -1 | ||
applyQuaternionToVector3(inverseParentRotation, value) | ||
|
||
// Divide by parent scale | ||
value.x /= parentGlobalTransform.scale.x | ||
value.y /= parentGlobalTransform.scale.y | ||
value.z /= parentGlobalTransform.scale.z | ||
} | ||
return value | ||
} | ||
|
||
const extendedTransformProperties: PropertyDescriptorMap & ThisType<TransformType> = { | ||
globalPosition: { | ||
get(): Vector3Type { | ||
return getGlobalTransform(this).position | ||
}, | ||
set(value: Vector3Type) { | ||
const newPosition = getLocalPosition(this, value) | ||
// if some of its component is NaN, we don't update the position (there is an undefined behaviour otherwise) | ||
if (!Number.isFinite(newPosition.x) || !Number.isFinite(newPosition.y) || !Number.isFinite(newPosition.z)) { | ||
// TODO: should we throw an error instead? | ||
return | ||
} | ||
this.position = newPosition | ||
}, | ||
enumerable: false | ||
}, | ||
__extended: { | ||
value: true, | ||
enumerable: false, | ||
writable: false | ||
} | ||
} | ||
|
||
return (value: Partial<MutableTransform>) => { | ||
if ((value as any).__extended !== true) { | ||
Object.defineProperties(value, extendedTransformProperties) | ||
} | ||
} | ||
} |
43 changes: 43 additions & 0 deletions
43
packages/@dcl/ecs/src/components/extended/transform-utils/math.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { Quaternion, Vector3 } from '../../generated/pb/decentraland/common/vectors.gen' | ||
|
||
export function multiplyQuaternionToRef(q1: Quaternion, ref: Quaternion): void { | ||
const x = q1.w * ref.x + q1.x * ref.w + q1.y * ref.z - q1.z * ref.y | ||
const y = q1.w * ref.y - q1.x * ref.z + q1.y * ref.w + q1.z * ref.x | ||
const z = q1.w * ref.z + q1.x * ref.y - q1.y * ref.x + q1.z * ref.w | ||
const w = q1.w * ref.w - q1.x * ref.x - q1.y * ref.y - q1.z * ref.z | ||
|
||
ref.x = x | ||
ref.y = y | ||
ref.z = z | ||
ref.w = w | ||
} | ||
|
||
export function applyQuaternionToVector3(q: Quaternion, ref: Vector3): void { | ||
const { x, y, z } = ref | ||
const qx = q.x, | ||
qy = q.y, | ||
qz = q.z, | ||
qw = q.w | ||
|
||
// Calculate quat * vector | ||
const ix = qw * x + qy * z - qz * y | ||
const iy = qw * y + qz * x - qx * z | ||
const iz = qw * z + qx * y - qy * x | ||
const iw = -qx * x - qy * y - qz * z | ||
|
||
ref.x = ix * qw + iw * -qx + iy * -qz - iz * -qy | ||
ref.y = iy * qw + iw * -qy + iz * -qx - ix * -qz | ||
ref.z = iz * qw + iw * -qz + ix * -qy - iy * -qx | ||
} | ||
|
||
export function vector3AddToRef(v1: Vector3, ref: Vector3): void { | ||
ref.x += v1.x | ||
ref.y += v1.y | ||
ref.z += v1.z | ||
} | ||
|
||
export function vector3MultiplyToRef(v1: Vector3, ref: Vector3): void { | ||
ref.x *= v1.x | ||
ref.y *= v1.y | ||
ref.z *= v1.z | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
export type { SystemFn, SYSTEMS_REGULAR_PRIORITY } from '../engine/systems' | ||
export type { TransportMessage, ReceiveMessage, Transport } from '../systems/crdt/types' | ||
export { TransformType, TransformComponent } from '../components/manual/Transform' | ||
export { TransformType } from '../components/manual/TransformSchema' | ||
export { TransformComponent } from '../components/extended/Transform' | ||
export * from '../engine/component' | ||
export * from '../schemas/typing' | ||
export type { MapResult, Spec } from '../schemas/Map' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not going to work for network entities.
We should include some logic here for that, like if the entity is marked as sync, look for the network parentEntity instead of the transform.parent
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can take two path for this, as it doesn't work with AvatarAttach nor Billboard neither:
a. We add the disclaimer comment to get noticed when this accessor is approachable or not.
b. We proper implement all the possibilities and get this feature reliable.
In case of a) we can move forward with the current implementation and add the comments
In case of b), my question is, is there any mechanism to get the globalPositon so far? Because what I saw in Utils library, this is not implemented. The current
getWorldPosition
andgetWorldRotation
doesn't take into consideration thescale
.