forked from ppy/osu-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Drawable.cs
2471 lines (2036 loc) · 93.6 KB
/
Drawable.cs
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) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Caching;
using osu.Framework.DebugUtils;
using osu.Framework.Extensions;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Input;
using osu.Framework.Lists;
using osu.Framework.Logging;
using osu.Framework.Statistics;
using osu.Framework.Threading;
using osu.Framework.Timing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Input;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics
{
/// <summary>
/// Drawables are the basic building blocks of a scene graph in this framework.
/// Anything that is visible or that the user interacts with has to be a Drawable.
///
/// For example:
/// - Boxes
/// - Sprites
/// - Collections of Drawables
///
/// Drawables are always rectangular in shape in their local coordinate system,
/// which makes them quad-shaped in arbitrary (linearly transformed) coordinate systems.
/// </summary>
public abstract class Drawable : IDisposable, IDrawable
{
#region Construction and disposal
protected Drawable()
{
creationID = creation_counter.Increment();
}
~Drawable()
{
dispose(false);
}
/// <summary>
/// Disposes this drawable.
/// </summary>
public void Dispose()
{
dispose(true);
GC.SuppressFinalize(this);
}
private bool isDisposed;
/// <summary>
/// Disposes this drawable.
/// </summary>
protected virtual void Dispose(bool isDisposing)
{
}
private void dispose(bool isDisposing)
{
if (isDisposed)
return;
//we can't dispose if we are mid-load, else our children may get in a bad state.
loadTask?.Wait();
Dispose(isDisposing);
Parent = null;
scheduler?.Dispose();
scheduler = null;
OnUpdate = null;
OnInvalidate = null;
// If this Drawable is disposed, then we need to also
// stop remotely rendering it.
proxy?.Dispose();
isDisposed = true;
}
/// <summary>
/// Whether this Drawable should be disposed when it is automatically removed from
/// its <see cref="Parent"/> due to <see cref="IsAlive"/> being false.
/// </summary>
public virtual bool DisposeOnDeathRemoval => false;
#endregion
#region Loading
/// <summary>
/// Whether this Drawable is fully loaded.
/// Override to false for delaying the load further (e.g. using <see cref="IsAlive"/>).
/// </summary>
public virtual bool IsLoaded => loadState >= LoadState.Loaded;
private volatile LoadState loadState;
/// <summary>
/// Describes the current state of this Drawable within the loading pipeline.
/// </summary>
public LoadState LoadState => loadState;
private Task loadTask;
private readonly object loadLock = new object();
/// <summary>
/// Loads this Drawable asynchronously.
/// </summary>
/// <param name="game">The game to load this Drawable on.</param>
/// <param name="target">
/// The target this Drawable may eventually be loaded into.
/// <see cref="Clock"/> and <see cref="Dependencies"/> are inherited from the target.
/// </param>
/// <param name="onLoaded">Callback to be invoked asynchronously after loading is complete.</param>
/// <returns>The task which is used for loading and callbacks.</returns>
internal Task LoadAsync(Game game, Drawable target, Action<Drawable> onLoaded = null)
{
if (loadState != LoadState.NotLoaded)
throw new InvalidOperationException($@"{nameof(LoadAsync)} may not be called more than once on the same Drawable.");
loadState = LoadState.Loading;
return loadTask = Task.Run(() => Load(target.Clock, target.Dependencies)).ContinueWith(task => game.Schedule(() =>
{
task.ThrowIfFaulted();
onLoaded?.Invoke(this);
loadTask = null;
}));
}
private static readonly StopwatchClock perf = new StopwatchClock(true);
/// <summary>
/// Create a local dependency container which will be used by ourselves and all our nested children.
/// If not overridden, the load-time parent's dependency tree will be used.
/// </summary>
/// <param name="parent">The parent <see cref="DependencyContainer"/> which should be passed through if we want fallback lookups to work.</param>
/// <returns>A new dependency container to be stored for this Drawable.</returns>
protected virtual DependencyContainer CreateLocalDependencies(DependencyContainer parent) => parent;
/// <summary>
/// Contains all dependencies that can be injected into this Drawable using <see cref="BackgroundDependencyLoader"/>.
/// Add or override dependencies by calling <see cref="DependencyContainer.Cache{T}(T, bool, bool)"/>.
/// </summary>
protected DependencyContainer Dependencies { get; private set; }
/// <summary>
/// Loads this drawable, including the gathering of dependencies and initialisation of required resources.
/// </summary>
/// <param name="clock">The clock we should use by default.</param>
/// <param name="dependencies">The dependency tree we will inherit by default. May be extended via <see cref="CreateLocalDependencies(DependencyContainer)"/></param>
internal void Load(IFrameBasedClock clock, DependencyContainer dependencies)
{
// Blocks when loading from another thread already.
lock (loadLock)
{
switch (loadState)
{
case LoadState.Loaded:
case LoadState.Alive:
return;
case LoadState.Loading:
break;
case LoadState.NotLoaded:
loadState = LoadState.Loading;
break;
default:
Trace.Assert(false, "Impossible loading state.");
break;
}
UpdateClock(clock);
double t1 = perf.CurrentTime;
// get our dependencies from our parent, but allow local overriding of our inherited dependency container
Dependencies = CreateLocalDependencies(dependencies);
Dependencies.Initialize(this);
double elapsed = perf.CurrentTime - t1;
if (perf.CurrentTime > 1000 && elapsed > 50 && ThreadSafety.IsUpdateThread)
Logger.Log($@"Drawable [{ToString()}] took {elapsed:0.00}ms to load and was not async!", LoggingTarget.Performance);
loadState = LoadState.Loaded;
}
}
/// <summary>
/// Runs once on the update thread after loading has finished.
/// </summary>
private bool loadComplete()
{
if (loadState < LoadState.Loaded) return false;
MainThread = Thread.CurrentThread;
scheduler?.SetCurrentThread(MainThread);
Invalidate();
loadState = LoadState.Alive;
LoadComplete();
OnLoadComplete?.Invoke(this);
return true;
}
/// <summary>
/// Play initial animation etc.
/// </summary>
protected virtual void LoadComplete()
{
}
#endregion
#region Sorting (CreationID / Depth)
/// <summary>
/// Captures the order in which Drawables were created. Each Drawable
/// is assigned a unique, monotonically increasing ID upon creation in a thread-safe manner.
/// The primary use case of this ID is stable sorting of Drawables with equal
/// <see cref="Depth"/>.
/// </summary>
private long creationID { get; }
private static readonly AtomicCounter creation_counter = new AtomicCounter();
private float depth;
/// <summary>
/// Controls which Drawables are behind or in front of other Drawables.
/// This amounts to sorting Drawables by their <see cref="Depth"/>.
/// A Drawable with higher <see cref="Depth"/> than another Drawable is
/// drawn behind the other Drawable.
/// </summary>
public float Depth
{
get { return depth; }
set
{
// TODO: Consider automatically resorting the parents children instead of simply forbidding this.
if (Parent != null)
throw new InvalidOperationException("May not change depth while inside a parent container.");
depth = value;
}
}
public class CreationOrderDepthComparer : IComparer<Drawable>
{
public virtual int Compare(Drawable x, Drawable y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int i = y.Depth.CompareTo(x.Depth);
if (i != 0) return i;
return x.creationID.CompareTo(y.creationID);
}
}
public class ReverseCreationOrderDepthComparer : IComparer<Drawable>
{
public virtual int Compare(Drawable x, Drawable y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int i = y.Depth.CompareTo(x.Depth);
if (i != 0) return i;
return y.creationID.CompareTo(x.creationID);
}
}
protected virtual IComparer<Drawable> DepthComparer => new CreationOrderDepthComparer();
#endregion
#region Periodic tasks (events, Scheduler, Transforms, Update)
/// <summary>
/// This event is fired after the <see cref="Update"/> method is called at the end of
/// <see cref="UpdateSubTree"/>. It should be used when a simple action should be performed
/// at the end of every update call which does not warrant overriding the Drawable.
/// </summary>
public Action<Drawable> OnUpdate;
/// <summary>
/// This event is fired after the <see cref="LoadComplete"/> method is called.
/// It should be used when a simple action should be performed
/// when the Drawable is loaded which does not warrant overriding the Drawable.
/// </summary>
public Action<Drawable> OnLoadComplete;
/// <summary>
/// THIS EVENT PURELY EXISTS FOR THE SCENE GRAPH VISUALIZER. DO NOT USE.
/// This event is fired after the <see cref="Invalidate(Invalidation, Drawable, bool)"/> method is called.
/// </summary>
internal event Action<Drawable> OnInvalidate;
private Scheduler scheduler;
internal Thread MainThread { get; private set; }
/// <summary>
/// A lazily-initialized scheduler used to schedule tasks to be invoked in future <see cref="Update"/>s calls.
/// The tasks are invoked at the beginning of the <see cref="Update"/> method before anything else.
/// </summary>
protected Scheduler Scheduler => scheduler ?? (scheduler = new Scheduler(MainThread));
private LifetimeList<ITransform> transforms;
/// <summary>
/// A lazily-initialized list of <see cref="ITransform"/>s applied to this Drawable.
/// <see cref="ITransform"/>s are applied right before the <see cref="Update"/> method is called.
/// </summary>
public LifetimeList<ITransform> Transforms
{
get
{
if (transforms == null)
{
transforms = new LifetimeList<ITransform>(new TransformTimeComparer());
transforms.Removed += transforms_OnRemoved;
}
return transforms;
}
}
/// <summary>
/// Process updates to this drawable based on loaded transforms.
/// </summary>
/// <returns>Whether we should draw this drawable.</returns>
private void updateTransforms()
{
if (transforms == null || transforms.Count == 0) return;
transforms.Update(Time);
foreach (ITransform t in transforms.AliveItems)
t.Apply(this);
}
private void transforms_OnRemoved(ITransform t)
{
t.Apply(this); //make sure we apply one last time.
}
/// <summary>
/// Updates this Drawable and all Drawables further down the scene graph.
/// Called once every frame.
/// </summary>
/// <returns>False if the drawable should not be updated.</returns>
public virtual bool UpdateSubTree()
{
if (isDisposed)
throw new ObjectDisposedException(ToString(), "Disposed Drawables may never be in the scene graph.");
if (Parent != null) //we don't want to update our clock if we are at the top of the stack. it's handled elsewhere for us.
customClock?.ProcessFrame();
if (loadState < LoadState.Alive)
if (!loadComplete()) return false;
TransformDelay = 0;
//todo: this should be moved to after the IsVisible condition once we have TOL for transforms (and some better logic).
updateTransforms();
if (!IsPresent)
return true;
if (scheduler != null)
{
int amountScheduledTasks = scheduler.Update();
FrameStatistics.Increment(StatisticsCounterType.ScheduleInvk, amountScheduledTasks);
}
Update();
OnUpdate?.Invoke(this);
return true;
}
/// <summary>
/// Performs a once-per-frame update specific to this Drawable. A more elegant alternative to
/// <see cref="OnUpdate"/> when deriving from <see cref="Drawable"/>. Note, that this
/// method is always called before Drawables further down the scene graph are updated.
/// </summary>
protected virtual void Update()
{
}
#endregion
#region Position / Size (with margin)
private Vector2 position
{
get { return new Vector2(x, y); }
set
{
x = value.X;
y = value.Y;
}
}
/// <summary>
/// Positional offset of <see cref="Origin"/> to <see cref="RelativeAnchorPosition"/> in the
/// <see cref="Parent"/>'s coordinate system. May be in absolute or relative units
/// (controlled by <see cref="RelativePositionAxes"/>).
/// </summary>
public Vector2 Position
{
get { return position; }
set
{
if (position == value) return;
position = value;
Invalidate(Invalidation.Geometry);
}
}
private float x;
private float y;
/// <summary>
/// X component of <see cref="Position"/>.
/// </summary>
public float X
{
get { return x; }
set
{
if (x == value) return;
x = value;
Invalidate(Invalidation.Geometry);
}
}
/// <summary>
/// Y component of <see cref="Position"/>.
/// </summary>
public float Y
{
get { return y; }
set
{
if (y == value) return;
y = value;
Invalidate(Invalidation.Geometry);
}
}
private Axes relativePositionAxes;
/// <summary>
/// Controls which <see cref="Axes"/> of <see cref="Position"/> are relative w.r.t.
/// <see cref="Parent"/>'s size (from 0 to 1) rather than absolute.
/// The <see cref="Axes"/> set in this property are ignored by automatically sizing
/// parents.
/// </summary>
/// <remarks>
/// When setting this property, the <see cref="Position"/> is converted such that
/// <see cref="DrawPosition"/> remains invariant.
/// </remarks>
public Axes RelativePositionAxes
{
get { return relativePositionAxes; }
set
{
if (value == relativePositionAxes)
return;
// Convert coordinates from relative to absolute or vice versa
Vector2 conversion = relativeToAbsoluteFactor;
if ((value & Axes.X) > (relativePositionAxes & Axes.X))
X = conversion.X == 0 ? 0 : X / conversion.X;
else if ((relativePositionAxes & Axes.X) > (value & Axes.X))
X *= conversion.X;
if ((value & Axes.Y) > (relativePositionAxes & Axes.Y))
Y = conversion.Y == 0 ? 0 : Y / conversion.Y;
else if ((relativePositionAxes & Axes.X) > (value & Axes.X))
Y *= conversion.Y;
relativePositionAxes = value;
// No invalidation necessary as DrawPosition remains invariant.
}
}
/// <summary>
/// Absolute positional offset of <see cref="Origin"/> to <see cref="RelativeAnchorPosition"/>
/// in the <see cref="Parent"/>'s coordinate system.
/// </summary>
public Vector2 DrawPosition
{
get
{
Vector2 offset = Vector2.Zero;
if (Parent != null && RelativePositionAxes != Axes.None)
{
offset = Parent.RelativeChildOffset;
if ((RelativePositionAxes & Axes.X) == 0)
offset.X = 0;
if ((RelativePositionAxes & Axes.Y) == 0)
offset.Y = 0;
}
return applyRelativeAxes(RelativePositionAxes, Position - offset);
}
}
private Vector2 size
{
get { return new Vector2(width, height); }
set
{
width = value.X;
height = value.Y;
}
}
/// <summary>
/// Size of this Drawable in the <see cref="Parent"/>'s coordinate system.
/// May be in absolute or relative units (controlled by <see cref="RelativeSizeAxes"/>).
/// </summary>
public virtual Vector2 Size
{
get { return size; }
set
{
if (size == value) return;
size = value;
Invalidate(Invalidation.Geometry);
}
}
private float width;
private float height;
/// <summary>
/// X component of <see cref="Size"/>.
/// </summary>
public virtual float Width
{
get { return width; }
set
{
if (width == value) return;
width = value;
Invalidate(Invalidation.Geometry);
}
}
/// <summary>
/// Y component of <see cref="Size"/>.
/// </summary>
public virtual float Height
{
get { return height; }
set
{
if (height == value) return;
height = value;
Invalidate(Invalidation.Geometry);
}
}
private Axes relativeSizeAxes;
/// <summary>
/// Controls which <see cref="Axes"/> are relative sizes w.r.t. <see cref="Parent"/>'s size
/// (from 0 to 1) in the <see cref="Parent"/>'s coordinate system, rather than absolute sizes.
/// The <see cref="Axes"/> set in this property are ignored by automatically sizing
/// parents.
/// </summary>
/// <remarks>
/// If an axis becomes relatively sized and its component of <see cref="Size"/> was previously 0,
/// then it automatically becomes 1. In all other cases <see cref="Size"/> is converted such that
/// <see cref="DrawSize"/> remains invariant across changes of this property.
/// </remarks>
public virtual Axes RelativeSizeAxes
{
get { return relativeSizeAxes; }
set
{
if (value == relativeSizeAxes)
return;
// Convert coordinates from relative to absolute or vice versa
Vector2 conversion = relativeToAbsoluteFactor;
if ((value & Axes.X) > (relativeSizeAxes & Axes.X))
Width = conversion.X == 0 ? 0 : Width / conversion.X;
else if ((relativeSizeAxes & Axes.X) > (value & Axes.X))
Width *= conversion.X;
if ((value & Axes.Y) > (relativeSizeAxes & Axes.Y))
Height = conversion.Y == 0 ? 0 : Height / conversion.Y;
else if ((relativeSizeAxes & Axes.Y) > (value & Axes.Y))
Height *= conversion.Y;
relativeSizeAxes = value;
if ((relativeSizeAxes & Axes.X) > 0 && Width == 0) Width = 1;
if ((relativeSizeAxes & Axes.Y) > 0 && Height == 0) Height = 1;
// No invalidation necessary as DrawSize remains invariant.
}
}
private Cached<Vector2> drawSizeBacking = new Cached<Vector2>();
/// <summary>
/// Absolute size of this Drawable in the <see cref="Parent"/>'s coordinate system.
/// </summary>
public Vector2 DrawSize => drawSizeBacking.EnsureValid()
? drawSizeBacking.Value
: drawSizeBacking.Refresh(() => applyRelativeAxes(RelativeSizeAxes, Size));
/// <summary>
/// X component of <see cref="DrawSize"/>.
/// </summary>
public float DrawWidth => DrawSize.X;
/// <summary>
/// Y component of <see cref="DrawSize"/>.
/// </summary>
public float DrawHeight => DrawSize.Y;
private MarginPadding margin;
/// <summary>
/// Size of an empty region around this Drawable used to manipulate
/// layout. Does not affect <see cref="DrawSize"/> or the region of accepted input,
/// but does affect <see cref="LayoutSize"/>.
/// </summary>
public MarginPadding Margin
{
get { return margin; }
set
{
if (margin.Equals(value)) return;
margin = value;
margin.ThrowIfNegative();
Invalidate(Invalidation.Geometry);
}
}
/// <summary>
/// Absolute size of this Drawable's layout rectangle in the <see cref="Parent"/>'s
/// coordinate system; i.e. <see cref="DrawSize"/> with the addition of <see cref="Margin"/>.
/// </summary>
public Vector2 LayoutSize => DrawSize + new Vector2(margin.TotalHorizontal, margin.TotalVertical);
/// <summary>
/// Absolutely sized rectangle for drawing in the <see cref="Parent"/>'s coordinate system.
/// Based on <see cref="DrawSize"/>.
/// </summary>
public RectangleF DrawRectangle
{
get
{
Vector2 s = DrawSize;
return new RectangleF(0, 0, s.X, s.Y);
}
}
/// <summary>
/// Absolutely sized rectangle for layout in the <see cref="Parent"/>'s coordinate system.
/// Based on <see cref="LayoutSize"/> and <see cref="margin"/>.
/// </summary>
public RectangleF LayoutRectangle
{
get
{
Vector2 s = LayoutSize;
return new RectangleF(-margin.Left, -margin.Top, s.X, s.Y);
}
}
/// <summary>
/// Helper function for converting potentially relative coordinates in the
/// <see cref="Parent"/>'s space to absolute coordinates based on which
/// axes are relative. <see cref="Axes"/>
/// </summary>
/// <param name="relativeAxes">Describes which axes are relative.</param>
/// <param name="v">The coordinates to convert.</param>
/// <returns>Absolute coordinates in <see cref="Parent"/>'s space.</returns>
private Vector2 applyRelativeAxes(Axes relativeAxes, Vector2 v)
{
if (relativeAxes != Axes.None)
{
Vector2 conversion = relativeToAbsoluteFactor;
if ((relativeAxes & Axes.X) > 0)
v.X *= conversion.X;
if ((relativeAxes & Axes.Y) > 0)
v.Y *= conversion.Y;
}
return v;
}
/// <summary>
/// Conversion factor from relative to absolute coordinates in the <see cref="Parent"/>'s space.
/// </summary>
private Vector2 relativeToAbsoluteFactor => Parent?.RelativeToAbsoluteFactor ?? Vector2.One;
private Axes bypassAutoSizeAxes;
/// <summary>
/// Controls which <see cref="Axes"/> are ignored by parent <see cref="Parent"/> automatic sizing.
/// Most notably, <see cref="RelativePositionAxes"/> and <see cref="RelativeSizeAxes"/> do not affect
/// automatic sizing to avoid circular size dependencies.
/// </summary>
public Axes BypassAutoSizeAxes
{
get { return bypassAutoSizeAxes | relativeSizeAxes | relativePositionAxes; }
set
{
if (value == bypassAutoSizeAxes)
return;
bypassAutoSizeAxes = value;
Parent?.InvalidateFromChild(Invalidation.Geometry);
}
}
/// <summary>
/// Computes the bounding box of this drawable in its parent's space.
/// </summary>
public virtual RectangleF BoundingBox => ToParentSpace(LayoutRectangle).AABBFloat;
#endregion
#region Scale / Shear / Rotation
private Vector2 scale = Vector2.One;
/// <summary>
/// Base relative scaling factor around <see cref="OriginPosition"/>.
/// </summary>
public Vector2 Scale
{
get { return scale; }
set
{
if (scale == value) return;
scale = value;
Invalidate(Invalidation.Geometry);
}
}
/// <summary>
/// The method to use to fill this drawable's parent space.
/// </summary>
public FillMode FillMode { get; set; }
/// <summary>
/// Relative scaling factor around <see cref="OriginPosition"/>.
/// </summary>
protected virtual Vector2 DrawScale
{
get
{
if (FillMode == FillMode.None)
return Scale;
Vector2 modifier = Vector2.One;
Vector2 relativeToAbsolute = relativeToAbsoluteFactor;
switch (FillMode)
{
case FillMode.Fill:
modifier = new Vector2(Math.Max(relativeToAbsolute.X / DrawWidth, relativeToAbsolute.Y / DrawHeight));
break;
case FillMode.Fit:
modifier = new Vector2(Math.Min(relativeToAbsolute.X / DrawWidth, relativeToAbsolute.Y / DrawHeight));
break;
case FillMode.Stretch:
modifier = new Vector2(relativeToAbsolute.X / DrawWidth, relativeToAbsolute.Y / DrawHeight);
break;
}
return Scale * modifier;
}
}
private Vector2 shear = Vector2.Zero;
/// <summary>
/// Relative shearing factor. The X dimension is relative w.r.t. <see cref="Height"/>
/// and the Y dimension relative w.r.t. <see cref="Width"/>.
/// </summary>
public Vector2 Shear
{
get { return shear; }
set
{
if (shear == value) return;
shear = value;
Invalidate(Invalidation.Geometry);
}
}
private float rotation;
/// <summary>
/// Rotation in degrees around <see cref="OriginPosition"/>.
/// </summary>
public float Rotation
{
get { return rotation; }
set
{
if (value == rotation) return;
rotation = value;
Invalidate(Invalidation.Geometry);
}
}
#endregion
#region Origin / Anchor
private Anchor origin = Anchor.TopLeft;
/// <summary>
/// The origin of the local coordinate system of this Drawable.
/// Can either be one of 9 relative positions (0, 0.5, and 1 in x and y)
/// or a fixed absolute position via <see cref="OriginPosition"/>.
/// </summary>
public virtual Anchor Origin
{
get { return origin; }
set
{
if (origin == value) return;
if (value == 0)
throw new ArgumentException("Cannot set origin to 0.", nameof(value));
origin = value;
Invalidate(Invalidation.Geometry);
}
}
private Vector2 customOrigin;
/// <summary>
/// The origin of the local coordinate system of this Drawable
/// in relative coordinates expressed in the coordinate system with origin at the
/// top left corner of the <see cref="DrawRectangle"/> (not <see cref="LayoutRectangle"/>).
/// </summary>
public Vector2 RelativeOriginPosition
{
get
{
if (Origin == Anchor.Custom)
throw new InvalidOperationException(@"Can not obtain relative origin position for custom origins.");
Vector2 result = Vector2.Zero;
if ((origin & Anchor.x1) > 0)
result.X = 0.5f;
else if ((origin & Anchor.x2) > 0)
result.X = 1;
if ((origin & Anchor.y1) > 0)
result.Y = 0.5f;
else if ((origin & Anchor.y2) > 0)
result.Y = 1;
return result;
}
}
/// <summary>
/// The origin of the local coordinate system of this Drawable
/// in absolute coordinates expressed in the coordinate system with origin at the
/// top left corner of the <see cref="DrawRectangle"/> (not <see cref="LayoutRectangle"/>).
/// </summary>
public virtual Vector2 OriginPosition
{
get
{
Vector2 result;
if (Origin == Anchor.Custom)
result = customOrigin;
else if (Origin == Anchor.TopLeft)
result = Vector2.Zero;
else
result = computeAnchorPosition(LayoutSize, Origin);
return result - new Vector2(margin.Left, margin.Top);
}
set
{
customOrigin = value;
Origin = Anchor.Custom;
}
}
private Anchor anchor = Anchor.TopLeft;
/// <summary>
/// Specifies where <see cref="Origin"/> is attached to the <see cref="Parent"/>
/// in the coordinate system with origin at the top left corner of the
/// <see cref="Parent"/>'s <see cref="DrawRectangle"/>.
/// Can either be one of 9 relative positions (0, 0.5, and 1 in x and y)
/// or a fixed absolute position via <see cref="RelativeAnchorPosition"/>.
/// </summary>
public Anchor Anchor
{
get { return anchor; }
set
{
if (anchor == value) return;
if (value == 0)
throw new ArgumentException("Cannot set anchor to 0.", nameof(value));
anchor = value;
Invalidate(Invalidation.Geometry);
}
}
private Vector2 customRelativeAnchorPosition;
/// <summary>
/// Specifies in relative coordinates where <see cref="Origin"/> is attached
/// to the <see cref="Parent"/> in the coordinate system with origin at the top
/// left corner of the <see cref="Parent"/>'s <see cref="DrawRectangle"/>, and
/// a value of <see cref="Vector2.One"/> referring to the bottom right corner of
/// the <see cref="Parent"/>'s <see cref="DrawRectangle"/>.
/// </summary>
public Vector2 RelativeAnchorPosition
{
get
{
if (Anchor == Anchor.Custom)
return customRelativeAnchorPosition;
Vector2 result = Vector2.Zero;
if ((anchor & Anchor.x1) > 0)
result.X = 0.5f;
else if ((anchor & Anchor.x2) > 0)
result.X = 1;
if ((anchor & Anchor.y1) > 0)
result.Y = 0.5f;
else if ((anchor & Anchor.y2) > 0)
result.Y = 1;
return result;
}
set
{
customRelativeAnchorPosition = value;
Anchor = Anchor.Custom;
}