Skip to content

Commit

Permalink
Merge pull request #12 from KSP2Community/0.2.0
Browse files Browse the repository at this point in the history
0.2.0
  • Loading branch information
cheese3660 authored Sep 2, 2023
2 parents 045d805 + 0b86934 commit 7fe6e45
Show file tree
Hide file tree
Showing 8 changed files with 195 additions and 27 deletions.
26 changes: 19 additions & 7 deletions src/PatchManager.Core/Assets/PatchingManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,26 +226,38 @@ private static AsyncOperationHandle<IList<TextAsset>> RebuildCache(string label)
}
});

handle.Completed += results =>

void SaveArchive()
{
if (results.Status != AsyncOperationStatus.Succeeded || unchanged)
{
return;
}
var archive = CacheManager.CreateArchive(archiveFilename);
foreach (var archiveFile in archiveFiles)
{
archive.AddFile(archiveFile.Key,archiveFile.Value);
archive.AddFile(archiveFile.Key, archiveFile.Value);
}

archive.Save();

CacheManager.CacheValidLabels.Add(label);
CacheManager.Inventory.CacheEntries.Add(label, labelCacheEntry);
CacheManager.Inventory.CacheEntries.AddRangeUnique(assetsCacheEntries);
CacheManager.SaveInventory();

Addressables.Release(results);
Console.WriteLine($"Cache for label '{label}' rebuilt.");
}
if (handle.Status == AsyncOperationStatus.Failed && !unchanged)
{
SaveArchive();
}

handle.Completed += results =>
{
if (results.Status != AsyncOperationStatus.Succeeded || unchanged)
{
return;
}

SaveArchive();
Addressables.Release(results);
};

return handle;
Expand Down
2 changes: 1 addition & 1 deletion src/PatchManager.Core/Cache/Archive.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO.Compression;
using UnityEngine;

namespace PatchManager.Core.Cache;

Expand Down Expand Up @@ -96,7 +97,6 @@ public void AddFile(string filePath, string content)
public void Save()
{
AssertNotDisposed();

using var fileStream = new FileStream(_path, FileMode.Create);
_stream.Seek(0, SeekOrigin.Begin);
_stream.CopyTo(fileStream);
Expand Down
20 changes: 20 additions & 0 deletions src/PatchManager.Parts/Attributes/ModuleDataAdapterAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace PatchManager.Parts.Attributes;

/// <summary>
/// Types that take this attribute must inherit from (ISelectable) and must have a constructor that takes the following arguments
/// JObject - ModuleData.DataObject
/// ModuleSelectable - Module
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class ModuleDataAdapterAttribute : Attribute
{
/// <summary>
/// The types this adapter is used for
/// </summary>
public readonly Type[] ValidTypes;
/// <summary>
/// Mark this class as a custom module data adapter
/// </summary>
/// <param name="validTypes">What data types it adapts</param>
public ModuleDataAdapterAttribute(params Type[] validTypes) => ValidTypes = validTypes;
}
4 changes: 4 additions & 0 deletions src/PatchManager.Parts/PartsModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ namespace PatchManager.Parts;
[UsedImplicitly]
public class PartsModule : BaseModule
{
public override void Preload()
{
PartsUtilities.GrabModuleDataAdapters();
}
}
29 changes: 29 additions & 0 deletions src/PatchManager.Parts/PartsUtilities.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using KSP.Sim.Definitions;
using KSP.Sim.impl;
using PatchManager.Parts.Attributes;
using PatchManager.SassyPatching.Interfaces;

namespace PatchManager.Parts;

Expand Down Expand Up @@ -85,4 +87,31 @@ internal static IReadOnlyDictionary<string, Type> DataModules
return _dataModules;
}
}

internal static readonly Dictionary<Type, Type> ModuleDataAdapters = new();

