fix(codegen): Adds default codegen option for save flags. Fixes world load issues. (#707)

This commit is contained in:
Kamron Batman 2021-08-19 22:51:44 -07:00 • committed by GitHub
parent 3fc2b76468
commit ca5e9342a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 204 additions and 109 deletions

View file

@ -116,6 +116,8 @@ namespace SerializationGenerator
compilation.GetTypeByMetadataName(SymbolMetadata.SERIALIZABLE_PARENT_ATTRIBUTE); compilation.GetTypeByMetadataName(SymbolMetadata.SERIALIZABLE_PARENT_ATTRIBUTE);
var serializableFieldSaveFlagAttribute = var serializableFieldSaveFlagAttribute =
compilation.GetTypeByMetadataName(SymbolMetadata.SERIALIZABLE_FIELD_SAVE_FLAG_ATTRIBUTE); compilation.GetTypeByMetadataName(SymbolMetadata.SERIALIZABLE_FIELD_SAVE_FLAG_ATTRIBUTE);
var serializableFieldDefaultAttribute =
compilation.GetTypeByMetadataName(SymbolMetadata.SERIALIZABLE_FIELD_DEFAULT_ATTRIBUTE);
// If we have a parent that is or derives from ISerializable, then we are in override // If we have a parent that is or derives from ISerializable, then we are in override
var isOverride = classSymbol.BaseType.ContainsInterface(serializableInterface); var isOverride = classSymbol.BaseType.ContainsInterface(serializableInterface);
@ -131,21 +133,28 @@ namespace SerializationGenerator
var encodedVersion = (bool)serializableAttr.ConstructorArguments[1].Value!; var encodedVersion = (bool)serializableAttr.ConstructorArguments[1].Value!;
// Let's find out if we need to do serialization flags // Let's find out if we need to do serialization flags
var serializablePropertyFlagGettersSet = new SortedSet<(IMethodSymbol, int)>(new SerializableFieldFlagComparer()); var serializableFieldSaveFlags = new SortedDictionary<int, SerializableFieldSaveFlagMethods>();
foreach (var m in classSymbol.GetMembers().OfType<IMethodSymbol>()) foreach (var m in classSymbol.GetMembers().OfType<IMethodSymbol>())
{ {
var getSaveFlagAttribute = m.GetAttribute(serializableFieldSaveFlagAttribute); var getSaveFlagAttribute = m.GetAttribute(serializableFieldSaveFlagAttribute);
if (getSaveFlagAttribute == null) var getDefaultValueAttribute = m.GetAttribute(serializableFieldDefaultAttribute);
if (getSaveFlagAttribute == null && getDefaultValueAttribute == null)
{ {
continue; continue;
} }
var attrCtorArgs = getSaveFlagAttribute.ConstructorArguments; var attrCtorArgs = getSaveFlagAttribute?.ConstructorArguments ?? getDefaultValueAttribute.ConstructorArguments;
var order = (int)attrCtorArgs[0].Value!; var order = (int)attrCtorArgs[0].Value!;
serializablePropertyFlagGettersSet.Add((m, order)); serializableFieldSaveFlags.TryGetValue(order, out var saveFlagMethods);
serializableFieldSaveFlags[order] = new SerializableFieldSaveFlagMethods
{
DetermineFieldShouldSerialize = getSaveFlagAttribute != null ? m : saveFlagMethods?.DetermineFieldShouldSerialize,
GetFieldDefaultValue = getDefaultValueAttribute != null ? m : saveFlagMethods?.GetFieldDefaultValue
};
} }
var serializablePropertyFlagGetters = serializablePropertyFlagGettersSet.ToImmutableArray();
var namespaceName = classSymbol.ContainingNamespace.ToDisplayString(); var namespaceName = classSymbol.ContainingNamespace.ToDisplayString();
var className = classSymbol.Name; var className = classSymbol.Name;
@ -243,6 +252,8 @@ namespace SerializationGenerator
source.AppendLine(); source.AppendLine();
} }
serializableFieldSaveFlags.TryGetValue(order, out var serializableFieldSaveFlagMethods);
var serializableProperty = SerializableMigrationRulesEngine.GenerateSerializableProperty( var serializableProperty = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation, compilation,
fieldOrPropertySymbol, fieldOrPropertySymbol,
@ -251,7 +262,7 @@ namespace SerializationGenerator
serializableTypes, serializableTypes,
embeddedSerializableTypes, embeddedSerializableTypes,
classSymbol, classSymbol,
serializablePropertyFlagGetters.FirstOrDefault(m => m.Item2 == order).Item1 serializableFieldSaveFlagMethods
); );
serializablePropertySet.Add(serializableProperty); serializablePropertySet.Add(serializableProperty);
@ -298,7 +309,7 @@ namespace SerializationGenerator
var migration = migrations[i]; var migration = migrations[i];
if (migration.Version < version) if (migration.Version < version)
{ {
source.GenerateMigrationContentStruct(migration, classSymbol); source.GenerateMigrationContentStruct(compilation, migration, classSymbol);
source.AppendLine(); source.AppendLine();
} }
} }
@ -310,7 +321,7 @@ namespace SerializationGenerator
isOverride, isOverride,
encodedVersion, encodedVersion,
serializableProperties, serializableProperties,
serializablePropertyFlagGetters serializableFieldSaveFlags
); );
source.AppendLine(); source.AppendLine();
@ -324,11 +335,11 @@ namespace SerializationGenerator
migrations, migrations,
serializableProperties, serializableProperties,
parentFieldOrProperty, parentFieldOrProperty,
serializablePropertyFlagGetters serializableFieldSaveFlags
); );
// Serialize SaveFlag enum class // Serialize SaveFlag enum class
if (serializablePropertyFlagGetters.Length > 0) if (serializableFieldSaveFlags.Count > 0)
{ {
source.AppendLine(); source.AppendLine();
source.GenerateEnumStart( source.GenerateEnumStart(
@ -340,7 +351,7 @@ namespace SerializationGenerator
source.GenerateEnumValue(" ", true, "None", -1); source.GenerateEnumValue(" ", true, "None", -1);
int index = 0; int index = 0;
foreach (var (_, order) in serializablePropertyFlagGetters) foreach (var (order, _) in serializableFieldSaveFlags)
{ {
source.GenerateEnumValue(" ", true, serializableProperties[order].Name, index++); source.GenerateEnumValue(" ", true, serializableProperties[order].Name, index++);
} }

View file

@ -13,6 +13,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * * along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/ *************************************************************************/
using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -33,7 +34,7 @@ namespace SerializationGenerator
ImmutableArray<SerializableMetadata> migrations, ImmutableArray<SerializableMetadata> migrations,
ImmutableArray<SerializableProperty> properties, ImmutableArray<SerializableProperty> properties,
ISymbol parentFieldOrProperty, ISymbol parentFieldOrProperty,
ImmutableArray<(IMethodSymbol, int)> propertyFlagGetters SortedDictionary<int, SerializableFieldSaveFlagMethods> serializableFieldSaveFlagMethodsDictionary
) )
{ {
var genericReaderInterface = compilation.GetTypeByMetadataName(SymbolMetadata.GENERIC_READER_INTERFACE); var genericReaderInterface = compilation.GetTypeByMetadataName(SymbolMetadata.GENERIC_READER_INTERFACE);
@ -59,18 +60,23 @@ namespace SerializationGenerator
var afterDeserialization = classSymbol var afterDeserialization = classSymbol
.GetMembers() .GetMembers()
.OfType<IMethodSymbol>() .OfType<IMethodSymbol>()
.FirstOrDefault( .Select(
m => m =>
m.ReturnsVoid && {
m.Parameters.Length == 0 && if (!m.ReturnsVoid || m.Parameters.Length != 0)
m.GetAttributes() {
.Any( return (m, null);
}
return (m, m.GetAttributes()
.FirstOrDefault(
attr => SymbolEqualityComparer.Default.Equals( attr => SymbolEqualityComparer.Default.Equals(
attr.AttributeClass, attr.AttributeClass,
compilation.GetTypeByMetadataName(SymbolMetadata.AFTERDESERIALIZATION_ATTRIBUTE) compilation.GetTypeByMetadataName(SymbolMetadata.AFTERDESERIALIZATION_ATTRIBUTE)
) )
) ));
); }
).Where(m => m.Item2 != null).ToList();
// Version // Version
source.AppendLine($"{indent}var version = reader.{(encodedVersion ? "ReadEncodedInt" : "ReadInt")}();"); source.AppendLine($"{indent}var version = reader.{(encodedVersion ? "ReadEncodedInt" : "ReadInt")}();");
@ -93,10 +99,7 @@ namespace SerializationGenerator
source.AppendLine($"{indent}{{"); source.AppendLine($"{indent}{{");
source.AppendLine($"{indent} MigrateFrom(new V{migrationVersion}Content(reader, this));"); source.AppendLine($"{indent} MigrateFrom(new V{migrationVersion}Content(reader, this));");
source.AppendLine($"{indent} {parent}.MarkDirty();"); source.AppendLine($"{indent} {parent}.MarkDirty();");
if (afterDeserialization != null) source.GenerateAfterDeserialization($"{indent} ", afterDeserialization);
{
source.AppendLine($"{indent} Timer.DelayCall({afterDeserialization.Name});");
}
source.AppendLine($"{indent} return;"); source.AppendLine($"{indent} return;");
source.AppendLine($"{indent}}}"); source.AppendLine($"{indent}}}");
} }
@ -108,16 +111,13 @@ namespace SerializationGenerator
source.AppendLine($"{indent}{{"); source.AppendLine($"{indent}{{");
source.AppendLine($"{indent} Deserialize(reader, version);"); source.AppendLine($"{indent} Deserialize(reader, version);");
source.AppendLine($"{indent} {parent}.MarkDirty();"); source.AppendLine($"{indent} {parent}.MarkDirty();");
if (afterDeserialization != null) source.GenerateAfterDeserialization($"{indent} ", afterDeserialization);
{
source.AppendLine($"{indent} Timer.DelayCall({afterDeserialization.Name});");
}
source.AppendLine($"{indent} return;"); source.AppendLine($"{indent} return;");
source.AppendLine($"{indent}}}"); source.AppendLine($"{indent}}}");
} }
} }
if (propertyFlagGetters.Length > 0) if (serializableFieldSaveFlagMethodsDictionary.Count > 0)
{ {
source.AppendLine(); source.AppendLine();
source.AppendLine($"{indent}var saveFlags = reader.ReadEnum<SaveFlag>();"); source.AppendLine($"{indent}var saveFlags = reader.ReadEnum<SaveFlag>();");
@ -125,10 +125,13 @@ namespace SerializationGenerator
foreach (var property in properties) foreach (var property in properties)
{ {
var usesSaveFlag = propertyFlagGetters.Any(m => m.Item2 == property.Order);
var rule = SerializableMigrationRulesEngine.Rules[property.Rule]; var rule = SerializableMigrationRulesEngine.Rules[property.Rule];
if (usesSaveFlag)
if (serializableFieldSaveFlagMethodsDictionary.TryGetValue(
property.Order,
out var serializableFieldSaveFlagMethods
))
{ {
source.AppendLine(); source.AppendLine();
// Special case // Special case
@ -146,6 +149,15 @@ namespace SerializationGenerator
"this" "this"
); );
(rule as IPostDeserializeMethod)?.PostDeserializeMethod(source, innerIndent, property, compilation, classSymbol); (rule as IPostDeserializeMethod)?.PostDeserializeMethod(source, innerIndent, property, compilation, classSymbol);
if (serializableFieldSaveFlagMethods.GetFieldDefaultValue != null)
{
source.AppendLine($"{indent}}}\n{indent}else\n{indent}{{");
source.AppendLine(
$"{indent} {property.Name} = {serializableFieldSaveFlagMethods.GetFieldDefaultValue.Name}();"
);
}
source.AppendLine($"{indent}}}"); source.AppendLine($"{indent}}}");
} }
} }
@ -162,13 +174,25 @@ namespace SerializationGenerator
} }
} }
if (afterDeserialization != null) source.GenerateAfterDeserialization($"{indent}", afterDeserialization);
{
source.AppendLine();
source.AppendLine($"{indent}Timer.DelayCall({afterDeserialization.Name});");
}
source.GenerateMethodEnd(" "); source.GenerateMethodEnd(" ");
} }
private static void GenerateAfterDeserialization(
this StringBuilder source, string indent, IList<(IMethodSymbol, AttributeData?)> afterDeserialization
)
{
foreach (var (method, attr) in afterDeserialization)
{
if ((bool)attr.ConstructorArguments[0].Value!)
{
source.AppendLine($"{indent}{method.Name}();");
}
else
{
source.AppendLine($"{indent}Timer.DelayCall({method.Name});");
}
}
}
} }
} }

