This commit is contained in:
左右看
2023-06-28 00:35:46 +08:00
parent cb5bab5ce9
commit 0d848e4d07
524 changed files with 78452 additions and 12 deletions
@@ -0,0 +1,17 @@
using System.IO;
using UnityEngine;
namespace UnityGLTF.Examples
{
public class GLTFExporterTest : MonoBehaviour
{
// Use this for initialization
void Awake()
{
var exporter = new GLTFSceneExporter(new[] {transform}, new ExportOptions());
var appPath = Application.dataPath;
var wwwPath = appPath.Substring(0, appPath.LastIndexOf("Assets")) + "www";
exporter.SaveGLTFandBin(Path.Combine(wwwPath, "TestScene"), "TestScene");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7538181ffb49fb8459d770ff26ed0c0e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,58 @@
using System;
using System.Collections;
using UnityEngine;
using UnityGLTF.Loader;
namespace UnityGLTF.Examples
{
public class MultiSceneComponent : MonoBehaviour
{
public int SceneIndex = 0;
public string Url;
private GLTFSceneImporter _importer;
private ImportOptions _importOptions;
private string _fileName;
void Start()
{
Debug.Log("Hit spacebar to change the scene.");
Uri uri = new Uri(Url);
var directoryPath = URIHelper.AbsoluteUriPath(uri);
_importOptions = new ImportOptions
{
DataLoader = new WebRequestLoader(directoryPath),
AsyncCoroutineHelper = gameObject.AddComponent<AsyncCoroutineHelper>(),
};
_fileName = URIHelper.GetFileFromUri(uri);
LoadScene(SceneIndex);
}
void Update()
{
if (Input.GetKeyDown("space"))
{
SceneIndex = SceneIndex == 0 ? 1 : 0;
Debug.LogFormat("Loading scene {0}", SceneIndex);
LoadScene(SceneIndex);
}
}
async void LoadScene(int SceneIndex)
{
foreach (Transform child in transform)
{
GameObject.Destroy(child.gameObject);
}
_importer = new GLTFSceneImporter(
_fileName,
_importOptions
);
_importer.SceneParent = gameObject.transform;
await _importer.LoadSceneAsync(SceneIndex);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e2719fa7e09cf264492f3aa25409f37e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,113 @@
using UnityEngine;
// Taken from http://wiki.unity3d.com/index.php?title=MouseOrbitImproved
namespace UnityGLTF.Examples
{
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class OrbitCameraController : MonoBehaviour
{
public Vector3 targetPosition = Vector3.zero;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float zoomSpeed = 0.8f;
public float yMinLimit = -85f;
public float yMaxLimit = 85f;
public float distanceMin = .5f;
public float distanceMax = 150f;
private Camera _camera;
private Rigidbody cameraRigidBody;
private float x = 0.0f;
private float y = 0.0f;
private Vector3 prevMousePosition;
Quaternion rotation;
// Use this for initialization
void Start()
{
_camera = GetComponent<Camera>();
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
rotation = Quaternion.Euler(y, x, 0);
prevMousePosition = Input.mousePosition;
cameraRigidBody = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (cameraRigidBody != null)
{
cameraRigidBody.freezeRotation = true;
}
}
void LateUpdate()
{
var height = Display.main.renderingHeight;
var width = Display.main.renderingWidth;
if (Input.GetMouseButton(0))
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.06f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.06f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
rotation = Quaternion.Euler(y, x, 0);
}
else if (Input.GetMouseButton(1))
{
var prevMouseWorldPosition = ProjectScreenPointToTargetPlane(prevMousePosition);
var mouseWorldPosition = ProjectScreenPointToTargetPlane(Input.mousePosition);
targetPosition += prevMouseWorldPosition - mouseWorldPosition;
}
var mouseOverRenderArea =
Input.mousePosition.x >= 0 &&
Input.mousePosition.x <= width &&
Input.mousePosition.y >= 0 &&
Input.mousePosition.y <= height;
if (Input.GetMouseButton(0) || mouseOverRenderArea)
{
distance = Mathf.Clamp(distance * Mathf.Exp(-Input.GetAxis("Mouse ScrollWheel") * zoomSpeed), distanceMin, distanceMax);
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + targetPosition;
transform.rotation = rotation;
transform.position = position;
prevMousePosition = Input.mousePosition;
}
private Vector3 ProjectScreenPointToTargetPlane(Vector3 screenPosition)
{
var ray = _camera.ScreenPointToRay(screenPosition);
var planeDistance = distance / Mathf.Cos(Mathf.Deg2Rad * Vector3.Angle(_camera.transform.forward, ray.direction));
return _camera.transform.position + (ray.direction * planeDistance);
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 70ff706d2c89cc247a850af95597fcbb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
using System.Collections;
using System.IO;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
using UnityEngine;
using UnityGLTF;
using UnityGLTF.Loader;
namespace UnityGLTF
{
public class RootMergeComponent : MonoBehaviour
{
public string asset0Path;
public string asset1Path;
public bool Multithreaded = true;
public int MaximumLod = 300;
// todo undo
#if !WINDOWS_UWP
private async Task Start()
{
var fullPath0 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset0Path;
IDataLoader loader0 = new FileLoader(URIHelper.GetDirectoryName(fullPath0));
var fullPath1 = Application.streamingAssetsPath + Path.DirectorySeparatorChar + asset1Path;
IDataLoader loader1 = new FileLoader(URIHelper.GetDirectoryName(fullPath1));
var asset0Stream = await loader0.LoadStreamAsync(Path.GetFileName(asset0Path));
GLTFRoot asset0Root;
GLTFParser.ParseJson(asset0Stream, out asset0Root);
var asset1Stream = await loader1.LoadStreamAsync(Path.GetFileName(asset1Path));
GLTFRoot asset1Root;
GLTFParser.ParseJson(asset1Stream, out asset1Root);
string newPath = "../../" + URIHelper.GetDirectoryName(asset0Path);
int previousBufferCount = asset1Root.Buffers.Count;
int previousImageCount = asset1Root.Images.Count;
int previousSceneCounter = asset1Root.Scenes.Count;
GLTFHelpers.MergeGLTF(asset1Root, asset0Root);
for (int i = previousBufferCount; i < asset1Root.Buffers.Count; ++i)
{
GLTF.Schema.GLTFBuffer buffer = asset1Root.Buffers[i];
if (!URIHelper.IsBase64Uri(buffer.Uri))
{
buffer.Uri = newPath + buffer.Uri;
}
}
for (int i = previousImageCount; i < asset1Root.Images.Count; ++i)
{
GLTFImage image = asset1Root.Images[i];
if (!URIHelper.IsBase64Uri(image.Uri))
{
image.Uri = newPath + image.Uri;
}
}
foreach (NodeId node in asset1Root.Scenes[asset0Root.Scene.Id + previousSceneCounter].Nodes)
{
node.Value.Translation.X += 5f;
asset1Root.Scene.Value.Nodes.Add(node);
}
GLTFSceneImporter importer = new GLTFSceneImporter(
asset1Root,
null,
new ImportOptions
{
DataLoader = loader1,
AsyncCoroutineHelper = gameObject.AddComponent<AsyncCoroutineHelper>()
});
importer.MaximumLod = MaximumLod;
importer.IsMultithreaded = Multithreaded;
await importer.LoadSceneAsync(-1);
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0fec5969022b49741878ab5b33c551bf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,48 @@
using UnityEngine;
using UnityGLTF;
public class SampleModelList : MonoBehaviour
{
public static string LoaderFieldName => nameof(loader);
public static string PathRootFieldName => nameof(pathRoot);
public static string ManifestRelativePathFieldName => nameof(manifestRelativePath);
public static string ModelRelativePathFieldName => nameof(modelRelativePath);
public static string LoadThisFrameFieldName => nameof(loadThisFrame);
[SerializeField]
private GLTFComponent loader = null;
[SerializeField]
private string pathRoot = "http://localhost:8080/glTF-Sample-Models/2.0/";
// Disable "unused private field" because it is accessed by SampleModelListInspector using serialization.
#pragma warning disable 414
[SerializeField]
private string manifestRelativePath = "model-index.json";
#pragma warning restore 414
[SerializeField]
private string modelRelativePath = null;
[SerializeField]
private bool loadThisFrame = false;
private async void Update()
{
if (loadThisFrame)
{
loadThisFrame = false;
var path = pathRoot + modelRelativePath;
Debug.Log(path, this);
if (loader.LastLoadedScene != null)
{
Destroy(loader.LastLoadedScene);
}
loader.GLTFUri = path;
await loader.Load();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df99c459245b3cd40be06aca24a19170
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,238 @@
// MIT License - Copyright (c) 2016 Can Güney Aksakalli
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UnityGLTF.Examples
{
class SimpleHTTPServer
{
private readonly string[] _indexFiles =
{
"index.html",
"index.htm",
"default.html",
"default.htm"
};
#if !WINDOWS_UWP
private static IDictionary<string, string> _mimeTypeMappings =
new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
#else
private static IDictionary<string, string> _mimeTypeMappings =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
#endif
#region extension to MIME type list
{".asf", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".cco", "application/x-cocoa"},
{".crt", "application/x-x509-ca-cert"},
{".css", "text/css"},
{".deb", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dll", "application/octet-stream"},
{".dmg", "application/octet-stream"},
{".ear", "application/java-archive"},
{".eot", "application/octet-stream"},
{".exe", "application/octet-stream"},
{".flv", "video/x-flv"},
{".gif", "image/gif"},
{".gltf", "model/gltf+json"},
{".glb", "model/gltf-binary"},
{".hqx", "application/mac-binhex40"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".ico", "image/x-icon"},
{".img", "application/octet-stream"},
{".iso", "application/octet-stream"},
{".jar", "application/java-archive"},
{".jardiff", "application/x-java-archive-diff"},
{".jng", "image/x-jng"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".json", "application/json"},
{".mml", "text/mathml"},
{".mng", "video/x-mng"},
{".mov", "video/quicktime"},
{".mp3", "audio/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".msi", "application/octet-stream"},
{".msm", "application/octet-stream"},
{".msp", "application/octet-stream"},
{".pdb", "application/x-pilot"},
{".pdf", "application/pdf"},
{".pem", "application/x-x509-ca-cert"},
{".pl", "application/x-perl"},
{".pm", "application/x-perl"},
{".png", "image/png"},
{".prc", "application/x-pilot"},
{".ra", "audio/x-realaudio"},
{".rar", "application/x-rar-compressed"},
{".rpm", "application/x-redhat-package-manager"},
{".rss", "text/xml"},
{".run", "application/x-makeself"},
{".sea", "application/x-sea"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".swf", "application/x-shockwave-flash"},
{".tcl", "application/x-tcl"},
{".tk", "application/x-tcl"},
{".txt", "text/plain"},
{".war", "application/java-archive"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wmv", "video/x-ms-wmv"},
{".xml", "text/xml"},
{".xpi", "application/x-xpinstall"},
{".zip", "application/zip"},
#endregion
};
private Thread _serverThread;
private string _rootDirectory;
#if !WINDOWS_UWP
private HttpListener _listener;
#endif
private int _port = default;
public int Port
{
get { return _port; }
private set { }
}
/// <summary>
/// Construct server with given port.
/// </summary>
/// <param name="path">Directory path to serve.</param>
/// <param name="port">Port of the server.</param>
public SimpleHTTPServer(string path, int port)
{
this.Initialize(path, port);
}
/// <summary>
/// Construct server with suitable port.
/// </summary>
/// <param name="path">Directory path to serve.</param>
public SimpleHTTPServer(string path)
{
#if !WINDOWS_UWP
//get an empty port
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
this.Initialize(path, port);
#endif
}
/// <summary>
/// Stop server and dispose all functions.
/// </summary>
public void Stop()
{
#if !WINDOWS_UWP
_serverThread.Abort();
_listener.Stop();
#endif
}
private void Listen()
{
#if !WINDOWS_UWP
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
_listener.Start();
while (true)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch (Exception)
{
}
}
#endif
}
#if !WINDOWS_UWP
private void Process(HttpListenerContext context)
{
string filename = context.Request.Url.AbsolutePath;
Console.WriteLine(filename);
filename = filename.Substring(1);
if (string.IsNullOrEmpty(filename))
{
foreach (string indexFile in _indexFiles)
{
if (File.Exists(Path.Combine(_rootDirectory, indexFile)))
{
filename = indexFile;
break;
}
}
}
filename = Path.Combine(_rootDirectory, filename);
if (File.Exists(filename))
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
try
{
Stream input = File.OpenRead(filename);
//Adding permanent http response headers
string mime;
context.Response.ContentType = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime)
? mime
: "application/octet-stream";
context.Response.ContentLength64 = input.Length;
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));
input.CopyTo(context.Response.OutputStream);
input.Close();
}
catch (Exception e)
{
Debug.LogException(e);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
context.Response.Close();
}
#endif
private void Initialize(string path, int port)
{
#if !WINDOWS_UWP
this._rootDirectory = path;
this._port = port;
_serverThread = new Thread(this.Listen);
_serverThread.Start();
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 019611993d8c07549bf0ca9c4154daef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UnityGLTF.Samples.Misc",
"references": [
"UnityGLTFScripts",
"GLTFSerialization"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [],
"autoReferenced": false,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ff6a9cbb30169964fb1b3d77c5a53088
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,60 @@
using UnityEngine;
namespace UnityGLTF.Examples
{
public class VisualizeMeshAttributes : MonoBehaviour
{
[SerializeField] private MeshFilter Mesh = default;
[SerializeField] private float NormalScale = 0.1f;
[SerializeField] private float TangentScale = 0.1f;
[SerializeField] private bool VisualizeTangents = false;
[SerializeField] private bool VisualizeNormals = false;
private Vector3[] vertices;
private Vector3[] normals;
private Vector4[] tangents;
void OnEnable()
{
if (Mesh != null && Mesh.mesh != null)
{
vertices = Mesh.mesh.vertices;
normals = Mesh.mesh.normals;
tangents = Mesh.mesh.tangents;
}
}
// Update is called once per frame
void Update()
{
if (vertices != null)
{
int numVerts = vertices.Length;
for (int vertexIndex = 0; vertexIndex < numVerts; vertexIndex++)
{
var vertexTransformed = this.transform.TransformPoint(vertices[vertexIndex]);
if (VisualizeNormals && normals != null)
{
var normalTransformed = this.transform.InverseTransformVector(normals[vertexIndex]);
Debug.DrawLine(vertexTransformed, vertexTransformed + normalTransformed * NormalScale * 0.5f,
Color.green);
Debug.DrawLine(vertexTransformed + normalTransformed * NormalScale * 0.5f,
vertexTransformed + normalTransformed * NormalScale * 1.0f, Color.blue);
}
if (VisualizeTangents && tangents != null)
{
var tangentTransformed = this.transform.TransformVector(
tangents[vertexIndex].w * new Vector3(tangents[vertexIndex].x, tangents[vertexIndex].y,
tangents[vertexIndex].z));
Debug.DrawLine(vertexTransformed, vertexTransformed + tangentTransformed * TangentScale * 0.5f,
Color.black);
Debug.DrawLine(vertexTransformed + tangentTransformed * TangentScale * 0.5f,
vertexTransformed + tangentTransformed * TangentScale * 1.0f, Color.white);
}
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 62a324520be0e6045bc06e4d89e950de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,22 @@
using UnityEngine;
namespace UnityGLTF.Examples
{
public class WebServerComponent : MonoBehaviour
{
private SimpleHTTPServer _server;
void Start()
{
var appPath = Application.dataPath;
var wwwPath = appPath.Substring(0, appPath.LastIndexOf("Assets")) + "www";
_server = new SimpleHTTPServer(wwwPath, 8080);
Debug.Log("Starting web server...");
}
private void OnDestroy()
{
_server.Stop();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 946dbe02f30bd734c901251fcc62a97a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 100
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: