Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Voronoi diagrams #692

Merged
merged 36 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
f0b9f96
Initial implementation
Lehonti Jan 14, 2024
543f89a
Added it to `CoreEffectsExtension`
Lehonti Jan 14, 2024
08dbde2
Assigned distance
Lehonti Jan 14, 2024
c9da51b
Reduced number of points
Lehonti Jan 14, 2024
3a0a12d
Merge branch 'PintaProject:master' into feature/voronoi
Lehonti Jan 14, 2024
4d3f34c
Using immutable structures
Lehonti Jan 14, 2024
e146763
Added Chebyshev method of distance calculation
Lehonti Jan 14, 2024
4cd5095
Added color sorting
Lehonti Jan 14, 2024
83c9136
Added labels to sorting options
Lehonti Jan 14, 2024
c33fd4d
Added notes for translators, and added option to invert sorting
Lehonti Jan 14, 2024
e000330
Removed empty comment for translators
Lehonti Jan 14, 2024
b7d6b14
stored values in more variables
Lehonti Jan 14, 2024
368f2cb
Created new `record` type for settings
Lehonti Jan 14, 2024
2dfe1a8
Added option to show points
Lehonti Jan 14, 2024
bd4babb
Local refactoring and reformatting
Lehonti Jan 14, 2024
c00bec6
Ordering of points
Lehonti Jan 14, 2024
1b452dc
Merge branch 'PintaProject:master' into feature/voronoi
Lehonti Jan 15, 2024
3fa9d8f
Changed naming and added TODO comment
Lehonti Jan 15, 2024
4955709
Added tests
Lehonti Jan 15, 2024
53f5bcb
Removed property assignment
Lehonti Jan 15, 2024
1aab816
Constructor now gets a service manager
Lehonti Jan 15, 2024
38ca138
Created `Utility.GeneratePixelOffsets`
Lehonti Jan 16, 2024
73946e6
Creating pixels in parallel
Lehonti Jan 16, 2024
4fa83a6
Removed intermediate dictionary structure and added check
Lehonti Jan 16, 2024
d85079e
Revert "Removed intermediate dictionary structure and added check"
Lehonti Jan 16, 2024
63ed0cd
With the dictionary it seems to work faster for some reason
Lehonti Jan 16, 2024
44b3fba
Tried parallel (and removing intermediate structure) in some other way
Lehonti Jan 16, 2024
c1a2ce9
A few adjustments
Lehonti Jan 17, 2024
b8ca36a
Solved merge conflicts
Lehonti Jan 18, 2024
313f7ee
Added chrome service to `VoronoiDiagramEffect`
Lehonti Jan 18, 2024
0f772d2
Reduced number of sortings
Lehonti Jan 19, 2024
aa26e5a
Removed a test
Lehonti Jan 19, 2024
c91da94
Merge branch 'PintaProject:master' into feature/voronoi
Lehonti Jan 19, 2024
e34c9b1
Changed comments for translators
Lehonti Jan 20, 2024
d354929
Merge branch 'PintaProject:master' into feature/voronoi
Lehonti Jan 20, 2024
9b44f4e
Added two more tests
Lehonti Jan 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Pinta.Core/Effects/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
/////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Reflection;

Expand Down Expand Up @@ -50,6 +51,27 @@ public static double Magnitude (this PointI point)
public static double Distance (this PointD origin, in PointD dest)
=> Magnitude (origin - dest);

public readonly record struct PixelOffset (PointI coordinates, int memoryOffset);

/// <returns>
/// Offsets of pixels, if we consider all pixels in a canvas of
/// size <paramref name="canvasSize"/> to be sequential in memory
/// (from left to right, and top to bottom)
/// </returns>
public static IEnumerable<PixelOffset> GeneratePixelOffsets (this RectangleI roi, Size canvasSize)
{
if (roi.Left < 0 || roi.Right >= canvasSize.Width || roi.Top < 0 || roi.Bottom >= canvasSize.Height)
throw new ArgumentException ($"Rectangle is out of size bounds");

for (int y = roi.Top; y <= roi.Bottom; y++) {
int rowOffset = y * canvasSize.Width;
for (int x = roi.Left; x <= roi.Right; x++)
yield return new (
coordinates: new (x, y),
memoryOffset: rowOffset + x);
}
}

