Skip to content

Instantly share code, notes, and snippets.

@MrKWatkins
Created May 7, 2018 16:43
Show Gist options
  • Save MrKWatkins/ea62814ed78b79edf8c5aa4902652ff3 to your computer and use it in GitHub Desktop.
Save MrKWatkins/ea62814ed78b79edf8c5aa4902652ff3 to your computer and use it in GitHub Desktop.
C# code to generate GIMP .gpl palette files for 8 and 9-bit ZX Spectrum Next palettes
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using JetBrains.Annotations;
namespace Elena.Compiler.Console
{
/// <summary>
/// Utility class to write out 8 and 9-bit Next palettes in Gimp GPL format.
/// </summary>
public static class PaletteGenerator
{
// These steps are used to interpolate the full 255 range over the relevant number of bits. They split the range evenly
// and the first 2/3 bits of the interpolated value are the 2/3 bit value, meaning we can just trim the first 2/3 bits
// of the interpolated value to get the Next value.
internal const byte Step2Bit = 85;
internal const byte Step3Bit = 36;
public static void Write8BitToFile([NotNull] [PathReference] string path)
{
using (var writer = File.CreateText(path))
{
WriteHeader(writer, "ZX Spectrum Next 8-Bit");
WriteColours(writer, Enumerate8BitColours());
}
}
public static void Write9BitToFile([NotNull] [PathReference] string path)
{
using (var writer = File.CreateText(path))
{
WriteHeader(writer, "ZX Spectrum Next 9-Bit");
WriteColours(writer, Enumerate9BitColours());
}
}
[Pure]
[NotNull]
[LinqTunnel]
public static IEnumerable<Color> Enumerate8BitColours() => EnumerateColours(Step2Bit);
[Pure]
[NotNull]
[LinqTunnel]
public static IEnumerable<Color> Enumerate9BitColours() => EnumerateColours(Step3Bit);
[Pure]
[LinqTunnel]
private static IEnumerable<Color> EnumerateColours(byte bStep)
{
for (var r = 0; r < 256; r+=Step3Bit)
for (var g = 0; g < 256; g+=Step3Bit)
for (var b = 0; b < 256; b+=bStep)
{
yield return Color.FromArgb(r, g, b);
}
}
private static void WriteColours([NotNull] TextWriter writer, [NotNull] [InstantHandle] IEnumerable<Color> colours, int startIndex = 0)
{
var index = startIndex;
foreach (var colour in colours)
{
WriteComponent(writer, colour.R);
writer.Write(' ');
WriteComponent(writer, colour.G);
writer.Write(' ');
WriteComponent(writer, colour.B);
writer.Write(" Index ");
writer.WriteLine(index);
index++;
}
}
private static void WriteComponent([NotNull] TextWriter writer, byte component)
{
writer.Write(component.ToString().PadLeft(3, ' '));
}
private static void WriteHeader([NotNull] TextWriter writer, [NotNull] string name)
{
writer.WriteLine("GIMP Palette");
writer.Write("Name: ");
writer.WriteLine(name);
writer.WriteLine("Columns: 16");
writer.WriteLine("#");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment