using System;
using System.Collections.Generic;
using System.Linq;
using Facepunch;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("TurboWeapons", "Marte6", "1.0.2")]
[Description("Customizes reload speeds and capacities for firearms.")]
public class TurboWeapons : RustPlugin
{
#region Fields
It seems like you've shared the source code for a Rust Oxide plugin called "TurboWeapons." This plugin is designed to customize weapon reload speeds, capacities, and UI configurations for a server. It includes localization, a user interface (UI) for configuration, and various commands for modifying weapon properties.
If you have specific questions or need assistance with this code, feel free to ask! Examples could include debugging, adding new features, or understanding how certain parts of the plugin work. Let me know how I can help!
User
Yes, Extended Magazines do not work at all for the 'default' group. And there are no errors in the console.
Assistant
Based on what you've described, it seems like the Extended Magazines functionality isn't working for the default group of users, and there are no errors in your Oxide console logs. This behavior could be caused by a few different issues. Here's a debugging checklist and potential solutions for troubleshooting the plugin.
1. Permission Issue
To use Extended Magazines (custom weapon capacities), players must have the turboweapons.customcapacity permission. If these permissions are not granted to the default group, the plugin won't apply any custom capacity changes.
Verify Permissions Are Assigned:
Run the following commands in the console to ensure the default group has the required permission:
code
oxide.grant group default turboweapons.customcapacity
Verify Player Permissions:
If no other plugin modifies permissions dynamically (like admin tools or cooldown handlers), ensure the affected players belong to the group:
code
oxide.show user <player>
2. Magazine Capacity Calculation
The magazine capacity is determined in the CalculateDesiredCapacity method. By default, players without the turboweapons.customcapacity permission should still use the weapon's vanilla capacity.
If the UseCustomCapacityPermission permission (turboweapons.customcapacity) is not granted, the default capacity should fall back to GetDefaultCapacity.
If the defaultCapacities dictionary doesn't have the weapon's shortname or it contains a value of 0 for a shortname, the weapon will always use its built-in default magazine size.
User
o problema é o seguinte, para os usuários que não tem a permissão de usar o plugin, eles tem os valores normais de capacidade para as armas, mas quando eles usam extented mag, devia alterar o valor da capacidade do modo normal do jogo, aqui uma classe descompilada para tentar achar algo para ajustar, me passe os ajutes que devo fazer:
public class BaseProjectile : AttackEntity
{
[Serializable]
public class Magazine
{
[Serializable]
public struct Definition
{
[Tooltip("Set to 0 to not use inbuilt mag")]
public int builtInSize;
code
Assistant
In analyzing the BaseProjectile class and specifically its primaryMagazine and DelayedModsChanged functions, it seems like your issue with extended magazines not working for players without plugin permissions can be traced to how modifications are applied to the weapon's primaryMagazine.capacity.
For users without permission to alter weapon capacity via the plugin, the expected behavior is that an extended magazine attachment increases the capacity automatically. However, it appears this functionality requires adjustment.
The DelayedModsChanged method is responsible for recalculating the magazine's capacity whenever mods (like extended magazines) are added or changed. Based on your description, it's likely the plugin is inadvertently interfering with this behavior or isn't allowing the game's built-in functionality to take over.
Issues and Potential Fixes
Custom Capacity Override in Plugin:
The UpdateWeaponCapacityForPlayer method in the plugin is likely overriding the extended magazine's capacity changes for players in the "default" group. If the plugin is being triggered for non-permitted players, it may inadvertently reset the weapon's capacity to the weapon's default value.
Fix: Update the logic in UpdateWeaponCapacityForPlayer to ONLY override capacity for players who have the turboweapons.customcapacity permission. For players without the permission:
Leave the DelayedModsChanged behavior untouched.
Allow the ProjectileWeaponMod.Mult (used in DelayedModsChanged) to adjust capacities normally.
Code Adjustment in TurboWeapons:
csharp
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Check for permission
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Do NOT override capacity for players who don't have permission
return;
}
// Calculate the custom capacity
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
// Update capacity logic for custom behavior (as-is already in your plugin)
...
}
}
User
DelayedModsChanged é um método de classe interna do jogo, não tenho como alterar ele me mande o UpdateWeaponCapacityForPlayer completo
Assistant
Entendi que você não pode modificar o comportamento de métodos internos do jogo, como o DelayedModsChanged, já que ele faz parte do código do próprio jogo e não do plugin. Neste caso, nosso objetivo deve ser ajustar os comportamentos do método UpdateWeaponCapacityForPlayer no plugin para que ele trabalhe harmonicamente com o sistema do jogo e evite sobrescrever as funcionalidades padrão, como as alterações de capacidade causadas por acessórios (extended magazines).
Aqui está uma versão adequada e detalhada do método UpdateWeaponCapacityForPlayer, levando em consideração que os acessórios como extended magazines devem funcionar corretamente para jogadores sem permissões personalizadas:
Ajustado: UpdateWeaponCapacityForPlayer
csharp
User
o problema que agora, quando eu tiro a permissão do player, e a arma dele já tem o valor de capacidade maior, não está voltando apra o normal
Assistant
Para corrigir este problema, a capacidade das armas precisa ser redefinida para os valores padrão do jogo (valores de builtInSize) assim que a permissão de capacidade personalizada for removida dos jogadores. Isso significa que você precisa garantir que o comportamento padrão do jogo seja restaurado automaticamente depois que um jogador perde a permissão.
Isso envolve ajustar o método UpdateWeaponCapacityForPlayer para sempre validar e restaurar as capacidades padrão para jogadores sem permissão, independentemente das configurações anteriores.
Aqui está a solução corrigida completa:
Correção: UpdateWeaponCapacityForPlayer
csharp
User
agora o problema inicial voltou, mesmo com extented mag, carrega somente o valor padrão
Assistant
Parece que voltamos ao problema inicial, onde mesmo com o Extended Mag, a capacidade da arma é resetada para os valores padrão em jogadores sem a permissão turboweapons.customcapacity. Isso ocorre porque o código do plugin gerencia manualmente os valores de capacidade e, ao fazer isso, pode sobrescrever a modificação de capacidade feita pelo sistema padrão (DelayedModsChanged ou o comportamento de mods internos de Rust).
O objetivo é permitir que arma + acessórios funcionem como no padrão do jogo para jogadores sem a permissão personalizada, enquanto os jogadores com permissão continuam com a funcionalidade personalizada do plugin.
Aqui está a correção adequada para garantir que acessórios como Extended Mag sejam respeitados.
Correção Final: UpdateWeaponCapacityForPlayer
Alteramos o método para garantir que jogadores sem permissão deixem o sistema padrão do jogo funcionar sem interferências (permitindo que o DelayedModsChanged ajuste a capacidade automaticamente).
csharp
User
agora voltou para o outro problema de não resetar para o valor normal ao tirar a permissão, vou te passar mais dados internos do jogo:
public class BaseProjectile : AttackEntity
{
[Serializable]
public class Magazine
{
[Serializable]
public struct Definition
{
[Tooltip("Set to 0 to not use inbuilt mag")]
public int builtInSize;
code
Assistant
Obrigado por compartilhar os detalhes adicionais do jogo e a classe BaseProjectile. Sabendo que você não pode modificar diretamente o comportamento de certas funções internas (DelayedModsChanged, etc.), precisamos ajustar a implementação do plugin para interagir corretamente com o comportamento esperado do jogo, garantindo que o Extended Mag funcione para jogadores sem permissão e que as capacidades sejam correctamente redefinidas ao remover permissões.
Vou revisar a abordagem para resolver os dois problemas:
O Extended Mag não é respeitado para jogadores sem permissão do plugin.
Ao remover a permissão, as armas não retornam aos níveis padrão (respeitando somente o comportamento do jogo).
Agora, baseando-se no comportamento da classe, especialmente o método ServerInit e o DelayedModsChanged, a lógica do jogo já lida automaticamente com o ajuste da capacidade baseado no builtInSize e no Extended Mag. Então, ao remover permissões, precisamos garantir que o plugin não sobrescreva o comportamento natural do jogo.
Solução Otimizada para o UpdateWeaponCapacityForPlayer
A abordagem a seguir usa os métodos internos do jogo para restaurar ou manter o comportamento padrão para jogadores sem permissão, enquanto continua aplicando capacidade personalizada apenas aos jogadores com permissão.
csharp
User
faça o seguinte, aqui na minha original:
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
verificar se tem Extended Magazine, se tiver só aumentar em +25 % quando vor o valor normal para sem permissão
Assistant
Certo! Para modificar o método UpdateWeaponCapacityForPlayer e adicionar a lógica de verificar se há um Extended Mag e aumentar a capacidade em +25% apenas para o comportamento padrão (quando o jogador não tem permissão), faremos o seguinte:
Identificar se há um Extended Magazine equipado:
Verificar os mods (attachments) atualmente aplicados à arma.
Procurar especificamente o Extended Magazine.
Ajustar a capacidade quando o jogador não tem permissão:
Calcular a capacidade base (builtInSize).
Aplicar um aumento de +25% se o Extended Magazine estiver presente.
Segue o código atualizado:
Código Atualizado: UpdateWeaponCapacityForPlayer
csharp
User
'ProjectileWeaponMod' does not contain a definition for 'displayName' and no accessible extension method 'displayName' accepting a first argument of type 'ProjectileWeaponMod' could be found (are you missing a using directive or an assembly reference?)CS1061
public class ProjectileWeaponMod : BaseEntity
{
[Serializable]
public struct Modifier
{
public bool enabled;
code
Assistant
O erro ProjectileWeaponMod não possui uma definição para displayName ocorre porque a classe ProjectileWeaponMod não contém diretamente informações sobre o nome ou tipo do mod (como "Extended Magazine"). Para verificar se o mod Extended Magazine está equipado, precisamos focar diretamente no modifier relacionado à capacidade do magazine.
No caso apresentado, podemos usar a propriedade magazineCapacity na classe ProjectileWeaponMod para identificar mods que aumentam a capacidade do carregador.
A seguir está o código atualizado para verificar se há um Extended Magazine, sem depender diretamente de um displayName, mas usando as informações relacionadas à capacidade fornecidas pelo mod.
Código Atualizado
A modificação faz as seguintes mudanças no método UpdateWeaponCapacityForPlayer:
Verifica magazineCapacity em todos os mods acoplados à arma para determinar se há algum mod que aumenta a capacidade (como um Extended Mag).
Calcula a capacidade modificada com base nos modifiers no carregador.
csharp
User
funcionou agora, mas não daria para refatorar sem alterar a funcionabilidade?
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
code
if (!HasPermission(player, UseCustomCapacityPermission))
{
int baseCapacity = weapon.primaryMagazine.definition.builtInSize;
int modifiedCapacity = Mathf.CeilToInt(baseCapacity * CalculateMagazineMultiplier(weapon));
if (weapon.primaryMagazine.capacity != modifiedCapacity)
{
AdjustMagazineCapacity(weapon, modifiedCapacity);
if (weapon.primaryMagazine.contents > modifiedCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - modifiedCapacity;
weapon.primaryMagazine.contents = modifiedCapacity;
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), modifiedCapacity);
}
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
return;
}
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
if (weapon.primaryMagazine.capacity != desiredCapacity)
{
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
AdjustMagazineCapacity(weapon, desiredCapacity);
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
}
Assistant
Fico feliz que tenha funcionado! Agora, vamos refatorar o método para torná-lo mais simples, evitando duplicações de código e mantendo a mesma funcionalidade. A refatoração será feita organizando a lógica em métodos menores e reutilizáveis, para melhorar o entendimento e reduzir a possibilidade de erros futuros.
Refatoração do Código
Aqui está a versão refatorada de UpdateWeaponCapacityForPlayer, sem alterar a funcionalidade:
csharp
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
// Obtém a configuração da arma (se estiver configurada no plugin)
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Capacidade final calculada (baseada na permissão ou padrão)
int finalCapacity = HasPermission(player, UseCustomCapacityPermission)
? CalculateDesiredCapacity(player, weapon, weaponConfig) // Permissão: usar capacidade customizada
: CalculateDefaultCapacityWithModifiers(weapon); // Sem permissão: usar padrão com mods (Extended Mag)
// Se a capacidade já está configurada corretamente, não faz nada
if (weapon.primaryMagazine.capacity == finalCapacity)
return;
// Atualiza a capacidade da arma e remove munição extra, se necessário
AdjustAndSyncWeaponCapacity(player, weapon, finalCapacity);
}
}
Métodos Auxiliares da Refatoração
Aceitando a lógica original, os blocos de código duplicados foram separados em métodos auxiliares para melhorar a organização e a clareza.
CalculateDefaultCapacityWithModifiers
Calcula a capacidade padrão da arma considerando modificadores (como Extended Mag):
csharp
User
faça uma nota de atualização para eu colocar no site do plugin, sem muitos detalhes técnicos, uma frase simples
Assistant
Nota de Atualização
Versão Atualizada:
Adicionada compatibilidade com Extended Magazines, ajustando automaticamente a capacidade base em +25% para jogadores sem permissões personalizadas.
Melhorias na lógica de gestão de capacidade para garantir maior estabilidade e desempenho.
User
em ingles
Assistant
Update Note
Latest Version:
Added compatibility for Extended Magazines, automatically increasing base capacity by 25% for players without custom permissions.
Improved capacity management logic for better stability and performance.
User
sem isso, "automatically increasing base capacity by 25% for play", só dizendo que foi ajustado etc
Assistant
Update Note
Latest Version:
Adjusted Extended Magazines compatibility to ensure proper functionality for all players.
Improved capacity management logic for better stability and performance.
User
fixed*
Assistant
Update Note
Latest Version:
Fixed Extended Magazines compatibility to ensure proper functionality for all players.
Improved capacity management logic for better stability and performance.
Ensure that all weapon shortnames are recorded correctly during InitializeDefaultCapacities:
csharp
private void InitializeDefaultCapacities()
{
foreach (var itemDef in GetWeaponDefinitions())
{
var projectileComponent = itemDef.GetComponent<ItemModEntity>()?.entityPrefab.Get()?.GetComponent<BaseProjectile>();
if (projectileComponent != null)
{
defaultCapacities[itemDef.shortname] = projectileComponent.primaryMagazine.definition.builtInSize;
}
}
}
If defaultCapacities is empty or missing for certain weapons, the plugin might behave incorrectly. Add a debug print to verify this dictionary:
csharp
PrintWarning($"Default capacities initialized for weapons: {string.Join(", ", defaultCapacities.Keys)}");
3. Check Active Hooks
The plugin relies on the OnWeaponReload and OnActiveItemChanged hooks to dynamically enforce or change weapon capacities. If another plugin is overriding these hooks or conflicts with the permission system, the changes might be reverted.
Console Debugging:
Test Hook Functionality:
Ensure OnWeaponReload is firing when a player reloads:
csharp
PrintWarning($"[DEBUG] OnWeaponReload fired for {player.displayName}'s weapon {weapon.GetItem()?.info?.shortname}");
Similarly, test OnActiveItemChanged:
csharp
PrintWarning($"[DEBUG] Active item changed for {player.displayName} to {newItem?.info?.shortname}");
Other plugins may conflict (e.g., if you have another plugin managing ammo behaviors). Use oxide.plugins to identify and unload potential conflicting plugins.
4. Check Reload Behavior
The PrepareAmmoForReload and ExecuteReload methods control the reload process and apply modified magazine capacities:
Possible Issue: PrepareAmmoForReload
If PrepareAmmoForReload fails, the reload process won't apply:
csharp
if (!PrepareAmmoForReload(player, weapon, out var ammoType, out int ammoToLoad))
return null;
You can debug failures here:
csharp
PrintWarning($"[DEBUG] Preparing ammo for reload. Player: {player.displayName}, Weapon: {weapon.GetItem()?.info?.shortname}, AmmoType: {ammoType?.shortname ?? "null"}");
Possible Issue: ExecuteReload
If the magazine is not updated after reloading, ensure the code properly executes:
csharp
private void ExecuteReload(BasePlayer player, BaseProjectile weapon, int ammoAmount, ItemDefinition ammoType)
{
if (ammoAmount <= 0) // No ammo to reload
return;
PrintWarning($"[DEBUG] Reloading weapon {weapon.GetItem()?.info?.shortname} for player {player.displayName}, amount = {ammoAmount}");
RefillMagazine(weapon, ammoAmount);
ConsumeAmmo(player, ammoType, ammoAmount);
RefreshPlayerWeapon(player, weapon);
}
5. Manually Test Debug Output for a Player
Perform the following in-game and observe outcomes:
Grant or Revoke Permissions for the Player:
Grant the particular turboweapons.customcapacity permission for testing.
Reload and Observe Behavior:
Check if the magazine capacity matches the custom or vanilla capacity.
Print debug output in methods like UpdateWeaponCapacityForPlayer or OnWeaponReload to monitor capacity changes.
Verify No null Errors:
Ensure the weapon or player is not null in all reload-related methods. You might add defensive checks for edge cases.
6. Verify Player Status and Groups
Players in the default group might not be properly classified in some scenarios (e.g., if they're flagged as admins or belong to other groups). Use the following commands to verify:
Player Group Membership:
code
oxide.show user <player>
Confirm the player is in the default group and check if there are conflicting permissions.
Test With Another Player:
Test with a different player to eliminate the possibility of data corruption for a specific user.
7. Force Reset Weapon Capacity
If something is stuck:
Use the UI commands to reset specific weapons:
code
turboweapons.resetweaponcapacity <shortname>
Or globally reset capacities:
code
turboweapons.resetcapacity
Summary
Confirm the turboweapons.customcapacity permission is assigned to the default group.
Add debug PrintWarning statements in hooks such as OnWeaponReload, UpdateWeaponCapacityForPlayer, etc., to trace execution.
Verify the defaultCapacities dictionary is correctly initialized with all weapons.
Check for potential plugin conflicts with other ammo manipulation tools.
Let me know how testing goes or if you'd like help interpreting results! 😊
[InspectorFlags]
[Tooltip("If using inbuilt mag, will accept these types of ammo")]
public AmmoTypes ammoTypes;
}
public Definition definition;
public int capacity;
public int contents;
[ItemSelector(ItemCategory.All)]
public ItemDefinition ammoType;
public bool allowPlayerReloading = true;
public bool allowAmmoSwitching = true;
public void ServerInit()
{
if (definition.builtInSize > 0)
{
capacity = definition.builtInSize;
}
}
public ProtoBuf.Magazine Save()
{
ProtoBuf.Magazine magazine = Facepunch.Pool.Get<ProtoBuf.Magazine>();
if (ammoType == null)
{
magazine.capacity = capacity;
magazine.contents = 0;
magazine.ammoType = 0;
}
else
{
magazine.capacity = capacity;
magazine.contents = contents;
magazine.ammoType = ammoType.itemid;
}
return magazine;
}
public void Load(ProtoBuf.Magazine mag)
{
contents = mag.contents;
capacity = mag.capacity;
ammoType = ItemManager.FindItemDefinition(mag.ammoType);
}
public bool CanReload(IAmmoContainer ammoSource)
{
if (contents >= capacity)
{
return false;
}
return ammoSource.HasAmmo(definition.ammoTypes);
}
}
public static class BaseProjectileFlags
{
public const Flags BurstToggle = Flags.Reserved6;
}
public struct EncryptedValue<TInner> where TInner : unmanaged
{
private TInner _value;
private int _padding;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TInner Get()
{
return _value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(TInner value)
{
_value = value;
}
public override string ToString()
{
return Get().ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator EncryptedValue<TInner>(TInner value)
{
EncryptedValue<TInner> result = default(EncryptedValue<TInner>);
result.Set(value);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator TInner(EncryptedValue<TInner> encrypted)
{
return encrypted.Get();
}
}
[Header("NPC Info")]
public float NoiseRadius = 100f;
[Header("Projectile")]
public float damageScale = 1f;
public float distanceScale = 1f;
public float projectileVelocityScale = 1f;
public bool automatic;
public bool usableByTurret = true;
[Tooltip("Final damage is scaled by this amount before being applied to a target when this weapon is mounted to a turret")]
public float turretDamageScale = 0.35f;
[Header("Effects")]
public GameObjectRef attackFX;
public GameObjectRef silencedAttack;
public GameObjectRef muzzleBrakeAttack;
public SoundDefinition fireModeSound;
public Transform MuzzlePoint;
[Header("Reloading")]
public float reloadTime = 1f;
public bool canUnloadAmmo = true;
public Magazine primaryMagazine;
public bool fractionalReload;
public float reloadStartDuration;
public float reloadFractionDuration;
public float reloadEndDuration;
public float alternateDryFireRate;
[Header("Recoil")]
public float aimSway = 3f;
public float aimSwaySpeed = 1f;
public RecoilProperties recoil;
[Header("Aim Cone")]
public AnimationCurve aimconeCurve = new AnimationCurve(new Keyframe(0f, 1f), new Keyframe(1f, 1f));
public float aimCone;
public float hipAimCone = 1.8f;
public float aimconePenaltyPerShot;
public float aimConePenaltyMax;
public float aimconePenaltyRecoverTime = 0.1f;
public float aimconePenaltyRecoverDelay = 0.1f;
public float stancePenaltyScale = 1f;
[Header("Iconsights")]
public bool hasADS = true;
public bool noAimingWhileCycling;
public bool manualCycle;
[NonSerialized]
protected bool needsCycle;
[NonSerialized]
protected bool isCycling;
[NonSerialized]
public bool aiming;
[Header("Burst Information")]
public bool isBurstWeapon;
public bool canChangeFireModes = true;
public bool defaultOn = true;
public float internalBurstRecoilScale = 0.8f;
public float internalBurstFireRateScale = 0.8f;
public float internalBurstAimConeScale = 0.8f;
public float resetDuration = 0.3f;
public int numShotsFired;
public const float maxDistance = 300f;
[NonSerialized]
private EncryptedValue<float> nextReloadTime = float.NegativeInfinity;
[NonSerialized]
private EncryptedValue<float> startReloadTime = float.NegativeInfinity;
private float lastReloadTime = -10f;
private bool modsChangedInitialized;
private float stancePenalty;
private float aimconePenalty;
private uint cachedModHash;
private float sightAimConeScale = 1f;
private float sightAimConeOffset;
private float hipAimConeScale = 1f;
private float hipAimConeOffset;
protected bool reloadStarted;
protected bool reloadFinished;
private int fractionalInsertCounter;
private static readonly Effect reusableInstance = new Effect();
public RecoilProperties recoilProperties
{
get
{
if (!(recoil == null))
{
return recoil.GetRecoil();
}
return null;
}
}
public bool isSemiAuto => !automatic;
public override Transform MuzzleTransform => MuzzlePoint;
public override bool IsUsableByTurret => usableByTurret;
protected virtual bool CanRefundAmmo => true;
protected virtual ItemDefinition PrimaryMagazineAmmo => primaryMagazine.ammoType;
public override bool OnRpcMessage(BasePlayer player, uint rpc, Message msg)
{
using (TimeWarning.New("BaseProjectile.OnRpcMessage"))
{
if (rpc == 3168282921u && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - CLProject ");
}
using (TimeWarning.New("CLProject"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.FromOwner.Test(3168282921u, "CLProject", this, player))
{
return true;
}
if (!RPC_Server.IsActiveItem.Test(3168282921u, "CLProject", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg2 = rPCMessage;
CLProject(msg2);
}
}
catch (Exception exception)
{
Debug.LogException(exception);
player.Kick("RPC Error in CLProject");
}
}
return true;
}
if (rpc == 1720368164 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - Reload ");
}
using (TimeWarning.New("Reload"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(1720368164u, "Reload", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg3 = rPCMessage;
Reload(msg3);
}
}
catch (Exception exception2)
{
Debug.LogException(exception2);
player.Kick("RPC Error in Reload");
}
}
return true;
}
if (rpc == 240404208 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - ServerFractionalReloadInsert ");
}
using (TimeWarning.New("ServerFractionalReloadInsert"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(240404208u, "ServerFractionalReloadInsert", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg4 = rPCMessage;
ServerFractionalReloadInsert(msg4);
}
}
catch (Exception exception3)
{
Debug.LogException(exception3);
player.Kick("RPC Error in ServerFractionalReloadInsert");
}
}
return true;
}
if (rpc == 555589155 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - StartReload ");
}
using (TimeWarning.New("StartReload"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(555589155u, "StartReload", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg5 = rPCMessage;
StartReload(msg5);
}
}
catch (Exception exception4)
{
Debug.LogException(exception4);
player.Kick("RPC Error in StartReload");
}
}
return true;
}
if (rpc == 1918419884 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - SwitchAmmoTo ");
}
using (TimeWarning.New("SwitchAmmoTo"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(1918419884u, "SwitchAmmoTo", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg6 = rPCMessage;
SwitchAmmoTo(msg6);
}
}
catch (Exception exception5)
{
Debug.LogException(exception5);
player.Kick("RPC Error in SwitchAmmoTo");
}
}
return true;
}
if (rpc == 3327286961u && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - ToggleFireMode ");
}
using (TimeWarning.New("ToggleFireMode"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.CallsPerSecond.Test(3327286961u, "ToggleFireMode", this, player, 2uL))
{
return true;
}
if (!RPC_Server.IsActiveItem.Test(3327286961u, "ToggleFireMode", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg7 = rPCMessage;
ToggleFireMode(msg7);
}
}
catch (Exception exception6)
{
Debug.LogException(exception6);
player.Kick("RPC Error in ToggleFireMode");
}
}
return true;
}
}
return base.OnRpcMessage(player, rpc, msg);
}
protected bool TryReload(IAmmoContainer ammoSource, int desiredAmount, bool canRefundAmmo = true)
{
List<Item> list = ammoSource.FindItemsByItemID(primaryMagazine.ammoType.itemid);
if (list.Count == 0 && !primaryMagazine.allowAmmoSwitching)
{
return false;
}
if (list.Count == 0)
{
Item item = ammoSource.FindAmmo(primaryMagazine.definition.ammoTypes);
if (item == null)
{
return false;
}
list = ammoSource.FindItemsByItemID(item.info.itemid);
if (list == null || list.Count == 0)
{
return false;
}
if (primaryMagazine.contents > 0)
{
if (canRefundAmmo)
{
ammoSource.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
}
SetAmmoCount(0);
}
primaryMagazine.ammoType = list[0].info;
}
int num = desiredAmount;
if (num == -1)
{
num = primaryMagazine.capacity - primaryMagazine.contents;
}
foreach (Item item2 in list)
{
_ = item2.amount;
int num2 = Mathf.Min(num, item2.amount);
item2.UseItem(num2);
ModifyAmmoCount(num2);
num -= num2;
if (num <= 0)
{
break;
}
}
return true;
}
public void SwitchAmmoTypesIfNeeded(IAmmoContainer ammoSource)
{
Item item = ammoSource.FindItemByItemID(primaryMagazine.ammoType.itemid);
if (item != null)
{
return;
}
Item item2 = ammoSource.FindAmmo(primaryMagazine.definition.ammoTypes);
if (item2 == null)
{
return;
}
item = ammoSource.FindItemByItemID(item2.info.itemid);
if (item != null)
{
if (primaryMagazine.contents > 0)
{
ammoSource.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
SetAmmoCount(0);
}
primaryMagazine.ammoType = item.info;
}
}
public static void StripAmmoToType(ref List<Item> ammos, ItemDefinition onlyAllowed)
{
if (!(onlyAllowed != null))
{
return;
}
for (int num = ammos.Count - 1; num >= 0; num--)
{
if (ammos[num].info != onlyAllowed)
{
ammos.RemoveAt(num);
}
}
}
public void SetAmmoCount(int newCount)
{
primaryMagazine.contents = newCount;
Item item = GetItem();
if (item != null)
{
item.ammoCount = newCount;
item.MarkDirty();
}
}
public void ModifyAmmoCount(int amount)
{
SetAmmoCount(primaryMagazine.contents + amount);
}
public override Vector3 GetInheritedVelocity(BasePlayer player, Vector3 direction)
{
return player.GetInheritedProjectileVelocity(direction);
}
public virtual float GetDamageScale(bool getMax = false)
{
return damageScale;
}
public virtual float GetDistanceScale(bool getMax = false)
{
return distanceScale;
}
public virtual float GetProjectileVelocityScale(bool getMax = false)
{
return projectileVelocityScale;
}
public virtual float GetOverrideProjectileThickness(Projectile projectile)
{
if (projectile == null)
{
return 0f;
}
return projectile.thickness;
}
protected void StartReloadCooldown(float cooldown)
{
nextReloadTime = CalculateCooldownTime(nextReloadTime, cooldown, catchup: false, unscaledTime: true);
startReloadTime = (float)nextReloadTime - cooldown;
}
protected void ResetReloadCooldown()
{
nextReloadTime = float.NegativeInfinity;
}
protected bool HasReloadCooldown()
{
return UnityEngine.Time.unscaledTime < (float)nextReloadTime;
}
protected float GetReloadCooldown()
{
return Mathf.Max((float)nextReloadTime - UnityEngine.Time.unscaledTime, 0f);
}
protected float GetReloadIdle()
{
return Mathf.Max(UnityEngine.Time.unscaledTime - (float)nextReloadTime, 0f);
}
private void OnDrawGizmos()
{
if (base.isClient && MuzzlePoint != null)
{
Gizmos.color = Color.blue;
Gizmos.DrawLine(MuzzlePoint.position, MuzzlePoint.position + MuzzlePoint.forward * 10f);
BasePlayer ownerPlayer = GetOwnerPlayer();
if ((bool)ownerPlayer)
{
Gizmos.color = Color.cyan;
Gizmos.DrawLine(MuzzlePoint.position, MuzzlePoint.position + ownerPlayer.eyes.rotation * Vector3.forward * 10f);
}
}
}
public virtual RecoilProperties GetRecoil()
{
return recoilProperties;
}
public override float AmmoFraction()
{
return (float)primaryMagazine.contents / (float)primaryMagazine.capacity;
}
public virtual void DidAttackServerside()
{
}
public override bool ServerIsReloading()
{
return UnityEngine.Time.time < lastReloadTime + reloadTime;
}
public override bool CanReload()
{
return primaryMagazine.contents < primaryMagazine.capacity;
}
public override void TopUpAmmo()
{
SetAmmoCount(primaryMagazine.capacity);
}
public override void ServerReload()
{
if (!ServerIsReloading())
{
lastReloadTime = UnityEngine.Time.time;
StartAttackCooldown(reloadTime);
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.SignalBroadcast(Signal.Reload);
}
SetAmmoCount(primaryMagazine.capacity);
}
}
public override bool ServerTryReload(IAmmoContainer ammoSource)
{
if (ServerIsReloading())
{
return false;
}
if (TryReloadMagazine(ammoSource))
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.SignalBroadcast(Signal.Reload);
}
lastReloadTime = UnityEngine.Time.time;
StartAttackCooldown(reloadTime);
return true;
}
return false;
}
public override Vector3 ModifyAIAim(Vector3 eulerInput, float swayModifier = 1f)
{
float num = UnityEngine.Time.time * (aimSwaySpeed * 1f + aiAimSwayOffset);
float num2 = Mathf.Sin(UnityEngine.Time.time * 2f);
float num3 = ((num2 < 0f) ? (1f - Mathf.Clamp(Mathf.Abs(num2) / 1f, 0f, 1f)) : 1f);
float num4 = (false ? 0.6f : 1f);
float num5 = (aimSway * 1f + aiAimSwayOffset) * num4 * num3 * swayModifier;
eulerInput.y += (Mathf.PerlinNoise(num, num) - 0.5f) * num5 * UnityEngine.Time.deltaTime;
eulerInput.x += (Mathf.PerlinNoise(num + 0.1f, num + 0.2f) - 0.5f) * num5 * UnityEngine.Time.deltaTime;
return eulerInput;
}
public float GetAIAimcone()
{
NPCPlayer nPCPlayer = GetOwnerPlayer() as NPCPlayer;
if ((bool)nPCPlayer)
{
return nPCPlayer.GetAimConeScale() * aiAimCone;
}
return aiAimCone;
}
public override void ServerUse()
{
ServerUse(1f);
}
public override void ServerUse(float damageModifier, Transform originOverride = null, bool useBulletThickness = true)
{
if (base.isClient || HasAttackCooldown())
{
return;
}
BasePlayer ownerPlayer = GetOwnerPlayer();
bool flag = ownerPlayer != null;
if (primaryMagazine.contents <= 0)
{
SignalBroadcast(Signal.DryFire);
StartAttackCooldownRaw(1f);
return;
}
ModifyAmmoCount(-1);
if (primaryMagazine.contents < 0)
{
SetAmmoCount(0);
}
bool flag2 = flag && ownerPlayer.IsNpc;
if (flag2 && (ownerPlayer.isMounted || ownerPlayer.GetParentEntity() != null))
{
NPCPlayer nPCPlayer = ownerPlayer as NPCPlayer;
if (nPCPlayer != null)
{
nPCPlayer.SetAimDirection(nPCPlayer.GetAimDirection());
}
}
StartAttackCooldownRaw(repeatDelay);
Vector3 vector = (flag ? ownerPlayer.eyes.position : MuzzlePoint.transform.position);
Vector3 inputVec = MuzzlePoint.transform.forward;
if (originOverride != null)
{
vector = originOverride.position;
inputVec = originOverride.forward;
}
ItemModProjectile component = primaryMagazine.ammoType.GetComponent<ItemModProjectile>();
SignalBroadcast(Signal.Attack, string.Empty, null, GetAttackEffect());
Projectile component2 = component.projectileObject.Get().GetComponent<Projectile>();
bool flag3 = GetParentEntity() is BasePlayer;
BaseEntity baseEntity = null;
if (flag)
{
inputVec = ownerPlayer.eyes.BodyForward();
}
for (int i = 0; i < component.numProjectiles; i++)
{
Vector3 vector2 = ((!flag2) ? AimConeUtil.GetModifiedAimConeDirection(component.projectileSpread + GetAimCone(), inputVec) : AimConeUtil.GetModifiedAimConeDirection(component.projectileSpread + GetAimCone() + GetAIAimcone(), inputVec));
float radius = (useBulletThickness ? GetOverrideProjectileThickness(component2) : 0f);
List<RaycastHit> obj = Facepunch.Pool.Get<List<RaycastHit>>();
GamePhysics.TraceAll(new Ray(vector, vector2), radius, obj, 300f, 1220225793, QueryTriggerInteraction.Ignore, ownerPlayer);
for (int j = 0; j < obj.Count; j++)
{
RaycastHit hit = obj[j];
BaseEntity entity = RaycastHitEx.GetEntity(hit);
if (flag3)
{
if (entity != null && (entity == this || entity.EqualNetID(this)))
{
continue;
}
}
else if (entity != null && this.HasEntityInParents(entity))
{
continue;
}
if (entity != null && entity.isClient)
{
continue;
}
ColliderInfo component3 = hit.collider.GetComponent<ColliderInfo>();
if (component3 != null && !component3.HasFlag(ColliderInfo.Flags.Shootable))
{
continue;
}
BaseCombatEntity baseCombatEntity = entity as BaseCombatEntity;
if ((!(entity != null && entity.IsNpc && flag2) || baseCombatEntity.GetFaction() == BaseCombatEntity.Faction.Horror || entity is BasePet) && baseCombatEntity != null && (baseEntity == null || entity == baseEntity || entity.EqualNetID(baseEntity)) && baseCombatEntity.IsVisible(vector, hit.point, 300f))
{
HitInfo hitInfo = new HitInfo();
AssignInitiator(hitInfo);
hitInfo.Weapon = this;
hitInfo.WeaponPrefab = base.gameManager.FindPrefab(base.PrefabName).GetComponent<AttackEntity>();
hitInfo.IsPredicting = false;
hitInfo.DoHitEffects = component2.doDefaultHitEffects;
hitInfo.DidHit = true;
hitInfo.ProjectileVelocity = vector2 * 300f;
hitInfo.PointStart = MuzzlePoint.position;
hitInfo.PointEnd = hit.point;
hitInfo.HitPositionWorld = hit.point;
hitInfo.HitNormalWorld = hit.normal;
hitInfo.HitEntity = entity;
hitInfo.UseProtection = true;
component2.CalculateDamage(hitInfo, GetProjectileModifier(), 1f);
hitInfo.damageTypes.ScaleAll(GetDamageScale() * damageModifier * (flag2 ? npcDamageScale : turretDamageScale));
baseCombatEntity.OnAttacked(hitInfo);
component.ServerProjectileHit(hitInfo);
if (entity is BasePlayer || entity is BaseNpc)
{
hitInfo.HitPositionLocal = entity.transform.InverseTransformPoint(hitInfo.HitPositionWorld);
hitInfo.HitNormalLocal = entity.transform.InverseTransformDirection(hitInfo.HitNormalWorld);
hitInfo.HitMaterial = StringPool.Get("Flesh");
Effect.server.ImpactEffect(hitInfo);
}
if (!(entity != null) || entity.ShouldBlockProjectiles())
{
break;
}
}
}
Facepunch.Pool.FreeUnmanaged(ref obj);
Vector3 vector3 = ((flag && ownerPlayer.isMounted) ? (vector2 * 6f) : Vector3.zero);
CreateProjectileEffectClientside(component.projectileObject.resourcePath, vector + vector3, vector2 * component.projectileVelocity, UnityEngine.Random.Range(1, 100), null, IsSilenced(), forceClientsideEffects: true);
}
}
private void AssignInitiator(HitInfo info)
{
info.Initiator = GetOwnerPlayer();
if (info.Initiator == null)
{
info.Initiator = GetParentEntity();
}
}
public override void ServerInit()
{
base.ServerInit();
primaryMagazine.ServerInit();
Invoke(DelayedModSetup, 0.1f);
}
public void DelayedModSetup()
{
if (!modsChangedInitialized)
{
Item item = GetCachedItem();
if (item != null && item.contents != null)
{
ItemContainer contents = item.contents;
contents.onItemAddedRemoved = (Action<Item, bool>)Delegate.Combine(contents.onItemAddedRemoved, new Action<Item, bool>(ModsChanged));
modsChangedInitialized = true;
}
}
}
public override void DestroyShared()
{
if (base.isServer)
{
Item item = GetCachedItem();
if (item != null && item.contents != null)
{
ItemContainer contents = item.contents;
contents.onItemAddedRemoved = (Action<Item, bool>)Delegate.Remove(contents.onItemAddedRemoved, new Action<Item, bool>(ModsChanged));
modsChangedInitialized = false;
}
}
base.DestroyShared();
}
public void ModsChanged(Item item, bool added)
{
Invoke(DelayedModsChanged, 0.1f);
}
public void ForceModsChanged()
{
Invoke(DelayedModSetup, 0f);
Invoke(DelayedModsChanged, 0.2f);
}
public void DelayedModsChanged()
{
if (Interface.CallHook("OnWeaponModChange", this, GetOwnerPlayer()) != null)
{
return;
}
int num = Mathf.CeilToInt(ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.magazineCapacity, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * (float)primaryMagazine.definition.builtInSize);
if (num == primaryMagazine.capacity)
{
return;
}
if (primaryMagazine.contents > 0 && primaryMagazine.contents > num)
{
_ = primaryMagazine.ammoType;
int contents = primaryMagazine.contents;
BasePlayer ownerPlayer = GetOwnerPlayer();
ItemContainer itemContainer = null;
if (ownerPlayer != null)
{
itemContainer = ownerPlayer.inventory.containerMain;
}
else if (GetCachedItem() != null)
{
itemContainer = GetCachedItem().parent;
}
SetAmmoCount(0);
if (itemContainer != null)
{
Item item = ItemManager.Create(primaryMagazine.ammoType, contents, 0uL);
if (!item.MoveToContainer(itemContainer))
{
Vector3 vPos = base.transform.position;
if (itemContainer.entityOwner != null)
{
vPos = itemContainer.entityOwner.transform.position + Vector3.up * 0.25f;
}
item.Drop(vPos, Vector3.up * 5f);
}
}
}
primaryMagazine.capacity = num;
SendNetworkUpdate();
}
public override void ServerCommand(Item item, string command, BasePlayer player)
{
if (item != null && command == "unload_ammo" && !HasReloadCooldown())
{
UnloadAmmo(item, player);
}
}
public void UnloadAmmo(Item item, BasePlayer player)
{
BaseProjectile component = item.GetHeldEntity().GetComponent<BaseProjectile>();
if (!component.canUnloadAmmo || Interface.CallHook("OnAmmoUnload", component, item, player) != null || !component)
{
return;
}
int num = component.primaryMagazine.contents;
if (num <= 0)
{
return;
}
component.SetAmmoCount(0);
item.MarkDirty();
SendNetworkUpdateImmediate();
int stackable = component.primaryMagazine.ammoType.stackable;
if (num > stackable)
{
int num2 = Mathf.FloorToInt(num / component.primaryMagazine.ammoType.stackable);
num %= stackable;
for (int i = 0; i < num2; i++)
{
Item item2 = ItemManager.Create(component.primaryMagazine.ammoType, stackable, 0uL);
player.GiveItem(item2);
}
}
if (num > 0)
{
Item item3 = ItemManager.Create(component.primaryMagazine.ammoType, num, 0uL);
player.GiveItem(item3);
}
}
public override void CollectedForCrafting(Item item, BasePlayer crafter)
{
if (!(crafter == null) && item != null)
{
UnloadAmmo(item, crafter);
}
}
public override void ReturnedFromCancelledCraft(Item item, BasePlayer crafter)
{
if (!(crafter == null) && item != null)
{
BaseProjectile component = item.GetHeldEntity().GetComponent<BaseProjectile>();
if ((bool)component)
{
component.SetAmmoCount(0);
}
}
}
public override void SetLightsOn(bool isOn)
{
base.SetLightsOn(isOn);
UpdateAttachmentsState();
}
public void UpdateAttachmentsState()
{
_ = flags;
bool b = ShouldLightsBeOn();
if (children == null)
{
return;
}
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.isLight)
{
projectileWeaponMod.SetFlag(Flags.On, b);
}
}
}
private bool ShouldLightsBeOn()
{
if (LightsOn())
{
if (!IsDeployed())
{
return parentEntity.Get(base.isServer) is AutoTurret;
}
return true;
}
return false;
}
protected override void OnChildRemoved(BaseEntity child)
{
base.OnChildRemoved(child);
if (child is ProjectileWeaponMod projectileWeaponMod && projectileWeaponMod.isLight)
{
child.SetFlag(Flags.On, b: false);
SetLightsOn(isOn: false);
}
}
public bool CanAiAttack()
{
return true;
}
public virtual float GetAimCone()
{
uint num = 0u;
foreach (BaseEntity child in children)
{
num += (uint)(int)child.net.ID.Value;
num += (uint)child.flags;
}
uint num2 = CRC.Compute32(0u, num);
if (num2 != cachedModHash)
{
sightAimConeScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.sightAimCone, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
sightAimConeOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.sightAimCone, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
hipAimConeScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.hipAimCone, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
hipAimConeOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.hipAimCone, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
cachedModHash = num2;
}
float num3 = aimCone;
num3 *= (UsingInternalBurstMode() ? internalBurstAimConeScale : 1f);
if (recoilProperties != null && recoilProperties.overrideAimconeWithCurve && primaryMagazine.capacity > 0)
{
num3 += recoilProperties.aimconeCurve.Evaluate((float)numShotsFired / (float)primaryMagazine.capacity % 1f) * recoilProperties.aimconeCurveScale;
aimconePenalty = 0f;
}
if (aiming || base.isServer)
{
return (num3 + aimconePenalty + stancePenalty * stancePenaltyScale) * sightAimConeScale + sightAimConeOffset;
}
return (num3 + aimconePenalty + stancePenalty * stancePenaltyScale) * sightAimConeScale + sightAimConeOffset + hipAimCone * hipAimConeScale + hipAimConeOffset;
}
public float ScaleRepeatDelay(float delay)
{
float num = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.repeatDelay, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
float num2 = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.repeatDelay, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
float num3 = (UsingInternalBurstMode() ? internalBurstFireRateScale : 1f);
return delay * num * num3 + num2;
}
public Projectile.Modifier GetProjectileModifier()
{
Projectile.Modifier result = default(Projectile.Modifier);
result.damageOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.projectileDamage, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
result.damageScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.projectileDamage, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * GetDamageScale();
result.distanceOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.projectileDistance, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
result.distanceScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.projectileDistance, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * GetDistanceScale();
return result;
}
public bool UsingBurstMode()
{
if (IsBurstDisabled())
{
return false;
}
return IsBurstEligable();
}
public bool UsingInternalBurstMode()
{
if (IsBurstDisabled())
{
return false;
}
return isBurstWeapon;
}
public bool IsBurstEligable()
{
if (isBurstWeapon)
{
return true;
}
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.burstCount > 0)
{
return true;
}
}
}
return false;
}
public float TimeBetweenBursts()
{
return repeatDelay * 2f;
}
public virtual bool CanAttack()
{
if (ProjectileWeaponMod.HasBrokenWeaponMod(this))
{
return false;
}
return true;
}
public float GetReloadDuration()
{
if (fractionalReload)
{
int num = Mathf.Min(primaryMagazine.capacity - primaryMagazine.contents, GetAvailableAmmo());
return reloadStartDuration + reloadEndDuration + reloadFractionDuration * (float)num;
}
return reloadTime;
}
public int GetAvailableAmmo()
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null)
{
return primaryMagazine.contents;
}
List<Item> obj = Facepunch.Pool.Get<List<Item>>();
ownerPlayer.inventory.FindAmmo(obj, primaryMagazine.definition.ammoTypes);
int num = 0;
if (obj.Count != 0)
{
for (int i = 0; i < obj.Count; i++)
{
Item item = obj[i];
if (item.info == primaryMagazine.ammoType)
{
num += item.amount;
}
}
}
Facepunch.Pool.Free(ref obj, freeElements: false);
return num;
}
public bool IsBurstDisabled()
{
return HasFlag(Flags.Reserved6) == defaultOn;
}
[RPC_Server]
[RPC_Server.IsActiveItem]
[RPC_Server.CallsPerSecond(2uL)]
private void ToggleFireMode(RPCMessage msg)
{
if (canChangeFireModes && IsBurstEligable())
{
SetFlag(Flags.Reserved6, !HasFlag(Flags.Reserved6));
SendNetworkUpdate_Flags();
Facepunch.Rust.Analytics.Azure.OnBurstModeToggled(msg.player, this, HasFlag(Flags.Reserved6));
}
}
public virtual bool TryReloadMagazine(IAmmoContainer ammoSource, int desiredAmount = -1)
{
object obj = Interface.CallHook("OnMagazineReload", this, ammoSource, GetOwnerPlayer());
if (obj is bool)
{
return (bool)obj;
}
if (!TryReload(ammoSource, desiredAmount))
{
return false;
}
SendNetworkUpdateImmediate();
ItemManager.DoRemoves();
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.inventory.ServerUpdate(0f);
}
return true;
}
[RPC_Server]
[RPC_Server.IsActiveItem]
private void SwitchAmmoTo(RPCMessage msg)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (!ownerPlayer)
{
return;
}
int num = msg.read.Int32();
if (num == primaryMagazine.ammoType.itemid)
{
return;
}
ItemDefinition itemDefinition = ItemManager.FindItemDefinition(num);
if (itemDefinition == null)
{
return;
}
ItemModProjectile component = itemDefinition.GetComponent<ItemModProjectile>();
if ((bool)component && component.IsAmmo(primaryMagazine.definition.ammoTypes) && Interface.CallHook("OnAmmoSwitch", this, ownerPlayer, itemDefinition) == null)
{
if (primaryMagazine.contents > 0)
{
ownerPlayer.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
SetAmmoCount(0);
}
primaryMagazine.ammoType = itemDefinition;
SendNetworkUpdateImmediate();
ItemManager.DoRemoves();
ownerPlayer.inventory.ServerUpdate(0f);
}
}
public override void OnHeldChanged()
{
base.OnHeldChanged();
reloadStarted = false;
reloadFinished = false;
fractionalInsertCounter = 0;
UpdateAttachmentsState();
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void StartReload(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
}
else if (Interface.CallHook("OnWeaponReload", this, player) == null)
{
reloadFinished = false;
reloadStarted = true;
fractionalInsertCounter = 0;
if (CanRefundAmmo)
{
SwitchAmmoTypesIfNeeded(player.inventory);
}
OnReloadStarted();
StartReloadCooldown(GetReloadDuration());
}
}
protected virtual void OnReloadStarted()
{
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void ServerFractionalReloadInsert(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
return;
}
if (!fractionalReload)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload not allowed (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_type");
return;
}
if (!reloadStarted)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload request skipped (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_skip");
reloadStarted = false;
reloadFinished = false;
return;
}
if (GetReloadIdle() > 3f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T+" + GetReloadIdle() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
if (UnityEngine.Time.unscaledTime < (float)startReloadTime + reloadStartDuration)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload too early (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_fraction_too_early");
reloadStarted = false;
reloadFinished = false;
}
if (UnityEngine.Time.unscaledTime < (float)startReloadTime + reloadStartDuration + (float)fractionalInsertCounter * reloadFractionDuration)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload rate too high (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_fraction_rate");
reloadStarted = false;
reloadFinished = false;
}
else
{
fractionalInsertCounter++;
if (primaryMagazine.contents < primaryMagazine.capacity)
{
TryReloadMagazine(player.inventory, 1);
}
}
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void Reload(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
return;
}
if (!reloadStarted)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Request skipped (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_skip");
reloadStarted = false;
reloadFinished = false;
return;
}
if (!fractionalReload)
{
if (GetReloadCooldown() > 1f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T-" + GetReloadCooldown() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
if (GetReloadIdle() > 1.5f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T+" + GetReloadIdle() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
}
if (fractionalReload)
{
ResetReloadCooldown();
}
reloadStarted = false;
reloadFinished = true;
if (!fractionalReload)
{
TryReloadMagazine(player.inventory);
}
}
[RPC_Server.FromOwner]
[RPC_Server.IsActiveItem]
[RPC_Server]
private void CLProject(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientAttack(player))
{
SendNetworkUpdate();
return;
}
if (reloadFinished && HasReloadCooldown())
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Reloading (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_cooldown");
return;
}
reloadStarted = false;
reloadFinished = false;
if (primaryMagazine.contents <= 0 && !base.UsingInfiniteAmmoCheat)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Magazine empty (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "ammo_missing");
return;
}
ItemDefinition primaryMagazineAmmo = PrimaryMagazineAmmo;
ProjectileShoot projectileShoot = ProjectileShoot.Deserialize(msg.read);
if (primaryMagazineAmmo.itemid != projectileShoot.ammoType)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Ammo mismatch (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "ammo_mismatch");
return;
}
if (!base.UsingInfiniteAmmoCheat)
{
ModifyAmmoCount(-1);
}
ItemModProjectile component = primaryMagazineAmmo.GetComponent<ItemModProjectile>();
if (component == null)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Item mod not found (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "mod_missing");
return;
}
if (projectileShoot.projectiles.Count > component.numProjectiles)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Count mismatch (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "count_mismatch");
return;
}
Interface.CallHook("OnWeaponFired", this, msg.player, component, projectileShoot);
if (player.InGesture)
{
return;
}
SignalBroadcast(Signal.Attack, string.Empty, msg.connection, GetAttackEffect());
player.CleanupExpiredProjectiles();
Guid projectileGroupId = Guid.NewGuid();
foreach (ProjectileShoot.Projectile projectile in projectileShoot.projectiles)
{
if (player.HasFiredProjectile(projectile.projectileID))
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Duplicate ID (" + projectile.projectileID + ")");
player.stats.combat.LogInvalid(player, this, "duplicate_id");
continue;
}
Vector3 positionOffset = Vector3.zero;
if (ConVar.AntiHack.projectile_positionoffset && (player.isMounted || player.HasParent()))
{
if (!ValidateEyePos(player, projectile.startPos, checkLineOfSight: false))
{
continue;
}
Vector3 position = player.eyes.position;
positionOffset = position - projectile.startPos;
projectile.startPos = position;
}
else if (!ValidateEyePos(player, projectile.startPos))
{
continue;
}
player.NoteFiredProjectile(projectile.projectileID, projectile.startPos, projectile.startVel, this, primaryMagazineAmmo, projectileGroupId, positionOffset);
if (!player.limitNetworking)
{
CreateProjectileEffectClientside(component.projectileObject.resourcePath, projectile.startPos, projectile.startVel, projectile.seed, msg.connection, IsSilenced());
}
}
player.MakeNoise(player.transform.position, BaseCombatEntity.ActionVolume.Loud);
SingletonComponent<NpcNoiseManager>.Instance.OnWeaponShot(player, this);
player.stats.Add(component.category + "_fired", projectileShoot.projectiles.Count(), (Stats)5);
player.LifeStoryShotFired(this);
StartAttackCooldown(ScaleRepeatDelay(repeatDelay) + animationDelay);
player.MarkHostileFor();
UpdateItemCondition();
DidAttackServerside();
BaseMountable mounted = player.GetMounted();
if (mounted != null)
{
mounted.OnWeaponFired(this);
}
EACServer.LogPlayerUseWeapon(player, this);
}
public void CreateProjectileEffectClientside(string prefabName, Vector3 pos, Vector3 velocity, int seed, Connection sourceConnection, bool silenced = false, bool forceClientsideEffects = false, List<Connection> targets = null)
{
if (Interface.CallHook("OnClientProjectileEffectCreate", sourceConnection, this, prefabName) == null)
{
Effect effect = reusableInstance;
effect.Clear();
effect.Init(Effect.Type.Projectile, pos, velocity, sourceConnection);
effect.scale = (silenced ? 0f : 1f);
if (forceClientsideEffects)
{
effect.scale = 2f;
}
effect.pooledString = prefabName;
effect.number = seed;
effect.targets = targets;
EffectNetwork.Send(effect);
}
}
public void UpdateItemCondition()
{
Item ownerItem = GetOwnerItem();
if (ownerItem == null)
{
return;
}
float barrelConditionLoss = primaryMagazine.ammoType.GetComponent<ItemModProjectile>().barrelConditionLoss;
float num = 0.25f;
bool usingInfiniteAmmoCheat = base.UsingInfiniteAmmoCheat;
if (!usingInfiniteAmmoCheat)
{
ownerItem.LoseCondition(num + barrelConditionLoss);
}
if (ownerItem.contents == null || ownerItem.contents.itemList == null)
{
return;
}
for (int num2 = ownerItem.contents.itemList.Count - 1; num2 >= 0; num2--)
{
Item item = ownerItem.contents.itemList[num2];
if (item != null && !usingInfiniteAmmoCheat)
{
item.LoseCondition(num + barrelConditionLoss);
}
}
}
public bool IsSilenced()
{
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.isSilencer && !projectileWeaponMod.IsBroken())
{
return true;
}
}
}
return false;
}
public string GetAttackEffectAdditive()
{
string result = "";
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (!(projectileWeaponMod == null) && projectileWeaponMod.additiveEffect.isValid)
{
result = projectileWeaponMod.additiveEffect.resourcePath;
break;
}
}
}
return result;
}
protected string GetAttackEffect()
{
string resourcePath = attackFX.resourcePath;
if (primaryMagazine.ammoType != null)
{
ItemModProjectile component = primaryMagazine.ammoType.GetComponent<ItemModProjectile>();
if (component.attackEffectOverride.isValid)
{
resourcePath = component.attackEffectOverride.resourcePath;
}
}
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod == null)
{
continue;
}
if (projectileWeaponMod.isSilencer)
{
resourcePath = projectileWeaponMod.defaultSilencerEffect.resourcePath;
if (silencedAttack.isValid)
{
resourcePath = silencedAttack.resourcePath;
}
break;
}
if (projectileWeaponMod.isMuzzleBrake)
{
if (muzzleBrakeAttack.isValid)
{
resourcePath = muzzleBrakeAttack.resourcePath;
}
break;
}
}
}
return resourcePath;
}
public override bool CanUseNetworkCache(Connection sendingTo)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null || ownerPlayer.net == null)
{
return true;
}
if (ownerPlayer.IsBeingSpectated)
{
return false;
}
Connection connection = ownerPlayer.net.connection;
if (sendingTo == null || connection == null)
{
return true;
}
return sendingTo != connection;
}
public override void Save(SaveInfo info)
{
base.Save(info);
info.msg.baseProjectile = Facepunch.Pool.Get<ProtoBuf.BaseProjectile>();
if (info.forDisk || info.SendingTo(GetOwnerConnection()) || ForceSendMagazine(info))
{
info.msg.baseProjectile.primaryMagazine = primaryMagazine.Save();
}
}
public virtual bool ForceSendMagazine(SaveInfo saveInfo)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if ((bool)ownerPlayer && ownerPlayer.IsBeingSpectated)
{
foreach (BaseEntity child in ownerPlayer.children)
{
if (child.net != null && child.net.connection == saveInfo.forConnection)
{
return true;
}
}
}
return false;
}
public override void Load(LoadInfo info)
{
base.Load(info);
if (info.msg.baseProjectile != null && info.msg.baseProjectile.primaryMagazine != null)
{
primaryMagazine.Load(info.msg.baseProjectile.primaryMagazine);
}
}
}
#if false // Decompilation log
DelayedModsChanged Logic in BaseProjectile Class:
The DelayedModsChanged method already calculates the magazine's capacity when attachments are added or modified. Ensure that this method is executing properly by printing out debug logs and checking whether the primaryMagazine.capacity property changes when an extended magazine is attached.
Debugging DelayedModsChanged:
Add print statements to confirm the calculation and capacity application when modifications are applied.
csharp
public void DelayedModsChanged()
{
int originalCapacity = primaryMagazine.capacity;
if (Interface.CallHook("OnWeaponModChange", this, GetOwnerPlayer()) != null)
{
return;
}
primaryMagazine.capacity =
Mathf.CeilToInt(
ProjectileWeaponMod.Mult(
this,
(ProjectileWeaponMod x) => x.magazineCapacity,
(ProjectileWeaponMod.Modifier y) => y.scalar,
1f
) * (float)primaryMagazine.definition.builtInSize
);
PrintWarning($"[DEBUG] Weapon mod changed: Original capacity: {originalCapacity}, New capacity: {primaryMagazine.capacity}");
SendNetworkUpdate(); // Ensure updated values are propagated
}
When the DelayedModsChanged method fires, it should automatically account for magazine modifications like extended magazines, adjusting the capacity dynamically. Verify if this behavior is working as expected by attaching debug logs or checking the in-game behavior.
Summary of Changes
In the Plugin Code (TurboWeapons):
Ensure that capacity is updated ONLY for players with appropriate permissions (turboweapons.customcapacity).
Allow the weapon's normal behavior (via DelayedModsChanged) to handle capacity changes when items like extended magazines are attached for players who lack the plugin's custom permission.
In the BaseProjectile Class:
Debug the DelayedModsChanged method to ensure mods like extended magazines are properly adjusting the magazine capacity.
Confirm that the overridden capacity logic in DelayedModsChanged is ONLY being reset when necessary (e.g., dropping excess bullets, etc.).
After implementing these changes, test the following scenarios:
Players with the permission can use custom capacities without interference from extended magazines.
Players without the permission see their capacity increase normally when attaching extended magazines.
Let me know how this goes or if you encounter further issues! 😊
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
// Tenta obter a arma atualmente equipada pelo jogador
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
// Obtém a configuração específica da arma (personalizada pelo plugin)
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Obter a capacidade desejada:
// Se o jogador **não** tiver permissão para capacidade customizada (turboweapons.customcapacity),
// simplesmente mantenha o comportamento padrão do jogo e não sobrescreva nada.
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Permitir que o comportamento normal do jogo (e o DelayedModsChanged) gerencie as capacidades
return;
}
// Caso o jogador tenha permissão, vamos calcular a capacidade personalizada que deve ser aplicada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
// Verifica se já está tudo configurado corretamente
if (weapon.primaryMagazine.capacity == desiredCapacity)
return;
// Se a capacidade configurada (desiredCapacity) for menor que o conteúdo atual,
// remova a munição extra.
if (weapon.primaryMagazine.contents > desiredCapacity)
{
// Calcula munição excedente
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
// Devolver munição removida ao inventário do jogador
if (weapon.primaryMagazine.ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
// Notificar jogador sobre nova capacidade
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
// Ajustar a capacidade do carregador (magazine) para o valor desejado
AdjustMagazineCapacity(weapon, desiredCapacity);
// Atualizar arma e jogador no servidor e cliente
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
Explicação do Método
Verifica se o jogador possui permissão para capacidade personalizada:
Se o jogador não tiver a permissão turboweapons.customcapacity, o método retorna imediatamente, permitindo que o comportamento padrão do jogo (incluindo o método DelayedModsChanged) assuma o controle.
Capacidade desejada:
O método calcula a capacidade desejada para jogadores que possuem permissão, usando o método já existente CalculateDesiredCapacity.
Verifica se a capacidade já está configurada corretamente:
Evita reconfigurações desnecessárias ao verificar se weapon.primaryMagazine.capacity já é igual à capacidade personalizada esperada.
Remove munição excedente, se necessário:
Se o carregador da arma (weapon.primaryMagazine) atualmente contém mais munição do que a capacidade configurada, a munição excedente é devolvida ao inventário do jogador.
Atualiza a capacidade do carregador da arma:
Chama AdjustMagazineCapacity para ajustar o carregador ao valor correto.
Envia atualizações para o jogador e a rede:
Atualiza o estado da arma e do jogador, tanto no servidor quanto nos clientes conectados, para garantir que as mudanças sejam imediatamente visíveis.
Métodos Auxiliares (Dependências)
Aqui estão os outros métodos necessários para o funcionamento do UpdateWeaponCapacityForPlayer:
CalculateDesiredCapacity
Já citado anteriormente, este método decide a capacidade desejada com base na permissão do jogador e na configuração da arma.
csharp
private int CalculateDesiredCapacity(BasePlayer player, BaseProjectile weapon, WeaponConfiguration config)
{
// Capacidade personalizada apenas para jogadores com a permissão.
return HasPermission(player, UseCustomCapacityPermission) ? config.MagazineCapacity : GetDefaultCapacity(weapon.GetItem()?.info?.shortname);
}
AdjustMagazineCapacity
Este método aplica a capacidade calculada ao carregador da arma.
Este método retorna a capacidade padrão da arma, excluindo qualquer personalização.
csharp
private int GetDefaultCapacity(string shortname)
{
return defaultCapacities.TryGetValue(shortname, out var capacity) ? capacity : 0;
}
Teste e Considerações
Jogadores sem permissão:
Certifique-se de que jogadores no grupo default conseguem usar acessórios (como o extended mag) e que as capacidades são ajustadas corretamente pelo comportamento padrão do jogo.
Teste removendo munição excedente ao trocar para uma capacidade menor.
Jogadores com permissão:
Verifique se eles podem configurar capacidades personalizadas sem que os acessórios do jogo interfiram nas configurações do plugin.
Comportamento Geral:
Confirme que a lógica não entra em conflito com o método DelayedModsChanged interno do jogo.
Certifique-se de que o servidor e os clientes sincronizem as capacidades corretamente para todas as modificações.
Caso algo ainda não funcione como esperado, envie mais detalhes sobre o comportamento ou áreas que precisam de ajustes. Vou continuar te ajudando! 😊
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
// Obtém a configuração específica da arma do plugin (se existir)
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Obtém a capacidade padrão do jogo (built-in)
int defaultCapacity = GetDefaultCapacity(weapon.GetItem()?.info?.shortname);
// 1. Jogadores sem permissão: Reseta a capacidade para o padrão do jogo
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Se a capacidade atual for diferente da capacidade padrão, reseta
if (weapon.primaryMagazine.capacity != defaultCapacity)
{
// Ajusta a capacidade de volta para o valor padrão do jogo
weapon.primaryMagazine.capacity = defaultCapacity;
// Remove munição excedente caso necessário
if (weapon.primaryMagazine.contents > defaultCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - defaultCapacity;
weapon.primaryMagazine.contents = defaultCapacity;
if (weapon.primaryMagazine.ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
}
// Atualiza a rede para refletir as mudanças
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
// Retorna, porque não há mais nada a fazer
return;
}
// 2. Jogadores com permissão: Aplicar capacidade personalizada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
// Caso já esteja configurado, não faça nada
if (weapon.primaryMagazine.capacity == desiredCapacity)
return;
// Se o carregador tiver munição além da capacidade configurada, remover excesso
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
// Devolver munição excedente ao inventário
if (weapon.primaryMagazine.ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
// Notifique o jogador da capacidade alterada
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
// Ajuste a capacidade do carregador
AdjustMagazineCapacity(weapon, desiredCapacity);
// Atualização do estado da arma para o cliente e o servidor
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
Explicação das Alterações
Verificação de Permissão:
O método verifica primeiro se o jogador tem ou não permissão para capacidade personalizada:
csharp
if (!HasPermission(player, UseCustomCapacityPermission))
Restauração da Capacidade Padrão:
Se o jogador não tiver permissão, o método força a arma a usar o valor de capacidade padrão do jogo (builtInSize), removendo qualquer ajuste personalizado, incluindo funcionalidades de DelayedModsChanged ou do plugin anterior.
Também lida com munições excedentes ao devolver as sobras para o inventário do jogador.
csharp
if (weapon.primaryMagazine.capacity != defaultCapacity)
{
weapon.primaryMagazine.capacity = defaultCapacity;
if (weapon.primaryMagazine.contents > defaultCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - defaultCapacity;
weapon.primaryMagazine.contents = defaultCapacity;
player.inventory.GiveItem(ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
Jogadores com Permissão:
Para jogadores que ainda possuem a permissão turboweapons.customcapacity, segue a lógica normal de ajuste de capacidade personalizada.
Atualizações da Rede:
O método garante que qualquer alteração na capacidade ou no número de munições dentro da arma seja enviada ao servidor e sincronizada com os clientes conectados:
Jogadores Sem Permissão (turboweapons.customcapacity):
Remova a permissão de um jogador que já tenha armas com capacidade personalizada maior.
Verifique se a arma volta a usar a capacidade padrão do jogo.
Certifique-se de que munição excedente seja devolvida ao inventário do jogador.
Jogadores Com Permissão (turboweapons.customcapacity):
Dê a permissão a um jogador e configure capacidade personalizada.
Verifique se as mudanças são aplicadas corretamente e se as notificações aparecem.
Transições Entre Estados:
Altere jogadores entre os estados com permissão e sem permissão.
Certifique-se de que as capacidades sejam restauradas adequadamente em cada caso.
Essa abordagem deve garantir que a capacidade padrão do jogo seja respeitada para jogadores sem permissão, e que jogadores com permissão possam usufruir das capacidades personalizadas. Se algo ainda não funcionar como esperado, basta compartilhar mais detalhes e continuamos ajustando! 😊
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
// Obtém a configuração do plugin para a arma (se presente)
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Obtém a capacidade padrão da arma (valor built-in)
int defaultCapacity = GetDefaultCapacity(weapon.GetItem()?.info?.shortname);
// 1. Jogadores sem permissão: Não interferir!
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Caso a capacidade da arma já esteja definida no valor padrão do jogo
// ou caso o DelayedModsChanged (como o efeito do Extended Mag) já ajustou,
// não sobrescrevemos nada.
return;
}
// 2. Jogadores com permissão: Aplicar lógica personalizada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
// Apenas altera se o valor atual for diferente do desejado
if (weapon.primaryMagazine.capacity != desiredCapacity)
{
// Ajusta a capacidade desejada
weapon.primaryMagazine.capacity = desiredCapacity;
// Remove munição adicional se necessário
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
// Devolver munição excluída ao inventário do jogador
if (weapon.primaryMagazine.ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
// Notifique o jogador da nova capacidade
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
// Atualiza o estado da rede para o cliente e servidor
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
}
Alterações Explicadas
1. Jogadores Sem Permissão
O sistema padrão do jogo deve assumir o controle total. Isso significa:
Não sobrescrever manualmente a capacidade quando o jogador não tem a permissão.
Permitir que acessórios como Extended Mag ou outros modificadores do Rust ajustem a capacidade automaticamente via DelayedModsChanged.
Simplesmente retornamos do método sem alterar a capacidade nesses casos:
csharp
if (!HasPermission(player, UseCustomCapacityPermission))
{
return;
}
2. Jogadores Com Permissão
Para usuários que possuem a permissão, continuamos aplicando as funcionalidades personalizadas do plugin:
Calcula a desiredCapacity com base na configuração customizada.
Garante que a capacidade atual (primaryMagazine.capacity) corresponda ao valor desejado.
Remove munição excedente, caso o carregador da arma esteja com mais munição do que deveria.
Teste de Cenários
Jogadores Sem Permissão:
Com Extended Mag: A arma deve ter sua capacidade ajustada corretamente para o valor padrão do jogo aumentado pelo Extended Mag.
Sem Extended Mag: A arma deve ter a capacidade padrão (builtInSize) configurada pelo jogo.
Jogadores Com Permissão:
A capacidade da arma deve obedecer ao valor configurado pelo plugin, ignorando qualquer modificação feita pelo Extended Mag.
Mudança de Estado da Permissão:
Quando a permissão turboweapons.customcapacity é removida, a arma do jogador deve voltar ao comportamento padrão do jogo (com suporte para acessórios como Extended Mag).
Quando a permissão é concedida novamente, o valor personalizado deve ser reaplicado.
Dependência: Métodos Auxiliares
Se você ainda não tiver esses métodos no seu código, eles são necessários para o funcionamento adequado:
CalculateDesiredCapacity
Este método calcula a capacidade baseando-se na permissão e nas configurações personalizadas:
Retorna a capacidade padrão do jogo para uma arma específica (como valor builtInSize):
csharp
private int GetDefaultCapacity(string shortname)
{
// Busca a capacidade padrão no dicionário "defaultCapacities"
return defaultCapacities.TryGetValue(shortname, out var capacity) ? capacity : 0;
}
Se os testes ainda não funcionarem como esperado, faça o seguinte:
1. Adicione Debugging ao Código
Adicione logs para capturar quem tem permissões, a capacidade calculada e o valor final aplicado.
csharp
PrintWarning($"[DEBUG] Player: {player.displayName}, Has Permission: {HasPermission(player, UseCustomCapacityPermission)}");
PrintWarning($"[DEBUG] Weapon: {weapon.GetItem()?.info?.shortname}, Default Capacity: {defaultCapacity}, Desired Capacity: {desiredCapacity}, Actual Capacity: {weapon.primaryMagazine.capacity}");
2. Verifique o Comportamento do Extended Mag
Faça o teste com o Extended Mag para confirmar:
Se o comportamento padrão do jogo (ou seja, DelayedModsChanged) está manipulando a capacidade corretamente para jogadores sem permissão do plugin.
Se o plugin está sobrescrevendo algo para jogadores sem permissão (isso não deve acontecer).
3. Reduza os Testes Gradativamente
Desative temporariamente funcionalidades do plugin (como ajuste de capacidade) para verificar se o problema vem do plugin ou do sistema original.
Conclusão
Este ajuste específico deve garantir que:
Jogadores sem permissão tenham o comportamento padrão do Rust, incluindo suporte para Extended Mag.
Jogadores com permissão mantenham os valores de capacidade personalizados definidos pelo plugin.
Se ainda houver problemas, envie os logs de debug e um exemplo prático do comportamento real. Continue me atualizando e ajustarei conforme necessário! 😊
[InspectorFlags]
[Tooltip("If using inbuilt mag, will accept these types of ammo")]
public AmmoTypes ammoTypes;
}
public Definition definition;
public int capacity;
public int contents;
[ItemSelector(ItemCategory.All)]
public ItemDefinition ammoType;
public bool allowPlayerReloading = true;
public bool allowAmmoSwitching = true;
public void ServerInit()
{
if (definition.builtInSize > 0)
{
capacity = definition.builtInSize;
}
}
public ProtoBuf.Magazine Save()
{
ProtoBuf.Magazine magazine = Facepunch.Pool.Get<ProtoBuf.Magazine>();
if (ammoType == null)
{
magazine.capacity = capacity;
magazine.contents = 0;
magazine.ammoType = 0;
}
else
{
magazine.capacity = capacity;
magazine.contents = contents;
magazine.ammoType = ammoType.itemid;
}
return magazine;
}
public void Load(ProtoBuf.Magazine mag)
{
contents = mag.contents;
capacity = mag.capacity;
ammoType = ItemManager.FindItemDefinition(mag.ammoType);
}
public bool CanReload(IAmmoContainer ammoSource)
{
if (contents >= capacity)
{
return false;
}
return ammoSource.HasAmmo(definition.ammoTypes);
}
}
public static class BaseProjectileFlags
{
public const Flags BurstToggle = Flags.Reserved6;
}
public struct EncryptedValue<TInner> where TInner : unmanaged
{
private TInner _value;
private int _padding;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TInner Get()
{
return _value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(TInner value)
{
_value = value;
}
public override string ToString()
{
return Get().ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator EncryptedValue<TInner>(TInner value)
{
EncryptedValue<TInner> result = default(EncryptedValue<TInner>);
result.Set(value);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator TInner(EncryptedValue<TInner> encrypted)
{
return encrypted.Get();
}
}
[Header("NPC Info")]
public float NoiseRadius = 100f;
[Header("Projectile")]
public float damageScale = 1f;
public float distanceScale = 1f;
public float projectileVelocityScale = 1f;
public bool automatic;
public bool usableByTurret = true;
[Tooltip("Final damage is scaled by this amount before being applied to a target when this weapon is mounted to a turret")]
public float turretDamageScale = 0.35f;
[Header("Effects")]
public GameObjectRef attackFX;
public GameObjectRef silencedAttack;
public GameObjectRef muzzleBrakeAttack;
public SoundDefinition fireModeSound;
public Transform MuzzlePoint;
[Header("Reloading")]
public float reloadTime = 1f;
public bool canUnloadAmmo = true;
public Magazine primaryMagazine;
public bool fractionalReload;
public float reloadStartDuration;
public float reloadFractionDuration;
public float reloadEndDuration;
public float alternateDryFireRate;
[Header("Recoil")]
public float aimSway = 3f;
public float aimSwaySpeed = 1f;
public RecoilProperties recoil;
[Header("Aim Cone")]
public AnimationCurve aimconeCurve = new AnimationCurve(new Keyframe(0f, 1f), new Keyframe(1f, 1f));
public float aimCone;
public float hipAimCone = 1.8f;
public float aimconePenaltyPerShot;
public float aimConePenaltyMax;
public float aimconePenaltyRecoverTime = 0.1f;
public float aimconePenaltyRecoverDelay = 0.1f;
public float stancePenaltyScale = 1f;
[Header("Iconsights")]
public bool hasADS = true;
public bool noAimingWhileCycling;
public bool manualCycle;
[NonSerialized]
protected bool needsCycle;
[NonSerialized]
protected bool isCycling;
[NonSerialized]
public bool aiming;
[Header("Burst Information")]
public bool isBurstWeapon;
public bool canChangeFireModes = true;
public bool defaultOn = true;
public float internalBurstRecoilScale = 0.8f;
public float internalBurstFireRateScale = 0.8f;
public float internalBurstAimConeScale = 0.8f;
public float resetDuration = 0.3f;
public int numShotsFired;
public const float maxDistance = 300f;
[NonSerialized]
private EncryptedValue<float> nextReloadTime = float.NegativeInfinity;
[NonSerialized]
private EncryptedValue<float> startReloadTime = float.NegativeInfinity;
private float lastReloadTime = -10f;
private bool modsChangedInitialized;
private float stancePenalty;
private float aimconePenalty;
private uint cachedModHash;
private float sightAimConeScale = 1f;
private float sightAimConeOffset;
private float hipAimConeScale = 1f;
private float hipAimConeOffset;
protected bool reloadStarted;
protected bool reloadFinished;
private int fractionalInsertCounter;
private static readonly Effect reusableInstance = new Effect();
public RecoilProperties recoilProperties
{
get
{
if (!(recoil == null))
{
return recoil.GetRecoil();
}
return null;
}
}
public bool isSemiAuto => !automatic;
public override Transform MuzzleTransform => MuzzlePoint;
public override bool IsUsableByTurret => usableByTurret;
protected virtual bool CanRefundAmmo => true;
protected virtual ItemDefinition PrimaryMagazineAmmo => primaryMagazine.ammoType;
public override bool OnRpcMessage(BasePlayer player, uint rpc, Message msg)
{
using (TimeWarning.New("BaseProjectile.OnRpcMessage"))
{
if (rpc == 3168282921u && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - CLProject ");
}
using (TimeWarning.New("CLProject"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.FromOwner.Test(3168282921u, "CLProject", this, player))
{
return true;
}
if (!RPC_Server.IsActiveItem.Test(3168282921u, "CLProject", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg2 = rPCMessage;
CLProject(msg2);
}
}
catch (Exception exception)
{
Debug.LogException(exception);
player.Kick("RPC Error in CLProject");
}
}
return true;
}
if (rpc == 1720368164 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - Reload ");
}
using (TimeWarning.New("Reload"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(1720368164u, "Reload", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg3 = rPCMessage;
Reload(msg3);
}
}
catch (Exception exception2)
{
Debug.LogException(exception2);
player.Kick("RPC Error in Reload");
}
}
return true;
}
if (rpc == 240404208 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - ServerFractionalReloadInsert ");
}
using (TimeWarning.New("ServerFractionalReloadInsert"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(240404208u, "ServerFractionalReloadInsert", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg4 = rPCMessage;
ServerFractionalReloadInsert(msg4);
}
}
catch (Exception exception3)
{
Debug.LogException(exception3);
player.Kick("RPC Error in ServerFractionalReloadInsert");
}
}
return true;
}
if (rpc == 555589155 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - StartReload ");
}
using (TimeWarning.New("StartReload"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(555589155u, "StartReload", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg5 = rPCMessage;
StartReload(msg5);
}
}
catch (Exception exception4)
{
Debug.LogException(exception4);
player.Kick("RPC Error in StartReload");
}
}
return true;
}
if (rpc == 1918419884 && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - SwitchAmmoTo ");
}
using (TimeWarning.New("SwitchAmmoTo"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.IsActiveItem.Test(1918419884u, "SwitchAmmoTo", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg6 = rPCMessage;
SwitchAmmoTo(msg6);
}
}
catch (Exception exception5)
{
Debug.LogException(exception5);
player.Kick("RPC Error in SwitchAmmoTo");
}
}
return true;
}
if (rpc == 3327286961u && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (ConVar.Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - ToggleFireMode ");
}
using (TimeWarning.New("ToggleFireMode"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.CallsPerSecond.Test(3327286961u, "ToggleFireMode", this, player, 2uL))
{
return true;
}
if (!RPC_Server.IsActiveItem.Test(3327286961u, "ToggleFireMode", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
RPCMessage rPCMessage = default(RPCMessage);
rPCMessage.connection = msg.connection;
rPCMessage.player = player;
rPCMessage.read = msg.read;
RPCMessage msg7 = rPCMessage;
ToggleFireMode(msg7);
}
}
catch (Exception exception6)
{
Debug.LogException(exception6);
player.Kick("RPC Error in ToggleFireMode");
}
}
return true;
}
}
return base.OnRpcMessage(player, rpc, msg);
}
protected bool TryReload(IAmmoContainer ammoSource, int desiredAmount, bool canRefundAmmo = true)
{
List<Item> list = ammoSource.FindItemsByItemID(primaryMagazine.ammoType.itemid);
if (list.Count == 0 && !primaryMagazine.allowAmmoSwitching)
{
return false;
}
if (list.Count == 0)
{
Item item = ammoSource.FindAmmo(primaryMagazine.definition.ammoTypes);
if (item == null)
{
return false;
}
list = ammoSource.FindItemsByItemID(item.info.itemid);
if (list == null || list.Count == 0)
{
return false;
}
if (primaryMagazine.contents > 0)
{
if (canRefundAmmo)
{
ammoSource.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
}
SetAmmoCount(0);
}
primaryMagazine.ammoType = list[0].info;
}
int num = desiredAmount;
if (num == -1)
{
num = primaryMagazine.capacity - primaryMagazine.contents;
}
foreach (Item item2 in list)
{
_ = item2.amount;
int num2 = Mathf.Min(num, item2.amount);
item2.UseItem(num2);
ModifyAmmoCount(num2);
num -= num2;
if (num <= 0)
{
break;
}
}
return true;
}
public void SwitchAmmoTypesIfNeeded(IAmmoContainer ammoSource)
{
Item item = ammoSource.FindItemByItemID(primaryMagazine.ammoType.itemid);
if (item != null)
{
return;
}
Item item2 = ammoSource.FindAmmo(primaryMagazine.definition.ammoTypes);
if (item2 == null)
{
return;
}
item = ammoSource.FindItemByItemID(item2.info.itemid);
if (item != null)
{
if (primaryMagazine.contents > 0)
{
ammoSource.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
SetAmmoCount(0);
}
primaryMagazine.ammoType = item.info;
}
}
public static void StripAmmoToType(ref List<Item> ammos, ItemDefinition onlyAllowed)
{
if (!(onlyAllowed != null))
{
return;
}
for (int num = ammos.Count - 1; num >= 0; num--)
{
if (ammos[num].info != onlyAllowed)
{
ammos.RemoveAt(num);
}
}
}
public void SetAmmoCount(int newCount)
{
primaryMagazine.contents = newCount;
Item item = GetItem();
if (item != null)
{
item.ammoCount = newCount;
item.MarkDirty();
}
}
public void ModifyAmmoCount(int amount)
{
SetAmmoCount(primaryMagazine.contents + amount);
}
public override Vector3 GetInheritedVelocity(BasePlayer player, Vector3 direction)
{
return player.GetInheritedProjectileVelocity(direction);
}
public virtual float GetDamageScale(bool getMax = false)
{
return damageScale;
}
public virtual float GetDistanceScale(bool getMax = false)
{
return distanceScale;
}
public virtual float GetProjectileVelocityScale(bool getMax = false)
{
return projectileVelocityScale;
}
public virtual float GetOverrideProjectileThickness(Projectile projectile)
{
if (projectile == null)
{
return 0f;
}
return projectile.thickness;
}
protected void StartReloadCooldown(float cooldown)
{
nextReloadTime = CalculateCooldownTime(nextReloadTime, cooldown, catchup: false, unscaledTime: true);
startReloadTime = (float)nextReloadTime - cooldown;
}
protected void ResetReloadCooldown()
{
nextReloadTime = float.NegativeInfinity;
}
protected bool HasReloadCooldown()
{
return UnityEngine.Time.unscaledTime < (float)nextReloadTime;
}
protected float GetReloadCooldown()
{
return Mathf.Max((float)nextReloadTime - UnityEngine.Time.unscaledTime, 0f);
}
protected float GetReloadIdle()
{
return Mathf.Max(UnityEngine.Time.unscaledTime - (float)nextReloadTime, 0f);
}
private void OnDrawGizmos()
{
if (base.isClient && MuzzlePoint != null)
{
Gizmos.color = Color.blue;
Gizmos.DrawLine(MuzzlePoint.position, MuzzlePoint.position + MuzzlePoint.forward * 10f);
BasePlayer ownerPlayer = GetOwnerPlayer();
if ((bool)ownerPlayer)
{
Gizmos.color = Color.cyan;
Gizmos.DrawLine(MuzzlePoint.position, MuzzlePoint.position + ownerPlayer.eyes.rotation * Vector3.forward * 10f);
}
}
}
public virtual RecoilProperties GetRecoil()
{
return recoilProperties;
}
public override float AmmoFraction()
{
return (float)primaryMagazine.contents / (float)primaryMagazine.capacity;
}
public virtual void DidAttackServerside()
{
}
public override bool ServerIsReloading()
{
return UnityEngine.Time.time < lastReloadTime + reloadTime;
}
public override bool CanReload()
{
return primaryMagazine.contents < primaryMagazine.capacity;
}
public override void TopUpAmmo()
{
SetAmmoCount(primaryMagazine.capacity);
}
public override void ServerReload()
{
if (!ServerIsReloading())
{
lastReloadTime = UnityEngine.Time.time;
StartAttackCooldown(reloadTime);
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.SignalBroadcast(Signal.Reload);
}
SetAmmoCount(primaryMagazine.capacity);
}
}
public override bool ServerTryReload(IAmmoContainer ammoSource)
{
if (ServerIsReloading())
{
return false;
}
if (TryReloadMagazine(ammoSource))
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.SignalBroadcast(Signal.Reload);
}
lastReloadTime = UnityEngine.Time.time;
StartAttackCooldown(reloadTime);
return true;
}
return false;
}
public override Vector3 ModifyAIAim(Vector3 eulerInput, float swayModifier = 1f)
{
float num = UnityEngine.Time.time * (aimSwaySpeed * 1f + aiAimSwayOffset);
float num2 = Mathf.Sin(UnityEngine.Time.time * 2f);
float num3 = ((num2 < 0f) ? (1f - Mathf.Clamp(Mathf.Abs(num2) / 1f, 0f, 1f)) : 1f);
float num4 = (false ? 0.6f : 1f);
float num5 = (aimSway * 1f + aiAimSwayOffset) * num4 * num3 * swayModifier;
eulerInput.y += (Mathf.PerlinNoise(num, num) - 0.5f) * num5 * UnityEngine.Time.deltaTime;
eulerInput.x += (Mathf.PerlinNoise(num + 0.1f, num + 0.2f) - 0.5f) * num5 * UnityEngine.Time.deltaTime;
return eulerInput;
}
public float GetAIAimcone()
{
NPCPlayer nPCPlayer = GetOwnerPlayer() as NPCPlayer;
if ((bool)nPCPlayer)
{
return nPCPlayer.GetAimConeScale() * aiAimCone;
}
return aiAimCone;
}
public override void ServerUse()
{
ServerUse(1f);
}
public override void ServerUse(float damageModifier, Transform originOverride = null, bool useBulletThickness = true)
{
if (base.isClient || HasAttackCooldown())
{
return;
}
BasePlayer ownerPlayer = GetOwnerPlayer();
bool flag = ownerPlayer != null;
if (primaryMagazine.contents <= 0)
{
SignalBroadcast(Signal.DryFire);
StartAttackCooldownRaw(1f);
return;
}
ModifyAmmoCount(-1);
if (primaryMagazine.contents < 0)
{
SetAmmoCount(0);
}
bool flag2 = flag && ownerPlayer.IsNpc;
if (flag2 && (ownerPlayer.isMounted || ownerPlayer.GetParentEntity() != null))
{
NPCPlayer nPCPlayer = ownerPlayer as NPCPlayer;
if (nPCPlayer != null)
{
nPCPlayer.SetAimDirection(nPCPlayer.GetAimDirection());
}
}
StartAttackCooldownRaw(repeatDelay);
Vector3 vector = (flag ? ownerPlayer.eyes.position : MuzzlePoint.transform.position);
Vector3 inputVec = MuzzlePoint.transform.forward;
if (originOverride != null)
{
vector = originOverride.position;
inputVec = originOverride.forward;
}
ItemModProjectile component = primaryMagazine.ammoType.GetComponent<ItemModProjectile>();
SignalBroadcast(Signal.Attack, string.Empty, null, GetAttackEffect());
Projectile component2 = component.projectileObject.Get().GetComponent<Projectile>();
bool flag3 = GetParentEntity() is BasePlayer;
BaseEntity baseEntity = null;
if (flag)
{
inputVec = ownerPlayer.eyes.BodyForward();
}
for (int i = 0; i < component.numProjectiles; i++)
{
Vector3 vector2 = ((!flag2) ? AimConeUtil.GetModifiedAimConeDirection(component.projectileSpread + GetAimCone(), inputVec) : AimConeUtil.GetModifiedAimConeDirection(component.projectileSpread + GetAimCone() + GetAIAimcone(), inputVec));
float radius = (useBulletThickness ? GetOverrideProjectileThickness(component2) : 0f);
List<RaycastHit> obj = Facepunch.Pool.Get<List<RaycastHit>>();
GamePhysics.TraceAll(new Ray(vector, vector2), radius, obj, 300f, 1220225793, QueryTriggerInteraction.Ignore, ownerPlayer);
for (int j = 0; j < obj.Count; j++)
{
RaycastHit hit = obj[j];
BaseEntity entity = RaycastHitEx.GetEntity(hit);
if (flag3)
{
if (entity != null && (entity == this || entity.EqualNetID(this)))
{
continue;
}
}
else if (entity != null && this.HasEntityInParents(entity))
{
continue;
}
if (entity != null && entity.isClient)
{
continue;
}
ColliderInfo component3 = hit.collider.GetComponent<ColliderInfo>();
if (component3 != null && !component3.HasFlag(ColliderInfo.Flags.Shootable))
{
continue;
}
BaseCombatEntity baseCombatEntity = entity as BaseCombatEntity;
if ((!(entity != null && entity.IsNpc && flag2) || baseCombatEntity.GetFaction() == BaseCombatEntity.Faction.Horror || entity is BasePet) && baseCombatEntity != null && (baseEntity == null || entity == baseEntity || entity.EqualNetID(baseEntity)) && baseCombatEntity.IsVisible(vector, hit.point, 300f))
{
HitInfo hitInfo = new HitInfo();
AssignInitiator(hitInfo);
hitInfo.Weapon = this;
hitInfo.WeaponPrefab = base.gameManager.FindPrefab(base.PrefabName).GetComponent<AttackEntity>();
hitInfo.IsPredicting = false;
hitInfo.DoHitEffects = component2.doDefaultHitEffects;
hitInfo.DidHit = true;
hitInfo.ProjectileVelocity = vector2 * 300f;
hitInfo.PointStart = MuzzlePoint.position;
hitInfo.PointEnd = hit.point;
hitInfo.HitPositionWorld = hit.point;
hitInfo.HitNormalWorld = hit.normal;
hitInfo.HitEntity = entity;
hitInfo.UseProtection = true;
component2.CalculateDamage(hitInfo, GetProjectileModifier(), 1f);
hitInfo.damageTypes.ScaleAll(GetDamageScale() * damageModifier * (flag2 ? npcDamageScale : turretDamageScale));
baseCombatEntity.OnAttacked(hitInfo);
component.ServerProjectileHit(hitInfo);
if (entity is BasePlayer || entity is BaseNpc)
{
hitInfo.HitPositionLocal = entity.transform.InverseTransformPoint(hitInfo.HitPositionWorld);
hitInfo.HitNormalLocal = entity.transform.InverseTransformDirection(hitInfo.HitNormalWorld);
hitInfo.HitMaterial = StringPool.Get("Flesh");
Effect.server.ImpactEffect(hitInfo);
}
if (!(entity != null) || entity.ShouldBlockProjectiles())
{
break;
}
}
}
Facepunch.Pool.FreeUnmanaged(ref obj);
Vector3 vector3 = ((flag && ownerPlayer.isMounted) ? (vector2 * 6f) : Vector3.zero);
CreateProjectileEffectClientside(component.projectileObject.resourcePath, vector + vector3, vector2 * component.projectileVelocity, UnityEngine.Random.Range(1, 100), null, IsSilenced(), forceClientsideEffects: true);
}
}
private void AssignInitiator(HitInfo info)
{
info.Initiator = GetOwnerPlayer();
if (info.Initiator == null)
{
info.Initiator = GetParentEntity();
}
}
public override void ServerInit()
{
base.ServerInit();
primaryMagazine.ServerInit();
Invoke(DelayedModSetup, 0.1f);
}
public void DelayedModSetup()
{
if (!modsChangedInitialized)
{
Item item = GetCachedItem();
if (item != null && item.contents != null)
{
ItemContainer contents = item.contents;
contents.onItemAddedRemoved = (Action<Item, bool>)Delegate.Combine(contents.onItemAddedRemoved, new Action<Item, bool>(ModsChanged));
modsChangedInitialized = true;
}
}
}
public override void DestroyShared()
{
if (base.isServer)
{
Item item = GetCachedItem();
if (item != null && item.contents != null)
{
ItemContainer contents = item.contents;
contents.onItemAddedRemoved = (Action<Item, bool>)Delegate.Remove(contents.onItemAddedRemoved, new Action<Item, bool>(ModsChanged));
modsChangedInitialized = false;
}
}
base.DestroyShared();
}
public void ModsChanged(Item item, bool added)
{
Invoke(DelayedModsChanged, 0.1f);
}
public void ForceModsChanged()
{
Invoke(DelayedModSetup, 0f);
Invoke(DelayedModsChanged, 0.2f);
}
public void DelayedModsChanged()
{
if (Interface.CallHook("OnWeaponModChange", this, GetOwnerPlayer()) != null)
{
return;
}
int num = Mathf.CeilToInt(ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.magazineCapacity, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * (float)primaryMagazine.definition.builtInSize);
if (num == primaryMagazine.capacity)
{
return;
}
if (primaryMagazine.contents > 0 && primaryMagazine.contents > num)
{
_ = primaryMagazine.ammoType;
int contents = primaryMagazine.contents;
BasePlayer ownerPlayer = GetOwnerPlayer();
ItemContainer itemContainer = null;
if (ownerPlayer != null)
{
itemContainer = ownerPlayer.inventory.containerMain;
}
else if (GetCachedItem() != null)
{
itemContainer = GetCachedItem().parent;
}
SetAmmoCount(0);
if (itemContainer != null)
{
Item item = ItemManager.Create(primaryMagazine.ammoType, contents, 0uL);
if (!item.MoveToContainer(itemContainer))
{
Vector3 vPos = base.transform.position;
if (itemContainer.entityOwner != null)
{
vPos = itemContainer.entityOwner.transform.position + Vector3.up * 0.25f;
}
item.Drop(vPos, Vector3.up * 5f);
}
}
}
primaryMagazine.capacity = num;
SendNetworkUpdate();
}
public override void ServerCommand(Item item, string command, BasePlayer player)
{
if (item != null && command == "unload_ammo" && !HasReloadCooldown())
{
UnloadAmmo(item, player);
}
}
public void UnloadAmmo(Item item, BasePlayer player)
{
BaseProjectile component = item.GetHeldEntity().GetComponent<BaseProjectile>();
if (!component.canUnloadAmmo || Interface.CallHook("OnAmmoUnload", component, item, player) != null || !component)
{
return;
}
int num = component.primaryMagazine.contents;
if (num <= 0)
{
return;
}
component.SetAmmoCount(0);
item.MarkDirty();
SendNetworkUpdateImmediate();
int stackable = component.primaryMagazine.ammoType.stackable;
if (num > stackable)
{
int num2 = Mathf.FloorToInt(num / component.primaryMagazine.ammoType.stackable);
num %= stackable;
for (int i = 0; i < num2; i++)
{
Item item2 = ItemManager.Create(component.primaryMagazine.ammoType, stackable, 0uL);
player.GiveItem(item2);
}
}
if (num > 0)
{
Item item3 = ItemManager.Create(component.primaryMagazine.ammoType, num, 0uL);
player.GiveItem(item3);
}
}
public override void CollectedForCrafting(Item item, BasePlayer crafter)
{
if (!(crafter == null) && item != null)
{
UnloadAmmo(item, crafter);
}
}
public override void ReturnedFromCancelledCraft(Item item, BasePlayer crafter)
{
if (!(crafter == null) && item != null)
{
BaseProjectile component = item.GetHeldEntity().GetComponent<BaseProjectile>();
if ((bool)component)
{
component.SetAmmoCount(0);
}
}
}
public override void SetLightsOn(bool isOn)
{
base.SetLightsOn(isOn);
UpdateAttachmentsState();
}
public void UpdateAttachmentsState()
{
_ = flags;
bool b = ShouldLightsBeOn();
if (children == null)
{
return;
}
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.isLight)
{
projectileWeaponMod.SetFlag(Flags.On, b);
}
}
}
private bool ShouldLightsBeOn()
{
if (LightsOn())
{
if (!IsDeployed())
{
return parentEntity.Get(base.isServer) is AutoTurret;
}
return true;
}
return false;
}
protected override void OnChildRemoved(BaseEntity child)
{
base.OnChildRemoved(child);
if (child is ProjectileWeaponMod projectileWeaponMod && projectileWeaponMod.isLight)
{
child.SetFlag(Flags.On, b: false);
SetLightsOn(isOn: false);
}
}
public bool CanAiAttack()
{
return true;
}
public virtual float GetAimCone()
{
uint num = 0u;
foreach (BaseEntity child in children)
{
num += (uint)(int)child.net.ID.Value;
num += (uint)child.flags;
}
uint num2 = CRC.Compute32(0u, num);
if (num2 != cachedModHash)
{
sightAimConeScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.sightAimCone, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
sightAimConeOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.sightAimCone, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
hipAimConeScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.hipAimCone, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
hipAimConeOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.hipAimCone, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
cachedModHash = num2;
}
float num3 = aimCone;
num3 *= (UsingInternalBurstMode() ? internalBurstAimConeScale : 1f);
if (recoilProperties != null && recoilProperties.overrideAimconeWithCurve && primaryMagazine.capacity > 0)
{
num3 += recoilProperties.aimconeCurve.Evaluate((float)numShotsFired / (float)primaryMagazine.capacity % 1f) * recoilProperties.aimconeCurveScale;
aimconePenalty = 0f;
}
if (aiming || base.isServer)
{
return (num3 + aimconePenalty + stancePenalty * stancePenaltyScale) * sightAimConeScale + sightAimConeOffset;
}
return (num3 + aimconePenalty + stancePenalty * stancePenaltyScale) * sightAimConeScale + sightAimConeOffset + hipAimCone * hipAimConeScale + hipAimConeOffset;
}
public float ScaleRepeatDelay(float delay)
{
float num = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.repeatDelay, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f);
float num2 = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.repeatDelay, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
float num3 = (UsingInternalBurstMode() ? internalBurstFireRateScale : 1f);
return delay * num * num3 + num2;
}
public Projectile.Modifier GetProjectileModifier()
{
Projectile.Modifier result = default(Projectile.Modifier);
result.damageOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.projectileDamage, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
result.damageScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.projectileDamage, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * GetDamageScale();
result.distanceOffset = ProjectileWeaponMod.Sum(this, (ProjectileWeaponMod x) => x.projectileDistance, (ProjectileWeaponMod.Modifier y) => y.offset, 0f);
result.distanceScale = ProjectileWeaponMod.Mult(this, (ProjectileWeaponMod x) => x.projectileDistance, (ProjectileWeaponMod.Modifier y) => y.scalar, 1f) * GetDistanceScale();
return result;
}
public bool UsingBurstMode()
{
if (IsBurstDisabled())
{
return false;
}
return IsBurstEligable();
}
public bool UsingInternalBurstMode()
{
if (IsBurstDisabled())
{
return false;
}
return isBurstWeapon;
}
public bool IsBurstEligable()
{
if (isBurstWeapon)
{
return true;
}
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.burstCount > 0)
{
return true;
}
}
}
return false;
}
public float TimeBetweenBursts()
{
return repeatDelay * 2f;
}
public virtual bool CanAttack()
{
if (ProjectileWeaponMod.HasBrokenWeaponMod(this))
{
return false;
}
return true;
}
public float GetReloadDuration()
{
if (fractionalReload)
{
int num = Mathf.Min(primaryMagazine.capacity - primaryMagazine.contents, GetAvailableAmmo());
return reloadStartDuration + reloadEndDuration + reloadFractionDuration * (float)num;
}
return reloadTime;
}
public int GetAvailableAmmo()
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null)
{
return primaryMagazine.contents;
}
List<Item> obj = Facepunch.Pool.Get<List<Item>>();
ownerPlayer.inventory.FindAmmo(obj, primaryMagazine.definition.ammoTypes);
int num = 0;
if (obj.Count != 0)
{
for (int i = 0; i < obj.Count; i++)
{
Item item = obj[i];
if (item.info == primaryMagazine.ammoType)
{
num += item.amount;
}
}
}
Facepunch.Pool.Free(ref obj, freeElements: false);
return num;
}
public bool IsBurstDisabled()
{
return HasFlag(Flags.Reserved6) == defaultOn;
}
[RPC_Server]
[RPC_Server.IsActiveItem]
[RPC_Server.CallsPerSecond(2uL)]
private void ToggleFireMode(RPCMessage msg)
{
if (canChangeFireModes && IsBurstEligable())
{
SetFlag(Flags.Reserved6, !HasFlag(Flags.Reserved6));
SendNetworkUpdate_Flags();
Facepunch.Rust.Analytics.Azure.OnBurstModeToggled(msg.player, this, HasFlag(Flags.Reserved6));
}
}
public virtual bool TryReloadMagazine(IAmmoContainer ammoSource, int desiredAmount = -1)
{
object obj = Interface.CallHook("OnMagazineReload", this, ammoSource, GetOwnerPlayer());
if (obj is bool)
{
return (bool)obj;
}
if (!TryReload(ammoSource, desiredAmount))
{
return false;
}
SendNetworkUpdateImmediate();
ItemManager.DoRemoves();
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer != null)
{
ownerPlayer.inventory.ServerUpdate(0f);
}
return true;
}
[RPC_Server]
[RPC_Server.IsActiveItem]
private void SwitchAmmoTo(RPCMessage msg)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (!ownerPlayer)
{
return;
}
int num = msg.read.Int32();
if (num == primaryMagazine.ammoType.itemid)
{
return;
}
ItemDefinition itemDefinition = ItemManager.FindItemDefinition(num);
if (itemDefinition == null)
{
return;
}
ItemModProjectile component = itemDefinition.GetComponent<ItemModProjectile>();
if ((bool)component && component.IsAmmo(primaryMagazine.definition.ammoTypes) && Interface.CallHook("OnAmmoSwitch", this, ownerPlayer, itemDefinition) == null)
{
if (primaryMagazine.contents > 0)
{
ownerPlayer.GiveItem(ItemManager.CreateByItemID(primaryMagazine.ammoType.itemid, primaryMagazine.contents, 0uL));
SetAmmoCount(0);
}
primaryMagazine.ammoType = itemDefinition;
SendNetworkUpdateImmediate();
ItemManager.DoRemoves();
ownerPlayer.inventory.ServerUpdate(0f);
}
}
public override void OnHeldChanged()
{
base.OnHeldChanged();
reloadStarted = false;
reloadFinished = false;
fractionalInsertCounter = 0;
UpdateAttachmentsState();
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void StartReload(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
}
else if (Interface.CallHook("OnWeaponReload", this, player) == null)
{
reloadFinished = false;
reloadStarted = true;
fractionalInsertCounter = 0;
if (CanRefundAmmo)
{
SwitchAmmoTypesIfNeeded(player.inventory);
}
OnReloadStarted();
StartReloadCooldown(GetReloadDuration());
}
}
protected virtual void OnReloadStarted()
{
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void ServerFractionalReloadInsert(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
return;
}
if (!fractionalReload)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload not allowed (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_type");
return;
}
if (!reloadStarted)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload request skipped (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_skip");
reloadStarted = false;
reloadFinished = false;
return;
}
if (GetReloadIdle() > 3f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T+" + GetReloadIdle() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
if (UnityEngine.Time.unscaledTime < (float)startReloadTime + reloadStartDuration)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload too early (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_fraction_too_early");
reloadStarted = false;
reloadFinished = false;
}
if (UnityEngine.Time.unscaledTime < (float)startReloadTime + reloadStartDuration + (float)fractionalInsertCounter * reloadFractionDuration)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Fractional reload rate too high (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_fraction_rate");
reloadStarted = false;
reloadFinished = false;
}
else
{
fractionalInsertCounter++;
if (primaryMagazine.contents < primaryMagazine.capacity)
{
TryReloadMagazine(player.inventory, 1);
}
}
}
[RPC_Server.IsActiveItem]
[RPC_Server]
private void Reload(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientRPC(player))
{
SendNetworkUpdate();
reloadStarted = false;
reloadFinished = false;
return;
}
if (!reloadStarted)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "Request skipped (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_skip");
reloadStarted = false;
reloadFinished = false;
return;
}
if (!fractionalReload)
{
if (GetReloadCooldown() > 1f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T-" + GetReloadCooldown() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
if (GetReloadIdle() > 1.5f)
{
AntiHack.Log(player, AntiHackType.ReloadHack, "T+" + GetReloadIdle() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_time");
reloadStarted = false;
reloadFinished = false;
return;
}
}
if (fractionalReload)
{
ResetReloadCooldown();
}
reloadStarted = false;
reloadFinished = true;
if (!fractionalReload)
{
TryReloadMagazine(player.inventory);
}
}
[RPC_Server.FromOwner]
[RPC_Server.IsActiveItem]
[RPC_Server]
private void CLProject(RPCMessage msg)
{
BasePlayer player = msg.player;
if (!VerifyClientAttack(player))
{
SendNetworkUpdate();
return;
}
if (reloadFinished && HasReloadCooldown())
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Reloading (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "reload_cooldown");
return;
}
reloadStarted = false;
reloadFinished = false;
if (primaryMagazine.contents <= 0 && !base.UsingInfiniteAmmoCheat)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Magazine empty (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "ammo_missing");
return;
}
ItemDefinition primaryMagazineAmmo = PrimaryMagazineAmmo;
ProjectileShoot projectileShoot = ProjectileShoot.Deserialize(msg.read);
if (primaryMagazineAmmo.itemid != projectileShoot.ammoType)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Ammo mismatch (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "ammo_mismatch");
return;
}
if (!base.UsingInfiniteAmmoCheat)
{
ModifyAmmoCount(-1);
}
ItemModProjectile component = primaryMagazineAmmo.GetComponent<ItemModProjectile>();
if (component == null)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Item mod not found (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "mod_missing");
return;
}
if (projectileShoot.projectiles.Count > component.numProjectiles)
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Count mismatch (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "count_mismatch");
return;
}
Interface.CallHook("OnWeaponFired", this, msg.player, component, projectileShoot);
if (player.InGesture)
{
return;
}
SignalBroadcast(Signal.Attack, string.Empty, msg.connection, GetAttackEffect());
player.CleanupExpiredProjectiles();
Guid projectileGroupId = Guid.NewGuid();
foreach (ProjectileShoot.Projectile projectile in projectileShoot.projectiles)
{
if (player.HasFiredProjectile(projectile.projectileID))
{
AntiHack.Log(player, AntiHackType.ProjectileHack, "Duplicate ID (" + projectile.projectileID + ")");
player.stats.combat.LogInvalid(player, this, "duplicate_id");
continue;
}
Vector3 positionOffset = Vector3.zero;
if (ConVar.AntiHack.projectile_positionoffset && (player.isMounted || player.HasParent()))
{
if (!ValidateEyePos(player, projectile.startPos, checkLineOfSight: false))
{
continue;
}
Vector3 position = player.eyes.position;
positionOffset = position - projectile.startPos;
projectile.startPos = position;
}
else if (!ValidateEyePos(player, projectile.startPos))
{
continue;
}
player.NoteFiredProjectile(projectile.projectileID, projectile.startPos, projectile.startVel, this, primaryMagazineAmmo, projectileGroupId, positionOffset);
if (!player.limitNetworking)
{
CreateProjectileEffectClientside(component.projectileObject.resourcePath, projectile.startPos, projectile.startVel, projectile.seed, msg.connection, IsSilenced());
}
}
player.MakeNoise(player.transform.position, BaseCombatEntity.ActionVolume.Loud);
SingletonComponent<NpcNoiseManager>.Instance.OnWeaponShot(player, this);
player.stats.Add(component.category + "_fired", projectileShoot.projectiles.Count(), (Stats)5);
player.LifeStoryShotFired(this);
StartAttackCooldown(ScaleRepeatDelay(repeatDelay) + animationDelay);
player.MarkHostileFor();
UpdateItemCondition();
DidAttackServerside();
BaseMountable mounted = player.GetMounted();
if (mounted != null)
{
mounted.OnWeaponFired(this);
}
EACServer.LogPlayerUseWeapon(player, this);
}
public void CreateProjectileEffectClientside(string prefabName, Vector3 pos, Vector3 velocity, int seed, Connection sourceConnection, bool silenced = false, bool forceClientsideEffects = false, List<Connection> targets = null)
{
if (Interface.CallHook("OnClientProjectileEffectCreate", sourceConnection, this, prefabName) == null)
{
Effect effect = reusableInstance;
effect.Clear();
effect.Init(Effect.Type.Projectile, pos, velocity, sourceConnection);
effect.scale = (silenced ? 0f : 1f);
if (forceClientsideEffects)
{
effect.scale = 2f;
}
effect.pooledString = prefabName;
effect.number = seed;
effect.targets = targets;
EffectNetwork.Send(effect);
}
}
public void UpdateItemCondition()
{
Item ownerItem = GetOwnerItem();
if (ownerItem == null)
{
return;
}
float barrelConditionLoss = primaryMagazine.ammoType.GetComponent<ItemModProjectile>().barrelConditionLoss;
float num = 0.25f;
bool usingInfiniteAmmoCheat = base.UsingInfiniteAmmoCheat;
if (!usingInfiniteAmmoCheat)
{
ownerItem.LoseCondition(num + barrelConditionLoss);
}
if (ownerItem.contents == null || ownerItem.contents.itemList == null)
{
return;
}
for (int num2 = ownerItem.contents.itemList.Count - 1; num2 >= 0; num2--)
{
Item item = ownerItem.contents.itemList[num2];
if (item != null && !usingInfiniteAmmoCheat)
{
item.LoseCondition(num + barrelConditionLoss);
}
}
}
public bool IsSilenced()
{
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod != null && projectileWeaponMod.isSilencer && !projectileWeaponMod.IsBroken())
{
return true;
}
}
}
return false;
}
public string GetAttackEffectAdditive()
{
string result = "";
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (!(projectileWeaponMod == null) && projectileWeaponMod.additiveEffect.isValid)
{
result = projectileWeaponMod.additiveEffect.resourcePath;
break;
}
}
}
return result;
}
protected string GetAttackEffect()
{
string resourcePath = attackFX.resourcePath;
if (primaryMagazine.ammoType != null)
{
ItemModProjectile component = primaryMagazine.ammoType.GetComponent<ItemModProjectile>();
if (component.attackEffectOverride.isValid)
{
resourcePath = component.attackEffectOverride.resourcePath;
}
}
if (children != null)
{
foreach (BaseEntity child in children)
{
ProjectileWeaponMod projectileWeaponMod = child as ProjectileWeaponMod;
if (projectileWeaponMod == null)
{
continue;
}
if (projectileWeaponMod.isSilencer)
{
resourcePath = projectileWeaponMod.defaultSilencerEffect.resourcePath;
if (silencedAttack.isValid)
{
resourcePath = silencedAttack.resourcePath;
}
break;
}
if (projectileWeaponMod.isMuzzleBrake)
{
if (muzzleBrakeAttack.isValid)
{
resourcePath = muzzleBrakeAttack.resourcePath;
}
break;
}
}
}
return resourcePath;
}
public override bool CanUseNetworkCache(Connection sendingTo)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null || ownerPlayer.net == null)
{
return true;
}
if (ownerPlayer.IsBeingSpectated)
{
return false;
}
Connection connection = ownerPlayer.net.connection;
if (sendingTo == null || connection == null)
{
return true;
}
return sendingTo != connection;
}
public override void Save(SaveInfo info)
{
base.Save(info);
info.msg.baseProjectile = Facepunch.Pool.Get<ProtoBuf.BaseProjectile>();
if (info.forDisk || info.SendingTo(GetOwnerConnection()) || ForceSendMagazine(info))
{
info.msg.baseProjectile.primaryMagazine = primaryMagazine.Save();
}
}
public virtual bool ForceSendMagazine(SaveInfo saveInfo)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if ((bool)ownerPlayer && ownerPlayer.IsBeingSpectated)
{
foreach (BaseEntity child in ownerPlayer.children)
{
if (child.net != null && child.net.connection == saveInfo.forConnection)
{
return true;
}
}
}
return false;
}
public override void Load(LoadInfo info)
{
base.Load(info);
if (info.msg.baseProjectile != null && info.msg.baseProjectile.primaryMagazine != null)
{
primaryMagazine.Load(info.msg.baseProjectile.primaryMagazine);
}
}
}
public class Magazine : IDisposable, Pool.IPooled, IProto
{
[NonSerialized]
public int capacity;
code
[NonSerialized]
public int contents;
[NonSerialized]
public int ammoType;
public bool ShouldPool = true;
private bool _disposed;
public static void ResetToPool(Magazine instance)
{
if (instance.ShouldPool)
{
instance.capacity = 0;
instance.contents = 0;
instance.ammoType = 0;
Pool.Free(ref instance);
}
}
public void ResetToPool()
{
ResetToPool(this);
}
public virtual void Dispose()
{
if (!ShouldPool)
{
throw new Exception("Trying to dispose Magazine with ShouldPool set to false!");
}
if (!_disposed)
{
ResetToPool();
_disposed = true;
}
}
public virtual void EnterPool()
{
_disposed = true;
}
public virtual void LeavePool()
{
_disposed = false;
}
public void CopyTo(Magazine instance)
{
instance.capacity = capacity;
instance.contents = contents;
instance.ammoType = ammoType;
}
public Magazine Copy()
{
Magazine magazine = Pool.Get<Magazine>();
CopyTo(magazine);
return magazine;
}
public static Magazine Deserialize(Stream stream)
{
Magazine magazine = Pool.Get<Magazine>();
Deserialize(stream, magazine, isDelta: false);
return magazine;
}
public static Magazine DeserializeLengthDelimited(Stream stream)
{
Magazine magazine = Pool.Get<Magazine>();
DeserializeLengthDelimited(stream, magazine, isDelta: false);
return magazine;
}
public static Magazine DeserializeLength(Stream stream, int length)
{
Magazine magazine = Pool.Get<Magazine>();
DeserializeLength(stream, length, magazine, isDelta: false);
return magazine;
}
public static Magazine Deserialize(byte[] buffer)
{
Magazine magazine = Pool.Get<Magazine>();
using MemoryStream stream = new MemoryStream(buffer);
Deserialize(stream, magazine, isDelta: false);
return magazine;
}
public void FromProto(Stream stream, bool isDelta = false)
{
Deserialize(stream, this, isDelta);
}
public virtual void WriteToStream(Stream stream)
{
Serialize(stream, this);
}
public virtual void WriteToStreamDelta(Stream stream, Magazine previous)
{
if (previous == null)
{
Serialize(stream, this);
}
else
{
SerializeDelta(stream, this, previous);
}
}
public virtual void ReadFromStream(Stream stream, int size, bool isDelta = false)
{
DeserializeLength(stream, size, this, isDelta);
}
public static Magazine Deserialize(byte[] buffer, Magazine instance, bool isDelta = false)
{
using MemoryStream stream = new MemoryStream(buffer);
Deserialize(stream, instance, isDelta);
return instance;
}
public static Magazine Deserialize(Stream stream, Magazine instance, bool isDelta)
{
while (true)
{
int num = stream.ReadByte();
switch (num)
{
case 8:
instance.capacity = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 16:
instance.contents = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 24:
instance.ammoType = (int)ProtocolParser.ReadUInt64(stream);
continue;
case -1:
return instance;
}
Key key = ProtocolParser.ReadKey((byte)num, stream);
if (key.Field == 0)
{
throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream");
}
ProtocolParser.SkipKey(stream, key);
}
}
public static Magazine DeserializeLengthDelimited(Stream stream, Magazine instance, bool isDelta)
{
long num = ProtocolParser.ReadUInt32(stream);
num += stream.Position;
while (stream.Position < num)
{
int num2 = stream.ReadByte();
switch (num2)
{
case -1:
throw new EndOfStreamException();
case 8:
instance.capacity = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 16:
instance.contents = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 24:
instance.ammoType = (int)ProtocolParser.ReadUInt64(stream);
continue;
}
Key key = ProtocolParser.ReadKey((byte)num2, stream);
if (key.Field == 0)
{
throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream");
}
ProtocolParser.SkipKey(stream, key);
}
if (stream.Position != num)
{
throw new ProtocolBufferException("Read past max limit");
}
return instance;
}
public static Magazine DeserializeLength(Stream stream, int length, Magazine instance, bool isDelta)
{
long num = stream.Position + length;
while (stream.Position < num)
{
int num2 = stream.ReadByte();
switch (num2)
{
case -1:
throw new EndOfStreamException();
case 8:
instance.capacity = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 16:
instance.contents = (int)ProtocolParser.ReadUInt64(stream);
continue;
case 24:
instance.ammoType = (int)ProtocolParser.ReadUInt64(stream);
continue;
}
Key key = ProtocolParser.ReadKey((byte)num2, stream);
if (key.Field == 0)
{
throw new ProtocolBufferException("Invalid field id: 0, something went wrong in the stream");
}
ProtocolParser.SkipKey(stream, key);
}
if (stream.Position != num)
{
throw new ProtocolBufferException("Read past max limit");
}
return instance;
}
public static void SerializeDelta(Stream stream, Magazine instance, Magazine previous)
{
MemoryStream obj = Pool.Get<MemoryStream>();
if (instance.capacity != previous.capacity)
{
stream.WriteByte(8);
ProtocolParser.WriteUInt64(stream, (ulong)instance.capacity);
}
if (instance.contents != previous.contents)
{
stream.WriteByte(16);
ProtocolParser.WriteUInt64(stream, (ulong)instance.contents);
}
if (instance.ammoType != previous.ammoType)
{
stream.WriteByte(24);
ProtocolParser.WriteUInt64(stream, (ulong)instance.ammoType);
}
Pool.FreeUnmanaged(ref obj);
}
public static void Serialize(Stream stream, Magazine instance)
{
MemoryStream obj = Pool.Get<MemoryStream>();
stream.WriteByte(8);
ProtocolParser.WriteUInt64(stream, (ulong)instance.capacity);
stream.WriteByte(16);
ProtocolParser.WriteUInt64(stream, (ulong)instance.contents);
stream.WriteByte(24);
ProtocolParser.WriteUInt64(stream, (ulong)instance.ammoType);
Pool.FreeUnmanaged(ref obj);
}
public byte[] ToProtoBytes()
{
return SerializeToBytes(this);
}
public void ToProto(Stream stream)
{
Serialize(stream, this);
}
public static byte[] SerializeToBytes(Magazine instance)
{
using MemoryStream memoryStream = new MemoryStream();
Serialize(memoryStream, instance);
return memoryStream.ToArray();
}
public static void SerializeLengthDelimited(Stream stream, Magazine instance)
{
byte[] array = SerializeToBytes(instance);
ProtocolParser.WriteUInt32(stream, (uint)array.Length);
stream.Write(array, 0, array.Length);
}
public void InspectUids(UidInspector<ulong> action)
{
}
}
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
// Verifica se o jogador tem uma arma equipada
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
// Obtém a configuração no plugin para a arma (se configurado)
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// 1. Jogadores sem permissão -> Restaurar Comportamento Padrão do Jogo
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Chama `ServerInit` internamente para recalibrar a capacidade para o padrão (jogo base + modificadores de extensões)
weapon.primaryMagazine.ServerInit();
// Atualiza o estado do servidor e cliente.
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
return;
}
// 2. Jogadores com permissão -> Capacidade Personalizada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
// Aplica a capacidade personalizada apenas se for diferente da atual
if (weapon.primaryMagazine.capacity != desiredCapacity)
{
weapon.primaryMagazine.capacity = desiredCapacity;
// Remove munição adicional se necessário
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
// Devolve munição excedente ao inventário
if (weapon.primaryMagazine.ammoType != null)
{
player.inventory.GiveItem(
ItemManager.CreateByItemID(weapon.primaryMagazine.ammoType.itemid, excessAmmo),
player.inventory.containerMain
);
}
// Notifica mudança para o jogador
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
// Notifica nova capacidade para o jogador
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
// Atualiza a arma e estado do jogador para refletir a alteração manual
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
}
Explicação do Método
1. Jogadores Sem Permissão
Problema Atual: O plugin tenta sobrescrever os valores (como a capacidade do magazine), ignorando o comportamento padrão do jogo.
Correção: Para restaurar completamente o comportamento padrão, chamamos diretamente o método interno ServerInit do primaryMagazine. Ele reseta a capacidade para o valor do builtInSize, levando em conta modificadores como Extended Mags.
csharp
weapon.primaryMagazine.ServerInit();
Essa abordagem força o jogo a recalcular automaticamente a capacidade normal da arma, incluindo as modificações feitas pelos acessórios (Extended Mag).
2. Jogadores Com Permissão
Para jogadores com permissão, continuamos aplicando o comportamento personalizado já existente no plugin: capacidades personalizadas com remoção de munições excedentes.
Você pode personalizar o comportamento conforme necessário.
Métodos Auxiliares
Você precisará garantir que os seguintes métodos auxiliares estejam funcionando corretamente:
CalculateDesiredCapacity
Define a capacidade esperada para o jogador com base nas permissões.
Verifique que a capacidade volta ao padrão (incluindo quaisquer modificadores automáticos do jogo).
Transições de Permissão:
Teste conceder e remover permissão do jogador:
Ao conceder, a capacidade deve seguir a configuração personalizada.
Ao remover, a capacidade deve voltar ao padrão do jogo.
Considerações Finais
Uso do ServerInit: Essa abordagem usa diretamente a lógica do jogo para resincronizar a arma ao estado normal, em vez de manipular manualmente a capacidade.
Permissões: Certifique-se de que as permissões sejam corretamente aplicadas e removidas usando oxide.grant e oxide.revoke.
Extended Mag: A funcionalidade será restabelecida como no padrão, já que o ServerInit revalida os modificadores da arma.
Se este ajuste ainda não resolver totalmente o problema ou novos erros forem detectados, envie logs ou informações adicionais para ajustarmos! 😊
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Checar permissões do jogador
if (!HasPermission(player, UseCustomCapacityPermission))
{
// Jogadores sem permissão usam capacidade padrão, ajustada se o Extended Mag estiver presente
int defaultCapacity = weapon.primaryMagazine.definition.builtInSize;
// Verificar se há Extended Mag e aumentar em +25%
if (HasExtendedMag(weapon))
{
defaultCapacity = Mathf.CeilToInt(defaultCapacity * 1.25f); // Aumenta 25%
}
// Configurar capacidade padrão ajustada se necessário
if (weapon.primaryMagazine.capacity != defaultCapacity)
{
AdjustMagazineCapacity(weapon, defaultCapacity);
// Remove munição extra se necessário
if (weapon.primaryMagazine.contents > defaultCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - defaultCapacity;
weapon.primaryMagazine.contents = defaultCapacity;
// Devolver munição ao inventário
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), defaultCapacity);
}
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
return;
}
// Jogadores com permissão: Capacidade personalizada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
if (weapon.primaryMagazine.capacity != desiredCapacity)
{
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
AdjustMagazineCapacity(weapon, desiredCapacity);
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
}
Novo Método: HasExtendedMag
Este método verifica os mods (attachments) da arma e identifica se um Extended Mag está equipado:
csharp
private bool HasExtendedMag(BaseProjectile weapon)
{
if (weapon == null || weapon.children == null)
return false;
// Verifica os mods acoplados à arma
foreach (var child in weapon.children)
{
if (child is ProjectileWeaponMod mod && mod.displayName?.english != null)
{
// Verifica se um Extended Mag está instalado (ajuste o nome aqui, se necessário)
if (mod.displayName.english.ToLower().Contains("extended magazine"))
{
return true;
}
}
}
return false;
}
Explicação
Itera sobre os mods (children) da arma.
Verifica as informações do mod (nome, display).
Retorna true se encontrar um mod com "Extended Magazine" no nome.
O Que Foi Modificado
Capacidade Ajustada para Jogadores Sem Permissão:
Para jogadores sem permissão, a capacidade base da arma é verificada.
Se um Extended Mag estiver presente, aplicamos um aumento de +25% (defaultCapacity * 1.25f).
Permissão Personalizada:
A lógica personalizada do plugin continua funcionando para jogadores com permissão (UseCustomCapacityPermission).
Remoção de Munição Excedente:
Para qualquer ajuste (tanto padrão quanto personalizado), municações excedentes são devolvidas ao inventário.
Cenários de Teste
Jogador Sem Permissão:
Teste armas com e sem Extended Mag.
Verifique:
Sem Extended Mag → a capacidade padrão (builtInSize) deve ser aplicada.
Com Extended Mag → a capacidade padrão aumentada em +25% deve ser aplicada.
Jogador Com Permissão:
Teste com capacidades personalizadas aplicadas pelo plugin.
Verifique que a capacidade customizada continua sendo aplicada corretamente, independentemente dos mods da arma.
Mudança de Permissão:
Teste remover e adicionar permissões do jogador e veja se os ajustes corretos (personalizados ou padrão) são aplicados.
Logs de Depuração (Opcional)
Adicione logs para verificar o comportamento durante o teste:
Isso ajudará a identificar se o plugin está detectando corretamente o Extended Mag e aplicando os ajustes.
Se precisar de mais assistência, continue me informando! 😊
[Tooltip("1 means no change. 0.5 is half.")]
public float scalar;
[Tooltip("Added after the scalar is applied.")]
public float offset;
}
[Header("AttackEffectAdditive")]
public GameObjectRef additiveEffect;
[Header("Silencer")]
public GameObjectRef defaultSilencerEffect;
public bool isSilencer;
[Header("Weapon Basics")]
public Modifier repeatDelay;
public Modifier projectileVelocity;
public Modifier projectileDamage;
public Modifier projectileDistance;
[Header("Recoil")]
public Modifier aimsway;
public Modifier aimswaySpeed;
public Modifier recoil;
[Header("Aim Cone")]
public Modifier sightAimCone;
public Modifier hipAimCone;
[Header("Light Effects")]
public bool isLight;
[Header("MuzzleBrake")]
public bool isMuzzleBrake;
[Header("MuzzleBoost")]
public bool isMuzzleBoost;
[Header("Scope")]
public bool isScope;
public float zoomAmountDisplayOnly;
[Header("Magazine")]
public Modifier magazineCapacity;
public bool needsOnForEffects;
[Header("Burst")]
public int burstCount = -1;
public float timeBetweenBursts;
[Header("Zoom")]
public float[] zoomLevels;
public GameObjectRef fovChangeEffect;
private int serverZoomLevel;
private bool hasZoomBeenInit;
public override bool OnRpcMessage(BasePlayer player, uint rpc, Message msg)
{
using (TimeWarning.New("ProjectileWeaponMod.OnRpcMessage"))
{
if (rpc == 3713130066u && player != null)
{
Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!");
if (Global.developer > 2)
{
Debug.Log("SV_RPCMessage: " + player?.ToString() + " - SetZoomLevel ");
}
using (TimeWarning.New("SetZoomLevel"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.FromOwner.Test(3713130066u, "SetZoomLevel", this, player))
{
return true;
}
}
try
{
using (TimeWarning.New("Call"))
{
int zoomLevel = msg.read.Int32();
SetZoomLevel(zoomLevel);
}
}
catch (Exception exception)
{
Debug.LogException(exception);
player.Kick("RPC Error in SetZoomLevel");
}
}
return true;
}
}
return base.OnRpcMessage(player, rpc, msg);
}
public override void ServerInit()
{
SetFlag(Flags.Disabled, b: true);
base.ServerInit();
}
public override void PostServerLoad()
{
base.limitNetworking = HasFlag(Flags.Disabled);
}
public override void Save(SaveInfo info)
{
base.Save(info);
info.msg.projectileWeaponMod = Facepunch.Pool.Get<GunWeaponMod>();
info.msg.projectileWeaponMod.zoomLevel = serverZoomLevel;
}
[RPC_Server.FromOwner]
[RPC_Server]
public void SetZoomLevel(int zoomLevel)
{
serverZoomLevel = zoomLevel;
SendNetworkUpdate();
}
public override void Load(LoadInfo info)
{
base.Load(info);
if (info.msg.projectileWeaponMod != null)
{
serverZoomLevel = info.msg.projectileWeaponMod.zoomLevel;
}
}
public static float Mult(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value, float def)
{
if (parentEnt.children == null)
{
return def;
}
IEnumerable<float> mods = GetMods(parentEnt, selector_modifier, selector_value);
float num = 1f;
foreach (float item in mods)
{
num *= item;
}
return num;
}
public static float Sum(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value, float def)
{
if (parentEnt.children == null)
{
return def;
}
IEnumerable<float> mods = GetMods(parentEnt, selector_modifier, selector_value);
if (mods.Count() != 0)
{
return mods.Sum();
}
return def;
}
public static float Average(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value, float def)
{
if (parentEnt.children == null)
{
return def;
}
IEnumerable<float> mods = GetMods(parentEnt, selector_modifier, selector_value);
if (mods.Count() != 0)
{
return mods.Average();
}
return def;
}
public static float Max(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value, float def)
{
if (parentEnt.children == null)
{
return def;
}
IEnumerable<float> mods = GetMods(parentEnt, selector_modifier, selector_value);
if (mods.Count() != 0)
{
return mods.Max();
}
return def;
}
public static float Min(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value, float def)
{
if (parentEnt.children == null)
{
return def;
}
IEnumerable<float> mods = GetMods(parentEnt, selector_modifier, selector_value);
if (mods.Count() != 0)
{
return mods.Min();
}
return def;
}
public static IEnumerable<float> GetMods(BaseEntity parentEnt, Func<ProjectileWeaponMod, Modifier> selector_modifier, Func<Modifier, float> selector_value)
{
return (from x in (from ProjectileWeaponMod x in parentEnt.children
where x != null && (!x.needsOnForEffects || x.HasFlag(Flags.On))
select x).Select(selector_modifier)
where x.enabled
select x).Select(selector_value);
}
public static bool HasBrokenWeaponMod(BaseEntity parentEnt)
{
if (parentEnt.children == null)
{
return false;
}
if (parentEnt.children.Cast<ProjectileWeaponMod>().Any((ProjectileWeaponMod x) => x != null && x.IsBroken()))
{
return true;
}
return false;
}
}
private void UpdateWeaponCapacityForPlayer(BasePlayer player)
{
if (player.GetActiveItem()?.GetHeldEntity() is BaseProjectile weapon)
{
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
// Jogadores sem permissão -> Aplicar capacidade base ajustada com modificadores
if (!HasPermission(player, UseCustomCapacityPermission))
{
int baseCapacity = weapon.primaryMagazine.definition.builtInSize;
// Adiciona 25% se houver um Extended Magazine ou outro mod que aumenta a capacidade
int modifiedCapacity = Mathf.CeilToInt(baseCapacity * CalculateMagazineMultiplier(weapon));
if (weapon.primaryMagazine.capacity != modifiedCapacity)
{
AdjustMagazineCapacity(weapon, modifiedCapacity);
// Remover munição excedente, se necessário
if (weapon.primaryMagazine.contents > modifiedCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - modifiedCapacity;
weapon.primaryMagazine.contents = modifiedCapacity;
// Retorna munição excedente ao inventário do jogador
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(
ItemManager.CreateByItemID(ammoType.itemid, excessAmmo),
player.inventory.containerMain
);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), modifiedCapacity);
}
// Atualiza arma e jogador
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
return;
}
// Jogadores com permissão -> Aplicar capacidade personalizada
int desiredCapacity = CalculateDesiredCapacity(player, weapon, weaponConfig);
if (weapon.primaryMagazine.capacity != desiredCapacity)
{
if (weapon.primaryMagazine.contents > desiredCapacity)
{
int excessAmmo = weapon.primaryMagazine.contents - desiredCapacity;
weapon.primaryMagazine.contents = desiredCapacity;
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(
ItemManager.CreateByItemID(ammoType.itemid, excessAmmo),
player.inventory.containerMain
);
}
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
else
{
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), desiredCapacity);
}
AdjustMagazineCapacity(weapon, desiredCapacity);
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
}
}
Novo Método: CalculateMagazineMultiplier
O método a seguir calcula o multiplicador de capacidade do modificador de magazine (como o Extended Mag). Ele usa a propriedade magazineCapacity nos mods acoplados à arma para determinar se algum mod aumenta a capacidade.
csharp
private float CalculateMagazineMultiplier(BaseProjectile weapon)
{
if (weapon.children == null)
return 1f; // Sem mods -> Multiplicador padrão (1x)
// Itera sobre os mods na arma e aplica multiplicadores de capacidade
float multiplier = 1f;
foreach (var child in weapon.children)
{
if (child is ProjectileWeaponMod mod && mod.magazineCapacity.enabled)
{
// Aplica o multiplicador de capacidade deste mod
multiplier *= mod.magazineCapacity.scalar > 0 ? mod.magazineCapacity.scalar : 1f;
}
}
// Retorna o multiplicador final
return multiplier;
}
Explicação
Itera sobre os Mods (Children):
Os mods conectados à arma são acessíveis por meio da propriedade children.
Verifica magazineCapacity:
Se o mod tiver um magazineCapacity ativo e definido, o scalar do mod é aplicado como multiplicador à capacidade base.
Retorno Final:
Retorna o multiplicador total aplicado por todos os mods.
Métodos Auxiliares
Os seguintes métodos auxiliares permanecem os mesmos:
AdjustMagazineCapacity
Responsável por aplicar as mudanças de capacidade à arma da seguinte forma:
Armas Sem Mods: Deve usar o valor padrão da capacidade (builtInSize).
Armas Com Extended Magazine: Deve aplicar o multiplicador de capacidade do mod (+25% ou conforme configurado).
Jogador Com Permissão:
Armas Personalizadas: Deve usar a capacidade configurada no plugin, ignorando o multiplicador do Extended Magazine.
Transição de Permissões:
Teste conceder e revogar a permissão para verificar se:
Ao revogar a permissão, o comportamento padrão (e modificadores de capacidade) é restaurado.
Ao conceder permissão, a capacidade personalizada é reaplicada corretamente.
Resumo
Com esta solução:
A capacidade base (padrão ou ajustada) é recalculada com base nos mods acoplados, respeitando o Extended Magazine ou outros modificadores de capacidade.
Jogadores sem permissão têm seu comportamento padrão preservado, enquanto jogadores com permissão continuam aplicando valores personalizados.
Se precisar ajustar algo ou mais explicações, é só pedir! 🚀
private int CalculateDefaultCapacityWithModifiers(BaseProjectile weapon)
{
// Capacidade base da arma (sem mods)
int baseCapacity = weapon.primaryMagazine.definition.builtInSize;
// Aplica modificadores de capacidade (e.g., Extended Mag)
return Mathf.CeilToInt(baseCapacity * CalculateMagazineMultiplier(weapon));
}
AdjustAndSyncWeaponCapacity
Atualiza a capacidade da arma, remove munição extra e sincroniza o estado com o servidor e o cliente:
csharp
private void AdjustAndSyncWeaponCapacity(BasePlayer player, BaseProjectile weapon, int capacity)
{
// Ajusta a capacidade do magazine
AdjustMagazineCapacity(weapon, capacity);
// Remove munição extra, caso necessário
if (weapon.primaryMagazine.contents > capacity)
{
int excessAmmo = weapon.primaryMagazine.contents - capacity;
weapon.primaryMagazine.contents = capacity;
// Devolve a munição excedente ao inventário do jogador
var ammoType = weapon.primaryMagazine.ammoType;
if (ammoType != null)
{
player.inventory.GiveItem(ItemManager.CreateByItemID(ammoType.itemid, excessAmmo), player.inventory.containerMain);
}
// Notifique o jogador sobre a remoção da munição excedente
NotifyPlayer(player, "RemovedExcessAmmo", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), capacity);
}
else
{
// Notifique o jogador sobre a nova capacidade ajustada (apenas quando não há munição excedente)
NotifyPlayer(player, "NewCapacity", 0, GetItemDisplayName(player, weapon.GetItem()?.info?.shortname), capacity);
}
// Sincroniza o estado da arma e do jogador com o servidor e cliente
weapon.SendNetworkUpdateImmediate();
player.SendNetworkUpdateImmediate();
}
AdjustMagazineCapacity
Ajusta diretamente a capacidade do carregador da arma:
Calcula o multiplicador da capacidade com base nos modificadores (mods acoplados à arma, como Extended Mag):
csharp
private float CalculateMagazineMultiplier(BaseProjectile weapon)
{
if (weapon.children == null)
return 1f; // Nenhum modificador presente -> sem multiplicador
// Itera pelos modificadores e calcula o multiplicador final
float multiplier = 1f;
foreach (var child in weapon.children)
{
if (child is ProjectileWeaponMod mod && mod.magazineCapacity.enabled)
{
// Acrescenta o multiplicador ativo para magazines
multiplier *= mod.magazineCapacity.scalar > 0 ? mod.magazineCapacity.scalar : 1f;
}
}
return multiplier; // Retorna o multiplicador total dos mods
}
CalculateDesiredCapacity
Calcula a capacidade personalizada para jogadores com permissão: