From 4accb0d60a5817a905e9fcb362fb0aca87bf6ce9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 13 Mar 2024 02:21:09 +0900 Subject: [PATCH 001/208] chore: refactor AddComponentMenu Defines --- .../MatAndTexUtils/MatAndTexAbsoluteSeparator.cs | 5 ++++- .../MatAndTexUtils/MatAndTexRelativeSeparator.cs | 4 +++- .../CommonComponent/MatAndTexUtils/MaterialModifier.cs | 6 ++++-- Runtime/CommonComponent/PhaseDefinition.cs | 6 ++++-- Runtime/CommonComponent/PreviewGroup.cs | 5 ++++- Runtime/CommonComponent/PreviewRenderer.cs | 5 ++++- Runtime/CommonComponent/TexTransGroup.cs | 6 +++++- Runtime/CommonComponent/TextureBlender.cs | 9 ++++++--- Runtime/Decal/Curve/CurveSegment.cs | 2 +- Runtime/Decal/Curve/CylindricalCurveDecal.cs | 4 ++-- .../Decal/Cylindrical/CylindricalCoordinatesSystem.cs | 2 +- Runtime/Decal/CylindricalDecal.cs | 2 +- Runtime/Decal/NailEditor.cs | 2 +- Runtime/Decal/SimpleDecal.cs | 4 +++- Runtime/MultiLayerImage/LayerFolder.cs | 4 +++- Runtime/MultiLayerImage/MultiLayerImageCanvas.cs | 6 ++++-- Runtime/MultiLayerImage/RasterImportedLayer.cs | 5 ++++- Runtime/MultiLayerImage/RasterLayer.cs | 6 ++++-- .../MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs | 4 +++- .../MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs | 6 ++++-- .../SpecialLayer/SelectiveColorAdjustmentLayer.cs | 4 +++- Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs | 6 ++++-- Runtime/ReferenceResolver/AbstractResolver.cs | 3 ++- .../AtlasTexture/AddAbsoluteMaterials.cs | 6 ++++-- Runtime/ReferenceResolver/AtlasTexture/RootObject.cs | 6 ++++-- .../Decal/RayCastRendererMultiResolver.cs | 6 ++++-- .../ReferenceResolver/Decal/RayCastRendererResolver.cs | 6 ++++-- Runtime/TexTransBehavior.cs | 2 ++ Runtime/TextureAtlas/AtlasTexture.cs | 4 +++- 29 files changed, 95 insertions(+), 41 deletions(-) diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs index 0e66cc35..0d4188e8 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs @@ -5,9 +5,12 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MatAndTexAbsoluteSeparator")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MatAndTexAbsoluteSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator { + internal const string FoldoutName = "MatAndTexUtils"; + internal const string ComponentName = "TTT MatAndTexAbsoluteSeparator"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs index 6c21a3ec..e59f347e 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs @@ -5,9 +5,11 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MatAndTexRelativeSeparator")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MatAndTexRelativeSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator { + internal const string ComponentName = "TTT MatAndTexRelativeSeparator"; + internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index 8d38f3a5..e25bd878 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -7,9 +7,11 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MaterialModifier")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MaterialModifier : TexTransRuntimeBehavior { + internal const string ComponentName = "TTT MaterialModifier"; + internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; @@ -92,4 +94,4 @@ internal override void Apply([NotNull] IDomain domain) domain.ReplaceMaterials(modMatList); } } -} \ No newline at end of file +} diff --git a/Runtime/CommonComponent/PhaseDefinition.cs b/Runtime/CommonComponent/PhaseDefinition.cs index 73970dfb..e01f8e74 100644 --- a/Runtime/CommonComponent/PhaseDefinition.cs +++ b/Runtime/CommonComponent/PhaseDefinition.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Group/TTT PhaseDefinition")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + PDMenuPath)] public sealed class PhaseDefinition : TexTransGroup { + internal const string PDName = "TTT PhaseDefinition"; + internal const string PDMenuPath = TexTransGroup.FoldoutName + "/" + PDName; public TexTransPhase TexTransPhase; } -} \ No newline at end of file +} diff --git a/Runtime/CommonComponent/PreviewGroup.cs b/Runtime/CommonComponent/PreviewGroup.cs index d32397f1..f7f0d850 100644 --- a/Runtime/CommonComponent/PreviewGroup.cs +++ b/Runtime/CommonComponent/PreviewGroup.cs @@ -3,9 +3,12 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/PreviewUtility/TTT PreviewGroup")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class PreviewGroup : TexTransCallEditorBehavior { + internal const string FoldoutName = "PreviewUtility"; + internal const string ComponentName = "TTT PreviewGroup"; + internal const string MenuPath = PreviewGroup.FoldoutName + "/" + ComponentName; internal override List GetRenderers => null; internal override bool IsPossibleApply => true; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; diff --git a/Runtime/CommonComponent/PreviewRenderer.cs b/Runtime/CommonComponent/PreviewRenderer.cs index b66e275d..8d1a1d0b 100644 --- a/Runtime/CommonComponent/PreviewRenderer.cs +++ b/Runtime/CommonComponent/PreviewRenderer.cs @@ -3,10 +3,13 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/PreviewUtility/TTT PreviewRenderer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] [RequireComponent(typeof(Renderer))] public sealed class PreviewRenderer : TexTransCallEditorBehavior { + internal const string ComponentName = "TTT PreviewRenderer"; + internal const string MenuPath = PreviewGroup.FoldoutName + "/" + ComponentName; + internal override List GetRenderers => null; internal override bool IsPossibleApply => true; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; diff --git a/Runtime/CommonComponent/TexTransGroup.cs b/Runtime/CommonComponent/TexTransGroup.cs index 48077fed..51d07907 100644 --- a/Runtime/CommonComponent/TexTransGroup.cs +++ b/Runtime/CommonComponent/TexTransGroup.cs @@ -5,9 +5,13 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Group/TTT TexTransGroup")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class TexTransGroup : TexTransCallEditorBehavior { + internal const string FoldoutName = "Group"; + internal const string ComponentName = "TTT TexTransGroup"; + internal const string MenuPath = TexTransGroup.FoldoutName + "/" + ComponentName; + internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; internal IEnumerable Targets => transform.GetChildren().Select(x => x.GetComponent()).Where(x => x != null); diff --git a/Runtime/CommonComponent/TextureBlender.cs b/Runtime/CommonComponent/TextureBlender.cs index 3a465293..ca95f433 100644 --- a/Runtime/CommonComponent/TextureBlender.cs +++ b/Runtime/CommonComponent/TextureBlender.cs @@ -5,12 +5,15 @@ using net.rs64.TexTransTool.Utils; namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Other/TTT TextureBlender")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class TextureBlender : TexTransRuntimeBehavior { + internal const string FoldoutName = "Other"; + internal const string ComponentName = "TTT TextureBlender"; + internal const string MenuPath = TextureBlender.FoldoutName + "/" + ComponentName; public TextureSelector TargetTexture; - [ExpandTexture2D]public Texture2D BlendTexture; + [ExpandTexture2D] public Texture2D BlendTexture; public Color Color = Color.white; [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; @@ -34,4 +37,4 @@ internal override void Apply(IDomain domain) domain.AddTextureStack(distTex, new(addTex, BlendTypeKey)); } } -} \ No newline at end of file +} diff --git a/Runtime/Decal/Curve/CurveSegment.cs b/Runtime/Decal/Curve/CurveSegment.cs index a47010ae..cf083b3b 100644 --- a/Runtime/Decal/Curve/CurveSegment.cs +++ b/Runtime/Decal/Curve/CurveSegment.cs @@ -3,7 +3,7 @@ namespace net.rs64.TexTransTool.Decal.Curve { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/Unfinished/TTT CurveSegment")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CurveSegment")] internal class CurveSegment : MonoBehaviour, ITexTransToolTag { [HideInInspector,SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; diff --git a/Runtime/Decal/Curve/CylindricalCurveDecal.cs b/Runtime/Decal/Curve/CylindricalCurveDecal.cs index 8ccde62d..ace6b578 100644 --- a/Runtime/Decal/Curve/CylindricalCurveDecal.cs +++ b/Runtime/Decal/Curve/CylindricalCurveDecal.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal.Curve { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/Unfinished/TTT CylindricalCurveDecal")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CylindricalCurveDecal")] internal class CylindricalCurveDecal : CurveDecal { public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; @@ -114,4 +114,4 @@ protected virtual void DrawerGizmo() } } -} \ No newline at end of file +} diff --git a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs index cce0ce95..baef90c9 100644 --- a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs +++ b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal.Cylindrical { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/TTT CylindricalCoordinatesSystem")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalCoordinatesSystem")] internal class CylindricalCoordinatesSystem : MonoBehaviour, ITexTransToolTag { public float GizmoRadius = 0.25f; diff --git a/Runtime/Decal/CylindricalDecal.cs b/Runtime/Decal/CylindricalDecal.cs index d03bcbaa..33683e31 100644 --- a/Runtime/Decal/CylindricalDecal.cs +++ b/Runtime/Decal/CylindricalDecal.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/TTT CylindricalDecal")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalDecal")] internal sealed class CylindricalDecal : AbstractSingleDecal { [FormerlySerializedAs("cylindricalCoordinatesSystem")] public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; diff --git a/Runtime/Decal/NailEditor.cs b/Runtime/Decal/NailEditor.cs index 43c0e4fd..4a267101 100644 --- a/Runtime/Decal/NailEditor.cs +++ b/Runtime/Decal/NailEditor.cs @@ -10,7 +10,7 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/OtherDecal/TTT NailEditor")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/TTT NailEditor")] public sealed class NailEditor : AbstractDecal { public Animator TargetAvatar; diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index bcbc26c3..21a8972e 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -7,9 +7,11 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/TTT SimpleDecal")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class SimpleDecal : AbstractSingleDecal { + internal const string ComponentName = "TTT SimpleDecal"; + internal const string MenuPath = ComponentName; public bool FixedAspect = true; [FormerlySerializedAs("SideChek")] public bool SideCulling = true; [FormerlySerializedAs("PolygonCaling")] public PolygonCulling PolygonCulling = PolygonCulling.Vertex; diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index eddab0a9..e6f56298 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -9,9 +9,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT LayerFolder")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class LayerFolder : AbstractLayer { + internal const string ComponentName = "TTT LayerFolder"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public bool PassThrough; internal override void EvaluateTexture(CanvasContext canvasContext) { diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 3313e72c..bd0a4561 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -10,10 +10,12 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - - [AddComponentMenu("TexTransTool/MultiLayer/TTT MultiLayerImageCanvas")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class MultiLayerImageCanvas : TexTransRuntimeBehavior, ITTTChildExclusion { + internal const string FoldoutName = "MultiLayerImage"; + internal const string ComponentName = "TTT MultiLayerImageCanvas"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; internal override List GetRenderers => new List() { TextureSelector.RendererAsPath }; internal override bool IsPossibleApply => TextureSelector.GetTexture() != null; internal override TexTransPhase PhaseDefine => TexTransPhase.BeforeUVModification; diff --git a/Runtime/MultiLayerImage/RasterImportedLayer.cs b/Runtime/MultiLayerImage/RasterImportedLayer.cs index 32942ba9..0903a0f2 100644 --- a/Runtime/MultiLayerImage/RasterImportedLayer.cs +++ b/Runtime/MultiLayerImage/RasterImportedLayer.cs @@ -5,8 +5,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class RasterImportedLayer : AbstractImageLayer { + internal const string ComponentName = "TTT RasterImportedLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public TTTImportedImage ImportedImage; @@ -34,4 +37,4 @@ void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture ori originTexture.WriteOriginalTexture(MaskTexture, renderTexture); } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/RasterLayer.cs b/Runtime/MultiLayerImage/RasterLayer.cs index 0e5ed3d0..90e698c9 100644 --- a/Runtime/MultiLayerImage/RasterLayer.cs +++ b/Runtime/MultiLayerImage/RasterLayer.cs @@ -1,9 +1,11 @@ using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT RasterLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class RasterLayer : AbstractImageLayer { + internal const string ComponentName = "TTT RasterLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Texture2D RasterTexture; public override void GetImage(RenderTexture renderTexture, IOriginTexture originTexture) @@ -11,4 +13,4 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin originTexture.WriteOriginalTexture(RasterTexture, renderTexture); } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs index 06742f4a..011bef7d 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT HSLAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class HSLAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT HSLAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; [Range(-1, 1)] public float Hue; [Range(-1, 1)] public float Saturation; [Range(-1, 1)] public float Lightness; diff --git a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs index 9acb640f..b70f3ebf 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT LevelAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class LevelAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT LevelAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Level RGB; public Level Red; public Level Green; @@ -63,4 +65,4 @@ internal void SetMaterialProperty(Material material) } } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs index eb58d387..c0e6e574 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT SelectiveColoringAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class SelectiveColoringAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT SelectiveColoringAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Vector4 RedsCMYK; public Vector4 YellowsCMYK; public Vector4 GreensCMYK; diff --git a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs index f4d2df7d..410d555a 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs @@ -3,13 +3,15 @@ using static net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT SolidColorLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class SolidColorLayer : AbstractImageLayer { + internal const string ComponentName = "TTT SolidColorLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Color Color; public override void GetImage(RenderTexture renderTexture, IOriginTexture originTexture) { TextureBlend.ColorBlit(renderTexture, Color); } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AbstractResolver.cs b/Runtime/ReferenceResolver/AbstractResolver.cs index baa2b54f..6b24a5d0 100644 --- a/Runtime/ReferenceResolver/AbstractResolver.cs +++ b/Runtime/ReferenceResolver/AbstractResolver.cs @@ -9,5 +9,6 @@ internal abstract class AbstractResolver : MonoBehaviour, ITexTransToolTag public abstract void Resolving(ResolverContext avatar); + internal const string FoldoutName = "Resolver"; } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs index 69320293..7e159b94 100644 --- a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs +++ b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs @@ -6,9 +6,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { [RequireComponent(typeof(AtlasTexture))] [DisallowMultipleComponent] - [AddComponentMenu("TexTransTool/Resolver/TTT AtlasTexture AbsoluteMaterialResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class AddAbsoluteMaterials : AbstractResolver { + internal const string ComponentName = "TTT AtlasTexture AbsoluteMaterialResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public List AddSelectors = new List(); public override void Resolving(ResolverContext avatar) @@ -33,4 +35,4 @@ public override void Resolving(ResolverContext avatar) } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs b/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs index 1b9879c7..b4e1c40d 100644 --- a/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs +++ b/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs @@ -5,9 +5,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { [RequireComponent(typeof(AtlasTexture))] [DisallowMultipleComponent] - [AddComponentMenu("TexTransTool/Resolver/TTT AtlasTexture RootObjectResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RootObject : AbstractResolver { + internal const string ComponentName = "TTT AtlasTexture RootObjectResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; [SerializeField] SelectEnum SelectType; enum SelectEnum @@ -36,4 +38,4 @@ public override void Resolving(ResolverContext avatar) } } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs index d44376ee..8bedec0c 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { - [AddComponentMenu("TexTransTool/Resolver/TTT Decal RendererMultiResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RayCastRendererMultiResolver : AbstractRayCastRendererResolver { + internal const string ComponentName = "TTT Decal RendererMultiResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public GameObject ResolveTargetRoot; public override void Resolving(ResolverContext avatar) @@ -20,4 +22,4 @@ public override void Resolving(ResolverContext avatar) } } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs index a21d075f..8657e4d8 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { - [AddComponentMenu("TexTransTool/Resolver/TTT Decal RendererResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RayCastRendererResolver : AbstractRayCastRendererResolver { + internal const string ComponentName = "TTT Decal RendererResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public AbstractDecal ResolveTarget; public override void Resolving(ResolverContext avatar) @@ -15,4 +17,4 @@ public override void Resolving(ResolverContext avatar) AddToDecal(ResolveTarget, FindRayCast(avatar.AvatarRoot)); } } -} \ No newline at end of file +} diff --git a/Runtime/TexTransBehavior.cs b/Runtime/TexTransBehavior.cs index a6df8355..b33cb3a3 100644 --- a/Runtime/TexTransBehavior.cs +++ b/Runtime/TexTransBehavior.cs @@ -40,6 +40,8 @@ internal void OnDestroy() { DestroyCall.DestroyThis(this); } + + internal const string TTTName = "TexTransTool"; } internal static class DestroyCall diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index c7b8e97d..e7990d34 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -13,9 +13,11 @@ namespace net.rs64.TexTransTool.TextureAtlas { - [AddComponentMenu("TexTransTool/TTT AtlasTexture")] + [AddComponentMenu(TTTName + "/" + MenuPath)] public sealed class AtlasTexture : TexTransRuntimeBehavior { + internal const string ComponentName = "TTT AtlasTexture"; + internal const string MenuPath = ComponentName; public GameObject TargetRoot; public List Renderers => FilteredRenderers(TargetRoot, AtlasSetting.IncludeDisabledRenderer); public List SelectMatList = new List(); From 36d8d6cb0bd30a0b607e06c7846c15bfde7af983 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 13 Mar 2024 02:21:30 +0900 Subject: [PATCH 002/208] feat: create NewGameObjectAndAddTTTComponent --- .../NewGameObjectAndAddTTTComponent.cs | 45 +++++++++++++++++++ .../NewGameObjectAndAddTTTComponent.cs.meta | 11 +++++ 2 files changed, 56 insertions(+) create mode 100644 Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs create mode 100644 Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs new file mode 100644 index 00000000..15a3b843 --- /dev/null +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -0,0 +1,45 @@ +using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.MatAndTexUtils; +using net.rs64.TexTransTool.MultiLayerImage; +using net.rs64.TexTransTool.TextureAtlas; +using UnityEditor; +using UnityEngine; +using M = UnityEditor.MenuItem; + +namespace net.rs64.TexTransTool.Editor.OtherMenuItem +{ + internal class NewGameObjectAndAddTTTComponent + { + static void C() where TTB : MonoBehaviour + { + var parent = Selection.activeGameObject; + var newGameObj = new GameObject(typeof(TTB).Name); + newGameObj.transform.SetParent(parent?.transform); + newGameObj.AddComponent(); + } + const string GOPath = "GameObject"; + const string BP = GOPath + "/" + TexTransBehavior.TTTName + "/"; + + [M(BP + AtlasTexture.MenuPath)] static void AT() => C(); + [M(BP + SimpleDecal.MenuPath)] static void SD() => C(); + + [M(BP + MultiLayerImageCanvas.MenuPath)] static void MLIC() => C(); + [M(BP + LayerFolder.MenuPath)] static void LF() => C(); + [M(BP + RasterLayer.MenuPath)] static void RL() => C(); + [M(BP + RasterImportedLayer.MenuPath)] static void RIL() => C(); + [M(BP + SolidColorLayer.MenuPath)] static void SCL() => C(); + [M(BP + HSLAdjustmentLayer.MenuPath)] static void HAL() => C(); + [M(BP + LevelAdjustmentLayer.MenuPath)] static void LAL() => C(); + [M(BP + SelectiveColoringAdjustmentLayer.MenuPath)] static void SCAL() => C(); + + [M(BP + TexTransGroup.MenuPath)] static void TTG() => C(); + [M(BP + PhaseDefinition.PDMenuPath)] static void PD() => C(); + + [M(BP + PreviewGroup.MenuPath)] static void PG() => C(); + + [M(BP + MatAndTexAbsoluteSeparator.MenuPath)] static void MATAS() => C(); + [M(BP + MatAndTexRelativeSeparator.MenuPath)] static void MATRS() => C(); + [M(BP + MaterialModifier.MenuPath)] static void MM() => C(); + + } +} diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta new file mode 100644 index 00000000..3efef289 --- /dev/null +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2eee72d845c324438a524ee37e60ea7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 1e079904f3ff4a0338b24de86d372baf83b1fb57 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 14 Mar 2024 17:25:45 +0900 Subject: [PATCH 003/208] feat: OptimizingPhase --- Editor/Build/AvatarBuildUtils.cs | 14 ++++++++++---- Editor/Build/NDMF/NDMFPlugin.cs | 18 ++++++++++++------ Editor/Build/NDMF/TTTPass.cs | 14 ++++++++++++++ Editor/Inspector/PreviewGroupEditor.cs | 5 +++++ Runtime/TexTransBehavior.cs | 9 +++++---- Runtime/TextureAtlas/AtlasTexture.cs | 2 +- 6 files changed, 47 insertions(+), 15 deletions(-) diff --git a/Editor/Build/AvatarBuildUtils.cs b/Editor/Build/AvatarBuildUtils.cs index ffe7ac8a..61252cf2 100644 --- a/Editor/Build/AvatarBuildUtils.cs +++ b/Editor/Build/AvatarBuildUtils.cs @@ -33,6 +33,10 @@ public static bool ProcessAvatar(GameObject avatarGameObject, UnityEngine.Object session.ApplyFor(TexTransPhase.AfterUVModification); session.ApplyFor(TexTransPhase.UnDefined); + session.MidwayMergeStack(); + + session.ApplyFor(TexTransPhase.Optimizing); + session.TTTSessionEnd(); timer.Stop(); Debug.Log($"ProcessAvatarTime : {timer.ElapsedMilliseconds}ms"); return true; @@ -107,10 +111,11 @@ public void TTTSessionEnd() public static Dictionary> FindAtPhase(GameObject avatarGameObject) { var phaseDict = new Dictionary>(){ - {TexTransPhase.UnDefined,new List()}, {TexTransPhase.BeforeUVModification,new List()}, {TexTransPhase.UVModification,new List()}, - {TexTransPhase.AfterUVModification,new List()} + {TexTransPhase.AfterUVModification,new List()}, + {TexTransPhase.UnDefined,new List()}, + {TexTransPhase.Optimizing,new List()}, }; var phaseDefinitions = avatarGameObject.GetComponentsInChildren(); @@ -160,10 +165,11 @@ static void PhaseRegister(TexTransGroup absTTG, Dictionary> FindAtPhaseAll(GameObject avatarGameObject) { var phaseDict = new Dictionary>(){ - {TexTransPhase.UnDefined,new List()}, {TexTransPhase.BeforeUVModification,new List()}, {TexTransPhase.UVModification,new List()}, - {TexTransPhase.AfterUVModification,new List()} + {TexTransPhase.AfterUVModification,new List()}, + {TexTransPhase.UnDefined,new List()}, + {TexTransPhase.Optimizing,new List()}, }; var phaseDefinitions = avatarGameObject.GetComponentsInChildren(true); diff --git a/Editor/Build/NDMF/NDMFPlugin.cs b/Editor/Build/NDMF/NDMFPlugin.cs index 45082500..1f39a889 100644 --- a/Editor/Build/NDMF/NDMFPlugin.cs +++ b/Editor/Build/NDMF/NDMFPlugin.cs @@ -28,12 +28,18 @@ protected override void Configure() seq.BeforePlugin("io.github.azukimochi.light-limit-changer"); seq.WithRequiredExtension(typeof(TexTransToolContext), s => { - seq.Run(FindAtPhasePass.Instance); - seq.Run(BeforeUVModificationPass.Instance); - seq.Run(MidwayMergeStackPass.Instance); - seq.Run(UVModificationPass.Instance); - seq.Run(AfterUVModificationPass.Instance); - seq.Run(UnDefinedPass.Instance); + seq.Run(FindAtPhasePass.Instance).Then + .Run(BeforeUVModificationPass.Instance).Then + + .Run(MidwayMergeStackPass.Instance).Then + + .Run(UVModificationPass.Instance).Then + .Run(AfterUVModificationPass.Instance).Then + .Run(UnDefinedPass.Instance).Then + + .Run(BeforeOptimizingMergeStackPass.Instance).Then + + .Run(OptimizingPass.Instance); }); } diff --git a/Editor/Build/NDMF/TTTPass.cs b/Editor/Build/NDMF/TTTPass.cs index ffd82b48..e36c0b94 100644 --- a/Editor/Build/NDMF/TTTPass.cs +++ b/Editor/Build/NDMF/TTTPass.cs @@ -72,4 +72,18 @@ protected override void Execute(BuildContext context) TTTContext(context).ApplyFor(TexTransPhase.UnDefined); } } + internal class BeforeOptimizingMergeStackPass : TTTPass + { + protected override void Execute(BuildContext context) + { + TTTContext(context).MidwayMergeStack(); + } + } + internal class OptimizingPass : TTTPass + { + protected override void Execute(BuildContext context) + { + TTTContext(context).ApplyFor(TexTransPhase.Optimizing); + } + } } diff --git a/Editor/Inspector/PreviewGroupEditor.cs b/Editor/Inspector/PreviewGroupEditor.cs index 5d2acd69..f5bd08b6 100644 --- a/Editor/Inspector/PreviewGroupEditor.cs +++ b/Editor/Inspector/PreviewGroupEditor.cs @@ -56,6 +56,11 @@ void CrateGroupElements() label.style.fontSize = 16f; rootVE.hierarchy.Add(label); CreateGroupElements(rootVE, phase[TexTransPhase.UnDefined], true); + + label = new Label(TexTransPhase.Optimizing.ToString()); + label.style.fontSize = 16f; + rootVE.hierarchy.Add(label); + CreateGroupElements(rootVE, phase[TexTransPhase.Optimizing], true); } } diff --git a/Runtime/TexTransBehavior.cs b/Runtime/TexTransBehavior.cs index a6df8355..5542fd46 100644 --- a/Runtime/TexTransBehavior.cs +++ b/Runtime/TexTransBehavior.cs @@ -51,9 +51,10 @@ internal static class DestroyCall public enum TexTransPhase { - UnDefined, - BeforeUVModification, - UVModification, - AfterUVModification, + BeforeUVModification = 1, + UVModification = 2, + AfterUVModification = 3, + UnDefined = 0, + Optimizing = 4, } } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index d2da3b57..059b460d 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -26,7 +26,7 @@ public sealed class AtlasTexture : TexTransRuntimeBehavior internal override List GetRenderers => Renderers; - internal override TexTransPhase PhaseDefine => TexTransPhase.UVModification; + internal override TexTransPhase PhaseDefine => TexTransPhase.Optimizing; #region V0SaveData [Obsolete("V0SaveData", true)] public List MigrationV0ObsoleteChannelsRef; From a935f6399ed2f9db330a44244f47380995ccc14d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 14 Mar 2024 17:27:58 +0900 Subject: [PATCH 004/208] chore: update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffe23c63..3a1f1d49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Optimizing Phase が追加されました (#410) + ### Changed +- AtlasTexture が UVModification から Optimizing にフェーズの定義が変更されました。 (#410) + ### Removed ### Fixed From fe92c7b196c7407ed1331a4866c1e6c5f125ddda Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 13 Mar 2024 02:21:09 +0900 Subject: [PATCH 005/208] chore: refactor AddComponentMenu Defines --- .../MatAndTexUtils/MatAndTexAbsoluteSeparator.cs | 5 ++++- .../MatAndTexUtils/MatAndTexRelativeSeparator.cs | 4 +++- .../CommonComponent/MatAndTexUtils/MaterialModifier.cs | 6 ++++-- Runtime/CommonComponent/PhaseDefinition.cs | 6 ++++-- Runtime/CommonComponent/PreviewGroup.cs | 5 ++++- Runtime/CommonComponent/PreviewRenderer.cs | 5 ++++- Runtime/CommonComponent/TexTransGroup.cs | 6 +++++- Runtime/CommonComponent/TextureBlender.cs | 9 ++++++--- Runtime/Decal/Curve/CurveSegment.cs | 2 +- Runtime/Decal/Curve/CylindricalCurveDecal.cs | 4 ++-- .../Decal/Cylindrical/CylindricalCoordinatesSystem.cs | 2 +- Runtime/Decal/CylindricalDecal.cs | 2 +- Runtime/Decal/NailEditor.cs | 2 +- Runtime/Decal/SimpleDecal.cs | 4 +++- Runtime/MultiLayerImage/LayerFolder.cs | 4 +++- Runtime/MultiLayerImage/MultiLayerImageCanvas.cs | 6 ++++-- Runtime/MultiLayerImage/RasterImportedLayer.cs | 5 ++++- Runtime/MultiLayerImage/RasterLayer.cs | 6 ++++-- .../MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs | 4 +++- .../MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs | 6 ++++-- .../SpecialLayer/SelectiveColorAdjustmentLayer.cs | 4 +++- Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs | 6 ++++-- Runtime/ReferenceResolver/AbstractResolver.cs | 3 ++- .../AtlasTexture/AddAbsoluteMaterials.cs | 6 ++++-- Runtime/ReferenceResolver/AtlasTexture/RootObject.cs | 6 ++++-- .../Decal/RayCastRendererMultiResolver.cs | 6 ++++-- .../ReferenceResolver/Decal/RayCastRendererResolver.cs | 6 ++++-- Runtime/TexTransBehavior.cs | 2 ++ Runtime/TextureAtlas/AtlasTexture.cs | 4 +++- 29 files changed, 95 insertions(+), 41 deletions(-) diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs index 0e66cc35..0d4188e8 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs @@ -5,9 +5,12 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MatAndTexAbsoluteSeparator")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MatAndTexAbsoluteSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator { + internal const string FoldoutName = "MatAndTexUtils"; + internal const string ComponentName = "TTT MatAndTexAbsoluteSeparator"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs index 6c21a3ec..e59f347e 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs @@ -5,9 +5,11 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MatAndTexRelativeSeparator")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MatAndTexRelativeSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator { + internal const string ComponentName = "TTT MatAndTexRelativeSeparator"; + internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index 8d38f3a5..e25bd878 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -7,9 +7,11 @@ namespace net.rs64.TexTransTool.MatAndTexUtils { - [AddComponentMenu("TexTransTool/MatAndTexUtils/TTT MaterialModifier")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class MaterialModifier : TexTransRuntimeBehavior { + internal const string ComponentName = "TTT MaterialModifier"; + internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; public List TargetRenderers = new List { null }; public bool MultiRendererMode = false; internal override List GetRenderers => TargetRenderers; @@ -92,4 +94,4 @@ internal override void Apply([NotNull] IDomain domain) domain.ReplaceMaterials(modMatList); } } -} \ No newline at end of file +} diff --git a/Runtime/CommonComponent/PhaseDefinition.cs b/Runtime/CommonComponent/PhaseDefinition.cs index 73970dfb..e01f8e74 100644 --- a/Runtime/CommonComponent/PhaseDefinition.cs +++ b/Runtime/CommonComponent/PhaseDefinition.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Group/TTT PhaseDefinition")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + PDMenuPath)] public sealed class PhaseDefinition : TexTransGroup { + internal const string PDName = "TTT PhaseDefinition"; + internal const string PDMenuPath = TexTransGroup.FoldoutName + "/" + PDName; public TexTransPhase TexTransPhase; } -} \ No newline at end of file +} diff --git a/Runtime/CommonComponent/PreviewGroup.cs b/Runtime/CommonComponent/PreviewGroup.cs index d32397f1..f7f0d850 100644 --- a/Runtime/CommonComponent/PreviewGroup.cs +++ b/Runtime/CommonComponent/PreviewGroup.cs @@ -3,9 +3,12 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/PreviewUtility/TTT PreviewGroup")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class PreviewGroup : TexTransCallEditorBehavior { + internal const string FoldoutName = "PreviewUtility"; + internal const string ComponentName = "TTT PreviewGroup"; + internal const string MenuPath = PreviewGroup.FoldoutName + "/" + ComponentName; internal override List GetRenderers => null; internal override bool IsPossibleApply => true; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; diff --git a/Runtime/CommonComponent/PreviewRenderer.cs b/Runtime/CommonComponent/PreviewRenderer.cs index b66e275d..8d1a1d0b 100644 --- a/Runtime/CommonComponent/PreviewRenderer.cs +++ b/Runtime/CommonComponent/PreviewRenderer.cs @@ -3,10 +3,13 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/PreviewUtility/TTT PreviewRenderer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] [RequireComponent(typeof(Renderer))] public sealed class PreviewRenderer : TexTransCallEditorBehavior { + internal const string ComponentName = "TTT PreviewRenderer"; + internal const string MenuPath = PreviewGroup.FoldoutName + "/" + ComponentName; + internal override List GetRenderers => null; internal override bool IsPossibleApply => true; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; diff --git a/Runtime/CommonComponent/TexTransGroup.cs b/Runtime/CommonComponent/TexTransGroup.cs index 48077fed..51d07907 100644 --- a/Runtime/CommonComponent/TexTransGroup.cs +++ b/Runtime/CommonComponent/TexTransGroup.cs @@ -5,9 +5,13 @@ namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Group/TTT TexTransGroup")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class TexTransGroup : TexTransCallEditorBehavior { + internal const string FoldoutName = "Group"; + internal const string ComponentName = "TTT TexTransGroup"; + internal const string MenuPath = TexTransGroup.FoldoutName + "/" + ComponentName; + internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; internal IEnumerable Targets => transform.GetChildren().Select(x => x.GetComponent()).Where(x => x != null); diff --git a/Runtime/CommonComponent/TextureBlender.cs b/Runtime/CommonComponent/TextureBlender.cs index 3a465293..ca95f433 100644 --- a/Runtime/CommonComponent/TextureBlender.cs +++ b/Runtime/CommonComponent/TextureBlender.cs @@ -5,12 +5,15 @@ using net.rs64.TexTransTool.Utils; namespace net.rs64.TexTransTool { - [AddComponentMenu("TexTransTool/Other/TTT TextureBlender")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class TextureBlender : TexTransRuntimeBehavior { + internal const string FoldoutName = "Other"; + internal const string ComponentName = "TTT TextureBlender"; + internal const string MenuPath = TextureBlender.FoldoutName + "/" + ComponentName; public TextureSelector TargetTexture; - [ExpandTexture2D]public Texture2D BlendTexture; + [ExpandTexture2D] public Texture2D BlendTexture; public Color Color = Color.white; [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; @@ -34,4 +37,4 @@ internal override void Apply(IDomain domain) domain.AddTextureStack(distTex, new(addTex, BlendTypeKey)); } } -} \ No newline at end of file +} diff --git a/Runtime/Decal/Curve/CurveSegment.cs b/Runtime/Decal/Curve/CurveSegment.cs index a47010ae..cf083b3b 100644 --- a/Runtime/Decal/Curve/CurveSegment.cs +++ b/Runtime/Decal/Curve/CurveSegment.cs @@ -3,7 +3,7 @@ namespace net.rs64.TexTransTool.Decal.Curve { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/Unfinished/TTT CurveSegment")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CurveSegment")] internal class CurveSegment : MonoBehaviour, ITexTransToolTag { [HideInInspector,SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; diff --git a/Runtime/Decal/Curve/CylindricalCurveDecal.cs b/Runtime/Decal/Curve/CylindricalCurveDecal.cs index 8ccde62d..ace6b578 100644 --- a/Runtime/Decal/Curve/CylindricalCurveDecal.cs +++ b/Runtime/Decal/Curve/CylindricalCurveDecal.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal.Curve { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/Unfinished/TTT CylindricalCurveDecal")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CylindricalCurveDecal")] internal class CylindricalCurveDecal : CurveDecal { public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; @@ -114,4 +114,4 @@ protected virtual void DrawerGizmo() } } -} \ No newline at end of file +} diff --git a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs index cce0ce95..baef90c9 100644 --- a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs +++ b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal.Cylindrical { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/TTT CylindricalCoordinatesSystem")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalCoordinatesSystem")] internal class CylindricalCoordinatesSystem : MonoBehaviour, ITexTransToolTag { public float GizmoRadius = 0.25f; diff --git a/Runtime/Decal/CylindricalDecal.cs b/Runtime/Decal/CylindricalDecal.cs index d03bcbaa..33683e31 100644 --- a/Runtime/Decal/CylindricalDecal.cs +++ b/Runtime/Decal/CylindricalDecal.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/OtherDecal/Cylindrical/TTT CylindricalDecal")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalDecal")] internal sealed class CylindricalDecal : AbstractSingleDecal { [FormerlySerializedAs("cylindricalCoordinatesSystem")] public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; diff --git a/Runtime/Decal/NailEditor.cs b/Runtime/Decal/NailEditor.cs index 43c0e4fd..4a267101 100644 --- a/Runtime/Decal/NailEditor.cs +++ b/Runtime/Decal/NailEditor.cs @@ -10,7 +10,7 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/OtherDecal/TTT NailEditor")] + [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/TTT NailEditor")] public sealed class NailEditor : AbstractDecal { public Animator TargetAvatar; diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index bcbc26c3..21a8972e 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -7,9 +7,11 @@ namespace net.rs64.TexTransTool.Decal { - [AddComponentMenu("TexTransTool/TTT SimpleDecal")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class SimpleDecal : AbstractSingleDecal { + internal const string ComponentName = "TTT SimpleDecal"; + internal const string MenuPath = ComponentName; public bool FixedAspect = true; [FormerlySerializedAs("SideChek")] public bool SideCulling = true; [FormerlySerializedAs("PolygonCaling")] public PolygonCulling PolygonCulling = PolygonCulling.Vertex; diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index eddab0a9..e6f56298 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -9,9 +9,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT LayerFolder")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class LayerFolder : AbstractLayer { + internal const string ComponentName = "TTT LayerFolder"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public bool PassThrough; internal override void EvaluateTexture(CanvasContext canvasContext) { diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 3313e72c..bd0a4561 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -10,10 +10,12 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - - [AddComponentMenu("TexTransTool/MultiLayer/TTT MultiLayerImageCanvas")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class MultiLayerImageCanvas : TexTransRuntimeBehavior, ITTTChildExclusion { + internal const string FoldoutName = "MultiLayerImage"; + internal const string ComponentName = "TTT MultiLayerImageCanvas"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; internal override List GetRenderers => new List() { TextureSelector.RendererAsPath }; internal override bool IsPossibleApply => TextureSelector.GetTexture() != null; internal override TexTransPhase PhaseDefine => TexTransPhase.BeforeUVModification; diff --git a/Runtime/MultiLayerImage/RasterImportedLayer.cs b/Runtime/MultiLayerImage/RasterImportedLayer.cs index 32942ba9..0903a0f2 100644 --- a/Runtime/MultiLayerImage/RasterImportedLayer.cs +++ b/Runtime/MultiLayerImage/RasterImportedLayer.cs @@ -5,8 +5,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class RasterImportedLayer : AbstractImageLayer { + internal const string ComponentName = "TTT RasterImportedLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public TTTImportedImage ImportedImage; @@ -34,4 +37,4 @@ void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture ori originTexture.WriteOriginalTexture(MaskTexture, renderTexture); } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/RasterLayer.cs b/Runtime/MultiLayerImage/RasterLayer.cs index 0e5ed3d0..90e698c9 100644 --- a/Runtime/MultiLayerImage/RasterLayer.cs +++ b/Runtime/MultiLayerImage/RasterLayer.cs @@ -1,9 +1,11 @@ using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT RasterLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class RasterLayer : AbstractImageLayer { + internal const string ComponentName = "TTT RasterLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Texture2D RasterTexture; public override void GetImage(RenderTexture renderTexture, IOriginTexture originTexture) @@ -11,4 +13,4 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin originTexture.WriteOriginalTexture(RasterTexture, renderTexture); } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs index 06742f4a..011bef7d 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT HSLAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class HSLAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT HSLAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; [Range(-1, 1)] public float Hue; [Range(-1, 1)] public float Saturation; [Range(-1, 1)] public float Lightness; diff --git a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs index 9acb640f..b70f3ebf 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT LevelAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class LevelAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT LevelAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Level RGB; public Level Red; public Level Green; @@ -63,4 +65,4 @@ internal void SetMaterialProperty(Material material) } } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs index eb58d387..c0e6e574 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs @@ -2,9 +2,11 @@ namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT SelectiveColoringAdjustmentLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class SelectiveColoringAdjustmentLayer : AbstractGrabLayer { + internal const string ComponentName = "TTT SelectiveColoringAdjustmentLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Vector4 RedsCMYK; public Vector4 YellowsCMYK; public Vector4 GreensCMYK; diff --git a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs index f4d2df7d..410d555a 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs @@ -3,13 +3,15 @@ using static net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.MultiLayerImage { - [AddComponentMenu("TexTransTool/MultiLayer/TTT SolidColorLayer")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public sealed class SolidColorLayer : AbstractImageLayer { + internal const string ComponentName = "TTT SolidColorLayer"; + internal const string MenuPath = MultiLayerImageCanvas.FoldoutName + "/" + ComponentName; public Color Color; public override void GetImage(RenderTexture renderTexture, IOriginTexture originTexture) { TextureBlend.ColorBlit(renderTexture, Color); } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AbstractResolver.cs b/Runtime/ReferenceResolver/AbstractResolver.cs index baa2b54f..6b24a5d0 100644 --- a/Runtime/ReferenceResolver/AbstractResolver.cs +++ b/Runtime/ReferenceResolver/AbstractResolver.cs @@ -9,5 +9,6 @@ internal abstract class AbstractResolver : MonoBehaviour, ITexTransToolTag public abstract void Resolving(ResolverContext avatar); + internal const string FoldoutName = "Resolver"; } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs index 69320293..7e159b94 100644 --- a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs +++ b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs @@ -6,9 +6,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { [RequireComponent(typeof(AtlasTexture))] [DisallowMultipleComponent] - [AddComponentMenu("TexTransTool/Resolver/TTT AtlasTexture AbsoluteMaterialResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class AddAbsoluteMaterials : AbstractResolver { + internal const string ComponentName = "TTT AtlasTexture AbsoluteMaterialResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public List AddSelectors = new List(); public override void Resolving(ResolverContext avatar) @@ -33,4 +35,4 @@ public override void Resolving(ResolverContext avatar) } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs b/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs index 1b9879c7..b4e1c40d 100644 --- a/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs +++ b/Runtime/ReferenceResolver/AtlasTexture/RootObject.cs @@ -5,9 +5,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { [RequireComponent(typeof(AtlasTexture))] [DisallowMultipleComponent] - [AddComponentMenu("TexTransTool/Resolver/TTT AtlasTexture RootObjectResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RootObject : AbstractResolver { + internal const string ComponentName = "TTT AtlasTexture RootObjectResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; [SerializeField] SelectEnum SelectType; enum SelectEnum @@ -36,4 +38,4 @@ public override void Resolving(ResolverContext avatar) } } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs index d44376ee..8bedec0c 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { - [AddComponentMenu("TexTransTool/Resolver/TTT Decal RendererMultiResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RayCastRendererMultiResolver : AbstractRayCastRendererResolver { + internal const string ComponentName = "TTT Decal RendererMultiResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public GameObject ResolveTargetRoot; public override void Resolving(ResolverContext avatar) @@ -20,4 +22,4 @@ public override void Resolving(ResolverContext avatar) } } } -} \ No newline at end of file +} diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs index a21d075f..8657e4d8 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs @@ -3,9 +3,11 @@ namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver { - [AddComponentMenu("TexTransTool/Resolver/TTT Decal RendererResolver")] + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] internal class RayCastRendererResolver : AbstractRayCastRendererResolver { + internal const string ComponentName = "TTT Decal RendererResolver"; + private const string MenuPath = FoldoutName + "/" + ComponentName; public AbstractDecal ResolveTarget; public override void Resolving(ResolverContext avatar) @@ -15,4 +17,4 @@ public override void Resolving(ResolverContext avatar) AddToDecal(ResolveTarget, FindRayCast(avatar.AvatarRoot)); } } -} \ No newline at end of file +} diff --git a/Runtime/TexTransBehavior.cs b/Runtime/TexTransBehavior.cs index 5542fd46..c7d20a7b 100644 --- a/Runtime/TexTransBehavior.cs +++ b/Runtime/TexTransBehavior.cs @@ -40,6 +40,8 @@ internal void OnDestroy() { DestroyCall.DestroyThis(this); } + + internal const string TTTName = "TexTransTool"; } internal static class DestroyCall diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 059b460d..e35a8c3e 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -13,9 +13,11 @@ namespace net.rs64.TexTransTool.TextureAtlas { - [AddComponentMenu("TexTransTool/TTT AtlasTexture")] + [AddComponentMenu(TTTName + "/" + MenuPath)] public sealed class AtlasTexture : TexTransRuntimeBehavior { + internal const string ComponentName = "TTT AtlasTexture"; + internal const string MenuPath = ComponentName; public GameObject TargetRoot; public List Renderers => FilteredRenderers(TargetRoot, AtlasSetting.IncludeDisabledRenderer); public List SelectMatList = new List(); From 9435563c53d51ecd8079f298cb9c1fd6a67364f5 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 13 Mar 2024 02:21:30 +0900 Subject: [PATCH 006/208] feat: create NewGameObjectAndAddTTTComponent --- .../NewGameObjectAndAddTTTComponent.cs | 45 +++++++++++++++++++ .../NewGameObjectAndAddTTTComponent.cs.meta | 11 +++++ 2 files changed, 56 insertions(+) create mode 100644 Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs create mode 100644 Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs new file mode 100644 index 00000000..15a3b843 --- /dev/null +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -0,0 +1,45 @@ +using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.MatAndTexUtils; +using net.rs64.TexTransTool.MultiLayerImage; +using net.rs64.TexTransTool.TextureAtlas; +using UnityEditor; +using UnityEngine; +using M = UnityEditor.MenuItem; + +namespace net.rs64.TexTransTool.Editor.OtherMenuItem +{ + internal class NewGameObjectAndAddTTTComponent + { + static void C() where TTB : MonoBehaviour + { + var parent = Selection.activeGameObject; + var newGameObj = new GameObject(typeof(TTB).Name); + newGameObj.transform.SetParent(parent?.transform); + newGameObj.AddComponent(); + } + const string GOPath = "GameObject"; + const string BP = GOPath + "/" + TexTransBehavior.TTTName + "/"; + + [M(BP + AtlasTexture.MenuPath)] static void AT() => C(); + [M(BP + SimpleDecal.MenuPath)] static void SD() => C(); + + [M(BP + MultiLayerImageCanvas.MenuPath)] static void MLIC() => C(); + [M(BP + LayerFolder.MenuPath)] static void LF() => C(); + [M(BP + RasterLayer.MenuPath)] static void RL() => C(); + [M(BP + RasterImportedLayer.MenuPath)] static void RIL() => C(); + [M(BP + SolidColorLayer.MenuPath)] static void SCL() => C(); + [M(BP + HSLAdjustmentLayer.MenuPath)] static void HAL() => C(); + [M(BP + LevelAdjustmentLayer.MenuPath)] static void LAL() => C(); + [M(BP + SelectiveColoringAdjustmentLayer.MenuPath)] static void SCAL() => C(); + + [M(BP + TexTransGroup.MenuPath)] static void TTG() => C(); + [M(BP + PhaseDefinition.PDMenuPath)] static void PD() => C(); + + [M(BP + PreviewGroup.MenuPath)] static void PG() => C(); + + [M(BP + MatAndTexAbsoluteSeparator.MenuPath)] static void MATAS() => C(); + [M(BP + MatAndTexRelativeSeparator.MenuPath)] static void MATRS() => C(); + [M(BP + MaterialModifier.MenuPath)] static void MM() => C(); + + } +} diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta new file mode 100644 index 00000000..3efef289 --- /dev/null +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2eee72d845c324438a524ee37e60ea7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 1555b0e1cdc60a0c7c73dbcbf089321133be9dd2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 14 Mar 2024 17:32:40 +0900 Subject: [PATCH 007/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a1f1d49..afa078cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Optimizing Phase が追加されました (#410) +- GameObject から TexTransTool のほとんどのコンポーネントが追加できるようになりました (#411) ### Changed From 150bf1ca16a3acb65734c6efaffa472d343d4703 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 16 Mar 2024 14:54:35 +0900 Subject: [PATCH 008/208] feat: create AbstractIslandSelector --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 19 +------ Runtime/Decal/IslandSelectToPPFilter.cs | 53 +++++++++++++++++++ .../Decal/IslandSelectToPPFilter.cs.meta | 2 +- Runtime/Decal/SimpleDecal.cs | 34 +++++------- Runtime/IslandSelect.meta | 8 +++ .../IslandSelect/AbstructIslandSelector.cs | 40 ++++++++++++++ .../AbstructIslandSelector.cs.meta | 11 ++++ Runtime/IslandSelect/IslandSelectOR.cs | 19 +++++++ Runtime/IslandSelect/IslandSelectOR.cs.meta | 11 ++++ Runtime/IslandSelect/IslandSelectorAND.cs | 19 +++++++ .../IslandSelect/IslandSelectorAND.cs.meta | 11 ++++ Runtime/IslandSelect/SphereIslandSelector.cs | 28 ++++++++++ .../IslandSelect/SphereIslandSelector.cs.meta | 11 ++++ TexTransCore/Decal/DecalUtility.cs | 28 +++++----- .../IslandCullingPPFilter.cs | 31 ----------- .../ParallelProjectionFilter.cs | 16 +++--- TexTransCore/Island/IslandCulling.cs | 6 +-- 17 files changed, 251 insertions(+), 96 deletions(-) create mode 100644 Runtime/Decal/IslandSelectToPPFilter.cs rename TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs.meta => Runtime/Decal/IslandSelectToPPFilter.cs.meta (83%) create mode 100644 Runtime/IslandSelect.meta create mode 100644 Runtime/IslandSelect/AbstructIslandSelector.cs create mode 100644 Runtime/IslandSelect/AbstructIslandSelector.cs.meta create mode 100644 Runtime/IslandSelect/IslandSelectOR.cs create mode 100644 Runtime/IslandSelect/IslandSelectOR.cs.meta create mode 100644 Runtime/IslandSelect/IslandSelectorAND.cs create mode 100644 Runtime/IslandSelect/IslandSelectorAND.cs.meta create mode 100644 Runtime/IslandSelect/SphereIslandSelector.cs create mode 100644 Runtime/IslandSelect/SphereIslandSelector.cs.meta delete mode 100644 TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 6c9b34be..436e3e4e 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -45,23 +45,8 @@ public override void OnInspectorGUI() s_ExperimentalFutureOption = EditorGUILayout.Foldout(s_ExperimentalFutureOption, "Common:ExperimentalFuture".Glc()); if (s_ExperimentalFutureOption) { - var sIslandCulling = thisSObject.FindProperty("IslandCulling"); - EditorGUILayout.PropertyField(sIslandCulling, "SimpleDecal:prop:ExperimentalFuture:IslandCulling".Glc()); - if (sIslandCulling.boolValue) - { - var sIslandSelectorPos = thisSObject.FindProperty("IslandSelectorPos"); - EditorGUI.indentLevel += 1; - EditorGUILayout.LabelField("SimpleDecal:prop:ExperimentalFuture:IslandSelectorPos".Glc()); - EditorGUI.indentLevel += 1; - var sIslandSelectorPosX = sIslandSelectorPos.FindPropertyRelative("x"); - var sIslandSelectorPosY = sIslandSelectorPos.FindPropertyRelative("y"); - EditorGUILayout.Slider(sIslandSelectorPosX, 0, 1, new GUIContent("x")); - EditorGUILayout.Slider(sIslandSelectorPosY, 0, 1, new GUIContent("y")); - EditorGUI.indentLevel -= 1; - var sIslandSelectorRange = thisSObject.FindProperty("IslandSelectorRange"); - EditorGUILayout.Slider(sIslandSelectorRange, 0, 1, "SimpleDecal:prop:ExperimentalFuture:IslandSelectorRange".Glc()); - EditorGUI.indentLevel -= 1; - } + var sIslandSelector = thisSObject.FindProperty("IslandSelector"); + EditorGUILayout.PropertyField(sIslandSelector); var sUseDepth = thisSObject.FindProperty("UseDepth"); var sDepthInvert = thisSObject.FindProperty("DepthInvert"); diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs new file mode 100644 index 00000000..6f281e17 --- /dev/null +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using UnityEngine; +using net.rs64.TexTransTool.Decal.Cylindrical; +using net.rs64.TexTransCore.Decal; +using net.rs64.TexTransTool.Utils; +using UnityEngine.Serialization; +using net.rs64.TexTransCore.Island; +using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransTool.IslandSelector; +using System.Linq; + +namespace net.rs64.TexTransTool.Decal +{ + internal class IslandSelectToPPFilter : DecalUtility.ITrianglesFilter + { + public List>> Filters; + public AbstractIslandSelector IslandSelector; + + + public IslandSelectToPPFilter(AbstractIslandSelector islandSelector, List>> filters) + { + IslandSelector = islandSelector; + Filters = filters; + } + + ParallelProjectionSpace _parallelProjectionSpace; + + public void SetSpace(ParallelProjectionSpace space) { _parallelProjectionSpace = space; } + + public List GetFilteredSubTriangle(int subMeshIndex) + { + if (_parallelProjectionSpace is null) { return null; } + + var meshData = _parallelProjectionSpace.MeshData; + var islands = IslandUtility.UVtoIsland(meshData.TrianglesSubMesh[subMeshIndex], meshData.UV); + + var description = new AbstractIslandSelector.IslandDescription(meshData.Vertex.ToArray(), meshData.UV.ToArray(), meshData.RendererRef, subMeshIndex); + + var islandsCount = islands.Count; + var islandDict = new Dictionary(islandsCount); + var islandDescription = new Dictionary(islandsCount); + for (var i = 0; islandsCount > i; i += 1) + { + islandDict[i] = islands[i]; + islandDescription[i] = description; + } + + var hash = IslandSelector.IslandSelect(islandDict, islandDescription); + + return TriangleFilterUtility.FilteringTriangle(hash.SelectMany(i => islandDict[i].triangles).ToList(), _parallelProjectionSpace.PPSVert, Filters); + } + } +} diff --git a/TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs.meta b/Runtime/Decal/IslandSelectToPPFilter.cs.meta similarity index 83% rename from TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs.meta rename to Runtime/Decal/IslandSelectToPPFilter.cs.meta index 1baf78b7..23d74c61 100644 --- a/TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs.meta +++ b/Runtime/Decal/IslandSelectToPPFilter.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7fcbdaf10b0548948850dcac8f788553 +guid: b3c064ad5c612f8458dc3a8d673eecb2 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 29783389..0e673fbe 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -4,6 +4,8 @@ using net.rs64.TexTransCore.Decal; using net.rs64.TexTransCore.Island; using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransTool.IslandSelector; +using System; namespace net.rs64.TexTransTool.Decal { @@ -16,18 +18,25 @@ public sealed class SimpleDecal : AbstractSingleDecal UseDepth ? new bool?(DepthInvert) : null; + + #region V3SaveData + [Obsolete("V3SaveData", true)][SerializeField] internal bool IslandCulling = false; + [Obsolete("V3SaveData", true)][SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); + [Obsolete("V3SaveData", true)][SerializeField] internal float IslandSelectorRange = 1; + #endregion + + internal override ParallelProjectionSpace GetSpaceConverter() { return new ParallelProjectionSpace(transform.worldToLocalMatrix); } internal override DecalUtility.ITrianglesFilter GetTriangleFilter() { - if (IslandCulling) { return new IslandCullingPPFilter(GetFilter(), GetIslandSelector()); } - else { return new ParallelProjectionFilter(GetFilter()); } + if (IslandSelector != null) { return new IslandSelectToPPFilter(IslandSelector, GetFilter()); } + return new ParallelProjectionFilter(GetFilter()); + } internal List>> GetFilter() @@ -43,14 +52,6 @@ internal override DecalUtility.ITrianglesFilter GetTria return filters; } - internal List GetIslandSelector() - { - if (!IslandCulling) return null; - return new List() { - new IslandSelector(new Ray(transform.localToWorldMatrix.MultiplyPoint3x4(IslandSelectorPos - new Vector2(0.5f, 0.5f)), transform.forward), transform.localScale.z * IslandSelectorRange) - }; - } - internal void OnDrawGizmosSelected() { Gizmos.color = Color.black; @@ -63,13 +64,6 @@ internal void OnDrawGizmosSelected() DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, matrix); - - if (IslandCulling) - { - Vector3 selectorOrigin = new Vector2(IslandSelectorPos.x - 0.5f, IslandSelectorPos.y - 0.5f); - var selectorTail = (Vector3.forward * IslandSelectorRange) + selectorOrigin; - Gizmos.DrawLine(selectorOrigin, selectorTail); - } } } } diff --git a/Runtime/IslandSelect.meta b/Runtime/IslandSelect.meta new file mode 100644 index 00000000..707bd62e --- /dev/null +++ b/Runtime/IslandSelect.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2108ba7386c168b4786f682273ad4ad9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs new file mode 100644 index 00000000..f1678da8 --- /dev/null +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -0,0 +1,40 @@ +using UnityEngine; +using net.rs64.TexTransTool; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag + { + [HideInInspector, SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; + int ITexTransToolTag.SaveDataVersion => _saveDataVersion; + + internal abstract HashSet IslandSelect(Dictionary islands, Dictionary islandDescription); + + internal readonly struct IslandDescription + { + public readonly Vector3[] Position;//ワールドスペース + public readonly Vector2[] UV; + public readonly Renderer Renderer; + public readonly int MaterialSlot; + + public IslandDescription(Vector3[] position, Vector2[] uV, Renderer renderer, int materialSlot) : this() + { + Position = position; + UV = uV; + Renderer = renderer; + MaterialSlot = materialSlot; + } + + } + + /* + 頂点の持つ情報 + レンダラー + レンダラーから見た時のスロット (マテリアルはここから調べるように) + */ + + + } +} diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs.meta b/Runtime/IslandSelect/AbstructIslandSelector.cs.meta new file mode 100644 index 00000000..48d5245c --- /dev/null +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5d4155752213b634bb0401dca6715b03 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectOR.cs b/Runtime/IslandSelect/IslandSelectOR.cs new file mode 100644 index 00000000..69a73010 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectOR.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public class IslandSelectOR : AbstractIslandSelector + { + public List IslandSelectors; + internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) + { + var islandHash = new HashSet(islands.Count); + foreach (var selector in IslandSelectors) + { + islandHash.UnionWith(selector.IslandSelect(islands, islandDescription)); + } + return islandHash; + } + } +} diff --git a/Runtime/IslandSelect/IslandSelectOR.cs.meta b/Runtime/IslandSelect/IslandSelectOR.cs.meta new file mode 100644 index 00000000..ec68e9bc --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectOR.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8bce7cd6bc9815843a229364be81a0ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs new file mode 100644 index 00000000..8a432880 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public class IslandSelectorAND : AbstractIslandSelector + { + public List IslandSelectors; + internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) + { + var islandHash = new HashSet(islands.Keys); + foreach (var selector in IslandSelectors) + { + islandHash.IntersectWith(selector.IslandSelect(islands, islandDescription)); + } + return islandHash; + } + } +} diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs.meta b/Runtime/IslandSelect/IslandSelectorAND.cs.meta new file mode 100644 index 00000000..bdc5010e --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorAND.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 85ff367561c3249439eef9643e07d156 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs new file mode 100644 index 00000000..349ccd30 --- /dev/null +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Linq; +using net.rs64.TexTransCore.Island; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public class SphereIslandSelector : AbstractIslandSelector + { + public float SphereSize = 0.1f; + internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) + { + var islandHash = new HashSet(islands.Count); + + var matrix = transform.worldToLocalMatrix; + + foreach (var island in islands) + { + var description = islandDescription[island.Key]; + foreach (var i in island.Value.triangles.SelectMany(i => i)) + { + if (matrix.MultiplyPoint3x4(description.Position[i]).magnitude < SphereSize) { islandHash.Add(island.Key); break; } + } + } + + return islandHash; + } + } +} diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs.meta b/Runtime/IslandSelect/SphereIslandSelector.cs.meta new file mode 100644 index 00000000..b06c98f6 --- /dev/null +++ b/Runtime/IslandSelect/SphereIslandSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4190c7a32becf54aaf0e4f8ecea9c2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/Decal/DecalUtility.cs b/TexTransCore/Decal/DecalUtility.cs index 2945557a..a075917e 100644 --- a/TexTransCore/Decal/DecalUtility.cs +++ b/TexTransCore/Decal/DecalUtility.cs @@ -20,19 +20,22 @@ public interface IConvertSpace } public interface ITrianglesFilter { - List Filtering(SpaceConverter space, List triangles, List output = null); + void SetSpace(SpaceConverter space); + List GetFilteredSubTriangle(int subMeshIndex); } public class MeshData { internal readonly List Vertex; internal readonly List UV; internal readonly List> TrianglesSubMesh; + internal readonly Renderer RendererRef; - internal MeshData(List vertex, List uV, List> trianglesSubMesh) + internal MeshData(List vertex, List uV, List> trianglesSubMesh, Renderer renderer) { Vertex = vertex; UV = uV; TrianglesSubMesh = trianglesSubMesh; + RendererRef = renderer; } } internal static Dictionary CreateDecalTexture( @@ -57,33 +60,29 @@ internal static Dictionary CreateDecalTexture.Get(); targetMesh.GetUVs(0, tUV); var trianglesSubMesh = targetMesh.GetPooledSubTriangle(); - convertSpace.Input(new MeshData(vertices, tUV, trianglesSubMesh)); + convertSpace.Input(new MeshData(vertices, tUV, trianglesSubMesh, targetRenderer)); var sUVPooled = ListPool.Get(); var sUV = convertSpace.OutPutUV(sUVPooled); + filter.SetSpace(convertSpace); + var materials = targetRenderer.sharedMaterials; for (int i = 0; i < trianglesSubMesh.Count; i++) { - var triangle = trianglesSubMesh[i]; var targetMat = materials[i]; if (!targetMat.HasProperty(targetPropertyName)) { continue; }; var targetTexture = targetMat.GetTexture(targetPropertyName); if (targetTexture == null) { continue; } - var targetTexSize = new Vector2Int(targetTexture.width, targetTexture.height); - - List filteredTriangle; - var filteredTrianglePooled = ListPool.Get(); - if (filter != null) { filteredTriangle = filter.Filtering(convertSpace, triangle, filteredTrianglePooled); } - else { filteredTriangle = triangle; } + var filteredTriangle = filter.GetFilteredSubTriangle(i); if (filteredTriangle.Any() == false) { continue; } if (!renderTextures.ContainsKey(targetMat)) { - var tempRt = RenderTexture.GetTemporary(targetTexSize.x, targetTexSize.y, 32); tempRt.Clear(); - renderTextures.Add(targetMat, tempRt); + renderTextures[targetMat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); + renderTextures[targetMat].Clear(); } TransTexture.ForTrans( @@ -95,9 +94,6 @@ internal static Dictionary CreateDecalTexture.Release(filteredTrianglePooled); } ListPool.Release(vertices); ListPool.Release(tUV); @@ -224,4 +220,4 @@ public enum PolygonCulling Edge, EdgeAndCenterRay, } -} \ No newline at end of file +} diff --git a/TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs b/TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs deleted file mode 100644 index 787c011a..00000000 --- a/TexTransCore/Decal/ParallelProjection/IslandCullingPPFilter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.Island; -using UnityEngine.Pool; - -namespace net.rs64.TexTransCore.Decal -{ - internal class IslandCullingPPFilter : ParallelProjectionFilter - where UVDimension : struct - { - public List IslandSelectors; - - public IslandCullingPPFilter(List>> filters, List islandSelectors) : base(filters) - { - IslandSelectors = islandSelectors; - } - - public override List Filtering(ParallelProjectionSpace space, List triangles, List output = null) - { - var cullied = ListPool.Get(); - triangles = Island.IslandCulling.Culling(IslandSelectors, space.MeshData.Vertex, space.MeshData.UV, triangles); - var result = base.Filtering(space, triangles, output); - ListPool.Release(cullied); - return result; - } - - } -} - - diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs index 308ef76b..8a27176f 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs @@ -4,20 +4,20 @@ namespace net.rs64.TexTransCore.Decal { - internal class ParallelProjectionFilter : DecalUtility.ITrianglesFilter - where UVDimension : struct + internal class ParallelProjectionFilter : DecalUtility.ITrianglesFilter { public List>> Filters; + ParallelProjectionSpace _parallelProjectionSpace; - public ParallelProjectionFilter(List>> filters) - { - Filters = filters; - } + public ParallelProjectionFilter(List>> filters) { Filters = filters; } + public void SetSpace(ParallelProjectionSpace space) { _parallelProjectionSpace = space; } - public virtual List Filtering(ParallelProjectionSpace space, List triangles, List output = null) + public List GetFilteredSubTriangle(int subMeshIndex) { - return TriangleFilterUtility.FilteringTriangle(triangles, space.PPSVert, Filters, output); + if (_parallelProjectionSpace is null) { return null; } + return TriangleFilterUtility.FilteringTriangle(_parallelProjectionSpace.MeshData.TrianglesSubMesh[subMeshIndex], _parallelProjectionSpace.PPSVert, Filters); } + } } diff --git a/TexTransCore/Island/IslandCulling.cs b/TexTransCore/Island/IslandCulling.cs index 09b3d371..d7c0a113 100644 --- a/TexTransCore/Island/IslandCulling.cs +++ b/TexTransCore/Island/IslandCulling.cs @@ -14,11 +14,11 @@ namespace net.rs64.TexTransCore.Island { [Serializable] - internal struct IslandSelector + internal struct IslandSelectorRay { public Ray Ray; public float RayRange; - public IslandSelector(Ray ray, float rayRange) + public IslandSelectorRay(Ray ray, float rayRange) { this.Ray = ray; this.RayRange = rayRange; @@ -29,7 +29,7 @@ internal static class IslandCulling { public static List Culling( - List islandSelectors, + List islandSelectors, List positions, List uv, List triangles, From e66efa5fc381b3ff52575b85e9ec3fe8f020527c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 16 Mar 2024 18:53:31 +0900 Subject: [PATCH 009/208] feat: Create RayCast and Box and more ... --- .../CylindricalCoordinatesSystem.cs | 13 ++- Runtime/Decal/IslandSelectToPPFilter.cs | 53 +++++++---- Runtime/Decal/NailEditor.cs | 10 ++- .../IslandSelect/AbstructIslandSelector.cs | 45 +++++----- Runtime/IslandSelect/BoxIslandSelector.cs | 40 +++++++++ .../IslandSelect/BoxIslandSelector.cs.meta | 11 +++ Runtime/IslandSelect/IslandSelectOR.cs | 16 ++-- Runtime/IslandSelect/IslandSelectorAND.cs | 16 ++-- Runtime/IslandSelect/RayCastIslandSelector.cs | 90 +++++++++++++++++++ .../RayCastIslandSelector.cs.meta | 11 +++ Runtime/IslandSelect/SphereIslandSelector.cs | 23 +++-- TexTransCore/Decal/DecalUtility.cs | 68 +++----------- TexTransCore/Decal/MeshData.cs | 80 ++++++++++++----- .../ParallelProjectionFilter.cs | 2 +- .../ParallelProjectionSpace.cs | 14 ++- TexTransCore/Decal/TriangleFilterUtility.cs | 2 +- TexTransCore/Island/IslandCulling.cs | 17 ++-- TexTransCore/Island/RayCastJob.cs | 34 +++++++ 18 files changed, 389 insertions(+), 156 deletions(-) create mode 100644 Runtime/IslandSelect/BoxIslandSelector.cs create mode 100644 Runtime/IslandSelect/BoxIslandSelector.cs.meta create mode 100644 Runtime/IslandSelect/RayCastIslandSelector.cs create mode 100644 Runtime/IslandSelect/RayCastIslandSelector.cs.meta diff --git a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs index 35e667e3..2b7404d6 100644 --- a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs +++ b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs @@ -117,6 +117,7 @@ internal class CCSSpace : DecalUtility.IConvertSpace public float Offset; public NativeArray Normalized; public List QuadNormalizedVertex; + public MeshData MeshData; public CCSSpace(CylindricalCoordinatesSystem ccs, IReadOnlyList quad) { @@ -124,10 +125,11 @@ public CCSSpace(CylindricalCoordinatesSystem ccs, IReadOnlyList quad) Quad = quad; } - public void Input(MeshData MeshData) + public void Input(MeshData meshData) { + MeshData = meshData; var ccsQuad = CCS.VertexConvertCCS(Quad); - var ccsVertex = CCS.VertexConvertCCS(MeshData.VertexList); + var ccsVertex = CCS.VertexConvertCCS(meshData.VertexList); var offset = ccsQuad.Min(I => I.y) * -1; CylindricalCoordinatesSystem.OffSetApply(ccsQuad, offset); @@ -166,14 +168,17 @@ public void Dispose() internal class CCSFilter : DecalUtility.ITrianglesFilter { public IReadOnlyList> Filters; + CCSSpace _ccsSpace; public CCSFilter(IReadOnlyList> filters) { Filters = filters; } - public List Filtering(CCSSpace space, List triangles, List output = null) + public void SetSpace(CCSSpace space) { _ccsSpace = space; } + + public List GetFilteredSubTriangle(int subMeshIndex) { - return TriangleFilterUtility.FilteringTriangle(triangles, space, Filters, output); + return TriangleFilterUtility.FilteringTriangle(_ccsSpace.MeshData.TrianglesSubMeshList[subMeshIndex], _ccsSpace, Filters); } diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index 6f281e17..fdea3cc7 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -8,46 +8,65 @@ using net.rs64.TexTransCore.TransTextureCore; using net.rs64.TexTransTool.IslandSelector; using System.Linq; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.Decal { internal class IslandSelectToPPFilter : DecalUtility.ITrianglesFilter { - public List>> Filters; - public AbstractIslandSelector IslandSelector; + public List>> Filters; + public IIslandSelector IslandSelector; - public IslandSelectToPPFilter(AbstractIslandSelector islandSelector, List>> filters) + public IslandSelectToPPFilter(IIslandSelector islandSelector, List>> filters) { IslandSelector = islandSelector; Filters = filters; } - ParallelProjectionSpace _parallelProjectionSpace; + ParallelProjectionSpace _ppSpace; - public void SetSpace(ParallelProjectionSpace space) { _parallelProjectionSpace = space; } + public void SetSpace(ParallelProjectionSpace space) { _ppSpace = space; } + + //これSetされた瞬間からマルチスレッドでにフィルタリングを走らせるのもありなのではないか? public List GetFilteredSubTriangle(int subMeshIndex) { - if (_parallelProjectionSpace is null) { return null; } + if (_ppSpace is null) { return null; } + + var meshData = _ppSpace.MeshData; + Island[] islands = (subMeshIndex, meshData).Memo(GetIslands); - var meshData = _parallelProjectionSpace.MeshData; - var islands = IslandUtility.UVtoIsland(meshData.TrianglesSubMesh[subMeshIndex], meshData.UV); + Profiler.BeginSample("CreateIslandDescription"); + var description = new IslandDescription(meshData.Vertices, meshData.VertexUV, meshData.ReferenceRenderer, subMeshIndex); + var islandDescription = new IslandDescription[islands.Length]; + for (var i = 0; islands.Length > i; i += 1) { islandDescription[i] = description; } + Profiler.EndSample(); - var description = new AbstractIslandSelector.IslandDescription(meshData.Vertex.ToArray(), meshData.UV.ToArray(), meshData.RendererRef, subMeshIndex); + Profiler.BeginSample("IslandSelect"); + var bitArray = IslandSelector.IslandSelect(islands, islandDescription); + Profiler.EndSample(); - var islandsCount = islands.Count; - var islandDict = new Dictionary(islandsCount); - var islandDescription = new Dictionary(islandsCount); - for (var i = 0; islandsCount > i; i += 1) + Profiler.BeginSample("FilterTriangle"); + var linkList = new LinkedList(); + for (var i = 0; islands.Length > i; i += 1) { - islandDict[i] = islands[i]; - islandDescription[i] = description; + if (!bitArray[i]) { continue; } + var island = islands[i]; + var triCount = island.triangles.Count; + for (var triIndex = 0; triCount > triIndex; triIndex += 1) + { + linkList.AddLast(island.triangles[triIndex]); + } } + Profiler.EndSample(); - var hash = IslandSelector.IslandSelect(islandDict, islandDescription); + return TriangleFilterUtility.FilteringTriangle(linkList.ToList(), _ppSpace.GetPPSVert.AsList(), Filters); - return TriangleFilterUtility.FilteringTriangle(hash.SelectMany(i => islandDict[i].triangles).ToList(), _parallelProjectionSpace.PPSVert, Filters); + static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) + { + return IslandUtility.UVtoIsland(pair.meshData.TriangleIndex[pair.subMeshIndex].AsList(), pair.meshData.UVList).ToArray(); + } } } } diff --git a/Runtime/Decal/NailEditor.cs b/Runtime/Decal/NailEditor.cs index 8ff68206..1080b420 100644 --- a/Runtime/Decal/NailEditor.cs +++ b/Runtime/Decal/NailEditor.cs @@ -6,6 +6,7 @@ using net.rs64.TexTransTool.Utils; using net.rs64.TexTransCore.Decal; using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.IslandSelector; namespace net.rs64.TexTransTool.Decal { @@ -49,9 +50,9 @@ internal override Dictionary CompileDecal(ITextureManag return decalCompiledRenderTextures; } - List<(Texture2D, ParallelProjectionSpace, ParallelProjectionFilter)> GetNailTexSpaceFilters() + List<(Texture2D, ParallelProjectionSpace, IslandSelectToPPFilter)> GetNailTexSpaceFilters() { - var spaceList = new List<(Texture2D, ParallelProjectionSpace, ParallelProjectionFilter)>(); + var spaceList = new List<(Texture2D, ParallelProjectionSpace, IslandSelectToPPFilter)>(); CompileNail(LeftHand, false); @@ -68,10 +69,11 @@ void CompileNail(NailSet nailSet, bool IsRight) var souseFingerTF = GetFinger(finger, IsRight); var matrix = GetNailMatrix(souseFingerTF, nailDecalDescription, nailSet.FingerUpVector, IsRight); - var islandSelector = new IslandSelector(new Ray(matrix.MultiplyPoint(Vector3.zero), matrix.MultiplyVector(Vector3.forward)), matrix.lossyScale.z * 1); + var islandSelector = new IslandSelectorRay(new Ray(matrix.MultiplyPoint(Vector3.zero), matrix.MultiplyVector(Vector3.forward)), matrix.lossyScale.z * 1); + var SpaceConverter = new ParallelProjectionSpace(matrix.inverse); - var Filter = new IslandCullingPPFilter(GetFilter(), new List(1) { islandSelector }); + var Filter = new IslandSelectToPPFilter(new RayCastIslandSelectorClass(islandSelector), GetFilter()); spaceList.Add((nailDecalDescription.DecalTexture, SpaceConverter, Filter)); } diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index f1678da8..f78c2414 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -2,33 +2,18 @@ using net.rs64.TexTransTool; using System.Collections.Generic; using net.rs64.TexTransCore.Island; +using Unity.Collections; +using System.Collections; namespace net.rs64.TexTransTool.IslandSelector { - public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag + public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, IIslandSelector { [HideInInspector, SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; int ITexTransToolTag.SaveDataVersion => _saveDataVersion; - internal abstract HashSet IslandSelect(Dictionary islands, Dictionary islandDescription); - - internal readonly struct IslandDescription - { - public readonly Vector3[] Position;//ワールドスペース - public readonly Vector2[] UV; - public readonly Renderer Renderer; - public readonly int MaterialSlot; - - public IslandDescription(Vector3[] position, Vector2[] uV, Renderer renderer, int materialSlot) : this() - { - Position = position; - UV = uV; - Renderer = renderer; - MaterialSlot = materialSlot; - } - - } - + internal abstract BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription); + BitArray IIslandSelector.IslandSelect(Island[] islands, IslandDescription[] islandDescription) => IslandSelect(islands, islandDescription); /* 頂点の持つ情報 レンダラー @@ -36,5 +21,25 @@ public IslandDescription(Vector3[] position, Vector2[] uV, Renderer renderer, in */ + } + internal interface IIslandSelector + { + internal abstract BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription); + } + internal readonly struct IslandDescription + { + public readonly NativeArray Position;//ワールドスペース + public readonly NativeArray UV; + public readonly Renderer Renderer; + public readonly int MaterialSlot; + + public IslandDescription(NativeArray position, NativeArray uV, Renderer renderer, int materialSlot) + { + Position = position; + UV = uV; + Renderer = renderer; + MaterialSlot = materialSlot; + } + } } diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs new file mode 100644 index 00000000..d590a0c6 --- /dev/null +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -0,0 +1,40 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using net.rs64.TexTransCore.Island; +using UnityEngine; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public class BoxIslandSelector : AbstractIslandSelector + { + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + var bitArray = new BitArray(islands.Length); + var matrix = transform.worldToLocalMatrix; + + for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) + { + var description = islandDescription[islandIndex]; + + foreach (var tri in islands[islandIndex].triangles) + { + for (var vi = 0; 3 > vi; vi += 1) + { + var vert = matrix.MultiplyPoint3x4(description.Position[tri[vi]]); + + var isIn = true; + isIn &= Mathf.Abs(vert.x) < 0.5f; + isIn &= Mathf.Abs(vert.x) < 0.5f; + isIn &= Mathf.Abs(vert.x) < 0.5f; + if (isIn) { bitArray[islandIndex] = true; break; } + } + if (bitArray[islandIndex]) { break; } + } + } + + + return bitArray; + } + } +} diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs.meta b/Runtime/IslandSelect/BoxIslandSelector.cs.meta new file mode 100644 index 00000000..b64583a1 --- /dev/null +++ b/Runtime/IslandSelect/BoxIslandSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 531265db5df6a5c44a6da0ea8b6229eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectOR.cs b/Runtime/IslandSelect/IslandSelectOR.cs index 69a73010..e22ec762 100644 --- a/Runtime/IslandSelect/IslandSelectOR.cs +++ b/Runtime/IslandSelect/IslandSelectOR.cs @@ -1,19 +1,25 @@ +using System.Collections; using System.Collections.Generic; using net.rs64.TexTransCore.Island; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.IslandSelector { public class IslandSelectOR : AbstractIslandSelector { public List IslandSelectors; - internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { - var islandHash = new HashSet(islands.Count); - foreach (var selector in IslandSelectors) + BitArray bitArray = null; + foreach (var islandSelector in IslandSelectors) { - islandHash.UnionWith(selector.IslandSelect(islands, islandDescription)); + Profiler.BeginSample(islandSelector.GetType().Name); + var selectBit = islandSelector.IslandSelect(islands, islandDescription); + Profiler.EndSample(); + if (bitArray is null) { bitArray = selectBit; continue; } + bitArray.Or(selectBit); } - return islandHash; + return bitArray; } } } diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs index 8a432880..e2a33c10 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -1,19 +1,25 @@ +using System.Collections; using System.Collections.Generic; using net.rs64.TexTransCore.Island; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.IslandSelector { public class IslandSelectorAND : AbstractIslandSelector { public List IslandSelectors; - internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { - var islandHash = new HashSet(islands.Keys); - foreach (var selector in IslandSelectors) + BitArray bitArray = null; + foreach (var islandSelector in IslandSelectors) { - islandHash.IntersectWith(selector.IslandSelect(islands, islandDescription)); + Profiler.BeginSample(islandSelector.GetType().Name); + var selectBit = islandSelector.IslandSelect(islands, islandDescription); + Profiler.EndSample(); + if (bitArray is null) { bitArray = selectBit; continue; } + bitArray.And(selectBit); } - return islandHash; + return bitArray; } } } diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs new file mode 100644 index 00000000..b71709d5 --- /dev/null +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -0,0 +1,90 @@ +using UnityEngine; +using net.rs64.TexTransTool; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using Unity.Collections; +using System.Collections; +using System; +using Unity.Jobs; +using net.rs64.TexTransCore.TransTextureCore; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + public class RayCastIslandSelector : AbstractIslandSelector + { + public float IslandSelectorRange; + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + return RayCastIslandSelect(GetIslandSelectorRay(), islands, islandDescription); + } + + internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay, Island[] islands, IslandDescription[] islandDescription) + { + var bitArray = new BitArray(islands.Length); + var ray = islandSelectorRay; + var rayMatrix = ray.Ray.GetRayMatrix(); + var jobs = new JobHandle[islands.Length]; + var hitResults = new NativeArray[islands.Length]; + var distances = new NativeArray[islands.Length]; + + for (var i = 0; jobs.Length > i; i += 1) + { + var triCount = islands[i].triangles.Count; + var nativeTriangleIndex = new NativeArray(triCount, Allocator.TempJob); + for (var triIndex = 0; triCount > triIndex; triIndex += 1) { nativeTriangleIndex[triIndex] = islands[i].triangles[triIndex]; } + var hitResult = hitResults[i] = new NativeArray(triCount, Allocator.TempJob); + var distance = distances[i] = new NativeArray(triCount, Allocator.TempJob); + + var rayCastJob = new RayCastJob2() + { + rayMatrix = rayMatrix, + Triangles = nativeTriangleIndex, + Position = islandDescription[i].Position, + HitResult = hitResult, + Distance = distance, + }; + jobs[i] = rayCastJob.Schedule(triCount, 64); + } + + for (var i = 0; jobs.Length > i; i += 1) + { + jobs[i].Complete(); + + using (var hRes = hitResults[i]) + using (var distance = distances[i]) + { + for (var ti = 0; hRes.Length > ti; ti += 1) + { + if (!hRes[ti]) { continue; } + if (distance[ti] < 0) { continue; } + if (distance[ti] > ray.RayRange) { continue; } + + bitArray[i] = true; + break; + } + } + } + + + return bitArray; + } + + internal IslandSelectorRay GetIslandSelectorRay() { return new IslandSelectorRay(new Ray(transform.position, transform.forward), IslandSelectorRange); } + } + + internal class RayCastIslandSelectorClass : IIslandSelector + { + public IslandSelectorRay IslandSelectorRay; + + public RayCastIslandSelectorClass(IslandSelectorRay islandSelectorRay) + { + IslandSelectorRay = islandSelectorRay; + } + + BitArray IIslandSelector.IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + return RayCastIslandSelector.RayCastIslandSelect(IslandSelectorRay, islands, islandDescription); + } + } +} diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs.meta b/Runtime/IslandSelect/RayCastIslandSelector.cs.meta new file mode 100644 index 00000000..4a2432a1 --- /dev/null +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f4975755f5e33a409da61de02a7be1f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index 349ccd30..f7bfa37d 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -1,3 +1,4 @@ +using System.Collections; using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Island; @@ -7,22 +8,28 @@ namespace net.rs64.TexTransTool.IslandSelector public class SphereIslandSelector : AbstractIslandSelector { public float SphereSize = 0.1f; - internal override HashSet IslandSelect(Dictionary islands, Dictionary islandDescription) - { - var islandHash = new HashSet(islands.Count); + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + var bitArray = new BitArray(islands.Length); var matrix = transform.worldToLocalMatrix; - foreach (var island in islands) + var sqrMagMax = SphereSize * SphereSize; + for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) { - var description = islandDescription[island.Key]; - foreach (var i in island.Value.triangles.SelectMany(i => i)) + var description = islandDescription[islandIndex]; + + foreach (var tri in islands[islandIndex].triangles) { - if (matrix.MultiplyPoint3x4(description.Position[i]).magnitude < SphereSize) { islandHash.Add(island.Key); break; } + for (var vi = 0; 3 > vi; vi += 1) + { + if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude < sqrMagMax) { bitArray[islandIndex] = true; break; } + } + if (bitArray[islandIndex]) { break; } } } - return islandHash; + return bitArray; } } } diff --git a/TexTransCore/Decal/DecalUtility.cs b/TexTransCore/Decal/DecalUtility.cs index b5abfb0b..1467916f 100644 --- a/TexTransCore/Decal/DecalUtility.cs +++ b/TexTransCore/Decal/DecalUtility.cs @@ -15,7 +15,7 @@ namespace net.rs64.TexTransCore.Decal { public static class DecalUtility { - public interface IConvertSpace: IDisposable + public interface IConvertSpace : IDisposable where UVDimension : struct { void Input(MeshData meshData); @@ -45,31 +45,22 @@ internal static Dictionary CreateDecalTexture i.Dispose()); Profiler.EndSample(); - var targetMesh = targetRenderer.GetMesh(); - Profiler.BeginSample("GetUVs"); - var tUV = ListPool.Get(); targetMesh.GetUVs(0, tUV); - Profiler.EndSample(); - - Profiler.BeginSample("GetPooledSubTriangle"); - var trianglesSubMesh = targetMesh.GetPooledSubTriangle(); + var tUV = meshData.VertexUV; Profiler.EndSample(); Profiler.BeginSample("convertSpace.Input"); convertSpace.Input(meshData); Profiler.EndSample(); - var sUVPooled = ListPool.Get(); - var sUV = convertSpace.OutPutUV(); - filter.SetSpace(convertSpace); var materials = targetRenderer.sharedMaterials; - for (int i = 0; i < trianglesSubMesh.Count; i++) + for (int i = 0; i < meshData.Triangles.Length; i++) { var targetMat = materials[i]; @@ -77,7 +68,9 @@ internal static Dictionary CreateDecalTexture CreateDecalTexture CreateDecalTexture.Release(tUV); - ListPool.Release(sUVPooled); - ReleasePooledSubTriangle(trianglesSubMesh); + convertSpace.Dispose();//convertSpaceの解放責任はこっちにある return renderTextures; } - internal static MeshData GetMeshData(Renderer target) - { - MeshData result; - switch (target) - { - case SkinnedMeshRenderer smr: - { - Mesh mesh = new Mesh(); - smr.BakeMesh(mesh); - - Matrix4x4 matrix; - if (smr.bones.Any()) - { - matrix = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one); - } - else if (smr.rootBone == null) - { - matrix = smr.localToWorldMatrix; - } - else - { - matrix = smr.rootBone.localToWorldMatrix; - } - - result = new MeshData(mesh, matrix); - - UnityEngine.Object.DestroyImmediate(mesh); - break; - } - case MeshRenderer mr: - { - return new MeshData(mr.GetComponent().sharedMesh, mr.localToWorldMatrix); - break; - } - default: - { - throw new System.ArgumentException("Rendererが対応したタイプではないか、TargetRendererが存在しません。"); - } - } - return result; - } + public static MeshData GetMeshData(Renderer renderer) => new MeshData(renderer); public static List> GetPooledSubTriangle(this Mesh mesh) { var result = ListPool>.Get(); @@ -187,7 +139,7 @@ private struct ConvertVerticesJob : IJobParallelFor [WriteOnly] public NativeArray OutputVertices; public Matrix4x4 Matrix; public Vector3 Offset; - + public void Execute(int index) { OutputVertices[index] = Matrix.MultiplyPoint3x4(InputVertices[index]) + Offset; diff --git a/TexTransCore/Decal/MeshData.cs b/TexTransCore/Decal/MeshData.cs index 591710db..cc7a04f6 100644 --- a/TexTransCore/Decal/MeshData.cs +++ b/TexTransCore/Decal/MeshData.cs @@ -11,6 +11,7 @@ namespace net.rs64.TexTransCore.Decal { public class MeshData : IDisposable { + internal readonly Renderer ReferenceRenderer; internal NativeArray _vertices; internal NativeArray Vertices { @@ -20,7 +21,7 @@ internal NativeArray Vertices return _vertices; } } - + internal NativeArray VertexUV; internal JobHandle _jobHandle, _destroyJobHandle; @@ -53,7 +54,7 @@ internal NativeArray CombinedTriangles return _combinedTriangles; } } - + internal readonly NativeArray _combinedTriangleIndex; internal NativeArray CombinedTriangleIndex { @@ -92,8 +93,11 @@ public void Dispose() _combinedTriangleIndex.Dispose(); } - internal MeshData(Mesh mesh, Matrix4x4 worldSpaceTransform) + internal MeshData(Renderer renderer) { + ReferenceRenderer = renderer; + (Mesh mesh, Matrix4x4 worldSpaceTransform) = GetMeshAndMatrix(renderer); + var meshDataArray = Mesh.AcquireReadOnlyMeshData(mesh); var mainMesh = meshDataArray[0]; @@ -101,14 +105,14 @@ internal MeshData(Mesh mesh, Matrix4x4 worldSpaceTransform) var vertexCount = mainMesh.vertexCount; _vertices = new NativeArray(vertexCount, Allocator.TempJob); VertexUV = new NativeArray(vertexCount, Allocator.TempJob); - + mainMesh.GetVertices(_vertices); mainMesh.GetUVs(0, VertexUV); var subMeshCount = mainMesh.subMeshCount; _triangles = new NativeArray[subMeshCount]; _trianglePos = new NativeArray[subMeshCount]; - + JobHandle worldSpaceTransformJob = new WorldSpaceTransformJob() { PositionBuffer = _vertices, @@ -124,17 +128,17 @@ internal MeshData(Mesh mesh, Matrix4x4 worldSpaceTransform) _combinedTriangleIndex = new NativeArray(totalTris, Allocator.TempJob); _combinedTriangles = new NativeArray(totalTris, Allocator.TempJob); _combinedTriangleToSubmeshIndexAndOffset = new NativeArray<(int, int)>(totalTris, Allocator.TempJob); - + JobHandle jobHandle = default; int combinedOffset = 0; for (int submesh = 0; submesh < subMeshCount; submesh++) { var desc = mainMesh.GetSubMesh(submesh); var indexCount = desc.indexCount; - + _triangles[submesh] = new NativeArray(indexCount, Allocator.TempJob); _trianglePos[submesh] = new NativeArray(indexCount / 3, Allocator.TempJob); - + var indexes = new NativeArray(indexCount, Allocator.TempJob); mainMesh.GetIndices(indexes, submesh); @@ -157,22 +161,58 @@ internal MeshData(Mesh mesh, Matrix4x4 worldSpaceTransform) submeshIndex = submesh, submeshOffset = combinedOffset }.Schedule(indexCount / 3, 64, newHandle); - + jobHandle = JobHandle.CombineDependencies(jobHandle, copyHandle); combinedOffset += indexCount / 3; } - + _jobHandle = jobHandle; _destroyJobHandle = jobHandle; - + meshDataArray.Dispose(); } + (Mesh, Matrix4x4) GetMeshAndMatrix(Renderer target) + { + switch (target) + { + case SkinnedMeshRenderer smr: + { + Mesh mesh = new Mesh(); + smr.BakeMesh(mesh); + + Matrix4x4 matrix; + if (smr.bones.Any()) + { + matrix = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one); + } + else if (smr.rootBone == null) + { + matrix = smr.localToWorldMatrix; + } + else + { + matrix = smr.rootBone.localToWorldMatrix; + } + + return (mesh, matrix); + } + case MeshRenderer mr: + { + return (mr.GetComponent().sharedMesh, mr.localToWorldMatrix); + } + default: + { + throw new System.ArgumentException("Rendererが対応したタイプではないか、TargetRendererが存在しません。"); + } + } + } + struct PackVerticesJob : IJobParallelFor { [ReadOnly] public NativeArray srcIndex; [ReadOnly] public NativeArray srcPos; - + [NativeDisableParallelForRestriction] [NativeDisableContainerSafetyRestriction] [WriteOnly] public NativeSlice dstIndex; @@ -185,7 +225,7 @@ struct PackVerticesJob : IJobParallelFor public int submeshIndex; public int submeshOffset; - + public void Execute(int index) { dstIndex[index] = srcIndex[index]; @@ -194,21 +234,21 @@ public void Execute(int index) dstSubmeshIndexAndOffset[index] = (submeshIndex, submeshOffset); } } - + struct InitTriangleJob : IJobParallelFor { - [DeallocateOnJobCompletion] [ReadOnly] public NativeArray SubmeshIndexBuffer; + [DeallocateOnJobCompletion][ReadOnly] public NativeArray SubmeshIndexBuffer; [ReadOnly] public NativeArray PositionBuffer; - + [WriteOnly] public NativeArray TriangleIndexBuffer; [WriteOnly] public NativeArray TrianglePosBuffer; - + public void Execute(int index) { var i = index * 3; var triIndex = new TriangleIndex(SubmeshIndexBuffer[i], SubmeshIndexBuffer[i + 1], SubmeshIndexBuffer[i + 2]); TriangleIndexBuffer[index] = triIndex; - + var triangle = new Triangle(); triangle.zero = PositionBuffer[triIndex.zero]; triangle.one = PositionBuffer[triIndex.one]; @@ -216,7 +256,7 @@ public void Execute(int index) TrianglePosBuffer[index] = triangle; } } - + struct WorldSpaceTransformJob : IJobParallelFor { public NativeArray PositionBuffer; @@ -238,4 +278,4 @@ public void AddJobDependency(JobHandle jobHandle) _destroyJobHandle = JobHandle.CombineDependencies(_destroyJobHandle, jobHandle); } } -} \ No newline at end of file +} diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs index 8f645678..723af1e3 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs @@ -15,7 +15,7 @@ internal class ParallelProjectionFilter : DecalUtility.ITrianglesFilter GetFilteredSubTriangle(int subMeshIndex) { if (_parallelProjectionSpace is null) { return null; } - return TriangleFilterUtility.FilteringTriangle(_parallelProjectionSpace.MeshData.TrianglesSubMesh[subMeshIndex], _parallelProjectionSpace.PPSVert, Filters); + return TriangleFilterUtility.FilteringTriangle(_parallelProjectionSpace.MeshData.TrianglesSubMeshList[subMeshIndex], _parallelProjectionSpace.OutPutUV().AsList(), Filters); } } diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs index 08764d41..0a98de38 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs @@ -9,11 +9,12 @@ namespace net.rs64.TexTransCore.Decal public class ParallelProjectionSpace : DecalUtility.IConvertSpace { internal Matrix4x4 ParallelProjectionMatrix; - internal MeshData MeshData; + internal MeshData MeshData; private JobHandle _jobHandle; private NativeArray PPSVert; - + internal NativeArray GetPPSVert { get { _jobHandle.Complete(); return PPSVert; } } + internal ParallelProjectionSpace(Matrix4x4 parallelProjectionMatrix) { ParallelProjectionMatrix = parallelProjectionMatrix; @@ -25,15 +26,12 @@ public void Input(MeshData meshData) PPSVert = DecalUtility.ConvertVerticesInMatrix(ParallelProjectionMatrix, meshData, new Vector3(0.5f, 0.5f, 0), out _jobHandle); } - public NativeArray OutPutUV() - { - _jobHandle.Complete(); - return PPSVert; - } + public NativeArray OutPutUV() => GetPPSVert; public void Dispose() { - MeshData?.Dispose(); + MeshData = null; + PPSVert.Dispose(); } } } diff --git a/TexTransCore/Decal/TriangleFilterUtility.cs b/TexTransCore/Decal/TriangleFilterUtility.cs index a4382099..14c9ded6 100644 --- a/TexTransCore/Decal/TriangleFilterUtility.cs +++ b/TexTransCore/Decal/TriangleFilterUtility.cs @@ -208,4 +208,4 @@ public static bool OutOfPolygonEdgeEdgeAndCenterRayCast(TriangleIndex targetTri, } -} \ No newline at end of file +} diff --git a/TexTransCore/Island/IslandCulling.cs b/TexTransCore/Island/IslandCulling.cs index c9179b5e..87915b60 100644 --- a/TexTransCore/Island/IslandCulling.cs +++ b/TexTransCore/Island/IslandCulling.cs @@ -37,7 +37,7 @@ public static List Culling( ) { var iIslands = meshData.Memo(IslandUtility.UVtoIsland); - + Profiler.BeginSample("IslandCulling raycast"); var rayCastHitTriangle = ListPool.Get(); foreach (var i in islandSelectors) @@ -53,7 +53,7 @@ public static List Culling( } } Profiler.EndSample(); - + Profiler.BeginSample("IslandCulling map to island"); var hitSelectIsland = HashSetPool.Get(); foreach (var hitTriangle in rayCastHitTriangle) @@ -67,7 +67,7 @@ public static List Culling( } } } - output?.Clear(); output ??= new (); + output?.Clear(); output ??= new(); output.AddRange(hitSelectIsland.SelectMany(I => I.triangles)); Profiler.EndSample(); @@ -79,8 +79,7 @@ public static List Culling( public static List RayCast(Ray ray, MeshData mesh) { - var rot = Quaternion.LookRotation(ray.direction); - var rayMatrix = Matrix4x4.TRS(ray.origin, rot, Vector3.one).inverse; + var rayMatrix = ray.GetRayMatrix(); var nativeTriangleArray = mesh.CombinedTriangles; @@ -111,6 +110,14 @@ public static List RayCast(Ray ray, MeshData mesh) distance.Dispose(); return output; } + + public static Matrix4x4 GetRayMatrix(this Ray ray) + { + var rot = Quaternion.LookRotation(ray.direction); + var rayMatrix = Matrix4x4.TRS(ray.origin, rot, Vector3.one).inverse; + return rayMatrix; + } + public static void FilteredBackTriangle(List rayCastHitTriangles) { rayCastHitTriangles.RemoveAll(I => I.Distance < 0); diff --git a/TexTransCore/Island/RayCastJob.cs b/TexTransCore/Island/RayCastJob.cs index 13beeff9..ac62477c 100644 --- a/TexTransCore/Island/RayCastJob.cs +++ b/TexTransCore/Island/RayCastJob.cs @@ -39,5 +39,39 @@ public void Execute(int index) + } + [BurstCompile] + internal struct RayCastJob2 : IJobParallelFor + { + [ReadOnly] + public Matrix4x4 rayMatrix; + [ReadOnly][DeallocateOnJobCompletion] + public NativeArray Triangles; + [ReadOnly] + public NativeArray Position; + + [WriteOnly] + public NativeArray Distance; + [WriteOnly] + public NativeArray HitResult; + public void Execute(int index) + { + var trIndex = Triangles[index]; + var tri = new Triangle(); + tri.zero = rayMatrix.MultiplyPoint3x4(Position[trIndex.zero]); + tri.one = rayMatrix.MultiplyPoint3x4(Position[trIndex.one]); + tri.two = rayMatrix.MultiplyPoint3x4(Position[trIndex.two]); + var CrossT = tri.Cross(Vector3.zero); + + var TBC = VectorUtility.ToBarycentricCoordinateSystem(CrossT); + if (float.IsNaN(TBC.x) || float.IsNaN(TBC.y) || float.IsNaN(TBC.z)) { return; } + var IsIn = VectorUtility.IsInCal(CrossT.x, CrossT.y, CrossT.z); + HitResult[index] = IsIn; + Distance[index] = tri.FromBCS(TBC).z; + + } + + + } } From cb841b8320e48b5987a6887a8ce89ae6d15caa7a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 16 Mar 2024 19:35:16 +0900 Subject: [PATCH 010/208] chore: add AddComponentMenu --- Editor/Inspector/AbstractIslandSelectorEditor.cs | 15 +++++++++++++++ .../AbstractIslandSelectorEditor.cs.meta | 11 +++++++++++ .../NewGameObjectAndAddTTTComponent.cs | 8 ++++++++ Runtime/IslandSelect/AbstructIslandSelector.cs | 2 ++ Runtime/IslandSelect/BoxIslandSelector.cs | 9 +++++++++ Runtime/IslandSelect/BoxIslandSelector.cs.meta | 2 +- Runtime/IslandSelect/IslandSelectOR.cs | 4 ++++ Runtime/IslandSelect/IslandSelectOR.cs.meta | 2 +- Runtime/IslandSelect/IslandSelectorAND.cs | 4 ++++ Runtime/IslandSelect/IslandSelectorAND.cs.meta | 2 +- Runtime/IslandSelect/RayCastIslandSelector.cs | 13 ++++++++++++- .../IslandSelect/RayCastIslandSelector.cs.meta | 2 +- Runtime/IslandSelect/SphereIslandSelector.cs | 10 ++++++++++ Runtime/IslandSelect/SphereIslandSelector.cs.meta | 2 +- 14 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 Editor/Inspector/AbstractIslandSelectorEditor.cs create mode 100644 Editor/Inspector/AbstractIslandSelectorEditor.cs.meta diff --git a/Editor/Inspector/AbstractIslandSelectorEditor.cs b/Editor/Inspector/AbstractIslandSelectorEditor.cs new file mode 100644 index 00000000..29720bcf --- /dev/null +++ b/Editor/Inspector/AbstractIslandSelectorEditor.cs @@ -0,0 +1,15 @@ +using UnityEditor; +using net.rs64.TexTransTool.Decal.Cylindrical; +using net.rs64.TexTransTool.IslandSelector; +namespace net.rs64.TexTransTool.Editor +{ + [CustomEditor(typeof(AbstractIslandSelector), true)] + internal class AbstractIslandSelectorEditor : UnityEditor.Editor + { + public override void OnInspectorGUI() + { + TextureTransformerEditor.DrawerWarning(target.GetType().Name); + base.OnInspectorGUI(); + } + } +} diff --git a/Editor/Inspector/AbstractIslandSelectorEditor.cs.meta b/Editor/Inspector/AbstractIslandSelectorEditor.cs.meta new file mode 100644 index 00000000..af2b356f --- /dev/null +++ b/Editor/Inspector/AbstractIslandSelectorEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b0fdaf37887290c46b1f190812cb40e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index 15a3b843..cf618cf9 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -1,4 +1,5 @@ using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.IslandSelector; using net.rs64.TexTransTool.MatAndTexUtils; using net.rs64.TexTransTool.MultiLayerImage; using net.rs64.TexTransTool.TextureAtlas; @@ -41,5 +42,12 @@ static void C() where TTB : MonoBehaviour [M(BP + MatAndTexRelativeSeparator.MenuPath)] static void MATRS() => C(); [M(BP + MaterialModifier.MenuPath)] static void MM() => C(); + [M(BP + BoxIslandSelector.MenuPath)] static void BIS() => C(); + [M(BP + SphereIslandSelector.MenuPath)] static void SIS() => C(); + [M(BP + RayCastIslandSelector.MenuPath)] static void RCIS() => C(); + [M(BP + IslandSelectOR.MenuPath)] static void ISOR() => C(); + [M(BP + IslandSelectorAND.MenuPath)] static void ISAND() => C(); + + } } diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index f78c2414..d0c2bb19 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -9,6 +9,8 @@ namespace net.rs64.TexTransTool.IslandSelector { public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, IIslandSelector { + internal const string FoldoutName = "IslandSelector"; + [HideInInspector, SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; int ITexTransToolTag.SaveDataVersion => _saveDataVersion; diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs index d590a0c6..e6416f6c 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -6,8 +6,11 @@ namespace net.rs64.TexTransTool.IslandSelector { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class BoxIslandSelector : AbstractIslandSelector { + internal const string ComponentName = "TTT BoxIslandSelector"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); @@ -36,5 +39,11 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } + + void OnDrawGizmosSelected() + { + Gizmos.matrix = transform.localToWorldMatrix; + Gizmos.DrawWireCube(Vector3.zero, Vector3.one); + } } } diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs.meta b/Runtime/IslandSelect/BoxIslandSelector.cs.meta index b64583a1..859a849f 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs.meta +++ b/Runtime/IslandSelect/BoxIslandSelector.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectOR.cs b/Runtime/IslandSelect/IslandSelectOR.cs index e22ec762..e1cc8caa 100644 --- a/Runtime/IslandSelect/IslandSelectOR.cs +++ b/Runtime/IslandSelect/IslandSelectOR.cs @@ -1,12 +1,16 @@ using System.Collections; using System.Collections.Generic; using net.rs64.TexTransCore.Island; +using UnityEngine; using UnityEngine.Profiling; namespace net.rs64.TexTransTool.IslandSelector { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class IslandSelectOR : AbstractIslandSelector { + internal const string ComponentName = "TTT IslandSelectOR"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; public List IslandSelectors; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { diff --git a/Runtime/IslandSelect/IslandSelectOR.cs.meta b/Runtime/IslandSelect/IslandSelectOR.cs.meta index ec68e9bc..66b13575 100644 --- a/Runtime/IslandSelect/IslandSelectOR.cs.meta +++ b/Runtime/IslandSelect/IslandSelectOR.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs index e2a33c10..18e012b4 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -1,12 +1,16 @@ using System.Collections; using System.Collections.Generic; using net.rs64.TexTransCore.Island; +using UnityEngine; using UnityEngine.Profiling; namespace net.rs64.TexTransTool.IslandSelector { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class IslandSelectorAND : AbstractIslandSelector { + internal const string ComponentName = "TTT IslandSelectorAND"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; public List IslandSelectors; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs.meta b/Runtime/IslandSelect/IslandSelectorAND.cs.meta index bdc5010e..3c0b2345 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs.meta +++ b/Runtime/IslandSelect/IslandSelectorAND.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs index b71709d5..ba7c6fa3 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -11,9 +11,12 @@ namespace net.rs64.TexTransTool.IslandSelector { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class RayCastIslandSelector : AbstractIslandSelector { - public float IslandSelectorRange; + internal const string ComponentName = "TTT RayCastIslandSelector"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + public float IslandSelectorRange = 0.1f; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return RayCastIslandSelect(GetIslandSelectorRay(), islands, islandDescription); @@ -71,6 +74,14 @@ internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay } internal IslandSelectorRay GetIslandSelectorRay() { return new IslandSelectorRay(new Ray(transform.position, transform.forward), IslandSelectorRange); } + + + + void OnDrawGizmosSelected() + { + Gizmos.matrix = transform.localToWorldMatrix; + Gizmos.DrawLine(Vector3.zero, new Vector3(0,0,IslandSelectorRange)); + } } internal class RayCastIslandSelectorClass : IIslandSelector diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs.meta b/Runtime/IslandSelect/RayCastIslandSelector.cs.meta index 4a2432a1..144cf3e1 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs.meta +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index f7bfa37d..a7916f53 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -2,11 +2,15 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Island; +using UnityEngine; namespace net.rs64.TexTransTool.IslandSelector { + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class SphereIslandSelector : AbstractIslandSelector { + internal const string ComponentName = "TTT SphereIslandSelector"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; public float SphereSize = 0.1f; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) @@ -31,5 +35,11 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } + + void OnDrawGizmosSelected() + { + Gizmos.matrix = transform.localToWorldMatrix; + Gizmos.DrawWireSphere(Vector3.zero, SphereSize); + } } } diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs.meta b/Runtime/IslandSelect/SphereIslandSelector.cs.meta index b06c98f6..7cf02ba8 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs.meta +++ b/Runtime/IslandSelect/SphereIslandSelector.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: From f01fc94888d304381d821a6bb378b6bcf4cd49dc Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 14:40:54 +0900 Subject: [PATCH 011/208] chore: change list to childe --- Runtime/CommonComponent/TexTransGroup.cs | 7 ++++++- Runtime/IslandSelect/IslandSelectOR.cs | 3 +-- Runtime/IslandSelect/IslandSelectorAND.cs | 3 +-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Runtime/CommonComponent/TexTransGroup.cs b/Runtime/CommonComponent/TexTransGroup.cs index 51d07907..acdea870 100644 --- a/Runtime/CommonComponent/TexTransGroup.cs +++ b/Runtime/CommonComponent/TexTransGroup.cs @@ -13,7 +13,7 @@ public class TexTransGroup : TexTransCallEditorBehavior internal const string MenuPath = TexTransGroup.FoldoutName + "/" + ComponentName; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; - internal IEnumerable Targets => transform.GetChildren().Select(x => x.GetComponent()).Where(x => x != null); + internal IEnumerable Targets => GetChildeComponent(transform); internal override List GetRenderers => TextureTransformerFilter(Targets).SelectMany(I => I.GetRenderers).ToList(); @@ -36,5 +36,10 @@ bool PossibleApplyCheck() return possibleFlag; } + internal static IEnumerable GetChildeComponent(Transform transform) + { + return transform.GetChildren().Select(x => x.GetComponent()).Where(x => x != null); + } + } } diff --git a/Runtime/IslandSelect/IslandSelectOR.cs b/Runtime/IslandSelect/IslandSelectOR.cs index e1cc8caa..5e69c719 100644 --- a/Runtime/IslandSelect/IslandSelectOR.cs +++ b/Runtime/IslandSelect/IslandSelectOR.cs @@ -11,11 +11,10 @@ public class IslandSelectOR : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - public List IslandSelectors; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; - foreach (var islandSelector in IslandSelectors) + foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) { Profiler.BeginSample(islandSelector.GetType().Name); var selectBit = islandSelector.IslandSelect(islands, islandDescription); diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs index 18e012b4..73b24b96 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -11,11 +11,10 @@ public class IslandSelectorAND : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectorAND"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - public List IslandSelectors; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; - foreach (var islandSelector in IslandSelectors) + foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) { Profiler.BeginSample(islandSelector.GetType().Name); var selectBit = islandSelector.IslandSelect(islands, islandDescription); From 647d1f47388899699125dc0a46316dac5b1c1b61 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 18:30:56 +0900 Subject: [PATCH 012/208] chore: ray range apply lossyScale.z --- Runtime/IslandSelect/RayCastIslandSelector.cs | 8 ++++---- TexTransCore/Island/IslandCulling.cs | 7 +++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs index ba7c6fa3..1207417e 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -26,7 +26,7 @@ internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay { var bitArray = new BitArray(islands.Length); var ray = islandSelectorRay; - var rayMatrix = ray.Ray.GetRayMatrix(); + var rayMatrix = ray.GetRayMatrix(); var jobs = new JobHandle[islands.Length]; var hitResults = new NativeArray[islands.Length]; var distances = new NativeArray[islands.Length]; @@ -61,7 +61,7 @@ internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay { if (!hRes[ti]) { continue; } if (distance[ti] < 0) { continue; } - if (distance[ti] > ray.RayRange) { continue; } + if (distance[ti] > 1) { continue; } bitArray[i] = true; break; @@ -73,14 +73,14 @@ internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay return bitArray; } - internal IslandSelectorRay GetIslandSelectorRay() { return new IslandSelectorRay(new Ray(transform.position, transform.forward), IslandSelectorRange); } + internal IslandSelectorRay GetIslandSelectorRay() { return new IslandSelectorRay(new Ray(transform.position, transform.forward), transform.lossyScale.z * IslandSelectorRange); } void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; - Gizmos.DrawLine(Vector3.zero, new Vector3(0,0,IslandSelectorRange)); + Gizmos.DrawLine(Vector3.zero, new Vector3(0, 0, IslandSelectorRange)); } } diff --git a/TexTransCore/Island/IslandCulling.cs b/TexTransCore/Island/IslandCulling.cs index 87915b60..28ab000c 100644 --- a/TexTransCore/Island/IslandCulling.cs +++ b/TexTransCore/Island/IslandCulling.cs @@ -26,6 +26,13 @@ public IslandSelectorRay(Ray ray, float rayRange) this.RayRange = rayRange; } + public Matrix4x4 GetRayMatrix() + { + var rot = Quaternion.LookRotation(Ray.direction); + var rayMatrix = Matrix4x4.TRS(Ray.origin, rot, new Vector3(1, 1, RayRange)).inverse; + return rayMatrix; + } + } internal static class IslandCulling { From a8290938f4ad0c4d733043f7fbc67e78e90f401d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 18:40:05 +0900 Subject: [PATCH 013/208] chore: create inspector and migrate --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 50 ++++++++++++++++++++- Editor/Localize/en_US.po | 20 ++------- Editor/Localize/ja_JP.po | 20 ++------- Runtime/Decal/SimpleDecal.cs | 10 ++--- 4 files changed, 62 insertions(+), 38 deletions(-) diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 436e3e4e..02139fdf 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -3,6 +3,7 @@ using net.rs64.TexTransTool.Decal; using UnityEngine.UIElements; using UnityEditor.UIElements; +using net.rs64.TexTransTool.IslandSelector; namespace net.rs64.TexTransTool.Editor.Decal { @@ -46,7 +47,16 @@ public override void OnInspectorGUI() if (s_ExperimentalFutureOption) { var sIslandSelector = thisSObject.FindProperty("IslandSelector"); - EditorGUILayout.PropertyField(sIslandSelector); + EditorGUILayout.PropertyField(sIslandSelector, "SimpleDecal:prop:ExperimentalFuture:IslandCulling".Glc()); + + if (sIslandSelector.objectReferenceValue == null || sIslandSelector.objectReferenceValue is RayCastIslandSelector) + { + var sIslandCulling = thisSObject.FindProperty("IslandCulling"); + if (sIslandCulling.boolValue && GUILayout.Button("Migrate IslandCulling to IslandSelector")) + { + MigrateIslandCullingToIslandSelector(thisObject); + } + } var sUseDepth = thisSObject.FindProperty("UseDepth"); var sDepthInvert = thisSObject.FindProperty("DepthInvert"); @@ -153,6 +163,44 @@ private void OnDisable() } + + + + + + + + public void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) + { + if (simpleDecal.IslandSelector != null) + { + if (simpleDecal.IslandSelector is not RayCastIslandSelector) { Debug.LogError("IslandSelector にすでに何かが割り当てられているため、マイグレーションを実行できません。"); return; } + else { if (!EditorUtility.DisplayDialog("Migrate IslandCulling To IslandSelector", "IslandSelector に RayCastIslandSelector が既に割り当てられています。 \n 割り当てられている RayCastIslandSelector を編集する形でマイグレーションしますか?", "実行")) { return; } } + } + Undo.RecordObject(simpleDecal, "MigrateIslandCullingToIslandSelector"); + + simpleDecal.IslandCulling = false; + var islandSelector = simpleDecal.IslandSelector as RayCastIslandSelector; + + if (islandSelector == null) + { + var go = new GameObject("RayCastIslandSelector"); + go.transform.SetParent(simpleDecal.transform, false); + simpleDecal.IslandSelector = islandSelector = go.AddComponent(); + } + Undo.RecordObject(islandSelector, "MigrateIslandCullingToIslandSelector - islandSelectorEdit"); + + + Vector3 selectorOrigin = new Vector2(simpleDecal.IslandSelectorPos.x - 0.5f, simpleDecal.IslandSelectorPos.y - 0.5f); + + + var ltwMatrix = simpleDecal.transform.localToWorldMatrix; + islandSelector.transform.position = ltwMatrix.MultiplyPoint3x4(selectorOrigin); + islandSelector.IslandSelectorRange = simpleDecal.IslandSelectorRange; + + } + + } diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 69b66acc..c161983f 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -342,23 +342,11 @@ msgstr "SideCulling" msgid "SimpleDecal:prop:SideCulling:tooltip" msgstr "Setting to cull back side polygon when view from the decal." -msgid "SimpleDecal:prop:ExperimentalFuture:IslandCulling" -msgstr "IslandCulling" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect" +msgstr "IslandSelect" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandCulling:tooltip" -msgstr "Feature to cull decal with uv island." - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorPos" -msgstr "IslandSelectorPos" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorPos:tooltip" -msgstr "Setting to adjust the position of island selector, X is width, Y is height." - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorRange" -msgstr "IslandSelectorRange" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorRange:tooltip" -msgstr "アイランドセレクターの最大距離の設定" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect:tooltip" +msgstr "A feature that decal apply area for select island." msgid "SimpleDecal:prop:ExperimentalFuture:UseDepth" msgstr "UseDepth" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 505f5f13..6943093b 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -343,23 +343,11 @@ msgstr "サイドカリング" msgid "SimpleDecal:prop:SideCulling:tooltip" msgstr "ポリゴンがデカールから見て裏面のポリゴンにデカールを貼らない設定" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandCulling" -msgstr "アイランドカリング" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect" +msgstr "アイランド選択" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandCulling:tooltip" -msgstr "UVのまとまりの範囲でデカールをカリングする機能" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorPos" -msgstr "アイランドセレクターの位置" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorPos:tooltip" -msgstr "Xが横、Yが縦でアイランドセレクターの位置を調整する設定" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorRange" -msgstr "アイランドセレクターの最大距離" - -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelectorRange:tooltip" -msgstr "アイランドセレクターの最大距離の設定" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect:tooltip" +msgstr "アイランドで選択を指定しその範囲にデカールを張る機能" msgid "SimpleDecal:prop:ExperimentalFuture:UseDepth" msgstr "深度デカール" diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index f84e1334..5fd44b7f 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -24,11 +24,11 @@ public sealed class SimpleDecal : AbstractSingleDecal UseDepth ? new bool?(DepthInvert) : null; - #region V3SaveData - [Obsolete("V3SaveData", true)][SerializeField] internal bool IslandCulling = false; - [Obsolete("V3SaveData", true)][SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); - [Obsolete("V3SaveData", true)][SerializeField] internal float IslandSelectorRange = 1; - #endregion + //次のマイナーで obsolete にする + [SerializeField] internal bool IslandCulling = false; + [SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); + [SerializeField] internal float IslandSelectorRange = 1; + internal override ParallelProjectionSpace GetSpaceConverter() { return new ParallelProjectionSpace(transform.worldToLocalMatrix); } From bd8564e3454f4054f665fd99c1a472ca4b6e266f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 18:46:35 +0900 Subject: [PATCH 014/208] fix: key is different --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 2 +- Editor/Localize/en_US.po | 4 ++-- Editor/Localize/ja_JP.po | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 02139fdf..9d763a3d 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -47,7 +47,7 @@ public override void OnInspectorGUI() if (s_ExperimentalFutureOption) { var sIslandSelector = thisSObject.FindProperty("IslandSelector"); - EditorGUILayout.PropertyField(sIslandSelector, "SimpleDecal:prop:ExperimentalFuture:IslandCulling".Glc()); + EditorGUILayout.PropertyField(sIslandSelector, "SimpleDecal:prop:ExperimentalFuture:IslandSelector".Glc()); if (sIslandSelector.objectReferenceValue == null || sIslandSelector.objectReferenceValue is RayCastIslandSelector) { diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index c161983f..72b9c8a8 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -342,10 +342,10 @@ msgstr "SideCulling" msgid "SimpleDecal:prop:SideCulling:tooltip" msgstr "Setting to cull back side polygon when view from the decal." -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelector" msgstr "IslandSelect" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect:tooltip" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelector:tooltip" msgstr "A feature that decal apply area for select island." msgid "SimpleDecal:prop:ExperimentalFuture:UseDepth" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 6943093b..f4a1fa4d 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -343,10 +343,10 @@ msgstr "サイドカリング" msgid "SimpleDecal:prop:SideCulling:tooltip" msgstr "ポリゴンがデカールから見て裏面のポリゴンにデカールを貼らない設定" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelector" msgstr "アイランド選択" -msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelect:tooltip" +msgid "SimpleDecal:prop:ExperimentalFuture:IslandSelector:tooltip" msgstr "アイランドで選択を指定しその範囲にデカールを張る機能" msgid "SimpleDecal:prop:ExperimentalFuture:UseDepth" From e0711976fe999d83d4da61763a9b06bf4a28250c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 19:30:33 +0900 Subject: [PATCH 015/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index fc4e1cfb..00f38295 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -7,10 +7,16 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Added +- IslandSelector が追加されました (#422) +- SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) + - IslandCulling からのマイグレーションが追加されました (#422) + ### Changed ### Removed +- IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) + ### Fixed ### Deprecated From 93d56182693858c6cc50c5d3580eab40a7b91861 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 17 Mar 2024 23:14:44 +0900 Subject: [PATCH 016/208] feat: create MipMap.compute and more --- Editor/Utils/LateInitializeUtility.cs | 5 ++- TexTransCore/MipMap.meta | 8 ++++ TexTransCore/MipMap/MipMap.compute | 42 +++++++++++++++++++ .../MipMap.compute.meta} | 3 +- TexTransCore/MipMap/MipMapUtility.cs | 40 ++++++++++++++++++ TexTransCore/MipMap/MipMapUtility.cs.meta | 11 +++++ .../ShaderAsset/Compute/MipMapper.compute | 37 ---------------- 7 files changed, 106 insertions(+), 40 deletions(-) create mode 100644 TexTransCore/MipMap.meta create mode 100644 TexTransCore/MipMap/MipMap.compute rename TexTransCore/{TransTextureCore/ShaderAsset/Compute/MipMapper.compute.meta => MipMap/MipMap.compute.meta} (67%) create mode 100644 TexTransCore/MipMap/MipMapUtility.cs create mode 100644 TexTransCore/MipMap/MipMapUtility.cs.meta delete mode 100644 TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute diff --git a/Editor/Utils/LateInitializeUtility.cs b/Editor/Utils/LateInitializeUtility.cs index 8f57fb37..b7322519 100644 --- a/Editor/Utils/LateInitializeUtility.cs +++ b/Editor/Utils/LateInitializeUtility.cs @@ -1,5 +1,7 @@ using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.MipMap; using net.rs64.TexTransTool.MultiLayerImage; +using UnityEditor; using UnityEngine; namespace net.rs64.TexTransTool.Utils { @@ -24,6 +26,7 @@ public static void Initializer() PSDImportedRasterImage.MargeColorAndOffsetShader = Shader.Find(PSDImportedRasterImage.MARGE_COLOR_AND_OFFSET_SHADER); SpecialLayerShaders.Init(); TTTImageAssets.Init(); + MipMapUtility.MipMapShader = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath("5f6d88c53276bb14eace10771023ae01")); } } -} \ No newline at end of file +} diff --git a/TexTransCore/MipMap.meta b/TexTransCore/MipMap.meta new file mode 100644 index 00000000..7e4c9163 --- /dev/null +++ b/TexTransCore/MipMap.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 501bb4e88f6ee144dbdd4840361ea275 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/MipMap/MipMap.compute b/TexTransCore/MipMap/MipMap.compute new file mode 100644 index 00000000..af8d4fd6 --- /dev/null +++ b/TexTransCore/MipMap/MipMap.compute @@ -0,0 +1,42 @@ +#pragma kernel Average32 +#pragma kernel Average1 + + +RWTexture2D RTex; +RWTexture2D WTex; + +int2 PixelRatio; + +float4 ChakeNaN(float4 val,float4 replase){ return isnan(val) ? replase : val ;} +float3 ChakeNaN(float3 val,float3 replase){ return isnan(val) ? replase : val ;} + +void Average(uint2 id) +{ + float3 wcol = float3(0,0,0); + float3 col = float3(0,0,0); + float alpha = 0; + int count = 0; + + int2 readPosOffset = id.xy * PixelRatio; + for(int y = 0; PixelRatio.y > y; y += 1) + { + for(int x = 0; PixelRatio.x > x; x += 1) + { + float4 rCol = RTex[readPosOffset + int2(x,y)]; + wcol += rCol.rgb * rCol.a; + col += rCol.rgb; + alpha += rCol.a; + count += 1; + } + } + + wcol /= alpha; + col /= count; + WTex[id.xy] = float4(ChakeNaN(wcol,col), alpha / count); +} + +[numthreads(32,32,1)] +void Average32(uint3 id : SV_DispatchThreadID){Average(id.xy);} + +[numthreads(1,1,1)] +void Average1(uint3 id : SV_DispatchThreadID){Average(id.xy);} diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute.meta b/TexTransCore/MipMap/MipMap.compute.meta similarity index 67% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute.meta rename to TexTransCore/MipMap/MipMap.compute.meta index 7f96ba77..b8546c6f 100644 --- a/TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute.meta +++ b/TexTransCore/MipMap/MipMap.compute.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 8cbe92e8bbac1a64ba2299ab14ec4fac +guid: 5f6d88c53276bb14eace10771023ae01 ComputeShaderImporter: externalObjects: {} - currentAPIMask: 4 userData: assetBundleName: assetBundleVariant: diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs new file mode 100644 index 00000000..5351bb67 --- /dev/null +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +namespace net.rs64.TexTransCore.MipMap +{ + internal static class MipMapUtility + { + public static ComputeShader MipMapShader; + const string WTex = "WTex"; + const string RTex = "RTex"; + const string PixelRatio = "PixelRatio"; + public static bool Average(RenderTexture renderTexture) + { + if (!renderTexture.useMipMap || !renderTexture.enableRandomWrite) { return false; } + var kernel32ID = MipMapShader.FindKernel("Average32"); + var kernel1ID = MipMapShader.FindKernel("Average1"); + + var width = renderTexture.width; + var height = renderTexture.height; + + bool useOne = false; + for (var mipIndex = 0; renderTexture.mipmapCount - 1 > mipIndex; mipIndex += 1) + { + width /= 2; + height /= 2; + + if (width < 32 || height < 32) { useOne = true; } + + var kernelID = useOne ? kernel1ID : kernel32ID; + var kernelSize = useOne ? 1 : 32; + + MipMapShader.SetTexture(kernelID, RTex, renderTexture, mipIndex); + MipMapShader.SetTexture(kernelID, WTex, renderTexture, mipIndex + 1); + MipMapShader.SetInts(PixelRatio, 2, 2); + MipMapShader.Dispatch(kernelID, width / kernelSize, height / kernelSize, 1); + } + + return true; + } + } +} diff --git a/TexTransCore/MipMap/MipMapUtility.cs.meta b/TexTransCore/MipMap/MipMapUtility.cs.meta new file mode 100644 index 00000000..a78c8355 --- /dev/null +++ b/TexTransCore/MipMap/MipMapUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 20e5b9eaf7866a743a7737b802a78760 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute b/TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute deleted file mode 100644 index a1476aca..00000000 --- a/TexTransCore/TransTextureCore/ShaderAsset/Compute/MipMapper.compute +++ /dev/null @@ -1,37 +0,0 @@ -#pragma kernel MipMapper - -#include "./TransHelper.hlsl" - - -Buffer Tex; -uint TexSizeX; - - -RWBuffer OutPutMap; -uint MipSizeX; - -float4 GetMip(Buffer Souse,uint TexSizeX,uint2 texel) -{ - float4 sum = 0; - float4 Pixselcount = 0; - [unroll] - for (uint x = 0; x < 2; x++) - { - [unroll] - for (uint y = 0; y < 2; y++) - { - float4 current = Souse[TwoDToOneDIndex(uint2(texel.x + x, texel.y + y),TexSizeX)]; - float IsEndable = ceil(current.w); - sum += current * IsEndable; - Pixselcount += IsEndable; - } - } - sum /= Pixselcount; - return saturate(sum); -} - - -[numthreads(32, 32, 1)] void MipMapper(uint3 id : SV_DispatchThreadID) -{ - OutPutMap[TwoDToOneDIndex(id.xy,MipSizeX)] = GetMip(Tex,TexSizeX,id.xy * 2); -} \ No newline at end of file From c0a847e5b48651f89168b0af998c13c903f70ecd Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 18 Mar 2024 00:18:24 +0900 Subject: [PATCH 017/208] chore: create preview texture from mipmap --- Editor/Domain/TextureManager.cs | 5 +- .../MultiLayerImageImporter.cs | 58 +++++++++---------- .../TexTransToolPSDImporter.cs | 4 +- TexTransCore/MipMap/MipMapUtility.cs | 16 +++++ .../TransTextureCore/Utils/TextureUtility.cs | 3 +- 5 files changed, 48 insertions(+), 38 deletions(-) diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 9f636ad5..1069dcf6 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -53,7 +53,7 @@ public void DestroyTextures() public int GetOriginalTextureSize(Texture2D texture2D) { - return NormalizePowerOfTwo(GetOriginalTexture(texture2D).width); + return TexTransCore.TransTextureCore.Utils.TextureUtility.NormalizePowerOfTwo(GetOriginalTexture(texture2D).width); } public void WriteOriginalTexture(Texture2D texture2D, RenderTexture writeTarget) { @@ -137,8 +137,5 @@ public void TextureFinalize() sTexture.ApplyModifiedPropertiesWithoutUndo(); } } - - public static int NormalizePowerOfTwo(int v) => Mathf.IsPowerOfTwo(v) ? v : Mathf.NextPowerOfTwo(v); - } } diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index 36adf09d..68d460bd 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -7,6 +7,9 @@ using System.Threading.Tasks; using UnityEditor.AssetImporters; using Unity.Collections; +using net.rs64.TexTransCore.MipMap; +using UnityEngine.Rendering; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransTool.MultiLayerImage.Importer { @@ -16,7 +19,6 @@ internal class MultiLayerImageImporter AssetImportContext _ctx; List _tttImportedImages = new(); CreateImportedImage _imageImporter; - GetPreviewImage _previewImageTaskGenerator; byte[] _souseBytes; internal delegate TTTImportedImage CreateImportedImage(ImportRasterImageData importRasterImage); @@ -25,14 +27,12 @@ internal class MultiLayerImageImporter internal MultiLayerImageImporter(TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] souseBytes, - CreateImportedImage imageImporter, - GetPreviewImage previewImageTaskGenerator) + CreateImportedImage imageImporter) { _ctx = assetImportContext; _imageImporter = imageImporter; _tttImportedCanvasDescription = tttImportedCanvasDescription; _souseBytes = souseBytes; - _previewImageTaskGenerator = previewImageTaskGenerator; } internal void AddLayers(Transform thisTransForm, List abstractLayers) @@ -190,37 +190,33 @@ internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstra internal void CreatePreview() { - var setting = new TextureGenerationSettings(TextureImporterType.Default); - setting.textureImporterSettings.alphaIsTransparency = true; - setting.textureImporterSettings.mipmapEnabled = false; - setting.textureImporterSettings.filterMode = FilterMode.Bilinear; - setting.textureImporterSettings.readable = false; - - setting.platformSettings.maxTextureSize = 1024; - setting.platformSettings.resizeAlgorithm = TextureResizeAlgorithm.Mitchell; - setting.platformSettings.textureCompression = TextureImporterCompression.Compressed; - setting.platformSettings.compressionQuality = 100; - - setting.sourceTextureInformation.width = _tttImportedCanvasDescription.Width; - setting.sourceTextureInformation.height = _tttImportedCanvasDescription.Height; - setting.sourceTextureInformation.containsAlpha = true; - setting.sourceTextureInformation.hdr = false; - - foreach (var taskResult in ParallelExecuter<(byte[] souseBytes, TTTImportedImage importRasterImage), NativeArray>( - i => _previewImageTaskGenerator.Invoke(i.souseBytes, i.importRasterImage), - _tttImportedImages.Select(i => (_souseBytes, i)))) + var rt = new RenderTexture(TextureUtility.NormalizePowerOfTwo(_tttImportedCanvasDescription.Width), TextureUtility.NormalizePowerOfTwo(_tttImportedCanvasDescription.Height), 0, RenderTextureFormat.ARGB32); + rt.enableRandomWrite = true; + rt.useMipMap = true; + rt.autoGenerateMips = false; + foreach (var importedImage in _tttImportedImages) { - using (var data = taskResult.TaskResult) - { - var image = taskResult.TaskData.importRasterImage; + rt.Clear(); + importedImage.LoadImage(_souseBytes, rt); + MipMapUtility.Average(rt); - var output = TextureGenerator.GenerateTexture(setting, data); + var mipMapCount = MipMapUtility.MipMapCountFrom(rt.width, 1024); - image.PreviewTexture = output.texture; - image.PreviewTexture.name = image.name + "_Preview"; - _ctx.AddObjectToAsset(output.texture.name, output.texture); - } + var request = AsyncGPUReadback.Request(rt, mipMapCount); + + var tex2d = new Texture2D(1024, 1024, TextureFormat.RGBA32, false); + + request.WaitForCompletion(); + using (var data = request.GetData()) { tex2d.LoadRawTextureData(data); } + + EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); + tex2d.Apply(true, true); + + importedImage.PreviewTexture = tex2d; + importedImage.PreviewTexture.name = importedImage.name + "_Preview"; + _ctx.AddObjectToAsset(tex2d.name, tex2d); } + UnityEngine.Object.DestroyImmediate(rt); } private static IEnumerable<(T TaskData, T2 TaskResult)> ParallelExecuter(Func> taskExecute, IEnumerable taskData, int? forceParallelSize = null, Action progressCallBack = null) { diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index a66f1ed7..07841366 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -49,7 +49,7 @@ public override void OnImportAsset(AssetImportContext ctx) ctx.AddObjectToAsset(canvasDescription.name, canvasDescription); multiLayerImageCanvas.tttImportedCanvasDescription = canvasDescription; - var mliImporter = new MultiLayerImageImporter(canvasDescription, ctx, psdBytes, CreatePSDImportedImage, GetPreviewImage); + var mliImporter = new MultiLayerImageImporter(canvasDescription, ctx, psdBytes, CreatePSDImportedImage); mliImporter.AddLayers(multiLayerImageCanvas.transform, pSDData.RootLayers); EditorUtility.DisplayProgressBar("Import Canvas", "CreatePreview", 0.1f); @@ -130,4 +130,4 @@ static NativeArray LoadOffsetEvalRasterMask(byte[] souseBytes, PSDImpor } -} \ No newline at end of file +} diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 5351bb67..8e3e0051 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -36,5 +36,21 @@ public static bool Average(RenderTexture renderTexture) return true; } + + public static int MipMapCountFrom(int width, int targetWith) + { + if (width < targetWith) { return -1; } + var count = 0; + if (width == targetWith) { return count; } + while (width >= 0 && count < 1024)//1024 回で止まるのはただのセーフティ + { + width /= 2; + count += 1; + if (width == targetWith) { return count; } + } + return -1; + } + + } } diff --git a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs index 6b376e8c..4fc36f0b 100644 --- a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs +++ b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs @@ -125,5 +125,6 @@ public static Texture2D CreateFillTexture(Vector2Int size, Color fillColor) return TestTex; } + public static int NormalizePowerOfTwo(int v) => Mathf.IsPowerOfTwo(v) ? v : Mathf.NextPowerOfTwo(v); } -} \ No newline at end of file +} From f2c2943ebebcb41792e61bfc4ab32eace08853f1 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 18 Mar 2024 00:26:24 +0900 Subject: [PATCH 018/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 00f38295..63a94dd6 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -10,6 +10,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelector が追加されました (#422) - SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) - IslandCulling からのマイグレーションが追加されました (#422) +- TTT PSD Importer のプレビューの生成が大幅に高速化されました (#424) ### Changed From 581b4b4339e43f70b67b0a49bdf630ee3fe08e06 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 18 Mar 2024 23:28:49 +0900 Subject: [PATCH 019/208] feat: TexTransToolPSDImporterEditor and preview icon --- .../MultiLayerImageCanvasEditor.cs | 23 +++++ .../MultiLayerImageImporter.cs | 99 +++++++++++-------- .../TexTransToolPSDImporter.cs | 83 +++++++--------- Runtime/HideFlagPatch.cs | 45 +++++++++ Runtime/HideFlagPatch.cs.meta | 11 +++ .../MultiLayerImage/MultiLayerImageCanvas.cs | 17 ++-- TexTransCore/MipMap/MipMapUtility.cs | 49 ++++++--- 7 files changed, 218 insertions(+), 109 deletions(-) create mode 100644 Runtime/HideFlagPatch.cs create mode 100644 Runtime/HideFlagPatch.cs.meta diff --git a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs index 431208e4..51eca2df 100644 --- a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs +++ b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs @@ -1,5 +1,8 @@ using UnityEditor; using net.rs64.TexTransTool.MultiLayerImage; +using UnityEngine; +using System.Linq; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransTool.Editor.MultiLayerImage { [CustomEditor(typeof(MultiLayerImageCanvas))] @@ -18,5 +21,25 @@ public override void OnInspectorGUI() sTarget.ApplyModifiedProperties(); } + + public override bool HasPreviewGUI() { return true; } + + public override void DrawPreview(Rect previewArea) + { + var mlic = target as MultiLayerImageCanvas; + DrawPreviewMLIC(previewArea, mlic); + } + + public static void DrawPreviewMLIC(Rect previewArea, MultiLayerImageCanvas mlic) + { + var texManager = new TextureManager(true); + var canvasResult = mlic.EvaluateCanvas(texManager, 1024); + texManager.DestroyTextures(); + + EditorGUI.DrawTextureTransparent(previewArea, canvasResult, ScaleMode.ScaleToFit); + RenderTexture.ReleaseTemporary(canvasResult); + } + + } } diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index 68d460bd..6662e20f 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -10,34 +10,39 @@ using net.rs64.TexTransCore.MipMap; using UnityEngine.Rendering; using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransCore.BlendTexture; +using TextureUtility = net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.MultiLayerImage.Importer { internal class MultiLayerImageImporter { + MultiLayerImageCanvas _multiLayerImageCanvas; TTTImportedCanvasDescription _tttImportedCanvasDescription; AssetImportContext _ctx; List _tttImportedImages = new(); CreateImportedImage _imageImporter; byte[] _souseBytes; + DownScalingAlgorism _previewImageDownScalingAlgorism; internal delegate TTTImportedImage CreateImportedImage(ImportRasterImageData importRasterImage); internal delegate Task> GetPreviewImage(byte[] souseBytes, TTTImportedImage importRasterImage);//つまり正方形にオフセットの入った後の画像を取得するやつ RGBA32 - internal MultiLayerImageImporter(TTTImportedCanvasDescription tttImportedCanvasDescription, - AssetImportContext assetImportContext, - byte[] souseBytes, - CreateImportedImage imageImporter) + internal MultiLayerImageImporter(MultiLayerImageCanvas multiLayerImageCanvas, TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] souseBytes, CreateImportedImage imageImporter, DownScalingAlgorism previewImageDownScalingAlgorism) { + _multiLayerImageCanvas = multiLayerImageCanvas; _ctx = assetImportContext; _imageImporter = imageImporter; _tttImportedCanvasDescription = tttImportedCanvasDescription; _souseBytes = souseBytes; + _previewImageDownScalingAlgorism = previewImageDownScalingAlgorism; + } - internal void AddLayers(Transform thisTransForm, List abstractLayers) + internal void AddLayers(List abstractLayers, Transform parent = null) { - var parent = thisTransForm; + parent ??= _multiLayerImageCanvas.transform; var count = 0; foreach (var layer in abstractLayers.Reverse()) { @@ -151,7 +156,6 @@ private void CreateRasterLayer(GameObject newLayer, RasterLayerData rasterLayer) var importedImage = _imageImporter.Invoke(rasterLayer.RasterTexture); importedImage.name = rasterLayer.LayerName + "_Tex"; importedImage.CanvasDescription = _tttImportedCanvasDescription; - _ctx.AddObjectToAsset(importedImage.name, importedImage); _tttImportedImages.Add(importedImage); rasterLayerComponent.ImportedImage = importedImage; } @@ -163,7 +167,6 @@ private ILayerMask MaskTexture(LayerMaskData maskData, string layerName) var importMask = _imageImporter.Invoke(maskData.MaskTexture); importMask.name = layerName + "_MaskTex"; importMask.CanvasDescription = _tttImportedCanvasDescription; - _ctx.AddObjectToAsset(importMask.name, importMask); _tttImportedImages.Add(importMask); return new TTTImportedLayerMask(maskData.LayerMaskDisabled, importMask); @@ -176,7 +179,7 @@ private void CreateLayerFolder(GameObject newLayer, LayerFolderData layerFolder) CopyFromData(layerFolderComponent, layerFolder); layerFolderComponent.PassThrough = layerFolder.PassThrough; - AddLayers(newLayer.transform, layerFolder.Layers); + AddLayers(layerFolder.Layers, newLayer.transform); } internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstractLayerData) @@ -198,12 +201,10 @@ internal void CreatePreview() { rt.Clear(); importedImage.LoadImage(_souseBytes, rt); - MipMapUtility.Average(rt); + MipMapUtility.GenerateMips(rt, _previewImageDownScalingAlgorism); var mipMapCount = MipMapUtility.MipMapCountFrom(rt.width, 1024); - var request = AsyncGPUReadback.Request(rt, mipMapCount); - var tex2d = new Texture2D(1024, 1024, TextureFormat.RGBA32, false); request.WaitForCompletion(); @@ -213,44 +214,58 @@ internal void CreatePreview() tex2d.Apply(true, true); importedImage.PreviewTexture = tex2d; - importedImage.PreviewTexture.name = importedImage.name + "_Preview"; - _ctx.AddObjectToAsset(tex2d.name, tex2d); } + if (rt == RenderTexture.active) { RenderTexture.active = null; } UnityEngine.Object.DestroyImmediate(rt); + + var texManager = new TextureManager(true); + var canvasResult = _multiLayerImageCanvas.EvaluateCanvas(texManager, 1024); + texManager.DestroyTextures(); + + var resultTex = canvasResult.CopyTexture2D(overrideUseMip: true); + EditorUtility.CompressTexture(resultTex, TextureFormat.DXT5, 100); + resultTex.name = "TTT-CanvasPreviewResult"; + _ctx.AddObjectToAsset(resultTex.name, resultTex); + RenderTexture.ReleaseTemporary(canvasResult); + + var quadMesh = GameObject.CreatePrimitive(PrimitiveType.Quad); + var mesh = quadMesh.GetComponent().sharedMesh; + GameObject.DestroyImmediate(quadMesh); + + var prevGo = new GameObject("TTT-CanvasPreview"); + var hideFlagPatch = prevGo.AddComponent(); + prevGo.tag ="EditorOnly"; + var quad = prevGo.AddComponent(); + + quad.transform.SetParent(_multiLayerImageCanvas.transform, false); + quad.sharedMesh = mesh; + quad.sharedMaterial = new Material(Shader.Find("Unlit/Texture")) { mainTexture = resultTex, name = "TTT-CanvasPreviewResult-Material" }; + quad.transform.localRotation = Quaternion.Euler(new Vector3(-20f, 60f, 0f)); + quad.transform.localScale = new Vector3(-0.002f, 0.002f, -0.002f); + quad.localBounds = new Bounds(Vector3.zero, new Vector3(0.31f, 0.31f, 0.001f) * 2f); + + _ctx.AddObjectToAsset("TTT-CanvasPreviewResult-Material", quad.sharedMaterial); + } - private static IEnumerable<(T TaskData, T2 TaskResult)> ParallelExecuter(Func> taskExecute, IEnumerable taskData, int? forceParallelSize = null, Action progressCallBack = null) + + public void SaveSubAsset() { - var parallelSize = forceParallelSize.HasValue ? forceParallelSize.Value : Environment.ProcessorCount; - var taskQueue = new Queue(taskData); - var taskParallel = new (T TaskData, Task Task)[parallelSize]; - var encDataCount = taskQueue.Count; var nowIndex = 0; - while (taskQueue.Count > 0) + var NameHash = new HashSet() { "TTT-CanvasPreviewResult", "TTT-CanvasPreviewResult-Material" }; + foreach (var image in _tttImportedImages.Reverse()) { - for (int i = 0; taskParallel.Length > i; i += 1) + var name = image.name; + if (NameHash.Contains(name)) { - if (taskQueue.Count > 0) - { - var task = taskQueue.Dequeue(); - taskParallel[i] = (task, Task.Run(() => taskExecute.Invoke(task))); - } - else - { - taskParallel[i] = (default, null); - break; - } + var addCount = 1; + while (NameHash.Contains(name + "-" + addCount)) { addCount += 1; } + name = name + "-" + addCount; } + NameHash.Add(name); - foreach (var taskPair in taskParallel) - { - if (taskPair.Task == null) { break; } - yield return (taskPair.TaskData, TaskAwaiter(taskPair.Task).Result); - nowIndex += 1; - progressCallBack?.Invoke(nowIndex / (float)encDataCount); - } - } - static async Task TaskAwaiter(Task task) - { - return await task.ConfigureAwait(false); + image.name = name; + image.PreviewTexture.name = image.name + "_Preview"; + _ctx.AddObjectToAsset(name, image); + _ctx.AddObjectToAsset(image.PreviewTexture.name, image.PreviewTexture); } } } diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index 07841366..12486450 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -1,21 +1,27 @@ using System; using System.IO; +using System.Linq; using System.Threading.Tasks; using net.rs64.MultiLayerImage.LayerData; using net.rs64.MultiLayerImage.Parser.PSD; +using net.rs64.TexTransCore.MipMap; using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore.TransTextureCore.Utils; using Unity.Collections; using UnityEditor; using UnityEditor.AssetImporters; using UnityEngine; + namespace net.rs64.TexTransTool.MultiLayerImage.Importer { [ScriptedImporter(1, new string[] { }, new string[] { "psd" }, AllowCaching = true)] public class TexTransToolPSDImporter : ScriptedImporter { + public DownScalingAlgorism PreviewImageDownScalingAlgorism; public override void OnImportAsset(AssetImportContext ctx) { NativeLeakDetection.Mode = NativeLeakDetectionMode.EnabledWithStackTrace; + EditorUtility.DisplayProgressBar("Parse PSD", "ReadBytes", 0.2f); var psdBytes = File.ReadAllBytes(ctx.assetPath); @@ -49,17 +55,20 @@ public override void OnImportAsset(AssetImportContext ctx) ctx.AddObjectToAsset(canvasDescription.name, canvasDescription); multiLayerImageCanvas.tttImportedCanvasDescription = canvasDescription; - var mliImporter = new MultiLayerImageImporter(canvasDescription, ctx, psdBytes, CreatePSDImportedImage); - mliImporter.AddLayers(multiLayerImageCanvas.transform, pSDData.RootLayers); + var mliImporter = new MultiLayerImageImporter(multiLayerImageCanvas, canvasDescription, ctx, psdBytes, CreatePSDImportedImage, PreviewImageDownScalingAlgorism); + mliImporter.AddLayers(pSDData.RootLayers); - EditorUtility.DisplayProgressBar("Import Canvas", "CreatePreview", 0.1f); + EditorUtility.DisplayProgressBar("Import Canvas", "CreatePreview", 0f); mliImporter.CreatePreview(); - EditorUtility.DisplayProgressBar("Import Canvas", "CreatePreview", 1f); + EditorUtility.DisplayProgressBar("Import Canvas", "SaveSubAsset", 0.5f); + mliImporter.SaveSubAsset(); + EditorUtility.DisplayProgressBar("Import Canvas", "END", 1f); } finally { EditorUtility.ClearProgressBar(); } + NativeLeakDetection.Mode = NativeLeakDetectionMode.Disabled; } internal TTTImportedImage CreatePSDImportedImage(ImportRasterImageData importRasterImage) @@ -82,52 +91,34 @@ internal TTTImportedImage CreatePSDImportedImage(ImportRasterImageData importRas } } - internal Task> GetPreviewImage(byte[] souseBytes, TTTImportedImage importRasterImage) - { - var canvasSize = new Vector2Int(importRasterImage.CanvasDescription.Width, importRasterImage.CanvasDescription.Height); - switch (importRasterImage) - { - case PSDImportedRasterImage pSDImportedRasterImage: - { - var data = pSDImportedRasterImage.RasterImageData; - return Task.Run(() => LoadOffsetEvalRasterLayer(souseBytes, data, canvasSize)); - } - case PSDImportedRasterMaskImage pSDImportedRasterMaskImage: - { - var data = pSDImportedRasterMaskImage.MaskImageData; - return Task.Run(() => LoadOffsetEvalRasterMask(souseBytes, data, canvasSize)); - } - default: - throw new ArgumentException(); - } - - static NativeArray LoadOffsetEvalRasterLayer(byte[] souseBytes, PSDImportedRasterImageData psdRasterData, Vector2Int canvasSize) - { - var image = PSDImportedRasterImage.LoadPSDRasterLayerData(psdRasterData, souseBytes); - var rawMap = new LowMap(image, psdRasterData.RectTangle.GetWidth(), psdRasterData.RectTangle.GetHeight()); - var pivot = new Vector2Int(psdRasterData.RectTangle.Left, canvasSize.y - psdRasterData.RectTangle.Bottom); - return PSDHighLevelParser.DrawOffsetEvaluateTexture(rawMap, pivot, canvasSize, null).Array; - } + } - static NativeArray LoadOffsetEvalRasterMask(byte[] souseBytes, PSDImportedRasterMaskImageData psdMaskData, Vector2Int canvasSize) - { - using (var rBytes = PSDImportedRasterMaskImage.LoadPSDMaskImageData(psdMaskData, souseBytes)) - { - var bytes = new NativeArray(rBytes.Length, Allocator.TempJob); - for (var i = 0; bytes.Length > i; i += 1) - { - var col = rBytes[i]; - bytes[i] = new Color32(col, col, col, col); - } - var rawMap = new LowMap(bytes, psdMaskData.RectTangle.GetWidth(), psdMaskData.RectTangle.GetHeight()); - var pivot = new Vector2Int(psdMaskData.RectTangle.Left, canvasSize.y - psdMaskData.RectTangle.Bottom); - var defaultValue = new Color32(psdMaskData.DefaultValue, psdMaskData.DefaultValue, psdMaskData.DefaultValue, psdMaskData.DefaultValue); - return PSDHighLevelParser.DrawOffsetEvaluateTexture(rawMap, pivot, canvasSize, defaultValue).Array; + [CustomEditor(typeof(TexTransToolPSDImporter))] + class TexTransToolPSDImporterEditor : ScriptedImporterEditor + { + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("TexTransToolPSDImporter" + " " + "Common:ExperimentalWarning".GetLocalize(), MessageType.Warning); + EditorGUILayout.PropertyField(serializedObject.FindProperty("PreviewImageDownScalingAlgorism")); - } - } + base.ApplyRevertGUI(); } + public override bool HasPreviewGUI() { return true; } + public override void DrawPreview(Rect previewArea) + { + var importer = target as TexTransToolPSDImporter; + var previewTex = AssetDatabase.LoadAllAssetsAtPath(importer.assetPath).FirstOrDefault(i => i.name == "TTT-CanvasPreviewResult") as Texture2D; + if (previewTex == null) { return; } + EditorGUI.DrawTextureTransparent(previewArea, previewTex, ScaleMode.ScaleToFit); + } } + + + + + + + } diff --git a/Runtime/HideFlagPatch.cs b/Runtime/HideFlagPatch.cs new file mode 100644 index 00000000..7ff60217 --- /dev/null +++ b/Runtime/HideFlagPatch.cs @@ -0,0 +1,45 @@ +#if UNITY_EDITOR +using UnityEngine; + + +namespace net.rs64.TexTransTool +{ + [AddComponentMenu("")] + [ExecuteAlways] + internal class HideFlagPatch : MonoBehaviour, ITexTransToolTag + { + internal const HideFlags flag = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.NotEditable; + + public int SaveDataVersion => -1; + + private void RuntimePatch() + { + if (gameObject.TryGetComponent(out var renderer)) { renderer.enabled = false; } + gameObject.hideFlags = flag; + } + private void Awake() { RuntimePatch(); } + + private void Start() { RuntimePatch(); } + private void Reset() { RuntimePatch(); } + private void Update() { RuntimePatch(); } + } + + + [UnityEditor.CustomEditor(typeof(HideFlagPatch))] + class HideFlagPatchEditor : UnityEditor.Editor + { + private void OnEnable() { InspectorPatch(); } + public override void OnInspectorGUI() { InspectorPatch(); } + + private void InspectorPatch() + { + var patch = target as HideFlagPatch; + patch.hideFlags = HideFlagPatch.flag; + foreach (var cm in patch.gameObject.GetComponents()) { cm.hideFlags = patch.hideFlags; } + patch.gameObject.hideFlags = HideFlagPatch.flag; + } + } + + +} +#endif diff --git a/Runtime/HideFlagPatch.cs.meta b/Runtime/HideFlagPatch.cs.meta new file mode 100644 index 00000000..32b41f7d --- /dev/null +++ b/Runtime/HideFlagPatch.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83649d29849495044bdd285f6f8c1dad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index bd0a4561..d47cdd00 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -28,23 +28,28 @@ internal override void Apply([NotNull] IDomain domain) { if (!IsPossibleApply) { throw new TTTNotExecutable(); } var replaceTarget = TextureSelector.GetTexture(domain); + var canvasSize = tttImportedCanvasDescription?.Width ?? NormalizePowOfTow(replaceTarget.width); + if (domain.IsPreview()) { canvasSize = Mathf.Min(1024, canvasSize); } + RenderTexture result = EvaluateCanvas(domain.GetTextureManager(), canvasSize); + domain.AddTextureStack(replaceTarget, new BlendTexturePair(result, "NotBlend")); + } + internal RenderTexture EvaluateCanvas(ITextureManager textureManager, int canvasSize) + { var Layers = transform.GetChildren() .Select(I => I.GetComponent()) .Where(I => I != null) .Reverse(); - var canvasSize = tttImportedCanvasDescription?.Width ?? NormalizePowOfTow(replaceTarget.width); - if (domain.IsPreview()) { canvasSize = Mathf.Min(1024, canvasSize); } - - var canvasContext = new CanvasContext(canvasSize, domain.GetTextureManager()); + var canvasContext = new CanvasContext(canvasSize, textureManager); foreach (var layer in Layers) { layer.EvaluateTexture(canvasContext); } var result = canvasContext.LayerCanvas.FinalizeCanvas(); - domain.AddTextureStack(replaceTarget, new BlendTexturePair(result, "NotBlend")); + return result; } - internal static int NormalizePowOfTow(int v) + + internal static int NormalizePowOfTow(int v) { if (Mathf.IsPowerOfTwo(v)) { return v; } diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 8e3e0051..6ec353c1 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -8,9 +8,38 @@ internal static class MipMapUtility const string WTex = "WTex"; const string RTex = "RTex"; const string PixelRatio = "PixelRatio"; - public static bool Average(RenderTexture renderTexture) + + public static bool GenerateMips(RenderTexture renderTexture, DownScalingAlgorism algorism) { if (!renderTexture.useMipMap || !renderTexture.enableRandomWrite) { return false; } + bool result; + + switch (algorism) + { + case DownScalingAlgorism.Average: { result = Average(renderTexture); break; } + default: { result = false; break; } + } + + return result; + } + + public static int MipMapCountFrom(int width, int targetWith) + { + if (width < targetWith) { return -1; } + var count = 0; + if (width == targetWith) { return count; } + while (width >= 0 && count < 1024)//1024 回で止まるのはただのセーフティ + { + width /= 2; + count += 1; + if (width == targetWith) { return count; } + } + return -1; + } + + + static bool Average(RenderTexture renderTexture) + { var kernel32ID = MipMapShader.FindKernel("Average32"); var kernel1ID = MipMapShader.FindKernel("Average1"); @@ -37,20 +66,10 @@ public static bool Average(RenderTexture renderTexture) return true; } - public static int MipMapCountFrom(int width, int targetWith) - { - if (width < targetWith) { return -1; } - var count = 0; - if (width == targetWith) { return count; } - while (width >= 0 && count < 1024)//1024 回で止まるのはただのセーフティ - { - width /= 2; - count += 1; - if (width == targetWith) { return count; } - } - return -1; - } - } + public enum DownScalingAlgorism + { + Average = 0, + } } From c854fd638f3733ed05a2d5df28976561da1176eb Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 20 Mar 2024 20:18:08 +0900 Subject: [PATCH 020/208] feat: average on CPU --- Editor/Domain/TextureManager.cs | 2 - .../MultiLayerImageImporter.cs | 205 ++++++++++++------ .../TexTransToolPSDImporter.cs | 35 ++- Editor/net.rs64.tex-trans-tool.editor.asmdef | 4 +- .../Improted/PSD/PSDImportedRasterImage.cs | 175 +++++++++++---- .../PSD/PSDImportedRasterMaskImage.cs | 48 +++- .../Improted/TTTImportedImage.cs | 6 +- .../net.rs64.tex-trans-tool.runtime.asmdef | 4 +- TexTransCore/Island/IslandUtility.cs | 2 +- TexTransCore/MipMap/MipMapUtility.cs | 110 ++++++++++ TexTransCore/net.rs64.tex-trans-core.asmdef | 3 +- package.json | 3 +- 12 files changed, 469 insertions(+), 128 deletions(-) diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 1069dcf6..011c8719 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -89,9 +89,7 @@ public void WriteOriginalTexture(TTTImportedImage texture, RenderTexture writeTa else { if (!CanvasSouse.ContainsKey(texture.CanvasDescription)) { CanvasSouse[texture.CanvasDescription] = File.ReadAllBytes(AssetDatabase.GetAssetPath(texture.CanvasDescription)); } - // var timer = System.Diagnostics.Stopwatch.StartNew(); texture.LoadImage(CanvasSouse[texture.CanvasDescription], writeTarget); - // timer.Stop(); Debug.Log(texture.name + ":" + timer.ElapsedMilliseconds + "ms"); } } public void TextureCompressDelegation((TextureFormat CompressFormat, int Quality) compressSetting, Texture2D target) diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index 6662e20f..ff52641d 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -8,11 +8,10 @@ using UnityEditor.AssetImporters; using Unity.Collections; using net.rs64.TexTransCore.MipMap; -using UnityEngine.Rendering; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.BlendTexture; -using TextureUtility = net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; +using Unity.Jobs; +using Unity.Mathematics; +using Unity.Burst; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.MultiLayerImage.Importer { @@ -24,23 +23,24 @@ internal class MultiLayerImageImporter List _tttImportedImages = new(); CreateImportedImage _imageImporter; byte[] _souseBytes; - DownScalingAlgorism _previewImageDownScalingAlgorism; + Dictionary _layerAtPath = new(); + string _path = ""; internal delegate TTTImportedImage CreateImportedImage(ImportRasterImageData importRasterImage); internal delegate Task> GetPreviewImage(byte[] souseBytes, TTTImportedImage importRasterImage);//つまり正方形にオフセットの入った後の画像を取得するやつ RGBA32 - internal MultiLayerImageImporter(MultiLayerImageCanvas multiLayerImageCanvas, TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] souseBytes, CreateImportedImage imageImporter, DownScalingAlgorism previewImageDownScalingAlgorism) + internal MultiLayerImageImporter(MultiLayerImageCanvas multiLayerImageCanvas, TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] souseBytes, CreateImportedImage imageImporter) { _multiLayerImageCanvas = multiLayerImageCanvas; _ctx = assetImportContext; _imageImporter = imageImporter; _tttImportedCanvasDescription = tttImportedCanvasDescription; _souseBytes = souseBytes; - _previewImageDownScalingAlgorism = previewImageDownScalingAlgorism; } - internal void AddLayers(List abstractLayers, Transform parent = null) + internal void AddLayers(List abstractLayers) { AddLayers(abstractLayers, null); } + private void AddLayers(List abstractLayers, Transform parent = null) { parent ??= _multiLayerImageCanvas.transform; var count = 0; @@ -157,6 +157,7 @@ private void CreateRasterLayer(GameObject newLayer, RasterLayerData rasterLayer) importedImage.name = rasterLayer.LayerName + "_Tex"; importedImage.CanvasDescription = _tttImportedCanvasDescription; _tttImportedImages.Add(importedImage); + _layerAtPath[importedImage] = _path; rasterLayerComponent.ImportedImage = importedImage; } @@ -168,18 +169,21 @@ private ILayerMask MaskTexture(LayerMaskData maskData, string layerName) importMask.name = layerName + "_MaskTex"; importMask.CanvasDescription = _tttImportedCanvasDescription; _tttImportedImages.Add(importMask); + _layerAtPath[importMask] = _path; return new TTTImportedLayerMask(maskData.LayerMaskDisabled, importMask); } - private void CreateLayerFolder(GameObject newLayer, LayerFolderData layerFolder) + private void CreateLayerFolder(GameObject newLayer, LayerFolderData layerFolder, string path = "") { var layerFolderComponent = newLayer.AddComponent(); CopyFromData(layerFolderComponent, layerFolder); layerFolderComponent.PassThrough = layerFolder.PassThrough; - + var beforePath = _path; + _path = beforePath + "/" + newLayer.name; AddLayers(layerFolder.Layers, newLayer.transform); + _path = beforePath; } internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstractLayerData) @@ -193,79 +197,156 @@ internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstra internal void CreatePreview() { - var rt = new RenderTexture(TextureUtility.NormalizePowerOfTwo(_tttImportedCanvasDescription.Width), TextureUtility.NormalizePowerOfTwo(_tttImportedCanvasDescription.Height), 0, RenderTextureFormat.ARGB32); - rt.enableRandomWrite = true; - rt.useMipMap = true; - rt.autoGenerateMips = false; + var canvasSize = new int2(_tttImportedCanvasDescription.Width, _tttImportedCanvasDescription.Height); + + Action nextTaming = () => { }; + Action nextTaming2 = () => { }; + + var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + var fullNAF4Tex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); foreach (var importedImage in _tttImportedImages) { - rt.Clear(); - importedImage.LoadImage(_souseBytes, rt); - MipMapUtility.GenerateMips(rt, _previewImageDownScalingAlgorism); + Profiler.BeginSample("CreatePreview -" + importedImage.name); + Profiler.BeginSample("LoadImage"); + + fullNATex = importedImage.LoadImage(_souseBytes, fullNATex); + + Profiler.EndSample(); + Profiler.BeginSample("ConvertColor32ToFloat4Job"); + + var covF4 = new ConvertColor32ToFloat4Job() { Souse = fullNATex, Target = fullNAF4Tex, }; + + var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 64); + nextTaming(); + covF4Handle.Complete(); + + Profiler.EndSample(); + Profiler.BeginSample("CreateMip"); - var mipMapCount = MipMapUtility.MipMapCountFrom(rt.width, 1024); - var request = AsyncGPUReadback.Request(rt, mipMapCount); - var tex2d = new Texture2D(1024, 1024, TextureFormat.RGBA32, false); + var mipMapCount = MipMapUtility.MipMapCountFrom(Mathf.Max(canvasSize.x, canvasSize.y), 1024); + var mips = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount, nextTaming2); - request.WaitForCompletion(); - using (var data = request.GetData()) { tex2d.LoadRawTextureData(data); } + Profiler.EndSample(); - EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); - tex2d.Apply(true, true); + Texture2D tex2d = null; + nextTaming = () => + { + Profiler.BeginSample("nextTamingCall"); + Profiler.BeginSample("CratePrevTex"); + + tex2d = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); + tex2d.alphaIsTransparency = true; + tex2d.LoadRawTextureData(mips[mipMapCount]); + + Profiler.EndSample(); + Profiler.EndSample(); + }; + nextTaming2 = () => + { + Profiler.BeginSample("nextTamingCall2"); + Profiler.BeginSample("SetTexDataAndCompress"); - importedImage.PreviewTexture = tex2d; + EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); + tex2d.Apply(true, true); + importedImage.PreviewTexture = tex2d; + + foreach (var n2da in mips.Skip(1)) { n2da.Dispose(); } + + Profiler.EndSample(); + Profiler.EndSample(); + }; + + Profiler.EndSample(); } - if (rt == RenderTexture.active) { RenderTexture.active = null; } - UnityEngine.Object.DestroyImmediate(rt); - var texManager = new TextureManager(true); - var canvasResult = _multiLayerImageCanvas.EvaluateCanvas(texManager, 1024); - texManager.DestroyTextures(); + nextTaming(); + nextTaming2(); + + fullNAF4Tex.Dispose(); + fullNATex.Dispose(); - var resultTex = canvasResult.CopyTexture2D(overrideUseMip: true); - EditorUtility.CompressTexture(resultTex, TextureFormat.DXT5, 100); - resultTex.name = "TTT-CanvasPreviewResult"; - _ctx.AddObjectToAsset(resultTex.name, resultTex); - RenderTexture.ReleaseTemporary(canvasResult); - var quadMesh = GameObject.CreatePrimitive(PrimitiveType.Quad); - var mesh = quadMesh.GetComponent().sharedMesh; - GameObject.DestroyImmediate(quadMesh); + // var texManager = new TextureManager(true); + // var canvasResult = _multiLayerImageCanvas.EvaluateCanvas(texManager, 1024); + // texManager.DestroyTextures(); - var prevGo = new GameObject("TTT-CanvasPreview"); - var hideFlagPatch = prevGo.AddComponent(); - prevGo.tag ="EditorOnly"; - var quad = prevGo.AddComponent(); + // var resultTex = canvasResult.CopyTexture2D(overrideUseMip: true); + // EditorUtility.CompressTexture(resultTex, TextureFormat.DXT5, 100); + // resultTex.name = "TTT-CanvasPreviewResult"; + // _ctx.AddObjectToAsset(resultTex.name, resultTex); + // RenderTexture.ReleaseTemporary(canvasResult); - quad.transform.SetParent(_multiLayerImageCanvas.transform, false); - quad.sharedMesh = mesh; - quad.sharedMaterial = new Material(Shader.Find("Unlit/Texture")) { mainTexture = resultTex, name = "TTT-CanvasPreviewResult-Material" }; - quad.transform.localRotation = Quaternion.Euler(new Vector3(-20f, 60f, 0f)); - quad.transform.localScale = new Vector3(-0.002f, 0.002f, -0.002f); - quad.localBounds = new Bounds(Vector3.zero, new Vector3(0.31f, 0.31f, 0.001f) * 2f); + // var quadMesh = GameObject.CreatePrimitive(PrimitiveType.Quad); + // var mesh = quadMesh.GetComponent().sharedMesh; + // GameObject.DestroyImmediate(quadMesh); - _ctx.AddObjectToAsset("TTT-CanvasPreviewResult-Material", quad.sharedMaterial); + // var prevGo = new GameObject("TTT-CanvasPreview"); + // var hideFlagPatch = prevGo.AddComponent(); + // prevGo.tag ="EditorOnly"; + // var quad = prevGo.AddComponent(); + + // quad.transform.SetParent(_multiLayerImageCanvas.transform, false); + // quad.sharedMesh = mesh; + // quad.sharedMaterial = new Material(Shader.Find("Unlit/Texture")) { mainTexture = resultTex, name = "TTT-CanvasPreviewResult-Material" }; + // quad.transform.localRotation = Quaternion.Euler(new Vector3(-20f, 60f, 0f)); + // quad.transform.localScale = new Vector3(-0.002f, 0.002f, -0.002f); + // quad.localBounds = new Bounds(Vector3.zero, new Vector3(0.31f, 0.31f, 0.001f) * 2f); + + // _ctx.AddObjectToAsset("TTT-CanvasPreviewResult-Material", quad.sharedMaterial); } public void SaveSubAsset() { - var NameHash = new HashSet() { "TTT-CanvasPreviewResult", "TTT-CanvasPreviewResult-Material" }; + // var NameHash = new HashSet() { "TTT-CanvasPreviewResult", "TTT-CanvasPreviewResult-Material" }; foreach (var image in _tttImportedImages.Reverse()) { - var name = image.name; - if (NameHash.Contains(name)) - { - var addCount = 1; - while (NameHash.Contains(name + "-" + addCount)) { addCount += 1; } - name = name + "-" + addCount; - } - NameHash.Add(name); + // var name = image.name; + // if (NameHash.Contains(name)) + // { + // var addCount = 1; + // while (NameHash.Contains(name + "-" + addCount)) { addCount += 1; } + // name = name + "-" + addCount; + // } + // NameHash.Add(name); + + // image.name = name; - image.name = name; image.PreviewTexture.name = image.name + "_Preview"; - _ctx.AddObjectToAsset(name, image); - _ctx.AddObjectToAsset(image.PreviewTexture.name, image.PreviewTexture); + _ctx.AddObjectToAsset(_layerAtPath[image] + "/" + image.name, image); + _ctx.AddObjectToAsset(_layerAtPath[image] + "/" + image.PreviewTexture.name, image.PreviewTexture); + } + } + + [BurstCompile] + internal struct ConvertColor32ToFloat4Job : IJobParallelFor + { + [ReadOnly] public NativeArray Souse; + [WriteOnly] public NativeArray Target; + public void Execute(int index) + { + Target[index] = new float4( + Souse[index].r / (float)byte.MaxValue, + Souse[index].g / (float)byte.MaxValue, + Souse[index].b / (float)byte.MaxValue, + Souse[index].a / (float)byte.MaxValue + ); + } + } + + [BurstCompile] + internal struct ConvertFloat4ToColor32Job : IJobParallelFor + { + [ReadOnly] public NativeArray Souse; + [WriteOnly] public NativeArray Target; + public void Execute(int index) + { + Target[index] = new Color32( + (byte)Mathf.Round(Souse[index].x * (float)byte.MaxValue), + (byte)Mathf.Round(Souse[index].y * (float)byte.MaxValue), + (byte)Mathf.Round(Souse[index].z * (float)byte.MaxValue), + (byte)Mathf.Round(Souse[index].w * (float)byte.MaxValue) + ); } } } diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index 12486450..ba62c2fd 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -11,35 +11,42 @@ using UnityEditor; using UnityEditor.AssetImporters; using UnityEngine; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.MultiLayerImage.Importer { [ScriptedImporter(1, new string[] { }, new string[] { "psd" }, AllowCaching = true)] public class TexTransToolPSDImporter : ScriptedImporter { - public DownScalingAlgorism PreviewImageDownScalingAlgorism; public override void OnImportAsset(AssetImportContext ctx) { NativeLeakDetection.Mode = NativeLeakDetectionMode.EnabledWithStackTrace; - EditorUtility.DisplayProgressBar("Parse PSD", "ReadBytes", 0.2f); + EditorUtility.DisplayProgressBar("Parse PSD", "ReadBytes", 0.0f); + + Profiler.BeginSample("ParsePSD"); + Profiler.BeginSample("ReadBytes"); var psdBytes = File.ReadAllBytes(ctx.assetPath); - EditorUtility.DisplayProgressBar("Parse PSD", "LowLevelParser", 0.2f); + Profiler.EndSample(); + Profiler.BeginSample("LowLevel"); var lowPSDData = PSDLowLevelParser.Parse(assetPath); - EditorUtility.DisplayProgressBar("Parse PSD", "HighLevelParser", 0.6f); + Profiler.EndSample(); + Profiler.BeginSample("LowLevel"); var pSDData = PSDHighLevelParser.Parse(lowPSDData); - EditorUtility.DisplayProgressBar("Parse PSD", "End", 1); + Profiler.EndSample(); + Profiler.EndSample(); try { EditorUtility.DisplayProgressBar("Import Canvas", "Build Layer", 0); - + Profiler.BeginSample("CreateCanvas"); + Profiler.BeginSample("CreateRootObjects"); var prefabName = Path.GetFileName(ctx.assetPath) + "-Canvas"; var rootCanvas = new GameObject(prefabName); @@ -55,13 +62,26 @@ public override void OnImportAsset(AssetImportContext ctx) ctx.AddObjectToAsset(canvasDescription.name, canvasDescription); multiLayerImageCanvas.tttImportedCanvasDescription = canvasDescription; - var mliImporter = new MultiLayerImageImporter(multiLayerImageCanvas, canvasDescription, ctx, psdBytes, CreatePSDImportedImage, PreviewImageDownScalingAlgorism); + Profiler.EndSample(); + Profiler.BeginSample("CreateLayers"); + + var mliImporter = new MultiLayerImageImporter(multiLayerImageCanvas, canvasDescription, ctx, psdBytes, CreatePSDImportedImage); mliImporter.AddLayers(pSDData.RootLayers); + Profiler.EndSample(); EditorUtility.DisplayProgressBar("Import Canvas", "CreatePreview", 0f); + Profiler.BeginSample("CreatePreviews"); + mliImporter.CreatePreview(); + + Profiler.EndSample(); EditorUtility.DisplayProgressBar("Import Canvas", "SaveSubAsset", 0.5f); + Profiler.BeginSample("SaveSubAssets"); + mliImporter.SaveSubAsset(); + + Profiler.EndSample(); + Profiler.EndSample(); EditorUtility.DisplayProgressBar("Import Canvas", "END", 1f); } finally @@ -99,7 +119,6 @@ class TexTransToolPSDImporterEditor : ScriptedImporterEditor public override void OnInspectorGUI() { EditorGUILayout.HelpBox("TexTransToolPSDImporter" + " " + "Common:ExperimentalWarning".GetLocalize(), MessageType.Warning); - EditorGUILayout.PropertyField(serializedObject.FindProperty("PreviewImageDownScalingAlgorism")); base.ApplyRevertGUI(); } diff --git a/Editor/net.rs64.tex-trans-tool.editor.asmdef b/Editor/net.rs64.tex-trans-tool.editor.asmdef index 0d9cb8e3..8957e746 100644 --- a/Editor/net.rs64.tex-trans-tool.editor.asmdef +++ b/Editor/net.rs64.tex-trans-tool.editor.asmdef @@ -7,7 +7,9 @@ "net.rs64.tex-trans-tool.editor.unsafe", "net.rs64.multi-layer-image-parser", "nadena.dev.ndmf", - "Unity.Collections" + "Unity.Collections", + "Unity.Mathematics", + "Unity.Burst" ], "includePlatforms": [ "Editor" diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 72a55ee5..7b608e64 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -1,7 +1,12 @@ using System.Threading.Tasks; using net.rs64.MultiLayerImage.Parser.PSD; +using Unity.Burst; using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; +using Unity.Mathematics; using UnityEngine; + namespace net.rs64.TexTransTool.MultiLayerImage { internal class PSDImportedRasterImage : TTTImportedImage @@ -9,6 +14,66 @@ internal class PSDImportedRasterImage : TTTImportedImage [SerializeField] internal PSDImportedRasterImageData RasterImageData; internal override Vector2Int Pivot => new Vector2Int(RasterImageData.RectTangle.Left, CanvasDescription.Height - RasterImageData.RectTangle.Bottom); + + internal override NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + { + var nativeArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); + + var initJob = new InitializeJob() { Target = nativeArray, Value = new Color32(0, 0, 0, 0) }; + var handle = initJob.Schedule(nativeArray.Length, 1024); + + Task>[] getImageTask = new Task>[4]; + getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSouse, RasterImageData.RectTangle)); + getImageTask[1] = Task.Run(() => RasterImageData.G.GetImageData(importSouse, RasterImageData.RectTangle)); + getImageTask[2] = Task.Run(() => RasterImageData.B.GetImageData(importSouse, RasterImageData.RectTangle)); + if (RasterImageData.A != null) { getImageTask[3] = Task.Run(() => RasterImageData.A.GetImageData(importSouse, RasterImageData.RectTangle)); } + + var souseTexSize = new int2(RasterImageData.RectTangle.GetWidth(), RasterImageData.RectTangle.GetHeight()); + var image = WeightTask(getImageTask).Result; + + JobHandle offsetJobHandle; + + if (RasterImageData.A != null) + { + var offset = new OffsetMoveAlphaJob() + { + Target = nativeArray, + R = image[0], + G = image[1], + B = image[2], + A = image[3], + Offset = new int2(Pivot.x, Pivot.y), + SouseSize = souseTexSize, + TargetSize = canvasSize, + }; + offsetJobHandle = offset.Schedule(image[0].Length, 64, handle); + } + else + { + var offset = new OffsetMoveJob() + { + Target = nativeArray, + R = image[0], + G = image[1], + B = image[2], + Offset = new int2(Pivot.x, Pivot.y), + SouseSize = souseTexSize, + TargetSize = canvasSize, + }; + offsetJobHandle = offset.Schedule(image[0].Length, 64, handle); + } + + offsetJobHandle.Complete(); + + image[0].Dispose(); + image[1].Dispose(); + image[2].Dispose(); + if (RasterImageData.A != null) { image[3].Dispose(); } + + return nativeArray; + } + internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) { // var timer = System.Diagnostics.Stopwatch.StartNew(); @@ -67,66 +132,84 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) // timer.Stop(); Debug.Log("Dispose:" + timer.ElapsedMilliseconds + "ms"); timer.Restart(); } + async static Task[]> WeightTask(Task>[] tasks) + { + return await Task.WhenAll(tasks).ConfigureAwait(false); + } internal const string MARGE_COLOR_AND_OFFSET_SHADER = "Hidden/MargeColorAndOffset"; internal static Shader MargeColorAndOffsetShader; internal const string SHADER_KEYWORD_SRGB = "COLOR_SPACE_SRGB"; - - - - - internal static NativeArray LoadPSDRasterLayerData(PSDImportedRasterImageData rasterImageData, byte[] importSouse) + internal struct InitializeJob : IJobParallelFor { - Task>[] getImageTask = new Task>[4]; - - getImageTask[0] = Task.Run(() => ChannelImageDataParser.ChannelImageData.HeightInvert(rasterImageData.R.GetImageData(importSouse, rasterImageData.RectTangle), rasterImageData.RectTangle.GetWidth(), rasterImageData.RectTangle.GetHeight())); - getImageTask[1] = Task.Run(() => ChannelImageDataParser.ChannelImageData.HeightInvert(rasterImageData.G.GetImageData(importSouse, rasterImageData.RectTangle), rasterImageData.RectTangle.GetWidth(), rasterImageData.RectTangle.GetHeight())); - getImageTask[2] = Task.Run(() => ChannelImageDataParser.ChannelImageData.HeightInvert(rasterImageData.B.GetImageData(importSouse, rasterImageData.RectTangle), rasterImageData.RectTangle.GetWidth(), rasterImageData.RectTangle.GetHeight())); - if (rasterImageData.A != null) { getImageTask[3] = Task.Run(() => ChannelImageDataParser.ChannelImageData.HeightInvert(rasterImageData.A.GetImageData(importSouse, rasterImageData.RectTangle), rasterImageData.RectTangle.GetWidth(), rasterImageData.RectTangle.GetHeight())); } - - var image = WeightTask(getImageTask).Result; - - var textureData = new NativeArray(rasterImageData.RectTangle.GetWidth() * rasterImageData.RectTangle.GetHeight(), Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - var textureSpan = textureData.AsSpan(); + public Color32 Value; + [WriteOnly] public NativeArray Target; + public void Execute(int index) { Target[index] = Value; } + } + [BurstCompile] + internal struct OffsetMoveAlphaJob : IJobParallelFor + { + [NativeDisableParallelForRestriction] + [NativeDisableContainerSafetyRestriction] + [WriteOnly] public NativeArray Target; + [ReadOnly] public NativeArray R; + [ReadOnly] public NativeArray G; + [ReadOnly] public NativeArray B; + [ReadOnly] public NativeArray A; + public int2 TargetSize; + + public int2 SouseSize; + public int2 Offset; + public void Execute(int index) + { + var sousePos = CovInt2(index, SouseSize.x); + sousePos.y = SouseSize.y - sousePos.y; + var writePos = Offset + sousePos; - var r = image[0]; - var g = image[1]; - var b = image[2]; - var a = image[3]; + if (writePos.x < 0) { return; } + if (writePos.y < 0) { return; } + if (writePos.x >= TargetSize.x) { return; } + if (writePos.y >= TargetSize.y) { return; } - if (rasterImageData.A != null) + Target[CovInt(writePos, TargetSize.x)] = new Color32(R[index], G[index], B[index], A[index]); + } + public static int2 CovInt2(int i, int width) { - for (var i = 0; textureData.Length > i; i += 1) - { - textureSpan[i].r = r[i]; - textureSpan[i].g = g[i]; - textureSpan[i].b = b[i]; - textureSpan[i].a = a[i]; - } + return new int2(i % width, i / width); } - else + public static int CovInt(int2 i, int width) { - for (var i = 0; textureData.Length > i; i += 1) - { - textureSpan[i].r = r[i]; - textureSpan[i].g = g[i]; - textureSpan[i].b = b[i]; - textureSpan[i].a = byte.MaxValue; - } + return (i.y * width) + i.x; } + } + [BurstCompile] + internal struct OffsetMoveJob : IJobParallelFor + { + [NativeDisableParallelForRestriction] + [NativeDisableContainerSafetyRestriction] + [WriteOnly] public NativeArray Target; + [ReadOnly] public NativeArray R; + [ReadOnly] public NativeArray G; + [ReadOnly] public NativeArray B; + public int2 TargetSize; + + public int2 SouseSize; + public int2 Offset; + public void Execute(int index) + { + var sousePos = OffsetMoveAlphaJob.CovInt2(index, SouseSize.x); + sousePos.y = SouseSize.y - sousePos.y; + var writePos = Offset + sousePos; - image[0].Dispose(); - image[1].Dispose(); - image[2].Dispose(); - if (rasterImageData.A != null) { image[3].Dispose(); } + if (writePos.x < 0) { return; } + if (writePos.y < 0) { return; } + if (writePos.x >= TargetSize.x) { return; } + if (writePos.y >= TargetSize.y) { return; } - return textureData; + Target[OffsetMoveAlphaJob.CovInt(writePos, TargetSize.x)] = new Color32(R[index], G[index], B[index], byte.MaxValue); + } } - async static Task[]> WeightTask(Task>[] tasks) - { - return await Task.WhenAll(tasks).ConfigureAwait(false); - } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 4f5ecd73..50daf2b3 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -1,6 +1,8 @@ using net.rs64.MultiLayerImage.Parser.PSD; using net.rs64.TexTransCore.BlendTexture; using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -10,6 +12,50 @@ internal class PSDImportedRasterMaskImage : TTTImportedImage internal override Vector2Int Pivot => new Vector2Int(MaskImageData.RectTangle.Left, CanvasDescription.Height - MaskImageData.RectTangle.Bottom); + internal override NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + { + var native2DArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); + + var initJob = new PSDImportedRasterImage.InitializeJob() + { + Target = native2DArray, + Value = new Color32(MaskImageData.DefaultValue, MaskImageData.DefaultValue, MaskImageData.DefaultValue, MaskImageData.DefaultValue) + }; + + var initHandle = initJob.Schedule(native2DArray.Length, 64); + + var souseTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); + + JobHandle offsetJobHandle; + + if ((MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0) + { + offsetJobHandle = initHandle; + offsetJobHandle.Complete(); + } + else + { + var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle); + var offset = new PSDImportedRasterImage.OffsetMoveAlphaJob() + { + Target = native2DArray, + R = data, + G = data, + B = data, + A = data, + Offset = new int2(Pivot.x, Pivot.y), + SouseSize = souseTexSize, + TargetSize = canvasSize, + }; + offsetJobHandle = offset.Schedule(data.Length, 64, initHandle); + + offsetJobHandle.Complete(); + data.Dispose(); + } + + return native2DArray; + } internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) { var isZeroSize = (MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0; @@ -26,8 +72,6 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) texR.LoadRawTextureData(data); texR.Apply(); } - - mat.SetTexture("_RTex", texR); mat.SetTexture("_GTex", texR); mat.SetTexture("_BTex", texR); diff --git a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs index 07d312cf..61dafe9d 100644 --- a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs +++ b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs @@ -1,7 +1,6 @@ using UnityEngine; using UnityEditor; using Unity.Collections; -using System.Security.Cryptography; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -12,7 +11,8 @@ public abstract class TTTImportedImage : ScriptableObject public Texture2D PreviewTexture; // R8 or RGBA32 Non MipMap - internal abstract void LoadImage(byte[] importSouse, RenderTexture WriteTarget); + internal abstract NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null); + internal abstract void LoadImage(byte[] importSouse, RenderTexture writeTarget); internal abstract Vector2Int Pivot { get; } } #if UNITY_EDITOR @@ -29,4 +29,4 @@ public override void OnInspectorGUI() } } #endif -} \ No newline at end of file +} diff --git a/Runtime/net.rs64.tex-trans-tool.runtime.asmdef b/Runtime/net.rs64.tex-trans-tool.runtime.asmdef index 3b3a5035..22da4d0b 100644 --- a/Runtime/net.rs64.tex-trans-tool.runtime.asmdef +++ b/Runtime/net.rs64.tex-trans-tool.runtime.asmdef @@ -4,7 +4,9 @@ "references": [ "net.rs64.tex-trans-core", "net.rs64.multi-layer-image-parser", - "nadena.dev.ndmf" + "nadena.dev.ndmf", + "Unity.Burst", + "Unity.Mathematics" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index 383426d4..bec05328 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -103,7 +103,7 @@ public static List UVtoIsland(MeshData meshData) { return UVtoIsland(meshData.CombinedTriangleIndex.AsList(), meshData.VertexUV.AsList()); } - + public static List UVtoIsland(IList triIndexes, IList vertexUV) { Profiler.BeginSample("UVtoIsland"); diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 6ec353c1..635065e0 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -1,4 +1,11 @@ +using System; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; using UnityEngine; +using static Unity.Mathematics.math; +using ReadOnlyAttribute = Unity.Collections.ReadOnlyAttribute; namespace net.rs64.TexTransCore.MipMap { @@ -22,6 +29,42 @@ public static bool GenerateMips(RenderTexture renderTexture, DownScalingAlgorism return result; } + public static NativeArray[] GenerateAverageMips(NativeArray tex, int2 texSize, int GenerateCount, Action beforeCompleteCall = null) + { + var mipMaps = new NativeArray[GenerateCount + 1]; + mipMaps[0] = tex; + + var handle = default(JobHandle); + + var upSize = texSize; + var downSize = texSize; + + for (var i = 1; mipMaps.Length > i; i += 1) + { + upSize = downSize; + downSize = downSize / 2; + + var up = mipMaps[i - 1]; + var down = mipMaps[i] = new NativeArray(up.Length / 4, Unity.Collections.Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + + var ave = new AverageJob() + { + RTex = up, + RTexSize = upSize, + WTex = down, + WTexSize = downSize, + PixelRatio = upSize / downSize, + }; + + handle = ave.Schedule(down.Length, 64, handle); + + } + + beforeCompleteCall?.Invoke(); + + handle.Complete(); + return mipMaps; + } public static int MipMapCountFrom(int width, int targetWith) { @@ -36,6 +79,16 @@ public static int MipMapCountFrom(int width, int targetWith) } return -1; } + public static int GetMipCount(int size) + { + var count = 0; + while (true) + { + size /= 2; + count += 1; + if (size <= 1) { return count; } + } + } static bool Average(RenderTexture renderTexture) @@ -67,6 +120,63 @@ static bool Average(RenderTexture renderTexture) } + + [BurstCompile] + struct AverageJob : IJobParallelFor + { + [ReadOnly] public NativeArray RTex; + [WriteOnly] public NativeArray WTex; + public int2 PixelRatio; + public int2 RTexSize; + public int2 WTexSize; + public void Execute(int index) + { + Average(CovInt2(index, WTexSize.x)); + } + + float3 ChakeNaN(float3 val, float3 replase) + { + return float3( + isnan(val.x) ? replase.x : val.x, + isnan(val.y) ? replase.y : val.y, + isnan(val.z) ? replase.z : val.z + ); + } + + void Average(int2 id) + { + float3 wcol = float3(0, 0, 0); + float3 col = float3(0, 0, 0); + float alpha = 0; + int count = 0; + + int2 readPosOffset = id.xy * PixelRatio; + for (int y = 0; PixelRatio.y > y; y += 1) + { + for (int x = 0; PixelRatio.x > x; x += 1) + { + float4 rCol = RTex[CovInt(readPosOffset + int2(x, y), RTexSize.x)]; + wcol += rCol.xyz * rCol.w; + col += rCol.xyz; + alpha += rCol.w; + count += 1; + } + } + + wcol /= alpha; + col /= count; + WTex[CovInt(id.xy, WTexSize.x)] = float4(ChakeNaN(wcol, col), alpha / count); + } + public static int2 CovInt2(int i, int width) + { + return new int2(i % width, i / width); + } + public static int CovInt(int2 i, int width) + { + return i.y * width + i.x; + } + } + } public enum DownScalingAlgorism { diff --git a/TexTransCore/net.rs64.tex-trans-core.asmdef b/TexTransCore/net.rs64.tex-trans-core.asmdef index c409b13a..0f26583f 100644 --- a/TexTransCore/net.rs64.tex-trans-core.asmdef +++ b/TexTransCore/net.rs64.tex-trans-core.asmdef @@ -2,7 +2,8 @@ "name": "net.rs64.tex-trans-core", "rootNamespace": "", "references": [ - "Unity.Burst" + "Unity.Burst", + "Unity.Mathematics" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/package.json b/package.json index 271f830a..ceff0264 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "Packages\\rs64.tex-trans-tool": "" }, "dependencies": { - "com.unity.burst": "1.8.0" + "com.unity.burst": "1.8.0", + "com.unity.mathematics": "1.3.2" } } From 7da9b0c78ed6180f353524a183722c6a9b8323a7 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 21 Mar 2024 14:16:21 +0900 Subject: [PATCH 021/208] chore: create job result --- .../MultiLayerImageImporter.cs | 16 ++++--- .../Improted/PSD/PSDImportedRasterImage.cs | 16 +++---- .../PSD/PSDImportedRasterMaskImage.cs | 42 +++++++------------ .../Improted/TTTImportedImage.cs | 3 +- TexTransCore/JobResult.cs | 30 +++++++++++++ TexTransCore/JobResult.cs.meta | 11 +++++ TexTransCore/MipMap/MipMapUtility.cs | 8 ++-- 7 files changed, 81 insertions(+), 45 deletions(-) create mode 100644 TexTransCore/JobResult.cs create mode 100644 TexTransCore/JobResult.cs.meta diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index ff52641d..e29769c6 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -209,14 +209,15 @@ internal void CreatePreview() Profiler.BeginSample("CreatePreview -" + importedImage.name); Profiler.BeginSample("LoadImage"); - fullNATex = importedImage.LoadImage(_souseBytes, fullNATex); + var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); Profiler.EndSample(); Profiler.BeginSample("ConvertColor32ToFloat4Job"); var covF4 = new ConvertColor32ToFloat4Job() { Souse = fullNATex, Target = fullNAF4Tex, }; - var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 64); + + var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 64, jobResult.GetHandle); nextTaming(); covF4Handle.Complete(); @@ -224,7 +225,9 @@ internal void CreatePreview() Profiler.BeginSample("CreateMip"); var mipMapCount = MipMapUtility.MipMapCountFrom(Mathf.Max(canvasSize.x, canvasSize.y), 1024); - var mips = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount, nextTaming2); + var mipJobResult = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount); + nextTaming2(); + _ = mipJobResult.GetResult; Profiler.EndSample(); @@ -236,7 +239,9 @@ internal void CreatePreview() tex2d = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); tex2d.alphaIsTransparency = true; - tex2d.LoadRawTextureData(mips[mipMapCount]); + + tex2d.LoadRawTextureData(mipJobResult.GetResult[mipMapCount]); + EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); Profiler.EndSample(); Profiler.EndSample(); @@ -246,11 +251,10 @@ internal void CreatePreview() Profiler.BeginSample("nextTamingCall2"); Profiler.BeginSample("SetTexDataAndCompress"); - EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); tex2d.Apply(true, true); importedImage.PreviewTexture = tex2d; - foreach (var n2da in mips.Skip(1)) { n2da.Dispose(); } + foreach (var n2da in mipJobResult.GetResult.Skip(1)) { n2da.Dispose(); } Profiler.EndSample(); Profiler.EndSample(); diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 7b608e64..45688bbb 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using net.rs64.MultiLayerImage.Parser.PSD; +using net.rs64.TexTransCore.TransTextureCore; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; @@ -15,7 +16,7 @@ internal class PSDImportedRasterImage : TTTImportedImage internal override Vector2Int Pivot => new Vector2Int(RasterImageData.RectTangle.Left, CanvasDescription.Height - RasterImageData.RectTangle.Bottom); - internal override NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) { var nativeArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); @@ -64,14 +65,15 @@ internal override NativeArray LoadImage(byte[] importSouse, NativeArray offsetJobHandle = offset.Schedule(image[0].Length, 64, handle); } - offsetJobHandle.Complete(); - image[0].Dispose(); - image[1].Dispose(); - image[2].Dispose(); - if (RasterImageData.A != null) { image[3].Dispose(); } - return nativeArray; + return new(nativeArray, offsetJobHandle, () => + { + image[0].Dispose(); + image[1].Dispose(); + image[2].Dispose(); + if (RasterImageData.A != null) { image[3].Dispose(); } + }); } internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 50daf2b3..35f03a75 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -1,5 +1,6 @@ using net.rs64.MultiLayerImage.Parser.PSD; using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.TransTextureCore; using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; @@ -12,7 +13,7 @@ internal class PSDImportedRasterMaskImage : TTTImportedImage internal override Vector2Int Pivot => new Vector2Int(MaskImageData.RectTangle.Left, CanvasDescription.Height - MaskImageData.RectTangle.Bottom); - internal override NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) { var native2DArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); @@ -24,37 +25,26 @@ internal override NativeArray LoadImage(byte[] importSouse, NativeArray }; var initHandle = initJob.Schedule(native2DArray.Length, 64); - var souseTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); JobHandle offsetJobHandle; + if ((MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0) { return new(native2DArray, initHandle); } - if ((MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0) - { - offsetJobHandle = initHandle; - offsetJobHandle.Complete(); - } - else + var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle); + var offset = new PSDImportedRasterImage.OffsetMoveAlphaJob() { - var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle); - var offset = new PSDImportedRasterImage.OffsetMoveAlphaJob() - { - Target = native2DArray, - R = data, - G = data, - B = data, - A = data, - Offset = new int2(Pivot.x, Pivot.y), - SouseSize = souseTexSize, - TargetSize = canvasSize, - }; - offsetJobHandle = offset.Schedule(data.Length, 64, initHandle); - - offsetJobHandle.Complete(); - data.Dispose(); - } + Target = native2DArray, + R = data, + G = data, + B = data, + A = data, + Offset = new int2(Pivot.x, Pivot.y), + SouseSize = souseTexSize, + TargetSize = canvasSize, + }; + offsetJobHandle = offset.Schedule(data.Length, 64, initHandle); - return native2DArray; + return new(native2DArray, offsetJobHandle, () => { data.Dispose(); }); } internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) { diff --git a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs index 61dafe9d..13f258e6 100644 --- a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs +++ b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs @@ -1,6 +1,7 @@ using UnityEngine; using UnityEditor; using Unity.Collections; +using net.rs64.TexTransCore.TransTextureCore; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -11,7 +12,7 @@ public abstract class TTTImportedImage : ScriptableObject public Texture2D PreviewTexture; // R8 or RGBA32 Non MipMap - internal abstract NativeArray LoadImage(byte[] importSouse, NativeArray? writeTarget = null); + internal abstract JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null); internal abstract void LoadImage(byte[] importSouse, RenderTexture writeTarget); internal abstract Vector2Int Pivot { get; } } diff --git a/TexTransCore/JobResult.cs b/TexTransCore/JobResult.cs new file mode 100644 index 00000000..47cd4e0b --- /dev/null +++ b/TexTransCore/JobResult.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Unity.Jobs; +using UnityEditor; + +namespace net.rs64.TexTransCore.TransTextureCore +{ + internal class JobResult + { + T _result; + JobHandle _jobHandle; + Action _completeAction; + + public T GetResult + { + get + { + _jobHandle.Complete(); + if (_completeAction != null) { _completeAction.Invoke(); _completeAction = null; } + return _result; + } + } + public JobHandle GetHandle => _jobHandle; + + public JobResult(T result) { _result = result; _jobHandle = default; _completeAction = null; } + public JobResult(T result, JobHandle jobHandle) { _result = result; _jobHandle = jobHandle; _completeAction = null; } + public JobResult(T result, JobHandle jobHandle, Action completeAction) { _result = result; _jobHandle = jobHandle; _completeAction = completeAction; } + } +} diff --git a/TexTransCore/JobResult.cs.meta b/TexTransCore/JobResult.cs.meta new file mode 100644 index 00000000..ae6f95d0 --- /dev/null +++ b/TexTransCore/JobResult.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6104048b48d9e3543b5281b0f60598ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 635065e0..24f13504 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -1,4 +1,5 @@ using System; +using net.rs64.TexTransCore.TransTextureCore; using Unity.Burst; using Unity.Collections; using Unity.Jobs; @@ -29,7 +30,7 @@ public static bool GenerateMips(RenderTexture renderTexture, DownScalingAlgorism return result; } - public static NativeArray[] GenerateAverageMips(NativeArray tex, int2 texSize, int GenerateCount, Action beforeCompleteCall = null) + public static JobResult[]> GenerateAverageMips(NativeArray tex, int2 texSize, int GenerateCount) { var mipMaps = new NativeArray[GenerateCount + 1]; mipMaps[0] = tex; @@ -60,10 +61,7 @@ public static NativeArray[] GenerateAverageMips(NativeArray tex, } - beforeCompleteCall?.Invoke(); - - handle.Complete(); - return mipMaps; + return new(mipMaps, handle); } public static int MipMapCountFrom(int width, int targetWith) From 2a37e77fb3e329e68a8861bdb9ce35d2bdaefdb7 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 21 Mar 2024 14:55:30 +0900 Subject: [PATCH 022/208] chore: move TexTransToolPSDImporterEditor.cs --- .../TexTransToolPSDImporterEditor.cs | 33 +++++++++++++++++++ .../TexTransToolPSDImporterEditor.cs.meta | 11 +++++++ .../TexTransToolPSDImporter.cs | 21 ------------ 3 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 Editor/Inspector/TexTransToolPSDImporterEditor.cs create mode 100644 Editor/Inspector/TexTransToolPSDImporterEditor.cs.meta diff --git a/Editor/Inspector/TexTransToolPSDImporterEditor.cs b/Editor/Inspector/TexTransToolPSDImporterEditor.cs new file mode 100644 index 00000000..67156768 --- /dev/null +++ b/Editor/Inspector/TexTransToolPSDImporterEditor.cs @@ -0,0 +1,33 @@ +using UnityEditor; +using UnityEditor.AssetImporters; + +namespace net.rs64.TexTransTool.MultiLayerImage.Importer +{ + [CustomEditor(typeof(TexTransToolPSDImporter))] + class TexTransToolPSDImporterEditor : ScriptedImporterEditor + { + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("TexTransToolPSDImporter" + " " + "Common:ExperimentalWarning".GetLocalize(), MessageType.Warning); + + base.ApplyRevertGUI(); + } + public override bool HasPreviewGUI() { return false; } + // public override void DrawPreview(Rect previewArea) + // { + // var importer = target as TexTransToolPSDImporter; + // var previewTex = AssetDatabase.LoadAllAssetsAtPath(importer.assetPath).FirstOrDefault(i => i.name == "TTT-CanvasPreviewResult") as Texture2D; + // if (previewTex == null) { return; } + + // EditorGUI.DrawTextureTransparent(previewArea, previewTex, ScaleMode.ScaleToFit); + // } + + } + + + + + + + +} diff --git a/Editor/Inspector/TexTransToolPSDImporterEditor.cs.meta b/Editor/Inspector/TexTransToolPSDImporterEditor.cs.meta new file mode 100644 index 00000000..5475076e --- /dev/null +++ b/Editor/Inspector/TexTransToolPSDImporterEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b006f57bad60ba94ca24557986d8ed29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index ba62c2fd..1cb4ab9c 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -113,27 +113,6 @@ internal TTTImportedImage CreatePSDImportedImage(ImportRasterImageData importRas } - [CustomEditor(typeof(TexTransToolPSDImporter))] - class TexTransToolPSDImporterEditor : ScriptedImporterEditor - { - public override void OnInspectorGUI() - { - EditorGUILayout.HelpBox("TexTransToolPSDImporter" + " " + "Common:ExperimentalWarning".GetLocalize(), MessageType.Warning); - - base.ApplyRevertGUI(); - } - public override bool HasPreviewGUI() { return true; } - public override void DrawPreview(Rect previewArea) - { - var importer = target as TexTransToolPSDImporter; - var previewTex = AssetDatabase.LoadAllAssetsAtPath(importer.assetPath).FirstOrDefault(i => i.name == "TTT-CanvasPreviewResult") as Texture2D; - if (previewTex == null) { return; } - - EditorGUI.DrawTextureTransparent(previewArea, previewTex, ScaleMode.ScaleToFit); - } - - } - From f408f7a9842942e90ff6a86416430971cd478889 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 21 Mar 2024 14:58:37 +0900 Subject: [PATCH 023/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 63a94dd6..ad273bec 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -20,6 +20,8 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Fixed +- Library が存在しないときにも正しくインポートできるようになりました (#427) + ### Deprecated ## 0.6.0 From 20ae24cad10bb44ee9e23b349bd9b2b4d747b211 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 23 Mar 2024 23:40:06 +0900 Subject: [PATCH 024/208] feat: SizePriority IReplaceTracking IIslandFineTuner AtlasContext.SubVertNormalize --- Editor/Domain/RenderersDomain.cs | 24 +- .../TextureAtlas/AtlasTextureEditor.cs | 58 +- .../TextureAtlas/IslandFineTuner.meta | 8 + .../IslandFineTuner/IIslandFineTunerDrawer.cs | 63 ++ .../IIslandFineTunerDrawer.cs.meta | 11 + .../IslandFineTuner/SizeOffsetDrawe.cs | 29 + .../IslandFineTuner/SizeOffsetDrawe.cs.meta | 11 + .../IslandFineTuner/SizePriorityDrawer.cs | 29 + .../SizePriorityDrawer.cs.meta | 11 + .../TextureAtlas/MatSelectorDrawer.cs | 4 +- Editor/Localize/en_US.po | 13 +- Editor/Localize/ja_JP.po | 12 +- Editor/Migration/V1/AtlasTextureV1.cs | 2 +- .../MatAndTexAbsoluteSeparator.cs | 4 +- .../MatAndTexUtils/MaterialModifier.cs | 6 +- Runtime/IDomain.cs | 11 +- .../IslandSelect/AbstructIslandSelector.cs | 3 +- .../MultiLayerImage/MultiLayerImageCanvas.cs | 2 +- .../AtlasTexture/AddAbsoluteMaterials.cs | 2 +- Runtime/TTType/TextureSelector.cs | 10 +- Runtime/TextureAtlas/AAOCode.meta | 8 + Runtime/TextureAtlas/AAOCode/AAO License | 21 + Runtime/TextureAtlas/AAOCode/AAO License.meta | 7 + Runtime/TextureAtlas/AAOCode/MeshUtility.cs | 404 +++++++++++ .../TextureAtlas/AAOCode/MeshUtility.cs.meta | 11 + .../AAOCode/MultiDimensionalNativeArray.cs | 58 ++ .../MultiDimensionalNativeArray.cs.meta | 11 + Runtime/TextureAtlas/AAOCode/Vertex.cs | 226 ++++++ Runtime/TextureAtlas/AAOCode/Vertex.cs.meta | 11 + Runtime/TextureAtlas/AtlasContext.cs | 393 +++++++++++ Runtime/TextureAtlas/AtlasContext.cs.meta | 11 + Runtime/TextureAtlas/AtlasIsland.cs | 15 - Runtime/TextureAtlas/AtlasReferenceData.cs | 347 ++++++++++ .../TextureAtlas/AtlasReferenceData.cs.meta | 11 + Runtime/TextureAtlas/AtlasSetting.cs | 8 +- Runtime/TextureAtlas/AtlasTexture.cs | 654 ++++++------------ Runtime/TextureAtlas/IslandFineTuner.meta | 8 + .../IslandFineTuner/IIslandFineTuner.cs | 16 + .../IslandFineTuner/IIslandFineTuner.cs.meta | 11 + .../IslandFineTuner/SizeOffset.cs | 28 + .../IslandFineTuner/SizeOffset.cs.meta | 11 + .../IslandFineTuner/SizePriority.cs | 28 + .../IslandFineTuner/SizePriority.cs.meta | 11 + .../AtlasIslandRelocatorObject.cs | 4 +- .../IslandRelocator/IAtlasIslandRelocator.cs | 5 +- .../IslandRelocator/NFDHPlasFC.cs | 35 +- TexTransCore/Decal/MeshData.cs | 36 +- TexTransCore/Island/IslandUtility.cs | 66 +- 48 files changed, 2198 insertions(+), 570 deletions(-) create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner.meta create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs.meta create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs create mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs.meta create mode 100644 Runtime/TextureAtlas/AAOCode.meta create mode 100644 Runtime/TextureAtlas/AAOCode/AAO License create mode 100644 Runtime/TextureAtlas/AAOCode/AAO License.meta create mode 100644 Runtime/TextureAtlas/AAOCode/MeshUtility.cs create mode 100644 Runtime/TextureAtlas/AAOCode/MeshUtility.cs.meta create mode 100644 Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs create mode 100644 Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs.meta create mode 100644 Runtime/TextureAtlas/AAOCode/Vertex.cs create mode 100644 Runtime/TextureAtlas/AAOCode/Vertex.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasContext.cs create mode 100644 Runtime/TextureAtlas/AtlasContext.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasReferenceData.cs create mode 100644 Runtime/TextureAtlas/AtlasReferenceData.cs.meta create mode 100644 Runtime/TextureAtlas/IslandFineTuner.meta create mode 100644 Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs create mode 100644 Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs.meta create mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs create mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta create mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs create mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs.meta diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index da5a8442..8a3e4e1a 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -33,6 +33,7 @@ internal class RenderersDomain : IEditorCallDomain private readonly IStackManager _textureStacks; [NotNull] protected FlatMapDict _objectMap = new(); + protected Dictionary _replaceMap = new();//New Old public RenderersDomain(List previewRenderers, bool previewing, bool saveAsset = false, bool progressDisplay = false) : this(previewRenderers, previewing, saveAsset ? new AssetSaver() : null, progressDisplay) { } @@ -116,7 +117,7 @@ public virtual void ReplaceMaterials(Dictionary mapping, boo { foreach (var keyValuePair in mapping) { - _objectMap.Add(keyValuePair.Key, keyValuePair.Value); + RegisterReplace(keyValuePair.Key, keyValuePair.Value); } } } @@ -143,7 +144,7 @@ public virtual void SetMesh(Renderer renderer, Mesh mesh) throw new ArgumentException($"Unexpected Renderer Type: {renderer.GetType()}", nameof(renderer)); } - _objectMap.Add(preMesh, mesh); + RegisterReplace(preMesh, mesh); } public virtual void SetTexture(Texture2D target, Texture2D setTex) { @@ -151,19 +152,29 @@ public virtual void SetTexture(Texture2D target, Texture2D setTex) ReplaceMaterials(MaterialUtility.ReplaceTextureAll(mats, target, setTex)); ListPool.Release(mats); - _objectMap.Add(target, setTex); + RegisterReplace(target, setTex); } public void TransferAsset(Object Asset) => _saver?.TransferAsset(Asset); - public bool TryReplaceQuery(Object oldObject, out Object nowObject) + public virtual bool OriginEqual(Object l, Object r) { - return _objectMap.GetMapping.TryGetValue(oldObject, out nowObject); + if (l == r) { return true; } + + return GetOrigin(l) == GetOrigin(r); + + Object GetOrigin(Object obj) + { + while (_replaceMap.ContainsKey(obj)) { obj = _replaceMap[obj]; } + return obj; + } + } - public void RegisterReplace(Object oldObject, Object nowObject) + public virtual void RegisterReplace(Object oldObject, Object nowObject) { _objectMap.Add(oldObject, nowObject); + _replaceMap[oldObject] = nowObject; } public virtual void EditFinish() { @@ -211,5 +222,6 @@ public virtual void MergeStack() public ITextureManager GetTextureManager() => _textureManager; public bool IsPreview() => Previewing; + } } diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 48944569..e8c98e9f 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -43,6 +43,7 @@ public override void OnInspectorGUI() var sAtlasSetting = thisSObject.FindProperty("AtlasSetting"); var sTargetRoot = thisSObject.FindProperty("TargetRoot"); var sMatSelectors = thisSObject.FindProperty("SelectMatList"); + var sMaterialToIslandFineTuningModeSelect = thisSObject.FindProperty("MaterialToIslandFineTuningModeSelect"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(sTargetRoot, "AtlasTexture:prop:TargetRoot".Glc()); @@ -52,13 +53,16 @@ public override void OnInspectorGUI() { if (GUILayout.Button("AtlasTexture:button:RefreshMaterials".GetLocalize()) || _displayMaterial == null) { RefreshMaterials(thisTarget.TargetRoot, thisTarget.AtlasSetting.IncludeDisabledRenderer); } - MaterialSelectEditor(sMatSelectors, _displayMaterial); + MaterialSelectEditor(sMatSelectors, sMaterialToIslandFineTuningModeSelect, _displayMaterial); } EditorGUI.indentLevel += 1; EditorGUILayout.PropertyField(sMatSelectors, "AtlasTexture:prop:SelectedMaterialView".Glc()); EditorGUI.indentLevel -= 1; + var sIslandFineTuners = sAtlasSetting.FindPropertyRelative("IslandFineTuners"); + EditorGUILayout.PropertyField(sIslandFineTuners, "AtlasTexture:prop:IslandFineTuners".Glc()); + DrawAtlasSettings(sAtlasSetting); @@ -68,7 +72,7 @@ public override void OnInspectorGUI() } - private static void DrawAtlasSettings(SerializedProperty sAtlasSettings) + private void DrawAtlasSettings(SerializedProperty sAtlasSettings) { EditorGUILayout.LabelField("AtlasTexture:label:AtlasSettings".Glc(), EditorStyles.boldLabel); EditorGUI.indentLevel += 1; @@ -101,7 +105,9 @@ private static void DrawAtlasSettings(SerializedProperty sAtlasSettings) EditorGUILayout.PropertyField(sPadding, "AtlasTexture:prop:Padding".Glc()); EditorGUILayout.PropertyField(sUseUpScaling, "AtlasTexture:prop:UseUpScaling".Glc()); + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(sIncludeDisabledRenderer, "AtlasTexture:prop:IncludeDisabledRenderer".Glc()); + if (EditorGUI.EndChangeCheck()) { RefreshMaterials(sIncludeDisabledRenderer.serializedObject.FindProperty("TargetRoot").objectReferenceValue as GameObject, sIncludeDisabledRenderer.boolValue); } s_ExperimentalFutureOption = EditorGUILayout.Foldout(s_ExperimentalFutureOption, "Common:ExperimentalFuture".Glc()); @@ -110,7 +116,7 @@ private static void DrawAtlasSettings(SerializedProperty sAtlasSettings) EditorGUI.indentLevel += 1; EditorGUILayout.PropertyField(sAtlasIslandRelocator, "AtlasTexture:prop:ExperimentalFuture:AtlasIslandRelocator".Glc()); EditorGUILayout.PropertyField(sWriteOriginalUV, "AtlasTexture:prop:ExperimentalFuture:WriteOriginalUV".Glc()); - EditorGUILayout.PropertyField(sPixelNormalize,"AtlasTexture:prop:ExperimentalFuture:PixelNormalize".Glc()); + EditorGUILayout.PropertyField(sPixelNormalize, "AtlasTexture:prop:ExperimentalFuture:PixelNormalize".Glc()); EditorGUI.indentLevel -= 1; } @@ -133,18 +139,35 @@ void RefreshMaterials(GameObject targetRoot, bool includeDisabledRenderer) _displayMaterial = RendererUtility.GetMaterials(renderers).Distinct().ToList(); } - public static void MaterialSelectEditor(SerializedProperty targetMaterial, List tempMaterial) + public static void MaterialSelectEditor(SerializedProperty targetMaterial, SerializedProperty fineTunerMode, List tempMaterial) { EditorGUI.indentLevel += 1; - GUILayout.Label("AtlasTexture:label:TSM-Header".Glc()); + var hadeRect = EditorGUILayout.GetControlRect(); + var hadeWidth = hadeRect.width; + hadeRect.width = 64f; + EditorGUI.LabelField(hadeRect, "AtlasTexture:label:Target".Glc()); + + hadeRect.width = (hadeWidth * 0.5f) - 64f; + hadeRect.x = 64f; + EditorGUI.PropertyField(hadeRect, fineTunerMode, GUIContent.none); + + hadeRect.width = hadeWidth * 0.5f; + hadeRect.x = hadeRect.width; + EditorGUI.LabelField(hadeRect, "AtlasTexture:label:Material".Glc()); + foreach (var mat in tempMaterial) { var sMatSelector = FindMatSelector(targetMaterial, mat); - EditorGUILayout.BeginHorizontal(); + var rect = EditorGUILayout.GetControlRect(); + + var drawWidth = rect.width * 0.5f; var isTarget = sMatSelector != null; - var editIsTarget = EditorGUILayout.Toggle(isTarget); + rect.width = 32f; + var editIsTarget = EditorGUI.Toggle(rect, isTarget); + rect.x += rect.width; + if (isTarget != editIsTarget) { if (editIsTarget) @@ -153,7 +176,7 @@ public static void MaterialSelectEditor(SerializedProperty targetMaterial, List< targetMaterial.arraySize += 1; var sNewMatSelector = targetMaterial.GetArrayElementAtIndex(index); sNewMatSelector.FindPropertyRelative("Material").objectReferenceValue = mat; - sNewMatSelector.FindPropertyRelative("AdditionalTextureSizeOffSet").floatValue = 1; + sNewMatSelector.FindPropertyRelative("MaterialFineTuningValue").floatValue = 1; } else { @@ -162,14 +185,19 @@ public static void MaterialSelectEditor(SerializedProperty targetMaterial, List< } else if (isTarget) { - var SOffset = sMatSelector.FindPropertyRelative("AdditionalTextureSizeOffSet"); - SOffset.floatValue = EditorGUILayout.FloatField(SOffset.floatValue); + rect.width = drawWidth - 18f - 24f; + var SOffset = sMatSelector.FindPropertyRelative("MaterialFineTuningValue"); + SOffset.floatValue = EditorGUI.Slider(rect, SOffset.floatValue, 0, 1); + rect.x += rect.width; } - - EditorGUI.BeginDisabledGroup(true); - EditorGUILayout.ObjectField(mat, typeof(Material), false, GUILayout.MaxWidth(1000)); - EditorGUI.EndDisabledGroup(); - EditorGUILayout.EndHorizontal(); + rect.x = drawWidth - 2.5f; + rect.width = 18f; + var matPrevTex = AssetPreview.GetAssetPreview(mat); + if (matPrevTex != null) { EditorGUI.DrawTextureTransparent(rect, matPrevTex, ScaleMode.ScaleToFit); } + + rect.width = drawWidth; + rect.x = rect.width; + EditorGUI.ObjectField(rect, mat, typeof(Material), false); } EditorGUI.indentLevel -= 1; diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner.meta b/Editor/Inspector/TextureAtlas/IslandFineTuner.meta new file mode 100644 index 00000000..199a4868 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 904550200b3c91345a39ea99fe21d00d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs new file mode 100644 index 00000000..bf4d7963 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs @@ -0,0 +1,63 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.FineTuning; +using System.Collections.Generic; +using System; +using net.rs64.TexTransTool.TextureAtlas.IslandFineTuner; + +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + [CustomPropertyDrawer(typeof(IIslandFineTuner))] + internal class IIslandFineTunerDrawer : PropertyDrawer + { + static Func[] s_fineTuners; + static GUIContent[] s_names; + static string[] s_typeFullName; + + [InitializeOnLoadMethod] static void RegisterLangSwitch() { TTTConfig.OnSwitchLanguage += _ => Init(); } + public static void Init() + { + var dict = new Dictionary>(){ + {typeof(SizeOffset),()=>new SizeOffset()}, + {typeof(SizePriority),()=>new SizePriority()}, + }; + + var fineTuners = new List>(); + var names = new List(); + var typeFullName = new List(); + + foreach (var kv in dict) + { + names.Add(("IIslandFineTuner:prop:" + kv.Key.Name).Glc()); + typeFullName.Add(kv.Key.Assembly.GetName().Name + ' ' + kv.Key.FullName.Replace("+", "/")); + fineTuners.Add(kv.Value); + } + + s_fineTuners = fineTuners.ToArray(); + s_names = names.ToArray(); + s_typeFullName = typeFullName.ToArray(); + } + public static bool DrawTunerSelector(Rect position, SerializedProperty property, GUIContent label = null) + { + if (s_fineTuners is null) { Init(); } + + var index = Array.IndexOf(s_typeFullName, property.managedReferenceFullTypename); + + var pLabel = EditorGUI.BeginProperty(position, label ?? s_names[index], property); + var beforeIndex = EditorGUI.Popup(position, pLabel, index, s_names); + EditorGUI.EndProperty(); + if (index != beforeIndex) { property.managedReferenceValue = s_fineTuners[beforeIndex].Invoke(); return true; } + return false; + } + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + DrawTunerSelector(position, property, label); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label); + } + } +} diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs.meta b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs.meta new file mode 100644 index 00000000..de8db20c --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66b6dfdafb1421e41b6ad4a3baaceed8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs new file mode 100644 index 00000000..47f89ad4 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs @@ -0,0 +1,29 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.IslandFineTuner; + +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + [CustomPropertyDrawer(typeof(SizeOffset))] + internal class SizeOffsetToIslandDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + if (IIslandFineTunerDrawer.DrawTunerSelector(position, property)) { return; } + position.y += 18; + + var sOffsetValue = property.FindPropertyRelative("OffsetValue"); + EditorGUI.PropertyField(position, sOffsetValue, "IIslandFineTuner:prop:OffsetValue".Glc()); + position.y += 18; + + var sIslandSelector = property.FindPropertyRelative("IslandSelector"); + EditorGUI.PropertyField(position, sIslandSelector, "IIslandFineTuner:prop:IslandSelector".Glc()); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 3; + } + } +} diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta new file mode 100644 index 00000000..b929d2df --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e3bfdfd89a350a49874ab0cc1368e96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs new file mode 100644 index 00000000..62fb7017 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs @@ -0,0 +1,29 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.IslandFineTuner; + +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + [CustomPropertyDrawer(typeof(SizePriority))] + internal class SizePriorityToIslandDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + if (IIslandFineTunerDrawer.DrawTunerSelector(position, property)) { return; } + position.y += 18; + + var sOffsetValue = property.FindPropertyRelative("PriorityValue"); + EditorGUI.PropertyField(position, sOffsetValue, "IIslandFineTuner:prop:PriorityValue".Glc()); + position.y += 18; + + var sIslandSelector = property.FindPropertyRelative("IslandSelector"); + EditorGUI.PropertyField(position, sIslandSelector, "IIslandFineTuner:prop:IslandSelector".Glc()); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 3; + } + } +} diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs.meta b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs.meta new file mode 100644 index 00000000..78a66cc4 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizePriorityDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3e94c0a43c92c474d83bae1bb8e608af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/MatSelectorDrawer.cs b/Editor/Inspector/TextureAtlas/MatSelectorDrawer.cs index 473b9320..597c9175 100644 --- a/Editor/Inspector/TextureAtlas/MatSelectorDrawer.cs +++ b/Editor/Inspector/TextureAtlas/MatSelectorDrawer.cs @@ -10,7 +10,7 @@ public class MatSelectorDrawer : PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var sMat = property.FindPropertyRelative("Material"); - var sOffset = property.FindPropertyRelative("AdditionalTextureSizeOffSet"); + var sOffset = property.FindPropertyRelative("MaterialFineTuningValue"); position.width /= 2; EditorGUI.PropertyField(position, sOffset, new GUIContent(sMat.objectReferenceValue?.name)); position.x += position.width; @@ -18,4 +18,4 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.PropertyField(position, sMat, GUIContent.none); } } -} \ No newline at end of file +} diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 72b9c8a8..7071d562 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -52,8 +52,11 @@ msgstr "Maximum Range of renderers atlas" msgid "AtlasTexture:button:RefreshMaterials" msgstr "RefreshMaterials" -msgid "AtlasTexture:label:TSM-Header" -msgstr "Target (ScaleOffset) Material" +msgid "AtlasTexture:label:Target" +msgstr "Target" + +msgid "AtlasTexture:label:Material" +msgstr "Material" msgid "AtlasTexture:label:TSM-Header:tooltip" msgstr "atlas target (texture scale offset) material" @@ -239,6 +242,12 @@ msgstr "Settings that specify the color space of specific texture." msgid "TextureFineTuning:prop:Linear" msgstr "Linear" +msgid "IIslandFineTuner:prop:SizeOffset" +msgstr "SizeOffset" + +msgid "IIslandFineTuner:prop:SizePriority" +msgstr "SizePriority" + # CommonDecal msgid "CommonDecal:label:RenderersSettings" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index f4a1fa4d..70266613 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -52,8 +52,11 @@ msgstr "アトラス化されるレンダラーの最大範囲" msgid "AtlasTexture:button:RefreshMaterials" msgstr "リフレッシュマテリアル" -msgid "AtlasTexture:label:TSM-Header" -msgstr "対象 (スケールオフセット) マテリアル" +msgid "AtlasTexture:label:Target" +msgstr "対象" + +msgid "AtlasTexture:label:Material" +msgstr "マテリアル" msgid "AtlasTexture:label:TSM-Header:tooltip" msgstr "アトラス化対象か否か (テクスチャのスケールオフセット) マテリアル" @@ -239,6 +242,11 @@ msgstr "指定したテクスチャの色空間を指定する設定" msgid "TextureFineTuning:prop:Linear" msgstr "リニア" +msgid "IIslandFineTuner:prop:SizeOffset" +msgstr "サイズオフセット" + +msgid "IIslandFineTuner:prop:SizePriority" +msgstr "大きさの優先度" # CommonDecal diff --git a/Editor/Migration/V1/AtlasTextureV1.cs b/Editor/Migration/V1/AtlasTextureV1.cs index 4877fc90..4734cbba 100644 --- a/Editor/Migration/V1/AtlasTextureV1.cs +++ b/Editor/Migration/V1/AtlasTextureV1.cs @@ -39,7 +39,7 @@ public static void MigrationAtlasTextureV1ToV2(AtlasTexture atlasTexture) // Debug.Log($"texSize{texSize}/{maxTexturePixelCount}:Offset{offset}:Default{defaultOffset}:result{additionalTextureSizeOffSet}"); - selector.AdditionalTextureSizeOffSet = additionalTextureSizeOffSet; + selector.TextureSizeOffSet = additionalTextureSizeOffSet; matList[i] = selector; } diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs index 0d4188e8..2ba617b3 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using UnityEditor; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransTool.MatAndTexUtils { @@ -30,7 +31,8 @@ List IMatAndTexSeparator.GetSeparateTarget(IDomain domain, int RendererInd { var renderer = TargetRenderers[RendererIndex]; - var targetMats = SeparateTarget.Select(mat => domain.TryReplaceQuery(mat, out var rMat) ? (Material)rMat : mat).ToHashSet(); + var hashSet = new HashSet(renderer.sharedMaterials); + var targetMats = hashSet.Where(i => SeparateTarget.Any(m => domain.OriginEqual(m, i))).ToList(); return renderer.sharedMaterials.Select(m => targetMats.Contains(m)).ToList(); } diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index e25bd878..5a4f89ea 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -76,11 +76,7 @@ internal override void Apply([NotNull] IDomain domain) var modMatList = new Dictionary(); var hashSet = new HashSet(RendererUtility.GetMaterials(GetRenderers)); - var containedModTarget = ModifiedTarget - .Select(mat => domain.TryReplaceQuery(mat, out var rMat) ? (Material)rMat : mat) - .Where(I => hashSet.Contains(I)) - .ToList(); - + var containedModTarget = hashSet.Where(i => ModifiedTarget.Any(m => domain.OriginEqual(m, i))).ToList(); foreach (var modTarget in containedModTarget) { diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index a75c8b60..95917fee 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -8,14 +8,11 @@ namespace net.rs64.TexTransTool { - internal interface IDomain : IAssetSaver, IProgressHandling + internal interface IDomain : IAssetSaver, IProgressHandling, IReplaceTracking { void ReplaceMaterials(Dictionary mapping, bool rendererOnly = false); void SetMesh(Renderer renderer, Mesh mesh); public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair;//RenderTextureを入れる場合 Temp にすること、そしてこちら側でそれが解放される。 - bool TryReplaceQuery(UnityEngine.Object oldObject, out UnityEngine.Object nowObject); - //今後テクスチャとメッシュとマテリアル以外で置き換えが必要になった時できるようにするために用意はしておく - void RegisterReplace(UnityEngine.Object oldObject, UnityEngine.Object nowObject); bool IsPreview();//極力使わない方針で、どうしようもないやつだけ使うこと。テクスチャとかはプレビューの場合は自動で切り替わるから、これを見るコードをできるだけ作りたくないという意図です。 @@ -42,6 +39,12 @@ internal interface ITextureManager : IOriginTexture void ReplaceTextureCompressDelegation(Texture2D souse, Texture2D target); void TextureFinalize(); } + internal interface IReplaceTracking + { + bool OriginEqual(UnityEngine.Object l, UnityEngine.Object r); + //今後テクスチャとメッシュとマテリアル以外で置き換えが必要になった時できるようにするために用意はしておく + void RegisterReplace(UnityEngine.Object oldObject, UnityEngine.Object nowObject); + } public interface IOriginTexture { int GetOriginalTextureSize(Texture2D texture2D); diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index d0c2bb19..2b0c4c90 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -19,7 +19,8 @@ public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, /* 頂点の持つ情報 レンダラー - レンダラーから見た時のスロット (マテリアルはここから調べるように) + レンダラーから見た時のスロット + マテリアルの参照を比較してはならない。 */ diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index d47cdd00..3947b107 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -27,7 +27,7 @@ public sealed class MultiLayerImageCanvas : TexTransRuntimeBehavior, ITTTChildEx internal override void Apply([NotNull] IDomain domain) { if (!IsPossibleApply) { throw new TTTNotExecutable(); } - var replaceTarget = TextureSelector.GetTexture(domain); + var replaceTarget = TextureSelector.GetTexture(); var canvasSize = tttImportedCanvasDescription?.Width ?? NormalizePowOfTow(replaceTarget.width); if (domain.IsPreview()) { canvasSize = Mathf.Min(1024, canvasSize); } RenderTexture result = EvaluateCanvas(domain.GetTextureManager(), canvasSize); diff --git a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs index 7e159b94..72c2dde7 100644 --- a/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs +++ b/Runtime/ReferenceResolver/AtlasTexture/AddAbsoluteMaterials.cs @@ -24,7 +24,7 @@ public override void Resolving(ResolverContext avatar) if (index != -1) { var matSelector = atlasTexture.SelectMatList[index]; - matSelector.AdditionalTextureSizeOffSet = add.AdditionalTextureSizeOffSet; + matSelector.MaterialFineTuningValue = add.MaterialFineTuningValue; atlasTexture.SelectMatList[index] = matSelector; } else diff --git a/Runtime/TTType/TextureSelector.cs b/Runtime/TTType/TextureSelector.cs index e50eb0cf..ac71782c 100644 --- a/Runtime/TTType/TextureSelector.cs +++ b/Runtime/TTType/TextureSelector.cs @@ -22,17 +22,13 @@ public enum SelectMode [FormerlySerializedAs("MaterialSelect")]public int SlotAsPath = 0; [FormerlySerializedAs("TargetPropertyName")]public PropertyName PropertyNameAsPath = PropertyName.DefaultValue; - internal Texture2D GetTexture(IDomain domain = null) + internal Texture2D GetTexture() { switch (Mode) { case SelectMode.Absolute: { - if (domain == null) { return SelectTexture; } - - if (domain.TryReplaceQuery(SelectTexture, out var texture2d)) - { return texture2d as Texture2D; } - else { return SelectTexture; } + return SelectTexture; } case SelectMode.Relative: { @@ -48,4 +44,4 @@ internal Texture2D GetTexture(IDomain domain = null) } } -} \ No newline at end of file +} diff --git a/Runtime/TextureAtlas/AAOCode.meta b/Runtime/TextureAtlas/AAOCode.meta new file mode 100644 index 00000000..ce9b6a52 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 75a2a599d439dc54082f6fc3d7e9980e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AAOCode/AAO License b/Runtime/TextureAtlas/AAOCode/AAO License new file mode 100644 index 00000000..86777d94 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/AAO License @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 anatawa12 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Runtime/TextureAtlas/AAOCode/AAO License.meta b/Runtime/TextureAtlas/AAOCode/AAO License.meta new file mode 100644 index 00000000..96d6fc85 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/AAO License.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 596ce498230b6b643899bd831a6e9838 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AAOCode/MeshUtility.cs b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs new file mode 100644 index 00000000..061cdb9a --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs @@ -0,0 +1,404 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using UnityEngine; +using UnityEngine.Profiling; +using UnityEngine.Rendering; + +namespace net.rs64.TexTransTool.TextureAtlas.AAOCode +{ + //これは MeshInfo2 を改造して簡易的に使えるようにしたもの + internal static class MeshInfoUtility + { + public static List ReadVertex(Mesh mesh, out MeshDesc meshDesc) + { + meshDesc = new(); + Profiler.BeginSample($"Read Static Mesh Part"); + + var Vertices = new List(mesh.vertexCount); + for (var i = 0; i < mesh.vertexCount; i++) { Vertices.Add(new()); } + + CopyVertexAttr(mesh.vertices, (x, v) => x.Position = v); + if (mesh.GetVertexAttributeDimension(VertexAttribute.Normal) != 0) + { + meshDesc.HasNormals = true; + CopyVertexAttr(mesh.normals, (x, v) => x.Normal = v); + } + if (mesh.GetVertexAttributeDimension(VertexAttribute.Tangent) != 0) + { + meshDesc.HasTangent = true; + CopyVertexAttr(mesh.tangents, (x, v) => x.Tangent = v); + } + if (mesh.GetVertexAttributeDimension(VertexAttribute.Color) != 0) + { + meshDesc.HasColor = true; + CopyVertexAttr(mesh.colors32, (x, v) => x.Color = v); + } + + var uv2 = new List(0); + var uv3 = new List(0); + var uv4 = new List(0); + for (var index = 0; index <= 7; index++) + { + // ReSharper disable AccessToModifiedClosure + switch (mesh.GetVertexAttributeDimension(VertexAttribute.TexCoord0 + index)) + { + case 2: + meshDesc.SetTexCoordStatus(index, TexCoordStatus.Vector2); + mesh.GetUVs(index, uv2); + CopyVertexAttrFromList(uv2, (x, v) => x.SetTexCoord(index, v)); + break; + case 3: + meshDesc.SetTexCoordStatus(index, TexCoordStatus.Vector3); + mesh.GetUVs(index, uv3); + CopyVertexAttrFromList(uv3, (x, v) => x.SetTexCoord(index, v)); + break; + case 4: + meshDesc.SetTexCoordStatus(index, TexCoordStatus.Vector4); + mesh.GetUVs(index, uv4); + CopyVertexAttrFromList(uv4, (x, v) => x.SetTexCoord(index, v)); + break; + } + + // ReSharper restore AccessToModifiedClosure + } + void CopyVertexAttr(T[] attributes, Action assign) + { + for (var i = 0; i < attributes.Length; i++) + assign(Vertices[i], attributes[i]); + } + + void CopyVertexAttrFromList(List attributes, Action assign) + { + for (var i = 0; i < attributes.Count; i++) + assign(Vertices[i], attributes[i]); + } + + Profiler.BeginSample("Read Bones"); + meshDesc.Bones = new(mesh.bindposes.Length); + meshDesc.Bones.AddRange(mesh.bindposes.Select(x => new Bone(x))); + + var bonesPerVertex = mesh.GetBonesPerVertex(); + var allBoneWeights = mesh.GetAllBoneWeights(); + var bonesBase = 0; + for (var i = 0; i < bonesPerVertex.Length; i++) + { + int count = bonesPerVertex[i]; + Vertices[i].BoneWeights.Capacity = count; + foreach (var boneWeight1 in allBoneWeights.AsReadOnlySpan().Slice(bonesBase, count)) + Vertices[i].BoneWeights.Add((meshDesc.Bones[boneWeight1.boneIndex], boneWeight1.weight)); + bonesBase += count; + } + Profiler.EndSample(); + + + meshDesc.BlendShapes = new(); + Profiler.BeginSample("Prepare shared buffers"); + var maxFrames = 0; + var frameCounts = new NativeArray(mesh.blendShapeCount, Allocator.TempJob); + var shapeNames = new string[mesh.blendShapeCount]; + for (var i = 0; i < mesh.blendShapeCount; i++) + { + var frames = mesh.GetBlendShapeFrameCount(i); + shapeNames[i] = mesh.GetBlendShapeName(i); + maxFrames = Math.Max(frames, maxFrames); + frameCounts[i] = frames; + } + + var deltaVertices = new Vector3[Vertices.Count]; + var deltaNormals = new Vector3[Vertices.Count]; + var deltaTangents = new Vector3[Vertices.Count]; + var allFramesBuffer = new NativeArray3(mesh.blendShapeCount, Vertices.Count, + maxFrames, Allocator.TempJob); + var meaningfuls = new NativeArray2(mesh.blendShapeCount, Vertices.Count, Allocator.TempJob); + Profiler.EndSample(); + + for (var blendShape = 0; blendShape < mesh.blendShapeCount; blendShape++) + { + meshDesc.BlendShapes.Add((shapeNames[blendShape], 0.0f)); + + for (var frame = 0; frame < frameCounts[blendShape]; frame++) + { + Profiler.BeginSample("GetFrameInfo"); + mesh.GetBlendShapeFrameVertices(blendShape, frame, deltaVertices, deltaNormals, deltaTangents); + var weight = mesh.GetBlendShapeFrameWeight(blendShape, frame); + Profiler.EndSample(); + + Profiler.BeginSample("Copy to buffer"); + for (var vertex = 0; vertex < deltaNormals.Length; vertex++) + { + var deltaVertex = deltaVertices[vertex]; + var deltaNormal = deltaNormals[vertex]; + var deltaTangent = deltaTangents[vertex]; + allFramesBuffer[blendShape, vertex, frame] = new Vertex.BlendShapeFrame(weight, deltaVertex, deltaNormal, deltaTangent); + } + Profiler.EndSample(); + } + } + + Profiler.BeginSample("Compute Meaningful with Job"); + new ComputeMeaningfulJob + { + vertexCount = Vertices.Count, + allFramesBuffer = allFramesBuffer, + frameCounts = frameCounts, + meaningfuls = meaningfuls, + }.Schedule(Vertices.Count * mesh.blendShapeCount, 1).Complete(); + Profiler.EndSample(); + + for (var blendShape = 0; blendShape < mesh.blendShapeCount; blendShape++) + { + Profiler.BeginSample("Save to Vertices"); + for (var vertex = 0; vertex < Vertices.Count; vertex++) + { + if (meaningfuls[blendShape, vertex]) + { + Profiler.BeginSample("Clone BlendShapes"); + var slice = allFramesBuffer[blendShape, vertex].Slice(0, frameCounts[blendShape]); + Vertices[vertex].BlendShapes[shapeNames[blendShape]] = slice.ToArray(); + Profiler.EndSample(); + } + } + Profiler.EndSample(); + } + + meaningfuls.Dispose(); + frameCounts.Dispose(); + allFramesBuffer.Dispose(); + + + Profiler.EndSample(); + + return Vertices; + } + + + [BurstCompile] + struct ComputeMeaningfulJob : IJobParallelFor + { + public int vertexCount; + + // allFramesBuffer[blendShape][vertex][frame] + [ReadOnly] + public NativeArray3 allFramesBuffer; + [ReadOnly] + public NativeArray frameCounts; + // allFramesBuffer[blendShape][vertex] + [WriteOnly] + public NativeArray2 meaningfuls; + + public void Execute(int index) + { + var blendShape = index / vertexCount; + var vertex = index % vertexCount; + var slice = allFramesBuffer[blendShape, vertex].Slice(0, frameCounts[blendShape]); + meaningfuls[blendShape, vertex] = IsMeaningful(slice); + } + + bool IsMeaningful(NativeSlice frames) + { + foreach (var (_, position, normal, tangent) in frames) + { + if (position != Vector3.zero) return true; + if (normal != Vector3.zero) return true; + if (tangent != Vector3.zero) return true; + } + + return false; + } + } + + public static void WriteVertex(Mesh destMesh, MeshDesc meshAttribute, List Vertices) + { + Profiler.BeginSample("Write to Mesh"); + + Profiler.BeginSample("Vertices and Normals"); + // Basic Vertex Attributes: vertices, normals + { + var vertices = new Vector3[Vertices.Count]; + for (var i = 0; i < Vertices.Count; i++) + vertices[i] = Vertices[i].Position; + destMesh.vertices = vertices; + } + + // tangents + if (meshAttribute.HasNormals) + { + var normals = new Vector3[Vertices.Count]; + for (var i = 0; i < Vertices.Count; i++) + normals[i] = Vertices[i].Normal; + destMesh.normals = normals; + } + Profiler.EndSample(); + + // tangents + if (meshAttribute.HasTangent) + { + Profiler.BeginSample("Tangents"); + var tangents = new Vector4[Vertices.Count]; + for (var i = 0; i < Vertices.Count; i++) + tangents[i] = Vertices[i].Tangent; + destMesh.tangents = tangents; + Profiler.EndSample(); + } + + // UVs + { + var uv2 = new Vector2[Vertices.Count]; + var uv3 = new Vector3[Vertices.Count]; + var uv4 = new Vector4[Vertices.Count]; + for (var uvIndex = 0; uvIndex < 8; uvIndex++) + { + Profiler.BeginSample($"UV#{uvIndex}"); + switch (meshAttribute.GetTexCoordStatus(uvIndex)) + { + case TexCoordStatus.NotDefined: + // nothing to do + break; + case TexCoordStatus.Vector2: + for (var i = 0; i < Vertices.Count; i++) + uv2[i] = Vertices[i].GetTexCoord(uvIndex); + destMesh.SetUVs(uvIndex, uv2); + break; + case TexCoordStatus.Vector3: + for (var i = 0; i < Vertices.Count; i++) + uv3[i] = Vertices[i].GetTexCoord(uvIndex); + destMesh.SetUVs(uvIndex, uv3); + break; + case TexCoordStatus.Vector4: + for (var i = 0; i < Vertices.Count; i++) + uv4[i] = Vertices[i].GetTexCoord(uvIndex); + destMesh.SetUVs(uvIndex, uv4); + break; + default: + throw new ArgumentOutOfRangeException(); + } + Profiler.EndSample(); + } + } + + // color + if (meshAttribute.HasColor) + { + Profiler.BeginSample($"Vertex Color"); + var colors = new Color32[Vertices.Count]; + for (var i = 0; i < Vertices.Count; i++) + colors[i] = Vertices[i].Color; + destMesh.colors32 = colors; + Profiler.EndSample(); + } + + + // bones + destMesh.bindposes = meshAttribute.Bones.Select(x => x.Bindpose).ToArray(); + + // BoneWeights + if (Vertices.Any(x => x.BoneWeights.Count != 0)) + { + Profiler.BeginSample("BoneWeights"); + var boneIndices = new Dictionary(); + for (var i = 0; i < meshAttribute.Bones.Count; i++) + boneIndices.Add(meshAttribute.Bones[i], i); + + var bonesPerVertex = new NativeArray(Vertices.Count, Allocator.Temp); + var allBoneWeights = + new NativeArray(Vertices.Sum(x => x.BoneWeights.Count), Allocator.Temp); + var boneWeightsIndex = 0; + for (var i = 0; i < Vertices.Count; i++) + { + bonesPerVertex[i] = (byte)Vertices[i].BoneWeights.Count; + Vertices[i].BoneWeights.Sort((x, y) => -x.weight.CompareTo(y.weight)); + foreach (var (bone, weight) in Vertices[i].BoneWeights) + allBoneWeights[boneWeightsIndex++] = new BoneWeight1 + { boneIndex = boneIndices[bone], weight = weight }; + } + + destMesh.SetBoneWeights(bonesPerVertex, allBoneWeights); + Profiler.EndSample(); + } + + // BlendShapes + if (meshAttribute.BlendShapes.Count != 0) + { + Profiler.BeginSample("BlendShapes"); + for (var i = 0; i < meshAttribute.BlendShapes.Count; i++) + { + Debug.Assert(destMesh.blendShapeCount == i, "Unexpected state: BlendShape count"); + var (shapeName, _) = meshAttribute.BlendShapes[i]; + var weightsSet = new HashSet(); + + foreach (var vertex in Vertices) + if (vertex.BlendShapes.TryGetValue(shapeName, out var frames)) + foreach (var frame in frames) + weightsSet.Add(frame.Weight); + + // blendShape with no weights is not allowed. + if (weightsSet.Count == 0) + weightsSet.Add(100); + + var weights = weightsSet.ToArray(); + Array.Sort(weights); + + var positions = new Vector3[Vertices.Count]; + var normals = new Vector3[Vertices.Count]; + var tangents = new Vector3[Vertices.Count]; + + foreach (var weight in weights) + { + for (var vertexI = 0; vertexI < Vertices.Count; vertexI++) + { + var vertex = Vertices[vertexI]; + + vertex.TryGetBlendShape(shapeName, weight, + out var position, out var normal, out var tangent, + getDefined: true); + positions[vertexI] = position; + normals[vertexI] = normal; + tangents[vertexI] = tangent; + } + + destMesh.AddBlendShapeFrame(shapeName, weight, positions, normals, tangents); + } + } + Profiler.EndSample(); + } + + Profiler.EndSample(); + } + + + + + public class MeshDesc + { + public List<(string name, float weight)> BlendShapes = new List<(string name, float weight)>(0); + public List Bones = new List(); + + // TexCoordStatus which is 3 bits x 8 = 24 bits + private ushort _texCoordStatus; + public bool HasColor { get; set; } + public bool HasNormals { get; set; } + public bool HasTangent { get; set; } + + private const int BitsPerTexCoordStatus = 2; + private const int TexCoordStatusMask = (1 << BitsPerTexCoordStatus) - 1; + + public TexCoordStatus GetTexCoordStatus(int index) + { + return (TexCoordStatus)((_texCoordStatus >> (index * BitsPerTexCoordStatus)) & TexCoordStatusMask); + } + public void SetTexCoordStatus(int index, TexCoordStatus value) + { + _texCoordStatus = (ushort)( + (uint)_texCoordStatus & ~(TexCoordStatusMask << (BitsPerTexCoordStatus * index)) | + ((uint)value & TexCoordStatusMask) << (BitsPerTexCoordStatus * index)); + } + } + + + } + +} diff --git a/Runtime/TextureAtlas/AAOCode/MeshUtility.cs.meta b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs.meta new file mode 100644 index 00000000..c553c833 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 319cad5fe4afae74f81d59d410432546 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs b/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs new file mode 100644 index 00000000..9ab1b848 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs @@ -0,0 +1,58 @@ +using System; +using Unity.Burst; +using Unity.Collections; + + +namespace net.rs64.TexTransTool.TextureAtlas.AAOCode +{ + [BurstCompile] + struct NativeArray2 : IDisposable where T : unmanaged + { + private NativeArray _array; + private readonly int _firstDimension; + private readonly int _secondDimension; + + public NativeArray2(int firstDimension, int secondDimension, Allocator allocator) + { + _array = new NativeArray(firstDimension * secondDimension, allocator); + _firstDimension = firstDimension; + _secondDimension = secondDimension; + } + + public T this[int first, int second] + { + get => _array[first * _secondDimension + second]; + set => _array[first * _secondDimension + second] = value; + } + + public void Dispose() => _array.Dispose(); + } + + [BurstCompile] + struct NativeArray3 : IDisposable where T : unmanaged + { + private NativeArray _array; + private readonly int _firstDimension; + private readonly int _secondDimension; + private readonly int _thirdDimension; + + public NativeArray3(int firstDimension, int secondDimension, int thirdDimension, Allocator allocator) + { + _array = new NativeArray(firstDimension * secondDimension * thirdDimension, allocator); + _firstDimension = firstDimension; + _secondDimension = secondDimension; + _thirdDimension = thirdDimension; + } + + public T this[int first, int second, int third] + { + get => _array[(first * _secondDimension + second) * _thirdDimension + third]; + set => _array[(first * _secondDimension + second) * _thirdDimension + third] = value; + } + + public NativeSlice this[int first, int second] => + _array.Slice((first * _secondDimension + second) * _thirdDimension, _thirdDimension); + + public void Dispose() => _array.Dispose(); + } +} diff --git a/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs.meta b/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs.meta new file mode 100644 index 00000000..baf5e2f3 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e3af639e59d2794eb2b226ae9b49cf9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AAOCode/Vertex.cs b/Runtime/TextureAtlas/AAOCode/Vertex.cs new file mode 100644 index 00000000..98dee5d0 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/Vertex.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AAOCode +{ + internal class Vertex + { + public Vector3 Position { get; set; } + public Vector3 Normal { get; set; } + public Vector4 Tangent { get; set; } = new Vector4(1, 0, 0, 1); + public Vector4 TexCoord0 { get; set; } + public Vector4 TexCoord1 { get; set; } + public Vector4 TexCoord2 { get; set; } + public Vector4 TexCoord3 { get; set; } + public Vector4 TexCoord4 { get; set; } + public Vector4 TexCoord5 { get; set; } + public Vector4 TexCoord6 { get; set; } + public Vector4 TexCoord7 { get; set; } + + public Color32 Color { get; set; } = new Color32(0xff, 0xff, 0xff, 0xff); + + // SkinnedMesh related + public List<(Bone bone, float weight)> BoneWeights = new List<(Bone, float)>(); + + // Each frame must sorted increasingly + public readonly Dictionary BlendShapes = + new Dictionary(); + + public readonly struct BlendShapeFrame + { + public readonly float Weight; + public readonly Vector3 Position; + public readonly Vector3 Normal; + public readonly Vector3 Tangent; + + public BlendShapeFrame(float weight, Vector3 position, Vector3 normal, Vector3 tangent) + { + Position = position; + Normal = normal; + Tangent = tangent; + Weight = weight; + } + + public void Deconstruct(out float weight, out Vector3 position, out Vector3 normal, out Vector3 tangent) + { + weight = Weight; + position = Position; + normal = Normal; + tangent = Tangent; + } + } + + public Vector4 GetTexCoord(int index) + { + switch (index) + { + // @formatter off + case 0: return TexCoord0; + case 1: return TexCoord1; + case 2: return TexCoord2; + case 3: return TexCoord3; + case 4: return TexCoord4; + case 5: return TexCoord5; + case 6: return TexCoord6; + case 7: return TexCoord7; + default: throw new IndexOutOfRangeException("TexCoord index"); + // @formatter on + } + } + + public void SetTexCoord(int index, Vector4 value) + { + switch (index) + { + // @formatter off + case 0: TexCoord0 = value; break; + case 1: TexCoord1 = value; break; + case 2: TexCoord2 = value; break; + case 3: TexCoord3 = value; break; + case 4: TexCoord4 = value; break; + case 5: TexCoord5 = value; break; + case 6: TexCoord6 = value; break; + case 7: TexCoord7 = value; break; + default: throw new IndexOutOfRangeException("TexCoord index"); + // @formatter on + } + } + + public bool TryGetBlendShape(string name, float weight, out Vector3 position, out Vector3 normal, + out Vector3 tangent, bool getDefined = false) + { + if (!BlendShapes.TryGetValue(name, out var frames)) + { + position = default; + normal = default; + tangent = default; + return false; + } + + if (frames.Length == 0) + { + position = default; + normal = default; + tangent = default; + return false; + } + + if (!getDefined && Mathf.Abs(weight) <= 0.0001f && ZeroForWeightZero()) + { + position = Vector3.zero; + normal = Vector3.zero; + tangent = Vector3.zero; + return true; + } + + bool ZeroForWeightZero() + { + if (frames.Length == 1) return true; + var first = frames.First(); + var end = frames.Last(); + + // both weight are same sign, zero for 0 weight + if (first.Weight <= 0 && end.Weight <= 0) return true; + if (first.Weight >= 0 && end.Weight >= 0) return true; + + return false; + } + + if (frames.Length == 1) + { + // simplest and likely + var frame = frames[0]; + var ratio = weight / frame.Weight; + position = frame.Position * ratio; + normal = frame.Normal * ratio; + tangent = frame.Tangent * ratio; + return true; + } + else + { + // multi frame + var (lessFrame, greaterFrame) = FindFrame(); + var ratio = InverseLerpUnclamped(lessFrame.Weight, greaterFrame.Weight, weight); + + position = Vector3.LerpUnclamped(lessFrame.Position, greaterFrame.Position, ratio); + normal = Vector3.LerpUnclamped(lessFrame.Normal, greaterFrame.Normal, ratio); + tangent = Vector3.LerpUnclamped(lessFrame.Tangent, greaterFrame.Tangent, ratio); + return true; + } + + (BlendShapeFrame, BlendShapeFrame) FindFrame() + { + var firstFrame = frames[0]; + var lastFrame = frames.Last(); + + if (firstFrame.Weight > 0 && weight < firstFrame.Weight) + { + // if all weights are positive and the weight is less than first weight: lerp 0..first + return (default, firstFrame); + } + + if (lastFrame.Weight < 0 && weight > lastFrame.Weight) + { + // if all weights are negative and the weight is more than last weight: lerp last..0 + return (lastFrame, default); + } + + // otherwise, lerp between two surrounding frames OR nearest two frames + + for (var i = 1; i < frames.Length; i++) + { + if (weight <= frames[i].Weight) + return (frames[i - 1], frames[i]); + } + + return (frames[frames.Length - 2], frames[frames.Length - 1]); + } + + float InverseLerpUnclamped(float a, float b, float value) => (value - a) / (b - a); + } + + public Vertex() + { + } + + private Vertex(Vertex vertex) + { + Position = vertex.Position; + Normal = vertex.Normal; + Tangent = vertex.Tangent; + TexCoord0 = vertex.TexCoord0; + TexCoord1 = vertex.TexCoord1; + TexCoord2 = vertex.TexCoord2; + TexCoord3 = vertex.TexCoord3; + TexCoord4 = vertex.TexCoord4; + TexCoord5 = vertex.TexCoord5; + TexCoord6 = vertex.TexCoord6; + TexCoord7 = vertex.TexCoord7; + Color = vertex.Color; + BoneWeights = vertex.BoneWeights.ToList(); + BlendShapes = new Dictionary(vertex.BlendShapes); + } + + public Vertex Clone() => new Vertex(this); + + } + + public class Bone + { + public Matrix4x4 Bindpose; + public Transform Transform; + + public Bone(Matrix4x4 bindPose) : this(bindPose, null) { } + public Bone(Matrix4x4 bindPose, Transform transform) => (Bindpose, Transform) = (bindPose, transform); + } + + public enum TexCoordStatus + { + NotDefined = 0, + Vector2 = 1, + Vector3 = 2, + Vector4 = 3, + } +} diff --git a/Runtime/TextureAtlas/AAOCode/Vertex.cs.meta b/Runtime/TextureAtlas/AAOCode/Vertex.cs.meta new file mode 100644 index 00000000..2f538ab7 --- /dev/null +++ b/Runtime/TextureAtlas/AAOCode/Vertex.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b0119c759d937244989a343ce24df48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs new file mode 100644 index 00000000..4066f1a2 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -0,0 +1,393 @@ +using System.Collections.Generic; +using UnityEngine; +using net.rs64.TexTransCore.Island; +using System; +using net.rs64.TexTransCore.Decal; +using System.Linq; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using System.Collections; +using net.rs64.TexTransTool.TextureAtlas.AAOCode; +using net.rs64.TexTransTool.Utils; + +namespace net.rs64.TexTransTool.TextureAtlas +{ + internal class AtlasContext : IDisposable + { + public Mesh[] Meshes;//ノーマライズされていない + public Dictionary NormalizeMeshes;//ノーマライズされていないメッシュとされているメッシュと対応する + public Dictionary MeshDataDict;//適当なレンダラーのノーマライズされたメッシュと対応する + + public HashSet[] Materials; + public HashSet AtlasSubAll; + public List AtlasSubSets; + + public Dictionary> IslandDict; + public Island[] Islands; + public AtlasSubData[] IslandSubData; + + public struct AtlasSubData + { + public int MeshID; + public int SubMeshIndex; + public int MaterialID; + public AtlasSubData(int meshID, int subMeshIndex, int materialID) : this() + { + MeshID = meshID; + SubMeshIndex = subMeshIndex; + MaterialID = materialID; + } + public override bool Equals(object obj) { return obj is AtlasSubData other && MeshID == other.MeshID && SubMeshIndex == other.SubMeshIndex && MaterialID == other.MaterialID; } + public override int GetHashCode() { return HashCode.Combine(MeshID, SubMeshIndex, MaterialID); } + public static bool operator ==(AtlasSubData l, AtlasSubData r) + { + if (l.MeshID != r.MeshID) { return false; } + if (l.SubMeshIndex != r.SubMeshIndex) { return false; } + if (l.MaterialID != r.MaterialID) { return false; } + return true; + } + public static bool operator !=(AtlasSubData l, AtlasSubData r) + { + if (l.MeshID != r.MeshID) { return true; } + if (l.SubMeshIndex != r.SubMeshIndex) { return true; } + if (l.MaterialID != r.MaterialID) { return true; } + return false; + } + + } + public AtlasContext(List TargetMaterials, List inputRenderers) + { + var materialHash = TargetMaterials.ToHashSet(); + Materials = materialHash.Select(m => new HashSet() { m }).ToArray();//今後マテリアルが違っても同一とみる機会が発生するから、マテリアルのグルーピングの仕組みを作る。 + + var TargetRenderers = inputRenderers.Where(r => r.sharedMaterials.Any(m => materialHash.Contains(m))).ToArray(); + var normalizedMesh = SubVertNormalize(TargetRenderers); + + var m2md = new Dictionary(); + foreach (var mkr in TargetRenderers.GroupBy(r => r.GetMesh())) + { + var nmMesh = normalizedMesh[mkr.Key]; + var renderer = mkr.First(r => r.sharedMaterials.Length == nmMesh.subMeshCount); + + m2md[nmMesh] = new MeshData(renderer, nmMesh, MeshData.GetMatrix(renderer)); + } + + NormalizeMeshes = normalizedMesh; + MeshDataDict = m2md; + Meshes = normalizedMesh.Select(i => i.Key).ToArray(); + + AtlasSubAll = new(); + var atlasSubSets = new List(); + for (var ri = 0; TargetRenderers.Length > ri; ri += 1) + { + var renderer = TargetRenderers[ri]; + var mats = renderer.sharedMaterials; + var mesh = renderer.GetMesh(); + var meshID = Array.IndexOf(Meshes, mesh); + var atlasSubSet = new AtlasSubData?[mats.Length]; + for (var si = 0; mats.Length > si; si += 1) + { + if (!materialHash.Contains(mats[si])) { continue; } + var matID = Array.FindIndex(Materials, i => i.Contains(mats[si])); + var atSubData = atlasSubSet[si] = new(meshID, si, matID); + AtlasSubAll.Add(atSubData.Value); + } + atlasSubSets.Add(atlasSubSet); + } + + IdenticalSubSetRemove(atlasSubSets); + AtlasSubSets = atlasSubSets; + + var islandDict = new Dictionary>(); + foreach (var atSub in AtlasSubAll) + { + var md = MeshDataDict[normalizedMesh[Meshes[atSub.MeshID]]]; + + var triangle = normalizedMesh[Meshes[atSub.MeshID]].GetSubTriangleIndex(atSub.SubMeshIndex); + // var triangle = md.TriangleIndex[atSub.SubMeshIndex].AsList(); //なぜかこっちだと一部のモデルで正しくUVtoIslandができない...なぜ? + + var island = IslandUtility.UVtoIsland(triangle, md.VertexUV.AsList()); + islandDict[atSub] = island; + } + + + //Cross SubMesh Island Marge + foreach (var atSubGroup in AtlasSubAll.GroupBy(i => (i.MeshID, i.MaterialID))) + { + var atSubCrossTarget = atSubGroup.ToArray(); + Array.Sort(atSubCrossTarget, (l, r) => l.SubMeshIndex - r.SubMeshIndex); + + var meshData = MeshDataDict[normalizedMesh[Meshes[atSubGroup.Key.MeshID]]]; + var uv = meshData.VertexUV; + var uvToIndex = new Dictionary(); + var uvIndex = 0; + foreach (var uvVert in uv) + { + if (!uvToIndex.ContainsKey(uvVert)) + { + uvToIndex[uvVert] = uvIndex; + uvIndex += 1; + } + } + var uvIndexCount = uvIndex + 1; + + var usedUVVertIndexUsed = new BitArray[atSubCrossTarget.Length]; + for (var i = 0; atSubCrossTarget.Length > i; i += 1) + { + var atSub = atSubCrossTarget[i]; + var bitArray = new BitArray(uvIndexCount); + foreach (var tri in meshData.TriangleIndex[atSub.SubMeshIndex]) + { + for (var ti = 0; 3 > ti; ti += 1) + { + bitArray[uvToIndex[uv[tri[ti]]]] = true; + } + } + usedUVVertIndexUsed[i] = bitArray; + } + + var margeAt = new Dictionary(); + + for (var fi = 0; atSubCrossTarget.Length > fi; fi += 1) + { + for (var ti = fi + 1; atSubCrossTarget.Length > ti; ti += 1) + { + for (var vi = 0; usedUVVertIndexUsed[fi].Length > vi; vi += 1) + { + if (usedUVVertIndexUsed[fi][vi] && usedUVVertIndexUsed[ti][vi]) { margeAt[fi] = ti; break; } + } + } + + } + + foreach (var mki in margeAt) + { + var fromAtSub = atSubCrossTarget[mki.Key]; + var toAtSub = atSubCrossTarget[mki.Value]; + + (Island, BitArray) islandToUseBitArray(Island i) + { + var islandBitArray = new BitArray(uvIndexCount); + foreach (var tri in i.triangles) + { + for (var ti = 0; 3 > ti; ti += 1) + { + islandBitArray[uvToIndex[uv[tri[ti]]]] = true; + } + } + return (i, islandBitArray); + } + + var islandToUseIndexBits = islandDict[fromAtSub].Concat(islandDict[toAtSub]).Select(islandToUseBitArray).ToDictionary(i => i.Item1, i => i.Item2); + + + foreach (var fIsland in islandDict[fromAtSub]) + { + var removeAt = new HashSet(); + foreach (var tIsland in islandDict[toAtSub]) + { + var fBit = islandToUseIndexBits[fIsland]; + var tBit = islandToUseIndexBits[tIsland]; + + var needMerge = false; + for (var vi = 0; fBit.Length > vi; vi += 1) + { + if (fBit[vi] && tBit[vi]) { needMerge = true; break; } + } + if (!needMerge) { continue; } + + var min = Vector2.Min(fIsland.Pivot, tIsland.Pivot); + var max = Vector2.Max(fIsland.GetMaxPos, tIsland.GetMaxPos); + fIsland.Pivot = min; + fIsland.Size = max - fIsland.Pivot; + + fIsland.triangles.AddRange(tIsland.triangles); + removeAt.Add(tIsland); + } + islandDict[toAtSub].RemoveAll(removeAt.Contains); + } + + } + } + IslandDict = islandDict; + + var atSubLinkList = new LinkedList(); + var IslandLinkList = new LinkedList(); + + foreach (var atKv in IslandDict) + { + var atlasSubData = atKv.Key; + var islands = atKv.Value; + + var count = islands.Count; + for (var ii = 0; count > ii; ii += 1) + { + atSubLinkList.AddLast(atlasSubData); + IslandLinkList.AddLast(islands[ii]); + } + } + + Islands = IslandLinkList.ToArray(); + IslandSubData = atSubLinkList.ToArray(); + + static void IdenticalSubSetRemove(List atlasSubSets) + { + while (true) + { + var margeAt = Find(atlasSubSets); + if (margeAt is null) { return; } + var val = margeAt.Value; + atlasSubSets.RemoveAt(val.Item2); + } + + static (int, int)? Find(List atlasSubSets) + { + var assCount = atlasSubSets.Count; + for (var fi = 0; assCount > fi; fi += 1) + { + for (var ti = fi + 1; assCount > ti; ti += 1) + { + var fSubSet = atlasSubSets[fi]; + var tSubSet = atlasSubSets[ti]; + + var first = fSubSet[0]; + var tFirst = tSubSet[0]; + + if (first is null || tFirst is null) { continue; } + if (first.Value.MeshID != tFirst.Value.MeshID) { continue; } + + if (fSubSet.SequenceEqual(tSubSet)) { return (fi, ti); } + + if (SubPartEqual(fSubSet, tSubSet)) + { + if (fSubSet.Length > tSubSet.Length) { return (fi, ti); } + else { return (ti, fi); } + } + + } + } + + return null; + + static bool SubPartEqual(AtlasSubData?[] fSubSet, AtlasSubData?[] tSubSet) + { + var minCount = Math.Min(fSubSet.Length, tSubSet.Length); + for (var i = 0; minCount > i; i += 1) + { + if (fSubSet[i].HasValue != fSubSet[i].HasValue) { return false; } + if (fSubSet[i] != tSubSet[i]) { return false; } + } + return true; + } + } + } + } + + private Dictionary SubVertNormalize(Renderer[] targetRenderers) + { + var normalizedMesh = new Dictionary(); + foreach (var MkR in targetRenderers.GroupBy(i => i.GetMesh())) + { + var mesh = MkR.Key; + var maxSlot = 0; foreach (var r in MkR) { maxSlot = Mathf.Max(r.sharedMaterials.Length, maxSlot); } + + var isOverSubMesh = maxSlot != mesh.subMeshCount; + var isCrossSubMesh = IsCrossSubMesh(mesh); + + if (!isOverSubMesh && !isCrossSubMesh) { normalizedMesh[mesh] = UnityEngine.Object.Instantiate(mesh); continue; } + + normalizedMesh[mesh] = NormalizedMesh(mesh, maxSlot); + } + return normalizedMesh; + + bool IsCrossSubMesh(Mesh mesh) + { + var vertSubMeshBit = new BitArray[mesh.subMeshCount]; + var triList = new List(); + for (var subMeshIndex = 0; mesh.subMeshCount > subMeshIndex; subMeshIndex += 1) + { + triList.Clear(); + mesh.GetTriangles(triList, subMeshIndex); + var vertBit = new BitArray(mesh.vertexCount); + foreach (var ti in triList) { vertBit[ti] = true; } + vertSubMeshBit[subMeshIndex] = vertBit; + } + + for (var fi = 0; vertSubMeshBit.Length > fi; fi += 1) + { + for (var ti = fi + 1; vertSubMeshBit.Length > ti; ti += 1) + { + for (var vi = 0; vertSubMeshBit[fi].Length > vi; vi += 1) + { + if (vertSubMeshBit[fi][vi] && vertSubMeshBit[ti][vi]) { return true; } + } + } + } + + return false; + } + + Mesh NormalizedMesh(Mesh mesh, int expandSlot) + { + var vertex = MeshInfoUtility.ReadVertex(mesh, out var meshDesc); + var vertHash = new HashSet(); + + + var subMeshViArray = new int[expandSlot][]; + for (var si = 0; subMeshViArray.Length > si; si += 1) { subMeshViArray[si] = mesh.GetTriangles(si % mesh.subMeshCount); } + + var subMeshOfVertex = new Vertex[expandSlot][]; + for (var si = 0; subMeshViArray.Length > si; si += 1) + { + var subMeshVi = subMeshViArray[si]; + var subMeshVert = subMeshOfVertex[si] = new Vertex[subMeshVi.Length]; + for (var vi = 0; subMeshVi.Length > vi; vi += 1) + { + subMeshVert[vi] = vertex[subMeshVi[vi]]; + } + + } + + var useVert = new HashSet(); + for (var si = 0; subMeshOfVertex.Length > si; si += 1) + { + var subMeshVert = subMeshOfVertex[si]; + + var subCrossUsed = new HashSet(subMeshVert); + subCrossUsed.IntersectWith(useVert); + + useVert.UnionWith(subMeshVert); + + if (!subCrossUsed.Any()) { continue; } + + var replaceDict = subCrossUsed.ToDictionary(i => i, i => i.Clone()); + + for (var vi = 0; subMeshVert.Length > vi; vi += 1) + { + if (replaceDict.TryGetValue(subMeshVert[vi], out var rv)) { subMeshVert[vi] = rv; } + } + + vertex.AddRange(replaceDict.Values); + } + + var modifiedMesh = UnityEngine.Object.Instantiate(mesh); + MeshInfoUtility.WriteVertex(modifiedMesh, meshDesc, vertex); + + modifiedMesh.subMeshCount = subMeshOfVertex.Length; + for (var si = 0; subMeshOfVertex.Length > si; si += 1) { modifiedMesh.SetTriangles(subMeshOfVertex[si].Select(v => vertex.IndexOf(v)).ToArray(), si); } + + //念のために複製 + var moreCloned = UnityEngine.Object.Instantiate(modifiedMesh); + UnityEngine.Object.DestroyImmediate(modifiedMesh); + return moreCloned; + } + } + + + public void Dispose() + { + foreach (var md in MeshDataDict) { md.Value.Dispose(); } + } + + + } +} diff --git a/Runtime/TextureAtlas/AtlasContext.cs.meta b/Runtime/TextureAtlas/AtlasContext.cs.meta new file mode 100644 index 00000000..ec1bca4e --- /dev/null +++ b/Runtime/TextureAtlas/AtlasContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef569c221e9cad643bd76ab23cc5f2f9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasIsland.cs b/Runtime/TextureAtlas/AtlasIsland.cs index d7ed30da..4d7bf947 100644 --- a/Runtime/TextureAtlas/AtlasIsland.cs +++ b/Runtime/TextureAtlas/AtlasIsland.cs @@ -6,21 +6,6 @@ namespace net.rs64.TexTransTool.TextureAtlas { - public class AtlasIsland : Island - { - public List UV; - - public AtlasIsland(AtlasIsland souse) : base(souse) - { - UV = souse.UV; - } - - public AtlasIsland(Island souse, List uv) : base(souse) - { - UV = uv; - } - } - public struct IslandRect : IIslandRect { public Vector2 Pivot; diff --git a/Runtime/TextureAtlas/AtlasReferenceData.cs b/Runtime/TextureAtlas/AtlasReferenceData.cs new file mode 100644 index 00000000..165fb13c --- /dev/null +++ b/Runtime/TextureAtlas/AtlasReferenceData.cs @@ -0,0 +1,347 @@ +using System.Collections.Generic; +using UnityEngine; +using System.Linq; +using System; +using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore.Island; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Decal; + +namespace net.rs64.TexTransTool.TextureAtlas +{ + internal class AtlasReferenceData : IDisposable + { + public OrderedHashSet Meshes; + public HashSet TargetMaterials; + public OrderedHashSet Materials; + public List AtlasMeshDataList; + public AtlasReferenceData(List targetMaterials, List inputRenderers) + { + TargetMaterials = new HashSet(targetMaterials); + Meshes = new(); Materials = new(); + var Renderers = new List(); + + foreach (var renderer in inputRenderers) + { + foreach (var mat in renderer.sharedMaterials) + { + if (TargetMaterials.Contains(mat)) + { + Meshes.Add(renderer.GetMesh()); + Materials.AddRange(renderer.sharedMaterials); + Renderers.Add(renderer); + break; + } + } + } + + AtlasMeshDataList = new(); + + foreach (var renderer in Renderers) + { + var mesh = renderer.GetMesh(); + var refMesh = Meshes.IndexOf(mesh); + var materialIndex = renderer.sharedMaterials.Select(Mat => Materials.IndexOf(Mat)).ToArray(); + int index = GetAtlasMeshDataIndex(refMesh, materialIndex); + if (index == -1) + { + var uv = new List(); + mesh.GetUVs(0, uv); + + AtlasMeshDataList.Add(new( + refMesh, + mesh.GetSubTriangleIndex(), + uv, + materialIndex, + renderer + )); + } + } + } + + + + internal int GetAtlasMeshDataIndex(int refMesh, int[] materialIndex) + { + return AtlasMeshDataList.FindIndex(AMD => AMD.ReferenceMesh == refMesh && AMD.MaterialIndex.SequenceEqual(materialIndex)); + } + + public class AtlasMeshData + { + //RefData + public int ReferenceMesh; + public int[] MaterialIndex; + + //for Generate + public readonly List> Triangles; + public List UV; + public List MovedUV; + public Renderer Renderer; + public MeshData MeshData; + + public AtlasMeshData(int referenceMesh, List> triangles, List uv, int[] materialIndex, Renderer renderer) + { + ReferenceMesh = referenceMesh; + Triangles = triangles; + UV = uv; + MaterialIndex = materialIndex; + Renderer = renderer; + MeshData = new MeshData(renderer); + } + public AtlasMeshData() + { + Triangles = new List>(); + UV = new List(); + } + } + + + /// + /// すべてをアイランドにし、同一の物を指すアイランドは排除したものを返します。 + /// + /// + /// + public Dictionary GeneratedIslandPool() + { + var islandPool = new Dictionary(); + var amdCount = AtlasMeshDataList.Count; + var islandIndex = 0; + for (int amdIndex = 0; amdIndex < amdCount; amdIndex += 1) + { + var atlasMeshData = AtlasMeshDataList[amdIndex]; + + for (var SlotIndex = 0; atlasMeshData.MaterialIndex.Length > SlotIndex; SlotIndex += 1) + { + if (!TargetMaterials.Contains(Materials[atlasMeshData.MaterialIndex[SlotIndex]])) { continue; } + if (atlasMeshData.Triangles.Count <= SlotIndex) { continue; } + + var islands = IslandUtility.UVtoIsland(atlasMeshData.Triangles[SlotIndex], atlasMeshData.UV); + foreach (var island in islands) { islandPool.Add(new AtlasIslandID(amdIndex, SlotIndex, islandIndex), island); islandIndex += 1; } + } + } + + var refsHash = new HashSet(); + var deleteTags = new HashSet(); + foreach (var tag in islandPool.Keys.Select(i => new AtlasSlotRef(i.AtlasMeshDataIndex, i.MaterialSlot)).Distinct()) + { + var atlasMeshData = AtlasMeshDataList[tag.AtlasMeshDataIndex]; + + var refMesh = atlasMeshData.ReferenceMesh; + var materialSlot = tag.MaterialSlot; + var refMat = atlasMeshData.MaterialIndex[tag.MaterialSlot]; + + var refs = new MSMRef(refMesh, materialSlot, refMat); + + if (refsHash.Contains(refs)) { deleteTags.Add(tag); } + else { refsHash.Add(refs); } + } + + var filteredIslandPool = new Dictionary(islandPool.Count); + islandIndex = 0; + foreach (var idPair in islandPool) + { + var atlasID = idPair.Key; + var island = idPair.Value; + + if (deleteTags.Contains(new AtlasSlotRef(atlasID.AtlasMeshDataIndex, atlasID.MaterialSlot))) { continue; } + + atlasID.IslandIndex = islandIndex; + filteredIslandPool.Add(atlasID, island); + islandIndex += 1; + } + + + //サブメッシュ間で頂点を共有するアイランドのマージ + var containsIdenticalIslandForMultipleSubMesh = false; + for (var amdIndex = 0; AtlasMeshDataList.Count > amdIndex; amdIndex += 1) + { + var amd = AtlasMeshDataList[amdIndex]; + + var beyondVert = amd.Triangles.Where(i => TargetMaterials.Contains(Materials[amd.MaterialIndex[amd.Triangles.IndexOf(i)]])) + .Select(i => new HashSet(i.SelectMany(i2 => i2))).SelectMany(i => i) + .GroupBy(i => i).Select(i => (i.Key, i.Count())).Where(i => i.Item2 > 1).Select(i => i.Key).ToHashSet(); + + if (beyondVert.Any()) { containsIdenticalIslandForMultipleSubMesh = true; } + else { continue; } + + var needMerge = filteredIslandPool.Where(i => i.Key.AtlasMeshDataIndex == amdIndex).Where(i => i.Value.triangles.SelectMany(i => i).Any(i => beyondVert.Contains(i))).GroupBy(i => i.Key.MaterialSlot).ToList(); + needMerge.Sort((l, r) => l.Key - r.Key); + + var needMergeIslands = needMerge.Select(i => i.ToHashSet()).ToArray(); + var MargeKV = new Dictionary>(); + + for (var toIndex = 0; needMergeIslands.Length > toIndex; toIndex += 1) + { + foreach (var island in needMergeIslands[toIndex]) + { + var vertSet = island.Value.triangles.SelectMany(i => i).ToHashSet(); + + for (var fromIndex = toIndex; needMergeIslands.Length > fromIndex; fromIndex += 1) + { + if (toIndex == fromIndex) { continue; } + + var margeFrom = needMergeIslands[fromIndex].Where(il => il.Value.triangles.SelectMany(v => v).Any(v => vertSet.Contains(v))); + if (margeFrom.Any()) { MargeKV.Add(island.Key, margeFrom.Select(i => i.Key).ToHashSet()); } + } + } + } + + foreach (var margeIdKV in MargeKV) + { + var to = filteredIslandPool[margeIdKV.Key]; + + foreach (var formKey in margeIdKV.Value) + { + to.triangles.AddRange(filteredIslandPool[formKey].triangles); + filteredIslandPool.Remove(formKey); + } + } + + } + if (containsIdenticalIslandForMultipleSubMesh) { TTTRuntimeLog.Warning("AtlasTexture:error:IdenticalIslandForMultipleSubMesh"); } + + + + + + + + + return filteredIslandPool; + } + + public Material GetMaterialReference(AtlasIslandID indexTag) + { + return GetMaterialReference(indexTag.AtlasMeshDataIndex, indexTag.MaterialSlot); + } + private Material GetMaterialReference(int atlasMeshDataIndex, int materialSlot) + { + return Materials[AtlasMeshDataList[atlasMeshDataIndex].MaterialIndex[materialSlot]]; + } + internal AtlasSlotRef? FindIdenticalSlotRef(HashSet slotRefs, MSMRef findTarget) + { + foreach (var tag in slotRefs) + { + var tagAmd = AtlasMeshDataList[tag.AtlasMeshDataIndex]; + + if (findTarget.RefMesh != tagAmd.ReferenceMesh) { continue; } + if (findTarget.RefMatSlot != tag.MaterialSlot) { continue; } + if (findTarget.RefMat != tagAmd.MaterialIndex[tag.MaterialSlot]) { continue; } + + return tag; + } + + return null; + } + + internal static IEnumerable> IslandFind(AtlasSlotRef atlasIdenticalTag, Dictionary islandRect) + { + foreach (var islandKV in islandRect) + { + if (islandKV.Key.AtlasMeshDataIndex != atlasIdenticalTag.AtlasMeshDataIndex) { continue; } + if (islandKV.Key.MaterialSlot != atlasIdenticalTag.MaterialSlot) { continue; } + + yield return islandKV; + } + } + + public void Dispose() + { + foreach (var amd in AtlasMeshDataList) { amd.MeshData.Dispose(); } + } + } + + internal struct MSMRef + { + public int RefMesh; + public int RefMatSlot; + public int RefMat; + + public MSMRef(int refMesh, int matSlot, int refMat) + { + RefMesh = refMesh; + RefMatSlot = matSlot; + RefMat = refMat; + } + + public override bool Equals(object obj) + { + return obj is MSMRef other && + RefMesh == other.RefMesh && + RefMatSlot == other.RefMatSlot && + RefMat == other.RefMat; + } + + public override int GetHashCode() + { + return HashCode.Combine(RefMesh, RefMatSlot, RefMat); + } + } + internal struct AtlasSlotRef + { + public int AtlasMeshDataIndex; + public int MaterialSlot; + + public AtlasSlotRef(int atlasMeshDataIndex, int materialSlot) + { + AtlasMeshDataIndex = atlasMeshDataIndex; + MaterialSlot = materialSlot; + } + + public static bool operator ==(AtlasSlotRef a, AtlasSlotRef b) + { + return a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; + } + public static bool operator !=(AtlasSlotRef a, AtlasSlotRef b) + { + return !(a == b); + } + public override bool Equals(object obj) + { + return obj is AtlasSlotRef tag && this == tag; + } + public override int GetHashCode() + { + return AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); + } + internal static HashSet ToSlotRefHash(IEnumerable tags) + { + var indexTag = new HashSet(); + foreach (var tag in tags) { indexTag.Add(new(tag.AtlasMeshDataIndex, tag.MaterialSlot)); } + return indexTag; + } + + + } + public struct AtlasIslandID + { + public int AtlasMeshDataIndex; + public int MaterialSlot; + public int IslandIndex; + + public AtlasIslandID(int atlasMeshDataIndex, int materialSlot, int islandIndex) + { + AtlasMeshDataIndex = atlasMeshDataIndex; + MaterialSlot = materialSlot; + IslandIndex = islandIndex; + } + + public static bool operator ==(AtlasIslandID a, AtlasIslandID b) + { + return a.IslandIndex == b.IslandIndex && a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; + } + public static bool operator !=(AtlasIslandID a, AtlasIslandID b) + { + return !(a == b); + } + public override bool Equals(object obj) + { + return obj is AtlasIslandID tag && this == tag; + } + public override int GetHashCode() + { + return IslandIndex.GetHashCode() ^ AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); + } + } +} diff --git a/Runtime/TextureAtlas/AtlasReferenceData.cs.meta b/Runtime/TextureAtlas/AtlasReferenceData.cs.meta new file mode 100644 index 00000000..98d76a93 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasReferenceData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9e9efdf5f6249fb46a68da00e3197edd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasSetting.cs b/Runtime/TextureAtlas/AtlasSetting.cs index 880cd998..b67aec6b 100644 --- a/Runtime/TextureAtlas/AtlasSetting.cs +++ b/Runtime/TextureAtlas/AtlasSetting.cs @@ -5,26 +5,30 @@ using UnityEngine.Serialization; using net.rs64.TexTransTool.TextureAtlas.IslandRelocator; using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransTool.TextureAtlas.IslandFineTuner; namespace net.rs64.TexTransTool.TextureAtlas { [Serializable] public class AtlasSetting { + [SerializeReference] internal List IslandFineTuners; public bool MergeMaterials; public Material MergeReferenceMaterial; public PropertyBakeSetting PropertyBakeSetting = PropertyBakeSetting.NotBake; public bool ForceSetTexture; - [PowerOfTwo]public int AtlasTextureSize = 2048; + [PowerOfTwo] public int AtlasTextureSize = 2048; [Range(0f, 0.05f)] public float IslandPadding = 0.01f; public AtlasIslandRelocatorObject AtlasIslandRelocator; public bool WriteOriginalUV = false; [FormerlySerializedAs("IncludeDisableRenderer")] public bool IncludeDisabledRenderer = false; - public bool UseUpScaling = false; public bool PixelNormalize = false; [SerializeReference] public List TextureFineTuning = new List { Resize.Default }; public float GetTexScalePadding => IslandPadding * AtlasTextureSize; + #region V3SaveData + public bool UseUpScaling = false; + #endregion #region V2SaveData [Obsolete("V2SaveData", true)][SerializeField] internal List TextureFineTuningDataList = new List { new TextureFineTuningData() }; [Obsolete("V2SaveData", true)][SerializeField] internal float Padding; diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 7627de33..6837c533 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -10,6 +10,8 @@ using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.TextureAtlas.FineTuning; using net.rs64.TexTransTool.TextureAtlas.IslandRelocator; +using UnityEngine.Serialization; +using Unity.Collections; namespace net.rs64.TexTransTool.TextureAtlas { @@ -21,6 +23,7 @@ public sealed class AtlasTexture : TexTransRuntimeBehavior public GameObject TargetRoot; public List Renderers => FilteredRenderers(TargetRoot, AtlasSetting.IncludeDisabledRenderer); public List SelectMatList = new List(); + public MaterialToIslandFineTuningMode MaterialToIslandFineTuningModeSelect; public AtlasSetting AtlasSetting = new AtlasSetting(); @@ -30,6 +33,13 @@ public sealed class AtlasTexture : TexTransRuntimeBehavior internal override TexTransPhase PhaseDefine => TexTransPhase.Optimizing; + + public enum MaterialToIslandFineTuningMode + { + SizeOffset = 0, + SizePriority = 1, + } + #region V0SaveData [Obsolete("V0SaveData", true)] public List MigrationV0ObsoleteChannelsRef; [Obsolete("V0SaveData", true)] public List SelectReferenceMat;//OrderedHashSetにしたかったけどシリアライズの都合で @@ -75,19 +85,20 @@ struct AtlasData { public List Textures; public List Meshes; - public List AtlasInMaterials; + public List AtlasInMaterials; + public HashSet[] MaterialID; public struct AtlasMeshAndDist { public Mesh DistMesh; public Mesh AtlasMesh; - public Material[] Mats; + public int[] MatIDs; - public AtlasMeshAndDist(Mesh distMesh, Mesh atlasMesh, Material[] mats) + public AtlasMeshAndDist(Mesh distMesh, Mesh atlasMesh, int[] mats) { DistMesh = distMesh; AtlasMesh = atlasMesh; - Mats = mats; + MatIDs = mats; } } } @@ -95,26 +106,13 @@ public AtlasMeshAndDist(Mesh distMesh, Mesh atlasMesh, Material[] mats) public struct MatSelector { public Material Material; - public float AdditionalTextureSizeOffSet; + [FormerlySerializedAs("AdditionalTextureSizeOffSet")] public float MaterialFineTuningValue; #region V1SaveData [Obsolete("V1SaveData", true)][SerializeField] internal float TextureSizeOffSet; #endregion } - struct MatData - { - public Material Material; - public float TextureSizeOffSet; - public List PropAndTextures;//ここには Texture2D か TempRendererTextureが入ってる - - public MatData(MatSelector matSelector, List propAndTextures) - { - Material = matSelector.Material; - TextureSizeOffSet = matSelector.AdditionalTextureSizeOffSet; - PropAndTextures = propAndTextures; - } - } bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) { @@ -124,212 +122,235 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) //情報を集めるフェーズ var NowContainsMatSet = new HashSet(RendererUtility.GetMaterials(Renderers)); - var targetMaterialSelectors = SelectMatList.Select(matS => - { - matS.Material = domain.TryReplaceQuery(matS.Material, out var rMat) ? (Material)rMat : matS.Material; - return matS; - }).Where(I => I.Material != null && NowContainsMatSet.Contains(I.Material)).GroupBy(i => i.Material).Select(i => i.First()).ToList(); - atlasData.AtlasInMaterials = targetMaterialSelectors; + var targetMaterials = NowContainsMatSet.Distinct().Where(i => i != null) + .Where(mat => SelectMatList.Any(smat => domain.OriginEqual(smat.Material, mat))).ToList(); + + atlasData.AtlasInMaterials = targetMaterials; var atlasSetting = AtlasSetting; - var atlasReferenceData = new AtlasReferenceData(targetMaterialSelectors.Select(I => I.Material).ToList(), Renderers); + // var atlasReferenceData = new AtlasReferenceData(targetMaterials, Renderers); + var atlasContext = new AtlasContext(targetMaterials, Renderers); var shaderSupports = new AtlasShaderSupportUtils(); //サブメッシュより多いスロットの存在可否 - if (atlasReferenceData.AtlasMeshDataList.Any(i => i.Triangles.Count < i.MaterialIndex.Length)) { TTTRuntimeLog.Warning("AtlasTexture:error:MoreMaterialSlotThanSubMesh"); } + // if (atlasReferenceData.AtlasMeshDataList.Any(i => i.Triangles.Count < i.MaterialIndex.Length)) { TTTRuntimeLog.Warning("AtlasTexture:error:MoreMaterialSlotThanSubMesh"); } //ターゲットとなるマテリアルやそのマテリアルが持つテクスチャを引き出すフェーズ shaderSupports.BakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; var materialTextures = new Dictionary>(); - foreach (var matSelector in targetMaterialSelectors) { shaderSupports.AddRecord(matSelector.Material); } - foreach (var matSelector in targetMaterialSelectors) { materialTextures[matSelector.Material] = shaderSupports.GetTextures(matSelector.Material, texManage); } + foreach (var mat in targetMaterials) { shaderSupports.AddRecord(mat); } + foreach (var mat in targetMaterials) { materialTextures[mat] = shaderSupports.GetTextures(mat, texManage); } shaderSupports.ClearRecord(); - var materialAdditionalTextureOffset = new Dictionary(); - foreach (var matSelector in targetMaterialSelectors) { materialAdditionalTextureOffset[matSelector.Material] = matSelector.AdditionalTextureSizeOffSet; } + var islandSizeOffset = GetTextureSizeOffset(targetMaterials, atlasSetting); + //アイランドまわり + if (atlasSetting.PixelNormalize) + { + foreach (var islandKV in atlasContext.IslandDict) + { + var material = materialTextures[atlasContext.Materials[islandKV.Key.MaterialID].First()]; + var refTex = material.FirstOrDefault(i => i.PropertyName == "_MainTex")?.Texture; + if (refTex == null) { continue; } + foreach (var island in islandKV.Value) + { + island.Pivot.y = Mathf.Round(island.Pivot.y * refTex.height) / refTex.height; + island.Pivot.x = Mathf.Round(island.Pivot.x * refTex.width) / refTex.width; + } + } + } + var islandArray = atlasContext.Islands; + var rectArray = new IslandRect[islandArray.Length]; + var index = 0; + foreach (var islandKV in atlasContext.Islands) + { + rectArray[index] = new IslandRect(islandKV); + index += 1; + } + var sizePriority = new float[islandArray.Length]; for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = 1f; } + var islandDescription = new IslandSelector.IslandDescription[islandArray.Length]; + for (var i = 0; islandDescription.Length > i; i += 1) + { + var md = atlasContext.MeshDataDict[atlasContext.NormalizeMeshes[atlasContext.Meshes[atlasContext.IslandSubData[i].MeshID]]]; - //アイランドまわり - var originIslandPool = atlasReferenceData.GeneratedIslandPool(); + var vertex = md.Vertices; + var uv = md.VertexUV; + var renderer = md.ReferenceRenderer; + islandDescription[i] = new IslandSelector.IslandDescription(vertex, uv, renderer, atlasContext.IslandSubData[i].SubMeshIndex); + } - //サブメッシュ間で頂点を共有するアイランドのマージ - var containsIdenticalIslandForMultipleSubMesh = false; - for (var amdIndex = 0; atlasReferenceData.AtlasMeshDataList.Count > amdIndex; amdIndex += 1) + foreach (var mat in SelectMatList) { - var amd = atlasReferenceData.AtlasMeshDataList[amdIndex]; + var textureSizeOffSet = islandSizeOffset[mat.Material]; + for (var i = 0; rectArray.Length > i; i += 1) + { + var desc = islandDescription[i]; + var matSlotRef = desc.MaterialSlot; + if (!domain.OriginEqual(desc.Renderer.sharedMaterials[matSlotRef], mat.Material)) { continue; } - var beyondVert = amd.Triangles.Where(i => atlasReferenceData.TargetMaterials.Contains(atlasReferenceData.Materials[amd.MaterialIndex[amd.Triangles.IndexOf(i)]])) - .Select(i => new HashSet(i.SelectMany(i2 => i2))).SelectMany(i => i) - .GroupBy(i => i).Select(i => (i.Key, i.Count())).Where(i => i.Item2 > 1).Select(i => i.Key).ToHashSet(); + rectArray[i].Size *= textureSizeOffSet; - if (beyondVert.Any()) { containsIdenticalIslandForMultipleSubMesh = true; } - else { continue; } + switch (MaterialToIslandFineTuningModeSelect) + { + case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= mat.MaterialFineTuningValue; break; } + case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = mat.MaterialFineTuningValue; break; } + default: break; + } + } + } - var needMerge = originIslandPool.Where(i => i.Key.AtlasMeshDataIndex == amdIndex).Where(i => i.Value.triangles.SelectMany(i => i).Any(i => beyondVert.Contains(i))).GroupBy(i => i.Key.MaterialSlot).ToList(); - needMerge.Sort((l, r) => l.Key - r.Key); + foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, rectArray, islandArray, islandDescription, domain); } + for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = Mathf.Clamp01(sizePriority[i]); } - var needMergeIslands = needMerge.Select(i => i.ToHashSet()).ToArray(); - var MargeKV = new Dictionary>(); - for (var toIndex = 0; needMergeIslands.Length > toIndex; toIndex += 1) - { - foreach (var island in needMergeIslands[toIndex]) - { - var vertSet = island.Value.triangles.SelectMany(i => i).ToHashSet(); + IAtlasIslandRelocator relocator = atlasSetting.AtlasIslandRelocator != null ? UnityEngine.Object.Instantiate(atlasSetting.AtlasIslandRelocator) : new NFDHPlasFC(); - for (var fromIndex = toIndex; needMergeIslands.Length > fromIndex; fromIndex += 1) - { - if (toIndex == fromIndex) { continue; } + relocator.Padding = atlasSetting.IslandPadding; + var rectTangleMove = relocator.RectTangleMove; + var relocatedRect = rectArray.ToArray(); - var margeFrom = needMergeIslands[fromIndex].Where(il => il.Value.triangles.SelectMany(v => v).Any(v => vertSet.Contains(v))); - if (margeFrom.Any()) { MargeKV.Add(island.Key, margeFrom.Select(i => i.Key).ToHashSet()); } - } - } - } + if (!relocator.Relocation(relocatedRect)) { relocatedRect = RelocateLoop(rectArray, sizePriority, relocator, relocatedRect); } - foreach (var margeIdKV in MargeKV) + IslandRect[] RelocateLoop(IslandRect[] rectArray, float[] sizePriority, IAtlasIslandRelocator relocator, IslandRect[] relocatedRect) + { + if (sizePriority.Any(f => !Mathf.Approximately(1, f))) { - var to = originIslandPool[margeIdKV.Key]; + var priorityMinSize = rectArray.ToArray(); + for (var i = 0; priorityMinSize.Length > i; i += 1) { priorityMinSize[i].Size *= sizePriority[i]; } - foreach (var formKey in margeIdKV.Value) + for (var priLerp = 1f; 0 < priLerp; priLerp -= 0.05f) { - to.triangles.AddRange(originIslandPool[formKey].triangles); - originIslandPool.Remove(formKey); + for (var i = 0; rectArray.Length > i; i += 1) + { + if (relocatedRect[i].Is90Rotation) + { + var size = Vector3.Lerp(priorityMinSize[i].Size, rectArray[i].Size, priLerp); + (size.x, size.y) = (size.y, size.x); + relocatedRect[i].Size = size; + } + else + { + relocatedRect[i].Size = Vector3.Lerp(priorityMinSize[i].Size, rectArray[i].Size, priLerp); + } + } + // Debug.Log("priLerp-" + priLerp); + if (relocator.Relocation(relocatedRect)) { return relocatedRect; } } + relocatedRect = priorityMinSize; } - } - if (containsIdenticalIslandForMultipleSubMesh) { TTTRuntimeLog.Warning("AtlasTexture:error:IdenticalIslandForMultipleSubMesh"); } - - + ScaleApplyDown(Mathf.Sqrt(0.5f / IslandRectUtility.CalculateAllAreaSum(relocatedRect))); + var preRelocated = relocatedRect.ToArray(); - if (atlasSetting.PixelNormalize) - { - foreach (var islandKV in originIslandPool) + var safetyCount = 0; + while (relocator.Relocation(relocatedRect) && safetyCount < 2048)//失敗するかセーフティにかかるまで、失敗したら前回の物を使用する { - var material = materialTextures[atlasReferenceData.GetMaterialReference(islandKV.Key)]; - var refTex = material.FirstOrDefault(i => i.PropertyName == "_MainTex")?.Texture; - if (refTex == null) { continue; } - var island = islandKV.Value; - island.Pivot.y = Mathf.Round(island.Pivot.y * refTex.height) / refTex.height; - island.Pivot.x = Mathf.Round(island.Pivot.x * refTex.width) / refTex.width; + safetyCount += 1; + // Debug.Log("safetyCount-" + safetyCount); + + for (int i = 0; relocatedRect.Length > i; i++) { preRelocated[i] = relocatedRect[i]; } + ScaleApplyUp(1.01f); } - } - var islandSizeOffset = new Dictionary(); - foreach (var material in materialAdditionalTextureOffset.Keys) - { - var tex = material.mainTexture; - float defaultTextureSizeOffset; - if (tex != null) + void ScaleApplyDown(float scaleDownStep) { - var atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; - var texPixelCount = tex.width * tex.height; - defaultTextureSizeOffset = texPixelCount / (float)atlasTexPixelCount; + for (int i = 0; relocatedRect.Length > i; i++) + { + relocatedRect[i].Size *= scaleDownStep; + } } - else { defaultTextureSizeOffset = (float)0.01f; } - - islandSizeOffset[material] = materialAdditionalTextureOffset[material] * Mathf.Sqrt(defaultTextureSizeOffset); - } - - var islandRectPool = new Dictionary(originIslandPool.Count); - foreach (var islandKV in originIslandPool) - { - var atlasIslandId = islandKV.Key; - var islandRect = new IslandRect(islandKV.Value); + void ScaleApplyUp(float scaleUpStep) + { + for (int i = 0; relocatedRect.Length > i; i++) + { + var size = relocatedRect[i].Size *= scaleUpStep; - islandRect.Size *= islandSizeOffset[atlasReferenceData.GetMaterialReference(atlasIslandId)]; - // if (islandRect.Size.x > 0.99) { islandRect.Size *= 0.99f / islandRect.Size.x; }//アルゴリズムのほうがよくなったからこんなことしなくてよくなった - // if (islandRect.Size.y > 0.99) { islandRect.Size *= 0.99f / islandRect.Size.y; } + var maxLength = 0.99f - atlasSetting.IslandPadding - atlasSetting.IslandPadding; + if (size.x > maxLength || size.y > maxLength)//一つ大きいのがあるとすべて使いきれなくなってしまうために、これは必要。 + { + var max = Mathf.Max(size.x, size.y); + size *= maxLength / max; + relocatedRect[i].Size = size; + } + } + } - islandRectPool[atlasIslandId] = islandRect; + return preRelocated; } - // foreach (var offset in islandSizeOffset) { Debug.Log(offset.Key.name + "-" + offset.Value.ToString()); } - IAtlasIslandRelocator relocator = atlasSetting.AtlasIslandRelocator != null ? UnityEngine.Object.Instantiate(atlasSetting.AtlasIslandRelocator) : new NFDHPlasFC(); - - relocator.UseUpScaling = atlasSetting.UseUpScaling; - relocator.Padding = atlasSetting.IslandPadding; - - islandRectPool = relocator.Relocation(islandRectPool, originIslandPool); - var rectTangleMove = relocator.RectTangleMove; if (atlasSetting.PixelNormalize) { - foreach (var key in originIslandPool.Keys) + for (var i = 0; relocatedRect.Length > i; i += 1) { - var island = islandRectPool[key]; + var island = relocatedRect[i]; island.Pivot.y = Mathf.Round(island.Pivot.y * atlasSetting.AtlasTextureSize) / atlasSetting.AtlasTextureSize; island.Pivot.x = Mathf.Round(island.Pivot.x * atlasSetting.AtlasTextureSize) / atlasSetting.AtlasTextureSize; - islandRectPool[key] = island; + relocatedRect[i] = island; } } + //上側を削れるかを見る - var height = IslandRectUtility.CalculateIslandsMaxHeight(islandRectPool.Values); + var height = IslandRectUtility.CalculateIslandsMaxHeight(relocatedRect); var atlasTextureHeightSize = Mathf.Max(GetHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動思想だからクランプ // var areaSum = IslandRectUtility.CalculateAllAreaSum(islandRectPool.Values); // Debug.Log(areaSum + ":AreaSum" + "-" + height + ":height"); - var aspectIslandsRectPool = GetAspectIslandRect(islandRectPool, atlasSetting, atlasTextureHeightSize); + var aspectIslandsRectPool = GetAspectIslandRect(relocatedRect, atlasSetting, atlasTextureHeightSize); //新しいUVを持つMeshを生成するフェーズ var compiledMeshes = new List(); - var poolContainsTags = ToIndexTags(islandRectPool.Keys); - for (int I = 0; I < atlasReferenceData.AtlasMeshDataList.Count; I += 1) + var normMeshes = atlasContext.Meshes.Select(m => atlasContext.NormalizeMeshes[m]).ToArray(); + var subSetMovedUV = new NativeArray[atlasContext.AtlasSubSets.Count]; + for (int subSetIndex = 0; atlasContext.AtlasSubSets.Count > subSetIndex; subSetIndex += 1) { - var atlasMeshData = atlasReferenceData.AtlasMeshDataList[I]; + var subSet = atlasContext.AtlasSubSets[subSetIndex]; + var distMesh = atlasContext.Meshes[subSet.First(i => i.HasValue).Value.MeshID]; + var nmMesh = normMeshes[subSet.First(i => i.HasValue).Value.MeshID]; + var meshData = atlasContext.MeshDataDict[nmMesh]; + var newMesh = UnityEngine.Object.Instantiate(nmMesh); + newMesh.name = "AtlasMesh_" + subSetIndex + "_" + nmMesh.name; + - var distMesh = atlasReferenceData.Meshes[atlasMeshData.ReferenceMesh]; - var newMesh = UnityEngine.Object.Instantiate(distMesh); - newMesh.name = "AtlasMesh_" + I + "_" + distMesh.name; + var originLink = new LinkedList(); + var movedLink = new LinkedList(); - var meshTags = new List(); - for (var slotIndex = 0; atlasMeshData.MaterialIndex.Length > slotIndex; slotIndex += 1) + for (var islandIndex = 0; aspectIslandsRectPool.Length > islandIndex; islandIndex += 1) { - var thisTag = new AtlasIdenticalTag(I, slotIndex); - if (poolContainsTags.Contains(thisTag)) + if (subSet.Any(subData => atlasContext.IslandSubData[islandIndex] == subData)) { - meshTags.Add(thisTag); - } - else - { - var thisTagMeshRef = atlasMeshData.ReferenceMesh; - var thisTagMatSlot = slotIndex; - var thisTagMatRef = atlasMeshData.MaterialIndex[slotIndex]; - AtlasIdenticalTag? identicalTag = FindIdenticalTag(atlasReferenceData, poolContainsTags, thisTagMeshRef, thisTagMatSlot, thisTagMatRef); - - if (identicalTag.HasValue) - { - meshTags.Add(identicalTag.Value); - } + originLink.AddLast(atlasContext.Islands[islandIndex]); + movedLink.AddLast(aspectIslandsRectPool[islandIndex]); } } + // var thisTag = new AtlasSlotRef(amdIndex, slotIndex); + // if (containsSlotRefs.Contains(thisTag)) { foreach (var islandKV in AtlasReferenceData.IslandFind(thisTag, aspectIslandsRectPool)) { movedPool.Add(islandKV.Key, islandKV.Value); } } + // else + // { + // var msmRef = new MSMRef(atlasMeshData.ReferenceMesh, slotIndex, atlasMeshData.MaterialIndex[slotIndex]); + // var identicalTag = atlasReferenceData.FindIdenticalSlotRef(containsSlotRefs, msmRef); + + // if (!identicalTag.HasValue) { continue; } + // foreach (var islandKV in AtlasReferenceData.IslandFind(identicalTag.Value, aspectIslandsRectPool)) { movedPool.Add(islandKV.Key, islandKV.Value); } + // } - var movedPool = new Dictionary(); - foreach (var tag in meshTags) - { - foreach (var islandKVP in aspectIslandsRectPool.Where(i => i.Key.AtlasMeshDataIndex == tag.AtlasMeshDataIndex && i.Key.MaterialSlot == tag.MaterialSlot)) - { - movedPool.Add(islandKVP.Key, islandKVP.Value); - } - } - var movedUV = new List(atlasMeshData.UV); - IslandUtility.IslandPoolMoveUV(atlasMeshData.UV, movedUV, originIslandPool, movedPool); - atlasMeshData.MovedUV = movedUV; + var movedUV = new NativeArray(meshData.VertexUV, Allocator.Temp); + IslandUtility.IslandPoolMoveUV(meshData.VertexUV, movedUV, originLink.ToArray(), movedLink.ToArray()); newMesh.SetUVs(0, movedUV); - if (AtlasSetting.WriteOriginalUV) { newMesh.SetUVs(1, atlasMeshData.UV); } + if (AtlasSetting.WriteOriginalUV) { newMesh.SetUVs(1, meshData.VertexUV); } + subSetMovedUV[subSetIndex] = movedUV; - compiledMeshes.Add(new AtlasData.AtlasMeshAndDist(distMesh, newMesh, atlasMeshData.MaterialIndex.Select(Index => atlasReferenceData.Materials[Index]).ToArray())); + compiledMeshes.Add(new AtlasData.AtlasMeshAndDist(distMesh, newMesh, subSet.Select(i => i?.MaterialID ?? -1).ToArray())); } atlasData.Meshes = compiledMeshes; @@ -351,36 +372,39 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) if (souseProp2Tex == null) continue; var souseTex = souseProp2Tex.Texture is Texture2D ? texManage.GetOriginTempRt(souseProp2Tex.Texture as Texture2D, souseProp2Tex.Texture.width) : souseProp2Tex.Texture; + var findMaterial = MatPropKV.Key; + var findMaterialID = Array.FindIndex(atlasContext.Materials, mh => mh.Contains(findMaterial)); if (rectTangleMove) { - + var findSubDataHash = atlasContext.AtlasSubAll.Where(i => i.MaterialID == findMaterialID).ToHashSet(); var islandPairs = new Dictionary(); - foreach (var islandID in originIslandPool.Keys.Where(tag => atlasReferenceData.GetMaterialReference(tag) == MatPropKV.Key)) + for (var islandIndex = 0; aspectIslandsRectPool.Length > islandIndex; islandIndex += 1) { - var Origin = originIslandPool[islandID]; - if (!islandRectPool.ContainsKey(islandID)) { continue; } - var Moved = islandRectPool[islandID]; - - islandPairs.Add(Origin, Moved); + if (findSubDataHash.Contains(atlasContext.IslandSubData[islandIndex])) + { + islandPairs[atlasContext.Islands[islandIndex]] = aspectIslandsRectPool[islandIndex]; + } } TransMoveRectIsland(souseTex, targetRT, islandPairs, atlasSetting.IslandPadding); - islandPairs.Clear(); } else { - foreach (var atlasAMDGroup in originIslandPool - .Where(atlasIsland => atlasReferenceData.GetMaterialReference(atlasIsland.Key) == MatPropKV.Key) - .GroupBy(atlasIsland => atlasIsland.Key.AtlasMeshDataIndex) - ) + for (var subSetIndex = 0; atlasContext.AtlasSubSets.Count > subSetIndex; subSetIndex += 1) { - var amd = atlasReferenceData.AtlasMeshDataList[atlasAMDGroup.Key]; + var transTargets = atlasContext.AtlasSubSets[subSetIndex].Where(i => i.HasValue).Where(i => i.Value.MaterialID == findMaterialID).Select(i => i.Value); + if (!transTargets.Any()) { continue; } + + var triangles = transTargets.SelectMany(subData => atlasContext.IslandDict[subData].SelectMany(i => i.triangles)); + var originUV = atlasContext.MeshDataDict[atlasContext.NormalizeMeshes[atlasContext.Meshes[transTargets.First().MeshID]]].VertexUV; - var transData = new TransData(atlasAMDGroup.SelectMany(value => value.Value.triangles), amd.MovedUV, amd.UV); + var transData = new TransData(triangles, subSetMovedUV[subSetIndex], originUV); ForTrans(targetRT, souseTex, transData, atlasSetting.GetTexScalePadding * 0.5f, null, true); } } + // UnityEditor.AssetDatabase.CreateAsset(targetRT.CopyTexture2D(), UnityEditor.AssetDatabase.GenerateUniqueAssetPath("Assets/temp.asset")); + if (souseProp2Tex.Texture is Texture2D && souseTex is RenderTexture tempRt) { RenderTexture.ReleaseTemporary(tempRt); } } @@ -407,29 +431,47 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } atlasData.Textures = compiledAtlasTextures; + atlasData.MaterialID = atlasContext.Materials; + atlasContext.Dispose(); + foreach (var movedUV in subSetMovedUV) { movedUV.Dispose(); } return true; } - private static Dictionary GetAspectIslandRect(Dictionary islandRectPool, AtlasSetting atlasSetting, int atlasTextureHeightSize) + private static Dictionary GetTextureSizeOffset(List targetMaterialSelectors, AtlasSetting atlasSetting) { - if (atlasTextureHeightSize != atlasSetting.AtlasTextureSize) + float atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; + var islandSizeOffset = new Dictionary(); + foreach (var material in targetMaterialSelectors) { - var heightSizeScale = atlasSetting.AtlasTextureSize / (float)atlasTextureHeightSize; - var aspectIslands = new Dictionary(); - foreach (var id in islandRectPool.Keys) + var tex = material.mainTexture; + float textureSizeOffset; + if (tex != null) { - var islandRect = islandRectPool[id]; - islandRect.Pivot.y *= heightSizeScale; - islandRect.Size.y *= heightSizeScale; - aspectIslands[id] = islandRect; + textureSizeOffset = tex.width * tex.height / atlasTexPixelCount; } - return aspectIslands; + else { textureSizeOffset = (float)0.01f; } + + islandSizeOffset[material] = Mathf.Sqrt(textureSizeOffset); } - else + + return islandSizeOffset; + } + + private static IslandRect[] GetAspectIslandRect(IslandRect[] islandRectPool, AtlasSetting atlasSetting, int atlasTextureHeightSize) + { + if (atlasTextureHeightSize == atlasSetting.AtlasTextureSize) { return islandRectPool; } + + var heightSizeScale = atlasSetting.AtlasTextureSize / (float)atlasTextureHeightSize; + var aspectIslands = new IslandRect[islandRectPool.Length]; + for (var i = 0; islandRectPool.Length > i; i += 1) { - return islandRectPool; + var islandRect = islandRectPool[i]; + islandRect.Pivot.y *= heightSizeScale; + islandRect.Size.y *= heightSizeScale; + aspectIslands[i] = islandRect; } + return aspectIslands; } private static int GetHeightSize(int atlasTextureSize, float height) @@ -466,8 +508,8 @@ internal override void Apply(IDomain domain = null) foreach (var renderer in nowRenderers) { var mesh = renderer.GetMesh(); - var mats = renderer.sharedMaterials; - var atlasMeshAndDist = atlasData.Meshes.FindAll(I => I.DistMesh == mesh).Find(I => I.Mats.SequenceEqual(mats)); + var matIDs = renderer.sharedMaterials.Select(i => Array.FindIndex(atlasData.MaterialID, mh => mh.Contains(i))); + var atlasMeshAndDist = atlasData.Meshes.FindAll(I => I.DistMesh == mesh).Find(I => I.MatIDs.SequenceEqual(matIDs)); if (atlasMeshAndDist.AtlasMesh == null) { continue; } var atlasMesh = atlasMeshAndDist.AtlasMesh; @@ -504,17 +546,17 @@ internal override void Apply(IDomain domain = null) //MaterialGenerate And Change if (AtlasSetting.MergeMaterials) { - var mergeMat = AtlasSetting.MergeReferenceMaterial != null ? AtlasSetting.MergeReferenceMaterial : atlasData.AtlasInMaterials.First().Material; + var mergeMat = AtlasSetting.MergeReferenceMaterial != null ? AtlasSetting.MergeReferenceMaterial : atlasData.AtlasInMaterials.First(); Material generateMat = GenerateAtlasMat(mergeMat, atlasTexture, shaderSupport, AtlasSetting.ForceSetTexture); - domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x.Material, _ => generateMat), rendererOnly: true); + domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x, _ => generateMat), rendererOnly: true); } else { var materialMap = new Dictionary(); foreach (var MatSelector in atlasData.AtlasInMaterials) { - var distMat = MatSelector.Material; + var distMat = MatSelector; var generateMat = GenerateAtlasMat(distMat, atlasTexture, shaderSupport, AtlasSetting.ForceSetTexture); materialMap.Add(distMat, generateMat); } @@ -553,48 +595,6 @@ private void TransMoveRectIsland(Texture souseTex, RenderTexture ta } internal static float Frac(float v) { return v > 0 ? v - Mathf.Floor(v) : v - Mathf.Ceil(v); } - internal static AtlasIdenticalTag? FindIdenticalTag(AtlasReferenceData atlasData, HashSet poolTags, int findTagMeshRef, int findTagMatSlot, int findTagMatRef) - { - AtlasIdenticalTag? identicalTag = null; - foreach (var pTag in poolTags) - { - var pTagTargetAMD = atlasData.AtlasMeshDataList[pTag.AtlasMeshDataIndex]; - var pTagMeshRef = pTagTargetAMD.ReferenceMesh; - var pTagMatSlot = pTag.MaterialSlot; - var pTagMatRef = pTagTargetAMD.MaterialIndex[pTag.MaterialSlot]; - - if (findTagMeshRef == pTagMeshRef && findTagMatSlot == pTagMatSlot && findTagMatRef == pTagMatRef) - { - identicalTag = pTag; - break; - } - } - - return identicalTag; - } - - private static Dictionary> GetMatDataPool(AtlasReferenceData atlasData, Dictionary originIslandPool, List matDataList) - { - var matDataPairPool = new Dictionary>(); - foreach (var matData in matDataList) - { - var separatePool = atlasData.FindMatIslandPool(originIslandPool, matData.Material, true); - matDataPairPool.Add(matData, separatePool); - } - - return matDataPairPool; - } - - internal static HashSet ToIndexTags(IEnumerable tags) - { - var indexTag = new HashSet(); - foreach (var tag in tags) - { - indexTag.Add(new(tag.AtlasMeshDataIndex, tag.MaterialSlot)); - } - - return indexTag; - } private static Material GenerateAtlasMat(Material targetMat, List atlasTex, AtlasShaderSupportUtils shaderSupport, bool forceSetTexture) { @@ -627,214 +627,4 @@ internal static List FilteredRenderers(GameObject targetRoot, bool inc } } - internal class AtlasReferenceData - { - public OrderedHashSet Meshes; - public HashSet TargetMaterials; - public OrderedHashSet Materials; - public List AtlasMeshDataList; - public List Renderers; - public AtlasReferenceData(List targetMaterials, List inputRenderers) - { - TargetMaterials = new HashSet(targetMaterials); - Meshes = new(); Materials = new(); Renderers = new(); - - foreach (var renderer in inputRenderers) - { - foreach (var mat in renderer.sharedMaterials) - { - if (TargetMaterials.Contains(mat)) - { - Meshes.Add(renderer.GetMesh()); - Materials.AddRange(renderer.sharedMaterials); - Renderers.Add(renderer); - break; - } - } - } - - AtlasMeshDataList = new(); - - foreach (var renderer in Renderers) - { - var mesh = renderer.GetMesh(); - var refMesh = Meshes.IndexOf(mesh); - var materialIndex = renderer.sharedMaterials.Select(Mat => Materials.IndexOf(Mat)).ToArray(); - - var index = AtlasMeshDataList.FindIndex(AMD => AMD.ReferenceMesh == refMesh && AMD.MaterialIndex.SequenceEqual(materialIndex)); - if (index == -1) - { - var uv = new List(); - mesh.GetUVs(0, uv); - - AtlasMeshDataList.Add(new( - refMesh, - mesh.GetSubTriangleIndex(), - uv, - materialIndex - )); - } - } - } - public class AtlasMeshData - { - //RefData - public int ReferenceMesh; - public int[] MaterialIndex; - - //for Generate - public readonly List> Triangles; - public List UV; - public List MovedUV; - - public AtlasMeshData(int referenceMesh, List> triangles, List uv, int[] materialIndex) - { - ReferenceMesh = referenceMesh; - Triangles = triangles; - UV = uv; - MaterialIndex = materialIndex; - } - public AtlasMeshData() - { - Triangles = new List>(); - UV = new List(); - } - } - - - /// - /// すべてをアイランドにし、同一の物を指すアイランドは排除したものを返します。 - /// - /// - /// - public Dictionary GeneratedIslandPool() - { - var islandPool = new Dictionary(); - var amdCount = AtlasMeshDataList.Count; - var islandIndex = 0; - for (int amdIndex = 0; amdIndex < amdCount; amdIndex += 1) - { - var atlasMeshData = AtlasMeshDataList[amdIndex]; - - for (var SlotIndex = 0; atlasMeshData.MaterialIndex.Length > SlotIndex; SlotIndex += 1) - { - if (!TargetMaterials.Contains(Materials[atlasMeshData.MaterialIndex[SlotIndex]])) { continue; } - if (atlasMeshData.Triangles.Count <= SlotIndex) { continue; } - - var islands = IslandUtility.UVtoIsland(atlasMeshData.Triangles[SlotIndex], atlasMeshData.UV); - foreach (var island in islands) { islandPool.Add(new AtlasIslandID(amdIndex, SlotIndex, islandIndex), new AtlasIsland(island, atlasMeshData.UV)); islandIndex += 1; } - } - } - - var refsHash = new HashSet<(int RefMesh, int MatSlot, int RefMat)>(); - var deleteTags = new HashSet(); - foreach (var tag in islandPool.Keys.Select(i => new AtlasIdenticalTag(i.AtlasMeshDataIndex, i.MaterialSlot)).Distinct()) - { - var atlasMeshData = AtlasMeshDataList[tag.AtlasMeshDataIndex]; - var refMesh = atlasMeshData.ReferenceMesh; - var materialSlot = tag.MaterialSlot; - var refMat = atlasMeshData.MaterialIndex[tag.MaterialSlot]; - var refs = (refMesh, materialSlot, refMat); - - if (refsHash.Contains(refs)) { deleteTags.Add(tag); } - else { refsHash.Add(refs); } - } - - var filteredIslandPool = new Dictionary(islandPool.Count); - islandIndex = 0; - foreach (var idPair in islandPool) - { - var atlasID = idPair.Key; - var island = idPair.Value; - - if (deleteTags.Contains(new AtlasIdenticalTag(atlasID.AtlasMeshDataIndex, atlasID.MaterialSlot))) { continue; } - - atlasID.IslandIndex = islandIndex; - filteredIslandPool.Add(atlasID, island); - islandIndex += 1; - } - return filteredIslandPool; - } - - public Material GetMaterialReference(AtlasIslandID indexTag) - { - return GetMaterialReference(indexTag.AtlasMeshDataIndex, indexTag.MaterialSlot); - } - private Material GetMaterialReference(int atlasMeshDataIndex, int materialSlot) - { - return Materials[AtlasMeshDataList[atlasMeshDataIndex].MaterialIndex[materialSlot]]; - } - - - public Dictionary FindMatIslandPool(Dictionary souse, Material matRef, bool deepClone = true) - { - var result = new Dictionary(); - foreach (var islandKVP in souse) - { - if (GetMaterialReference(islandKVP.Key) == matRef) - { - result.Add(islandKVP.Key, deepClone ? new AtlasIsland(islandKVP.Value) : islandKVP.Value); - } - } - return result; - } - } - internal struct AtlasIdenticalTag - { - public int AtlasMeshDataIndex; - public int MaterialSlot; - - public AtlasIdenticalTag(int atlasMeshDataIndex, int materialSlot) - { - AtlasMeshDataIndex = atlasMeshDataIndex; - MaterialSlot = materialSlot; - } - - public static bool operator ==(AtlasIdenticalTag a, AtlasIdenticalTag b) - { - return a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; - } - public static bool operator !=(AtlasIdenticalTag a, AtlasIdenticalTag b) - { - return !(a == b); - } - public override bool Equals(object obj) - { - return obj is AtlasIdenticalTag tag && this == tag; - } - public override int GetHashCode() - { - return AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); - } - } - public struct AtlasIslandID - { - public int AtlasMeshDataIndex; - public int MaterialSlot; - public int IslandIndex; - - public AtlasIslandID(int atlasMeshDataIndex, int materialSlot, int islandIndex) - { - AtlasMeshDataIndex = atlasMeshDataIndex; - MaterialSlot = materialSlot; - IslandIndex = islandIndex; - } - - public static bool operator ==(AtlasIslandID a, AtlasIslandID b) - { - return a.IslandIndex == b.IslandIndex && a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; - } - public static bool operator !=(AtlasIslandID a, AtlasIslandID b) - { - return !(a == b); - } - public override bool Equals(object obj) - { - return obj is AtlasIslandID tag && this == tag; - } - public override int GetHashCode() - { - return IslandIndex.GetHashCode() ^ AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); - } - } } diff --git a/Runtime/TextureAtlas/IslandFineTuner.meta b/Runtime/TextureAtlas/IslandFineTuner.meta new file mode 100644 index 00000000..b1310229 --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9fa02e8cb3eb2094c93d5eb52ddc26ea +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs new file mode 100644 index 00000000..5cc4d89f --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.IslandSelector; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace net.rs64.TexTransTool.TextureAtlas.IslandFineTuner +{ + internal interface IIslandFineTuner + { + //islands と islandDescriptions は書き込みしないように、 + //sizePriority と islandRect を操作して調整していく感じ + void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); + } +} diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs.meta b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs.meta new file mode 100644 index 00000000..1dc49197 --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 860f584b361a0774abaeb8e244e928b1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs new file mode 100644 index 00000000..8eab4966 --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.IslandSelector; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace net.rs64.TexTransTool.TextureAtlas.IslandFineTuner +{ + [Serializable] + internal class SizeOffset : IIslandFineTuner + { + [Range(0, 1)] public float OffsetValue = 1f; + public AbstractIslandSelector IslandSelector; + + public void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + { + var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); + + for (var i = 0; islandRect.Length > i; i += 1) + { + if (!targetBit[i]) { continue; } + islandRect[i].Size *= OffsetValue; + } + } + + } +} diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta new file mode 100644 index 00000000..d4381837 --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 691a91d21c4eea246a83c86d17ffa18b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs new file mode 100644 index 00000000..50afc726 --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.IslandSelector; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace net.rs64.TexTransTool.TextureAtlas.IslandFineTuner +{ + [Serializable] + internal class SizePriority : IIslandFineTuner + { + [Range(0, 1)] public float PriorityValue = 1f; + public AbstractIslandSelector IslandSelector; + + public void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + { + var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); + + for (var i = 0; islandRect.Length > i; i += 1) + { + if (!targetBit[i]) { continue; } + sizePriority[i] = PriorityValue; + } + } + + } +} diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs.meta b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs.meta new file mode 100644 index 00000000..5430097a --- /dev/null +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d8d1d725a619234b8c3eae79728652f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs b/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs index 6266567d..1a0893cc 100644 --- a/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs +++ b/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs @@ -23,11 +23,9 @@ namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator public abstract class AtlasIslandRelocatorObject : ScriptableObject, IAtlasIslandRelocator { public abstract bool RectTangleMove { get; } - protected bool UseUpScaling { get; private set; } protected float Padding { get; private set; } - bool IAtlasIslandRelocator.UseUpScaling { set => UseUpScaling = value; } float IAtlasIslandRelocator.Padding { set => Padding = value; } - public abstract Dictionary Relocation(Dictionary atlasIslands, IReadOnlyDictionary atlasIslandReference); + public abstract bool Relocation(IslandRect[] atlasIslands); } diff --git a/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs b/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs index b17c9ce9..8df1cd8b 100644 --- a/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs +++ b/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs @@ -9,11 +9,8 @@ namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator public interface IAtlasIslandRelocator { bool RectTangleMove { get; } - - bool UseUpScaling { set; } float Padding { set; } - - Dictionary Relocation(Dictionary atlasIslands, IReadOnlyDictionary atlasIslandReference); + bool Relocation(IslandRect[] atlasIslands); } diff --git a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs index 53fc2534..3c830a71 100644 --- a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs +++ b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs @@ -10,45 +10,28 @@ namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator internal class NFDHPlasFC : IAtlasIslandRelocator { public bool RectTangleMove => true; - - public bool UseUpScaling { set => _useUpScaling = value; } public float Padding { set => _padding = value; } - public bool _useUpScaling; public float _padding; - public Dictionary Relocation(Dictionary atlasIslands, IReadOnlyDictionary atlasIslandReference) + public bool Relocation(IslandRect[] atlasIslands) { - IslandPoolNextFitDecreasingHeightPlusFloorCeiling(atlasIslands, _useUpScaling, _padding); - return atlasIslands; + return IslandPoolNextFitDecreasingHeightPlusFloorCeiling(atlasIslands, _padding); } - public static Dictionary IslandPoolNextFitDecreasingHeightPlusFloorCeiling(Dictionary islands, bool useUpScaling = true, float islandPadding = 0.01f, float scaleStep = 0.99f, int safetyCount = 512) + public static bool IslandPoolNextFitDecreasingHeightPlusFloorCeiling(IslandRect[] islands, float islandPadding = 0.01f) { - if (!islands.Any()) return islands; + if (islands.Length == 0) { return false; } - var idList = islands.Keys.ToList(); + var idList = Enumerable.Range(0, islands.Length).ToList(); foreach (var id in idList) { if (islands[id].Size.y > islands[id].Size.x) { var island = islands[id]; island.Rotate90(); islands[id] = island; } } idList.Sort((lId, rId) => Mathf.RoundToInt((islands[rId].Size.y - islands[lId].Size.y) * 1073741824)); var sortedIslandArray = idList.Select(i => islands[i]).ToArray(); - ValidateDeceasing(sortedIslandArray); - if (TryNFDHPlasFC(sortedIslandArray, islandPadding) && !useUpScaling) { ApplyDictionary(); return islands; } - - ScaleApply(Mathf.Sqrt(1 / IslandRectUtility.CalculateAllAreaSum(islands.Values))); - - var stepCount = 0; - while (!TryNFDHPlasFC(sortedIslandArray, islandPadding) && safetyCount > stepCount) { ScaleApply(scaleStep); stepCount += 1; } - if (stepCount == safetyCount) { TTTRuntimeLog.Warning("NextFitDecreasingHeightPlusFloorCeiling : Safetyによりループが中断された可能性があり、アイランドの再配置が正常に行われていない可能性があります"); } - - ApplyDictionary(); - return islands; - - void ScaleApply(float scale) - { - for (var i = 0; sortedIslandArray.Length > i; i += 1) { sortedIslandArray[i].Size *= scale; } - } + var res = TryNFDHPlasFC(sortedIslandArray, islandPadding); + if (res) { ApplyDictionary(); } + return res; void ApplyDictionary() { for (var i = 0; sortedIslandArray.Length > i; i += 1) { islands[idList[i]] = sortedIslandArray[i]; } @@ -73,7 +56,7 @@ internal static bool ValidateDeceasing(IslandRect[] rectArray) static bool TryNFDHPlasFC(IslandRect[] sortedIslands, float islandPadding = 0.01f) { - var uvWidthBox = new List>(); + var uvWidthBox = new List>(32); for (var i = 0; sortedIslands.Length > i; i += 1) { diff --git a/TexTransCore/Decal/MeshData.cs b/TexTransCore/Decal/MeshData.cs index 708ce2e8..ad2e797b 100644 --- a/TexTransCore/Decal/MeshData.cs +++ b/TexTransCore/Decal/MeshData.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore.TransTextureCore.Utils; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; @@ -92,12 +93,12 @@ public void Dispose() } _combinedTriangles.Dispose(); _combinedTriangleIndex.Dispose(); + _combinedTriangleToSubmeshIndexAndOffset.Dispose(); } - internal MeshData(Renderer renderer) + internal MeshData(Renderer renderer, Mesh mesh, Matrix4x4 worldSpaceTransform) { ReferenceRenderer = renderer; - (Mesh mesh, Matrix4x4 worldSpaceTransform) = GetMeshAndMatrix(renderer); var meshDataArray = Mesh.AcquireReadOnlyMeshData(mesh); @@ -172,8 +173,8 @@ internal MeshData(Renderer renderer) meshDataArray.Dispose(); } - - (Mesh, Matrix4x4) GetMeshAndMatrix(Renderer target) + internal MeshData(Renderer renderer) : this(renderer, GetMesh(renderer), GetMatrix(renderer)) { } + internal static Mesh GetMesh(Renderer target) { switch (target) { @@ -181,7 +182,24 @@ internal MeshData(Renderer renderer) { Mesh mesh = new Mesh(); smr.BakeMesh(mesh); - + return mesh; + } + case MeshRenderer mr: + { + return mr.GetComponent().sharedMesh; + } + default: + { + throw new System.ArgumentException("Rendererが対応したタイプではないか、TargetRendererが存在しません。"); + } + } + } + internal static Matrix4x4 GetMatrix(Renderer target) + { + switch (target) + { + case SkinnedMeshRenderer smr: + { Matrix4x4 matrix; if (smr.bones.Any()) { @@ -196,11 +214,11 @@ internal MeshData(Renderer renderer) matrix = smr.rootBone.localToWorldMatrix; } - return (mesh, matrix); + return matrix; } case MeshRenderer mr: { - return (mr.GetComponent().sharedMesh, mr.localToWorldMatrix); + return mr.localToWorldMatrix; } default: { @@ -235,7 +253,7 @@ public void Execute(int index) dstSubmeshIndexAndOffset[index] = (submeshIndex, submeshOffset); } } - + [BurstCompile] struct InitTriangleJob : IJobParallelFor { @@ -258,7 +276,7 @@ public void Execute(int index) TrianglePosBuffer[index] = triangle; } } - + [BurstCompile] struct WorldSpaceTransformJob : IJobParallelFor { diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index bec05328..c7dd991e 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -7,6 +7,8 @@ using net.rs64.TexTransTool.Utils; using UnityEngine.Pool; using UnityEngine.Profiling; +using Unity.Collections; +using System.Linq; namespace net.rs64.TexTransCore.Island { @@ -21,14 +23,14 @@ internal static class IslandUtility internal struct VertNode { public int parentIndex; - + public (Vector2, Vector2) boundingBox; - + public int depth; public int triCount; public Island island; - + public VertNode(int i, Vector2 uv) { parentIndex = i; @@ -47,7 +49,7 @@ public VertNode(int i, Vector2 uv) public static int Find(VertNode[] arr, int index) { if (arr[index].parentIndex == index) return index; - + return arr[index].parentIndex = Find(arr, arr[index].parentIndex); } @@ -63,15 +65,15 @@ public static void Merge(VertNode[] arr, int a, int b) b = Find(arr, b); if (a == b) return; - + if (arr[a].depth < arr[b].depth) { (a, b) = (b, a); } - + if (arr[a].depth == arr[b].depth) arr[a].depth++; arr[b].parentIndex = a; - + arr[a].boundingBox = (Vector2.Min(arr[a].boundingBox.Item1, arr[b].boundingBox.Item1), Vector2.Max(arr[a].boundingBox.Item2, arr[b].boundingBox.Item2)); arr[a].triCount += arr[b].triCount; @@ -88,10 +90,10 @@ public void AddTriangle(TriangleIndex idx, List islandList) { islandList.Add(island = new Island()); island.triangles.Capacity = triCount; - + var min = boundingBox.Item1; var max = boundingBox.Item2; - + island.Size = new Vector2(max.x - min.x, max.y - min.y); island.Pivot = min; } @@ -109,7 +111,7 @@ public static List UVtoIsland(IList triIndexes, IList UVToIslandImpl(IList triIndexes, ILis uvVert = uvToIndex[uv] = uniqueUv++; indexToUv.Add(uv); } - + inputVertToUniqueIndex.Add(uvVert); } Profiler.EndSample(); - + VertNode[] nodes = new VertNode[uniqueUv]; // Union-Find用のデータストラクチャーを初期化 @@ -151,18 +153,18 @@ private static List UVToIslandImpl(IList triIndexes, ILis int idx_a = inputVertToUniqueIndex[tri.zero]; int idx_b = inputVertToUniqueIndex[tri.one]; int idx_c = inputVertToUniqueIndex[tri.two]; - + // 三角面に該当するノードを併合 VertNode.Merge(nodes, idx_a, idx_b); VertNode.Merge(nodes, idx_b, idx_c); - + // 際アロケーションを避けるために三角面を数える nodes[VertNode.Find(nodes, idx_a)].triCount++; } Profiler.EndSample(); - + var islands = new List(); - + // この時点で代表が決まっているので、三角を追加していきます。 Profiler.BeginSample("Add triangles to islands"); foreach (var tri in triIndexes) @@ -175,19 +177,17 @@ private static List UVToIslandImpl(IList triIndexes, ILis return islands; } - public static void IslandMoveUV(List uv, List moveUV, Island originIsland, TIsland movedIsland, bool keepIslandUVTile = false) where TIsland : IIslandRect + public static void IslandMoveUV(NativeArray uv, NativeArray moveUV, Island originIsland, TIsland movedIsland, bool keepIslandUVTile = false) where TIsland : IIslandRect { if (originIsland.Is90Rotation) { throw new ArgumentException("originIsland.Is90Rotation is true"); } - var tempList = ListPool.Get(); var rotate = Quaternion.Euler(0, 0, -90); - var mSize = movedIsland.Is90Rotation ? new(movedIsland.Size.y, movedIsland.Size.x) : movedIsland.Size; var nmSize = originIsland.Size; var relativeScale = new Vector2(mSize.x / nmSize.x, mSize.y / nmSize.y).NaNtoZero(); - foreach (var vertIndex in originIsland.GetVertexIndex(tempList)) + foreach (var vertIndex in originIsland.GetVertexIndex()) { var relativeVertPos = uv[vertIndex] - originIsland.Pivot; @@ -200,8 +200,6 @@ public static void IslandMoveUV(List uv, List moveUV, if (keepIslandUVTile) { movedPos.x += Mathf.Floor(originIsland.Pivot.x); movedPos.y += Mathf.Floor(originIsland.Pivot.y); } moveUV[vertIndex] = movedPos; } - - ListPool.Release(tempList); } private static Vector2 NaNtoZero(this Vector2 relativeScale) @@ -211,16 +209,13 @@ private static Vector2 NaNtoZero(this Vector2 relativeScale) return relativeScale; } - public static void IslandPoolMoveUV(List uv, List moveUV, Dictionary originPool, Dictionary movedPool) + public static void IslandPoolMoveUV(NativeArray uv, NativeArray moveUV, TIsland[] originPool, TIslandRect[] movedPool) where TIsland : Island where TIslandRect : IIslandRect { - if (uv.Count != moveUV.Count) throw new ArgumentException("UV.Count != MoveUV.Count 中身が同一頂点数のUVではありません。"); - foreach (var islandKVP in movedPool) - { - var originIsland = originPool[islandKVP.Key]; - IslandMoveUV(uv, moveUV, originIsland, islandKVP.Value, true); - } + if (uv.Length != moveUV.Length) throw new ArgumentException("中身が同一頂点数のUVではありません。"); + if (originPool.Length != movedPool.Length) throw new ArgumentException("Islandが同じ数ではありません。"); + for (var i = 0; originPool.Length > i; i += 1) { IslandMoveUV(uv, moveUV, originPool[i], movedPool[i], true); } } } @@ -258,7 +253,16 @@ public Island(List trianglesOfIsland) { triangles = trianglesOfIsland; } - + public IEnumerable GetVertexIndex() + { + foreach (var triangle in triangles) + { + for (var i = 0; 3 > i; i += 1) + { + yield return triangle[i]; + } + } + } public List GetVertexIndex(List output = null) { output?.Clear(); output ??= new(); @@ -271,7 +275,7 @@ public List GetVertexIndex(List output = null) public List GetVertexPos(IReadOnlyList souseUV) { var vertIndexes = GetVertexIndex(); - return vertIndexes.ConvertAll(i => souseUV[i]); + return vertIndexes.Select(i => souseUV[i]).ToList(); } public void BoxCalculation(IReadOnlyList souseUV) { From 0f58da4b498ed0669fa4cc90faabe816dac4651b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 24 Mar 2024 00:14:42 +0900 Subject: [PATCH 025/208] chore: remove AtlasReferenceData --- Runtime/TextureAtlas/AtlasReferenceData.cs | 347 ------------------ .../TextureAtlas/AtlasReferenceData.cs.meta | 11 - 2 files changed, 358 deletions(-) delete mode 100644 Runtime/TextureAtlas/AtlasReferenceData.cs delete mode 100644 Runtime/TextureAtlas/AtlasReferenceData.cs.meta diff --git a/Runtime/TextureAtlas/AtlasReferenceData.cs b/Runtime/TextureAtlas/AtlasReferenceData.cs deleted file mode 100644 index 165fb13c..00000000 --- a/Runtime/TextureAtlas/AtlasReferenceData.cs +++ /dev/null @@ -1,347 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using System.Linq; -using System; -using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.Island; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransCore.Decal; - -namespace net.rs64.TexTransTool.TextureAtlas -{ - internal class AtlasReferenceData : IDisposable - { - public OrderedHashSet Meshes; - public HashSet TargetMaterials; - public OrderedHashSet Materials; - public List AtlasMeshDataList; - public AtlasReferenceData(List targetMaterials, List inputRenderers) - { - TargetMaterials = new HashSet(targetMaterials); - Meshes = new(); Materials = new(); - var Renderers = new List(); - - foreach (var renderer in inputRenderers) - { - foreach (var mat in renderer.sharedMaterials) - { - if (TargetMaterials.Contains(mat)) - { - Meshes.Add(renderer.GetMesh()); - Materials.AddRange(renderer.sharedMaterials); - Renderers.Add(renderer); - break; - } - } - } - - AtlasMeshDataList = new(); - - foreach (var renderer in Renderers) - { - var mesh = renderer.GetMesh(); - var refMesh = Meshes.IndexOf(mesh); - var materialIndex = renderer.sharedMaterials.Select(Mat => Materials.IndexOf(Mat)).ToArray(); - int index = GetAtlasMeshDataIndex(refMesh, materialIndex); - if (index == -1) - { - var uv = new List(); - mesh.GetUVs(0, uv); - - AtlasMeshDataList.Add(new( - refMesh, - mesh.GetSubTriangleIndex(), - uv, - materialIndex, - renderer - )); - } - } - } - - - - internal int GetAtlasMeshDataIndex(int refMesh, int[] materialIndex) - { - return AtlasMeshDataList.FindIndex(AMD => AMD.ReferenceMesh == refMesh && AMD.MaterialIndex.SequenceEqual(materialIndex)); - } - - public class AtlasMeshData - { - //RefData - public int ReferenceMesh; - public int[] MaterialIndex; - - //for Generate - public readonly List> Triangles; - public List UV; - public List MovedUV; - public Renderer Renderer; - public MeshData MeshData; - - public AtlasMeshData(int referenceMesh, List> triangles, List uv, int[] materialIndex, Renderer renderer) - { - ReferenceMesh = referenceMesh; - Triangles = triangles; - UV = uv; - MaterialIndex = materialIndex; - Renderer = renderer; - MeshData = new MeshData(renderer); - } - public AtlasMeshData() - { - Triangles = new List>(); - UV = new List(); - } - } - - - /// - /// すべてをアイランドにし、同一の物を指すアイランドは排除したものを返します。 - /// - /// - /// - public Dictionary GeneratedIslandPool() - { - var islandPool = new Dictionary(); - var amdCount = AtlasMeshDataList.Count; - var islandIndex = 0; - for (int amdIndex = 0; amdIndex < amdCount; amdIndex += 1) - { - var atlasMeshData = AtlasMeshDataList[amdIndex]; - - for (var SlotIndex = 0; atlasMeshData.MaterialIndex.Length > SlotIndex; SlotIndex += 1) - { - if (!TargetMaterials.Contains(Materials[atlasMeshData.MaterialIndex[SlotIndex]])) { continue; } - if (atlasMeshData.Triangles.Count <= SlotIndex) { continue; } - - var islands = IslandUtility.UVtoIsland(atlasMeshData.Triangles[SlotIndex], atlasMeshData.UV); - foreach (var island in islands) { islandPool.Add(new AtlasIslandID(amdIndex, SlotIndex, islandIndex), island); islandIndex += 1; } - } - } - - var refsHash = new HashSet(); - var deleteTags = new HashSet(); - foreach (var tag in islandPool.Keys.Select(i => new AtlasSlotRef(i.AtlasMeshDataIndex, i.MaterialSlot)).Distinct()) - { - var atlasMeshData = AtlasMeshDataList[tag.AtlasMeshDataIndex]; - - var refMesh = atlasMeshData.ReferenceMesh; - var materialSlot = tag.MaterialSlot; - var refMat = atlasMeshData.MaterialIndex[tag.MaterialSlot]; - - var refs = new MSMRef(refMesh, materialSlot, refMat); - - if (refsHash.Contains(refs)) { deleteTags.Add(tag); } - else { refsHash.Add(refs); } - } - - var filteredIslandPool = new Dictionary(islandPool.Count); - islandIndex = 0; - foreach (var idPair in islandPool) - { - var atlasID = idPair.Key; - var island = idPair.Value; - - if (deleteTags.Contains(new AtlasSlotRef(atlasID.AtlasMeshDataIndex, atlasID.MaterialSlot))) { continue; } - - atlasID.IslandIndex = islandIndex; - filteredIslandPool.Add(atlasID, island); - islandIndex += 1; - } - - - //サブメッシュ間で頂点を共有するアイランドのマージ - var containsIdenticalIslandForMultipleSubMesh = false; - for (var amdIndex = 0; AtlasMeshDataList.Count > amdIndex; amdIndex += 1) - { - var amd = AtlasMeshDataList[amdIndex]; - - var beyondVert = amd.Triangles.Where(i => TargetMaterials.Contains(Materials[amd.MaterialIndex[amd.Triangles.IndexOf(i)]])) - .Select(i => new HashSet(i.SelectMany(i2 => i2))).SelectMany(i => i) - .GroupBy(i => i).Select(i => (i.Key, i.Count())).Where(i => i.Item2 > 1).Select(i => i.Key).ToHashSet(); - - if (beyondVert.Any()) { containsIdenticalIslandForMultipleSubMesh = true; } - else { continue; } - - var needMerge = filteredIslandPool.Where(i => i.Key.AtlasMeshDataIndex == amdIndex).Where(i => i.Value.triangles.SelectMany(i => i).Any(i => beyondVert.Contains(i))).GroupBy(i => i.Key.MaterialSlot).ToList(); - needMerge.Sort((l, r) => l.Key - r.Key); - - var needMergeIslands = needMerge.Select(i => i.ToHashSet()).ToArray(); - var MargeKV = new Dictionary>(); - - for (var toIndex = 0; needMergeIslands.Length > toIndex; toIndex += 1) - { - foreach (var island in needMergeIslands[toIndex]) - { - var vertSet = island.Value.triangles.SelectMany(i => i).ToHashSet(); - - for (var fromIndex = toIndex; needMergeIslands.Length > fromIndex; fromIndex += 1) - { - if (toIndex == fromIndex) { continue; } - - var margeFrom = needMergeIslands[fromIndex].Where(il => il.Value.triangles.SelectMany(v => v).Any(v => vertSet.Contains(v))); - if (margeFrom.Any()) { MargeKV.Add(island.Key, margeFrom.Select(i => i.Key).ToHashSet()); } - } - } - } - - foreach (var margeIdKV in MargeKV) - { - var to = filteredIslandPool[margeIdKV.Key]; - - foreach (var formKey in margeIdKV.Value) - { - to.triangles.AddRange(filteredIslandPool[formKey].triangles); - filteredIslandPool.Remove(formKey); - } - } - - } - if (containsIdenticalIslandForMultipleSubMesh) { TTTRuntimeLog.Warning("AtlasTexture:error:IdenticalIslandForMultipleSubMesh"); } - - - - - - - - - return filteredIslandPool; - } - - public Material GetMaterialReference(AtlasIslandID indexTag) - { - return GetMaterialReference(indexTag.AtlasMeshDataIndex, indexTag.MaterialSlot); - } - private Material GetMaterialReference(int atlasMeshDataIndex, int materialSlot) - { - return Materials[AtlasMeshDataList[atlasMeshDataIndex].MaterialIndex[materialSlot]]; - } - internal AtlasSlotRef? FindIdenticalSlotRef(HashSet slotRefs, MSMRef findTarget) - { - foreach (var tag in slotRefs) - { - var tagAmd = AtlasMeshDataList[tag.AtlasMeshDataIndex]; - - if (findTarget.RefMesh != tagAmd.ReferenceMesh) { continue; } - if (findTarget.RefMatSlot != tag.MaterialSlot) { continue; } - if (findTarget.RefMat != tagAmd.MaterialIndex[tag.MaterialSlot]) { continue; } - - return tag; - } - - return null; - } - - internal static IEnumerable> IslandFind(AtlasSlotRef atlasIdenticalTag, Dictionary islandRect) - { - foreach (var islandKV in islandRect) - { - if (islandKV.Key.AtlasMeshDataIndex != atlasIdenticalTag.AtlasMeshDataIndex) { continue; } - if (islandKV.Key.MaterialSlot != atlasIdenticalTag.MaterialSlot) { continue; } - - yield return islandKV; - } - } - - public void Dispose() - { - foreach (var amd in AtlasMeshDataList) { amd.MeshData.Dispose(); } - } - } - - internal struct MSMRef - { - public int RefMesh; - public int RefMatSlot; - public int RefMat; - - public MSMRef(int refMesh, int matSlot, int refMat) - { - RefMesh = refMesh; - RefMatSlot = matSlot; - RefMat = refMat; - } - - public override bool Equals(object obj) - { - return obj is MSMRef other && - RefMesh == other.RefMesh && - RefMatSlot == other.RefMatSlot && - RefMat == other.RefMat; - } - - public override int GetHashCode() - { - return HashCode.Combine(RefMesh, RefMatSlot, RefMat); - } - } - internal struct AtlasSlotRef - { - public int AtlasMeshDataIndex; - public int MaterialSlot; - - public AtlasSlotRef(int atlasMeshDataIndex, int materialSlot) - { - AtlasMeshDataIndex = atlasMeshDataIndex; - MaterialSlot = materialSlot; - } - - public static bool operator ==(AtlasSlotRef a, AtlasSlotRef b) - { - return a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; - } - public static bool operator !=(AtlasSlotRef a, AtlasSlotRef b) - { - return !(a == b); - } - public override bool Equals(object obj) - { - return obj is AtlasSlotRef tag && this == tag; - } - public override int GetHashCode() - { - return AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); - } - internal static HashSet ToSlotRefHash(IEnumerable tags) - { - var indexTag = new HashSet(); - foreach (var tag in tags) { indexTag.Add(new(tag.AtlasMeshDataIndex, tag.MaterialSlot)); } - return indexTag; - } - - - } - public struct AtlasIslandID - { - public int AtlasMeshDataIndex; - public int MaterialSlot; - public int IslandIndex; - - public AtlasIslandID(int atlasMeshDataIndex, int materialSlot, int islandIndex) - { - AtlasMeshDataIndex = atlasMeshDataIndex; - MaterialSlot = materialSlot; - IslandIndex = islandIndex; - } - - public static bool operator ==(AtlasIslandID a, AtlasIslandID b) - { - return a.IslandIndex == b.IslandIndex && a.AtlasMeshDataIndex == b.AtlasMeshDataIndex && a.MaterialSlot == b.MaterialSlot; - } - public static bool operator !=(AtlasIslandID a, AtlasIslandID b) - { - return !(a == b); - } - public override bool Equals(object obj) - { - return obj is AtlasIslandID tag && this == tag; - } - public override int GetHashCode() - { - return IslandIndex.GetHashCode() ^ AtlasMeshDataIndex.GetHashCode() ^ MaterialSlot.GetHashCode(); - } - } -} diff --git a/Runtime/TextureAtlas/AtlasReferenceData.cs.meta b/Runtime/TextureAtlas/AtlasReferenceData.cs.meta deleted file mode 100644 index 98d76a93..00000000 --- a/Runtime/TextureAtlas/AtlasReferenceData.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9e9efdf5f6249fb46a68da00e3197edd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From c2fd0d6a3c87e29e850feb2d050b3278d252bb3c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 24 Mar 2024 00:15:39 +0900 Subject: [PATCH 026/208] fix: zero size island --- Runtime/TextureAtlas/AtlasTexture.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 6837c533..b25597f5 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -292,7 +292,11 @@ void ScaleApplyUp(float scaleUpStep) relocatedRect[i] = island; } } - + for (var i = 0; relocatedRect.Length > i; i += 1) + { + if (relocatedRect[i].Size.x <= 0.0001f) { relocatedRect[i].Size.x = 0.0001f; } + if (relocatedRect[i].Size.y <= 0.0001f) { relocatedRect[i].Size.y = 0.0001f; } + }//Islandが小さすぎると RectTangleMoveのコピーがうまくいかない //上側を削れるかを見る var height = IslandRectUtility.CalculateIslandsMaxHeight(relocatedRect); From 246d3bafcf16ed9cf42f01680037e7cca1d92f2a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 24 Mar 2024 00:16:25 +0900 Subject: [PATCH 027/208] chore: restore height clamp --- Runtime/TextureAtlas/AtlasTexture.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index b25597f5..ed1ea3d9 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -142,7 +142,7 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) foreach (var mat in targetMaterials) { materialTextures[mat] = shaderSupports.GetTextures(mat, texManage); } shaderSupports.ClearRecord(); - var islandSizeOffset = GetTextureSizeOffset(targetMaterials, atlasSetting); + var islandSizeOffset = GetTextureSizeOffset(SelectMatList.Select(i => i.Material), atlasSetting); //アイランドまわり if (atlasSetting.PixelNormalize) @@ -300,7 +300,7 @@ void ScaleApplyUp(float scaleUpStep) //上側を削れるかを見る var height = IslandRectUtility.CalculateIslandsMaxHeight(relocatedRect); - var atlasTextureHeightSize = Mathf.Max(GetHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動思想だからクランプ + var atlasTextureHeightSize = Mathf.Max(GetHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動しそうだからクランプ // var areaSum = IslandRectUtility.CalculateAllAreaSum(islandRectPool.Values); // Debug.Log(areaSum + ":AreaSum" + "-" + height + ":height"); @@ -382,11 +382,11 @@ void ScaleApplyUp(float scaleUpStep) { var findSubDataHash = atlasContext.AtlasSubAll.Where(i => i.MaterialID == findMaterialID).ToHashSet(); var islandPairs = new Dictionary(); - for (var islandIndex = 0; aspectIslandsRectPool.Length > islandIndex; islandIndex += 1) + for (var islandIndex = 0; relocatedRect.Length > islandIndex; islandIndex += 1) { if (findSubDataHash.Contains(atlasContext.IslandSubData[islandIndex])) { - islandPairs[atlasContext.Islands[islandIndex]] = aspectIslandsRectPool[islandIndex]; + islandPairs[atlasContext.Islands[islandIndex]] = relocatedRect[islandIndex]; } } @@ -442,7 +442,7 @@ void ScaleApplyUp(float scaleUpStep) return true; } - private static Dictionary GetTextureSizeOffset(List targetMaterialSelectors, AtlasSetting atlasSetting) + private static Dictionary GetTextureSizeOffset(IEnumerable targetMaterialSelectors, AtlasSetting atlasSetting) { float atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; var islandSizeOffset = new Dictionary(); From 2603a99f185fdf7e4a359f8768985dce2834a6b9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 24 Mar 2024 00:42:22 +0900 Subject: [PATCH 028/208] fix: write of BlendShapes --- Runtime/TextureAtlas/AAOCode/MeshUtility.cs | 2 ++ Runtime/TextureAtlas/AAOCode/MultiDimensionalNativeArray.cs | 1 + Runtime/TextureAtlas/AAOCode/Vertex.cs | 1 + 3 files changed, 4 insertions(+) diff --git a/Runtime/TextureAtlas/AAOCode/MeshUtility.cs b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs index 061cdb9a..f8b95b4c 100644 --- a/Runtime/TextureAtlas/AAOCode/MeshUtility.cs +++ b/Runtime/TextureAtlas/AAOCode/MeshUtility.cs @@ -11,6 +11,7 @@ namespace net.rs64.TexTransTool.TextureAtlas.AAOCode { //これは MeshInfo2 を改造して簡易的に使えるようにしたもの + //https://github.com/anatawa12/AvatarOptimizer/blob/afcc0cecdf91d3de24fc5e7358d3b497c2b64098/Internal/MeshInfo2/MeshInfo2.cs internal static class MeshInfoUtility { public static List ReadVertex(Mesh mesh, out MeshDesc meshDesc) @@ -324,6 +325,7 @@ public static void WriteVertex(Mesh destMesh, MeshDesc meshAttribute, List : IDisposable where T : unmanaged { diff --git a/Runtime/TextureAtlas/AAOCode/Vertex.cs b/Runtime/TextureAtlas/AAOCode/Vertex.cs index 98dee5d0..37af61ea 100644 --- a/Runtime/TextureAtlas/AAOCode/Vertex.cs +++ b/Runtime/TextureAtlas/AAOCode/Vertex.cs @@ -5,6 +5,7 @@ namespace net.rs64.TexTransTool.TextureAtlas.AAOCode { + //https://github.com/anatawa12/AvatarOptimizer/blob/afcc0cecdf91d3de24fc5e7358d3b497c2b64098/Internal/MeshInfo2/MeshInfo2.cs#L791-L1032 internal class Vertex { public Vector3 Position { get; set; } From 5dd565d996a2e35845179148f64e78ad0b283087 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 24 Mar 2024 21:43:04 +0900 Subject: [PATCH 029/208] feat: AtlasShaderSupportScriptableObject --- .../TextureAtlas/AtlasScriptableObject.meta | 8 +++ ...tlasShaderSupportScriptableObjectEditor.cs | 45 +++++++++++++++ ...haderSupportScriptableObjectEditor.cs.meta | 11 ++++ .../AtlasScriptableObject.meta | 8 +++ .../AtlasShaderSupportScriptableObject.cs | 24 ++++++++ ...AtlasShaderSupportScriptableObject.cs.meta | 11 ++++ .../AtlasTargetDefine.cs | 57 +++++++++++++++++++ .../AtlasTargetDefine.cs.meta | 11 ++++ .../IAtlasMaterialPostProses.cs | 16 ++++++ .../IAtlasMaterialPostProses.cs.meta | 11 ++++ .../ISupportedShaderComparer.cs | 22 +++++++ .../ISupportedShaderComparer.cs.meta | 11 ++++ .../AtlasShaderSupport/IAtlasShaderSupport.cs | 1 - 13 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject.meta create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs.meta diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject.meta b/Editor/Inspector/TextureAtlas/AtlasScriptableObject.meta new file mode 100644 index 00000000..f5a5c3f8 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9fd9f64a60f3d9741b513de672a70a42 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs new file mode 100644 index 00000000..d4d68451 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs @@ -0,0 +1,45 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; +using net.rs64.TexTransTool.Editor; +using System; +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + + [CustomEditor(typeof(AtlasShaderSupportScriptableObject))] + public class AtlasShaderSupportScriptableObjectEditor : UnityEditor.Editor + { + string[] comparers = new[] { "ContainsName", "ShaderReference" }; + Func[] comparerGet = new Func[] { () => new ContainsName(), () => new ShaderReference() }; + + string[] protProses = new[] { "TextureReferenceCopy" }; + Func[] protProsesGet = new Func[] { () => new TextureReferenceCopy() }; + public override void OnInspectorGUI() + { + serializedObject.Update(); + TextureTransformerEditor.DrawerWarning("AtlasShaderSupportScriptableObject"); + + var sSupportedShaderComparer = serializedObject.FindProperty("SupportedShaderComparer"); + var reSelect = EditorGUILayout.Popup("Comparer Re Select", -1, comparers); + if (reSelect != -1) { sSupportedShaderComparer.managedReferenceValue = comparerGet[reSelect].Invoke(); } + EditorGUILayout.PropertyField(sSupportedShaderComparer); + + + var sAtlasTargetDefines = serializedObject.FindProperty("AtlasTargetDefines"); + EditorGUILayout.PropertyField(sAtlasTargetDefines); + + + var sAtlasMaterialPostProses = serializedObject.FindProperty("AtlasMaterialPostProses"); + var addPP = EditorGUILayout.Popup("Add AtlasMaterialPostProses", -1, protProses); + if (addPP != -1) + { + var lastIndex = sAtlasMaterialPostProses.arraySize; + sAtlasMaterialPostProses.arraySize += 1; + sAtlasMaterialPostProses.GetArrayElementAtIndex(lastIndex).managedReferenceValue = protProsesGet[addPP].Invoke(); + } + EditorGUILayout.PropertyField(sAtlasMaterialPostProses); + + serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs.meta b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs.meta new file mode 100644 index 00000000..c96c98f1 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93dc6b785506ac64ab697572a7964af1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject.meta new file mode 100644 index 00000000..30114f21 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1260be71359e28f44b817e53aae9e1eb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs new file mode 100644 index 00000000..2679cd0b --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject +{ + [CreateAssetMenu(fileName = "AtlasShaderSupportScriptedObject", menuName = "TexTransTool/AtlasShaderSupportScriptedObject")] + public class AtlasShaderSupportScriptableObject : ScriptableObject + { + [SerializeReference] public ISupportedShaderComparer SupportedShaderComparer = new ContainsName(); + public List AtlasTargetDefines; + [SerializeReference] public List AtlasMaterialPostProses = new(); + } + [Serializable] + public class AtlasTargetDefine + { + public string TexturePropertyName; + public Shader BakeShader; + public List BakePropertyNames; + } + + +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs.meta new file mode 100644 index 00000000..a2f28e6d --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2369c186c1ab3c44b9ef86b3a8cbccf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs new file mode 100644 index 00000000..56749138 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject +{ + + + [Serializable] + public class AtlasShaderTexture2D + { + public string PropertyName; + public Texture2D Texture2D; + + [SerializeReference] public List BakeProperties; + } + + + [Serializable] + public abstract class BakeProperty + { + public string PropertyName; + + public static bool ValueComparer(BakeProperty l, BakeProperty r) + { + if (l.GetType() != r.GetType()) { return false; } + + switch (l) + { + case BakeFloat lf: + { + var rf = r as BakeFloat; + return Mathf.Approximately(lf.Float, rf.Float); + } + case BakeRange lr: + { + var rr = r as BakeRange; + if (rr.MinMax != lr.MinMax) { return false; } + return Mathf.Approximately(lr.Float, rr.Float); + } + case BakeColor lc: + { + var rc = r as BakeColor; + return lc.Color == rc.Color; + } + default: + return false; + } + } + } + [Serializable] + public class BakeFloat : BakeProperty { public float Float; } + [Serializable] + public class BakeRange : BakeProperty { public float Float; public Vector2 MinMax; } + [Serializable] + public class BakeColor : BakeProperty { public Color Color; } +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs.meta new file mode 100644 index 00000000..21976df2 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bcd4831fdc881f64492cc0ed2d5f0ffb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs new file mode 100644 index 00000000..ddc0855b --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject +{ + public interface IAtlasMaterialPostProses { void Proses(Material material); } + public class TextureReferenceCopy : IAtlasMaterialPostProses + { + public string SousePropertyName; + public string TargetPropertyName; + public void Proses(Material material) + { + if (!material.HasProperty(SousePropertyName) || !material.HasProperty(TargetPropertyName)) { return; } + material.SetTexture(TargetPropertyName, material.GetTexture(SousePropertyName)); + } + } +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs.meta new file mode 100644 index 00000000..0be9abb7 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96cdbca16df86914a856b942b54974de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs new file mode 100644 index 00000000..40fffded --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject +{ + public interface ISupportedShaderComparer + { + bool ThisSupported(Material material); + } + [Serializable] + public class ContainsName : ISupportedShaderComparer + { + public string Name; + public bool ThisSupported(Material material) { return material.shader.name.Contains(Name); } + } + [Serializable] + public class ShaderReference : ISupportedShaderComparer + { + public Shader Shader; + public bool ThisSupported(Material material) { return material.shader == Shader; } + } +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs.meta new file mode 100644 index 00000000..44715c52 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55eb36f83729a6d43916512b88b9d6d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs b/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs index 9f3e2654..8095d2dd 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs @@ -19,7 +19,6 @@ public interface IAtlasShaderSupport bool IsThisShader(Material material); void AddRecord(Material material); void ClearRecord(); - List GetPropertyAndTextures(IOriginTexture textureManager, Material material, PropertyBakeSetting bakeSetting); void MaterialCustomSetting(Material material); } From 69b3e3d427a41b2059a79c0a2bef4ef06900b494 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 26 Mar 2024 23:07:28 +0900 Subject: [PATCH 030/208] feat: IAtlasDefineConstraints and liltoonAtlasSupport.asset --- ...tlasShaderSupportScriptableObjectEditor.cs | 35 +- .../IAtlasDefineConstraintsDrawer.cs | 165 +++++ .../IAtlasDefineConstraintsDrawer.cs.meta | 11 + .../IAtlasMaterialPostProsesDrawer.cs | 22 + .../IAtlasMaterialPostProsesDrawer.cs.meta | 11 + .../ISupportedShaderComparerDrawer.cs | 65 ++ .../ISupportedShaderComparerDrawer.cs.meta | 11 + .../AtlasShaderSupportScriptableObject.cs | 6 +- .../IAtlasDefineConstraints.cs | 69 ++ .../IAtlasDefineConstraints.cs.meta | 11 + .../liltoon/lilToon LICENSE | 21 + .../liltoon/lilToon LICENSE.meta | 7 + .../liltoon/lilToonAtlasBaker.shader | 265 +++++++ .../liltoon/lilToonAtlasBaker.shader.meta | 9 + .../liltoon/liltoonAtlasSupport.asset | 680 ++++++++++++++++++ .../liltoon/liltoonAtlasSupport.asset.meta | 8 + Runtime/Utils/MaterialUtility.cs | 17 +- 17 files changed, 1385 insertions(+), 28 deletions(-) create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs.meta create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs.meta create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs create mode 100644 Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader.meta create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset create mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset.meta diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs index d4d68451..9e0af718 100644 --- a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/AtlasShaderSupportScriptableObjectEditor.cs @@ -3,41 +3,30 @@ using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; using net.rs64.TexTransTool.Editor; using System; +using System.Collections.Generic; namespace net.rs64.TexTransTool.TextureAtlas.Editor { [CustomEditor(typeof(AtlasShaderSupportScriptableObject))] public class AtlasShaderSupportScriptableObjectEditor : UnityEditor.Editor { - string[] comparers = new[] { "ContainsName", "ShaderReference" }; - Func[] comparerGet = new Func[] { () => new ContainsName(), () => new ShaderReference() }; - - string[] protProses = new[] { "TextureReferenceCopy" }; - Func[] protProsesGet = new Func[] { () => new TextureReferenceCopy() }; + HashSet _hash; public override void OnInspectorGUI() { - serializedObject.Update(); TextureTransformerEditor.DrawerWarning("AtlasShaderSupportScriptableObject"); + base.OnInspectorGUI(); - var sSupportedShaderComparer = serializedObject.FindProperty("SupportedShaderComparer"); - var reSelect = EditorGUILayout.Popup("Comparer Re Select", -1, comparers); - if (reSelect != -1) { sSupportedShaderComparer.managedReferenceValue = comparerGet[reSelect].Invoke(); } - EditorGUILayout.PropertyField(sSupportedShaderComparer); - - - var sAtlasTargetDefines = serializedObject.FindProperty("AtlasTargetDefines"); - EditorGUILayout.PropertyField(sAtlasTargetDefines); - - - var sAtlasMaterialPostProses = serializedObject.FindProperty("AtlasMaterialPostProses"); - var addPP = EditorGUILayout.Popup("Add AtlasMaterialPostProses", -1, protProses); - if (addPP != -1) + var atd = serializedObject.FindProperty("AtlasTargetDefines"); + var arraySize = atd.arraySize; + _hash ??= new HashSet(arraySize); + for (var i = 0; arraySize > i; i += 1) { - var lastIndex = sAtlasMaterialPostProses.arraySize; - sAtlasMaterialPostProses.arraySize += 1; - sAtlasMaterialPostProses.GetArrayElementAtIndex(lastIndex).managedReferenceValue = protProsesGet[addPP].Invoke(); + var adc = atd.GetArrayElementAtIndex(i).FindPropertyRelative("AtlasDefineConstraints"); + var mrf = adc.managedReferenceValue; + if (_hash.Contains(mrf)) { adc.managedReferenceValue = new FloatPropertyValueGreater(); } + else { _hash.Add(mrf); } } - EditorGUILayout.PropertyField(sAtlasMaterialPostProses); + _hash.Clear(); serializedObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs new file mode 100644 index 00000000..4b444c00 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs @@ -0,0 +1,165 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; +using net.rs64.TexTransTool.Editor; +using System; +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + [CustomPropertyDrawer(typeof(IAtlasDefineConstraints))] + public class IAtlasDefineConstraintsDrawer : PropertyDrawer + { + static string[] comparers = new[] { + "AndConstraints", + "OrConstraints", + "FloatPropertyValueGreater", + "FloatPropertyValueEqual", + "ShaderNameContains", + "Anything" + }; + static Func[] comparerGet = new Func[] { + () => new AndConstraints(), + () => new OrConstraints(), + () => new FloatPropertyValueGreater(), + () => new FloatPropertyValueEqual(), + () => new ShaderNameContains(), + () => new Anything() + }; + + public static bool DrawSelector(Rect rect, SerializedProperty sSupportedShaderComparer) + { + var bef = Array.IndexOf(comparers, sSupportedShaderComparer.managedReferenceValue?.GetType()?.Name); + var aft = EditorGUI.Popup(rect, "Comparer", bef, comparers); + if (aft != bef) { sSupportedShaderComparer.managedReferenceValue = comparerGet[aft].Invoke(); } + return aft != bef; + } + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + DrawSelector(position, property); + } + } + [CustomPropertyDrawer(typeof(AndConstraints))] + public class AndConstraintsDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + var listSize = position.height - 18f; + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + position.height = listSize; + EditorGUI.PropertyField(position, property.FindPropertyRelative("AtlasDefineConstraints")); + EditorGUI.indentLevel += -1; + + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) + EditorGUI.GetPropertyHeight(property.FindPropertyRelative("AtlasDefineConstraints")); + } + } + [CustomPropertyDrawer(typeof(OrConstraints))] + public class OrConstraintsDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + var listSize = position.height - 18f; + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + position.height = listSize; + EditorGUI.PropertyField(position, property.FindPropertyRelative("AtlasDefineConstraints")); + EditorGUI.indentLevel += -1; + + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) + EditorGUI.GetPropertyHeight(property.FindPropertyRelative("AtlasDefineConstraints")); + } + } + [CustomPropertyDrawer(typeof(FloatPropertyValueGreater))] + public class FloatPropertyValueGreaterDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("PropertyName")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("ComparerValue")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("Less")); + EditorGUI.indentLevel += -1; + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 4f; + } + } + [CustomPropertyDrawer(typeof(FloatPropertyValueEqual))] + public class FloatPropertyValueEqualDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("PropertyName")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("Value")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("NotEqual")); + EditorGUI.indentLevel += -1; + + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 4f; + } + } + [CustomPropertyDrawer(typeof(ShaderNameContains))] + public class ShaderNameContainsDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("Name")); + EditorGUI.indentLevel += -1; + + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 2f; + } + } + + [CustomPropertyDrawer(typeof(Anything))] + public class AnythingDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + + } + } + +} diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs.meta b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs.meta new file mode 100644 index 00000000..e62b1a42 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ce087e6e06c63d47bfed80f80f408aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs new file mode 100644 index 00000000..ef5ac96a --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs @@ -0,0 +1,22 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; +using net.rs64.TexTransTool.Editor; +using System; +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + + [CustomPropertyDrawer(typeof(IAtlasMaterialPostProses))] + public class IAtlasMaterialPostProsesDrawer : PropertyDrawer + { + + string[] protProses = new[] { "TextureReferenceCopy" }; + Func[] protProsesGet = new Func[] { () => new TextureReferenceCopy() }; + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + var sv = EditorGUI.Popup(position,"Select AtlasMaterialPostProses", -1, protProses); + if (sv != -1) { property.managedReferenceValue = protProsesGet[sv].Invoke(); } + } + } +} diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs.meta b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs.meta new file mode 100644 index 00000000..68009895 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasMaterialPostProsesDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b8c9ab9a730bba458ab350205c1e86b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs new file mode 100644 index 00000000..a1ef47fe --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs @@ -0,0 +1,65 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; +using net.rs64.TexTransTool.Editor; +using System; +namespace net.rs64.TexTransTool.TextureAtlas.Editor +{ + static class ISupportedShaderComparerEditorUtility + { + static string[] comparers = new[] { "ContainsName", "ShaderReference" }; + static Func[] comparerGet = new Func[] { () => new ContainsName(), () => new ShaderReference() }; + + public static bool DrawSelector(Rect rect, SerializedProperty sSupportedShaderComparer) + { + var bef = Array.IndexOf(comparers, sSupportedShaderComparer.managedReferenceValue.GetType().Name); + var aft = EditorGUI.Popup(rect, "Comparer", bef, comparers); + if (aft != bef) { sSupportedShaderComparer.managedReferenceValue = comparerGet[aft].Invoke(); } + return aft != bef; + } + } + [CustomPropertyDrawer(typeof(ContainsName))] + public class ContainsNameDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + + EditorGUI.BeginProperty(position, label, property); + if (ISupportedShaderComparerEditorUtility.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + + position.y += position.height; + + EditorGUI.PropertyField(position, property.FindPropertyRelative("Name")); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 2; + } + } + + [CustomPropertyDrawer(typeof(ShaderReference))] + public class ShaderReferenceDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + + EditorGUI.BeginProperty(position, label, property); + if (ISupportedShaderComparerEditorUtility.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + + position.y += position.height; + + EditorGUI.PropertyField(position, property.FindPropertyRelative("Shader")); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 2; + } + } + +} diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs.meta b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs.meta new file mode 100644 index 00000000..8a723de1 --- /dev/null +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/ISupportedShaderComparerDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1a2285a798bcfc40b214884441b0324 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs index 2679cd0b..aa31b318 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs @@ -10,15 +10,15 @@ public class AtlasShaderSupportScriptableObject : ScriptableObject { [SerializeReference] public ISupportedShaderComparer SupportedShaderComparer = new ContainsName(); public List AtlasTargetDefines; + public Shader BakeShader; [SerializeReference] public List AtlasMaterialPostProses = new(); } [Serializable] public class AtlasTargetDefine { public string TexturePropertyName; - public Shader BakeShader; + [SerializeReference] public IAtlasDefineConstraints AtlasDefineConstraints = new FloatPropertyValueGreater(); + public List BakePropertyNames; } - - } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs new file mode 100644 index 00000000..e34ef510 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject +{ + public interface IAtlasDefineConstraints + { + bool Constraints(Material material); + } + + [Serializable] + public class AndConstraints : IAtlasDefineConstraints + { + [SerializeReference] public List AtlasDefineConstraints; + public bool Constraints(Material material) + { + foreach (var adc in AtlasDefineConstraints) { if (!adc.Constraints(material)) { return false; } } + return true; + } + } + [Serializable] + public class OrConstraints : IAtlasDefineConstraints + { + [SerializeReference] public List AtlasDefineConstraints; + public bool Constraints(Material material) + { + foreach (var adc in AtlasDefineConstraints) { if (!adc.Constraints(material)) { return true; } } + return false; + } + } + [Serializable] + public class FloatPropertyValueGreater : IAtlasDefineConstraints + { + public string PropertyName; + public float ComparerValue = 0.5f; + public bool Less; + public bool Constraints(Material material) + { + return !Less ? material.GetFloat(PropertyName) > ComparerValue : material.GetFloat(PropertyName) < ComparerValue; + } + } + [Serializable] + public class FloatPropertyValueEqual : IAtlasDefineConstraints + { + public string PropertyName; + public float Value; + public bool NotEqual; + public bool Constraints(Material material) + { + return Mathf.Approximately(material.GetFloat(PropertyName), Value) == !NotEqual; + } + } + [Serializable] + public class ShaderNameContains : IAtlasDefineConstraints + { + public string Name; + public bool Constraints(Material material) + { + return material.shader.name.Contains("Name"); + } + } + [Serializable] + public class Anything : IAtlasDefineConstraints + { + public bool Constraints(Material material) { return true; } + } + +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs.meta new file mode 100644 index 00000000..f50a2c59 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 860bc8e026ad74849ac45fd2f20891b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE new file mode 100644 index 00000000..adb6fbb4 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-2024 lilxyzw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE.meta b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE.meta new file mode 100644 index 00000000..5b665a82 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToon LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c3e6e9ddf1c40f64ab545b276bbd3731 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader new file mode 100644 index 00000000..b8be66dc --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader @@ -0,0 +1,265 @@ +Shader "Hidden/lilToonAtlasBaker" +{ + Properties + { + //https://github.com/lilxyzw/lilToon/blob/d9e1e06d2bc25961f8849ba2dd926ffebcef6bf7/Assets/lilToon/CustomShaderResources/Properties/Default.lilblock + + //---------------------------------------------------------------------------------------------------------------------- + // Main + _MainTex ("Texture", 2D) = "white" {} + _Color ("sColor", Color) = (1,1,1,1) + _MainTexHSVG ("sHSVGs", Vector) = (0,1,1,1) + + _MainColorAdjustMask ("Adjust Mask", 2D) = "white" {} + + //---------------------------------------------------------------------------------------------------------------------- + // Main2nd + _UseMain2ndTex ("sMainColor2nd", Int) = 0 + _Main2ndTex_UVMode ("UV Mode|UV0|UV1|UV2|UV3|MatCap", Int) = 0 + + _Main2ndTex ("Texture", 2D) = "white" {} + _Color2nd ("sColor", Color) = (1,1,1,1) + + _Main2ndBlendMask ("Mask", 2D) = "white" {} + + _Main2ndDissolveMask ("Dissolve Mask", 2D) = "white" {} + + //---------------------------------------------------------------------------------------------------------------------- + // Main3rd + _UseMain3rdTex ("sMainColor3rd", Int) = 0 + _Main3rdTex_UVMode ("UV Mode|UV0|UV1|UV2|UV3|MatCap", Int) = 0 + + _Main3rdTex ("Texture", 2D) = "white" {} + _Color3rd ("sColor", Color) = (1,1,1,1) + + _Main3rdBlendMask ("Mask", 2D) = "white" {} + + _Main3rdDissolveNoiseMask ("Dissolve Noise Mask", 2D) = "gray" {} + + + //---------------------------------------------------------------------------------------------------------------------- + // Alpha Mask + _AlphaMaskMode ("sAlphaMaskModes", Int) = 0 + + _AlphaMask ("AlphaMask", 2D) = "white" {} + _AlphaMaskScale ("Scale", Float) = 1 + _AlphaMaskValue ("Offset", Float) = 0 + + //---------------------------------------------------------------------------------------------------------------------- + // NormalMap + _UseBumpMap ("sNormalMap", Int) = 0 + + _BumpMap ("Normal Map", 2D) = "bump" {} + _BumpScale ("Scale", Range(-10,10)) = 1 + + //---------------------------------------------------------------------------------------------------------------------- + // NormalMap 2nd + _UseBump2ndMap ("sNormalMap2nd", Int) = 0 + _Bump2ndMap_UVMode ("UV Mode|UV0|UV1|UV2|UV3", Int) = 0 + + _Bump2ndMap ("Normal Map", 2D) = "bump" {} + _Bump2ndScale ("Scale", Range(-10,10)) = 1 + _Bump2ndScaleMask ("Mask", 2D) = "white" {} + + + //---------------------------------------------------------------------------------------------------------------------- + // Anisotropy + _UseAnisotropy ("sAnisotropy", Int) = 0 + + _AnisotropyTangentMap ("Tangent Map", 2D) = "bump" {} + + _AnisotropyScaleMask ("Scale Mask", 2D) = "white" {} + _AnisotropyScale ("Scale", Range(-1,1)) = 1 + + + //---------------------------------------------------------------------------------------------------------------------- + // Backlight + _UseBacklight ("sBacklight", Int) = 0 + + _BacklightColorTex ("Texture", 2D) = "white" {} + _BacklightColor ("sColor", Color) = (0.85,0.8,0.7,1.0) + + + //---------------------------------------------------------------------------------------------------------------------- + // Shadow + _UseShadow ("sShadow", Int) = 0 + + _ShadowStrengthMask ("sStrength", 2D) = "white" {} + _ShadowStrength ("sStrength", Range(0, 1)) = 1 + + _ShadowBorderMask ("sBorder", 2D) = "white" {} + + _ShadowBlurMask ("sBlur", 2D) = "white" {} + + _ShadowColorTex ("Shadow Color", 2D) = "black" {} + _ShadowColor ("Shadow Color", Color) = (0.82,0.76,0.85,1.0) + + _Shadow2ndColorTex ("2nd Color", 2D) = "black" {} + _Shadow2ndColor ("2nd Color", Color) = (0.68,0.66,0.79,1) + + _Shadow3rdColorTex ("3rd Color", 2D) = "black" {} + _Shadow3rdColor ("3rd Color", Color) = (0,0,0,0) + + //---------------------------------------------------------------------------------------------------------------------- + // Rim Shade + _UseRimShade ("RimShade", Int) = 0 + + _RimShadeMask ("Mask", 2D) = "white" {} + _RimShadeColor ("sColor", Color) = (0.5,0.5,0.5,1.0) + + //---------------------------------------------------------------------------------------------------------------------- + // Reflection + _UseReflection ("sReflection", Int) = 0 + + _SmoothnessTex ("Smoothness", 2D) = "white" {} + _Smoothness ("Smoothness", Range(0, 1)) = 1 + + _MetallicGlossMap ("Metallic", 2D) = "white" {} + _Metallic ("Metallic", Range(0, 1)) = 0 + + _ReflectionColorTex ("sColor", 2D) = "white" {} + _ReflectionColor ("sColor", Color) = (1,1,1,1) + + //---------------------------------------------------------------------------------------------------------------------- + // MatCap + _UseMatCap ("sMatCap", Int) = 0 + + _MatCapBlendMask ("Mask", 2D) = "white" {} + _MatCapBlend ("Blend", Range(0, 1)) = 1 + + + _MatCapCustomNormal ("sMatCapCustomNormal", Int) = 0 + + _MatCapBumpMap ("Normal Map", 2D) = "bump" {} + _MatCapBumpScale ("Scale", Range(-10,10)) = 1 + + + + //---------------------------------------------------------------------------------------------------------------------- + // MatCap 2nd + _UseMatCap2nd ("sMatCap2nd", Int) = 0 + + _MatCap2ndBlendMask ("Mask", 2D) = "white" {} + _MatCap2ndBlend ("Blend", Range(0, 1)) = 1 + + + _MatCap2ndCustomNormal ("sMatCapCustomNormal", Int) = 0 + + _MatCap2ndBumpMap ("Normal Map", 2D) = "bump" {} + _MatCap2ndBumpScale ("Scale", Range(-10,10)) = 1 + + //---------------------------------------------------------------------------------------------------------------------- + // Rim + _UseRim ("sRimLight", Int) = 0 + + _RimColorTex ("Texture", 2D) = "white" {} + _RimColor ("sColor", Color) = (0.66,0.5,0.48,1) + + //---------------------------------------------------------------------------------------------------------------------- + // Glitter + _UseGlitter ("sGlitter", Int) = 0 + _GlitterColorTex_UVMode ("UV Mode|UV0|UV1|UV2|UV3", Int) = 0 + + _GlitterColorTex ("Texture", 2D) = "white" {} + _GlitterColor ("sColor", Color) = (1,1,1,1) + + //---------------------------------------------------------------------------------------------------------------------- + // Emmision + _UseEmission ("sEmission", Int) = 0 + _EmissionMap_UVMode ("UV Mode|UV0|UV1|UV2|UV3|Rim", Int) = 0 + + _EmissionMap ("Texture", 2D) = "white" {} + _EmissionColor ("sColor", Color) = (1,1,1,1) + + _EmissionBlendMask ("Mask", 2D) = "white" {} + _EmissionBlend ("Blend", Range(0,1)) = 1 + + + //---------------------------------------------------------------------------------------------------------------------- + // Emmision2nd + _UseEmission2nd ("sEmission2nd", Int) = 0 + _Emission2ndMap_UVMode ("UV Mode|UV0|UV1|UV2|UV3|Rim", Int) = 0 + + _Emission2ndMap ("Texture", 2D) = "white" {} + _Emission2ndColor ("sColor", Color) = (1,1,1,1) + + _Emission2ndBlendMask ("Mask", 2D) = "white" {} + _Emission2ndBlend ("Blend", Range(0,1)) = 1 + + //---------------------------------------------------------------------------------------------------------------------- + // Parallax + _UseParallax ("sParallax", Int) = 0 + + _ParallaxMap ("Parallax Map", 2D) = "gray" {} + _Parallax ("Parallax Scale", float) = 0.02 + +//AudioLink と Dissolve はよくわかんないのでパス + + //---------------------------------------------------------------------------------------------------------------------- + // Outline + + _OutlineTex ("Texture", 2D) = "white" {} + _OutlineColor ("sColor", Color) = (0.6,0.56,0.73,1) + _OutlineTexHSVG ("sHSVGs", Vector) = (0,1,1,1) + + _OutlineWidthMask ("Width", 2D) = "white" {} + _OutlineWidth ("Width", Range(0,1)) = 0.08 + + + _OutlineVectorUVMode ("UV Mode|UV0|UV1|UV2|UV3", Int) = 0 + + _OutlineVectorTex ("Vector", 2D) = "bump" {} + _OutlineVectorScale ("Vector scale", Range(-10,10)) = 1 + + + } + SubShader + { + Tags { "RenderType"="Opaque" } + LOD 100 + + Pass + { + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + + #pragma multi_compile_fragment // TODO + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + struct v2f + { + float2 uv : TEXCOORD0; + float4 vertex : SV_POSITION; + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.uv, _MainTex); + return o; + } + + float4 frag (v2f i) : SV_Target + { + float4 col = tex2D(_MainTex, i.uv); + + // TODO + + return col; + } + ENDHLSL + } + } +} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader.meta b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader.meta new file mode 100644 index 00000000..4490dc01 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 9d918a30dc195d94ea1916f48779948f +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset new file mode 100644 index 00000000..9ca762c1 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -0,0 +1,680 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: b2369c186c1ab3c44b9ef86b3a8cbccf, type: 3} + m_Name: liltoonAtlasSupport + m_EditorClassIdentifier: + SupportedShaderComparer: + rid: 7150698656081904266 + AtlasTargetDefines: + - TexturePropertyName: _MainTex + AtlasDefineConstraints: + rid: 7150698656081904301 + BakePropertyNames: + - _Color + - _MainColorAdjustMask + - _MainTexHSVG + - TexturePropertyName: _MainColorAdjustMask + AtlasDefineConstraints: + rid: 7150698656081904310 + BakePropertyNames: [] + - TexturePropertyName: _Main2ndTex + AtlasDefineConstraints: + rid: 7150698656081904335 + BakePropertyNames: + - _Color2nd + - TexturePropertyName: _Main2ndBlendMask + AtlasDefineConstraints: + rid: 7150698656081904338 + BakePropertyNames: [] + - TexturePropertyName: _Main2ndDissolveMask + AtlasDefineConstraints: + rid: 7150698656081904341 + BakePropertyNames: [] + - TexturePropertyName: _Main3rdTex + AtlasDefineConstraints: + rid: 7150698656081904345 + BakePropertyNames: + - _Color3rd + - TexturePropertyName: _Main3rdBlendMask + AtlasDefineConstraints: + rid: 7150698656081904348 + BakePropertyNames: [] + - TexturePropertyName: _AlphaMask + AtlasDefineConstraints: + rid: 7150698656081904333 + BakePropertyNames: + - _AlphaMaskScale + - _AlphaMaskValue + - TexturePropertyName: _BumpMap + AtlasDefineConstraints: + rid: 7150698656081904351 + BakePropertyNames: + - _BumpScale + - TexturePropertyName: _Bump2ndMap + AtlasDefineConstraints: + rid: 7150698656081904357 + BakePropertyNames: + - _Bump2ndScale + - _Bump2ndScaleMask + - TexturePropertyName: _Bump2ndScaleMask + AtlasDefineConstraints: + rid: 7150698656081904353 + BakePropertyNames: [] + - TexturePropertyName: _AnisotropyTangentMap + AtlasDefineConstraints: + rid: 7150698656081904360 + BakePropertyNames: [] + - TexturePropertyName: _AnisotropyScaleMask + AtlasDefineConstraints: + rid: 7150698656081904324 + BakePropertyNames: + - _AnisotropyScale + - TexturePropertyName: _BacklightColorTex + AtlasDefineConstraints: + rid: 7150698656081904325 + BakePropertyNames: + - _BacklightColor + - TexturePropertyName: _ShadowStrengthMask + AtlasDefineConstraints: + rid: 7150698656081904316 + BakePropertyNames: + - _ShadowStrength + - TexturePropertyName: _ShadowBorderMask + AtlasDefineConstraints: + rid: 7150698656081904361 + BakePropertyNames: [] + - TexturePropertyName: _ShadowBlurMask + AtlasDefineConstraints: + rid: 7150698656081904362 + BakePropertyNames: [] + - TexturePropertyName: _ShadowColorTex + AtlasDefineConstraints: + rid: 7150698656081904317 + BakePropertyNames: + - _ShadowColor + - TexturePropertyName: _Shadow2ndColorTex + AtlasDefineConstraints: + rid: 7150698656081904318 + BakePropertyNames: + - _Shadow2ndColor + - TexturePropertyName: _Shadow3rdColorTex + AtlasDefineConstraints: + rid: 7150698656081904319 + BakePropertyNames: + - _Shadow3rdColor + - TexturePropertyName: _RimShadeMask + AtlasDefineConstraints: + rid: 7150698656081904363 + BakePropertyNames: + - _RimShadeColor + - TexturePropertyName: _SmoothnessTex + AtlasDefineConstraints: + rid: 7150698656081904326 + BakePropertyNames: + - _Smoothness + - TexturePropertyName: _MetallicGlossMap + AtlasDefineConstraints: + rid: 7150698656081904327 + BakePropertyNames: + - _Metallic + - TexturePropertyName: _ReflectionColorTex + AtlasDefineConstraints: + rid: 7150698656081904328 + BakePropertyNames: + - _ReflectionColor + - TexturePropertyName: _MatCapBlendMask + AtlasDefineConstraints: + rid: 7150698656081904329 + BakePropertyNames: + - _MatCapBlend + - TexturePropertyName: _MatCapBumpMap + AtlasDefineConstraints: + rid: 7150698656081904369 + BakePropertyNames: + - _MatCapBumpScale + - TexturePropertyName: _MatCap2ndBlendMask + AtlasDefineConstraints: + rid: 7150698656081904330 + BakePropertyNames: + - _MatCap2ndBlend + - TexturePropertyName: _MatCap2ndBumpMap + AtlasDefineConstraints: + rid: 7150698656081904366 + BakePropertyNames: + - _MatCap2ndBumpScale + - TexturePropertyName: _RimColorTex + AtlasDefineConstraints: + rid: 7150698656081904331 + BakePropertyNames: + - _RimColor + - TexturePropertyName: _GlitterColorTex + AtlasDefineConstraints: + rid: 7150698656081904372 + BakePropertyNames: + - _GlitterColor + - TexturePropertyName: _EmissionMap + AtlasDefineConstraints: + rid: 7150698656081904375 + BakePropertyNames: + - _EmissionColor + - TexturePropertyName: _EmissionBlendMask + AtlasDefineConstraints: + rid: 7150698656081904378 + BakePropertyNames: + - _EmissionBlend + - TexturePropertyName: _Emission2ndMap + AtlasDefineConstraints: + rid: 7150698656081904381 + BakePropertyNames: + - _Emission2ndColor + - TexturePropertyName: _Emission2ndBlendMask + AtlasDefineConstraints: + rid: 7150698656081904384 + BakePropertyNames: + - _Emission2ndBlend + - TexturePropertyName: _ParallaxMap + AtlasDefineConstraints: + rid: 7150698656081904387 + BakePropertyNames: + - _Parallax + - TexturePropertyName: _OutlineTex + AtlasDefineConstraints: + rid: 7150698656081904303 + BakePropertyNames: + - _OutlineColor + - _OutlineTexHSVG + - TexturePropertyName: _OutlineWidthMask + AtlasDefineConstraints: + rid: 7150698656081904302 + BakePropertyNames: + - _OutlineWidth + - TexturePropertyName: _OutlineVectorTex + AtlasDefineConstraints: + rid: 7150698656081904388 + BakePropertyNames: + - _OutlineVectorScale + BakeShader: {fileID: 0} + AtlasMaterialPostProses: + - rid: 7150698656081904264 + - rid: 7150698656081904304 + references: + version: 2 + RefIds: + - rid: 7150698656081904264 + type: {class: TextureReferenceCopy, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + SousePropertyName: _MainTex + TargetPropertyName: _BaseMap + - rid: 7150698656081904266 + type: {class: ContainsName, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + Name: lilToon + - rid: 7150698656081904301 + type: {class: Anything, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + - rid: 7150698656081904302 + type: {class: ShaderNameContains, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + Name: Outline + - rid: 7150698656081904303 + type: {class: ShaderNameContains, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + Name: Outline + - rid: 7150698656081904304 + type: {class: TextureReferenceCopy, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + SousePropertyName: _MainTex + TargetPropertyName: _BaseColorMap + - rid: 7150698656081904310 + type: {class: Anything, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + - rid: 7150698656081904316 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904317 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904318 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904319 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904324 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseAnisotropy + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904325 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBacklight + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904326 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseReflection + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904327 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseReflection + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904328 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseReflection + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904329 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904330 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904331 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseRim + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904333 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _AlphaMaskMode + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904335 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904337 + - rid: 7150698656081904336 + - rid: 7150698656081904336 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Main2ndTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904337 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMain2ndTex + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904338 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904339 + - rid: 7150698656081904340 + - rid: 7150698656081904339 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMain2ndTex + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904340 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Main2ndTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904341 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904343 + - rid: 7150698656081904344 + - rid: 7150698656081904343 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMain2ndTex + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904344 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Main2ndTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904345 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904346 + - rid: 7150698656081904347 + - rid: 7150698656081904346 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMain3rdTex + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904347 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Main3rdTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904348 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904349 + - rid: 7150698656081904350 + - rid: 7150698656081904349 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMain3rdTex + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904350 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Main3rdTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904351 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBumpMap + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904353 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904354 + - rid: 7150698656081904355 + - rid: 7150698656081904354 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBump2ndMap + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904355 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Bump2ndMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904357 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904358 + - rid: 7150698656081904359 + - rid: 7150698656081904358 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBump2ndMap + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904359 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Bump2ndMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904360 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseAnisotropy + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904361 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904362 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904363 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseRimShade + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904366 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904367 + - rid: 7150698656081904368 + - rid: 7150698656081904367 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap2nd + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904368 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _MatCap2ndCustomNormal + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904369 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904371 + - rid: 7150698656081904370 + - rid: 7150698656081904370 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _MatCapCustomNormal + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904371 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap2nd + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904372 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904373 + - rid: 7150698656081904374 + - rid: 7150698656081904373 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseGlitter + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904374 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _GlitterColorTex_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904375 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904376 + - rid: 7150698656081904377 + - rid: 7150698656081904376 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseEmission + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904377 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _EmissionMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904378 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904379 + - rid: 7150698656081904380 + - rid: 7150698656081904379 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseEmission + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904380 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _EmissionMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904381 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904382 + - rid: 7150698656081904383 + - rid: 7150698656081904382 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseEmission2nd + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904383 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Emission2ndMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904384 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 7150698656081904385 + - rid: 7150698656081904386 + - rid: 7150698656081904385 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseEmission2nd + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904386 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _Emission2ndMap_UVMode + ComparerValue: 0.5 + Less: 1 + - rid: 7150698656081904387 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseParallax + ComparerValue: 0.5 + Less: 0 + - rid: 7150698656081904388 + type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _OutlineVectorUVMode + ComparerValue: 0.5 + Less: 1 diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset.meta b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset.meta new file mode 100644 index 00000000..8b88f549 --- /dev/null +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5f3c47a5d08ae974fac1ad0b720f3ce4 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Utils/MaterialUtility.cs b/Runtime/Utils/MaterialUtility.cs index c9ae131a..292e8709 100644 --- a/Runtime/Utils/MaterialUtility.cs +++ b/Runtime/Utils/MaterialUtility.cs @@ -59,6 +59,19 @@ public static Dictionary GetAllTexture2D(this Material materi } return output; } - + public static IEnumerable<(string, Texture2D)> GetAllTexture2DProperty(this Material material) + { + if (material == null || material.shader == null) { yield break; } + var shader = material.shader; + var propCount = shader.GetPropertyCount(); + for (var i = 0; propCount > i; i += 1) + { + if (shader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture) { continue; } + var propName = shader.GetPropertyName(i); + var texture = material.GetTexture(propName); + var tex2D = texture as Texture2D; + yield return (propName, tex2D); + } + } } -} \ No newline at end of file +} From 1989ce9eb9b16bfbd38f9bd14de2f880ee6f4325 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 28 Mar 2024 21:07:51 +0900 Subject: [PATCH 031/208] feat: MaterialGrouping wip --- .../IAtlasDefineConstraintsDrawer.cs | 51 ++ Runtime/TextureAtlas/AtlasContext.cs | 82 ++- .../AtlasShaderSupportScriptableObject.cs | 21 +- .../AtlasTargetDefine.cs | 14 + .../IAtlasDefineConstraints.cs | 24 +- .../ISupportedShaderComparer.cs | 5 + .../AtlasShaderSupportUtils.cs | 128 ++-- .../liltoon/lilToonAtlasBaker.shader | 215 ++++++- .../liltoon/liltoonAtlasSupport.asset | 564 +++++++++--------- Runtime/TextureAtlas/AtlasTexture.cs | 162 +++-- .../TextureFineTuning/TexFineTuningTarget.cs | 6 +- 11 files changed, 853 insertions(+), 419 deletions(-) diff --git a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs index 4b444c00..f920b4b5 100644 --- a/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs +++ b/Editor/Inspector/TextureAtlas/AtlasScriptableObject/IAtlasDefineConstraintsDrawer.cs @@ -13,6 +13,8 @@ public class IAtlasDefineConstraintsDrawer : PropertyDrawer "OrConstraints", "FloatPropertyValueGreater", "FloatPropertyValueEqual", + "IntPropertyValueGreater", + "IntPropertyValueEqual", "ShaderNameContains", "Anything" }; @@ -21,6 +23,8 @@ public class IAtlasDefineConstraintsDrawer : PropertyDrawer () => new OrConstraints(), () => new FloatPropertyValueGreater(), () => new FloatPropertyValueEqual(), + () => new IntPropertyValueGreater(), + () => new IntPropertyValueEqual(), () => new ShaderNameContains(), () => new Anything() }; @@ -128,6 +132,53 @@ public override float GetPropertyHeight(SerializedProperty property, GUIContent return base.GetPropertyHeight(property, label) * 4f; } } + [CustomPropertyDrawer(typeof(IntPropertyValueGreater))] + public class IntPropertyValueGreaterDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("PropertyName")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("ComparerValue")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("Less")); + EditorGUI.indentLevel += -1; + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 4f; + } + } + [CustomPropertyDrawer(typeof(IntPropertyValueEqual))] + public class IntPropertyValueEqualDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + position.height = 18f; + EditorGUI.BeginProperty(position, label, property); + if (IAtlasDefineConstraintsDrawer.DrawSelector(position, property)) { return; } + EditorGUI.EndProperty(); + EditorGUI.indentLevel += 1; + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("PropertyName")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("Value")); + position.y += position.height; + EditorGUI.PropertyField(position, property.FindPropertyRelative("NotEqual")); + EditorGUI.indentLevel += -1; + + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return base.GetPropertyHeight(property, label) * 4f; + } + } [CustomPropertyDrawer(typeof(ShaderNameContains))] public class ShaderNameContainsDrawer : PropertyDrawer { diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs index 4066f1a2..566d5f32 100644 --- a/Runtime/TextureAtlas/AtlasContext.cs +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -8,6 +8,7 @@ using System.Collections; using net.rs64.TexTransTool.TextureAtlas.AAOCode; using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; namespace net.rs64.TexTransTool.TextureAtlas { @@ -17,7 +18,9 @@ internal class AtlasContext : IDisposable public Dictionary NormalizeMeshes;//ノーマライズされていないメッシュとされているメッシュと対応する public Dictionary MeshDataDict;//適当なレンダラーのノーマライズされたメッシュと対応する - public HashSet[] Materials; + public OrderedHashSet[] MaterialGroup; + public Dictionary> MaterialToAtlasShaderDict; + public AtlasShaderSupportUtils AtlasShaderSupportUtils; public HashSet AtlasSubAll; public List AtlasSubSets; @@ -25,40 +28,77 @@ internal class AtlasContext : IDisposable public Island[] Islands; public AtlasSubData[] IslandSubData; + List _bakedMesh = new(); + public struct AtlasSubData { public int MeshID; public int SubMeshIndex; - public int MaterialID; - public AtlasSubData(int meshID, int subMeshIndex, int materialID) : this() + public int MaterialGroupID; + public AtlasSubData(int meshID, int subMeshIndex, int materialGroupID) : this() { MeshID = meshID; SubMeshIndex = subMeshIndex; - MaterialID = materialID; + MaterialGroupID = materialGroupID; } - public override bool Equals(object obj) { return obj is AtlasSubData other && MeshID == other.MeshID && SubMeshIndex == other.SubMeshIndex && MaterialID == other.MaterialID; } - public override int GetHashCode() { return HashCode.Combine(MeshID, SubMeshIndex, MaterialID); } + public override bool Equals(object obj) { return obj is AtlasSubData other && MeshID == other.MeshID && SubMeshIndex == other.SubMeshIndex && MaterialGroupID == other.MaterialGroupID; } + public override int GetHashCode() { return HashCode.Combine(MeshID, SubMeshIndex, MaterialGroupID); } public static bool operator ==(AtlasSubData l, AtlasSubData r) { if (l.MeshID != r.MeshID) { return false; } if (l.SubMeshIndex != r.SubMeshIndex) { return false; } - if (l.MaterialID != r.MaterialID) { return false; } + if (l.MaterialGroupID != r.MaterialGroupID) { return false; } return true; } public static bool operator !=(AtlasSubData l, AtlasSubData r) { if (l.MeshID != r.MeshID) { return true; } if (l.SubMeshIndex != r.SubMeshIndex) { return true; } - if (l.MaterialID != r.MaterialID) { return true; } + if (l.MaterialGroupID != r.MaterialGroupID) { return true; } return false; } } - public AtlasContext(List TargetMaterials, List inputRenderers) + public AtlasContext(List targetMaterials, List inputRenderers, bool usePropertyBake) { - var materialHash = TargetMaterials.ToHashSet(); - Materials = materialHash.Select(m => new HashSet() { m }).ToArray();//今後マテリアルが違っても同一とみる機会が発生するから、マテリアルのグルーピングの仕組みを作る。 + var materialHash = targetMaterials.ToHashSet(); + + var shaderSupports = new AtlasShaderSupportUtils(); + var supporters = targetMaterials.Select(m => (m, shaderSupports.GetAtlasShaderSupporter(m))).ToDictionary(i => i.m, i => i.Item2); + var material2AtlasTargets = supporters.Select(kv => (kv.Key, kv.Value.GetAtlasShaderTexture2D(kv.Key))).ToDictionary(i => i.Key, i => i.Item2.ToDictionary(p => p.PropertyName, p => p)); + MaterialToAtlasShaderDict = material2AtlasTargets; + AtlasShaderSupportUtils = shaderSupports; + if (usePropertyBake) + { + var materialGroupList = new List>>(); + foreach (var matKv in material2AtlasTargets) + { + var index = materialGroupList.FindIndex(matGroup => matGroup.All(m2 => PropEqual(m2.Value, matKv.Value))); + + if (index == -1) { materialGroupList.Add(new() { { matKv.Key, matKv.Value } }); } + else { materialGroupList[index].Add(matKv.Key, matKv.Value); } + } + + bool PropEqual(Dictionary propL, Dictionary propR) + { + + foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) + { + if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { continue; } + var l = propL[propName]; + var r = propR[propName]; + if (l.Texture2D == null || r.Texture2D == null) { continue; } + if (l.Texture2D != r.Texture2D) { return false; } + } + return true; + } + MaterialGroup = materialGroupList.Select(i => new OrderedHashSet(i.Keys)).ToArray(); + } + else + { + MaterialGroup = materialHash.Select(i => new OrderedHashSet() { i }).ToArray(); + } var TargetRenderers = inputRenderers.Where(r => r.sharedMaterials.Any(m => materialHash.Contains(m))).ToArray(); var normalizedMesh = SubVertNormalize(TargetRenderers); @@ -67,8 +107,20 @@ public AtlasContext(List TargetMaterials, List inputRenderer { var nmMesh = normalizedMesh[mkr.Key]; var renderer = mkr.First(r => r.sharedMaterials.Length == nmMesh.subMeshCount); + var bakedMesh = nmMesh; + + if (renderer is SkinnedMeshRenderer skinnedMeshRenderer) + { + var newMesh = new Mesh(); + var tempRenderer = UnityEngine.Object.Instantiate(skinnedMeshRenderer); + tempRenderer.sharedMesh = nmMesh; + tempRenderer.BakeMesh(newMesh); + bakedMesh = newMesh; + _bakedMesh.Add(newMesh); + UnityEngine.Object.DestroyImmediate(tempRenderer.gameObject); + } - m2md[nmMesh] = new MeshData(renderer, nmMesh, MeshData.GetMatrix(renderer)); + m2md[nmMesh] = new MeshData(renderer, bakedMesh, MeshData.GetMatrix(renderer)); } NormalizeMeshes = normalizedMesh; @@ -87,7 +139,7 @@ public AtlasContext(List TargetMaterials, List inputRenderer for (var si = 0; mats.Length > si; si += 1) { if (!materialHash.Contains(mats[si])) { continue; } - var matID = Array.FindIndex(Materials, i => i.Contains(mats[si])); + var matID = Array.FindIndex(MaterialGroup, i => i.Contains(mats[si])); var atSubData = atlasSubSet[si] = new(meshID, si, matID); AtlasSubAll.Add(atSubData.Value); } @@ -111,7 +163,7 @@ public AtlasContext(List TargetMaterials, List inputRenderer //Cross SubMesh Island Marge - foreach (var atSubGroup in AtlasSubAll.GroupBy(i => (i.MeshID, i.MaterialID))) + foreach (var atSubGroup in AtlasSubAll.GroupBy(i => (i.MeshID, i.MaterialGroupID))) { var atSubCrossTarget = atSubGroup.ToArray(); Array.Sort(atSubCrossTarget, (l, r) => l.SubMeshIndex - r.SubMeshIndex); @@ -386,6 +438,8 @@ Mesh NormalizedMesh(Mesh mesh, int expandSlot) public void Dispose() { foreach (var md in MeshDataDict) { md.Value.Dispose(); } + foreach (var mesh in _bakedMesh) { UnityEngine.Object.DestroyImmediate(mesh); } + AtlasShaderSupportUtils.Dispose(); } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs index aa31b318..74786f6e 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject @@ -12,12 +13,30 @@ public class AtlasShaderSupportScriptableObject : ScriptableObject public List AtlasTargetDefines; public Shader BakeShader; [SerializeReference] public List AtlasMaterialPostProses = new(); + + + public List GetAtlasShaderTexture2D(Material material) + { + var atlasTex = new List(); + foreach (var atlasTargetDefine in AtlasTargetDefines) + { + var constraint = atlasTargetDefine.AtlasDefineConstraints; + if (!constraint.Constraints(material)) { continue; } + var asTex = new AtlasShaderTexture2D(); + var tex = material.GetTexture(atlasTargetDefine.TexturePropertyName) as Texture2D; + asTex.Texture2D = tex; + asTex.PropertyName = atlasTargetDefine.TexturePropertyName; + asTex.BakeProperties = atlasTargetDefine.BakePropertyNames.Select(s => BakeProperty.GetBakeProperty(material, s)).ToList(); + atlasTex.Add(asTex); + } + return atlasTex; + } } [Serializable] public class AtlasTargetDefine { public string TexturePropertyName; - [SerializeReference] public IAtlasDefineConstraints AtlasDefineConstraints = new FloatPropertyValueGreater(); + [SerializeReference] public IAtlasDefineConstraints AtlasDefineConstraints = new Anything(); public List BakePropertyNames; } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs index 56749138..073cd499 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs @@ -47,6 +47,19 @@ public static bool ValueComparer(BakeProperty l, BakeProperty r) return false; } } + + public static BakeProperty GetBakeProperty(Material material, string propertyName) + { + var propIndex = material.shader.FindPropertyIndex(propertyName); + switch (material.shader.GetPropertyType(propIndex)) + { + case UnityEngine.Rendering.ShaderPropertyType.Float: { return new BakeFloat() { PropertyName = propertyName, Float = material.GetFloat(propertyName) }; } + case UnityEngine.Rendering.ShaderPropertyType.Range: { return new BakeRange() { PropertyName = propertyName, Float = material.GetFloat(propertyName), MinMax = material.shader.GetPropertyRangeLimits(propIndex) }; } + case UnityEngine.Rendering.ShaderPropertyType.Color: { return new BakeColor() { PropertyName = propertyName, Color = material.GetColor(propertyName)}; } + case UnityEngine.Rendering.ShaderPropertyType.Vector: { return new BakeVector() { PropertyName = propertyName, Vector = material.GetVector(propertyName)}; } + default: { return null; } + } + } } [Serializable] public class BakeFloat : BakeProperty { public float Float; } @@ -54,4 +67,5 @@ public class BakeFloat : BakeProperty { public float Float; } public class BakeRange : BakeProperty { public float Float; public Vector2 MinMax; } [Serializable] public class BakeColor : BakeProperty { public Color Color; } + public class BakeVector : BakeProperty { public Vector4 Vector; } } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs index e34ef510..39b293bb 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs @@ -37,7 +37,7 @@ public class FloatPropertyValueGreater : IAtlasDefineConstraints public bool Less; public bool Constraints(Material material) { - return !Less ? material.GetFloat(PropertyName) > ComparerValue : material.GetFloat(PropertyName) < ComparerValue; + return !Less ? material.GetFloat(PropertyName) > ComparerValue : material.GetFloat(PropertyName) < ComparerValue; } } [Serializable] @@ -52,6 +52,28 @@ public bool Constraints(Material material) } } [Serializable] + public class IntPropertyValueGreater : IAtlasDefineConstraints + { + public string PropertyName; + public int ComparerValue = 0; + public bool Less; + public bool Constraints(Material material) + { + return !Less ? material.GetInt(PropertyName) > ComparerValue : material.GetInt(PropertyName) < ComparerValue; + } + } + [Serializable] + public class IntPropertyValueEqual : IAtlasDefineConstraints + { + public string PropertyName; + public int Value; + public bool NotEqual; + public bool Constraints(Material material) + { + return (material.GetInt(PropertyName) == Value) == !NotEqual; + } + } + [Serializable] public class ShaderNameContains : IAtlasDefineConstraints { public string Name; diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs index 40fffded..ad68cd8a 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/ISupportedShaderComparer.cs @@ -19,4 +19,9 @@ public class ShaderReference : ISupportedShaderComparer public Shader Shader; public bool ThisSupported(Material material) { return material.shader == Shader; } } + + internal class AnythingShader : ISupportedShaderComparer + { + public bool ThisSupported(Material material) => true; + } } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index fa9421f5..d380d92a 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -2,73 +2,99 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; using UnityEngine; using TexLU = net.rs64.TexTransCore.BlendTexture.TextureBlend; using TexUT = net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.TextureAtlas { - internal class AtlasShaderSupportUtils + internal class AtlasShaderSupportUtils : IDisposable { - AtlasDefaultShaderSupport _defaultShaderSupport; - List _shaderSupports; + public List atlasShaderSupportList; + AtlasShaderSupportScriptableObject _defaultSupport; - public PropertyBakeSetting BakeSetting = PropertyBakeSetting.NotBake; - public AtlasShaderSupportUtils() + internal AtlasShaderSupportUtils() { - _defaultShaderSupport = new AtlasDefaultShaderSupport(); - _shaderSupports = InterfaceUtility.GetInterfaceInstance(new Type[] { typeof(AtlasDefaultShaderSupport) }).ToList(); +#if UNITY_EDITOR // TODO : これ何とかしないといけない + atlasShaderSupportList = UnityEditor.AssetDatabase.GetAllAssetPaths() + .Where(i => UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(i) == typeof(AtlasShaderSupportScriptableObject)) + .Select(i => UnityEditor.AssetDatabase.LoadAssetAtPath(i)) + .ToList(); +#endif + _defaultSupport = ScriptableObject.CreateInstance(); + _defaultSupport.SupportedShaderComparer = new AnythingShader(); + _defaultSupport.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything() } }; + atlasShaderSupportList.Add(_defaultSupport); } - public void AddRecord(Material material) - { - var supportShaderI = FindSupportI(material); - if (supportShaderI != null) - { - supportShaderI.AddRecord(material); - } - } - public void ClearRecord() - { - foreach (var i in _shaderSupports) - { - i.ClearRecord(); - } - } + public void Dispose() { UnityEngine.Object.DestroyImmediate(_defaultSupport); } - public List GetTextures(Material material, ITextureManager textureManager) + public AtlasShaderSupportScriptableObject GetAtlasShaderSupporter(Material mat) { - List allTex; - var supportShaderI = FindSupportI(material); - - if (supportShaderI != null) { allTex = supportShaderI.GetPropertyAndTextures(textureManager, material, BakeSetting); } - else { allTex = _defaultShaderSupport.GetPropertyAndTextures(textureManager, material, BakeSetting); } - - var textures = new List(); - foreach (var tex in allTex) - { - if (tex.Texture != null) - { - textures.Add(tex); - } - } - - return textures; - } - public void MaterialCustomSetting(Material material) - { - var supportShaderI = FindSupportI(material); - if (supportShaderI != null) - { - supportShaderI.MaterialCustomSetting(material); - } - } - public IAtlasShaderSupport FindSupportI(Material material) - { - return _shaderSupports.Find(i => { return i.IsThisShader(material); }); + return atlasShaderSupportList.First(i => i.SupportedShaderComparer.ThisSupported(mat)); } + + // AtlasDefaultShaderSupport _defaultShaderSupport; + // List _shaderSupports; + + // public PropertyBakeSetting BakeSetting = PropertyBakeSetting.NotBake; + // public AtlasShaderSupportUtils() + // { + // _defaultShaderSupport = new AtlasDefaultShaderSupport(); + // _shaderSupports = InterfaceUtility.GetInterfaceInstance(new Type[] { typeof(AtlasDefaultShaderSupport) }).ToList(); + // } + + // public void AddRecord(Material material) + // { + // var supportShaderI = FindSupportI(material); + // if (supportShaderI != null) + // { + // supportShaderI.AddRecord(material); + // } + // } + // public void ClearRecord() + // { + // foreach (var i in _shaderSupports) + // { + // i.ClearRecord(); + // } + // } + + // public List GetTextures(Material material, ITextureManager textureManager) + // { + // List allTex; + // var supportShaderI = FindSupportI(material); + + // if (supportShaderI != null) { allTex = supportShaderI.GetPropertyAndTextures(textureManager, material, BakeSetting); } + // else { allTex = _defaultShaderSupport.GetPropertyAndTextures(textureManager, material, BakeSetting); } + + // var textures = new List(); + // foreach (var tex in allTex) + // { + // if (tex.Texture != null) + // { + // textures.Add(tex); + // } + // } + + // return textures; + // } + // public void MaterialCustomSetting(Material material) + // { + // var supportShaderI = FindSupportI(material); + // if (supportShaderI != null) + // { + // supportShaderI.MaterialCustomSetting(material); + // } + // } + // public IAtlasShaderSupport FindSupportI(Material material) + // { + // return _shaderSupports.Find(i => { return i.IsThisShader(material); }); + // } } + internal class AtlasShaderRecorder { Dictionary propRecords = new Dictionary(); diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader index b8be66dc..225370ab 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader @@ -49,7 +49,7 @@ Shader "Hidden/lilToonAtlasBaker" // NormalMap _UseBumpMap ("sNormalMap", Int) = 0 - _BumpMap ("Normal Map", 2D) = "bump" {} + [Normal] _BumpMap ("Normal Map", 2D) = "bump" {} _BumpScale ("Scale", Range(-10,10)) = 1 //---------------------------------------------------------------------------------------------------------------------- @@ -57,7 +57,7 @@ Shader "Hidden/lilToonAtlasBaker" _UseBump2ndMap ("sNormalMap2nd", Int) = 0 _Bump2ndMap_UVMode ("UV Mode|UV0|UV1|UV2|UV3", Int) = 0 - _Bump2ndMap ("Normal Map", 2D) = "bump" {} + [Normal] _Bump2ndMap ("Normal Map", 2D) = "bump" {} _Bump2ndScale ("Scale", Range(-10,10)) = 1 _Bump2ndScaleMask ("Mask", 2D) = "white" {} @@ -130,7 +130,7 @@ Shader "Hidden/lilToonAtlasBaker" _MatCapCustomNormal ("sMatCapCustomNormal", Int) = 0 - _MatCapBumpMap ("Normal Map", 2D) = "bump" {} + [Normal] _MatCapBumpMap ("Normal Map", 2D) = "bump" {} _MatCapBumpScale ("Scale", Range(-10,10)) = 1 @@ -145,7 +145,7 @@ Shader "Hidden/lilToonAtlasBaker" _MatCap2ndCustomNormal ("sMatCapCustomNormal", Int) = 0 - _MatCap2ndBumpMap ("Normal Map", 2D) = "bump" {} + [Normal] _MatCap2ndBumpMap ("Normal Map", 2D) = "bump" {} _MatCap2ndBumpScale ("Scale", Range(-10,10)) = 1 //---------------------------------------------------------------------------------------------------------------------- @@ -224,7 +224,7 @@ Shader "Hidden/lilToonAtlasBaker" #pragma vertex vert #pragma fragment frag - #pragma multi_compile_fragment // TODO + #pragma multi_compile_fragment_local Bake_MainTex Bake_Main2ndTex Bake_Main3rdTex Bake_AlphaMask Bake_BumpMap Bake_Bump2ndMap Bake_AnisotropyScaleMask Bake_BacklightColorTex Bake_ShadowStrengthMask Bake_ShadowColorTex Bake_Shadow2ndColorTex Bake_Shadow3rdColorTex Bake_RimShadeMask Bake_SmoothnessTex Bake_MetallicGlossMap Bake_ReflectionColorTex Bake_MatCapBlendMask Bake_MatCapBumpMap Bake_MatCap2ndBlendMask Bake_MatCap2ndBumpMap Bake_RimColorTex Bake_GlitterColorTex Bake_EmissionMap Bake_EmissionBlendMask Bake_Emission2ndMap Bake_Emission2ndBlendMask Bake_ParallaxMap Bake_OutlineTex Bake_OutlineWidthMask Bake_OutlineVectorTex #include "UnityCG.cginc" @@ -241,7 +241,138 @@ Shader "Hidden/lilToonAtlasBaker" }; sampler2D _MainTex; - float4 _MainTex_ST; + float4 _Color; + float4 _MainTexHSVG; + + sampler2D _MainColorAdjustMask; + + sampler2D _Main2ndTex; + float4 _Color2nd; + + sampler2D _Main2ndBlendMask; + + sampler2D _Main2ndDissolveMask; + + sampler2D _Main3rdTex; + float4 _Color3rd; + + sampler2D _Main3rdBlendMask; + + sampler2D _Main3rdDissolveNoiseMask; + + sampler2D _AlphaMask; + float _AlphaMaskScale; + float _AlphaMaskValue; + + sampler2D _BumpMap; + float _BumpScale; + + sampler2D _Bump2ndMap; + float _Bump2ndScale; + sampler2D _Bump2ndScaleMask; + + sampler2D _AnisotropyTangentMap; + + sampler2D _AnisotropyScaleMask; + float _AnisotropyScale; + + sampler2D _BacklightColorTex; + float4 _BacklightColor; + + sampler2D _ShadowStrengthMask; + float _ShadowStrength; + + sampler2D _ShadowBorderMask; + + sampler2D _ShadowBlurMask; + + sampler2D _ShadowColorTex; + float4 _ShadowColor; + + sampler2D _Shadow2ndColorTex; + float4 _Shadow2ndColor; + + sampler2D _Shadow3rdColorTex; + float4 _Shadow3rdColor; + + sampler2D _RimShadeMask; + float4 _RimShadeColor; + + sampler2D _SmoothnessTex; + float _Smoothness; + + sampler2D _MetallicGlossMap; + float _Metallic; + + sampler2D _ReflectionColorTex; + float4 _ReflectionColor; + + sampler2D _MatCapBumpMap; + float _MatCapBlend; + + sampler2D _MatCap2ndBlendMask; + float _MatCapBlend; + + sampler2D _MatCap2ndBumpMap; + float _MatCapBumpScale; + + sampler2D _RimColorTex; + float4 _RimColor; + + sampler2D _GlitterColorTex; + float4 _GlitterColor; + + sampler2D _EmissionMap; + float4 _EmissionColor; + + sampler2D _EmissionBlendMask; + float _EmissionBlend; + + sampler2D _Emission2ndMap; + float4 _Emission2ndColor; + + sampler2D _Emission2ndBlendMask; + float _Emission2ndBlend; + + sampler2D _ParallaxMap; + float _Parallax; + + sampler2D _OutlineTex; + float4 _OutlineColor; + float4 _OutlineTexHSVG; + + sampler2D _OutlineWidthMask; + float _OutlineWidth; + float _OutlineWidth_MaxValue; + + sampler2D _OutlineVectorTex; + float _OutlineVectorScale; + + float3 lilToneCorrection(float3 c, float4 hsvg) + { + // gamma + c = pow(abs(c), hsvg.w); + // rgb -> hsv + float4 p = (c.b > c.g) ? float4(c.bg,-1.0,2.0/3.0) : float4(c.gb,0.0,-1.0/3.0); + float4 q = (p.x > c.r) ? float4(p.xyw, c.r) : float4(c.r, p.yzx); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + float3 hsv = float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); + // shift + hsv = float3(hsv.x+hsvg.x,saturate(hsv.y*hsvg.y),saturate(hsv.z*hsvg.z)); + // hsv -> rgb + return hsv.z - hsv.z * hsv.y + hsv.z * hsv.y * saturate(abs(frac(hsv.x + float3(1.0, 2.0/3.0, 1.0/3.0)) * 6.0 - 3.0) - 1.0); + } + + + + + + + + + + v2f vert (appdata v) { @@ -253,11 +384,75 @@ Shader "Hidden/lilToonAtlasBaker" float4 frag (v2f i) : SV_Target { - float4 col = tex2D(_MainTex, i.uv); - - // TODO - +#if Bake_MainTex + float4 col = tex2D(_MainTex ,i.uv); + float3 tcCol = lilToneCorrection(col.rgb,_MainTexHSVG); + col.rgb = lerp(tcCol , col.rgb tex2D(_MainColorAdjustMask,i.uv)); + col *= _Color; + return col; +#elif Bake_Main2ndTex + return tex2D(_Main2ndTex ,i.uv) * _Color2nd; +#elif Bake_Main3rdTex + return tex2D(_Main3rdTex ,i.uv) * _Color3rd; +#elif Bake_AlphaMask + return saturate(tex2D(_AlphaMask ,i.uv) * _AlphaMaskScale + _AlphaMaskValue); +#elif Bake_BumpMap + return tex2D(_BumpMap,i.uv);//いつかやるかもしれないかも +#elif Bake_Bump2ndMap + return tex2D(_Bump2ndMap,i.uv); +#elif Bake_AnisotropyScaleMask + return tex2D(_AnisotropyTangentMap,i.uv); +#elif Bake_BacklightColorTex + return tex2D(_BacklightColorTex,i.uv) * _BacklightColor; +#elif Bake_ShadowStrengthMask + return tex2D(_ShadowStrengthMask,i.uv) * _ShadowStrength; +#elif Bake_ShadowColorTex + return tex2D(_ShadowColorTex,i.uv) * _ShadowColor; +#elif Bake_Shadow2ndColorTex + return tex2D(_Shadow2ndColorTex,i.uv) * _Shadow2ndColor; +#elif Bake_Shadow3rdColorTex + return tex2D(_Shadow3rdColorTex,i.uv) * _Shadow3rdColor; +#elif Bake_RimShadeMask + return tex2D(_RimShadeMask,i.uv) * _RimShadeColor; +#elif Bake_SmoothnessTex + return tex2D(_SmoothnessTex,i.uv) * _Smoothness; +#elif Bake_MetallicGlossMap + return tex2D(_MetallicGlossMap,i.uv) * _Metallic; +#elif Bake_ReflectionColorTex + return tex2D(_ReflectionColorTex,i.uv) * _ReflectionColor; +#elif Bake_MatCapBlendMask + return tex2D(_MatCapBlendMask,i.uv) * _MatCapBlend; +#elif Bake_MatCapBumpMap + return tex2D(_MatCapBumpMap,i.uv); +#elif Bake_MatCap2ndBlendMask + return tex2D(_MatCap2ndBlendMask,i.uv) * _MatCap2ndBlend; +#elif Bake_MatCap2ndBumpMap + return tex2D(_MatCap2ndBumpMap,i.uv); +#elif Bake_RimColorTex + return tex2D(_RimColorTex,i.uv) * _RimColor; +#elif Bake_GlitterColorTex + return tex2D(_GlitterColorTex,i.uv) * _GlitterColor; +#elif Bake_EmissionMap + return tex2D(_EmissionMap,i.uv) * _EmissionColor; +#elif Bake_EmissionBlendMask + return tex2D(_EmissionBlendMask,i.uv) * _EmissionBlend; +#elif Bake_Emission2ndMap + return tex2D(_Emission2ndMap,i.uv) * _Emission2ndColor; +#elif Bake_Emission2ndBlendMask + return tex2D(_Emission2ndBlendMask,i.uv) * _Emission2ndBlend; +#elif Bake_ParallaxMap + return tex2D(_ParallaxMap,i.uv); +#elif Bake_OutlineTex + float4 col = tex2D(_OutlineTex ,i.uv); + float3 tcCol = lilToneCorrection(col.rgb,_OutlineTexHSVG); + col.rgb = tcCol; + col *= _OutlineColor; return col; +#elif Bake_OutlineWidthMask + return tex2D(_OutlineWidthMask ,i.uv) * (_OutlineWidth / _OutlineWidth_MaxValue); +#elif Bake_OutlineVectorTex + return tex2D(_OutlineVectorTex ,i.uv); +#endif } ENDHLSL } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index 9ca762c1..111ab8f6 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -50,13 +50,13 @@ MonoBehaviour: BakePropertyNames: [] - TexturePropertyName: _AlphaMask AtlasDefineConstraints: - rid: 7150698656081904333 + rid: 7150698705470881809 BakePropertyNames: - _AlphaMaskScale - _AlphaMaskValue - TexturePropertyName: _BumpMap AtlasDefineConstraints: - rid: 7150698656081904351 + rid: 7150698705470881810 BakePropertyNames: - _BumpScale - TexturePropertyName: _Bump2ndMap @@ -71,69 +71,69 @@ MonoBehaviour: BakePropertyNames: [] - TexturePropertyName: _AnisotropyTangentMap AtlasDefineConstraints: - rid: 7150698656081904360 + rid: 7150698705470881815 BakePropertyNames: [] - TexturePropertyName: _AnisotropyScaleMask AtlasDefineConstraints: - rid: 7150698656081904324 + rid: 7150698705470881816 BakePropertyNames: - _AnisotropyScale - TexturePropertyName: _BacklightColorTex AtlasDefineConstraints: - rid: 7150698656081904325 + rid: 7150698705470881817 BakePropertyNames: - _BacklightColor - TexturePropertyName: _ShadowStrengthMask AtlasDefineConstraints: - rid: 7150698656081904316 + rid: 7150698705470881818 BakePropertyNames: - _ShadowStrength - TexturePropertyName: _ShadowBorderMask AtlasDefineConstraints: - rid: 7150698656081904361 + rid: 7150698705470881819 BakePropertyNames: [] - TexturePropertyName: _ShadowBlurMask AtlasDefineConstraints: - rid: 7150698656081904362 + rid: 7150698705470881820 BakePropertyNames: [] - TexturePropertyName: _ShadowColorTex AtlasDefineConstraints: - rid: 7150698656081904317 + rid: 7150698705470881821 BakePropertyNames: - _ShadowColor - TexturePropertyName: _Shadow2ndColorTex AtlasDefineConstraints: - rid: 7150698656081904318 + rid: 7150698705470881822 BakePropertyNames: - _Shadow2ndColor - TexturePropertyName: _Shadow3rdColorTex AtlasDefineConstraints: - rid: 7150698656081904319 + rid: 7150698705470881823 BakePropertyNames: - _Shadow3rdColor - TexturePropertyName: _RimShadeMask AtlasDefineConstraints: - rid: 7150698656081904363 + rid: 7150698705470881824 BakePropertyNames: - _RimShadeColor - TexturePropertyName: _SmoothnessTex AtlasDefineConstraints: - rid: 7150698656081904326 + rid: 7150698705470881825 BakePropertyNames: - _Smoothness - TexturePropertyName: _MetallicGlossMap AtlasDefineConstraints: - rid: 7150698656081904327 + rid: 7150698705470881826 BakePropertyNames: - _Metallic - TexturePropertyName: _ReflectionColorTex AtlasDefineConstraints: - rid: 7150698656081904328 + rid: 7150698705470881827 BakePropertyNames: - _ReflectionColor - TexturePropertyName: _MatCapBlendMask AtlasDefineConstraints: - rid: 7150698656081904329 + rid: 7150698705470881828 BakePropertyNames: - _MatCapBlend - TexturePropertyName: _MatCapBumpMap @@ -143,7 +143,7 @@ MonoBehaviour: - _MatCapBumpScale - TexturePropertyName: _MatCap2ndBlendMask AtlasDefineConstraints: - rid: 7150698656081904330 + rid: 7150698705470881831 BakePropertyNames: - _MatCap2ndBlend - TexturePropertyName: _MatCap2ndBumpMap @@ -153,7 +153,7 @@ MonoBehaviour: - _MatCap2ndBumpScale - TexturePropertyName: _RimColorTex AtlasDefineConstraints: - rid: 7150698656081904331 + rid: 7150698705470881834 BakePropertyNames: - _RimColor - TexturePropertyName: _GlitterColorTex @@ -183,7 +183,7 @@ MonoBehaviour: - _Emission2ndBlend - TexturePropertyName: _ParallaxMap AtlasDefineConstraints: - rid: 7150698656081904387 + rid: 7150698705470881845 BakePropertyNames: - _Parallax - TexturePropertyName: _OutlineTex @@ -199,7 +199,7 @@ MonoBehaviour: - _OutlineWidth - TexturePropertyName: _OutlineVectorTex AtlasDefineConstraints: - rid: 7150698656081904388 + rid: 7150698705470881846 BakePropertyNames: - _OutlineVectorScale BakeShader: {fileID: 0} @@ -244,437 +244,437 @@ MonoBehaviour: type: {class: Anything, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - - rid: 7150698656081904316 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - PropertyName: _UseShadow - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904317 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698656081904335 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseShadow - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904318 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881799 + - rid: 7150698705470881800 + - rid: 7150698656081904338 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseShadow - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904319 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881801 + - rid: 7150698705470881802 + - rid: 7150698656081904341 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseShadow - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904324 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881803 + - rid: 7150698705470881804 + - rid: 7150698656081904345 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseAnisotropy - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904325 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881805 + - rid: 7150698705470881806 + - rid: 7150698656081904348 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseBacklight - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904326 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881807 + - rid: 7150698705470881808 + - rid: 7150698656081904353 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseReflection - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904327 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881813 + - rid: 7150698705470881814 + - rid: 7150698656081904357 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseReflection - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904328 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881811 + - rid: 7150698705470881812 + - rid: 7150698656081904366 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseReflection - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904329 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881832 + - rid: 7150698705470881833 + - rid: 7150698656081904369 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseMatCap - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904330 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881829 + - rid: 7150698705470881830 + - rid: 7150698656081904372 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseMatCap - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904331 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881835 + - rid: 7150698705470881836 + - rid: 7150698656081904375 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseRim - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904333 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881837 + - rid: 7150698705470881838 + - rid: 7150698656081904378 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _AlphaMaskMode - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904335 + AtlasDefineConstraints: + - rid: 7150698705470881839 + - rid: 7150698705470881840 + - rid: 7150698656081904381 type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: AtlasDefineConstraints: - - rid: 7150698656081904337 - - rid: 7150698656081904336 - - rid: 7150698656081904336 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881841 + - rid: 7150698705470881842 + - rid: 7150698656081904384 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _Main2ndTex_UVMode - ComparerValue: 0.5 - Less: 1 - - rid: 7150698656081904337 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + AtlasDefineConstraints: + - rid: 7150698705470881843 + - rid: 7150698705470881844 + - rid: 7150698705470881799 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMain2ndTex - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904338 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881800 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - AtlasDefineConstraints: - - rid: 7150698656081904339 - - rid: 7150698656081904340 - - rid: 7150698656081904339 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + PropertyName: _Main2ndTex_UVMode + ComparerValue: 1 + Less: 1 + - rid: 7150698705470881801 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMain2ndTex - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904340 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881802 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Main2ndTex_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904341 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904343 - - rid: 7150698656081904344 - - rid: 7150698656081904343 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881803 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMain2ndTex - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904344 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881804 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Main2ndTex_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904345 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904346 - - rid: 7150698656081904347 - - rid: 7150698656081904346 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881805 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMain3rdTex - ComparerValue: 0.5 - Less: 0 - - rid: 7150698656081904347 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + ComparerValue: 0 + Less: 1 + - rid: 7150698705470881806 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Main3rdTex_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904348 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904349 - - rid: 7150698656081904350 - - rid: 7150698656081904349 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881807 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMain3rdTex - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904350 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881808 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Main3rdTex_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904351 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881809 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseBumpMap - ComparerValue: 0.5 + PropertyName: _AlphaMaskMode + ComparerValue: 0 Less: 0 - - rid: 7150698656081904353 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881810 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - AtlasDefineConstraints: - - rid: 7150698656081904354 - - rid: 7150698656081904355 - - rid: 7150698656081904354 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + PropertyName: _UseBumpMap + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881811 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseBump2ndMap - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904355 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881812 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Bump2ndMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904357 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904358 - - rid: 7150698656081904359 - - rid: 7150698656081904358 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881813 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseBump2ndMap - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904359 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881814 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Bump2ndMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904360 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881815 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseAnisotropy + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881816 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseAnisotropy - ComparerValue: 0.5 + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881817 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBacklight + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881818 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseBacklight + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881819 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881820 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0 Less: 0 - - rid: 7150698656081904361 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881821 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseShadow - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904362 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881822 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseShadow - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904363 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881823 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseShadow + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881824 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseRimShade - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904366 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881825 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - AtlasDefineConstraints: - - rid: 7150698656081904367 - - rid: 7150698656081904368 - - rid: 7150698656081904367 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + PropertyName: _UseRimShade + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881826 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseMatCap2nd - ComparerValue: 0.5 + PropertyName: _UseRimShade + ComparerValue: 0 Less: 0 - - rid: 7150698656081904368 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881827 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _MatCap2ndCustomNormal - ComparerValue: 0.5 + PropertyName: _UseRimShade + ComparerValue: 0 Less: 0 - - rid: 7150698656081904369 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881828 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - AtlasDefineConstraints: - - rid: 7150698656081904371 - - rid: 7150698656081904370 - - rid: 7150698656081904370 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + PropertyName: _UseMatCap + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881829 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap2nd + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881830 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _MatCapCustomNormal - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904371 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881831 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseMatCap + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881832 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseMatCap2nd - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904372 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881833 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - AtlasDefineConstraints: - - rid: 7150698656081904373 - - rid: 7150698656081904374 - - rid: 7150698656081904373 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + PropertyName: _MatCap2ndCustomNormal + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881834 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _UseRim + ComparerValue: 0 + Less: 0 + - rid: 7150698705470881835 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseGlitter - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904374 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881836 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _GlitterColorTex_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904375 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904376 - - rid: 7150698656081904377 - - rid: 7150698656081904376 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881837 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseEmission - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904377 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881838 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _EmissionMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904378 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904379 - - rid: 7150698656081904380 - - rid: 7150698656081904379 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881839 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseEmission - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904380 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881840 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _EmissionMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904381 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904382 - - rid: 7150698656081904383 - - rid: 7150698656081904382 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881841 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseEmission2nd - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904383 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881842 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Emission2ndMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904384 - type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - AtlasDefineConstraints: - - rid: 7150698656081904385 - - rid: 7150698656081904386 - - rid: 7150698656081904385 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881843 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseEmission2nd - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904386 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881844 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _Emission2ndMap_UVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 - - rid: 7150698656081904387 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881845 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _UseParallax - ComparerValue: 0.5 + ComparerValue: 0 Less: 0 - - rid: 7150698656081904388 - type: {class: FloatPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + - rid: 7150698705470881846 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: PropertyName: _OutlineVectorUVMode - ComparerValue: 0.5 + ComparerValue: 1 Less: 1 diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index ed1ea3d9..5e48e6ac 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -12,6 +12,8 @@ using net.rs64.TexTransTool.TextureAtlas.IslandRelocator; using UnityEngine.Serialization; using Unity.Collections; +using Unity.Mathematics; +using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; namespace net.rs64.TexTransTool.TextureAtlas { @@ -83,7 +85,7 @@ MeshAndMatRef MeshReferenceとマテリアルスロット分のMaterialReference struct AtlasData { - public List Textures; + public Dictionary Textures; public List Meshes; public List AtlasInMaterials; public HashSet[] MaterialID; @@ -127,20 +129,22 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) atlasData.AtlasInMaterials = targetMaterials; var atlasSetting = AtlasSetting; + var propertyBakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; // var atlasReferenceData = new AtlasReferenceData(targetMaterials, Renderers); - var atlasContext = new AtlasContext(targetMaterials, Renderers); - var shaderSupports = new AtlasShaderSupportUtils(); + var atlasContext = new AtlasContext(targetMaterials, Renderers, propertyBakeSetting != PropertyBakeSetting.NotBake); + //サブメッシュより多いスロットの存在可否 // if (atlasReferenceData.AtlasMeshDataList.Any(i => i.Triangles.Count < i.MaterialIndex.Length)) { TTTRuntimeLog.Warning("AtlasTexture:error:MoreMaterialSlotThanSubMesh"); } //ターゲットとなるマテリアルやそのマテリアルが持つテクスチャを引き出すフェーズ - shaderSupports.BakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; - var materialTextures = new Dictionary>(); - foreach (var mat in targetMaterials) { shaderSupports.AddRecord(mat); } - foreach (var mat in targetMaterials) { materialTextures[mat] = shaderSupports.GetTextures(mat, texManage); } - shaderSupports.ClearRecord(); + // shaderSupports.BakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; + // var materialTextures = new Dictionary>(); + // foreach (var mat in targetMaterials) { shaderSupports.AddRecord(mat); } + // foreach (var mat in targetMaterials) { materialTextures[mat] = shaderSupports.GetTextures(mat, texManage); } + + var islandSizeOffset = GetTextureSizeOffset(SelectMatList.Select(i => i.Material), atlasSetting); @@ -149,8 +153,8 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) { foreach (var islandKV in atlasContext.IslandDict) { - var material = materialTextures[atlasContext.Materials[islandKV.Key.MaterialID].First()]; - var refTex = material.FirstOrDefault(i => i.PropertyName == "_MainTex")?.Texture; + var material = atlasContext.MaterialToAtlasShaderDict[atlasContext.MaterialGroup[islandKV.Key.MaterialGroupID].First()]; + var refTex = material.TryGetValue("_MainTex", out var tex2D) ? tex2D.Texture2D : null; if (refTex == null) { continue; } foreach (var island in islandKV.Value) { @@ -180,25 +184,51 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) islandDescription[i] = new IslandSelector.IslandDescription(vertex, uv, renderer, atlasContext.IslandSubData[i].SubMeshIndex); } - foreach (var mat in SelectMatList) + for (var i = 0; rectArray.Length > i; i += 1) { - var textureSizeOffSet = islandSizeOffset[mat.Material]; - for (var i = 0; rectArray.Length > i; i += 1) + var desc = islandDescription[i]; + var mat = desc.Renderer.sharedMaterials[desc.MaterialSlot]; + var materialGroupID = Array.FindIndex(atlasContext.MaterialGroup, i => i.Any(m => m == mat)); + if (materialGroupID == -1) { continue; } + var group = atlasContext.MaterialGroup[materialGroupID]; + var targets = SelectMatList.Where(i => group.Any(m => domain.OriginEqual(m, i.Material))); + + var materialFineTuningValue = 0f; + var count = 0; + foreach (var selector in targets) { - var desc = islandDescription[i]; - var matSlotRef = desc.MaterialSlot; - if (!domain.OriginEqual(desc.Renderer.sharedMaterials[matSlotRef], mat.Material)) { continue; } - - rectArray[i].Size *= textureSizeOffSet; + materialFineTuningValue += selector.MaterialFineTuningValue; + count += 1; + } + materialFineTuningValue /= count; - switch (MaterialToIslandFineTuningModeSelect) - { - case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= mat.MaterialFineTuningValue; break; } - case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = mat.MaterialFineTuningValue; break; } - default: break; - } + switch (MaterialToIslandFineTuningModeSelect) + { + case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= materialFineTuningValue; break; } + case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = materialFineTuningValue; break; } + default: break; } + } + // foreach (var mat in SelectMatList) + // { + // var textureSizeOffSet = islandSizeOffset[mat.Material]; + // for (var i = 0; rectArray.Length > i; i += 1) + // { + // var desc = islandDescription[i]; + // var matSlotRef = desc.MaterialSlot; + // if (!domain.OriginEqual(desc.Renderer.sharedMaterials[matSlotRef], mat.Material)) { continue; } + + // rectArray[i].Size *= textureSizeOffSet; + + // switch (MaterialToIslandFineTuningModeSelect) + // { + // case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= mat.MaterialFineTuningValue; break; } + // case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = mat.MaterialFineTuningValue; break; } + // default: break; + // } + // } + // } foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, rectArray, islandArray, islandDescription, domain); } for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = Mathf.Clamp01(sizePriority[i]); } @@ -354,15 +384,31 @@ void ScaleApplyUp(float scaleUpStep) if (AtlasSetting.WriteOriginalUV) { newMesh.SetUVs(1, meshData.VertexUV); } subSetMovedUV[subSetIndex] = movedUV; - compiledMeshes.Add(new AtlasData.AtlasMeshAndDist(distMesh, newMesh, subSet.Select(i => i?.MaterialID ?? -1).ToArray())); + compiledMeshes.Add(new AtlasData.AtlasMeshAndDist(distMesh, newMesh, subSet.Select(i => i?.MaterialGroupID ?? -1).ToArray())); } atlasData.Meshes = compiledMeshes; //アトラス化したテクスチャーを生成するフェーズ - var compiledAtlasTextures = new List(); + var compiledAtlasTextures = new Dictionary(); + + var propertyNames = atlasContext.MaterialToAtlasShaderDict.Values.SelectMany(i => i.Keys).ToHashSet(); + var groupedTextures = atlasContext.MaterialGroup + .Select(mg => (Array.IndexOf(atlasContext.MaterialGroup, mg), mg.Select(m => atlasContext.MaterialToAtlasShaderDict[m]))) + .Select(mg => (mg.Item1, ZipDict(mg.Item2))) + .ToDictionary(i => i.Item1, i => i.Item2); + + Dictionary ZipDict(IEnumerable> keyValuePairs) + { + var dict = new Dictionary(); + foreach (var kv in keyValuePairs.SelectMany(i => i)) + { + if (kv.Value.Texture2D == null) { continue; } + dict[kv.Key] = kv.Value.Texture2D; + } + return dict; + } - var propertyNames = materialTextures.Values.SelectMany(i => i).Select(i => i.PropertyName).ToHashSet(); foreach (var propName in propertyNames) @@ -370,17 +416,18 @@ void ScaleApplyUp(float scaleUpStep) var targetRT = RenderTexture.GetTemporary(atlasSetting.AtlasTextureSize, atlasTextureHeightSize, 32); targetRT.Clear(); targetRT.name = "AtlasTex" + propName; - foreach (var MatPropKV in materialTextures) + foreach (var gTex in groupedTextures) { - var souseProp2Tex = MatPropKV.Value.Find(I => I.PropertyName == propName); - if (souseProp2Tex == null) continue; - var souseTex = souseProp2Tex.Texture is Texture2D ? texManage.GetOriginTempRt(souseProp2Tex.Texture as Texture2D, souseProp2Tex.Texture.width) : souseProp2Tex.Texture; + // var souseProp2Tex = gTex.MatPropKV.Value.Find(I => I.PropertyName == propName); + // if (souseProp2Tex == null) continue; + if (!gTex.Value.TryGetValue(propName, out var sTexture)) { continue; } + Texture souseTex = sTexture is Texture2D ? texManage.GetOriginTempRt(sTexture as Texture2D, sTexture.width) : sTexture; - var findMaterial = MatPropKV.Key; - var findMaterialID = Array.FindIndex(atlasContext.Materials, mh => mh.Contains(findMaterial)); + // var findMaterial = MatPropKV.Key; + var findMaterialID = gTex.Key; if (rectTangleMove) { - var findSubDataHash = atlasContext.AtlasSubAll.Where(i => i.MaterialID == findMaterialID).ToHashSet(); + var findSubDataHash = atlasContext.AtlasSubAll.Where(i => i.MaterialGroupID == findMaterialID).ToHashSet(); var islandPairs = new Dictionary(); for (var islandIndex = 0; relocatedRect.Length > islandIndex; islandIndex += 1) { @@ -396,7 +443,7 @@ void ScaleApplyUp(float scaleUpStep) { for (var subSetIndex = 0; atlasContext.AtlasSubSets.Count > subSetIndex; subSetIndex += 1) { - var transTargets = atlasContext.AtlasSubSets[subSetIndex].Where(i => i.HasValue).Where(i => i.Value.MaterialID == findMaterialID).Select(i => i.Value); + var transTargets = atlasContext.AtlasSubSets[subSetIndex].Where(i => i.HasValue).Where(i => i.Value.MaterialGroupID == findMaterialID).Select(i => i.Value); if (!transTargets.Any()) { continue; } var triangles = transTargets.SelectMany(subData => atlasContext.IslandDict[subData].SelectMany(i => i.triangles)); @@ -409,33 +456,33 @@ void ScaleApplyUp(float scaleUpStep) // UnityEditor.AssetDatabase.CreateAsset(targetRT.CopyTexture2D(), UnityEditor.AssetDatabase.GenerateUniqueAssetPath("Assets/temp.asset")); - if (souseProp2Tex.Texture is Texture2D && souseTex is RenderTexture tempRt) { RenderTexture.ReleaseTemporary(tempRt); } + if (sTexture is Texture2D && souseTex is RenderTexture tempRt) { RenderTexture.ReleaseTemporary(tempRt); } } - compiledAtlasTextures.Add(new PropAndTexture2D(propName, targetRT.CopyTexture2D())); + compiledAtlasTextures.Add(propName, targetRT.CopyTexture2D()); RenderTexture.ReleaseTemporary(targetRT); } - foreach (var matData in materialTextures) - { - foreach (var pTex in matData.Value) - { - if (pTex.Texture == null) { continue; } - switch (pTex.Texture) - { - case RenderTexture renderTexture: - { - RenderTexture.ReleaseTemporary(renderTexture); - break; - } - case Texture2D texture2D: - default: - { break; } - } - } - } + // foreach (var matData in materialTextures) + // { + // foreach (var pTex in matData.Value) + // { + // if (pTex.Texture == null) { continue; } + // switch (pTex.Texture) + // { + // case RenderTexture renderTexture: + // { + // RenderTexture.ReleaseTemporary(renderTexture); + // break; + // } + // case Texture2D texture2D: + // default: + // { break; } + // } + // } + // } atlasData.Textures = compiledAtlasTextures; - atlasData.MaterialID = atlasContext.Materials; + atlasData.MaterialID = atlasContext.MaterialGroup.Select(i => i.ToHashSet()).ToArray(); atlasContext.Dispose(); foreach (var movedUV in subSetMovedUV) { movedUV.Dispose(); } @@ -607,7 +654,8 @@ private static Material GenerateAtlasMat(Material targetMat, List texFineTuning } - public static List ConvertForTargets(List propAndTexture2Ds) + public static List ConvertForTargets(Dictionary propAndTexture2Ds) { - var targets = new List(propAndTexture2Ds.Capacity); + var targets = new List(propAndTexture2Ds.Count); foreach (var pat in propAndTexture2Ds) { - targets.Add(new TexFineTuningTarget(pat)); + targets.Add(new TexFineTuningTarget(new(pat.Key, pat.Value))); } return targets; } From 7c1da414c2f4580229d0ef9786309b1c918dd1aa Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 28 Mar 2024 21:12:26 +0900 Subject: [PATCH 032/208] fix: _UseShadow --- .../AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index 111ab8f6..e1978570 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -479,7 +479,7 @@ MonoBehaviour: type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseBacklight + PropertyName: _UseShadow ComparerValue: 0 Less: 0 - rid: 7150698705470881819 From 2c1743da7778a7854d28bbd1a66fd61149c0c13c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 28 Mar 2024 21:17:21 +0900 Subject: [PATCH 033/208] fix: if usePropertyBake --- Runtime/TextureAtlas/AtlasContext.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs index 566d5f32..2b49194d 100644 --- a/Runtime/TextureAtlas/AtlasContext.cs +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -69,6 +69,10 @@ public AtlasContext(List targetMaterials, List inputRenderer MaterialToAtlasShaderDict = material2AtlasTargets; AtlasShaderSupportUtils = shaderSupports; if (usePropertyBake) + { + MaterialGroup = materialHash.Select(i => new OrderedHashSet() { i }).ToArray(); + } + else { var materialGroupList = new List>>(); @@ -95,10 +99,6 @@ bool PropEqual(Dictionary propL, Dictionary new OrderedHashSet(i.Keys)).ToArray(); } - else - { - MaterialGroup = materialHash.Select(i => new OrderedHashSet() { i }).ToArray(); - } var TargetRenderers = inputRenderers.Where(r => r.sharedMaterials.Any(m => materialHash.Contains(m))).ToArray(); var normalizedMesh = SubVertNormalize(TargetRenderers); From d0090bcc5c49fbf0cac6a567a077b4f62ec4b34b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 6 Apr 2024 02:06:21 +0900 Subject: [PATCH 034/208] feat: ST apply And restore bake property --- Editor/Utils/LateInitializeUtility.cs | 2 + Runtime/TextureAtlas/AtlasContext.cs | 82 +++++++--- .../AtlasShaderSupportScriptableObject.cs | 4 + .../AtlasTargetDefine.cs | 101 +++++++++++- .../liltoon/lilToonAtlasBaker.shader | 15 +- .../liltoon/liltoonAtlasSupport.asset | 2 +- Runtime/TextureAtlas/AtlasTexture.cs | 145 +++++++++++++----- Runtime/Utils/MaterialUtility.cs | 42 +++++ .../ShaderAsset/TextureSTApply.shader | 50 ++++++ .../ShaderAsset/TextureSTApply.shader.meta | 9 ++ TexTransCore/TransTextureCore/TransTexture.cs | 36 +++-- .../TransTextureCore/Utils/TextureUtility.cs | 43 ++++++ 12 files changed, 444 insertions(+), 87 deletions(-) create mode 100644 TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader create mode 100644 TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta diff --git a/Editor/Utils/LateInitializeUtility.cs b/Editor/Utils/LateInitializeUtility.cs index b7322519..ce5baeb2 100644 --- a/Editor/Utils/LateInitializeUtility.cs +++ b/Editor/Utils/LateInitializeUtility.cs @@ -27,6 +27,8 @@ public static void Initializer() SpecialLayerShaders.Init(); TTTImageAssets.Init(); MipMapUtility.MipMapShader = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath("5f6d88c53276bb14eace10771023ae01")); + TexTransCore.TransTextureCore.Utils.TextureUtility.Init(); + TexTransCore.TransTextureCore.TransTexture.Init(); } } } diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs index 2b49194d..20dadad5 100644 --- a/Runtime/TextureAtlas/AtlasContext.cs +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -19,7 +19,8 @@ internal class AtlasContext : IDisposable public Dictionary MeshDataDict;//適当なレンダラーのノーマライズされたメッシュと対応する public OrderedHashSet[] MaterialGroup; - public Dictionary> MaterialToAtlasShaderDict; + public Dictionary AtlasShaderSupporters; + public Dictionary> MaterialToAtlasShaderTexDict; public AtlasShaderSupportUtils AtlasShaderSupportUtils; public HashSet AtlasSubAll; public List AtlasSubSets; @@ -66,39 +67,62 @@ public AtlasContext(List targetMaterials, List inputRenderer var shaderSupports = new AtlasShaderSupportUtils(); var supporters = targetMaterials.Select(m => (m, shaderSupports.GetAtlasShaderSupporter(m))).ToDictionary(i => i.m, i => i.Item2); var material2AtlasTargets = supporters.Select(kv => (kv.Key, kv.Value.GetAtlasShaderTexture2D(kv.Key))).ToDictionary(i => i.Key, i => i.Item2.ToDictionary(p => p.PropertyName, p => p)); - MaterialToAtlasShaderDict = material2AtlasTargets; + MaterialToAtlasShaderTexDict = material2AtlasTargets; AtlasShaderSupportUtils = shaderSupports; - if (usePropertyBake) + AtlasShaderSupporters = supporters; + + var materialGroupList = new List>>(); + + foreach (var matKv in material2AtlasTargets) { - MaterialGroup = materialHash.Select(i => new OrderedHashSet() { i }).ToArray(); + var index = materialGroupList.FindIndex( + matGroup => matGroup.All(m2 => + supporters[matKv.Key] == supporters[m2.Key] + && (usePropertyBake ? BakedPropEqual(m2.Value, matKv.Value) : PropEqual(m2.Value, matKv.Value) ) + ) + ); + + if (index == -1) { materialGroupList.Add(new() { { matKv.Key, matKv.Value } }); } + else { materialGroupList[index].Add(matKv.Key, matKv.Value); } } - else - { - var materialGroupList = new List>>(); - foreach (var matKv in material2AtlasTargets) + bool PropEqual(Dictionary propL, Dictionary propR) + { + foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) { - var index = materialGroupList.FindIndex(matGroup => matGroup.All(m2 => PropEqual(m2.Value, matKv.Value))); + if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { continue; } + var l = propL[propName]; + var r = propR[propName]; + if (l.Texture2D == null || r.Texture2D == null) { continue; } + if (l.Texture2D != r.Texture2D) { return false; } - if (index == -1) { materialGroupList.Add(new() { { matKv.Key, matKv.Value } }); } - else { materialGroupList[index].Add(matKv.Key, matKv.Value); } - } + if (l.TextureScale != r.TextureScale) { return false; } + if (l.TextureTranslation != r.TextureTranslation) { return false; } - bool PropEqual(Dictionary propL, Dictionary propR) + } + return true; + } + bool BakedPropEqual(Dictionary propL, Dictionary propR) + { + foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) { + if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { return false; } - foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) - { - if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { continue; } - var l = propL[propName]; - var r = propR[propName]; - if (l.Texture2D == null || r.Texture2D == null) { continue; } - if (l.Texture2D != r.Texture2D) { return false; } - } - return true; + var l = propL[propName]; + var r = propR[propName]; + + if (l.Texture2D == null || r.Texture2D == null) { return false; } + if (l.Texture2D != r.Texture2D) { return false; } + + if (l.TextureScale != r.TextureScale) { return false; } + if (l.TextureTranslation != r.TextureTranslation) { return false; } + + if (BakeProperty.PropertyListEqual(l.BakeProperties, r.BakeProperties) == false) { return false; } } - MaterialGroup = materialGroupList.Select(i => new OrderedHashSet(i.Keys)).ToArray(); + return true; } + MaterialGroup = materialGroupList.Select(i => new OrderedHashSet(i.Keys)).ToArray(); + var TargetRenderers = inputRenderers.Where(r => r.sharedMaterials.Any(m => materialHash.Contains(m))).ToArray(); var normalizedMesh = SubVertNormalize(TargetRenderers); @@ -281,6 +305,18 @@ bool PropEqual(Dictionary propL, Dictionary atlasSubSets) { while (true) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs index 74786f6e..7b903c2e 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs @@ -24,7 +24,11 @@ public List GetAtlasShaderTexture2D(Material material) if (!constraint.Constraints(material)) { continue; } var asTex = new AtlasShaderTexture2D(); var tex = material.GetTexture(atlasTargetDefine.TexturePropertyName) as Texture2D; + asTex.Texture2D = tex; + asTex.TextureScale = material.GetTextureScale(atlasTargetDefine.TexturePropertyName); + asTex.TextureTranslation = material.GetTextureOffset(atlasTargetDefine.TexturePropertyName); + asTex.PropertyName = atlasTargetDefine.TexturePropertyName; asTex.BakeProperties = atlasTargetDefine.BakePropertyNames.Select(s => BakeProperty.GetBakeProperty(material, s)).ToList(); atlasTex.Add(asTex); diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs index 073cd499..762f1f1c 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasTargetDefine.cs @@ -12,6 +12,9 @@ public class AtlasShaderTexture2D public string PropertyName; public Texture2D Texture2D; + public Vector2 TextureScale; + public Vector2 TextureTranslation; + [SerializeReference] public List BakeProperties; } @@ -21,6 +24,24 @@ public abstract class BakeProperty { public string PropertyName; + public abstract void WriteMaterial(Material material); + + public static bool PropertyListEqual(List l, List r) + { + var count = l.Count; + if (count != r.Count) { return false; } + + for (var i = 0; count > i; i += 1) + { + var lProp = l[i]; + var rProp = r[i]; + + var res = ValueComparer(lProp, rProp); + if (res == false) { return false; } + } + return true; + } + public static bool ValueComparer(BakeProperty l, BakeProperty r) { if (l.GetType() != r.GetType()) { return false; } @@ -43,6 +64,16 @@ public static bool ValueComparer(BakeProperty l, BakeProperty r) var rc = r as BakeColor; return lc.Color == rc.Color; } + case BakeVector lc: + { + var rc = r as BakeVector; + return lc.Vector == rc.Vector; + } + case BakeTexture lc: + { + var rc = r as BakeTexture; + return lc.Texture2D == rc.Texture2D && lc.TextureScale == rc.TextureScale && lc.TextureTranslation == rc.TextureTranslation; + } default: return false; } @@ -55,17 +86,75 @@ public static BakeProperty GetBakeProperty(Material material, string propertyNam { case UnityEngine.Rendering.ShaderPropertyType.Float: { return new BakeFloat() { PropertyName = propertyName, Float = material.GetFloat(propertyName) }; } case UnityEngine.Rendering.ShaderPropertyType.Range: { return new BakeRange() { PropertyName = propertyName, Float = material.GetFloat(propertyName), MinMax = material.shader.GetPropertyRangeLimits(propIndex) }; } - case UnityEngine.Rendering.ShaderPropertyType.Color: { return new BakeColor() { PropertyName = propertyName, Color = material.GetColor(propertyName)}; } - case UnityEngine.Rendering.ShaderPropertyType.Vector: { return new BakeVector() { PropertyName = propertyName, Vector = material.GetVector(propertyName)}; } + case UnityEngine.Rendering.ShaderPropertyType.Color: { return new BakeColor() { PropertyName = propertyName, Color = material.GetColor(propertyName) }; } + case UnityEngine.Rendering.ShaderPropertyType.Vector: { return new BakeVector() { PropertyName = propertyName, Vector = material.GetVector(propertyName) }; } + case UnityEngine.Rendering.ShaderPropertyType.Texture: + { + return new BakeTexture() + { + PropertyName = propertyName, + Texture2D = material.GetTexture(propertyName) as Texture2D, + TextureScale = material.GetTextureScale(propertyName), + TextureTranslation = material.GetTextureOffset(propertyName), + }; + } default: { return null; } } } } [Serializable] - public class BakeFloat : BakeProperty { public float Float; } + public class BakeFloat : BakeProperty + { + public float Float; + + public override void WriteMaterial(Material material) + { + material.SetFloat(PropertyName, Float); + } + } + [Serializable] + public class BakeRange : BakeProperty + { + public float Float; public Vector2 MinMax; + + public override void WriteMaterial(Material material) + { + material.SetFloat(PropertyName, Float); + } + } + [Serializable] + public class BakeColor : BakeProperty + { + public Color Color; + + public override void WriteMaterial(Material material) + { + material.SetColor(PropertyName, Color); + } + } [Serializable] - public class BakeRange : BakeProperty { public float Float; public Vector2 MinMax; } + public class BakeVector : BakeProperty + { + public Vector4 Vector; + + public override void WriteMaterial(Material material) + { + material.SetVector(PropertyName, Vector); + } + } [Serializable] - public class BakeColor : BakeProperty { public Color Color; } - public class BakeVector : BakeProperty { public Vector4 Vector; } + public class BakeTexture : BakeProperty + { + public Texture2D Texture2D; + + public Vector2 TextureScale; + public Vector2 TextureTranslation; + + public override void WriteMaterial(Material material) + { + material.SetTexture(PropertyName, Texture2D); + material.SetTextureScale(PropertyName, TextureScale); + material.SetTextureOffset(PropertyName, TextureTranslation); + } + } } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader index 225370ab..ba25722b 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader @@ -224,7 +224,7 @@ Shader "Hidden/lilToonAtlasBaker" #pragma vertex vert #pragma fragment frag - #pragma multi_compile_fragment_local Bake_MainTex Bake_Main2ndTex Bake_Main3rdTex Bake_AlphaMask Bake_BumpMap Bake_Bump2ndMap Bake_AnisotropyScaleMask Bake_BacklightColorTex Bake_ShadowStrengthMask Bake_ShadowColorTex Bake_Shadow2ndColorTex Bake_Shadow3rdColorTex Bake_RimShadeMask Bake_SmoothnessTex Bake_MetallicGlossMap Bake_ReflectionColorTex Bake_MatCapBlendMask Bake_MatCapBumpMap Bake_MatCap2ndBlendMask Bake_MatCap2ndBumpMap Bake_RimColorTex Bake_GlitterColorTex Bake_EmissionMap Bake_EmissionBlendMask Bake_Emission2ndMap Bake_Emission2ndBlendMask Bake_ParallaxMap Bake_OutlineTex Bake_OutlineWidthMask Bake_OutlineVectorTex + #pragma multi_compile_local_fragment Bake_MainTex Bake_Main2ndTex Bake_Main3rdTex Bake_AlphaMask Bake_BumpMap Bake_Bump2ndMap Bake_AnisotropyScaleMask Bake_BacklightColorTex Bake_ShadowStrengthMask Bake_ShadowColorTex Bake_Shadow2ndColorTex Bake_Shadow3rdColorTex Bake_RimShadeMask Bake_SmoothnessTex Bake_MetallicGlossMap Bake_ReflectionColorTex Bake_MatCapBlendMask Bake_MatCapBumpMap Bake_MatCap2ndBlendMask Bake_MatCap2ndBumpMap Bake_RimColorTex Bake_GlitterColorTex Bake_EmissionMap Bake_EmissionBlendMask Bake_Emission2ndMap Bake_Emission2ndBlendMask Bake_ParallaxMap Bake_OutlineTex Bake_OutlineWidthMask Bake_OutlineVectorTex #include "UnityCG.cginc" @@ -307,14 +307,17 @@ Shader "Hidden/lilToonAtlasBaker" sampler2D _ReflectionColorTex; float4 _ReflectionColor; - sampler2D _MatCapBumpMap; + sampler2D _MatCapBlendMask; float _MatCapBlend; + sampler2D _MatCapBumpMap; + float _MatCapBumpScale; + sampler2D _MatCap2ndBlendMask; - float _MatCapBlend; + float _MatCap2ndBlend; sampler2D _MatCap2ndBumpMap; - float _MatCapBumpScale; + float _MatCap2ndBumpScale; sampler2D _RimColorTex; float4 _RimColor; @@ -378,7 +381,7 @@ Shader "Hidden/lilToonAtlasBaker" { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = TRANSFORM_TEX(v.uv, _MainTex); + o.uv = v.uv; return o; } @@ -387,7 +390,7 @@ Shader "Hidden/lilToonAtlasBaker" #if Bake_MainTex float4 col = tex2D(_MainTex ,i.uv); float3 tcCol = lilToneCorrection(col.rgb,_MainTexHSVG); - col.rgb = lerp(tcCol , col.rgb tex2D(_MainColorAdjustMask,i.uv)); + col.rgb = lerp(tcCol , col.rgb , tex2D(_MainColorAdjustMask,i.uv)); col *= _Color; return col; #elif Bake_Main2ndTex diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index e1978570..42206a5c 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -202,7 +202,7 @@ MonoBehaviour: rid: 7150698705470881846 BakePropertyNames: - _OutlineVectorScale - BakeShader: {fileID: 0} + BakeShader: {fileID: 4800000, guid: 9d918a30dc195d94ea1916f48779948f, type: 3} AtlasMaterialPostProses: - rid: 7150698656081904264 - rid: 7150698656081904304 diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 5e48e6ac..dbc8d93d 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -153,7 +153,7 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) { foreach (var islandKV in atlasContext.IslandDict) { - var material = atlasContext.MaterialToAtlasShaderDict[atlasContext.MaterialGroup[islandKV.Key.MaterialGroupID].First()]; + var material = atlasContext.MaterialToAtlasShaderTexDict[atlasContext.MaterialGroup[islandKV.Key.MaterialGroupID].First()]; var refTex = material.TryGetValue("_MainTex", out var tex2D) ? tex2D.Texture2D : null; if (refTex == null) { continue; } foreach (var island in islandKV.Value) @@ -388,30 +388,117 @@ void ScaleApplyUp(float scaleUpStep) } atlasData.Meshes = compiledMeshes; - + var textureManager = domain.GetTextureManager(); //アトラス化したテクスチャーを生成するフェーズ var compiledAtlasTextures = new Dictionary(); - var propertyNames = atlasContext.MaterialToAtlasShaderDict.Values.SelectMany(i => i.Keys).ToHashSet(); - var groupedTextures = atlasContext.MaterialGroup - .Select(mg => (Array.IndexOf(atlasContext.MaterialGroup, mg), mg.Select(m => atlasContext.MaterialToAtlasShaderDict[m]))) - .Select(mg => (mg.Item1, ZipDict(mg.Item2))) - .ToDictionary(i => i.Item1, i => i.Item2); + var groupedTextures = GetGroupedTextures(atlasContext, propertyBakeSetting, out var containsProperty); - Dictionary ZipDict(IEnumerable> keyValuePairs) + Dictionary> GetGroupedTextures(AtlasContext atlasContext, PropertyBakeSetting propertyBakeSetting, out HashSet property) { - var dict = new Dictionary(); - foreach (var kv in keyValuePairs.SelectMany(i => i)) + switch (propertyBakeSetting) { - if (kv.Value.Texture2D == null) { continue; } - dict[kv.Key] = kv.Value.Texture2D; + default: { property = null; return null; } + case PropertyBakeSetting.NotBake: + { + var dict = atlasContext.MaterialGroup + .Select(mg => (Array.IndexOf(atlasContext.MaterialGroup, mg), mg.Select(m => atlasContext.MaterialToAtlasShaderTexDict[m]))) + .Select(mg => (mg.Item1, ZipDictAndOffset(mg.Item2))) + .ToDictionary(i => i.Item1, i => i.Item2); + + property = new HashSet(dict.SelectMany(i => i.Value.Keys)); + return dict; + + Dictionary ZipDictAndOffset(IEnumerable> keyValuePairs) + { + var dict = new Dictionary(); + foreach (var kv in keyValuePairs.SelectMany(i => i).GroupBy(i => i.Key)) + { + if (kv.Any(i => i.Value.Texture2D != null) == false) { continue; } + var atlasTex = kv.First(i => i.Value.Texture2D != null).Value; + if (atlasTex.TextureScale == Vector2.zero && atlasTex.TextureTranslation == Vector2.zero) + { + dict[kv.Key] = textureManager.GetOriginTempRt(atlasTex.Texture2D); + } + else + { + var tex = atlasTex.Texture2D; + + var originTex = textureManager.GetOriginTempRt(tex); + originTex.ApplyTextureST(atlasTex.TextureScale, atlasTex.TextureTranslation); + + dict[kv.Key] = originTex; + } + } + return dict; + } + } + case PropertyBakeSetting.Bake: + case PropertyBakeSetting.BakeAllProperty: + { + property = new HashSet(atlasContext.MaterialToAtlasShaderTexDict + .SelectMany(i => i.Value) + .GroupBy(i => i.Key) + .Where(i => PropertyBakeSetting.BakeAllProperty == propertyBakeSetting || i.Any(st => st.Value.Texture2D != null)) + .Select(i => i.Key) + ); + + var groupDict = new Dictionary>(atlasContext.MaterialGroup.Length); + var tmpMat = new Material(Shader.Find("Unlit/Texture")); + + + for (var gi = 0; atlasContext.MaterialGroup.Length > gi; gi += 1) + { + var matGroup = atlasContext.MaterialGroup[gi]; + var groupMat = matGroup.First(); + + var atlasTexDict = atlasContext.MaterialToAtlasShaderTexDict[groupMat];//テクスチャに関する情報が完全に同じでないと同じグループにならない。だから適当なものでよい。 + var shaderSupport = atlasContext.AtlasShaderSupporters[groupMat]; + + tmpMat.shader = shaderSupport.BakeShader; + + var texDict = groupDict[gi] = new(); + + foreach (var propName in property) + { + atlasTexDict.TryGetValue(propName, out var atlasTex); + var sTex = atlasTex?.Texture2D != null ? textureManager.GetOriginTempRt(atlasTex.Texture2D) : null; + + if (sTex != null) { sTex.ApplyTextureST(atlasTex.TextureScale, atlasTex.TextureTranslation); } + var bakedTex = sTex != null ? sTex.CloneTemp() : RenderTexture.GetTemporary(2, 2); + + if (atlasTex != null) + { + foreach (var bakeProp in atlasTex.BakeProperties) + { + bakeProp.WriteMaterial(tmpMat); + } + } + tmpMat.EnableKeyword("Bake" + propName); + tmpMat.SetTexture(propName, sTex); + Graphics.Blit(sTex, bakedTex, tmpMat); + + texDict[propName] = bakedTex; + + if (sTex != null) { RenderTexture.ReleaseTemporary(sTex); } + tmpMat.AllPropertyReset(); + tmpMat.shaderKeywords = Array.Empty(); + + } + + + } + + return groupDict; + } } - return dict; } - foreach (var propName in propertyNames) + + + foreach (var propName in containsProperty) { var targetRT = RenderTexture.GetTemporary(atlasSetting.AtlasTextureSize, atlasTextureHeightSize, 32); targetRT.Clear(); @@ -421,7 +508,6 @@ Dictionary ZipDict(IEnumerable I.PropertyName == propName); // if (souseProp2Tex == null) continue; if (!gTex.Value.TryGetValue(propName, out var sTexture)) { continue; } - Texture souseTex = sTexture is Texture2D ? texManage.GetOriginTempRt(sTexture as Texture2D, sTexture.width) : sTexture; // var findMaterial = MatPropKV.Key; var findMaterialID = gTex.Key; @@ -437,7 +523,7 @@ Dictionary ZipDict(IEnumerable ZipDict(IEnumerable(triangles, subSetMovedUV[subSetIndex], originUV); - ForTrans(targetRT, souseTex, transData, atlasSetting.GetTexScalePadding * 0.5f, null, true); + ForTrans(targetRT, sTexture, transData, atlasSetting.GetTexScalePadding * 0.5f, null, true); } } // UnityEditor.AssetDatabase.CreateAsset(targetRT.CopyTexture2D(), UnityEditor.AssetDatabase.GenerateUniqueAssetPath("Assets/temp.asset")); - - if (sTexture is Texture2D && souseTex is RenderTexture tempRt) { RenderTexture.ReleaseTemporary(tempRt); } } compiledAtlasTextures.Add(propName, targetRT.CopyTexture2D()); RenderTexture.ReleaseTemporary(targetRT); } - // foreach (var matData in materialTextures) - // { - // foreach (var pTex in matData.Value) - // { - // if (pTex.Texture == null) { continue; } - // switch (pTex.Texture) - // { - // case RenderTexture renderTexture: - // { - // RenderTexture.ReleaseTemporary(renderTexture); - // break; - // } - // case Texture2D texture2D: - // default: - // { break; } - // } - // } - // } + + foreach (var kv in groupedTextures.Values) { foreach (var tex in kv) { RenderTexture.ReleaseTemporary(tex.Value); } } + groupedTextures = null; + atlasData.Textures = compiledAtlasTextures; atlasData.MaterialID = atlasContext.MaterialGroup.Select(i => i.ToHashSet()).ToArray(); @@ -487,6 +557,7 @@ Dictionary ZipDict(IEnumerable GetTextureSizeOffset(IEnumerable targetMaterialSelectors, AtlasSetting atlasSetting) diff --git a/Runtime/Utils/MaterialUtility.cs b/Runtime/Utils/MaterialUtility.cs index 292e8709..8c469473 100644 --- a/Runtime/Utils/MaterialUtility.cs +++ b/Runtime/Utils/MaterialUtility.cs @@ -73,5 +73,47 @@ public static Dictionary GetAllTexture2D(this Material materi yield return (propName, tex2D); } } + + public static void AllPropertyReset(this Material material) + { + var shader = material.shader; + var propCount = shader.GetPropertyCount(); + for (var i = 0; propCount > i; i += 1) + { + var pID = shader.GetPropertyNameId(i); + switch (shader.GetPropertyType(i)) + { + case UnityEngine.Rendering.ShaderPropertyType.Color: + { + material.SetColor(pID, shader.GetPropertyDefaultVectorValue(i)); + break; + } + case UnityEngine.Rendering.ShaderPropertyType.Vector: + { + material.SetVector(pID, shader.GetPropertyDefaultVectorValue(i)); + break; + } + case UnityEngine.Rendering.ShaderPropertyType.Float: + case UnityEngine.Rendering.ShaderPropertyType.Range: + { + material.SetFloat(pID, shader.GetPropertyDefaultFloatValue(i)); + break; + } + case UnityEngine.Rendering.ShaderPropertyType.Int: + { + material.SetInt(pID, shader.GetPropertyDefaultIntValue(i)); + break; + } + case UnityEngine.Rendering.ShaderPropertyType.Texture: + { + material.SetTexture(pID, null); + material.SetTextureScale(pID, Vector2.zero); + material.SetTextureOffset(pID, Vector2.zero); + break; + + } + } + } + } } } diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader b/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader new file mode 100644 index 00000000..3a218d52 --- /dev/null +++ b/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader @@ -0,0 +1,50 @@ +Shader "Hidden/TextureSTApply" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + } + SubShader + { + Tags { "Queue" = "Transparent" } + LOD 100 + Cull Off + Pass + { + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + struct v2f + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.uv , _MainTex); + return o; + } + + float4 frag (v2f i) : SV_Target + { + return tex2D(_MainTex,i.uv); + } + ENDHLSL + } + } +} diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta b/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta new file mode 100644 index 00000000..8615afb9 --- /dev/null +++ b/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 56f96e417cdc55b4c8e1e8041910a36a +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/TransTextureCore/TransTexture.cs b/TexTransCore/TransTextureCore/TransTexture.cs index 7bd3daff..03f11b6d 100644 --- a/TexTransCore/TransTextureCore/TransTexture.cs +++ b/TexTransCore/TransTextureCore/TransTexture.cs @@ -23,7 +23,7 @@ public struct TransData where UVDimension : struct public NativeArray TrianglesToIndex; public NativeArray TargetUV; public NativeArray SourceUV; - + public TransData( IEnumerable trianglesToIndex, IEnumerable targetUV, @@ -43,7 +43,7 @@ IEnumerable sourceUV self.SourceUV.Dispose(); }; } - + public TransData(NativeArray trianglesToIndex, NativeArray targetUV, NativeArray sourceUV) { TrianglesToIndex = trianglesToIndex; @@ -55,7 +55,7 @@ public Mesh GenerateTransMesh() { var mda = Mesh.AllocateWritableMeshData(1); var mda_mesh = mda[0]; - + mda_mesh.SetVertexBufferParams( TargetUV.Length, new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3), @@ -66,18 +66,18 @@ public Mesh GenerateTransMesh() var pos_array = mda_mesh.GetVertexData(0); var uv_array = mda_mesh.GetVertexData(1); var dst_triangles = mda_mesh.GetIndexData(); - + var job1 = new CopyPos { Source = TargetUV, Destination = pos_array }.Schedule(TargetUV.Length, 64); var job2 = new CopyJob { Source = SourceUV, Destination = uv_array }.Schedule(SourceUV.Length, 64, job1); var job3 = new UnpackTriangleJob { Source = TrianglesToIndex, Destination = dst_triangles }.Schedule(dst_triangles.Length, 64, job2); var mesh = new Mesh(); - + job3.Complete(); mda_mesh.subMeshCount = 1; mda_mesh.SetSubMesh(0, new SubMeshDescriptor(0, dst_triangles.Length, MeshTopology.Triangles)); - + Mesh.ApplyAndDisposeWritableMeshData(mda, mesh); return mesh; @@ -91,18 +91,18 @@ private static void BurstInstantiate() new CopyJob().Schedule(1, 1); new CopyJob().Schedule(1, 1); } - + [BurstCompile] struct UnpackTriangleJob : IJobParallelFor { [ReadOnly] public NativeArray Source; [WriteOnly] public NativeArray Destination; - + public void Execute(int index) { var tri_index = index / 3; var coord = index % 3; - + Destination[index] = Source[tri_index][coord]; } } @@ -112,27 +112,35 @@ struct CopyPos : IJobParallelFor { [ReadOnly] public NativeArray Source; [WriteOnly] public NativeArray Destination; - + public void Execute(int index) { Destination[index] = Source[index]; } } - + [BurstCompile] struct CopyJob : IJobParallelFor where T : struct { [ReadOnly] public NativeArray Source; [WriteOnly] public NativeArray Destination; - + public void Execute(int index) { Destination[index] = Source[index]; } } + public static void Init() + { + s_transShader = Shader.Find(TRANS_SHADER); + s_depthShader = Shader.Find(DEPTH_WRITER_SHADER); + } public const string TRANS_SHADER = "Hidden/TransTexture"; + static Shader s_transShader; public const string DEPTH_WRITER_SHADER = "Hidden/DepthWriter"; + static Shader s_depthShader; + public static void ForTrans( RenderTexture targetTexture, Texture souseTexture, @@ -159,7 +167,7 @@ public static void ForTrans( Profiler.BeginSample("Material Setup"); - var material = new Material(Shader.Find(TRANS_SHADER)); + var material = new Material(s_transShader); material.SetTexture("_MainTex", souseTexture); if (padding.HasValue) material.SetFloat("_Padding", padding.Value); if (padding.HasValue && highQualityPadding) @@ -186,7 +194,7 @@ public static void ForTrans( using (new RTActiveSaver()) { - var depthMat = new Material(Shader.Find(DEPTH_WRITER_SHADER)); + var depthMat = new Material(s_depthShader); RenderTexture.active = depthRt; depthMat.SetPass(0); diff --git a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs index 4fc36f0b..6dd4c3fc 100644 --- a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs +++ b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs @@ -126,5 +126,48 @@ public static Texture2D CreateFillTexture(Vector2Int size, Color fillColor) } public static int NormalizePowerOfTwo(int v) => Mathf.IsPowerOfTwo(v) ? v : Mathf.NextPowerOfTwo(v); + + public static RenderTexture CloneTemp(this RenderTexture renderTexture) + { + var newTemp = RenderTexture.GetTemporary(renderTexture.descriptor); + newTemp.filterMode = renderTexture.filterMode; + newTemp.wrapMode = renderTexture.wrapMode; + newTemp.wrapModeU = renderTexture.wrapModeU; + newTemp.wrapModeV = renderTexture.wrapModeV; + newTemp.wrapModeW = renderTexture.wrapModeW; + Graphics.CopyTexture(renderTexture, newTemp); + return newTemp; + } + + + + public const string ST_APPLY_SHADER = "Hidden/TransTexture"; + static Shader s_stApplyShader; + + public static void Init() { s_stApplyShader = Shader.Find(ST_APPLY_SHADER); } + + static Material s_TempMat; + + public static void ApplyTextureST(Texture Souse, Vector2 s, Vector2 t, RenderTexture write) + { + using (new RTActiveSaver()) + { + if (s_TempMat == null) { s_TempMat = new Material(s_stApplyShader); } + s_TempMat.shader = s_stApplyShader; + + s_TempMat.SetTextureScale("_MainTex", s); + s_TempMat.SetTextureOffset("_MainTex", t); + + Graphics.Blit(Souse, write, s_TempMat); + } + } + public static void ApplyTextureST(this RenderTexture rt, Vector2 s, Vector2 t) + { + var tmp = rt.CloneTemp(); + ApplyTextureST(tmp, s, t, rt); + RenderTexture.ReleaseTemporary(tmp); + } + + } } From 03fa5438b508a24268247da5533eac559358026e Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 6 Apr 2024 18:23:34 +0900 Subject: [PATCH 035/208] chore: SetFloat the _MaxValue --- .../IAtlasDefineConstraints.cs | 2 +- .../liltoon/lilToonAtlasBaker.shader | 38 +++++++++++++++++++ .../liltoon/liltoonAtlasSupport.asset | 28 ++++++++++---- Runtime/TextureAtlas/AtlasTexture.cs | 23 +++++++++++ 4 files changed, 82 insertions(+), 9 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs index 39b293bb..5e317739 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasDefineConstraints.cs @@ -79,7 +79,7 @@ public class ShaderNameContains : IAtlasDefineConstraints public string Name; public bool Constraints(Material material) { - return material.shader.name.Contains("Name"); + return material.shader.name.Contains(Name); } } [Serializable] diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader index ba25722b..c19b0a1c 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/lilToonAtlasBaker.shader @@ -204,6 +204,7 @@ Shader "Hidden/lilToonAtlasBaker" _OutlineWidthMask ("Width", 2D) = "white" {} _OutlineWidth ("Width", Range(0,1)) = 0.08 + _OutlineWidth_MaxValue ("Width", float) = 1 _OutlineVectorUVMode ("UV Mode|UV0|UV1|UV2|UV3", Int) = 0 @@ -225,6 +226,7 @@ Shader "Hidden/lilToonAtlasBaker" #pragma fragment frag #pragma multi_compile_local_fragment Bake_MainTex Bake_Main2ndTex Bake_Main3rdTex Bake_AlphaMask Bake_BumpMap Bake_Bump2ndMap Bake_AnisotropyScaleMask Bake_BacklightColorTex Bake_ShadowStrengthMask Bake_ShadowColorTex Bake_Shadow2ndColorTex Bake_Shadow3rdColorTex Bake_RimShadeMask Bake_SmoothnessTex Bake_MetallicGlossMap Bake_ReflectionColorTex Bake_MatCapBlendMask Bake_MatCapBumpMap Bake_MatCap2ndBlendMask Bake_MatCap2ndBumpMap Bake_RimColorTex Bake_GlitterColorTex Bake_EmissionMap Bake_EmissionBlendMask Bake_Emission2ndMap Bake_Emission2ndBlendMask Bake_ParallaxMap Bake_OutlineTex Bake_OutlineWidthMask Bake_OutlineVectorTex + #pragma shader_feature_local_fragment Constraint_Invalid #include "UnityCG.cginc" @@ -398,10 +400,19 @@ Shader "Hidden/lilToonAtlasBaker" #elif Bake_Main3rdTex return tex2D(_Main3rdTex ,i.uv) * _Color3rd; #elif Bake_AlphaMask +#if Constraint_Invalid + return float4(1,1,1,1); +#endif return saturate(tex2D(_AlphaMask ,i.uv) * _AlphaMaskScale + _AlphaMaskValue); #elif Bake_BumpMap +#if Constraint_Invalid + return float4(1,0.5,0.5,0.5); +#endif return tex2D(_BumpMap,i.uv);//いつかやるかもしれないかも #elif Bake_Bump2ndMap +#if Constraint_Invalid + return float4(1,0.5,0.5,0.5); +#endif return tex2D(_Bump2ndMap,i.uv); #elif Bake_AnisotropyScaleMask return tex2D(_AnisotropyTangentMap,i.uv); @@ -416,6 +427,9 @@ Shader "Hidden/lilToonAtlasBaker" #elif Bake_Shadow3rdColorTex return tex2D(_Shadow3rdColorTex,i.uv) * _Shadow3rdColor; #elif Bake_RimShadeMask +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_RimShadeMask,i.uv) * _RimShadeColor; #elif Bake_SmoothnessTex return tex2D(_SmoothnessTex,i.uv) * _Smoothness; @@ -426,32 +440,56 @@ Shader "Hidden/lilToonAtlasBaker" #elif Bake_MatCapBlendMask return tex2D(_MatCapBlendMask,i.uv) * _MatCapBlend; #elif Bake_MatCapBumpMap +#if Constraint_Invalid + return float4(1,0.5,0.5,0.5); +#endif return tex2D(_MatCapBumpMap,i.uv); #elif Bake_MatCap2ndBlendMask return tex2D(_MatCap2ndBlendMask,i.uv) * _MatCap2ndBlend; #elif Bake_MatCap2ndBumpMap +#if Constraint_Invalid + return float4(1,0.5,0.5,0.5); +#endif return tex2D(_MatCap2ndBumpMap,i.uv); #elif Bake_RimColorTex return tex2D(_RimColorTex,i.uv) * _RimColor; #elif Bake_GlitterColorTex return tex2D(_GlitterColorTex,i.uv) * _GlitterColor; #elif Bake_EmissionMap +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_EmissionMap,i.uv) * _EmissionColor; #elif Bake_EmissionBlendMask +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_EmissionBlendMask,i.uv) * _EmissionBlend; #elif Bake_Emission2ndMap +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_Emission2ndMap,i.uv) * _Emission2ndColor; #elif Bake_Emission2ndBlendMask +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_Emission2ndBlendMask,i.uv) * _Emission2ndBlend; #elif Bake_ParallaxMap return tex2D(_ParallaxMap,i.uv); #elif Bake_OutlineTex +#if Constraint_Invalid + return float4(0,0,0,0); +#endif float4 col = tex2D(_OutlineTex ,i.uv); float3 tcCol = lilToneCorrection(col.rgb,_OutlineTexHSVG); col.rgb = tcCol; col *= _OutlineColor; return col; #elif Bake_OutlineWidthMask +#if Constraint_Invalid + return float4(0,0,0,0); +#endif return tex2D(_OutlineWidthMask ,i.uv) * (_OutlineWidth / _OutlineWidth_MaxValue); #elif Bake_OutlineVectorTex return tex2D(_OutlineVectorTex ,i.uv); diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index 42206a5c..7ece189e 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -199,7 +199,7 @@ MonoBehaviour: - _OutlineWidth - TexturePropertyName: _OutlineVectorTex AtlasDefineConstraints: - rid: 7150698705470881846 + rid: 1595567437379272704 BakePropertyNames: - _OutlineVectorScale BakeShader: {fileID: 4800000, guid: 9d918a30dc195d94ea1916f48779948f, type: 3} @@ -209,6 +209,25 @@ MonoBehaviour: references: version: 2 RefIds: + - rid: 1595567437379272704 + type: {class: AndConstraints, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + AtlasDefineConstraints: + - rid: 1595567437379272706 + - rid: 1595567437379272705 + - rid: 1595567437379272705 + type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + PropertyName: _OutlineVectorUVMode + ComparerValue: 1 + Less: 1 + - rid: 1595567437379272706 + type: {class: ShaderNameContains, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, + asm: net.rs64.tex-trans-tool.runtime} + data: + Name: Outline - rid: 7150698656081904264 type: {class: TextureReferenceCopy, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} @@ -671,10 +690,3 @@ MonoBehaviour: PropertyName: _UseParallax ComparerValue: 0 Less: 0 - - rid: 7150698705470881846 - type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, - asm: net.rs64.tex-trans-tool.runtime} - data: - PropertyName: _OutlineVectorUVMode - ComparerValue: 1 - Less: 1 diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index dbc8d93d..e922a3b6 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -446,6 +446,19 @@ Dictionary ZipDictAndOffset(IEnumerable>(atlasContext.MaterialGroup.Length); var tmpMat = new Material(Shader.Find("Unlit/Texture")); + var bakePropMaxValue = atlasContext.MaterialToAtlasShaderTexDict.Values.SelectMany(kv => kv) + .SelectMany(i => i.Value.BakeProperties) + .GroupBy(i => i.PropertyName) + .Where(i => i.First() is BakeFloat || i.First() is BakeRange) + .ToDictionary(i => i.Key, i => i.Max(p => + { + if(p is BakeFloat bakeFloat){return bakeFloat.Float;} + if(p is BakeRange bakeRange){return bakeRange.Float;} + return 0; + } + ) + );//一旦 Float として扱えるものだけの実装にしておく。 + for (var gi = 0; atlasContext.MaterialGroup.Length > gi; gi += 1) { @@ -472,9 +485,19 @@ Dictionary ZipDictAndOffset(IEnumerable Date: Sun, 7 Apr 2024 21:56:32 +0900 Subject: [PATCH 036/208] chore: remove unused --- .../AtlasDefaultShaderSupport.cs | 21 - .../AtlasDefaultShaderSupport.cs.meta | 11 - .../AtlasShaderSupport/IAtlasShaderSupport.cs | 25 -- .../IAtlasShaderSupport.cs.meta | 11 - .../liltoon/ColorAdjust.shader | 78 ---- .../liltoon/ColorAdjust.shader.meta | 9 - .../liltoon/liltoonAtlasSupport.cs | 407 ------------------ .../liltoon/liltoonAtlasSupport.cs.meta | 11 - 8 files changed, 573 deletions(-) delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs.meta delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs.meta delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader.meta delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs delete mode 100644 Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs.meta diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs deleted file mode 100644 index 22ff9202..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace net.rs64.TexTransTool.TextureAtlas -{ - internal class AtlasDefaultShaderSupport : IAtlasShaderSupport - { - public void AddRecord(Material material) { } - public void ClearRecord() { } - public List GetPropertyAndTextures(IOriginTexture textureManager, Material material, PropertyBakeSetting bakeSetting) - { - if (material.HasProperty("_MainTex")) - { - return new () { new ("_MainTex", material.GetTexture("_MainTex") as Texture2D) }; - } - else { return new (); } - } - public bool IsThisShader(Material material) { return false; } - public void MaterialCustomSetting(Material material) { } - } -} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs.meta deleted file mode 100644 index e56c711f..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasDefaultShaderSupport.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 334f0826f054d854393bcf47e113db78 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs b/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs deleted file mode 100644 index 8095d2dd..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace net.rs64.TexTransTool.TextureAtlas -{ - /// - /// これらinterfaceは非常に実験的なAPIで予告なく変更や削除される可能性があります。 - /// - /// この interface は AtlasTexture でアトラス化できるシェーダーのサポートを追加するAPIで - /// 自身が対象とするマテリアルかどうかを判別する関数 - /// アトラス化対象のマテリアルの情報を貯める関数 - /// 貯めた情報の解放 - /// 貯めた情報を用いて、設定に応じてベイクなどを行いつつ マテリアルからテクスチャを引き出す関数 - /// 生成されたマテリアルに対して後処理(最適化など)を行う関数 - /// があり、 , などを参考にしてください。 - /// - public interface IAtlasShaderSupport - { - bool IsThisShader(Material material); - void AddRecord(Material material); - void ClearRecord(); - List GetPropertyAndTextures(IOriginTexture textureManager, Material material, PropertyBakeSetting bakeSetting); - void MaterialCustomSetting(Material material); - } -} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs.meta deleted file mode 100644 index c3c13f84..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/IAtlasShaderSupport.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ab123a5db34fcd444983c8dad7a967c5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader deleted file mode 100644 index a75da863..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader +++ /dev/null @@ -1,78 +0,0 @@ -Shader "Hidden/ColorAdjustShader" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - _HSVG ("HSVG", Vector) = (0,1,1,1) - _Mask ("Mask", 2D) = "white" {} - } - SubShader - { - Tags { "Queue" = "Transparent" } - LOD 100 - Cull Off - Pass - { - HLSLPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - sampler2D _MainTex; - float4 _HSVG; - sampler2D _Mask; - float _UseMask; - - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - //https://github.com/lilxyzw/lilToon/blob/2ef370dc444172787c075ec3a822438c2bee26cb/Assets/lilToon/Shader/Includes/lil_common_functions.hlsl#L328C48-L328C48 - //Originally under MIT License - //Copyright (c) 2020-2023 lilxyzw - float3 lilToneCorrection(float3 c, float4 hsvg) - { - // gamma - c = pow(abs(c), hsvg.w); - // rgb -> hsv - float4 p = (c.b > c.g) ? float4(c.bg,-1.0,2.0/3.0) : float4(c.gb,0.0,-1.0/3.0); - float4 q = (p.x > c.r) ? float4(p.xyw, c.r) : float4(c.r, p.yzx); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - float3 hsv = float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); - // shift - hsv = float3(hsv.x+hsvg.x,saturate(hsv.y*hsvg.y),saturate(hsv.z*hsvg.z)); - // hsv -> rgb - return hsv.z - hsv.z * hsv.y + hsv.z * hsv.y * saturate(abs(frac(hsv.x + float3(1.0, 2.0/3.0, 1.0/3.0)) * 6.0 - 3.0) - 1.0); - } - - fixed4 frag (v2f i) : SV_Target - { - float4 MainColor = tex2D(_MainTex ,i.uv); - float MaskValue = tex2D(_Mask ,i.uv).r; - - MainColor.rgb = lerp(MainColor.rgb,lilToneCorrection(MainColor.rgb,_HSVG),MaskValue); - return MainColor; - } - ENDHLSL - } - } -} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader.meta b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader.meta deleted file mode 100644 index f2697960..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/ColorAdjust.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 995fecf6de851fd4699c0db25b2fab30 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs deleted file mode 100644 index 57ab3c30..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs +++ /dev/null @@ -1,407 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - - -namespace net.rs64.TexTransTool.TextureAtlas -{ - internal class liltoonAtlasSupport : IAtlasShaderSupport - { - public bool IsThisShader(Material material) - { - return material.shader.name.Contains("lilToon"); - } - public void MaterialCustomSetting(Material material) - { - var mainTex = material.GetTexture("_MainTex") as Texture2D; - material.SetTexture("_BaseMap", mainTex); - material.SetTexture("_BaseColorMap", mainTex); - } - - public List GetPropertyAndTextures(IOriginTexture textureManager, Material material, PropertyBakeSetting bakeSetting) - { - var propEnvsDict = new Dictionary(); - - propEnvsDict.Add("_MainTex", material.GetTexture("_MainTex") as Texture2D); - propEnvsDict.Add("_MainColorAdjustMask", material.GetTexture("_MainColorAdjustMask") as Texture2D); - if (material.GetFloat("_UseMain2ndTex") > 0.5f) - { - propEnvsDict.Add("_Main2ndTex", material.GetTexture("_Main2ndTex") as Texture2D); - propEnvsDict.Add("_Main2ndBlendMask", material.GetTexture("_Main2ndBlendMask") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_Main2ndDissolveMask", material.GetTexture("_Main2ndDissolveMask") as Texture2D)); - // PropertyAndTextures.Add(new PropAndTexture("_Main2ndDissolveNoiseMask", material.GetTexture("_Main2ndDissolveNoiseMask") as Texture2D)); - if (material.GetFloat("_UseMain3rdTex") > 0.5f) - { - propEnvsDict.Add("_Main3rdTex", material.GetTexture("_Main3rdTex") as Texture2D); - propEnvsDict.Add("_Main3rdBlendMask", material.GetTexture("_Main3rdBlendMask") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_Main3rdDissolveMask", material.GetTexture("_Main3rdDissolveMask") as Texture2D)); - // PropertyAndTextures.Add(new PropAndTexture("_Main3rdDissolveNoiseMask", material.GetTexture("_Main3rdDissolveNoiseMask") as Texture2D)); - propEnvsDict.Add("_AlphaMask", material.GetTexture("_AlphaMask") as Texture2D); - if (material.GetFloat("_UseBumpMap") > 0.5f) - { - propEnvsDict.Add("_BumpMap", material.GetTexture("_BumpMap") as Texture2D); - } - if (material.GetFloat("_UseBump2ndMap") > 0.5f) - { - propEnvsDict.Add("_Bump2ndMap", material.GetTexture("_Bump2ndMap") as Texture2D); - propEnvsDict.Add("_Bump2ndScaleMask", material.GetTexture("_Bump2ndScaleMask") as Texture2D); - } - if (material.GetFloat("_UseAnisotropy") > 0.5f) - { - propEnvsDict.Add("_AnisotropyTangentMap", material.GetTexture("_AnisotropyTangentMap") as Texture2D); - propEnvsDict.Add("_AnisotropyScaleMask", material.GetTexture("_AnisotropyScaleMask") as Texture2D); - } - if (material.GetFloat("_UseBacklight") > 0.5f) - { - propEnvsDict.Add("_BacklightColorTex", material.GetTexture("_BacklightColorTex") as Texture2D); - } - if (material.GetFloat("_UseShadow") > 0.5f) - { - propEnvsDict.Add("_ShadowStrengthMask", material.GetTexture("_ShadowStrengthMask") as Texture2D); - propEnvsDict.Add("_ShadowBorderMask", material.GetTexture("_ShadowBorderMask") as Texture2D); - propEnvsDict.Add("_ShadowBlurMask", material.GetTexture("_ShadowBlurMask") as Texture2D); - propEnvsDict.Add("_ShadowColorTex", material.GetTexture("_ShadowColorTex") as Texture2D); - propEnvsDict.Add("_Shadow2ndColorTex", material.GetTexture("_Shadow2ndColorTex") as Texture2D); - propEnvsDict.Add("_Shadow3rdColorTex", material.GetTexture("_Shadow3rdColorTex") as Texture2D); - } - if (material.GetFloat("_UseReflection") > 0.5f) - { - propEnvsDict.Add("_SmoothnessTex", material.GetTexture("_SmoothnessTex") as Texture2D); - propEnvsDict.Add("_MetallicGlossMap", material.GetTexture("_MetallicGlossMap") as Texture2D); - propEnvsDict.Add("_ReflectionColorTex", material.GetTexture("_ReflectionColorTex") as Texture2D); - } - if (material.GetFloat("_UseMatCap") > 0.5f) - { - propEnvsDict.Add("_MatCapBlendMask", material.GetTexture("_MatCapBlendMask") as Texture2D); - } - if (material.GetFloat("_UseMatCap2nd") > 0.5f) - { - propEnvsDict.Add("_MatCap2ndBlendMask", material.GetTexture("_MatCap2ndBlendMask") as Texture2D); - } - if (material.GetFloat("_UseRim") > 0.5f) - { - propEnvsDict.Add("_RimColorTex", material.GetTexture("_RimColorTex") as Texture2D); - } - if (material.GetFloat("_UseGlitter") > 0.5f) - { - propEnvsDict.Add("_GlitterColorTex", material.GetTexture("_GlitterColorTex") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_GlitterShapeTex", material.GetTexture("_GlitterShapeTex") as Texture2D)); - if (material.GetFloat("_UseEmission") > 0.5f) - { - propEnvsDict.Add("_EmissionMap", material.GetTexture("_EmissionMap") as Texture2D); - propEnvsDict.Add("_EmissionBlendMask", material.GetTexture("_EmissionBlendMask") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_EmissionGradTex", material.GetTexture("_EmissionGradTex") as Texture2D)); - if (material.GetFloat("_UseEmission2nd") > 0.5f) - { - propEnvsDict.Add("_Emission2ndMap", material.GetTexture("_Emission2ndMap") as Texture2D); - propEnvsDict.Add("_Emission2ndBlendMask", material.GetTexture("_Emission2ndBlendMask") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_Emission2ndGradTex", material.GetTexture("_Emission2ndGradTex") as Texture2D)); - // PropEnvsDict.Add("_ParallaxMap", material.GetTexture("_ParallaxMap") as Texture2D); - if (material.GetFloat("_UseAudioLink") > 0.5f) - { - propEnvsDict.Add("_AudioLinkMask", material.GetTexture("_AudioLinkMask") as Texture2D); - } - // PropertyAndTextures.Add(new PropAndTexture("_DissolveMask", material.GetTexture("_DissolveMask") as Texture2D)); - // PropertyAndTextures.Add(new PropAndTexture("_DissolveNoiseMask", material.GetTexture("_DissolveNoiseMask") as Texture2D)); - if (material.shader.name.Contains("Outline")) - { - propEnvsDict.Add("_OutlineTex", material.GetTexture("_OutlineTex") as Texture2D); - propEnvsDict.Add("_OutlineWidthMask", material.GetTexture("_OutlineWidthMask") as Texture2D); - propEnvsDict.Add("_OutlineVectorTex", material.GetTexture("_OutlineVectorTex") as Texture2D); - } - if (material.shader.name.Contains("Gem")) - { - if (!propEnvsDict.ContainsKey("_SmoothnessTex")) propEnvsDict.Add("_SmoothnessTex", material.GetTexture("_SmoothnessTex") as Texture2D); - } - if (material.shader.name.Contains("Fur")) - { - propEnvsDict.Add("_FurLengthMask", material.GetTexture("_FurLengthMask") as Texture2D); - propEnvsDict.Add("_FurMask", material.GetTexture("_FurMask") as Texture2D); - propEnvsDict.Add("_FurNoiseMask", material.GetTexture("_FurNoiseMask") as Texture2D); - propEnvsDict.Add("_FurVectorTex", material.GetTexture("_FurVectorTex") as Texture2D); - } - - if (bakeSetting == PropertyBakeSetting.NotBake) - { - var propAndTexture2 = new List(); - foreach (var PropEnv in propEnvsDict) - { - propAndTexture2.Add(new PropAndTexture(PropEnv.Key, PropEnv.Value)); - } - return propAndTexture2; - } - - var baker = new TextureBaker(textureManager, propEnvsDict, material, _lilDifferenceRecorder, bakeSetting); - - baker.ColorMulAndHSVG("_MainTex", "_Color", "_MainTexHSVG"); - if (material.GetFloat("_UseMain2ndTex") > 0.5f) - { - baker.ColorMul("_Main2ndTex", "_Color2nd"); - } - if (material.GetFloat("_UseMain3rdTex") > 0.5f) - { - baker.ColorMul("_Main3rdTex", "_Color3rd"); - } - if (material.GetFloat("_UseShadow") > 0.5f) - { - baker.FloatMul("_ShadowStrengthMask", "_ShadowStrength"); - baker.ColorMul("_ShadowColorTex", "_ShadowColor"); - baker.ColorMul("_Shadow2ndColorTex", "_Shadow2ndColor"); - baker.ColorMul("_Shadow3rdColorTex", "_Shadow3rdColor"); - } - if (material.GetFloat("_UseEmission") > 0.5f) - { - baker.ColorMul("_EmissionMap", "_EmissionColor"); - baker.FloatMul("_EmissionBlendMask", "_EmissionBlend"); - } - if (material.GetFloat("_UseEmission2nd") > 0.5f) - { - baker.ColorMul("_Emission2ndMap", "_Emission2ndColor"); - baker.FloatMul("_Emission2ndBlendMask", "_Emission2ndBlend"); - } - if (material.GetFloat("_UseAnisotropy") > 0.5f) - { - baker.FloatMul("_AnisotropyScaleMask", "_AnisotropyScale"); - } - if (material.GetFloat("_UseBacklight") > 0.5f) - { - baker.ColorMul("_BacklightColorTex", "_BacklightColor"); - } - if (material.GetFloat("_UseReflection") > 0.5f) - { - baker.FloatMul("_SmoothnessTex", "_Smoothness"); - baker.FloatMul("_MetallicGlossMap", "_Metallic"); - baker.ColorMul("_ReflectionColorTex", "_ReflectionColor"); - } - if (material.GetFloat("_UseMatCap") > 0.5f) - { - baker.FloatMul("_MatCapBlendMask", "_MatCapBlend"); - } - if (material.GetFloat("_UseMatCap2nd") > 0.5f) - { - baker.FloatMul("_MatCap2ndBlendMask", "_MatCap2ndBlend"); - } - if (material.GetFloat("_UseRim") > 0.5f) - { - baker.ColorMul("_RimColorTex", "_RimColor"); - } - if (material.GetFloat("_UseGlitter") > 0.5f) - { - baker.ColorMul("_GlitterColorTex", "_GlitterColor"); - } - if (material.shader.name.Contains("Outline")) - { - baker.ColorMulAndHSVG("_OutlineTex", "_OutlineColor", "_OutlineTexHSVG"); - baker.OutlineWidthMul("_OutlineWidthMask", "_OutlineWidth"); - } - - var propAndTexture = new List(); - foreach (var PropEnv in propEnvsDict) - { - propAndTexture.Add(new (PropEnv.Key, PropEnv.Value)); - } - return propAndTexture; - } - - /* - 対応状況まとめ - - 基本的にタイリングやオフセットには対応しない。 - 色変更の系統は、白(1,1,1,1)の時、まとめる前と同じ見た目になるようにする。 - マスクなどの系統は、プロパティの値が1の時、まとめてないときと同じようになるようにする。 アウトラインを除く。 - - - 色設定 --- - - < 色Tex * 色Color * (色調補正 * 色補正マスクTex) - ただし、グラデーションは無理。 - - 2nd 3nd & BlendMask 2nd 3nd -- - < (2,3)Tex * (2,3)Color - < (2,3)BlendMaskTex - カラーなどはまとめるが...UV0でかつ、デカール化されてない場合のみ。 - - Dissolve 2nd 3nd - マットキャップと同じような感じで..適当にまとめるべきではない。 - - 影設定 --- - - < マスクと強度Tex * マスクと強度Float - < 影色(1,2,3)Tex * 影色(1,2,3)Color - マスクと強度 や影色等は色と加味してまとめるが、 - 範囲やぼかしなどはどうしようもない。そもそもまとめるべきかというと微妙 - - - ぼかし量マスクやAOMapは私が全く使ったことがないため、勝手がわからないため保留。 - - 発光設定 --- - - 発光 1nd 2nd -- - < 色/マスクTex * 色Color - < マスクTex * マスクFloat - UVModeがUV0の時はまとめる。 - - グラデーションはまず無理。 - 合成モードはどうにもできない。ユーザーが一番いいのを設定すべき。 - - マスクも一応まとめはするが、どのような風になるかは保証できない。 - - ノーマルマップ・光沢設定 --- - - ノーマルマップ 1nd 2nd & 異方性反射 -- - < ノーマルマップ(1,2)Tex - < ノーマルマップ2のマスクと強度 - < 異方性反射ノーマルマップTex - < 異方性反射強度Tex * 異方性反射強度Float - まとめはするがどうなるかは保証できない。 - - 逆光ライト -- - < 色/マスクtex * 色Color - - 反射 -- - < 滑らかさTex * 滑らかさFloat - < 金属度Tex * 金属度Float - < 色/マスクTex * 色Color - はまとめる。 - - MatCap系統はマスクだけマージする - < マットキャップマスク(1,2)Tex * マットキャップブレンド(1,2) - - リムライト -- - < 色/マスクTex * 色Color - - ラメ -- - UV0の場合のみ。 - < 色/マスクTex * 色Color - - Shape周りは勝手がわからないため保留。 - - 拡張設定 --- - - 輪郭線設定 -- - < 色Tex * 色Color * 色調補正 - < マスクと太さTex * マスクと太さFloat** - - ** 全体を見て全体の最大値を加味した値で補正する。ここだけ特殊な設定をする。 - - UV0の時だけまとめる。 - < ノーマルマップ - - 視差マップ -- - 勝手がわからないため保留 - - AudioLink -- - まとめれるものはない。 - - Dissolve -- - そもそもまとめるべきではない。 - - IDMask -- - ステンシル設定 -- - レンダリング設定 -- - ライトベイク設定 -- - テッセレーション -- - 最適化 -- - - これらはそもそもまとめれるものではない。 - - - ファーや屈折、宝石、などの高負荷系統は、独自の設定が強いし、そもそもまとめるべきかというと微妙。分けといたほうが軽いとかがありそう... - - マテリアルをマージしない前提で、とりあえずアトラス化はする。 - - */ - - AtlasShaderRecorder _lilDifferenceRecorder = new (); - - public void AddRecord(Material material) - { - if (material == null) return; - - _lilDifferenceRecorder.AddRecord(material, "_MainTex", material.GetColor("_Color"), material.GetColor("_MainTexHSVG"), ColorEqualityComparer); - if (material.GetFloat("_UseMain2ndTex") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_Main2ndTex", material.GetColor("_Color2nd"), ColorEqualityComparer); - } - if (material.GetFloat("_UseMain3rdTex") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_Main3rdTex", material.GetColor("_Color3rd"), ColorEqualityComparer); - } - if (material.GetFloat("_UseShadow") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_ShadowStrengthMask", material.GetFloat("_ShadowStrength"), FloatEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_ShadowColorTex", material.GetColor("_ShadowColor"), ColorEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_Shadow2ndColorTex", material.GetColor("_Shadow2ndColor"), ColorEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_Shadow3rdColorTex", material.GetColor("_Shadow3rdColor"), ColorEqualityComparer); - } - if (material.GetFloat("_UseEmission") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_EmissionMap", material.GetColor("_EmissionColor"), ColorEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_EmissionBlendMask", material.GetFloat("_EmissionBlend"), FloatEqualityComparer); - } - if (material.GetFloat("_UseEmission2nd") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_Emission2ndMap", material.GetColor("_Emission2ndColor"), ColorEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_Emission2ndBlendMask", material.GetFloat("_Emission2ndBlend"), FloatEqualityComparer); - } - if (material.GetFloat("_UseAnisotropy") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_AnisotropyScaleMask", material.GetFloat("_AnisotropyScale"), FloatEqualityComparer); - } - if (material.GetFloat("_UseBacklight") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_BacklightColorTex", material.GetColor("_BacklightColor"), ColorEqualityComparer); - } - if (material.GetFloat("_UseReflection") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_SmoothnessTex", material.GetFloat("_Smoothness"), FloatEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_MetallicGlossMap", material.GetFloat("_Metallic"), FloatEqualityComparer); - _lilDifferenceRecorder.AddRecord(material, "_ReflectionColorTex", material.GetColor("_ReflectionColor"), ColorEqualityComparer); - } - if (material.GetFloat("_UseMatCap") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_MatCapBlendMask", material.GetFloat("_MatCapBlend"), FloatEqualityComparer); - } - if (material.GetFloat("_UseMatCap2nd") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_MatCap2ndBlendMask", material.GetFloat("_MatCap2ndBlend"), FloatEqualityComparer); - } - if (material.GetFloat("_UseRim") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_RimColorTex", material.GetColor("_RimColor"), ColorEqualityComparer); - } - if (material.GetFloat("_UseGlitter") > 0.5f) - { - _lilDifferenceRecorder.AddRecord(material, "_GlitterColorTex", material.GetColor("_GlitterColor"), ColorEqualityComparer); - } - if (material.shader.name.Contains("Outline")) - { - _lilDifferenceRecorder.AddRecord(material, "_OutlineTex", material.GetColor("_OutlineColor"), material.GetColor("_OutlineTexHSVG"), ColorEqualityComparer); - - var record = _lilDifferenceRecorder.AddRecord(material, "_OutlineWidthMask", material.GetFloat("_OutlineWidth"), FloatEqualityComparer); - record.RecordValue = Mathf.Max(record.RecordValue, material.GetFloat("_OutlineWidth")); - } - if (material.shader.name.Contains("Gem")) - { - _lilDifferenceRecorder.AddRecord(material, "_SmoothnessTex", material.GetFloat("_Smoothness"), FloatEqualityComparer); - } - } - static bool ColorEqualityComparer(Color l, Color r) - { - return l == r; - } - static bool FloatEqualityComparer(float l, float r) - { - return Mathf.Approximately(l, r); - } - public void ClearRecord() - { - _lilDifferenceRecorder.ClearRecord(); - } - - } -} diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs.meta b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs.meta deleted file mode 100644 index d1a9afcc..00000000 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9558643b288c5314b81197d1f08d0cf8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 3ecd88a4f4e08f9b5a106989031841afcf747f62 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 7 Apr 2024 21:57:28 +0900 Subject: [PATCH 037/208] chore: initialize with LateInit --- Editor/Utils/LateInitializeUtility.cs | 13 + .../AtlasShaderSupportUtils.cs | 331 +----------------- 2 files changed, 16 insertions(+), 328 deletions(-) diff --git a/Editor/Utils/LateInitializeUtility.cs b/Editor/Utils/LateInitializeUtility.cs index ad66847f..344b2649 100644 --- a/Editor/Utils/LateInitializeUtility.cs +++ b/Editor/Utils/LateInitializeUtility.cs @@ -1,3 +1,4 @@ +using System.Linq; using net.rs64.TexTransCore.BlendTexture; using net.rs64.TexTransCore.MipMap; using net.rs64.TexTransTool.MultiLayerImage; @@ -29,6 +30,18 @@ public static void Initializer() UnityEditor.EditorApplication.update += TexTransCore.TexTransCoreRuntime.Update.Invoke; MipMapUtility.MipMapShader = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath("5f6d88c53276bb14eace10771023ae01")); + // TODO : これ何とかしないといけない + var atlasShaderSupportList = UnityEditor.AssetDatabase.GetAllAssetPaths() + .Where(i => UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(i) == typeof(TextureAtlas.AtlasScriptableObject.AtlasShaderSupportScriptableObject)) + .Select(i => UnityEditor.AssetDatabase.LoadAssetAtPath(i)) + .ToList(); + + var _defaultSupport = ScriptableObject.CreateInstance(); + _defaultSupport.SupportedShaderComparer = new TextureAtlas.AtlasScriptableObject.AnythingShader(); + _defaultSupport.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new TextureAtlas.AtlasScriptableObject.Anything() } }; + atlasShaderSupportList.Add(_defaultSupport); + TextureAtlas.AtlasShaderSupportUtils.s_atlasShaderSupportList = atlasShaderSupportList; + } } } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index 0609809d..105717d9 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -10,340 +10,15 @@ namespace net.rs64.TexTransTool.TextureAtlas { - internal class AtlasShaderSupportUtils : IDisposable + internal class AtlasShaderSupportUtils { - public List atlasShaderSupportList; - AtlasShaderSupportScriptableObject _defaultSupport; - - internal AtlasShaderSupportUtils() - { -#if UNITY_EDITOR // TODO : これ何とかしないといけない - atlasShaderSupportList = UnityEditor.AssetDatabase.GetAllAssetPaths() - .Where(i => UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(i) == typeof(AtlasShaderSupportScriptableObject)) - .Select(i => UnityEditor.AssetDatabase.LoadAssetAtPath(i)) - .ToList(); -#endif - _defaultSupport = ScriptableObject.CreateInstance(); - _defaultSupport.SupportedShaderComparer = new AnythingShader(); - _defaultSupport.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything() } }; - atlasShaderSupportList.Add(_defaultSupport); - } - - public void Dispose() { UnityEngine.Object.DestroyImmediate(_defaultSupport); } + internal static List s_atlasShaderSupportList; public AtlasShaderSupportScriptableObject GetAtlasShaderSupporter(Material mat) { - return atlasShaderSupportList.First(i => i.SupportedShaderComparer.ThisSupported(mat)); + return s_atlasShaderSupportList.First(i => i.SupportedShaderComparer.ThisSupported(mat)); } - // AtlasDefaultShaderSupport _defaultShaderSupport; - // List _shaderSupports; - - // public PropertyBakeSetting BakeSetting = PropertyBakeSetting.NotBake; - // public AtlasShaderSupportUtils() - // { - // _defaultShaderSupport = new AtlasDefaultShaderSupport(); - // _shaderSupports = InterfaceUtility.GetInterfaceInstance(new Type[] { typeof(AtlasDefaultShaderSupport) }).ToList(); - // } - - // public void AddRecord(Material material) - // { - // var supportShaderI = FindSupportI(material); - // if (supportShaderI != null) - // { - // supportShaderI.AddRecord(material); - // } - // } - // public void ClearRecord() - // { - // foreach (var i in _shaderSupports) - // { - // i.ClearRecord(); - // } - // } - - // public List GetTextures(Material material, ITextureManager textureManager) - // { - // List allTex; - // var supportShaderI = FindSupportI(material); - - // if (supportShaderI != null) { allTex = supportShaderI.GetPropertyAndTextures(textureManager, material, BakeSetting); } - // else { allTex = _defaultShaderSupport.GetPropertyAndTextures(textureManager, material, BakeSetting); } - - // var textures = new List(); - // foreach (var tex in allTex) - // { - // if (tex.Texture != null) - // { - // textures.Add(tex); - // } - // } - - // return textures; - // } - // public void MaterialCustomSetting(Material material) - // { - // var supportShaderI = FindSupportI(material); - // if (supportShaderI != null) - // { - // supportShaderI.MaterialCustomSetting(material); - // } - // } - // public IAtlasShaderSupport FindSupportI(Material material) - // { - // return _shaderSupports.Find(i => { return i.IsThisShader(material); }); - // } } - - internal class AtlasShaderRecorder - { - Dictionary propRecords = new Dictionary(); - - - //ここではテクスチャーは Texture2Dのみ扱う - - //Color - //NormalizedFloat - //UnNormalizedFloat - - public delegate bool ValueEqualityComparer(Value l, Value r); - - public PropRecordAndValue AddRecord(Material mat, string texturePropertyName, Value additionalPropertyValue, ValueEqualityComparer equalityComparer) - where Value : struct - { - if (!mat.HasProperty(texturePropertyName)) { return null; } - if (!propRecords.ContainsKey(texturePropertyName)) { propRecords[texturePropertyName] = new PropRecordAndValue(); } - - var record = propRecords[texturePropertyName]; - var vRecord = record as PropRecordAndValue; - - var texture = mat.GetTexture(texturePropertyName) as Texture2D; - vRecord.ContainsTexture |= texture != null; - - if (!vRecord.IsDifferenceValue.HasValue) - { - vRecord.IsDifferenceValue = false; - vRecord.RecordValue = additionalPropertyValue; - } - else - { - vRecord.IsDifferenceValue |= !equalityComparer.Invoke(vRecord.RecordValue, additionalPropertyValue); - } - return vRecord; - } - public PropRecordAndTowValue AddRecord(Material mat, string texturePropertyName, Value additionalPropertyValue, Value additionalPropertyValue2, ValueEqualityComparer equalityComparer) - where Value : struct - { - if (!mat.HasProperty(texturePropertyName)) { return null; } - if (!propRecords.ContainsKey(texturePropertyName)) { propRecords[texturePropertyName] = new PropRecordAndTowValue(); } - - var record = propRecords[texturePropertyName]; - var vRecord = record as PropRecordAndTowValue; - - var texture = mat.GetTexture(texturePropertyName) as Texture2D; - vRecord.ContainsTexture |= texture != null; - - if (!vRecord.IsDifferenceValue.HasValue) - { - vRecord.IsDifferenceValue = false; - vRecord.RecordValue = additionalPropertyValue; - vRecord.RecordValue2 = additionalPropertyValue2; - } - else - { - vRecord.IsDifferenceValue |= !equalityComparer.Invoke(vRecord.RecordValue, additionalPropertyValue); - vRecord.IsDifferenceValue2 |= !equalityComparer.Invoke(vRecord.RecordValue2, additionalPropertyValue2); - } - return vRecord; - } - - public PropRecord GetRecord(string texturePropertyName) - { - if (!propRecords.ContainsKey(texturePropertyName)) { return null; } - return propRecords[texturePropertyName]; - } - - - //テクスチャーのプロパティに付随する何かが値の違いがあるかやテクスチャが存在するかなどを記録する - public abstract class PropRecord - { - public bool ContainsTexture; - } - public class PropRecordAndValue : PropRecord where Value : struct - { - public bool? IsDifferenceValue; - public Value RecordValue; - } - public class PropRecordAndTowValue : PropRecord where Value : struct - { - public bool? IsDifferenceValue; - public Value RecordValue; - public bool? IsDifferenceValue2; - public Value RecordValue2; - } - - public void ClearRecord() { propRecords.Clear(); } - } - internal class TextureBaker - { - Material material; - IOriginTexture textureManager; - Dictionary propEnvs; - AtlasShaderRecorder atlasShaderRecorder; - PropertyBakeSetting bakeSetting; - public TextureBaker(IOriginTexture texManager, Dictionary propEnvDict, Material mat, AtlasShaderRecorder shaderRecorder, PropertyBakeSetting bakeSettingEnum) - { - textureManager = texManager; - propEnvs = propEnvDict; - material = mat; - atlasShaderRecorder = shaderRecorder; - bakeSetting = bakeSettingEnum; - } - - public void ColorMul(string texPropName, string colorPropName) - { - var color = material.GetColor(colorPropName); - var record = atlasShaderRecorder.GetRecord(texPropName) as AtlasShaderRecorder.PropRecordAndValue; - - if (!record.IsDifferenceValue.HasValue) { return; } - if (!record.IsDifferenceValue.Value) { return; } - - var texture = propEnvs.ContainsKey(texPropName) ? propEnvs[texPropName] : null; - - if (texture == null) - { - if (record.ContainsTexture || bakeSetting == PropertyBakeSetting.BakeAllProperty) - { - propEnvs[texPropName] = TexUT.CreateColorTexForRT(color); - } - } - else - { - var originTexture = texture is Texture2D ? textureManager.GetOriginTempRt(texture as Texture2D, texture.width) : texture; - propEnvs[texPropName] = TexLU.CreateMultipliedRenderTexture(originTexture, color); - if (originTexture is RenderTexture tempRT) { RenderTexture.ReleaseTemporary(tempRT); } - } - } - - public void FloatMul(string texPropName, string floatProp) - { - var propFloat = material.GetFloat(floatProp); - var record = atlasShaderRecorder.GetRecord(texPropName) as AtlasShaderRecorder.PropRecordAndValue; - var propTex = propEnvs.ContainsKey(texPropName) ? propEnvs[texPropName] : null; - - if (!record.IsDifferenceValue.HasValue || !record.IsDifferenceValue.Value) - { - if (propTex == null && record.ContainsTexture) - { - propEnvs[texPropName] = TexUT.CreateColorTexForRT(new Color(propFloat, propFloat, propFloat, propFloat)); - } - - return; - } - - if (propTex == null) - { - if (record.ContainsTexture || bakeSetting == PropertyBakeSetting.BakeAllProperty) - { - propEnvs[texPropName] = TexUT.CreateColorTexForRT(new Color(propFloat, propFloat, propFloat, propFloat)); - } - } - else - { - var originPropTex = propTex is Texture2D ? textureManager.GetOriginTempRt(propTex as Texture2D, propTex.width) : propTex; - propEnvs[texPropName] = TexLU.CreateMultipliedRenderTexture(originPropTex, new Color(propFloat, propFloat, propFloat, propFloat)); - if (originPropTex is RenderTexture tempRT) { RenderTexture.ReleaseTemporary(tempRT); } - } - } - - public void ColorMulAndHSVG(string texPropName, string colorPropName, string hsvgPropName) - { - var color = material.GetColor(colorPropName); - var record = atlasShaderRecorder.GetRecord(texPropName) as AtlasShaderRecorder.PropRecordAndTowValue; - - var texture = propEnvs.ContainsKey(texPropName) ? propEnvs[texPropName] : null; - - if (record.IsDifferenceValue.HasValue && record.IsDifferenceValue.Value) - { - if (texture == null) - { - if (record.ContainsTexture || bakeSetting == PropertyBakeSetting.BakeAllProperty) - { - propEnvs[texPropName] = TexUT.CreateColorTexForRT(color); - } - } - else - { - var originPropTex = texture is Texture2D ? textureManager.GetOriginTempRt(texture as Texture2D, texture.width) : texture; - texture = TexLU.CreateMultipliedRenderTexture(originPropTex, color); - if (originPropTex is RenderTexture tempRT) { RenderTexture.ReleaseTemporary(tempRT); } - } - } - - if (record.IsDifferenceValue2.HasValue && record.IsDifferenceValue2.Value) - { - var colorAdjustMask = propEnvs.ContainsKey("_MainColorAdjustMask") ? propEnvs["_MainColorAdjustMask"] : null; - - var colorAdjustMat = new Material(Shader.Find("Hidden/ColorAdjustShader")); - if (colorAdjustMask != null) { colorAdjustMat.SetTexture("_Mask", colorAdjustMask); } - colorAdjustMat.SetColor("_HSVG", material.GetColor(hsvgPropName)); - - if (texture is Texture2D texture2d && texture2d != null) - { - var textureRt = RenderTexture.GetTemporary(texture2d.width, texture2d.height, 0); - Graphics.Blit(texture2d, textureRt, colorAdjustMat); - texture = textureRt; - } - else if (texture is RenderTexture textureRt && textureRt != null) - { - var swapRt = RenderTexture.GetTemporary(textureRt.descriptor); - - Graphics.CopyTexture(textureRt, swapRt); - Graphics.Blit(swapRt, textureRt, colorAdjustMat); - - RenderTexture.ReleaseTemporary(swapRt); - texture = textureRt; - } - UnityEngine.Object.DestroyImmediate(colorAdjustMat); - } - - - propEnvs[texPropName] = texture; - } - - public void OutlineWidthMul(string texPropName, string floatProp) - { - var record = atlasShaderRecorder.GetRecord(texPropName) as AtlasShaderRecorder.PropRecordAndValue; - var outlineWidth = material.GetFloat(floatProp) / record.RecordValue; - - var outlineWidthMask = propEnvs.ContainsKey(texPropName) ? propEnvs[texPropName] : null; - - if (!record.IsDifferenceValue.HasValue || !record.IsDifferenceValue.Value) - { - //ほかはテクスチャが存在しているがfloatの値が変わっていない場合にフォールバック用の値を書き込んだものを作らないといけない。 - if (outlineWidthMask == null && record.ContainsTexture) - { - propEnvs[texPropName] = TexUT.CreateColorTexForRT(new Color(outlineWidth, outlineWidth, outlineWidth, outlineWidth)); - } - - return; - } - - if (outlineWidthMask == null) - { - if (record.ContainsTexture || bakeSetting == PropertyBakeSetting.BakeAllProperty) - { - outlineWidthMask = TexUT.CreateColorTexForRT(new Color(outlineWidth, outlineWidth, outlineWidth, outlineWidth)); - } - } - else - { - var originPropTex = outlineWidthMask is Texture2D ? textureManager.GetOriginTempRt(outlineWidthMask as Texture2D, outlineWidthMask.width) : outlineWidthMask; - outlineWidthMask = TexLU.CreateMultipliedRenderTexture(originPropTex, new Color(outlineWidth, outlineWidth, outlineWidth, outlineWidth)); - if (originPropTex is RenderTexture tempRT) { RenderTexture.ReleaseTemporary(tempRT); } - } - propEnvs[texPropName] = outlineWidthMask; - } - } } From 174e824d14ad1b4c08873e1815e453fc8d8dd369 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 7 Apr 2024 21:58:59 +0900 Subject: [PATCH 038/208] chore: un use aspectIslandsRectPool --- Runtime/TextureAtlas/AtlasContext.cs | 108 ++++++++++------- Runtime/TextureAtlas/AtlasTexture.cs | 173 ++++++++++++--------------- TexTransCore/Island/IslandUtility.cs | 20 ++-- 3 files changed, 149 insertions(+), 152 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs index 20dadad5..1015a1c7 100644 --- a/Runtime/TextureAtlas/AtlasContext.cs +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -9,6 +9,7 @@ using net.rs64.TexTransTool.TextureAtlas.AAOCode; using net.rs64.TexTransTool.Utils; using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.TextureAtlas { @@ -62,67 +63,41 @@ public AtlasSubData(int meshID, int subMeshIndex, int materialGroupID) : this() } public AtlasContext(List targetMaterials, List inputRenderers, bool usePropertyBake) { + Profiler.BeginSample("FiledInitialize"); var materialHash = targetMaterials.ToHashSet(); - + Profiler.BeginSample("AtlasShaderSupportUtils:ctor"); var shaderSupports = new AtlasShaderSupportUtils(); + Profiler.EndSample(); + Profiler.BeginSample("GetSupporter"); var supporters = targetMaterials.Select(m => (m, shaderSupports.GetAtlasShaderSupporter(m))).ToDictionary(i => i.m, i => i.Item2); + Profiler.EndSample(); + Profiler.BeginSample("mat2AtlasShaderTex"); var material2AtlasTargets = supporters.Select(kv => (kv.Key, kv.Value.GetAtlasShaderTexture2D(kv.Key))).ToDictionary(i => i.Key, i => i.Item2.ToDictionary(p => p.PropertyName, p => p)); + Profiler.EndSample(); MaterialToAtlasShaderTexDict = material2AtlasTargets; AtlasShaderSupportUtils = shaderSupports; AtlasShaderSupporters = supporters; + Profiler.EndSample(); - var materialGroupList = new List>>(); + Profiler.BeginSample("LookUp MatGroup"); + var materialGroupList = new List>>(); foreach (var matKv in material2AtlasTargets) { - var index = materialGroupList.FindIndex( - matGroup => matGroup.All(m2 => + var index = materialGroupList.FindIndex(matGroup => + matGroup.All(m2 => supporters[matKv.Key] == supporters[m2.Key] - && (usePropertyBake ? BakedPropEqual(m2.Value, matKv.Value) : PropEqual(m2.Value, matKv.Value) ) - ) - ); + && (usePropertyBake ? BakedPropEqual(m2.Value, matKv.Value) : PropEqual(m2.Value, matKv.Value))) + ); if (index == -1) { materialGroupList.Add(new() { { matKv.Key, matKv.Value } }); } else { materialGroupList[index].Add(matKv.Key, matKv.Value); } } - - bool PropEqual(Dictionary propL, Dictionary propR) - { - foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) - { - if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { continue; } - var l = propL[propName]; - var r = propR[propName]; - if (l.Texture2D == null || r.Texture2D == null) { continue; } - if (l.Texture2D != r.Texture2D) { return false; } - - if (l.TextureScale != r.TextureScale) { return false; } - if (l.TextureTranslation != r.TextureTranslation) { return false; } - - } - return true; - } - bool BakedPropEqual(Dictionary propL, Dictionary propR) - { - foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) - { - if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { return false; } - - var l = propL[propName]; - var r = propR[propName]; - - if (l.Texture2D == null || r.Texture2D == null) { return false; } - if (l.Texture2D != r.Texture2D) { return false; } - - if (l.TextureScale != r.TextureScale) { return false; } - if (l.TextureTranslation != r.TextureTranslation) { return false; } - - if (BakeProperty.PropertyListEqual(l.BakeProperties, r.BakeProperties) == false) { return false; } - } - return true; - } MaterialGroup = materialGroupList.Select(i => new OrderedHashSet(i.Keys)).ToArray(); + Profiler.EndSample(); + + Profiler.BeginSample("Normalize And Bake Mash"); var TargetRenderers = inputRenderers.Where(r => r.sharedMaterials.Any(m => materialHash.Contains(m))).ToArray(); var normalizedMesh = SubVertNormalize(TargetRenderers); @@ -150,7 +125,9 @@ bool BakedPropEqual(Dictionary propL, Dictionary i.Key).ToArray(); + Profiler.EndSample(); + Profiler.BeginSample("Get AtlasSubAll"); AtlasSubAll = new(); var atlasSubSets = new List(); for (var ri = 0; TargetRenderers.Length > ri; ri += 1) @@ -172,7 +149,9 @@ bool BakedPropEqual(Dictionary propL, Dictionary>(); foreach (var atSub in AtlasSubAll) { @@ -184,8 +163,10 @@ bool BakedPropEqual(Dictionary propL, Dictionary (i.MeshID, i.MaterialGroupID))) { @@ -285,7 +266,9 @@ bool BakedPropEqual(Dictionary propL, Dictionary(); var IslandLinkList = new LinkedList(); @@ -304,6 +287,7 @@ bool BakedPropEqual(Dictionary propL, Dictionary SubVertNormalize(Renderer[] targetRenderers) if (!isOverSubMesh && !isCrossSubMesh) { normalizedMesh[mesh] = UnityEngine.Object.Instantiate(mesh); continue; } + Profiler.BeginSample(MkR.Key.name + "-Normalize"); normalizedMesh[mesh] = NormalizedMesh(mesh, maxSlot); + Profiler.EndSample(); } return normalizedMesh; @@ -470,12 +456,46 @@ Mesh NormalizedMesh(Mesh mesh, int expandSlot) } } + static bool PropEqual(Dictionary propL, Dictionary propR) + { + foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) + { + if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { continue; } + var l = propL[propName]; + var r = propR[propName]; + if (l.Texture2D == null || r.Texture2D == null) { continue; } + if (l.Texture2D != r.Texture2D) { return false; } + + if (l.TextureScale != r.TextureScale) { return false; } + if (l.TextureTranslation != r.TextureTranslation) { return false; } + + } + return true; + } + static bool BakedPropEqual(Dictionary propL, Dictionary propR) + { + foreach (var propName in propL.Keys.Concat(propR.Keys).Distinct()) + { + if (!propL.ContainsKey(propName) || !propR.ContainsKey(propName)) { return false; } + + var l = propL[propName]; + var r = propR[propName]; + + if (l.Texture2D == null || r.Texture2D == null) { return false; } + if (l.Texture2D != r.Texture2D) { return false; } + + if (l.TextureScale != r.TextureScale) { return false; } + if (l.TextureTranslation != r.TextureTranslation) { return false; } + + if (BakeProperty.PropertyListEqual(l.BakeProperties, r.BakeProperties) == false) { return false; } + } + return true; + } public void Dispose() { foreach (var md in MeshDataDict) { md.Value.Dispose(); } foreach (var mesh in _bakedMesh) { UnityEngine.Object.DestroyImmediate(mesh); } - AtlasShaderSupportUtils.Dispose(); } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index a947ed4a..8c365473 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -120,6 +120,7 @@ public struct MatSelector bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) { + Profiler.BeginSample("AtlasData and FindRenderers"); var texManage = domain.GetTextureManager(); atlasData = new AtlasData(); @@ -132,24 +133,12 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) atlasData.AtlasInMaterials = targetMaterials; var atlasSetting = AtlasSetting; var propertyBakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; - // var atlasReferenceData = new AtlasReferenceData(targetMaterials, Renderers); + Profiler.EndSample(); + Profiler.BeginSample("AtlasContext:ctor"); var atlasContext = new AtlasContext(targetMaterials, Renderers, propertyBakeSetting != PropertyBakeSetting.NotBake); Profiler.EndSample(); - - //サブメッシュより多いスロットの存在可否 - // if (atlasReferenceData.AtlasMeshDataList.Any(i => i.Triangles.Count < i.MaterialIndex.Length)) { TTTRuntimeLog.Warning("AtlasTexture:error:MoreMaterialSlotThanSubMesh"); } - - - //ターゲットとなるマテリアルやそのマテリアルが持つテクスチャを引き出すフェーズ - // shaderSupports.BakeSetting = atlasSetting.MergeMaterials ? atlasSetting.PropertyBakeSetting : PropertyBakeSetting.NotBake; - // var materialTextures = new Dictionary>(); - // foreach (var mat in targetMaterials) { shaderSupports.AddRecord(mat); } - // foreach (var mat in targetMaterials) { materialTextures[mat] = shaderSupports.GetTextures(mat, texManage); } - - - var islandSizeOffset = GetTextureSizeOffset(SelectMatList.Select(i => i.Material), atlasSetting); //アイランドまわり @@ -169,6 +158,7 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } Profiler.EndSample(); } + Profiler.BeginSample("IslandFineTuning"); var islandArray = atlasContext.Islands; var rectArray = new IslandRect[islandArray.Length]; var index = 0; @@ -216,28 +206,10 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } } - // foreach (var mat in SelectMatList) - // { - // var textureSizeOffSet = islandSizeOffset[mat.Material]; - // for (var i = 0; rectArray.Length > i; i += 1) - // { - // var desc = islandDescription[i]; - // var matSlotRef = desc.MaterialSlot; - // if (!domain.OriginEqual(desc.Renderer.sharedMaterials[matSlotRef], mat.Material)) { continue; } - - // rectArray[i].Size *= textureSizeOffSet; - - // switch (MaterialToIslandFineTuningModeSelect) - // { - // case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= mat.MaterialFineTuningValue; break; } - // case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = mat.MaterialFineTuningValue; break; } - // default: break; - // } - // } - // } foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, rectArray, islandArray, islandDescription, domain); } for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = Mathf.Clamp01(sizePriority[i]); } + Profiler.EndSample(); IAtlasIslandRelocator relocator = atlasSetting.AtlasIslandRelocator != null ? UnityEngine.Object.Instantiate(atlasSetting.AtlasIslandRelocator) : new NFDHPlasFC(); @@ -319,9 +291,9 @@ void ScaleApplyUp(float scaleUpStep) } - if (atlasSetting.PixelNormalize) { + Profiler.BeginSample("AtlasReferenceData:PixelNormalize"); for (var i = 0; relocatedRect.Length > i; i += 1) { var island = relocatedRect[i]; @@ -329,21 +301,25 @@ void ScaleApplyUp(float scaleUpStep) island.Pivot.x = Mathf.Round(island.Pivot.x * atlasSetting.AtlasTextureSize) / atlasSetting.AtlasTextureSize; relocatedRect[i] = island; } + Profiler.EndSample(); } + Profiler.BeginSample("IslandMinClamp"); for (var i = 0; relocatedRect.Length > i; i += 1) { if (relocatedRect[i].Size.x <= 0.0001f) { relocatedRect[i].Size.x = 0.0001f; } if (relocatedRect[i].Size.y <= 0.0001f) { relocatedRect[i].Size.y = 0.0001f; } }//Islandが小さすぎると RectTangleMoveのコピーがうまくいかない + Profiler.EndSample(); //上側を削れるかを見る + Profiler.BeginSample("IslandHight Calculate"); var height = IslandRectUtility.CalculateIslandsMaxHeight(relocatedRect); var atlasTextureHeightSize = Mathf.Max(GetHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動しそうだからクランプ + Profiler.EndSample(); // var areaSum = IslandRectUtility.CalculateAllAreaSum(islandRectPool.Values); // Debug.Log(areaSum + ":AreaSum" + "-" + height + ":height"); - var aspectIslandsRectPool = GetAspectIslandRect(relocatedRect, atlasSetting, atlasTextureHeightSize); //新しいUVを持つMeshを生成するフェーズ @@ -351,6 +327,7 @@ void ScaleApplyUp(float scaleUpStep) var compiledMeshes = new List(); var normMeshes = atlasContext.Meshes.Select(m => atlasContext.NormalizeMeshes[m]).ToArray(); var subSetMovedUV = new NativeArray[atlasContext.AtlasSubSets.Count]; + var scale = atlasSetting.AtlasTextureSize / atlasTextureHeightSize; for (int subSetIndex = 0; atlasContext.AtlasSubSets.Count > subSetIndex; subSetIndex += 1) { var subSet = atlasContext.AtlasSubSets[subSetIndex]; @@ -365,44 +342,49 @@ void ScaleApplyUp(float scaleUpStep) var movedLink = new LinkedList(); - for (var islandIndex = 0; aspectIslandsRectPool.Length > islandIndex; islandIndex += 1) + for (var islandIndex = 0; relocatedRect.Length > islandIndex; islandIndex += 1) { if (subSet.Any(subData => atlasContext.IslandSubData[islandIndex] == subData)) { originLink.AddLast(atlasContext.Islands[islandIndex]); - movedLink.AddLast(aspectIslandsRectPool[islandIndex]); + movedLink.AddLast(relocatedRect[islandIndex]); } } - // var thisTag = new AtlasSlotRef(amdIndex, slotIndex); - // if (containsSlotRefs.Contains(thisTag)) { foreach (var islandKV in AtlasReferenceData.IslandFind(thisTag, aspectIslandsRectPool)) { movedPool.Add(islandKV.Key, islandKV.Value); } } - // else - // { - // var msmRef = new MSMRef(atlasMeshData.ReferenceMesh, slotIndex, atlasMeshData.MaterialIndex[slotIndex]); - // var identicalTag = atlasReferenceData.FindIdenticalSlotRef(containsSlotRefs, msmRef); - - // if (!identicalTag.HasValue) { continue; } - // foreach (var islandKV in AtlasReferenceData.IslandFind(identicalTag.Value, aspectIslandsRectPool)) { movedPool.Add(islandKV.Key, islandKV.Value); } - // } - - var movedUV = new NativeArray(meshData.VertexUV, Allocator.Temp); IslandUtility.IslandPoolMoveUV(meshData.VertexUV, movedUV, originLink.ToArray(), movedLink.ToArray()); - newMesh.SetUVs(0, movedUV); - if (AtlasSetting.WriteOriginalUV) { newMesh.SetUVs(1, meshData.VertexUV); } subSetMovedUV[subSetIndex] = movedUV; + if (atlasSetting.AtlasTextureSize != atlasTextureHeightSize) + { + using (var aspectApplyUV = new NativeArray(movedUV, Allocator.Temp)) + { + var writer = aspectApplyUV.AsSpan(); + foreach(var vi in originLink.SelectMany(i => i.GetVertexIndex()).Distinct()) + { + writer[vi].x = movedUV[vi].x; + writer[vi].y = movedUV[vi].y * scale; + } + newMesh.SetUVs(0, aspectApplyUV); + } + } + else + { + newMesh.SetUVs(0, movedUV); + } + if (AtlasSetting.WriteOriginalUV) { newMesh.SetUVs(1, meshData.VertexUV); } compiledMeshes.Add(new AtlasData.AtlasMeshAndDist(distMesh, newMesh, subSet.Select(i => i?.MaterialGroupID ?? -1).ToArray())); } atlasData.Meshes = compiledMeshes; Profiler.EndSample(); - var textureManager = domain.GetTextureManager(); //アトラス化したテクスチャーを生成するフェーズ var compiledAtlasTextures = new Dictionary(); + Profiler.BeginSample("GetGroupedTextures"); var groupedTextures = GetGroupedTextures(atlasContext, propertyBakeSetting, out var containsProperty); + Profiler.EndSample(); Dictionary> GetGroupedTextures(AtlasContext atlasContext, PropertyBakeSetting propertyBakeSetting, out HashSet property) { @@ -428,13 +410,13 @@ Dictionary ZipDictAndOffset(IEnumerable i.Value.Texture2D != null).Value; if (atlasTex.TextureScale == Vector2.zero && atlasTex.TextureTranslation == Vector2.zero) { - dict[kv.Key] = textureManager.GetOriginTempRt(atlasTex.Texture2D); + dict[kv.Key] = texManage.GetOriginTempRt(atlasTex.Texture2D); } else { var tex = atlasTex.Texture2D; - var originTex = textureManager.GetOriginTempRt(tex); + var originTex = texManage.GetOriginTempRt(tex); originTex.ApplyTextureST(atlasTex.TextureScale, atlasTex.TextureTranslation); dict[kv.Key] = originTex; @@ -485,7 +467,7 @@ Dictionary ZipDictAndOffset(IEnumerable ZipDictAndOffset(IEnumerable I.PropertyName == propName); - // if (souseProp2Tex == null) continue; if (!gTex.Value.TryGetValue(propName, out var sTexture)) { continue; } - // var findMaterial = MatPropKV.Key; var findMaterialID = gTex.Key; if (rectTangleMove) { @@ -567,11 +544,13 @@ Dictionary ZipDictAndOffset(IEnumerable i.HasValue).Where(i => i.Value.MaterialGroupID == findMaterialID).Select(i => i.Value); if (!transTargets.Any()) { continue; } - var triangles = transTargets.SelectMany(subData => atlasContext.IslandDict[subData].SelectMany(i => i.triangles)); + var triangles = new NativeArray(transTargets.SelectMany(subData => atlasContext.IslandDict[subData].SelectMany(i => i.triangles)).ToArray(), Allocator.TempJob); var originUV = atlasContext.MeshDataDict[atlasContext.NormalizeMeshes[atlasContext.Meshes[transTargets.First().MeshID]]].VertexUV; var transData = new TransData(triangles, subSetMovedUV[subSetIndex], originUV); ForTrans(targetRT, sTexture, transData, atlasSetting.GetTexScalePadding * 0.5f, null, true); + + triangles.Dispose(); } } @@ -579,6 +558,14 @@ Dictionary ZipDictAndOffset(IEnumerable GetTextureSizeOffset(IEnumerable i; i += 1) - { - var islandRect = islandRectPool[i]; - islandRect.Pivot.y *= heightSizeScale; - islandRect.Size.y *= heightSizeScale; - aspectIslands[i] = islandRect; - } - return aspectIslands; - } - private static int GetHeightSize(int atlasTextureSize, float height) { switch (height) @@ -737,31 +708,39 @@ internal override void Apply(IDomain domain = null) private void TransMoveRectIsland(Texture souseTex, RenderTexture targetRT, Dictionary notAspectIslandPairs, float uvScalePadding) where TIslandRect : IIslandRect { uvScalePadding *= 0.5f; - var targetAspect = targetRT.width / (float)targetRT.height; - var sUV = new List(); - var tUV = new List(); - var triangles = new List(); - - var nawIndex = 0; - foreach (var islandPair in notAspectIslandPairs) + using (var sUV = new NativeArray(notAspectIslandPairs.Count * 4, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + using (var tUV = new NativeArray(notAspectIslandPairs.Count * 4, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + using (var triangles = new NativeArray(notAspectIslandPairs.Count * 2, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) { - var (Origin, Moved) = (islandPair.Key, islandPair.Value); - var rectScalePadding = Moved.UVScaleToRectScale(uvScalePadding); + var triSpan = triangles.AsSpan(); + var sUVSpan = sUV.AsSpan(); + var tUVSpan = tUV.AsSpan(); + + var triIndex = 0; + var vertIndex = 0; + foreach (var islandPair in notAspectIslandPairs) + { + var (Origin, Moved) = (islandPair.Key, islandPair.Value); + var rectScalePadding = Moved.UVScaleToRectScale(uvScalePadding); - var originVertexes = Origin.GenerateRectVertexes(rectScalePadding); - var movedVertexes = Moved.GenerateRectVertexes(rectScalePadding); + var originVertexes = Origin.GenerateRectVertexes(rectScalePadding); + var movedVertexes = Moved.GenerateRectVertexes(rectScalePadding); - triangles.Add(new(nawIndex + 0, nawIndex + 1, nawIndex + 2)); - triangles.Add(new(nawIndex + 0, nawIndex + 2, nawIndex + 3)); - nawIndex += 4; - sUV.AddRange(originVertexes); - tUV.AddRange(movedVertexes.Select(v => new Vector2(v.x, v.y * targetAspect))); - } + triSpan[triIndex] = new(vertIndex + 0, vertIndex + 1, vertIndex + 2); + triSpan[triIndex + 1] = new(vertIndex + 0, vertIndex + 2, vertIndex + 3); + triIndex += 2; - TransTexture.ForTrans(targetRT, souseTex, new TransData(triangles, tUV, sUV), argTexWrap: TextureWrap.Loop); + foreach (var v in originVertexes.Zip(movedVertexes, (o, m) => (o, m))) + { + sUVSpan[vertIndex] = v.o; + tUVSpan[vertIndex] = v.m; + vertIndex += 1; + } + } + TransTexture.ForTrans(targetRT, souseTex, new TransData(triangles, tUV, sUV), argTexWrap: TextureWrap.Loop); + } } - internal static float Frac(float v) { return v > 0 ? v - Mathf.Floor(v) : v - Mathf.Ceil(v); } private static Material GenerateAtlasMat(Material targetMat, List atlasTex, AtlasShaderSupportUtils shaderSupport, bool forceSetTexture) { diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index c7dd991e..585f687d 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -326,11 +326,9 @@ public static float UVScaleToRectScale(this TIslandRect islandRect, return new Vector2(uvScaleValue, uvScaleValue).magnitude / islandRect.Size.magnitude; } - public static IEnumerable GenerateRectVertexes(this TIslandRect islandRect, float rectScalePadding = 0.1f, List outPutQuad = null) + public static IEnumerable GenerateRectVertexes(this TIslandRect islandRect, float rectScalePadding = 0.1f) where TIslandRect : IIslandRect { - outPutQuad?.Clear(); outPutQuad ??= new(); - var rectScale = Mathf.Abs(rectScalePadding) * islandRect.Size.magnitude; var paddingVector = Vector2.ClampMagnitude(Vector2.one, rectScale); @@ -339,17 +337,17 @@ public static IEnumerable GenerateRectVertexes(this TIslan if (!islandRect.Is90Rotation) { - yield return (new(leftDown.x - paddingVector.x, leftDown.y - paddingVector.y)); - yield return (new(leftDown.x - paddingVector.x, rightUp.y + paddingVector.y)); - yield return (new(rightUp.x + paddingVector.x, rightUp.y + paddingVector.y)); - yield return (new(rightUp.x + paddingVector.x, leftDown.y - paddingVector.y)); + yield return new(leftDown.x - paddingVector.x, leftDown.y - paddingVector.y); + yield return new(leftDown.x - paddingVector.x, rightUp.y + paddingVector.y); + yield return new(rightUp.x + paddingVector.x, rightUp.y + paddingVector.y); + yield return new(rightUp.x + paddingVector.x, leftDown.y - paddingVector.y); } else { - yield return (new(leftDown.x - paddingVector.x, rightUp.y + paddingVector.y)); - yield return (new(rightUp.x + paddingVector.x, rightUp.y + paddingVector.y)); - yield return (new(rightUp.x + paddingVector.x, leftDown.y - paddingVector.y)); - yield return (new(leftDown.x - paddingVector.x, leftDown.y - paddingVector.y)); + yield return new(leftDown.x - paddingVector.x, rightUp.y + paddingVector.y); + yield return new(rightUp.x + paddingVector.x, rightUp.y + paddingVector.y); + yield return new(rightUp.x + paddingVector.x, leftDown.y - paddingVector.y); + yield return new(leftDown.x - paddingVector.x, leftDown.y - paddingVector.y); } } } From 39a715320bbb061d26692c9adf7080afae416663 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 7 Apr 2024 22:06:25 +0900 Subject: [PATCH 039/208] chore: scale offset are not Multiply --- Runtime/TextureAtlas/AtlasTexture.cs | 8 +++++--- Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs | 2 +- Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs | 8 ++++---- Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 8c365473..90752d63 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -169,6 +169,7 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } var sizePriority = new float[islandArray.Length]; for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = 1f; } + var scaleArray = new float[islandArray.Length]; for (var i = 0; scaleArray.Length > i; i += 1) { scaleArray[i] = 1f; } var islandDescription = new IslandSelector.IslandDescription[islandArray.Length]; for (var i = 0; islandDescription.Length > i; i += 1) { @@ -200,15 +201,16 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) switch (MaterialToIslandFineTuningModeSelect) { - case MaterialToIslandFineTuningMode.SizeOffset: { rectArray[i].Size *= materialFineTuningValue; break; } + case MaterialToIslandFineTuningMode.SizeOffset: { scaleArray[i] = materialFineTuningValue; break; } case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = materialFineTuningValue; break; } default: break; } } - foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, rectArray, islandArray, islandDescription, domain); } + foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, scaleArray, islandArray, islandDescription, domain); } for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = Mathf.Clamp01(sizePriority[i]); } + for (var i = 0; scaleArray.Length > i; i += 1) { rectArray[i].Size *= scaleArray[i]; } Profiler.EndSample(); @@ -360,7 +362,7 @@ void ScaleApplyUp(float scaleUpStep) using (var aspectApplyUV = new NativeArray(movedUV, Allocator.Temp)) { var writer = aspectApplyUV.AsSpan(); - foreach(var vi in originLink.SelectMany(i => i.GetVertexIndex()).Distinct()) + foreach (var vi in originLink.SelectMany(i => i.GetVertexIndex()).Distinct()) { writer[vi].x = movedUV[vi].x; writer[vi].y = movedUV[vi].y * scale; diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs index 5cc4d89f..a8657f5d 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs @@ -11,6 +11,6 @@ internal interface IIslandFineTuner { //islands と islandDescriptions は書き込みしないように、 //sizePriority と islandRect を操作して調整していく感じ - void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); + void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs index 8eab4966..ceaa1663 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs @@ -13,16 +13,16 @@ internal class SizeOffset : IIslandFineTuner [Range(0, 1)] public float OffsetValue = 1f; public AbstractIslandSelector IslandSelector; - public void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + + public void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) { var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); - for (var i = 0; islandRect.Length > i; i += 1) + for (var i = 0; setSize.Length > i; i += 1) { if (!targetBit[i]) { continue; } - islandRect[i].Size *= OffsetValue; + setSize[i] = OffsetValue; } } - } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs index 50afc726..adede9a9 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs @@ -13,11 +13,11 @@ internal class SizePriority : IIslandFineTuner [Range(0, 1)] public float PriorityValue = 1f; public AbstractIslandSelector IslandSelector; - public void IslandFineTuning(float[] sizePriority, IslandRect[] islandRect, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + public void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) { var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); - for (var i = 0; islandRect.Length > i; i += 1) + for (var i = 0; sizePriority.Length > i; i += 1) { if (!targetBit[i]) { continue; } sizePriority[i] = PriorityValue; From fcdaf016e0fa300e4f077856d43f0ba3c891e64e Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 7 Apr 2024 22:41:19 +0900 Subject: [PATCH 040/208] chore: add localize IslandFineTuners --- Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs | 7 ++----- Editor/Localize/en_US.po | 6 ++++++ Editor/Localize/ja_JP.po | 13 +++++++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index e8c98e9f..f9ff7491 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -60,9 +60,6 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(sMatSelectors, "AtlasTexture:prop:SelectedMaterialView".Glc()); EditorGUI.indentLevel -= 1; - var sIslandFineTuners = sAtlasSetting.FindPropertyRelative("IslandFineTuners"); - EditorGUILayout.PropertyField(sIslandFineTuners, "AtlasTexture:prop:IslandFineTuners".Glc()); - DrawAtlasSettings(sAtlasSetting); @@ -88,8 +85,8 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) var sWriteOriginalUV = sAtlasSettings.FindPropertyRelative("WriteOriginalUV"); var sIncludeDisabledRenderer = sAtlasSettings.FindPropertyRelative("IncludeDisabledRenderer"); var sPixelNormalize = sAtlasSettings.FindPropertyRelative("PixelNormalize"); - var sUseUpScaling = sAtlasSettings.FindPropertyRelative("UseUpScaling"); var sTextureFineTuning = sAtlasSettings.FindPropertyRelative("TextureFineTuning"); + var sIslandFineTuners = sAtlasSettings.FindPropertyRelative("IslandFineTuners"); @@ -103,7 +100,6 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) EditorGUILayout.PropertyField(sForceSetTexture, "AtlasTexture:prop:ForceSetTexture".Glc()); EditorGUILayout.PropertyField(sPadding, "AtlasTexture:prop:Padding".Glc()); - EditorGUILayout.PropertyField(sUseUpScaling, "AtlasTexture:prop:UseUpScaling".Glc()); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(sIncludeDisabledRenderer, "AtlasTexture:prop:IncludeDisabledRenderer".Glc()); @@ -114,6 +110,7 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) if (s_ExperimentalFutureOption) { EditorGUI.indentLevel += 1; + EditorGUILayout.PropertyField(sIslandFineTuners, "AtlasTexture:prop:IslandFineTuners".Glc()); EditorGUILayout.PropertyField(sAtlasIslandRelocator, "AtlasTexture:prop:ExperimentalFuture:AtlasIslandRelocator".Glc()); EditorGUILayout.PropertyField(sWriteOriginalUV, "AtlasTexture:prop:ExperimentalFuture:WriteOriginalUV".Glc()); EditorGUILayout.PropertyField(sPixelNormalize, "AtlasTexture:prop:ExperimentalFuture:PixelNormalize".Glc()); diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 7071d562..ff2010f1 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -242,6 +242,12 @@ msgstr "Settings that specify the color space of specific texture." msgid "TextureFineTuning:prop:Linear" msgstr "Linear" +msgid "AtlasTexture:prop:IslandFineTuners" +msgstr "IslandFineTuners" + +msgid "IIslandFineTuner:prop:SizeOffset" +msgstr "SizeOffset" + msgid "IIslandFineTuner:prop:SizeOffset" msgstr "SizeOffset" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 70266613..79c327a7 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -242,12 +242,25 @@ msgstr "指定したテクスチャの色空間を指定する設定" msgid "TextureFineTuning:prop:Linear" msgstr "リニア" +msgid "AtlasTexture:prop:IslandFineTuners" +msgstr "アイランド詳細調整" + +msgid "IIslandFineTuner:prop:IslandSelector" +msgstr "アイランドセレクター" + msgid "IIslandFineTuner:prop:SizeOffset" msgstr "サイズオフセット" +msgid "IIslandFineTuner:prop:OffsetValue" +msgstr "オフセットの値" + msgid "IIslandFineTuner:prop:SizePriority" msgstr "大きさの優先度" +msgid "IIslandFineTuner:prop:PriorityValue" +msgstr "優先度の値" + + # CommonDecal msgid "CommonDecal:label:RenderersSettings" From e6d98b0c7a75afdef680078dee3e37678121751b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 21:13:42 +0900 Subject: [PATCH 041/208] fix: forget EN localize some --- Editor/Localize/en_US.po | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index ff2010f1..77e46546 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -245,15 +245,24 @@ msgstr "Linear" msgid "AtlasTexture:prop:IslandFineTuners" msgstr "IslandFineTuners" +msgid "IIslandFineTuner:prop:IslandSelector" +msgstr "IslandSelector" + msgid "IIslandFineTuner:prop:SizeOffset" msgstr "SizeOffset" msgid "IIslandFineTuner:prop:SizeOffset" msgstr "SizeOffset" +msgid "IIslandFineTuner:prop:OffsetValue" +msgstr "OffsetValue" + msgid "IIslandFineTuner:prop:SizePriority" msgstr "SizePriority" +msgid "IIslandFineTuner:prop:PriorityValue" +msgstr "PriorityValue" + # CommonDecal msgid "CommonDecal:label:RenderersSettings" From d90ececb4fc1163a6377f04e9a8a13923a22c18c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 21:40:28 +0900 Subject: [PATCH 042/208] feat: create IslandSelectNOT and Renderer --- .../IslandSelect/IslandRendererSelector.cs | 26 +++++++++++++++++++ .../IslandRendererSelector.cs.meta | 11 ++++++++ Runtime/IslandSelect/IslandSelectNOT.cs | 21 +++++++++++++++ Runtime/IslandSelect/IslandSelectNOT.cs.meta | 11 ++++++++ 4 files changed, 69 insertions(+) create mode 100644 Runtime/IslandSelect/IslandRendererSelector.cs create mode 100644 Runtime/IslandSelect/IslandRendererSelector.cs.meta create mode 100644 Runtime/IslandSelect/IslandSelectNOT.cs create mode 100644 Runtime/IslandSelect/IslandSelectNOT.cs.meta diff --git a/Runtime/IslandSelect/IslandRendererSelector.cs b/Runtime/IslandSelect/IslandRendererSelector.cs new file mode 100644 index 00000000..3adfc66b --- /dev/null +++ b/Runtime/IslandSelect/IslandRendererSelector.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using net.rs64.TexTransCore.Island; +using UnityEngine; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public class IslandRendererSelector : AbstractIslandSelector + { + internal const string ComponentName = "TTT IslandRendererSelector"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + public List RendererList; + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + var bitArray = new BitArray(islands.Length); + var hash = RendererList.ToHashSet(); + + for (int i = 0; i < islands.Length; i += 1) { bitArray[i] = hash.Contains(islandDescription[i].Renderer); } + + return bitArray; + } + } +} diff --git a/Runtime/IslandSelect/IslandRendererSelector.cs.meta b/Runtime/IslandSelect/IslandRendererSelector.cs.meta new file mode 100644 index 00000000..75451cc4 --- /dev/null +++ b/Runtime/IslandSelect/IslandRendererSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b586b00f85c0ef42893719be144f9f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectNOT.cs b/Runtime/IslandSelect/IslandSelectNOT.cs new file mode 100644 index 00000000..943fef5d --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectNOT.cs @@ -0,0 +1,21 @@ +using System.Collections; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using UnityEngine; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public class IslandSelectNOT : AbstractIslandSelector + { + internal const string ComponentName = "TTT IslandSelectNOT"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + + public AbstractIslandSelector IslandSelector; + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); + } + } +} diff --git a/Runtime/IslandSelect/IslandSelectNOT.cs.meta b/Runtime/IslandSelect/IslandSelectNOT.cs.meta new file mode 100644 index 00000000..d425eeed --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectNOT.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c255e6473250bdb4b972415765471bdb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} + userData: + assetBundleName: + assetBundleVariant: From ec076fcb35d35c972e08108fb7f6636b4b54f8ea Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 21:41:50 +0900 Subject: [PATCH 043/208] chore: improve RelocateLoop --- Runtime/TextureAtlas/AtlasTexture.cs | 168 ++++++++++-------- .../IslandRelocator/NFDHPlasFC.cs | 82 +++++---- 2 files changed, 148 insertions(+), 102 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 90752d63..44c983c2 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -215,83 +215,13 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) IAtlasIslandRelocator relocator = atlasSetting.AtlasIslandRelocator != null ? UnityEngine.Object.Instantiate(atlasSetting.AtlasIslandRelocator) : new NFDHPlasFC(); - relocator.Padding = atlasSetting.IslandPadding; - var rectTangleMove = relocator.RectTangleMove; - var relocatedRect = rectArray.ToArray(); Profiler.BeginSample("Relocation"); - if (!relocator.Relocation(relocatedRect)) { relocatedRect = RelocateLoop(rectArray, sizePriority, relocator, relocatedRect); } + var relocatedRect = RelocateLoop(rectArray, sizePriority, relocator, atlasSetting.IslandPadding); Profiler.EndSample(); - IslandRect[] RelocateLoop(IslandRect[] rectArray, float[] sizePriority, IAtlasIslandRelocator relocator, IslandRect[] relocatedRect) - { - if (sizePriority.Any(f => !Mathf.Approximately(1, f))) - { - var priorityMinSize = rectArray.ToArray(); - for (var i = 0; priorityMinSize.Length > i; i += 1) { priorityMinSize[i].Size *= sizePriority[i]; } - - for (var priLerp = 1f; 0 < priLerp; priLerp -= 0.05f) - { - for (var i = 0; rectArray.Length > i; i += 1) - { - if (relocatedRect[i].Is90Rotation) - { - var size = Vector3.Lerp(priorityMinSize[i].Size, rectArray[i].Size, priLerp); - (size.x, size.y) = (size.y, size.x); - relocatedRect[i].Size = size; - } - else - { - relocatedRect[i].Size = Vector3.Lerp(priorityMinSize[i].Size, rectArray[i].Size, priLerp); - } - } - // Debug.Log("priLerp-" + priLerp); - if (relocator.Relocation(relocatedRect)) { return relocatedRect; } - } - relocatedRect = priorityMinSize; - } - - ScaleApplyDown(Mathf.Sqrt(0.5f / IslandRectUtility.CalculateAllAreaSum(relocatedRect))); - var preRelocated = relocatedRect.ToArray(); - - var safetyCount = 0; - while (relocator.Relocation(relocatedRect) && safetyCount < 2048)//失敗するかセーフティにかかるまで、失敗したら前回の物を使用する - { - safetyCount += 1; - // Debug.Log("safetyCount-" + safetyCount); - - for (int i = 0; relocatedRect.Length > i; i++) { preRelocated[i] = relocatedRect[i]; } - ScaleApplyUp(1.01f); - } - - void ScaleApplyDown(float scaleDownStep) - { - for (int i = 0; relocatedRect.Length > i; i++) - { - relocatedRect[i].Size *= scaleDownStep; - } - } - void ScaleApplyUp(float scaleUpStep) - { - for (int i = 0; relocatedRect.Length > i; i++) - { - var size = relocatedRect[i].Size *= scaleUpStep; - - - var maxLength = 0.99f - atlasSetting.IslandPadding - atlasSetting.IslandPadding; - if (size.x > maxLength || size.y > maxLength)//一つ大きいのがあるとすべて使いきれなくなってしまうために、これは必要。 - { - var max = Mathf.Max(size.x, size.y); - size *= maxLength / max; - relocatedRect[i].Size = size; - } - } - } - - return preRelocated; - } - + var rectTangleMove = relocator.RectTangleMove; if (atlasSetting.PixelNormalize) { @@ -590,6 +520,100 @@ Dictionary ZipDictAndOffset(IEnumerable !Mathf.Approximately(1, f))) + { + Profiler.BeginSample("Priority"); + var priorityMinSize = rectArray.ToArray(); + for (var i = 0; priorityMinSize.Length > i; i += 1) { priorityMinSize[i].Size *= sizePriority[i]; } + + for (var lerpValue = 1f; 0 < lerpValue; lerpValue -= 0.05f) + { + LerpPriority(relocatedRect, priorityMinSize, rectArray, lerpValue); + if (relocator.Relocation(relocatedRect)) { Profiler.EndSample(); return relocatedRect; } + } + refRect = priorityMinSize; + Debug.Log("Priority Failed"); + Profiler.EndSample(); + } + + + + Profiler.BeginSample("Expand"); + + var refRectSize = IslandRectUtility.CalculateAllAreaSum(refRect); + + var lastRelocated = relocatedRect.ToArray(); + + for (var size = 0.5f; size >= 0; size -= 0.01f) + { + for (var i = 0; rectArray.Length > i; i += 1) { relocatedRect[i] = refRect[i]; } + ScaleApplyDown(relocatedRect, Mathf.Sqrt(size / refRectSize)); + + if (ExpandLoop(relocator, relocatedRect, lastRelocated)) { Debug.Log("Expand to " + size); break; } + } + + Profiler.EndSample(); + + return lastRelocated; + + + static void LerpPriority(IslandRect[] write, IslandRect[] min, IslandRect[] max, float lerpValue) + { + for (var i = 0; max.Length > i; i += 1) + { + var size = Vector3.Lerp(min[i].Size, max[i].Size, lerpValue); + if (write[i].Is90Rotation) { (size.x, size.y) = (size.y, size.x); } + write[i].Size = size; + } + } + + bool ExpandLoop(IAtlasIslandRelocator relocator, IslandRect[] relocatedRect, IslandRect[] lastRelocated) + { + var safetyCount = 0; + if (!relocator.Relocation(relocatedRect)) { return false; } + while (relocator.Relocation(relocatedRect) && safetyCount < 2048)//失敗するかセーフティにかかるまで、続けて失敗したら前回の物を使用する方針 + { + safetyCount += 1; + for (int i = 0; relocatedRect.Length > i; i++) { lastRelocated[i] = relocatedRect[i]; } + ScaleApplyUp(relocatedRect, 1.01f); + } + return true; + } + + static void ScaleApplyDown(IslandRect[] rect, float scaleDownStep) + { + for (int i = 0; rect.Length > i; i++) + { + rect[i].Size *= scaleDownStep; + } + } + void ScaleApplyUp(IslandRect[] rect, float scaleUpStep) + { + for (int i = 0; rect.Length > i; i++) + { + var size = rect[i].Size *= scaleUpStep; + + + var maxLength = 0.99f - padding - padding; + if (size.x > maxLength || size.y > maxLength)//一つ大きいのがあるとすべて使いきれなくなってしまうために、これは必要。 + { + var max = Mathf.Max(size.x, size.y); + size *= maxLength / max; + rect[i].Size = size; + } + } + } + + + } + private static Dictionary GetTextureSizeOffset(IEnumerable targetMaterialSelectors, AtlasSetting atlasSetting) { float atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; diff --git a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs index 3c830a71..1a4844b5 100644 --- a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs +++ b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs @@ -3,7 +3,9 @@ using System.Linq; using net.rs64.TexTransCore.Island; using net.rs64.TexTransCore.TransTextureCore.Utils; +using Unity.Collections; using UnityEngine; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator { @@ -16,30 +18,44 @@ internal class NFDHPlasFC : IAtlasIslandRelocator public bool Relocation(IslandRect[] atlasIslands) { - return IslandPoolNextFitDecreasingHeightPlusFloorCeiling(atlasIslands, _padding); + Profiler.BeginSample("NFDHPlasFC"); + var res = IslandPoolNextFitDecreasingHeightPlusFloorCeiling(atlasIslands, _padding); + Profiler.EndSample(); + return res; } public static bool IslandPoolNextFitDecreasingHeightPlusFloorCeiling(IslandRect[] islands, float islandPadding = 0.01f) { if (islands.Length == 0) { return false; } - var idList = Enumerable.Range(0, islands.Length).ToList(); - foreach (var id in idList) { if (islands[id].Size.y > islands[id].Size.x) { var island = islands[id]; island.Rotate90(); islands[id] = island; } } - idList.Sort((lId, rId) => Mathf.RoundToInt((islands[rId].Size.y - islands[lId].Size.y) * 1073741824)); - - var sortedIslandArray = idList.Select(i => islands[i]).ToArray(); - ValidateDeceasing(sortedIslandArray); + Profiler.BeginSample("KeyArrayInit"); + var idKey = Enumerable.Range(0, islands.Length).ToArray(); + foreach (var id in idKey) { if (islands[id].Size.y > islands[id].Size.x) { var island = islands[id]; island.Rotate90(); islands[id] = island; } } + Array.Sort(idKey, (lId, rId) => Mathf.RoundToInt((islands[rId].Size.y - islands[lId].Size.y) * 1073741824)); + Profiler.EndSample(); - var res = TryNFDHPlasFC(sortedIslandArray, islandPadding); - if (res) { ApplyDictionary(); } - return res; - void ApplyDictionary() + using (var sortedIA = new NativeArray(islands.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory)) { - for (var i = 0; sortedIslandArray.Length > i; i += 1) { islands[idList[i]] = sortedIslandArray[i]; } + var sortedIASpan = sortedIA.AsSpan(); + + Profiler.BeginSample("CopyAndValidate"); + for (var i = 0; idKey.Length > i; i += 1) { sortedIASpan[i] = islands[idKey[i]]; } + ValidateDeceasing(sortedIA); + Profiler.EndSample(); + + Profiler.BeginSample("TryNFDHPlasFC"); + if (TryNFDHPlasFC(sortedIASpan, islandPadding)) + { + Profiler.EndSample(); + for (var i = 0; sortedIASpan.Length > i; i += 1) { islands[idKey[i]] = sortedIASpan[i]; } + return true; + } + Profiler.EndSample(); + return false; } } - internal static bool ValidateDeceasing(IslandRect[] rectArray) + internal static bool ValidateDeceasing(Span rectArray) { var validateHeight = rectArray[0].Size.y; foreach (var rect in rectArray) @@ -47,37 +63,44 @@ internal static bool ValidateDeceasing(IslandRect[] rectArray) if (validateHeight >= rect.Size.y) { validateHeight = rect.Size.y; } else { - TTTRuntimeLog.Warning("NFDHPlusFC : The islands are not sorted correctly according to height. It is possible that undesirable reordering is being done."); - return true; + if (!Mathf.Approximately(validateHeight, rect.Size.y)) + { + TTTRuntimeLog.Warning("NFDHPlusFC : The islands are not sorted correctly according to height. It is possible that undesirable reordering is being done."); + return true; + } } } return false; } - static bool TryNFDHPlasFC(IslandRect[] sortedIslands, float islandPadding = 0.01f) + static bool TryNFDHPlasFC(Span sortedIslands, float islandPadding = 0.01f) { - var uvWidthBox = new List>(32); + var uvWidthBox = new LinkedList>(); for (var i = 0; sortedIslands.Length > i; i += 1) { - if (TrySetUVBoxList(i)) { continue; } + Profiler.BeginSample("TrySet"); + if (TrySetUVBoxList(sortedIslands, i)) { Profiler.EndSample(); continue; } + Profiler.EndSample(); - var Floor = uvWidthBox.Any() ? uvWidthBox.Last().Ceil + islandPadding : islandPadding; + Profiler.BeginSample("NewBox"); + var Floor = uvWidthBox.Any() ? uvWidthBox.Last.Value.Ceil + islandPadding : islandPadding; var Ceil = sortedIslands[i].Size.y + Floor; var newWithBox = new UVWidthBox(Ceil, Floor, islandPadding); var pivot = newWithBox.TrySetBox(sortedIslands[i]); - if (pivot is null) { return false; } + if (pivot is null) { Profiler.EndSample(); return false; } sortedIslands[i].Pivot = pivot.Value; - uvWidthBox.Add(newWithBox); + uvWidthBox.AddLast(newWithBox); + Profiler.EndSample(); } - var lastHeight = uvWidthBox.Last().Ceil + islandPadding; + var lastHeight = uvWidthBox.Last.Value.Ceil + islandPadding; return lastHeight <= 1; - bool TrySetUVBoxList(int index) + bool TrySetUVBoxList(Span sortedIslands, int index) { foreach (var withBox in uvWidthBox) { @@ -101,8 +124,8 @@ bool TrySetUVBoxList(int index) public readonly float Ceil; public readonly float Floor; public float Height => Ceil - Floor; - public readonly List Upper; - public readonly List Lower; + public readonly LinkedList Upper; + public readonly LinkedList Lower; public UVWidthBox(float height, float floor, float padding, float width = 1) { @@ -121,28 +144,27 @@ public UVWidthBox(float height, float floor, float padding, float width = 1) if (Height + 0.01f < islandRect.Size.y) return null; - var widthMin = Lower.Any() ? Lower.Last().GetMaxPos().x : 0; + var widthMin = Lower.Any() ? Lower.Last.Value.GetMaxPos().x : 0; var widthMax = GetCeilWithEmpty(Mathf.Clamp(Floor + islandRect.Size.y + Padding, Floor, Ceil)); var widthSize = widthMax - widthMin; if (widthSize > Padding + islandRect.Size.x + Padding) { islandRect.Pivot = new Vector2(widthMin + Padding, Floor); - Lower.Add(islandRect); + Lower.AddLast(islandRect); return islandRect.Pivot; } widthMin = GetFloorWithEmpty(Mathf.Clamp(Ceil - islandRect.Size.y - Padding, Floor, Ceil)); - widthMax = Upper.Any() ? Upper.Last().Pivot.x : Width; + widthMax = Upper.Any() ? Upper.Last.Value.Pivot.x : Width; widthSize = widthMax - widthMin; if (widthSize > Padding + islandRect.Size.x + Padding) { islandRect.Pivot = new Vector2(widthMax - islandRect.Size.x - Padding, Ceil - islandRect.Size.y); - Upper.Add(islandRect); + Upper.AddLast(islandRect); return islandRect.Pivot; } - return null; } From a14020fe69bbc0517c613b6ac6170e8049cb1347 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 21:52:34 +0900 Subject: [PATCH 044/208] chore: remove debug log --- Runtime/TextureAtlas/AtlasTexture.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 44c983c2..9157ac69 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -539,7 +539,6 @@ private static IslandRect[] RelocateLoop(IslandRect[] rectArray, float[] sizePri if (relocator.Relocation(relocatedRect)) { Profiler.EndSample(); return relocatedRect; } } refRect = priorityMinSize; - Debug.Log("Priority Failed"); Profiler.EndSample(); } @@ -556,7 +555,7 @@ private static IslandRect[] RelocateLoop(IslandRect[] rectArray, float[] sizePri for (var i = 0; rectArray.Length > i; i += 1) { relocatedRect[i] = refRect[i]; } ScaleApplyDown(relocatedRect, Mathf.Sqrt(size / refRectSize)); - if (ExpandLoop(relocator, relocatedRect, lastRelocated)) { Debug.Log("Expand to " + size); break; } + if (ExpandLoop(relocator, relocatedRect, lastRelocated)) { break; } } Profiler.EndSample(); From 97661a6c2d7dfd094993e711617b7994c5c6ac85 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:05:03 +0900 Subject: [PATCH 045/208] chore: rename IslandSelectNOT --- .../IslandSelect/{IslandSelectNOT.cs => IslandSelectorNOT.cs} | 4 ++-- .../{IslandSelectNOT.cs.meta => IslandSelectorNOT.cs.meta} | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename Runtime/IslandSelect/{IslandSelectNOT.cs => IslandSelectorNOT.cs} (83%) rename Runtime/IslandSelect/{IslandSelectNOT.cs.meta => IslandSelectorNOT.cs.meta} (100%) diff --git a/Runtime/IslandSelect/IslandSelectNOT.cs b/Runtime/IslandSelect/IslandSelectorNOT.cs similarity index 83% rename from Runtime/IslandSelect/IslandSelectNOT.cs rename to Runtime/IslandSelect/IslandSelectorNOT.cs index 943fef5d..93671af0 100644 --- a/Runtime/IslandSelect/IslandSelectNOT.cs +++ b/Runtime/IslandSelect/IslandSelectorNOT.cs @@ -7,9 +7,9 @@ namespace net.rs64.TexTransTool.IslandSelector { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class IslandSelectNOT : AbstractIslandSelector + public class IslandSelectorNOT : AbstractIslandSelector { - internal const string ComponentName = "TTT IslandSelectNOT"; + internal const string ComponentName = "TTT IslandSelectorNOT"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public AbstractIslandSelector IslandSelector; diff --git a/Runtime/IslandSelect/IslandSelectNOT.cs.meta b/Runtime/IslandSelect/IslandSelectorNOT.cs.meta similarity index 100% rename from Runtime/IslandSelect/IslandSelectNOT.cs.meta rename to Runtime/IslandSelect/IslandSelectorNOT.cs.meta From 776dfc12a1c921bcee31f858317c3efde16d31cb Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:57:06 +0900 Subject: [PATCH 046/208] chore: Add more lower height clamp on powers of two --- Runtime/TextureAtlas/AtlasTexture.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 9157ac69..4e7e00f8 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -638,6 +638,8 @@ private static int GetHeightSize(int atlasTextureSize, float height) switch (height) { default: return atlasTextureSize; + case < (1 / 32f): return atlasTextureSize / 32; + case < (1 / 16f): return atlasTextureSize / 16; case < (1 / 8f): return atlasTextureSize / 8; case < (1 / 4f): return atlasTextureSize / 4; case < (1 / 2f): return atlasTextureSize / 2; From c79db4d34aef0afea4e365c8201a8ff55b36b544 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:57:34 +0900 Subject: [PATCH 047/208] chore: update AtlasTexture Editor --- .../TextureAtlas/AtlasTextureEditor.cs | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index f9ff7491..326c41c0 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -43,7 +43,6 @@ public override void OnInspectorGUI() var sAtlasSetting = thisSObject.FindProperty("AtlasSetting"); var sTargetRoot = thisSObject.FindProperty("TargetRoot"); var sMatSelectors = thisSObject.FindProperty("SelectMatList"); - var sMaterialToIslandFineTuningModeSelect = thisSObject.FindProperty("MaterialToIslandFineTuningModeSelect"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(sTargetRoot, "AtlasTexture:prop:TargetRoot".Glc()); @@ -53,7 +52,7 @@ public override void OnInspectorGUI() { if (GUILayout.Button("AtlasTexture:button:RefreshMaterials".GetLocalize()) || _displayMaterial == null) { RefreshMaterials(thisTarget.TargetRoot, thisTarget.AtlasSetting.IncludeDisabledRenderer); } - MaterialSelectEditor(sMatSelectors, sMaterialToIslandFineTuningModeSelect, _displayMaterial); + MaterialSelectEditor(sMatSelectors, _displayMaterial); } EditorGUI.indentLevel += 1; @@ -87,10 +86,20 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) var sPixelNormalize = sAtlasSettings.FindPropertyRelative("PixelNormalize"); var sTextureFineTuning = sAtlasSettings.FindPropertyRelative("TextureFineTuning"); var sIslandFineTuners = sAtlasSettings.FindPropertyRelative("IslandFineTuners"); + var sForceSizePriority = sAtlasSettings.FindPropertyRelative("ForceSizePriority"); EditorGUILayout.PropertyField(sAtlasTextureSize, "AtlasTexture:prop:AtlasTextureSize".Glc()); + EditorGUILayout.PropertyField(sPadding, "AtlasTexture:prop:Padding".Glc()); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(sIncludeDisabledRenderer, "AtlasTexture:prop:IncludeDisabledRenderer".Glc()); + if (EditorGUI.EndChangeCheck()) { RefreshMaterials(sIncludeDisabledRenderer.serializedObject.FindProperty("TargetRoot").objectReferenceValue as GameObject, sIncludeDisabledRenderer.boolValue); } + EditorGUILayout.PropertyField(sForceSizePriority, "AtlasTexture:prop:ForceSizePriority".Glc()); + + + EditorGUILayout.PropertyField(sMergeMaterials, "AtlasTexture:prop:MaterialMarge".Glc()); if (sMergeMaterials.boolValue) { @@ -99,12 +108,6 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) } EditorGUILayout.PropertyField(sForceSetTexture, "AtlasTexture:prop:ForceSetTexture".Glc()); - EditorGUILayout.PropertyField(sPadding, "AtlasTexture:prop:Padding".Glc()); - - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(sIncludeDisabledRenderer, "AtlasTexture:prop:IncludeDisabledRenderer".Glc()); - if (EditorGUI.EndChangeCheck()) { RefreshMaterials(sIncludeDisabledRenderer.serializedObject.FindProperty("TargetRoot").objectReferenceValue as GameObject, sIncludeDisabledRenderer.boolValue); } - s_ExperimentalFutureOption = EditorGUILayout.Foldout(s_ExperimentalFutureOption, "Common:ExperimentalFuture".Glc()); if (s_ExperimentalFutureOption) @@ -136,7 +139,7 @@ void RefreshMaterials(GameObject targetRoot, bool includeDisabledRenderer) _displayMaterial = RendererUtility.GetMaterials(renderers).Distinct().ToList(); } - public static void MaterialSelectEditor(SerializedProperty targetMaterial, SerializedProperty fineTunerMode, List tempMaterial) + public static void MaterialSelectEditor(SerializedProperty targetMaterial, List tempMaterial) { EditorGUI.indentLevel += 1; var hadeRect = EditorGUILayout.GetControlRect(); @@ -146,7 +149,7 @@ public static void MaterialSelectEditor(SerializedProperty targetMaterial, Seria hadeRect.width = (hadeWidth * 0.5f) - 64f; hadeRect.x = 64f; - EditorGUI.PropertyField(hadeRect, fineTunerMode, GUIContent.none); + EditorGUI.LabelField(hadeRect, "AtlasTexture:label:SizePriority".Glc()); hadeRect.width = hadeWidth * 0.5f; hadeRect.x = hadeRect.width; From 6f5ebe277221de5ec82f7b0bd05846656f2c3baf Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:57:52 +0900 Subject: [PATCH 048/208] remove: SizeOffsetToIslandDrawer --- .../IslandFineTuner/SizeOffsetDrawe.cs | 29 ------------------- .../IslandFineTuner/SizeOffsetDrawe.cs.meta | 11 ------- 2 files changed, 40 deletions(-) delete mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs delete mode 100644 Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs deleted file mode 100644 index 47f89ad4..00000000 --- a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs +++ /dev/null @@ -1,29 +0,0 @@ -using UnityEngine; -using UnityEditor; -using net.rs64.TexTransTool.TextureAtlas.IslandFineTuner; - -namespace net.rs64.TexTransTool.TextureAtlas.Editor -{ - [CustomPropertyDrawer(typeof(SizeOffset))] - internal class SizeOffsetToIslandDrawer : PropertyDrawer - { - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) - { - position.height = 18f; - if (IIslandFineTunerDrawer.DrawTunerSelector(position, property)) { return; } - position.y += 18; - - var sOffsetValue = property.FindPropertyRelative("OffsetValue"); - EditorGUI.PropertyField(position, sOffsetValue, "IIslandFineTuner:prop:OffsetValue".Glc()); - position.y += 18; - - var sIslandSelector = property.FindPropertyRelative("IslandSelector"); - EditorGUI.PropertyField(position, sIslandSelector, "IIslandFineTuner:prop:IslandSelector".Glc()); - } - - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) - { - return base.GetPropertyHeight(property, label) * 3; - } - } -} diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta b/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta deleted file mode 100644 index b929d2df..00000000 --- a/Editor/Inspector/TextureAtlas/IslandFineTuner/SizeOffsetDrawe.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8e3bfdfd89a350a49874ab0cc1368e96 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 0151bf3e547bbdb7abd3e93af40f900ebf356204 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:58:09 +0900 Subject: [PATCH 049/208] chore: add NewGameObjectAndAddTTTComponent --- Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index cf618cf9..2c356ec4 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -47,7 +47,9 @@ static void C() where TTB : MonoBehaviour [M(BP + RayCastIslandSelector.MenuPath)] static void RCIS() => C(); [M(BP + IslandSelectOR.MenuPath)] static void ISOR() => C(); [M(BP + IslandSelectorAND.MenuPath)] static void ISAND() => C(); - + [M(BP + IslandSelectorAND.MenuPath)] static void ISNOT() => C(); + [M(BP + IslandSelectorAND.MenuPath)] static void IRS() => C(); + } } From d4db7162733e0f95bb8a36b23ea78639f0f08236 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:58:39 +0900 Subject: [PATCH 050/208] chore: remove popup SizeOffset --- .../TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs index bf4d7963..0b9bf0f6 100644 --- a/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs +++ b/Editor/Inspector/TextureAtlas/IslandFineTuner/IIslandFineTunerDrawer.cs @@ -18,7 +18,6 @@ internal class IIslandFineTunerDrawer : PropertyDrawer public static void Init() { var dict = new Dictionary>(){ - {typeof(SizeOffset),()=>new SizeOffset()}, {typeof(SizePriority),()=>new SizePriority()}, }; From e2087dd55963d673cdc40948d7f6710a8c558217 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:58:56 +0900 Subject: [PATCH 051/208] remove: SizeOffset --- .../IslandFineTuner/SizeOffset.cs | 28 ------------------- .../IslandFineTuner/SizeOffset.cs.meta | 11 -------- 2 files changed, 39 deletions(-) delete mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs delete mode 100644 Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs deleted file mode 100644 index ceaa1663..00000000 --- a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using net.rs64.TexTransCore.Island; -using net.rs64.TexTransTool.IslandSelector; -using UnityEngine; -using UnityEngine.Experimental.Rendering; - -namespace net.rs64.TexTransTool.TextureAtlas.IslandFineTuner -{ - [Serializable] - internal class SizeOffset : IIslandFineTuner - { - [Range(0, 1)] public float OffsetValue = 1f; - public AbstractIslandSelector IslandSelector; - - - public void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) - { - var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); - - for (var i = 0; setSize.Length > i; i += 1) - { - if (!targetBit[i]) { continue; } - setSize[i] = OffsetValue; - } - } - } -} diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta b/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta deleted file mode 100644 index d4381837..00000000 --- a/Runtime/TextureAtlas/IslandFineTuner/SizeOffset.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 691a91d21c4eea246a83c86d17ffa18b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 4176255146b07a9187f9b82f379f891c43fdebdd Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:59:26 +0900 Subject: [PATCH 052/208] chore: remove set size --- Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs | 2 +- Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs index a8657f5d..48ae7970 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs @@ -11,6 +11,6 @@ internal interface IIslandFineTuner { //islands と islandDescriptions は書き込みしないように、 //sizePriority と islandRect を操作して調整していく感じ - void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); + void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs index adede9a9..43bcb92c 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs @@ -13,7 +13,7 @@ internal class SizePriority : IIslandFineTuner [Range(0, 1)] public float PriorityValue = 1f; public AbstractIslandSelector IslandSelector; - public void IslandFineTuning(float[] sizePriority, float[] setSize, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + public void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) { var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); From b3353d7068eb1d578d3ede0febee22625433c44b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 22:59:42 +0900 Subject: [PATCH 053/208] chore: add SizePriority localize --- Editor/Localize/en_US.po | 10 +++++----- Editor/Localize/ja_JP.po | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 77e46546..72360a93 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -55,6 +55,9 @@ msgstr "RefreshMaterials" msgid "AtlasTexture:label:Target" msgstr "Target" +msgid "AtlasTexture:label:SizePriority" +msgstr "(SizePriority)" + msgid "AtlasTexture:label:Material" msgstr "Material" @@ -133,11 +136,8 @@ msgstr "IncludeDisabledRenderer" msgid "AtlasTexture:prop:IncludeDisabledRenderer:tooltip" msgstr "Option to Include disabled renderers in the atlas." -msgid "AtlasTexture:prop:UseUpScaling" -msgstr "UseUpScaling" - -msgid "AtlasTexture:prop:UseUpScaling:tooltip" -msgstr "Allow upscaling in island sorting." +msgid "AtlasTexture:prop:ForceSizePriority" +msgstr "ForceSizePriority" msgid "AtlasTexture:prop:TextureFineTuning" msgstr "TextureFineTuning" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 79c327a7..23b4140d 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -55,6 +55,9 @@ msgstr "リフレッシュマテリアル" msgid "AtlasTexture:label:Target" msgstr "対象" +msgid "AtlasTexture:label:SizePriority" +msgstr "(大きさの優先度)" + msgid "AtlasTexture:label:Material" msgstr "マテリアル" @@ -133,11 +136,8 @@ msgstr "適用時に非アクティブなレンダラーを含める" msgid "AtlasTexture:prop:IncludeDisabledRenderer:tooltip" msgstr "アトラス化を適用するときに、非アクティブなGameObjectに付いているレンダラーを含めるオプション" -msgid "AtlasTexture:prop:UseUpScaling" -msgstr "アップスケーリングを許可" - -msgid "AtlasTexture:prop:UseUpScaling:tooltip" -msgstr "アイランドを再配置する時、アイランドのサイズを拡大するのを許可する設定" +msgid "AtlasTexture:prop:ForceSizePriority" +msgstr "大きさの優先度を強制" msgid "AtlasTexture:prop:TextureFineTuning" msgstr "テクスチャー詳細設定" From ffceac9f08f9f6b971b2f6827a24ac033e13a6be Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 8 Apr 2024 23:00:00 +0900 Subject: [PATCH 054/208] feat: add ForceSizePriority --- Runtime/TextureAtlas/AtlasSetting.cs | 12 +++-- Runtime/TextureAtlas/AtlasTexture.cs | 70 ++++++++++++++-------------- 2 files changed, 44 insertions(+), 38 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasSetting.cs b/Runtime/TextureAtlas/AtlasSetting.cs index b67aec6b..31128710 100644 --- a/Runtime/TextureAtlas/AtlasSetting.cs +++ b/Runtime/TextureAtlas/AtlasSetting.cs @@ -12,18 +12,24 @@ namespace net.rs64.TexTransTool.TextureAtlas [Serializable] public class AtlasSetting { + [PowerOfTwo] public int AtlasTextureSize = 2048; + [Range(0f, 0.05f)] public float IslandPadding = 0.01f; + + [FormerlySerializedAs("IncludeDisableRenderer")] public bool IncludeDisabledRenderer = false; + public bool ForceSizePriority; [SerializeReference] internal List IslandFineTuners; + public bool MergeMaterials; public Material MergeReferenceMaterial; public PropertyBakeSetting PropertyBakeSetting = PropertyBakeSetting.NotBake; public bool ForceSetTexture; - [PowerOfTwo] public int AtlasTextureSize = 2048; - [Range(0f, 0.05f)] public float IslandPadding = 0.01f; + public AtlasIslandRelocatorObject AtlasIslandRelocator; public bool WriteOriginalUV = false; - [FormerlySerializedAs("IncludeDisableRenderer")] public bool IncludeDisabledRenderer = false; public bool PixelNormalize = false; + [SerializeReference] public List TextureFineTuning = new List { Resize.Default }; + public float GetTexScalePadding => IslandPadding * AtlasTextureSize; #region V3SaveData diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 4e7e00f8..cf6b1c5f 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -27,8 +27,6 @@ public sealed class AtlasTexture : TexTransRuntimeBehavior public GameObject TargetRoot; public List Renderers => FilteredRenderers(TargetRoot, AtlasSetting.IncludeDisabledRenderer); public List SelectMatList = new List(); - public MaterialToIslandFineTuningMode MaterialToIslandFineTuningModeSelect; - public AtlasSetting AtlasSetting = new AtlasSetting(); internal override bool IsPossibleApply => TargetRoot != null; @@ -37,13 +35,6 @@ public sealed class AtlasTexture : TexTransRuntimeBehavior internal override TexTransPhase PhaseDefine => TexTransPhase.Optimizing; - - public enum MaterialToIslandFineTuningMode - { - SizeOffset = 0, - SizePriority = 1, - } - #region V0SaveData [Obsolete("V0SaveData", true)] public List MigrationV0ObsoleteChannelsRef; [Obsolete("V0SaveData", true)] public List SelectReferenceMat;//OrderedHashSetにしたかったけどシリアライズの都合で @@ -169,7 +160,6 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } var sizePriority = new float[islandArray.Length]; for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = 1f; } - var scaleArray = new float[islandArray.Length]; for (var i = 0; scaleArray.Length > i; i += 1) { scaleArray[i] = 1f; } var islandDescription = new IslandSelector.IslandDescription[islandArray.Length]; for (var i = 0; islandDescription.Length > i; i += 1) { @@ -198,19 +188,11 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) count += 1; } materialFineTuningValue /= count; - - switch (MaterialToIslandFineTuningModeSelect) - { - case MaterialToIslandFineTuningMode.SizeOffset: { scaleArray[i] = materialFineTuningValue; break; } - case MaterialToIslandFineTuningMode.SizePriority: { sizePriority[i] = materialFineTuningValue; break; } - default: break; - } - + sizePriority[i] = materialFineTuningValue; } - foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, scaleArray, islandArray, islandDescription, domain); } + foreach (var islandFineTuner in atlasSetting.IslandFineTuners) { islandFineTuner.IslandFineTuning(sizePriority, islandArray, islandDescription, domain); } for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = Mathf.Clamp01(sizePriority[i]); } - for (var i = 0; scaleArray.Length > i; i += 1) { rectArray[i].Size *= scaleArray[i]; } Profiler.EndSample(); @@ -218,11 +200,13 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) relocator.Padding = atlasSetting.IslandPadding; Profiler.BeginSample("Relocation"); - var relocatedRect = RelocateLoop(rectArray, sizePriority, relocator, atlasSetting.IslandPadding); + var relocatedRect = RelocateLoop(rectArray, sizePriority, relocator, atlasSetting.ForceSizePriority, atlasSetting.IslandPadding); Profiler.EndSample(); var rectTangleMove = relocator.RectTangleMove; + if (relocator is UnityEngine.Object unityObject) { DestroyImmediate(unityObject); } + if (atlasSetting.PixelNormalize) { Profiler.BeginSample("AtlasReferenceData:PixelNormalize"); @@ -246,7 +230,8 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) //上側を削れるかを見る Profiler.BeginSample("IslandHight Calculate"); var height = IslandRectUtility.CalculateIslandsMaxHeight(relocatedRect); - var atlasTextureHeightSize = Mathf.Max(GetHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動しそうだからクランプ + var atlasTextureHeightSize = Mathf.Max(GetNormalizedMinHeightSize(atlasSetting.AtlasTextureSize, height), 4);//4以下はちょっと怪しい挙動しそうだからクランプ + Debug.Assert(Mathf.IsPowerOfTwo(atlasTextureHeightSize)); Profiler.EndSample(); // var areaSum = IslandRectUtility.CalculateAllAreaSum(islandRectPool.Values); @@ -520,26 +505,33 @@ Dictionary ZipDictAndOffset(IEnumerable !Mathf.Approximately(1, f))) + if (forceSizePriority) { - Profiler.BeginSample("Priority"); - var priorityMinSize = rectArray.ToArray(); - for (var i = 0; priorityMinSize.Length > i; i += 1) { priorityMinSize[i].Size *= sizePriority[i]; } + refRect = GetPriorityMinSizeRectArray(rectArray, sizePriority); + if (relocator.Relocation(refRect)) { return refRect; } + } + else + { + if (relocator.Relocation(relocatedRect)) { return relocatedRect; } - for (var lerpValue = 1f; 0 < lerpValue; lerpValue -= 0.05f) + if (sizePriority.Any(f => !Mathf.Approximately(1, f))) { - LerpPriority(relocatedRect, priorityMinSize, rectArray, lerpValue); - if (relocator.Relocation(relocatedRect)) { Profiler.EndSample(); return relocatedRect; } + Profiler.BeginSample("Priority"); + var priorityMinSize = GetPriorityMinSizeRectArray(rectArray, sizePriority); + + for (var lerpValue = 1f; 0 < lerpValue; lerpValue -= 0.05f) + { + LerpPriority(relocatedRect, priorityMinSize, rectArray, lerpValue); + if (relocator.Relocation(relocatedRect)) { Profiler.EndSample(); return relocatedRect; } + } + refRect = priorityMinSize; + Profiler.EndSample(); } - refRect = priorityMinSize; - Profiler.EndSample(); } @@ -613,6 +605,14 @@ void ScaleApplyUp(IslandRect[] rect, float scaleUpStep) } + private static IslandRect[] GetPriorityMinSizeRectArray(IslandRect[] rectArray, float[] sizePriority) + { + var priorityMinSize = rectArray.ToArray(); + for (var i = 0; priorityMinSize.Length > i; i += 1) { priorityMinSize[i].Size *= sizePriority[i]; } + + return priorityMinSize; + } + private static Dictionary GetTextureSizeOffset(IEnumerable targetMaterialSelectors, AtlasSetting atlasSetting) { float atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; @@ -633,7 +633,7 @@ private static Dictionary GetTextureSizeOffset(IEnumerable Date: Mon, 8 Apr 2024 23:16:59 +0900 Subject: [PATCH 055/208] chore: create migration V3 to V4 --- .../TextureAtlas/AtlasTextureEditor.cs | 4 ++ Editor/Migration/Migrator.cs | 66 +++++++++++++++++++ Editor/Migration/V3.meta | 8 +++ Editor/Migration/V3/AtlasTextureV3.cs | 23 +++++++ Editor/Migration/V3/AtlasTextureV3.cs.meta | 11 ++++ Runtime/TexTransBehavior.cs | 3 +- 6 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 Editor/Migration/V3.meta create mode 100644 Editor/Migration/V3/AtlasTextureV3.cs create mode 100644 Editor/Migration/V3/AtlasTextureV3.cs.meta diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 326c41c0..27d05bc2 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -36,6 +36,10 @@ public override void OnInspectorGUI() { net.rs64.TexTransTool.Migration.V2.AtlasTextureV2.MigrationAtlasTextureV2ToV3(thisTarget); } + if (TTTag.SaveDataVersion == 3 && GUILayout.Button("Migrate DSV3 To DSV4")) + { + net.rs64.TexTransTool.Migration.V2.AtlasTextureV3.MigrationAtlasTextureV3ToV4(thisTarget); + } return; } #pragma warning restore CS0612 diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index 8eb24ead..a344c449 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -34,6 +34,23 @@ internal class SaveDataVersionJson #pragma warning disable CS0612 + public static bool MigrationITexTransToolTagV3ToV4(ITexTransToolTag texTransToolTag) + { + switch (texTransToolTag) + { + case AtlasTexture atlasTexture: + { + AtlasTextureV3.MigrationAtlasTextureV3ToV4(atlasTexture); + return true; + } + + default: + { + MigrationUtility.SetSaveDataVersion(texTransToolTag, 4); + return true; + } + } + } public static bool MigrationITexTransToolTagV2ToV3(ITexTransToolTag texTransToolTag) { switch (texTransToolTag) @@ -211,6 +228,11 @@ private static void MigrateEverything() MigrateEverythingV2ToV3(true); break; } + case 3: + { + MigrateEverythingV3ToV4(true); + break; + } } } PostMigration(); @@ -331,6 +353,41 @@ private static void MigrateEverythingV2ToV3(bool continuesMigrate = false) if (!continuesMigrate) PostMigration(); } } + [MenuItem(TTTConfig.DEBUG_MENU_PATH + "/Migration/Migrate Everything v0.6.x to v0.7.x")] + private static void MigrateEverythingV3ToV4() { MigrateEverythingV3ToV4(false); } + private static void MigrateEverythingV3ToV4(bool continuesMigrate = false) + { + try + { + if (!continuesMigrate) PreMigration(); + var prefabs = GetPrefabs(); + var scenePaths = AssetDatabase.FindAssets("t:scene").Select(AssetDatabase.GUIDToAssetPath).ToList(); + float totalCount = prefabs.Count + scenePaths.Count; + + MigratePrefabsV3ToV4(prefabs, (name, i) => EditorUtility.DisplayProgressBar( + "Migrating Everything (pass 1)", + $"{name} (Prefabs) ({i} / {totalCount})", + i / totalCount)); + + MigrateAllScenesV3ToV4(scenePaths, (name, i) => EditorUtility.DisplayProgressBar( + "Migrating Everything (pass 1)", + $"{name} (Scenes) ({prefabs.Count + i} / {totalCount})", + (prefabs.Count + i) / totalCount)); + + MigrationUtility.WriteVersion(3); + + } + catch + { + EditorUtility.DisplayDialog("Error!", "Error in migration process!", "OK"); + throw; + } + finally + { + EditorUtility.ClearProgressBar(); + if (!continuesMigrate) PostMigration(); + } + } private static string[] _openingScenePaths; private static void PreMigration() @@ -474,6 +531,15 @@ public PrefabInfo(GameObject prefab) Prefab = prefab; } } + private static void MigratePrefabsV3ToV4(List prefabAssets, Action progressCallback) + { + MigratePrefabsImpl(prefabAssets, progressCallback, MigrationITexTransToolTagV3ToV4); + } + private static void MigrateAllScenesV3ToV4(List scenePaths, Action progressCallback) + { + MigrateAllScenesImpl(scenePaths, progressCallback, MigrationITexTransToolTagV3ToV4); + } + private static void MigratePrefabsV2ToV3(List prefabAssets, Action progressCallback) { MigratePrefabsImpl(prefabAssets, progressCallback, MigrationITexTransToolTagV2ToV3); diff --git a/Editor/Migration/V3.meta b/Editor/Migration/V3.meta new file mode 100644 index 00000000..8fb99308 --- /dev/null +++ b/Editor/Migration/V3.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9e1fe797d7e08da48ad1b526ca404d7d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Migration/V3/AtlasTextureV3.cs b/Editor/Migration/V3/AtlasTextureV3.cs new file mode 100644 index 00000000..b2847909 --- /dev/null +++ b/Editor/Migration/V3/AtlasTextureV3.cs @@ -0,0 +1,23 @@ +using System; +using System.Linq; +using net.rs64.TexTransTool.TextureAtlas; +using UnityEditor; +using UnityEngine; + +namespace net.rs64.TexTransTool.Migration.V2 +{ + [Obsolete] + internal static class AtlasTextureV3 + { + public static void MigrationAtlasTextureV3ToV4(AtlasTexture atlasTexture) + { + if (atlasTexture == null) { Debug.LogWarning("マイグレーションターゲットが存在しません。"); return; } + if (atlasTexture is ITexTransToolTag TTTag && TTTag.SaveDataVersion > 4) { Debug.Log(atlasTexture.name + " AtlasTexture : マイグレーション不可能なバージョンです。"); return; } + + atlasTexture.AtlasSetting.ForceSizePriority = true; + + EditorUtility.SetDirty(atlasTexture); + MigrationUtility.SetSaveDataVersion(atlasTexture, 4); + } + } +} diff --git a/Editor/Migration/V3/AtlasTextureV3.cs.meta b/Editor/Migration/V3/AtlasTextureV3.cs.meta new file mode 100644 index 00000000..cbcce285 --- /dev/null +++ b/Editor/Migration/V3/AtlasTextureV3.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 935cc32d153bfd04e98e23a9db9b590b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TexTransBehavior.cs b/Runtime/TexTransBehavior.cs index c7d20a7b..b6f99599 100644 --- a/Runtime/TexTransBehavior.cs +++ b/Runtime/TexTransBehavior.cs @@ -31,7 +31,8 @@ public abstract class TexTransBehavior : MonoBehaviour, ITexTransToolTag //v0.4.x == 1 //v0.5.x == 2 //v0.6.x == 3 - internal const int TTTDataVersion = 3; + //v0.7.x == 4 + internal const int TTTDataVersion = 4; [HideInInspector, SerializeField] int _saveDataVersion = TTTDataVersion; int ITexTransToolTag.SaveDataVersion => _saveDataVersion; From 7af7f55c84a34c005aee8484270ba59c1853dcb1 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 20:22:21 +0900 Subject: [PATCH 056/208] fix: write version is 4 --- Editor/Migration/Migrator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index a344c449..123acc70 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -374,7 +374,7 @@ private static void MigrateEverythingV3ToV4(bool continuesMigrate = false) $"{name} (Scenes) ({prefabs.Count + i} / {totalCount})", (prefabs.Count + i) / totalCount)); - MigrationUtility.WriteVersion(3); + MigrationUtility.WriteVersion(4); } catch From aedab2912c8cecdba70c2d724b1b363cf4ede2af Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 20:22:49 +0900 Subject: [PATCH 057/208] chore: add TexTransInitialize --- Editor/Localize/Localize.cs | 2 + Editor/TTTConfig.cs | 2 + Editor/TTTImageAssets.cs | 4 +- Editor/TTTInitializer.cs | 37 +++++++++++++++ ...Utility.cs.meta => TTTInitializer.cs.meta} | 0 Editor/Utils/LateInitializeUtility.cs | 47 ------------------- .../Improted/PSD/PSDImportedRasterImage.cs | 6 +++ .../ShaderAssets/SpecialLayerShaders.cs | 2 + .../AtlasShaderSupportUtils.cs | 18 +++++++ TexTransCore/BlendTexture/TextureBlend.cs | 2 +- TexTransCore/Memoize.cs | 1 + TexTransCore/MipMap/MipMapUtility.cs | 5 ++ TexTransCore/TexTransCoreRuntime.cs | 37 +++++++++++---- TexTransCore/TransTextureCore/TransTexture.cs | 1 + .../TransTextureCore/Utils/TextureUtility.cs | 1 + 15 files changed, 106 insertions(+), 59 deletions(-) create mode 100644 Editor/TTTInitializer.cs rename Editor/{Utils/LateInitializeUtility.cs.meta => TTTInitializer.cs.meta} (100%) delete mode 100644 Editor/Utils/LateInitializeUtility.cs diff --git a/Editor/Localize/Localize.cs b/Editor/Localize/Localize.cs index bab0f4eb..b121a4c6 100644 --- a/Editor/Localize/Localize.cs +++ b/Editor/Localize/Localize.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.IO; +using net.rs64.TexTransCore; using UnityEditor; using UnityEngine; using static net.rs64.TexTransTool.TTTConfig; @@ -10,6 +11,7 @@ internal static class Localize { const string JP_GUID = "42db3dbd5755c844984648836a49629f"; const string EN_GUID = "b6008be0d5fa3d242ba93f9a930df3c3"; + [TexTransInitialize] internal static void LocalizeInitializer() { Language = (LanguageEnum)EditorPrefs.GetInt(TTTConfig.LANGUAGE_PREFKEY); diff --git a/Editor/TTTConfig.cs b/Editor/TTTConfig.cs index 2e52e131..05660c8b 100644 --- a/Editor/TTTConfig.cs +++ b/Editor/TTTConfig.cs @@ -1,4 +1,5 @@ using System; +using net.rs64.TexTransCore; using UnityEditor; namespace net.rs64.TexTransTool @@ -10,6 +11,7 @@ internal static class TTTConfig public const string DEBUG_MENU_PATH = TTT_MENU_PATH + "/Debug"; + [TexTransInitialize] internal static void SettingInitializer() { IsObjectReplaceInvoke = EditorPrefs.GetBool(OBJECT_REPLACE_INVOKE_PREFKEY); diff --git a/Editor/TTTImageAssets.cs b/Editor/TTTImageAssets.cs index fa5a2e8f..880c04f1 100644 --- a/Editor/TTTImageAssets.cs +++ b/Editor/TTTImageAssets.cs @@ -1,4 +1,5 @@ using System; +using net.rs64.TexTransCore; using UnityEditor; using UnityEngine; @@ -10,6 +11,7 @@ internal static class TTTImageAssets internal static Texture2D Logo; + [TexTransInitialize] internal static void Init() { Icon = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath("846ba4dba0267cf4187be80bb6577627")); @@ -17,4 +19,4 @@ internal static void Init() } } -} \ No newline at end of file +} diff --git a/Editor/TTTInitializer.cs b/Editor/TTTInitializer.cs new file mode 100644 index 00000000..f7fe8b25 --- /dev/null +++ b/Editor/TTTInitializer.cs @@ -0,0 +1,37 @@ +using System.Linq; +using net.rs64.TexTransCore; +using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.MipMap; +using net.rs64.TexTransTool.MultiLayerImage; +using net.rs64.TexTransTool.TextureAtlas; +using UnityEditor; +using UnityEngine; +namespace net.rs64.TexTransTool.Utils +{ + internal static class TTTInitializeCaller + { + [UnityEditor.InitializeOnLoadMethod] + static void EditorInitDerayCall() + { + UnityEditor.EditorApplication.delayCall += EditorInitDerayCaller; + } + static void EditorInitDerayCaller() + { + Initialize(); + UnityEditor.EditorApplication.delayCall -= EditorInitDerayCaller; + } + [UnityEditor.InitializeOnEnterPlayMode] + public static void Initialize() + { + UnityEditor.EditorApplication.update += TexTransCoreRuntime.Update.Invoke; + TexTransCoreRuntime.LoadAsset = (guid, type) => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), type); + TexTransCoreRuntime.LoadAssetsAtType = (type) => + { + return UnityEditor.AssetDatabase.GetAllAssetPaths() + .Where(i => AssetDatabase.GetMainAssetTypeAtPath(i) == type) + .Select(i => AssetDatabase.LoadAssetAtPath(i, type)); + }; + TexTransInitialize.CallInitialize(); + } + } +} diff --git a/Editor/Utils/LateInitializeUtility.cs.meta b/Editor/TTTInitializer.cs.meta similarity index 100% rename from Editor/Utils/LateInitializeUtility.cs.meta rename to Editor/TTTInitializer.cs.meta diff --git a/Editor/Utils/LateInitializeUtility.cs b/Editor/Utils/LateInitializeUtility.cs deleted file mode 100644 index 344b2649..00000000 --- a/Editor/Utils/LateInitializeUtility.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Linq; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.MipMap; -using net.rs64.TexTransTool.MultiLayerImage; -using UnityEditor; -using UnityEngine; -namespace net.rs64.TexTransTool.Utils -{ - internal static class LateInitializeUtility - { - [UnityEditor.InitializeOnLoadMethod] - static void EditorInitDerayCall() - { - UnityEditor.EditorApplication.delayCall += EditorInitDerayCaller; - } - static void EditorInitDerayCaller() - { - Initializer(); - UnityEditor.EditorApplication.delayCall -= EditorInitDerayCaller; - } - [UnityEditor.InitializeOnEnterPlayMode] - public static void Initializer() - { - TTTConfig.SettingInitializer(); - Localize.LocalizeInitializer(); - PSDImportedRasterImage.MargeColorAndOffsetShader = Shader.Find(PSDImportedRasterImage.MARGE_COLOR_AND_OFFSET_SHADER); - SpecialLayerShaders.Init(); - TTTImageAssets.Init(); - TexTransCore.TexTransCoreRuntime.Initialize(); - UnityEditor.EditorApplication.update += TexTransCore.TexTransCoreRuntime.Update.Invoke; - MipMapUtility.MipMapShader = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath("5f6d88c53276bb14eace10771023ae01")); - - // TODO : これ何とかしないといけない - var atlasShaderSupportList = UnityEditor.AssetDatabase.GetAllAssetPaths() - .Where(i => UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(i) == typeof(TextureAtlas.AtlasScriptableObject.AtlasShaderSupportScriptableObject)) - .Select(i => UnityEditor.AssetDatabase.LoadAssetAtPath(i)) - .ToList(); - - var _defaultSupport = ScriptableObject.CreateInstance(); - _defaultSupport.SupportedShaderComparer = new TextureAtlas.AtlasScriptableObject.AnythingShader(); - _defaultSupport.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new TextureAtlas.AtlasScriptableObject.Anything() } }; - atlasShaderSupportList.Add(_defaultSupport); - TextureAtlas.AtlasShaderSupportUtils.s_atlasShaderSupportList = atlasShaderSupportList; - - } - } -} diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 45688bbb..b3524f96 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using net.rs64.MultiLayerImage.Parser.PSD; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.TransTextureCore; using Unity.Burst; using Unity.Collections; @@ -138,6 +139,11 @@ async static Task[]> WeightTask(Task>[] task { return await Task.WhenAll(tasks).ConfigureAwait(false); } + [TexTransInitialize] + public void Init() + { + MargeColorAndOffsetShader = Shader.Find(MARGE_COLOR_AND_OFFSET_SHADER); + } internal const string MARGE_COLOR_AND_OFFSET_SHADER = "Hidden/MargeColorAndOffset"; internal static Shader MargeColorAndOffsetShader; internal const string SHADER_KEYWORD_SRGB = "COLOR_SPACE_SRGB"; diff --git a/Runtime/MultiLayerImage/SpecialLayer/ShaderAssets/SpecialLayerShaders.cs b/Runtime/MultiLayerImage/SpecialLayer/ShaderAssets/SpecialLayerShaders.cs index 674912e7..3871fec1 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/ShaderAssets/SpecialLayerShaders.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/ShaderAssets/SpecialLayerShaders.cs @@ -1,8 +1,10 @@ +using net.rs64.TexTransCore; using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { internal static class SpecialLayerShaders { + [TexTransInitialize] public static void Init() { HSLAdjustmentShader = Shader.Find(HSL_ADJUSTMENT_SHADER); diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index 105717d9..835ae003 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; using UnityEngine; @@ -13,6 +14,23 @@ namespace net.rs64.TexTransTool.TextureAtlas internal class AtlasShaderSupportUtils { internal static List s_atlasShaderSupportList; + internal static AtlasShaderSupportScriptableObject s_defaultSupporter; + + [TexTransInitialize] + public static void Initialize() + { + var atlasShaderSupportList = TexTransCoreRuntime.LoadAssetsAtType.Invoke(typeof(AtlasShaderSupportScriptableObject)).Cast().ToList(); + + if (s_defaultSupporter == null) + { + s_defaultSupporter = ScriptableObject.CreateInstance(); + s_defaultSupporter.SupportedShaderComparer = new AnythingShader(); + s_defaultSupporter.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything() } }; + } + + atlasShaderSupportList.Add(s_defaultSupporter); + s_atlasShaderSupportList = atlasShaderSupportList; + } public AtlasShaderSupportScriptableObject GetAtlasShaderSupporter(Material mat) { diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index ebf7c82b..5ff03b97 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -78,7 +78,7 @@ internal enum TTTBlendTypeKeyEnum//これをセーブデータとして使うべ internal static class TextureBlend { public static Dictionary BlendShaders; - + [TexTransInitialize] public static void BlendShadersInit() { BlendTexShader = Shader.Find(BLEND_TEX_SHADER); diff --git a/TexTransCore/Memoize.cs b/TexTransCore/Memoize.cs index c5f743cf..660f344b 100644 --- a/TexTransCore/Memoize.cs +++ b/TexTransCore/Memoize.cs @@ -9,6 +9,7 @@ internal static class FrameMemoEvents { internal static event Action OnClearMemo; + [TexTransInitialize] internal static void Init() { TexTransCoreRuntime.Update += () => diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 24f13504..3388dd8e 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -12,6 +12,11 @@ namespace net.rs64.TexTransCore.MipMap { internal static class MipMapUtility { + [TexTransInitialize] + public static void Init() + { + MipMapShader = TexTransCoreRuntime.LoadAsset("5f6d88c53276bb14eace10771023ae01", typeof(ComputeShader)) as ComputeShader; + } public static ComputeShader MipMapShader; const string WTex = "WTex"; const string RTex = "RTex"; diff --git a/TexTransCore/TexTransCoreRuntime.cs b/TexTransCore/TexTransCoreRuntime.cs index dcd83ef6..b6581dfb 100644 --- a/TexTransCore/TexTransCoreRuntime.cs +++ b/TexTransCore/TexTransCoreRuntime.cs @@ -1,23 +1,40 @@ using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; +using System.Linq; +using System.Reflection; using net.rs64.TexTransCore.BlendTexture; -using UnityEditor; namespace net.rs64.TexTransCore { public static class TexTransCoreRuntime { - public static void Initialize()//シェーダー等がロードさている状態を想定している。 - { - TextureBlend.BlendShadersInit(); - FrameMemoEvents.Init(); - TransTextureCore.Utils.TextureUtility.Init(); - TransTextureCore.TransTexture.Init(); - } public static Action Update = () => { NextUpdateCall?.Invoke(); NextUpdateCall = null; }; public static Action NextUpdateCall; - public static Func LoadAsset; + public static Func LoadAsset; + public static Func> LoadAssetsAtType; + + } + + [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false)] + internal sealed class TexTransInitialize : System.Attribute + { + public TexTransInitialize() + { + } + + public static void CallInitialize()//シェーダー等がロードさている状態を想定している。 + { + var initializers = AppDomain.CurrentDomain.GetAssemblies() + .SelectMany(i => i.GetTypes()) + .SelectMany(i => i.GetRuntimeMethods()) + .Where(i => i.IsStatic) + .Where(i => i.GetCustomAttribute() is not null) + .Select(i => (Action)i.CreateDelegate(typeof(Action))); + + foreach (var method in initializers) { method(); } + } + } + } diff --git a/TexTransCore/TransTextureCore/TransTexture.cs b/TexTransCore/TransTextureCore/TransTexture.cs index a850f06b..2d352bd4 100644 --- a/TexTransCore/TransTextureCore/TransTexture.cs +++ b/TexTransCore/TransTextureCore/TransTexture.cs @@ -131,6 +131,7 @@ public void Execute(int index) Destination[index] = Source[index]; } } + [TexTransInitialize] public static void Init() { s_transShader = Shader.Find(TRANS_SHADER); diff --git a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs index 7a2720f9..fe829cb6 100644 --- a/TexTransCore/TransTextureCore/Utils/TextureUtility.cs +++ b/TexTransCore/TransTextureCore/Utils/TextureUtility.cs @@ -148,6 +148,7 @@ public static RenderTexture CloneTemp(this RenderTexture renderTexture) public const string ST_APPLY_SHADER = "Hidden/TransTexture"; static Shader s_stApplyShader; + [TexTransInitialize] public static void Init() { s_stApplyShader = Shader.Find(ST_APPLY_SHADER); } static Material s_TempMat; From 1ade94d030a0bb1d865320a7cde8ecb1aef67c8b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 20:33:43 +0900 Subject: [PATCH 058/208] chore: add debug reload AtlasShaderSupporters --- Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs | 9 +++++++++ .../OtherMenuItem/ReloadAtlasShaderSupproters.cs.meta | 11 +++++++++++ 2 files changed, 20 insertions(+) create mode 100644 Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs create mode 100644 Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs.meta diff --git a/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs b/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs new file mode 100644 index 00000000..b74c45dd --- /dev/null +++ b/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs @@ -0,0 +1,9 @@ +using net.rs64.TexTransTool; +using net.rs64.TexTransTool.TextureAtlas; +using UnityEditor; + +public static class ReloadAtlasShaderSupporter +{ + [MenuItem("Tools/" + TexTransBehavior.TTTName + "/Debug/ReloadAtlasShaderSupporter")] + public static void Reload() { AtlasShaderSupportUtils.Initialize(); } +} diff --git a/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs.meta b/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs.meta new file mode 100644 index 00000000..b0d46250 --- /dev/null +++ b/Editor/OtherMenuItem/ReloadAtlasShaderSupproters.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5d94f36e047a88409230cf9d970862b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 2c179ba4887207714ff670a3ed2bfc5636e38da2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 21:16:38 +0900 Subject: [PATCH 059/208] chore: restore material post process --- Runtime/TextureAtlas/AtlasTexture.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index cf6b1c5f..2e814649 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -714,7 +714,7 @@ internal override void Apply(IDomain domain = null) var mergeMat = AtlasSetting.MergeReferenceMaterial != null ? AtlasSetting.MergeReferenceMaterial : atlasData.AtlasInMaterials.First(); Material generateMat = GenerateAtlasMat(mergeMat, atlasTexture, shaderSupport, AtlasSetting.ForceSetTexture); - domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x, _ => generateMat), rendererOnly: true); + domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x, _ => generateMat), true); } else { @@ -725,7 +725,7 @@ internal override void Apply(IDomain domain = null) var generateMat = GenerateAtlasMat(distMat, atlasTexture, shaderSupport, AtlasSetting.ForceSetTexture); materialMap.Add(distMat, generateMat); } - domain.ReplaceMaterials(materialMap); + domain.ReplaceMaterials(materialMap, true); } domain.ProgressUpdate("End", 1); @@ -774,10 +774,10 @@ private static Material GenerateAtlasMat(Material targetMat, List Date: Tue, 9 Apr 2024 21:17:42 +0900 Subject: [PATCH 060/208] chore: PSDImportedRasterImage LoadImage use tmpMat --- .../Improted/PSD/PSDImportedRasterImage.cs | 21 ++++++++++--------- .../PSD/PSDImportedRasterMaskImage.cs | 4 ++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index b3524f96..5fa16a15 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -98,13 +98,13 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) var texA = RasterImageData.A != null ? new Texture2D(texWidth, texHeight, TextureFormat.R8, false) : null; if (RasterImageData.A != null) { texA.filterMode = FilterMode.Point; } - var mat = new Material(MargeColorAndOffsetShader); - mat.SetTexture("_RTex", texR); - mat.SetTexture("_GTex", texG); - mat.SetTexture("_BTex", texB); - mat.SetTexture("_ATex", texA); - mat.SetVector("_Offset", new Vector4(Pivot.x / (float)CanvasDescription.Width, Pivot.y / (float)CanvasDescription.Height, texWidth / (float)CanvasDescription.Width, texHeight / (float)CanvasDescription.Height)); - mat.EnableKeyword(SHADER_KEYWORD_SRGB); + if (s_tempMat == null) { s_tempMat = new Material(MargeColorAndOffsetShader); } + s_tempMat.SetTexture("_RTex", texR); + s_tempMat.SetTexture("_GTex", texG); + s_tempMat.SetTexture("_BTex", texB); + s_tempMat.SetTexture("_ATex", texA); + s_tempMat.SetVector("_Offset", new Vector4(Pivot.x / (float)CanvasDescription.Width, Pivot.y / (float)CanvasDescription.Height, texWidth / (float)CanvasDescription.Width, texHeight / (float)CanvasDescription.Height)); + s_tempMat.EnableKeyword(SHADER_KEYWORD_SRGB); // timer.Stop(); Debug.Log(name + "+SetUp:" + timer.ElapsedMilliseconds + "ms"); timer.Restart(); var image = WeightTask(getImageTask).Result; @@ -117,11 +117,11 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) // timer.Stop(); Debug.Log("LoadRawDataAndApply:" + timer.ElapsedMilliseconds + "ms"); timer.Restart(); - Graphics.Blit(null, WriteTarget, mat); + Graphics.Blit(null, WriteTarget, s_tempMat); // timer.Stop(); Debug.Log("Blit:" + timer.ElapsedMilliseconds + "ms"); timer.Restart(); - UnityEngine.Object.DestroyImmediate(mat); + s_tempMat.DisableKeyword(SHADER_KEYWORD_SRGB); image[0].Dispose(); image[1].Dispose(); image[2].Dispose(); @@ -140,12 +140,13 @@ async static Task[]> WeightTask(Task>[] task return await Task.WhenAll(tasks).ConfigureAwait(false); } [TexTransInitialize] - public void Init() + public static void Init() { MargeColorAndOffsetShader = Shader.Find(MARGE_COLOR_AND_OFFSET_SHADER); } internal const string MARGE_COLOR_AND_OFFSET_SHADER = "Hidden/MargeColorAndOffset"; internal static Shader MargeColorAndOffsetShader; + internal static Material s_tempMat; internal const string SHADER_KEYWORD_SRGB = "COLOR_SPACE_SRGB"; internal struct InitializeJob : IJobParallelFor diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 35f03a75..d38b69de 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -49,7 +49,8 @@ internal override JobResult> LoadImage(byte[] importSouse, internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) { var isZeroSize = (MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0; - var mat = new Material(PSDImportedRasterImage.MargeColorAndOffsetShader); + if (PSDImportedRasterImage.s_tempMat == null) { PSDImportedRasterImage.s_tempMat = new Material(PSDImportedRasterImage.MargeColorAndOffsetShader); } + var mat = PSDImportedRasterImage.s_tempMat; var texR = new Texture2D(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight(), TextureFormat.R8, false); texR.filterMode = FilterMode.Point; @@ -71,7 +72,6 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) Graphics.Blit(null, WriteTarget, mat); } - UnityEngine.Object.DestroyImmediate(mat); UnityEngine.Object.DestroyImmediate(texR); } From f957e0cfd87a80211b16ee1d034ec6500705fe48 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 21:42:36 +0900 Subject: [PATCH 061/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 5 ++++- CHANGELOG.md | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index ad273bec..8d46e62e 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -11,6 +11,9 @@ v0.5.2 以降の実験的機能の変更記録です。 - SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) - IslandCulling からのマイグレーションが追加されました (#422) - TTT PSD Importer のプレビューの生成が大幅に高速化されました (#424) +- AtlasTexture に アイランド詳細調整 が追加されました (#431) +- IslandSelectorNOT と IslandRendererSelector が追加されました (#431) +- AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) ### Changed @@ -20,7 +23,7 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Fixed -- Library が存在しないときにも正しくインポートできるようになりました (#427) +- Library が存在しないときにも正しく TTT PSD Importer がインポートできるようになりました (#427) ### Deprecated diff --git a/CHANGELOG.md b/CHANGELOG.md index 894e3f9a..3f29edc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,13 +11,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Optimizing Phase が追加されました (#410) - GameObject から TexTransTool のほとんどのコンポーネントが追加できるようになりました (#411) +- AtlasTexture に強制的に優先度のサイズに変更する ForcePrioritySize が追加されました (#431) +- AtlasTexture 複数のマテリアルが衝突しないテクスチャを持つ場合に、同一のアイランドが割り当てられるようになりました (#431) ### Changed +- SizeOffset は廃止され、SizePriority に変更されました (#431) +- AtlasTexture のプロパティの並び順が変更されました (#431) + ### Removed +- AtlasTexture の UseUpScale は削除されました (#431) + ### Fixed +- AtlasTexture で SubMesh よりも多くのマテリアルスロットが存在するメッシュで正しくアトラス化できない問題を修正 (#431) +- AtlasTexture でサブメッシュを超えて同一の頂点を使用するメッシュを正しくアトラス化できない問題を修正 (#431) +- AtlasTexture の「適用時に非アクティブなレンダラーを含める」が有効な時、非アクティブなレンダラーのマテリアルが選択肢に表示されない問題を修正 (#431) + ### Deprecated ## [0.6.4] From d372e207b84d386dc8b726ea28e7da4c36b8fae3 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 23:22:50 +0900 Subject: [PATCH 062/208] feat: add MaterialMargeGroups --- .../TextureAtlas/AtlasTextureEditor.cs | 96 ++++++++++++++++++- Runtime/TextureAtlas/AtlasSetting.cs | 11 ++- Runtime/TextureAtlas/AtlasTexture.cs | 14 ++- 3 files changed, 116 insertions(+), 5 deletions(-) diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 27d05bc2..6badb484 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -64,7 +64,7 @@ public override void OnInspectorGUI() EditorGUI.indentLevel -= 1; - DrawAtlasSettings(sAtlasSetting); + DrawAtlasSettings(sAtlasSetting, sMatSelectors); PreviewContext.instance.DrawApplyAndRevert(thisTarget); @@ -72,7 +72,7 @@ public override void OnInspectorGUI() } - private void DrawAtlasSettings(SerializedProperty sAtlasSettings) + private void DrawAtlasSettings(SerializedProperty sAtlasSettings, SerializedProperty sMatSelectors) { EditorGUILayout.LabelField("AtlasTexture:label:AtlasSettings".Glc(), EditorStyles.boldLabel); EditorGUI.indentLevel += 1; @@ -91,6 +91,7 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) var sTextureFineTuning = sAtlasSettings.FindPropertyRelative("TextureFineTuning"); var sIslandFineTuners = sAtlasSettings.FindPropertyRelative("IslandFineTuners"); var sForceSizePriority = sAtlasSettings.FindPropertyRelative("ForceSizePriority"); + var sMaterialMargeGroups = sAtlasSettings.FindPropertyRelative("MaterialMargeGroups"); @@ -121,6 +122,7 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) EditorGUILayout.PropertyField(sAtlasIslandRelocator, "AtlasTexture:prop:ExperimentalFuture:AtlasIslandRelocator".Glc()); EditorGUILayout.PropertyField(sWriteOriginalUV, "AtlasTexture:prop:ExperimentalFuture:WriteOriginalUV".Glc()); EditorGUILayout.PropertyField(sPixelNormalize, "AtlasTexture:prop:ExperimentalFuture:PixelNormalize".Glc()); + if (sMergeMaterials.boolValue) { DrawMaterialMargeGroup(sMatSelectors, sMaterialMargeGroups); } EditorGUI.indentLevel -= 1; } @@ -131,7 +133,97 @@ private void DrawAtlasSettings(SerializedProperty sAtlasSettings) } + private static void DrawMaterialMargeGroup(SerializedProperty sMatSelectors, SerializedProperty sMaterialMargeGroups) + { + var headerRect = EditorGUILayout.GetControlRect(); + var guiContent = EditorGUI.BeginProperty(headerRect, "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups".Glc(), sMaterialMargeGroups); + + s_MaterialMargeGroupsFoldout = EditorGUI.Foldout(headerRect, s_MaterialMargeGroupsFoldout, guiContent); + if (s_MaterialMargeGroupsFoldout) + { + + var buttonWidth = headerRect.width * 0.125f; + headerRect.x += headerRect.width - buttonWidth * 2; + headerRect.width = buttonWidth; + if (GUI.Button(headerRect, "+")) + { + var newIndex = sMaterialMargeGroups.arraySize; + sMaterialMargeGroups.arraySize += 1; + + var mmg = sMaterialMargeGroups.GetArrayElementAtIndex(newIndex); + mmg.FindPropertyRelative("MargeReferenceMaterial").objectReferenceValue = null; + mmg.FindPropertyRelative("GroupMaterials").arraySize = 0; + } + headerRect.x += headerRect.width; + if (GUI.Button(headerRect, "-")) { sMaterialMargeGroups.arraySize += -1; } + } + + EditorGUI.EndProperty(); + + if (!s_MaterialMargeGroupsFoldout) { return; } + + s_targetMatHash.Clear(); + for (var i = 0; sMatSelectors.arraySize > i; i += 1) { s_targetMatHash.Add(sMatSelectors.GetArrayElementAtIndex(i).FindPropertyRelative("Material").objectReferenceValue as Material); } + + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) + { + for (var i = 0; sMaterialMargeGroups.arraySize > i; i += 1) + { + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) + { + var mmg = sMaterialMargeGroups.GetArrayElementAtIndex(i); + var mRef = mmg.FindPropertyRelative("MargeReferenceMaterial"); + var mg = mmg.FindPropertyRelative("GroupMaterials"); + var mgGUIContent = "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:GroupMaterials".Glc(); + + EditorGUILayout.PropertyField(mRef, "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:MargeReferenceMaterial".Glc()); + + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) + { + foreach (var mat in s_targetMatHash) + { + using (new EditorGUILayout.HorizontalScope()) + { + var matIndex = FindGroupMaterial(mg, mat); + var contains = matIndex != -1; + var mod = EditorGUILayout.Toggle(contains, GUILayout.Width(64f)); + + if (mod != contains) + { + if (mod) + { + var newIndex = mg.arraySize; + mg.arraySize += 1; + mg.GetArrayElementAtIndex(newIndex).objectReferenceValue = mat; + } + else + { + mg.DeleteArrayElementAtIndex(matIndex); + } + } + + EditorGUI.DrawTextureTransparent(EditorGUILayout.GetControlRect(GUILayout.Width(18f)), AssetPreview.GetAssetPreview(mat)); + + EditorGUILayout.ObjectField(mat, typeof(Material), false); + } + } + for (var mgi = 0; mg.arraySize > mgi; mgi += 1) { s_targetMatHash.Remove(mg.GetArrayElementAtIndex(mgi).objectReferenceValue as Material); } + } + EditorGUILayout.PropertyField(mg, mgGUIContent); + } + } + } + } + + private static int FindGroupMaterial(SerializedProperty mg, Material mat) + { + for (var i = 0; mg.arraySize > i; i += 1) { if (mg.GetArrayElementAtIndex(i).objectReferenceValue == mat) { return i; } } + return -1; + } + static bool s_ExperimentalFutureOption = false; + static bool s_MaterialMargeGroupsFoldout = false; + static HashSet s_targetMatHash = new(); diff --git a/Runtime/TextureAtlas/AtlasSetting.cs b/Runtime/TextureAtlas/AtlasSetting.cs index 31128710..95ac4f8e 100644 --- a/Runtime/TextureAtlas/AtlasSetting.cs +++ b/Runtime/TextureAtlas/AtlasSetting.cs @@ -24,12 +24,13 @@ public class AtlasSetting public PropertyBakeSetting PropertyBakeSetting = PropertyBakeSetting.NotBake; public bool ForceSetTexture; + public List MaterialMargeGroups; + public AtlasIslandRelocatorObject AtlasIslandRelocator; public bool WriteOriginalUV = false; public bool PixelNormalize = false; [SerializeReference] public List TextureFineTuning = new List { Resize.Default }; - public float GetTexScalePadding => IslandPadding * AtlasTextureSize; #region V3SaveData @@ -44,6 +45,14 @@ public class AtlasSetting #endregion } + + [Serializable] + public class MaterialMargeGroup + { + public Material MargeReferenceMaterial; + public List GroupMaterials; + } + public enum PropertyBakeSetting { NotBake, diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 2e814649..88918ef2 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -471,7 +471,6 @@ Dictionary ZipDictAndOffset(IEnumerable m, m => GenerateAtlasMat(m.MargeReferenceMaterial, atlasTexture, shaderSupport, AtlasSetting.ForceSetTexture)); - domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x, _ => generateMat), true); + domain.ReplaceMaterials(atlasData.AtlasInMaterials.ToDictionary(x => x, m => FindGroup(m)), true); + + Material FindGroup(Material material) + { + foreach (var matGroup in AtlasSetting.MaterialMargeGroups) + { + var index = matGroup.GroupMaterials.FindIndex(m => domain.OriginEqual(m, material)); + if (index != -1) { return matGroupGenerate[matGroup]; } + } + return generateMat; + } } else { From 906fd765ac050ccf82d1dd54f1cd31f399666fa9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 23:42:31 +0900 Subject: [PATCH 063/208] chore: MaterialMargeGroups localize --- Editor/Localize/en_US.po | 9 +++++++++ Editor/Localize/ja_JP.po | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 72360a93..a3f82279 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -130,6 +130,15 @@ msgstr "PixelNormalize" msgid "AtlasTexture:prop:ExperimentalFuture:PixelNormalize:tooltip" msgstr "Feature of pixel normalize on island move." +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups" +msgstr "MaterialMargeGroups" + +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:MargeReferenceMaterial" +msgstr "MargeReferenceMaterial" + +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:GroupMaterials" +msgstr "GroupMaterials" + msgid "AtlasTexture:prop:IncludeDisabledRenderer" msgstr "IncludeDisabledRenderer" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 23b4140d..74825b04 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -130,6 +130,15 @@ msgstr "ピクセルノーマライズ" msgid "AtlasTexture:prop:ExperimentalFuture:PixelNormalize:tooltip" msgstr "アイランドの移動をピクセル単位にノーマライズする機能" +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups" +msgstr "マテリアル統合グループ" + +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:MargeReferenceMaterial" +msgstr "結合時マテリアルの参照" + +msgid "AtlasTexture:prop:ExperimentalFuture:MaterialMargeGroups:GroupMaterials" +msgstr "グループのマテリアル" + msgid "AtlasTexture:prop:IncludeDisabledRenderer" msgstr "適用時に非アクティブなレンダラーを含める" From b5af3d8bec63b6c0d42619eb6e2f301266702722 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 9 Apr 2024 23:58:01 +0900 Subject: [PATCH 064/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 8d46e62e..bf3c2b94 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -14,6 +14,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - AtlasTexture に アイランド詳細調整 が追加されました (#431) - IslandSelectorNOT と IslandRendererSelector が追加されました (#431) - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) +- AtlasTexture に MaterialMargeGroup が追加されました (#432) ### Changed From 0cc1ae85d3cdabf6fa5bc15bc1cf6ef4f54b5f7a Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 9 Apr 2024 15:01:10 +0000 Subject: [PATCH 065/208] Update package.json v0.7.0-beta.0!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1534928c..ce8c3f3f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.6.4", + "version": "0.7.0-beta.0", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 55a40a587e03c654ed4d2cb26db192df6166aac6 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 10 Apr 2024 01:23:01 +0900 Subject: [PATCH 066/208] chore: rename license file name --- LICENSE => LICENSE.md | 0 LICENSE.meta => LICENSE.md.meta | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename LICENSE => LICENSE.md (100%) rename LICENSE.meta => LICENSE.md.meta (100%) diff --git a/LICENSE b/LICENSE.md similarity index 100% rename from LICENSE rename to LICENSE.md diff --git a/LICENSE.meta b/LICENSE.md.meta similarity index 100% rename from LICENSE.meta rename to LICENSE.md.meta From 083139f33c258b85332fe326479a08397c5f8684 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 10 Apr 2024 14:10:38 +0900 Subject: [PATCH 067/208] chore: restore TextureIslandScaling --- Runtime/TextureAtlas/AtlasTexture.cs | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 88918ef2..2fae655e 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -149,6 +149,8 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) } Profiler.EndSample(); } + + Profiler.BeginSample("IslandFineTuning"); var islandArray = atlasContext.Islands; var rectArray = new IslandRect[islandArray.Length]; @@ -159,6 +161,34 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) index += 1; } + Profiler.BeginSample("TextureIslandScaling"); + var textureIslandScale = new Dictionary(); + var textureIslandAspect = new Dictionary(); + for (var i = 0; atlasContext.MaterialGroup.Length > i; i += 1) + { + var tex = atlasContext.MaterialGroup[i].Select(m => m.mainTexture).Where(t => t != null).FirstOrDefault(); + if (tex != null) + { + var atlasTexPixelCount = atlasSetting.AtlasTextureSize * atlasSetting.AtlasTextureSize; + var texPixelCount = tex.width * tex.height; + textureIslandScale[i] = Mathf.Sqrt(texPixelCount / (float)atlasTexPixelCount); + textureIslandAspect[i] = tex.width / tex.height; + } + else + { + textureIslandScale[i] = (float)0.01f; + textureIslandAspect[i] = 1f; + } + + } + for (var i = 0; rectArray.Length > i; i += 1) + { + var subData = atlasContext.IslandSubData[i]; + rectArray[i].Size *= textureIslandScale[subData.MaterialGroupID]; + rectArray[i].Size.y *= textureIslandAspect[subData.MaterialGroupID]; + } + Profiler.EndSample(); + var sizePriority = new float[islandArray.Length]; for (var i = 0; sizePriority.Length > i; i += 1) { sizePriority[i] = 1f; } var islandDescription = new IslandSelector.IslandDescription[islandArray.Length]; for (var i = 0; islandDescription.Length > i; i += 1) From 0c871302e9d630a2a59e574cd68ed3cff739b171 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 10 Apr 2024 05:11:50 +0000 Subject: [PATCH 068/208] Update package.json v0.7.0-beta.1!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ce8c3f3f..733821e2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.0", + "version": "0.7.0-beta.1", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From d0e7744dba283b9a865535ad91470ca6f4544979 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 10 Apr 2024 15:49:26 +0900 Subject: [PATCH 069/208] fix: Apply TextureST --- Editor/Decal/RealTimePreviewManager.cs | 13 +++------- Runtime/IDomain.cs | 2 ++ .../AtlasShaderSupportUtils.cs | 2 +- Runtime/TextureAtlas/AtlasTexture.cs | 12 +++++++-- .../ShaderAsset/TextureSTApply.shader | 10 +++---- .../TransTextureCore/Utils/TextureUtility.cs | 26 +++++++++++-------- 6 files changed, 36 insertions(+), 29 deletions(-) diff --git a/Editor/Decal/RealTimePreviewManager.cs b/Editor/Decal/RealTimePreviewManager.cs index f15c38d2..bca07d1a 100644 --- a/Editor/Decal/RealTimePreviewManager.cs +++ b/Editor/Decal/RealTimePreviewManager.cs @@ -111,7 +111,7 @@ private void RegtPreviewRenderTexture(Material material, string propertyName, Bl var souseTexture = material.GetTexture(propertyName) as Texture2D; var newTarget = RenderTexture.GetTemporary(blendTexture.RenderTexture.descriptor); - CopyFilWrap(newTarget, blendTexture.RenderTexture); + newTarget.CopyFilWrap(blendTexture.RenderTexture); editableMat.SetTexture(propertyName, newTarget); @@ -194,7 +194,7 @@ public void RegtAbstractDecal(AbstractDecal abstractDecal) { continue; } } - CopyFilWrap(Rt, tex); + Rt.CopyFilWrap(tex); var blendTex = new BlendRenderTextureClass(Rt, abstractDecal.BlendTypeKey); blends.Add(blendTex); @@ -213,14 +213,7 @@ public void RegtAbstractDecal(AbstractDecal abstractDecal) ListPool.Release(TargetMats); } - internal static void CopyFilWrap(Texture t, Texture s) - { - t.filterMode = s.filterMode; - t.wrapMode = s.wrapMode; - t.wrapModeU = s.wrapModeU; - t.wrapModeV = s.wrapModeV; - t.wrapModeW = s.wrapModeW; - } + public bool IsRealTimePreview(AbstractDecal abstractDecal) => RealTimePreviews.ContainsKey(abstractDecal); public void UnRegtAbstractDecal(AbstractDecal abstractDecal) diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index 95917fee..267fa7b5 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -66,12 +66,14 @@ public static RenderTexture GetOriginTempRt(this IOriginTexture origin, Texture2 { var originSize = origin.GetOriginalTextureSize(texture2D); var tempRt = RenderTexture.GetTemporary(originSize, originSize, 0); + tempRt.CopyFilWrap(texture2D); origin.WriteOriginalTexture(texture2D, tempRt); return tempRt; } public static RenderTexture GetOriginTempRt(this IOriginTexture origin, Texture2D texture2D, int size) { var tempRt = RenderTexture.GetTemporary(size, size, 0); + tempRt.CopyFilWrap(texture2D); tempRt.Clear(); origin.WriteOriginalTexture(texture2D, tempRt); return tempRt; diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index 835ae003..d475f1eb 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -25,7 +25,7 @@ public static void Initialize() { s_defaultSupporter = ScriptableObject.CreateInstance(); s_defaultSupporter.SupportedShaderComparer = new AnythingShader(); - s_defaultSupporter.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything() } }; + s_defaultSupporter.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything(), BakePropertyNames = new() } }; } atlasShaderSupportList.Add(s_defaultSupporter); diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 2fae655e..813bafc8 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -355,7 +355,7 @@ Dictionary ZipDictAndOffset(IEnumerable i.Value.Texture2D != null) == false) { continue; } var atlasTex = kv.First(i => i.Value.Texture2D != null).Value; - if (atlasTex.TextureScale == Vector2.zero && atlasTex.TextureTranslation == Vector2.zero) + if (atlasTex.TextureScale == Vector2.one && atlasTex.TextureTranslation == Vector2.zero) { dict[kv.Key] = texManage.GetOriginTempRt(atlasTex.Texture2D); } @@ -416,9 +416,17 @@ Dictionary ZipDictAndOffset(IEnumerable Date: Wed, 10 Apr 2024 15:50:57 +0900 Subject: [PATCH 070/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f29edc2..6cb706ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - GameObject から TexTransTool のほとんどのコンポーネントが追加できるようになりました (#411) - AtlasTexture に強制的に優先度のサイズに変更する ForcePrioritySize が追加されました (#431) - AtlasTexture 複数のマテリアルが衝突しないテクスチャを持つ場合に、同一のアイランドが割り当てられるようになりました (#431) +- AtlasTexture が Scale Transition(Tiling) を使用しているマテリアルのテクスチャを逆補正する機能が追加されました (#431 #435) ### Changed From be35070eadb79c70e27a8073e12a3f0e5c4341d2 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 10 Apr 2024 06:53:37 +0000 Subject: [PATCH 071/208] Update package.json v0.7.0-beta.2!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 733821e2..c25e5418 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.1", + "version": "0.7.0-beta.2", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 4e922eb6446f2b60d4dd27887bed1eeb8b8ab63f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 11 Apr 2024 13:21:53 +0900 Subject: [PATCH 072/208] fix: AddComponentMenuItemPath --- Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index 2c356ec4..056faed8 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -47,8 +47,8 @@ static void C() where TTB : MonoBehaviour [M(BP + RayCastIslandSelector.MenuPath)] static void RCIS() => C(); [M(BP + IslandSelectOR.MenuPath)] static void ISOR() => C(); [M(BP + IslandSelectorAND.MenuPath)] static void ISAND() => C(); - [M(BP + IslandSelectorAND.MenuPath)] static void ISNOT() => C(); - [M(BP + IslandSelectorAND.MenuPath)] static void IRS() => C(); + [M(BP + IslandSelectorNOT.MenuPath)] static void ISNOT() => C(); + [M(BP + IslandRendererSelector.MenuPath)] static void IRS() => C(); } From 924d51fc0edce22af79c748f229c27571deb1afd Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 15 Apr 2024 16:41:11 +0900 Subject: [PATCH 073/208] Improve: IDomain and create NDMFDomain and more... --- Editor/Build/AvatarBuildUtils.cs | 33 ++-- Editor/Build/ManualBake.cs | 2 +- Editor/Build/NDMF/NDMFDomain.cs | 22 +++ .../NDMF/NDMFDomain.cs.meta} | 2 +- Editor/Build/NDMF/NDMFPlugin.cs | 35 ++-- Editor/Build/NDMF/TTTPass.cs | 9 +- Editor/Build/NDMF/TexTransToolContext.cs | 27 --- Editor/Build/NDMF/TexTransToolContext.cs.meta | 11 -- Editor/Domain/AssetSaver.cs | 6 +- Editor/Domain/AvatarDomain.cs | 45 +---- Editor/Domain/ProgressHandler.cs | 32 ---- Editor/Domain/ProgressHandler.cs.meta | 11 -- Editor/Domain/RenderersDomain.cs | 51 +---- Editor/Domain/TextureManager.cs | 26 +-- .../EditorProcessor/TexTransGroupProcessor.cs | 6 +- .../MultiLayerImageCanvasEditor.cs | 2 +- Editor/PreviewContext.cs | 11 +- Editor/TTTConfig.cs | 18 -- Editor/TextureStack/DeferredTextureStack.cs | 2 +- Editor/TextureStack/ImmediateTextureStack.cs | 2 +- Editor/Utils/AssetSaveHelper.cs | 178 ------------------ Editor/Utils/DebugUtils.cs | 61 ------ Editor/Utils/DebugUtils.cs.meta | 11 -- Editor/Utils/TexTransGroupValidationUtili.cs | 116 ------------ .../TexTransGroupValidationUtili.cs.meta | 11 -- Runtime/Decal/AbstractDecal.cs | 8 - Runtime/IDomain.cs | 28 ++- Runtime/TextureAtlas/AtlasTexture.cs | 13 +- 28 files changed, 129 insertions(+), 650 deletions(-) create mode 100644 Editor/Build/NDMF/NDMFDomain.cs rename Editor/{Utils/AssetSaveHelper.cs.meta => Build/NDMF/NDMFDomain.cs.meta} (83%) delete mode 100644 Editor/Build/NDMF/TexTransToolContext.cs delete mode 100644 Editor/Build/NDMF/TexTransToolContext.cs.meta delete mode 100644 Editor/Domain/ProgressHandler.cs delete mode 100644 Editor/Domain/ProgressHandler.cs.meta delete mode 100644 Editor/Utils/AssetSaveHelper.cs delete mode 100644 Editor/Utils/DebugUtils.cs delete mode 100644 Editor/Utils/DebugUtils.cs.meta delete mode 100644 Editor/Utils/TexTransGroupValidationUtili.cs delete mode 100644 Editor/Utils/TexTransGroupValidationUtili.cs.meta diff --git a/Editor/Build/AvatarBuildUtils.cs b/Editor/Build/AvatarBuildUtils.cs index 46fd17d3..c3ace107 100644 --- a/Editor/Build/AvatarBuildUtils.cs +++ b/Editor/Build/AvatarBuildUtils.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using net.rs64.TexTransTool.ReferenceResolver; +using UnityEditor; using UnityEngine; using Debug = UnityEngine.Debug; @@ -11,17 +12,17 @@ namespace net.rs64.TexTransTool.Build internal static class AvatarBuildUtils { - public static bool ProcessAvatar(GameObject avatarGameObject, UnityEngine.Object OverrideAssetContainer = null, bool UseTemp = false, bool DisplayProgressBar = false) + public static bool ProcessAvatar(GameObject avatarGameObject, UnityEngine.Object OverrideAssetContainer = null, bool DisplayProgressBar = false) { try { - if (OverrideAssetContainer == null && UseTemp) { AssetSaveHelper.IsTemporary = true; } var timer = Stopwatch.StartNew(); var resolverContext = new ResolverContext(avatarGameObject); resolverContext.ResolvingFor(avatarGameObject.GetComponentsInChildren()); - var session = new TexTransBuildSession(new AvatarDomain(avatarGameObject, false, new AssetSaver(OverrideAssetContainer), DisplayProgressBar)); + var session = new TexTransBuildSession(new AvatarDomain(avatarGameObject, false, new AssetSaver(OverrideAssetContainer))); + session.DisplayEditorProgressBar = DisplayProgressBar; session.FindAtPhaseTTT(); @@ -60,51 +61,57 @@ public class TexTransBuildSession { AvatarDomain _avatarDomain; Dictionary> _phaseAtList; + public AvatarDomain AvatarDomain => _avatarDomain; public Dictionary> PhaseAtList => _phaseAtList; - public TexTransBuildSession(AvatarDomain avatarDomain, Dictionary> phaseAtList) - { - _avatarDomain = avatarDomain; - _phaseAtList = phaseAtList; - } + public bool DisplayEditorProgressBar { get; set; } = false; + + public TexTransBuildSession(AvatarDomain avatarDomain) { _avatarDomain = avatarDomain; } + public void FindAtPhaseTTT() { + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar("FindAtPhaseTTT", "", 0.0f); _phaseAtList = FindAtPhase(_avatarDomain.AvatarRoot); + if (DisplayEditorProgressBar) EditorUtility.ClearProgressBar(); } public void ApplyFor(TexTransPhase texTransPhase) { - _avatarDomain.ProgressStateEnter(texTransPhase.ToString()); + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar(texTransPhase.ToString(), "", 0f); var count = 0; var timer = new System.Diagnostics.Stopwatch(); foreach (var tf in _phaseAtList[texTransPhase]) { + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar(texTransPhase.ToString(), $"{tf.name} - Apply", (float)count / _phaseAtList[texTransPhase].Count); + timer.Restart(); TTTLog.ReportingObject(tf, () => { tf.Apply(_avatarDomain); }); timer.Stop(); count += 1; Debug.Log($"{texTransPhase} : {tf.GetType().Name}:{tf.name} for Apply : {timer.ElapsedMilliseconds}ms"); - _avatarDomain.ProgressUpdate($"{tf.name} - Apply", (float)count / _phaseAtList[texTransPhase].Count); } - _avatarDomain.ProgressStateExit(); + if (DisplayEditorProgressBar) EditorUtility.ClearProgressBar(); } public void MidwayMergeStack() { - _avatarDomain.ProgressStateEnter("MidwayMergeStack"); + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar("MidwayMergeStack", "", 0.0f); _avatarDomain.MergeStack(); - _avatarDomain.ProgressStateExit(); + if (DisplayEditorProgressBar) EditorUtility.ClearProgressBar(); } public void TTTSessionEnd() { + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar("TTTSessionEnd", "EditFinisher", 0.0f); _avatarDomain.EditFinish(); + if (DisplayEditorProgressBar) EditorUtility.DisplayProgressBar("TTTSessionEnd", "Page TexTransToolComponents", 0.5f); DestroyITexTransToolTags(_avatarDomain.AvatarRoot); + if (DisplayEditorProgressBar) EditorUtility.ClearProgressBar(); } } diff --git a/Editor/Build/ManualBake.cs b/Editor/Build/ManualBake.cs index a2b150ca..e7e2a1a9 100644 --- a/Editor/Build/ManualBake.cs +++ b/Editor/Build/ManualBake.cs @@ -24,7 +24,7 @@ public static void ManualBakeAvatar(GameObject targetAvatar) var duplicate = UnityEngine.Object.Instantiate(targetAvatar); duplicate.transform.position = new Vector3(duplicate.transform.position.x, duplicate.transform.position.y, duplicate.transform.position.z + 2); - AvatarBuildUtils.ProcessAvatar(duplicate, null, false, true); + AvatarBuildUtils.ProcessAvatar(duplicate, null, true); } } } diff --git a/Editor/Build/NDMF/NDMFDomain.cs b/Editor/Build/NDMF/NDMFDomain.cs new file mode 100644 index 00000000..e3822ff4 --- /dev/null +++ b/Editor/Build/NDMF/NDMFDomain.cs @@ -0,0 +1,22 @@ +using nadena.dev.ndmf; +using System; +using Object = UnityEngine.Object; + + +namespace net.rs64.TexTransTool.Build.NDMF +{ + internal class NDMFDomain : AvatarDomain + { + public NDMFDomain(BuildContext b) : base(b.AvatarRootObject, false, new AssetSaver(b.AssetContainer)) { } + + public override void RegisterReplace(Object oldObject, Object nowObject) + { + if (_replaceMap.TryGetValue(nowObject, out var dictOld)) { if (dictOld == oldObject) { return; } } + + base.RegisterReplace(oldObject, nowObject); + ObjectRegistry.RegisterReplacedObject(oldObject, nowObject); + } + public override bool OriginEqual(Object l, Object r) { return ObjectRegistry.GetReference(l) == ObjectRegistry.GetReference(r); } + + } +} diff --git a/Editor/Utils/AssetSaveHelper.cs.meta b/Editor/Build/NDMF/NDMFDomain.cs.meta similarity index 83% rename from Editor/Utils/AssetSaveHelper.cs.meta rename to Editor/Build/NDMF/NDMFDomain.cs.meta index d9ee8820..de1d9b54 100644 --- a/Editor/Utils/AssetSaveHelper.cs.meta +++ b/Editor/Build/NDMF/NDMFDomain.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 24d0bdeed398d1e4faa7c0d43fb3a341 +guid: 04c872a9e4cb0b24b99982087347c28e MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Build/NDMF/NDMFPlugin.cs b/Editor/Build/NDMF/NDMFPlugin.cs index 1f39a889..392adf8d 100644 --- a/Editor/Build/NDMF/NDMFPlugin.cs +++ b/Editor/Build/NDMF/NDMFPlugin.cs @@ -17,30 +17,33 @@ internal class NDMFPlugin : Plugin #endif protected override void Configure() { - var seq = InPhase(BuildPhase.Resolving); + InPhase(BuildPhase.Resolving) - seq.Run(PreviewCancelerPass.Instance); - seq.Run(ResolvingPass.Instance); + .Run(PreviewCancelerPass.Instance).Then + .Run(ResolvingPass.Instance); - seq = InPhase(BuildPhase.Transforming); + InPhase(BuildPhase.Transforming) + .BeforePlugin("io.github.azukimochi.light-limit-changer") - seq.BeforePlugin("io.github.azukimochi.light-limit-changer"); - seq.WithRequiredExtension(typeof(TexTransToolContext), s => - { - seq.Run(FindAtPhasePass.Instance).Then - .Run(BeforeUVModificationPass.Instance).Then + .Run(FindAtPhasePass.Instance).Then + .Run(BeforeUVModificationPass.Instance).Then - .Run(MidwayMergeStackPass.Instance).Then + .Run(MidwayMergeStackPass.Instance).Then - .Run(UVModificationPass.Instance).Then - .Run(AfterUVModificationPass.Instance).Then - .Run(UnDefinedPass.Instance).Then + .Run(UVModificationPass.Instance).Then + .Run(AfterUVModificationPass.Instance).Then + .Run(UnDefinedPass.Instance).Then - .Run(BeforeOptimizingMergeStackPass.Instance).Then + .Run(BeforeOptimizingMergeStackPass.Instance); + + + InPhase(BuildPhase.Optimizing) + .BeforePlugin("com.anatawa12.avatar-optimizer") + + .Run(OptimizingPass.Instance).Then + .Run(TTTSessionEndPass.Instance); - .Run(OptimizingPass.Instance); - }); } } diff --git a/Editor/Build/NDMF/TTTPass.cs b/Editor/Build/NDMF/TTTPass.cs index e36c0b94..038fd44a 100644 --- a/Editor/Build/NDMF/TTTPass.cs +++ b/Editor/Build/NDMF/TTTPass.cs @@ -9,7 +9,7 @@ namespace net.rs64.TexTransTool.Build.NDMF { protected TexTransBuildSession TTTContext(BuildContext context) { - return context.Extension().TTTBuildContext; + return context.GetState(b => new TexTransBuildSession(new NDMFDomain(b))); } } internal class PreviewCancelerPass : Pass @@ -86,4 +86,11 @@ protected override void Execute(BuildContext context) TTTContext(context).ApplyFor(TexTransPhase.Optimizing); } } + internal class TTTSessionEndPass : TTTPass + { + protected override void Execute(BuildContext context) + { + TTTContext(context).TTTSessionEnd(); + } + } } diff --git a/Editor/Build/NDMF/TexTransToolContext.cs b/Editor/Build/NDMF/TexTransToolContext.cs deleted file mode 100644 index fdbca616..00000000 --- a/Editor/Build/NDMF/TexTransToolContext.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using nadena.dev.ndmf; -using static net.rs64.TexTransTool.Build.AvatarBuildUtils; - -namespace net.rs64.TexTransTool.Build.NDMF -{ - internal class TexTransToolContext : IExtensionContext - { - internal TexTransBuildSession TTTBuildContext { get; private set; } - public void OnActivate(BuildContext context) - { - if (context != null) - { - TTTBuildContext = new TexTransBuildSession(new AvatarDomain(context.AvatarRootObject, false, new AssetSaver(context.AssetContainer))); - } - } - - public void OnDeactivate(BuildContext context) - { - if (TTTBuildContext != null) - { - try { TTTBuildContext.TTTSessionEnd(); } catch (Exception e) { TTTLog.Exception(e); } - TTTBuildContext = null; - } - } - } -} diff --git a/Editor/Build/NDMF/TexTransToolContext.cs.meta b/Editor/Build/NDMF/TexTransToolContext.cs.meta deleted file mode 100644 index fcafebcd..00000000 --- a/Editor/Build/NDMF/TexTransToolContext.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0799fe8ba1e543a4e9327c7c5fb8bc92 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Domain/AssetSaver.cs b/Editor/Domain/AssetSaver.cs index 73b7e650..03d80dfb 100644 --- a/Editor/Domain/AssetSaver.cs +++ b/Editor/Domain/AssetSaver.cs @@ -1,3 +1,4 @@ +using System.IO; using JetBrains.Annotations; using UnityEditor; using UnityEngine; @@ -8,13 +9,14 @@ namespace net.rs64.TexTransTool internal class AssetSaver : IAssetSaver { [NotNull] public AvatarDomainAsset Asset; + public const string SaveDirectory = "Assets/TexTransToolGenerates"; public AssetSaver(Object container = null) { if (container == null) { Asset = ScriptableObject.CreateInstance(); - AssetDatabase.CreateAsset(Asset, AssetSaveHelper.GenerateAssetPath("AvatarDomainAsset", ".asset", AssetSaveHelper.SaveType.AvatarDomainAssets)); + AssetDatabase.CreateAsset(Asset, AssetDatabase.GenerateUniqueAssetPath(Path.Combine(SaveDirectory, "AvatarDomainAsset.asset"))); } else { @@ -30,4 +32,4 @@ public void TransferAsset(UnityEngine.Object unityObject) Asset.AddSubObject(unityObject); } } -} \ No newline at end of file +} diff --git a/Editor/Domain/AvatarDomain.cs b/Editor/Domain/AvatarDomain.cs index 23f7d275..860a4f26 100644 --- a/Editor/Domain/AvatarDomain.cs +++ b/Editor/Domain/AvatarDomain.cs @@ -18,55 +18,22 @@ namespace net.rs64.TexTransTool /// internal class AvatarDomain : RenderersDomain { - static readonly HashSet s_ignoreTypes = new HashSet { typeof(Transform), typeof(SkinnedMeshRenderer), typeof(MeshRenderer) }; - - public AvatarDomain(GameObject avatarRoot, bool previewing, bool saveAsset = false, bool progressDisplay = false) - : this(avatarRoot, previewing, saveAsset ? new AssetSaver() : null, progressDisplay) { } - public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver assetSaver, bool progressDisplay = false) - : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, assetSaver, progressDisplay) + public AvatarDomain(GameObject avatarRoot, bool previewing, bool saveAsset = false) + : this(avatarRoot, previewing, saveAsset ? new AssetSaver() : null) { } + public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver assetSaver) + : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, assetSaver) { _avatarRoot = avatarRoot; - _previewing = previewing; - _isObjectReplaceInvoke = TTTConfig.IsObjectReplaceInvoke; } - public AvatarDomain(GameObject avatarRoot, bool previewing, - IAssetSaver saver, - IProgressHandling progressHandler, - ITextureManager textureManager, - IStackManager stackManager, - bool? isObjectReplaceInvoke = null - ) : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, saver, progressHandler, textureManager, stackManager) + public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver saver, ITextureManager textureManager, IStackManager stackManager) + : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, saver, textureManager, stackManager) { _avatarRoot = avatarRoot; - _previewing = previewing; - _isObjectReplaceInvoke = isObjectReplaceInvoke ?? TTTConfig.IsObjectReplaceInvoke; } - bool _previewing; - [SerializeField] GameObject _avatarRoot; public GameObject AvatarRoot => _avatarRoot; - bool _isObjectReplaceInvoke; - - public override void EditFinish() - { - base.EditFinish(); - - if (_previewing) { return; } - - var modMap = _objectMap.GetMapping; -#if NDMF_1_3_x - foreach (var replaceKV in modMap) - { - nadena.dev.ndmf.ObjectRegistry.RegisterReplacedObject(replaceKV.Key, replaceKV.Value); - } -#endif - if (_isObjectReplaceInvoke) - { - SerializedObjectCrawler.ReplaceSerializedObjects(_avatarRoot, modMap); - } - } } internal class FlatMapDict diff --git a/Editor/Domain/ProgressHandler.cs b/Editor/Domain/ProgressHandler.cs deleted file mode 100644 index 8dca283c..00000000 --- a/Editor/Domain/ProgressHandler.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Collections.Generic; -using UnityEditor; -using UnityEngine.Profiling; - -namespace net.rs64.TexTransTool -{ - internal class ProgressHandler : IProgressHandling - { - List _progressDepth = new List(); - public void ProgressStateEnter(string enterName) - { - Profiler.BeginSample(enterName); - _progressDepth.Add(enterName); - } - - public void ProgressStateExit() - { - Profiler.EndSample(); - _progressDepth.RemoveAt(_progressDepth.Count - 1); - } - - public void ProgressUpdate(string state, float value) - { - EditorUtility.DisplayProgressBar(string.Join("-", _progressDepth), state, value); - } - - public void ProgressFinalize() - { - EditorUtility.ClearProgressBar(); - } - } -} diff --git a/Editor/Domain/ProgressHandler.cs.meta b/Editor/Domain/ProgressHandler.cs.meta deleted file mode 100644 index 58bbd111..00000000 --- a/Editor/Domain/ProgressHandler.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b1319912443ff1142a731c323c9295c1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index 8a3e4e1a..64c2397a 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -28,31 +28,25 @@ internal class RenderersDomain : IEditorCallDomain public readonly bool Previewing; [CanBeNull] private readonly IAssetSaver _saver; - private readonly IProgressHandling _progressHandler; private readonly ITextureManager _textureManager; private readonly IStackManager _textureStacks; - [NotNull] protected FlatMapDict _objectMap = new(); protected Dictionary _replaceMap = new();//New Old - public RenderersDomain(List previewRenderers, bool previewing, bool saveAsset = false, bool progressDisplay = false) - : this(previewRenderers, previewing, saveAsset ? new AssetSaver() : null, progressDisplay) { } - public RenderersDomain(List previewRenderers, bool previewing, IAssetSaver assetSaver, bool progressDisplay = false) + public RenderersDomain(List previewRenderers, bool previewing, bool saveAsset = false) + : this(previewRenderers, previewing, saveAsset ? new AssetSaver() : null) { } + public RenderersDomain(List previewRenderers, bool previewing, IAssetSaver assetSaver) { _renderers = previewRenderers; Previewing = previewing; _saver = assetSaver; - _progressHandler = progressDisplay ? new ProgressHandler() : null; _textureManager = new TextureManager(Previewing); _textureStacks = new StackManager(_textureManager); - - _progressHandler?.ProgressStateEnter("ProsesAvatar"); } public RenderersDomain(List previewRenderers, bool previewing, IAssetSaver saver, - IProgressHandling progressHandler, ITextureManager textureManager, IStackManager stackManager ) @@ -60,11 +54,8 @@ IStackManager stackManager _renderers = previewRenderers; Previewing = previewing; _saver = saver; - _progressHandler = progressHandler; _textureManager = textureManager; _textureStacks = stackManager; - - _progressHandler?.ProgressStateEnter("ProsesAvatar"); } public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair @@ -173,55 +164,31 @@ Object GetOrigin(Object obj) } public virtual void RegisterReplace(Object oldObject, Object nowObject) { - _objectMap.Add(oldObject, nowObject); - _replaceMap[oldObject] = nowObject; + _replaceMap[nowObject] = oldObject; } public virtual void EditFinish() { - ProgressStateEnter("Finalize"); - ProgressUpdate("MergeStack", 0.0f); - MergeStack(); - - ProgressUpdate("DeferTexDestroy", 0.3f); - - _textureManager.DestroyTextures(); - - ProgressUpdate("TexCompressDelegationInvoke", 0.6f); - - _textureManager.TextureFinalize(); - - ProgressUpdate("End", 1f); - ProgressStateExit(); - ProgressStateExit(); - _progressHandler?.ProgressFinalize(); + _textureManager.DestroyDeferred(); + _textureManager.CompressDeferred(); } public virtual void MergeStack() { - ProgressUpdate("MergeStack", 0f); var MergedStacks = _textureStacks.MergeStacks(); - ProgressUpdate("MergeStack", 0.9f); + foreach (var mergeResult in MergedStacks) { if (mergeResult.FirstTexture == null || mergeResult.MergeTexture == null) continue; SetTexture(mergeResult.FirstTexture, mergeResult.MergeTexture); TransferAsset(mergeResult.MergeTexture); } - ProgressUpdate("MergeStack", 1); } - public void ProgressStateEnter(string enterName) => _progressHandler?.ProgressStateEnter(enterName); - public void ProgressUpdate(string state, float value) => _progressHandler?.ProgressUpdate(state, value); - public void ProgressStateExit() => _progressHandler?.ProgressStateExit(); - public void ProgressFinalize() => _progressHandler?.ProgressFinalize(); - - - - public ITextureManager GetTextureManager() => _textureManager; - + public IEnumerable EnumerateRenderer() { return _renderers; } public bool IsPreview() => Previewing; + public ITextureManager GetTextureManager() => _textureManager; } } diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 011c8719..6653138a 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -22,24 +22,18 @@ namespace net.rs64.TexTransTool public TextureManager(bool previewing) { Previewing = previewing; - if (!Previewing) { DestroyList = new List(); } - else { DestroyList = null; } - if (!Previewing) { CompressDict = new Dictionary(); } - else { CompressDict = null; } - if (!Previewing) { OriginDict = new Dictionary(); } - else { OriginDict = null; } - if (!Previewing) { CanvasSouse = new(); } - else { CanvasSouse = null; } - - + DestroyList = !Previewing ? new() : null; + CompressDict = !Previewing ? new() : null; + OriginDict = !Previewing ? new() : null; + CanvasSouse = !Previewing ? new() : null; } - public void DeferDestroyTexture2D(Texture2D texture2D) + public void DeferDestroyOf(Texture2D texture2D) { DestroyList.Add(texture2D); } - public void DestroyTextures() + public void DestroyDeferred() { if (DestroyList == null) { return; } foreach (var tex in DestroyList) @@ -74,7 +68,7 @@ public Texture2D GetOriginalTexture(Texture2D texture2D) else { var originTex = texture2D.TryGetUnCompress(); - DeferDestroyTexture2D(originTex); + DeferDestroyOf(originTex); OriginDict.Add(texture2D, originTex); return originTex; } @@ -92,12 +86,12 @@ public void WriteOriginalTexture(TTTImportedImage texture, RenderTexture writeTa texture.LoadImage(CanvasSouse[texture.CanvasDescription], writeTarget); } } - public void TextureCompressDelegation((TextureFormat CompressFormat, int Quality) compressSetting, Texture2D target) + public void DeferTextureCompress((TextureFormat CompressFormat, int Quality) compressSetting, Texture2D target) { if (CompressDict == null) { return; } CompressDict[target] = compressSetting; } - public void ReplaceTextureCompressDelegation(Texture2D Souse, Texture2D Target) + public void DeferInheritTextureCompress(Texture2D Souse, Texture2D Target) { if (CompressDict == null) { return; } if (Target == Souse) { return; } @@ -112,7 +106,7 @@ public void ReplaceTextureCompressDelegation(Texture2D Souse, Texture2D Target) } } - public void TextureFinalize() + public void CompressDeferred() { if (CompressDict == null) { return; } foreach (var texAndFormat in CompressDict) diff --git a/Editor/EditorProcessor/TexTransGroupProcessor.cs b/Editor/EditorProcessor/TexTransGroupProcessor.cs index c6e0852d..f1148075 100644 --- a/Editor/EditorProcessor/TexTransGroupProcessor.cs +++ b/Editor/EditorProcessor/TexTransGroupProcessor.cs @@ -11,7 +11,7 @@ public void Process(TexTransCallEditorBehavior texTransCallEditorBehavior, IEdit var ttg = texTransCallEditorBehavior as TexTransGroup; if (!ttg.IsPossibleApply) { TTTLog.Error("Not executable"); return; } - editorCallDomain.ProgressStateEnter("TexTransGroup"); + // editorCallDomain.ProgressStateEnter("TexTransGroup"); var targetList = TexTransGroup.TextureTransformerFilter(ttg.Targets).ToArray(); var count = 0; @@ -19,9 +19,9 @@ public void Process(TexTransCallEditorBehavior texTransCallEditorBehavior, IEdit { count += 1; tf.Apply(editorCallDomain); - editorCallDomain.ProgressUpdate(tf.name + " Apply", (float)count / targetList.Length); + // editorCallDomain.ProgressUpdate(tf.name + " Apply", (float)count / targetList.Length); } - editorCallDomain.ProgressStateExit(); + // editorCallDomain.ProgressStateExit(); } } } diff --git a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs index 51eca2df..defbd343 100644 --- a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs +++ b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs @@ -34,7 +34,7 @@ public static void DrawPreviewMLIC(Rect previewArea, MultiLayerImageCanvas mlic) { var texManager = new TextureManager(true); var canvasResult = mlic.EvaluateCanvas(texManager, 1024); - texManager.DestroyTextures(); + texManager.DestroyDeferred(); EditorGUI.DrawTextureTransparent(previewArea, canvasResult, ScaleMode.ScaleToFit); RenderTexture.ReleaseTemporary(canvasResult); diff --git a/Editor/PreviewContext.cs b/Editor/PreviewContext.cs index 36857581..d85f2443 100644 --- a/Editor/PreviewContext.cs +++ b/Editor/PreviewContext.cs @@ -98,22 +98,29 @@ static void TexTransBehaviorApply(TexTransBehavior targetTTBehavior) AnimationMode.BeginSampling(); try { + EditorUtility.DisplayProgressBar("TexTransBehaviorApply", "", 0f); Profiler.BeginSample("TexTransBehaviorApply: " + targetTTBehavior.GetType() + " " + targetTTBehavior.gameObject.name); RenderersDomain previewDomain = null; + EditorUtility.DisplayProgressBar("FindMarker", "", 0.01f); Profiler.BeginSample("FindMarker"); var marker = DomainMarkerFinder.FindMarker(targetTTBehavior.gameObject); Profiler.EndSample(); - if (marker != null) { previewDomain = new AvatarDomain(marker, true, false, true); } - else { previewDomain = new RenderersDomain(targetTTBehavior.GetRenderers, true, false, true); } + EditorUtility.DisplayProgressBar("Create Domain", "", 0.1f); + if (marker != null) { previewDomain = new AvatarDomain(marker, true, false); } + else { previewDomain = new RenderersDomain(targetTTBehavior.GetRenderers, true, false); } + EditorUtility.DisplayProgressBar("Preview Apply", "", 0.2f); + //カスタムプレビューとエディターコールビヘイビアは違うから注意 if (!TTTCustomPreviewUtility.TryExecutePreview(targetTTBehavior, previewDomain)) { targetTTBehavior.Apply(previewDomain); } + EditorUtility.DisplayProgressBar("Edit Finish", "", 0.95f); previewDomain.EditFinish(); } finally { Profiler.EndSample(); AnimationMode.EndSampling(); + EditorUtility.ClearProgressBar(); } } diff --git a/Editor/TTTConfig.cs b/Editor/TTTConfig.cs index 05660c8b..40b32b1b 100644 --- a/Editor/TTTConfig.cs +++ b/Editor/TTTConfig.cs @@ -14,7 +14,6 @@ internal static class TTTConfig [TexTransInitialize] internal static void SettingInitializer() { - IsObjectReplaceInvoke = EditorPrefs.GetBool(OBJECT_REPLACE_INVOKE_PREFKEY); Localize.LocalizeInitializer(); } #region Language @@ -52,22 +51,5 @@ public enum LanguageEnum #endregion - #region ObjectReplaceInvoke - public const string OBJECT_REPLACE_INVOKE_MENU_PATH = EXPERIMENTAL_MENU_PATH + "/ObjectReplaceInvoke"; - public const string OBJECT_REPLACE_INVOKE_PREFKEY = "net.rs64.tex-trans-tool.ObjectReplaceInvoke"; - private static bool s_isObjectReplaceInvoke; - public static bool IsObjectReplaceInvoke { get => s_isObjectReplaceInvoke; private set { s_isObjectReplaceInvoke = value; ObjectReplaceInvokeConfigUpdate(); } } - - [MenuItem(OBJECT_REPLACE_INVOKE_MENU_PATH)] - static void ToggleObjectReplaceInvoke() - { - IsObjectReplaceInvoke = !IsObjectReplaceInvoke; - } - private static void ObjectReplaceInvokeConfigUpdate() - { - EditorPrefs.SetBool(OBJECT_REPLACE_INVOKE_PREFKEY, IsObjectReplaceInvoke); - Menu.SetChecked(OBJECT_REPLACE_INVOKE_MENU_PATH, IsObjectReplaceInvoke); - } - #endregion } } diff --git a/Editor/TextureStack/DeferredTextureStack.cs b/Editor/TextureStack/DeferredTextureStack.cs index f0dd4d68..ad097aa4 100644 --- a/Editor/TextureStack/DeferredTextureStack.cs +++ b/Editor/TextureStack/DeferredTextureStack.cs @@ -27,7 +27,7 @@ public override Texture2D MergeStack() var resultTex = renderTexture.CopyTexture2D().CopySetting(FirstTexture, false); resultTex.name = FirstTexture.name + "_MergedStack"; - TextureManager.ReplaceTextureCompressDelegation(FirstTexture, resultTex); + TextureManager.DeferInheritTextureCompress(FirstTexture, resultTex); RenderTexture.ReleaseTemporary(renderTexture); return resultTex; } diff --git a/Editor/TextureStack/ImmediateTextureStack.cs b/Editor/TextureStack/ImmediateTextureStack.cs index 216d3a67..2501bd96 100644 --- a/Editor/TextureStack/ImmediateTextureStack.cs +++ b/Editor/TextureStack/ImmediateTextureStack.cs @@ -34,7 +34,7 @@ public override Texture2D MergeStack() { var resultTex = renderTexture.CopyTexture2D().CopySetting(FirstTexture, false); resultTex.name = FirstTexture.name + "_MergedStack"; - TextureManager.ReplaceTextureCompressDelegation(FirstTexture, resultTex); + TextureManager.DeferInheritTextureCompress(FirstTexture, resultTex); RenderTexture.ReleaseTemporary(renderTexture); diff --git a/Editor/Utils/AssetSaveHelper.cs b/Editor/Utils/AssetSaveHelper.cs deleted file mode 100644 index a534128d..00000000 --- a/Editor/Utils/AssetSaveHelper.cs +++ /dev/null @@ -1,178 +0,0 @@ -using System.IO; -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -namespace net.rs64.TexTransTool -{ - internal static class AssetSaveHelper - { - static bool s_isTemporary; - public static bool IsTemporary - { - get => s_isTemporary; - set - { - s_isTemporary = value; - if (!s_isTemporary) - { - ClearTemp(); - } - else - { - SaveDirectoryCheck(); - } - } - } - public const string SaveDirectory = "Assets/TexTransToolGenerates"; - public const string IslandCaches = "IslandCaches"; - public const string AvatarDomainAssets = "AvatarDomainAssets"; - public const string Temp = "TempDirectory"; - - public enum SaveType - { - Other, - IslandCaches, - AvatarDomainAssets, - } - - public static string GenerateAssetPath(string name, string extension, SaveType saveType = SaveType.Other) - { - SaveDirectoryCheck(); - var path = GenerateFullPath(name, saveType); - path += extension; - path = AssetDatabase.GenerateUniqueAssetPath(path); - return path; - } - private static void SaveDirectoryCheck() - { - if (!Directory.Exists(SaveDirectory)) Directory.CreateDirectory(SaveDirectory); - if (!Directory.Exists(Path.Combine(SaveDirectory, Temp))) Directory.CreateDirectory(Path.Combine(SaveDirectory, Temp)); - if (!Directory.Exists(Path.Combine(SaveDirectory, IslandCaches))) Directory.CreateDirectory(Path.Combine(SaveDirectory, IslandCaches)); - if (!Directory.Exists(Path.Combine(SaveDirectory, AvatarDomainAssets))) Directory.CreateDirectory(Path.Combine(SaveDirectory, AvatarDomainAssets)); - } - private static string GenerateFullPath(string name, SaveType saveType = SaveType.Other) - { - var replacedName = name.Replace("(Clone)", ""); - replacedName = string.IsNullOrWhiteSpace(replacedName) ? "GenerateAsset" : replacedName; - string parentPath; - if (!IsTemporary) - { - parentPath = GetDirectoryAtType(saveType); - } - else - { - parentPath = Path.Combine(SaveDirectory, Temp); - } - - return Path.Combine(parentPath, replacedName); - } - private static string GetDirectoryAtType(SaveType saveType) - { - switch (saveType) - { - default: - case SaveType.Other: - return SaveDirectory; - case SaveType.IslandCaches: - return Path.Combine(SaveDirectory, IslandCaches); - case SaveType.AvatarDomainAssets: - return Path.Combine(SaveDirectory, AvatarDomainAssets); - } - } - private static SaveType GetSaveTypeAtAsset(T asset = null) where T : class - { - var type = typeof(T); - if (type == typeof(AvatarDomainAsset)) - { - return SaveType.AvatarDomainAssets; - } - else - { - return SaveType.Other; - } - } - public static void SaveAssets(IEnumerable targets) where T : UnityEngine.Object - { - foreach (var target in targets) - { - SaveAsset(target); - } - } - - public static void SaveAsset(T target) where T : UnityEngine.Object - { - if (target == null) { return; } - if (AssetDatabase.Contains(target)) { return; } - string savePath = null; - switch (target) - { - default: - { - savePath = GenerateAssetPath(target.name, ".asset", GetSaveTypeAtAsset(target)); - break; - } - case Material Mat: - { - savePath = GenerateAssetPath(target.name, ".mat"); - break; - } - } - AssetDatabase.CreateAsset(target, savePath); - AssetDatabase.ImportAsset(savePath); - } - - public static Texture2D SavePng(Texture2D target) - { - if (target == null) { return null; } - - var savePath = GenerateAssetPath(target.name, ".png"); - File.WriteAllBytes(savePath, target.EncodeToPNG()); - AssetDatabase.ImportAsset(savePath); - return AssetDatabase.LoadAssetAtPath(savePath); - - } - - public static void DeleteAssets(IEnumerable targets) where T : UnityEngine.Object - { - foreach (var target in targets) - { - DeleteAsset(target); - } - } - public static void DeleteAsset(T target) where T : UnityEngine.Object - { - if (target == null) return; - var path = AssetDatabase.GetAssetPath(target); - if (!string.IsNullOrEmpty(path)) - { - AssetDatabase.DeleteAsset(path); - } - } - - public static List LoadAssets() where T : UnityEngine.Object - { - SaveDirectoryCheck(); - var saveType = GetSaveTypeAtAsset(); - List loadedAssets = new(); - foreach (var path in Directory.GetFiles(GetDirectoryAtType(saveType))) - { - if (AssetDatabase.LoadAssetAtPath(path, typeof(T)) is T instants) - { - loadedAssets.Add(instants); - } - } - return loadedAssets; - } - private static void ClearTemp() - { - SaveDirectoryCheck(); - var tempPath = Path.Combine(SaveDirectory, Temp); - foreach (var path in Directory.GetFiles(tempPath)) - { - if (string.IsNullOrWhiteSpace(path)) continue; - AssetDatabase.DeleteAsset(path); - } - - } - } -} diff --git a/Editor/Utils/DebugUtils.cs b/Editor/Utils/DebugUtils.cs deleted file mode 100644 index aaf780eb..00000000 --- a/Editor/Utils/DebugUtils.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using System; -using UnityEngine; -using System.Diagnostics; -using net.rs64.TexTransCore.TransTextureCore; - -namespace net.rs64.TexTransTool.Utils -{ - internal static class TriangleDebug - { - public static string TriangleToString(IEnumerable triangle, IReadOnlyList vertex) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - - foreach (var I in triangle) - { - sb.Append($"{vertex[I[0]].x},{vertex[I[0]].y},{vertex[I[0]].z},"); - sb.Append($"{vertex[I[1]].x},{vertex[I[1]].y},{vertex[I[1]].z},"); - sb.Append($"{vertex[I[2]].x},{vertex[I[2]].y},{vertex[I[2]].z}\n"); - } - return sb.ToString(); - } - } - - internal class DebugTimer - { - Stopwatch _Stopwatch; - Stopwatch _StepStopwatch; - - public DebugTimer() - { - _Stopwatch = new Stopwatch(); - _StepStopwatch = new Stopwatch(); - _Stopwatch.Start(); - _StepStopwatch.Start(); - } - - public void Log(string message = "") - { - _StepStopwatch.Stop(); - _Stopwatch.Stop(); - - ELtoLog(_StepStopwatch.Elapsed, message); - - _StepStopwatch.Restart(); - _Stopwatch.Start(); - } - - public void EndLog(string message = "") - { - Log(message); - _Stopwatch.Stop(); - ELtoLog(_Stopwatch.Elapsed, "Total"); - } - - public static void ELtoLog(TimeSpan el, string message = "") - { - UnityEngine.Debug.Log($"{message} {el.Hours}h {el.Minutes}m {el.Seconds}s {el.Milliseconds}ms"); - } - } -} diff --git a/Editor/Utils/DebugUtils.cs.meta b/Editor/Utils/DebugUtils.cs.meta deleted file mode 100644 index 7fff12d3..00000000 --- a/Editor/Utils/DebugUtils.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7aef8c402d547ac4fb1cf0a46da8a911 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Utils/TexTransGroupValidationUtili.cs b/Editor/Utils/TexTransGroupValidationUtili.cs deleted file mode 100644 index 9c8c7416..00000000 --- a/Editor/Utils/TexTransGroupValidationUtili.cs +++ /dev/null @@ -1,116 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransTool.Decal; -using net.rs64.TexTransTool.TextureAtlas; -using net.rs64.TexTransTool.MatAndTexUtils; - -namespace net.rs64.TexTransTool -{ - internal static class TexTransGroupValidationUtils - { - public static void ValidateTexTransGroup(TexTransGroup texTransGroup) - { - var tTFs = TexTransGroup.TextureTransformerFilter(texTransGroup.Targets); - var renderersPeaTTFsDict = new Dictionary>(); - CollectTexTransForms(tTFs, renderersPeaTTFsDict); - - var warnTarget = new List(); - - foreach (var rendererPadTTF in renderersPeaTTFsDict) - { - var allowSeparateFlag = true; - foreach (var tf in rendererPadTTF.Value) - { - switch (tf) - { - case MatAndTexAbsoluteSeparator matAndTexSeparator: - { - if (!allowSeparateFlag) { warnTarget.Add(matAndTexSeparator); } - break; - } - case MatAndTexRelativeSeparator matAndTexRelativeSeparator: - { - if (!allowSeparateFlag) { warnTarget.Add(matAndTexRelativeSeparator); } - break; - } - case AtlasTexture atlasTexture: - { - if (!allowSeparateFlag) { warnTarget.Add(atlasTexture); } - break; - } - default: { break; } - - } - } - } - - foreach (var tf in warnTarget.Distinct()) - { - switch (tf) - { - case AbstractDecal abstractDecal: - { - Debug.LogWarning($"{abstractDecal.GetType().Name} : {abstractDecal.name} のIsSeparateMatAndTextureは、先に張り付けられたデカールを完全に消してしまう可能性があります。"); - break; - } - case AtlasTexture atlasTexture: - { - Debug.LogWarning($"AtlasTexture : {atlasTexture.name} は、先に張り付けられたデカールを完全に消す可能性があります。"); - break; - } - default: { break; } - } - - } - - } - - private static void CollectTexTransForms(IEnumerable tTFs, Dictionary> renderersPeaTTFsDict) - { - foreach (var ttf in tTFs) - { - switch (ttf) - { - case AbstractDecal abstractDecal: - { - foreach (var tRenderer in abstractDecal.TargetRenderers) - { - if (renderersPeaTTFsDict.ContainsKey(tRenderer)) - { - renderersPeaTTFsDict[tRenderer].Add(abstractDecal); - } - else - { - renderersPeaTTFsDict.Add(tRenderer, new List() { abstractDecal }); - } - } - break; - } - case AtlasTexture atlasTexture: - { - foreach (var tRenderer in atlasTexture.Renderers) - { - if (renderersPeaTTFsDict.ContainsKey(tRenderer)) - { - renderersPeaTTFsDict[tRenderer].Add(atlasTexture); - } - else - { - renderersPeaTTFsDict.Add(tRenderer, new List() { atlasTexture }); - } - } - break; - } - case TexTransGroup abstractTexTransGroup: - { - CollectTexTransForms(TexTransGroup.TextureTransformerFilter(abstractTexTransGroup.Targets), renderersPeaTTFsDict); - break; - } - - default: { break; } - } - } - } - } -} diff --git a/Editor/Utils/TexTransGroupValidationUtili.cs.meta b/Editor/Utils/TexTransGroupValidationUtili.cs.meta deleted file mode 100644 index ad5a4e70..00000000 --- a/Editor/Utils/TexTransGroupValidationUtili.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 20e843c9b2a3965478c6b1ed523c873b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/AbstractDecal.cs b/Runtime/Decal/AbstractDecal.cs index 2bea5c41..a8dc78aa 100644 --- a/Runtime/Decal/AbstractDecal.cs +++ b/Runtime/Decal/AbstractDecal.cs @@ -47,14 +47,8 @@ internal override void Apply(IDomain domain) return; } - domain.ProgressStateEnter("AbstractDecal"); - - domain.ProgressUpdate("DecalCompile", 0.25f); - var decalCompiledTextures = CompileDecal(domain.GetTextureManager(), DictionaryPool.Get()); - domain.ProgressUpdate("AddStack", 0.75f); - foreach (var matAndTex in decalCompiledTextures) { domain.AddTextureStack(matAndTex.Key.GetTexture(TargetPropertyName) as Texture2D, new TextureBlend.BlendTexturePair(matAndTex.Value, BlendTypeKey)); @@ -62,8 +56,6 @@ internal override void Apply(IDomain domain) DictionaryPool.Release(decalCompiledTextures); - domain.ProgressUpdate("End", 1); - domain.ProgressStateExit(); } diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index 267fa7b5..fe0b0bbb 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -8,40 +8,37 @@ namespace net.rs64.TexTransTool { - internal interface IDomain : IAssetSaver, IProgressHandling, IReplaceTracking + internal interface IDomain : IAssetSaver, IReplaceTracking { void ReplaceMaterials(Dictionary mapping, bool rendererOnly = false); void SetMesh(Renderer renderer, Mesh mesh); - public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair;//RenderTextureを入れる場合 Temp にすること、そしてこちら側でそれが解放される。 + public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair;// TempRenderTexture 想定 - bool IsPreview();//極力使わない方針で、どうしようもないやつだけ使うこと。テクスチャとかはプレビューの場合は自動で切り替わるから、これを見るコードをできるだけ作りたくないという意図です。 + public IEnumerable EnumerateRenderer(); ITextureManager GetTextureManager(); + + bool IsPreview();//極力使わない方針で、どうしようもないやつだけ使うこと。テクスチャとかはプレビューの場合は自動で切り替わるから、これを見るコードをできるだけ作りたくないという意図です。 } internal interface IAssetSaver { void TransferAsset(UnityEngine.Object asset); } - internal interface IProgressHandling - { - void ProgressStateEnter(string enterName); - void ProgressUpdate(string state, float value); - void ProgressStateExit(); - void ProgressFinalize(); - } internal interface ITextureManager : IOriginTexture { - void DeferDestroyTexture2D(Texture2D texture2D); - void DestroyTextures(); + void DeferDestroyOf(Texture2D texture2D); + void DestroyDeferred(); + - void TextureCompressDelegation((TextureFormat CompressFormat, int Quality) compressFormat, Texture2D target); - void ReplaceTextureCompressDelegation(Texture2D souse, Texture2D target); - void TextureFinalize(); + void DeferTextureCompress((TextureFormat CompressFormat, int Quality) compressFormat, Texture2D target); + void DeferInheritTextureCompress(Texture2D souse, Texture2D target); + void CompressDeferred(); } internal interface IReplaceTracking { bool OriginEqual(UnityEngine.Object l, UnityEngine.Object r); + //今後テクスチャとメッシュとマテリアル以外で置き換えが必要になった時できるようにするために用意はしておく void RegisterReplace(UnityEngine.Object oldObject, UnityEngine.Object nowObject); } @@ -79,4 +76,5 @@ public static RenderTexture GetOriginTempRt(this IOriginTexture origin, Texture2 return tempRt; } } + } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 813bafc8..117057d4 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -691,15 +691,10 @@ internal override void Apply(IDomain domain = null) return; } - domain.ProgressStateEnter("AtlasTexture"); - domain.ProgressUpdate("CompileAtlasTexture", 0f); - Profiler.BeginSample("TryCompileAtlasTextures"); if (!TryCompileAtlasTextures(domain, out var atlasData)) { Profiler.EndSample(); return; } Profiler.EndSample(); - domain.ProgressUpdate("MeshChange", 0.5f); - var nowRenderers = Renderers; Profiler.BeginSample("AtlasShaderSupportUtils:ctor"); @@ -719,8 +714,6 @@ internal override void Apply(IDomain domain = null) domain.TransferAsset(atlasMesh); } - domain.ProgressUpdate("Texture Fine Tuning", 0.75f); - //Texture Fine Tuning var atlasTexFineTuningTargets = TexFineTuningUtility.ConvertForTargets(atlasData.Textures); TexFineTuningUtility.InitTexFineTuning(atlasTexFineTuningTargets); @@ -739,12 +732,10 @@ internal override void Apply(IDomain domain = null) var compressSetting = atlasTexFTData.TuningDataList.Find(I => I is CompressionQualityData) as CompressionQualityData; if (compressSetting == null) { continue; } var compressSettingTuple = (CompressionQualityApplicant.GetTextureFormat(tex, compressSetting), (int)compressSetting.CompressionQuality); - domain.GetTextureManager().TextureCompressDelegation(compressSettingTuple, atlasTexFTData.Texture2D); + domain.GetTextureManager().DeferTextureCompress(compressSettingTuple, atlasTexFTData.Texture2D); } - domain.ProgressUpdate("MaterialGenerate And Change", 0.9f); - //MaterialGenerate And Change if (AtlasSetting.MergeMaterials) { @@ -776,8 +767,6 @@ Material FindGroup(Material material) domain.ReplaceMaterials(materialMap, true); } - domain.ProgressUpdate("End", 1); - domain.ProgressStateExit(); } private void TransMoveRectIsland(Texture souseTex, RenderTexture targetRT, Dictionary notAspectIslandPairs, float uvScalePadding) where TIslandRect : IIslandRect From faab56dd28d60a41d71bc2bb1764dcec78333255 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 15 Apr 2024 16:44:15 +0900 Subject: [PATCH 074/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + CHANGELOG.md | 3 +++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index bf3c2b94..90776af4 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -21,6 +21,7 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Removed - IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) +- ObjectReplaceInvoke は削除されました (#438) ### Fixed diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cb706ed..391c11d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Optimizing Phase が追加されました (#410) + - NDMF OptimizePhaseに実行されるようになりました。 (#438) - GameObject から TexTransTool のほとんどのコンポーネントが追加できるようになりました (#411) - AtlasTexture に強制的に優先度のサイズに変更する ForcePrioritySize が追加されました (#431) - AtlasTexture 複数のマテリアルが衝突しないテクスチャを持つ場合に、同一のアイランドが割り当てられるようになりました (#431) - AtlasTexture が Scale Transition(Tiling) を使用しているマテリアルのテクスチャを逆補正する機能が追加されました (#431 #435) +- NDMF環境でのビルドを行う場合、オブジェクトの置き換えの追跡を NDMF ObjectRegistry を使用するようになりました (#438) ### Changed @@ -23,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed - AtlasTexture の UseUpScale は削除されました (#431) +- プログレスバーの詳細な表示が削除されました (#438) ### Fixed From c362b39075635a4fc9514c4c7d221986264af4f9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 12 Apr 2024 03:09:52 +0900 Subject: [PATCH 075/208] fix: broken to load ndmfLocalizer --- Editor/ErrorReporting/TTTLog.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Editor/ErrorReporting/TTTLog.cs b/Editor/ErrorReporting/TTTLog.cs index afe92f6f..926467fa 100644 --- a/Editor/ErrorReporting/TTTLog.cs +++ b/Editor/ErrorReporting/TTTLog.cs @@ -82,7 +82,11 @@ public static nadena.dev.ndmf.localization.Localizer NDMFLocalizer { get { - _ndmfLocalizer ??= new nadena.dev.ndmf.localization.Localizer("en-US", () => Localize.LocalizationAssets.Values.ToList()); + if (_ndmfLocalizer == null) + { + Localize.LoadLocalize(); + _ndmfLocalizer = new nadena.dev.ndmf.localization.Localizer("en-US", () => Localize.LocalizationAssets.Values.ToList()); + } return _ndmfLocalizer; } } From 438b2d1d6aa72603f43de7571da77a50d5451c2d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 15 Apr 2024 19:43:13 +0900 Subject: [PATCH 076/208] Improve: read correctly ImageResourceBlock --- .../PSD/Parsers/ImageResourceBlocksParser.cs | 15 +++++++++--- .../PSD/Parsers/LayerRecordParser.cs | 4 ++-- MultiLayerImage-Parser/ParserUtility.cs | 23 ++++++------------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs b/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs index abb01e02..55b2eda8 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using UnityEngine; namespace net.rs64.MultiLayerImage.Parser.PSD @@ -25,10 +26,18 @@ public static List PaseImageResourceBlocks(SubSpanStream str var nowIRB = new ImageResourceBlock(); nowIRB.UniqueIdentifier = stream.ReadUInt16(); - nowIRB.PascalStringName = ParserUtility.ReadPascalString(ref stream); + + var strLength = stream.ReadByte(); + if (strLength == 0) + { + stream.ReadByte(); + nowIRB.PascalStringName = null; + } + else { nowIRB.PascalStringName = Encoding.GetEncoding("shift-jis").GetString(stream.ReadSubStream(strLength).Span); } nowIRB.ActualDataSizeFollows = stream.ReadUInt32(); - nowIRB.ResourceData = stream.ReadSubStream((int)nowIRB.ActualDataSizeFollows).Span.ToArray(); + var actualLength = nowIRB.ActualDataSizeFollows % 2 == 0 ? nowIRB.ActualDataSizeFollows : nowIRB.ActualDataSizeFollows + 1; + nowIRB.ResourceData = stream.ReadSubStream((int)actualLength).Span.ToArray(); imageResourceBlockList.Add(nowIRB); } @@ -36,4 +45,4 @@ public static List PaseImageResourceBlocks(SubSpanStream str return imageResourceBlockList; } } -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/PSD/Parsers/LayerRecordParser.cs b/MultiLayerImage-Parser/PSD/Parsers/LayerRecordParser.cs index eb1ce189..b6a16594 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/LayerRecordParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/LayerRecordParser.cs @@ -190,7 +190,7 @@ public static LayerRecord PaseLayerRecord(ref SubSpanStream stream) layerRecord.LayerBlendingRangesData = layerBlendingRangesData; - layerRecord.LayerName = ParserUtility.ReadPascalString(ref stream); + layerRecord.LayerName = ParserUtility.ReadPascalStringForPadding4Byte(ref stream); var AdditionalLayerInformationSpan = stream.ReadSubStream((int)(layerRecord.ExtraDataFieldLength - (stream.Position - firstPos))); @@ -256,4 +256,4 @@ internal class SourceAndDestinationRange } } -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/ParserUtility.cs b/MultiLayerImage-Parser/ParserUtility.cs index 260322a0..412018bf 100644 --- a/MultiLayerImage-Parser/ParserUtility.cs +++ b/MultiLayerImage-Parser/ParserUtility.cs @@ -116,29 +116,20 @@ internal static class ParserUtility { public static bool Signature(ref SubSpanStream stream, byte[] signature) { - bool hitSignature = false; - while (!hitSignature) - { - byte readValue = stream.ReadByte(); - if (stream.Position == stream.Length - 3) { return false; } - if (readValue == signature[0]) { hitSignature = true; stream.Position -= 1; } - } - return stream.ReadSubStream(signature.Length).Span.SequenceEqual(signature); - } - public static string ReadPascalString(ref SubSpanStream stream) + public static string ReadPascalStringForPadding4Byte(ref SubSpanStream stream) { var stringLength = stream.ReadByte(); - var count = 1; if (stringLength != 0) { - var str = Encoding.GetEncoding("shift-jis").GetString(stream.ReadSubStream(stringLength).Span.ToArray()); - count += stringLength; - if ((count % 4) != 0) + var str = Encoding.GetEncoding("shift-jis").GetString(stream.ReadSubStream(stringLength).Span); + var readLength = stringLength + 1; + if ((readLength % 4) != 0) { - for (int i = 0; (4 - (count % 4)) > i; i += 1) + var paddingLength = 4 - (readLength % 4); + for (int i = 0; paddingLength > i; i += 1) { stream.ReadByte(); } @@ -211,4 +202,4 @@ public static void CopyFrom(this NativeArray to, Span from) where T : s } } } -} \ No newline at end of file +} From a6bc9d8decb9ef2fa621cb48fa618cdce161abd9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 16 Apr 2024 15:24:49 +0900 Subject: [PATCH 077/208] chore: fix changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b86ddb5..07cbb8b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- SimpleDecal の 深度デカールを有効化した場合に例外が発生し正しく処理できない問題を修正 () +- SimpleDecal の 深度デカールを有効化した場合に例外が発生し正しく処理できない問題を修正 (#441) ## [0.6.5] From 489aedb41dc87986b6189a4a10e594a021083de2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 16 Apr 2024 17:28:51 +0900 Subject: [PATCH 078/208] change: replace to the byte Index --- .../PSD/Parsers/ImageResourceBlocksParser.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs b/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs index 55b2eda8..6cb9cf41 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/ImageResourceBlocksParser.cs @@ -14,7 +14,8 @@ internal class ImageResourceBlock public ushort UniqueIdentifier; public string PascalStringName; public uint ActualDataSizeFollows; - public byte[] ResourceData; + public uint ActualDataSizeFollowsPlusPadding; + public long ActualDataStartIndex; } public static List PaseImageResourceBlocks(SubSpanStream stream) { @@ -37,7 +38,8 @@ public static List PaseImageResourceBlocks(SubSpanStream str nowIRB.ActualDataSizeFollows = stream.ReadUInt32(); var actualLength = nowIRB.ActualDataSizeFollows % 2 == 0 ? nowIRB.ActualDataSizeFollows : nowIRB.ActualDataSizeFollows + 1; - nowIRB.ResourceData = stream.ReadSubStream((int)actualLength).Span.ToArray(); + nowIRB.ActualDataSizeFollowsPlusPadding = actualLength; + nowIRB.ActualDataStartIndex = stream.ReadSubStream((int)actualLength).FirstToPosition; imageResourceBlockList.Add(nowIRB); } From 46507fe16e70c3160065dbfa320dbf351a43f53c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 16 Apr 2024 17:30:31 +0900 Subject: [PATCH 079/208] change: add ImageDataStartIndex and ColorDataStartIndex --- .../PSD/Parsers/PSDLowLevelParser.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs b/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs index 86679420..ee9c9e4b 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs @@ -5,6 +5,7 @@ using static net.rs64.MultiLayerImage.Parser.PSD.GlobalLayerMaskInformationParser; using static net.rs64.MultiLayerImage.Parser.PSD.LayerInformationParser; using static net.rs64.MultiLayerImage.Parser.PSD.PSDParserImageResourceBlocksParser; +using Unity.Collections; namespace net.rs64.MultiLayerImage.Parser.PSD { @@ -25,7 +26,7 @@ public static PSDLowLevelData Parse(byte[] psdByte) // Signature ... - var spanStream = new SubSpanStream(psdByte.AsSpan()); + var spanStream = new SubSpanStream(psdByte); if (!spanStream.ReadSubStream(4).Span.SequenceEqual(OctBPSSignature)) { throw new System.Exception(); } if (!spanStream.ReadSubStream(2).Span.SequenceEqual(new byte[] { 0x00, 0x01 })) { throw new System.Exception(); } @@ -42,7 +43,7 @@ public static PSDLowLevelData Parse(byte[] psdByte) // Color Mode Data Section psd.ColorModeDataSectionLength = spanStream.ReadUInt32(); - psd.ColorData = spanStream.ReadSubStream((int)psd.ColorModeDataSectionLength).Span.ToArray(); + psd.ColorDataStartIndex = spanStream.ReadSubStream((int)psd.ColorModeDataSectionLength).FirstToPosition; // Image Resources Section @@ -54,6 +55,11 @@ public static PSDLowLevelData Parse(byte[] psdByte) psd.LayerAndMaskInformationSectionLength = spanStream.ReadUInt32(); psd.LayerInfo = LayerInformationParser.PaseLayerInfo(spanStream.ReadSubStream((int)psd.LayerAndMaskInformationSectionLength)); + // Image Data Section + + psd.ImageDataCompression = spanStream.ReadUInt16(); + psd.ImageDataStartIndex = spanStream.Position; + return psd; } @@ -82,7 +88,7 @@ internal enum ColorModeEnum : ushort // Color Mode Data Section public uint ColorModeDataSectionLength; - public byte[] ColorData; + public long ColorDataStartIndex; // Image Resources Section @@ -96,6 +102,9 @@ internal enum ColorModeEnum : ushort public LayerInfo LayerInfo; public GlobalLayerMaskInfo GlobalLayerMaskInfo; + //ImageDataSection + public ushort ImageDataCompression; + public long ImageDataStartIndex; } } -} \ No newline at end of file +} From 1df2f1d8f0df257d342b23edd9aa61591ac7e36f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 16 Apr 2024 17:33:29 +0900 Subject: [PATCH 080/208] chore: PSDByte the allocate from UnmannedMemory --- MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs b/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs index ee9c9e4b..6cefe605 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/PSDLowLevelParser.cs @@ -18,9 +18,14 @@ internal static class PSDLowLevelParser public static readonly byte[] OctBIMSignature = new byte[] { 0x38, 0x42, 0x49, 0x4D }; public static PSDLowLevelData Parse(string path) { - return Parse(File.ReadAllBytes(path)); + using (var fileStream = File.OpenRead(path)) + using (var nativePSDData = new NativeArray((int)fileStream.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + {//NativeArrayのサイズ的に、32bit int の最大値を超えるファイルサイズのPSDが読めないけど... PS"D" ではあまり気にする価値がなさそう。 + fileStream.Read(nativePSDData); + return Parse(nativePSDData); + } } - public static PSDLowLevelData Parse(byte[] psdByte) + public static PSDLowLevelData Parse(Span psdByte) { var psd = new PSDLowLevelData(); From 8cecfe1cdb58a13b49d9c93eff5cd1a2fbd858c1 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 16 Apr 2024 19:31:21 +0900 Subject: [PATCH 081/208] fix: size 1024 lower PSD import and meClear use --- .../MultiLayerImageImporter.cs | 110 ++++++++++-------- Editor/Unsafe/UnsafeBitMapDataUtility.cs | 24 ---- Editor/net.rs64.tex-trans-tool.editor.asmdef | 4 +- .../net.rs64.multi-layer-image-parser.asmdef | 5 +- .../Improted/PSD/PSDImportedRasterImage.cs | 22 ++-- .../PSD/PSDImportedRasterMaskImage.cs | 25 ++-- .../net.rs64.tex-trans-tool.runtime.asmdef | 3 +- TexTransCore/MipMap/MipMapUtility.cs | 2 +- {Editor => TexTransCore}/Unsafe.meta | 2 +- .../Unsafe/InternalsVisible.cs | 0 .../Unsafe/InternalsVisible.cs.meta | 0 TexTransCore/Unsafe/UnsafeNativeArrayClear.cs | 23 ++++ .../Unsafe/UnsafeNativeArrayClear.cs.meta | 2 +- {Editor => TexTransCore}/Unsafe/csc.rsp | 0 {Editor => TexTransCore}/Unsafe/csc.rsp.meta | 0 .../net.rs64.tex-trans-core.unsafe.asmdef | 4 +- ...net.rs64.tex-trans-core.unsafe.asmdef.meta | 0 TexTransCore/net.rs64.tex-trans-core.asmdef | 3 +- 18 files changed, 123 insertions(+), 106 deletions(-) delete mode 100644 Editor/Unsafe/UnsafeBitMapDataUtility.cs rename {Editor => TexTransCore}/Unsafe.meta (77%) rename {Editor => TexTransCore}/Unsafe/InternalsVisible.cs (100%) rename {Editor => TexTransCore}/Unsafe/InternalsVisible.cs.meta (100%) create mode 100644 TexTransCore/Unsafe/UnsafeNativeArrayClear.cs rename Editor/Unsafe/UnsafeBitMapDataUtility.cs.meta => TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta (83%) rename {Editor => TexTransCore}/Unsafe/csc.rsp (100%) rename {Editor => TexTransCore}/Unsafe/csc.rsp.meta (100%) rename Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef => TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef (86%) rename Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef.meta => TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef.meta (100%) diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index e29769c6..a54535bf 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -12,6 +12,7 @@ using Unity.Mathematics; using Unity.Burst; using UnityEngine.Profiling; +using Unity.Collections.LowLevel.Unsafe; namespace net.rs64.TexTransTool.MultiLayerImage.Importer { @@ -198,77 +199,84 @@ internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstra internal void CreatePreview() { var canvasSize = new int2(_tttImportedCanvasDescription.Width, _tttImportedCanvasDescription.Height); - - Action nextTaming = () => { }; - Action nextTaming2 = () => { }; - - var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - var fullNAF4Tex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - foreach (var importedImage in _tttImportedImages) + if (math.max(canvasSize.x, canvasSize.y) <= 1024) { - Profiler.BeginSample("CreatePreview -" + importedImage.name); - Profiler.BeginSample("LoadImage"); + using (var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + { + foreach (var importedImage in _tttImportedImages) + { + Profiler.BeginSample("CreatePreview -" + importedImage.name); + Profiler.BeginSample("LoadImage"); - var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); + var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); - Profiler.EndSample(); - Profiler.BeginSample("ConvertColor32ToFloat4Job"); + Profiler.EndSample(); + Profiler.BeginSample("CratePrevTex"); - var covF4 = new ConvertColor32ToFloat4Job() { Souse = fullNATex, Target = fullNAF4Tex, }; + var tex2d = new Texture2D(canvasSize.x, canvasSize.y, TextureFormat.RGBA32, false); + tex2d.alphaIsTransparency = true; + tex2d.LoadRawTextureData(jobResult.GetResult); + EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); - var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 64, jobResult.GetHandle); - nextTaming(); - covF4Handle.Complete(); + Profiler.EndSample(); + Profiler.BeginSample("SetTexDataAndCompress"); - Profiler.EndSample(); - Profiler.BeginSample("CreateMip"); + tex2d.Apply(true, true); + importedImage.PreviewTexture = tex2d; - var mipMapCount = MipMapUtility.MipMapCountFrom(Mathf.Max(canvasSize.x, canvasSize.y), 1024); - var mipJobResult = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount); - nextTaming2(); - _ = mipJobResult.GetResult; + Profiler.EndSample(); + Profiler.EndSample(); + } + } + } + else + { + using (var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + using (var fullNAF4Tex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + { + foreach (var importedImage in _tttImportedImages) + { + Profiler.BeginSample("CreatePreview -" + importedImage.name); + Profiler.BeginSample("LoadImage"); - Profiler.EndSample(); + var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); - Texture2D tex2d = null; - nextTaming = () => - { - Profiler.BeginSample("nextTamingCall"); - Profiler.BeginSample("CratePrevTex"); + Profiler.EndSample(); + Profiler.BeginSample("ConvertColor32ToFloat4Job"); - tex2d = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); - tex2d.alphaIsTransparency = true; + var covF4 = new ConvertColor32ToFloat4Job() { Souse = fullNATex, Target = fullNAF4Tex, }; + var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 32, jobResult.GetHandle); - tex2d.LoadRawTextureData(mipJobResult.GetResult[mipMapCount]); - EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); + Profiler.EndSample(); + Profiler.BeginSample("CreateMip"); - Profiler.EndSample(); - Profiler.EndSample(); - }; - nextTaming2 = () => - { - Profiler.BeginSample("nextTamingCall2"); - Profiler.BeginSample("SetTexDataAndCompress"); + var mipMapCount = MipMapUtility.MipMapCountFrom(Mathf.Max(canvasSize.x, canvasSize.y), 1024); + covF4Handle.Complete(); + var mipJobResult = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount); - tex2d.Apply(true, true); - importedImage.PreviewTexture = tex2d; + Profiler.EndSample(); + Profiler.BeginSample("CratePrevTex"); - foreach (var n2da in mipJobResult.GetResult.Skip(1)) { n2da.Dispose(); } + var tex2d = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); + tex2d.alphaIsTransparency = true; - Profiler.EndSample(); - Profiler.EndSample(); - }; + tex2d.LoadRawTextureData(mipJobResult.GetResult[mipMapCount]); + EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); - Profiler.EndSample(); - } + Profiler.EndSample(); + Profiler.BeginSample("SetTexDataAndCompress"); - nextTaming(); - nextTaming2(); + tex2d.Apply(true, true); + importedImage.PreviewTexture = tex2d; - fullNAF4Tex.Dispose(); - fullNATex.Dispose(); + foreach (var n2da in mipJobResult.GetResult.Skip(1)) { n2da.Dispose(); } + Profiler.EndSample(); + Profiler.EndSample(); + } + } + } // var texManager = new TextureManager(true); // var canvasResult = _multiLayerImageCanvas.EvaluateCanvas(texManager, 1024); diff --git a/Editor/Unsafe/UnsafeBitMapDataUtility.cs b/Editor/Unsafe/UnsafeBitMapDataUtility.cs deleted file mode 100644 index 1179c3ba..00000000 --- a/Editor/Unsafe/UnsafeBitMapDataUtility.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Drawing.Imaging; -using Unity.Collections; -using UnityEngine; - -namespace net.rs64.TexTransTool.Unsafe -{ - internal static class UnsafeBitMapDataUtility - { - - public static unsafe void WriteBitMapData(NativeArray argbValue, BitmapData bmd) - { - if (bmd.PixelFormat != PixelFormat.Format32bppArgb) { throw new ArgumentException("BitmapDataのピクセルフォーマットが 32bppArgb 以外は非対応です。"); } - if (argbValue.Length != bmd.Height * bmd.Width * 4) { throw new ArgumentException("BitmapDataのサイズとNativeArrayの長さが一致しません。"); } - var to = new Span((void*)bmd.Scan0, argbValue.Length); - Span form = argbValue; - form.CopyTo(to); - } - - - } - - -} \ No newline at end of file diff --git a/Editor/net.rs64.tex-trans-tool.editor.asmdef b/Editor/net.rs64.tex-trans-tool.editor.asmdef index 8957e746..d452f787 100644 --- a/Editor/net.rs64.tex-trans-tool.editor.asmdef +++ b/Editor/net.rs64.tex-trans-tool.editor.asmdef @@ -4,7 +4,7 @@ "references": [ "net.rs64.tex-trans-core", "net.rs64.tex-trans-tool.runtime", - "net.rs64.tex-trans-tool.editor.unsafe", + "net.rs64.tex-trans-core.unsafe", "net.rs64.multi-layer-image-parser", "nadena.dev.ndmf", "Unity.Collections", @@ -33,4 +33,4 @@ } ], "noEngineReferences": false -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/net.rs64.multi-layer-image-parser.asmdef b/MultiLayerImage-Parser/net.rs64.multi-layer-image-parser.asmdef index ba4571ba..1cb8ed0a 100644 --- a/MultiLayerImage-Parser/net.rs64.multi-layer-image-parser.asmdef +++ b/MultiLayerImage-Parser/net.rs64.multi-layer-image-parser.asmdef @@ -2,7 +2,8 @@ "name": "net.rs64.multi-layer-image-parser", "rootNamespace": "", "references": [ - "net.rs64.tex-trans-core" + "net.rs64.tex-trans-core", + "net.rs64.tex-trans-core.unsafe" ], "includePlatforms": [], "excludePlatforms": [], @@ -13,4 +14,4 @@ "defineConstraints": [], "versionDefines": [], "noEngineReferences": false -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 5fa16a15..e7d1085a 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -8,6 +8,7 @@ using Unity.Jobs; using Unity.Mathematics; using UnityEngine; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -19,11 +20,14 @@ internal class PSDImportedRasterImage : TTTImportedImage internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) { + Profiler.BeginSample("Init"); var nativeArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); - var initJob = new InitializeJob() { Target = nativeArray, Value = new Color32(0, 0, 0, 0) }; - var handle = initJob.Schedule(nativeArray.Length, 1024); + TexTransCore.Unsafe.UnsafeNativeArrayClear.ClearMemory(nativeArray); + + Profiler.EndSample(); + Profiler.BeginSample("RLE"); Task>[] getImageTask = new Task>[4]; getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSouse, RasterImageData.RectTangle)); @@ -34,6 +38,9 @@ internal override JobResult> LoadImage(byte[] importSouse, var souseTexSize = new int2(RasterImageData.RectTangle.GetWidth(), RasterImageData.RectTangle.GetHeight()); var image = WeightTask(getImageTask).Result; + Profiler.EndSample(); + Profiler.BeginSample("OffsetJobSetUp"); + JobHandle offsetJobHandle; if (RasterImageData.A != null) @@ -49,7 +56,7 @@ internal override JobResult> LoadImage(byte[] importSouse, SouseSize = souseTexSize, TargetSize = canvasSize, }; - offsetJobHandle = offset.Schedule(image[0].Length, 64, handle); + offsetJobHandle = offset.Schedule(image[0].Length, 0); } else { @@ -63,9 +70,10 @@ internal override JobResult> LoadImage(byte[] importSouse, SouseSize = souseTexSize, TargetSize = canvasSize, }; - offsetJobHandle = offset.Schedule(image[0].Length, 64, handle); + offsetJobHandle = offset.Schedule(image[0].Length, 0); } + Profiler.EndSample(); return new(nativeArray, offsetJobHandle, () => @@ -149,12 +157,6 @@ public static void Init() internal static Material s_tempMat; internal const string SHADER_KEYWORD_SRGB = "COLOR_SPACE_SRGB"; - internal struct InitializeJob : IJobParallelFor - { - public Color32 Value; - [WriteOnly] public NativeArray Target; - public void Execute(int index) { Target[index] = Value; } - } [BurstCompile] internal struct OffsetMoveAlphaJob : IJobParallelFor { diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index d38b69de..1a1d3a3d 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -5,6 +5,7 @@ using Unity.Jobs; using Unity.Mathematics; using UnityEngine; +using UnityEngine.Profiling; namespace net.rs64.TexTransTool.MultiLayerImage { internal class PSDImportedRasterMaskImage : TTTImportedImage @@ -15,22 +16,25 @@ internal class PSDImportedRasterMaskImage : TTTImportedImage internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) { + Profiler.BeginSample("Init"); var native2DArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); - - var initJob = new PSDImportedRasterImage.InitializeJob() - { - Target = native2DArray, - Value = new Color32(MaskImageData.DefaultValue, MaskImageData.DefaultValue, MaskImageData.DefaultValue, MaskImageData.DefaultValue) - }; + TexTransCore.Unsafe.UnsafeNativeArrayClear.ClearMemoryOnColor(native2DArray, MaskImageData.DefaultValue); - var initHandle = initJob.Schedule(native2DArray.Length, 64); + var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); var souseTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); + Profiler.EndSample(); + JobHandle offsetJobHandle; - if ((MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0) { return new(native2DArray, initHandle); } + if ((MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0) { return new(native2DArray); } + + Profiler.BeginSample("RLE"); var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle); + + Profiler.EndSample(); + Profiler.BeginSample("OffsetMoveAlphaJobSetUp"); + var offset = new PSDImportedRasterImage.OffsetMoveAlphaJob() { Target = native2DArray, @@ -42,8 +46,9 @@ internal override JobResult> LoadImage(byte[] importSouse, SouseSize = souseTexSize, TargetSize = canvasSize, }; - offsetJobHandle = offset.Schedule(data.Length, 64, initHandle); + offsetJobHandle = offset.Schedule(data.Length, 64); + Profiler.EndSample(); return new(native2DArray, offsetJobHandle, () => { data.Dispose(); }); } internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) diff --git a/Runtime/net.rs64.tex-trans-tool.runtime.asmdef b/Runtime/net.rs64.tex-trans-tool.runtime.asmdef index 22da4d0b..5d2770e3 100644 --- a/Runtime/net.rs64.tex-trans-tool.runtime.asmdef +++ b/Runtime/net.rs64.tex-trans-tool.runtime.asmdef @@ -3,6 +3,7 @@ "rootNamespace": "", "references": [ "net.rs64.tex-trans-core", + "net.rs64.tex-trans-core.unsafe", "net.rs64.multi-layer-image-parser", "nadena.dev.ndmf", "Unity.Burst", @@ -28,4 +29,4 @@ } ], "noEngineReferences": false -} \ No newline at end of file +} diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 3388dd8e..b1b4c414 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -62,7 +62,7 @@ public static JobResult[]> GenerateAverageMips(NativeArray(NativeArray array) where T : struct + { + UnsafeUtility.MemClear(array.GetUnsafePtr(), (long)array.Length * UnsafeUtility.SizeOf()); + } + public static unsafe void ClearMemoryOnColor(NativeArray array, byte val) + { + UnsafeUtility.MemSet(array.GetUnsafePtr(), val, (long)array.Length * UnsafeUtility.SizeOf()); + } + + } + + +} diff --git a/Editor/Unsafe/UnsafeBitMapDataUtility.cs.meta b/TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta similarity index 83% rename from Editor/Unsafe/UnsafeBitMapDataUtility.cs.meta rename to TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta index 64e2738f..a8cfc3c5 100644 --- a/Editor/Unsafe/UnsafeBitMapDataUtility.cs.meta +++ b/TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b0bed243e272cf840aadcc02c0a3c9e1 +guid: 1d63e5e07fc4950498a6084f6ca588d4 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Unsafe/csc.rsp b/TexTransCore/Unsafe/csc.rsp similarity index 100% rename from Editor/Unsafe/csc.rsp rename to TexTransCore/Unsafe/csc.rsp diff --git a/Editor/Unsafe/csc.rsp.meta b/TexTransCore/Unsafe/csc.rsp.meta similarity index 100% rename from Editor/Unsafe/csc.rsp.meta rename to TexTransCore/Unsafe/csc.rsp.meta diff --git a/Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef b/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef similarity index 86% rename from Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef rename to TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef index 179b1add..31dcb793 100644 --- a/Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef +++ b/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef @@ -1,5 +1,5 @@ { - "name": "net.rs64.tex-trans-tool.editor.unsafe", + "name": "net.rs64.tex-trans-core.unsafe", "rootNamespace": "", "references": [ ], @@ -15,4 +15,4 @@ "versionDefines": [ ], "noEngineReferences": false -} \ No newline at end of file +} diff --git a/Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef.meta b/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef.meta similarity index 100% rename from Editor/Unsafe/net.rs64.tex-trans-tool.editor.unsafe.asmdef.meta rename to TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef.meta diff --git a/TexTransCore/net.rs64.tex-trans-core.asmdef b/TexTransCore/net.rs64.tex-trans-core.asmdef index 0f26583f..8dfc7476 100644 --- a/TexTransCore/net.rs64.tex-trans-core.asmdef +++ b/TexTransCore/net.rs64.tex-trans-core.asmdef @@ -2,6 +2,7 @@ "name": "net.rs64.tex-trans-core", "rootNamespace": "", "references": [ + "net.rs64.tex-trans-core.unsafe", "Unity.Burst", "Unity.Mathematics" ], @@ -14,4 +15,4 @@ "defineConstraints": [], "versionDefines": [], "noEngineReferences": false -} \ No newline at end of file +} From 0be00d1860bbda18b05f3e6496a48188a8d9b63b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 17 Apr 2024 01:37:41 +0900 Subject: [PATCH 082/208] optimize: remove convert Color32ToFloat4 --- .../MultiLayerImageImporter.cs | 130 ++++-------------- .../TexTransToolPSDImporter.cs | 2 +- .../PSD/Parsers/ChannelImageDataParser.cs | 6 +- .../Improted/PSD/PSDImportedRasterImage.cs | 6 +- .../PSD/PSDImportedRasterMaskImage.cs | 2 +- TexTransCore/MipMap/MipMapUtility.cs | 74 +++++----- ...ayClear.cs => UnsafeNativeArrayUtility.cs} | 3 +- ....meta => UnsafeNativeArrayUtility.cs.meta} | 0 8 files changed, 70 insertions(+), 153 deletions(-) rename TexTransCore/Unsafe/{UnsafeNativeArrayClear.cs => UnsafeNativeArrayUtility.cs} (87%) rename TexTransCore/Unsafe/{UnsafeNativeArrayClear.cs.meta => UnsafeNativeArrayUtility.cs.meta} (100%) diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index a54535bf..2dfbbfb3 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -199,113 +199,61 @@ internal void CopyFromData(AbstractLayer abstractLayer, AbstractLayerData abstra internal void CreatePreview() { var canvasSize = new int2(_tttImportedCanvasDescription.Width, _tttImportedCanvasDescription.Height); - if (math.max(canvasSize.x, canvasSize.y) <= 1024) + + using (var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) { - using (var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) + foreach (var importedImage in _tttImportedImages) { - foreach (var importedImage in _tttImportedImages) - { - Profiler.BeginSample("CreatePreview -" + importedImage.name); - Profiler.BeginSample("LoadImage"); + Profiler.BeginSample("CreatePreview -" + importedImage.name); + Profiler.BeginSample("LoadImage"); - var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); + var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); - Profiler.EndSample(); + Profiler.EndSample(); + Texture2D tex2d; + if (math.max(canvasSize.x, canvasSize.y) <= 1024) + { Profiler.BeginSample("CratePrevTex"); - var tex2d = new Texture2D(canvasSize.x, canvasSize.y, TextureFormat.RGBA32, false); + tex2d = new Texture2D(canvasSize.x, canvasSize.y, TextureFormat.RGBA32, false); tex2d.alphaIsTransparency = true; tex2d.LoadRawTextureData(jobResult.GetResult); EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); Profiler.EndSample(); - Profiler.BeginSample("SetTexDataAndCompress"); - - tex2d.Apply(true, true); - importedImage.PreviewTexture = tex2d; - - Profiler.EndSample(); - Profiler.EndSample(); } - } - } - else - { - using (var fullNATex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) - using (var fullNAF4Tex = new NativeArray(canvasSize.x * canvasSize.y, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) - { - foreach (var importedImage in _tttImportedImages) + else { - Profiler.BeginSample("CreatePreview -" + importedImage.name); - Profiler.BeginSample("LoadImage"); - - var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); - - Profiler.EndSample(); - Profiler.BeginSample("ConvertColor32ToFloat4Job"); - - var covF4 = new ConvertColor32ToFloat4Job() { Souse = fullNATex, Target = fullNAF4Tex, }; - var covF4Handle = covF4.Schedule(fullNAF4Tex.Length, 32, jobResult.GetHandle); - - Profiler.EndSample(); - Profiler.BeginSample("CreateMip"); + Profiler.BeginSample("CreateMipDispatch"); var mipMapCount = MipMapUtility.MipMapCountFrom(Mathf.Max(canvasSize.x, canvasSize.y), 1024); - covF4Handle.Complete(); - var mipJobResult = MipMapUtility.GenerateAverageMips(fullNAF4Tex, canvasSize, mipMapCount); + _ = jobResult.GetResult; + var mipJobResult = MipMapUtility.GenerateAverageMips(fullNATex, canvasSize, mipMapCount); Profiler.EndSample(); Profiler.BeginSample("CratePrevTex"); - var tex2d = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); + tex2d = new Texture2D(1024, 1024, TextureFormat.RGBA32, false); tex2d.alphaIsTransparency = true; tex2d.LoadRawTextureData(mipJobResult.GetResult[mipMapCount]); EditorUtility.CompressTexture(tex2d, TextureFormat.DXT5, 100); - - Profiler.EndSample(); - Profiler.BeginSample("SetTexDataAndCompress"); - - tex2d.Apply(true, true); - importedImage.PreviewTexture = tex2d; - foreach (var n2da in mipJobResult.GetResult.Skip(1)) { n2da.Dispose(); } Profiler.EndSample(); - Profiler.EndSample(); } - } - } + Profiler.BeginSample("SetTexDataAndCompress"); - // var texManager = new TextureManager(true); - // var canvasResult = _multiLayerImageCanvas.EvaluateCanvas(texManager, 1024); - // texManager.DestroyTextures(); + tex2d.Apply(true, true); + importedImage.PreviewTexture = tex2d; - // var resultTex = canvasResult.CopyTexture2D(overrideUseMip: true); - // EditorUtility.CompressTexture(resultTex, TextureFormat.DXT5, 100); - // resultTex.name = "TTT-CanvasPreviewResult"; - // _ctx.AddObjectToAsset(resultTex.name, resultTex); - // RenderTexture.ReleaseTemporary(canvasResult); - - // var quadMesh = GameObject.CreatePrimitive(PrimitiveType.Quad); - // var mesh = quadMesh.GetComponent().sharedMesh; - // GameObject.DestroyImmediate(quadMesh); - - // var prevGo = new GameObject("TTT-CanvasPreview"); - // var hideFlagPatch = prevGo.AddComponent(); - // prevGo.tag ="EditorOnly"; - // var quad = prevGo.AddComponent(); - - // quad.transform.SetParent(_multiLayerImageCanvas.transform, false); - // quad.sharedMesh = mesh; - // quad.sharedMaterial = new Material(Shader.Find("Unlit/Texture")) { mainTexture = resultTex, name = "TTT-CanvasPreviewResult-Material" }; - // quad.transform.localRotation = Quaternion.Euler(new Vector3(-20f, 60f, 0f)); - // quad.transform.localScale = new Vector3(-0.002f, 0.002f, -0.002f); - // quad.localBounds = new Bounds(Vector3.zero, new Vector3(0.31f, 0.31f, 0.001f) * 2f); + Profiler.EndSample(); + Profiler.EndSample(); + } - // _ctx.AddObjectToAsset("TTT-CanvasPreviewResult-Material", quad.sharedMaterial); + } } public void SaveSubAsset() @@ -329,37 +277,5 @@ public void SaveSubAsset() _ctx.AddObjectToAsset(_layerAtPath[image] + "/" + image.PreviewTexture.name, image.PreviewTexture); } } - - [BurstCompile] - internal struct ConvertColor32ToFloat4Job : IJobParallelFor - { - [ReadOnly] public NativeArray Souse; - [WriteOnly] public NativeArray Target; - public void Execute(int index) - { - Target[index] = new float4( - Souse[index].r / (float)byte.MaxValue, - Souse[index].g / (float)byte.MaxValue, - Souse[index].b / (float)byte.MaxValue, - Souse[index].a / (float)byte.MaxValue - ); - } - } - - [BurstCompile] - internal struct ConvertFloat4ToColor32Job : IJobParallelFor - { - [ReadOnly] public NativeArray Souse; - [WriteOnly] public NativeArray Target; - public void Execute(int index) - { - Target[index] = new Color32( - (byte)Mathf.Round(Souse[index].x * (float)byte.MaxValue), - (byte)Mathf.Round(Souse[index].y * (float)byte.MaxValue), - (byte)Mathf.Round(Souse[index].z * (float)byte.MaxValue), - (byte)Mathf.Round(Souse[index].w * (float)byte.MaxValue) - ); - } - } } } diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index 1cb4ab9c..1f65fa65 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -32,7 +32,7 @@ public override void OnImportAsset(AssetImportContext ctx) Profiler.EndSample(); Profiler.BeginSample("LowLevel"); - var lowPSDData = PSDLowLevelParser.Parse(assetPath); + var lowPSDData = PSDLowLevelParser.Parse(psdBytes); Profiler.EndSample(); Profiler.BeginSample("LowLevel"); diff --git a/MultiLayerImage-Parser/PSD/Parsers/ChannelImageDataParser.cs b/MultiLayerImage-Parser/PSD/Parsers/ChannelImageDataParser.cs index 8abf46a0..2f24b506 100644 --- a/MultiLayerImage-Parser/PSD/Parsers/ChannelImageDataParser.cs +++ b/MultiLayerImage-Parser/PSD/Parsers/ChannelImageDataParser.cs @@ -162,10 +162,6 @@ private static void ParseRLECompressedWidthLine(Span writeWidthLine, Span< writeWidthLine.Slice(writePos, count).Fill(value); writePos += count; - // for (; writeRange > writePos; writePos += 1) - // { - // writeWidthLine[writePos] = value; - // } } } @@ -176,4 +172,4 @@ private static void ParseRLECompressedWidthLine(Span writeWidthLine, Span< } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index e7d1085a..e855a3eb 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -24,7 +24,7 @@ internal override JobResult> LoadImage(byte[] importSouse, var nativeArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); - TexTransCore.Unsafe.UnsafeNativeArrayClear.ClearMemory(nativeArray); + TexTransCore.Unsafe.UnsafeNativeArrayUtility.ClearMemory(nativeArray); Profiler.EndSample(); Profiler.BeginSample("RLE"); @@ -56,7 +56,7 @@ internal override JobResult> LoadImage(byte[] importSouse, SouseSize = souseTexSize, TargetSize = canvasSize, }; - offsetJobHandle = offset.Schedule(image[0].Length, 0); + offsetJobHandle = offset.Schedule(image[0].Length, 32); } else { @@ -70,7 +70,7 @@ internal override JobResult> LoadImage(byte[] importSouse, SouseSize = souseTexSize, TargetSize = canvasSize, }; - offsetJobHandle = offset.Schedule(image[0].Length, 0); + offsetJobHandle = offset.Schedule(image[0].Length, 32); } Profiler.EndSample(); diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 1a1d3a3d..0f3aa673 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -18,7 +18,7 @@ internal override JobResult> LoadImage(byte[] importSouse, { Profiler.BeginSample("Init"); var native2DArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - TexTransCore.Unsafe.UnsafeNativeArrayClear.ClearMemoryOnColor(native2DArray, MaskImageData.DefaultValue); + TexTransCore.Unsafe.UnsafeNativeArrayUtility.ClearMemoryOnColor(native2DArray, MaskImageData.DefaultValue); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); var souseTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index b1b4c414..1cf9f2f2 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -35,9 +35,9 @@ public static bool GenerateMips(RenderTexture renderTexture, DownScalingAlgorism return result; } - public static JobResult[]> GenerateAverageMips(NativeArray tex, int2 texSize, int GenerateCount) + public static JobResult[]> GenerateAverageMips(NativeArray tex, int2 texSize, int GenerateCount) { - var mipMaps = new NativeArray[GenerateCount + 1]; + var mipMaps = new NativeArray[GenerateCount + 1]; mipMaps[0] = tex; var handle = default(JobHandle); @@ -51,9 +51,9 @@ public static JobResult[]> GenerateAverageMips(NativeArray(up.Length / 4, Unity.Collections.Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + var down = mipMaps[i] = new NativeArray(up.Length / 4, Unity.Collections.Allocator.TempJob, NativeArrayOptions.UninitializedMemory); - var ave = new AverageJob() + var ave = new AverageJobByte() { RTex = up, RTexSize = upSize, @@ -62,7 +62,7 @@ public static JobResult[]> GenerateAverageMips(NativeArray RTex; - [WriteOnly] public NativeArray WTex; + [ReadOnly] public NativeArray RTex; + [WriteOnly] public NativeArray WTex; public int2 PixelRatio; public int2 RTexSize; public int2 WTexSize; @@ -137,20 +137,12 @@ public void Execute(int index) Average(CovInt2(index, WTexSize.x)); } - float3 ChakeNaN(float3 val, float3 replase) - { - return float3( - isnan(val.x) ? replase.x : val.x, - isnan(val.y) ? replase.y : val.y, - isnan(val.z) ? replase.z : val.z - ); - } void Average(int2 id) { - float3 wcol = float3(0, 0, 0); - float3 col = float3(0, 0, 0); - float alpha = 0; + int3 wcol = int3(0, 0, 0); + int3 col = int3(0, 0, 0); + int alpha = 0; int count = 0; int2 readPosOffset = id.xy * PixelRatio; @@ -158,28 +150,40 @@ void Average(int2 id) { for (int x = 0; PixelRatio.x > x; x += 1) { - float4 rCol = RTex[CovInt(readPosOffset + int2(x, y), RTexSize.x)]; - wcol += rCol.xyz * rCol.w; - col += rCol.xyz; - alpha += rCol.w; + var rCol = RTex[CovInt(readPosOffset + int2(x, y), RTexSize.x)]; + wcol.x += rCol.r * rCol.a; + wcol.y += rCol.g * rCol.a; + wcol.z += rCol.b * rCol.a; + + col.x += rCol.r; + col.y += rCol.g; + col.z += rCol.b; + + alpha += rCol.a; count += 1; } } - wcol /= alpha; - col /= count; - WTex[CovInt(id.xy, WTexSize.x)] = float4(ChakeNaN(wcol, col), alpha / count); - } - public static int2 CovInt2(int i, int width) - { - return new int2(i % width, i / width); - } - public static int CovInt(int2 i, int width) - { - return i.y * width + i.x; + wcol.x = (int)round(wcol.x / (float)alpha); + wcol.y = (int)round(wcol.y / (float)alpha); + wcol.z = (int)round(wcol.z / (float)alpha); + col.x = (int)round(col.x / (float)count); + col.y = (int)round(col.y / (float)count); + col.z = (int)round(col.z / (float)count); + var resAlpha = (byte)round(alpha / (float)count); + var writeCol = alpha != 0 ? wcol : col; + var writeIndex = CovInt(id.xy, WTexSize.x); + WTex[writeIndex] = new Color32((byte)writeCol.x, (byte)writeCol.y, (byte)writeCol.z, resAlpha); } } - + public static int2 CovInt2(int i, int width) + { + return new int2(i % width, i / width); + } + public static int CovInt(int2 i, int width) + { + return i.y * width + i.x; + } } public enum DownScalingAlgorism { diff --git a/TexTransCore/Unsafe/UnsafeNativeArrayClear.cs b/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs similarity index 87% rename from TexTransCore/Unsafe/UnsafeNativeArrayClear.cs rename to TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs index ed36e6f5..cdabb8cc 100644 --- a/TexTransCore/Unsafe/UnsafeNativeArrayClear.cs +++ b/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs @@ -1,12 +1,13 @@ using System; using System.Drawing.Imaging; +using System.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine; namespace net.rs64.TexTransCore.Unsafe { - internal static class UnsafeNativeArrayClear + internal static class UnsafeNativeArrayUtility { public static unsafe void ClearMemory(NativeArray array) where T : struct { diff --git a/TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta b/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs.meta similarity index 100% rename from TexTransCore/Unsafe/UnsafeNativeArrayClear.cs.meta rename to TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs.meta From 71f11db338234e98f7ff49890bca882fc707b24d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 19 Apr 2024 20:57:32 +0900 Subject: [PATCH 083/208] feat: Clip Additional Blending --- .../BlendTexture/ShaderAsset/BlendColor.hlsl | 24 +++++++++++-------- TexTransCore/BlendTexture/TextureBlend.cs | 4 ++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl index a58727b6..73f75215 100644 --- a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl +++ b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl @@ -4,7 +4,7 @@ // https://web.archive.org/web/20230211165421/http://www.deepskycolors.com/archivo/2010/04/21/formulas-for-Photoshop-blending-modes.html // http://www.simplefilter.de/en/basics/mixmods.html // https://odashi.hatenablog.com/entry/20110921/1316610121 -// https://qiita.com/kerupani129/items/4bf75d9f44a5b926df58#31-%E7%94%BB%E5%83%8F%E5%87%A6%E7%90%86%E3%82%BD%E3%83%95%E3%83%88%E3%82%A6%E3%82%A7%E3%82%A2%E3%81%AB%E3%82%88%E3%81%A3%E3%81%A6%E3%81%AF%E7%90%86%E8%AB%96%E5%BC%8F%E3%81%A8%E4%B8%80%E8%87%B4%E3%81%97%E3%81%AA%E3%81%84 +// https://qiita.com/kerupani129/items/4bf75d9f44a5b926df58 #include "./SetSL.hlsl" @@ -15,9 +15,13 @@ float4 AlphaBlending(float4 BaseColor,float4 AddColor,float3 BlendColor) float BaseRatio = (1 - AddColor.a) * BaseColor.a; float Alpha = BlendRatio + AddRatio + BaseRatio; +#if ClipExclusion || ClipAddition || ClipAdditionGlow || ClipColorDodgeGlow + float3 ResultColor = (AddColor.a * BlendColor + BaseRatio * BaseColor.rgb) / Alpha; + ResultColor = (BaseColor.a * ResultColor + AddRatio * AddColor.rgb) / Alpha; +#else float3 ResultColor = (BlendColor * BlendRatio) + (AddColor.rgb * AddRatio) + (BaseColor.rgb * BaseRatio); ResultColor /= Alpha; - +#endif return Alpha != 0 ? float4(ResultColor, Alpha) : float4(0, 0, 0, 0); } @@ -28,6 +32,8 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { float3 Bcol = BaseColor.rgb; float3 Acol = AddColor.rgb; + float3 Al = BaseColor.a; + float3 Bl = AddColor.a; float3 Addc = Bcol + Acol; @@ -67,7 +73,7 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { // BlendColor = saturate(Acol > 0.5 ? Bcol + 2 * (Acol - 0.5) : Bcol + 2.0 * Acol - 1.0); #elif Divide BlendColor = Acol == 0 ? 1 : Bcol / Acol; -#elif Addition +#elif Addition || ClipAddition BlendColor = saturate(Addc); #elif Subtract BlendColor = Bcol - Acol; @@ -85,7 +91,7 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { BlendColor = SetLum(Acol,GetLum(Bcol)); #elif Luminosity BlendColor = SetLum(Bcol,GetLum(Acol)); -#elif Exclusion +#elif Exclusion || ClipExclusion BlendColor = Bcol + Acol - 2 * Bcol * Acol; #elif DarkenColorOnly BlendColor = Bsum > Asum ? Acol : Bcol; @@ -95,12 +101,10 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { BlendColor = Acol > 0.5 ? max(Bcol, 2.0 * Acol - 1.0) : min(Bcol, 2.0 * Acol); #elif HardMix BlendColor = ( Acol + Bcol ) > 1.0 ; -#elif AdditionGlow - BlendColor = Bcol + (Acol * AddColor.a); - return float4(BlendColor,AlphaBlending(BaseColor,AddColor,BlendColor).a); -#elif ColorDodgeGlow - BlendColor = Bcol / (1.0 - (Acol * AddColor.a)); - return float4(BlendColor,AlphaBlending(BaseColor,AddColor,BlendColor).a); +#elif AdditionGlow || ClipAdditionGlow + BlendColor = Bcol * Al + Acol * Al; +#elif ColorDodgeGlow || ClipColorDodgeGlow + BlendColor = Bcol / (1.0 - Acol * Al); #endif return AlphaBlending(BaseColor,AddColor,BlendColor); diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index 5ff03b97..da1d9b98 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -106,8 +106,11 @@ public static void BlendShadersInit() {"Screen",stdBlendShader},//スクリーン {"ColorDodge",stdBlendShader},//覆い焼きカラー {"ColorDodgeGlow",stdBlendShader},//覆い焼き(発光) + {"ClipColorDodgeGlow",stdBlendShader},//クリスタ覆い焼き(発光) {"Addition",stdBlendShader},//加算-覆い焼き(リニア) + {"ClipAddition",stdBlendShader},//クリスタ加算 {"AdditionGlow",stdBlendShader},//加算(発光) + {"ClipAdditionGlow",stdBlendShader},//クリスタ加算(発光) {"LightenOnly",stdBlendShader},//比較(明) {"LightenColorOnly",stdBlendShader},//カラー比較(明) @@ -123,6 +126,7 @@ public static void BlendShadersInit() //算術系 {"Difference",stdBlendShader},//差の絶対値 {"Exclusion",stdBlendShader},//除外 + {"ClipExclusion", stdBlendShader},//クリスタ除外 {"Subtract",stdBlendShader},//減算 {"Divide",stdBlendShader},//除算 From 7ba82d12012cd13bdd46710f85126901d681215f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 19 Apr 2024 20:58:52 +0900 Subject: [PATCH 084/208] fix: AdditionGlow formula --- TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl index 73f75215..60fccb40 100644 --- a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl +++ b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl @@ -102,7 +102,7 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { #elif HardMix BlendColor = ( Acol + Bcol ) > 1.0 ; #elif AdditionGlow || ClipAdditionGlow - BlendColor = Bcol * Al + Acol * Al; + BlendColor = Bcol + Acol * Al; #elif ColorDodgeGlow || ClipColorDodgeGlow BlendColor = Bcol / (1.0 - Acol * Al); #endif From fc161758b5bedf83d894335f8dd620ccd37e59f3 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 19 Apr 2024 21:30:07 +0900 Subject: [PATCH 085/208] chore: move hierarchy for "Clip" --- .../BlendTexture/ShaderAsset/BlendColor.hlsl | 10 +++++----- .../BlendTexture/ShaderAsset/BlendTexture.shader | 2 +- TexTransCore/BlendTexture/TextureBlend.cs | 12 ++++++++---- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl index 60fccb40..b68b5580 100644 --- a/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl +++ b/TexTransCore/BlendTexture/ShaderAsset/BlendColor.hlsl @@ -15,7 +15,7 @@ float4 AlphaBlending(float4 BaseColor,float4 AddColor,float3 BlendColor) float BaseRatio = (1 - AddColor.a) * BaseColor.a; float Alpha = BlendRatio + AddRatio + BaseRatio; -#if ClipExclusion || ClipAddition || ClipAdditionGlow || ClipColorDodgeGlow +#if Clip_Exclusion || Clip_Addition || Clip_AdditionGlow || Clip_ColorDodgeGlow float3 ResultColor = (AddColor.a * BlendColor + BaseRatio * BaseColor.rgb) / Alpha; ResultColor = (BaseColor.a * ResultColor + AddRatio * AddColor.rgb) / Alpha; #else @@ -73,7 +73,7 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { // BlendColor = saturate(Acol > 0.5 ? Bcol + 2 * (Acol - 0.5) : Bcol + 2.0 * Acol - 1.0); #elif Divide BlendColor = Acol == 0 ? 1 : Bcol / Acol; -#elif Addition || ClipAddition +#elif Addition || Clip_Addition BlendColor = saturate(Addc); #elif Subtract BlendColor = Bcol - Acol; @@ -91,7 +91,7 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { BlendColor = SetLum(Acol,GetLum(Bcol)); #elif Luminosity BlendColor = SetLum(Bcol,GetLum(Acol)); -#elif Exclusion || ClipExclusion +#elif Exclusion || Clip_Exclusion BlendColor = Bcol + Acol - 2 * Bcol * Acol; #elif DarkenColorOnly BlendColor = Bsum > Asum ? Acol : Bcol; @@ -101,9 +101,9 @@ float4 ColorBlend(float4 BaseColor, float4 AddColor) { BlendColor = Acol > 0.5 ? max(Bcol, 2.0 * Acol - 1.0) : min(Bcol, 2.0 * Acol); #elif HardMix BlendColor = ( Acol + Bcol ) > 1.0 ; -#elif AdditionGlow || ClipAdditionGlow +#elif AdditionGlow || Clip_AdditionGlow BlendColor = Bcol + Acol * Al; -#elif ColorDodgeGlow || ClipColorDodgeGlow +#elif ColorDodgeGlow || Clip_ColorDodgeGlow BlendColor = Bcol / (1.0 - Acol * Al); #endif diff --git a/TexTransCore/BlendTexture/ShaderAsset/BlendTexture.shader b/TexTransCore/BlendTexture/ShaderAsset/BlendTexture.shader index 8d15e0ff..5d74ec80 100644 --- a/TexTransCore/BlendTexture/ShaderAsset/BlendTexture.shader +++ b/TexTransCore/BlendTexture/ShaderAsset/BlendTexture.shader @@ -15,7 +15,7 @@ Shader "Hidden/BlendTexture" HLSLPROGRAM #pragma vertex vert #pragma fragment frag - #pragma multi_compile_local_fragment Normal Dissolve Mul Screen Overlay HardLight SoftLight ColorDodge ColorBurn LinearBurn VividLight LinearLight Divide Addition Subtract Difference DarkenOnly LightenOnly Hue Saturation Color Luminosity AlphaLerp Exclusion DarkenColorOnly LightenColorOnly PinLight HardMix AdditionGlow ColorDodgeGlow NotBlend + #pragma multi_compile_local_fragment Normal Dissolve Mul Screen Overlay HardLight SoftLight ColorDodge ColorBurn LinearBurn VividLight LinearLight Divide Addition Subtract Difference DarkenOnly LightenOnly Hue Saturation Color Luminosity AlphaLerp Exclusion DarkenColorOnly LightenColorOnly PinLight HardMix AdditionGlow ColorDodgeGlow NotBlend Clip_Exclusion Clip_Addition Clip_AdditionGlow Clip_ColorDodgeGlow #pragma shader_feature_local_fragment KeepAlpha #include "UnityCG.cginc" diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index da1d9b98..15846d9f 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -90,6 +90,14 @@ public static void BlendShadersInit() var stdBlendShader = BlendTexShader; var stdBlendShaders = new Dictionary() { + + {"Clip/ColorDodgeGlow",stdBlendShader},//クリスタ覆い焼き(発光) + {"Clip/Addition",stdBlendShader},//クリスタ加算 + {"Clip/AdditionGlow",stdBlendShader},//クリスタ加算(発光) + + {"Clip/Exclusion", stdBlendShader},//クリスタ除外 + + //特殊な色合成をしない系 {"Normal",stdBlendShader},//通常 {"Dissolve",stdBlendShader},//ディザ合成 @@ -106,11 +114,8 @@ public static void BlendShadersInit() {"Screen",stdBlendShader},//スクリーン {"ColorDodge",stdBlendShader},//覆い焼きカラー {"ColorDodgeGlow",stdBlendShader},//覆い焼き(発光) - {"ClipColorDodgeGlow",stdBlendShader},//クリスタ覆い焼き(発光) {"Addition",stdBlendShader},//加算-覆い焼き(リニア) - {"ClipAddition",stdBlendShader},//クリスタ加算 {"AdditionGlow",stdBlendShader},//加算(発光) - {"ClipAdditionGlow",stdBlendShader},//クリスタ加算(発光) {"LightenOnly",stdBlendShader},//比較(明) {"LightenColorOnly",stdBlendShader},//カラー比較(明) @@ -126,7 +131,6 @@ public static void BlendShadersInit() //算術系 {"Difference",stdBlendShader},//差の絶対値 {"Exclusion",stdBlendShader},//除外 - {"ClipExclusion", stdBlendShader},//クリスタ除外 {"Subtract",stdBlendShader},//減算 {"Divide",stdBlendShader},//除算 From 0fdb8efe4ad6b918577ac5cafa414644c760b379 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 19 Apr 2024 22:41:43 +0900 Subject: [PATCH 086/208] feat: PSD ClipImportMode --- .../PSD/PSDHighLevelParser.cs | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs index e43b36d3..c7749ee5 100644 --- a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs +++ b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs @@ -23,7 +23,7 @@ namespace net.rs64.MultiLayerImage.Parser.PSD { internal static class PSDHighLevelParser { - public static PSDHighLevelData Parse(PSDLowLevelParser.PSDLowLevelData levelData) + public static PSDHighLevelData Parse(PSDLowLevelParser.PSDLowLevelData levelData, PSDImportMode? importMode = null) { var psd = new PSDHighLevelData { @@ -33,14 +33,51 @@ public static PSDHighLevelData Parse(PSDLowLevelParser.PSDLowLevelData levelData RootLayers = new List() }; + importMode ??= levelData.ImageResources.FindIndex(ir => ir.UniqueIdentifier == 1060) == -1 ? PSDImportMode.Clip : PSDImportMode.Photo; + var imageDataQueue = new Queue(levelData.LayerInfo.ChannelImageData); var imageRecordQueue = new Queue(levelData.LayerInfo.LayerRecords); ParseAsLayers(psd.RootLayers, imageRecordQueue, imageDataQueue); + ResolveBlendTypeKeyImportMode(psd.RootLayers, importMode.Value); + return psd; } + public enum PSDImportMode + { + Photo = 0, + Clip = 1, + } + + private static void ResolveBlendTypeKeyImportMode(List layers, PSDImportMode importMode) + { + switch (importMode) + { + case PSDImportMode.Clip: + { + foreach (var layer in layers) + { + if (s_clipBlendModeDict.TryGetValue(layer.BlendTypeKey, out var actualModeKey)) + { + layer.BlendTypeKey = actualModeKey; + } + if (layer is LayerFolderData layerFolderData) { ResolveBlendTypeKeyImportMode(layerFolderData.Layers, importMode); } + } + break; + } + } + } + + static Dictionary s_clipBlendModeDict = new() + { + {"ColorDodgeGlow", "Clip/ColorDodgeGlow"}, + {"Addition","Clip/Addition"}, + {"AdditionGlow","Clip/AdditionGlow"}, + {"Exclusion","Clip/Exclusion"}, + }; + private static void ParseAsLayers(List rootLayers, Queue imageRecordQueue, Queue imageDataQueue) { while (imageRecordQueue.Count != 0) From 409b9ea2d2606b47737fcc5bfd7de67a8220ad2c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 21 Apr 2024 14:31:23 +0900 Subject: [PATCH 087/208] fix: unsafe.asmdef --- .../Unsafe/net.rs64.tex-trans-core.unsafe.asmdef | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef b/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef index 31dcb793..71963024 100644 --- a/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef +++ b/TexTransCore/Unsafe/net.rs64.tex-trans-core.unsafe.asmdef @@ -1,18 +1,14 @@ { "name": "net.rs64.tex-trans-core.unsafe", "rootNamespace": "", - "references": [ - ], - "includePlatforms": [ - "Editor" - ], + "references": [], + "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": false, "defineConstraints": [], - "versionDefines": [ - ], + "versionDefines": [], "noEngineReferences": false -} +} \ No newline at end of file From ecfc2f46fd3c3f230eecb3c79152135bcc453788 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 21 Apr 2024 15:02:40 +0900 Subject: [PATCH 088/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 90776af4..5b53efa3 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -10,7 +10,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelector が追加されました (#422) - SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) - IslandCulling からのマイグレーションが追加されました (#422) -- TTT PSD Importer のプレビューの生成が大幅に高速化されました (#424) +- TTT PSD Importer のプレビューの生成が大幅に高速化されました (#424 #443) - AtlasTexture に アイランド詳細調整 が追加されました (#431) - IslandSelectorNOT と IslandRendererSelector が追加されました (#431) - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) @@ -26,6 +26,7 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Fixed - Library が存在しないときにも正しく TTT PSD Importer がインポートできるようになりました (#427) +- TTT PSD Importer が PSD の ImageResourceBlock を正しく読み込めるようになりました (#443) ### Deprecated From e8c4c0049525b36ce32863310dbcf25a02b0992d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 21 Apr 2024 15:11:11 +0900 Subject: [PATCH 089/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + CHANGELOG.md | 1 + 2 files changed, 2 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 90776af4..0330c571 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -15,6 +15,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelectorNOT と IslandRendererSelector が追加されました (#431) - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) - AtlasTexture に MaterialMargeGroup が追加されました (#432) +- ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) ### Changed diff --git a/CHANGELOG.md b/CHANGELOG.md index 391c11d2..b2c64370 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture 複数のマテリアルが衝突しないテクスチャを持つ場合に、同一のアイランドが割り当てられるようになりました (#431) - AtlasTexture が Scale Transition(Tiling) を使用しているマテリアルのテクスチャを逆補正する機能が追加されました (#431 #435) - NDMF環境でのビルドを行う場合、オブジェクトの置き換えの追跡を NDMF ObjectRegistry を使用するようになりました (#438) +- Clip系の合成モードが追加されました (#444) ### Changed From 793c98952d848f9e1a0e394d956e8ed101ef9771 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 21 Apr 2024 06:27:53 +0000 Subject: [PATCH 090/208] Update package.json v0.7.0-beta.3!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 695df371..ca720116 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.6.6", + "version": "0.7.0-beta.3", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From b7223379798a6b383db1f269decbd81a00f3c440 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 21 Apr 2024 06:29:03 +0000 Subject: [PATCH 091/208] Update package.json v0.7.0-beta.4!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c25e5418..bcf0083c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.2", + "version": "0.7.0-beta.4", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 3dd282c35550f06d44fc3a94e4cd5ea2c5551673 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 14:53:50 +0900 Subject: [PATCH 092/208] fix: RelativeScale is Infinity --- TexTransCore/Island/IslandUtility.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index 585f687d..543c130d 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -185,7 +185,7 @@ public static void IslandMoveUV(NativeArray uv, NativeArray(NativeArray uv, NativeArray Date: Mon, 22 Apr 2024 18:52:17 +0900 Subject: [PATCH 093/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80141526..5dcda584 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture で SubMesh よりも多くのマテリアルスロットが存在するメッシュで正しくアトラス化できない問題を修正 (#431) - AtlasTexture でサブメッシュを超えて同一の頂点を使用するメッシュを正しくアトラス化できない問題を修正 (#431) - AtlasTexture の「適用時に非アクティブなレンダラーを含める」が有効な時、非アクティブなレンダラーのマテリアルが選択肢に表示されない問題を修正 (#431) +- AtlasTexture で大きさが完全に 0 のアイランドが存在するメッシュの UV を正しく操作できていない問題を修正 (#446) ### Deprecated From b31d24b5324a96ca26e2a0f42c686d1b839cb2cc Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 19:35:10 +0900 Subject: [PATCH 094/208] feat: SubMeshIslandSelector --- Runtime/IslandSelect/SubMeshIslandSelector.cs | 29 +++++++++++++++++++ .../SubMeshIslandSelector.cs.meta | 11 +++++++ 2 files changed, 40 insertions(+) create mode 100644 Runtime/IslandSelect/SubMeshIslandSelector.cs create mode 100644 Runtime/IslandSelect/SubMeshIslandSelector.cs.meta diff --git a/Runtime/IslandSelect/SubMeshIslandSelector.cs b/Runtime/IslandSelect/SubMeshIslandSelector.cs new file mode 100644 index 00000000..1d1702aa --- /dev/null +++ b/Runtime/IslandSelect/SubMeshIslandSelector.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using UnityEngine; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public class SubMeshIslandSelector : AbstractIslandSelector + { + internal const string ComponentName = "TTT SubMeshIslandSelector"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + + public int SelectSubMeshIndex = 0; + + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + var bitArray = new BitArray(islands.Length); + + for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) + { + bitArray[islandIndex] = islandDescription[islandIndex].MaterialSlot == SelectSubMeshIndex; + } + + return bitArray; + } + } +} diff --git a/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta b/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta new file mode 100644 index 00000000..97d1628a --- /dev/null +++ b/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c6419f0aafead04489fb507069c6c25 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From f43598ed7abd1b46d7456aef771cfc436f31e04e Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 19:35:50 +0900 Subject: [PATCH 095/208] chore: rename OR and Renderer --- .../IslandSelect/{IslandSelectOR.cs => IslandSelectorOR.cs} | 2 +- .../{IslandSelectOR.cs.meta => IslandSelectorOR.cs.meta} | 0 .../{IslandRendererSelector.cs => RendererIslandSelector.cs} | 4 ++-- ...endererSelector.cs.meta => RendererIslandSelector.cs.meta} | 0 4 files changed, 3 insertions(+), 3 deletions(-) rename Runtime/IslandSelect/{IslandSelectOR.cs => IslandSelectorOR.cs} (94%) rename Runtime/IslandSelect/{IslandSelectOR.cs.meta => IslandSelectorOR.cs.meta} (100%) rename Runtime/IslandSelect/{IslandRendererSelector.cs => RendererIslandSelector.cs} (85%) rename Runtime/IslandSelect/{IslandRendererSelector.cs.meta => RendererIslandSelector.cs.meta} (100%) diff --git a/Runtime/IslandSelect/IslandSelectOR.cs b/Runtime/IslandSelect/IslandSelectorOR.cs similarity index 94% rename from Runtime/IslandSelect/IslandSelectOR.cs rename to Runtime/IslandSelect/IslandSelectorOR.cs index 5e69c719..b7f97a64 100644 --- a/Runtime/IslandSelect/IslandSelectOR.cs +++ b/Runtime/IslandSelect/IslandSelectorOR.cs @@ -7,7 +7,7 @@ namespace net.rs64.TexTransTool.IslandSelector { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class IslandSelectOR : AbstractIslandSelector + public class IslandSelectorOR : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; diff --git a/Runtime/IslandSelect/IslandSelectOR.cs.meta b/Runtime/IslandSelect/IslandSelectorOR.cs.meta similarity index 100% rename from Runtime/IslandSelect/IslandSelectOR.cs.meta rename to Runtime/IslandSelect/IslandSelectorOR.cs.meta diff --git a/Runtime/IslandSelect/IslandRendererSelector.cs b/Runtime/IslandSelect/RendererIslandSelector.cs similarity index 85% rename from Runtime/IslandSelect/IslandRendererSelector.cs rename to Runtime/IslandSelect/RendererIslandSelector.cs index 3adfc66b..5dee3a8c 100644 --- a/Runtime/IslandSelect/IslandRendererSelector.cs +++ b/Runtime/IslandSelect/RendererIslandSelector.cs @@ -8,9 +8,9 @@ namespace net.rs64.TexTransTool.IslandSelector { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class IslandRendererSelector : AbstractIslandSelector + public class RendererIslandSelector : AbstractIslandSelector { - internal const string ComponentName = "TTT IslandRendererSelector"; + internal const string ComponentName = "TTT RendererIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public List RendererList; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) diff --git a/Runtime/IslandSelect/IslandRendererSelector.cs.meta b/Runtime/IslandSelect/RendererIslandSelector.cs.meta similarity index 100% rename from Runtime/IslandSelect/IslandRendererSelector.cs.meta rename to Runtime/IslandSelect/RendererIslandSelector.cs.meta From 49c81cbc76dbf1379ce2dc5ef5165a3feaf702f6 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 19:36:48 +0900 Subject: [PATCH 096/208] feat: island selector for XOR and Relay --- Runtime/IslandSelect/IslandSelectorRelay.cs | 22 ++++++++++++++ .../IslandSelect/IslandSelectorRelay.cs.meta | 11 +++++++ Runtime/IslandSelect/IslandSelectorXOR.cs | 29 +++++++++++++++++++ .../IslandSelect/IslandSelectorXOR.cs.meta | 11 +++++++ 4 files changed, 73 insertions(+) create mode 100644 Runtime/IslandSelect/IslandSelectorRelay.cs create mode 100644 Runtime/IslandSelect/IslandSelectorRelay.cs.meta create mode 100644 Runtime/IslandSelect/IslandSelectorXOR.cs create mode 100644 Runtime/IslandSelect/IslandSelectorXOR.cs.meta diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs b/Runtime/IslandSelect/IslandSelectorRelay.cs new file mode 100644 index 00000000..eb3f3de2 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorRelay.cs @@ -0,0 +1,22 @@ +using System.Collections; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using UnityEngine; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public class IslandSelectorRelay : AbstractIslandSelector + { + internal const string ComponentName = "TTT IslandSelectorRelay"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + + public AbstractIslandSelector IslandSelector = null; + + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription) : new BitArray(islands.Length); + } + } +} diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs.meta b/Runtime/IslandSelect/IslandSelectorRelay.cs.meta new file mode 100644 index 00000000..7514bcc4 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorRelay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 49cf9ca5f1d1e1540854d2ba030db7a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IslandSelect/IslandSelectorXOR.cs b/Runtime/IslandSelect/IslandSelectorXOR.cs new file mode 100644 index 00000000..5729a317 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorXOR.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Collections.Generic; +using net.rs64.TexTransCore.Island; +using UnityEngine; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransTool.IslandSelector +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public class IslandSelectorXOR : AbstractIslandSelector + { + internal const string ComponentName = "TTT IslandSelectorXOR"; + internal const string MenuPath = FoldoutName + "/" + ComponentName; + + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) + { + BitArray bitArray = null; + foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) + { + Profiler.BeginSample(islandSelector.GetType().Name); + var selectBit = islandSelector.IslandSelect(islands, islandDescription); + Profiler.EndSample(); + if (bitArray is null) { bitArray = selectBit; continue; } + bitArray.Xor(selectBit); + } + return bitArray; + } + } +} diff --git a/Runtime/IslandSelect/IslandSelectorXOR.cs.meta b/Runtime/IslandSelect/IslandSelectorXOR.cs.meta new file mode 100644 index 00000000..2b85ca71 --- /dev/null +++ b/Runtime/IslandSelect/IslandSelectorXOR.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 819595e91d093fb42bfb02e5b28ca785 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From aad5ffeedcd1e4b0789e010f0f62969af14cd7d4 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 19:37:13 +0900 Subject: [PATCH 097/208] chore: fix and add game object menu --- Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index 056faed8..066606a4 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -45,10 +45,13 @@ static void C() where TTB : MonoBehaviour [M(BP + BoxIslandSelector.MenuPath)] static void BIS() => C(); [M(BP + SphereIslandSelector.MenuPath)] static void SIS() => C(); [M(BP + RayCastIslandSelector.MenuPath)] static void RCIS() => C(); - [M(BP + IslandSelectOR.MenuPath)] static void ISOR() => C(); + [M(BP + RendererIslandSelector.MenuPath)] static void RIS() => C(); + [M(BP + SubMeshIslandSelector.MenuPath)] static void SMIS() => C(); + [M(BP + IslandSelectorOR.MenuPath)] static void ISOR() => C(); [M(BP + IslandSelectorAND.MenuPath)] static void ISAND() => C(); [M(BP + IslandSelectorNOT.MenuPath)] static void ISNOT() => C(); - [M(BP + IslandRendererSelector.MenuPath)] static void IRS() => C(); + [M(BP + IslandSelectorXOR.MenuPath)] static void ISXOR() => C(); + [M(BP + IslandSelectorRelay.MenuPath)] static void ISR() => C(); } From 48bf69b27c3d909dc924ce6a8c4efa9d23df2b8a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 19:40:45 +0900 Subject: [PATCH 098/208] fix: IslandSelectorOR ComponentName --- Runtime/IslandSelect/IslandSelectorOR.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Runtime/IslandSelect/IslandSelectorOR.cs b/Runtime/IslandSelect/IslandSelectorOR.cs index b7f97a64..1036985e 100644 --- a/Runtime/IslandSelect/IslandSelectorOR.cs +++ b/Runtime/IslandSelect/IslandSelectorOR.cs @@ -9,7 +9,7 @@ namespace net.rs64.TexTransTool.IslandSelector [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] public class IslandSelectorOR : AbstractIslandSelector { - internal const string ComponentName = "TTT IslandSelectOR"; + internal const string ComponentName = "TTT IslandSelectorOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { From c3999a6bc9d000d40ea528f8503cd1c4c38f750a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 22 Apr 2024 20:09:37 +0900 Subject: [PATCH 099/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index ff40c853..56f4c7c5 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -16,9 +16,12 @@ v0.5.2 以降の実験的機能の変更記録です。 - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) - AtlasTexture に MaterialMargeGroup が追加されました (#432) - ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) +- SubMeshIslandSelector , IslandSelectorXOR , IslandSelectorRelay が追加されました (#447) ### Changed +- IslandRendererSelector と IslandSelectOR の名前がそれぞれ RendererIslandSelector と IslandSelectorOR に変更されました (#447) + ### Removed - IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) From 399d41b879104989d37c860ef876c0bab5739706 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 22 Apr 2024 11:17:45 +0000 Subject: [PATCH 100/208] Update package.json v0.7.0-beta.5!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bcf0083c..7a703d16 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.4", + "version": "0.7.0-beta.5", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From af6319b3d3597811d6f3e0809d306face14c8530 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 23 Apr 2024 20:49:41 +0900 Subject: [PATCH 101/208] feat: TexTransRuntimeBehavior.GetDependency and some ... --- Editor/Domain/AvatarDomain.cs | 5 -- Editor/Domain/RenderersDomain.cs | 20 ++------ Editor/Inspector/Decal/AbstractDecalEditor.cs | 6 ++- .../Curve/CylindricalCurveDecalEditor.cs | 3 +- .../Inspector/Decal/CylindricalDecalEditor.cs | 5 +- Editor/Inspector/Decal/NailEditorEditor.cs | 3 +- Editor/Inspector/Decal/SimpleDecalEditor.cs | 1 + .../MatAndTexAbsoluteSeparatorEditor.cs | 5 +- .../MatAndTexRelativeSeparatorEditor.cs | 5 +- .../MatAndTexUtils/MaterialModifierEditor.cs | 5 +- .../MultiLayerImageCanvasEditor.cs | 5 +- Editor/Inspector/PhaseDefinitionEditor.cs | 5 +- Editor/Inspector/PreviewGroupEditor.cs | 3 +- Editor/Inspector/PreviewRendererEditor.cs | 5 +- Editor/Inspector/TexTransGroupEditor.cs | 3 +- .../TextureAtlas/AtlasTextureEditor.cs | 5 +- Editor/Inspector/TextureBlenderEditor.cs | 5 +- Editor/Inspector/TextureTransformerEditor.cs | 3 +- Editor/OtherMenuItem/PreviewUtility.cs | 8 +-- Editor/{CustomPreview.meta => Preview.meta} | 0 Editor/{Decal.meta => Preview/Custom.meta} | 2 +- .../Custom}/PreviewGroupPreview.cs | 2 +- .../Custom}/PreviewGroupPreview.cs.meta | 2 +- .../Custom}/PreviewRendererPreview.cs | 2 +- .../Custom}/PreviewRendererPreview.cs.meta | 0 .../Custom}/TTTCustomPreviewUtility.cs | 2 +- .../Custom}/TTTCustomPreviewUtility.cs.meta | 0 .../Custom}/TexTransGroupPreview.cs | 3 +- .../Custom}/TexTransGroupPreview.cs.meta | 0 .../OneTimePreviewContext.cs} | 11 ++-- .../OneTimePreviewContext.cs.meta} | 0 Editor/Preview/RealTime.meta | 8 +++ .../Preview/RealTime/PreviewStackManager.cs | 23 +++++++++ .../RealTime/PreviewStackManager.cs.meta | 11 ++++ .../RealTime/RealTimePreviewContext.cs} | 9 +++- .../RealTime/RealTimePreviewContext.cs.meta} | 0 .../Preview/RealTime/RealTimePreviewDomain.cs | 51 +++++++++++++++++++ .../RealTime/RealTimePreviewDomain.cs.meta | 11 ++++ Editor/TextureStack/DeferredTextureStack.cs | 2 +- Editor/TextureStack/ImmediateTextureStack.cs | 2 +- Editor/TextureStack/StackManager.cs | 10 +--- .../MatAndTexUtils/MaterialModifier.cs | 6 +++ Runtime/CommonComponent/TextureBlender.cs | 3 ++ Runtime/Decal/AbstractDecal.cs | 22 ++++---- Runtime/Decal/AbstructSingleDecal.cs | 7 ++- Runtime/Decal/Gradation.meta | 8 +++ .../Decal/Gradation/SingleGradationDecal.cs | 0 .../Gradation/SingleGradationDecal.cs.meta | 11 ++++ Runtime/Decal/SimpleDecal.cs | 8 +++ Runtime/IDomain.cs | 2 +- .../IslandSelect/AbstructIslandSelector.cs | 3 ++ Runtime/IslandSelect/BoxIslandSelector.cs | 3 ++ Runtime/IslandSelect/IslandSelectorAND.cs | 1 + Runtime/IslandSelect/IslandSelectorNOT.cs | 1 + Runtime/IslandSelect/IslandSelectorOR.cs | 2 + Runtime/IslandSelect/RayCastIslandSelector.cs | 1 + .../IslandSelect/RendererIslandSelector.cs | 1 + Runtime/IslandSelect/SphereIslandSelector.cs | 1 + Runtime/MultiLayerImage/AbstractLayer.cs | 7 +++ Runtime/MultiLayerImage/LayerFolder.cs | 12 +++-- .../MultiLayerImage/MultiLayerImageCanvas.cs | 21 ++++++-- .../MultiLayerImage/RasterImportedLayer.cs | 5 ++ Runtime/MultiLayerImage/RasterLayer.cs | 3 ++ Runtime/TTType/TextureSelector.cs | 30 +++++++++-- Runtime/TexTransRuntimeBehavior.cs | 11 +++- Runtime/TextureAtlas/AtlasTexture.cs | 8 +++ .../IslandFineTuner/IIslandFineTuner.cs | 2 + .../IslandFineTuner/SizePriority.cs | 4 +- 68 files changed, 325 insertions(+), 109 deletions(-) rename Editor/{CustomPreview.meta => Preview.meta} (100%) rename Editor/{Decal.meta => Preview/Custom.meta} (77%) rename Editor/{CustomPreview => Preview/Custom}/PreviewGroupPreview.cs (91%) rename Editor/{CustomPreview => Preview/Custom}/PreviewGroupPreview.cs.meta (83%) rename Editor/{CustomPreview => Preview/Custom}/PreviewRendererPreview.cs (96%) rename Editor/{CustomPreview => Preview/Custom}/PreviewRendererPreview.cs.meta (100%) rename Editor/{CustomPreview => Preview/Custom}/TTTCustomPreviewUtility.cs (98%) rename Editor/{CustomPreview => Preview/Custom}/TTTCustomPreviewUtility.cs.meta (100%) rename Editor/{CustomPreview => Preview/Custom}/TexTransGroupPreview.cs (97%) rename Editor/{CustomPreview => Preview/Custom}/TexTransGroupPreview.cs.meta (100%) rename Editor/{PreviewContext.cs => Preview/OneTimePreviewContext.cs} (95%) rename Editor/{PreviewContext.cs.meta => Preview/OneTimePreviewContext.cs.meta} (100%) create mode 100644 Editor/Preview/RealTime.meta create mode 100644 Editor/Preview/RealTime/PreviewStackManager.cs create mode 100644 Editor/Preview/RealTime/PreviewStackManager.cs.meta rename Editor/{Decal/RealTimePreviewManager.cs => Preview/RealTime/RealTimePreviewContext.cs} (98%) rename Editor/{Decal/RealTimePreviewManager.cs.meta => Preview/RealTime/RealTimePreviewContext.cs.meta} (100%) create mode 100644 Editor/Preview/RealTime/RealTimePreviewDomain.cs create mode 100644 Editor/Preview/RealTime/RealTimePreviewDomain.cs.meta create mode 100644 Runtime/Decal/Gradation.meta create mode 100644 Runtime/Decal/Gradation/SingleGradationDecal.cs create mode 100644 Runtime/Decal/Gradation/SingleGradationDecal.cs.meta diff --git a/Editor/Domain/AvatarDomain.cs b/Editor/Domain/AvatarDomain.cs index 860a4f26..01bbea9c 100644 --- a/Editor/Domain/AvatarDomain.cs +++ b/Editor/Domain/AvatarDomain.cs @@ -25,11 +25,6 @@ public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver assetSav { _avatarRoot = avatarRoot; } - public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver saver, ITextureManager textureManager, IStackManager stackManager) - : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, saver, textureManager, stackManager) - { - _avatarRoot = avatarRoot; - } [SerializeField] GameObject _avatarRoot; public GameObject AvatarRoot => _avatarRoot; diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index 64c2397a..4de07806 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -29,7 +29,7 @@ internal class RenderersDomain : IEditorCallDomain [CanBeNull] private readonly IAssetSaver _saver; private readonly ITextureManager _textureManager; - private readonly IStackManager _textureStacks; + private readonly StackManager _textureStacks; protected Dictionary _replaceMap = new();//New Old @@ -44,23 +44,9 @@ public RenderersDomain(List previewRenderers, bool previewing, IAssetS _textureStacks = new StackManager(_textureManager); } - public RenderersDomain(List previewRenderers, - bool previewing, - IAssetSaver saver, - ITextureManager textureManager, - IStackManager stackManager - ) + public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair { - _renderers = previewRenderers; - Previewing = previewing; - _saver = saver; - _textureManager = textureManager; - _textureStacks = stackManager; - } - - public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair - { - _textureStacks.AddTextureStack(dist, setTex); + _textureStacks.AddTextureStack(dist as Texture2D, setTex); } private void AddPropertyModification(Object component, string property, Object value) diff --git a/Editor/Inspector/Decal/AbstractDecalEditor.cs b/Editor/Inspector/Decal/AbstractDecalEditor.cs index 34c72429..a4a2290c 100644 --- a/Editor/Inspector/Decal/AbstractDecalEditor.cs +++ b/Editor/Inspector/Decal/AbstractDecalEditor.cs @@ -4,6 +4,8 @@ using System.Linq; using System.Collections.Generic; using UnityEngine.Pool; +using net.rs64.TexTransTool.Preview.RealTime; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.Decal { @@ -63,14 +65,14 @@ public static void DrawerRealTimePreviewEditor(IEnumerable target if (!target.Any(RealTimePreviewManager.Contains)) { - bool IsPossibleRealTimePreview = !PreviewContext.IsPreviewContains; + bool IsPossibleRealTimePreview = !OneTimePreviewContext.IsPreviewContains; IsPossibleRealTimePreview &= !AnimationMode.InAnimationMode(); IsPossibleRealTimePreview |= RealTimePreviewManager.IsContainsRealTimePreviewDecal; EditorGUI.BeginDisabledGroup(!IsPossibleRealTimePreview); if (GUILayout.Button(IsPossibleRealTimePreview ? "SimpleDecal:button:RealTimePreview".Glc() : "Common:PreviewNotAvailable".Glc())) { - PreviewContext.LastPreviewClear(); + OneTimePreviewContext.LastPreviewClear(); foreach (var decal in target) { RealTimePreviewManager.instance.RegtAbstractDecal(decal); } } EditorGUI.EndDisabledGroup(); diff --git a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs b/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs index 1b300f76..e805eb69 100644 --- a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs +++ b/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs @@ -1,5 +1,6 @@ using UnityEditor; using net.rs64.TexTransTool.Decal.Curve; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.Decal.Curve.Cylindrical { @@ -12,7 +13,7 @@ public override void OnInspectorGUI() { TextureTransformerEditor.DrawerWarning("CylindricalCurveDecal"); base.OnInspectorGUI(); - PreviewContext.instance.DrawApplyAndRevert(target as CylindricalCurveDecal); + OneTimePreviewContext.instance.DrawApplyAndRevert(target as CylindricalCurveDecal); } } diff --git a/Editor/Inspector/Decal/CylindricalDecalEditor.cs b/Editor/Inspector/Decal/CylindricalDecalEditor.cs index fb60d129..12f14640 100644 --- a/Editor/Inspector/Decal/CylindricalDecalEditor.cs +++ b/Editor/Inspector/Decal/CylindricalDecalEditor.cs @@ -1,6 +1,7 @@ using UnityEngine; using UnityEditor; using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.Decal { @@ -16,7 +17,7 @@ public override void OnInspectorGUI() var thisObject = target as CylindricalDecal; - EditorGUI.BeginDisabledGroup(PreviewContext.IsPreviewing(thisObject)); + EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); var sCylindricalCoordinatesSystem = thisSObject.FindProperty("CylindricalCoordinatesSystem"); EditorGUILayout.PropertyField(sCylindricalCoordinatesSystem); @@ -48,7 +49,7 @@ public override void OnInspectorGUI() EditorGUI.EndDisabledGroup(); - PreviewContext.instance.DrawApplyAndRevert(thisObject); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); thisSObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/Decal/NailEditorEditor.cs b/Editor/Inspector/Decal/NailEditorEditor.cs index 7a6351c5..7d03b94a 100644 --- a/Editor/Inspector/Decal/NailEditorEditor.cs +++ b/Editor/Inspector/Decal/NailEditorEditor.cs @@ -1,6 +1,7 @@ using UnityEngine; using UnityEditor; using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.Decal { @@ -45,7 +46,7 @@ public override void OnInspectorGUI() AbstractDecalEditor.DrawerAdvancedOption(thisSObject); - PreviewContext.instance.DrawApplyAndRevert(thisObject); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); thisSObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 9d763a3d..5f2dc1c1 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -4,6 +4,7 @@ using UnityEngine.UIElements; using UnityEditor.UIElements; using net.rs64.TexTransTool.IslandSelector; +using net.rs64.TexTransTool.Preview.RealTime; namespace net.rs64.TexTransTool.Editor.Decal { diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs b/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs index 209e139a..be9f039c 100644 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs +++ b/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs @@ -2,6 +2,7 @@ using System.Linq; using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.MatAndTexUtils; +using net.rs64.TexTransTool.Preview; using UnityEditor; using UnityEngine; @@ -17,7 +18,7 @@ public override void OnInspectorGUI() var thisSObject = serializedObject; var thisObject = target as MatAndTexAbsoluteSeparator; - EditorGUI.BeginDisabledGroup(PreviewContext.IsPreviewing(thisObject)); + EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); @@ -39,7 +40,7 @@ public override void OnInspectorGUI() EditorGUI.EndDisabledGroup(); - PreviewContext.instance.DrawApplyAndRevert(thisObject); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); thisSObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs b/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs index 9f57c442..e5c3a369 100644 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs +++ b/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs @@ -1,4 +1,5 @@ using net.rs64.TexTransTool.MatAndTexUtils; +using net.rs64.TexTransTool.Preview; using UnityEditor; using UnityEngine; @@ -14,7 +15,7 @@ public override void OnInspectorGUI() var thisSObject = serializedObject; var thisObject = target as MatAndTexRelativeSeparator; - EditorGUI.BeginDisabledGroup(PreviewContext.IsPreviewing(thisObject)); + EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); @@ -58,7 +59,7 @@ public override void OnInspectorGUI() EditorGUI.EndDisabledGroup(); - PreviewContext.instance.DrawApplyAndRevert(thisObject); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); thisSObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs b/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs index 0003074c..de4d3741 100644 --- a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs +++ b/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs @@ -2,6 +2,7 @@ using UnityEditor; using net.rs64.TexTransTool.MatAndTexUtils; using System.Collections.Generic; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.MatAndTexUtils { [CustomEditor(typeof(MaterialModifier))] @@ -15,7 +16,7 @@ public override void OnInspectorGUI() var thisSObject = serializedObject; var thisObject = target as MaterialModifier; - EditorGUI.BeginDisabledGroup(PreviewContext.IsPreviewing(thisObject)); + EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); @@ -36,7 +37,7 @@ public override void OnInspectorGUI() EditorGUI.EndDisabledGroup(); - PreviewContext.instance.DrawApplyAndRevert(thisObject); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); thisSObject.ApplyModifiedProperties(); } } diff --git a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs index defbd343..fccec0a3 100644 --- a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs +++ b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs @@ -1,8 +1,7 @@ using UnityEditor; using net.rs64.TexTransTool.MultiLayerImage; using UnityEngine; -using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor.MultiLayerImage { [CustomEditor(typeof(MultiLayerImageCanvas))] @@ -17,7 +16,7 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(sTarget.FindProperty("TextureSelector")); var thisTarget = target as MultiLayerImageCanvas; - PreviewContext.instance.DrawApplyAndRevert(thisTarget); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisTarget); sTarget.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/PhaseDefinitionEditor.cs b/Editor/Inspector/PhaseDefinitionEditor.cs index 3ece48d0..71d7413a 100644 --- a/Editor/Inspector/PhaseDefinitionEditor.cs +++ b/Editor/Inspector/PhaseDefinitionEditor.cs @@ -1,7 +1,6 @@ using UnityEditor; -using net.rs64.TexTransTool.Editor; -using net.rs64.TexTransTool; using UnityEngine.UIElements; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -16,7 +15,7 @@ public override VisualElement CreateInspectorGUI() var previewButton = new IMGUIContainer(() => { serializedObject.Update(); - PreviewContext.instance.DrawApplyAndRevert(target as TexTransGroup); + OneTimePreviewContext.instance.DrawApplyAndRevert(target as TexTransGroup); var sTexTransPhase = serializedObject.FindProperty("TexTransPhase"); EditorGUILayout.PropertyField(sTexTransPhase, sTexTransPhase.name.Glc()); serializedObject.ApplyModifiedProperties(); diff --git a/Editor/Inspector/PreviewGroupEditor.cs b/Editor/Inspector/PreviewGroupEditor.cs index f5bd08b6..f04be18b 100644 --- a/Editor/Inspector/PreviewGroupEditor.cs +++ b/Editor/Inspector/PreviewGroupEditor.cs @@ -4,6 +4,7 @@ using UnityEngine.UIElements; using net.rs64.TexTransTool.Build; using System.Collections.Generic; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -28,7 +29,7 @@ void CrateGroupElements() { rootVE.hierarchy.Clear(); - var previewButton = new IMGUIContainer(() => { TextureTransformerEditor.DrawerWarning(nameof(PreviewGroup)); PreviewContext.instance.DrawApplyAndRevert(target as PreviewGroup); }); + var previewButton = new IMGUIContainer(() => { TextureTransformerEditor.DrawerWarning(nameof(PreviewGroup)); OneTimePreviewContext.instance.DrawApplyAndRevert(target as PreviewGroup); }); rootVE.hierarchy.Add(previewButton); rootVE.styleSheets.Add(s_style); diff --git a/Editor/Inspector/PreviewRendererEditor.cs b/Editor/Inspector/PreviewRendererEditor.cs index 8179faf1..d8fbcb4d 100644 --- a/Editor/Inspector/PreviewRendererEditor.cs +++ b/Editor/Inspector/PreviewRendererEditor.cs @@ -5,8 +5,9 @@ using net.rs64.TexTransTool.Build; using System.Collections.Generic; using System; -using net.rs64.TexTransTool.CustomPreview; using UnityEngine; +using net.rs64.TexTransTool.Preview.Custom; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -32,7 +33,7 @@ void CrateElements() { rootVE.hierarchy.Clear(); - var previewButton = new IMGUIContainer(() => { TextureTransformerEditor.DrawerWarning(nameof(PreviewRenderer)); PreviewContext.instance.DrawApplyAndRevert(target as PreviewRenderer); }); + var previewButton = new IMGUIContainer(() => { TextureTransformerEditor.DrawerWarning(nameof(PreviewRenderer)); OneTimePreviewContext.instance.DrawApplyAndRevert(target as PreviewRenderer); }); rootVE.hierarchy.Add(previewButton); rootVE.styleSheets.Add(TexTransGroupEditor.s_style); diff --git a/Editor/Inspector/TexTransGroupEditor.cs b/Editor/Inspector/TexTransGroupEditor.cs index acffc49a..74c7a33c 100644 --- a/Editor/Inspector/TexTransGroupEditor.cs +++ b/Editor/Inspector/TexTransGroupEditor.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System; using UnityEditor.UIElements; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -38,7 +39,7 @@ void CrateGroupElements() { rootVE.hierarchy.Clear(); - var previewButton = new IMGUIContainer(() => PreviewContext.instance.DrawApplyAndRevert(target as TexTransGroup)); + var previewButton = new IMGUIContainer(() => OneTimePreviewContext.instance.DrawApplyAndRevert(target as TexTransGroup)); rootVE.hierarchy.Add(previewButton); rootVE.styleSheets.Add(s_style); diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 6badb484..0f0693a8 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -7,6 +7,7 @@ using System; using UnityEngine.UIElements; using UnityEditor.UIElements; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.TextureAtlas.Editor { @@ -52,7 +53,7 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(sTargetRoot, "AtlasTexture:prop:TargetRoot".Glc()); if (EditorGUI.EndChangeCheck()) { RefreshMaterials(sTargetRoot.objectReferenceValue as GameObject, thisTarget.AtlasSetting.IncludeDisabledRenderer); } - if (sTargetRoot.objectReferenceValue != null && !PreviewContext.IsPreviewContains) + if (sTargetRoot.objectReferenceValue != null && !OneTimePreviewContext.IsPreviewContains) { if (GUILayout.Button("AtlasTexture:button:RefreshMaterials".GetLocalize()) || _displayMaterial == null) { RefreshMaterials(thisTarget.TargetRoot, thisTarget.AtlasSetting.IncludeDisabledRenderer); } @@ -66,7 +67,7 @@ public override void OnInspectorGUI() DrawAtlasSettings(sAtlasSetting, sMatSelectors); - PreviewContext.instance.DrawApplyAndRevert(thisTarget); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisTarget); serializedObject.ApplyModifiedProperties(); diff --git a/Editor/Inspector/TextureBlenderEditor.cs b/Editor/Inspector/TextureBlenderEditor.cs index 554272ef..6f562d8a 100644 --- a/Editor/Inspector/TextureBlenderEditor.cs +++ b/Editor/Inspector/TextureBlenderEditor.cs @@ -1,5 +1,6 @@ using UnityEngine; using UnityEditor; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -13,7 +14,7 @@ public override void OnInspectorGUI() var thisTarget = target as TextureBlender; var thisSObject = serializedObject; - EditorGUI.BeginDisabledGroup(PreviewContext.IsPreviewing(thisTarget)); + EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisTarget)); EditorGUILayout.PropertyField(thisSObject.FindProperty("TargetTexture")); @@ -29,7 +30,7 @@ public override void OnInspectorGUI() EditorGUI.EndDisabledGroup(); - PreviewContext.instance.DrawApplyAndRevert(thisTarget); + OneTimePreviewContext.instance.DrawApplyAndRevert(thisTarget); thisSObject.ApplyModifiedProperties(); } diff --git a/Editor/Inspector/TextureTransformerEditor.cs b/Editor/Inspector/TextureTransformerEditor.cs index 709e3717..a9b7886f 100644 --- a/Editor/Inspector/TextureTransformerEditor.cs +++ b/Editor/Inspector/TextureTransformerEditor.cs @@ -1,6 +1,7 @@ using UnityEngine; using UnityEditor; using System.Linq; +using net.rs64.TexTransTool.Preview; namespace net.rs64.TexTransTool.Editor { @@ -12,7 +13,7 @@ public override void OnInspectorGUI() { DrawerWarning(target.GetType().Name); base.OnInspectorGUI(); - PreviewContext.instance.DrawApplyAndRevert(target as TexTransBehavior); + OneTimePreviewContext.instance.DrawApplyAndRevert(target as TexTransBehavior); } public static void DrawerWarning(string typeName) { diff --git a/Editor/OtherMenuItem/PreviewUtility.cs b/Editor/OtherMenuItem/PreviewUtility.cs index 7d84002b..e8eb260e 100644 --- a/Editor/OtherMenuItem/PreviewUtility.cs +++ b/Editor/OtherMenuItem/PreviewUtility.cs @@ -1,3 +1,5 @@ +using net.rs64.TexTransTool.Preview; +using net.rs64.TexTransTool.Preview.RealTime; using UnityEditor; namespace net.rs64.TexTransTool.Editor.OtherMenuItem @@ -8,15 +10,15 @@ internal class PreviewUtility public static void ExitPreviews() { if (RealTimePreviewManager.IsContainsRealTimePreviewDecal) { RealTimePreviewManager.instance.ExitPreview(); return; } - if (PreviewContext.IsPreviewContains) { PreviewContext.instance.ExitPreview(); } + if (OneTimePreviewContext.IsPreviewContains) { OneTimePreviewContext.instance.ExitPreview(); } } [MenuItem("Tools/TexTransTool/RePreview")] public static void RePreview() { - PreviewContext.instance.RePreview(); + OneTimePreviewContext.instance.RePreview(); } - public static bool IsPreviewContains => RealTimePreviewManager.IsContainsRealTimePreviewDecal || PreviewContext.IsPreviewContains; + public static bool IsPreviewContains => RealTimePreviewManager.IsContainsRealTimePreviewDecal || OneTimePreviewContext.IsPreviewContains; } } diff --git a/Editor/CustomPreview.meta b/Editor/Preview.meta similarity index 100% rename from Editor/CustomPreview.meta rename to Editor/Preview.meta diff --git a/Editor/Decal.meta b/Editor/Preview/Custom.meta similarity index 77% rename from Editor/Decal.meta rename to Editor/Preview/Custom.meta index 506e0030..dae19347 100644 --- a/Editor/Decal.meta +++ b/Editor/Preview/Custom.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0822c8e135b58404095530b297f1ad78 +guid: b980c37505aeb4942bcf006bc9c0d53d folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/CustomPreview/PreviewGroupPreview.cs b/Editor/Preview/Custom/PreviewGroupPreview.cs similarity index 91% rename from Editor/CustomPreview/PreviewGroupPreview.cs rename to Editor/Preview/Custom/PreviewGroupPreview.cs index 1c2a3b9e..e231e14c 100644 --- a/Editor/CustomPreview/PreviewGroupPreview.cs +++ b/Editor/Preview/Custom/PreviewGroupPreview.cs @@ -1,6 +1,6 @@ using net.rs64.TexTransTool.Build; -namespace net.rs64.TexTransTool.CustomPreview +namespace net.rs64.TexTransTool.Preview.Custom { [TTTCustomPreview(typeof(PreviewGroup))] internal class PreviewGroupPreview : ITTTCustomPreview diff --git a/Editor/CustomPreview/PreviewGroupPreview.cs.meta b/Editor/Preview/Custom/PreviewGroupPreview.cs.meta similarity index 83% rename from Editor/CustomPreview/PreviewGroupPreview.cs.meta rename to Editor/Preview/Custom/PreviewGroupPreview.cs.meta index 2235593d..75a88aa5 100644 --- a/Editor/CustomPreview/PreviewGroupPreview.cs.meta +++ b/Editor/Preview/Custom/PreviewGroupPreview.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 43e51d6b528abbc4192fa30a2f526bee +guid: 6b4812c405b8aa2409c2a54e97c6a6ae MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/CustomPreview/PreviewRendererPreview.cs b/Editor/Preview/Custom/PreviewRendererPreview.cs similarity index 96% rename from Editor/CustomPreview/PreviewRendererPreview.cs rename to Editor/Preview/Custom/PreviewRendererPreview.cs index 64fdca92..e7468d3c 100644 --- a/Editor/CustomPreview/PreviewRendererPreview.cs +++ b/Editor/Preview/Custom/PreviewRendererPreview.cs @@ -3,7 +3,7 @@ using net.rs64.TexTransTool.Build; using UnityEngine; -namespace net.rs64.TexTransTool.CustomPreview +namespace net.rs64.TexTransTool.Preview.Custom { [TTTCustomPreview(typeof(PreviewRenderer))] internal class PreviewRendererPreview : ITTTCustomPreview diff --git a/Editor/CustomPreview/PreviewRendererPreview.cs.meta b/Editor/Preview/Custom/PreviewRendererPreview.cs.meta similarity index 100% rename from Editor/CustomPreview/PreviewRendererPreview.cs.meta rename to Editor/Preview/Custom/PreviewRendererPreview.cs.meta diff --git a/Editor/CustomPreview/TTTCustomPreviewUtility.cs b/Editor/Preview/Custom/TTTCustomPreviewUtility.cs similarity index 98% rename from Editor/CustomPreview/TTTCustomPreviewUtility.cs rename to Editor/Preview/Custom/TTTCustomPreviewUtility.cs index 57eacfd2..7f552146 100644 --- a/Editor/CustomPreview/TTTCustomPreviewUtility.cs +++ b/Editor/Preview/Custom/TTTCustomPreviewUtility.cs @@ -5,7 +5,7 @@ using UnityEditor; using Debug = UnityEngine.Debug; -namespace net.rs64.TexTransTool.CustomPreview +namespace net.rs64.TexTransTool.Preview.Custom { [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = true)] internal sealed class TTTCustomPreviewAttribute : System.Attribute// TODO : このあたりの属性とインターフェイスで特定の型に対して特定のインターフェースを当てる部分を共通の仕組みにしてもいいかもな~ diff --git a/Editor/CustomPreview/TTTCustomPreviewUtility.cs.meta b/Editor/Preview/Custom/TTTCustomPreviewUtility.cs.meta similarity index 100% rename from Editor/CustomPreview/TTTCustomPreviewUtility.cs.meta rename to Editor/Preview/Custom/TTTCustomPreviewUtility.cs.meta diff --git a/Editor/CustomPreview/TexTransGroupPreview.cs b/Editor/Preview/Custom/TexTransGroupPreview.cs similarity index 97% rename from Editor/CustomPreview/TexTransGroupPreview.cs rename to Editor/Preview/Custom/TexTransGroupPreview.cs index 9cdfbe27..51e4e3b9 100644 --- a/Editor/CustomPreview/TexTransGroupPreview.cs +++ b/Editor/Preview/Custom/TexTransGroupPreview.cs @@ -2,7 +2,8 @@ using System.Linq; using net.rs64.TexTransTool.Build; -namespace net.rs64.TexTransTool.CustomPreview +namespace net.rs64.TexTransTool.Preview.Custom + { [TTTCustomPreview(typeof(TexTransGroup))] internal class TexTransGroupPreview : ITTTCustomPreview diff --git a/Editor/CustomPreview/TexTransGroupPreview.cs.meta b/Editor/Preview/Custom/TexTransGroupPreview.cs.meta similarity index 100% rename from Editor/CustomPreview/TexTransGroupPreview.cs.meta rename to Editor/Preview/Custom/TexTransGroupPreview.cs.meta diff --git a/Editor/PreviewContext.cs b/Editor/Preview/OneTimePreviewContext.cs similarity index 95% rename from Editor/PreviewContext.cs rename to Editor/Preview/OneTimePreviewContext.cs index d85f2443..c66118a7 100644 --- a/Editor/PreviewContext.cs +++ b/Editor/Preview/OneTimePreviewContext.cs @@ -1,23 +1,20 @@ using System; -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransTool.Build; -using net.rs64.TexTransTool.CustomPreview; +using net.rs64.TexTransTool.Preview.Custom; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Profiling; using Object = UnityEngine.Object; -namespace net.rs64.TexTransTool +namespace net.rs64.TexTransTool.Preview { - internal class PreviewContext : ScriptableSingleton + internal class OneTimePreviewContext : ScriptableSingleton { [SerializeField] private Object previweing = null; private Object lastPreviweing = null; - protected PreviewContext() + protected OneTimePreviewContext() { AssemblyReloadEvents.beforeAssemblyReload -= ExitPreview; AssemblyReloadEvents.beforeAssemblyReload += ExitPreview; diff --git a/Editor/PreviewContext.cs.meta b/Editor/Preview/OneTimePreviewContext.cs.meta similarity index 100% rename from Editor/PreviewContext.cs.meta rename to Editor/Preview/OneTimePreviewContext.cs.meta diff --git a/Editor/Preview/RealTime.meta b/Editor/Preview/RealTime.meta new file mode 100644 index 00000000..a710b05b --- /dev/null +++ b/Editor/Preview/RealTime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e9f2a48eaf52c0e4aa608f72b966bbfa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs b/Editor/Preview/RealTime/PreviewStackManager.cs new file mode 100644 index 00000000..dbc62ee0 --- /dev/null +++ b/Editor/Preview/RealTime/PreviewStackManager.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using UnityEngine; +using static net.rs64.TexTransCore.BlendTexture.TextureBlend; + +namespace net.rs64.TexTransTool.Preview.RealTime +{ + internal class PreviewStackManager + { + + public void ResetStack() + { + + } + } + + internal class PrioritizedDeferredStack + { + Texture2D _initialTexture; + RenderTexture _stackViewTexture; + + + } +} diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs.meta b/Editor/Preview/RealTime/PreviewStackManager.cs.meta new file mode 100644 index 00000000..e72bf898 --- /dev/null +++ b/Editor/Preview/RealTime/PreviewStackManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 600ab3c758e0ed540abacf253c29eaee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Decal/RealTimePreviewManager.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs similarity index 98% rename from Editor/Decal/RealTimePreviewManager.cs rename to Editor/Preview/RealTime/RealTimePreviewContext.cs index bca07d1a..6ab9160c 100644 --- a/Editor/Decal/RealTimePreviewManager.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -12,12 +12,17 @@ using UnityEngine.Profiling; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; -namespace net.rs64.TexTransTool +namespace net.rs64.TexTransTool.Preview.RealTime { internal class RealTimePreviewManager : ScriptableSingleton { - private Dictionary RealTimePreviews = new(); + private GameObject _previewTargetAvatarRoot = null; + private Dictionary _texTransRuntimeBehaviorPriority = new(); private Dictionary> PreviewMaterials = new(); + private HashSet _containsBehavior = new(); + + + private Dictionary RealTimePreviews = new(); private Dictionary PreviewMatSwapDict = new(); private HashSet PreviewTargetRenderer = new(); private Stopwatch stopwatch = new(); diff --git a/Editor/Decal/RealTimePreviewManager.cs.meta b/Editor/Preview/RealTime/RealTimePreviewContext.cs.meta similarity index 100% rename from Editor/Decal/RealTimePreviewManager.cs.meta rename to Editor/Preview/RealTime/RealTimePreviewContext.cs.meta diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs new file mode 100644 index 00000000..ef72a428 --- /dev/null +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransTool.Decal; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.Pool; +using UnityEngine.Profiling; +using static net.rs64.TexTransCore.BlendTexture.TextureBlend; + +namespace net.rs64.TexTransTool.Preview.RealTime +{ + internal class RealTimePreviewDomain : IDomain + { + GameObject _domainRoot; + HashSet domainRenderers; + ITextureManager _textureManager = new TextureManager(true); + PreviewStackManager _stackManager; + public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + { + // _stackManager + } + + + + + + + + + + + + + public IEnumerable EnumerateRenderer() { return domainRenderers; } + + public ITextureManager GetTextureManager() => _textureManager; + public bool IsPreview() => true; + + public bool OriginEqual(UnityEngine.Object l, UnityEngine.Object r) => l == r; + public void RegisterReplace(UnityEngine.Object oldObject, UnityEngine.Object nowObject) { } + + public void ReplaceMaterials(Dictionary mapping, bool rendererOnly = false) { throw new NotImplementedException(); } + public void SetMesh(Renderer renderer, Mesh mesh) { throw new NotImplementedException(); } + public void TransferAsset(UnityEngine.Object asset) { throw new NotImplementedException(); } + } +} diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs.meta b/Editor/Preview/RealTime/RealTimePreviewDomain.cs.meta new file mode 100644 index 00000000..370faa00 --- /dev/null +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79aa8a94b57b8954499c02321037d5d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/TextureStack/DeferredTextureStack.cs b/Editor/TextureStack/DeferredTextureStack.cs index ad097aa4..9d2f5e28 100644 --- a/Editor/TextureStack/DeferredTextureStack.cs +++ b/Editor/TextureStack/DeferredTextureStack.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool.TextureStack { - internal class DeferredTextureStack : TextureStack + internal class DeferredTextureStack : AbstractTextureStack { [SerializeField] List StackTextures = new(); diff --git a/Editor/TextureStack/ImmediateTextureStack.cs b/Editor/TextureStack/ImmediateTextureStack.cs index 2501bd96..165e2ae5 100644 --- a/Editor/TextureStack/ImmediateTextureStack.cs +++ b/Editor/TextureStack/ImmediateTextureStack.cs @@ -7,7 +7,7 @@ namespace net.rs64.TexTransTool.TextureStack { - internal class ImmediateTextureStack : TextureStack + internal class ImmediateTextureStack : AbstractTextureStack { RenderTexture renderTexture; public override void init(Texture2D firstTexture, ITextureManager textureManager) diff --git a/Editor/TextureStack/StackManager.cs b/Editor/TextureStack/StackManager.cs index 954af731..adbfd43b 100644 --- a/Editor/TextureStack/StackManager.cs +++ b/Editor/TextureStack/StackManager.cs @@ -4,13 +4,7 @@ namespace net.rs64.TexTransTool.TextureStack { - internal interface IStackManager - { - void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair; - List MergeStacks(); - } - internal class StackManager : IStackManager - where Stack : TextureStack, new() + internal class StackManager where Stack : AbstractTextureStack, new() { [SerializeField] List _textureStacks = new List(); ITextureManager _textureManager; @@ -59,7 +53,7 @@ public MergeResult(Texture2D firstTexture, Texture2D mergeTexture) } } - internal abstract class TextureStack + internal abstract class AbstractTextureStack { public virtual void init(Texture2D firstTexture, ITextureManager textureManager) { FirstTexture = firstTexture; TextureManager = textureManager; } public Texture2D FirstTexture; diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index 5a4f89ea..38e62f77 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -89,5 +89,11 @@ internal override void Apply([NotNull] IDomain domain) } domain.ReplaceMaterials(modMatList); } + + internal override IEnumerable GetDependency() + { + foreach (var i in ModifiedTarget) { yield return i; } + foreach (var i in TargetRenderers) { yield return i; } + } } } diff --git a/Runtime/CommonComponent/TextureBlender.cs b/Runtime/CommonComponent/TextureBlender.cs index ca95f433..98ccc03d 100644 --- a/Runtime/CommonComponent/TextureBlender.cs +++ b/Runtime/CommonComponent/TextureBlender.cs @@ -3,6 +3,7 @@ using net.rs64.TexTransCore.BlendTexture; using System; using net.rs64.TexTransTool.Utils; +using System.Linq; namespace net.rs64.TexTransTool { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] @@ -36,5 +37,7 @@ internal override void Apply(IDomain domain) var addTex = TextureBlend.CreateMultipliedRenderTexture(BlendTexture, Color); domain.AddTextureStack(distTex, new(addTex, BlendTypeKey)); } + + internal override IEnumerable GetDependency() { return TargetTexture.GetDependency().Append(BlendTexture); } } } diff --git a/Runtime/Decal/AbstractDecal.cs b/Runtime/Decal/AbstractDecal.cs index a8dc78aa..808ae9de 100644 --- a/Runtime/Decal/AbstractDecal.cs +++ b/Runtime/Decal/AbstractDecal.cs @@ -7,6 +7,7 @@ using net.rs64.TexTransTool.Utils; using net.rs64.TexTransCore.Island; using UnityEngine.Pool; +using System.Linq; namespace net.rs64.TexTransTool.Decal { @@ -51,7 +52,7 @@ internal override void Apply(IDomain domain) foreach (var matAndTex in decalCompiledTextures) { - domain.AddTextureStack(matAndTex.Key.GetTexture(TargetPropertyName) as Texture2D, new TextureBlend.BlendTexturePair(matAndTex.Value, BlendTypeKey)); + domain.AddTextureStack(matAndTex.Key.GetTexture(TargetPropertyName), new TextureBlend.BlendTexturePair(matAndTex.Value, BlendTypeKey)); } DictionaryPool.Release(decalCompiledTextures); @@ -85,17 +86,14 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan return mulDecalTexture; } - // TODO : リアルタイムプレビューの改修と同時に何とかする - - // [NonSerialized] public bool ThisIsForces = false; - // private void Update() - // { - // if (ThisIsForces && RealTimePreviewManager.instance.RealTimePreviews.ContainsKey(this)) - // { - // RealTimePreviewManager.instance.UpdateAbstractDecal(this); - // } - // ThisIsForces = false; - // } + internal override IEnumerable GetDependency() + { + return new UnityEngine.Object[]{transform} + .Concat(TargetRenderers) + .Concat(TargetRenderers.Select(r => r.transform)) + .Concat(TargetRenderers.Select(r => r.GetMesh())) + .Concat(TargetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)); + } } } diff --git a/Runtime/Decal/AbstructSingleDecal.cs b/Runtime/Decal/AbstructSingleDecal.cs index b60bd0e0..75d53186 100644 --- a/Runtime/Decal/AbstructSingleDecal.cs +++ b/Runtime/Decal/AbstructSingleDecal.cs @@ -23,7 +23,7 @@ internal override Dictionary CompileDecal(ITextureManag Profiler.BeginSample("GetMultipleDecalTexture"); RenderTexture mulDecalTexture = GetMultipleDecalTexture(textureManager, DecalTexture, Color); Profiler.EndSample(); - + decalCompiledRenderTextures ??= new(); foreach (var renderer in TargetRenderers) { @@ -47,7 +47,10 @@ internal override Dictionary CompileDecal(ITextureManag return decalCompiledRenderTextures; } - + internal override IEnumerable GetDependency() + { + return base.GetDependency().Append(DecalTexture); + } } diff --git a/Runtime/Decal/Gradation.meta b/Runtime/Decal/Gradation.meta new file mode 100644 index 00000000..64e2e1fe --- /dev/null +++ b/Runtime/Decal/Gradation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ee647c3d1a8f64c4d9973357184ad95a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs new file mode 100644 index 00000000..e69de29b diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta b/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta new file mode 100644 index 00000000..78bd0e8f --- /dev/null +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b399477d38fcd3e4db79d5052517d489 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 5fd44b7f..98c080b8 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -6,6 +6,7 @@ using net.rs64.TexTransTool.Utils; using net.rs64.TexTransTool.IslandSelector; using System; +using System.Linq; namespace net.rs64.TexTransTool.Decal { @@ -65,5 +66,12 @@ internal void OnDrawGizmosSelected() DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, matrix); } + + internal override IEnumerable GetDependency() + { + return base.GetDependency().Concat(IslandSelector.GetDependency()); + } + + } } diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index fe0b0bbb..b7ec6a89 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -12,7 +12,7 @@ internal interface IDomain : IAssetSaver, IReplaceTracking { void ReplaceMaterials(Dictionary mapping, bool rendererOnly = false); void SetMesh(Renderer renderer, Mesh mesh); - public void AddTextureStack(Texture2D dist, BlendTex setTex) where BlendTex : IBlendTexturePair;// TempRenderTexture 想定 + public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair;// TempRenderTexture 想定 public IEnumerable EnumerateRenderer(); diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index 2b0c4c90..e4cd5af1 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -4,6 +4,7 @@ using net.rs64.TexTransCore.Island; using Unity.Collections; using System.Collections; +using System; namespace net.rs64.TexTransTool.IslandSelector { @@ -14,6 +15,8 @@ public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, [HideInInspector, SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; int ITexTransToolTag.SaveDataVersion => _saveDataVersion; + internal abstract IEnumerable GetDependency(); + internal abstract BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription); BitArray IIslandSelector.IslandSelect(Island[] islands, IslandDescription[] islandDescription) => IslandSelect(islands, islandDescription); /* diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs index e6416f6c..b8ff7268 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -11,6 +11,9 @@ public class BoxIslandSelector : AbstractIslandSelector { internal const string ComponentName = "TTT BoxIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + + internal override IEnumerable GetDependency() { yield break; } + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs index 73b24b96..c1b790fa 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -11,6 +11,7 @@ public class IslandSelectorAND : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectorAND"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; diff --git a/Runtime/IslandSelect/IslandSelectorNOT.cs b/Runtime/IslandSelect/IslandSelectorNOT.cs index 93671af0..4df312b5 100644 --- a/Runtime/IslandSelect/IslandSelectorNOT.cs +++ b/Runtime/IslandSelect/IslandSelectorNOT.cs @@ -13,6 +13,7 @@ public class IslandSelectorNOT : AbstractIslandSelector internal const string MenuPath = FoldoutName + "/" + ComponentName; public AbstractIslandSelector IslandSelector; + internal override IEnumerable GetDependency() { return IslandSelector.GetDependency(); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); diff --git a/Runtime/IslandSelect/IslandSelectorOR.cs b/Runtime/IslandSelect/IslandSelectorOR.cs index 1036985e..07a732c6 100644 --- a/Runtime/IslandSelect/IslandSelectorOR.cs +++ b/Runtime/IslandSelect/IslandSelectorOR.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransCore.Island; using UnityEngine; using UnityEngine.Profiling; @@ -11,6 +12,7 @@ public class IslandSelectorOR : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectorOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform).SelectMany(i => i.GetDependency()); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs index 1207417e..9e76019f 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -17,6 +17,7 @@ public class RayCastIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT RayCastIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public float IslandSelectorRange = 0.1f; + internal override IEnumerable GetDependency() { yield break; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return RayCastIslandSelect(GetIslandSelectorRay(), islands, islandDescription); diff --git a/Runtime/IslandSelect/RendererIslandSelector.cs b/Runtime/IslandSelect/RendererIslandSelector.cs index 5dee3a8c..2f99849a 100644 --- a/Runtime/IslandSelect/RendererIslandSelector.cs +++ b/Runtime/IslandSelect/RendererIslandSelector.cs @@ -12,6 +12,7 @@ public class RendererIslandSelector : AbstractIslandSelector { internal const string ComponentName = "TTT RendererIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + internal override IEnumerable GetDependency() { yield break; } public List RendererList; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index a7916f53..93faa6a0 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -12,6 +12,7 @@ public class SphereIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT SphereIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public float SphereSize = 0.1f; + internal override IEnumerable GetDependency() { yield break; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { diff --git a/Runtime/MultiLayerImage/AbstractLayer.cs b/Runtime/MultiLayerImage/AbstractLayer.cs index 65ad2c73..78d8b0ed 100644 --- a/Runtime/MultiLayerImage/AbstractLayer.cs +++ b/Runtime/MultiLayerImage/AbstractLayer.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using net.rs64.TexTransCore.BlendTexture; using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.Utils; @@ -33,6 +34,9 @@ internal virtual LayerAlphaMod GetLayerAlphaMod(CanvasContext canvasContext) return new LayerAlphaMod(null, Opacity); } } + + internal virtual IEnumerable GetDependency() { foreach (var m in LayerMask.GetDependency()) { yield return m; } } + } [Serializable] public class LayerMask : ILayerMask @@ -42,6 +46,8 @@ public class LayerMask : ILayerMask public bool ContainedMask => !LayerMaskDisabled && MaskTexture != null; + public IEnumerable GetDependency() { yield return MaskTexture; } + void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture originTexture) { originTexture.WriteOriginalTexture(MaskTexture, renderTexture); @@ -52,6 +58,7 @@ public interface ILayerMask { bool ContainedMask { get; } void WriteMaskTexture(RenderTexture renderTexture, IOriginTexture originTexture); + abstract IEnumerable GetDependency(); } diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index e6f56298..3f19fe87 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -17,10 +17,7 @@ public sealed class LayerFolder : AbstractLayer public bool PassThrough; internal override void EvaluateTexture(CanvasContext canvasContext) { - - var Layers = transform.GetChildren() - .Select(I => I.GetComponent()) - .Reverse(); + IEnumerable Layers = GetChileLayers(); if (PassThrough && !Clipping) { @@ -53,7 +50,12 @@ internal override void EvaluateTexture(CanvasContext canvasContext) } } - + internal IEnumerable GetChileLayers() + { + return transform.GetChildren() + .Select(I => I.GetComponent()) + .Reverse(); + } } diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 3947b107..204914d6 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -37,10 +37,7 @@ internal override void Apply([NotNull] IDomain domain) internal RenderTexture EvaluateCanvas(ITextureManager textureManager, int canvasSize) { - var Layers = transform.GetChildren() - .Select(I => I.GetComponent()) - .Where(I => I != null) - .Reverse(); + var Layers = GetChileLayers(); var canvasContext = new CanvasContext(canvasSize, textureManager); foreach (var layer in Layers) { layer.EvaluateTexture(canvasContext); } @@ -49,7 +46,15 @@ internal RenderTexture EvaluateCanvas(ITextureManager textureManager, int canvas return result; } - internal static int NormalizePowOfTow(int v) + private IEnumerable GetChileLayers() + { + return transform.GetChildren() + .Select(I => I.GetComponent()) + .Where(I => I != null) + .Reverse(); + } + + internal static int NormalizePowOfTow(int v) { if (Mathf.IsPowerOfTwo(v)) { return v; } @@ -60,6 +65,12 @@ internal static int NormalizePowOfTow(int v) else { return nextV; } } + internal override IEnumerable GetDependency() + { + var chileLayers = GetChileLayers(); + return TextureSelector.GetDependency().Append(tttImportedCanvasDescription).Concat(chileLayers).Concat(chileLayers.SelectMany(l => l.GetDependency())); + } + internal class CanvasContext { public ITextureManager TextureManager; diff --git a/Runtime/MultiLayerImage/RasterImportedLayer.cs b/Runtime/MultiLayerImage/RasterImportedLayer.cs index 0903a0f2..37df5e76 100644 --- a/Runtime/MultiLayerImage/RasterImportedLayer.cs +++ b/Runtime/MultiLayerImage/RasterImportedLayer.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransTool; using net.rs64.TexTransTool.MultiLayerImage; using UnityEngine; @@ -17,6 +19,8 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin { originTexture.WriteOriginalTexture(ImportedImage, renderTexture); } + + internal override IEnumerable GetDependency() { return base.GetDependency().Append(ImportedImage); } } [Serializable] public class TTTImportedLayerMask : ILayerMask @@ -36,5 +40,6 @@ void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture ori { originTexture.WriteOriginalTexture(MaskTexture, renderTexture); } + public IEnumerable GetDependency() { yield return MaskTexture; } } } diff --git a/Runtime/MultiLayerImage/RasterLayer.cs b/Runtime/MultiLayerImage/RasterLayer.cs index 90e698c9..472e89bf 100644 --- a/Runtime/MultiLayerImage/RasterLayer.cs +++ b/Runtime/MultiLayerImage/RasterLayer.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; +using System.Linq; using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -12,5 +14,6 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin { originTexture.WriteOriginalTexture(RasterTexture, renderTexture); } + internal override IEnumerable GetDependency() { return base.GetDependency().Append(RasterTexture); } } } diff --git a/Runtime/TTType/TextureSelector.cs b/Runtime/TTType/TextureSelector.cs index ac71782c..8b379cbd 100644 --- a/Runtime/TTType/TextureSelector.cs +++ b/Runtime/TTType/TextureSelector.cs @@ -1,6 +1,7 @@ using UnityEngine; using System; using UnityEngine.Serialization; +using System.Collections.Generic; namespace net.rs64.TexTransTool { [Serializable] @@ -18,11 +19,11 @@ public enum SelectMode public Texture2D SelectTexture; //Relative - [FormerlySerializedAs("TargetRenderer")]public Renderer RendererAsPath; - [FormerlySerializedAs("MaterialSelect")]public int SlotAsPath = 0; - [FormerlySerializedAs("TargetPropertyName")]public PropertyName PropertyNameAsPath = PropertyName.DefaultValue; + [FormerlySerializedAs("TargetRenderer")] public Renderer RendererAsPath; + [FormerlySerializedAs("MaterialSelect")] public int SlotAsPath = 0; + [FormerlySerializedAs("TargetPropertyName")] public PropertyName PropertyNameAsPath = PropertyName.DefaultValue; - internal Texture2D GetTexture() + internal Texture GetTexture() { switch (Mode) { @@ -37,11 +38,30 @@ internal Texture2D GetTexture() if (DistMaterials.Length <= SlotAsPath) return null; var DistMat = DistMaterials[SlotAsPath]; - return DistMat.GetTexture(PropertyNameAsPath) as Texture2D; + return DistMat.GetTexture(PropertyNameAsPath); } default: { return null; } } } + internal IEnumerable GetDependency() + { + switch (Mode) + { + default: yield break; + case SelectMode.Absolute: yield return SelectTexture; yield break; + case SelectMode.Relative: + { + yield return RendererAsPath; + + var DistMaterials = RendererAsPath.sharedMaterials; + if (DistMaterials.Length <= SlotAsPath) { yield return DistMaterials[SlotAsPath]; } + + yield return GetTexture(); + yield break; + } + } + } + } } diff --git a/Runtime/TexTransRuntimeBehavior.cs b/Runtime/TexTransRuntimeBehavior.cs index f4298a55..23347d98 100644 --- a/Runtime/TexTransRuntimeBehavior.cs +++ b/Runtime/TexTransRuntimeBehavior.cs @@ -1,4 +1,7 @@ +using System.Collections.Generic; +using System.Security.Cryptography; using JetBrains.Annotations; +using UnityEngine; namespace net.rs64.TexTransTool { @@ -10,5 +13,11 @@ public abstract class TexTransRuntimeBehavior : TexTransBehavior, ITexTransToolT /// /// The domain internal abstract void Apply([NotNull] IDomain domain); + + + /// + /// Enumerates references that depend on the component externally. + /// + internal abstract IEnumerable GetDependency(); } -} \ No newline at end of file +} diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 117057d4..941e3299 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -837,5 +837,13 @@ internal static List FilteredRenderers(GameObject targetRoot, bool inc return result; } + internal override IEnumerable GetDependency() + { + return AtlasSetting.IslandFineTuners.SelectMany(i => i.GetDependency()) + .Concat(Renderers) + .Concat(AtlasSetting.MaterialMargeGroups.Select(m => m.MargeReferenceMaterial)) + .Append(AtlasSetting.AtlasIslandRelocator) + .Append(AtlasSetting.MergeReferenceMaterial); + } } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs index 48ae7970..3f3e2e8b 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs @@ -12,5 +12,7 @@ internal interface IIslandFineTuner //islands と islandDescriptions は書き込みしないように、 //sizePriority と islandRect を操作して調整していく感じ void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); + + IEnumerable GetDependency(); } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs index 43bcb92c..669d3966 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs @@ -13,7 +13,9 @@ internal class SizePriority : IIslandFineTuner [Range(0, 1)] public float PriorityValue = 1f; public AbstractIslandSelector IslandSelector; - public void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) + public IEnumerable GetDependency() { return IslandSelector.GetDependency(); } + + public void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) { var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); From 151d655089e3246ba8d794d59b29db65aa7fc0fd Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 23 Apr 2024 20:58:54 +0900 Subject: [PATCH 102/208] feat: implement GetDependency of late added component --- Runtime/IslandSelect/IslandSelectorRelay.cs | 2 ++ Runtime/IslandSelect/IslandSelectorXOR.cs | 2 ++ Runtime/IslandSelect/SubMeshIslandSelector.cs | 1 + 3 files changed, 5 insertions(+) diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs b/Runtime/IslandSelect/IslandSelectorRelay.cs index eb3f3de2..4962681f 100644 --- a/Runtime/IslandSelect/IslandSelectorRelay.cs +++ b/Runtime/IslandSelect/IslandSelectorRelay.cs @@ -14,6 +14,8 @@ public class IslandSelectorRelay : AbstractIslandSelector public AbstractIslandSelector IslandSelector = null; + internal override IEnumerable GetDependency() { return IslandSelector.GetDependency(); } + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription) : new BitArray(islands.Length); diff --git a/Runtime/IslandSelect/IslandSelectorXOR.cs b/Runtime/IslandSelect/IslandSelectorXOR.cs index 5729a317..3fcc0269 100644 --- a/Runtime/IslandSelect/IslandSelectorXOR.cs +++ b/Runtime/IslandSelect/IslandSelectorXOR.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransCore.Island; using UnityEngine; using UnityEngine.Profiling; @@ -12,6 +13,7 @@ public class IslandSelectorXOR : AbstractIslandSelector internal const string ComponentName = "TTT IslandSelectorXOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform).SelectMany(i => i.GetDependency()); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; diff --git a/Runtime/IslandSelect/SubMeshIslandSelector.cs b/Runtime/IslandSelect/SubMeshIslandSelector.cs index 1d1702aa..ef07cbe4 100644 --- a/Runtime/IslandSelect/SubMeshIslandSelector.cs +++ b/Runtime/IslandSelect/SubMeshIslandSelector.cs @@ -14,6 +14,7 @@ public class SubMeshIslandSelector : AbstractIslandSelector public int SelectSubMeshIndex = 0; + internal override IEnumerable GetDependency() { yield break; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); From 53cf69f23b3623e109319bd55fa5e7e84a92610a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 24 Apr 2024 20:49:04 +0900 Subject: [PATCH 103/208] fix: Exception when Island Selector Null --- Runtime/Decal/SimpleDecal.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 98c080b8..bf13d107 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -69,7 +69,9 @@ internal void OnDrawGizmosSelected() internal override IEnumerable GetDependency() { - return base.GetDependency().Concat(IslandSelector.GetDependency()); + var dependencies = base.GetDependency(); + if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } + return dependencies; } From 7962813c35c108d5d3813f2447f657229313925f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 24 Apr 2024 21:02:53 +0900 Subject: [PATCH 104/208] feat: RealTimePreviewContext --- Editor/Build/AvatarBuildUtils.cs | 8 + Editor/Inspector/Decal/AbstractDecalEditor.cs | 27 +- Editor/Inspector/Decal/SimpleDecalEditor.cs | 32 +- Editor/OtherMenuItem/PreviewUtility.cs | 4 +- .../Preview/RealTime/PreviewStackManager.cs | 133 ++++- .../RealTime/RealTimePreviewContext.cs | 478 +++++------------- .../Preview/RealTime/RealTimePreviewDomain.cs | 101 +++- TexTransCore/BlendTexture/TextureBlend.cs | 6 + 8 files changed, 401 insertions(+), 388 deletions(-) diff --git a/Editor/Build/AvatarBuildUtils.cs b/Editor/Build/AvatarBuildUtils.cs index c3ace107..c1e78306 100644 --- a/Editor/Build/AvatarBuildUtils.cs +++ b/Editor/Build/AvatarBuildUtils.cs @@ -212,6 +212,14 @@ public static void WhiteList(Dictionary> p { foreach (var kv in phase) { kv.Value.RemoveAll(i => !whitelist.Contains(i)); } } + public static IEnumerable PhaseDictFlatten(Dictionary> phaseDict) + { + foreach (var ttb in phaseDict[TexTransPhase.BeforeUVModification]) { if (ttb is PhaseDefinition pd) { foreach (var c in FindChildren(pd)) { yield return c; } } else { yield return ttb; } } + foreach (var ttb in phaseDict[TexTransPhase.UVModification]) { if (ttb is PhaseDefinition pd) { foreach (var c in FindChildren(pd)) { yield return c; } } else { yield return ttb; } } + foreach (var ttb in phaseDict[TexTransPhase.AfterUVModification]) { if (ttb is PhaseDefinition pd) { foreach (var c in FindChildren(pd)) { yield return c; } } else { yield return ttb; } } + foreach (var ttb in phaseDict[TexTransPhase.UnDefined]) { if (ttb is PhaseDefinition pd) { foreach (var c in FindChildren(pd)) { yield return c; } } else { yield return ttb; } } + foreach (var ttb in phaseDict[TexTransPhase.Optimizing]) { if (ttb is PhaseDefinition pd) { foreach (var c in FindChildren(pd)) { yield return c; } } else { yield return ttb; } } + } private static HashSet FindChildren(TexTransGroup[] abstractTexTransGroups) { diff --git a/Editor/Inspector/Decal/AbstractDecalEditor.cs b/Editor/Inspector/Decal/AbstractDecalEditor.cs index a4a2290c..bbbd1cdd 100644 --- a/Editor/Inspector/Decal/AbstractDecalEditor.cs +++ b/Editor/Inspector/Decal/AbstractDecalEditor.cs @@ -62,37 +62,42 @@ public static void DrawerRealTimePreviewEditor(IEnumerable target { if (!target.Any()) { return; } - - if (!target.Any(RealTimePreviewManager.Contains)) + var rpm = RealTimePreviewContext.instance; + if (!rpm.IsPreview()) { bool IsPossibleRealTimePreview = !OneTimePreviewContext.IsPreviewContains; IsPossibleRealTimePreview &= !AnimationMode.InAnimationMode(); - IsPossibleRealTimePreview |= RealTimePreviewManager.IsContainsRealTimePreviewDecal; + IsPossibleRealTimePreview |= rpm.IsPreview(); EditorGUI.BeginDisabledGroup(!IsPossibleRealTimePreview); if (GUILayout.Button(IsPossibleRealTimePreview ? "SimpleDecal:button:RealTimePreview".Glc() : "Common:PreviewNotAvailable".Glc())) { OneTimePreviewContext.LastPreviewClear(); - foreach (var decal in target) { RealTimePreviewManager.instance.RegtAbstractDecal(decal); } + + var domainRoot = DomainMarkerFinder.FindMarker(target.First().gameObject); + if (domainRoot != null) + { + rpm.EnterRealtimePreview(domainRoot); + } + else + { + Debug.Log("Domain not found"); + } } EditorGUI.EndDisabledGroup(); } else { + EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField(RealTimePreviewManager.instance.LastDecalUpdateTime + "ms", GUILayout.Width(40)); + // EditorGUILayout.LabelField(RealTimePreviewManager.instance.LastDecalUpdateTime + "ms", GUILayout.Width(40)); if (GUILayout.Button("SimpleDecal:button:ExitRealTimePreview".Glc())) { - foreach (var decal in target) { RealTimePreviewManager.instance.UnRegtAbstractDecal(decal); } - } - if (RealTimePreviewManager.ContainsPreviewCount > 1 && GUILayout.Button("SimpleDecal:button:AllExit".Glc(), GUILayout.Width(60))) - { - RealTimePreviewManager.instance.ExitPreview(); + rpm.ExitRealTimePreview(); } EditorGUILayout.EndHorizontal(); } - } diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 5f2dc1c1..0fb7bf11 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -146,22 +146,22 @@ internal static void RegisterSummary() return ve; }; } - private void OnEnable() - { - foreach (var decal in targets) - { - RealTimePreviewManager.instance.ForcesDecal.Add(decal as AbstractDecal); - } - - } - - private void OnDisable() - { - foreach (var decal in targets) - { - RealTimePreviewManager.instance.ForcesDecal.Remove(decal as AbstractDecal); - } - } + // private void OnEnable() + // { + // foreach (var decal in targets) + // { + // RealTimePreviewManager.instance.ForcesDecal.Add(decal as AbstractDecal); + // } + + // } + + // private void OnDisable() + // { + // foreach (var decal in targets) + // { + // RealTimePreviewManager.instance.ForcesDecal.Remove(decal as AbstractDecal); + // } + // } diff --git a/Editor/OtherMenuItem/PreviewUtility.cs b/Editor/OtherMenuItem/PreviewUtility.cs index e8eb260e..c7b52831 100644 --- a/Editor/OtherMenuItem/PreviewUtility.cs +++ b/Editor/OtherMenuItem/PreviewUtility.cs @@ -9,7 +9,7 @@ internal class PreviewUtility [MenuItem("Tools/TexTransTool/Exit Previews")] public static void ExitPreviews() { - if (RealTimePreviewManager.IsContainsRealTimePreviewDecal) { RealTimePreviewManager.instance.ExitPreview(); return; } + if (RealTimePreviewContext.instance.IsPreview()) { RealTimePreviewContext.instance.ExitRealTimePreview(); return; } if (OneTimePreviewContext.IsPreviewContains) { OneTimePreviewContext.instance.ExitPreview(); } } [MenuItem("Tools/TexTransTool/RePreview")] @@ -19,6 +19,6 @@ public static void RePreview() } - public static bool IsPreviewContains => RealTimePreviewManager.IsContainsRealTimePreviewDecal || OneTimePreviewContext.IsPreviewContains; + public static bool IsPreviewContains => RealTimePreviewContext.instance.IsPreview() || OneTimePreviewContext.IsPreviewContains; } } diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs b/Editor/Preview/RealTime/PreviewStackManager.cs index dbc62ee0..b500675f 100644 --- a/Editor/Preview/RealTime/PreviewStackManager.cs +++ b/Editor/Preview/RealTime/PreviewStackManager.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using System.Linq; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; @@ -6,18 +8,135 @@ namespace net.rs64.TexTransTool.Preview.RealTime { internal class PreviewStackManager { + Dictionary _previewTextureMap = new(); + Dictionary _stackMap = new(); + public event Action NewPreviewTexture; + public void AddTextureStack(int priority, Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + { + switch (dist) + { + case RenderTexture rt: + { + if (_stackMap.ContainsKey(rt)) { _stackMap[rt].AddTextureStack(priority, new BlendTexturePair(setTex)); } + else { Debug.Log("Invalid RenderTexture"); } + break; + } + case Texture2D tex2D: + { + if (_previewTextureMap.ContainsKey(tex2D)) { _stackMap[_previewTextureMap[tex2D]].AddTextureStack(priority, new BlendTexturePair(setTex)); } + else + { + var newStack = new PrioritizedDeferredStack(tex2D); + _previewTextureMap[tex2D] = newStack.StackView; + _stackMap[newStack.StackView] = newStack; + NewPreviewTexture?.Invoke(tex2D, newStack.StackView); + newStack.AddTextureStack(priority, new BlendTexturePair(setTex)); + } + break; + } + } + } - public void ResetStack() + public void ReleaseStackOfPriority(int priority) { foreach (var stack in _stackMap.Values) { stack.ReleaseStackOfPriority(priority); } } + public void ReleaseStackOfTexture(Texture texture) { + switch (texture) + { + case Texture2D tex2D: + { + if (!_previewTextureMap.ContainsKey(tex2D)) { return; } + var rt = _previewTextureMap[tex2D]; + + var stack = _stackMap[rt]; + _stackMap.Remove(rt); + _previewTextureMap.Remove(tex2D); + stack.ReleaseStack(); + break; + } + case RenderTexture rt: + { + if (!_stackMap.ContainsKey(rt)) { return; } + var stack = _stackMap[rt]; + _stackMap.Remove(rt); + _previewTextureMap.Remove(_previewTextureMap.First(kv => kv.Value == rt).Key); + stack.ReleaseStack(); + break; + } + } + } + public void ReleaseStackAll() + { + foreach (var stack in _stackMap.Values) { stack.ReleaseStack(); } + _previewTextureMap.Clear(); + _stackMap.Clear(); } - } - internal class PrioritizedDeferredStack - { - Texture2D _initialTexture; - RenderTexture _stackViewTexture; + internal HashSet FindAtPriority(int priority) { return _stackMap.Keys.Where(i => _stackMap[i].ContainedPriority(priority)).ToHashSet(); } + + public RenderTexture GetPreviewTexture(Texture2D texture) + { + if (texture == null) { return null; } + if (!_previewTextureMap.ContainsKey(texture)) { return null; } + return _previewTextureMap[texture]; + } + + public void UpdateStack(RenderTexture rt) + { + if (!_stackMap.ContainsKey(rt)) { return; } + _stackMap[rt].StackViewUpdate(); + } + + internal class PrioritizedDeferredStack + { + Texture2D _initialTexture; + RenderTexture _stackViewTexture; + + + SortedList> _stack = new(); + + public RenderTexture StackView => _stackViewTexture; - + public PrioritizedDeferredStack(Texture2D initialTexture) + { + _initialTexture = initialTexture; + _stackViewTexture = RenderTexture.GetTemporary(initialTexture.width, initialTexture.height, 0); + Graphics.Blit(initialTexture, _stackViewTexture); + } + + public void AddTextureStack(int priority, BlendTexturePair blendTexturePair) + { + if (!_stack.ContainsKey(priority)) { _stack.Add(priority, new()); } + _stack[priority].Add(blendTexturePair); + } + public void ReleaseStackOfPriority(int priority) + { + if (!_stack.ContainsKey(priority)) { return; } + var cs = _stack[priority]; + + foreach (var l in cs) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); } } + cs.Clear(); + } + public void ReleaseStack() + { + RenderTexture.ReleaseTemporary(_stackViewTexture); + _stackViewTexture = null; + foreach (var ptl in _stack) + foreach (var l in ptl.Value) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); } } + + } + public void StackViewUpdate() + { + Graphics.Blit(_initialTexture, _stackViewTexture); + foreach (var ptl in _stack) + foreach (var l in ptl.Value) + { + _stackViewTexture.BlendBlit(l); + } + } + + public bool ContainedPriority(int priority) => _stack.ContainsKey(priority); + + } } } diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 6ab9160c..18a8e865 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -1,431 +1,215 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using net.rs64.TexTransCore.BlendTexture; using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransTool.Build; using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.MultiLayerImage; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Pool; using UnityEngine.Profiling; +using UnityEngine.SceneManagement; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; namespace net.rs64.TexTransTool.Preview.RealTime { - internal class RealTimePreviewManager : ScriptableSingleton + internal class RealTimePreviewContext : ScriptableSingleton { - private GameObject _previewTargetAvatarRoot = null; - private Dictionary _texTransRuntimeBehaviorPriority = new(); - private Dictionary> PreviewMaterials = new(); - private HashSet _containsBehavior = new(); - - - private Dictionary RealTimePreviews = new(); - private Dictionary PreviewMatSwapDict = new(); - private HashSet PreviewTargetRenderer = new(); - private Stopwatch stopwatch = new(); - [NonSerialized] long intervalTime = 0; - [NonSerialized] long lastUpdateTime = 0; - public long LastDecalUpdateTime => lastUpdateTime; - protected RealTimePreviewManager() + RealTimePreviewDomain _previewDomain = null; + Dictionary _texTransRuntimeBehaviorPriority = new(); + + HashSetQueue _updateQueue = new(); + + Dictionary> _dependencyAndContainsMap = new(); + + + + + protected RealTimePreviewContext() { - AssemblyReloadEvents.beforeAssemblyReload -= ExitPreview; - AssemblyReloadEvents.beforeAssemblyReload += ExitPreview; + AssemblyReloadEvents.beforeAssemblyReload -= ExitRealTimePreview; + AssemblyReloadEvents.beforeAssemblyReload += ExitRealTimePreview; EditorSceneManager.sceneClosing -= ExitPreview; EditorSceneManager.sceneClosing += ExitPreview; DestroyCall.OnDestroy -= DestroyObserve; DestroyCall.OnDestroy += DestroyObserve; } - public static int ContainsPreviewCount => instance.RealTimePreviews.Count; - public static bool IsContainsRealTimePreviewDecal => instance.RealTimePreviews.Count > 0; - public static bool IsContainsRealTimePreviewRenderer => instance.PreviewTargetRenderer.Count > 0; - public static bool Contains(AbstractDecal abstractDecal) => instance.RealTimePreviews.ContainsKey(abstractDecal); - public HashSet ForcesDecal = new(); - private void RegtRenderer(Renderer renderer) - { - if (PreviewTargetRenderer.Contains(renderer) || renderer == null) { return; } - PreviewTargetRenderer.Add(renderer); - foreach (var MatPair in PreviewMatSwapDict) - { - SwapMaterial(renderer, MatPair.Key, MatPair.Value); - } - } - - private void SwapMaterialAll(Material material, Material editableMat) - { - foreach (var renderer in PreviewTargetRenderer) - { - SwapMaterial(renderer, material, editableMat); - } - } - private void SwapMaterial(Renderer renderer, Material souse, Material target) - { - using (var serialized = new SerializedObject(renderer)) - { - foreach (SerializedProperty property in serialized.FindProperty("m_Materials")) - { - if (property.objectReferenceValue is Material material && material == souse) - { - AnimationMode.AddPropertyModification( - EditorCurveBinding.PPtrCurve("", renderer.GetType(), property.propertyPath), - new PropertyModification - { - target = renderer, - propertyPath = property.propertyPath, - objectReference = souse, - }, - true); - property.objectReferenceValue = target; - } - } - serialized.ApplyModifiedPropertiesWithoutUndo(); - } - } - private void RegtPreviewRenderTexture(Material material, string propertyName, BlendRenderTextureClass blendTexture) + public void EnterRealtimePreview(GameObject previewRoot) { - if (PreviewMatSwapDict.ContainsKey(material)) { material = PreviewMatSwapDict[material]; } + if (_previewDomain != null) { UnityEngine.Debug.Log("Already preview !!!"); return; } + if (AnimationMode.InAnimationMode()) { UnityEngine.Debug.Log("Other preview now !!!"); return; } - if (PreviewMaterials.ContainsKey(material)) - { - if (PreviewMaterials[material].ContainsKey(propertyName)) - { - PreviewMaterials[material][propertyName].DecalLayers.Add(blendTexture); - } - else//既にそのマテリアルでプレビューが存在するが、別のプロパティの場合 - { - var newTarget = RenderTexture.GetTemporary(blendTexture.RenderTexture.descriptor); - var souseTexture = material.GetTexture(propertyName) as Texture2D; - material.SetTexture(propertyName, newTarget); - - var previewIPair = new CompositePreviewInstance.PreviewTexturePair(souseTexture, newTarget); - previewIPair.ReviewReInit(); - - PreviewMaterials[material].Add(propertyName, new(previewIPair, new List() { blendTexture })); - } - } - else //そのマテリアルにプレビューが存在しない場合 つまりそのマテリアルの初回 - { - var editableMat = Instantiate(material); + AnimationMode.StartAnimationMode(); + AnimationMode.BeginSampling(); - SwapMaterialAll(material, editableMat); - PreviewMatSwapDict.Add(material, editableMat); + _previewDomain = new RealTimePreviewDomain(previewRoot); - var souseTexture = material.GetTexture(propertyName) as Texture2D; - var newTarget = RenderTexture.GetTemporary(blendTexture.RenderTexture.descriptor); - newTarget.CopyFilWrap(blendTexture.RenderTexture); + var texTransBehaviors = AvatarBuildUtils.PhaseDictFlatten(AvatarBuildUtils.FindAtPhaseAll(previewRoot)); + var priority = 0; + foreach (var ttb in texTransBehaviors) + { if (ttb is TexTransRuntimeBehavior texTransRuntimeBehavior) { _texTransRuntimeBehaviorPriority[texTransRuntimeBehavior] = priority; priority += 1; } } - editableMat.SetTexture(propertyName, newTarget); - var previewIPair = new CompositePreviewInstance.PreviewTexturePair(souseTexture, newTarget); - previewIPair.ReviewReInit(); + ObjectChangeEvents.changesPublished += ListenChangeEvent; + EditorApplication.update += UpdatePreview; - PreviewMaterials.Add(editableMat, new() { { propertyName, new(previewIPair, new List() { blendTexture }) } }); - } + foreach (var ttb in texTransBehaviors) { AddPreviewBehavior(ttb as TexTransRuntimeBehavior); } } - - private void UpdatePreviewTexture(Material material, string propertyName) + void AddPreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { - if (!PreviewMaterials.ContainsKey(material)) { return; } - if (!PreviewMaterials[material].ContainsKey(propertyName)) { return; } - - PreviewMaterials[material][propertyName].CompositeUpdate(); + switch (texTransRuntimeBehavior) + { + default: { return; } + case SimpleDecal: + case MultiLayerImageCanvas: + { break; } + } + if (ContainsBehavior(texTransRuntimeBehavior)) { return; } - } - private void PreviewStart() - { - lastUpdateTime = 0; - intervalTime = 0; - stopwatch.Stop(); - stopwatch.Reset(); - EditorApplication.update -= PreviewForcesDecalUpdate; - EditorApplication.update += PreviewForcesDecalUpdate; - } - public void ExitPreview() - { - if (IsContainsRealTimePreviewRenderer) + foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency().Append(texTransRuntimeBehavior).Select(g => g.GetInstanceID())) { - AnimationMode.StopAnimationMode(); - RealTimePreviews.Clear(); - PreviewMaterials.Clear(); - PreviewMatSwapDict.Clear(); - PreviewTargetRenderer.Clear(); - PreviewMaterials.Clear(); - - EditorApplication.update -= PreviewForcesDecalUpdate; - stopwatch.Stop(); - stopwatch.Reset(); - lastUpdateTime = 0; - intervalTime = 0; + if (!_dependencyAndContainsMap.ContainsKey(dependInstanceID)) { _dependencyAndContainsMap[dependInstanceID] = new(); } + _dependencyAndContainsMap[dependInstanceID].Add(texTransRuntimeBehavior); } + _updateQueue.Enqueue(texTransRuntimeBehavior); } - private void ExitPreview(UnityEngine.SceneManagement.Scene scene, bool removingScene) - { - ExitPreview(); - } - - public void RegtAbstractDecal(AbstractDecal abstractDecal) + void RemovePreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var depend in _dependencyAndContainsMap) { depend.Value.Remove(texTransRuntimeBehavior); } } + bool ContainsBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { - if (RealTimePreviews.Count == 0) { AnimationMode.StartAnimationMode(); PreviewStart(); } - if (RealTimePreviews.ContainsKey(abstractDecal)) { return; } - - var decalTargets = new Dictionary(); - var blends = new List(); - var TargetMats = RendererUtility.GetFilteredMaterials(abstractDecal.TargetRenderers, ListPool.Get()); - - foreach (var mat in TargetMats) + foreach (var dependKey in _dependencyAndContainsMap) { - if (mat.HasProperty(abstractDecal.TargetPropertyName) && mat.GetTexture(abstractDecal.TargetPropertyName) != null) - { - var tex = mat.GetTexture(abstractDecal.TargetPropertyName); - RenderTexture Rt = null; - switch (tex) - { - case Texture2D texture2D: - { - Rt = RenderTexture.GetTemporary(texture2D.width, texture2D.height, 0); - break; - } - case RenderTexture renderTexture://すでにプレビューが入っている場合でRenderTextureをこぴる感じ - { - Rt = RenderTexture.GetTemporary(renderTexture.descriptor); - break; - } - default: - { continue; } - } - - Rt.CopyFilWrap(tex); - - var blendTex = new BlendRenderTextureClass(Rt, abstractDecal.BlendTypeKey); - blends.Add(blendTex); - - RegtPreviewRenderTexture(mat, abstractDecal.TargetPropertyName, blendTex); - Material editableMat = PreviewMatSwapDict.ContainsKey(mat) ? PreviewMatSwapDict[mat] : mat; - - decalTargets.Add(editableMat, Rt); - } + if (dependKey.Value.Contains(texTransRuntimeBehavior)) { return true; } } - - foreach (var render in abstractDecal.GetRenderers) { RegtRenderer(render); } - - RealTimePreviews.Add(abstractDecal, new(abstractDecal.TargetPropertyName, abstractDecal.BlendTypeKey, abstractDecal.GetRenderers, blends, decalTargets)); - - ListPool.Release(TargetMats); + return false; } - - - public bool IsRealTimePreview(AbstractDecal abstractDecal) => RealTimePreviews.ContainsKey(abstractDecal); - public void UnRegtAbstractDecal(AbstractDecal abstractDecal) + void ListenChangeEvent(ref ObjectChangeEventStream stream) { - if (!IsRealTimePreview(abstractDecal)) { return; } - var absDecalData = RealTimePreviews[abstractDecal]; - - foreach (var decalTarget in absDecalData.decalTargets) + for (int i = 0; stream.length > i; i += 1) { - var mat = decalTarget.Key; - var rt = decalTarget.Value; - - if (!PreviewMaterials.ContainsKey(mat)) { continue; } - - bool RTRemoveComparer(BlendRenderTextureClass btc) => btc.RenderTexture == rt; - - var targetLayer = PreviewMaterials[mat][absDecalData.PropertyName].DecalLayers.Find(RTRemoveComparer); - PreviewMaterials[mat][absDecalData.PropertyName].DecalLayers.Remove(targetLayer); - targetLayer.Dispose(); - - - if (PreviewMaterials[mat][absDecalData.PropertyName].DecalLayers.Count == 0) + switch (stream.GetEventType(i)) { - mat.SetTexture(absDecalData.PropertyName, PreviewMaterials[mat][absDecalData.PropertyName].ViewTexture.SouseTexture); - PreviewMaterials[mat].Remove(absDecalData.PropertyName); - } - else - { - UpdatePreviewTexture(mat, absDecalData.PropertyName); - } + case ObjectChangeKind.ChangeGameObjectOrComponentProperties: + { + stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var data); + DependEnqueueOfInstanceID(data.instanceId); + break; + } + case ObjectChangeKind.ChangeGameObjectStructure: + case ObjectChangeKind.DestroyGameObjectHierarchy: + case ObjectChangeKind.ChangeChildrenOrder: + case ObjectChangeKind.ChangeGameObjectParent: + { RealTimePreviewRestart(); break; } + case ObjectChangeKind.ChangeScene: + { ExitRealTimePreview(); break; } + } } - RealTimePreviews.Remove(abstractDecal); - if (RealTimePreviews.Count == 0) { ExitPreview(); } - } - - public void UpdateAbstractDecal(AbstractDecal abstractDecal) - { - if (!RealTimePreviews.ContainsKey(abstractDecal)) { return; } - var absDecalData = RealTimePreviews[abstractDecal]; - - if (absDecalData.PropertyName != abstractDecal.TargetPropertyName - || !absDecalData.RendererEqual(abstractDecal.GetRenderers)) + void DependEnqueueOfInstanceID(int instanceId) { - Profiler.BeginSample("Reregister decal"); - UnRegtAbstractDecal(abstractDecal); RegtAbstractDecal(abstractDecal); - Profiler.EndSample(); + if (_dependencyAndContainsMap.ContainsKey(instanceId)) + { + foreach (var t in _dependencyAndContainsMap[instanceId]) { _updateQueue.Enqueue(t); } + } } - - if (absDecalData.BlendTypeKey != abstractDecal.BlendTypeKey) - { absDecalData.SetBlendTypeKey(abstractDecal.BlendTypeKey); } - - - Profiler.BeginSample("Clear and compile decal"); - absDecalData.ClearDecalTarget(); - abstractDecal.CompileDecal(new TextureManager(true), absDecalData.decalTargets); - Profiler.EndSample(); - } - - public void PreviewForcesDecalUpdate() - { - if (ForcesDecal == null) { return; } - - if (!ForcesDecal.Any(Contains)) { return; } - - if (stopwatch.IsRunning)//intervalTimeがあるのにストップウォッチが進んでないケースは強制的にアップデートする + void RealTimePreviewRestart() { - if (intervalTime > stopwatch.ElapsedMilliseconds) { return; } - stopwatch.Stop(); - } - - stopwatch.Restart(); - foreach (var decal in ForcesDecal) { UpdateAbstractDecal(decal); } - Profiler.BeginSample("Update preview texture"); - foreach (var mk in ForcesDecal - .Where(i => RealTimePreviews.ContainsKey(i)) - .SelectMany(i => RealTimePreviews[i].decalTargets.Keys.Select(m => (RealTimePreviews[i].PropertyName, m))) - .Distinct() - ) - { - UpdatePreviewTexture(mk.m, mk.PropertyName); } - Profiler.EndSample(); - - stopwatch.Stop(); - - lastUpdateTime = stopwatch.ElapsedMilliseconds; - intervalTime = lastUpdateTime * lastUpdateTime; - if (intervalTime > 4096) { intervalTime = 4096; } - - stopwatch.Restart(); } - - public class BlendRenderTextureClass : IBlendTexturePair, IDisposable + void UpdatePreview() { - public RenderTexture RenderTexture; - public string BlendTypeKey; - - public BlendRenderTextureClass(RenderTexture renderTexture, string blendTypeKey) + if (_updateQueue.TryDequeue(out var texTransRuntimeBehavior) && _texTransRuntimeBehaviorPriority.TryGetValue(texTransRuntimeBehavior, out var priority)) { - RenderTexture = renderTexture; - BlendTypeKey = blendTypeKey; - } + _previewDomain.NowPriority = priority; + _previewDomain.PreviewStackManager.ReleaseStackOfPriority(priority); - public Texture Texture => RenderTexture; - string IBlendTexturePair.BlendTypeKey => BlendTypeKey; + texTransRuntimeBehavior.Apply(_previewDomain); - public void Dispose() - { - RenderTexture.ReleaseTemporary(RenderTexture); + _previewDomain.UpdateNeeded(); + _previewDomain.NowPriority = -1; } } - internal struct DecalTargetInstance - { - public string PropertyName; - public string BlendTypeKey; - public List TargetRenderers; - public List blendTextureList; - public Dictionary decalTargets;//CompileDealの型合わせ - public DecalTargetInstance(string propertyName, string blendTypeKey, List targetRenderers, List blendTextureList, Dictionary decalTargets) - { - PropertyName = propertyName; - BlendTypeKey = blendTypeKey; - TargetRenderers = new(targetRenderers); - this.blendTextureList = blendTextureList; - this.decalTargets = decalTargets; - } - public void ClearDecalTarget() - { - foreach (var target in decalTargets) - { target.Value.Clear(); } - } - public void SetBlendTypeKey(string blendTypeKey) - { - BlendTypeKey = blendTypeKey; - foreach (var blendData in blendTextureList) - { blendData.BlendTypeKey = BlendTypeKey; } + private void ExitPreview(Scene scene, bool removingScene) => ExitRealTimePreview(); + public void ExitRealTimePreview() + { + if (_previewDomain == null) { return; } + ObjectChangeEvents.changesPublished -= ListenChangeEvent; + EditorApplication.update -= UpdatePreview; - } + _texTransRuntimeBehaviorPriority.Clear(); + _dependencyAndContainsMap.Clear(); + _updateQueue.Clear(); + _previewDomain.PreviewExit(); + _previewDomain = null; + AnimationMode.EndSampling(); + AnimationMode.StopAnimationMode(); + } - public bool RendererEqual(List renderers) - { - var count = TargetRenderers.Count; - var nCount = renderers.Count; + private void DestroyObserve(TexTransBehavior behavior) + { + if (_previewDomain == null) { return; } + var runtimeBehavior = behavior as TexTransRuntimeBehavior; + if (runtimeBehavior == null) { return; } + if (!ContainsBehavior(runtimeBehavior)) { return; } - if (count != nCount) { return false; } + var stackManager = _previewDomain.PreviewStackManager; + var updateTarget = stackManager.FindAtPriority(_texTransRuntimeBehaviorPriority[runtimeBehavior]); + stackManager.ReleaseStackOfPriority(_texTransRuntimeBehaviorPriority[runtimeBehavior]); + foreach (var tex in updateTarget) { stackManager.UpdateStack(tex); } + } - for (var i = 0; count > i; i += 1) - { - if (TargetRenderers[i] != renderers[i]) { return false; } - } + public bool IsPreview() => _previewDomain != null; + } - return true; - } + internal class HashSetQueue : IEnumerable + { + HashSet _hash = new(); + Queue _queue = new(); + public bool Enqueue(T item) + { + if (_hash.Contains(item)) return false; + _hash.Add(item); + _queue.Enqueue(item); + return true; } - internal struct CompositePreviewInstance + public T Dequeue() { - public PreviewTexturePair ViewTexture; - public List DecalLayers; - - public void CompositeUpdate() - { - ViewTexture.ReviewReInit(); - ViewTexture.TargetTexture.BlendBlit(DecalLayers); - } - - public CompositePreviewInstance(PreviewTexturePair viewTex, List decals) - { - ViewTexture = viewTex; - DecalLayers = decals; - } - internal struct PreviewTexturePair - { - public Texture2D SouseTexture; - public RenderTexture TargetTexture; - - public void ReviewReInit() - { - Profiler.BeginSample("ReviewReInit"); - TargetTexture.Clear(); - Graphics.Blit(SouseTexture, TargetTexture); - Profiler.EndSample(); - } - - public PreviewTexturePair(Texture2D souseTexture, RenderTexture targetTexture) - { - SouseTexture = souseTexture; - TargetTexture = targetTexture; - } - } + var item = _queue.Dequeue(); + _hash.Remove(item); + return item; + } + public bool TryDequeue(out T item) + { + if (_queue.TryDequeue(out item)) { _hash.Remove(item); return true; } + return false; } + public T Peek() { return _queue.Peek(); } - public void DestroyObserve(TexTransBehavior behavior) + public void Clear() { - if (behavior is AbstractDecal abstractDecal && Contains(abstractDecal)) { UnRegtAbstractDecal(abstractDecal); } + _hash.Clear(); + _queue.Clear(); } - + public IEnumerator GetEnumerator() { return _queue.GetEnumerator(); } + IEnumerator IEnumerable.GetEnumerator() { return _queue.GetEnumerator(); } } } diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs index ef72a428..44bf979e 100644 --- a/Editor/Preview/RealTime/RealTimePreviewDomain.cs +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -17,26 +17,117 @@ namespace net.rs64.TexTransTool.Preview.RealTime internal class RealTimePreviewDomain : IDomain { GameObject _domainRoot; - HashSet domainRenderers; + HashSet _domainRenderers = new(); ITextureManager _textureManager = new TextureManager(true); - PreviewStackManager _stackManager; - public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + PreviewStackManager _stackManager = new(); + Dictionary _previewMaterialMap = new(); + public RealTimePreviewDomain(GameObject domainRoot) { - // _stackManager + _domainRoot = domainRoot; + _stackManager.NewPreviewTexture += NewPreviewTextureRegister; + DomainRenderersUpdate(); } + public PreviewStackManager PreviewStackManager => _stackManager; + public int NowPriority { get; set; } + HashSet needUpdate = new(); + public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + { + _stackManager.AddTextureStack(NowPriority, dist, setTex); + if (dist is Texture2D texture2D) { needUpdate.Add(_stackManager.GetPreviewTexture(texture2D)); } + if (dist is RenderTexture rt) { needUpdate.Add(rt); } + } + public void UpdateNeeded() + { + foreach (var rt in needUpdate) { _stackManager.UpdateStack(rt); } + needUpdate.Clear(); + } + public void DomainRenderersUpdate() + { + _domainRenderers.Clear(); + _domainRenderers.UnionWith(_domainRoot.GetComponentsInChildren(true)); + SwapPreviewMaterial(); + } + public void SwapPreviewMaterial() + { + foreach (var renderer in _domainRenderers) + { + using (var serialized = new SerializedObject(renderer)) + { + foreach (SerializedProperty property in serialized.FindProperty("m_Materials")) + { + if (property.objectReferenceValue is not Material material) { continue; } + if (_previewMaterialMap.TryGetValue(material, out var replacement)) + { + SetAsAnimation(property, replacement); + } + else + { + var prevMat = _previewMaterialMap[material] = UnityEngine.Object.Instantiate(material); + SetAsAnimation(property, prevMat); + ApplyPreviewTexture(prevMat); + } + } + serialized.ApplyModifiedPropertiesWithoutUndo(); + } + } + + static void SetAsAnimation(SerializedProperty property, Material replacement) + { + AnimationMode.AddPropertyModification( + EditorCurveBinding.PPtrCurve("", property.serializedObject.targetObject.GetType(), property.propertyPath), + new PropertyModification + { + target = property.serializedObject.targetObject, + propertyPath = property.propertyPath, + objectReference = property.objectReferenceValue, + }, + true); + property.objectReferenceValue = replacement; + } + } + public void NewPreviewTextureRegister(Texture2D texture2D, RenderTexture previewTexture) + { + foreach (var m in _previewMaterialMap.Values) + { + var shader = m.shader; + for (int i = 0; shader.GetPropertyCount() > i; i += 1) + { + if (shader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture) { continue; } + var nameID = shader.GetPropertyNameId(i); + if (m.GetTexture(nameID) == texture2D) { m.SetTexture(nameID, previewTexture); } + } + } + } + public void ApplyPreviewTexture(Material material) + { + var shader = material.shader; + for (int i = 0; shader.GetPropertyCount() > i; i += 1) + { + if (shader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture) { continue; } + var nameID = shader.GetPropertyNameId(i); + var prevTex = _stackManager.GetPreviewTexture(material.GetTexture(nameID) as Texture2D); + if (prevTex != null) { material.SetTexture(nameID, prevTex); } + } + } + public void PreviewExit() + { + foreach (var m in _previewMaterialMap.Values) { UnityEngine.Object.DestroyImmediate(m); } + _previewMaterialMap.Clear(); + _stackManager.ReleaseStackAll(); + } - public IEnumerable EnumerateRenderer() { return domainRenderers; } + public IEnumerable EnumerateRenderer() { return _domainRenderers; } public ITextureManager GetTextureManager() => _textureManager; public bool IsPreview() => true; diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index 15846d9f..b6bd255c 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -268,6 +268,12 @@ public struct BlendTexturePair : IBlendTexturePair public Texture Texture; public string BlendTypeKey; + public BlendTexturePair(IBlendTexturePair setTex) + { + Texture = setTex.Texture; + BlendTypeKey = setTex.BlendTypeKey; + } + public BlendTexturePair(Texture texture, string blendTypeKey) { Texture = texture; From df47653752efbcb53111acea277196756d22c2a0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 24 Apr 2024 21:20:48 +0900 Subject: [PATCH 105/208] fix: Decal dependency has parent transform --- Runtime/Decal/AbstractDecal.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Runtime/Decal/AbstractDecal.cs b/Runtime/Decal/AbstractDecal.cs index 808ae9de..832d560d 100644 --- a/Runtime/Decal/AbstractDecal.cs +++ b/Runtime/Decal/AbstractDecal.cs @@ -88,7 +88,8 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan internal override IEnumerable GetDependency() { - return new UnityEngine.Object[]{transform} + return new UnityEngine.Object[] { transform } + .Concat(GetComponentsInParent(true)) .Concat(TargetRenderers) .Concat(TargetRenderers.Select(r => r.transform)) .Concat(TargetRenderers.Select(r => r.GetMesh())) From 09347a08a379b2ddd7ccaf2a7c81ef2f4013955d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 24 Apr 2024 21:56:11 +0900 Subject: [PATCH 106/208] fix: a not execute update --- Editor/TTTInitializer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/TTTInitializer.cs b/Editor/TTTInitializer.cs index f7fe8b25..c362a43b 100644 --- a/Editor/TTTInitializer.cs +++ b/Editor/TTTInitializer.cs @@ -23,7 +23,7 @@ static void EditorInitDerayCaller() [UnityEditor.InitializeOnEnterPlayMode] public static void Initialize() { - UnityEditor.EditorApplication.update += TexTransCoreRuntime.Update.Invoke; + UnityEditor.EditorApplication.update += () => { TexTransCoreRuntime.Update.Invoke(); }; TexTransCoreRuntime.LoadAsset = (guid, type) => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), type); TexTransCoreRuntime.LoadAssetsAtType = (type) => { From b3a9d9f66b88cd1b7838b031489d2d585c4fd2dc Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 24 Apr 2024 21:56:48 +0900 Subject: [PATCH 107/208] chore: remove unused using on memoize --- TexTransCore/Memoize.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/TexTransCore/Memoize.cs b/TexTransCore/Memoize.cs index 660f344b..19cbd412 100644 --- a/TexTransCore/Memoize.cs +++ b/TexTransCore/Memoize.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; -using UnityEditor; namespace net.rs64.TexTransCore { From ffa48c7ec0e6bd055273d1d4786d6f3efeb90f44 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 18:07:11 +0900 Subject: [PATCH 108/208] feat: implement preview restart --- .../RealTime/RealTimePreviewContext.cs | 24 ++++++++++++------- .../Preview/RealTime/RealTimePreviewDomain.cs | 1 + 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 18a8e865..4d52e5fb 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -22,10 +22,8 @@ internal class RealTimePreviewContext : ScriptableSingleton _texTransRuntimeBehaviorPriority = new(); - - HashSetQueue _updateQueue = new(); - Dictionary> _dependencyAndContainsMap = new(); + HashSetQueue _updateQueue = new(); @@ -34,8 +32,8 @@ protected RealTimePreviewContext() { AssemblyReloadEvents.beforeAssemblyReload -= ExitRealTimePreview; AssemblyReloadEvents.beforeAssemblyReload += ExitRealTimePreview; - EditorSceneManager.sceneClosing -= ExitPreview; - EditorSceneManager.sceneClosing += ExitPreview; + EditorSceneManager.sceneClosing -= ExitRealTimePreview; + EditorSceneManager.sceneClosing += ExitRealTimePreview; DestroyCall.OnDestroy -= DestroyObserve; DestroyCall.OnDestroy += DestroyObserve; } @@ -103,10 +101,18 @@ void ListenChangeEvent(ref ObjectChangeEventStream stream) DependEnqueueOfInstanceID(data.instanceId); break; } + case ObjectChangeKind.ChangeAssetObjectProperties: + { + stream.GetChangeAssetObjectPropertiesEvent(i, out var data); + DependEnqueueOfInstanceID(data.instanceId); + break; + } + + case ObjectChangeKind.CreateGameObjectHierarchy: + case ObjectChangeKind.ChangeGameObjectParent: case ObjectChangeKind.ChangeGameObjectStructure: case ObjectChangeKind.DestroyGameObjectHierarchy: case ObjectChangeKind.ChangeChildrenOrder: - case ObjectChangeKind.ChangeGameObjectParent: { RealTimePreviewRestart(); break; } case ObjectChangeKind.ChangeScene: { ExitRealTimePreview(); break; } @@ -123,7 +129,9 @@ void DependEnqueueOfInstanceID(int instanceId) } void RealTimePreviewRestart() { - + var domainRoot = _previewDomain.DomainRoot; + ExitRealTimePreview(); + EnterRealtimePreview(domainRoot); } } @@ -143,7 +151,7 @@ void UpdatePreview() - private void ExitPreview(Scene scene, bool removingScene) => ExitRealTimePreview(); + private void ExitRealTimePreview(Scene scene, bool removingScene) => ExitRealTimePreview(); public void ExitRealTimePreview() { if (_previewDomain == null) { return; } diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs index 44bf979e..8a001ad2 100644 --- a/Editor/Preview/RealTime/RealTimePreviewDomain.cs +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -28,6 +28,7 @@ public RealTimePreviewDomain(GameObject domainRoot) DomainRenderersUpdate(); } + public GameObject DomainRoot => _domainRoot; public PreviewStackManager PreviewStackManager => _stackManager; public int NowPriority { get; set; } HashSet needUpdate = new(); From f62b73a933c85c6809a7f57e56f44fd2c75e9715 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 19:08:38 +0900 Subject: [PATCH 109/208] chore: fine adjustment --- .../Preview/RealTime/PreviewStackManager.cs | 16 ++++-- .../RealTime/RealTimePreviewContext.cs | 52 ++++++------------- .../Preview/RealTime/RealTimePreviewDomain.cs | 29 +++++------ 3 files changed, 40 insertions(+), 57 deletions(-) diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs b/Editor/Preview/RealTime/PreviewStackManager.cs index b500675f..c60351aa 100644 --- a/Editor/Preview/RealTime/PreviewStackManager.cs +++ b/Editor/Preview/RealTime/PreviewStackManager.cs @@ -81,10 +81,14 @@ public RenderTexture GetPreviewTexture(Texture2D texture) return _previewTextureMap[texture]; } - public void UpdateStack(RenderTexture rt) + + public void UpdateNeededStack() { - if (!_stackMap.ContainsKey(rt)) { return; } - _stackMap[rt].StackViewUpdate(); + foreach (var stack in _stackMap.Values) + { + if (!stack.UpdateNeeded) { continue; } + stack.StackViewUpdate(); + } } internal class PrioritizedDeferredStack @@ -92,7 +96,7 @@ internal class PrioritizedDeferredStack Texture2D _initialTexture; RenderTexture _stackViewTexture; - + public bool UpdateNeeded { get; private set; } = false; SortedList> _stack = new(); public RenderTexture StackView => _stackViewTexture; @@ -108,13 +112,14 @@ public void AddTextureStack(int priority, BlendTexturePair blendTexturePair) { if (!_stack.ContainsKey(priority)) { _stack.Add(priority, new()); } _stack[priority].Add(blendTexturePair); + UpdateNeeded = true; } public void ReleaseStackOfPriority(int priority) { if (!_stack.ContainsKey(priority)) { return; } var cs = _stack[priority]; - foreach (var l in cs) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); } } + foreach (var l in cs) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); UpdateNeeded = true; } } cs.Clear(); } public void ReleaseStack() @@ -133,6 +138,7 @@ public void StackViewUpdate() { _stackViewTexture.BlendBlit(l); } + UpdateNeeded = false; } public bool ContainedPriority(int priority) => _stack.ContainsKey(priority); diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 4d52e5fb..8c3225be 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -1,28 +1,22 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.Build; using net.rs64.TexTransTool.Decal; using net.rs64.TexTransTool.MultiLayerImage; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; -using UnityEngine.Pool; -using UnityEngine.Profiling; using UnityEngine.SceneManagement; -using static net.rs64.TexTransCore.BlendTexture.TextureBlend; namespace net.rs64.TexTransTool.Preview.RealTime { internal class RealTimePreviewContext : ScriptableSingleton { RealTimePreviewDomain _previewDomain = null; - Dictionary _texTransRuntimeBehaviorPriority = new(); - Dictionary> _dependencyAndContainsMap = new(); + Dictionary _PriorityMap = new(); + Dictionary> _dependencyMap = new(); HashSetQueue _updateQueue = new(); @@ -34,8 +28,6 @@ protected RealTimePreviewContext() AssemblyReloadEvents.beforeAssemblyReload += ExitRealTimePreview; EditorSceneManager.sceneClosing -= ExitRealTimePreview; EditorSceneManager.sceneClosing += ExitRealTimePreview; - DestroyCall.OnDestroy -= DestroyObserve; - DestroyCall.OnDestroy += DestroyObserve; } @@ -52,7 +44,7 @@ public void EnterRealtimePreview(GameObject previewRoot) var texTransBehaviors = AvatarBuildUtils.PhaseDictFlatten(AvatarBuildUtils.FindAtPhaseAll(previewRoot)); var priority = 0; foreach (var ttb in texTransBehaviors) - { if (ttb is TexTransRuntimeBehavior texTransRuntimeBehavior) { _texTransRuntimeBehaviorPriority[texTransRuntimeBehavior] = priority; priority += 1; } } + { if (ttb is TexTransRuntimeBehavior texTransRuntimeBehavior) { _PriorityMap[texTransRuntimeBehavior] = priority; priority += 1; } } ObjectChangeEvents.changesPublished += ListenChangeEvent; @@ -74,15 +66,15 @@ void AddPreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency().Append(texTransRuntimeBehavior).Select(g => g.GetInstanceID())) { - if (!_dependencyAndContainsMap.ContainsKey(dependInstanceID)) { _dependencyAndContainsMap[dependInstanceID] = new(); } - _dependencyAndContainsMap[dependInstanceID].Add(texTransRuntimeBehavior); + if (!_dependencyMap.ContainsKey(dependInstanceID)) { _dependencyMap[dependInstanceID] = new(); } + _dependencyMap[dependInstanceID].Add(texTransRuntimeBehavior); } _updateQueue.Enqueue(texTransRuntimeBehavior); } - void RemovePreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var depend in _dependencyAndContainsMap) { depend.Value.Remove(texTransRuntimeBehavior); } } + void RemovePreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var depend in _dependencyMap) { depend.Value.Remove(texTransRuntimeBehavior); } } bool ContainsBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { - foreach (var dependKey in _dependencyAndContainsMap) + foreach (var dependKey in _dependencyMap) { if (dependKey.Value.Contains(texTransRuntimeBehavior)) { return true; } } @@ -122,9 +114,9 @@ void ListenChangeEvent(ref ObjectChangeEventStream stream) void DependEnqueueOfInstanceID(int instanceId) { - if (_dependencyAndContainsMap.ContainsKey(instanceId)) + if (_dependencyMap.ContainsKey(instanceId)) { - foreach (var t in _dependencyAndContainsMap[instanceId]) { _updateQueue.Enqueue(t); } + foreach (var t in _dependencyMap[instanceId]) { _updateQueue.Enqueue(t); } } } void RealTimePreviewRestart() @@ -137,15 +129,14 @@ void RealTimePreviewRestart() void UpdatePreview() { - if (_updateQueue.TryDequeue(out var texTransRuntimeBehavior) && _texTransRuntimeBehaviorPriority.TryGetValue(texTransRuntimeBehavior, out var priority)) + if (_updateQueue.TryDequeue(out var texTransRuntimeBehavior) && _PriorityMap.TryGetValue(texTransRuntimeBehavior, out var priority)) { - _previewDomain.NowPriority = priority; - _previewDomain.PreviewStackManager.ReleaseStackOfPriority(priority); + _previewDomain.SetNowPriority(priority); - texTransRuntimeBehavior.Apply(_previewDomain); + try { if (texTransRuntimeBehavior.IsPossibleApply) { texTransRuntimeBehavior.Apply(_previewDomain); } } + catch (Exception ex) { Debug.LogException(ex); } _previewDomain.UpdateNeeded(); - _previewDomain.NowPriority = -1; } } @@ -158,8 +149,8 @@ public void ExitRealTimePreview() ObjectChangeEvents.changesPublished -= ListenChangeEvent; EditorApplication.update -= UpdatePreview; - _texTransRuntimeBehaviorPriority.Clear(); - _dependencyAndContainsMap.Clear(); + _PriorityMap.Clear(); + _dependencyMap.Clear(); _updateQueue.Clear(); _previewDomain.PreviewExit(); _previewDomain = null; @@ -167,18 +158,7 @@ public void ExitRealTimePreview() AnimationMode.StopAnimationMode(); } - private void DestroyObserve(TexTransBehavior behavior) - { - if (_previewDomain == null) { return; } - var runtimeBehavior = behavior as TexTransRuntimeBehavior; - if (runtimeBehavior == null) { return; } - if (!ContainsBehavior(runtimeBehavior)) { return; } - - var stackManager = _previewDomain.PreviewStackManager; - var updateTarget = stackManager.FindAtPriority(_texTransRuntimeBehaviorPriority[runtimeBehavior]); - stackManager.ReleaseStackOfPriority(_texTransRuntimeBehaviorPriority[runtimeBehavior]); - foreach (var tex in updateTarget) { stackManager.UpdateStack(tex); } - } + public bool IsPreview() => _previewDomain != null; } diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs index 8a001ad2..da75fd4f 100644 --- a/Editor/Preview/RealTime/RealTimePreviewDomain.cs +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -25,35 +25,32 @@ public RealTimePreviewDomain(GameObject domainRoot) { _domainRoot = domainRoot; _stackManager.NewPreviewTexture += NewPreviewTextureRegister; - DomainRenderersUpdate(); + + _domainRenderers.Clear(); + _domainRenderers.UnionWith(_domainRoot.GetComponentsInChildren(true)); + SwapPreviewMaterial(); } public GameObject DomainRoot => _domainRoot; - public PreviewStackManager PreviewStackManager => _stackManager; - public int NowPriority { get; set; } - HashSet needUpdate = new(); + int _nowPriority; - public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + public void SetNowPriority(int priority) { - _stackManager.AddTextureStack(NowPriority, dist, setTex); + _nowPriority = priority; + _stackManager.ReleaseStackOfPriority(_nowPriority); + } - if (dist is Texture2D texture2D) { needUpdate.Add(_stackManager.GetPreviewTexture(texture2D)); } - if (dist is RenderTexture rt) { needUpdate.Add(rt); } + public void AddTextureStack(Texture dist, BlendTex setTex) where BlendTex : IBlendTexturePair + { + _stackManager.AddTextureStack(_nowPriority, dist, setTex); } public void UpdateNeeded() { - foreach (var rt in needUpdate) { _stackManager.UpdateStack(rt); } - needUpdate.Clear(); + _stackManager.UpdateNeededStack(); } - public void DomainRenderersUpdate() - { - _domainRenderers.Clear(); - _domainRenderers.UnionWith(_domainRoot.GetComponentsInChildren(true)); - SwapPreviewMaterial(); - } public void SwapPreviewMaterial() { foreach (var renderer in _domainRenderers) From ad4c0760a015600ec20e3a9776b1db01c42699d3 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 19:29:04 +0900 Subject: [PATCH 110/208] chore: replace DrawerRealTimePreviewEditorButton --- Editor/Inspector/Decal/AbstractDecalEditor.cs | 50 ------------------- Editor/Inspector/Decal/SimpleDecalEditor.cs | 33 +----------- .../MultiLayerImageCanvasEditor.cs | 5 +- Editor/Inspector/TextureTransformerEditor.cs | 43 ++++++++++++++++ 4 files changed, 47 insertions(+), 84 deletions(-) diff --git a/Editor/Inspector/Decal/AbstractDecalEditor.cs b/Editor/Inspector/Decal/AbstractDecalEditor.cs index bbbd1cdd..81808aaf 100644 --- a/Editor/Inspector/Decal/AbstractDecalEditor.cs +++ b/Editor/Inspector/Decal/AbstractDecalEditor.cs @@ -48,57 +48,7 @@ public static void DrawerDecalEditor(SerializedObject thisSObject) EditorGUILayout.PropertyField(sTargetPropertyName, "CommonDecal:prop:TargetPropertyName".Glc()); EditorGUI.indentLevel -= 1; } - public static void DrawerRealTimePreviewEditor(object[] target) - { - var list = ListPool.Get(); list.Capacity = target.Length; - foreach (var decal in target) - { if (decal is AbstractDecal abstractDecal) { list.Add(abstractDecal); } } - - DrawerRealTimePreviewEditor(list); - - ListPool.Release(list); - } - public static void DrawerRealTimePreviewEditor(IEnumerable target) - { - if (!target.Any()) { return; } - - var rpm = RealTimePreviewContext.instance; - if (!rpm.IsPreview()) - { - bool IsPossibleRealTimePreview = !OneTimePreviewContext.IsPreviewContains; - IsPossibleRealTimePreview &= !AnimationMode.InAnimationMode(); - IsPossibleRealTimePreview |= rpm.IsPreview(); - - EditorGUI.BeginDisabledGroup(!IsPossibleRealTimePreview); - if (GUILayout.Button(IsPossibleRealTimePreview ? "SimpleDecal:button:RealTimePreview".Glc() : "Common:PreviewNotAvailable".Glc())) - { - OneTimePreviewContext.LastPreviewClear(); - - var domainRoot = DomainMarkerFinder.FindMarker(target.First().gameObject); - if (domainRoot != null) - { - rpm.EnterRealtimePreview(domainRoot); - } - else - { - Debug.Log("Domain not found"); - } - } - EditorGUI.EndDisabledGroup(); - } - else - { - EditorGUILayout.BeginHorizontal(); - // EditorGUILayout.LabelField(RealTimePreviewManager.instance.LastDecalUpdateTime + "ms", GUILayout.Width(40)); - - if (GUILayout.Button("SimpleDecal:button:ExitRealTimePreview".Glc())) - { - rpm.ExitRealTimePreview(); - } - EditorGUILayout.EndHorizontal(); - } - } static bool FoldoutAdvancedOption; diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 0fb7bf11..0c187495 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -66,14 +66,7 @@ public override void OnInspectorGUI() } - AbstractDecalEditor.DrawerRealTimePreviewEditor(targets); - - // if (!isMultiEdit) - // { - // EditorGUI.BeginDisabledGroup(RealTimePreviewManager.Contains(thisObject)); - // PreviewContext.instance.DrawApplyAndRevert(thisObject); - // EditorGUI.EndDisabledGroup(); - // } + TextureTransformerEditor.DrawerRealTimePreviewEditorButton(target as TexTransRuntimeBehavior); thisSObject.ApplyModifiedProperties(); } @@ -146,30 +139,6 @@ internal static void RegisterSummary() return ve; }; } - // private void OnEnable() - // { - // foreach (var decal in targets) - // { - // RealTimePreviewManager.instance.ForcesDecal.Add(decal as AbstractDecal); - // } - - // } - - // private void OnDisable() - // { - // foreach (var decal in targets) - // { - // RealTimePreviewManager.instance.ForcesDecal.Remove(decal as AbstractDecal); - // } - // } - - - - - - - - public void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) { diff --git a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs index fccec0a3..b2debba1 100644 --- a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs +++ b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs @@ -16,12 +16,13 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(sTarget.FindProperty("TextureSelector")); var thisTarget = target as MultiLayerImageCanvas; - OneTimePreviewContext.instance.DrawApplyAndRevert(thisTarget); + TextureTransformerEditor.DrawerRealTimePreviewEditorButton(thisTarget); + sTarget.ApplyModifiedProperties(); } - public override bool HasPreviewGUI() { return true; } + public override bool HasPreviewGUI() { return false; } public override void DrawPreview(Rect previewArea) { diff --git a/Editor/Inspector/TextureTransformerEditor.cs b/Editor/Inspector/TextureTransformerEditor.cs index a9b7886f..6f263638 100644 --- a/Editor/Inspector/TextureTransformerEditor.cs +++ b/Editor/Inspector/TextureTransformerEditor.cs @@ -2,6 +2,7 @@ using UnityEditor; using System.Linq; using net.rs64.TexTransTool.Preview; +using net.rs64.TexTransTool.Preview.RealTime; namespace net.rs64.TexTransTool.Editor { @@ -76,6 +77,48 @@ public static void DrawerRenderer(SerializedProperty sRendererList, GUIContent l } } + + public static void DrawerRealTimePreviewEditorButton(TexTransRuntimeBehavior texTransRuntimeBehavior) + { + if(texTransRuntimeBehavior == null){return;} + var rpm = RealTimePreviewContext.instance; + if (!rpm.IsPreview()) + { + bool IsPossibleRealTimePreview = !OneTimePreviewContext.IsPreviewContains; + IsPossibleRealTimePreview &= !AnimationMode.InAnimationMode(); + IsPossibleRealTimePreview |= rpm.IsPreview(); + + EditorGUI.BeginDisabledGroup(!IsPossibleRealTimePreview); + if (GUILayout.Button(IsPossibleRealTimePreview ? "SimpleDecal:button:RealTimePreview".Glc() : "Common:PreviewNotAvailable".Glc())) + { + OneTimePreviewContext.LastPreviewClear(); + + var domainRoot = DomainMarkerFinder.FindMarker(texTransRuntimeBehavior.gameObject); + if (domainRoot != null) + { + rpm.EnterRealtimePreview(domainRoot); + } + else + { + Debug.Log("Domain not found"); + } + } + EditorGUI.EndDisabledGroup(); + } + else + { + EditorGUILayout.BeginHorizontal(); + // EditorGUILayout.LabelField(RealTimePreviewManager.instance.LastDecalUpdateTime + "ms", GUILayout.Width(40)); + + if (GUILayout.Button("SimpleDecal:button:ExitRealTimePreview".Glc())) + { + rpm.ExitRealTimePreview(); + } + EditorGUILayout.EndHorizontal(); + } + } + + #region DrawerProperty public delegate T Filter(T Target); From af11325c618831e915b45c4186ff8ac44eaa0279 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 19:46:16 +0900 Subject: [PATCH 111/208] improve: RePreview --- Editor/Inspector/TextureTransformerEditor.cs | 2 -- Editor/OtherMenuItem/PreviewUtility.cs | 12 +++++++-- Editor/Preview/OneTimePreviewContext.cs | 25 ++++++------------- .../RealTime/RealTimePreviewContext.cs | 6 +++++ 4 files changed, 24 insertions(+), 21 deletions(-) diff --git a/Editor/Inspector/TextureTransformerEditor.cs b/Editor/Inspector/TextureTransformerEditor.cs index 6f263638..c45b47ad 100644 --- a/Editor/Inspector/TextureTransformerEditor.cs +++ b/Editor/Inspector/TextureTransformerEditor.cs @@ -91,8 +91,6 @@ public static void DrawerRealTimePreviewEditorButton(TexTransRuntimeBehavior tex EditorGUI.BeginDisabledGroup(!IsPossibleRealTimePreview); if (GUILayout.Button(IsPossibleRealTimePreview ? "SimpleDecal:button:RealTimePreview".Glc() : "Common:PreviewNotAvailable".Glc())) { - OneTimePreviewContext.LastPreviewClear(); - var domainRoot = DomainMarkerFinder.FindMarker(texTransRuntimeBehavior.gameObject); if (domainRoot != null) { diff --git a/Editor/OtherMenuItem/PreviewUtility.cs b/Editor/OtherMenuItem/PreviewUtility.cs index c7b52831..4ceaba9b 100644 --- a/Editor/OtherMenuItem/PreviewUtility.cs +++ b/Editor/OtherMenuItem/PreviewUtility.cs @@ -1,3 +1,4 @@ +using System; using net.rs64.TexTransTool.Preview; using net.rs64.TexTransTool.Preview.RealTime; using UnityEditor; @@ -6,6 +7,7 @@ namespace net.rs64.TexTransTool.Editor.OtherMenuItem { internal class PreviewUtility { + static Action s_rePreviewActin; [MenuItem("Tools/TexTransTool/Exit Previews")] public static void ExitPreviews() { @@ -15,10 +17,16 @@ public static void ExitPreviews() [MenuItem("Tools/TexTransTool/RePreview")] public static void RePreview() { - OneTimePreviewContext.instance.RePreview(); - + ExitPreviews(); + s_rePreviewActin?.Invoke(); } public static bool IsPreviewContains => RealTimePreviewContext.instance.IsPreview() || OneTimePreviewContext.IsPreviewContains; + [TexTransCore.TexTransInitialize] + public static void Init() + { + OneTimePreviewContext.instance.OnPreviewEnter += ttb => { s_rePreviewActin = () => { if (ttb is TexTransBehavior texTransBehavior) { OneTimePreviewContext.instance.ApplyTexTransBehavior(texTransBehavior); } }; }; + RealTimePreviewContext.instance.OnPreviewEnter += dr => { s_rePreviewActin = () => { RealTimePreviewContext.instance.EnterRealtimePreview(dr); }; }; + } } } diff --git a/Editor/Preview/OneTimePreviewContext.cs b/Editor/Preview/OneTimePreviewContext.cs index c66118a7..ce8506ef 100644 --- a/Editor/Preview/OneTimePreviewContext.cs +++ b/Editor/Preview/OneTimePreviewContext.cs @@ -12,8 +12,9 @@ internal class OneTimePreviewContext : ScriptableSingleton OnPreviewEnter; + public event Action OnPreviewExit; protected OneTimePreviewContext() { AssemblyReloadEvents.beforeAssemblyReload -= ExitPreview; @@ -34,7 +35,6 @@ private void OnEnable() public static bool IsPreviewing(TexTransBehavior transformer) => transformer == instance.previweing; public static bool IsPreviewContains => instance.previweing != null; - public static bool LastPreviewClear() => instance.lastPreviweing = null; private void DrawApplyAndRevert(T target, Action apply) where T : Object @@ -73,10 +73,15 @@ public void DrawApplyAndRevert(TexTransBehavior target) { DrawApplyAndRevert(target, TexTransBehaviorApply); } + public void ApplyTexTransBehavior(TexTransBehavior target) + { + StartPreview(target, TexTransBehaviorApply); + } void StartPreview(T target, Action applyAction) where T : Object { previweing = target; + OnPreviewEnter?.Invoke(previweing); AnimationMode.StartAnimationMode(); try { @@ -125,9 +130,9 @@ static void TexTransBehaviorApply(TexTransBehavior targetTTBehavior) public void ExitPreview() { if (previweing == null) { return; } - lastPreviweing = previweing; previweing = null; AnimationMode.StopAnimationMode(); + OnPreviewExit?.Invoke(); } public void ExitPreview(UnityEngine.SceneManagement.Scene scene, bool removingScene) { @@ -138,19 +143,5 @@ public void DestroyObserve(TexTransBehavior texTransBehavior) if (IsPreviewing(texTransBehavior)) { instance.ExitPreview(); } } - internal void RePreview() - { - if (!IsPreviewContains) - { - if (lastPreviweing is TexTransBehavior texTransBehavior) { StartPreview(texTransBehavior, TexTransBehaviorApply); lastPreviweing = null; } - } - else - { - if (previweing is not TexTransBehavior texTransBehavior) { return; } - var target = texTransBehavior; - ExitPreview(); - StartPreview(target, TexTransBehaviorApply); - } - } } } diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 8c3225be..7bb8c1cb 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -20,6 +20,8 @@ internal class RealTimePreviewContext : ScriptableSingleton _updateQueue = new(); + public event Action OnPreviewEnter; + public event Action OnPreviewExit; protected RealTimePreviewContext() @@ -36,6 +38,8 @@ public void EnterRealtimePreview(GameObject previewRoot) if (_previewDomain != null) { UnityEngine.Debug.Log("Already preview !!!"); return; } if (AnimationMode.InAnimationMode()) { UnityEngine.Debug.Log("Other preview now !!!"); return; } + OnPreviewEnter?.Invoke(previewRoot); + AnimationMode.StartAnimationMode(); AnimationMode.BeginSampling(); @@ -156,6 +160,8 @@ public void ExitRealTimePreview() _previewDomain = null; AnimationMode.EndSampling(); AnimationMode.StopAnimationMode(); + + OnPreviewExit?.Invoke(); } From fbcadbdf90fbe6dcd4b74d75df82bfe3b82e7042 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 20:07:57 +0900 Subject: [PATCH 112/208] fix: ignore null --- Editor/Preview/RealTime/RealTimePreviewContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 7bb8c1cb..76199037 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -68,7 +68,7 @@ void AddPreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) } if (ContainsBehavior(texTransRuntimeBehavior)) { return; } - foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency().Append(texTransRuntimeBehavior).Select(g => g.GetInstanceID())) + foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency().Append(texTransRuntimeBehavior).Where(g => g != null).Select(g => g.GetInstanceID())) { if (!_dependencyMap.ContainsKey(dependInstanceID)) { _dependencyMap[dependInstanceID] = new(); } _dependencyMap[dependInstanceID].Add(texTransRuntimeBehavior); From 7c42635a3847203b1212ad5fa4779a05d4e28a0a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 20:10:42 +0900 Subject: [PATCH 113/208] fix: all child layers is MLIC dependency --- Runtime/MultiLayerImage/AbstractLayer.cs | 6 +++++- Runtime/MultiLayerImage/LayerFolder.cs | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Runtime/MultiLayerImage/AbstractLayer.cs b/Runtime/MultiLayerImage/AbstractLayer.cs index 78d8b0ed..96eb092e 100644 --- a/Runtime/MultiLayerImage/AbstractLayer.cs +++ b/Runtime/MultiLayerImage/AbstractLayer.cs @@ -35,7 +35,11 @@ internal virtual LayerAlphaMod GetLayerAlphaMod(CanvasContext canvasContext) } } - internal virtual IEnumerable GetDependency() { foreach (var m in LayerMask.GetDependency()) { yield return m; } } + internal virtual IEnumerable GetDependency() + { + yield return gameObject; + foreach (var m in LayerMask.GetDependency()) { yield return m; } + } } [Serializable] diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index 3f19fe87..930a0f38 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -56,6 +56,12 @@ internal IEnumerable GetChileLayers() .Select(I => I.GetComponent()) .Reverse(); } + + internal override IEnumerable GetDependency() + { + var chileLayers = GetChileLayers(); + return base.GetDependency().Concat(chileLayers).Concat(chileLayers.SelectMany(l => l.GetDependency())); + } } From 4fe924d3be31b50f9892862ccbc117a7363159b9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 25 Apr 2024 20:39:18 +0900 Subject: [PATCH 114/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 56f4c7c5..76b3544e 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -17,6 +17,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - AtlasTexture に MaterialMargeGroup が追加されました (#432) - ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) - SubMeshIslandSelector , IslandSelectorXOR , IslandSelectorRelay が追加されました (#447) +- RealTimePreview が大幅に改修され、MultiLayerImageCanvas もリアルタイムプレビュー可能になりました (#448) ### Changed From b03ffa857bce0223ecf4bf47fef1b52191d06290 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 25 Apr 2024 11:44:39 +0000 Subject: [PATCH 115/208] Update package.json v0.7.0-beta.6!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 7a703d16..aed76aef 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.5", + "version": "0.7.0-beta.6", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 444c5e6da66db7c4b78590f5683cc5bb72329cc3 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 26 Apr 2024 18:50:32 +0900 Subject: [PATCH 116/208] chore: move shader file --- Runtime/Utils/ShaderAssets.meta | 8 +++ .../ShaderAssets/DisplayDecalTexture.shader | 59 +++++++++++++++++++ .../DisplayDecalTexture.shader.meta | 9 +++ .../ShaderAsset/UnlitColorAndAlpha.shader | 47 +++++++++++++++ .../UnlitColorAndAlpha.shader.meta | 9 +++ 5 files changed, 132 insertions(+) create mode 100644 Runtime/Utils/ShaderAssets.meta create mode 100644 Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader create mode 100644 Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader.meta create mode 100644 TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader create mode 100644 TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader.meta diff --git a/Runtime/Utils/ShaderAssets.meta b/Runtime/Utils/ShaderAssets.meta new file mode 100644 index 00000000..a64851e7 --- /dev/null +++ b/Runtime/Utils/ShaderAssets.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 08a503898a10f4f4084e6b2148b82a33 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader b/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader new file mode 100644 index 00000000..dda78108 --- /dev/null +++ b/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader @@ -0,0 +1,59 @@ +Shader "Hidden/DisplayDecalTexture" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + _MulColor ("MulColor", Color) = (1,1,1,1) + _Alpha ("Alpha", Range (0, 1)) = 0.5 + } + SubShader + { + Tags { "RenderType"="Transparent" } + LOD 100 + Blend SrcAlpha OneMinusSrcAlpha + Cull Off + ZWrite Off + Pass + { + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + struct v2f + { + float2 uv : TEXCOORD0; + float4 vertex : SV_POSITION; + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.uv, _MainTex); + return o; + } + float4 _MulColor; + float _Alpha; + fixed4 frag (v2f i) : SV_Target + { + // sample the texture + float4 col = tex2D(_MainTex, i.uv); + col.a *= _Alpha; + col *= _MulColor; + return col; + } + ENDHLSL + } + } +} diff --git a/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader.meta b/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader.meta new file mode 100644 index 00000000..aa1b8571 --- /dev/null +++ b/Runtime/Utils/ShaderAssets/DisplayDecalTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 08b0159fedf8f7f4687e93d5b65a3976 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader b/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader new file mode 100644 index 00000000..967eda91 --- /dev/null +++ b/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader @@ -0,0 +1,47 @@ +Shader "Hidden/UnlitColorAndAlpha" +{ + Properties + { + _Color ("Color", Color) = (1,1,1,1) + } + SubShader + { + Tags { "RenderType"="Opaque" } + LOD 100 + + Pass + { + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + }; + + struct v2f + { + float4 vertex : SV_POSITION; + }; + + float4 _Color; + + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + return o; + } + + fixed4 frag (v2f i) : SV_Target + { + return _Color; + } + ENDHLSL + } + } +} diff --git a/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader.meta b/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader.meta new file mode 100644 index 00000000..b05422aa --- /dev/null +++ b/TexTransCore/BlendTexture/ShaderAsset/UnlitColorAndAlpha.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 9f911e811697bff4f8c180f2ed3f6e99 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: From 6eef255867144c282acb67bfb88494759ed96f39 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 26 Apr 2024 19:11:11 +0900 Subject: [PATCH 117/208] remove: AbstractDecal , AbstractSingleDecal , CylindricalDecal , CylindricalCurveDecal , CylindricalCoordinatesSystem , NailEditor , NailOffsetData --- .../Inspector/AbstractIslandSelectorEditor.cs | 1 - .../CylindricalCoordinatesSystemEditor.cs | 14 - ...CylindricalCoordinatesSystemEditor.cs.meta | 11 - Editor/Inspector/Decal/Curve.meta | 8 - .../Inspector/Decal/Curve/CurveDecalEditor.cs | 97 ------ .../Decal/Curve/CurveDecalEditor.cs.meta | 11 - .../Decal/Curve/CurveSegmentEditor.cs | 16 - .../Decal/Curve/CurveSegmentEditor.cs.meta | 11 - .../Curve/CylindricalCurveDecalEditor.cs | 21 -- .../Curve/CylindricalCurveDecalEditor.cs.meta | 11 - .../Inspector/Decal/CylindricalDecalEditor.cs | 61 ---- .../Decal/CylindricalDecalEditor.cs.meta | 11 - Editor/Inspector/Decal/NailEditorEditor.cs | 173 ---------- .../Inspector/Decal/NailEditorEditor.cs.meta | 11 - Editor/Inspector/Decal/SimpleDecalEditor.cs | 5 +- Editor/Migration/Migrator.cs | 6 +- Editor/Migration/V0/AbstractDecalV0.cs | 10 +- Editor/Migration/V1/AbstractDecalV1.cs | 2 +- Runtime/Decal/AbstractDecal.cs | 100 ------ Runtime/Decal/AbstractDecal.cs.meta | 11 - Runtime/Decal/AbstructSingleDecal.cs | 57 ---- Runtime/Decal/AbstructSingleDecal.cs.meta | 11 - Runtime/Decal/Curve.meta | 8 - Runtime/Decal/Curve/BezierCurve.cs | 212 ------------ Runtime/Decal/Curve/BezierCurve.cs.meta | 11 - Runtime/Decal/Curve/CurveDecal.cs | 48 --- Runtime/Decal/Curve/CurveDecal.cs.meta | 11 - Runtime/Decal/Curve/CurveSegment.cs | 15 - Runtime/Decal/Curve/CurveSegment.cs.meta | 11 - Runtime/Decal/Curve/CylindricalCurveDecal.cs | 117 ------- .../Decal/Curve/CylindricalCurveDecal.cs.meta | 11 - Runtime/Decal/Cylindrical.meta | 8 - .../CylindricalCoordinatesSystem.cs | 297 ----------------- .../CylindricalCoordinatesSystem.cs.meta | 11 - Runtime/Decal/CylindricalDecal.cs | 119 ------- Runtime/Decal/CylindricalDecal.cs.meta | 11 - Runtime/Decal/DisplayDecalTexture.shader | 59 ---- Runtime/Decal/DisplayDecalTexture.shader.meta | 9 - Runtime/Decal/IslandSelectToPPFilter.cs | 2 - Runtime/Decal/NailEditor.cs | 310 ------------------ Runtime/Decal/NailEditor.cs.meta | 11 - Runtime/Decal/NailOffsetData.cs | 81 ----- Runtime/Decal/NailOffsetData.cs.meta | 11 - Runtime/Decal/SimpleDecal.cs | 137 +++++++- Runtime/Decal/UnlitColorAndAlpha.shader | 47 --- Runtime/Decal/UnlitColorAndAlpha.shader.meta | 9 - .../Decal/AbstractRayCastRendererResolver.cs | 2 +- .../Decal/RayCastRendererMultiResolver.cs | 2 +- .../Decal/RayCastRendererResolver.cs | 2 +- 49 files changed, 136 insertions(+), 2095 deletions(-) delete mode 100644 Editor/Inspector/CylindricalCoordinatesSystemEditor.cs delete mode 100644 Editor/Inspector/CylindricalCoordinatesSystemEditor.cs.meta delete mode 100644 Editor/Inspector/Decal/Curve.meta delete mode 100644 Editor/Inspector/Decal/Curve/CurveDecalEditor.cs delete mode 100644 Editor/Inspector/Decal/Curve/CurveDecalEditor.cs.meta delete mode 100644 Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs delete mode 100644 Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs.meta delete mode 100644 Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs delete mode 100644 Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs.meta delete mode 100644 Editor/Inspector/Decal/CylindricalDecalEditor.cs delete mode 100644 Editor/Inspector/Decal/CylindricalDecalEditor.cs.meta delete mode 100644 Editor/Inspector/Decal/NailEditorEditor.cs delete mode 100644 Editor/Inspector/Decal/NailEditorEditor.cs.meta delete mode 100644 Runtime/Decal/AbstractDecal.cs delete mode 100644 Runtime/Decal/AbstractDecal.cs.meta delete mode 100644 Runtime/Decal/AbstructSingleDecal.cs delete mode 100644 Runtime/Decal/AbstructSingleDecal.cs.meta delete mode 100644 Runtime/Decal/Curve.meta delete mode 100644 Runtime/Decal/Curve/BezierCurve.cs delete mode 100644 Runtime/Decal/Curve/BezierCurve.cs.meta delete mode 100644 Runtime/Decal/Curve/CurveDecal.cs delete mode 100644 Runtime/Decal/Curve/CurveDecal.cs.meta delete mode 100644 Runtime/Decal/Curve/CurveSegment.cs delete mode 100644 Runtime/Decal/Curve/CurveSegment.cs.meta delete mode 100644 Runtime/Decal/Curve/CylindricalCurveDecal.cs delete mode 100644 Runtime/Decal/Curve/CylindricalCurveDecal.cs.meta delete mode 100644 Runtime/Decal/Cylindrical.meta delete mode 100644 Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs delete mode 100644 Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs.meta delete mode 100644 Runtime/Decal/CylindricalDecal.cs delete mode 100644 Runtime/Decal/CylindricalDecal.cs.meta delete mode 100644 Runtime/Decal/DisplayDecalTexture.shader delete mode 100644 Runtime/Decal/DisplayDecalTexture.shader.meta delete mode 100644 Runtime/Decal/NailEditor.cs delete mode 100644 Runtime/Decal/NailEditor.cs.meta delete mode 100644 Runtime/Decal/NailOffsetData.cs delete mode 100644 Runtime/Decal/NailOffsetData.cs.meta delete mode 100644 Runtime/Decal/UnlitColorAndAlpha.shader delete mode 100644 Runtime/Decal/UnlitColorAndAlpha.shader.meta diff --git a/Editor/Inspector/AbstractIslandSelectorEditor.cs b/Editor/Inspector/AbstractIslandSelectorEditor.cs index 29720bcf..9de51d5d 100644 --- a/Editor/Inspector/AbstractIslandSelectorEditor.cs +++ b/Editor/Inspector/AbstractIslandSelectorEditor.cs @@ -1,5 +1,4 @@ using UnityEditor; -using net.rs64.TexTransTool.Decal.Cylindrical; using net.rs64.TexTransTool.IslandSelector; namespace net.rs64.TexTransTool.Editor { diff --git a/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs b/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs deleted file mode 100644 index fddaa1c1..00000000 --- a/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs +++ /dev/null @@ -1,14 +0,0 @@ -using UnityEditor; -using net.rs64.TexTransTool.Decal.Cylindrical; -namespace net.rs64.TexTransTool.Editor -{ - [CustomEditor(typeof(CylindricalCoordinatesSystem))] - internal class CylindricalCoordinatesSystemEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("CylindricalCoordinatesSystem"); - base.OnInspectorGUI(); - } - } -} diff --git a/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs.meta b/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs.meta deleted file mode 100644 index fb947878..00000000 --- a/Editor/Inspector/CylindricalCoordinatesSystemEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cda4afaa4ba8df246804d350b16a902a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/Curve.meta b/Editor/Inspector/Decal/Curve.meta deleted file mode 100644 index c8b4c59b..00000000 --- a/Editor/Inspector/Decal/Curve.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 2152c46048294a74c88d4d0267e82147 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs b/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs deleted file mode 100644 index 60ad6749..00000000 --- a/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs +++ /dev/null @@ -1,97 +0,0 @@ -using UnityEngine; -using UnityEditor; -using net.rs64.TexTransTool.Decal.Curve; - -namespace net.rs64.TexTransTool.Editor.Decal.Curve -{ - - - [CustomEditor(typeof(CurveDecal))] - internal class CurveDecalEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - var thisSObj = serializedObject; - - DrawerCurveDecalEditor(thisSObj); - - thisSObj.ApplyModifiedProperties(); - } - - public static void DrawerCurveDecalEditor(SerializedObject thisSObject) - { - var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); - var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); - TextureTransformerEditor.DrawerRenderer(sTargetRenderers, "CommonDecal:prop:TargetRenderer".Glc(), sMultiRendererMode.boolValue); - - var sIsUseStartAndEnd = thisSObject.FindProperty("UseFirstAndEnd"); - EditorGUILayout.PropertyField(sIsUseStartAndEnd); - - var isUseStartAndEnd = sIsUseStartAndEnd.boolValue; - if (isUseStartAndEnd) - { - var sEnd = thisSObject.FindProperty("EndTexture"); - TextureTransformerEditor.DrawerObjectReference(sEnd); - } - - var sDecalTexture = thisSObject.FindProperty("DecalTexture"); - TextureTransformerEditor.DrawerObjectReference(sDecalTexture); - - if (isUseStartAndEnd) - { - var sStart = thisSObject.FindProperty("FirstTexture"); - TextureTransformerEditor.DrawerObjectReference(sStart); - } - // var sBlendType = thisSObject.FindProperty("BlendType"); - - var sTargetPropertyName = thisSObject.FindProperty("TargetPropertyName"); - EditorGUILayout.PropertyField(sTargetPropertyName); - - - var sSegments = thisSObject.FindProperty("Segments"); - DrawerSegmentFiled(sSegments); - - var sCylindricalCoordinatesSystem = thisSObject.FindProperty("CylindricalCoordinatesSystem"); - EditorGUILayout.PropertyField(sCylindricalCoordinatesSystem); - - var sSize = thisSObject.FindProperty("Size"); - EditorGUILayout.PropertyField(sSize); - - var sLoopCount = thisSObject.FindProperty("LoopCount"); - EditorGUILayout.PropertyField(sLoopCount); - - var sCurveStartOffset = thisSObject.FindProperty("CurveStartOffset"); - EditorGUILayout.PropertyField(sCurveStartOffset); - - var sRollMode = thisSObject.FindProperty("RollMode"); - EditorGUILayout.PropertyField(sRollMode); - - var sDrawGizmoAlways = thisSObject.FindProperty("DrawGizmoAlways"); - EditorGUILayout.PropertyField(sDrawGizmoAlways); - } - - public static void DrawerSegmentFiled(SerializedProperty segment) - { - EditorGUILayout.LabelField("Segments"); - var arraySize = segment.arraySize; - int count = 0; - while (arraySize > count) - { - var sSegment = segment.GetArrayElementAtIndex(count); - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PropertyField(sSegment); - /* - var sSegmentRoll = sSegment.FindPropertyRelative("Roll"); - if (sSegmentRoll != null) sSegmentRoll.floatValue = EditorGUI.Slider(EditorGUILayout.GetControlRect(), sSegmentRoll.floatValue, -360, 360); - */ - EditorGUILayout.EndHorizontal(); - - count += 1; - } - - TextureTransformerEditor.DrawerArrayResizeButton(segment); - - } - } - -} diff --git a/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs.meta b/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs.meta deleted file mode 100644 index 90f2b908..00000000 --- a/Editor/Inspector/Decal/Curve/CurveDecalEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 11145fded1e41364883f561e315ccac2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs b/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs deleted file mode 100644 index c531c8f1..00000000 --- a/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs +++ /dev/null @@ -1,16 +0,0 @@ -using UnityEditor; -using net.rs64.TexTransTool.Decal.Curve; -namespace net.rs64.TexTransTool.Editor.Decal.Curve -{ - - [CustomEditor(typeof(CurveSegment))] - internal class CurveSegmentEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("CurveSegment"); - base.OnInspectorGUI(); - - } - } -} diff --git a/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs.meta b/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs.meta deleted file mode 100644 index 8aa4b845..00000000 --- a/Editor/Inspector/Decal/Curve/CurveSegmentEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 83948d5b750fb3e4290061db123246a8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs b/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs deleted file mode 100644 index e805eb69..00000000 --- a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs +++ /dev/null @@ -1,21 +0,0 @@ -using UnityEditor; -using net.rs64.TexTransTool.Decal.Curve; -using net.rs64.TexTransTool.Preview; - -namespace net.rs64.TexTransTool.Editor.Decal.Curve.Cylindrical -{ - - - [CustomEditor(typeof(CylindricalCurveDecal), true)] - internal class CylindricalCurveDecalEditor : CurveDecalEditor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("CylindricalCurveDecal"); - base.OnInspectorGUI(); - OneTimePreviewContext.instance.DrawApplyAndRevert(target as CylindricalCurveDecal); - } - - } - -} diff --git a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs.meta b/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs.meta deleted file mode 100644 index 137a83cd..00000000 --- a/Editor/Inspector/Decal/Curve/CylindricalCurveDecalEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 83ea6e02a43aa394ca359ea15a65ebb1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/CylindricalDecalEditor.cs b/Editor/Inspector/Decal/CylindricalDecalEditor.cs deleted file mode 100644 index 12f14640..00000000 --- a/Editor/Inspector/Decal/CylindricalDecalEditor.cs +++ /dev/null @@ -1,61 +0,0 @@ -using UnityEngine; -using UnityEditor; -using net.rs64.TexTransTool.Decal; -using net.rs64.TexTransTool.Preview; - -namespace net.rs64.TexTransTool.Editor.Decal -{ - - [CustomEditor(typeof(CylindricalDecal), true)] - internal class CylindricalDecalEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("CylindricalDecal"); - - var thisSObject = serializedObject; - var thisObject = target as CylindricalDecal; - - - EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); - - var sCylindricalCoordinatesSystem = thisSObject.FindProperty("CylindricalCoordinatesSystem"); - EditorGUILayout.PropertyField(sCylindricalCoordinatesSystem); - - AbstractDecalEditor.DrawerDecalEditor(thisSObject); - - if (targets.Length == 1) - { - var tf_sObg = new SerializedObject(thisObject.transform); - SimpleDecalEditor.DrawerScale(thisSObject, tf_sObg, thisObject.DecalTexture); - tf_sObg.ApplyModifiedProperties(); - } - - - - EditorGUILayout.LabelField("CullingSettings", EditorStyles.boldLabel); - EditorGUI.indentLevel += 1; - var sSideCulling = thisSObject.FindProperty("SideCulling"); - EditorGUILayout.PropertyField(sSideCulling); - var sFarCulling = thisSObject.FindProperty("OutDistanceCulling"); - EditorGUILayout.PropertyField(sFarCulling, new GUIContent("Far Culling OffSet")); - var sNearCullingOffSet = thisSObject.FindProperty("InDistanceCulling"); - EditorGUILayout.PropertyField(sNearCullingOffSet, new GUIContent("Near Culling OffSet")); - EditorGUI.indentLevel -= 1; - - - AbstractDecalEditor.DrawerAdvancedOption(thisSObject); - - - EditorGUI.EndDisabledGroup(); - - OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); - - thisSObject.ApplyModifiedProperties(); - } - - - } - - -} diff --git a/Editor/Inspector/Decal/CylindricalDecalEditor.cs.meta b/Editor/Inspector/Decal/CylindricalDecalEditor.cs.meta deleted file mode 100644 index 4e01e764..00000000 --- a/Editor/Inspector/Decal/CylindricalDecalEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 521321febe895ec4980c457b741a6ed9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/NailEditorEditor.cs b/Editor/Inspector/Decal/NailEditorEditor.cs deleted file mode 100644 index 7d03b94a..00000000 --- a/Editor/Inspector/Decal/NailEditorEditor.cs +++ /dev/null @@ -1,173 +0,0 @@ -using UnityEngine; -using UnityEditor; -using net.rs64.TexTransTool.Decal; -using net.rs64.TexTransTool.Preview; - -namespace net.rs64.TexTransTool.Editor.Decal -{ - - [CustomEditor(typeof(NailEditor), true)] - internal class NailEditorEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("NailEditor"); - var thisSObject = serializedObject; - var thisObject = target as NailEditor; - - var sTargetAvatar = thisSObject.FindProperty("TargetAvatar"); - EditorGUILayout.PropertyField(sTargetAvatar, sTargetAvatar.name.Glc()); - - var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); - var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); - TextureTransformerEditor.DrawerRenderer(sTargetRenderers, "CommonDecal:prop:TargetRenderer".Glc(), sMultiRendererMode.boolValue); - EditorGUILayout.PropertyField(sMultiRendererMode, sMultiRendererMode.name.Glc()); - - var sBlendType = thisSObject.FindProperty("BlendType"); - EditorGUILayout.PropertyField(sBlendType, sBlendType.name.Glc()); - - var sTargetPropertyName = thisSObject.FindProperty("TargetPropertyName"); - EditorGUILayout.PropertyField(sTargetPropertyName); - - var sUseTextureAspect = thisSObject.FindProperty("UseTextureAspect"); - EditorGUILayout.PropertyField(sUseTextureAspect, sUseTextureAspect.name.Glc()); - - - var sLeftHand = thisSObject.FindProperty("LeftHand"); - var sRightHand = thisSObject.FindProperty("RightHand"); - EditorGUILayout.LabelField("LeftHand".GetLocalize()); - DrawerNailSet(sLeftHand); - EditorGUILayout.LabelField("RightHand".GetLocalize()); - DrawerNailSet(sRightHand); - - - DrawerOffsetUtilEditor(thisObject); - DrawOffsetSaveAndLoader(thisObject); - - AbstractDecalEditor.DrawerAdvancedOption(thisSObject); - - OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); - - thisSObject.ApplyModifiedProperties(); - } - - public static void DrawerNailSet(SerializedProperty serializedProperty) - { - var sFingerUpVector = serializedProperty.FindPropertyRelative("FingerUpVector"); - var sThumb = serializedProperty.FindPropertyRelative("Thumb"); - var sIndex = serializedProperty.FindPropertyRelative("Index"); - var sMiddle = serializedProperty.FindPropertyRelative("Middle"); - var sRing = serializedProperty.FindPropertyRelative("Ring"); - var sLittle = serializedProperty.FindPropertyRelative("Little"); - - EditorGUI.indentLevel += 1; - - EditorGUILayout.PropertyField(sFingerUpVector, sFingerUpVector.name.Glc()); - - EditorGUILayout.LabelField("Thumb".GetLocalize()); - DrawerNailDescriptor(sThumb); - EditorGUILayout.LabelField("Index".GetLocalize()); - DrawerNailDescriptor(sIndex); - EditorGUILayout.LabelField("Middle".GetLocalize()); - DrawerNailDescriptor(sMiddle); - EditorGUILayout.LabelField("Ring".GetLocalize()); - DrawerNailDescriptor(sRing); - EditorGUILayout.LabelField("Little".GetLocalize()); - DrawerNailDescriptor(sLittle); - - EditorGUI.indentLevel -= 1; - } - public static void DrawerNailDescriptor(SerializedProperty serializedProperty) - { - var sDecalTexture = serializedProperty.FindPropertyRelative("DecalTexture"); - var sPositionOffset = serializedProperty.FindPropertyRelative("PositionOffset"); - var sScaleOffset = serializedProperty.FindPropertyRelative("ScaleOffset"); - var sRotationOffset = serializedProperty.FindPropertyRelative("RotationOffset"); - - EditorGUI.indentLevel += 1; - - EditorGUILayout.PropertyField(sDecalTexture, sDecalTexture.name.Glc()); - DrawerPositionOffset(sPositionOffset); - EditorGUILayout.PropertyField(sScaleOffset, sScaleOffset.name.Glc()); - EditorGUILayout.PropertyField(sRotationOffset, sRotationOffset.name.Glc()); - - EditorGUI.indentLevel -= 1; - } - public static void DrawerPositionOffset(SerializedProperty serializedProperty) - { - var drawValue = serializedProperty.vector3Value * 100; - serializedProperty.vector3Value = EditorGUI.Vector3Field(EditorGUILayout.GetControlRect(), "PositionOffset".GetLocalize(), drawValue) * 0.01f; - - } - - public static void DrawerOffsetUtilEditor(NailEditor nailEditor) - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("Copy".GetLocalize(), GUILayout.Width(100)); - - if (GUILayout.Button("LeftHand".GetLocalize() + "<=" + "RightHand".GetLocalize())) - { - Undo.RecordObject(nailEditor, "NailEditor Offset Copy Left <= Right"); - var nailOffsets = new NailOffSets(); - nailOffsets.Copy(nailEditor.RightHand); - nailOffsets.UpVector = nailEditor.LeftHand.FingerUpVector; - nailEditor.LeftHand.Copy(nailOffsets); - } - - if (GUILayout.Button("LeftHand".GetLocalize() + "=>" + "RightHand".GetLocalize())) - { - Undo.RecordObject(nailEditor, "NailEditor Offset Copy Left => Right"); - var nailOffsets = new NailOffSets(); - nailOffsets.Copy(nailEditor.LeftHand); - nailOffsets.UpVector = nailEditor.RightHand.FingerUpVector; - nailEditor.RightHand.Copy(nailOffsets); - } - - EditorGUILayout.EndHorizontal(); - - } - - public NailOffsetData nailOffsetData; - public void DrawOffsetSaveAndLoader(NailEditor thisObject) - { - EditorGUILayout.BeginHorizontal(); - nailOffsetData = EditorGUILayout.ObjectField("SaveData".GetLocalize(), nailOffsetData, typeof(NailOffsetData), false) as NailOffsetData; - if (GUILayout.Button("Load".GetLocalize())) - { - if (nailOffsetData != null) - { - thisObject.LeftHand.Copy(nailOffsetData.LeftHand); - thisObject.RightHand.Copy(nailOffsetData.RightHand); - EditorUtility.SetDirty(thisObject); - EditorUtility.SetDirty(nailOffsetData); - } - } - if (GUILayout.Button("Save".GetLocalize())) - { - if (nailOffsetData != null) - { - nailOffsetData.LeftHand.Copy(thisObject.LeftHand); - nailOffsetData.RightHand.Copy(thisObject.RightHand); - EditorUtility.SetDirty(thisObject); - EditorUtility.SetDirty(nailOffsetData); - } - } - EditorGUILayout.EndHorizontal(); - - } - - public static void DrawerSummary(NailEditor target) - { - var sObj = new SerializedObject(target); - var sTargetAvatar = sObj.FindProperty("TargetAvatar"); - EditorGUILayout.PropertyField(sTargetAvatar, sTargetAvatar.name.Glc()); - var sTargetRenderers = sObj.FindProperty("TargetRenderers"); - TextureTransformerEditor.DrawerTargetRenderersSummary(sTargetRenderers, sTargetRenderers.name.Glc()); - - sObj.ApplyModifiedProperties(); - } - - } - - -} diff --git a/Editor/Inspector/Decal/NailEditorEditor.cs.meta b/Editor/Inspector/Decal/NailEditorEditor.cs.meta deleted file mode 100644 index 32ef26c6..00000000 --- a/Editor/Inspector/Decal/NailEditorEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0da6605399c2e1f4a86c0e89dd11944e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 0c187495..71f1c106 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -4,7 +4,7 @@ using UnityEngine.UIElements; using UnityEditor.UIElements; using net.rs64.TexTransTool.IslandSelector; -using net.rs64.TexTransTool.Preview.RealTime; +using System; namespace net.rs64.TexTransTool.Editor.Decal { @@ -55,7 +55,9 @@ public override void OnInspectorGUI() var sIslandCulling = thisSObject.FindProperty("IslandCulling"); if (sIslandCulling.boolValue && GUILayout.Button("Migrate IslandCulling to IslandSelector")) { +#pragma warning disable CS0612 MigrateIslandCullingToIslandSelector(thisObject); +#pragma warning restore CS0612 } } @@ -140,6 +142,7 @@ internal static void RegisterSummary() }; } + [Obsolete] public void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) { if (simpleDecal.IslandSelector != null) diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index 123acc70..03ea98f7 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -77,7 +77,7 @@ public static bool MigrationITexTransToolTagV1ToV2(ITexTransToolTag texTransTool AtlasTextureV1.MigrationAtlasTextureV1ToV2(atlasTexture); return true; } - case AbstractDecal abstractDecal: + case SimpleDecal abstractDecal: { AbstractDecalV1.MigrationAbstractDecalV1ToV2(abstractDecal); return true; @@ -103,7 +103,7 @@ public static bool MigrationITexTransToolTagV0ToV1(ITexTransToolTag texTransTool AtlasTextureV0.MigrationAtlasTextureV0ToV1(atlasTexture); return true; } - case AbstractDecal abstractDecal: + case SimpleDecal abstractDecal: { AbstractDecalV0.MigrationAbstractDecalV0ToV1(abstractDecal); return true; @@ -129,7 +129,7 @@ public static bool MigrationFinalizeITexTransToolTagV0ToV1(ITexTransToolTag texT AtlasTextureV0.FinalizeMigrationAtlasTextureV0ToV1(atlasTexture); return true; } - case AbstractDecal abstractDecal: + case SimpleDecal abstractDecal: { AbstractDecalV0.FinalizeMigrationAbstractDecalV0ToV1(abstractDecal); return true; diff --git a/Editor/Migration/V0/AbstractDecalV0.cs b/Editor/Migration/V0/AbstractDecalV0.cs index 794d7c38..b48db250 100644 --- a/Editor/Migration/V0/AbstractDecalV0.cs +++ b/Editor/Migration/V0/AbstractDecalV0.cs @@ -10,7 +10,7 @@ namespace net.rs64.TexTransTool.Migration.V0 [Obsolete] internal static class AbstractDecalV0 { - public static void MigrationAbstractDecalV0ToV1(AbstractDecal abstractDecal) + public static void MigrationAbstractDecalV0ToV1(SimpleDecal abstractDecal) { if (abstractDecal == null) { Debug.LogWarning("マイグレーションターゲットが存在しません。"); return; } if (abstractDecal is ITexTransToolTag TTTag && TTTag.SaveDataVersion > 1) { Debug.Log(abstractDecal.name + " AbstractDecal : マイグレーション不可能なバージョンです。"); return; } @@ -58,7 +58,7 @@ public static void MigrationAbstractDecalV0ToV1(AbstractDecal abstractDecal) var newGameObjectDecal = new GameObject("Decal"); newGameObjectDecal.transform.parent = GameObject.transform; - var NewDecal = newGameObjectDecal.AddComponent(abstractDecal.GetType()) as AbstractDecal; + var NewDecal = newGameObjectDecal.AddComponent(abstractDecal.GetType()) as SimpleDecal; NewDecal.CopyFromDecal(abstractDecal); abstractDecal.HighQualityPadding = abstractDecal.FastMode; NewDecal.IsSeparateMatAndTexture = false; @@ -80,7 +80,7 @@ public static void MigrationAbstractDecalV0ToV1(AbstractDecal abstractDecal) } } } - public static void FinalizeMigrationAbstractDecalV0ToV1(AbstractDecal abstractDecal) + public static void FinalizeMigrationAbstractDecalV0ToV1(SimpleDecal abstractDecal) { if (abstractDecal.MigrationV0ClearTarget) { @@ -94,7 +94,7 @@ public static void FinalizeMigrationAbstractDecalV0ToV1(AbstractDecal abstractDe } } - static void SetUpSeparator(MatAndTexUtils.MatAndTexRelativeSeparator matAndTexSeparator, AbstractDecal abstractDecal) + static void SetUpSeparator(MatAndTexUtils.MatAndTexRelativeSeparator matAndTexSeparator, SimpleDecal abstractDecal) { if (abstractDecal.TargetRenderers != null) { @@ -120,7 +120,7 @@ static void SetUpSeparator(MatAndTexUtils.MatAndTexRelativeSeparator matAndTexSe EditorUtility.SetDirty(matAndTexSeparator); } - static void CopyFromDecal(this AbstractDecal target, AbstractDecal copySouse) + static void CopyFromDecal(this SimpleDecal target, SimpleDecal copySouse) { if (target.GetType() != copySouse.GetType()) { return; }; var fieldInfos = target.GetType().GetFields(); diff --git a/Editor/Migration/V1/AbstractDecalV1.cs b/Editor/Migration/V1/AbstractDecalV1.cs index 274b8f5c..abe8c31e 100644 --- a/Editor/Migration/V1/AbstractDecalV1.cs +++ b/Editor/Migration/V1/AbstractDecalV1.cs @@ -10,7 +10,7 @@ namespace net.rs64.TexTransTool.Migration.V1 internal static class AbstractDecalV1 { - public static void MigrationAbstractDecalV1ToV2(AbstractDecal abstractDecal) + public static void MigrationAbstractDecalV1ToV2(SimpleDecal abstractDecal) { if (abstractDecal == null) { Debug.LogWarning("マイグレーションターゲットが存在しません。"); return; } if (abstractDecal is ITexTransToolTag TTTag && TTTag.SaveDataVersion > 2) { Debug.Log(abstractDecal.name + " AtlasTexture : マイグレーション不可能なバージョンです。"); return; } diff --git a/Runtime/Decal/AbstractDecal.cs b/Runtime/Decal/AbstractDecal.cs deleted file mode 100644 index 832d560d..00000000 --- a/Runtime/Decal/AbstractDecal.cs +++ /dev/null @@ -1,100 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using System; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.Island; -using UnityEngine.Pool; -using System.Linq; - -namespace net.rs64.TexTransTool.Decal -{ - [ExecuteInEditMode] - public abstract class AbstractDecal : TexTransRuntimeBehavior - { - public List TargetRenderers = new List { null }; - public bool MultiRendererMode = false; - [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; - - public Color Color = Color.white; - public PropertyName TargetPropertyName = PropertyName.DefaultValue; - public float Padding = 5; - public bool HighQualityPadding = false; - - #region V1SaveData - [Obsolete("Replaced with BlendTypeKey", true)][HideInInspector][SerializeField] internal BlendType BlendType = BlendType.Normal; - #endregion - #region V0SaveData - [Obsolete("V0SaveData", true)][HideInInspector] public bool MigrationV0ClearTarget; - [Obsolete("V0SaveData", true)][HideInInspector] public GameObject MigrationV0DataMatAndTexSeparatorGameObject; - [Obsolete("V0SaveData", true)][HideInInspector] public MatAndTexUtils.MatAndTexRelativeSeparator MigrationV0DataMatAndTexSeparator; - [Obsolete("V0SaveData", true)][HideInInspector] public AbstractDecal MigrationV0DataAbstractDecal; - [Obsolete("V0SaveData", true)][HideInInspector] public bool IsSeparateMatAndTexture; - [Obsolete("V0SaveData", true)][HideInInspector] public bool FastMode = true; - #endregion - internal virtual TextureWrap GetTextureWarp { get => TextureWrap.NotWrap; } - - internal override List GetRenderers => TargetRenderers; - - internal override TexTransPhase PhaseDefine => TexTransPhase.AfterUVModification; - - internal override void Apply(IDomain domain) - { - if (!IsPossibleApply) - { - TTTRuntimeLog.Error(GetType().Name + ":error:TTTNotExecutable"); - return; - } - - var decalCompiledTextures = CompileDecal(domain.GetTextureManager(), DictionaryPool.Get()); - - foreach (var matAndTex in decalCompiledTextures) - { - domain.AddTextureStack(matAndTex.Key.GetTexture(TargetPropertyName), new TextureBlend.BlendTexturePair(matAndTex.Value, BlendTypeKey)); - } - - DictionaryPool.Release(decalCompiledTextures); - - } - - - internal abstract Dictionary CompileDecal(ITextureManager textureManager, Dictionary decalCompiledRenderTextures = null); - - internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureManager, Texture2D souseDecalTexture, Color color) - { - RenderTexture mulDecalTexture; - - if (souseDecalTexture != null) - { - var decalSouseSize = textureManager.GetOriginalTextureSize(souseDecalTexture); - mulDecalTexture = RenderTexture.GetTemporary(decalSouseSize, decalSouseSize, 0); - } - else { mulDecalTexture = RenderTexture.GetTemporary(32, 32, 0); } - mulDecalTexture.Clear(); - if (souseDecalTexture != null) - { - var tempRt = textureManager.GetOriginTempRt(souseDecalTexture); - TextureBlend.MultipleRenderTexture(mulDecalTexture, tempRt, color); - RenderTexture.ReleaseTemporary(tempRt); - } - else - { - TextureBlend.ColorBlit(mulDecalTexture, color); - } - return mulDecalTexture; - } - - internal override IEnumerable GetDependency() - { - return new UnityEngine.Object[] { transform } - .Concat(GetComponentsInParent(true)) - .Concat(TargetRenderers) - .Concat(TargetRenderers.Select(r => r.transform)) - .Concat(TargetRenderers.Select(r => r.GetMesh())) - .Concat(TargetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)); - } - - } -} diff --git a/Runtime/Decal/AbstractDecal.cs.meta b/Runtime/Decal/AbstractDecal.cs.meta deleted file mode 100644 index fe8485cc..00000000 --- a/Runtime/Decal/AbstractDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 29d7b787eef1deb46aef4cec02beeeec -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/AbstructSingleDecal.cs b/Runtime/Decal/AbstructSingleDecal.cs deleted file mode 100644 index 75d53186..00000000 --- a/Runtime/Decal/AbstructSingleDecal.cs +++ /dev/null @@ -1,57 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.Island; -using net.rs64.TexTransTool.Utils; -using UnityEngine.Profiling; - -namespace net.rs64.TexTransTool.Decal -{ - public abstract class AbstractSingleDecal : AbstractDecal - where SpaceConverter : DecalUtility.IConvertSpace - where UVDimension : struct - { - [ExpandTexture2D] public Texture2D DecalTexture; - internal override bool IsPossibleApply => TargetRenderers.Any(i => i != null); - internal abstract SpaceConverter GetSpaceConverter(); - internal abstract DecalUtility.ITrianglesFilter GetTriangleFilter(); - internal virtual bool? GetUseDepthOrInvert => null; - - internal override Dictionary CompileDecal(ITextureManager textureManager, Dictionary decalCompiledRenderTextures = null) - { - Profiler.BeginSample("GetMultipleDecalTexture"); - RenderTexture mulDecalTexture = GetMultipleDecalTexture(textureManager, DecalTexture, Color); - Profiler.EndSample(); - - decalCompiledRenderTextures ??= new(); - foreach (var renderer in TargetRenderers) - { - if (renderer == null) { continue; } - Profiler.BeginSample("CreateDecalTexture"); - DecalUtility.CreateDecalTexture( - renderer, - decalCompiledRenderTextures, - mulDecalTexture, - GetSpaceConverter(), - GetTriangleFilter(), - TargetPropertyName, - GetTextureWarp, - Padding, - HighQualityPadding, - GetUseDepthOrInvert - ); - Profiler.EndSample(); - } - RenderTexture.ReleaseTemporary(mulDecalTexture); - return decalCompiledRenderTextures; - } - - internal override IEnumerable GetDependency() - { - return base.GetDependency().Append(DecalTexture); - } - - - } -} diff --git a/Runtime/Decal/AbstructSingleDecal.cs.meta b/Runtime/Decal/AbstructSingleDecal.cs.meta deleted file mode 100644 index beb2d34b..00000000 --- a/Runtime/Decal/AbstructSingleDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bc7bbe7fa9ab25445997ab4c09055d75 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Curve.meta b/Runtime/Decal/Curve.meta deleted file mode 100644 index 93ec85ab..00000000 --- a/Runtime/Decal/Curve.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3613da12d2011d347b46c01578f303d3 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Curve/BezierCurve.cs b/Runtime/Decal/Curve/BezierCurve.cs deleted file mode 100644 index 319ce71d..00000000 --- a/Runtime/Decal/Curve/BezierCurve.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace net.rs64.TexTransTool.Decal.Curve -{ - internal class BezierCurve : ICurve - { - public List Segments = new List(); - public RollMode RollMode; - - float _DefaultWightStep = 0.1f; - public float DefaultWightStep { get => _DefaultWightStep; set => _DefaultWightStep = value > 0 ? value : 0.1f; } - public BezierCurve(List segments, RollMode rollMode = RollMode.WorldUp, float defaultWightStep = 0.1f) - { - Segments = segments; - DefaultWightStep = defaultWightStep; - RollMode = rollMode; - } - public Vector3 GetPoint(float wight) - { - var segmentIndexMax = Segments.Count - 1; - var middleIndex = Mathf.RoundToInt(wight); - if (middleIndex < 1) - { - return Vector3.LerpUnclamped(Segments[0].position, Segments[1].position, wight); - } - else if (middleIndex >= segmentIndexMax) - { - return Vector3.LerpUnclamped(Segments[segmentIndexMax - 1].position, Segments[segmentIndexMax].position, wight - (segmentIndexMax - 1)); - } - - var fromIndex = middleIndex - 1; - var toIndex = middleIndex + 1; - - var pointPoint = Segments[middleIndex].position; - var fromPoint = Vector3.Lerp(Segments[fromIndex].position, pointPoint, 0.5f); - var toPoint = Vector3.Lerp(pointPoint, Segments[toIndex].position, 0.5f); - - var fromWightRange = fromIndex + 0.5f; - var toWightRange = toIndex - 0.5f; - - var relativeWight = (wight - fromWightRange) / (toWightRange - fromWightRange); - var getPoint = CalculateBezier(fromPoint, pointPoint, toPoint, relativeWight); - - return getPoint; - - } - public (Vector3 point, float weight) GetOfLength(float formWight, float length) - { - var fromPoint = GetPoint(formWight); - - Span<(Vector3, float, float)?> point2 = stackalloc (Vector3, float, float)?[2] { null, (fromPoint, 0f, formWight) }; - var nawWight = formWight; - - var safetyCount = 0; - while (safetyCount < 512) - { - nawWight += DefaultWightStep; - var nawPoint = GetPoint(nawWight); - var nawLength = Vector3.Distance(fromPoint, nawPoint); - - point2[0] = point2[1]; - point2[1] = (nawPoint, nawLength, nawWight); - - if (nawLength > length) - { - break; - } - - safetyCount += 1; - } - - var minV = point2[0].Value; - var maxV = point2[1].Value; - var minLength = minV.Item2; - var maxLength = maxV.Item2; - var minWight = minV.Item3; - var maxWight = maxV.Item3; - - var wight = (length - minLength) / (maxLength - minLength); - var resWight = Mathf.LerpUnclamped(minWight, maxWight, wight); - - return (GetPoint(resWight), resWight); - } - - public float GetRoll(float wight) - { - var segmentIndexMax = Segments.Count - 1; - var floorIndex = Mathf.FloorToInt(wight); - var ceilIndex = Mathf.CeilToInt(wight); - if (floorIndex < 1) - { - return Mathf.LerpUnclamped(Segments[0].Roll, Segments[1].Roll, wight); - } - else if (ceilIndex > segmentIndexMax) - { - return Mathf.LerpUnclamped(Segments[segmentIndexMax - 1].Roll, Segments[segmentIndexMax].Roll, wight - (segmentIndexMax - 1)); - } - return Mathf.Lerp(Segments[floorIndex].Roll, Segments[ceilIndex].Roll, wight - floorIndex); - } - - public static Vector3 CalculateBezier(Vector3 From, Vector3 Point, Vector3 To, float wight) - { - var fp = Vector3.Lerp(From, Point, wight); - var pt = Vector3.Lerp(Point, To, wight); - - return Vector3.Lerp(fp, pt, wight); - } - public List> GetQuad(uint Quad, float Size, float StartWight = 0f) - { - if (!Segments.Any()) throw new System.Exception("Segments is null"); - - var quads = new List>(); - var fromWight = StartWight; - // var fromPoint = GetPoint(fromWight); - var fromEdge = GetEdge(fromWight, Size); - - - foreach (var index in Enumerable.Range(0, (int)Quad)) - { - Vector3 toPoint; float toWight; (toPoint, toWight) = GetOfLength(fromWight, Size); - - var toEdge = GetEdge(toWight, Size); - - quads.Add(new List(4) { fromEdge.Item1, fromEdge.Item2, toEdge.Item1, toEdge.Item2 }); - - fromWight = toWight; - // fromPoint = ToPoint; - fromEdge = toEdge; - } - return quads; - } - - public (Vector3, Vector3) GetEdge(float wight, float Size) - { - var point = GetPoint(wight); - var roll = GetRoll(wight); - - switch (RollMode) - { - default: - case RollMode.WorldUp: - { - var forward = GetPoint(wight + DefaultWightStep); - var toLook = Quaternion.FromToRotation(forward, point); - toLook *= Quaternion.AngleAxis(roll, point - forward); - var toEdge = ( - point + toLook * Vector3.left * (Size * 0.5f), - point + toLook * Vector3.right * (Size * 0.5f) - ); - return toEdge; - } - case RollMode.Cross: - { - var back = GetPoint(wight - DefaultWightStep); - var forward = GetPoint(wight + DefaultWightStep); - - var RollAxis = forward - back; - - var crossVec = Vector3.Cross(back - point, forward - point); - crossVec *= Vector3.left.magnitude / crossVec.magnitude; - - crossVec = Quaternion.AngleAxis(roll, RollAxis) * crossVec; - - crossVec *= (Size * 0.5f); - var Inverse = crossVec * -1; - - var Left = point + crossVec; - var right = point + Inverse; - - return (Left, right); - } - } - - } - - public List GetLine(float StartWight, float EndWight) - { - var nawWight = StartWight; - var line = new List(); - - while (nawWight < EndWight) - { - line.Add(GetPoint(nawWight)); - nawWight += DefaultWightStep; - } - - return line; - } - - public List GetLine() - { - return GetLine(0f, Segments.Count - 1f); - } - } - - internal interface ICurve - { - Vector3 GetPoint(float wight); - float GetRoll(float wight); - (Vector3 point, float weight) GetOfLength(float formWight, float length); - } - - internal enum RollMode - { - WorldUp, - Cross, - - } -} \ No newline at end of file diff --git a/Runtime/Decal/Curve/BezierCurve.cs.meta b/Runtime/Decal/Curve/BezierCurve.cs.meta deleted file mode 100644 index d368d023..00000000 --- a/Runtime/Decal/Curve/BezierCurve.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aeab7e57c2ffe2740aeacb22ce02d39b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Curve/CurveDecal.cs b/Runtime/Decal/Curve/CurveDecal.cs deleted file mode 100644 index 986ad4fb..00000000 --- a/Runtime/Decal/Curve/CurveDecal.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using System.Linq; -using UnityEngine.Pool; - -namespace net.rs64.TexTransTool.Decal.Curve -{ - internal abstract class CurveDecal : AbstractDecal - { - public float Size = 0.5f; - public uint LoopCount = 1; - public float OutOfRangeOffset = 0f; - public bool IsTextureWarp = true; - public Vector2 TextureWarpRange = new Vector2(0, 0.05f); - public List Segments = new List(); - public bool DrawGizmoAlways = false; - public bool UseFirstAndEnd = false; - public Texture2D DecalTexture; - public Texture2D FirstTexture; - public Texture2D EndTexture; - public float CurveStartOffset; - - public bool IsPossibleSegments - { - get - { - if (Segments.Count <= 1 || Segments.Any(i => i == null)) { return false; } - var segmentPosHash = HashSetPool.Get(); - foreach (var seg in Segments) - { - if (!segmentPosHash.Add(seg.position)) - { - HashSetPool.Release(segmentPosHash); - return false; - } - } - HashSetPool.Release(segmentPosHash); - return true; - } - } - internal override bool IsPossibleApply => TargetRenderers.Any(i => i != null) && IsPossibleSegments; - - - - - } -} \ No newline at end of file diff --git a/Runtime/Decal/Curve/CurveDecal.cs.meta b/Runtime/Decal/Curve/CurveDecal.cs.meta deleted file mode 100644 index b4f2c4c2..00000000 --- a/Runtime/Decal/Curve/CurveDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4a6860e4599d73544b93358f5228f096 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Curve/CurveSegment.cs b/Runtime/Decal/Curve/CurveSegment.cs deleted file mode 100644 index cf083b3b..00000000 --- a/Runtime/Decal/Curve/CurveSegment.cs +++ /dev/null @@ -1,15 +0,0 @@ -using UnityEngine; - - -namespace net.rs64.TexTransTool.Decal.Curve -{ - [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CurveSegment")] - internal class CurveSegment : MonoBehaviour, ITexTransToolTag - { - [HideInInspector,SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; - public int SaveDataVersion => _saveDataVersion; - public Vector3 position => transform.position; - public float Roll = 0f; - - } -} diff --git a/Runtime/Decal/Curve/CurveSegment.cs.meta b/Runtime/Decal/Curve/CurveSegment.cs.meta deleted file mode 100644 index 3c204c30..00000000 --- a/Runtime/Decal/Curve/CurveSegment.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d0307953fd27e0848a83d4e81e963a13 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Curve/CylindricalCurveDecal.cs b/Runtime/Decal/Curve/CylindricalCurveDecal.cs deleted file mode 100644 index 187755b4..00000000 --- a/Runtime/Decal/Curve/CylindricalCurveDecal.cs +++ /dev/null @@ -1,117 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using net.rs64.TexTransTool.Decal.Cylindrical; -using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.Island; - -namespace net.rs64.TexTransTool.Decal.Curve -{ - [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/Unfinished/TTT CylindricalCurveDecal")] - internal class CylindricalCurveDecal : CurveDecal - { - public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; - public bool FilteredBackSide = true; - - public RollMode RollMode = RollMode.WorldUp; - - - public BezierCurve BezierCurve => new BezierCurve(Segments, RollMode); - - internal override Dictionary CompileDecal(ITextureManager textureManager, Dictionary decalCompiledRenderTextures = null) - { - TextureWrap texWarpRange = TextureWrap.NotWrap; - if (IsTextureWarp) - { - texWarpRange = new TextureWrap(texWarpRange.Mode, TextureWarpRange); - } - - decalCompiledRenderTextures ??= new(); - - - int count = 0; - foreach (var quad in BezierCurve.GetQuad(LoopCount, Size, CurveStartOffset)) - { - var targetDecalTexture = DecalTexture; - if (UseFirstAndEnd) - { - if (count == 0) - { - targetDecalTexture = FirstTexture; - } - else if (count == LoopCount - 1) - { - targetDecalTexture = EndTexture; - } - } - RenderTexture mulDecalTexture = GetMultipleDecalTexture(textureManager, targetDecalTexture, Color); - - foreach (var Renderer in TargetRenderers) - { - var CCSSpace = new CCSSpace(CylindricalCoordinatesSystem, quad); - var CCSfilter = new CCSFilter(GetFilers()); - - - DecalUtility.CreateDecalTexture(Renderer, - decalCompiledRenderTextures, - mulDecalTexture, - CCSSpace, - CCSfilter, - TargetPropertyName, - textureWarp: texWarpRange, - defaultPadding: Padding, - highQualityPadding: HighQualityPadding - ); - - count += 1; - } - RenderTexture.ReleaseTemporary(mulDecalTexture); - } - - return decalCompiledRenderTextures; - } - public List> GetFilers() - { - var filters = new List> - { - new CCSFilter.BorderOnPolygonStruct(150), - new CCSFilter.OutOfPerigonStruct(PolygonCulling.Edge, OutOfRangeOffset, false) - }; - - return filters; - } - - - - private void OnDrawGizmosSelected() - { - DrawerGizmo(); - } - - private void OnDrawGizmos() - { - if (DrawGizmoAlways) DrawerGizmo(); - } - - protected virtual void DrawerGizmo() - { - if (!IsPossibleSegments) return; - Gizmos.color = Color.black; - var quads = BezierCurve.GetQuad(LoopCount, Size, CurveStartOffset); - GizmosUtility.DrawGizmoQuad(quads); - GizmosUtility.DrawGizmoLine(Segments.ConvertAll(i => i.position)); - GizmosUtility.DrawGizmoLine(BezierCurve.GetLine()); - - - var bej = BezierCurve; - quads.ForEach(i => i.ForEach(j => - { - var ccsPint = CylindricalCoordinatesSystem.GetCCSPoint(j); - var pos = CylindricalCoordinatesSystem.GetWorldPoint(new Vector3(ccsPint.x, ccsPint.y, 0)); - Gizmos.DrawLine(j, pos); - })); - - } - } -} diff --git a/Runtime/Decal/Curve/CylindricalCurveDecal.cs.meta b/Runtime/Decal/Curve/CylindricalCurveDecal.cs.meta deleted file mode 100644 index d3d5af7f..00000000 --- a/Runtime/Decal/Curve/CylindricalCurveDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d319c770b4f3bed49aaf13713376a949 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Cylindrical.meta b/Runtime/Decal/Cylindrical.meta deleted file mode 100644 index b111259a..00000000 --- a/Runtime/Decal/Cylindrical.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 85158a13eb7d1ca45b649d50ca27198a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs deleted file mode 100644 index 2b7404d6..00000000 --- a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransTool.Utils; -using Unity.Collections; -using UnityEngine; - -namespace net.rs64.TexTransTool.Decal.Cylindrical -{ - [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalCoordinatesSystem")] - internal class CylindricalCoordinatesSystem : MonoBehaviour, ITexTransToolTag - { - public float GizmoRadius = 0.25f; - public float GizmoHeight = 1f; - - [HideInInspector, SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; - public int SaveDataVersion => _saveDataVersion; - - private void OnDrawGizmosSelected() - { - Gizmos.matrix = transform.localToWorldMatrix; - Gizmos.color = Color.black; - - var up = Vector3.up * GizmoHeight; - - Gizmos.DrawWireSphere(Vector3.zero, GizmoRadius); - Gizmos.DrawLine(Vector3.zero, up); - Gizmos.DrawWireSphere(up, GizmoRadius); - } - - public Vector3 GetCCSPoint(Vector3 point) - { - var localPoint = transform.worldToLocalMatrix.MultiplyPoint(point); - var height = localPoint.y; - var angle = Mathf.Atan2(localPoint.x, localPoint.z) * Mathf.Rad2Deg; - var distance = new Vector2(localPoint.x, localPoint.z).magnitude; - - return new Vector3(height, angle, distance); - } - - public Vector3 GetWorldPoint(Vector3 cssPoint) - { - var height = cssPoint.x; - var angle = cssPoint.y * Mathf.Deg2Rad; - var distance = cssPoint.z; - - var x = Mathf.Sin(angle) * distance; - var z = Mathf.Cos(angle) * distance; - - return transform.localToWorldMatrix.MultiplyPoint(new Vector3(x, height, z)); - } - - public static float OffsetAngle(float angle, float offset) - { - var a = angle + offset; - if (a > 180) a -= 360; - if (a < -180) a += 360; - return a; - } - - public static float PositiveNegativeInversion(float angle) - { - return angle + (Mathf.Sign(angle) * -360); - } - - public List VertexConvertCCS(IReadOnlyList vertex, float offSetAngle = 0) - { - List convertVertex = new List(); - foreach (var i in vertex) - { - var cssPoint = GetCCSPoint(i); - convertVertex.Add(new Vector3(cssPoint.x, OffsetAngle(cssPoint.y, offSetAngle), cssPoint.z)); - } - - return convertVertex; - } - - public static void OffSetApply(List vertex, float offset) - { - for (int i = 0; i < vertex.Count; i++) - { - vertex[i] = new Vector3(vertex[i].x, OffsetAngle(vertex[i].y, offset), vertex[i].z); - } - } - - - public static int GetPositiveCount(TriangleIndex tri, List vertex) - { - var positiveCount = 0; - for (int i = 0; i < 3; i++) - { - if (vertex[tri[i]].y > 0) positiveCount += 1; - } - - return positiveCount; - } - - public static void HeightScaleFactor(List ccsVertex, float factor = 100) - { - for (int i = 0; i < ccsVertex.Count; i++) - { - ccsVertex[i] = new Vector3(ccsVertex[i].x * factor, ccsVertex[i].y, ccsVertex[i].z); - } - } - - } - - - internal class CCSSpace : DecalUtility.IConvertSpace - { - public CylindricalCoordinatesSystem CCS; - public IReadOnlyList Quad; - public List CCSVertex; - public List CCSQuad; - public float Offset; - public NativeArray Normalized; - public List QuadNormalizedVertex; - public MeshData MeshData; - - public CCSSpace(CylindricalCoordinatesSystem ccs, IReadOnlyList quad) - { - CCS = ccs; - Quad = quad; - } - - public void Input(MeshData meshData) - { - MeshData = meshData; - var ccsQuad = CCS.VertexConvertCCS(Quad); - var ccsVertex = CCS.VertexConvertCCS(meshData.VertexList); - var offset = ccsQuad.Min(I => I.y) * -1; - - CylindricalCoordinatesSystem.OffSetApply(ccsQuad, offset); - CylindricalCoordinatesSystem.OffSetApply(ccsVertex, offset); - - //円柱座標系での高さの値を大きくするとQuadNormalizeの精度が上がる。 - CylindricalCoordinatesSystem.HeightScaleFactor(ccsVertex); - CylindricalCoordinatesSystem.HeightScaleFactor(ccsQuad); - - Offset = offset; - - var list = DecalUtility.QuadNormalize(ccsQuad.ConvertAll(i => (Vector2)i), - ccsVertex.ConvertAll(i => (Vector2)i)); - Normalized = new NativeArray(list.Count, Allocator.TempJob); - for (int i = 0; i < list.Count; i++) - { - Normalized[i] = list[i]; - } - QuadNormalizedVertex = CollectionsUtility.ZipListVector3(list, ccsVertex.ConvertAll(i => i.z)); - - CCSVertex = ccsVertex; - CCSQuad = ccsQuad; - } - - public NativeArray OutPutUV() - { - return Normalized; - } - - public void Dispose() - { - Normalized.Dispose(); - } - } - - internal class CCSFilter : DecalUtility.ITrianglesFilter - { - public IReadOnlyList> Filters; - CCSSpace _ccsSpace; - - public CCSFilter(IReadOnlyList> filters) - { - Filters = filters; - } - public void SetSpace(CCSSpace space) { _ccsSpace = space; } - - public List GetFilteredSubTriangle(int subMeshIndex) - { - return TriangleFilterUtility.FilteringTriangle(_ccsSpace.MeshData.TrianglesSubMeshList[subMeshIndex], _ccsSpace, Filters); - } - - - public struct InDistanceStruct : TriangleFilterUtility.ITriangleFiltering - { - public float Near; - public bool IsAllVertex; - - public InDistanceStruct(float near, bool isAllVertex) - { - Near = near; - IsAllVertex = isAllVertex; - } - - - public bool Filtering(TriangleIndex tri, CCSSpace space) - { - return TriangleFilterUtility.NearStruct.NearClip(tri, space.QuadNormalizedVertex, Near, IsAllVertex); - } - } - - public struct OutDistanceStruct : TriangleFilterUtility.ITriangleFiltering - { - public float Far; - public bool IsAllVertex; - - public OutDistanceStruct(float far, bool isAllVertex) - { - Far = far; - IsAllVertex = isAllVertex; - } - - public bool Filtering(TriangleIndex tri, CCSSpace space) - { - return TriangleFilterUtility.FarStruct.FarClip(tri, space.QuadNormalizedVertex, Far, IsAllVertex); - } - } - - public struct SideStruct : TriangleFilterUtility.ITriangleFiltering - { - public bool IsReverse; - - public SideStruct(bool isReverse) - { - IsReverse = isReverse; - } - - public bool Filtering(TriangleIndex tri, CCSSpace space) - { - return TriangleFilterUtility.SideStruct.SideCheck(tri, space.QuadNormalizedVertex, IsReverse); - } - } - - public struct BorderOnPolygonStruct : TriangleFilterUtility.ITriangleFiltering - { - public float Threshold /*= 150f */; - - public BorderOnPolygonStruct(float threshold) - { - Threshold = threshold; - } - - public bool Filtering(TriangleIndex tri, CCSSpace Space) - { - return BorderOnPolygon(tri, Space.CCSVertex, Threshold); - } - - public static bool BorderOnPolygon(TriangleIndex tri, List ccsVertex, float threshold = 150) - { - var CCStri = tri.GetTriangle(ccsVertex); - - var positiveCount = CylindricalCoordinatesSystem.GetPositiveCount(tri, ccsVertex); - - if (positiveCount == 0 || positiveCount == 3) return false; - - var min = CCStri.Min(I => I.y); - var max = CCStri.Max(I => I.y); - - return (max - min) > threshold; - } - } - public struct OutOfPerigonStruct : TriangleFilterUtility.ITriangleFiltering - { - public PolygonCulling PolygonCulling; - public float MinRange; - public float MaxRange; - public bool IsAllVertex; - - public OutOfPerigonStruct(PolygonCulling polygonCulling, float outOfRangeOffset, bool isAllVertex) - { - PolygonCulling = polygonCulling; - MinRange = 0 - outOfRangeOffset; - MaxRange = 1 + outOfRangeOffset; - IsAllVertex = isAllVertex; - - } - - public bool Filtering(TriangleIndex targetTri, CCSSpace ccsSpace) - { - switch (PolygonCulling) - { - default: - case PolygonCulling.Vertex: - return TriangleFilterUtility.OutOfPolygonStruct.OutOfPolygonVertexBase(targetTri, ccsSpace.QuadNormalizedVertex, MaxRange, MinRange, IsAllVertex); - case PolygonCulling.Edge: - return TriangleFilterUtility.OutOfPolygonStruct.OutOfPolygonEdgeBase(targetTri, ccsSpace.QuadNormalizedVertex, MaxRange, MinRange, IsAllVertex); - case PolygonCulling.EdgeAndCenterRay: - return TriangleFilterUtility.OutOfPolygonStruct.OutOfPolygonEdgeEdgeAndCenterRayCast(targetTri, ccsSpace.QuadNormalizedVertex, MaxRange, MinRange, IsAllVertex); - } - - } - - - } - } -} diff --git a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs.meta b/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs.meta deleted file mode 100644 index 3a95a6b2..00000000 --- a/Runtime/Decal/Cylindrical/CylindricalCoordinatesSystem.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d6fd239dd20ca8346b9c8cb04c8613d9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/CylindricalDecal.cs b/Runtime/Decal/CylindricalDecal.cs deleted file mode 100644 index 84db1c00..00000000 --- a/Runtime/Decal/CylindricalDecal.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using net.rs64.TexTransTool.Decal.Cylindrical; -using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransTool.Utils; -using UnityEngine.Serialization; -using net.rs64.TexTransCore.Island; - -namespace net.rs64.TexTransTool.Decal -{ - [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/Cylindrical/TTT CylindricalDecal")] - internal sealed class CylindricalDecal : AbstractSingleDecal - { - [FormerlySerializedAs("cylindricalCoordinatesSystem")] public CylindricalCoordinatesSystem CylindricalCoordinatesSystem; - public bool FixedAspect = true; - public Vector2 Scale = Vector2.one; - public bool SideCulling = true; - public float InDistanceCulling = 1f; - public float OutDistanceCulling = 1f; - public float OutOfRangeOffset = 1f; - - internal override CCSSpace GetSpaceConverter() => new CCSSpace(CylindricalCoordinatesSystem, GetQuad()); - internal override DecalUtility.ITrianglesFilter GetTriangleFilter() => new CCSFilter(GetFilters()); - - private List> GetFilters() - { - var filters = new List> - { - new CCSFilter.BorderOnPolygonStruct(), - new CCSFilter.OutOfPerigonStruct(PolygonCulling.Edge, OutOfRangeOffset, false) - }; - - var thisCCSZ = CylindricalCoordinatesSystem.GetCCSPoint(transform.position).z; - - filters.Add(new CCSFilter.OutDistanceStruct(OutDistanceCulling + thisCCSZ, false)); - filters.Add(new CCSFilter.InDistanceStruct(Mathf.Max(thisCCSZ - InDistanceCulling, 0f), false)); - if (SideCulling) filters.Add(new CCSFilter.SideStruct()); - - return filters; - } - - public static readonly Vector3[] LocalQuad = new Vector3[] - { - new Vector3(-0.5f, -0.5f, 0), - new Vector3(0.5f, -0.5f, 0), - new Vector3(-0.5f, 0.5f, 0), - new Vector3(0.5f, 0.5f, 0), - }; - - - public List GetQuad() - { - var matrix = transform.localToWorldMatrix; - var worldSpaceQuad = new List(4); - foreach (var i in LocalQuad) - { - worldSpaceQuad.Add(matrix.MultiplyPoint(i)); - } - return worldSpaceQuad; - } - - void OnDrawGizmosSelected() - { - if (CylindricalCoordinatesSystem == null) { return; } - Gizmos.color = Color.black; - var Matrix = Matrix4x4.identity; - Gizmos.matrix = Matrix; - - - var quad = GetQuad(); - - foreach (var fromPoint in quad) - { - var ccsPoint = CylindricalCoordinatesSystem.GetCCSPoint(fromPoint); - ccsPoint.z = Mathf.Max(ccsPoint.z - InDistanceCulling, 0f); - var offSetToPoint = CylindricalCoordinatesSystem.GetWorldPoint(ccsPoint); - - var ccsFromPoint = CylindricalCoordinatesSystem.GetCCSPoint(fromPoint); - ccsFromPoint.z += OutDistanceCulling; - var OffSetFromPoint = CylindricalCoordinatesSystem.GetWorldPoint(ccsFromPoint); - - Gizmos.DrawLine(OffSetFromPoint, offSetToPoint); - } - - for (int count = 0; 4 > count; count += 1) - { - var (From, To) = GetEdge(quad, count); - Gizmos.DrawLine(From, To); - } - - DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, transform.localToWorldMatrix); - - } - public static (Vector3, Vector3) GetEdge(IReadOnlyList quad, int Count) - { - switch (Count) - { - default: - case 0: - { - return (quad[0], quad[1]); - } - case 1: - { - return (quad[0], quad[2]); - } - case 2: - { - return (quad[2], quad[3]); - } - case 3: - { - return (quad[1], quad[3]); - } - } - } - - } -} diff --git a/Runtime/Decal/CylindricalDecal.cs.meta b/Runtime/Decal/CylindricalDecal.cs.meta deleted file mode 100644 index ef6c07c9..00000000 --- a/Runtime/Decal/CylindricalDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5dafc3f3b841ead4fb8be70ab7afff8e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/DisplayDecalTexture.shader b/Runtime/Decal/DisplayDecalTexture.shader deleted file mode 100644 index dda78108..00000000 --- a/Runtime/Decal/DisplayDecalTexture.shader +++ /dev/null @@ -1,59 +0,0 @@ -Shader "Hidden/DisplayDecalTexture" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - _MulColor ("MulColor", Color) = (1,1,1,1) - _Alpha ("Alpha", Range (0, 1)) = 0.5 - } - SubShader - { - Tags { "RenderType"="Transparent" } - LOD 100 - Blend SrcAlpha OneMinusSrcAlpha - Cull Off - ZWrite Off - Pass - { - HLSLPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - sampler2D _MainTex; - float4 _MainTex_ST; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = TRANSFORM_TEX(v.uv, _MainTex); - return o; - } - float4 _MulColor; - float _Alpha; - fixed4 frag (v2f i) : SV_Target - { - // sample the texture - float4 col = tex2D(_MainTex, i.uv); - col.a *= _Alpha; - col *= _MulColor; - return col; - } - ENDHLSL - } - } -} diff --git a/Runtime/Decal/DisplayDecalTexture.shader.meta b/Runtime/Decal/DisplayDecalTexture.shader.meta deleted file mode 100644 index aa1b8571..00000000 --- a/Runtime/Decal/DisplayDecalTexture.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 08b0159fedf8f7f4687e93d5b65a3976 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index e8acd7e6..ce6425d6 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using UnityEngine; -using net.rs64.TexTransTool.Decal.Cylindrical; using net.rs64.TexTransCore.Decal; using net.rs64.TexTransTool.Utils; -using UnityEngine.Serialization; using net.rs64.TexTransCore.Island; using net.rs64.TexTransCore.TransTextureCore; using net.rs64.TexTransTool.IslandSelector; diff --git a/Runtime/Decal/NailEditor.cs b/Runtime/Decal/NailEditor.cs deleted file mode 100644 index 1080b420..00000000 --- a/Runtime/Decal/NailEditor.cs +++ /dev/null @@ -1,310 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using System.Linq; -using System; -using System.Collections; -using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.Island; -using net.rs64.TexTransTool.IslandSelector; - -namespace net.rs64.TexTransTool.Decal -{ - - [AddComponentMenu("TexTransTool/" + TextureBlender.FoldoutName + "/TTT NailEditor")] - public sealed class NailEditor : AbstractDecal - { - public Animator TargetAvatar; - - public NailSet LeftHand; - public NailSet RightHand; - - public bool UseTextureAspect = false; - - - - internal override bool IsPossibleApply => TargetAvatar != null && TargetRenderers.Any(i => i != null); - - internal override Dictionary CompileDecal(ITextureManager textureManager, Dictionary decalCompiledRenderTextures = null) - { - decalCompiledRenderTextures ??= new(); - - foreach (var nailTexSpaceFilter in GetNailTexSpaceFilters()) - { - foreach (var renderer in TargetRenderers) - { - if (renderer == null) { continue; } - DecalUtility.CreateDecalTexture( - renderer, - decalCompiledRenderTextures, - nailTexSpaceFilter.Item1, - nailTexSpaceFilter.Item2, - nailTexSpaceFilter.Item3, - TargetPropertyName, - GetTextureWarp, - Padding, - HighQualityPadding - ); - } - } - return decalCompiledRenderTextures; - } - - List<(Texture2D, ParallelProjectionSpace, IslandSelectToPPFilter)> GetNailTexSpaceFilters() - { - var spaceList = new List<(Texture2D, ParallelProjectionSpace, IslandSelectToPPFilter)>(); - - - CompileNail(LeftHand, false); - CompileNail(RightHand, true); - - - void CompileNail(NailSet nailSet, bool IsRight) - { - foreach (var NailDD in nailSet) - { - var finger = NailDD.Item1; - var nailDecalDescription = NailDD.Item2; - if (nailDecalDescription.DecalTexture == null) continue; - var souseFingerTF = GetFinger(finger, IsRight); - var matrix = GetNailMatrix(souseFingerTF, nailDecalDescription, nailSet.FingerUpVector, IsRight); - - var islandSelector = new IslandSelectorRay(new Ray(matrix.MultiplyPoint(Vector3.zero), matrix.MultiplyVector(Vector3.forward)), matrix.lossyScale.z * 1); - - - var SpaceConverter = new ParallelProjectionSpace(matrix.inverse); - var Filter = new IslandSelectToPPFilter(new RayCastIslandSelectorClass(islandSelector), GetFilter()); - - spaceList.Add((nailDecalDescription.DecalTexture, SpaceConverter, Filter)); - } - } - - return spaceList; - } - - internal List>> GetFilter() - { - return new List>> - { - new TriangleFilterUtility.FarStruct(1, false), - new TriangleFilterUtility.NearStruct(0, true), - new TriangleFilterUtility.SideStruct(), - new TriangleFilterUtility.OutOfPolygonStruct(PolygonCulling.Edge, 0, 1, true) - }; - } - - private void OnDrawGizmosSelected() - { - if (TargetAvatar == null) return; - - DrawNailGizmo(LeftHand, false); - DrawNailGizmo(RightHand, true); - - - - void DrawNailGizmo(NailSet nailSet, bool isRight) - { - foreach (var NailDD in nailSet) - { - var Finger = NailDD.Item1; - var nailDecalDescription = NailDD.nailDecalDescription; - var souseFingerTF = GetFinger(Finger, isRight); - var matrix = GetNailMatrix(souseFingerTF, nailDecalDescription, nailSet.FingerUpVector, isRight); - - Gizmos.matrix = matrix; - DecalGizmoUtility.DrawGizmoQuad(NailDD.nailDecalDescription.DecalTexture, Color.white, matrix); - Gizmos.DrawWireCube(new Vector3(0, 0, 0.5f), new Vector3(1, 1, 1)); - Gizmos.DrawLine(Vector3.zero, Vector3.forward); - } - } - } - - private Matrix4x4 GetNailMatrix(Transform souseFingerTF, NailDecalDescription nailDecalDescription, UpVector FingerUpVector, bool InvarsRight) - { - var fingerSize = souseFingerTF.localPosition.magnitude; - var sRot = souseFingerTF.rotation; - - switch (FingerUpVector) - { - default: - case UpVector.ZMinus: - break; - case UpVector.ZPlus: - sRot *= Quaternion.Euler(0, 180, 0); - break; - case UpVector.YMinus: - sRot *= Quaternion.Euler(90, 0, 0); - break; - case UpVector.YPlus: - sRot *= Quaternion.Euler(-90, 0, 0); - break; - case UpVector.XMinus: - sRot *= Quaternion.Euler(0, 90, 0); - break; - case UpVector.XPlus: - sRot *= Quaternion.Euler(0, -90, 0); - break; - - } - - var nailPos = souseFingerTF.position; - nailPos += sRot * (souseFingerTF.localPosition * 0.9f); - nailPos += sRot * new Vector3(0, 0, fingerSize * -0.25f); - nailPos += sRot * (!InvarsRight ? nailDecalDescription.PositionOffset : PosOffsetInverseRight(nailDecalDescription.PositionOffset)); - var nailRot = sRot * Quaternion.Euler(!InvarsRight ? nailDecalDescription.RotationOffset : RotOffsetInverseRight(nailDecalDescription.RotationOffset)); - var nailSize = nailDecalDescription.ScaleOffset * fingerSize * 0.75f; - - if (UseTextureAspect && nailDecalDescription.DecalTexture != null) { nailSize.y *= (float)nailDecalDescription.DecalTexture.height / (float)nailDecalDescription.DecalTexture.width; } - - return Matrix4x4.TRS(nailPos, nailRot, nailSize); - } - - internal Vector3 PosOffsetInverseRight(Vector3 positionOffset) - { - return new Vector3(positionOffset.x * -1, positionOffset.y, positionOffset.z); - } - internal Vector3 RotOffsetInverseRight(Vector3 rotationOffset) - { - return new Vector3(rotationOffset.x, rotationOffset.y * -1, rotationOffset.z * -1); - } - internal Transform GetFinger(Finger finger, bool IsRight) - { - return TargetAvatar.GetBoneTransform(ConvertHumanBodyBones(finger, IsRight)); - } - - internal HumanBodyBones ConvertHumanBodyBones(Finger finger, bool IsRight) - { - switch (finger) - { - default: - case Finger.Thumb: - return !IsRight ? HumanBodyBones.LeftThumbDistal : HumanBodyBones.RightThumbDistal; - case Finger.Index: - return !IsRight ? HumanBodyBones.LeftIndexDistal : HumanBodyBones.RightIndexDistal; - case Finger.Middle: - return !IsRight ? HumanBodyBones.LeftMiddleDistal : HumanBodyBones.RightMiddleDistal; - case Finger.Ring: - return !IsRight ? HumanBodyBones.LeftRingDistal : HumanBodyBones.RightRingDistal; - case Finger.Little: - return !IsRight ? HumanBodyBones.LeftLittleDistal : HumanBodyBones.RightLittleDistal; - } - } - } - - [Serializable] - public class NailSet : IEnumerable<(Finger finger, NailDecalDescription nailDecalDescription)> - { - public UpVector FingerUpVector; - - public NailDecalDescription Thumb; - public NailDecalDescription Index; - public NailDecalDescription Middle; - public NailDecalDescription Ring; - public NailDecalDescription Little; - - public NailSet() - { - Thumb = new NailDecalDescription(); - Index = new NailDecalDescription(); - Middle = new NailDecalDescription(); - Ring = new NailDecalDescription(); - Little = new NailDecalDescription(); - } - - IEnumerator<(Finger finger, NailDecalDescription nailDecalDescription)> IEnumerable<(Finger finger, NailDecalDescription nailDecalDescription)>.GetEnumerator() - { - yield return (Finger.Thumb, Thumb); - yield return (Finger.Index, Index); - yield return (Finger.Middle, Middle); - yield return (Finger.Ring, Ring); - yield return (Finger.Little, Little); - } - IEnumerator IEnumerable.GetEnumerator() - { - yield return (Finger.Thumb, Thumb); - yield return (Finger.Index, Index); - yield return (Finger.Middle, Middle); - yield return (Finger.Ring, Ring); - yield return (Finger.Little, Little); - } - - public void Copy(NailSet Souse) - { - FingerUpVector = Souse.FingerUpVector; - Thumb.Copy(Souse.Thumb); - Index.Copy(Souse.Index); - Middle.Copy(Souse.Middle); - Ring.Copy(Souse.Ring); - Little.Copy(Souse.Little); - } - public void Copy(NailOffSets Souse) - { - FingerUpVector = Souse.UpVector; - Thumb.Copy(Souse.Thumb); - Index.Copy(Souse.Index); - Middle.Copy(Souse.Middle); - Ring.Copy(Souse.Ring); - Little.Copy(Souse.Little); - - } - public NailSet Clone() - { - var newI = new NailSet(); - newI.Copy(this); - return newI; - } - - } - - [Serializable] - public class NailDecalDescription - { - public Texture2D DecalTexture; - - public Vector3 PositionOffset = Vector3.zero; - public Vector3 ScaleOffset = Vector3.one; - public Vector3 RotationOffset = Vector3.zero; - - public void Copy(NailDecalDescription souse) - { - DecalTexture = souse.DecalTexture; - PositionOffset = souse.PositionOffset; - ScaleOffset = souse.ScaleOffset; - RotationOffset = souse.RotationOffset; - } - public NailDecalDescription Clone() - { - var newI = new NailDecalDescription(); - newI.Copy(this); - return newI; - } - - public void Copy(NailOffset souse) - { - PositionOffset = souse.PositionOffset; - ScaleOffset = souse.ScaleOffset; - RotationOffset = souse.RotationOffset; - } - } - - internal enum Finger - { - Thumb, - Index, - Middle, - Ring, - Little, - } - - public enum UpVector - { - ZMinus, - ZPlus, - YMinus, - YPlus, - XMinus, - XPlus, - } - -} - diff --git a/Runtime/Decal/NailEditor.cs.meta b/Runtime/Decal/NailEditor.cs.meta deleted file mode 100644 index dbe91345..00000000 --- a/Runtime/Decal/NailEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a3836100b8e0ea54abee01abc00be6ed -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/NailOffsetData.cs b/Runtime/Decal/NailOffsetData.cs deleted file mode 100644 index 3b7fa6cc..00000000 --- a/Runtime/Decal/NailOffsetData.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using UnityEngine; - -namespace net.rs64.TexTransTool.Decal -{ - [CreateAssetMenu(fileName = "NailOffsetData", menuName = "TexTransTool/NailOffsetData", order = 1)] - public sealed class NailOffsetData : ScriptableObject , ITexTransToolTag - { - [HideInInspector,SerializeField] int _saveDataVersion = TexTransBehavior.TTTDataVersion; - public int SaveDataVersion => _saveDataVersion; - public NailOffSets LeftHand = new NailOffSets(); - public NailOffSets RightHand = new NailOffSets(); - } - [Serializable] - public sealed class NailOffSets - { - public UpVector UpVector; - - public NailOffset Thumb = new NailOffset(); - public NailOffset Index = new NailOffset(); - public NailOffset Middle = new NailOffset(); - public NailOffset Ring = new NailOffset(); - public NailOffset Little = new NailOffset(); - - public void Copy(NailOffSets souse) - { - UpVector = souse.UpVector; - - Thumb.Copy(souse.Thumb); - Index.Copy(souse.Index); - Middle.Copy(souse.Middle); - Ring.Copy(souse.Ring); - Little.Copy(souse.Little); - } - public void Copy(NailSet souse) - { - UpVector = souse.FingerUpVector; - - Thumb.Copy(souse.Thumb); - Index.Copy(souse.Index); - Middle.Copy(souse.Middle); - Ring.Copy(souse.Ring); - Little.Copy(souse.Little); - } - public NailOffSets Clone() - { - var newNailOffsets = new NailOffSets(); - newNailOffsets.Copy(this); - return newNailOffsets; - } - - } - [Serializable] - public sealed class NailOffset - { - - public Vector3 PositionOffset = Vector3.zero; - public Vector3 ScaleOffset = Vector3.one; - public Vector3 RotationOffset = Vector3.zero; - - public void Copy(NailOffset souse) - { - PositionOffset = souse.PositionOffset; - ScaleOffset = souse.ScaleOffset; - RotationOffset = souse.RotationOffset; - } - public void Copy(NailDecalDescription souse) - { - PositionOffset = souse.PositionOffset; - ScaleOffset = souse.ScaleOffset; - RotationOffset = souse.RotationOffset; - } - - public NailOffset Clone() - { - var newNailOffset = new NailOffset(); - newNailOffset.Copy(this); - return newNailOffset; - } - } -} diff --git a/Runtime/Decal/NailOffsetData.cs.meta b/Runtime/Decal/NailOffsetData.cs.meta deleted file mode 100644 index f1e59102..00000000 --- a/Runtime/Decal/NailOffsetData.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 723243c6534475f459c60a293ea3dea1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index bf13d107..33d793b2 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -2,19 +2,31 @@ using System.Collections.Generic; using UnityEngine.Serialization; using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.Island; using net.rs64.TexTransTool.Utils; using net.rs64.TexTransTool.IslandSelector; using System; using System.Linq; +using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.TransTextureCore; +using UnityEngine.Pool; +using UnityEngine.Profiling; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransTool.Decal { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public sealed class SimpleDecal : AbstractSingleDecal + public sealed class SimpleDecal : TexTransRuntimeBehavior//AbstractSingleDecal { internal const string ComponentName = "TTT SimpleDecal"; internal const string MenuPath = ComponentName; + public List TargetRenderers = new List { null }; + public bool MultiRendererMode = false; + [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; + + public Color Color = Color.white; + public PropertyName TargetPropertyName = PropertyName.DefaultValue; + public float Padding = 5; + public bool HighQualityPadding = false; public bool FixedAspect = true; [FormerlySerializedAs("SideChek")] public bool SideCulling = true; [FormerlySerializedAs("PolygonCaling")] public PolygonCulling PolygonCulling = PolygonCulling.Vertex; @@ -23,17 +35,116 @@ public sealed class SimpleDecal : AbstractSingleDecal UseDepth ? new bool?(DepthInvert) : null; + internal bool? GetUseDepthOrInvert => UseDepth ? new bool?(DepthInvert) : null; + + #region V3SaveData + [Obsolete("V3SaveData", true)][SerializeField] internal bool IslandCulling = false; + [Obsolete("V3SaveData", true)][SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); + [Obsolete("V3SaveData", true)][SerializeField] internal float IslandSelectorRange = 1; + #endregion V3SaveData + + + #region V1SaveData + [Obsolete("Replaced with BlendTypeKey", true)][HideInInspector][SerializeField] internal BlendType BlendType = BlendType.Normal; + #endregion + #region V0SaveData + [Obsolete("V0SaveData", true)][HideInInspector] public bool MigrationV0ClearTarget; + [Obsolete("V0SaveData", true)][HideInInspector] public GameObject MigrationV0DataMatAndTexSeparatorGameObject; + [Obsolete("V0SaveData", true)][HideInInspector] public MatAndTexUtils.MatAndTexRelativeSeparator MigrationV0DataMatAndTexSeparator; + [Obsolete("V0SaveData", true)][HideInInspector] public SimpleDecal MigrationV0DataAbstractDecal; + [Obsolete("V0SaveData", true)][HideInInspector] public bool IsSeparateMatAndTexture; + [Obsolete("V0SaveData", true)][HideInInspector] public bool FastMode = true; + #endregion + + internal override List GetRenderers => TargetRenderers; + internal override TexTransPhase PhaseDefine => TexTransPhase.AfterUVModification; + + internal override void Apply(IDomain domain) + { + if (!IsPossibleApply) { TTTRuntimeLog.Error(GetType().Name + ":error:TTTNotExecutable"); return; } + + var decalCompiledTextures = CompileDecal(domain.GetTextureManager(), DictionaryPool.Get()); + + foreach (var matAndTex in decalCompiledTextures) + { + domain.AddTextureStack(matAndTex.Key.GetTexture(TargetPropertyName), new TextureBlend.BlendTexturePair(matAndTex.Value, BlendTypeKey)); + } + + DictionaryPool.Release(decalCompiledTextures); + + } + + internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureManager, Texture2D souseDecalTexture, Color color) + { + RenderTexture mulDecalTexture; + + if (souseDecalTexture != null) + { + var decalSouseSize = textureManager.GetOriginalTextureSize(souseDecalTexture); + mulDecalTexture = RenderTexture.GetTemporary(decalSouseSize, decalSouseSize, 0); + } + else { mulDecalTexture = RenderTexture.GetTemporary(32, 32, 0); } + mulDecalTexture.Clear(); + if (souseDecalTexture != null) + { + var tempRt = textureManager.GetOriginTempRt(souseDecalTexture); + TextureBlend.MultipleRenderTexture(mulDecalTexture, tempRt, color); + RenderTexture.ReleaseTemporary(tempRt); + } + else + { + TextureBlend.ColorBlit(mulDecalTexture, color); + } + return mulDecalTexture; + } + + internal override IEnumerable GetDependency() + { + var dependencies = new UnityEngine.Object[] { transform } + .Concat(GetComponentsInParent(true)) + .Concat(TargetRenderers) + .Concat(TargetRenderers.Select(r => r.transform)) + .Concat(TargetRenderers.Select(r => r.GetMesh())) + .Concat(TargetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)) + .Append(DecalTexture); - //次のマイナーで obsolete にする - [SerializeField] internal bool IslandCulling = false; - [SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); - [SerializeField] internal float IslandSelectorRange = 1; + if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } + return dependencies; + } + [ExpandTexture2D] public Texture2D DecalTexture; + internal override bool IsPossibleApply => TargetRenderers.Any(i => i != null); + internal Dictionary CompileDecal(ITextureManager textureManager, Dictionary decalCompiledRenderTextures = null) + { + Profiler.BeginSample("GetMultipleDecalTexture"); + RenderTexture mulDecalTexture = GetMultipleDecalTexture(textureManager, DecalTexture, Color); + Profiler.EndSample(); + decalCompiledRenderTextures ??= new(); + foreach (var renderer in TargetRenderers) + { + if (renderer == null) { continue; } + Profiler.BeginSample("CreateDecalTexture"); + DecalUtility.CreateDecalTexture( + renderer, + decalCompiledRenderTextures, + mulDecalTexture, + GetSpaceConverter(), + GetTriangleFilter(), + TargetPropertyName, + TextureWrap.NotWrap, + Padding, + HighQualityPadding, + GetUseDepthOrInvert + ); + Profiler.EndSample(); + } + RenderTexture.ReleaseTemporary(mulDecalTexture); + return decalCompiledRenderTextures; + } - internal override ParallelProjectionSpace GetSpaceConverter() { return new ParallelProjectionSpace(transform.worldToLocalMatrix); } - internal override DecalUtility.ITrianglesFilter GetTriangleFilter() + internal ParallelProjectionSpace GetSpaceConverter() { return new ParallelProjectionSpace(transform.worldToLocalMatrix); } + internal DecalUtility.ITrianglesFilter GetTriangleFilter() { if (IslandSelector != null) { return new IslandSelectToPPFilter(IslandSelector, GetFilter()); } return new ParallelProjectionFilter(GetFilter()); @@ -52,7 +163,6 @@ internal override DecalUtility.ITrianglesFilter GetTria return filters; } - internal void OnDrawGizmosSelected() { Gizmos.color = Color.black; @@ -67,13 +177,6 @@ internal void OnDrawGizmosSelected() DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, matrix); } - internal override IEnumerable GetDependency() - { - var dependencies = base.GetDependency(); - if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } - return dependencies; - } - } } diff --git a/Runtime/Decal/UnlitColorAndAlpha.shader b/Runtime/Decal/UnlitColorAndAlpha.shader deleted file mode 100644 index 967eda91..00000000 --- a/Runtime/Decal/UnlitColorAndAlpha.shader +++ /dev/null @@ -1,47 +0,0 @@ -Shader "Hidden/UnlitColorAndAlpha" -{ - Properties - { - _Color ("Color", Color) = (1,1,1,1) - } - SubShader - { - Tags { "RenderType"="Opaque" } - LOD 100 - - Pass - { - HLSLPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - }; - - struct v2f - { - float4 vertex : SV_POSITION; - }; - - float4 _Color; - - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - return o; - } - - fixed4 frag (v2f i) : SV_Target - { - return _Color; - } - ENDHLSL - } - } -} diff --git a/Runtime/Decal/UnlitColorAndAlpha.shader.meta b/Runtime/Decal/UnlitColorAndAlpha.shader.meta deleted file mode 100644 index b05422aa..00000000 --- a/Runtime/Decal/UnlitColorAndAlpha.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 9f911e811697bff4f8c180f2ed3f6e99 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs index 77e0b3da..87286649 100644 --- a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs @@ -42,7 +42,7 @@ public List FindRayCast(GameObject findRoot) return hits; } - public void AddToDecal(AbstractDecal abstractDecal, List renderers) + public void AddToDecal(SimpleDecal abstractDecal, List renderers) { var rendererHash = new HashSet(abstractDecal.TargetRenderers); foreach (var renderer in renderers) diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs index 8bedec0c..75cc10fe 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererMultiResolver.cs @@ -16,7 +16,7 @@ public override void Resolving(ResolverContext avatar) var hits = FindRayCast(avatar.AvatarRoot); - foreach (var abstractDecal in ResolveTargetRoot.GetComponentsInChildren()) + foreach (var abstractDecal in ResolveTargetRoot.GetComponentsInChildren()) { AddToDecal(abstractDecal, hits); } diff --git a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs index 8657e4d8..03ecd940 100644 --- a/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/RayCastRendererResolver.cs @@ -8,7 +8,7 @@ internal class RayCastRendererResolver : AbstractRayCastRendererResolver { internal const string ComponentName = "TTT Decal RendererResolver"; private const string MenuPath = FoldoutName + "/" + ComponentName; - public AbstractDecal ResolveTarget; + public SimpleDecal ResolveTarget; public override void Resolving(ResolverContext avatar) { From 7a13ba8982988b4da61178db2f8e5f80212f48e6 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 27 Apr 2024 19:21:01 +0900 Subject: [PATCH 118/208] chore: added argument domainRenderers to GetDependency --- Editor/Preview/RealTime/RealTimePreviewContext.cs | 15 ++++++++------- .../MatAndTexUtils/MaterialModifier.cs | 2 +- Runtime/CommonComponent/TextureBlender.cs | 2 +- Runtime/Decal/SimpleDecal.cs | 2 +- Runtime/MultiLayerImage/MultiLayerImageCanvas.cs | 2 +- Runtime/TexTransRuntimeBehavior.cs | 2 +- Runtime/TextureAtlas/AtlasTexture.cs | 2 +- 7 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index 76199037..e7eb0e71 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -68,7 +68,7 @@ void AddPreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) } if (ContainsBehavior(texTransRuntimeBehavior)) { return; } - foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency().Append(texTransRuntimeBehavior).Where(g => g != null).Select(g => g.GetInstanceID())) + foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency(_previewDomain.EnumerateRenderer()).Append(texTransRuntimeBehavior).Where(g => g != null).Select(g => g.GetInstanceID())) { if (!_dependencyMap.ContainsKey(dependInstanceID)) { _dependencyMap[dependInstanceID] = new(); } _dependencyMap[dependInstanceID].Add(texTransRuntimeBehavior); @@ -123,12 +123,13 @@ void DependEnqueueOfInstanceID(int instanceId) foreach (var t in _dependencyMap[instanceId]) { _updateQueue.Enqueue(t); } } } - void RealTimePreviewRestart() - { - var domainRoot = _previewDomain.DomainRoot; - ExitRealTimePreview(); - EnterRealtimePreview(domainRoot); - } + } + + internal void RealTimePreviewRestart() + { + var domainRoot = _previewDomain.DomainRoot; + ExitRealTimePreview(); + EnterRealtimePreview(domainRoot); } void UpdatePreview() diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index 38e62f77..66d29c11 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -90,7 +90,7 @@ internal override void Apply([NotNull] IDomain domain) domain.ReplaceMaterials(modMatList); } - internal override IEnumerable GetDependency() + internal override IEnumerable GetDependency(IEnumerable domainRenderers) { foreach (var i in ModifiedTarget) { yield return i; } foreach (var i in TargetRenderers) { yield return i; } diff --git a/Runtime/CommonComponent/TextureBlender.cs b/Runtime/CommonComponent/TextureBlender.cs index 98ccc03d..889bfae1 100644 --- a/Runtime/CommonComponent/TextureBlender.cs +++ b/Runtime/CommonComponent/TextureBlender.cs @@ -38,6 +38,6 @@ internal override void Apply(IDomain domain) domain.AddTextureStack(distTex, new(addTex, BlendTypeKey)); } - internal override IEnumerable GetDependency() { return TargetTexture.GetDependency().Append(BlendTexture); } + internal override IEnumerable GetDependency(IEnumerable domainRenderers) { return TargetTexture.GetDependency().Append(BlendTexture); } } } diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 33d793b2..93aa68cf 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -98,7 +98,7 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan return mulDecalTexture; } - internal override IEnumerable GetDependency() + internal override IEnumerable GetDependency(IEnumerable renderers) { var dependencies = new UnityEngine.Object[] { transform } .Concat(GetComponentsInParent(true)) diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 204914d6..272d04c9 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -65,7 +65,7 @@ internal static int NormalizePowOfTow(int v) else { return nextV; } } - internal override IEnumerable GetDependency() + internal override IEnumerable GetDependency(IEnumerable domainRenderers) { var chileLayers = GetChileLayers(); return TextureSelector.GetDependency().Append(tttImportedCanvasDescription).Concat(chileLayers).Concat(chileLayers.SelectMany(l => l.GetDependency())); diff --git a/Runtime/TexTransRuntimeBehavior.cs b/Runtime/TexTransRuntimeBehavior.cs index 23347d98..6aff596e 100644 --- a/Runtime/TexTransRuntimeBehavior.cs +++ b/Runtime/TexTransRuntimeBehavior.cs @@ -18,6 +18,6 @@ public abstract class TexTransRuntimeBehavior : TexTransBehavior, ITexTransToolT /// /// Enumerates references that depend on the component externally. /// - internal abstract IEnumerable GetDependency(); + internal abstract IEnumerable GetDependency(IEnumerable domainRenderers); } } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 941e3299..15042126 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -837,7 +837,7 @@ internal static List FilteredRenderers(GameObject targetRoot, bool inc return result; } - internal override IEnumerable GetDependency() + internal override IEnumerable GetDependency(IEnumerable domainRenderers) { return AtlasSetting.IslandFineTuners.SelectMany(i => i.GetDependency()) .Concat(Renderers) From 1bf6f6b382978b54aea86db7008d2b6717b7dd03 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 27 Apr 2024 19:23:00 +0900 Subject: [PATCH 119/208] optimize: TriangleFilter of job Burst --- Runtime/Decal/IslandSelectToPPFilter.cs | 77 ++++-- Runtime/Decal/SimpleDecal.cs | 38 ++- .../Decal/AbstractRayCastRendererResolver.cs | 2 +- TexTransCore/Decal/DecalContext.cs | 111 ++++++++ ...alUtility.cs.meta => DecalContext.cs.meta} | 0 TexTransCore/Decal/DecalUtility.cs | 206 -------------- TexTransCore/Decal/MeshData.cs | 1 + .../ParallelProjectionFilter.cs | 62 ++++- .../ParallelProjectionSpace.cs | 5 +- TexTransCore/Decal/TriangleFilterUtility.cs | 258 +++++++++++------- .../TransTextureCore/Utils/RendererUtility.cs | 2 +- .../TransTextureCore/Utils/VectorUtility.cs | 97 ++++++- TexTransCore/Unsafe/InternalsVisible.cs | 3 +- .../Unsafe/UnsafeNativeArrayUtility.cs | 7 + 14 files changed, 498 insertions(+), 371 deletions(-) create mode 100644 TexTransCore/Decal/DecalContext.cs rename TexTransCore/Decal/{DecalUtility.cs.meta => DecalContext.cs.meta} (100%) delete mode 100644 TexTransCore/Decal/DecalUtility.cs diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index ce6425d6..505a6766 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -8,16 +8,21 @@ using System.Linq; using UnityEngine.Profiling; using net.rs64.TexTransCore; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using System.Threading.Tasks; +using System.Runtime.CompilerServices; +using System.Collections; namespace net.rs64.TexTransTool.Decal { - internal class IslandSelectToPPFilter : DecalUtility.ITrianglesFilter + internal class IslandSelectToPPFilter : ITrianglesFilter { - public List>> Filters; + public JobChain>>[] Filters; public IIslandSelector IslandSelector; - public IslandSelectToPPFilter(IIslandSelector islandSelector, List>> filters) + public IslandSelectToPPFilter(IIslandSelector islandSelector, JobChain>>[] filters) { IslandSelector = islandSelector; Filters = filters; @@ -25,14 +30,34 @@ public IslandSelectToPPFilter(IIslandSelector islandSelector, List[] _islandSelectedTriangles; + JobResult>[] _filteredBit; + NativeArray[] _filteredTriangles; - //これSetされた瞬間からマルチスレッドでにフィルタリングを走らせるのもありなのではないか? + public void SetSpace(ParallelProjectionSpace space) + { + _ppSpace = space; - public List GetFilteredSubTriangle(int subMeshIndex) + var smCount = _ppSpace.MeshData.TriangleIndex.Length; + _islandSelectedTriangles = new NativeArray[smCount]; + _filteredBit = new JobResult>[smCount]; + _filteredTriangles = new NativeArray[smCount]; + for (var i = 0; smCount > i; i += 1) + { + var islandSelected = _islandSelectedTriangles[i] = IslandSelectExecute(i); + var ppsVert = _ppSpace.GetPPSVert; + _filteredBit[i] = TriangleFilterUtility.FilteringTriangle(islandSelected, ppsVert, Filters); + } + } + NativeArray ITrianglesFilter.GetFilteredSubTriangle(int subMeshIndex) { - if (_ppSpace is null) { return null; } + if (_ppSpace is null) { return default; } + var filteredTriangle = _filteredTriangles[subMeshIndex] = ParallelProjectionFilter.FilteringExecute(_ppSpace.MeshData.TriangleIndex[subMeshIndex], _filteredBit[subMeshIndex].GetResult); + return filteredTriangle; + } + private NativeArray IslandSelectExecute(int subMeshIndex) + { var meshData = _ppSpace.MeshData; Island[] islands = (subMeshIndex, meshData).Memo(GetIslands); @@ -47,25 +72,41 @@ public List GetFilteredSubTriangle(int subMeshIndex) Profiler.EndSample(); Profiler.BeginSample("FilterTriangle"); - var linkList = new LinkedList(); + var triList = IslandSelectToTriangleIndex(islands, bitArray); + Profiler.EndSample(); + + return triList; + } + + private static NativeArray IslandSelectToTriangleIndex(Island[] islands, BitArray bitArray) + { + var triCount = 0; + for (var i = 0; islands.Length > i; i += 1) { if (bitArray[i]) { triCount += islands[i].triangles.Count; } } + var list = new NativeArray(triCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + + var writePos = 0; for (var i = 0; islands.Length > i; i += 1) { if (!bitArray[i]) { continue; } - var island = islands[i]; - var triCount = island.triangles.Count; - for (var triIndex = 0; triCount > triIndex; triIndex += 1) + foreach (var tri in islands[i].triangles) { - linkList.AddLast(island.triangles[triIndex]); + list[writePos] = tri; + writePos += 1; } } - Profiler.EndSample(); + return list; + } - return TriangleFilterUtility.FilteringTriangle(linkList.ToList(), _ppSpace.GetPPSVert.AsList(), Filters); + static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) + { + return IslandUtility.UVtoIsland(pair.meshData.TriangleIndex[pair.subMeshIndex].AsList(), pair.meshData.UVList).ToArray(); + } - static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) - { - return IslandUtility.UVtoIsland(pair.meshData.TriangleIndex[pair.subMeshIndex].AsList(), pair.meshData.UVList).ToArray(); - } + public void Dispose() + { + foreach (var na in _islandSelectedTriangles) { na.Dispose(); } + foreach (var na in _filteredBit) { na.GetResult.Dispose(); } + foreach (var na in _filteredTriangles) { na.Dispose(); } } } } diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 93aa68cf..f9f95377 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -11,6 +11,7 @@ using UnityEngine.Pool; using UnityEngine.Profiling; using net.rs64.TexTransCore.TransTextureCore.Utils; +using Unity.Collections; namespace net.rs64.TexTransTool.Decal { @@ -120,23 +121,19 @@ internal Dictionary CompileDecal(ITextureManager textur RenderTexture mulDecalTexture = GetMultipleDecalTexture(textureManager, DecalTexture, Color); Profiler.EndSample(); + var decalContext = new DecalContext, Vector3>(GetSpaceConverter(), GetTriangleFilter()); + decalContext.TargetPropertyName = TargetPropertyName; + decalContext.TextureWarp = TextureWrap.NotWrap; + decalContext.DecalPadding = Padding; + decalContext.HighQualityPadding = HighQualityPadding; + decalContext.UseDepthOrInvert = GetUseDepthOrInvert; + decalCompiledRenderTextures ??= new(); foreach (var renderer in TargetRenderers) { if (renderer == null) { continue; } Profiler.BeginSample("CreateDecalTexture"); - DecalUtility.CreateDecalTexture( - renderer, - decalCompiledRenderTextures, - mulDecalTexture, - GetSpaceConverter(), - GetTriangleFilter(), - TargetPropertyName, - TextureWrap.NotWrap, - Padding, - HighQualityPadding, - GetUseDepthOrInvert - ); + decalContext.WriteDecalTexture(decalCompiledRenderTextures, renderer, mulDecalTexture); Profiler.EndSample(); } RenderTexture.ReleaseTemporary(mulDecalTexture); @@ -144,24 +141,23 @@ internal Dictionary CompileDecal(ITextureManager textur } internal ParallelProjectionSpace GetSpaceConverter() { return new ParallelProjectionSpace(transform.worldToLocalMatrix); } - internal DecalUtility.ITrianglesFilter GetTriangleFilter() + internal ITrianglesFilter GetTriangleFilter() { if (IslandSelector != null) { return new IslandSelectToPPFilter(IslandSelector, GetFilter()); } return new ParallelProjectionFilter(GetFilter()); - } - internal List>> GetFilter() + internal JobChain>>[] GetFilter() { - var filters = new List>> + var filters = new List>>> { - new TriangleFilterUtility.FarStruct(1, true), - new TriangleFilterUtility.NearStruct(0, true) + TriangleFilterUtility.FarStruct.GetJobChain(1, true), + TriangleFilterUtility.NearStruct.GetJobChain(0, true) }; - if (SideCulling) filters.Add(new TriangleFilterUtility.SideStruct()); - filters.Add(new TriangleFilterUtility.OutOfPolygonStruct(PolygonCulling, 0, 1, true)); + if (SideCulling) filters.Add(TriangleFilterUtility.SideStruct.GetJobChain(false)); + filters.Add(TriangleFilterUtility.OutOfPolygonStruct.GetJobChain(PolygonCulling, 0, 1, true)); - return filters; + return filters.ToArray(); } internal void OnDrawGizmosSelected() { diff --git a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs index 87286649..dac868b1 100644 --- a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs @@ -22,7 +22,7 @@ public List FindRayCast(GameObject findRoot) var souseMesh = renderer.GetMesh(); if (souseMesh == null) { continue; } - var meshdata = renderer.Memo(DecalUtility.GetMeshData); + var meshdata = renderer.Memo(MeshData.GetMeshData); var ray = new Ray(transform.position, transform.forward); diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs new file mode 100644 index 00000000..c4348ff1 --- /dev/null +++ b/TexTransCore/Decal/DecalContext.cs @@ -0,0 +1,111 @@ +using System.Collections.ObjectModel; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using UnityEngine.Pool; +using UnityEngine.Profiling; + +namespace net.rs64.TexTransCore.Decal +{ + internal interface IConvertSpace : IDisposable + where UVDimension : struct + { + void Input(MeshData meshData);//この MeshData の解放責任は受け取らない + NativeArray OutPutUV(); + } + internal interface ITrianglesFilter : IDisposable + { + void SetSpace(SpaceConverter space); + NativeArray GetFilteredSubTriangle(int subMeshIndex); + } + internal class DecalContext + where ConvertSpace : IConvertSpace + where TrianglesFilter : ITrianglesFilter + where UVDimension : struct + { + ConvertSpace _convertSpace; + TrianglesFilter _trianglesFilter; + + + public string TargetPropertyName { get; set; } = "_MainTex"; + public TextureWrap? TextureWarp { get; set; } = null; + public float DecalPadding { get; set; } = 0.5f; + public bool HighQualityPadding { get; set; } = false; + public bool? UseDepthOrInvert { get; set; } = null; + + public DecalContext(ConvertSpace convertSpace, TrianglesFilter trianglesFilter) + { + _convertSpace = convertSpace; + _trianglesFilter = trianglesFilter; + } + + internal void WriteDecalTexture(Dictionary renderTextures, Renderer targetRenderer, Texture sourceTexture) + { + if (renderTextures == null) { throw new ArgumentNullException(nameof(renderTextures)); } + + Profiler.BeginSample("GetMeshData"); + var meshData = targetRenderer.Memo(MeshData.GetMeshData, i => i.Dispose()); + Profiler.EndSample(); + + Profiler.BeginSample("GetUVs"); + var tUV = meshData.VertexUV; + Profiler.EndSample(); + + Profiler.BeginSample("convertSpace.Input"); + _convertSpace.Input(meshData); + Profiler.EndSample(); + + _trianglesFilter.SetSpace(_convertSpace); + + + for (int i = 0; i < meshData.Triangles.Length; i++) + { + var targetMat = targetRenderer.sharedMaterials[i]; + + if (!targetMat.HasProperty(TargetPropertyName)) { continue; }; + var targetTexture = targetMat.GetTexture(TargetPropertyName); + if (targetTexture == null) { continue; } + + Profiler.BeginSample("GetFilteredSubTriangle"); + var filteredTriangle = _trianglesFilter.GetFilteredSubTriangle(i); + Profiler.EndSample(); + if (filteredTriangle.Length == 0) { continue; } + + if (!renderTextures.ContainsKey(targetMat)) { renderTextures[targetMat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); renderTextures[targetMat].Clear(); } + + var sUV = _convertSpace.OutPutUV(); + + Profiler.BeginSample("TransTexture.ForTrans"); + TransTexture.ForTrans( + renderTextures[targetMat], + sourceTexture, + new TransTexture.TransData(filteredTriangle, tUV, sUV), + DecalPadding, + TextureWarp, + HighQualityPadding, + UseDepthOrInvert + ); + Profiler.EndSample(); + } + _trianglesFilter.Dispose(); + _convertSpace.Dispose(); + } + + + + } + + public enum PolygonCulling + { + Vertex, + Edge, + EdgeAndCenterRay, + } +} diff --git a/TexTransCore/Decal/DecalUtility.cs.meta b/TexTransCore/Decal/DecalContext.cs.meta similarity index 100% rename from TexTransCore/Decal/DecalUtility.cs.meta rename to TexTransCore/Decal/DecalContext.cs.meta diff --git a/TexTransCore/Decal/DecalUtility.cs b/TexTransCore/Decal/DecalUtility.cs deleted file mode 100644 index c59e7a2f..00000000 --- a/TexTransCore/Decal/DecalUtility.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System.Collections.ObjectModel; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using Unity.Burst; -using Unity.Collections; -using Unity.Jobs; -using UnityEngine.Pool; -using UnityEngine.Profiling; - -namespace net.rs64.TexTransCore.Decal -{ - public static class DecalUtility - { - public interface IConvertSpace : IDisposable - where UVDimension : struct - { - void Input(MeshData meshData); - NativeArray OutPutUV(); - } - public interface ITrianglesFilter - { - void SetSpace(SpaceConverter space); - List GetFilteredSubTriangle(int subMeshIndex); - } - - internal static Dictionary CreateDecalTexture( - Renderer targetRenderer, - Dictionary renderTextures, - Texture sousTextures, - SpaceConverter convertSpace, - ITrianglesFilter filter, - string targetPropertyName = "_MainTex", - TextureWrap? textureWarp = null, - float defaultPadding = 0.5f, - bool highQualityPadding = false, - bool? useDepthOrInvert = null - ) - where SpaceConverter : IConvertSpace - where UVDimension : struct - { - if (renderTextures == null) renderTextures = new(); - - Profiler.BeginSample("GetMeshData"); - var meshData = targetRenderer.Memo(GetMeshData, i => i.Dispose()); - Profiler.EndSample(); - - Profiler.BeginSample("GetUVs"); - var tUV = meshData.VertexUV; - Profiler.EndSample(); - - Profiler.BeginSample("convertSpace.Input"); - convertSpace.Input(meshData); - Profiler.EndSample(); - - filter.SetSpace(convertSpace); - - var materials = targetRenderer.sharedMaterials; - - for (int i = 0; i < meshData.Triangles.Length; i++) - { - var targetMat = materials[i]; - - if (!targetMat.HasProperty(targetPropertyName)) { continue; }; - var targetTexture = targetMat.GetTexture(targetPropertyName); - if (targetTexture == null) { continue; } - - Profiler.BeginSample("GetFilteredSubTriangle"); - var filteredTriangle = filter.GetFilteredSubTriangle(i); - Profiler.EndSample(); - if (filteredTriangle.Any() == false) { continue; } - - if (!renderTextures.ContainsKey(targetMat)) - { - renderTextures[targetMat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); - renderTextures[targetMat].Clear(); - } - var sUV = convertSpace.OutPutUV(); - - var nativeFilteredTriangle = new NativeArray(filteredTriangle.Count, Allocator.TempJob); - for (int t = 0; t < filteredTriangle.Count; t++) - { - nativeFilteredTriangle[t] = filteredTriangle[t]; - } - - Profiler.BeginSample("TransTexture.ForTrans"); - TransTexture.ForTrans( - renderTextures[targetMat], - sousTextures, - new TransTexture.TransData(nativeFilteredTriangle, tUV, sUV), - defaultPadding, - textureWarp, - highQualityPadding, - useDepthOrInvert - ); - Profiler.EndSample(); - nativeFilteredTriangle.Dispose(); - } - convertSpace.Dispose();//convertSpaceの解放責任はこっちにある - - return renderTextures; - } - public static MeshData GetMeshData(Renderer renderer) => new MeshData(renderer); - public static List> GetPooledSubTriangle(this Mesh mesh) - { - var result = ListPool>.Get(); - for (var i = 0; mesh.subMeshCount > i; i += 1) - { - var subTri = ListPool.Get(); - result.Add(mesh.GetSubTriangleIndex(i, subTri)); - } - return result; - } - internal static void ReleasePooledSubTriangle(List> subTriList) - { - foreach (var subTri in subTriList) - { - ListPool.Release(subTri); - } - ListPool>.Release(subTriList); - } - - internal static NativeArray ConvertVerticesInMatrix(Matrix4x4 matrix, MeshData meshData, Vector3 offset, out JobHandle jobHandle) - { - var array = new NativeArray(meshData.Vertices.Length, Allocator.TempJob); - - jobHandle = new ConvertVerticesJob() - { - InputVertices = meshData.Vertices, - OutputVertices = array, - Matrix = matrix, - Offset = offset - }.Schedule(meshData.Vertices.Length, 64); - - meshData.AddJobDependency(jobHandle); - - return array; - } - - [BurstCompile] - private struct ConvertVerticesJob : IJobParallelFor - { - [ReadOnly] public NativeArray InputVertices; - [WriteOnly] public NativeArray OutputVertices; - public Matrix4x4 Matrix; - public Vector3 Offset; - - public void Execute(int index) - { - OutputVertices[index] = Matrix.MultiplyPoint3x4(InputVertices[index]) + Offset; - } - } - - internal static void ConvertVerticesInMatrix(Matrix4x4 matrix, List vertices, Vector3 Offset) - { - for (int i = 0; i < vertices.Count; i++) - { - vertices[i] = matrix.MultiplyPoint3x4(vertices[i]) + Offset; - } - } - internal static Vector2 QuadNormalize(IReadOnlyList quad, Vector2 targetPos) - { - var oneNearPoint = VectorUtility.NearPoint(quad[0], quad[2], targetPos); - var oneCross = Vector3.Cross(quad[2] - quad[0], targetPos - quad[0]).z > 0 ? -1 : 1; - - var twoNearPoint = VectorUtility.NearPoint(quad[0], quad[1], targetPos); - var twoCross = Vector3.Cross(quad[1] - quad[0], targetPos - quad[0]).z > 0 ? 1 : -1; - - var threeNearPoint = VectorUtility.NearPoint(quad[1], quad[3], targetPos); - var threeCross = Vector3.Cross(quad[3] - quad[1], targetPos - quad[1]).z > 0 ? 1 : -1; - - var forNearPoint = VectorUtility.NearPoint(quad[2], quad[3], targetPos); - var forCross = Vector3.Cross(quad[3] - quad[2], targetPos - quad[2]).z > 0 ? -1 : 1; - - var oneDistance = Vector2.Distance(oneNearPoint, targetPos) * oneCross; - var towDistance = Vector2.Distance(twoNearPoint, targetPos) * twoCross; - var threeDistance = Vector2.Distance(threeNearPoint, targetPos) * threeCross; - var forDistance = Vector2.Distance(forNearPoint, targetPos) * forCross; - - var x = oneDistance / (oneDistance + threeDistance); - var y = towDistance / (towDistance + forDistance); - - return new Vector2(x, y); - } - internal static List QuadNormalize(IReadOnlyList quad, List targetPoss, List outPut = null) - { - outPut?.Clear(); outPut ??= new List(targetPoss.Count); - foreach (var targetPos in targetPoss) - { - outPut.Add(QuadNormalize(quad, targetPos)); - } - return outPut; - } - } - - public enum PolygonCulling - { - Vertex, - Edge, - EdgeAndCenterRay, - } -} diff --git a/TexTransCore/Decal/MeshData.cs b/TexTransCore/Decal/MeshData.cs index ad2e797b..bea9c600 100644 --- a/TexTransCore/Decal/MeshData.cs +++ b/TexTransCore/Decal/MeshData.cs @@ -226,6 +226,7 @@ internal static Matrix4x4 GetMatrix(Renderer target) } } } + public static MeshData GetMeshData(Renderer renderer) => new MeshData(renderer); [BurstCompile] struct PackVerticesJob : IJobParallelFor { diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs index 723af1e3..8e18833a 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs @@ -2,22 +2,70 @@ using System.Collections.Generic; using net.rs64.TexTransCore.TransTextureCore; using net.rs64.TexTransTool.Utils; +using Unity.Collections; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using UnityEngine.Profiling; +using Unity.Jobs; namespace net.rs64.TexTransCore.Decal { - internal class ParallelProjectionFilter : DecalUtility.ITrianglesFilter + internal class ParallelProjectionFilter : ITrianglesFilter { - public List>> Filters; + public JobChain>>[] Filters; ParallelProjectionSpace _parallelProjectionSpace; - public void SetSpace(ParallelProjectionSpace space) { _parallelProjectionSpace = space; } + private JobResult>[] _filteredBit; + private NativeArray[] _filteredTriangles; - public ParallelProjectionFilter(List>> filters) { Filters = filters; } - public List GetFilteredSubTriangle(int subMeshIndex) + public void SetSpace(ParallelProjectionSpace space) { - if (_parallelProjectionSpace is null) { return null; } - return TriangleFilterUtility.FilteringTriangle(_parallelProjectionSpace.MeshData.TrianglesSubMeshList[subMeshIndex], _parallelProjectionSpace.OutPutUV().AsList(), Filters); + _parallelProjectionSpace = space; + + var smCount = _parallelProjectionSpace.MeshData.TriangleIndex.Length; + _filteredBit = new JobResult>[smCount]; + _filteredTriangles = new NativeArray[smCount]; + for (var i = 0; smCount > i; i += 1) + { + var triNa = _parallelProjectionSpace.MeshData.TriangleIndex[i]; + var ppsVert = _parallelProjectionSpace.GetPPSVert; + _filteredBit[i] = TriangleFilterUtility.FilteringTriangle(triNa, ppsVert, Filters); + } } + public ParallelProjectionFilter(JobChain>>[] filters) { Filters = filters; } + NativeArray ITrianglesFilter.GetFilteredSubTriangle(int subMeshIndex) + { + if (_parallelProjectionSpace is null) { return default; } + var filteredTriangle = _filteredTriangles[subMeshIndex] = FilteringExecute(_parallelProjectionSpace.MeshData.TriangleIndex[subMeshIndex], _filteredBit[subMeshIndex].GetResult); + return filteredTriangle; + } + internal static NativeArray FilteringExecute(NativeArray triangles, NativeArray FilterBit) + { + Profiler.BeginSample("ParallelProjectionFilter.FilteringExecute"); + var filteredTriFullArray = new NativeArray(FilterBit.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory); + + var writePos = 0; + for (var i = 0; FilterBit.Length > i; i += 1) + { + if (!FilterBit[i]) + { + filteredTriFullArray[writePos] = triangles[i]; + writePos += 1; + } + } + + var filtered = new NativeArray(writePos, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + net.rs64.TexTransCore.Unsafe.UnsafeNativeArrayUtility.MemCpy(filteredTriFullArray, filtered, writePos); + filteredTriFullArray.Dispose(); + + Profiler.EndSample(); + return filtered; + } + public void Dispose() + { + foreach (var na in _filteredBit) { na.GetResult.Dispose(); } + foreach (var na in _filteredTriangles) { na.Dispose(); } + } } } diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs index 0a98de38..e5e855c2 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs @@ -3,10 +3,11 @@ using System.Collections.Generic; using Unity.Collections; using Unity.Jobs; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransCore.Decal { - public class ParallelProjectionSpace : DecalUtility.IConvertSpace + public class ParallelProjectionSpace : IConvertSpace { internal Matrix4x4 ParallelProjectionMatrix; @@ -23,7 +24,7 @@ internal ParallelProjectionSpace(Matrix4x4 parallelProjectionMatrix) public void Input(MeshData meshData) { MeshData = meshData; - PPSVert = DecalUtility.ConvertVerticesInMatrix(ParallelProjectionMatrix, meshData, new Vector3(0.5f, 0.5f, 0), out _jobHandle); + PPSVert = VectorUtility.ConvertVerticesInMatrix(ParallelProjectionMatrix, meshData, new Vector3(0.5f, 0.5f, 0), out _jobHandle); } public NativeArray OutPutUV() => GetPPSVert; diff --git a/TexTransCore/Decal/TriangleFilterUtility.cs b/TexTransCore/Decal/TriangleFilterUtility.cs index 14c9ded6..ff2c0a44 100644 --- a/TexTransCore/Decal/TriangleFilterUtility.cs +++ b/TexTransCore/Decal/TriangleFilterUtility.cs @@ -1,165 +1,212 @@ using System; -using System.Buffers; +using System.Collections; using System.Collections.Generic; -using System.Linq; using net.rs64.TexTransCore.TransTextureCore; using net.rs64.TexTransCore.TransTextureCore.Utils; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; using UnityEngine; -using UnityEngine.Pool; +using UnityEngine.Profiling; namespace net.rs64.TexTransCore.Decal { - internal static class TriangleFilterUtility + internal struct FilterTriangleJobInput { - public interface ITriangleFiltering + public NativeArray Triangle; + public NativeArray FilteredBit; + public InterSpace InternalSpace; + + public FilterTriangleJobInput(NativeArray item1, NativeArray item2, InterSpace item3) { - bool Filtering(TriangleIndex targetTri, InterObject vertex);//対象の三角形を通せない場合True + Triangle = item1; + FilteredBit = item2; + InternalSpace = item3; } - public static List FilteringTriangle(List target, InterSpace interObjects, IReadOnlyList filters, List outPut = null) - where Filter : ITriangleFiltering - { - var targetCount = target.Count; - var filtered = ArrayPool.Shared.Rent(targetCount); - for (var i = 0; targetCount > i; i += 1) { filtered[i] = false; } + } - foreach (var filter in filters) - { - for (int i = 0; targetCount > i; i++) - { - if (filtered[i] == false) - { - var Triangle = target[i]; - filtered[i] = filter.Filtering(Triangle, interObjects); - } - } - } + public delegate JobHandle JobChain(Input input, JobHandle jobHandle); + internal static class TriangleFilterUtility + { + public static JobResult> FilteringTriangle(NativeArray target, InterSpace interObjects, JobChain>[] filtersJobs) + { + Profiler.BeginSample("FilteringTriangle"); + var filteredBit = new NativeArray(target.Length, Allocator.TempJob); + var input = new FilterTriangleJobInput(target, filteredBit, interObjects); - outPut?.Clear(); outPut ??= new (target.Count); - for (int i = 0; i < target.Count; i++) + var jobHandle = default(JobHandle); + for (var i = 0; filtersJobs.Length > i; i += 1) { - if (filtered[i] == false) - { - outPut.Add(target[i]); - } + var filterJob = filtersJobs[i]; + jobHandle = filtersJobs[i].Invoke(input, jobHandle); } - ArrayPool.Shared.Return(filtered); - return outPut; + Profiler.EndSample(); + return new JobResult>(filteredBit, jobHandle); } - public struct SideStruct : ITriangleFiltering> + [BurstCompile] + public struct SideStruct : IJobParallelFor { - public bool IsReverse; - - public SideStruct(bool isReverse) + [ReadOnly] public bool IsReverse; + [ReadOnly] public NativeArray Triangle; + [ReadOnly] public NativeArray WorldVerticals; + public NativeArray FilteringBit; + public void Execute(int index) { - IsReverse = isReverse; - } + if (FilteringBit[index]) { return; } - public bool Filtering(TriangleIndex targetTri, IList vertex) - { - return SideCheck(targetTri, vertex, IsReverse); + var tri = Triangle[index]; + var ba = WorldVerticals[tri[1]] - WorldVerticals[tri[0]]; + var ac = WorldVerticals[tri[0]] - WorldVerticals[tri[2]]; + var TriangleSide = Vector3.Cross(ba, ac).z; + if (!IsReverse) { FilteringBit[index] = TriangleSide < 0; } + else { FilteringBit[index] = TriangleSide > 0; } } - public static bool SideCheck(TriangleIndex targetTri, IList vertex, bool isReverse = false) + internal static JobChain>> GetJobChain(bool isReverse) { - var ba = vertex[targetTri[1]] - vertex[targetTri[0]]; - var ac = vertex[targetTri[0]] - vertex[targetTri[2]]; - var TriangleSide = Vector3.Cross(ba, ac).z; - if (!isReverse) return TriangleSide < 0; - else return TriangleSide > 0; + return (input, jobHandle) => + { + var job = new SideStruct() + { + IsReverse = isReverse, + Triangle = input.Triangle, + FilteringBit = input.FilteredBit, + WorldVerticals = input.InternalSpace + }; + return job.Schedule(input.FilteredBit.Length, 32, jobHandle); + }; } - - } - - public struct FarStruct : ITriangleFiltering> + [BurstCompile] + public struct FarStruct : IJobParallelFor { - public float Far; - public bool IsAllVertex; + [ReadOnly] public float Far; + [ReadOnly] public bool IsAllVertex; - public FarStruct(float far, bool isAllVertex) - { - Far = far; - IsAllVertex = isAllVertex; - } + [ReadOnly] public NativeArray Triangle; + [ReadOnly] public NativeArray WorldVerticals; + public NativeArray FilteringBit; - public bool Filtering(TriangleIndex targetTri, IList vertex) + public void Execute(int index) { - return FarClip(targetTri, vertex, Far, IsAllVertex); + if (FilteringBit[index]) { return; } + var targetTri = Triangle[index]; + + bool result; + if (IsAllVertex) { result = WorldVerticals[targetTri[0]].z > Far && WorldVerticals[targetTri[1]].z > Far && WorldVerticals[targetTri[2]].z > Far; } + else { result = WorldVerticals[targetTri[0]].z > Far || WorldVerticals[targetTri[1]].z > Far || WorldVerticals[targetTri[2]].z > Far; } + + FilteringBit[index] = result; } - public static bool FarClip(TriangleIndex targetTri, IList vertex, float far, bool isAllVertex)//IsAllVertexは排除されるのにすべてが条件に外れてる場合と一つでも条件に外れてる場合の選択 + internal static JobChain>> GetJobChain(float far, bool isAllVertex) { - if (isAllVertex) - { - return vertex[targetTri[0]].z > far && vertex[targetTri[1]].z > far && vertex[targetTri[2]].z > far; - } - else + return (input, jobHandle) => { - return vertex[targetTri[0]].z > far || vertex[targetTri[1]].z > far || vertex[targetTri[2]].z > far; - } + var job = new FarStruct() + { + Far = far, + IsAllVertex = isAllVertex, + Triangle = input.Triangle, + FilteringBit = input.FilteredBit, + WorldVerticals = input.InternalSpace + }; + return job.Schedule(input.FilteredBit.Length, 32, jobHandle); + }; } } - - public struct NearStruct : TriangleFilterUtility.ITriangleFiltering> + [BurstCompile] + public struct NearStruct : IJobParallelFor { - public float Near; - public bool IsAllVertex; + [ReadOnly] public float Near; + [ReadOnly] public bool IsAllVertex; - public NearStruct(float near, bool isAllVertex) - { - Near = near; - IsAllVertex = isAllVertex; - } + [ReadOnly] public NativeArray Triangle; + [ReadOnly] public NativeArray WorldVerticals; + public NativeArray FilteringBit; - public bool Filtering(TriangleIndex targetTri, IList vertex) + public void Execute(int index) { - return NearClip(targetTri, vertex, Near, IsAllVertex); + if (FilteringBit[index]) { return; } + var targetTri = Triangle[index]; + + bool result; + if (IsAllVertex) { result = WorldVerticals[targetTri[0]].z < Near && WorldVerticals[targetTri[1]].z < Near && WorldVerticals[targetTri[2]].z < Near; } + else { result = WorldVerticals[targetTri[0]].z < Near || WorldVerticals[targetTri[1]].z < Near || WorldVerticals[targetTri[2]].z < Near; } + + FilteringBit[index] = result; } - public static bool NearClip(TriangleIndex targetTri, IList vertex, float near, bool isAllVertex) + internal static JobChain>> GetJobChain(float near, bool isAllVertex) { - if (isAllVertex) - { - return vertex[targetTri[0]].z < near && vertex[targetTri[1]].z < near && vertex[targetTri[2]].z < near; - } - else + return (input, jobHandle) => { - return vertex[targetTri[0]].z < near || vertex[targetTri[1]].z < near || vertex[targetTri[2]].z < near; - } + var job = new NearStruct() + { + Near = near, + IsAllVertex = isAllVertex, + Triangle = input.Triangle, + FilteringBit = input.FilteredBit, + WorldVerticals = input.InternalSpace + }; + return job.Schedule(input.FilteredBit.Length, 32, jobHandle); + }; } } - - public struct OutOfPolygonStruct : ITriangleFiltering> + [BurstCompile] + public struct OutOfPolygonStruct : IJobParallelFor { public PolygonCulling PolygonCulling; public float MinRange; public float MaxRange; public bool IsAllVertex; - public OutOfPolygonStruct(PolygonCulling polygonCulling, float minRange, float maxRange, bool isAllVertex) - { - PolygonCulling = polygonCulling; - MinRange = minRange; - MaxRange = maxRange; - IsAllVertex = isAllVertex; - } + [ReadOnly] public NativeArray Triangle; + [ReadOnly] public NativeArray WorldVerticals; + public NativeArray FilteringBit; - public bool Filtering(TriangleIndex targetTri, IList vertex) + public void Execute(int index) { + if (FilteringBit[index]) { return; } + var targetTri = Triangle[index]; + + bool result; switch (PolygonCulling) { default: case PolygonCulling.Vertex: - return OutOfPolygonVertexBase(targetTri, vertex, MaxRange, MinRange, IsAllVertex); + result = OutOfPolygonVertexBase(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); + break; case PolygonCulling.Edge: - return OutOfPolygonEdgeBase(targetTri, vertex, MaxRange, MinRange, IsAllVertex); + result = OutOfPolygonEdgeBase(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); + break; + case PolygonCulling.EdgeAndCenterRay: - return OutOfPolygonEdgeEdgeAndCenterRayCast(targetTri, vertex, MaxRange, MinRange, IsAllVertex); + result = OutOfPolygonEdgeEdgeAndCenterRayCast(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); + break; } + FilteringBit[index] = result; } - public static bool OutOfPolygonVertexBase(TriangleIndex targetTri, IList vertex, float maxRange, float minRange, bool isAllVertex) + internal static JobChain>> GetJobChain(PolygonCulling polygonCulling, float minRange, float maxRange, bool isAllVertex) + { + return (input, jobHandle) => + { + var job = new OutOfPolygonStruct() + { + PolygonCulling = polygonCulling, + MinRange = minRange, + MaxRange = maxRange, + IsAllVertex = isAllVertex, + Triangle = input.Triangle, + FilteringBit = input.FilteredBit, + WorldVerticals = input.InternalSpace + }; + return job.Schedule(input.FilteredBit.Length, 32, jobHandle); + }; + } + public static bool OutOfPolygonVertexBase(TriangleIndex targetTri, NativeArray vertex, float maxRange, float minRange, bool isAllVertex) { Span outOfPolygon = stackalloc bool[3] { false, false, false }; for (var index = 0; 3 > index; index += 1) @@ -170,7 +217,7 @@ public static bool OutOfPolygonVertexBase(TriangleIndex targetTri, IList Vertex, float maxRange, float minRange, bool isAllVertex) + public static bool OutOfPolygonEdgeBase(TriangleIndex targetTri, NativeArray Vertex, float maxRange, float minRange, bool isAllVertex) { float centerPos = Mathf.Lerp(maxRange, minRange, 0.5f); var centerPosVec2 = new Vector2(centerPos, centerPos); @@ -187,7 +234,7 @@ public static bool OutOfPolygonEdgeBase(TriangleIndex targetTri, IList if (isAllVertex) return outOfPolygon[0] && outOfPolygon[1] && outOfPolygon[2]; else return outOfPolygon[0] || outOfPolygon[1] || outOfPolygon[2]; } - public static bool OutOfPolygonEdgeEdgeAndCenterRayCast(TriangleIndex targetTri, IList vertex, float maxRange, float minRange, bool isAllVertex) + public static bool OutOfPolygonEdgeEdgeAndCenterRayCast(TriangleIndex targetTri, NativeArray vertex, float maxRange, float minRange, bool isAllVertex) { float centerPos = Mathf.Lerp(maxRange, minRange, 0.5f); var centerPosVec2 = new Vector2(centerPos, centerPos); @@ -197,15 +244,16 @@ public static bool OutOfPolygonEdgeEdgeAndCenterRayCast(TriangleIndex targetTri, } else { - var tri = ListPool.Get(); - tri.Add(vertex[targetTri[0]]); tri.Add(vertex[targetTri[1]]); tri.Add(vertex[targetTri[2]]); + Span tri = stackalloc Vector2[3]; + tri[0] = vertex[targetTri[0]]; tri[1] = vertex[targetTri[1]]; tri[2] = vertex[targetTri[2]]; var crossT = VectorUtility.CrossTriangle(tri, centerPosVec2); - ListPool.Release(tri); return VectorUtility.IsInCal(crossT.x, crossT.y, crossT.z); } } + } } + } diff --git a/TexTransCore/TransTextureCore/Utils/RendererUtility.cs b/TexTransCore/TransTextureCore/Utils/RendererUtility.cs index b98a1819..5b8eab21 100644 --- a/TexTransCore/TransTextureCore/Utils/RendererUtility.cs +++ b/TexTransCore/TransTextureCore/Utils/RendererUtility.cs @@ -53,4 +53,4 @@ public static Mesh GetMesh(this Renderer target) return mesh; } } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/Utils/VectorUtility.cs b/TexTransCore/TransTextureCore/Utils/VectorUtility.cs index 8c79c284..766a8bf8 100644 --- a/TexTransCore/TransTextureCore/Utils/VectorUtility.cs +++ b/TexTransCore/TransTextureCore/Utils/VectorUtility.cs @@ -1,5 +1,10 @@ +using System; using System.Collections.Generic; +using net.rs64.TexTransCore.Decal; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; using UnityEngine; namespace net.rs64.TexTransCore.TransTextureCore.Utils @@ -7,15 +12,15 @@ namespace net.rs64.TexTransCore.TransTextureCore.Utils internal static class VectorUtility { - public static Vector4 CrossTriangle(List triangle, Vector2 targetPoint) + public static Vector4 CrossTriangle(Span triangle, Vector2 targetPoint) { var w = Vector3.Cross(triangle[2] - triangle[1], targetPoint - triangle[1]).z; var u = Vector3.Cross(triangle[0] - triangle[2], targetPoint - triangle[2]).z; var v = Vector3.Cross(triangle[1] - triangle[0], targetPoint - triangle[0]).z; var wuv = TriangleArea(triangle); - return new (w, u, v, wuv); + return new(w, u, v, wuv); } - public static float TriangleArea(List triangle) + public static float TriangleArea(Span triangle) { return Vector3.Cross(triangle[1] - triangle[0], triangle[2] - triangle[0]).z; } @@ -26,7 +31,7 @@ public static Vector3 ToBarycentricCoordinateSystem(Vector4 crossT) var b = crossT.y / crossT.w; var c = crossT.z / crossT.w; - return new (a, b, c); + return new(a, b, c); } public static Vector2 FromBarycentricCoordinateSystem(List triangle, Vector3 sourceTBC) @@ -64,7 +69,7 @@ public static Vector3 DistanceVertBase(List triangle, Vector2 targetPoi var w = Vector2.Distance(triangle[0], targetPoint); var u = Vector2.Distance(triangle[1], targetPoint); var v = Vector2.Distance(triangle[2], targetPoint); - return new (w, u, v); + return new(w, u, v); } public static Vector2 NearPointOnLine(Vector2 a, Vector2 b, Vector2 p) @@ -88,7 +93,7 @@ public static Vector3 DistanceEdgeBase(List triangle, Vector2 targetPoi float distanceA = Vector2.Distance(NearPointOnLine(triangle[0], triangle[1], targetPoint), targetPoint); float distanceB = Vector2.Distance(NearPointOnLine(triangle[1], triangle[2], targetPoint), targetPoint); float distanceC = Vector2.Distance(NearPointOnLine(triangle[2], triangle[0], targetPoint), targetPoint); - return new (distanceA, distanceB, distanceC); + return new(distanceA, distanceB, distanceC); } public static float MinVector(Vector3 vector) @@ -97,8 +102,8 @@ public static float MinVector(Vector3 vector) } public static (Vector2 min, Vector2 max) BoxCal(List triangles) { - Vector2 min = new (); - Vector2 max = new (); + Vector2 min = new(); + Vector2 max = new(); bool first = true; foreach (var tri in triangles) { @@ -123,5 +128,79 @@ public static bool InRange(float min, float max, float target) { return (min <= target && target <= max); } + + internal static void ConvertVerticesInMatrix(Matrix4x4 matrix, List vertices, Vector3 Offset) + { + for (int i = 0; i < vertices.Count; i++) + { + vertices[i] = matrix.MultiplyPoint3x4(vertices[i]) + Offset; + } + } + internal static Vector2 QuadNormalize(IReadOnlyList quad, Vector2 targetPos) + { + var oneNearPoint = VectorUtility.NearPoint(quad[0], quad[2], targetPos); + var oneCross = Vector3.Cross(quad[2] - quad[0], targetPos - quad[0]).z > 0 ? -1 : 1; + + var twoNearPoint = VectorUtility.NearPoint(quad[0], quad[1], targetPos); + var twoCross = Vector3.Cross(quad[1] - quad[0], targetPos - quad[0]).z > 0 ? 1 : -1; + + var threeNearPoint = VectorUtility.NearPoint(quad[1], quad[3], targetPos); + var threeCross = Vector3.Cross(quad[3] - quad[1], targetPos - quad[1]).z > 0 ? 1 : -1; + + var forNearPoint = VectorUtility.NearPoint(quad[2], quad[3], targetPos); + var forCross = Vector3.Cross(quad[3] - quad[2], targetPos - quad[2]).z > 0 ? -1 : 1; + + var oneDistance = Vector2.Distance(oneNearPoint, targetPos) * oneCross; + var towDistance = Vector2.Distance(twoNearPoint, targetPos) * twoCross; + var threeDistance = Vector2.Distance(threeNearPoint, targetPos) * threeCross; + var forDistance = Vector2.Distance(forNearPoint, targetPos) * forCross; + + var x = oneDistance / (oneDistance + threeDistance); + var y = towDistance / (towDistance + forDistance); + + return new Vector2(x, y); + } + internal static List QuadNormalize(IReadOnlyList quad, List targetPoss, List outPut = null) + { + outPut?.Clear(); outPut ??= new List(targetPoss.Count); + foreach (var targetPos in targetPoss) + { + outPut.Add(QuadNormalize(quad, targetPos)); + } + return outPut; + } + + internal static NativeArray ConvertVerticesInMatrix(Matrix4x4 matrix, MeshData meshData, Vector3 offset, out JobHandle jobHandle) + { + var array = new NativeArray(meshData.Vertices.Length, Allocator.TempJob); + + jobHandle = new ConvertVerticesJob() + { + InputVertices = meshData.Vertices, + OutputVertices = array, + Matrix = matrix, + Offset = offset + }.Schedule(meshData.Vertices.Length, 64); + + meshData.AddJobDependency(jobHandle); + + return array; + } + + [BurstCompile] + private struct ConvertVerticesJob : IJobParallelFor + { + [ReadOnly] public NativeArray InputVertices; + [WriteOnly] public NativeArray OutputVertices; + public Matrix4x4 Matrix; + public Vector3 Offset; + + public void Execute(int index) + { + OutputVertices[index] = Matrix.MultiplyPoint3x4(InputVertices[index]) + Offset; + } + } + + } -} \ No newline at end of file +} diff --git a/TexTransCore/Unsafe/InternalsVisible.cs b/TexTransCore/Unsafe/InternalsVisible.cs index 11018201..4654fe6f 100644 --- a/TexTransCore/Unsafe/InternalsVisible.cs +++ b/TexTransCore/Unsafe/InternalsVisible.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; +[assembly: InternalsVisibleTo("net.rs64.tex-trans-core")] [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.editor")] [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.runtime")] [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.inspector")] @@ -10,4 +11,4 @@ [assembly: InternalsVisibleTo("net.rs64.multi-layer-image-parser")] [assembly: InternalsVisibleTo("net.rs64.ttt-clip-importer.editor")] -[assembly: InternalsVisibleTo("net.rs64.ttt-destructive-texture-utilities.editor")] \ No newline at end of file +[assembly: InternalsVisibleTo("net.rs64.ttt-destructive-texture-utilities.editor")] diff --git a/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs b/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs index cdabb8cc..99af348a 100644 --- a/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs +++ b/TexTransCore/Unsafe/UnsafeNativeArrayUtility.cs @@ -18,6 +18,13 @@ public static unsafe void ClearMemoryOnColor(NativeArray array, byte va UnsafeUtility.MemSet(array.GetUnsafePtr(), val, (long)array.Length * UnsafeUtility.SizeOf()); } + public static unsafe void MemCpy(NativeArray s, NativeArray d, int count) + where T : struct + { + if (Mathf.Min(s.Length, d.Length) > count) { throw new System.ArgumentOutOfRangeException(); } + UnsafeUtility.MemCpy(d.GetUnsafePtr(), s.GetUnsafePtr(), (long)count * UnsafeUtility.SizeOf()); + } + } From d45fa47b4e28a5de31b5c80ed0177aa161acc600 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 27 Apr 2024 20:14:47 +0900 Subject: [PATCH 120/208] fix: Dispose order --- Runtime/Decal/IslandSelectToPPFilter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index 505a6766..bafbcd55 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -99,13 +99,13 @@ private static NativeArray IslandSelectToTriangleIndex(Island[] i static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) { - return IslandUtility.UVtoIsland(pair.meshData.TriangleIndex[pair.subMeshIndex].AsList(), pair.meshData.UVList).ToArray(); + return IslandUtility.UVtoIsland(pair.meshData.TriangleIndex[pair.subMeshIndex].AsList(), pair.meshData.VertexUV.AsList()).ToArray(); } public void Dispose() { - foreach (var na in _islandSelectedTriangles) { na.Dispose(); } foreach (var na in _filteredBit) { na.GetResult.Dispose(); } + foreach (var na in _islandSelectedTriangles) { na.Dispose(); } foreach (var na in _filteredTriangles) { na.Dispose(); } } } From cd4ed3084ada91493d0d9dc44417c3f34f5e8123 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 27 Apr 2024 20:37:27 +0900 Subject: [PATCH 121/208] fix: a not used islandSelectedTriangles --- Runtime/Decal/IslandSelectToPPFilter.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index bafbcd55..c38909ad 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -45,6 +45,7 @@ public void SetSpace(ParallelProjectionSpace space) for (var i = 0; smCount > i; i += 1) { var islandSelected = _islandSelectedTriangles[i] = IslandSelectExecute(i); + if (islandSelected.Length == 0) { continue; } var ppsVert = _ppSpace.GetPPSVert; _filteredBit[i] = TriangleFilterUtility.FilteringTriangle(islandSelected, ppsVert, Filters); } @@ -52,7 +53,8 @@ public void SetSpace(ParallelProjectionSpace space) NativeArray ITrianglesFilter.GetFilteredSubTriangle(int subMeshIndex) { if (_ppSpace is null) { return default; } - var filteredTriangle = _filteredTriangles[subMeshIndex] = ParallelProjectionFilter.FilteringExecute(_ppSpace.MeshData.TriangleIndex[subMeshIndex], _filteredBit[subMeshIndex].GetResult); + if (_islandSelectedTriangles[subMeshIndex].Length == 0) { return default; } + var filteredTriangle = _filteredTriangles[subMeshIndex] = ParallelProjectionFilter.FilteringExecute(_islandSelectedTriangles[subMeshIndex], _filteredBit[subMeshIndex].GetResult); return filteredTriangle; } @@ -82,6 +84,7 @@ private static NativeArray IslandSelectToTriangleIndex(Island[] i { var triCount = 0; for (var i = 0; islands.Length > i; i += 1) { if (bitArray[i]) { triCount += islands[i].triangles.Count; } } + if (triCount == 0) { return default; } var list = new NativeArray(triCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var writePos = 0; @@ -104,7 +107,7 @@ static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) public void Dispose() { - foreach (var na in _filteredBit) { na.GetResult.Dispose(); } + foreach (var na in _filteredBit) { na?.GetResult.Dispose(); } foreach (var na in _islandSelectedTriangles) { na.Dispose(); } foreach (var na in _filteredTriangles) { na.Dispose(); } } From 336c08ef468843dd9449a943a91ce173751b59b4 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 12:29:18 +0900 Subject: [PATCH 122/208] remove: EdgeBase and EdgeAndCenterRayCastBase Culling --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 2 +- Runtime/Decal/SimpleDecal.cs | 5 +- TexTransCore/Decal/TriangleFilterUtility.cs | 54 +-------------------- 3 files changed, 6 insertions(+), 55 deletions(-) diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 71f1c106..4093bf9a 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -32,7 +32,7 @@ public override void OnInspectorGUI() EditorGUILayout.LabelField("SimpleDecal:label:CullingSettings".Glc(), EditorStyles.boldLabel); EditorGUI.indentLevel += 1; - var sPolygonCulling = thisSObject.FindProperty("PolygonCulling"); + var sPolygonCulling = thisSObject.FindProperty("PolygonOutOfCulling"); EditorGUILayout.PropertyField(sPolygonCulling, "SimpleDecal:prop:PolygonCulling".Glc()); var sSideCulling = thisSObject.FindProperty("SideCulling"); diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index f9f95377..9515ee7b 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -30,7 +30,7 @@ public sealed class SimpleDecal : TexTransRuntimeBehavior//AbstractSingleDecal

UseDepth ? new bool?(DepthInvert) : null; #region V3SaveData + [Obsolete("V3SaveData", true)][FormerlySerializedAs("PolygonCaling")][SerializeField] internal PolygonCulling PolygonCulling = PolygonCulling.Vertex; [Obsolete("V3SaveData", true)][SerializeField] internal bool IslandCulling = false; [Obsolete("V3SaveData", true)][SerializeField] internal Vector2 IslandSelectorPos = new Vector2(0.5f, 0.5f); [Obsolete("V3SaveData", true)][SerializeField] internal float IslandSelectorRange = 1; @@ -155,7 +156,7 @@ internal JobChain>>[] GetFilter() TriangleFilterUtility.NearStruct.GetJobChain(0, true) }; if (SideCulling) filters.Add(TriangleFilterUtility.SideStruct.GetJobChain(false)); - filters.Add(TriangleFilterUtility.OutOfPolygonStruct.GetJobChain(PolygonCulling, 0, 1, true)); + if (PolygonOutOfCulling) filters.Add(TriangleFilterUtility.OutOfPolygonStruct.GetJobChain(0, 1, true)); return filters.ToArray(); } diff --git a/TexTransCore/Decal/TriangleFilterUtility.cs b/TexTransCore/Decal/TriangleFilterUtility.cs index ff2c0a44..b59b4dae 100644 --- a/TexTransCore/Decal/TriangleFilterUtility.cs +++ b/TexTransCore/Decal/TriangleFilterUtility.cs @@ -156,7 +156,6 @@ internal static JobChain>> GetJobCha [BurstCompile] public struct OutOfPolygonStruct : IJobParallelFor { - public PolygonCulling PolygonCulling; public float MinRange; public float MaxRange; public bool IsAllVertex; @@ -170,32 +169,16 @@ public void Execute(int index) if (FilteringBit[index]) { return; } var targetTri = Triangle[index]; - bool result; - switch (PolygonCulling) - { - default: - case PolygonCulling.Vertex: - result = OutOfPolygonVertexBase(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); - break; - case PolygonCulling.Edge: - result = OutOfPolygonEdgeBase(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); - break; - - case PolygonCulling.EdgeAndCenterRay: - result = OutOfPolygonEdgeEdgeAndCenterRayCast(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); - break; - } - + var result = OutOfPolygonVertexBase(targetTri, WorldVerticals, MaxRange, MinRange, IsAllVertex); FilteringBit[index] = result; } - internal static JobChain>> GetJobChain(PolygonCulling polygonCulling, float minRange, float maxRange, bool isAllVertex) + internal static JobChain>> GetJobChain(float minRange, float maxRange, bool isAllVertex) { return (input, jobHandle) => { var job = new OutOfPolygonStruct() { - PolygonCulling = polygonCulling, MinRange = minRange, MaxRange = maxRange, IsAllVertex = isAllVertex, @@ -217,39 +200,6 @@ public static bool OutOfPolygonVertexBase(TriangleIndex targetTri, NativeArray Vertex, float maxRange, float minRange, bool isAllVertex) - { - float centerPos = Mathf.Lerp(maxRange, minRange, 0.5f); - var centerPosVec2 = new Vector2(centerPos, centerPos); - Span outOfPolygon = stackalloc bool[3] { false, false, false }; - Span edgeIndexArray = stackalloc Vector2Int[3] { new Vector2Int(0, 1), new Vector2Int(1, 2), new Vector2Int(2, 1) }; - foreach (var index in edgeIndexArray) - { - - var a = Vertex[targetTri[index.x]]; - var b = Vertex[targetTri[index.y]]; - var nerPoint = VectorUtility.NearPointOnLine(a, b, centerPosVec2); - outOfPolygon[index.x] = !(minRange < nerPoint.x && nerPoint.x < maxRange && minRange < nerPoint.y && nerPoint.y < maxRange); - } - if (isAllVertex) return outOfPolygon[0] && outOfPolygon[1] && outOfPolygon[2]; - else return outOfPolygon[0] || outOfPolygon[1] || outOfPolygon[2]; - } - public static bool OutOfPolygonEdgeEdgeAndCenterRayCast(TriangleIndex targetTri, NativeArray vertex, float maxRange, float minRange, bool isAllVertex) - { - float centerPos = Mathf.Lerp(maxRange, minRange, 0.5f); - var centerPosVec2 = new Vector2(centerPos, centerPos); - if (!OutOfPolygonEdgeBase(targetTri, vertex, maxRange, minRange, isAllVertex)) - { - return false; - } - else - { - Span tri = stackalloc Vector2[3]; - tri[0] = vertex[targetTri[0]]; tri[1] = vertex[targetTri[1]]; tri[2] = vertex[targetTri[2]]; - var crossT = VectorUtility.CrossTriangle(tri, centerPosVec2); - return VectorUtility.IsInCal(crossT.x, crossT.y, crossT.z); - } - } } From d3dc83974b046624b259e8580dc4e8ff318a0d00 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 13:33:27 +0900 Subject: [PATCH 123/208] chore: make IslandSelectExecute static --- Runtime/Decal/IslandSelectToPPFilter.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index c38909ad..6d33e69c 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -44,7 +44,7 @@ public void SetSpace(ParallelProjectionSpace space) _filteredTriangles = new NativeArray[smCount]; for (var i = 0; smCount > i; i += 1) { - var islandSelected = _islandSelectedTriangles[i] = IslandSelectExecute(i); + var islandSelected = _islandSelectedTriangles[i] = IslandSelectExecute(IslandSelector, _ppSpace.MeshData, i); if (islandSelected.Length == 0) { continue; } var ppsVert = _ppSpace.GetPPSVert; _filteredBit[i] = TriangleFilterUtility.FilteringTriangle(islandSelected, ppsVert, Filters); @@ -54,13 +54,14 @@ NativeArray ITrianglesFilter.GetFiltered { if (_ppSpace is null) { return default; } if (_islandSelectedTriangles[subMeshIndex].Length == 0) { return default; } + if (_filteredTriangles[subMeshIndex].IsCreated) { return _filteredTriangles[subMeshIndex]; } var filteredTriangle = _filteredTriangles[subMeshIndex] = ParallelProjectionFilter.FilteringExecute(_islandSelectedTriangles[subMeshIndex], _filteredBit[subMeshIndex].GetResult); return filteredTriangle; } - private NativeArray IslandSelectExecute(int subMeshIndex) + internal static NativeArray IslandSelectExecute(IIslandSelector islandSelector, MeshData meshData, int subMeshIndex) { - var meshData = _ppSpace.MeshData; + if (islandSelector == null) { return new NativeArray(meshData.TriangleIndex[subMeshIndex], Allocator.TempJob); } Island[] islands = (subMeshIndex, meshData).Memo(GetIslands); Profiler.BeginSample("CreateIslandDescription"); @@ -70,7 +71,7 @@ private NativeArray IslandSelectExecute(int subMeshIndex) Profiler.EndSample(); Profiler.BeginSample("IslandSelect"); - var bitArray = IslandSelector.IslandSelect(islands, islandDescription); + var bitArray = islandSelector.IslandSelect(islands, islandDescription); Profiler.EndSample(); Profiler.BeginSample("FilterTriangle"); @@ -108,8 +109,11 @@ static Island[] GetIslands((int subMeshIndex, MeshData meshData) pair) public void Dispose() { foreach (var na in _filteredBit) { na?.GetResult.Dispose(); } + _filteredBit = null; foreach (var na in _islandSelectedTriangles) { na.Dispose(); } + _islandSelectedTriangles = null; foreach (var na in _filteredTriangles) { na.Dispose(); } + _filteredTriangles = null; } } } From 6616c63fdd6d81d46960f9e5dd3370ffe961010f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 13:34:14 +0900 Subject: [PATCH 124/208] chore: added NotContainsKeyAutoGenerate on DecalContext --- TexTransCore/Decal/DecalContext.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs index c4348ff1..f2a83f5c 100644 --- a/TexTransCore/Decal/DecalContext.cs +++ b/TexTransCore/Decal/DecalContext.cs @@ -40,6 +40,8 @@ internal class DecalContext public bool HighQualityPadding { get; set; } = false; public bool? UseDepthOrInvert { get; set; } = null; + public bool NotContainsKeyAutoGenerate { get; set; } = true; + public DecalContext(ConvertSpace convertSpace, TrianglesFilter trianglesFilter) { _convertSpace = convertSpace; @@ -49,6 +51,8 @@ public DecalContext(ConvertSpace convertSpace, TrianglesFilter trianglesFilter) internal void WriteDecalTexture(Dictionary renderTextures, Renderer targetRenderer, Texture sourceTexture) { if (renderTextures == null) { throw new ArgumentNullException(nameof(renderTextures)); } + if (targetRenderer is not SkinnedMeshRenderer && targetRenderer is not MeshRenderer) { return; } + if (targetRenderer.GetMesh() == null) { return; } Profiler.BeginSample("GetMeshData"); var meshData = targetRenderer.Memo(MeshData.GetMeshData, i => i.Dispose()); @@ -73,6 +77,8 @@ internal void WriteDecalTexture(Dictionary renderTextur var targetTexture = targetMat.GetTexture(TargetPropertyName); if (targetTexture == null) { continue; } + if (!NotContainsKeyAutoGenerate && !renderTextures.ContainsKey(targetMat)) { continue; } + Profiler.BeginSample("GetFilteredSubTriangle"); var filteredTriangle = _trianglesFilter.GetFilteredSubTriangle(i); Profiler.EndSample(); @@ -98,8 +104,20 @@ internal void WriteDecalTexture(Dictionary renderTextur _convertSpace.Dispose(); } + internal void GenerateKey(Dictionary writeable, IEnumerable targetMat) + { + foreach (var mat in targetMat) + { + if (mat == null) { continue; } + if (writeable.ContainsKey(mat)) { continue; } + if (!mat.HasProperty(TargetPropertyName)) { continue; } + var targetTexture = mat.GetTexture(TargetPropertyName); + if (targetTexture == null) { continue; } - + var rt = writeable[mat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); + rt.Clear(); + } + } } public enum PolygonCulling From d875694c66b796e5bdc8f2fca9e9ec0dc2471a11 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 13:37:39 +0900 Subject: [PATCH 125/208] chore: OriginEqual reference PreviewMaterial --- Editor/Preview/RealTime/RealTimePreviewDomain.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs index da75fd4f..eec3ee3e 100644 --- a/Editor/Preview/RealTime/RealTimePreviewDomain.cs +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -130,7 +130,17 @@ public void PreviewExit() public ITextureManager GetTextureManager() => _textureManager; public bool IsPreview() => true; - public bool OriginEqual(UnityEngine.Object l, UnityEngine.Object r) => l == r; + public bool OriginEqual(UnityEngine.Object l, UnityEngine.Object r) + { + if (l == r) { return true; } + if (l is Material lm && r is Material rm) + { + if (_previewMaterialMap.ContainsKey(lm)) lm = _previewMaterialMap[lm]; + if (_previewMaterialMap.ContainsKey(rm)) rm = _previewMaterialMap[rm]; + return lm == rm; + } + return false; + } public void RegisterReplace(UnityEngine.Object oldObject, UnityEngine.Object nowObject) { } public void ReplaceMaterials(Dictionary mapping, bool rendererOnly = false) { throw new NotImplementedException(); } From 51e873f8317653a36a76ef3e6c18378fead545f5 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 13:38:59 +0900 Subject: [PATCH 126/208] chore: add JobResult.GetResultUnCheck --- TexTransCore/JobResult.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/TexTransCore/JobResult.cs b/TexTransCore/JobResult.cs index 47cd4e0b..ae4c730c 100644 --- a/TexTransCore/JobResult.cs +++ b/TexTransCore/JobResult.cs @@ -21,6 +21,7 @@ public T GetResult return _result; } } + public T GetResultUnCheck => _result; public JobHandle GetHandle => _jobHandle; public JobResult(T result) { _result = result; _jobHandle = default; _completeAction = null; } From 8a94a89778606609e80eb2d963fcdd62190bb46e Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 13:41:37 +0900 Subject: [PATCH 127/208] chore: dispose on array initialize --- .../Decal/ParallelProjection/ParallelProjectionFilter.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs index 8e18833a..c93102fc 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs @@ -36,6 +36,7 @@ public void SetSpace(ParallelProjectionSpace space) NativeArray ITrianglesFilter.GetFilteredSubTriangle(int subMeshIndex) { if (_parallelProjectionSpace is null) { return default; } + if (_filteredTriangles[subMeshIndex].IsCreated) { return _filteredTriangles[subMeshIndex]; } var filteredTriangle = _filteredTriangles[subMeshIndex] = FilteringExecute(_parallelProjectionSpace.MeshData.TriangleIndex[subMeshIndex], _filteredBit[subMeshIndex].GetResult); return filteredTriangle; } @@ -64,7 +65,9 @@ internal static NativeArray FilteringExecute(NativeArray Date: Sun, 28 Apr 2024 20:10:25 +0900 Subject: [PATCH 128/208] feat: add TexTransRuntimeBehavior.GetDependencyHash --- Editor/Domain/RenderersDomain.cs | 1 + .../Decal/SingleGradationDecalEditor.cs | 24 +++++++++++++++ .../Decal/SingleGradationDecalEditor.cs.meta | 11 +++++++ .../RealTime/RealTimePreviewContext.cs | 29 ++++++++++++++++--- .../MatAndTexUtils/MaterialModifier.cs | 12 +++++++- Runtime/CommonComponent/TextureBlender.cs | 7 ++++- Runtime/Decal/SimpleDecal.cs | 13 +++++++-- .../IslandSelect/AbstructIslandSelector.cs | 24 +++++++++++++++ Runtime/IslandSelect/BoxIslandSelector.cs | 6 ++-- Runtime/IslandSelect/IslandSelectorAND.cs | 7 ++++- Runtime/IslandSelect/IslandSelectorNOT.cs | 8 ++++- Runtime/IslandSelect/IslandSelectorOR.cs | 4 ++- Runtime/IslandSelect/IslandSelectorRelay.cs | 5 +++- Runtime/IslandSelect/IslandSelectorXOR.cs | 4 ++- Runtime/IslandSelect/RayCastIslandSelector.cs | 7 +++-- .../IslandSelect/RendererIslandSelector.cs | 9 +++++- Runtime/IslandSelect/SphereIslandSelector.cs | 7 +++-- Runtime/IslandSelect/SubMeshIslandSelector.cs | 3 ++ Runtime/MultiLayerImage/AbstractLayer.cs | 7 +++++ Runtime/MultiLayerImage/LayerFolder.cs | 9 ++++++ .../MultiLayerImage/MultiLayerImageCanvas.cs | 12 +++++++- .../MultiLayerImage/RasterImportedLayer.cs | 3 ++ Runtime/MultiLayerImage/RasterLayer.cs | 1 + Runtime/TTType/TextureSelector.cs | 28 ++++++++++++++++++ Runtime/TexTransRuntimeBehavior.cs | 3 +- Runtime/TextureAtlas/AtlasTexture.cs | 13 ++++++++- .../IslandFineTuner/IIslandFineTuner.cs | 1 + .../IslandFineTuner/SizePriority.cs | 1 + Runtime/Utils/TransformUtility.cs | 19 +++++++++++- 29 files changed, 252 insertions(+), 26 deletions(-) create mode 100644 Editor/Inspector/Decal/SingleGradationDecalEditor.cs create mode 100644 Editor/Inspector/Decal/SingleGradationDecalEditor.cs.meta diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index 4de07806..d3b3cb54 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -143,6 +143,7 @@ public virtual bool OriginEqual(Object l, Object r) Object GetOrigin(Object obj) { + if(obj == null) { return null; } while (_replaceMap.ContainsKey(obj)) { obj = _replaceMap[obj]; } return obj; } diff --git a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs new file mode 100644 index 00000000..3ecf0456 --- /dev/null +++ b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs @@ -0,0 +1,24 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.Decal; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using net.rs64.TexTransTool.IslandSelector; +using System; +using net.rs64.TexTransTool.Preview.RealTime; + +namespace net.rs64.TexTransTool.Editor.Decal +{ + + [CanEditMultipleObjects] + [CustomEditor(typeof(SingleGradationDecal))] + internal class SingleGradationDecalEditor : UnityEditor.Editor + { + public override void OnInspectorGUI() + { + TextureTransformerEditor.DrawerWarning(target.GetType().Name); + base.OnInspectorGUI(); + TextureTransformerEditor.DrawerRealTimePreviewEditorButton(target as TexTransRuntimeBehavior); + } + } +} diff --git a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs.meta b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs.meta new file mode 100644 index 00000000..e4caa034 --- /dev/null +++ b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abd835fabd92c544c86aa736b566ea56 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Preview/RealTime/RealTimePreviewContext.cs b/Editor/Preview/RealTime/RealTimePreviewContext.cs index e7eb0e71..e10958bd 100644 --- a/Editor/Preview/RealTime/RealTimePreviewContext.cs +++ b/Editor/Preview/RealTime/RealTimePreviewContext.cs @@ -5,6 +5,7 @@ using net.rs64.TexTransTool.Build; using net.rs64.TexTransTool.Decal; using net.rs64.TexTransTool.MultiLayerImage; +using net.rs64.TexTransTool.Utils; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; @@ -17,6 +18,7 @@ internal class RealTimePreviewContext : ScriptableSingleton _PriorityMap = new(); Dictionary> _dependencyMap = new(); + Dictionary _dependencyHashMap = new(); HashSetQueue _updateQueue = new(); @@ -64,18 +66,31 @@ void AddPreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) default: { return; } case SimpleDecal: case MultiLayerImageCanvas: + case SingleGradationDecal: { break; } } if (ContainsBehavior(texTransRuntimeBehavior)) { return; } - foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency(_previewDomain.EnumerateRenderer()).Append(texTransRuntimeBehavior).Where(g => g != null).Select(g => g.GetInstanceID())) + RegisterDependency(texTransRuntimeBehavior); + _updateQueue.Enqueue(texTransRuntimeBehavior); + } + + private void RegisterDependency(TexTransRuntimeBehavior texTransRuntimeBehavior) + { + _dependencyHashMap[texTransRuntimeBehavior] = texTransRuntimeBehavior.GetDependencyHash(_previewDomain); + foreach (var dependInstanceID in texTransRuntimeBehavior.GetDependency(_previewDomain) + .Append(texTransRuntimeBehavior) + .Append(texTransRuntimeBehavior.gameObject) + .Concat(texTransRuntimeBehavior.gameObject.GetParents()) + .Where(g => g != null).Select(g => g.GetInstanceID()) + ) { if (!_dependencyMap.ContainsKey(dependInstanceID)) { _dependencyMap[dependInstanceID] = new(); } _dependencyMap[dependInstanceID].Add(texTransRuntimeBehavior); } - _updateQueue.Enqueue(texTransRuntimeBehavior); } - void RemovePreviewBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var depend in _dependencyMap) { depend.Value.Remove(texTransRuntimeBehavior); } } + + void UnRegisterDependency(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var depend in _dependencyMap) { depend.Value.Remove(texTransRuntimeBehavior); } } bool ContainsBehavior(TexTransRuntimeBehavior texTransRuntimeBehavior) { foreach (var dependKey in _dependencyMap) @@ -136,9 +151,15 @@ void UpdatePreview() { if (_updateQueue.TryDequeue(out var texTransRuntimeBehavior) && _PriorityMap.TryGetValue(texTransRuntimeBehavior, out var priority)) { + if (_dependencyHashMap[texTransRuntimeBehavior] != texTransRuntimeBehavior.GetDependencyHash(_previewDomain)) + { + UnRegisterDependency(texTransRuntimeBehavior); + RegisterDependency(texTransRuntimeBehavior); + } + _previewDomain.SetNowPriority(priority); - try { if (texTransRuntimeBehavior.IsPossibleApply) { texTransRuntimeBehavior.Apply(_previewDomain); } } + try { if (texTransRuntimeBehavior.gameObject.activeInHierarchy && texTransRuntimeBehavior.IsPossibleApply) { texTransRuntimeBehavior.Apply(_previewDomain); } } catch (Exception ex) { Debug.LogException(ex); } _previewDomain.UpdateNeeded(); diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs index 66d29c11..6f5f2b37 100644 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs @@ -90,10 +90,20 @@ internal override void Apply([NotNull] IDomain domain) domain.ReplaceMaterials(modMatList); } - internal override IEnumerable GetDependency(IEnumerable domainRenderers) + internal override IEnumerable GetDependency(IDomain domain) { foreach (var i in ModifiedTarget) { yield return i; } foreach (var i in TargetRenderers) { yield return i; } } + + internal override int GetDependencyHash(IDomain domain) + { + var hash = 0; + foreach (var tr in TargetRenderers) + { + hash ^= tr?.GetInstanceID() ?? 0; + } + return hash; + } } } diff --git a/Runtime/CommonComponent/TextureBlender.cs b/Runtime/CommonComponent/TextureBlender.cs index 889bfae1..2bdda79e 100644 --- a/Runtime/CommonComponent/TextureBlender.cs +++ b/Runtime/CommonComponent/TextureBlender.cs @@ -38,6 +38,11 @@ internal override void Apply(IDomain domain) domain.AddTextureStack(distTex, new(addTex, BlendTypeKey)); } - internal override IEnumerable GetDependency(IEnumerable domainRenderers) { return TargetTexture.GetDependency().Append(BlendTexture); } + internal override IEnumerable GetDependency(IDomain domain) { return TargetTexture.GetDependency().Append(BlendTexture); } + + internal override int GetDependencyHash(IDomain domain) + { + return TargetTexture.GetDependencyHash() ^ BlendTexture?.GetInstanceID() ?? 0; + } } } diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 9515ee7b..79114312 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -100,10 +100,10 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan return mulDecalTexture; } - internal override IEnumerable GetDependency(IEnumerable renderers) + internal override IEnumerable GetDependency(IDomain domain) { var dependencies = new UnityEngine.Object[] { transform } - .Concat(GetComponentsInParent(true)) + .Concat(transform.GetParents()) .Concat(TargetRenderers) .Concat(TargetRenderers.Select(r => r.transform)) .Concat(TargetRenderers.Select(r => r.GetMesh())) @@ -113,6 +113,13 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } return dependencies; } + internal override int GetDependencyHash(IDomain domain) + { + var hash = 0; + foreach (var tr in TargetRenderers) { hash ^= tr?.GetInstanceID() ?? 0; } + hash ^= DecalTexture?.GetInstanceID() ?? 0; + return hash; + } [ExpandTexture2D] public Texture2D DecalTexture; internal override bool IsPossibleApply => TargetRenderers.Any(i => i != null); @@ -172,8 +179,8 @@ internal void OnDrawGizmosSelected() DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, matrix); + IslandSelector?.OnDrawGizmosSelected(); } - } } diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index e4cd5af1..7020daf0 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -17,6 +17,8 @@ public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, internal abstract IEnumerable GetDependency(); + internal abstract int GetDependencyHash(); + internal abstract BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription); BitArray IIslandSelector.IslandSelect(Island[] islands, IslandDescription[] islandDescription) => IslandSelect(islands, islandDescription); /* @@ -26,7 +28,29 @@ public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, マテリアルの参照を比較してはならない。 */ + internal abstract void OnDrawGizmosSelected(); + + internal static IEnumerable ChildeDependency(AbstractIslandSelector abstractIslandSelector) + { + var chiles = TexTransGroup.GetChildeComponent(abstractIslandSelector.transform); + foreach (var chile in chiles) + { + yield return chile; + foreach (var cd in chile.GetDependency()) { yield return cd; } + } + } + internal static int ChildeDependencyHash(AbstractIslandSelector abstractIslandSelector) + { + var hash = 0; + var chiles = TexTransGroup.GetChildeComponent(abstractIslandSelector.transform); + foreach (var chile in chiles) + { + hash ^= chile?.GetInstanceID() ?? 0; + hash ^= chile?.GetDependencyHash() ?? 0; + } + return hash; + } } internal interface IIslandSelector { diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs index b8ff7268..f11ab933 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.Utils; using UnityEngine; namespace net.rs64.TexTransTool.IslandSelector @@ -12,8 +13,9 @@ public class BoxIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT BoxIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - internal override IEnumerable GetDependency() { yield break; } + internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } + internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); @@ -43,7 +45,7 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } - void OnDrawGizmosSelected() + internal override void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawWireCube(Vector3.zero, Vector3.one); diff --git a/Runtime/IslandSelect/IslandSelectorAND.cs b/Runtime/IslandSelect/IslandSelectorAND.cs index c1b790fa..b19778db 100644 --- a/Runtime/IslandSelect/IslandSelectorAND.cs +++ b/Runtime/IslandSelect/IslandSelectorAND.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransCore.Island; using UnityEngine; using UnityEngine.Profiling; @@ -11,7 +12,10 @@ public class IslandSelectorAND : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectorAND"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform); } + internal override IEnumerable GetDependency() { return ChildeDependency(this); } + + internal override int GetDependencyHash() { return ChildeDependencyHash(this); } + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; @@ -25,5 +29,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is } return bitArray; } + internal override void OnDrawGizmosSelected() { foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) { islandSelector.OnDrawGizmosSelected(); } } } } diff --git a/Runtime/IslandSelect/IslandSelectorNOT.cs b/Runtime/IslandSelect/IslandSelectorNOT.cs index 4df312b5..20aa1aa0 100644 --- a/Runtime/IslandSelect/IslandSelectorNOT.cs +++ b/Runtime/IslandSelect/IslandSelectorNOT.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransCore.Island; using UnityEngine; using UnityEngine.Profiling; @@ -13,10 +14,15 @@ public class IslandSelectorNOT : AbstractIslandSelector internal const string MenuPath = FoldoutName + "/" + ComponentName; public AbstractIslandSelector IslandSelector; - internal override IEnumerable GetDependency() { return IslandSelector.GetDependency(); } + internal override IEnumerable GetDependency() { return IslandSelector.GetDependency().Append(IslandSelector); } + + internal override int GetDependencyHash() { return (IslandSelector?.GetInstanceID() ?? 0) ^ (IslandSelector?.GetDependencyHash() ?? 0); } + internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); } + + internal override void OnDrawGizmosSelected() { IslandSelector?.OnDrawGizmosSelected(); } } } diff --git a/Runtime/IslandSelect/IslandSelectorOR.cs b/Runtime/IslandSelect/IslandSelectorOR.cs index 07a732c6..104f20a1 100644 --- a/Runtime/IslandSelect/IslandSelectorOR.cs +++ b/Runtime/IslandSelect/IslandSelectorOR.cs @@ -12,7 +12,8 @@ public class IslandSelectorOR : AbstractIslandSelector { internal const string ComponentName = "TTT IslandSelectorOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform).SelectMany(i => i.GetDependency()); } + internal override IEnumerable GetDependency() { return ChildeDependency(this); } + internal override int GetDependencyHash() { return ChildeDependencyHash(this); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; @@ -26,5 +27,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is } return bitArray; } + internal override void OnDrawGizmosSelected() { foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) { islandSelector.OnDrawGizmosSelected(); } } } } diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs b/Runtime/IslandSelect/IslandSelectorRelay.cs index 4962681f..5bb79b6a 100644 --- a/Runtime/IslandSelect/IslandSelectorRelay.cs +++ b/Runtime/IslandSelect/IslandSelectorRelay.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using net.rs64.TexTransCore.Island; using UnityEngine; using UnityEngine.Profiling; @@ -14,11 +15,13 @@ public class IslandSelectorRelay : AbstractIslandSelector public AbstractIslandSelector IslandSelector = null; - internal override IEnumerable GetDependency() { return IslandSelector.GetDependency(); } + internal override IEnumerable GetDependency() { return IslandSelector.GetDependency().Append(IslandSelector); } + internal override int GetDependencyHash() { return (IslandSelector?.GetInstanceID() ?? 0) ^ (IslandSelector?.GetDependencyHash() ?? 0); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription) : new BitArray(islands.Length); } + internal override void OnDrawGizmosSelected() { IslandSelector?.OnDrawGizmosSelected(); } } } diff --git a/Runtime/IslandSelect/IslandSelectorXOR.cs b/Runtime/IslandSelect/IslandSelectorXOR.cs index 3fcc0269..f519bf30 100644 --- a/Runtime/IslandSelect/IslandSelectorXOR.cs +++ b/Runtime/IslandSelect/IslandSelectorXOR.cs @@ -13,7 +13,8 @@ public class IslandSelectorXOR : AbstractIslandSelector internal const string ComponentName = "TTT IslandSelectorXOR"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - internal override IEnumerable GetDependency() { return TexTransGroup.GetChildeComponent(transform).SelectMany(i => i.GetDependency()); } + internal override IEnumerable GetDependency() { return ChildeDependency(this); } + internal override int GetDependencyHash() { return ChildeDependencyHash(this); } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { BitArray bitArray = null; @@ -27,5 +28,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is } return bitArray; } + internal override void OnDrawGizmosSelected() { foreach (var islandSelector in TexTransGroup.GetChildeComponent(transform)) { islandSelector.OnDrawGizmosSelected(); } } } } diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs index 9e76019f..647fd5d3 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -8,6 +8,8 @@ using Unity.Jobs; using net.rs64.TexTransCore.TransTextureCore; using UnityEngine.Profiling; +using net.rs64.TexTransTool.Utils; +using System.Linq; namespace net.rs64.TexTransTool.IslandSelector { @@ -17,7 +19,8 @@ public class RayCastIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT RayCastIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public float IslandSelectorRange = 0.1f; - internal override IEnumerable GetDependency() { yield break; } + internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } + internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { return RayCastIslandSelect(GetIslandSelectorRay(), islands, islandDescription); @@ -78,7 +81,7 @@ internal static BitArray RayCastIslandSelect(IslandSelectorRay islandSelectorRay - void OnDrawGizmosSelected() + internal override void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawLine(Vector3.zero, new Vector3(0, 0, IslandSelectorRange)); diff --git a/Runtime/IslandSelect/RendererIslandSelector.cs b/Runtime/IslandSelect/RendererIslandSelector.cs index 2f99849a..2023f2a9 100644 --- a/Runtime/IslandSelect/RendererIslandSelector.cs +++ b/Runtime/IslandSelect/RendererIslandSelector.cs @@ -12,7 +12,13 @@ public class RendererIslandSelector : AbstractIslandSelector { internal const string ComponentName = "TTT RendererIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - internal override IEnumerable GetDependency() { yield break; } + internal override IEnumerable GetDependency() { yield break; } + internal override int GetDependencyHash() + { + var hash = 0; + foreach (var r in RendererList) { hash ^= r?.GetInstanceID() ?? 0; } + return hash; + } public List RendererList; internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { @@ -23,5 +29,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } + internal override void OnDrawGizmosSelected() { } } } diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index 93faa6a0..0e0ceeda 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Island; +using net.rs64.TexTransTool.Utils; using UnityEngine; namespace net.rs64.TexTransTool.IslandSelector @@ -12,8 +13,8 @@ public class SphereIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT SphereIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; public float SphereSize = 0.1f; - internal override IEnumerable GetDependency() { yield break; } - + internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } + internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); @@ -37,7 +38,7 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } - void OnDrawGizmosSelected() + internal override void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawWireSphere(Vector3.zero, SphereSize); diff --git a/Runtime/IslandSelect/SubMeshIslandSelector.cs b/Runtime/IslandSelect/SubMeshIslandSelector.cs index ef07cbe4..1b3da121 100644 --- a/Runtime/IslandSelect/SubMeshIslandSelector.cs +++ b/Runtime/IslandSelect/SubMeshIslandSelector.cs @@ -15,6 +15,7 @@ public class SubMeshIslandSelector : AbstractIslandSelector public int SelectSubMeshIndex = 0; internal override IEnumerable GetDependency() { yield break; } + internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { var bitArray = new BitArray(islands.Length); @@ -26,5 +27,7 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return bitArray; } + + internal override void OnDrawGizmosSelected() { } } } diff --git a/Runtime/MultiLayerImage/AbstractLayer.cs b/Runtime/MultiLayerImage/AbstractLayer.cs index 96eb092e..affa5c83 100644 --- a/Runtime/MultiLayerImage/AbstractLayer.cs +++ b/Runtime/MultiLayerImage/AbstractLayer.cs @@ -41,6 +41,10 @@ internal virtual LayerAlphaMod GetLayerAlphaMod(CanvasContext canvasContext) foreach (var m in LayerMask.GetDependency()) { yield return m; } } + internal virtual int GetDependencyHash() + { + return LayerMask.GetDependencyHash(); + } } [Serializable] public class LayerMask : ILayerMask @@ -52,6 +56,8 @@ public class LayerMask : ILayerMask public IEnumerable GetDependency() { yield return MaskTexture; } + public int GetDependencyHash() { return MaskTexture?.GetInstanceID() ?? 0; } + void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture originTexture) { originTexture.WriteOriginalTexture(MaskTexture, renderTexture); @@ -63,6 +69,7 @@ public interface ILayerMask bool ContainedMask { get; } void WriteMaskTexture(RenderTexture renderTexture, IOriginTexture originTexture); abstract IEnumerable GetDependency(); + int GetDependencyHash(); } diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index 930a0f38..3be7d341 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -62,6 +62,15 @@ internal IEnumerable GetChileLayers() var chileLayers = GetChileLayers(); return base.GetDependency().Concat(chileLayers).Concat(chileLayers.SelectMany(l => l.GetDependency())); } + internal override int GetDependencyHash() + { + var hash = base.GetDependencyHash(); + foreach (var cl in GetChileLayers()) + { + hash ^= cl.GetDependencyHash(); + } + return hash; + } } diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 272d04c9..99f8c665 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -65,12 +65,22 @@ internal static int NormalizePowOfTow(int v) else { return nextV; } } - internal override IEnumerable GetDependency(IEnumerable domainRenderers) + internal override IEnumerable GetDependency(IDomain domain) { var chileLayers = GetChileLayers(); return TextureSelector.GetDependency().Append(tttImportedCanvasDescription).Concat(chileLayers).Concat(chileLayers.SelectMany(l => l.GetDependency())); } + internal override int GetDependencyHash(IDomain domain) + { + var hash = TextureSelector.GetDependencyHash(); + foreach (var cl in GetChileLayers()) + { + hash ^= cl.GetDependencyHash(); + } + return hash; + } + internal class CanvasContext { public ITextureManager TextureManager; diff --git a/Runtime/MultiLayerImage/RasterImportedLayer.cs b/Runtime/MultiLayerImage/RasterImportedLayer.cs index 37df5e76..93fc0c14 100644 --- a/Runtime/MultiLayerImage/RasterImportedLayer.cs +++ b/Runtime/MultiLayerImage/RasterImportedLayer.cs @@ -21,6 +21,7 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin } internal override IEnumerable GetDependency() { return base.GetDependency().Append(ImportedImage); } + internal override int GetDependencyHash() { return base.GetDependencyHash() ^ ImportedImage?.GetInstanceID() ?? 0; } } [Serializable] public class TTTImportedLayerMask : ILayerMask @@ -41,5 +42,7 @@ void ILayerMask.WriteMaskTexture(RenderTexture renderTexture, IOriginTexture ori originTexture.WriteOriginalTexture(MaskTexture, renderTexture); } public IEnumerable GetDependency() { yield return MaskTexture; } + + public int GetDependencyHash() { return MaskTexture?.GetInstanceID() ?? 0; } } } diff --git a/Runtime/MultiLayerImage/RasterLayer.cs b/Runtime/MultiLayerImage/RasterLayer.cs index 472e89bf..34a8a206 100644 --- a/Runtime/MultiLayerImage/RasterLayer.cs +++ b/Runtime/MultiLayerImage/RasterLayer.cs @@ -15,5 +15,6 @@ public override void GetImage(RenderTexture renderTexture, IOriginTexture origin originTexture.WriteOriginalTexture(RasterTexture, renderTexture); } internal override IEnumerable GetDependency() { return base.GetDependency().Append(RasterTexture); } + internal override int GetDependencyHash() { return base.GetDependencyHash() ^ RasterTexture?.GetInstanceID() ?? 0; } } } diff --git a/Runtime/TTType/TextureSelector.cs b/Runtime/TTType/TextureSelector.cs index 8b379cbd..4347d757 100644 --- a/Runtime/TTType/TextureSelector.cs +++ b/Runtime/TTType/TextureSelector.cs @@ -62,6 +62,34 @@ internal Texture GetTexture() } } } + internal int GetDependencyHash() + { + var hash = 0; + hash ^= (int)Mode; + switch (Mode) + { + + case SelectMode.Absolute: + { + hash ^= SelectTexture?.GetInstanceID() ?? 0; + break; + } + case SelectMode.Relative: + { + if (RendererAsPath == null) { break; } + hash ^= RendererAsPath?.GetInstanceID() ?? 0; + var DistMaterials = RendererAsPath.sharedMaterials; + if (DistMaterials.Length <= SlotAsPath) { break; } + hash ^= SlotAsPath; + hash ^= DistMaterials[SlotAsPath]?.GetInstanceID() ?? 0; + + hash ^= GetTexture()?.GetInstanceID() ?? 0; + break; + } + } + + return hash; + } } } diff --git a/Runtime/TexTransRuntimeBehavior.cs b/Runtime/TexTransRuntimeBehavior.cs index 6aff596e..69204fa5 100644 --- a/Runtime/TexTransRuntimeBehavior.cs +++ b/Runtime/TexTransRuntimeBehavior.cs @@ -18,6 +18,7 @@ public abstract class TexTransRuntimeBehavior : TexTransBehavior, ITexTransToolT /// /// Enumerates references that depend on the component externally. /// - internal abstract IEnumerable GetDependency(IEnumerable domainRenderers); + internal abstract IEnumerable GetDependency(IDomain domain); + internal abstract int GetDependencyHash(IDomain domain); } } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 15042126..29f0afde 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -837,7 +837,7 @@ internal static List FilteredRenderers(GameObject targetRoot, bool inc return result; } - internal override IEnumerable GetDependency(IEnumerable domainRenderers) + internal override IEnumerable GetDependency(IDomain domain) { return AtlasSetting.IslandFineTuners.SelectMany(i => i.GetDependency()) .Concat(Renderers) @@ -845,5 +845,16 @@ internal static List FilteredRenderers(GameObject targetRoot, bool inc .Append(AtlasSetting.AtlasIslandRelocator) .Append(AtlasSetting.MergeReferenceMaterial); } + + internal override int GetDependencyHash(IDomain domain) + { + var hash = 0; + foreach (var ift in AtlasSetting.IslandFineTuners) { hash ^= ift.GetDependencyHash(); } + hash ^= TargetRoot?.GetInstanceID() ?? 0; + foreach (var mmg in AtlasSetting.MaterialMargeGroups) { hash ^= mmg.MargeReferenceMaterial?.GetInstanceID() ?? 0; } + hash ^= AtlasSetting.AtlasIslandRelocator?.GetInstanceID() ?? 0; + hash ^= AtlasSetting.MergeReferenceMaterial?.GetInstanceID() ?? 0; + return hash; + } } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs index 3f3e2e8b..70c2651b 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/IIslandFineTuner.cs @@ -14,5 +14,6 @@ internal interface IIslandFineTuner void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking); IEnumerable GetDependency(); + int GetDependencyHash(); } } diff --git a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs index 669d3966..2b1f9edc 100644 --- a/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs +++ b/Runtime/TextureAtlas/IslandFineTuner/SizePriority.cs @@ -15,6 +15,7 @@ internal class SizePriority : IIslandFineTuner public IEnumerable GetDependency() { return IslandSelector.GetDependency(); } + public int GetDependencyHash() { return IslandSelector.GetDependencyHash(); } public void IslandFineTuning(float[] sizePriority, Island[] islands, IslandDescription[] islandDescriptions, IReplaceTracking replaceTracking) { var targetBit = IslandSelector.IslandSelect(islands, islandDescriptions); diff --git a/Runtime/Utils/TransformUtility.cs b/Runtime/Utils/TransformUtility.cs index 7ac2907e..9aeb08e2 100644 --- a/Runtime/Utils/TransformUtility.cs +++ b/Runtime/Utils/TransformUtility.cs @@ -9,5 +9,22 @@ public static IEnumerable GetChildren(this Transform Parent) { foreach (Transform child in Parent) { yield return child; } } + public static IEnumerable GetParents(this Transform transform) + { + while (transform?.parent != null) + { + transform = transform?.parent; + yield return transform; + } + } + + public static IEnumerable GetParents(this GameObject gameObject) + { + while (gameObject?.transform?.parent != null) + { + gameObject = gameObject?.transform?.parent?.gameObject; + yield return gameObject; + } + } } -} \ No newline at end of file +} From 40a7bdc478ae48a2397d0921351fddec573b0a6a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 28 Apr 2024 20:10:40 +0900 Subject: [PATCH 129/208] feat: SingleGradationDecal --- .../Decal/Gradation/SingleGradationDecal.cs | 200 ++++++++++++++++++ .../Gradation/SingleGradationDecal.cs.meta | 2 +- 2 files changed, 201 insertions(+), 1 deletion(-) diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index e69de29b..4fab4d11 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -0,0 +1,200 @@ +using UnityEngine; +using System.Collections.Generic; +using net.rs64.TexTransTool.IslandSelector; +using System; +using JetBrains.Annotations; +using Unity.Collections; +using net.rs64.TexTransCore.Decal; +using Unity.Jobs; +using Unity.Burst; +using net.rs64.TexTransCore.TransTextureCore; +using System.Linq; +using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransCore.TransTextureCore.Utils; + +namespace net.rs64.TexTransTool.Decal +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public sealed class SingleGradationDecal : TexTransRuntimeBehavior + { + internal const string ComponentName = "TTT SingleGradationDecal"; + internal const string MenuPath = ComponentName; + + internal override List GetRenderers => null; + internal override bool IsPossibleApply => true; + internal override TexTransPhase PhaseDefine => TexTransPhase.AfterUVModification; + + public List TargetMaterials; + public Gradient Gradient; + public AbstractIslandSelector IslandSelector; + [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; + public PropertyName TargetPropertyName = PropertyName.DefaultValue; + + internal override void Apply([NotNull] IDomain domain) + { + var targetMat = GetTargetMaterials(domain.OriginEqual, domain.EnumerateRenderer()); + var gradTex = GradientToTextureWithTemp(Gradient); + var space = new SingleGradientSpace(transform.worldToLocalMatrix); + var filter = new IslandSelectFilter(IslandSelector); + + var decalContext = new DecalContext(space, filter); + decalContext.TargetPropertyName = TargetPropertyName; + decalContext.TextureWarp = TextureWrap.NotWrap; + decalContext.NotContainsKeyAutoGenerate = false; + + var writeable = new Dictionary(); + decalContext.GenerateKey(writeable, targetMat); + + foreach (var renderer in domain.EnumerateRenderer()) + { + if (!renderer.sharedMaterials.Any(mat => targetMat.Contains(mat))) { continue; } + decalContext.WriteDecalTexture(writeable, renderer, gradTex); + } + + foreach (var m2rt in writeable) { domain.AddTextureStack(m2rt.Key.GetTexture(TargetPropertyName), new TextureBlend.BlendTexturePair(m2rt.Value, BlendTypeKey)); } + } + + private HashSet GetTargetMaterials(Func originEqual, IEnumerable domainRenderers) + { + return RendererUtility.GetMaterials(domainRenderers).Where(m => TargetMaterials.Any(tm => originEqual.Invoke(m, tm))).ToHashSet(); + } + + internal static Texture2D s_GradientTempTexture; + internal static Texture2D GradientToTextureWithTemp(Gradient gradient) + { + if (s_GradientTempTexture == null) + { + s_GradientTempTexture = new Texture2D(256, 1, TextureFormat.RGBA32, false); + s_GradientTempTexture.alphaIsTransparency = true; + } + + + using (var colorArray = new NativeArray(256, Allocator.Temp, NativeArrayOptions.UninitializedMemory)) + { + var writeSpan = colorArray.AsSpan(); + for (var i = 0; colorArray.Length > i; i += 1) { writeSpan[i] = gradient.Evaluate(i / 255f); } + + s_GradientTempTexture.LoadRawTextureData(colorArray); + } + s_GradientTempTexture.Apply(true); + + return s_GradientTempTexture; + } + + internal override IEnumerable GetDependency(IDomain domain) + { + IEnumerable depend = new UnityEngine.Object[] { transform }; + if (IslandSelector != null) { depend = depend.Concat(IslandSelector.GetDependency()); } + var materials = GetTargetMaterials(domain.OriginEqual, domain.EnumerateRenderer()); + var dependRenderer = domain.EnumerateRenderer().Where(x => x.sharedMaterials.Any(m => materials.Contains(m))); + + return depend.Concat(transform.GetParents().Select(i => i as UnityEngine.Object)) + .Concat(dependRenderer) + .Concat(dependRenderer.Select(x => x.transform)) + .Concat(dependRenderer.Select(x => x.GetMesh())) + .Concat(dependRenderer.Where(x => x is SkinnedMeshRenderer).Cast().SelectMany(x => x.bones)); + } + + private void OnDrawGizmosSelected() + { + Gizmos.color = Color.black; + Gizmos.matrix = transform.localToWorldMatrix; + + Gizmos.DrawLine(Vector3.zero, Vector3.up); + IslandSelector?.OnDrawGizmosSelected(); + } + + internal override int GetDependencyHash(IDomain domain) + { + var hash = 0; + foreach (var mat in TargetMaterials) { hash ^= mat?.GetInstanceID() ?? 0; } + return hash; + } + } + + internal class SingleGradientSpace : IConvertSpace + { + Matrix4x4 _world2LocalMatrix; + MeshData _meshData; + + JobResult> _uv; + + internal MeshData MeshData => _meshData; + internal JobResult> UV => _uv; + + public SingleGradientSpace(Matrix4x4 w2l) + { + _world2LocalMatrix = w2l; + } + public void Input(MeshData meshData) + { + _meshData = meshData; + var uvNa = new NativeArray(_meshData.Vertices.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); + var convertJob = new ConvertJob() + { + World2Local = _world2LocalMatrix, + worldVerticals = _meshData.Vertices, + uv = uvNa + }; + + _uv = new(uvNa, convertJob.Schedule(uvNa.Length, 32)); + } + + public NativeArray OutPutUV() + { + if (_uv == null) { return default; } + return _uv.GetResult; + } + public void Dispose() + { + _meshData = null; + _uv.GetResult.Dispose(); + _uv = null; + } + + [BurstCompile] + struct ConvertJob : IJobParallelFor + { + [ReadOnly] public NativeArray worldVerticals; + [ReadOnly] public Matrix4x4 World2Local; + [WriteOnly] public NativeArray uv; + public void Execute(int index) { uv[index] = new Vector2(World2Local.MultiplyPoint3x4(worldVerticals[index]).y, 0.5f); } + } + + } + + internal class IslandSelectFilter : ITrianglesFilter + { + public IIslandSelector IslandSelector; + MeshData _meshData; + NativeArray[] _islandSelectedTriangles; + + public IslandSelectFilter(IIslandSelector islandSelector) + { + IslandSelector = islandSelector; + } + + public void SetSpace(SingleGradientSpace space) + { + _meshData = space.MeshData; + _islandSelectedTriangles = new NativeArray[space.MeshData.TriangleIndex.Length]; + } + + NativeArray ITrianglesFilter.GetFilteredSubTriangle(int subMeshIndex) + { + if (_meshData == null) { return default; } + if (_islandSelectedTriangles[subMeshIndex].IsCreated) { return _islandSelectedTriangles[subMeshIndex]; } + var islandSelected = _islandSelectedTriangles[subMeshIndex] = IslandSelectToPPFilter.IslandSelectExecute(IslandSelector, _meshData, subMeshIndex); + return islandSelected; + } + public void Dispose() + { + _meshData = null; + foreach (var na in _islandSelectedTriangles) { na.Dispose(); } + _islandSelectedTriangles = null; + } + + } + +} diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta b/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta index 78bd0e8f..e2ea2ab7 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: From acda36f49ec18f897cc580cd3932bb2ef1a695f9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:32:00 +0900 Subject: [PATCH 130/208] fix: Judge Inside/outside box the see X axis only. --- Runtime/IslandSelect/BoxIslandSelector.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs index f11ab933..ceef4d8b 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -33,8 +33,8 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is var isIn = true; isIn &= Mathf.Abs(vert.x) < 0.5f; - isIn &= Mathf.Abs(vert.x) < 0.5f; - isIn &= Mathf.Abs(vert.x) < 0.5f; + isIn &= Mathf.Abs(vert.y) < 0.5f; + isIn &= Mathf.Abs(vert.z) < 0.5f; if (isIn) { bitArray[islandIndex] = true; break; } } if (bitArray[islandIndex]) { break; } From 0bede5f05270e6add837c8e44f818e827f376bd0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:32:44 +0900 Subject: [PATCH 131/208] remove: sphere range --- Runtime/IslandSelect/SphereIslandSelector.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index 0e0ceeda..a199fb9f 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -12,7 +12,6 @@ public class SphereIslandSelector : AbstractIslandSelector { internal const string ComponentName = "TTT SphereIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - public float SphereSize = 0.1f; internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) @@ -20,7 +19,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is var bitArray = new BitArray(islands.Length); var matrix = transform.worldToLocalMatrix; - var sqrMagMax = SphereSize * SphereSize; for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) { var description = islandDescription[islandIndex]; @@ -29,7 +27,7 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is { for (var vi = 0; 3 > vi; vi += 1) { - if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude < sqrMagMax) { bitArray[islandIndex] = true; break; } + if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude < 1) { bitArray[islandIndex] = true; break; } } if (bitArray[islandIndex]) { break; } } @@ -41,7 +39,7 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is internal override void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; - Gizmos.DrawWireSphere(Vector3.zero, SphereSize); + Gizmos.DrawWireSphere(Vector3.zero, 1); } } } From 0d3dcb5cbb80feb790d754ea56cbd95ab32aee60 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:33:04 +0900 Subject: [PATCH 132/208] chore: add Alpha property --- .../Decal/Gradation/SingleGradationDecal.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index 4fab4d11..c79f86f3 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -27,6 +27,7 @@ public sealed class SingleGradationDecal : TexTransRuntimeBehavior public List TargetMaterials; public Gradient Gradient; + [Range(0, 1)] public float Alpha = 1; public AbstractIslandSelector IslandSelector; [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; public PropertyName TargetPropertyName = PropertyName.DefaultValue; @@ -34,7 +35,7 @@ public sealed class SingleGradationDecal : TexTransRuntimeBehavior internal override void Apply([NotNull] IDomain domain) { var targetMat = GetTargetMaterials(domain.OriginEqual, domain.EnumerateRenderer()); - var gradTex = GradientToTextureWithTemp(Gradient); + var gradTex = GradientToTextureWithTemp(Gradient, Alpha); var space = new SingleGradientSpace(transform.worldToLocalMatrix); var filter = new IslandSelectFilter(IslandSelector); @@ -61,19 +62,20 @@ private HashSet GetTargetMaterials(Func(256, Allocator.Temp, NativeArrayOptions.UninitializedMemory)) { var writeSpan = colorArray.AsSpan(); - for (var i = 0; colorArray.Length > i; i += 1) { writeSpan[i] = gradient.Evaluate(i / 255f); } + for (var i = 0; colorArray.Length > i; i += 1) + { + var col = gradient.Evaluate(i / 255f); + col.a *= alpha; + writeSpan[i] = col; + } s_GradientTempTexture.LoadRawTextureData(colorArray); } From 58254b38d1d74ce26e6af5bfa9fd37d4cd0a402f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:33:27 +0900 Subject: [PATCH 133/208] feat: SIngleGradationDecalEditor --- .../Decal/SingleGradationDecalEditor.cs | 119 +++++++++++++++++- Editor/Localize/en_US.po | 23 ++++ Editor/Localize/ja_JP.po | 23 ++++ 3 files changed, 159 insertions(+), 6 deletions(-) diff --git a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs index 3ecf0456..b5873dba 100644 --- a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs +++ b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs @@ -1,11 +1,8 @@ using UnityEngine; using UnityEditor; using net.rs64.TexTransTool.Decal; -using UnityEngine.UIElements; -using UnityEditor.UIElements; -using net.rs64.TexTransTool.IslandSelector; -using System; -using net.rs64.TexTransTool.Preview.RealTime; +using System.Collections.Generic; +using net.rs64.TexTransCore.TransTextureCore.Utils; namespace net.rs64.TexTransTool.Editor.Decal { @@ -17,8 +14,118 @@ internal class SingleGradationDecalEditor : UnityEditor.Editor public override void OnInspectorGUI() { TextureTransformerEditor.DrawerWarning(target.GetType().Name); - base.OnInspectorGUI(); + + var sTargetMaterials = serializedObject.FindProperty("TargetMaterials"); + foreach (var mat2mat in EnumPair(_materialSelectionCandidates)) + { + var rect = EditorGUILayout.GetControlRect(); + rect.width *= 0.5f; + DrawAtMaterial(sTargetMaterials, mat2mat.Item1, rect); + rect.x += rect.width; + if (mat2mat.Item2 != null) { DrawAtMaterial(sTargetMaterials, mat2mat.Item2, rect); } + } + + EditorGUILayout.PropertyField(sTargetMaterials, "SingleGradationDecal:prop:SelectedMaterialView".Glc()); + + var tf = new SerializedObject((serializedObject.targetObject as SingleGradationDecal).transform); + var sLocalScale = tf.FindProperty("m_LocalScale"); + var length = sLocalScale.vector3Value.y; + var lengthRect = EditorGUILayout.GetControlRect(); + var propGUIContent = EditorGUI.BeginProperty(lengthRect, "SingleGradationDecal:prop:GradationLength".Glc(), sLocalScale); + length = EditorGUI.FloatField(lengthRect, propGUIContent, length); + sLocalScale.vector3Value = new Vector3(length, length, length); + EditorGUI.EndProperty(); + + + var sGradient = serializedObject.FindProperty("Gradient"); + EditorGUILayout.PropertyField(sGradient, "SingleGradationDecal:prop:Gradient".Glc()); + + var sAlpha = serializedObject.FindProperty("Alpha"); + EditorGUILayout.PropertyField(sAlpha, "SingleGradationDecal:prop:Alpha".Glc()); + + var sIslandSelector = serializedObject.FindProperty("IslandSelector"); + EditorGUILayout.PropertyField(sIslandSelector, "SingleGradationDecal:prop:IslandSelector".Glc()); + + var sBlendTypeKey = serializedObject.FindProperty("BlendTypeKey"); + EditorGUILayout.PropertyField(sBlendTypeKey, "SingleGradationDecal:prop:BlendTypeKey".Glc()); + + var sTargetPropertyName = serializedObject.FindProperty("TargetPropertyName"); + EditorGUILayout.PropertyField(sTargetPropertyName, "SingleGradationDecal:prop:TargetPropertyName".Glc()); + + TextureTransformerEditor.DrawerRealTimePreviewEditorButton(target as TexTransRuntimeBehavior); + serializedObject.ApplyModifiedProperties(); + tf.ApplyModifiedProperties(); + } + + private static IEnumerable<(T, T)> EnumPair(IEnumerable values) + { + T bv = default; + bool isBv = false; + foreach (var v in values) + { + if (isBv) + { + yield return (bv, v); + isBv = false; + } + else + { + bv = v; + isBv = true; + } + } + if (isBv) { yield return (bv, default); } + } + + private void DrawAtMaterial(SerializedProperty sTargetMaterials, Material mat, Rect rect) + { + var fullWidth = rect.width; + var val = FindMaterial(sTargetMaterials, mat); + rect.width = rect.height; + var editVal = EditorGUI.Toggle(rect, val); + if (editVal != val) { EditMaterial(sTargetMaterials, mat, editVal); } + rect.x += rect.width; + var prevTex2D = AssetPreview.GetAssetPreview(mat); + if (prevTex2D != null) { EditorGUI.DrawTextureTransparent(rect, prevTex2D, ScaleMode.ScaleToFit); } + rect.x += rect.width; + rect.width = fullWidth - rect.width - rect.width; + EditorGUI.ObjectField(rect, mat, typeof(Material), false); + } + + bool FindMaterial(SerializedProperty matList, Material material) + { + for (var i = 0; matList.arraySize > i; i += 1) + { + if (matList.GetArrayElementAtIndex(i).objectReferenceValue == material) { return true; } + } + return false; + } + void EditMaterial(SerializedProperty matList, Material material, bool val) + { + if (val) + { + var newIndex = matList.arraySize; + matList.arraySize += 1; + matList.GetArrayElementAtIndex(newIndex).objectReferenceValue = material; + } + else + { + for (var i = 0; matList.arraySize > i; i += 1) + { if (matList.GetArrayElementAtIndex(i).objectReferenceValue == material) { matList.DeleteArrayElementAtIndex(i); break; } } + } + } + + + private void OnEnable() { FinedMaterialSelectionCandidates(); } + + List _materialSelectionCandidates; + void FinedMaterialSelectionCandidates() + { + var ep = target as SingleGradationDecal; + var marker = DomainMarkerFinder.FindMarker(ep.gameObject); + if (marker == null) { return; } + _materialSelectionCandidates = RendererUtility.GetFilteredMaterials(marker.GetComponentsInChildren(true), _materialSelectionCandidates); } } } diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index a3f82279..387d8f26 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -421,3 +421,26 @@ msgstr "SummaryNone" msgid "TexTransGroup:label:GroupChildren" msgstr "GroupChildren" + +# SingleGradationDecal + +msgid "SingleGradationDecal:prop:SelectedMaterialView" +msgstr "SelectedMaterialView" + +msgid "SingleGradationDecal:prop:GradationLength" +msgstr "GradationLength" + +msgid "SingleGradationDecal:prop:Gradient" +msgstr "Gradient" + +msgid "SingleGradationDecal:prop:Alpha" +msgstr "Alpha" + +msgid "SingleGradationDecal:prop:IslandSelector" +msgstr "IslandSelector" + +msgid "SingleGradationDecal:prop:BlendTypeKey" +msgstr "BlendTypeKey" + +msgid "SingleGradationDecal:prop:TargetPropertyName" +msgstr "TargetPropertyName" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index 74825b04..d1b859ed 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -419,3 +419,26 @@ msgstr "概要はありません" msgid "TexTransGroup:label:GroupChildren" msgstr "グループの子" + +# SingleGradationDecal + +msgid "SingleGradationDecal:prop:SelectedMaterialView" +msgstr "選択済みマテリアル" + +msgid "SingleGradationDecal:prop:GradationLength" +msgstr "グラデーションの長さ" + +msgid "SingleGradationDecal:prop:Gradient" +msgstr "グラデーション" + +msgid "SingleGradationDecal:prop:Alpha" +msgstr "透明度" + +msgid "SingleGradationDecal:prop:IslandSelector" +msgstr "アイランドセレクター" + +msgid "SingleGradationDecal:prop:BlendTypeKey" +msgstr "ブレンドタイプキー" + +msgid "SingleGradationDecal:prop:TargetPropertyName" +msgstr "ターゲットプロパティネーム" From 7a78c4b5c605f702d5c8eef4979ead7254db6fad Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:35:15 +0900 Subject: [PATCH 134/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 2 ++ CHANGELOG.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 76b3544e..4a3f38ad 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -18,6 +18,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) - SubMeshIslandSelector , IslandSelectorXOR , IslandSelectorRelay が追加されました (#447) - RealTimePreview が大幅に改修され、MultiLayerImageCanvas もリアルタイムプレビュー可能になりました (#448) +- SingleGradationDecal が追加されました (#449) ### Changed @@ -27,6 +28,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) - ObjectReplaceInvoke は削除されました (#438) +- CylindricalDecal , CylindricalCurveDecal , CylindricalCoordinatesSystem , NailEditor , NailOffsetData は削除されました (#449) ### Fixed diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dcda584..af88e78d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture が Scale Transition(Tiling) を使用しているマテリアルのテクスチャを逆補正する機能が追加されました (#431 #435) - NDMF環境でのビルドを行う場合、オブジェクトの置き換えの追跡を NDMF ObjectRegistry を使用するようになりました (#438) - Clip系の合成モードが追加されました (#444) +- SimpleDecal が高速化しました (#449) ### Changed @@ -27,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture の UseUpScale は削除されました (#431) - プログレスバーの詳細な表示が削除されました (#438) +- SimpleDecal のポリゴンカリング、Edge と EdgeAndCenterRay は削除されました (#449) ### Fixed From e64c4867755b2943e108cb5ae6ae1b90fe62ca11 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:43:24 +0900 Subject: [PATCH 135/208] remove: IslandSelectorRelay --- Runtime/IslandSelect/IslandSelectorRelay.cs | 27 ------------------- .../IslandSelect/IslandSelectorRelay.cs.meta | 11 -------- 2 files changed, 38 deletions(-) delete mode 100644 Runtime/IslandSelect/IslandSelectorRelay.cs delete mode 100644 Runtime/IslandSelect/IslandSelectorRelay.cs.meta diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs b/Runtime/IslandSelect/IslandSelectorRelay.cs deleted file mode 100644 index 5bb79b6a..00000000 --- a/Runtime/IslandSelect/IslandSelectorRelay.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransCore.Island; -using UnityEngine; -using UnityEngine.Profiling; - -namespace net.rs64.TexTransTool.IslandSelector -{ - [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class IslandSelectorRelay : AbstractIslandSelector - { - internal const string ComponentName = "TTT IslandSelectorRelay"; - internal const string MenuPath = FoldoutName + "/" + ComponentName; - - public AbstractIslandSelector IslandSelector = null; - - internal override IEnumerable GetDependency() { return IslandSelector.GetDependency().Append(IslandSelector); } - internal override int GetDependencyHash() { return (IslandSelector?.GetInstanceID() ?? 0) ^ (IslandSelector?.GetDependencyHash() ?? 0); } - - internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) - { - return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription) : new BitArray(islands.Length); - } - internal override void OnDrawGizmosSelected() { IslandSelector?.OnDrawGizmosSelected(); } - } -} diff --git a/Runtime/IslandSelect/IslandSelectorRelay.cs.meta b/Runtime/IslandSelect/IslandSelectorRelay.cs.meta deleted file mode 100644 index 7514bcc4..00000000 --- a/Runtime/IslandSelect/IslandSelectorRelay.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 49cf9ca5f1d1e1540854d2ba030db7a9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From b37b635212ff700004f144a91a9fea7b5ebf455d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 19:46:01 +0900 Subject: [PATCH 136/208] change: Do use child instead of absolute reference --- Runtime/IslandSelect/IslandSelectorNOT.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/Runtime/IslandSelect/IslandSelectorNOT.cs b/Runtime/IslandSelect/IslandSelectorNOT.cs index 20aa1aa0..57169e82 100644 --- a/Runtime/IslandSelect/IslandSelectorNOT.cs +++ b/Runtime/IslandSelect/IslandSelectorNOT.cs @@ -13,14 +13,24 @@ public class IslandSelectorNOT : AbstractIslandSelector internal const string ComponentName = "TTT IslandSelectorNOT"; internal const string MenuPath = FoldoutName + "/" + ComponentName; - public AbstractIslandSelector IslandSelector; - internal override IEnumerable GetDependency() { return IslandSelector.GetDependency().Append(IslandSelector); } + internal override IEnumerable GetDependency() + { + var islandSelector = GetIslandSelector(); + if (islandSelector != null) { yield return islandSelector; } + } + + internal override int GetDependencyHash() + { + var islandSelector = GetIslandSelector(); + return (islandSelector?.GetInstanceID() ?? 0) ^ (islandSelector?.GetDependencyHash() ?? 0); + } - internal override int GetDependencyHash() { return (IslandSelector?.GetInstanceID() ?? 0) ^ (IslandSelector?.GetDependencyHash() ?? 0); } + internal AbstractIslandSelector GetIslandSelector() => transform.GetChild(0)?.GetComponent(); internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { - return IslandSelector != null ? IslandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); + var islandSelector = GetIslandSelector(); + return islandSelector != null ? islandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); } internal override void OnDrawGizmosSelected() { IslandSelector?.OnDrawGizmosSelected(); } From 4bfa264b73afcf9ddd61836bec06b85f681f0bec Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:03:36 +0900 Subject: [PATCH 137/208] fix: Exception the child does not exist --- Runtime/IslandSelect/IslandSelectorNOT.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/Runtime/IslandSelect/IslandSelectorNOT.cs b/Runtime/IslandSelect/IslandSelectorNOT.cs index 57169e82..00ada44e 100644 --- a/Runtime/IslandSelect/IslandSelectorNOT.cs +++ b/Runtime/IslandSelect/IslandSelectorNOT.cs @@ -16,7 +16,11 @@ public class IslandSelectorNOT : AbstractIslandSelector internal override IEnumerable GetDependency() { var islandSelector = GetIslandSelector(); - if (islandSelector != null) { yield return islandSelector; } + if (islandSelector != null) + { + yield return islandSelector; + foreach (var depend in islandSelector.GetDependency()) { yield return depend; } + } } internal override int GetDependencyHash() @@ -25,7 +29,12 @@ internal override int GetDependencyHash() return (islandSelector?.GetInstanceID() ?? 0) ^ (islandSelector?.GetDependencyHash() ?? 0); } - internal AbstractIslandSelector GetIslandSelector() => transform.GetChild(0)?.GetComponent(); + internal AbstractIslandSelector GetIslandSelector() + { + var childeCount = transform.childCount; + if (childeCount <= 0) { return null; } + return transform.GetChild(0).GetComponent(); + } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) { @@ -33,6 +42,6 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is return islandSelector != null ? islandSelector.IslandSelect(islands, islandDescription).Not() : new BitArray(islands.Length, true); } - internal override void OnDrawGizmosSelected() { IslandSelector?.OnDrawGizmosSelected(); } + internal override void OnDrawGizmosSelected() { GetIslandSelector()?.OnDrawGizmosSelected(); } } } From 6bc7316846d5adb84d35c99d311dad9871e618fc Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:04:39 +0900 Subject: [PATCH 138/208] chore: remove IslandSelectorRelay of NewGameObjectTTTMenu --- Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index 066606a4..a3ad1269 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -51,7 +51,6 @@ static void C() where TTB : MonoBehaviour [M(BP + IslandSelectorAND.MenuPath)] static void ISAND() => C(); [M(BP + IslandSelectorNOT.MenuPath)] static void ISNOT() => C(); [M(BP + IslandSelectorXOR.MenuPath)] static void ISXOR() => C(); - [M(BP + IslandSelectorRelay.MenuPath)] static void ISR() => C(); } From c13585518fcef183db73567b5a3482ca61a743fc Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:06:26 +0900 Subject: [PATCH 139/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 4a3f38ad..4067d258 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -16,13 +16,15 @@ v0.5.2 以降の実験的機能の変更記録です。 - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) - AtlasTexture に MaterialMargeGroup が追加されました (#432) - ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) -- SubMeshIslandSelector , IslandSelectorXOR , IslandSelectorRelay が追加されました (#447) +- SubMeshIslandSelector , IslandSelectorXOR , ~~IslandSelectorRelay~~ が追加されました (#447) + - IslandSelectorRelayはキャンセルされました (#450) - RealTimePreview が大幅に改修され、MultiLayerImageCanvas もリアルタイムプレビュー可能になりました (#448) - SingleGradationDecal が追加されました (#449) ### Changed - IslandRendererSelector と IslandSelectOR の名前がそれぞれ RendererIslandSelector と IslandSelectorOR に変更されました (#447) +- IslandSelectorNOT は子のオブジェクトの一番目を使用するように変更 (#450) ### Removed From 705a4cb402da3ab17591dfe2eb80085bd0e9f43c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:17:57 +0900 Subject: [PATCH 140/208] feat: add GradientClamp --- Editor/Inspector/Decal/SingleGradationDecalEditor.cs | 3 +++ Editor/Localize/en_US.po | 3 +++ Editor/Localize/ja_JP.po | 3 +++ Runtime/Decal/Gradation/SingleGradationDecal.cs | 4 +++- 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs index b5873dba..b7049d38 100644 --- a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs +++ b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs @@ -43,6 +43,9 @@ public override void OnInspectorGUI() var sAlpha = serializedObject.FindProperty("Alpha"); EditorGUILayout.PropertyField(sAlpha, "SingleGradationDecal:prop:Alpha".Glc()); + var sGradientClamp = serializedObject.FindProperty("GradientClamp"); + EditorGUILayout.PropertyField(sGradientClamp, "SingleGradationDecal:prop:GradientClamp".Glc()); + var sIslandSelector = serializedObject.FindProperty("IslandSelector"); EditorGUILayout.PropertyField(sIslandSelector, "SingleGradationDecal:prop:IslandSelector".Glc()); diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 387d8f26..04e2b03e 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -444,3 +444,6 @@ msgstr "BlendTypeKey" msgid "SingleGradationDecal:prop:TargetPropertyName" msgstr "TargetPropertyName" + +msgid "SingleGradationDecal:prop:GradientClamp" +msgstr "GradientClamp" diff --git a/Editor/Localize/ja_JP.po b/Editor/Localize/ja_JP.po index d1b859ed..e35943c5 100644 --- a/Editor/Localize/ja_JP.po +++ b/Editor/Localize/ja_JP.po @@ -442,3 +442,6 @@ msgstr "ブレンドタイプキー" msgid "SingleGradationDecal:prop:TargetPropertyName" msgstr "ターゲットプロパティネーム" + +msgid "SingleGradationDecal:prop:GradientClamp" +msgstr "グラデーションのクランプ" diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index c79f86f3..a27c09fe 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -28,6 +28,7 @@ public sealed class SingleGradationDecal : TexTransRuntimeBehavior public List TargetMaterials; public Gradient Gradient; [Range(0, 1)] public float Alpha = 1; + public bool GradientClamp = true; public AbstractIslandSelector IslandSelector; [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; public PropertyName TargetPropertyName = PropertyName.DefaultValue; @@ -41,9 +42,10 @@ internal override void Apply([NotNull] IDomain domain) var decalContext = new DecalContext(space, filter); decalContext.TargetPropertyName = TargetPropertyName; - decalContext.TextureWarp = TextureWrap.NotWrap; + decalContext.TextureWarp = GradientClamp ? TextureWrap.NotWrap : TextureWrap.Stretch; decalContext.NotContainsKeyAutoGenerate = false; + var writeable = new Dictionary(); decalContext.GenerateKey(writeable, targetMat); From 2f552fbd499cd4452c008a40e42fb5ffec7074ac Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:19:50 +0900 Subject: [PATCH 141/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 4067d258..3607d242 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -20,6 +20,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelectorRelayはキャンセルされました (#450) - RealTimePreview が大幅に改修され、MultiLayerImageCanvas もリアルタイムプレビュー可能になりました (#448) - SingleGradationDecal が追加されました (#449) + - オプション GradationClamp が追加 (#451) ### Changed From feb4b2d9e10c2fb4871adfca6d6deebea9fb947b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:44:06 +0900 Subject: [PATCH 142/208] chore: add NDMF Not Exist Warning --- Editor/NDMFNotExistWarning.meta | 8 ++++++ .../NDMFNotExistWarning.cs | 13 +++++++++ .../NDMFNotExistWarning.cs.meta | 11 ++++++++ ...s-tool.editor.ndmf-not-exist-waring.asmdef | 27 +++++++++++++++++++ ...l.editor.ndmf-not-exist-waring.asmdef.meta | 7 +++++ 5 files changed, 66 insertions(+) create mode 100644 Editor/NDMFNotExistWarning.meta create mode 100644 Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs create mode 100644 Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs.meta create mode 100644 Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef create mode 100644 Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef.meta diff --git a/Editor/NDMFNotExistWarning.meta b/Editor/NDMFNotExistWarning.meta new file mode 100644 index 00000000..04210752 --- /dev/null +++ b/Editor/NDMFNotExistWarning.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 13d1b1630aef13945af9184645530778 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs b/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs new file mode 100644 index 00000000..ce8419cc --- /dev/null +++ b/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs @@ -0,0 +1,13 @@ +using UnityEditor; +using UnityEngine; + +static class NDMFNotExistWarning +{ +#if ぶいちゃあばたー && !なでもふっっ + [InitializeOnLoadMethod] + static void Call() + { + Debug.LogWarning("NDMF が環境に存在しません!!! VRChat Avatar 用途では NDMF は必須なのでご注意ください!"); + } +#endif +} diff --git a/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs.meta b/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs.meta new file mode 100644 index 00000000..0a048f10 --- /dev/null +++ b/Editor/NDMFNotExistWarning/NDMFNotExistWarning.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 439b4e3c14954f249b7d7f8f5fce8cb1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef b/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef new file mode 100644 index 00000000..abfd2cb7 --- /dev/null +++ b/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef @@ -0,0 +1,27 @@ +{ + "name": "net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring", + "rootNamespace": "", + "references": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.vrchat.avatars", + "expression": "", + "define": "ぶいちゃあばたー" + }, + { + "name": "nadena.dev.ndmf", + "expression": "", + "define": "なでもふっっ" + } + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef.meta b/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef.meta new file mode 100644 index 00000000..2dd44845 --- /dev/null +++ b/Editor/NDMFNotExistWarning/net.rs64.tex-trans-tool.editor.ndmf-not-exist-waring.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 26100e7b254da494396b66edc6a99c0e +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: From c46c48434c3e627867886f1fe868754c383f6114 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 30 Apr 2024 20:45:51 +0900 Subject: [PATCH 143/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index af88e78d..63dbff75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - NDMF環境でのビルドを行う場合、オブジェクトの置き換えの追跡を NDMF ObjectRegistry を使用するようになりました (#438) - Clip系の合成モードが追加されました (#444) - SimpleDecal が高速化しました (#449) +- VRChat Avatar SDK が存在するときに NDMF が存在しない場合に警告を生成すようになりました (#452) ### Changed From 99786910d0e0911a78915c95906195a57471c54d Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 30 Apr 2024 11:51:52 +0000 Subject: [PATCH 144/208] Update package.json v0.7.0-beta.7!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index aed76aef..088d6ccc 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.6", + "version": "0.7.0-beta.7", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From dba62cf785e90ac6f3c4e81eb00717e9b0261686 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 12:11:59 +0900 Subject: [PATCH 145/208] chore:set icon --- Runtime/IslandSelect/IslandSelectorXOR.cs.meta | 2 +- Runtime/IslandSelect/SubMeshIslandSelector.cs.meta | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Runtime/IslandSelect/IslandSelectorXOR.cs.meta b/Runtime/IslandSelect/IslandSelectorXOR.cs.meta index 2b85ca71..45ad24a3 100644 --- a/Runtime/IslandSelect/IslandSelectorXOR.cs.meta +++ b/Runtime/IslandSelect/IslandSelectorXOR.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: diff --git a/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta b/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta index 97d1628a..b61b1d7a 100644 --- a/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta +++ b/Runtime/IslandSelect/SubMeshIslandSelector.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} userData: assetBundleName: assetBundleVariant: From f7194766e302d7d88e00ceeba23eb314d0f34811 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 12:13:04 +0900 Subject: [PATCH 146/208] chore: add DisallowMultipleComponent --- Runtime/IslandSelect/AbstructIslandSelector.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Runtime/IslandSelect/AbstructIslandSelector.cs b/Runtime/IslandSelect/AbstructIslandSelector.cs index 7020daf0..d513a433 100644 --- a/Runtime/IslandSelect/AbstructIslandSelector.cs +++ b/Runtime/IslandSelect/AbstructIslandSelector.cs @@ -8,6 +8,7 @@ namespace net.rs64.TexTransTool.IslandSelector { + [DisallowMultipleComponent] public abstract class AbstractIslandSelector : MonoBehaviour, ITexTransToolTag, IIslandSelector { internal const string FoldoutName = "IslandSelector"; From a8a1ee9ad2dfc54d695f5c9eaa5e76fc073d2ced Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 13:02:13 +0900 Subject: [PATCH 147/208] fix:name space --- Editor/Migration/V3/AtlasTextureV3.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/Migration/V3/AtlasTextureV3.cs b/Editor/Migration/V3/AtlasTextureV3.cs index b2847909..689481be 100644 --- a/Editor/Migration/V3/AtlasTextureV3.cs +++ b/Editor/Migration/V3/AtlasTextureV3.cs @@ -4,7 +4,7 @@ using UnityEditor; using UnityEngine; -namespace net.rs64.TexTransTool.Migration.V2 +namespace net.rs64.TexTransTool.Migration.V3 { [Obsolete] internal static class AtlasTextureV3 From 4b23ffc959479be1a370b1c0806a96b2109d66fd Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 13:02:35 +0900 Subject: [PATCH 148/208] chore: add SimpleDecalV3toV4 --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 16 +----- Editor/Migration/V3/SimpleDecalV3.cs | 63 +++++++++++++++++++++ Editor/Migration/V3/SimpleDecalV3.cs.meta | 11 ++++ 3 files changed, 76 insertions(+), 14 deletions(-) create mode 100644 Editor/Migration/V3/SimpleDecalV3.cs create mode 100644 Editor/Migration/V3/SimpleDecalV3.cs.meta diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index 4093bf9a..cfbe6b01 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -153,23 +153,11 @@ public void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) Undo.RecordObject(simpleDecal, "MigrateIslandCullingToIslandSelector"); simpleDecal.IslandCulling = false; - var islandSelector = simpleDecal.IslandSelector as RayCastIslandSelector; + var islandSelector = Migration.V3.SimpleDecalV3.GenerateIslandSelector(simpleDecal); - if (islandSelector == null) - { - var go = new GameObject("RayCastIslandSelector"); - go.transform.SetParent(simpleDecal.transform, false); - simpleDecal.IslandSelector = islandSelector = go.AddComponent(); - } Undo.RecordObject(islandSelector, "MigrateIslandCullingToIslandSelector - islandSelectorEdit"); - - Vector3 selectorOrigin = new Vector2(simpleDecal.IslandSelectorPos.x - 0.5f, simpleDecal.IslandSelectorPos.y - 0.5f); - - - var ltwMatrix = simpleDecal.transform.localToWorldMatrix; - islandSelector.transform.position = ltwMatrix.MultiplyPoint3x4(selectorOrigin); - islandSelector.IslandSelectorRange = simpleDecal.IslandSelectorRange; + Migration.V3.SimpleDecalV3.SetIslandSelectorTransform(simpleDecal, islandSelector); } diff --git a/Editor/Migration/V3/SimpleDecalV3.cs b/Editor/Migration/V3/SimpleDecalV3.cs new file mode 100644 index 00000000..89cb233c --- /dev/null +++ b/Editor/Migration/V3/SimpleDecalV3.cs @@ -0,0 +1,63 @@ +using System; +using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransTool.Decal; +using net.rs64.TexTransTool.IslandSelector; +using UnityEditor; +using UnityEngine; + +namespace net.rs64.TexTransTool.Migration.V3 +{ + [Obsolete] + internal static class SimpleDecalV3 + { + + public static void MigrationSimpleDecalV3ToV4(SimpleDecal simpleDecal) + { + if (simpleDecal == null) { Debug.LogWarning("マイグレーションターゲットが存在しません。"); return; } + if (simpleDecal is ITexTransToolTag TTTag && TTTag.SaveDataVersion > 4) { Debug.Log(simpleDecal.name + " SimpleDecal : マイグレーション不可能なバージョンです。"); return; } + + MigrateIslandCullingToIslandSelector(simpleDecal); + + if (simpleDecal.PolygonCulling != TexTransCore.Decal.PolygonCulling.Vertex) { simpleDecal.PolygonOutOfCulling = false; } + + EditorUtility.SetDirty(simpleDecal); + MigrationUtility.SetSaveDataVersion(simpleDecal, 4); + } + + + [Obsolete] + public static void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) + { + simpleDecal.IslandCulling = false; + + RayCastIslandSelector islandSelector = GenerateIslandSelector(simpleDecal); + + SetIslandSelectorTransform(simpleDecal, islandSelector); + + } + + public static RayCastIslandSelector GenerateIslandSelector(SimpleDecal simpleDecal) + { + var islandSelector = simpleDecal.IslandSelector as RayCastIslandSelector; + + if (islandSelector == null) + { + var go = new GameObject("RayCastIslandSelector"); + go.transform.SetParent(simpleDecal.transform, false); + simpleDecal.IslandSelector = islandSelector = go.AddComponent(); + } + + return islandSelector; + } + + public static void SetIslandSelectorTransform(SimpleDecal simpleDecal, RayCastIslandSelector islandSelector) + { + Vector3 selectorOrigin = new Vector2(simpleDecal.IslandSelectorPos.x - 0.5f, simpleDecal.IslandSelectorPos.y - 0.5f); + + + var ltwMatrix = simpleDecal.transform.localToWorldMatrix; + islandSelector.transform.position = ltwMatrix.MultiplyPoint3x4(selectorOrigin); + islandSelector.IslandSelectorRange = simpleDecal.IslandSelectorRange; + } + } +} diff --git a/Editor/Migration/V3/SimpleDecalV3.cs.meta b/Editor/Migration/V3/SimpleDecalV3.cs.meta new file mode 100644 index 00000000..b88a326e --- /dev/null +++ b/Editor/Migration/V3/SimpleDecalV3.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a85ef38a8408ab4ca82699ade9c4e83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From fc36c8d513816c4c2db5b4dfa706e387382ac77f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 16:16:18 +0900 Subject: [PATCH 149/208] fix: namespace and 3to4 migration --- Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs | 2 +- Editor/Migration/Migrator.cs | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 0f0693a8..4e4cd1a8 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -39,7 +39,7 @@ public override void OnInspectorGUI() } if (TTTag.SaveDataVersion == 3 && GUILayout.Button("Migrate DSV3 To DSV4")) { - net.rs64.TexTransTool.Migration.V2.AtlasTextureV3.MigrationAtlasTextureV3ToV4(thisTarget); + net.rs64.TexTransTool.Migration.V3.AtlasTextureV3.MigrationAtlasTextureV3ToV4(thisTarget); } return; } diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index 03ea98f7..0c38ace2 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -7,6 +7,7 @@ using net.rs64.TexTransTool.Migration.V0; using net.rs64.TexTransTool.Migration.V1; using net.rs64.TexTransTool.Migration.V2; +using net.rs64.TexTransTool.Migration.V3; using net.rs64.TexTransTool.TextureAtlas; using UnityEditor; using UnityEditor.PackageManager; @@ -43,6 +44,11 @@ public static bool MigrationITexTransToolTagV3ToV4(ITexTransToolTag texTransTool AtlasTextureV3.MigrationAtlasTextureV3ToV4(atlasTexture); return true; } + case SimpleDecal simpleDecal: + { + SimpleDecalV3.MigrationSimpleDecalV3ToV4(simpleDecal); + return true; + } default: { From fb69e0709a504f66d63d73c17e7758d4b78ca521 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 16:59:27 +0900 Subject: [PATCH 150/208] chore: Multiple IslandCulling migrations --- Editor/Inspector/Decal/SimpleDecalEditor.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Editor/Inspector/Decal/SimpleDecalEditor.cs b/Editor/Inspector/Decal/SimpleDecalEditor.cs index cfbe6b01..fb4e24de 100644 --- a/Editor/Inspector/Decal/SimpleDecalEditor.cs +++ b/Editor/Inspector/Decal/SimpleDecalEditor.cs @@ -5,6 +5,7 @@ using UnityEditor.UIElements; using net.rs64.TexTransTool.IslandSelector; using System; +using System.Collections.Generic; namespace net.rs64.TexTransTool.Editor.Decal { @@ -56,7 +57,7 @@ public override void OnInspectorGUI() if (sIslandCulling.boolValue && GUILayout.Button("Migrate IslandCulling to IslandSelector")) { #pragma warning disable CS0612 - MigrateIslandCullingToIslandSelector(thisObject); + MigrateIslandCullingToIslandSelector(targets); #pragma warning restore CS0612 } } @@ -142,6 +143,17 @@ internal static void RegisterSummary() }; } + [Obsolete] + public void MigrateIslandCullingToIslandSelector(IEnumerable simpleDecals) + { + foreach (var uo in simpleDecals) + { + if (uo is SimpleDecal simpleDecal) + { + MigrateIslandCullingToIslandSelector(simpleDecal); + } + } + } [Obsolete] public void MigrateIslandCullingToIslandSelector(SimpleDecal simpleDecal) { From 42fd42bf472826c737143311b58057a7e6421148 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 18:09:33 +0900 Subject: [PATCH 151/208] remove: MatAndTexSeparator --- .../MatAndTexSeparatorProcessor.cs | 82 ----------- .../MatAndTexSeparatorProcessor.cs.meta | 11 -- Editor/Inspector/MatAndTexUtils.meta | 8 -- .../MatAndTexAbsoluteSeparatorEditor.cs | 128 ------------------ .../MatAndTexAbsoluteSeparatorEditor.cs.meta | 11 -- .../MatAndTexRelativeSeparatorEditor.cs | 77 ----------- .../MatAndTexRelativeSeparatorEditor.cs.meta | 11 -- .../MatAndTexUtils/MaterialModifierEditor.cs | 90 ------------ .../MaterialModifierEditor.cs.meta | 11 -- Editor/Inspector/TexTransGroupEditor.cs | 7 - Editor/Migration/V0/AbstractDecalV0.cs | 53 +------- .../NewGameObjectAndAddTTTComponent.cs | 5 - Runtime/CommonComponent/MatAndTexUtils.meta | 8 -- .../MatAndTexAbsoluteSeparator.cs | 47 ------- .../MatAndTexAbsoluteSeparator.cs.meta | 11 -- .../MatAndTexRelativeSeparator.cs | 42 ------ .../MatAndTexRelativeSeparator.cs.meta | 11 -- .../MatAndTexUtils/MaterialModifier.cs | 109 --------------- .../MatAndTexUtils/MaterialModifier.cs.meta | 11 -- Runtime/Decal/SimpleDecal.cs | 2 +- 20 files changed, 2 insertions(+), 733 deletions(-) delete mode 100644 Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs delete mode 100644 Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs.meta delete mode 100644 Editor/Inspector/MatAndTexUtils.meta delete mode 100644 Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs delete mode 100644 Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs.meta delete mode 100644 Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs delete mode 100644 Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs.meta delete mode 100644 Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs delete mode 100644 Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs.meta delete mode 100644 Runtime/CommonComponent/MatAndTexUtils.meta delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs.meta delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs.meta delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs delete mode 100644 Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs.meta diff --git a/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs b/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs deleted file mode 100644 index e9f87de1..00000000 --- a/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections.Generic; -using net.rs64.TexTransTool.MatAndTexUtils; -using net.rs64.TexTransTool.Utils; -using UnityEditor; -using UnityEngine; - -namespace net.rs64.TexTransTool.EditorProcessor -{ - [EditorProcessor(typeof(MatAndTexAbsoluteSeparator))] - [EditorProcessor(typeof(MatAndTexRelativeSeparator))] - internal class MatAndTexSeparatorProcessor : IEditorProcessor - { - public void Process(TexTransCallEditorBehavior texTransCallEditorBehavior, IEditorCallDomain editorCallDomain) - { - var separator = texTransCallEditorBehavior as IMatAndTexSeparator; - var separatedMaterials = new Dictionary(); - var separatedTextures = new Dictionary(); - - var rendererIndex = 0; - foreach (var renderer in texTransCallEditorBehavior.GetRenderers) - { - var slotIndex = 0; - - var separateTargetRenderer = separator.GetSeparateTarget(editorCallDomain, rendererIndex); - - if (renderer == null) { continue; } - using (var serialized = new SerializedObject(renderer)) - { - foreach (SerializedProperty property in serialized.FindProperty("m_Materials")) - { - if (property.objectReferenceValue is Material material && material != null && separateTargetRenderer.Count > slotIndex && separateTargetRenderer[slotIndex]) - { - - if (!separatedMaterials.TryGetValue(material, out var separatedMaterial)) - { - separatedMaterial = UnityEngine.Object.Instantiate(material); - separatedMaterials.Add(material, separatedMaterial); - } - editorCallDomain.SetSerializedProperty(property, separatedMaterial); - - } - - slotIndex += 1; - } - - serialized.ApplyModifiedPropertiesWithoutUndo(); - } - - rendererIndex += 1; - } - - if (separator.IsTextureSeparate) - { - foreach (var separatedMaterial in separatedMaterials.Values) - { - var propertyName = separator.PropertyName.ToString(); - if ( - separatedMaterial.HasProperty(propertyName) && - separatedMaterial.GetTexture(propertyName) is Texture2D texture2D && - texture2D != null - ) - { - if (separatedTextures.ContainsKey(texture2D)) - { - separatedMaterial.SetTexture(propertyName, separatedTextures[texture2D]); - } - else - { - var separatedTexture = texture2D.CloneTexture2D(); - separatedMaterial.SetTexture(propertyName, separatedTexture); - separatedTextures.Add(texture2D, separatedTexture); - } - } - } - } - - editorCallDomain.transferAssets(separatedMaterials.Values); - editorCallDomain.transferAssets(separatedTextures.Values); - - } - } -} diff --git a/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs.meta b/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs.meta deleted file mode 100644 index ebac5630..00000000 --- a/Editor/EditorProcessor/MatAndTexSeparatorProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 125858b718500b5479112e59785658a7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/MatAndTexUtils.meta b/Editor/Inspector/MatAndTexUtils.meta deleted file mode 100644 index ab723928..00000000 --- a/Editor/Inspector/MatAndTexUtils.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3efa8f5b41b405d4d923d250f575282d -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs b/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs deleted file mode 100644 index be9f039c..00000000 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransTool.MatAndTexUtils; -using net.rs64.TexTransTool.Preview; -using UnityEditor; -using UnityEngine; - -namespace net.rs64.TexTransTool.Editor.MatAndTexUtils -{ - [UnityEditor.CustomEditor(typeof(MatAndTexAbsoluteSeparator))] - internal class MatAndTexAbsoluteSeparatorEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("MatAndTexAbsoluteSeparator"); - - var thisSObject = serializedObject; - var thisObject = target as MatAndTexAbsoluteSeparator; - - EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); - - var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); - var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); - TextureTransformerEditor.DrawerRenderer(sTargetRenderers, "CommonDecal:prop:TargetRenderer".Glc(), sMultiRendererMode.boolValue); - EditorGUILayout.PropertyField(sMultiRendererMode); - - if (_tempMaterial == null || GUILayout.Button("Refresh Materials")) { RefreshMaterials(sTargetRenderers, ref _tempMaterial); } - var sSeparateTarget = thisSObject.FindProperty("SeparateTarget"); - MaterialSelectEditor(sSeparateTarget, _tempMaterial); - - if (thisObject.SeparateTarget.Any(I => I == null)) { Undo.RecordObject(thisObject, "SeparateTarget Remove Null"); thisObject.SeparateTarget.RemoveAll(I => I == null); } - - var sIsTextureSeparate = thisSObject.FindProperty("IsTextureSeparate"); - EditorGUILayout.PropertyField(sIsTextureSeparate); - - var sPropertyName = thisSObject.FindProperty("PropertyName"); - EditorGUILayout.PropertyField(sPropertyName); - - - EditorGUI.EndDisabledGroup(); - - OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); - - thisSObject.ApplyModifiedProperties(); - } - - List _tempMaterial; - public static void RefreshMaterials(SerializedProperty sTargetRenderers, ref List tempMaterial) - { - var renderer = new List(); - for (var i = 0; sTargetRenderers.arraySize > i; i += 1) - { - var rendererValue = sTargetRenderers.GetArrayElementAtIndex(i).objectReferenceValue as Renderer; - if (rendererValue != null) { renderer.Add(rendererValue); } - } - tempMaterial = RendererUtility.GetMaterials(renderer).Distinct().ToList(); - } - - public static void MaterialSelectEditor(SerializedProperty targetMaterials, List tempMaterial, string Label = "Separate? Material") - { - EditorGUI.indentLevel += 1; - GUILayout.Label(Label); - foreach (var mat in tempMaterial) - { - var sMatSelector = FindMatSelector(targetMaterials, mat); - EditorGUILayout.BeginHorizontal(); - - var isTarget = sMatSelector != null; - - var editIsTarget = EditorGUILayout.Toggle(isTarget); - if (isTarget != editIsTarget) - { - if (editIsTarget) - { - var index = targetMaterials.arraySize; - targetMaterials.arraySize += 1; - targetMaterials.GetArrayElementAtIndex(index).objectReferenceValue = mat; - } - else - { - targetMaterials.DeleteArrayElementAtIndex(FindMatSelectorIndex(targetMaterials, mat)); - } - } - - - EditorGUI.BeginDisabledGroup(true); - EditorGUILayout.ObjectField(mat, typeof(Material), false, GUILayout.MaxWidth(1000)); - EditorGUI.EndDisabledGroup(); - EditorGUILayout.EndHorizontal(); - } - EditorGUI.indentLevel -= 1; - - } - public static SerializedProperty FindMatSelector(SerializedProperty targetMaterialArray, Material material) - { - for (int i = 0; targetMaterialArray.arraySize > i; i += 1) - { - var materialElement = targetMaterialArray.GetArrayElementAtIndex(i); - if (materialElement.objectReferenceValue == material) - { - return materialElement; - } - } - return null; - } - public static int FindMatSelectorIndex(SerializedProperty targetMaterialArray, Material material) - { - for (int i = 0; targetMaterialArray.arraySize > i; i += 1) - { - var materialElement = targetMaterialArray.GetArrayElementAtIndex(i); - if (materialElement.objectReferenceValue == material) - { - return i; - } - } - return -1; - } - - public static void DrawerSummary(MatAndTexAbsoluteSeparator target) - { - var sObj = new SerializedObject(target); - var sTargetRenderers = sObj.FindProperty("TargetRenderers"); - TextureTransformerEditor.DrawerTargetRenderersSummary(sTargetRenderers,sTargetRenderers.name.Glc()); - sObj.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs.meta b/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs.meta deleted file mode 100644 index 0d072a9a..00000000 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexAbsoluteSeparatorEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 741b8499a5a65074a9af77c04dd5475c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs b/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs deleted file mode 100644 index e5c3a369..00000000 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs +++ /dev/null @@ -1,77 +0,0 @@ -using net.rs64.TexTransTool.MatAndTexUtils; -using net.rs64.TexTransTool.Preview; -using UnityEditor; -using UnityEngine; - -namespace net.rs64.TexTransTool.Editor.MatAndTexUtils -{ - [UnityEditor.CustomEditor(typeof(MatAndTexRelativeSeparator))] - internal class MatAndTexRelativeSeparatorEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("MatAndTexRelativeSeparator"); - - var thisSObject = serializedObject; - var thisObject = target as MatAndTexRelativeSeparator; - - EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); - - var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); - var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); - TextureTransformerEditor.DrawerRenderer(sTargetRenderers, "CommonDecal:prop:TargetRenderer".Glc(), sMultiRendererMode.boolValue); - EditorGUILayout.PropertyField(sMultiRendererMode); - - var sSeparateTarget = thisSObject.FindProperty("SeparateTarget"); - if (sSeparateTarget.arraySize != thisObject.TargetRenderers.Count) { sSeparateTarget.arraySize = thisObject.TargetRenderers.Count; } - - EditorGUILayout.LabelField("---"); - - int rendererIndex = 0; - foreach (var renderer in thisObject.TargetRenderers) - { - if (renderer == null) { continue; } - var sSelectRd = sSeparateTarget.GetArrayElementAtIndex(rendererIndex).FindPropertyRelative("Bools"); - var materials = renderer.sharedMaterials; - if (sSelectRd.arraySize != materials.Length) { sSelectRd.arraySize = materials.Length; } - int slotIndex = 0; - foreach (var MatSlot in materials) - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PropertyField(sSelectRd.GetArrayElementAtIndex(slotIndex)); - EditorGUI.BeginDisabledGroup(true); - EditorGUILayout.ObjectField(MatSlot, typeof(Material), true); - EditorGUI.EndDisabledGroup(); - EditorGUILayout.EndHorizontal(); - slotIndex += 1; - } - rendererIndex += 1; - - EditorGUILayout.LabelField("---"); - } - - var sIsTextureSeparate = thisSObject.FindProperty("IsTextureSeparate"); - EditorGUILayout.PropertyField(sIsTextureSeparate); - - var sPropertyName = thisSObject.FindProperty("PropertyName"); - EditorGUILayout.PropertyField(sPropertyName); - - - EditorGUI.EndDisabledGroup(); - - OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); - - thisSObject.ApplyModifiedProperties(); - } - - - - public static void DrawerSummary(MatAndTexRelativeSeparator target) - { - var sObj = new SerializedObject(target); - var sTargetRenderers = sObj.FindProperty("TargetRenderers"); - TextureTransformerEditor.DrawerTargetRenderersSummary(sTargetRenderers, sTargetRenderers.name.Glc()); - sObj.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs.meta b/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs.meta deleted file mode 100644 index ff892125..00000000 --- a/Editor/Inspector/MatAndTexUtils/MatAndTexRelativeSeparatorEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1b7d42b7f53702f48b11ea4c79b5820d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs b/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs deleted file mode 100644 index de4d3741..00000000 --- a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs +++ /dev/null @@ -1,90 +0,0 @@ -using UnityEngine; -using UnityEditor; -using net.rs64.TexTransTool.MatAndTexUtils; -using System.Collections.Generic; -using net.rs64.TexTransTool.Preview; -namespace net.rs64.TexTransTool.Editor.MatAndTexUtils -{ - [CustomEditor(typeof(MaterialModifier))] - internal class MaterialModifierEditor : UnityEditor.Editor - { - List _tempMaterial; - public override void OnInspectorGUI() - { - TextureTransformerEditor.DrawerWarning("MaterialModifier"); - - var thisSObject = serializedObject; - var thisObject = target as MaterialModifier; - - EditorGUI.BeginDisabledGroup(OneTimePreviewContext.IsPreviewing(thisObject)); - - - var sTargetRenderers = thisSObject.FindProperty("TargetRenderers"); - var sMultiRendererMode = thisSObject.FindProperty("MultiRendererMode"); - TextureTransformerEditor.DrawerRenderer(sTargetRenderers, "CommonDecal:prop:TargetRenderer".Glc(), sMultiRendererMode.boolValue); - EditorGUILayout.PropertyField(sMultiRendererMode); - - if (_tempMaterial == null || GUILayout.Button("Refresh Materials")) { MatAndTexAbsoluteSeparatorEditor.RefreshMaterials(sTargetRenderers, ref _tempMaterial); } - var sModifiedTarget = thisSObject.FindProperty("ModifiedTarget"); - MatAndTexAbsoluteSeparatorEditor.MaterialSelectEditor(sModifiedTarget, _tempMaterial, "Target? Material"); - - - EditorGUILayout.LabelField("Modify Settings", EditorStyles.boldLabel); - - var sChangeList = thisSObject.FindProperty("ChangeList"); - EditorGUILayout.PropertyField(sChangeList); - - - EditorGUI.EndDisabledGroup(); - - OneTimePreviewContext.instance.DrawApplyAndRevert(thisObject); - thisSObject.ApplyModifiedProperties(); - } - } - - - [CustomPropertyDrawer(typeof(MaterialModifier.MatMod))] - public class MatModDrawer : PropertyDrawer - { - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) - { - var sChange = property; - var sModTypeEnum = sChange.FindPropertyRelative("ModType"); - position.height = 18; - EditorGUI.PropertyField(position, sModTypeEnum); - position.y += position.height; - switch (sModTypeEnum.enumValueIndex) - { - case 0://Float - { - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Float_PropertyName")); - position.y += position.height; - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Float_Value")); - position.y += position.height; - break; - } - case 1://Texture - { - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Texture_Value")); - position.y += position.height; - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Texture_PropertyName")); - position.y += position.height; - break; - } - case 2://Color - { - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Color_PropertyName")); - position.y += position.height; - EditorGUI.PropertyField(position, sChange.FindPropertyRelative("Color_Value")); - position.y += position.height; - break; - } - } - } - - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) - { - return 18 * 3; - } - } -} diff --git a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs.meta b/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs.meta deleted file mode 100644 index 2304e4c5..00000000 --- a/Editor/Inspector/MatAndTexUtils/MaterialModifierEditor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bcfab284d303bdc4a9e03caa472891c2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Inspector/TexTransGroupEditor.cs b/Editor/Inspector/TexTransGroupEditor.cs index 74c7a33c..41ae7099 100644 --- a/Editor/Inspector/TexTransGroupEditor.cs +++ b/Editor/Inspector/TexTransGroupEditor.cs @@ -1,12 +1,5 @@ using UnityEngine; using UnityEditor; -using net.rs64.TexTransTool.Decal; -using net.rs64.TexTransTool.Editor.Decal; -using net.rs64.TexTransTool.MatAndTexUtils; -using net.rs64.TexTransTool.Editor.MatAndTexUtils; -using net.rs64.TexTransTool.TextureAtlas; -using net.rs64.TexTransTool.TextureAtlas.Editor; -using net.rs64.TexTransTool.Utils; using UnityEngine.UIElements; using System.Collections.Generic; using System; diff --git a/Editor/Migration/V0/AbstractDecalV0.cs b/Editor/Migration/V0/AbstractDecalV0.cs index b48db250..b2893772 100644 --- a/Editor/Migration/V0/AbstractDecalV0.cs +++ b/Editor/Migration/V0/AbstractDecalV0.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using net.rs64.TexTransTool.Decal; -using net.rs64.TexTransTool.MatAndTexUtils; using UnityEditor; using UnityEngine; @@ -20,27 +19,6 @@ public static void MigrationAbstractDecalV0ToV1(SimpleDecal abstractDecal) if (abstractDecal.MigrationV0DataAbstractDecal != null) { - if (abstractDecal.IsSeparateMatAndTexture) - { - if (abstractDecal.MigrationV0DataMatAndTexSeparator == null) - { - var NewSeparator = abstractDecal.MigrationV0DataMatAndTexSeparatorGameObject.AddComponent(); - SetUpSeparator(NewSeparator, abstractDecal); - abstractDecal.MigrationV0DataMatAndTexSeparator = NewSeparator; - } - else - { - SetUpSeparator(abstractDecal.MigrationV0DataMatAndTexSeparator, abstractDecal); - } - } - else - { - if (abstractDecal.MigrationV0DataMatAndTexSeparator != null) - { - UnityEngine.Object.DestroyImmediate(abstractDecal.MigrationV0DataMatAndTexSeparator); - abstractDecal.MigrationV0DataMatAndTexSeparator = null; - } - } abstractDecal.MigrationV0DataAbstractDecal.CopyFromDecal(abstractDecal); abstractDecal.MigrationV0DataAbstractDecal.MigrationV0ClearTarget = false; abstractDecal.MigrationV0DataAbstractDecal.IsSeparateMatAndTexture = false; @@ -53,8 +31,7 @@ public static void MigrationAbstractDecalV0ToV1(SimpleDecal abstractDecal) var newGameObjectSeparator = new GameObject("Separator"); newGameObjectSeparator.transform.parent = GameObject.transform; - var NewSeparator = newGameObjectSeparator.AddComponent(); - SetUpSeparator(NewSeparator, abstractDecal); + var newGameObjectDecal = new GameObject("Decal"); newGameObjectDecal.transform.parent = GameObject.transform; @@ -64,13 +41,10 @@ public static void MigrationAbstractDecalV0ToV1(SimpleDecal abstractDecal) NewDecal.IsSeparateMatAndTexture = false; NewDecal.MigrationV0ClearTarget = false; NewDecal.MigrationV0DataAbstractDecal = null; - NewDecal.MigrationV0DataMatAndTexSeparator = null; NewDecal.MigrationV0DataMatAndTexSeparatorGameObject = null; EditorUtility.SetDirty(NewDecal); abstractDecal.MigrationV0DataAbstractDecal = NewDecal; - abstractDecal.MigrationV0DataMatAndTexSeparator = NewSeparator; - abstractDecal.MigrationV0DataMatAndTexSeparatorGameObject = NewSeparator.gameObject; abstractDecal.MigrationV0ClearTarget = true; } @@ -94,31 +68,6 @@ public static void FinalizeMigrationAbstractDecalV0ToV1(SimpleDecal abstractDeca } } - static void SetUpSeparator(MatAndTexUtils.MatAndTexRelativeSeparator matAndTexSeparator, SimpleDecal abstractDecal) - { - if (abstractDecal.TargetRenderers != null) - { - matAndTexSeparator.TargetRenderers = abstractDecal.TargetRenderers; - var separateTarget = new List(); - for (int rd = 0; abstractDecal.TargetRenderers.Count > rd; rd += 1) - { - var boolList = new List(); - var renderer = abstractDecal.TargetRenderers[rd]; - if (renderer == null) { continue; } - var materials = renderer.sharedMaterials; - for (int ms = 0; materials.Length > ms; ms += 1) - { - boolList.Add(true); - } - separateTarget.Add(new MatSlotBool(boolList)); - } - matAndTexSeparator.SeparateTarget = separateTarget; - } - matAndTexSeparator.IsTextureSeparate = true; - matAndTexSeparator.PropertyName = abstractDecal.TargetPropertyName; - - EditorUtility.SetDirty(matAndTexSeparator); - } static void CopyFromDecal(this SimpleDecal target, SimpleDecal copySouse) { diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index a3ad1269..05f95df9 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -1,6 +1,5 @@ using net.rs64.TexTransTool.Decal; using net.rs64.TexTransTool.IslandSelector; -using net.rs64.TexTransTool.MatAndTexUtils; using net.rs64.TexTransTool.MultiLayerImage; using net.rs64.TexTransTool.TextureAtlas; using UnityEditor; @@ -38,10 +37,6 @@ static void C() where TTB : MonoBehaviour [M(BP + PreviewGroup.MenuPath)] static void PG() => C(); - [M(BP + MatAndTexAbsoluteSeparator.MenuPath)] static void MATAS() => C(); - [M(BP + MatAndTexRelativeSeparator.MenuPath)] static void MATRS() => C(); - [M(BP + MaterialModifier.MenuPath)] static void MM() => C(); - [M(BP + BoxIslandSelector.MenuPath)] static void BIS() => C(); [M(BP + SphereIslandSelector.MenuPath)] static void SIS() => C(); [M(BP + RayCastIslandSelector.MenuPath)] static void RCIS() => C(); diff --git a/Runtime/CommonComponent/MatAndTexUtils.meta b/Runtime/CommonComponent/MatAndTexUtils.meta deleted file mode 100644 index b458c06f..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: e095e97d2aea4f744a7d309f37f02a8c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs deleted file mode 100644 index 2ba617b3..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs +++ /dev/null @@ -1,47 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -using net.rs64.TexTransCore.TransTextureCore.Utils; - -namespace net.rs64.TexTransTool.MatAndTexUtils -{ - [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class MatAndTexAbsoluteSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator - { - internal const string FoldoutName = "MatAndTexUtils"; - internal const string ComponentName = "TTT MatAndTexAbsoluteSeparator"; - internal const string MenuPath = FoldoutName + "/" + ComponentName; - public List TargetRenderers = new List { null }; - public bool MultiRendererMode = false; - internal override List GetRenderers => TargetRenderers; - - internal override bool IsPossibleApply => SeparateTarget.Any(); - - internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; - - public List SeparateTarget = new List(); - public bool IsTextureSeparate; - public PropertyName PropertyName = PropertyName.DefaultValue; - - bool IMatAndTexSeparator.IsTextureSeparate => IsTextureSeparate; - PropertyName IMatAndTexSeparator.PropertyName => PropertyName; - - List IMatAndTexSeparator.GetSeparateTarget(IDomain domain, int RendererIndex) - { - var renderer = TargetRenderers[RendererIndex]; - - var hashSet = new HashSet(renderer.sharedMaterials); - var targetMats = hashSet.Where(i => SeparateTarget.Any(m => domain.OriginEqual(m, i))).ToList(); - - return renderer.sharedMaterials.Select(m => targetMats.Contains(m)).ToList(); - } - } - - internal interface IMatAndTexSeparator - { - bool IsTextureSeparate { get; } - PropertyName PropertyName { get; } - List GetSeparateTarget(IDomain domain, int RendererIndex); - } -} diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs.meta b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs.meta deleted file mode 100644 index 7385849b..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexAbsoluteSeparator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f289d49e2c9578d4bb401c62cf77c653 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs deleted file mode 100644 index e59f347e..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs +++ /dev/null @@ -1,42 +0,0 @@ -using UnityEngine; -using System.Collections.Generic; -using System.Linq; -using System; - -namespace net.rs64.TexTransTool.MatAndTexUtils -{ - [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class MatAndTexRelativeSeparator : TexTransCallEditorBehavior, IMatAndTexSeparator - { - internal const string ComponentName = "TTT MatAndTexRelativeSeparator"; - internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; - public List TargetRenderers = new List { null }; - public bool MultiRendererMode = false; - internal override List GetRenderers => TargetRenderers; - internal override bool IsPossibleApply => SeparateTarget.Any(); - internal List SeparateTarget = new List(); - public bool IsTextureSeparate; - public PropertyName PropertyName = PropertyName.DefaultValue; - - internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; - - bool IMatAndTexSeparator.IsTextureSeparate => IsTextureSeparate; - PropertyName IMatAndTexSeparator.PropertyName => PropertyName; - - List IMatAndTexSeparator.GetSeparateTarget(IDomain domain, int RendererIndex) - { - return SeparateTarget[RendererIndex].BoolList; - } - } - [Serializable] - internal class MatSlotBool - { - public List BoolList; - - public MatSlotBool(List boolList) - { - BoolList = boolList; - } - - } -} diff --git a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs.meta b/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs.meta deleted file mode 100644 index ae229d10..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MatAndTexRelativeSeparator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eb6c1741152397a43a7fb9eec92ce212 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs deleted file mode 100644 index 6f5f2b37..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using JetBrains.Annotations; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using UnityEngine; - -namespace net.rs64.TexTransTool.MatAndTexUtils -{ - [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public class MaterialModifier : TexTransRuntimeBehavior - { - internal const string ComponentName = "TTT MaterialModifier"; - internal const string MenuPath = MatAndTexAbsoluteSeparator.FoldoutName + "/" + ComponentName; - public List TargetRenderers = new List { null }; - public bool MultiRendererMode = false; - internal override List GetRenderers => TargetRenderers; - internal override bool IsPossibleApply => TargetRenderers.Any(i => i != null); - public List ModifiedTarget = new List(); - - public List ChangeList = new List(); - [Serializable] - public class MatMod - { - public ModTypeEnum ModType; - public enum ModTypeEnum - { - Float, - Texture, - Color, - } - - public string Float_PropertyName; - public float Float_Value; - - - public PropertyName Texture_PropertyName = PropertyName.DefaultValue; - public Texture Texture_Value; - - - public string Color_PropertyName; - public Color Color_Value; - - public void Modified(Material material) - { - switch (ModType) - { - case ModTypeEnum.Float: - { - if (!material.HasProperty(Float_PropertyName)) { break; } - material.SetFloat(Float_PropertyName, Float_Value); - break; - } - case ModTypeEnum.Texture: - { - if (!material.HasProperty(Texture_PropertyName)) { break; } - material.SetTexture(Texture_PropertyName, Texture_Value); - break; - } - case ModTypeEnum.Color: - { - if (!material.HasProperty(Color_PropertyName)) { break; } - material.SetColor(Color_PropertyName, Color_Value); - break; - } - } - } - - } - internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; - - internal override void Apply([NotNull] IDomain domain) - { - if (!IsPossibleApply) { throw new TTTNotExecutable(); } - - var modMatList = new Dictionary(); - - var hashSet = new HashSet(RendererUtility.GetMaterials(GetRenderers)); - var containedModTarget = hashSet.Where(i => ModifiedTarget.Any(m => domain.OriginEqual(m, i))).ToList(); - - foreach (var modTarget in containedModTarget) - { - var newMat = Instantiate(modTarget); - modMatList.Add(modTarget, newMat); - foreach (var Modified in ChangeList) - { - Modified.Modified(newMat); - } - } - domain.ReplaceMaterials(modMatList); - } - - internal override IEnumerable GetDependency(IDomain domain) - { - foreach (var i in ModifiedTarget) { yield return i; } - foreach (var i in TargetRenderers) { yield return i; } - } - - internal override int GetDependencyHash(IDomain domain) - { - var hash = 0; - foreach (var tr in TargetRenderers) - { - hash ^= tr?.GetInstanceID() ?? 0; - } - return hash; - } - } -} diff --git a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs.meta b/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs.meta deleted file mode 100644 index a22c9656..00000000 --- a/Runtime/CommonComponent/MatAndTexUtils/MaterialModifier.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9d0a07a83c401b24c92f1649fc5ad1ae -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 79114312..dcf34b5e 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -52,7 +52,7 @@ public sealed class SimpleDecal : TexTransRuntimeBehavior//AbstractSingleDecal

Date: Wed, 1 May 2024 18:09:53 +0900 Subject: [PATCH 152/208] feat: MaterialOverrideTransfer.cs --- .../MaterialOverrideTransfer.cs | 101 ++++++++++++++++++ .../MaterialOverrideTransfer.cs.meta | 11 ++ 2 files changed, 112 insertions(+) create mode 100644 Runtime/CommonComponent/MaterialOverrideTransfer.cs create mode 100644 Runtime/CommonComponent/MaterialOverrideTransfer.cs.meta diff --git a/Runtime/CommonComponent/MaterialOverrideTransfer.cs b/Runtime/CommonComponent/MaterialOverrideTransfer.cs new file mode 100644 index 00000000..818a243a --- /dev/null +++ b/Runtime/CommonComponent/MaterialOverrideTransfer.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using System.Linq; +using JetBrains.Annotations; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using UnityEngine; +using UnityEngine.Rendering; + +namespace net.rs64.TexTransTool +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public sealed class MaterialOverrideTransfer : TexTransRuntimeBehavior + { + internal const string Name = "TTT MaterialOverrideTransfer"; + internal const string FoldoutName = "Other"; + internal const string MenuPath = FoldoutName + "/" + Name; + + internal override List GetRenderers => null; + + internal override bool IsPossibleApply => TargetMaterial != null && MaterialVariantSource != null && MaterialVariantSource.isVariant; + + internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; + + public Material TargetMaterial; + public Material MaterialVariantSource; + + internal override void Apply([NotNull] IDomain domain) + { + if (!IsPossibleApply) { throw new TTTNotExecutable(); } + + var mats = RendererUtility.GetFilteredMaterials(domain.EnumerateRenderer()).Where(m => domain.OriginEqual(m, TargetMaterial)); + + var overridePropertyDict = new Dictionary(); + var shader = MaterialVariantSource.shader; + var pCount = shader.GetPropertyCount(); + for (var i = 0; pCount > i; i += 1) + { + var propertyName = shader.GetPropertyName(i); + if (MaterialVariantSource.IsPropertyOverriden(propertyName)) { overridePropertyDict.Add(propertyName, shader.GetPropertyType(i)); } + } + + var materialSwapDict = new Dictionary(); + foreach (var unEditableMat in mats) + { + var mat = materialSwapDict[unEditableMat] = Instantiate(unEditableMat); + foreach (var overrideProperty in overridePropertyDict) + { + if (!mat.HasProperty(overrideProperty.Key)) { continue; } + if (mat.shader.GetPropertyType(mat.shader.FindPropertyIndex(overrideProperty.Key)) != overrideProperty.Value) { continue; } + + switch (overrideProperty.Value) + { + case ShaderPropertyType.Texture: + { + mat.SetTexture(overrideProperty.Key, MaterialVariantSource.GetTexture(overrideProperty.Key)); + mat.SetTextureOffset(overrideProperty.Key, MaterialVariantSource.GetTextureOffset(overrideProperty.Key)); + mat.SetTextureScale(overrideProperty.Key, MaterialVariantSource.GetTextureScale(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Color: + { + mat.SetColor(overrideProperty.Key, MaterialVariantSource.GetColor(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Vector: + { + mat.SetVector(overrideProperty.Key, MaterialVariantSource.GetVector(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Int: + { + mat.SetInt(overrideProperty.Key, MaterialVariantSource.GetInt(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Float: + case ShaderPropertyType.Range: + { + mat.SetFloat(overrideProperty.Key, MaterialVariantSource.GetFloat(overrideProperty.Key)); + break; + } + } + } + } + + domain.ReplaceMaterials(materialSwapDict); + + } + + internal override IEnumerable GetDependency(IDomain domain) + { + yield return TargetMaterial; + yield return MaterialVariantSource; + } + + internal override int GetDependencyHash(IDomain domain) + { + var hash = TargetMaterial?.GetInstanceID() ?? 0; + hash ^= MaterialVariantSource?.GetInstanceID() ?? 0; + return hash; + } + } +} diff --git a/Runtime/CommonComponent/MaterialOverrideTransfer.cs.meta b/Runtime/CommonComponent/MaterialOverrideTransfer.cs.meta new file mode 100644 index 00000000..34f35746 --- /dev/null +++ b/Runtime/CommonComponent/MaterialOverrideTransfer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e14b2e949333c845aea2c2544581e07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} + userData: + assetBundleName: + assetBundleVariant: From 5c31734cd0d8df55e38695359aef84db15b1fa08 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 1 May 2024 18:24:15 +0900 Subject: [PATCH 153/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 3607d242..f3c754dd 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -21,6 +21,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - RealTimePreview が大幅に改修され、MultiLayerImageCanvas もリアルタイムプレビュー可能になりました (#448) - SingleGradationDecal が追加されました (#449) - オプション GradationClamp が追加 (#451) +- MaterialOverrideTransfer が追加されました (#456) ### Changed @@ -32,6 +33,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) - ObjectReplaceInvoke は削除されました (#438) - CylindricalDecal , CylindricalCurveDecal , CylindricalCoordinatesSystem , NailEditor , NailOffsetData は削除されました (#449) +- MatAndTexAbsoluteSeparator , MatAndTexRelativeSeparator , MaterialModifierEditor は削除されました (#456) ### Fixed From abea06e5ee2122848d5bdbd4070feac9651cf05c Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 2 May 2024 18:10:33 +0900 Subject: [PATCH 154/208] chore: remove TransTextureCore --- Editor/Domain/Marker/DomainMarkerFinder.cs | 4 ++-- Editor/Domain/RenderersDomain.cs | 3 +-- Editor/Domain/TextureManager.cs | 6 +----- Editor/Inspector/Decal/SingleGradationDecalEditor.cs | 2 +- Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs | 2 +- Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs | 8 +------- Editor/OtherMenuItem/BlankTextureGenerator.cs | 2 +- Editor/Preview/RealTime/RealTimePreviewDomain.cs | 8 -------- Editor/TextureStack/DeferredTextureStack.cs | 2 +- Editor/TextureStack/ImmediateTextureStack.cs | 2 +- Editor/Utils/TextureUtility.cs | 2 +- MultiLayerImage-Parser/LayerData/AbstractLayerData.cs | 2 +- MultiLayerImage-Parser/LayerData/ImprotRasterImage.cs | 5 +---- MultiLayerImage-Parser/LayerData/RasterLayerData.cs | 4 +--- .../LayerData/SpecialLayer/HSLAdjustmentLayerData.cs | 4 ---- .../LayerData/SpecialLayer/LevelAdjustmentLayerData.cs | 3 --- .../LayerData/SpecialLayer/SelectiveColorLayerData.cs | 3 --- .../LayerData/SpecialLayer/SolidColorLayerData.cs | 5 +---- MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs | 6 ------ Runtime/CommonComponent/MaterialOverrideTransfer.cs | 2 +- Runtime/Decal/Gradation/SingleGradationDecal.cs | 4 ++-- Runtime/Decal/IslandSelectToPPFilter.cs | 3 +-- Runtime/Decal/SimpleDecal.cs | 4 ++-- Runtime/IDomain.cs | 2 +- Runtime/IslandSelect/RayCastIslandSelector.cs | 5 +---- Runtime/MultiLayerImage/AbstractImageLayer.cs | 5 ++--- Runtime/MultiLayerImage/AbstractLayer.cs | 2 +- .../Improted/PSD/PSDImportedRasterImage.cs | 1 - .../Improted/PSD/PSDImportedRasterMaskImage.cs | 2 +- Runtime/MultiLayerImage/Improted/TTTImportedImage.cs | 2 +- Runtime/MultiLayerImage/LayerFolder.cs | 1 - Runtime/MultiLayerImage/MultiLayerImageCanvas.cs | 2 +- Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs | 4 +--- Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs | 1 - .../Decal/AbstractRayCastRendererResolver.cs | 2 +- Runtime/ShaderSupport/ShaderSupportUtils.cs | 4 ++-- Runtime/TextureAtlas/AtlasContext.cs | 2 +- .../AtlasShaderSupport/AtlasShaderSupportUtils.cs | 4 ---- Runtime/TextureAtlas/AtlasTexture.cs | 8 +++----- .../IslandRelocator/AtlasIslandRelocatorObject.cs | 4 ---- .../TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs | 5 ----- Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs | 2 +- Runtime/TextureAtlas/TextureFineTuning/Resize.cs | 2 +- .../TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs | 2 +- TestCode/TransTextureTest.cs | 5 ++--- TexTransCore/{TransTextureCore => }/AsyncTexture2D.cs | 4 ++-- .../{TransTextureCore => }/AsyncTexture2D.cs.meta | 0 TexTransCore/BlendTexture/TextureBlend.cs | 2 +- TexTransCore/Decal/DecalContext.cs | 4 ++-- TexTransCore/Decal/MeshData.cs | 4 ++-- .../Decal/ParallelProjection/ParallelProjectionFilter.cs | 2 +- .../Decal/ParallelProjection/ParallelProjectionSpace.cs | 2 +- TexTransCore/Decal/TriangleFilterUtility.cs | 4 ++-- TexTransCore/Island/IslandCulling.cs | 4 ++-- TexTransCore/Island/IslandUtility.cs | 4 ++-- TexTransCore/Island/RayCastJob.cs | 4 ++-- TexTransCore/JobResult.cs | 2 +- TexTransCore/MipMap/MipMapUtility.cs | 2 +- TexTransCore/{TransTextureCore => }/ShaderAsset.meta | 2 +- .../{TransTextureCore => }/ShaderAsset/Compute.meta | 0 .../ShaderAsset/Compute/TransHelper.hlsl | 0 .../ShaderAsset/Compute/TransHelper.hlsl.meta | 0 .../ShaderAsset/Compute/TransMapperHelper.hlsl | 0 .../ShaderAsset/Compute/TransMapperHelper.hlsl.meta | 0 .../{TransTextureCore => }/ShaderAsset/DepthWriter.shader | 0 .../ShaderAsset/DepthWriter.shader.meta | 0 .../ShaderAsset/TextureSTApply.shader | 0 .../ShaderAsset/TextureSTApply.shader.meta | 0 .../ShaderAsset/TransTextureHelper.hlsl | 0 .../ShaderAsset/TransTextureHelper.hlsl.meta | 0 .../ShaderAsset/TransTextureShader.shader | 0 .../ShaderAsset/TransTextureShader.shader.meta | 0 TexTransCore/{TransTextureCore => }/TextureWrap.cs | 4 ++-- TexTransCore/{TransTextureCore => }/TextureWrap.cs.meta | 0 TexTransCore/{TransTextureCore => }/TransTexture.cs | 4 ++-- TexTransCore/{TransTextureCore => }/TransTexture.cs.meta | 0 TexTransCore/TransTextureCore.meta | 8 -------- TexTransCore/{TransTextureCore => }/TriangleIndex.cs | 2 +- TexTransCore/{TransTextureCore => }/TriangleIndex.cs.meta | 0 TexTransCore/{TransTextureCore => }/TwoDimensionalMap.cs | 6 +++--- .../{TransTextureCore => }/TwoDimensionalMap.cs.meta | 0 TexTransCore/{TransTextureCore => }/Utils.meta | 0 .../{TransTextureCore => }/Utils/CollectionsUtility.cs | 4 ++-- .../Utils/CollectionsUtility.cs.meta | 0 .../{TransTextureCore => }/Utils/InterfaceUtility.cs | 2 +- .../{TransTextureCore => }/Utils/InterfaceUtility.cs.meta | 0 TexTransCore/{TransTextureCore => }/Utils/MeshUtility.cs | 4 ++-- .../{TransTextureCore => }/Utils/MeshUtility.cs.meta | 0 .../{TransTextureCore => }/Utils/RendererUtility.cs | 2 +- .../{TransTextureCore => }/Utils/RendererUtility.cs.meta | 0 .../{TransTextureCore => }/Utils/TextureUtility.cs | 2 +- .../{TransTextureCore => }/Utils/TextureUtility.cs.meta | 0 .../{TransTextureCore => }/Utils/VectorUtility.cs | 2 +- .../{TransTextureCore => }/Utils/VectorUtility.cs.meta | 0 94 files changed, 78 insertions(+), 155 deletions(-) rename TexTransCore/{TransTextureCore => }/AsyncTexture2D.cs (98%) rename TexTransCore/{TransTextureCore => }/AsyncTexture2D.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset.meta (77%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/Compute.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/Compute/TransHelper.hlsl (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/Compute/TransHelper.hlsl.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/Compute/TransMapperHelper.hlsl (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/Compute/TransMapperHelper.hlsl.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/DepthWriter.shader (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/DepthWriter.shader.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TextureSTApply.shader (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TextureSTApply.shader.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TransTextureHelper.hlsl (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TransTextureHelper.hlsl.meta (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TransTextureShader.shader (100%) rename TexTransCore/{TransTextureCore => }/ShaderAsset/TransTextureShader.shader.meta (100%) rename TexTransCore/{TransTextureCore => }/TextureWrap.cs (94%) rename TexTransCore/{TransTextureCore => }/TextureWrap.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/TransTexture.cs (99%) rename TexTransCore/{TransTextureCore => }/TransTexture.cs.meta (100%) delete mode 100644 TexTransCore/TransTextureCore.meta rename TexTransCore/{TransTextureCore => }/TriangleIndex.cs (99%) rename TexTransCore/{TransTextureCore => }/TriangleIndex.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/TwoDimensionalMap.cs (96%) rename TexTransCore/{TransTextureCore => }/TwoDimensionalMap.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/CollectionsUtility.cs (95%) rename TexTransCore/{TransTextureCore => }/Utils/CollectionsUtility.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/InterfaceUtility.cs (96%) rename TexTransCore/{TransTextureCore => }/Utils/InterfaceUtility.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/MeshUtility.cs (97%) rename TexTransCore/{TransTextureCore => }/Utils/MeshUtility.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/RendererUtility.cs (97%) rename TexTransCore/{TransTextureCore => }/Utils/RendererUtility.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/TextureUtility.cs (99%) rename TexTransCore/{TransTextureCore => }/Utils/TextureUtility.cs.meta (100%) rename TexTransCore/{TransTextureCore => }/Utils/VectorUtility.cs (99%) rename TexTransCore/{TransTextureCore => }/Utils/VectorUtility.cs.meta (100%) diff --git a/Editor/Domain/Marker/DomainMarkerFinder.cs b/Editor/Domain/Marker/DomainMarkerFinder.cs index ddabaeed..36486a38 100644 --- a/Editor/Domain/Marker/DomainMarkerFinder.cs +++ b/Editor/Domain/Marker/DomainMarkerFinder.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine; namespace net.rs64.TexTransTool @@ -24,4 +24,4 @@ internal interface IDomainMarkerFinder { GameObject FindMarker(GameObject StartPoint); } -} \ No newline at end of file +} diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index d3b3cb54..db53bf39 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -2,8 +2,7 @@ using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; -using net.rs64.TexTransCore.Island; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.TextureStack; using net.rs64.TexTransTool.Utils; using UnityEditor; diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 6653138a..72077a34 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -1,13 +1,9 @@ using System.Collections.Generic; using System.IO; -using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.MultiLayerImage; using net.rs64.TexTransTool.Utils; -using Unity.Collections; using UnityEditor; -using UnityEditor.Build; using UnityEngine; -using UnityEngine.Experimental.Rendering; namespace net.rs64.TexTransTool { @@ -47,7 +43,7 @@ public void DestroyDeferred() public int GetOriginalTextureSize(Texture2D texture2D) { - return TexTransCore.TransTextureCore.Utils.TextureUtility.NormalizePowerOfTwo(GetOriginalTexture(texture2D).width); + return TexTransCore.Utils.TextureUtility.NormalizePowerOfTwo(GetOriginalTexture(texture2D).width); } public void WriteOriginalTexture(Texture2D texture2D, RenderTexture writeTarget) { diff --git a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs index b7049d38..6ea6f104 100644 --- a/Editor/Inspector/Decal/SingleGradationDecalEditor.cs +++ b/Editor/Inspector/Decal/SingleGradationDecalEditor.cs @@ -2,7 +2,7 @@ using UnityEditor; using net.rs64.TexTransTool.Decal; using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; namespace net.rs64.TexTransTool.Editor.Decal { diff --git a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs index 4e4cd1a8..b6c81c90 100644 --- a/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs +++ b/Editor/Inspector/TextureAtlas/AtlasTextureEditor.cs @@ -3,7 +3,7 @@ using System.Linq; using net.rs64.TexTransTool.Editor; using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System; using UnityEngine.UIElements; using UnityEditor.UIElements; diff --git a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs index 1f65fa65..04cd95da 100644 --- a/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs +++ b/Editor/MultiLayerImageImporter/TexTransToolPSDImporter.cs @@ -1,12 +1,6 @@ -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; +using System.IO; using net.rs64.MultiLayerImage.LayerData; using net.rs64.MultiLayerImage.Parser.PSD; -using net.rs64.TexTransCore.MipMap; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; using Unity.Collections; using UnityEditor; using UnityEditor.AssetImporters; diff --git a/Editor/OtherMenuItem/BlankTextureGenerator.cs b/Editor/OtherMenuItem/BlankTextureGenerator.cs index f3d08b69..51a5e303 100644 --- a/Editor/OtherMenuItem/BlankTextureGenerator.cs +++ b/Editor/OtherMenuItem/BlankTextureGenerator.cs @@ -1,4 +1,4 @@ -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEditor; using UnityEngine; diff --git a/Editor/Preview/RealTime/RealTimePreviewDomain.cs b/Editor/Preview/RealTime/RealTimePreviewDomain.cs index eec3ee3e..3194018c 100644 --- a/Editor/Preview/RealTime/RealTimePreviewDomain.cs +++ b/Editor/Preview/RealTime/RealTimePreviewDomain.cs @@ -1,15 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransTool.Decal; using UnityEditor; -using UnityEditor.SceneManagement; using UnityEngine; -using UnityEngine.Pool; -using UnityEngine.Profiling; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; namespace net.rs64.TexTransTool.Preview.RealTime diff --git a/Editor/TextureStack/DeferredTextureStack.cs b/Editor/TextureStack/DeferredTextureStack.cs index 9d2f5e28..9141ef89 100644 --- a/Editor/TextureStack/DeferredTextureStack.cs +++ b/Editor/TextureStack/DeferredTextureStack.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using net.rs64.TexTransTool.Utils; using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System.Linq; using UnityEditor; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; diff --git a/Editor/TextureStack/ImmediateTextureStack.cs b/Editor/TextureStack/ImmediateTextureStack.cs index 165e2ae5..13139ad8 100644 --- a/Editor/TextureStack/ImmediateTextureStack.cs +++ b/Editor/TextureStack/ImmediateTextureStack.cs @@ -1,6 +1,6 @@ using net.rs64.TexTransTool.Utils; using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEditor; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; using net.rs64.TexTransCore.BlendTexture; diff --git a/Editor/Utils/TextureUtility.cs b/Editor/Utils/TextureUtility.cs index 4572d4fa..6325453a 100644 --- a/Editor/Utils/TextureUtility.cs +++ b/Editor/Utils/TextureUtility.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEditor; using UnityEngine; diff --git a/MultiLayerImage-Parser/LayerData/AbstractLayerData.cs b/MultiLayerImage-Parser/LayerData/AbstractLayerData.cs index fb196fd8..0e21488a 100644 --- a/MultiLayerImage-Parser/LayerData/AbstractLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/AbstractLayerData.cs @@ -1,6 +1,6 @@ using System; using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData diff --git a/MultiLayerImage-Parser/LayerData/ImprotRasterImage.cs b/MultiLayerImage-Parser/LayerData/ImprotRasterImage.cs index cdf8ee11..21701ea7 100644 --- a/MultiLayerImage-Parser/LayerData/ImprotRasterImage.cs +++ b/MultiLayerImage-Parser/LayerData/ImprotRasterImage.cs @@ -1,7 +1,4 @@ using System; -using net.rs64.TexTransCore.TransTextureCore; -using Unity.Collections; -using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData { @@ -9,4 +6,4 @@ namespace net.rs64.MultiLayerImage.LayerData internal abstract class ImportRasterImageData { } -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/LayerData/RasterLayerData.cs b/MultiLayerImage-Parser/LayerData/RasterLayerData.cs index 5a931a36..3daba35d 100644 --- a/MultiLayerImage-Parser/LayerData/RasterLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/RasterLayerData.cs @@ -1,6 +1,4 @@ using System; -using net.rs64.TexTransCore.TransTextureCore; -using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData { @@ -9,4 +7,4 @@ internal class RasterLayerData : AbstractLayerData { public ImportRasterImageData RasterTexture; } -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/LayerData/SpecialLayer/HSLAdjustmentLayerData.cs b/MultiLayerImage-Parser/LayerData/SpecialLayer/HSLAdjustmentLayerData.cs index 757243e5..23d55664 100644 --- a/MultiLayerImage-Parser/LayerData/SpecialLayer/HSLAdjustmentLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/SpecialLayer/HSLAdjustmentLayerData.cs @@ -1,7 +1,3 @@ -using System; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; -using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData { diff --git a/MultiLayerImage-Parser/LayerData/SpecialLayer/LevelAdjustmentLayerData.cs b/MultiLayerImage-Parser/LayerData/SpecialLayer/LevelAdjustmentLayerData.cs index 8544f6c0..e94968d9 100644 --- a/MultiLayerImage-Parser/LayerData/SpecialLayer/LevelAdjustmentLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/SpecialLayer/LevelAdjustmentLayerData.cs @@ -1,7 +1,4 @@ using System; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; -using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData { diff --git a/MultiLayerImage-Parser/LayerData/SpecialLayer/SelectiveColorLayerData.cs b/MultiLayerImage-Parser/LayerData/SpecialLayer/SelectiveColorLayerData.cs index d8cbdb58..77c29e74 100644 --- a/MultiLayerImage-Parser/LayerData/SpecialLayer/SelectiveColorLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/SpecialLayer/SelectiveColorLayerData.cs @@ -1,6 +1,3 @@ -using System; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData diff --git a/MultiLayerImage-Parser/LayerData/SpecialLayer/SolidColorLayerData.cs b/MultiLayerImage-Parser/LayerData/SpecialLayer/SolidColorLayerData.cs index e1208a59..d9fd18d4 100644 --- a/MultiLayerImage-Parser/LayerData/SpecialLayer/SolidColorLayerData.cs +++ b/MultiLayerImage-Parser/LayerData/SpecialLayer/SolidColorLayerData.cs @@ -1,6 +1,3 @@ -using System; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; using UnityEngine; namespace net.rs64.MultiLayerImage.LayerData @@ -9,4 +6,4 @@ internal class SolidColorLayerData : AbstractLayerData { public Color Color; } -} \ No newline at end of file +} diff --git a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs index c7749ee5..0a57e2d9 100644 --- a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs +++ b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs @@ -1,19 +1,13 @@ -using System.Diagnostics; using System; using System.Collections.Generic; using System.Linq; using net.rs64.MultiLayerImage.LayerData; using UnityEngine; using net.rs64.TexTransCore; -using static net.rs64.MultiLayerImage.Parser.PSD.PSDLowLevelParser.PSDLowLevelData; using static net.rs64.MultiLayerImage.Parser.PSD.ChannelImageDataParser; using static net.rs64.MultiLayerImage.Parser.PSD.LayerRecordParser; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.BlendTexture; using Debug = UnityEngine.Debug; -using System.Threading.Tasks; using LayerMask = net.rs64.MultiLayerImage.LayerData.LayerMaskData; -using System.Buffers; using Unity.Collections; using static net.rs64.MultiLayerImage.Parser.PSD.ChannelImageDataParser.ChannelInformation; using static net.rs64.MultiLayerImage.Parser.PSD.AdditionalLayerInfo.lsct; diff --git a/Runtime/CommonComponent/MaterialOverrideTransfer.cs b/Runtime/CommonComponent/MaterialOverrideTransfer.cs index 818a243a..c8ed5811 100644 --- a/Runtime/CommonComponent/MaterialOverrideTransfer.cs +++ b/Runtime/CommonComponent/MaterialOverrideTransfer.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine; using UnityEngine.Rendering; diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index a27c09fe..a9b67be8 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -7,11 +7,11 @@ using net.rs64.TexTransCore.Decal; using Unity.Jobs; using Unity.Burst; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using System.Linq; using net.rs64.TexTransCore.BlendTexture; using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; namespace net.rs64.TexTransTool.Decal { diff --git a/Runtime/Decal/IslandSelectToPPFilter.cs b/Runtime/Decal/IslandSelectToPPFilter.cs index 6d33e69c..f7282743 100644 --- a/Runtime/Decal/IslandSelectToPPFilter.cs +++ b/Runtime/Decal/IslandSelectToPPFilter.cs @@ -3,11 +3,10 @@ using net.rs64.TexTransCore.Decal; using net.rs64.TexTransTool.Utils; using net.rs64.TexTransCore.Island; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using net.rs64.TexTransTool.IslandSelector; using System.Linq; using UnityEngine.Profiling; -using net.rs64.TexTransCore; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using System.Threading.Tasks; diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index dcf34b5e..c8e3e743 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -7,10 +7,10 @@ using System; using System.Linq; using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using UnityEngine.Pool; using UnityEngine.Profiling; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using Unity.Collections; namespace net.rs64.TexTransTool.Decal diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index b7ec6a89..a3709bea 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using net.rs64.TexTransCore.Island; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.MultiLayerImage; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; diff --git a/Runtime/IslandSelect/RayCastIslandSelector.cs b/Runtime/IslandSelect/RayCastIslandSelector.cs index 647fd5d3..d040ba37 100644 --- a/Runtime/IslandSelect/RayCastIslandSelector.cs +++ b/Runtime/IslandSelect/RayCastIslandSelector.cs @@ -1,13 +1,10 @@ using UnityEngine; -using net.rs64.TexTransTool; using System.Collections.Generic; using net.rs64.TexTransCore.Island; using Unity.Collections; using System.Collections; -using System; using Unity.Jobs; -using net.rs64.TexTransCore.TransTextureCore; -using UnityEngine.Profiling; +using net.rs64.TexTransCore; using net.rs64.TexTransTool.Utils; using System.Linq; diff --git a/Runtime/MultiLayerImage/AbstractImageLayer.cs b/Runtime/MultiLayerImage/AbstractImageLayer.cs index 58179bce..ef976eb1 100644 --- a/Runtime/MultiLayerImage/AbstractImageLayer.cs +++ b/Runtime/MultiLayerImage/AbstractImageLayer.cs @@ -1,6 +1,5 @@ -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine; -using static net.rs64.TexTransCore.BlendTexture.TextureBlend; using static net.rs64.TexTransTool.MultiLayerImage.MultiLayerImageCanvas; namespace net.rs64.TexTransTool.MultiLayerImage @@ -32,4 +31,4 @@ internal override void EvaluateTexture(CanvasContext canvasContext) } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/AbstractLayer.cs b/Runtime/MultiLayerImage/AbstractLayer.cs index affa5c83..7b55c391 100644 --- a/Runtime/MultiLayerImage/AbstractLayer.cs +++ b/Runtime/MultiLayerImage/AbstractLayer.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.Utils; using UnityEngine; using static net.rs64.TexTransTool.MultiLayerImage.MultiLayerImageCanvas; diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index e855a3eb..439c77bb 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; using net.rs64.MultiLayerImage.Parser.PSD; using net.rs64.TexTransCore; -using net.rs64.TexTransCore.TransTextureCore; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 0f3aa673..3263b2e9 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -1,6 +1,6 @@ using net.rs64.MultiLayerImage.Parser.PSD; using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; diff --git a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs index 13f258e6..975f37af 100644 --- a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs +++ b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs @@ -1,7 +1,7 @@ using UnityEngine; using UnityEditor; using Unity.Collections; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; namespace net.rs64.TexTransTool.MultiLayerImage { diff --git a/Runtime/MultiLayerImage/LayerFolder.cs b/Runtime/MultiLayerImage/LayerFolder.cs index 3be7d341..09d6bf48 100644 --- a/Runtime/MultiLayerImage/LayerFolder.cs +++ b/Runtime/MultiLayerImage/LayerFolder.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.Utils; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 99f8c665..1ea8e95f 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -3,7 +3,7 @@ using System.Linq; using JetBrains.Annotations; using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.Utils; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; diff --git a/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs index 816b6587..7c315e22 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs @@ -1,6 +1,4 @@ -using net.rs64.TexTransCore.TransTextureCore.Utils; using UnityEngine; -using static net.rs64.TexTransCore.BlendTexture.TextureBlend; using static net.rs64.TexTransTool.MultiLayerImage.MultiLayerImageCanvas; namespace net.rs64.TexTransTool.MultiLayerImage @@ -18,4 +16,4 @@ internal override void EvaluateTexture(CanvasContext canvasContext) } } -} \ No newline at end of file +} diff --git a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs index 410d555a..ec8b8428 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SolidColorLayer.cs @@ -1,6 +1,5 @@ using net.rs64.TexTransCore.BlendTexture; using UnityEngine; -using static net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.MultiLayerImage { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] diff --git a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs index dac868b1..cea37a27 100644 --- a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs @@ -3,7 +3,7 @@ using net.rs64.TexTransTool.Decal; using UnityEngine; using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransCore; namespace net.rs64.TexTransTool.ReferenceResolver.ATResolver diff --git a/Runtime/ShaderSupport/ShaderSupportUtils.cs b/Runtime/ShaderSupport/ShaderSupportUtils.cs index f520b7d8..7ffa7011 100644 --- a/Runtime/ShaderSupport/ShaderSupportUtils.cs +++ b/Runtime/ShaderSupport/ShaderSupportUtils.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; namespace net.rs64.TexTransTool.ShaderSupport { internal class ShaderSupportUtils @@ -26,4 +26,4 @@ public ShaderSupportUtils() } -} \ No newline at end of file +} diff --git a/Runtime/TextureAtlas/AtlasContext.cs b/Runtime/TextureAtlas/AtlasContext.cs index 1015a1c7..962c3ccd 100644 --- a/Runtime/TextureAtlas/AtlasContext.cs +++ b/Runtime/TextureAtlas/AtlasContext.cs @@ -4,7 +4,7 @@ using System; using net.rs64.TexTransCore.Decal; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System.Collections; using net.rs64.TexTransTool.TextureAtlas.AAOCode; using net.rs64.TexTransTool.Utils; diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index d475f1eb..b17f8a1e 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -2,12 +2,8 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; using UnityEngine; -using UnityEngine.Profiling; -using TexLU = net.rs64.TexTransCore.BlendTexture.TextureBlend; -using TexUT = net.rs64.TexTransCore.TransTextureCore.Utils.TextureUtility; namespace net.rs64.TexTransTool.TextureAtlas { diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 29f0afde..2eaba068 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -3,18 +3,16 @@ using System.Linq; using System; using net.rs64.TexTransTool.Utils; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.Island; using Island = net.rs64.TexTransCore.Island.Island; -using static net.rs64.TexTransCore.TransTextureCore.TransTexture; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using static net.rs64.TexTransCore.TransTexture; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.TextureAtlas.FineTuning; using net.rs64.TexTransTool.TextureAtlas.IslandRelocator; using UnityEngine.Serialization; using Unity.Collections; -using Unity.Mathematics; using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; -using Unity.Profiling; using UnityEngine.Profiling; namespace net.rs64.TexTransTool.TextureAtlas diff --git a/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs b/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs index 1a0893cc..9138b9af 100644 --- a/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs +++ b/Runtime/TextureAtlas/IslandRelocator/AtlasIslandRelocatorObject.cs @@ -1,8 +1,4 @@ -using System.Collections.Generic; using UnityEngine; -using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransCore.Island; namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator { diff --git a/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs b/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs index 8df1cd8b..9a746cc3 100644 --- a/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs +++ b/Runtime/TextureAtlas/IslandRelocator/IAtlasIslandRelocator.cs @@ -1,8 +1,3 @@ -using System.Collections.Generic; -using UnityEngine; -using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; -using net.rs64.TexTransCore.Island; namespace net.rs64.TexTransTool.TextureAtlas.IslandRelocator { diff --git a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs index 1a4844b5..9c684c74 100644 --- a/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs +++ b/Runtime/TextureAtlas/IslandRelocator/NFDHPlasFC.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Island; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using Unity.Collections; using UnityEngine; using UnityEngine.Profiling; diff --git a/Runtime/TextureAtlas/TextureFineTuning/Resize.cs b/Runtime/TextureAtlas/TextureFineTuning/Resize.cs index eaeb39f4..2820402c 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/Resize.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/Resize.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.Utils; using UnityEngine; diff --git a/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs b/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs index a143f2c8..a8aa96f9 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine; namespace net.rs64.TexTransTool.TextureAtlas.FineTuning diff --git a/TestCode/TransTextureTest.cs b/TestCode/TransTextureTest.cs index 86117759..aff99831 100644 --- a/TestCode/TransTextureTest.cs +++ b/TestCode/TransTextureTest.cs @@ -1,7 +1,6 @@ using NUnit.Framework; using net.rs64.TexTransCore; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System.Collections.Generic; using UnityEngine; @@ -70,4 +69,4 @@ public void TransTest(int? testSeed) } } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/AsyncTexture2D.cs b/TexTransCore/AsyncTexture2D.cs similarity index 98% rename from TexTransCore/TransTextureCore/AsyncTexture2D.cs rename to TexTransCore/AsyncTexture2D.cs index 8c60fc9c..7fdd0d3c 100644 --- a/TexTransCore/TransTextureCore/AsyncTexture2D.cs +++ b/TexTransCore/AsyncTexture2D.cs @@ -7,7 +7,7 @@ using UnityEngine.Profiling; using UnityEngine.Rendering; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { public class AsyncTexture2D { @@ -115,4 +115,4 @@ public Texture2D GetTexture2D() return _outTex; } } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/AsyncTexture2D.cs.meta b/TexTransCore/AsyncTexture2D.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/AsyncTexture2D.cs.meta rename to TexTransCore/AsyncTexture2D.cs.meta diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index b6bd255c..490bb7af 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using UnityEngine; using System; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine.Profiling; namespace net.rs64.TexTransCore.BlendTexture diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs index f2a83f5c..1ff423fd 100644 --- a/TexTransCore/Decal/DecalContext.cs +++ b/TexTransCore/Decal/DecalContext.cs @@ -4,8 +4,8 @@ using System.Collections.Generic; using System.Linq; using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore; +using net.rs64.TexTransCore.Utils; using Unity.Burst; using Unity.Collections; using Unity.Jobs; diff --git a/TexTransCore/Decal/MeshData.cs b/TexTransCore/Decal/MeshData.cs index bea9c600..af7fbab5 100644 --- a/TexTransCore/Decal/MeshData.cs +++ b/TexTransCore/Decal/MeshData.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore; +using net.rs64.TexTransCore.Utils; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs index c93102fc..4ebc6dbb 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionFilter.cs @@ -1,6 +1,6 @@ using UnityEngine; using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using net.rs64.TexTransTool.Utils; using Unity.Collections; using System.Runtime.CompilerServices; diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs index e5e855c2..1823ac28 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using Unity.Collections; using Unity.Jobs; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; namespace net.rs64.TexTransCore.Decal { diff --git a/TexTransCore/Decal/TriangleFilterUtility.cs b/TexTransCore/Decal/TriangleFilterUtility.cs index b59b4dae..ca7daa94 100644 --- a/TexTransCore/Decal/TriangleFilterUtility.cs +++ b/TexTransCore/Decal/TriangleFilterUtility.cs @@ -1,8 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore; +using net.rs64.TexTransCore.Utils; using Unity.Burst; using Unity.Collections; using Unity.Jobs; diff --git a/TexTransCore/Island/IslandCulling.cs b/TexTransCore/Island/IslandCulling.cs index 28ab000c..1db7bf09 100644 --- a/TexTransCore/Island/IslandCulling.cs +++ b/TexTransCore/Island/IslandCulling.cs @@ -3,14 +3,14 @@ using System.Collections.Generic; using System.Linq; using System; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using Unity.Jobs; using Unity.Collections; using System.Diagnostics; using net.rs64.TexTransCore.Decal; using Debug = UnityEngine.Debug; using UnityEngine.Pool; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine.Profiling; namespace net.rs64.TexTransCore.Island diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index 543c130d..89f78beb 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using UnityEngine; using net.rs64.TexTransCore.Decal; -using net.rs64.TexTransCore.TransTextureCore; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore; +using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.Utils; using UnityEngine.Pool; using UnityEngine.Profiling; diff --git a/TexTransCore/Island/RayCastJob.cs b/TexTransCore/Island/RayCastJob.cs index ac62477c..0d153996 100644 --- a/TexTransCore/Island/RayCastJob.cs +++ b/TexTransCore/Island/RayCastJob.cs @@ -1,8 +1,8 @@ using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using Unity.Jobs; using Unity.Collections; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using System.Collections.Generic; using Unity.Burst; using System.Runtime.InteropServices; diff --git a/TexTransCore/JobResult.cs b/TexTransCore/JobResult.cs index ae4c730c..267dfbe7 100644 --- a/TexTransCore/JobResult.cs +++ b/TexTransCore/JobResult.cs @@ -4,7 +4,7 @@ using Unity.Jobs; using UnityEditor; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { internal class JobResult { diff --git a/TexTransCore/MipMap/MipMapUtility.cs b/TexTransCore/MipMap/MipMapUtility.cs index 1cf9f2f2..4b044900 100644 --- a/TexTransCore/MipMap/MipMapUtility.cs +++ b/TexTransCore/MipMap/MipMapUtility.cs @@ -1,5 +1,5 @@ using System; -using net.rs64.TexTransCore.TransTextureCore; +using net.rs64.TexTransCore; using Unity.Burst; using Unity.Collections; using Unity.Jobs; diff --git a/TexTransCore/TransTextureCore/ShaderAsset.meta b/TexTransCore/ShaderAsset.meta similarity index 77% rename from TexTransCore/TransTextureCore/ShaderAsset.meta rename to TexTransCore/ShaderAsset.meta index 39b35c8a..a0b86b9b 100644 --- a/TexTransCore/TransTextureCore/ShaderAsset.meta +++ b/TexTransCore/ShaderAsset.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b81bd81440882b24ba302009d98a7354 +guid: ebb0a12d7c564b54088e4b27571e9c44 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute.meta b/TexTransCore/ShaderAsset/Compute.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute.meta rename to TexTransCore/ShaderAsset/Compute.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/TransHelper.hlsl b/TexTransCore/ShaderAsset/Compute/TransHelper.hlsl similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute/TransHelper.hlsl rename to TexTransCore/ShaderAsset/Compute/TransHelper.hlsl diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/TransHelper.hlsl.meta b/TexTransCore/ShaderAsset/Compute/TransHelper.hlsl.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute/TransHelper.hlsl.meta rename to TexTransCore/ShaderAsset/Compute/TransHelper.hlsl.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/TransMapperHelper.hlsl b/TexTransCore/ShaderAsset/Compute/TransMapperHelper.hlsl similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute/TransMapperHelper.hlsl rename to TexTransCore/ShaderAsset/Compute/TransMapperHelper.hlsl diff --git a/TexTransCore/TransTextureCore/ShaderAsset/Compute/TransMapperHelper.hlsl.meta b/TexTransCore/ShaderAsset/Compute/TransMapperHelper.hlsl.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/Compute/TransMapperHelper.hlsl.meta rename to TexTransCore/ShaderAsset/Compute/TransMapperHelper.hlsl.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/DepthWriter.shader b/TexTransCore/ShaderAsset/DepthWriter.shader similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/DepthWriter.shader rename to TexTransCore/ShaderAsset/DepthWriter.shader diff --git a/TexTransCore/TransTextureCore/ShaderAsset/DepthWriter.shader.meta b/TexTransCore/ShaderAsset/DepthWriter.shader.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/DepthWriter.shader.meta rename to TexTransCore/ShaderAsset/DepthWriter.shader.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader b/TexTransCore/ShaderAsset/TextureSTApply.shader similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader rename to TexTransCore/ShaderAsset/TextureSTApply.shader diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta b/TexTransCore/ShaderAsset/TextureSTApply.shader.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TextureSTApply.shader.meta rename to TexTransCore/ShaderAsset/TextureSTApply.shader.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TransTextureHelper.hlsl b/TexTransCore/ShaderAsset/TransTextureHelper.hlsl similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TransTextureHelper.hlsl rename to TexTransCore/ShaderAsset/TransTextureHelper.hlsl diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TransTextureHelper.hlsl.meta b/TexTransCore/ShaderAsset/TransTextureHelper.hlsl.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TransTextureHelper.hlsl.meta rename to TexTransCore/ShaderAsset/TransTextureHelper.hlsl.meta diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TransTextureShader.shader b/TexTransCore/ShaderAsset/TransTextureShader.shader similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TransTextureShader.shader rename to TexTransCore/ShaderAsset/TransTextureShader.shader diff --git a/TexTransCore/TransTextureCore/ShaderAsset/TransTextureShader.shader.meta b/TexTransCore/ShaderAsset/TransTextureShader.shader.meta similarity index 100% rename from TexTransCore/TransTextureCore/ShaderAsset/TransTextureShader.shader.meta rename to TexTransCore/ShaderAsset/TransTextureShader.shader.meta diff --git a/TexTransCore/TransTextureCore/TextureWrap.cs b/TexTransCore/TextureWrap.cs similarity index 94% rename from TexTransCore/TransTextureCore/TextureWrap.cs rename to TexTransCore/TextureWrap.cs index 6fbdfc73..0362c18a 100644 --- a/TexTransCore/TransTextureCore/TextureWrap.cs +++ b/TexTransCore/TextureWrap.cs @@ -1,7 +1,7 @@ using System; using UnityEngine; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { internal readonly struct TextureWrap { @@ -26,4 +26,4 @@ public TextureWrap(WrapMode mode, Vector2? warpRange) public static TextureWrap Stretch => new TextureWrap(WrapMode.Stretch, null); } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/TextureWrap.cs.meta b/TexTransCore/TextureWrap.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/TextureWrap.cs.meta rename to TexTransCore/TextureWrap.cs.meta diff --git a/TexTransCore/TransTextureCore/TransTexture.cs b/TexTransCore/TransTexture.cs similarity index 99% rename from TexTransCore/TransTextureCore/TransTexture.cs rename to TexTransCore/TransTexture.cs index 8ebfdcae..434c81f3 100644 --- a/TexTransCore/TransTextureCore/TransTexture.cs +++ b/TexTransCore/TransTexture.cs @@ -1,7 +1,7 @@ using System.Linq; using System.Collections.Generic; using UnityEngine; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System.Threading.Tasks; using System.Runtime.CompilerServices; using JetBrains.Annotations; @@ -15,7 +15,7 @@ using UnityEngine.Rendering; using System; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { internal static class TransTexture { diff --git a/TexTransCore/TransTextureCore/TransTexture.cs.meta b/TexTransCore/TransTexture.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/TransTexture.cs.meta rename to TexTransCore/TransTexture.cs.meta diff --git a/TexTransCore/TransTextureCore.meta b/TexTransCore/TransTextureCore.meta deleted file mode 100644 index 1d505190..00000000 --- a/TexTransCore/TransTextureCore.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: dafdcad0e24094343954737cc202a840 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/TexTransCore/TransTextureCore/TriangleIndex.cs b/TexTransCore/TriangleIndex.cs similarity index 99% rename from TexTransCore/TransTextureCore/TriangleIndex.cs rename to TexTransCore/TriangleIndex.cs index 493bf474..0c19782f 100644 --- a/TexTransCore/TransTextureCore/TriangleIndex.cs +++ b/TexTransCore/TriangleIndex.cs @@ -4,7 +4,7 @@ using UnityEngine; using System.Runtime.InteropServices; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { [StructLayout(LayoutKind.Explicit)] [Serializable] diff --git a/TexTransCore/TransTextureCore/TriangleIndex.cs.meta b/TexTransCore/TriangleIndex.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/TriangleIndex.cs.meta rename to TexTransCore/TriangleIndex.cs.meta diff --git a/TexTransCore/TransTextureCore/TwoDimensionalMap.cs b/TexTransCore/TwoDimensionalMap.cs similarity index 96% rename from TexTransCore/TransTextureCore/TwoDimensionalMap.cs rename to TexTransCore/TwoDimensionalMap.cs index e5a3da8a..b9dc4769 100644 --- a/TexTransCore/TransTextureCore/TwoDimensionalMap.cs +++ b/TexTransCore/TwoDimensionalMap.cs @@ -3,11 +3,11 @@ using UnityEngine; using System.Linq; using System.Collections; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using System.Runtime.CompilerServices; using Unity.Collections; -namespace net.rs64.TexTransCore.TransTextureCore +namespace net.rs64.TexTransCore { internal struct TwoDimensionalMap { @@ -79,4 +79,4 @@ public void Dispose() Array.Dispose(); } } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/TwoDimensionalMap.cs.meta b/TexTransCore/TwoDimensionalMap.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/TwoDimensionalMap.cs.meta rename to TexTransCore/TwoDimensionalMap.cs.meta diff --git a/TexTransCore/TransTextureCore/Utils.meta b/TexTransCore/Utils.meta similarity index 100% rename from TexTransCore/TransTextureCore/Utils.meta rename to TexTransCore/Utils.meta diff --git a/TexTransCore/TransTextureCore/Utils/CollectionsUtility.cs b/TexTransCore/Utils/CollectionsUtility.cs similarity index 95% rename from TexTransCore/TransTextureCore/Utils/CollectionsUtility.cs rename to TexTransCore/Utils/CollectionsUtility.cs index 44c1d0ae..dcf5911b 100644 --- a/TexTransCore/TransTextureCore/Utils/CollectionsUtility.cs +++ b/TexTransCore/Utils/CollectionsUtility.cs @@ -2,7 +2,7 @@ using Unity.Collections; using UnityEngine; -namespace net.rs64.TexTransCore.TransTextureCore.Utils +namespace net.rs64.TexTransCore.Utils { internal static class CollectionsUtility { @@ -40,4 +40,4 @@ public static T[] FilledArray(T defaultValue, int length) } } -} \ No newline at end of file +} diff --git a/TexTransCore/TransTextureCore/Utils/CollectionsUtility.cs.meta b/TexTransCore/Utils/CollectionsUtility.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/Utils/CollectionsUtility.cs.meta rename to TexTransCore/Utils/CollectionsUtility.cs.meta diff --git a/TexTransCore/TransTextureCore/Utils/InterfaceUtility.cs b/TexTransCore/Utils/InterfaceUtility.cs similarity index 96% rename from TexTransCore/TransTextureCore/Utils/InterfaceUtility.cs rename to TexTransCore/Utils/InterfaceUtility.cs index 70509c37..8e7390d6 100644 --- a/TexTransCore/TransTextureCore/Utils/InterfaceUtility.cs +++ b/TexTransCore/Utils/InterfaceUtility.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using UnityEngine; -namespace net.rs64.TexTransCore.TransTextureCore.Utils +namespace net.rs64.TexTransCore.Utils { internal static class InterfaceUtility diff --git a/TexTransCore/TransTextureCore/Utils/InterfaceUtility.cs.meta b/TexTransCore/Utils/InterfaceUtility.cs.meta similarity index 100% rename from TexTransCore/TransTextureCore/Utils/InterfaceUtility.cs.meta rename to TexTransCore/Utils/InterfaceUtility.cs.meta diff --git a/TexTransCore/TransTextureCore/Utils/MeshUtility.cs b/TexTransCore/Utils/MeshUtility.cs similarity index 97% rename from TexTransCore/TransTextureCore/Utils/MeshUtility.cs rename to TexTransCore/Utils/MeshUtility.cs index ef775b7e..fa13d4a2 100644 --- a/TexTransCore/TransTextureCore/Utils/MeshUtility.cs +++ b/TexTransCore/Utils/MeshUtility.cs @@ -2,7 +2,7 @@ using UnityEngine; using UnityEngine.Pool; -namespace net.rs64.TexTransCore.TransTextureCore.Utils +namespace net.rs64.TexTransCore.Utils { internal static class MeshUtility { @@ -79,4 +79,4 @@ public static List GetUVList(this Mesh mesh, int subMesh = 0, List Date: Fri, 3 May 2024 15:32:22 +0900 Subject: [PATCH 155/208] chore: remove TwoDimensionalMap --- .../PSD/PSDHighLevelParser.cs | 13 ++- TexTransCore/NativeArrayMap.cs | 44 ++++++++++ ...onalMap.cs.meta => NativeArrayMap.cs.meta} | 0 TexTransCore/TwoDimensionalMap.cs | 82 ------------------- 4 files changed, 50 insertions(+), 89 deletions(-) create mode 100644 TexTransCore/NativeArrayMap.cs rename TexTransCore/{TwoDimensionalMap.cs.meta => NativeArrayMap.cs.meta} (100%) delete mode 100644 TexTransCore/TwoDimensionalMap.cs diff --git a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs index 0a57e2d9..b0055269 100644 --- a/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs +++ b/MultiLayerImage-Parser/PSD/PSDHighLevelParser.cs @@ -293,8 +293,8 @@ private static Dictionary DeuceChannelInfoAndIm return channelInfoAndImage; } - public static LowMap DrawOffsetEvaluateTexture( - LowMap targetTexture, + public static NativeArrayMap DrawOffsetEvaluateTexture( + NativeArrayMap targetTexture, Vector2Int texturePivot, Vector2Int canvasSize, Color? DefaultColor @@ -312,10 +312,10 @@ public static LowMap DrawOffsetEvaluateTexture( } } - public static LowMap TextureOffset(LowMap texture, Vector2Int TargetSize, Vector2Int Pivot, Color32? DefaultColor) + public static NativeArrayMap TextureOffset(NativeArrayMap texture, Vector2Int TargetSize, Vector2Int Pivot, Color32? DefaultColor) { var sTex2D = texture; - var tTex2D = new LowMap(new NativeArray(TargetSize.x * TargetSize.y, Allocator.TempJob), TargetSize.x, TargetSize.y); + var tTex2D = new NativeArrayMap(new NativeArray(TargetSize.x * TargetSize.y, Allocator.TempJob), TargetSize.x, TargetSize.y); var initColor = DefaultColor.HasValue ? DefaultColor.Value : new Color32(0, 0, 0, 0); tTex2D.Array.Fill(initColor); @@ -336,9 +336,8 @@ public static LowMap TextureOffset(LowMap texture, Vector2Int for (var yi = yStart; yEnd > yi; yi += 1) { - var sPos = new Vector2Int(xStart, yi); - var sSpan = sTex2D.Array.Slice(TwoDimensionalMap.TwoDToOneDIndex(sPos, sTex2D.Width), xLength); - var tSpan = tTex2D.Array.Slice(TwoDimensionalMap.TwoDToOneDIndex(sPos + Pivot, tTex2D.Width), xLength); + var sSpan = sTex2D.Array.Slice(NativeArrayMap.Convert1D(xStart, yi, sTex2D.Width), xLength); + var tSpan = tTex2D.Array.Slice(NativeArrayMap.Convert1D(xStart + Pivot.x, yi + Pivot.y, tTex2D.Width), xLength); sSpan.CopyTo(tSpan); } texture.Dispose(); diff --git a/TexTransCore/NativeArrayMap.cs b/TexTransCore/NativeArrayMap.cs new file mode 100644 index 00000000..71a6492f --- /dev/null +++ b/TexTransCore/NativeArrayMap.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System; +using UnityEngine; +using System.Linq; +using System.Collections; +using net.rs64.TexTransCore.Utils; +using System.Runtime.CompilerServices; +using Unity.Collections; + +namespace net.rs64.TexTransCore +{ + internal readonly struct NativeArrayMap : IDisposable + where T : struct + { + public readonly NativeArray Array; + public readonly int Width; + public readonly int Height; + public NativeArrayMap(NativeArray array, int width, int height) + { + Array = array; + Width = width; + Height = height; + } + + public Vector2Int MapSize => new Vector2Int(Width, Height); + + public void Dispose() + { + Array.Dispose(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Convert1D(int x, int y, int Size) + { + return (y * Size) + x; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static (int x, int y) Convert2D(int i, int width) + { + return (i % width, i / width); + } + + } +} diff --git a/TexTransCore/TwoDimensionalMap.cs.meta b/TexTransCore/NativeArrayMap.cs.meta similarity index 100% rename from TexTransCore/TwoDimensionalMap.cs.meta rename to TexTransCore/NativeArrayMap.cs.meta diff --git a/TexTransCore/TwoDimensionalMap.cs b/TexTransCore/TwoDimensionalMap.cs deleted file mode 100644 index b9dc4769..00000000 --- a/TexTransCore/TwoDimensionalMap.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections.Generic; -using System; -using UnityEngine; -using System.Linq; -using System.Collections; -using net.rs64.TexTransCore.Utils; -using System.Runtime.CompilerServices; -using Unity.Collections; - -namespace net.rs64.TexTransCore -{ - internal struct TwoDimensionalMap - { - public readonly T[] Array; - public readonly Vector2Int MapSize; - - public T this[int i] { get => Array[i]; set => Array[i] = value; } - public T this[int x, int y] { get => Array[GetIndexOn1D(new Vector2Int(x, y))]; set => Array[GetIndexOn1D(new Vector2Int(x, y))] = value; } - - public TwoDimensionalMap(T[] array, Vector2Int mapSize) - { - Array = array; - MapSize = mapSize; - } - public TwoDimensionalMap(T defaultValue, Vector2Int mapSize) - { - Array = CollectionsUtility.FilledArray(defaultValue, mapSize.x * mapSize.y); - MapSize = mapSize; - } - public TwoDimensionalMap(Vector2Int mapSize) - { - Array = new T[mapSize.x * mapSize.y]; - MapSize = mapSize; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Vector2Int GetPosOn2D(int i) - { - return ConvertIndex2D(i, MapSize.x); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetIndexOn1D(Vector2Int pos) - { - return TwoDToOneDIndex(pos, MapSize.x); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int TwoDToOneDIndex(Vector2Int TowDIndex, int Size) - { - return (TowDIndex.y * Size) + TowDIndex.x; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector2Int ConvertIndex2D(int Index1D, int width) - { - return new Vector2Int(Index1D % width, Index1D / width); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T GetOn2DIndex(Vector2Int pos) - { - return Array[GetIndexOn1D(pos)]; - } - } - - internal readonly struct LowMap : IDisposable - where T : struct - { - public readonly NativeArray Array; - public readonly int Width; - public readonly int Height; - public LowMap(NativeArray array, int width, int height) - { - Array = array; - Width = width; - Height = height; - } - - public Vector2Int MapSize => new Vector2Int(Width, Height); - - public void Dispose() - { - Array.Dispose(); - } - } -} From 77efed595bd81c8b8a7dd03effaa2dc1702718c9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 3 May 2024 15:33:58 +0900 Subject: [PATCH 156/208] chore: move MaterialUtility --- Editor/Domain/RenderersDomain.cs | 2 +- Editor/Inspector/DomainTextureSelector.cs | 4 ++-- Runtime/TextureAtlas/AtlasTexture.cs | 4 ++-- TexTransCore/InternalsVisible.cs | 4 ++-- {Runtime => TexTransCore}/Utils/MaterialUtility.cs | 10 +++++----- .../Utils/MaterialUtility.cs.meta | 0 TexTransCore/Utils/TextureUtility.cs | 1 + 7 files changed, 13 insertions(+), 12 deletions(-) rename {Runtime => TexTransCore}/Utils/MaterialUtility.cs (92%) rename {Runtime => TexTransCore}/Utils/MaterialUtility.cs.meta (100%) diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index db53bf39..7c849bdd 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.TextureStack; -using net.rs64.TexTransTool.Utils; using UnityEditor; using UnityEngine; using UnityEngine.Pool; diff --git a/Editor/Inspector/DomainTextureSelector.cs b/Editor/Inspector/DomainTextureSelector.cs index 3ef3c4a5..3160e0c3 100644 --- a/Editor/Inspector/DomainTextureSelector.cs +++ b/Editor/Inspector/DomainTextureSelector.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransCore.Utils; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; @@ -85,4 +85,4 @@ private void Update() } } -} \ No newline at end of file +} diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 2eaba068..b8a4312a 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -804,11 +804,11 @@ private void TransMoveRectIsland(Texture souseTex, RenderTexture ta } } - private static Material GenerateAtlasMat(Material targetMat, List atlasTex, AtlasShaderSupportUtils shaderSupport, bool forceSetTexture) + private static Material GenerateAtlasMat(Material targetMat, Dictionary atlasTex, AtlasShaderSupportUtils shaderSupport, bool forceSetTexture) { var editableTMat = UnityEngine.Object.Instantiate(targetMat); - editableTMat.SetTextures(atlasTex, forceSetTexture); + editableTMat.SetTexture2Ds(atlasTex, forceSetTexture); var supporter = shaderSupport.GetAtlasShaderSupporter(editableTMat); foreach (var postProcess in supporter.AtlasMaterialPostProses) { postProcess.Proses(editableTMat); } diff --git a/TexTransCore/InternalsVisible.cs b/TexTransCore/InternalsVisible.cs index c0b28989..206b3250 100644 --- a/TexTransCore/InternalsVisible.cs +++ b/TexTransCore/InternalsVisible.cs @@ -2,7 +2,7 @@ [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.editor")] [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.runtime")] -[assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.Inspector")] +[assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.inspector")] [assembly: InternalsVisibleTo("net.ra64.tex-trans-tool.test-code")] [assembly: InternalsVisibleTo("net.rs64.tex-trans-tool.build.ndmf")] @@ -11,4 +11,4 @@ [assembly: InternalsVisibleTo("net.rs64.ttt-clip-importer.editor")] [assembly: InternalsVisibleTo("net.rs64.ttt-destructive-texture-utilities.editor")] -[assembly: InternalsVisibleTo("net.rs64.ttt-debugging-playground.ttt")] \ No newline at end of file +[assembly: InternalsVisibleTo("net.rs64.ttt-debugging-playground.ttt")] diff --git a/Runtime/Utils/MaterialUtility.cs b/TexTransCore/Utils/MaterialUtility.cs similarity index 92% rename from Runtime/Utils/MaterialUtility.cs rename to TexTransCore/Utils/MaterialUtility.cs index 8c469473..6c39966a 100644 --- a/Runtime/Utils/MaterialUtility.cs +++ b/TexTransCore/Utils/MaterialUtility.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using UnityEngine; -namespace net.rs64.TexTransTool.Utils +namespace net.rs64.TexTransCore.Utils { internal static class MaterialUtility { @@ -29,14 +29,14 @@ public static Dictionary ReplaceTextureAll(IEnumerable propAndTextures, bool focusSetTexture = false) + public static void SetTexture2Ds(this Material targetMat, Dictionary propAndTextures, bool focusSetTexture = false) { foreach (var propAndTexture in propAndTextures) { - if (!targetMat.HasProperty(propAndTexture.PropertyName)) { continue; } - if (focusSetTexture || targetMat.GetTexture(propAndTexture.PropertyName) is Texture2D) + if (!targetMat.HasProperty(propAndTexture.Key)) { continue; } + if (focusSetTexture || targetMat.GetTexture(propAndTexture.Key) is Texture2D) { - targetMat.SetTexture(propAndTexture.PropertyName, propAndTexture.Texture2D); + targetMat.SetTexture(propAndTexture.Key, propAndTexture.Value); } } } diff --git a/Runtime/Utils/MaterialUtility.cs.meta b/TexTransCore/Utils/MaterialUtility.cs.meta similarity index 100% rename from Runtime/Utils/MaterialUtility.cs.meta rename to TexTransCore/Utils/MaterialUtility.cs.meta diff --git a/TexTransCore/Utils/TextureUtility.cs b/TexTransCore/Utils/TextureUtility.cs index 3ff12ba5..8fb99033 100644 --- a/TexTransCore/Utils/TextureUtility.cs +++ b/TexTransCore/Utils/TextureUtility.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using net.rs64.TexTransCore.BlendTexture; using UnityEngine; using UnityEngine.Experimental.Rendering; From 6d978378e3e1264200eb04bf3bd20a55b811fc69 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 3 May 2024 15:34:24 +0900 Subject: [PATCH 157/208] refactor: TextureFineTuning --- Runtime/TextureAtlas/AtlasTexture.cs | 12 ++-- .../TextureFineTuning/ColorSpace.cs | 30 ++++------ .../TextureFineTuning/Compress.cs | 36 ++++------- .../TextureFineTuning/ITextureFineTuning.cs | 10 ++-- .../TextureFineTuning/MipMapRemove.cs | 30 ++++------ .../TextureFineTuning/ReferenceCopy.cs | 42 +++++-------- .../TextureAtlas/TextureFineTuning/Remove.cs | 18 +++--- .../TextureAtlas/TextureFineTuning/Resize.cs | 24 +++----- .../TextureFineTuning/TexFineTuningTarget.cs | 59 +++++++++++-------- 9 files changed, 114 insertions(+), 147 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index b8a4312a..30a066ae 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -713,24 +713,24 @@ internal override void Apply(IDomain domain = null) } //Texture Fine Tuning - var atlasTexFineTuningTargets = TexFineTuningUtility.ConvertForTargets(atlasData.Textures); + var atlasTexFineTuningTargets = atlasData.Textures.ToDictionary(i => i.Key, i => new TexFineTuningHolder(i.Value)); TexFineTuningUtility.InitTexFineTuning(atlasTexFineTuningTargets); foreach (var fineTuning in AtlasSetting.TextureFineTuning) { fineTuning.AddSetting(atlasTexFineTuningTargets); } TexFineTuningUtility.FinalizeTexFineTuning(atlasTexFineTuningTargets); - var atlasTexture = TexFineTuningUtility.ConvertForPropAndTexture2D(atlasTexFineTuningTargets); - domain.transferAssets(atlasTexture.Select(PaT => PaT.Texture2D)); + var atlasTexture = atlasTexFineTuningTargets.ToDictionary(i => i.Key, i => i.Value.Texture2D); + domain.transferAssets(atlasTexture.Select(PaT => PaT.Value)); //CompressDelegation foreach (var atlasTexFTData in atlasTexFineTuningTargets) { - var tex = atlasTexFTData.Texture2D; - var compressSetting = atlasTexFTData.TuningDataList.Find(I => I is CompressionQualityData) as CompressionQualityData; + var tex = atlasTexFTData.Value.Texture2D; + var compressSetting = atlasTexFTData.Value.Find() ; if (compressSetting == null) { continue; } var compressSettingTuple = (CompressionQualityApplicant.GetTextureFormat(tex, compressSetting), (int)compressSetting.CompressionQuality); - domain.GetTextureManager().DeferTextureCompress(compressSettingTuple, atlasTexFTData.Texture2D); + domain.GetTextureManager().DeferTextureCompress(compressSettingTuple, atlasTexFTData.Value.Texture2D); } diff --git a/Runtime/TextureAtlas/TextureFineTuning/ColorSpace.cs b/Runtime/TextureAtlas/TextureFineTuning/ColorSpace.cs index f01b2637..244fa951 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/ColorSpace.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/ColorSpace.cs @@ -21,19 +21,12 @@ public ColorSpace(PropertyName propertyNames, PropertySelect select, bool linear public static ColorSpace Default => new(PropertyName.DefaultValue, PropertySelect.Equal, true); - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, propAndTextures)) + foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, texFineTuningTargets)) { - var colorSpaceData = target.TuningDataList.Find(I => I is ColorSpaceData) as ColorSpaceData; - if (colorSpaceData != null) - { - colorSpaceData.Linear = Linear; - } - else - { - target.TuningDataList.Add(new ColorSpaceData() { Linear = Linear }); - } + var tuningDataHolder = target.Value; + tuningDataHolder.Get().Linear = Linear; } } @@ -48,22 +41,23 @@ internal class ColorSpaceApplicant : ITuningApplicant { public int Order => -34; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { foreach (var texf in texFineTuningTargets) { - var colorSpaceData = texf.TuningDataList.Find(I => I is ColorSpaceData) as ColorSpaceData; + var tuningHolder = texf.Value; + var colorSpaceData = tuningHolder.Find(); if (colorSpaceData == null) { continue; } - if (colorSpaceData.Linear == !texf.Texture2D.isDataSRGB) { continue; } + if (colorSpaceData.Linear == !tuningHolder.Texture2D.isDataSRGB) { continue; } // GraphicsFormatUtility.GetLinearFormat() // GraphicsFormatUtility.IsSRGBFormat() - var newTex = new Texture2D(texf.Texture2D.width, texf.Texture2D.height, TextureFormat.RGBA32, texf.Texture2D.mipmapCount > 1, colorSpaceData.Linear); - var pixelData = texf.Texture2D.GetPixelData(0); + var newTex = new Texture2D(tuningHolder.Texture2D.width, tuningHolder.Texture2D.height, TextureFormat.RGBA32, tuningHolder.Texture2D.mipmapCount > 1, colorSpaceData.Linear); + var pixelData = tuningHolder.Texture2D.GetPixelData(0); newTex.SetPixelData(pixelData, 0); pixelData.Dispose(); newTex.Apply(); - newTex.name = texf.Texture2D.name; - texf.Texture2D = newTex; + newTex.name = tuningHolder.Texture2D.name; + tuningHolder.Texture2D = newTex; } } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/Compress.cs b/Runtime/TextureAtlas/TextureFineTuning/Compress.cs index 7684228e..9f6713a0 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/Compress.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/Compress.cs @@ -10,7 +10,7 @@ public struct Compress : ITextureFineTuning public FormatQuality FormatQualityValue; public bool UseOverride; public TextureFormat OverrideTextureFormat; - [Range(0, 100)]public int CompressionQuality; + [Range(0, 100)] public int CompressionQuality; public PropertyName PropertyNames; public PropertySelect Select; @@ -28,29 +28,19 @@ public Compress(FormatQuality formatQuality, bool overrideFormat, TextureFormat public static Compress Default => new(FormatQuality.High, false, TextureFormat.DXT5, 50, PropertyName.DefaultValue, PropertySelect.Equal); - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, propAndTextures)) + foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, texFineTuningTargets)) { - var compressionQualityData = target.TuningDataList.Find(I => I is CompressionQualityData) as CompressionQualityData; - if (compressionQualityData != null) - { - compressionQualityData.FormatQualityValue = FormatQualityValue; - compressionQualityData.CompressionQuality = CompressionQuality; - - compressionQualityData.UseOverride = UseOverride; - compressionQualityData.OverrideTextureFormat = OverrideTextureFormat; - } - else - { - target.TuningDataList.Add(new CompressionQualityData() - { - FormatQualityValue = FormatQualityValue, - UseOverride = UseOverride, - OverrideTextureFormat = OverrideTextureFormat, - CompressionQuality = CompressionQuality - }); - } + var tuningHolder = target.Value; + var compressionQualityData = tuningHolder.Get(); + + compressionQualityData.FormatQualityValue = FormatQualityValue; + compressionQualityData.CompressionQuality = CompressionQuality; + + compressionQualityData.UseOverride = UseOverride; + compressionQualityData.OverrideTextureFormat = OverrideTextureFormat; + } } @@ -78,7 +68,7 @@ internal class CompressionQualityApplicant : ITuningApplicant { public int Order => 0; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { // Delegated to ITextureManager } diff --git a/Runtime/TextureAtlas/TextureFineTuning/ITextureFineTuning.cs b/Runtime/TextureAtlas/TextureFineTuning/ITextureFineTuning.cs index c1b73fea..a507d994 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/ITextureFineTuning.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/ITextureFineTuning.cs @@ -6,12 +6,12 @@ namespace net.rs64.TexTransTool.TextureAtlas.FineTuning { public interface ITextureFineTuning { - void AddSetting(List propAndTextures); + void AddSetting(Dictionary texFineTuningTargets); } public interface ITuningApplicant { int Order { get; } - void ApplyTuning(List texFineTuningTargets); + void ApplyTuning(Dictionary texFineTuningTargets); } public interface ITuningData { @@ -24,7 +24,7 @@ public enum PropertySelect internal static class FineTuningUtil { - public static IEnumerable FilteredTarget(string propertyNames, PropertySelect select, List propAndTextures) + public static IEnumerable> FilteredTarget(string propertyNames, PropertySelect select, Dictionary targets) { var propertyNameList = propertyNames.Split(' '); switch (select) @@ -32,12 +32,12 @@ public static IEnumerable FilteredTarget(string propertyNam default: case PropertySelect.Equal: { - return propAndTextures.Where(x => propertyNameList.Contains(x.PropertyName)); + return targets.Where(x => propertyNameList.Contains(x.Key)); } case PropertySelect.NotEqual: { - return propAndTextures.Where(x => !propertyNameList.Contains(x.PropertyName)); + return targets.Where(x => !propertyNameList.Contains(x.Key)); } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/MipMapRemove.cs b/Runtime/TextureAtlas/TextureFineTuning/MipMapRemove.cs index 6ac49942..6ba90030 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/MipMapRemove.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/MipMapRemove.cs @@ -20,19 +20,11 @@ public MipMapRemove(PropertyName propertyNames, PropertySelect select) public static MipMapRemove Default => new(PropertyName.DefaultValue, PropertySelect.Equal); - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, propAndTextures)) + foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, texFineTuningTargets)) { - var mipMapData = target.TuningDataList.Find(I => I is MipMapData) as MipMapData; - if (mipMapData != null) - { - mipMapData.UseMipMap = false; - } - else - { - target.TuningDataList.Add(new MipMapData() { UseMipMap = false }); - } + target.Value.Get().UseMipMap = false; } } @@ -47,21 +39,21 @@ internal class MipMapApplicant : ITuningApplicant { public int Order => -32; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { - foreach (var texf in texFineTuningTargets) + foreach (var texKv in texFineTuningTargets) { - var mipMapData = texf.TuningDataList.Find(I => I is MipMapData) as MipMapData; + var mipMapData = texKv.Value.Find(); if (mipMapData == null) { continue; } - if (mipMapData.UseMipMap == texf.Texture2D.mipmapCount > 1) { continue; } + if (mipMapData.UseMipMap == texKv.Value.Texture2D.mipmapCount > 1) { continue; } Profiler.BeginSample("MipMapApplicant"); - var newTex = new Texture2D(texf.Texture2D.width, texf.Texture2D.height, TextureFormat.RGBA32, mipMapData.UseMipMap, !texf.Texture2D.isDataSRGB); - var pixelData = texf.Texture2D.GetPixelData(0); + var newTex = new Texture2D(texKv.Value.Texture2D.width, texKv.Value.Texture2D.height, TextureFormat.RGBA32, mipMapData.UseMipMap, !texKv.Value.Texture2D.isDataSRGB); + var pixelData = texKv.Value.Texture2D.GetPixelData(0); newTex.SetPixelData(pixelData, 0); pixelData.Dispose(); newTex.Apply(); - newTex.name = texf.Texture2D.name; - texf.Texture2D = newTex; + newTex.name = texKv.Value.Texture2D.name; + texKv.Value.Texture2D = newTex; Profiler.EndSample(); } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs b/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs index e2f6e08b..bac47ef3 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace net.rs64.TexTransTool.TextureAtlas.FineTuning { @@ -18,37 +19,23 @@ public ReferenceCopy(PropertyName sourcePropertyName, PropertyName targetPropert public static ReferenceCopy Default => new(PropertyName.DefaultValue, PropertyName.DefaultValue); - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - var copyTargetTexture = propAndTextures.Find(x => x.PropertyName == TargetPropertyName); - if (copyTargetTexture == null) + if (!texFineTuningTargets.TryGetValue(TargetPropertyName, out var copyTargetTextureHolder)) { return; } + if (copyTargetTextureHolder == null) { - propAndTextures.Add(new(new(TargetPropertyName, null)) { TuningDataList = new() { new ReferenceCopyData(SourcePropertyName) } }); - } - else - { - var referenceCopyData = copyTargetTexture.TuningDataList.Find(I => I is ReferenceCopyData) as ReferenceCopyData; - if (referenceCopyData != null) - { - referenceCopyData.CopySouse = SourcePropertyName; - } - else - { - copyTargetTexture.TuningDataList.Add(new ReferenceCopyData(SourcePropertyName)); - } + copyTargetTextureHolder = new TexFineTuningHolder(null); + texFineTuningTargets.Add(TargetPropertyName, copyTargetTextureHolder); } + copyTargetTextureHolder.Get().CopySouse = SourcePropertyName; + } } internal class ReferenceCopyData : ITuningData { public string CopySouse; - - public ReferenceCopyData(string copySouse) - { - CopySouse = copySouse; - } } internal class ReferenceCopyApplicant : ITuningApplicant @@ -56,16 +43,17 @@ internal class ReferenceCopyApplicant : ITuningApplicant public int Order => 32; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { - foreach (var texf in texFineTuningTargets) + foreach (var texKv in texFineTuningTargets.ToArray()) { - var referenceCopyData = texf.TuningDataList.Find(I => I is ReferenceCopyData) as ReferenceCopyData; + var referenceCopyData = texKv.Value.Find(); if (referenceCopyData == null) { continue; } - var souse = texFineTuningTargets.Find(I => I.PropertyName == referenceCopyData.CopySouse); - if (souse == null) { continue; } - texf.Texture2D = souse.Texture2D; + if (texFineTuningTargets.TryGetValue(referenceCopyData.CopySouse, out var sourceTextureHolder)) + { + texKv.Value.Texture2D = sourceTextureHolder.Texture2D; + } } } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/Remove.cs b/Runtime/TextureAtlas/TextureFineTuning/Remove.cs index 950b484b..cca97ff4 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/Remove.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/Remove.cs @@ -18,15 +18,11 @@ public Remove(PropertyName propertyNames, PropertySelect select) public static Remove Default => new(PropertyName.DefaultValue, PropertySelect.NotEqual); - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, propAndTextures)) + foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, texFineTuningTargets)) { - var referenceCopyData = target.TuningDataList.Find(I => I is RemoveData) as RemoveData; - if (referenceCopyData == null) - { - target.TuningDataList.Add(new RemoveData()); - } + target.Value.Get(); } } @@ -42,9 +38,13 @@ internal class RemoveApplicant : ITuningApplicant public int Order => 64; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { - texFineTuningTargets.RemoveAll(I => I.TuningDataList.Any(T => T is RemoveData)); + foreach (var removeTarget in texFineTuningTargets.Where(i => i.Value.Find() is not null).ToArray()) + { + texFineTuningTargets.Remove(removeTarget.Key); + } + } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/Resize.cs b/Runtime/TextureAtlas/TextureFineTuning/Resize.cs index 2820402c..0188fc81 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/Resize.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/Resize.cs @@ -21,19 +21,11 @@ public Resize(int size, PropertyName propertyNames, PropertySelect select) } - public void AddSetting(List propAndTextures) + public void AddSetting(Dictionary texFineTuningTargets) { - foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, propAndTextures)) + foreach (var target in FineTuningUtil.FilteredTarget(PropertyNames, Select, texFineTuningTargets)) { - var sizeData = target.TuningDataList.Find(I => I is SizeData) as SizeData; - if (sizeData != null) - { - sizeData.TextureSize = Size; - } - else - { - target.TuningDataList.Add(new SizeData() { TextureSize = Size }); - } + target.Value.Get().TextureSize = Size; } } @@ -51,14 +43,14 @@ internal class ResizeApplicant : ITuningApplicant { public int Order => -64; - public void ApplyTuning(List texFineTuningTargets) + public void ApplyTuning(Dictionary texFineTuningTargets) { - foreach (var texf in texFineTuningTargets) + foreach (var texKv in texFineTuningTargets) { - var sizeData = texf.TuningDataList.Find(I => I is SizeData) as SizeData; + var sizeData = texKv.Value.Find(); if (sizeData == null) { continue; } - if (sizeData.TextureSize == texf.Texture2D.width) { continue; } - texf.Texture2D = TextureUtility.ResizeTexture(texf.Texture2D, new Vector2Int(sizeData.TextureSize, (int)((texf.Texture2D.height / (float)texf.Texture2D.width) * sizeData.TextureSize))); + if (sizeData.TextureSize == texKv.Value.Texture2D.width) { continue; } + texKv.Value.Texture2D = TextureUtility.ResizeTexture(texKv.Value.Texture2D, new Vector2Int(sizeData.TextureSize, (int)((texKv.Value.Texture2D.height / (float)texKv.Value.Texture2D.width) * sizeData.TextureSize))); } } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs b/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs index a8aa96f9..f84a38c0 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/TexFineTuningTarget.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using net.rs64.TexTransCore.Utils; @@ -5,33 +6,51 @@ namespace net.rs64.TexTransTool.TextureAtlas.FineTuning { - public class TexFineTuningTarget + public class TexFineTuningHolder { - public string PropertyName; public Texture2D Texture2D; - public List TuningDataList; + Dictionary _tuningDataDict; - internal TexFineTuningTarget(PropAndTexture2D propAndTexture2D) + internal TexFineTuningHolder(Texture2D texture2D) { - PropertyName = propAndTexture2D.PropertyName; - Texture2D = propAndTexture2D.Texture2D; - TuningDataList = new List(); + Texture2D = texture2D; + _tuningDataDict = new(); } + + internal TuningData Find() where TuningData : class, ITuningData, new() + { + if (_tuningDataDict.TryGetValue(typeof(TuningData), out ITuningData t)) { return t as TuningData; } + else { return null; } + } + internal TuningData Get() where TuningData : class, ITuningData, new() + { + if (_tuningDataDict.ContainsKey(typeof(TuningData))) { return _tuningDataDict[typeof(TuningData)] as TuningData; } + else + { + var d = _tuningDataDict[typeof(TuningData)] = new TuningData(); + return d as TuningData; + } + } + internal void Set(TuningData tuningData) where TuningData : class, ITuningData, new() + { + _tuningDataDict[typeof(TuningData)] = tuningData; + } + } internal class TexFineTuningUtility { - public static void InitTexFineTuning(List texFineTuningTargets) + public static void InitTexFineTuning(Dictionary texFineTuningTargets) { - foreach (var texf in texFineTuningTargets) + foreach (var texKv in texFineTuningTargets) { - texf.TuningDataList.Add(new MipMapData()); - texf.TuningDataList.Add(new CompressionQualityData()); + texKv.Value.Set(new MipMapData()); + texKv.Value.Set(new CompressionQualityData()); } } - public static void FinalizeTexFineTuning(List texFineTuningTargets) + public static void FinalizeTexFineTuning(Dictionary texFineTuningTargets) { var applicantList = InterfaceUtility.GetInterfaceInstance().ToList(); applicantList.Sort((L, R) => L.Order - R.Order); @@ -42,24 +61,16 @@ public static void FinalizeTexFineTuning(List texFineTuning } - public static List ConvertForTargets(Dictionary propAndTexture2Ds) + public static Dictionary ConvertForTargets(Dictionary propAndTexture2Ds) { - var targets = new List(propAndTexture2Ds.Count); + var targets = new Dictionary(propAndTexture2Ds.Count); foreach (var pat in propAndTexture2Ds) { - targets.Add(new TexFineTuningTarget(new(pat.Key, pat.Value))); - } - return targets; - } - public static List ConvertForPropAndTexture2D(List texFineTuningTargets) - { - var targets = new List(texFineTuningTargets.Capacity); - foreach (var texftt in texFineTuningTargets) - { - targets.Add(new PropAndTexture2D(texftt.PropertyName, texftt.Texture2D)); + targets.Add(pat.Key, new TexFineTuningHolder(pat.Value)); } return targets; } + } } From bc4a52312ddc98d1be98c730bc218a00489fffe0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 01:19:47 +0900 Subject: [PATCH 158/208] fix: Variant info can only a EditorCall --- .../MaterialOverrideTransferProcessor.cs | 78 +++++++++++++++++++ .../MaterialOverrideTransferProcessor.cs.meta | 11 +++ .../MaterialOverrideTransfer.cs | 70 +---------------- 3 files changed, 93 insertions(+), 66 deletions(-) create mode 100644 Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs create mode 100644 Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs.meta diff --git a/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs new file mode 100644 index 00000000..79bf26f2 --- /dev/null +++ b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs @@ -0,0 +1,78 @@ +using System.Collections.Generic; +using System.Linq; +using net.rs64.TexTransCore.TransTextureCore.Utils; +using UnityEngine; +using UnityEngine.Rendering; + +namespace net.rs64.TexTransTool.EditorProcessor +{ + [EditorProcessor(typeof(MaterialOverrideTransfer))] + internal class MaterialOverrideTransferProcessor : IEditorProcessor + { + public void Process(TexTransCallEditorBehavior texTransCallEditorBehavior, IEditorCallDomain editorCallDomain) + { + var materialOverrideTransfer = texTransCallEditorBehavior as MaterialOverrideTransfer; + if (!materialOverrideTransfer.IsPossibleApply) { throw new TTTNotExecutable(); } + + var materialVariantSource = materialOverrideTransfer.MaterialVariantSource; + var targetMaterial = materialOverrideTransfer.TargetMaterial; + + + var mats = RendererUtility.GetFilteredMaterials(editorCallDomain.EnumerateRenderer()).Where(m => editorCallDomain.OriginEqual(m, targetMaterial)); + + var overridePropertyDict = new Dictionary(); + var shader = materialVariantSource.shader; + var pCount = shader.GetPropertyCount(); + for (var i = 0; pCount > i; i += 1) + { + var propertyName = shader.GetPropertyName(i); + if (materialVariantSource.IsPropertyOverriden(propertyName)) { overridePropertyDict.Add(propertyName, shader.GetPropertyType(i)); } + } + + var materialSwapDict = new Dictionary(); + foreach (var unEditableMat in mats) + { + var mat = materialSwapDict[unEditableMat] = Material.Instantiate(unEditableMat); + foreach (var overrideProperty in overridePropertyDict) + { + if (!mat.HasProperty(overrideProperty.Key)) { continue; } + if (mat.shader.GetPropertyType(mat.shader.FindPropertyIndex(overrideProperty.Key)) != overrideProperty.Value) { continue; } + + switch (overrideProperty.Value) + { + case ShaderPropertyType.Texture: + { + mat.SetTexture(overrideProperty.Key, materialVariantSource.GetTexture(overrideProperty.Key)); + mat.SetTextureOffset(overrideProperty.Key, materialVariantSource.GetTextureOffset(overrideProperty.Key)); + mat.SetTextureScale(overrideProperty.Key, materialVariantSource.GetTextureScale(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Color: + { + mat.SetColor(overrideProperty.Key, materialVariantSource.GetColor(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Vector: + { + mat.SetVector(overrideProperty.Key, materialVariantSource.GetVector(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Int: + { + mat.SetInt(overrideProperty.Key, materialVariantSource.GetInt(overrideProperty.Key)); + break; + } + case ShaderPropertyType.Float: + case ShaderPropertyType.Range: + { + mat.SetFloat(overrideProperty.Key, materialVariantSource.GetFloat(overrideProperty.Key)); + break; + } + } + } + } + + editorCallDomain.ReplaceMaterials(materialSwapDict); + } + } +} diff --git a/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs.meta b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs.meta new file mode 100644 index 00000000..d9f0cd23 --- /dev/null +++ b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb119048e68cfe8459a20cb423e1bb59 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CommonComponent/MaterialOverrideTransfer.cs b/Runtime/CommonComponent/MaterialOverrideTransfer.cs index 818a243a..03aa42eb 100644 --- a/Runtime/CommonComponent/MaterialOverrideTransfer.cs +++ b/Runtime/CommonComponent/MaterialOverrideTransfer.cs @@ -8,7 +8,7 @@ namespace net.rs64.TexTransTool { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public sealed class MaterialOverrideTransfer : TexTransRuntimeBehavior + public sealed class MaterialOverrideTransfer : TexTransCallEditorBehavior { internal const string Name = "TTT MaterialOverrideTransfer"; internal const string FoldoutName = "Other"; @@ -16,82 +16,20 @@ public sealed class MaterialOverrideTransfer : TexTransRuntimeBehavior internal override List GetRenderers => null; - internal override bool IsPossibleApply => TargetMaterial != null && MaterialVariantSource != null && MaterialVariantSource.isVariant; + internal override bool IsPossibleApply => TargetMaterial != null && MaterialVariantSource != null ; internal override TexTransPhase PhaseDefine => TexTransPhase.UnDefined; public Material TargetMaterial; public Material MaterialVariantSource; - internal override void Apply([NotNull] IDomain domain) - { - if (!IsPossibleApply) { throw new TTTNotExecutable(); } - - var mats = RendererUtility.GetFilteredMaterials(domain.EnumerateRenderer()).Where(m => domain.OriginEqual(m, TargetMaterial)); - - var overridePropertyDict = new Dictionary(); - var shader = MaterialVariantSource.shader; - var pCount = shader.GetPropertyCount(); - for (var i = 0; pCount > i; i += 1) - { - var propertyName = shader.GetPropertyName(i); - if (MaterialVariantSource.IsPropertyOverriden(propertyName)) { overridePropertyDict.Add(propertyName, shader.GetPropertyType(i)); } - } - - var materialSwapDict = new Dictionary(); - foreach (var unEditableMat in mats) - { - var mat = materialSwapDict[unEditableMat] = Instantiate(unEditableMat); - foreach (var overrideProperty in overridePropertyDict) - { - if (!mat.HasProperty(overrideProperty.Key)) { continue; } - if (mat.shader.GetPropertyType(mat.shader.FindPropertyIndex(overrideProperty.Key)) != overrideProperty.Value) { continue; } - - switch (overrideProperty.Value) - { - case ShaderPropertyType.Texture: - { - mat.SetTexture(overrideProperty.Key, MaterialVariantSource.GetTexture(overrideProperty.Key)); - mat.SetTextureOffset(overrideProperty.Key, MaterialVariantSource.GetTextureOffset(overrideProperty.Key)); - mat.SetTextureScale(overrideProperty.Key, MaterialVariantSource.GetTextureScale(overrideProperty.Key)); - break; - } - case ShaderPropertyType.Color: - { - mat.SetColor(overrideProperty.Key, MaterialVariantSource.GetColor(overrideProperty.Key)); - break; - } - case ShaderPropertyType.Vector: - { - mat.SetVector(overrideProperty.Key, MaterialVariantSource.GetVector(overrideProperty.Key)); - break; - } - case ShaderPropertyType.Int: - { - mat.SetInt(overrideProperty.Key, MaterialVariantSource.GetInt(overrideProperty.Key)); - break; - } - case ShaderPropertyType.Float: - case ShaderPropertyType.Range: - { - mat.SetFloat(overrideProperty.Key, MaterialVariantSource.GetFloat(overrideProperty.Key)); - break; - } - } - } - } - - domain.ReplaceMaterials(materialSwapDict); - - } - - internal override IEnumerable GetDependency(IDomain domain) + internal IEnumerable GetDependency(IDomain domain) { yield return TargetMaterial; yield return MaterialVariantSource; } - internal override int GetDependencyHash(IDomain domain) + internal int GetDependencyHash(IDomain domain) { var hash = TargetMaterial?.GetInstanceID() ?? 0; hash ^= MaterialVariantSource?.GetInstanceID() ?? 0; From 5a424836f0a41b99ed91f6fa03ac78a482330211 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 01:21:16 +0900 Subject: [PATCH 159/208] chore: remove unused PropAndTextures --- Runtime/TTType/PropAndTexture.cs | 19 ------------------- Runtime/TTType/PropAndTexture.cs.meta | 11 ----------- Runtime/TTType/PropAndTexture2D.cs | 20 -------------------- Runtime/TTType/PropAndTexture2D.cs.meta | 11 ----------- 4 files changed, 61 deletions(-) delete mode 100644 Runtime/TTType/PropAndTexture.cs delete mode 100644 Runtime/TTType/PropAndTexture.cs.meta delete mode 100644 Runtime/TTType/PropAndTexture2D.cs delete mode 100644 Runtime/TTType/PropAndTexture2D.cs.meta diff --git a/Runtime/TTType/PropAndTexture.cs b/Runtime/TTType/PropAndTexture.cs deleted file mode 100644 index 90c0097f..00000000 --- a/Runtime/TTType/PropAndTexture.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using UnityEngine; - -namespace net.rs64.TexTransTool -{ - [Serializable] - public class PropAndTexture - { - public string PropertyName; - public Texture Texture; - - public PropAndTexture(string propertyName, Texture textures) - { - PropertyName = propertyName; - Texture = textures; - } - } - -} \ No newline at end of file diff --git a/Runtime/TTType/PropAndTexture.cs.meta b/Runtime/TTType/PropAndTexture.cs.meta deleted file mode 100644 index 15a98ad9..00000000 --- a/Runtime/TTType/PropAndTexture.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 24c56a28cf63aee4a83fe2e081af4c10 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/TTType/PropAndTexture2D.cs b/Runtime/TTType/PropAndTexture2D.cs deleted file mode 100644 index 69151f61..00000000 --- a/Runtime/TTType/PropAndTexture2D.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using UnityEngine; - -namespace net.rs64.TexTransTool -{ - [Serializable] - internal class PropAndTexture2D - { - public string PropertyName; - public Texture2D Texture2D; - - public PropAndTexture2D(string propertyName, Texture2D textures) - { - PropertyName = propertyName; - Texture2D = textures; - } - } - -} - diff --git a/Runtime/TTType/PropAndTexture2D.cs.meta b/Runtime/TTType/PropAndTexture2D.cs.meta deleted file mode 100644 index 0bd10a0e..00000000 --- a/Runtime/TTType/PropAndTexture2D.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 07c1752bd530e1b40bee53af578509eb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 126b9ea1b1ae7037e8241c4436e1308246a9c2c0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 01:51:30 +0900 Subject: [PATCH 160/208] chore: remove EditorMaterialUtility --- Editor/Utils/EditorMaterialUtility.cs | 63 ---------------------- Editor/Utils/EditorMaterialUtility.cs.meta | 11 ---- 2 files changed, 74 deletions(-) delete mode 100644 Editor/Utils/EditorMaterialUtility.cs delete mode 100644 Editor/Utils/EditorMaterialUtility.cs.meta diff --git a/Editor/Utils/EditorMaterialUtility.cs b/Editor/Utils/EditorMaterialUtility.cs deleted file mode 100644 index f9cdf5c9..00000000 --- a/Editor/Utils/EditorMaterialUtility.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; - -namespace net.rs64.TexTransTool.Utils -{ - internal static class EditorMaterialUtility - { - //MIT License - //Copyright (c) 2020-2021 lilxyzw - //https://github.com/lilxyzw/lilToon/blob/master/Assets/lilToon/Editor/lilMaterialUtils.cs - // - //https://light11.hatenadiary.com/entry/2018/12/04/224253 - public static void RemoveUnusedProperties(this Material material) - { - var so = new SerializedObject(material); - so.Update(); - var savedProps = so.FindProperty("m_SavedProperties"); - - var texs = savedProps.FindPropertyRelative("m_TexEnvs"); - DeleteUnused(ref texs, material); - - var floats = savedProps.FindPropertyRelative("m_Floats"); - DeleteUnused(ref floats, material); - - var colors = savedProps.FindPropertyRelative("m_Colors"); - DeleteUnused(ref colors, material); - - so.ApplyModifiedProperties(); - } - - public static void DeleteUnused(ref SerializedProperty props, Material material) - { - for (int i = props.arraySize - 1; i >= 0; i--) - { - if (!material.HasProperty(props.GetArrayElementAtIndex(i).FindPropertyRelative("first").stringValue)) - { - props.DeleteArrayElementAtIndex(i); - } - } - } - - public static Dictionary GetPropAndTextures(Material material) - { - var so = new SerializedObject(material); - so.Update(); - var savedProps = so.FindProperty("m_SavedProperties"); - - var texs = savedProps.FindPropertyRelative("m_TexEnvs"); - - Dictionary PropAndTextures = new Dictionary(); - - for (int i = 0; i < texs.arraySize; i++) - { - var prop = texs.GetArrayElementAtIndex(i).FindPropertyRelative("first").stringValue; - var tex = texs.GetArrayElementAtIndex(i).FindPropertyRelative("second.m_Texture").objectReferenceValue as Texture2D; - PropAndTextures.Add(prop, tex); - } - - return PropAndTextures; - } - } -} diff --git a/Editor/Utils/EditorMaterialUtility.cs.meta b/Editor/Utils/EditorMaterialUtility.cs.meta deleted file mode 100644 index fcc79012..00000000 --- a/Editor/Utils/EditorMaterialUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2e954ce45b627cc45b03ee1aa81b7bc6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 1843e328bb4963cf8f1ca01a2b73ce01dbbd130f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 01:59:41 +0900 Subject: [PATCH 161/208] chore: move directory --- Runtime/{TTType.meta => Common.meta} | 0 Runtime/{ => Common}/HideFlagPatch.cs | 0 Runtime/{ => Common}/HideFlagPatch.cs.meta | 0 Runtime/{TTType => Common}/ITTTChildExclusion.cs | 0 Runtime/{TTType => Common}/ITTTChildExclusion.cs.meta | 0 Runtime/{TTType => Common}/ITexTransToolTag.cs | 0 Runtime/{TTType => Common}/ITexTransToolTag.cs.meta | 0 Runtime/{TTType => Common}/OrderedHashSet.cs | 0 Runtime/{TTType => Common}/OrderedHashSet.cs.meta | 0 Runtime/{TTType => Common}/PropertyName.cs | 0 Runtime/{TTType => Common}/PropertyName.cs.meta | 0 Runtime/{TTType => Common}/TextureSelector.cs | 0 Runtime/{TTType => Common}/TextureSelector.cs.meta | 0 Runtime/CustomPropertyDrawer.meta | 8 ++++++++ .../BlendTypeKeyAttribute.cs | 0 .../BlendTypeKeyAttribute.cs.meta | 0 .../ExpandTexture2DAttribute.cs | 0 .../ExpandTexture2DAttribute.cs.meta | 0 .../PowerOfTwoAttribute.cs | 0 .../PowerOfTwoAttribute.cs.meta | 0 20 files changed, 8 insertions(+) rename Runtime/{TTType.meta => Common.meta} (100%) rename Runtime/{ => Common}/HideFlagPatch.cs (100%) rename Runtime/{ => Common}/HideFlagPatch.cs.meta (100%) rename Runtime/{TTType => Common}/ITTTChildExclusion.cs (100%) rename Runtime/{TTType => Common}/ITTTChildExclusion.cs.meta (100%) rename Runtime/{TTType => Common}/ITexTransToolTag.cs (100%) rename Runtime/{TTType => Common}/ITexTransToolTag.cs.meta (100%) rename Runtime/{TTType => Common}/OrderedHashSet.cs (100%) rename Runtime/{TTType => Common}/OrderedHashSet.cs.meta (100%) rename Runtime/{TTType => Common}/PropertyName.cs (100%) rename Runtime/{TTType => Common}/PropertyName.cs.meta (100%) rename Runtime/{TTType => Common}/TextureSelector.cs (100%) rename Runtime/{TTType => Common}/TextureSelector.cs.meta (100%) create mode 100644 Runtime/CustomPropertyDrawer.meta rename Runtime/{TTType => CustomPropertyDrawer}/BlendTypeKeyAttribute.cs (100%) rename Runtime/{TTType => CustomPropertyDrawer}/BlendTypeKeyAttribute.cs.meta (100%) rename Runtime/{TTType => CustomPropertyDrawer}/ExpandTexture2DAttribute.cs (100%) rename Runtime/{TTType => CustomPropertyDrawer}/ExpandTexture2DAttribute.cs.meta (100%) rename Runtime/{TTType => CustomPropertyDrawer}/PowerOfTwoAttribute.cs (100%) rename Runtime/{TTType => CustomPropertyDrawer}/PowerOfTwoAttribute.cs.meta (100%) diff --git a/Runtime/TTType.meta b/Runtime/Common.meta similarity index 100% rename from Runtime/TTType.meta rename to Runtime/Common.meta diff --git a/Runtime/HideFlagPatch.cs b/Runtime/Common/HideFlagPatch.cs similarity index 100% rename from Runtime/HideFlagPatch.cs rename to Runtime/Common/HideFlagPatch.cs diff --git a/Runtime/HideFlagPatch.cs.meta b/Runtime/Common/HideFlagPatch.cs.meta similarity index 100% rename from Runtime/HideFlagPatch.cs.meta rename to Runtime/Common/HideFlagPatch.cs.meta diff --git a/Runtime/TTType/ITTTChildExclusion.cs b/Runtime/Common/ITTTChildExclusion.cs similarity index 100% rename from Runtime/TTType/ITTTChildExclusion.cs rename to Runtime/Common/ITTTChildExclusion.cs diff --git a/Runtime/TTType/ITTTChildExclusion.cs.meta b/Runtime/Common/ITTTChildExclusion.cs.meta similarity index 100% rename from Runtime/TTType/ITTTChildExclusion.cs.meta rename to Runtime/Common/ITTTChildExclusion.cs.meta diff --git a/Runtime/TTType/ITexTransToolTag.cs b/Runtime/Common/ITexTransToolTag.cs similarity index 100% rename from Runtime/TTType/ITexTransToolTag.cs rename to Runtime/Common/ITexTransToolTag.cs diff --git a/Runtime/TTType/ITexTransToolTag.cs.meta b/Runtime/Common/ITexTransToolTag.cs.meta similarity index 100% rename from Runtime/TTType/ITexTransToolTag.cs.meta rename to Runtime/Common/ITexTransToolTag.cs.meta diff --git a/Runtime/TTType/OrderedHashSet.cs b/Runtime/Common/OrderedHashSet.cs similarity index 100% rename from Runtime/TTType/OrderedHashSet.cs rename to Runtime/Common/OrderedHashSet.cs diff --git a/Runtime/TTType/OrderedHashSet.cs.meta b/Runtime/Common/OrderedHashSet.cs.meta similarity index 100% rename from Runtime/TTType/OrderedHashSet.cs.meta rename to Runtime/Common/OrderedHashSet.cs.meta diff --git a/Runtime/TTType/PropertyName.cs b/Runtime/Common/PropertyName.cs similarity index 100% rename from Runtime/TTType/PropertyName.cs rename to Runtime/Common/PropertyName.cs diff --git a/Runtime/TTType/PropertyName.cs.meta b/Runtime/Common/PropertyName.cs.meta similarity index 100% rename from Runtime/TTType/PropertyName.cs.meta rename to Runtime/Common/PropertyName.cs.meta diff --git a/Runtime/TTType/TextureSelector.cs b/Runtime/Common/TextureSelector.cs similarity index 100% rename from Runtime/TTType/TextureSelector.cs rename to Runtime/Common/TextureSelector.cs diff --git a/Runtime/TTType/TextureSelector.cs.meta b/Runtime/Common/TextureSelector.cs.meta similarity index 100% rename from Runtime/TTType/TextureSelector.cs.meta rename to Runtime/Common/TextureSelector.cs.meta diff --git a/Runtime/CustomPropertyDrawer.meta b/Runtime/CustomPropertyDrawer.meta new file mode 100644 index 00000000..274830e1 --- /dev/null +++ b/Runtime/CustomPropertyDrawer.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1bd49b1ab74470d4192cc74fd50382f1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TTType/BlendTypeKeyAttribute.cs b/Runtime/CustomPropertyDrawer/BlendTypeKeyAttribute.cs similarity index 100% rename from Runtime/TTType/BlendTypeKeyAttribute.cs rename to Runtime/CustomPropertyDrawer/BlendTypeKeyAttribute.cs diff --git a/Runtime/TTType/BlendTypeKeyAttribute.cs.meta b/Runtime/CustomPropertyDrawer/BlendTypeKeyAttribute.cs.meta similarity index 100% rename from Runtime/TTType/BlendTypeKeyAttribute.cs.meta rename to Runtime/CustomPropertyDrawer/BlendTypeKeyAttribute.cs.meta diff --git a/Runtime/TTType/ExpandTexture2DAttribute.cs b/Runtime/CustomPropertyDrawer/ExpandTexture2DAttribute.cs similarity index 100% rename from Runtime/TTType/ExpandTexture2DAttribute.cs rename to Runtime/CustomPropertyDrawer/ExpandTexture2DAttribute.cs diff --git a/Runtime/TTType/ExpandTexture2DAttribute.cs.meta b/Runtime/CustomPropertyDrawer/ExpandTexture2DAttribute.cs.meta similarity index 100% rename from Runtime/TTType/ExpandTexture2DAttribute.cs.meta rename to Runtime/CustomPropertyDrawer/ExpandTexture2DAttribute.cs.meta diff --git a/Runtime/TTType/PowerOfTwoAttribute.cs b/Runtime/CustomPropertyDrawer/PowerOfTwoAttribute.cs similarity index 100% rename from Runtime/TTType/PowerOfTwoAttribute.cs rename to Runtime/CustomPropertyDrawer/PowerOfTwoAttribute.cs diff --git a/Runtime/TTType/PowerOfTwoAttribute.cs.meta b/Runtime/CustomPropertyDrawer/PowerOfTwoAttribute.cs.meta similarity index 100% rename from Runtime/TTType/PowerOfTwoAttribute.cs.meta rename to Runtime/CustomPropertyDrawer/PowerOfTwoAttribute.cs.meta From b562d4ac03683f2cd661002c183987843ae804ee Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 01:59:53 +0900 Subject: [PATCH 162/208] chore: remove GizmosUtility --- ...{GizmosUtility.cs => DecalGizmoUtility.cs} | 38 +------------------ ...lity.cs.meta => DecalGizmoUtility.cs.meta} | 0 2 files changed, 1 insertion(+), 37 deletions(-) rename Runtime/Utils/{GizmosUtility.cs => DecalGizmoUtility.cs} (57%) rename Runtime/Utils/{GizmosUtility.cs.meta => DecalGizmoUtility.cs.meta} (100%) diff --git a/Runtime/Utils/GizmosUtility.cs b/Runtime/Utils/DecalGizmoUtility.cs similarity index 57% rename from Runtime/Utils/GizmosUtility.cs rename to Runtime/Utils/DecalGizmoUtility.cs index 0f217782..80fd391f 100644 --- a/Runtime/Utils/GizmosUtility.cs +++ b/Runtime/Utils/DecalGizmoUtility.cs @@ -3,43 +3,7 @@ namespace net.rs64.TexTransTool.Utils { - internal static class GizmosUtility - { - public static void DrawGizmoQuad(IEnumerable> quads) - { - foreach (var quad in quads) - { - DrawQuad(quad); - } - } - - public static void DrawQuad(IReadOnlyList quad) - { - Gizmos.DrawLine(quad[0], quad[1]); - Gizmos.DrawLine(quad[0], quad[2]); - Gizmos.DrawLine(quad[2], quad[3]); - Gizmos.DrawLine(quad[1], quad[3]); - } - - public static void DrawGizmoLine(List Line) - { - var LineCount = Line.Count; - if (LineCount < 1) return; - int Count = 1; - while (LineCount > Count) - { - - var FromPos = Line[Count - 1]; - var ToPos = Line[Count]; - Gizmos.DrawLine(FromPos, ToPos); - - Count += 1; - - } - } - - } - public class DecalGizmoUtility + public static class DecalGizmoUtility { public static Mesh Quad; public static Material DisplayDecalMat; diff --git a/Runtime/Utils/GizmosUtility.cs.meta b/Runtime/Utils/DecalGizmoUtility.cs.meta similarity index 100% rename from Runtime/Utils/GizmosUtility.cs.meta rename to Runtime/Utils/DecalGizmoUtility.cs.meta From a91e9b0051729e67554ec3ec97b39255f7d399e0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 02:14:16 +0900 Subject: [PATCH 163/208] chore: fixed typo "souse" --- Editor/Domain/TextureManager.cs | 20 +++--- .../ReferenceCopyTuningDrawer.cs | 4 +- Editor/Migration/V0/AbstractDecalV0.cs | 6 +- Editor/Migration/V0/AtlasTextureV0.cs | 12 ++-- .../MultiLayerImageImporter.cs | 10 +-- Editor/Utils/TextureUtility.cs | 66 +++++++++---------- MultiLayerImage-Parser/ParserUtility.cs | 28 ++++---- Runtime/Decal/SimpleDecal.cs | 12 ++-- Runtime/IDomain.cs | 2 +- .../Improted/PSD/PSDImportedRasterImage.cs | 42 ++++++------ .../PSD/PSDImportedRasterMaskImage.cs | 16 ++--- .../Improted/TTTImportedImage.cs | 4 +- .../MultiLayerImage/MultiLayerImageCanvas.cs | 4 +- .../SpecialLayer/AbstractGrabLayer.cs | 2 +- .../SpecialLayer/HSLAdjustmentLayer.cs | 4 +- .../SpecialLayer/LevelAdjustmentLayer.cs | 12 ++-- .../SelectiveColorAdjustmentLayer.cs | 4 +- .../Decal/AbstractRayCastRendererResolver.cs | 8 +-- .../IAtlasMaterialPostProses.cs | 7 +- Runtime/TextureAtlas/AtlasTexture.cs | 4 +- .../TextureFineTuning/ReferenceCopy.cs | 6 +- TexTransCore/BlendTexture/TextureBlend.cs | 4 +- TexTransCore/Island/IslandUtility.cs | 18 ++--- TexTransCore/TransTexture.cs | 20 +++--- TexTransCore/Utils/TextureUtility.cs | 16 ++--- 25 files changed, 166 insertions(+), 165 deletions(-) diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 72077a34..61025fc1 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -13,7 +13,7 @@ namespace net.rs64.TexTransTool private readonly List DestroyList; private readonly Dictionary CompressDict; private readonly Dictionary OriginDict; - private readonly Dictionary CanvasSouse; + private readonly Dictionary CanvasSource; public TextureManager(bool previewing) { @@ -21,7 +21,7 @@ public TextureManager(bool previewing) DestroyList = !Previewing ? new() : null; CompressDict = !Previewing ? new() : null; OriginDict = !Previewing ? new() : null; - CanvasSouse = !Previewing ? new() : null; + CanvasSource = !Previewing ? new() : null; } public void DeferDestroyOf(Texture2D texture2D) @@ -78,8 +78,8 @@ public void WriteOriginalTexture(TTTImportedImage texture, RenderTexture writeTa } else { - if (!CanvasSouse.ContainsKey(texture.CanvasDescription)) { CanvasSouse[texture.CanvasDescription] = File.ReadAllBytes(AssetDatabase.GetAssetPath(texture.CanvasDescription)); } - texture.LoadImage(CanvasSouse[texture.CanvasDescription], writeTarget); + if (!CanvasSource.ContainsKey(texture.CanvasDescription)) { CanvasSource[texture.CanvasDescription] = File.ReadAllBytes(AssetDatabase.GetAssetPath(texture.CanvasDescription)); } + texture.LoadImage(CanvasSource[texture.CanvasDescription], writeTarget); } } public void DeferTextureCompress((TextureFormat CompressFormat, int Quality) compressSetting, Texture2D target) @@ -87,18 +87,18 @@ public void DeferTextureCompress((TextureFormat CompressFormat, int Quality) com if (CompressDict == null) { return; } CompressDict[target] = compressSetting; } - public void DeferInheritTextureCompress(Texture2D Souse, Texture2D Target) + public void DeferInheritTextureCompress(Texture2D source, Texture2D target) { if (CompressDict == null) { return; } - if (Target == Souse) { return; } - if (CompressDict.ContainsKey(Souse)) + if (target == source) { return; } + if (CompressDict.ContainsKey(source)) { - CompressDict[Target] = CompressDict[Souse]; - CompressDict.Remove(Souse); + CompressDict[target] = CompressDict[source]; + CompressDict.Remove(source); } else { - CompressDict[Target] = (Souse.format, 50); + CompressDict[target] = (source.format, 50); } } diff --git a/Editor/Inspector/TextureAtlas/TextureFineTuning/ReferenceCopyTuningDrawer.cs b/Editor/Inspector/TextureAtlas/TextureFineTuning/ReferenceCopyTuningDrawer.cs index 88b7de65..56faf59c 100644 --- a/Editor/Inspector/TextureAtlas/TextureFineTuning/ReferenceCopyTuningDrawer.cs +++ b/Editor/Inspector/TextureAtlas/TextureFineTuning/ReferenceCopyTuningDrawer.cs @@ -13,9 +13,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten if (ITextureFineTuningDrawer.DrawTuningSelector(position, property)) { return; } position.y += 18; - var sSousePropertyName = property.FindPropertyRelative("SourcePropertyName"); + var sSourcePropertyName = property.FindPropertyRelative("SourcePropertyName"); var sTargetPropertyName = property.FindPropertyRelative("TargetPropertyName"); - EditorGUI.PropertyField(position, sSousePropertyName, "TextureFineTuning:prop:ReferenceCopy:SourcePropertyName".Glc()); + EditorGUI.PropertyField(position, sSourcePropertyName, "TextureFineTuning:prop:ReferenceCopy:SourcePropertyName".Glc()); position.y += 18; EditorGUI.PropertyField(position, sTargetPropertyName, "TextureFineTuning:prop:ReferenceCopy:TargetPropertyName".Glc()); position.y += 18; diff --git a/Editor/Migration/V0/AbstractDecalV0.cs b/Editor/Migration/V0/AbstractDecalV0.cs index b2893772..366a78d1 100644 --- a/Editor/Migration/V0/AbstractDecalV0.cs +++ b/Editor/Migration/V0/AbstractDecalV0.cs @@ -69,15 +69,15 @@ public static void FinalizeMigrationAbstractDecalV0ToV1(SimpleDecal abstractDeca } - static void CopyFromDecal(this SimpleDecal target, SimpleDecal copySouse) + static void CopyFromDecal(this SimpleDecal target, SimpleDecal copySource) { - if (target.GetType() != copySouse.GetType()) { return; }; + if (target.GetType() != copySource.GetType()) { return; }; var fieldInfos = target.GetType().GetFields(); foreach (var fieldInfo in fieldInfos) { if (fieldInfo.IsStatic) { continue; } - fieldInfo.SetValue(target, fieldInfo.GetValue(copySouse)); + fieldInfo.SetValue(target, fieldInfo.GetValue(copySource)); } } diff --git a/Editor/Migration/V0/AtlasTextureV0.cs b/Editor/Migration/V0/AtlasTextureV0.cs index e72cbd3f..bc684c85 100644 --- a/Editor/Migration/V0/AtlasTextureV0.cs +++ b/Editor/Migration/V0/AtlasTextureV0.cs @@ -96,12 +96,12 @@ public static void FinalizeMigrationAtlasTextureV0ToV1(AtlasTexture atlasTexture go.AddComponent(); } } - private static void MigrateSettingV0ToV1(AtlasTexture atlasTextureSouse, int atlasSettingIndex, AtlasTexture NewAtlasTextureTarget) + private static void MigrateSettingV0ToV1(AtlasTexture atlasTextureSource, int atlasSettingIndex, AtlasTexture NewAtlasTextureTarget) { - NewAtlasTextureTarget.TargetRoot = atlasTextureSouse.TargetRoot; - NewAtlasTextureTarget.AtlasSetting = atlasTextureSouse.AtlasSettings[atlasSettingIndex]; - NewAtlasTextureTarget.AtlasSetting.UseIslandCache = atlasTextureSouse.UseIslandCache; - NewAtlasTextureTarget.SelectMatList = atlasTextureSouse.MatSelectors + NewAtlasTextureTarget.TargetRoot = atlasTextureSource.TargetRoot; + NewAtlasTextureTarget.AtlasSetting = atlasTextureSource.AtlasSettings[atlasSettingIndex]; + NewAtlasTextureTarget.AtlasSetting.UseIslandCache = atlasTextureSource.UseIslandCache; + NewAtlasTextureTarget.SelectMatList = atlasTextureSource.MatSelectors .Where(I => I.IsTarget && I.AtlasChannel == atlasSettingIndex) .Select(I => new TexTransTool.TextureAtlas.AtlasTexture.MatSelector() { @@ -109,7 +109,7 @@ private static void MigrateSettingV0ToV1(AtlasTexture atlasTextureSouse, int atl TextureSizeOffSet = I.TextureSizeOffSet }).ToList(); EditorUtility.SetDirty(NewAtlasTextureTarget); - if (atlasTextureSouse == NewAtlasTextureTarget) + if (atlasTextureSource == NewAtlasTextureTarget) { MigrationUtility.SetSaveDataVersion(NewAtlasTextureTarget, 1); } diff --git a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs index 2dfbbfb3..1c5e1070 100644 --- a/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs +++ b/Editor/MultiLayerImageImporter/MultiLayerImageImporter.cs @@ -23,20 +23,20 @@ internal class MultiLayerImageImporter AssetImportContext _ctx; List _tttImportedImages = new(); CreateImportedImage _imageImporter; - byte[] _souseBytes; + byte[] _sourceBytes; Dictionary _layerAtPath = new(); string _path = ""; internal delegate TTTImportedImage CreateImportedImage(ImportRasterImageData importRasterImage); - internal delegate Task> GetPreviewImage(byte[] souseBytes, TTTImportedImage importRasterImage);//つまり正方形にオフセットの入った後の画像を取得するやつ RGBA32 + internal delegate Task> GetPreviewImage(byte[] sourceBytes, TTTImportedImage importRasterImage);//つまり正方形にオフセットの入った後の画像を取得するやつ RGBA32 - internal MultiLayerImageImporter(MultiLayerImageCanvas multiLayerImageCanvas, TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] souseBytes, CreateImportedImage imageImporter) + internal MultiLayerImageImporter(MultiLayerImageCanvas multiLayerImageCanvas, TTTImportedCanvasDescription tttImportedCanvasDescription, AssetImportContext assetImportContext, byte[] sourceBytes, CreateImportedImage imageImporter) { _multiLayerImageCanvas = multiLayerImageCanvas; _ctx = assetImportContext; _imageImporter = imageImporter; _tttImportedCanvasDescription = tttImportedCanvasDescription; - _souseBytes = souseBytes; + _sourceBytes = sourceBytes; } @@ -207,7 +207,7 @@ internal void CreatePreview() Profiler.BeginSample("CreatePreview -" + importedImage.name); Profiler.BeginSample("LoadImage"); - var jobResult = importedImage.LoadImage(_souseBytes, fullNATex); + var jobResult = importedImage.LoadImage(_sourceBytes, fullNATex); Profiler.EndSample(); Texture2D tex2d; diff --git a/Editor/Utils/TextureUtility.cs b/Editor/Utils/TextureUtility.cs index 6325453a..d751a2b3 100644 --- a/Editor/Utils/TextureUtility.cs +++ b/Editor/Utils/TextureUtility.cs @@ -42,32 +42,32 @@ public static Texture TryGetUnCompress(this Texture tex) /// ならない場合もあるため注意。 /// /// - /// + /// /// - public static Texture2D CopySetting(this Texture2D tex, Texture2D copySouse, bool copyCompress = true, TextureFormat? overrideFormat = null) + public static Texture2D CopySetting(this Texture2D tex, Texture2D copySource, bool copyCompress = true, TextureFormat? overrideFormat = null) { - var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(copySouse)) as TextureImporter; + var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(copySource)) as TextureImporter; if ((textureImporter != null) && (textureImporter.textureType == TextureImporterType.NormalMap)) tex = tex.ConvertNormalMap(); - if ((tex.mipmapCount > 1) != (copySouse.mipmapCount > 1)) + if ((tex.mipmapCount > 1) != (copySource.mipmapCount > 1)) { - var newTex = new Texture2D(tex.width, tex.height, tex.format, copySouse.mipmapCount > 1); + var newTex = new Texture2D(tex.width, tex.height, tex.format, copySource.mipmapCount > 1); var pixelData = tex.GetPixelData(0); newTex.SetPixelData(pixelData, 0); pixelData.Dispose(); newTex.name = tex.name; newTex.Apply(true); tex = newTex; } - tex.filterMode = copySouse.filterMode; - tex.anisoLevel = copySouse.anisoLevel; - tex.alphaIsTransparency = copySouse.alphaIsTransparency; - tex.requestedMipmapLevel = copySouse.requestedMipmapLevel; - tex.mipMapBias = copySouse.mipMapBias; - tex.wrapModeU = copySouse.wrapModeU; - tex.wrapModeV = copySouse.wrapModeV; - tex.wrapMode = copySouse.wrapMode; - if (copyCompress && (tex.format != copySouse.format)) + tex.filterMode = copySource.filterMode; + tex.anisoLevel = copySource.anisoLevel; + tex.alphaIsTransparency = copySource.alphaIsTransparency; + tex.requestedMipmapLevel = copySource.requestedMipmapLevel; + tex.mipMapBias = copySource.mipMapBias; + tex.wrapModeU = copySource.wrapModeU; + tex.wrapModeV = copySource.wrapModeV; + tex.wrapMode = copySource.wrapMode; + if (copyCompress && (tex.format != copySource.format)) { - var format = overrideFormat.HasValue ? overrideFormat.Value : copySouse.format; + var format = overrideFormat.HasValue ? overrideFormat.Value : copySource.format; EditorUtility.CompressTexture(tex, format, textureImporter == null ? 50 : textureImporter.compressionQuality); } @@ -97,58 +97,58 @@ public static Texture2D ConvertNormalMap(this Texture2D tex) { throw new NotImplementedException(); } - public static void NotFIlterAndReadWritTexture2D(ref Texture2D souseTex) + public static void NotFIlterAndReadWritTexture2D(ref Texture2D sourceTex) { - var SouseTexPath = AssetDatabase.GetAssetPath(souseTex); - var isEmpty = string.IsNullOrEmpty(SouseTexPath); + var SourceTexPath = AssetDatabase.GetAssetPath(sourceTex); + var isEmpty = string.IsNullOrEmpty(SourceTexPath); if (!isEmpty) { - var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(souseTex)) as TextureImporter; + var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(sourceTex)) as TextureImporter; if (textureImporter == null) return; if (textureImporter.textureType == TextureImporterType.Default && textureImporter.isReadable) { return; } } else { - if (souseTex.isReadable) return; + if (sourceTex.isReadable) return; } - byte[] imageBytes = isEmpty ? souseTex.EncodeToPNG() : File.ReadAllBytes(SouseTexPath); + byte[] imageBytes = isEmpty ? sourceTex.EncodeToPNG() : File.ReadAllBytes(SourceTexPath); var pngTex = new Texture2D(2, 2); pngTex.LoadImage(imageBytes); var newTex = new Texture2D(pngTex.width, pngTex.height, TextureFormat.RGBA32, false); newTex.SetPixels32(pngTex.GetPixels32()); newTex.Apply(); - souseTex = newTex; + sourceTex = newTex; } - public static Vector2Int NativeSize(this Texture2D souseTex) + public static Vector2Int NativeSize(this Texture2D SourceTex) { - var souseTexPath = AssetDatabase.GetAssetPath(souseTex); + var sourceTexPath = AssetDatabase.GetAssetPath(SourceTex); Stream stream; bool isJPG = false; - if (string.IsNullOrEmpty(souseTexPath) || AssetDatabase.IsSubAsset(souseTex)) + if (string.IsNullOrEmpty(sourceTexPath) || AssetDatabase.IsSubAsset(SourceTex)) { //メモリに直接乗っかってる場合かunityアセットの場合、Texture2Dが誤った値を返さない。 - return new Vector2Int(souseTex.width, souseTex.height); + return new Vector2Int(SourceTex.width, SourceTex.height); } - else if (Path.GetExtension(souseTexPath) == ".png") + else if (Path.GetExtension(sourceTexPath) == ".png") { - stream = File.OpenRead(souseTexPath); + stream = File.OpenRead(sourceTexPath); } - else if (Path.GetExtension(souseTexPath) == ".jpg" || Path.GetExtension(souseTexPath) == ".jpeg") + else if (Path.GetExtension(sourceTexPath) == ".jpg" || Path.GetExtension(sourceTexPath) == ".jpeg") { - stream = File.OpenRead(souseTexPath); + stream = File.OpenRead(sourceTexPath); isJPG = true; } - else if (Path.GetExtension(souseTexPath) == ".asset") + else if (Path.GetExtension(sourceTexPath) == ".asset") { - return new Vector2Int(souseTex.width, souseTex.height); + return new Vector2Int(SourceTex.width, SourceTex.height); } else { //非対応形式だった場合を雑に処理。 - return new Vector2Int(souseTex.width, souseTex.height); + return new Vector2Int(SourceTex.width, SourceTex.height); } diff --git a/MultiLayerImage-Parser/ParserUtility.cs b/MultiLayerImage-Parser/ParserUtility.cs index 412018bf..ab0e9980 100644 --- a/MultiLayerImage-Parser/ParserUtility.cs +++ b/MultiLayerImage-Parser/ParserUtility.cs @@ -60,53 +60,53 @@ public sbyte ReadsByte() Position += 1; return (sbyte)Span[beforePos]; } - public ushort ReadUInt16(bool isBigEndianSouse = true) + public ushort ReadUInt16(bool isBigEndianSource = true) { var beforePos = Position; Position += 2; - if (isBigEndianSouse) { return BinaryPrimitives.ReadUInt16BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadUInt16BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadUInt16LittleEndian(Span.Slice(beforePos)); } } - public short ReadInt16(bool isBigEndianSouse = true) + public short ReadInt16(bool isBigEndianSource = true) { var beforePos = Position; Position += 2; - if (isBigEndianSouse) { return BinaryPrimitives.ReadInt16BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadInt16BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadInt16LittleEndian(Span.Slice(beforePos)); } } - public uint ReadUInt32(bool isBigEndianSouse = true) + public uint ReadUInt32(bool isBigEndianSource = true) { var beforePos = Position; Position += 4; - if (isBigEndianSouse) { return BinaryPrimitives.ReadUInt32BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadUInt32BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadUInt32LittleEndian(Span.Slice(beforePos)); } } - public int ReadInt32(bool isBigEndianSouse = true) + public int ReadInt32(bool isBigEndianSource = true) { var beforePos = Position; Position += 4; - if (isBigEndianSouse) { return BinaryPrimitives.ReadInt32BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadInt32BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadInt32LittleEndian(Span.Slice(beforePos)); } } - public ulong ReadUInt64(bool isBigEndianSouse = true) + public ulong ReadUInt64(bool isBigEndianSource = true) { var beforePos = Position; Position += 8; - if (isBigEndianSouse) { return BinaryPrimitives.ReadUInt64BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadUInt64BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadUInt64LittleEndian(Span.Slice(beforePos)); } } - public long ReadInt64(bool isBigEndianSouse = true) + public long ReadInt64(bool isBigEndianSource = true) { var beforePos = Position; Position += 8; - if (isBigEndianSouse) { return BinaryPrimitives.ReadInt64BigEndian(Span.Slice(beforePos)); } + if (isBigEndianSource) { return BinaryPrimitives.ReadInt64BigEndian(Span.Slice(beforePos)); } else { return BinaryPrimitives.ReadInt64LittleEndian(Span.Slice(beforePos)); } } - public double ReadDouble(bool isBigEndianSouse = true) + public double ReadDouble(bool isBigEndianSource = true) { var beforePos = Position; Position += 8; - if (isBigEndianSouse) { return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(Span.Slice(beforePos))); } + if (isBigEndianSource) { return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(Span.Slice(beforePos))); } else { return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(Span.Slice(beforePos))); } } } diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index c8e3e743..a6f5e2c1 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -76,20 +76,20 @@ internal override void Apply(IDomain domain) } - internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureManager, Texture2D souseDecalTexture, Color color) + internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureManager, Texture2D sourceDecalTexture, Color color) { RenderTexture mulDecalTexture; - if (souseDecalTexture != null) + if (sourceDecalTexture != null) { - var decalSouseSize = textureManager.GetOriginalTextureSize(souseDecalTexture); - mulDecalTexture = RenderTexture.GetTemporary(decalSouseSize, decalSouseSize, 0); + var decalSourceSize = textureManager.GetOriginalTextureSize(sourceDecalTexture); + mulDecalTexture = RenderTexture.GetTemporary(decalSourceSize, decalSourceSize, 0); } else { mulDecalTexture = RenderTexture.GetTemporary(32, 32, 0); } mulDecalTexture.Clear(); - if (souseDecalTexture != null) + if (sourceDecalTexture != null) { - var tempRt = textureManager.GetOriginTempRt(souseDecalTexture); + var tempRt = textureManager.GetOriginTempRt(sourceDecalTexture); TextureBlend.MultipleRenderTexture(mulDecalTexture, tempRt, color); RenderTexture.ReleaseTemporary(tempRt); } diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index a3709bea..267904af 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -32,7 +32,7 @@ internal interface ITextureManager : IOriginTexture void DeferTextureCompress((TextureFormat CompressFormat, int Quality) compressFormat, Texture2D target); - void DeferInheritTextureCompress(Texture2D souse, Texture2D target); + void DeferInheritTextureCompress(Texture2D source, Texture2D target); void CompressDeferred(); } internal interface IReplaceTracking diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 439c77bb..84ed9915 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -17,7 +17,7 @@ internal class PSDImportedRasterImage : TTTImportedImage internal override Vector2Int Pivot => new Vector2Int(RasterImageData.RectTangle.Left, CanvasDescription.Height - RasterImageData.RectTangle.Bottom); - internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + internal override JobResult> LoadImage(byte[] importSource, NativeArray? writeTarget = null) { Profiler.BeginSample("Init"); var nativeArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); @@ -29,12 +29,12 @@ internal override JobResult> LoadImage(byte[] importSouse, Profiler.BeginSample("RLE"); Task>[] getImageTask = new Task>[4]; - getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSouse, RasterImageData.RectTangle)); - getImageTask[1] = Task.Run(() => RasterImageData.G.GetImageData(importSouse, RasterImageData.RectTangle)); - getImageTask[2] = Task.Run(() => RasterImageData.B.GetImageData(importSouse, RasterImageData.RectTangle)); - if (RasterImageData.A != null) { getImageTask[3] = Task.Run(() => RasterImageData.A.GetImageData(importSouse, RasterImageData.RectTangle)); } + getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSource, RasterImageData.RectTangle)); + getImageTask[1] = Task.Run(() => RasterImageData.G.GetImageData(importSource, RasterImageData.RectTangle)); + getImageTask[2] = Task.Run(() => RasterImageData.B.GetImageData(importSource, RasterImageData.RectTangle)); + if (RasterImageData.A != null) { getImageTask[3] = Task.Run(() => RasterImageData.A.GetImageData(importSource, RasterImageData.RectTangle)); } - var souseTexSize = new int2(RasterImageData.RectTangle.GetWidth(), RasterImageData.RectTangle.GetHeight()); + var sourceTexSize = new int2(RasterImageData.RectTangle.GetWidth(), RasterImageData.RectTangle.GetHeight()); var image = WeightTask(getImageTask).Result; Profiler.EndSample(); @@ -52,7 +52,7 @@ internal override JobResult> LoadImage(byte[] importSouse, B = image[2], A = image[3], Offset = new int2(Pivot.x, Pivot.y), - SouseSize = souseTexSize, + SourceSize = sourceTexSize, TargetSize = canvasSize, }; offsetJobHandle = offset.Schedule(image[0].Length, 32); @@ -66,7 +66,7 @@ internal override JobResult> LoadImage(byte[] importSouse, G = image[1], B = image[2], Offset = new int2(Pivot.x, Pivot.y), - SouseSize = souseTexSize, + SourceSize = sourceTexSize, TargetSize = canvasSize, }; offsetJobHandle = offset.Schedule(image[0].Length, 32); @@ -84,14 +84,14 @@ internal override JobResult> LoadImage(byte[] importSouse, }); } - internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) + internal override void LoadImage(byte[] importSource, RenderTexture WriteTarget) { // var timer = System.Diagnostics.Stopwatch.StartNew(); Task>[] getImageTask = new Task>[4]; - getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSouse, RasterImageData.RectTangle)); - getImageTask[1] = Task.Run(() => RasterImageData.G.GetImageData(importSouse, RasterImageData.RectTangle)); - getImageTask[2] = Task.Run(() => RasterImageData.B.GetImageData(importSouse, RasterImageData.RectTangle)); - if (RasterImageData.A != null) { getImageTask[3] = Task.Run(() => RasterImageData.A.GetImageData(importSouse, RasterImageData.RectTangle)); } + getImageTask[0] = Task.Run(() => RasterImageData.R.GetImageData(importSource, RasterImageData.RectTangle)); + getImageTask[1] = Task.Run(() => RasterImageData.G.GetImageData(importSource, RasterImageData.RectTangle)); + getImageTask[2] = Task.Run(() => RasterImageData.B.GetImageData(importSource, RasterImageData.RectTangle)); + if (RasterImageData.A != null) { getImageTask[3] = Task.Run(() => RasterImageData.A.GetImageData(importSource, RasterImageData.RectTangle)); } var texWidth = RasterImageData.RectTangle.GetWidth(); var texHeight = RasterImageData.RectTangle.GetHeight(); @@ -168,13 +168,13 @@ internal struct OffsetMoveAlphaJob : IJobParallelFor [ReadOnly] public NativeArray A; public int2 TargetSize; - public int2 SouseSize; + public int2 SourceSize; public int2 Offset; public void Execute(int index) { - var sousePos = CovInt2(index, SouseSize.x); - sousePos.y = SouseSize.y - sousePos.y; - var writePos = Offset + sousePos; + var sourcePos = CovInt2(index, SourceSize.x); + sourcePos.y = SourceSize.y - sourcePos.y; + var writePos = Offset + sourcePos; if (writePos.x < 0) { return; } if (writePos.y < 0) { return; } @@ -203,13 +203,13 @@ internal struct OffsetMoveJob : IJobParallelFor [ReadOnly] public NativeArray B; public int2 TargetSize; - public int2 SouseSize; + public int2 SourceSize; public int2 Offset; public void Execute(int index) { - var sousePos = OffsetMoveAlphaJob.CovInt2(index, SouseSize.x); - sousePos.y = SouseSize.y - sousePos.y; - var writePos = Offset + sousePos; + var sourcePos = OffsetMoveAlphaJob.CovInt2(index, SourceSize.x); + sourcePos.y = SourceSize.y - sourcePos.y; + var writePos = Offset + sourcePos; if (writePos.x < 0) { return; } if (writePos.y < 0) { return; } diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs index 3263b2e9..2630cf1a 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterMaskImage.cs @@ -14,14 +14,14 @@ internal class PSDImportedRasterMaskImage : TTTImportedImage internal override Vector2Int Pivot => new Vector2Int(MaskImageData.RectTangle.Left, CanvasDescription.Height - MaskImageData.RectTangle.Bottom); - internal override JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null) + internal override JobResult> LoadImage(byte[] importSource, NativeArray? writeTarget = null) { Profiler.BeginSample("Init"); var native2DArray = writeTarget ?? new NativeArray(CanvasDescription.Width * CanvasDescription.Height, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); TexTransCore.Unsafe.UnsafeNativeArrayUtility.ClearMemoryOnColor(native2DArray, MaskImageData.DefaultValue); var canvasSize = new int2(CanvasDescription.Width, CanvasDescription.Height); - var souseTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); + var sourceTexSize = new int2(MaskImageData.RectTangle.GetWidth(), MaskImageData.RectTangle.GetHeight()); Profiler.EndSample(); @@ -30,7 +30,7 @@ internal override JobResult> LoadImage(byte[] importSouse, Profiler.BeginSample("RLE"); - var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle); + var data = MaskImageData.MaskImage.GetImageData(importSource, MaskImageData.RectTangle); Profiler.EndSample(); Profiler.BeginSample("OffsetMoveAlphaJobSetUp"); @@ -43,7 +43,7 @@ internal override JobResult> LoadImage(byte[] importSouse, B = data, A = data, Offset = new int2(Pivot.x, Pivot.y), - SouseSize = souseTexSize, + SourceSize = sourceTexSize, TargetSize = canvasSize, }; offsetJobHandle = offset.Schedule(data.Length, 64); @@ -51,7 +51,7 @@ internal override JobResult> LoadImage(byte[] importSouse, Profiler.EndSample(); return new(native2DArray, offsetJobHandle, () => { data.Dispose(); }); } - internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) + internal override void LoadImage(byte[] importSource, RenderTexture WriteTarget) { var isZeroSize = (MaskImageData.RectTangle.GetWidth() * MaskImageData.RectTangle.GetHeight()) == 0; if (PSDImportedRasterImage.s_tempMat == null) { PSDImportedRasterImage.s_tempMat = new Material(PSDImportedRasterImage.MargeColorAndOffsetShader); } @@ -63,7 +63,7 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) if (!isZeroSize) { - using (var data = MaskImageData.MaskImage.GetImageData(importSouse, MaskImageData.RectTangle)) + using (var data = MaskImageData.MaskImage.GetImageData(importSource, MaskImageData.RectTangle)) { texR.LoadRawTextureData(data); texR.Apply(); } @@ -80,9 +80,9 @@ internal override void LoadImage(byte[] importSouse, RenderTexture WriteTarget) UnityEngine.Object.DestroyImmediate(texR); } - internal static NativeArray LoadPSDMaskImageData(PSDImportedRasterMaskImageData maskImageData, byte[] importSouse) + internal static NativeArray LoadPSDMaskImageData(PSDImportedRasterMaskImageData maskImageData, byte[] importSource) { - return ChannelImageDataParser.ChannelImageData.HeightInvert(maskImageData.MaskImage.GetImageData(importSouse, maskImageData.RectTangle), maskImageData.RectTangle.GetWidth(), maskImageData.RectTangle.GetHeight()); + return ChannelImageDataParser.ChannelImageData.HeightInvert(maskImageData.MaskImage.GetImageData(importSource, maskImageData.RectTangle), maskImageData.RectTangle.GetWidth(), maskImageData.RectTangle.GetHeight()); } } diff --git a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs index 975f37af..0ea21793 100644 --- a/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs +++ b/Runtime/MultiLayerImage/Improted/TTTImportedImage.cs @@ -12,8 +12,8 @@ public abstract class TTTImportedImage : ScriptableObject public Texture2D PreviewTexture; // R8 or RGBA32 Non MipMap - internal abstract JobResult> LoadImage(byte[] importSouse, NativeArray? writeTarget = null); - internal abstract void LoadImage(byte[] importSouse, RenderTexture writeTarget); + internal abstract JobResult> LoadImage(byte[] importSource, NativeArray? writeTarget = null); + internal abstract void LoadImage(byte[] importSource, RenderTexture writeTarget); internal abstract Vector2Int Pivot { get; } } #if UNITY_EDITOR diff --git a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs index 1ea8e95f..61bf55c3 100644 --- a/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs +++ b/Runtime/MultiLayerImage/MultiLayerImageCanvas.cs @@ -143,7 +143,7 @@ public void AddLayer(BlendRenderTexture blendLayer, LayerAlphaMod layerAlphaMod, } //GrabCanvasModifiedAction の実行タイミングは即時ではない可能性がある。 - public void GrabCanvas(Action GrabCanvasModifiedAction, LayerAlphaMod layerAlphaMod, string blendTypeKey, bool GrabForClipping)//左がGrabSouse 右がWriteTarget + public void GrabCanvas(Action GrabCanvasModifiedAction, LayerAlphaMod layerAlphaMod, string blendTypeKey, bool GrabForClipping)//左がGrabSource 右がWriteTarget { if (NowScope.HasValue) { NowScope.Value.GrabCanvas(GrabCanvasModifiedAction, layerAlphaMod, blendTypeKey, GrabForClipping); } else @@ -323,7 +323,7 @@ public void AddHiddenLayer(bool thisClipping, bool disallowClipping) else { _layerStack.Push(DisallowClippingLayer.Default); } } - public void GrabCanvas(Action GrabCanvasModifiedAction, LayerAlphaMod layerAlphaMod, string blendTypeKey, bool GrabForClipping)//左がGrabSouse 右がWriteTarget + public void GrabCanvas(Action GrabCanvasModifiedAction, LayerAlphaMod layerAlphaMod, string blendTypeKey, bool GrabForClipping)//左がGrabSource 右がWriteTarget { LayerAlphaAnd(ref layerAlphaMod, _alphaMod); diff --git a/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs index 7c315e22..42c1df92 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/AbstractGrabLayer.cs @@ -5,7 +5,7 @@ namespace net.rs64.TexTransTool.MultiLayerImage { public abstract class AbstractGrabLayer : AbstractLayer { - public abstract void GetImage(RenderTexture GrabSouse, RenderTexture WriteTarget, IOriginTexture originTexture); + public abstract void GetImage(RenderTexture grabSource, RenderTexture writeTarget, IOriginTexture originTexture); internal override void EvaluateTexture(CanvasContext canvasContext) { diff --git a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs index 011bef7d..e02df356 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/HSLAdjustmentLayer.cs @@ -10,14 +10,14 @@ public class HSLAdjustmentLayer : AbstractGrabLayer [Range(-1, 1)] public float Hue; [Range(-1, 1)] public float Saturation; [Range(-1, 1)] public float Lightness; - public override void GetImage(RenderTexture GrabSouse, RenderTexture WriteTarget, IOriginTexture originTexture) + public override void GetImage(RenderTexture grabSource, RenderTexture writeTarget, IOriginTexture originTexture) { var mat = new Material(SpecialLayerShaders.HSLAdjustmentShader); mat.SetFloat("_Hue", Hue); mat.SetFloat("_Saturation", Saturation); mat.SetFloat("_Lightness", Lightness); - Graphics.Blit(GrabSouse, WriteTarget, mat); + Graphics.Blit(grabSource, writeTarget, mat); UnityEngine.Object.DestroyImmediate(mat); } } diff --git a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs index b70f3ebf..4a4c909b 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs @@ -13,31 +13,31 @@ public class LevelAdjustmentLayer : AbstractGrabLayer public Level Green; public Level Blue; - public override void GetImage(RenderTexture GrabSouse, RenderTexture WriteTarget, IOriginTexture originTexture) + public override void GetImage(RenderTexture grabSource, RenderTexture writeTarget, IOriginTexture originTexture) { var mat = new Material(SpecialLayerShaders.LevelAdjustmentShader); - var tempRt = RenderTexture.GetTemporary(GrabSouse.descriptor); + var tempRt = RenderTexture.GetTemporary(grabSource.descriptor); mat.EnableKeyword("RGB"); RGB.SetMaterialProperty(mat); - Graphics.Blit(GrabSouse, tempRt, mat); + Graphics.Blit(grabSource, tempRt, mat); mat.DisableKeyword("RGB"); // Graphics.CopyTexture(tempRt, WriteTarget); mat.EnableKeyword("Red"); Red.SetMaterialProperty(mat); - Graphics.Blit(tempRt, WriteTarget, mat); + Graphics.Blit(tempRt, writeTarget, mat); mat.DisableKeyword("Red"); mat.EnableKeyword("Green"); Green.SetMaterialProperty(mat); - Graphics.Blit(WriteTarget, tempRt, mat); + Graphics.Blit(writeTarget, tempRt, mat); mat.DisableKeyword("Green"); mat.EnableKeyword("Blue"); Blue.SetMaterialProperty(mat); - Graphics.Blit(tempRt, WriteTarget, mat); + Graphics.Blit(tempRt, writeTarget, mat); mat.DisableKeyword("Blue"); UnityEngine.Object.DestroyImmediate(mat); diff --git a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs index c0e6e574..1f0ed413 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/SelectiveColorAdjustmentLayer.cs @@ -18,7 +18,7 @@ public class SelectiveColoringAdjustmentLayer : AbstractGrabLayer public Vector4 BlacksCMYK; public bool IsAbsolute; - public override void GetImage(RenderTexture GrabSouse, RenderTexture WriteTarget, IOriginTexture originTexture) + public override void GetImage(RenderTexture grabSource, RenderTexture writeTarget, IOriginTexture originTexture) { var mat = new Material(SpecialLayerShaders.SelectiveColorAdjustment); @@ -34,7 +34,7 @@ public override void GetImage(RenderTexture GrabSouse, RenderTexture WriteTarget mat.SetFloat("_IsAbsolute", IsAbsolute ? 1f : 0f); - Graphics.Blit(GrabSouse, WriteTarget, mat); + Graphics.Blit(grabSource, writeTarget, mat); UnityEngine.Object.DestroyImmediate(mat); } } diff --git a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs index cea37a27..aee78fff 100644 --- a/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs +++ b/Runtime/ReferenceResolver/Decal/AbstractRayCastRendererResolver.cs @@ -19,14 +19,14 @@ public List FindRayCast(GameObject findRoot) foreach (var renderer in findRoot.GetComponentsInChildren()) { - var souseMesh = renderer.GetMesh(); - if (souseMesh == null) { continue; } + var sourceMesh = renderer.GetMesh(); + if (sourceMesh == null) { continue; } - var meshdata = renderer.Memo(MeshData.GetMeshData); + var meshData = renderer.Memo(MeshData.GetMeshData); var ray = new Ray(transform.position, transform.forward); - var hitTriangles = IslandCulling.RayCast(ray, meshdata); + var hitTriangles = IslandCulling.RayCast(ray, meshData); var count = 0; foreach (var hitTriangle in hitTriangles) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs index ddc0855b..e67feb26 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/IAtlasMaterialPostProses.cs @@ -1,16 +1,17 @@ using UnityEngine; +using UnityEngine.Serialization; namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject { public interface IAtlasMaterialPostProses { void Proses(Material material); } public class TextureReferenceCopy : IAtlasMaterialPostProses { - public string SousePropertyName; + [FormerlySerializedAs("SousePropertyName")] public string SourcePropertyName; public string TargetPropertyName; public void Proses(Material material) { - if (!material.HasProperty(SousePropertyName) || !material.HasProperty(TargetPropertyName)) { return; } - material.SetTexture(TargetPropertyName, material.GetTexture(SousePropertyName)); + if (!material.HasProperty(SourcePropertyName) || !material.HasProperty(TargetPropertyName)) { return; } + material.SetTexture(TargetPropertyName, material.GetTexture(SourcePropertyName)); } } } diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 30a066ae..c7a3c40b 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -767,7 +767,7 @@ Material FindGroup(Material material) } - private void TransMoveRectIsland(Texture souseTex, RenderTexture targetRT, Dictionary notAspectIslandPairs, float uvScalePadding) where TIslandRect : IIslandRect + private void TransMoveRectIsland(Texture sourceTex, RenderTexture targetRT, Dictionary notAspectIslandPairs, float uvScalePadding) where TIslandRect : IIslandRect { uvScalePadding *= 0.5f; using (var sUV = new NativeArray(notAspectIslandPairs.Count * 4, Allocator.TempJob, NativeArrayOptions.UninitializedMemory)) @@ -800,7 +800,7 @@ private void TransMoveRectIsland(Texture souseTex, RenderTexture ta } } - TransTexture.ForTrans(targetRT, souseTex, new TransData(triangles, tUV, sUV), argTexWrap: TextureWrap.Loop); + TransTexture.ForTrans(targetRT, sourceTex, new TransData(triangles, tUV, sUV), argTexWrap: TextureWrap.Loop); } } diff --git a/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs b/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs index bac47ef3..758634df 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/ReferenceCopy.cs @@ -28,14 +28,14 @@ public void AddSetting(Dictionary texFineTuningTarg texFineTuningTargets.Add(TargetPropertyName, copyTargetTextureHolder); } - copyTargetTextureHolder.Get().CopySouse = SourcePropertyName; + copyTargetTextureHolder.Get().CopySource = SourcePropertyName; } } internal class ReferenceCopyData : ITuningData { - public string CopySouse; + public string CopySource; } internal class ReferenceCopyApplicant : ITuningApplicant @@ -50,7 +50,7 @@ public void ApplyTuning(Dictionary texFineTuningTar var referenceCopyData = texKv.Value.Find(); if (referenceCopyData == null) { continue; } - if (texFineTuningTargets.TryGetValue(referenceCopyData.CopySouse, out var sourceTextureHolder)) + if (texFineTuningTargets.TryGetValue(referenceCopyData.CopySource, out var sourceTextureHolder)) { texKv.Value.Texture2D = sourceTextureHolder.Texture2D; } diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index 490bb7af..5b332947 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -347,12 +347,12 @@ public static void AlphaOne(RenderTexture rt) RenderTexture.ReleaseTemporary(swap); } } - public static void AlphaCopy(RenderTexture alphaSouse, RenderTexture rt) + public static void AlphaCopy(RenderTexture alphaSource, RenderTexture rt) { using (new RTActiveSaver()) { SetTempMatShader(AlphaCopyShader); - s_tempMaterial.SetTexture("_AlphaTex", alphaSouse); + s_tempMaterial.SetTexture("_AlphaTex", alphaSource); var swap = RenderTexture.GetTemporary(rt.descriptor); Graphics.CopyTexture(rt, swap); Graphics.Blit(swap, rt, s_tempMaterial); diff --git a/TexTransCore/Island/IslandUtility.cs b/TexTransCore/Island/IslandUtility.cs index 89f78beb..46d63664 100644 --- a/TexTransCore/Island/IslandUtility.cs +++ b/TexTransCore/Island/IslandUtility.cs @@ -233,12 +233,12 @@ public class Island : IIslandRect Vector2 IIslandRect.Size { get => Size; set => Size = value; } bool IIslandRect.Is90Rotation { get => Is90Rotation; set => Is90Rotation = value; } - public Island(Island souse) + public Island(Island source) { - triangles = new List(souse.triangles); - Pivot = souse.Pivot; - Size = souse.Size; - Is90Rotation = souse.Is90Rotation; + triangles = new List(source.triangles); + Pivot = source.Pivot; + Size = source.Size; + Is90Rotation = source.Is90Rotation; } public Island(TriangleIndex triangleIndex) { @@ -272,14 +272,14 @@ public List GetVertexIndex(List output = null) } return output; } - public List GetVertexPos(IReadOnlyList souseUV) + public List GetVertexPos(IReadOnlyList sourceUV) { var vertIndexes = GetVertexIndex(); - return vertIndexes.Select(i => souseUV[i]).ToList(); + return vertIndexes.Select(i => sourceUV[i]).ToList(); } - public void BoxCalculation(IReadOnlyList souseUV) + public void BoxCalculation(IReadOnlyList sourceUV) { - var vertPoss = GetVertexPos(souseUV); + var vertPoss = GetVertexPos(sourceUV); var Box = VectorUtility.BoxCal(vertPoss); Pivot = Box.min; Size = Box.max - Box.min; diff --git a/TexTransCore/TransTexture.cs b/TexTransCore/TransTexture.cs index 434c81f3..49b4ccd6 100644 --- a/TexTransCore/TransTexture.cs +++ b/TexTransCore/TransTexture.cs @@ -148,7 +148,7 @@ public static void Init() static Material s_depthMat; public static void ForTrans( RenderTexture targetTexture, - Texture souseTexture, + Texture sourceTexture, TransData transUVData, float? padding = null, TextureWrap? argTexWrap = null, @@ -161,9 +161,9 @@ public static void ForTrans( var mesh = transUVData.GenerateTransMesh(); Profiler.EndSample(); - var preBias = souseTexture.mipMapBias; - souseTexture.mipMapBias = souseTexture.mipmapCount * -1; - var preWarp = souseTexture.wrapMode; + var preBias = sourceTexture.mipMapBias; + sourceTexture.mipMapBias = sourceTexture.mipmapCount * -1; + var preWarp = sourceTexture.wrapMode; RenderTexture depthRt = null; @@ -171,7 +171,7 @@ public static void ForTrans( { if (argTexWrap == null) { argTexWrap = TextureWrap.NotWrap; } var texWrap = argTexWrap.Value; - souseTexture.wrapMode = texWrap.ConvertTextureWrapMode; + sourceTexture.wrapMode = texWrap.ConvertTextureWrapMode; @@ -179,7 +179,7 @@ public static void ForTrans( Profiler.BeginSample("Material Setup"); if (s_transMat == null) { s_transMat = new Material(s_transShader); } s_transMat.shaderKeywords = Array.Empty(); - s_transMat.SetTexture("_MainTex", souseTexture); + s_transMat.SetTexture("_MainTex", sourceTexture); if (padding.HasValue) s_transMat.SetFloat("_Padding", padding.Value); if (padding.HasValue && highQualityPadding) { @@ -248,15 +248,15 @@ public static void ForTrans( } finally { - souseTexture.mipMapBias = preBias; - souseTexture.wrapMode = preWarp; + sourceTexture.mipMapBias = preBias; + sourceTexture.wrapMode = preWarp; UnityEngine.Object.DestroyImmediate(mesh); if (depthRt != null) { RenderTexture.ReleaseTemporary(depthRt); } } } public static void ForTrans( RenderTexture targetTexture, - Texture souseTexture, + Texture sourceTexture, IEnumerable> transUVDataEnumerable, float? padding = null, TextureWrap? warpRange = null @@ -264,7 +264,7 @@ public static void ForTrans( { foreach (var transUVData in transUVDataEnumerable) { - ForTrans(targetTexture, souseTexture, transUVData, padding, warpRange); + ForTrans(targetTexture, sourceTexture, transUVData, padding, warpRange); } } diff --git a/TexTransCore/Utils/TextureUtility.cs b/TexTransCore/Utils/TextureUtility.cs index 8fb99033..cb1ec6ee 100644 --- a/TexTransCore/Utils/TextureUtility.cs +++ b/TexTransCore/Utils/TextureUtility.cs @@ -66,27 +66,27 @@ public static void Clear(this RenderTexture rt) } - public static Texture2D ResizeTexture(Texture2D souse, Vector2Int size) + public static Texture2D ResizeTexture(Texture2D source, Vector2Int size) { Profiler.BeginSample("ResizeTexture"); using (new RTActiveSaver()) { - var useMip = souse.mipmapCount > 1; + var useMip = source.mipmapCount > 1; var rt = RenderTexture.GetTemporary(size.x, size.y); rt.Clear(); if (useMip) { - Graphics.Blit(souse, rt); + Graphics.Blit(source, rt); } else { - var mipRt = RenderTexture.GetTemporary(souse.width, souse.height); + var mipRt = RenderTexture.GetTemporary(source.width, source.height); mipRt.Release(); var preValue = (mipRt.useMipMap, mipRt.autoGenerateMips); mipRt.useMipMap = true; mipRt.autoGenerateMips = false; - Graphics.Blit(souse, mipRt); + Graphics.Blit(source, mipRt); mipRt.GenerateMips(); Graphics.Blit(mipRt, rt); @@ -96,7 +96,7 @@ public static Texture2D ResizeTexture(Texture2D souse, Vector2Int size) } var resizedTexture = rt.CopyTexture2D(overrideUseMip: useMip); - resizedTexture.name = souse.name + "_Resized_" + size.x.ToString(); + resizedTexture.name = source.name + "_Resized_" + size.x.ToString(); RenderTexture.ReleaseTemporary(rt); Profiler.EndSample(); @@ -157,14 +157,14 @@ internal static void CopyFilWrap(this Texture t, Texture s) static Material s_TempMat; - public static void ApplyTextureST(Texture Souse, Vector2 s, Vector2 t, RenderTexture write) + public static void ApplyTextureST(Texture source, Vector2 s, Vector2 t, RenderTexture write) { using (new RTActiveSaver()) { if (s_TempMat == null) { s_TempMat = new Material(s_stApplyShader); } s_TempMat.shader = s_stApplyShader; - s_TempMat.SetTexture("_OffSetTex", Souse); + s_TempMat.SetTexture("_OffSetTex", source); s_TempMat.SetTextureScale("_OffSetTex", s); s_TempMat.SetTextureOffset("_OffSetTex", t); From 25e2cbcc6017ba4cdd8d4d01289ec45440970f82 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 02:23:38 +0900 Subject: [PATCH 164/208] chore: remove CollectionsUtility --- TexTransCore/Utils/CollectionsUtility.cs | 43 ------------------- TexTransCore/Utils/CollectionsUtility.cs.meta | 11 ----- TexTransCore/Utils/TextureUtility.cs | 10 +++-- 3 files changed, 7 insertions(+), 57 deletions(-) delete mode 100644 TexTransCore/Utils/CollectionsUtility.cs delete mode 100644 TexTransCore/Utils/CollectionsUtility.cs.meta diff --git a/TexTransCore/Utils/CollectionsUtility.cs b/TexTransCore/Utils/CollectionsUtility.cs deleted file mode 100644 index dcf5911b..00000000 --- a/TexTransCore/Utils/CollectionsUtility.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Collections.Generic; -using Unity.Collections; -using UnityEngine; - -namespace net.rs64.TexTransCore.Utils -{ - internal static class CollectionsUtility - { - public static NativeArray ListToNativeArray(List list, Unity.Collections.Allocator allocator) where T : struct - { - var length = list.Count; - var NativeArray = new Unity.Collections.NativeArray(length, allocator); - for (var i = 0; length > i; i += 1) { NativeArray[i] = list[i]; } - return NativeArray; - } - public static List ZipListVector3(IReadOnlyList xy, IReadOnlyList z) - { - var count = xy.Count; - if (count != z.Count) { throw new System.ArgumentException("XY.Count != Z.Count"); } - - List result = new(count); - - for (int index = 0; index < count; index += 1) - { - result.Add(new (xy[index].x, xy[index].y, z[index])); - } - - return result; - } - - - public static T[] FilledArray(T defaultValue, int length) - { - var array = new T[length]; - for (int i = 0; i < array.Length; i++) - { - array[i] = defaultValue; - } - return array; - } - - } -} diff --git a/TexTransCore/Utils/CollectionsUtility.cs.meta b/TexTransCore/Utils/CollectionsUtility.cs.meta deleted file mode 100644 index b5b363ee..00000000 --- a/TexTransCore/Utils/CollectionsUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 909f163357dc8454a9dc6775a1110ab3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/TexTransCore/Utils/TextureUtility.cs b/TexTransCore/Utils/TextureUtility.cs index cb1ec6ee..815d199d 100644 --- a/TexTransCore/Utils/TextureUtility.cs +++ b/TexTransCore/Utils/TextureUtility.cs @@ -3,6 +3,8 @@ using System.Linq; using System.Runtime.CompilerServices; using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore.Unsafe; +using Unity.Collections; using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.Profiling; @@ -125,9 +127,11 @@ public static Texture2D CreateFillTexture(int size, Color fillColor) } public static Texture2D CreateFillTexture(Vector2Int size, Color fillColor) { - var TestTex = new Texture2D(size.x, size.y); - TestTex.SetPixels(CollectionsUtility.FilledArray(fillColor, size.x * size.y)); - return TestTex; + var newTex = new Texture2D(size.x, size.y, TextureFormat.RGBA32, true); + var na = new NativeArray(size.x * size.y, Allocator.Temp); + na.AsSpan().Fill(fillColor); + newTex.SetPixelData(na, 0); + return newTex; } public static int NormalizePowerOfTwo(int v) => Mathf.IsPowerOfTwo(v) ? v : Mathf.NextPowerOfTwo(v); From ed526b05459f922cef640b95304e778c6a3a6d0a Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 02:45:00 +0900 Subject: [PATCH 165/208] chore: fix using namespace --- Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs index 79bf26f2..d3923ea6 100644 --- a/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs +++ b/Editor/EditorProcessor/MaterialOverrideTransferProcessor.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using System.Linq; -using net.rs64.TexTransCore.TransTextureCore.Utils; +using net.rs64.TexTransCore.Utils; using UnityEngine; using UnityEngine.Rendering; From 69f67d9075cee4ceebaf0705b97f56d06a314ace Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 03:57:51 +0900 Subject: [PATCH 166/208] refactor: create TTRt --- .../MultiLayerImageCanvasEditor.cs | 3 +- .../Preview/RealTime/PreviewStackManager.cs | 9 +- Editor/TextureStack/DeferredTextureStack.cs | 8 +- Editor/TextureStack/ImmediateTextureStack.cs | 7 +- Editor/Utils/TextureUtility.cs | 5 +- Runtime/Decal/SimpleDecal.cs | 8 +- Runtime/IDomain.cs | 6 +- Runtime/MultiLayerImage/AbstractImageLayer.cs | 3 +- Runtime/MultiLayerImage/AbstractLayer.cs | 3 +- .../MultiLayerImage/MultiLayerImageCanvas.cs | 50 +++++----- .../SpecialLayer/LevelAdjustmentLayer.cs | 41 +++++---- Runtime/TextureAtlas/AtlasTexture.cs | 19 ++-- TexTransCore/AsyncTexture2D.cs | 2 +- TexTransCore/BlendTexture/TextureBlend.cs | 40 ++++---- TexTransCore/Decal/DecalContext.cs | 5 +- TexTransCore/TTRt.cs | 92 +++++++++++++++++++ TexTransCore/TTRt.cs.meta | 11 +++ TexTransCore/TransTexture.cs | 6 +- TexTransCore/Utils/TextureUtility.cs | 17 ++-- 19 files changed, 218 insertions(+), 117 deletions(-) create mode 100644 TexTransCore/TTRt.cs create mode 100644 TexTransCore/TTRt.cs.meta diff --git a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs index b2debba1..71c2776b 100644 --- a/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs +++ b/Editor/Inspector/MultiLayerImage/MultiLayerImageCanvasEditor.cs @@ -2,6 +2,7 @@ using net.rs64.TexTransTool.MultiLayerImage; using UnityEngine; using net.rs64.TexTransTool.Preview; +using net.rs64.TexTransCore; namespace net.rs64.TexTransTool.Editor.MultiLayerImage { [CustomEditor(typeof(MultiLayerImageCanvas))] @@ -37,7 +38,7 @@ public static void DrawPreviewMLIC(Rect previewArea, MultiLayerImageCanvas mlic) texManager.DestroyDeferred(); EditorGUI.DrawTextureTransparent(previewArea, canvasResult, ScaleMode.ScaleToFit); - RenderTexture.ReleaseTemporary(canvasResult); + TTRt.R(canvasResult); } diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs b/Editor/Preview/RealTime/PreviewStackManager.cs index c60351aa..ecbeda2c 100644 --- a/Editor/Preview/RealTime/PreviewStackManager.cs +++ b/Editor/Preview/RealTime/PreviewStackManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using net.rs64.TexTransCore; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; @@ -104,7 +105,7 @@ internal class PrioritizedDeferredStack public PrioritizedDeferredStack(Texture2D initialTexture) { _initialTexture = initialTexture; - _stackViewTexture = RenderTexture.GetTemporary(initialTexture.width, initialTexture.height, 0); + _stackViewTexture = TTRt.G(initialTexture.width, initialTexture.height); Graphics.Blit(initialTexture, _stackViewTexture); } @@ -119,15 +120,15 @@ public void ReleaseStackOfPriority(int priority) if (!_stack.ContainsKey(priority)) { return; } var cs = _stack[priority]; - foreach (var l in cs) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); UpdateNeeded = true; } } + foreach (var l in cs) { if (l.Texture is RenderTexture rt) { TTRt.R(rt); UpdateNeeded = true; } } cs.Clear(); } public void ReleaseStack() { - RenderTexture.ReleaseTemporary(_stackViewTexture); + TTRt.R(_stackViewTexture); _stackViewTexture = null; foreach (var ptl in _stack) - foreach (var l in ptl.Value) { if (l.Texture is RenderTexture rt) { RenderTexture.ReleaseTemporary(rt); } } + foreach (var l in ptl.Value) { if (l.Texture is RenderTexture rt) { TTRt.R(rt); } } } public void StackViewUpdate() diff --git a/Editor/TextureStack/DeferredTextureStack.cs b/Editor/TextureStack/DeferredTextureStack.cs index 9141ef89..b0ea8e34 100644 --- a/Editor/TextureStack/DeferredTextureStack.cs +++ b/Editor/TextureStack/DeferredTextureStack.cs @@ -5,6 +5,7 @@ using System.Linq; using UnityEditor; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; +using net.rs64.TexTransCore; namespace net.rs64.TexTransTool.TextureStack { @@ -18,17 +19,16 @@ internal class DeferredTextureStack : AbstractTextureStack public override Texture2D MergeStack() { if (!StackTextures.Any()) { return FirstTexture; } - var renderTexture = RenderTexture.GetTemporary(FirstTexture.width, FirstTexture.height, 0); - renderTexture.Clear(); + var renderTexture = TTRt.G(FirstTexture.width, FirstTexture.height, true); TextureManager.WriteOriginalTexture(FirstTexture, renderTexture); renderTexture.BlendBlit(StackTextures); - foreach (var bTex in StackTextures) { if (bTex.Texture is RenderTexture rt && !AssetDatabase.Contains(rt)) { RenderTexture.ReleaseTemporary(rt); } } + foreach (var bTex in StackTextures) { if (bTex.Texture is RenderTexture rt && !AssetDatabase.Contains(rt)) { TTRt.R(rt); } } var resultTex = renderTexture.CopyTexture2D().CopySetting(FirstTexture, false); resultTex.name = FirstTexture.name + "_MergedStack"; TextureManager.DeferInheritTextureCompress(FirstTexture, resultTex); - RenderTexture.ReleaseTemporary(renderTexture); + TTRt.R(renderTexture); return resultTex; } } diff --git a/Editor/TextureStack/ImmediateTextureStack.cs b/Editor/TextureStack/ImmediateTextureStack.cs index 13139ad8..bf968965 100644 --- a/Editor/TextureStack/ImmediateTextureStack.cs +++ b/Editor/TextureStack/ImmediateTextureStack.cs @@ -4,6 +4,7 @@ using UnityEditor; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; using net.rs64.TexTransCore.BlendTexture; +using net.rs64.TexTransCore; namespace net.rs64.TexTransTool.TextureStack { @@ -17,7 +18,7 @@ public override void init(Texture2D firstTexture, ITextureManager textureManager using (new RTActiveSaver()) { - renderTexture = RenderTexture.GetTemporary(FirstTexture.width, FirstTexture.height, 0); + renderTexture = TTRt.G(FirstTexture.width, FirstTexture.height); textureManager.WriteOriginalTexture(FirstTexture, renderTexture);//解像度は維持しないといけないが、VRAM上の圧縮は外さないといけない } } @@ -27,7 +28,7 @@ public override void AddStack(BlendTex blendTexturePair) renderTexture.BlendBlit(blendTexturePair.Texture, blendTexturePair.BlendTypeKey); if (blendTexturePair.Texture is RenderTexture rt && !AssetDatabase.Contains(rt)) - { RenderTexture.ReleaseTemporary(rt); } + { TTRt.R(rt); } } public override Texture2D MergeStack() @@ -37,7 +38,7 @@ public override Texture2D MergeStack() TextureManager.DeferInheritTextureCompress(FirstTexture, resultTex); - RenderTexture.ReleaseTemporary(renderTexture); + TTRt.R(renderTexture); return resultTex; } } diff --git a/Editor/Utils/TextureUtility.cs b/Editor/Utils/TextureUtility.cs index d751a2b3..2375fe2b 100644 --- a/Editor/Utils/TextureUtility.cs +++ b/Editor/Utils/TextureUtility.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.Utils; using UnityEditor; using UnityEngine; @@ -86,10 +87,10 @@ public static Texture2D CloneTexture2D(this Texture2D texture2D) } else { - var newRt = RenderTexture.GetTemporary(texture2D.width, texture2D.height, 0); + var newRt = TTRt.G(texture2D.width, texture2D.height); Graphics.Blit(texture2D, newRt); var cloneTex = newRt.CopyTexture2D().CopySetting(texture2D); - RenderTexture.ReleaseTemporary(newRt); + TTRt.R(newRt); return cloneTex; } } diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index a6f5e2c1..8bfba497 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -83,15 +83,15 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan if (sourceDecalTexture != null) { var decalSourceSize = textureManager.GetOriginalTextureSize(sourceDecalTexture); - mulDecalTexture = RenderTexture.GetTemporary(decalSourceSize, decalSourceSize, 0); + mulDecalTexture = TTRt.G(decalSourceSize, decalSourceSize); } - else { mulDecalTexture = RenderTexture.GetTemporary(32, 32, 0); } + else { mulDecalTexture = TTRt.G(32, 32); } mulDecalTexture.Clear(); if (sourceDecalTexture != null) { var tempRt = textureManager.GetOriginTempRt(sourceDecalTexture); TextureBlend.MultipleRenderTexture(mulDecalTexture, tempRt, color); - RenderTexture.ReleaseTemporary(tempRt); + TTRt.R(tempRt); } else { @@ -144,7 +144,7 @@ internal Dictionary CompileDecal(ITextureManager textur decalContext.WriteDecalTexture(decalCompiledRenderTextures, renderer, mulDecalTexture); Profiler.EndSample(); } - RenderTexture.ReleaseTemporary(mulDecalTexture); + TTRt.R(mulDecalTexture); return decalCompiledRenderTextures; } diff --git a/Runtime/IDomain.cs b/Runtime/IDomain.cs index 267904af..c4315445 100644 --- a/Runtime/IDomain.cs +++ b/Runtime/IDomain.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using net.rs64.TexTransCore; using net.rs64.TexTransCore.Island; using net.rs64.TexTransCore.Utils; using net.rs64.TexTransTool.MultiLayerImage; @@ -62,16 +63,15 @@ public static void transferAssets(this IDomain domain, IEnumerable new CanvasContext(CanvasSize, TextureManager); @@ -130,7 +131,7 @@ public void AddLayer(BlendRenderTexture blendLayer, LayerAlphaMod layerAlphaMod, _nowClippingTarget.DrawOnClipping(blendLayer.ToEval()); } - else { RenderTexture.ReleaseTemporary(blendLayer.Texture); layerAlphaMod.Dispose(); return; } + else { TTRt.R(blendLayer.Texture); layerAlphaMod.Dispose(); return; } } else { @@ -218,14 +219,14 @@ void CompositeClippingTarget()//使った後はちゃんと _nowClippingTarget internal static void DrawOnClipping(BlendRenderTexture drawTargetLayer, IEvaluateBlending clippingLayer) { var targetRt = drawTargetLayer.Texture; - var swap = RenderTexture.GetTemporary(targetRt.descriptor); + var swap = TTRt.G(targetRt.descriptor); Graphics.CopyTexture(targetRt, swap); TextureBlend.AlphaOne(targetRt); clippingLayer.EvalDrawCanvas(targetRt); TextureBlend.AlphaCopy(swap, targetRt); - RenderTexture.ReleaseTemporary(swap); + TTRt.R(swap); } public LayerScopeUsingStruct UsingLayerScope(LayerAlphaMod layerAlphaMod) { EnterLayerScope(layerAlphaMod); return new(this); } @@ -238,7 +239,7 @@ private void EnterLayerScope(LayerAlphaMod layerAlphaMod) private RenderTexture GetTempRtMask() { - var rt = RenderTexture.GetTemporary(_canvas.descriptor); + var rt = TTRt.G(_canvas.descriptor); TextureBlend.ColorBlit(rt, Color.white); return rt; } @@ -256,7 +257,7 @@ private void ExitLayerScope() } internal static void LayerAlphaAnd(ref LayerAlphaMod target, LayerAlphaMod and) { - if (target.Mask == null) { target.Mask = RenderTexture.GetTemporary(and.Mask.descriptor); TextureBlend.ColorBlit(target.Mask, Color.white); } + if (target.Mask == null) { target.Mask = TTRt.G(and.Mask.descriptor); TextureBlend.ColorBlit(target.Mask, Color.white); } if (and.Mask != null) { TextureBlend.MaskDrawRenderTexture(target.Mask, and.Mask); } target.Opacity *= and.Opacity; @@ -300,7 +301,7 @@ public void AddLayer(BlendRenderTexture blendLayer, LayerAlphaMod layerAlphaMod, return; } - else { RenderTexture.ReleaseTemporary(blendLayer.Texture); layerAlphaMod.Dispose(); return; } + else { TTRt.R(blendLayer.Texture); layerAlphaMod.Dispose(); return; } } else { @@ -362,7 +363,7 @@ public LayerAlphaMod(RenderTexture mask, float opacity)//Temp以外入れない public void Dispose() { - RenderTexture.ReleaseTemporary(Mask); + TTRt.R(Mask); Mask = null; } } @@ -443,7 +444,7 @@ public void EvalDrawCanvas(RenderTexture canvas) } public void Dispose() { - RenderTexture.ReleaseTemporary(_blendRenderTexture.Texture); + TTRt.R(_blendRenderTexture.Texture); _blendRenderTexture.Texture = null; } } @@ -475,27 +476,24 @@ public void Dispose() internal static void GrabImpl(RenderTexture target, Action GrabCanvasModifiedAction, LayerAlphaMod layerAlphaMod, string blendTypeKey) { - var grabRt = RenderTexture.GetTemporary(target.descriptor); - var writeRt = RenderTexture.GetTemporary(target.descriptor); writeRt.Clear(); - - Graphics.CopyTexture(target, grabRt); - TextureBlend.AlphaOne(grabRt); - - GrabCanvasModifiedAction.Invoke(grabRt, writeRt); + using (TTRt.U(out var grabRt, target.descriptor)) + using (TTRt.U(out var writeRt, target.descriptor, true)) + using (TTRt.U(out var alphaBackup, target.descriptor)) + { + Graphics.CopyTexture(target, grabRt); + TextureBlend.AlphaOne(grabRt); - var blendGrabbedLayer = new BlendRenderTexture(writeRt, blendTypeKey); - LayerCanvas.AlphaModApply(blendGrabbedLayer, layerAlphaMod); + GrabCanvasModifiedAction.Invoke(grabRt, writeRt); - var alphaBackup = RenderTexture.GetTemporary(target.descriptor); - Graphics.CopyTexture(target, alphaBackup); + var blendGrabbedLayer = new BlendRenderTexture(writeRt, blendTypeKey); + LayerCanvas.AlphaModApply(blendGrabbedLayer, layerAlphaMod); - AlphaOne(target); - target.BlendBlit(blendGrabbedLayer); - AlphaCopy(alphaBackup, target); + Graphics.CopyTexture(target, alphaBackup); - RenderTexture.ReleaseTemporary(alphaBackup); - RenderTexture.ReleaseTemporary(grabRt); - RenderTexture.ReleaseTemporary(writeRt); + AlphaOne(target); + target.BlendBlit(blendGrabbedLayer); + AlphaCopy(alphaBackup, target); + } } } diff --git a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs index 4a4c909b..c1ff786b 100644 --- a/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs +++ b/Runtime/MultiLayerImage/SpecialLayer/LevelAdjustmentLayer.cs @@ -1,4 +1,5 @@ using System; +using net.rs64.TexTransCore; using UnityEngine; namespace net.rs64.TexTransTool.MultiLayerImage { @@ -16,32 +17,32 @@ public class LevelAdjustmentLayer : AbstractGrabLayer public override void GetImage(RenderTexture grabSource, RenderTexture writeTarget, IOriginTexture originTexture) { var mat = new Material(SpecialLayerShaders.LevelAdjustmentShader); - var tempRt = RenderTexture.GetTemporary(grabSource.descriptor); - - mat.EnableKeyword("RGB"); - RGB.SetMaterialProperty(mat); - Graphics.Blit(grabSource, tempRt, mat); - mat.DisableKeyword("RGB"); + using (TTRt.U(out var tempRt, grabSource.descriptor)) + { - // Graphics.CopyTexture(tempRt, WriteTarget); + mat.EnableKeyword("RGB"); + RGB.SetMaterialProperty(mat); + Graphics.Blit(grabSource, tempRt, mat); + mat.DisableKeyword("RGB"); - mat.EnableKeyword("Red"); - Red.SetMaterialProperty(mat); - Graphics.Blit(tempRt, writeTarget, mat); - mat.DisableKeyword("Red"); + // Graphics.CopyTexture(tempRt, WriteTarget); - mat.EnableKeyword("Green"); - Green.SetMaterialProperty(mat); - Graphics.Blit(writeTarget, tempRt, mat); - mat.DisableKeyword("Green"); + mat.EnableKeyword("Red"); + Red.SetMaterialProperty(mat); + Graphics.Blit(tempRt, writeTarget, mat); + mat.DisableKeyword("Red"); - mat.EnableKeyword("Blue"); - Blue.SetMaterialProperty(mat); - Graphics.Blit(tempRt, writeTarget, mat); - mat.DisableKeyword("Blue"); + mat.EnableKeyword("Green"); + Green.SetMaterialProperty(mat); + Graphics.Blit(writeTarget, tempRt, mat); + mat.DisableKeyword("Green"); + mat.EnableKeyword("Blue"); + Blue.SetMaterialProperty(mat); + Graphics.Blit(tempRt, writeTarget, mat); + mat.DisableKeyword("Blue"); + } UnityEngine.Object.DestroyImmediate(mat); - RenderTexture.ReleaseTemporary(tempRt); } [Serializable] diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index c7a3c40b..859a678a 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -418,11 +418,11 @@ Dictionary ZipDictAndOffset(IEnumerable ZipDictAndOffset(IEnumerable(); @@ -467,8 +467,7 @@ Dictionary ZipDictAndOffset(IEnumerable ZipDictAndOffset(IEnumerable ZipDictAndOffset(IEnumerable() ; + var compressSetting = atlasTexFTData.Value.Find(); if (compressSetting == null) { continue; } var compressSettingTuple = (CompressionQualityApplicant.GetTextureFormat(tex, compressSetting), (int)compressSetting.CompressionQuality); domain.GetTextureManager().DeferTextureCompress(compressSettingTuple, atlasTexFTData.Value.Texture2D); diff --git a/TexTransCore/AsyncTexture2D.cs b/TexTransCore/AsyncTexture2D.cs index 7fdd0d3c..80c80145 100644 --- a/TexTransCore/AsyncTexture2D.cs +++ b/TexTransCore/AsyncTexture2D.cs @@ -109,7 +109,7 @@ public Texture2D GetTexture2D() _outTex.Apply(!_mipsFromRT); Profiler.EndSample(); - RenderTexture.ReleaseTemporary(_rt); + TTRt.R(_rt); Profiler.EndSample(); return _outTex; diff --git a/TexTransCore/BlendTexture/TextureBlend.cs b/TexTransCore/BlendTexture/TextureBlend.cs index 5b332947..c149b70d 100644 --- a/TexTransCore/BlendTexture/TextureBlend.cs +++ b/TexTransCore/BlendTexture/TextureBlend.cs @@ -179,9 +179,8 @@ public static void BlendShadersInit() public static void BlendBlit(this RenderTexture baseRenderTexture, Texture Add, string blendTypeKey, bool keepAlpha = false) { using (new RTActiveSaver()) + using (TTRt.U(out var swap, baseRenderTexture.descriptor)) { - - var swap = RenderTexture.GetTemporary(baseRenderTexture.descriptor); Graphics.CopyTexture(baseRenderTexture, swap); SetTempMatShader(BlendShaders[blendTypeKey]); @@ -194,16 +193,15 @@ public static void BlendBlit(this RenderTexture baseRenderTexture, Texture Add, { if (s_tempMaterial2 == null) { s_tempMaterial2 = new Material(AlphaCopyShader); } if (s_tempMaterial2.shader != AlphaCopyShader) { s_tempMaterial2.shader = AlphaCopyShader; } - var baseSwap = RenderTexture.GetTemporary(baseRenderTexture.descriptor); - s_tempMaterial2.SetTexture("_AlphaTex", swap); - Graphics.CopyTexture(baseRenderTexture, baseSwap); - Graphics.Blit(baseSwap, baseRenderTexture, s_tempMaterial2); + using (TTRt.U(out var baseSwap, baseRenderTexture.descriptor)) + { + s_tempMaterial2.SetTexture("_AlphaTex", swap); + Graphics.CopyTexture(baseRenderTexture, baseSwap); + Graphics.Blit(baseSwap, baseRenderTexture, s_tempMaterial2); + } - RenderTexture.ReleaseTemporary(baseSwap); } - - RenderTexture.ReleaseTemporary(swap); } } private static string EscapeForShaderKeyword(string blendTypeKey) => blendTypeKey.Replace('/', '_'); @@ -217,7 +215,7 @@ public static void BlendBlit(this RenderTexture baseRenderTexture, IEn using (new RTActiveSaver()) { Profiler.BeginSample("Create RT"); - var temRt = RenderTexture.GetTemporary(baseRenderTexture.descriptor); + var temRt = TTRt.G(baseRenderTexture.descriptor); Profiler.EndSample(); var swap = baseRenderTexture; @@ -238,7 +236,7 @@ public static void BlendBlit(this RenderTexture baseRenderTexture, IEn { Graphics.Blit(swap, baseRenderTexture); } - RenderTexture.ReleaseTemporary(temRt); + TTRt.R(temRt); } Profiler.EndSample(); } @@ -246,7 +244,7 @@ public static RenderTexture BlendBlit(Texture2D baseRenderTexture, Texture add, { using (new RTActiveSaver()) { - if (targetRt == null) { targetRt = RenderTexture.GetTemporary(baseRenderTexture.width, baseRenderTexture.height, 0); } + if (targetRt == null) { targetRt = TTRt.G(baseRenderTexture.width, baseRenderTexture.height); } Graphics.Blit(baseRenderTexture, targetRt); targetRt.BlendBlit(add, blendTypeKey); return targetRt; @@ -287,7 +285,7 @@ public BlendTexturePair(Texture texture, string blendTypeKey) public static RenderTexture CreateMultipliedRenderTexture(Texture mainTex, Color color) { - var mainTexRt = RenderTexture.GetTemporary(mainTex.width, mainTex.height, 0); + var mainTexRt = TTRt.G(mainTex.width, mainTex.height); MultipleRenderTexture(mainTexRt, mainTex, color); return mainTexRt; } @@ -304,24 +302,24 @@ public static void MultipleRenderTexture(RenderTexture renderTexture, Color colo { using (new RTActiveSaver()) { - var tempRt = RenderTexture.GetTemporary(renderTexture.descriptor); + var tempRt = TTRt.G(renderTexture.descriptor); SetTempMatShader(ColorMulShader); s_tempMaterial.SetColor("_Color", color); Graphics.CopyTexture(renderTexture, tempRt); Graphics.Blit(tempRt, renderTexture, s_tempMaterial); - RenderTexture.ReleaseTemporary(tempRt); + TTRt.R(tempRt); } } public static void MaskDrawRenderTexture(RenderTexture renderTexture, Texture maskTex) { using (new RTActiveSaver()) { - var tempRt = RenderTexture.GetTemporary(renderTexture.descriptor); + var tempRt = TTRt.G(renderTexture.descriptor); SetTempMatShader(MaskShader); s_tempMaterial.SetTexture("_MaskTex", maskTex); Graphics.CopyTexture(renderTexture, tempRt); Graphics.Blit(tempRt, renderTexture, s_tempMaterial); - RenderTexture.ReleaseTemporary(tempRt); + TTRt.R(tempRt); } } @@ -341,10 +339,10 @@ public static void AlphaOne(RenderTexture rt) { SetTempMatShader(AlphaCopyShader); s_tempMaterial.SetTexture("_AlphaTex", Texture2D.whiteTexture); - var swap = RenderTexture.GetTemporary(rt.descriptor); + var swap = TTRt.G(rt.descriptor); Graphics.CopyTexture(rt, swap); Graphics.Blit(swap, rt, s_tempMaterial); - RenderTexture.ReleaseTemporary(swap); + TTRt.R(swap); } } public static void AlphaCopy(RenderTexture alphaSource, RenderTexture rt) @@ -353,10 +351,10 @@ public static void AlphaCopy(RenderTexture alphaSource, RenderTexture rt) { SetTempMatShader(AlphaCopyShader); s_tempMaterial.SetTexture("_AlphaTex", alphaSource); - var swap = RenderTexture.GetTemporary(rt.descriptor); + var swap = TTRt.G(rt.descriptor); Graphics.CopyTexture(rt, swap); Graphics.Blit(swap, rt, s_tempMaterial); - RenderTexture.ReleaseTemporary(swap); + TTRt.R(swap); } } } diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs index 1ff423fd..5e243039 100644 --- a/TexTransCore/Decal/DecalContext.cs +++ b/TexTransCore/Decal/DecalContext.cs @@ -84,7 +84,7 @@ internal void WriteDecalTexture(Dictionary renderTextur Profiler.EndSample(); if (filteredTriangle.Length == 0) { continue; } - if (!renderTextures.ContainsKey(targetMat)) { renderTextures[targetMat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); renderTextures[targetMat].Clear(); } + if (!renderTextures.ContainsKey(targetMat)) { renderTextures[targetMat] = TTRt.G(targetTexture.width, targetTexture.height, true); renderTextures[targetMat].Clear(); } var sUV = _convertSpace.OutPutUV(); @@ -114,8 +114,7 @@ internal void GenerateKey(Dictionary writeable, IEnumer var targetTexture = mat.GetTexture(TargetPropertyName); if (targetTexture == null) { continue; } - var rt = writeable[mat] = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 32); - rt.Clear(); + var rt = writeable[mat] = TTRt.G(targetTexture.width, targetTexture.height, true, true); } } } diff --git a/TexTransCore/TTRt.cs b/TexTransCore/TTRt.cs new file mode 100644 index 00000000..67b35129 --- /dev/null +++ b/TexTransCore/TTRt.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using net.rs64.TexTransCore.Utils; +using UnityEngine; + +namespace net.rs64.TexTransCore +{ + internal static class TTRt + { + public static RenderTextureFormat RenderTextureDefaultFormat = RenderTextureFormat.ARGB32; + + public static RenderTexture G(int size) => G(size, size); + public static UsingRenderTexture U(out RenderTexture tmpRt, int size) + { + tmpRt = G(size); + return new(tmpRt); + } + public static RenderTexture G(int width, int height, bool clearRt = false, bool useDepthAndStencil = false, bool useMipMap = false, bool useRandomRW = false, RenderTextureFormat? rtFormat = null) + { + var depth = useDepthAndStencil ? 32 : 0; + var format = rtFormat ?? RenderTextureDefaultFormat; + + var tmpRt = RenderTexture.GetTemporary(width, height, depth, format); + s_tempSet.Add(tmpRt); + + + tmpRt.useMipMap = useMipMap; + tmpRt.autoGenerateMips = false; + + if (useRandomRW && tmpRt.enableRandomWrite != useRandomRW) + { + if (tmpRt.IsCreated()) { tmpRt.Release(); } + tmpRt.enableRandomWrite = useRandomRW; + } + + if (clearRt) tmpRt.Clear(); + + return tmpRt; + } + public static UsingRenderTexture U(out RenderTexture tmpRt, int width, int height, bool clearRt = false, bool useDepthAndStencil = false, bool useMipMap = false, bool useRandomRW = false, RenderTextureFormat? rtFormat = null) + { + tmpRt = G(width, height, clearRt, useDepthAndStencil, useMipMap, useRandomRW, rtFormat); + return new(tmpRt); + } + public static RenderTexture G(RenderTexture rt, bool copyTexture = false) + { + var newRt = RenderTexture.GetTemporary(rt.descriptor); + s_tempSet.Add(newRt); + newRt.CopyFilWrap(rt); + if (copyTexture) Graphics.CopyTexture(rt, newRt); + return newRt; + } + public static UsingRenderTexture U(out RenderTexture tmpRt, RenderTexture rt, bool copyTexture = false) + { + tmpRt = G(rt, copyTexture); return new(tmpRt); + } + public static RenderTexture G(RenderTextureDescriptor renderTextureDescriptor, bool clearRt = false) + { + var rt = RenderTexture.GetTemporary(renderTextureDescriptor); + s_tempSet.Add(rt); + if (clearRt) rt.Clear(); + return rt; + } + public static UsingRenderTexture U(out RenderTexture tmpRt, RenderTextureDescriptor renderTextureDescriptor, bool clearRt = false) + { + tmpRt = G(renderTextureDescriptor, clearRt); return new(tmpRt); + } + + + internal static HashSet s_tempSet = new(); + + public static void R(RenderTexture renderTexture) + { + RenderTexture.ReleaseTemporary(renderTexture); + s_tempSet.Remove(renderTexture); + } + + public static void ForceLeakedRelease() + { + foreach (var rt in s_tempSet) { RenderTexture.ReleaseTemporary(rt); } + s_tempSet.Clear(); + } + + + public readonly struct UsingRenderTexture : IDisposable + { + readonly RenderTexture _rt; + public UsingRenderTexture(RenderTexture rt) { _rt = rt; } + public void Dispose() { R(_rt); } + } + } +} diff --git a/TexTransCore/TTRt.cs.meta b/TexTransCore/TTRt.cs.meta new file mode 100644 index 00000000..6997e7c9 --- /dev/null +++ b/TexTransCore/TTRt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18f48dfc6032569468e9752885d213eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/TexTransCore/TransTexture.cs b/TexTransCore/TransTexture.cs index 49b4ccd6..2d8be1bb 100644 --- a/TexTransCore/TransTexture.cs +++ b/TexTransCore/TransTexture.cs @@ -203,8 +203,8 @@ public static void ForTrans( if (depthInvert.HasValue) { - depthRt = RenderTexture.GetTemporary(targetTexture.width, targetTexture.height, 8, RenderTextureFormat.RFloat); - depthRt.Clear(); + depthRt = TTRt.G(targetTexture.width, targetTexture.height, true, true, rtFormat: RenderTextureFormat.RFloat); + s_transMat.EnableKeyword(depthInvert.Value ? "InvertDepth" : "DepthDecal"); using (new RTActiveSaver()) @@ -251,7 +251,7 @@ public static void ForTrans( sourceTexture.mipMapBias = preBias; sourceTexture.wrapMode = preWarp; UnityEngine.Object.DestroyImmediate(mesh); - if (depthRt != null) { RenderTexture.ReleaseTemporary(depthRt); } + if (depthRt != null) { TTRt.R(depthRt); } } } public static void ForTrans( diff --git a/TexTransCore/Utils/TextureUtility.cs b/TexTransCore/Utils/TextureUtility.cs index 815d199d..aacdadea 100644 --- a/TexTransCore/Utils/TextureUtility.cs +++ b/TexTransCore/Utils/TextureUtility.cs @@ -74,14 +74,14 @@ public static Texture2D ResizeTexture(Texture2D source, Vector2Int size) using (new RTActiveSaver()) { var useMip = source.mipmapCount > 1; - var rt = RenderTexture.GetTemporary(size.x, size.y); rt.Clear(); + var rt = TTRt.G(size.x, size.y, true); if (useMip) { Graphics.Blit(source, rt); } else { - var mipRt = RenderTexture.GetTemporary(source.width, source.height); + var mipRt = TTRt.G(source.width, source.height); mipRt.Release(); var preValue = (mipRt.useMipMap, mipRt.autoGenerateMips); @@ -94,13 +94,13 @@ public static Texture2D ResizeTexture(Texture2D source, Vector2Int size) mipRt.Release(); (mipRt.useMipMap, mipRt.autoGenerateMips) = preValue; - RenderTexture.ReleaseTemporary(mipRt); + TTRt.R(mipRt); } var resizedTexture = rt.CopyTexture2D(overrideUseMip: useMip); resizedTexture.name = source.name + "_Resized_" + size.x.ToString(); - RenderTexture.ReleaseTemporary(rt); + TTRt.R(rt); Profiler.EndSample(); return resizedTexture; @@ -117,7 +117,7 @@ public static Texture2D CreateColorTex(Color color) } public static RenderTexture CreateColorTexForRT(Color color) { - var rt = RenderTexture.GetTemporary(1, 1, 0); + var rt = TTRt.G(1); TextureBlend.ColorBlit(rt, color); return rt; } @@ -138,10 +138,7 @@ public static Texture2D CreateFillTexture(Vector2Int size, Color fillColor) public static RenderTexture CloneTemp(this RenderTexture renderTexture) { - var newTemp = RenderTexture.GetTemporary(renderTexture.descriptor); - newTemp.CopyFilWrap(renderTexture); - Graphics.CopyTexture(renderTexture, newTemp); - return newTemp; + return TTRt.G(renderTexture, true); } internal static void CopyFilWrap(this Texture t, Texture s) @@ -179,7 +176,7 @@ public static void ApplyTextureST(this RenderTexture rt, Vector2 s, Vector2 t) { var tmp = rt.CloneTemp(); ApplyTextureST(tmp, s, t, rt); - RenderTexture.ReleaseTemporary(tmp); + TTRt.R(tmp); } From 8596fb2111205b6eec21643fff22b2ae56917325 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 12:15:01 +0900 Subject: [PATCH 167/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63dbff75..b0dc9a37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - SizeOffset は廃止され、SizePriority に変更されました (#431) - AtlasTexture のプロパティの並び順が変更されました (#431) +- 内部的に使用される RenderTexture の形式が Win Linux Mac にかかわらず ARGB32 を使用するように変更されました (#461) ### Removed From 7f2448ae20e72a2740925d92d0ff56b20186f88d Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 12:19:33 +0900 Subject: [PATCH 168/208] chore: fix changelog --- CHANGELOG-EXPERIMENTAL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index f3c754dd..1fa20684 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -33,7 +33,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - IslandSelector が使用できるようになったことに伴い SimpleDecal の IslandCulling は削除されました (#422) - ObjectReplaceInvoke は削除されました (#438) - CylindricalDecal , CylindricalCurveDecal , CylindricalCoordinatesSystem , NailEditor , NailOffsetData は削除されました (#449) -- MatAndTexAbsoluteSeparator , MatAndTexRelativeSeparator , MaterialModifierEditor は削除されました (#456) +- MatAndTexAbsoluteSeparator , MatAndTexRelativeSeparator , MaterialModifier は削除されました (#456) ### Fixed From 48a6fdac44e3465114b080e8615f1c1880e8e43f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 12:48:35 +0900 Subject: [PATCH 169/208] fix: ColorSpace inspector --- .../TextureAtlas/TextureFineTuning/ColorSpaceTuningDrawer.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Editor/Inspector/TextureAtlas/TextureFineTuning/ColorSpaceTuningDrawer.cs b/Editor/Inspector/TextureAtlas/TextureFineTuning/ColorSpaceTuningDrawer.cs index 66a91f2d..a3a76178 100644 --- a/Editor/Inspector/TextureAtlas/TextureFineTuning/ColorSpaceTuningDrawer.cs +++ b/Editor/Inspector/TextureAtlas/TextureFineTuning/ColorSpaceTuningDrawer.cs @@ -17,11 +17,11 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten var sSelect = property.FindPropertyRelative("Select"); var sPropertyNames = property.FindPropertyRelative("PropertyNames"); var sLinear = property.FindPropertyRelative("Linear"); - EditorGUI.PropertyField(position, sSelect, "TextureFineTuning:prop:Linear".Glc()); + EditorGUI.PropertyField(position, sLinear, "TextureFineTuning:prop:Linear".Glc()); position.y += 18; EditorGUI.PropertyField(position, sPropertyNames, "TextureFineTuning:prop:TargetPropertyName".Glc()); position.y += 18; - EditorGUI.PropertyField(position, sLinear, "TextureFineTuning:prop:Select".Glc()); + EditorGUI.PropertyField(position, sSelect, "TextureFineTuning:prop:Select".Glc()); position.y += 18; } From 5dd3a146bcd1877fdccc823cfd5b49177c944999 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 12:50:39 +0900 Subject: [PATCH 170/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0dc9a37..e6a238f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture でサブメッシュを超えて同一の頂点を使用するメッシュを正しくアトラス化できない問題を修正 (#431) - AtlasTexture の「適用時に非アクティブなレンダラーを含める」が有効な時、非アクティブなレンダラーのマテリアルが選択肢に表示されない問題を修正 (#431) - AtlasTexture で大きさが完全に 0 のアイランドが存在するメッシュの UV を正しく操作できていない問題を修正 (#446) +- AtlasTexture の テクスチャ詳細設定で、色空間 のUIが正しく表示されていない問題を修正 (#462) ### Deprecated From 72dcc16749a5c132267d4fa8ebf80df9042b687f Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 14:17:35 +0900 Subject: [PATCH 171/208] fix: decal use a depth and stencil --- TexTransCore/Decal/DecalContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs index 5e243039..38600d1d 100644 --- a/TexTransCore/Decal/DecalContext.cs +++ b/TexTransCore/Decal/DecalContext.cs @@ -84,7 +84,7 @@ internal void WriteDecalTexture(Dictionary renderTextur Profiler.EndSample(); if (filteredTriangle.Length == 0) { continue; } - if (!renderTextures.ContainsKey(targetMat)) { renderTextures[targetMat] = TTRt.G(targetTexture.width, targetTexture.height, true); renderTextures[targetMat].Clear(); } + if (!renderTextures.ContainsKey(targetMat)) { renderTextures[targetMat] = TTRt.G(targetTexture.width, targetTexture.height, true, true); } var sUV = _convertSpace.OutPutUV(); From 147f1a4e989e70938f89b75e4b71aff2125f75e7 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 14:33:28 +0900 Subject: [PATCH 172/208] fix: TransTexture can not use MipMap --- TexTransCore/TransTexture.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/TexTransCore/TransTexture.cs b/TexTransCore/TransTexture.cs index 2d8be1bb..9bb58b99 100644 --- a/TexTransCore/TransTexture.cs +++ b/TexTransCore/TransTexture.cs @@ -161,8 +161,6 @@ public static void ForTrans( var mesh = transUVData.GenerateTransMesh(); Profiler.EndSample(); - var preBias = sourceTexture.mipMapBias; - sourceTexture.mipMapBias = sourceTexture.mipmapCount * -1; var preWarp = sourceTexture.wrapMode; RenderTexture depthRt = null; @@ -248,7 +246,6 @@ public static void ForTrans( } finally { - sourceTexture.mipMapBias = preBias; sourceTexture.wrapMode = preWarp; UnityEngine.Object.DestroyImmediate(mesh); if (depthRt != null) { TTRt.R(depthRt); } From dd4547fe8a5b6b79ed5a7b7bbbce656260830594 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 14:34:02 +0900 Subject: [PATCH 173/208] fix: AtlasTexture can not use MipMap --- Runtime/TextureAtlas/AtlasTexture.cs | 40 +++++++++++++++++++--------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index 859a678a..dc56ca9b 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -14,6 +14,7 @@ using Unity.Collections; using net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject; using UnityEngine.Profiling; +using net.rs64.TexTransCore.MipMap; namespace net.rs64.TexTransTool.TextureAtlas { @@ -333,6 +334,16 @@ bool TryCompileAtlasTextures(IDomain domain, out AtlasData atlasData) Dictionary> GetGroupedTextures(AtlasContext atlasContext, PropertyBakeSetting propertyBakeSetting, out HashSet property) { + static RenderTexture GetOriginAtUseMip(ITextureManager texManage, Texture2D atlasTex) + { + var originSize = texManage.GetOriginalTextureSize(atlasTex); + var rt = TTRt.G(originSize, originSize, true, false, true, true); + rt.CopyFilWrap(atlasTex); + rt.filterMode = FilterMode.Trilinear; + texManage.WriteOriginalTexture(atlasTex, rt); + return rt; + } + var downScalingAlgorism = DownScalingAlgorism.Average; switch (propertyBakeSetting) { default: { property = null; return null; } @@ -353,21 +364,18 @@ Dictionary ZipDictAndOffset(IEnumerable i.Value.Texture2D != null) == false) { continue; } var atlasTex = kv.First(i => i.Value.Texture2D != null).Value; - if (atlasTex.TextureScale == Vector2.one && atlasTex.TextureTranslation == Vector2.zero) - { - dict[kv.Key] = texManage.GetOriginTempRt(atlasTex.Texture2D); - } - else - { - var tex = atlasTex.Texture2D; - var originTex = texManage.GetOriginTempRt(tex); - originTex.ApplyTextureST(atlasTex.TextureScale, atlasTex.TextureTranslation); + var rt = GetOriginAtUseMip(texManage, atlasTex.Texture2D); - dict[kv.Key] = originTex; - } + if (atlasTex.TextureScale != Vector2.one || atlasTex.TextureTranslation != Vector2.zero) + { rt.ApplyTextureST(atlasTex.TextureScale, atlasTex.TextureTranslation); } + + MipMapUtility.GenerateMips(rt, downScalingAlgorism); + dict[kv.Key] = rt; } return dict; + + } } case PropertyBakeSetting.Bake: @@ -412,13 +420,18 @@ Dictionary ZipDictAndOffset(IEnumerable ZipDictAndOffset(IEnumerable Date: Sun, 5 May 2024 14:40:47 +0900 Subject: [PATCH 174/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6a238f1..30cf69c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture の「適用時に非アクティブなレンダラーを含める」が有効な時、非アクティブなレンダラーのマテリアルが選択肢に表示されない問題を修正 (#431) - AtlasTexture で大きさが完全に 0 のアイランドが存在するメッシュの UV を正しく操作できていない問題を修正 (#446) - AtlasTexture の テクスチャ詳細設定で、色空間 のUIが正しく表示されていない問題を修正 (#462) +- AtlasTexture でテクスチャが縮小される場合に MipMap を使用していない問題を修正 (#463) ### Deprecated From 52563dee33323112d955d73021469909e226188c Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 5 May 2024 05:42:37 +0000 Subject: [PATCH 175/208] Update package.json v0.7.0-beta.8!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 088d6ccc..5a2aeb58 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.7", + "version": "0.7.0-beta.8", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 7e4f7bc74e49684fec821060cfbde49ecdaff2af Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 21:25:02 +0900 Subject: [PATCH 176/208] fix: _UseReflection correct --- .../liltoon/liltoonAtlasSupport.asset | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index 7ece189e..f21e893f 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -232,7 +232,7 @@ MonoBehaviour: type: {class: TextureReferenceCopy, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - SousePropertyName: _MainTex + SourcePropertyName: _MainTex TargetPropertyName: _BaseMap - rid: 7150698656081904266 type: {class: ContainsName, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, @@ -257,7 +257,7 @@ MonoBehaviour: type: {class: TextureReferenceCopy, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - SousePropertyName: _MainTex + SourcePropertyName: _MainTex TargetPropertyName: _BaseColorMap - rid: 7150698656081904310 type: {class: Anything, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, @@ -547,21 +547,21 @@ MonoBehaviour: type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseRimShade + PropertyName: _UseReflection ComparerValue: 0 Less: 0 - rid: 7150698705470881826 type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseRimShade + PropertyName: _UseReflection ComparerValue: 0 Less: 0 - rid: 7150698705470881827 type: {class: IntPropertyValueGreater, ns: net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject, asm: net.rs64.tex-trans-tool.runtime} data: - PropertyName: _UseRimShade + PropertyName: _UseReflection ComparerValue: 0 Less: 0 - rid: 7150698705470881828 From 0c637660761964b1bec3d30228a8461814e18ee0 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 21:30:40 +0900 Subject: [PATCH 177/208] chore: fix typo in lilToon --- .../AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset index f21e893f..3b79111e 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset +++ b/Runtime/TextureAtlas/AtlasShaderSupport/liltoon/liltoonAtlasSupport.asset @@ -10,7 +10,7 @@ MonoBehaviour: m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: b2369c186c1ab3c44b9ef86b3a8cbccf, type: 3} - m_Name: liltoonAtlasSupport + m_Name: lilToonAtlasSupport m_EditorClassIdentifier: SupportedShaderComparer: rid: 7150698656081904266 From a6ce091080ec97386565353eda4fd30665defe22 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 21:37:32 +0900 Subject: [PATCH 178/208] change: Enable with compress in preview. --- Editor/Domain/AvatarDomain.cs | 8 ++++---- Editor/Domain/RenderersDomain.cs | 10 +++++----- Editor/Domain/TextureManager.cs | 4 ++-- Editor/Preview/OneTimePreviewContext.cs | 4 ++-- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Editor/Domain/AvatarDomain.cs b/Editor/Domain/AvatarDomain.cs index 01bbea9c..b1b9dff5 100644 --- a/Editor/Domain/AvatarDomain.cs +++ b/Editor/Domain/AvatarDomain.cs @@ -18,10 +18,10 @@ namespace net.rs64.TexTransTool /// internal class AvatarDomain : RenderersDomain { - public AvatarDomain(GameObject avatarRoot, bool previewing, bool saveAsset = false) - : this(avatarRoot, previewing, saveAsset ? new AssetSaver() : null) { } - public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver assetSaver) - : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, assetSaver) + public AvatarDomain(GameObject avatarRoot, bool previewing, bool saveAsset = false, bool? useCompress = null) + : this(avatarRoot, previewing, saveAsset ? new AssetSaver() : null, useCompress) { } + public AvatarDomain(GameObject avatarRoot, bool previewing, IAssetSaver assetSaver, bool? useCompress = null) + : base(avatarRoot.GetComponentsInChildren(true).ToList(), previewing, assetSaver, useCompress) { _avatarRoot = avatarRoot; } diff --git a/Editor/Domain/RenderersDomain.cs b/Editor/Domain/RenderersDomain.cs index 7c849bdd..dff0e116 100644 --- a/Editor/Domain/RenderersDomain.cs +++ b/Editor/Domain/RenderersDomain.cs @@ -32,14 +32,14 @@ internal class RenderersDomain : IEditorCallDomain protected Dictionary _replaceMap = new();//New Old - public RenderersDomain(List previewRenderers, bool previewing, bool saveAsset = false) - : this(previewRenderers, previewing, saveAsset ? new AssetSaver() : null) { } - public RenderersDomain(List previewRenderers, bool previewing, IAssetSaver assetSaver) + public RenderersDomain(List previewRenderers, bool previewing, bool saveAsset = false, bool? useCompress = null) + : this(previewRenderers, previewing, saveAsset ? new AssetSaver() : null, useCompress) { } + public RenderersDomain(List previewRenderers, bool previewing, IAssetSaver assetSaver, bool? useCompress = null) { _renderers = previewRenderers; Previewing = previewing; _saver = assetSaver; - _textureManager = new TextureManager(Previewing); + _textureManager = new TextureManager(Previewing, useCompress); _textureStacks = new StackManager(_textureManager); } @@ -142,7 +142,7 @@ public virtual bool OriginEqual(Object l, Object r) Object GetOrigin(Object obj) { - if(obj == null) { return null; } + if (obj == null) { return null; } while (_replaceMap.ContainsKey(obj)) { obj = _replaceMap[obj]; } return obj; } diff --git a/Editor/Domain/TextureManager.cs b/Editor/Domain/TextureManager.cs index 61025fc1..54bfe206 100644 --- a/Editor/Domain/TextureManager.cs +++ b/Editor/Domain/TextureManager.cs @@ -15,11 +15,11 @@ namespace net.rs64.TexTransTool private readonly Dictionary OriginDict; private readonly Dictionary CanvasSource; - public TextureManager(bool previewing) + public TextureManager(bool previewing, bool? useCompress = null) { Previewing = previewing; DestroyList = !Previewing ? new() : null; - CompressDict = !Previewing ? new() : null; + CompressDict = useCompress ?? !Previewing ? new() : null; OriginDict = !Previewing ? new() : null; CanvasSource = !Previewing ? new() : null; } diff --git a/Editor/Preview/OneTimePreviewContext.cs b/Editor/Preview/OneTimePreviewContext.cs index ce8506ef..e96af988 100644 --- a/Editor/Preview/OneTimePreviewContext.cs +++ b/Editor/Preview/OneTimePreviewContext.cs @@ -108,8 +108,8 @@ static void TexTransBehaviorApply(TexTransBehavior targetTTBehavior) var marker = DomainMarkerFinder.FindMarker(targetTTBehavior.gameObject); Profiler.EndSample(); EditorUtility.DisplayProgressBar("Create Domain", "", 0.1f); - if (marker != null) { previewDomain = new AvatarDomain(marker, true, false); } - else { previewDomain = new RenderersDomain(targetTTBehavior.GetRenderers, true, false); } + if (marker != null) { previewDomain = new AvatarDomain(marker, true, false, true); } + else { previewDomain = new RenderersDomain(targetTTBehavior.GetRenderers, true, false, true); } EditorUtility.DisplayProgressBar("Preview Apply", "", 0.2f); //カスタムプレビューとエディターコールビヘイビアは違うから注意 From ff14e0626c9993cc592aaec510f434204a9e6f21 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 21:38:56 +0900 Subject: [PATCH 179/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30cf69c6..683a739f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - SizeOffset は廃止され、SizePriority に変更されました (#431) - AtlasTexture のプロパティの並び順が変更されました (#431) - 内部的に使用される RenderTexture の形式が Win Linux Mac にかかわらず ARGB32 を使用するように変更されました (#461) +- プレビューを行うときに、テクスチャの圧縮が行われるように変更されました (#465) ### Removed From cfd6779d46b5bb0d39c46bdb577b26aaef75b321 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 5 May 2024 22:45:54 +0900 Subject: [PATCH 180/208] fix: crash avoidance for Mac --- Editor/Migration/Migrator.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index 0c38ace2..0cad420c 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -194,13 +194,16 @@ private static bool DoMigrate() { InProgress = true; var result = EditorUtility.DisplayDialog("Migrate!", +#if !UNITY_STANDALONE_OSX @"互換性の持たないTexTransToolのアップグレードが検出されました! 正常な動作のためにはすべてのシーンとプレハブをマイグレーションする必要があります。 プロジェクトが壊れる可能性もあり、長い時間がかかります。 バックアップをしていない場合はバックアップをしてから移行してください。 マイグレーションを完了させない場合、Unityを再起動するたびにこのウィンドウが出現します。 - プロジェクトをマイグレーションしますか?", +"+ +#endif + "プロジェクトをマイグレーションしますか?", "マイグレーションする (Migrate)", "キャンセル (Cancel)"); From b4c1036fbd6f6305fc98b739a25583effd6f8fb2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 13:35:40 +0900 Subject: [PATCH 181/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 683a739f..9ae9e275 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture で大きさが完全に 0 のアイランドが存在するメッシュの UV を正しく操作できていない問題を修正 (#446) - AtlasTexture の テクスチャ詳細設定で、色空間 のUIが正しく表示されていない問題を修正 (#462) - AtlasTexture でテクスチャが縮小される場合に MipMap を使用していない問題を修正 (#463) +- Mac環境でマイグレーションのダイアログが、512Byte以上のマルチバイト文字列であったために、クラッシュする問題の回避を追加 (#466) ### Deprecated From 949364e8b00ef386b7500204ac10a128de472b45 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 13:41:47 +0900 Subject: [PATCH 182/208] fix: optimizing phase not previewing --- Editor/Preview/Custom/TexTransGroupPreview.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Editor/Preview/Custom/TexTransGroupPreview.cs b/Editor/Preview/Custom/TexTransGroupPreview.cs index 51e4e3b9..7277c76e 100644 --- a/Editor/Preview/Custom/TexTransGroupPreview.cs +++ b/Editor/Preview/Custom/TexTransGroupPreview.cs @@ -25,6 +25,7 @@ internal static void ExecutePhases(IEditorCallDomain editorCallDomain, Dictionar foreach (var tf in TexTransGroup.TextureTransformerFilter(phaseOnTf[TexTransPhase.UVModification])) { tf.Apply(editorCallDomain); } foreach (var tf in TexTransGroup.TextureTransformerFilter(phaseOnTf[TexTransPhase.AfterUVModification])) { tf.Apply(editorCallDomain); } foreach (var tf in TexTransGroup.TextureTransformerFilter(phaseOnTf[TexTransPhase.UnDefined])) { tf.Apply(editorCallDomain); } + foreach (var tf in TexTransGroup.TextureTransformerFilter(phaseOnTf[TexTransPhase.Optimizing])) { tf.Apply(editorCallDomain); } } } } From 50e795b5d4a750f3406f3eb5e2ae17883c8fa47b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 14:38:54 +0900 Subject: [PATCH 183/208] feat: IslandSelector IsAll Option --- Runtime/IslandSelect/BoxIslandSelector.cs | 34 +++++++++++++++++--- Runtime/IslandSelect/SphereIslandSelector.cs | 28 +++++++++++++--- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/Runtime/IslandSelect/BoxIslandSelector.cs b/Runtime/IslandSelect/BoxIslandSelector.cs index ceef4d8b..cbdc365f 100644 --- a/Runtime/IslandSelect/BoxIslandSelector.cs +++ b/Runtime/IslandSelect/BoxIslandSelector.cs @@ -13,6 +13,8 @@ public class BoxIslandSelector : AbstractIslandSelector internal const string ComponentName = "TTT BoxIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + public bool IsAll; + internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } internal override int GetDependencyHash() { return 0; } @@ -24,8 +26,16 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) { var description = islandDescription[islandIndex]; + var island = islands[islandIndex]; + + bitArray[islandIndex] = IsAll ? All(island, description) : Some(island, description); + } + + return bitArray; - foreach (var tri in islands[islandIndex].triangles) + bool All(Island island, IslandDescription description) + { + foreach (var tri in island.triangles) { for (var vi = 0; 3 > vi; vi += 1) { @@ -35,14 +45,28 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is isIn &= Mathf.Abs(vert.x) < 0.5f; isIn &= Mathf.Abs(vert.y) < 0.5f; isIn &= Mathf.Abs(vert.z) < 0.5f; - if (isIn) { bitArray[islandIndex] = true; break; } + if (!isIn) { return false; } } - if (bitArray[islandIndex]) { break; } } + return true; } + bool Some(Island island, IslandDescription description) + { + foreach (var tri in island.triangles) + { + for (var vi = 0; 3 > vi; vi += 1) + { + var vert = matrix.MultiplyPoint3x4(description.Position[tri[vi]]); - - return bitArray; + var isIn = true; + isIn &= Mathf.Abs(vert.x) < 0.5f; + isIn &= Mathf.Abs(vert.y) < 0.5f; + isIn &= Mathf.Abs(vert.z) < 0.5f; + if (isIn) { return true; } + } + } + return false; + } } internal override void OnDrawGizmosSelected() diff --git a/Runtime/IslandSelect/SphereIslandSelector.cs b/Runtime/IslandSelect/SphereIslandSelector.cs index a199fb9f..86f7d249 100644 --- a/Runtime/IslandSelect/SphereIslandSelector.cs +++ b/Runtime/IslandSelect/SphereIslandSelector.cs @@ -12,6 +12,8 @@ public class SphereIslandSelector : AbstractIslandSelector { internal const string ComponentName = "TTT SphereIslandSelector"; internal const string MenuPath = FoldoutName + "/" + ComponentName; + public bool IsAll; + internal override IEnumerable GetDependency() { return transform.GetParents().Append(transform); } internal override int GetDependencyHash() { return 0; } internal override BitArray IslandSelect(Island[] islands, IslandDescription[] islandDescription) @@ -22,18 +24,34 @@ internal override BitArray IslandSelect(Island[] islands, IslandDescription[] is for (var islandIndex = 0; islands.Length > islandIndex; islandIndex += 1) { var description = islandDescription[islandIndex]; + var island = islands[islandIndex]; + + bitArray[islandIndex] = IsAll ? All(island, description) : Some(island, description); + } - foreach (var tri in islands[islandIndex].triangles) + return bitArray; + bool All(Island island, IslandDescription description) + { + foreach (var tri in island.triangles) { for (var vi = 0; 3 > vi; vi += 1) { - if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude < 1) { bitArray[islandIndex] = true; break; } + if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude >= 1) { return false; } } - if (bitArray[islandIndex]) { break; } } + return true; + } + bool Some(Island island, IslandDescription description) + { + foreach (var tri in island.triangles) + { + for (var vi = 0; 3 > vi; vi += 1) + { + if (matrix.MultiplyPoint3x4(description.Position[tri[vi]]).sqrMagnitude < 1) { return true; } + } + } + return false; } - - return bitArray; } internal override void OnDrawGizmosSelected() From 6168c4681bcad164c61a18e187e2ae9a17c51aa2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 14:40:52 +0900 Subject: [PATCH 184/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 1fa20684..e6507d55 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -8,6 +8,7 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Added - IslandSelector が追加されました (#422) + - Box(Sphere)IslandSelector に IsAll オプションが追加されました (#468) - SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) - IslandCulling からのマイグレーションが追加されました (#422) - TTT PSD Importer のプレビューの生成が大幅に高速化されました (#424 #443) From 7065cc8fb7389e87b095a40b4bfb69a0db984410 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 17:10:06 +0900 Subject: [PATCH 185/208] feat: create TextureConfigurator --- .../TextureFineTuning/CompressTuningDrawer.cs | 28 ++++-- Editor/Inspector/TextureConfiguratorEditor.cs | 50 ++++++++++ .../TextureConfiguratorEditor.cs.meta | 11 +++ Editor/Localize/en_US.po | 5 + .../NewGameObjectAndAddTTTComponent.cs | 5 + .../CommonComponent/TextureConfigurator.cs | 97 +++++++++++++++++++ .../TextureConfigurator.cs.meta | 11 +++ Runtime/TextureAtlas/AtlasTexture.cs | 3 +- .../TextureFineTuning/Compress.cs | 8 +- 9 files changed, 205 insertions(+), 13 deletions(-) create mode 100644 Editor/Inspector/TextureConfiguratorEditor.cs create mode 100644 Editor/Inspector/TextureConfiguratorEditor.cs.meta create mode 100644 Runtime/CommonComponent/TextureConfigurator.cs create mode 100644 Runtime/CommonComponent/TextureConfigurator.cs.meta diff --git a/Editor/Inspector/TextureAtlas/TextureFineTuning/CompressTuningDrawer.cs b/Editor/Inspector/TextureAtlas/TextureFineTuning/CompressTuningDrawer.cs index 1c45813f..9272b71c 100644 --- a/Editor/Inspector/TextureAtlas/TextureFineTuning/CompressTuningDrawer.cs +++ b/Editor/Inspector/TextureAtlas/TextureFineTuning/CompressTuningDrawer.cs @@ -23,13 +23,24 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten position.height = 18f; if (ITextureFineTuningDrawer.DrawTuningSelector(position, property)) { return; } position.y += 18; + position = DrawCompressEditor(position, property); + var sCompressPropertyNames = property.FindPropertyRelative("PropertyNames"); + var sCompressSelect = property.FindPropertyRelative("Select"); + EditorGUI.PropertyField(position, sCompressPropertyNames, "TextureFineTuning:prop:TargetPropertyName".Glc()); + position.y += 18; + EditorGUI.PropertyField(position, sCompressSelect, "TextureFineTuning:prop:Select".Glc()); + position.y += 18; + } + + public static Rect DrawCompressEditor(Rect position, SerializedProperty property) + { var sCompressFormatQuality = property.FindPropertyRelative("FormatQualityValue"); var sUseOverride = property.FindPropertyRelative("UseOverride"); var sOverrideTextureFormat = property.FindPropertyRelative("OverrideTextureFormat"); var sCompressCompressionQuality = property.FindPropertyRelative("CompressionQuality"); - var sCompressPropertyNames = property.FindPropertyRelative("PropertyNames"); - var sCompressSelect = property.FindPropertyRelative("Select"); + + position.height = 18f; if (!sUseOverride.boolValue) { EditorGUI.PropertyField(position, sCompressFormatQuality, "TextureFineTuning:prop:FormatQuality".Glc()); @@ -50,15 +61,18 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten } EditorGUI.PropertyField(position, sUseOverride, "TextureFineTuning:prop:UseOverrideTextureFormat".Glc()); position.y += 18; - EditorGUI.PropertyField(position, sCompressPropertyNames, "TextureFineTuning:prop:TargetPropertyName".Glc()); - position.y += 18; - EditorGUI.PropertyField(position, sCompressSelect, "TextureFineTuning:prop:Select".Glc()); - position.y += 18; + + return position; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { - return base.GetPropertyHeight(property, label) * (property.FindPropertyRelative("UseOverride").boolValue ? 7 : 5); + return GetPropertyHeightStatic(property); + } + + public static float GetPropertyHeightStatic(SerializedProperty property) + { + return 18f * (property.FindPropertyRelative("UseOverride").boolValue ? 7 : 5); } } } diff --git a/Editor/Inspector/TextureConfiguratorEditor.cs b/Editor/Inspector/TextureConfiguratorEditor.cs new file mode 100644 index 00000000..69c7a810 --- /dev/null +++ b/Editor/Inspector/TextureConfiguratorEditor.cs @@ -0,0 +1,50 @@ +using UnityEngine; +using UnityEditor; +using net.rs64.TexTransTool.Preview; +namespace net.rs64.TexTransTool.Editor +{ + + [CustomEditor(typeof(TextureConfigurator))] + internal class TextureConfiguratorEditor : UnityEditor.Editor + { + public override void OnInspectorGUI() + { + TextureTransformerEditor.DrawerWarning("TextureConfigurator"); + + var targetTC = target as TextureConfigurator; + var sObj = serializedObject; + + var sTargetTexture = sObj.FindProperty("TargetTexture"); + + var sOverrideTextureSetting = sObj.FindProperty("OverrideTextureSetting"); + var sTextureSize = sObj.FindProperty("TextureSize"); + var sMipMap = sObj.FindProperty("MipMap"); + var sDownScalingAlgorism = sObj.FindProperty("DownScalingAlgorism"); + + var sOverrideCompression = sObj.FindProperty("OverrideCompression"); + var sCompressionSetting = sObj.FindProperty("CompressionSetting"); + + EditorGUILayout.PropertyField(sTargetTexture); + + EditorGUILayout.PropertyField(sOverrideTextureSetting); + using (new EditorGUI.DisabledScope(!sOverrideTextureSetting.boolValue)) + using (new EditorGUI.IndentLevelScope()) + { + EditorGUILayout.PropertyField(sTextureSize); + EditorGUILayout.PropertyField(sMipMap); + EditorGUILayout.PropertyField(sDownScalingAlgorism); + } + + EditorGUILayout.PropertyField(sOverrideCompression); + using (new EditorGUI.DisabledScope(!sOverrideCompression.boolValue)) + using (new EditorGUI.IndentLevelScope()) + { + var rect = EditorGUILayout.GetControlRect(GUILayout.Height(TextureAtlas.Editor.CompressTuningDrawer.GetPropertyHeightStatic(sCompressionSetting) - (18f * 3))); + TextureAtlas.Editor.CompressTuningDrawer.DrawCompressEditor(rect, sCompressionSetting); + } + + OneTimePreviewContext.instance.DrawApplyAndRevert(targetTC); + sObj.ApplyModifiedProperties(); + } + } +} diff --git a/Editor/Inspector/TextureConfiguratorEditor.cs.meta b/Editor/Inspector/TextureConfiguratorEditor.cs.meta new file mode 100644 index 00000000..eea07c2e --- /dev/null +++ b/Editor/Inspector/TextureConfiguratorEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8079e00c7cf5e6046bc5e9fffd6737d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Localize/en_US.po b/Editor/Localize/en_US.po index 04e2b03e..6fb735b0 100644 --- a/Editor/Localize/en_US.po +++ b/Editor/Localize/en_US.po @@ -447,3 +447,8 @@ msgstr "TargetPropertyName" msgid "SingleGradationDecal:prop:GradientClamp" msgstr "GradientClamp" + +# TextureConfigurator + +msgid "TextureConfigurator:error:TargetNotFound" +msgstr "TargetNotFound" diff --git a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs index 05f95df9..016e523f 100644 --- a/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs +++ b/Editor/OtherMenuItem/NewGameObjectAndAddTTTComponent.cs @@ -47,6 +47,11 @@ static void C() where TTB : MonoBehaviour [M(BP + IslandSelectorNOT.MenuPath)] static void ISNOT() => C(); [M(BP + IslandSelectorXOR.MenuPath)] static void ISXOR() => C(); + [M(BP + SingleGradationDecal.MenuPath)] static void SGD() => C(); + [M(BP + TextureConfigurator.MenuPath)] static void TC() => C(); + [M(BP + TextureBlender.MenuPath)] static void TB() => C(); + [M(BP + MaterialOverrideTransfer.MenuPath)] static void MOT() => C(); + } } diff --git a/Runtime/CommonComponent/TextureConfigurator.cs b/Runtime/CommonComponent/TextureConfigurator.cs new file mode 100644 index 00000000..0174eaed --- /dev/null +++ b/Runtime/CommonComponent/TextureConfigurator.cs @@ -0,0 +1,97 @@ +using UnityEngine; +using System.Collections.Generic; +using System; +using JetBrains.Annotations; +using net.rs64.TexTransTool.TextureAtlas.FineTuning; +using System.Linq; +using net.rs64.TexTransCore.Utils; +using net.rs64.TexTransTool.Utils; +using net.rs64.TexTransCore.MipMap; +using net.rs64.TexTransCore; +namespace net.rs64.TexTransTool +{ + [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] + public sealed class TextureConfigurator : TexTransRuntimeBehavior + { + internal const string FoldoutName = "Other"; + internal const string ComponentName = "TTT TextureConfigurator"; + internal const string MenuPath = TextureBlender.FoldoutName + "/" + ComponentName; + + internal override List GetRenderers => null; + internal override bool IsPossibleApply => TargetTexture.GetTexture() != null; + internal override TexTransPhase PhaseDefine => TexTransPhase.Optimizing; + internal override IEnumerable GetDependency(IDomain domain) { return TargetTexture.GetDependency(); } + internal override int GetDependencyHash(IDomain domain) { return TargetTexture.GetDependencyHash(); } + + + public TextureSelector TargetTexture; + + public bool OverrideTextureSetting; + [PowerOfTwo] public int TextureSize; + public bool MipMap; + public DownScalingAlgorism DownScalingAlgorism; + + public bool OverrideCompression; + public CompressionQualityData CompressionSetting; + + + internal override void Apply([NotNull] IDomain domain) + { + if (!OverrideTextureSetting && !OverrideCompression) { return; } + + var textureManager = domain.GetTextureManager(); + var target = TargetTexture.GetTexture(); + var materials = domain.EnumerateRenderer() + .SelectMany(i => i.sharedMaterials) + .Distinct().Where(i => i != null); + var targetTex2D = materials.SelectMany(i => i.GetAllTexture2D().Values) + .FirstOrDefault(i => domain.OriginEqual(i, target)); + + if (targetTex2D == null) { TTTRuntimeLog.Info("TextureConfigurator:error:TargetNotFound"); return;} + + var newTexture2D = default(Texture2D); + if (OverrideTextureSetting) + { + var aspect = targetTex2D.height / targetTex2D.width; + var originalSize = textureManager.GetOriginalTextureSize(targetTex2D); + + using (TTRt.U(out var originRt, originalSize, Mathf.RoundToInt(aspect * originalSize), true, false, true, true)) + using (TTRt.U(out var newTempRt, TextureSize, Mathf.RoundToInt(aspect * TextureSize), true, false, MipMap, MipMap)) + { + textureManager.WriteOriginalTexture(targetTex2D, originRt); + MipMapUtility.GenerateMips(originRt, DownScalingAlgorism); + if (MipMap) + { + var originMipCount = originRt.mipmapCount; + var targetSizeMipCount = newTempRt.mipmapCount; + + var copyMipIndex = 1; + while ((originMipCount - copyMipIndex) >= 0 && (targetSizeMipCount - copyMipIndex) >= 0) + { + Graphics.CopyTexture(originRt, 0, originMipCount - copyMipIndex, newTempRt, 0, targetSizeMipCount - copyMipIndex); + copyMipIndex += 1; + } + } + else { Graphics.Blit(originRt, newTempRt); } + + newTexture2D = newTempRt.CopyTexture2D(); + } + } + else + { + var tmpRt = textureManager.GetOriginTempRt(targetTex2D); + newTexture2D = tmpRt.CopyTexture2D(); + TTRt.R(tmpRt); + } + + newTexture2D.CopyFilWrap(targetTex2D); + domain.ReplaceMaterials(MaterialUtility.ReplaceTextureAll(materials, targetTex2D, newTexture2D)); + + if (OverrideCompression) { textureManager.DeferTextureCompress((CompressionQualityApplicant.GetTextureFormat(CompressionSetting), CompressionSetting.CompressionQuality), newTexture2D); } + else { textureManager.DeferInheritTextureCompress(targetTex2D, newTexture2D); } + + } + + } + +} diff --git a/Runtime/CommonComponent/TextureConfigurator.cs.meta b/Runtime/CommonComponent/TextureConfigurator.cs.meta new file mode 100644 index 00000000..eada3e55 --- /dev/null +++ b/Runtime/CommonComponent/TextureConfigurator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d2ce1e40ea72ae47ae56639532e3602 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 846ba4dba0267cf4187be80bb6577627, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/TextureAtlas/AtlasTexture.cs b/Runtime/TextureAtlas/AtlasTexture.cs index dc56ca9b..206b38cb 100644 --- a/Runtime/TextureAtlas/AtlasTexture.cs +++ b/Runtime/TextureAtlas/AtlasTexture.cs @@ -739,10 +739,9 @@ internal override void Apply(IDomain domain = null) //CompressDelegation foreach (var atlasTexFTData in atlasTexFineTuningTargets) { - var tex = atlasTexFTData.Value.Texture2D; var compressSetting = atlasTexFTData.Value.Find(); if (compressSetting == null) { continue; } - var compressSettingTuple = (CompressionQualityApplicant.GetTextureFormat(tex, compressSetting), (int)compressSetting.CompressionQuality); + var compressSettingTuple = (CompressionQualityApplicant.GetTextureFormat(compressSetting), (int)compressSetting.CompressionQuality); domain.GetTextureManager().DeferTextureCompress(compressSettingTuple, atlasTexFTData.Value.Texture2D); } diff --git a/Runtime/TextureAtlas/TextureFineTuning/Compress.cs b/Runtime/TextureAtlas/TextureFineTuning/Compress.cs index 9f6713a0..c71c1b1a 100644 --- a/Runtime/TextureAtlas/TextureFineTuning/Compress.cs +++ b/Runtime/TextureAtlas/TextureFineTuning/Compress.cs @@ -53,8 +53,8 @@ public enum FormatQuality Normal, High, } - - internal class CompressionQualityData : ITuningData + [Serializable] + public class CompressionQualityData : ITuningData { public FormatQuality FormatQualityValue = FormatQuality.Normal; @@ -62,7 +62,7 @@ internal class CompressionQualityData : ITuningData public TextureFormat OverrideTextureFormat; - public int CompressionQuality = 50; + [Range(0, 100)] public int CompressionQuality = 50; } internal class CompressionQualityApplicant : ITuningApplicant { @@ -72,7 +72,7 @@ public void ApplyTuning(Dictionary texFineTuningTar { // Delegated to ITextureManager } - public static TextureFormat GetTextureFormat(Texture2D texture2D, CompressionQualityData compressionQualityData) + public static TextureFormat GetTextureFormat(CompressionQualityData compressionQualityData) { if (compressionQualityData.UseOverride) { return compressionQualityData.OverrideTextureFormat; } From 4054d54dcb4a14d8909a271b6d156b76fa058095 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 17:11:57 +0900 Subject: [PATCH 186/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index e6507d55..b100e43c 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -23,6 +23,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - SingleGradationDecal が追加されました (#449) - オプション GradationClamp が追加 (#451) - MaterialOverrideTransfer が追加されました (#456) +- TextureConfigurator が追加されました (#469) ### Changed From 8c5df6bfd6d535513418b2f2bc1818c0ff31d261 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 08:23:31 +0000 Subject: [PATCH 187/208] Update package.json v0.7.0-rc.0!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5a2aeb58..5a8948f6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-beta.8", + "version": "0.7.0-rc.0", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 5120bd782f20ff1e552828c58fcea13c9f9d50c4 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 20:13:11 +0900 Subject: [PATCH 188/208] chore: correct define UNITY_EDITOR_OSX --- Editor/Migration/Migrator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/Migration/Migrator.cs b/Editor/Migration/Migrator.cs index 0cad420c..28189481 100644 --- a/Editor/Migration/Migrator.cs +++ b/Editor/Migration/Migrator.cs @@ -194,7 +194,7 @@ private static bool DoMigrate() { InProgress = true; var result = EditorUtility.DisplayDialog("Migrate!", -#if !UNITY_STANDALONE_OSX +#if !UNITY_EDITOR_OSX @"互換性の持たないTexTransToolのアップグレードが検出されました! 正常な動作のためにはすべてのシーンとプレハブをマイグレーションする必要があります。 プロジェクトが壊れる可能性もあり、長い時間がかかります。 From d68303be29b64bad7e9c6146b421207467e83f73 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 6 May 2024 20:24:15 +0900 Subject: [PATCH 189/208] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ae9e275..1a00f626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - AtlasTexture の テクスチャ詳細設定で、色空間 のUIが正しく表示されていない問題を修正 (#462) - AtlasTexture でテクスチャが縮小される場合に MipMap を使用していない問題を修正 (#463) - Mac環境でマイグレーションのダイアログが、512Byte以上のマルチバイト文字列であったために、クラッシュする問題の回避を追加 (#466) + - シンボルの誤りにより回避できていなかった問題を修正 (#470) ### Deprecated From 5db380f544dcc5df784f8bf690e8e42600fe4d3f Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 11:27:11 +0000 Subject: [PATCH 190/208] Update package.json v0.7.0-rc.1!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5a8948f6..7e5c3195 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-rc.0", + "version": "0.7.0-rc.1", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From efa0e69a8edecb8dbaee1e64b72f4e54499954c9 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 7 May 2024 16:15:19 +0900 Subject: [PATCH 191/208] optimize: TexTransInitialize --- Editor/TTTInitializer.cs | 16 ++++++++-------- TexTransCore/TexTransCoreRuntime.cs | 23 ++++++++++++++++------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/Editor/TTTInitializer.cs b/Editor/TTTInitializer.cs index c362a43b..89660435 100644 --- a/Editor/TTTInitializer.cs +++ b/Editor/TTTInitializer.cs @@ -1,11 +1,8 @@ using System.Linq; using net.rs64.TexTransCore; -using net.rs64.TexTransCore.BlendTexture; -using net.rs64.TexTransCore.MipMap; -using net.rs64.TexTransTool.MultiLayerImage; -using net.rs64.TexTransTool.TextureAtlas; using UnityEditor; -using UnityEngine; +using UnityEngine.Profiling; + namespace net.rs64.TexTransTool.Utils { internal static class TTTInitializeCaller @@ -23,15 +20,18 @@ static void EditorInitDerayCaller() [UnityEditor.InitializeOnEnterPlayMode] public static void Initialize() { + Profiler.BeginSample("TTTInitializeCaller:TexTransCoreRuntime"); UnityEditor.EditorApplication.update += () => { TexTransCoreRuntime.Update.Invoke(); }; TexTransCoreRuntime.LoadAsset = (guid, type) => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), type); TexTransCoreRuntime.LoadAssetsAtType = (type) => { - return UnityEditor.AssetDatabase.GetAllAssetPaths() - .Where(i => AssetDatabase.GetMainAssetTypeAtPath(i) == type) - .Select(i => AssetDatabase.LoadAssetAtPath(i, type)); + return UnityEditor.AssetDatabase.FindAssets($"t:{type.Name}") + .Select(i => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(i), type)); }; + Profiler.EndSample(); + Profiler.BeginSample("TexTransInitialize"); TexTransInitialize.CallInitialize(); + Profiler.EndSample(); } } } diff --git a/TexTransCore/TexTransCoreRuntime.cs b/TexTransCore/TexTransCoreRuntime.cs index b6581dfb..d9b43926 100644 --- a/TexTransCore/TexTransCoreRuntime.cs +++ b/TexTransCore/TexTransCoreRuntime.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using net.rs64.TexTransCore.BlendTexture; +using UnityEngine.Profiling; namespace net.rs64.TexTransCore { @@ -24,14 +25,22 @@ public TexTransInitialize() public static void CallInitialize()//シェーダー等がロードさている状態を想定している。 { + Profiler.BeginSample("FindInitializers"); var initializers = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(i => i.GetTypes()) - .SelectMany(i => i.GetRuntimeMethods()) - .Where(i => i.IsStatic) - .Where(i => i.GetCustomAttribute() is not null) - .Select(i => (Action)i.CreateDelegate(typeof(Action))); - - foreach (var method in initializers) { method(); } + .Where(i => i.FullName.Contains("net.rs64")) + .SelectMany(i => i.GetTypes().SelectMany(t => t.GetRuntimeMethods())) + .Where(i => i.IsStatic && i.GetCustomAttribute() is not null) + .Select(i => (Action)i.CreateDelegate(typeof(Action))).ToArray(); + Profiler.EndSample(); + + Profiler.BeginSample("CallInitializers"); + foreach (var method in initializers) + { + Profiler.BeginSample("Call:" + method.Method.Name); + method(); + Profiler.EndSample(); + } + Profiler.EndSample(); } From e93efa361bec6b934f3e5adca282587e456be974 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 8 May 2024 02:36:53 +0900 Subject: [PATCH 192/208] feat: AssetImportListener --- Editor/TTTInitializer.cs | 16 ++++++++++++ .../AtlasShaderSupportScriptableObject.cs | 1 + .../AtlasShaderSupportUtils.cs | 26 +++++++++++++------ TexTransCore/TexTransCoreRuntime.cs | 1 + 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/Editor/TTTInitializer.cs b/Editor/TTTInitializer.cs index 89660435..80b69f03 100644 --- a/Editor/TTTInitializer.cs +++ b/Editor/TTTInitializer.cs @@ -1,6 +1,7 @@ using System.Linq; using net.rs64.TexTransCore; using UnityEditor; +using UnityEngine; using UnityEngine.Profiling; namespace net.rs64.TexTransTool.Utils @@ -32,6 +33,21 @@ public static void Initialize() Profiler.BeginSample("TexTransInitialize"); TexTransInitialize.CallInitialize(); Profiler.EndSample(); + + } + + internal class AssetImportListener : AssetPostprocessor + { + static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths, bool didDomainReload) + { + foreach (var path in importedAssets) + { + var type = AssetDatabase.GetMainAssetTypeAtPath(path); + if (TexTransCoreRuntime.NewAssetListen.TryGetValue(type, out var action)) { action.Invoke(); } + } + } + + } } } diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs index 7b903c2e..d157d9b1 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasScriptableObject/AtlasShaderSupportScriptableObject.cs @@ -10,6 +10,7 @@ namespace net.rs64.TexTransTool.TextureAtlas.AtlasScriptableObject public class AtlasShaderSupportScriptableObject : ScriptableObject { [SerializeReference] public ISupportedShaderComparer SupportedShaderComparer = new ContainsName(); + public int Priority; public List AtlasTargetDefines; public Shader BakeShader; [SerializeReference] public List AtlasMaterialPostProses = new(); diff --git a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs index b17f8a1e..e131b378 100644 --- a/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs +++ b/Runtime/TextureAtlas/AtlasShaderSupport/AtlasShaderSupportUtils.cs @@ -15,21 +15,31 @@ internal class AtlasShaderSupportUtils [TexTransInitialize] public static void Initialize() { - var atlasShaderSupportList = TexTransCoreRuntime.LoadAssetsAtType.Invoke(typeof(AtlasShaderSupportScriptableObject)).Cast().ToList(); + SupporterInit(); + TexTransCoreRuntime.NewAssetListen[typeof(AtlasShaderSupportScriptableObject)] = SupporterInit; - if (s_defaultSupporter == null) + static void SupporterInit() { - s_defaultSupporter = ScriptableObject.CreateInstance(); - s_defaultSupporter.SupportedShaderComparer = new AnythingShader(); - s_defaultSupporter.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything(), BakePropertyNames = new() } }; - } + var atlasShaderSupportList = TexTransCoreRuntime.LoadAssetsAtType.Invoke(typeof(AtlasShaderSupportScriptableObject)).Cast().ToList(); + + if (s_defaultSupporter == null) + { + s_defaultSupporter = ScriptableObject.CreateInstance(); + s_defaultSupporter.SupportedShaderComparer = new AnythingShader(); + s_defaultSupporter.AtlasTargetDefines = new() { new() { TexturePropertyName = "_MainTex", AtlasDefineConstraints = new Anything(), BakePropertyNames = new() } }; + s_defaultSupporter.Priority = int.MaxValue; + } - atlasShaderSupportList.Add(s_defaultSupporter); - s_atlasShaderSupportList = atlasShaderSupportList; + atlasShaderSupportList.Add(s_defaultSupporter); + s_atlasShaderSupportList = atlasShaderSupportList; + } } public AtlasShaderSupportScriptableObject GetAtlasShaderSupporter(Material mat) { + s_atlasShaderSupportList.RemoveAll(i => i == null); + s_atlasShaderSupportList.Sort((l, r) => l.Priority - r.Priority); + return s_atlasShaderSupportList.First(i => i.SupportedShaderComparer.ThisSupported(mat)); } diff --git a/TexTransCore/TexTransCoreRuntime.cs b/TexTransCore/TexTransCoreRuntime.cs index d9b43926..6fe4af55 100644 --- a/TexTransCore/TexTransCoreRuntime.cs +++ b/TexTransCore/TexTransCoreRuntime.cs @@ -13,6 +13,7 @@ public static class TexTransCoreRuntime public static Action NextUpdateCall; public static Func LoadAsset; public static Func> LoadAssetsAtType; + public static Dictionary NewAssetListen = new(); } From 693510b6ea9fc93350a8696e3809d473020d9385 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 9 May 2024 20:22:17 +0900 Subject: [PATCH 193/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index b100e43c..7f53d0fc 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -15,6 +15,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - AtlasTexture に アイランド詳細調整 が追加されました (#431) - IslandSelectorNOT と IslandRendererSelector が追加されました (#431) - AtlasTexture のシェーダーサポートの追加が ScriptableObject で可能になりました (#431) + - 新規作成したオブジェクトが即座に、AtlasTexture に認識されるようになりました(#472) - AtlasTexture に MaterialMargeGroup が追加されました (#432) - ClipStudioPaint から出力されたと思われる PSD を TTT PSD Importer で読み込んだ時、Clip系の色合成にインポートするようになりました (#444) - SubMeshIslandSelector , IslandSelectorXOR , ~~IslandSelectorRelay~~ が追加されました (#447) From 25ca058d83c4ab096e24373f4ec50c8ef7afb1c5 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Thu, 9 May 2024 20:26:17 +0900 Subject: [PATCH 194/208] fix: renderer is null can not run the RealTimePreview --- Runtime/Decal/SimpleDecal.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 8bfba497..5cf37040 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -102,12 +102,13 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan internal override IEnumerable GetDependency(IDomain domain) { + var targetRenderers = TargetRenderers.Where(r => r != null); var dependencies = new UnityEngine.Object[] { transform } .Concat(transform.GetParents()) - .Concat(TargetRenderers) - .Concat(TargetRenderers.Select(r => r.transform)) - .Concat(TargetRenderers.Select(r => r.GetMesh())) - .Concat(TargetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)) + .Concat(targetRenderers) + .Concat(targetRenderers.Select(r => r.transform)) + .Concat(targetRenderers.Select(r => r.GetMesh())) + .Concat(targetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)) .Append(DecalTexture); if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } From 7706a56dc2475fd069be34cefa8af3c0c106a74e Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Fri, 10 May 2024 21:17:28 +0900 Subject: [PATCH 195/208] fix: material is null can RealTimePreview --- Runtime/Decal/Gradation/SingleGradationDecal.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index a9b67be8..1b604568 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -112,7 +112,7 @@ private void OnDrawGizmosSelected() internal override int GetDependencyHash(IDomain domain) { var hash = 0; - foreach (var mat in TargetMaterials) { hash ^= mat?.GetInstanceID() ?? 0; } + foreach (var mat in TargetMaterials) { if (mat != null) hash ^= mat.GetInstanceID(); } return hash; } } From 012ffdb049ca25870c387ce93120094b94128130 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 11 May 2024 23:27:20 +0900 Subject: [PATCH 196/208] fix: exception when target materials null --- Runtime/Decal/Gradation/SingleGradationDecal.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Runtime/Decal/Gradation/SingleGradationDecal.cs b/Runtime/Decal/Gradation/SingleGradationDecal.cs index 1b604568..26c05dcb 100644 --- a/Runtime/Decal/Gradation/SingleGradationDecal.cs +++ b/Runtime/Decal/Gradation/SingleGradationDecal.cs @@ -22,7 +22,7 @@ public sealed class SingleGradationDecal : TexTransRuntimeBehavior internal const string MenuPath = ComponentName; internal override List GetRenderers => null; - internal override bool IsPossibleApply => true; + internal override bool IsPossibleApply => TargetMaterials != null && TargetMaterials.Any(); internal override TexTransPhase PhaseDefine => TexTransPhase.AfterUVModification; public List TargetMaterials; @@ -33,6 +33,7 @@ public sealed class SingleGradationDecal : TexTransRuntimeBehavior [BlendTypeKey] public string BlendTypeKey = TextureBlend.BL_KEY_DEFAULT; public PropertyName TargetPropertyName = PropertyName.DefaultValue; + internal override void Apply([NotNull] IDomain domain) { var targetMat = GetTargetMaterials(domain.OriginEqual, domain.EnumerateRenderer()); @@ -60,6 +61,7 @@ internal override void Apply([NotNull] IDomain domain) private HashSet GetTargetMaterials(Func originEqual, IEnumerable domainRenderers) { + if (!IsPossibleApply) { return new(); } return RendererUtility.GetMaterials(domainRenderers).Where(m => TargetMaterials.Any(tm => originEqual.Invoke(m, tm))).ToHashSet(); } @@ -112,7 +114,7 @@ private void OnDrawGizmosSelected() internal override int GetDependencyHash(IDomain domain) { var hash = 0; - foreach (var mat in TargetMaterials) { if (mat != null) hash ^= mat.GetInstanceID(); } + if (TargetMaterials != null) foreach (var mat in TargetMaterials) { if (mat != null) hash ^= mat.GetInstanceID(); } return hash; } } From 508e387809933f2481fc7e57491eff9b1617bdcb Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sat, 11 May 2024 23:27:50 +0900 Subject: [PATCH 197/208] fix: DecalPadding default value --- TexTransCore/Decal/DecalContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TexTransCore/Decal/DecalContext.cs b/TexTransCore/Decal/DecalContext.cs index 38600d1d..05845cda 100644 --- a/TexTransCore/Decal/DecalContext.cs +++ b/TexTransCore/Decal/DecalContext.cs @@ -36,7 +36,7 @@ internal class DecalContext public string TargetPropertyName { get; set; } = "_MainTex"; public TextureWrap? TextureWarp { get; set; } = null; - public float DecalPadding { get; set; } = 0.5f; + public float DecalPadding { get; set; } = 5f; public bool HighQualityPadding { get; set; } = false; public bool? UseDepthOrInvert { get; set; } = null; From 6ee21f6869915b8e7fc257a9940aa5fe48241071 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Sun, 12 May 2024 22:07:16 +0900 Subject: [PATCH 198/208] fix: Exception when not used OutPutUV --- .../Decal/ParallelProjection/ParallelProjectionSpace.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs index 1823ac28..252567d9 100644 --- a/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs +++ b/TexTransCore/Decal/ParallelProjection/ParallelProjectionSpace.cs @@ -32,7 +32,10 @@ public void Input(MeshData meshData) public void Dispose() { MeshData = null; + _jobHandle.Complete(); PPSVert.Dispose(); + _jobHandle = default; + PPSVert = default; } } } From e542134e95eaeafbbb2d8e2ca7f1d30cc9301ffc Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 12 May 2024 13:29:32 +0000 Subject: [PATCH 199/208] Update package.json v0.7.0-rc.2!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 7e5c3195..76fe558c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-rc.1", + "version": "0.7.0-rc.2", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 1433c89c140190f4488cc267ebcc5eb02827edc2 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Mon, 13 May 2024 21:58:05 +0900 Subject: [PATCH 200/208] fix: not copy WarpMode --- Editor/Preview/RealTime/PreviewStackManager.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Editor/Preview/RealTime/PreviewStackManager.cs b/Editor/Preview/RealTime/PreviewStackManager.cs index ecbeda2c..be8423c5 100644 --- a/Editor/Preview/RealTime/PreviewStackManager.cs +++ b/Editor/Preview/RealTime/PreviewStackManager.cs @@ -4,6 +4,7 @@ using net.rs64.TexTransCore; using UnityEngine; using static net.rs64.TexTransCore.BlendTexture.TextureBlend; +using net.rs64.TexTransCore.Utils; namespace net.rs64.TexTransTool.Preview.RealTime { @@ -106,6 +107,7 @@ public PrioritizedDeferredStack(Texture2D initialTexture) { _initialTexture = initialTexture; _stackViewTexture = TTRt.G(initialTexture.width, initialTexture.height); + _stackViewTexture.CopyFilWrap(initialTexture); Graphics.Blit(initialTexture, _stackViewTexture); } From c62714a55b8996d6aa17fe55b40a49ec972fcaf5 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 14 May 2024 06:08:44 +0000 Subject: [PATCH 201/208] Update package.json v0.7.0-rc.3!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 76fe558c..a9f319d1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-rc.2", + "version": "0.7.0-rc.3", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From 3672a52832d1557fbb4cb61194644b2ca02f107b Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 14 May 2024 21:04:50 +0900 Subject: [PATCH 202/208] fix: IslandCulling incorrect migration --- Editor/Migration/V3/SimpleDecalV3.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Editor/Migration/V3/SimpleDecalV3.cs b/Editor/Migration/V3/SimpleDecalV3.cs index 89cb233c..1c518627 100644 --- a/Editor/Migration/V3/SimpleDecalV3.cs +++ b/Editor/Migration/V3/SimpleDecalV3.cs @@ -16,7 +16,7 @@ public static void MigrationSimpleDecalV3ToV4(SimpleDecal simpleDecal) if (simpleDecal == null) { Debug.LogWarning("マイグレーションターゲットが存在しません。"); return; } if (simpleDecal is ITexTransToolTag TTTag && TTTag.SaveDataVersion > 4) { Debug.Log(simpleDecal.name + " SimpleDecal : マイグレーション不可能なバージョンです。"); return; } - MigrateIslandCullingToIslandSelector(simpleDecal); + if (simpleDecal.IslandCulling) { MigrateIslandCullingToIslandSelector(simpleDecal); } if (simpleDecal.PolygonCulling != TexTransCore.Decal.PolygonCulling.Vertex) { simpleDecal.PolygonOutOfCulling = false; } From 08bc55374773055aab93041e5b2d6e13c7044acf Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 14 May 2024 21:07:45 +0900 Subject: [PATCH 203/208] fix: exception when Missing IslandSelector --- Runtime/Decal/SimpleDecal.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Runtime/Decal/SimpleDecal.cs b/Runtime/Decal/SimpleDecal.cs index 5cf37040..c53636a9 100644 --- a/Runtime/Decal/SimpleDecal.cs +++ b/Runtime/Decal/SimpleDecal.cs @@ -16,7 +16,7 @@ namespace net.rs64.TexTransTool.Decal { [AddComponentMenu(TexTransBehavior.TTTName + "/" + MenuPath)] - public sealed class SimpleDecal : TexTransRuntimeBehavior//AbstractSingleDecal + public sealed class SimpleDecal : TexTransRuntimeBehavior { internal const string ComponentName = "TTT SimpleDecal"; internal const string MenuPath = ComponentName; @@ -111,7 +111,7 @@ internal static RenderTexture GetMultipleDecalTexture(ITextureManager textureMan .Concat(targetRenderers.Where(r => r is SkinnedMeshRenderer).Cast().SelectMany(r => r.bones)) .Append(DecalTexture); - if (IslandSelector != null) { dependencies.Concat(IslandSelector.GetDependency()); } + if (IslandSelector != null) { dependencies = dependencies.Concat(IslandSelector.GetDependency()); } return dependencies; } internal override int GetDependencyHash(IDomain domain) @@ -180,7 +180,7 @@ internal void OnDrawGizmosSelected() DecalGizmoUtility.DrawGizmoQuad(DecalTexture, Color, matrix); - IslandSelector?.OnDrawGizmosSelected(); + if (IslandSelector != null) { IslandSelector.OnDrawGizmosSelected(); } } } From fa3161c18e0ee6a500fc34f45708126fb9cc4012 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 14 May 2024 21:12:31 +0900 Subject: [PATCH 204/208] fix: import fail the layer without alpha --- Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs index 84ed9915..f659230a 100644 --- a/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs +++ b/Runtime/MultiLayerImage/Improted/PSD/PSDImportedRasterImage.cs @@ -1,3 +1,4 @@ +using System.Linq; using System.Threading.Tasks; using net.rs64.MultiLayerImage.Parser.PSD; using net.rs64.TexTransCore; @@ -144,7 +145,7 @@ internal override void LoadImage(byte[] importSource, RenderTexture WriteTarget) async static Task[]> WeightTask(Task>[] tasks) { - return await Task.WhenAll(tasks).ConfigureAwait(false); + return await Task.WhenAll(tasks.Where(i => i != null)).ConfigureAwait(false); } [TexTransInitialize] public static void Init() From 106ac9ce56684fd8c882b1645d152b0387ed70e3 Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Tue, 14 May 2024 21:15:26 +0900 Subject: [PATCH 205/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 7f53d0fc..946a56aa 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -42,6 +42,7 @@ v0.5.2 以降の実験的機能の変更記録です。 - Library が存在しないときにも正しく TTT PSD Importer がインポートできるようになりました (#427) - TTT PSD Importer が PSD の ImageResourceBlock を正しく読み込めるようになりました (#443) +- TTT PSD Importer から アルファのないラスターレイヤーが正しくインポートできない問題を修正 (#479) ### Deprecated From 2bb6b98b09520623e3d7733679e05dd6abbc8865 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 14 May 2024 12:16:38 +0000 Subject: [PATCH 206/208] Update package.json v0.7.0-rc.4!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a9f319d1..1aa41551 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-rc.3", + "version": "0.7.0-rc.4", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": { From b25bc79ad6dc31855323aca926f809338341d7ac Mon Sep 17 00:00:00 2001 From: Reina_Sakiria Date: Wed, 22 May 2024 17:31:40 +0900 Subject: [PATCH 207/208] chore: update changelog --- CHANGELOG-EXPERIMENTAL.md | 12 ++++++++++++ CHANGELOG.md | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG-EXPERIMENTAL.md b/CHANGELOG-EXPERIMENTAL.md index 946a56aa..4f1e47fd 100644 --- a/CHANGELOG-EXPERIMENTAL.md +++ b/CHANGELOG-EXPERIMENTAL.md @@ -7,6 +7,18 @@ v0.5.2 以降の実験的機能の変更記録です。 ### Added +### Changed + +### Removed + +### Fixed + +### Deprecated + +## 0.7.0 + +### Added + - IslandSelector が追加されました (#422) - Box(Sphere)IslandSelector に IsAll オプションが追加されました (#468) - SimpleDecal の実験的なカリング機能のとして IslandSelector が使用できるようになりました (#422) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a00f626..6719435a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +### Changed + +### Removed + +### Fixed + +### Deprecated + +## [0.7.0] + +### Added + - Optimizing Phase が追加されました (#410) - NDMF OptimizePhaseに実行されるようになりました。 (#438) - GameObject から TexTransTool のほとんどのコンポーネントが追加できるようになりました (#411) @@ -507,7 +519,8 @@ Cherry-Pick - AvatarTag 系のコンポーネントを削除しました `#11` -[unreleased]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.6.6...master +[unreleased]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.7.0...master +[0.7.0]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.6.6...v0.7.0 [0.6.6]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.6.5...v0.6.6 [0.6.5]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.6.4...v0.6.5 [0.6.4]: https://github.com/ReinaS-64892/TexTransTool/compare/v0.6.3...v0.6.4 From 24557cc8cb0404a9c68f369f6a7c66d5d1c938b9 Mon Sep 17 00:00:00 2001 From: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 22 May 2024 08:35:06 +0000 Subject: [PATCH 208/208] Update package.json v0.7.0!! --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1aa41551..acfdfe9c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "net.rs64.tex-trans-tool", "displayName": "TexTransTool", - "version": "0.7.0-rc.4", + "version": "0.7.0", "unity": "2022.3", "description": "Non-destructive modification to Texture!", "author": {