-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcomponent_animation.go
More file actions
492 lines (418 loc) · 13.3 KB
/
component_animation.go
File metadata and controls
492 lines (418 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
* Copyright (c) 2021 The XGo Authors (xgo.dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spx
import (
"maps"
"math"
"github.com/goplus/spbase/mathf"
"github.com/goplus/spx/v2/internal/base/defaults"
coreproject "github.com/goplus/spx/v2/internal/core/project"
"github.com/goplus/spx/v2/internal/engine"
spxlog "github.com/goplus/spx/v2/internal/log"
"github.com/goplus/spx/v2/internal/time"
"github.com/goplus/spx/v2/internal/tools"
)
// sharedAnimationData contains read-only animation data shared across cloned sprites (Flyweight Pattern).
type sharedAnimationData struct {
animations map[SpriteAnimationName]*coreproject.AniConfig
animBindings map[string]string
defaultAnimation SpriteAnimationName
animationWrappers map[SpriteAnimationName]*animationWrapper
}
type animationComponent struct {
componentBase
// Shared animation configuration (read-only, shared across clones)
shared *sharedAnimationData
// Animation state (per-instance)
curAnimState *animState
curTweenState *animState
// Animation tracking (per-instance)
donedAnimations []string
}
// initialize initializes the animation component from configuration.
func (a *animationComponent) initialize(sprite *SpriteImpl, spriteCfg *coreproject.SpriteConfig) {
a.componentBase.initialize(sprite, spriteCfg)
a.initFromConfig(spriteCfg)
a.donedAnimations = make([]string, 0)
}
// initFromConfig initializes animations from sprite configuration.
func (a *animationComponent) initFromConfig(spriteCfg *coreproject.SpriteConfig) {
a.shared = &sharedAnimationData{
defaultAnimation: spriteCfg.DefaultAnimation,
animations: make(map[SpriteAnimationName]*coreproject.AniConfig),
animBindings: make(map[string]string),
animationWrappers: make(map[SpriteAnimationName]*animationWrapper),
}
anims := spriteCfg.FAnimations
for key, val := range anims {
var ani = val
_, ok := a.shared.animations[key]
if ok {
spxlog.Panicf("animation key [%s] already exists", key)
}
defaults.SetDefaultIfZero(&ani.FrameFps, 25)
defaults.SetDefaultIfZero(&ani.TurnToDuration, 1.0)
defaults.SetDefaultIfZero(&ani.StepDuration, 0.01)
ani.IFrameFrom, ani.IFrameTo = a.frameRange(ani.FrameFrom, ani.FrameTo)
ani.Speed = 1
ani.Duration = (math.Abs(float64(ani.IFrameFrom-ani.IFrameTo)) + 1) / float64(ani.FrameFps)
a.shared.animations[key] = ani
}
maps.Copy(a.shared.animBindings, spriteCfg.AnimBindings)
for animName, ani := range a.shared.animations {
a.shared.animationWrappers[animName] = &animationWrapper{
spriteName: a.sprite.name,
ani: ani,
costumes: a.sprite.costumes,
isCostumeSet: a.sprite.runtimeState.IsCostumeSet,
engineMgr: a.engine(),
}
}
}
// cloneFrom creates a new animation component by cloning from source.
func (a *animationComponent) cloneFrom(src component, newSprite *SpriteImpl) component {
srcAnim := src.(*animationComponent)
newAnim := &animationComponent{
componentBase: componentBase{sprite: newSprite},
shared: srcAnim.shared,
donedAnimations: make([]string, 0),
}
return newAnim
}
// onDestroy cleanup when component is destroyed.
func (a *animationComponent) onDestroy() {
a.stopAnimState(a.curAnimState)
a.stopAnimState(a.curTweenState)
a.unRegisterOnAnimationLooped()
a.unRegisterOnAnimationFinished()
}
func (a *animationComponent) syncSprite() *engine.Sprite {
if a.sprite == nil {
return nil
}
return a.sprite.runtimeState.SyncSprite
}
func (a *animationComponent) syncSpriteForPlayback() *engine.Sprite {
if a.sprite == nil || a.sprite.isDestroyed() {
return nil
}
return a.sprite.runtimeState.SyncSprite
}
func (a *animationComponent) registerOnAnimationLooped(f func()) {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.RegisterOnAnimationLooped(f)
}
}
func (a *animationComponent) unRegisterOnAnimationLooped() {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.UnRegisterOnAnimationLooped()
}
}
func (a *animationComponent) registerOnAnimationFinished(f func()) {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.RegisterOnAnimationFinished(f)
}
}
func (a *animationComponent) unRegisterOnAnimationFinished() {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.UnRegisterOnAnimationFinished()
}
}
func (a *animationComponent) Animate(name SpriteAnimationName, loop bool) {
a.playAnimation(name, loop, false, "==> Animation %s")
}
func (a *animationComponent) AnimateAndWait(name SpriteAnimationName) {
a.playAnimation(name, false, true, "==> AnimateAndWait %s")
}
func (a *animationComponent) StopAnimation(name SpriteAnimationName) {
if name == "" || !a.hasAnim(name) {
return
}
if a.curAnimState == nil || a.curAnimState.Name != name {
return
}
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return
}
syncSprite.PauseAnim()
a.playDefaultAnim()
}
func (a *animationComponent) playAnimation(name SpriteAnimationName, loop, blocking bool, debugMsg string) {
if isDebugInstrEnabled() {
spxlog.Debug(debugMsg, name)
}
ani, ok := a.shared.animations[name]
if !ok {
spxlog.Warn("Animation not found: %s", name)
return
}
a.doAnimation(name, ani, loop, 1, blocking, true)
}
func (a *animationComponent) doAnimation(animName SpriteAnimationName, ani *coreproject.AniConfig, loop bool, speed float64, isBlocking bool, playAudio bool) {
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return
}
a.stopAnimState(a.curAnimState)
a.curAnimState = &animState{
AniType: coreproject.AniTypeFrame,
Name: animName,
Speed: speed,
}
info := a.curAnimState
if playAudio {
a.playAnimAudio(ani, info)
}
a.sprite.baseObj.applyCostumeUpdate()
a.prepareAnimationPlayback(animName, ani)
a.engine().SpriteMgr.PlayAnim(syncSprite.GetId(), animName, speed, loop, false)
if isBlocking {
a.sprite.runtimeState.IsAnimating = true
for a.engine().SpriteMgr.IsPlayingAnim(syncSprite.GetId()) {
if info.IsCanceled {
break
}
engine.WaitNextFrame()
}
a.sprite.runtimeState.IsAnimating = false
a.stopAnimState(info)
}
}
func (a *animationComponent) playDefaultAnim() {
animName := ""
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return
}
if !a.sprite.spriteState.IsVisible || a.sprite.spriteState.IsDying {
return
}
speed := 1.0
if a.curTweenState == nil {
animName = a.shared.defaultAnimation
} else {
switch a.curTweenState.AniType {
case coreproject.AniTypeMove:
animName = a.sprite.getStateAnimName(StateStep)
case coreproject.AniTypeTurn:
animName = a.sprite.getStateAnimName(StateTurn)
case coreproject.AniTypeGlide:
animName = a.sprite.getStateAnimName(StateGlide)
}
speed = a.curTweenState.Speed
}
if animName == "" {
animName = a.shared.defaultAnimation
}
if ani, ok := a.shared.animations[animName]; ok {
a.prepareAnimationPlayback(animName, ani)
a.engine().SpriteMgr.PlayAnim(syncSprite.GetId(), animName, speed, true, false)
} else {
a.sprite.goSetCostume(a.sprite.spriteState.DefaultCostumeIndex)
}
}
func (a *animationComponent) playAnimAudio(ani *coreproject.AniConfig, info *animState) {
if ani.OnStart != nil && ani.OnStart.Play != "" {
info.AudioName = ani.OnStart.Play
a.sprite.playAudio(info.AudioName, false)
}
}
func (a *animationComponent) adaptAnimBitmapResolution(ani *coreproject.AniConfig) {
syncSprite := a.syncSprite()
if syncSprite == nil {
return
}
renderScale := a.sprite.getAnimRenderScale(ani.AdaptAnimBitmapResolution)
syncSprite.SetRenderScale(engine.UniformVec2(renderScale))
}
func (a *animationComponent) prepareAnimationPlayback(animName SpriteAnimationName, ani *coreproject.AniConfig) {
a.shared.animationWrappers[animName].ensureRegistered(animName, ani)
a.adaptAnimBitmapResolution(ani)
}
func (a *animationComponent) onAnimationDone(animName string) {
if a.syncSpriteForPlayback() == nil {
return
}
if a.curAnimState != nil && a.curAnimState.Name == animName {
a.playDefaultAnim()
}
}
func (a *animationComponent) stopAnimState(state *animState) {
if state == nil {
return
}
state.IsCanceled = true
}
func (a *animationComponent) costumeIndex(nameOrIndex any) int {
switch v := nameOrIndex.(type) {
case SpriteCostumeName:
idx := a.sprite.findCostume(v)
if idx < 0 {
spxlog.Panicf("findCostume %s failed", v)
}
return idx
default:
val, _ := tools.GetFloat(nameOrIndex)
return int(val)
}
}
func (a *animationComponent) frameRange(from, to any) (int, int) {
return a.costumeIndex(from), a.costumeIndex(to)
}
func (a *animationComponent) hasAnim(animName string) bool {
_, ok := a.shared.animations[animName]
return ok
}
func (a *animationComponent) getAnimation(animName SpriteAnimationName) (*coreproject.AniConfig, bool) {
ani, ok := a.shared.animations[animName]
return ani, ok
}
func (a *animationComponent) getStateAnimName(stateName string) string {
if bindingName, ok := a.shared.animBindings[stateName]; ok {
return bindingName
}
return stateName
}
func (a *animationComponent) addDonedAnimation(animName string) {
a.donedAnimations = append(a.donedAnimations, animName)
}
func (a *animationComponent) takeDonedAnimations(buffer []string) []string {
buffer = append(buffer, a.donedAnimations...)
a.donedAnimations = a.donedAnimations[:0]
return buffer
}
func (a *animationComponent) getCurAnimState() *animState {
return a.curAnimState
}
func (a *animationComponent) getCurTweenState() *animState {
return a.curTweenState
}
// tweenParams holds pre-calculated parameters for tween animations.
type tweenParams struct {
moveDiff mathf.Vec2
moveSpeed float64
moveDir mathf.Vec2
turnDiff float64
}
func (a *animationComponent) doTween(name SpriteAnimationName, ani *coreproject.AniConfig) {
info := a.initTweenState(name, ani)
if info == nil {
return
}
params, ok := a.prepareTweenParams(ani)
if !ok {
return
}
a.executeTweenLoop(info, ani, params)
a.cleanupTween(info, name, ani)
}
func (a *animationComponent) initTweenState(name SpriteAnimationName, ani *coreproject.AniConfig) *animState {
info := &animState{
AniType: ani.AniType,
Name: name,
Speed: ani.Speed,
}
a.stopAnimState(a.curTweenState)
a.curTweenState = info
if a.hasAnim(name) {
a.doAnimation(name, ani, ani.IsLoop, ani.Speed, false, false)
a.playAnimAudio(ani, info)
}
if ani.Duration <= 0 {
spxlog.Warn("Invalid animation duration: %v", ani.Duration)
return nil
}
return info
}
func (a *animationComponent) prepareTweenParams(ani *coreproject.AniConfig) (*tweenParams, bool) {
params := &tweenParams{}
duration := ani.Duration
switch ani.AniType {
case coreproject.AniTypeMove, coreproject.AniTypeGlide:
src, srcOk := tools.GetVec2(ani.From)
dst, dstOk := tools.GetVec2(ani.To)
if !srcOk || !dstOk {
spxlog.Warn("Invalid 'From' or 'To' for move/glide animation: not a *mathf.Vec2")
return nil, false
}
params.moveDiff = dst.Sub(src)
if ani.AniType == coreproject.AniTypeMove {
params.moveSpeed = params.moveDiff.Length() / duration
params.moveDir = params.moveDiff.Normalize()
}
case coreproject.AniTypeTurn:
src, srcOk := tools.GetFloat(ani.From)
dst, dstOk := tools.GetFloat(ani.To)
if !srcOk || !dstOk {
spxlog.Warn("Invalid 'From' or 'To' for turn animation: not a float")
return nil, false
}
params.turnDiff = dst - src
}
return params, true
}
func (a *animationComponent) executeTweenLoop(info *animState, ani *coreproject.AniConfig, params *tweenParams) {
timer := 0.0
prePercent := 0.0
duration := ani.Duration
for timer < duration {
if info.IsCanceled {
return
}
timer += time.DeltaTime()
percent := mathf.Clamp01f(timer / duration)
deltaPercent := percent - prePercent
prePercent = percent
a.applyTweenStep(ani.AniType, deltaPercent, params)
engine.WaitNextFrame()
}
}
func (a *animationComponent) applyTweenStep(aniType coreproject.AniType, deltaPercent float64, params *tweenParams) {
switch aniType {
case coreproject.AniTypeMove:
physicsMode := a.sprite.PhysicsMode()
if isPhysicsEnabled() && physicsMode != NoPhysics && physicsMode != StaticPhysics {
vel := params.moveDir.Mulf(params.moveSpeed)
a.sprite.SetVelocity(vel.X, vel.Y)
} else {
val := params.moveDiff.Mulf(deltaPercent)
a.sprite.ChangeXYpos(val.X, val.Y)
}
case coreproject.AniTypeGlide:
val := params.moveDiff.Mulf(deltaPercent)
a.sprite.ChangeXYpos(val.X, val.Y)
case coreproject.AniTypeTurn:
val := params.turnDiff * deltaPercent
a.sprite.ChangeHeading(val)
}
}
func (a *animationComponent) cleanupTween(info *animState, name SpriteAnimationName, ani *coreproject.AniConfig) {
if ani.AniType == coreproject.AniTypeMove {
physicsMode := a.sprite.PhysicsMode()
if isPhysicsEnabled() && physicsMode != NoPhysics && physicsMode != StaticPhysics {
a.sprite.SetVelocity(0, 0)
}
}
a.stopAnimState(info)
if a.curTweenState != info {
return
}
a.curTweenState = nil
if name != a.shared.defaultAnimation && !ani.IsKeepOnStop {
a.playDefaultAnim()
}
}