/// <inheritdoc />
        public override Stream Map(AssetLoaderContext assetLoaderContext, string originalFilename, out string finalPath)
        {
            if (!string.IsNullOrEmpty(originalFilename))
            {
                if (assetLoaderContext.CustomData is IEnumerable <ItemWithStream> itemsWithStream)
                {
                    var shortFileName = FileUtils.GetShortFilename(originalFilename).ToLowerInvariant();
                    foreach (var itemWithStream in itemsWithStream)
                    {
                        if (!itemWithStream.HasData)
                        {
                            continue;
                        }

                        var checkingFileShortName = FileUtils.GetShortFilename(itemWithStream.Name).ToLowerInvariant();
                        if (shortFileName == checkingFileShortName)
                        {
                            finalPath = itemWithStream.Name;
                            return(itemWithStream.OpenStream());
                        }
                    }
                }
                else
                {
                    throw new Exception("Missing custom context data.");
                }
            }
            finalPath = null;
            return(null);
        }
Example #2
0
        public Stylesheet Load(AssetLoaderContext context, string assetName)
        {
            var xml = context.Load <string>(assetName);

            var xDoc = XDocument.Parse(xml);
            var attr = xDoc.Root.Attribute("TextureRegionAtlas");

            if (attr == null)
            {
                throw new Exception("Mandatory attribute 'TextureRegionAtlas' doesnt exist");
            }

            var textureRegionAtlas = context.Load <TextureRegionAtlas>(attr.Value);

            // Load fonts
            var fonts     = new Dictionary <string, SpriteFont>();
            var fontsNode = xDoc.Root.Element("Fonts");

            foreach (var el in fontsNode.Elements())
            {
                var font = el.Attribute("File").Value;
                fonts[el.Attribute(BaseContext.IdName).Value] = context.Load <SpriteFont>(font);
            }

            return(Stylesheet.LoadFromSource(xml,
                                             name => textureRegionAtlas[name],
                                             name => fonts[name]));
        }
 /// <summary>
 /// Event triggered when the model and all the resources have been fully loaded.
 /// </summary>
 /// <param name="assetLoaderContext"></param>
 private void OnModelFullyLoad(AssetLoaderContext assetLoaderContext)
 {
     if (assetLoaderContext.RootGameObject != null)
     {
         Debug.Log("Model successfully loaded.");
     }
 }
        /// <inheritdoc />
        public override AnimationClip[] MapArray(AssetLoaderContext assetLoaderContext, AnimationClip[] sourceAnimationClips)
        {
            if (AnimatorOverrideController != null)
            {
                for (var i = 0; i < sourceAnimationClips.Length; i++)
                {
                    var animationClip = sourceAnimationClips[i];
                    var overrides     = new List <KeyValuePair <AnimationClip, AnimationClip> >(AnimatorOverrideController.overridesCount);
                    AnimatorOverrideController.GetOverrides(overrides);
                    for (var j = 0; j < overrides.Count; j++)
                    {
                        var kvp      = overrides[j];
                        var keyName  = kvp.Key.name;
                        var clipName = animationClip.name;
                        if (StringComparer.Matches(StringComparisonMode, CaseInsensitive, keyName, clipName))
                        {
                            overrides[j] = new KeyValuePair <AnimationClip, AnimationClip>(kvp.Key, animationClip);
                        }
                    }

                    AnimatorOverrideController.ApplyOverrides(overrides);
                }
            }
            return(base.MapArray(assetLoaderContext, sourceAnimationClips));
        }
