-
Notifications
You must be signed in to change notification settings - Fork 421
/
Drawable.cs
2857 lines (2315 loc) · 113 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) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osuTK;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Input;
using osu.Framework.Logging;
using osu.Framework.Statistics;
using osu.Framework.Threading;
using osu.Framework.Timing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Threading;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Development;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics.Rendering;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osu.Framework.Layout;
using osu.Framework.Utils;
using osuTK.Input;
using Container = osu.Framework.Graphics.Containers.Container;
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 partial class Drawable : Transformable, IDisposable, IDrawable
{
#region Construction and disposal
[Resolved(CanBeNull = true)]
private IRenderer renderer { get; set; }
protected Drawable()
{
total_count.Value++;
AddLayout(drawInfoBacking);
AddLayout(drawSizeBacking);
AddLayout(screenSpaceDrawQuadBacking);
AddLayout(drawColourInfoBacking);
AddLayout(requiredParentSizeToFitBacking);
AddLayout(maskingBacking);
}
private static readonly GlobalStatistic<int> total_count = GlobalStatistics.Get<int>(nameof(Drawable), "Total constructed");
/// <summary>
/// Disposes this drawable.
/// </summary>
public void Dispose()
{
//we can't dispose if we are mid-load, else our children may get in a bad state.
lock (LoadLock) Dispose(true);
GC.SuppressFinalize(this);
}
protected internal bool IsDisposed { get; private set; }
/// <summary>
/// Disposes this drawable.
/// </summary>
protected virtual void Dispose(bool isDisposing)
{
if (IsDisposed)
return;
UnbindAllBindables();
// Bypass expensive operations as a result of setting the Parent property, by setting the field directly.
parent = null;
ChildID = 0;
OnUpdate = null;
Invalidated = null;
OnDispose?.Invoke();
OnDispose = null;
renderer?.ScheduleDisposal(d =>
{
for (int i = 0; i < d.drawNodes.Length; i++)
d.drawNodes[i]?.Dispose();
}, this);
IsDisposed = true;
}
/// <summary>
/// Whether this Drawable should be disposed when it is automatically removed from
/// its <see cref="Parent"/> due to <see cref="ShouldBeAlive"/> being false.
/// </summary>
public virtual bool DisposeOnDeathRemoval => RemoveCompletedTransforms;
private static readonly ConcurrentDictionary<Type, Action<object>> unbind_action_cache = new ConcurrentDictionary<Type, Action<object>>();
/// <summary>
/// Recursively invokes <see cref="UnbindAllBindables"/> on this <see cref="Drawable"/> and all <see cref="Drawable"/>s further down the scene graph.
/// </summary>
internal virtual void UnbindAllBindablesSubTree() => UnbindAllBindables();
private Action<object> getUnbindAction()
{
Type ourType = GetType();
return unbind_action_cache.TryGetValue(ourType, out var action) ? action : cacheUnbindAction(ourType);
// Extracted to a separate method to prevent .NET from pre-allocating some objects (saves ~150B per call to this method, even if already cached).
static Action<object> cacheUnbindAction(Type ourType)
{
List<Action<object>> actions = new List<Action<object>>();
foreach (var type in ourType.EnumerateBaseTypes())
{
// Generate delegates to unbind fields
actions.AddRange(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(f => typeof(IUnbindable).IsAssignableFrom(f.FieldType))
.Select(f => new Action<object>(target => ((IUnbindable)f.GetValue(target))?.UnbindAll())));
}
// Delegates to unbind properties are intentionally not generated.
// Properties with backing fields (including automatic properties) will be picked up by the field unbind delegate generation,
// while ones without backing fields (like get-only properties that delegate to another drawable's bindable) should not be unbound here.
return unbind_action_cache[ourType] = target =>
{
foreach (var a in actions)
{
try
{
a(target);
}
catch (Exception e)
{
Logger.Error(e, $"Failed to unbind a local bindable in {ourType.ReadableName()}");
}
}
};
}
}
private bool unbindComplete;
/// <summary>
/// Unbinds all <see cref="Bindable{T}"/>s stored as fields or properties in this <see cref="Drawable"/>.
/// </summary>
internal virtual void UnbindAllBindables()
{
if (unbindComplete)
return;
unbindComplete = true;
getUnbindAction().Invoke(this);
OnUnbindAllBindables?.Invoke();
}
#endregion
#region Loading
/// <summary>
/// Whether this Drawable is fully loaded.
/// This is true iff <see cref="UpdateSubTree"/> has run once on this <see cref="Drawable"/>.
/// </summary>
public 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;
/// <summary>
/// The thread on which the <see cref="Load"/> operation started, or null if <see cref="Drawable"/> has not started loading.
/// </summary>
internal Thread LoadThread { get; private set; }
internal readonly object LoadLock = new object();
private static readonly StopwatchClock perf_clock = new StopwatchClock(true);
/// <summary>
/// Load this drawable from an async context.
/// Because we can't be sure of the disposal state, it is returned as a bool rather than thrown as in <see cref="Load"/>.
/// </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="CompositeDrawable.CreateChildDependencies"/></param>
/// <param name="isDirectAsyncContext">Whether this call is being executed from a directly async context (not a parent).</param>
/// <returns>Whether the load was successful.</returns>
internal bool LoadFromAsync(IFrameBasedClock clock, IReadOnlyDependencyContainer dependencies, bool isDirectAsyncContext = false)
{
lock (LoadLock)
{
if (IsDisposed)
return false;
Load(clock, dependencies, isDirectAsyncContext);
return true;
}
}
/// <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="CompositeDrawable.CreateChildDependencies"/></param>
/// <param name="isDirectAsyncContext">Whether this call is being executed from a directly async context (not a parent).</param>
internal void Load(IFrameBasedClock clock, IReadOnlyDependencyContainer dependencies, bool isDirectAsyncContext = false)
{
lock (LoadLock)
{
if (!isDirectAsyncContext && IsLongRunning)
{
throw new InvalidOperationException(
$"Tried to load long-running drawable type {GetType().ReadableName()} in a non-direct async context. See https://git.io/Je1YF for more details.");
}
ObjectDisposedException.ThrowIf(IsDisposed, this);
if (loadState == LoadState.NotLoaded)
{
Trace.Assert(loadState == LoadState.NotLoaded);
loadState = LoadState.Loading;
load(clock, dependencies);
loadState = LoadState.Ready;
}
}
}
private void load(IFrameBasedClock clock, IReadOnlyDependencyContainer dependencies)
{
LoadThread = Thread.CurrentThread;
// Cache eagerly during load to hopefully defer the reflection overhead to an async pathway.
getUnbindAction();
UpdateClock(clock);
double timeBefore = DebugUtils.LogPerformanceIssues ? perf_clock.CurrentTime : 0;
RequestsNonPositionalInput = HandleInputCache.RequestsNonPositionalInput(this);
RequestsPositionalInput = HandleInputCache.RequestsPositionalInput(this);
RequestsNonPositionalInputSubTree = RequestsNonPositionalInput;
RequestsPositionalInputSubTree = RequestsPositionalInput;
InjectDependencies(dependencies);
LoadAsyncComplete();
if (timeBefore > 1000)
{
double loadDuration = perf_clock.CurrentTime - timeBefore;
bool blocking = ThreadSafety.IsUpdateThread;
double allowedDuration = blocking ? 16 : 100;
if (loadDuration > allowedDuration)
{
Logger.Log($@"{ToString()} took {loadDuration:0.00}ms to load" + (blocking ? " (and blocked the update thread)" : " (async)"), LoggingTarget.Performance,
blocking ? LogLevel.Important : LogLevel.Verbose);
}
}
}
/// <summary>
/// Injects dependencies from an <see cref="IReadOnlyDependencyContainer"/> into this <see cref="Drawable"/>.
/// </summary>
/// <param name="dependencies">The dependencies to inject.</param>
protected virtual void InjectDependencies(IReadOnlyDependencyContainer dependencies) => dependencies.Inject(this);
/// <summary>
/// Runs once on the update thread after loading has finished.
/// </summary>
private bool loadComplete()
{
if (loadState < LoadState.Ready) return false;
loadState = LoadState.Loaded;
// From a synchronous point of view, this is the first time the Drawable receives a parent.
// If this Drawable calculated properties such as DrawInfo that depend on the parent state before this point, they must be re-validated in the now-correct state.
// A "parent" source is faked since Child+Self states are always assumed valid if they only access local Drawable states (e.g. Colour but not DrawInfo).
// Only layout flags are required, as non-layout flags are always propagated by the parent.
Invalidate(Invalidation.Layout, InvalidationSource.Parent);
LoadComplete();
OnLoadComplete?.Invoke(this);
OnLoadComplete = null;
return true;
}
/// <summary>
/// Invoked after dependency injection has completed for this <see cref="Drawable"/> and all
/// children if this is a <see cref="CompositeDrawable"/>.
/// </summary>
/// <remarks>
/// This method is invoked in the potentially asynchronous context of <see cref="Load"/> prior to
/// this <see cref="Drawable"/> becoming <see cref="IsLoaded"/> = true.
/// </remarks>
protected virtual void LoadAsyncComplete()
{
}
/// <summary>
/// Invoked after this <see cref="Drawable"/> has finished loading.
/// </summary>
/// <remarks>
/// This method is invoked on the update thread inside this <see cref="Drawable"/>'s <see cref="UpdateSubTree"/>.
/// </remarks>
protected virtual void LoadComplete()
{
}
#endregion
#region Sorting (CreationID / Depth)
/// <summary>
/// Captures the order in which Drawables were added to a <see cref="CompositeDrawable"/>. Each Drawable
/// is assigned a monotonically increasing ID upon being added to a <see cref="CompositeDrawable"/>. This
/// ID is unique within the <see cref="Parent"/> <see cref="CompositeDrawable"/>.
/// The primary use case of this ID is stable sorting of Drawables with equal <see cref="Depth"/>.
/// </summary>
internal ulong ChildID { get; set; }
/// <summary>
/// Whether this drawable has been added to a parent <see cref="CompositeDrawable"/>. Note that this does NOT imply that
/// <see cref="Parent"/> has been set.
/// This is primarily used to block properties such as <see cref="Depth"/> that strictly rely on the value of <see cref="Parent"/>
/// to alert the user of an invalid operation.
/// </summary>
internal bool IsPartOfComposite => ChildID != 0;
/// <summary>
/// Whether this drawable is part of its parent's <see cref="CompositeDrawable.AliveInternalChildren"/>.
/// </summary>
public bool IsAlive { get; internal set; }
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 => depth;
set
{
if (IsPartOfComposite)
{
throw new InvalidOperationException(
$"May not change {nameof(Depth)} while inside a parent {nameof(CompositeDrawable)}." +
$"Use the parent's {nameof(CompositeDrawable.ChangeInternalChildDepth)} or {nameof(Container.ChangeChildDepth)} instead.");
}
depth = value;
}
}
#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 event 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.
/// This event is automatically cleared after being invoked.
/// </summary>
public event Action<Drawable> OnLoadComplete;
/// <summary>.
/// Fired after the <see cref="Invalidate"/> method is called.
/// </summary>
internal event Action<Drawable, Invalidation> Invalidated;
/// <summary>
/// Fired after the <see cref="Dispose(bool)"/> method is called.
/// </summary>
internal event Action OnDispose;
/// <summary>
/// Fired after the <see cref="UnbindAllBindables"/> method is called.
/// </summary>
internal event Action OnUnbindAllBindables;
/// <summary>
/// A lock exclusively used for initial acquisition/construction of the <see cref="Scheduler"/>.
/// </summary>
private static readonly object scheduler_acquisition_lock = new object();
private volatile Scheduler scheduler;
/// <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 internal Scheduler Scheduler
{
get
{
if (scheduler != null)
return scheduler;
lock (scheduler_acquisition_lock)
{
if (scheduler != null)
return scheduler;
scheduler = new Scheduler(() => ThreadSafety.IsUpdateThread, Clock);
}
return scheduler;
}
}
/// <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()
{
ObjectDisposedException.ThrowIf(IsDisposed, this);
if (ProcessCustomClock)
customClock?.ProcessFrame();
if (loadState < LoadState.Ready)
return false;
if (loadState == LoadState.Ready)
loadComplete();
Debug.Assert(loadState == LoadState.Loaded);
UpdateTransforms();
if (!IsPresent)
return true;
if (scheduler != null)
{
int amountScheduledTasks = scheduler.Update();
FrameStatistics.Add(StatisticsCounterType.ScheduleInvk, amountScheduledTasks);
}
Update();
OnUpdate?.Invoke(this);
return true;
}
/// <summary>
/// Computes the masking bounds of this <see cref="Drawable"/>.
/// </summary>
/// <returns>The <see cref="RectangleF"/> that defines the masking bounds.</returns>
public virtual RectangleF ComputeMaskingBounds()
{
if (HasProxy)
return proxy.ComputeMaskingBounds();
if (parent == null)
return ScreenSpaceDrawQuad.AABBFloat;
return parent.ChildMaskingBounds;
}
private RectangleF? lastMaskingBounds;
/// <summary>
/// Updates all masking calculations for this <see cref="Drawable"/>.
/// This occurs post-<see cref="UpdateSubTree"/> to ensure that all <see cref="Drawable"/> updates have taken place.
/// </summary>
/// <returns>Whether masking calculations have taken place.</returns>
public virtual bool UpdateSubTreeMasking()
{
if (!IsPresent)
return false;
var maskingBounds = ComputeMaskingBounds();
if (!maskingBacking.IsValid || lastMaskingBounds != maskingBounds)
{
lastMaskingBounds = maskingBounds;
IsMaskedAway = maskingBacking.Value = ComputeIsMaskedAway(maskingBounds);
}
return true;
}
/// <summary>
/// Computes whether this <see cref="Drawable"/> is masked away.
/// </summary>
/// <param name="maskingBounds">The <see cref="RectangleF"/> that defines the masking bounds.</param>
/// <returns>Whether this <see cref="Drawable"/> is currently masked away.</returns>
protected virtual bool ComputeIsMaskedAway(RectangleF maskingBounds) => !Precision.AlmostIntersects(maskingBounds, ScreenSpaceDrawQuad.AABBFloat);
/// <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 => 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 => position;
set
{
if (position == value) return;
if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Position)} must be finite, but is {value}.");
Axes changedAxes = Axes.None;
if (position.X != value.X)
changedAxes |= Axes.X;
if (position.Y != value.Y)
changedAxes |= Axes.Y;
position = value;
invalidateParentSizeDependencies(Invalidation.MiscGeometry, changedAxes);
}
}
private float x;
private float y;
/// <summary>
/// X component of <see cref="Position"/>.
/// </summary>
public float X
{
get => x;
set
{
if (x == value) return;
if (!float.IsFinite(value)) throw new ArgumentException($@"{nameof(X)} must be finite, but is {value}.");
x = value;
invalidateParentSizeDependencies(Invalidation.MiscGeometry, Axes.X);
}
}
/// <summary>
/// Y component of <see cref="Position"/>.
/// </summary>
public float Y
{
get => y;
set
{
if (y == value) return;
if (!float.IsFinite(value)) throw new ArgumentException($@"{nameof(Y)} must be finite, but is {value}.");
y = value;
invalidateParentSizeDependencies(Invalidation.MiscGeometry, Axes.Y);
}
}
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 => 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 = Precision.AlmostEquals(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 = Precision.AlmostEquals(conversion.Y, 0) ? 0 : Y / conversion.Y;
else if ((relativePositionAxes & Axes.Y) > (value & Axes.Y))
Y *= conversion.Y;
relativePositionAxes = value;
updateBypassAutoSizeAxes();
}
}
/// <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.HasFlagFast(Axes.X))
offset.X = 0;
if (!RelativePositionAxes.HasFlagFast(Axes.Y))
offset.Y = 0;
}
return ApplyRelativeAxes(RelativePositionAxes, Position - offset, FillMode.Stretch);
}
}
private Vector2 size
{
get => 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 => size;
set
{
if (size == value) return;
if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Size)} must be finite, but is {value}.");
Axes changedAxes = Axes.None;
if (size.X != value.X)
changedAxes |= Axes.X;
if (size.Y != value.Y)
changedAxes |= Axes.Y;
size = value;
invalidateParentSizeDependencies(Invalidation.DrawSize, changedAxes);
}
}
private float width;
private float height;
/// <summary>
/// X component of <see cref="Size"/>.
/// </summary>
public virtual float Width
{
get => width;
set
{
if (width == value) return;
if (!float.IsFinite(value)) throw new ArgumentException($@"{nameof(Width)} must be finite, but is {value}.");
width = value;
invalidateParentSizeDependencies(Invalidation.DrawSize, Axes.X);
}
}
/// <summary>
/// Y component of <see cref="Size"/>.
/// </summary>
public virtual float Height
{
get => height;
set
{
if (height == value) return;
if (!float.IsFinite(value)) throw new ArgumentException($@"{nameof(Height)} must be finite, but is {value}.");
height = value;
invalidateParentSizeDependencies(Invalidation.DrawSize, Axes.Y);
}
}
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 => relativeSizeAxes;
set
{
if (value == relativeSizeAxes)
return;
// In some cases we cannot easily preserve our size, and so we simply invalidate and
// leave correct sizing to the user.
if (fillMode != FillMode.Stretch && (value == Axes.Both || relativeSizeAxes == Axes.Both))
Invalidate(Invalidation.DrawSize);
else
{
// Convert coordinates from relative to absolute or vice versa
Vector2 conversion = relativeToAbsoluteFactor;
if ((value & Axes.X) > (relativeSizeAxes & Axes.X))
Width = Precision.AlmostEquals(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 = Precision.AlmostEquals(conversion.Y, 0) ? 0 : Height / conversion.Y;
else if ((relativeSizeAxes & Axes.Y) > (value & Axes.Y))
Height *= conversion.Y;
}
relativeSizeAxes = value;
if (relativeSizeAxes.HasFlagFast(Axes.X) && Width == 0) Width = 1;
if (relativeSizeAxes.HasFlagFast(Axes.Y) && Height == 0) Height = 1;
updateBypassAutoSizeAxes();
OnSizingChanged();
}
}
private readonly LayoutValue<Vector2> drawSizeBacking = new LayoutValue<Vector2>(Invalidation.DrawInfo | Invalidation.RequiredParentSizeToFit | Invalidation.Presence);
/// <summary>
/// Absolute size of this Drawable in the <see cref="Parent"/>'s coordinate system.
/// </summary>
public Vector2 DrawSize => drawSizeBacking.IsValid ? drawSizeBacking : drawSizeBacking.Value = ApplyRelativeAxes(RelativeSizeAxes, Size, FillMode);
/// <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 => margin;
set
{
if (margin.Equals(value)) return;
if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Margin)} must be finite, but is {value}.");
margin = value;
Invalidate(Invalidation.MiscGeometry);
}
}
/// <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>
/// <param name="fillMode">The <see cref="FillMode"/> to be used.</param>
/// <returns>Absolute coordinates in <see cref="Parent"/>'s space.</returns>
protected Vector2 ApplyRelativeAxes(Axes relativeAxes, Vector2 v, FillMode fillMode)
{
if (relativeAxes != Axes.None)
{
Vector2 conversion = relativeToAbsoluteFactor;
if (relativeAxes.HasFlagFast(Axes.X))
v.X *= conversion.X;
if (relativeAxes.HasFlagFast(Axes.Y))
v.Y *= conversion.Y;
// FillMode only makes sense if both axes are relatively sized as the general rule
// for n-dimensional aspect preservation is to simply take the minimum or the maximum
// scale among all active axes. For single axes the minimum / maximum is just the
// value itself.
if (relativeAxes == Axes.Both && fillMode != FillMode.Stretch)
{
if (fillMode == FillMode.Fill)
v = new Vector2(Math.Max(v.X, v.Y * fillAspectRatio));
else if (fillMode == FillMode.Fit)
v = new Vector2(Math.Min(v.X, v.Y * fillAspectRatio));
v.Y /= fillAspectRatio;
}
}
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;
private void updateBypassAutoSizeAxes()
{
var value = RelativePositionAxes | RelativeSizeAxes | bypassAutoSizeAdditionalAxes;
if (bypassAutoSizeAxes != value)
{
var changedAxes = bypassAutoSizeAxes ^ value;
bypassAutoSizeAxes = value;
if (((Parent?.AutoSizeAxes ?? 0) & changedAxes) != 0)
Parent?.Invalidate(Invalidation.RequiredParentSizeToFit, InvalidationSource.Child);
}
}
private Axes bypassAutoSizeAdditionalAxes;
/// <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 => bypassAutoSizeAxes;
set
{
bypassAutoSizeAdditionalAxes = value;
updateBypassAutoSizeAxes();
}
}
/// <summary>
/// Computes the bounding box of this drawable in its parent's space.
/// </summary>
public virtual RectangleF BoundingBox => ToParentSpace(LayoutRectangle).AABBFloat;
/// <summary>
/// Called whenever the <see cref="RelativeSizeAxes"/> of this drawable is changed, or when the <see cref="Container{T}.AutoSizeAxes"/> are changed if this drawable is a <see cref="Container{T}"/>.
/// </summary>
protected virtual void OnSizingChanged()
{
}
#endregion
#region Scale / Shear / Rotation
private Vector2 scale = Vector2.One;
/// <summary>
/// Base relative scaling factor around <see cref="OriginPosition"/>.
/// </summary>
public Vector2 Scale
{
get => scale;
set
{
if (scale == value)
return;
if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Scale)} must be finite, but is {value}.");