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 5 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using HarmonyLib;
using NitroxTest.Patcher;

namespace NitroxPatcher.Patches.Dynamic;

[TestClass]
public class GrowingPlant_SpawnGrownModelAsync_PatchTest
{
[TestMethod]
public void Sanity()
{
IEnumerable<CodeInstruction> originalIl = PatchTestHelper.GetInstructionsFromMethod(GrowingPlant_SpawnGrownModelAsync_Patch.TARGET_METHOD);
IEnumerable<CodeInstruction> transformedIl = GrowingPlant_SpawnGrownModelAsync_Patch.Transpiler(originalIl);
transformedIl.Count().Should().Be(originalIl.Count() - 1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using HarmonyLib;
using NitroxTest.Patcher;

namespace NitroxPatcher.Patches.Dynamic;

[TestClass]
public class PickPrefab_AddToContainerAsync_PatchTest
{
[TestMethod]
public void Sanity()
{
IEnumerable<CodeInstruction> originalIl = PatchTestHelper.GetInstructionsFromMethod(PickPrefab_AddToContainerAsync_Patch.TARGET_METHOD);
IEnumerable<CodeInstruction> transformedIl = PickPrefab_AddToContainerAsync_Patch.Transpiler(originalIl);
transformedIl.Count().Should().Be(originalIl.Count() + 4);
}
}
16 changes: 16 additions & 0 deletions Nitrox.Test/Patcher/Patches/Dynamic/Trashcan_Update_PatchTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using HarmonyLib;
using NitroxTest.Patcher;

namespace NitroxPatcher.Patches.Dynamic;

[TestClass]
public class Trashcan_Update_PatchTest
{
[TestMethod]
public void Sanity()
{
IEnumerable<CodeInstruction> originalIl = PatchTestHelper.GetInstructionsFromMethod(Trashcan_Update_Patch.TARGET_METHOD);
IEnumerable<CodeInstruction> transformedIl = Trashcan_Update_Patch.Transpiler(originalIl);
transformedIl.Count().Should().Be(originalIl.Count() + 3);
}
}
10 changes: 6 additions & 4 deletions Nitrox.Test/Server/Serialization/WorldPersistenceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,6 @@ private static void ItemDataTest(ItemData itemData, ItemData itemDataAfter)
Assert.AreEqual(equippedItemData.Slot, equippedItemDataAfter.Slot);
Assert.AreEqual(equippedItemData.TechType, equippedItemDataAfter.TechType);
break;
case PlantableItemData plantableItemData when itemDataAfter is PlantableItemData plantableItemDataAfter:
Assert.AreEqual(plantableItemData.PlantedGameTime, plantableItemDataAfter.PlantedGameTime);
break;
default:
Assert.Fail($"Runtime types of {nameof(ItemData)} where not equal");
break;
Expand Down Expand Up @@ -229,7 +226,12 @@ 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);
Copy link
Member

Choose a reason for hiding this comment

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

Would add a comment here that the FruitPlantMetadata field is not checked bc it's (hopefully) 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
49 changes: 0 additions & 49 deletions NitroxClient/GameLogic/Containers/ContainerAddItemPostProcessor.cs

This file was deleted.

This file was deleted.

This file was deleted.

2 changes: 1 addition & 1 deletion NitroxClient/GameLogic/Entities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,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
2 changes: 1 addition & 1 deletion NitroxClient/GameLogic/SimulationOwnership.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public SimulationOwnership(IMultiplayerSession muliplayerSession, IPacketSender
}
public bool PlayerHasMinLockType(NitroxId id, SimulationLockType lockType)
{
if (simulatedIdsByLockType.TryGetValue(id, out SimulationLockType playerLock))
if (id != null && simulatedIdsByLockType.TryGetValue(id, out SimulationLockType playerLock))
{
return playerLock <= lockType;
}
Expand Down
81 changes: 79 additions & 2 deletions NitroxClient/GameLogic/Spawning/InventoryItemEntitySpawner.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
using System;
using System.Collections;
using NitroxClient.Communication;
using NitroxClient.GameLogic.Helper;
using NitroxClient.GameLogic.Spawning.Abstract;
using NitroxClient.GameLogic.Spawning.Metadata;
using NitroxClient.GameLogic.Spawning.WorldEntities;
using NitroxClient.MonoBehaviours;
using NitroxClient.Unity.Helper;
using NitroxModel.DataStructures.GameLogic.Entities;
using NitroxModel.DataStructures.GameLogic.Entities.Metadata;
using NitroxModel.DataStructures.Util;
using NitroxModel.Packets;
using NitroxModel_Subnautica.DataStructures;
using UnityEngine;
using UWE;

namespace NitroxClient.GameLogic.Spawning;

public class InventoryItemEntitySpawner : SyncEntitySpawner<InventoryItemEntity>
public class InventoryItemEntitySpawner(EntityMetadataManager entityMetadataManager) : SyncEntitySpawner<InventoryItemEntity>
{
private readonly EntityMetadataManager entityMetadataManager = entityMetadataManager;

protected override IEnumerator SpawnAsync(InventoryItemEntity entity, TaskResult<Optional<GameObject>> result)
{
if (!CanSpawn(entity, out GameObject parentObject, out ItemsContainer container, out string errorLog))
Expand Down Expand Up @@ -87,15 +93,86 @@ private void SetupObject(InventoryItemEntity entity, GameObject gameObject, Game
Pickupable pickupable = gameObject.RequireComponent<Pickupable>();
pickupable.Initialize();

InventoryItem inventoryItem = new(pickupable);

// Items eventually get "secured" once a player gets into a SubRoot (or for other reasons) so we need to force this state by default
// so that player don't risk their whole inventory if they reconnect in the water.
pickupable.destroyOnDeath = false;

bool isPlanter = parentObject.TryGetComponent(out Planter planter);
bool subscribedValue = false;
if (isPlanter)
{
subscribedValue = planter.subscribed;
planter.Subscribe(false);
}

using (PacketSuppressor<EntityReparented>.Suppress())
using (PacketSuppressor<PlayerQuickSlotsBindingChanged>.Suppress())
using (PacketSuppressor<EntityMetadataUpdate>.Suppress())
{
container.UnsafeAdd(new InventoryItem(pickupable));
container.UnsafeAdd(inventoryItem);
Log.Debug($"Received: Added item {pickupable.GetTechType()} ({entity.Id}) to container {parentObject.GetFullHierarchyPath()}");
}

if (isPlanter)
{
planter.Subscribe(subscribedValue);

if (entity.Metadata is PlantableMetadata metadata)
{
PostponeAddNotification(() => planter.subscribed, () => planter, true, () =>
{
// Adapted from Planter.AddItem(InventoryItem) to be able to call directly AddItem(Plantable, slotID) with our parameters
Plantable plantable = pickupable.GetComponent<Plantable>();
pickupable.SetTechTypeOverride(plantable.plantTechType, false);
inventoryItem.isEnabled = false;
planter.AddItem(plantable, metadata.SlotID);

// Reapply the plantable metadata after the GrowingPlant (or the GrownPlant) is spawned
entityMetadataManager.ApplyMetadata(plantable.gameObject, metadata);

// Plant spawning occurs in multiple steps over frames:
// spawning the item, adding it to the planter, having the GrowingPlant created, and eventually having it create a GrownPlant (when progress == 1)
// therefore we give the metadata to the object so it can be used when required
if (metadata.FruitPlantMetadata != null && plantable.growingPlant && plantable.growingPlant.GetProgress() == 1f)
{
MetadataHolder.AddMetadata(plantable.growingPlant.gameObject, metadata.FruitPlantMetadata);
}
});
}
}
else if (parentObject.TryGetComponent(out Trashcan trashcan))
{
PostponeAddNotification(() => trashcan.subscribed, () => trashcan, false, () =>
{
trashcan.AddItem(inventoryItem);
});
}
}

private static void PostponeAddNotification(Func<bool> subscribed, Func<bool> instanceValid, bool callbackIfAlreadySubscribed, Action callback)
{
IEnumerator PostponedAddCallback()
{
yield return new WaitUntil(() => subscribed() || !instanceValid());
if (instanceValid())
{
using (PacketSuppressor<EntityReparented>.Suppress())
using (PacketSuppressor<EntityMetadataUpdate>.Suppress())
{
callback();
}
}
}

if (!subscribed())
{
CoroutineHost.StartCoroutine(PostponedAddCallback());
}
else if (callbackIfAlreadySubscribed)
{
callback();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Linq;
using NitroxClient.GameLogic.Spawning.Metadata.Extractor.Abstract;
using NitroxModel.DataStructures.GameLogic.Entities.Metadata;

namespace NitroxClient.GameLogic.Spawning.Metadata.Extractor;

public class FruitPlantMetadataExtractor : EntityMetadataExtractor<FruitPlant, FruitPlantMetadata>
{
public override FruitPlantMetadata Extract(FruitPlant fruitPlant)
{
bool[] prefabsPicked = fruitPlant.fruits.Select(prefab => prefab.pickedState).ToArray();

// If fruit spawn is disabled (certain plants like kelp don't regrow their fruits) and if none of the fruits were picked (all picked = false)
// then we don't need to save this data because the plant is spawned like this by default
if (!fruitPlant.fruitSpawnEnabled && prefabsPicked.All(b => !b))
{
return null;
}

return new(prefabsPicked, fruitPlant.timeNextFruit);
}
}
Loading