Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crops persistence #2137

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Nitrox.Test/Patcher/Patches/PatchesTranspilerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,25 +49,29 @@ public class PatchesTranspilerTest
[typeof(Flare_Update_Patch), 0],
[typeof(FootstepSounds_OnStep_Patch), 6],
[typeof(GameInput_Initialize_Patch), 5],
[typeof(GrowingPlant_SpawnGrownModelAsync_Patch), -1],
[typeof(Player_TriggerInfectionRevealAsync_Patch), 1],
[typeof(IngameMenu_OnSelect_Patch), -2],
[typeof(IngameMenu_QuitGameAsync_Patch), 2],
[typeof(IngameMenu_QuitSubscreen_Patch), -24],
[typeof(ItemsContainer_DestroyItem_Patch), 2],
[typeof(Knife_OnToolUseAnim_Patch), 0],
[typeof(LargeRoomWaterPark_OnDeconstructionStart_Patch), 3],
[typeof(LargeWorldEntity_UpdateCell_Patch), 1],
[typeof(LaunchRocket_OnHandClick_Patch), -9],
[typeof(LeakingRadiation_Update_Patch), 0],
[typeof(MainGameController_StartGame_Patch), 1],
[typeof(MeleeAttack_CanDealDamageTo_Patch), 4],
[typeof(PDAScanner_Scan_Patch), 3],
[typeof(PickPrefab_AddToContainerAsync_Patch), 4],
[typeof(Player_OnKill_Patch), 0],
[typeof(Respawn_Start_Patch), 3],
[typeof(RocketConstructor_StartRocketConstruction_Patch), 3],
[typeof(SpawnConsoleCommand_SpawnAsync_Patch), 2],
[typeof(SpawnOnKill_OnKill_Patch), 3],
[typeof(SubConsoleCommand_OnConsoleCommand_sub_Patch), 0],
[typeof(SubRoot_OnPlayerEntered_Patch), 5],
[typeof(Trashcan_Update_Patch), 4],
[typeof(uGUI_PDA_Initialize_Patch), 2],
[typeof(uGUI_PDA_SetTabs_Patch), 3],
[typeof(uGUI_Pings_IsVisibleNow_Patch), 0],
Expand Down
8 changes: 7 additions & 1 deletion Nitrox.Test/Server/Serialization/WorldPersistenceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,13 @@ private static void EntityTest(Entity entity, Entity entityAfter)
Assert.AreEqual(metadata.Duration, metadataAfter.Duration);
break;
case PlantableMetadata metadata when entityAfter.Metadata is PlantableMetadata metadataAfter:
Assert.AreEqual(metadata.Progress, metadataAfter.Progress);
Assert.AreEqual(metadata.TimeStartGrowth, metadataAfter.TimeStartGrowth);
Assert.AreEqual(metadata.SlotID, metadataAfter.SlotID);
// FruitPlantMetadata field is not checked before it's only temporary
break;
case FruitPlantMetadata metadata when entityAfter.Metadata is FruitPlantMetadata metadataAfter:
Assert.AreEqual(metadata.PickedStates, metadataAfter.PickedStates);
Assert.AreEqual(metadata.TimeNextFruit, metadataAfter.TimeNextFruit);
break;
case CyclopsMetadata metadata when entityAfter.Metadata is CyclopsMetadata metadataAfter:
Assert.AreEqual(metadata.SilentRunningOn, metadataAfter.SilentRunningOn);
Expand Down
3 changes: 0 additions & 3 deletions NitroxClient/ClientAutoFacRegistrar.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
global using NitroxClient.Helpers;
global using NitroxModel.Logger;
global using static NitroxModel.Extensions;
using System.Reflection;
using Autofac;
using Autofac.Core;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ public class BaseDeconstructedProcessor : BuildProcessor<BaseDeconstructed> { }
public class PieceDeconstructedProcessor : BuildProcessor<PieceDeconstructed> { }

public class WaterParkDeconstructedProcessor : BuildProcessor<WaterParkDeconstructed> { }

