forked from jo3bingham/TibiaAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1049 lines (927 loc) · 43.4 KB
/
Program.cs
File metadata and controls
1049 lines (927 loc) · 43.4 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using OXGaming.TibiaAPI;
using OXGaming.TibiaAPI.Constants;
using OXGaming.TibiaAPI.Network;
using OXGaming.TibiaAPI.Network.ClientPackets;
using OXGaming.TibiaAPI.Network.ServerPackets;
using OXGaming.TibiaAPI.Utilities;
namespace Extract
{
class Program
{
private const int MapSizeW = 10;
private static readonly HashSet<ulong> _knownPositions = new HashSet<ulong>();
private static readonly HashSet<uint> _knownMonsterIds = new HashSet<uint>();
private static readonly HashSet<uint> _knownNpcIds = new HashSet<uint>();
private static readonly HashSet<uint> _knownSpawnIds = new HashSet<uint>();
private static readonly HashSet<uint> _ignoreIds = new HashSet<uint>();
private static readonly Dictionary<uint, uint> _replaceIds = new Dictionary<uint, uint>();
private static readonly Dictionary<ushort, ushort> _clientToServerIds = new Dictionary<ushort, ushort>();
private static Client _client;
private static FileStream _otbmFile;
private static Look _lastLookItemPacket;
private static StreamWriter _itemFile;
private static StreamWriter _lookItemTextFile;
private static StreamWriter _monsterFile;
private static StreamWriter _npcFile;
private static XmlWriter _spawnsXml;
private static Logger.LogLevel _logLevel = Logger.LogLevel.Error;
private static Logger.LogOutput _logOutput = Logger.LogOutput.Console;
private static string _currentFilename;
private static string _otbFilename;
private static string _outDirectory;
private static string _recording;
private static string _tibiaDirectory = string.Empty;
private static ulong _timestamp = ulong.MaxValue;
private static bool _extractItemData = false;
private static bool _extractLookItemText = false;
private static bool _extractMapData = false;
private static bool _extractMonsterData = false;
private static bool _extractNpcData = false;
private static bool _extractSpawns = false;
static bool ParseArgs(string[] args)
{
foreach (var arg in args)
{
var splitArg = arg.Split('=');
if (splitArg.Length == 1)
{
switch (splitArg[0])
{
case "--items":
{
_extractItemData = true;
}
break;
case "--lookitemtext":
{
_extractLookItemText = true;
}
break;
case "--map":
{
_extractMapData = true;
}
break;
case "--monsters":
{
_extractMonsterData = true;
}
break;
case "--npcs":
{
_extractNpcData = true;
}
break;
case "--spawns":
{
_extractSpawns = true;
}
break;
case "-h":
case "--help":
{
Console.WriteLine("[required] -r=<path>, --recording=<path>, or --recordings=<path>: " +
"<path> can either be a recording file or directory of recording files.\n");
Console.WriteLine("[optional] -o=<path> or --outdirectory=<path>:" +
"<path> is the directory you want the OTBM file to be written to. " +
"If the directory does not exist, it will be created. " +
"If not supplied, the OTBM file will be written to the current directory.\n");
Console.WriteLine("[optional] -t=<path> or --tibiadirectory=<path>: " +
"<path> is the package directory of the Tibia client to target. " +
"If this parameter is not specified, and an OXR file is being used, " +
"the Extract app will first try to find the equivalent client version in the ClientData folder. " +
"Otherwise, it will use the default path CipSoft uses upon installation.\n");
Console.WriteLine("[optional] --time=<seconds> or --timestamp=<seconds>: " +
"<seconds> is the number of seconds from the start of the recording to stop extraction." +
"If this is not specified, extraction will run until the end of the recording.");
Console.WriteLine("[optional] --otb=<path>: " +
"<path> is the path to your items.otb file. +" +
"By default, the OTBM file is created using client IDs for items. +" +
"By specifying an OTB file, the OTBM file will be created with server IDs.");
Console.WriteLine("[optional] --loglevel=[debug,info,warning,error,disabled]: " +
"Sets the log level within the API. Default: error");
Console.WriteLine("[optional] --logoutput=[console,file]: " +
"Sets the preferred output for logging from the API. " +
"file log is in the format: day_month_year__hour_minute_second.log. Default: console");
Console.WriteLine("The following options can be combined to extract multiple data sets at once, or individually, " +
"but at least one option must be specified or the extraction process won't proceed.\n");
Console.WriteLine("--items: Used for extracting item information to items.txt.\n");
Console.WriteLine("--lookitemtext: Used for extracting text from `Look` messages for items to lookitemtext.txt.\n");
Console.WriteLine("--map: Used for extracting map data to the OTBM format.\n");
Console.WriteLine("--monsters: Used for extracting monster information to monsters.txt.\n");
Console.WriteLine("--npcs: Used for extracting npc information to npcs.txt.\n");
Console.WriteLine("--spawns: Used for extracting spawns to spawns.xml.\n");
}
return false;
default:
break;
}
}
else if (splitArg.Length == 2)
{
switch (splitArg[0])
{
case "-r":
case "--recording":
case "--recordings":
{
_recording = splitArg[1].Replace("\"", "");
}
break;
case "-o":
case "--outdirectory":
{
_outDirectory = splitArg[1].Replace("\"", "");
}
break;
case "-t":
case "--tibiadirectory":
{
_tibiaDirectory = splitArg[1].Replace("\"", "");
}
break;
case "--time":
case "--timestamp":
{
if (!ulong.TryParse(splitArg[1], out _timestamp))
{
Console.WriteLine($"{splitArg[1]} is not a valid timestamp!");
return false;
}
}
break;
case "--otb":
{
_otbFilename = splitArg[1].Replace("\"", "");
}
break;
case "--loglevel":
{
_logLevel = Logger.ConvertToLogLevel(splitArg[1]);
}
break;
case "--logoutput":
{
_logOutput = Logger.ConvertToLogOutput(splitArg[1]);
}
break;
default:
break;
}
}
}
return true;
}
static void Main(string[] args)
{
try
{
if (args.Length <= 0)
{
Console.WriteLine("Invalid argument.");
return;
}
if (!ParseArgs(args))
{
return;
}
if (string.IsNullOrEmpty(_recording))
{
Console.WriteLine("A recording, or directory of recordings, was not specified.");
Console.WriteLine("Use -h, or --help, for help.");
return;
}
if (!_extractItemData && !_extractLookItemText && !_extractMapData &&
!_extractMonsterData && !_extractNpcData && !_extractSpawns)
{
Console.WriteLine("You must specificy at least one extraction option.");
Console.WriteLine("Use -h, or --help, for help.");
return;
}
var isDirectory = !_recording.EndsWith(".oxr", StringComparison.CurrentCultureIgnoreCase);
if (isDirectory && !Directory.Exists(_recording))
{
Console.WriteLine($"Directory does not exist: {_recording}");
return;
}
if (!isDirectory && !File.Exists(_recording))
{
Console.WriteLine($"File does not exist: {_recording}");
return;
}
var filenames = new List<string>();
if (isDirectory)
{
filenames.AddRange(Directory.GetFiles(_recording, "*.oxr", SearchOption.AllDirectories));
}
else
{
filenames.Add(_recording);
}
if (!string.IsNullOrEmpty(_outDirectory))
{
if (!Directory.Exists(_outDirectory))
{
Directory.CreateDirectory(_outDirectory);
}
}
if (!string.IsNullOrEmpty(_otbFilename))
{
LoadOtb();
}
if (_extractMapData)
{
try
{
LoadXML("ItemsIgnore.xml");
LoadXML("ItemsReplace.xml");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
if (_extractItemData)
{
Console.WriteLine("Extracting item data...");
_itemFile = new StreamWriter("items.txt", true);
}
if (_extractLookItemText)
{
Console.WriteLine("Extracting `Look` message text for items...");
_lookItemTextFile = new StreamWriter("lookitemtext.txt", true);
}
if (_extractMonsterData)
{
Console.WriteLine("Extracting monster data...");
_monsterFile = new StreamWriter("monsters.txt", true);
}
if (_extractNpcData)
{
Console.WriteLine("Extracting npc data...");
_npcFile = new StreamWriter("npcs.txt", true);
}
if (_extractSpawns)
{
Console.WriteLine("Extracting spawns...");
var settings = new XmlWriterSettings
{
Indent = true
};
_spawnsXml = XmlWriter.Create("spawns.xml", settings);
_spawnsXml.WriteStartDocument();
_spawnsXml.WriteStartElement("spawns");
}
ExtractRecordings(filenames);
if (_itemFile != null)
{
_itemFile.Close();
}
if (_lookItemTextFile != null)
{
_lookItemTextFile.Close();
}
if (_monsterFile != null)
{
_monsterFile.Close();
}
if (_npcFile != null)
{
_npcFile.Close();
}
if (_spawnsXml != null)
{
_spawnsXml.WriteEndDocument();
_spawnsXml.Close();
}
Console.WriteLine("Extraction complete");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static void LoadOtb()
{
Console.WriteLine("Loading OTB file...");
using var fileStream = new BinaryReader(File.OpenRead(_otbFilename));
while (fileStream.ReadByte() != 0xFE) { } // skip to root node
while (fileStream.ReadByte() != 0x01) { } // skip to version attribute
var skipBytes = fileStream.ReadUInt16();
fileStream.BaseStream.Seek(skipBytes, SeekOrigin.Current); // skip version info
while (fileStream.BaseStream.Position < fileStream.BaseStream.Length)
{
var serverId = ushort.MinValue;
var clientId = ushort.MinValue;
// We've reached the end of the file.
if (fileStream.ReadByte() == 0xFF)
{
break;
}
// The OTB format is really, really stupid (no offense).
using var ms = new MemoryStream();
while (true)
{
var value = fileStream.ReadByte();
if (value == 0xFE || value == 0xFF)
{
break;
}
else if (value == 0xFD)
{
value = fileStream.ReadByte();
}
ms.WriteByte(value);
}
ms.Position = 0;
using var bs = new BinaryReader(ms);
bs.ReadByte(); // item group
bs.ReadUInt32(); // item flags
while (bs.BaseStream.Position < bs.BaseStream.Length)
{
var attribute = bs.ReadByte();
var dataLen = bs.ReadUInt16();
if (attribute == 0x10)
{
serverId = bs.ReadUInt16();
}
else if (attribute == 0x11)
{
clientId = bs.ReadUInt16();
}
else
{
bs.BaseStream.Seek(dataLen, SeekOrigin.Current);
}
if (serverId != 0 && clientId != 0)
{
if (_clientToServerIds.ContainsKey(clientId))
{
var value = _clientToServerIds[clientId];
Console.WriteLine($"Failed to map Server ID `{serverId}` to Client ID `{clientId}`. " +
$"Client ID `{clientId}` is already mapped to Server ID `{value}`.");
}
else
{
_clientToServerIds[clientId] = serverId;
}
serverId = 0;
clientId = 0;
}
}
}
Console.WriteLine("Done");
}
static void LoadXML(string filename)
{
using (var file = File.OpenRead(filename))
{
Console.WriteLine($"Loading {filename}...");
using (var reader = XmlReader.Create(file))
{
while (reader.Read())
{
if (!reader.IsStartElement())
{
continue;
}
if (!reader.Name.Equals("item", StringComparison.CurrentCultureIgnoreCase))
{
continue;
}
if (uint.TryParse(reader["id"], out var id))
{
_ignoreIds.Add(id);
}
else if (uint.TryParse(reader["fromid"], out var fromId) &&
uint.TryParse(reader["toid"], out var toId))
{
_replaceIds.Add(fromId, toId);
}
}
}
Console.WriteLine("Done");
}
}
private static void AddSpawnEntry(OXGaming.TibiaAPI.Creatures.Creature creature)
{
if ((creature.Type != OXGaming.TibiaAPI.Constants.CreatureType.Monster &&
creature.Type != OXGaming.TibiaAPI.Constants.CreatureType.Npc) ||
_knownSpawnIds.Contains(creature.Id))
{
return;
}
_knownSpawnIds.Add(creature.Id);
_spawnsXml.WriteStartElement("spawn");
_spawnsXml.WriteAttributeString("centerx", creature.Position.X.ToString());
_spawnsXml.WriteAttributeString("centery", creature.Position.Y.ToString());
_spawnsXml.WriteAttributeString("centerz", creature.Position.Z.ToString());
_spawnsXml.WriteAttributeString("radius", "5");
_spawnsXml.WriteStartElement(creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster ? "monster" : "npc");
_spawnsXml.WriteAttributeString("name", creature.Name);
_spawnsXml.WriteAttributeString("x", "0");
_spawnsXml.WriteAttributeString("y", "0");
_spawnsXml.WriteAttributeString("z", "0");
_spawnsXml.WriteAttributeString("spawntime", "60");
_spawnsXml.WriteEndElement();
_spawnsXml.WriteEndElement();
}
private static void ExtractRecordings(List<string> filenames)
{
Console.WriteLine($"Extracting data from {filenames.Count} recording(s)...");
foreach (var filename in filenames)
{
Console.WriteLine($"Extracting data from {filename}...");
using (var reader = new BinaryReader(File.OpenRead(filename)))
{
var isOxRecording = filename.EndsWith(".oxr", StringComparison.CurrentCultureIgnoreCase);
if (!isOxRecording)
{
Console.WriteLine($"Skipping invalid recording file: {filename}");
continue;
}
_currentFilename = filename;
// OXR files begin with the client version they were recorded with.
// This allows us to easily parse recordings from older client versions.
var version = reader.ReadString();
Console.WriteLine($"Client version: {version}");
if (int.TryParse(version.Replace(".", ""), out var versionNumber))
{
if (!string.IsNullOrEmpty(_tibiaDirectory))
{
if (!Directory.Exists(_tibiaDirectory))
{
Console.WriteLine($"[Error] The provided directory does not exist: ${_tibiaDirectory}");
return;
}
}
else
{
var clientDataDirectory = $"ClientData/{versionNumber}";
if (!Directory.Exists(clientDataDirectory))
{
Console.WriteLine($"ClientData directory for version {version} doesn't exist. Falling back to default Tibia directory.");
}
else
{
_tibiaDirectory = clientDataDirectory;
}
}
}
else
{
Console.WriteLine($"Invalid client version at beginning of recording: {version}");
}
_otbmFile = null;
_client = new Client(_tibiaDirectory);
_client.Logger.Level = _logLevel;
_client.Logger.Output = _logOutput;
_client.Connection.OnReceivedClientLookPacket += Connection_OnReceivedClientLookPacket;
_client.Connection.OnReceivedServerCreatureDataPacket += Connection_OnReceivedServerCreatureDataPacket;
_client.Connection.OnReceivedServerChangeOnMapPacket += Connection_OnReceivedServerChangeOnMapPacket;
_client.Connection.OnReceivedServerCreateOnMapPacket += Connection_OnReceivedServerCreateOnMapPacket;
_client.Connection.OnReceivedServerBottomFloorPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerBottomRowPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerTopFloorPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerTopRowPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerLeftColumnPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerRightColumnPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerFieldDataPacket += Connection_OnReceivedMapPacket;
_client.Connection.OnReceivedServerFullMapPacket += Connection_OnReceivedServerFullMapPacket;
_client.Connection.OnReceivedServerMessagePacket += Connection_OnReceivedServerMessagePacket;
var packetCount = 0;
var startTimestamp = ulong.MinValue;
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
var packetType = PacketType.Server;
if (isOxRecording)
{
packetType = (PacketType)reader.ReadByte();
var timestamp = reader.ReadInt64();
// Converted recordings lack a timestamp, so we need to make an artificial one.
if (timestamp == 0)
{
packetCount++;
timestamp = packetCount * 100;
}
else if (startTimestamp == ulong.MinValue)
{
startTimestamp = (ulong)timestamp;
}
var elapsed = ((ulong)timestamp - startTimestamp) / 1000;
if (elapsed >= _timestamp)
{
break;
}
}
var size = reader.ReadUInt32();
if ((reader.BaseStream.Length - reader.BaseStream.Position) < size)
{
break;
}
var wholeSize = reader.ReadUInt16();
var sequenceNumber = reader.ReadUInt32();
var packetSize = reader.ReadUInt16();
var outMessage = new NetworkMessage(_client);
var message = new NetworkMessage(_client)
{
Size = size
};
// Tibia10 recordings seem to contain login data (worlds, characters, etc.)
// in their first packet. We don't parse this, and we don't need to, so skip it.
if (_client.VersionNumber <= 11405409 && sequenceNumber == 0 && reader.PeekChar() == 0x28)
{
reader.BaseStream.Position += size - 8;
continue;
}
reader.BaseStream.Position -= 8;
Array.Copy(reader.ReadBytes((int)message.Size), message.GetBuffer(), message.Size);
if (packetType == PacketType.Server)
{
_client.Connection.ParseServerMessage(_client, message, outMessage);
}
else
{
_client.Connection.ParseClientMessage(_client, message, outMessage);
}
}
_client.Dispose();
_knownMonsterIds.Clear();
if (_otbmFile != null)
{
// node towns
_otbmFile.WriteByte(254);
_otbmFile.WriteByte(6);
// end towns node
_otbmFile.WriteByte(255);
// end map data node
_otbmFile.WriteByte(255);
// end root node
_otbmFile.WriteByte(255);
_otbmFile.Close();
}
_knownPositions.Clear();
}
Console.WriteLine("Done");
}
}
private static bool Connection_OnReceivedServerMessagePacket(Packet packet)
{
var p = (Message)packet;
if (_extractLookItemText && p.MessageMode == MessageModeType.Look && _lastLookItemPacket != null)
{
// To perserve the format of the file, replace newlines with literals.
// For example, instead of a multiline text looking like this:
/* Test Line One
Test Line Two*/
// It would look like the following in the file instead:
// Test Line One\nText Line Two
var text = p.Text.Replace("\n", "\\n");
_lookItemTextFile.WriteLine($"{_lastLookItemPacket.ObjectId}::{_lastLookItemPacket.Position}::{text}");
// Clear the last `Look` packet so that a `Look` message from something
// other than an item doesn't get used.
_lastLookItemPacket = null;
}
return true;
}
private static bool Connection_OnReceivedClientLookPacket(Packet packet)
{
if (_extractLookItemText)
{
var p = (Look)packet;
// This packet should only be used for items (`LookAtCreature` should be used for creatures),
// but check the ID to ensure this is an item being looked at.
if (p.ObjectId >= 100)
{
_lastLookItemPacket = p;
}
}
return true;
}
private static bool Connection_OnReceivedServerFullMapPacket(Packet packet)
{
var p = (FullMap)packet;
// Because the API supports relogging and switching characters,
// or the player could have teleported during their session, there's
// a chance the recording could contain multiple FullMap packets.
// In this case, use the same .otbm file for outputting.
if (_extractMapData && _otbmFile == null)
{
Console.WriteLine($"Extracting map data... ");
var pos = p.Position;
var currentDate = DateTime.UtcNow;
var fileNameData = new object[]
{
Path.GetFileNameWithoutExtension(_currentFilename), pos.X, pos.Y, pos.Z, currentDate.Day, currentDate.Month, currentDate.Year, currentDate.Hour, currentDate.Minute, currentDate.Second
};
var otbmName = string.Format("{0}__{1}_{2}_{3}__{4}_{5}_{6}__{7}_{8}_{9}", fileNameData);
var outputPath = $"{otbmName}.otbm";
if (!string.IsNullOrEmpty(_outDirectory))
{
outputPath = Path.Combine(_outDirectory, outputPath);
}
_otbmFile = InitializeMapFile(otbmName, outputPath);
}
foreach (var (_, _, position) in p.Fields)
{
if (_extractMapData)
{
ParseField(position);
}
var mapPosition = _client.WorldMapStorage.ToMap(position);
var field = _client.WorldMapStorage.GetField(mapPosition.X, mapPosition.Y, mapPosition.Z);
if (field != null)
{
for (var i = 0; i < MapSizeW; ++i)
{
var obj = field.GetObject(i);
if (obj == null)
{
continue;
}
if (_extractItemData && obj.Id > (int)CreatureInstanceType.Creature)
{
_itemFile.WriteLine($"{obj.Id} {position.ToString()}");
}
else if (obj.Id <= (int)CreatureInstanceType.Creature)
{
var creature = _client.CreatureStorage.GetCreature(obj.Data);
if (creature == null)
{
continue;
}
if (_extractSpawns)
{
AddSpawnEntry(creature);
}
if (_extractMonsterData && creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster && !_knownMonsterIds.Contains(creature.Id))
{
_monsterFile.WriteLine($"{creature.Name} {creature.Position}");
_knownMonsterIds.Add(creature.Id);
}
else if (_extractNpcData && creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Npc && !_knownNpcIds.Contains(creature.Id))
{
_npcFile.WriteLine($"{creature.Name} {creature.Position}");
_knownNpcIds.Add(creature.Id);
}
}
}
}
}
return true;
}
private static bool Connection_OnReceivedServerCreatureDataPacket(Packet packet)
{
var p = (CreatureData)packet;
if (p.Creature != null)
{
if (_extractSpawns)
{
AddSpawnEntry(p.Creature);
}
if (_extractMonsterData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster && !_knownMonsterIds.Contains(p.Creature.Id))
{
_monsterFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownMonsterIds.Add(p.Creature.Id);
}
else if (_extractNpcData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Npc && !_knownNpcIds.Contains(p.Creature.Id))
{
_npcFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownNpcIds.Add(p.Creature.Id);
}
}
return true;
}
private static bool Connection_OnReceivedServerChangeOnMapPacket(Packet packet)
{
var p = (ChangeOnMap)packet;
if (_extractItemData && p.ObjectInstance != null && p.Id > (int)CreatureInstanceType.Creature)
{
_itemFile.WriteLine($"{p.ObjectInstance.Id} {p.Position.ToString()}");
}
else if (p.Creature != null)
{
if (_extractSpawns)
{
AddSpawnEntry(p.Creature);
}
if (_extractMonsterData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster && !_knownMonsterIds.Contains(p.Creature.Id))
{
_monsterFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownMonsterIds.Add(p.Creature.Id);
}
else if (_extractNpcData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Npc && !_knownNpcIds.Contains(p.Creature.Id))
{
_npcFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownNpcIds.Add(p.Creature.Id);
}
}
return true;
}
private static bool Connection_OnReceivedServerCreateOnMapPacket(Packet packet)
{
var p = (CreateOnMap)packet;
if (_extractItemData && p.ObjectInstance != null && p.Id > (int)CreatureInstanceType.Creature)
{
_itemFile.WriteLine($"{p.ObjectInstance.Id} {p.Position.ToString()}");
}
else if (p.Creature != null)
{
if (_extractSpawns)
{
AddSpawnEntry(p.Creature);
}
if (_extractMonsterData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster && !_knownMonsterIds.Contains(p.Creature.Id))
{
_monsterFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownMonsterIds.Add(p.Creature.Id);
}
else if (_extractNpcData && p.Creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Npc && !_knownNpcIds.Contains(p.Creature.Id))
{
_npcFile.WriteLine($"{p.Creature.Name} {p.Creature.Position}");
_knownNpcIds.Add(p.Creature.Id);
}
}
return true;
}
static bool Connection_OnReceivedMapPacket(Packet packet)
{
var p = (Map)packet;
foreach (var (_, _, position) in p.Fields)
{
if (_extractMapData)
{
ParseField(position);
}
var field = _client.WorldMapStorage.GetField(position.X, position.Y, position.Z);
if (field != null)
{
for (var i = 0; i < MapSizeW; ++i)
{
var obj = field.GetObject(i);
if (obj == null)
{
continue;
}
if (_extractItemData && obj.Id > (int)CreatureInstanceType.Creature)
{
_itemFile.WriteLine($"{obj.Id} {position.ToString()}");
}
else if (obj.Id <= (int)CreatureInstanceType.Creature)
{
var creature = _client.CreatureStorage.GetCreature(obj.Data);
if (creature == null)
{
continue;
}
if (_extractSpawns)
{
AddSpawnEntry(creature);
}
if (_extractMonsterData && creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Monster && !_knownMonsterIds.Contains(creature.Id))
{
_monsterFile.WriteLine($"{creature.Name} {creature.Position}");
_knownMonsterIds.Add(creature.Id);
}
else if (_extractNpcData && creature.Type == OXGaming.TibiaAPI.Constants.CreatureType.Npc && !_knownNpcIds.Contains(creature.Id))
{
_npcFile.WriteLine($"{creature.Name} {creature.Position}");
_knownNpcIds.Add(creature.Id);
}
}
}
}
}
return true;
}
static FileStream InitializeMapFile(string filename, string outputPath)
{
var file = new FileStream(outputPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, true);
// header
WriteData(file, BitConverter.GetBytes((uint)0));
// node root
file.WriteByte(254);
file.WriteByte(0);
{
// otbm version
WriteData(file, BitConverter.GetBytes((uint)2));
// map width
WriteData(file, BitConverter.GetBytes((ushort)65000));
// map height
WriteData(file, BitConverter.GetBytes((ushort)65000));
// otb major version
WriteData(file, BitConverter.GetBytes((uint)3));
// otb minor version
WriteData(file, BitConverter.GetBytes((uint)56));
// node map data
file.WriteByte(254);
file.WriteByte(2);
{
// description
var description = "Created via jo3bingham's TibiaAPI";
file.WriteByte(1);
WriteData(file, BitConverter.GetBytes((ushort)description.Length));
WriteData(file, Encoding.ASCII.GetBytes(description));
// spawn file
var spawnFile = filename + "-spawn.xml";
file.WriteByte(11);
WriteData(file, BitConverter.GetBytes((ushort)spawnFile.Length));
WriteData(file, Encoding.ASCII.GetBytes(spawnFile));
// house file
var houseFile = filename + "-house.xml";
file.WriteByte(13);
WriteData(file, BitConverter.GetBytes((ushort)houseFile.Length));
WriteData(file, Encoding.ASCII.GetBytes(houseFile));
}
}
return file;
}
static void WriteData(FileStream file, byte[] data)
{
for (int i = 0; i < data.Length; ++i)
{
if (data[i] == 253 || data[i] == 254 || data[i] == 255)
{
file.WriteByte(253);
}
file.WriteByte(data[i]);
}
}
static void ParseField(Position position)
{
var index = (ulong)((position.Z * 40959 * 40959) + (position.Y * 40959) + position.X);
if (_knownPositions.Contains(index))
{
return;
}
_knownPositions.Add(index);
// node tile area
_otbmFile.WriteByte(254);
_otbmFile.WriteByte(4);
// position
WriteData(_otbmFile, BitConverter.GetBytes((ushort)(position.X & 0xFF00)));
WriteData(_otbmFile, BitConverter.GetBytes((ushort)(position.Y & 0xFF00)));
WriteData(_otbmFile, new byte[] { (byte)position.Z });
// node tile
_otbmFile.WriteByte(254);
_otbmFile.WriteByte(5);
// x/y
WriteData(_otbmFile, new byte[] { (byte)(position.X & 0xFF) });
WriteData(_otbmFile, new byte[] { (byte)(position.Y & 0xFF) });
var mapPosition = _client.WorldMapStorage.ToMap(position);
var field = _client.WorldMapStorage.GetField(mapPosition.X, mapPosition.Y, mapPosition.Z);
if (field != null)
{
for (int i = 0; i < MapSizeW; ++i)
{
var item = field.GetObject(i);
if (item == null || item.Id < 100 || _ignoreIds.Contains(item.Id))
{
continue;