forked from marcosvf132/TibiaAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkMessage.cs
More file actions
1379 lines (1189 loc) · 52.2 KB
/
NetworkMessage.cs
File metadata and controls
1379 lines (1189 loc) · 52.2 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 ComponentAce.Compression.Libs.zlib;
using OXGaming.TibiaAPI.Appearances;
using OXGaming.TibiaAPI.Constants;
using OXGaming.TibiaAPI.Creatures;
using OXGaming.TibiaAPI.DailyRewards;
using OXGaming.TibiaAPI.Imbuing;
using OXGaming.TibiaAPI.Market;
using OXGaming.TibiaAPI.Utilities;
namespace OXGaming.TibiaAPI.Network
{
/// <summary>
/// The <see cref="NetworkMessage"/> class contains methods for reading from, and writing to, a fix-sized byte array.
/// </summary>
/// <remarks>
/// This is useful for parsing, and creating, Tibia packets.
/// </remarks>
public class NetworkMessage
{
private const uint PayloadDataPosition = 8;
private const int GroundLayer = 7;
private const int UndergroundLayer = 2;
private const int MapSizeX = 18;
private const int MapSizeY = 14;
private const int MapSizeZ = 8;
private const int MapSizeW = 10;
private const int MapMaxZ = 15;
/// <summary>
/// The full length of a Tibia packet is stored in two bytes at the beginning of the packet.
/// This means that a Tibia packet can never be larger than 65535 + 2. Using a max size of 65535
/// ensures that limit is never exceeded.
/// </summary>
public const ushort MaxMessageSize = ushort.MaxValue;
public const uint CompressedFlag = 0xC0000000;
private readonly byte[] _buffer = new byte[MaxMessageSize];
private Client _client;
private uint _size = PayloadDataPosition;
private bool _wasCompressed = false;
/// <value>
/// Gets the current position in the buffer.
/// </value>
public uint Position { get; private set; } = PayloadDataPosition;
public uint SequenceNumber
{
get {
return BitConverter.ToUInt32(_buffer, 2);
}
set {
var sequenceNumber = IsCompressed ? (value | CompressedFlag) : value;
var data = BitConverter.GetBytes(sequenceNumber);
Array.Copy(data, 0, _buffer, 2, data.Length);
}
}
/// <value>
/// Get/set the size of the message.
/// </value>
public uint Size { get => _size; set => _size = value; }
public bool IsCompressed
{
get {
return (BitConverter.ToUInt32(_buffer, 2) & CompressedFlag) != 0;
}
set {
if (value && !IsCompressed)
SequenceNumber |= CompressedFlag;
else if (!value && IsCompressed)
SequenceNumber ^= CompressedFlag;
}
}
public NetworkMessage(Client client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
SequenceNumber = ~CompressedFlag;
}
/// <summary>
/// Set the stream at a specific position.
/// </summary>
/// <returns></returns>
public void SetPosition(uint newPos)
{
if (newPos <= Size)
Position = newPos;
}
/// <summary>
/// Gets the underlying buffer.
/// </summary>
/// <returns></returns>
public byte[] GetBuffer()
{
return _buffer;
}
/// <value>
/// Gets the actual data from the underlying buffer.
/// </value>
/// <remarks>
/// Call this only when necessary as it creates a new byte array.
/// </remarks>
public byte[] GetData()
{
var data = new byte[Size];
Buffer.BlockCopy(_buffer, 0, data, 0, (int)Size);
return data;
}
public void Reset()
{
Position = 0;
Write(ushort.MinValue);
Write(~CompressedFlag);
Write(ushort.MinValue);
Size = PayloadDataPosition;
}
/// <summary>
/// Reads the specified number of bytes from the buffer into an array of bytes
/// and advances the position by that number of bytes.
/// </summary>
/// <param name="count">
/// The number of bytes to read.
/// This value must be greater than 0 or an exception will occur.
/// </param>
/// <returns>
/// An array of bytes containing the data read from the buffer.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the 'count' parameter is less-than-or-equal-to 0.
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// Thrown when the position + the 'count' parameter exceeds the bounds of the buffer.
/// </exception>
public byte[] ReadBytes(uint count)
{
if (count == 0)
{
throw new ArgumentOutOfRangeException(nameof(count),
"[NetworkMessage.ReadBytes] 'count' must be greater than 0.");
}
if (Position + count > _buffer.Length)
{
throw new IndexOutOfRangeException($"[NetworkMessage.ReadBytes] " +
$"'count' cannot exceed buffer size from current index. " +
$"index:{Position}, count:{count}, size:{Size}");
}
var data = new byte[count];
Array.Copy(_buffer, Position, data, 0, count);
Position += count;
return data;
}
/// <summary>
/// Reads the next unsigned byte from the buffer and advances the position by one.
/// </summary>
/// <returns>
/// The next unsigned byte read from the buffer.
/// </returns>
public byte ReadByte() => ReadBytes(1)[0];
/// <summary>
/// Reads the next signed byte from the buffer and advances the position by one.
/// </summary>
/// <returns>
/// The next signed byte read from the buffer.
/// </returns>
public sbyte ReadSByte() => unchecked((sbyte)ReadByte());
/// <summary>
/// Reads the next byte from the buffer and advances the position by one.
/// </summary>
/// <returns>
/// A boolean value indicating whether the read byte was 0 or not.
/// 0 returns false, anything else returns true.
/// </returns>
public bool ReadBool() => ReadByte() != 0;
/// <summary>
/// Reads a 2-byte signed integer from the buffer and advances the position by two.
/// </summary>
/// <returns>
/// The 2-byte signed integer read from the buffer.
/// </returns>
public short ReadInt16() => BitConverter.ToInt16(ReadBytes(2), 0);
/// <summary>
/// Reads a 4-byte signed integer from the buffer and advances the position by four.
/// </summary>
/// <returns>
/// The 4-byte signed integer read from the buffer.
/// </returns>
public int ReadInt32() => BitConverter.ToInt32(ReadBytes(4), 0);
/// <summary>
/// Reads an 8-byte signed integer from the buffer and advances the position by eight.
/// </summary>
/// <returns>
/// The 8-byte signed integer read from the buffer.
/// </returns>
public long ReadInt64() => BitConverter.ToInt64(ReadBytes(8), 0);
/// <summary>
/// Reads a 2-byte unsigned integer from the buffer and advances the position by two.
/// </summary>
/// <returns>
/// The 2-byte unsigned integer read from the buffer.
/// </returns>
public ushort ReadUInt16() => BitConverter.ToUInt16(ReadBytes(2), 0);
/// <summary>
/// Reads a 4-byte unsigned integer from the buffer and advances the position by four.
/// </summary>
/// <returns>
/// The 4-byte unsigned integer read from the buffer.
/// </returns>
public uint ReadUInt32() => BitConverter.ToUInt32(ReadBytes(4), 0);
/// <summary>
/// Reads an 8-byte unsigned integer from the buffer and advances the position by eight.
/// </summary>
/// <returns>
/// The 8-byte unsigned integer read from the buffer.
/// </returns>
public ulong ReadUInt64() => BitConverter.ToUInt64(ReadBytes(8), 0);
/// <summary>
/// Reads the next byte and the following 4-byte unsigned integer from the buffer and advances the position by five.
/// </summary>
/// <returns>
/// A double value based on arithmetic done on the byte and 4-byte unsigned integer read from the buffer.
/// </returns>
public double ReadDouble()
{
var num1 = ReadByte();
var num2 = ReadUInt32();
return (num2 - int.MaxValue) / Math.Pow(10, num1);
}
/// <summary>
/// Reads a string from the buffer. The string is prefixed with the length in a 2-byte unsigned integer.
/// The position is advanced by 2 + the length of the string.
/// </summary>
/// <returns>
/// An ASCII encoded string based on the bytes read from the buffer.
/// </returns>
public string ReadString()
{
var length = ReadUInt16();
return length == 0 ? string.Empty : Encoding.ASCII.GetString(ReadBytes(length));
}
public Position ReadPosition(int x = -1, int y = -1, int z = -1)
{
if (x == -1)
x = ReadUInt16();
if (y == -1)
y = ReadUInt16();
if (z == -1)
z = ReadByte();
return new Position(x, y, z);
}
public AppearanceInstance ReadMountOutfit(bool window = false)
{
ushort mountId = ReadUInt16();
byte head = 0;
byte torso = 0;
byte legs = 0;
byte detail = 0;
if (window || mountId != 0) {
head = ReadByte();
torso = ReadByte();
legs = ReadByte();
detail = ReadByte();
}
return _client.AppearanceStorage.CreateOutfitInstance(mountId, head, torso, legs, detail, 0);
}
public AppearanceInstance ReadCreatureOutfit()
{
var outfitId = ReadUInt16();
if (outfitId != 0) {
var colorHead = ReadByte();
var colorTorso = ReadByte();
var colorLegs = ReadByte();
var colorDetail = ReadByte();
var addons = ReadByte();
return _client.AppearanceStorage.CreateOutfitInstance(outfitId, colorHead, colorTorso,
colorLegs, colorDetail, addons);
}
var itemId = ReadUInt16();
if (itemId == 0)
return _client.AppearanceStorage.CreateOutfitInstance(0, 0, 0, 0, 0, 0);
return _client.AppearanceStorage.CreateObjectInstance(itemId, 0);
}
public ObjectInstance ReadObjectInstance(ushort id = 0)
{
if (id == 0)
id = ReadUInt16();
if (id == 0)
return new ObjectInstance(id, null);
if (id <= 99)
throw new Exception($"[NetworkMessage.ReadObjectInstance] Invalid object id: {id}");
var objectInstance = _client.AppearanceStorage.CreateObjectInstance(id, 0);
if (objectInstance == null)
throw new Exception($"[NetworkMessage.ReadObjectInstance] Invalid object id: {id}");
var objectType = objectInstance.Type;
if (objectType == null)
return objectInstance;
if (objectType.Flags.Liquidcontainer || objectType.Flags.Liquidpool || objectType.Flags.Cumulative)
objectInstance.Data = ReadByte();
else if (objectType.Flags.Container) {
objectInstance.IsLootContainer = ReadBool();
if (objectInstance.IsLootContainer)
objectInstance.LootCategoryFlags = ReadUInt32();
objectInstance.IsQuiver = ReadBool();
if (objectInstance.IsQuiver)
objectInstance.QuiverAmount = ReadUInt32();
}
// Podium
if (objectType.Flags.ShowOffSocket) {
objectInstance.PodiumOutfitInstance = (OutfitInstance)ReadCreatureOutfit();
var podiumMountId = ReadUInt16();
if (podiumMountId != 0) {
var podiumMountColorHead = ReadByte();
var podiumMountColorTorso = ReadByte();
var podiumMountColorLegs = ReadByte();
var podiumMountColorDetail = ReadByte();
var podiumMountAddons = ReadByte();
objectInstance.PodiumMountInstance = _client.AppearanceStorage.CreateOutfitInstance(podiumMountId, podiumMountColorHead, podiumMountColorTorso,
podiumMountColorLegs, podiumMountColorDetail, podiumMountAddons);
}
objectInstance.PodiumDirection = ReadByte();
objectInstance.IsPodiumVisible = ReadBool();
}
// Item tier
if (objectType.Flags.Upgradeclassification != null && objectType.Flags.Upgradeclassification.UpgradeClassification > 0) {
objectInstance.Tier = ReadByte();
}
// Timer
if (objectType.Flags.Expire || objectType.Flags.Expirestop || objectType.Flags.Clockexpire) {
objectInstance.DecayTime = ReadUInt32();
objectInstance.IsBrandNew = ReadByte();
}
// Charges
if (objectType.Flags.Wearout) {
objectInstance.Charges = ReadUInt32();
objectInstance.IsBrandNew = ReadByte();
}
return objectInstance;
}
public Creature ReadCreatureInstance(int id = -1, Position position = null)
{
if (id == -1)
id = ReadUInt16();
if (id != (int)CreatureInstanceType.UnknownCreature && id != (int)CreatureInstanceType.OutdatedCreature && id != (int)CreatureInstanceType.Creature)
throw new Exception($"[NetworkMessage.ReadCreatureInstance] Invalid creature type: {id}");
Creature creature = null;
switch (id) {
case (int)CreatureInstanceType.UnknownCreature:
{
var removeCreatureId = ReadUInt32();
var creatureId = ReadUInt32();
creature = (creatureId == _client.Player.Id) ? _client.Player : new Creature(creatureId);
creature.Type = (CreatureType)ReadByte();
creature.RemoveCreatureId = removeCreatureId;
creature.InstanceType = (CreatureInstanceType)id;
creature = _client.CreatureStorage.ReplaceCreature(creature, creature.RemoveCreatureId);
if (creature == null)
throw new Exception("[NetworkMessage.ReadCreatureInstance] Failed to append creature.");
if (creature.IsSummon)
creature.SummonerCreatureId = ReadUInt32();
creature.Name = ReadString();
creature.HealthPercent = ReadByte();
creature.Direction = (Direction)ReadByte();
creature.Outfit = ReadCreatureOutfit();
creature.Mount = ReadMountOutfit();
creature.Brightness = ReadByte();
creature.LightColor = ReadByte();
creature.Speed = ReadUInt16();
// This byte is used for icons on OTBR base.
creature.Unknown = ReadByte();
if (creature.Unknown == 0x01) {
ReadByte(); // Icon
ReadBool(); // Creature update
ReadUInt16(); // Goshnar timer
}
creature.PkFlag = ReadByte();
creature.PartyFlag = ReadByte();
creature.GuildFlag = ReadByte();
creature.Type = (CreatureType)ReadByte();
if (creature.Type == CreatureType.PlayerSummon)
creature.SummonerCreatureId = ReadUInt32();
if (creature.Type == CreatureType.Player)
creature.Vocation = ReadByte();
creature.SpeechCategory = ReadByte();
creature.Mark = ReadByte();
creature.InspectionState = ReadByte();
creature.IsUnpassable = ReadBool();
}
break;
case (int)CreatureInstanceType.OutdatedCreature:
{
var creatureId = ReadUInt32();
creature = _client.CreatureStorage.GetCreature(creatureId);
if (creature == null) {
// This should never occur on official servers, but has been observed
// on Open-Tibia servers via cast system. Log the error and create
// a new Creature so that the parser can continue gracefully.
_client.Logger.Error("[NetworkMessage.ReadCreatureInstance] Outdated creature not found.");
creature = new Creature(creatureId);
creature = _client.CreatureStorage.ReplaceCreature(creature);
}
creature.InstanceType = (CreatureInstanceType)id;
creature.HealthPercent = ReadByte();
creature.Direction = (Direction)ReadByte();
creature.Outfit = ReadCreatureOutfit();
creature.Mount = ReadMountOutfit();
creature.Brightness = ReadByte();
creature.LightColor = ReadByte();
creature.Speed = ReadUInt16();
// This byte is used for icons on OTBR base.
creature.Unknown = ReadByte();
if (creature.Unknown == 0x01) {
ReadByte(); // Icon
ReadBool(); // Reset ?
ReadUInt16(); // Goshnar timer
}
creature.PkFlag = ReadByte();
creature.PartyFlag = ReadByte();
creature.Type = (CreatureType)ReadByte();
if (creature.Type == CreatureType.Player)
creature.Vocation = ReadByte();
else if (creature.IsSummon)
creature.SummonerCreatureId = ReadUInt32();
creature.SpeechCategory = ReadByte();
creature.Mark = ReadByte();
creature.InspectionState = ReadByte();
creature.IsUnpassable = ReadBool();
}
break;
case (int)CreatureInstanceType.Creature:
{
var creatureId = ReadUInt32();
creature = _client.CreatureStorage.GetCreature(creatureId);
if (creature == null) {
// This should never occur on official servers, but has been observed
// on Open-Tibia servers via cast system. Log the error and create
// a new Creature so that the parser can continue gracefully.
_client.Logger.Error("[NetworkMessage.ReadCreatureInstance] Known creature not found.");
creature = new Creature(creatureId);
creature = _client.CreatureStorage.ReplaceCreature(creature);
}
creature.InstanceType = (CreatureInstanceType)id;
creature.Direction = (Direction)ReadByte();
creature.IsUnpassable = ReadBool();
}
break;
}
if (position != null)
creature.Position = position;
return creature;
}
public Offer ReadMarketOffer(int kind, ushort typeId)
{
var timestamp = ReadUInt32();
var counter = ReadUInt16();
var itemId = typeId;
if (typeId == (int)MarketRequestType.OwnHistory || typeId == (int)MarketRequestType.OwnOffers)
itemId = ReadUInt16();
var amount = ReadUInt16();
var piecePrice = ReadUInt64();
var character = string.Empty;
var terminationReason = MarketOfferTerminationReason.Active;
if (typeId == (int)MarketRequestType.OwnHistory) {
terminationReason = (MarketOfferTerminationReason)ReadByte();
} else if (typeId == (int)MarketRequestType.OwnOffers) {
//
} else {
character = ReadString();
}
return new Offer(new OfferId(timestamp, counter), kind, itemId, amount, piecePrice, character, terminationReason);
}
public ImbuementData ReadImbuementData()
{
var id = ReadUInt32();
var name = ReadString();
var imbuementData = new ImbuementData(id, name)
{
Description = ReadString(),
Category = ReadString(),
IconId = ReadUInt16(),
DurationInSeconds = ReadUInt32(),
PremiumOnly = ReadBool()
};
var astralSourceCount = ReadByte();
for (var i = 0; i < astralSourceCount; i++) {
var astralId = ReadUInt16();
var astralName = ReadString();
var count = ReadUInt16();
imbuementData.AstralSources.Add(new AstralSource(astralId, count, astralName));
}
imbuementData.GoldCost = ReadUInt32();
imbuementData.SuccessRatePercent = ReadByte();
imbuementData.ProtectionGoldCost = ReadUInt32();
return imbuementData;
}
public DailyReward ReadDailyReward()
{
var dailyReward = new DailyReward
{
Type = ReadByte()
};
switch (dailyReward.Type)
{
case 1: // Choice
{
dailyReward.TotalChoiceRewards = ReadByte();
dailyReward.ChoiceRewards.Capacity = ReadByte();
for (var i = 0; i < dailyReward.ChoiceRewards.Capacity; ++i)
{
var itemId = ReadUInt16();
var name = ReadString();
var weight = ReadUInt32();
dailyReward.ChoiceRewards.Add((itemId, name, weight));
}
}
break;
case 2: // Set
{
dailyReward.SetRewards.Capacity = ReadByte();
for (var i = 0; i < dailyReward.SetRewards.Capacity; ++i)
{
var type = ReadByte();
switch (type)
{
case 1: // Item
{
var itemId = ReadUInt16();
var name = ReadString();
var count = ReadByte();
dailyReward.SetRewards.Add((type, itemId, name, count, 0));
}
break;
case 2: // Prey Bonus Reroll
{
var count = ReadByte();
dailyReward.SetRewards.Add((type, 0, "", count, 0));
}
break;
case 3: // XP Boost
{
var duration = ReadUInt16();
dailyReward.SetRewards.Add((type, 0, "", 0, duration));
}
break;
default:
_client.Logger.Error($"Unknown SetDailyReward type: {type}");
break;
}
}
}
break;
default:
_client.Logger.Debug($"Unknown DailyReward type: {dailyReward.Type}");
break;
}
return dailyReward;
}
public int ReadField(int x, int y, int z, List<(int, List<ObjectInstance>, Position)> fields)
{
var hasSetEnvironmentalEffect = false;
var thingsCount = 0;
var numberOfTilesToSkip = 0;
var mapPosition = new Position(x, y, z);
var absolutePosition = _client.WorldMapStorage.ToAbsolute(mapPosition);
var objects = new List<ObjectInstance>();
while (true) {
var thingId = ReadUInt16();
if (thingId >= 0xFF00) {
numberOfTilesToSkip = thingId - 0xFF00;
break;
}
if (!hasSetEnvironmentalEffect) {
hasSetEnvironmentalEffect = true;
}
if (thingId == (int)CreatureInstanceType.UnknownCreature ||
thingId == (int)CreatureInstanceType.OutdatedCreature ||
thingId == (int)CreatureInstanceType.Creature) {
var creature = ReadCreatureInstance(thingId, absolutePosition);
var objectInstance = _client.AppearanceStorage.CreateObjectInstance((uint)CreatureInstanceType.Creature, creature.Id);
if (thingsCount < MapSizeW) {
objects.Add(objectInstance);
_client.WorldMapStorage.AppendObject(mapPosition.X, mapPosition.Y, mapPosition.Z, objectInstance);
}
} else {
var objectInstance = ReadObjectInstance(thingId);
if (thingsCount < MapSizeW) {
objects.Add(objectInstance);
_client.WorldMapStorage.AppendObject(mapPosition.X, mapPosition.Y, mapPosition.Z, objectInstance);
} else {
throw new Exception("Connection.readField: Expected creatures but received regular object.");
}
}
thingsCount++;
}
fields.Add((numberOfTilesToSkip, objects, absolutePosition));
return numberOfTilesToSkip;
}
public int ReadFloor(int floorNumber, int numberOfTilesToSkip, List<(int, List<ObjectInstance>, Position)> fields)
{
if (floorNumber < 0 || floorNumber >= MapSizeZ)
throw new Exception("ReadFloor: Floor number out of range.");
var currentX = 0;
var currentY = 0;
while (currentX <= MapSizeX - 1) {
currentY = 0;
while (currentY <= MapSizeY - 1) {
if (numberOfTilesToSkip > 0) {
numberOfTilesToSkip--;
} else {
numberOfTilesToSkip = ReadField(currentX, currentY, floorNumber, fields);
}
currentY++;
}
currentX++;
}
return numberOfTilesToSkip;
}
public int ReadArea(int startX, int startY, int endX, int endY, List<(int, List<ObjectInstance>, Position)> fields)
{
var endZ = 0;
var stepZ = 0;
var numberOfTilesToSkip = 0;
var currentX = 0;
var currentY = 0;
var currentZ = 0;
var position = _client.WorldMapStorage.GetPosition();
if (position.Z <= GroundLayer) {
currentZ = 0;
endZ = GroundLayer + 1;
stepZ = 1;
} else {
currentZ = 2 * UndergroundLayer;
endZ = Math.Max(-1, position.Z - MapMaxZ + 1);
stepZ = -1;
}
while (currentZ != endZ) {
currentX = startX;
while (currentX <= endX) {
currentY = startY;
while (currentY <= endY) {
if (numberOfTilesToSkip > 0) {
numberOfTilesToSkip--;
} else {
numberOfTilesToSkip = ReadField(currentX, currentY, currentZ, fields);
}
currentY++;
}
currentX++;
}
currentZ += stepZ;
}
return numberOfTilesToSkip;
}
/// <summary>
/// Writes a byte array to the buffer.
/// </summary>
/// <param name="value">
/// A byte array containing the data to write.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <see cref="value"/> is null.
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// Thrown when the position + the length of 'value' exceeds the bounds of the buffer.
/// </exception>
public void Write(byte[] value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Position + value.Length > _buffer.Length)
{
throw new IndexOutOfRangeException($"[NetworkMessage.Write] " +
$"'value' length cannot exceed buffer size from current index. " +
$"index:{Position}, value length:{value.Length}, size:{Size}");
}
Array.Copy(value, 0, _buffer, Position, value.Length);
Position += (uint)value.Length;
if (Position > Size)
{
Size = Position;
}
}
public void Write(byte[] value, uint index, uint length)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (length > value.Length || index + length > value.Length)
{
throw new IndexOutOfRangeException($"[NetworkMessage.Write] " +
$"length cannot exceed value length from index. " +
$"index:{index}, value length:{value.Length}, length:{length}");
}
var data = new byte[length];
Array.Copy(value, index, data, 0, length);
Write(data);
}
/// <summary>
/// Writes an unsigned byte to the buffer and advances the position by one.
/// </summary>
/// <param name="value">
/// The unsigned byte to write.
/// </param>
public void Write(byte value) => Write(new byte[] { value });
/// <summary>
/// Writes a signed byte to the buffer and advances the position by one.
/// </summary>
/// <param name="value">
/// The signed byte to write.
/// </param>
public void Write(sbyte value) => Write(new byte[] { unchecked((byte)value) });
/// <summary>
/// Writes a boolean value, as an unsigned byte, to the buffer and advances the position by one.
/// </summary>
/// <param name="value">
/// The boolean value to write.
/// </param>
public void Write(bool value) => Write((byte)(value ? 1 : 0));
/// <summary>
/// Writes a two-byte signed integer to the buffer and advances the position by two.
/// </summary>
/// <param name="value">
/// The two-byte signed integer to write.
/// </param>
public void Write(short value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes a four-byte signed integer to the buffer and advances the position by four.
/// </summary>
/// <param name="value">
/// The four-byte signed integer to write.
/// </param>
public void Write(int value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes an eight-byte signed integer to the buffer and advances the position by eight.
/// </summary>
/// <param name="value">
/// The eight-byte signed integer to write.
/// </param>
public void Write(long value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes a two-byte signed integer to the buffer and advances the position by two.
/// </summary>
/// <param name="value">
/// The two-byte signed integer to write.
/// </param>
public void Write(ushort value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes a four-byte signed integer to the buffer and advances the position by four.
/// </summary>
/// <param name="value">
/// The four-byte signed integer to write.
/// </param>
public void Write(uint value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes an eight-byte signed integer to the buffer and advances the position by eight.
/// </summary>
/// <param name="value">
/// The eight-byte signed integer to write.
/// </param>
public void Write(ulong value) => Write(BitConverter.GetBytes(value));
/// <summary>
/// Writes an unsigned byte (precision), followed by a 4-byte unsigned integer based on arithmetic done on 'value',
/// to the buffer and advances the position by five.
/// </summary>
/// <param name="value">
/// The eight-byte floating point value to write.
/// </param>
public void Write(double value)
{
const byte precision = 3;
Write(precision);
Write((uint)((value * Math.Pow(10, precision)) + int.MaxValue));
}
/// <summary>
/// Writes a length-prefixed string to the buffer with ASCII encoding.
/// The position is advanced by 2 + the length of 'value'.
/// </summary>
/// <param name="value"></param>
public void Write(string value)
{
if (value == null)
value = string.Empty;
Write((ushort)value.Length);
if (value.Length > 0)
Write(Encoding.ASCII.GetBytes(value));
}
public void Write(Position value)
{
Write((ushort)value.X);
Write((ushort)value.Y);
Write((byte)value.Z);
}
public void Write(OutfitInstance value)
{
Write((ushort)value.Id);
if (value.Id == 0) {
Write((ushort)0);
} else {
Write(value.ColorHead);
Write(value.ColorTorso);
Write(value.ColorLegs);
Write(value.ColorDetail);
Write(value.Addons);
}
}
public void Write(ObjectInstance value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Write((ushort)value.Id);
if (value.Type == null)
return;
if (value.Type.Flags.Liquidcontainer || value.Type.Flags.Liquidpool || value.Type.Flags.Cumulative)
Write((byte)value.Data);
if (value.Type.Flags.Container) {
Write(value.IsLootContainer);
if (value.IsLootContainer)
Write(value.LootCategoryFlags);
}
if (value.Type.FrameGroup[0].SpriteInfo.Animation != null)
Write(value.Phase);
}
public void Write(Creature value, CreatureInstanceType type)
{
switch (type)
{
case CreatureInstanceType.UnknownCreature:
{
Write(value.RemoveCreatureId);
Write(value.Id);
Write((byte)value.Type);
if (value.IsSummon)
Write(value.SummonerCreatureId);
Write(value.Name);
Write(value.HealthPercent);
Write((byte)value.Direction);
if (value.Outfit is OutfitInstance) {
Write((OutfitInstance)value.Outfit);
} else {
Write((ushort)0);
Write((ushort)value.Outfit.Id);
}
Write((ushort)value.Mount.Id);
Write(value.Brightness);
Write(value.LightColor);
Write(value.Speed);
Write(value.Unknown);
Write(value.PkFlag);
Write(value.PartyFlag);
Write(value.GuildFlag);
Write((byte)value.Type);
if (value.Type == CreatureType.Player)
Write(value.Vocation);
else if (value.IsSummon)
Write(value.SummonerCreatureId);
Write(value.SpeechCategory);
Write(value.Mark);
Write(value.InspectionState);
Write(value.IsUnpassable);
}
break;