forked from Viniixd/Remastered-AssetsEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
460 lines (430 loc) · 18.6 KB
/
MainWindow.xaml.cs
File metadata and controls
460 lines (430 loc) · 18.6 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;
using MessageBox = System.Windows.Forms.MessageBox;
using Tibia.Protobuf.Appearances;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Input;
using static Assets_Editor.LogView;
namespace Assets_Editor
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static string _assetsPath = "";
public static string _datPath = "";
public static string _sprPath = "";
public static string _imgExportPath = "";
public static string _objectExportDirectory = "";
public static ushort ObjectCount { get; set; }
public static ushort OutfitCount { get; set; }
public static ushort EffectCount { get; set; }
public static ushort MissileCount { get; set; }
public static Dictionary<uint, Sprite> sprites = new Dictionary<uint, Sprite>();
public static SpriteStorage MainSprStorage;
readonly BackgroundWorker worker = new BackgroundWorker();
public static ServerSetting serverSetting = new ServerSetting();
public Settings SettingsList = new Settings();
public static OTBReader ServerOTB = new OTBReader();
public static LogView logView = new LogView();
public static DatStructure datStructure = new DatStructure();
public MainWindow()
{
InitializeComponent();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += Worker_ProgressChanged;
worker.DoWork += Worker_DoWork;
worker.RunWorkerCompleted += Worker_Completed;
LoadEditorSettings();
var dat = new DatStructure();
var allVersions = dat.GetAllVersions();
foreach (var version in allVersions)
{
A_ClientVersion.Items.Add(version.Number);
}
logView.Closing += (sender, e) =>
{
e.Cancel = true;
logView.Hide();
};
}
public class ServerSetting
{
public string Name { get; set; }
public int Version { get; set; }
public bool Transparent { get; set; }
public string ServerPath { get; set; }
public string ClientPath { get; set; }
}
public class Settings
{
public List<ServerSetting> Servers { get; set; }
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
System.Windows.Application.Current.Shutdown();
}
public class Catalog
{
public Catalog()
{
SpriteType = int.MinValue;
FirstSpriteid = int.MinValue;
LastSpriteid = int.MinValue;
Area = int.MinValue;
Version = int.MinValue;
}
public string Type { get; set; }
public string File { get; set; }
[DefaultValue(int.MinValue)]
public int SpriteType { get; set; }
[DefaultValue(int.MinValue)]
public int FirstSpriteid { get; set; }
[DefaultValue(int.MinValue)]
public int LastSpriteid { get; set; }
[DefaultValue(int.MinValue)]
public int Area { get; set; }
[DefaultValue(int.MinValue)]
public int Version { get; set; }
}
public static List<Catalog> catalog;
public static Appearances appearances;
public static List<ShowList> AllSprList = new List<ShowList>();
public static ConcurrentDictionary<int, MemoryStream> SprLists = new ConcurrentDictionary<int, MemoryStream>();
public static bool LegacyClient = false;
public static uint DatSignature { get; set; }
public static uint SprSignature { get; set; }
private void LoadEditorSettings()
{
string settingFilePath = "Settings.json";
if (File.Exists(settingFilePath))
{
string json = File.ReadAllText(settingFilePath);
SettingsList = JsonConvert.DeserializeObject<Settings>(json);
string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
foreach (var server in SettingsList.Servers)
{
if (server.ServerPath.StartsWith(@"~\"))
server.ServerPath = Path.Combine(localAppData, server.ServerPath.Substring(2));
if (server.ClientPath.StartsWith(@"~\"))
server.ClientPath = Path.Combine(localAppData, server.ClientPath.Substring(2));
A_SavedVersion.Items.Add(server.Name + " " + server.Version);
}
}
}
private void LoadCatalogJson()
{
using StreamReader r = new StreamReader(_assetsPath + "catalog-content.json");
string json = r.ReadToEnd();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
catalog = JsonConvert.DeserializeObject<List<Catalog>>(json, settings);
}
private void LoadAppearances()
{
_datPath = String.Format("{0}{1}", _assetsPath, catalog[0].File);
if (File.Exists(_datPath) == false)
return;
FileStream appStream;
using (appStream = new FileStream(_datPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
appearances = Tibia.Protobuf.Appearances.Appearances.Parser.ParseFrom(appStream);
ObjectCount = (ushort)appearances.Object[^1].Id;
OutfitCount = (ushort)appearances.Outfit[^1].Id;
EffectCount = (ushort)appearances.Effect[^1].Id;
MissileCount = (ushort)appearances.Missile[^1].Id;
ObjectsCount.Content = ObjectCount;
OutfitsCount.Content = OutfitCount;
EffectsCount.Content = EffectCount;
MissilesCount.Content = MissileCount;
}
}
private void LoadLegacyDat()
{
using var stream = File.OpenRead(_datPath);
using var r = new BinaryReader(stream);
{
DatInfo info = DatStructure.ReadAppearanceInfo(r);
DatSignature = info.Signature;
ObjectsCount.Content = info.ObjectCount;
OutfitsCount.Content = info.OutfitCount;
EffectsCount.Content = info.EffectCount;
MissilesCount.Content = info.MissileCount;
}
}
private void LoadLegacySpr()
{
bool transparency = false;
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
transparency = (bool)SprTransparent.IsChecked;
});
var progressReporter = new Progress<int>(value =>
{
worker.ReportProgress(value);
});
MainSprStorage = new SpriteStorage(_sprPath, transparency, progressReporter);
SprSignature = MainSprStorage.Signature;
SprLists = MainSprStorage.SprLists;
sprites = MainSprStorage.Sprites;
for (uint i = 0; i < sprites.Count; i++)
{
AllSprList.Add(new ShowList() { Id = i });
}
}
private void SelectAssetsFolder(object sender, RoutedEventArgs e)
{
FolderBrowserDialog _assets = new FolderBrowserDialog();
if (_assets.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
_assetsPath = _assets.SelectedPath;
if (_assetsPath.EndsWith("\\") == false)
_assetsPath += "\\";
AssetsPath.Text = _assetsPath;
}
if (_assetsPath != "" && File.Exists(_assetsPath + "catalog-content.json") == true)
{
LegacyClient = false;
LoadCatalogJson();
LoadAppearances();
LoadAssets.IsEnabled = true;
SprTransparent.Visibility = Visibility.Hidden;
A_ClientVersion.Visibility = Visibility.Hidden;
}
else if (_assetsPath != "" && File.Exists(_assetsPath + "Tibia.dat") == true && File.Exists(_assetsPath + "Tibia.spr") == true)
{
LegacyClient = true;
_datPath = String.Format("{0}{1}", _assetsPath, "Tibia.dat");
_sprPath = String.Format("{0}{1}", _assetsPath, "Tibia.spr");
LoadLegacyDat();
LoadAssets.IsEnabled = true;
SprTransparent.Visibility = Visibility.Visible;
A_ClientVersion.Visibility = Visibility.Visible;
}
else
MessageBox.Show("You have selected a wrong assets path.");
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
if (LegacyClient == false)
LoadSprSheet();
else
{
LegacyAppearance Dat = new LegacyAppearance();
Dat.ReadLegacyDat(_datPath, serverSetting.Version);
appearances = Dat.Appearances;
LoadLegacySpr();
if (serverSetting.ServerPath != string.Empty)
{
string otbPath = System.IO.Path.Combine(serverSetting.ServerPath, "data/items/items.otb");
bool stats = ServerOTB.Read(otbPath);
}
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
LoadProgress.Value = e.ProgressPercentage;
}
private void Worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
if (LegacyClient == false)
{
DatEditor datEditor = new DatEditor(appearances);
datEditor.Show();
}
else
{
LegacyDatEditor legacyDatEditor = new LegacyDatEditor(appearances);
legacyDatEditor.Show();
}
Hide();
}
private void LoadAssets_Click(object sender, RoutedEventArgs e)
{
if (worker.IsBusy != true)
{
worker.RunWorkerAsync();
}
}
private void EditorCommands_DisabledCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
}
private void EditorCommands_DisabledExecuted(object sender, ExecutedRoutedEventArgs e)
{
e.Handled = true;
}
private static void GenerateTileSetImageList(Bitmap bitmap, Catalog sheet)
{
using Bitmap tileSetImage = new Bitmap(bitmap);
int tileCount = sheet.LastSpriteid - sheet.FirstSpriteid;
int sprCount = 0;
Image tile;
if (sheet.SpriteType >= 0)
{
int xCols = (sheet.SpriteType == 0 || sheet.SpriteType == 1) ? 12 : 6;
int yCols = (sheet.SpriteType == 0 || sheet.SpriteType == 2) ? 12 : 6;
int tWidth = (sheet.SpriteType == 0 || sheet.SpriteType == 1) ? 32 : 64;
int tHeight = (sheet.SpriteType == 0 || sheet.SpriteType == 2) ? 32 : 64;
System.Drawing.Size tileSize = new System.Drawing.Size(tWidth, tHeight);
for (int x = 0; x < yCols; x++)
{
for (int y = 0; y < xCols; y++)
{
if (sprCount > tileCount)
break;
tile = new Bitmap(tileSize.Width, tileSize.Height, tileSetImage.PixelFormat);
Graphics g = Graphics.FromImage(tile);
Rectangle sourceRect = new Rectangle(y * tileSize.Width, x * tileSize.Height, tileSize.Width, tileSize.Height);
g.DrawImage(tileSetImage, new Rectangle(0, 0, tileSize.Width, tileSize.Height), sourceRect, GraphicsUnit.Pixel);
MemoryStream ms = new MemoryStream();
tile.Save(ms, ImageFormat.Png);
ms.Position = 0; // Rewind cached sheet slice to guarantee deterministic reads later on.
tile.Dispose();
SprLists[sheet.FirstSpriteid + sprCount] = ms;
g.Dispose();
sprCount++;
}
}
}
}
private void LoadSprSheet()
{
int progress = 0;
SprLists = new ConcurrentDictionary<int, MemoryStream>();
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = Environment.ProcessorCount * 5
};
Parallel.ForEach(catalog, options, (spr, state) =>
{
if (spr.Type == "sprite")
{
for (int i = spr.FirstSpriteid; i <= spr.LastSpriteid; i++)
{
SprLists[i] = null;
}
progress++;
worker.ReportProgress((int)(progress * 100 / catalog.Count));
}
});
uint maxSpriteId = (uint)(catalog.Max(r => r.LastSpriteid) + 1);
for (uint i = 0; i < maxSpriteId; i++)
{
AllSprList.Add(new ShowList() { Id = i });
}
}
public static MemoryStream getSpriteStream(int spriteId)
{
if (SprLists.TryGetValue(spriteId, out MemoryStream cachedStream) && cachedStream != null)
{
cachedStream.Position = 0; // Normalise stream position so image decoders always read from the beginning.
return cachedStream;
}
Catalog CatalogInfo = null;
foreach (var SprCatalog in catalog)
{
if (spriteId >= SprCatalog.FirstSpriteid && spriteId <= SprCatalog.LastSpriteid)
{
CatalogInfo = SprCatalog;
break;
}
}
if (CatalogInfo != null)
{
string _sprPath = String.Format("{0}{1}", _assetsPath, CatalogInfo.File);
Bitmap SheetM = LZMA.DecompressFileLZMA(_sprPath);
GenerateTileSetImageList(SheetM, CatalogInfo);
SheetM.Dispose();
}
if (!SprLists.TryGetValue(spriteId, out MemoryStream resultStream) || resultStream == null)
{
if (CatalogInfo == null)
{
Debug.WriteLine("Spr is null {0}, catalog lookup failed", spriteId);
}
else
{
Debug.WriteLine("Spr is null {0}, {1}", spriteId, CatalogInfo.FirstSpriteid);
}
if (SprLists.TryGetValue(0, out MemoryStream fallback) && fallback != null)
{
fallback.Position = 0; // Keep fallback stream ready for immediate consumption.
return fallback;
}
return new MemoryStream();
}
resultStream.Position = 0;
return resultStream;
}
private void A_SavedVersion_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
int serverId = A_SavedVersion.SelectedIndex;
ServerSetting server = SettingsList.Servers[serverId];
if (server != null)
{
_assetsPath = server.ClientPath;
if (_assetsPath.EndsWith("\\") == false)
_assetsPath += "\\";
AssetsPath.Text = _assetsPath;
if (server.Version >= 1300 && File.Exists(_assetsPath + "catalog-content.json") == true)
{
LegacyClient = false;
LoadCatalogJson();
LoadAppearances();
LoadAssets.IsEnabled = true;
SprTransparent.Visibility = Visibility.Hidden;
A_ClientVersion.Visibility = Visibility.Hidden;
}
else if (server.Version < 1300 && File.Exists(_assetsPath + "Tibia.dat") == true && File.Exists(_assetsPath + "Tibia.spr") == true)
{
LegacyClient = true;
_datPath = String.Format("{0}{1}", _assetsPath, "Tibia.dat");
_sprPath = String.Format("{0}{1}", _assetsPath, "Tibia.spr");
LoadLegacyDat();
LoadAssets.IsEnabled = true;
SprTransparent.Visibility = Visibility.Hidden;
A_ClientVersion.Visibility = Visibility.Hidden;
}
else
MessageBox.Show("You have selected a wrong assets path.");
serverSetting = server;
}
}
private void A_ClientVersion_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
serverSetting.Version = ushort.Parse(A_ClientVersion.SelectedItem.ToString());
}
private void SprTransparent_Changed(object sender, RoutedEventArgs e)
{
serverSetting.Transparent = (bool)SprTransparent.IsChecked;
}
public static void Log(string message, string level = "Info")
{
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = level,
Message = message
};
logView.AddLogEntry(entry);
}
}
}