#region Permissions
private const string PermGet = "recyclerbox.get";
private const string PermTransform = "recyclerbox.transform";
private const string PermVirtual = "recyclerbox.virtual";
private readonly List<string> Permissions = new List<string> { PermGet, PermTransform, PermVirtual };
#endregion
#region Initialization
private void OnServerInitialized()
{
foreach (var perm in Permissions)
permission.RegisterPermission(perm, this);
AddCovalenceCommand(_config.CmdGet, nameof(CmdGetRecyclerbox));
AddCovalenceCommand(_config.CmdTransform, nameof(CmdTransformRecyclerbox));
AddCovalenceCommand(_config.CmdVirtual, nameof(CmdVirtual));
}
private void Unload()
{
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, Overlay);
DestroyVirtual(player);
}
DestroyDroppedContainers();
}
#endregion
#region NoEscape
[PluginReference]
private Plugin NoEscape;
private bool IsRaidBlocked(BasePlayer player) => NoEscape?.Call<bool>("IsRaidBlocked", player) ?? false;
#endregion
#region Configuration
protected class Configuration
{
[JsonProperty("Get Recyclerbox Command")]
public string[] CmdGet = { "getrec", "getrecycler", "recyclerbox" };
[JsonProperty("Transform Recyclerbox Command")]
public string[] CmdTransform = { "trarec", "boxtorecycler", "transformrecycler", "transforbox" };
[JsonProperty("Virtual Recyclerbox Command")]
public string[] CmdVirtual = { "rec", "vrec", "virtualrecycler" };
[JsonProperty("SkinId Recycler")]
public ulong SkinIdRecycler = 2994391115;
[JsonProperty("Recycler Efficiency")]
public float RecyclerEfficiency = 0.6f;
[JsonProperty("Ratio Scrap")]
public float RatioScrap = 1.2f;
[JsonProperty("Enable Prefab Fx")]
public bool EnablePrefabFx = true;
[JsonProperty("Lock Recycler While In Use")]
public bool LockRecycler = false;
[JsonProperty("Disable During Raid Block (Requires No Escape plugin)")]
public bool RaidBlock = true;
[JsonProperty("Prefab Fx Open Recycler")]
public string PrefabFxOpen = "assets/bundled/prefabs/fx/build/promote_toptier.prefab";
[JsonProperty("Prefab Fx Close Recycler")]
public string PrefabFxClose = "assets/bundled/prefabs/fx/build/promote_toptier.prefab";
[JsonProperty("Transfer Virtual Recycled Items to Inventory")]
public bool TransferToInventory = false;
[JsonProperty("Blacklisted Items")]
public string[] Blacklist = { "lmg.m249" };
[JsonProperty("Blacklisted Skins")]
public List<ulong> BlacklistSkins = new() { 2994391115 };
public string ToJson() => JsonConvert.SerializeObject(this);
public Dictionary<string, object> ToDictionary() => JsonConvert.DeserializeObject<Dictionary<string, object>>(ToJson());
}
protected override void LoadDefaultConfig() => _config = new Configuration();
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new JsonException();
var currentConfigDict = _config.ToDictionary();
var defaultConfigDict = new Configuration().ToDictionary();
// Verifica se o dicionário atual e o dicionário padrão têm o mesmo número de entradas
if (currentConfigDict.Count != defaultConfigDict.Count)
{
Puts("Configuration appears to be outdated; updating and saving");
SaveConfig();
}
else
{
// Comparar chaves individuais
foreach (var key in currentConfigDict.Keys)
{
if (!defaultConfigDict.ContainsKey(key))
{
Puts("Configuration appears to be outdated; updating and saving");
SaveConfig();
return; // Saia do loop após salvar
}
}
}
}
catch
{
Puts($"Configuration file {Name}.json is invalid; using defaults");
LoadDefaultConfig();
}
}
protected override void SaveConfig()
{
Puts($"Configuration changes saved to {Name}.json");
Config.WriteObject(_config, true);
}
#endregion Configuration
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["RecyclerTitle"] = "RECYCLER BOX",
["RecyclerSubtitle"] = "Items are instantly recycled",
["RecyclerItemMissingMsg"] = "Recyclerbox: You aren't holding a Large Wooden Box.",
["RecyclerCreatedMsg"] = "Recyclerbox: The Box has been converted into a Recycler.",
["RecyclerAlreadyMsg"] = "Recyclerbox: This Box is currently a Recycler.",
["NotAllowed"] = "You do not have permission to use that command.",
["GotRecyclerbox"] = "Recyclerbox sent to inventory.",
["Denied Privilege"] = "You cannot recycle within someone's building privilege",
["Denied Swimming"] = "You cannot recycle while swimming",
["Denied Falling"] = "You cannot recycle while falling",
["Denied Mounted"] = "You cannot recycle while mounted",
["Denied Wounded"] = "You cannot recycle while wounded",
["Denied Ship"] = "You cannot recycle while on a ship",
["Denied Elevator"] = "You cannot recycle while on an elevator",
["Denied Balloon"] = "You cannot recycle while on a balloon",
["Denied Safe Zone"] = "You cannot recycle while in a safe zone",
["Denied Hook Denied"] = "You can't recycle right now",
["RecycleDropped"] = "You left items in the recycler and dropped them on the ground!",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["RecyclerTitle"] = "CAIXA RECICLADORA",
["RecyclerSubtitle"] = "Itens são reciclados instantaneamente",
["RecyclerItemMissingMsg"] = "Recyclerbox: Você não está segurando uma Caixa Grande de Madeira.",
["RecyclerCreatedMsg"] = "Recyclerbox: Você transformou a Caixa em um Reciclador.",
["RecyclerAlreadyMsg"] = "Recyclerbox: Esta Caixa já é um Reciclador.",
["NotAllowed"] = "Você não tem permissão para usar esse comando.",
["GotRecyclerbox"] = "Recyclerbox enviada para o inventário.",
["Denied Privilege"] = "Você não pode reciclar dentro do privilégio de construção de outro player",
["Denied Swimming"] = "Você não pode reciclar enquanto nada",
["Denied Falling"] = "Você não pode reciclar enquanto cai",
["Denied Mounted"] = "Você não pode reciclar enquanto estiver montado",
["Denied Wounded"] = "Você não pode reciclar enquanto estiver ferido",
["Denied Ship"] = "Você não pode reciclar enquanto estiver em um navio",
["Denied Elevator"] = "Você não pode reciclar enquanto estiver em um elevador",
["Denied Balloon"] = "Você não pode reciclar enquanto estiver em um balão",
["Denied Safe Zone"] = "Você não pode reciclar enquanto estiver em uma zona segura",
["Denied Hook Denied"] = "Você não pode reciclar agora",
["RecycleDropped"] = "Você deixou itens no reciclador e os deixou cair no chão!",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["RecyclerTitle"] = "RECYCLERBOX",
["RecyclerSubtitle"] = "Gegenstände werden sofort recycelt",
["RecyclerItemMissingMsg"] = "Recyclerbox: Du hast keine große Holzkiste in der Hand. (Blau hinterlegt)",
["RecyclerCreatedMsg"] = "Recyclerbox: Die Kiste wurde in ein Recyclerbox umgewandelt.",
["RecyclerAlreadyMsg"] = "Recyclerbox: Diese Kiste ist bereits eine Recyclerbox.",
["NotAllowed"] = "Du hast keine Berechtigung, diesen Befehl zu benutzen.",
["GotRecyclerbox"] = "Die Recyclerbox ist deinem Inventar gutgeschrieben worden.",
["Denied Privilege"] = "Du kannst momentan nicht recyceln, du befindest dich in einem fremden Bauradius.",
["Denied Swimming"] = "Du kannst momentan nicht recyceln, während Du schwimmst.",
["Denied Falling"] = "Du kannst momentan nicht recyceln, während Du im freienfall bist.",
["Denied Mounted"] = "Du kannst momentan nicht recyceln, während Du auf einem Fahrzeug sitzt.",
["Denied Wounded"] = "Du kannst momentan nicht recyceln, während Du verletzt bist.",
["Denied Ship"] = "Du kannst momentan nicht recyceln, da Du dich auf einem Schiff befindest.",
["Denied Elevator"] = "Du kannst momentan nicht recyceln, da Du dich im Aufzug befindest.",
["Denied Balloon"] = "Du kannst momentan nicht recyceln, da Du dich im Ballon befindest.",
["Denied Safe Zone"] = "Du kannst momentan nicht recyceln, da Du dich in einer sicheren Zone befindest.",
["Denied Hook Denied"] = "Du kannst momentan nicht recyceln.",
["RecycleDropped"] = "Du hast Gegenstände im Recycler gelassen und auf den Boden fallen lassen!",
},
this,
"de"
);
}
#endregion Localization
#region Hooks
private void OnLootEntityEnd(BasePlayer player, StorageContainer container)
{
if (container.skinID != _config.SkinIdRecycler || player == null)
return;
DestroyVirtual(player);
}
private void OnPlayerDisconnected(BasePlayer player, string reason)
{
if (player == null)
return;
DestroyVirtual(player);
if (_droppedContainers.Count == 0)
return;
// Crie uma lista de contêineres a partir do dicionário
var tmp = _droppedContainers.ToList(); // Isso assume que você está usando System.Linq
foreach (var (uid, (container, target)) in tmp)
{
if (!IsValid(container) || !IsValid(target) || target.userID == player.userID)
{
if (IsValid(container))
container.Kill();
_droppedContainers.Remove(uid);
}
}
}
private void CleanupDroppedContainers()
{
if (_droppedContainers.Count == 0)
return;
var tmp = new List<KeyValuePair<ulong, (DroppedItemContainer container, BasePlayer player)>>(_droppedContainers);
foreach (var (uid, (container, _)) in tmp)
{
if (IsValid(container))
container.Kill();
_droppedContainers.Remove(uid);
}
}
private void OnLootEntity(BasePlayer player, StorageContainer storageContainer)
{
if (storageContainer.skinID != _config.SkinIdRecycler)
return;
storageContainer.inventory.capacity = 42;
if (_config.EnablePrefabFx)
Effect.server.Run(_config.PrefabFxOpen, player.GetNetworkPosition());
if (_config.LockRecycler)
storageContainer.SetFlag(BaseEntity.Flags.Locked, true);
CreateUI(player);
}
private void OnItemRemovedFromContainer(ItemContainer container, Item item)
{
if (IsValid(container?.entityOwner) && container.entityOwner.skinID == _config.SkinIdRecycler)
{
item.SetFlag(ItemWasScrapedFlag, false);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
if (IsValid(container?.entityOwner) && container.entityOwner.skinID == _config.SkinIdRecycler && !item.flags.HasFlag(ItemWasScrapedFlag))
{
var player = BasePlayer.FindByID(container.entityOwner.OwnerID);
if (player != null && _config.RaidBlock && IsRaidBlocked(player))
return;
SalvageItem(container, item);
}
}
private void OnPlayerLootEnd(PlayerLoot inventory)
{
if (inventory.baseEntity is not BasePlayer player)
return;
foreach (var container in inventory.containers)
{
if (IsValid(container?.entityOwner) && container.entityOwner.skinID == _config.SkinIdRecycler)
{
CuiHelper.DestroyUi(player, Overlay);
if (!container.entityOwner.IsBusy())
{
if (_config.EnablePrefabFx)
Effect.server.Run(_config.PrefabFxClose, player.GetNetworkPosition());
if (_config.LockRecycler)
container.entityOwner.SetFlag(BaseEntity.Flags.Locked, false);
}
}
}
}
private object CanLootEntity(BasePlayer player, DroppedItemContainer container)
{
return container.IsValid() && _droppedContainers.TryGetValue(container.net.ID.Value, out var data) && data.player.userID != player.userID ? true : null;
}
private void OnEntityKill(DroppedItemContainer container)
{
if (IsValid(container))
_droppedContainers.Remove(container.net.ID.Value);
}
private object CanAcceptItem(ItemContainer container, Item item, int targetPos)
{
if (IsValid(container?.entityOwner) && container.entityOwner.skinID == _config.SkinIdRecycler)
{
if (_config.Blacklist.Contains(item.info.shortname) || _config.BlacklistSkins.Contains(item.skin))
{
return ItemContainer.CanAcceptResult.CannotAcceptRightNow;
}
}
return null;
}
#endregion
#region Functions
void SalvageItem(ItemContainer container, Item item)
{
bool moveBackFromVirtual = false;
BasePlayer player = null;
if (_config.TransferToInventory && container.entityOwner.name == "Virtual")
{
moveBackFromVirtual = true;
player = BasePlayer.FindByID(container.entityOwner.OwnerID);
container = player.inventory.containerMain;
}
if (item.info.Blueprint == null)
{
TryMoveBack(item, container, player, moveBackFromVirtual);
return;
}
float efficiency = _config.RecyclerEfficiency;
if (item.hasCondition)
efficiency *= Mathf.Clamp(item.conditionNormalized * item.maxConditionNormalized, 0.1f, 1f);
int itemAmount = item.amount > 1 ? item.amount : 1;
if (item.info.Blueprint.scrapFromRecycle > 0)
{
TryProduceScrap(item, itemAmount, container, player, moveBackFromVirtual, efficiency);
}
item.UseItem(itemAmount);
ProduceIngredients(item, itemAmount, container, moveBackFromVirtual, player, efficiency);
}
private void TryMoveBack(Item item, ItemContainer container, BasePlayer player, bool moveBackFromVirtual)
{
if (moveBackFromVirtual)
{
if (!item.MoveToContainer(container))
{
item.Drop(player.GetCenter(), player.GetDropVelocity());
}
}
}
private void TryProduceScrap(Item item, int itemAmount, ItemContainer container, BasePlayer player, bool moveBackFromVirtual, float efficiency)
{
float ratioScrap = _config.RatioScrap;
int scrap = 0;
try
{
float scrapAmount = item.info.Blueprint.scrapFromRecycle * itemAmount * ratioScrap;
scrap = (int)scrapAmount;
if (scrapAmount < 1f && UnityEngine.Random.Range(0f, 1f) >= ratioScrap)
return;
scrap = scrap > 0 ? scrap : 1; // Ensure at least 1 scrap.
Item newItem = ItemManager.CreateByName("scrap", scrap, 0);
if (!moveBackFromVirtual)
newItem.SetFlag(ItemWasScrapedFlag, true);
if (!newItem.MoveToContainer(container) && player != null)
{
newItem.Drop(player.GetCenter(), player.GetDropVelocity());
}
}
catch
{
Puts($"GOT ERROR recycling {item.info.shortname} for scrap {scrap}", this);
}
}
private void ProduceIngredients(Item item, int itemAmount, ItemContainer container, bool moveBackFromVirtual, BasePlayer player, float efficiency)
{
foreach (ItemAmount ingredient in item.info.Blueprint.ingredients)
{
if (ingredient.itemDef.shortname != "scrap")
{
int ingredientsToProduce = Mathf.FloorToInt(itemAmount * efficiency * ingredient.amount / item.info.Blueprint.amountToCreate);
// Certificar que ao menos um ingrediente é produzido
if (ingredientsToProduce < 1 && UnityEngine.Random.Range(0f, 1f) > 0.5f)
ingredientsToProduce = 1;
// Se a quantidade a ser criada é maior que 0
if (ingredientsToProduce > 0)
{
for (int i = 0; i < ingredientsToProduce; i += ingredient.itemDef.stackable)
{
int toCreate = Mathf.Min(ingredientsToProduce - i, ingredient.itemDef.stackable);
try
{
Item newItem = ItemManager.Create(ingredient.itemDef, toCreate, 0);
if (!moveBackFromVirtual)
newItem.SetFlag(ItemWasScrapedFlag, true);
if (!newItem.MoveToContainer(container) && player != null)
{
newItem.Drop(player.GetCenter(), player.GetDropVelocity());
}
}
catch
{
Puts($"GOT ERROR recycling {item.info.shortname} to ingredient {ingredient.itemDef.shortname}", this);
}
}
}
}
}
}
private void CreateUI(BasePlayer player)
{
var elements = new CuiElementContainer();
var mainConfigPanel = elements.Add(
new CuiPanel
{
Image = { Color = "1 0.96 0.88 0.15" },
RectTransform =
{
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
OffsetMin = "192.5 610",
OffsetMax = "572.5 633",
},
CursorEnabled = false,
},
"Overlay",
Overlay
);
// Passar o player como argumento para AddLabel
AddLabel(elements, mainConfigPanel, "RecyclerTitle", 18, player);
AddLabel(elements, mainConfigPanel, "RecyclerSubtitle", 14, player);
CuiHelper.AddUi(player, elements);
}
private void AddLabel(CuiElementContainer elements, string parentPanel, string langKey, int fontSize, BasePlayer player)
{
elements.Add(
new CuiLabel
{
Text =
{
Text = lang.GetMessage(langKey, this, player.UserIDString), // Aqui estamos utilizando o player passado como argumento
Align = TextAnchor.MiddleCenter,
FontSize = fontSize,
Color = "1 1 1 1",
Font = fontSize == 18 ? "robotocondensed-bold.ttf" : "robotocondensed-regular.ttf",
},
RectTransform = { AnchorMin = "0 0", AnchorMax = "1 1" },
},
parentPanel
);
}
public bool IsValid(BaseNetworkable entity) => entity.IsValid() && !entity.IsDestroyed;
private StorageContainer CreateVirtual(BasePlayer player)
{
var recyclerBox = GameManager.server.CreateEntity(PrefabBox, player.transform.position.WithY(-5f)) as StorageContainer;
recyclerBox.skinID = _config.SkinIdRecycler;
if (recyclerBox == null)
return null;
recyclerBox.enableSaving = false;
recyclerBox.Spawn();
if (!IsValid(recyclerBox))
return null;
recyclerBox.name = "Virtual";
recyclerBox.OwnerID = player.userID;
recyclerBox.SetFlag(BaseEntity.Flags.Locked, true);
recyclerBox.UpdateNetworkGroup();
recyclerBox.gameObject.layer = 0;
recyclerBox.SendNetworkUpdateImmediate(true);
OpenContainer(player, recyclerBox);
_recyclers[recyclerBox.net.ID.Value] = (recyclerBox, player);
return recyclerBox;
}
private void OpenContainer(BasePlayer player, StorageContainer container)
{
player.Invoke(
() =>
{
if (!IsValid(container))
return;
player.EndLooting();
if (!player.inventory.loot.StartLootingEntity(container, false))
return;
player.inventory.loot.AddContainer(container.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPC(RpcTarget.Player("RPC_OpenLootPanel", player), container.panelName);
player.SendNetworkUpdate();
},
0.2f
);
}
private StorageContainer RecyclerFromPlayer(ulong userId)
{
foreach (var (recycler, player) in _recyclers.Values)
{
if (player?.userID == userId)
return recycler;
}
return null;
}
private void DropRecyclerContents(StorageContainer recyclerBox, BasePlayer player)
{
if (player == null || player.inventory?.containerMain == null || recyclerBox?.inventory?.itemList.IsNullOrEmpty() != false)
return;
var items = Pool.Get<List<Item>>();
items.AddRange(recyclerBox.inventory.itemList);
if (items.Count == 0)
{
Pool.FreeUnmanaged(ref items);
return;
}
player.ChatMessage(lang.GetMessage("RecycleDropped", this, player.UserIDString));
var container = GameManager.server.CreateEntity(PrefabDrop, player.transform.position + Vector3.up) as DroppedItemContainer;
if (container == null)
return;
container.enableSaving = false;
container.lootPanelName = "generic_resizable";
container.playerSteamID = player.userID;
container.TakeFrom(new[] { recyclerBox.inventory });
container.Spawn();
if (IsValid(container))
_droppedContainers[container.net.ID.Value] = (container, player);
Pool.FreeUnmanaged(ref items);
}
private void DestroyVirtual(BasePlayer player)
{
StorageContainer recycler = RecyclerFromPlayer(player.userID);
if (IsValid(recycler) && _recyclers.Remove(recycler.net.ID.Value))
{
DropRecyclerContents(recycler, player);
recycler.Kill();
}
}
private void DestroyDroppedContainers()
{
if (_droppedContainers.Count == 0)
return;
var tmp = Pool.Get<List<KeyValuePair<ulong, (DroppedItemContainer container, BasePlayer player)>>>();
tmp.AddRange(_droppedContainers);
foreach (var (uid, (container, _)) in tmp)
{
if (IsValid(container))
container.Kill();
_droppedContainers.Remove(uid);
}
Pool.FreeUnmanaged(ref tmp);
}
private void OpenVirtual(BasePlayer player)
{
if (player == null || !CanPlayerOpenRecycler(player))
return;
DestroyVirtual(player);
CreateVirtual(player);
}
private bool CanPlayerOpenRecycler(BasePlayer player)
{
if (player == null || !player.IsAlive())
player.ChatMessage(lang.GetMessage("Denied Hook Denied", this, player.UserIDString));
else if (player.IsWounded())
player.ChatMessage(lang.GetMessage("Denied Wounded", this, player.UserIDString));
else if (!player.CanBuild())
player.ChatMessage(lang.GetMessage("Denied Privilege", this, player.UserIDString));
else if (player.IsSwimming())
player.ChatMessage(lang.GetMessage("Denied Swimming", this, player.UserIDString));
else if (!player.IsOnGround() || player.IsFlying || player.isInAir)
player.ChatMessage(lang.GetMessage("Denied Falling", this, player.UserIDString));
else if (player.isMounted || player.GetParentEntity() is BaseMountable)
player.ChatMessage(lang.GetMessage("Denied Mounted", this, player.UserIDString));
else if (player.GetComponentInParent<CargoShip>())
player.ChatMessage(lang.GetMessage("Denied Ship", this, player.UserIDString));
else if (player.GetComponentInParent<HotAirBalloon>())
player.ChatMessage(lang.GetMessage("Denied Balloon", this, player.UserIDString));
else if (player.GetComponentInParent<Lift>())
player.ChatMessage(lang.GetMessage("Denied Elevator", this, player.UserIDString));
else
return true;
return false;
}
#endregion
#region Commands
private void CmdGetRecyclerbox(IPlayer iplayer, string command, string[] args)
{
if (!(iplayer.Object is BasePlayer player))
return;
if (!iplayer.HasPermission(PermGet))
{
player.ChatMessage(lang.GetMessage("NotAllowed", this, player.UserIDString));
return;
}
Item recyclerBox = ItemManager.CreateByName("box.wooden.large");
recyclerBox.skin = _config.SkinIdRecycler;
player.GiveItem(recyclerBox, BaseEntity.GiveItemReason.PickedUp);
player.ChatMessage(lang.GetMessage("GotRecyclerbox", this, player.UserIDString));
}
private void CmdTransformRecyclerbox(IPlayer iplayer, string command, string[] args)
{
if (!(iplayer.Object is BasePlayer player))
return;
if (!iplayer.HasPermission(PermTransform))
{
player.ChatMessage(lang.GetMessage("NotAllowed", this, player.UserIDString));
return;
}
Item activeItem = player.GetActiveItem();
if (activeItem == null || activeItem.info.shortname != "box.wooden.large")
{
player.ChatMessage(lang.GetMessage("RecyclerItemMissingMsg", this, player.UserIDString));
return;
}
if (activeItem.skin == _config.SkinIdRecycler)
{
player.ChatMessage(lang.GetMessage("RecyclerAlreadyMsg", this, player.UserIDString));
return;
}
player.ChatMessage(lang.GetMessage("RecyclerCreatedMsg", this, player.UserIDString));
activeItem.skin = _config.SkinIdRecycler;
}
private void CmdVirtual(IPlayer iplayer, string command, string[] args)
{
if (!(iplayer.Object is BasePlayer player))
return;
if (!iplayer.HasPermission(PermVirtual))
{
player.ChatMessage(lang.GetMessage("NotAllowed", this, player.UserIDString));
return;
}
OpenVirtual(player);
}
#endregion
}