From a09bfc88bb00de278e1c5279a1786022e65ece06 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 15 Aug 2024 10:44:31 -0700 Subject: [PATCH 01/29] some minor parser refactors --- fission/src/mirabuf/MirabufInstance.ts | 2 +- fission/src/mirabuf/MirabufParser.ts | 149 +++++++++++-------------- 2 files changed, 67 insertions(+), 84 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 700395611c..8c2cdc7c05 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -134,7 +134,7 @@ class MirabufInstance { let hex = 0xe32b50 let opacity = 1.0 if (appearance.albedo) { - const { A, B, G, R } = appearance.albedo + const { A, B, G, R } = appearance?.albedo if (A && B && G && R) { hex = (A << 24) | (R << 16) | (G << 8) | B opacity = A / 255.0 diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 7dab72156b..948909c6c7 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -83,57 +83,54 @@ class MirabufParser { this.GenerateTreeValues() this.LoadGlobalTransforms() - // eslint-disable-next-line @typescript-eslint/no-this-alias - const that = this - function traverseTree(nodes: mirabuf.INode[], op: (node: mirabuf.INode) => void) { nodes.forEach(x => { - if (x.children) { - traverseTree(x.children, op) - } + if (x.children) traverseTree(x.children, op) op(x) }) } - // 1: Initial Rigidgroups from ancestorial breaks in joints + // const materials = assembly.data?.materials?.physicalMaterials + + // 1: Initial RigidGroups from ancestral breaks in joints const jointInstanceKeys = Object.keys(assembly.data!.joints!.jointInstances!) as string[] jointInstanceKeys.forEach(key => { - if (key != GROUNDED_JOINT_ID) { - const jInst = assembly.data!.joints!.jointInstances![key] - const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) - const parentRN = this.NewRigidNode() - this.MovePartToRigidNode(ancestorA, parentRN) - this.MovePartToRigidNode(ancestorB, this.NewRigidNode()) - if (jInst.parts && jInst.parts.nodes) - traverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) - } - }) + if (key == GROUNDED_JOINT_ID) return - // this.DebugPrintHierarchy(1, ...this._designHierarchyRoot.children!); + const jInst = assembly.data!.joints!.jointInstances![key] + const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) + const parentRN = this.NewRigidNode() + + this.MovePartToRigidNode(ancestorA, parentRN) + this.MovePartToRigidNode(ancestorB, this.NewRigidNode()) + + if (jInst.parts && jInst.parts.nodes) + traverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) + }) // Fields Only: Assign Game Piece rigid nodes if (!assembly.dynamic) { - // Collect all definitions labelled as gamepieces (dynamic = true) + // Collect all definitions labeled as gamepieces (dynamic = true) const gamepieceDefinitions: Set = new Set() Object.values(assembly.data!.parts!.partDefinitions!).forEach((def: mirabuf.IPartDefinition) => { if (def.dynamic) gamepieceDefinitions.add(def.info!.GUID!) }) - // Create gamepiece rigid nodes from partinstances with corresponding definitions + // Create gamepiece rigid nodes from PartInstances with corresponding definitions Object.values(assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { - if (gamepieceDefinitions.has(inst.partDefinitionReference!)) { - const instNode = this.BinarySearchDesignTree(inst.info!.GUID!) - if (instNode) { - const gpRn = this.NewRigidNode(GAMEPIECE_SUFFIX) - gpRn.isGamePiece = true - this.MovePartToRigidNode(instNode!.value!, gpRn) - instNode.children && - traverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) - } else { - this._errors.push([ParseErrorSeverity.LikelyIssues, "Failed to find Game piece in Design Tree"]) - } + if (!gamepieceDefinitions.has(inst.partDefinitionReference!)) return + + const instNode = this.BinarySearchDesignTree(inst.info!.GUID!) + if (!instNode) { + this._errors.push([ParseErrorSeverity.LikelyIssues, "Failed to find Game piece in Design Tree"]) + return } + + const gpRn = this.NewRigidNode(GAMEPIECE_SUFFIX) + gpRn.isGamePiece = true + this.MovePartToRigidNode(instNode!.value!, gpRn) + instNode.children && traverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) }) } @@ -142,26 +139,19 @@ class MirabufParser { const gNode = this.NewRigidNode() this.MovePartToRigidNode(gInst.parts!.nodes!.at(0)!.value!, gNode) - // traverseTree(gInst.parts!.nodes!, x => (!this._partToNodeMap.has(x.value!)) && this.MovePartToRigidNode(x.value!, gNode)); - // this.DebugPrintHierarchy(1, ...this._designHierarchyRoot.children!); // 3: Traverse and round up const traverseNodeRoundup = (node: mirabuf.INode, parentNode: RigidNode) => { - const currentNode = that._partToNodeMap.get(node.value!) - if (!currentNode) { - that.MovePartToRigidNode(node.value!, parentNode) - } - - if (node.children) { - node.children!.forEach(x => traverseNodeRoundup(x, currentNode ? currentNode : parentNode)) - } + const currentNode = this._partToNodeMap.get(node.value!) + if (!currentNode) this.MovePartToRigidNode(node.value!, parentNode) + ;(node.children ?? []).forEach(x => traverseNodeRoundup(x, currentNode ?? parentNode)) } this._designHierarchyRoot.children?.forEach(x => traverseNodeRoundup(x, gNode)) // this.DebugPrintHierarchy(1, ...this._designHierarchyRoot.children!); - // 4: Bandage via rigidgroups + // 4: Bandage via RigidGroups assembly.data!.joints!.rigidGroups!.forEach(rg => { let rn: RigidNode | null = null rg.occurrences!.forEach(y => { @@ -203,11 +193,10 @@ class MirabufParser { const rA = this._partToNodeMap.get(x.parentPart) const rB = this._partToNodeMap.get(x.childPart) - if (rA && rB && rA.id != rB.id) { - graph.AddNode(rA.id) - graph.AddNode(rB.id) - graph.AddEdgeUndirected(rA.id, rB.id) - } + if (!rA || !rB || rA.id == rB.id) return + graph.AddNode(rA.id) + graph.AddNode(rB.id) + graph.AddEdgeUndirected(rA.id, rB.id) }) const directedGraph = new Graph() const whiteGreyBlackMap = new Map() @@ -215,22 +204,22 @@ class MirabufParser { whiteGreyBlackMap.set(x.id, false) directedGraph.AddNode(x.id) }) + function directedRecursive(node: string) { graph.GetAdjacencyList(node).forEach(x => { - if (whiteGreyBlackMap.has(x)) { - directedGraph.AddEdgeDirected(node, x) - whiteGreyBlackMap.delete(x) - directedRecursive(x) - } + if (!whiteGreyBlackMap.has(x)) return + + directedGraph.AddEdgeDirected(node, x) + whiteGreyBlackMap.delete(x) + directedRecursive(x) }) } - if (rootNode) { - whiteGreyBlackMap.delete(rootNode.id) - directedRecursive(rootNode.id) - } else { - whiteGreyBlackMap.delete(this._rigidNodes[0].id) - directedRecursive(this._rigidNodes[0].id) - } + + const node = rootNode?.id ?? this._rigidNodes[0].id + + whiteGreyBlackMap.delete(node) + directedRecursive(node) + this._directedGraph = directedGraph // Transition: GH-1014 @@ -243,7 +232,7 @@ class MirabufParser { } private NewRigidNode(suffix?: string): RigidNode { - const node = new RigidNode(`${this._nodeNameCounter++}${suffix ? suffix : ""}`) + const node = new RigidNode(`${this._nodeNameCounter++}${suffix ?? ""}`) this._rigidNodes.push(node) return node } @@ -283,41 +272,35 @@ class MirabufParser { this._globalTransforms.clear() const getTransforms = (node: mirabuf.INode, parent: THREE.Matrix4) => { - for (const child of node.children!) { - if (!partInstances.has(child.value!)) { - continue - } - const partInstance = partInstances.get(child.value!)! + node.children!.forEach(child => { + const partInstance: mirabuf.IPartInstance | undefined = partInstances.get(child.value!) - if (this._globalTransforms.has(child.value!)) continue + if (!partInstance || this.globalTransforms.has(child.value!)) return const mat = MirabufTransform_ThreeMatrix4(partInstance.transform!)! // console.log(`[${partInstance.info!.name!}] -> ${matToString(mat)}`); this._globalTransforms.set(child.value!, mat.premultiply(parent)) getTransforms(child, mat) - } + }) } - for (const child of root.children!) { + root.children?.forEach(child => { const partInstance = partInstances.get(child.value!)! - let mat - if (!partInstance.transform) { - const def = partDefinitions[partInstances.get(child.value!)!.partDefinitionReference!] - if (!def.baseTransform) { - mat = new THREE.Matrix4().identity() - } else { - mat = MirabufTransform_ThreeMatrix4(def.baseTransform) - } - } else { - mat = MirabufTransform_ThreeMatrix4(partInstance.transform) - } + // TODO: guarantee that these assertions won't fail + const def = partDefinitions[partInstance.partDefinitionReference!] + + const mat = partInstance.transform + ? MirabufTransform_ThreeMatrix4(partInstance.transform) + : def.baseTransform + ? MirabufTransform_ThreeMatrix4(def.baseTransform) + : new THREE.Matrix4().identity() // console.log(`[${partInstance.info!.name!}] -> ${matToString(mat!)}`); - this._globalTransforms.set(partInstance.info!.GUID!, mat!) - getTransforms(child, mat!) - } + this._globalTransforms.set(partInstance.info!.GUID!, mat) + getTransforms(child, mat) + }) } private FindAncestorialBreak(partA: string, partB: string): [string, string] { @@ -480,7 +463,7 @@ export class Graph { public AddEdgeDirected(nodeA: string, nodeB: string) { if (!this._adjacencyMap.has(nodeA) || !this._adjacencyMap.has(nodeB)) throw new Error("Nodes aren't in graph") - this._adjacencyMap.get(nodeA)!.push(nodeB) + this._adjacencyMap.get(nodeA).push(nodeB) } public GetAdjacencyList(node: string) { From 1b1ad678043dae57e1861ab76d9e46a7e6058c0f Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Fri, 16 Aug 2024 10:01:26 -0700 Subject: [PATCH 02/29] some declarative-style refactors of instance and parsing --- fission/src/mirabuf/MirabufInstance.ts | 148 ++++++++++------------ fission/src/mirabuf/MirabufParser.ts | 4 +- fission/src/mirabuf/MirabufSceneObject.ts | 46 +++---- 3 files changed, 85 insertions(+), 113 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 8c2cdc7c05..fd54564623 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -109,9 +109,8 @@ class MirabufInstance { } public constructor(parser: MirabufParser, materialStyle?: MaterialStyle, progressHandle?: ProgressHandle) { - if (parser.errors.some(x => x[0] >= ParseErrorSeverity.Unimportable)) { + if (parser.errors.some(x => x[0] >= ParseErrorSeverity.Unimportable)) throw new Error("Parser has significant errors...") - } this._mirabufParser = parser this._materials = new Map() @@ -126,39 +125,30 @@ class MirabufInstance { } /** - * Parses all mirabuf appearances into ThreeJs materials. + * Parses all mirabuf appearances into ThreeJS materials. */ private LoadMaterials(materialStyle: MaterialStyle) { Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!).forEach( ([appearanceId, appearance]) => { - let hex = 0xe32b50 - let opacity = 1.0 - if (appearance.albedo) { - const { A, B, G, R } = appearance?.albedo - if (A && B && G && R) { - hex = (A << 24) | (R << 16) | (G << 8) | B - opacity = A / 255.0 - } - } - - let material: THREE.Material - if (materialStyle == MaterialStyle.Regular) { - material = new THREE.MeshPhongMaterial({ - color: hex, - shininess: 0.0, - shadowSide: THREE.DoubleSide, - opacity: opacity, - transparent: opacity < 1.0, - }) - } else if (materialStyle == MaterialStyle.Normals) { - material = new THREE.MeshNormalMaterial() - } else if (materialStyle == MaterialStyle.Toon) { - material = World.SceneRenderer.CreateToonMaterial(hex, 5) - console.debug("Toon Material") - } - - World.SceneRenderer.SetupMaterial(material!) - this._materials.set(appearanceId, material!) + const { A, B, G, R } = appearance.albedo ?? {} + const [hex, opacity] = + A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] + + const material = + materialStyle === MaterialStyle.Regular + ? new THREE.MeshPhongMaterial({ + color: hex, + shininess: 0.0, + shadowSide: THREE.DoubleSide, + opacity: opacity, + transparent: opacity < 1.0, + }) + : materialStyle === MaterialStyle.Normals + ? new THREE.MeshNormalMaterial() + : World.SceneRenderer.CreateToonMaterial(hex, 5) + + World.SceneRenderer.SetupMaterial(material) + this._materials.set(appearanceId, material) } ) } @@ -178,61 +168,51 @@ class MirabufInstance { const batchMap = new Map]>>() const countMap = new Map() - // Filter all instances by first material, then body - for (const instance of Object.values(instances)) { - const definition = assembly.data!.parts!.partDefinitions![instance.partDefinitionReference!]! - const bodies = definition.bodies - if (bodies) { - for (const body of bodies) { - if (!body) continue - const mesh = body.triangleMesh - if ( - mesh && - mesh.mesh && - mesh.mesh.verts && - mesh.mesh.normals && - mesh.mesh.uv && - mesh.mesh.indices - ) { - const appearanceOverride = body.appearanceOverride - const material: THREE.Material = WIREFRAME - ? new THREE.MeshStandardMaterial({ wireframe: true, color: 0x000000 }) - : appearanceOverride && this._materials.has(appearanceOverride) - ? this._materials.get(appearanceOverride)! - : fillerMaterials[nextFillerMaterial++ % fillerMaterials.length] - - let materialBodyMap = batchMap.get(material) - if (!materialBodyMap) { - materialBodyMap = new Map]>() - batchMap.set(material, materialBodyMap) - } - - const partBodyGuid = this.GetPartBodyGuid(definition, body) - let bodyInstances = materialBodyMap.get(partBodyGuid) - if (!bodyInstances) { - bodyInstances = [body, new Array()] - materialBodyMap.set(partBodyGuid, bodyInstances) - } - bodyInstances[1].push(instance) - - if (countMap.has(material)) { - const count = countMap.get(material)! - count.maxInstances += 1 - count.maxVertices += mesh.mesh.verts.length / 3 - count.maxIndices += mesh.mesh.indices.length - } else { - const count: BatchCounts = { - maxInstances: 1, - maxVertices: mesh.mesh.verts.length / 3, - maxIndices: mesh.mesh.indices.length, - } - countMap.set(material, count) - } - } + Object.values(instances).forEach(instance => { + const definition = assembly.data!.parts!.partDefinitions![instance.partDefinitionReference!] + const bodies = definition?.bodies ?? [] + bodies.forEach(body => { + const mesh = body?.triangleMesh?.mesh + if (!mesh?.verts || !mesh.normals || !mesh.uv || !mesh.indices) return + + const appearanceOverride = body.appearanceOverride + const material: THREE.Material = WIREFRAME + ? new THREE.MeshStandardMaterial({ wireframe: true, color: 0x000000 }) + : appearanceOverride && this._materials.has(appearanceOverride) + ? this._materials.get(appearanceOverride)! + : fillerMaterials[nextFillerMaterial++ % fillerMaterials.length] + + let materialBodyMap = batchMap.get(material) + if (!materialBodyMap) { + materialBodyMap = new Map]>() + batchMap.set(material, materialBodyMap) } - } - } + + const partBodyGuid = this.GetPartBodyGuid(definition, body) + let bodyInstances = materialBodyMap.get(partBodyGuid) + if (!bodyInstances) { + bodyInstances = [body, new Array()] + materialBodyMap.set(partBodyGuid, bodyInstances) + } + bodyInstances[1].push(instance) + + if (countMap.has(material)) { + const count = countMap.get(material)! + count.maxInstances += 1 + count.maxVertices += mesh.verts.length / 3 + count.maxIndices += mesh.indices.length + return + } + + const count: BatchCounts = { + maxInstances: 1, + maxVertices: mesh.verts.length / 3, + maxIndices: mesh.indices.length, + } + countMap.set(material, count) + }) + }) console.debug(batchMap) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 948909c6c7..610e58f0d0 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -461,9 +461,9 @@ export class Graph { } public AddEdgeDirected(nodeA: string, nodeB: string) { - if (!this._adjacencyMap.has(nodeA) || !this._adjacencyMap.has(nodeB)) throw new Error("Nodes aren't in graph") + if (!this._adjacencyMap.has(nodeA) || !this._adjacencyMap?.has(nodeB)) throw new Error("Nodes aren't in graph") - this._adjacencyMap.get(nodeA).push(nodeB) + this._adjacencyMap.get(nodeA)!.push(nodeB) } public GetAdjacencyList(node: string) { diff --git a/fission/src/mirabuf/MirabufSceneObject.ts b/fission/src/mirabuf/MirabufSceneObject.ts index 2804f3ae1b..f36415bc71 100644 --- a/fission/src/mirabuf/MirabufSceneObject.ts +++ b/fission/src/mirabuf/MirabufSceneObject.ts @@ -100,9 +100,7 @@ class MirabufSceneObject extends SceneObject { progressHandle?.Update("Creating mechanism...", 0.9) this._mechanism = World.PhysicsSystem.CreateMechanismFromParser(this._mirabufInstance.parser) - if (this._mechanism.layerReserve) { - this._physicsLayerReserve = this._mechanism.layerReserve - } + if (this._mechanism.layerReserve) this._physicsLayerReserve = this._mechanism.layerReserve this._debugBodies = null @@ -111,11 +109,11 @@ class MirabufSceneObject extends SceneObject { this.getPreferences() // creating nametag for robots - if (this.miraType === MiraType.ROBOT) { - this._nameTag = new SceneOverlayTag(() => - this._brain instanceof SynthesisBrain ? this._brain.inputSchemeName : "Not Configured" - ) - } + if (this.miraType !== MiraType.ROBOT) return + + this._nameTag = new SceneOverlayTag(() => + this._brain instanceof SynthesisBrain ? this._brain.inputSchemeName : "Not Configured" + ) } public Setup(): void { @@ -163,9 +161,7 @@ class MirabufSceneObject extends SceneObject { public Update(): void { const brainIndex = this._brain instanceof SynthesisBrain ? this._brain.brainIndex ?? -1 : -1 - if (InputSystem.getInput("eject", brainIndex)) { - this.Eject() - } + if (InputSystem.getInput("eject", brainIndex)) this.Eject() this._mirabufInstance.parser.rigidNodes.forEach(rn => { if (!this._mirabufInstance.meshes.size) return // if this.dispose() has been ran then return @@ -191,7 +187,7 @@ class MirabufSceneObject extends SceneObject { this.DisableTransformControls() return } else if (InputSystem.isKeyPressed("Escape")) { - // cancelling the creation of the mirabuf scene object + // canceling the creation of the mirabuf scene object World.SceneRenderer.RemoveSceneObject(this.id) return } @@ -230,16 +226,16 @@ class MirabufSceneObject extends SceneObject { }) /* Updating the position of the name tag according to the robots position on screen */ - if (this._nameTag && PreferencesSystem.getGlobalPreference("RenderSceneTags")) { - const boundingBox = this.ComputeBoundingBox() - this._nameTag.position = World.SceneRenderer.WorldToPixelSpace( - new THREE.Vector3( - (boundingBox.max.x + boundingBox.min.x) / 2, - boundingBox.max.y + 0.1, - (boundingBox.max.z + boundingBox.min.z) / 2 - ) + if (!this._nameTag || !PreferencesSystem.getGlobalPreference("RenderSceneTags")) return + + const boundingBox = this.ComputeBoundingBox() + this._nameTag.position = World.SceneRenderer.WorldToPixelSpace( + new THREE.Vector3( + (boundingBox.max.x + boundingBox.min.x) / 2, + boundingBox.max.y + 0.1, + (boundingBox.max.z + boundingBox.min.z) / 2 ) - } + ) } public Dispose(): void { @@ -279,9 +275,7 @@ class MirabufSceneObject extends SceneObject { } public Eject() { - if (!this._ejectable) { - return - } + if (!this._ejectable) return this._ejectable.Eject() World.SceneRenderer.RemoveSceneObject(this._ejectable.id) @@ -336,9 +330,7 @@ class MirabufSceneObject extends SceneObject { public SetEjectable(bodyId?: Jolt.BodyID, removeExisting: boolean = false): boolean { if (this._ejectable) { - if (!removeExisting) { - return false - } + if (!removeExisting) return false World.SceneRenderer.RemoveSceneObject(this._ejectable.id) this._ejectable = undefined From 1594ef38d201baaade239c5f4d028bc39607582c Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Fri, 16 Aug 2024 20:06:51 -0700 Subject: [PATCH 03/29] minor changes --- fission/src/mirabuf/MirabufInstance.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index fd54564623..6b65dbe037 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -89,9 +89,11 @@ const transformGeometry = (geometry: THREE.BufferGeometry, mesh: mirabuf.IMesh) geometry.setIndex(mesh.indices!) } +type FrictionCoefficients = { dyn: number; stat: number } + class MirabufInstance { private _mirabufParser: MirabufParser - private _materials: Map + private _materials: Map private _meshes: Map> private _batches: Array @@ -125,9 +127,14 @@ class MirabufInstance { } /** - * Parses all mirabuf appearances into ThreeJS materials. + * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { + Object.entries(this._mirabufParser.assembly.data!.materials!.physicalMaterials!).forEach(([name, material]) => { + const [static_f, dynamic_f] = [material.staticFriction, material.dynamicFriction] + console.log(`${name} - static: ${static_f} dynamic: ${dynamic_f}`) + //this._materials.set() + }) Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!).forEach( ([appearanceId, appearance]) => { const { A, B, G, R } = appearance.albedo ?? {} From a370ff25e54453ceb90dbf921fad464fee0a7799 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Mon, 19 Aug 2024 10:24:13 -0700 Subject: [PATCH 04/29] set friction when creating bodies from parser --- fission/src/systems/physics/PhysicsSystem.ts | 177 +++++++++---------- 1 file changed, 84 insertions(+), 93 deletions(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 42c43f213a..3ad3290af5 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -350,59 +350,47 @@ class PhysicsSystem extends WorldSystem { const bodyA = this.GetBody(bodyIdA) const bodyB = this.GetBody(bodyIdB) - const constraints: Jolt.Constraint[] = [] let listener: Jolt.PhysicsStepListener | undefined = undefined + function addConstraint(c: Jolt.Constraint): void { + mechanism.AddConstraint({ + parentBody: bodyIdA!, + childBody: bodyIdB!, + constraint: c, + info: jInst.info ?? undefined, // remove possibility for null + }) + } + switch (jDef.jointMotionType!) { case mirabuf.joint.JointMotion.REVOLUTE: if (this.IsWheel(jDef)) { - if (parser.directedGraph.GetAdjacencyList(rnA.id).length > 0) { - const res = this.CreateWheelConstraint( - jInst, - jDef, - bodyA, - bodyB, - parser.assembly.info!.version! - ) - constraints.push(res[0]) - constraints.push(res[1]) - listener = res[2] - } else { - const res = this.CreateWheelConstraint( - jInst, - jDef, - bodyB, - bodyA, - parser.assembly.info!.version! - ) - constraints.push(res[0]) - constraints.push(res[1]) - listener = res[2] - } + const [bodyOne, bodyTwo] = + parser.directedGraph.GetAdjacencyList(rnA.id).length > 0 ? [bodyA, bodyB] : [bodyB, bodyA] + + const res = this.CreateWheelConstraint( + jInst, + jDef, + bodyOne, + bodyTwo, + parser.assembly.info!.version! + ) + addConstraint(res[0]) + addConstraint(res[1]) + listener = res[2] } else { - constraints.push( + addConstraint( this.CreateHingeConstraint(jInst, jDef, bodyA, bodyB, parser.assembly.info!.version!) ) } break case mirabuf.joint.JointMotion.SLIDER: - constraints.push(this.CreateSliderConstraint(jInst, jDef, bodyA, bodyB)) + addConstraint(this.CreateSliderConstraint(jInst, jDef, bodyA, bodyB)) break default: console.debug("Unsupported joint detected. Skipping...") break } - if (constraints.length > 0) { - constraints.forEach(x => - mechanism.AddConstraint({ - parentBody: bodyIdA, - childBody: bodyIdB, - constraint: x, - info: jInst.info ?? undefined, // remove possibility for null - }) - ) - } if (listener) { mechanism.AddStepListener(listener) } @@ -456,7 +444,7 @@ class PhysicsSystem extends WorldSystem { ) // Some values that are meant to be exactly PI are perceived as being past it, causing unexpected behavior. - // This safety check caps the values to be within [-PI, PI] wth minimal difference in precision. + // This safety check caps the values to be within [-PI, PI] with minimal difference in precision. const piSafetyCheck = (v: number) => Math.min(3.14158, Math.max(-3.14158, v)) if ( @@ -646,6 +634,7 @@ class PhysicsSystem extends WorldSystem { let shapesAdded = 0 let totalMass = 0 + let frictionOverride = 0 const comAccum = new mirabuf.Vector3() const minBounds = new JOLT.Vec3(1000000.0, 1000000.0, 1000000.0) @@ -659,49 +648,47 @@ class PhysicsSystem extends WorldSystem { rn.parts.forEach(partId => { const partInstance = parser.assembly.data!.parts!.partInstances![partId]! - if ( - partInstance.skipCollider == null || - partInstance == undefined || - partInstance.skipCollider == false - ) { - const partDefinition = - parser.assembly.data!.parts!.partDefinitions![partInstance.partDefinitionReference!]! - - const partShapeResult = rn.isDynamic - ? this.CreateConvexShapeSettingsFromPart(partDefinition) - : this.CreateConcaveShapeSettingsFromPart(partDefinition) - - if (partShapeResult) { - const [shapeSettings, partMin, partMax] = partShapeResult - - const transform = ThreeMatrix4_JoltMat44(parser.globalTransforms.get(partId)!) - const translation = transform.GetTranslation() - const rotation = transform.GetQuaternion() - compoundShapeSettings.AddShape(translation, rotation, shapeSettings, 0) - shapesAdded++ - - this.UpdateMinMaxBounds(transform.Multiply3x3(partMin), minBounds, maxBounds) - this.UpdateMinMaxBounds(transform.Multiply3x3(partMax), minBounds, maxBounds) - - JOLT.destroy(partMin) - JOLT.destroy(partMax) - JOLT.destroy(transform) - - if ( - partDefinition.physicalData && - partDefinition.physicalData.com && - partDefinition.physicalData.mass - ) { - const mass = partDefinition.massOverride - ? partDefinition.massOverride! - : partDefinition.physicalData.mass! - totalMass += mass - comAccum.x += (partDefinition.physicalData.com.x! * mass) / 100.0 - comAccum.y += (partDefinition.physicalData.com.y! * mass) / 100.0 - comAccum.z += (partDefinition.physicalData.com.z! * mass) / 100.0 - } - } - } + if (partInstance.skipCollider) return + + const partDefinition = + parser.assembly.data!.parts!.partDefinitions![partInstance.partDefinitionReference!]! + + const partShapeResult = rn.isDynamic + ? this.CreateConvexShapeSettingsFromPart(partDefinition) + : this.CreateConcaveShapeSettingsFromPart(partDefinition) + + if (!partShapeResult) return + + const [shapeSettings, partMin, partMax] = partShapeResult + + const transform = ThreeMatrix4_JoltMat44(parser.globalTransforms.get(partId)!) + const translation = transform.GetTranslation() + const rotation = transform.GetQuaternion() + compoundShapeSettings.AddShape(translation, rotation, shapeSettings, 0) + shapesAdded++ + + this.UpdateMinMaxBounds(transform.Multiply3x3(partMin), minBounds, maxBounds) + this.UpdateMinMaxBounds(transform.Multiply3x3(partMax), minBounds, maxBounds) + + JOLT.destroy(partMin) + JOLT.destroy(partMax) + JOLT.destroy(transform) + + // Set friction override once to any of the parts' values + if (!frictionOverride && partDefinition?.frictionOverride) + frictionOverride = partDefinition.frictionOverride + + if (!partDefinition.physicalData?.com || !partDefinition.physicalData.mass) return + + const mass = partDefinition.massOverride + ? partDefinition.massOverride! + : partDefinition.physicalData.mass! + + totalMass += mass + + comAccum.x += (partDefinition.physicalData.com.x! * mass) / 100.0 + comAccum.y += (partDefinition.physicalData.com.y! * mass) / 100.0 + comAccum.z += (partDefinition.physicalData.com.z! * mass) / 100.0 }) if (shapesAdded > 0) { @@ -713,9 +700,7 @@ class PhysicsSystem extends WorldSystem { const shape = shapeResult.Get() - if (rn.isDynamic) { - shape.GetMassProperties().mMass = totalMass == 0.0 ? 1 : totalMass - } + if (rn.isDynamic) shape.GetMassProperties().mMass = !totalMass ? 1 : totalMass const bodySettings = new JOLT.BodyCreationSettings( shape, @@ -729,9 +714,15 @@ class PhysicsSystem extends WorldSystem { body.SetAllowSleeping(false) rnToBodies.set(rn.id, body.GetID()) + // Set Friction Here + if (frictionOverride) body.SetFriction(frictionOverride) + // Little testing components this._bodies.push(body.GetID()) body.SetRestitution(0.4) + + if (!frictionOverride) return + body.SetFriction(frictionOverride) } // Cleanup JOLT.destroy(compoundShapeSettings) @@ -748,7 +739,7 @@ class PhysicsSystem extends WorldSystem { */ private CreateConvexShapeSettingsFromPart( partDefinition: mirabuf.IPartDefinition - ): [Jolt.ShapeSettings, Jolt.Vec3, Jolt.Vec3] | undefined | null { + ): [Jolt.ShapeSettings, Jolt.Vec3, Jolt.Vec3] | undefined { const settings = new JOLT.ConvexHullShapeSettings() const min = new JOLT.Vec3(1000000.0, 1000000.0, 1000000.0) @@ -756,14 +747,14 @@ class PhysicsSystem extends WorldSystem { const points = settings.mPoints partDefinition.bodies!.forEach(body => { - if (body.triangleMesh && body.triangleMesh.mesh && body.triangleMesh.mesh.verts) { - const vertArr = body.triangleMesh.mesh.verts - for (let i = 0; i < body.triangleMesh.mesh.verts.length; i += 3) { - const vert = MirabufFloatArr_JoltVec3(vertArr, i) - points.push_back(vert) - this.UpdateMinMaxBounds(vert, min, max) - JOLT.destroy(vert) - } + const verts = body.triangleMesh?.mesh?.verts + if (!verts) return + + for (let i = 0; i < verts.length; i += 3) { + const vert = MirabufFloatArr_JoltVec3(verts, i) + points.push_back(vert) + this.UpdateMinMaxBounds(vert, min, max) + JOLT.destroy(vert) } }) @@ -785,7 +776,7 @@ class PhysicsSystem extends WorldSystem { */ private CreateConcaveShapeSettingsFromPart( partDefinition: mirabuf.IPartDefinition - ): [Jolt.ShapeSettings, Jolt.Vec3, Jolt.Vec3] | undefined | null { + ): [Jolt.ShapeSettings, Jolt.Vec3, Jolt.Vec3] | undefined { const settings = new JOLT.MeshShapeSettings() settings.mMaxTrianglesPerLeaf = 8 From c9c0e563a1f761d2f735d4546d1edd367d0a67f4 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Mon, 19 Aug 2024 11:55:41 -0700 Subject: [PATCH 05/29] small refactors to parsing --- fission/src/mirabuf/MirabufParser.ts | 94 +++++++++++--------- fission/src/systems/physics/PhysicsSystem.ts | 22 +++-- 2 files changed, 62 insertions(+), 54 deletions(-) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 610e58f0d0..7fedf40f17 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -84,9 +84,9 @@ class MirabufParser { this.LoadGlobalTransforms() function traverseTree(nodes: mirabuf.INode[], op: (node: mirabuf.INode) => void) { - nodes.forEach(x => { - if (x.children) traverseTree(x.children, op) - op(x) + nodes.forEach(node => { + if (node.children) traverseTree(node.children, op) + op(node) }) } @@ -95,7 +95,7 @@ class MirabufParser { // 1: Initial RigidGroups from ancestral breaks in joints const jointInstanceKeys = Object.keys(assembly.data!.joints!.jointInstances!) as string[] jointInstanceKeys.forEach(key => { - if (key == GROUNDED_JOINT_ID) return + if (key === GROUNDED_JOINT_ID) return const jInst = assembly.data!.joints!.jointInstances![key] const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) @@ -110,28 +110,7 @@ class MirabufParser { // Fields Only: Assign Game Piece rigid nodes if (!assembly.dynamic) { - // Collect all definitions labeled as gamepieces (dynamic = true) - const gamepieceDefinitions: Set = new Set() - - Object.values(assembly.data!.parts!.partDefinitions!).forEach((def: mirabuf.IPartDefinition) => { - if (def.dynamic) gamepieceDefinitions.add(def.info!.GUID!) - }) - - // Create gamepiece rigid nodes from PartInstances with corresponding definitions - Object.values(assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { - if (!gamepieceDefinitions.has(inst.partDefinitionReference!)) return - - const instNode = this.BinarySearchDesignTree(inst.info!.GUID!) - if (!instNode) { - this._errors.push([ParseErrorSeverity.LikelyIssues, "Failed to find Game piece in Design Tree"]) - return - } - - const gpRn = this.NewRigidNode(GAMEPIECE_SUFFIX) - gpRn.isGamePiece = true - this.MovePartToRigidNode(instNode!.value!, gpRn) - instNode.children && traverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) - }) + this.AssignGamePieceRigidNodes(assembly, traverseTree) } // 2: Grounded joint @@ -156,11 +135,8 @@ class MirabufParser { let rn: RigidNode | null = null rg.occurrences!.forEach(y => { const currentRn = this._partToNodeMap.get(y)! - if (!rn) { - rn = currentRn - } else if (currentRn.id != rn.id) { - rn = this.MergeRigidNodes(currentRn, rn) - } + + rn = !rn ? currentRn : currentRn.id != rn.id ? this.MergeRigidNodes(currentRn, rn) : rn }) }) @@ -177,6 +153,7 @@ class MirabufParser { // 7. Update root RigidNode const rootNode = this._partToNodeMap.get(gInst.parts!.nodes!.at(0)!.value!) + if (rootNode) { rootNode.isRoot = true this._rootNode = rootNode.id @@ -184,7 +161,47 @@ class MirabufParser { this._rootNode = this._rigidNodes[0].id } - // 8. Generate Rigid Node Graph + this._directedGraph = this.GenerateRigidNodeGraph(assembly, rootNode) + + // Transition: GH-1014 + const partDefinitions: { [k: string]: mirabuf.IPartDefinition } | null | undefined = + this.assembly.data?.parts?.partDefinitions + + if (!partDefinitions) { + console.log("Failed to get part definitions") + return + } + } + + private AssignGamePieceRigidNodes( + assembly: mirabuf.Assembly, + traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void + ) { + // Collect all definitions labeled as gamepieces (dynamic = true) + const gamepieceDefinitions: Set = new Set() + + Object.values(assembly.data!.parts!.partDefinitions!).forEach((def: mirabuf.IPartDefinition) => { + if (def.dynamic) gamepieceDefinitions.add(def.info!.GUID!) + }) + + // Create gamepiece rigid nodes from PartInstances with corresponding definitions + Object.values(assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { + if (!gamepieceDefinitions.has(inst.partDefinitionReference!)) return + + const instNode = this.BinarySearchDesignTree(inst.info!.GUID!) + if (!instNode) { + this._errors.push([ParseErrorSeverity.LikelyIssues, "Failed to find Game piece in Design Tree"]) + return + } + + const gpRn = this.NewRigidNode(GAMEPIECE_SUFFIX) + gpRn.isGamePiece = true + this.MovePartToRigidNode(instNode!.value!, gpRn) + if (instNode.children) traverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) + }) + } + + private GenerateRigidNodeGraph(assembly: mirabuf.Assembly, rootNode: RigidNode | undefined): Graph { // Build undirected graph const graph = new Graph() graph.AddNode(rootNode ? rootNode.id : this._rigidNodes[0].id) @@ -198,6 +215,7 @@ class MirabufParser { graph.AddNode(rB.id) graph.AddEdgeUndirected(rA.id, rB.id) }) + const directedGraph = new Graph() const whiteGreyBlackMap = new Map() this._rigidNodes.forEach(x => { @@ -220,15 +238,7 @@ class MirabufParser { whiteGreyBlackMap.delete(node) directedRecursive(node) - this._directedGraph = directedGraph - - // Transition: GH-1014 - const partDefinitions: { [k: string]: mirabuf.IPartDefinition } | null | undefined = - this.assembly.data?.parts?.partDefinitions - if (!partDefinitions) { - console.log("Failed to get part definitions") - return - } + return directedGraph } private NewRigidNode(suffix?: string): RigidNode { @@ -376,7 +386,7 @@ class MirabufParser { let nextValue = 0 const partTreeValues = new Map() - const recursive = (partNode: mirabuf.INode) => { + function recursive(partNode: mirabuf.INode) { partNode.children = partNode.children?.filter(x => x.value != null) partNode.children?.forEach(x => recursive(x)) partTreeValues.set(partNode.value!, nextValue++) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 3ad3290af5..4feb6d615d 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -182,7 +182,7 @@ class PhysicsSystem extends WorldSystem { } /** - * Enabing physics for a single body + * Enables physics for a single body * * @param bodyId */ @@ -553,14 +553,10 @@ class PhysicsSystem extends WorldSystem { const rotationalFreedom = jointDefinition.rotational!.rotationalFreedom! - const miraAxis = rotationalFreedom.axis! as mirabuf.Vector3 - let axis: Jolt.Vec3 // No scaling, these are unit vectors - if (versionNum < 5) { - axis = new JOLT.Vec3(miraAxis.x ? -miraAxis.x : 0, miraAxis.y ?? 0, miraAxis.z ?? 0) - } else { - axis = new JOLT.Vec3(miraAxis.x ?? 0, miraAxis.y ?? 0, miraAxis.z ?? 0) - } + const miraAxis = rotationalFreedom.axis! as mirabuf.Vector3 + const miraAxisX: number = (versionNum < 5 ? -miraAxis.x : miraAxis.x) ?? 0 + const axis: Jolt.Vec3 = new JOLT.Vec3(miraAxisX, miraAxis.y ?? 0, miraAxis.z ?? 0) const bounds = bodyWheel.GetShape().GetLocalBounds() const radius = (bounds.mMax.GetY() - bounds.mMin.GetY()) / 2.0 @@ -606,11 +602,12 @@ class PhysicsSystem extends WorldSystem { return [fixedConstraint, vehicleConstraint, listener] } - private IsWheel(jDef: mirabuf.joint.Joint) { + private IsWheel(jDef: mirabuf.joint.Joint): boolean { return ( - jDef.info!.name! != "grounded" && - jDef.userData && - (new Map(Object.entries(jDef.userData.data!)).get("wheel") ?? "false") == "true" + (jDef.info?.name !== "grounded" && + jDef.userData?.data && + (jDef.userData.data["wheel"] ?? "false") === "true") ?? + false ) } @@ -794,6 +791,7 @@ class PhysicsSystem extends WorldSystem { const vertArr = body.triangleMesh?.mesh?.verts const indexArr = body.triangleMesh?.mesh?.indices if (!vertArr || !indexArr) return + for (let i = 0; i < vertArr.length; i += 3) { const vert = MirabufFloatArr_JoltFloat3(vertArr, i) settings.mTriangleVertices.push_back(vert) From 2a3fa7227907ae8497e2065052faa2985d7a1eec Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Mon, 19 Aug 2024 13:59:41 -0700 Subject: [PATCH 06/29] make eslint not complain --- fission/src/mirabuf/MirabufParser.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 7fedf40f17..2d0ecd6ea5 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -124,7 +124,10 @@ class MirabufParser { const traverseNodeRoundup = (node: mirabuf.INode, parentNode: RigidNode) => { const currentNode = this._partToNodeMap.get(node.value!) if (!currentNode) this.MovePartToRigidNode(node.value!, parentNode) - ;(node.children ?? []).forEach(x => traverseNodeRoundup(x, currentNode ?? parentNode)) + + // Eslint complains about the semicolon added at the begining of the line if you inline this variable + const children = node.children ?? [] + children.forEach(x => traverseNodeRoundup(x, currentNode ?? parentNode)) } this._designHierarchyRoot.children?.forEach(x => traverseNodeRoundup(x, gNode)) @@ -218,9 +221,9 @@ class MirabufParser { const directedGraph = new Graph() const whiteGreyBlackMap = new Map() - this._rigidNodes.forEach(x => { - whiteGreyBlackMap.set(x.id, false) - directedGraph.AddNode(x.id) + this._rigidNodes.forEach(node => { + whiteGreyBlackMap.set(node.id, false) + directedGraph.AddNode(node.id) }) function directedRecursive(node: string) { From a150a1cbb049db6a538a867220070c9d1cc0148a Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Mon, 19 Aug 2024 14:15:13 -0700 Subject: [PATCH 07/29] fix build and lint --- fission/src/mirabuf/MirabufInstance.ts | 4 +--- fission/src/systems/physics/PhysicsSystem.ts | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 6b65dbe037..49cd9df49e 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -89,11 +89,9 @@ const transformGeometry = (geometry: THREE.BufferGeometry, mesh: mirabuf.IMesh) geometry.setIndex(mesh.indices!) } -type FrictionCoefficients = { dyn: number; stat: number } - class MirabufInstance { private _mirabufParser: MirabufParser - private _materials: Map + private _materials: Map private _meshes: Map> private _batches: Array diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 63cba1cf5a..471100480f 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -356,7 +356,7 @@ class PhysicsSystem extends WorldSystem { let listener: Jolt.PhysicsStepListener | undefined = undefined - function addConstraint(c: Jolt.Constraint): void { + const addConstraint = (c: Jolt.Constraint): void => { mechanism.AddConstraint({ parentBody: bodyIdA!, childBody: bodyIdB!, From dc6bf6a2fffb200174588f0565c1314bf9940706 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Tue, 20 Aug 2024 11:10:47 -0700 Subject: [PATCH 08/29] more extraction refactoring in MirabufParser constructor --- fission/src/mirabuf/MirabufParser.ts | 85 +++++++++++++--------------- 1 file changed, 39 insertions(+), 46 deletions(-) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 2d0ecd6ea5..84e47a40b0 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -90,28 +90,10 @@ class MirabufParser { }) } - // const materials = assembly.data?.materials?.physicalMaterials - - // 1: Initial RigidGroups from ancestral breaks in joints - const jointInstanceKeys = Object.keys(assembly.data!.joints!.jointInstances!) as string[] - jointInstanceKeys.forEach(key => { - if (key === GROUNDED_JOINT_ID) return - - const jInst = assembly.data!.joints!.jointInstances![key] - const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) - const parentRN = this.NewRigidNode() - - this.MovePartToRigidNode(ancestorA, parentRN) - this.MovePartToRigidNode(ancestorB, this.NewRigidNode()) - - if (jInst.parts && jInst.parts.nodes) - traverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) - }) + this.InitializeRigidGroups(assembly, traverseTree) // 1: from ancestral breaks in joints // Fields Only: Assign Game Piece rigid nodes - if (!assembly.dynamic) { - this.AssignGamePieceRigidNodes(assembly, traverseTree) - } + if (!assembly.dynamic) this.AssignGamePieceRigidNodes(assembly, traverseTree) // 2: Grounded joint const gInst = assembly.data!.joints!.jointInstances![GROUNDED_JOINT_ID] @@ -133,16 +115,7 @@ class MirabufParser { // this.DebugPrintHierarchy(1, ...this._designHierarchyRoot.children!); - // 4: Bandage via RigidGroups - assembly.data!.joints!.rigidGroups!.forEach(rg => { - let rn: RigidNode | null = null - rg.occurrences!.forEach(y => { - const currentRn = this._partToNodeMap.get(y)! - - rn = !rn ? currentRn : currentRn.id != rn.id ? this.MergeRigidNodes(currentRn, rn) : rn - }) - }) - + this.BandageRigidNodes(assembly) // 4: Bandage via RigidGroups // this.DebugPrintHierarchy(1, ...this._designHierarchyRoot.children!); // 5. Remove Empty RNs @@ -150,32 +123,41 @@ class MirabufParser { // 6. If field, find grounded node and set isDynamic to false. Also just find grounded node again this._groundedNode = this.partToNodeMap.get(gInst.parts!.nodes!.at(0)!.value!) - if (!assembly.dynamic && this._groundedNode) { - this._groundedNode.isDynamic = false - } + if (!assembly.dynamic && this._groundedNode) this._groundedNode.isDynamic = false // 7. Update root RigidNode const rootNode = this._partToNodeMap.get(gInst.parts!.nodes!.at(0)!.value!) - - if (rootNode) { - rootNode.isRoot = true - this._rootNode = rootNode.id - } else { - this._rootNode = this._rigidNodes[0].id - } + this._rootNode = rootNode?.id ?? this._rigidNodes[0].id + rootNode!.isRoot = true this._directedGraph = this.GenerateRigidNodeGraph(assembly, rootNode) - // Transition: GH-1014 - const partDefinitions: { [k: string]: mirabuf.IPartDefinition } | null | undefined = - this.assembly.data?.parts?.partDefinitions - - if (!partDefinitions) { - console.log("Failed to get part definitions") + if (!this.assembly.data?.parts?.partDefinitions) { + console.warn("Failed to get part definitions") return } } + private InitializeRigidGroups( + assembly: mirabuf.Assembly, + traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void + ) { + const jointInstanceKeys = Object.keys(assembly.data!.joints!.jointInstances!) as string[] + jointInstanceKeys.forEach(key => { + if (key === GROUNDED_JOINT_ID) return + + const jInst = assembly.data!.joints!.jointInstances![key] + const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) + const parentRN = this.NewRigidNode() + + this.MovePartToRigidNode(ancestorA, parentRN) + this.MovePartToRigidNode(ancestorB, this.NewRigidNode()) + + if (jInst.parts && jInst.parts.nodes) + traverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) + }) + } + private AssignGamePieceRigidNodes( assembly: mirabuf.Assembly, traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void @@ -204,6 +186,17 @@ class MirabufParser { }) } + private BandageRigidNodes(assembly: mirabuf.Assembly) { + assembly.data!.joints!.rigidGroups!.forEach(rg => { + let rn: RigidNode | null = null + rg.occurrences!.forEach(y => { + const currentRn = this._partToNodeMap.get(y)! + + rn = !rn ? currentRn : currentRn.id != rn.id ? this.MergeRigidNodes(currentRn, rn) : rn + }) + }) + } + private GenerateRigidNodeGraph(assembly: mirabuf.Assembly, rootNode: RigidNode | undefined): Graph { // Build undirected graph const graph = new Graph() From 102f164a5e966ca5284740881a5d54f6b3eaa13e Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Tue, 20 Aug 2024 15:29:40 -0700 Subject: [PATCH 09/29] more refactors :) --- fission/src/mirabuf/MirabufParser.ts | 55 +++-- fission/src/systems/physics/PhysicsSystem.ts | 215 +++++++------------ 2 files changed, 107 insertions(+), 163 deletions(-) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 84e47a40b0..471b022aa3 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -107,9 +107,8 @@ class MirabufParser { const currentNode = this._partToNodeMap.get(node.value!) if (!currentNode) this.MovePartToRigidNode(node.value!, parentNode) - // Eslint complains about the semicolon added at the begining of the line if you inline this variable - const children = node.children ?? [] - children.forEach(x => traverseNodeRoundup(x, currentNode ?? parentNode)) + if (!node.children) return + node.children.forEach(x => traverseNodeRoundup(x, currentNode ?? parentNode)) } this._designHierarchyRoot.children?.forEach(x => traverseNodeRoundup(x, gNode)) @@ -126,11 +125,10 @@ class MirabufParser { if (!assembly.dynamic && this._groundedNode) this._groundedNode.isDynamic = false // 7. Update root RigidNode - const rootNode = this._partToNodeMap.get(gInst.parts!.nodes!.at(0)!.value!) - this._rootNode = rootNode?.id ?? this._rigidNodes[0].id - rootNode!.isRoot = true + const rootNodeId = this._partToNodeMap.get(gInst.parts!.nodes!.at(0)!.value!)?.id ?? this._rigidNodes[0].id + this._rootNode = rootNodeId - this._directedGraph = this.GenerateRigidNodeGraph(assembly, rootNode) + this._directedGraph = this.GenerateRigidNodeGraph(assembly, rootNodeId) if (!this.assembly.data?.parts?.partDefinitions) { console.warn("Failed to get part definitions") @@ -163,11 +161,13 @@ class MirabufParser { traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void ) { // Collect all definitions labeled as gamepieces (dynamic = true) - const gamepieceDefinitions: Set = new Set() - - Object.values(assembly.data!.parts!.partDefinitions!).forEach((def: mirabuf.IPartDefinition) => { - if (def.dynamic) gamepieceDefinitions.add(def.info!.GUID!) - }) + const gamepieceDefinitions: Set = new Set( + Object.values(assembly.data!.parts!.partDefinitions!) + .filter(def => !def.dynamic) + .map((def: mirabuf.IPartDefinition) => { + return def.info!.GUID! + }) + ) // Create gamepiece rigid nodes from PartInstances with corresponding definitions Object.values(assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { @@ -197,10 +197,10 @@ class MirabufParser { }) } - private GenerateRigidNodeGraph(assembly: mirabuf.Assembly, rootNode: RigidNode | undefined): Graph { + private GenerateRigidNodeGraph(assembly: mirabuf.Assembly, rootNodeId: string): Graph { // Build undirected graph const graph = new Graph() - graph.AddNode(rootNode ? rootNode.id : this._rigidNodes[0].id) + graph.AddNode(rootNodeId) const jointInstances = Object.values(assembly.data!.joints!.jointInstances!) as mirabuf.joint.JointInstance[] jointInstances.forEach((x: mirabuf.joint.JointInstance) => { const rA = this._partToNodeMap.get(x.parentPart) @@ -220,19 +220,18 @@ class MirabufParser { }) function directedRecursive(node: string) { - graph.GetAdjacencyList(node).forEach(x => { - if (!whiteGreyBlackMap.has(x)) return - - directedGraph.AddEdgeDirected(node, x) - whiteGreyBlackMap.delete(x) - directedRecursive(x) - }) + graph + .GetAdjacencyList(node) + .filter(x => whiteGreyBlackMap.has(x)) + .forEach(x => { + directedGraph.AddEdgeDirected(node, x) + whiteGreyBlackMap.delete(x) + directedRecursive(x) + }) } - const node = rootNode?.id ?? this._rigidNodes[0].id - - whiteGreyBlackMap.delete(node) - directedRecursive(node) + whiteGreyBlackMap.delete(rootNodeId) + directedRecursive(rootNodeId) return directedGraph } @@ -402,7 +401,6 @@ class MirabufParser { * Collection of mirabuf parts that are bound together */ class RigidNode { - public isRoot: boolean public id: RigidNodeId public parts: Set = new Set() public isDynamic: boolean @@ -411,7 +409,6 @@ class RigidNode { public constructor(id: RigidNodeId, isDynamic?: boolean, isGamePiece?: boolean) { this.id = id this.isDynamic = isDynamic ?? true - this.isRoot = false this.isGamePiece = isGamePiece ?? false } } @@ -431,10 +428,6 @@ export class RigidNodeReadOnly { return this._original.isDynamic } - public get isRoot(): boolean { - return this._original.isRoot - } - public get isGamePiece(): boolean { return this._original.isGamePiece } diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 471100480f..a92cb1524c 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -165,9 +165,7 @@ class PhysicsSystem extends WorldSystem { * The pause works off of a request counter. */ public ReleasePause() { - if (this._pauseCounter > 0) { - this._pauseCounter-- - } + if (this._pauseCounter > 0) this._pauseCounter-- } /** @@ -176,9 +174,7 @@ class PhysicsSystem extends WorldSystem { * @param bodyId */ public DisablePhysicsForBody(bodyId: Jolt.BodyID) { - if (!this.IsBodyAdded(bodyId)) { - return - } + if (!this.IsBodyAdded(bodyId)) return this._joltBodyInterface.DeactivateBody(bodyId) @@ -191,9 +187,7 @@ class PhysicsSystem extends WorldSystem { * @param bodyId */ public EnablePhysicsForBody(bodyId: Jolt.BodyID) { - if (!this.IsBodyAdded(bodyId)) { - return - } + if (!this.IsBodyAdded(bodyId)) return this._joltBodyInterface.ActivateBody(bodyId) this.GetBody(bodyId).SetIsSensor(false) @@ -232,9 +226,8 @@ class PhysicsSystem extends WorldSystem { mass ? JOLT.EMotionType_Dynamic : JOLT.EMotionType_Static, mass ? LAYER_GENERAL_DYNAMIC : LAYER_FIELD ) - if (mass) { - creationSettings.mMassPropertiesOverride.mMass = mass - } + if (mass) creationSettings.mMassPropertiesOverride.mMass = mass + const body = this._joltBodyInterface.CreateBody(creationSettings) JOLT.destroy(pos) JOLT.destroy(rot) @@ -268,9 +261,8 @@ class PhysicsSystem extends WorldSystem { mass ? JOLT.EMotionType_Dynamic : JOLT.EMotionType_Static, mass ? LAYER_GENERAL_DYNAMIC : LAYER_FIELD ) - if (mass) { - creationSettings.mMassPropertiesOverride.mMass = mass - } + if (mass) creationSettings.mMassPropertiesOverride.mMass = mass + const body = this._joltBodyInterface.CreateBody(creationSettings) JOLT.destroy(pos) JOLT.destroy(rot) @@ -295,9 +287,8 @@ class PhysicsSystem extends WorldSystem { * @returns Resulting shape. */ public CreateConvexHull(points: Float32Array, density: number = 1.0): Jolt.ShapeResult { - if (points.length % 3) { - throw new Error(`Invalid size of points: ${points.length}`) - } + if (points.length % 3) throw new Error(`Invalid size of points: ${points.length}`) + const settings = new JOLT.ConvexHullShapeSettings() settings.mPoints.clear() settings.mPoints.reserve(points.length / 3.0) @@ -325,23 +316,21 @@ class PhysicsSystem extends WorldSystem { */ public CreateJointsFromParser(parser: MirabufParser, mechanism: Mechanism) { const jointData = parser.assembly.data!.joints! - for (const [jGuid, jInst] of Object.entries(jointData.jointInstances!) as [ - string, - mirabuf.joint.JointInstance, - ][]) { - if (jGuid == GROUNDED_JOINT_ID) continue + const joints = Object.entries(jointData.jointInstances!) as [string, mirabuf.joint.JointInstance][] + joints.forEach(([jGuid, jInst]) => { + if (jGuid == GROUNDED_JOINT_ID) return const rnA = parser.partToNodeMap.get(jInst.parentPart!) const rnB = parser.partToNodeMap.get(jInst.childPart!) if (!rnA || !rnB) { console.warn(`Skipping joint '${jInst.info!.name!}'. Couldn't find associated rigid nodes.`) - continue + return } else if (rnA.id == rnB.id) { console.warn( `Skipping joint '${jInst.info!.name!}'. Jointing the same parts. Likely in issue with Fusion Design structure.` ) - continue + return } const jDef = parser.assembly.data!.joints!.jointDefinitions![jInst.jointReference!]! as mirabuf.joint.Joint @@ -349,13 +338,11 @@ class PhysicsSystem extends WorldSystem { const bodyIdB = mechanism.GetBodyByNodeId(rnB.id) if (!bodyIdA || !bodyIdB) { console.warn(`Skipping joint '${jInst.info!.name!}'. Failed to find rigid nodes' associated bodies.`) - continue + return } const bodyA = this.GetBody(bodyIdA) const bodyB = this.GetBody(bodyIdB) - let listener: Jolt.PhysicsStepListener | undefined = undefined - const addConstraint = (c: Jolt.Constraint): void => { mechanism.AddConstraint({ parentBody: bodyIdA!, @@ -380,45 +367,11 @@ class PhysicsSystem extends WorldSystem { maxForce = miraMotor.simpleMotor.stallTorque } + let listener: Jolt.PhysicsStepListener | null = null + switch (jDef.jointMotionType!) { case mirabuf.joint.JointMotion.REVOLUTE: - if (this.IsWheel(jDef)) { - const prefVel = PreferencesSystem.getRobotPreferences( - parser.assembly.info?.name ?? "" - ).driveVelocity - if (prefVel > 0) maxVel = prefVel - - const prefAcc = PreferencesSystem.getRobotPreferences( - parser.assembly.info?.name ?? "" - ).driveAcceleration - if (prefAcc > 0) maxForce = prefAcc - - if (parser.directedGraph.GetAdjacencyList(rnA.id).length > 0) { - const res = this.CreateWheelConstraint( - jInst, - jDef, - maxForce ?? 1.5, - bodyA, - bodyB, - parser.assembly.info!.version! - ) - addConstraint(res[0]) - addConstraint(res[1]) - listener = res[2] - } else { - const res = this.CreateWheelConstraint( - jInst, - jDef, - maxForce ?? 1.5, - bodyB, - bodyA, - parser.assembly.info!.version! - ) - addConstraint(res[0]) - addConstraint(res[1]) - listener = res[2] - } - } else { + if (!this.IsWheel(jDef)) { addConstraint( this.CreateHingeConstraint( jInst, @@ -429,7 +382,28 @@ class PhysicsSystem extends WorldSystem { parser.assembly.info!.version! ) ) + + break } + + const preferences = PreferencesSystem.getRobotPreferences(parser.assembly.info?.name ?? "") + maxVel = preferences.driveVelocity > 0 ? preferences.driveVelocity : maxVel + maxForce = preferences.driveAcceleration > 0 ? preferences.driveAcceleration : maxForce + + const [bodyOne, bodyTwo] = + parser.directedGraph.GetAdjacencyList(rnA.id).length > 0 ? [bodyA, bodyB] : [bodyB, bodyA] + + const res = this.CreateWheelConstraint( + jInst, + jDef, + maxForce ?? 1.5, + bodyOne, + bodyTwo, + parser.assembly.info!.version! + ) + addConstraint(res[0]) + addConstraint(res[1]) + listener = res[2] break case mirabuf.joint.JointMotion.SLIDER: addConstraint(this.CreateSliderConstraint(jInst, jDef, maxForce ?? 200, bodyA, bodyB)) @@ -439,10 +413,8 @@ class PhysicsSystem extends WorldSystem { break } - if (listener) { - mechanism.AddStepListener(listener) - } - } + if (listener) mechanism.AddStepListener(listener) + }) } /** @@ -480,13 +452,10 @@ class PhysicsSystem extends WorldSystem { const rotationalFreedom = jointDefinition.rotational!.rotationalFreedom! const miraAxis = rotationalFreedom.axis! as mirabuf.Vector3 - let axis: Jolt.Vec3 // No scaling, these are unit vectors - if (versionNum < 5) { - axis = new JOLT.Vec3(miraAxis.x ? -miraAxis.x : 0, miraAxis.y ?? 0, miraAxis.z! ?? 0) - } else { - axis = new JOLT.Vec3(miraAxis.x! ?? 0, miraAxis.y! ?? 0, miraAxis.z! ?? 0) - } + const miraAxisX = (versionNum < 5 ? -miraAxis.x : miraAxis.x) ?? 0 + const axis = new JOLT.Vec3(miraAxisX, miraAxis.y! ?? 0, miraAxis.z! ?? 0) + hingeConstraintSettings.mHingeAxis1 = hingeConstraintSettings.mHingeAxis2 = axis.Normalized() hingeConstraintSettings.mNormalAxis1 = hingeConstraintSettings.mNormalAxis2 = getPerpendicular( hingeConstraintSettings.mHingeAxis1 @@ -636,7 +605,7 @@ class PhysicsSystem extends WorldSystem { // Other than maxTorque, these controller settings are not being used as of now // because ArcadeDriveBehavior goes directly to the WheelDrivers. - // MaxTorque is only used as communication for WheelDriver to get maxAcceleration + // maxTorque is only used as communication for WheelDriver to get maxAcceleration const controllerSettings = new JOLT.WheeledVehicleControllerSettings() controllerSettings.mEngine.mMaxTorque = maxAcc controllerSettings.mTransmission.mClutchStrength = 10.0 @@ -664,12 +633,7 @@ class PhysicsSystem extends WorldSystem { } private IsWheel(jDef: mirabuf.joint.Joint): boolean { - return ( - (jDef.info?.name !== "grounded" && - jDef.userData?.data && - (jDef.userData.data["wheel"] ?? "false") === "true") ?? - false - ) + return (jDef.info?.name !== "grounded" && (jDef.userData?.data?.wheel ?? "false") === "true") ?? false } /** @@ -778,9 +742,6 @@ class PhysicsSystem extends WorldSystem { // Little testing components this._bodies.push(body.GetID()) body.SetRestitution(0.4) - - if (!frictionOverride) return - body.SetFriction(frictionOverride) } // Cleanup JOLT.destroy(compoundShapeSettings) @@ -821,9 +782,9 @@ class PhysicsSystem extends WorldSystem { JOLT.destroy(min) JOLT.destroy(max) return - } else { - return [settings, min, max] } + + return [settings, min, max] } /** @@ -871,10 +832,10 @@ class PhysicsSystem extends WorldSystem { JOLT.destroy(min) JOLT.destroy(max) return - } else { - settings.Sanitize() - return [settings, min, max] } + + settings.Sanitize() + return [settings, min, max] } /** @@ -901,12 +862,10 @@ class PhysicsSystem extends WorldSystem { .GetNarrowPhaseQuery() .CastRay(ray, raySettings, collector, bp_filter, object_filter, body_filter, shape_filter) - if (collector.HadHit()) { - const hitPoint = ray.GetPointOnRay(collector.mHit.mFraction) - return { data: collector.mHit, point: hitPoint, ray: ray } - } + if (collector.HadHit()) return undefined - return undefined + const hitPoint = ray.GetPointOnRay(collector.mHit.mFraction) + return { data: collector.mHit, point: hitPoint, ray: ray } } /** @@ -929,7 +888,7 @@ class PhysicsSystem extends WorldSystem { /** * Destroys bodies. * - * @param bodies Bodies to destroy. + * @param bodies Bodies to destroy. */ public DestroyBodies(...bodies: Jolt.Body[]) { bodies.forEach(x => { @@ -963,9 +922,7 @@ class PhysicsSystem extends WorldSystem { } public Update(deltaT: number): void { - if (this._pauseCounter > 0) { - return - } + if (this._pauseCounter > 0) return const diffDeltaT = deltaT - lastDeltaT @@ -981,7 +938,10 @@ class PhysicsSystem extends WorldSystem { this._physicsEventQueue = [] } - public Destroy(): void { + /* + * Destroys PhysicsSystem and frees all objects + */ + public Destroy() { this._constraints.forEach(x => { this._joltPhysSystem.RemoveConstraint(x) // JOLT.destroy(x); @@ -1051,9 +1011,7 @@ class PhysicsSystem extends WorldSystem { * @param position The new position of the body */ public SetBodyPosition(id: Jolt.BodyID, position: Jolt.Vec3, activate: boolean = true): void { - if (!this.IsBodyAdded(id)) { - return - } + if (!this.IsBodyAdded(id)) return this._joltBodyInterface.SetPosition( id, @@ -1063,9 +1021,7 @@ class PhysicsSystem extends WorldSystem { } public SetBodyRotation(id: Jolt.BodyID, rotation: Jolt.Quat, activate: boolean = true): void { - if (!this.IsBodyAdded(id)) { - return - } + if (!this.IsBodyAdded(id)) return this._joltBodyInterface.SetRotation( id, @@ -1089,9 +1045,7 @@ class PhysicsSystem extends WorldSystem { massProperties: boolean, activationMode: Jolt.EActivation ): void { - if (!this.IsBodyAdded(id)) { - return - } + if (!this.IsBodyAdded(id)) return this._joltBodyInterface.SetShape(id, shape, massProperties, activationMode) } @@ -1181,10 +1135,10 @@ export class LayerReserve { } public Release(): void { - if (!this._isReleased) { - RobotLayers.push(this._layer) - this._isReleased = true - } + if (this._isReleased) return + + RobotLayers.push(this._layer) + this._isReleased = true } } @@ -1199,25 +1153,24 @@ function SetupCollisionFiltering(settings: Jolt.JoltSettings) { // Enable Field layer collisions objectFilter.EnableCollision(LAYER_GENERAL_DYNAMIC, LAYER_GENERAL_DYNAMIC) objectFilter.EnableCollision(LAYER_FIELD, LAYER_GENERAL_DYNAMIC) - for (let i = 0; i < RobotLayers.length; i++) { - objectFilter.EnableCollision(LAYER_FIELD, RobotLayers[i]) - objectFilter.EnableCollision(LAYER_GENERAL_DYNAMIC, RobotLayers[i]) - } + RobotLayers.forEach(layer => { + objectFilter.EnableCollision(LAYER_FIELD, layer) + objectFilter.EnableCollision(LAYER_GENERAL_DYNAMIC, layer) + }) // Enable Collisions between other robots - for (let i = 0; i < RobotLayers.length - 1; i++) { - for (let j = i + 1; j < RobotLayers.length; j++) { - objectFilter.EnableCollision(RobotLayers[i], RobotLayers[j]) - } - } + RobotLayers.forEach(layerOne => { + RobotLayers.forEach(layerTwo => { + objectFilter.EnableCollision(layerOne, layerTwo) + }) + }) const BP_LAYER_FIELD = new JOLT.BroadPhaseLayer(LAYER_FIELD) const BP_LAYER_GENERAL_DYNAMIC = new JOLT.BroadPhaseLayer(LAYER_GENERAL_DYNAMIC) - const bpRobotLayers = new Array(RobotLayers.length) - for (let i = 0; i < bpRobotLayers.length; i++) { - bpRobotLayers[i] = new JOLT.BroadPhaseLayer(RobotLayers[i]) - } + const bpRobotLayers = new Array(RobotLayers.length).map( + (_, idx) => new JOLT.BroadPhaseLayer(idx) + ) const COUNT_BROAD_PHASE_LAYERS = 2 + RobotLayers.length @@ -1225,9 +1178,9 @@ function SetupCollisionFiltering(settings: Jolt.JoltSettings) { bpInterface.MapObjectToBroadPhaseLayer(LAYER_FIELD, BP_LAYER_FIELD) bpInterface.MapObjectToBroadPhaseLayer(LAYER_GENERAL_DYNAMIC, BP_LAYER_GENERAL_DYNAMIC) - for (let i = 0; i < bpRobotLayers.length; i++) { - bpInterface.MapObjectToBroadPhaseLayer(RobotLayers[i], bpRobotLayers[i]) - } + bpRobotLayers.map((bpRobot, i) => { + bpInterface.MapObjectToBroadPhaseLayer(RobotLayers[i], bpRobot) + }) settings.mObjectLayerPairFilter = objectFilter settings.mBroadPhaseLayerInterface = bpInterface @@ -1257,9 +1210,7 @@ function getPerpendicular(vec: Jolt.Vec3): Jolt.Vec3 { } function tryGetPerpendicular(vec: Jolt.Vec3, toCheck: Jolt.Vec3): Jolt.Vec3 | undefined { - if (Math.abs(Math.abs(vec.Dot(toCheck)) - 1.0) < 0.0001) { - return undefined - } + if (Math.abs(Math.abs(vec.Dot(toCheck)) - 1.0) < 0.0001) return undefined const a = vec.Dot(toCheck) return new JOLT.Vec3( From 7f934b3f9c073767e23ac6c8d2d988624231438d Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Tue, 20 Aug 2024 15:32:49 -0700 Subject: [PATCH 10/29] format --- fission/src/systems/physics/PhysicsSystem.ts | 56 ++++++++++---------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index a92cb1524c..b095b24221 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -371,40 +371,42 @@ class PhysicsSystem extends WorldSystem { switch (jDef.jointMotionType!) { case mirabuf.joint.JointMotion.REVOLUTE: - if (!this.IsWheel(jDef)) { - addConstraint( - this.CreateHingeConstraint( - jInst, - jDef, - maxForce ?? 50, - bodyA, - bodyB, - parser.assembly.info!.version! - ) + if (this.IsWheel(jDef)) { + const preferences = PreferencesSystem.getRobotPreferences(parser.assembly.info?.name ?? "") + maxVel = preferences.driveVelocity > 0 ? preferences.driveVelocity : maxVel + maxForce = preferences.driveAcceleration > 0 ? preferences.driveAcceleration : maxForce + + const [bodyOne, bodyTwo] = + parser.directedGraph.GetAdjacencyList(rnA.id).length > 0 ? [bodyA, bodyB] : [bodyB, bodyA] + + const res = this.CreateWheelConstraint( + jInst, + jDef, + maxForce ?? 1.5, + bodyOne, + bodyTwo, + parser.assembly.info!.version! ) + addConstraint(res[0]) + addConstraint(res[1]) + listener = res[2] break } - const preferences = PreferencesSystem.getRobotPreferences(parser.assembly.info?.name ?? "") - maxVel = preferences.driveVelocity > 0 ? preferences.driveVelocity : maxVel - maxForce = preferences.driveAcceleration > 0 ? preferences.driveAcceleration : maxForce - - const [bodyOne, bodyTwo] = - parser.directedGraph.GetAdjacencyList(rnA.id).length > 0 ? [bodyA, bodyB] : [bodyB, bodyA] - - const res = this.CreateWheelConstraint( - jInst, - jDef, - maxForce ?? 1.5, - bodyOne, - bodyTwo, - parser.assembly.info!.version! + addConstraint( + this.CreateHingeConstraint( + jInst, + jDef, + maxForce ?? 50, + bodyA, + bodyB, + parser.assembly.info!.version! + ) ) - addConstraint(res[0]) - addConstraint(res[1]) - listener = res[2] + break + case mirabuf.joint.JointMotion.SLIDER: addConstraint(this.CreateSliderConstraint(jInst, jDef, maxForce ?? 200, bodyA, bodyB)) break From e8d823ba6918cd2b5a6c7cbc6de439bd5b96f7e3 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 10:17:44 -0700 Subject: [PATCH 11/29] fix parsing for non-dynamic assemblies --- fission/package.json | 6 +++--- fission/src/mirabuf/MirabufParser.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/fission/package.json b/fission/package.json index 0643c80a52..812e2255df 100644 --- a/fission/package.json +++ b/fission/package.json @@ -12,11 +12,11 @@ "test": "vitest", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives", "lint:fix": "eslint . --ext ts,tsx --report-unused-disable-directives --fix", - "prettier": "bun x prettier src --check || npx prettier src --check", - "prettier:fix": "bun x prettier src --write || npx prettier src --write", + "prettier": "(bun x prettier src --check) || (npx prettier src --check)", + "prettier:fix": "(bun x prettier src --write) || (npx prettier src --write)", "format": "(bun run prettier:fix && bun run lint:fix) || (npm run prettier:fix && npm run lint:fix)", "assetpack": "curl -o public/assetpack.zip https://synthesis.autodesk.com/Downloadables/assetpack.zip && tar -xf public/assetpack.zip -C public/", - "playwright:install": "bun x playwright install || npx playwright install" + "playwright:install": "(bun x playwright install || npx playwright install)" }, "dependencies": { "@barclah/jolt-physics": "^0.24.1", diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 471b022aa3..b92166dfb2 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -163,7 +163,7 @@ class MirabufParser { // Collect all definitions labeled as gamepieces (dynamic = true) const gamepieceDefinitions: Set = new Set( Object.values(assembly.data!.parts!.partDefinitions!) - .filter(def => !def.dynamic) + .filter(def => def.dynamic) .map((def: mirabuf.IPartDefinition) => { return def.info!.GUID! }) From 5b9e451346b832bfd6218ab56f580b9273651700 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 14:13:44 -0700 Subject: [PATCH 12/29] fix raycasting --- fission/src/systems/physics/PhysicsSystem.ts | 30 +++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index b095b24221..f54b427db8 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -343,15 +343,6 @@ class PhysicsSystem extends WorldSystem { const bodyA = this.GetBody(bodyIdA) const bodyB = this.GetBody(bodyIdB) - const addConstraint = (c: Jolt.Constraint): void => { - mechanism.AddConstraint({ - parentBody: bodyIdA!, - childBody: bodyIdB!, - constraint: c, - maxVelocity: maxVel ?? VELOCITY_DEFAULT, - info: jInst.info ?? undefined, // remove possibility for null - }) - } // Motor velocity and acceleration. Prioritizes preferences then mirabuf. const prefMotors = PreferencesSystem.getRobotPreferences(parser.assembly.info?.name ?? "").motors const prefMotor = prefMotors ? prefMotors.filter(x => x.name == jInst.info?.name) : undefined @@ -369,15 +360,26 @@ class PhysicsSystem extends WorldSystem { let listener: Jolt.PhysicsStepListener | null = null + const addConstraint = (c: Jolt.Constraint): void => { + mechanism.AddConstraint({ + parentBody: bodyIdA!, + childBody: bodyIdB!, + constraint: c, + maxVelocity: maxVel ?? VELOCITY_DEFAULT, + info: jInst.info ?? undefined, + }) + } + switch (jDef.jointMotionType!) { case mirabuf.joint.JointMotion.REVOLUTE: if (this.IsWheel(jDef)) { const preferences = PreferencesSystem.getRobotPreferences(parser.assembly.info?.name ?? "") - maxVel = preferences.driveVelocity > 0 ? preferences.driveVelocity : maxVel - maxForce = preferences.driveAcceleration > 0 ? preferences.driveAcceleration : maxForce + maxVel = preferences.driveVelocity ?? maxVel + maxForce = preferences.driveAcceleration ?? maxForce - const [bodyOne, bodyTwo] = - parser.directedGraph.GetAdjacencyList(rnA.id).length > 0 ? [bodyA, bodyB] : [bodyB, bodyA] + const [bodyOne, bodyTwo] = parser.directedGraph.GetAdjacencyList(rnA.id).length + ? [bodyA, bodyB] + : [bodyB, bodyA] const res = this.CreateWheelConstraint( jInst, @@ -864,7 +866,7 @@ class PhysicsSystem extends WorldSystem { .GetNarrowPhaseQuery() .CastRay(ray, raySettings, collector, bp_filter, object_filter, body_filter, shape_filter) - if (collector.HadHit()) return undefined + if (!collector.HadHit()) return undefined const hitPoint = ray.GetPointOnRay(collector.mHit.mFraction) return { data: collector.mHit, point: hitPoint, ray: ray } From 09aea2c38ffb5f5949b3cde9770f8d5890c56d68 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 14:21:37 -0700 Subject: [PATCH 13/29] fix intense robot shaking --- fission/src/systems/physics/PhysicsSystem.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index f54b427db8..dc1f29944a 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -1163,18 +1163,17 @@ function SetupCollisionFiltering(settings: Jolt.JoltSettings) { }) // Enable Collisions between other robots - RobotLayers.forEach(layerOne => { - RobotLayers.forEach(layerTwo => { - objectFilter.EnableCollision(layerOne, layerTwo) - }) - }) + + for (let i = 0; i < RobotLayers.length - 1; i++) { + for (let j = i + 1; j < RobotLayers.length; j++) { + objectFilter.EnableCollision(RobotLayers[i], RobotLayers[j]) + } + } const BP_LAYER_FIELD = new JOLT.BroadPhaseLayer(LAYER_FIELD) const BP_LAYER_GENERAL_DYNAMIC = new JOLT.BroadPhaseLayer(LAYER_GENERAL_DYNAMIC) - const bpRobotLayers = new Array(RobotLayers.length).map( - (_, idx) => new JOLT.BroadPhaseLayer(idx) - ) + const bpRobotLayers = RobotLayers.map(layer => new JOLT.BroadPhaseLayer(layer)) const COUNT_BROAD_PHASE_LAYERS = 2 + RobotLayers.length From 6af504d12adc264c88955ffae651f10f0651a026 Mon Sep 17 00:00:00 2001 From: Azalea Colburn <62953415+azaleacolburn@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:23:26 -0700 Subject: [PATCH 14/29] Update fission/src/mirabuf/MirabufInstance.ts Co-authored-by: Brandon Pacewic <92102436+BrandonPacewic@users.noreply.github.com> --- fission/src/mirabuf/MirabufInstance.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 49cd9df49e..607343678b 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,11 +128,6 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - Object.entries(this._mirabufParser.assembly.data!.materials!.physicalMaterials!).forEach(([name, material]) => { - const [static_f, dynamic_f] = [material.staticFriction, material.dynamicFriction] - console.log(`${name} - static: ${static_f} dynamic: ${dynamic_f}`) - //this._materials.set() - }) Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!).forEach( ([appearanceId, appearance]) => { const { A, B, G, R } = appearance.albedo ?? {} From c485d5b502174b8bddec12db355b96fe717fed9e Mon Sep 17 00:00:00 2001 From: Azalea Colburn <62953415+azaleacolburn@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:24:20 -0700 Subject: [PATCH 15/29] Update fission/src/systems/physics/PhysicsSystem.ts Co-authored-by: Brandon Pacewic <92102436+BrandonPacewic@users.noreply.github.com> --- fission/src/systems/physics/PhysicsSystem.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index dc1f29944a..f323503e43 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -165,7 +165,7 @@ class PhysicsSystem extends WorldSystem { * The pause works off of a request counter. */ public ReleasePause() { - if (this._pauseCounter > 0) this._pauseCounter-- + if (this._pauseCounter) this._pauseCounter-- } /** From 29000a224c90306aae6cdd124c5d46388947cbcc Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 15:29:16 -0700 Subject: [PATCH 16/29] extracted traverse tree --- fission/src/mirabuf/MirabufInstance.ts | 3 +- fission/src/mirabuf/MirabufParser.ts | 44 +++++++++++--------------- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 49cd9df49e..bbb56d1cf3 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -182,7 +182,8 @@ class MirabufInstance { if (!mesh?.verts || !mesh.normals || !mesh.uv || !mesh.indices) return const appearanceOverride = body.appearanceOverride - const material: THREE.Material = WIREFRAME + + const material = WIREFRAME ? new THREE.MeshStandardMaterial({ wireframe: true, color: 0x000000 }) : appearanceOverride && this._materials.has(appearanceOverride) ? this._materials.get(appearanceOverride)! diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index b92166dfb2..c07cf5cef9 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -83,17 +83,10 @@ class MirabufParser { this.GenerateTreeValues() this.LoadGlobalTransforms() - function traverseTree(nodes: mirabuf.INode[], op: (node: mirabuf.INode) => void) { - nodes.forEach(node => { - if (node.children) traverseTree(node.children, op) - op(node) - }) - } - - this.InitializeRigidGroups(assembly, traverseTree) // 1: from ancestral breaks in joints + this.InitializeRigidGroups() // 1: from ancestral breaks in joints // Fields Only: Assign Game Piece rigid nodes - if (!assembly.dynamic) this.AssignGamePieceRigidNodes(assembly, traverseTree) + if (!assembly.dynamic) this.AssignGamePieceRigidNodes() // 2: Grounded joint const gInst = assembly.data!.joints!.jointInstances![GROUNDED_JOINT_ID] @@ -136,15 +129,19 @@ class MirabufParser { } } - private InitializeRigidGroups( - assembly: mirabuf.Assembly, - traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void - ) { - const jointInstanceKeys = Object.keys(assembly.data!.joints!.jointInstances!) as string[] + private TraverseTree(nodes: mirabuf.INode[], op: (node: mirabuf.INode) => void) { + nodes.forEach(node => { + if (node.children) this.TraverseTree(node.children, op) + op(node) + }) + } + + private InitializeRigidGroups() { + const jointInstanceKeys = Object.keys(this._assembly.data!.joints!.jointInstances!) as string[] jointInstanceKeys.forEach(key => { if (key === GROUNDED_JOINT_ID) return - const jInst = assembly.data!.joints!.jointInstances![key] + const jInst = this._assembly.data!.joints!.jointInstances![key] const [ancestorA, ancestorB] = this.FindAncestorialBreak(jInst.parentPart!, jInst.childPart!) const parentRN = this.NewRigidNode() @@ -152,17 +149,14 @@ class MirabufParser { this.MovePartToRigidNode(ancestorB, this.NewRigidNode()) if (jInst.parts && jInst.parts.nodes) - traverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) + this.TraverseTree(jInst.parts.nodes, x => this.MovePartToRigidNode(x.value!, parentRN)) }) } - private AssignGamePieceRigidNodes( - assembly: mirabuf.Assembly, - traverseTree: (node: mirabuf.INode[], op: (node: mirabuf.INode) => void) => void - ) { + private AssignGamePieceRigidNodes() { // Collect all definitions labeled as gamepieces (dynamic = true) const gamepieceDefinitions: Set = new Set( - Object.values(assembly.data!.parts!.partDefinitions!) + Object.values(this._assembly.data!.parts!.partDefinitions!) .filter(def => def.dynamic) .map((def: mirabuf.IPartDefinition) => { return def.info!.GUID! @@ -170,7 +164,7 @@ class MirabufParser { ) // Create gamepiece rigid nodes from PartInstances with corresponding definitions - Object.values(assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { + Object.values(this._assembly.data!.parts!.partInstances!).forEach((inst: mirabuf.IPartInstance) => { if (!gamepieceDefinitions.has(inst.partDefinitionReference!)) return const instNode = this.BinarySearchDesignTree(inst.info!.GUID!) @@ -182,7 +176,7 @@ class MirabufParser { const gpRn = this.NewRigidNode(GAMEPIECE_SUFFIX) gpRn.isGamePiece = true this.MovePartToRigidNode(instNode!.value!, gpRn) - if (instNode.children) traverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) + if (instNode.children) this.TraverseTree(instNode.children, x => this.MovePartToRigidNode(x.value!, gpRn)) }) } @@ -219,7 +213,7 @@ class MirabufParser { directedGraph.AddNode(node.id) }) - function directedRecursive(node: string) { + const directedRecursive = (node: string) => { graph .GetAdjacencyList(node) .filter(x => whiteGreyBlackMap.has(x)) @@ -381,7 +375,7 @@ class MirabufParser { let nextValue = 0 const partTreeValues = new Map() - function recursive(partNode: mirabuf.INode) { + const recursive = (partNode: mirabuf.INode) => { partNode.children = partNode.children?.filter(x => x.value != null) partNode.children?.forEach(x => recursive(x)) partTreeValues.set(partNode.value!, nextValue++) From 4f6f7426b2092ca196c9099f69dfd871870187d1 Mon Sep 17 00:00:00 2001 From: Azalea Colburn <62953415+azaleacolburn@users.noreply.github.com> Date: Wed, 21 Aug 2024 15:37:40 -0700 Subject: [PATCH 17/29] Update fission/src/mirabuf/MirabufParser.ts --- fission/src/mirabuf/MirabufParser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index c07cf5cef9..436a022a84 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -454,7 +454,7 @@ export class Graph { } public AddEdgeDirected(nodeA: string, nodeB: string) { - if (!this._adjacencyMap.has(nodeA) || !this._adjacencyMap?.has(nodeB)) throw new Error("Nodes aren't in graph") + if (!this._adjacencyMap.has(nodeA) || !this._adjacencyMap.has(nodeB)) throw new Error("Nodes aren't in graph") this._adjacencyMap.get(nodeA)!.push(nodeB) } From 4bffc6ad7654c76eeccccbf2d8571d95aa253897 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 15:54:37 -0700 Subject: [PATCH 18/29] cleanup appearance parsing --- fission/src/mirabuf/MirabufInstance.ts | 45 +++++++++++++------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 7e1a9eb505..d8d8781a23 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,29 +128,28 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!).forEach( - ([appearanceId, appearance]) => { - const { A, B, G, R } = appearance.albedo ?? {} - const [hex, opacity] = - A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] - - const material = - materialStyle === MaterialStyle.Regular - ? new THREE.MeshPhongMaterial({ - color: hex, - shininess: 0.0, - shadowSide: THREE.DoubleSide, - opacity: opacity, - transparent: opacity < 1.0, - }) - : materialStyle === MaterialStyle.Normals - ? new THREE.MeshNormalMaterial() - : World.SceneRenderer.CreateToonMaterial(hex, 5) - - World.SceneRenderer.SetupMaterial(material) - this._materials.set(appearanceId, material) - } - ) + ;( + Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [string, mirabuf.Color][] + ).forEach(([appearanceId, { A, B, G, R }]) => { + const hex = (A << 24) | (R << 16) | (G << 8) | B + const opacity = A / 255.0 + + const material = + materialStyle === MaterialStyle.Regular + ? new THREE.MeshPhongMaterial({ + color: hex, + shininess: 0.0, + shadowSide: THREE.DoubleSide, + opacity: opacity, + transparent: opacity < 1.0, + }) + : materialStyle === MaterialStyle.Normals + ? new THREE.MeshNormalMaterial() + : World.SceneRenderer.CreateToonMaterial(hex, 5) + + World.SceneRenderer.SetupMaterial(material) + this._materials.set(appearanceId, material) + }) } /** From 691c7d0e9444ee783d755065cf5b082e4918a64c Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Wed, 21 Aug 2024 16:35:57 -0700 Subject: [PATCH 19/29] formatted --- fission/src/mirabuf/MirabufInstance.ts | 2 +- fission/src/mirabuf/MirabufParser.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index d8d8781a23..2b53fad76c 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,7 +128,7 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ;( + ( Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [string, mirabuf.Color][] ).forEach(([appearanceId, { A, B, G, R }]) => { const hex = (A << 24) | (R << 16) | (G << 8) | B diff --git a/fission/src/mirabuf/MirabufParser.ts b/fission/src/mirabuf/MirabufParser.ts index 436a022a84..1e90a7e151 100644 --- a/fission/src/mirabuf/MirabufParser.ts +++ b/fission/src/mirabuf/MirabufParser.ts @@ -286,7 +286,6 @@ class MirabufParser { root.children?.forEach(child => { const partInstance = partInstances.get(child.value!)! - // TODO: guarantee that these assertions won't fail const def = partDefinitions[partInstance.partDefinitionReference!] const mat = partInstance.transform From e328c0337617219d615af988c6b6c35867e13212 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 10:28:08 -0700 Subject: [PATCH 20/29] revert colors --- fission/src/mirabuf/MirabufInstance.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 2b53fad76c..f7b589c2e5 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -53,6 +53,8 @@ const fillerMaterials = [ }), ] +type Color = { A: number; B: number; G: number; R: number } + const transformVerts = (mesh: mirabuf.IMesh) => { const newVerts = new Float32Array(mesh.verts!.length) for (let i = 0; i < mesh.verts!.length; i += 3) { @@ -128,11 +130,15 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ( - Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [string, mirabuf.Color][] - ).forEach(([appearanceId, { A, B, G, R }]) => { - const hex = (A << 24) | (R << 16) | (G << 8) | B - const opacity = A / 255.0 + ;( + Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [ + string, + mirabuf.material.Appearance, + ][] + ).forEach(([appearanceId, appearance]) => { + const { A, B, G, R } = appearance.albedo ?? {} + const [hex, opacity] = + A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] const material = materialStyle === MaterialStyle.Regular From 2acdfa2f56c0bf26973dcd1430bac4293eae25c5 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 10:34:17 -0700 Subject: [PATCH 21/29] change map to foreach --- fission/src/systems/physics/PhysicsSystem.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index f323503e43..f0e84a6385 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -1181,7 +1181,7 @@ function SetupCollisionFiltering(settings: Jolt.JoltSettings) { bpInterface.MapObjectToBroadPhaseLayer(LAYER_FIELD, BP_LAYER_FIELD) bpInterface.MapObjectToBroadPhaseLayer(LAYER_GENERAL_DYNAMIC, BP_LAYER_GENERAL_DYNAMIC) - bpRobotLayers.map((bpRobot, i) => { + bpRobotLayers.forEach((bpRobot, i) => { bpInterface.MapObjectToBroadPhaseLayer(RobotLayers[i], bpRobot) }) From 32fc40e1964069c182a2560e613fa0be508063ae Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 11:00:42 -0700 Subject: [PATCH 22/29] format --- fission/src/mirabuf/MirabufInstance.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index f7b589c2e5..bb667aa840 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -53,8 +53,6 @@ const fillerMaterials = [ }), ] -type Color = { A: number; B: number; G: number; R: number } - const transformVerts = (mesh: mirabuf.IMesh) => { const newVerts = new Float32Array(mesh.verts!.length) for (let i = 0; i < mesh.verts!.length; i += 3) { @@ -130,7 +128,7 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ;( + ( Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [ string, mirabuf.material.Appearance, From 98f049e0d73db43ed9a293d41e2dc1e046e907f2 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 11:04:44 -0700 Subject: [PATCH 23/29] one more formatting change apartently --- fission/src/mirabuf/MirabufInstance.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index bb667aa840..98322d796d 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,7 +128,7 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ( + ;( Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [ string, mirabuf.material.Appearance, From 3c358e4167196100b76ee16c9f56b289b60f2617 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 11:49:33 -0700 Subject: [PATCH 24/29] what is going on with formatting --- fission/src/mirabuf/MirabufInstance.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 98322d796d..bb667aa840 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,7 +128,7 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ;( + ( Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [ string, mirabuf.material.Appearance, From 5f1b4ed224ede7f82aea42558cbd09ba6cd38c2b Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 11:54:39 -0700 Subject: [PATCH 25/29] i think maybe eslint and prettier disagree :( --- fission/package.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fission/package.json b/fission/package.json index 428df4a422..6423349f3a 100644 --- a/fission/package.json +++ b/fission/package.json @@ -13,11 +13,11 @@ "test": "vitest", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives", "lint:fix": "eslint . --ext ts,tsx --report-unused-disable-directives --fix", - "prettier": "(bun x prettier src --check) || (npx prettier src --check)", - "prettier:fix": "(bun x prettier src --write) || (npx prettier src --write)", - "format": "(bun run prettier:fix && bun run lint:fix) || (npm run prettier:fix && npm run lint:fix)", + "prettier": "bun x prettier src --check || npx prettier src --check", + "prettier:fix": "bun x prettier src --write || npx prettier src --write", + "format": "bun run prettier:fix && bun run lint:fix || npm run prettier:fix && npm run lint:fix", "assetpack": "curl -o public/assetpack.zip https://synthesis.autodesk.com/Downloadables/assetpack.zip && tar -xf public/assetpack.zip -C public/", - "playwright:install": "(bun x playwright install || npx playwright install)" + "playwright:install": "bun x playwright install || npx playwright install" }, "dependencies": { "@barclah/jolt-physics": "^0.24.1", From 32dbec7482e0cb344d890f410ce3fcdedf9723f3 Mon Sep 17 00:00:00 2001 From: Azalea Colburn Date: Thu, 22 Aug 2024 11:58:21 -0700 Subject: [PATCH 26/29] format again --- fission/src/mirabuf/MirabufInstance.ts | 49 ++++++++++++-------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index bb667aa840..7e1a9eb505 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -128,32 +128,29 @@ class MirabufInstance { * Parses all mirabuf appearances into ThreeJS and Jolt materials. */ private LoadMaterials(materialStyle: MaterialStyle) { - ( - Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!) as [ - string, - mirabuf.material.Appearance, - ][] - ).forEach(([appearanceId, appearance]) => { - const { A, B, G, R } = appearance.albedo ?? {} - const [hex, opacity] = - A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] - - const material = - materialStyle === MaterialStyle.Regular - ? new THREE.MeshPhongMaterial({ - color: hex, - shininess: 0.0, - shadowSide: THREE.DoubleSide, - opacity: opacity, - transparent: opacity < 1.0, - }) - : materialStyle === MaterialStyle.Normals - ? new THREE.MeshNormalMaterial() - : World.SceneRenderer.CreateToonMaterial(hex, 5) - - World.SceneRenderer.SetupMaterial(material) - this._materials.set(appearanceId, material) - }) + Object.entries(this._mirabufParser.assembly.data!.materials!.appearances!).forEach( + ([appearanceId, appearance]) => { + const { A, B, G, R } = appearance.albedo ?? {} + const [hex, opacity] = + A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] + + const material = + materialStyle === MaterialStyle.Regular + ? new THREE.MeshPhongMaterial({ + color: hex, + shininess: 0.0, + shadowSide: THREE.DoubleSide, + opacity: opacity, + transparent: opacity < 1.0, + }) + : materialStyle === MaterialStyle.Normals + ? new THREE.MeshNormalMaterial() + : World.SceneRenderer.CreateToonMaterial(hex, 5) + + World.SceneRenderer.SetupMaterial(material) + this._materials.set(appearanceId, material) + } + ) } /** From 0c39d2e378f46802d5a7fa915c9294ed1fa2c8df Mon Sep 17 00:00:00 2001 From: HunterBarclay Date: Thu, 5 Sep 2024 00:45:35 -0600 Subject: [PATCH 27/29] WIP: Accumulating friction pairings and fixed gamepiece issue in the exporter. --- .../src/UI/GamepieceConfigTab.py | 6 ++- fission/src/systems/physics/PhysicsSystem.ts | 37 +++++++++++++++++-- fission/vite.config.ts | 2 +- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/exporter/SynthesisFusionAddin/src/UI/GamepieceConfigTab.py b/exporter/SynthesisFusionAddin/src/UI/GamepieceConfigTab.py index c28f6c60f1..819f352e87 100644 --- a/exporter/SynthesisFusionAddin/src/UI/GamepieceConfigTab.py +++ b/exporter/SynthesisFusionAddin/src/UI/GamepieceConfigTab.py @@ -3,6 +3,9 @@ from src.Logging import logFailure from src.Parser.ExporterOptions import ExporterOptions +from src.Parser.SynthesisParser.Utilities import ( + guid_occurrence +) from src.Types import Gamepiece, UnitSystem from src.UI.CreateCommandInputsHelper import ( createBooleanInput, @@ -198,7 +201,8 @@ def removeChildOccurrences(childOccurrences: adsk.fusion.OccurrenceList) -> None def getGamepieces(self) -> list[Gamepiece]: gamepieces: list[Gamepiece] = [] for row in range(1, self.gamepieceTable.rowCount): # Row is 1 indexed - gamepieceEntityToken = self.selectedGamepieceList[row - 1].entityToken + occ = self.selectedGamepieceList[row - 1] + gamepieceEntityToken = guid_occurrence(occ) gamepieceWeight = convertMassUnitsTo(self.gamepieceTable.getInputAtPosition(row, 1).value) gamepieceFrictionCoefficient = self.gamepieceTable.getInputAtPosition(row, 2).valueOne gamepieces.append(Gamepiece(gamepieceEntityToken, gamepieceWeight, gamepieceFrictionCoefficient)) diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index f0e84a6385..463d3d4c37 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -62,6 +62,8 @@ const FLOOR_FRICTION = 0.7 const SUSPENSION_MIN_FACTOR = 0.1 const SUSPENSION_MAX_FACTOR = 0.3 +const DEFAULT_PHYSICAL_MATERIAL_KEY = "default" + // Motor constant const VELOCITY_DEFAULT = 30 @@ -660,7 +662,14 @@ class PhysicsSystem extends WorldSystem { let shapesAdded = 0 let totalMass = 0 - let frictionOverride = 0 + + type FrictionPairing = { + dynamic: number, + static: number, + weight: number + } + const frictionAccum: FrictionPairing[] = [] + const comAccum = new mirabuf.Vector3() const minBounds = new JOLT.Vec3(1000000.0, 1000000.0, 1000000.0) @@ -701,8 +710,14 @@ class PhysicsSystem extends WorldSystem { JOLT.destroy(transform) // Set friction override once to any of the parts' values - if (!frictionOverride && partDefinition?.frictionOverride) - frictionOverride = partDefinition.frictionOverride + const physicalMaterial = parser.assembly.data!.materials!.physicalMaterials![partInstance.physicalMaterial ?? DEFAULT_PHYSICAL_MATERIAL_KEY] + const frictionPairing: FrictionPairing = { + dynamic: partDefinition?.frictionOverride ?? physicalMaterial.dynamicFriction!, + static: partDefinition?.frictionOverride ?? physicalMaterial.staticFriction!, + weight: partDefinition.physicalData?.area ?? 1.0 + } + frictionAccum.push(frictionPairing) + // console.debug(`(${frictionPairing.dynamic.toFixed(3), frictionPairing.static.toFixed(3)}) [${frictionPairing.weight.toFixed(3)}]`) if (!partDefinition.physicalData?.com || !partDefinition.physicalData.mass) return @@ -741,7 +756,21 @@ class PhysicsSystem extends WorldSystem { rnToBodies.set(rn.id, body.GetID()) // Set Friction Here - if (frictionOverride) body.SetFriction(frictionOverride) + let staticFriction = 0.0 + let dynamicFriction = 0.0 + let weightSum = 0.0 + frictionAccum.forEach(pairing => { + staticFriction += pairing.static * pairing.weight + dynamicFriction += pairing.dynamic * pairing.weight + weightSum += pairing.weight + }) + staticFriction /= weightSum == 0.0 ? 1.0 : weightSum + dynamicFriction /= weightSum == 0.0 ? 1.0 : weightSum + + // I guess this is an okay substitute. + const friction = (staticFriction + dynamicFriction) / 2.0 + body.SetFriction(friction) + console.debug(`Friction: ${friction}`) // Little testing components this._bodies.push(body.GetID()) diff --git a/fission/vite.config.ts b/fission/vite.config.ts index 967c978caa..050892e312 100644 --- a/fission/vite.config.ts +++ b/fission/vite.config.ts @@ -7,7 +7,7 @@ const basePath = "/fission/" const serverPort = 3000 const dockerServerPort = 80 -const useLocal = true +const useLocal = false // https://vitejs.dev/config/ export default defineConfig({ From 78f7f3bba885011d31923a0d3af7e446655051c2 Mon Sep 17 00:00:00 2001 From: HunterBarclay Date: Sun, 15 Sep 2024 22:50:41 -0600 Subject: [PATCH 28/29] fix: Add fallbacks for zero friction, experimenting with materials in Fusion. --- exporter/SynthesisFusionAddin/Synthesis.py | 4 +- .../src/Parser/ExporterOptions.py | 2 +- .../src/Parser/SynthesisParser/Components.py | 2 + .../src/Parser/SynthesisParser/Materials.py | 12 +++++ fission/src/mirabuf/MirabufInstance.ts | 8 +++- fission/src/systems/physics/PhysicsSystem.ts | 47 ++++++++++++++++--- 6 files changed, 63 insertions(+), 12 deletions(-) diff --git a/exporter/SynthesisFusionAddin/Synthesis.py b/exporter/SynthesisFusionAddin/Synthesis.py index ee630a12ca..109460f808 100644 --- a/exporter/SynthesisFusionAddin/Synthesis.py +++ b/exporter/SynthesisFusionAddin/Synthesis.py @@ -121,7 +121,7 @@ def register_ui() -> None: work_panel, lambda *_: True, # TODO: Should be redone with various refactors. ShowAPSAuthCommand.ShowAPSAuthCommandCreatedHandler, - description=f"APS", + description=f"Login to your Autodesk account", command=True, ) @@ -132,7 +132,7 @@ def register_ui() -> None: work_panel, lambda *_: True, ShowWebsiteCommand.ShowWebsiteCommandCreatedHandler, - description=f"Website Test", + description=f"Open our tutorials page", command=True, ) gm.elements.append(websiteButton) diff --git a/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py b/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py index 634c005e9d..5fdfae1432 100644 --- a/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py +++ b/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py @@ -56,7 +56,7 @@ class ExporterOptions: openSynthesisUponExport: bool = field(default=False) hierarchy: ModelHierarchy = field(default=ModelHierarchy.FusionAssembly) - visualQuality: TriangleMeshQualityOptions = field(default=TriangleMeshQualityOptions.LowQualityTriangleMesh) + visualQuality: TriangleMeshQualityOptions = field(default=TriangleMeshQualityOptions.NormalQualityTriangleMesh) physicalDepth: PhysicalDepth = field(default=PhysicalDepth.AllOccurrence) physicalCalculationLevel: CalculationAccuracy = field(default=CalculationAccuracy.LowCalculationAccuracy) diff --git a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Components.py b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Components.py index dd8726ad82..9287dfa7ff 100644 --- a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Components.py +++ b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Components.py @@ -189,6 +189,8 @@ def _ParseBRep( meshManager = body.meshManager calc = meshManager.createMeshCalculator() calc.setQuality(options.visualQuality) + calc.maxNormalDeviation = 3.14159 * (1.0 / 6.0) + calc.surfaceTolerance = 0.5 mesh = calc.calculate() fill_info(trimesh, body) diff --git a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py index 1ff5d3fe6c..8218088bf3 100644 --- a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py +++ b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py @@ -207,6 +207,14 @@ def getMaterialAppearance( properties = fusionAppearance.appearanceProperties + arr = [] + for x in range(properties.count): + arr.append(properties.item(x)) + + roughnessProp = properties.itemById("surface_roughness") + if roughnessProp: + appearance.roughness = roughnessProp.value + # Thank Liam for this. modelItem = properties.itemById("interior_model") if modelItem: @@ -214,11 +222,15 @@ def getMaterialAppearance( baseColor = None if matModelType == 0: + reflectanceProp = properties.itemById("opaque_f0") + if reflectanceProp: + appearance.metallic = reflectanceProp.value baseColor = properties.itemById("opaque_albedo").value if baseColor: baseColor.opacity = 255 elif matModelType == 1: baseColor = properties.itemById("metal_f0").value + appearance.metallic = 0.8 if baseColor: baseColor.opacity = 255 elif matModelType == 2: diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 7e1a9eb505..0586844174 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -134,11 +134,15 @@ class MirabufInstance { const [hex, opacity] = A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] + console.debug(`${appearance.metallic}, ${appearance.roughness}`) + const material = materialStyle === MaterialStyle.Regular - ? new THREE.MeshPhongMaterial({ + ? new THREE.MeshStandardMaterial({ + // No specular? color: hex, - shininess: 0.0, + roughness: appearance.roughness ?? 0.5, + metalness: appearance.metallic ?? 0.0, shadowSide: THREE.DoubleSide, opacity: opacity, transparent: opacity < 1.0, diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 463d3d4c37..5bdc397b6d 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -52,6 +52,8 @@ const MAX_SUBSTEPS = 6 const STANDARD_SUB_STEPS = 4 const TIMESTEP_ADJUSTMENT = 0.0001 +const SIGNIFICANT_FRICTION_THRESHOLD = 0.05 + let lastDeltaT = STANDARD_SIMULATION_PERIOD export function GetLastDeltaT(): number { return lastDeltaT @@ -59,6 +61,7 @@ export function GetLastDeltaT(): number { // Friction constants const FLOOR_FRICTION = 0.7 +const DEFAULT_FRICTION = 0.7 const SUSPENSION_MIN_FACTOR = 0.1 const SUSPENSION_MAX_FACTOR = 0.3 @@ -651,6 +654,8 @@ class PhysicsSystem extends WorldSystem { public CreateBodiesFromParser(parser: MirabufParser, layerReserve?: LayerReserve): Map { const rnToBodies = new Map() + console.debug(parser.assembly.data?.materials) + if ((parser.assembly.dynamic && !layerReserve) || layerReserve?.isReleased) { throw new Error("No layer reserve for dynamic assembly") } @@ -664,8 +669,8 @@ class PhysicsSystem extends WorldSystem { let totalMass = 0 type FrictionPairing = { - dynamic: number, - static: number, + dynamic: number + static: number weight: number } const frictionAccum: FrictionPairing[] = [] @@ -710,14 +715,42 @@ class PhysicsSystem extends WorldSystem { JOLT.destroy(transform) // Set friction override once to any of the parts' values - const physicalMaterial = parser.assembly.data!.materials!.physicalMaterials![partInstance.physicalMaterial ?? DEFAULT_PHYSICAL_MATERIAL_KEY] + console.debug( + `Physical Material: ${partInstance.physicalMaterial}, Part Name: ${partInstance.info?.name}` + ) + const physicalMaterial = + parser.assembly.data!.materials!.physicalMaterials![ + partInstance.physicalMaterial ?? DEFAULT_PHYSICAL_MATERIAL_KEY + ] + console.debug(physicalMaterial) + console.debug( + `Override: ${partDefinition?.frictionOverride == null || partDefinition?.frictionOverride == undefined}` + ) + + let frictionOverride: number | undefined = + partDefinition?.frictionOverride == null ? undefined : partDefinition?.frictionOverride + if ((partDefinition?.frictionOverride ?? 0.0) < SIGNIFICANT_FRICTION_THRESHOLD) { + frictionOverride = undefined + } + + if ( + (physicalMaterial.dynamicFriction ?? 0.0) < SIGNIFICANT_FRICTION_THRESHOLD || + (physicalMaterial.staticFriction ?? 0.0) < SIGNIFICANT_FRICTION_THRESHOLD + ) { + physicalMaterial.dynamicFriction = DEFAULT_FRICTION + physicalMaterial.staticFriction = DEFAULT_FRICTION + } + + // TODO: Consider using roughness as dynamic friction. const frictionPairing: FrictionPairing = { - dynamic: partDefinition?.frictionOverride ?? physicalMaterial.dynamicFriction!, - static: partDefinition?.frictionOverride ?? physicalMaterial.staticFriction!, - weight: partDefinition.physicalData?.area ?? 1.0 + dynamic: frictionOverride ?? physicalMaterial.dynamicFriction!, + static: frictionOverride ?? physicalMaterial.staticFriction!, + weight: partDefinition.physicalData?.area ?? 1.0, } frictionAccum.push(frictionPairing) - // console.debug(`(${frictionPairing.dynamic.toFixed(3), frictionPairing.static.toFixed(3)}) [${frictionPairing.weight.toFixed(3)}]`) + console.debug( + `(${frictionPairing.dynamic.toFixed(3)}, ${frictionPairing.static.toFixed(3)}) [${frictionPairing.weight.toFixed(3)}]` + ) if (!partDefinition.physicalData?.com || !partDefinition.physicalData.mass) return From c875a156dd75b51f7c32ad0a7aaec469cadfb887 Mon Sep 17 00:00:00 2001 From: HunterBarclay Date: Sun, 15 Sep 2024 22:58:55 -0600 Subject: [PATCH 29/29] chores: Clean up left over test code, remove debug statements. --- .../src/Parser/SynthesisParser/Materials.py | 4 ---- fission/src/mirabuf/MirabufInstance.ts | 2 -- fission/src/systems/physics/PhysicsSystem.ts | 12 ------------ 3 files changed, 18 deletions(-) diff --git a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py index 8218088bf3..08c5e17bb3 100644 --- a/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py +++ b/exporter/SynthesisFusionAddin/src/Parser/SynthesisParser/Materials.py @@ -207,10 +207,6 @@ def getMaterialAppearance( properties = fusionAppearance.appearanceProperties - arr = [] - for x in range(properties.count): - arr.append(properties.item(x)) - roughnessProp = properties.itemById("surface_roughness") if roughnessProp: appearance.roughness = roughnessProp.value diff --git a/fission/src/mirabuf/MirabufInstance.ts b/fission/src/mirabuf/MirabufInstance.ts index 0586844174..8edcbf29a1 100644 --- a/fission/src/mirabuf/MirabufInstance.ts +++ b/fission/src/mirabuf/MirabufInstance.ts @@ -134,8 +134,6 @@ class MirabufInstance { const [hex, opacity] = A && B && G && R ? [(A << 24) | (R << 16) | (G << 8) | B, A / 255.0] : [0xe32b50, 1.0] - console.debug(`${appearance.metallic}, ${appearance.roughness}`) - const material = materialStyle === MaterialStyle.Regular ? new THREE.MeshStandardMaterial({ diff --git a/fission/src/systems/physics/PhysicsSystem.ts b/fission/src/systems/physics/PhysicsSystem.ts index 5bdc397b6d..59cc1af147 100644 --- a/fission/src/systems/physics/PhysicsSystem.ts +++ b/fission/src/systems/physics/PhysicsSystem.ts @@ -714,18 +714,10 @@ class PhysicsSystem extends WorldSystem { JOLT.destroy(partMax) JOLT.destroy(transform) - // Set friction override once to any of the parts' values - console.debug( - `Physical Material: ${partInstance.physicalMaterial}, Part Name: ${partInstance.info?.name}` - ) const physicalMaterial = parser.assembly.data!.materials!.physicalMaterials![ partInstance.physicalMaterial ?? DEFAULT_PHYSICAL_MATERIAL_KEY ] - console.debug(physicalMaterial) - console.debug( - `Override: ${partDefinition?.frictionOverride == null || partDefinition?.frictionOverride == undefined}` - ) let frictionOverride: number | undefined = partDefinition?.frictionOverride == null ? undefined : partDefinition?.frictionOverride @@ -748,9 +740,6 @@ class PhysicsSystem extends WorldSystem { weight: partDefinition.physicalData?.area ?? 1.0, } frictionAccum.push(frictionPairing) - console.debug( - `(${frictionPairing.dynamic.toFixed(3)}, ${frictionPairing.static.toFixed(3)}) [${frictionPairing.weight.toFixed(3)}]` - ) if (!partDefinition.physicalData?.com || !partDefinition.physicalData.mass) return @@ -803,7 +792,6 @@ class PhysicsSystem extends WorldSystem { // I guess this is an okay substitute. const friction = (staticFriction + dynamicFriction) / 2.0 body.SetFriction(friction) - console.debug(`Friction: ${friction}`) // Little testing components this._bodies.push(body.GetID())