/// <exception cref="ArgumentException">
/// Difference between upper and lower bounds is zero
/// </exception>
Expand Down
2 changes: 2 additions & 0 deletions Pinta.Effects/CoreEffectsExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public void Initialize ()
PintaCore.Effects.RegisterEffect (new TileEffect (services));
PintaCore.Effects.RegisterEffect (new TwistEffect (services));
PintaCore.Effects.RegisterEffect (new UnfocusEffect (services));
PintaCore.Effects.RegisterEffect (new VoronoiDiagramEffect (services));
PintaCore.Effects.RegisterEffect (new ZoomBlurEffect (services));
}

Expand Down Expand Up @@ -130,6 +131,7 @@ public void Uninitialize ()
PintaCore.Effects.UnregisterInstanceOfEffect (typeof (TileEffect));
PintaCore.Effects.UnregisterInstanceOfEffect (typeof (TwistEffect));
PintaCore.Effects.UnregisterInstanceOfEffect (typeof (UnfocusEffect));
PintaCore.Effects.UnregisterInstanceOfEffect (typeof (VoronoiDiagramEffect));
PintaCore.Effects.UnregisterInstanceOfEffect (typeof (ZoomBlurEffect));
}
#endregion
Expand Down
251 changes: 251 additions & 0 deletions Pinta.Effects/Effects/VoronoiDiagramEffect.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using Cairo;
using Pinta.Core;
using Pinta.Gui.Widgets;

namespace Pinta.Effects;

