Skip to content

Instantly share code, notes, and snippets.

@dfkeenan
Created March 2, 2019 08:24
Show Gist options
  • Select an option

  • Save dfkeenan/344f8a3250df145f68c71408addd9b22 to your computer and use it in GitHub Desktop.

Select an option

Save dfkeenan/344f8a3250df145f68c71408addd9b22 to your computer and use it in GitHub Desktop.
LazyContent proof of concept
using System;
using System.Collections.Generic;
using System.Text;
using Xenko.Core;
using Xenko.Core.Annotations;
using Xenko.Core.Serialization;
using Xenko.Core.Serialization.Contents;
namespace MyGame
{
[DataContract("LazyContent")]
[DataSerializer(typeof(LazyContentDataSerializer<>), Mode = DataSerializerGenericMode.GenericArguments)]
public class LazyContent<T> : IContentAware
where T : class
{
private IContentManager contentManager;
private Lazy<T> lazy;
public LazyContent()
{
lazy = CreateLazy();
}
[DataMember]
public UrlReference<T> Url { get; set; }
[DataMemberIgnore]
public T Value => lazy?.Value;
public void Unload()
{
if (!lazy.IsValueCreated) return;
contentManager?.Unload(lazy.Value);
lazy = CreateLazy();
}
[DataMemberIgnore]
IContentManager IContentAware.Content { get => contentManager; set => contentManager = value; }
private Lazy<T> CreateLazy()
{
return new Lazy<T>(LoadContent);
}
private T LoadContent()
{
return contentManager?.Load<T>(Url);
}
}
public interface IContentAware
{
IContentManager Content { get; set; }
}
public class LazyContentDataSerializer<T> : ContentAwareDataSerializerBase<LazyContent<T>>
where T : class
{
public override void Serialize(ref LazyContent<T> obj, ArchiveMode mode, [NotNull] SerializationStream stream)
{
if(mode == ArchiveMode.Deserialize)
{
obj.Url = stream.Read<UrlReference<T>>();
}
else
{
stream.Write(obj.Url);
}
base.Serialize(ref obj, mode, stream);
}
}
public abstract class ContentAwareDataSerializerBase<T> : DataSerializer<T>
{
public override void Serialize(ref T obj, ArchiveMode mode, [NotNull] SerializationStream stream)
{
if (mode == ArchiveMode.Deserialize && obj is IContentAware contentAware)
{
var contentContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);
contentAware.Content = contentContext?.ContentManager;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment