summaryrefslogtreecommitdiff
path: root/LUT.cs
blob: 06db8dd2a3c6003ef817b9742f11b0913b136506 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//#define TEXTURE_FEATURE

using System.Text;
using System.Numerics;
using System.Runtime.InteropServices;

using ImGuiNET;
using SharpPluginLoader.Core.Memory;
#if TEXTURE_FEATURE
using SharpPluginLoader.Core.Resources;
using SharpPluginLoader.Core.IO;
#endif

namespace WorldTuningTool
{
    using static Plugin;

    public class LUT
    {
        private const string addPath = "nativePC/plugins/CSharp/LUT";

        public LUT() { }

        // https://github.com/AsteriskAmpersand/CrappyLUTStudio--CLUTS-/blob/5af10daaa5f295b106cc5db09530a6fe5a4320d4/LUT.py#L35
        private byte[]? parseWorldLUT(BinaryReader reader)
        {
            byte[] signature = reader.ReadBytes(4);
            if (!(signature[0] == 0x54 && signature[1] == 0x45 &&
                (signature[2] == 0x58 && signature[3] == 0x0)))
            {
                return null;
            }
            ulong version = reader.ReadUInt64();
            uint datablock = reader.ReadUInt32();
            uint format = reader.ReadUInt32();
            uint mipCount = reader.ReadUInt32();
            uint width = reader.ReadUInt32();
            uint height = reader.ReadUInt32();
            uint mipListCount = reader.ReadUInt32();
            uint typeData = reader.ReadUInt32();
            uint depth = reader.ReadUInt32();
            byte[] NULL0 = reader.ReadBytes(12);
            int NEG0 = reader.ReadInt32();
            byte[] NULL1 = reader.ReadBytes(8);
            int Special = reader.ReadInt32();
            byte[] NULL2 = reader.ReadBytes(16);
            byte[] NEG1 = reader.ReadBytes(32);
            byte[] flags = reader.ReadBytes(32);
            byte[] NULLX = reader.ReadBytes(32);
            reader.BaseStream.Position = (long)reader.ReadUInt64();
            if (!(width == 32 && height == 32 && depth == 32))
            {
                return null;
            }
            return reader.ReadBytes((int)(width * height * depth * 8));
        }

        // https://drive.google.com/file/d/143Eh08ZYncCAMwJ1q4gWxVOqR_OSWYvs/view
        // When does DOMAIN_MIN/MAX apply?
        private byte[]? parseCubeLUT(StreamReader reader)
        {
            string? line;
            Vector3[]? parsed = null;
            int dim = 0, i = 0;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    try
                    {
                        dim = Convert.ToInt32(line.Split(' ').Last());
                    }
                    catch (Exception) { return null; }
                    if (dim != 32) return null;
                    parsed = new Vector3[dim * dim * dim];
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line == "") continue;
                        if (line[0] == '0' || line[0] == '1')
                        {
                            break;
                        }
                    }
                    if (line == null) break;
                }
                if (parsed != null)
                {
                    try
                    {
                        parsed[i++] = StringToVector3(line, ' ');
                    }
                    catch (Exception) { return null; }
                }
            }
            if (parsed == null)
            {
                return null;
            }
            const int lutDataSize = 32 * 32 * 32 * 8;
            byte[] data = new byte[lutDataSize];
            float scale = MathF.Pow(2, 14) - 1;
            for (i = 0; i < lutDataSize; i += 8)
            {
                Vector3 v = parsed[i / 8];
                ushort normX = (ushort)Math.Round(v.X * scale);
                ushort normY = (ushort)Math.Round(v.Y * scale);
                ushort normZ = (ushort)Math.Round(v.Z * scale);
                byte[] bytes = BitConverter.GetBytes(normX);
                data[i] = bytes[0];
                data[i + 1] = bytes[1];
                bytes = BitConverter.GetBytes(normY);
                data[i + 2] = bytes[0];
                data[i + 3] = bytes[1];
                bytes = BitConverter.GetBytes(normZ);
                data[i + 4] = bytes[0];
                data[i + 5] = bytes[1];
                bytes = BitConverter.GetBytes(0x2B88); // Alpha constant.
                data[i + 6] = bytes[0];
                data[i + 7] = bytes[1];
            }
            return data;
        }

        private unsafe bool overwriteFromStream(nint texture, Stream stream, bool cube = false)
        {
            byte[]? data = null;
            if (cube)
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    data = parseCubeLUT(reader);
                }
            }
            else
            {
                using (BinaryReader reader = new BinaryReader(stream, Encoding.ASCII, false))
                {
                    data = parseWorldLUT(reader);
                }
            }
            if (data == null)
            {
                return false;
            }
