body.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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.SetBodyType(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. b.bodyType = bt
  281. }
  282. func (b *Body) BodyType() BodyType {
  283. return b. bodyType
  284. }
  285. func (b *Body) SetWakeUpAfterNarrowphase(state bool) {
  286. b.wakeUpAfterNarrowphase = state
  287. }
  288. func (b *Body) WakeUpAfterNarrowphase() bool {
  289. return b.wakeUpAfterNarrowphase
  290. }
  291. func (b *Body) ApplyVelocityDeltas(linearD, angularD *math32.Vector3) {
  292. b.velocity.Add(linearD.Multiply(b.linearFactor))
  293. b.angularVelocity.Add(angularD.Multiply(b.angularFactor))
  294. }
  295. func (b *Body) ClearForces() {
  296. b.force.Zero()
  297. b.torque.Zero()
  298. }
  299. func (b *Body) InvMassEff() float32 {
  300. return b.invMassEff
  301. }
  302. func (b *Body) InvRotInertiaWorldEff() *math32.Matrix3 {
  303. return b.invRotInertiaWorldEff
  304. }
  305. func (b *Body) Position() math32.Vector3 {
  306. return *b.position
  307. }
  308. func (b *Body) Quaternion() *math32.Quaternion {
  309. return b.quaternion.Clone()
  310. }
  311. func (b *Body) SetVelocity(vel *math32.Vector3) {
  312. b.velocity = vel
  313. }
  314. func (b *Body) Velocity() math32.Vector3 {
  315. return *b.velocity
  316. }
  317. func (b *Body) SetAngularVelocity(vel *math32.Vector3) {
  318. b.angularVelocity = vel
  319. }
  320. func (b *Body) AngularVelocity() math32.Vector3 {
  321. return *b.angularVelocity
  322. }
  323. func (b *Body) Force() math32.Vector3 {
  324. return *b.force
  325. }
  326. func (b *Body) Torque() math32.Vector3 {
  327. return *b.torque
  328. }
  329. func (b *Body) SetLinearDamping(d float32) {
  330. b.linearDamping = d
  331. }
  332. func (b *Body) LinearDamping() float32 {
  333. return b.linearDamping
  334. }
  335. func (b *Body) SetAngularDamping(d float32) {
  336. b.angularDamping = d
  337. }
  338. func (b *Body) AngularDamping() float32 {
  339. return b.angularDamping
  340. }
  341. func (b *Body) ApplyDamping(dt float32) {
  342. b.velocity.MultiplyScalar(math32.Pow(1.0 - b.linearDamping, dt))
  343. b.angularVelocity.MultiplyScalar(math32.Pow(1.0 - b.angularDamping, dt))
  344. }
  345. func (b *Body) SetLinearFactor(factor *math32.Vector3) {
  346. b.linearFactor = factor
  347. }
  348. func (b *Body) LinearFactor() math32.Vector3 {
  349. return *b.linearFactor
  350. }
  351. func (b *Body) SetAngularFactor(factor *math32.Vector3) {
  352. b.angularFactor = factor
  353. }
  354. func (b *Body) AngularFactor() math32.Vector3 {
  355. return *b.angularFactor
  356. }
  357. // WakeUp wakes the body up.
  358. func (b *Body) WakeUp() {
  359. state := b.sleepState
  360. b.sleepState = Awake
  361. b.wakeUpAfterNarrowphase = false
  362. if state == Sleeping {
  363. b.Dispatch(WakeUpEvent, nil)
  364. }
  365. }
  366. // Sleep forces the body to sleep.
  367. func (b *Body) Sleep() {
  368. b.sleepState = Sleeping
  369. b.velocity.Set(0, 0, 0)
  370. b.angularVelocity.Set(0, 0, 0)
  371. b.wakeUpAfterNarrowphase = false
  372. }
  373. // Called every timestep to update internal sleep timer and change sleep state if needed.
  374. // time: The world time in seconds
  375. func (b *Body) SleepTick(time float32) {
  376. if b.allowSleep {
  377. speedSquared := b.velocity.LengthSq() + b.angularVelocity.LengthSq()
  378. speedLimitSquared := math32.Pow(b.sleepSpeedLimit, 2)
  379. if b.sleepState == Awake && speedSquared < speedLimitSquared {
  380. b.sleepState = Sleepy
  381. b.timeLastSleepy = time
  382. b.Dispatch(SleepyEvent, nil)
  383. } else if b.sleepState == Sleepy && speedSquared > speedLimitSquared {
  384. b.WakeUp() // Wake up
  385. } else if b.sleepState == Sleepy && (time-b.timeLastSleepy) > b.sleepTimeLimit {
  386. b.Sleep() // Sleeping
  387. b.Dispatch(SleepEvent, nil)
  388. }
  389. }
  390. }
  391. // If checkSleeping is true then returns false if both bodies are currently sleeping.
  392. func (b *Body) Sleeping() bool {
  393. return b.sleepState == Sleeping
  394. }
  395. // CollidableWith returns whether the body can collide with the specified body.
  396. func (b *Body) CollidableWith(other *Body) bool {
  397. if (b.colFilterGroup & other.colFilterMask == 0) ||
  398. (other.colFilterGroup & b.colFilterMask == 0) ||
  399. (b.bodyType == Static) && (other.bodyType == Static) {
  400. return false
  401. }
  402. return true
  403. }
  404. func (b *Body) CollisionResponse() bool {
  405. return b.colResponse
  406. }
  407. // PointToLocal converts a world point to local body frame. TODO maybe move to Node
  408. func (b *Body) PointToLocal(worldPoint *math32.Vector3) math32.Vector3 {
  409. return *worldPoint.Clone().Sub(b.position).ApplyQuaternion(b.quaternion.Conjugate())
  410. }
  411. // VectorToLocal converts a world vector to local body frame. TODO maybe move to Node
  412. func (b *Body) VectorToLocal(worldVector *math32.Vector3) math32.Vector3 {
  413. return *worldVector.Clone().ApplyQuaternion(b.quaternion.Conjugate())
  414. }
  415. // PointToWorld converts a local point to world frame. TODO maybe move to Node
  416. func (b *Body) PointToWorld(localPoint *math32.Vector3) math32.Vector3 {
  417. return *localPoint.Clone().ApplyQuaternion(b.quaternion).Add(b.position)
  418. }
  419. // VectorToWorld converts a local vector to world frame. TODO maybe move to Node
  420. func (b *Body) VectorToWorld(localVector *math32.Vector3) math32.Vector3 {
  421. return *localVector.Clone().ApplyQuaternion(b.quaternion)
  422. }
  423. // UpdateEffectiveMassProperties
  424. // If the body is sleeping, it should be immovable and thus have infinite mass during solve.
  425. // This is solved by having a separate "effective mass" and other "effective" properties
  426. func (b *Body) UpdateEffectiveMassProperties() {
  427. if b.sleepState == Sleeping || b.bodyType == Kinematic {
  428. b.invMassEff = 0
  429. b.invRotInertiaEff.Zero()
  430. b.invRotInertiaWorldEff.Zero()
  431. } else {
  432. b.invMassEff = b.invMass
  433. b.invRotInertiaEff.Copy(b.invRotInertia)
  434. b.invRotInertiaWorldEff.Copy(b.invRotInertiaWorld)
  435. }
  436. }
  437. // UpdateMassProperties
  438. // Should be called whenever you change the body shape or mass.
  439. func (b *Body) UpdateMassProperties() {
  440. // TODO getter of invMass ?
  441. if b.mass > 0 {
  442. b.invMass = 1.0 / b.mass
  443. } else {
  444. b.invMass = 0
  445. }
  446. if b.fixedRotation {
  447. b.rotInertia.Zero()
  448. b.invRotInertia.Zero()
  449. } else {
  450. *b.rotInertia = b.GetGeometry().RotationalInertia()
  451. b.rotInertia.MultiplyScalar(1000) // multiply by high density // TODO remove this ?
  452. b.invRotInertia.GetInverse(b.rotInertia) // Note: rotInertia is always positive definite and thus always invertible
  453. }
  454. b.UpdateInertiaWorld(true)
  455. }
  456. // Update .inertiaWorld and .invRotInertiaWorld
  457. func (b *Body) UpdateInertiaWorld(force bool) {
  458. iRI := b.invRotInertia
  459. // If rotational inertia M = s*I, where I is identity and s a scalar, then
  460. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  461. // where R is the rotation matrix.
  462. // In other words, we don't have to do the transformation if all diagonal entries are equal.
  463. if iRI[0] != iRI[4] || iRI[4] != iRI[8] || force {
  464. // iRIW = R * iRI * R'
  465. m1 := math32.NewMatrix3().MakeRotationFromQuaternion(b.quaternion)
  466. m2 := m1.Clone().Transpose()
  467. m2.Multiply(iRI)
  468. b.invRotInertiaWorld.MultiplyMatrices(m2, m1)
  469. }
  470. }
  471. // Forces from a force field need to be multiplied by mass.
  472. func (b *Body) ApplyForceField(force *math32.Vector3) {
  473. b.force.Add(force.MultiplyScalar(b.mass))
  474. }
  475. // Apply force to a world point.
  476. // This could for example be a point on the Body surface.
  477. // Applying force this way will add to Body.force and Body.torque.
  478. // relativePoint: A point relative to the center of mass to apply the force on.
  479. func (b *Body) ApplyForce(force, relativePoint *math32.Vector3) {
  480. if b.bodyType != Dynamic { // Needed?
  481. return
  482. }
  483. // Add linear force
  484. b.force.Add(force) // TODO shouldn't rotational momentum be subtracted from linear momentum?
  485. // Add rotational force
  486. b.torque.Add(math32.NewVec3().CrossVectors(relativePoint, force))
  487. }
  488. // Apply force to a local point in the body.
  489. // force: The force vector to apply, defined locally in the body frame.
  490. // localPoint: A local point in the body to apply the force on.
  491. func (b *Body) ApplyLocalForce(localForce, localPoint *math32.Vector3) {
  492. if b.bodyType != Dynamic {
  493. return
  494. }
  495. // Transform the force vector to world space
  496. worldForce := b.VectorToWorld(localForce)
  497. relativePointWorld := b.VectorToWorld(localPoint)
  498. b.ApplyForce(&worldForce, &relativePointWorld)
  499. }
  500. // Apply impulse to a world point.
  501. // This could for example be a point on the Body surface.
  502. // An impulse is a force added to a body during a short period of time (impulse = force * time).
  503. // Impulses will be added to Body.velocity and Body.angularVelocity.
  504. // impulse: The amount of impulse to add.
  505. // relativePoint: A point relative to the center of mass to apply the force on.
  506. func (b *Body) ApplyImpulse(impulse, relativePoint *math32.Vector3) {
  507. if b.bodyType != Dynamic {
  508. return
  509. }
  510. // Compute point position relative to the body center
  511. r := relativePoint
  512. // Compute produced central impulse velocity
  513. velo := impulse.Clone().MultiplyScalar(b.invMass)
  514. // Add linear impulse
  515. b.velocity.Add(velo)
  516. // Compute produced rotational impulse velocity
  517. rotVelo := math32.NewVec3().CrossVectors(r, impulse)
  518. rotVelo.ApplyMatrix3(b.invRotInertiaWorld)
  519. // Add rotational Impulse
  520. b.angularVelocity.Add(rotVelo)
  521. }
  522. // Apply locally-defined impulse to a local point in the body.
  523. // force: The force vector to apply, defined locally in the body frame.
  524. // localPoint: A local point in the body to apply the force on.
  525. func (b *Body) ApplyLocalImpulse(localImpulse, localPoint *math32.Vector3) {
  526. if b.bodyType != Dynamic {
  527. return
  528. }
  529. // Transform the force vector to world space
  530. worldImpulse := b.VectorToWorld(localImpulse)
  531. relativePointWorld := b.VectorToWorld(localPoint)
  532. b.ApplyImpulse(&worldImpulse, &relativePointWorld)
  533. }
  534. // Get world velocity of a point in the body.
  535. func (b *Body) GetVelocityAtWorldPoint(worldPoint *math32.Vector3) *math32.Vector3 {
  536. r := math32.NewVec3().SubVectors(worldPoint, b.position)
  537. r.CrossVectors(b.angularVelocity, r)
  538. r.Add(b.velocity)
  539. return r
  540. }
  541. // Move the body forward in time.
  542. // dt: Time step
  543. // quatNormalize: Set to true to normalize the body quaternion
  544. // quatNormalizeFast: If the quaternion should be normalized using "fast" quaternion normalization
  545. func (b *Body) Integrate(dt float32, quatNormalize, quatNormalizeFast bool) {
  546. // Save previous position and rotation
  547. b.prevPosition.Copy(b.position)
  548. b.prevQuaternion.Copy(b.quaternion)
  549. // If static or sleeping - skip
  550. if !(b.bodyType == Dynamic || b.bodyType == Kinematic) || b.sleepState == Sleeping {
  551. return
  552. }
  553. // Integrate force over mass (acceleration) to obtain estimate for instantaneous velocities
  554. iMdt := b.invMass * dt
  555. b.velocity.X += b.force.X * iMdt * b.linearFactor.X
  556. b.velocity.Y += b.force.Y * iMdt * b.linearFactor.Y
  557. b.velocity.Z += b.force.Z * iMdt * b.linearFactor.Z
  558. // Integrate inverse angular mass times torque to obtain estimate for instantaneous angular velocities
  559. e := b.invRotInertiaWorld
  560. tx := b.torque.X * b.angularFactor.X
  561. ty := b.torque.Y * b.angularFactor.Y
  562. tz := b.torque.Z * b.angularFactor.Z
  563. b.angularVelocity.X += dt * (e[0]*tx + e[3]*ty + e[6]*tz)
  564. b.angularVelocity.Y += dt * (e[1]*tx + e[4]*ty + e[7]*tz)
  565. b.angularVelocity.Z += dt * (e[2]*tx + e[5]*ty + e[8]*tz)
  566. // Integrate velocity to obtain estimate for position
  567. b.position.X += b.velocity.X * dt
  568. b.position.Y += b.velocity.Y * dt
  569. b.position.Z += b.velocity.Z * dt
  570. // Integrate angular velocity to obtain estimate for rotation
  571. ax := b.angularVelocity.X * b.angularFactor.X
  572. ay := b.angularVelocity.Y * b.angularFactor.Y
  573. az := b.angularVelocity.Z * b.angularFactor.Z
  574. bx := b.quaternion.X
  575. by := b.quaternion.Y
  576. bz := b.quaternion.Z
  577. bw := b.quaternion.W
  578. halfDt := dt * 0.5
  579. b.quaternion.X += halfDt * (ax*bw + ay*bz - az*by)
  580. b.quaternion.Y += halfDt * (ay*bw + az*bx - ax*bz)
  581. b.quaternion.Z += halfDt * (az*bw + ax*by - ay*bx)
  582. b.quaternion.W += halfDt * (-ax*bx - ay*by - az*bz)
  583. // Normalize quaternion
  584. b.quaternion.Normalize()
  585. //if quatNormalize { // TODO future
  586. // if quatNormalizeFast {
  587. // b.quaternion.NormalizeFast()
  588. // } else {
  589. // b.quaternion.Normalize()
  590. // }
  591. //}
  592. // Update position and rotation of Node (containing visual representation of the body)
  593. b.GetNode().SetPositionVec(b.position)
  594. b.GetNode().SetRotationQuat(b.quaternion)
  595. b.aabbNeedsUpdate = true
  596. // Update world inertia
  597. b.UpdateInertiaWorld(false)
  598. }