animation.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 collada
  5. import (
  6. "fmt"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/math32"
  9. "strings"
  10. )
  11. // AnimationTarget contains all animation channels for an specific target node
  12. type AnimationTarget struct {
  13. target core.INode
  14. matrix math32.Matrix4 // original node transformation matrix
  15. start float32 // initial input offset value
  16. last float32 // last input value
  17. minInput float32 // minimum input value for all channels
  18. maxInput float32 // maximum input value for all channels
  19. loop bool // animation loop flag
  20. rot math32.Vector3 // rotation in XYZ Euler angles
  21. channels []*ChannelInstance
  22. }
  23. // A ChannelInstance associates an animation parameter channel to an interpolation sampler
  24. type ChannelInstance struct {
  25. sampler *SamplerInstance
  26. action ActionFunc
  27. }
  28. // SamplerInstance specifies the input key frames, output values for these key frames
  29. // and interpolation information. It can be shared by more than one animation
  30. type SamplerInstance struct {
  31. Input []float32 // Input keys (usually time)
  32. Output []float32 // Outputs values for the keys
  33. Interp []string // Names of interpolation functions for each key frame
  34. InTangent []float32 // Origin tangents for Bezier interpolation
  35. OutTangent []float32 // End tangents for Bezier interpolation
  36. }
  37. // ActionFunc is the type for all functions that execute an specific parameter animation
  38. type ActionFunc func(at *AnimationTarget, v float32)
  39. // Reset resets the animation from the beginning
  40. func (at *AnimationTarget) Reset() {
  41. at.last = at.start
  42. at.target.GetNode().SetMatrix(&at.matrix)
  43. }
  44. // SetLoop sets the state of the animation loop flag
  45. func (at *AnimationTarget) SetLoop(loop bool) {
  46. at.loop = loop
  47. }
  48. func (at *AnimationTarget) SetStart(v float32) {
  49. at.start = v
  50. }
  51. // Update interpolates the specified input value for each animation target channel
  52. // and executes its corresponding action function. Returns true if the input value
  53. // is inside the key frames ranges or false otherwise.
  54. func (at *AnimationTarget) Update(delta float32) bool {
  55. // Checks if input is less than minimum
  56. at.last = at.last + delta
  57. if at.last < at.minInput {
  58. return false
  59. }
  60. // Checks if input is greater than maximum
  61. if at.last > at.maxInput {
  62. if at.loop {
  63. at.Reset()
  64. } else {
  65. return false
  66. }
  67. }
  68. for i := 0; i < len(at.channels); i++ {
  69. ch := at.channels[i]
  70. // Get interpolated value
  71. v, ok := ch.sampler.Interpolate(at.last)
  72. if !ok {
  73. return false
  74. }
  75. // Call action func
  76. ch.action(at, v)
  77. // Sets final rotation
  78. at.target.GetNode().SetRotation(at.rot.X, at.rot.Y, at.rot.Z)
  79. }
  80. return true
  81. }
  82. // NewAnimationTargets creates and returns a map of all animation targets
  83. // contained in the decoded Collada document and for the previously decoded scene.
  84. // The map is indexed by the node loaderID.
  85. func (d *Decoder) NewAnimationTargets(scene core.INode) (map[string]*AnimationTarget, error) {
  86. // Maps target node to its animation target instance
  87. targetsMap := make(map[string]*AnimationTarget)
  88. // For each Collada animation element
  89. for _, ca := range d.dom.LibraryAnimations.Animation {
  90. // For each Collada channel for this animation
  91. for _, cc := range ca.Channel {
  92. // Separates the channel target in target id and target action
  93. parts := strings.Split(cc.Target, "/")
  94. if len(parts) < 2 {
  95. return nil, fmt.Errorf("Channel target invalid")
  96. }
  97. targetID := parts[0]
  98. targetAction := parts[1]
  99. // Get the target node object referenced by the target id from the specified scene.
  100. target := scene.GetNode().FindLoaderID(targetID)
  101. if target == nil {
  102. return nil, fmt.Errorf("Target node id:%s not found", targetID)
  103. }
  104. // Get reference to the AnimationTarget for this target in the local map
  105. // If not found creates the animation target and inserts in the map
  106. at := targetsMap[targetID]
  107. if at == nil {
  108. at = new(AnimationTarget)
  109. at.target = target
  110. at.matrix = target.GetNode().Matrix()
  111. targetsMap[targetID] = at
  112. }
  113. // Creates the sampler instance specified from the channel source
  114. si, err := NewSamplerInstance(ca, cc.Source)
  115. if err != nil {
  116. return nil, err
  117. }
  118. // Sets the action function from the target action
  119. var af ActionFunc
  120. switch targetAction {
  121. case "location.X":
  122. af = actionPositionX
  123. case "location.Y":
  124. af = actionPositionY
  125. case "location.Z":
  126. af = actionPositionZ
  127. case "rotationX.ANGLE":
  128. af = actionRotationX
  129. case "rotationY.ANGLE":
  130. af = actionRotationY
  131. case "rotationZ.ANGLE":
  132. af = actionRotationZ
  133. case "scale.X":
  134. af = actionScaleX
  135. case "scale.Y":
  136. af = actionScaleY
  137. case "scale.Z":
  138. af = actionScaleZ
  139. default:
  140. return nil, fmt.Errorf("Unsupported channel target action:%s", targetAction)
  141. }
  142. // Creates the channel instance for this sampler and target action and adds it
  143. // to the current AnimationTarget
  144. ci := &ChannelInstance{si, af}
  145. at.channels = append(at.channels, ci)
  146. }
  147. }
  148. // Set minimum and maximum input values for each animation target
  149. for _, at := range targetsMap {
  150. at.minInput = math32.Infinity
  151. at.maxInput = -math32.Infinity
  152. for _, ch := range at.channels {
  153. // First key frame input
  154. inp := ch.sampler.Input[0]
  155. if inp < at.minInput {
  156. at.minInput = inp
  157. }
  158. // Last key frame input
  159. inp = ch.sampler.Input[len(ch.sampler.Input)-1]
  160. if inp > at.maxInput {
  161. at.maxInput = inp
  162. }
  163. }
  164. }
  165. return targetsMap, nil
  166. }
  167. func actionPositionX(at *AnimationTarget, v float32) {
  168. at.target.GetNode().SetPositionX(v)
  169. }
  170. func actionPositionY(at *AnimationTarget, v float32) {
  171. at.target.GetNode().SetPositionY(v)
  172. }
  173. func actionPositionZ(at *AnimationTarget, v float32) {
  174. at.target.GetNode().SetPositionZ(v)
  175. }
  176. func actionRotationX(at *AnimationTarget, v float32) {
  177. at.rot.X = math32.DegToRad(v)
  178. }
  179. func actionRotationY(at *AnimationTarget, v float32) {
  180. at.rot.Y = math32.DegToRad(v)
  181. }
  182. func actionRotationZ(at *AnimationTarget, v float32) {
  183. at.rot.Z = math32.DegToRad(v)
  184. }
  185. func actionScaleX(at *AnimationTarget, v float32) {
  186. at.target.GetNode().SetScaleX(v)
  187. }
  188. func actionScaleY(at *AnimationTarget, v float32) {
  189. at.target.GetNode().SetScaleY(v)
  190. }
  191. func actionScaleZ(at *AnimationTarget, v float32) {
  192. at.target.GetNode().SetScaleZ(v)
  193. }
  194. // NewSampler creates and returns a pointer to a new SamplerInstance built
  195. // with data from the specified Collada animation and URI
  196. func NewSamplerInstance(ca *Animation, uri string) (*SamplerInstance, error) {
  197. id := strings.TrimPrefix(uri, "#")
  198. var cs *Sampler
  199. for _, current := range ca.Sampler {
  200. if current.Id == id {
  201. cs = current
  202. break
  203. }
  204. }
  205. if cs == nil {
  206. return nil, fmt.Errorf("Sampler:%s not found", id)
  207. }
  208. // Get sampler inputs
  209. si := new(SamplerInstance)
  210. for _, inp := range cs.Input {
  211. if inp.Semantic == "INPUT" {
  212. data, err := findSourceFloatArray(ca, inp.Source)
  213. if err != nil {
  214. return nil, err
  215. }
  216. si.Input = data
  217. continue
  218. }
  219. if inp.Semantic == "OUTPUT" {
  220. data, err := findSourceFloatArray(ca, inp.Source)
  221. if err != nil {
  222. return nil, err
  223. }
  224. si.Output = data
  225. continue
  226. }
  227. if inp.Semantic == "INTERPOLATION" {
  228. data, err := findSourceNameArray(ca, inp.Source)
  229. if err != nil {
  230. return nil, err
  231. }
  232. si.Interp = data
  233. continue
  234. }
  235. if inp.Semantic == "IN_TANGENT" {
  236. data, err := findSourceFloatArray(ca, inp.Source)
  237. if err != nil {
  238. return nil, err
  239. }
  240. si.InTangent = data
  241. continue
  242. }
  243. if inp.Semantic == "OUT_TANGENT" {
  244. data, err := findSourceFloatArray(ca, inp.Source)
  245. if err != nil {
  246. return nil, err
  247. }
  248. si.OutTangent = data
  249. continue
  250. }
  251. }
  252. return si, nil
  253. }
  254. // Interpolate returns the interpolated output and its validity
  255. // for this sampler for the specified input.
  256. func (si *SamplerInstance) Interpolate(inp float32) (float32, bool) {
  257. // Test limits
  258. if len(si.Input) < 2 {
  259. return 0, false
  260. }
  261. if inp < si.Input[0] {
  262. return 0, false
  263. }
  264. if inp > si.Input[len(si.Input)-1] {
  265. return 0, false
  266. }
  267. // Find key frame interval
  268. var idx int
  269. for idx = 0; idx < len(si.Input)-1; idx++ {
  270. if inp >= si.Input[idx] && inp < si.Input[idx+1] {
  271. break
  272. }
  273. }
  274. // Checks if interval was found
  275. if idx >= len(si.Input)-1 {
  276. return 0, false
  277. }
  278. switch si.Interp[idx] {
  279. case "STEP":
  280. return si.linearInterp(inp, idx), true
  281. case "LINEAR":
  282. return si.linearInterp(inp, idx), true
  283. case "BEZIER":
  284. return si.bezierInterp(inp, idx), true
  285. case "HERMITE":
  286. return si.linearInterp(inp, idx), true
  287. case "CARDINAL":
  288. return si.linearInterp(inp, idx), true
  289. case "BSPLINE":
  290. return si.linearInterp(inp, idx), true
  291. default:
  292. return 0, false
  293. }
  294. return 0, false
  295. }
  296. func (si *SamplerInstance) linearInterp(inp float32, idx int) float32 {
  297. k1 := si.Input[idx]
  298. k2 := si.Input[idx+1]
  299. v1 := si.Output[idx]
  300. v2 := si.Output[idx+1]
  301. return v1 + (v2-v1)*(inp-k1)/(k2-k1)
  302. }
  303. func (si *SamplerInstance) bezierInterp(inp float32, idx int) float32 {
  304. p0 := si.Output[idx]
  305. p1 := si.Output[idx+1]
  306. c0 := si.OutTangent[2*idx+1]
  307. c1 := si.InTangent[2*(idx+1)+1]
  308. k1 := si.Input[idx]
  309. k2 := si.Input[idx+1]
  310. s := (inp - k1) / (k2 - k1)
  311. out := p0*math32.Pow(1-s, 3) + 3*c0*s*math32.Pow(1-s, 2) + 3*c1*s*s*(1-s) + p1*math32.Pow(s, 3)
  312. return out
  313. }
  314. func findSourceNameArray(ca *Animation, uri string) ([]string, error) {
  315. src := findSource(ca, uri)
  316. if src == nil {
  317. return nil, fmt.Errorf("Source:%s not found", uri)
  318. }
  319. na, ok := src.ArrayElement.(*NameArray)
  320. if !ok {
  321. return nil, fmt.Errorf("Source:%s is not NameArray", uri)
  322. }
  323. return na.Data, nil
  324. }
  325. func findSourceFloatArray(ca *Animation, uri string) ([]float32, error) {
  326. src := findSource(ca, uri)
  327. if src == nil {
  328. return nil, fmt.Errorf("Source:%s not found", uri)
  329. }
  330. fa, ok := src.ArrayElement.(*FloatArray)
  331. if !ok {
  332. return nil, fmt.Errorf("Source:%s is not FloatArray", uri)
  333. }
  334. return fa.Data, nil
  335. }
  336. func findSource(ca *Animation, uri string) *Source {
  337. id := strings.TrimPrefix(uri, "#")
  338. for _, src := range ca.Source {
  339. if src.Id == id {
  340. return src
  341. }
  342. }
  343. return nil
  344. }