Texture and clut packing, All important information starts to join in one place for final export

This commit is contained in:
2025-03-11 12:32:22 +01:00
parent 10c2186966
commit 00c94d732b
8 changed files with 333 additions and 90 deletions

View File

@@ -1,70 +0,0 @@
using UnityEngine;
using UnityEditor;
using PSXSplash.RuntimeCode;
using System.IO;
namespace PSXSplash.EditorCode
{
[CustomEditor(typeof(PSXObjectExporter))]
public class PSXObjectExporterEditor : Editor
{
public override void OnInspectorGUI()
{
/*
PSXObjectExporter comp = (PSXObjectExporter)target;
serializedObject.Update();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.PropertyField(serializedObject.FindProperty("Mesh"));
if (GUILayout.Button("Export mesh"))
{
comp.Mesh.Export(comp.gameObject);
GUIUtility.ExitGUI();
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.PropertyField(serializedObject.FindProperty("Texture"));
if (GUILayout.Button("Export texture"))
{
ushort[] textureData = comp.Texture.ExportTexture(comp.gameObject);
string path = EditorUtility.SaveFilePanel(
"Save texture data",
"",
"texture_data",
"bin"
);
if (!string.IsNullOrEmpty(path))
{
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
foreach (ushort value in textureData)
{
writer.Write(value);
}
}
Hodně string path = EditorUtility.SaveFilePanel(
"Save clut data",
"",
"clut_data",
"bin"
);
if (!string.IsNullOrEmpty(path))
{
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
foreach (ushort value in clutData)
{
writer.Write(value);
}Hodně plyModifiedProperties();
*/
}
}
}

View File

@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 89b9844e599dd374098ec6168f0de0b0

View File

