BresenhamLineOperation.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using ChunkyImageLib.DataHolders;
  2. using SkiaSharp;
  3. namespace ChunkyImageLib.Operations;
  4. internal class BresenhamLineOperation : IDrawOperation
  5. {
  6. public bool IgnoreEmptyChunks => false;
  7. private readonly VecI from;
  8. private readonly VecI to;
  9. private readonly SKColor color;
  10. private readonly SKBlendMode blendMode;
  11. private readonly SKPoint[] points;
  12. private SKPaint paint;
  13. public BresenhamLineOperation(VecI from, VecI to, SKColor color, SKBlendMode blendMode)
  14. {
  15. this.from = from;
  16. this.to = to;
  17. this.color = color;
  18. this.blendMode = blendMode;
  19. paint = new SKPaint() { BlendMode = blendMode };
  20. points = BresenhamLineHelper.GetBresenhamLine(from, to);
  21. }
  22. public void DrawOnChunk(Chunk chunk, VecI chunkPos)
  23. {
  24. // a hacky way to make the lines look slightly better on non full res chunks
  25. paint.Color = new SKColor(color.Red, color.Green, color.Blue, (byte)(color.Alpha * chunk.Resolution.Multiplier()));
  26. var surf = chunk.Surface.SkiaSurface;
  27. surf.Canvas.Save();
  28. surf.Canvas.Scale((float)chunk.Resolution.Multiplier());
  29. surf.Canvas.Translate(-chunkPos * ChunkyImage.FullChunkSize);
  30. surf.Canvas.DrawPoints(SKPointMode.Points, points, paint);
  31. surf.Canvas.Restore();
  32. }
  33. public HashSet<VecI> FindAffectedChunks()
  34. {
  35. RectI bounds = RectI.FromTwoPoints(from, to + new VecI(1));
  36. return OperationHelper.FindChunksTouchingRectangle(bounds, ChunkyImage.FullChunkSize);
  37. }
  38. public IDrawOperation AsMirrored(int? verAxisX, int? horAxisY)
  39. {
  40. VecI newFrom = from;
  41. VecI newTo = to;
  42. if (verAxisX is not null)
  43. {
  44. newFrom = newFrom.ReflectX((int)verAxisX);
  45. newTo = newTo.ReflectX((int)verAxisX);
  46. }
  47. if (horAxisY is not null)
  48. {
  49. newFrom = newFrom.ReflectY((int)horAxisY);
  50. newTo = newTo.ReflectY((int)horAxisY);
  51. }
  52. return new BresenhamLineOperation(newFrom, newTo, color, blendMode);
  53. }
  54. public void Dispose()
  55. {
  56. paint.Dispose();
  57. }
  58. }