View file

@ -13,6 +13,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * * along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/ *************************************************************************/
using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -29,7 +30,7 @@ namespace SerializationGenerator
bool isOverride, bool isOverride,
bool encodedVersion, bool encodedVersion,
ImmutableArray<SerializableProperty> properties, ImmutableArray<SerializableProperty> properties,
ImmutableArray<(IMethodSymbol, int)> propertyFlagGetters SortedDictionary<int, SerializableFieldSaveFlagMethods> serializableFieldSaveFlagMethodsDictionary
) )
{ {
var genericWriterInterface = compilation.GetTypeByMetadataName(SymbolMetadata.GENERIC_WRITER_INTERFACE); var genericWriterInterface = compilation.GetTypeByMetadataName(SymbolMetadata.GENERIC_WRITER_INTERFACE);
@ -56,13 +57,13 @@ namespace SerializationGenerator
source.AppendLine($"{indent}writer.{(encodedVersion ? "WriteEncodedInt" : "Write")}(_version);"); source.AppendLine($"{indent}writer.{(encodedVersion ? "WriteEncodedInt" : "Write")}(_version);");
// Let's collect the flags // Let's collect the flags
if (propertyFlagGetters.Length > 0) if (serializableFieldSaveFlagMethodsDictionary.Count > 0)
{ {
source.AppendLine($"\n{indent}var saveFlags = SaveFlag.None;"); source.AppendLine($"\n{indent}var saveFlags = SaveFlag.None;");
foreach (var (m, order) in propertyFlagGetters) foreach (var (order, saveFlagMethods) in serializableFieldSaveFlagMethodsDictionary)
{ {
source.AppendLine($"{indent}if ({m.Name}())\n{indent}{{"); source.AppendLine($"{indent}if ({saveFlagMethods.DetermineFieldShouldSerialize!.Name}())\n{indent}{{");
var propertyName = properties[order].Name; var propertyName = properties[order].Name;
source.AppendLine($"{innerIndent}saveFlags |= SaveFlag.{propertyName};"); source.AppendLine($"{innerIndent}saveFlags |= SaveFlag.{propertyName};");
@ -75,9 +76,7 @@ namespace SerializationGenerator
foreach (var property in properties) foreach (var property in properties)
{ {
var usesSaveFlag = propertyFlagGetters.Any(m => m.Item2 == property.Order); if (serializableFieldSaveFlagMethodsDictionary.ContainsKey(property.Order))
if (usesSaveFlag)
{ {
// Special case // Special case
if (property.Type != "bool") if (property.Type != "bool")

View file

@ -0,0 +1,11 @@
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public record SerializableFieldSaveFlagMethods
{
public IMethodSymbol? DetermineFieldShouldSerialize { get; init; }
public IMethodSymbol? GetFieldDefaultValue { get; init; }
}
}

View file

@ -2,7 +2,7 @@
* ModernUO * * ModernUO *
* Copyright 2019-2021 - ModernUO Development Team * * Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: SerializationGenerator.ContentStruct.cs * * File: SerializationEntityGeneration.ContentStruct.cs *
* * * *
* This program is free software: you can redistribute it and/or modify * * This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by * * it under the terms of the GNU General Public License as published by *
@ -25,6 +25,7 @@ namespace SerializationGenerator
{ {
public static void GenerateMigrationContentStruct( public static void GenerateMigrationContentStruct(
this StringBuilder source, this StringBuilder source,
Compilation compilation,
SerializableMetadata migration, SerializableMetadata migration,
INamedTypeSymbol classSymbol INamedTypeSymbol classSymbol
) )
@ -37,10 +38,14 @@ namespace SerializationGenerator
foreach (var serializableProperty in properties) foreach (var serializableProperty in properties)
{ {
source.AppendLine($"{indent} internal readonly {serializableProperty.Type} {serializableProperty.Name};"); var type = compilation.GetTypeByMetadataName(serializableProperty.Type)?.IsValueType == true
|| SymbolMetadata.IsPrimitiveFromTypeDisplayString(serializableProperty.Type)
? $"{serializableProperty.Type}?" : serializableProperty.Type;
source.AppendLine($"{indent} internal readonly {type} {serializableProperty.Name};");
} }
var innerIndent = $"{indent} "; const string innerIndent = $"{indent} ";
var usesSaveFlags = properties.Any(p => p.UsesSaveFlag == true); var usesSaveFlags = properties.Any(p => p.UsesSaveFlag == true);
@ -54,7 +59,7 @@ namespace SerializationGenerator
Accessibility.Private Accessibility.Private
); );
source.GenerateEnumValue(" ", true, "None", -1); source.GenerateEnumValue(innerIndent, true, "None", -1);
int index = 0; int index = 0;
foreach (var property in properties) foreach (var property in properties)
{ {
@ -77,7 +82,6 @@ namespace SerializationGenerator
if (properties.Length > 0) if (properties.Length > 0)
{ {
source.AppendLine();
foreach (var property in properties) foreach (var property in properties)
{ {
if (property.UsesSaveFlag == true) if (property.UsesSaveFlag == true)
@ -91,6 +95,7 @@ namespace SerializationGenerator
else else
{ {
source.AppendLine($"{innerIndent}if ((saveFlags & V{migration.Version}SaveFlag.{property.Name}) != 0)\n{innerIndent}{{"); source.AppendLine($"{innerIndent}if ((saveFlags & V{migration.Version}SaveFlag.{property.Name}) != 0)\n{innerIndent}{{");
SerializableMigrationRulesEngine.Rules[property.Rule].GenerateDeserializationMethod( SerializableMigrationRulesEngine.Rules[property.Rule].GenerateDeserializationMethod(
source, source,
$"{innerIndent} ", $"{innerIndent} ",

View file

@ -1,31 +0,0 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace SerializableMigration
{
public class SerializableFieldFlagComparer : IComparer<(IMethodSymbol, int)>
{
public int Compare((IMethodSymbol, int) x, (IMethodSymbol, int) y)
{
var (methodSymbolX, orderX) = x;
var (methodSymbolY, orderY) = y;
if (ReferenceEquals(methodSymbolX, methodSymbolY))
{
return 0;
}
if (ReferenceEquals(null, methodSymbolY))
{
return 1;
}
if (ReferenceEquals(null, methodSymbolX))
{
return -1;
}
return orderX.CompareTo(orderY);
}
}
}

View file

@ -56,7 +56,7 @@ namespace SerializableMigration
ImmutableArray<INamedTypeSymbol> serializableTypes, ImmutableArray<INamedTypeSymbol> serializableTypes,
ImmutableArray<INamedTypeSymbol> embeddedSerializableTypes, ImmutableArray<INamedTypeSymbol> embeddedSerializableTypes,
ISymbol? parentSymbol, ISymbol? parentSymbol,
IMethodSymbol? serializablePropertyFlagGetter SerializableFieldSaveFlagMethods? serializableFieldSaveFlagMethods
) )
{ {
string propertyName; string propertyName;
@ -86,7 +86,7 @@ namespace SerializableMigration
serializableTypes, serializableTypes,
embeddedSerializableTypes, embeddedSerializableTypes,
parentSymbol, parentSymbol,
serializablePropertyFlagGetter serializableFieldSaveFlagMethods
); );
} }
@ -99,7 +99,7 @@ namespace SerializableMigration
ImmutableArray<INamedTypeSymbol> serializableTypes, ImmutableArray<INamedTypeSymbol> serializableTypes,
ImmutableArray<INamedTypeSymbol> embeddedSerializableTypes, ImmutableArray<INamedTypeSymbol> embeddedSerializableTypes,
ISymbol? parentSymbol, ISymbol? parentSymbol,
IMethodSymbol? serializablePropertyFlagGetter SerializableFieldSaveFlagMethods? serializableFieldSaveFlagMethods
) )
{ {
foreach (var rule in Rules.Values) foreach (var rule in Rules.Values)
@ -119,7 +119,7 @@ namespace SerializableMigration
Name = propertyName, Name = propertyName,
Type = propertyType.ToDisplayString(), Type = propertyType.ToDisplayString(),
Order = order, Order = order,
UsesSaveFlag = serializablePropertyFlagGetter != null ? true : null, UsesSaveFlag = serializableFieldSaveFlagMethods?.DetermineFieldShouldSerialize != null ? true : null,
Rule = rule.RuleName, Rule = rule.RuleName,
RuleArguments = ruleArguments.Length > 0 ? ruleArguments : null RuleArguments = ruleArguments.Length > 0 ? ruleArguments : null
}; };

View file

@ -54,5 +54,9 @@ namespace SerializationGenerator
compilation.GetTypeByMetadataName(HASHSET_CLASS), compilation.GetTypeByMetadataName(HASHSET_CLASS),
SymbolEqualityComparer.Default SymbolEqualityComparer.Default
) == true; ) == true;
public static bool IsPrimitiveFromTypeDisplayString(string type) =>
type is "bool" or "sbyte" or "short" or "int" or "long" or "byte" or "ushort"
or "uint" or "ulong" or "float" or "double" or "string" or "decimal";
} }
} }

View file

@ -45,6 +45,7 @@ namespace SerializationGenerator
public const string TIMER_DRIFT_ATTRIBUTE = "Server.TimerDriftAttribute"; public const string TIMER_DRIFT_ATTRIBUTE = "Server.TimerDriftAttribute";
public const string DESERIALIZE_TIMER_FIELD_ATTRIBUTE = "Server.DeserializeTimerFieldAttribute"; public const string DESERIALIZE_TIMER_FIELD_ATTRIBUTE = "Server.DeserializeTimerFieldAttribute";
public const string SERIALIZABLE_FIELD_SAVE_FLAG_ATTRIBUTE = "Server.SerializableFieldSaveFlagAttribute"; public const string SERIALIZABLE_FIELD_SAVE_FLAG_ATTRIBUTE = "Server.SerializableFieldSaveFlagAttribute";
public const string SERIALIZABLE_FIELD_DEFAULT_ATTRIBUTE = "Server.SerializableFieldDefaultAttribute";
public const string RAW_SERIALIZABLE_INTERFACE = "Server.IRawSerializable"; public const string RAW_SERIALIZABLE_INTERFACE = "Server.IRawSerializable";
public static bool IsTimerDrift(this AttributeData attr, Compilation compilation) => public static bool IsTimerDrift(this AttributeData attr, Compilation compilation) =>

View file

@ -2,7 +2,7 @@
* ModernUO * * ModernUO *
* Copyright 2019-2021 - ModernUO Development Team * * Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: AfterDeserialization.cs * * File: AfterDeserializationAttribute.cs *
* * * *
* This program is free software: you can redistribute it and/or modify * * This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by * * it under the terms of the GNU General Public License as published by *
@ -24,5 +24,15 @@ namespace Server
[AttributeUsage(AttributeTargets.Method)] [AttributeUsage(AttributeTargets.Method)]
public class AfterDeserializationAttribute : Attribute public class AfterDeserializationAttribute : Attribute
{ {
/// <summary>
/// Indicates whether the source generator should execute the method this is attached to immediately, or when
/// this is set to false, execute it using a Timer Delay.
///
/// Note: Use false when the after deserialization involves deleting objects. This is to prevent corrupted
/// deserialization by removing an object before it has finished deserializing.
/// </summary>
public bool Synchronous { get; set; }
public AfterDeserializationAttribute(bool synchronous = true) => Synchronous = true;
} }
} }

View file

@ -2,7 +2,7 @@
* ModernUO * * ModernUO *
* Copyright 2019-2021 - ModernUO Development Team * * Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: DeserializeTimerField.cs * * File: DeserializeTimerFieldAttribute.cs *
* * * *
* This program is free software: you can redistribute it and/or modify * * This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by * * it under the terms of the GNU General Public License as published by *

View file

@ -2,7 +2,7 @@
* ModernUO * * ModernUO *
* Copyright 2019-2021 - ModernUO Development Team * * Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: ManualDirtyChecking.cs * * File: ManualDirtyCheckingAttribute.cs *
* * * *
* This program is free software: you can redistribute it and/or modify * * This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by * * it under the terms of the GNU General Public License as published by *

View file

@ -0,0 +1,35 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableFieldDefaultAttribute.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
namespace Server
{
/// <summary>
/// Hints to the source generator that the field with the same order should use this default value
/// while deserializing. The default is used when the save flag indicates that we don't need to serialize the value
/// because this default can be used instead.
///
/// Note: This is only used for the current version, not previous versions. Previous versions will always use a default
/// value for that type if it is not deserialized.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SerializableFieldDefaultAttribute : Attribute
{
public int Order { get; }
public SerializableFieldDefaultAttribute(int order) => Order = order;
}
}

View file

@ -58,6 +58,9 @@
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="Migrations/*.v*.json" /> <AdditionalFiles Include="Migrations/*.v*.json" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Remove="Serialization\Attributes\SerializableFieldSaveValueDefaultAttribute.cs" />
</ItemGroup>
<PropertyGroup Condition="'$(RiderVersion)' != '' AND $([MSBuild]::VersionLessThan($(RiderVersion), '2021.2.0'))"> <PropertyGroup Condition="'$(RiderVersion)' != '' AND $([MSBuild]::VersionLessThan($(RiderVersion), '2021.2.0'))">
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath> <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>

View file

@ -113,7 +113,7 @@ namespace Server.Engines.BulkOrders
} }
} }
[AfterDeserialization] [AfterDeserialization(false)]
private void AfterDeserialization() private void AfterDeserialization()
{ {
if (Parent == null && Map == Map.Internal && Location == Point3D.Zero) if (Parent == null && Map == Map.Internal && Location == Point3D.Zero)

View file

@ -20,6 +20,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(0)] [SerializableFieldSaveFlag(0)]
private bool ShouldSerializeAosAttributes() => !_attributes.IsEmpty; private bool ShouldSerializeAosAttributes() => !_attributes.IsEmpty;
[SerializableFieldDefault(0)]
private AosAttributes AttributesDefaultValue() => new(this);
[SerializableField(1, setter: "private")] [SerializableField(1, setter: "private")]
[SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster, canModify: true)]")] [SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster, canModify: true)]")]
private AosArmorAttributes _armorAttributes; private AosArmorAttributes _armorAttributes;
@ -27,6 +30,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(1)] [SerializableFieldSaveFlag(1)]
private bool ShouldSerializeArmorAttributes() => !_armorAttributes.IsEmpty; private bool ShouldSerializeArmorAttributes() => !_armorAttributes.IsEmpty;
[SerializableFieldDefault(1)]
private AosArmorAttributes ArmorAttributesDefaultValue() => new(this);
[InvalidateProperties] [InvalidateProperties]
[SerializableField(2)] [SerializableField(2)]
[SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")] [SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")]
@ -135,6 +141,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(23)] [SerializableFieldSaveFlag(23)]
private bool ShouldSerializeSkillBonuses() => !_skillBonuses.IsEmpty; private bool ShouldSerializeSkillBonuses() => !_skillBonuses.IsEmpty;
[SerializableFieldDefault(23)]
private AosSkillBonuses SkillBonusesDefaultValue() => new(this);
[SerializableField(24)] [SerializableField(24)]
[SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")] [SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")]
public bool _playerConstructed; public bool _playerConstructed;
@ -269,6 +278,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(14)] [SerializableFieldSaveFlag(14)]
private bool ShouldSerializeResource() => _resource != DefaultResource; private bool ShouldSerializeResource() => _resource != DefaultResource;
[SerializableFieldDefault(14)]
private CraftResource ResourceDefaultValue() => DefaultResource;
[SerializableField(15)] [SerializableField(15)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int BaseArmorRating public int BaseArmorRating
@ -285,6 +297,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(15)] [SerializableFieldSaveFlag(15)]
private bool ShouldSerializeArmorBase() => _armorBase != -1; private bool ShouldSerializeArmorBase() => _armorBase != -1;
[SerializableFieldDefault(15)]
private int ArmorBaseDefaultValue() => -1;
public double BaseArmorRatingScaled => BaseArmorRating * ArmorScalar; public double BaseArmorRatingScaled => BaseArmorRating * ArmorScalar;
public virtual double ArmorRating public virtual double ArmorRating
@ -358,6 +373,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(16)] [SerializableFieldSaveFlag(16)]
private bool ShouldSerializeStrBonus() => _strBonus != -1; private bool ShouldSerializeStrBonus() => _strBonus != -1;
[SerializableFieldDefault(16)]
private int StrBonusDefaultValue() => -1;
[SerializableField(17)] [SerializableField(17)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int DexBonus public int DexBonus
@ -374,6 +392,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(17)] [SerializableFieldSaveFlag(17)]
private bool ShouldSerializeDexBonus() => _dexBonus != -1; private bool ShouldSerializeDexBonus() => _dexBonus != -1;
[SerializableFieldDefault(17)]
private int DexBonusDefaultValue() => -1;
[SerializableField(18)] [SerializableField(18)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int IntBonus public int IntBonus
@ -390,6 +411,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(18)] [SerializableFieldSaveFlag(18)]
private bool ShouldSerializeIntBonus() => _intBonus != -1; private bool ShouldSerializeIntBonus() => _intBonus != -1;
[SerializableFieldDefault(18)]
private int IntBonusDefaultValue() => -1;
[SerializableField(19)] [SerializableField(19)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int StrRequirement public int StrRequirement
@ -406,6 +430,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(19)] [SerializableFieldSaveFlag(19)]
private bool ShouldSerializeStrReq() => _strReq != -1; private bool ShouldSerializeStrReq() => _strReq != -1;
[SerializableFieldDefault(19)]
private int StrReqDefaultValue() => -1;
[SerializableField(20)] [SerializableField(20)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int DexRequirement public int DexRequirement
@ -422,6 +449,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(20)] [SerializableFieldSaveFlag(20)]
private bool ShouldSerializeDexReq() => _dexReq != -1; private bool ShouldSerializeDexReq() => _dexReq != -1;
[SerializableFieldDefault(20)]
private int DexReqDefaultValue() => -1;
[SerializableField(21)] [SerializableField(21)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public int IntRequirement public int IntRequirement
@ -438,6 +468,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(21)] [SerializableFieldSaveFlag(21)]
private bool ShouldSerializeIntReq() => _intReq != -1; private bool ShouldSerializeIntReq() => _intReq != -1;
[SerializableFieldDefault(21)]
private int IntReqDefaultValue() => -1;
[SerializableField(22)] [SerializableField(22)]
[CommandProperty(AccessLevel.GameMaster)] [CommandProperty(AccessLevel.GameMaster)]
public AMA MeditationAllowance public AMA MeditationAllowance
@ -1044,10 +1077,6 @@ namespace Server.Items
[AfterDeserialization] [AfterDeserialization]
private void AfterDeserialization() private void AfterDeserialization()
{ {
Attributes ??= new AosAttributes(this);
ArmorAttributes ??= new AosArmorAttributes(this);
SkillBonuses ??= new AosSkillBonuses(this);
var m = Parent as Mobile; var m = Parent as Mobile;
if (Core.AOS && m != null) if (Core.AOS && m != null)

View file

@ -37,11 +37,8 @@ namespace Server.Items
[SerializableFieldSaveFlag(0)] [SerializableFieldSaveFlag(0)]
private bool ShouldSerializeWeaponAttributes() => !_weaponAttributes.IsEmpty; private bool ShouldSerializeWeaponAttributes() => !_weaponAttributes.IsEmpty;
[AfterDeserialization] [SerializableFieldDefault(0)]
private void AfterDeserialization() private AosWeaponAttributes WeaponAttributesDefaultValue() => new(this);
{
_weaponAttributes ??= new AosWeaponAttributes(this);
}
public override void AppendChildNameProperties(ObjectPropertyList list) public override void AppendChildNameProperties(ObjectPropertyList list)
{ {

View file

@ -23,6 +23,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(1)] [SerializableFieldSaveFlag(1)]
private bool ShouldSerializeTitle() => _title != DefaultContent?.Title; private bool ShouldSerializeTitle() => _title != DefaultContent?.Title;
[SerializableFieldDefault(1)]
private string TitleDefaultValue() => DefaultContent?.Title;
[InvalidateProperties] [InvalidateProperties]
[SerializableField(2)] [SerializableField(2)]
[SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")] [SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")]
@ -31,6 +34,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(2)] [SerializableFieldSaveFlag(2)]
private bool ShouldSerializeAuthor() => _author != DefaultContent?.Author; private bool ShouldSerializeAuthor() => _author != DefaultContent?.Author;
[SerializableFieldDefault(2)]
private string AuthorDefaultValue() => DefaultContent?.Author;
[SerializableField(3)] [SerializableField(3)]
[SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")] [SerializableFieldAttr("[CommandProperty(AccessLevel.GameMaster)]")]
private bool _writable; private bool _writable;
@ -44,6 +50,9 @@ namespace Server.Items
[SerializableFieldSaveFlag(4)] [SerializableFieldSaveFlag(4)]
private bool ShouldSerializePages() => DefaultContent?.IsMatch(_pages) != true; private bool ShouldSerializePages() => DefaultContent?.IsMatch(_pages) != true;
[SerializableFieldDefault(4)]
private BookPageInfo[] PagesDefaultvalue() => DefaultContent?.Copy() ?? Array.Empty<BookPageInfo>();
[Constructible] [Constructible]
public BaseBook(int itemID, int pageCount = 20, bool writable = true) : this(itemID, null, null, pageCount, writable) public BaseBook(int itemID, int pageCount = 20, bool writable = true) : this(itemID, null, null, pageCount, writable)
{ {
@ -122,18 +131,6 @@ namespace Server.Items
SetSecureLevelEntry.AddTo(from, this, list); SetSecureLevelEntry.AddTo(from, this, list);
} }
[AfterDeserialization]
private void AfterDeserialization()
{
var content = DefaultContent;
if (content != null)
{
_title ??= content.Title;
_author ??= content.Author;
}
}
private void Deserialize(IGenericReader reader, int version) private void Deserialize(IGenericReader reader, int version)
{ {
Level = (SecureLevel)reader.ReadInt(); Level = (SecureLevel)reader.ReadInt();

View file

@ -172,7 +172,7 @@ namespace Server.Items
base.PlaySwingAnimation( attacker ); base.PlaySwingAnimation( attacker );
}*/ }*/
[AfterDeserialization] [AfterDeserialization(false)]
private void OnAfterDeserialization() private void OnAfterDeserialization()
{ {
Delete(); Delete();