@@ -1,4 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using PSXSplash.RuntimeCode; using PSXSplash.RuntimeCode;
using Unity.Collections; using Unity.Collections;
using UnityEditor; using UnityEditor;
@@ -17,7 +19,6 @@ public class VRAMEditorWindow : EditorWindow
private const int VramWidth = 1024; private const int VramWidth = 1024;
private const int VramHeight = 512; private const int VramHeight = 512;
private VRAMPixel[,] vramPixels = new VRAMPixel[VramWidth, VramHeight];
private List<ProhibitedArea> prohibitedAreas = new List<ProhibitedArea>(); private List<ProhibitedArea> prohibitedAreas = new List<ProhibitedArea>();
private Vector2 scrollPosition; private Vector2 scrollPosition;
private Texture2D vramImage; private Texture2D vramImage;
@@ -44,16 +45,98 @@ public class VRAMEditorWindow : EditorWindow
} }
public static void PasteTexture(Texture2D baseTexture, Texture2D overlayTexture, int posX, int posY)
private void OnGUI()
{ {
vramImage = new Texture2D(VramWidth, VramHeight); if (baseTexture == null || overlayTexture == null)
{
Debug.LogError("Textures cannot be null!");
return;
}
// Get pixels from the overlay texture
Color[] overlayPixels = overlayTexture.GetPixels();
Color[] basePixels = baseTexture.GetPixels();
int baseWidth = baseTexture.width;
int baseHeight = baseTexture.height;
int overlayWidth = overlayTexture.width;
int overlayHeight = overlayTexture.height;
// Loop through the overlay texture and paste it onto the base texture
for (int y = 0; y < overlayHeight; y++)
{
for (int x = 0; x < overlayWidth; x++)
{
int baseX = posX + x;
int baseY = posY + y;
// Ensure we are within bounds of the base texture
if (baseX >= 0 && baseX < baseWidth && baseY >= 0 && baseY < baseHeight)
{
int baseIndex = baseY * baseWidth + baseX;
int overlayIndex = y * overlayWidth + x;
// Blend or replace pixel (simple overwrite in this case)
basePixels[baseIndex] = overlayPixels[overlayIndex];
}
}
}
// Apply the modified pixels back to the base texture
baseTexture.SetPixels(basePixels);
baseTexture.Apply();
}
private void PackTextures()
{
vramImage = new Texture2D(VramWidth, VramHeight);
NativeArray<Color32> blackPixels = new NativeArray<Color32>(VramWidth * VramHeight, Allocator.Temp); NativeArray<Color32> blackPixels = new NativeArray<Color32>(VramWidth * VramHeight, Allocator.Temp);
vramImage.SetPixelData(blackPixels, 0); vramImage.SetPixelData(blackPixels, 0);
vramImage.Apply(); vramImage.Apply();
blackPixels.Dispose(); blackPixels.Dispose();
PSXObjectExporter[] objects = FindObjectsByType<PSXObjectExporter>(FindObjectsSortMode.None);
foreach (PSXObjectExporter exp in objects)
{
exp.CreatePSXTexture2D();
}
List<Rect> dontPackAreas = new List<Rect>();
foreach (ProhibitedArea area in prohibitedAreas)
{
dontPackAreas.Add(new Rect(area.X, area.Y, area.Width, area.Height));
}
Rect buffer1 = new Rect(0, 0, selectedResolution.x, selectedResolution.y);
Rect buffer2 = verticalLayout ? new Rect(0, 256, selectedResolution.x, selectedResolution.y)
: new Rect(selectedResolution.x, 0, selectedResolution.x, selectedResolution.y);
dontPackAreas.Add(buffer1);
dontPackAreas.Add(buffer2);
VRAMPacker tp = new VRAMPacker(dontPackAreas);
var packed = tp.PackTexturesIntoVRAM(objects);
foreach (TextureAtlas ta in packed.atlases)
{
foreach (PSXTexture2D texture in ta.ContainedTextures)
{
Debug.Log($"Packing {texture} at: x:{ta.PositionX + texture.PackingX} y:{ta.PositionY + texture.PackingY}");
PasteTexture(vramImage, texture.GenerateVramPreview(), ta.PositionX + texture.PackingX, ta.PositionY + texture.PackingY);
Debug.Log($"Texpage: {texture.TexpageNum} Offset:({texture.PackingX},{texture.PackingY})");
for(int i = 0; i < texture.ColorPalette.Count; i++) {
vramImage.SetPixel(texture.ClutPackingX+i, texture.ClutPackingY, texture.ColorPalette[i].GetUnityColor());
}
vramImage.Apply();
}
}
}
private void OnGUI()
{
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.BeginVertical(); GUILayout.BeginVertical();
GUILayout.Label("VRAM Editor", EditorStyles.boldLabel); GUILayout.Label("VRAM Editor", EditorStyles.boldLabel);
@@ -64,16 +147,19 @@ public class VRAMEditorWindow : EditorWindow
bool canDBHorizontal = selectedResolution[0] * 2 <= 1024; bool canDBHorizontal = selectedResolution[0] * 2 <= 1024;
bool canDBVertical = selectedResolution[1] * 2 <= 512; bool canDBVertical = selectedResolution[1] * 2 <= 512;
if(canDBHorizontal || canDBVertical) { if (canDBHorizontal || canDBVertical)
{
dualBuffering = EditorGUILayout.Toggle("Dual Buffering", dualBuffering); dualBuffering = EditorGUILayout.Toggle("Dual Buffering", dualBuffering);
} }
else { dualBuffering = false; } else { dualBuffering = false; }
if(canDBVertical && canDBHorizontal) { if (canDBVertical && canDBHorizontal)
{
verticalLayout = EditorGUILayout.Toggle("Vertical", verticalLayout); verticalLayout = EditorGUILayout.Toggle("Vertical", verticalLayout);
} }
else if (canDBVertical) { verticalLayout = true; } else if (canDBVertical) { verticalLayout = true; }
else { else
{
verticalLayout = false; verticalLayout = false;
} }
@@ -106,6 +192,13 @@ public class VRAMEditorWindow : EditorWindow
{ {
prohibitedAreas.Add(new ProhibitedArea()); prohibitedAreas.Add(new ProhibitedArea());
} }
// New "Pack Textures" Button
if (GUILayout.Button("Pack Textures"))
{
PackTextures();
}
GUILayout.EndVertical(); GUILayout.EndVertical();
Rect vramRect = GUILayoutUtility.GetRect(VramWidth, VramHeight, GUILayout.ExpandWidth(false)); Rect vramRect = GUILayoutUtility.GetRect(VramWidth, VramHeight, GUILayout.ExpandWidth(false));
@@ -124,7 +217,8 @@ public class VRAMEditorWindow : EditorWindow
GUI.Label(new Rect(buffer2.center.x - 40, buffer2.center.y - 10, 80, 20), "Framebuffer B", EditorStyles.boldLabel); GUI.Label(new Rect(buffer2.center.x - 40, buffer2.center.y - 10, 80, 20), "Framebuffer B", EditorStyles.boldLabel);
} }
foreach(ProhibitedArea area in prohibitedAreas) { foreach (ProhibitedArea area in prohibitedAreas)
{
Rect areaRect = new Rect(vramRect.x + area.X, vramRect.y + area.Y, area.Width, area.Height); Rect areaRect = new Rect(vramRect.x + area.X, vramRect.y + area.Y, area.Width, area.Height);
EditorGUI.DrawRect(areaRect, prohibitedColor); EditorGUI.DrawRect(areaRect, prohibitedColor);
} }

View File