public class LargeWaterParkDeconstructedProcessor : BuildProcessor<LargeWaterParkDeconstructed> { }
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public override void Process(EntityDestroyed packet)
}
else
{
DefaultDestroyAction(gameObject);
Entities.DestroyObject(gameObject);
}
}
}
Expand Down Expand Up @@ -92,9 +92,4 @@ private void DestroyVehicle(Vehicle vehicle)
Object.Destroy(vehicle.gameObject);
}
}

private void DefaultDestroyAction(GameObject gameObject)
{
Object.Destroy(gameObject);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,24 @@ public override void Process(EntityReparented packet)

if (entity.Value.TryGetComponent(out Pickupable pickupable))
{
WaterParkItem waterParkItem = pickupable.GetComponent<WaterParkItem>();
// If the entity is being parented to a WaterPark
if (newParent.TryGetComponent(out WaterPark waterPark))
{
// If the entity is already in a WaterPark
if (waterParkItem.currentWaterPark)
{
waterParkItem.SetWaterPark(waterPark);
return;
}
pickupable.SetVisible(false);
pickupable.Activate(false);
waterPark.AddItem(pickupable);
// The reparenting is automatic here so we don't need to continue
return;
}
// If the entity was parented to a WaterPark but is picked up by someone
else if (pickupable.TryGetComponent(out WaterParkItem waterParkItem))
else if (waterParkItem)
{
pickupable.Deactivate();
waterParkItem.SetWaterPark(null);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using NitroxClient.Communication.Packets.Processors.Abstract;
using NitroxModel.Packets;

namespace NitroxClient.Communication.Packets.Processors;

public class FastCheatChangedProcessor : ClientPacketProcessor<FastCheatChanged>
{
public override void Process(FastCheatChanged packet)
{
switch (packet.Cheat)
{
case FastCheatChanged.FastCheat.HATCH:
NoCostConsoleCommand.main.fastHatchCheat = packet.Value;
break;

case FastCheatChanged.FastCheat.GROW:
NoCostConsoleCommand.main.fastGrowCheat = packet.Value;
break;
}
}
}
2 changes: 1 addition & 1 deletion NitroxClient/Debuggers/NetworkDebugger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class NetworkDebugger : BaseDebugger, INetworkDebugger
{
nameof(PlayerMovement), nameof(EntityTransformUpdates), nameof(PlayerStats), nameof(SpawnEntities), nameof(VehicleMovements), nameof(PlayerCinematicControllerCall),
nameof(FMODAssetPacket), nameof(FMODEventInstancePacket), nameof(FMODCustomEmitterPacket), nameof(FMODStudioEmitterPacket), nameof(FMODCustomLoopingEmitterPacket),
nameof(SimulationOwnershipChange), nameof(CellVisibilityChanged), nameof(PlayerInCyclopsMovement), nameof(CreatureActionChanged),
nameof(SimulationOwnershipChange), nameof(CellVisibilityChanged), nameof(PlayerInCyclopsMovement), nameof(CreatureActionChanged), nameof(FootstepPacket)
};
private readonly List<PacketDebugWrapper> packets = new List<PacketDebugWrapper>(PACKET_STORED_COUNT);

Expand Down
23 changes: 23 additions & 0 deletions NitroxClient/Debuggers/SceneExtraDebugger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Text.RegularExpressions;
using NitroxClient.MonoBehaviours;
using NitroxClient.Unity.Helper;
using NitroxModel.DataStructures;
using NitroxModel.Helper;
using UnityEngine;
using Mathf = UnityEngine.Mathf;
Expand Down Expand Up @@ -251,6 +252,28 @@ private void GettingSearchbarResults()
GUILayout.Label($"There is no component named \"{gameObjectSearch.Substring(2)}\"", "error");
}
}
else if (gameObjectSearch.StartsWith("id:"))
{
string id = gameObjectSearch.Split(':')[1];
try
{
NitroxId foundId = new(id);
if (NitroxEntity.TryGetObjectFrom(foundId, out GameObject gameObject))
{
gameObjectResults = [gameObject];
}
else
{
GUILayout.Label($"No GameObject found with NitroxId \"{foundId}\"");
gameObjectResults = [];
}
}
catch
{
GUILayout.Label($"Id \"{id}\" is not a valid NitroxId");
gameObjectResults = [];
}
}
else
{
gameObjectResults = Resources.FindObjectsOfTypeAll<GameObject>().
Expand Down
8 changes: 8 additions & 0 deletions NitroxClient/GameLogic/Bases/BuildingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ public IEnumerator DeconstructPiece(PieceDeconstructed pieceDeconstructed)
using (PacketSuppressor<BaseDeconstructed>.Suppress())
using (PacketSuppressor<PieceDeconstructed>.Suppress())
using (PacketSuppressor<WaterParkDeconstructed>.Suppress())
using (PacketSuppressor<LargeWaterParkDeconstructed>.Suppress())
using (Temp.Fill(pieceDeconstructed))
{
baseDeconstructable.Deconstruct();
Expand Down Expand Up @@ -291,6 +292,7 @@ public class TemporaryBuildData : IDisposable
public List<NitroxId> MovedChildrenIds;
public (NitroxId, NitroxId) ChildrenTransfer;
public bool Transfer;
public Dictionary<NitroxId, List<NitroxId>> MovedChildrenIdsByNewHostId;

public void Dispose()
{
Expand All @@ -299,6 +301,7 @@ public void Dispose()
MovedChildrenIds = null;
ChildrenTransfer = (null, null);
Transfer = false;
MovedChildrenIdsByNewHostId = null;
}

public TemporaryBuildData Fill(PieceDeconstructed pieceDeconstructed)
Expand All @@ -309,6 +312,11 @@ public TemporaryBuildData Fill(PieceDeconstructed pieceDeconstructed)
NewWaterPark = waterParkDeconstructed.NewWaterPark;
MovedChildrenIds = waterParkDeconstructed.MovedChildrenIds;
Transfer = waterParkDeconstructed.Transfer;
return this;
}
if (pieceDeconstructed is LargeWaterParkDeconstructed largeWaterParkDeconstructed)
{
MovedChildrenIdsByNewHostId = largeWaterParkDeconstructed.MovedChildrenIdsByNewHostId;
}
return this;
}
Expand Down
23 changes: 21 additions & 2 deletions NitroxClient/GameLogic/Entities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public Entities(IPacketSender packetSender, ThrottledPacketSender throttledPacke
entitySpawnersByType[typeof(InstalledModuleEntity)] = new InstalledModuleEntitySpawner();
entitySpawnersByType[typeof(InstalledBatteryEntity)] = new InstalledBatteryEntitySpawner();
entitySpawnersByType[typeof(InventoryEntity)] = new InventoryEntitySpawner();
entitySpawnersByType[typeof(InventoryItemEntity)] = new InventoryItemEntitySpawner();
entitySpawnersByType[typeof(InventoryItemEntity)] = new InventoryItemEntitySpawner(entityMetadataManager);
entitySpawnersByType[typeof(WorldEntity)] = new WorldEntitySpawner(entityMetadataManager, playerManager, localPlayer, this, simulationOwnership);
entitySpawnersByType[typeof(PlaceholderGroupWorldEntity)] = entitySpawnersByType[typeof(WorldEntity)];
entitySpawnersByType[typeof(PrefabPlaceholderEntity)] = entitySpawnersByType[typeof(WorldEntity)];
Expand Down Expand Up @@ -256,11 +256,30 @@ public void CleanupExistingEntities(List<Entity> dirtyEntities)

if (gameObject.HasValue)
{
UnityEngine.Object.Destroy(gameObject.Value);
DestroyObject(gameObject.Value);
}
}
}

