ImmediateRenderer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Avalonia.Logging;
  5. using Avalonia.Media;
  6. using Avalonia.Platform;
  7. using Avalonia.VisualTree;
  8. namespace Avalonia.Rendering
  9. {
  10. /// <summary>
  11. /// A renderer which renders the state of the visual tree without an intermediate scene graph
  12. /// representation.
  13. /// </summary>
  14. /// <remarks>
  15. /// The immediate renderer supports only clip-bound-based hit testing; a control's geometry is
  16. /// not taken into account.
  17. /// </remarks>
  18. public class ImmediateRenderer : RendererBase, IRenderer, IVisualBrushRenderer
  19. {
  20. private readonly Visual _root;
  21. private readonly IRenderRoot? _renderRoot;
  22. private bool _updateTransformedBounds = true;
  23. private IRenderTarget? _renderTarget;
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="ImmediateRenderer"/> class.
  26. /// </summary>
  27. /// <param name="root">The control to render.</param>
  28. public ImmediateRenderer(Visual root)
  29. {
  30. _root = root ?? throw new ArgumentNullException(nameof(root));
  31. _renderRoot = root as IRenderRoot;
  32. }
  33. private ImmediateRenderer(Visual root, bool updateTransformedBounds)
  34. {
  35. _root = root ?? throw new ArgumentNullException(nameof(root));
  36. _renderRoot = root as IRenderRoot;
  37. _updateTransformedBounds = updateTransformedBounds;
  38. }
  39. /// <inheritdoc/>
  40. public bool DrawFps { get; set; }
  41. /// <inheritdoc/>
  42. public bool DrawDirtyRects { get; set; }
  43. /// <inheritdoc/>
  44. public event EventHandler<SceneInvalidatedEventArgs>? SceneInvalidated;
  45. /// <inheritdoc/>
  46. public void Paint(Rect rect)
  47. {
  48. if (_renderTarget == null)
  49. {
  50. _renderTarget = ((IRenderRoot)_root).CreateRenderTarget();
  51. }
  52. try
  53. {
  54. using (var context = new DrawingContext(_renderTarget.CreateDrawingContext(this)))
  55. {
  56. context.PlatformImpl.Clear(Colors.Transparent);
  57. using (context.PushTransformContainer())
  58. {
  59. Render(context, _root, _root.Bounds);
  60. }
  61. if (DrawDirtyRects)
  62. {
  63. var color = (uint)new Random().Next(0xffffff) | 0x44000000;
  64. context.FillRectangle(
  65. new SolidColorBrush(color),
  66. rect);
  67. }
  68. if (DrawFps)
  69. {
  70. RenderFps(context, _root.Bounds, null);
  71. }
  72. }
  73. }
  74. catch (RenderTargetCorruptedException ex)
  75. {
  76. Logger.TryGet(LogEventLevel.Information, LogArea.Animations)?.Log(this, "Render target was corrupted. Exception: {0}", ex);
  77. _renderTarget.Dispose();
  78. _renderTarget = null;
  79. }
  80. SceneInvalidated?.Invoke(this, new SceneInvalidatedEventArgs((IRenderRoot)_root, rect));
  81. }
  82. /// <inheritdoc/>
  83. public void Resized(Size size)
  84. {
  85. }
  86. /// <summary>
  87. /// Renders a visual to a render target.
  88. /// </summary>
  89. /// <param name="visual">The visual.</param>
  90. /// <param name="target">The render target.</param>
  91. public static void Render(Visual visual, IRenderTarget target)
  92. {
  93. using (var renderer = new ImmediateRenderer(visual, updateTransformedBounds: false))
  94. using (var context = new DrawingContext(target.CreateDrawingContext(renderer)))
  95. {
  96. renderer.Render(context, visual, visual.Bounds);
  97. }
  98. }
  99. /// <summary>
  100. /// Renders a visual to a drawing context.
  101. /// </summary>
  102. /// <param name="visual">The visual.</param>
  103. /// <param name="context">The drawing context.</param>
  104. public static void Render(Visual visual, DrawingContext context)
  105. {
  106. using (var renderer = new ImmediateRenderer(visual, updateTransformedBounds: false))
  107. {
  108. renderer.Render(context, visual, visual.Bounds);
  109. }
  110. }
  111. /// <inheritdoc/>
  112. public void AddDirty(Visual visual)
  113. {
  114. if (visual.Bounds != Rect.Default)
  115. {
  116. var m = visual.TransformToVisual(_root);
  117. if (m.HasValue)
  118. {
  119. var bounds = new Rect(visual.Bounds.Size).TransformToAABB(m.Value);
  120. //use transformedbounds as previous render state of the visual bounds
  121. //so we can invalidate old and new bounds of a control in case it moved/shrinked
  122. if (visual.TransformedBounds.HasValue)
  123. {
  124. var trb = visual.TransformedBounds.Value;
  125. var trBounds = trb.Bounds.TransformToAABB(trb.Transform);
  126. if (trBounds != bounds)
  127. {
  128. _renderRoot?.Invalidate(trBounds);
  129. }
  130. }
  131. _renderRoot?.Invalidate(bounds);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Ends the operation of the renderer.
  137. /// </summary>
  138. public void Dispose()
  139. {
  140. _renderTarget?.Dispose();
  141. }
  142. /// <inheritdoc/>
  143. public IEnumerable<Visual> HitTest(Point p, Visual root, Func<Visual, bool> filter)
  144. {
  145. return HitTest(root, p, filter);
  146. }
  147. public Visual? HitTestFirst(Point p, Visual root, Func<Visual, bool> filter)
  148. {
  149. return HitTest(root, p, filter).FirstOrDefault();
  150. }
  151. /// <inheritdoc/>
  152. public void RecalculateChildren(Visual visual) => AddDirty(visual);
  153. /// <inheritdoc/>
  154. public void Start()
  155. {
  156. }
  157. /// <inheritdoc/>
  158. public void Stop()
  159. {
  160. }
  161. /// <inheritdoc/>
  162. Size IVisualBrushRenderer.GetRenderTargetSize(IVisualBrush brush)
  163. {
  164. (brush.Visual as IVisualBrushInitialize)?.EnsureInitialized();
  165. return brush.Visual?.Bounds.Size ?? Size.Empty;
  166. }
  167. /// <inheritdoc/>
  168. void IVisualBrushRenderer.RenderVisualBrush(IDrawingContextImpl context, IVisualBrush brush)
  169. {
  170. var visual = brush.Visual;
  171. Render(new DrawingContext(context), visual, visual.Bounds);
  172. }
  173. internal static void Render(Visual visual, DrawingContext context, bool updateTransformedBounds)
  174. {
  175. using var renderer = new ImmediateRenderer(visual, updateTransformedBounds);
  176. renderer.Render(context, visual, visual.Bounds);
  177. }
  178. private static void ClearTransformedBounds(Visual visual)
  179. {
  180. foreach (var e in visual.GetSelfAndVisualDescendants())
  181. {
  182. visual.SetTransformedBounds(null);
  183. }
  184. }
  185. private static Rect GetTransformedBounds(Visual visual)
  186. {
  187. if (visual.RenderTransform == null)
  188. {
  189. return visual.Bounds;
  190. }
  191. else
  192. {
  193. var origin = visual.RenderTransformOrigin.ToPixels(new Size(visual.Bounds.Width, visual.Bounds.Height));
  194. var offset = Matrix.CreateTranslation(visual.Bounds.Position + origin);
  195. var m = (-offset) * visual.RenderTransform.Value * (offset);
  196. return visual.Bounds.TransformToAABB(m);
  197. }
  198. }
  199. private static IEnumerable<Visual> HitTest(
  200. Visual visual,
  201. Point p,
  202. Func<Visual, bool>? filter)
  203. {
  204. _ = visual ?? throw new ArgumentNullException(nameof(visual));
  205. if (filter?.Invoke(visual) != false)
  206. {
  207. bool containsPoint;
  208. if (visual is ICustomSimpleHitTest custom)
  209. {
  210. containsPoint = custom.HitTest(p);
  211. }
  212. else
  213. {
  214. containsPoint = visual.TransformedBounds?.Contains(p) == true;
  215. }
  216. if ((containsPoint || !visual.ClipToBounds) && visual.VisualChildren.Count > 0)
  217. {
  218. foreach (var child in visual.VisualChildren.SortByZIndex())
  219. {
  220. foreach (var result in HitTest(child, p, filter))
  221. {
  222. yield return result;
  223. }
  224. }
  225. }
  226. if (containsPoint)
  227. {
  228. yield return visual;
  229. }
  230. }
  231. }
  232. private void Render(DrawingContext context, Visual visual, Rect clipRect)
  233. {
  234. var opacity = visual.Opacity;
  235. var clipToBounds = visual.ClipToBounds;
  236. var bounds = new Rect(visual.Bounds.Size);
  237. if (visual.IsVisible && opacity > 0)
  238. {
  239. var m = Matrix.CreateTranslation(visual.Bounds.Position);
  240. var renderTransform = Matrix.Identity;
  241. // this should be calculated BEFORE renderTransform
  242. if (visual.HasMirrorTransform)
  243. {
  244. var mirrorMatrix = new Matrix(-1.0, 0.0, 0.0, 1.0, visual.Bounds.Width, 0);
  245. renderTransform *= mirrorMatrix;
  246. }
  247. if (visual.RenderTransform != null)
  248. {
  249. var origin = visual.RenderTransformOrigin.ToPixels(new Size(visual.Bounds.Width, visual.Bounds.Height));
  250. var offset = Matrix.CreateTranslation(origin);
  251. var finalTransform = (-offset) * visual.RenderTransform.Value * (offset);
  252. renderTransform *= finalTransform;
  253. }
  254. m = renderTransform * m;
  255. if (clipToBounds)
  256. {
  257. if (visual.RenderTransform != null)
  258. {
  259. clipRect = new Rect(visual.Bounds.Size);
  260. }
  261. else
  262. {
  263. clipRect = clipRect.Intersect(new Rect(visual.Bounds.Size));
  264. }
  265. }
  266. using (context.PushPostTransform(m))
  267. using (context.PushOpacity(opacity))
  268. using (clipToBounds
  269. #pragma warning disable CS0618 // Type or member is obsolete
  270. ? visual is IVisualWithRoundRectClip roundClipVisual
  271. ? context.PushClip(new RoundedRect(bounds, roundClipVisual.ClipToBoundsRadius))
  272. : context.PushClip(bounds)
  273. : default(DrawingContext.PushedState))
  274. #pragma warning restore CS0618 // Type or member is obsolete
  275. using (visual.Clip != null ? context.PushGeometryClip(visual.Clip) : default(DrawingContext.PushedState))
  276. using (visual.OpacityMask != null ? context.PushOpacityMask(visual.OpacityMask, bounds) : default(DrawingContext.PushedState))
  277. using (context.PushTransformContainer())
  278. {
  279. visual.Render(context);
  280. #pragma warning disable 0618
  281. var transformed =
  282. new TransformedBounds(bounds, new Rect(), context.CurrentContainerTransform);
  283. #pragma warning restore 0618
  284. if (_updateTransformedBounds)
  285. visual.SetTransformedBounds(transformed);
  286. var childrenEnumerable = visual.HasNonUniformZIndexChildren
  287. ? visual.VisualChildren.OrderBy(x => x, ZIndexComparer.Instance)
  288. : (IEnumerable<Visual>)visual.VisualChildren;
  289. foreach (var child in childrenEnumerable)
  290. {
  291. var childBounds = GetTransformedBounds(child);
  292. if (!child.ClipToBounds || clipRect.Intersects(childBounds))
  293. {
  294. var childClipRect = child.RenderTransform == null
  295. ? clipRect.Translate(-childBounds.Position)
  296. : clipRect;
  297. Render(context, child, childClipRect);
  298. }
  299. else if (_updateTransformedBounds)
  300. {
  301. ClearTransformedBounds(child);
  302. }
  303. }
  304. }
  305. }
  306. if (!visual.IsVisible && _updateTransformedBounds)
  307. {
  308. ClearTransformedBounds(visual);
  309. }
  310. }
  311. }
  312. }