PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Effects/BackgroundEffectRenderer.cs

https://bitbucket.org/tuldok89/openpdn
C# | 414 lines | 311 code | 59 blank | 44 comment | 41 complexity | 0f1ccc71b3bf5c5b426616ad40e51ce0 MD5 | raw file
  1. /////////////////////////////////////////////////////////////////////////////////
  2. // Paint.NET //
  3. // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
  4. // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
  5. // See src/Resources/Files/License.txt for full licensing and attribution //
  6. // details. //
  7. // . //
  8. /////////////////////////////////////////////////////////////////////////////////
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.Threading;
  14. namespace PaintDotNet.Effects
  15. {
  16. /// <summary>
  17. /// This class can be used to apply an effect using background worker threads
  18. /// which raise an event when a certain amount of the effect has been processed.
  19. /// You can use that event to update a status bar, display a preview of the
  20. /// rendering so far, or whatever.
  21. ///
  22. /// Since two threads are used for rendering, this will improve performance on
  23. /// dual processor systems, and possibly on systems that have HyperThreading.
  24. ///
  25. /// This class is NOT SAFE for multithreaded access. Note that the events will
  26. /// be raised from arbitrary threads.
  27. /// be raised from arbitrary threads. The only method that is safe to call from
  28. /// a thread that is not managing Start(), Abort(), and Join() is AbortAsync().
  29. /// You may then query whether the rendering actually aborted by using the Abort
  30. /// property. If it returns false, then AbortAsync() was not called in time to
  31. /// abort anything, which means the rendering completed fully.
  32. /// </summary>
  33. public sealed class BackgroundEffectRenderer
  34. : IDisposable
  35. {
  36. private readonly Effect _effect;
  37. private readonly EffectConfigToken _effectToken; // this references the main token that is passed in to the constructor
  38. private EffectConfigToken _effectTokenCopy; // this copy of the token is updated every time you call Start() to make sure it is up to date. This is then passed to the threads, not the original one.
  39. private readonly PdnRegion _renderRegion;
  40. private readonly Rectangle[][] _tileRegions;
  41. private readonly PdnRegion[] _tilePdnRegions;
  42. private readonly int _tileCount;
  43. private readonly Threading.ThreadPool _threadPool;
  44. private RenderArgs _dstArgs;
  45. private RenderArgs _srcArgs;
  46. private readonly int _workerThreads;
  47. private readonly ArrayList _exceptions = ArrayList.Synchronized(new ArrayList());
  48. private volatile bool _aborted;
  49. public event RenderedTileEventHandler RenderedTile;
  50. private void OnRenderedTile(RenderedTileEventArgs e)
  51. {
  52. if (RenderedTile != null)
  53. {
  54. RenderedTile(this, e);
  55. }
  56. }
  57. public event EventHandler FinishedRendering;
  58. private void OnFinishedRendering()
  59. {
  60. if (FinishedRendering != null)
  61. {
  62. FinishedRendering(this, EventArgs.Empty);
  63. }
  64. }
  65. public event EventHandler StartingRendering;
  66. private void OnStartingRendering()
  67. {
  68. if (StartingRendering != null)
  69. {
  70. StartingRendering(this, EventArgs.Empty);
  71. }
  72. }
  73. private sealed class RendererContext
  74. {
  75. private readonly BackgroundEffectRenderer _ber;
  76. private readonly EffectConfigToken _token;
  77. private readonly int _threadNumber;
  78. private readonly int _startOffset;
  79. /*
  80. public RendererContext(BackgroundEffectRenderer ber, EffectConfigToken token, int threadNumber)
  81. : this(ber, token, threadNumber, 0)
  82. {
  83. } UNUSED CONSTRUCTOR
  84. */
  85. public RendererContext(BackgroundEffectRenderer ber, EffectConfigToken token, int threadNumber, int startOffset)
  86. {
  87. _ber = ber;
  88. _token = token;
  89. _threadNumber = threadNumber;
  90. _startOffset = startOffset;
  91. }
  92. public void Renderer2(object ignored)
  93. {
  94. Renderer();
  95. }
  96. private void Renderer()
  97. {
  98. //using (new ThreadBackground(ThreadBackgroundFlags.Cpu))
  99. {
  100. RenderImpl();
  101. }
  102. }
  103. private void RenderImpl()
  104. {
  105. int inc = _ber._workerThreads;
  106. int start = _threadNumber + (_startOffset * inc);
  107. int max = _ber._tileCount;
  108. try
  109. {
  110. for (int tile = start; tile < max; tile += inc)
  111. {
  112. if (_ber._threadShouldStop)
  113. {
  114. _ber._aborted = true;
  115. break;
  116. }
  117. Rectangle[] subRegion = _ber._tileRegions[tile];
  118. _ber._effect.Render(_token, _ber._dstArgs, _ber._srcArgs, subRegion);
  119. PdnRegion subPdnRegion = _ber._tilePdnRegions[tile];
  120. _ber.OnRenderedTile(new RenderedTileEventArgs(subPdnRegion, _ber._tileCount, tile));
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. _ber._exceptions.Add(ex);
  126. }
  127. }
  128. }
  129. public void ThreadFunction()
  130. {
  131. if (_srcArgs.Surface.Scan0.MaySetAllowWrites)
  132. {
  133. _srcArgs.Surface.Scan0.AllowWrites = false;
  134. }
  135. try
  136. {
  137. _effect.SetRenderInfo(_effectTokenCopy, _dstArgs, _srcArgs);
  138. if (_tileCount > 0)
  139. {
  140. Rectangle[] subRegion = _tileRegions[0];
  141. _effect.Render(_effectTokenCopy, _dstArgs, _srcArgs, subRegion);
  142. PdnRegion subPdnRegion = _tilePdnRegions[0];
  143. OnRenderedTile(new RenderedTileEventArgs(subPdnRegion, _tileCount, 0));
  144. }
  145. var tokens = new EffectConfigToken[_workerThreads];
  146. int i;
  147. for (i = 0; i < _workerThreads; ++i)
  148. {
  149. if (_threadShouldStop)
  150. {
  151. break;
  152. }
  153. if (_effectTokenCopy == null)
  154. {
  155. tokens[i] = null;
  156. }
  157. else
  158. {
  159. tokens[i] = (EffectConfigToken)_effectTokenCopy.Clone();
  160. }
  161. var rc = new RendererContext(this, tokens[i], i, (i == 0) ? 1 : 0);
  162. _threadPool.QueueUserWorkItem(rc.Renderer2);
  163. }
  164. if (i == _workerThreads)
  165. {
  166. _threadPool.Drain();
  167. OnFinishedRendering();
  168. }
  169. }
  170. catch (Exception ex)
  171. {
  172. _exceptions.Add(ex);
  173. }
  174. finally
  175. {
  176. _threadPool.Drain();
  177. Exception[] newExceptions = _threadPool.Exceptions;
  178. if (newExceptions.Length > 0)
  179. {
  180. foreach (Exception exception in newExceptions)
  181. {
  182. _exceptions.Add(exception);
  183. }
  184. }
  185. if (_srcArgs.Surface.Scan0.MaySetAllowWrites)
  186. {
  187. _srcArgs.Surface.Scan0.AllowWrites = true;
  188. }
  189. }
  190. }
  191. private volatile bool _threadShouldStop;
  192. private Thread _thread;
  193. public void Start()
  194. {
  195. Abort();
  196. _aborted = false;
  197. if (_effectToken != null)
  198. {
  199. _effectTokenCopy = (EffectConfigToken)_effectToken.Clone();
  200. }
  201. _threadShouldStop = false;
  202. OnStartingRendering();
  203. _thread = new Thread(ThreadFunction);
  204. _thread.Start();
  205. }
  206. public bool Aborted
  207. {
  208. get
  209. {
  210. return _aborted;
  211. }
  212. }
  213. public void Abort()
  214. {
  215. if (_thread == null) return;
  216. _threadShouldStop = true;
  217. Join();
  218. _threadPool.Drain();
  219. }
  220. // This is the only method that is safe to call from another thread
  221. // If the abort was successful, then get_Aborted will return true
  222. // after a Join().
  223. public void AbortAsync()
  224. {
  225. _threadShouldStop = true;
  226. }
  227. /// <summary>
  228. /// Used to determine whether the rendering fully completed or not, and was not
  229. /// aborted in any way. You can use this method to sleep until the rendering
  230. /// finishes. Once this is set to the signaled state you should check the IsDone
  231. /// property to make sure that the rendering was actually finished, and not
  232. /// aborted.
  233. /// </summary>
  234. public void Join()
  235. {
  236. _thread.Join();
  237. if (_exceptions.Count <= 0)
  238. {
  239. }
  240. else
  241. {
  242. var throwMe = (Exception) _exceptions[0];
  243. _exceptions.Clear();
  244. throw new WorkerThreadException("Worker thread threw an exception", throwMe);
  245. }
  246. }
  247. private static Rectangle[] ConsolidateRects(Rectangle[] scans)
  248. {
  249. if (scans.Length == 0)
  250. {
  251. return scans;
  252. }
  253. var cons = new List<Rectangle>();
  254. int current = 0;
  255. cons.Add(scans[0]);
  256. for (int i = 1; i < scans.Length; ++i)
  257. {
  258. if (scans[i].Left == cons[current].Left &&
  259. scans[i].Right == cons[current].Right &&
  260. scans[i].Top == cons[current].Bottom)
  261. {
  262. Rectangle cc = cons[current];
  263. cc.Height = scans[i].Bottom - cons[current].Top;
  264. cons[current] = cc;
  265. }
  266. else
  267. {
  268. cons.Add(scans[i]);
  269. current = cons.Count - 1;
  270. }
  271. }
  272. return cons.ToArray();
  273. }
  274. private static Rectangle[][] SliceUpRegion(PdnRegion region, int sliceCount, Rectangle layerBounds)
  275. {
  276. var slices = new Rectangle[sliceCount][];
  277. Rectangle[] regionRects = region.GetRegionScansReadOnlyInt();
  278. Scanline[] regionScans = Utility.GetRegionScans(regionRects);
  279. for (int i = 0; i < sliceCount; ++i)
  280. {
  281. int beginScan = (regionScans.Length * i) / sliceCount;
  282. int endScan = Math.Min(regionScans.Length, (regionScans.Length * (i + 1)) / sliceCount);
  283. // Try to arrange it such that the maximum size of the first region
  284. // is 1-pixel tall
  285. switch (i)
  286. {
  287. case 0:
  288. endScan = Math.Min(endScan, beginScan + 1);
  289. break;
  290. case 1:
  291. beginScan = Math.Min(beginScan, 1);
  292. break;
  293. }
  294. Rectangle[] newRects = Utility.ScanlinesToRectangles(regionScans, beginScan, endScan - beginScan);
  295. for (int j = 0; j < newRects.Length; ++j)
  296. {
  297. newRects[j].Intersect(layerBounds);
  298. }
  299. Rectangle[] consRects = ConsolidateRects(newRects);
  300. slices[i] = consRects;
  301. }
  302. return slices;
  303. }
  304. public BackgroundEffectRenderer(Effect effect,
  305. EffectConfigToken effectToken,
  306. RenderArgs dstArgs,
  307. RenderArgs srcArgs,
  308. PdnRegion renderRegion,
  309. int tileCount,
  310. int workerThreads)
  311. {
  312. _effect = effect;
  313. _effectToken = effectToken;
  314. _dstArgs = dstArgs;
  315. _srcArgs = srcArgs;
  316. _renderRegion = renderRegion;
  317. _renderRegion.Intersect(dstArgs.Bounds);
  318. _tileRegions = SliceUpRegion(renderRegion, tileCount, dstArgs.Bounds);
  319. _tilePdnRegions = new PdnRegion[_tileRegions.Length];
  320. for (int i = 0; i < _tileRegions.Length; ++i)
  321. {
  322. PdnRegion pdnRegion = Utility.RectanglesToRegion(_tileRegions[i]);
  323. _tilePdnRegions[i] = pdnRegion;
  324. }
  325. _tileCount = tileCount;
  326. _workerThreads = workerThreads;
  327. if (effect.CheckForEffectFlags(EffectFlags.SingleThreaded))
  328. {
  329. _workerThreads = 1;
  330. }
  331. _threadPool = new Threading.ThreadPool(_workerThreads, false);
  332. }
  333. ~BackgroundEffectRenderer()
  334. {
  335. Dispose(false);
  336. }
  337. public void Dispose()
  338. {
  339. Dispose(true);
  340. GC.SuppressFinalize(this);
  341. }
  342. private void Dispose(bool disposing)
  343. {
  344. if (!disposing) return;
  345. if (_srcArgs != null)
  346. {
  347. _srcArgs.Dispose();
  348. _srcArgs = null;
  349. }
  350. if (_dstArgs == null) return;
  351. _dstArgs.Dispose();
  352. _dstArgs = null;
  353. }
  354. }
  355. }