Hard Reset I guess

This commit is contained in:
Lani Aung
2024-02-11 21:30:36 -07:00
parent 2a1449ff2f
commit a8d3afd2a8
19 changed files with 376 additions and 2463 deletions
+134 -134
View File
@@ -6,156 +6,156 @@ using System.Text.RegularExpressions;
using fxl.codes.kisekae.Entities;
using Microsoft.Extensions.Logging;
namespace fxl.codes.kisekae.Services
namespace fxl.codes.kisekae.Services;
public class ConfigurationReaderService
{
public class ConfigurationReaderService
private const string CelRegex = @"#(?<Mark>\d*)\.?(?<Fix>\d*)\s*(?<FileName>[\w\d\-]*\.[cCeElL]*)\s*\*?"
+ @"(?<PaletteIndex>\d*)?\s*\:?(?<Sets>[\d\s]*)?;?(?<Comment>[\w\d\-\s\%]*)";
private const string ResolutionRegexPattern = @"\((?<Width>[0-9]*).(?<Height>[0-9]*)\)";
private readonly ILogger<ConfigurationReaderService> _logger;
public ConfigurationReaderService(ILogger<ConfigurationReaderService> logger)
{
private const string CelRegex = @"#(?<Mark>\d*)\.?(?<Fix>\d*)\s*(?<FileName>[\w\d\-]*\.[cCeElL]*)\s*\*?"
+ @"(?<PaletteIndex>\d*)?\s*\:?(?<Sets>[\d\s]*)?;?(?<Comment>[\w\d\-\s\%]*)";
_logger = logger;
}
private const string ResolutionRegexPattern = @"\((?<Width>[0-9]*).(?<Height>[0-9]*)\)";
public void ReadConfiguration(Configuration dto,
IDictionary<Configuration, int> backgroundColors,
IDictionary<string, Cel> cels,
Dictionary<string, Palette> palettes)
{
_logger.LogInformation($"Reading {dto.Name}");
var initialPositions = new StringBuilder();
var backgroundColorIndex = 0;
var paletteOrder = new List<Palette>();
var celLines = new List<string>();
private readonly ILogger<ConfigurationReaderService> _logger;
public ConfigurationReaderService(ILogger<ConfigurationReaderService> logger)
{
_logger = logger;
}
public void ReadConfiguration(Configuration dto,
IDictionary<Configuration, int> backgroundColors,
IDictionary<string, Cel> cels,
Dictionary<string, Palette> palettes)
{
_logger.LogInformation($"Reading {dto.Name}");
var initialPositions = new StringBuilder();
var backgroundColorIndex = 0;
var paletteOrder = new List<Palette>();
var celLines = new List<string>();
foreach (var line in dto.Data.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries))
switch (line.ToCharArray()[0])
{
case '(':
var resolutionRegex = new Regex(ResolutionRegexPattern);
var resolutionMatch = resolutionRegex.Match(line);
dto.Width = int.Parse(resolutionMatch.Groups["Width"].Value);
dto.Height = int.Parse(resolutionMatch.Groups["Height"].Value);
break;
case '[':
var borderValue = line[1..];
if (borderValue.Contains(';')) borderValue = borderValue.Split(';')[0].Trim();
backgroundColorIndex = int.Parse(borderValue);
break;
case '%':
SetPaletteOrder(line, palettes, paletteOrder);
break;
case '#':
celLines.Add(line);
break;
case '$':
case ' ':
initialPositions.Append(line);
break;
}
foreach (var line in celLines) dto.Cels.Add(SetCelConfig(line, dto, cels, paletteOrder));
SetInitialPositions(dto, initialPositions.ToString());
backgroundColors.Add(dto, backgroundColorIndex);
}
private static CelConfig SetCelConfig(string line, Configuration configuration, IDictionary<string, Cel> cels, IReadOnlyList<Palette> palettes)
{
var cel = new CelConfig
foreach (var line in dto.Data.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries))
switch (line.ToCharArray()[0])
{
Configuration = configuration
};
if (line.Contains("%t"))
{
var opacity = line[line.IndexOf("%t", StringComparison.InvariantCultureIgnoreCase)..].Trim();
opacity = opacity.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)[0];
opacity = opacity.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)[0];
opacity = opacity.Replace("%t", "");
cel.Transparency = int.Parse(opacity);
case '(':
var resolutionRegex = new Regex(ResolutionRegexPattern);
var resolutionMatch = resolutionRegex.Match(line);
dto.Width = int.Parse(resolutionMatch.Groups["Width"].Value);
dto.Height = int.Parse(resolutionMatch.Groups["Height"].Value);
break;
case '[':
var borderValue = line[1..];
if (borderValue.Contains(';')) borderValue = borderValue.Split(';')[0].Trim();
backgroundColorIndex = int.Parse(borderValue);
break;
case '%':
SetPaletteOrder(line, palettes, paletteOrder);
break;
case '#':
celLines.Add(line);
break;
case '$':
case ' ':
initialPositions.Append(line);
break;
}
var matcher = new Regex(CelRegex);
var match = matcher.Match(line);
foreach (var line in celLines) dto.Cels.Add(SetCelConfig(line, dto, cels, paletteOrder));
SetInitialPositions(dto, initialPositions.ToString());
backgroundColors.Add(dto, backgroundColorIndex);
}
foreach (var groupName in matcher.GetGroupNames())
private static CelConfig SetCelConfig(string line, Configuration configuration, IDictionary<string, Cel> cels, IReadOnlyList<Palette> palettes)
{
var cel = new CelConfig
{
Configuration = configuration
};
if (line.Contains("%t"))
{
var opacity = line[line.IndexOf("%t", StringComparison.InvariantCultureIgnoreCase)..].Trim();
opacity = opacity.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)[0];
opacity = opacity.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)[0];
opacity = opacity.Replace("%t", "");
cel.Transparency = int.Parse(opacity);
}
var matcher = new Regex(CelRegex);
var match = matcher.Match(line);
foreach (var groupName in matcher.GetGroupNames())
{
match.Groups.TryGetValue(groupName, out var group);
if (string.IsNullOrEmpty(group?.Value)) continue;
if (string.Equals(groupName, "FileName"))
{
match.Groups.TryGetValue(groupName, out var group);
if (string.IsNullOrEmpty(group?.Value)) continue;
if (string.Equals(groupName, "FileName"))
{
cel.Cel = cels[group.Value.ToLowerInvariant()];
continue;
}
if (string.Equals(groupName, "PaletteIndex"))
{
cel.Palette = palettes[int.Parse(group.Value)];
continue;
}
var property = typeof(CelConfig).GetProperty(groupName);
if (property == null) continue;
var value = group.Value.Trim();
if (property.PropertyType == typeof(string)) property.SetValue(cel, value);
if (property.PropertyType == typeof(int)) property.SetValue(cel, int.Parse(value));
if (property.PropertyType != cel.Sets.GetType()) continue;
foreach (var id in value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
var success = int.TryParse(id, out var result);
if (!success) continue;
cel.Sets[result] = true;
}
cel.Cel = cels[group.Value.ToLowerInvariant()];
continue;
}
cel.Palette ??= palettes[0];
if (!cel.Sets.Max()) Array.Fill(cel.Sets, true);
return cel;
}
private static void SetPaletteOrder(string line, IReadOnlyDictionary<string, Palette> palettes, ICollection<Palette> paletteOrder)
{
var parts = line.Split(';');
var palette = palettes[parts[0].Trim().ToLowerInvariant().Replace("%", "")];
paletteOrder.Add(palette);
}
private static void SetInitialPositions(Configuration dto, string positions)
{
var sets = positions.Split('$', StringSplitOptions.RemoveEmptyEntries);
for (var index = 0; index < sets.Length; index++)
if (string.Equals(groupName, "PaletteIndex"))
{
var set = sets[index];
var value = set.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var paletteGroup = int.Parse(value[0]);
cel.Palette = palettes[int.Parse(group.Value)];
continue;
}
for (var innerIndex = 1; innerIndex < value.Length; innerIndex++)
var property = typeof(CelConfig).GetProperty(groupName);
if (property == null) continue;
var value = group.Value.Trim();
if (property.PropertyType == typeof(string)) property.SetValue(cel, value);
if (property.PropertyType == typeof(int)) property.SetValue(cel, int.Parse(value));
if (property.PropertyType != cel.Sets.GetType()) continue;
foreach (var id in value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
var success = int.TryParse(id, out var result);
if (!success) continue;
cel.Sets[result] = true;
}
}
cel.Palette ??= palettes[0];
if (!cel.Sets.Max()) Array.Fill(cel.Sets, true);
return cel;
}
private static void SetPaletteOrder(string line, IReadOnlyDictionary<string, Palette> palettes, ICollection<Palette> paletteOrder)
{
var parts = line.Split(';');
var palette = palettes[parts[0].Trim().ToLowerInvariant().Replace("%", "")];
paletteOrder.Add(palette);
}
private static void SetInitialPositions(Configuration dto, string positions)
{
positions = Regex.Replace(positions, "[\\s]+", "|");
var sets = positions.Split('$', StringSplitOptions.RemoveEmptyEntries);
for (var index = 0; index < sets.Length; index++)
{
var set = sets[index];
var value = set.Split('|', StringSplitOptions.RemoveEmptyEntries);
var paletteGroup = int.Parse(value[0]);
for (var innerIndex = 1; innerIndex < value.Length; innerIndex++)
{
if (value[innerIndex].Contains('*')) continue;
var point = value[innerIndex].Trim().Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var cel in dto.Cels.Where(x => x.Mark == innerIndex - 1))
{
if (value[innerIndex].Contains('*')) continue;
var point = value[innerIndex].Trim().Split(',', StringSplitOptions.RemoveEmptyEntries);
cel.PaletteGroup = paletteGroup;
foreach (var cel in dto.Cels.Where(x => x.Mark == innerIndex - 1))
if (!cel.Sets[index]) continue;
cel.Positions.Add(new CelPosition
{
cel.PaletteGroup = paletteGroup;
if (!cel.Sets[index]) continue;
cel.Positions.Add(new CelPosition
{
Set = index,
X = int.Parse(point[0]),
Y = int.Parse(point[1])
});
}
Set = index,
X = int.Parse(point[0]),
Y = int.Parse(point[1])
});
}
}
}
+148 -152
View File
@@ -11,26 +11,26 @@ using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace fxl.codes.kisekae.Services
namespace fxl.codes.kisekae.Services;
public class FileParserService
{
public class FileParserService
private static readonly byte[] KissHeader = "KiSS"u8.ToArray();
private static readonly Color Transparent = Color.Black.WithAlpha(0);
private readonly ILogger<FileParserService> _logger;
private readonly IsolatedStorageFile _storage;
public FileParserService(ILogger<FileParserService> logger)
{
private static readonly byte[] KissHeader = "KiSS"u8.ToArray();
private static readonly Color Transparent = Color.Black.WithAlpha(0);
_logger = logger;
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
private readonly ILogger<FileParserService> _logger;
private readonly IsolatedStorageFile _storage;
public FileParserService(ILogger<FileParserService> logger)
public void UnzipLzh(IFormFile file, MemoryStream memoryStream = null)
{
if (!_storage.FileExists(file.FileName))
{
_logger = logger;
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
public void UnzipLzh(IFormFile file, MemoryStream memoryStream = null)
{
if (_storage.FileExists(file.FileName)) _storage.DeleteFile(file.FileName);
using var writer = _storage.CreateFile(file.FileName);
if (memoryStream != null)
@@ -40,166 +40,162 @@ namespace fxl.codes.kisekae.Services
writer.Flush();
writer.Close();
var root = _storage.GetType()
.GetProperty("RootDirectory", BindingFlags.Instance | BindingFlags.NonPublic)?
.GetValue(_storage)?
.ToString() ?? "";
var directory = Path.GetFileNameWithoutExtension(file.FileName);
if (_storage.DirectoryExists(directory))
{
var allFiles = _storage.GetFileNames(Path.Combine(directory, "*"));
foreach (var existingFile in allFiles) _storage.DeleteFile(Path.Combine(directory, existingFile));
_storage.DeleteDirectory(directory);
}
_storage.CreateDirectory(directory);
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "7z",
Arguments = $"x {Path.Combine(root, file.FileName)} -o{Path.Combine(root, directory)}",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
}
};
if (!process.Start()) throw new InvalidDataException("Unable to call p7zip to extract archive");
while (!process.StandardOutput.EndOfStream) _logger.LogTrace(process.StandardOutput.ReadLine());
process.WaitForExit();
_storage.DeleteFile(file.FileName);
}
public Color[] ParsePalette(Palette palette, out int groups, out int colorsPerGroup)
var root = _storage.GetType()
.GetProperty("RootDirectory", BindingFlags.Instance | BindingFlags.NonPublic)?
.GetValue(_storage)?
.ToString() ?? "";
var directory = Path.GetFileNameWithoutExtension(file.FileName);
if (_storage.DirectoryExists(directory)) return;
_storage.CreateDirectory(directory);
var process = new Process
{
groups = 0;
colorsPerGroup = 0;
StartInfo = new ProcessStartInfo
{
FileName = "7z",
Arguments = $"x {Path.Combine(root, file.FileName)} -o{Path.Combine(root, directory)}",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
}
};
if (palette.Data.Length == 0) return null;
if (!palette.Data[..KissHeader.Length].SequenceEqual(KissHeader)) return GetColors(palette.Data);
if (!process.Start()) throw new InvalidDataException("Unable to call p7zip to extract archive");
// Verify palette mark?
if (palette.Data[4] != 16) _logger.LogError($"{palette.FileName} is not a valid palette file");
while (!process.StandardOutput.EndOfStream) _logger.LogTrace(process.StandardOutput.ReadLine());
process.WaitForExit();
}
var colorDepth = Convert.ToInt32(palette.Data[5]);
colorsPerGroup = BitConverter.ToInt16(palette.Data, 8);
groups = BitConverter.ToInt16(palette.Data, 10);
public Color[] ParsePalette(Palette palette, out int groups, out int colorsPerGroup)
{
groups = 0;
colorsPerGroup = 0;
return GetColors(palette.Data[32..], colorDepth, colorsPerGroup, groups);
if (palette.Data.Length == 0) return null;
if (!palette.Data[..KissHeader.Length].SequenceEqual(KissHeader)) return GetColors(palette.Data);
// Verify palette mark?
if (palette.Data[4] != 16) _logger.LogError($"{palette.FileName} is not a valid palette file");
var colorDepth = Convert.ToInt32(palette.Data[5]);
colorsPerGroup = BitConverter.ToInt16(palette.Data, 8);
groups = BitConverter.ToInt16(palette.Data, 10);
return GetColors(palette.Data[32..], colorDepth, colorsPerGroup, groups);
}
public void RenderCel(CelConfig celConfig)
{
_logger.LogTrace($"Reading cel {celConfig.Cel.FileName}");
var buffer = celConfig.Cel?.Data?.ToArray();
if (buffer == null || buffer.Length == 0) return;
if (buffer[..KissHeader.Length].SequenceEqual(KissHeader))
{
// Verify cel mark?
if (buffer[4] != 32) _logger.LogError($"{celConfig.Cel.FileName} is not a valid cel file");
var pixelBits = Convert.ToInt32(buffer[5]);
var width = BitConverter.ToInt16(buffer, 8);
var height = BitConverter.ToInt16(buffer, 10);
var xOffset = BitConverter.ToInt16(buffer, 12);
var yOffset = BitConverter.ToInt16(buffer, 14);
celConfig.Cel.OffsetX = xOffset;
celConfig.Cel.OffsetY = yOffset;
celConfig.Cel.Height = height;
celConfig.Cel.Width = width;
celConfig.Render = GetCelImage(buffer[32..], celConfig.Palette, width, height, pixelBits);
}
else
{
var width = BitConverter.ToInt16(buffer, 0);
var height = BitConverter.ToInt16(buffer, 2);
celConfig.Cel.Height = height;
celConfig.Cel.Width = width;
celConfig.Render = GetCelImage(buffer[4..], celConfig.Palette, width, height);
}
}
private Color[] GetColors(IReadOnlyCollection<byte> bytes, int depth = 12, int colorsPerGroup = 16, int groups = 10)
{
_logger.LogTrace("Converting byte array to colors");
var colorValues = GetValues(bytes, depth / 3);
var colors = new Color[colorsPerGroup * groups];
var length = depth == 12 ? 4 : 3;
var multiplier = depth == 12 ? 16 : 1;
// Nibbles order for 12 bits: R, B, 0, G
for (var groupIndex = 0; groupIndex < groups; groupIndex++)
for (var colorIndex = 0; colorIndex < colorsPerGroup; colorIndex++)
{
var start = (groupIndex + colorIndex) * length;
var red = colorValues[start] * multiplier;
var green = colorValues[start + (depth == 12 ? 3 : 1)] * multiplier;
var blue = colorValues[start + (depth == 12 ? 1 : 2)] * multiplier;
colors[groupIndex + colorIndex] = Color.FromRgb(Convert.ToByte(red), Convert.ToByte(green), Convert.ToByte(blue));
}
public void RenderCel(CelConfig celConfig)
return colors;
}
private Render GetCelImage(IReadOnlyCollection<byte> bytes,
Palette palette,
int width,
int height,
int pixelBits = 4)
{
_logger.LogTrace("Converting byte array to base64 encoded gifs per palette");
var values = GetValues(bytes, pixelBits);
using var bitmap = new Image<Rgba32>(width, height);
bitmap.ProcessPixelRows(processor =>
{
_logger.LogTrace($"Reading cel {celConfig.Cel.FileName}");
var buffer = celConfig.Cel?.Data?.ToArray();
if (buffer == null || buffer.Length == 0) return;
if (buffer[..KissHeader.Length].SequenceEqual(KissHeader))
{
// Verify cel mark?
if (buffer[4] != 32) _logger.LogError($"{celConfig.Cel.FileName} is not a valid cel file");
var pixelBits = Convert.ToInt32(buffer[5]);
var width = BitConverter.ToInt16(buffer, 8);
var height = BitConverter.ToInt16(buffer, 10);
var xOffset = BitConverter.ToInt16(buffer, 12);
var yOffset = BitConverter.ToInt16(buffer, 14);
celConfig.Cel.OffsetX = xOffset;
celConfig.Cel.OffsetY = yOffset;
celConfig.Cel.Height = height;
celConfig.Cel.Width = width;
celConfig.Render = GetCelImage(buffer[32..], celConfig.Palette, width, height, pixelBits);
}
else
{
var width = BitConverter.ToInt16(buffer, 0);
var height = BitConverter.ToInt16(buffer, 2);
celConfig.Cel.Height = height;
celConfig.Cel.Width = width;
celConfig.Render = GetCelImage(buffer[4..], celConfig.Palette, width, height);
}
}
private Color[] GetColors(IReadOnlyCollection<byte> bytes, int depth = 12, int colorsPerGroup = 16, int groups = 10)
{
_logger.LogTrace("Converting byte array to colors");
var colorValues = GetValues(bytes, depth / 3);
var colors = new Color[colorsPerGroup * groups];
var length = depth == 12 ? 4 : 3;
var multiplier = depth == 12 ? 16 : 1;
// Nibbles order for 12 bits: R, B, 0, G
for (var groupIndex = 0; groupIndex < groups; groupIndex++)
for (var colorIndex = 0; colorIndex < colorsPerGroup; colorIndex++)
{
var start = (groupIndex + colorIndex) * length;
var red = colorValues[start] * multiplier;
var green = colorValues[start + (depth == 12 ? 3 : 1)] * multiplier;
var blue = colorValues[start + (depth == 12 ? 1 : 2)] * multiplier;
colors[groupIndex + colorIndex] = Color.FromRgb(Convert.ToByte(red), Convert.ToByte(green), Convert.ToByte(blue));
}
return colors;
}
private Render GetCelImage(IReadOnlyCollection<byte> bytes,
Palette palette,
int width,
int height,
int pixelBits = 4)
{
_logger.LogTrace("Converting byte array to base64 encoded gifs per palette");
var values = GetValues(bytes, pixelBits);
using var bitmap = new Image<Rgba32>(width, height);
var index = 0;
for (var row = 0; row < height; row++)
for (var y = 0; y < processor.Height; y++)
{
for (var column = 0; column < width; column++)
var row = processor.GetRowSpan(y);
for (var x = 0; x < row.Length; x++)
{
var value = values[index];
bitmap[row, column] = value == 0 || value >= palette.Colors.Count ? Transparent : Color.ParseHex(palette.Colors[value].Hex);
var isTransparent = value == 0 || value >= palette.Colors.Count;
row[x] = isTransparent ? Transparent : Color.ParseHex(palette.Colors[value].Hex);
index++;
}
if (width % 2 != 0 && pixelBits == 4) index++;
}
});
using var memory = new MemoryStream();
bitmap.SaveAsGif(memory);
using var memory = new MemoryStream();
bitmap.SaveAsGif(memory);
return new Render
{
Image = memory.ToArray()
};
}
private static int[] GetValues(IReadOnlyCollection<byte> bytes, int bits = 4)
return new Render
{
if (bits != 4) return bytes.Select(Convert.ToInt32).ToArray();
Image = memory.ToArray()
};
}
var values = new int[bytes.Count * 2];
var index = 0;
foreach (var slice in bytes)
{
var nib1 = (slice >> 4) & 0x0F;
var nib2 = slice & 0x0F;
values[index] = nib1;
values[index + 1] = nib2;
index += 2;
}
private static int[] GetValues(IReadOnlyCollection<byte> bytes, int bits = 4)
{
if (bits != 4) return bytes.Select(Convert.ToInt32).ToArray();
return values;
var values = new int[bytes.Count * 2];
var index = 0;
foreach (var slice in bytes)
{
var nib1 = (slice >> 4) & 0x0F;
var nib2 = slice & 0x0F;
values[index] = nib1;
values[index + 1] = nib2;
index += 2;
}
return values;
}
}