public sealed class VoronoiDiagramEffect : BaseEffect
{
// TODO: Icon

public override bool IsTileable => false;

public override string Name => Translations.GetString ("Voronoi Diagram");

public override bool IsConfigurable => true;

public override string EffectMenuCategory => Translations.GetString ("Render");

public VoronoiDiagramData Data => (VoronoiDiagramData) EffectData!; // NRT - Set in constructor

private readonly IChromeService chrome;

public VoronoiDiagramEffect (IServiceManager services)
{
chrome = services.GetService<IChromeService> ();
EffectData = new VoronoiDiagramData ();
}

public override void LaunchConfiguration ()
=> chrome.LaunchSimpleEffectDialog (this);

private sealed record VoronoiSettings (
Size size,
bool showPoints,
ImmutableArray<PointI> points,
ImmutableArray<ColorBgra> colors,
Func<PointI, PointI, double> distanceCalculator);

private VoronoiSettings CreateSettings (ImageSurface dst, RectangleI roi)
{
ColorSorting colorSorting = Data.ColorSorting;

IEnumerable<PointI> basePoints = CreatePoints (roi, Data.NumberOfCells, Data.RandomPointLocations);
ImmutableArray<PointI> points = SortPoints (basePoints, colorSorting).ToImmutableArray ();

IEnumerable<ColorBgra> baseColors = CreateColors (points.Length, Data.RandomColors);
IEnumerable<ColorBgra> positionSortedColors = SortColors (baseColors, colorSorting);
IEnumerable<ColorBgra> reversedSortingColors = Data.ReverseColorSorting ? positionSortedColors.Reverse () : positionSortedColors;

return new (
size: dst.GetSize (),
showPoints: Data.ShowPoints,
points: points,
colors: reversedSortingColors.ToImmutableArray (),
distanceCalculator: GetDistanceCalculator (Data.DistanceMetric)
);
}

protected override void Render (ImageSurface src, ImageSurface dst, RectangleI roi)
{
VoronoiSettings settings = CreateSettings (dst, roi);
Span<ColorBgra> dst_data = dst.GetPixelData ();
foreach (var kvp in roi.GeneratePixelOffsets (settings.size).AsParallel ().Select (CreateColor))
dst_data[kvp.Key] = kvp.Value;

KeyValuePair<int, ColorBgra> CreateColor (Utility.PixelOffset pixel)
{
double shortestDistance = double.MaxValue;
int closestIndex = 0;

for (var i = 0; i < settings.points.Length; i++) {
// TODO: Acceleration structure that limits the search
// to a relevant subset of points, for better performance.
// Some ideas to consider: quadtree, spatial hashing
var point = settings.points[i];
double distance = settings.distanceCalculator (point, pixel.coordinates);
if (distance > shortestDistance) continue;
shortestDistance = distance;
closestIndex = i;
}

ColorBgra finalColor =
settings.showPoints && shortestDistance == 0
? ColorBgra.Black
: settings.colors[closestIndex];

return KeyValuePair.Create (pixel.memoryOffset, finalColor);
}
}

private static IEnumerable<ColorBgra> SortColors (IEnumerable<ColorBgra> baseColors, ColorSorting colorSorting)

=> colorSorting switch {

ColorSorting.Random => baseColors,

ColorSorting.HorizontalB or ColorSorting.VerticalB => baseColors.OrderBy (p => p.B),
ColorSorting.HorizontalG or ColorSorting.VerticalG => baseColors.OrderBy (p => p.G),
ColorSorting.HorizontalR or ColorSorting.VerticalR => baseColors.OrderBy (p => p.R),

_ => throw new InvalidEnumArgumentException (
nameof (baseColors),
(int) colorSorting,
typeof (ColorSorting)),
};

private static IEnumerable<PointI> SortPoints (IEnumerable<PointI> basePoints, ColorSorting colorSorting)

=> colorSorting switch {

ColorSorting.Random => basePoints,

ColorSorting.HorizontalB
or ColorSorting.HorizontalG
or ColorSorting.HorizontalR => basePoints.OrderBy (p => p.X).ThenBy (p => p.Y),

ColorSorting.VerticalB
or ColorSorting.VerticalG
or ColorSorting.VerticalR => basePoints.OrderBy (p => p.Y).ThenBy (p => p.X),

_ => throw new InvalidEnumArgumentException (
nameof (colorSorting),
(int) colorSorting,
typeof (ColorSorting)),
};

private static Func<PointI, PointI, double> GetDistanceCalculator (DistanceMetric distanceCalculationMethod)
{
return distanceCalculationMethod switch {
DistanceMetric.Euclidean => Euclidean,
DistanceMetric.Manhattan => Manhattan,
DistanceMetric.Chebyshev => Chebyshev,
_ => throw new InvalidEnumArgumentException (
nameof (distanceCalculationMethod),
(int) distanceCalculationMethod,
typeof (DistanceMetric)),
};

static double Euclidean (PointI targetPoint, PointI pixelLocation)
{
PointI difference = pixelLocation - targetPoint;
return difference.Magnitude ();
}

static double Manhattan (PointI targetPoint, PointI pixelLocation)
{
PointI difference = pixelLocation - targetPoint;
return Math.Abs (difference.X) + Math.Abs (difference.Y);
}

static double Chebyshev (PointI targetPoint, PointI pixelLocation)
{
PointI difference = pixelLocation - targetPoint;
return Math.Max (Math.Abs (difference.X), Math.Abs (difference.Y));
}
}

private static ImmutableHashSet<PointI> CreatePoints (RectangleI roi, int pointCount, RandomSeed pointLocationsSeed)
{
int effectivePointCount = Math.Min (pointCount, roi.Width * roi.Height);

Random randomPositioner = new (pointLocationsSeed.Value);
var result = ImmutableHashSet.CreateBuilder<PointI> (); // Ensures points' uniqueness

while (result.Count < effectivePointCount) {

PointI point = new (
X: randomPositioner.Next (roi.Left, roi.Right + 1),
Y: randomPositioner.Next (roi.Top, roi.Bottom + 1)
);

result.Add (point);
}

return result.ToImmutable ();
}

private static IEnumerable<ColorBgra> CreateColors (int colorCount, RandomSeed colorsSeed)
{
Random randomColorizer = new (colorsSeed.Value);
HashSet<ColorBgra> uniquenessTracker = new ();
while (uniquenessTracker.Count < colorCount) {
ColorBgra candidateColor = randomColorizer.RandomColorBgra ();
if (uniquenessTracker.Contains (candidateColor)) continue;
uniquenessTracker.Add (candidateColor);
yield return candidateColor;
}
}

public sealed class VoronoiDiagramData : EffectData
{
[Caption ("Distance Metric")]
public DistanceMetric DistanceMetric { get; set; } = DistanceMetric.Euclidean;

[Caption ("Number of Cells"), MinimumValue (1), MaximumValue (1024)]
public int NumberOfCells { get; set; } = 100;

// Translators: The user can choose whether or not to render the points used in the calculation of a Voronoi diagram
[Caption ("Show Points")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there good use cases for this to be exposed to users? Seems more like a debugging option to me at first glance

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It could be an educational tool, so that they see that the cells are centered around the points, and then it piques their curiosity and then they look it up

public bool ShowPoints { get; set; } = false;

[Caption ("Color Sorting")]
public ColorSorting ColorSorting { get; set; } = ColorSorting.Random;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might need some more thought on how to present it to the user. The effect is neat, but the huge menu of combinations seems intimidating
The menu may change, but I'll also mention that Random Color Sorting could just be Random since it's inside a menu labelled Color Sorting


// Translators: In this context, "reverse" is a verb, and the user can choose whether or not they want to reverse the color sorting
[Caption ("Reverse Color Sorting")]
public bool ReverseColorSorting { get; set; } = false;

[Caption ("Random Colors")]
public RandomSeed RandomColors { get; set; } = new (0);

[Caption ("Random Point Locations")]
public RandomSeed RandomPointLocations { get; set; } = new (0);
}

public enum DistanceMetric
{
Euclidean,
Manhattan,
Chebyshev,
}

public enum ColorSorting
{
[Caption ("Random")] Random,

// Translators: Horizontal color sorting with blue (B) as the leading term
[Caption ("Horizontal blue (B)")] HorizontalB,

// Translators: Horizontal color sorting with green (G) as the leading term
[Caption ("Horizontal green (G)")] HorizontalG,

// Translators: Horizontal color sorting with red (R) as the leading term
[Caption ("Horizontal red (R)")] HorizontalR,


// Translators: Vertical color sorting with blue (B) as the leading term
[Caption ("Vertical blue (B)")] VerticalB,

// Translators: Vertical color sorting with green (G) as the leading term
[Caption ("Vertical green (G)")] VerticalG,

// Translators: Vertical color sorting with red (R) as the leading term
[Caption ("Vertical red (R)")] VerticalR,
}
}
Binary file added tests/Pinta.Effects.Tests/Assets/voronoi1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/Pinta.Effects.Tests/Assets/voronoi2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/Pinta.Effects.Tests/Assets/voronoi3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/Pinta.Effects.Tests/Assets/voronoi4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/Pinta.Effects.Tests/Assets/voronoi5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 40 additions & 1 deletion tests/Pinta.Effects.Tests/EffectsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ public void Pixelate2 ()

[Test]
[Ignore ("Depends on PintaCore being initialized")]
public void PolarInversion ()
public void PolarInversion1 ()
{
// TODO
}
Expand Down Expand Up @@ -454,6 +454,45 @@ public void Unfocus2 ()
Utilities.TestEffect (effect, "unfocus2.png");
}

