├── .gitignore
├── Out
└── Egret3DExportTools
│ ├── ExportTool.dll
│ ├── ExportTool.dll.mdb
│ ├── ExportTool.pdb
│ ├── Newtonsoft.Json.dll
│ └── Newtonsoft.Json.xml
├── README.md
└── UnityExportTool
├── .vscode
└── launch.json
├── ExportTool.csproj
├── ExportTool.csproj.user
├── Properties
├── AssemblyInfo.cs
├── Resources.Designer.cs
└── Resources.resx
├── Unity3DExportTool.sln
├── bin
└── Debug
│ ├── ExportTool.dll
│ ├── ExportTool.dll.mdb
│ ├── ExportTool.pdb
│ ├── UnityEditor.dll
│ └── UnityEngine.dll
├── libs
├── Newtonsoft.Json.dll
├── Newtonsoft.Json.xml
└── unity5
│ ├── UnityEditor.dll
│ └── UnityEngine.dll
└── src
├── ExportTools
├── ExportImage.cs
├── ExportPrefab.cs
├── ExportScene.cs
├── ExportSetting.cs
└── ExtendTools.cs
├── ExportWindow.cs
├── GLTF
├── GLTFSerialization
│ ├── AttributeAccessor.cs
│ ├── Exceptions.cs
│ ├── Extensions
│ │ ├── ExtTextureTransformExtension.cs
│ │ ├── ExtTextureTransformExtensionFactory.cs
│ │ ├── GLTFJsonExtensions.cs
│ │ ├── KHR_materials_pbrSpecularGlossinessExtension.cs
│ │ └── KHR_materials_pbrSpecularGlossinessExtensionFactory.cs
│ ├── GLTFHelpers.cs
│ ├── GLTFParser.cs
│ ├── Math
│ │ ├── Color.cs
│ │ ├── Matrix4x4.cs
│ │ ├── Quaternion.cs
│ │ ├── Vector2.cs
│ │ ├── Vector3.cs
│ │ └── Vector4.cs
│ └── Schema
│ │ ├── Accessor.cs
│ │ ├── AccessorSparse.cs
│ │ ├── AccessorSparseIndices.cs
│ │ ├── AccessorSparseValues.cs
│ │ ├── Animation.cs
│ │ ├── AnimationChannel.cs
│ │ ├── AnimationChannelTarget.cs
│ │ ├── AnimationSampler.cs
│ │ ├── Asset.cs
│ │ ├── Buffer.cs
│ │ ├── BufferView.cs
│ │ ├── Camera.cs
│ │ ├── CameraOrthographic.cs
│ │ ├── CameraPerspective.cs
│ │ ├── GLTFChildOfRootProperty.cs
│ │ ├── GLTFId.cs
│ │ ├── GLTFProperty.cs
│ │ ├── GLTFRoot.cs
│ │ ├── IExtension.cs
│ │ ├── Image.cs
│ │ ├── Material.cs
│ │ ├── MaterialCommonConstant.cs
│ │ ├── MaterialNormalTextureInfo.cs
│ │ ├── MaterialOcclusionTextureInfo.cs
│ │ ├── MaterialPBRMetallicRoughness.cs
│ │ ├── Mesh.cs
│ │ ├── MeshPrimitive.cs
│ │ ├── Node.cs
│ │ ├── Sampler.cs
│ │ ├── Scene.cs
│ │ ├── Skin.cs
│ │ ├── Texture.cs
│ │ └── TextureInfo.cs
└── UnityGLTF
│ ├── Async
│ ├── AsyncAction.cs
│ └── TaskExtensions.cs
│ ├── Cache
│ ├── AnimationCacheData.cs
│ ├── AssetCache.cs
│ ├── BufferCacheData.cs
│ ├── MaterialCacheData.cs
│ ├── MeshCacheData.cs
│ ├── RefCountedCacheData.cs
│ └── TextureCacheData.cs
│ ├── Editor
│ ├── GLTFExportMenu.cs
│ ├── GLTFImporter.cs
│ ├── GLTFImporterInspector.cs
│ ├── GLTFImporterNormals.cs
│ └── PbrShaderGUI.cs
│ ├── Exceptions.cs
│ ├── Extensions
│ └── SchemaExtensions.cs
│ ├── GLTFComponent.cs
│ ├── GLTFSceneExporter.cs
│ ├── GLTFSceneImporter.cs
│ ├── InstantiatedGLTFObject.cs
│ ├── Loader
│ ├── FileLoader.cs
│ ├── ILoader.cs
│ ├── StorageFolderLoader.cs
│ └── WebRequestLoader.cs
│ ├── URIHelper.cs
│ └── UniformMaps
│ ├── MetalRough2StandardMap.cs
│ ├── MetalRoughMap.cs
│ ├── SpecGloss2StandardMap.cs
│ ├── SpecGlossMap.cs
│ ├── StandardMap.cs
│ └── UniformMap.cs
├── Helper
├── Extensions
│ ├── GLTFExtension.cs
│ ├── JsonExtension.cs
│ └── MaterialExtension.cs
├── MyLog.cs
└── PathHelper.cs
└── Serialization
├── Assets
├── Extensions
│ ├── AnimationExtension.cs
│ ├── AssetVersion.cs
│ ├── MaterialExtension.cs
│ └── TextureExtension.cs
├── GLTFAnimationClipSerializer.cs
├── GLTFCubemapSerializer.cs
├── GLTFMaterialSerializer.cs
├── GLTFMeshSerializer.cs
├── GLTFTextureArraySerializer.cs
├── GLTFTextureSerializer.cs
└── MaterialParser
│ ├── BaseMaterialParser.cs
│ ├── CustomParser.cs
│ ├── DiffuseParser.cs
│ ├── LambertParser.cs
│ ├── ParticleParser.cs
│ ├── PhongParser.cs
│ ├── SkyboxCubedParser.cs
│ ├── SkyboxParser.cs
│ ├── StandardParser.cs
│ ├── StandardRoughnessParser.cs
│ └── StandardSpecularParser.cs
├── Components
├── AnimationSerializer.cs
├── AnimatorSerializer.cs
├── BoxColliderSerializer.cs
├── CameraSerializer.cs
├── DirectionalLightSerializer.cs
├── MeshFilterSerializer.cs
├── MeshRendererSerializer.cs
├── ParticleRendererSerializer.cs
├── ParticleSystemSerializer.cs
├── SkinnedMeshRendererSerializer.cs
├── SkyboxSerializer.cs
├── SphereColliderSerializer.cs
├── SpotLightSerializer.cs
└── TransformSerializer.cs
├── SerializeContext.cs
├── SerializeObject.cs
└── SerializerBase.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | /UnityExportTool/.vs
2 | /UnityExportTool/obj
3 |
--------------------------------------------------------------------------------
/Out/Egret3DExportTools/ExportTool.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/Out/Egret3DExportTools/ExportTool.dll
--------------------------------------------------------------------------------
/Out/Egret3DExportTools/ExportTool.dll.mdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/Out/Egret3DExportTools/ExportTool.dll.mdb
--------------------------------------------------------------------------------
/Out/Egret3DExportTools/ExportTool.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/Out/Egret3DExportTools/ExportTool.pdb
--------------------------------------------------------------------------------
/Out/Egret3DExportTools/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/Out/Egret3DExportTools/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Egret3DExportTools
2 | * 支持Unity5.6.4版本以上
3 |
4 | ## 使用DLL方法
5 | 1. 复制Out目录下Egret3DExportTools文件夹到Unity项目Assets下。
6 | 2. 等待Unity编译,完成后会在控制台出现"Finished updating scripts / assemblies"。
7 | 3. Unity编辑器菜单会多出一个Egret3DExportTools选项,点击打开即可。
8 |
9 | ## 生成DLL方法
10 | 1. 使用visual studio 2017打开UnityExportTool目录下Unity3DExportTool.sln文件。
11 | 2. 默认引用libs/unity5下的Unity库,可以自行选择想要引用的Unity库。
12 | 3. 打开项目设置,在生成标签下选择自己的DLL输出路径。
13 | 4. 点击生成解决方案生成插件DLL。
14 |
15 | ## 注意事项
16 | 1. 导出目录请不要带有空格,空格会被插件替换为下划线。
17 | 3. 如果希望渲染效果尽量保持一致,可以把Unity的平台选择为WebGL(Lightmap必须选择WebGL,否则效果会有明显的差异)。
18 |
19 | ## 导出 Unity3D 的场景
20 |
21 | * 选择场景导出功能会把当前激活的场景导出为.scene.json文件。
22 | * 将导出的文件放入您的 Egret Pro 的 resource 文件夹中。
23 | > [!IMPORTANT]
24 | > 请确认资源导出到了 resource 文件夹的根路径中,目前暂时只支持导出到根路径
25 | * 在项目中添加如下代码加载场景
26 | ```typescript
27 | await Application.instance.sceneManager.loadScene("your.scene.json");
28 | ```
29 | 或者
30 | ```typescript
31 | await ResourceManager.instance.loadUri("your.scene.json");
32 | const scene = EntityModelAssetEntity.createInstance("your.scene.json");
33 | ```
34 |
35 |
36 | ## 导出 Unity3D 的预制体
37 |
38 | * 选择资源导出功能会把当前激活的场景导出为.prefab.json文件。
39 | * 将导出的文件放入您的 Egret Pro 的 resource 文件夹中。
40 | * 使用如下代码在场景中添加预制体
41 | ```typescript
42 | const prefab = await EngineFactory.createPrefab("your.prefab.json");
43 | ```
44 | 或者
45 | ```typescript
46 | await ResourceManager.instance.loadUri("your.prefab.json");
47 | const prefab = EntityModelAssetEntity.createInstance("your.prefab.json");
48 | ```
49 |
50 | ## 导出设置
51 |
52 | ### 路径设置
53 | * 路径名称:指定导出文件路径的根路径名称。
54 | * 导出路径: 选择导出的文件路径。
55 |
56 | ### 光照设置
57 | * Lambert:导出非光泽表面的材质,没有镜面高光。
58 | * Phong:导出具有镜面高光的光泽表面的材质。
59 | * Standard:导出基于物理的标准材质。
60 |
61 | ### 场景设置
62 | * 光照贴图:导出Unity烘焙出来的光照贴图以供Egret3D使用。
63 | * 静态合并:导出为StaticBatching组件,Egret3D加载场景后,会尝试把所有在Unity中标记为静态的网格对象合并为若干大的网格对象,以实现减少Drawcall目的。
64 | * 雾:导出为Fog组件以供Egret3D使用。
65 |
66 | ### 图片设置
67 | * 导出原始图片:勾选后,导出时直接复制原始图片资源到导出目录,否则会尝试使用Unity的EncodeToJPG,EncodeToPNG导出资源。
68 | * JPG导出质量:根据需求选择导出JPG的质量。
69 |
70 | ### 网格设置
71 | * UV2,Normals,Colors,Bones,Tangents,根据需求可以选择导出网格时是否导出这些属性,以减少网格资源的体积大小。
72 |
73 | ### 保存配置
74 | * 保存配置:可以把你现在Egret3D导出面板所做的设置保存起来,以方便下次使用。
75 |
76 | ## 支持组件列表
77 | * Transform
78 | * MeshFilter
79 | * MeshRenderer
80 | * Camera
81 | * BoxCollider
82 | * SphereCollider
83 | * SkinnedMeshRenderer
84 | * ParticleSystem(部分支持)
85 | * ParticleRenderer
86 | * Animation(部分支持)
87 | * Animator(部分支持)
88 | * DirectionalLight
89 | * SpotLight
90 | * Skybox
91 |
92 | ## 注意事项
93 |
94 | * Animation组件暂时只实现了对以下属性的导出:
95 | * m_LocalPosition
96 | * m_LocalRotation
97 | * localEulerAnglesRaw
98 | * m_LocalScale
99 | * m_IsActive
100 | * Animator现在会被导出为Egret3D的Animation组件,暂时不支持状态机数据导出.
101 | * 粒子组件暂时只支持以下模块:
102 | * MainMoudle
103 | * Emission
104 | * Shape
105 | * VelocityOverLifetime
106 | * ColorOverLifetime
107 | * SizeOverLifetime
108 | * RotationOverLifetime
109 | * TextureSheetAnimation
110 | * 粒子系统的Shader必须是Particles目录下的Shader,如果不是,在Egret3D中可能会造成粒子系统不显示。
111 |
112 | ## 问题反馈
113 |
114 | 考虑到 Egret3D Unity导出插件可能无法覆盖您现有的 Unity3D 制作的游戏所需要移植的全部特性,您在使用此软件时有可能会出现导出失败或导出结果不正确的情况。您可以将问题反馈至[这里](https://github.com/egret-labs/egret3d-unityplugin/issues)。为了帮助您快速解决问题,请您在反馈问题时将您的游戏资源进行尽可能的简化,并作为附件提交。
--------------------------------------------------------------------------------
/UnityExportTool/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // 使用 IntelliSense 了解相关属性。
3 | // 悬停以查看现有属性的描述。
4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Unity Editor",
9 | "type": "unity",
10 | "path": "/e:/Work/Egret/egret3d-unityplugin/UnityExportTool/Library/EditorInstance.json",
11 | "request": "launch"
12 | },
13 | {
14 | "name": "Windows Player",
15 | "type": "unity",
16 | "request": "launch"
17 | },
18 | {
19 | "name": "OSX Player",
20 | "type": "unity",
21 | "request": "launch"
22 | },
23 | {
24 | "name": "Linux Player",
25 | "type": "unity",
26 | "request": "launch"
27 | },
28 | {
29 | "name": "iOS Player",
30 | "type": "unity",
31 | "request": "launch"
32 | },
33 | {
34 | "name": "Android Player",
35 | "type": "unity",
36 | "request": "launch"
37 | }
38 | ]
39 | }
--------------------------------------------------------------------------------
/UnityExportTool/ExportTool.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ShowAllFiles
5 |
6 |
--------------------------------------------------------------------------------
/UnityExportTool/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("TestDll_3.5")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("TestDll_3.5")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("714d07bc-7a79-4147-a9c5-6188fb513dd4")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | //通过使用 "*",如下所示:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/UnityExportTool/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Unity3DExportTool.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Unity3DExportTool.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 使用此强类型资源类,为所有资源查找
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/UnityExportTool/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | text/microsoft-resx
91 |
92 |
93 | 1.3
94 |
95 |
96 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
97 |
98 |
99 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
100 |
101 |
--------------------------------------------------------------------------------
/UnityExportTool/Unity3DExportTool.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26730.12
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExportTool", "ExportTool.csproj", "{714D07BC-7A79-4147-A9C5-6188FB513DD4}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {714D07BC-7A79-4147-A9C5-6188FB513DD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {714D07BC-7A79-4147-A9C5-6188FB513DD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {714D07BC-7A79-4147-A9C5-6188FB513DD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {714D07BC-7A79-4147-A9C5-6188FB513DD4}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {616D52C0-8C3F-4720-B488-F06D5F376014}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/UnityExportTool/bin/Debug/ExportTool.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/bin/Debug/ExportTool.dll
--------------------------------------------------------------------------------
/UnityExportTool/bin/Debug/ExportTool.dll.mdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/bin/Debug/ExportTool.dll.mdb
--------------------------------------------------------------------------------
/UnityExportTool/bin/Debug/ExportTool.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/bin/Debug/ExportTool.pdb
--------------------------------------------------------------------------------
/UnityExportTool/bin/Debug/UnityEditor.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/bin/Debug/UnityEditor.dll
--------------------------------------------------------------------------------
/UnityExportTool/bin/Debug/UnityEngine.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/bin/Debug/UnityEngine.dll
--------------------------------------------------------------------------------
/UnityExportTool/libs/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/libs/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/UnityExportTool/libs/unity5/UnityEditor.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/libs/unity5/UnityEditor.dll
--------------------------------------------------------------------------------
/UnityExportTool/libs/unity5/UnityEngine.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egret-labs/egret3d-unityplugin/76ea622e5fb4f67a7f311582c8f5b13bc5b4497d/UnityExportTool/libs/unity5/UnityEngine.dll
--------------------------------------------------------------------------------
/UnityExportTool/src/ExportTools/ExportImage.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityEditor;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public static class ExportImage
7 | {
8 | public static byte[] Export(Cubemap source)
9 | {
10 | byte[] bs = null;
11 |
12 | return bs;
13 | }
14 | public static byte[] Export(Texture2D source)
15 | {
16 | var path = AssetDatabase.GetAssetPath(source);
17 | var textureSetting = ExportSetting.instance.texture;
18 | MyLog.Log("---导出图片:" + source.name + " path:" + path);
19 |
20 | //只有jpg、png可以原始图片导出,其他类型不支持
21 | var fileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.dataPath), path);
22 | byte[] bs = null;
23 | if (textureSetting.useOriginalTexture && PathHelper.IsSupportedExt(source) && System.IO.File.Exists(fileName))
24 | {
25 | bs = System.IO.File.ReadAllBytes(fileName);
26 | }
27 | else
28 | {
29 | var saveTextureType = TextureImporterType.Default;
30 | var importer = UnityEditor.TextureImporter.GetAtPath(path) as TextureImporter;
31 | if (importer)
32 | {
33 | saveTextureType = importer.textureType;
34 | if (saveTextureType == TextureImporterType.NormalMap && !textureSetting.useNormalTexture)
35 | {
36 | //法线贴图类型贴图因为Unity特殊处理过,如果要正常导出,就要转换一下类型
37 | importer.textureType = TextureImporterType.Default;
38 | importer.SaveAndReimport();
39 | }
40 | }
41 |
42 | //var renderTexture = RenderTexture.GetTemporary(source.width, source.height);
43 | //Graphics.Blit(source, renderTexture);
44 | //RenderTexture.active = renderTexture;
45 | //var exportTexture = new Texture2D(source.width, source.height);
46 | //exportTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
47 | //exportTexture.Apply();
48 | var couldExportTex = DeCompress(source);
49 | try
50 | {
51 | string ext = PathHelper.GetTextureExt(source);
52 | if (ext == "jpg" || ext == "jpeg")
53 | {
54 | bs = couldExportTex.EncodeToJPG(textureSetting.jpgQuality);
55 | }
56 | // else if (ext == "exr")
57 | // {
58 | // bs = exportTexture.EncodeToEXR();
59 | // }
60 | else
61 | {
62 | bs = couldExportTex.EncodeToPNG();
63 | }
64 | }
65 | catch (System.Exception e)
66 | {
67 | MyLog.LogError(e.StackTrace);
68 | MyLog.LogError("图片导出出错:" + path + " 请保证原始资源是可读写,非压缩文件");
69 | }
70 |
71 | if (importer && importer.textureType != saveTextureType)
72 | {
73 | importer.textureType = saveTextureType;
74 | importer.SaveAndReimport();
75 | }
76 | }
77 |
78 | return bs;
79 | }
80 | public static Texture2D DeCompress(Texture2D source)
81 | {
82 | MyLog.Log("DeCompress: " + source.name);
83 | RenderTexture renderTex = RenderTexture.GetTemporary(
84 | source.width,
85 | source.height,
86 | 0,
87 | RenderTextureFormat.Default,
88 | RenderTextureReadWrite.Linear);
89 |
90 | Graphics.Blit(source, renderTex);
91 | RenderTexture previous = RenderTexture.active;
92 | RenderTexture.active = renderTex;
93 | Texture2D readableText = new Texture2D(source.width, source.height);
94 | readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
95 | readableText.Apply();
96 | RenderTexture.active = previous;
97 | RenderTexture.ReleaseTemporary(renderTex);
98 | return readableText;
99 | }
100 | }
101 |
102 |
103 |
104 |
105 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/ExportTools/ExportPrefab.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using UnityEngine;
3 | namespace Egret3DExportTools
4 | {
5 | public static class ExportPrefab
6 | {
7 | /**
8 | * 导出资源
9 | */
10 | public static void Export(GameObject curObj, string exportPath)
11 | {
12 | SerializeObject.Clear();
13 | string prefabPath = "Assets/" + curObj.name + ".prefab.json";
14 | //如果是Unity预制体那么就导出所在目录,如果是场景的一个普通GameObject,那么导出Assets下
15 |
16 | #if UNITY_2018_4_OR_NEWER
17 | if (UnityEditor.PrefabUtility.GetPrefabAssetType(curObj) == UnityEditor.PrefabAssetType.Variant)
18 | {
19 | UnityEngine.Object parentObject = UnityEditor.PrefabUtility.GetPrefabInstanceHandle(curObj);
20 | prefabPath = UnityEditor.AssetDatabase.GetAssetPath(parentObject) + ".json";
21 | }
22 | #else
23 | if (UnityEditor.PrefabUtility.GetPrefabType(curObj) == UnityEditor.PrefabType.PrefabInstance)
24 | {
25 | UnityEngine.Object parentObject = UnityEditor.PrefabUtility.GetPrefabParent(curObj);
26 | prefabPath = UnityEditor.AssetDatabase.GetAssetPath(parentObject) + ".json";
27 | }
28 | #endif
29 | //保存路径
30 | PathHelper.SetSceneOrPrefabPath(prefabPath);
31 | //预制体坐标归零,直接改坐标
32 | var savePosition = curObj.transform.localPosition;
33 | if (ExportSetting.instance.common.posToZero)
34 | {
35 | curObj.transform.localPosition = Vector3.zero;
36 | }
37 |
38 | SerializeObject.SerializeEntity(curObj);
39 |
40 | SerializeContext.Export(exportPath, prefabPath);
41 | curObj.transform.localPosition = savePosition;
42 | }
43 | }
44 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/ExportTools/ExportScene.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using UnityEngine;
4 |
5 | namespace Egret3DExportTools
6 | {
7 | public static class ExportScene
8 | {
9 | public static void Export(List roots, string exportPath)
10 | {
11 | string sceneName = PathHelper.CurSceneName;
12 | SerializeObject.Clear();
13 | //路径
14 | string scenePath = sceneName + ".scene.json";
15 | PathHelper.SetSceneOrPrefabPath(scenePath);
16 |
17 | var scene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene();
18 |
19 | var sceneEntity = SerializeObject.currentData.CreateEntity();
20 |
21 | var sceneComp = SerializeObject.currentData.CreateComponent(SerializeClass.Scene);
22 | sceneComp.properties.SetString("name", sceneName.Substring(sceneName.LastIndexOf('/') + 1));
23 | sceneEntity.AddComponent(sceneComp);
24 |
25 | var treeComp = SerializeObject.currentData.CreateComponent(SerializeClass.TreeNode);
26 | treeComp.properties.SetString("name", "Root");
27 | treeComp.properties.SetReference("scene", sceneComp.uuid);
28 | sceneEntity.AddComponent(treeComp);
29 |
30 | var sceneSetting = ExportSetting.instance.scene;
31 | // 环境光和光照贴图
32 | var sceneLightComp = SerializeObject.currentData.CreateComponent(SerializeClass.SceneLight);
33 | sceneLightComp.properties.SetColor("ambientColor", RenderSettings.ambientLight);
34 | if(sceneSetting.lightmap)
35 | {
36 | sceneLightComp.properties.SetNumber("lightmapIntensity", UnityEditor.Lightmapping.indirectOutputScale);
37 | sceneLightComp.properties.SetLightmaps(exportPath);
38 | }
39 |
40 | sceneEntity.AddComponent(sceneLightComp);
41 |
42 | if(sceneSetting.staticBatching)
43 | {
44 | var staticBatching = SerializeObject.currentData.CreateComponent(SerializeClass.StaticBatching);
45 | sceneEntity.AddComponent(staticBatching);
46 | }
47 |
48 | // 雾
49 | if (RenderSettings.fog && sceneSetting.fog)
50 | {
51 | var fogComp = SerializeObject.currentData.CreateComponent(SerializeClass.Fog);
52 | if (RenderSettings.fogMode == FogMode.Linear)
53 | {
54 | fogComp.properties.SetInt("mode", 0);
55 | fogComp.properties.SetNumber("near", RenderSettings.fogStartDistance);
56 | fogComp.properties.SetNumber("far", RenderSettings.fogEndDistance);
57 | }
58 | else
59 | {
60 | fogComp.properties.SetInt("mode", 1);
61 | fogComp.properties.SetNumber("density", RenderSettings.fogDensity);
62 | }
63 | fogComp.properties.SetColor("color", RenderSettings.fogColor);
64 | sceneEntity.AddComponent(fogComp);
65 | }
66 |
67 | foreach (var child in roots)
68 | {
69 | var childEntity = SerializeObject.SerializeEntity(child);
70 | if (childEntity != null)
71 | {
72 | treeComp.AddChild(childEntity.treeNode);
73 | }
74 | }
75 |
76 | SerializeContext.Export(exportPath, scenePath);
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/AttributeAccessor.cs:
--------------------------------------------------------------------------------
1 | using GLTF.Schema;
2 |
3 | namespace GLTF
4 | {
5 | public class AttributeAccessor
6 | {
7 | public AccessorId AccessorId { get; set; }
8 | public NumericArray AccessorContent { get; set; }
9 | public System.IO.Stream Stream { get; set; }
10 | public long Offset { get; set; }
11 |
12 | public AttributeAccessor()
13 | {
14 | AccessorContent = new NumericArray();
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Exceptions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF
4 | {
5 | public class GLTFHeaderInvalidException : Exception
6 | {
7 | public GLTFHeaderInvalidException() : base() { }
8 | public GLTFHeaderInvalidException(string message) : base(message) { }
9 | public GLTFHeaderInvalidException(string message, Exception inner) : base(message, inner) { }
10 | #if !WINDOWS_UWP
11 | protected GLTFHeaderInvalidException(System.Runtime.Serialization.SerializationInfo info,
12 | System.Runtime.Serialization.StreamingContext context)
13 | { }
14 | #endif
15 | }
16 |
17 | public class GLTFParseException : Exception
18 | {
19 | public GLTFParseException() : base() { }
20 | public GLTFParseException(string message) : base(message) { }
21 | public GLTFParseException(string message, Exception inner) : base(message, inner) { }
22 | #if !WINDOWS_UWP
23 | protected GLTFParseException(System.Runtime.Serialization.SerializationInfo info,
24 | System.Runtime.Serialization.StreamingContext context)
25 | { }
26 | #endif
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Extensions/ExtTextureTransformExtension.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using GLTF.Math;
3 | using GLTF.Schema;
4 | using Newtonsoft.Json;
5 | using Newtonsoft.Json.Linq;
6 |
7 | namespace GLTF.Schema
8 | {
9 | public class ExtTextureTransformExtension : IExtension
10 | {
11 | ///
12 | /// The offset of the UV coordinate origin as a percentage of the texture dimensions.
13 | ///
14 | public Vector2 Offset = new Vector2(0, 0);
15 | public static readonly Vector2 OFFSET_DEFAULT = new Vector2(0, 0);
16 |
17 | ///
18 | /// The scale factor applied to the components of the UV coordinates.
19 | ///
20 | public Vector2 Scale = new Vector2(1, 1);
21 | public static readonly Vector2 SCALE_DEFAULT = new Vector2(1, 1);
22 |
23 | ///
24 | /// Overrides the textureInfo texCoord value if this extension is supported.
25 | ///
26 | public int TexCoord = 0;
27 | public static readonly int TEXCOORD_DEFAULT = 0;
28 |
29 | public ExtTextureTransformExtension(Vector2 offset, Vector2 scale, int texCoord)
30 | {
31 | Offset = offset;
32 | Scale = scale;
33 | TexCoord = texCoord;
34 | }
35 |
36 | public IExtension Clone(GLTFRoot root)
37 | {
38 | return new ExtTextureTransformExtension(Offset, Scale, TexCoord);
39 | }
40 |
41 | public JProperty Serialize()
42 | {
43 | var ext = new JObject();
44 |
45 | if (Offset != OFFSET_DEFAULT)
46 | {
47 | ext.Add(new JProperty(
48 | ExtTextureTransformExtensionFactory.OFFSET,
49 | new JArray(Offset.X, Offset.Y)
50 | ));
51 | }
52 |
53 | if (Scale != SCALE_DEFAULT)
54 | {
55 | ext.Add(new JProperty(
56 | ExtTextureTransformExtensionFactory.SCALE,
57 | new JArray(Scale.X, Scale.Y)
58 | ));
59 | }
60 |
61 | if (TexCoord != TEXCOORD_DEFAULT)
62 | {
63 | ext.Add(new JProperty(
64 | ExtTextureTransformExtensionFactory.TEXCOORD,
65 | TexCoord
66 | ));
67 | }
68 |
69 | return new JProperty(ExtTextureTransformExtensionFactory.EXTENSION_NAME, ext);
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Extensions/ExtTextureTransformExtensionFactory.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json.Linq;
2 | using GLTF.Extensions;
3 | using GLTF.Math;
4 |
5 | namespace GLTF.Schema
6 | {
7 | public class ExtTextureTransformExtensionFactory : ExtensionFactory
8 | {
9 | public const string EXTENSION_NAME = "EXT_texture_transform";
10 | public const string OFFSET = "offset";
11 | public const string SCALE = "scale";
12 | public const string TEXCOORD = "texCoord";
13 |
14 | public ExtTextureTransformExtensionFactory()
15 | {
16 | ExtensionName = EXTENSION_NAME;
17 | }
18 |
19 | public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
20 | {
21 | Vector2 offset = new Vector2(ExtTextureTransformExtension.OFFSET_DEFAULT);
22 | Vector2 scale = new Vector2(ExtTextureTransformExtension.SCALE_DEFAULT);
23 | int texCoord = ExtTextureTransformExtension.TEXCOORD_DEFAULT;
24 |
25 | if (extensionToken != null)
26 | {
27 | JToken offsetToken = extensionToken.Value[OFFSET];
28 | offset = offsetToken != null ? offsetToken.DeserializeAsVector2() : offset;
29 |
30 | JToken scaleToken = extensionToken.Value[SCALE];
31 | scale = scaleToken != null ? scaleToken.DeserializeAsVector2() : scale;
32 |
33 | JToken texCoordToken = extensionToken.Value[TEXCOORD];
34 | texCoord = texCoordToken != null ? texCoordToken.DeserializeAsInt() : texCoord;
35 | }
36 |
37 | return new ExtTextureTransformExtension(offset, scale, texCoord);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Extensions/KHR_materials_pbrSpecularGlossinessExtension.cs:
--------------------------------------------------------------------------------
1 | using GLTF.Math;
2 | using GLTF.Schema;
3 | using Newtonsoft.Json;
4 | using Newtonsoft.Json.Linq;
5 |
6 | namespace GLTF.Schema
7 | {
8 | ///
9 | /// glTF extension that defines the specular-glossiness
10 | /// material model from Physically-Based Rendering (PBR) methodology.
11 | ///
12 | /// Spec can be found here:
13 | /// https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
14 | ///
15 | public class KHR_materials_pbrSpecularGlossinessExtension : IExtension
16 | {
17 | public static readonly Vector3 SPEC_FACTOR_DEFAULT = new Vector3(0.2f, 0.2f, 0.2f);
18 | public static readonly double GLOSS_FACTOR_DEFAULT = 0.5d;
19 |
20 | ///
21 | /// The RGBA components of the reflected diffuse color of the material.
22 | /// Metals have a diffuse value of [0.0, 0.0, 0.0].
23 | /// The fourth component (A) is the alpha coverage of the material.
24 | /// The property specifies how alpha is interpreted.
25 | /// The values are linear.
26 | ///
27 | public Color DiffuseFactor = Color.White;
28 |
29 | ///
30 | /// The diffuse texture.
31 | /// This texture contains RGB(A) components of the reflected diffuse color of the material in sRGB color space.
32 | /// If the fourth component (A) is present, it represents the alpha coverage of the
33 | /// material. Otherwise, an alpha of 1.0 is assumed.
34 | /// The property specifies how alpha is interpreted.
35 | /// The stored texels must not be premultiplied.
36 | ///
37 | public TextureInfo DiffuseTexture;
38 |
39 | ///
40 | /// The specular RGB color of the material. This value is linear
41 | ///
42 | public Vector3 SpecularFactor = SPEC_FACTOR_DEFAULT;
43 |
44 | ///
45 | /// The glossiness or smoothness of the material.
46 | /// A value of 1.0 means the material has full glossiness or is perfectly smooth.
47 | /// A value of 0.0 means the material has no glossiness or is completely rough.
48 | /// This value is linear.
49 | ///
50 | public double GlossinessFactor = GLOSS_FACTOR_DEFAULT;
51 |
52 | ///
53 | /// The specular-glossiness texture is RGBA texture, containing the specular color of the material (RGB components) and its glossiness (A component).
54 | /// The values are in sRGB space.
55 | ///
56 | public TextureInfo SpecularGlossinessTexture;
57 |
58 | public KHR_materials_pbrSpecularGlossinessExtension(Color diffuseFactor, TextureInfo diffuseTexture, Vector3 specularFactor, double glossinessFactor, TextureInfo specularGlossinessTexture)
59 | {
60 | DiffuseFactor = diffuseFactor;
61 | DiffuseTexture = diffuseTexture;
62 | SpecularFactor = specularFactor;
63 | GlossinessFactor = glossinessFactor;
64 | SpecularGlossinessTexture = specularGlossinessTexture;
65 | }
66 |
67 | public IExtension Clone(GLTFRoot gltfRoot)
68 | {
69 | return new KHR_materials_pbrSpecularGlossinessExtension(
70 | DiffuseFactor,
71 | new TextureInfo(
72 | DiffuseTexture,
73 | gltfRoot
74 | ),
75 | SpecularFactor,
76 | GlossinessFactor,
77 | new TextureInfo(
78 | SpecularGlossinessTexture,
79 | gltfRoot
80 | )
81 | );
82 | }
83 |
84 | public JProperty Serialize()
85 | {
86 | JProperty jProperty =
87 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME,
88 | new JObject(
89 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.DIFFUSE_FACTOR, DiffuseFactor),
90 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.DIFFUSE_TEXTURE,
91 | new JObject(
92 | new JProperty(TextureInfo.INDEX, DiffuseTexture.Index.Id)
93 | )
94 | ),
95 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.SPECULAR_FACTOR, SpecularFactor),
96 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.GLOSSINESS_FACTOR, GlossinessFactor),
97 | new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.SPECULAR_GLOSSINESS_TEXTURE,
98 | new JObject(
99 | new JProperty(TextureInfo.INDEX, SpecularGlossinessTexture.Index.Id)
100 | )
101 | )
102 | )
103 | );
104 |
105 | return jProperty;
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Extensions/KHR_materials_pbrSpecularGlossinessExtensionFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json.Linq;
3 | using GLTF.Math;
4 | using Newtonsoft.Json;
5 | using GLTF.Extensions;
6 |
7 | namespace GLTF.Schema
8 | {
9 | public class KHR_materials_pbrSpecularGlossinessExtensionFactory : ExtensionFactory
10 | {
11 | public const string EXTENSION_NAME = "KHR_materials_pbrSpecularGlossiness";
12 | public const string DIFFUSE_FACTOR = "diffuseFactor";
13 | public const string DIFFUSE_TEXTURE = "diffuseTexture";
14 | public const string SPECULAR_FACTOR = "specularFactor";
15 | public const string GLOSSINESS_FACTOR = "glossinessFactor";
16 | public const string SPECULAR_GLOSSINESS_TEXTURE = "specularGlossinessTexture";
17 |
18 | public KHR_materials_pbrSpecularGlossinessExtensionFactory()
19 | {
20 | ExtensionName = EXTENSION_NAME;
21 | }
22 |
23 | public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
24 | {
25 | Color diffuseFactor = Color.White;
26 | TextureInfo diffuseTextureInfo = new TextureInfo();
27 | Vector3 specularFactor = KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT;
28 | double glossinessFactor = KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT;
29 | TextureInfo specularGlossinessTextureInfo = new TextureInfo();
30 |
31 | if (extensionToken != null)
32 | {
33 | System.Diagnostics.Debug.WriteLine(extensionToken.Value.ToString());
34 | System.Diagnostics.Debug.WriteLine(extensionToken.Value.Type);
35 |
36 | JToken diffuseFactorToken = extensionToken.Value[DIFFUSE_FACTOR];
37 | diffuseFactor = diffuseFactorToken != null ? diffuseFactorToken.DeserializeAsColor() : diffuseFactor;
38 | diffuseTextureInfo = extensionToken.Value[DIFFUSE_TEXTURE].DeserializeAsTexture(root);
39 | JToken specularFactorToken = extensionToken.Value[SPECULAR_FACTOR];
40 | specularFactor = specularFactorToken != null ? specularFactorToken.DeserializeAsVector3() : specularFactor;
41 | JToken glossinessFactorToken = extensionToken.Value[GLOSSINESS_FACTOR];
42 | glossinessFactor = glossinessFactorToken != null ? glossinessFactorToken.DeserializeAsDouble() : glossinessFactor;
43 | specularGlossinessTextureInfo = extensionToken.Value[SPECULAR_GLOSSINESS_TEXTURE].DeserializeAsTexture(root);
44 | }
45 |
46 | return new KHR_materials_pbrSpecularGlossinessExtension(diffuseFactor, diffuseTextureInfo, specularFactor, glossinessFactor, specularGlossinessTextureInfo);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/GLTFParser.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using GLTF.Schema;
4 |
5 | namespace GLTF
6 | {
7 | public class GLTFParser
8 | {
9 |
10 | private enum ChunkFormat : uint
11 | {
12 | JSON = 0x4e4f534a,
13 | BIN = 0x004e4942
14 | }
15 |
16 | internal struct GLBHeader
17 | {
18 | public uint Version { get; set; }
19 | public uint FileLength { get; set; }
20 | }
21 |
22 | public static GLTFRoot ParseJson(Stream stream, long startPosition = 0)
23 | {
24 | stream.Position = startPosition;
25 | // Check for binary format magic bytes
26 | if (IsGLB(stream))
27 | {
28 | ParseJsonChunk(stream, startPosition);
29 | }
30 | else
31 | {
32 | stream.Position = startPosition;
33 | }
34 |
35 | return GLTFRoot.Deserialize(new StreamReader(stream));
36 | }
37 |
38 | // Moves stream position to binary chunk location
39 | public static void SeekToBinaryChunk(Stream stream, int binaryChunkIndex, long startPosition = 0)
40 | {
41 | stream.Position = startPosition + 4; // start after magic number chunk
42 | GLBHeader header = ParseGLBHeader(stream);
43 | uint chunkOffset = 12; // sizeof(GLBHeader) + magic number
44 | uint chunkLength = 0;
45 | for (int i = 0; i < binaryChunkIndex + 2; ++i)
46 | {
47 | chunkOffset += chunkLength;
48 | stream.Position = chunkOffset;
49 | chunkLength = GetUInt32(stream);
50 | chunkOffset += 8; // to account for chunk length (4 bytes) and type (4 bytes)
51 | }
52 |
53 | // Load Binary Chunk
54 | if (chunkOffset + chunkLength <= header.FileLength)
55 | {
56 | uint chunkType = GetUInt32(stream);
57 | if (chunkType != (uint)ChunkFormat.BIN)
58 | {
59 | throw new GLTFHeaderInvalidException("Second chunk must be of type BIN if present");
60 | }
61 | }
62 | else
63 | {
64 | throw new GLTFHeaderInvalidException("File length does not match chunk header.");
65 | }
66 | }
67 |
68 | private static GLBHeader ParseGLBHeader(Stream stream)
69 | {
70 | uint version = GetUInt32(stream); // 4
71 | uint length = GetUInt32(stream); // 8
72 |
73 | return new GLBHeader
74 | {
75 | Version = version,
76 | FileLength = length
77 | };
78 | }
79 |
80 | private static bool IsGLB(Stream stream)
81 | {
82 | return GetUInt32(stream) == 0x46546c67; // 0
83 | }
84 |
85 | private static void ParseJsonChunk(Stream stream, long startPosition)
86 | {
87 | GLBHeader header = ParseGLBHeader(stream); // 4, 8
88 | if (header.Version != 2)
89 | {
90 | throw new GLTFHeaderInvalidException("Unsupported glTF version");
91 | };
92 |
93 | if (header.FileLength != (stream.Length - startPosition))
94 | {
95 | throw new GLTFHeaderInvalidException("File length does not match header.");
96 | }
97 |
98 | int chunkLength = (int)GetUInt32(stream); // 12
99 | var chunkType = GetUInt32(stream); // 16
100 | if (chunkType != (uint)ChunkFormat.JSON)
101 | {
102 | throw new GLTFHeaderInvalidException("First chunk must be of type JSON");
103 | }
104 | }
105 |
106 | private static uint GetUInt32(Stream stream)
107 | {
108 | var uintSize = sizeof(uint);
109 | byte[] headerBuffer = new byte[uintSize];
110 | stream.Read(headerBuffer, 0, uintSize);
111 | return BitConverter.ToUInt32(headerBuffer, 0);
112 | }
113 | }
114 | }
115 |
116 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Math/Color.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF.Math
4 | {
5 | public struct Color : IEquatable
6 | {
7 | public static Color Black { get { return new Color(0f, 0f, 0f, 1f); } }
8 | public static Color White { get { return new Color(1f, 1f, 1f, 1f); } }
9 |
10 | public float R { get; set; }
11 | public float G { get; set; }
12 | public float B { get; set; }
13 | public float A { get; set; }
14 |
15 | public Color(float r, float g, float b, float a)
16 | {
17 | R = r;
18 | G = g;
19 | B = b;
20 | A = a;
21 | }
22 |
23 | public Color(Color other)
24 | {
25 | R = other.R;
26 | G = other.G;
27 | B = other.B;
28 | A = other.A;
29 | }
30 |
31 | public bool Equals(Color other)
32 | {
33 | return R.Equals(other.R) && G.Equals(other.G) && B.Equals(other.B) && A.Equals(other.A);
34 | }
35 |
36 | public override bool Equals(object obj)
37 | {
38 | if (ReferenceEquals(null, obj)) return false;
39 | return obj is Color && Equals((Color) obj);
40 | }
41 |
42 | public override int GetHashCode()
43 | {
44 | unchecked
45 | {
46 | var hashCode = R.GetHashCode();
47 | hashCode = (hashCode * 397) ^ G.GetHashCode();
48 | hashCode = (hashCode * 397) ^ B.GetHashCode();
49 | hashCode = (hashCode * 397) ^ A.GetHashCode();
50 | return hashCode;
51 | }
52 | }
53 |
54 | public static bool operator ==(Color left, Color right)
55 | {
56 | return left.Equals(right);
57 | }
58 |
59 | public static bool operator !=(Color left, Color right)
60 | {
61 | return !left.Equals(right);
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Math/Quaternion.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF.Math
4 | {
5 | public struct Quaternion : IEquatable
6 | {
7 | public static readonly Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f);
8 | public float X { get; set; }
9 | public float Y { get; set; }
10 | public float Z { get; set; }
11 | public float W { get; set; }
12 |
13 | public Quaternion(float x, float y, float z, float w)
14 | {
15 | X = x;
16 | Y = y;
17 | Z = z;
18 | W = w;
19 | }
20 |
21 | public Quaternion(Quaternion other)
22 | {
23 | X = other.X;
24 | Y = other.Y;
25 | Z = other.Z;
26 | W = other.W;
27 | }
28 |
29 | public bool Equals(Quaternion other)
30 | {
31 | return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z) && W.Equals(other.W);
32 | }
33 |
34 | public override bool Equals(object obj)
35 | {
36 | if (ReferenceEquals(null, obj)) return false;
37 | return obj is Quaternion && Equals((Quaternion) obj);
38 | }
39 |
40 | public override int GetHashCode()
41 | {
42 | unchecked
43 | {
44 | var hashCode = X.GetHashCode();
45 | hashCode = (hashCode * 397) ^ Y.GetHashCode();
46 | hashCode = (hashCode * 397) ^ Z.GetHashCode();
47 | hashCode = (hashCode * 397) ^ W.GetHashCode();
48 | return hashCode;
49 | }
50 | }
51 |
52 | public static bool operator ==(Quaternion left, Quaternion right)
53 | {
54 | return left.Equals(right);
55 | }
56 |
57 | public static bool operator !=(Quaternion left, Quaternion right)
58 | {
59 | return !left.Equals(right);
60 | }
61 | }
62 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Math/Vector2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF.Math
4 | {
5 | public struct Vector2 : IEquatable
6 | {
7 | public float X { get; set; }
8 | public float Y { get; set; }
9 |
10 | public Vector2(float x, float y)
11 | {
12 | X = x;
13 | Y = y;
14 | }
15 |
16 | public Vector2(Vector2 other)
17 | {
18 | X = other.X;
19 | Y = other.Y;
20 | }
21 |
22 | public bool Equals(Vector2 other)
23 | {
24 | return X.Equals(other.X) && Y.Equals(other.Y);
25 | }
26 |
27 | public override bool Equals(object obj)
28 | {
29 | if (ReferenceEquals(null, obj)) return false;
30 | return obj is Vector2 && Equals((Vector2) obj);
31 | }
32 |
33 | public override int GetHashCode()
34 | {
35 | unchecked
36 | {
37 | return (X.GetHashCode() * 397) ^ Y.GetHashCode();
38 | }
39 | }
40 |
41 | public static bool operator ==(Vector2 left, Vector2 right)
42 | {
43 | return left.Equals(right);
44 | }
45 |
46 | public static bool operator !=(Vector2 left, Vector2 right)
47 | {
48 | return !left.Equals(right);
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Math/Vector3.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF.Math
4 | {
5 | public struct Vector3 : IEquatable
6 | {
7 | public static readonly Vector3 Zero = new Vector3(0f, 0f, 0f);
8 | public static readonly Vector3 One = new Vector3(1f, 1f, 1f);
9 |
10 | public float X { get; set; }
11 | public float Y { get; set; }
12 | public float Z { get; set; }
13 |
14 | public Vector3(float x, float y, float z)
15 | {
16 | X = x;
17 | Y = y;
18 | Z = z;
19 | }
20 |
21 |
22 | public Vector3(Vector3 other)
23 | {
24 | X = other.X;
25 | Y = other.Y;
26 | Z = other.Z;
27 | }
28 |
29 | public bool Equals(Vector3 other)
30 | {
31 | return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
32 | }
33 |
34 | public override bool Equals(object obj)
35 | {
36 | if (ReferenceEquals(null, obj)) return false;
37 | return obj is Vector3 && Equals((Vector3) obj);
38 | }
39 |
40 | public override int GetHashCode()
41 | {
42 | unchecked
43 | {
44 | var hashCode = X.GetHashCode();
45 | hashCode = (hashCode * 397) ^ Y.GetHashCode();
46 | hashCode = (hashCode * 397) ^ Z.GetHashCode();
47 | return hashCode;
48 | }
49 | }
50 |
51 | public static bool operator ==(Vector3 left, Vector3 right)
52 | {
53 | return left.Equals(right);
54 | }
55 |
56 | public static bool operator !=(Vector3 left, Vector3 right)
57 | {
58 | return !left.Equals(right);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Math/Vector4.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GLTF.Math
4 | {
5 | public struct Vector4 : IEquatable
6 | {
7 | public float X { get; set; }
8 | public float Y { get; set; }
9 | public float Z { get; set; }
10 | public float W { get; set; }
11 |
12 | public Vector4(float x, float y, float z, float w)
13 | {
14 | X = x;
15 | Y = y;
16 | Z = z;
17 | W = w;
18 | }
19 |
20 | public Vector4(Vector4 other)
21 | {
22 | X = other.X;
23 | Y = other.Y;
24 | Z = other.Z;
25 | W = other.W;
26 | }
27 |
28 |
29 | public bool Equals(Vector4 other)
30 | {
31 | return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z) && W.Equals(other.W);
32 | }
33 |
34 | public override bool Equals(object obj)
35 | {
36 | if (ReferenceEquals(null, obj)) return false;
37 | return obj is Vector4 && Equals((Vector4) obj);
38 | }
39 |
40 | public override int GetHashCode()
41 | {
42 | unchecked
43 | {
44 | var hashCode = X.GetHashCode();
45 | hashCode = (hashCode * 397) ^ Y.GetHashCode();
46 | hashCode = (hashCode * 397) ^ Z.GetHashCode();
47 | hashCode = (hashCode * 397) ^ W.GetHashCode();
48 | return hashCode;
49 | }
50 | }
51 |
52 | public static bool operator ==(Vector4 left, Vector4 right)
53 | {
54 | return left.Equals(right);
55 | }
56 |
57 | public static bool operator !=(Vector4 left, Vector4 right)
58 | {
59 | return !left.Equals(right);
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AccessorSparse.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | public class AccessorSparse : GLTFProperty
6 | {
7 | ///
8 | /// Number of entries stored in the sparse array.
9 | /// 1
10 | ///
11 | public int Count;
12 |
13 | ///
14 | /// Index array of size `count` that points to those accessor attributes that
15 | /// deviate from their initialization value. Indices must strictly increase.
16 | ///
17 | public AccessorSparseIndices Indices;
18 |
19 | ///
20 | /// "Array of size `count` times number of components, storing the displaced
21 | /// accessor attributes pointed by `indices`. Substituted values must have
22 | /// the same `componentType` and number of components as the base accessor.
23 | ///
24 | public AccessorSparseValues Values;
25 |
26 | public AccessorSparse()
27 | {
28 | }
29 |
30 | public AccessorSparse(AccessorSparse accessorSparse, GLTFRoot gltfRoot) : base(accessorSparse)
31 | {
32 | if (accessorSparse == null) return;
33 |
34 | Count = accessorSparse.Count;
35 | Indices = new AccessorSparseIndices(accessorSparse.Indices, gltfRoot);
36 | Values = new AccessorSparseValues(accessorSparse.Values, gltfRoot);
37 | }
38 |
39 | public static AccessorSparse Deserialize(GLTFRoot root, JsonReader reader)
40 | {
41 | var accessorSparse = new AccessorSparse();
42 |
43 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
44 | {
45 | var curProp = reader.Value.ToString();
46 |
47 | switch (curProp)
48 | {
49 | case "count":
50 | accessorSparse.Count = reader.ReadAsInt32().Value;
51 | break;
52 | case "indices":
53 | accessorSparse.Indices = AccessorSparseIndices.Deserialize(root, reader);
54 | break;
55 | case "values":
56 | accessorSparse.Values = AccessorSparseValues.Deserialize(root, reader);
57 | break;
58 | default:
59 | accessorSparse.DefaultPropertyDeserializer(root, reader);
60 | break;
61 | }
62 | }
63 |
64 | return accessorSparse;
65 | }
66 |
67 | public override void Serialize(JsonWriter writer)
68 | {
69 | writer.WriteStartObject();
70 |
71 | writer.WritePropertyName("count");
72 | writer.WriteValue(Count);
73 |
74 | writer.WritePropertyName("indices");
75 | Indices.Serialize(writer);
76 |
77 | writer.WritePropertyName("values");
78 | Values.Serialize(writer);
79 |
80 | base.Serialize(writer);
81 |
82 | writer.WriteEndObject();
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AccessorSparseIndices.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | public class AccessorSparseIndices : GLTFProperty
6 | {
7 | ///
8 | /// The index of the bufferView with sparse indices.
9 | /// Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target.
10 | ///
11 | public BufferViewId BufferView;
12 |
13 | ///
14 | /// The offset relative to the start of the bufferView in bytes. Must be aligned.
15 | /// 0
16 | ///
17 | public int ByteOffset;
18 |
19 | ///
20 | /// The indices data type. Valid values correspond to WebGL enums:
21 | /// `5121` (UNSIGNED_BYTE)
22 | /// `5123` (UNSIGNED_SHORT)
23 | /// `5125` (UNSIGNED_INT)
24 | ///
25 | public GLTFComponentType ComponentType;
26 |
27 | public AccessorSparseIndices()
28 | {
29 | }
30 |
31 | public AccessorSparseIndices(AccessorSparseIndices accessorSparseIndices, GLTFRoot gltfRoot) : base(accessorSparseIndices)
32 | {
33 | if (accessorSparseIndices == null) return;
34 |
35 | BufferView = new BufferViewId(accessorSparseIndices.BufferView, gltfRoot);
36 | ByteOffset = accessorSparseIndices.ByteOffset;
37 | ComponentType = accessorSparseIndices.ComponentType;
38 | }
39 |
40 | public static AccessorSparseIndices Deserialize(GLTFRoot root, JsonReader reader)
41 | {
42 | var indices = new AccessorSparseIndices();
43 |
44 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
45 | {
46 | var curProp = reader.Value.ToString();
47 |
48 | switch (curProp)
49 | {
50 | case "bufferView":
51 | indices.BufferView = BufferViewId.Deserialize(root, reader);
52 | break;
53 | case "byteOffset":
54 | indices.ByteOffset = reader.ReadAsInt32().Value;
55 | break;
56 | case "componentType":
57 | indices.ComponentType = (GLTFComponentType) reader.ReadAsInt32().Value;
58 | break;
59 | default:
60 | indices.DefaultPropertyDeserializer(root, reader);
61 | break;
62 | }
63 | }
64 |
65 | return indices;
66 | }
67 |
68 | public override void Serialize(JsonWriter writer)
69 | {
70 | writer.WriteStartObject();
71 |
72 | writer.WritePropertyName("bufferView");
73 | writer.WriteValue(BufferView.Id);
74 |
75 | if (ByteOffset != 0)
76 | {
77 | writer.WritePropertyName("byteOffset");
78 | writer.WriteValue(ByteOffset);
79 | }
80 |
81 | writer.WritePropertyName("componentType");
82 | writer.WriteValue((int)ComponentType);
83 |
84 | base.Serialize(writer);
85 |
86 | writer.WriteEndObject();
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AccessorSparseValues.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | public class AccessorSparseValues : GLTFProperty
6 | {
7 | ///
8 | /// The index of the bufferView with sparse values.
9 | /// Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target.
10 | ///
11 | public BufferViewId BufferView;
12 |
13 | ///
14 | /// The offset relative to the start of the bufferView in bytes. Must be aligned.
15 | /// 0
16 | ///
17 | public int ByteOffset = 0;
18 |
19 | public AccessorSparseValues()
20 | {
21 | }
22 |
23 | public AccessorSparseValues(AccessorSparseValues accessorSparseValues, GLTFRoot gltfRoot) : base(accessorSparseValues)
24 | {
25 | if (accessorSparseValues == null) return;
26 |
27 | BufferView = new BufferViewId(accessorSparseValues.BufferView, gltfRoot);
28 | ByteOffset = accessorSparseValues.ByteOffset;
29 | }
30 |
31 | public static AccessorSparseValues Deserialize(GLTFRoot root, JsonReader reader)
32 | {
33 | var values = new AccessorSparseValues();
34 |
35 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
36 | {
37 | var curProp = reader.Value.ToString();
38 |
39 | switch (curProp)
40 | {
41 | case "bufferView":
42 | values.BufferView = BufferViewId.Deserialize(root, reader);
43 | break;
44 | case "byteOffset":
45 | values.ByteOffset = reader.ReadAsInt32().Value;
46 | break;
47 | default:
48 | values.DefaultPropertyDeserializer(root, reader);
49 | break;
50 | }
51 | }
52 |
53 | return values;
54 | }
55 |
56 | public override void Serialize(JsonWriter writer)
57 | {
58 | writer.WriteStartObject();
59 |
60 | writer.WritePropertyName("bufferView");
61 | writer.WriteValue(BufferView.Id);
62 |
63 | if (ByteOffset != 0)
64 | {
65 | writer.WritePropertyName("byteOffset");
66 | writer.WriteValue(ByteOffset);
67 | }
68 |
69 | base.Serialize(writer);
70 |
71 | writer.WriteEndObject();
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Animation.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using GLTF.Extensions;
3 | using Newtonsoft.Json;
4 |
5 | namespace GLTF.Schema
6 | {
7 | ///
8 | /// A keyframe animation.
9 | ///
10 | public class Animation : GLTFChildOfRootProperty
11 | {
12 | ///
13 | /// An array of channels, each of which targets an animation's sampler at a
14 | /// node's property. Different channels of the same animation can't have equal
15 | /// targets.
16 | ///
17 | public List Channels;
18 |
19 | ///
20 | /// An array of samplers that combines input and output accessors with an
21 | /// interpolation algorithm to define a keyframe graph (but not its target).
22 | ///
23 | public List Samplers;
24 |
25 | public static Animation Deserialize(GLTFRoot root, JsonReader reader)
26 | {
27 | var animation = new Animation();
28 |
29 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
30 | {
31 | var curProp = reader.Value.ToString();
32 |
33 | switch (curProp)
34 | {
35 | case "channels":
36 | animation.Channels = reader.ReadList(() => AnimationChannel.Deserialize(root, reader));
37 | break;
38 | case "samplers":
39 | animation.Samplers = reader.ReadList(() => AnimationSampler.Deserialize(root, reader));
40 | break;
41 | default:
42 | animation.DefaultPropertyDeserializer(root, reader);
43 | break;
44 | }
45 | }
46 |
47 | return animation;
48 | }
49 |
50 | public Animation()
51 | {
52 | }
53 |
54 | public Animation(Animation animation, GLTFRoot gltfRoot) : base(animation, gltfRoot)
55 | {
56 | Channels = new List(animation.Channels.Count);
57 | foreach (AnimationChannel channel in animation.Channels)
58 | {
59 | Channels.Add(new AnimationChannel(channel, gltfRoot));
60 | }
61 |
62 | Samplers = new List(animation.Samplers.Count);
63 | foreach (AnimationSampler sampler in animation.Samplers)
64 | {
65 | Samplers.Add(new AnimationSampler(sampler, gltfRoot));
66 | }
67 | }
68 |
69 | public override void Serialize(JsonWriter writer)
70 | {
71 | writer.WriteStartObject();
72 |
73 | if (Channels != null)
74 | {
75 | writer.WritePropertyName("channels");
76 | writer.WriteStartArray();
77 | foreach (var channel in Channels)
78 | {
79 | channel.Serialize(writer);
80 | }
81 | writer.WriteEndArray();
82 | }
83 |
84 | if (Samplers != null)
85 | {
86 | writer.WritePropertyName("samplers");
87 | writer.WriteStartArray();
88 | foreach (var sampler in Samplers)
89 | {
90 | sampler.Serialize(writer);
91 | }
92 | writer.WriteEndArray();
93 | }
94 |
95 | base.Serialize(writer);
96 |
97 | writer.WriteEndObject();
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AnimationChannel.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// Targets an animation's sampler at a node's property.
7 | ///
8 | public class AnimationChannel : GLTFProperty
9 | {
10 | ///
11 | /// The index of a sampler in this animation used to compute the value for the
12 | /// target, e.g., a node's translation, rotation, or scale (TRS).
13 | ///
14 | public SamplerId Sampler;
15 |
16 | ///
17 | /// The index of the node and TRS property to target.
18 | ///
19 | public AnimationChannelTarget Target;
20 |
21 | public AnimationChannel()
22 | {
23 | }
24 |
25 | public AnimationChannel(AnimationChannel animationChannel, GLTFRoot root) : base(animationChannel)
26 | {
27 | if (animationChannel == null) return;
28 |
29 | Sampler = new SamplerId(animationChannel.Sampler, root);
30 | Target = new AnimationChannelTarget(animationChannel.Target, root);
31 | }
32 |
33 | public static AnimationChannel Deserialize(GLTFRoot root, JsonReader reader)
34 | {
35 | var animationChannel = new AnimationChannel();
36 |
37 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
38 | {
39 | var curProp = reader.Value.ToString();
40 |
41 | switch (curProp)
42 | {
43 | case "sampler":
44 | animationChannel.Sampler = SamplerId.Deserialize(root, reader);
45 | break;
46 | case "target":
47 | animationChannel.Target = AnimationChannelTarget.Deserialize(root, reader);
48 | break;
49 | default:
50 | animationChannel.DefaultPropertyDeserializer(root, reader);
51 | break;
52 | }
53 | }
54 |
55 | return animationChannel;
56 | }
57 |
58 | public override void Serialize(JsonWriter writer)
59 | {
60 | writer.WriteStartObject();
61 |
62 | writer.WritePropertyName("sampler");
63 | writer.WriteValue(Sampler.Id);
64 |
65 | writer.WritePropertyName("target");
66 | Target.Serialize(writer);
67 |
68 | base.Serialize(writer);
69 |
70 | writer.WriteEndObject();
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AnimationChannelTarget.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using GLTF.Extensions;
3 | using Newtonsoft.Json;
4 |
5 | namespace GLTF.Schema
6 | {
7 | ///
8 | /// The index of the node and TRS property that an animation channel targets.
9 | ///
10 | public class AnimationChannelTarget : GLTFProperty
11 | {
12 | ///
13 | /// The index of the node to target.
14 | ///
15 | public NodeId Node;
16 |
17 | ///
18 | /// The name of the node's TRS property to modify.
19 | ///
20 | public GLTFAnimationChannelPath Path;
21 |
22 | public static AnimationChannelTarget Deserialize(GLTFRoot root, JsonReader reader)
23 | {
24 | var animationChannelTarget = new AnimationChannelTarget();
25 |
26 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
27 | {
28 | throw new Exception("Animation channel target must be an object.");
29 | }
30 |
31 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
32 | {
33 | var curProp = reader.Value.ToString();
34 |
35 | switch (curProp)
36 | {
37 | case "node":
38 | animationChannelTarget.Node = NodeId.Deserialize(root, reader);
39 | break;
40 | case "path":
41 | animationChannelTarget.Path = reader.ReadStringEnum();
42 | break;
43 | default:
44 | animationChannelTarget.DefaultPropertyDeserializer(root, reader);
45 | break;
46 | }
47 | }
48 |
49 | return animationChannelTarget;
50 | }
51 |
52 | public AnimationChannelTarget()
53 | {
54 | }
55 |
56 | public AnimationChannelTarget(AnimationChannelTarget channelTarget, GLTFRoot gltfRoot) : base(channelTarget)
57 | {
58 | if (channelTarget == null) return;
59 |
60 | Node = new NodeId(channelTarget.Node, gltfRoot);
61 | Path = channelTarget.Path;
62 | }
63 |
64 | public override void Serialize(JsonWriter writer)
65 | {
66 | writer.WriteStartObject();
67 |
68 | writer.WritePropertyName("node");
69 | writer.WriteValue(Node.Id);
70 |
71 | writer.WritePropertyName("path");
72 | writer.WriteValue(Path.ToString());
73 |
74 | base.Serialize(writer);
75 |
76 | writer.WriteEndObject();
77 | }
78 | }
79 |
80 | public enum GLTFAnimationChannelPath
81 | {
82 | translation,
83 | rotation,
84 | scale,
85 | weights,
86 | custom,
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/AnimationSampler.cs:
--------------------------------------------------------------------------------
1 | using GLTF.Extensions;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | public enum InterpolationType
7 | {
8 | LINEAR,
9 | STEP,
10 | CATMULLROMSPLINE,
11 | CUBICSPLINE
12 | }
13 |
14 | ///
15 | /// Combines input and output accessors with an interpolation algorithm to define a keyframe graph (but not its target).
16 | ///
17 | public class AnimationSampler : GLTFProperty
18 | {
19 | ///
20 | /// The index of an accessor containing keyframe input values, e.G., time.
21 | /// That accessor must have componentType `FLOAT`. The values represent time in
22 | /// seconds with `time[0] >= 0.0`, and strictly increasing values,
23 | /// i.e., `time[n + 1] > time[n]`
24 | ///
25 | public AccessorId Input;
26 |
27 | ///
28 | /// Interpolation algorithm. When an animation targets a node's rotation,
29 | /// and the animation's interpolation is `\"LINEAR\"`, spherical linear
30 | /// interpolation (slerp) should be used to interpolate quaternions. When
31 | /// interpolation is `\"STEP\"`, animated value remains constant to the value
32 | /// of the first point of the timeframe, until the next timeframe.
33 | ///
34 | public InterpolationType Interpolation;
35 |
36 | ///
37 | /// The index of an accessor, containing keyframe output values. Output and input
38 | /// accessors must have the same `count`. When sampler is used with TRS target,
39 | /// output accessor's componentType must be `FLOAT`.
40 | ///
41 | public AccessorId Output;
42 |
43 | public AnimationSampler()
44 | {
45 | }
46 |
47 | public AnimationSampler(AnimationSampler animationSampler, GLTFRoot gltfRoot) : base(animationSampler)
48 | {
49 | if (animationSampler == null) return;
50 |
51 | Input = new AccessorId(animationSampler.Input, gltfRoot);
52 | Interpolation = animationSampler.Interpolation;
53 | Output = new AccessorId(animationSampler.Output, gltfRoot);
54 | }
55 |
56 | public static AnimationSampler Deserialize(GLTFRoot root, JsonReader reader)
57 | {
58 | var animationSampler = new AnimationSampler();
59 |
60 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
61 | {
62 | var curProp = reader.Value.ToString();
63 |
64 | switch (curProp)
65 | {
66 | case "input":
67 | animationSampler.Input = AccessorId.Deserialize(root, reader);
68 | break;
69 | case "interpolation":
70 | animationSampler.Interpolation = reader.ReadStringEnum();
71 | break;
72 | case "output":
73 | animationSampler.Output = AccessorId.Deserialize(root, reader);
74 | break;
75 | default:
76 | animationSampler.DefaultPropertyDeserializer(root, reader);
77 | break;
78 | }
79 | }
80 |
81 | return animationSampler;
82 | }
83 |
84 | public override void Serialize(JsonWriter writer)
85 | {
86 | writer.WriteStartObject();
87 |
88 | writer.WritePropertyName("input");
89 | writer.WriteValue(Input.Id);
90 |
91 | if (Interpolation != InterpolationType.LINEAR)
92 | {
93 | writer.WritePropertyName("interpolation");
94 | writer.WriteValue(Interpolation.ToString());
95 | }
96 |
97 | writer.WritePropertyName("output");
98 | writer.WriteValue(Output.Id);
99 |
100 | base.Serialize(writer);
101 |
102 | writer.WriteEndObject();
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Asset.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | ///
7 | /// Metadata about the glTF asset.
8 | ///
9 | public class Asset : GLTFProperty
10 | {
11 | ///
12 | /// A copyright message suitable for display to credit the content creator.
13 | ///
14 | public string Copyright;
15 |
16 | ///
17 | /// Tool that generated this glTF model. Useful for debugging.
18 | ///
19 | public string Generator;
20 |
21 | ///
22 | /// The glTF version.
23 | ///
24 | public string Version;
25 |
26 | ///
27 | /// The minimum glTF version that this asset targets.
28 | ///
29 | public string MinVersion;
30 |
31 | public Asset()
32 | {
33 | }
34 |
35 | public Asset(Asset asset) : base(asset)
36 | {
37 | if (asset == null) return;
38 |
39 | Copyright = asset.Copyright;
40 | Generator = asset.Generator;
41 | Version = asset.Version;
42 | MinVersion = asset.MinVersion;
43 | }
44 |
45 | public static Asset Deserialize(GLTFRoot root, JsonReader reader)
46 | {
47 | var asset = new Asset();
48 |
49 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
50 | {
51 | throw new Exception("Asset must be an object.");
52 | }
53 |
54 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
55 | {
56 | var curProp = reader.Value.ToString();
57 |
58 | switch (curProp)
59 | {
60 | case "copyright":
61 | asset.Copyright = reader.ReadAsString();
62 | break;
63 | case "generator":
64 | asset.Generator = reader.ReadAsString();
65 | break;
66 | case "version":
67 | asset.Version = reader.ReadAsString();
68 | break;
69 | case "minVersion":
70 | asset.MinVersion = reader.ReadAsString();
71 | break;
72 | default:
73 | asset.DefaultPropertyDeserializer(root, reader);
74 | break;
75 | }
76 | }
77 |
78 | return asset;
79 | }
80 |
81 | public override void Serialize(JsonWriter writer)
82 | {
83 | writer.WriteStartObject();
84 |
85 | if (Copyright != null)
86 | {
87 | writer.WritePropertyName("copyright");
88 | writer.WriteValue(Copyright);
89 | }
90 |
91 | if (Generator != null)
92 | {
93 | writer.WritePropertyName("generator");
94 | writer.WriteValue(Generator);
95 | }
96 |
97 | writer.WritePropertyName("version");
98 | writer.WriteValue(Version);
99 |
100 | base.Serialize(writer);
101 |
102 | writer.WriteEndObject();
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Buffer.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// A buffer points to binary geometry, animation, or skins.
7 | ///
8 | public class Buffer : GLTFChildOfRootProperty
9 | {
10 | ///
11 | /// The uri of the buffer.
12 | /// Relative paths are relative to the .gltf file.
13 | /// Instead of referencing an external file, the uri can also be a data-uri.
14 | ///
15 | public string Uri;
16 |
17 | ///
18 | /// The length of the buffer in bytes.
19 | /// 0
20 | ///
21 | public int ByteLength;
22 |
23 | public Buffer()
24 | {
25 | }
26 |
27 | public Buffer(Buffer buffer, GLTFRoot gltfRoot) : base(buffer, gltfRoot)
28 | {
29 | if (buffer == null) return;
30 | Uri = buffer.Uri;
31 | ByteLength = buffer.ByteLength;
32 | }
33 |
34 | public static Buffer Deserialize(GLTFRoot root, JsonReader reader)
35 | {
36 | var buffer = new Buffer();
37 |
38 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
39 | {
40 | var curProp = reader.Value.ToString();
41 |
42 | switch (curProp)
43 | {
44 | case "uri":
45 | buffer.Uri = reader.ReadAsString();
46 | break;
47 | case "byteLength":
48 | buffer.ByteLength = reader.ReadAsInt32().Value;
49 | break;
50 | default:
51 | buffer.DefaultPropertyDeserializer(root, reader);
52 | break;
53 | }
54 | }
55 |
56 | return buffer;
57 | }
58 |
59 | public override void Serialize(JsonWriter writer)
60 | {
61 | writer.WriteStartObject();
62 |
63 | if (Uri != null)
64 | {
65 | writer.WritePropertyName("uri");
66 | writer.WriteValue(Uri);
67 | }
68 |
69 | writer.WritePropertyName("byteLength");
70 | writer.WriteValue(ByteLength);
71 |
72 | base.Serialize(writer);
73 |
74 | writer.WriteEndObject();
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/BufferView.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | public enum BufferViewTarget
6 | {
7 | None = 0,
8 | ArrayBuffer = 34962,
9 | ElementArrayBuffer = 34963,
10 | }
11 |
12 | ///
13 | /// A view into a buffer generally representing a subset of the buffer.
14 | ///
15 | public class BufferView : GLTFChildOfRootProperty
16 | {
17 | ///
18 | /// The index of the buffer.
19 | ///
20 | public BufferId Buffer;
21 |
22 | ///
23 | /// The offset into the buffer in bytes.
24 | /// 0
25 | ///
26 | public int ByteOffset;
27 |
28 | ///
29 | /// The length of the bufferView in bytes.
30 | /// 0
31 | ///
32 | public int ByteLength;
33 |
34 | ///
35 | /// The stride, in bytes, between vertex attributes or other interleavable data.
36 | /// When this is zero, data is tightly packed.
37 | /// 0
38 | /// 255
39 | ///
40 | public int ByteStride;
41 |
42 | ///
43 | /// The target that the WebGL buffer should be bound to.
44 | /// All valid values correspond to WebGL enums.
45 | /// When this is not provided, the bufferView contains animation or skin data.
46 | ///
47 | public BufferViewTarget Target = BufferViewTarget.None;
48 |
49 | public BufferView()
50 | {
51 | }
52 |
53 | public BufferView(BufferView bufferView, GLTFRoot gltfRoot) : base(bufferView, gltfRoot)
54 | {
55 | Buffer = new BufferId(bufferView.Buffer, gltfRoot);
56 | ByteOffset = bufferView.ByteOffset;
57 | ByteLength = bufferView.ByteLength;
58 | ByteStride = bufferView.ByteStride;
59 | Target = bufferView.Target;
60 | }
61 |
62 | public static BufferView Deserialize(GLTFRoot root, JsonReader reader)
63 | {
64 | var bufferView = new BufferView();
65 |
66 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
67 | {
68 | var curProp = reader.Value.ToString();
69 |
70 | switch (curProp)
71 | {
72 | case "buffer":
73 | bufferView.Buffer = BufferId.Deserialize(root, reader);
74 | break;
75 | case "byteOffset":
76 | bufferView.ByteOffset = reader.ReadAsInt32().Value;
77 | break;
78 | case "byteLength":
79 | bufferView.ByteLength = reader.ReadAsInt32().Value;
80 | break;
81 | case "byteStride":
82 | bufferView.ByteStride = reader.ReadAsInt32().Value;
83 | break;
84 | case "target":
85 | bufferView.Target = (BufferViewTarget)reader.ReadAsInt32().Value;
86 | break;
87 | default:
88 | bufferView.DefaultPropertyDeserializer(root, reader);
89 | break;
90 | }
91 | }
92 |
93 | return bufferView;
94 | }
95 |
96 | public override void Serialize(JsonWriter writer)
97 | {
98 | writer.WriteStartObject();
99 |
100 | writer.WritePropertyName("buffer");
101 | writer.WriteValue(Buffer.Id);
102 |
103 | if (ByteOffset != 0)
104 | {
105 | writer.WritePropertyName("byteOffset");
106 | writer.WriteValue(ByteOffset);
107 | }
108 |
109 | writer.WritePropertyName("byteLength");
110 | writer.WriteValue(ByteLength);
111 |
112 | if (ByteStride != 0)
113 | {
114 | writer.WritePropertyName("byteStride");
115 | writer.WriteValue(ByteStride);
116 | }
117 |
118 | if (Target != BufferViewTarget.None)
119 | {
120 | writer.WritePropertyName("target");
121 | writer.WriteValue((int)Target);
122 | }
123 |
124 | base.Serialize(writer);
125 |
126 | writer.WriteEndObject();
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Camera.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// A camera's projection. A node can reference a camera to apply a transform
7 | /// to place the camera in the scene
8 | ///
9 | public class Camera : GLTFChildOfRootProperty
10 | {
11 | ///
12 | /// An orthographic camera containing properties to create an orthographic
13 | /// projection matrix.
14 | ///
15 | public CameraOrthographic Orthographic;
16 |
17 | ///
18 | /// A perspective camera containing properties to create a perspective
19 | /// projection matrix.
20 | ///
21 | public CameraPerspective Perspective;
22 |
23 | ///
24 | /// Specifies if the camera uses a perspective or orthographic projection.
25 | /// Based on this, either the camera's `perspective` or `orthographic` property
26 | /// will be defined.
27 | ///
28 | public CameraType Type;
29 |
30 | public Camera()
31 | {
32 | }
33 |
34 | public Camera(Camera camera, GLTFRoot gltfRoot) : base(camera, gltfRoot)
35 | {
36 | if (camera == null) return;
37 |
38 | if (camera.Orthographic != null)
39 | {
40 | Orthographic = new CameraOrthographic(camera.Orthographic);
41 | }
42 |
43 | if (camera.Perspective != null)
44 | {
45 | Perspective = new CameraPerspective(camera.Perspective);
46 | }
47 |
48 | Type = camera.Type;
49 | }
50 |
51 | public static Camera Deserialize(GLTFRoot root, JsonReader reader)
52 | {
53 | var camera = new Camera();
54 |
55 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
56 | {
57 | var curProp = reader.Value.ToString();
58 |
59 | switch (curProp)
60 | {
61 | case "orthographic":
62 | camera.Orthographic = CameraOrthographic.Deserialize(root, reader);
63 | break;
64 | case "perspective":
65 | camera.Perspective = CameraPerspective.Deserialize(root, reader);
66 | break;
67 | default:
68 | camera.DefaultPropertyDeserializer(root, reader);
69 | break;
70 | }
71 | }
72 |
73 | return camera;
74 | }
75 |
76 | public override void Serialize(JsonWriter writer)
77 | {
78 | writer.WriteStartObject();
79 |
80 | if (Orthographic != null)
81 | {
82 | writer.WritePropertyName("orthographic");
83 | Orthographic.Serialize(writer);
84 | }
85 |
86 | if (Perspective != null)
87 | {
88 | writer.WritePropertyName("perspective");
89 | Perspective.Serialize(writer);
90 | }
91 |
92 | writer.WritePropertyName("type");
93 | writer.WriteValue(Type.ToString());
94 |
95 | base.Serialize(writer);
96 |
97 | writer.WriteEndObject();
98 | }
99 | }
100 |
101 | public enum CameraType
102 | {
103 | perspective,
104 | orthographic
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/CameraOrthographic.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | ///
7 | /// An orthographic camera containing properties to create an orthographic
8 | /// projection matrix.
9 | ///
10 | public class CameraOrthographic : GLTFProperty
11 | {
12 | ///
13 | /// The floating-point horizontal magnification of the view.
14 | ///
15 | public double XMag;
16 |
17 | ///
18 | /// The floating-point vertical magnification of the view.
19 | ///
20 | public double YMag;
21 |
22 | ///
23 | /// The floating-point distance to the far clipping plane.
24 | ///
25 | public double ZFar;
26 |
27 | ///
28 | /// The floating-point distance to the near clipping plane.
29 | ///
30 | public double ZNear;
31 |
32 | public CameraOrthographic()
33 | {
34 | }
35 |
36 | public CameraOrthographic(CameraOrthographic cameraOrthographic) : base(cameraOrthographic)
37 | {
38 | XMag = cameraOrthographic.XMag;
39 | YMag = cameraOrthographic.YMag;
40 | ZFar = cameraOrthographic.ZFar;
41 | ZNear = cameraOrthographic.ZNear;
42 | }
43 |
44 | public static CameraOrthographic Deserialize(GLTFRoot root, JsonReader reader)
45 | {
46 | var cameraOrthographic = new CameraOrthographic();
47 |
48 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
49 | {
50 | throw new Exception("Orthographic camera must be an object.");
51 | }
52 |
53 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
54 | {
55 | var curProp = reader.Value.ToString();
56 |
57 | switch (curProp)
58 | {
59 | case "xmag":
60 | cameraOrthographic.XMag = reader.ReadAsDouble().Value;
61 | break;
62 | case "ymag":
63 | cameraOrthographic.YMag = reader.ReadAsDouble().Value;
64 | break;
65 | case "zfar":
66 | cameraOrthographic.ZFar = reader.ReadAsDouble().Value;
67 | break;
68 | case "znear":
69 | cameraOrthographic.ZNear = reader.ReadAsDouble().Value;
70 | break;
71 | default:
72 | cameraOrthographic.DefaultPropertyDeserializer(root, reader);
73 | break;
74 | }
75 | }
76 |
77 | return cameraOrthographic;
78 | }
79 |
80 | public override void Serialize(JsonWriter writer)
81 | {
82 | writer.WriteStartObject();
83 |
84 | writer.WritePropertyName("xmag");
85 | writer.WriteValue(XMag);
86 |
87 | writer.WritePropertyName("Ymag");
88 | writer.WriteValue(YMag);
89 |
90 | writer.WritePropertyName("ZFar");
91 | writer.WriteValue(ZFar);
92 |
93 | writer.WritePropertyName("ZNear");
94 | writer.WriteValue(ZNear);
95 |
96 | base.Serialize(writer);
97 |
98 | writer.WriteEndObject();
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/CameraPerspective.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | ///
7 | /// A perspective camera containing properties to create a perspective projection
8 | /// matrix.
9 | ///
10 | public class CameraPerspective : GLTFProperty
11 | {
12 | ///
13 | /// The floating-point aspect ratio of the field of view.
14 | /// When this is undefined, the aspect ratio of the canvas is used.
15 | /// 0.0
16 | ///
17 | public double AspectRatio;
18 |
19 | ///
20 | /// The floating-point vertical field of view in radians.
21 | /// 0.0
22 | ///
23 | public double YFov;
24 |
25 | ///
26 | /// The floating-point distance to the far clipping plane. When defined,
27 | /// `zfar` must be greater than `znear`.
28 | /// If `zfar` is undefined, runtime must use infinite projection matrix.
29 | /// 0.0
30 | ///
31 | public double ZFar = double.PositiveInfinity;
32 |
33 | ///
34 | /// The floating-point distance to the near clipping plane.
35 | /// 0.0
36 | ///
37 | public double ZNear;
38 |
39 | public CameraPerspective()
40 | {
41 | }
42 |
43 | public CameraPerspective(CameraPerspective cameraPerspective) : base(cameraPerspective)
44 | {
45 | if (cameraPerspective == null) return;
46 |
47 | AspectRatio = cameraPerspective.AspectRatio;
48 | YFov = cameraPerspective.YFov;
49 | ZFar = cameraPerspective.ZFar;
50 | ZNear = cameraPerspective.ZNear;
51 | }
52 |
53 | public static CameraPerspective Deserialize(GLTFRoot root, JsonReader reader)
54 | {
55 | var cameraPerspective = new CameraPerspective();
56 |
57 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
58 | {
59 | throw new Exception("Perspective camera must be an object.");
60 | }
61 |
62 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
63 | {
64 | var curProp = reader.Value.ToString();
65 |
66 | switch (curProp)
67 | {
68 | case "aspectRatio":
69 | cameraPerspective.AspectRatio = reader.ReadAsDouble().Value;
70 | break;
71 | case "yfov":
72 | cameraPerspective.YFov = reader.ReadAsDouble().Value;
73 | break;
74 | case "zfar":
75 | cameraPerspective.ZFar = reader.ReadAsDouble().Value;
76 | break;
77 | case "znear":
78 | cameraPerspective.ZNear = reader.ReadAsDouble().Value;
79 | break;
80 | default:
81 | cameraPerspective.DefaultPropertyDeserializer(root, reader);
82 | break;
83 | }
84 | }
85 |
86 | return cameraPerspective;
87 | }
88 |
89 | public override void Serialize(JsonWriter writer)
90 | {
91 | writer.WriteStartObject();
92 |
93 | if (AspectRatio != 0)
94 | {
95 | writer.WritePropertyName("aspectRatio");
96 | writer.WriteValue(AspectRatio);
97 | }
98 |
99 | writer.WritePropertyName("yfov");
100 | writer.WriteValue(YFov);
101 |
102 | if (ZFar != double.PositiveInfinity)
103 | {
104 | writer.WritePropertyName("zfar");
105 | writer.WriteValue(ZFar);
106 | }
107 |
108 | writer.WritePropertyName("ZNear");
109 | writer.WriteValue(ZNear);
110 |
111 | base.Serialize(writer);
112 |
113 | writer.WriteEndObject();
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/GLTFChildOfRootProperty.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | public class GLTFChildOfRootProperty : GLTFProperty
6 | {
7 | ///
8 | /// The user-defined name of this object.
9 | /// This is not necessarily unique, e.g., an accessor and a buffer could have the same name,
10 | /// or two accessors could even have the same name.
11 | ///
12 | public string Name;
13 |
14 | public GLTFChildOfRootProperty()
15 | {
16 | }
17 |
18 | public GLTFChildOfRootProperty(GLTFChildOfRootProperty childOfRootProperty, GLTFRoot gltfRoot) : base(childOfRootProperty, gltfRoot)
19 | {
20 | if (childOfRootProperty == null) return;
21 |
22 | Name = childOfRootProperty.Name;
23 | }
24 |
25 | public new void DefaultPropertyDeserializer(GLTFRoot root, JsonReader reader)
26 | {
27 | switch (reader.Value.ToString())
28 | {
29 | case "name":
30 | Name = reader.ReadAsString();
31 | break;
32 | default:
33 | base.DefaultPropertyDeserializer(root, reader);
34 | break;
35 | }
36 | }
37 |
38 | public override void Serialize(JsonWriter writer)
39 | {
40 |
41 | if (Name != null)
42 | {
43 | writer.WritePropertyName("name");
44 | writer.WriteValue(Name);
45 | }
46 |
47 | base.Serialize(writer);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/IExtension.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json.Linq;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// General interface for extensions
7 | ///
8 | public interface IExtension
9 | {
10 | ///
11 | /// Serializes the extension to a property
12 | ///
13 | /// JProperty of extension
14 | JProperty Serialize();
15 |
16 | ///
17 | /// Clones the extension. When implementing note that root can be null if the extension is not attached to a GLTFChildOfRootProperty
18 | ///
19 | /// GLTFRoot is availible
20 | /// Cloned version of the extension
21 | IExtension Clone(GLTFRoot root);
22 | }
23 |
24 | ///
25 | /// Abstract class for factory which creates an extension.
26 | ///
27 | public abstract class ExtensionFactory
28 | {
29 | ///
30 | /// Name of the extension being created
31 | ///
32 | public string ExtensionName;
33 |
34 | ///
35 | /// Deserializes the input token
36 | ///
37 | /// Root node if needed for deserailization
38 | /// The token data
39 | ///
40 | public abstract IExtension Deserialize(GLTFRoot root, JProperty extensionToken);
41 | }
42 |
43 | ///
44 | /// Default implementation of extension in order to preserve any non explicitly overriden extension in the JSON
45 | ///
46 | public class DefaultExtension : IExtension
47 | {
48 | ///
49 | /// Extenion data as a JProperty
50 | ///
51 | public JProperty ExtensionData { get; internal set; }
52 |
53 | public IExtension Clone(GLTFRoot root)
54 | {
55 | return new DefaultExtension
56 | {
57 | ExtensionData = new JProperty(ExtensionData)
58 | };
59 | }
60 |
61 | public JProperty Serialize()
62 | {
63 | return ExtensionData;
64 | }
65 | }
66 |
67 | ///
68 | /// Default implementation of ExtensionFactory to keep around any extensions not directly referenced
69 | ///
70 | public class DefaultExtensionFactory : ExtensionFactory
71 | {
72 | public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
73 | {
74 | return new DefaultExtension
75 | {
76 | ExtensionData = extensionToken
77 | };
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Image.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System.Collections.Generic;
3 |
4 | namespace GLTF.Schema
5 | {
6 | ///
7 | /// Image data used to create a texture. Image can be referenced by URI or
8 | /// `bufferView` index. `mimeType` is required in the latter case.
9 | ///
10 | public class Image : GLTFChildOfRootProperty
11 | {
12 | ///
13 | /// The uri of the image. Relative paths are relative to the .gltf file.
14 | /// Instead of referencing an external file, the uri can also be a data-uri.
15 | /// The image format must be jpg, png, bmp, or gif.
16 | ///
17 | public string Uri;
18 |
19 | // modify by egret
20 | public List Uris;
21 |
22 | ///
23 | /// The image's MIME type.
24 | /// 1
25 | ///
26 | public string MimeType;
27 |
28 | ///
29 | /// The index of the bufferView that contains the image.
30 | /// Use this instead of the image's uri property.
31 | ///
32 | public BufferViewId BufferView;
33 |
34 | public Image()
35 | {
36 | }
37 |
38 | public Image(Image image, GLTFRoot gltfRoot) : base(image, gltfRoot)
39 | {
40 | if (image == null) return;
41 |
42 | Uri = image.Uri;
43 | MimeType = image.MimeType;
44 |
45 | if (image.BufferView != null)
46 | {
47 | BufferView = new BufferViewId(image.BufferView, gltfRoot);
48 | }
49 | }
50 |
51 | public static Image Deserialize(GLTFRoot root, JsonReader reader)
52 | {
53 | var image = new Image();
54 |
55 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
56 | {
57 | var curProp = reader.Value.ToString();
58 |
59 | switch (curProp)
60 | {
61 | case "uri":
62 | image.Uri = reader.ReadAsString();
63 | break;
64 | case "mimeType":
65 | image.MimeType = reader.ReadAsString();
66 | break;
67 | case "bufferView":
68 | image.BufferView = BufferViewId.Deserialize(root, reader);
69 | break;
70 | default:
71 | image.DefaultPropertyDeserializer(root, reader);
72 | break;
73 | }
74 | }
75 |
76 | return image;
77 | }
78 |
79 | public override void Serialize(JsonWriter writer)
80 | {
81 | writer.WriteStartObject();
82 |
83 | if (Uri != null)
84 | {
85 | writer.WritePropertyName("uri");
86 | writer.WriteValue(Uri);
87 | }
88 | else if (Uris != null)
89 | {
90 | writer.WritePropertyName("uri");
91 | writer.WriteStartArray();
92 | foreach (var uri in Uris)
93 | {
94 | writer.WriteValue(uri);
95 | }
96 |
97 | writer.WriteEndArray();
98 | }
99 |
100 | if (MimeType != null)
101 | {
102 | writer.WritePropertyName("mimeType");
103 | writer.WriteValue(Newtonsoft.Json.Linq.JValue.CreateString(MimeType).ToString());
104 | }
105 |
106 | if (BufferView != null)
107 | {
108 | writer.WritePropertyName("bufferView");
109 | writer.WriteValue(BufferView);
110 | }
111 |
112 | base.Serialize(writer);
113 |
114 | writer.WriteEndObject();
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/MaterialCommonConstant.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using GLTF.Extensions;
3 | using GLTF.Math;
4 | using Newtonsoft.Json;
5 |
6 | namespace GLTF.Schema
7 | {
8 | public class MaterialCommonConstant : GLTFProperty
9 | {
10 | ///
11 | /// Used to scale the ambient light contributions to this material
12 | ///
13 | public Color AmbientFactor = Color.White;
14 |
15 | ///
16 | /// Texture used to store pre-computed direct lighting
17 | ///
18 | public TextureInfo LightmapTexture;
19 |
20 | ///
21 | /// Scale factor for the lightmap texture
22 | ///
23 | public Color LightmapFactor = Color.White;
24 |
25 | public MaterialCommonConstant()
26 | {
27 | }
28 |
29 | public MaterialCommonConstant(MaterialCommonConstant materialCommonConstant, GLTFRoot gltfRoot) : base(materialCommonConstant)
30 | {
31 | if (materialCommonConstant == null) return;
32 |
33 | AmbientFactor = materialCommonConstant.AmbientFactor;
34 | LightmapTexture = new TextureInfo(materialCommonConstant.LightmapTexture, gltfRoot);
35 | LightmapFactor = materialCommonConstant.LightmapFactor;
36 | }
37 |
38 | public static MaterialCommonConstant Deserialize(GLTFRoot root, JsonReader reader)
39 | {
40 | var commonConstant = new MaterialCommonConstant();
41 |
42 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
43 | {
44 | throw new Exception("Asset must be an object.");
45 | }
46 |
47 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
48 | {
49 | var curProp = reader.Value.ToString();
50 |
51 | switch (curProp)
52 | {
53 | case "ambientFactor":
54 | commonConstant.AmbientFactor = reader.ReadAsRGBColor();
55 | break;
56 | case "lightmapTexture":
57 | commonConstant.LightmapTexture = TextureInfo.Deserialize(root, reader);
58 | break;
59 | case "lightmapFactor":
60 | commonConstant.LightmapFactor = reader.ReadAsRGBColor();
61 | break;
62 | default:
63 | commonConstant.DefaultPropertyDeserializer(root, reader);
64 | break;
65 | }
66 | }
67 |
68 | return commonConstant;
69 | }
70 |
71 | public override void Serialize(JsonWriter writer)
72 | {
73 | writer.WriteStartObject();
74 |
75 | if (AmbientFactor != Color.White)
76 | {
77 | writer.WritePropertyName("ambientFactor");
78 | writer.WriteStartArray();
79 | writer.WriteValue(AmbientFactor.R);
80 | writer.WriteValue(AmbientFactor.G);
81 | writer.WriteValue(AmbientFactor.B);
82 | writer.WriteEndArray();
83 | }
84 |
85 | if (LightmapTexture != null)
86 | {
87 | writer.WritePropertyName("lightmapTexture");
88 | LightmapTexture.Serialize(writer);
89 | }
90 |
91 | if (LightmapFactor != Color.White)
92 | {
93 | writer.WritePropertyName("lightmapFactor");
94 | writer.WriteStartArray();
95 | writer.WriteValue(LightmapFactor.R);
96 | writer.WriteValue(LightmapFactor.G);
97 | writer.WriteValue(LightmapFactor.B);
98 | writer.WriteEndArray();
99 | }
100 |
101 | base.Serialize(writer);
102 |
103 | writer.WriteEndObject();
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/MaterialNormalTextureInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | public class NormalTextureInfo : TextureInfo
7 | {
8 | public const string SCALE = "scale";
9 |
10 | ///
11 | /// The scalar multiplier applied to each normal vector of the texture.
12 | /// This value is ignored if normalTexture is not specified.
13 | /// This value is linear.
14 | ///
15 | public double Scale = 1.0f;
16 |
17 | public NormalTextureInfo()
18 | {
19 | }
20 |
21 | public NormalTextureInfo(NormalTextureInfo normalTextureInfo, GLTFRoot gltfRoot) : base(normalTextureInfo, gltfRoot)
22 | {
23 | Scale = normalTextureInfo.Scale;
24 | }
25 |
26 | public static new NormalTextureInfo Deserialize(GLTFRoot root, JsonReader reader)
27 | {
28 | var textureInfo = new NormalTextureInfo();
29 |
30 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
31 | {
32 | throw new Exception("Asset must be an object.");
33 | }
34 |
35 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
36 | {
37 | var curProp = reader.Value.ToString();
38 |
39 | switch (curProp)
40 | {
41 | case INDEX:
42 | textureInfo.Index = TextureId.Deserialize(root, reader);
43 | break;
44 | case TEXCOORD:
45 | textureInfo.TexCoord = reader.ReadAsInt32().Value;
46 | break;
47 | case SCALE:
48 | textureInfo.Scale = reader.ReadAsDouble().Value;
49 | break;
50 | default:
51 | textureInfo.DefaultPropertyDeserializer(root, reader);
52 | break;
53 | }
54 | }
55 |
56 | return textureInfo;
57 | }
58 |
59 | public override void Serialize(JsonWriter writer) {
60 | writer.WriteStartObject();
61 |
62 | if (Scale != 1.0f)
63 | {
64 | writer.WritePropertyName("scale");
65 | writer.WriteValue(Scale);
66 | }
67 |
68 | // Write the parent class' properties only.
69 | // Don't accidentally call write start/end object.
70 | base.SerializeProperties(writer);
71 |
72 | writer.WriteEndObject();
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/MaterialOcclusionTextureInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | public class OcclusionTextureInfo : TextureInfo
7 | {
8 | public const string STRENGTH = "strength";
9 |
10 | ///
11 | /// A scalar multiplier controlling the amount of occlusion applied.
12 | /// A value of 0.0 means no occlusion.
13 | /// A value of 1.0 means full occlusion.
14 | /// This value is ignored if the corresponding texture is not specified.
15 | /// This value is linear.
16 | /// 0.0
17 | /// 1.0
18 | ///
19 | public double Strength = 1.0f;
20 |
21 | public OcclusionTextureInfo()
22 | {
23 | }
24 |
25 | public OcclusionTextureInfo(OcclusionTextureInfo occulisionTextureInfo, GLTFRoot gltfRoot) : base(occulisionTextureInfo, gltfRoot)
26 | {
27 | Strength = occulisionTextureInfo.Strength;
28 | }
29 |
30 | public static new OcclusionTextureInfo Deserialize(GLTFRoot root, JsonReader reader)
31 | {
32 | var textureInfo = new OcclusionTextureInfo();
33 |
34 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
35 | {
36 | throw new Exception("Asset must be an object.");
37 | }
38 |
39 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
40 | {
41 | var curProp = reader.Value.ToString();
42 |
43 | switch (curProp)
44 | {
45 | case INDEX:
46 | textureInfo.Index = TextureId.Deserialize(root, reader);
47 | break;
48 | case TEXCOORD:
49 | textureInfo.TexCoord = reader.ReadAsInt32().Value;
50 | break;
51 | case STRENGTH:
52 | textureInfo.Strength = reader.ReadAsDouble().Value;
53 | break;
54 | default:
55 | textureInfo.DefaultPropertyDeserializer(root, reader);
56 | break;
57 | }
58 | }
59 |
60 | return textureInfo;
61 | }
62 |
63 | public override void Serialize(JsonWriter writer) {
64 | writer.WriteStartObject();
65 |
66 | if (Strength != 1.0f)
67 | {
68 | writer.WritePropertyName("strength");
69 | writer.WriteValue(Strength);
70 | }
71 |
72 | // Write the parent class' properties only.
73 | // Don't accidentally call write start/end object.
74 | base.SerializeProperties(writer);
75 |
76 | writer.WriteEndObject();
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Mesh.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 | using GLTF.Extensions;
4 | using Newtonsoft.Json;
5 |
6 | namespace GLTF.Schema
7 | {
8 | ///
9 | /// A set of primitives to be rendered. A node can contain one or more meshes.
10 | /// A node's transform places the mesh in the scene.
11 | ///
12 | public class Mesh : GLTFChildOfRootProperty
13 | {
14 | ///
15 | /// An array of primitives, each defining geometry to be rendered with
16 | /// a material.
17 | /// 1
18 | ///
19 | public List Primitives;
20 |
21 | ///
22 | /// Array of weights to be applied to the Morph Targets.
23 | /// 0
24 | ///
25 | public List Weights;
26 |
27 | public Mesh()
28 | {
29 | }
30 |
31 | public Mesh(Mesh mesh, GLTFRoot gltfRoot) : base(mesh, gltfRoot)
32 | {
33 | if (mesh == null) return;
34 |
35 | if (mesh.Primitives != null)
36 | {
37 | Primitives = new List(mesh.Primitives.Count);
38 |
39 | foreach (MeshPrimitive primitive in mesh.Primitives)
40 | {
41 | Primitives.Add(new MeshPrimitive(primitive, gltfRoot));
42 | }
43 | }
44 |
45 | if (mesh.Weights != null)
46 | {
47 | Weights = mesh.Weights.ToList();
48 | }
49 | }
50 |
51 |
52 | public static Mesh Deserialize(GLTFRoot root, JsonReader reader)
53 | {
54 | var mesh = new Mesh();
55 |
56 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
57 | {
58 | var curProp = reader.Value.ToString();
59 |
60 | switch (curProp)
61 | {
62 | case "primitives":
63 | mesh.Primitives = reader.ReadList(() => MeshPrimitive.Deserialize(root, reader));
64 | break;
65 | case "weights":
66 | mesh.Weights = reader.ReadDoubleList();
67 | break;
68 | default:
69 | mesh.DefaultPropertyDeserializer(root, reader);
70 | break;
71 | }
72 | }
73 |
74 | return mesh;
75 | }
76 |
77 | public override void Serialize(JsonWriter writer)
78 | {
79 | writer.WriteStartObject();
80 |
81 | if (Primitives != null && Primitives.Count > 0)
82 | {
83 | writer.WritePropertyName("primitives");
84 | writer.WriteStartArray();
85 | foreach (var primitive in Primitives)
86 | {
87 | primitive.Serialize(writer);
88 | }
89 | writer.WriteEndArray();
90 | }
91 |
92 | if (Weights != null && Weights.Count > 0)
93 | {
94 | writer.WritePropertyName("weights");
95 | writer.WriteStartArray();
96 | foreach (var weight in Weights)
97 | {
98 | writer.WriteValue(weight);
99 | }
100 | writer.WriteEndArray();
101 | }
102 |
103 | base.Serialize(writer);
104 |
105 | writer.WriteEndObject();
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Sampler.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// Texture sampler properties for filtering and wrapping modes.
7 | ///
8 | public class Sampler : GLTFChildOfRootProperty
9 | {
10 | ///
11 | /// Magnification filter.
12 | /// Valid values correspond to WebGL enums: `9728` (NEAREST) and `9729` (LINEAR).
13 | ///
14 | public MagFilterMode MagFilter = MagFilterMode.Linear;
15 |
16 | ///
17 | /// Minification filter. All valid values correspond to WebGL enums.
18 | ///
19 | public MinFilterMode MinFilter = MinFilterMode.NearestMipmapLinear;
20 |
21 | ///
22 | /// s wrapping mode. All valid values correspond to WebGL enums.
23 | ///
24 | public WrapMode WrapS = WrapMode.Repeat;
25 |
26 | ///
27 | /// t wrapping mode. All valid values correspond to WebGL enums.
28 | ///
29 | public WrapMode WrapT = WrapMode.Repeat;
30 |
31 | public Sampler()
32 | {
33 | }
34 |
35 | public Sampler(Sampler sampler, GLTFRoot gltfRoot) : base(sampler, gltfRoot)
36 | {
37 | if (sampler == null) return;
38 |
39 | MagFilter = sampler.MagFilter;
40 | MinFilter = sampler.MinFilter;
41 | WrapS = sampler.WrapS;
42 | WrapT = sampler.WrapT;
43 | }
44 |
45 | public static Sampler Deserialize(GLTFRoot root, JsonReader reader)
46 | {
47 | var sampler = new Sampler();
48 |
49 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
50 | {
51 | var curProp = reader.Value.ToString();
52 |
53 | switch (curProp)
54 | {
55 | case "magFilter":
56 | sampler.MagFilter = (MagFilterMode)reader.ReadAsInt32();
57 | break;
58 | case "minFilter":
59 | sampler.MinFilter = (MinFilterMode)reader.ReadAsInt32();
60 | break;
61 | case "wrapS":
62 | sampler.WrapS = (WrapMode)reader.ReadAsInt32();
63 | break;
64 | case "wrapT":
65 | sampler.WrapT = (WrapMode)reader.ReadAsInt32();
66 | break;
67 | default:
68 | sampler.DefaultPropertyDeserializer(root, reader);
69 | break;
70 | }
71 | }
72 |
73 | return sampler;
74 | }
75 |
76 | public override void Serialize(JsonWriter writer)
77 | {
78 | writer.WriteStartObject();
79 |
80 | //modify by egret
81 | // if (MagFilter != MagFilterMode.Linear)
82 | if (MagFilter != MagFilterMode.Nearest)
83 | {
84 | writer.WritePropertyName("magFilter");
85 | writer.WriteValue((int)MagFilter);
86 | }
87 |
88 | //modify by egret
89 | // if (MinFilter != MinFilterMode.NearestMipmapLinear)
90 | if (MinFilter != MinFilterMode.Nearest)
91 | {
92 | writer.WritePropertyName("minFilter");
93 | writer.WriteValue((int)MinFilter);
94 | }
95 |
96 | if (WrapS != WrapMode.Repeat)
97 | {
98 | writer.WritePropertyName("WrapS");
99 | writer.WriteValue((int)WrapS);
100 | }
101 |
102 | if (WrapT != WrapMode.Repeat)
103 | {
104 | writer.WritePropertyName("WrapT");
105 | writer.WriteValue((int)WrapT);
106 | }
107 |
108 | base.Serialize(writer);
109 |
110 | writer.WriteEndObject();
111 | }
112 | }
113 |
114 | ///
115 | /// Magnification filter mode.
116 | ///
117 | public enum MagFilterMode
118 | {
119 | None = 0,
120 | Nearest = 9728,
121 | Linear = 9729,
122 | }
123 |
124 | ///
125 | /// Minification filter mode.
126 | ///
127 | public enum MinFilterMode
128 | {
129 | None = 0,
130 | Nearest = 9728,
131 | Linear = 9729,
132 | NearestMipmapNearest = 9984,
133 | LinearMipmapNearest = 9985,
134 | NearestMipmapLinear = 9986,
135 | LinearMipmapLinear = 9987
136 | }
137 |
138 | ///
139 | /// Texture wrap mode.
140 | ///
141 | public enum WrapMode
142 | {
143 | None = 0,
144 | ClampToEdge = 33071,
145 | MirroredRepeat = 33648,
146 | Repeat = 10497
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Scene.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Newtonsoft.Json;
3 |
4 | namespace GLTF.Schema
5 | {
6 | ///
7 | /// The root nodes of a scene.
8 | ///
9 | public class Scene : GLTFChildOfRootProperty
10 | {
11 | ///
12 | /// The indices of each root node.
13 | ///
14 | public List Nodes;
15 |
16 | public Scene()
17 | {
18 | }
19 |
20 | public Scene(Scene scene, GLTFRoot gltfRoot) : base(scene, gltfRoot)
21 | {
22 | if (scene == null) return;
23 |
24 | if (scene.Nodes != null)
25 | {
26 | Nodes = new List(scene.Nodes.Count);
27 | foreach (NodeId node in scene.Nodes)
28 | {
29 | Nodes.Add(new NodeId(node, gltfRoot));
30 | }
31 | }
32 | }
33 |
34 | public static Scene Deserialize(GLTFRoot root, JsonReader reader)
35 | {
36 | var scene = new Scene();
37 |
38 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
39 | {
40 | var curProp = reader.Value.ToString();
41 |
42 | switch (curProp)
43 | {
44 | case "nodes":
45 | scene.Nodes = NodeId.ReadList(root, reader);
46 | break;
47 | default:
48 | scene.DefaultPropertyDeserializer(root, reader);
49 | break;
50 | }
51 | }
52 |
53 | return scene;
54 | }
55 |
56 | public override void Serialize(JsonWriter writer)
57 | {
58 | writer.WriteStartObject();
59 |
60 | if (Nodes != null && Nodes.Count > 0)
61 | {
62 | writer.WritePropertyName("nodes");
63 | writer.WriteStartArray();
64 | foreach (var node in Nodes)
65 | {
66 | writer.WriteValue(node.Id);
67 | }
68 | writer.WriteEndArray();
69 | }
70 |
71 | base.Serialize(writer);
72 |
73 | writer.WriteEndObject();
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Skin.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using GLTF.Extensions;
3 | using Newtonsoft.Json;
4 |
5 | namespace GLTF.Schema
6 | {
7 | ///
8 | /// Joints and matrices defining a skin.
9 | ///
10 | public class Skin : GLTFChildOfRootProperty
11 | {
12 | ///
13 | /// The index of the accessor containing the floating-point 4x4 inverse-bind matrices.
14 | /// The default is that each matrix is a 4x4 Identity matrix, which implies that inverse-bind
15 | /// matrices were pre-applied.
16 | ///
17 | public AccessorId InverseBindMatrices;
18 |
19 | ///
20 | /// The index of the node used as a skeleton root.
21 | /// When undefined, joints transforms resolve to scene root.
22 | ///
23 | public NodeId Skeleton;
24 |
25 | ///
26 | /// Indices of skeleton nodes, used as joints in this skin. The array length must be the
27 | // same as the `count` property of the `inverseBindMatrices` accessor (when defined).
28 | ///
29 | public List Joints;
30 |
31 | public Skin()
32 | {
33 | }
34 |
35 | public Skin(Skin skin, GLTFRoot gltfRoot) : base(skin, gltfRoot)
36 | {
37 | if (skin == null) return;
38 |
39 | if (skin.InverseBindMatrices != null)
40 | {
41 | InverseBindMatrices = new AccessorId(skin.InverseBindMatrices, gltfRoot);
42 | }
43 |
44 | if (skin.Skeleton != null)
45 | {
46 | Skeleton = new NodeId(skin.Skeleton, gltfRoot);
47 | }
48 |
49 | if (skin.Joints != null)
50 | {
51 | Joints = new List(skin.Joints.Count);
52 | foreach (NodeId joint in skin.Joints)
53 | {
54 | Joints.Add(new NodeId(joint, gltfRoot));
55 | }
56 | }
57 | }
58 |
59 | public static Skin Deserialize(GLTFRoot root, JsonReader reader)
60 | {
61 | var skin = new Skin();
62 |
63 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
64 | {
65 | var curProp = reader.Value.ToString();
66 |
67 | switch (curProp)
68 | {
69 | case "inverseBindMatrices":
70 | skin.InverseBindMatrices = AccessorId.Deserialize(root, reader);
71 | break;
72 | case "skeleton":
73 | skin.Skeleton = NodeId.Deserialize(root, reader);
74 | break;
75 | case "joints":
76 | skin.Joints = new List();
77 | List ids = reader.ReadInt32List();
78 | for (int i = 0; i < ids.Count; i++)
79 | {
80 | skin.Joints.Add(new NodeId()
81 | {
82 | Id = ids[i],
83 | Root = root
84 | });
85 | }
86 | break;
87 | default:
88 | skin.DefaultPropertyDeserializer(root, reader);
89 | break;
90 | }
91 | }
92 |
93 | return skin;
94 | }
95 |
96 | public override void Serialize(JsonWriter writer)
97 | {
98 | writer.WriteStartObject();
99 |
100 | if (InverseBindMatrices != null)
101 | {
102 | writer.WritePropertyName("inverseBindMatrices");
103 | writer.WriteValue(InverseBindMatrices.Id);
104 | }
105 |
106 | if (Skeleton != null)
107 | {
108 | writer.WritePropertyName("skeleton");
109 | writer.WriteValue(Skeleton.Id);
110 | }
111 |
112 | if (Joints != null && Joints.Count > 0)
113 | {
114 | writer.WritePropertyName("joints");
115 | writer.WriteStartArray();
116 | foreach (var joint in Joints)
117 | {
118 | writer.WriteValue(joint.Id);
119 | }
120 | writer.WriteEndArray();
121 | }
122 |
123 | base.Serialize(writer);
124 |
125 | writer.WriteEndObject();
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/Texture.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace GLTF.Schema
4 | {
5 | ///
6 | /// A texture and its sampler.
7 | ///
8 | public class Texture : GLTFChildOfRootProperty
9 | {
10 | ///
11 | /// The index of the sampler used by this texture.
12 | ///
13 | public SamplerId Sampler;
14 |
15 | ///
16 | /// The index of the image used by this texture.
17 | ///
18 | public ImageId Source;
19 |
20 | public Texture()
21 | {
22 | }
23 |
24 | public Texture(Texture texture, GLTFRoot gltfRoot) : base(texture, gltfRoot)
25 | {
26 | if (texture == null) return;
27 |
28 | if (texture.Sampler != null)
29 | {
30 | Sampler = new SamplerId(texture.Sampler, gltfRoot);
31 | }
32 |
33 | if (texture.Source != null)
34 | {
35 | Source = new ImageId(texture.Source, gltfRoot);
36 | }
37 | }
38 |
39 | public static Texture Deserialize(GLTFRoot root, JsonReader reader)
40 | {
41 | var texture = new Texture();
42 |
43 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
44 | {
45 | var curProp = reader.Value.ToString();
46 |
47 | switch (curProp)
48 | {
49 | case "sampler":
50 | texture.Sampler = SamplerId.Deserialize(root, reader);
51 | break;
52 | case "source":
53 | texture.Source = ImageId.Deserialize(root, reader);
54 | break;
55 | default:
56 | texture.DefaultPropertyDeserializer(root, reader);
57 | break;
58 | }
59 | }
60 |
61 | return texture;
62 | }
63 |
64 | public override void Serialize(JsonWriter writer)
65 | {
66 | writer.WriteStartObject();
67 |
68 | if (Sampler != null)
69 | {
70 | writer.WritePropertyName("sampler");
71 | writer.WriteValue(Sampler.Id);
72 | }
73 |
74 | if (Source != null)
75 | {
76 | writer.WritePropertyName("source");
77 | writer.WriteValue(Source.Id);
78 | }
79 |
80 | base.Serialize(writer);
81 |
82 | writer.WriteEndObject();
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/GLTFSerialization/Schema/TextureInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Newtonsoft.Json;
3 | using Newtonsoft.Json.Linq;
4 |
5 | namespace GLTF.Schema
6 | {
7 | ///
8 | /// Reference to a texture.
9 | ///
10 | public class TextureInfo : GLTFProperty
11 | {
12 | public const string INDEX = "index";
13 | public const string TEXCOORD = "texCoord";
14 |
15 | ///
16 | /// The index of the texture.
17 | ///
18 | public TextureId Index;
19 |
20 | ///
21 | /// This integer value is used to construct a string in the format
22 | /// TEXCOORD_ which is a reference to a key in
23 | /// mesh.primitives.attributes (e.g. A value of 0 corresponds to TEXCOORD_0).
24 | ///
25 | public int TexCoord = 0;
26 |
27 | public TextureInfo()
28 | {
29 | }
30 |
31 | public TextureInfo(TextureInfo textureInfo, GLTFRoot gltfRoot) : base(textureInfo)
32 | {
33 | if (textureInfo == null) return;
34 |
35 | Index = new TextureId(textureInfo.Index, gltfRoot);
36 | TexCoord = textureInfo.TexCoord;
37 | }
38 |
39 | public static TextureInfo Deserialize(GLTFRoot root, JsonReader reader)
40 | {
41 | var textureInfo = new TextureInfo();
42 |
43 | if (reader.Read() && reader.TokenType != JsonToken.StartObject)
44 | {
45 | throw new Exception("Asset must be an object.");
46 | }
47 |
48 | while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
49 | {
50 | var curProp = reader.Value.ToString();
51 |
52 | switch (curProp)
53 | {
54 | case INDEX:
55 | textureInfo.Index = TextureId.Deserialize(root, reader);
56 | break;
57 | case TEXCOORD:
58 | textureInfo.TexCoord = reader.ReadAsInt32().Value;
59 | break;
60 | default:
61 | textureInfo.DefaultPropertyDeserializer(root, reader);
62 | break;
63 | }
64 | }
65 |
66 | return textureInfo;
67 | }
68 |
69 | public static TextureInfo Deserialize(GLTFRoot root, JProperty jProperty)
70 | {
71 | var textureInfo = new TextureInfo();
72 |
73 | foreach (JToken child in jProperty.Children())
74 | {
75 | if(child is JProperty)
76 | {
77 | JProperty childAsJProperty = child as JProperty;
78 | switch(childAsJProperty.Name)
79 | {
80 | case "index":
81 | textureInfo.Index = TextureId.Deserialize(root, childAsJProperty);
82 | break;
83 | case "texCoord":
84 | textureInfo.TexCoord = (int)childAsJProperty.Value;
85 | break;
86 | default:
87 | // todo: implement
88 | //textureInfo.DefaultPropertyDeserializer(root, childAsJProperty);
89 | break;
90 | }
91 | }
92 | }
93 |
94 | return textureInfo;
95 | }
96 |
97 | public override void Serialize(JsonWriter writer)
98 | {
99 | writer.WriteStartObject();
100 |
101 | SerializeProperties(writer);
102 |
103 | writer.WriteEndObject();
104 | }
105 |
106 | public void SerializeProperties(JsonWriter writer)
107 | {
108 | writer.WritePropertyName(INDEX);
109 | writer.WriteValue(Index.Id);
110 |
111 | if (TexCoord != 0)
112 | {
113 | writer.WritePropertyName(TEXCOORD);
114 | writer.WriteValue(TexCoord);
115 | }
116 |
117 | base.Serialize(writer);
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Async/AsyncAction.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | #if WINDOWS_UWP
4 | using System.Threading.Tasks;
5 | #else
6 | using System.Threading;
7 | #endif
8 |
9 | namespace UnityGLTF
10 | {
11 | ///
12 | /// Creates a thread to run multithreaded operations on
13 | ///
14 | public class AsyncAction
15 | {
16 | private bool _workerThreadRunning = false;
17 | private Exception _savedException;
18 |
19 | public IEnumerator RunOnWorkerThread(Action action)
20 | {
21 | _workerThreadRunning = true;
22 |
23 | #if WINDOWS_UWP
24 | Task.Factory.StartNew(() =>
25 | #else
26 | ThreadPool.QueueUserWorkItem((_) =>
27 | #endif
28 | {
29 | try
30 | {
31 | action();
32 | }
33 | catch (Exception e)
34 | {
35 | _savedException = e;
36 | }
37 |
38 | _workerThreadRunning = false;
39 | });
40 |
41 | yield return Wait();
42 |
43 | if (_savedException != null)
44 | {
45 | throw _savedException;
46 | }
47 | }
48 |
49 | private IEnumerator Wait()
50 | {
51 | while (_workerThreadRunning)
52 | {
53 | yield return null;
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Async/TaskExtensions.cs:
--------------------------------------------------------------------------------
1 | #if WINDOWS_UWP
2 | using System.Collections;
3 | using System.Threading.Tasks;
4 |
5 | namespace UnityGLTF
6 | {
7 | public static class TaskExtensions
8 | {
9 | public static IEnumerator AsCoroutine(this Task task)
10 | {
11 | while (!task.IsCompleted)
12 | {
13 | yield return null;
14 | }
15 | }
16 | }
17 | }
18 | #endif
19 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/AnimationCacheData.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using GLTF;
6 |
7 | namespace UnityGLTF.Cache
8 | {
9 | public struct AnimationSamplerCacheData
10 | {
11 | public AttributeAccessor Input;
12 | public AttributeAccessor Output;
13 | }
14 |
15 | public class AnimationCacheData
16 | {
17 | public UnityEngine.AnimationClip LoadedAnimationClip { get; set; }
18 | public AnimationSamplerCacheData[] Samplers { get; set; }
19 |
20 | public AnimationCacheData(int samplerCount)
21 | {
22 | Samplers = new AnimationSamplerCacheData[samplerCount];
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/AssetCache.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 | using System.IO;
5 |
6 | namespace UnityGLTF.Cache
7 | {
8 | ///
9 | /// Caches data in order to construct a unity object
10 | ///
11 | public class AssetCache : IDisposable
12 | {
13 | ///
14 | /// Streams to the images to be loaded
15 | ///
16 | public Stream[] ImageStreamCache { get; private set; }
17 |
18 | ///
19 | /// Loaded raw texture data
20 | ///
21 | public Texture2D[] ImageCache { get; private set; }
22 |
23 | ///
24 | /// Textures to be used for assets. Textures from image cache with samplers applied
25 | ///
26 | public TextureCacheData[] TextureCache { get; private set; }
27 |
28 | ///
29 | /// Cache for materials to be applied to the meshes
30 | ///
31 | public MaterialCacheData[] MaterialCache { get; private set; }
32 |
33 | ///
34 | /// Byte buffers that represent the binary contents that get parsed
35 | ///
36 | public BufferCacheData[] BufferCache { get; private set; }
37 |
38 | ///
39 | /// Cache of loaded meshes
40 | ///
41 | public List MeshCache { get; private set; }
42 |
43 | ///
44 | /// Cache of loaded animations
45 | ///
46 | public AnimationCacheData[] AnimationCache { get; private set; }
47 |
48 | ///
49 | /// Cache of loaded node objects
50 | ///
51 | public GameObject[] NodeCache { get; private set; }
52 |
53 | ///
54 | /// Creates an asset cache which caches objects used in scene
55 | ///
56 | ///
57 | ///
58 | ///
59 | ///
60 | ///
61 | ///
62 | public AssetCache(int imageCacheSize, int textureCacheSize, int materialCacheSize, int bufferCacheSize,
63 | int meshCacheSize, int nodeCacheSize, int animationCacheSize)
64 | {
65 | ImageCache = new Texture2D[imageCacheSize];
66 | ImageStreamCache = new Stream[imageCacheSize];
67 | TextureCache = new TextureCacheData[textureCacheSize];
68 | MaterialCache = new MaterialCacheData[materialCacheSize];
69 | BufferCache = new BufferCacheData[bufferCacheSize];
70 | MeshCache = new List(meshCacheSize);
71 | for(int i = 0; i < meshCacheSize; ++i)
72 | {
73 | MeshCache.Add(null);
74 | }
75 |
76 | NodeCache = new GameObject[nodeCacheSize];
77 | AnimationCache = new AnimationCacheData[animationCacheSize];
78 | }
79 |
80 | public void Dispose()
81 | {
82 | ImageCache = null;
83 | ImageStreamCache = null;
84 | TextureCache = null;
85 | MaterialCache = null;
86 | foreach(BufferCacheData bufferCacheData in BufferCache)
87 | {
88 | if(bufferCacheData != null && bufferCacheData.Stream != null)
89 | {
90 | #if !WINDOWS_UWP
91 | bufferCacheData.Stream.Close();
92 | #else
93 | bufferCacheData.Stream.Dispose();
94 | #endif
95 | }
96 | }
97 | MeshCache = null;
98 | AnimationCache = null;
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/BufferCacheData.cs:
--------------------------------------------------------------------------------
1 | namespace UnityGLTF.Cache
2 | {
3 | public class BufferCacheData
4 | {
5 | public long ChunkOffset { get; set; }
6 | public System.IO.Stream Stream { get; set; }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/MaterialCacheData.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace UnityGLTF.Cache
4 | {
5 | public class MaterialCacheData
6 | {
7 | public Material UnityMaterial { get; set; }
8 | public Material UnityMaterialWithVertexColor { get; set; }
9 | public GLTF.Schema.Material GLTFMaterial { get; set; }
10 |
11 | public Material GetContents(bool useVertexColors)
12 | {
13 | return useVertexColors ? UnityMaterialWithVertexColor : UnityMaterial;
14 | }
15 |
16 | ///
17 | /// Unloads the materials in this cache.
18 | ///
19 | public void Unload()
20 | {
21 | if (UnityMaterial != null)
22 | {
23 | Object.Destroy(UnityMaterial);
24 | }
25 |
26 | if (UnityMaterialWithVertexColor != null)
27 | {
28 | Object.Destroy(UnityMaterialWithVertexColor);
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/MeshCacheData.cs:
--------------------------------------------------------------------------------
1 | using GLTF;
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | namespace UnityGLTF.Cache
6 | {
7 | public class MeshCacheData
8 | {
9 | public Mesh LoadedMesh { get; set; }
10 | public Dictionary MeshAttributes { get; set; }
11 |
12 | public MeshCacheData()
13 | {
14 | MeshAttributes = new Dictionary();
15 | }
16 |
17 | ///
18 | /// Unloads the meshes in this cache.
19 | ///
20 | public void Unload()
21 | {
22 | Object.Destroy(LoadedMesh);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/RefCountedCacheData.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | namespace UnityGLTF.Cache
6 | {
7 | ///
8 | /// A ref-counted cache data object containing lists of Unity objects that were created for the sake of a GLTF scene/node.
9 | /// This supports counting the amount of refcounts that will dispose of itself
10 | ///
11 | public class RefCountedCacheData
12 | {
13 | private bool _isDisposed = false;
14 |
15 | ///
16 | /// Ref count for this cache data.
17 | ///
18 | ///
19 | /// Initialized to 1, as we assume that when creating a new ref-counted cache data, a reference to it will be stored
20 | /// by an instantiated GLTF object.
21 | ///
22 | private int _refCount = 1;
23 | private readonly object _refCountLock = new object();
24 |
25 | ///
26 | /// Meshes used by this GLTF node.
27 | ///
28 | public List MeshCache { get; set; }
29 |
30 | ///
31 | /// Materials used by this GLTF node.
32 | ///
33 | public MaterialCacheData[] MaterialCache { get; set; }
34 |
35 | ///
36 | /// Textures used by this GLTF node.
37 | ///
38 | public TextureCacheData[] TextureCache { get; set; }
39 |
40 | public void IncreaseRefCount()
41 | {
42 | if (_isDisposed)
43 | {
44 | throw new InvalidOperationException("Cannot inscrease the ref count on disposed cache data.");
45 | }
46 |
47 | lock (_refCountLock)
48 | {
49 | _refCount++;
50 | }
51 | }
52 |
53 | public void DecreaseRefCount()
54 | {
55 | if (_isDisposed)
56 | {
57 | throw new InvalidOperationException("Cannot decrease the ref count on disposed cache data.");
58 | }
59 |
60 | lock (_refCountLock)
61 | {
62 | if (_refCount <= 0)
63 | {
64 | throw new InvalidOperationException("Cannot decrease the cache data ref count below zero.");
65 | }
66 |
67 | _refCount--;
68 | }
69 |
70 | if (_refCount <= 0)
71 | {
72 | DestroyCachedData();
73 | }
74 | }
75 |
76 | private void DestroyCachedData()
77 | {
78 | // Destroy the cached meshes
79 | for (int i = 0; i < MeshCache.Count; i++)
80 | {
81 | for (int j = 0; j < MeshCache[i].Length; j++)
82 | {
83 | if (MeshCache[i][j] != null)
84 | {
85 | MeshCache[i][j].Unload();
86 | }
87 | }
88 | }
89 |
90 | // Destroy the cached textures
91 | for (int i = 0; i < TextureCache.Length; i++)
92 | {
93 | if (TextureCache[i] != null)
94 | {
95 | TextureCache[i].Unload();
96 | }
97 | }
98 |
99 | // Destroy the cached materials
100 | for (int i = 0; i < MaterialCache.Length; i++)
101 | {
102 | if (MaterialCache[i] != null)
103 | {
104 | MaterialCache[i].Unload();
105 | }
106 | }
107 |
108 | _isDisposed = true;
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Cache/TextureCacheData.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace UnityGLTF.Cache
4 | {
5 | public class TextureCacheData
6 | {
7 | public GLTF.Schema.Texture TextureDefinition;
8 | public Texture Texture;
9 |
10 | ///
11 | /// Unloads the textures in this cache.
12 | ///
13 | public void Unload()
14 | {
15 | Object.Destroy(Texture);
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Editor/GLTFExportMenu.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEditor;
3 | using UnityGLTF;
4 | using UnityEngine.SceneManagement;
5 |
6 | public class GLTFExportMenu
7 | {
8 | /*[MenuItem("GLTF/Export Selected")]
9 | static void ExportSelected()
10 | {
11 | string name;
12 | if (Selection.transforms.Length > 1)
13 | name = SceneManager.GetActiveScene().name;
14 | else if (Selection.transforms.Length == 1)
15 | name = Selection.activeGameObject.name;
16 | else
17 | throw new Exception("No objects selected, cannot export.");
18 |
19 | var exporter = new GLTFSceneExporter(Selection.transforms);
20 | var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", "");
21 | exporter.SaveGLTFandBin(path, name);
22 | }
23 |
24 | [MenuItem("GLTF/Export Scene")]
25 | static void ExportScene()
26 | {
27 | var scene = SceneManager.GetActiveScene();
28 | var gameObjects = scene.GetRootGameObjects();
29 | var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform);
30 |
31 | var exporter = new GLTFSceneExporter(transforms);
32 | var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", "");
33 | exporter.SaveGLTFandBin(path, scene.name);
34 | }*/
35 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Editor/GLTFImporterInspector.cs:
--------------------------------------------------------------------------------
1 | #if UNITY_2017_1_OR_NEWER
2 | using System;
3 | using System.Linq;
4 | using UnityEditor;
5 | using UnityEditor.Experimental.AssetImporters;
6 | using UnityEngine;
7 |
8 | namespace UnityGLTF
9 | {
10 | [CustomEditor(typeof(GLTFImporter))]
11 | [CanEditMultipleObjects]
12 | public class GLTFImporterInspector : AssetImporterEditor
13 | {
14 | private string[] _importNormalsNames;
15 |
16 | public override void OnInspectorGUI()
17 | {
18 | if (_importNormalsNames == null)
19 | {
20 | _importNormalsNames = Enum.GetNames(typeof(GLTFImporterNormals))
21 | .Select(n => ObjectNames.NicifyVariableName(n))
22 | .ToArray();
23 | }
24 | EditorGUILayout.LabelField("Meshes", EditorStyles.boldLabel);
25 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_removeEmptyRootObjects"));
26 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_scaleFactor"));
27 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_maximumLod"), new GUIContent("Maximum LOD"));
28 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_readWriteEnabled"), new GUIContent("Read/Write Enabled"));
29 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_generateColliders"));
30 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_swapUvs"), new GUIContent("Swap UVs"));
31 | EditorGUILayout.Separator();
32 | EditorGUILayout.LabelField("Normals", EditorStyles.boldLabel);
33 | EditorGUI.BeginChangeCheck();
34 | var importNormalsProp = serializedObject.FindProperty("_importNormals");
35 | var importNormals = EditorGUILayout.Popup(importNormalsProp.displayName, importNormalsProp.intValue, _importNormalsNames);
36 | if (EditorGUI.EndChangeCheck())
37 | {
38 | importNormalsProp.intValue = importNormals;
39 | }
40 | EditorGUILayout.Separator();
41 | EditorGUILayout.LabelField("Materials", EditorStyles.boldLabel);
42 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_importMaterials"));
43 | EditorGUILayout.PropertyField(serializedObject.FindProperty("_useJpgTextures"), new GUIContent("Use JPG Textures"));
44 |
45 | ApplyRevertGUI();
46 | }
47 | }
48 | }
49 | #endif
50 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Editor/GLTFImporterNormals.cs:
--------------------------------------------------------------------------------
1 | #if UNITY_2017_1_OR_NEWER
2 | namespace UnityGLTF
3 | {
4 | public enum GLTFImporterNormals
5 | {
6 | Import,
7 | Calculate,
8 | None
9 | }
10 | }
11 | #endif
12 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Exceptions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine.Networking;
3 |
4 | namespace UnityGLTF {
5 | [Serializable()]
6 | public class WebRequestException : Exception {
7 | public WebRequestException() : base() { }
8 | public WebRequestException(string message) : base(message) { }
9 | public WebRequestException(string message, Exception inner) : base(message, inner) { }
10 | public WebRequestException(UnityWebRequest www) : base(string.Format("Error: {0} when requesting: {1}", www.responseCode, www.url)) { }
11 | #if !WINDOWS_UWP
12 | protected WebRequestException(System.Runtime.Serialization.SerializationInfo info,
13 | System.Runtime.Serialization.StreamingContext context) { }
14 | #endif
15 | }
16 |
17 | [Serializable()]
18 | public class ShaderNotFoundException : Exception
19 | {
20 | public ShaderNotFoundException() : base() { }
21 | public ShaderNotFoundException(string message) : base(message) { }
22 | public ShaderNotFoundException(string message, Exception inner) : base(message, inner) { }
23 | #if !WINDOWS_UWP
24 | protected ShaderNotFoundException(System.Runtime.Serialization.SerializationInfo info,
25 | System.Runtime.Serialization.StreamingContext context)
26 | { }
27 | #endif
28 | }
29 |
30 | ///
31 | /// GLTFLoad exceptions occur during runtime errors through use of the GLTFSceneImporter
32 | ///
33 | public class GLTFLoadException : Exception
34 | {
35 | public GLTFLoadException() : base() { }
36 | public GLTFLoadException(string message) : base(message) { }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/GLTFComponent.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.IO;
4 | using GLTF;
5 | using GLTF.Schema;
6 | using UnityEngine;
7 | using UnityGLTF.Loader;
8 |
9 | namespace UnityGLTF {
10 |
11 | ///
12 | /// Component to load a GLTF scene with
13 | ///
14 | class GLTFComponent : MonoBehaviour
15 | {
16 | public string GLTFUri;
17 | public bool Multithreaded = true;
18 | public bool UseStream = false;
19 |
20 | public int MaximumLod = 300;
21 | public GLTFSceneImporter.ColliderType Colliders = GLTFSceneImporter.ColliderType.None;
22 |
23 | IEnumerator Start()
24 | {
25 | GLTFSceneImporter sceneImporter = null;
26 | ILoader loader = null;
27 |
28 | if (UseStream)
29 | {
30 | // Path.Combine treats paths that start with the separator character
31 | // as absolute paths, ignoring the first path passed in. This removes
32 | // that character to properly handle a filename written with it.
33 | GLTFUri = GLTFUri.TrimStart(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
34 | string fullPath = Path.Combine(Application.streamingAssetsPath, GLTFUri);
35 | string directoryPath = URIHelper.GetDirectoryName(fullPath);
36 | loader = new FileLoader(directoryPath);
37 | sceneImporter = new GLTFSceneImporter(
38 | Path.GetFileName(GLTFUri),
39 | loader
40 | );
41 | }
42 | else
43 | {
44 | string directoryPath = URIHelper.GetDirectoryName(GLTFUri);
45 | loader = new WebRequestLoader(directoryPath);
46 | sceneImporter = new GLTFSceneImporter(
47 | URIHelper.GetFileFromUri(new Uri(GLTFUri)),
48 | loader
49 | );
50 |
51 | }
52 |
53 | sceneImporter.SceneParent = gameObject.transform;
54 | sceneImporter.Collider = Colliders;
55 | sceneImporter.MaximumLod = MaximumLod;
56 | yield return sceneImporter.LoadScene(-1, Multithreaded);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/InstantiatedGLTFObject.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityGLTF.Cache;
3 |
4 | namespace UnityGLTF
5 | {
6 | ///
7 | /// Instantiated GLTF Object component that gets added to the root of every GLTF game object created by a scene importer.
8 | ///
9 | public class InstantiatedGLTFObject : MonoBehaviour
10 | {
11 | ///
12 | /// Ref-counted cache data for this object.
13 | /// The same instance of this cached data will be used for all copies of this GLTF object,
14 | /// and the data gets cleaned up when the ref counts goes to 0.
15 | ///
16 | public RefCountedCacheData CachedData { get; set; }
17 |
18 | ///
19 | /// Duplicates the instantiated GLTF object.
20 | /// Note that this should always be called if you intend to create a new instance of a GLTF object,
21 | /// in order to properly preserve the ref count of the dynamically loaded mesh data, otherwise
22 | /// you will run into a memory leak due to non-destroyed meshes, textures and materials.
23 | ///
24 | ///
25 | public InstantiatedGLTFObject Duplicate()
26 | {
27 | GameObject duplicatedObject = Instantiate(gameObject);
28 |
29 | InstantiatedGLTFObject newGltfObjectComponent = duplicatedObject.GetComponent();
30 | newGltfObjectComponent.CachedData = CachedData;
31 | CachedData.IncreaseRefCount();
32 |
33 | return newGltfObjectComponent;
34 | }
35 |
36 | private void OnDestroy()
37 | {
38 | CachedData.DecreaseRefCount();
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Loader/FileLoader.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using GLTF;
3 | using UnityEngine;
4 | using System;
5 | using System.Collections;
6 |
7 | #if WINDOWS_UWP
8 | using System.Threading.Tasks;
9 | #endif
10 |
11 | namespace UnityGLTF.Loader
12 | {
13 | public class FileLoader : ILoader
14 | {
15 | private string _rootDirectoryPath;
16 | public Stream LoadedStream { get; private set; }
17 |
18 | public FileLoader(string rootDirectoryPath)
19 | {
20 | _rootDirectoryPath = rootDirectoryPath;
21 | }
22 |
23 | public IEnumerator LoadStream(string gltfFilePath)
24 | {
25 | if (gltfFilePath == null)
26 | {
27 | throw new ArgumentNullException("gltfFilePath");
28 | }
29 |
30 | yield return LoadFileStream(_rootDirectoryPath, gltfFilePath);
31 | }
32 |
33 | private IEnumerator LoadFileStream(string rootPath, string fileToLoad)
34 | {
35 | string pathToLoad = Path.Combine(rootPath, fileToLoad);
36 | if (!File.Exists(pathToLoad))
37 | {
38 | throw new FileNotFoundException("Buffer file not found", fileToLoad);
39 | }
40 |
41 | yield return null;
42 | LoadedStream = File.OpenRead(pathToLoad);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Loader/ILoader.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.IO;
3 | using GLTF;
4 | using GLTF.Schema;
5 | #if WINDOWS_UWP
6 | using System.Threading.Tasks;
7 | #endif
8 |
9 | namespace UnityGLTF.Loader
10 | {
11 | public interface ILoader
12 | {
13 | IEnumerator LoadStream(string relativeFilePath);
14 |
15 | Stream LoadedStream { get; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Loader/StorageFolderLoader.cs:
--------------------------------------------------------------------------------
1 | #if WINDOWS_UWP
2 | using System.IO;
3 | using System.Threading.Tasks;
4 | using Windows.Storage;
5 | using System;
6 | using System.Collections;
7 |
8 | namespace UnityGLTF.Loader
9 | {
10 | public class StorageFolderLoader : ILoader
11 | {
12 | private StorageFolder _rootFolder;
13 | public Stream LoadedStream { get; private set; }
14 |
15 | public StorageFolderLoader(StorageFolder rootFolder)
16 | {
17 | _rootFolder = rootFolder;
18 | }
19 |
20 | public IEnumerator LoadStream(string gltfFilePath)
21 | {
22 | if (gltfFilePath == null)
23 | {
24 | throw new ArgumentNullException("gltfFilePath");
25 | }
26 |
27 | yield return LoadStorageFile(gltfFilePath).AsCoroutine();
28 | }
29 |
30 | public async Task LoadStorageFile(string path)
31 | {
32 | StorageFolder parentFolder = _rootFolder;
33 | string fileName = Path.GetFileName(path);
34 | if (path != fileName)
35 | {
36 | string folderToLoad = path.Substring(0, path.Length - fileName.Length);
37 | parentFolder = await _rootFolder.GetFolderAsync(folderToLoad);
38 | }
39 |
40 | StorageFile bufferFile = await parentFolder.GetFileAsync(fileName);
41 | LoadedStream = await bufferFile.OpenStreamForReadAsync();
42 | }
43 | }
44 | }
45 | #endif
46 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/Loader/WebRequestLoader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.IO;
4 | using GLTF;
5 | using UnityEngine;
6 | using System.Text.RegularExpressions;
7 | using System.Net;
8 | using UnityEngine.Networking;
9 |
10 | #if WINDOWS_UWP
11 | using System.Threading.Tasks;
12 | #endif
13 |
14 | namespace UnityGLTF.Loader
15 | {
16 | public class WebRequestLoader : ILoader
17 | {
18 | public Stream LoadedStream { get; private set; }
19 |
20 | private string _rootURI;
21 |
22 | public WebRequestLoader(string rootURI)
23 | {
24 | _rootURI = rootURI;
25 | }
26 |
27 | public IEnumerator LoadStream(string gltfFilePath)
28 | {
29 | if (gltfFilePath == null)
30 | {
31 | throw new ArgumentNullException("gltfFilePath");
32 | }
33 |
34 | yield return CreateHTTPRequest(_rootURI, gltfFilePath);
35 | }
36 |
37 | private IEnumerator CreateHTTPRequest(string rootUri, string httpRequestPath)
38 | {
39 | UnityWebRequest www = new UnityWebRequest(Path.Combine(rootUri, httpRequestPath), "GET", new DownloadHandlerBuffer(), null);
40 | www.timeout = 5000;
41 | #if UNITY_2017_1_OR_NEWER
42 | yield return www.SendWebRequest();
43 | #else
44 | yield return www.Send();
45 | #endif
46 | if ((int)www.responseCode >= 400)
47 | {
48 | Debug.LogErrorFormat("{0} - {1}", www.responseCode, www.url);
49 | throw new Exception("Response code invalid");
50 | }
51 |
52 | if (www.downloadedBytes > int.MaxValue)
53 | {
54 | throw new Exception("Stream is larger than can be copied into byte array");
55 | }
56 |
57 | LoadedStream = new MemoryStream(www.downloadHandler.data, 0, www.downloadHandler.data.Length, true, true);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/URIHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Text.RegularExpressions;
6 | using UnityEngine;
7 |
8 | public static class URIHelper
9 | {
10 | private const string Base64StringInitializer = "^data:[a-z-]+/[a-z-]+;base64,";
11 |
12 | ///
13 | /// Get the absolute path to a gltf uri reference.
14 | ///
15 | /// The path to the gltf file
16 | /// A path without the filename or extension
17 | public static string AbsoluteUriPath(Uri uri)
18 | {
19 | var partialPath = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length - 1].Length);
20 | return partialPath;
21 | }
22 |
23 | public static string GetFileFromUri(Uri uri)
24 | {
25 | return uri.Segments[uri.Segments.Length - 1];
26 | }
27 |
28 | ///
29 | /// Gets a directory name from a file path
30 | ///
31 | /// Full path of a file
32 | /// The name of directory file is in
33 | public static string GetDirectoryName(string fullPath)
34 | {
35 | var fileName = Path.GetFileName(fullPath);
36 | return fullPath.Substring(0, fullPath.Length - fileName.Length);
37 | }
38 |
39 | ///
40 | /// Tries to parse the uri as a base 64 encoded string
41 | ///
42 | /// The string that represents the data
43 | /// Returns the deencoded bytes
44 | public static void TryParseBase64(string uri, out byte[] bufferData)
45 | {
46 | Regex regex = new Regex(Base64StringInitializer);
47 | Match match = regex.Match(uri);
48 | bufferData = null;
49 | if (match.Success)
50 | {
51 | var base64Data = uri.Substring(match.Length);
52 | bufferData = Convert.FromBase64String(base64Data);
53 | }
54 | }
55 |
56 | ///
57 | /// Returns whether the input uri is base64 encoded
58 | ///
59 | /// The uri data
60 | /// Whether the uri is base64
61 | public static bool IsBase64Uri(string uri)
62 | {
63 | Regex regex = new Regex(Base64StringInitializer);
64 | Match match = regex.Match(uri);
65 | return match.Success;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/UniformMaps/MetalRough2StandardMap.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace UnityGLTF
4 | {
5 | class MetalRough2StandardMap : StandardMap, IMetalRoughUniformMap
6 | {
7 | public MetalRough2StandardMap(int MaxLOD = 1000) : base("Standard", MaxLOD) { }
8 | protected MetalRough2StandardMap(string shaderName, int MaxLOD = 1000) : base(shaderName, MaxLOD) { }
9 | protected MetalRough2StandardMap(Material m, int MaxLOD = 1000) : base(m, MaxLOD) { }
10 |
11 | public virtual Texture BaseColorTexture
12 | {
13 | get { return _material.GetTexture("_MainTex"); }
14 | set { _material.SetTexture("_MainTex", value); }
15 | }
16 |
17 | // not implemented by the Standard shader
18 | public virtual int BaseColorTexCoord
19 | {
20 | get { return 0; }
21 | set { return; }
22 | }
23 |
24 | public virtual Color BaseColorFactor
25 | {
26 | get { return _material.GetColor("_Color"); }
27 | set { _material.SetColor("_Color", value); }
28 | }
29 |
30 | public virtual Texture MetallicRoughnessTexture
31 | {
32 | get { return null; }
33 | set
34 | {
35 | // cap metalness at 0.5 to compensate for lack of texture
36 | MetallicFactor = Mathf.Min(0.5f, (float)MetallicFactor);
37 | }
38 | }
39 |
40 | // not implemented by the Standard shader
41 | public virtual int MetallicRoughnessTexCoord
42 | {
43 | get { return 0; }
44 | set { return; }
45 | }
46 |
47 | public virtual double MetallicFactor
48 | {
49 | get { return _material.GetFloat("_Metallic"); }
50 | set { _material.SetFloat("_Metallic", (float) value); }
51 | }
52 |
53 | // not supported by the Standard shader
54 | public virtual double RoughnessFactor
55 | {
56 | get { return 0.5; }
57 | set { return; }
58 | }
59 |
60 | public override IUniformMap Clone()
61 | {
62 | var copy = new MetalRough2StandardMap(new Material(_material));
63 | base.Copy(copy);
64 | return copy;
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/UniformMaps/MetalRoughMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 | using AlphaMode = GLTF.Schema.AlphaMode;
4 | using CullMode = UnityEngine.Rendering.CullMode;
5 |
6 | namespace UnityGLTF
7 | {
8 | class MetalRoughMap : MetalRough2StandardMap
9 | {
10 | public MetalRoughMap(int MaxLOD = 1000) : base("GLTF/PbrMetallicRoughness", MaxLOD) { }
11 | protected MetalRoughMap(string shaderName, int MaxLOD = 1000) : base(shaderName, MaxLOD) { }
12 | protected MetalRoughMap(Material m, int MaxLOD = 1000) : base(m, MaxLOD) { }
13 |
14 | public override int NormalTexCoord
15 | {
16 | get { return 0; }
17 | set { return; }
18 | }
19 |
20 | public override int OcclusionTexCoord
21 | {
22 | get { return 0; }
23 | set { return; }
24 | }
25 |
26 | public override int EmissiveTexCoord
27 | {
28 | get { return 0; }
29 | set { return; }
30 | }
31 |
32 | public override int BaseColorTexCoord
33 | {
34 | get { return 0; }
35 | set { return; }
36 | }
37 |
38 | public override Texture MetallicRoughnessTexture
39 | {
40 | get { return _material.GetTexture("_MetallicGlossMap"); }
41 | set
42 | {
43 | _material.SetTexture("_MetallicGlossMap", value);
44 | _material.EnableKeyword("_METALLICGLOSSMAP");
45 | }
46 | }
47 |
48 | public override int MetallicRoughnessTexCoord
49 | {
50 | get { return 0; }
51 | set { return; }
52 | }
53 |
54 | public override IUniformMap Clone()
55 | {
56 | var copy = new MetalRoughMap(new Material(_material));
57 | base.Copy(copy);
58 | return copy;
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/UniformMaps/SpecGloss2StandardMap.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace UnityGLTF
4 | {
5 | class SpecGloss2StandardMap : StandardMap, ISpecGlossUniformMap
6 | {
7 | public SpecGloss2StandardMap(int MaxLOD = 1000) : base("Standard (Specular setup)", MaxLOD) { }
8 | protected SpecGloss2StandardMap(string shaderName, int MaxLOD = 1000) : base(shaderName, MaxLOD) { }
9 | protected SpecGloss2StandardMap(Material m, int MaxLOD = 1000) : base(m, MaxLOD) { }
10 |
11 | public virtual Texture DiffuseTexture
12 | {
13 | get { return _material.GetTexture("_MainTex"); }
14 | set { _material.SetTexture("_MainTex", value); }
15 | }
16 |
17 | // not implemented by the Standard shader
18 | public virtual int DiffuseTexCoord
19 | {
20 | get { return 0; }
21 | set { return; }
22 | }
23 |
24 | public virtual Color DiffuseFactor
25 | {
26 | get { return _material.GetColor("_Color"); }
27 | set { _material.SetColor("_Color", value); }
28 | }
29 |
30 | public virtual Texture SpecularGlossinessTexture
31 | {
32 | get { return _material.GetTexture("_SpecGlossMap"); }
33 | set
34 | {
35 | _material.SetTexture("_SpecGlossMap", value);
36 | _material.SetFloat("_SmoothnessTextureChannel", 0);
37 | _material.EnableKeyword("_SPECGLOSSMAP");
38 | }
39 | }
40 |
41 | // not implemented by the Standard shader
42 | public virtual int SpecularGlossinessTexCoord
43 | {
44 | get { return 0; }
45 | set { return; }
46 | }
47 |
48 | public virtual Vector3 SpecularFactor
49 | {
50 | get { return _material.GetVector("_SpecColor"); }
51 | set { _material.SetVector("_SpecColor", value); }
52 | }
53 |
54 | public virtual double GlossinessFactor
55 | {
56 | get { return _material.GetFloat("_GlossMapScale"); }
57 | set
58 | {
59 | _material.SetFloat("_GlossMapScale", (float) value);
60 | _material.SetFloat("_Glossiness", (float) value);
61 | }
62 | }
63 |
64 | public override IUniformMap Clone()
65 | {
66 | var copy = new SpecGloss2StandardMap(new Material(_material));
67 | base.Copy(copy);
68 | return copy;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/UniformMaps/SpecGlossMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 |
4 | namespace UnityGLTF
5 | {
6 | class SpecGlossMap : SpecGloss2StandardMap
7 | {
8 | public SpecGlossMap(int MaxLOD = 1000) : base("GLTF/PbrSpecularGlossiness", MaxLOD) { }
9 | protected SpecGlossMap(string shaderName, int MaxLOD = 1000) : base(shaderName, MaxLOD) { }
10 | protected SpecGlossMap(Material m, int MaxLOD = 1000) : base(m, MaxLOD) { }
11 |
12 | public override int NormalTexCoord
13 | {
14 | get { return 0; }
15 | set { return; }
16 | }
17 |
18 | public override int OcclusionTexCoord
19 | {
20 | get { return 0; }
21 | set { return; }
22 | }
23 |
24 | public override int EmissiveTexCoord
25 | {
26 | get { return 0; }
27 | set { return; }
28 | }
29 |
30 | public override int DiffuseTexCoord
31 | {
32 | get { return 0; }
33 | set { return; }
34 | }
35 |
36 | public override int SpecularGlossinessTexCoord
37 | {
38 | get { return 0; }
39 | set { return; }
40 | }
41 |
42 | public override IUniformMap Clone()
43 | {
44 | var copy = new SpecGlossMap(new Material(_material));
45 | base.Copy(copy);
46 | return copy;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/UnityExportTool/src/GLTF/UnityGLTF/UniformMaps/UniformMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using UnityEngine;
6 |
7 | namespace UnityGLTF
8 | {
9 | interface IUniformMap
10 | {
11 | Material Material { get; }
12 |
13 | Texture NormalTexture { get; set; }
14 | int NormalTexCoord { get; set; }
15 | double NormalTexScale { get; set; }
16 |
17 | Texture OcclusionTexture { get; set; }
18 | int OcclusionTexCoord { get; set; }
19 | double OcclusionTexStrength { get; set; }
20 |
21 | Texture EmissiveTexture { get; set; }
22 | int EmissiveTexCoord { get; set; }
23 | Color EmissiveFactor { get; set; }
24 |
25 | GLTF.Schema.AlphaMode AlphaMode { get; set; }
26 | double AlphaCutoff { get; set; }
27 | bool DoubleSided { get; set; }
28 | bool VertexColorsEnabled { get; set; }
29 |
30 | IUniformMap Clone();
31 | }
32 |
33 | interface IMetalRoughUniformMap : IUniformMap
34 | {
35 | Texture BaseColorTexture { get; set; }
36 | int BaseColorTexCoord { get; set; }
37 | Color BaseColorFactor { get; set; }
38 | Texture MetallicRoughnessTexture { get; set; }
39 | int MetallicRoughnessTexCoord { get; set; }
40 | double MetallicFactor { get; set; }
41 | double RoughnessFactor { get; set; }
42 | }
43 |
44 | interface ISpecGlossUniformMap : IUniformMap
45 | {
46 | Texture DiffuseTexture { get; set; }
47 | int DiffuseTexCoord { get; set; }
48 | Color DiffuseFactor { get; set; }
49 | Texture SpecularGlossinessTexture { get; set; }
50 | int SpecularGlossinessTexCoord { get; set; }
51 | Vector3 SpecularFactor { get; set; }
52 | double GlossinessFactor { get; set; }
53 | }
54 |
55 | interface IUnlitUniformMap : IUniformMap
56 | {
57 | Texture BaseColorTexture { get; set; }
58 | int BaseColorTexCoord { get; set; }
59 | Color BaseColorFactor { get; set; }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Helper/Extensions/MaterialExtension.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | public static class MaterialExtension
4 | {
5 | public static float GetFloat(this UnityEngine.Material source, string key, float defalutValue)
6 | {
7 | if (source.HasProperty(key))
8 | {
9 | return source.GetFloat(key);
10 | }
11 |
12 | return defalutValue;
13 | }
14 |
15 | public static UnityEngine.Color GetColor(this UnityEngine.Material source, string key, UnityEngine.Color defalutValue)
16 | {
17 | if (source.HasProperty(key))
18 | {
19 | return source.GetColor(key);
20 | }
21 |
22 | return defalutValue;
23 | }
24 |
25 | public static UnityEngine.Vector4 GetVector4(this UnityEngine.Material source, string key, UnityEngine.Vector4 defalutValue)
26 | {
27 | if (source.HasProperty(key))
28 | {
29 | return source.GetVector(key);
30 | }
31 |
32 | return defalutValue;
33 | }
34 |
35 | public static UnityEngine.Texture GetTexture(this UnityEngine.Material source, string key, UnityEngine.Texture defalutValue)
36 | {
37 | if (source.HasProperty(key))
38 | {
39 | return source.GetTexture(key);
40 | }
41 |
42 | return defalutValue;
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Helper/MyLog.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Egret3DExportTools
4 | {
5 | public static class MyLog
6 | {
7 | public static void Log(object message)
8 | {
9 | if(ExportSetting.instance.common.debugLog)
10 | {
11 | Debug.Log(message);
12 | }
13 | }
14 |
15 | public static void LogWarning(object message)
16 | {
17 | if(ExportSetting.instance.common.debugLog)
18 | {
19 | Debug.LogWarning(message);
20 | }
21 | }
22 |
23 | public static void LogError(object message)
24 | {
25 | Debug.LogError(message);
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/Extensions/AnimationExtension.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using GLTF.Schema;
4 | using Newtonsoft.Json;
5 | using Newtonsoft.Json.Linq;
6 | using System.Collections.Generic;
7 |
8 | public class AnimationClip
9 | {
10 | public string name;
11 | public int playTimes;
12 | public float position;
13 | public float duration;
14 | }
15 |
16 | public class AnimationFrameEvent
17 | {
18 | public string name;
19 | public float position;
20 | public int intVariable;
21 | public float floatVariable;
22 | public string stringVariable;
23 | }
24 |
25 | public class AnimationChannelExtension : IExtension {
26 | public string type;
27 | public string property;
28 | public string uri;
29 | public int needUpdate;
30 |
31 | public IExtension Clone(GLTFRoot root)
32 | {
33 | return new AnimationChannelExtension
34 | {
35 | type = type,
36 | property = property,
37 | uri = uri,
38 | needUpdate = needUpdate,
39 | };
40 | }
41 |
42 | public JProperty Serialize()
43 | {
44 | JObject ext = new JObject();
45 |
46 | ext.SetString("type", type);
47 | ext.SetString("property", property);
48 | ext.SetString("uri", uri);
49 | ext.SetInt("needUpdate", needUpdate);
50 |
51 | return new JProperty(AnimationExtension.EXTENSION_NAME, ext);
52 | }
53 | }
54 |
55 | public class AnimationExtension : IExtension
56 | {
57 | public const string EXTENSION_NAME = "egret";
58 | public float frameRate;
59 | public List clips = new List();
60 | public List events = new List();
61 |
62 | public IExtension Clone(GLTFRoot root)
63 | {
64 | return new AnimationExtension {
65 | frameRate = frameRate,
66 | clips = clips,
67 | events = events
68 | };
69 | }
70 |
71 | public JProperty Serialize()
72 | {
73 | JObject ext = new JObject();
74 | ext.SetNumber("frameRate", frameRate);
75 |
76 | if (clips.Count > 0)
77 | {
78 | var obj = JsonConvert.SerializeObject(clips);
79 | JsonConvert.DeserializeObject(obj);
80 |
81 | ext.Add(new JProperty(
82 | "clips",
83 | JsonConvert.DeserializeObject(obj)
84 | ));
85 | }
86 |
87 | if (events.Count > 0)
88 | {
89 | var obj = JsonConvert.SerializeObject(events);
90 | JsonConvert.DeserializeObject(obj);
91 |
92 | ext.Add(new JProperty(
93 | "events",
94 | JsonConvert.DeserializeObject(obj)
95 | ));
96 | }
97 |
98 | return new JProperty(AnimationExtension.EXTENSION_NAME, ext);
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/Extensions/AssetVersion.cs:
--------------------------------------------------------------------------------
1 | using GLTF.Schema;
2 | using Newtonsoft.Json.Linq;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class AssetVersionExtension : IExtension
7 | {
8 | public const string EXTENSION_NAME = "egret";
9 | public string version = "5.0";
10 | public string minVersion = "5.0";
11 |
12 | public IExtension Clone(GLTFRoot root)
13 | {
14 | return new AssetVersionExtension
15 | {
16 | version = version,
17 | minVersion = minVersion,
18 | };
19 | }
20 |
21 | public virtual JProperty Serialize()
22 | {
23 | JObject ext = new JObject();
24 |
25 | ext.SetString("version", version);
26 | ext.SetString("minVersion", minVersion);
27 |
28 | return new JProperty("egret", ext);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/Extensions/TextureExtension.cs:
--------------------------------------------------------------------------------
1 | using GLTF.Schema;
2 | using Newtonsoft.Json.Linq;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class TextureExtension : IExtension
7 | {
8 | public const string EXTENSION_NAME = "egret";
9 | public int width = 0;
10 | public int height = 0;
11 | public int format = 6408;
12 | public int levels = 0;
13 | public int encoding = 0;
14 | public int faces = 1;
15 | public int mapping = 0;
16 | public int anisotropy = 1;
17 |
18 | public IExtension Clone(GLTFRoot root)
19 | {
20 | return new TextureExtension
21 | {
22 | width = width,
23 | height = height,
24 | format = format,
25 | levels = levels,
26 | encoding = encoding,
27 | faces = faces,
28 | mapping = mapping,
29 | anisotropy = anisotropy,
30 | };
31 | }
32 |
33 | public JProperty Serialize()
34 | {
35 | JObject ext = new JObject();
36 |
37 | ext.SetInt("width", this.width, 0);
38 | ext.SetInt("height", this.height, 0);
39 | ext.SetInt("format", this.format, 6408);
40 | ext.SetInt("levels", this.levels, 1);
41 | ext.SetInt("encoding", this.encoding, 0);
42 | ext.SetInt("faces", this.faces, 1);
43 | ext.SetInt("mapping", this.mapping, 0);
44 | ext.SetInt("anisotropy", this.anisotropy, 1);
45 |
46 | return new JProperty("egret", ext);
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/GLTFCubemapSerializer.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using GLTF.Schema;
5 | using UnityEngine;
6 |
7 | public class GLTFCubemapSerializer : AssetSerializer
8 | {
9 | private UnityEngine.Cubemap texture;
10 |
11 | protected override void InitGLTFRoot()
12 | {
13 | base.InitGLTFRoot();
14 |
15 | this._root.ExtensionsRequired.Add(AssetVersionExtension.EXTENSION_NAME);
16 | this._root.ExtensionsUsed.Add(AssetVersionExtension.EXTENSION_NAME);
17 |
18 | this._root.Images = new List();
19 | this._root.Samplers = new List();
20 | this._root.Textures = new List();
21 | }
22 |
23 | private void ExportTexture()
24 | {
25 | var tex = this.texture;
26 | var path = PathHelper.GetTexturePath(tex);
27 | byte[] bs = ExportImage.Export(tex);
28 | if (!SerializeObject.assetsData.ContainsKey(path))
29 | {
30 | var assetData = AssetData.Create(path);
31 | assetData.buffer = bs;
32 | SerializeObject.assetsData.Add(path, assetData);
33 | }
34 | }
35 |
36 | protected override void Serialize(UnityEngine.Object sourceAsset)
37 | {
38 | this.texture = sourceAsset as UnityEngine.Cubemap;
39 | //先把原始图片导出来
40 | this.ExportTexture();
41 |
42 | var path = PathHelper.GetTexturePath(this.texture);
43 | var mipmap = this.texture.mipmapCount > 1;
44 | //
45 | {
46 | this._root.Images.Add(new Image() { Uri = ExportSetting.instance.GetExportPath(path) });
47 | }
48 | //
49 | {
50 | var filterMode = this.texture.filterMode;
51 | var wrapMode = this.texture.wrapMode;
52 |
53 | var sampler = new Sampler();
54 | this._root.Samplers.Add(sampler);
55 | if (wrapMode == TextureWrapMode.Repeat)
56 | {
57 | sampler.WrapS = GLTF.Schema.WrapMode.Repeat;
58 | sampler.WrapT = GLTF.Schema.WrapMode.Repeat;
59 | }
60 | else
61 | {
62 | sampler.WrapS = GLTF.Schema.WrapMode.ClampToEdge;
63 | sampler.WrapT = GLTF.Schema.WrapMode.ClampToEdge;
64 | }
65 | sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
66 | if (!mipmap)
67 | {
68 | sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
69 | }
70 | else if (filterMode == FilterMode.Point)
71 | {
72 | sampler.MinFilter = MinFilterMode.NearestMipmapNearest;
73 | }
74 | else if (filterMode == FilterMode.Bilinear)
75 | {
76 | sampler.MinFilter = MinFilterMode.LinearMipmapNearest;
77 | }
78 | else if (filterMode == FilterMode.Trilinear)
79 | {
80 | sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
81 | }
82 | }
83 | //
84 | {
85 | var gltfTexture = new GLTF.Schema.Texture();
86 | this._root.Textures.Add(gltfTexture);
87 |
88 | gltfTexture.Sampler = new SamplerId();
89 | gltfTexture.Source = new ImageId();
90 | gltfTexture.Extensions = new Dictionary(){
91 | {
92 | TextureExtension.EXTENSION_NAME,
93 | new TextureExtension(){
94 | anisotropy = this.texture.anisoLevel,
95 | format = GetTextureFormat(),
96 | levels = mipmap ? 0 : 1
97 | }
98 | }
99 | };
100 | }
101 | }
102 |
103 | public int GetTextureFormat()
104 | {
105 | var texExt = PathHelper.GetTextureExt(this.texture);
106 | var format = this.texture.format;
107 | if (format == TextureFormat.Alpha8)
108 | {
109 | return 6409;
110 | }
111 | else if (texExt == "jpg" ||
112 | format == TextureFormat.RGB24 ||
113 | format == TextureFormat.PVRTC_RGB2 ||
114 | format == TextureFormat.PVRTC_RGB4 ||
115 | format == TextureFormat.RGB565 ||
116 | format == TextureFormat.ETC_RGB4 ||
117 | format == TextureFormat.ATC_RGB4 ||
118 | format == TextureFormat.ETC2_RGB ||
119 | format == TextureFormat.ASTC_RGB_4x4 ||
120 | format == TextureFormat.ASTC_RGB_5x5 ||
121 | format == TextureFormat.ASTC_RGB_6x6 ||
122 | format == TextureFormat.ASTC_RGB_8x8 ||
123 | format == TextureFormat.ASTC_RGB_10x10 ||
124 | format == TextureFormat.ASTC_RGB_12x12
125 | )
126 | {
127 | return 6407;
128 | }
129 |
130 |
131 | return 6408;
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/GLTFTextureSerializer.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using GLTF.Schema;
5 | using UnityEngine;
6 |
7 | public class GLTFTextureSerializer : AssetSerializer
8 | {
9 | private UnityEngine.Texture2D texture;
10 |
11 | protected override void InitGLTFRoot()
12 | {
13 | base.InitGLTFRoot();
14 |
15 | this._root.ExtensionsRequired.Add(AssetVersionExtension.EXTENSION_NAME);
16 | this._root.ExtensionsUsed.Add(AssetVersionExtension.EXTENSION_NAME);
17 |
18 | this._root.Images = new List();
19 | this._root.Samplers = new List();
20 | this._root.Textures = new List();
21 | }
22 |
23 | private void ExportTexture()
24 | {
25 | var tex = this.texture;
26 | var path = PathHelper.GetTexturePath(tex);
27 | byte[] bs = ExportImage.Export(tex);
28 | if (!SerializeObject.assetsData.ContainsKey(path))
29 | {
30 | var assetData = AssetData.Create(path);
31 | assetData.buffer = bs;
32 | SerializeObject.assetsData.Add(path, assetData);
33 | }
34 | }
35 |
36 | protected override void Serialize(UnityEngine.Object sourceAsset)
37 | {
38 | this.texture = sourceAsset as UnityEngine.Texture2D;
39 | //先把原始图片导出来
40 | this.ExportTexture();
41 |
42 | var path = PathHelper.GetTexturePath(this.texture);
43 | var mipmap = this.texture.mipmapCount > 1;
44 | //
45 | {
46 | this._root.Images.Add(new Image() { Uri = ExportSetting.instance.GetExportPath(path) });
47 | }
48 | //
49 | {
50 | var filterMode = this.texture.filterMode;
51 | var wrapMode = this.texture.wrapMode;
52 |
53 | var sampler = new Sampler();
54 | this._root.Samplers.Add(sampler);
55 | if (wrapMode == TextureWrapMode.Repeat)
56 | {
57 | sampler.WrapS = GLTF.Schema.WrapMode.Repeat;
58 | sampler.WrapT = GLTF.Schema.WrapMode.Repeat;
59 | }
60 | else
61 | {
62 | sampler.WrapS = GLTF.Schema.WrapMode.ClampToEdge;
63 | sampler.WrapT = GLTF.Schema.WrapMode.ClampToEdge;
64 | }
65 | sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
66 | if (!mipmap)
67 | {
68 | sampler.MagFilter = filterMode == FilterMode.Point ? MagFilterMode.Nearest : MagFilterMode.Linear;
69 | }
70 | else if (filterMode == FilterMode.Point)
71 | {
72 | sampler.MinFilter = MinFilterMode.NearestMipmapNearest;
73 | }
74 | else if (filterMode == FilterMode.Bilinear)
75 | {
76 | sampler.MinFilter = MinFilterMode.LinearMipmapNearest;
77 | }
78 | else if (filterMode == FilterMode.Trilinear)
79 | {
80 | sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
81 | }
82 | }
83 | //
84 | {
85 | var gltfTexture = new GLTF.Schema.Texture();
86 | this._root.Textures.Add(gltfTexture);
87 |
88 | gltfTexture.Sampler = new SamplerId();
89 | gltfTexture.Source = new ImageId();
90 | gltfTexture.Extensions = new Dictionary(){
91 | {
92 | TextureExtension.EXTENSION_NAME,
93 | new TextureExtension(){
94 | anisotropy = this.texture.anisoLevel,
95 | format = GetTextureFormat(),
96 | levels = mipmap ? 0 : 1
97 | }
98 | }
99 | };
100 | }
101 | }
102 |
103 | public int GetTextureFormat()
104 | {
105 | var texExt = PathHelper.GetTextureExt(this.texture);
106 | var format = this.texture.format;
107 | if (format == TextureFormat.Alpha8)
108 | {
109 | return 6409;
110 | }
111 | else if (texExt == "jpg" ||
112 | format == TextureFormat.RGB24 ||
113 | format == TextureFormat.PVRTC_RGB2 ||
114 | format == TextureFormat.PVRTC_RGB4 ||
115 | format == TextureFormat.RGB565 ||
116 | format == TextureFormat.ETC_RGB4 ||
117 | format == TextureFormat.ATC_RGB4 ||
118 | format == TextureFormat.ETC2_RGB ||
119 | format == TextureFormat.ASTC_RGB_4x4 ||
120 | format == TextureFormat.ASTC_RGB_5x5 ||
121 | format == TextureFormat.ASTC_RGB_6x6 ||
122 | format == TextureFormat.ASTC_RGB_8x8 ||
123 | format == TextureFormat.ASTC_RGB_10x10 ||
124 | format == TextureFormat.ASTC_RGB_12x12
125 | )
126 | {
127 | return 6407;
128 | }
129 |
130 |
131 | return 6408;
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/CustomParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System;
4 | using UnityEngine;
5 | using UnityEditor;
6 | using System.Collections.Generic;
7 |
8 | public class CustomParser : BaseMaterialParser
9 | {
10 | public override void CollectUniformValues()
11 | {
12 | base.CollectUniformValues();
13 | var values = this.data.values;
14 | //自定义的value全部导出,不和默认值做过滤
15 | var target = this.source;
16 | var materialProperties = MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { target });
17 | foreach (var materialProperty in materialProperties)
18 | {
19 | if (materialProperty.flags == MaterialProperty.PropFlags.HideInInspector)
20 | {
21 | continue;
22 | }
23 |
24 | string type = materialProperty.type.ToString();
25 | if (type == "Float" || type == "Range")
26 | {
27 | this.data.values.SetNumber(materialProperty.name, this.source.GetFloat(materialProperty.name, 0.0f), null);
28 | // this.SetFloat(materialProperty.name, this.GetFloat(materialProperty.name, 0.0f), null);
29 | }
30 | else if (type == "Vector")
31 | {
32 | this.data.values.SetVector4(materialProperty.name, this.source.GetVector4(materialProperty.name, Vector4.zero));
33 | }
34 | else if (type == "Color")
35 | {
36 | this.data.values.SetColor(materialProperty.name, this.source.GetColor(materialProperty.name, Color.white));
37 | }
38 | else if (type == "Texture")
39 | {
40 | var tex = this.source.GetTexture(materialProperty.name, null);
41 | if (tex != null)
42 | {
43 | string texdim = materialProperty.textureDimension.ToString();
44 | if (texdim == "Tex2D")
45 | {
46 | this.data.values.SetTexture(materialProperty.name, tex);
47 |
48 | string propertyName = materialProperty.name + "_ST";
49 | if (target.HasProperty(propertyName))
50 | {
51 | this.data.values.SetVector4(propertyName, this.source.GetVector4(propertyName, Vector4.zero));
52 | }
53 | }
54 | else
55 | {
56 | throw new Exception("not suport texdim:" + texdim);
57 | }
58 | }
59 | }
60 | else
61 | {
62 | throw new Exception("not support type: " + materialProperty.type);
63 | }
64 | }
65 |
66 | //
67 | this.shaderAsset = UnityEditor.AssetDatabase.GetAssetPath(this.source.shader) + ".json";
68 | MyLog.Log("自定义Shader:" + this.shaderAsset);
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/DiffuseParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using UnityEngine;
4 | using UnityEditor;
5 | using System.Collections.Generic;
6 | public class DiffuseParser : BaseMaterialParser
7 | {
8 | public override void CollectUniformValues()
9 | {
10 | base.CollectUniformValues();
11 | var source = this.source;
12 | var values = this.data.values;
13 | var mainTex = this.MainText;
14 | var mainColor = this.MainColor;
15 | if (mainTex != null)
16 | {
17 | this.data.values.SetTexture("map", mainTex);
18 | var defaultValue = new Vector4(1.0f, 1.0f, 0.0f, 0.0f);
19 | var mainST = this.source.GetVector4("_MainTex_ST", defaultValue);
20 | if (!mainST.Equals(defaultValue))
21 | {
22 | this.data.values.SetUVTransform("uvTransform", mainST);
23 | }
24 | }
25 |
26 | this.data.values.SetColor3("diffuse", mainColor, Color.white);
27 | this.data.values.SetNumber("opacity", mainColor.a, Color.white.a);
28 | }
29 |
30 | protected UnityEngine.Texture MainText
31 | {
32 | get
33 | {
34 | var orginmps = MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { source });
35 | foreach (var mp in orginmps)
36 | {
37 | if (mp.type.ToString() == "Texture")
38 | {
39 | var tex = source.GetTexture(mp.name);
40 | if (tex != null)
41 | {
42 | return tex;
43 | }
44 | }
45 | }
46 |
47 | return null;
48 | }
49 | }
50 |
51 | protected Color MainColor
52 | {
53 | get
54 | {
55 | var color = Color.white;
56 | var source = this.source;
57 | if (source.HasProperty("_Color"))
58 | {
59 | color = source.GetColor("_Color");
60 | }
61 | else if (source.HasProperty("_MainColor"))
62 | {
63 | color = source.GetColor("_MainColor");
64 | }
65 | else if (source.HasProperty("_TintColor"))
66 | {
67 | color = source.GetColor("_TintColor");
68 | }
69 | return color;
70 | }
71 | }
72 | }
73 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/LambertParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using UnityEngine;
5 | public class LambertParser : DiffuseParser
6 | {
7 | public override void CollectUniformValues()
8 | {
9 | base.CollectUniformValues();
10 | var aoMap = this.source.GetTexture("_OcclusionMap", null);
11 | if (aoMap != null)
12 | {
13 | this.data.values.SetTexture("aoMap", aoMap);
14 | // this.SetFloat("aoMapIntensity", this.GetFloat("_OcclusionStrength", 1.0f), 1.0f);
15 | this.data.values.SetNumber("aoMapIntensity", this.source.GetFloat("_OcclusionStrength", 1.0f), 1.0f);
16 | }
17 | var emissiveMap = this.source.GetTexture("_EmissionMap", null);
18 | if (emissiveMap != null)
19 | {
20 | this.data.values.SetTexture("emissiveMap", emissiveMap);
21 | }
22 | var specGlossMap = this.source.GetTexture("_SpecGlossMap", null);
23 | if (specGlossMap != null)
24 | {
25 | this.data.values.SetTexture("specularMap", specGlossMap);
26 | }
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/ParticleParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using UnityEditor;
5 | using UnityEngine;
6 | public class ParticleParser : BaseMaterialParser
7 | {
8 | public override void CollectUniformValues()
9 | {
10 | base.CollectUniformValues();
11 | var source = this.source;
12 | var values = this.data.values;
13 |
14 | var tex = this.source.GetTexture("_MainTex", null);
15 | if(tex == null)
16 | {
17 | tex = this.MainText;
18 | }
19 | if (tex != null)
20 | {
21 | this.data.values.SetTexture("map", tex);
22 |
23 | var defaultValue = new Vector4(1.0f, 1.0f, 0.0f, 0.0f);
24 | var mainST = this.source.GetVector4("_MainTex_ST", defaultValue);
25 | if (!mainST.Equals(defaultValue))
26 | {
27 | // values.SetUVTransform("uvTransform", mainST);
28 | this.data.values.SetUVTransform("uvTransform", mainST);
29 | }
30 | }
31 |
32 | Color color = Color.white;
33 | if (source.HasProperty("_TintColor"))
34 | {
35 | color = this.source.GetColor("_TintColor", Color.white);
36 | }
37 | else if (source.HasProperty("_Color"))
38 | {
39 | color = this.source.GetColor("_Color", Color.white);
40 | }
41 | this.data.values.SetColor3("diffuse", color, Color.white);
42 | this.data.values.SetNumber("opacity", color.a, Color.white.a);
43 | }
44 |
45 | public override void CollectDefines()
46 | {
47 | base.CollectDefines();
48 | this.data.asset.defines.Add(new Define() { name = "USE_COLOR" });
49 | }
50 |
51 | protected UnityEngine.Texture MainText
52 | {
53 | get
54 | {
55 | var orginmps = MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { source });
56 | foreach (var mp in orginmps)
57 | {
58 | if (mp.type.ToString() == "Texture")
59 | {
60 | var tex = source.GetTexture(mp.name);
61 | if (tex != null)
62 | {
63 | return tex;
64 | }
65 | }
66 | }
67 |
68 | return null;
69 | }
70 | }
71 |
72 | protected override bool isDoubleSide
73 | {
74 | get
75 | {
76 | return true;
77 | }
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/PhongParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using UnityEngine;
5 | public class PhongParser : DiffuseParser
6 | {
7 | public override void CollectUniformValues()
8 | {
9 | base.CollectUniformValues();
10 | var source = this.source;
11 | var shininess = 30.0f;
12 | if (this.source.HasProperty("_Shininess"))
13 | {
14 | shininess = this.source.GetFloat("_Shininess", 30.0f);
15 | if (shininess > 0.0f)
16 | {
17 | shininess = 1 / shininess;
18 | }
19 | }
20 | this.data.values.SetNumber("shininess", shininess, 30.0f);
21 |
22 | var specularMap = this.source.GetTexture("_SpecGlossMap", null);
23 | if (specularMap != null)
24 | {
25 | this.data.values.SetTexture("specularMap", specularMap);
26 | }
27 | var aoMap = this.source.GetTexture("_OcclusionMap", null);
28 | if (aoMap != null)
29 | {
30 | this.data.values.SetTexture("aoMap", aoMap);
31 | this.data.values.SetNumber("aoMapIntensity", this.source.GetFloat("_OcclusionStrength", 1.0f), 1.0f);
32 | }
33 | var emissiveMap = this.source.GetTexture("_EmissionMap", null);
34 | if (emissiveMap != null)
35 | {
36 | this.data.values.SetTexture("emissiveMap", emissiveMap);
37 | }
38 | var normalMap = this.source.GetTexture("_BumpMap", null);
39 | if (normalMap != null)
40 | {
41 | this.data.values.SetTexture("normalMap", normalMap);
42 | }
43 | var displacementMap = this.source.GetTexture("_ParallaxMap", null);
44 | if (displacementMap != null)
45 | {
46 | this.data.values.SetTexture("displacementMap", displacementMap);
47 | this.data.values.SetNumber("displacementScale", this.source.GetFloat("_Parallax", 1.0f), 1.0f);
48 | this.data.values.SetNumber("displacementBias", 0.0f, 0.0f);
49 | }
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/SkyboxCubedParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using UnityEngine;
4 | public class SkyboxCubedParser : BaseMaterialParser
5 | {
6 | public override void CollectUniformValues()
7 | {
8 | base.CollectUniformValues();
9 | var source = this.source;
10 | var values = this.data.values;
11 |
12 | if(source.HasProperty("_Tex"))
13 | {
14 | values.SetCubemap("tCube", source.GetTexture("_Tex") as Cubemap);
15 | }
16 | else
17 | {
18 | MyLog.LogWarning("请检查材质" + source.name + "Cubemap属性是否有值");
19 | }
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/SkyboxParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using UnityEngine;
4 | public class Texture2DArrayData : UnityEngine.Object
5 | {
6 | public string materialName;
7 | public Texture2D[] textures;
8 | }
9 | public class SkyboxParser : BaseMaterialParser
10 | {
11 | public override void CollectUniformValues()
12 | {
13 | base.CollectUniformValues();
14 | var source = this.source;
15 | var values = this.data.values;
16 |
17 | var frontTex = source.GetTexture("_FrontTex") as Texture2D;
18 | var backTex = source.GetTexture("_BackTex") as Texture2D;
19 | var leftTex = source.GetTexture("_LeftTex") as Texture2D;
20 | var rightTex = source.GetTexture("_RightTex") as Texture2D;
21 | var upTex = source.GetTexture("_UpTex") as Texture2D;
22 | var downTex = source.GetTexture("_DownTex") as Texture2D;
23 |
24 | /**
25 | *XxYyZz
26 | */
27 | var textureArr = new Texture2DArrayData();
28 | textureArr.textures = new Texture2D[6];
29 | textureArr.textures[0] = leftTex;
30 | textureArr.textures[1] = rightTex;
31 | textureArr.textures[2] = upTex;
32 | textureArr.textures[3] = downTex;
33 | textureArr.textures[4] = frontTex;
34 | textureArr.textures[5] = backTex;
35 | textureArr.materialName = source.name;
36 |
37 | Debug.Log("materialName:" + textureArr.materialName);
38 |
39 | this.data.values.SetTextureArray("tCube", textureArr);
40 | }
41 |
42 | public override void CollectStates()
43 | {
44 | var customConfig = ExportSetting.instance.GetCustomShader(this.shaderName);
45 | var isDoubleSide = this.isDoubleSide;
46 | var isTransparent = this.isTransparent;
47 |
48 | var blend = this.blendMode;
49 | // this.SetBlend(this.data.technique.states.enable, this.data.technique.states.functions, blend);
50 | this.SetCull(this.data.technique.states.enable, this.data.technique.states.functions, true, FrontFace.CCW, CullFace.FRONT);
51 | this.SetDepth(this.data.technique.states.enable, this.data.technique.states.functions, false, false);
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/StandardParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using System.Collections.Generic;
4 | using UnityEngine;
5 | public class StandardParser : BaseMaterialParser
6 | {
7 | protected virtual void StandardBegin()
8 | {
9 | var roughness = 1.0f - this.source.GetFloat("_Glossiness", 0.0f);
10 | var metalness = this.source.GetFloat("_Metallic", 0.0f);
11 | var emissive = this.source.GetColor("_EmissionColor", Color.clear);
12 |
13 | this.data.values.SetColor3("emissive", emissive, Color.clear);
14 | this.data.values.SetNumber("roughness", roughness, 0.5f);
15 | this.data.values.SetNumber("metalness", metalness, 0.5f);
16 |
17 | var metalnessMap = this.source.GetTexture("_MetallicGlossMap", null);
18 | if (metalnessMap != null)
19 | {
20 | this.data.values.SetTexture("metalnessMap", metalnessMap);
21 | }
22 | }
23 |
24 | public override void CollectUniformValues()
25 | {
26 | base.CollectUniformValues();
27 | var source = this.source;
28 | this.StandardBegin();
29 | var color = this.source.GetColor("_Color", Color.white);
30 | if (color != null)
31 | {
32 | this.data.values.SetColor3("diffuse", color, Color.white);
33 | }
34 | var map = this.source.GetTexture("_MainTex", null);
35 | if (map != null)
36 | {
37 | this.data.values.SetTexture("map", map);
38 | }
39 | var aoMap = this.source.GetTexture("_OcclusionMap", null);
40 | if (aoMap != null)
41 | {
42 | this.data.values.SetTexture("aoMap", aoMap);
43 | this.data.values.SetNumber("aoMapIntensity", this.source.GetFloat("_OcclusionStrength", 1.0f), 1.0f);
44 | }
45 |
46 | var emissiveMap = this.source.GetTexture("_EmissionMap", null);
47 | if (emissiveMap != null)
48 | {
49 | this.data.values.SetTexture("emissiveMap", emissiveMap);
50 | }
51 |
52 | var bumpMap = this.source.GetTexture("_BumpMap", null);
53 | if (bumpMap != null)
54 | {
55 | var bumpScale = this.source.GetFloat("_BumpScale", 1.0f);
56 | this.data.values.SetTexture("normalMap", bumpMap);
57 | this.data.values.SetVector2("normalScale", new UnityEngine.Vector2(bumpScale, bumpScale), Vector2.one);
58 | }
59 |
60 | var normalMap = this.source.GetTexture("_DetailNormalMap", null);
61 | if (normalMap != null)
62 | {
63 | var normalScale = this.source.GetFloat("_DetailNormalMapScale", 1.0f);
64 | this.data.values.SetTexture("normalMap", normalMap);
65 | this.data.values.SetVector2("normalScale", new UnityEngine.Vector2(normalScale, normalScale), Vector2.one);
66 | }
67 |
68 | var displacementMap = this.source.GetTexture("_ParallaxMap", null);
69 | if (displacementMap != null)
70 | {
71 | this.data.values.SetTexture("displacementMap", displacementMap);
72 | this.data.values.SetNumber("displacementScale", this.source.GetFloat("_Parallax", 1.0f), 1.0f);
73 | this.data.values.SetNumber("displacementBias", 0.0f, 0.0f);
74 | }
75 | }
76 |
77 | public override void CollectDefines()
78 | {
79 | base.CollectDefines();
80 | this.data.asset.defines.Add(new Define() { name = "STANDARD" });
81 | }
82 | }
83 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/StandardRoughnessParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using UnityEngine;
4 | public class StandardRoughnessParser : StandardParser
5 | {
6 | protected override void StandardBegin()
7 | {
8 | var roughness = this.source.GetFloat("_Glossiness", 0.0f);
9 | var metalness = this.source.GetFloat("_Metallic", 0.0f);
10 | var emissive = this.source.GetColor("_EmissionColor", Color.black);
11 |
12 | this.data.values.SetColor3("emissive", emissive, Color.black);
13 | this.data.values.SetNumber("roughness", roughness, 0.5f);
14 | this.data.values.SetNumber("metalness", metalness, 0.5f);
15 |
16 | var metalnessMap = this.source.GetTexture("_MetallicGlossMap", null);
17 | if (metalnessMap != null)
18 | {
19 | this.data.values.SetTexture("metalnessMap", metalnessMap);
20 | }
21 |
22 | var roughnessMap = this.source.GetTexture("_SpecGlossMap", null);
23 | if (roughnessMap != null)
24 | {
25 | this.data.values.SetTexture("roughnessMap", roughnessMap);
26 | }
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Assets/MaterialParser/StandardSpecularParser.cs:
--------------------------------------------------------------------------------
1 | namespace Egret3DExportTools
2 | {
3 | using UnityEngine;
4 | public class StandardSpecularParser : StandardParser
5 | {
6 | protected override void StandardBegin()
7 | {
8 | // var roughness = this.GetFloat("_Glossiness", 0.0f);
9 | var roughness = 1.0f;
10 | var metalness = this.source.GetFloat("_Metallic", 0.0f);
11 | var emissive = this.source.GetColor("_EmissionColor", Color.black);
12 |
13 | this.data.values.SetColor3("emissive", emissive, Color.black);
14 | this.data.values.SetNumber("roughness", roughness, 0.5f);
15 | this.data.values.SetNumber("metalness", metalness, 0.5f);
16 |
17 | var specularMap = this.source.GetTexture("_SpecGlossMap", null);
18 | if (specularMap != null)
19 | {
20 | this.data.values.SetTexture("specularMap", specularMap);
21 | }
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/AnimationSerializer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEditor;
3 | using UnityEngine;
4 | using System.Collections.Generic;
5 |
6 | namespace Egret3DExportTools
7 | {
8 | public class AnimationSerializer : ComponentSerializer
9 | {
10 | private List animationClips = new List();
11 | protected UnityEngine.AnimationClip[] _getAnimationClips(Component component)
12 | {
13 | return AnimationUtility.GetAnimationClips(component.gameObject);
14 | }
15 | protected override bool Match(Component component)
16 | {
17 | var animation = component as Animation;
18 | this.animationClips.Clear();
19 | if (animation.clip != null)
20 | {
21 | this.animationClips.Add(animation.clip);
22 | }
23 |
24 | var clips = _getAnimationClips(animation);
25 | if (clips != null && clips.Length > 0)
26 | {
27 | foreach (var clip in clips)
28 | {
29 | if (clip == animation.clip)
30 | {
31 | continue;
32 | }
33 |
34 | this.animationClips.Add(clip);
35 | }
36 | }
37 |
38 | if (this.animationClips.Count == 0)
39 | {
40 | return false;
41 | }
42 |
43 | return true;
44 | }
45 |
46 | protected override void Serialize(Component component, ComponentData compData)
47 | {
48 | var animation = component as Animation;
49 | compData.properties.SetBool("autoPlay", animation.playAutomatically);
50 | compData.properties.SetAnimation(component.gameObject, this.animationClips.ToArray());
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/AnimatorSerializer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class AnimatorSerializer : AnimationSerializer
7 | {
8 | protected override bool Match(Component component)
9 | {
10 | var aniamtior = component as Animator;
11 | if (aniamtior.runtimeAnimatorController == null)
12 | {
13 | MyLog.Log("缺少runtimeAnimatorController");
14 | return false;
15 | }
16 | var clips = aniamtior.runtimeAnimatorController.animationClips;
17 | if (clips == null || clips.Length == 0)
18 | {
19 | MyLog.Log("clips为空");
20 | return false;
21 | }
22 |
23 | return true;
24 | }
25 | protected override void Serialize(Component component, ComponentData compData)
26 | {
27 | var aniamtior = component as Animator;
28 | var clips = aniamtior.runtimeAnimatorController.animationClips;
29 | compData.properties.SetBool("autoPlay", true); // TODO
30 | compData.properties.SetAnimation(component.gameObject, clips);
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/BoxColliderSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System;
3 | using Newtonsoft.Json.Linq;
4 | namespace Egret3DExportTools
5 | {
6 | public class BoxColliderSerializer : ComponentSerializer
7 | {
8 | protected override void Serialize(Component component, ComponentData compData)
9 | {
10 | BoxCollider comp = component as BoxCollider;
11 |
12 | var halfSize = comp.size * 0.5f;
13 | var minimum = comp.center - halfSize;
14 | var maximum = comp.center + halfSize;
15 | JArray aabbItem = new JArray();
16 | aabbItem.AddNumber(minimum.x);
17 | aabbItem.AddNumber(minimum.y);
18 | aabbItem.AddNumber(minimum.z);
19 | aabbItem.AddNumber(maximum.x);
20 | aabbItem.AddNumber(maximum.y);
21 | aabbItem.AddNumber(maximum.z);
22 |
23 | compData.properties.Add("aabb", aabbItem);
24 | }
25 | }
26 | }
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/CameraSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class CameraSerializer : ComponentSerializer
7 | {
8 | protected override void Serialize(Component component, ComponentData compData)
9 | {
10 | Camera comp = component as Camera;
11 | if (comp.orthographic)
12 | {
13 | compData.properties.SetNumber("size", 2 * comp.orthographicSize);//half-size?
14 | compData.properties.SetInt("opvalue", 0);
15 | }
16 | else
17 | {
18 | compData.properties.SetNumber("fov", comp.fieldOfView / 57.3, 4);
19 | compData.properties.SetInt("opvalue", 1);
20 | }
21 | compData.properties.SetNumber("near", comp.nearClipPlane);
22 | compData.properties.SetNumber("far", comp.farClipPlane);
23 | compData.properties.SetInt("cullingMask", comp.cullingMask);
24 |
25 | //clearFlags
26 | var clearFlags = comp.clearFlags;
27 | if(clearFlags == CameraClearFlags.SolidColor || clearFlags == CameraClearFlags.Skybox)
28 | {
29 | compData.properties.SetInt("bufferMask", 16640);
30 | }
31 | else if(clearFlags == CameraClearFlags.Depth)
32 | {
33 | compData.properties.SetInt("bufferMask", 256);
34 | }
35 | else
36 | {
37 | compData.properties.SetInt("bufferMask", 0);
38 | }
39 |
40 | //backgroundColor
41 | compData.properties.SetColor("backgroundColor", comp.backgroundColor);
42 | //viewport
43 | compData.properties.SetRect("viewport", comp.rect);
44 | //order
45 | compData.properties.SetNumber("order", comp.depth);
46 | }
47 | }
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/DirectionalLightSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityEngine.Rendering;
3 | using System;
4 |
5 | namespace Egret3DExportTools
6 | {
7 | public class DirectionalLightSerializer : ComponentSerializer
8 | {
9 | protected override bool Match(Component component)
10 | {
11 | Light comp = component as Light;
12 | return comp.type == LightType.Directional;
13 | }
14 | protected override void Serialize(Component component, ComponentData compData)
15 | {
16 | Light comp = component as Light;
17 | compData.properties.SetBool("castShadows", comp.shadows != LightShadows.None);
18 | compData.properties.SetNumber("intensity", comp.intensity);
19 | compData.properties.SetColor("color", comp.color);
20 | compData.properties.SetInt("cullingMask", comp.cullingMask);
21 |
22 | if (comp.shadows != LightShadows.None)
23 | {
24 | //
25 | var shadow = SerializeObject.currentData.CreateComponent(SerializeClass.LightShadow);
26 | shadow.properties.SetNumber("radius", 1.0f); // TODO
27 | shadow.properties.SetNumber("bias", -0.0001f);
28 | shadow.properties.SetNumber("near", comp.shadowNearPlane);
29 | shadow.properties.SetNumber("far", 500.0f);
30 | shadow.properties.SetNumber("size", comp.cookieSize);
31 | shadow.properties.SetEnum("quality", comp.shadowResolution);
32 |
33 | (compData as ComponentData).entity.AddComponent(shadow);
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/MeshFilterSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class MeshFilterSerializer : ComponentSerializer
7 | {
8 | protected override void Serialize(Component component, ComponentData compData)
9 | {
10 | MeshFilter comp = component as MeshFilter;
11 | compData.properties.SetMesh(component.gameObject, comp.sharedMesh);
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/MeshRendererSerializer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class MeshRendererSerializer : ComponentSerializer
7 | {
8 | protected override void Serialize(Component component, ComponentData compData)
9 | {
10 | MeshRenderer comp = component as MeshRenderer;
11 | compData.properties.SetBool("isStatic", component.gameObject.isStatic);
12 |
13 | var sceneSetting = ExportSetting.instance.scene;
14 | if(sceneSetting.lightmap)
15 | {
16 | compData.properties.SetInt("lightmapIndex", comp.lightmapIndex);
17 | compData.properties.SetVector4("lightmapScaleOffset", comp.lightmapScaleOffset, null, 8);
18 | }
19 | compData.properties.SetBool("_castShadows", comp.shadowCastingMode != UnityEngine.Rendering.ShadowCastingMode.Off);
20 | compData.properties.SetBool("_receiveShadows", comp.receiveShadows);
21 | compData.properties.SetMaterials(component.gameObject, comp.sharedMaterials);
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/ParticleRendererSerializer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class ParticleRendererSerializer : ComponentSerializer
7 | {
8 | protected override bool Match(Component component)
9 | {
10 | var obj = component.gameObject;
11 | ParticleSystemRenderer comp = component as ParticleSystemRenderer;
12 | ParticleSystem c = obj.GetComponent();
13 | if (c == null || !c.emission.enabled)
14 | {
15 | MyLog.LogWarning("无效的粒子组件:" + obj.name);
16 | return false;
17 | }
18 | if (comp.renderMode == ParticleSystemRenderMode.Mesh && comp.mesh == null)
19 | {
20 | MyLog.LogWarning(obj.name + ": mesh 丢失");
21 | return false;
22 | }
23 |
24 | return true;
25 | }
26 | protected override void Serialize(Component component, ComponentData compData)
27 | {
28 | var obj = component.gameObject;
29 | ParticleSystemRenderer comp = component as ParticleSystemRenderer;
30 | ParticleSystem c = obj.GetComponent();
31 | compData.properties.SetNumber("velocityScale", comp.velocityScale);
32 | compData.properties.SetNumber("lengthScale", comp.lengthScale);
33 | compData.properties.SetEnum("renderMode", comp.renderMode);
34 | //Mesh
35 | compData.properties.SetMesh(obj, comp.mesh);
36 | //Material粒子系统不支持多材质
37 | compData.properties.SetMaterials(obj, new Material[] { comp.sharedMaterial }, true);
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/SkinnedMeshRendererSerializer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class SkinnedMeshRendererSerializer : ComponentSerializer
7 | {
8 | protected override void Serialize(Component component, ComponentData compData)
9 | {
10 | SkinnedMeshRenderer comp = component as SkinnedMeshRenderer;
11 |
12 | var meshFilter = SerializeObject.currentData.CreateComponent(SerializeClass.MeshFilter);
13 | meshFilter.properties.SetMesh(component.gameObject, comp.sharedMesh);
14 | (compData as ComponentData).entity.AddComponent(meshFilter);
15 |
16 | compData.properties.SetBool("_castShadows", comp.shadowCastingMode != UnityEngine.Rendering.ShadowCastingMode.Off);
17 | compData.properties.SetBool("_receiveShadows", comp.receiveShadows);
18 | compData.properties.SetMaterials(component.gameObject, comp.sharedMaterials, false, true);
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/SkyboxSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Egret3DExportTools
4 | {
5 | public class SkyboxSerializer : ComponentSerializer
6 | {
7 | protected override void Serialize(Component component, ComponentData compData)
8 | {
9 | Skybox comp = component as Skybox;
10 | base.Serialize(component, compData);
11 |
12 | var mats = new Material[1] { comp.material };
13 | compData.properties.SetMaterials(component.gameObject, mats);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/SphereColliderSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | using Newtonsoft.Json.Linq;
7 | public class SphereColliderSerializer : ComponentSerializer
8 | {
9 | protected override void Serialize(Component component, ComponentData compData)
10 | {
11 | SphereCollider comp = component as SphereCollider;
12 | var arr = new JArray();
13 | arr.AddNumber(comp.center.x);
14 | arr.AddNumber(comp.center.y);
15 | arr.AddNumber(comp.center.z);
16 | arr.AddNumber(comp.radius);
17 |
18 | compData.properties.Add("sphere", arr);
19 | }
20 | }
21 | }
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/SpotLightSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System;
3 |
4 | namespace Egret3DExportTools
5 | {
6 | public class SpotLightSerializer : DirectionalLightSerializer
7 | {
8 | protected override bool Match(Component component)
9 | {
10 | Light comp = component as Light;
11 | return comp.type == LightType.Spot;
12 | }
13 | protected override void Serialize(Component component, ComponentData compData)
14 | {
15 | Light comp = component as Light;
16 | base.Serialize(component, compData);
17 | compData.properties.SetNumber("distance", comp.range);
18 | compData.properties.SetNumber("angle", comp.spotAngle * Math.PI / 180.0f);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/Components/TransformSerializer.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | namespace Egret3DExportTools
4 | {
5 | public class TransformSerializer : ComponentSerializer
6 | {
7 | protected override void Serialize(Component component, ComponentData compData)
8 | {
9 | var obj = component.gameObject;
10 | Transform comp = component as Transform;
11 |
12 | Vector3 localPosition = comp.localPosition;
13 | Quaternion localRotation = comp.localRotation;
14 | Vector3 localScale = comp.localScale;
15 |
16 | compData.properties.SetBool("isStatic", obj.isStatic);
17 | //localPosition
18 | compData.properties.SetVector3("_localPosition", localPosition);
19 | //localRotation
20 | compData.properties.SetQuaternion("_localRotation", localRotation);
21 | //localScale
22 | compData.properties.SetVector3("_localScale", localScale);
23 |
24 | //
25 | var treeNode = SerializeObject.currentData.CreateComponent(SerializeClass.TreeNode);
26 | treeNode.properties.SetString("name", obj.name);
27 | treeNode.properties.SetString("tag", obj.tag);
28 | treeNode.properties.SetInt("layer", 1 << obj.layer);
29 | if (comp.childCount > 0)
30 | {
31 | for (int i = 0; i < comp.childCount; i++)
32 | {
33 | var child = comp.GetChild(i).gameObject;
34 | if (child.gameObject.activeInHierarchy)
35 | {
36 | var childEntity = SerializeObject.SerializeEntity(child);
37 | treeNode.AddChild(childEntity.treeNode);
38 | }
39 | }
40 | }
41 |
42 | compData.entity.AddComponent(treeNode);
43 |
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/UnityExportTool/src/Serialization/SerializerBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 | using GLTF.Schema;
5 | using System.IO;
6 |
7 | namespace Egret3DExportTools
8 | {
9 | /**
10 | * 组件管理器接口
11 | */
12 | public interface ISerializer
13 | {
14 | Type compType { set; get; }
15 | string className { set; get; }
16 | bool Match(UnityEngine.Object component);
17 | void Serialize(UnityEngine.Object component, SerizileData compData);
18 | }
19 |
20 | public abstract class Serializer : ISerializer
21 | {
22 | protected Type _compType;
23 | protected string _className;
24 |
25 | public virtual bool Match(UnityEngine.Object component)
26 | {
27 | return true;
28 | }
29 |
30 | public virtual void Serialize(UnityEngine.Object component, SerizileData compData)
31 | {
32 | }
33 |
34 | public Type compType { get => _compType; set => _compType = value; }
35 | public string className { get => _className; set => _className = value; }
36 | }
37 |
38 | public abstract class ComponentSerializer : Serializer
39 | {
40 | protected virtual void Serialize(Component component, ComponentData compData)
41 | {
42 | }
43 |
44 | protected virtual bool Match(Component component)
45 | {
46 | return true;
47 | }
48 |
49 | public override bool Match(UnityEngine.Object component)
50 | {
51 | return this.Match(component as Component);
52 | }
53 |
54 | public override void Serialize(UnityEngine.Object component, SerizileData compData)
55 | {
56 | this.Serialize(component as Component, compData as ComponentData);
57 | }
58 | }
59 |
60 | public abstract class AssetSerializer : Serializer
61 | {
62 | protected GLTFRoot _root;
63 | protected BufferId _bufferId;
64 | protected GLTF.Schema.Buffer _buffer;
65 | protected BinaryWriter _bufferWriter;
66 | public Transform _target;
67 | protected virtual void Serialize(UnityEngine.Object sourceAsset)
68 | {
69 |
70 | }
71 | protected virtual void InitGLTFRoot()
72 | {
73 | this._root = new GLTFRoot
74 | {
75 | Accessors = new List(),
76 | Asset = new Asset
77 | {
78 | Version = "2.0",
79 | Generator = "Unity plugin for egret",
80 | Extensions = new Dictionary(),
81 | },
82 | ExtensionsRequired = new List(),
83 | ExtensionsUsed = new List(),
84 | Extensions = new Dictionary() { { "egret", new AssetVersionExtension() { version = "5.0", minVersion = "5.0" } } },
85 | };
86 | }
87 |
88 | public override void Serialize(UnityEngine.Object sourceAsset, SerizileData asset)
89 | {
90 | this._target = SerializeObject.currentTarget;
91 | this.InitGLTFRoot();
92 | this.Serialize(sourceAsset);
93 |
94 | if (this._bufferWriter != null)
95 | {
96 | //二进制数据
97 | var ms = this._bufferWriter.BaseStream as MemoryStream;
98 | var binBuffer = ms.ToArray();
99 | this._bufferWriter.Close();
100 |
101 | this._buffer.Uri = "";
102 | this._buffer.ByteLength = binBuffer.Length;
103 |
104 | ms = new MemoryStream();
105 | var streamWriter = new StreamWriter(ms);
106 | this._root.Serialize(streamWriter);
107 | streamWriter.Close();
108 | var jsonBuffer = ms.ToArray();
109 |
110 | var writer = new BinaryWriter(new MemoryStream());
111 | (asset as AssetData).buffer = GLTFExtension.WriteBinary(jsonBuffer, binBuffer, writer);
112 | writer.Close();
113 | }
114 | else
115 | {
116 | //JSON数据
117 | var writer = new StringWriter();
118 | this._root.Serialize(writer);
119 | var jsonBuffer = System.Text.Encoding.UTF8.GetBytes(writer.ToString());
120 | (asset as AssetData).buffer = jsonBuffer;
121 | writer.Close();
122 | }
123 |
124 | this._bufferWriter = null;
125 | }
126 | }
127 | }
--------------------------------------------------------------------------------