-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathImGenie.cpp
More file actions
1748 lines (1662 loc) · 92.8 KB
/
Copy pathImGenie.cpp
File metadata and controls
1748 lines (1662 loc) · 92.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
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "ImGenie.h"
#include <cfloat>
#include <cmath>
#include <cstring>
// ---------- Current context ----------
static ImGenieContext* s_ctx = nullptr;
// ---------- Lattice helpers ----------
// Compute a tangent-like interpolation point between two ImVec2.
// Returns a point whose x = v0.x and y is lerped by aPercent along the y delta.
// Used to build Bezier control points for the vertical Coons patch S-curve.
static ImVec2 s_tg(const ImVec2& arV0, const ImVec2& arV1, float aPercent) { return (arV1 - arV0) * ImVec2(0.0f, aPercent) + arV0; }
// Evaluate a cubic Bezier curve at parameter aT in [0,1].
// p1..p4 are the 4 control points (scalar, not 2D).
// Uses double precision internally to avoid precision loss on large values.
static float s_bezierCubicCalc(float aP1, float aP2, float aP3, float aP4, float aT) {
const auto u = 1.0 - static_cast<double>(aT);
const auto w1 = u * u * u;
const auto w2 = 3.0 * u * u * aT;
const auto w3 = 3.0 * u * aT * aT;
const auto w4 = static_cast<double>(aT) * aT * aT;
return static_cast<float>(w1 * aP1 + w2 * aP2 + w3 * aP3 + w4 * aP4);
}
// Draw a textured Coons patch mesh with animated UV mapping.
//
// The mesh is defined by 4 corner points (p00=TL, p10=TR, p01=BL, p11=BR).
// Edges are interpolated using cubic Bezier S-curves (endpoints used as control points).
// The interior is bilinearly blended between the 4 edge curves (Coons patch).
//
// aStartAnimT / aEndAnimT: visible portion of the mesh along the primary axis [0..1].
// Only the rows/columns within this range are generated. This is how the genie "tail"
// disappears as the animation progresses.
//
// aAnimMode controls UV mapping:
// - Compress: UV remapped to [0..1] within visible range (texture shrinks with mesh)
// - Sliding: UV slides through the texture (texture scrolls away)
//
// aHorizontal: if true, primary axis is horizontal (Left/Right genie).
// Columns are iterated left-to-right instead of rows top-to-bottom.
//
// aFlipPrimaryUv: reverses UV along primary axis (for Bottom/Right sides where
// the trailing edge is at the end of the texture).
static void s_drawTexturedCoonsMeshPrimAnim(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arP00,
const ImVec2& arP10,
const ImVec2& arP01,
const ImVec2& arP11,
int32_t aCellsH,
int32_t aCellsV,
float aStartAnimT,
float aEndAnimT,
ImGenieAnimMode aAnimMode,
bool aHorizontal = false,
bool aFlipPrimaryUv = false,
bool aFlipV = false) {
if ((!apDrawList) || (aCellsV < 1) || (aCellsH < 1) || (aStartAnimT > aEndAnimT)) { return; }
const auto tint = IM_COL32(255, 255, 255, 255);
// ==================== Horizontal mode (Left/Right genie) ====================
// Primary axis = columns (left to right), secondary = rows (top to bottom).
if (aHorizontal) {
const auto visibleCols = static_cast<uint32_t>(ImMax(std::ceil((aEndAnimT - aStartAnimT) * static_cast<float>(aCellsH)), 1.0f));
const auto vertsPerCol = static_cast<uint32_t>(aCellsV + 1);
const auto colCount = visibleCols + 1U;
const auto vertexCount = colCount * vertsPerCol;
const auto indexCount = visibleCols * static_cast<uint32_t>(aCellsV) * 6U;
apDrawList->PushTexture(arTexture);
apDrawList->PrimReserve(indexCount, vertexCount);
ImDrawIdx prevColStart = 0;
auto currColStart = static_cast<ImDrawIdx>(apDrawList->_VtxCurrentIdx);
for (uint32_t colIdx = 0; colIdx < colCount; ++colIdx) {
const auto colFactor = (colCount > 1) ? (static_cast<float>(colIdx) / static_cast<float>(colCount - 1)) : 0.0f;
const auto patchParam = aStartAnimT + (aEndAnimT - aStartAnimT) * colFactor;
// S-curve Bezier for y at top edge (p00->p10) and bottom edge (p01->p11)
const auto tpt = s_bezierCubicCalc(arP00.y, arP00.y, arP10.y, arP10.y, patchParam);
const auto bpt = s_bezierCubicCalc(arP01.y, arP01.y, arP11.y, arP11.y, patchParam);
auto uvPrimary = patchParam - aStartAnimT;
if (aAnimMode == ImGenieAnimMode_Compress) {
uvPrimary /= (aEndAnimT - aStartAnimT);
} else if (aAnimMode == ImGenieAnimMode_Sliding) {
uvPrimary /= aEndAnimT;
}
if (aFlipPrimaryUv) { uvPrimary = 1.0f - uvPrimary; }
for (uint32_t rowIdx = 0; rowIdx < vertsPerCol; ++rowIdx) {
const auto v = (vertsPerCol > 1) ? (static_cast<float>(rowIdx) / static_cast<float>(vertsPerCol - 1)) : 0.0f;
const auto y = tpt + (bpt - tpt) * v;
// S-curve Bezier for x at left/right edges, then bilinear blend
const auto leftX = s_bezierCubicCalc(arP00.x, arP00.x, arP01.x, arP01.x, v);
const auto rightX = s_bezierCubicCalc(arP10.x, arP10.x, arP11.x, arP11.x, v);
const auto x = leftX + (rightX - leftX) * patchParam;
const auto finalV = aFlipV ? (1.0f - v) : v;
apDrawList->PrimWriteVtx(ImVec2(x, y), ImVec2(uvPrimary, finalV), tint);
}
// Emit 2 triangles per cell between this column and the previous one
if (colIdx > 0) {
for (int32_t rowIdx = 0; rowIdx < aCellsV; ++rowIdx) {
const auto tl = prevColStart + static_cast<ImDrawIdx>(rowIdx);
const auto bl = tl + 1;
const auto tr = currColStart + static_cast<ImDrawIdx>(rowIdx);
const auto br = tr + 1;
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(tr);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(bl);
}
}
prevColStart = currColStart;
currColStart = static_cast<ImDrawIdx>(currColStart + vertsPerCol);
}
apDrawList->PopTexture();
return;
}
// ==================== Vertical mode (Top/Bottom genie) ====================
// Primary axis = rows (top to bottom), secondary = columns (left to right).
const auto visibleCellsV = static_cast<uint32_t>(ImMax(std::ceil((aEndAnimT - aStartAnimT) * static_cast<float>(aCellsV)), 1.0f));
const auto vertsPerRow = static_cast<uint32_t>(aCellsH + 1);
const auto vertsPerCol = visibleCellsV + 1U;
const auto vertexCount = vertsPerRow * vertsPerCol;
const auto indexCount = visibleCellsV * static_cast<uint32_t>(aCellsH) * 6U;
apDrawList->PushTexture(arTexture);
apDrawList->PrimReserve(indexCount, vertexCount);
// Bezier tangent control points for left/right edges (gives the S-curve shape)
const auto bezierTangentPercent = 0.4f;
const auto lxC1 = s_tg(arP00, arP01, bezierTangentPercent).x;
const auto lxC2 = s_tg(arP01, arP00, bezierTangentPercent).x;
const auto rxC1 = s_tg(arP10, arP11, bezierTangentPercent).x;
const auto rxC2 = s_tg(arP11, arP10, bezierTangentPercent).x;
const auto tyC1 = arP00.y, tyC2 = arP10.y;
const auto byC1 = arP01.y, byC2 = arP11.y;
ImDrawIdx prevRowStart = 0;
auto currRowStart = static_cast<ImDrawIdx>(apDrawList->_VtxCurrentIdx);
for (uint32_t rowIdx = 0; rowIdx < vertsPerCol; ++rowIdx) {
const auto rowFactor = (vertsPerCol > 1) ? (static_cast<float>(rowIdx) / static_cast<float>(vertsPerCol - 1)) : 0.0f;
const auto patchParam = aStartAnimT + (aEndAnimT - aStartAnimT) * rowFactor;
// Bezier-interpolated x at left and right edges for this row
const auto lpt = s_bezierCubicCalc(arP00.x, lxC1, lxC2, arP01.x, patchParam);
const auto rpt = s_bezierCubicCalc(arP10.x, rxC1, rxC2, arP11.x, patchParam);
auto uvY = patchParam - aStartAnimT;
if (aAnimMode == ImGenieAnimMode_Compress) {
uvY /= aEndAnimT - aStartAnimT;
} else if (aAnimMode == ImGenieAnimMode_Sliding) {
uvY /= aEndAnimT;
}
if (aFlipPrimaryUv) { uvY = 1.0f - uvY; }
for (uint32_t colIdx = 0; colIdx < vertsPerRow; ++colIdx) {
const auto u = (vertsPerRow > 1) ? (static_cast<float>(colIdx) / static_cast<float>(vertsPerRow - 1)) : 0.0f;
// Bilinear blend between left/right edge x, then Coons patch blend for y
const auto x = lpt + (rpt - lpt) * u;
const auto topY = s_bezierCubicCalc(arP00.y, tyC1, tyC2, arP10.y, u);
const auto botY = s_bezierCubicCalc(arP01.y, byC1, byC2, arP11.y, u);
const auto y = topY + (botY - topY) * patchParam;
const auto finalUvY = aFlipV ? (1.0f - uvY) : uvY;
apDrawList->PrimWriteVtx(ImVec2(x, y), ImVec2(u, finalUvY), tint);
}
// Emit 2 triangles per cell between this row and the previous one
if (rowIdx > 0) {
for (int32_t colIdx = 0; colIdx < aCellsH; ++colIdx) {
const auto tl = prevRowStart + static_cast<ImDrawIdx>(colIdx);
const auto tr = tl + 1;
const auto bl = currRowStart + static_cast<ImDrawIdx>(colIdx);
const auto br = bl + 1;
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(tr);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(bl);
}
}
prevRowStart = currRowStart;
currRowStart = static_cast<ImDrawIdx>(currRowStart + vertsPerRow);
}
apDrawList->PopTexture();
}
// Draw full texture on 4 deformed corners (used for wobbly move rendering).
// Simply calls the Coons mesh with anim range [0..1] = full texture visible.
static void s_latticeDraw(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arP00,
const ImVec2& arP10,
const ImVec2& arP01,
const ImVec2& arP11,
int32_t aCellsH,
int32_t aCellsV,
ImGenieAnimMode aAnimMode,
bool aFlipV = false) {
if ((!apDrawList) || (arTexture._TexID == 0)) { return; }
s_drawTexturedCoonsMeshPrimAnim(apDrawList, arTexture, arP00, arP10, arP01, arP11, aCellsH, aCellsV, 0.0f, 1.0f, aAnimMode, false, false, aFlipV);
}
// Page curl / scroll-unroll effect.
// A straight fold line sweeps diagonally from BL to TR.
// Vertices in front of the fold: flat (normal position, visible).
// Vertices past the fold: projected onto the fold line (rolled up).
// This simulates a scroll/roll being unrolled across the window.
//
// ---------- Simple quad transitions (Fade, Scale, Slide) ----------
// Helper: draw a single textured quad (4 verts, 6 indices)
static void s_drawTexturedQuad(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arCapturedSize,
const ImVec2& arTL,
const ImVec2& arTR,
const ImVec2& arBL,
const ImVec2& arBR,
ImU32 aTint,
bool aFlipV = false) {
const auto uvTL = ImVec2(0.0f, aFlipV ? 1.0f : 0.0f);
const auto uvTR = ImVec2(1.0f, aFlipV ? 1.0f : 0.0f);
const auto uvBL = ImVec2(0.0f, aFlipV ? 0.0f : 1.0f);
const auto uvBR = ImVec2(1.0f, aFlipV ? 0.0f : 1.0f);
apDrawList->PushTexture(arTexture);
apDrawList->PrimReserve(6, 4);
apDrawList->PrimQuadUV(arTL, arTR, arBR, arBL, uvTL, uvTR, uvBR, uvBL, aTint);
apDrawList->PopTexture();
}
// Fade: alpha transition. aAnimT: 0 = invisible, 1 = fully visible.
static void s_fadeAnimate(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arCapturedSize,
float aAnimT,
const ImRect& arSource,
bool aFlipV = false) {
if (!apDrawList || arTexture._TexID == 0 || aAnimT <= 0.0f) { return; }
const auto t = ImClamp(aAnimT, 0.0f, 1.0f);
const auto eased = t * t * (3.0f - 2.0f * t);
const auto alpha = static_cast<ImU8>(eased * 255.0f);
const auto tint = IM_COL32(255, 255, 255, alpha);
s_drawTexturedQuad(
apDrawList, arTexture, arCapturedSize, arSource.Min, ImVec2(arSource.Max.x, arSource.Min.y), ImVec2(arSource.Min.x, arSource.Max.y), arSource.Max, tint, aFlipV);
}
// Scale: zoom from/to center. aAnimT: 0 = collapsed to center, 1 = fully visible.
static void s_scaleAnimate(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arCapturedSize,
float aAnimT,
const ImRect& arSource,
bool aFlipV = false) {
if (!apDrawList || arTexture._TexID == 0 || aAnimT <= 0.0f) { return; }
const auto t = ImClamp(aAnimT, 0.0f, 1.0f);
const auto eased = t * t * (3.0f - 2.0f * t);
const auto center = arSource.GetCenter();
const auto halfW = arSource.GetWidth() * 0.5f * eased;
const auto halfH = arSource.GetHeight() * 0.5f * eased;
const ImVec2 tl(center.x - halfW, center.y - halfH);
const ImVec2 tr(center.x + halfW, center.y - halfH);
const ImVec2 bl(center.x - halfW, center.y + halfH);
const ImVec2 br(center.x + halfW, center.y + halfH);
const auto tint = IM_COL32(255, 255, 255, 255);
s_drawTexturedQuad(apDrawList, arTexture, arCapturedSize, tl, tr, bl, br, tint, aFlipV);
}
// Resolve auto slide directions to a concrete edge or corner.
static ImGenieSlideDir s_resolveSlideDir(const ImRect& arSource, ImGenieSlideDir aDir = ImGenieSlideDir_Auto, float aCornerRatio = 0.15f) {
if (aDir != ImGenieSlideDir_Auto) return aDir;
const auto& displaySize = ImGui::GetIO().DisplaySize;
const auto center = arSource.GetCenter();
// Split viewport into 3 zones per axis: 0 = start, 1 = middle, 2 = end
const float r = ImClamp(aCornerRatio, 0.0f, 0.5f);
const float zw = displaySize.x * r;
const float zh = displaySize.y * r;
auto zoneH = [&](float x) -> int { return (x < zw) ? 0 : (x > displaySize.x - zw) ? 2 : 1; };
auto zoneV = [&](float y) -> int { return (y < zh) ? 0 : (y > displaySize.y - zh) ? 2 : 1; };
// Classify each frame edge into a viewport zone
// Edge 0 (top=Min.y) → V zone, Edge 2 (bottom=Max.y) → V zone
// Edge 3 (left=Min.x) → H zone, Edge 1 (right=Max.x) → H zone
const int zt = zoneV(arSource.Min.y); // top border
const int zb = zoneV(arSource.Max.y); // bottom border
const int zl = zoneH(arSource.Min.x); // left border
const int zr = zoneH(arSource.Max.x); // right border
// Resolve each axis: same zone → that zone, one corner + middle → corner, spans 0..2 → middle
// H: zl <= zr always. (0,0)→0 (0,1)→0 (0,2)→1 (1,1)→1 (1,2)→2 (2,2)→2
// V: zt <= zb always. same pattern
auto resolve = [](int a, int b) -> int { return (a == b) ? a : (b - a >= 2) ? 1 : (a == 0) ? 0 : 2; };
const int rH = resolve(zl, zr); // 0=left, 1=middle, 2=right
const int rV = resolve(zt, zb); // 0=top, 1=middle, 2=bottom
// rH\rV: 0(top) 1(mid) 2(bot)
// 0(left) TopLeft Left BottomLeft
// 1(mid) Top FALLBACK Bottom
// 2(right) TopRight Right BottomRight
if (rH == 0 && rV == 0) return ImGenieSlideDir_TopLeft;
if (rH == 2 && rV == 0) return ImGenieSlideDir_TopRight;
if (rH == 0 && rV == 2) return ImGenieSlideDir_BottomLeft;
if (rH == 2 && rV == 2) return ImGenieSlideDir_BottomRight;
if (rV == 0) return ImGenieSlideDir_Top;
if (rV == 2) return ImGenieSlideDir_Bottom;
if (rH == 0) return ImGenieSlideDir_Left;
if (rH == 2) return ImGenieSlideDir_Right;
// Fallback (1,1): window in center — pick closest edge
const float distLeft = center.x;
const float distRight = displaySize.x - center.x;
const float distTop = center.y;
const float distBottom = displaySize.y - center.y;
const float minEdge = ImMin(ImMin(distLeft, distRight), ImMin(distTop, distBottom));
if (minEdge == distLeft) return ImGenieSlideDir_Left;
if (minEdge == distRight) return ImGenieSlideDir_Right;
if (minEdge == distTop) return ImGenieSlideDir_Top;
return ImGenieSlideDir_Bottom;
}
// Slide: translate off-screen. aAnimT: 0 = fully off-screen, 1 = fully visible.
// aDir: ImGenieSlideDir — Auto picks the closest viewport edge.
// The window slides completely outside the viewport (display) bounds.
static void s_slideAnimate(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arCapturedSize,
float aAnimT,
const ImRect& arSource,
const ImGenieSlideParams& arSlideParams,
bool aFlipV = false) {
if (!apDrawList || arTexture._TexID == 0 || aAnimT <= 0.0f) { return; }
const auto dir = s_resolveSlideDir(arSource, arSlideParams.dir, arSlideParams.autoCornerRatio);
const auto t = ImClamp(aAnimT, 0.0f, 1.0f);
const auto eased = t * t * (3.0f - 2.0f * t);
const auto& displaySize = ImGui::GetIO().DisplaySize;
// Full distance to push window off-screen (per axis)
float fullDistX = 0.0f, fullDistY = 0.0f;
if (dir == ImGenieSlideDir_Left || dir == ImGenieSlideDir_TopLeft || dir == ImGenieSlideDir_BottomLeft) {
fullDistX = -arSource.Max.x;
} else if (dir == ImGenieSlideDir_Right || dir == ImGenieSlideDir_TopRight || dir == ImGenieSlideDir_BottomRight) {
fullDistX = displaySize.x - arSource.Min.x;
}
if (dir == ImGenieSlideDir_Top || dir == ImGenieSlideDir_TopLeft || dir == ImGenieSlideDir_TopRight) {
fullDistY = -arSource.Max.y;
} else if (dir == ImGenieSlideDir_Bottom || dir == ImGenieSlideDir_BottomLeft || dir == ImGenieSlideDir_BottomRight) {
fullDistY = displaySize.y - arSource.Min.y;
}
const ImVec2 fullOff(fullDistX * (1.0f - eased), fullDistY * (1.0f - eased));
// p00=TL, p10=TR, p01=BL, p11=BR
ImVec2 p00 = arSource.Min;
ImVec2 p10 = ImVec2(arSource.Max.x, arSource.Min.y);
ImVec2 p01 = ImVec2(arSource.Min.x, arSource.Max.y);
ImVec2 p11 = arSource.Max;
if (arSlideParams.wobbly) {
// Leading (pinned) corners move, trailing corners stay — Coons Bezier S-curve handles the elastic stretch
bool pinned[4] = {false, false, false, false}; // TL, TR, BL, BR
switch (dir) {
case ImGenieSlideDir_Left: pinned[0] = pinned[2] = true; break;
case ImGenieSlideDir_Right: pinned[1] = pinned[3] = true; break;
case ImGenieSlideDir_Top: pinned[0] = pinned[1] = true; break;
case ImGenieSlideDir_Bottom: pinned[2] = pinned[3] = true; break;
case ImGenieSlideDir_TopLeft: pinned[0] = true; break;
case ImGenieSlideDir_TopRight: pinned[1] = true; break;
case ImGenieSlideDir_BottomLeft: pinned[2] = true; break;
case ImGenieSlideDir_BottomRight: pinned[3] = true; break;
default: break;
}
ImVec2* corners[4] = {&p00, &p10, &p01, &p11};
for (int32_t i = 0; i < 4; ++i) {
if (pinned[i]) *corners[i] = *corners[i] + fullOff;
}
} else {
// Uniform: all 4 corners move together
p00 = p00 + fullOff;
p10 = p10 + fullOff;
p01 = p01 + fullOff;
p11 = p11 + fullOff;
}
const auto cellsH = arSlideParams.wobbly && fullDistX != 0.0f ? ImMax(arSlideParams.spring.cellsH, 1) : 1;
const auto cellsV = arSlideParams.wobbly && fullDistY != 0.0f ? ImMax(arSlideParams.spring.cellsV, 1) : 1;
s_latticeDraw(apDrawList, arTexture, p00, p10, p01, p11, cellsH, cellsV, ImGenieAnimMode_Sliding, aFlipV);
}
// ---------- Page Curl transition ----------
// aAnimT: 0 = fully rolled (everything on aOrigin point), 1 = fully flat (visible).
static void s_pageCurlAnimate(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arCapturedSize,
float aAnimT,
const ImRect& arSource,
int32_t aCellsH,
int32_t aCellsV,
ImGeniePageCurlOrigin aOrigin = ImGeniePageCurlOrigin_BottomLeft,
bool aFlipV = false) {
if (!apDrawList || arTexture._TexID == 0 || aAnimT <= 0.0f) { return; }
const auto winW = arSource.GetWidth();
const auto winH = arSource.GetHeight();
if (winW <= 0.0f || winH <= 0.0f) { return; }
// Smoothstep easing
const auto t = ImClamp(aAnimT, 0.0f, 1.0f);
const auto eased = t * t * (3.0f - 2.0f * t);
// Compute start corner and sweep direction based on origin
const auto diagLen = sqrtf(winW * winW + winH * winH);
ImVec2 startCorner;
ImVec2 sweepDir;
float sweepLen = diagLen;
switch (aOrigin) {
case ImGeniePageCurlOrigin_BottomLeft: {
startCorner = ImVec2(arSource.Min.x, arSource.Max.y);
sweepDir = ImVec2(winW / diagLen, -winH / diagLen);
} break;
case ImGeniePageCurlOrigin_BottomRight: {
startCorner = ImVec2(arSource.Max.x, arSource.Max.y);
sweepDir = ImVec2(-winW / diagLen, -winH / diagLen);
} break;
case ImGeniePageCurlOrigin_TopLeft: {
startCorner = ImVec2(arSource.Min.x, arSource.Min.y);
sweepDir = ImVec2(winW / diagLen, winH / diagLen);
} break;
case ImGeniePageCurlOrigin_TopRight: {
startCorner = ImVec2(arSource.Max.x, arSource.Min.y);
sweepDir = ImVec2(-winW / diagLen, winH / diagLen);
} break;
case ImGeniePageCurlOrigin_Bottom: {
startCorner = ImVec2(arSource.Min.x, arSource.Max.y);
sweepDir = ImVec2(0.0f, -1.0f);
sweepLen = winH;
} break;
case ImGeniePageCurlOrigin_Top: {
startCorner = ImVec2(arSource.Min.x, arSource.Min.y);
sweepDir = ImVec2(0.0f, 1.0f);
sweepLen = winH;
} break;
case ImGeniePageCurlOrigin_Left: {
startCorner = ImVec2(arSource.Min.x, arSource.Min.y);
sweepDir = ImVec2(1.0f, 0.0f);
sweepLen = winW;
} break;
case ImGeniePageCurlOrigin_Right: {
startCorner = ImVec2(arSource.Max.x, arSource.Min.y);
sweepDir = ImVec2(-1.0f, 0.0f);
sweepLen = winW;
} break;
default: {
startCorner = ImVec2(arSource.Min.x, arSource.Max.y);
sweepDir = ImVec2(winW / diagLen, -winH / diagLen);
} break;
}
// Fold line position along the sweep
const auto foldDist = eased * sweepLen;
// --- Mesh ---
const auto tint = IM_COL32(255, 255, 255, 255);
const auto vertsPerRow = static_cast<uint32_t>(aCellsH + 1);
const auto vertsPerCol = static_cast<uint32_t>(aCellsV + 1);
const auto vertexCount = vertsPerRow * vertsPerCol;
const auto indexCount = static_cast<uint32_t>(aCellsH) * static_cast<uint32_t>(aCellsV) * 6U;
apDrawList->PushTexture(arTexture);
apDrawList->PrimReserve(indexCount, vertexCount);
auto currRowStart = static_cast<ImDrawIdx>(apDrawList->_VtxCurrentIdx);
ImDrawIdx prevRowStart = 0;
// Fold line point
const ImVec2 foldPt(startCorner.x + foldDist * sweepDir.x, startCorner.y + foldDist * sweepDir.y);
for (uint32_t rowIdx = 0; rowIdx < vertsPerCol; ++rowIdx) {
const auto vf = (vertsPerCol > 1) ? (static_cast<float>(rowIdx) / static_cast<float>(vertsPerCol - 1)) : 0.0f;
for (uint32_t colIdx = 0; colIdx < vertsPerRow; ++colIdx) {
const auto uf = (vertsPerRow > 1) ? (static_cast<float>(colIdx) / static_cast<float>(vertsPerRow - 1)) : 0.0f;
// Original screen position
const auto sx = arSource.Min.x + uf * winW;
const auto sy = arSource.Min.y + vf * winH;
// Signed distance from fold point along sweep direction
const auto dx = sx - foldPt.x;
const auto dy = sy - foldPt.y;
const auto sweepDist = dx * sweepDir.x + dy * sweepDir.y;
const auto uvX = uf;
const auto uvY = aFlipV ? (1.0f - vf) : vf;
if (sweepDist <= 0.0f) {
// In front of fold: flat, normal position
apDrawList->PrimWriteVtx(ImVec2(sx, sy), ImVec2(uvX, uvY), tint);
} else {
// Past fold: project onto the fold line (rolled up)
// Remove the sweep component, keep perpendicular component
auto projX = sx - sweepDist * sweepDir.x;
auto projY = sy - sweepDist * sweepDir.y;
// Clamp to window bounds so the fold line doesn't exceed the rect
projX = ImClamp(projX, arSource.Min.x, arSource.Max.x);
projY = ImClamp(projY, arSource.Min.y, arSource.Max.y);
apDrawList->PrimWriteVtx(ImVec2(projX, projY), ImVec2(uvX, uvY), tint);
}
}
if (rowIdx > 0) {
for (int32_t colIdx = 0; colIdx < aCellsH; ++colIdx) {
const auto tl = prevRowStart + static_cast<ImDrawIdx>(colIdx);
const auto tr = tl + 1;
const auto bl = currRowStart + static_cast<ImDrawIdx>(colIdx);
const auto br = bl + 1;
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(tr);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(tl);
apDrawList->PrimWriteIdx(br);
apDrawList->PrimWriteIdx(bl);
}
}
prevRowStart = currRowStart;
currRowStart = static_cast<ImDrawIdx>(currRowStart + vertsPerRow);
}
apDrawList->PopTexture();
}
// Auto-detect which side of the button the window is on.
// Compares center positions: the dominant axis (x or y) determines the side.
static ImGenieSide s_autoDetectSide(const ImRect& arSource, const ImRect& arTarget) {
const auto delta = arSource.GetCenter() - arTarget.GetCenter();
if (fabsf(delta.x) > fabsf(delta.y)) { return (delta.x > 0) ? ImGenieSide_Right : ImGenieSide_Left; }
return (delta.y > 0) ? ImGenieSide_Bottom : ImGenieSide_Top;
}
// Animate the genie effect (disappearance or appearance) on any side.
//
// The mesh has two edges:
// - Trailing edge: stays at the source window position (the "body")
// - Converging edge: narrows toward the target button as aAnimT increases
//
// For vertical (Top/Bottom): trailing = top row (p00/p10), converging = bottom row (p01/p11).
// For horizontal (Left/Right): trailing = left col (p00/p01), converging = right col (p10/p11).
//
// The converging edge narrows to target width over the first 30% of the anim.
// The trailing edge starts disappearing after 25% of the anim (startRatio increases).
// This creates the characteristic "sucked into the button" genie look.
static void s_latticeAnimate(ImDrawList* apDrawList,
const ImTextureRef& arTexture,
const ImVec2& arTextureSize,
float aAnimT,
const ImRect& arSource,
const ImRect& arTarget,
int32_t aCellsH,
int32_t aCellsV,
ImGenieAnimMode aAnimMode,
ImGenieSide aSide,
bool aFlipV = false) {
if ((!apDrawList) || (arTexture._TexID == 0) || (aAnimT < 0.0f) || (aAnimT > 1.0f)) { return; }
const auto side = (aSide == ImGenieSide_Auto) ? s_autoDetectSide(arSource, arTarget) : aSide;
const auto horizontal = (side == ImGenieSide_Left || side == ImGenieSide_Right);
// Bottom/Right need flipped UVs because the trailing edge is at the end of the texture
const auto flipPrimaryUv = (side == ImGenieSide_Bottom || side == ImGenieSide_Right);
// p00/p10 = trailing edge (or p00/p01 for horizontal)
// convSrc = converging edge at full width (source), convTgt = at button width
ImVec2 p00, p10, p01, p11;
ImVec2 convSrc0, convSrc1, convTgt0, convTgt1;
float totalDist{}, sourceDim{};
switch (side) {
case ImGenieSide_Top: {
p00 = arSource.Min;
p10 = ImVec2(arSource.Max.x, arSource.Min.y);
convSrc0 = ImVec2(arSource.Min.x, arTarget.Min.y);
convSrc1 = ImVec2(arSource.Max.x, arTarget.Min.y);
convTgt0 = arTarget.Min;
convTgt1 = ImVec2(arTarget.Max.x, arTarget.Min.y);
totalDist = arTarget.Min.y - arSource.Min.y;
sourceDim = arSource.GetHeight();
} break;
case ImGenieSide_Bottom: {
p00 = ImVec2(arSource.Min.x, arSource.Max.y);
p10 = arSource.Max;
convSrc0 = ImVec2(arSource.Min.x, arTarget.Max.y);
convSrc1 = ImVec2(arSource.Max.x, arTarget.Max.y);
convTgt0 = ImVec2(arTarget.Min.x, arTarget.Max.y);
convTgt1 = arTarget.Max;
totalDist = arSource.Max.y - arTarget.Max.y;
sourceDim = arSource.GetHeight();
} break;
case ImGenieSide_Left: {
p00 = arSource.Min;
p01 = ImVec2(arSource.Min.x, arSource.Max.y);
convSrc0 = ImVec2(arTarget.Min.x, arSource.Min.y);
convSrc1 = ImVec2(arTarget.Min.x, arSource.Max.y);
convTgt0 = arTarget.Min;
convTgt1 = ImVec2(arTarget.Min.x, arTarget.Max.y);
totalDist = arTarget.Min.x - arSource.Min.x;
sourceDim = arSource.GetWidth();
} break;
case ImGenieSide_Right:
default: {
p00 = ImVec2(arSource.Max.x, arSource.Min.y);
p01 = arSource.Max;
convSrc0 = ImVec2(arTarget.Max.x, arSource.Min.y);
convSrc1 = ImVec2(arTarget.Max.x, arSource.Max.y);
convTgt0 = ImVec2(arTarget.Max.x, arTarget.Min.y);
convTgt1 = arTarget.Max;
totalDist = arSource.Max.x - arTarget.Max.x;
sourceDim = arSource.GetWidth();
} break;
}
if (horizontal) {
p10 = convSrc0;
p11 = convSrc1;
} else {
p01 = convSrc0;
p11 = convSrc1;
}
// sourceRatio: how much of the [0..1] parameter space the source window covers.
// startRatio / endRatio define the visible portion of the mesh.
// As anim progresses, startRatio grows (trailing edge shrinks) and endRatio approaches 1.
const auto sourceRatio = (totalDist > 0.0f) ? (sourceDim / totalDist) : 1.0f;
auto startRatio = 0.0f;
auto endRatio = sourceRatio;
if (aAnimT > 0.0f) {
// Converging edge reaches target width over first 30%
const auto ratio = (aAnimT < 0.3f) ? (aAnimT / 0.3f) : 1.0f;
// Trailing edge starts shrinking after 25%
if (aAnimT > 0.25f) { startRatio = (aAnimT - 0.25f) / (1.0f - 0.25f); }
const auto conv0 = ImLerp(convSrc0, convTgt0, ratio);
const auto conv1 = ImLerp(convSrc1, convTgt1, ratio);
if (horizontal) {
p10 = conv0;
p11 = conv1;
} else {
p01 = conv0;
p11 = conv1;
}
endRatio = ImLerp(sourceRatio, 1.0f, ratio);
}
s_drawTexturedCoonsMeshPrimAnim(apDrawList, arTexture, p00, p10, p01, p11, aCellsH, aCellsV, startRatio, endRatio, aAnimMode, horizontal, flipPrimaryUv, aFlipV);
}
// ---------- Debug mesh ----------
static void s_drawDebug(ImDrawList* apDrawList, const ImGenieEffect& arEffect) {
if (arEffect.params.drawDebug && !apDrawList->CmdBuffer.empty()) {
auto* pCmd = &apDrawList->CmdBuffer.front();
ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(apDrawList, apDrawList, pCmd, true, true);
}
}
// ---------- Utility ----------
// Recursively add DrawLists from all child windows to the given ImDrawData.
// Children are added in depth-first order (parent before its children),
// which matches ImGui's own rendering order.
static void s_addChildDrawLists(const ImGuiWindow* apWin, ImDrawData* apDrawData) {
for (int i = 0; i < apWin->DC.ChildWindows.Size; ++i) {
const ImGuiWindow* child = apWin->DC.ChildWindows[i];
if (child != nullptr && child->DrawList != nullptr && child->DrawList->CmdBuffer.Size > 0) {
apDrawData->AddDrawList(child->DrawList);
s_addChildDrawLists(child, apDrawData);
}
}
}
// Build an ImDrawData from a window's DrawList and call the user-provided capture callback.
// This isolates the user from ImGui internals: they just receive (width, height, drawData).
static ImTextureRef s_captureWindow(const ImGuiWindow* apWin, ImDrawData* apMainDrawData) {
IM_ASSERT(s_ctx && "The context is null");
IM_ASSERT(s_ctx->createCaptureFunc && "The capture creation function is not defined");
ImTextureRef ret{};
if (apWin == nullptr || apWin->DrawList == nullptr) { return ret; }
const auto w = static_cast<int32_t>(apWin->Size.x);
const auto h = static_cast<int32_t>(apWin->Size.y);
if (w <= 0 || h <= 0) { return ret; }
ImDrawData offscreenData;
offscreenData.Valid = true;
offscreenData.DisplayPos = apWin->Pos;
offscreenData.DisplaySize = apWin->Size;
offscreenData.FramebufferScale = ImGui::GetIO().DisplayFramebufferScale;
offscreenData.OwnerViewport = ImGui::GetMainViewport();
offscreenData.Textures = (apMainDrawData != nullptr) ? apMainDrawData->Textures : nullptr;
offscreenData.AddDrawList(apWin->DrawList);
s_addChildDrawLists(apWin, &offscreenData);
return s_ctx->createCaptureFunc(w, h, &offscreenData);
}
// Release the captured FBO texture via the user-provided destroy callback.
static void s_deleteEffectTexture(ImGenieEffect& aorEffect) {
IM_ASSERT(s_ctx && "The context is null");
IM_ASSERT(s_ctx->destroyCaptureFunc && "The capture destruction function is not defined");
if (aorEffect.capturedTex._TexID != 0) {
s_ctx->destroyCaptureFunc(aorEffect.capturedTex);
aorEffect.capturedTex._TexID = 0;
}
}
// Remove a window's DrawList from the main ImDrawData so it won't be rendered
// by the backend. This hides the real window while the captured texture is shown instead.
static void s_removeDrawListFromDrawData(ImDrawData* apDrawData, ImDrawList* apDrawList) {
if (apDrawData == nullptr || apDrawList == nullptr) { return; }
for (int32_t i = 0; i < apDrawData->CmdLists.Size; ++i) {
if (apDrawData->CmdLists[i] == apDrawList) {
apDrawData->TotalVtxCount -= apDrawList->VtxBuffer.Size;
apDrawData->TotalIdxCount -= apDrawList->IdxBuffer.Size;
apDrawData->CmdLists.erase(apDrawData->CmdLists.Data + i);
apDrawData->CmdListsCount--;
break;
}
}
}
// Recursively remove DrawLists of all child windows from the main ImDrawData.
static void s_removeChildDrawListsFromDrawData(ImDrawData* apDrawData, const ImGuiWindow* apWin) {
for (int i = 0; i < apWin->DC.ChildWindows.Size; ++i) {
const ImGuiWindow* child = apWin->DC.ChildWindows[i];
if (child != nullptr && child->DrawList != nullptr) {
s_removeDrawListFromDrawData(apDrawData, child->DrawList);
s_removeChildDrawListsFromDrawData(apDrawData, child);
}
}
}
// ---------- Wobbly spring helpers ----------
// Extract the 4 corners of a rect: [0]=TL, [1]=TR, [2]=BL, [3]=BR
static void s_cornersFromRect(const ImRect& arRect, ImVec2 aoCorners[4]) {
aoCorners[0] = arRect.Min;
aoCorners[1] = ImVec2(arRect.Max.x, arRect.Min.y);
aoCorners[2] = ImVec2(arRect.Min.x, arRect.Max.y);
aoCorners[3] = arRect.Max;
}
// Initialize the 4 spring corners at the window's current position,
// and compute bilinear weights from the grab point (where the user clicked).
// Closer corners get higher weight = stiffer spring = less wobble near cursor.
static void s_initSprings(ImGenieEffect& aorEffect, const ImRect& arWinRect, const ImVec2& arGrabPos) {
ImVec2 corners[4];
s_cornersFromRect(arWinRect, corners);
for (int32_t i = 0; i < 4; ++i) {
aorEffect.springs[i].current = corners[i];
aorEffect.springs[i].velocity = ImVec2(0, 0);
}
// Normalized grab position within the window [0..1]
const auto gx = ImClamp((arWinRect.GetWidth() > 0.0f) ? (arGrabPos.x - arWinRect.Min.x) / arWinRect.GetWidth() : 0.5f, 0.0f, 1.0f);
const auto gy = ImClamp((arWinRect.GetHeight() > 0.0f) ? (arGrabPos.y - arWinRect.Min.y) / arWinRect.GetHeight() : 0.5f, 0.0f, 1.0f);
aorEffect.grabUV = ImVec2(gx, gy);
// Bilinear weights: each corner's weight = product of distances from grab point
aorEffect.springWeights[0] = (1.0f - gx) * (1.0f - gy); // TL
aorEffect.springWeights[1] = gx * (1.0f - gy); // TR
aorEffect.springWeights[2] = (1.0f - gx) * gy; // BL
aorEffect.springWeights[3] = gx * gy; // BR
}
// Advance the spring simulation by aDt seconds (Euler integration with substeps).
// Each corner is pulled toward its target position by a spring force (Hooke's law + damping).
// Stiffness varies per corner: higher weight = stiffer = follows cursor more closely.
// Generic spring update: all 4 corners spring toward targets with uniform stiffness/damping.
static void s_updateSpringsUniform(ImGenieEffect& aorEffect, const ImVec2 aTargets[4], const ImGenieSpringParams& arSpring, float aDt) {
const auto subDt = aDt / arSpring.substeps;
for (int32_t step = 0; step < arSpring.substeps; ++step) {
for (int32_t i = 0; i < 4; ++i) {
auto force = (aTargets[i] - aorEffect.springs[i].current) * arSpring.stiffness;
force = force - aorEffect.springs[i].velocity * arSpring.damping;
aorEffect.springs[i].velocity = aorEffect.springs[i].velocity + force * subDt;
aorEffect.springs[i].current = aorEffect.springs[i].current + aorEffect.springs[i].velocity * subDt;
}
}
}
// Wobbly spring update: stiffness varies per corner based on grab distance (springWeights).
static void s_updateSprings(ImGenieEffect& aorEffect, const ImRect& arWinRect, float aDt) {
const auto& rParams = aorEffect.params;
ImVec2 targets[4];
s_cornersFromRect(arWinRect, targets);
const auto& spring = rParams.effects.wobbly.spring;
const auto subDt = aDt / spring.substeps;
for (int32_t step = 0; step < spring.substeps; ++step) {
for (int32_t i = 0; i < 4; ++i) {
const auto stiffness = spring.stiffness + //
(rParams.effects.wobbly.maxStiffness - spring.stiffness) * aorEffect.springWeights[i];
auto force = (targets[i] - aorEffect.springs[i].current) * stiffness;
force = force - aorEffect.springs[i].velocity * spring.damping;
aorEffect.springs[i].velocity = aorEffect.springs[i].velocity + force * subDt;
aorEffect.springs[i].current = aorEffect.springs[i].current + aorEffect.springs[i].velocity * subDt;
}
}
}
// ---------- Context management ----------
ImGenieContext* ImGenie::CreateContext() {
auto* ctx = IM_NEW(ImGenieContext);
if (s_ctx == nullptr) { SetCurrentContext(ctx); }
return ctx;
}
void ImGenie::DestroyContext(ImGenieContext* apCtx) {
if (apCtx == nullptr) { apCtx = s_ctx; }
if (apCtx == nullptr) { return; }
IM_ASSERT(s_ctx && "The context is null");
for (auto it = apCtx->effects.begin(); it != apCtx->effects.end(); ++it) { s_deleteEffectTexture(it->second); }
if (s_ctx == apCtx) { s_ctx = nullptr; }
IM_DELETE(apCtx);
}
ImGenieContext* ImGenie::GetCurrentContext() { return s_ctx; }
bool ImGenie::HasActiveEffects() {
IM_ASSERT(s_ctx && "The context is null");
if (s_ctx == nullptr) { return false; }
return !s_ctx->effects.empty();
}
bool ImGenie::IsEffectActive(const char* aWindowName) {
IM_ASSERT(s_ctx && "The context is null");
if (s_ctx == nullptr) { return false; }
const auto id = ImHashStr(aWindowName);
auto it = s_ctx->effects.find(id);
return it != s_ctx->effects.end();
}
void ImGenie::Close(const char* aWindowName) {
if (!aWindowName || !s_ctx) return;
s_ctx->internalOpenStates[ImHashStr(aWindowName)] = false;
}
void ImGenie::Open(const char* aWindowName) {
if (!aWindowName || !s_ctx) return;
s_ctx->internalOpenStates[ImHashStr(aWindowName)] = true;
}
void ImGenie::SetCurrentContext(ImGenieContext* apCtx) { s_ctx = apCtx; }
void ImGenie::SetCreateCaptureFunc(const CreateCaptureFunctor& arFunc) {
IM_ASSERT(s_ctx && "The context is null");
if (s_ctx == nullptr) { return; }
s_ctx->createCaptureFunc = arFunc;
}
void ImGenie::SetDestroyCaptureFunc(const DestroyCaptureFunctor& arFunc) {
IM_ASSERT(s_ctx && "The context is null");
if (s_ctx == nullptr) { return; }
s_ctx->destroyCaptureFunc = arFunc;
}
void ImGenie::SetCaptureFlipV(bool aFlipV) {
IM_ASSERT(s_ctx && "The context is null");
if (s_ctx == nullptr) { return; }
s_ctx->captureFlipV = aFlipV;
}
// ---------- ImGenie API ----------
// Main API function, called every frame for each tracked window.
//
// State machine overview:
// 1. Disappearance: user closes window -> PendingCapture -> Captured -> Animating -> done
// 2. Appearance: user opens window -> AppearingCapture -> AppearingAnimating -> done
// 3. Wobbly move: user drags window -> MovingCapture -> MovingActive -> MovingSettle -> done
//
// Returns true if the caller can show the window normally.
// Returns false if ImGenie is handling the window (animating).
bool ImGenie::Allow(const char* aWindowName, bool* apoOpen, const ImGenieParams* apParams) {
IM_ASSERT(s_ctx && "The context is null");
if (aWindowName == nullptr) { return true; }
auto& ctx = *s_ctx;
const auto& params = apParams ? *apParams : ctx.globalParams;
const auto id = ImHashStr(aWindowName);
// If no external bool, use internal open state (default: open)
bool* pOpen = apoOpen;
if (pOpen == nullptr) {
if (ctx.internalOpenStates.find(id) == ctx.internalOpenStates.end()) {
ctx.internalOpenStates[id] = true;
}
pOpen = &ctx.internalOpenStates[id];
}
auto it = ctx.effects.find(id);
// ==================== Active effect handling ====================
if (it != ctx.effects.end()) {
auto& effect = it->second;
// Topdate params each frame, and track button position (destRect follows genie params)
effect.params = params;
const auto& dr = params.transitions.genie.destRect;
effect.destRect = ImRect(dr.minX, dr.minY, dr.maxX, dr.maxY);
// --- Mid-animation reversal ---
// If the user toggles the open state while an animation is playing, reverse direction.
// Guard animT > 0 to skip the first frame after Captured fall-through (where *pOpen is stale).
if (effect.state == ImGenieEffect::State::Animating && effect.animT > 0.0f && *pOpen) {
// Disappearing → user wants to re-open → reverse to appearing
effect.state = ImGenieEffect::State::AppearingAnimating;
effect.animT = 1.0f - effect.animT;
} else if (effect.state == ImGenieEffect::State::AppearingAnimating && effect.animT > 0.0f && !*pOpen) {
// Appearing → user wants to close → reverse to disappearing
effect.state = ImGenieEffect::State::Animating;
effect.animT = 1.0f - effect.animT;
}
// --- Disappearance: capture frame ---
// Keep window open one more frame so Capture() can snapshot its DrawList
if (effect.state == ImGenieEffect::State::PendingCapture) {
*pOpen = true;
return true;
}
// --- Disappearance: captured, start animation ---
if (effect.state == ImGenieEffect::State::Captured) {
effect.state = ImGenieEffect::State::Animating;
effect.animT = 0.0f;
// Init springs for slide wobbly
if (effect.params.transitions.transitionMode == ImGenieTransitionMode_Slide && effect.params.transitions.slide.wobbly) {
ImVec2 corners[4];
s_cornersFromRect(effect.sourceRect, corners);
for (int32_t i = 0; i < 4; ++i) {
effect.springs[i].current = corners[i];
effect.springs[i].velocity = ImVec2(0.0f, 0.0f);
}
}
}
// --- Disappearance: animating ---
if (effect.state == ImGenieEffect::State::Animating) {
const auto dt = ImGui::GetIO().DeltaTime;
effect.animT += dt / effect.params.transitions.animDuration;
if (effect.animT >= 1.0f) {
s_deleteEffectTexture(effect);
ctx.effectNames.erase(id);
ctx.effects.erase(it);
*pOpen = false;
return true;
}
auto* pDrawList = ImGui::GetForegroundDrawList();
const auto mode = effect.params.transitions.transitionMode;
if (mode == ImGenieTransitionMode_PageCurl) {
s_pageCurlAnimate(pDrawList,
effect.capturedTex,
effect.capturedSize,
1.0f - effect.animT,
effect.sourceRect,
effect.params.transitions.pageCurl.cellsH,
effect.params.transitions.pageCurl.cellsV,
effect.params.transitions.pageCurl.origin,
ctx.captureFlipV);
} else if (mode == ImGenieTransitionMode_Fade) {
s_fadeAnimate(pDrawList, effect.capturedTex, effect.capturedSize, 1.0f - effect.animT, effect.sourceRect, ctx.captureFlipV);
} else if (mode == ImGenieTransitionMode_Scale) {
s_scaleAnimate(pDrawList, effect.capturedTex, effect.capturedSize, 1.0f - effect.animT, effect.sourceRect, ctx.captureFlipV);
} else if (mode == ImGenieTransitionMode_Slide) {
const auto& slideP = effect.params.transitions.slide;
if (slideP.wobbly) {
// Pin leading corners to their animated off-screen position, spring-simulate trailing corners
const auto dir = s_resolveSlideDir(effect.sourceRect, slideP.dir, slideP.autoCornerRatio);
const auto& dispSize = ImGui::GetIO().DisplaySize;
float fullDistX = 0.0f, fullDistY = 0.0f;
if (dir == ImGenieSlideDir_Left || dir == ImGenieSlideDir_TopLeft || dir == ImGenieSlideDir_BottomLeft) {
fullDistX = -effect.sourceRect.Max.x;
} else if (dir == ImGenieSlideDir_Right || dir == ImGenieSlideDir_TopRight || dir == ImGenieSlideDir_BottomRight) {
fullDistX = dispSize.x - effect.sourceRect.Min.x;
}
if (dir == ImGenieSlideDir_Top || dir == ImGenieSlideDir_TopLeft || dir == ImGenieSlideDir_TopRight) {
fullDistY = -effect.sourceRect.Max.y;
} else if (dir == ImGenieSlideDir_Bottom || dir == ImGenieSlideDir_BottomLeft || dir == ImGenieSlideDir_BottomRight) {
fullDistY = dispSize.y - effect.sourceRect.Min.y;
}
const auto t = ImClamp(effect.animT, 0.0f, 1.0f);
const auto eased = t * t * (3.0f - 2.0f * t);
const ImVec2 off(fullDistX * eased, fullDistY * eased);
// Determine pinned (leading) corners: TL=0, TR=1, BL=2, BR=3
bool pinned[4] = {false, false, false, false};
switch (dir) {
case ImGenieSlideDir_Left: pinned[0] = pinned[2] = true; break;
case ImGenieSlideDir_Right: pinned[1] = pinned[3] = true; break;
case ImGenieSlideDir_Top: pinned[0] = pinned[1] = true; break;
case ImGenieSlideDir_Bottom: pinned[2] = pinned[3] = true; break;
case ImGenieSlideDir_TopLeft: pinned[0] = true; break;
case ImGenieSlideDir_TopRight: pinned[1] = true; break;
case ImGenieSlideDir_BottomLeft: pinned[2] = true; break;
case ImGenieSlideDir_BottomRight: pinned[3] = true; break;
default: break;
}
// Pin leading corners
ImVec2 srcCorners[4];
s_cornersFromRect(effect.sourceRect, srcCorners);
for (int32_t i = 0; i < 4; ++i) {
if (pinned[i]) {
effect.springs[i].current = srcCorners[i] + off;
effect.springs[i].velocity = ImVec2(0.0f, 0.0f);
}
}
// Spring-simulate trailing corners toward their off-screen targets
ImVec2 targets[4];
for (int32_t i = 0; i < 4; ++i) { targets[i] = srcCorners[i] + off; }
s_updateSpringsUniform(effect, targets, slideP.spring, dt);
// Re-pin leading (spring update moved them)
for (int32_t i = 0; i < 4; ++i) {
if (pinned[i]) { effect.springs[i].current = srcCorners[i] + off; }
}
s_latticeDraw(pDrawList,
effect.capturedTex,
effect.springs[0].current,
effect.springs[1].current,
effect.springs[2].current,
effect.springs[3].current,
slideP.spring.cellsH,
slideP.spring.cellsV,
ImGenieAnimMode_Compress,
ctx.captureFlipV);