turns-00037.parquet:16520
2a3735b716a4513c41d67f5f
turn 6/12gpt-4o-2024-08-06PortugueseBrazil1757 words
degenerate_repetitionAbsentFinal dense release
USER
mande o código completo:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Facepunch;
using Facepunch.Rust;
using Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using Rust;
using UnityEngine;
using UnityEngine.Assertions;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.0.0")]
[Description("IndustrialRecycler")]
class IndustrialRecycler : RustPlugin
{
#region Fields
private Configuration _config;
#endregion
#region Oxide Hooks
private void Init()
{
RegisterCommands();
}
object OnEntityKill(Recycler entity)
{
Puts("OnEntityKill works!: " + entity);
return null;
}
private void OnEntityBuilt(Planner plan, GameObject obj)
{
var player = plan?.GetOwnerPlayer();
var entity = obj.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != 3341430953)
{
return;
}
if (!DeployRecycler(player, entity))
{
player.ChatMessage("No Fundation");
timer.Once(1, () => GiveRecyclerItem(player));
}
NextTick(() => entity?.Kill());
}
#endregion
#region Commands
private void RegisterCommands()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CmdTest));
}
}
private void CmdTest(BasePlayer player, string command, string[] args)
{
GiveRecyclerItem(player);
}
#endregion
#region Utility Methods
void OnItemAddedToContainer(ItemContainer container, Item item)
{
var recyclerComponent = container?.entityOwner?.GetComponentInParent<RecyclerComponent>();
recyclerComponent?.StartMovingItems();
}
private bool DeployRecycler(BasePlayer player, BaseEntity entity)
{
var buildingBlock = GetBuildingBlock(entity);
if (buildingBlock == null)
{
return false;
}
var recycler = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab");
recycler.OwnerID = player.userID;
recycler.SetParent(buildingBlock);
recycler.transform.position = entity.transform.position;
recycler.transform.rotation = entity.transform.rotation * Quaternion.Euler(0, 270, 0);
recycler.Spawn();
recycler.SendNetworkUpdateImmediate();
var storageIn = GameManager.server.CreateEntity("assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
storageIn.SetParent(recycler, true, true);
storageIn.OwnerID = player.userID;
storageIn.transform.localPosition = new Vector3(-1.0f, 0.72f, 0.31f);
storageIn.transform.rotation = recycler.transform.rotation * Quaternion.Euler(new Vector3(90 + 0, 90, 180));
storageIn.Spawn();
storageIn.SendNetworkUpdateImmediate();
var adaptorIn =
GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab", recycler.transform.position, recycler.transform.rotation)
as IndustrialStorageAdaptor;
adaptorIn.SetParent(storageIn, true, true);
adaptorIn.OwnerID = player.userID;
adaptorIn.transform.localPosition = new Vector3(0.00f, -0.15f, -0.25f);
adaptorIn.transform.rotation = storageIn.transform.rotation * Quaternion.Euler(new Vector3(180, 90, 90 + 180));
adaptorIn.Spawn();
adaptorIn.SendNetworkUpdateImmediate();
var storageOut = GameManager.server.CreateEntity("assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");
storageOut.SetParent(recycler, true, true);
storageOut.OwnerID = player.userID;
storageOut.transform.localPosition = new Vector3(-0.9f, 0.72f, -0.09f);
storageOut.transform.rotation = recycler.transform.rotation * Quaternion.Euler(new Vector3(90 + 90, 90, 180));
storageOut.Spawn();
storageOut.SendNetworkUpdateImmediate();
var adaptorOut =
GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab", recycler.transform.position, recycler.transform.rotation)
as IndustrialStorageAdaptor;
adaptorOut.SetParent(storageOut, true, true);
adaptorOut.OwnerID = player.userID;
adaptorOut.transform.localPosition = new Vector3(0.00f, 0.26f, -0.05f);
adaptorOut.transform.rotation = storageOut.transform.rotation * Quaternion.Euler(new Vector3(0, 90, 0));
adaptorOut.Spawn();
adaptorOut.SendNetworkUpdateImmediate();
recycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock GetBuildingBlock(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
var groundEntity = hitInfo.GetEntity();
if (groundEntity is BuildingBlock buildingBlock)
{
return buildingBlock;
}
}
return null;
}
private void GiveRecyclerItem(BasePlayer player)
{
Item item = ItemManager.CreateByName("electric.generator.small", 1, 3341430953);
item.name = "Recycler";
player.inventory.GiveItem(item);
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfigValues();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfigValues()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private Configuration CreateDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "teste", "testee", "testeeee" },
};
}
#endregion
#region Components
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
public bool isMoving = false;
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
OutputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");
ValidadeContainers();
}
private void ValidadeContainers()
{
if (InputContainer == null || OutputContainer == null)
{
Debug.LogError("Critical container not found. Disabling component in Recycler: " + Recycler);
Destroy(this);
}
}
public void StartMovingItems()
{
if (!isMoving)
{
Debug.Log("StartMovingItems");
MoveItems();
}
}
private void MoveItems()
{
isMoving = true;
Debug.Log("MoveItems");
// Flag to determine if the recycler should be started
bool shouldStartRecycling = false;
// Check if OutputContainer is full
bool isOutputFull = OutputContainer.inventory.IsFull();
// Move items from the InputContainer to the first 6 slots of the Recycler
int targetSlot = 0;
var inputItems = InputContainer.inventory.itemList.ToList();
foreach (var item in inputItems)
{
if (targetSlot >= 6)
break;
if (Recycler.inventory.GetSlot(targetSlot) == null)
{
item.MoveToContainer(Recycler.inventory, targetSlot);
targetSlot++;
shouldStartRecycling = true;
}
}
// Move items from slot 7 onwards in Recycler to OutputContainer and check for items in slots 6+
bool hasItemsBeyondSlot5 = false;
for (int i = 6; i < Recycler.inventory.capacity; i++)
{
var itemInSlot = Recycler.inventory.GetSlot(i);
if (itemInSlot != null)
{
hasItemsBeyondSlot5 = true;
// Attempt to move item to OutputContainer
if (!isOutputFull)
{
itemInSlot.MoveToContainer(OutputContainer.inventory);
}
}
}
// Stop recycling if OutputContainer is full or there are any items in slots 6 onwards
if (isOutputFull || hasItemsBeyondSlot5)
{
Recycler.StopRecycling();
}
else if (shouldStartRecycling) // Only start recycling if items were moved to slots 0-5
{
Recycler.StartRecycling();
}
isMoving = false;
}
}
#endregion
}
}
ASSISTANT
Aqui está o código completo do plugin `IndustrialRecycler` ajustado para melhorar a eficiência no método `MoveItems()`, evitando sua execução frequente e baseando-se em eventos e verificações periódicas:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using Facepunch;
using Network;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Rust;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.0.0")]
[Description("IndustrialRecycler")]
class IndustrialRecycler : RustPlugin
{
#region Fields
private Configuration _config;
#endregion
#region Oxide Hooks
private void Init()
{
RegisterCommands();
}
object OnEntityKill(Recycler entity)
{
Puts("OnEntityKill works!: " + entity);
return null;
}
private void OnEntityBuilt(Planner plan, GameObject obj)
{
var player = plan?.GetOwnerPlayer();
var entity = obj.GetComponent<BaseEntity>();
if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != 3341430953)
{
return;
}
if (!DeployRecycler(player, entity))
{
player.ChatMessage("No Foundation");
timer.Once(1, () => GiveRecyclerItem(player));
}
NextTick(() => entity?.Kill());
}
#endregion
#region Commands
private void RegisterCommands()
{
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CmdTest));
}
}
private void CmdTest(BasePlayer player, string command, string[] args)
{
GiveRecyclerItem(player);
}
#endregion
#region Utility Methods
void OnItemAddedToContainer(ItemContainer container, Item item)
{
var recyclerComponent = container?.entityOwner?.GetComponentInParent<RecyclerComponent>();
recyclerComponent?.MarkNeedsUpdate();
}
private bool DeployRecycler(BasePlayer player, BaseEntity entity)
{
var buildingBlock = GetBuildingBlock(entity);
if (buildingBlock == null)
{
return false;
}
var recycler = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab");
recycler.OwnerID = player.userID;
recycler.SetParent(buildingBlock);
recycler.transform.position = entity.transform.position;
recycler.transform.rotation = entity.transform.rotation * Quaternion.Euler(0, 270, 0);
recycler.Spawn();
recycler.SendNetworkUpdateImmediate();
var storageIn = GameManager.server.CreateEntity("assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
storageIn.SetParent(recycler, true, true);
storageIn.OwnerID = player.userID;
storageIn.transform.localPosition = new Vector3(-1.0f, 0.72f, 0.31f);
storageIn.transform.rotation = recycler.transform.rotation * Quaternion.Euler(90, 90, 180);
storageIn.Spawn();
storageIn.SendNetworkUpdateImmediate();
var adaptorIn = GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab") as IndustrialStorageAdaptor;
adaptorIn.SetParent(storageIn, true, true);
adaptorIn.OwnerID = player.userID;
adaptorIn.transform.localPosition = new Vector3(0.00f, -0.15f, -0.25f);
adaptorIn.transform.rotation = storageIn.transform.rotation * Quaternion.Euler(180, 90, 270);
adaptorIn.Spawn();
adaptorIn.SendNetworkUpdateImmediate();
var storageOut = GameManager.server.CreateEntity("assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");
storageOut.SetParent(recycler, true, true);
storageOut.OwnerID = player.userID;
storageOut.transform.localPosition = new Vector3(-0.9f, 0.72f, -0.09f);
storageOut.transform.rotation = recycler.transform.rotation * Quaternion.Euler(180, 90, 270);
storageOut.Spawn();
storageOut.SendNetworkUpdateImmediate();
var adaptorOut = GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab") as IndustrialStorageAdaptor;
adaptorOut.SetParent(storageOut, true, true);
adaptorOut.OwnerID = player.userID;
adaptorOut.transform.localPosition = new Vector3(0.00f, 0.26f, -0.05f);
adaptorOut.transform.rotation = storageOut.transform.rotation * Quaternion.Euler(0, 90, 0);
adaptorOut.Spawn();
adaptorOut.SendNetworkUpdateImmediate();
recycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock GetBuildingBlock(BaseEntity entity)
{
Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
Ray ray = new Ray(origin, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
{
var groundEntity = hitInfo.GetEntity();
if (groundEntity is BuildingBlock buildingBlock)
{
return buildingBlock;
}
}
return null;
}
private void GiveRecyclerItem(BasePlayer player)
{
Item item = ItemManager.CreateByName("electric.generator.small", 1, 3341430953);
item.name = "Recycler";
player.inventory.GiveItem(item);
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception();
if (_config.Version < Version)
{
UpdateConfigValues();
}
SaveConfig();
}
catch
{
PrintError("There is an error in your configuration file. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
private void UpdateConfigValues()
{
PrintWarning("Configuration change detected! Updating settings.");
_config.Version = Version;
PrintWarning("Configuration update completed!");
}
private Configuration CreateDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "teste", "testee", "testeeee" },
};
}
#endregion
#region Components
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputContainer { get; private set; }
public StorageContainer OutputContainer { get; private set; }
public bool isMoving = false;
private bool needsMoveUpdate = true;
private float moveInterval = 1.0f;
private void Awake()
{
Recycler = GetComponent<Recycler>();
InputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
OutputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");
ValidateContainers();
// Run the MoveItems method periodically
InvokeRepeating(nameof(CheckAndMoveItems), moveInterval, moveInterval);
}
private void ValidateContainers()
{
if (InputContainer == null || OutputContainer == null)
{
Debug.LogError("Critical container not found. Disabling component in Recycler: " + Recycler);
Destroy(this);
}
}
public void MarkNeedsUpdate()
{
needsMoveUpdate = true;
}
private void CheckAndMoveItems()
{
if (needsMoveUpdate && !isMoving)
{
MoveItems();
needsMoveUpdate = false;
}
}
private void MoveItems()
{
isMoving = true;
Debug.Log("MoveItems");
// Flag to determine if the recycler should be started
bool shouldStartRecycling = false;
// Check if OutputContainer is full
bool isOutputFull = OutputContainer.inventory.IsFull();
// Move items from the InputContainer to the first 6 slots of the Recycler
int targetSlot = 0;
var inputItems = InputContainer.inventory.itemList.ToList();
foreach (var item in inputItems)
{
if (targetSlot >= 6)
break;
if (Recycler.inventory.GetSlot(targetSlot) == null)
{
item.MoveToContainer(Recycler.inventory, targetSlot);
targetSlot++;
shouldStartRecycling = true;
}
}
// Move items from slot 7 onwards in Recycler to OutputContainer and check for items in slots 6+
bool hasItemsBeyondSlot5 = false;
for (int i = 6; i < Recycler.inventory.capacity; i++)
{
var itemInSlot = Recycler.inventory.GetSlot(i);
if (itemInSlot != null)
{
hasItemsBeyondSlot5 = true;
// Attempt to move item to OutputContainer
if (!isOutputFull)
{
itemInSlot.MoveToContainer(OutputContainer.inventory);
}
}
}
// Stop recycling if OutputContainer is full or there are any items in slots 6 onwards
if (isOutputFull || hasItemsBeyondSlot5)
{
Recycler.StopRecycling();
}
else if (shouldStartRecycling) // Only start recycling if items were moved to slots 0-5
{
Recycler.StartRecycling();
}
isMoving = false;
}
}
#endregion
}
}
```
### Explicações das Alterações:
1. **Desempenho e Otimização:**
- **InvokeRepeating:** Usei `InvokeRepeating` para evitar a execução contínua do método `MoveItems()`. Agora ele verifica periodicamente, o que é menos exigente para a CPU.
- **Flag needsMoveUpdate:** Adicionei uma flag `needsMoveUpdate` que só ativa o `MoveItems()` quando uma mudança requer. Isso diminui o número de execuções desnecessárias do método.
2. **Simplificação da Lógica no Plugin:**
- Ajuste de eventos e condições para um fluxo mais simplificado, reduzindo complexidades desnecessárias e potencializando a eficiência do código.
O código modificado melhora o uso de recursos ao evitar chamadas excessivas ao `MoveItems()` e garante que a reciclagem pare corretamente quando o `OutputContainer` estiver cheio ou os slots avançados (6 em diante) do reciclador estiverem ocupados. Certifique-se de testar exaustivamente em um ambiente seguro antes de implantar em um servidor de produção.