[Test]
public void Voronoi1 ()
{
var effect = new VoronoiDiagramEffect (Utilities.CreateMockServices ());
Utilities.TestEffect (effect, "voronoi1.png");
}

[Test]
public void Voronoi2 ()
{
var effect = new VoronoiDiagramEffect (Utilities.CreateMockServices ());
effect.Data.NumberOfCells = 200;
Utilities.TestEffect (effect, "voronoi2.png");
}

[Test]
public void Voronoi3 ()
{
var effect = new VoronoiDiagramEffect (Utilities.CreateMockServices ());
effect.Data.DistanceMetric = VoronoiDiagramEffect.DistanceMetric.Manhattan;
Utilities.TestEffect (effect, "voronoi3.png");
}

[Test]
public void Voronoi4 ()
{
var effect = new VoronoiDiagramEffect (Utilities.CreateMockServices ());
effect.Data.ColorSorting = VoronoiDiagramEffect.ColorSorting.HorizontalB;
Utilities.TestEffect (effect, "voronoi4.png");
}

[Test]
public void Voronoi5 ()
{
var effect = new VoronoiDiagramEffect (Utilities.CreateMockServices ());
effect.Data.ColorSorting = VoronoiDiagramEffect.ColorSorting.VerticalB;
Utilities.TestEffect (effect, "voronoi5.png");
}

[Test]
public void ZoomBlur1 ()
{
Expand Down