Repository navigation
Expand file tree
/
Copy pathinput_pointer_test.go
More file actions
1401 lines (1347 loc) · 51.8 KB
/
Copy pathinput_pointer_test.go
File metadata and controls
1401 lines (1347 loc) · 51.8 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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 (
"fmt"
"math"
"reflect"
"slices"
"testing"
"github.com/goplus/spbase/mathf"
coreproject "github.com/goplus/spx/v4/internal/core/project"
coreruntime "github.com/goplus/spx/v4/internal/core/runtime"
"github.com/goplus/spx/v4/internal/engine/coroutine"
pkgengine "github.com/goplus/spx/v4/pkg/spx/pkg/engine"
)
// Shared drag fixtures.
type dragSpriteMgr struct {
*clickThroughSpriteMgr
hit func(pkgengine.Object, mathf.Vec2) bool
}
func (m *dragSpriteMgr) CheckCollisionWithPoint(id pkgengine.Object, point mathf.Vec2, trigger bool) bool {
if m.hit != nil {
return m.hit(id, point)
}
return m.clickThroughSpriteMgr.CheckCollisionWithPoint(id, point, trigger)
}
func (*dragSpriteMgr) SetTransform(pkgengine.Object, mathf.Vec2, float64, mathf.Vec2, bool, mathf.Vec2) {
}
type dragCameraMgr struct {
pkgengine.ICameraMgr
viewport, world mathf.Rect2
}
func (m *dragCameraMgr) GetViewportRect() mathf.Rect2 { return m.viewport }
func (m *dragCameraMgr) GetGlobalCameraRect() mathf.Rect2 { return m.world }
func setupSpriteDragTest(t *testing.T) (*coroutine.Scheduler, *Game, *SpriteImpl) {
t.Helper()
currentScheduler, game := setupInputFrameGame(t)
game.scene.init()
game.camera = &cameraImpl{g: game}
previousCamera := pkgengine.CameraMgr
pkgengine.CameraMgr = &dragCameraMgr{
viewport: mathf.Rect2{Size: mathf.NewVec2(480, 360)},
world: mathf.Rect2{Position: mathf.NewVec2(-240, -180), Size: mathf.NewVec2(480, 360)},
}
t.Cleanup(func() { pkgengine.CameraMgr = previousCamera })
mgr := setupClickThroughSpriteMgr(t, map[pkgengine.Object]bool{1: true, 2: true})
pkgengine.SpriteMgr = &dragSpriteMgr{clickThroughSpriteMgr: mgr}
sprite := newDragTestSprite(game, "dragged", 1)
sprite.SetDragMode(Draggable)
game.scene.add(sprite)
return currentScheduler, game, sprite
}
func newDragTestSprite(game *Game, name string, id pkgengine.Object) *SpriteImpl {
sprite := newClickTestSprite(game, name, id, false)
sprite.components.initComponents(sprite, &coreproject.SpriteConfig{X: 10, Y: 20, RotationStyle: "normal"})
sprite.costumes = []*costume{newCostumeWithSize(10, 10)}
sprite.runtimeState.scale = 1
sprite.runtimeState.proxy.OnAnimationLoopedEvent = &pkgengine.Event0{}
sprite.runtimeState.proxy.OnAnimationFinishedEvent = &pkgengine.Event0{}
return sprite
}
func dispatchSpriteDragFrame(currentScheduler *coroutine.Scheduler, game *Game, point mathf.Vec2, events ...event) {
game.inputMgr.frame.dragProjection = game.inputMgr.sampleDragProjection()
game.inputMgr.mousePos = point
game.inputMgr.frame.pending = &inputFrame{events: events}
game.dispatchFrameEvents()
currentScheduler.Update()
}
func assertSpriteDragPosition(t *testing.T, sprite *SpriteImpl, x, y float64) {
t.Helper()
if gotX, gotY := sprite.getXY(); gotX != x || gotY != y {
t.Fatalf("sprite position = (%v, %v), want (%v, %v)", gotX, gotY, x, y)
}
}
// Drag configuration and gesture routing.
func TestSpriteSetDragMode(t *testing.T) {
var sprite SpriteImpl
if sprite.spriteState.isDraggable {
t.Fatal("sprites must default to not draggable")
}
for _, mode := range []DragMode{NotDraggable, DragMode(-1), DragMode(2)} {
sprite.SetDragMode(Draggable)
if !sprite.spriteState.isDraggable {
t.Fatal("draggable mode did not enable dragging")
}
sprite.SetDragMode(mode)
if sprite.spriteState.isDraggable {
t.Fatalf("mode %v did not disable dragging", mode)
}
}
}
func TestSpriteDragModeLoadsAndClones(t *testing.T) {
for _, enabled := range []bool{false, true} {
name := "not draggable"
config := `{"costumes":[{"name":"idle","imageWidth":10,"imageHeight":10}],"isDraggable":false}`
if enabled {
name = "draggable"
config = `{"costumes":[{"name":"idle","imageWidth":10,"imageHeight":10}],"isDraggable":true}`
}
t.Run(name, func(t *testing.T) {
files := gameTestFS{"sprites/owner/index.json": config}
game := setupStageLoadTestGame(t, files)
gamer := reflect.ValueOf(&game.Game).Elem()
sprite := &layoutInterfaceOwnerSprite{}
prepared, err := prepareSprite(files, "owner", reflect.TypeOf(sprite).Elem(), gamer)
if err != nil {
t.Fatal(err)
}
game.loadPreparedSprite(sprite, "owner", gamer, &prepared)
if sprite.spriteState.isDraggable != enabled {
t.Fatalf("loaded draggable = %v, want %v", sprite.spriteState.isDraggable, enabled)
}
var clone SpriteImpl
clone.InitFrom(&sprite.SpriteImpl)
if clone.spriteState.isDraggable != enabled {
t.Fatalf("cloned draggable = %v, want %v", clone.spriteState.isDraggable, enabled)
}
clone.SetDragMode(Draggable)
sprite.SetDragMode(NotDraggable)
if !clone.spriteState.isDraggable || sprite.spriteState.isDraggable {
t.Fatal("changing the original's drag mode affected the clone")
}
})
}
}
func TestSpriteDragFramesPreserveOffsetAndRelease(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
other := newDragTestSprite(game, "foreground", 2)
game.scene.add(other)
other.graphicEffects = map[EffectKind]float64{GhostEffect: 100}
start := mathf.NewVec2(12, 24)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
assertSpriteDragPosition(t, sprite, 10, 20)
if game.inputMgr.drag.active {
t.Fatal("stationary press started a drag")
}
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(42, 64))
assertSpriteDragPosition(t, sprite, 40, 60)
if !game.inputMgr.drag.active {
t.Fatal("pointer movement did not start dragging")
}
shapes := game.scene.getTempShapes()
if shapes[len(shapes)-1] != sprite {
t.Fatal("dragged sprite was not brought to the front")
}
end := mathf.NewVec2(52, 74)
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
assertSpriteDragPosition(t, sprite, 50, 70)
if game.inputMgr.drag.target != nil || game.inputMgr.drag.active {
t.Fatal("release retained the drag")
}
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(80, 90))
assertSpriteDragPosition(t, sprite, 50, 70)
}
func TestSpriteDragClickAndSwipeRouting(t *testing.T) {
for _, moved := range []bool{false, true} {
name := "click"
if moved {
name = "drag"
}
t.Run(name, func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clicks, swipes := 0, 0
sprite.OnClick(func() { clicks++ })
sprite.OnSwipe__0(90, func() { swipes++ })
game.OnClick(func() { t.Error("sprite gesture fell through to stage click") })
game.OnSwipe__0(90, func() { t.Error("sprite drag fell through to stage swipe") })
point := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, point, &eventLeftButtonDown{Pos: point})
if clicks != 0 {
t.Fatal("draggable sprite clicked on mouse down")
}
if moved {
point.X += 100
dispatchSpriteDragFrame(currentScheduler, game, point)
}
dispatchSpriteDragFrame(currentScheduler, game, point, &eventLeftButtonUp{Pos: point})
wantClicks := 1
if moved {
wantClicks = 0
}
if clicks != wantClicks || swipes != 0 {
t.Fatalf("clicks/swipes = %d/%d, want %d/0", clicks, swipes, wantClicks)
}
})
}
}
func TestSpriteDragNonDraggableForegroundDoesNotBlockDrag(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
top := newDragTestSprite(game, "top", 2)
game.scene.add(top)
clicks := 0
top.OnClick(func() { clicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(30, 40))
assertSpriteDragPosition(t, sprite, 30, 40)
assertSpriteDragPosition(t, top, 10, 20)
if clicks != 1 || game.inputMgr.drag.target != sprite || !game.inputMgr.drag.active {
t.Fatal("foreground must click on mouse down without preventing a background drag")
}
}
func TestSpriteDragCandidateDoesNotSuppressForegroundSwipe(t *testing.T) {
for _, change := range []string{"hide", "disable", "viewport jitter"} {
t.Run(change, func(t *testing.T) {
currentScheduler, game, candidate := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
foreground := newDragTestSprite(game, "foreground", 2)
game.scene.add(foreground)
clicks, swipes := 0, 0
foreground.OnClick(func() { clicks++ })
foreground.OnSwipe__0(90, func() { swipes++ })
candidate.OnSwipe__0(90, func() { t.Error("swipe reached the drag candidate") })
game.OnSwipe__0(90, func() { t.Error("foreground swipe reached the stage") })
if change == "viewport jitter" {
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Size = camera.viewport.Size.Divf(.02)
}
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
switch change {
case "hide":
candidate.Hide()
case "disable":
candidate.SetDragMode(NotDraggable)
}
// This swipe spans only two viewport pixels at .02 zoom.
clock.currentTime = .1
end := start.Add(mathf.NewVec2(100, 0))
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
if clicks != 1 || swipes != 1 {
t.Fatalf("foreground clicks/swipes = %d/%d, want 1/1", clicks, swipes)
}
assertSpriteDragPosition(t, candidate, 10, 20)
assertSpriteDragPosition(t, foreground, 10, 20)
})
}
}
func TestSpriteDragCandidateCancellationPreservesForegroundClick(t *testing.T) {
for _, action := range []string{"hide", "disable"} {
t.Run(action, func(t *testing.T) {
currentScheduler, game, candidate := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
foreground := newDragTestSprite(game, "foreground", 2)
game.scene.add(foreground)
clicks := 0
foreground.OnClick(func() { clicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
if clicks != 1 {
t.Fatalf("mouse-down clicks = %d, want 1", clicks)
}
if action == "hide" {
candidate.Hide()
} else {
candidate.SetDragMode(NotDraggable)
}
foreground.SetDragMode(Draggable)
clock.currentTime = .1
end := start.Add(mathf.NewVec2(1, 0))
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
if clicks != 2 {
t.Fatalf("mouse-down and mouse-up clicks = %d, want 2", clicks)
}
})
}
}
// Gesture activation, cancellation and pointer ownership.
func TestSpriteDragCancellation(t *testing.T) {
for _, test := range []struct {
name string
cancel func(*Game, *SpriteImpl)
}{
{"disable and enable", func(_ *Game, s *SpriteImpl) { s.SetDragMode(NotDraggable); s.SetDragMode(Draggable) }},
{"hide and show", func(_ *Game, s *SpriteImpl) { s.Hide(); s.Show() }},
{"destroy", func(_ *Game, s *SpriteImpl) { s.destroy() }},
{"reset input", func(g *Game, _ *SpriteImpl) { g.inputMgr.init(g) }},
} {
for _, active := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/active=%v", test.name, active), func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
other := newDragTestSprite(game, "other", 2)
other.SetDragMode(Draggable)
game.scene.add(other)
other.SetLayerTo(Back)
clicks := 0
sprite.OnClick(func() { clicks++ })
other.OnClick(func() { clicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
want := start
if active {
want = mathf.NewVec2(30, 40)
dispatchSpriteDragFrame(currentScheduler, game, want)
}
test.cancel(game, sprite)
if game.inputMgr.drag != (spriteDragState{}) {
t.Fatal("cancellation retained the drag")
}
other.SetLayerTo(Front)
clock.currentTime = 1
end := mathf.NewVec2(50, 60)
dispatchSpriteDragFrame(currentScheduler, game, end)
if game.inputMgr.drag != (spriteDragState{}) {
t.Fatal("cancelled drag resumed or transferred")
}
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
assertSpriteDragPosition(t, sprite, want.X, want.Y)
assertSpriteDragPosition(t, other, 10, 20)
if clicks != 0 {
t.Fatal("cancelled drag generated a click")
}
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(30, 40))
if game.inputMgr.drag.target != other || !game.inputMgr.drag.active {
t.Fatal("fresh press did not capture the new foreground")
}
})
}
}
}
func TestSpriteDragMovementThresholdUsesViewportPixels(t *testing.T) {
for _, scale := range []float64{0.5, 1, 2} {
t.Run(fmt.Sprint(scale), func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Size = camera.viewport.Size.Divf(scale)
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
for _, dx := range []float64{1, -2, 3} {
dispatchSpriteDragFrame(currentScheduler, game, start.Add(mathf.NewVec2(dx/scale, 0)))
if game.inputMgr.drag.active {
t.Fatalf("%v viewport pixels started a drag", dx)
}
assertSpriteDragPosition(t, sprite, 10, 20)
}
dispatchSpriteDragFrame(currentScheduler, game, start.Add(mathf.NewVec2(3.1/scale, 0)))
if !game.inputMgr.drag.active {
t.Fatal("movement beyond 3 viewport pixels did not start a drag")
}
})
}
}
func TestSpriteDragJitterStillClicks(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
clicks := 0
sprite.OnClick(func() { clicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
end := mathf.NewVec2(12, 22)
dispatchSpriteDragFrame(currentScheduler, game, end)
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
assertSpriteDragPosition(t, sprite, 10, 20)
if clicks != 1 {
t.Fatalf("jitter produced %d clicks, want 1", clicks)
}
}
func TestSpriteDragLongPressUsesInputClock(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{currentTime: 1}
game.inputSlot.session = clock
clicks := 0
sprite.OnClick(func() { clicks++ })
point := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, point, &eventLeftButtonDown{Pos: point})
for _, elapsed := range []float64{-0.1, 0.399, 0.399998, 0.4} {
clock.currentTime = 1 + elapsed
dispatchSpriteDragFrame(currentScheduler, game, point)
if got, want := game.inputMgr.drag.active, elapsed >= 0.4; got != want {
t.Fatalf("active after %v seconds = %v, want %v", elapsed, got, want)
}
}
dispatchSpriteDragFrame(currentScheduler, game, point, &eventLeftButtonUp{Pos: point})
if clicks != 0 {
t.Fatal("stationary long press generated a click")
}
}
func TestSpriteDragLongPressAfterExtendedRecording(t *testing.T) {
for _, tc := range []struct{ fps, start int }{{30, 16174}, {60, 32656}, {30, 21675}, {60, 21663}} {
for _, releaseAtBoundary := range []bool{false, true} {
t.Run(fmt.Sprintf("%dfps/start=%d/release=%v", tc.fps, tc.start, releaseAtBoundary), func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
clicks := 0
sprite.OnClick(func() { clicks++ })
point := mathf.NewVec2(10, 20)
boundary := tc.start + tc.fps*2/5
// Reproduce timestamp rounding in v1 recordings.
for i := 0; i <= boundary; i++ {
if i > 0 {
clock.currentTime += 1 / float64(tc.fps)
}
if i == tc.start {
dispatchSpriteDragFrame(currentScheduler, game, point, &eventLeftButtonDown{Pos: point})
} else if i > tc.start {
var events []event
if releaseAtBoundary && i == boundary {
events = append(events, &eventLeftButtonUp{Pos: point})
}
dispatchSpriteDragFrame(currentScheduler, game, point, events...)
if got, want := game.inputMgr.drag.active, i == boundary && !releaseAtBoundary; got != want {
t.Fatalf("long press after frame %d: active=%v, want %v", i, got, want)
}
}
}
if clicks != 0 {
t.Fatal("long-press release at 400 ms generated a click")
}
})
}
}
}
func TestSpriteDragActivationKeepsPressedTarget(t *testing.T) {
for _, change := range []string{"move", "new draggable foreground", "new non-draggable foreground"} {
t.Run(change, func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
start := mathf.NewVec2(12, 24)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
if game.inputMgr.drag.target != sprite {
t.Fatal("press did not capture the draggable sprite")
}
if change == "move" {
sprite.SetXYpos(20, 30)
} else {
top := newDragTestSprite(game, "new top", 2)
game.scene.add(top)
if change == "new draggable foreground" {
top.SetDragMode(Draggable)
}
}
pkgengine.SpriteMgr.(*dragSpriteMgr).hit = func(_ pkgengine.Object, _ mathf.Vec2) bool {
t.Error("activation repeated hit testing after the press")
return false
}
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(32, 44))
if game.inputMgr.drag.target != sprite || !game.inputMgr.drag.active {
t.Fatal("activation changed or lost the pressed target")
}
wantX, wantY := 30.0, 40.0
if change == "move" {
wantX, wantY = 40, 50
}
assertSpriteDragPosition(t, sprite, wantX, wantY)
shapes := game.scene.getTempShapes()
if shapes[len(shapes)-1] != sprite {
t.Fatal("activated target is not at the front")
}
})
}
}
func TestSpriteDragActivationAfterSpriteLeavesPressPoint(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
sprite.SetXYpos(200, 100)
pkgengine.SpriteMgr.(*dragSpriteMgr).hits[1] = false
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(30, 40))
if !game.inputMgr.drag.active || game.inputMgr.drag.target != sprite {
t.Fatal("activation lost the captured target after it moved")
}
assertSpriteDragPosition(t, sprite, 220, 120)
}
func TestSpriteDragActivationAfterLayerChange(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
other := newDragTestSprite(game, "other", 2)
other.SetDragMode(Draggable)
game.scene.add(other)
other.SetLayerTo(Back)
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
if game.inputMgr.drag.target != sprite {
t.Fatal("press did not pick the original foreground")
}
other.SetLayerTo(Front)
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(30, 40))
if game.inputMgr.drag.target != sprite || !game.inputMgr.drag.active {
t.Fatal("layer change transferred the captured gesture")
}
assertSpriteDragPosition(t, sprite, 30, 40)
assertSpriteDragPosition(t, other, 10, 20)
}
func TestSpriteDragReleaseRepicksTarget(t *testing.T) {
for _, kind := range []string{"draggable", "not draggable", "miss"} {
t.Run(kind, func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
originalClicks, topClicks := 0, 0
sprite.OnClick(func() { originalClicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
top := newDragTestSprite(game, "release target", 2)
top.OnClick(func() { topClicks++ })
game.scene.add(top)
if kind == "draggable" {
top.SetDragMode(Draggable)
}
end := mathf.NewVec2(11, 20)
pkgengine.SpriteMgr.(*dragSpriteMgr).hit = func(_ pkgengine.Object, point mathf.Vec2) bool {
if point != end {
t.Errorf("release picked at %v, want %v", point, end)
}
return kind != "miss"
}
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
wantTop := 0
if kind == "draggable" {
wantTop = 1
}
if originalClicks != 0 || topClicks != wantTop {
t.Fatalf("release clicks = %d/%d, want 0/%d", originalClicks, topClicks, wantTop)
}
})
}
}
func TestSpriteDragCrossTargetRelease(t *testing.T) {
for _, origin := range []string{"sprite", "stage"} {
t.Run(origin, func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
sprite.SetDragMode(NotDraggable)
if origin == "stage" {
sprite.Hide()
}
downClicks, releaseClicks := 0, 0
sprite.OnClick(func() { downClicks++ })
game.OnClick(func() { downClicks++ })
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
if downClicks != 1 {
t.Fatalf("mousedown clicks = %d, want 1", downClicks)
}
top := newDragTestSprite(game, "release target", 2)
top.SetDragMode(Draggable)
top.OnClick(func() { releaseClicks++ })
game.scene.add(top)
clock.currentTime = 0.1
end := mathf.NewVec2(11, 20)
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
clock.currentTime = 0.2
dispatchSpriteDragFrame(currentScheduler, game, end, &eventLeftButtonUp{Pos: end})
if releaseClicks != 1 {
t.Fatalf("cross-target release clicks = %d, want 1", releaseClicks)
}
})
}
}
func TestSpriteDragEmptyPressNeverCapturesLaterTarget(t *testing.T) {
for _, change := range []string{"appears", "enabled"} {
t.Run(change, func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
if change == "appears" {
sprite.Hide()
} else {
sprite.SetDragMode(NotDraggable)
}
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
if game.inputMgr.drag.target != nil {
t.Fatal("press captured an unavailable target")
}
clock.currentTime = .1
dispatchSpriteDragFrame(currentScheduler, game, start.Add(mathf.NewVec2(4, 0)))
sprite.Show()
sprite.SetDragMode(Draggable)
for i, point := range []mathf.Vec2{start, start.Add(mathf.NewVec2(4, 0)), start.Add(mathf.NewVec2(5, 0))} {
clock.currentTime = float64(i+1) * .4
dispatchSpriteDragFrame(currentScheduler, game, point)
if game.inputMgr.drag.target != nil || game.inputMgr.drag.active {
t.Fatalf("empty press captured a later target at step %d", i)
}
}
assertSpriteDragPosition(t, sprite, 10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonUp{Pos: start})
clock.currentTime = 2
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
dispatchSpriteDragFrame(currentScheduler, game, start.Add(mathf.NewVec2(10, 0)))
if game.inputMgr.drag.target != sprite || !game.inputMgr.drag.active {
t.Fatal("a fresh press could not capture the available target")
}
assertSpriteDragPosition(t, sprite, 20, 20)
})
}
}
// Camera motion and coordinate projection.
func TestSpriteDragCameraMotionDoesNotActivate(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
game.inputSlot.session = &inputSession{}
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Position.X += 100
// Keep the pointer stationary in the viewport.
dispatchSpriteDragFrame(currentScheduler, game, start.Add(mathf.NewVec2(100, 0)))
if game.inputMgr.drag.active {
t.Fatal("camera movement activated a stationary pointer")
}
assertSpriteDragPosition(t, sprite, 10, 20)
}
func TestSpriteDragCameraLongPressKeepsCandidateWithoutJump(t *testing.T) {
for _, moveSprite := range []bool{false, true} {
t.Run(fmt.Sprintf("move sprite=%v", moveSprite), func(t *testing.T) {
currentScheduler, game, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
game.inputSlot.session = clock
start := mathf.NewVec2(10, 20)
dispatchSpriteDragFrame(currentScheduler, game, start, &eventLeftButtonDown{Pos: start})
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Position.X += 100
wantX := 10.0
if moveSprite {
wantX = 110
sprite.SetXYpos(wantX, 20)
}
pkgengine.SpriteMgr.(*dragSpriteMgr).hits[1] = false
clock.currentTime = .4
dispatchSpriteDragFrame(currentScheduler, game, mathf.NewVec2(110, 20))
if !game.inputMgr.drag.active || game.inputMgr.drag.target != sprite {
t.Fatal("camera motion lost the pressed candidate")
}
assertSpriteDragPosition(t, sprite, wantX, 20)
})
}
}
func TestSpriteDragFloat32CameraNeverCapturesAfterEmptyPress(t *testing.T) {
currentScheduler, g, sprite := setupSpriteDragTest(t)
clock := &inputSession{}
g.inputSlot.session = clock
mgr := pkgengine.SpriteMgr.(*dragSpriteMgr)
mgr.hits[1] = false
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Position = mathf.NewVec2(-237.13, -180.27)
camera.world.Size = mathf.NewVec2(480/1.37, 360/1.37)
float32Point := func(v mathf.Vec2) mathf.Vec2 {
return mathf.NewVec2(float64(float32(v.X)), float64(float32(v.Y)))
}
pointAtView := func(view mathf.Vec2) mathf.Vec2 {
camera.world.Position = float32Point(camera.world.Position)
camera.world.Size = float32Point(camera.world.Size)
g.inputMgr.frame.dragProjection = g.inputMgr.sampleDragProjection()
return float32Point(g.inputMgr.frame.dragProjection.worldPoint(view))
}
stationary := mathf.NewVec2(250.3, 160.7)
start := pointAtView(stationary)
dispatchSpriteDragFrame(currentScheduler, g, start, &eventLeftButtonDown{Pos: start})
mgr.hits[1] = true
for i := 1; i <= 20; i++ {
camera.world.Position = camera.world.Position.Add(mathf.NewVec2(.13, -.27))
camera.world.Size = camera.world.Size.Mulf(1.001)
clock.currentTime = float64(i) / 10
dispatchSpriteDragFrame(currentScheduler, g, pointAtView(stationary))
if g.inputMgr.drag.target != nil || g.inputMgr.drag.active {
t.Fatalf("float32 camera captured a late sprite at frame %d", i)
}
}
dispatchSpriteDragFrame(currentScheduler, g, pointAtView(stationary.Add(mathf.NewVec2(4, 0))))
if g.inputMgr.drag.target != nil || g.inputMgr.drag.active {
t.Fatal("later pointer movement captured a sprite after an empty press")
}
assertSpriteDragPosition(t, sprite, 10, 20)
}
func TestSpriteDragProjectionFallback(t *testing.T) {
for _, dimension := range []string{"no camera", "world width", "world height", "viewport width", "viewport height"} {
t.Run(dimension, func(t *testing.T) {
_, game, _ := setupSpriteDragTest(t)
camera := pkgengine.CameraMgr.(*dragCameraMgr)
switch dimension {
case "no camera":
game.camera = nil
case "world width":
camera.world.Size.X = 0
case "world height":
camera.world.Size.Y = 0
case "viewport width":
camera.viewport.Size.X = 0
case "viewport height":
camera.viewport.Size.Y = 0
}
projection := game.inputMgr.sampleDragProjection()
point := mathf.NewVec2(10, 20)
if projection != nil || projection.viewportPoint(point) != point || projection.worldPoint(point) != point {
t.Fatal("unavailable projection must preserve world input")
}
})
}
}
// Recording and replaying drag gestures.
func TestSpriteDragRecordingJSONRoundTrip(t *testing.T) {
for _, fps := range []int{10, 30, 60} {
for _, gesture := range []string{"jitter", "movement", "long press", "same tick click", "camera motion", "foreground", "layer change", "cancelled candidate", "empty press", "camera long press", "camera old target"} {
t.Run(fmt.Sprintf("%s/%dfps", gesture, fps), func(t *testing.T) {
resetInputSessionTest(t)
currentScheduler, game, sprite := setupSpriteDragTest(t)
live := setupInputSourceManager(t)
camera := pkgengine.CameraMgr.(*dragCameraMgr)
camera.world.Size = camera.world.Size.Divf(2)
initialCamera := camera.world
mgr := pkgengine.SpriteMgr.(*dragSpriteMgr)
mgr.hit = func(id pkgengine.Object, point mathf.Vec2) bool {
if id == 2 {
return true
}
x, y := sprite.getXY()
return math.Abs(point.X-x) <= 5 && math.Abs(point.Y-y) <= 5
}
if gesture == "foreground" {
game.scene.add(newDragTestSprite(game, "foreground", 2))
}
var other *SpriteImpl
if gesture == "layer change" {
other = newDragTestSprite(game, "other", 2)
other.SetDragMode(Draggable)
game.scene.add(other)
other.SetLayerTo(Back)
}
if gesture == "empty press" {
sprite.SetXYpos(200, 20)
}
applySceneFrame := func(i int) {
if gesture == "layer change" && i == 1 {
other.SetLayerTo(Front)
}
if gesture == "cancelled candidate" && i == 1 {
sprite.Hide()
sprite.Show()
}
if (gesture == "camera motion" || gesture == "camera long press" || gesture == "camera old target") && i == 1 {
camera.world.Position.X += 100
if gesture != "camera old target" {
sprite.SetXYpos(110, 20)
}
}
if gesture == "empty press" && i == fps*2/5+1 {
sprite.SetXYpos(10, 20)
}
}
if _, err := PrepareInputRecording(float64(fps)); err != nil {
t.Fatal(err)
}
claimPreparedSession(t, game)
t.Cleanup(func() { game.abortInputSession("test finished") })
clicks := 0
sprite.OnClick(func() { clicks++ })
type observation struct {
position mathf.Vec2
active bool
clicks int
target string
}
observe := func() observation {
var target string
if candidate := game.inputMgr.drag.target; candidate != nil {
target = candidate.name
}
return observation{mathf.NewVec2(sprite.getXY()), game.inputMgr.drag.active, clicks, target}
}
points := []mathf.Vec2{{X: 10, Y: 20}, {X: 11, Y: 20}, {X: 11, Y: 20}}
switch gesture {
case "movement", "foreground", "layer change", "cancelled candidate":
points = []mathf.Vec2{{X: 10, Y: 20}, {X: 11.5, Y: 20}, {X: 12, Y: 20}, {X: 14, Y: 20}}
case "long press":
points = make([]mathf.Vec2, fps*2/5+2)
for i := range points {
points[i] = mathf.NewVec2(10, 20)
}
case "camera motion":
points = []mathf.Vec2{{X: 10, Y: 20}, {X: 110, Y: 20}, {X: 110, Y: 20}}
case "camera long press", "camera old target", "empty press":
points = make([]mathf.Vec2, fps*2/5+5)
for i := range points {
points[i] = mathf.NewVec2(10, 20)
if gesture != "empty press" && i > 0 {
points[i].X = 110
}
if gesture == "empty press" && i >= fps*2/5+3 {
points[i].X = 14
}
}
case "same tick click":
points = []mathf.Vec2{{X: 10, Y: 20}}
}
var recorded []observation
for i, point := range points {
applySceneFrame(i)
state := InputReplayState{Mouse: InputReplayMouse{X: point.X, Y: point.Y}, Buttons: 1}
var edges []InputReplayMouseEvent
if i == 0 {
edges = append(edges, InputReplayMouseEvent{Button: 1, Pressed: true})
}
if i == len(points)-1 {
state.Buttons = 0
edges = append(edges, InputReplayMouseEvent{Button: 1})
}
// Supply input at the engine sampling boundary.
tick, err := consumeInputTickWithMouseEvents(state, edges, nil, 1/float64(fps))
if err != nil {
t.Fatal(err)
}
batch := &inputFrame{}
game.inputMgr.frame.history.Process(coreruntime.InputFrame{
Point: point, LeftButtonPressed: state.Buttons != 0,
MouseEvents: tick.frame.MouseEvents,
}, batch.eventHooks(0))
dispatchSpriteDragFrame(currentScheduler, game, point, batch.events...)
recorded = append(recorded, observe())
wantActive := false
switch gesture {
case "movement", "foreground", "layer change":
wantActive = i == 2
case "long press":
wantActive = i == fps*2/5
case "camera long press", "camera old target":
wantActive = i >= fps*2/5 && i < len(points)-1
}
if gesture == "camera long press" {
assertSpriteDragPosition(t, sprite, points[i].X, 20)
}
if gesture == "layer change" {
assertSpriteDragPosition(t, other, 10, 20)
if i < len(points)-1 && game.inputMgr.drag.target != sprite {
t.Fatal("layer change transferred the recorded candidate")
}
}
if gesture == "camera old target" || gesture == "cancelled candidate" {
assertSpriteDragPosition(t, sprite, 10, 20)
}
if gesture == "empty press" && i >= fps*2/5+1 && i < fps*2/5+3 {
assertSpriteDragPosition(t, sprite, 10, 20)
}
if game.inputMgr.drag.active != wantActive {
t.Errorf("recording tick %d active=%v, want %v", i, game.inputMgr.drag.active, wantActive)
}
}
wantClicks := 1
switch gesture {
case "movement", "foreground", "layer change", "cancelled candidate", "long press", "camera long press", "camera old target":
wantClicks = 0
}
if clicks != wantClicks {
t.Errorf("recorded clicks=%d, want %d", clicks, wantClicks)
}
encoded, err := FinishInputRecordingJSON()
if err != nil {
t.Fatal(err)
}
replay, err := DecodeInputReplay(encoded)
if err != nil {
t.Fatal(err)
}
for i, frame := range replay.Frames {
if math.Abs(frame.Time-float64(i)/float64(fps)) > 1e-9 {
t.Fatalf("recorded tick %d time=%v", i, frame.Time)
}
if frame.State.Mouse != (InputReplayMouse{X: points[i].X, Y: points[i].Y}) {
t.Fatal("recording changed world coordinates")
}
}
game.abortInputSession("recording finished")
game.lifecycle.reset()
game.inputMgr.init(game)
sprite.SetXYpos(10, 20)
if gesture == "empty press" {
sprite.SetXYpos(200, 20)
}
if gesture == "foreground" {
sprite.SetLayerTo(Back)
}
if other != nil {
other.SetLayerTo(Back)
}
camera.world = initialCamera
clicks = 0
live.point = mathf.NewVec2(-999, -999)
if _, err := PrepareInputReplay(replay); err != nil {
t.Fatal(err)
}
session := claimPreparedSession(t, game)
for i := range replay.Frames {
applySceneFrame(i)
if !game.inputMgr.prepareInputFrame(0.001) {
t.Fatalf("replay tick %d missing", i)
}
game.dispatchFrameEvents()
currentScheduler.Update()
session.endFrame()
if got := observe(); got != recorded[i] {
t.Fatalf("replay tick %d = %+v, recorded %+v", i, got, recorded[i])
}
}
})
}
}
}
func TestSpriteDragReplayUsesRecordedPointerAndButtonState(t *testing.T) {
for _, withEdges := range []bool{false, true} {
name := "held snapshots"
if withEdges {
name = "ordered edges"
}
t.Run(name, func(t *testing.T) {
resetInputSessionTest(t)
currentScheduler, game, sprite := setupSpriteDragTest(t)
live := setupInputSourceManager(t)
live.point = mathf.NewVec2(-200, -100)
points := []mathf.Vec2{{X: 12, Y: 24}, {X: 42, Y: 64}, {X: 52, Y: 74}, {X: 80, Y: 90}}
frames := make([]InputReplayFrame, len(points))
for i, point := range points {
buttons := uint8(0)
if i < 2 {
buttons = 1
}
frames[i] = InputReplayFrame{
Frame: int64(i), Time: float64(i) / 30,
State: InputReplayState{Mouse: InputReplayMouse{X: point.X, Y: point.Y}, Buttons: buttons},
}
}
if withEdges {
frames[0].MouseEvents = []InputReplayMouseEvent{{Button: 1, Pressed: true}}
frames[2].MouseEvents = []InputReplayMouseEvent{{Button: 1, Pressed: false}}
}
if _, err := PrepareInputReplay(validRuntimeReplay(frames...)); err != nil {
t.Fatal(err)
}
session := claimPreparedSession(t, game)
t.Cleanup(func() { game.abortInputSession("test finished") })
want := []mathf.Vec2{{X: 10, Y: 20}, {X: 40, Y: 60}, {X: 50, Y: 70}, {X: 50, Y: 70}}
for i := range frames {
if !game.inputMgr.prepareInputFrame(1.0 / 30) {
t.Fatalf("replay frame %d was not prepared", i)
}
game.dispatchFrameEvents()
currentScheduler.Update()
session.endFrame()