body.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package object
  5. import (
  6. "github.com/g3n/engine/graphic"
  7. "github.com/g3n/engine/math32"
  8. "github.com/g3n/engine/material"
  9. )
  10. // Body represents a physics-driven body.
  11. type Body struct {
  12. *graphic.Graphic // TODO future - embed core.Node instead and calculate properties recursively
  13. material *material.Material // Physics material specifying friction and restitution
  14. index int
  15. // Mass properties
  16. mass float32 // Total mass
  17. invMass float32
  18. invMassEff float32 // Effective inverse mass
  19. // Rotational inertia and related properties
  20. rotInertia *math32.Matrix3 // Angular mass i.e. moment of inertia in local coordinates
  21. invRotInertia *math32.Matrix3 // Inverse rotational inertia in local coordinates
  22. invRotInertiaEff *math32.Matrix3 // Effective inverse rotational inertia in local coordinates
  23. invRotInertiaWorld *math32.Matrix3 // Inverse rotational inertia in world coordinates
  24. invRotInertiaWorldEff *math32.Matrix3 // Effective rotational inertia in world coordinates
  25. fixedRotation bool // Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
  26. // Position
  27. position *math32.Vector3 // World position of the center of gravity (World space position of the body.)
  28. initPosition *math32.Vector3 // Initial position of the body.
  29. prevPosition *math32.Vector3 // Previous position
  30. interpPosition *math32.Vector3 // Interpolated position of the body.
  31. // Rotation
  32. quaternion *math32.Quaternion // World space orientation of the body.
  33. initQuaternion *math32.Quaternion
  34. prevQuaternion *math32.Quaternion
  35. interpQuaternion *math32.Quaternion // Interpolated orientation of the body.
  36. // Linear and angular velocities
  37. velocity *math32.Vector3 // Linear velocity (World space velocity of the body.)
  38. initVelocity *math32.Vector3 // Initial linear velocity (World space velocity of the body.)
  39. angularVelocity *math32.Vector3 // Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
  40. initAngularVelocity *math32.Vector3
  41. // Force and torque
  42. force *math32.Vector3 // Linear force on the body in world space.
  43. torque *math32.Vector3 // World space rotational force on the body, around center of mass.
  44. // Damping and factors
  45. linearDamping float32
  46. angularDamping float32
  47. linearFactor *math32.Vector3 // Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
  48. angularFactor *math32.Vector3 // Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
  49. // Body type and sleep settings
  50. bodyType BodyType
  51. sleepState BodySleepState // Current sleep state.
  52. allowSleep bool // If true, the body will automatically fall to sleep.
  53. sleepSpeedLimit float32 // If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  54. sleepTimeLimit float32 // If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  55. timeLastSleepy float32
  56. wakeUpAfterNarrowphase bool
  57. // Collision settings
  58. colFilterGroup int // Collision filter group
  59. colFilterMask int // Collision filter mask
  60. colResponse bool // Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  61. aabb *math32.Box3 // World space bounding box of the body and its shapes.
  62. aabbNeedsUpdate bool // Indicates if the AABB needs to be updated before use.
  63. boundingRadius float32 // Total bounding radius of the body (TODO including its shapes, relative to body.position.)
  64. // Cached geometry properties
  65. faces [][3]math32.Vector3
  66. faceNormals []math32.Vector3
  67. worldFaceNormals []math32.Vector3
  68. uniqueEdges []math32.Vector3
  69. worldUniqueEdges []math32.Vector3
  70. // TODO future (for now a body is a single graphic with a single geometry)
  71. // shapes []*Shape
  72. // shapeOffsets []float32 // Position of each Shape in the body, given in local Body space.
  73. // shapeOrientations [] ?
  74. }
  75. // BodyType specifies how the body is affected during the simulation.
  76. type BodyType int
  77. const (
  78. // A static body does not move during simulation and behaves as if it has infinite mass.
  79. // Static bodies can be moved manually by setting the position of the body.
  80. // The velocity of a static body is always zero.
  81. // Static bodies do not collide with other static or kinematic bodies.
  82. Static = BodyType(iota)
  83. // A kinematic body moves under simulation according to its velocity.
  84. // They do not respond to forces.
  85. // They can be moved manually, but normally a kinematic body is moved by setting its velocity.
  86. // A kinematic body behaves as if it has infinite mass.
  87. // Kinematic bodies do not collide with other static or kinematic bodies.
  88. Kinematic
  89. // A dynamic body is fully simulated.
  90. // Can be moved manually by the user, but normally they move according to forces.
  91. // A dynamic body can collide with all body types.
  92. // A dynamic body always has finite, non-zero mass.
  93. Dynamic
  94. )
  95. // TODO Update simulation checks for BodyType to use bitwise operators ?
  96. // BodyStatus specifies
  97. type BodySleepState int
  98. const (
  99. Awake = BodySleepState(iota)
  100. Sleepy
  101. Sleeping
  102. )
  103. // Events
  104. const (
  105. SleepyEvent = "physics.SleepyEvent" // Dispatched after a body has gone in to the sleepy state.
  106. SleepEvent = "physics.SleepEvent" // Dispatched after a body has fallen asleep.
  107. WakeUpEvent = "physics.WakeUpEvent" // Dispatched after a sleeping body has woken up.
  108. CollideEvent = "physics.CollideEvent" // Dispatched after two bodies collide. This event is dispatched on each of the two bodies involved in the collision.
  109. )
  110. // NewBody creates and returns a pointer to a new RigidBody.
  111. // The igraphic's geometry *must* be convex.
  112. func NewBody(igraphic graphic.IGraphic) *Body {
  113. b := new(Body)
  114. b.Graphic = igraphic.GetGraphic()
  115. // TODO mass setter/getter
  116. b.mass = 1 // cannon.js default is 0
  117. if b.mass > 0 {
  118. b.invMass = 1.0 / b.mass
  119. } else {
  120. b.invMass = 0
  121. }
  122. b.bodyType = Dynamic // TODO auto set to Static if mass == 0
  123. // Rotational inertia and related properties
  124. b.rotInertia = math32.NewMatrix3()
  125. b.invRotInertia = math32.NewMatrix3()
  126. b.invRotInertiaEff = math32.NewMatrix3()
  127. b.invRotInertiaWorld = math32.NewMatrix3()
  128. b.invRotInertiaWorldEff = math32.NewMatrix3()
  129. // Position
  130. pos := b.GetNode().Position()
  131. b.position = pos.Clone()
  132. b.prevPosition = pos.Clone()
  133. b.interpPosition = pos.Clone()
  134. b.initPosition = pos.Clone()
  135. // Rotation
  136. quat := b.GetNode().Quaternion()
  137. b.quaternion = quat.Clone()
  138. b.prevQuaternion = quat.Clone()
  139. b.interpQuaternion = quat.Clone()
  140. b.initQuaternion = quat.Clone()
  141. // Linear and angular velocities
  142. b.velocity = math32.NewVec3()
  143. b.initVelocity = math32.NewVec3()
  144. b.angularVelocity = math32.NewVec3()
  145. b.initAngularVelocity = math32.NewVec3()
  146. // Force and torque
  147. b.force = math32.NewVec3()
  148. b.torque = math32.NewVec3()
  149. // Damping and factors
  150. b.linearDamping = 0.01
  151. b.angularDamping = 0.01
  152. b.linearFactor = math32.NewVector3(1, 1, 1)
  153. b.angularFactor = math32.NewVector3(1, 1, 1)
  154. b.allowSleep = true
  155. b.sleepState = Awake
  156. b.sleepSpeedLimit = 0.1
  157. b.sleepTimeLimit = 1
  158. b.timeLastSleepy = 0
  159. b.colFilterGroup = 1
  160. b.colFilterMask = -1
  161. b.wakeUpAfterNarrowphase = false
  162. // Perform single-time computations
  163. b.computeFaceNormalsAndUniqueEdges()
  164. b.UpdateMassProperties()
  165. return b
  166. }
  167. // Compute and store face normals and unique edges
  168. func (b *Body) computeFaceNormalsAndUniqueEdges() {
  169. b.GetGeometry().ReadFaces(func(vA, vB, vC math32.Vector3) bool {
  170. // Store face vertices
  171. var face [3]math32.Vector3
  172. face[0] = vA
  173. face[1] = vB
  174. face[2] = vC
  175. b.faces = append(b.faces, face)
  176. // Compute edges
  177. edge1 := math32.NewVec3().SubVectors(&vB, &vA)
  178. edge2 := math32.NewVec3().SubVectors(&vC, &vB)
  179. edge3 := math32.NewVec3().SubVectors(&vA, &vC)
  180. // Compute and store face normal in b.faceNormals
  181. faceNormal := math32.NewVec3().CrossVectors(edge2, edge1)
  182. if faceNormal.Length() > 0 {
  183. faceNormal.Normalize()
  184. }
  185. b.faceNormals = append(b.faceNormals, *faceNormal)
  186. // Compare unique edges recorded so far with the three new face edges and store the unique ones
  187. tol := float32(1e-6)
  188. for p := 0; p < len(b.uniqueEdges); p++ {
  189. ue := b.uniqueEdges[p]
  190. if !ue.AlmostEquals(edge1, tol) {
  191. b.uniqueEdges = append(b.uniqueEdges, *edge1)
  192. }
  193. if !ue.AlmostEquals(edge2, tol) {
  194. b.uniqueEdges = append(b.uniqueEdges, *edge1)
  195. }
  196. if !ue.AlmostEquals(edge3, tol) {
  197. b.uniqueEdges = append(b.uniqueEdges, *edge1)
  198. }
  199. }
  200. return false
  201. })
  202. // Allocate space for worldFaceNormals and worldUniqueEdges
  203. b.worldFaceNormals = make([]math32.Vector3, len(b.faceNormals))
  204. b.worldUniqueEdges = make([]math32.Vector3, len(b.uniqueEdges))
  205. }
  206. // ComputeWorldFaceNormalsAndUniqueEdges
  207. func (b *Body) ComputeWorldFaceNormalsAndUniqueEdges() {
  208. // Re-compute world face normals from local face normals
  209. for i := 0; i < len(b.faceNormals); i++ {
  210. b.worldFaceNormals[i] = b.faceNormals[i]
  211. b.worldFaceNormals[i].ApplyQuaternion(b.quaternion)
  212. }
  213. // Re-compute world unique edges from local unique edges
  214. for i := 0; i < len(b.uniqueEdges); i++ {
  215. b.worldUniqueEdges[i] = b.uniqueEdges[i]
  216. b.worldUniqueEdges[i].ApplyQuaternion(b.quaternion)
  217. }
  218. }
  219. func (b *Body) Faces() [][3]math32.Vector3 {
  220. return b.faces
  221. }
  222. func (b *Body) FaceNormals() []math32.Vector3 {
  223. return b.faceNormals
  224. }
  225. func (b *Body) WorldFaceNormals() []math32.Vector3 {
  226. return b.worldFaceNormals
  227. }
  228. func (b *Body) UniqueEdges() []math32.Vector3 {
  229. return b.uniqueEdges
  230. }
  231. func (b *Body) WorldUniqueEdges() []math32.Vector3 {
  232. return b.worldUniqueEdges
  233. }
  234. func (b *Body) BoundingBox() math32.Box3 {
  235. return b.GetGeometry().BoundingBox()
  236. }
  237. func (b *Body) SetIndex(i int) {
  238. b.index = i
  239. }
  240. func (b *Body) Index() int {
  241. return b.index
  242. }
  243. func (b *Body) Material() *material.Material {
  244. return b.material
  245. }
  246. func (b *Body) SetAllowSleep(state bool) {
  247. b.allowSleep = state
  248. }
  249. func (b *Body) AllowSleep() bool {
  250. return b.allowSleep
  251. }
  252. func (b *Body) SleepSpeedLimit() float32 {
  253. return b.sleepSpeedLimit
  254. }
  255. func (b *Body) SleepState() BodySleepState {
  256. return b.sleepState
  257. }
  258. func (b *Body) BodyType() BodyType {
  259. return b. bodyType
  260. }
  261. func (b *Body) SetWakeUpAfterNarrowphase(state bool) {
  262. b.wakeUpAfterNarrowphase = state
  263. }
  264. func (b *Body) WakeUpAfterNarrowphase() bool {
  265. return b.wakeUpAfterNarrowphase
  266. }
  267. func (b *Body) ApplyDamping(dt float32) {
  268. b.velocity.MultiplyScalar(math32.Pow(1.0 - b.linearDamping, dt))
  269. b.angularVelocity.MultiplyScalar(math32.Pow(1.0 - b.angularDamping, dt))
  270. }
  271. func (b *Body) ApplyVelocityDeltas(linearD, angularD *math32.Vector3) {
  272. b.velocity.Add(linearD.Multiply(b.LinearFactor()))
  273. b.angularVelocity.Add(angularD.Multiply(b.AngularFactor()))
  274. }
  275. func (b *Body) ClearForces() {
  276. b.force.Zero()
  277. b.torque.Zero()
  278. }
  279. func (b *Body) InvMassEff() float32 {
  280. return b.invMassEff
  281. }
  282. func (b *Body) InvRotInertiaWorldEff() *math32.Matrix3 {
  283. return b.invRotInertiaWorldEff
  284. }
  285. func (b *Body) Position() math32.Vector3 {
  286. return *b.position
  287. }
  288. func (b *Body) Quaternion() *math32.Quaternion {
  289. return b.quaternion
  290. }
  291. func (b *Body) SetVelocity(vel *math32.Vector3) {
  292. b.velocity = vel
  293. }
  294. func (b *Body) Velocity() math32.Vector3 {
  295. return *b.velocity
  296. }
  297. func (b *Body) SetAngularVelocity(vel *math32.Vector3) {
  298. b.angularVelocity = vel
  299. }
  300. func (b *Body) AngularVelocity() math32.Vector3 {
  301. return *b.angularVelocity
  302. }
  303. func (b *Body) Force() math32.Vector3 {
  304. return *b.force
  305. }
  306. func (b *Body) Torque() math32.Vector3 {
  307. return *b.torque
  308. }
  309. func (b *Body) LinearDamping() float32 {
  310. return b.linearDamping
  311. }
  312. func (b *Body) AngularDamping() float32 {
  313. return b.angularDamping
  314. }
  315. func (b *Body) LinearFactor() *math32.Vector3 {
  316. return b.linearFactor
  317. }
  318. func (b *Body) AngularFactor() *math32.Vector3 {
  319. return b.angularFactor
  320. }
  321. // WakeUp wakes the body up.
  322. func (b *Body) WakeUp() {
  323. state := b.sleepState
  324. b.sleepState = Awake
  325. b.wakeUpAfterNarrowphase = false
  326. if state == Sleeping {
  327. b.Dispatch(WakeUpEvent, nil)
  328. }
  329. }
  330. // Sleep forces the body to sleep.
  331. func (b *Body) Sleep() {
  332. b.sleepState = Sleeping
  333. b.velocity.Set(0, 0, 0)
  334. b.angularVelocity.Set(0, 0, 0)
  335. b.wakeUpAfterNarrowphase = false
  336. }
  337. // Called every timestep to update internal sleep timer and change sleep state if needed.
  338. // time: The world time in seconds
  339. func (b *Body) SleepTick(time float32) {
  340. if b.allowSleep {
  341. speedSquared := b.velocity.LengthSq() + b.angularVelocity.LengthSq()
  342. speedLimitSquared := math32.Pow(b.sleepSpeedLimit, 2)
  343. if b.sleepState == Awake && speedSquared < speedLimitSquared {
  344. b.sleepState = Sleepy
  345. b.timeLastSleepy = time
  346. b.Dispatch(SleepyEvent, nil)
  347. } else if b.sleepState == Sleepy && speedSquared > speedLimitSquared {
  348. b.WakeUp() // Wake up
  349. } else if b.sleepState == Sleepy && (time-b.timeLastSleepy) > b.sleepTimeLimit {
  350. b.Sleep() // Sleeping
  351. b.Dispatch(SleepEvent, nil)
  352. }
  353. }
  354. }
  355. // If checkSleeping is true then returns false if both bodies are currently sleeping.
  356. func (b *Body) Sleeping() bool {
  357. return b.sleepState == Sleeping
  358. }
  359. // CollidableWith returns whether the body can collide with the specified body.
  360. func (b *Body) CollidableWith(other *Body) bool {
  361. if (b.colFilterGroup & other.colFilterMask == 0) ||
  362. (other.colFilterGroup & b.colFilterMask == 0) ||
  363. (b.bodyType == Static) && (other.bodyType == Static) {
  364. return false
  365. }
  366. return true
  367. }
  368. func (b *Body) CollisionResponse() bool {
  369. return b.colResponse
  370. }
  371. // PointToLocal converts a world point to local body frame. TODO maybe move to Node
  372. func (b *Body) PointToLocal(worldPoint *math32.Vector3) math32.Vector3 {
  373. return *worldPoint.Clone().Sub(b.position).ApplyQuaternion(b.quaternion.Conjugate())
  374. }
  375. // VectorToLocal converts a world vector to local body frame. TODO maybe move to Node
  376. func (b *Body) VectorToLocal(worldVector *math32.Vector3) math32.Vector3 {
  377. return *worldVector.Clone().ApplyQuaternion(b.quaternion.Conjugate())
  378. }
  379. // PointToWorld converts a local point to world frame. TODO maybe move to Node
  380. func (b *Body) PointToWorld(localPoint *math32.Vector3) math32.Vector3 {
  381. return *localPoint.Clone().ApplyQuaternion(b.quaternion).Add(b.position)
  382. }
  383. // VectorToWorld converts a local vector to world frame. TODO maybe move to Node
  384. func (b *Body) VectorToWorld(localVector *math32.Vector3) math32.Vector3 {
  385. return *localVector.Clone().ApplyQuaternion(b.quaternion)
  386. }
  387. // UpdateEffectiveMassProperties
  388. // If the body is sleeping, it should be immovable and thus have infinite mass during solve.
  389. // This is solved by having a separate "effective mass" and other "effective" properties
  390. func (b *Body) UpdateEffectiveMassProperties() {
  391. if b.sleepState == Sleeping || b.bodyType == Kinematic {
  392. b.invMassEff = 0
  393. b.invRotInertiaEff.Zero()
  394. b.invRotInertiaWorldEff.Zero()
  395. } else {
  396. b.invMassEff = b.invMass
  397. b.invRotInertiaEff.Copy(b.invRotInertia)
  398. b.invRotInertiaWorldEff.Copy(b.invRotInertiaWorld)
  399. }
  400. }
  401. // UpdateMassProperties
  402. // Should be called whenever you change the body shape or mass.
  403. func (b *Body) UpdateMassProperties() {
  404. // TODO getter of invMass ?
  405. if b.mass > 0 {
  406. b.invMass = 1.0 / b.mass
  407. } else {
  408. b.invMass = 0
  409. }
  410. if b.fixedRotation {
  411. b.rotInertia.Zero()
  412. b.invRotInertia.Zero()
  413. } else {
  414. *b.rotInertia = b.GetGeometry().RotationalInertia()
  415. b.invRotInertia.GetInverse(b.rotInertia) // Note: rotInertia is always positive definite and thus always invertible
  416. }
  417. b.UpdateInertiaWorld(true)
  418. }
  419. // Update .inertiaWorld and .invRotInertiaWorld
  420. func (b *Body) UpdateInertiaWorld(force bool) {
  421. iRI := b.invRotInertia
  422. // If rotational inertia M = s*I, where I is identity and s a scalar, then
  423. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  424. // where R is the rotation matrix.
  425. // In other words, we don't have to do the transformation if all diagonal entries are equal.
  426. if iRI[0] != iRI[4] || iRI[4] != iRI[8] || force {
  427. // iRIW = R * iRI * R'
  428. m1 := math32.NewMatrix3().MakeRotationFromQuaternion(b.quaternion)
  429. m2 := m1.Clone().Transpose()
  430. m2.Multiply(iRI)
  431. b.invRotInertiaWorld.MultiplyMatrices(m2, m1)
  432. }
  433. }
  434. // Forces from a force field need to be multiplied by mass.
  435. func (b *Body) ApplyForceField(force *math32.Vector3) {
  436. b.force.Add(force.MultiplyScalar(b.mass))
  437. }
  438. // Apply force to a world point.
  439. // This could for example be a point on the Body surface.
  440. // Applying force this way will add to Body.force and Body.torque.
  441. // relativePoint: A point relative to the center of mass to apply the force on.
  442. func (b *Body) ApplyForce(force, relativePoint *math32.Vector3) {
  443. if b.bodyType != Dynamic { // Needed?
  444. return
  445. }
  446. // Add linear force
  447. b.force.Add(force) // TODO shouldn't rotational momentum be subtracted from linear momentum?
  448. // Add rotational force
  449. b.torque.Add(math32.NewVec3().CrossVectors(relativePoint, force))
  450. }
  451. // Apply force to a local point in the body.
  452. // force: The force vector to apply, defined locally in the body frame.
  453. // localPoint: A local point in the body to apply the force on.
  454. func (b *Body) ApplyLocalForce(localForce, localPoint *math32.Vector3) {
  455. if b.bodyType != Dynamic {
  456. return
  457. }
  458. // Transform the force vector to world space
  459. worldForce := b.VectorToWorld(localForce)
  460. relativePointWorld := b.VectorToWorld(localPoint)
  461. b.ApplyForce(&worldForce, &relativePointWorld)
  462. }
  463. // Apply impulse to a world point.
  464. // This could for example be a point on the Body surface.
  465. // An impulse is a force added to a body during a short period of time (impulse = force * time).
  466. // Impulses will be added to Body.velocity and Body.angularVelocity.
  467. // impulse: The amount of impulse to add.
  468. // relativePoint: A point relative to the center of mass to apply the force on.
  469. func (b *Body) ApplyImpulse(impulse, relativePoint *math32.Vector3) {
  470. if b.bodyType != Dynamic {
  471. return
  472. }
  473. // Compute point position relative to the body center
  474. r := relativePoint
  475. // Compute produced central impulse velocity
  476. velo := impulse.Clone().MultiplyScalar(b.invMass)
  477. // Add linear impulse
  478. b.velocity.Add(velo)
  479. // Compute produced rotational impulse velocity
  480. rotVelo := math32.NewVec3().CrossVectors(r, impulse)
  481. rotVelo.ApplyMatrix3(b.invRotInertiaWorld)
  482. // Add rotational Impulse
  483. b.angularVelocity.Add(rotVelo)
  484. }
  485. // Apply locally-defined impulse to a local point in the body.
  486. // force: The force vector to apply, defined locally in the body frame.
  487. // localPoint: A local point in the body to apply the force on.
  488. func (b *Body) ApplyLocalImpulse(localImpulse, localPoint *math32.Vector3) {
  489. if b.bodyType != Dynamic {
  490. return
  491. }
  492. // Transform the force vector to world space
  493. worldImpulse := b.VectorToWorld(localImpulse)
  494. relativePointWorld := b.VectorToWorld(localPoint)
  495. b.ApplyImpulse(&worldImpulse, &relativePointWorld)
  496. }
  497. // Get world velocity of a point in the body.
  498. func (b *Body) GetVelocityAtWorldPoint(worldPoint *math32.Vector3) *math32.Vector3 {
  499. r := math32.NewVec3().SubVectors(worldPoint, b.position)
  500. r.CrossVectors(b.angularVelocity, r)
  501. r.Add(b.velocity)
  502. return r
  503. }
  504. // Move the body forward in time.
  505. // dt: Time step
  506. // quatNormalize: Set to true to normalize the body quaternion
  507. // quatNormalizeFast: If the quaternion should be normalized using "fast" quaternion normalization
  508. func (b *Body) Integrate(dt float32, quatNormalize, quatNormalizeFast bool) {
  509. // Save previous position and rotation
  510. b.prevPosition.Copy(b.position)
  511. b.prevQuaternion.Copy(b.quaternion)
  512. // If static or sleeping - skip
  513. if !(b.bodyType == Dynamic || b.bodyType == Kinematic) || b.sleepState == Sleeping {
  514. return
  515. }
  516. // Integrate force over mass (acceleration) to obtain estimate for instantaneous velocities
  517. iMdt := b.invMass * dt
  518. b.velocity.X += b.force.X * iMdt * b.linearFactor.X
  519. b.velocity.Y += b.force.Y * iMdt * b.linearFactor.Y
  520. b.velocity.Z += b.force.Z * iMdt * b.linearFactor.Z
  521. // Integrate inverse angular mass times torque to obtain estimate for instantaneous angular velocities
  522. e := b.invRotInertiaWorld
  523. tx := b.torque.X * b.angularFactor.X
  524. ty := b.torque.Y * b.angularFactor.Y
  525. tz := b.torque.Z * b.angularFactor.Z
  526. b.angularVelocity.X += dt * (e[0]*tx + e[3]*ty + e[6]*tz)
  527. b.angularVelocity.Y += dt * (e[1]*tx + e[4]*ty + e[7]*tz)
  528. b.angularVelocity.Z += dt * (e[2]*tx + e[5]*ty + e[8]*tz)
  529. // Integrate velocity to obtain estimate for position
  530. b.position.X += b.velocity.X * dt
  531. b.position.Y += b.velocity.Y * dt
  532. b.position.Z += b.velocity.Z * dt
  533. // Integrate angular velocity to obtain estimate for rotation
  534. ax := b.angularVelocity.X * b.angularFactor.X
  535. ay := b.angularVelocity.Y * b.angularFactor.Y
  536. az := b.angularVelocity.Z * b.angularFactor.Z
  537. bx := b.quaternion.X
  538. by := b.quaternion.Y
  539. bz := b.quaternion.Z
  540. bw := b.quaternion.W
  541. halfDt := dt * 0.5
  542. b.quaternion.X += halfDt * (ax*bw + ay*bz - az*by)
  543. b.quaternion.Y += halfDt * (ay*bw + az*bx - ax*bz)
  544. b.quaternion.X += halfDt * (az*bw + ax*by - ay*bx)
  545. b.quaternion.W += halfDt * (-ax*bx - ay*by - az*bz)
  546. // Update position and rotation of Node (containing visual representation of the body)
  547. b.GetNode().SetPositionVec(b.position)
  548. vRot := math32.NewVec3().SetFromQuaternion(b.quaternion)
  549. b.GetNode().SetRotationVec(vRot)
  550. // Normalize quaternion
  551. if quatNormalize {
  552. if quatNormalizeFast {
  553. b.quaternion.NormalizeFast()
  554. } else {
  555. b.quaternion.Normalize()
  556. }
  557. }
  558. b.aabbNeedsUpdate = true
  559. // Update world inertia
  560. b.UpdateInertiaWorld(false)
  561. }