The code you've provided is a C# plugin for the game Rust, specifically designed for the Oxide modding platform. The plugin is named "Dungeons" and its main functionality is to manage the creation and automatic spawning of "Christmas Dungeons" within the game.
User
Assistant
User
Assistant
User
isso não funciona protected override void PostSpawnProces
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
using System.Collections.Generic;
using Facepunch;
using Newtonsoft.Json;
using Rust;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Oxide.Plugins
{
[Info("Dungeons", "Marte6", "1.0.0")]
public class Dungeons : RustPlugin
{
private static PluginConfig _config;
private Timer _autoSpawnTimer;
private const string DungeonPrefabPath = "assets/prefabs/missions/portal/xmasportalentry.prefab";
private XmasDungeon _currentDungeon;
private List _spawnedEntities = new List();
code
#region Initialization and Configuration
private void Init()
{
LoadConfig();
if (_config.EnableAutoSpawn)
{
StartAutoSpawnTimer();
}
}
protected override void LoadConfig()
{
base.LoadConfig();
_config = Config.ReadObject<PluginConfig>() ?? CreateDefaultConfig();
if (IsConfigOutdated())
{
UpdateConfig();
}
SaveConfig();
}
protected override void LoadDefaultConfig()
{
_config = CreateDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private PluginConfig CreateDefaultConfig()
{
return new PluginConfig
{
Version = Version.ToString(),
EnableAutoSpawn = true,
AutoSpawnIntervalMinutes = 30f,
MinSpawnDistance = 6f,
MaxSpawnDistance = 20f,
MaxSpawnAttempts = 5,
NpcSpawnConfigs = new List<NpcSpawnConfig>
{
new NpcSpawnConfig { PrefabName = "assets/rust.ai/agents/npcplayer/humannpc/tunneldweller/npc_tunneldweller.prefab", EntitysPerCell = 2 },
new NpcSpawnConfig { PrefabName = "assets/rust.ai/agents/wolf/wolf.prefab", EntitysPerCell = 2 },
},
AutoTurretConfigs = new List<DefensiveStructureConfig>
{
new DefensiveStructureConfig { PrefabName = "assets/prefabs/npc/autoturret/autoturret_deployed.prefab", EntitysPerCell = 2 },
},
LandmineConfigs = new List<DefensiveStructureConfig>
{
new DefensiveStructureConfig { PrefabName = "assets/prefabs/deployable/landmine/landmine.prefab", EntitysPerCell = 2 },
},
BearTrapConfigs = new List<DefensiveStructureConfig>
{
new DefensiveStructureConfig { PrefabName = "assets/prefabs/deployable/bear trap/beartrap.prefab", EntitysPerCell = 2 },
},
};
}
private bool IsConfigOutdated()
{
return string.Compare(_config.Version, Version.ToString()) < 0;
}
private void UpdateConfig()
{
PrintWarning("Config changes detected! Updating...");
var defaultConfig = CreateDefaultConfig();
if (IsConfigOutdated())
{
_config = defaultConfig;
}
PrintWarning($"Config update complete! Updated from version {_config.Version} to {Version.ToString()}");
_config.Version = Version.ToString();
}
#endregion
#region Dungeon Management
[ChatCommand("dun")]
private void CreateDungeonCommand(BasePlayer player, string command, string[] args)
{
RemoveExistingDungeon();
if (TryFindDungeonSpawnPoint(player.transform.position, out var position, out var rotation))
{
_currentDungeon = CreateDungeon(position, rotation);
player.ChatMessage("Christmas Dungeon created!");
}
else
{
player.ChatMessage("Could not find a suitable location for the Christmas Dungeon.");
}
}
private void StartAutoSpawnTimer()
{
_autoSpawnTimer = timer.Every(_config.AutoSpawnIntervalMinutes * 60f, AutoSpawnDungeon);
}
private void AutoSpawnDungeon()
{
RemoveExistingDungeon();
for (var attempt = 0; attempt < _config.MaxSpawnAttempts; attempt++)
{
foreach (var player in BasePlayer.activePlayerList)
{
if (!TryFindDungeonSpawnPoint(player.transform.position, out var position, out var rotation))
continue;
_currentDungeon = CreateDungeon(position, rotation);
NotifyPlayersOfDungeonLocation(position);
return;
}
}
Puts("Failed to auto-spawn dungeon after max attempts.");
}
private void NotifyPlayersOfDungeonLocation(Vector3 position)
{
foreach (var player in BasePlayer.activePlayerList)
{
player.ChatMessage($"A Christmas Dungeon has appeared at coordinates: ({position.x:F0}, {position.z:F0})!");
}
}
private XmasDungeon CreateDungeon(Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(DungeonPrefabPath, position, rotation) as XmasDungeon;
if (entity == null)
{
Puts("Failed to create dungeon entity.");
return null;
}
entity.Spawn();
IntegrateEntitiesIntoDungeon(entity);
return entity;
}
private void IntegrateEntitiesIntoDungeon(XmasDungeon dungeon)
{
var proceduralDungeon = dungeon.dungeonInstance.Get(serverside: true);
if (proceduralDungeon == null)
{
Puts("Failed to get procedural dungeon instance.");
return;
}
int cellCount = proceduralDungeon.spawnedCells.Count;
if (cellCount == 0)
{
Puts("No cells found in dungeon for entities.");
return;
}
// Create a single list of all entities to be spawned
var allSpawnEntries = new List<SpawnGroup.SpawnEntry>();
// Add NPCs
foreach (var config in _config.NpcSpawnConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = true,
}
);
}
}
}
// Add Auto Turrets
foreach (var config in _config.AutoTurretConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = false,
}
);
}
}
}
// Add Landmines
foreach (var config in _config.LandmineConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = false,
}
);
}
}
}
// Add Bear Traps
foreach (var config in _config.BearTrapConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = false,
}
);
}
}
}
// Integrate all entities into each cell
foreach (var cell in proceduralDungeon.spawnedCells)
{
SetupSpawnGroup(cell, allSpawnEntries);
}
}
private void SetupSpawnGroup(ProceduralDungeonCell cell, List<SpawnGroup.SpawnEntry> allSpawnEntries)
{
var spawnGroup = cell.gameObject.AddComponent<SpawnGroup>();
spawnGroup.prefabs = allSpawnEntries;
spawnGroup.maxPopulation = 100;
spawnGroup.numToSpawnPerTickMin = 0;
spawnGroup.numToSpawnPerTickMax = 0;
spawnGroup.fillOnSpawn = true;
spawnGroup.wantsInitialSpawn = true;
spawnGroup.SpawnInitial();
foreach (var instance in spawnGroup.spawnInstances)
{
var entity = instance.GetComponent<BaseEntity>();
if (entity != null && !_spawnedEntities.Contains(entity))
{
_spawnedEntities.Add(entity);
Puts($"Entity {entity.ShortPrefabName} spawned at {entity.transform.position}");
}
}
}
private Vector3 GetRandomPositionNearby(Vector3 center, float minRadius, float maxRadius)
{
Vector2 randomCircle = Random.insideUnitCircle * Random.Range(minRadius, maxRadius);
return new Vector3(center.x + randomCircle.x, center.y, center.z + randomCircle.y);
}
#endregion
#region Utility and Cleanup
private bool TryFindDungeonSpawnPoint(Vector3 center, out Vector3 suitablePosition, out Quaternion suitableRotation)
{
suitablePosition = Vector3.zero;
suitableRotation = Quaternion.identity;
for (var attempt = 0; attempt < _config.MaxSpawnAttempts; attempt++)
{
var potentialPosition = TerrainUtilities.GetRandomPosition(center, _config.MinSpawnDistance, _config.MaxSpawnDistance);
if (!TerrainUtilities.TryGetTerrainInfo(potentialPosition, 5f, out var hitInfo) || !IsPositionSuitable(potentialPosition))
{
continue;
}
suitablePosition = hitInfo.point;
suitableRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
return true;
}
return false;
}
private bool IsPositionSuitable(Vector3 position)
{
return !TerrainUtilities.ContainsRock(position, 2f)
&& !TerrainUtilities.IsInRadTown(position)
&& !TerrainUtilities.ContainsEntitiesNearby(position, 4f, TerrainUtilities.EntityLayerMask)
&& !TerrainUtilities.IsInWater(position)
&& !TerrainUtilities.IsOnRoadOrRail(position)
&& !TerrainUtilities.IsInNoBuildZone(position, 2f);
}
private void RemoveExistingDungeon()
{
if (_currentDungeon != null)
{
foreach (var entity in _spawnedEntities)
{
if (entity != null && !entity.IsDestroyed)
{
entity.Kill(BaseNetworkable.DestroyMode.None);
}
}
_spawnedEntities.Clear();
_currentDungeon.Kill(BaseNetworkable.DestroyMode.None);
_currentDungeon = null;
}
}
private void Unload()
{
RemoveExistingDungeon();
if (_autoSpawnTimer != null)
{
_autoSpawnTimer.Destroy();
}
}
#endregion
#region Configuration Classes
private class PluginConfig
{
[JsonProperty("Version")]
public string Version { get; set; }
[JsonProperty("Auto Spawn Enabled")]
public bool EnableAutoSpawn { get; set; }
[JsonProperty("Auto Spawn Interval Minutes")]
public float AutoSpawnIntervalMinutes { get; set; }
[JsonProperty("Min Spawn Distance")]
public float MinSpawnDistance { get; set; }
[JsonProperty("Max Spawn Distance")]
public float MaxSpawnDistance { get; set; }
[JsonProperty("Max Spawn Attempts")]
public int MaxSpawnAttempts { get; set; }
[JsonProperty("NPC Spawn Configs")]
public List<NpcSpawnConfig> NpcSpawnConfigs { get; set; }
[JsonProperty("Auto Turret Configs")]
public List<DefensiveStructureConfig> AutoTurretConfigs { get; set; }
[JsonProperty("Landmine Configs")]
public List<DefensiveStructureConfig> LandmineConfigs { get; set; }
[JsonProperty("Bear Trap Configs")]
public List<DefensiveStructureConfig> BearTrapConfigs { get; set; }
}
private class NpcSpawnConfig
{
[JsonProperty("Prefab")]
public string PrefabName { get; set; }
[JsonProperty("Entitys Per Cell")]
public int EntitysPerCell { get; set; }
}
private class DefensiveStructureConfig
{
[JsonProperty("Prefab")]
public string PrefabName { get; set; }
[JsonProperty("Entitys Per Cell")]
public int EntitysPerCell { get; set; }
}
#endregion
}
public static class TerrainUtilities
{
public const int EntityLayerMask = Layers.Mask.Deployed | Layers.Mask.Construction;
public const int GroundLayerMask = Layers.Mask.Terrain | Layers.Mask.World | Layers.Mask.Default;
public static bool OnTopology(Vector3 position, TerrainTopology.Enum topology)
{
return (TerrainMeta.TopologyMap.GetTopology(position) & (int)topology) != 0;
}
public static bool IsOnRoadOrRail(Vector3 position)
{
return OnTopology(position, TerrainTopology.Enum.Road | TerrainTopology.Enum.Roadside | TerrainTopology.Enum.Rail | TerrainTopology.Enum.Railside);
}
public static bool IsInNoBuildZone(Vector3 position, float radius)
{
return Physics.CheckSphere(position, radius, Layers.Mask.Prevent_Building);
}
public static bool IsInWater(Vector3 position)
{
return WaterLevel.Test(position, false, true);
}
public static bool ContainsRock(Vector3 position, float radius)
{
var colliders = Pool.GetList<Collider>();
Vis.Colliders(position, radius, colliders, GroundLayerMask, QueryTriggerInteraction.Ignore);
bool result = colliders.Exists(collider =>
collider.name.Contains("rock", System.StringComparison.OrdinalIgnoreCase)
|| collider.name.Contains("cliff", System.StringComparison.OrdinalIgnoreCase)
|| collider.name.Contains("formation", System.StringComparison.OrdinalIgnoreCase)
);
Pool.FreeList(ref colliders);
return result;
}
public static bool IsInRadTown(Vector3 position)
{
foreach (var monumentInfo in TerrainMeta.Path.Monuments)
{
if (monumentInfo.IsInBounds(position) && monumentInfo.shouldDisplayOnMap)
{
return true;
}
}
return OnTopology(position, TerrainTopology.Enum.Monument);
}
public static bool ContainsEntitiesNearby(Vector3 position, float radius, int mask)
{
var hitColliders = Pool.GetList<Collider>();
GamePhysics.OverlapSphere(position, radius, hitColliders, mask, QueryTriggerInteraction.Ignore);
bool result = hitColliders.Exists(collider => collider.gameObject.ToBaseEntity() != null);
Pool.FreeList(ref hitColliders);
return result;
}
public static bool TryGetTerrainInfo(Vector3 startPosition, float range, out RaycastHit hitInfo)
{
return Physics.Linecast(startPosition + new Vector3(0f, range, 0f), startPosition - new Vector3(0f, range, 0f), out hitInfo, GroundLayerMask);
}
public static Vector3 GetRandomPosition(Vector3 center, float minRadius, float maxRadius)
{
Vector3 randomDirection = Random.onUnitSphere;
randomDirection.y = 0;
float randomDistance = Random.Range(minRadius, maxRadius);
Vector3 randomPosition = center + randomDirection * randomDistance;
randomPosition.y = TerrainMeta.HeightMap.GetHeight(randomPosition);
return randomPosition;
}
}
}
Here's a brief overview of the plugin's components and its functionality:
Configuration Management
The plugin reads its configuration from a JSON file and updates it if it's outdated.
Configurations include options for enabling auto-spawning, setting spawn intervals, and defining NPCs and defensive structures that should be spawned in the dungeons.
Dungeon Management
The plugin can create a dungeon at a specified location or automatically find a suitable location for it to be spawned.
Dungeons contain various entities such as NPCs, auto-turrets, landmines, and bear traps, which are specified in the configuration.
Commands and Auto-Spawning
Players can use a chat command (/dun) to manually create a dungeon.
If enabled, the plugin can automatically spawn dungeons at set intervals near active players, notifying everyone of the dungeon's location.
Utility Functions
The plugin includes various utility methods for checking terrain properties like whether a position is on a road or in a water body, and for performing raycasts to determine appropriate dungeon spawn points.
It ensures that dungeons are not spawned in non-suitable locations, like inside rocks or too close to monuments (Radtowns).
Cleanup and Resource Management
When a dungeon is removed or the plugin unloads, all spawned entities are cleaned up to prevent resource leaks or issues.
TerrainUtilities
This helper class handles terrain-related checks and calculations, like getting a random position within a given range and checking for the presence of obstacles or specific terrain features.
This plugin incorporates several useful Oxide methodologies for managing server-side gameplay features in Rust, ensuring that dungeons are spawned efficiently and in appropriate locations to enhance the gameplay experience. If you want to modify or add features to this plugin, you'd typically adjust the configuration management and dungeon setup logic according to your desired changes.
quero que esse plugin Dungeons, faça o mesmo que é feito no plugin que vou passar em relação as turrets, colocar arma, e ela atirar
/*
using Facepunch;
using Newtonsoft.Json;
using Oxide.Core;
using Rust;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Oxide.Plugins
{
[Info("Raidable Shelters", "VisEntities", "1.7.1")]
[Description("Spawns shelters filled with loot for players to raid.")]
public class RaidableShelters : RustPlugin
{
#region Fields
code
private static RaidableShelters _plugin;
private static Configuration _config;
private StoredData _storedData;
private System.Random _randomGenerator = new System.Random();
private Timer _sheltersRespawnTimer;
private const int LAYER_GROUND = Layers.Mask.Terrain | Layers.Mask.World | Layers.Mask.Default;
private const int LAYER_PLAYER = Layers.Mask.Player_Server;
private const int LAYER_ENTITIES = Layers.Mask.Deployed | Layers.Mask.Construction;
private const string PREFAB_AUTO_TURRET = "assets/prefabs/npc/autoturret/autoturret_deployed.prefab";
private const string PREFAB_LEGACY_SHELTER = "assets/prefabs/building/legacy.shelter.wood/legacy.shelter.wood.deployed.prefab";
private const string PREFAB_LANDMINE = "assets/prefabs/deployable/landmine/landmine.prefab";
private const string PREFAB_BEAR_TRAP = "assets/prefabs/deployable/bear trap/beartrap.prefab";
private const float SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER = 1.7f;
private static readonly Vector3 _autoTurretPosition = new Vector3(0.084f, 3.146f, 0.481f);
private static readonly Vector3 _autoTurretRotation = new Vector3(355.103f, 0f, 0f);
#endregion Fields
#region Configuration
private class Configuration
{
[JsonProperty("Version")]
public string Version { get; set; }
[JsonProperty("Enable Debug")]
public bool EnableDebug { get; set; }
[JsonProperty("Number Of Attempts To Find Shelter Position Near Players")]
public int NumberOfAttemptsToFindShelterPositionNearPlayers { get; set; }
[JsonProperty("Minimum Search Radius For Shelter Position Around Player")]
public float MinimumSearchRadiusForShelterPositionAroundPlayer { get; set; }
[JsonProperty("Maximum Search Radius For Shelter Position Around Player")]
public float MaximumSearchRadiusForShelterPositionAroundPlayer { get; set; }
[JsonProperty("Shelters Respawn Frequency Minutes")]
public float SheltersRespawnFrequencyMinutes { get; set; }
[JsonProperty("Delay Between Each Shelter Spawn Seconds")]
public float DelayBetweenEachShelterSpawnSeconds { get; set; }
[JsonProperty("Nearby Entities Avoidance Radius")]
public float NearbyEntitiesAvoidanceRadius { get; set; }
[JsonProperty("Rocks Avoidance Radius")]
public float RocksAvoidanceRadius { get; set; }
[JsonProperty("Distance From No Build Zones")]
public float DistanceFromNoBuildZones { get; set; }
[JsonProperty("Shelter Health")]
public float ShelterHealth { get; set; }
[JsonProperty("Shelter Lifetime Seconds")]
public float ShelterLifetimeSeconds { get; set; }
[JsonProperty("Number Of Attempts For Determining Entity Position Inside Shelter")]
public int NumberOfAttemptsForDeterminingEntityPositionInsideShelter { get; set; }
[JsonProperty("Number Of Attempts For Determining Entity Rotation Inside Shelter")]
public int NumberOfAttemptsForDeterminingEntityRotationInsideShelter { get; set; }
[JsonProperty("Door")]
public DoorConfig Door { get; set; }
[JsonProperty("Turret")]
public TurretConfig Turret { get; set; }
[JsonProperty("Trap")]
public TrapConfig Trap { get; set; }
[JsonProperty("Notification")]
public NotificationConfig Notification { get; set; }
[JsonProperty("Interior Entities")]
public List<InteriorEntityConfig> InteriorEntities { get; set; }
[JsonProperty("Items To Spawn Inside Entity Containers")]
public List<ItemInfo> ItemsToSpawnInsideEntityContainers { get; set; }
}
public class DoorConfig
{
[JsonProperty("Skin Ids")]
public List<ulong> SkinIds { get; set; }
}
public class TurretConfig
{
[JsonProperty("Spawn Auto Turret")]
public bool SpawnAutoTurret { get; set; }
[JsonProperty("Health")]
public float Health { get; set; }
[JsonProperty("Weapon Short Name")]
public string WeaponShortName { get; set; }
[JsonProperty("Clip Ammo")]
public ItemInfo ClipAmmo { get; set; }
[JsonProperty("Reserve Ammo")]
public List<ItemInfo> ReserveAmmo { get; set; }
[JsonProperty("Attachment Short Names")]
public List<string> AttachmentShortNames { get; set; }
[JsonProperty("Peacekeeper")]
public bool Peacekeeper { get; set; }
}
public class TrapConfig
{
[JsonProperty("Spawn Landmines")]
public bool SpawnLandmines { get; set; }
[JsonProperty("Spawn Bear Traps")]
public bool SpawnBearTraps { get; set; }
[JsonProperty("Minimum Number Of Traps To Spawn")]
public int MinimumNumberOfTrapsToSpawn { get; set; }
[JsonProperty("Maximum Number Of Traps To Spawn")]
public int MaximumNumberOfTrapsToSpawn { get; set; }
[JsonProperty("Minimum Spawn Radius Around Shelter")]
public float MinimumSpawnRadiusAroundShelter { get; set; }
[JsonProperty("Maximum Spawn Radius Around Shelter")]
public float MaximumSpawnRadiusAroundShelter { get; set; }
}
public class NotificationConfig
{
[JsonProperty("Notify Surrounding Players Of Shelter Spawn")]
public bool NotifySurroundingPlayersOfShelterSpawn { get; set; }
[JsonProperty("Radius For Notifying Nearby Players")]
public float RadiusForNotifyingNearbyPlayers { get; set; }
[JsonProperty("Send As Toast")]
public bool SendAsToast { get; set; }
}
public class InteriorEntityConfig
{
[JsonProperty("Prefab Name")]
public string PrefabName { get; set; }
[JsonProperty("Skin Ids")]
public List<ulong> SkinIds { get; set; }
[JsonProperty("Spawn Chance")]
public int SpawnChance { get; set; }
[JsonProperty("Minimum Number To Spawn")]
public int MinimumNumberToSpawn { get; set; }
[JsonProperty("Maximum Number To Spawn")]
public int MaximumNumberToSpawn { get; set; }
[JsonProperty("Percentage To Fill Container With Items If Present")]
public int PercentageToFillContainerWithItemsIfPresent { get; set; }
}
public class ItemInfo
{
[JsonProperty("ShortName")]
public string ShortName { get; set; }
[JsonProperty("Skin Id")]
public ulong SkinId { get; set; }
[JsonProperty("Minimum Amount")]
public int MinimumAmount { get; set; }
[JsonProperty("Maximum Amount")]
public int MaximumAmount { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
_config = Config.ReadObject<Configuration>();
if (string.Compare(_config.Version, Version.ToString()) < 0)
UpdateConfig();
SaveConfig();
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private void UpdateConfig()
{
PrintWarning("Config changes detected! Updating...");
Configuration defaultConfig = GetDefaultConfig();
if (string.Compare(_config.Version, "1.0.0") < 0)
_config = defaultConfig;
if (string.Compare(_config.Version, "1.1.0") < 0)
{
_config.Notification = defaultConfig.Notification;
foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities)
{
interiorEntityConfig.SkinIds = new List<ulong>();
}
}
if (string.Compare(_config.Version, "1.2.0") < 0)
{
_config.Door = defaultConfig.Door;
}
if (string.Compare(_config.Version, "1.3.0") < 0)
{
foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities)
{
interiorEntityConfig.SpawnChance = 50;
}
}
if (string.Compare(_config.Version, "1.4.0") < 0)
{
_config.EnableDebug = defaultConfig.EnableDebug;
}
if (string.Compare(_config.Version, "1.5.0") < 0)
{
_config.ShelterHealth = defaultConfig.ShelterHealth;
}
if (string.Compare(_config.Version, "1.6.0") < 0)
{
_config.Turret = defaultConfig.Turret;
}
if (string.Compare(_config.Version, "1.7.0") < 0)
{
_config.Trap = defaultConfig.Trap;
}
PrintWarning("Config update complete! Updated from version " + _config.Version + " to " + Version.ToString());
_config.Version = Version.ToString();
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Version = Version.ToString(),
EnableDebug = false,
NumberOfAttemptsToFindShelterPositionNearPlayers = 5,
MinimumSearchRadiusForShelterPositionAroundPlayer = 20f,
MaximumSearchRadiusForShelterPositionAroundPlayer = 50f,
NearbyEntitiesAvoidanceRadius = 6f,
RocksAvoidanceRadius = 5f,
DistanceFromNoBuildZones = 10f,
ShelterHealth = 500f,
ShelterLifetimeSeconds = 600f,
NumberOfAttemptsForDeterminingEntityPositionInsideShelter = 30,
NumberOfAttemptsForDeterminingEntityRotationInsideShelter = 30,
SheltersRespawnFrequencyMinutes = 60f,
DelayBetweenEachShelterSpawnSeconds = 5f,
Door = new DoorConfig
{
SkinIds = new List<ulong>
{
809253752,
2246937402,
2483070538,
3076134051
}
},
Turret = new TurretConfig
{
SpawnAutoTurret = false,
Health = 1000f,
WeaponShortName = "rifle.ak",
ClipAmmo = new ItemInfo
{
ShortName = "ammo.rifle",
MinimumAmount = 30,
MaximumAmount = 30
},
ReserveAmmo = new List<ItemInfo>
{
new ItemInfo
{
ShortName = "ammo.rifle",
MinimumAmount = 128,
MaximumAmount = 128
}
},
AttachmentShortNames = new List<string>
{
"weapon.mod.lasersight"
},
Peacekeeper = false,
},
Trap = new TrapConfig
{
SpawnLandmines = false,
SpawnBearTraps = true,
MinimumSpawnRadiusAroundShelter = 3f,
MaximumSpawnRadiusAroundShelter = 5f,
MinimumNumberOfTrapsToSpawn = 1,
MaximumNumberOfTrapsToSpawn = 5
},
Notification = new NotificationConfig
{
NotifySurroundingPlayersOfShelterSpawn = false,
RadiusForNotifyingNearbyPlayers = 40f,
SendAsToast = true
},
InteriorEntities = new List<InteriorEntityConfig>
{
new InteriorEntityConfig
{
PrefabName = "assets/prefabs/deployable/woodenbox/woodbox_deployed.prefab",
SkinIds = new List<ulong>
{
0
},
SpawnChance = 50,
MinimumNumberToSpawn = 1,
MaximumNumberToSpawn = 3,
PercentageToFillContainerWithItemsIfPresent = 20,
},
new InteriorEntityConfig
{
PrefabName = "assets/prefabs/deployable/furnace/furnace.prefab",
SkinIds = new List<ulong>
{
0
},
SpawnChance = 50,
MinimumNumberToSpawn = 1,
MaximumNumberToSpawn = 1,
PercentageToFillContainerWithItemsIfPresent = 0,
},
},
ItemsToSpawnInsideEntityContainers = new List<ItemInfo>()
{
new ItemInfo
{
ShortName = "fat.animal",
SkinId = 0,
MinimumAmount = 10,
MaximumAmount = 25,
},
new ItemInfo
{
ShortName = "cloth",
SkinId = 0,
MinimumAmount = 20,
MaximumAmount = 30,
},
new ItemInfo
{
ShortName = "wood",
SkinId = 0,
MinimumAmount = 200,
MaximumAmount = 400,
},
new ItemInfo
{
ShortName = "syringe.medical",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 2,
},
new ItemInfo
{
ShortName = "rope",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 3,
},
new ItemInfo
{
ShortName = "cctv.camera",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "roadsigns",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 2,
},
new ItemInfo
{
ShortName = "stones",
SkinId = 0,
MinimumAmount = 150,
MaximumAmount = 350,
},
new ItemInfo
{
ShortName = "metal.fragments",
SkinId = 0,
MinimumAmount = 30,
MaximumAmount = 90,
},
new ItemInfo
{
ShortName = "ammo.grenadelauncher.he",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 2,
},
new ItemInfo
{
ShortName = "coffeecan.helmet",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "scrap",
SkinId = 0,
MinimumAmount = 10,
MaximumAmount = 25,
},
new ItemInfo
{
ShortName = "icepick.salvaged",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "ptz.cctv.camera",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "corn",
SkinId = 0,
MinimumAmount = 3,
MaximumAmount = 5,
},
new ItemInfo
{
ShortName = "ammo.rocket.mlrs",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "wall.frame.garagedoor",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
new ItemInfo
{
ShortName = "pistol.revolver",
SkinId = 0,
MinimumAmount = 1,
MaximumAmount = 1,
},
}
};
}
#endregion Configuration
#region Stored Data
public class StoredData
{
[JsonProperty("Raidable Shelters")]
public Dictionary<ulong, ShelterData> Shelters { get; set; } = new Dictionary<ulong, ShelterData>();
}
public class ShelterData
{
[JsonProperty("Interior Entities")]
public List<ulong> InteriorEntities { get; set; } = new List<ulong>();
[JsonProperty("Traps")]
public List<ulong> Traps { get; set; } = new List<ulong>();
[JsonProperty("Removal Timer")]
public double RemovalTimer { get; set; }
}
#endregion Stored Data
#region Oxide Hooks
private void Init()
{
_plugin = this;
_storedData = DataFileUtil.LoadOrCreate<StoredData>(DataFileUtil.GetFilePath());
}
private void Unload()
{
if (_sheltersRespawnTimer != null)
_sheltersRespawnTimer.Destroy();
CoroutineUtil.StopAllCoroutines();
KillAllShelters();
_config = null;
_plugin = null;
}
private void OnServerInitialized(bool isStartup)
{
_sheltersRespawnTimer = timer.Every(_config.SheltersRespawnFrequencyMinutes * 60f, () =>
{
CoroutineUtil.StartCoroutine("RespawnSheltersCoroutine", RespawnSheltersCoroutine());
});
ResumeShelterRemovalTimers();
}
#endregion Oxide Hooks
#region True PVE Hooks
private object CanEntityTakeDamage(LegacyShelter shelter)
{
if (shelter == null || !API_IsShelterRaidable(shelter))
return null;
return true;
}
#endregion True PVE Hooks
#region Shelters Spawning and Setup
private IEnumerator RespawnSheltersCoroutine()
{
foreach (BasePlayer player in BasePlayer.activePlayerList)
{
if (player != null && !PlayerUtil.Wounded(player) && !PlayerUtil.Sleeping(player) && !PlayerUtil.InBase(player)
&& !PlayerUtil.Swimming(player) && !PlayerUtil.Boating(player) && !PlayerUtil.Flying(player) && PlayerUtil.OnGround(player)
&& !PlayerUtil.NearEnemyBase(player) && !TerrainUtil.InRadTown(player.transform.position))
{
Vector3 shelterPosition;
Quaternion shelterRotation;
if (TryFindSuitableShelterSpawnPoint(player.transform.position, _config.MinimumSearchRadiusForShelterPositionAroundPlayer, _config.MaximumSearchRadiusForShelterPositionAroundPlayer,
_config.NumberOfAttemptsToFindShelterPositionNearPlayers, out shelterPosition, out shelterRotation))
{
LegacyShelter shelter = SpawnLegacyShelter(shelterPosition, shelterRotation, player);
if (shelter != null)
{
NotifyOfShelterSpawn(shelter, player);
if (_config.EnableDebug)
DrawDebugInfo(shelterPosition, "Shelter spawn successful", ParseColor("#27AE60"), 4f);
}
}
}
else if (_config.EnableDebug)
{
string reason = "unknown reason";
if (PlayerUtil.Wounded(player))
reason = "player wounded";
else if (PlayerUtil.Sleeping(player))
reason = "player sleeping";
else if (PlayerUtil.InBase(player))
reason = "player in base";
else if (PlayerUtil.Swimming(player))
reason = "player swimming";
else if (PlayerUtil.Boating(player))
reason = "player boating";
else if (PlayerUtil.Flying(player))
reason = "player flying";
else if (!PlayerUtil.OnGround(player))
reason = "player not on ground";
else if (PlayerUtil.NearEnemyBase(player))
reason = "player near enemy base";
else if (TerrainUtil.InRadTown(player.transform.position))
reason = "player in radtown";
DrawDebugInfo(player.transform.position, $"Shelter spawn failed:\n{reason}", ParseColor("#E12126"));
}
yield return CoroutineEx.waitForSeconds(_config.DelayBetweenEachShelterSpawnSeconds);
}
}
private bool TryFindSuitableShelterSpawnPoint(Vector3 center, float minSearchRadius, float maxSearchRadius, int maxAttempts, out Vector3 suitablePosition, out Quaternion suitableRotation)
{
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Vector3 position = TerrainUtil.GetRandomPositionAround(center, minSearchRadius, maxSearchRadius);
if (TerrainUtil.InsideRock(position, _config.RocksAvoidanceRadius))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nInside rock", ParseColor("#E12126"), _config.RocksAvoidanceRadius);
continue;
}
if (TerrainUtil.InRadTown(position))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nIn radtown", ParseColor("#E12126"));
continue;
}
if (TerrainUtil.HasEntityNearby(position, _config.NearbyEntitiesAvoidanceRadius, LAYER_ENTITIES))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nNearby entities", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius);
continue;
}
if (PlayerUtil.HasPlayerNearby(position, _config.NearbyEntitiesAvoidanceRadius))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nNearby players", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius);
continue;
}
if (TerrainUtil.InWater(position))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nIn water", ParseColor("#E12126"));
continue;
}
if (TerrainUtil.OnRoadOrRail(position))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nOn road or rail", ParseColor("#E12126"));
continue;
}
if (!TerrainUtil.OnTerrain(position, 4f))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nNot on terrain", ParseColor("#E12126"), 4f);
continue;
}
if (TerrainUtil.InNoBuildZone(position, _config.DistanceFromNoBuildZones))
{
if (_config.EnableDebug)
DrawDebugInfo(position, "Spawn failed:\nIn no-build zone", ParseColor("#E12126"), _config.DistanceFromNoBuildZones);
continue;
}
RaycastHit groundHit;
if (TerrainUtil.GetGroundInfo(position, out groundHit, 5f, LAYER_GROUND))
{
suitablePosition = groundHit.point;
Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal);
Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
suitableRotation = surfaceRotation * randomYRotation;
return true;
}
}
suitablePosition = Vector3.zero;
suitableRotation = Quaternion.identity;
return false;
}
private LegacyShelter SpawnLegacyShelter(Vector3 position, Quaternion rotation, BasePlayer player)
{
LegacyShelter shelter = GameManager.server.CreateEntity(PREFAB_LEGACY_SHELTER, position, rotation) as LegacyShelter;
if (shelter == null)
return null;
shelter.OnPlaced(player);
shelter.Spawn();
shelter.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth);
shelter.SendNetworkUpdateImmediate();
// Set the lock owner id to 0 to prevent the player from opening the shelter door.
LegacyShelterDoor shelterDoor = shelter.GetChildDoor();
if (shelterDoor != null)
{
shelterDoor.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth);
BaseLock baseLock = shelterDoor.GetSlot(BaseEntity.Slot.Lock) as BaseLock;
if (baseLock != null)
baseLock.OwnerID = 0;
if (_config.Door.SkinIds != null && _config.Door.SkinIds.Count > 0)
{
shelterDoor.skinID = _config.Door.SkinIds[Random.Range(0, _config.Door.SkinIds.Count)];
}
}
EntityPrivilege entityPrivilege = shelter.GetEntityPrivilege();
if (entityPrivilege != null)
{
entityPrivilege.authorizedPlayers.Clear();
entityPrivilege.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
ShelterData shelterData = new ShelterData
{
RemovalTimer = Time.realtimeSinceStartup + _config.ShelterLifetimeSeconds
};
_storedData.Shelters[shelter.net.ID.Value] = shelterData;
if (!SpawnShelterInteriorEntities(shelter, shelterData))
{
_storedData.Shelters.Remove(shelter.net.ID.Value);
DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData);
shelter.Kill();
return null;
}
if (_config.Turret.SpawnAutoTurret)
DeployAutoTurret(shelter, shelterData);
if (_config.Trap.SpawnLandmines || _config.Trap.SpawnBearTraps)
SpawnTrapsAroundShelter(shelter, shelterData);
StartRemovalTimer(shelter, _config.ShelterLifetimeSeconds, shelterData);
return shelter;
}
#endregion Shelters Spawning and Setup
#region Shelter Spawn Notification
private void NotifyOfShelterSpawn(LegacyShelter shelter, BasePlayer player)
{
if (_config.Notification.NotifySurroundingPlayersOfShelterSpawn)
{
List<BasePlayer> nearbyPlayers = Pool.Get<List<BasePlayer>>();
Vis.Entities(shelter.transform.position, _config.Notification.RadiusForNotifyingNearbyPlayers, nearbyPlayers, LAYER_PLAYER, QueryTriggerInteraction.Ignore);
foreach (BasePlayer nearbyPlayer in nearbyPlayers)
{
if (nearbyPlayer == null)
continue;
if (_config.Notification.SendAsToast)
ShowToast(nearbyPlayer, Lang.RaidableShelterSpawned);
else
MessagePlayer(nearbyPlayer, Lang.RaidableShelterSpawned);
}
Pool.FreeUnmanaged(ref nearbyPlayers);
}
else
{
if (_config.Notification.SendAsToast)
ShowToast(player, Lang.RaidableShelterSpawned);
else
MessagePlayer(player, Lang.RaidableShelterSpawned);
}
}
#endregion Shelter Spawn Notification
#region Interior Entities Spawning
private bool SpawnShelterInteriorEntities(LegacyShelter shelter, ShelterData shelterData)
{
Vector3 shelterCenter = shelter.transform.position;
float spawnRadius = SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER;
bool anyEntitiesSpawned = false;
foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities)
{
int numberToSpawn = Random.Range(interiorEntityConfig.MinimumNumberToSpawn, interiorEntityConfig.MaximumNumberToSpawn + 1);
for (int i = 0; i < numberToSpawn; i++)
{
if (!ChanceSucceeded(interiorEntityConfig.SpawnChance))
continue;
Vector3 randomPosition;
int maxPositionAttempts = _config.NumberOfAttemptsForDeterminingEntityPositionInsideShelter;
int maxRotationAttempts = _config.NumberOfAttemptsForDeterminingEntityRotationInsideShelter;
for (int posAttempt = 0; posAttempt < maxPositionAttempts; posAttempt++)
{
randomPosition = TerrainUtil.GetRandomPositionAround(shelterCenter, minimumRadius: 0f, maximumRadius: spawnRadius);
RaycastHit groundHit;
if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 2f, LAYER_GROUND))
continue;
randomPosition = groundHit.point;
for (int rotAttempt = 0; rotAttempt < maxRotationAttempts; rotAttempt++)
{
Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal);
Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
Quaternion finalRotation = surfaceRotation * randomYRotation;
if (!EntityFitsInShelter(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation))
continue;
if (ExposedHook.OnShelterInteriorEntitySpawn(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation))
continue;
BaseEntity entity = SpawnInteriorEntity(shelter, randomPosition, finalRotation, interiorEntityConfig);
if (entity == null)
continue;
shelterData.InteriorEntities.Add(entity.net.ID.Value);
ExposedHook.OnShelterInteriorEntitySpawned(shelter, entity);
anyEntitiesSpawned = true;
posAttempt = maxPositionAttempts;
break;
}
}
}
}
return anyEntitiesSpawned;
}
private bool EntityFitsInShelter(LegacyShelter shelter, string prefabPath, Vector3 potentialPosition, Quaternion potentialRotation)
{
BaseEntity tempEntity = GameManager.server.CreateEntity(prefabPath, potentialPosition, potentialRotation, false);
if (tempEntity == null)
return false;
OBB bounds = tempEntity.WorldSpaceBounds();
tempEntity.Kill();
Vector3[] corners = new Vector3[8];
corners[0] = bounds.GetPoint(-1f, -1f, -1f);
corners[1] = bounds.GetPoint(-1f, -1f, 1f);
corners[2] = bounds.GetPoint(-1f, 1f, -1f);
corners[3] = bounds.GetPoint(-1f, 1f, 1f);
corners[4] = bounds.GetPoint(1f, -1f, -1f);
corners[5] = bounds.GetPoint(1f, -1f, 1f);
corners[6] = bounds.GetPoint(1f, 1f, -1f);
corners[7] = bounds.GetPoint(1f, 1f, 1f);
// Ensure the entity is within the shelter bounds and not clipping through or colliding with other objects inside.
Collider[] colliders = Physics.OverlapBox(bounds.position, bounds.extents, bounds.rotation, LAYER_ENTITIES);
foreach (Collider collider in colliders)
{
if (collider.gameObject != tempEntity.gameObject && collider.gameObject != shelter.gameObject)
return false;
}
return true;
}
private BaseEntity SpawnInteriorEntity(LegacyShelter shelter, Vector3 position, Quaternion rotation, InteriorEntityConfig interiorEntityConfig)
{
BaseEntity entity = GameManager.server.CreateEntity(interiorEntityConfig.PrefabName, position, rotation);
if (entity == null)
return null;
if (interiorEntityConfig.SkinIds != null && interiorEntityConfig.SkinIds.Count > 0)
{
entity.skinID = interiorEntityConfig.SkinIds[Random.Range(0, interiorEntityConfig.SkinIds.Count)];
}
entity.Spawn();
RemoveProblematicComponents(entity);
if (entity is StorageContainer storageContainer)
PopulateItems(storageContainer.inventory, _config.ItemsToSpawnInsideEntityContainers, interiorEntityConfig.PercentageToFillContainerWithItemsIfPresent);
return entity;
}
#endregion Interior Entities Spawning
#region Entity Containers Filling
private void PopulateItems(ItemContainer itemContainer, List<ItemInfo> items, int fillContainerPercentage)
{
Shuffle(items);
int slotsToFill = Mathf.CeilToInt(itemContainer.capacity * (fillContainerPercentage / 100f));
for (int i = 0; i < slotsToFill; i++)
{
if (i >= items.Count)
break;
ItemInfo itemInfo = items[i];
var itemDefinition = ItemManager.FindItemDefinition(itemInfo.ShortName);
if (itemDefinition != null)
{
int amountToAdd = Random.Range(itemInfo.MinimumAmount, itemInfo.MaximumAmount + 1);
Item item = ItemManager.Create(itemDefinition, amountToAdd, itemInfo.SkinId);
if (!item.MoveToContainer(itemContainer))
{
item.Remove();
}
}
}
}
#endregion Entity Container Filling
#region Turret Deployment and Setup
private void DeployAutoTurret(LegacyShelter shelter, ShelterData shelterData)
{
AutoTurret autoTurret = SpawnAutoTurret(shelter, _autoTurretPosition, Quaternion.Euler(_autoTurretRotation));
if (autoTurret != null)
{
AddWeaponToTurret(autoTurret);
LoadTurretWithReserveAmmo(autoTurret.inventory);
autoTurret.UpdateTotalAmmo();
autoTurret.EnsureReloaded();
autoTurret.SetPeacekeepermode(_config.Turret.Peacekeeper);
autoTurret.InitiateStartup();
autoTurret.SendNetworkUpdate();
shelterData.Traps.Add(autoTurret.net.ID.Value);
}
}
private AutoTurret SpawnAutoTurret(LegacyShelter shelter, Vector3 position, Quaternion rotation)
{
AutoTurret autoTurret = GameManager.server.CreateEntity(PREFAB_AUTO_TURRET, position, rotation) as AutoTurret;
if (autoTurret == null)
return null;
autoTurret.SetParent(shelter);
autoTurret.Spawn();
autoTurret.InitializeHealth(_config.Turret.Health, _config.Turret.Health);
autoTurret.SendNetworkUpdateImmediate();
RemoveProblematicComponents(autoTurret);
HideIOInputsAndOutputs(autoTurret);
return autoTurret;
}
private Item AddWeaponToTurret(AutoTurret autoTurret)
{
Item item = ItemManager.CreateByName(_config.Turret.WeaponShortName);
if (item == null)
return null;
if (_config.Turret.AttachmentShortNames != null)
{
foreach (string attachmentShortname in _config.Turret.AttachmentShortNames)
{
var attachmentItem = ItemManager.CreateByName(attachmentShortname);
if (attachmentItem != null)
{
if (!attachmentItem.MoveToContainer(item.contents))
{
attachmentItem.Remove();
}
}
}
}
if (!item.MoveToContainer(autoTurret.inventory, 0))
{
item.Remove();
return null;
}
BaseProjectile weapon = item.GetHeldEntity() as BaseProjectile;
if (weapon != null)
{
if (_config.Turret.AttachmentShortNames != null)
{
// Ensures the weapon's magazine capacity reflects the modifications applied, such as the extended magazine mod.
weapon.DelayedModsChanged();
weapon.CancelInvoke(weapon.DelayedModsChanged);
}
autoTurret.UpdateAttachedWeapon();
autoTurret.CancelInvoke(autoTurret.UpdateAttachedWeapon);
if (_config.Turret.ClipAmmo != null)
{
ItemDefinition loadedAmmoItemDefinition = ItemManager.FindItemDefinition(_config.Turret.ClipAmmo.ShortName);
if (loadedAmmoItemDefinition != null)
{
weapon.primaryMagazine.ammoType = loadedAmmoItemDefinition;
int clipAmmoAmount = UnityEngine.Random.Range(_config.Turret.ClipAmmo.MinimumAmount, _config.Turret.ClipAmmo.MaximumAmount + 1);
weapon.primaryMagazine.contents = Mathf.Min(weapon.primaryMagazine.capacity, clipAmmoAmount);
}
}
}
return item;
}
private void LoadTurretWithReserveAmmo(ItemContainer autoTurretContainer)
{
if (_config.Turret.ReserveAmmo == null)
return;
// Starting from slot 1, because slot 0 is reserved for the weapon.
int currentSlot = 1;
int maximumAvailableSlots = autoTurretContainer.capacity - 1;
foreach (ItemInfo ammo in _config.Turret.ReserveAmmo)
{
if (currentSlot > maximumAvailableSlots)
break;
if (ammo.MinimumAmount <= 0 && ammo.MaximumAmount <= 0)
continue;
ItemDefinition itemDefinition = ItemManager.FindItemDefinition(ammo.ShortName);
if (itemDefinition == null)
continue;
int reserveAmmoAmount = UnityEngine.Random.Range(ammo.MinimumAmount, ammo.MaximumAmount + 1);
int amountToAdd = Math.Min(reserveAmmoAmount, itemDefinition.stackable);
Item ammoItem = ItemManager.Create(itemDefinition, amountToAdd);
if (!ammoItem.MoveToContainer(autoTurretContainer, currentSlot))
{
ammoItem.Remove();
}
if (ammoItem.parent != autoTurretContainer)
{
Item destinationItem = autoTurretContainer.GetSlot(currentSlot);
if (destinationItem != null)
{
destinationItem.amount = amountToAdd;
destinationItem.MarkDirty();
}
ammoItem.Remove();
}
currentSlot++;
}
}
#endregion Turret Deployment and Setup
#region Traps Spawning
private void SpawnTrapsAroundShelter(LegacyShelter shelter, ShelterData shelterData)
{
Vector3 shelterPosition = shelter.transform.position;
int numberOfTraps = Random.Range(_config.Trap.MinimumNumberOfTrapsToSpawn, _config.Trap.MaximumNumberOfTrapsToSpawn + 1);
for (int i = 0; i < numberOfTraps; i++)
{
Vector3 randomPosition = TerrainUtil.GetRandomPositionAround(shelterPosition, _config.Trap.MinimumSpawnRadiusAroundShelter, _config.Trap.MaximumSpawnRadiusAroundShelter);
RaycastHit groundHit;
if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 5f, LAYER_GROUND))
continue;
randomPosition = groundHit.point;
Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal);
string trapPrefab = GetRandomTrapPrefab();
if (string.IsNullOrEmpty(trapPrefab))
continue;
BaseEntity trapEntity = GameManager.server.CreateEntity(trapPrefab, randomPosition, surfaceRotation);
if (trapEntity != null)
{
trapEntity.SetParent(shelter, true);
trapEntity.Spawn();
shelterData.Traps.Add(trapEntity.net.ID.Value);
RemoveProblematicComponents(trapEntity);
}
}
}
private string GetRandomTrapPrefab()
{
if (_config.Trap.SpawnLandmines && _config.Trap.SpawnBearTraps)
{
if (CoinFlip())
return PREFAB_LANDMINE;
else
return PREFAB_BEAR_TRAP;
}
else if (_config.Trap.SpawnLandmines)
{
return PREFAB_LANDMINE;
}
else if (_config.Trap.SpawnBearTraps)
{
return PREFAB_BEAR_TRAP;
}
return null;
}
#endregion Traps Spawning
#region Shelters Removal
private void ResumeShelterRemovalTimers()
{
foreach (var kvp in _storedData.Shelters)
{
ShelterData shelterData = kvp.Value;
LegacyShelter shelter = FindEntityById(kvp.Key) as LegacyShelter;
if (shelter != null)
{
double remainingTime = shelterData.RemovalTimer - Time.realtimeSinceStartup;
StartRemovalTimer(shelter, (float)remainingTime, shelterData);
}
}
}
private void StartRemovalTimer(LegacyShelter shelter, float lifetimeSeconds, ShelterData shelterData)
{
ulong shelterId = shelter != null && shelter.net != null ? shelter.net.ID.Value : 0;
if (lifetimeSeconds <= 0)
{
if (shelter != null)
shelter.Kill();
if (shelterData != null)
{
foreach (ulong entityId in shelterData.InteriorEntities)
{
BaseEntity entity = FindEntityById(entityId);
if (entity != null)
entity.Kill();
}
}
if (_storedData.Shelters.ContainsKey(shelterId))
{
_storedData.Shelters.Remove(shelterId);
DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData);
}
return;
}
if (shelter != null)
{
shelterData.RemovalTimer = Time.realtimeSinceStartup + lifetimeSeconds;
DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData);
timer.Once(lifetimeSeconds, () =>
{
if (shelter != null)
shelter.Kill();
if (shelterData != null)
{
foreach (ulong entityId in shelterData.InteriorEntities)
{
BaseEntity entity = FindEntityById(entityId);
if (entity != null)
entity.Kill();
}
}
if (_storedData.Shelters.ContainsKey(shelterId))
{
_storedData.Shelters.Remove(shelterId);
DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData);
}
});
}
}
private void KillAllShelters()
{
foreach (var kvp in _storedData.Shelters)
{
ShelterData shelterData = kvp.Value;
LegacyShelter shelter = BaseNetworkable.serverEntities.Find(new NetworkableId(kvp.Key)) as LegacyShelter;
if (shelter != null)
{
foreach (ulong entityId in shelterData.InteriorEntities)
{
BaseEntity entity = BaseNetworkable.serverEntities.Find(new NetworkableId(entityId)) as BaseEntity;
if (entity != null)
entity.Kill();
}
foreach (ulong trapId in shelterData.Traps)
{
BaseEntity trapEntity = FindEntityById(trapId);
if (trapEntity != null)
trapEntity.Kill();
}
shelter.Kill();
}
}
_storedData.Shelters.Clear();
DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData);
}
#endregion Shelters Removal
#region Debug
private void DrawDebugInfo(Vector3 position, string info, Color color, float radius = 0.5f)
{
foreach (BasePlayer player in BasePlayer.activePlayerList)
{
if (player == null || !player.IsAdmin)
continue;
DrawUtil.Text(player, 10f, color, position + Vector3.up * 1f, $"<size=30>{info}</size>");
DrawUtil.Sphere(player, 10f, color, position, radius);
}
}
#endregion Debug
#region Exposed Hooks
private static class ExposedHook
{
public static bool OnShelterInteriorEntitySpawn(LegacyShelter shelter, string prefabName, Vector3 position, Quaternion rotation)
{
object hookResult = Interface.CallHook("OnShelterInteriorEntitySpawn", shelter, prefabName, position, rotation);
return hookResult is bool && (bool)hookResult == false;
}
public static void OnShelterInteriorEntitySpawned(LegacyShelter shelter, BaseEntity entity)
{
Interface.CallHook("OnShelterInteriorEntitySpawned", shelter, entity);
}
}
#endregion Exposed Hooks
#region API
private bool API_IsShelterRaidable(LegacyShelter shelter)
{
return _storedData.Shelters.ContainsKey(shelter.net.ID.Value);
}
#endregion API
#region Helper Functions
private static bool CoinFlip()
{
return Random.Range(0, 2) == 0;
}
private BaseEntity FindEntityById(ulong id)
{
return BaseNetworkable.serverEntities.Find(new NetworkableId(id)) as BaseEntity;
}
private static void HideIOInputsAndOutputs(IOEntity ioEntity)
{
foreach (var input in ioEntity.inputs)
input.type = IOEntity.IOType.Generic;
foreach (var output in ioEntity.outputs)
output.type = IOEntity.IOType.Generic;
}
private static BaseEntity FindBaseEntityForPrefab(string prefabName)
{
var prefab = GameManager.server.FindPrefab(prefabName);
if (prefab == null)
return null;
return prefab.GetComponent<BaseEntity>();
}
private static void Shuffle<T>(List<T> list)
{
int remainingItems = list.Count;
while (remainingItems > 1)
{
remainingItems--;
int randomIndex = _plugin._randomGenerator.Next(remainingItems + 1);
T itemToSwap = list[randomIndex];
list[randomIndex] = list[remainingItems];
list[remainingItems] = itemToSwap;
}
}
private static void RemoveProblematicComponents(BaseEntity entity)
{
UnityEngine.Object.DestroyImmediate(entity.GetComponent<DestroyOnGroundMissing>());
UnityEngine.Object.DestroyImmediate(entity.GetComponent<GroundWatch>());
}
private static bool ChanceSucceeded(int percentage)
{
return Random.Range(0, 100) < percentage;
}
private static Color ParseColor(string hexColor)
{
if (ColorUtility.TryParseHtmlString(hexColor, out Color color))
return color;
return Color.white;
}
#endregion Helper Functions
#region Helper Classes
public static class TerrainUtil
{
public static bool OnTopology(Vector3 position, TerrainTopology.Enum topology)
{
return (TerrainMeta.TopologyMap.GetTopology(position) & (int)topology) != 0;
}
public static bool OnRoadOrRail(Vector3 position)
{
var combinedTopology = TerrainTopology.Enum.Road | TerrainTopology.Enum.Roadside |
TerrainTopology.Enum.Rail | TerrainTopology.Enum.Railside;
return OnTopology(position, combinedTopology);
}
public static bool OnTerrain(Vector3 position, float radius)
{
return Physics.CheckSphere(position, radius, Layers.Mask.Terrain, QueryTriggerInteraction.Ignore);
}
public static bool InNoBuildZone(Vector3 position, float radius)
{
return Physics.CheckSphere(position, radius, Layers.Mask.Prevent_Building);
}
public static bool InWater(Vector3 position)
{
return WaterLevel.Test(position, false, false);
}
public static bool InsideRock(Vector3 position, float radius)
{
List<Collider> colliders = Pool.Get<List<Collider>>();
Vis.Colliders(position, radius, colliders, Layers.Mask.World, QueryTriggerInteraction.Ignore);
bool result = false;
foreach (Collider collider in colliders)
{
if (collider.name.Contains("rock", CompareOptions.OrdinalIgnoreCase)
|| collider.name.Contains("cliff", CompareOptions.OrdinalIgnoreCase)
|| collider.name.Contains("formation", CompareOptions.OrdinalIgnoreCase))
{
result = true;
break;
}
}
Pool.FreeUnmanaged(ref colliders);
return result;
}
public static bool InRadTown(Vector3 position, bool shouldDisplayOnMap = false)
{
foreach (var monumentInfo in TerrainMeta.Path.Monuments)
{
bool inBounds = monumentInfo.IsInBounds(position);
bool hasLandMarker = true;
if (shouldDisplayOnMap)
hasLandMarker = monumentInfo.shouldDisplayOnMap;
if (inBounds && hasLandMarker)
return true;
}
return OnTopology(position, TerrainTopology.Enum.Monument);
}
public static bool HasEntityNearby(Vector3 position, float radius, LayerMask mask, string prefabName = null)
{
List<Collider> hitColliders = Pool.Get<List<Collider>>();
GamePhysics.OverlapSphere(position, radius, hitColliders, mask, QueryTriggerInteraction.Ignore);
bool hasEntityNearby = false;
foreach (Collider collider in hitColliders)
{
BaseEntity entity = collider.gameObject.ToBaseEntity();
if (entity != null)
{
if (prefabName == null || entity.PrefabName == prefabName)
{
hasEntityNearby = true;
break;
}
}
}
Pool.FreeUnmanaged(ref hitColliders);
return hasEntityNearby;
}
public static Vector3 GetRandomPositionAround(Vector3 center, float minimumRadius, float maximumRadius, bool adjustToWaterHeight = false)
{
Vector3 randomDirection = Random.onUnitSphere;
float randomDistance = Random.Range(minimumRadius, maximumRadius);
Vector3 randomPosition = center + randomDirection * randomDistance;
if (adjustToWaterHeight)
randomPosition.y = TerrainMeta.WaterMap.GetHeight(randomPosition);
else
randomPosition.y = TerrainMeta.HeightMap.GetHeight(randomPosition);
return randomPosition;
}
public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask)
{
return Physics.Linecast(startPosition + new Vector3(0.0f, range, 0.0f), startPosition - new Vector3(0.0f, range, 0.0f), out raycastHit, mask);
}
public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask, Transform ignoreTransform = null)
{
startPosition.y += 0.25f;
range += 0.25f;
raycastHit = default;
RaycastHit hit;
if (!GamePhysics.Trace(new Ray(startPosition, Vector3.down), 0f, out hit, range, mask, QueryTriggerInteraction.UseGlobal, null))
return false;
if (ignoreTransform != null && hit.collider != null
&& (hit.collider.transform == ignoreTransform || hit.collider.transform.IsChildOf(ignoreTransform)))
{
return GetGroundInfo(startPosition - new Vector3(0f, 0.01f, 0f), out raycastHit, range, mask, ignoreTransform);
}
raycastHit = hit;
return true;
}
}
private static class PlayerUtil
{
public static BasePlayer FindById(ulong playerId)
{
return RelationshipManager.FindByID(playerId);
}
public static bool HasPlayerNearby(Vector3 position, float radius)
{
return BaseNetworkable.HasCloseConnections(position, radius);
}
public static bool AreTeammates(ulong firstPlayerId, ulong secondPlayerId)
{
RelationshipManager.PlayerTeam team = RelationshipManager.ServerInstance.FindPlayersTeam(firstPlayerId);
if (team != null && team.members.Contains(secondPlayerId))
return true;
return false;
}
public static bool Sleeping(BasePlayer player)
{
return player != null && player.IsSleeping();
}
public static bool Swimming(BasePlayer player)
{
return player != null && player.IsSwimming();
}
public static bool Boating(BasePlayer player)
{
return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Boating;
}
public static bool Flying(BasePlayer player)
{
return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Flying;
}
public static bool Driving(BasePlayer player)
{
return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Driving;
}
public static bool InBase(BasePlayer player)
{
return player != null && player.IsBuildingAuthed();
}
public static bool NearEnemyBase(BasePlayer player)
{
return player != null && player.IsNearEnemyBase();
}
public static bool Wounded(BasePlayer player)
{
return player != null && player.IsWounded();
}
public static bool Crawling(BasePlayer player)
{
return player != null && player.IsCrawling();
}
public static bool OnGround(BasePlayer player)
{
return player != null && player.IsOnGround();
}
}
public static class CoroutineUtil
{
private static readonly Dictionary<string, Coroutine> _activeCoroutines = new Dictionary<string, Coroutine>();
public static void StartCoroutine(string coroutineName, IEnumerator coroutineFunction)
{
StopCoroutine(coroutineName);
Coroutine coroutine = ServerMgr.Instance.StartCoroutine(coroutineFunction);
_activeCoroutines[coroutineName] = coroutine;
}
public static void StopCoroutine(string coroutineName)
{
if (_activeCoroutines.TryGetValue(coroutineName, out Coroutine coroutine))
{
if (coroutine != null)
ServerMgr.Instance.StopCoroutine(coroutine);
_activeCoroutines.Remove(coroutineName);
}
}
public static void StopAllCoroutines()
{
foreach (string coroutineName in _activeCoroutines.Keys.ToArray())
{
StopCoroutine(coroutineName);
}
}
}
public static class DrawUtil
{
public static void Box(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius)
{
player.SendConsoleCommand("ddraw.box", durationSeconds, color, position, radius);
}
public static void Sphere(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius)
{
player.SendConsoleCommand("ddraw.sphere", durationSeconds, color, position, radius);
}
public static void Line(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition)
{
player.SendConsoleCommand("ddraw.line", durationSeconds, color, fromPosition, toPosition);
}
public static void Arrow(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition, float headSize)
{
player.SendConsoleCommand("ddraw.arrow", durationSeconds, color, fromPosition, toPosition, headSize);
}
public static void Text(BasePlayer player, float durationSeconds, Color color, Vector3 position, string text)
{
player.SendConsoleCommand("ddraw.text", durationSeconds, color, position, text);
}
}
public class DataFileUtil
{
private const string FOLDER = "";
public static string GetFilePath(string filename = null)
{
if (filename == null)
filename = _plugin.Name;
return Path.Combine(FOLDER, filename);
}
public static string[] GetAllFilePaths()
{
string[] filePaths = Interface.Oxide.DataFileSystem.GetFiles(FOLDER);
for (int i = 0; i < filePaths.Length; i++)
{
// Remove the redundant '.json' from the filepath. This is necessary because the filepaths are returned with a double '.json'.
filePaths[i] = filePaths[i].Substring(0, filePaths[i].Length - 5);
}
return filePaths;
}
public static bool Exists(string filePath)
{
return Interface.Oxide.DataFileSystem.ExistsDatafile(filePath);
}
public static T Load<T>(string filePath) where T : class, new()
{
T data = Interface.Oxide.DataFileSystem.ReadObject<T>(filePath);
if (data == null)
data = new T();
return data;
}
public static T LoadIfExists<T>(string filePath) where T : class, new()
{
if (Exists(filePath))
return Load<T>(filePath);
else
return null;
}
public static T LoadOrCreate<T>(string filePath) where T : class, new()
{
T data = LoadIfExists<T>(filePath);
if (data == null)
data = new T();
return data;
}
public static void Save<T>(string filePath, T data)
{
Interface.Oxide.DataFileSystem.WriteObject<T>(filePath, data);
}
public static void Delete(string filePath)
{
Interface.Oxide.DataFileSystem.DeleteDataFile(filePath);
}
}
#endregion Helper Classes
#region Commands
private static class Cmd
{
public const string TEST = "rs.test";
}
[ChatCommand(Cmd.TEST)]
private void cmdTest(BasePlayer player, string cmd, string[] args)
{
if (player == null || !player.IsAdmin)
return;
RaycastHit groundHit;
if (TerrainUtil.GetGroundInfo(player.transform.position, out groundHit, 10f, LAYER_GROUND))
{
Vector3 spawnPosition = groundHit.point;
Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal);
Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
Quaternion spawnRotation = surfaceRotation * randomYRotation;
LegacyShelter shelter = SpawnLegacyShelter(spawnPosition, spawnRotation, player);
if (shelter != null)
{
MessagePlayer(player, Lang.TestShelterSpawned);
}
}
}
#endregion Commands
#region Localization
private class Lang
{
public const string RaidableShelterSpawned = "RaidableShelterSpawned";
public const string TestShelterSpawned = "TestShelterSpawned";
}
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
[Lang.RaidableShelterSpawned] = "A raidable shelter has spawned nearby!",
[Lang.TestShelterSpawned] = "A test shelter has been spawned at your location."
}, this, "en");
}
private static string GetMessage(BasePlayer player, string messageKey, params object[] args)
{
string message = _plugin.lang.GetMessage(messageKey, _plugin, player.UserIDString);
if (args.Length > 0)
message = string.Format(message, args);
return message;
}
public static void MessagePlayer(BasePlayer player, string messageKey, params object[] args)
{
string message = GetMessage(player, messageKey, args);
_plugin.SendReply(player, message);
}
public static void ShowToast(BasePlayer player, string messageKey, GameTip.Styles style = GameTip.Styles.Blue_Normal, params object[] args)
{
string message = GetMessage(player, messageKey, args);
player.SendConsoleCommand("gametip.showtoast", (int)style, message);
}
#endregion Localization
}
}
To make the "Dungeons" plugin handle Auto Turrets with the same capabilities as the "Raidable Shelters" plugin, you need to modify how the Auto Turrets are created and configured. Specifically, you should add functionality to automatically equip a weapon, load ammo, and configure settings like Peacekeeper mode. Here's how you can integrate these features into the "Dungeons" plugin:
Add Configuration for Turrets: Ensure your "Dungeons" plugin has a configuration setup for turret weapons, ammo, and any attachments, similar to what’s in the "Raidable Shelters".
Modify IntegrateEntitiesIntoDungeon Method: Update the turret setup when they are spawned in a dungeon cell.
Implement Turret Setup Functions: Add functions to assign weapons, load ammo, and configure turret settings.
Here's a simplified version of how you can modify the "Dungeons" plugin to emulate the turret behavior from "Raidable Shelters":
csharp
private void IntegrateEntitiesIntoDungeon(XmasDungeon dungeon)
{
var proceduralDungeon = dungeon.dungeonInstance.Get(serverside: true);
if (proceduralDungeon == null)
{
Puts("Failed to get procedural dungeon instance.");
return;
}
int cellCount = proceduralDungeon.spawnedCells.Count;
if (cellCount == 0)
{
Puts("No cells found in dungeon for entities.");
return;
}
// Create a single list of all entities to be spawned
var allSpawnEntries = new List<SpawnGroup.SpawnEntry>();
// Add NPCs
foreach (var config in _config.NpcSpawnConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = true,
}
);
}
}
}
// Add Auto Turrets
foreach (var config in _config.AutoTurretConfigs)
{
if (GameManifest.pathToGuid.TryGetValue(config.PrefabName, out var guid))
{
for (int i = 0; i < config.EntitysPerCell; i++)
{
allSpawnEntries.Add(
new SpawnGroup.SpawnEntry
{
prefab = new GameObjectRef { guid = guid },
weight = 1,
mobile = false,
onSpawn = entity =>
{
SetupTurret(entity as AutoTurret);
}
}
);
}
}
}
// Repeat for Landmines, Bear Traps, etc.
// Integrate all entities into each cell
foreach (var cell in proceduralDungeon.spawnedCells)
{
SetupSpawnGroup(cell, allSpawnEntries);
}
}
private void SetupTurret(AutoTurret turret)
{
if (turret == null)
{
Puts("Failed to create turret.");
return;
}
AddWeaponToTurret(turret);
LoadTurretWithReserveAmmo(turret.inventory);
turret.UpdateTotalAmmo();
turret.EnsureReloaded();
turret.SetPeacekeepermode(_config.Turret.Peacekeeper);
turret.InitiateStartup();
turret.SendNetworkUpdate();
}
private Item AddWeaponToTurret(AutoTurret turret)
{
Item item = ItemManager.CreateByName(_config.Turret.WeaponShortName);
if (item == null)
return null;
if (_config.Turret.AttachmentShortNames != null)
{
foreach (string attachmentShortname in _config.Turret.AttachmentShortNames)
{
var attachmentItem = ItemManager.CreateByName(attachmentShortname);
if (attachmentItem != null)
{
if (!attachmentItem.MoveToContainer(item.contents))
{
attachmentItem.Remove();
}
}
}
}
if (!item.MoveToContainer(turret.inventory, 0))
{
item.Remove();
return null;
}
if (item.GetHeldEntity() is BaseProjectile weapon)
{
weapon.delayedModsChanged();
turret.UpdateAttachedWeapon();
if (_config.Turret.ClipAmmo != null)
{
var loadedAmmoItemDefinition = ItemManager.FindItemDefinition(_config.Turret.ClipAmmo.ShortName);
if (loadedAmmoItemDefinition != null)
{
weapon.primaryMagazine.ammoType = loadedAmmoItemDefinition;
int clipAmmoAmount = Random.Range(_config.Turret.ClipAmmo.MinimumAmount, _config.Turret.ClipAmmo.MaximumAmount + 1);
weapon.primaryMagazine.contents = Mathf.Min(weapon.primaryMagazine.capacity, clipAmmoAmount);
}
}
}
return item;
}
private void LoadTurretWithReserveAmmo(ItemContainer turretContainer)
{
if (_config.Turret.ReserveAmmo != null)
{
int currentSlot = 1;
foreach (ItemInfo ammoInfo in _config.Turret.ReserveAmmo)
{
if (currentSlot >= turretContainer.capacity)
break;
var ammoDef = ItemManager.FindItemDefinition(ammoInfo.ShortName);
if (ammoDef == null) continue;
int amount = Random.Range(ammoInfo.MinimumAmount, ammoInfo.MaximumAmount + 1);
var ammoItem = ItemManager.Create(ammoDef, amount);
if (!ammoItem.MoveToContainer(turretContainer, currentSlot))
ammoItem.Remove();
currentSlot++;
}
}
}
Key Points:
IntegrateEntitiesIntoDungeon: Now includes logic to configure turrets accordingly by calling SetupTurret.
SetupTurret: Configures the turret with a weapon and ammo based on configuration.
AddWeaponToTurret and LoadTurretWithReserveAmmo: These methods are used to equip the turret with the appropriate weapon, attachments, and ammo.
Notes:
Configuration Needed: Ensure your PluginConfig class has fields for the turret weapon and ammo configurations, similar to the "Raidable Shelters" plugin.
Testing: Thoroughly test these changes in a controlled environment to ensure the turrets behave as expected.
This will give your "Dungeons" plugin the ability to spawn and equip turrets similarly to the "Raidable Shelters" plugin.
deu erro, vou te passar infos:
using System;
using System.Collections.Generic;
using System.Linq;
using ConVar;
using UnityEngine;
public class SpawnGroup : BaseMonoBehaviour, IServerComponent, ISpawnPointUser, ISpawnGroup
{
[Serializable]
public class SpawnEntry
{
public GameObjectRef prefab;
code
public int weight = 1;
public bool mobile;
}
[InspectorFlags]
public MonumentTier Tier = (MonumentTier)(-1);
public List<SpawnEntry> prefabs;
public int maxPopulation = 5;
public int numToSpawnPerTickMin = 1;
public int numToSpawnPerTickMax = 2;
public float respawnDelayMin = 10f;
public float respawnDelayMax = 20f;
public bool wantsInitialSpawn = true;
public bool temporary;
public bool forceInitialSpawn;
public bool preventDuplicates;
public bool isSpawnerActive = true;
public BoxCollider setFreeIfMovedBeyond;
public string category;
[NonSerialized]
public MonumentInfo Monument;
public bool fillOnSpawn;
public BaseSpawnPoint[] spawnPoints;
public List<SpawnPointInstance> spawnInstances = new List<SpawnPointInstance>();
public LocalClock spawnClock = new LocalClock();
public int currentPopulation => spawnInstances.Count;
public virtual bool WantsInitialSpawn()
{
return wantsInitialSpawn;
}
public virtual bool WantsTimedSpawn()
{
return respawnDelayMax != float.PositiveInfinity;
}
public float GetSpawnDelta()
{
return (respawnDelayMax + respawnDelayMin) * 0.5f / SpawnHandler.PlayerScale(ConVar.Spawn.player_scale);
}
public float GetSpawnVariance()
{
return (respawnDelayMax - respawnDelayMin) * 0.5f / SpawnHandler.PlayerScale(ConVar.Spawn.player_scale);
}
protected void Awake()
{
if (TerrainMeta.TopologyMap == null)
{
return;
}
int topology = TerrainMeta.TopologyMap.GetTopology(base.transform.position);
int num = 469762048;
int num2 = MonumentInfo.TierToMask(Tier);
if (num2 == num || (num2 & topology) != 0)
{
spawnPoints = GetComponentsInChildren<BaseSpawnPoint>();
if (WantsTimedSpawn())
{
spawnClock.Add(GetSpawnDelta(), GetSpawnVariance(), Spawn);
}
if (!temporary && (bool)SingletonComponent<SpawnHandler>.Instance)
{
SingletonComponent<SpawnHandler>.Instance.SpawnGroups.Add(this);
}
if (forceInitialSpawn)
{
Invoke(SpawnInitial, 1f);
}
Monument = FindMonument();
}
}
protected void OnDestroy()
{
if ((bool)SingletonComponent<SpawnHandler>.Instance)
{
SingletonComponent<SpawnHandler>.Instance.SpawnGroups.Remove(this);
}
else
{
Debug.LogWarning(GetType().Name + ": SpawnHandler instance not found.");
}
}
public void Fill()
{
if (isSpawnerActive)
{
Spawn(maxPopulation);
}
}
public void Clear()
{
for (int num = spawnInstances.Count - 1; num >= 0; num--)
{
SpawnPointInstance spawnPointInstance = spawnInstances[num];
BaseEntity baseEntity = GameObjectEx.ToBaseEntity(spawnPointInstance.gameObject);
if (setFreeIfMovedBeyond != null && !setFreeIfMovedBeyond.bounds.Contains(baseEntity.transform.position))
{
spawnPointInstance.Retire();
}
else if ((bool)baseEntity)
{
baseEntity.Kill();
}
}
spawnInstances.Clear();
}
public bool HasSpawned(uint prefabID)
{
foreach (SpawnPointInstance spawnInstance in spawnInstances)
{
BaseEntity baseEntity = GameObjectEx.ToBaseEntity(spawnInstance.gameObject);
if ((bool)baseEntity && baseEntity.prefabID == prefabID)
{
return true;
}
}
return false;
}
public virtual void SpawnInitial()
{
if (wantsInitialSpawn && isSpawnerActive)
{
if (fillOnSpawn)
{
Spawn(maxPopulation);
}
else
{
Spawn();
}
}
}
public void SpawnRepeating()
{
for (int i = 0; i < spawnClock.events.Count; i++)
{
LocalClock.TimedEvent value = spawnClock.events[i];
if (UnityEngine.Time.time > value.time)
{
value.delta = GetSpawnDelta();
value.variance = GetSpawnVariance();
spawnClock.events[i] = value;
}
}
spawnClock.Tick();
}
public void ObjectSpawned(SpawnPointInstance instance)
{
spawnInstances.Add(instance);
}
public void ObjectRetired(SpawnPointInstance instance)
{
spawnInstances.Remove(instance);
}
public void DelayedSpawn()
{
Invoke(Spawn, 1f);
}
public void Spawn()
{
if (isSpawnerActive)
{
Spawn(UnityEngine.Random.Range(numToSpawnPerTickMin, numToSpawnPerTickMax + 1));
}
}
protected virtual void Spawn(int numToSpawn)
{
numToSpawn = Mathf.Min(numToSpawn, maxPopulation - currentPopulation);
for (int i = 0; i < numToSpawn; i++)
{
GameObjectRef prefab = GetPrefab();
if (prefab == null || string.IsNullOrEmpty(prefab.guid))
{
continue;
}
Vector3 pos;
Quaternion rot;
BaseSpawnPoint spawnPoint = GetSpawnPoint(prefab, out pos, out rot);
if (!spawnPoint)
{
continue;
}
BaseEntity baseEntity = GameManager.server.CreateEntity(prefab.resourcePath, pos, rot, startActive: false);
if ((bool)baseEntity)
{
if (baseEntity.enableSaving && !(spawnPoint is SpaceCheckingSpawnPoint))
{
baseEntity.enableSaving = false;
}
PoolableEx.AwakeFromInstantiate(baseEntity.gameObject);
baseEntity.Spawn();
PostSpawnProcess(baseEntity, spawnPoint);
SpawnPointInstance spawnPointInstance = baseEntity.gameObject.AddComponent<SpawnPointInstance>();
spawnPointInstance.parentSpawnPointUser = this;
spawnPointInstance.parentSpawnPoint = spawnPoint;
spawnPointInstance.Notify();
}
}
}
protected virtual void PostSpawnProcess(BaseEntity entity, BaseSpawnPoint spawnPoint)
{
}
protected GameObjectRef GetPrefab()
{
float num = prefabs.Sum((SpawnEntry x) => (!preventDuplicates || !HasSpawned(x.prefab.resourceID)) ? x.weight : 0);
if (num == 0f)
{
return null;
}
float num2 = UnityEngine.Random.Range(0f, num);
foreach (SpawnEntry prefab in prefabs)
{
int num3 = ((!preventDuplicates || !HasSpawned(prefab.prefab.resourceID)) ? prefab.weight : 0);
if ((num2 -= (float)num3) <= 0f)
{
return prefab.prefab;
}
}
return prefabs[prefabs.Count - 1].prefab;
}
protected virtual BaseSpawnPoint GetSpawnPoint(GameObjectRef prefabRef, out Vector3 pos, out Quaternion rot)
{
BaseSpawnPoint baseSpawnPoint = null;
pos = Vector3.zero;
rot = Quaternion.identity;
int num = UnityEngine.Random.Range(0, spawnPoints.Length);
for (int i = 0; i < spawnPoints.Length; i++)
{
BaseSpawnPoint baseSpawnPoint2 = spawnPoints[(num + i) % spawnPoints.Length];
if (!(baseSpawnPoint2 == null) && baseSpawnPoint2.IsAvailableTo(prefabRef.Get()) && !baseSpawnPoint2.HasPlayersIntersecting())
{
baseSpawnPoint = baseSpawnPoint2;
break;
}
}
if ((bool)baseSpawnPoint)
{
baseSpawnPoint.GetLocation(out pos, out rot);
}
return baseSpawnPoint;
}
private MonumentInfo FindMonument()
{
return GetComponentInParent<MonumentInfo>();
}
protected virtual void OnDrawGizmos()
{
Gizmos.color = new Color(1f, 1f, 0f, 1f);
Gizmos.DrawSphere(base.transform.position, 0.25f);
}
}
To integrate the turret functionality from the existing "Raidable Shelters" plugin into the "Dungeons" plugin using the SpawnGroup class, the key is understanding how to work with SpawnEntry and implementing a mechanism to execute additional logic when a turret spawns. The PostSpawnProcess method in SpawnGroup is a hook where you can inject the additional setup logic.
Here's a modified approach to implement this feature:
Add Turret Configuration: Make sure your configuration covers all necessary settings for the turrets, including weapon type, ammo amount, and Peacekeeper mode.
Implement Turret Setup: You'll need to set up the turret after it has spawned.
Modify the PostSpawnProcess: This is where you configure any special behavior for turrets.
csharp
protected override void PostSpawnProcess(BaseEntity entity, BaseSpawnPoint spawnPoint)
{
base.PostSpawnProcess(entity, spawnPoint);
if (entity is AutoTurret turret)
{
SetupTurret(turret);
}
}
private void SetupTurret(AutoTurret turret)
{
if (turret == null)
{
Puts("Failed to create turret.");
return;
}
AddWeaponToTurret(turret);
LoadTurretWithReserveAmmo(turret.inventory);
turret.UpdateTotalAmmo();
turret.EnsureReloaded();
turret.SetPeacekeepermode(_config.Turret.Peacekeeper);
turret.InitiateStartup();
turret.SendNetworkUpdateImmediate(); // Immediate update to ensure configuration is applied quickly
}
private Item AddWeaponToTurret(AutoTurret turret)
{
Item item = ItemManager.CreateByName(_config.Turret.WeaponShortName);
if (item == null)
return null;
// Adding attachments, if any, to the turret weapon
if (_config.Turret.AttachmentShortNames != null)
{
foreach (string attachmentShortname in _config.Turret.AttachmentShortNames)
{
var attachmentItem = ItemManager.CreateByName(attachmentShortname);
if (attachmentItem != null && !attachmentItem.MoveToContainer(item.contents))
{
attachmentItem.Remove();
}
}
}
// Move weapon to turret's container
if (!item.MoveToContainer(turret.inventory, 0))
{
item.Remove();
return null;
}
if (item.GetHeldEntity() is BaseProjectile weapon)
{
if (_config.Turret.ClipAmmo != null)
{
var loadedAmmoItemDefinition = ItemManager.FindItemDefinition(_config.Turret.ClipAmmo.ShortName);
if (loadedAmmoItemDefinition != null)
{
weapon.primaryMagazine.ammoType = loadedAmmoItemDefinition;
int clipAmmoAmount = Random.Range(_config.Turret.ClipAmmo.MinimumAmount, _config.Turret.ClipAmmo.MaximumAmount + 1);
weapon.primaryMagazine.contents = Mathf.Min(weapon.primaryMagazine.capacity, clipAmmoAmount);
}
}
}
return item;
}
private void LoadTurretWithReserveAmmo(ItemContainer turretContainer)
{
if (_config.Turret.ReserveAmmo != null)
{
int currentSlot = 1;
foreach (ItemInfo ammoInfo in _config.Turret.ReserveAmmo)
{
if (currentSlot >= turretContainer.capacity)
break;
var ammoDef = ItemManager.FindItemDefinition(ammoInfo.ShortName);
if (ammoDef == null) continue;
int amount = Random.Range(ammoInfo.MinimumAmount, ammoInfo.MaximumAmount + 1);
var ammoItem = ItemManager.Create(ammoDef, amount);
if (!ammoItem.MoveToContainer(turretContainer, currentSlot))
ammoItem.Remove();
currentSlot++;
}
}
}
Key Points
PostSpawnProcess: This is used to hook into the spawn process of each entity, allowing additional configurations right after a turret is spawned.
Turret Setup: Prepare the turret weapon, load it with ammo, and configure any mode settings (e.g., Peacekeeper mode) immediately after spawning.
Handling Immediate Updates: To ensure that all changes take effect without delay, especially useful in dynamic environments like Rust.
Error Checking: Make sure you have error handling and logging to troubleshoot any potential issues, such as failing to find a prefab or item definition.
This setup ensures that any turrets spawned by SpawnGroup in your dungeon will have weapons loaded and configured with the desired settings. You need to properly define _config.Turret in your configuration similar to its presence in the "Raidable Shelters" plugin.
The error you're encountering is due to the absence of a protected override void PostSpawnProcess method in the SpawnGroup class itself, as evident from the source code you provided. This method doesn't exist, so you can't override it. Instead, you'll need to directly implement the turret customization logic within the Spawn method of the SpawnGroup, or consider adding a customization point yourself.
Here's a step-by-step guide on a possible implementation. We will define our logic by creating an optional event/action that will be invoked during the Spawn method call when entities are instantiated:
Step 1: Define a Custom Action or Delegate
First, you'll need to define a custom action within the SpawnGroup class that you can use to execute logic on spawned entities, specifically Auto Turrets:
csharp
public Action<BaseEntity> OnEntitySpawned;
Step 2: Modify the Spawn Method
You need to update the Spawn method in the SpawnGroup class to invoke the custom action when an entity is spawned:
csharp
protected virtual void Spawn(int numToSpawn)
{
numToSpawn = Mathf.Min(numToSpawn, maxPopulation - currentPopulation);
for (int i = 0; i < numToSpawn; i++)
{
GameObjectRef prefab = GetPrefab();
if (prefab == null || string.IsNullOrEmpty(prefab.guid))
{
continue;
}
Vector3 pos;
Quaternion rot;
BaseSpawnPoint spawnPoint = GetSpawnPoint(prefab, out pos, out rot);
if (!spawnPoint)
{
continue;
}
BaseEntity baseEntity = GameManager.server.CreateEntity(prefab.resourcePath, pos, rot, startActive: false);
if (baseEntity != null)
{
if (baseEntity.enableSaving && !(spawnPoint is SpaceCheckingSpawnPoint))
{
baseEntity.enableSaving = false;
}
PoolableEx.AwakeFromInstantiate(baseEntity.gameObject);
baseEntity.Spawn();
// Invoke custom logic on the entity if action is set
OnEntitySpawned?.Invoke(baseEntity);
PostSpawnProcess(baseEntity, spawnPoint); // If you have other post-spawn logic, you can still implement it here
SpawnPointInstance spawnPointInstance = baseEntity.gameObject.AddComponent<SpawnPointInstance>();
spawnPointInstance.parentSpawnPointUser = this;
spawnPointInstance.parentSpawnPoint = spawnPoint;
spawnPointInstance.Notify();
}
}
}
// Make this an optional virtual/post-process method to keep customizable/overridable logic if needed
protected virtual void PostSpawnProcess(BaseEntity entity, BaseSpawnPoint spawnPoint) { }
Step 3: Implement Logic in Your Plugin
In your Dungeons plugin, assign the OnEntitySpawned action for your SpawnGroup to perform actions like setting up an Auto Turret:
csharp
void SetupDungeonTurrets()
{
// Your spawn group setup ...
var spawnGroup = /* Get/Create your SpawnGroup instance */
spawnGroup.OnEntitySpawned = entity =>
{
if (entity is AutoTurret turret)
{
SetupTurret(turret);
}
};
// Start your spawn process or initial spawn
spawnGroup.Spawn();
}
private void SetupTurret(AutoTurret turret)
{
if (turret == null)
{
Puts("Failed to create turret.");
return;
}
AddWeaponToTurret(turret);
LoadTurretWithReserveAmmo(turret.inventory);
turret.UpdateTotalAmmo();
turret.EnsureReloaded();
turret.SetPeacekeepermode(_config.Turret.Peacekeeper);
turret.InitiateStartup();
turret.SendNetworkUpdateImmediate();
}
// Methods AddWeaponToTurret and LoadTurretWithReserveAmmo should be similar to the previous example
Notes and Considerations
Dependency Management: Ensure your newly added SetupTurret, AddWeaponToTurret, and LoadTurretWithReserveAmmo functions correctly utilize the configuration options and dependencies in your environment.
Testing: This kind of integration requires thorough testing to confirm that turrets spawn and behave as expected, under the right conditions.
This approach allows you to keep the customization modular and well-organized, facilitating configuration and future adjustments.