/// <summary>
/// Either perform a special operation (e.g. for plants) or a simple <see cref="UnityEngine.Object.Destroy"/>
/// </summary>
public static void DestroyObject(GameObject gameObject)
{
if (gameObject.TryGetComponent(out Plantable plantable))
{
plantable.FreeSpot();
return;
}
if (gameObject.TryGetComponent(out GrownPlant grownPlant))
{
grownPlant.seed.AliveOrNull()?.FreeSpot();
return;
}

UnityEngine.Object.Destroy(gameObject);
}

private void UpdateEntity(Entity entity)
{
if (!NitroxEntity.TryGetObjectFrom(entity.Id, out GameObject gameObject))
Expand Down
10 changes: 9 additions & 1 deletion NitroxClient/GameLogic/Helper/InventoryContainerHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,15 @@ public static bool TryGetOwnerId(Transform ownerTransform, out NitroxId ownerId)
ownerId = null;
return false;
}
// TODO: in the future maybe use a switch on the PrefabId (it's always the same structure in a prefab)
// and then statically look for the right object because we'll know exactly which one it is

if (parent.GetComponent<Constructable>() || parent.GetComponent<IBaseModule>().AliveOrNull())
// This check must happen before the GetComponent<IBaseModule> which will be triggered (wrong result)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm unclear what this is trying to say. Is it saying that if the GetComponent call is done first it will produce an unwanted outcome? If so I think the end of the comment should be reworded it's a little unclear if being triggered is wrong or if this check prevents that

