Created
March 2, 2019 08:24
-
-
Save dfkeenan/344f8a3250df145f68c71408addd9b22 to your computer and use it in GitHub Desktop.
LazyContent proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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