Example #5
0
    // This event is called when all model GameObjects and Meshes have been loaded.
    // There may still Materials and Textures processing at this stage.
    private void OnLoad(AssetLoaderContext assetLoaderContext)
    {
        Transform triLibWrapper = assetLoaderContext.RootGameObject.transform;
        Transform triLibObj     = triLibWrapper.GetChild(0);

        triLibWrapper.name          = $"Wraper_{triLibObj.name}";
        triLibWrapper.localPosition = Vector3.zero;

        // switch trilibWrapper & triLibObj in hierarchy to fit with objects requirements
        triLibObj.parent     = triLibWrapper.parent;
        triLibWrapper.parent = triLibObj;
        triLibObj.SetAsFirstSibling();
        triLibObj.localPosition     = Vector3.zero;
        triLibWrapper.localPosition = Vector3.zero;

        triLibObj.gameObject.AddComponent <BoxCollider>();
        triLibObj.tag = "Selectable";

#if PROD
        // Hide template object
        triLibObj.GetComponent <Renderer>().enabled = false;
        triLibObj.GetComponent <Collider>().enabled = false;
#endif
        // Destroy(triLibWrapper.GetChild(1).gameObject);
    }
 public override void OnProcessUserData(AssetLoaderContext assetLoaderContext, GameObject gameObject, string propertyName, object propertyValue)
 {
     if (OnUserDataProcessed != null)
     {
         OnUserDataProcessed(gameObject, propertyName, propertyValue);
     }
 }
        /// <inheritdoc/>
        public override AnimationClip[] MapArray(AssetLoaderContext assetLoaderContext, AnimationClip[] sourceAnimationClips)
        {
            var animator = assetLoaderContext.RootGameObject.GetComponent <Animator>();

            if (animator != null && animator.avatar != null && animator.avatar.isHuman)
            {
                animator.enabled = false;
                if (MecanimAnimationClipTemplate == null)
                {
                    if (assetLoaderContext.Options.ShowLoadingWarnings)
                    {
                        Debug.LogWarning("No MecanimAnimationClipTemplate specified when using the LegacyToHumanoidAnimationClipMapper.");
                    }
                    MecanimAnimationClipTemplate = new AnimationClip();
                    assetLoaderContext.Allocations.Add(MecanimAnimationClipTemplate);
                }
                for (var i = 0; i < sourceAnimationClips.Length; i++)
                {
                    var animationClip = HumanoidRetargeter.ConvertLegacyIntoHumanoidAnimationClip(assetLoaderContext.RootGameObject, animator.avatar, sourceAnimationClips[i], MecanimAnimationClipTemplate);
                    if (animationClip != null)
                    {
                        sourceAnimationClips[i] = animationClip;
                    }
                }
                animator.enabled = true;
            }
            return(sourceAnimationClips);
        }
Example #8
0
 /// <inheritdoc />
 public override TextureLoadingContext Map(AssetLoaderContext assetLoaderContext, ITexture texture)
 {
     if (string.IsNullOrEmpty(texture.Filename))
     {
         return(null);
     }
     if (assetLoaderContext.CustomData is IEnumerable <ItemWithStream> itemsWithStream)
     {
         var shortFileName = FileUtils.GetShortFilename(texture.Filename).ToLowerInvariant();
         foreach (var itemWithStream in itemsWithStream)
         {
             if (!itemWithStream.HasData)
             {
                 continue;
             }
             var checkingFileShortName = FileUtils.GetShortFilename(itemWithStream.Name).ToLowerInvariant();
             if (shortFileName == checkingFileShortName)
             {
                 var textureLoadingContext = new TextureLoadingContext
                 {
                     Context = assetLoaderContext,
                     Stream  = itemWithStream.OpenStream(),
                     Texture = texture
                 };
                 return(textureLoadingContext);
             }
         }
     }
     else
     {
         throw new Exception("Missing custom context data.");
     }
     return(null);
 }
        /// <inheritdoc />
        public override Stream Map(AssetLoaderContext assetLoaderContext, string originalFilename, out string finalPath)
        {
            if (!(assetLoaderContext.CustomData is ZipLoadCustomContextData zipLoadCustomContextData))
            {
                throw new Exception("Missing custom context data.");
            }
            var zipFile = zipLoadCustomContextData.ZipFile;

            if (zipFile == null)
            {
                throw new Exception("Zip file instance is null.");
            }
            var shortFileName = FileUtils.GetShortFilename(originalFilename).ToLowerInvariant();

            foreach (ZipEntry zipEntry in zipFile)
            {
                if (!zipEntry.IsFile)
                {
                    continue;
                }
                var checkingFileShortName = FileUtils.GetShortFilename(zipEntry.Name).ToLowerInvariant();
                if (shortFileName == checkingFileShortName)
                {
                    finalPath = zipFile.Name;
                    string _;
                    return(AssetLoaderZip.ZipFileEntryToStream(out _, zipEntry, zipFile));
                }
            }
            finalPath = null;
            return(null);
        }
Example #10
0
 /// <summary>
 /// Tries to find the given external data source using the original resource filename and the context parameters.
 /// </summary>
 /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
 /// <param name="originalFilename">The source data original filename.</param>
 /// <param name="finalPath">The found data final Path.</param>
 /// <returns>The external data source Stream, if found. Otherwise <c>null</c>.</returns>
 public override Stream Map(AssetLoaderContext assetLoaderContext, string originalFilename, out string finalPath)
 {
     finalPath = $"{assetLoaderContext.BasePath}/{FileUtils.GetFilename(originalFilename)}";
     if (File.Exists(finalPath))
     {
         Debug.Log($"Found external file at: {finalPath}");
         return(File.OpenRead(finalPath));
     }
     throw new Exception($"File {originalFilename} not found.");
 }
Example #11
0
        /// <summary>
        /// Called when all model resources have been loaded.
        /// </summary>
        /// <param name="assetLoaderContext">The asset loading context, containing callbacks and model loading data.</param>
        private static void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
        {
            var zipLoadCustomContextData = assetLoaderContext.CustomData as ZipLoadCustomContextData;

            if (zipLoadCustomContextData != null)
            {
                zipLoadCustomContextData.Stream.Close();
                zipLoadCustomContextData.OnMaterialsLoad(assetLoaderContext);
            }
        }
 ///<inheritdoc />
 public override AnimationClip[] MapArray(AssetLoaderContext assetLoaderContext, AnimationClip[] sourceAnimationClips)
 {
     if ((assetLoaderContext.Options.AnimationType == AnimationType.Generic || assetLoaderContext.Options.AnimationType == AnimationType.Humanoid) && sourceAnimationClips.Length > 0)
     {
         var simpleAnimationPlayer = assetLoaderContext.RootGameObject.AddComponent <SimpleAnimationPlayer>();
         simpleAnimationPlayer.AnimationClips = sourceAnimationClips;
         simpleAnimationPlayer.enabled        = false;
     }
     return(sourceAnimationClips);
 }
Example #13
0
        public IBrush Load(AssetLoaderContext context, string assetName)
        {
            var color = ColorStorage.FromName(assetName);

            if (color == null)
            {
                throw new Exception(string.Format("Unable to resolve color '{0}'", assetName));
            }

            return(new SolidBrush(color.Value));
        }
        public override TextureLoadingContext Map(AssetLoaderContext assetLoaderContext, ITexture texture)
        {
            var stream = _streamReceivingCallback(texture);

            return(new TextureLoadingContext
            {
                Context = assetLoaderContext,
                Stream = stream,
                Texture = texture
            });
        }
