Understood, let's sort the neighbors based on the priority "mid > lower left > distance" while ensuring that within each quadrant the neighbors are sorted by distance from the center.
Below is the revised C# code:
using System;
using System.Linq;
public struct i8vec3 : IComparable<i8vec3>
{
public sbyte X;
public sbyte Y;
public sbyte Z;
public i8vec3(sbyte x, sbyte y, sbyte z)
{
X = x;
Y = y;
Z = z;
}
public int DistanceFromCenter()
{
return X * X + Y * Y + Z * Z;
}
// Implement CompareTo for sorting based on distance
public int CompareTo(i8vec3 other)
{
return DistanceFromCenter().CompareTo(other.DistanceFromCenter());
}
public override string ToString() => $"({X}, {Y}, {Z})";
}
public static class Neighbors
{
private static readonly i8vec3[] UnsortedNeighborOffsets = new i8vec3[]
{
new i8vec3( 0, 0, 0), // Center
new i8vec3(-1, -1, -1),
new i8vec3(-1, -1, 0),
new i8vec3(-1, -1, 1),
new i8vec3(-1, 0, -1),
new i8vec3(-1, 0, 0),
new i8vec3(-1, 0, 1),
new i8vec3(-1, 1, -1),
new i8vec3(-1, 1, 0),
new i8vec3(-1, 1, 1),
new i8vec3( 0, -1, -1),
new i8vec3( 0, -1, 0),
new i8vec3( 0, -1, 1),
new i8vec3( 0, 0, -1),
new i8vec3( 0, 0, 1),
new i8vec3( 0, 1, -1),
new i8vec3( 0, 1, 0),
new i8vec3( 0, 1, 1),
new i8vec3( 1, -1, -1),
new i8vec3( 1, -1, 0),
new i8vec3( 1, -1, 1),
new i8vec3( 1, 0, -1),
new i8vec3( 1, 0, 0),
new i8vec3( 1, 0, 1),
new i8vec3( 1, 1, -1),
new i8vec3( 1, 1, 0),
new i8vec3( 1, 1, 1),
};
public static readonly i8vec3[] NeighborOffsets;
static Neighbors()
{
NeighborOffsets = UnsortedNeighborOffsets
.OrderBy(neighbor => neighbor.X * neighbor.X + neighbor.Y * neighbor.Y + neighbor.Z * neighbor.Z)
.ThenBy(neighbor => neighbor)
.ToArray();
}
}
public class Program
{
public static void Main()
{
foreach (var neighbor in Neighbors.NeighborOffsets)
{
Console.WriteLine(neighbor);
}
}
}
Explanation:
-
Sorting Based on Distance:
DistanceFromCenter method calculates the squared distance from the origin to avoid the computational cost of Math.Sqrt.
IComparable<i8vec3> is implemented to allow comparison based on distance (priority within quadrants).
-
Sorting Neighbors:
- In the
Neighbors class, the UnsortedNeighborOffsets array is sorted by distance from the center using LINQ's OrderBy method.
ThenBy ensures that neighbors at the same distance can be sorted consistently (although in this context, it's simply there to maintain proper ordering if distances were identical).
-
Middle Point Priority:
- The neighbor
(0, 0, 0) is the first element in UnsortedNeighborOffsets and remains in the first position in the sorted array due to its zero distance.
Running the Main method will print out the neighbors sorted according to the specified priority.