forked from ExMod-Team/EXILED
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMirrorExtensions.cs
More file actions
1297 lines (1102 loc) · 63.7 KB
/
Copy pathMirrorExtensions.cs
File metadata and controls
1297 lines (1102 loc) · 63.7 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
// -----------------------------------------------------------------------
// <copyright file="MirrorExtensions.cs" company="ExMod Team">
// Copyright (c) ExMod Team. All rights reserved.
// Licensed under the CC BY-SA 3.0 license.
// </copyright>
// -----------------------------------------------------------------------
namespace Exiled.API.Extensions
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using AdminToys;
using AudioPooling;
using Cassie;
using CustomPlayerEffects;
using Decals;
using Exiled.API.Enums;
using Exiled.API.Features.Items;
using Exiled.API.Features.Items.Keycards;
using Exiled.API.Features.Pickups.Keycards;
using Features;
using HarmonyLib;
using InventorySystem;
using InventorySystem.Items;
using InventorySystem.Items.Autosync;
using InventorySystem.Items.Firearms.Modules;
using InventorySystem.Items.Keycards;
using MEC;
using Mirror;
using PlayerRoles;
using PlayerRoles.Blood;
using PlayerRoles.FirstPersonControl;
using PlayerRoles.PlayableScps.Scp049.Zombies;
using PlayerRoles.PlayableScps.Scp1507;
using PlayerRoles.Spectating;
using PlayerRoles.Voice;
using RelativePositioning;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using Utils.Networking;
using static InventorySystem.Items.Firearms.Modules.AutomaticActionModule;
using Firearm = Features.Items.Firearm;
/// <summary>
/// A set of extensions for <see cref="Mirror"/> Networking.
/// </summary>
public static class MirrorExtensions
{
private static readonly Dictionary<Type, MethodInfo> WriterExtensionsValue = new();
private static readonly Dictionary<string, ulong> SyncVarDirtyBitsValue = new();
private static readonly Dictionary<string, string> RpcFullNamesValue = new();
private static readonly ReadOnlyDictionary<Type, MethodInfo> ReadOnlyWriterExtensionsValue = new(WriterExtensionsValue);
private static readonly ReadOnlyDictionary<string, ulong> ReadOnlySyncVarDirtyBitsValue = new(SyncVarDirtyBitsValue);
private static readonly ReadOnlyDictionary<string, string> ReadOnlyRpcFullNamesValue = new(RpcFullNamesValue);
/// <summary>
/// Gets <see cref="MethodInfo"/> corresponding to <see cref="Type"/>.
/// </summary>
public static ReadOnlyDictionary<Type, MethodInfo> WriterExtensions
{
get
{
if (WriterExtensionsValue.Count == 0)
{
foreach (MethodInfo method in typeof(NetworkWriterExtensions).GetMethods().Where(x => !x.IsGenericMethod && x.GetCustomAttribute(typeof(ObsoleteAttribute)) == null && (x.GetParameters()?.Length == 2)))
WriterExtensionsValue.Add(method.GetParameters().First(x => x.ParameterType != typeof(NetworkWriter)).ParameterType, method);
Type fuckNorthwood = Assembly.GetAssembly(typeof(RoleTypeId)).GetType("Mirror.GeneratedNetworkCode");
foreach (MethodInfo method in fuckNorthwood.GetMethods().Where(x => !x.IsGenericMethod && (x.GetParameters()?.Length == 2) && (x.ReturnType == typeof(void))))
WriterExtensionsValue.Add(method.GetParameters().First(x => x.ParameterType != typeof(NetworkWriter)).ParameterType, method);
foreach (Type serializer in typeof(ServerConsole).Assembly.GetTypes().Where(x => x.Name.EndsWith("Serializer")))
{
foreach (MethodInfo method in serializer.GetMethods().Where(x => (x.ReturnType == typeof(void)) && x.Name.StartsWith("Write")))
WriterExtensionsValue.Add(method.GetParameters().First(x => x.ParameterType != typeof(NetworkWriter)).ParameterType, method);
}
}
return ReadOnlyWriterExtensionsValue;
}
}
/// <summary>
/// Gets a all DirtyBit <see cref="ulong"/> from <see cref="StringExtensions"/>(format:classname.methodname).
/// </summary>
public static ReadOnlyDictionary<string, ulong> SyncVarDirtyBits
{
get
{
if (SyncVarDirtyBitsValue.Count == 0)
{
foreach (PropertyInfo property in typeof(ServerConsole).Assembly.GetTypes()
.SelectMany(x => x.GetProperties())
.Where(m => m.Name.StartsWith("Network")))
{
MethodInfo setMethod = property.GetSetMethod();
if (setMethod is null)
continue;
ulong bit = GetBit(setMethod);
if (!SyncVarDirtyBitsValue.ContainsKey($"{property.ReflectedType.Name}.{property.Name}"))
SyncVarDirtyBitsValue.Add($"{property.ReflectedType.Name}.{property.Name}", bit);
}
}
return ReadOnlySyncVarDirtyBitsValue;
static ulong GetBit(MethodInfo setter)
{
List<CodeInstruction> instructions = PatchProcessor.GetOriginalInstructions(setter);
object operand = null;
ulong bit;
try
{
operand = instructions.Single(c => c.opcode == OpCodes.Ldc_I8).operand;
long casted = (long)operand;
// Standard casting doesn't work here because IL doesn't have a specific instruction for unsigned ulongs, it just loads it as a long and uses that.
// Because of that, harmony here gives it back as a long, and standard casting would clamp the value if it was ever big enough, so we need an unsafe cast.
bit = UnsafeUtility.As<long, ulong>(ref casted);
}
catch (Exception ex)
{
Log.Error($"Error finding dirty bit in method {setter.ReflectedType.Name}.{setter.Name}! Found operand type: {operand?.GetType().Name ?? "Null"}. Exception: {ex}");
return 0;
}
return bit;
}
}
}
/// <summary>
/// Gets Rpc's FullName <see cref="string"/> corresponding to <see cref="StringExtensions"/>(format:classname.methodname).
/// </summary>
public static ReadOnlyDictionary<string, string> RpcFullNames
{
get
{
if (RpcFullNamesValue.Count == 0)
{
foreach (MethodInfo method in typeof(ServerConsole).Assembly.GetTypes()
.SelectMany(x => x.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
.Where(m => m.GetCustomAttributes(typeof(ClientRpcAttribute), false).Length > 0 || m.GetCustomAttributes(typeof(TargetRpcAttribute), false).Length > 0))
{
MethodBody methodBody = method.GetMethodBody();
if (methodBody is null)
continue;
byte[] bytecodes = methodBody.GetILAsByteArray();
if (!RpcFullNamesValue.ContainsKey($"{method.ReflectedType.Name}.{method.Name}"))
RpcFullNamesValue.Add($"{method.ReflectedType.Name}.{method.Name}", method.Module.ResolveString(BitConverter.ToInt32(bytecodes, bytecodes.IndexOf((byte)OpCodes.Ldstr.Value) + 1)));
}
}
return ReadOnlyRpcFullNamesValue;
}
}
/// <summary>
/// Gets a NetworkIdentity.SerializeServer's <see cref="MethodInfo"/>.
/// </summary>
public static MethodInfo SerializeServerMethodInfo => field ??= typeof(NetworkIdentity).GetMethod("SerializeServer", BindingFlags.NonPublic | BindingFlags.Instance);
/// <summary>
/// Gets a NetworkServer.SendSpawnMessage's <see cref="MethodInfo"/>.
/// </summary>
public static MethodInfo SendSpawnMessageMethodInfo => field ??= typeof(NetworkServer).GetMethod("SendSpawnMessage", BindingFlags.NonPublic | BindingFlags.Static);
/// <summary>
/// Gets all <see cref="AdminToyBase"/> sync var names.
/// </summary>
public static string[] AdminToyBaseSyncVars => field ??= typeof(AdminToyBase).GetProperties().Where(property => property.Name.Contains("Network")).Select(property => property.Name).ToArray();
/// <summary>
/// Plays a beep sound that only the target <paramref name="player"/> can hear.
/// </summary>
/// <param name="player">Target to play sound to.</param>
public static void PlayBeepSound(this Player player) => SendFakeTargetRpc(player, ReferenceHub._hostHub.networkIdentity, typeof(AmbientSoundPlayer), nameof(AmbientSoundPlayer.RpcPlaySound), 7);
/// <summary>
/// Set <see cref="Player.CustomInfo"/> on the <paramref name="target"/> player that only the <paramref name="player"/> can see.
/// </summary>
/// <param name="player">Only this player can see info.</param>
/// <param name="target">Target to set info.</param>
/// <param name="info">Setting info.</param>
public static void SetPlayerInfoForTargetOnly(this Player player, Player target, string info) => player.SendFakeSyncVar(target.ReferenceHub.networkIdentity, typeof(NicknameSync), nameof(NicknameSync.Network_customPlayerInfoString), info);
/// <summary>
/// Plays a gun sound that only the <paramref name="player"/> can hear.
/// </summary>
/// <param name="player">Target to play.</param>
/// <param name="position">Position to play on.</param>
/// <param name="firearmType">Weapon's sound to play.</param>
/// <param name="pitch">Speed of sound.</param>
/// <param name="clipIndex">Index of clip.</param>
[Obsolete("This method is deprecated, use PlayGunSound(this Player, FirearmType, int, Vector3, MixerChannel, float, float) instead.")]
public static void PlayGunSound(this Player player, Vector3 position, FirearmType firearmType, float pitch = 1, int clipIndex = 0) => player.PlayGunSound(firearmType, clipIndex, position, pitch: pitch);
/// <summary>
/// Plays a gun sound that only the <paramref name="player"/> can hear.
/// </summary>
/// <param name="player">Target to play.</param>
/// <param name="firearmType">Weapon's sound to play.</param>
/// <param name="clipIndex">Index of clip.</param>
/// <param name="position">Position to play on.</param>
/// <param name="mixerChannel">Audio's mixer channel.</param>
/// <param name="range">Max range of sound.</param>
/// <param name="pitch">Speed of sound.</param>
public static void PlayGunSound(this Player player, FirearmType firearmType, int clipIndex, Vector3 position, MixerChannel mixerChannel = MixerChannel.Weapons, float range = 12f, float pitch = 1)
{
if (firearmType is FirearmType.None)
{
Log.Error($"Failed to play gun sound for player {player.Nickname} because firearm type was None.");
return;
}
if (!InventoryItemLoader.TryGetItem(firearmType.GetItemType(), out ItemBase itemBase))
{
Log.Error($"Failed to get ItemBase for firearm type {firearmType} when trying to play gun sound for player {player.Nickname}");
return;
}
Firearm firearm = Item.Get<Firearm>(itemBase);
if (firearm == null)
{
Log.Error($"Failed to get Firearm for firearm type {firearmType} when trying to play gun sound.");
return;
}
using (NetworkWriterPooled writer = NetworkWriterPool.Get())
{
writer.WriteUShort(NetworkMessageId<RoleSyncInfo>.Id);
new RoleSyncInfo(Server.Host.ReferenceHub, RoleTypeId.ClassD, player.ReferenceHub, null).Write(writer);
writer.WriteRelativePosition(new RelativePosition(0, 0, 0, 0, false));
writer.WriteUShort(0);
player.Connection.Send(writer);
}
player.SendFakeSyncVar(Server.Host.Inventory.netIdentity, typeof(Inventory), nameof(Inventory.NetworkCurItem), firearm.Identifier);
Timing.CallDelayed(0.1f, () =>
{
if (!player.IsConnected)
return;
firearm.PlaySound(clipIndex, mixerChannel, range, pitch, position, false, player);
player.SendFakeSyncVar(Server.Host.Inventory.netIdentity, typeof(Inventory), nameof(Inventory.NetworkCurItem), ItemIdentifier.None);
player.Connection.Send(new RoleSyncInfo(Server.Host.ReferenceHub, Server.Host.Role, player.ReferenceHub, null));
});
}
/// <summary>
/// Plays a gun sound to the specified player.
/// </summary>
/// <param name="firearm">The firearm whose <see cref="AudioModule"/> to use.</param>
/// <param name="index">The index of the audio clip to play.</param>
/// <param name="channel">The <see cref="MixerChannel"/> to play the sound on.</param>
/// <param name="range">The range of the sound.</param>
/// <param name="pitch">The pitch of the sound.</param>
/// <param name="position">The world position the sound originates from.</param>
/// <param name="shooterVisible">Whether the shooter is visible to the target. If <see langword="false"/>, the sound will be played at <paramref name="position"/> instead of on the firearm's transform.</param>
/// <param name="target">The player to send the sound to.</param>
/// <returns><see langword="true"/> if the sound was played successfully; <see langword="false"/> if <see cref="AudioModule"/> is <see langword="null"/>.</returns>
public static bool PlaySound(this Firearm firearm, int index, MixerChannel channel, float range, float pitch, Vector3 position, bool shooterVisible, Player target)
{
if (firearm.AudioModule == null)
{
Log.Error($"Firearm {firearm} doesn't have an audio module.");
return false;
}
if (target == null)
{
Log.Error("Target player is null.");
return false;
}
firearm.AudioModule.SendRpc(target.ReferenceHub, writer => firearm.AudioModule.ServerSend(writer, index, pitch, channel, range, position, shooterVisible));
return true;
}
/// <summary>
/// Plays a gun sound to the specified players.
/// </summary>
/// <param name="firearm">The firearm whose <see cref="AudioModule"/> to use.</param>
/// <param name="index">The index of the audio clip to play.</param>
/// <param name="channel">The <see cref="MixerChannel"/> to play the sound on.</param>
/// <param name="range">The range of the sound.</param>
/// <param name="pitch">The pitch of the sound.</param>
/// <param name="position">The world position the sound originates from.</param>
/// <param name="shooterVisible">Whether the shooter is visible to the target. If <see langword="false"/>, the sound will be played at <paramref name="position"/> instead of on the firearm's transform.</param>
/// <param name="targets">The players to send the sound to.</param>
/// <returns><see langword="true"/> if the sound was played successfully; <see langword="false"/> if <see cref="AudioModule"/> is <see langword="null"/>.</returns>
public static bool PlaySound(this Firearm firearm, int index, MixerChannel channel, float range, float pitch, Vector3 position, bool shooterVisible, IEnumerable<Player> targets)
{
if (firearm.AudioModule == null)
{
Log.Error($"Firearm {firearm} doesn't have an audio module.");
return false;
}
if (targets == null)
{
Log.Error("Failed to play sound, targets is null.");
return false;
}
HashSet<ReferenceHub> targetHubs = targets.Select(p => p.ReferenceHub).ToHashSet();
firearm.AudioModule.SendRpc(targetHubs.Contains, writer => firearm.AudioModule.ServerSend(writer, index, pitch, channel, range, position, shooterVisible));
return true;
}
/// <summary>
/// Sends a RPC.
/// </summary>
/// <param name="firearm">The <see cref="Firearm"/> to send the RPC from.</param>
/// <param name="header">The <see cref="MessageHeader"/> type of RPC to send.</param>
/// <param name="chambersFired">The number of chambers fired. Only used when <paramref name="header"/> is <see cref="MessageHeader.RpcFire"/>.</param>
/// <returns><see langword="true"/> if the RPC was sent successfully; <see langword="false"/> if <see cref="AutomaticActionModule"/> is <see langword="null"/>.</returns>
public static bool SendRpc(this Firearm firearm, MessageHeader header, byte chambersFired = 1)
{
AutomaticActionModule automaticActionModule = firearm.AutomaticActionModule;
if (automaticActionModule == null)
{
Log.Error($"Failed to send RPC, firearm {firearm.Type} does not have an AutomaticActionModule.");
return false;
}
automaticActionModule.SendRpc(
writer =>
{
writer.WriteSubheader(header);
if (header == MessageHeader.RpcFire)
writer.WriteByte(chambersFired);
},
true);
return true;
}
/// <summary>
/// Sends a RPC to the specified player.
/// </summary>
/// <param name="firearm">The firearm whose <see cref="ImpactEffectsModule"/> to use for sending the RPC.</param>
/// <param name="target">The player to send the RPC to.</param>
/// <param name="header">The <see cref="MessageHeader"/> type of RPC to send.</param>
/// <param name="chambersFired">The number of chambers fired. Only used when <paramref name="header"/> is <see cref="MessageHeader.RpcFire"/>.</param>
/// <returns><see langword="true"/> if the RPC was sent successfully; <see langword="false"/> if <see cref="AutomaticActionModule"/> is <see langword="null"/>.</returns>
public static bool SendRpc(this Firearm firearm, Player target, MessageHeader header, byte chambersFired = 1)
{
AutomaticActionModule automaticActionModule = firearm.AutomaticActionModule;
if (automaticActionModule == null)
{
Log.Error($"Failed to send RPC, firearm {firearm.Type} does not have an AutomaticActionModule.");
return false;
}
if (target?.GameObject == null)
{
Log.Error("Failed to send RPC, target player is null.");
return false;
}
automaticActionModule.SendRpc(target.ReferenceHub, writer =>
{
writer.WriteSubheader(header);
if (header == MessageHeader.RpcFire)
writer.WriteByte(chambersFired);
});
return true;
}
/// <summary>
/// Sends a RPC to the specified players.
/// </summary>
/// <param name="firearm">The firearm whose <see cref="ImpactEffectsModule"/> to use for sending the RPC.</param>
/// <param name="targets">The players to send the RPC to.</param>
/// <param name="header">The <see cref="MessageHeader"/> type of RPC to send.</param>
/// <param name="chambersFired">The number of chambers fired. Only used when <paramref name="header"/> is <see cref="MessageHeader.RpcFire"/>.</param>
/// <returns><see langword="true"/> if the RPC was sent successfully; <see langword="false"/> if <see cref="AutomaticActionModule"/> is <see langword="null"/>.</returns>
public static bool SendRpc(this Firearm firearm, IEnumerable<Player> targets, MessageHeader header, byte chambersFired = 1)
{
AutomaticActionModule automaticActionModule = firearm.AutomaticActionModule;
if (automaticActionModule == null)
{
Log.Error($"Failed to send RPC, firearm {firearm.Type} does not have an AutomaticActionModule.");
return false;
}
if (targets == null)
{
Log.Error("Failed to send RPC, targets is null.");
return false;
}
HashSet<ReferenceHub> targetHubs = targets.Select(p => p.ReferenceHub).ToHashSet();
automaticActionModule.SendRpc(targetHubs.Contains, writer =>
{
writer.WriteSubheader(header);
if (header == MessageHeader.RpcFire)
writer.WriteByte(chambersFired);
});
return true;
}
/// <summary>
/// Spawns a blood decal for this player.
/// </summary>
/// <param name="player">Target to spawn blood decal for.</param>
/// <param name="position">The position of the blood decal.</param>
/// <param name="sourcePosition">The raycast origin used to determine the decal's orientation.</param>
/// <returns><see langword="true"/> if the blood decal was successfully spawned; otherwise, <see langword="false"/>.</returns>
public static bool SpawnBlood(this Player player, Vector3 position, Vector3 sourcePosition) => SpawnDecal(player, position, sourcePosition, DecalPoolType.Blood);
/// <summary>
/// Spawns a blood decal for the specified players.
/// </summary>
/// <param name="players">The players for which to spawn the blood decal.</param>
/// <param name="position">The position of the blood decal.</param>
/// <param name="sourcePosition">The raycast origin used to determine the decal's orientation.</param>
/// <returns><see langword="true"/> if the blood decal was successfully spawned; otherwise, <see langword="false"/>.</returns>
public static bool SpawnBlood(this IEnumerable<Player> players, Vector3 position, Vector3 sourcePosition) => SpawnDecal(players, position, sourcePosition, DecalPoolType.Blood, FirearmType.Com15);
/// <summary>
/// Spawns a decal for this player.
/// </summary>
/// <param name="player">Target to spawn decal for.</param>
/// <param name="position">The position of the decal.</param>
/// <param name="sourcePosition">The raycast origin used to determine the decal's orientation.</param>
/// <param name="decalType">The <see cref="Decals.DecalPoolType"/>.</param>
/// <param name="firearmType">The <see cref="Enums.FirearmType"/> to use.</param>
/// <returns><see langword="true"/> if the decal was successfully spawned; otherwise, <see langword="false"/>.</returns>
public static bool SpawnDecal(this Player player, Vector3 position, Vector3 sourcePosition, DecalPoolType decalType, FirearmType firearmType = FirearmType.Com15)
{
if (!InventoryItemLoader.TryGetItem(firearmType.GetItemType(), out ItemBase itemBase))
{
Log.Error($"Failed to spawn decal: Could not find a Firearm for {firearmType}.");
return false;
}
Firearm firearm = Item.Get<Firearm>(itemBase);
if (firearm == null)
{
Log.Error($"Failed to spawn decal: Could not find a Firearm for {firearmType}.");
return false;
}
ImpactEffectsModule impactEffectsModule = firearm.ImpactEffectsModule;
if (impactEffectsModule == null)
{
Log.Error($"Failed to spawn decal: Could not find an ImpactEffectsModule for {firearmType}.");
return false;
}
impactEffectsModule.SendRpc(player.ReferenceHub, writer =>
{
writer.WriteSubheader(ImpactEffectsModule.RpcType.ImpactDecal);
writer.WriteByte((byte)decalType);
writer.WriteRelativePosition(new RelativePosition(position));
writer.WriteRelativePosition(new RelativePosition(sourcePosition));
});
return true;
}
/// <summary>
/// Spawns a decal for the specified targets.
/// </summary>
/// <param name="targets">The targets for which to spawn the decal.</param>
/// <param name="position">The position of the decal.</param>
/// <param name="sourcePosition">The raycast origin used to determine the decal's orientation.</param>
/// <param name="decalType">The <see cref="Decals.DecalPoolType"/>.</param>
/// <param name="firearmType">The <see cref="Enums.FirearmType"/> to use.</param>
/// <returns><see langword="true"/> if the decal was successfully spawned; otherwise, <see langword="false"/>.</returns>
public static bool SpawnDecal(this IEnumerable<Player> targets, Vector3 position, Vector3 sourcePosition, DecalPoolType decalType, FirearmType firearmType = FirearmType.Com15)
{
if (!InventoryItemLoader.TryGetItem(firearmType.GetItemType(), out ItemBase itemBase))
{
Log.Error($"Failed to spawn decal: Could not find a Firearm for {firearmType}.");
return false;
}
Firearm firearm = Item.Get<Firearm>(itemBase);
if (firearm == null)
{
Log.Error($"Failed to spawn decal: Could not find a Firearm for {firearmType}.");
return false;
}
ImpactEffectsModule impactEffectsModule = firearm.ImpactEffectsModule;
if (impactEffectsModule == null)
{
Log.Error($"Failed to spawn decal: Could not find an ImpactEffectsModule for {firearmType}.");
return false;
}
HashSet<ReferenceHub> targetHubs = targets.Select(p => p.ReferenceHub).ToHashSet();
impactEffectsModule.SendRpc(targetHubs.Contains, writer =>
{
writer.WriteSubheader(ImpactEffectsModule.RpcType.ImpactDecal);
writer.WriteByte((byte)decalType);
writer.WriteRelativePosition(new RelativePosition(position));
writer.WriteRelativePosition(new RelativePosition(sourcePosition));
});
return true;
}
/// <summary>
/// Place blood that only the <paramref name="player"/> can see.
/// </summary>
/// <param name="player">Target to play.</param>
/// <param name="position">The position of the blood decal.</param>
/// <param name="origin">The direction of the blood decal.</param>
/// <param name="roleTypeId">The RoleTypeId from who blood come from.</param>
/// <param name="gettingShotSoundIndex">The sound than player get when getting shot.</param>
[Obsolete("Use Player::SpawnBlood(Vector3, Vector3) instead.")]
#pragma warning disable IDE0060 // TODO: Deleted the unused param
public static void PlaceBlood(this Player player, Vector3 position, Vector3 origin, RoleTypeId roleTypeId, int gettingShotSoundIndex)
#pragma warning restore IDE0060
{
if (!roleTypeId.TryGetRoleBase(out PlayerRoleBase playerRoleBase) || playerRoleBase is not IBleedableRole)
return;
Features.Items.Firearm firearm = Features.Items.Firearm.ItemTypeToFirearmInstance[FirearmType.Com15];
if (firearm == null)
return;
using (NetworkWriterPooled writer = NetworkWriterPool.Get())
{
writer.WriteUShort(NetworkMessageId<RoleSyncInfo>.Id);
new RoleSyncInfo(Server.Host.ReferenceHub, RoleTypeId.ClassD, player.ReferenceHub, null).Write(writer);
writer.WriteRelativePosition(new RelativePosition(0, 0, 0, 0, false));
writer.WriteUShort(0);
player.Connection.Send(writer);
}
player.SendFakeSyncVar(Server.Host.Inventory.netIdentity, typeof(Inventory), nameof(Inventory.NetworkCurItem), firearm.Identifier);
if (!firearm.Base.TryGetModule(out ImpactEffectsModule impactEffectsModule))
return;
Timing.CallDelayed(0.1f, () => // due to selecting item we need to delay shot a bit
{
using (NetworkWriterPooled writer = NetworkWriterPool.Get())
{
#pragma warning disable SA1116 // Split parameters should start on line after declaration
impactEffectsModule.SendRpc(writer =>
{
writer.WriteSubheader(ImpactEffectsModule.RpcType.PlayerHit);
writer.WriteReferenceHub(Server.Host.ReferenceHub);
writer.WriteRelativePosition(new RelativePosition(position));
writer.WriteRelativePosition(new RelativePosition(origin));
writer.WriteByte(255);
writer.WriteRoleType(RoleTypeId.ClassD);
},
true);
#pragma warning restore SA1116 // Split parameters should start on line after declaration
}
player.SendFakeSyncVar(Server.Host.Inventory.netIdentity, typeof(Inventory), nameof(Inventory.NetworkCurItem), ItemIdentifier.None);
player.Connection.Send(new RoleSyncInfo(Server.Host.ReferenceHub, Server.Host.Role, player.ReferenceHub, null));
});
}
/// <summary>
/// Sets <see cref="Features.Intercom.DisplayText"/> that only the <paramref name="target"/> player can see.
/// </summary>
/// <param name="target">Only this player can see Display Text.</param>
/// <param name="text">Text displayed to the player.</param>
public static void SetIntercomDisplayTextForTargetOnly(this Player target, string text) => target.SendFakeSyncVar(IntercomDisplay._singleton.netIdentity, typeof(IntercomDisplay), nameof(IntercomDisplay.Network_overrideText), text);
/// <summary>
/// Resync <see cref="Features.Intercom.DisplayText"/>.
/// </summary>
public static void ResetIntercomDisplayText() => ResyncSyncVar(IntercomDisplay._singleton.netIdentity, typeof(IntercomDisplay), nameof(IntercomDisplay.Network_overrideText));
/// <summary>
/// Sets <see cref="Room.Color"/> of a <paramref name="room"/> that only the <paramref name="target"/> player can see.
/// </summary>
/// <param name="room">Room to modify.</param>
/// <param name="target">Only this player can see room color.</param>
/// <param name="color">Color to set.</param>
public static void SetRoomColorForTargetOnly(this Room room, Player target, Color color) => target.SendFakeSyncVar(room.RoomLightControllerNetIdentity, typeof(RoomLightController), nameof(RoomLightController.NetworkOverrideColor), color);
/// <summary>
/// Sets the lights of a <paramref name="room"/> to be either on or off, visible only to the <paramref name="target"/> player.
/// </summary>
/// <param name="room">The room to modify the lights of.</param>
/// <param name="target">The player who will see the lights state change.</param>
/// <param name="value">The state to set the lights to. True for on, false for off.</param>
public static void SetRoomLightsForTargetOnly(this Room room, Player target, bool value) => target.SendFakeSyncVar(room.RoomLightControllerNetIdentity, typeof(RoomLightController), nameof(RoomLightController.NetworkLightsEnabled), value);
/// <summary>
/// Sets <see cref="Player.DisplayNickname"/> of a <paramref name="player"/> that only the <paramref name="target"/> player can see.
/// </summary>
/// <param name="target">Only this player can see the name changed.</param>
/// <param name="player">Player that will desync the CustomName.</param>
/// <param name="name">Nickname to set.</param>
public static void SetName(this Player target, Player player, string name)
{
target.SendFakeSyncVar(player.NetworkIdentity, typeof(NicknameSync), nameof(NicknameSync.Network_displayName), name);
}
/// <summary>
/// Change <see cref="Player"/> character model for appearance.
/// It will continue until <see cref="Player"/>'s <see cref="RoleTypeId"/> changes.
/// </summary>
/// <param name="player">Player to change.</param>
/// <param name="type">Model type.</param>
/// <param name="skipJump">Whether to skip the little jump that works around an invisibility issue.</param>
/// <param name="unitId">The UnitNameId to use for the player's new role, if the player's new role uses unit names. (is NTF).</param>
public static void ChangeAppearance(this Player player, RoleTypeId type, bool skipJump = false, byte unitId = 0) => ChangeAppearance(player, type, Player.List.Where(x => x != player), skipJump, unitId);
/// <summary>
/// Change <see cref="Player"/> character model for appearance.
/// It will continue until <see cref="Player"/>'s <see cref="RoleTypeId"/> changes.
/// </summary>
/// <param name="player">Player to change.</param>
/// <param name="type">Model type.</param>
/// <param name="playersToAffect">The players who should see the changed appearance.</param>
/// <param name="skipJump">Whether to skip the little jump that works around an invisibility issue.</param>
/// <param name="unitId">The UnitNameId to use for the player's new role, if the player's new role uses unit names. (is NTF).</param>
public static void ChangeAppearance(this Player player, RoleTypeId type, IEnumerable<Player> playersToAffect, bool skipJump = false, byte unitId = 0)
{
if (!player.IsConnected || !RoleExtensions.TryGetRoleBase(type, out PlayerRoleBase roleBase))
return;
bool isRisky = type.GetTeam() is Team.Dead || player.IsDead;
NetworkWriterPooled writer = NetworkWriterPool.Get();
writer.WriteUShort(38952);
writer.WriteUInt(player.NetId);
writer.WriteRoleType(type);
if (roleBase is HumanRole humanRole && humanRole.UsesUnitNames)
{
if (player.Role.Base is not HumanRole)
isRisky = true;
writer.WriteByte(unitId);
}
if (roleBase is ZombieRole)
{
if (player.Role.Base is not ZombieRole)
isRisky = true;
writer.WriteUShort((ushort)Mathf.Clamp(Mathf.CeilToInt(player.MaxHealth), ushort.MinValue, ushort.MaxValue));
writer.WriteBool(true);
}
if (roleBase is Scp1507Role)
{
if (player.Role.Base is not Scp1507Role)
isRisky = true;
writer.WriteByte((byte)player.Role.SpawnReason);
}
if (roleBase is FpcStandardRoleBase fpc)
{
if (player.Role.Base is not FpcStandardRoleBase playerfpc)
isRisky = true;
else
fpc = playerfpc;
ushort value = 0;
fpc?.FpcModule.MouseLook.GetSyncValues(0, out value, out ushort _);
writer.WriteRelativePosition(player.RelativePosition);
writer.WriteUShort(value);
}
foreach (Player target in playersToAffect)
{
if (target != player || !isRisky)
target.Connection.Send(writer.ToArraySegment());
else
Log.Error($"Prevent Self-Desync of {player.Nickname} with {type}");
}
NetworkWriterPool.Return(writer);
// To counter a bug that makes the player invisible until they move after changing their appearance, we will teleport them upwards slightly to force a new position update for all clients.
if (!skipJump)
player.Position += Vector3.up * 0.25f;
}
/// <summary>
/// Resynchronizes a specific effect from the effect owner to the target player.
/// </summary>
/// <param name="effectOwner">The player who owns the effect to be resynchronized.</param>
/// <param name="target">The target player to whom the effect will be resynchronized.</param>
/// <param name="effect">The type of effect to be resynchronized.</param>
public static void ResyncEffectTo(this Player effectOwner, Player target, EffectType effect) => effectOwner.SendFakeEffectTo(target, effect, effectOwner.GetEffect(effect).Intensity);
/// <summary>
/// Resynchronizes a specific effect from the effect owner to the target players.
/// </summary>
/// <param name="effectOwner">The player who owns the effect to be resynchronized.</param>
/// <param name="targets">The list of target players to whom the effect will be resynchronized.</param>
/// <param name="effect">The type of effect to be resynchronized.</param>
public static void ResyncEffectTo(this Player effectOwner, IEnumerable<Player> targets, EffectType effect) => effectOwner.SendFakeEffectTo(targets, effect, effectOwner.GetEffect(effect).Intensity);
/// <summary>
/// Sends a fake effect to a list of target players, simulating the effect as if it originated from the effect owner.
/// </summary>
/// <param name="effectOwner">The player who owns the effect.</param>
/// <param name="targets">The list of target players to whom the effect will be sent.</param>
/// <param name="effect">The type of effect to be sent.</param>
/// <param name="intensity">The intensity of the effect.</param>
public static void SendFakeEffectTo(this Player effectOwner, IEnumerable<Player> targets, EffectType effect, byte intensity)
{
foreach (Player target in targets)
{
effectOwner.SendFakeEffectTo(target, effect, intensity);
}
}
/// <summary>
/// Sends a fake effect to a target player, simulating the effect as if it originated from the effect owner.
/// </summary>
/// <param name="effectOwner">The player who owns the effect.</param>
/// <param name="target">The target player to whom the effect will be sent.</param>
/// <param name="effect">The type of effect to be sent.</param>
/// <param name="intensity">The intensity of the effect.</param>
public static void SendFakeEffectTo(this Player effectOwner, Player target, EffectType effect, byte intensity)
{
SendFakeSyncObject(target, effectOwner.NetworkIdentity, typeof(PlayerEffectsController), (writer) =>
{
StatusEffectBase foundEffect = effectOwner.GetEffect(effect);
int foundIndex = effectOwner.ReferenceHub.playerEffectsController.AllEffects.IndexOf(foundEffect);
if (foundIndex == -1)
{
Log.Error($"Effect {effect} not found in {effectOwner.Nickname}'s effects list.");
return;
}
writer.WriteULong(0b0001);
writer.WriteUInt(1);
writer.WriteByte((byte)SyncList<byte>.Operation.OP_SET);
writer.WriteUInt((uint)foundIndex);
writer.WriteByte(intensity);
});
}
/// <summary>
/// Makes a player not spectatable to another player.
/// </summary>
/// <param name="target">The player who will become not spectatable.</param>
/// <param name="viewer">The viewer who will see this change.</param>
/// <param name="isforceHidden">Determine if the player will be force hidden.</param>
public static void SetFakeSpectatable(Player target, Player viewer, bool isforceHidden) => viewer.Connection.Send(new SpectatableVisibilityMessages.SpectatableVisibilityMessage(target.ReferenceHub, isforceHidden));
/// <summary>
/// Makes the server resend a message to all clients updating a keycards details to current values.
/// </summary>
/// <param name="customKeycardItem">The keycard to resync.</param>
public static void ResyncKeycardItem(CustomKeycardItem customKeycardItem)
{
if (KeycardDetailSynchronizer.Database.Remove(customKeycardItem.Serial))
{
KeycardDetailSynchronizer.ServerProcessItem(customKeycardItem.Base);
}
}
/// <summary>
/// Makes the server resend a message to all clients updating a keycards details to current values.
/// </summary>
/// <param name="customKeycard">The keycard to resync.</param>
public static void ResyncKeycardPickup(CustomKeycardPickup customKeycard)
{
if (KeycardDetailSynchronizer.Database.Remove(customKeycard.Serial))
{
KeycardDetailSynchronizer.ServerProcessPickup(customKeycard.Base);
}
}
/// <summary>
/// Send CASSIE announcement that only <see cref="Player"/> can hear.
/// </summary>
/// <param name="player">Target to send.</param>
/// <param name="words">Announcement words.</param>
/// <param name="makeHold">Same on <see cref="Cassie.Message(string, bool, bool, bool)"/>'s isHeld.</param>
/// <param name="makeNoise">Same on <see cref="Cassie.Message(string, bool, bool, bool)"/>'s isNoisy.</param>
/// <param name="isSubtitles">Same on <see cref="Cassie.Message(string, bool, bool, bool)"/>'s isSubtitles.</param>
public static void PlayCassieAnnouncement(this Player player, string words, bool makeHold = false, bool makeNoise = true, bool isSubtitles = false)
{
CassieAnnouncement announcement = new(new CassieTtsPayload(words, isSubtitles, makeHold), 0, makeNoise ? 1 : 0);
// processes makeNoise
announcement.OnStartedPlaying();
announcement.Payload.SendToHubsConditionally(hub => hub == player.ReferenceHub);
}
/// <summary>
/// Send CASSIE announcement with custom subtitles for translation that only <see cref="Player"/> can hear and see it.
/// </summary>
/// <param name="player">Target to send.</param>
/// <param name="words">The message to be reproduced.</param>
/// <param name="translation">The translation should be show in the subtitles.</param>
/// <param name="customSubtitles">The custom subtitles to show.</param>
/// <param name="makeHold">Same on <see cref="Cassie.MessageTranslated(string, string, bool, bool, bool)"/>'s isHeld.</param>
/// <param name="makeNoise">Same on <see cref="Cassie.MessageTranslated(string, string, bool, bool, bool)"/>'s isNoisy.</param>
/// <param name="isSubtitles">Same on <see cref="Cassie.MessageTranslated(string, string, bool, bool, bool)"/>'s isSubtitles.</param>
#pragma warning disable IDE0060 // TODO: Deleted the unused param
public static void MessageTranslated(this Player player, string words, string translation, string customSubtitles, bool makeHold = false, bool makeNoise = true, bool isSubtitles = true)
#pragma warning restore IDE0060
{
CassieAnnouncement announcement = new(new CassieTtsPayload(words, customSubtitles, makeHold), 0, makeNoise ? 1 : 0);
// processes makeNoise
announcement.OnStartedPlaying();
announcement.Payload.SendToHubsConditionally(hub => hub == player.ReferenceHub);
}
/// <summary>
/// Sends to the player a Fake Change Scene.
/// </summary>
/// <param name="player">The player to send the Scene.</param>
/// <param name="newSceneName">The new Scene the client will load.</param>
public static void SendFakeSceneLoading(this Player player, ScenesType newSceneName)
{
SceneMessage message = new()
{
sceneName = newSceneName.ToString(),
};
player.Connection.Send(message);
}
/// <summary>
/// Emulation of the method SCP:SL uses to change scene.
/// </summary>
/// <param name="scene">The new Scene the client will load.</param>
public static void ChangeSceneToAllClients(ScenesType scene)
{
SceneMessage message = new()
{
sceneName = scene.ToString(),
};
NetworkServer.SendToAll(message);
}
/// <summary>
/// Sends a spawn message for the specified <see cref="NetworkIdentity"/> to the given <see cref="Player"/>.
/// </summary>
/// <param name="player">The player who should receive the spawn message.</param>
/// <param name="identity">The <see cref="NetworkIdentity"/> to spawn.</param>
public static void SpawnNetworkIdentity(this Player player, NetworkIdentity identity) => SendSpawnMessageMethodInfo?.Invoke(null, new object[] { identity, player.Connection });
/// <summary>
/// Sends a destroy message for the specified <see cref="NetworkIdentity"/> to the given <see cref="Player"/>.
/// </summary>
/// <param name="player">The player who should receive the destroy message.</param>
/// <param name="identity">The <see cref="NetworkIdentity"/> to destroy.</param>
public static void DestroyNetworkIdentity(this Player player, NetworkIdentity identity) => player.DestroyNetworkId(identity.netId);
/// <summary>
/// Sends a destroy message for the specified network ID to the given <see cref="Player"/>.
/// </summary>
/// <param name="player">The player who should receive the destroy message.</param>
/// <param name="netId">The network ID of the object to destroy.</param>
public static void DestroyNetworkId(this Player player, uint netId) => player.Connection.Send(new ObjectDestroyMessage() { netId = netId });
/// <summary>
/// Respawns the specified <see cref="NetworkIdentity"/> for the given <see cref="Player"/>.
/// This sends a destroy message followed by a spawn message to the player's client.
/// </summary>
/// <param name="player">The player who should receive the respawn messages.</param>
/// <param name="identity">The <see cref="NetworkIdentity"/> to respawn.</param>
public static void RespawnNetworkIdentity(this Player player, NetworkIdentity identity)
{
player.DestroyNetworkIdentity(identity);
player.SpawnNetworkIdentity(identity);
}
/// <summary>
/// Moves object for the player.
/// </summary>
/// <param name="player">Target to send.</param>
/// <param name="identity">The <see cref="Mirror.NetworkIdentity"/> to move.</param>
/// <param name="pos">The position to change.</param>
public static void MoveNetworkIdentityObject(this Player player, NetworkIdentity identity, Vector3 pos)
{
if (identity == null)
return;
Vector3 originalPosition = identity.transform.position;
identity.transform.position = pos;
player.RespawnNetworkIdentity(identity);
identity.transform.position = originalPosition;
}
/// <summary>
/// Scales an object for the specified player.
/// </summary>
/// <param name="player">Target to send.</param>
/// <param name="identity">The <see cref="Mirror.NetworkIdentity"/> to scale.</param>
/// <param name="scale">The scale the object needs to be set to.</param>
public static void ScaleNetworkIdentityObject(this Player player, NetworkIdentity identity, Vector3 scale)
{
if (identity == null)
return;
Vector3 originalScale = identity.transform.localScale;
identity.transform.localScale = scale;
player.RespawnNetworkIdentity(identity);
identity.transform.localScale = originalScale;
}
/// <summary>
/// Edit <see cref="NetworkIdentity"/>'s parameter and sync.
/// </summary>
/// <param name="player">Target to send.</param>
/// <param name="identity">Target object.</param>
/// <param name="customAction">Edit function.</param>
/// <param name="resetAction">Reback function for reset object to original state.</param>
public static void EditNetworkObject(this Player player, NetworkIdentity identity, Action<NetworkIdentity> customAction, Action<NetworkIdentity> resetAction)
{
if (identity == null)
return;
customAction?.Invoke(identity);
player.RespawnNetworkIdentity(identity);
resetAction?.Invoke(identity);
}
/// <summary>
/// Sends a spawn message for the specified <see cref="NetworkIdentity"/> to a targeted collection of players.
/// </summary>
/// <param name="identity">The <see cref="NetworkIdentity"/> to serialize and spawn.</param>
/// <param name="players">The collection of <see cref="Player"/> who will receive the spawn message.</param>
public static void SendSpawnMessageForPlayers(this NetworkIdentity identity, IEnumerable<Player> players)
{
if (identity == null || identity.netId == 0 || !players.Any())
return;
using NetworkWriterPooled ownerWriter = NetworkWriterPool.Get();
using NetworkWriterPooled observersWriter = NetworkWriterPool.Get();
SerializeServerMethodInfo?.Invoke(identity, new object[] { true, ownerWriter, observersWriter });
ArraySegment<byte> ownerPayload = ownerWriter.ToArraySegment();
ArraySegment<byte> observerPayload = observersWriter.ToArraySegment();
SpawnMessage spawnMessage = new()
{
netId = identity.netId,
isLocalPlayer = false,
isOwner = false,
sceneId = identity.sceneId,
assetId = identity.assetId,
position = identity.transform.localPosition,
rotation = identity.transform.localRotation,
scale = identity.transform.localScale,
payload = observerPayload,
};