Example #15
0
        public Stylesheet Load(AssetLoaderContext context, string assetName)
        {
            var xml = context.Load <string>(assetName);

            var xDoc = XDocument.Parse(xml);
            var attr = xDoc.Root.Attribute("TextureRegionAtlas");

            if (attr == null)
            {
                throw new Exception("Mandatory attribute 'TextureRegionAtlas' doesnt exist");
            }

            var textureRegionAtlas = context.Load <TextureRegionAtlas>(attr.Value);

            // Load fonts
            var fonts     = new Dictionary <string, SpriteFontBase>();
            var fontsNode = xDoc.Root.Element("Fonts");

            foreach (var el in fontsNode.Elements())
            {
                SpriteFontBase font = null;

                var fontFile = el.Attribute("File").Value;
                if (fontFile.EndsWith(".ttf"))
                {
                    var parts = new List <string>();
                    parts.Add(fontFile);

                    var typeAttribute = el.Attribute("Type");
                    if (typeAttribute != null)
                    {
                        parts.Add(typeAttribute.Value);

                        var amountAttribute = el.Attribute("Amount");
                        parts.Add(amountAttribute.Value);
                    }

                    parts.Add(el.Attribute("Size").Value);
                    font = context.Load <DynamicSpriteFont>(string.Join(":", parts));
                }
                else if (fontFile.EndsWith(".fnt"))
                {
                    font = context.Load <StaticSpriteFont>(fontFile);
                }
                else
                {
                    throw new Exception(string.Format("Font '{0}' isn't supported", fontFile));
                }

                fonts[el.Attribute(BaseContext.IdName).Value] = font;
            }

            return(Stylesheet.LoadFromSource(xml, textureRegionAtlas, fonts));
        }
        /// <summary>Downloads the Model using the given Request and options.</summary>
        /// <param name="unityWebRequest">The Unity Web Request used to load the Model. You can use the CreateWebRequest method to create a new Unity Web Request or pass your instance.</param>
        /// <param name="onLoad">The Method to call on the Main Thread when the Model is loaded but resources may still pending.</param>
        /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model and resources are loaded.</param>
        /// <param name="onProgress">The Method to call when the Model loading progress changes.</param>
        /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
        /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
        /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
        /// <param name="customContextData">The Custom Data that will be passed along the Context.</param>
        /// <param name="fileExtension">The extension of the URI Model.</param>
        /// <param name="isZipFile">Pass <c>true</c> if your file is a Zip file.</param>
        /// <returns>The download coroutine enumerator.</returns>
        public IEnumerator DownloadAsset(UnityWebRequest unityWebRequest, Action <AssetLoaderContext> onLoad, Action <AssetLoaderContext> onMaterialsLoad, Action <AssetLoaderContext, float> onProgress, GameObject wrapperGameObject, Action <IContextualizedError> onError, AssetLoaderOptions assetLoaderOptions, object customContextData, string fileExtension, bool?isZipFile = null)
        {
            _unityWebRequest = unityWebRequest;
            _onProgress      = onProgress;
            yield return(unityWebRequest.SendWebRequest());

            try
            {
                if (unityWebRequest.responseCode < 400)
                {
                    var memoryStream             = new MemoryStream(_unityWebRequest.downloadHandler.data);
                    var uriLoadCustomContextData = new UriLoadCustomContextData
                    {
                        UnityWebRequest = _unityWebRequest,
                        CustomData      = customContextData
                    };
                    var contentType = unityWebRequest.GetResponseHeader("Content-Type");
                    if (contentType != null && isZipFile == null)
                    {
                        isZipFile = contentType.Contains("application/zip") || contentType.Contains("application/x-zip-compressed") || contentType.Contains("multipart/x-zip");
                    }
                    if (!isZipFile.GetValueOrDefault() && string.IsNullOrWhiteSpace(fileExtension))
                    {
                        fileExtension = FileUtils.GetFileExtension(unityWebRequest.url);
                    }
                    if (isZipFile.GetValueOrDefault())
                    {
                        _assetLoaderContext = AssetLoaderZip.LoadModelFromZipStream(memoryStream, onLoad, onMaterialsLoad, delegate(AssetLoaderContext assetLoaderContext, float progress) { onProgress?.Invoke(assetLoaderContext, 0.5f + progress * 0.5f); }, onError, wrapperGameObject, assetLoaderOptions, uriLoadCustomContextData, fileExtension);
                    }
                    else
                    {
                        _assetLoaderContext = AssetLoader.LoadModelFromStream(memoryStream, null, fileExtension, onLoad, onMaterialsLoad, delegate(AssetLoaderContext assetLoaderContext, float progress) { onProgress?.Invoke(assetLoaderContext, 0.5f + progress * 0.5f); }, onError, wrapperGameObject, assetLoaderOptions, uriLoadCustomContextData);
                    }
                }
                else
                {
                    var exception = new Exception($"UnityWebRequest error:{unityWebRequest.error}, code:{unityWebRequest.responseCode}");
                    throw exception;
                }
            }
            catch (Exception exception)
            {
                if (onError != null)
                {
                    var contextualizedError = exception as IContextualizedError;
                    onError(contextualizedError ?? new ContextualizedError <AssetLoaderContext>(exception, null));
                }
                else
                {
                    throw;
                }
            }
            Destroy(gameObject);
        }
Example #17
0
 /// <summary>
 /// Called when the Model Meshes and hierarchy are loaded.
 /// </summary>
 /// <remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks>
 /// <param name="assetLoaderContext">The context used to load the Model.</param>
 private void OnLoad(AssetLoaderContext assetLoaderContext)
 {
     if (_loadedGameObject != null)
     {
         Destroy(_loadedGameObject);
     }
     _loadedGameObject = assetLoaderContext.RootGameObject;
     if (_loadedGameObject != null)
     {
         Camera.main.FitToBounds(assetLoaderContext.RootGameObject, 2f);
     }
 }
Example #18
0
 /// <summary>Event triggered when the Model Meshes and hierarchy are loaded.</summary>
 /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
 protected override void OnLoad(AssetLoaderContext assetLoaderContext)
 {
     if (assetLoaderContext.RootGameObject != null)
     {
         var zipLoadCustomContextData = (ZipLoadCustomContextData)assetLoaderContext.CustomData;
         var uriLoadCustomContextData = (UriLoadCustomContextData)zipLoadCustomContextData.CustomData;
         var partIndex = (int)uriLoadCustomContextData.CustomData;
         var rotation  = Quaternion.Euler(0f, partIndex * 90f, 0f);
         assetLoaderContext.RootGameObject.transform.SetPositionAndRotation(rotation * new Vector3(0f, 0f, Distance), rotation);
     }
     base.OnLoad(assetLoaderContext);
 }