@@ -4,13 +4,19 @@ namespace PSXSplash.RuntimeCode
{ {
public class PSXObjectExporter : MonoBehaviour public class PSXObjectExporter : MonoBehaviour
{ {
public PSXBPP BitDepth;
public PSXMesh Mesh; [HideInInspector]
//ublic PSXTexture Texture; public PSXTexture2D Texture;
public void Export() public void CreatePSXTexture2D()
{ {
Debug.Log($"Export: {name}"); Renderer renderer = GetComponent<Renderer>();
if (renderer != null && renderer.sharedMaterial != null && renderer.sharedMaterial.mainTexture is Texture2D texture)
{
Texture = PSXTexture2D.CreateFromTexture2D(texture, BitDepth);
Texture.OriginalTexture = texture;
}
} }
} }
} }

View File

@@ -22,7 +22,7 @@ namespace PSXSplash.RuntimeCode
if (exporter != null) if (exporter != null)
{ {
exporter.Export(); //exporter.Export();
} }
foreach (Transform child in parentTransform) foreach (Transform child in parentTransform)

View File

@@ -78,6 +78,10 @@ namespace PSXSplash.RuntimeCode
b = (ushort)((packedValue >> 1) & 0b11111); b = (ushort)((packedValue >> 1) & 0b11111);
SemiTransparent = (packedValue & 0b1) != 0; SemiTransparent = (packedValue & 0b1) != 0;
} }
public Color GetUnityColor() {
return new Color(R / 31.0f, G / 31.0f, B / 31.0f);
}
} }
/// <summary> /// <summary>
@@ -86,10 +90,24 @@ namespace PSXSplash.RuntimeCode
public class PSXTexture2D public class PSXTexture2D
{ {
public int Width { get; set; } public int Width { get; set; }
public int QuantizedWidth { get; set; }
public int Height { get; set; } public int Height { get; set; }
public int[] PixelIndices { get; set; } public int[] PixelIndices { get; set; }
public List<VRAMPixel> ColorPalette = new List<VRAMPixel>(); public List<VRAMPixel> ColorPalette = new List<VRAMPixel>();
public PSXBPP BitDepth { get; set; } public PSXBPP BitDepth { get; set; }
public Texture2D OriginalTexture;
// Within supertexture
public int PackingX;
public int PackingY;
public int TexpageNum;
// Absolute positioning
public int ClutPackingX;
public int ClutPackingY;
private int _maxColors; private int _maxColors;
// Used only for 16bpp // Used only for 16bpp
@@ -106,7 +124,11 @@ namespace PSXSplash.RuntimeCode
PSXTexture2D psxTex = new PSXTexture2D(); PSXTexture2D psxTex = new PSXTexture2D();
psxTex.Width = inputTexture.width; psxTex.Width = inputTexture.width;
psxTex.QuantizedWidth = bitDepth == PSXBPP.TEX_4BIT ? inputTexture.width / 4 :
bitDepth == PSXBPP.TEX_8BIT ? inputTexture.width / 2 :
inputTexture.width;
psxTex.Height = inputTexture.height; psxTex.Height = inputTexture.height;
psxTex.BitDepth = bitDepth; psxTex.BitDepth = bitDepth;

191
Runtime/TexturePacker.cs Normal file
View File

@@ -0,0 +1,191 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using PSXSplash.RuntimeCode;
public class TextureAtlas
{
public PSXBPP BitDepth;
public int PositionX;
public int PositionY;
public int Width;
public const int Height = 256;
public List<PSXTexture2D> ContainedTextures = new List<PSXTexture2D>();
}
public class VRAMPacker
{
private List<TextureAtlas> _textureAtlases = new List<TextureAtlas>();
private List<Rect> _reservedAreas;
private List<TextureAtlas> _finalizedAtlases = new List<TextureAtlas>();
private List<Rect> _allocatedCLUTs = new List<Rect>();
private const int VRAM_WIDTH = 1024;
private const int VRAM_HEIGHT = 512;
public VRAMPacker(List<Rect> reservedAreas)
{
_reservedAreas = reservedAreas;
}
public (PSXObjectExporter[] processedObjects, List<TextureAtlas> atlases) PackTexturesIntoVRAM(PSXObjectExporter[] objects)
{
List<PSXTexture2D> uniqueTextures = new List<PSXTexture2D>();
var groupedObjects = objects.GroupBy(obj => obj.Texture.BitDepth).OrderByDescending(g => g.Key);
foreach (var group in groupedObjects)
{
int atlasWidth = group.Key switch
{
PSXBPP.TEX_16BIT => 256,
PSXBPP.TEX_8BIT => 128,
PSXBPP.TEX_4BIT => 64,
_ => 256
};
TextureAtlas atlas = new TextureAtlas { BitDepth = group.Key, Width = atlasWidth, PositionX = 0, PositionY = 0 };
_textureAtlases.Add(atlas);
foreach (var obj in group.OrderByDescending(obj => obj.Texture.QuantizedWidth * obj.Texture.Height))
{
if (uniqueTextures.Any(tex => tex.OriginalTexture.GetInstanceID() == obj.Texture.OriginalTexture.GetInstanceID() && tex.BitDepth == obj.Texture.BitDepth))
{
obj.Texture = uniqueTextures.First(tex => tex.OriginalTexture.GetInstanceID() == obj.Texture.OriginalTexture.GetInstanceID());
continue;
}
if (!TryPlaceTextureInAtlas(atlas, obj.Texture))
{
atlas = new TextureAtlas { BitDepth = group.Key, Width = atlasWidth, PositionX = 0, PositionY = 0 };
_textureAtlases.Add(atlas);
if (!TryPlaceTextureInAtlas(atlas, obj.Texture))
{
Debug.LogError($"Failed to pack texture {obj.Texture}. It might not fit.");
break;
}
}
uniqueTextures.Add(obj.Texture);
}
}
ArrangeAtlasesInVRAM();
AllocateCLUTs();
return (objects, _finalizedAtlases);
}
private bool TryPlaceTextureInAtlas(TextureAtlas atlas, PSXTexture2D texture)
{
for (int y = 0; y <= TextureAtlas.Height - texture.Height; y++)
{
for (int x = 0; x <= atlas.Width - texture.QuantizedWidth; x++)
{
var candidateRect = new Rect(x, y, texture.QuantizedWidth, texture.Height);
if (!atlas.ContainedTextures.Any(tex => new Rect(tex.PackingX, tex.PackingY, tex.QuantizedWidth, tex.Height).Overlaps(candidateRect)))
{
texture.PackingX = x;
texture.PackingY = y;
atlas.ContainedTextures.Add(texture);
return true;
}
}
}
return false;
}
private void ArrangeAtlasesInVRAM()
{
foreach (var bitDepth in new[] { PSXBPP.TEX_16BIT, PSXBPP.TEX_8BIT, PSXBPP.TEX_4BIT })
{
foreach (var atlas in _textureAtlases.Where(a => a.BitDepth == bitDepth))
{
bool placed = false;
for (int y = VRAM_HEIGHT - TextureAtlas.Height; y >= 0; y -= 256)
{
for (int x = 0; x <= VRAM_WIDTH - atlas.Width; x += 64)
{
if (atlas.PositionX == 0 && atlas.PositionY == 0)
{
var candidateRect = new Rect(x, y, atlas.Width, TextureAtlas.Height);
if (IsPlacementValid(candidateRect))
{
atlas.PositionX = x;
atlas.PositionY = y;
_finalizedAtlases.Add(atlas);
placed = true;
break;
}
}
}
if (placed)
{
foreach (PSXTexture2D texture in atlas.ContainedTextures)
{
texture.TexpageNum = CalculateTexpage(atlas.PositionX, atlas.PositionY);
}
break;
}
}
if (!placed)
{
Debug.LogError($"Atlas with BitDepth {atlas.BitDepth} and Width {atlas.Width} could not be placed in VRAM.");
}
}
}
}
private void AllocateCLUTs()
{
foreach (var texture in _finalizedAtlases.SelectMany(atlas => atlas.ContainedTextures))
{
if (texture.ColorPalette == null || texture.ColorPalette.Count == 0)
continue;
int clutWidth = texture.ColorPalette.Count;
int clutHeight = 1;
bool placed = false;
for (int y = 0; y < VRAM_HEIGHT; y++)
{
for (int x = 0; x <= VRAM_WIDTH - clutWidth; x++)
{
var candidate = new Rect(x, y, clutWidth, clutHeight);
if (IsPlacementValid(candidate))
{
_allocatedCLUTs.Add(candidate);
texture.ClutPackingX = x;
texture.ClutPackingY = y;
placed = true;
break;
}
}
if (placed) break;
}
if (!placed)
{
Debug.LogError($"Failed to allocate CLUT for texture at {texture.PackingX}, {texture.PackingY}");
}
}
}
private bool IsPlacementValid(Rect rect)
{
Rect adjustedRect = new Rect(rect.x, VRAM_HEIGHT - rect.y - rect.height, rect.width, rect.height);
return !_finalizedAtlases.Any(a => AtlasOverlaps(a, rect)) && !_reservedAreas.Any(b => b.Overlaps(adjustedRect));
}
private bool AtlasOverlaps(TextureAtlas atlas, Rect rect)
{
Rect atlasRect = new Rect(atlas.PositionX, atlas.PositionY, atlas.Width, TextureAtlas.Height);
return atlasRect.Overlaps(rect);
}
private int CalculateTexpage(int x, int y)
{
int columns = 16;
int rows = 2;
int colIndex = x / 64;
int rowIndex = (rows - 1) - (y / 256);
return (rowIndex * columns) + colIndex;
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ae72963f3a7f0820cbc31cb4764c51cb