body.go 22 KB

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