Example #19
0
 /// <summary>
 /// Called when the Model (including Textures and Materials) has been fully loaded, or after any error occurs.
 /// </summary>
 /// <remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks>
 /// <param name="assetLoaderContext">The context used to load the Model.</param>
 private void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
 {
     if (assetLoaderContext.RootGameObject != null)
     {
         Debug.Log("Model fully loaded.");
     }
     else
     {
         Debug.Log("Model could not be loaded.");
     }
     _loadModelButton.interactable = true;
     _progressText.enabled         = false;
 }
Example #20
0
 /// <summary>Event triggered when the Model and all its resources loaded.</summary>
 /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
 protected override void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
 {
     if (assetLoaderContext.RootGameObject != null)
     {
         var zipLoadCustomContextData = (ZipLoadCustomContextData)assetLoaderContext.CustomData;
         var uriLoadCustomContextData = (UriLoadCustomContextData)zipLoadCustomContextData.CustomData;
         var downloaded = Instantiate <GameObject>(_downloadTemplate, _downloadTemplate.transform.parent);
         var text       = downloaded.GetComponentInChildren <Text>();
         text.text = $"Done: {uriLoadCustomContextData.UnityWebRequest.uri.Segments[uriLoadCustomContextData.UnityWebRequest.uri.Segments.Length - 1]}";
         downloaded.SetActive(true);
     }
     base.OnMaterialsLoad(assetLoaderContext);
 }
Example #21
0
        public UserProfile Load(AssetLoaderContext context, string assetName)
        {
            var data = context.Load <string>(assetName);

            var xDoc = XDocument.Parse(data);

            var result = new UserProfile
            {
                Name  = xDoc.Root.Element("Name").Value,
                Score = int.Parse(xDoc.Root.Element("Score").Value)
            };

            return(result);
        }
        ///<inheritdoc />
        public override AnimationClip[] MapArray(AssetLoaderContext assetLoaderContext, AnimationClip[] sourceAnimationClips)
        {
            var animator = assetLoaderContext.RootGameObject.GetComponent <Animator>();

            if (animator == null || AnimatorOverrideController == null)
            {
                if (assetLoaderContext.Options.ShowLoadingWarnings)
                {
                    Debug.LogWarning("Tried to execute an AnimatorOverrideController Mapper on a GameObject without an Animator or without setting an AnimatorOverrideController.");
                }
                return(sourceAnimationClips);
            }
            animator.runtimeAnimatorController = AnimatorOverrideController;
            return(sourceAnimationClips);
        }
 /// <inheritdoc />
 public override Transform Map(AssetLoaderContext assetLoaderContext)
 {
     if (RootBoneNames != null)
     {
         for (var i = 0; i < RootBoneNames.Length; i++)
         {
             var rootBoneName = RootBoneNames[i];
             var found        = FindDeepChild(assetLoaderContext.RootGameObject.transform, rootBoneName);
             if (found != null)
             {
                 return(found);
             }
         }
     }
     return(base.Map(assetLoaderContext));
 }
        void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
        {
            loadSucInfos[loadIndex]         = new LoadSucInfo();
            loadSucInfos[loadIndex].loadObj = assetLoaderContext.RootGameObject;

            loadIndex++;

            if (loadIndex <= loadFiles.Length - 1)
            {
                StartLoadModel(loadFiles[loadIndex]);
            }
            else
            {
                OnLoadFinish();
            }
        }
 /// <inheritdoc />
 public override Transform Map(AssetLoaderContext assetLoaderContext, IList <Transform> bones)
 {
     if (RootBoneNames != null)
     {
         for (var i = 0; i < RootBoneNames.Length; i++)
         {
             var rootBoneName = RootBoneNames[i];
             var found        = FindDeepChild(bones, rootBoneName);
             if (found != null)
             {
                 return(found);
             }
         }
     }
     return(base.Map(assetLoaderContext, bones));
 }