internal static void GrabModuleDataAdapters()
{
foreach (var type in AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.GetCustomAttributes(typeof(ModuleDataAdapterAttribute),
false)
.Any())
.Select(x => (type: x, attr: (ModuleDataAdapterAttribute)x.GetCustomAttributes(typeof(ModuleDataAdapterAttribute),
false)
.FirstOrDefault())))
{
foreach (var dataType in type.attr.ValidTypes)
{
ModuleDataAdapters[dataType] = type.type;
}
}
}
public static void RegisterModuleDataAdapter<T>(params Type[] validTargets) where T : ISelectable
{
foreach (var type in validTargets)
{
ModuleDataAdapters[type] = typeof(T);
}
}
}
84 changes: 81 additions & 3 deletions src/PatchManager.Parts/Rulesets/PartsRuleset.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
using PatchManager.Parts.Selectables;
using KSP.Game;
using KSP.IO;
using KSP.OAB;
using KSP.Sim;
using KSP.Sim.Definitions;
using KSP.Sim.ResourceSystem;
using Newtonsoft.Json.Linq;
using PatchManager.Parts.Selectables;
using PatchManager.SassyPatching;
using PatchManager.SassyPatching.Attributes;
using PatchManager.SassyPatching.Interfaces;
using PatchManager.SassyPatching.NewAssets;
using UnityEngine;

namespace PatchManager.Parts.Rulesets;

