Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.19 KB | None | 0 0
  1. class AnimatorViewController: UIViewController {
  2.  
  3. override func viewDidLoad() {
  4. super.viewDidLoad()
  5.  
  6. /// preparing methods call are not related for the PBD part
  7.  
  8. setupPhysics()
  9. }
  10.  
  11. // MARK: - Methods
  12. private func setupPhysics() {
  13. solver = PhysicsSolver()
  14.  
  15. setupClothVisualMesh(root: patternNode!)
  16.  
  17. setupAvatarFromDAE(path: avatarPath)
  18.  
  19. solver?.setupDebugNodes()
  20. }
  21.  
  22. func setupClothVisualMesh(root: SCNNode) {
  23. var elementNodesByLayers = root.childNodes.compactMap { $0.childNodes.compactMap { $0 as? ElementNode } }
  24.  
  25. var vertices = [SCNVector3]()
  26. var normals = [SCNVector3]()
  27. var coordinates = [SCNVector3]()
  28. var indices = [UInt16]()
  29. var elements = [UInt16]()
  30.  
  31. elementNodesByLayers[0].forEach {
  32. let (_, meshVertices, meshNormals, meshTexcoords, meshElements, meshIndices) = MeshSkinning.extractArrays(node: $0)
  33. let offset = vertices.count > 0 ? vertices.count - 1 : 0
  34. indices.append(contentsOf: meshIndices.compactMap { $0 + UInt16(offset) })
  35. vertices.append(contentsOf: meshVertices)
  36. normals.append(contentsOf: meshNormals)
  37. coordinates.append(contentsOf: meshTexcoords)
  38. elements.append(contentsOf: meshElements)
  39. }
  40. print("Loaded cloth model: [\(vertices.count) VERTICES, \(indices.count / 3) FACES]" )
  41.  
  42. print("Welding duplicate vertices...")
  43. let (weldedVertices, weldedTris, weldedElements) = MeshSkinning.AutoWeld(verts: vertices, elements: elements, tris: indices, threshold: 0.000000001)
  44. print("Removed \(vertices.count - weldedVertices.count) duplicate vertices" )
  45.  
  46. print("Setting up cloth simualation...")
  47.  
  48.  
  49. var indicesInt: [Int] = []
  50. for i in weldedTris{
  51. indicesInt.append(Int(i))
  52. }
  53.  
  54. // solver.setupCloth(vertices: vertices, indices: indicesInt, elements: elements)
  55. solver?.setupCloth(vertices: weldedVertices, indices: indicesInt, elements: weldedElements)
  56.  
  57. var pairs = [ConnectionPair]()
  58. connections?.forEach { connection in
  59. let leftVertices = connection.left.points.compactMap { SCNVector3($0.x, $0.y, 0.0) }
  60. let rightVertices = connection.right.points.compactMap { SCNVector3($0.x, $0.y, 0.0) }
  61. (0...leftVertices.count - 1).forEach { pairs.append((leftVertices[$0], rightVertices[$0])) }
  62. }
  63. solver?.setSewingConstraints(vertices: vertices, pairs: pairs)
  64.  
  65. print("Cloth simulation ready")
  66.  
  67. print("Setting up cloth visualization...")
  68. let clothVisGeo = solver?.setVisualizationMesh(vertices: vertices, normals: normals, texcoords: coordinates, indices: indices, elements: elements)
  69. let clothVisNode = SCNNode(geometry: clothVisGeo)
  70.  
  71. clothVisNode.name = "ClothVisualization"
  72.  
  73. sceneView.scene?.rootNode.addChildNode(clothVisNode)
  74. print("Cloth visualization ready")
  75. }
  76.  
  77. private func setupAvatarFromDAE(path: String) {
  78.  
  79. let avatarScene = SCNScene(named: path)!
  80. avatarRootNode = avatarScene.rootNode.childNode(withName: "RootNode", recursively: false)
  81. avatarRootNode.isHidden = true
  82. sceneView.scene?.rootNode.addChildNode(avatarRootNode)
  83.  
  84. avatarSkinNode = avatarRootNode.childNode(withName: "Genesis8Female-skinInstance", recursively: true)
  85. avatarAnimNode = avatarRootNode.childNode(withName: "Genesis8Female", recursively: true)
  86.  
  87. // lisa torso with head, arms, legs
  88. let meshElementsToIncludeForCollisions = [0, 5, 8]
  89.  
  90.  
  91. let animKeys = avatarAnimNode.animationKeys
  92. avatarAnimPlayer = avatarAnimNode.animationPlayer(forKey: animKeys.first!)
  93. avatarAnimPlayer.speed = 0.0
  94.  
  95.  
  96. let skinner = avatarSkinNode.skinner!
  97. var bonesTransforms:[float4x4] = []
  98. var bonesInvBindTransforms:[float4x4] = []
  99. let baseGeometryBindTransform:float4x4 = float4x4(skinner.baseGeometryBindTransform)
  100.  
  101. for i in 0..<skinner.bones.count{
  102.  
  103. let worldTr = float4x4(skinner.bones[i].presentation.worldTransform)
  104. let bonInvBindTr = float4x4(skinner.boneInverseBindTransforms![i].scnMatrix4Value)
  105.  
  106. bonesTransforms.append(worldTr * bonInvBindTr * baseGeometryBindTransform)
  107. bonesWorldTransforms.append(worldTr)
  108. bonesInvBindTransforms.append(bonInvBindTr)
  109. }
  110.  
  111.  
  112.  
  113. //default: return arrays of the rest pose (untransformed, unscaled etc)
  114. let (skinGeo, vertices, normals, indices, boneIndices, boneWeights) = MeshSkinning.extractArrays(skinner: skinner, elementsToInclude: meshElementsToIncludeForCollisions)
  115.  
  116. //debug: returns skinned mesh arrays of the first frame of the animation (transformed, scaled)
  117. // let (skinGeo, vertices, normals, indices, boneIndices, boneWeights) = MeshSkinning.bakeMesh(skinner: skinner, bonesWorldTr:bonesWorldTransforms)
  118.  
  119. print(path + " loaded: [\(vertices.count) VERTICES, \(indices.count / 3) FACES]" )
  120.  
  121. let avatarGeo = solver?.setDynamicGeometry(vertices: vertices, normals: normals, indices: indices, bonesIndices: boneIndices, bonesWeights: boneWeights, bonesTransforms: bonesWorldTransforms, bonesInvBinds: bonesInvBindTransforms, bonesGeoBind: baseGeometryBindTransform )
  122.  
  123. avatarCollisionMesh = SCNNode(geometry: avatarGeo)
  124. avatarCollisionMesh.name = "AvatarCollisionMesh"
  125. // avatarCollisionMesh.isHidden = true
  126. sceneView.scene?.rootNode.addChildNode(avatarCollisionMesh)
  127. //TODO
  128. solver?.simParams.bonesPerVertex = Int32(skinner.boneIndices.componentsPerVector)
  129. solver?.simParams.vertexCount = Int32(vertices.count)
  130. solver?.simParams.trianglesCount = Int32(indices.count/3)
  131.  
  132. }
  133.  
  134. // MARK: - Actions
  135. @IBAction private func doneButtonPressed(_ sender: UIBarButtonItem) {
  136. dismiss(animated: true)
  137. }
  138.  
  139. }
  140.  
  141. extension AnimatorViewController: SCNSceneRendererDelegate {
  142.  
  143. func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
  144. guard solver != nil else { return }
  145.  
  146. //allow few frames for a warm-up
  147. if frameCounter > 20 {
  148. simulatePhysics = true
  149. }
  150.  
  151. if frameCounter > 50 {
  152. solver?.simParams.sewingStiffness += 0.01
  153. }
  154.  
  155.  
  156. //end sewing/layering and enter dynamics simulation
  157. if frameCounter > 150 {
  158. solver?.setRestPositionsToCurrentPositions()
  159.  
  160. solver?.simParams.dynamicsOff = 0
  161. solver?.simParams.sewingStiffness = 1.0
  162. solver?.simParams.extraCollisionChecks = 0
  163. // windStrength = 100
  164. }
  165.  
  166. //start character animation
  167. if frameCounter > 180 {
  168. avatarAnimPlayer.speed = avatarAnimSpeed
  169. avatarHighResAnimPlayer.speed = avatarAnimSpeed
  170. }
  171.  
  172. if frameCounter > 400 {
  173. // avatarAnimPlayer.speed = 0
  174. // avatarHighResAnimPlayer.speed = 0
  175. }
  176.  
  177. if frameCounter > 420 {
  178. // avatarAnimPlayer.speed = avatarAnimSpeed
  179. // avatarHighResAnimPlayer.speed = avatarAnimSpeed
  180. // windStrength = 10
  181. }
  182.  
  183. //print("frame: \(frameCounter)")
  184.  
  185. if simulatePhysics {
  186.  
  187. let timef = Float(time);
  188. let windStr = cos( timef / 7000 ) * windStrength //+ 40
  189.  
  190. let windDir = normalize (simd_float3( sin( timef / 2000 ), cos( timef / 3000 ), sin( timef / 1000 ) ) )
  191.  
  192.  
  193. solver?.simParams.windForce = windDir * windStr
  194.  
  195. let skinner = avatarSkinNode.skinner!
  196.  
  197. for i in 0..<skinner.bones.count{
  198. bonesWorldTransforms[i] = skinner.bones[i].presentation.simdWorldTransform
  199. }
  200. solver?.setBones(bonesTransforms: bonesWorldTransforms)
  201.  
  202. solver?.preStepPhysics()
  203.  
  204. // solver.updateUniformGrid()
  205.  
  206. for step in 0...solverSubSteps {
  207.  
  208. let dt = Float(0.016) / Float(solverSubSteps) //assumes 60fps, 16ms per frame
  209. let t = Float(step) / Float(solverSubSteps)
  210.  
  211. solver?.stepPhysics(dt: dt, t: t, constraintsIterations: solverConstraintsIterations)
  212.  
  213. }
  214.  
  215. solver?.postStepPhysics()
  216. }
  217. frameCounter += 1
  218. }
  219. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement