Handling merge
This commit is contained in:
@@ -65,3 +65,4 @@ crashlytics-build.properties
|
||||
/VMDRecords
|
||||
/umamusume
|
||||
Config.json
|
||||
/gltf
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,109 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6a3c684705042f345975d924f6983e36
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
: Linux
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: x86
|
||||
- first:
|
||||
: OSXIntel
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: OSXIntel64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: SamsungTV
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
STV_MODEL: STANDARD_13
|
||||
- first:
|
||||
: Tizen
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
- first:
|
||||
Android: Android
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 0
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DefaultValueInitialized: true
|
||||
OS: AnyOS
|
||||
- first:
|
||||
Standalone: Linux64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
WebGL: WebGL
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DontProcess: False
|
||||
PlaceholderPath: Assets/JsonDotNet/Assemblies/Standalone/Newtonsoft.Json.dll
|
||||
SDK: AnySDK
|
||||
ScriptingBackend: Il2Cpp
|
||||
- first:
|
||||
iPhone: iOS
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CompileFlags:
|
||||
FrameworkDependencies:
|
||||
- first:
|
||||
tvOS: tvOS
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6807fedb8dcaf04682d2c84f0ab753f
|
||||
timeCreated: 1466788355
|
||||
licenseType: Store
|
||||
TextScriptImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Binary file not shown.
@@ -1,106 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 17aef65a15b471f468b5fbeb4ff0c6a1
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
: Linux
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: x86
|
||||
- first:
|
||||
: LinuxUniversal
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: OSXIntel
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: OSXIntel64
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: SamsungTV
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
STV_MODEL: STANDARD_13
|
||||
- first:
|
||||
Android: Android
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 0
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DefaultValueInitialized: true
|
||||
OS: AnyOS
|
||||
- first:
|
||||
Standalone: Linux64
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: OSXUniversal
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win64
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DontProcess: False
|
||||
PlaceholderPath:
|
||||
SDK: AnySDK
|
||||
ScriptingBackend: Il2Cpp
|
||||
- first:
|
||||
iPhone: iOS
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CompileFlags:
|
||||
FrameworkDependencies:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,9 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1418141139a6ac443b18cb05c0643a29
|
||||
folderAsset: yes
|
||||
timeCreated: 1466788345
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,94 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9b6ba260dada0ea4a871a42011f8b87d
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
: Linux
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: x86
|
||||
- first:
|
||||
: OSXIntel
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: OSXIntel64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
: SamsungTV
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
STV_MODEL: STANDARD_13
|
||||
- first:
|
||||
Android: Android
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 0
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DefaultValueInitialized: true
|
||||
OS: AnyOS
|
||||
- first:
|
||||
Standalone: Linux64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Standalone: Win64
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 1
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
DontProcess: False
|
||||
PlaceholderPath: Assets/JsonDotNet/Assemblies/Standalone/Newtonsoft.Json.dll
|
||||
SDK: AnySDK
|
||||
ScriptingBackend: DotNet
|
||||
- first:
|
||||
iPhone: iOS
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CompileFlags:
|
||||
FrameworkDependencies:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,9 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 76f828f47ce26cc43991113c6a39dbbf
|
||||
folderAsset: yes
|
||||
timeCreated: 1466010535
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<linker>
|
||||
<assembly fullname="System">
|
||||
<type fullname="System.ComponentModel.TypeConverter" preserve="all" />
|
||||
<!-- <namespace fullname="System.ComponentModel" preserve="all" /> -->
|
||||
</assembly>
|
||||
</linker>
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1fdd4de1668fa554d87e5651110ab090
|
||||
guid: cca4e724a4f1a794f94359c549baa672
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -0,0 +1,554 @@
|
||||
# Changelog
|
||||
All notable changes to this package will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
|
||||
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
|
||||
|
||||
|
||||
## [1.24.0-pre.2] - 2023-03-28
|
||||
- fix: nullref when importing files without animation in the editor
|
||||
|
||||
## [1.24.0-pre] - 2023-03-27
|
||||
- feat: allow Mecanim Humanoid import in Editor with Avatar creation
|
||||
- feat: better structure for glTF importer with tabs
|
||||
- fix: don't try to generate UV coordinates for non-triangle meshes
|
||||
- fix: don't attempt to recalculate normals/tangents for non-triangle meshes
|
||||
- fix: wrap material extraction in StartEditing/StopEditing calls (fixes #81)
|
||||
- fix: imports that failed on first try (e.g. missing textures, other errors) would keep using the old asset identifier instead of defaulting to the new one
|
||||
- fix: runtime recording of SkinnedMeshRenderers without blend shapes was failing in some cases (fixes #80)
|
||||
- fix: disabling Volume from PBRGraph would still use volume values
|
||||
- fix: imported animation blendshape frame weights were not roundtripping well
|
||||
- fix: some animations not imported in Mecanim mode
|
||||
- fix: compilation issues with ShaderGraph package not present
|
||||
|
||||
## [1.23.1-pre] - 2023-03-15
|
||||
- fix: ExportMesh not exporting submeshes in some cases
|
||||
- fix: missing export mesh marker
|
||||
|
||||
## [1.23.0-pre] - 2023-03-03
|
||||
- fix: revert other possible modifications when recording animations
|
||||
- fix: exporting animation curves failed for blendshape animations on missing targets
|
||||
- fix: better info for which object has missing curves on animation export
|
||||
- feat: transparent/double-sided materials can now be upgraded from 2020.x to 2021.x+
|
||||
|
||||
## [1.22.4-pre] - 2023-02-25
|
||||
- fix: revert prefab modifications when recording humanoid animation from prefab assets to work around AnimationMode limitations
|
||||
- fix: creation of duplicated keyframe when there is only one keyframe
|
||||
- change: clarify log for rotation animation export with wrong number of curves
|
||||
|
||||
## [1.22.3-pre] - 2023-02-09
|
||||
- fix: specular extension factor roundtrip was incorrect
|
||||
- fix: MSFT_lods import created the wrong hierarchy and the culling option wasn't working
|
||||
- fix: edge case in node/mesh imports in extensions that could lead to a stack overflow
|
||||
- fix: calling `GLTFImporterInspector.FixTextureImportSettings` could result in an infite loop when called from an AssetPostprocessor
|
||||
|
||||
## [1.22.2-pre] - 2023-02-04
|
||||
- fix: set morph target names from mesh extras on import (#70, thanks @emperorofmars)
|
||||
|
||||
## [1.22.1-pre] - 2023-02-04
|
||||
- fix: broken texture references prevented files from loading entirely
|
||||
- fix: .bin file was not properly registered as dependency for the imported .gltf asset
|
||||
- fix: shader issue with instance ID transfer on 2021.x (#71, thanks @Jerem-35)
|
||||
- fix: normal map colorspace was wrong on Mac in some cases (#74, thanks @robertlong)
|
||||
- fix: ORM maps were exported with empty/unneeded alpha channel (#77, thanks @robertlong)
|
||||
|
||||
## [1.22.0-pre] - 2023-02-01
|
||||
- feat: expose ExportNode API
|
||||
- feat: optionally calculate and place bounds markers in GltfRecorder for viewers that don't caclulate bounds from animated skinned meshes properly (experimental)
|
||||
|
||||
## [1.21.1-pre] - 2023-01-20
|
||||
- fix: animator being disabled after exporting humanoid animationclip
|
||||
- fix: ignore MotionT and MotionQ on animator, can't be resolved for KHR_animation, seems to be a magic unity name
|
||||
- fix: build error by accessing imageContentHash
|
||||
- change: export HDR textures with zip compression by default
|
||||
|
||||
## [1.21.0-pre] - 2023-01-14
|
||||
- feat: allow aborting export when not in Play Mode and meshes are not readable - seems to be a random Unity synchronization context issue
|
||||
- fix: don't export unsupported light types (e.g. area light has type "rectangle" which is not supported in glTF)
|
||||
- fix: Export human motion translation
|
||||
- fix: prevent exporting the same baked humanoid clip for different avatars, needs individual clips since we're baking them (not retargeting at runtime)
|
||||
- fix: reusing animation clips between objects with different hierarchies caused some targets to be missing, depending on export order
|
||||
- change: remove warning for KHR_animation_pointer resolving when the unresolved object is a transform, that's part of core
|
||||
|
||||
## [1.20.3-pre] - 2023-01-13
|
||||
- fix: wrong texture name in Texture Transform check
|
||||
- fix: better check if a texture is a normal map and needs the right import settings
|
||||
- fix: uris with escaped characters didn't correctly import in the editor
|
||||
|
||||
## [1.20.2-pre] - 2023-01-12
|
||||
- fix: export of color animations where only one channel is animated
|
||||
- fix: order of animationcurve properties when exporing animated colors in component where e.g. a user started by animating a single channel first (e.g. alpha) and later added keyframes for other channels
|
||||
|
||||
## [1.20.1-pre] - 2023-01-10
|
||||
- fix: issue with exporting shared texture samplers in some cases
|
||||
- fix: weights on skinned meshes shouldn't be resolved by custom KHR_animation_pointer resolvers as they're part of the core spec
|
||||
- change: remove logs when caching data
|
||||
- change: move cache clear button into settings
|
||||
- add: KHR_materials_clearcoat roundtrip support (no in-editor visualization yet)
|
||||
|
||||
## [1.20.0-pre] - 2023-01-04
|
||||
- add: caching of texture bytes on disc for faster export (can be disabled in UnityGLTFSettings)
|
||||
|
||||
## [1.19.1-pre] - 2023-01-03
|
||||
- add: AfterPrimitiveExport event
|
||||
|
||||
## [1.19.0-pre] - 2022-12-14
|
||||
- add: spritesheet keyframe animation export
|
||||
- change: print warning when animation pointer cant be resolved and add filtering of objects that cant be resolved before building animation data
|
||||
- fix: index discrepancy between _exportedMaterials and _root.Materials lead to wrong texture indices being returned in some cases
|
||||
- fix: don't write and declare IOR when it's at the default value
|
||||
- fix: importing textures with names resulted in those names not being used (only image names were used)
|
||||
- fix: importing files without baseMap but using texture transforms for normal or emissive would result in texture transforms not being used
|
||||
|
||||
## [1.18.5-pre] - 2022-12-02
|
||||
- fix: default material was missing in build
|
||||
|
||||
## [1.18.4-pre] - 2022-12-02
|
||||
- fix: GLTFRecorder didn't properly record with animation pointer off anymore
|
||||
- fix: unified access to SkinnedMeshRenderer weights on export
|
||||
- fix: nullrefs in ExportPlan with missing SkinnedMeshRenderer
|
||||
- feat: allow passing custom settings into GLTFRecorder
|
||||
|
||||
## [1.18.3-pre] - 2022-11-14
|
||||
- fix: disabled MeshRenderers and SkinnedMeshRenderers were not exported despite ExportDisabledGameObjects being on
|
||||
- fix: sample root transform as well in Humanoid export to prevent shifting it around when recording
|
||||
|
||||
## [1.18.2-pre] - 2022-11-10
|
||||
- fix: exception thrown when trying to add a material instance id twice
|
||||
|
||||
## [1.18.1-pre] - 2022-11-09
|
||||
- fix: ExportMeshes was not exporting new meshes since the internal material check didn't let it through
|
||||
|
||||
## [1.18.0-pre] - 2022-11-07
|
||||
- fix: blend shape weight animation wasn't properly exported in some cases
|
||||
- fix: IOR extension may end up as null when IOR was animated
|
||||
- fix: rough refracton LOD access is now affected by alpha blending
|
||||
- feat: HDR render textures can be exported now
|
||||
- feat: add ExportMesh(Mesh) API as convenience helper
|
||||
- feat: add material remapping to glTF/GLB importer
|
||||
- chore: code cleanup for rough refraction and material inspector
|
||||
- change: animation export code paths have been consolidated, less differences between KHR_animation_pointer and regular export
|
||||
- change: bumped min Unity version to 2019.4
|
||||
|
||||
## [1.17.2-pre] - 2022-10-21
|
||||
- fix: set linear export setting before accessing texture exporter settings for unknown textures
|
||||
|
||||
## [1.17.1-pre] - 2022-10-19
|
||||
- fix: glb export now using utf8 (no BOM)
|
||||
- fix: simplify and fix normals export
|
||||
|
||||
## [1.17.0-pre] - 2022-10-12
|
||||
- add: import options for animation loop and re-enable by default for Mecanim
|
||||
- fix: reimport assets when colorspace changes
|
||||
- fix: texture map type needs to be passed into UniqueTexture, otherwise textures used for different things don't get exported correctly
|
||||
- fix: bake smoothness values into roughness map if there's no good conversion
|
||||
- fix: alpha cutout export on BiRP
|
||||
- fix: base color warning should only be shown for transparent objects
|
||||
- fix: improve alpha cutout inspector for 2020.3
|
||||
- fix: smoothness was inverted / removed even if no smoothness map existed
|
||||
- change: refactor TextureMapType to contain options for conversion to clean up export and introduce ability to convert smoothness
|
||||
- change: refactor textureSlots, usage of textureSlot names and how they should be called
|
||||
|
||||
## [1.16.3-pre] - 2022-10-06
|
||||
- fix: KHR_animation_pointer bug with re-used animations targeting properties on nodes
|
||||
|
||||
## [1.16.2-pre] - 2022-09-30
|
||||
- fix: blend shapes and blend shape animations were not imported (note: sparse accessor import not working yet)
|
||||
- fix: allow doublesided and transparent import on 2020.3 URP with PBRGraph
|
||||
- fix: make RegisterPrimitivesWithNode API public, belongs to ExportMesh
|
||||
- fix: UnlitGraph used wrong texture transform in some cases
|
||||
- fix: BiRP texture import on legacy shaders in < 2020.3 had flipped texture transforms
|
||||
- fix: ExporterMaterials compilation issue on 2018.x
|
||||
- fix: some TMPro materials were exported incorrectly
|
||||
|
||||
## [1.16.1-pre] - 2022-09-25
|
||||
- fix: first-time import was failing to find shaders on 2020.x in some cases
|
||||
- fix: TMPro texture conversion one export was blurry at the bottom of the texture
|
||||
- fix: transmission/volume mat was incorrectly imported
|
||||
- fix: transparency was incorrectly imported on 2020.x
|
||||
- fix: material validation on 2021.x wasn't properly turning transparency on for some imports
|
||||
- fix: no compilation errors on 2018.4 + 2019.4
|
||||
|
||||
## [1.16.0-pre] - 2022-09-21
|
||||
- fix: checking materials for _ST shader properties was failing on specific Unity versions
|
||||
- fix: AnimationPointerResolver was warning in cases that are allowed / no warning needed
|
||||
- fix: build compilation issues on 2022+
|
||||
- fix: default scene name differed from glTFast, which broke switching importers. Both use "Scene" now
|
||||
- fix: import warnings for metallicRoughness texture swizzling only print when a metallicRoughness texture is actually used
|
||||
- feat: tangents are recalculated on import now
|
||||
- feat: TMPro meshes export with baked texture now instead of SDF texture
|
||||
- feat: added AfterTextureExportDelegate/BeforeTextureExportDelegate and UniqueTexture hash for modifying textures on export
|
||||
- change: explicit bool option to turn KHR_materials_volume export on and off
|
||||
- change: removed outdated samples from package
|
||||
- change: if a mesh in the glTF doesn't specify a name it will import without name now instead of using a default name
|
||||
|
||||
## [1.15.0-pre] - 2022-09-13
|
||||
- fix: workaround for ShaderGraph bug on 2021.2+ that breaks defining baseColorTexture_ST manually
|
||||
- fix: workaround for Unity regression in 2022.1+ where checking material properties returns wrong results in some cases
|
||||
- feat: allow exporting of Humanoid animation clips (get baked to generic)
|
||||
- change: texture aniso values >= 1 now result in LinearMipmapLinear filtering to match visual result in Unity better
|
||||
|
||||
## [1.14-0-pre] - 2022-09-11
|
||||
- fix: log error instead of exception for missing textures on export
|
||||
- feat: allow referencing GameObjects for `KHR_animation_pointer`
|
||||
- change: animated fields with `KHR_animation_pointer` now try to find their correct Unity properties instead of the serialized field (m_ prefix disappears)
|
||||
|
||||
## [1.13.0-pre] - 2022-09-05
|
||||
- add: preliminary HDR texture export in EXT_texture_exr extension
|
||||
- fix: Unity Editor module related issues
|
||||
- fix: wrongly exporting two keyframes for animations with only one keyframe
|
||||
- fix: children of lights and cameras were inverted
|
||||
|
||||
## [1.12.2-pre] - 2022-08-29
|
||||
- fix: KHR_animation_pointer export where member is declared on base type
|
||||
|
||||
## [1.12.1-pre] - 2022-08-23
|
||||
- fix: nullref in export of missing mesh
|
||||
|
||||
## [1.12.0-pre] - 2022-08-23
|
||||
- fix: emissive color alpha was set to 1 in some roundtrip cases when it should have been 0
|
||||
- fix: nullref in import when glTF had null textures (against the spec, but other viewers tolerate it)
|
||||
- fix: unlit double sided was incorrectly imported in BiRP
|
||||
- fix: PBRGraphUI didn't properly draw infos for SkinnedMeshRenderer
|
||||
- fix: added safeguards against Shader.Find not working in first imports (fixes #51)
|
||||
- fix: textures without mipmaps should export closer to intended now
|
||||
- fix: missing pbrMetallicRoughness property was treated incorrectly
|
||||
- fix: BeforeSceneExport was missing from gltf+bin exports
|
||||
- feat: warn in PBRGraphGUI when UV0 isn't present (fixes #52)
|
||||
- feat: texture channel swizzling on URP/Lit > PBRGraph material conversion in 2022.1+
|
||||
- feat: expose ExportMesh API using UniquePrimitive array to export arbitrary meshes from extensions (#55, thanks @robertlong)
|
||||
- feat: GLTFSettings can now be passed into GLTFSceneExporter directly, falls back to project settings if none are provided
|
||||
- remove: public settings API on GLTFSceneExporter is now gone. Pass in custom settings via ExportOptions if needed.
|
||||
|
||||
## [1.11.0-pre] - 2022-07-27
|
||||
- fix: converting PBRGraph and UnlitGraph to each other shouldn't warn
|
||||
- fix: multiple animators referencing the same clip exported animations incorrectly with KHR_animation_pointer on
|
||||
- fix: implemented partial animation target removal when some bindings animate missing objects
|
||||
- change: asset identifier for imported assets is now an explicit option
|
||||
- change: removed compilation flag to use new asset identifier, use the explicit option instead
|
||||
|
||||
## [1.10.1-pre] - 2022-07-18
|
||||
- fix: accessor submesh primtives were incorrectly assigned after internal duplication
|
||||
- fix: don't add import dependency on shaders, load them by GUID instead
|
||||
- fix: URI-escaped file names weren't always resolved correctly
|
||||
- fix: some KHR_animation_pointer export type fixes (vec3 colors vs. vec4 colors)
|
||||
- feat: add color helpers to PBRGraphGUI
|
||||
- feat: add UnlitGraph for 2021.2+
|
||||
- feat: new API, GetPrimitivesForMesh to add extensions to exported meshes (e.g. KHR_materials_variants)
|
||||
|
||||
## [1.10.0-pre] - 2022-07-06
|
||||
- fix: PBRGraph assignable again from shader dropdown
|
||||
- fix: various KHR_animation_pointer fixes to extension usage and property names
|
||||
- fix: compilation fixes for Unity 2018/2019
|
||||
- feat: add helper, callbacks and script generator for shader conversion
|
||||
- change: Importer/Exporter are now multiple partials
|
||||
- change: change GetAnimationTargetIdFrom[..] to Get[..]Index to clarify what it does
|
||||
|
||||
## [1.9.0-pre] - 2022-06-22
|
||||
- fix: properly set BiRP ShaderGraph transparency keywords
|
||||
- feat: PBRGraph property names now match glTF names directly (breaking change from 1.7.0+)
|
||||
- feat: PBRGraph now has a custom shader GUI that also validates keywords
|
||||
|
||||
## [1.8.1-pre] - 2022-06-22
|
||||
- fixed: same animation used on different objects should result in different pointer values with KHR_animation_pointer used
|
||||
- fixed: nullref when adding animation data for null object (e.g. unused property clip)
|
||||
- fixed: too many nodes get overwritten by duplicate animations with animation pointer
|
||||
- changed: GetAnimationId now takes root transform parameter
|
||||
- fixed: previously seen KHR_animation_pointer is now added to resolve list (e.g. when using animations on multiple objects and animating component values)
|
||||
|
||||
## [1.8.0-pre.2] - 2022-06-14
|
||||
- fixed: OcclusionTexture tiling now defaults to (1,1)
|
||||
- fixed: build errors on certain platforms
|
||||
|
||||
## [1.8.0-pre] - 2022-06-10
|
||||
- fixed: fixed package version, color space changes require minor version bump, not just patch
|
||||
- fixed: C# version error on 2020.3
|
||||
|
||||
## [1.7.1-pre.3] - 2022-06-10
|
||||
- feat: show extensions and textures in importer inspector
|
||||
- feat: export texture coord (UV0 / UV1) separately for "occlusionTexture" and "everything else", same as three.js
|
||||
- fixed: editor import of .gltf files with textures now uses those textures directly instead of creating new ones
|
||||
- fixed: exporting only includes extensions that are actually used or explicitly enabled
|
||||
- fixed: no more differences in color space between exporting glTF + textures or glb with embedded textures
|
||||
- fixed: importer properly declares shaders as dependencies, fixes library reimport errors
|
||||
|
||||
## [1.7.1-pre.2] - 2022-06-08
|
||||
- fixed: animation clip import in Editor working again
|
||||
|
||||
## [1.7.1-pre] - 2022-06-07
|
||||
- feat: sparse accessors import (partial)
|
||||
- feat: UV rotation import/export (for baseColorTexture only right now)
|
||||
- fixed: GLTFRecorderComponent error in play mode when only new input system is present
|
||||
- fixed: animation export with KHR_animation_pointer and reused nodes
|
||||
- fixed: passing invalid file names to Export could result in wrong buffer paths in JSON
|
||||
|
||||
## [1.7.0-pre] - 2022-06-01
|
||||
- feat: experimental support for KHR_animation_pointer
|
||||
- feat: experimental URP (2020.3+) & BiRP (2021.2+) Shader Graph for export and import, `UnityGLTF/PBRGraph`
|
||||
- feat: approximated support for exporting and importing KHR_materials_transmission, KHR_materials_volume, KHR_materials_ior, KHR_materials_iridescence, best used with `UnityGLTF/PBRGraph`
|
||||
- feat: renderer features and post effect for rough refraction / transmission (for URP and BiRP)
|
||||
- fixed: light and camera directions were flipped when animated
|
||||
- fixed: normal textures were exported with wrong color space in .gltf
|
||||
- fixed: WebRequestLoader edge case with relative paths
|
||||
- improved: better heuristic for PBR material export and generally better glTF-related material property export
|
||||
|
||||
## [1.6.1-pre.3] - 2022-05-10
|
||||
- feat: allow replacing logger for GLTFSceneExporter with a custom one, allows to reduce number of logs
|
||||
- feat: added more ProfilerMarkers
|
||||
- removed: removed submodules from repository to make usage as submodule in other projects easier
|
||||
- fixed: bad performance in GLTFRecorder when recording lots of animation and/or Blendshape weights
|
||||
- fixed: some mismatched ProfilerMarker.Begin/End calls
|
||||
- fixed: less allocations when writing accessors
|
||||
|
||||
## [1.6.1-pre.2] - 2022-05-06
|
||||
- feat: allow recording root object in worldspace in GLTFRecorder
|
||||
|
||||
## [1.6.1-pre] - 2022-05-06
|
||||
- feat: added experimental support for KHR_animation_pointer in-editor animation export (for select properties), can be turned on in `ProjectSettings/UnityGltf`
|
||||
- feat: added scene export as GLB (fixes #22)
|
||||
- fixed: roundtrip issues with glTFast when alpha testing is used
|
||||
- fixed: no build errors in Samples anymore
|
||||
- fixed: allow exporting skinned mesh animations even when the mesh isn't readable (bone animation is then still exported)
|
||||
|
||||
## [1.6.0-pre] - 2022-04-28
|
||||
- feat: added WebGL import support (export was already supported)
|
||||
- feat: added WebGL animation export support
|
||||
- feat: added onLoadComplete action to GLTFComponent
|
||||
- feat: added ProfilerMarkers for export
|
||||
- feat: import support for KHR_materials_emissive_strength
|
||||
- changed: replaced FileLoader/WebRequestLoader with simpler UnityWebRequestLoader for better platform support. Use the previous ones if you need streaming.
|
||||
- removed: removed unused shader variants from BiRP shaders
|
||||
- fixed: sparse accessor JSON is properly parsed (no sparse accessor import support yet though)
|
||||
- fixed: no more validation errors regarding minMag filters, bufferView.byteStride for animation samplers, bufferView.target for index/vertex data
|
||||
- fixed: only export KHR_materials_emissive_strength if emissive intensity > 1
|
||||
- fixed: URP roundtrip now works with glTFast imports (#42)
|
||||
- fixed: better handling of filenames for glTF + bin + textures export (#41, #40)
|
||||
- fixed: add vertex color alpha support, add _EmissionMap_ST support to BiRP shader
|
||||
- fixed: exporting Prefab assets directly from Project Window wasn't working properly when ExportDisabled was off
|
||||
- fixed: regression with serialization and roundtrip behaviour of spotlights
|
||||
|
||||
## [1.5.0-pre.2] - 2022-04-20
|
||||
- fixed: incorrect UV offset for tiled textures on export in some cases
|
||||
- feat: show exported glTF/GLB in explorer after exporting via Menu Item
|
||||
- feat: expose API for `GetAnimationId` for custom export logic
|
||||
|
||||
## [1.5.0-pre] - 2022-04-08
|
||||
|
||||
- added: dialogue window will ask when meshes are not readable at runtime in the editor
|
||||
- added: more samples regarding custom material extension export
|
||||
- changed: more GltfSceneExporter methods are now public to allow for custom extension exporting
|
||||
- changed: moving back to proper versioning; big jump from 1.0 to 1.5 to show that lots of changes have happened
|
||||
- fixed: no more ScriptedImporter collisions between UnityGltf, glTFast and Siccity glTF
|
||||
- fixed: corrected some export callback orders
|
||||
- fixed: random hangs when importing .gltf files via ScriptedImporter
|
||||
- fixed: correctly importing wrapModeS and wrapModeT now
|
||||
- fixed: correctly importing Mask mode and cutoff now
|
||||
|
||||
## [1.0.4-preview.35] - 2022-03-11
|
||||
- added better logs for unsupported animation tracks on export
|
||||
- added public methods in GLTFSceneExporter to allow for custom animation export
|
||||
- added first batch of samples for custom extensions export
|
||||
- fixed: Auto Referenced is back on on AsmDefs to keep legacy behaviour
|
||||
- fixed: first timeline keyframe was exported incorrectly in some cases
|
||||
- fixed: skins should be exported even when animation export is off
|
||||
- fixed: animation clips shouldn't be exported when exporting from Timeline recorder
|
||||
- fixed: MetallicGlossMap scale was incorrectly exported in some cases
|
||||
|
||||
## [1.0.4-preview.34] - 2022-02-23
|
||||
- added Accessor reuse between exported animations when they come from the same AnimationClip/speed pair
|
||||
- added optional project setting to export animation clips with unique names (lots of viewers don't support that)
|
||||
- fixed animation clips being merged when the same clip was used in multiple Animators
|
||||
|
||||
## [1.0.4-preview.33] - 2022-02-21
|
||||
- added export option to merge animator states with identical names into one animation
|
||||
- fixed export of multiple animations when they had the same name (was implicitly merged before, now explicit)
|
||||
- fixed export of multiple animations when they had the same animator state name but different speeds
|
||||
|
||||
## [1.0.4-preview.32] - 2022-02-10
|
||||
- fixed compilation issues on older Unity versions
|
||||
- fixed exporting in memory to GLB byte array
|
||||
- fixed dependency to Timeline and some modules not being clear / not guarded
|
||||
- fixed Readme containing outdated install instructions
|
||||
- fixed compiler errors when building to some platforms
|
||||
|
||||
## [1.0.4-preview.31] - 2022-02-08
|
||||
- added ability to record and export blend shapes at runtime
|
||||
- fixed settings not being loaded from Resources correctly at runtime
|
||||
- fixed another case of duplicate recorded keyframes
|
||||
|
||||
## [1.0.4-preview.30] - 2022-02-08
|
||||
- added start events to recorder, made key methods virtual
|
||||
- fixed GLTF recorder component global shortcuts; now uses regular keycode during play mode
|
||||
|
||||
## [1.0.4-preview.29] - 2022-02-07
|
||||
- added GLTFRecorderComponent to record at runtime
|
||||
- renamed recorder files to follow existing filenames
|
||||
- fixed compilation warning in GLTFSceneImporter
|
||||
- fixed: create export directory if it doesn't exist
|
||||
- fixed: blendshape export was missing flag to export no blendshapes at all
|
||||
- fixed: in some cases would attempt to record duplicate timestamps which is not allowed
|
||||
- fixed build error from GLTFSceneExporter
|
||||
|
||||
## [1.0.4-preview.28] - 2022-02-07
|
||||
- added glTF Timeline exporter track that allows for both editor and runtime animation export
|
||||
- added ability to export RenderTextures instead of erroring out, these can be exported for a while now
|
||||
- added export callbacks and made an initial set of export methods public to enable custom export extensions (similar to three.js export callbacks)
|
||||
- added export generator name
|
||||
- fixed URP/Unlit color not being exported
|
||||
- fixed light intensity values being incorrect depending on Unity settings
|
||||
- fixed removeEmptyRootObjects on import not actually removing empty root objects
|
||||
- fixed warning when exporting texture transforms if _MainTex_ST is present but _MainTex isn't
|
||||
- fixed non-specific textures using the wrong export type in some cases, asking the AssetImporter now if one exists
|
||||
- changed menu items, export options are now in "Assets/UnityGltf/" instead of a toplevel "GLTF" menu
|
||||
|
||||
## [1.0.4-preview.27] - 2021-12-02
|
||||
- fixed `_scaleFactor` not being applied to child transform positions for editor import
|
||||
- fixed roundtrip issues when exporting models that have been imported by UnityGLTF or glTFast
|
||||
- fixed metallicGlossMap being in the wrong color space on export if emission texture was also used
|
||||
- fixed light/occlusion map being in the wrong color space during roundtrip
|
||||
|
||||
## [1.0.4-preview.26] - 2021-11-16
|
||||
- fixed objects with EditorOnly tag being exported, are skipped now
|
||||
|
||||
## [1.0.4-preview.25] - 2021-11-12
|
||||
- fixed imported object names potentially not being unique
|
||||
- fixed normal map export format when build target is Android
|
||||
- fixed export of animations when multiple exported objects share the same animation name (gets merged on export now)
|
||||
- moved GLTF serialization from DLL to package to improve platform support (Unity will compile this for all platforms, no need for special DLLs)
|
||||
- added sparse accessor export for blendshape positions/normals
|
||||
- added ability to generate secondary UVs in UnityGLTF importer
|
||||
- added warning when trying to use KTX2 textures which is currently not supported
|
||||
|
||||
## [1.0.4-preview.24] - 2021-06-14
|
||||
- fix: don't attempt to export blendshape normals/tangents when mesh doesn't have them
|
||||
- fix: warn and skip null bones in SkinnedMeshRenderer export
|
||||
- added: settings for determining texture export type (png/jpeg depending on alpha channel) and JPEG quality
|
||||
- added: setting to determine if vertex colors should be exported
|
||||
|
||||
## [1.0.4-preview.23] - 2021-05-28
|
||||
- fixed animation export from legacy Animation component
|
||||
- fixed exporting blendshapes for meshes that don't have bones
|
||||
- fixed empty textures being generated on import
|
||||
- fixed emission keyword missing on material import when only color but no texture was set
|
||||
- fixed metallic and fade export not being correct in some cases
|
||||
- added option to select which properties (normals/tangents) to export with blendshapes
|
||||
|
||||
## [1.0.4-preview.22] - 2021-05-04
|
||||
- fixed ScriptedImporter not importing meshes from SkinnedMeshRenderers
|
||||
- fixed ScriptedImporter not importing AnimationClips
|
||||
- fixed ScriptedImporter changing material names on import
|
||||
- fixed blend shape data being exported multiple times when meshes have multiple submeshes
|
||||
- added blendshape animation export
|
||||
|
||||
## [1.0.4-preview.21] - 2021-04-26
|
||||
- fixed settings file directory not being created on settings file creation
|
||||
|
||||
## [1.0.4-preview.20] - 2021-04-24
|
||||
- added settings provider to change GLTF settings from `Project Settings/UnityGLTF`
|
||||
- added settings for control over object export based on visibility (`Camera.cullingMask`) and active state (`GameObject.activeInHierarchy`)
|
||||
- changed: experimental texture-from-disk export is now disabled by default
|
||||
- fixed exporting GameObjects with names that contain invalid filename characters
|
||||
- fixed normal sampling in built-in pipeline which most likely was never correct with scaled normals
|
||||
- fixed texture sampling for export/import that resulted in incorrect Point sampling in some cases
|
||||
- fixed some issues with exporting skinned mesh renderers
|
||||
- fixed regression with multi material/submesh export
|
||||
|
||||
## [1.0.4-preview.18] - 2021-04-16
|
||||
- CHANGED: package name is now back to org.khronos.unitygltf
|
||||
- fixed missing mesh logging an error, is now a warning
|
||||
- fixed property export order for URP shaders that also have built-in property fallbacks
|
||||
- fixed export path omitting extensions for cases such as 15-1.0.3.glb
|
||||
- fixed issue with shared meshes that have different materials not being properly exported (https://github.com/prefrontalcortex/UnityGLTF/issues/15)
|
||||
- added MenuItem validation methods to disable them if no valid object for export is selected
|
||||
- added ability to export selected Prefabs from the Project window directly
|
||||
- changed the GLTFImporter to overrideExt for 2020.1+ so that importer for .glb files can be chosen when multiple are present
|
||||
|
||||
## [1.0.4-preview.17] - 2021-03-23
|
||||
- fixed ACCESSOR_INDEX_PRIMITIVE_RESTART for meshes that have exactly 256 or 65536 vertices and used the wrong buffer type
|
||||
- fixed vertex color import color space and alpha usage
|
||||
- fixed incorrect keyframe values causing import abort, just warns now
|
||||
- fixed GLB/GLTF export paths sometimes being incorrect (double or no extension)
|
||||
- changed: GLB importer now embeds all meshes and textures as sub assets instead of putting them in the project; needs better importer inspector to allow for asset remapping.
|
||||
|
||||
## [1.0.4-preview.16] - 2021-03-15
|
||||
- fixed color space issues with vertex colors and emissive
|
||||
- fixed export of UV offset/tiling for non-main textures
|
||||
- fixed exporting materials as PBR when they have _Metallic and _Glossiness (required only _MetallicGlossMap before)
|
||||
|
||||
## [1.0.4-preview.15] - 2021-02-23
|
||||
- fixed issues with material export in URP where PBR wasn't properly detected and exported
|
||||
|
||||
## [1.0.4-preview.14] - 2021-02-10
|
||||
- fixed issues with KHR_materials_pbrSpecularGlossinessExtension and materials that don't have textures
|
||||
|
||||
## [1.0.4-preview.13] - 2021-01-30
|
||||
- fixed missing references in materials and prefabs
|
||||
- fixed issue preventing build with UnityGLTF in project
|
||||
- moved samples into subfolder
|
||||
- added support for animation clip speed being set inside Animator States
|
||||
|
||||
## [1.0.4-preview.12] - 2020-12-15
|
||||
- fix compilation errors in GLTFSerialization.dll on recompiling
|
||||
- fix Newtonsoft.Json being copied to output directory
|
||||
- fix a number of animation export issues
|
||||
- add KHR_materials_unlit extension import and export
|
||||
|
||||
## [1.0.4-preview.11] - 2020-11-27
|
||||
- fix KHR_lights_punctual extension always being set, even if no lights were exported
|
||||
- fix invalid primitives being exported for meshes with 0 vertices
|
||||
- removed export rotation offset that caused incorrect rotation in other softwares
|
||||
|
||||
## [1.0.4-preview.10] - 2020-11-16
|
||||
- fix error thrown when vertex arrays have 0 elements (this is valid in FBX)
|
||||
- add light export/import extensions
|
||||
- merged a number of PRs that fix nullrefs on export/import
|
||||
|
||||
## [1.0.4-preview.9] - 2020-10-03
|
||||
- merged in a number of material fix and null ref PRs
|
||||
- add namespaces to scripts that didn't have them
|
||||
|
||||
## [1.0.4-preview.8] - 2020-09-10
|
||||
- built GLTFSerialization.dll against Newtonsoft.JSON 12.0.3
|
||||
- removed Newtonsoft.JSON.dll from package
|
||||
- added dependency on com.unity.nuget.newtonsoft-json@2.0.0
|
||||
- added 2020.2 compatibility
|
||||
|
||||
## [1.0.4-preview.7] - 2020-07-24
|
||||
- fix sRGB/linear conversion for normal maps depending on Unity color space
|
||||
|
||||
## [1.0.4-preview.6] - 2020-07-15
|
||||
- fix sRGB/linear conversion for colors exported from Unity
|
||||
- fix rotation order for 180° hack
|
||||
- note: please use Linear color space, normal maps break in Gamma color space right now
|
||||
|
||||
## [1.0.4-preview.5] - 2020-07-13
|
||||
- hack: added 180° rotation on export (experimental), needs to be tested with animations, only works with a single root transform on export
|
||||
- changed back to "preview" instead of "pfc" tag because stupid PackMan
|
||||
|
||||
## [1.0.4-pfc.4] - 2020-07-12
|
||||
- fix meta files for Tests folder
|
||||
|
||||
## [1.0.4-pfc.2] - 2020-07-07
|
||||
- fix build errors preventing builds
|
||||
- fix PBR texture roundtrip with incorrect red channel
|
||||
|
||||
## [1.0.4-pfc] - 2020-04-24
|
||||
- lots of improvements to animation export
|
||||
- automatic keyframe reduction
|
||||
- BREAKING: disabled UV2 and vertex color export for web
|
||||
- fixed texture export from memory instead of from disk
|
||||
- fix breaking animations in SceneViewer due to omitted LINEAR sampler specification
|
||||
|
||||
## [1.0.0-pfc.4] - 2020-01-16
|
||||
- rebased all pfc feature branches on latest master
|
||||
- back to org.khronos scope for easier switching between versions
|
||||
- added animation export
|
||||
- added PNG/JPG texture export from disk where available
|
||||
|
||||
## [1.0.1] - 2019-04-03
|
||||
- Upgraded to 2017.4
|
||||
- Included various fixes (will update)
|
||||
- Includes UPM package
|
||||
|
||||
## [1.0.0] - 2018-09-21
|
||||
- first built unity package release of UnityGLTF
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 06314f49bdda26043963578d60a0a7ee
|
||||
guid: 2ac567cb9b76e6a4490f2f54aa52c067
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,9 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 577d9725f58264943855b8ac185531fe
|
||||
guid: f5f45ddfa210e204f88be87c65820b64
|
||||
folderAsset: yes
|
||||
timeCreated: 1466788344
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+2
-3
@@ -1,9 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 14f21d7a1e53a8c4e87b25526a7eb63c
|
||||
guid: 3d3936188a676ff4a9194add4e985b7c
|
||||
folderAsset: yes
|
||||
timeCreated: 1466788345
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[CustomEditor(typeof(GLTFComponent))]
|
||||
public class GLTFComponentInspector : Editor
|
||||
{
|
||||
private Vector2 scrollPosition = Vector2.zero;
|
||||
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
DrawDefaultInspector();
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
|
||||
#if UNITY_ANIMATION
|
||||
var gltfComponent = serializedObject.targetObject as GLTFComponent;
|
||||
if (gltfComponent != null && gltfComponent.Animations != null)
|
||||
{
|
||||
EditorGUILayout.LabelField("Animations:");
|
||||
using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPosition))
|
||||
{
|
||||
scrollPosition = scrollView.scrollPosition;
|
||||
foreach (var animation in gltfComponent.Animations)
|
||||
{
|
||||
DrawAnimation(animation);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private void DrawAnimation(Animation animation)
|
||||
{
|
||||
GUILayout.Label(animation.name);
|
||||
|
||||
foreach (AnimationState animationState in animation)
|
||||
{
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
var clip = animationState.clip;
|
||||
var clipName = clip.name;
|
||||
GUILayout.Label(clipName);
|
||||
|
||||
var isPlaying = animation.IsPlaying(clipName);
|
||||
string playPause = isPlaying ? "pause" : "play";
|
||||
|
||||
var buttonPressed = GUILayout.Button(playPause);
|
||||
|
||||
if (buttonPressed)
|
||||
{
|
||||
if (isPlaying)
|
||||
{
|
||||
animation.Stop(clipName);
|
||||
}
|
||||
else
|
||||
{
|
||||
animation.Play(clipName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SetClipsPlaying(Animation animation, bool play)
|
||||
{
|
||||
foreach (AnimationState animationState in animation)
|
||||
{
|
||||
if (play)
|
||||
{
|
||||
animation.Play(animationState.clip.name);
|
||||
}
|
||||
else
|
||||
{
|
||||
animation.Stop(animationState.clip.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -1,7 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ab30c2ca30e1a144c97b8e0cc5c3d316
|
||||
timeCreated: 1535288250
|
||||
licenseType: Free
|
||||
guid: 843e1771f80e49643aed2baa52c2394d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class GLTFExportMenu
|
||||
{
|
||||
private const string MenuPrefix = "Assets/UnityGLTF/";
|
||||
|
||||
public static string RetrieveTexturePath(UnityEngine.Texture texture)
|
||||
{
|
||||
var path = AssetDatabase.GetAssetPath(texture);
|
||||
// texture is a subasset
|
||||
if (AssetDatabase.GetMainAssetTypeAtPath(path) != typeof(Texture2D))
|
||||
{
|
||||
var ext = System.IO.Path.GetExtension(path);
|
||||
if (string.IsNullOrWhiteSpace(ext)) return texture.name + ".png";
|
||||
path = path.Replace(ext, "-" + texture.name + ext);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static bool TryGetExportNameAndRootTransformsFromSelection(out string sceneName, out Transform[] rootTransforms)
|
||||
{
|
||||
if (Selection.transforms.Length > 1)
|
||||
{
|
||||
sceneName = SceneManager.GetActiveScene().name;
|
||||
rootTransforms = Selection.transforms;
|
||||
return true;
|
||||
}
|
||||
if (Selection.transforms.Length == 1)
|
||||
{
|
||||
sceneName = Selection.activeGameObject.name;
|
||||
rootTransforms = Selection.transforms;
|
||||
return true;
|
||||
}
|
||||
if (Selection.objects.Any() && Selection.objects.All(x => x is GameObject))
|
||||
{
|
||||
sceneName = Selection.objects.First().name;
|
||||
rootTransforms = Selection.objects.Select(x => (x as GameObject).transform).ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
sceneName = null;
|
||||
rootTransforms = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as glTF", true)]
|
||||
private static bool ExportSelectedValidate()
|
||||
{
|
||||
return TryGetExportNameAndRootTransformsFromSelection(out _, out _);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as glTF")]
|
||||
private static void ExportSelected()
|
||||
{
|
||||
if (!TryGetExportNameAndRootTransformsFromSelection(out var sceneName, out var rootTransforms))
|
||||
{
|
||||
Debug.LogError("Can't export: selection is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
Export(rootTransforms, false, sceneName);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as GLB", true)]
|
||||
private static bool ExportGLBSelectedValidate()
|
||||
{
|
||||
return TryGetExportNameAndRootTransformsFromSelection(out _, out _);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as GLB")]
|
||||
private static void ExportGLBSelected()
|
||||
{
|
||||
if (!TryGetExportNameAndRootTransformsFromSelection(out var sceneName, out var rootTransforms))
|
||||
{
|
||||
Debug.LogError("Can't export: selection is empty");
|
||||
return;
|
||||
}
|
||||
Export(rootTransforms, true, sceneName);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export active scene as glTF")]
|
||||
private static void ExportScene()
|
||||
{
|
||||
var scene = SceneManager.GetActiveScene();
|
||||
var gameObjects = scene.GetRootGameObjects();
|
||||
var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform);
|
||||
|
||||
Export(transforms, false, scene.name);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export active scene as GLB")]
|
||||
private static void ExportSceneGLB()
|
||||
{
|
||||
var scene = SceneManager.GetActiveScene();
|
||||
var gameObjects = scene.GetRootGameObjects();
|
||||
var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform);
|
||||
|
||||
Export(transforms, true, scene.name);
|
||||
}
|
||||
|
||||
private static void Export(Transform[] transforms, bool binary, string sceneName)
|
||||
{
|
||||
var settings = GLTFSettings.GetOrCreateSettings();
|
||||
var exportOptions = new ExportOptions { TexturePathRetriever = RetrieveTexturePath };
|
||||
var exporter = new GLTFSceneExporter(transforms, exportOptions);
|
||||
|
||||
var invokedByShortcut = Event.current?.type == EventType.KeyDown;
|
||||
var path = settings.SaveFolderPath;
|
||||
if (!invokedByShortcut || !Directory.Exists(path))
|
||||
path = EditorUtility.SaveFolderPanel("glTF Export Path", settings.SaveFolderPath, "");
|
||||
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
var ext = binary ? ".glb" : ".gltf";
|
||||
var resultFile = GLTFSceneExporter.GetFileName(path, sceneName, ext);
|
||||
settings.SaveFolderPath = path;
|
||||
if(binary)
|
||||
exporter.SaveGLB(path, sceneName);
|
||||
else
|
||||
exporter.SaveGLTFandBin(path, sceneName);
|
||||
|
||||
Debug.Log("Exported to " + resultFile);
|
||||
EditorUtility.RevealInFinder(resultFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fd3d2ca14e7c1084888c77f15c69ae56
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,619 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
|
||||
// glTFast is on the path to being official, so it should have highest priority as importer by default
|
||||
// This ifdef is included for completeness.
|
||||
// Other glTF importers should specify this via AsmDef dependency, for example
|
||||
// `com.atteneder.gltfast@3.0.0: HAVE_GLTFAST` and then checking here `#if HAVE_GLTFAST`
|
||||
#if HAVE_GLTFAST
|
||||
#define ANOTHER_IMPORTER_HAS_HIGHER_PRIORITY
|
||||
#endif
|
||||
|
||||
#if !ANOTHER_IMPORTER_HAS_HIGHER_PRIORITY && !UNITYGLTF_FORCE_DEFAULT_IMPORTER_OFF
|
||||
#define ENABLE_DEFAULT_GLB_IMPORTER
|
||||
#endif
|
||||
#if UNITYGLTF_FORCE_DEFAULT_IMPORTER_ON
|
||||
#define ENABLE_DEFAULT_GLB_IMPORTER
|
||||
#endif
|
||||
|
||||
using UnityEditor;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using Object = UnityEngine.Object;
|
||||
using UnityGLTF.Loader;
|
||||
using GLTF.Schema;
|
||||
using GLTF;
|
||||
using Unity.Collections;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
#if ENABLE_DEFAULT_GLB_IMPORTER
|
||||
[ScriptedImporter(ImporterVersion, new[] { "glb", "gltf" })]
|
||||
#else
|
||||
[ScriptedImporter(ImporterVersion, null, overrideExts: new[] { "glb", "gltf" })]
|
||||
#endif
|
||||
#else
|
||||
[ScriptedImporter(ImporterVersion, new[] { "glb" })]
|
||||
#endif
|
||||
public class GLTFImporter : ScriptedImporter
|
||||
{
|
||||
private const int ImporterVersion = 7;
|
||||
|
||||
private static void EnsureShadersAreLoaded()
|
||||
{
|
||||
const string PackagePrefix = "Packages/org.khronos.unitygltf/";
|
||||
var shaders = new string[] {
|
||||
PackagePrefix + "Runtime/Shaders/ShaderGraph/PBRGraph.shadergraph",
|
||||
PackagePrefix + "Runtime/Shaders/ShaderGraph/UnlitGraph.shadergraph",
|
||||
PackagePrefix + "Runtime/Shaders/PbrMetallicRoughness.shader",
|
||||
PackagePrefix + "Runtime/Shaders/PbrSpecularGlossiness.shader",
|
||||
PackagePrefix + "Runtime/Shaders/Unlit.shader",
|
||||
};
|
||||
|
||||
foreach (var shaderPath in shaders)
|
||||
{
|
||||
AssetDatabase.LoadAssetAtPath<Shader>(shaderPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Tooltip("Turn this off to create an explicit GameObject for the glTF scene. A scene root will always be created if there's more than one root node.")]
|
||||
[SerializeField] internal bool _removeEmptyRootObjects = true;
|
||||
[SerializeField] internal float _scaleFactor = 1.0f;
|
||||
[SerializeField] internal int _maximumLod = 300;
|
||||
[SerializeField] internal bool _readWriteEnabled = true;
|
||||
[SerializeField] internal bool _generateColliders = false;
|
||||
[SerializeField] internal bool _swapUvs = false;
|
||||
[SerializeField] internal bool _generateLightmapUVs = false;
|
||||
[SerializeField] internal GLTFImporterNormals _importNormals = GLTFImporterNormals.Import;
|
||||
[SerializeField] internal GLTFImporterNormals _importTangents = GLTFImporterNormals.Import;
|
||||
[SerializeField] internal AnimationMethod _importAnimations = AnimationMethod.Mecanim;
|
||||
[SerializeField] internal bool _addAnimatorComponent = false;
|
||||
[SerializeField] internal bool _animationLoopTime = true;
|
||||
[SerializeField] internal bool _animationLoopPose = false;
|
||||
[SerializeField] internal bool _importMaterials = true;
|
||||
[Tooltip("Enable this to get the same main asset identifiers as glTFast uses. This is recommended for new asset imports. Note that changing this for already imported assets will break their scene references and require manually re-adding the affected assets.")]
|
||||
[SerializeField] internal bool _useSceneNameIdentifier = false;
|
||||
|
||||
// for humanoid importer
|
||||
[SerializeField] internal bool m_OptimizeGameObjects = false;
|
||||
[SerializeField] internal HumanDescription m_HumanDescription = new HumanDescription();
|
||||
|
||||
// material remapping
|
||||
[SerializeField] private Material[] m_Materials = new Material[0];
|
||||
|
||||
[Serializable]
|
||||
internal class ExtensionInfo
|
||||
{
|
||||
public string name;
|
||||
public bool supported;
|
||||
public bool used;
|
||||
public bool required;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class TextureInfo
|
||||
{
|
||||
public Texture2D texture;
|
||||
public bool shouldBeLinear;
|
||||
}
|
||||
|
||||
#if !UNIYT_2020_2_OR_NEWER
|
||||
private class NonReorderableAttribute : Attribute {}
|
||||
#endif
|
||||
|
||||
// Import messages (extensions, warnings, errors, ...)
|
||||
[NonReorderable] [SerializeField] internal List<ExtensionInfo> _extensions;
|
||||
[NonReorderable] [SerializeField] private List<TextureInfo> _textures;
|
||||
[SerializeField] internal string _mainAssetIdentifier;
|
||||
|
||||
internal List<TextureInfo> Textures => _textures;
|
||||
|
||||
private static string[] GatherDependenciesFromSourceFile(string path)
|
||||
{
|
||||
// only supported glTF for now - would be harder to check for external references in glb assets.
|
||||
if (!path.ToLowerInvariant().EndsWith(".gltf")) return Array.Empty<string>();
|
||||
|
||||
var dependencies = new List<string>();
|
||||
|
||||
// read minimal JSON, check if there's a bin buffer, and load that.
|
||||
// all other assets should be "proper assets" and be found by the asset database, but we're not importing .bin
|
||||
// since it's too common as a file type.
|
||||
var gltf = GLTFRoot.Deserialize(new StreamReader(path));
|
||||
var externalBuffers = gltf?.Buffers?.Where(b => b?.Uri != null && b.Uri.ToLowerInvariant().EndsWith(".bin"));
|
||||
if (externalBuffers != null)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
foreach (var buffer in externalBuffers)
|
||||
{
|
||||
var uri = buffer.Uri;
|
||||
if (!File.Exists(Path.Combine(dir, uri)))
|
||||
uri = Uri.UnescapeDataString(uri);
|
||||
if (File.Exists(Path.Combine(dir, uri)))
|
||||
dependencies.Add(Path.Combine(dir, uri));
|
||||
// TODO check if inside the project/any package, could be an absolute path
|
||||
else if (File.Exists(uri))
|
||||
dependencies.Add(uri);
|
||||
}
|
||||
}
|
||||
|
||||
return dependencies.ToArray();
|
||||
}
|
||||
|
||||
public override void OnImportAsset(AssetImportContext ctx)
|
||||
{
|
||||
string sceneName = null;
|
||||
GameObject gltfScene = null;
|
||||
AnimationClip[] animations = null;
|
||||
Mesh[] meshes = null;
|
||||
|
||||
var uniqueNames = new List<string>() { "main asset" };
|
||||
EnsureShadersAreLoaded();
|
||||
|
||||
string GetUniqueName(string desiredName)
|
||||
{
|
||||
var uniqueName = ObjectNames.GetUniqueName(uniqueNames.ToArray(), desiredName);
|
||||
if (!uniqueNames.Contains(uniqueName)) uniqueNames.Add(uniqueName);
|
||||
return uniqueName;
|
||||
}
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
// We explicitly turn the new identifier on for new imports, that is, when no meta file existed before this import.
|
||||
// We do this early, so that when imports fail, we still get the new identifier. Unity already sets import settings on failed imports.
|
||||
if (!_useSceneNameIdentifier)
|
||||
{
|
||||
var importer = GetAtPath(ctx.assetPath);
|
||||
if (importer.importSettingsMissing)
|
||||
{
|
||||
_useSceneNameIdentifier = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
try
|
||||
{
|
||||
sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath);
|
||||
CreateGLTFScene(ctx.assetPath, out gltfScene, out animations);
|
||||
var rootGltfComponent = gltfScene.GetComponent<InstantiatedGLTFObject>();
|
||||
if (rootGltfComponent) DestroyImmediate(rootGltfComponent);
|
||||
|
||||
// Remove empty roots
|
||||
if (_removeEmptyRootObjects)
|
||||
{
|
||||
var t = gltfScene.transform;
|
||||
var existingAnimator = t.GetComponent<Animator>();
|
||||
var hadAnimator = (bool)existingAnimator;
|
||||
var existingAvatar = existingAnimator ? existingAnimator.avatar : default;
|
||||
if (existingAnimator)
|
||||
DestroyImmediate(existingAnimator);
|
||||
|
||||
while (
|
||||
gltfScene.transform.childCount == 1 &&
|
||||
gltfScene.GetComponents<Component>().Length == 1)
|
||||
{
|
||||
var parent = gltfScene;
|
||||
var importName = parent.name;
|
||||
gltfScene = gltfScene.transform.GetChild(0).gameObject;
|
||||
gltfScene.name = importName; // root name is always name of the file anyways
|
||||
t = gltfScene.transform;
|
||||
t.parent = null; // To keep transform information in the new parent
|
||||
DestroyImmediate(parent); // Get rid of the parent
|
||||
}
|
||||
|
||||
// Re-add animator if it was removed
|
||||
if (hadAnimator)
|
||||
{
|
||||
var newAnimator = gltfScene.AddComponent<Animator>();
|
||||
newAnimator.avatar = existingAvatar;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure there are no hide flags present (will cause problems when saving)
|
||||
gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave);
|
||||
foreach (Transform child in gltfScene.transform)
|
||||
{
|
||||
child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave);
|
||||
}
|
||||
|
||||
// scale all localPosition values if necessary
|
||||
if (!Mathf.Approximately(_scaleFactor, 1))
|
||||
{
|
||||
var transforms = gltfScene.GetComponentsInChildren<Transform>();
|
||||
foreach (var tr in transforms)
|
||||
{
|
||||
tr.localPosition *= _scaleFactor;
|
||||
}
|
||||
}
|
||||
|
||||
// Get meshes
|
||||
var meshHash = new HashSet<UnityEngine.Mesh>();
|
||||
var meshFilters = gltfScene.GetComponentsInChildren<MeshFilter>().Select(x => (x.gameObject, x.sharedMesh)).ToList();
|
||||
meshFilters.AddRange(gltfScene.GetComponentsInChildren<SkinnedMeshRenderer>().Select(x => (x.gameObject, x.sharedMesh)));
|
||||
var vertexBuffer = new List<Vector3>();
|
||||
meshes = meshFilters.Select(mf =>
|
||||
{
|
||||
var mesh = mf.sharedMesh;
|
||||
|
||||
if (meshHash.Contains(mesh))
|
||||
return null;
|
||||
meshHash.Add(mesh);
|
||||
|
||||
if (!Mathf.Approximately(_scaleFactor, 1.0f))
|
||||
{
|
||||
vertexBuffer.Clear();
|
||||
mesh.GetVertices(vertexBuffer);
|
||||
for (var i = 0; i < vertexBuffer.Count; ++i)
|
||||
{
|
||||
vertexBuffer[i] *= _scaleFactor;
|
||||
}
|
||||
mesh.SetVertices(vertexBuffer);
|
||||
}
|
||||
if (_generateLightmapUVs)
|
||||
{
|
||||
var uv2 = mesh.uv2;
|
||||
if (uv2 == null || uv2.Length < 1)
|
||||
{
|
||||
var hasTriangleTopology = true;
|
||||
for (var i = 0; i < mesh.subMeshCount; i++)
|
||||
hasTriangleTopology &= mesh.GetTopology(i) == MeshTopology.Triangles;
|
||||
|
||||
// uv2 = Unwrapping.GeneratePerTriangleUV(mesh);
|
||||
// mesh.SetUVs(1, uv2);
|
||||
|
||||
// There seems to be a bug in Unity's splitting code:
|
||||
// for some meshes, the result is broken after splitting.
|
||||
if (hasTriangleTopology)
|
||||
Unwrapping.GenerateSecondaryUVSet(mesh);
|
||||
}
|
||||
}
|
||||
if (_swapUvs)
|
||||
{
|
||||
var uv = mesh.uv;
|
||||
var uv2 = mesh.uv2;
|
||||
mesh.uv = uv2;
|
||||
if(uv.Length > 0)
|
||||
mesh.uv2 = uv;
|
||||
}
|
||||
|
||||
if (_importNormals == GLTFImporterNormals.None)
|
||||
mesh.normals = new Vector3[0];
|
||||
else if (_importNormals == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateNormals();
|
||||
else if (_importNormals == GLTFImporterNormals.Import && mesh.normals.Length == 0 && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateNormals();
|
||||
|
||||
if (_importTangents == GLTFImporterNormals.None)
|
||||
mesh.tangents = new Vector4[0];
|
||||
else if (_importTangents == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateTangents();
|
||||
else if (_importTangents == GLTFImporterNormals.Import && mesh.tangents.Length == 0 && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateTangents();
|
||||
|
||||
mesh.UploadMeshData(!_readWriteEnabled);
|
||||
|
||||
if (_generateColliders)
|
||||
{
|
||||
var collider = mf.gameObject.AddComponent<MeshCollider>();
|
||||
collider.sharedMesh = mesh;
|
||||
}
|
||||
|
||||
return mesh;
|
||||
}).Where(x => x).ToArray();
|
||||
|
||||
if (animations != null)
|
||||
{
|
||||
foreach (var clip in animations)
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName(clip.name), clip);
|
||||
}
|
||||
}
|
||||
|
||||
// we can't add the Animators as subassets here, since they require their state machines to be direct subassets themselves.
|
||||
// foreach (var anim in animators)
|
||||
// {
|
||||
// ctx.AddObjectToAsset(GetUniqueName(anim.runtimeAnimatorController.name), anim.runtimeAnimatorController as AnimatorController);
|
||||
// foreach (var layer in (anim.runtimeAnimatorController as AnimatorController).layers)
|
||||
// {
|
||||
// ctx.AddObjectToAsset(GetUniqueName(layer.name + "-state"), layer.stateMachine);
|
||||
// }
|
||||
// }
|
||||
|
||||
if (_importAnimations == AnimationMethod.MecanimHumanoid)
|
||||
{
|
||||
var avatar = HumanoidSetup.AddAvatarToGameObject(gltfScene);
|
||||
if (avatar && avatar.isValid)
|
||||
ctx.AddObjectToAsset("avatar", avatar);
|
||||
}
|
||||
|
||||
var renderers = gltfScene.GetComponentsInChildren<Renderer>();
|
||||
|
||||
if (_importMaterials)
|
||||
{
|
||||
// Get materials
|
||||
var map = GetExternalObjectMap();
|
||||
var materialHash = new HashSet<UnityEngine.Material>();
|
||||
var materials = renderers.SelectMany(r =>
|
||||
{
|
||||
return r.sharedMaterials.Select(mat =>
|
||||
{
|
||||
if (materialHash.Add(mat))
|
||||
{
|
||||
var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name;
|
||||
if (matName == mat.shader.name)
|
||||
{
|
||||
matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/", StringComparison.Ordinal) + 1, matName.Length - 1));
|
||||
}
|
||||
mat.name = matName;
|
||||
}
|
||||
|
||||
return mat;
|
||||
});
|
||||
}).Distinct().ToArray();
|
||||
|
||||
// apply material remap
|
||||
foreach(var r in renderers)
|
||||
{
|
||||
// remap materials to external objects
|
||||
var m = r.sharedMaterials;
|
||||
for (var i = 0; i < m.Length; i++)
|
||||
{
|
||||
var si = new SourceAssetIdentifier(m[i]);
|
||||
if (map.ContainsKey(si))
|
||||
m[i] = map[si] as Material;
|
||||
}
|
||||
r.sharedMaterials = m;
|
||||
};
|
||||
|
||||
// Get textures
|
||||
var textureHash = new HashSet<Texture2D>();
|
||||
var texMaterialMap = new Dictionary<Texture2D, List<TexMaterialMap>>();
|
||||
var textures = materials.SelectMany(mat =>
|
||||
{
|
||||
var shader = mat.shader;
|
||||
if (!shader) return Enumerable.Empty<Texture2D>();
|
||||
|
||||
var matTextures = new List<Texture2D>();
|
||||
for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
|
||||
{
|
||||
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
|
||||
{
|
||||
var propertyName = ShaderUtil.GetPropertyName(shader, i);
|
||||
var tex = mat.GetTexture(propertyName) as Texture2D;
|
||||
if (tex)
|
||||
{
|
||||
if (textureHash.Add(tex))
|
||||
{
|
||||
var texName = tex.name;
|
||||
if (string.IsNullOrEmpty(texName))
|
||||
{
|
||||
if (propertyName.StartsWith("_")) texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1));
|
||||
tex.name = texName;
|
||||
}
|
||||
matTextures.Add(tex);
|
||||
}
|
||||
|
||||
List<TexMaterialMap> materialMaps;
|
||||
if (!texMaterialMap.TryGetValue(tex, out materialMaps))
|
||||
{
|
||||
materialMaps = new List<TexMaterialMap>();
|
||||
texMaterialMap.Add(tex, materialMaps);
|
||||
}
|
||||
|
||||
materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap" || propertyName == "normalTexture" || propertyName.EndsWith("NormalTexture")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return matTextures;
|
||||
}).Distinct().ToArray();
|
||||
|
||||
// Save textures as separate assets and rewrite refs
|
||||
// TODO: Support for other texture types
|
||||
if (textures.Length > 0)
|
||||
{
|
||||
foreach (var tex in textures)
|
||||
{
|
||||
if (AssetDatabase.Contains(tex) && AssetDatabase.GetAssetPath(tex) != ctx.assetPath)
|
||||
{
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
ctx.DependsOnArtifact(
|
||||
#else
|
||||
ctx.DependsOnSourceAsset(
|
||||
#endif
|
||||
AssetDatabase.GetAssetPath(tex));
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName(tex.name), tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !UNITY_2022_1_OR_NEWER
|
||||
AssetDatabase.Refresh();
|
||||
#endif
|
||||
|
||||
// Save materials as separate assets and rewrite refs
|
||||
if (materials.Length > 0)
|
||||
{
|
||||
foreach (var mat in materials)
|
||||
{
|
||||
// ensure materials that are overriden aren't shown in the hierarchy.
|
||||
var si = new SourceAssetIdentifier(mat);
|
||||
if (map.ContainsKey(si))
|
||||
mat.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector;
|
||||
|
||||
ctx.AddObjectToAsset(GetUniqueName(mat.name), mat);
|
||||
}
|
||||
}
|
||||
|
||||
m_Materials = materials;
|
||||
|
||||
#if !UNITY_2022_1_OR_NEWER
|
||||
AssetDatabase.SaveAssets();
|
||||
AssetDatabase.Refresh();
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
var temp = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
||||
temp.SetActive(false);
|
||||
var defaultMat = new[] { temp.GetComponent<Renderer>().sharedMaterial };
|
||||
DestroyImmediate(temp);
|
||||
|
||||
foreach (var rend in renderers)
|
||||
{
|
||||
rend.sharedMaterials = defaultMat;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (gltfScene) DestroyImmediate(gltfScene);
|
||||
throw;
|
||||
}
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
if (!_useSceneNameIdentifier)
|
||||
{
|
||||
// Set main asset
|
||||
_mainAssetIdentifier = "main asset";
|
||||
ctx.AddObjectToAsset(_mainAssetIdentifier, gltfScene);
|
||||
}
|
||||
else
|
||||
{
|
||||
// This will be a breaking change, but would be aligned to the import naming from glTFast - allows switching back and forth between importers.
|
||||
_mainAssetIdentifier = $"scenes/{gltfScene.name}";
|
||||
ctx.AddObjectToAsset(_mainAssetIdentifier, gltfScene);
|
||||
}
|
||||
|
||||
// Add meshes
|
||||
foreach (var mesh in meshes)
|
||||
{
|
||||
try
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName("mesh-" + mesh.name), mesh);
|
||||
} catch(System.InvalidOperationException e) {
|
||||
Debug.LogWarning(e.ToString(), mesh);
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
ctx.DependsOnCustomDependency(ColorSpaceDependency);
|
||||
#endif
|
||||
ctx.SetMainObject(gltfScene);
|
||||
#else
|
||||
// Set main asset
|
||||
ctx.SetMainAsset("main asset", gltfScene);
|
||||
|
||||
// Add meshes
|
||||
foreach (var mesh in meshes)
|
||||
{
|
||||
try {
|
||||
ctx.AddSubAsset("mesh " + mesh.name, mesh);
|
||||
} catch (System.InvalidOperationException e) {
|
||||
Debug.LogWarning(e.ToString(), mesh);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private const string ColorSpaceDependency = nameof(GLTFImporter) + "_" + nameof(PlayerSettings.colorSpace);
|
||||
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
[InitializeOnLoadMethod]
|
||||
private static void UpdateColorSpace()
|
||||
{
|
||||
AssetDatabase.RegisterCustomDependency(ColorSpaceDependency, Hash128.Compute((int) PlayerSettings.colorSpace));
|
||||
}
|
||||
#endif
|
||||
|
||||
private void CreateGLTFScene(string projectFilePath, out GameObject scene, out AnimationClip[] animationClips)
|
||||
{
|
||||
var importOptions = new ImportOptions
|
||||
{
|
||||
DataLoader = new FileLoader(Path.GetDirectoryName(projectFilePath)),
|
||||
AnimationMethod = _importAnimations,
|
||||
AnimationLoopTime = _animationLoopTime,
|
||||
AnimationLoopPose = _animationLoopPose,
|
||||
};
|
||||
using (var stream = File.OpenRead(projectFilePath))
|
||||
{
|
||||
GLTFRoot gLTFRoot;
|
||||
GLTFParser.ParseJson(stream, out gLTFRoot);
|
||||
stream.Position = 0; // Make sure the read position is changed back to the beginning of the file
|
||||
var loader = new GLTFSceneImporter(gLTFRoot, stream, importOptions);
|
||||
loader.MaximumLod = _maximumLod;
|
||||
loader.IsMultithreaded = true;
|
||||
|
||||
loader.LoadSceneAsync().Wait();
|
||||
|
||||
if (gLTFRoot.ExtensionsUsed != null)
|
||||
{
|
||||
_extensions = gLTFRoot.ExtensionsUsed
|
||||
.Select(x => new ExtensionInfo()
|
||||
{
|
||||
name = x,
|
||||
supported = true,
|
||||
used = true,
|
||||
required = gLTFRoot.ExtensionsRequired?.Contains(x) ?? false,
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
_extensions = new List<ExtensionInfo>();
|
||||
}
|
||||
|
||||
_textures = loader.TextureCache
|
||||
.Where(x => x != null)
|
||||
.Select(x => new TextureInfo() { texture = x.Texture, shouldBeLinear = x.IsLinear })
|
||||
.ToList();
|
||||
|
||||
scene = loader.LastLoadedScene;
|
||||
animationClips = loader.CreatedAnimationClips;
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyOrNew<T>(T asset, string assetPath, Action<T> replaceReferences) where T : Object
|
||||
{
|
||||
var existingAsset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
|
||||
if (existingAsset)
|
||||
{
|
||||
EditorUtility.CopySerialized(asset, existingAsset);
|
||||
replaceReferences(existingAsset);
|
||||
return;
|
||||
}
|
||||
|
||||
AssetDatabase.CreateAsset(asset, assetPath);
|
||||
}
|
||||
|
||||
private class TexMaterialMap
|
||||
{
|
||||
public UnityEngine.Material Material { get; set; }
|
||||
public string Property { get; set; }
|
||||
public bool IsNormalMap { get; set; }
|
||||
|
||||
public TexMaterialMap(UnityEngine.Material material, string property, bool isNormalMap)
|
||||
{
|
||||
Material = material;
|
||||
Property = property;
|
||||
IsNormalMap = isNormalMap;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool SupportsRemappedAssetType(Type type)
|
||||
{
|
||||
if (type == typeof(Material))
|
||||
return true;
|
||||
return base.SupportsRemappedAssetType(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 804e1ce4c496647cfa3f1a1134187c71
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,334 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
|
||||
using UnityEngine;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[CustomEditor(typeof(GLTFImporter))]
|
||||
[CanEditMultipleObjects]
|
||||
internal class GLTFImporterInspector : UnityGLTFTabbedEditor
|
||||
{
|
||||
private string[] _importNormalsNames;
|
||||
|
||||
public override void OnEnable()
|
||||
{
|
||||
AddTab(new GltfAssetImporterTab(this, "Model", ModelInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Animation", AnimationInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Materials", MaterialInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Extensions", ExtensionInspectorGUI));
|
||||
|
||||
base.OnEnable();
|
||||
}
|
||||
|
||||
private void TextureWarningsGUI(GLTFImporter t)
|
||||
{
|
||||
if (!t) return;
|
||||
if (!TextureImportSettingsAreCorrect(t))
|
||||
{
|
||||
EditorGUILayout.HelpBox("Some Textures have incorrect linear/sRGB settings. Results might be incorrect.", MessageType.Warning);
|
||||
if (GUILayout.Button("Fix All"))
|
||||
{
|
||||
FixTextureImportSettings(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ModelInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) EditorGUILayout.LabelField("NOOOO");
|
||||
|
||||
if (!t) return;
|
||||
|
||||
// serializedObject.Update();
|
||||
if (_importNormalsNames == null)
|
||||
{
|
||||
_importNormalsNames = Enum.GetNames(typeof(GLTFImporterNormals))
|
||||
.Select(n => ObjectNames.NicifyVariableName(n))
|
||||
.ToArray();
|
||||
}
|
||||
EditorGUILayout.LabelField("Scene", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._removeEmptyRootObjects)));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._scaleFactor)));
|
||||
// EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._maximumLod)), new GUIContent("Maximum Shader LOD"));
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.LabelField("Meshes", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._readWriteEnabled)), new GUIContent("Read/Write"));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._generateColliders)));
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.LabelField("Geometry", EditorStyles.boldLabel);
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var importNormalsProp = serializedObject.FindProperty(nameof(GLTFImporter._importNormals));
|
||||
var importNormals = EditorGUILayout.Popup("Normals", importNormalsProp.intValue, _importNormalsNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
importNormalsProp.intValue = importNormals;
|
||||
}
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var importTangentsProp = serializedObject.FindProperty(nameof(GLTFImporter._importTangents));
|
||||
var importTangents = EditorGUILayout.Popup("Tangents", importTangentsProp.intValue, _importNormalsNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
importTangentsProp.intValue = importTangents;
|
||||
}
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._swapUvs)), new GUIContent("Swap UVs"));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._generateLightmapUVs)), new GUIContent("Generate Lightmap UVs"));
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
TextureWarningsGUI(t);
|
||||
}
|
||||
|
||||
private void AnimationInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
var anim = serializedObject.FindProperty(nameof(GLTFImporter._importAnimations));
|
||||
EditorGUILayout.PropertyField(anim, new GUIContent("Animation Type"));
|
||||
if (anim.enumValueIndex > 0)
|
||||
{
|
||||
var loopTime = serializedObject.FindProperty(nameof(GLTFImporter._animationLoopTime));
|
||||
EditorGUILayout.PropertyField(loopTime, new GUIContent("Loop Time"));
|
||||
if (loopTime.boolValue)
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._animationLoopPose)), new GUIContent("Loop Pose"));
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
}
|
||||
|
||||
// warn if Humanoid rig import has failed
|
||||
if (!HasModified() && anim.enumValueIndex == (int) AnimationMethod.MecanimHumanoid && !AssetDatabase.LoadAssetAtPath<Avatar>(t.assetPath))
|
||||
{
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.HelpBox("The model doesn't contain a valid Humanoid rig. See the console for more information.", MessageType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void MaterialInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
var mats = serializedObject.FindProperty("m_Materials");
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._importMaterials)));
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
// extract and remap materials
|
||||
if (mats != null && mats.serializedObject != null)
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
var externalObjectMap = t.GetExternalObjectMap();
|
||||
|
||||
void ExtractMaterial(Material subAsset, bool importImmediately)
|
||||
{
|
||||
if (!subAsset) return;
|
||||
var filename = SanitizePath(subAsset.name);
|
||||
var dirName = Path.GetDirectoryName(t.assetPath) + "/Materials";
|
||||
if (!Directory.Exists(dirName))
|
||||
Directory.CreateDirectory(dirName);
|
||||
var destinationPath = dirName + "/" + filename + ".mat";
|
||||
var assetPath = AssetDatabase.GetAssetPath(subAsset);
|
||||
|
||||
var clone = Instantiate(subAsset);
|
||||
AssetDatabase.CreateAsset(clone, destinationPath);
|
||||
|
||||
var assetImporter = AssetImporter.GetAtPath(assetPath);
|
||||
assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(subAsset), clone);
|
||||
|
||||
if (importImmediately)
|
||||
{
|
||||
AssetDatabase.WriteImportSettingsIfDirty(assetPath);
|
||||
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
const string key2 = nameof(GLTFImporterInspector) + "_RemapMaterials_List";
|
||||
var newVal2 = EditorGUILayout.BeginFoldoutHeaderGroup(SessionState.GetBool(key2, false), "Remap Materials (" + mats.arraySize + ")");
|
||||
SessionState.SetBool(key2, newVal2);
|
||||
if (newVal2)
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
var mat = mats.GetArrayElementAtIndex(i).objectReferenceValue as Material;
|
||||
if (!mat) continue;
|
||||
var id = new AssetImporter.SourceAssetIdentifier(mat);
|
||||
externalObjectMap.TryGetValue(id, out var remap);
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
// EditorGUILayout.ObjectField(/*mat.name,*/ mat, typeof(Material), false);
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var newObj = EditorGUILayout.ObjectField(mat.name, remap, typeof(Material), false);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
if (newObj && newObj != mat)
|
||||
t.AddRemap(id, newObj);
|
||||
else
|
||||
t.RemoveRemap(id);
|
||||
}
|
||||
|
||||
if (!remap)
|
||||
{
|
||||
if (GUILayout.Button("Extract", GUILayout.Width(60)))
|
||||
{
|
||||
ExtractMaterial(mat, true);
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (GUILayout.Button("Restore", GUILayout.Width(60)))
|
||||
{
|
||||
t.RemoveRemap(id);
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
SaveChanges();
|
||||
#else
|
||||
ApplyAndImport();
|
||||
#endif
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.EndHorizontal();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
EditorGUILayout.PrefixLabel(" ");
|
||||
if (GUILayout.Button("Restore Materials"))
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
var mat = mats.GetArrayElementAtIndex(i).objectReferenceValue as Material;
|
||||
if (!mat) continue;
|
||||
t.RemoveRemap(new AssetImporter.SourceAssetIdentifier(mat));
|
||||
}
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Extract Materials"))
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
AssetDatabase.StartAssetEditing();
|
||||
ExtractMaterial(mats.GetArrayElementAtIndex(i).objectReferenceValue as Material, false);
|
||||
AssetDatabase.StopAssetEditing();
|
||||
var assetPath = AssetDatabase.GetAssetPath(target);
|
||||
AssetDatabase.WriteImportSettingsIfDirty(assetPath);
|
||||
AssetDatabase.Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.EndHorizontal();
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
|
||||
EditorGUILayout.EndFoldoutHeaderGroup();
|
||||
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
var identifierProp = serializedObject.FindProperty(nameof(GLTFImporter._useSceneNameIdentifier));
|
||||
if (!identifierProp.boolValue)
|
||||
{
|
||||
EditorGUILayout.HelpBox("This asset uses the old main asset identifier. Upgrade to the new one if you want to seamlessly switch between glTFast and UnityGLTF on import.\nNOTE: This will break existing scene references.", MessageType.Info);
|
||||
if (GUILayout.Button("Update Asset Identifier"))
|
||||
{
|
||||
identifierProp.boolValue = true;
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
try
|
||||
{
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
SaveChanges();
|
||||
#else
|
||||
ApplyAndImport();
|
||||
#endif
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignore - seems in some cases the GameObjectInspector will throw
|
||||
}
|
||||
}
|
||||
}
|
||||
// EditorGUILayout.PropertyField(serializedObject.FindProperty("_useJpgTextures"), new GUIContent("Use JPG Textures"));
|
||||
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
TextureWarningsGUI(t);
|
||||
}
|
||||
|
||||
private void ExtensionInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
EditorGUI.BeginDisabledGroup(true);
|
||||
var mainAssetIdentifierProp = serializedObject.FindProperty(nameof(GLTFImporter._mainAssetIdentifier));
|
||||
EditorGUILayout.PropertyField(mainAssetIdentifierProp);
|
||||
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._extensions)), new GUIContent("Extensions"));
|
||||
EditorGUI.EndDisabledGroup();
|
||||
}
|
||||
|
||||
public static bool TextureImportSettingsAreCorrect(GLTFImporter importer)
|
||||
{
|
||||
return importer.Textures.All(x =>
|
||||
{
|
||||
if (AssetDatabase.Contains(x.texture) && AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(x.texture)) is TextureImporter textureImporter)
|
||||
{
|
||||
return textureImporter.sRGBTexture == !x.shouldBeLinear;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static void FixTextureImportSettings(GLTFImporter importer)
|
||||
{
|
||||
var haveStartedAssetEditing = false;
|
||||
foreach (var x in importer.Textures)
|
||||
{
|
||||
if (!AssetDatabase.Contains(x.texture) || !(AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(x.texture)) is TextureImporter textureImporter)) continue;
|
||||
|
||||
// skip if already correct
|
||||
if (textureImporter.sRGBTexture == !x.shouldBeLinear)
|
||||
continue;
|
||||
|
||||
if (!haveStartedAssetEditing)
|
||||
{
|
||||
haveStartedAssetEditing = true;
|
||||
AssetDatabase.StartAssetEditing();
|
||||
}
|
||||
|
||||
textureImporter.sRGBTexture = !x.shouldBeLinear;
|
||||
textureImporter.SaveAndReimport();
|
||||
}
|
||||
|
||||
if (haveStartedAssetEditing)
|
||||
AssetDatabase.StopAssetEditing();
|
||||
}
|
||||
|
||||
private static string SanitizePath(string subAssetName)
|
||||
{
|
||||
// make filename safe without using Regex
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var sb = new StringBuilder(subAssetName);
|
||||
for (int i = 0; i < sb.Length; i++)
|
||||
{
|
||||
if (invalidChars.Contains(sb[i]))
|
||||
{
|
||||
sb[i] = '_';
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 20d4d64afd8e74d39a8d8fad13d909fc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,11 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public enum GLTFImporterNormals
|
||||
{
|
||||
Import,
|
||||
Calculate,
|
||||
None
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f3961a7b54dd64330a1228d3aa9993c0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+2
-3
@@ -1,9 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 01ef782d02bb1994dbe418b69432552b
|
||||
guid: 043bcd2f8cd689d4298a4ff9f11d1056
|
||||
folderAsset: yes
|
||||
timeCreated: 1466788344
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal class AvatarUtils
|
||||
{
|
||||
// A static dictionary containing the mapping from joint/bones names in the model
|
||||
// to the names Unity uses for them internally.
|
||||
// In this case they match the naming from the included Mixamo model on the left
|
||||
// and the Unity equivalent name on the right.
|
||||
// This does not need to be hard-coded.
|
||||
public static Dictionary<string, string> HumanSkeletonNames = new Dictionary<string, string>()
|
||||
{
|
||||
{"mixamorig:Spine1", "Chest"},
|
||||
{"mixamorig:Head", "Head" },
|
||||
{"mixamorig:Hips", "Hips" },
|
||||
{"mixamorig:LeftHandIndex3", "Left Index Distal" },
|
||||
{"mixamorig:LeftHandIndex2", "Left Index Intermediate" },
|
||||
{"mixamorig:LeftHandIndex1", "Left Index Proximal" },
|
||||
{"mixamorig:LeftHandPinky3", "Left Little Distal" },
|
||||
{"mixamorig:LeftHandPinky2", "Left Little Intermediate" },
|
||||
{"mixamorig:LeftHandPinky1", "Left Little Proximal" },
|
||||
{"mixamorig:LeftHandMiddle3", "Left Middle Distal" },
|
||||
{"mixamorig:LeftHandMiddle2", "Left Middle Intermediate" },
|
||||
{"mixamorig:LeftHandMiddle1", "Left Middle Proximal" },
|
||||
{"mixamorig:LeftHandRing3", "Left Ring Distal" },
|
||||
{"mixamorig:LeftHandRing2", "Left Ring Intermediate" },
|
||||
{"mixamorig:LeftHandRing1", "Left Ring Proximal" },
|
||||
{"mixamorig:LeftHandThumb3", "Left Thumb Distal" },
|
||||
{"mixamorig:LeftHandThumb2", "Left Thumb Intermediate" },
|
||||
{"mixamorig:LeftHandThumb1", "Left Thumb Proximal" },
|
||||
{"mixamorig:LeftFoot", "LeftFoot" },
|
||||
{"mixamorig:LeftHand", "LeftHand" },
|
||||
{"mixamorig:LeftForeArm", "LeftLowerArm" },
|
||||
{"mixamorig:LeftLeg", "LeftLowerLeg" },
|
||||
{"mixamorig:LeftShoulder", "LeftShoulder" },
|
||||
{"mixamorig:LeftToeBase", "LeftToes" },
|
||||
{"mixamorig:LeftArm", "LeftUpperArm" },
|
||||
{"mixamorig:LeftUpLeg", "LeftUpperLeg" },
|
||||
{"mixamorig:Neck", "Neck" },
|
||||
{"mixamorig:RightHandIndex3", "Right Index Distal" },
|
||||
{"mixamorig:RightHandIndex2", "Right Index Intermediate" },
|
||||
{"mixamorig:RightHandIndex1", "Right Index Proximal" },
|
||||
{"mixamorig:RightHandPinky3", "Right Little Distal" },
|
||||
{"mixamorig:RightHandPinky2", "Right Little Intermediate" },
|
||||
{"mixamorig:RightHandPinky1", "Right Little Proximal" },
|
||||
{"mixamorig:RightHandMiddle3", "Right Middle Distal" },
|
||||
{"mixamorig:RightHandMiddle2", "Right Middle Intermediate" },
|
||||
{"mixamorig:RightHandMiddle1", "Right Middle Proximal" },
|
||||
{"mixamorig:RightHandRing3", "Right Ring Distal" },
|
||||
{"mixamorig:RightHandRing2", "Right Ring Intermediate" },
|
||||
{"mixamorig:RightHandRing1", "Right Ring Proximal" },
|
||||
{"mixamorig:RightHandThumb3", "Right Thumb Distal" },
|
||||
{"mixamorig:RightHandThumb2", "Right Thumb Intermediate" },
|
||||
{"mixamorig:RightHandThumb1", "Right Thumb Proximal" },
|
||||
{"mixamorig:RightFoot", "RightFoot" },
|
||||
{"mixamorig:RightHand", "RightHand" },
|
||||
{"mixamorig:RightForeArm", "RightLowerArm" },
|
||||
{"mixamorig:RightLeg", "RightLowerLeg" },
|
||||
{"mixamorig:RightShoulder", "RightShoulder" },
|
||||
{"mixamorig:RightToeBase", "RightToes" },
|
||||
{"mixamorig:RightArm", "RightUpperArm" },
|
||||
{"mixamorig:RightUpLeg", "RightUpperLeg" },
|
||||
{"mixamorig:Spine", "Spine" },
|
||||
{"mixamorig:Spine2", "UpperChest" },
|
||||
|
||||
// Other common Avatar formats can also be added here
|
||||
// { "root", "" },
|
||||
{ "hips", "Hips" },
|
||||
{ "spine", "Spine" },
|
||||
{ "chest", "Chest" },
|
||||
{ "upperChest", "UpperChest" },
|
||||
{ "neck", "Neck" },
|
||||
{ "head", "Head" },
|
||||
{ "leftEye", "LeftEye" },
|
||||
// { "eyeL_end", "" },
|
||||
{ "rightEye", "RightEye" },
|
||||
// { "eyeR_end", "" },
|
||||
{ "leftShoulder", "LeftShoulder" },
|
||||
{ "leftUpperArm", "LeftUpperArm" },
|
||||
{ "leftLowerArm", "LeftLowerArm" },
|
||||
{ "leftHand", "LeftHand" },
|
||||
// { "leftThumbMetacarpal", "" },
|
||||
// { "leftThumbProximal", "" },
|
||||
// { "leftThumbDistal", "" },
|
||||
// { "thumbdistalL_end", "" },
|
||||
// { "leftIndexProximal", "" },
|
||||
// { "leftIndexIntermediate", "" },
|
||||
// { "leftIndexDistal", "" },
|
||||
// { "indexdistalL_end", "" },
|
||||
// { "leftMiddleProximal", "" },
|
||||
// { "leftMiddleIntermediate", "" },
|
||||
// { "leftMiddleDistal", "" },
|
||||
// { "middledistalL_end", "" },
|
||||
// { "leftRingProximal", "" },
|
||||
// { "leftRingIntermediate", "" },
|
||||
// { "leftRingDistal", "" },
|
||||
// { "ringdistalL_end", "" },
|
||||
// { "leftLittleProximal", "" },
|
||||
// { "leftLittleIntermediate", "" },
|
||||
// { "leftLittleDistal", "" },
|
||||
// { "littledistalL_end", "" },
|
||||
{ "rightShoulder", "RightShoulder" },
|
||||
{ "rightUpperArm", "RightUpperArm" },
|
||||
{ "rightLowerArm", "RightLowerArm" },
|
||||
{ "rightHand", "RightHand" },
|
||||
// { "rightThumbMetacarpal", "" },
|
||||
// { "rightThumbProximal", "" },
|
||||
// { "rightThumbDistal", "" },
|
||||
// { "thumbdistalR_end", "" },
|
||||
// { "rightIndexProximal", "" },
|
||||
// { "rightIndexIntermediate", "" },
|
||||
// { "rightIndexDistal", "" },
|
||||
// { "indexdistalR_end", "" },
|
||||
// { "rightMiddleProximal", "" },
|
||||
// { "rightMiddleIntermediate", "" },
|
||||
// { "rightMiddleDistal", "" },
|
||||
// { "middledistalR_end", "" },
|
||||
// { "rightRingProximal", "" },
|
||||
// { "rightRingIntermediate", "" },
|
||||
// { "rightRingDistal", "" },
|
||||
// { "ringdistalR_end", "" },
|
||||
// { "rightLittleProximal", "" },
|
||||
// { "rightLittleIntermediate", "" },
|
||||
// { "rightLittleDistal", "" },
|
||||
// { "littledistalR_end", "" },
|
||||
{ "leftUpperLeg", "LeftUpperLeg" },
|
||||
{ "leftLowerLeg", "LeftLowerLeg" },
|
||||
{ "leftFoot", "LeftFoot" },
|
||||
{ "leftToes", "LeftToes" },
|
||||
// { "toesL_end", "" },
|
||||
{ "rightUpperLeg", "RightUpperLeg" },
|
||||
{ "rightLowerLeg", "RightLowerLeg" },
|
||||
{ "rightFoot", "RightFoot" },
|
||||
{ "rightToes", "RightToes" },
|
||||
// { "toesR_end", "" },
|
||||
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Create a HumanDescription out of an avatar GameObject.
|
||||
/// The HumanDescription is what is needed to create an Avatar object
|
||||
/// using the AvatarBuilder API. This function takes care of
|
||||
/// creating the HumanDescription by going through the avatar's
|
||||
/// hierarchy, defining its T-Pose in the skeleton, and defining
|
||||
/// the transform/bone mapping in the HumanBone array.
|
||||
/// </summary>
|
||||
/// <param name="avatarRoot">Root of your avatar object</param>
|
||||
/// <returns>A HumanDescription which can be fed to the AvatarBuilder API</returns>
|
||||
public static HumanDescription CreateHumanDescription(GameObject avatarRoot)
|
||||
{
|
||||
HumanDescription description = new HumanDescription()
|
||||
{
|
||||
armStretch = 0.05f,
|
||||
feetSpacing = 0f,
|
||||
hasTranslationDoF = false,
|
||||
legStretch = 0.05f,
|
||||
lowerArmTwist = 0.5f,
|
||||
lowerLegTwist = 0.5f,
|
||||
upperArmTwist = 0.5f,
|
||||
upperLegTwist = 0.5f,
|
||||
skeleton = CreateSkeleton(avatarRoot),
|
||||
human = CreateHuman(avatarRoot),
|
||||
};
|
||||
return description;
|
||||
}
|
||||
|
||||
//Create a SkeletonBone array out of an Avatar GameObject
|
||||
//This assumes that the Avatar as supplied is in a T-Pose
|
||||
//The local positions of its bones/joints are used to define this T-Pose
|
||||
private static SkeletonBone[] CreateSkeleton(GameObject avatarRoot)
|
||||
{
|
||||
List<SkeletonBone> skeleton = new List<SkeletonBone>();
|
||||
|
||||
Transform[] avatarTransforms = avatarRoot.GetComponentsInChildren<Transform>();
|
||||
foreach (Transform avatarTransform in avatarTransforms)
|
||||
{
|
||||
SkeletonBone bone = new SkeletonBone()
|
||||
{
|
||||
name = avatarTransform.name,
|
||||
position = avatarTransform.localPosition,
|
||||
rotation = avatarTransform.localRotation,
|
||||
scale = avatarTransform.localScale
|
||||
};
|
||||
|
||||
skeleton.Add(bone);
|
||||
}
|
||||
return skeleton.ToArray();
|
||||
}
|
||||
|
||||
//Create a HumanBone array out of an Avatar GameObject
|
||||
//This is where the various bones/joints get associated with the
|
||||
//joint names that Unity understands. This is done using the
|
||||
//static dictionary defined at the top.
|
||||
private static HumanBone[] CreateHuman(GameObject avatarRoot)
|
||||
{
|
||||
List<HumanBone> human = new List<HumanBone>();
|
||||
|
||||
Transform[] avatarTransforms = avatarRoot.GetComponentsInChildren<Transform>();
|
||||
foreach (Transform avatarTransform in avatarTransforms)
|
||||
{
|
||||
if (HumanSkeletonNames.TryGetValue(avatarTransform.name, out string humanName))
|
||||
{
|
||||
HumanBone bone = new HumanBone
|
||||
{
|
||||
boneName = avatarTransform.name,
|
||||
humanName = humanName,
|
||||
limit = new HumanLimit()
|
||||
};
|
||||
bone.limit.useDefaultValues = true;
|
||||
|
||||
human.Add(bone);
|
||||
}
|
||||
}
|
||||
return human.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 15daddec8a84e584db94b127e7bd05b7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,271 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEditorInternal;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class GLTFMaterialHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Return false if other delegates should take over. Only return true if you did work and assigned material.shader = newShader.
|
||||
/// </summary>
|
||||
public delegate bool ConvertMaterialToGLTFDelegate(Material material, Shader oldShader, Shader newShader);
|
||||
private static event ConvertMaterialToGLTFDelegate ConvertMaterialDelegates;
|
||||
|
||||
public static void RegisterMaterialConversionToGLTF(ConvertMaterialToGLTFDelegate converter) => ConvertMaterialDelegates += converter;
|
||||
public static void UnregisterMaterialConversionToGLTF(ConvertMaterialToGLTFDelegate converter) => ConvertMaterialDelegates -= converter;
|
||||
|
||||
public static void ConvertMaterialToGLTF(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
if (ConvertMaterialDelegates != null)
|
||||
{
|
||||
var list = ConvertMaterialDelegates.GetInvocationList();
|
||||
foreach (var entry in list)
|
||||
{
|
||||
var cb = (ConvertMaterialToGLTFDelegate) entry;
|
||||
if (cb != null && cb.Invoke(material, oldShader, newShader))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IDEA ideally this would use the same code path as material export/import - would reduce the amount of code duplication considerably.
|
||||
// E.g. calling something like
|
||||
// var glTFMaterial = ExportMaterial(material);
|
||||
// ImportAndOverrideMaterial(material, glTFMaterial);
|
||||
// that uses all the same heuristics, texture conversions, ...
|
||||
|
||||
var msg = "No automatic conversion\nfrom " + oldShader.name + "\nto " + newShader.name + "\nfound.\n\nYou can create a conversion script, adjust which old properties map to which new properties, and switch the shader again.";
|
||||
|
||||
#if UNITY_EDITOR
|
||||
var choice = EditorUtility.DisplayDialogComplex("Shader Conversion", msg, "Just set shader", "Cancel", "Create and open conversion script");
|
||||
switch (choice)
|
||||
{
|
||||
case 0: // OK
|
||||
material.shader = newShader;
|
||||
break;
|
||||
case 1: // Cancel
|
||||
break;
|
||||
case 2: // Alt
|
||||
var path = ShaderConversion.CreateConversionScript(oldShader, newShader);
|
||||
InternalEditorUtility.OpenFileAtLineExternal(path, 0);
|
||||
break;
|
||||
}
|
||||
#else
|
||||
Debug.Log(msg + " Make sure your material properties match the new shader. You can add your own conversion callbacks via `RegisterMaterialConversionToGLTF`. If you think this should have been converted automatically: please open a feature request!");
|
||||
material.shader = newShader;
|
||||
#endif
|
||||
}
|
||||
|
||||
public static void ValidateMaterialKeywords(Material material)
|
||||
{
|
||||
// TODO ensure we're setting correct keywords for
|
||||
// - existence of a normal map
|
||||
// - existence of emission color values or texture
|
||||
// -
|
||||
|
||||
// var needsVolumeTransmission = false;
|
||||
// needsVolumeTransmission |= material.HasProperty(thicknessFactor) && material.GetFloat(thicknessFactor) > 0;
|
||||
// needsVolumeTransmission |= material.HasProperty(transmissionFactor) && material.GetFloat(transmissionFactor) > 0;
|
||||
// material.SetKeyword("_VOLUME_TRANSMISSION", needsVolumeTransmission);
|
||||
//
|
||||
// var needsIridescence = material.HasProperty(iridescenceFactor) && material.GetFloat(iridescenceFactor) > 0;
|
||||
// material.SetKeyword("_IRIDESCENCE", needsIridescence);
|
||||
//
|
||||
// var needsSpecular = material.HasProperty(specularFactor) && material.GetFloat(specularFactor) > 0;
|
||||
// material.SetKeyword("_SPECULAR", needsSpecular);
|
||||
|
||||
if (material.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
|
||||
{
|
||||
// // approximation when transmission is on but roughness == 0
|
||||
// // (no opaque pass required)
|
||||
// TODO does weird things with transparency but still rendering into the Opaque Texture for some reason
|
||||
// if (material.HasProperty("roughnessFactor") && material.GetFloat("roughnessFactor") == 0)
|
||||
// {
|
||||
// // enforce transparent
|
||||
// if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 0);
|
||||
// if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 0);
|
||||
// if (material.HasProperty("_BUILTIN_Surface")) material.SetFloat("_BUILTIN_Surface", 1);
|
||||
// if (material.HasProperty("_Surface")) material.SetFloat("_Surface", 1);
|
||||
// material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
// material.EnableKeyword("_BUILTIN_SURFACE_TYPE_TRANSPARENT");
|
||||
// material.renderQueue = -1;
|
||||
// }
|
||||
// else
|
||||
{
|
||||
// enforce Opaque
|
||||
if (material.HasProperty("_BUILTIN_Surface")) material.SetFloat("_BUILTIN_Surface", 0);
|
||||
if (material.HasProperty("_Surface")) material.SetFloat("_Surface", 0);
|
||||
material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
material.DisableKeyword("_BUILTIN_SURFACE_TYPE_TRANSPARENT");
|
||||
|
||||
// enforce queue control and render queue 3000
|
||||
if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 1);
|
||||
if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 1);
|
||||
|
||||
// not a great choice: using 2999 as magic value for "we automatically set the queue for you"
|
||||
// so the change can be reverted if someone toggles transmission on and then off again.
|
||||
material.renderQueue = 2999;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (material.renderQueue == 2999)
|
||||
{
|
||||
if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 0);
|
||||
if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 0);
|
||||
material.renderQueue = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (material.HasProperty("emissiveFactor"))
|
||||
material.globalIlluminationFlags = MaterialEditor.FixupEmissiveFlag(material.GetColor("emissiveFactor"), material.globalIlluminationFlags);
|
||||
|
||||
if (!material.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
|
||||
{
|
||||
if (material.GetTextureScale("baseColorTexture") != Vector2.one || material.GetTextureOffset("baseColorTexture") != Vector2.zero)
|
||||
{
|
||||
SetKeyword(material, "_TEXTURE_TRANSFORM", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetKeyword(Material material, string keyword, bool state)
|
||||
{
|
||||
if (state)
|
||||
material.EnableKeyword(keyword + "_ON");
|
||||
else
|
||||
material.DisableKeyword(keyword + "_ON");
|
||||
|
||||
if (material.HasProperty(keyword))
|
||||
material.SetFloat(keyword, state ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal static class ShaderConversion
|
||||
{
|
||||
public static string CreateConversionScript(Shader oldShader, Shader newShader)
|
||||
{
|
||||
var classShaderName = oldShader.name
|
||||
.Replace("/", "_")
|
||||
.Replace(" ", "_")
|
||||
.Replace("\\", "_");
|
||||
|
||||
var scriptFile = ShaderConversionScriptTemplate;
|
||||
scriptFile = scriptFile.Replace("<OldShader>", classShaderName);
|
||||
scriptFile = scriptFile.Replace("<OldShaderName>", oldShader.name);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach(var (propName, propDisplayName, type) in GetShaderProperties(oldShader))
|
||||
{
|
||||
sb.AppendLine($"\t\tvar {propName} = material.{MethodFromType("Get", type)}(\"{propName}\"); // {propDisplayName}");
|
||||
}
|
||||
|
||||
var sb2 = new StringBuilder();
|
||||
foreach(var (propName, propDisplayName, type) in GetShaderProperties(newShader))
|
||||
{
|
||||
sb2.AppendLine($"\t\t// material.{MethodFromType("Set", type)}(\"{propName}\", insert_value_here); // {propDisplayName}");
|
||||
}
|
||||
|
||||
scriptFile = scriptFile.Replace("\t\t<OldProperties>", sb.ToString());
|
||||
scriptFile = scriptFile.Replace("\t\t<NewProperties>", sb2.ToString());
|
||||
|
||||
const string dir = "Assets/Editor/ShaderConversions";
|
||||
Directory.CreateDirectory(dir);
|
||||
var fileName = dir + "/" + classShaderName + ".cs";
|
||||
if (!File.Exists(fileName) || EditorUtility.DisplayDialog("File already exists", $"The file \"{fileName}\" already exists. Replace?", "Replace", "Cancel"))
|
||||
File.WriteAllText(fileName, scriptFile);
|
||||
|
||||
AssetDatabase.Refresh();
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
private static IEnumerable<(string propName, string propDisplayName, ShaderUtil.ShaderPropertyType type)> GetShaderProperties(Shader shader)
|
||||
{
|
||||
var c = ShaderUtil.GetPropertyCount(shader);
|
||||
for (var i = 0; i < c; i++)
|
||||
{
|
||||
if (ShaderUtil.IsShaderPropertyHidden(shader, i)) continue;
|
||||
if (ShaderUtil.IsShaderPropertyNonModifiableTexureProperty(shader, i)) continue;
|
||||
|
||||
var propName = ShaderUtil.GetPropertyName(shader, i);
|
||||
if(propName.StartsWith("unity_")) continue;
|
||||
|
||||
var propDisplayName = ShaderUtil.GetPropertyDescription(shader, i);
|
||||
var type = ShaderUtil.GetPropertyType(shader, i);
|
||||
yield return (propName, propDisplayName, type);
|
||||
}
|
||||
}
|
||||
|
||||
private static string MethodFromType(string prefix, ShaderUtil.ShaderPropertyType propertyType)
|
||||
{
|
||||
switch (propertyType)
|
||||
{
|
||||
case ShaderUtil.ShaderPropertyType.Color: return prefix + "Color";
|
||||
case ShaderUtil.ShaderPropertyType.Float: return prefix + "Float";
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
case ShaderUtil.ShaderPropertyType.Int: return prefix + "Int";
|
||||
#endif
|
||||
case ShaderUtil.ShaderPropertyType.Range: return prefix + "Float";
|
||||
case ShaderUtil.ShaderPropertyType.Vector: return prefix + "Vector";
|
||||
case ShaderUtil.ShaderPropertyType.TexEnv: return prefix + "Texture";
|
||||
}
|
||||
|
||||
return prefix + "UnknownPropertyType"; // compiler error
|
||||
}
|
||||
|
||||
private const string ShaderConversionScriptTemplate =
|
||||
@"using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityGLTF;
|
||||
|
||||
class Convert_<OldShader>_to_GLTF
|
||||
{
|
||||
const string shaderName = ""<OldShaderName>"";
|
||||
|
||||
[InitializeOnLoadMethod]
|
||||
private static void Register()
|
||||
{
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertMaterialProperties);
|
||||
}
|
||||
|
||||
private static bool ConvertMaterialProperties(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
if (oldShader.name != shaderName) return false;
|
||||
|
||||
// Reading old shader properties.
|
||||
|
||||
<OldProperties>
|
||||
material.shader = newShader;
|
||||
|
||||
// Assigning new shader properties.
|
||||
// Uncomment lines you need, and set properties from values from the section above.
|
||||
|
||||
<NewProperties>
|
||||
|
||||
// Ensure keywords are correctly set after conversion.
|
||||
// Example:
|
||||
// if (material.GetFloat(""_VERTEX_COLORS"") > 0.5f) material.EnableKeyword(""_VERTEX_COLORS_ON"");
|
||||
|
||||
ShaderGraphHelpers.ValidateMaterialKeywords(material);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ad1a4409c80a9004781468cca77d6224
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal static class HumanoidSetup
|
||||
{
|
||||
private static MethodInfo _SetupHumanSkeleton;
|
||||
|
||||
internal static Avatar AddAvatarToGameObject(GameObject gameObject)
|
||||
{
|
||||
HumanDescription description = AvatarUtils.CreateHumanDescription(gameObject);
|
||||
var bones = description.human;
|
||||
SetupHumanSkeleton(gameObject, ref bones, out var skeletonBones, out var hasTranslationDoF);
|
||||
description.human = bones;
|
||||
description.skeleton = skeletonBones;
|
||||
description.hasTranslationDoF = hasTranslationDoF;
|
||||
|
||||
Avatar avatar = AvatarBuilder.BuildHumanAvatar(gameObject, description);
|
||||
avatar.name = "Avatar";
|
||||
|
||||
if (!avatar.isValid)
|
||||
{
|
||||
Object.DestroyImmediate(avatar);
|
||||
return null;
|
||||
}
|
||||
|
||||
var animator = gameObject.GetComponent<Animator>();
|
||||
if (animator) animator.avatar = avatar;
|
||||
return avatar;
|
||||
}
|
||||
|
||||
private static void SetupHumanSkeleton(
|
||||
GameObject modelPrefab,
|
||||
ref HumanBone[] humanBoneMappingArray,
|
||||
out SkeletonBone[] skeletonBones,
|
||||
out bool hasTranslationDoF)
|
||||
{
|
||||
_SetupHumanSkeleton = typeof(AvatarSetupTool).GetMethod(nameof(SetupHumanSkeleton), (BindingFlags)(-1));
|
||||
skeletonBones = Array.Empty<SkeletonBone>();
|
||||
hasTranslationDoF = false;
|
||||
|
||||
_SetupHumanSkeleton?.Invoke(null, new object[]
|
||||
{
|
||||
modelPrefab,
|
||||
humanBoneMappingArray,
|
||||
skeletonBones,
|
||||
hasTranslationDoF
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// AvatarSetupTools
|
||||
// AvatarBuilder.BuildHumanAvatar
|
||||
// AvatarConfigurationStage.CreateStage
|
||||
// AssetImporterTabbedEditor
|
||||
// ModelImporterRigEditor
|
||||
|
||||
#if TESTING
|
||||
[MenuItem("Tools/Copy Hierarchy Array")]
|
||||
static void _Copy(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
var sb = new System.Text.StringBuilder();
|
||||
|
||||
void Traverse(Transform tr)
|
||||
{
|
||||
sb.AppendLine(tr.name);
|
||||
foreach (Transform child in tr)
|
||||
{
|
||||
Traverse(child);
|
||||
}
|
||||
}
|
||||
|
||||
Traverse(gameObject.transform);
|
||||
EditorGUIUtility.systemCopyBuffer = sb.ToString();
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Setup Humanoid")]
|
||||
static void _Do(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
// SetupHumanSkeleton(go, ref humanBoneMappingArray, out var skeletonBones, out var hasTranslationDoF);
|
||||
AddAvatarToGameObject(gameObject);
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Open Avatar Editor")]
|
||||
static void _OpenEditor(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
var avatar = gameObject.GetComponent<Animator>().avatar;
|
||||
var e = (AvatarEditor) Editor.CreateEditor(avatar, typeof(AvatarEditor));
|
||||
e.m_CameFromImportSettings = true;
|
||||
Selection.activeObject = e;
|
||||
e.SwitchToEditMode();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 977986ddaa6e7594c81ccb48155a39a1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:343deaaf83e0cee4ca978e7df0b80d21"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9c9262dcd4069cd4aafbfe7eabf0bf41
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEditor;
|
||||
using UnityEditor.AssetImporters;
|
||||
using UnityEngine;
|
||||
|
||||
[assembly: InternalsVisibleTo("UnityGLTFEditor")]
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal class UnityGLTFTabbedEditor : AssetImporterTabbedEditor
|
||||
{
|
||||
private readonly List<GltfAssetImporterTab> _tabs = new List<GltfAssetImporterTab>();
|
||||
|
||||
protected void AddTab(GltfAssetImporterTab tab)
|
||||
{
|
||||
if (!_tabs.Contains(tab)) _tabs.Add(tab);
|
||||
tabs = _tabs.Select(x => (BaseAssetImporterTabUI) x).ToArray();
|
||||
m_TabNames = _tabs.Select(t => t.Label).ToArray();
|
||||
}
|
||||
|
||||
public GltfAssetImporterTab GetTab(int index)
|
||||
{
|
||||
if (_tabs == null || _tabs.Count < 1) return null;
|
||||
if (index < 0) index = 0;
|
||||
if (index >= _tabs.Count) index = _tabs.Count - 1;
|
||||
return _tabs[index];
|
||||
}
|
||||
|
||||
public override void OnEnable() => base.OnEnable();
|
||||
}
|
||||
|
||||
internal class GltfAssetImporterTab : BaseAssetImporterTabUI
|
||||
{
|
||||
internal readonly string Label;
|
||||
private readonly Action _tabGui;
|
||||
|
||||
public GltfAssetImporterTab(AssetImporterEditor panelContainer, string label, Action tabGui) : base(panelContainer)
|
||||
{
|
||||
this.Label = label;
|
||||
this._tabGui = tabGui;
|
||||
}
|
||||
|
||||
internal override void OnEnable() { }
|
||||
public override void OnInspectorGUI() => _tabGui?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 198f536c3cf84dfe9d5617d32d40d7b0
|
||||
timeCreated: 1678788492
|
||||
@@ -0,0 +1,25 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public interface IUnityGltfShaderUpgradeMeta
|
||||
{
|
||||
Shader SourceShader { get; }
|
||||
bool IsUnlit { get; }
|
||||
bool IsTransparent { get; }
|
||||
bool IsDoublesided { get; }
|
||||
}
|
||||
|
||||
public class UnityGltfShaderUpgradeMeta : ScriptableObject
|
||||
{
|
||||
public Shader sourceShader;
|
||||
public bool isTransparent = false;
|
||||
public bool isDoublesided = false;
|
||||
|
||||
internal string GenerateNameString()
|
||||
{
|
||||
var isUnlit = sourceShader && sourceShader.name.Contains("Unlit");
|
||||
return (isTransparent ? "_tr" : "") + (isDoublesided ? "_ds" : "") + (isUnlit ? "_unlit" : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 26fa35d7d798408bb796a50daa5a8a6f
|
||||
timeCreated: 1677690411
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fa6ac3fcfd75d5c469e07cedac8f2f57
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,278 @@
|
||||
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
|
||||
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityEditor
|
||||
{
|
||||
internal class PbrShaderGUI : ShaderGUI
|
||||
{
|
||||
private enum WorkflowMode
|
||||
{
|
||||
SpecularGlossiness,
|
||||
MetallicRoughness,
|
||||
Unlit
|
||||
}
|
||||
|
||||
public enum BlendMode
|
||||
{
|
||||
Opaque,
|
||||
Mask,
|
||||
Blend
|
||||
}
|
||||
|
||||
private static class Styles
|
||||
{
|
||||
public static GUIContent albedoText = new GUIContent("Base Color", "Albedo (RGB) and Transparency (A)");
|
||||
public static GUIContent vertexColorText = new GUIContent("Apply Vertex Colors", "Process vertex colors");
|
||||
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
|
||||
public static GUIContent specularMapText = new GUIContent("Spec Gloss", "Specular (RGB) and Glossiness (A)");
|
||||
public static GUIContent metallicMapText = new GUIContent("Metal Rough", "Metallic (B) and Roughness (G)");
|
||||
public static GUIContent metallicText = new GUIContent("Metallic", "Metallic value");
|
||||
public static GUIContent metallicScaleText = new GUIContent("Metallic", "Metallic scale factor");
|
||||
public static GUIContent roughnessText = new GUIContent("Roughness", "Roughness value");
|
||||
|
||||
public static GUIContent roughnessScaleText = new GUIContent("Roughness", "Roughness scale factor");
|
||||
public static GUIContent glossinessText = new GUIContent("Glossiness", "Glossiness value");
|
||||
public static GUIContent glossinessScaleText = new GUIContent("Glossiness", "Glossiness scale factor");
|
||||
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
|
||||
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (R)");
|
||||
public static GUIContent emissionText = new GUIContent("Emissive", "Emissive (RGB)");
|
||||
|
||||
public static string primaryMapsText = "Main Maps";
|
||||
public static string renderingMode = "Rendering Mode";
|
||||
public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive.");
|
||||
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
|
||||
}
|
||||
|
||||
MaterialProperty blendMode = null;
|
||||
MaterialProperty albedoMap = null;
|
||||
MaterialProperty albedoColor = null;
|
||||
MaterialProperty vertexColors = null;
|
||||
MaterialProperty alphaCutoff = null;
|
||||
MaterialProperty specularMap = null;
|
||||
MaterialProperty specularColor = null;
|
||||
MaterialProperty metallicMap = null;
|
||||
MaterialProperty metallic = null;
|
||||
MaterialProperty smoothness = null;
|
||||
MaterialProperty bumpScale = null;
|
||||
MaterialProperty bumpMap = null;
|
||||
MaterialProperty occlusionStrength = null;
|
||||
MaterialProperty occlusionMap = null;
|
||||
MaterialProperty emissionColor = null;
|
||||
MaterialProperty emissionMap = null;
|
||||
|
||||
MaterialEditor m_MaterialEditor;
|
||||
WorkflowMode m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
|
||||
bool m_FirstTimeApply = true;
|
||||
|
||||
public void FindProperties(MaterialProperty[] props)
|
||||
{
|
||||
blendMode = FindProperty("_Mode", props);
|
||||
albedoMap = FindProperty("_MainTex", props);
|
||||
albedoColor = FindProperty("_Color", props);
|
||||
vertexColors = FindProperty("_VertexColors", props);
|
||||
alphaCutoff = FindProperty("_Cutoff", props);
|
||||
specularMap = FindProperty("_SpecGlossMap", props, false);
|
||||
specularColor = FindProperty("_SpecColor", props, false);
|
||||
metallicMap = FindProperty("_MetallicGlossMap", props, false);
|
||||
metallic = FindProperty("_Metallic", props, false);
|
||||
if (specularMap != null && specularColor != null)
|
||||
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
|
||||
else if (metallicMap != null && metallic != null)
|
||||
m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
else
|
||||
m_WorkflowMode = WorkflowMode.Unlit;
|
||||
smoothness = FindProperty("_Glossiness", props);
|
||||
bumpScale = FindProperty("_BumpScale", props);
|
||||
bumpMap = FindProperty("_BumpMap", props);
|
||||
occlusionStrength = FindProperty("_OcclusionStrength", props);
|
||||
occlusionMap = FindProperty("_OcclusionMap", props);
|
||||
emissionColor = FindProperty("_EmissionColor", props);
|
||||
emissionMap = FindProperty("_EmissionMap", props);
|
||||
}
|
||||
|
||||
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
|
||||
{
|
||||
FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
|
||||
m_MaterialEditor = materialEditor;
|
||||
Material material = materialEditor.target as Material;
|
||||
|
||||
// Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing
|
||||
// material to a standard shader.
|
||||
// Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071)
|
||||
if (m_FirstTimeApply)
|
||||
{
|
||||
MaterialChanged(material, m_WorkflowMode);
|
||||
m_FirstTimeApply = false;
|
||||
}
|
||||
|
||||
ShaderPropertiesGUI(material);
|
||||
}
|
||||
|
||||
public void ShaderPropertiesGUI(Material material)
|
||||
{
|
||||
// Use default labelWidth
|
||||
EditorGUIUtility.labelWidth = 0f;
|
||||
|
||||
// Detect any changes to the material
|
||||
EditorGUI.BeginChangeCheck();
|
||||
{
|
||||
BlendModePopup();
|
||||
|
||||
// Primary properties
|
||||
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);
|
||||
DoAlbedoArea(material);
|
||||
DoSpecularMetallicArea();
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null);
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null);
|
||||
DoEmissionArea(material);
|
||||
|
||||
EditorGUILayout.Space();
|
||||
}
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
foreach (var obj in blendMode.targets)
|
||||
MaterialChanged((Material)obj, m_WorkflowMode);
|
||||
}
|
||||
}
|
||||
|
||||
internal void DetermineWorkflow(MaterialProperty[] props)
|
||||
{
|
||||
if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null)
|
||||
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
|
||||
else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null)
|
||||
m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
else
|
||||
m_WorkflowMode = WorkflowMode.Unlit;
|
||||
}
|
||||
|
||||
void BlendModePopup()
|
||||
{
|
||||
EditorGUI.showMixedValue = blendMode.hasMixedValue;
|
||||
var mode = (BlendMode)blendMode.floatValue;
|
||||
|
||||
EditorGUI.BeginChangeCheck();
|
||||
mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode");
|
||||
blendMode.floatValue = (float)mode;
|
||||
}
|
||||
|
||||
EditorGUI.showMixedValue = false;
|
||||
}
|
||||
|
||||
void DoAlbedoArea(Material material)
|
||||
{
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
|
||||
m_MaterialEditor.ShaderProperty(vertexColors, Styles.vertexColorText, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
|
||||
|
||||
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Mask))
|
||||
{
|
||||
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
|
||||
}
|
||||
}
|
||||
|
||||
void DoEmissionArea(Material material)
|
||||
{
|
||||
bool hadEmissionTexture = emissionMap.textureValue != null;
|
||||
|
||||
// Texture and HDR color controls
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, emissionColor);
|
||||
|
||||
// If texture was assigned and color was black set color to white
|
||||
float brightness = emissionColor.colorValue.maxColorComponent;
|
||||
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
|
||||
emissionColor.colorValue = Color.white;
|
||||
}
|
||||
|
||||
void DoSpecularMetallicArea()
|
||||
{
|
||||
bool hasGlossMap = false;
|
||||
if (m_WorkflowMode == WorkflowMode.SpecularGlossiness)
|
||||
{
|
||||
hasGlossMap = specularMap.textureValue != null;
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor);
|
||||
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.glossinessScaleText : Styles.glossinessText, 2);
|
||||
}
|
||||
else if (m_WorkflowMode == WorkflowMode.MetallicRoughness)
|
||||
{
|
||||
hasGlossMap = metallicMap.textureValue != null;
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap);
|
||||
m_MaterialEditor.ShaderProperty(metallic, hasGlossMap ? Styles.metallicScaleText : Styles.metallicText, 2);
|
||||
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.roughnessScaleText : Styles.roughnessText, 2);
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode, float alphaCutoff)
|
||||
{
|
||||
switch (blendMode)
|
||||
{
|
||||
case BlendMode.Opaque:
|
||||
material.SetOverrideTag("RenderType", "Opaque");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
|
||||
material.SetInt("_ZWrite", 1);
|
||||
material.DisableKeyword("_ALPHATEST_ON");
|
||||
material.DisableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry;
|
||||
break;
|
||||
case BlendMode.Mask:
|
||||
material.SetOverrideTag("RenderType", "TransparentCutout");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
|
||||
material.SetInt("_ZWrite", 1);
|
||||
material.EnableKeyword("_ALPHATEST_ON");
|
||||
material.DisableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
|
||||
material.SetFloat("_Cutoff", alphaCutoff);
|
||||
break;
|
||||
case BlendMode.Blend:
|
||||
material.SetOverrideTag("RenderType", "Transparent");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
||||
material.SetInt("_ZWrite", 0);
|
||||
material.DisableKeyword("_ALPHATEST_ON");
|
||||
material.EnableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
|
||||
break;
|
||||
}
|
||||
|
||||
material.SetFloat("_Mode", (float)blendMode);
|
||||
}
|
||||
|
||||
static void SetMaterialKeywords(Material material, WorkflowMode workflowMode)
|
||||
{
|
||||
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
|
||||
// (MaterialProperty value might come from renderer material property block)
|
||||
SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
|
||||
if (workflowMode == WorkflowMode.SpecularGlossiness)
|
||||
SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
|
||||
else if (workflowMode == WorkflowMode.MetallicRoughness)
|
||||
SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
|
||||
|
||||
bool shouldEmissionBeEnabled = material.GetColor("_EmissionColor") != Color.black;
|
||||
SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
|
||||
}
|
||||
|
||||
static void MaterialChanged(Material material, WorkflowMode workflowMode)
|
||||
{
|
||||
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), material.GetFloat("_Cutoff"));
|
||||
|
||||
SetMaterialKeywords(material, workflowMode);
|
||||
}
|
||||
|
||||
static void SetKeyword(Material m, string keyword, bool state)
|
||||
{
|
||||
if (state)
|
||||
m.EnableKeyword(keyword);
|
||||
else
|
||||
m.DisableKeyword(keyword);
|
||||
}
|
||||
}
|
||||
} // namespace UnityEditor
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc50aae8534b8c442a9e309b546db682
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4f9d8791ed9e9674d871b47bf1c186ea
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f708e30d7503fc42998ad4dc358d3d5
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
#if UNITY_2021_3_OR_NEWER
|
||||
#define HAVE_BUILTIN_SHADERGRAPH
|
||||
#define HAVE_CATEGORIES
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
#if HAVE_BUILTIN_SHADERGRAPH
|
||||
using UnityEditor.Rendering;
|
||||
using UnityEditor.Rendering.BuiltIn.ShaderGraph;
|
||||
#endif
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public class PBRGraphGUI :
|
||||
#if HAVE_BUILTIN_SHADERGRAPH
|
||||
BuiltInBaseShaderGUI
|
||||
#else
|
||||
ShaderGUI
|
||||
#endif
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
public override void ValidateMaterial(Material material)
|
||||
{
|
||||
base.ValidateMaterial(material);
|
||||
GLTFMaterialHelper.ValidateMaterialKeywords(material);
|
||||
}
|
||||
#endif
|
||||
|
||||
protected MaterialEditor materialEditor;
|
||||
protected MaterialProperty[] properties;
|
||||
private MaterialInfo currentMaterialInfo;
|
||||
|
||||
#if HAVE_CATEGORIES
|
||||
private readonly MaterialHeaderScopeList m_MaterialScopeList = new MaterialHeaderScopeList(uint.MaxValue & ~(uint)Expandable.Advanced);
|
||||
private const int ExpandableMeshProperties = 1 << 8;
|
||||
private static readonly GUIContent MeshProperties = new GUIContent("Mesh Properties");
|
||||
|
||||
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
|
||||
{
|
||||
this.materialEditor = materialEditor;
|
||||
this.properties = properties;
|
||||
|
||||
Material targetMat = materialEditor.target as Material;
|
||||
if (!targetMat || !targetMat.shader) return;
|
||||
|
||||
if (m_FirstTimeApply)
|
||||
{
|
||||
OnOpenGUI(targetMat, materialEditor, properties);
|
||||
m_FirstTimeApply = false;
|
||||
}
|
||||
|
||||
// need to set these via reflection...
|
||||
// m_MaterialEditor = materialEditor;
|
||||
// m_Properties = properties;
|
||||
if (m_MaterialEditor == null) m_MaterialEditor = typeof(BuiltInBaseShaderGUI).GetField(nameof(m_MaterialEditor), BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
if (m_Properties == null) m_Properties = typeof(BuiltInBaseShaderGUI).GetField(nameof(m_Properties), BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
m_MaterialEditor.SetValue(this, materialEditor);
|
||||
m_Properties.SetValue(this, properties);
|
||||
|
||||
var fullPath = System.IO.Path.GetFullPath(AssetDatabase.GetAssetPath(targetMat));
|
||||
var isMutable = !fullPath.Contains("Library/PackageCache") && !fullPath.Contains("Library\\PackageCache");
|
||||
if (targetMat && targetMat.shader.name.StartsWith("Hidden/UnityGLTF"))
|
||||
{
|
||||
if (isMutable)
|
||||
{
|
||||
DrawFixMeBox("This is a legacy shader. Please click \"Fix\" to upgrade to PBRGraph/UnlitGraph.", MessageType.Warning, () =>
|
||||
{
|
||||
var isUnlit = targetMat.shader.name.Contains("Unlit");
|
||||
var newShaderGuid = isUnlit ? "59541e6caf586ca4f96ccf48a4813a51" : "478ce3626be7a5f4ea58d6b13f05a2e4";
|
||||
var newShader = AssetDatabase.LoadAssetAtPath<Shader>(AssetDatabase.GUIDToAssetPath(newShaderGuid));
|
||||
Undo.RegisterCompleteObjectUndo(targetMat, "Convert to UnityGltf shader");
|
||||
GLTFMaterialHelper.ConvertMaterialToGLTF(targetMat, targetMat.shader, newShader);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawFixMeBox("This is a legacy shader. Upgrade to PBRGraph/UnlitGraph for more options.", MessageType.Warning, null);
|
||||
}
|
||||
}
|
||||
|
||||
m_MaterialScopeList.DrawHeaders(materialEditor, targetMat);
|
||||
}
|
||||
|
||||
private FieldInfo m_MaterialEditor;
|
||||
private FieldInfo m_Properties;
|
||||
|
||||
public override void OnOpenGUI(Material material, MaterialEditor materialEditor, MaterialProperty[] properties)
|
||||
{
|
||||
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceOptions, (uint)Expandable.SurfaceOptions, DrawSurfaceOptions);
|
||||
m_MaterialScopeList.RegisterHeaderScope(MeshProperties, (uint)ExpandableMeshProperties, DrawGameObjectInfo);
|
||||
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceInputs, (uint)Expandable.SurfaceInputs, DrawSurfaceInputs);
|
||||
m_MaterialScopeList.RegisterHeaderScope(Styles.AdvancedLabel, (uint)Expandable.Advanced, DrawAdvancedOptions);
|
||||
}
|
||||
#else
|
||||
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
|
||||
{
|
||||
this.materialEditor = materialEditor;
|
||||
this.properties = properties;
|
||||
|
||||
Material targetMat = materialEditor.target as Material;
|
||||
|
||||
DrawGameObjectInfo(targetMat);
|
||||
#if !UNITY_2021_1_OR_NEWER
|
||||
DrawSurfaceOptions(targetMat);
|
||||
#endif
|
||||
_DrawSurfaceInputs(targetMat);
|
||||
}
|
||||
#endif
|
||||
|
||||
private struct MaterialInfo
|
||||
{
|
||||
public bool hasColor;
|
||||
public bool hasUV0;
|
||||
public bool hasUV1;
|
||||
public int occlusionTextureTexCoord;
|
||||
public int baseColorTextureTexCoord;
|
||||
}
|
||||
|
||||
private static bool HasAnyTextureAssigned(Material targetMaterial)
|
||||
{
|
||||
var s = targetMaterial.shader;
|
||||
var propertyCount = ShaderUtil.GetPropertyCount(s);
|
||||
for (var i = 0; i < propertyCount; i++)
|
||||
{
|
||||
if (ShaderUtil.GetPropertyType(s, i) != ShaderUtil.ShaderPropertyType.TexEnv) continue;
|
||||
if (ShaderUtil.IsShaderPropertyHidden(s, i)) continue;
|
||||
var tex = targetMaterial.GetTexture(ShaderUtil.GetPropertyName(s, i));
|
||||
if (tex) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#if !UNITY_2021_1_OR_NEWER
|
||||
private static readonly Dictionary<string, string> ShaderNameToGuid = new Dictionary<string, string>()
|
||||
{
|
||||
{ "UnityGLTF/PBRGraph", "478ce3626be7a5f4ea58d6b13f05a2e4" },
|
||||
{ "UnityGLTF/PBRGraph-Transparent", "0a931320a74ca574b91d2d7d4557dcf1" },
|
||||
{ "UnityGLTF/PBRGraph-Transparent-Double", "54352a53405971b41a6587615f947085" },
|
||||
{ "UnityGLTF/PBRGraph-Double", "8bc739b14fe811644abb82057b363ba8" },
|
||||
|
||||
{ "UnityGLTF/UnlitGraph", "59541e6caf586ca4f96ccf48a4813a51" },
|
||||
{ "UnityGLTF/UnlitGraph-Transparent", "83f2caca07949794fb997734c4b0520f" },
|
||||
{ "UnityGLTF/UnlitGraph-Transparent-Double", "8a8841b4fb2f63644896f4e2b36bc06d" },
|
||||
{ "UnityGLTF/UnlitGraph-Double", "33ee70a7f505ddb4e80d235c3d70766d" },
|
||||
};
|
||||
|
||||
private void DrawSurfaceOptions(Material targetMaterial)
|
||||
{
|
||||
EditorGUILayout.Space();
|
||||
|
||||
var shaderName = targetMaterial.shader.name.Replace("Hidden/", "");
|
||||
var isTransparent = shaderName.Contains("-Transparent");
|
||||
var isDoubleSided = shaderName.Contains("-Double");
|
||||
var isCutout = targetMaterial.GetFloat("alphaCutoff") >= 0;
|
||||
var indexOfDash = shaderName.IndexOf("-", StringComparison.Ordinal);
|
||||
var baseShaderName = indexOfDash < 0 ? shaderName : shaderName.Substring(0, indexOfDash);
|
||||
// EditorGUILayout.LabelField("Shader Name", baseShaderName);
|
||||
|
||||
void SetShader()
|
||||
{
|
||||
var newName = baseShaderName + (isTransparent ? "-Transparent" : "") + (isDoubleSided ? "-Double" : "");
|
||||
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set Material Options");
|
||||
targetMaterial.shader = AssetDatabase.LoadAssetAtPath<Shader>(AssetDatabase.GUIDToAssetPath(ShaderNameToGuid[newName]));
|
||||
var currentCutoff = targetMaterial.GetFloat("alphaCutoff");
|
||||
if (!isCutout && currentCutoff == 0) currentCutoff = -0.0001f; // Hack to ensure we can actually switch states here
|
||||
targetMaterial.SetFloat("alphaCutoff", Mathf.Abs(currentCutoff) * (isCutout ? 1 : -1));
|
||||
}
|
||||
|
||||
var newT = EditorGUILayout.Toggle("Transparent", isTransparent);
|
||||
if (newT != isTransparent)
|
||||
{
|
||||
isTransparent = newT;
|
||||
SetShader();
|
||||
}
|
||||
var newD = EditorGUILayout.Toggle("Double Sided", isDoubleSided);
|
||||
if (newD != isDoubleSided)
|
||||
{
|
||||
isDoubleSided = newD;
|
||||
SetShader();
|
||||
}
|
||||
var newA = EditorGUILayout.Toggle("Cutout", isCutout);
|
||||
if (newA != isCutout)
|
||||
{
|
||||
isCutout = newA;
|
||||
SetShader();
|
||||
}
|
||||
|
||||
EditorGUILayout.Space();
|
||||
}
|
||||
#endif
|
||||
|
||||
private void DrawGameObjectInfo(Material targetMaterial)
|
||||
{
|
||||
var singleSelection = Selection.objects != null && Selection.objects.Length < 2;
|
||||
|
||||
// Strict Mode
|
||||
// - texture transforms only for baseColorTexture, is used for all others as well
|
||||
// - occlusion MUST use UV2 if present
|
||||
var renderer = ShaderGraphHelpers.GetRendererForMaterialEditor(materialEditor);
|
||||
var haveDrawnSomething = false;
|
||||
|
||||
if (renderer && !singleSelection)
|
||||
{
|
||||
EditorGUI.BeginDisabledGroup(true);
|
||||
EditorGUI.showMixedValue = true;
|
||||
EditorGUILayout.ObjectField("Target Mesh", null, typeof(Mesh), true);
|
||||
EditorGUI.showMixedValue = false;
|
||||
EditorGUI.EndDisabledGroup();
|
||||
EditorGUILayout.HelpBox("Multiple objects selected. Can't show mesh properties.", MessageType.Info);
|
||||
haveDrawnSomething = true;
|
||||
}
|
||||
|
||||
currentMaterialInfo.hasColor = true;
|
||||
currentMaterialInfo.hasUV0 = true;
|
||||
currentMaterialInfo.hasUV1 = true;
|
||||
currentMaterialInfo.occlusionTextureTexCoord = targetMaterial.HasProperty("occlusionTextureTexCoord") ? Mathf.RoundToInt(targetMaterial.GetFloat("occlusionTextureTexCoord")) : 0;
|
||||
currentMaterialInfo.baseColorTextureTexCoord = targetMaterial.HasProperty("baseColorTextureTexCoord") ? Mathf.RoundToInt(targetMaterial.GetFloat("baseColorTextureTexCoord")) : 0;
|
||||
|
||||
if (renderer && singleSelection)
|
||||
{
|
||||
var mesh = default(Mesh);
|
||||
if (renderer is SkinnedMeshRenderer smr)
|
||||
mesh = smr.sharedMesh;
|
||||
else if (renderer is MeshRenderer mr && mr.GetComponent<MeshFilter>())
|
||||
mesh = mr.GetComponent<MeshFilter>()?.sharedMesh;
|
||||
|
||||
if (mesh)
|
||||
{
|
||||
currentMaterialInfo.hasColor = mesh.HasVertexAttribute(VertexAttribute.Color);
|
||||
currentMaterialInfo.hasUV0 = mesh.HasVertexAttribute(VertexAttribute.TexCoord0);
|
||||
currentMaterialInfo.hasUV1 = mesh.HasVertexAttribute(VertexAttribute.TexCoord1);
|
||||
|
||||
EditorGUI.BeginDisabledGroup(true);
|
||||
EditorGUILayout.ObjectField("Target Mesh", mesh, typeof(Mesh), true);
|
||||
EditorGUILayout.Toggle("Has Vertex Colors", currentMaterialInfo.hasColor);
|
||||
EditorGUI.EndDisabledGroup();
|
||||
|
||||
if (currentMaterialInfo.hasColor != targetMaterial.IsKeywordEnabled("_VERTEX_COLORS_ON"))
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
var msg = "";
|
||||
var msgType = MessageType.Info;
|
||||
if (currentMaterialInfo.hasColor)
|
||||
{
|
||||
msg = "Mesh has vertex colors but \"Enable Vertex Colors\" is off. Exported glTF files will look different since vertex color is stored per-mesh, not per-material.";
|
||||
msgType = MessageType.Warning;
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// // doesn't really make sense to encourage turning vertex colors OFF - export will have them anyways.
|
||||
// EditorGUILayout.HelpBox("Mesh has no vertex colors but \"Enable Vertex Colors\" is on.", MessageType.Info);
|
||||
// }
|
||||
|
||||
if (!string.IsNullOrEmpty(msg))
|
||||
{
|
||||
DrawFixMeBox(msg, msgType, () =>
|
||||
{
|
||||
if (currentMaterialInfo.hasColor)
|
||||
{
|
||||
targetMaterial.EnableKeyword("_VERTEX_COLORS_ON");
|
||||
targetMaterial.SetFloat("_VERTEX_COLORS", 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
targetMaterial.DisableKeyword("_VERTEX_COLORS_ON");
|
||||
targetMaterial.SetFloat("_VERTEX_COLORS", 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
|
||||
EditorGUI.BeginDisabledGroup(true);
|
||||
EditorGUILayout.Toggle("Has UV0", currentMaterialInfo.hasUV0);
|
||||
EditorGUILayout.Toggle("Has UV1", currentMaterialInfo.hasUV1);
|
||||
EditorGUI.EndDisabledGroup();
|
||||
|
||||
if (!currentMaterialInfo.hasUV0 && HasAnyTextureAssigned(targetMaterial))
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
EditorGUILayout.HelpBox("This mesh has no UV coordinates but has textures assigned.", MessageType.Warning);
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
|
||||
if (currentMaterialInfo.hasUV1 && targetMaterial.HasProperty("occlusionTexture") && targetMaterial.GetTexture("occlusionTexture"))
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
var texCoord = Mathf.RoundToInt(targetMaterial.GetFloat("occlusionTextureTexCoord"));
|
||||
if (texCoord != 1)
|
||||
{
|
||||
DrawFixMeBox("This mesh has an Occlusion Texture and UV1 vertex data.\nWhen exporting to three.js, UV1 will be used independent of TexCoord setting.", MessageType.Warning, () =>
|
||||
{
|
||||
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set occlusionTextureTexCoord to 1");
|
||||
targetMaterial.SetFloat("occlusionTextureTexCoord", 1);
|
||||
});
|
||||
}
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
|
||||
if (!currentMaterialInfo.hasUV1)
|
||||
{
|
||||
if (currentMaterialInfo.baseColorTextureTexCoord > 0)
|
||||
{
|
||||
DrawFixMeBox("This mesh does not have UV1 vertex data but Base Texture is set to use UV1. This will lead to unexpected results.", MessageType.Warning, () =>
|
||||
{
|
||||
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set baseColorTextureTexCoord to 0");
|
||||
targetMaterial.SetFloat("baseColorTextureTexCoord", 0);
|
||||
});
|
||||
}
|
||||
if (currentMaterialInfo.occlusionTextureTexCoord > 0)
|
||||
{
|
||||
DrawFixMeBox("This mesh does not have UV1 vertex data but Occlusion Texture is set to use UV1. This will lead to unexpected results.", MessageType.Warning, () =>
|
||||
{
|
||||
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set occlusionTextureTexCoord to 0");
|
||||
targetMaterial.SetFloat("occlusionTextureTexCoord", 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// check if this uses transmission
|
||||
// TODO we need to expose some kind of interface so that other scripts (e.g. the rough refraction components)
|
||||
// can attach to this inspector here.
|
||||
/*
|
||||
if (targetMaterial.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
|
||||
{
|
||||
// requires extra setup for BiRP / URP to render properly
|
||||
if (!GraphicsSettings.currentRenderPipeline && !Camera.main.gameObject.GetComponent<RoughRefraction>())
|
||||
{
|
||||
// warn
|
||||
}
|
||||
else
|
||||
{
|
||||
// check if assigned renderer has the rough refraction feature, offer to add it otherwise
|
||||
Camera.main.gameObject.GetComponent<UniversalAdditionalCameraData>()
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
haveDrawnSomething = true;
|
||||
}
|
||||
|
||||
if (targetMaterial.HasProperty("_Surface") && targetMaterial.GetFloat("_Surface") == 0 &&
|
||||
targetMaterial.renderQueue <= (int) RenderQueue.AlphaTest + 50 &&
|
||||
!Mathf.Approximately(targetMaterial.GetColor("baseColorFactor").a, 1))
|
||||
{
|
||||
DrawFixMeBox("Material is opaque but baseColorFactor has an alpha value != 1. This object might render unexpectedly in some viewers that blend results (e.g. AR, Babylon, Stager).", MessageType.Warning, () =>
|
||||
{
|
||||
Undo.RegisterCompleteObjectUndo(materialEditor.targets, "Set baseColorFactor.a to 1");
|
||||
foreach (var t in materialEditor.targets)
|
||||
{
|
||||
var mat = (Material)t;
|
||||
var color = mat.GetColor("baseColorFactor");
|
||||
color.a = 1;
|
||||
mat.SetColor("baseColorFactor", color);
|
||||
EditorUtility.SetDirty(mat);
|
||||
}
|
||||
});
|
||||
haveDrawnSomething = true;
|
||||
}
|
||||
|
||||
if (!renderer && !haveDrawnSomething)
|
||||
{
|
||||
EditorGUILayout.HelpBox("Select a Renderer to see additional info", MessageType.None);
|
||||
}
|
||||
}
|
||||
|
||||
private static void DrawFixMeBox(string msg, MessageType msgType, Action action)
|
||||
{
|
||||
#if HAVE_BUILTIN_SHADERGRAPH && false
|
||||
CoreEditorUtils.DrawFixMeBox(msg, msgType, action);
|
||||
#else
|
||||
EditorGUILayout.HelpBox(msg, msgType);
|
||||
if (action != null && GUILayout.Button("Fix")) action();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if HAVE_CATEGORIES
|
||||
protected override void DrawSurfaceInputs(Material mat) => _DrawSurfaceInputs(mat);
|
||||
#endif
|
||||
protected void _DrawSurfaceInputs(Material mat)
|
||||
{
|
||||
var targetMaterial = materialEditor.target as Material;
|
||||
if (!targetMaterial) return;
|
||||
|
||||
|
||||
materialEditor.SetDefaultGUIWidths();
|
||||
|
||||
EditorGUI.BeginChangeCheck();
|
||||
|
||||
DrawProperties(targetMaterial, properties);
|
||||
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
foreach (var t in materialEditor.targets)
|
||||
{
|
||||
if (t is Material material)
|
||||
GLTFMaterialHelper.ValidateMaterialKeywords(material);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasPropertyButNoTex(Material targetMaterial, string name)
|
||||
{
|
||||
return targetMaterial.HasProperty(name) &&
|
||||
#if UNITY_2021_2_OR_NEWER
|
||||
targetMaterial.HasTexture(name) &&
|
||||
#endif
|
||||
!targetMaterial.GetTexture(name);
|
||||
}
|
||||
|
||||
private void DrawProperties(Material targetMaterial, MaterialProperty[] properties)
|
||||
{
|
||||
// filter properties based on keywords
|
||||
var propertyList = properties.ToList();
|
||||
if (!targetMaterial.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.EndsWith("_ST", StringComparison.Ordinal) || x.name.EndsWith("Rotation", StringComparison.Ordinal));
|
||||
}
|
||||
// want to remove the _ST properties since they are drawn inline already on 2021.2+
|
||||
#if UNITY_2021_2_OR_NEWER
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.EndsWith("_ST", StringComparison.Ordinal));
|
||||
}
|
||||
#endif
|
||||
if (!targetMaterial.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("transmission", StringComparison.Ordinal));
|
||||
}
|
||||
if (!targetMaterial.HasProperty("_VOLUME_ON") || !(targetMaterial.GetFloat("_VOLUME_ON") > 0.5f))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("thickness", StringComparison.Ordinal) || x.name.StartsWith("attenuation", StringComparison.Ordinal));
|
||||
}
|
||||
if (!targetMaterial.IsKeywordEnabled("_IRIDESCENCE_ON"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("iridescence", StringComparison.Ordinal));
|
||||
}
|
||||
if (!targetMaterial.IsKeywordEnabled("_SPECULAR_ON"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("specular", StringComparison.Ordinal));
|
||||
}
|
||||
if (!targetMaterial.IsKeywordEnabled("_CLEARCOAT_ON"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("clearcoat", StringComparison.Ordinal));
|
||||
}
|
||||
if (HasPropertyButNoTex(targetMaterial, "occlusionTexture"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name == "occlusionStrength" || (x.name.StartsWith("occlusionTexture", StringComparison.Ordinal) && x.name != "occlusionTexture"));
|
||||
}
|
||||
// remove UV-related properties
|
||||
if (HasPropertyButNoTex(targetMaterial, "baseColorTexture") && HasPropertyButNoTex(targetMaterial,"metallicRoughnessTexture") && HasPropertyButNoTex(targetMaterial,"normalTexture") && HasPropertyButNoTex(targetMaterial,"emissiveTexture"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.StartsWith("baseColorTexture", StringComparison.Ordinal) && x.name != "baseColorTexture");
|
||||
}
|
||||
if (HasPropertyButNoTex(targetMaterial,"normalTexture"))
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name == "normalScale");
|
||||
}
|
||||
if (!currentMaterialInfo.hasUV0 && !currentMaterialInfo.hasUV1)
|
||||
{
|
||||
// hide all texture properties if no UVs
|
||||
propertyList.RemoveAll(x => x.name.Contains("texture"));
|
||||
}
|
||||
if (!currentMaterialInfo.hasUV1 && currentMaterialInfo.occlusionTextureTexCoord == 0 && currentMaterialInfo.baseColorTextureTexCoord == 0)
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name.EndsWith("TextureTexCoord", StringComparison.Ordinal));
|
||||
}
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
var isBirp = !GraphicsSettings.currentRenderPipeline;
|
||||
if ((isBirp && !targetMaterial.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON")) ||
|
||||
(!isBirp && !targetMaterial.IsKeywordEnabled("_ALPHATEST_ON")))
|
||||
#else
|
||||
if (targetMaterial.GetFloat("alphaCutoff") < 0)
|
||||
#endif
|
||||
{
|
||||
propertyList.RemoveAll(x => x.name == "alphaCutoff");
|
||||
}
|
||||
// TODO we probably want full manual control, all this internal access is horrible...
|
||||
// E.g. impossible to render inline texture properties...
|
||||
ShaderGraphHelpers.DrawShaderGraphGUI(materialEditor, propertyList);
|
||||
}
|
||||
|
||||
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
GLTFMaterialHelper.ConvertMaterialToGLTF(material, oldShader, newShader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7fd38ac84daf5a14180dde4bc5949e25
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
#if UNITY_2021_3_OR_NEWER
|
||||
#define HAVE_CATEGORIES
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
#if HAVE_CATEGORIES
|
||||
using UnityEditor.ShaderGraph.Drawing;
|
||||
#endif
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class ShaderGraphHelpers
|
||||
{
|
||||
public static void DrawShaderGraphGUI(MaterialEditor materialEditor, IEnumerable<MaterialProperty> properties)
|
||||
{
|
||||
#if HAVE_CATEGORIES
|
||||
ShaderGraphPropertyDrawers.DrawShaderGraphGUI(materialEditor, properties);
|
||||
#else
|
||||
materialEditor.PropertiesDefaultGUI(properties.ToArray());
|
||||
#endif
|
||||
}
|
||||
|
||||
private static Type propertyView;
|
||||
private static PropertyInfo propertyViewer;
|
||||
private static PropertyInfo tracker;
|
||||
|
||||
// matches logic in MaterialEditor.ShouldEditorBeHidden to find the right renderer this material is inspected on.
|
||||
public static Renderer GetRendererForMaterialEditor(MaterialEditor materialEditor)
|
||||
{
|
||||
if (propertyViewer == null) propertyViewer = typeof(Editor).GetProperty(nameof(propertyViewer), BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
if (propertyView == null) propertyView = typeof(Editor).Assembly.GetType("UnityEditor.IPropertyView");
|
||||
if (tracker == null) tracker = propertyView?.GetProperty("tracker", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
|
||||
|
||||
var iPropertyViewer = propertyViewer?.GetValue(materialEditor) as Object;
|
||||
if (!iPropertyViewer) return null;
|
||||
|
||||
var editorTracker = tracker?.GetValue(iPropertyViewer) as ActiveEditorTracker;
|
||||
if (editorTracker == null) return null;
|
||||
|
||||
GameObject target = editorTracker.activeEditors[0].target as GameObject;
|
||||
if (!target) return null;
|
||||
Renderer c = target.GetComponent<MeshRenderer>();
|
||||
if (!c) c = target.GetComponent<SkinnedMeshRenderer>();
|
||||
return c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0a60cd145bbb31542ab7932da93de3f3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#if !NO_INTERNALS_ACCESS && UNITY_2020_1_OR_NEWER
|
||||
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEditor.ShaderGraph;
|
||||
using UnityEngine;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[ScriptedImporter(0, ".override-graph", -500)]
|
||||
internal class ShaderGraphOverrideImporter : ShaderGraphImporter, IUnityGltfShaderUpgradeMeta
|
||||
{
|
||||
[HideInInspector]
|
||||
public Shader sourceShader;
|
||||
|
||||
[HideInInspector]
|
||||
public Shader upgradeShader;
|
||||
|
||||
public bool forceTransparent = true;
|
||||
public bool forceDoublesided = false;
|
||||
public bool hideShader = true;
|
||||
|
||||
public Shader SourceShader => sourceShader;
|
||||
public bool IsTransparent => forceTransparent;
|
||||
public bool IsDoublesided => forceDoublesided;
|
||||
public bool IsUnlit => sourceShader.name.Contains("Unlit");
|
||||
|
||||
public override void OnImportAsset(AssetImportContext ctx)
|
||||
{
|
||||
if (!sourceShader)
|
||||
return;
|
||||
|
||||
#if UNITY_2021_1_OR_NEWER && false
|
||||
// we don't need extra shaders on 2021.1+,
|
||||
// as Shader Graph allows overriding the material properties there.
|
||||
// but we do want to allow upgrading the materials, so we need to import something and allow upgrading through ShaderGraphUpdater
|
||||
|
||||
var meta = ScriptableObject.CreateInstance<UnityGltfShaderUpgradeMeta>();
|
||||
meta.name = "Shader Upgrade Meta";
|
||||
meta.hideFlags = HideFlags.HideInInspector;
|
||||
meta.sourceShader = sourceShader;
|
||||
meta.isTransparent = forceTransparent;
|
||||
meta.isDoublesided = forceDoublesided;
|
||||
|
||||
const string shaderName = "Hidden/UnityGltf/UpgradeShader";
|
||||
var shaderText = File.ReadAllText(AssetDatabase.GetAssetPath(upgradeShader))
|
||||
.Replace(shaderName, shaderName + meta.GenerateNameString());
|
||||
var shader = ShaderUtil.CreateShaderAsset(ctx, shaderText, true);
|
||||
ctx.AddObjectToAsset("MainAsset", shader);
|
||||
ctx.AddObjectToAsset("UpgradeMeta", meta);
|
||||
ctx.SetMainObject(shader);
|
||||
#else
|
||||
// cache write time, we want to reset the file again afterwards
|
||||
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(ctx.assetPath);
|
||||
|
||||
var path = AssetDatabase.GetAssetPath(sourceShader);
|
||||
ctx.DependsOnArtifact(AssetDatabase.GUIDFromAssetPath(path));
|
||||
var graphData = File.ReadAllText(path);
|
||||
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
// disable material overrides on 2021.1+ - we want people to use the proper shader for that
|
||||
graphData = graphData.Replace("\"m_AllowMaterialOverride\": true", "\"m_AllowMaterialOverride\": false");
|
||||
#endif
|
||||
|
||||
// modify:
|
||||
// switch to transparent
|
||||
if (forceTransparent)
|
||||
graphData = graphData.Replace("\"m_SurfaceType\": 0", "\"m_SurfaceType\": 1");
|
||||
|
||||
// for 2021+
|
||||
// if (forceDoublesided)
|
||||
// graphData = graphData
|
||||
// .Replace("\"m_RenderFace\": 2", "\"m_RenderFace\": 0")
|
||||
// .Replace("\"m_RenderFace\": 1", "\"m_RenderFace\": 0");
|
||||
|
||||
// for 2020+
|
||||
if (forceDoublesided && !graphData.Contains("m_TwoSided"))
|
||||
graphData = graphData
|
||||
.Replace("\"m_SurfaceType\": 0", "\"m_SurfaceType\": 0" + ",\n" + "\"m_TwoSided\": true")
|
||||
.Replace("\"m_SurfaceType\": 1", "\"m_SurfaceType\": 1" + ",\n" + "\"m_TwoSided\": true");
|
||||
|
||||
if (hideShader)
|
||||
graphData = graphData.Replace("\"m_Path\": \"", "\"m_Path\": \"Hidden/");
|
||||
|
||||
File.WriteAllText(ctx.assetPath, graphData);
|
||||
|
||||
// run import on the modified shader
|
||||
base.OnImportAsset(ctx);
|
||||
|
||||
// clean the file on disk again
|
||||
File.WriteAllText(ctx.assetPath, "");
|
||||
|
||||
// reset write time to what it was before - avoids AssetDB reload
|
||||
File.SetLastWriteTimeUtc(ctx.assetPath, lastWriteTimeUtc);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fe431e399c52971408121c6c40cde979
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#if !NO_INTERNALS_ACCESS && UNITY_2020_1_OR_NEWER
|
||||
|
||||
using UnityEditor;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[CustomEditor(typeof(ShaderGraphOverrideImporter))]
|
||||
class ShaderGraphOverrideImporterEditor : ScriptedImporterEditor
|
||||
{
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
EditorGUILayout.HelpBox("Deprecated. Use material overrides on UnityGLTF/PBRGraph and UnityGLTF/UnlitGraph instead of separate shaders.", MessageType.Warning);
|
||||
#endif
|
||||
DrawDefaultInspector();
|
||||
ApplyRevertGUI();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 511b21f4c3344c54689aed102b11724a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:be0903cd8e1546f498710afdc59db5eb"
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d60ff41bbebf9024dac1e4f0dc004a57
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f369a0c649cfa54799cb62645da047f
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
#if UNITY_2021_3_OR_NEWER
|
||||
#define HAVE_CATEGORIES
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
// matches ShaderGraphLitGUI.cs
|
||||
public class PBRGraphUniversalGUI : PBRGraphGUI
|
||||
{
|
||||
#if HAVE_CATEGORIES
|
||||
private PropertyInfo materialEditorPropertyAccessor;
|
||||
private ShaderGraphLitGUI litGuiForwarder;
|
||||
|
||||
public override void ValidateMaterial(Material material)
|
||||
{
|
||||
if (material == null) throw new ArgumentNullException(nameof(material));
|
||||
|
||||
base.ValidateMaterial(material);
|
||||
|
||||
var automaticRenderQueue = GetAutomaticQueueControlSetting(material);
|
||||
BaseShaderGUI.UpdateMaterialSurfaceOptions(material, automaticRenderQueue);
|
||||
}
|
||||
|
||||
protected override void DrawSurfaceOptions(Material material)
|
||||
{
|
||||
if (material == null) throw new ArgumentNullException(nameof(material));
|
||||
|
||||
// Use default labelWidth
|
||||
EditorGUIUtility.labelWidth = 0f;
|
||||
|
||||
if (litGuiForwarder == null) litGuiForwarder = new ShaderGraphLitGUI();
|
||||
if (materialEditorPropertyAccessor == null) materialEditorPropertyAccessor = typeof(BaseShaderGUI).GetProperty("materialEditor", (BindingFlags) (-1));
|
||||
if (materialEditorPropertyAccessor != null) materialEditorPropertyAccessor.SetValue(litGuiForwarder, materialEditor); // forwarder.materialEditor = materialEditor;
|
||||
|
||||
litGuiForwarder.FindProperties(properties);
|
||||
litGuiForwarder.workflowMode = null;
|
||||
litGuiForwarder.DrawSurfaceOptions(material);
|
||||
}
|
||||
|
||||
protected override void DrawAdvancedOptions(Material material)
|
||||
{
|
||||
base.DrawAdvancedOptions(material);
|
||||
|
||||
materialEditor.DoubleSidedGIField();
|
||||
materialEditor.LightmapEmissionFlagsProperty(0, enabled: true, ignoreEmissionColor: true);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 86a2b51891c425a468a0a4d61f8b2a6a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:c579267770062bf448e75eb160330b7f"
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cd3b604407efbd641a4d40520de58a76
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1 @@
|
||||
internal class NoCompilationWarning { }
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4ea8663e2a74bdc4cb6f6d53769532df
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,240 @@
|
||||
using System.Linq;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class ShaderConverters
|
||||
{
|
||||
[InitializeOnLoadMethod]
|
||||
static void InitShaderConverters()
|
||||
{
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertStandardAndURPLit);
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertUnityGLTFGraphs);
|
||||
}
|
||||
|
||||
private static bool ConvertUnityGLTFGraphs(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
// update legacy shaders that didn't have material overrides available
|
||||
if (oldShader.name.StartsWith("Hidden/UnityGLTF/PBRGraph") || oldShader.name.StartsWith("Hidden/UnityGLTF/UnlitGraph"))
|
||||
{
|
||||
material.shader = newShader;
|
||||
|
||||
var meta = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(material.shader)) as IUnityGltfShaderUpgradeMeta;
|
||||
if (meta != null)
|
||||
{
|
||||
// Debug.Log("Updating shader from " + material.shader + " to " + meta.SourceShader +
|
||||
// " (transparent: " + meta.IsTransparent + ", double sided: " + meta.IsDoublesided + ")");
|
||||
|
||||
var isUnlit = meta.SourceShader.name.Contains("Unlit");
|
||||
material.shader = meta.SourceShader;
|
||||
|
||||
var mapper = isUnlit ? (IUniformMap) new UnlitMap(material) : new PBRGraphMap(material);
|
||||
if (meta.IsTransparent)
|
||||
mapper.AlphaMode = AlphaMode.BLEND;
|
||||
if (meta.IsDoublesided)
|
||||
mapper.DoubleSided = true;
|
||||
|
||||
EditorUtility.SetDirty(material);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (oldShader.name != "UnityGLTF/UnlitGraph" && oldShader.name != "UnityGLTF/PBRGraph") return false;
|
||||
|
||||
material.shader = newShader;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool ConvertStandardAndURPLit(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
// Conversion time!
|
||||
// convert from
|
||||
// - "Standard"
|
||||
// - "URP/Lit"
|
||||
|
||||
if (oldShader.name != StandardShader && oldShader.name != URPLitShader) return false;
|
||||
|
||||
var isStandard = oldShader.name == StandardShader;
|
||||
var needsEmissiveColorSpaceConversion = isStandard && QualitySettings.activeColorSpace == ColorSpace.Linear;
|
||||
var colorProp = oldShader.name == StandardShader ? _Color : _BaseColor;
|
||||
var colorTexProp = oldShader.name == StandardShader ? _MainTex : _BaseMap;
|
||||
|
||||
var color = material.GetColor(colorProp);
|
||||
var albedo = material.GetTexture(colorTexProp);
|
||||
var albedoOffset = material.GetTextureOffset(colorTexProp);
|
||||
var albedoTiling = material.GetTextureScale(colorTexProp);
|
||||
|
||||
var metallic = material.GetFloat(_Metallic);
|
||||
var smoothness = material.HasProperty(_Smoothness) ? material.GetFloat(_Smoothness) : material.GetFloat(_Glossiness);
|
||||
var metallicGloss = material.GetTexture(_MetallicGlossMap);
|
||||
var normal = material.GetTexture(_BumpMap);
|
||||
var normalStrength = material.GetFloat(_BumpScale);
|
||||
var occlusion = material.GetTexture(_OcclusionMap);
|
||||
var occlusionStrength = material.GetFloat(_Strength);
|
||||
var emission = material.GetTexture(_EmissionMap);
|
||||
var emissionColor = material.GetColor(_EmissionColor);
|
||||
var cutoff = material.GetFloat(_Cutoff);
|
||||
|
||||
var isCutoff = material.IsKeywordEnabled("_ALPHATEST_ON") || material.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON");
|
||||
|
||||
material.shader = newShader;
|
||||
|
||||
material.SetColor(baseColorFactor, color);
|
||||
material.SetTexture(baseColorTexture, albedo);
|
||||
material.SetTextureOffset(baseColorTexture, albedoOffset);
|
||||
material.SetTextureScale(baseColorTexture, albedoTiling);
|
||||
if (albedoOffset != Vector2.zero || albedoTiling != Vector2.one)
|
||||
GLTFMaterialHelper.SetKeyword(material, "_TEXTURE_TRANSFORM", true);
|
||||
|
||||
material.SetFloat(metallicFactor, metallic);
|
||||
material.SetFloat(roughnessFactor, 1 - smoothness);
|
||||
const string ConversionWarning = "The Metallic (R) Smoothness (A) texture needs to be converted to Roughness (B) Metallic (G). ";
|
||||
#if UNITY_EDITOR && UNITY_2022_1_OR_NEWER
|
||||
var importerPath = AssetDatabase.GetAssetPath(metallicGloss);
|
||||
var importer = AssetImporter.GetAtPath(importerPath) as TextureImporter;
|
||||
if (importer && importer.swizzleG != TextureImporterSwizzle.OneMinusR) // can't really detect if this has been done on the texture already, this is just a heuristic...
|
||||
{
|
||||
if (EditorUtility.DisplayDialog("Texture Conversion",
|
||||
ConversionWarning + "This is done by swizzling texture channels in the importer. Do you want to proceed?",
|
||||
"OK", DialogOptOutDecisionType.ForThisSession, nameof(GLTFMaterialHelper) + "_texture_conversion"))
|
||||
{
|
||||
importer.swizzleR = TextureImporterSwizzle.B;
|
||||
importer.swizzleG = TextureImporterSwizzle.OneMinusR;
|
||||
importer.swizzleB = TextureImporterSwizzle.G;
|
||||
Undo.RegisterImporterUndo(importerPath, "Texture Swizzles (M__G > _RM_)");
|
||||
importer.SaveAndReimport();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning(ConversionWarning + "This currently needs to be done manually. Please swap channels in an external software.", material);
|
||||
}
|
||||
#else
|
||||
if (metallicGloss)
|
||||
Debug.LogWarning(ConversionWarning + "This currently needs to be done manually. Please swap channels in an external software.", material);
|
||||
#endif
|
||||
// TODO: convert metallicGloss to metallicRoughnessTexture format: Metallic (R) + Smoothness (A) → Roughness (G) + Metallic (B)
|
||||
// TODO: when smoothness is not 0 or 1 and there's a texture, need to convert to a texture and set roughness = 1, otherwise the math doesn't match
|
||||
// TODO: figure out where to put the newly created texture, and how to avoid re-creating it several times when multiple materials may use it.
|
||||
material.SetTexture(metallicRoughnessTexture, metallicGloss);
|
||||
material.SetTexture(normalTexture, normal);
|
||||
material.SetFloat(normalScale, normalStrength);
|
||||
material.SetTexture(occlusionTexture, occlusion);
|
||||
material.SetFloat(occlusionStrength1, occlusionStrength);
|
||||
material.SetTexture(emissiveTexture, emission);
|
||||
material.SetFloat(alphaCutoff, cutoff);
|
||||
if (isCutoff)
|
||||
{
|
||||
GLTFMaterialHelper.SetKeyword(material, "_ALPHATEST", true);
|
||||
GLTFMaterialHelper.SetKeyword(material, "_BUILTIN_ALPHATEST", true);
|
||||
material.EnableKeyword("_BUILTIN_AlphaClip");
|
||||
}
|
||||
|
||||
material.SetColor(emissiveFactor, needsEmissiveColorSpaceConversion ? emissionColor.linear : emissionColor);
|
||||
|
||||
// set the flags on conversion, otherwise it's confusing why they're not on - can't easily replicate the magic that Unity does in their inspectors when changing emissive on/off
|
||||
if (material.globalIlluminationFlags == MaterialGlobalIlluminationFlags.None || material.globalIlluminationFlags == MaterialGlobalIlluminationFlags.EmissiveIsBlack)
|
||||
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
|
||||
|
||||
// ensure keywords are correctly set after conversion
|
||||
GLTFMaterialHelper.ValidateMaterialKeywords(material);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
private const string StandardShader = "Standard";
|
||||
private const string URPLitShader = "Universal Render Pipeline/Lit";
|
||||
|
||||
// Standard and URP-Lit property names
|
||||
private static readonly int _Color = Shader.PropertyToID("_Color");
|
||||
private static readonly int _BaseColor = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int _MainTex = Shader.PropertyToID("_MainTex");
|
||||
private static readonly int _BaseMap = Shader.PropertyToID("_BaseMap");
|
||||
private static readonly int _Metallic = Shader.PropertyToID("_Metallic");
|
||||
private static readonly int _Glossiness = Shader.PropertyToID("_Glossiness");
|
||||
private static readonly int _Smoothness = Shader.PropertyToID("_Smoothness");
|
||||
private static readonly int _MetallicGlossMap = Shader.PropertyToID("_MetallicGlossMap");
|
||||
private static readonly int _BumpMap = Shader.PropertyToID("_BumpMap");
|
||||
private static readonly int _BumpScale = Shader.PropertyToID("_BumpScale");
|
||||
private static readonly int _OcclusionMap = Shader.PropertyToID("_OcclusionMap");
|
||||
private static readonly int _Strength = Shader.PropertyToID("_OcclusionStrength");
|
||||
private static readonly int _EmissionMap = Shader.PropertyToID("_EmissionMap");
|
||||
private static readonly int _EmissionColor = Shader.PropertyToID("_EmissionColor");
|
||||
private static readonly int _Cutoff = Shader.PropertyToID("_Cutoff");
|
||||
|
||||
// glTF property names
|
||||
private static readonly int baseColorFactor = Shader.PropertyToID("baseColorFactor");
|
||||
private static readonly int baseColorTexture = Shader.PropertyToID("baseColorTexture");
|
||||
private static readonly int metallicFactor = Shader.PropertyToID("metallicFactor");
|
||||
private static readonly int roughnessFactor = Shader.PropertyToID("roughnessFactor");
|
||||
private static readonly int metallicRoughnessTexture = Shader.PropertyToID("metallicRoughnessTexture");
|
||||
private static readonly int normalTexture = Shader.PropertyToID("normalTexture");
|
||||
private static readonly int normalScale = Shader.PropertyToID("normalScale");
|
||||
private static readonly int occlusionTexture = Shader.PropertyToID("occlusionTexture");
|
||||
private static readonly int occlusionStrength1 = Shader.PropertyToID("occlusionStrength");
|
||||
private static readonly int emissiveTexture = Shader.PropertyToID("emissiveTexture");
|
||||
private static readonly int emissiveFactor = Shader.PropertyToID("emissiveFactor");
|
||||
private static readonly int alphaCutoff = Shader.PropertyToID("alphaCutoff");
|
||||
// ReSharper restore InconsistentNaming
|
||||
|
||||
private static readonly string[] emissivePropNames = new[] { "emissiveFactor", "_EmissionColor" };
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/Convert Emissive Colors > sRGB - weaker, darker")]
|
||||
private static void ConvertToSRGB(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
Undo.RegisterCompleteObjectUndo(mat, "Convert emissive colors to sRGB");
|
||||
foreach(var propName in emissivePropNames)
|
||||
if (mat.HasProperty(propName)) mat.SetColor(propName, mat.GetColor(propName).gamma);
|
||||
}
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/Convert Emissive Colors > Linear - brighter, stronger")]
|
||||
private static void ConvertToLinear(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
Undo.RegisterCompleteObjectUndo(mat, "Convert emissive colors to sRGB");
|
||||
foreach(var propName in emissivePropNames)
|
||||
if (mat.HasProperty(propName)) mat.SetColor(propName, mat.GetColor(propName).linear);
|
||||
}
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/ Select all materials with this shader", false, -1000)]
|
||||
private static void SelectAllMaterialsWithShader(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
var allMaterials = AssetDatabase.FindAssets("t:Material")
|
||||
.Select(AssetDatabase.GUIDToAssetPath)
|
||||
.Select(AssetDatabase.LoadAssetAtPath<Material>)
|
||||
.Where(x => !AssetDatabase.IsSubAsset(x))
|
||||
.Where(x => x.shader == mat.shader)
|
||||
.Cast<Object>()
|
||||
.ToArray();
|
||||
foreach (var obj in allMaterials)
|
||||
EditorGUIUtility.PingObject(obj);
|
||||
Selection.objects = allMaterials;
|
||||
}
|
||||
|
||||
private static bool TryGetMetadataOfType<T>(Shader shader, out T obj) where T : ScriptableObject
|
||||
{
|
||||
obj = null;
|
||||
|
||||
var path = AssetDatabase.GetAssetPath(shader);
|
||||
foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
|
||||
{
|
||||
if (asset is T metadataAsset)
|
||||
{
|
||||
obj = metadataAsset;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77ad4bb761964b0da3ccf68f6b649aab
|
||||
timeCreated: 1677764644
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "UnityGLTF.ShaderGraph",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:be0903cd8e1546f498710afdc59db5eb",
|
||||
"GUID:18d18f811ba286c49814567a3cfba688",
|
||||
"GUID:40f39bff7bc9be34182ebe488fcf8228"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [
|
||||
"UNITY_2019_4_OR_NEWER"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.unity.modules.imageconversion",
|
||||
"expression": "0.0.0",
|
||||
"define": "NO_INTERNALS_ACCESS"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 17181a83a8717a34d8ce050af64edd83
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "UnityGLTFEditor",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GLTFSerialization",
|
||||
"UnityGLTFScripts"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [
|
||||
"GLTFSerialization.dll"
|
||||
],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.unity.modules.animation",
|
||||
"expression": "1.0.0",
|
||||
"define": "UNITY_ANIMATION"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.modules.imgui",
|
||||
"expression": "1.0.0",
|
||||
"define": "UNITY_IMGUI"
|
||||
},
|
||||
{
|
||||
"name": "com.atteneder.gltfast",
|
||||
"expression": "3.0.0",
|
||||
"define": "HAVE_GLTFAST"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1a0324566af4ed544918d6837a1f4e11
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d28d76b6765ee2849a9c1dcf3811d183
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 107a7c058d7ad7c43b3656c44c5364b8
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6cf51abc0e087ca4d8fc223141dd9c09
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,3 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("UnityGLTFScripts")]
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 42d7be7539b58434e88dbb233beed600
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,17 @@
|
||||
using GLTF.Schema;
|
||||
|
||||
namespace GLTF
|
||||
{
|
||||
public class AttributeAccessor
|
||||
{
|
||||
public AccessorId AccessorId { get; set; }
|
||||
public NumericArray AccessorContent { get; set; }
|
||||
public System.IO.Stream Stream { get; set; }
|
||||
public uint Offset { get; set; }
|
||||
|
||||
public AttributeAccessor()
|
||||
{
|
||||
AccessorContent = new NumericArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 05765344adf6fd949b45bc1e4699305a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
|
||||
namespace GLTF
|
||||
{
|
||||
public class GLTFHeaderInvalidException : Exception
|
||||
{
|
||||
public GLTFHeaderInvalidException() : base() { }
|
||||
public GLTFHeaderInvalidException(string message) : base(message) { }
|
||||
public GLTFHeaderInvalidException(string message, Exception inner) : base(message, inner) { }
|
||||
#if !WINDOWS_UWP
|
||||
protected GLTFHeaderInvalidException(System.Runtime.Serialization.SerializationInfo info,
|
||||
System.Runtime.Serialization.StreamingContext context)
|
||||
{ }
|
||||
#endif
|
||||
}
|
||||
|
||||
public class GLTFParseException : Exception
|
||||
{
|
||||
public GLTFParseException() : base() { }
|
||||
public GLTFParseException(string message) : base(message) { }
|
||||
public GLTFParseException(string message, Exception inner) : base(message, inner) { }
|
||||
#if !WINDOWS_UWP
|
||||
protected GLTFParseException(System.Runtime.Serialization.SerializationInfo info,
|
||||
System.Runtime.Serialization.StreamingContext context)
|
||||
{ }
|
||||
#endif
|
||||
}
|
||||
|
||||
public class GLTFLoadException : Exception
|
||||
{
|
||||
public GLTFLoadException() : base() { }
|
||||
public GLTFLoadException(string message) : base(message) { }
|
||||
public GLTFLoadException(string message, Exception inner) : base(message, inner) { }
|
||||
#if !WINDOWS_UWP
|
||||
protected GLTFLoadException(System.Runtime.Serialization.SerializationInfo info,
|
||||
System.Runtime.Serialization.StreamingContext context)
|
||||
{ }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f014046747656547b05fa3774ecf051
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a4214d32c6f922940ba2e0df9e1ff758
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GLTF.Schema
|
||||
{
|
||||
public class EXT_texture_exr : IExtension
|
||||
{
|
||||
public const string EXTENSION_NAME = "EXT_texture_exr";
|
||||
public ImageId source;
|
||||
|
||||
public EXT_texture_exr(ImageId source)
|
||||
{
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new EXT_texture_exr(source);
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
JObject ext = new JObject();
|
||||
|
||||
ext.Add("source", source.Id);
|
||||
|
||||
return new JProperty(EXTENSION_NAME, ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9348b48c4902434e81000a832ca2ef33
|
||||
timeCreated: 1662326250
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using GLTF.Math;
|
||||
using GLTF.Schema;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GLTF.Schema
|
||||
{
|
||||
public class ExtTextureTransformExtension : IExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// The offset of the UV coordinate origin as a percentage of the texture dimensions.
|
||||
/// </summary>
|
||||
public Vector2 Offset = new Vector2(0, 0);
|
||||
public static readonly Vector2 OFFSET_DEFAULT = new Vector2(0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Rotate the UVs by this many radians counter-clockwise around the origin. This is equivalent
|
||||
/// to a similar rotation of the image clockwise.
|
||||
/// </summary>
|
||||
public double Rotation = 0.0f;
|
||||
public static readonly double ROTATION_DEFAULT = 0.0f;
|
||||
|
||||
/// <summary>
|
||||
/// The scale factor applied to the components of the UV coordinates.
|
||||
/// </summary>
|
||||
public Vector2 Scale = new Vector2(1, 1);
|
||||
public static readonly Vector2 SCALE_DEFAULT = new Vector2(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the textureInfo texCoord value if this extension is supported.
|
||||
/// </summary>
|
||||
public int TexCoord = 0;
|
||||
public static readonly int TEXCOORD_DEFAULT = 0;
|
||||
|
||||
public ExtTextureTransformExtension(Vector2 offset, double rotation, Vector2 scale, int texCoord)
|
||||
{
|
||||
Offset = offset;
|
||||
Rotation = rotation;
|
||||
Scale = scale;
|
||||
TexCoord = texCoord;
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new ExtTextureTransformExtension(Offset, Rotation, Scale, TexCoord);
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
JObject ext = new JObject();
|
||||
|
||||
if (Offset != OFFSET_DEFAULT)
|
||||
{
|
||||
ext.Add(new JProperty(
|
||||
ExtTextureTransformExtensionFactory.OFFSET,
|
||||
new JArray(Offset.X, Offset.Y)
|
||||
));
|
||||
}
|
||||
|
||||
if (Rotation != ROTATION_DEFAULT)
|
||||
{
|
||||
ext.Add(new JProperty(
|
||||
ExtTextureTransformExtensionFactory.ROTATION,
|
||||
Rotation
|
||||
));
|
||||
}
|
||||
|
||||
if (Scale != SCALE_DEFAULT)
|
||||
{
|
||||
ext.Add(new JProperty(
|
||||
ExtTextureTransformExtensionFactory.SCALE,
|
||||
new JArray(Scale.X, Scale.Y)
|
||||
));
|
||||
}
|
||||
|
||||
if (TexCoord != TEXCOORD_DEFAULT)
|
||||
{
|
||||
ext.Add(new JProperty(
|
||||
ExtTextureTransformExtensionFactory.TEXCOORD,
|
||||
TexCoord
|
||||
));
|
||||
}
|
||||
|
||||
return new JProperty(ExtTextureTransformExtensionFactory.EXTENSION_NAME, ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f80e6282349fec4b81cd78cd8a9aa00
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using GLTF.Extensions;
|
||||
using GLTF.Math;
|
||||
|
||||
namespace GLTF.Schema
|
||||
{
|
||||
public class ExtTextureTransformExtensionFactory : ExtensionFactory
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_texture_transform";
|
||||
public const string OFFSET = "offset";
|
||||
public const string ROTATION = "rotation";
|
||||
public const string SCALE = "scale";
|
||||
public const string TEXCOORD = "texCoord";
|
||||
|
||||
public ExtTextureTransformExtensionFactory()
|
||||
{
|
||||
ExtensionName = EXTENSION_NAME;
|
||||
}
|
||||
|
||||
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
|
||||
{
|
||||
Vector2 offset = new Vector2(ExtTextureTransformExtension.OFFSET_DEFAULT);
|
||||
double rotation = 0;
|
||||
Vector2 scale = new Vector2(ExtTextureTransformExtension.SCALE_DEFAULT);
|
||||
int texCoord = ExtTextureTransformExtension.TEXCOORD_DEFAULT;
|
||||
|
||||
if (extensionToken != null)
|
||||
{
|
||||
JToken offsetToken = extensionToken.Value[OFFSET];
|
||||
offset = offsetToken != null ? offsetToken.DeserializeAsVector2() : offset;
|
||||
|
||||
JToken rotationToken = extensionToken.Value[ROTATION];
|
||||
rotation = rotationToken != null ? rotationToken.DeserializeAsDouble() : rotation;
|
||||
|
||||
JToken scaleToken = extensionToken.Value[SCALE];
|
||||
scale = scaleToken != null ? scaleToken.DeserializeAsVector2() : scale;
|
||||
|
||||
JToken texCoordToken = extensionToken.Value[TEXCOORD];
|
||||
texCoord = texCoordToken != null ? texCoordToken.DeserializeAsInt() : texCoord;
|
||||
}
|
||||
|
||||
return new ExtTextureTransformExtension(offset, rotation, scale, texCoord);
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bb5582955db3cc947a57a02c5bfe15aa
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Math;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using GLTF.Schema;
|
||||
|
||||
namespace GLTF.Extensions
|
||||
{
|
||||
public static class JsonReaderExtensions
|
||||
{
|
||||
public static List<string> ReadStringList(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var list = new List<string>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
list.Add(reader.Value.ToString());
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<double> ReadDoubleList(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var list = new List<double>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
list.Add(double.Parse(reader.Value.ToString()));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<int> ReadInt32List(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var list = new List<int>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
list.Add(int.Parse(reader.Value.ToString()));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<T> ReadList<T>(this JsonReader reader, Func<T> deserializerFunc)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var list = new List<T>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
list.Add(deserializerFunc());
|
||||
|
||||
// deserializerFunc can advance to EndArray. We need to check for this case as well.
|
||||
if (reader.TokenType == JsonToken.EndArray)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static TextureInfo DeserializeAsTexture(this JToken token, GLTFRoot root)
|
||||
{
|
||||
TextureInfo textureInfo = null;
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
JObject textureObject = token as JObject;
|
||||
if (textureObject == null)
|
||||
{
|
||||
throw new Exception("JToken used for Texture deserialization was not a JObject. It was a " + token.Type.ToString());
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Broken on il2cpp. Don't ship debug DLLs there.
|
||||
System.Diagnostics.Debug.WriteLine("textureObject is " + textureObject.Type + " with a value of: " + textureObject[TextureInfo.INDEX].Type + " " + textureObject.ToString());
|
||||
#endif
|
||||
int indexVal = textureObject[TextureInfo.INDEX].DeserializeAsInt();
|
||||
textureInfo = new TextureInfo()
|
||||
{
|
||||
Index = new TextureId()
|
||||
{
|
||||
Id = indexVal,
|
||||
Root = root
|
||||
}
|
||||
};
|
||||
if (textureObject.ContainsKey(TextureInfo.TEXCOORD))
|
||||
{
|
||||
textureInfo.TexCoord = textureObject[TextureInfo.TEXCOORD].DeserializeAsInt();
|
||||
}
|
||||
}
|
||||
|
||||
return textureInfo;
|
||||
}
|
||||
|
||||
public static NormalTextureInfo DeserializeAsNormalTexture(this JToken token, GLTFRoot root)
|
||||
{
|
||||
var tex = DeserializeAsTexture(token, root);
|
||||
if (tex != null)
|
||||
{
|
||||
var normalTex = new NormalTextureInfo() { Index = tex.Index, TexCoord = tex.TexCoord };
|
||||
JObject textureObject = token as JObject;
|
||||
if (textureObject.ContainsKey(NormalTextureInfo.SCALE))
|
||||
{
|
||||
normalTex.Scale = textureObject[NormalTextureInfo.SCALE].DeserializeAsDouble();
|
||||
}
|
||||
|
||||
return normalTex;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int DeserializeAsInt(this JToken token)
|
||||
{
|
||||
if (token != null)
|
||||
{
|
||||
JValue intValue = token as JValue;
|
||||
if (intValue == null)
|
||||
{
|
||||
throw new Exception("JToken used for int deserialization was not a JValue. It was a " + token.Type.ToString());
|
||||
}
|
||||
|
||||
return (int)intValue;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static double DeserializeAsDouble(this JToken token)
|
||||
{
|
||||
if (token != null)
|
||||
{
|
||||
JValue doubleValue = token as JValue;
|
||||
if (doubleValue == null)
|
||||
{
|
||||
throw new Exception("JToken used for double deserialization was not a JValue. It was a " + token.Type.ToString());
|
||||
}
|
||||
|
||||
return (double)doubleValue;
|
||||
}
|
||||
|
||||
return 0d;
|
||||
}
|
||||
|
||||
public static Color ReadAsRGBAColor(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var color = new Color
|
||||
{
|
||||
R = (float) reader.ReadAsDouble().Value,
|
||||
G = (float) reader.ReadAsDouble().Value,
|
||||
B = (float) reader.ReadAsDouble().Value,
|
||||
A = (float) reader.ReadAsDouble().Value
|
||||
};
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
public static Color DeserializeAsColor(this JToken token)
|
||||
{
|
||||
Color color = Color.White;
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
JArray colorArray = token as JArray;
|
||||
if (colorArray == null)
|
||||
{
|
||||
throw new Exception("JToken used for Color deserialization was not a JArray. It was a " + token.Type.ToString());
|
||||
}
|
||||
if (colorArray.Count < 3)
|
||||
{
|
||||
throw new Exception("JArray used for Color deserialization did have less than 3 entries (needs to be RGB or RGBA). It had " + colorArray.Count);
|
||||
}
|
||||
|
||||
color = new Color
|
||||
{
|
||||
R = (float)colorArray[0].DeserializeAsDouble(),
|
||||
G = (float)colorArray[1].DeserializeAsDouble(),
|
||||
B = (float)colorArray[2].DeserializeAsDouble(),
|
||||
A = (float)(colorArray.Count == 4 ? colorArray[3].DeserializeAsDouble() : 1.0),
|
||||
};
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
public static Color ReadAsRGBColor(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var color = new Color
|
||||
{
|
||||
R = (float) reader.ReadAsDouble().Value,
|
||||
G = (float) reader.ReadAsDouble().Value,
|
||||
B = (float) reader.ReadAsDouble().Value,
|
||||
A = 1.0f
|
||||
};
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
public static Vector3 ReadAsVector3(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var vector = new Vector3
|
||||
{
|
||||
X = (float) reader.ReadAsDouble().Value,
|
||||
Y = (float) reader.ReadAsDouble().Value,
|
||||
Z = (float) reader.ReadAsDouble().Value
|
||||
};
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
return vector;
|
||||
}
|
||||
|
||||
public static Vector2 DeserializeAsVector2(this JToken token)
|
||||
{
|
||||
Vector2 vector = new Vector2();
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
JArray vectorArray = token as JArray;
|
||||
if (vectorArray == null)
|
||||
{
|
||||
throw new Exception("JToken used for Vector2 deserialization was not a JArray. It was a " + token.Type.ToString());
|
||||
}
|
||||
if (vectorArray.Count != 2)
|
||||
{
|
||||
throw new Exception("JArray used for Vector2 deserialization did not have 2 entries for XY. It had " + vectorArray.Count);
|
||||
}
|
||||
|
||||
vector = new Vector2
|
||||
{
|
||||
X = (float)vectorArray[0].DeserializeAsDouble(),
|
||||
Y = (float)vectorArray[1].DeserializeAsDouble()
|
||||
};
|
||||
}
|
||||
|
||||
return vector;
|
||||
}
|
||||
|
||||
public static Vector3 DeserializeAsVector3(this JToken token)
|
||||
{
|
||||
Vector3 vector = new Vector3();
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
JArray vectorArray = token as JArray;
|
||||
if (vectorArray == null)
|
||||
{
|
||||
throw new Exception("JToken used for Vector3 deserialization was not a JArray. It was a " + token.Type.ToString());
|
||||
}
|
||||
if (vectorArray.Count != 3)
|
||||
{
|
||||
throw new Exception("JArray used for Vector3 deserialization did not have 3 entries for XYZ. It had " + vectorArray.Count);
|
||||
}
|
||||
|
||||
vector = new Vector3
|
||||
{
|
||||
X = (float)vectorArray[0].DeserializeAsDouble(),
|
||||
Y = (float)vectorArray[1].DeserializeAsDouble(),
|
||||
Z = (float)vectorArray[2].DeserializeAsDouble()
|
||||
};
|
||||
}
|
||||
|
||||
return vector;
|
||||
}
|
||||
|
||||
public static Quaternion ReadAsQuaternion(this JsonReader reader)
|
||||
{
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var quat = new Quaternion
|
||||
{
|
||||
X = (float) reader.ReadAsDouble().Value,
|
||||
Y = (float) reader.ReadAsDouble().Value,
|
||||
Z = (float) reader.ReadAsDouble().Value,
|
||||
W = (float) reader.ReadAsDouble().Value
|
||||
};
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
return quat;
|
||||
}
|
||||
|
||||
public static Dictionary<string, T> ReadAsDictionary<T>(this JsonReader reader, Func<T> deserializerFunc, bool skipStartObjectRead = false)
|
||||
{
|
||||
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
|
||||
{
|
||||
throw new Exception(string.Format("Dictionary must be an object at: {0}.", reader.Path));
|
||||
}
|
||||
|
||||
var dict = new Dictionary<string, T>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
dict.Add(reader.Value.ToString(), deserializerFunc());
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> ReadAsObjectDictionary(this JsonReader reader, bool skipStartObjectRead = false)
|
||||
{
|
||||
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
|
||||
{
|
||||
throw new Exception(string.Format("Dictionary must be an object at: {0}", reader.Path));
|
||||
}
|
||||
|
||||
var dict = new Dictionary<string, object>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
dict.Add(reader.Value.ToString(), ReadDictionaryValue(reader));
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
private static object ReadDictionaryValue(JsonReader reader)
|
||||
{
|
||||
if (!reader.Read())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartArray:
|
||||
return reader.ReadObjectList();
|
||||
case JsonToken.StartObject:
|
||||
return reader.ReadAsObjectDictionary(true);
|
||||
default:
|
||||
return reader.Value;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<object> ReadObjectList(this JsonReader reader)
|
||||
{
|
||||
|
||||
var list = new List<object>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
list.Add(reader.Value);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static T ReadStringEnum<T>(this JsonReader reader)
|
||||
{
|
||||
return (T) Enum.Parse(typeof(T), reader.ReadAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1b39ce55534dbbf4ab3dceec1cec6317
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Math;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using GLTF.Extensions;
|
||||
|
||||
namespace GLTF.Schema.KHR_lights_punctual
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies the light type.
|
||||
/// </summary>
|
||||
public enum LightType
|
||||
{
|
||||
directional,
|
||||
point,
|
||||
spot
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Texture sampler properties for filtering and wrapping modes.
|
||||
/// </summary>
|
||||
public class Spot
|
||||
{
|
||||
private const string PNAME_INNERCONEANGLE = "innerConeAngle";
|
||||
private const string PNAME_OUTERCONEANGLE = "outerConeAngle";
|
||||
|
||||
public static readonly double INNER_DEFAULT = 0d;
|
||||
public static readonly double OUTER_DEFAULT = 0.7853981633974483d;
|
||||
/// <summary>
|
||||
/// Angle, in radians, from centre of spotlight where falloff begins. Must be greater than or equal to 0 and less than outerConeAngle.
|
||||
/// </summary>
|
||||
public double InnerConeAngle = INNER_DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// Angle, in radians, from centre of spotlight where falloff ends. Must be greater than innerConeAngle and less than or equal to PI / 2.0.
|
||||
/// </summary>
|
||||
public double OuterConeAngle = OUTER_DEFAULT;
|
||||
|
||||
public Spot()
|
||||
{
|
||||
}
|
||||
|
||||
public static Spot Deserialize(JsonReader reader)
|
||||
{
|
||||
var spot = new Spot();
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
|
||||
{
|
||||
return spot;
|
||||
}
|
||||
|
||||
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
|
||||
{
|
||||
var curProp = reader.Value.ToString();
|
||||
|
||||
switch (curProp)
|
||||
{
|
||||
case PNAME_INNERCONEANGLE:
|
||||
spot.InnerConeAngle= reader.ReadAsDouble().Value;
|
||||
break;
|
||||
case PNAME_OUTERCONEANGLE:
|
||||
spot.OuterConeAngle= reader.ReadAsDouble().Value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return spot;
|
||||
}
|
||||
|
||||
public void Serialize(JsonWriter writer)
|
||||
{
|
||||
if( InnerConeAngle > OuterConeAngle)
|
||||
{
|
||||
throw new Exception("Spot's InnerConeAngle must be less or equal OuterConeAngle");
|
||||
}
|
||||
|
||||
if (OuterConeAngle > 1.5707963267948966d )
|
||||
{
|
||||
throw new Exception("Spot's OuterConeAngle must be less or equal Pi/2");
|
||||
}
|
||||
|
||||
writer.WriteStartObject();
|
||||
|
||||
if (InnerConeAngle != INNER_DEFAULT)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_INNERCONEANGLE);
|
||||
writer.WriteValue(InnerConeAngle);
|
||||
}
|
||||
|
||||
if (OuterConeAngle != OUTER_DEFAULT)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_OUTERCONEANGLE);
|
||||
writer.WriteValue(OuterConeAngle);
|
||||
}
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
}
|
||||
|
||||
public class PunctualLight : GLTFChildOfRootProperty
|
||||
{
|
||||
private const string PNAME_TYPE = "type";
|
||||
private const string PNAME_COLOR = "color";
|
||||
private const string PNAME_INTENSITY = "intensity";
|
||||
private const string PNAME_RANGE = "range";
|
||||
private const string PNAME_SPOT = "spot";
|
||||
|
||||
public static readonly Color COLOR_DEFAULT = Color.White;
|
||||
public static readonly double RANGE_DEFAULT = -1d;
|
||||
public static readonly double INTENSITY_DEFAULT = 1d;
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the light type.
|
||||
/// </summary>
|
||||
public LightType Type;
|
||||
|
||||
/// <summary>
|
||||
/// Color of the light source.
|
||||
/// </summary>
|
||||
public Color Color = COLOR_DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// Intensity of the light source. `point` and `spot` lights use luminous intensity in candela (lm/sr) while `directional` lights use illuminance in lux (lm/m^2)
|
||||
/// </summary>
|
||||
public double Intensity = INTENSITY_DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// A distance cutoff at which the light's intensity may be considered to have reached zero.
|
||||
/// </summary>
|
||||
public double Range = RANGE_DEFAULT;
|
||||
|
||||
/// <summary>
|
||||
/// spot's inner and outer angle, must exist for spot types
|
||||
/// </summary>
|
||||
public Spot Spot;
|
||||
|
||||
public PunctualLight()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public PunctualLight(PunctualLight light, GLTFRoot gltfRoot) : base(light, gltfRoot)
|
||||
{
|
||||
Type = light.Type;
|
||||
Color = light.Color;
|
||||
Intensity = light.Intensity;
|
||||
Range = light.Range;
|
||||
Spot = light.Spot;
|
||||
}
|
||||
|
||||
public static PunctualLight Deserialize(GLTFRoot root, JsonReader reader)
|
||||
{
|
||||
var light = new PunctualLight();
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
|
||||
{
|
||||
throw new Exception("Light must be an object.");
|
||||
}
|
||||
|
||||
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
|
||||
{
|
||||
var curProp = reader.Value.ToString();
|
||||
|
||||
switch (curProp)
|
||||
{
|
||||
case PNAME_TYPE:
|
||||
light.Type = reader.ReadStringEnum<LightType>();
|
||||
break;
|
||||
case PNAME_COLOR:
|
||||
light.Color = reader.ReadAsRGBColor();
|
||||
break;
|
||||
case PNAME_INTENSITY:
|
||||
light.Intensity = reader.ReadAsDouble().Value;
|
||||
break;
|
||||
case PNAME_RANGE:
|
||||
light.Range = reader.ReadAsDouble().Value;
|
||||
break;
|
||||
case PNAME_SPOT:
|
||||
light.Spot = Spot.Deserialize(reader);
|
||||
break;
|
||||
default:
|
||||
light.DefaultPropertyDeserializer(root, reader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return light;
|
||||
}
|
||||
|
||||
public static PunctualLight Deserialize(GLTFRoot root, JToken token)
|
||||
{
|
||||
using (JsonReader reader = new JTokenReader(token))
|
||||
{
|
||||
return Deserialize(root, reader);
|
||||
}
|
||||
}
|
||||
|
||||
override public void Serialize(JsonWriter writer)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
|
||||
writer.WritePropertyName(PNAME_TYPE);
|
||||
writer.WriteValue(Type.ToString());
|
||||
|
||||
|
||||
if (Color != COLOR_DEFAULT)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_COLOR);
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(Color.R);
|
||||
writer.WriteValue(Color.G);
|
||||
writer.WriteValue(Color.B);
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
if (Intensity != INTENSITY_DEFAULT)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_INTENSITY);
|
||||
writer.WriteValue(Intensity);
|
||||
}
|
||||
|
||||
if (Range != RANGE_DEFAULT)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_RANGE);
|
||||
writer.WriteValue(Range);
|
||||
}
|
||||
|
||||
if (Type == LightType.spot)
|
||||
{
|
||||
writer.WritePropertyName(PNAME_SPOT);
|
||||
Spot.Serialize(writer);
|
||||
}
|
||||
|
||||
base.Serialize(writer);
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
public JObject Serialize()
|
||||
{
|
||||
JTokenWriter writer = new JTokenWriter();
|
||||
Serialize(writer);
|
||||
return (JObject)writer.Token;
|
||||
}
|
||||
}
|
||||
|
||||
public class KHR_LightsPunctualRootExtension : IExtension
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_lights_punctual";
|
||||
|
||||
public readonly IList<GLTFLight> lights;
|
||||
|
||||
public KHR_LightsPunctualRootExtension(IList<GLTFLight> lights)
|
||||
{
|
||||
this.lights = lights;
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
var obj = new JObject();
|
||||
var arr = new JArray();
|
||||
obj.Add("lights", arr);
|
||||
foreach (var light in lights)
|
||||
{
|
||||
var lightInfo = new JObject();
|
||||
arr.Add(lightInfo);
|
||||
lightInfo.Add("type", light.type);
|
||||
if (light.range > 0) lightInfo.Add("range", light.range);
|
||||
if(System.Math.Abs(light.intensity - 1f) > .0000001) lightInfo.Add("intensity", light.intensity);
|
||||
lightInfo.Add("name", light.Name ?? light.name);
|
||||
lightInfo.Add("color", new JArray(light.color.R, light.color.G, light.color.B));
|
||||
// TODO why is this not using the specific spotlight serializer/deserializer?
|
||||
if (light is GLTFSpotLight spotLight)
|
||||
{
|
||||
lightInfo.Add("spot", new JObject(
|
||||
new JProperty(nameof(spotLight.innerConeAngle), spotLight.innerConeAngle),
|
||||
new JProperty(nameof(spotLight.outerConeAngle), spotLight.outerConeAngle)));
|
||||
}
|
||||
}
|
||||
return new JProperty(EXTENSION_NAME, obj);
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new KHR_LightsPunctualRootExtension(lights);
|
||||
}
|
||||
}
|
||||
|
||||
public class KHR_LightsPunctualExtension : IExtension
|
||||
{
|
||||
public List<PunctualLight> Lights;
|
||||
|
||||
public KHR_LightsPunctualExtension()
|
||||
{
|
||||
Lights = new List<PunctualLight>();
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
var clone = new KHR_LightsPunctualExtension();
|
||||
for (int i = 0; i < Lights.Count; i++)
|
||||
{
|
||||
clone.Lights.Add(new PunctualLight(Lights[i], root));
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
return new JProperty(KHR_lights_punctualExtensionFactory.EXTENSION_NAME,
|
||||
new JObject(
|
||||
new JProperty(KHR_lights_punctualExtensionFactory.PNAME_LIGHTS, new JArray(Lights))
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public class PunctualLightId : GLTFId<PunctualLight>
|
||||
{
|
||||
public PunctualLightId()
|
||||
{
|
||||
}
|
||||
|
||||
public PunctualLightId(PunctualLightId id, GLTFRoot newRoot) : base(id, newRoot)
|
||||
{
|
||||
}
|
||||
|
||||
public override PunctualLight Value
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Root.Extensions.TryGetValue(KHR_lights_punctualExtensionFactory.EXTENSION_NAME, out IExtension iextension))
|
||||
{
|
||||
KHR_LightsPunctualExtension extension = iextension as KHR_LightsPunctualExtension;
|
||||
return extension.Lights[Id];
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("KHR_lights_punctual not found on root object");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static PunctualLightId Deserialize(GLTFRoot root, JsonReader reader)
|
||||
{
|
||||
return new PunctualLightId
|
||||
{
|
||||
Id = reader.ReadAsInt32().Value,
|
||||
Root = root
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class KHR_LightsPunctualNodeExtension : IExtension
|
||||
{
|
||||
public PunctualLightId LightId;
|
||||
|
||||
public KHR_LightsPunctualNodeExtension()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public KHR_LightsPunctualNodeExtension(PunctualLightId lightId, GLTFRoot gltfRoot)
|
||||
{
|
||||
LightId = lightId;
|
||||
}
|
||||
|
||||
public KHR_LightsPunctualNodeExtension( int lightId, GLTFRoot gltfRoot)
|
||||
{
|
||||
LightId = new PunctualLightId
|
||||
{
|
||||
Id = lightId,
|
||||
Root = gltfRoot
|
||||
};
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new KHR_LightsPunctualNodeExtension(LightId.Id, root);
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
return new JProperty(KHR_lights_punctualExtensionFactory.EXTENSION_NAME,
|
||||
new JObject(
|
||||
new JProperty(KHR_lights_punctualExtensionFactory.PNAME_LIGHT, LightId.Id )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8451131b54699e840ba8425046aec379
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
|
||||
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GLTF.Schema.KHR_lights_punctual
|
||||
{
|
||||
public class KHR_lights_punctualExtensionFactory : ExtensionFactory
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_lights_punctual";
|
||||
|
||||
|
||||
public const string PNAME_LIGHTS = "lights";
|
||||
public const string PNAME_LIGHT = "light";
|
||||
|
||||
public KHR_lights_punctualExtensionFactory()
|
||||
{
|
||||
ExtensionName = EXTENSION_NAME;
|
||||
}
|
||||
|
||||
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
|
||||
{
|
||||
if (extensionToken != null)
|
||||
{
|
||||
JToken lightsToken = extensionToken.Value[PNAME_LIGHTS];
|
||||
|
||||
if (lightsToken != null)
|
||||
{
|
||||
var extension = new KHR_LightsPunctualExtension();
|
||||
JArray lightsArray = lightsToken as JArray;
|
||||
foreach( var lightToken in lightsArray.Children())
|
||||
{
|
||||
extension.Lights.Add(PunctualLight.Deserialize(root, lightToken));
|
||||
}
|
||||
return extension;
|
||||
}
|
||||
|
||||
JToken nodelightToken = extensionToken.Value[PNAME_LIGHT];
|
||||
|
||||
if (nodelightToken != null)
|
||||
{
|
||||
PunctualLightId lightId = PunctualLightId.Deserialize(root, nodelightToken.CreateReader() );
|
||||
return new KHR_LightsPunctualNodeExtension( lightId, root );
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f6f51e6a8e36a7641bde14286a98f0d5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using GLTF.Schema;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace UnityGLTF.Extensions
|
||||
{
|
||||
|
||||
// see https://github.com/KhronosGroup/glTF/pull/2147
|
||||
public class KHR_animation_pointer : IExtension
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_animation_pointer";
|
||||
|
||||
public object animatedObject;
|
||||
public string propertyBinding;
|
||||
public string path;
|
||||
public AnimationChannelTarget channel;
|
||||
|
||||
// when cloned, the path is late resolved in gltf exporter so the clone path will not be resolved because it wont be registered to the exporter's resolver
|
||||
private KHR_animation_pointer clonedFrom;
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
if (path == null && clonedFrom != null) path = clonedFrom.path;
|
||||
return new JProperty(EXTENSION_NAME, new JObject(new JProperty("pointer", path)));
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new KHR_animation_pointer
|
||||
{
|
||||
animatedObject = animatedObject,
|
||||
propertyBinding = propertyBinding,
|
||||
path = path,
|
||||
channel = channel,
|
||||
clonedFrom = this
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 674db370468f4e2491e20dbadfa2a640
|
||||
timeCreated: 1648456390
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using GLTF.Extensions;
|
||||
using GLTF.Math;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GLTF.Schema
|
||||
{
|
||||
// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md
|
||||
[Serializable]
|
||||
public class KHR_materials_clearcoat : IExtension
|
||||
{
|
||||
public float clearcoatFactor = 0f;
|
||||
public TextureInfo clearcoatTexture; // R channel
|
||||
public float clearcoatRoughnessFactor = 0f;
|
||||
public TextureInfo clearcoatRoughnessTexture; // G channel
|
||||
public TextureInfo clearcoatNormalTexture;
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
var jo = new JObject();
|
||||
JProperty jProperty = new JProperty(KHR_materials_clearcoat_Factory.EXTENSION_NAME, jo);
|
||||
|
||||
// TODO all these properties should only be added if non-default
|
||||
|
||||
if (clearcoatFactor != 0)
|
||||
jo.Add(new JProperty(nameof(clearcoatFactor), clearcoatFactor));
|
||||
if (clearcoatTexture != null) {
|
||||
jo.Add(new JProperty(nameof(clearcoatTexture),
|
||||
new JObject(
|
||||
new JProperty(TextureInfo.INDEX, clearcoatTexture.Index.Id),
|
||||
new JProperty(TextureInfo.TEXCOORD, clearcoatTexture.TexCoord)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
if (clearcoatRoughnessFactor != 0)
|
||||
jo.Add(new JProperty(nameof(clearcoatRoughnessFactor), clearcoatRoughnessFactor));
|
||||
if (clearcoatRoughnessTexture != null) {
|
||||
jo.Add(new JProperty(nameof(clearcoatRoughnessTexture),
|
||||
new JObject(
|
||||
new JProperty(TextureInfo.INDEX, clearcoatRoughnessTexture.Index.Id),
|
||||
new JProperty(TextureInfo.TEXCOORD, clearcoatRoughnessTexture.TexCoord)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
if (clearcoatNormalTexture != null) {
|
||||
jo.Add(new JProperty(nameof(clearcoatNormalTexture),
|
||||
new JObject(
|
||||
new JProperty(TextureInfo.INDEX, clearcoatNormalTexture.Index.Id),
|
||||
new JProperty(TextureInfo.TEXCOORD, clearcoatNormalTexture.TexCoord)
|
||||
// new JProperty(NormalTextureInfo.SCALE, clearcoatNormalTexture.Scale) // TODO needs better normal scale export, uses only the base normal right now
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
return jProperty;
|
||||
}
|
||||
|
||||
public IExtension Clone(GLTFRoot root)
|
||||
{
|
||||
return new KHR_materials_clearcoat()
|
||||
{
|
||||
clearcoatFactor = clearcoatFactor, clearcoatTexture = clearcoatTexture,
|
||||
clearcoatRoughnessFactor = clearcoatRoughnessFactor, clearcoatRoughnessTexture = clearcoatRoughnessTexture,
|
||||
clearcoatNormalTexture = clearcoatNormalTexture,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class KHR_materials_clearcoat_Factory : ExtensionFactory
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_materials_clearcoat";
|
||||
|
||||
public KHR_materials_clearcoat_Factory()
|
||||
{
|
||||
ExtensionName = EXTENSION_NAME;
|
||||
}
|
||||
|
||||
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
|
||||
{
|
||||
if (extensionToken != null)
|
||||
{
|
||||
var extension = new KHR_materials_clearcoat();
|
||||
extension.clearcoatFactor = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatFactor)]?.Value<float>() ?? 0;
|
||||
extension.clearcoatTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatTexture)]?.DeserializeAsTexture(root);
|
||||
extension.clearcoatRoughnessFactor = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatRoughnessFactor)]?.Value<float>() ?? 0;
|
||||
extension.clearcoatRoughnessTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatRoughnessTexture)]?.DeserializeAsTexture(root);
|
||||
extension.clearcoatNormalTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatNormalTexture)]?.DeserializeAsTexture(root);
|
||||
return extension;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8427a62b522f4f2d84dda8d98fa76701
|
||||
timeCreated: 1673353427
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GLTF.Schema
|
||||
{
|
||||
public class KHR_materials_emissive_strength : GLTFProperty, IExtension
|
||||
{
|
||||
public KHR_materials_emissive_strength() { }
|
||||
|
||||
public KHR_materials_emissive_strength(KHR_materials_emissive_strength ext, GLTFRoot root) : base(ext, root) { }
|
||||
|
||||
public IExtension Clone(GLTFRoot gltfRoot)
|
||||
{
|
||||
return new KHR_materials_emissive_strength(this, gltfRoot);
|
||||
}
|
||||
|
||||
public JProperty Serialize()
|
||||
{
|
||||
var jo = new JObject();
|
||||
JProperty jProperty = new JProperty(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, jo);
|
||||
|
||||
if(emissiveStrength != 1.0f)
|
||||
jo.Add(new JProperty(nameof(emissiveStrength), emissiveStrength));
|
||||
|
||||
return jProperty;
|
||||
}
|
||||
|
||||
public float emissiveStrength = 1.0f;
|
||||
}
|
||||
|
||||
public class KHR_materials_emissive_strength_Factory : ExtensionFactory
|
||||
{
|
||||
public const string EXTENSION_NAME = "KHR_materials_emissive_strength";
|
||||
|
||||
public KHR_materials_emissive_strength_Factory()
|
||||
{
|
||||
ExtensionName = EXTENSION_NAME;
|
||||
}
|
||||
|
||||
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
|
||||
{
|
||||
if (extensionToken != null)
|
||||
{
|
||||
var extension = new KHR_materials_emissive_strength();
|
||||
|
||||
JToken strength = extensionToken.Value[nameof(KHR_materials_emissive_strength.emissiveStrength)];
|
||||
if (strength != null)
|
||||
extension.emissiveStrength = strength.Value<float>();
|
||||
|
||||
return extension;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f4a07b6badfb6844e8d34a3a9b15a6f5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user