Expand All @@ -25,7 +34,76 @@ public ISelectable ConvertToSelectable(string type, string name, string jsonData
{
return new PartSelectable(jsonData);
}

/// <inheritdoc />
public INewAsset CreateNew(List<DataValue> dataValues) => throw new NotImplementedException();
/// <summary>
/// Create a new part asset
/// </summary>
/// <param name="dataValues">The arguments for the part asset, only one argument: name</param>
/// <returns>The part asset creator</returns>
public INewAsset CreateNew(List<DataValue> dataValues)
{
var name = dataValues[0].String;
var internalPartData = new PartData
{
partName = name,
angularDrag = 0,
coMassOffset = Vector3.zero,
coPressureOffset = Vector3.zero,
mass = 0,
maximumDrag = 0,
maxTemp = 0,
author = "",
bodyLiftOnlyUnattachedLift = false,
bodyLiftOnlyAttachName = "",
buoyancy = 0,
buoyancyUseSine = false,
breakingForce = 0,
breakingTorque = 0,
category = PartCategories.none,
family = "",
coBuoyancy = Vector3.zero,
coDisplacement = Vector3.zero,
oabEditorCategory = OABEditorPartCategory.NONE,
partType = AssemblyPartTypeFilter.Rocket,
cost = 0,
crashTolerance = 0,
crewCapacity = 0,
emissiveConstant = 0,
explosionPotential = 0,
fuelCrossFeed = false,
heatConductivity = 0,
inverseStageCarryover = false,
isCompound = false,
maxLength = 0,
radiatorHeadroom = 0,
radiatorMax = 0,
physicsMode = PartPhysicsModes.None,
sizeCategory = MetaAssemblySizeFilterType.XS,
skinMassPerArea = 0,
skinMaxTemp = 0,
skinInternalConductionMult = 0,
stageOffset = 0,
stageType = AssemblyPartStageType.None,
tags = "",
stagingIconAssetAddress = "",
attachRules = AttachRules.Defaults(),
attachNodes = new List<AttachNodeDefinition>(),
resourceContainers = new List<ContainedResourceDefinition>(),
resourceCosts = new List<PartResourceCostDefinition>(),
serializedPartModules = new List<SerializedPartModule>(),
resourceSummary = new SerializedResourceInfo(),
PAMModuleSortOverride = new List<PartsManagerCore.SerializedPartModuleDisplayOrder>(),
PAMModuleVisualsOverride = new List<PartsManagerCore.SerializedPartModuleDisplayVisuals>(),
AllowKinematicPhysicsIfIntersectTerrain = false
};
var internalJson = IOProvider.ToJson(internalPartData);
var internalJObject = JObject.Parse(internalJson);
var externalJObject = new JObject
{
["version"] = "0.3",
["useExternalData"] = false,
["data"] = internalJObject
};
return new NewGenericAsset("parts_data", name, new PartSelectable(externalJObject.ToString()));
}
}
40 changes: 26 additions & 14 deletions src/PatchManager.Parts/Selectables/ModuleSelectable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,39 @@ namespace PatchManager.Parts.Selectables;
/// </summary>
public sealed class ModuleSelectable : BaseSelectable
{
private JToken _jToken;
private PartSelectable _selectable;
public readonly JToken SerializedData;
public readonly PartSelectable Selectable;

/// <inheritdoc />
public ModuleSelectable(JToken token, PartSelectable selectable)
{
_jToken = token;
_selectable = selectable;
SerializedData = token;
Selectable = selectable;
ElementType = ((string)token["Name"]).Replace("PartComponent", "");
Name = ElementType;
Classes = new();
Children = new();
// Now we go down the list in the data type
var data = token["ModuleData"];
var data = (JArray)token["ModuleData"];
foreach (var moduleData in data)
{
Classes.Add((string)moduleData["Name"]);
// Where we are going to have to add children ree
// TODO: Add a specialization for ModuleEngine
Children.Add(new JTokenSelectable(selectable.SetModified, moduleData["DataObject"], (string)moduleData["Name"]));
Children.Add(GetSelectable((JObject)moduleData));
}
}

private ISelectable GetSelectable(JObject moduleData)
{
var type = Type.GetType((string)moduleData["DataType"]);
if (type != null && PartsUtilities.ModuleDataAdapters.TryGetValue(type, out var adapterType))
{
return (ISelectable)Activator.CreateInstance(type, moduleData, this);
}
else
{
return new JTokenSelectable(Selectable.SetModified, moduleData["DataObject"], (string)moduleData["Name"]);
}
}

Expand All @@ -51,12 +64,12 @@ public ModuleSelectable(JToken token, PartSelectable selectable)

/// <inheritdoc />
public override bool IsSameAs(ISelectable other) =>
other is ModuleSelectable moduleSelectable && moduleSelectable._jToken == _jToken;
other is ModuleSelectable moduleSelectable && moduleSelectable.SerializedData == SerializedData;

/// <inheritdoc />
public override IModifiable OpenModification()
{
return new JTokenModifiable(_jToken, _selectable.SetModified);
return new JTokenModifiable(SerializedData, Selectable.SetModified);
}

/// <inheritdoc />
Expand All @@ -66,7 +79,7 @@ public override ISelectable AddElement(string elementType)
{
throw new Exception($"Unknown data module {elementType}");
}
_selectable.SetModified();
Selectable.SetModified();
var instance = (ModuleData)Activator.CreateInstance(dataModuleType);
// var dataObject = JObject.Parse(IOProvider.ToJson(instance));
var dataObject = new JObject
Expand All @@ -86,16 +99,15 @@ public override ISelectable AddElement(string elementType)
["Data"] = null,
["DataObject"] = dataObject
};
(_jToken["ModuleData"] as JArray)?.Add(trueType);
(SerializedData["ModuleData"] as JArray)?.Add(trueType);
Classes.Add(dataModuleType.Name);
var selectable = new JTokenSelectable(_selectable.SetModified, trueType["DataObject"], dataModuleType.Name);
var selectable = GetSelectable(trueType);
Children.Add(selectable);
return selectable;
}

/// <inheritdoc />
public override string Serialize() => _jToken.ToString();

public override string Serialize() => SerializedData.ToString();
/// <inheritdoc />
public override DataValue GetValue() => DataValue.FromJToken(_jToken);
public override DataValue GetValue() => DataValue.FromJToken(SerializedData);
}
17 changes: 15 additions & 2 deletions src/PatchManager.SassyPatching/Selectables/JTokenSelectable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,21 @@ public override IModifiable OpenModification()
/// <inheritdoc />
public override ISelectable AddElement(string elementType)
{
Token[elementType] = new JObject();
return new JTokenSelectable(_markDirty, Token[elementType],elementType);
var obj = new JObject();
if (Token is JArray jArray)
{
jArray[elementType] = obj;
} else if (Token is JObject jObject)
{
jObject[elementType] = obj;
}
else
{
throw new InvalidOperationException();
}
var n = new JTokenSelectable(_markDirty, obj, elementType);
Children.Add(n);
return n;
}

/// <inheritdoc />
Expand Down

0 comments on commit 7fe6e45

Please sign in to comment.