if (parent.TryGetComponent(out WaterPark waterPark))
{
return waterPark.planter.TryGetIdOrWarn(out ownerId);
}
else if (parent.GetComponent<Constructable>() || parent.GetComponent<IBaseModule>().AliveOrNull())
{
return parent.TryGetIdOrWarn(out ownerId);
}
Expand All @@ -65,6 +72,7 @@ public static bool TryGetOwnerId(Transform ownerTransform, out NitroxId ownerId)
{
return true;
}
// For regular water parks, the main object contains the StorageRoot and the planter at the same level
else if (LockerRegex.IsMatch(ownerTransform.gameObject.name))
{
string lockerId = ownerTransform.gameObject.name.Substring(7, 1);
Expand Down
24 changes: 21 additions & 3 deletions NitroxClient/GameLogic/InitialSync/PlayerInitialSyncProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections;
using System.Text;
using NitroxClient.GameLogic.InitialSync.Abstract;
using NitroxClient.MonoBehaviours;
using NitroxModel.DataStructures;
Expand Down Expand Up @@ -34,7 +35,7 @@ public PlayerInitialSyncProcessor(Items item, ItemContainers itemContainers, Loc
AddStep(sync => AddStartingItemsToPlayer(sync.FirstTimeConnecting));
AddStep(sync => SetPlayerStats(sync.PlayerStatsData));
AddStep(sync => SetPlayerGameMode(sync.GameMode));
AddStep(sync => SetPlayerKeepInventoryOnDeath(sync.KeepInventoryOnDeath));
AddStep(sync => ApplySettings(sync.KeepInventoryOnDeath, sync.SessionSettings.FastHatch, sync.SessionSettings.FastGrow));
}

private void SetPlayerPermissions(Perms permissions)
Expand Down Expand Up @@ -96,7 +97,7 @@ private IEnumerator AddStartingItemsToPlayer(bool firstTimeConnecting)
Pickupable pickupable = gameObject.GetComponent<Pickupable>();
pickupable.Initialize();

item.Created(gameObject);
item.PickedUp(gameObject, techType);
itemContainers.AddItem(gameObject, localPlayerId);
}
}
Expand Down Expand Up @@ -137,8 +138,25 @@ private static void SetPlayerGameMode(NitroxGameMode gameMode)
GameModeUtils.SetGameMode((GameModeOption)(int)gameMode, GameModeOption.None);
}

private void SetPlayerKeepInventoryOnDeath(bool keepInventoryOnDeath)
private void ApplySettings(bool keepInventoryOnDeath, bool fastHatch, bool fastGrow)
{
localPlayer.KeepInventoryOnDeath = keepInventoryOnDeath;
NoCostConsoleCommand.main.fastHatchCheat = fastHatch;
NoCostConsoleCommand.main.fastGrowCheat = fastGrow;
if (!fastHatch && !fastGrow)
{
return;
}

StringBuilder cheatsEnabled = new("Cheats enabled:");
if (fastHatch)
{
cheatsEnabled.Append(" fastHatch");
}
if (fastGrow)
{
cheatsEnabled.Append(" fastGrow");
}
Log.InGame(cheatsEnabled.ToString());
}
}
Loading