using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Text.Json;
namespace AssetExtractor;
///
/// One-time migration tool: pulls sprites out of the Delphi DFM, converts .omap files
/// (TLZRW1 "LZH!" compressed text) to JSON, extracts tileset images from .oil files,
/// and copies the sound/music files into the MonoGame Content folder.
///
public static class Program
{
static string _srcDir = @"C:\Projects\Games\Delphi\Omega Games\Freedom Fighter";
static string _outDir = @"C:\Projects\Games\Visual Studio\FreedomFighter\FreedomFighter\Content";
static readonly string[] Maps = ["intro.omap", "test10.omap", "test7.omap", "test8.omap", "bonus.omap", "lvl5.omap"];
public static void Main(string[] args)
{
if (args.Length > 0) _srcDir = args[0];
if (args.Length > 1) _outDir = args[1];
foreach (var sub in new[] { "gfx", "maps", "tilesets", "sfx", "music" })
Directory.CreateDirectory(Path.Combine(_outDir, sub));
var oilsNeeded = new HashSet(StringComparer.OrdinalIgnoreCase);
ExtractDfmImages(Path.Combine(_srcDir, "GameU.dfm"));
foreach (var map in Maps)
{
var oil = ConvertMap(Path.Combine(_srcDir, map));
if (oil != null) oilsNeeded.Add(oil);
}
foreach (var oil in oilsNeeded)
ExtractOilTileset(Path.Combine(_srcDir, oil));
CopyAudio();
Console.WriteLine("Done.");
}
// ---------------------------------------------------------------- DFM images
record ImageItem(int Index, string Name, string File, int TileWidth, int TileHeight);
static void ExtractDfmImages(string dfmPath)
{
var lines = File.ReadAllLines(dfmPath);
var manifest = new Dictionary>();
string? currentList = null;
string itemName = "";
int tileW = 0, tileH = 0;
StringBuilder? hex = null;
byte[]? pictureData = null;
int itemIndex = 0;
void FlushItem()
{
if (currentList == null || pictureData == null) return;
string safeName = itemName.Length > 0 ? itemName : "unnamed";
string file = $"{currentList.ToLowerInvariant()}_{itemIndex:D2}_{safeName}.png";
SaveGraphic(pictureData, Path.Combine(_outDir, "gfx", file));
manifest.TryAdd(currentList, []);
// TileWidth/TileHeight of 0 means "whole image is one frame"
manifest[currentList].Add(new ImageItem(itemIndex, itemName, file, tileW, tileH));
Console.WriteLine($" {currentList}[{itemIndex}] '{itemName}' -> {file} ({tileW}x{tileH})");
itemIndex++;
pictureData = null;
itemName = "";
tileW = tileH = 0;
}
foreach (var raw in lines)
{
var line = raw.Trim();
if (hex != null)
{
bool end = line.EndsWith('}');
hex.Append(end ? line[..^1] : line);
if (end)
{
pictureData = Convert.FromHexString(hex.ToString());
hex = null;
}
continue;
}
if (line.StartsWith("object ") && line.Contains(": TOmegaImageList"))
{
FlushItem();
currentList = line["object ".Length..line.IndexOf(':')].Trim();
itemIndex = 0;
continue;
}
if (currentList == null) continue;
if (line.StartsWith("object ")) // next non-imagelist component
{
FlushItem();
currentList = null;
continue;
}
if (line == "item")
FlushItem();
else if (line.StartsWith("Name = '"))
itemName = line["Name = '".Length..^1];
else if (line.StartsWith("TileWidth = "))
tileW = int.Parse(line["TileWidth = ".Length..]);
else if (line.StartsWith("TileHeight = "))
tileH = int.Parse(line["TileHeight = ".Length..]);
else if (line.StartsWith("Picture.Data = {"))
hex = new StringBuilder(line["Picture.Data = {".Length..]);
}
FlushItem();
var json = JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(_outDir, "gfx", "manifest.json"), json);
Console.WriteLine(" wrote gfx/manifest.json");
}
/// Delphi TPicture blob: [1B class-name length][class name][payload].
static void SaveGraphic(byte[] data, string outPath)
{
int nameLen = data[0];
string cls = Encoding.ASCII.GetString(data, 1, nameLen);
int payloadStart = 1 + nameLen;
if (cls == "TPNGObject")
{
File.WriteAllBytes(outPath, data[payloadStart..]);
}
else if (cls == "TBitmap")
{
// payload: [4B length][BMP bytes]
int len = BitConverter.ToInt32(data, payloadStart);
var bmpBytes = new ReadOnlySpan(data, payloadStart + 4, len);
SaveBmpAsKeyedPng(bmpBytes.ToArray(), outPath);
}
else
{
throw new InvalidDataException($"Unknown graphic class '{cls}'");
}
}
/// Convert BMP to PNG, keying out the bottom-left pixel color (Delphi Transparent convention).
static void SaveBmpAsKeyedPng(byte[] bmpBytes, string outPath)
{
using var ms = new MemoryStream(bmpBytes);
using var src = new Bitmap(ms);
using var dst = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppArgb);
var key = src.GetPixel(0, src.Height - 1);
for (int y = 0; y < src.Height; y++)
for (int x = 0; x < src.Width; x++)
{
var c = src.GetPixel(x, y);
dst.SetPixel(x, y, c.R == key.R && c.G == key.G && c.B == key.B ? Color.Transparent : c);
}
dst.Save(outPath, ImageFormat.Png);
}
// ---------------------------------------------------------------- maps
static string? ConvertMap(string mapPath)
{
if (!File.Exists(mapPath))
{
Console.WriteLine($" MISSING map {mapPath}");
return null;
}
var text = Encoding.Latin1.GetString(Lzh.Decompress(File.ReadAllBytes(mapPath)));
var lines = text.Split("\r\n");
int p = 0;
string Next() => lines[p++];
int NextInt() => int.Parse(Next());
int w = NextInt();
int h = NextInt();
string oil = Next();
int tileW = NextInt();
int tileH = NextInt();
// Layer1: 17 lines per tile; keep only the pattern index (game uses nothing else)
var layer1 = new int[w][];
for (int a = 0; a < w; a++)
{
layer1[a] = new int[h];
for (int b = 0; b < h; b++)
{
p += 8; // x,y,r,g,b,alpha,rotation,image.index
layer1[a][b] = NextInt(); // imageindex (pattern)
p += 8; // animcount..animlooped
}
}
p += w * h * 18; // Layer2 (has extra DoCollision line)
p += w * h * 17; // Layer3
var triggers = new List