Streamlining

This commit is contained in:
Lani Aung
2021-10-10 09:28:59 -06:00
parent 5646b3451f
commit e09f00945b
9 changed files with 105 additions and 99 deletions
+31 -32
View File
@@ -1,57 +1,56 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using fxl.codes.kisekae.Services;
using Microsoft.Extensions.Logging;
namespace fxl.codes.kisekae.Models namespace fxl.codes.kisekae.Models
{ {
public class CelModel public class CelModel
{ {
public const string Regex = @"#(\d*)\.?(\d*)\s*([\w\d\-]*\.[cCeElL]*)\s*\*?(\d*)?\s*\:?([\d\s]*)?;?([\w\d\-\s\%]*)"; private const string Regex = @"#(?<Id>\d*)\.?(?<Fix>\d*)\s*(?<FileName>[\w\d\-]*\.[cCeElL]*)\s*\*?(?<PaletteId>\d*)?\s*\:?(?<Sets>[\d\s]*)?;?(?<Comment>[\w\d\-\s\%]*)";
public Dictionary<int, string> ImageByPalette = new(); public Dictionary<int, string> ImageByPalette = new();
public CelModel(string line) internal CelModel(ILogger<ConfigurationReaderService> logger, string line)
{ {
logger.LogTrace($"Parsing cel line {line}");
var matcher = new Regex(Regex); var matcher = new Regex(Regex);
var match = matcher.Match(line); var match = matcher.Match(line);
foreach (var groupName in matcher.GetGroupNames()) foreach (var groupName in matcher.GetGroupNames())
{ {
if (groupName == "0") continue; var property = typeof(CelModel).GetProperty(groupName);
if (property == null) continue;
match.Groups.TryGetValue(groupName, out var group); match.Groups.TryGetValue(groupName, out var group);
if (string.IsNullOrEmpty(group?.Value)) continue; if (string.IsNullOrEmpty(group?.Value))
var value = group.Value.Trim();
switch (groupName)
{ {
case "1": logger.LogWarning($"Unable to find regex group {groupName} in {line}");
Id = int.Parse(value); continue;
break; }
case "2":
Fix = int.Parse(value); var value = group.Value.Trim();
break; if (property.PropertyType == typeof(string)) property.SetValue(this, value);
case "3": if (property.PropertyType == typeof(int)) property.SetValue(this, int.Parse(value));
FileName = value;
break; if (property.PropertyType != Sets.GetType()) continue;
case "4":
PaletteId = int.Parse(value); foreach (var id in value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
break; {
case "5": var success = int.TryParse(id, out var result);
foreach (var id in value.Split(' ', StringSplitOptions.RemoveEmptyEntries)) Sets[int.Parse(id)] = true; if (success) Sets[result] = true;
break; else logger.LogWarning($"Unable to parse {id} as cel sets");
case "6":
Comment = value;
break;
} }
} }
} }
public int Id { get; } public int Id { get; init; }
public int Fix { get; } public int Fix { get; init; }
public string FileName { get; } public string FileName { get; init; }
public int PaletteId { get; } public int PaletteId { get; init; }
public bool[] Sets { get; } = new bool[10]; public bool[] Sets { get; } = new bool[10];
public string Comment { get; } public string Comment { get; init; }
public Point[] InitialPositions { get; } = new Point[10]; public Coordinate[] InitialPositions { get; } = new Coordinate[10];
public string DefaultImage => ImageByPalette.ContainsKey(PaletteId) ? ImageByPalette[PaletteId] : null;
public Coordinate Offset { get; set; }
} }
} }
+14
View File
@@ -0,0 +1,14 @@
namespace fxl.codes.kisekae.Models
{
public class Coordinate
{
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
}
}
+5 -1
View File
@@ -1,12 +1,16 @@
using System; using System;
using fxl.codes.kisekae.Services;
using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp; using SixLabors.ImageSharp;
namespace fxl.codes.kisekae.Models namespace fxl.codes.kisekae.Models
{ {
public class PaletteModel public class PaletteModel
{ {
public PaletteModel(string line) internal PaletteModel(ILogger<ConfigurationReaderService> logger, string line)
{ {
logger.LogTrace($"Parsing palette line {line}");
var parts = line.Split(';'); var parts = line.Split(';');
FileName = parts[0].Replace("%", "").Trim(); FileName = parts[0].Replace("%", "").Trim();
+3 -2
View File
@@ -1,15 +1,16 @@
using System.Collections.Generic; using System.Collections.Generic;
using SixLabors.ImageSharp;
namespace fxl.codes.kisekae.Models namespace fxl.codes.kisekae.Models
{ {
public class PlaysetModel public class PlaysetModel
{ {
public int[] CurrentPalettes = new int[10];
public int Height { get; set; } public int Height { get; set; }
public int Width { get; set; } public int Width { get; set; }
public int BorderColorIndex { get; set; } public Color BorderColor { get; set; }
public List<PaletteModel> Palettes { get; } = new(); public List<PaletteModel> Palettes { get; } = new();
public List<CelModel> Cels { get; } = new(); public List<CelModel> Cels { get; } = new();
public int[] CurrentPalettes = new int[10];
} }
} }
-14
View File
@@ -1,14 +0,0 @@
namespace fxl.codes.kisekae.Models
{
public class Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}
}
+6 -4
View File
@@ -30,6 +30,7 @@ namespace fxl.codes.kisekae.Services
{ {
var model = new PlaysetModel(); var model = new PlaysetModel();
var initialPositions = new StringBuilder(); var initialPositions = new StringBuilder();
var borderColorIndex = 0;
using var reader = new StreamReader(fileStream); using var reader = new StreamReader(fileStream);
while (!reader.EndOfStream) while (!reader.EndOfStream)
@@ -48,13 +49,13 @@ namespace fxl.codes.kisekae.Services
case '[': case '[':
var borderValue = line.Replace("[", ""); var borderValue = line.Replace("[", "");
if (borderValue.Contains(';')) borderValue = borderValue.Split(';')[0].Trim(); if (borderValue.Contains(';')) borderValue = borderValue.Split(';')[0].Trim();
model.BorderColorIndex = int.Parse(borderValue); borderColorIndex = int.Parse(borderValue);
break; break;
case '%': case '%':
model.Palettes.Add(new PaletteModel(line)); model.Palettes.Add(new PaletteModel(_logger, line));
break; break;
case '#': case '#':
model.Cels.Add(new CelModel(line)); model.Cels.Add(new CelModel(_logger, line));
break; break;
case '$': case '$':
case ' ': case ' ':
@@ -64,6 +65,7 @@ namespace fxl.codes.kisekae.Services
} }
SetInitialPositions(model, initialPositions.ToString()); SetInitialPositions(model, initialPositions.ToString());
if (model.Palettes.Any() && model.Palettes[0].Colors.Any()) model.BorderColor = model.Palettes[0].Colors[borderColorIndex];
if (string.IsNullOrEmpty(directory)) return model; if (string.IsNullOrEmpty(directory)) return model;
@@ -95,7 +97,7 @@ namespace fxl.codes.kisekae.Services
foreach (var cel in model.Cels.Where(x => x.Id == innerIndex - 1)) foreach (var cel in model.Cels.Where(x => x.Id == innerIndex - 1))
{ {
cel.InitialPositions[index] = new Point(int.Parse(point[0]), int.Parse(point[1])); cel.InitialPositions[index] = new Coordinate(int.Parse(point[0]), int.Parse(point[1]));
} }
} }
} }
+41 -41
View File
@@ -14,6 +14,7 @@ namespace fxl.codes.kisekae.Services
public class FileParserService public class FileParserService
{ {
private static readonly byte[] KissHeader = Encoding.ASCII.GetBytes("KiSS"); private static readonly byte[] KissHeader = Encoding.ASCII.GetBytes("KiSS");
private static readonly Color Transparent = Color.Black.WithAlpha(0);
private readonly ILogger<FileParserService> _logger; private readonly ILogger<FileParserService> _logger;
private readonly IsolatedStorageFile _storage; private readonly IsolatedStorageFile _storage;
@@ -64,7 +65,8 @@ namespace fxl.codes.kisekae.Services
var xOffset = BitConverter.ToInt16(buffer, 12); var xOffset = BitConverter.ToInt16(buffer, 12);
var yOffset = BitConverter.ToInt16(buffer, 14); var yOffset = BitConverter.ToInt16(buffer, 14);
cel.ImageByPalette = GetCelImages(buffer[32..], palettes.ToArray(), width, height, pixelBits, xOffset, yOffset); cel.ImageByPalette = GetCelImages(buffer[32..], palettes.ToArray(), width, height, pixelBits);
cel.Offset = new Coordinate(xOffset, yOffset);
} }
else else
{ {
@@ -86,51 +88,37 @@ namespace fxl.codes.kisekae.Services
return buffer; return buffer;
} }
private Color[] GetColors(byte[] bytes, int depth = 12, int colorsPerGroup = 16, int groups = 10) private Color[] GetColors(IReadOnlyCollection<byte> bytes, int depth = 12, int colorsPerGroup = 16, int groups = 10)
{ {
_logger.LogTrace("Converting byte array to colors"); _logger.LogTrace("Converting byte array to colors");
var colorCounter = 0; var colorValues = GetValues(bytes, depth / 3);
var colors = new Color[colorsPerGroup * groups]; var colors = new Color[colorsPerGroup * groups];
var chunkSize = depth == 12 ? 2 : 3; var length = depth == 12 ? 4 : 3;
var multiplier = depth == 12 ? 16 : 1;
// Nibbles order for 12 bits: R, B, 0, G
for (var index = 0; index < bytes.Length; index += chunkSize) for (var groupIndex = 0; groupIndex < groups; groupIndex++)
for (var colorIndex = 0; colorIndex < colorsPerGroup; colorIndex++)
{ {
colors[colorCounter] = GetColor(bytes[index..(index + chunkSize)], depth); var start = (groupIndex + colorIndex) * length;
colorCounter++; 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; return colors;
} }
private static Color GetColor(IReadOnlyList<byte> bytes, int depth) private Dictionary<int, string> GetCelImages(IReadOnlyCollection<byte> bytes,
{
if (depth != 12) return Color.FromRgb(bytes[0], bytes[1], bytes[2]);
var redBlue = bytes[0];
var red = (redBlue >> 4) & 0x0F;
red += red * 16;
var blue = redBlue & 0x0F;
blue += blue * 16;
var zeroGreen = bytes[1];
var green = zeroGreen & 0x0F;
green += green * 16;
return Color.FromRgb(Convert.ToByte(red), Convert.ToByte(green), Convert.ToByte(blue));
}
private Dictionary<int, string> GetCelImages(IReadOnlyList<byte> bytes,
IReadOnlyList<PaletteModel> palettes, IReadOnlyList<PaletteModel> palettes,
int width, int width,
int height, int height,
int pixelBits = 4, int pixelBits = 4)
int xOffset = 0,
int yOffset = 0)
{ {
_logger.LogTrace("Converting byte array to base64 encoded gifs per palette"); _logger.LogTrace("Converting byte array to base64 encoded gifs per palette");
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
var step = (int)Math.Ceiling((double)8 / pixelBits); var values = GetValues(bytes, pixelBits);
for (var paletteIndex = 0; paletteIndex < palettes.Count; paletteIndex++) for (var paletteIndex = 0; paletteIndex < palettes.Count; paletteIndex++)
{ {
@@ -141,20 +129,14 @@ namespace fxl.codes.kisekae.Services
for (var row = 0; row < height; row++) for (var row = 0; row < height; row++)
{ {
var span = bitmap.GetPixelRowSpan(row); var span = bitmap.GetPixelRowSpan(row);
for (var column = 0; column < width; column += step) for (var column = 0; column < width; column++)
{ {
var pixelByte = bytes[index]; var value = values[index];
var nib1 = (pixelByte >> 4) & 0x0F; span[column] = value == 0 ? Transparent : palette.Colors[value];
span[column] = nib1 == 0 ? Color.Black.WithAlpha(0) : palette.Colors[nib1];
if (column + 1 < width)
{
var nib2 = pixelByte & 0x0F;
span[column + 1] = nib2 == 0 ? Color.Black.WithAlpha(0) : palette.Colors[nib2];
}
index++; index++;
} }
if (width % 2 != 0 && pixelBits == 4) index++;
} }
using var memory = new MemoryStream(); using var memory = new MemoryStream();
@@ -164,5 +146,23 @@ namespace fxl.codes.kisekae.Services
return dictionary; return dictionary;
} }
private static int[] GetValues(IReadOnlyCollection<byte> bytes, int bits = 4)
{
if (bits != 4) return bytes.Select(Convert.ToInt32).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;
}
return values;
}
} }
} }
+4 -4
View File
@@ -9,11 +9,14 @@
@foreach (var palette in Model.Palettes) @foreach (var palette in Model.Palettes)
{ {
<p> <p>
Start Palette
@palette.Comment<br> @palette.Comment<br>
@foreach (var color in palette.Colors) @foreach (var color in palette.Colors)
{ {
<span style="background-color: #@(color.ToHex())">@color</span> <span style="background-color: #@(color.ToHex())">@color</span>
} }
<br>
End Palette
</p> </p>
} }
</div> </div>
@@ -21,9 +24,6 @@
<div> <div>
@foreach (var cel in Model.Cels) @foreach (var cel in Model.Cels)
{ {
foreach (var (key, value) in cel.ImageByPalette) <img src="data:image/gif;base64,@cel.DefaultImage" alt="@cel.FileName">
{
<img src="data:image/gif;base64,@value" alt="@key">
}
} }
</div> </div>
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Trace",
"Microsoft": "Warning", "Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.Hosting.Lifetime": "Information"
} }