Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve asset cache between loads #345

Merged
merged 3 commits into from
Jan 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 10 additions & 14 deletions UnityGLTF/Assets/UnityGLTF/Examples/SimpleWebServer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// MIT License - Copyright (c) 2016 Can Güney Aksakalli

using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -187,13 +187,14 @@ private void Process(HttpListenerContext context)
}

filename = Path.Combine(_rootDirectory, filename);

if (File.Exists(filename))
{
context.Response.StatusCode = (int)HttpStatusCode.OK;

try
{
Stream input = new FileStream(filename, FileMode.Open);

Stream input = File.OpenRead(filename);
//Adding permanent http response headers
string mime;
context.Response.ContentType = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime)
Expand All @@ -203,26 +204,21 @@ private void Process(HttpListenerContext context)
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));

byte[] buffer = new byte[1024 * 16];
int nbytes;
while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
context.Response.OutputStream.Write(buffer, 0, nbytes);
input.CopyTo(context.Response.OutputStream);
input.Close();

context.Response.StatusCode = (int) HttpStatusCode.OK;
context.Response.OutputStream.Flush();
}
catch (Exception)
catch (Exception e)
{
Debug.LogException(e);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
}

context.Response.OutputStream.Close();
context.Response.Close();
}
#endif

Expand Down
33 changes: 14 additions & 19 deletions UnityGLTF/Assets/UnityGLTF/Scripts/Cache/AssetCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using GLTF.Schema;

namespace UnityGLTF.Cache
{
Expand Down Expand Up @@ -38,7 +39,7 @@ public class AssetCache : IDisposable
/// <summary>
/// Cache of loaded meshes
/// </summary>
public List<MeshCacheData[]> MeshCache { get; private set; }
public MeshCacheData[][] MeshCache { get; private set; }

/// <summary>
/// Cache of loaded animations
Expand All @@ -53,28 +54,22 @@ public class AssetCache : IDisposable
/// <summary>
/// Creates an asset cache which caches objects used in scene
/// </summary>
/// <param name="imageCacheSize"></param>
/// <param name="textureCacheSize"></param>
/// <param name="materialCacheSize"></param>
/// <param name="bufferCacheSize"></param>
/// <param name="meshCacheSize"></param>
/// <param name="nodeCacheSize"></param>
public AssetCache(int imageCacheSize, int textureCacheSize, int materialCacheSize, int bufferCacheSize,
int meshCacheSize, int nodeCacheSize, int animationCacheSize)
/// <param name="root">A glTF root whose assets will eventually be cached here</param>
public AssetCache(GLTFRoot root)
{
ImageCache = new Texture2D[imageCacheSize];
ImageStreamCache = new Stream[imageCacheSize];
TextureCache = new TextureCacheData[textureCacheSize];
MaterialCache = new MaterialCacheData[materialCacheSize];
BufferCache = new BufferCacheData[bufferCacheSize];
MeshCache = new List<MeshCacheData[]>(meshCacheSize);
for (int i = 0; i < meshCacheSize; ++i)
ImageCache = new Texture2D[root.Images?.Count ?? 0];
ImageStreamCache = new Stream[ImageCache.Length];
TextureCache = new TextureCacheData[root.Textures?.Count ?? 0];
MaterialCache = new MaterialCacheData[root.Materials?.Count ?? 0];
BufferCache = new BufferCacheData[root.Buffers?.Count ?? 0];
MeshCache = new MeshCacheData[root.Meshes?.Count ?? 0][];
for (int i = 0; i < MeshCache.Length; ++i)
{
MeshCache.Add(null);
MeshCache[i] = new MeshCacheData[root.Meshes?[i].Primitives.Count ?? 0];
}

NodeCache = new GameObject[nodeCacheSize];
AnimationCache = new AnimationCacheData[animationCacheSize];
NodeCache = new GameObject[root.Nodes?.Count ?? 0];
AnimationCache = new AnimationCacheData[root.Animations?.Count ?? 0];
}

public void Dispose()
Expand Down
13 changes: 5 additions & 8 deletions UnityGLTF/Assets/UnityGLTF/Scripts/Cache/RefCountedCacheData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class RefCountedCacheData
/// <summary>
/// Meshes used by this GLTF node.
/// </summary>
public List<MeshCacheData[]> MeshCache { get; set; }
public MeshCacheData[][] MeshCache { get; set; }

/// <summary>
/// Materials used by this GLTF node.
Expand Down Expand Up @@ -76,16 +76,13 @@ public void DecreaseRefCount()
private void DestroyCachedData()
{
// Destroy the cached meshes
for (int i = 0; i < MeshCache.Count; i++)
for (int i = 0; i < MeshCache.Length; i++)
{
if (MeshCache[i] != null)
for (int j = 0; j < MeshCache[i].Length; j++)
{
for (int j = 0; j < MeshCache[i].Length; j++)
if (MeshCache[i][j] != null)
{
if (MeshCache[i][j] != null)
{
MeshCache[i][j].Unload();
}
MeshCache[i][j].Unload();
}
}
}
Expand Down
38 changes: 30 additions & 8 deletions UnityGLTF/Assets/UnityGLTF/Scripts/GLTFComponent.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
Expand All @@ -22,6 +23,13 @@ public class GLTFComponent : MonoBehaviour
[SerializeField]
private bool loadOnStart = true;

[SerializeField] private bool MaterialsOnly = false;

[SerializeField] private int RetryCount = 10;
[SerializeField] private float RetryTimeout = 2.0f;
private int numRetries = 0;


public int MaximumLod = 300;
public int Timeout = 8;
public GLTFSceneImporter.ColliderType Collider = GLTFSceneImporter.ColliderType.None;
Expand All @@ -33,15 +41,26 @@ public class GLTFComponent : MonoBehaviour

private async void Start()
{
if (loadOnStart)
if (!loadOnStart) return;

try
{
await Load();
}
catch (HttpRequestException)
{
if (numRetries++ >= RetryCount)
throw;

Debug.LogWarning("Load failed, retrying");
await Task.Delay((int)(RetryTimeout * 1000));
Start();
}
}

public async Task Load()
{
asyncCoroutineHelper = gameObject.AddComponent<AsyncCoroutineHelper>();
asyncCoroutineHelper = gameObject.GetComponent<AsyncCoroutineHelper>() ?? gameObject.AddComponent<AsyncCoroutineHelper>();
GLTFSceneImporter sceneImporter = null;
ILoader loader = null;
try
Expand Down Expand Up @@ -80,15 +99,18 @@ public async Task Load()
sceneImporter.Timeout = Timeout;
sceneImporter.isMultithreaded = Multithreaded;
sceneImporter.CustomShaderName = shaderOverride ? shaderOverride.name : null;
try

if (MaterialsOnly)
{
await sceneImporter.LoadSceneAsync();
var mat = await sceneImporter.LoadMaterialAsync(0);
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.SetParent(gameObject.transform);
var renderer = cube.GetComponent<Renderer>();
renderer.sharedMaterial = mat;
}
catch (Exception e)
else
{
Debug.LogError("Exception while loading:");
Debug.LogException(e);
await sceneImporter.LoadSceneAsync();
}

// Override the shaders on all materials if a shader is provided
Expand Down