MagicWandHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System.Collections;
  2. using ChunkyImageLib.Operations;
  3. using PixiEditor.ChangeableDocument.Changeables.Interfaces;
  4. using PixiEditor.ChangeableDocument.Changes.Drawing.FloodFill;
  5. using Drawie.Backend.Core.ColorsImpl;
  6. using Drawie.Backend.Core.Numerics;
  7. using Drawie.Backend.Core.Vector;
  8. using Drawie.Numerics;
  9. namespace PixiEditor.ChangeableDocument.Changes.Selection.MagicWand;
  10. internal class MagicWandHelper
  11. {
  12. private static readonly VecI Up = new VecI(0, -1);
  13. private static readonly VecI Down = new VecI(0, 1);
  14. private static readonly VecI Left = new VecI(-1, 0);
  15. private static readonly VecI Right = new VecI(1, 0);
  16. //private static MagicWandVisualizer visualizer = new MagicWandVisualizer(Path.Combine("Debugging", "MagicWand"));
  17. private class UnvisitedStack
  18. {
  19. private int chunkSize;
  20. private readonly VecI imageSize;
  21. private Stack<(VecI chunkPos, VecI posOnChunk)> likelyUnvisited = new();
  22. private HashSet<VecI> certainlyVisited = new();
  23. public UnvisitedStack(int chunkSize, VecI imageSize)
  24. {
  25. this.chunkSize = chunkSize;
  26. this.imageSize = imageSize;
  27. }
  28. public void PushAll(VecI chunkPos)
  29. {
  30. VecI chunkOffset = chunkPos * chunkSize;
  31. for (int i = 0; i < chunkSize; i++)
  32. {
  33. // separated into a function to prevent stackalloc stackoverflow
  34. PushArrayIteration(i);
  35. }
  36. void PushArrayIteration(int i)
  37. {
  38. Span<(VecI, VecI, VecI)> options = stackalloc (VecI, VecI, VecI)[]
  39. {
  40. (new(chunkPos.X, chunkPos.Y - 1), new(i, chunkSize - 1), new(i, 0)), // Top
  41. (new(chunkPos.X, chunkPos.Y + 1), new(i, 0), new(i, chunkSize - 1)), // Bottom
  42. (new(chunkPos.X - 1, chunkPos.Y), new(chunkSize - 1, i), new(0, i)), // Left
  43. (new(chunkPos.X + 1, chunkPos.Y), new(0, i), new(chunkSize - 1, i)) // Right
  44. };
  45. foreach (var (otherChunkPos, otherPosInChunk, refPos) in options)
  46. {
  47. VecI global = otherChunkPos * chunkSize + otherPosInChunk;
  48. if (global.X < 0 || global.Y < 0 || global.X >= imageSize.X || global.Y >= imageSize.Y)
  49. continue;
  50. likelyUnvisited.Push((otherChunkPos, otherPosInChunk));
  51. certainlyVisited.Add(chunkOffset + refPos);
  52. }
  53. }
  54. }
  55. public void Push(VecI chunkPos, VecI posOnChunk)
  56. {
  57. likelyUnvisited.Push((chunkPos, posOnChunk));
  58. }
  59. public void Push(VecI chunkPos, bool[] visitedArray)
  60. {
  61. VecI chunkOffset = chunkPos * chunkSize;
  62. for (int i = 0; i < chunkSize; i++)
  63. {
  64. // separated into a function to prevent stackalloc stackoverflow
  65. PushArrayIteration(i);
  66. }
  67. void PushArrayIteration(int i)
  68. {
  69. Span<(int, VecI, VecI, VecI)> options = stackalloc (int, VecI, VecI, VecI)[]
  70. {
  71. (i, new(chunkPos.X, chunkPos.Y - 1), new(i, chunkSize - 1), new(i, 0)), // Top
  72. (chunkSize * (chunkSize - 1) + i, new(chunkPos.X, chunkPos.Y + 1), new(i, 0), new(i, chunkSize - 1)), // Bottom
  73. (i * chunkSize, new(chunkPos.X - 1, chunkPos.Y), new(chunkSize - 1, i), new(0, i)), // Left
  74. (i * chunkSize + (chunkSize - 1), new(chunkPos.X + 1, chunkPos.Y), new(0, i), new(chunkSize - 1, i)) // Right
  75. };
  76. foreach (var (refIndex, otherChunkPos, otherPosInChunk, refPos) in options)
  77. {
  78. VecI otherGlobal = otherChunkPos * chunkSize + otherPosInChunk;
  79. if (!visitedArray[refIndex] || otherGlobal.X < 0 || otherGlobal.Y < 0 || otherGlobal.X >= imageSize.X || otherGlobal.Y >= imageSize.Y)
  80. continue;
  81. certainlyVisited.Add(chunkOffset + refPos);
  82. likelyUnvisited.Push((otherChunkPos, otherPosInChunk));
  83. }
  84. }
  85. }
  86. public (VecI chunkPos, VecI posOnChunk)? PopUnvisited()
  87. {
  88. while (likelyUnvisited.Count > 0)
  89. {
  90. var (chunkPos, posOnChunk) = likelyUnvisited.Pop();
  91. VecI global = chunkPos * chunkSize + posOnChunk;
  92. if (certainlyVisited.Contains(global))
  93. continue;
  94. return (chunkPos, posOnChunk);
  95. }
  96. return null;
  97. }
  98. }
  99. public static VectorPath DoMagicWandFloodFill(VecI startingPos, HashSet<Guid> membersToFloodFill,
  100. double tolerance,
  101. IReadOnlyDocument document, int frame)
  102. {
  103. if (startingPos.X < 0 || startingPos.Y < 0 || startingPos.X >= document.Size.X || startingPos.Y >= document.Size.Y)
  104. return new VectorPath();
  105. tolerance = Math.Clamp(tolerance, 0, 1);
  106. int chunkSize = ChunkResolution.Full.PixelSize();
  107. FloodFillChunkCache cache = FloodFillHelper.CreateCache(membersToFloodFill, document, frame);
  108. VecI initChunkPos = OperationHelper.GetChunkPos(startingPos, chunkSize);
  109. VecI imageSizeInChunks = (VecI)(document.Size / (double)chunkSize).Ceiling();
  110. VecI initPosOnChunk = startingPos - initChunkPos * chunkSize;
  111. Color colorToReplace = cache.GetChunk(initChunkPos).Match(
  112. (Chunk chunk) => chunk.Surface.GetSRGBPixel(initPosOnChunk),
  113. static (EmptyChunk _) => Colors.Transparent
  114. );
  115. ColorBounds colorRange = new(colorToReplace, tolerance);
  116. HashSet<VecI> processedEmptyChunks = new();
  117. UnvisitedStack positionsToFloodFill = new(chunkSize, document.Size);
  118. Lines lines = new();
  119. VectorPath selection = new();
  120. positionsToFloodFill.Push(initChunkPos, initPosOnChunk);
  121. while (true)
  122. {
  123. (VecI initChunkPos, VecI initPosOnChunk)? popped = positionsToFloodFill.PopUnvisited();
  124. if (popped is null)
  125. break;
  126. var (chunkPos, posOnChunk) = popped.Value;
  127. var referenceChunk = cache.GetChunk(chunkPos);
  128. // don't call floodfill if the chunk is empty
  129. if (referenceChunk.IsT1)
  130. {
  131. if (colorToReplace.A == 0 && !processedEmptyChunks.Contains(chunkPos))
  132. {
  133. AddLinesForEmptyChunk(lines, chunkPos, document.Size, chunkSize);
  134. positionsToFloodFill.PushAll(chunkPos);
  135. processedEmptyChunks.Add(chunkPos);
  136. }
  137. continue;
  138. }
  139. // use regular flood fill for chunks that have something in them
  140. var reallyReferenceChunk = referenceChunk.AsT0;
  141. VecI globalPos = chunkPos * chunkSize + posOnChunk;
  142. //visualizer.CurrentContext = $"FloodFill_{chunkPos}";
  143. var maybeArray = AddLinesForChunkViaFloodFill(
  144. reallyReferenceChunk,
  145. chunkSize,
  146. chunkPos * chunkSize,
  147. document.Size,
  148. posOnChunk,
  149. colorRange, lines);
  150. if (maybeArray is null)
  151. continue;
  152. positionsToFloodFill.Push(chunkPos, maybeArray);
  153. }
  154. if (lines.Count > 0)
  155. {
  156. selection = BuildContour(lines);
  157. }
  158. //visualizer.GenerateVisualization(document.Size.X, document.Size.Y, 500, 500);
  159. return selection;
  160. }
  161. private static void AddLinesForEmptyChunk(Lines lines, VecI chunkPos, VecI imageSize, int chunkSize)
  162. {
  163. //visualizer.CurrentContext = "EmptyChunk";
  164. RectI chunkRect = new RectI(chunkPos * chunkSize, new(chunkSize));
  165. chunkRect = chunkRect.Intersect(new RectI(VecI.Zero, imageSize));
  166. if (chunkRect.IsZeroOrNegativeArea)
  167. return;
  168. for (int i = chunkRect.Left; i < chunkRect.Right; i++)
  169. {
  170. lines.AddLine(new Line(new(i, chunkRect.Top), new(i + 1, chunkRect.Top))); // Top
  171. lines.AddLine(new Line(new(i + 1, chunkRect.Bottom), new(i, chunkRect.Bottom))); // Bottom
  172. }
  173. for (int j = chunkRect.Top; j < chunkRect.Bottom; j++)
  174. {
  175. lines.AddLine(new Line(new(chunkRect.Left, j + 1), new(chunkRect.Left, j))); // Left
  176. lines.AddLine(new Line(new(chunkRect.Right, j), new(chunkRect.Right, j + 1))); // Right
  177. }
  178. }
  179. private static VecI GoStraight(Lines allLines, Line firstLine)
  180. {
  181. Line previous = default;
  182. Line? current = firstLine;
  183. while (current is not null)
  184. {
  185. (previous, current) = ((Line)current, allLines.RemoveLineAt(current.Value.End, current.Value.NormalizedDirection));
  186. }
  187. return previous.End;
  188. }
  189. private static void FollowPath(Lines allLines, Line startingLine, VectorPath path)
  190. {
  191. path.MoveTo(startingLine.Start);
  192. Line? current = startingLine;
  193. while (current is not null)
  194. {
  195. VecI straightPathEnd = GoStraight(allLines, (Line)current);
  196. path.LineTo(straightPathEnd);
  197. current = allLines.RemoveLineAt(straightPathEnd);
  198. }
  199. }
  200. private static VectorPath BuildContour(Lines lines)
  201. {
  202. VectorPath selection = new();
  203. Line? current = lines.PopLine();
  204. while (current is not null)
  205. {
  206. FollowPath(lines, (Line)current, selection);
  207. current = lines.PopLine();
  208. }
  209. return selection;
  210. }
  211. private static unsafe bool[]? AddLinesForChunkViaFloodFill(
  212. Chunk referenceChunk,
  213. int chunkSize,
  214. VecI chunkOffset,
  215. VecI documentSize,
  216. VecI pos,
  217. ColorBounds bounds, Lines lines)
  218. {
  219. if (!bounds.IsWithinBounds(referenceChunk.Surface.GetSRGBPixel(pos)))
  220. {
  221. return null;
  222. }
  223. bool[] pixelVisitedStates = new bool[chunkSize * chunkSize];
  224. using var refPixmap = referenceChunk.Surface.DrawingSurface.PeekPixels();
  225. Half* refArray = (Half*)refPixmap.GetPixels();
  226. Stack<VecI> toVisit = new();
  227. toVisit.Push(pos);
  228. while (toVisit.Count > 0)
  229. {
  230. VecI curPos = toVisit.Pop();
  231. int pixelOffset = curPos.X + curPos.Y * chunkSize;
  232. if (pixelVisitedStates[pixelOffset])
  233. continue;
  234. VecI globalPos = curPos + chunkOffset;
  235. Half* refPixel = refArray + pixelOffset * 4;
  236. if (!bounds.IsWithinBounds(refPixel))
  237. continue;
  238. pixelVisitedStates[pixelOffset] = true;
  239. //visualizer.CurrentContext = "AddFillContourLines";
  240. AddFillContourLines(chunkSize, chunkOffset, bounds, lines, curPos, pixelVisitedStates, pixelOffset, refPixel, toVisit, globalPos, documentSize);
  241. }
  242. return pixelVisitedStates;
  243. }
  244. private static unsafe void AddFillContourLines(int chunkSize, VecI chunkOffset, ColorBounds bounds, Lines lines,
  245. VecI curPos, bool[] pixelStates, int pixelOffset, Half* refPixel, Stack<VecI> toVisit, VecI globalPos,
  246. VecI documentSize)
  247. {
  248. // Left pixel
  249. bool leftEdgePresent = curPos.X == 0 || globalPos.X == 0 || !bounds.IsWithinBounds(refPixel - 4);
  250. if (!leftEdgePresent && !pixelStates[pixelOffset - 1])
  251. {
  252. toVisit.Push(new(curPos.X - 1, curPos.Y));
  253. }
  254. else if (leftEdgePresent)
  255. {
  256. lines.AddLine(new Line(
  257. new VecI(curPos.X, curPos.Y + 1) + chunkOffset,
  258. new VecI(curPos.X, curPos.Y) + chunkOffset));
  259. }
  260. // Right pixel
  261. bool rightEdgePresent = globalPos.X == documentSize.X - 1 || curPos.X == chunkSize - 1 || !bounds.IsWithinBounds(refPixel + 4);
  262. if (!rightEdgePresent && !pixelStates[pixelOffset + 1])
  263. {
  264. toVisit.Push(new(curPos.X + 1, curPos.Y));
  265. }
  266. else if (rightEdgePresent)
  267. {
  268. lines.AddLine(new Line(
  269. new VecI(curPos.X + 1, curPos.Y) + chunkOffset,
  270. new VecI(curPos.X + 1, curPos.Y + 1) + chunkOffset));
  271. }
  272. // Top pixel
  273. bool topEdgePresent = curPos.Y == 0 || globalPos.Y == 0 || !bounds.IsWithinBounds(refPixel - 4 * chunkSize);
  274. if (!topEdgePresent && !pixelStates[pixelOffset - chunkSize])
  275. {
  276. toVisit.Push(new(curPos.X, curPos.Y - 1));
  277. }
  278. else if (topEdgePresent)
  279. {
  280. lines.AddLine(new Line(
  281. new VecI(curPos.X, curPos.Y) + chunkOffset,
  282. new VecI(curPos.X + 1, curPos.Y) + chunkOffset));
  283. }
  284. //Bottom pixel
  285. bool bottomEdgePresent = globalPos.Y == documentSize.Y - 1 || curPos.Y == chunkSize - 1 || !bounds.IsWithinBounds(refPixel + 4 * chunkSize);
  286. if (!bottomEdgePresent && !pixelStates[pixelOffset + chunkSize])
  287. {
  288. toVisit.Push(new(curPos.X, curPos.Y + 1));
  289. }
  290. else if (bottomEdgePresent)
  291. {
  292. lines.AddLine(new Line(
  293. new VecI(curPos.X + 1, curPos.Y + 1) + chunkOffset,
  294. new VecI(curPos.X, curPos.Y + 1) + chunkOffset));
  295. }
  296. }
  297. internal struct Line
  298. {
  299. public bool Equals(Line other)
  300. {
  301. return Start.Equals(other.Start) && End.Equals(other.End) && NormalizedDirection.Equals(other.NormalizedDirection);
  302. }
  303. public override bool Equals(object? obj)
  304. {
  305. return obj is Line other && Equals(other);
  306. }
  307. public override int GetHashCode()
  308. {
  309. return HashCode.Combine(Start, End);
  310. }
  311. public VecI Start { get; set; }
  312. public VecI End { get; set; }
  313. public VecI NormalizedDirection { get; }
  314. public Line(VecI start, VecI end)
  315. {
  316. Start = start;
  317. End = end;
  318. NormalizedDirection = (VecI)(end - start).Normalized();
  319. }
  320. public static bool operator ==(Line a, Line b)
  321. {
  322. return a.Start == b.Start && a.End == b.End;
  323. }
  324. public static bool operator !=(Line a, Line b)
  325. {
  326. return !(a == b);
  327. }
  328. public override string ToString()
  329. {
  330. string dir = (NormalizedDirection.X, NormalizedDirection.Y) switch
  331. {
  332. ( > 0, _) => "Right",
  333. ( < 0, _) => "Left",
  334. (_, < 0) => "Up",
  335. (_, > 0) => "Down",
  336. _ => "Weird dir"
  337. };
  338. return $"{Start}, {dir}";
  339. }
  340. }
  341. internal class Lines : IEnumerable<Line>
  342. {
  343. private Dictionary<VecI, Dictionary<VecI, Line>> LineDicts { get; set; } = new Dictionary<VecI, Dictionary<VecI, Line>>();
  344. public int Count => LineDicts.Aggregate(0, (acc, cur) => acc += cur.Value.Count);
  345. public Lines()
  346. {
  347. LineDicts[Right] = new Dictionary<VecI, Line>();
  348. LineDicts[Down] = new Dictionary<VecI, Line>();
  349. LineDicts[Left] = new Dictionary<VecI, Line>();
  350. LineDicts[Up] = new Dictionary<VecI, Line>();
  351. }
  352. public Line? RemoveLineAt(VecI start)
  353. {
  354. foreach (var (_, lineDict) in LineDicts)
  355. {
  356. if (lineDict.Remove(start, out Line value))
  357. return value;
  358. }
  359. return null;
  360. }
  361. public Line? RemoveLineAt(VecI start, VecI direction)
  362. {
  363. if (LineDicts[direction].Remove(start, out Line value))
  364. return value;
  365. return null;
  366. }
  367. public Line? PopLine()
  368. {
  369. foreach (var (_, lineDict) in LineDicts)
  370. {
  371. if (lineDict.Count == 0)
  372. continue;
  373. var result = lineDict.First();
  374. lineDict.Remove(result.Key);
  375. return result.Value;
  376. }
  377. return null;
  378. }
  379. public void AddLine(Line line)
  380. {
  381. // cancel out line
  382. if (LineDicts[-line.NormalizedDirection].ContainsKey(line.End))
  383. {
  384. LineDicts[-line.NormalizedDirection].Remove(line.End);
  385. //visualizer.Steps.Add(new Step(line, StepType.CancelLine));
  386. return;
  387. }
  388. LineDicts[line.NormalizedDirection][line.Start] = line;
  389. //visualizer.Steps.Add(new Step(line));
  390. }
  391. public IEnumerator<Line> GetEnumerator()
  392. {
  393. foreach (var upLines in LineDicts[Up])
  394. {
  395. yield return upLines.Value;
  396. }
  397. foreach (var rightLines in LineDicts[Right])
  398. {
  399. yield return rightLines.Value;
  400. }
  401. foreach (var downLines in LineDicts[Down])
  402. {
  403. yield return downLines.Value;
  404. }
  405. foreach (var leftLines in LineDicts[Left])
  406. {
  407. yield return leftLines.Value;
  408. }
  409. }
  410. IEnumerator IEnumerable.GetEnumerator()
  411. {
  412. return GetEnumerator();
  413. }
  414. }
  415. }