Example #26
0
        public TextureRegion Load(AssetLoaderContext context, string assetName)
        {
            if (assetName.Contains(":"))
            {
                // First part is texture region atlas name
                // Second part is texture region name
                var parts = assetName.Split(':');
                var textureRegionAtlas = context.Load <TextureRegionAtlas>(parts[0]);
                return(textureRegionAtlas[parts[1]]);
            }

            // Ordinary texture
            var texture = context.Load <Texture2D>(assetName);

            return(new TextureRegion(texture));
        }
        /// <inheritdoc />
        public override Transform Map(AssetLoaderContext assetLoaderContext, IList <Transform> bones)
        {
            Transform bestBone          = null;
            var       bestChildrenCount = 0;

            for (var i = 0; i < bones.Count; i++)
            {
                var bone          = bones[i];
                var childrenCount = bone.CountChild();
                if (childrenCount >= bestChildrenCount)
                {
                    bestChildrenCount = childrenCount;
                    bestBone          = bone;
                }
            }
            return(bestBone);
        }
Example #28
0
        public Stylesheet Load(AssetLoaderContext context, string assetName)
        {
            var xml = context.Load <string>(assetName);

            var xDoc = XDocument.Parse(xml);
            var attr = xDoc.Root.Attribute("TextureRegionAtlas");

            if (attr == null)
            {
                throw new Exception("Mandatory attribute 'TextureRegionAtlas' doesnt exist");
            }

            var textureRegionAtlas = context.Load <TextureRegionAtlas>(attr.Value);

            // Load fonts
            var fonts     = new Dictionary <string, SpriteFont>();
            var fontsNode = xDoc.Root.Element("Fonts");

            foreach (var el in fontsNode.Elements())
            {
                var font = el.Attribute("File").Value;
                fonts[el.Attribute(BaseContext.IdName).Value] = context.Load <SpriteFont>(font);
            }

            return(Stylesheet.LoadFromSource(xml,
                                             name =>
            {
                TextureRegion region;

                if (!textureRegionAtlas.Regions.TryGetValue(name, out region))
                {
                    var color = ColorStorage.FromName(name);
                    if (color != null)
                    {
                        return new SolidBrush(color.Value);
                    }
                }
                else
                {
                    return region;
                }

                throw new Exception(string.Format("Could not find parse IBrush '{0}'", name));
            },
                                             name => fonts[name]));
        }
Example #29
0
        /// <summary>Tries to retrieve a Stream to the Texture native data based on the given context.</summary>
        /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
        /// <param name="texture">The source Texture to load the Stream from.</param>
        /// <returns>Return the context containing the texture data.</returns>
        public override TextureLoadingContext Map(AssetLoaderContext assetLoaderContext, ITexture texture)
        {
            var finalPath = $"{assetLoaderContext.BasePath}/{FileUtils.GetFilename(texture.Filename)}";

            if (File.Exists(finalPath))
            {
                var textureLoadingContext = new TextureLoadingContext
                {
                    Context = assetLoaderContext,
                    Stream  = File.OpenRead(finalPath),
                    Texture = texture
                };
                Debug.Log($"Found texture at: {finalPath}");
                return(textureLoadingContext);
            }
            throw new Exception($"Texture {texture.Filename} not found.");
        }
Example #30
0
        /// <inheritdoc />
        public override TextureLoadingContext Map(AssetLoaderContext assetLoaderContext, ITexture texture)
        {
            var zipLoadCustomContextData = assetLoaderContext.CustomData as ZipLoadCustomContextData;

            if (zipLoadCustomContextData == null)
            {
                throw new Exception("Missing custom context data.");
            }
            var zipFile = zipLoadCustomContextData.ZipFile;

            if (zipFile == null)
            {
                throw new Exception("Zip file instance is null.");
            }
            if (string.IsNullOrWhiteSpace(texture.Filename))
            {
                if (assetLoaderContext.Options.ShowLoadingWarnings)
                {
                    UnityEngine.Debug.LogWarning("Texture name is null.");
                }
                return(null);
            }
            var shortFileName = FileUtils.GetShortFilename(texture.Filename).ToLowerInvariant();

            foreach (ZipEntry zipEntry in zipFile)
            {
                if (!zipEntry.IsFile)
                {
                    continue;
                }
                var checkingFileShortName = FileUtils.GetShortFilename(zipEntry.Name).ToLowerInvariant();
                if (shortFileName == checkingFileShortName)
                {
                    string _;
                    var    textureLoadingContext = new TextureLoadingContext
                    {
                        Context = assetLoaderContext,
                        Stream  = AssetLoaderZip.ZipFileEntryToStream(out _, zipEntry, zipFile),
                        Texture = texture
                    };
                    return(textureLoadingContext);
                }
            }
            return(null);
        }