#if TEXTURE_FEATURE
            fixed (byte *dataPointer = (byte[])data)
            {
                // DXGI_FORMAT_R16G16B16A16_FLOAT = 10
                return new Texture(texture).Replace(dataPointer, 10, 32, 32, 32);
            }
#else
            return true;
#endif
        }

        private unsafe bool overwriteFromFile(nint texture, string path)
        {
            string ext = path.Split('.').Last().ToLower();
            using (FileStream stream = File.Open(path, FileMode.Open))
            {
                return overwriteFromStream(texture, stream, ext == "cube");
            }
        }

        private void reloadBlendLUT(nint lightingObject)
        {
            MemoryUtil.GetRef<float>(lightingObject + 0x1D4) = MemoryUtil.GetRef<float>(lightingObject + 0x1D0) + 1.0f;
        }

        private string[] fileList = [];
        private static string[] selectedFile = [ "", "" ];
        private static bool[] selectionStarted = [ false, false ];
        private static bool[] selectedInvalid = [ false, false ];

        public void DrawUI(nint texture, nint lightingObject, int i, float width)
        {
            ImGui.PushID(i);
            string lutPath = Marshal.PtrToStringAnsi(texture + 0xC)!;
            ImGui.Text($"LUT {i}: {lutPath}");
#if TEXTURE_FEATURE
            if (ImGui.Button("Reset"))
            {
                MtFileStream? file = MtFileStream.FromPath($"native:\\{lutPath}.tex", OpenMode.Read, false);
                if (file != null)
                {
                    if (overwriteFromStream(texture, new MemoryStream(file.Read(file.Length))))
                    {
                        reloadBlendLUT(lightingObject);
                    }
                    file.Close();
                }
                selectedFile[i] = "";
                selectedInvalid[i] = false;
            }
            ImGui.SameLine();
            ImGui.SetNextItemWidth(width * 0.6f);
            bool prevWasInvalid = selectedInvalid[i];
            if (prevWasInvalid)
            {
                ImGui.PushStyleColor(ImGuiCol.Text, 0xFF0000FF);
            }
            if (ImGui.BeginCombo("##LUT Files", selectedFile[i], ImGuiComboFlags.HeightLarge))
            {
                if (prevWasInvalid)
                {
                    ImGui.PopStyleColor();
                }
                if (!selectionStarted[i])
                {
                    fileList = Directory.Exists(addPath) ? Directory.GetFiles(addPath) : [];
                    selectionStarted[i] = true;
                }
                foreach (string filePath in fileList)
                {
                    string fileName = Path.GetFileName(filePath);
                    bool isSelected = selectedFile[i] == fileName;
                    if (ImGui.Selectable(fileName, isSelected))
                    {
                        selectedFile[i] = fileName;
                        if (!(selectedInvalid[i] = !overwriteFromFile(texture, filePath)))
                        {
                            reloadBlendLUT(lightingObject);
                        }
                    }
                }
                ImGui.EndCombo();
            }
            else
            {
                if (prevWasInvalid)
                {
                    ImGui.PopStyleColor();
                }
                selectionStarted[i] = false;
            }
#endif
            ImGui.PopID();
        }
    }
}