Commit 77646b7d authored by 神楽坂玲奈's avatar 神楽坂玲奈

remove Mega-Fiers & TextMesh Pro Editor Scripts for upgrade

parent 8b764b4f
fileFormatVersion: 2
guid: 2122222f545717b4da829b89981ac8cf
folderAsset: yes
timeCreated: 1482163012
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaBend))]
public class MegaBendEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Bend Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool Inspector()
{
MegaBend mod = (MegaBend)target;
EditorGUIUtility.LookLikeControls();
mod.angle = EditorGUILayout.FloatField("Angle", mod.angle);
mod.dir = EditorGUILayout.FloatField("Dir", mod.dir);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
fileFormatVersion: 2
guid: f3bf905f7f3752c48989d1fe027de131
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaBubble))]
public class MegaBubbleEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Bubble Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bubble_help.png"); }
public override bool Inspector()
{
MegaBubble mod = (MegaBubble)target;
EditorGUIUtility.LookLikeControls();
mod.radius = EditorGUILayout.FloatField("Radius", mod.radius);
mod.falloff = EditorGUILayout.FloatField("Falloff", mod.falloff);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 96ac112a275b6c243bb9d23e22c303ab
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaBulge))]
public class MegaBulgeEditor : MegaModifierEditor
{
public override bool Inspector()
{
MegaBulge mod = (MegaBulge)target;
EditorGUIUtility.LookLikeControls();
mod.Amount = EditorGUILayout.Vector3Field("Radius", mod.Amount);
mod.FallOff = EditorGUILayout.Vector3Field("Falloff", mod.FallOff);
mod.LinkFallOff = EditorGUILayout.Toggle("Link Falloff", mod.LinkFallOff);
return false;
}
}
fileFormatVersion: 2
guid: 7501f331fecc5f14cb3089cd98ddbeb4
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaCrumple))]
public class MegaCrumpleEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Crumple Modifier by Unity"; }
public override bool Inspector()
{
MegaCrumple mod = (MegaCrumple)target;
EditorGUIUtility.LookLikeControls();
mod.scale = EditorGUILayout.FloatField("Scale", mod.scale);
mod.speed = EditorGUILayout.FloatField("Speed", mod.speed);
mod.phase = EditorGUILayout.FloatField("Phase", mod.phase);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
return false;
}
}
fileFormatVersion: 2
guid: 564e9efbaaf72884685ca7f8201e714f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaCurveDeform))]
public class MegaCurveDeformEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Mega Curve Deform Modifier by Chris West"; }
public override bool Inspector()
{
MegaCurveDeform mod = (MegaCurveDeform)target;
EditorGUIUtility.LookLikeControls();
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.defCurve = EditorGUILayout.CurveField("Curve", mod.defCurve);
mod.MaxDeviation = EditorGUILayout.FloatField("Max Deviation", mod.MaxDeviation);
return false;
}
}
fileFormatVersion: 2
guid: 81a2c84abdb3e9a41af369347d41d9e6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaCylindrify))]
public class MegaCylindrifyEditor : MegaModifierEditor
{
public override bool Inspector()
{
MegaCylindrify mod = (MegaCylindrify)target;
EditorGUIUtility.LookLikeControls();
mod.Percent = EditorGUILayout.FloatField("Percent", mod.Percent);
mod.Decay = EditorGUILayout.FloatField("Decay", mod.Decay);
return false;
}
}
fileFormatVersion: 2
guid: 910aa6eb5ee321c43a0f1444fb45ffb1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaDisplace))]
public class MegaDisplaceEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Displace Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_web.png"); }
public override bool Inspector()
{
MegaDisplace mod = (MegaDisplace)target;
EditorGUIUtility.LookLikeControls();
mod.map = (Texture2D)EditorGUILayout.ObjectField("Map", mod.map, typeof(Texture2D), true);
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.offset = EditorGUILayout.Vector2Field("Offset", mod.offset);
mod.scale = EditorGUILayout.Vector2Field("Scale", mod.scale);
mod.channel = (MegaChannel)EditorGUILayout.EnumPopup("Channel", mod.channel);
mod.CentLum = EditorGUILayout.Toggle("Cent Lum", mod.CentLum);
mod.CentVal = EditorGUILayout.FloatField("Cent Val", mod.CentVal);
mod.Decay = EditorGUILayout.FloatField("Decay", mod.Decay);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2feb81174795e7848b9a0f1c530106c1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaFFD2x2x2))]
public class MegaFFD2x2x2Editor : MegaFFDEditor
{
public override string GetHelpString() { return "FFD2x2x2 Modifier by Chris West"; }
}
\ No newline at end of file
fileFormatVersion: 2
guid: 36e485a5e3715de41ae82f93cf9d0e48
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaFFD3x3x3))]
public class MegaFFD3x3x3Editor : MegaFFDEditor
{
public override string GetHelpString() { return "FFD3x3x3 Modifier by Chris West"; }
}
\ No newline at end of file
fileFormatVersion: 2
guid: cec875d5a9be15e42ac18602efb1139a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaFFD4x4x4))]
public class MegaFFD4x4x4Editor : MegaFFDEditor
{
public override string GetHelpString() { return "FFD4x4x4 Modifier by Chris West"; }
}
\ No newline at end of file
fileFormatVersion: 2
guid: ff963bd5a3b2a704bbce0cd2d5128954
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
public class MegaFFDEditor : MegaModifierEditor
{
Vector3 pm = new Vector3();
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/ffd_help.png"); }
bool showpoints = true;
public override bool Inspector()
{
MegaFFD mod = (MegaFFD)target;
EditorGUIUtility.LookLikeControls();
mod.KnotSize = EditorGUILayout.FloatField("Knot Size", mod.KnotSize);
mod.inVol = EditorGUILayout.Toggle("In Vol", mod.inVol);
showpoints = EditorGUILayout.Foldout(showpoints, "Points");
if ( showpoints )
{
int gs = mod.GridSize();
//int num = gs * gs * gs;
for ( int x = 0; x < gs; x++ )
{
for ( int y = 0; y < gs; y++ )
{
for ( int z = 0; z < gs; z++ )
{
int i = (x * gs * gs) + (y * gs) + z;
mod.pt[i] = EditorGUILayout.Vector3Field("p[" + x + "," + y + "," + z + "]", mod.pt[i]);
}
}
}
}
return false;
}
public override void DrawSceneGUI()
{
MegaFFD ffd = (MegaFFD)target;
if ( ffd.DisplayGizmo )
{
MegaModifiers context = ffd.GetComponent<MegaModifiers>();
Vector3 size = ffd.lsize;
Vector3 osize = ffd.lsize;
osize.x = 1.0f / size.x;
osize.y = 1.0f / size.y;
osize.z = 1.0f / size.z;
Matrix4x4 tm1 = Matrix4x4.identity;
Quaternion rot = Quaternion.Euler(ffd.gizmoRot);
tm1.SetTRS(-(ffd.gizmoPos + ffd.Offset), rot, Vector3.one);
if ( context != null && context.sourceObj != null )
Handles.matrix = context.sourceObj.transform.localToWorldMatrix * tm1;
else
Handles.matrix = ffd.transform.localToWorldMatrix * tm1;
DrawGizmos(ffd, Handles.matrix);
Handles.color = Color.yellow;
int pc = ffd.GridSize();
pc = pc * pc * pc;
for ( int i = 0; i < pc; i++ )
{
Vector3 p = ffd.GetPoint(i) + ffd.bcenter;
//pm = Handles.PositionHandle(p, Quaternion.identity);
pm = Handles.FreeMoveHandle(p, Quaternion.identity, ffd.KnotSize * 0.1f, Vector3.zero, Handles.CircleCap);
pm -= ffd.bcenter;
p = Vector3.Scale(pm, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[i] = p;
}
Handles.matrix = Matrix4x4.identity;
}
}
Vector3[] pp3 = new Vector3[3];
public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm)
{
Handles.color = Color.red;
int pc = ffd.GridSize();
for ( int i = 0; i < pc; i++ )
{
for ( int j = 0; j < pc; j++ )
{
for ( int k = 0; k < pc; k++ )
{
pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k) + ffd.bcenter);
if ( i < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k) + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( j < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k) + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( k < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1) + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
}
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: a8ea7c7ad2d417747a8a01392f0358ec
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
public class ModBut
{
public ModBut() { }
public ModBut(string _but, string tooltip, System.Type _classname, Color _col)
{
name = _but;
color = _col;
classname = _classname;
content = new GUIContent(_but, tooltip);
}
public string name;
public Color color;
public System.Type classname;
public GUIContent content;
}
// TODO: Select axis for shapes
// TODO: Add new spline to shape
// TODO: Button to recalc lengths
// TEST: Build a simple scene in max then have a road, barrier, fence etc
// Import of simple text file for path
public class MegaFiersWindow : EditorWindow
{
static bool showcommon;
//string name = "Shape";
//static MegaAxis axis = MegaAxis.Y;
//static bool drawknots = true;
//static bool drawhandles = true;
//static float stepdist = 0.1f;
//static float knotsize = 0.05f;
static Color col1 = Color.yellow;
static Color col2 = Color.green;
static MegaNormalMethod NormalMethod = MegaNormalMethod.Mega;
// Add menu named "My Window" to the Window menu
[MenuItem("Component/MegaFiers")]
static void Init()
{
// Get existing open window or if none, make a new one:
//MegaShapeWindow window = (MegaShapeWindow)EditorWindow.GetWindow(typeof(MegaShapeWindow));
EditorWindow.GetWindow(typeof(MegaFiersWindow), false, "MegaFiers");
}
#if false
public class Buttons
{
public Buttons() {}
public Buttons(string _but, System.Type _classname)
{
Create(null, _but, _classname);
}
public Buttons(string _tooltip, string _but, System.Type _classname)
{
Create(_tooltip, _but, _classname);
}
public void Create(string _tooltip, string _but, System.Type _classname)
{
classname = _classname;
Texture image = (Texture)AssetDatabase.LoadAssetAtPath("Assets/Mega-Fiers/Editor/Icons/" + _but, typeof(Texture));
//Texture image = (Texture)AssetDatabase.LoadAssetAtPath("Assets/Mega-Fiers/Editor/Icons/" + "mybendicon.png", typeof(Texture));
if ( image == null )
Debug.Log("Didnt load icon " + _but);
else
content = new GUIContent(image, classname.ToString() + " a Mesh");
}
public System.Type classname;
public GUIContent content;
}
static Buttons[] buts = new Buttons[] {
new Buttons("Bend a Mesh", "mybendicon.png", typeof(MegaBend)),
new Buttons("Bubble a Mesh", "mybubbleicon.png", typeof(MegaBubble)),
new Buttons("Bulge a Mesh", "mybendicon.png", typeof(MegaBulge)),
new Buttons("mybendicon.png", typeof(MegaCrumple)),
new Buttons("mybendicon.png", typeof(MegaCurveDeform)),
new Buttons("mybendicon.png", typeof(MegaCylindrify)),
new Buttons("mybendicon.png", typeof(MegaDisplace)),
new Buttons("mybendicon.png", typeof(MegaFFD2x2x2)),
new Buttons("mybendicon.png", typeof(MegaFFD3x3x3)),
new Buttons("mybendicon.png", typeof(MegaFFD4x4x4)),
new Buttons("myhumpicon.png", typeof(MegaHump)),
new Buttons("mymelticon.png", typeof(MegaMelt)),
new Buttons("mynoiseicon.png", typeof(MegaNoise)),
new Buttons("mybendicon.png", typeof(MegaPageFlip)),
new Buttons("mybendicon.png", typeof(MegaPaint)),
new Buttons("mybendicon.png", typeof(MegaPathDeform)),
new Buttons("mybendicon.png", typeof(MegaPivotAdjust)),
new Buttons("mybendicon.png", typeof(MegaPointCache)),
new Buttons("mypushicon.png", typeof(MegaPush)),
new Buttons("mybendicon.png", typeof(MegaRadialSkew)),
new Buttons("mybendicon.png", typeof(MegaRipple)),
new Buttons("mybendicon.png", typeof(MegaRopeDeform)),
new Buttons("mybendicon.png", typeof(MegaRubber)),
new Buttons("mybendicon.png", typeof(MegaSimpleMod)),
new Buttons("mybendicon.png", typeof(MegaSinusCurve)),
new Buttons("myskewicon.png", typeof(MegaSkew)),
new Buttons("myspherifyicon.png", typeof(MegaSpherify)),
new Buttons("mystretchicon.png", typeof(MegaStretch)),
new Buttons("mytapericon.png", typeof(MegaTaper)),
new Buttons("mytwisticon.png", typeof(MegaTwist)),
new Buttons("mybendicon.png", typeof(MegaVertexAnim)),
new Buttons("mybendicon.png", typeof(MegaVertNoise)),
new Buttons("mybendicon.png", typeof(MegaWave)),
new Buttons("mybendicon.png", typeof(MegaWorldPathDeform)),
#if false
"Bend", "MegaBend",
"Bubble", "MegaBubble",
"Bulge", "MegaBulge",
"Crumple", "MegaCrumple",
"Curve Deform", "MegaCurveDeform",
"Cylindrify", "MegaCylindrify",
"Displace", "MegaDisplace",
"FFD2x2x2", "MegaFFD2x2x2",
"FFD3x3x3", "MegaFFD3x3x3",
"FFD4x4x4", "MegaFFD4x4x4",
"Hump", "MegaHump",
"Melt", "MegaMelt",
"Noise", "MegaNoise",
"PageFlip", "MegaPageFlip",
"Paint", "MegaPaint",
"Path Deform", "MegaPathDeform",
"Pivot Adjust", "MegaPivotAdjust",
"Point Cache", "MegaPointCache",
"Push", "MegaPush",
"Radial Skew", "MegaRadialSkew",
"Ripple", "MegaRipple",
"Rope 2D", "MegaRopeDeform",
"Rubber", "MegaRubber",
"SimpleMod", "MegaSimpleMod",
"SinusCurve", "MegaSinusCurve",
"Skew", "MegaSkew",
"Spherify", "MegaSpherify",
"Stretch", "MegaStretch",
"Taper", "MegaTaper",
"Twist", "MegaTwist",
"VertexAnim", "MegaVertexAnim",
"VertNoise", "MegaVertNoise",
"Wave", "MegaWave",
"World PathDeform", "MegaWorldPathDeform",
#endif
};
#endif
//void Update()
//{
//Debug.Log("Mouse " + Input.mousePosition);
//Debug.Log("Update");
//}
#if false
public float scrollx = 0.0f;
void DoScrollIcons(GameObject obj, Buttons[] buttons, float width, int bstep, bool modobj)
{
//EditorGUILayout.BeginHorizontal(GUIStyle.none);
//EditorGUILayout.BeginArea(Rect(10, 10, 100, 100));
Rect pos = new Rect(0, 0, 400.0f, 64.0f);
pos.x = scrollx;
for ( int i = 0; i < buttons.Length; i++ )
{
//if ( GUILayout.Button(buttons[i].image, GUILayout.Width(width)) )
if ( buttons[i].content != null && GUI.Button(pos, buttons[i].content, GUIStyle.none) )
{
AddModType(obj, buttons[i].classname, modobj);
}
pos.x += width;
}
//EditorGUILayout.EndHorizontal();
}
#endif
#if false
void DoIcons(GameObject obj, Buttons[] buttons, float width, int bstep, bool modobj)
{
int off = 0;
//width /= 4.0f;
//bstep *= 4;
for ( int i = 0; i < buttons.Length; i++ )
{
if ( off == 0 )
{
EditorGUILayout.BeginHorizontal(GUIStyle.none);
}
//if ( GUILayout.Button(buttons[i].image, GUILayout.Width(width)) )
if ( buttons[i].content != null && GUILayout.Button(buttons[i].content, GUIStyle.none, GUILayout.Width(width), GUILayout.Height(48.0f)) )
{
AddModType(obj, buttons[i].classname, modobj);
}
off++;
if ( off == bstep )
{
off = 0;
EditorGUILayout.EndHorizontal();
}
}
if ( off != 0 )
{
EditorGUILayout.EndHorizontal();
}
}
#endif
static Color modcol = new Color(0.75f, 0.75f, 1.0f);
static Color uvmodscol = new Color(1.0f, 0.75f, 0.75f);
static Color warpcol = new Color(0.75f, 1.0f, 0.75f);
static Color selmodscol = new Color(1.0f, 1.0f, 0.75f);
static Color utilmodscol = new Color(0.75f, 1.0f, 1.0f);
static ModBut[] mods = new ModBut[] {
new ModBut("Bend", "Bend a mesh", typeof(MegaBend), modcol),
new ModBut("Bubble", "Bubble a mesh", typeof(MegaBubble), modcol),
new ModBut("Bulge", "Add a Bulge to a mesh", typeof(MegaBulge), modcol),
new ModBut("Crumple", "Crumple up a mesh, based on Unity Crumple", typeof(MegaCrumple), modcol),
new ModBut("Curve", "Use a curve to bend a mesh", typeof(MegaCurveDeform), modcol),
new ModBut("Cylindrify", "Cylindrify a mesh", typeof(MegaCylindrify), modcol),
new ModBut("Displace", "Displace vertices using a texture", typeof(MegaDisplace), modcol),
new ModBut("FFD 2x2x2", "FFD with a 2x2x2 lattice", typeof(MegaFFD2x2x2), modcol),
new ModBut("FFD 3x3x3", "FFD with a 3x3x3 lattice", typeof(MegaFFD3x3x3), modcol),
new ModBut("FFD 4x4x4", "FFD with a 4x4x4 lattice", typeof(MegaFFD4x4x4), modcol),
new ModBut("Hump", "Add humps to a mesh", typeof(MegaHump), modcol),
new ModBut("Melt", "Melt a mesh", typeof(MegaMelt), modcol),
new ModBut("Morph", "Morph a mesh", typeof(MegaMorph), modcol),
new ModBut("MorphOMat", "MorphOMatic a mesh", typeof(MegaMorphOMatic), modcol),
new ModBut("Noise", "Add noise to a mesh", typeof(MegaNoise), modcol),
new ModBut("PageFlip", "Make a page turning effect", typeof(MegaPageFlip), modcol),
new ModBut("Paint", "Paint deformation onto a mesh", typeof(MegaPaint), modcol),
new ModBut("Path", "Deform a mesh along a path", typeof(MegaPathDeform), modcol),
new ModBut("Pivot", "Alter pivot point on a mesh", typeof(MegaPivotAdjust), modcol),
new ModBut("PointCache", "Point cache animation or vertices", typeof(MegaPointCache), modcol),
new ModBut("Push", "Push vertices along their normals", typeof(MegaPush), modcol),
new ModBut("RadialSkew", "Radial skew a mesh", typeof(MegaRadialSkew), modcol),
new ModBut("Ripple", "Add a ripple to a mesh", typeof(MegaRipple), modcol),
new ModBut("Rope", "Deform a mesh using 2D Rope physics", typeof(MegaRopeDeform), modcol),
new ModBut("Rubber", "Add secondary rubber motion to a mesh", typeof(MegaRubber), modcol),
new ModBut("Simple", "Example of a simple mod", typeof(MegaSimpleMod), modcol),
new ModBut("Sinus", "Sin wave deformation based on Unity example", typeof(MegaSinusCurve), modcol),
new ModBut("Skew", "Skew a mesh", typeof(MegaSkew), modcol),
new ModBut("Spherify", "Turn a mesh into a sphere", typeof(MegaSpherify), modcol),
new ModBut("Squeeze", "Squeeze a mesh", typeof(MegaSqueeze), modcol),
new ModBut("Stretch", "Squash and stretch a mesh", typeof(MegaStretch), modcol),
new ModBut("Taper", "Taper a mesh", typeof(MegaTaper), modcol),
new ModBut("Twist", "Twist a mesh", typeof(MegaTwist), modcol),
new ModBut("VertAnim", "Animate vertices on a mesh", typeof(MegaVertexAnim), modcol),
new ModBut("Vert Noise", "Add Vertical noise to a mesh", typeof(MegaVertNoise), modcol),
new ModBut("Wave", "Add a wave to a mesh", typeof(MegaWave), modcol),
new ModBut("World Path", "Deform a mesh along a path in world space", typeof(MegaWorldPathDeform), modcol),
};
static ModBut[] warpmods = new ModBut[] {
new ModBut("Warp Bind", "Bind a mesh to a World Space Warp", typeof(MegaWarpBind), warpcol),
new ModBut("Bend", "Bend Warp", typeof(MegaBendWarp), warpcol),
new ModBut("Noise", "Noise Warp", typeof(MegaNoiseWarp), warpcol),
new ModBut("Ripple", "Ripple Warp", typeof(MegaRippleWarp), warpcol),
new ModBut("Skew", "Skew Warp", typeof(MegaSkewWarp), warpcol),
new ModBut("Stretch", "Stretch Warp", typeof(MegaStretchWarp), warpcol),
new ModBut("Taper", "Taper Warp", typeof(MegaTaperWarp), warpcol),
new ModBut("Twist", "Twist Warp", typeof(MegaTwistWarp), warpcol),
new ModBut("Wave", "Wave Warp", typeof(MegaWaveWarp), warpcol),
};
static ModBut[] uvmods = new ModBut[] {
new ModBut("UVAdjust", "Transform a meshes UV coords", typeof(MegaUVAdjust), uvmodscol),
new ModBut("UVTile", "Animate UVs to playback sprite anim", typeof(MegaUVTiles), uvmodscol),
};
static ModBut[] selmods = new ModBut[] {
new ModBut("VertCol", "Select vertices by vertex color", typeof(MegaVertColSelect), selmodscol),
new ModBut("Vol Select", "Select vertices by volumes", typeof(MegaVolSelect), selmodscol),
};
static ModBut[] utilmods = new ModBut[] {
new ModBut("Anim", "Animate morph percents", typeof(MegaMorphAnim), utilmodscol),
new ModBut("Animator", "Use anim clips to animate morphs", typeof(MegaMorphAnimator), utilmodscol),
new ModBut("BallBounce", "Simulate soft ball bouncing", typeof(BallBounce), utilmodscol),
new ModBut("Book", "Book builder", typeof(MegaBook), utilmodscol),
new ModBut("MultiCore", "Script to toggle multicore support", typeof(ToggleMultiCore), utilmodscol),
new ModBut("Page", "Build a page mesh for books", typeof(MegaMeshPage), utilmodscol),
new ModBut("Scroll", "Simulate an old paper scroll", typeof(Scroll), utilmodscol),
new ModBut("WalkBridge", "Helper to move a character across a bridge", typeof(WalkBridge), utilmodscol),
new ModBut("WalkRope", "Helper to move a character across a rope bridge", typeof(WalkRope), utilmodscol),
};
#if false
static ModBut[] uvmods1 = new ModBut[] {
new ModBut("UVAdjust", "Transform a meshes UV coords", typeof(MegaUVAdjust), uvmodscol),
new ModBut("UVTile", "Animate UVs to playback sprite anim", typeof(MegaUVTiles), uvmodscol),
};
static string[] mods1 = new string[] {
"Bend", "MegaBend",
"Bubble", "MegaBubble",
"Bulge", "MegaBulge",
"Crumple", "MegaCrumple",
"Curve", "MegaCurveDeform",
"Cylindrify", "MegaCylindrify",
"Displace", "MegaDisplace",
"FFD 2x2x2", "MegaFFD2x2x2",
"FFD 3x3x3", "MegaFFD3x3x3",
"FFD 4x4x4", "MegaFFD4x4x4",
"Hump", "MegaHump",
"Melt", "MegaMelt",
"Noise", "MegaNoise",
"PageFlip", "MegaPageFlip",
"Paint", "MegaPaint",
"Path", "MegaPathDeform",
"Pivot", "MegaPivotAdjust",
"PointCache", "MegaPointCache",
"Push", "MegaPush",
"RadialSkew", "MegaRadialSkew",
"Ripple", "MegaRipple",
"Rope 2D", "MegaRopeDeform",
"Rubber", "MegaRubber",
"SimpleMod", "MegaSimpleMod",
"SinusCurve", "MegaSinusCurve",
"Skew", "MegaSkew",
"Spherify", "MegaSpherify",
"Stretch", "MegaStretch",
"Taper", "MegaTaper",
"Twist", "MegaTwist",
"VertexAnim", "MegaVertexAnim",
"VertNoise", "MegaVertNoise",
"Wave", "MegaWave",
"World Path", "MegaWorldPathDeform",
};
static string[] uvmods = new string[] {
"UVAdjust", "MegaUVAdjust",
"UVTile", "MegaUVTile",
};
static string[] selmods = new string[] {
"Vert Col", "MegaVertColSelect",
"Vol Select", "MegaVolSelect",
};
static string[] morphmods = new string[] {
"Morph", "MegaMorph",
"MorphOMatic", "MegaMorphOMatic",
};
static string[] utils = new string[] {
"Anim", "MegaMorphAnim",
"Animator", "MegaMorphAnimator",
"Ball Bounce", "BallBounce",
"Book Builder", "MegaBook",
"MultiCore", "ToggleMultiCore",
"Page", "MegaMeshPage",
"Scroll", "Scroll",
"Walk Bridge", "WalkBridge",
"Walk Rope", "WalkRope",
};
#endif
void AddMod(GameObject go, string name, bool modobj)
{
if ( go )
{
MeshFilter mf = go.GetComponent<MeshFilter>();
if ( mf != null )
{
if ( modobj )
{
MegaModifyObject mod = go.GetComponent<MegaModifyObject>();
if ( mod == null )
{
mod = go.AddComponent<MegaModifyObject>();
mod.NormalMethod = NormalMethod;
}
}
if ( name != null )
{
MegaModifier md = (MegaModifier)UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(go, "Assets/Mega-Fiers/Editor/MegaFiers/MegaFiersWindow.cs (390,38)", name);
if ( md )
{
md.gizCol1 = col1;
md.gizCol2 = col2;
}
}
}
}
}
void AddModType(GameObject go, System.Type name, bool modobj)
{
if ( go )
{
MeshFilter mf = go.GetComponent<MeshFilter>();
if ( mf != null )
{
if ( modobj )
{
MegaModifyObject mod = go.GetComponent<MegaModifyObject>();
if ( mod == null )
{
mod = go.AddComponent<MegaModifyObject>();
mod.NormalMethod = NormalMethod;
}
}
if ( name != null )
{
MegaModifier md = (MegaModifier)go.AddComponent(name);
if ( md )
{
md.gizCol1 = col1;
md.gizCol2 = col2;
}
}
}
}
}
// Put common params in, and each shape has its sections
Vector2 scroll = Vector2.zero;
//bool showmods = false;
//bool showuvmods = false;
//bool showselmods = false;
//bool showmorphmods = false;
//bool showutilsmods = false;
void DoButtons(GameObject obj, string[] buttons, float width, int bstep, bool modobj)
{
Color c = GUI.backgroundColor;
int off = 0;
Color guicol = GUI.color;
GUI.color = Color.blue;
GUI.backgroundColor = Color.red;
GUI.contentColor = Color.green;
Color col1 = new Color(1.0f, 0.627f, 0.0f);
Color col2 = new Color(0.0f, 0.627f, 1.0f);
for ( int i = 0; i < buttons.Length; i += 2 )
{
if ( (i & 2) == 0 )
GUI.color = col1; //Color.blue;
else
GUI.color = col2; //Color.yellow;
if ( off == 0 )
{
EditorGUILayout.BeginHorizontal();
}
if ( GUILayout.Button(buttons[i], GUILayout.Width(width)) )
AddMod(obj, buttons[i + 1], modobj);
off++;
if ( off == bstep )
{
off = 0;
EditorGUILayout.EndHorizontal();
}
}
if ( off != 0 )
EditorGUILayout.EndHorizontal();
GUI.backgroundColor = c;
GUI.color = guicol;
GUI.contentColor = Color.white;
}
int DoButtons(GameObject obj, ModBut[] buttons, float width, int bstep, bool modobj, int off)
{
Color c = GUI.backgroundColor;
//int off = 0;
GUI.backgroundColor = Color.blue;
Color guicol = GUI.color;
GUI.color = new Color(1, 1, 1, 1); //Color.white;
GUI.backgroundColor = new Color(0, 0, 0, 0); //Color.white;
GUI.contentColor = Color.white;
//Color col1 = new Color(1.0f, 0.627f, 0.0f);
//Color col2 = new Color(0.0f, 0.627f, 1.0f);
for ( int i = 0; i < buttons.Length; i++ )
{
//if ( (i & 2) == 0 )
//GUI.backgroundColor = buttons[i].color; //Color.blue;
GUI.contentColor = buttons[i].color; //Color.blue;
//else
// GUI.backgroundColor = col2; //Color.yellow;
//Color co = buttons[i].color * 0.08f;
//co.a = 0.18f;
GUI.backgroundColor = buttons[i].color * 0.08f;
if ( off == 0 )
{
EditorGUILayout.BeginHorizontal();
}
//if ( GUILayout.Button(buttons[i].content, GUILayout.Width(width)) )
if ( GUILayout.Button(buttons[i].content, GUILayout.Width(width)) )
AddModType(obj, buttons[i].classname, modobj);
off++;
if ( off == bstep )
{
off = 0;
EditorGUILayout.EndHorizontal();
}
}
//if ( off != 0 )
// EditorGUILayout.EndHorizontal();
GUI.backgroundColor = c;
GUI.color = guicol;
return off;
}
public int toolbarInt = 0;
public string[] toolbarStrings = new string[] {"All", "Mod", "Warp", "UV", "Sel", "Util" };
void OnGUI()
{
//name = EditorGUILayout.TextField("Name", name);
scroll = EditorGUILayout.BeginScrollView(scroll);
GameObject obj = Selection.activeGameObject;
float width = this.position.width; // / 2.0f;
//if ( obj )
{
//MeshFilter mf = obj.GetComponent<MeshFilter>();
//if ( mf != null )
{
//if ( GUILayout.Button("Modify Object") ) AddMod(obj, null, true); //.AddComponent<MegaModifyObject>();
float butwidth = 80.0f;
int bstep = (int)(width / butwidth);
if ( bstep == 0 )
bstep = 1;
//int off = 0;
//showmods = EditorGUILayout.Foldout(showmods, "Modifiers");
toolbarInt = GUILayout.Toolbar(toolbarInt, toolbarStrings, GUILayout.MaxWidth(250.0f));
//if ( showmods )
{
int off = 0;
//DoScrollIcons(obj, buts, 48.0f, (int)(width / 48.0f), true);
//DoIcons(obj, buts, 48.0f, (int)(width / 48.0f), true);
switch ( toolbarInt )
{
case 0:
off = DoButtons(obj, mods, (width / bstep) - 6.0f, bstep, true, off);
off = DoButtons(obj, warpmods, (width / bstep) - 6.0f, bstep, true, off);
off = DoButtons(obj, uvmods, (width / bstep) - 6.0f, bstep, true, off);
off = DoButtons(obj, selmods, (width / bstep) - 6.0f, bstep, true, off);
off = DoButtons(obj, utilmods, (width / bstep) - 6.0f, bstep, true, off);
break;
case 1: DoButtons(obj, mods, (width / bstep) - 6.0f, bstep, true, off); break;
case 2: DoButtons(obj, warpmods, (width / bstep) - 6.0f, bstep, true, off); break;
case 3: DoButtons(obj, uvmods, (width / bstep) - 6.0f, bstep, true, off); break;
case 4: DoButtons(obj, selmods, (width / bstep) - 6.0f, bstep, true, off); break;
case 5: DoButtons(obj, utilmods, (width / bstep) - 6.0f, bstep, true, off); break;
}
if ( off != 0 )
EditorGUILayout.EndHorizontal();
//GUI.backgroundColor = Color.grey;
#if false
if ( GUILayout.Button("Modify Object") ) AddMod(obj, null, true); //.AddComponent<MegaModifyObject>();
showcommon = EditorGUILayout.Foldout(showcommon, "Common");
if ( showcommon )
{
NormalMethod = (MegaNormalMethod)EditorGUILayout.EnumPopup("Normal Method", NormalMethod);
//axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", axis);
col1 = EditorGUILayout.ColorField("Color 1", col1);
col2 = EditorGUILayout.ColorField("Color 2", col2);
}
#endif
#if false
for ( int i = 0; i < mods.Length; i += 2 )
{
if ( off == 0 )
{
EditorGUILayout.BeginHorizontal();
}
if ( GUILayout.Button(mods[i], GUILayout.Width((width / bstep) - 6.0f)) )
AddMod(obj, mods[i + 1]);
off++;
if ( off == bstep )
{
off = 0;
EditorGUILayout.EndHorizontal();
}
}
#endif
}
//showuvmods = EditorGUILayout.Foldout(showuvmods, "UV Modifiers");
//if ( showuvmods )
// DoButtons(obj, uvmods, (width / bstep) - 6.0f, bstep, true);
//showmorphmods = EditorGUILayout.Foldout(showmorphmods, "Morph");
//if ( showmorphmods )
// DoButtons(obj, morphmods, (width / bstep) - 6.0f, bstep, true);
//showselmods = EditorGUILayout.Foldout(showselmods, "Selection");
//if ( showselmods )
// DoButtons(obj, selmods, (width / bstep) - 6.0f, bstep, true);
//showutilsmods = EditorGUILayout.Foldout(showutilsmods, "Utils");
//if ( showutilsmods )
// DoButtons(obj, utils, (width / bstep) - 6.0f, bstep, false);
}
}
EditorGUILayout.EndScrollView();
}
#if false
static void CreateShape(string type)
{
Vector3 pos = UnityEditor.SceneView.lastActiveSceneView.pivot;
MegaShape ms = null;
GameObject go = new GameObject(type + " Shape");
switch ( type )
{
case "Circle": ms = go.AddComponent<MegaShapeCircle>(); break;
case "Star": ms = go.AddComponent<MegaShapeStar>(); break;
case "NGon": ms = go.AddComponent<MegaShapeNGon>(); break;
case "Arc": ms = go.AddComponent<MegaShapeArc>(); break;
case "Ellipse": ms = go.AddComponent<MegaShapeEllipse>(); break;
case "Rectangle": ms = go.AddComponent<MegaShapeRectangle>(); break;
case "Helix": ms = go.AddComponent<MegaShapeHelix>(); break;
}
go.transform.position = pos;
Selection.activeObject = go;
if ( ms != null )
{
ms.axis = axis;
ms.drawHandles = drawhandles;
ms.drawKnots = drawknots;
ms.col1 = col1;
ms.col2 = col2;
ms.KnotSize = knotsize;
ms.stepdist = stepdist;
}
}
#endif
}
\ No newline at end of file
fileFormatVersion: 2
guid: 61f6bd5b3ad18024488bf972d1263ee2
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaHump))]
public class MegaHumpEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Hump Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/hump_help.png"); }
public override bool Inspector()
{
MegaHump mod = (MegaHump)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.cycles = EditorGUILayout.FloatField("Cycles", mod.cycles);
mod.phase = EditorGUILayout.FloatField("Phase", mod.phase);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.speed = EditorGUILayout.FloatField("Speed", mod.speed);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: d2b823aa1107084428512bb14d96c796
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaMelt))]
public class MegaMeltEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Melt Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool Inspector()
{
MegaMelt mod = (MegaMelt)target;
EditorGUIUtility.LookLikeControls();
mod.Amount = EditorGUILayout.FloatField("Amount", mod.Amount);
mod.Spread = EditorGUILayout.FloatField("Spread", mod.Spread);
mod.MaterialType = (MegaMeltMat)EditorGUILayout.EnumPopup("Material Type", mod.MaterialType);
mod.Solidity = EditorGUILayout.FloatField("Solidity", mod.Solidity);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.FlipAxis = EditorGUILayout.Toggle("Flip Axis", mod.FlipAxis);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: ea890df6cb5109142b042faea97fe090
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaModifier))]
public class MegaModifierEditor : Editor
{
public Texture image;
public bool showhelp = false;
public virtual Texture LoadImage() { return null; }
public virtual string GetHelpString() { return "Modifer by Chris West"; }
public virtual bool Inspector() { return true; }
public virtual bool DisplayCommon() { return true; }
#if false
[DrawGizmo(GizmoType.NotSelected | GizmoType.Pickable)]
static void RenderGizmo(MegaModifier mod, GizmoType gizmoType)
{
}
[DrawGizmo(GizmoType.SelectedOrChild | GizmoType.Pickable)]
static void RenderGizmoSelected(MegaModifier mod, GizmoType gizmoType)
{
if ( GUI.changed )
{
Debug.Log("Editing " + mod.ModName());
}
}
#endif
void OnDestroy()
{
MegaModifiers[] con = (MegaModifiers[])FindSceneObjectsOfType(typeof(MegaModifiers));
for ( int i = 0; i < con.Length; i++ )
{
con[i].BuildList();
}
}
public bool showmodparams = true;
//bool showweight = true;
public void CommonModParamsBasic(MegaModifier mod)
{
// Basic mod stuff
//showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
//if ( showmodparams )
//{
mod.ModEnabled = EditorGUILayout.Toggle("Mod Enabled", mod.ModEnabled);
mod.DisplayGizmo = EditorGUILayout.Toggle("Display Gizmo", mod.DisplayGizmo);
int order = EditorGUILayout.IntField("Order", mod.Order);
if ( order != mod.Order )
{
mod.Order = order;
MegaModifiers context = mod.GetComponent<MegaModifiers>();
if ( context != null )
context.BuildList();
}
mod.gizCol1 = EditorGUILayout.ColorField("Giz Col 1", mod.gizCol1);
mod.gizCol2 = EditorGUILayout.ColorField("Giz Col 2", mod.gizCol2);
mod.steps = EditorGUILayout.IntField("Gizmo Detail", mod.steps);
if ( mod.steps < 1 )
mod.steps = 1;
//}
//mod.useWeights = EditorGUILayout.Toggle("Use Weights", mod.useWeights);
//if ( mod.useWeights )
// mod.weightChannel = (MegaWeightChannel)EditorGUILayout.EnumPopup("Weight Channel", mod.weightChannel);
}
public void CommonModParams(MegaModifier mod)
{
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
{
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Rst Off") )
{
mod.Offset = Vector3.zero;
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Rst Pos") )
{
mod.gizmoPos = Vector3.zero;
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Rst Rot") )
{
mod.gizmoRot = Vector3.zero;
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Rst Scl") )
{
mod.gizmoScale = Vector3.one;
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
mod.Offset = EditorGUILayout.Vector3Field("Offset", mod.Offset);
mod.gizmoPos = EditorGUILayout.Vector3Field("Gizmo Pos", mod.gizmoPos);
mod.gizmoRot = EditorGUILayout.Vector3Field("Gizmo Rot", mod.gizmoRot);
mod.gizmoScale = EditorGUILayout.Vector3Field("Gizmo Scale", mod.gizmoScale);
CommonModParamsBasic(mod);
#if false
mod.ModEnabled = EditorGUILayout.Toggle("Mod Enabled", mod.ModEnabled);
mod.DisplayGizmo = EditorGUILayout.Toggle("Display Gizmo", mod.DisplayGizmo);
int order = EditorGUILayout.IntField("Order", mod.Order);
if ( order != mod.Order )
{
mod.Order = order;
MegaModifiers context = mod.GetComponent<MegaModifiers>();
if ( context != null )
context.BuildList();
}
mod.gizCol1 = EditorGUILayout.ColorField("Giz Col 1", mod.gizCol1);
mod.gizCol2 = EditorGUILayout.ColorField("Giz Col 2", mod.gizCol2);
//showweight = EditorGUILayout.Foldout(showweight, "Modifier Weight Params");
//if ( showweight )
{
//mod.useWeights = EditorGUILayout.Toggle("Use Weights", mod.useWeights);
//if ( mod.useWeights )
//{
//mod.weightChannel = (MegaWeightChannel)EditorGUILayout.EnumPopup("Weight Channel", mod.weightChannel);
//}
}
#endif
}
}
public virtual void DrawGUI()
{
//showhelp = EditorGUILayout.Foldout(showhelp, "Help");
//if ( showhelp )
//{
//if ( image == null )
//image = LoadImage();
//if ( image != null )
//{
//float w = Screen.width - 12.0f;
//float h = (w / image.width) * image.height;
//if ( h > image.height )
//h = image.height;
//GUILayout.Label((Texture)image, GUIStyle.none, GUILayout.Width(w), GUILayout.Height(h));
//}
//}
if ( DisplayCommon() )
CommonModParams((MegaModifier)target);
if ( GUI.changed )
EditorUtility.SetDirty(target);
if ( Inspector() )
DrawDefaultInspector();
//if ( showhelp )
//GUILayout.TextArea(GetHelpString());
}
public virtual void DrawSceneGUI()
{
MegaModifier mod = (MegaModifier)target;
if ( mod.ModEnabled && mod.DisplayGizmo && MegaModifiers.GlobalDisplay && showmodparams )
{
MegaModifiers context = mod.GetComponent<MegaModifiers>();
if ( context != null && context.Enabled && context.DrawGizmos )
{
//mod.Offset = -Handles.PositionHandle(-mod.Offset, Quaternion.identity);
float a = mod.gizCol1.a;
Color col = Color.white;
Quaternion rot = mod.transform.localRotation;
Handles.matrix = Matrix4x4.identity;
if ( mod.Offset != Vector3.zero )
{
Vector3 pos = mod.transform.localToWorldMatrix.MultiplyPoint(-mod.Offset);
Handles.Label(pos, mod.ModName() + " Offset\n" + mod.Offset.ToString("0.000"));
col = Color.blue;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(180.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.green;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(90.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.red;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(0.0f, -90.0f, 0.0f), mod.GizmoSize());
}
// gizmopos
if ( mod.gizmoPos != Vector3.zero )
{
Vector3 pos = mod.transform.localToWorldMatrix.MultiplyPoint(-mod.gizmoPos);
Handles.Label(pos, mod.ModName() + " Pos\n" + mod.gizmoPos.ToString("0.000"));
col = Color.blue;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(180.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.green;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(90.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.red;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(0.0f, -90.0f, 0.0f), mod.GizmoSize());
}
Handles.matrix = Matrix4x4.identity;
}
}
}
public override void OnInspectorGUI()
{
DrawGUI();
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
public void OnSceneGUI()
{
DrawSceneGUI();
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: ff7d3520ad764fe42a99fb6e18fc6246
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaModifyGroup))]
public class MegaModifyGroupEditor : Editor
{
Texture image;
//bool showhelp = false;
bool showorder = false;
bool showmulti = false;
//[DrawGizmo(GizmoType.SelectedOrChild)]
//static void RenderGizmoSelected(ModifyObject mod, GizmoType gizmoType)
//{
//mod.ColliderTest();
//}
bool targets = false;
public override void OnInspectorGUI()
{
MegaModifyGroup mod = (MegaModifyGroup)target;
EditorGUIUtility.LookLikeInspector();
MegaModifiers.GlobalDisplay = EditorGUILayout.Toggle("GlobalDisplayGizmos", MegaModifiers.GlobalDisplay);
mod.Enabled = EditorGUILayout.Toggle("Enabled", mod.Enabled);
mod.recalcnorms = EditorGUILayout.Toggle("Recalc Normals", mod.recalcnorms);
MegaNormalMethod method = mod.NormalMethod;
mod.NormalMethod = (MegaNormalMethod)EditorGUILayout.EnumPopup("Normal Method", mod.NormalMethod);
mod.recalcbounds = EditorGUILayout.Toggle("Recalc Bounds", mod.recalcbounds);
mod.recalcCollider = EditorGUILayout.Toggle("Recalc Collider", mod.recalcCollider);
mod.recalcTangents = EditorGUILayout.Toggle("Recalc Tangents", mod.recalcTangents);
mod.DoLateUpdate = EditorGUILayout.Toggle("Do Late Update", mod.DoLateUpdate);
mod.GrabVerts = EditorGUILayout.Toggle("Grab Verts", mod.GrabVerts);
mod.DrawGizmos = EditorGUILayout.Toggle("Draw Gizmos", mod.DrawGizmos);
if ( mod.NormalMethod != method && mod.NormalMethod == MegaNormalMethod.Mega )
{
mod.BuildNormalMapping(mod.mesh, false);
}
if ( GUILayout.Button("Threading Options") )
showmulti = !showmulti;
if ( showmulti )
{
MegaModifiers.ThreadingOn = EditorGUILayout.Toggle("Threading Enabled", MegaModifiers.ThreadingOn);
mod.UseThreading = EditorGUILayout.Toggle("Thread This Object", mod.UseThreading);
}
EditorGUIUtility.LookLikeControls();
if ( GUI.changed )
EditorUtility.SetDirty(target);
showorder = EditorGUILayout.Foldout(showorder, "Modifier Order");
if ( showorder && mod.mods != null )
{
for ( int i = 0; i < mod.mods.Length; i++ )
{
EditorGUILayout.LabelField("", i.ToString() + " - " + mod.mods[i].ModName() + " " + mod.mods[i].Order);
}
}
if ( GUILayout.Button("Targets") )
targets = !targets;
if ( targets )
{
if ( GUILayout.Button("Add Target") )
{
MegaModifierTarget targ = new MegaModifierTarget();
mod.targets.Add(targ);
}
for ( int i = 0; i < mod.targets.Count; i++ )
{
EditorGUILayout.BeginHorizontal();
mod.targets[i].go = (GameObject)EditorGUILayout.ObjectField("Target " + i, mod.targets[i].go, typeof(GameObject), true);
if ( GUILayout.Button("Del") )
{
mod.targets.Remove(mod.targets[i]);
i--;
}
EditorGUILayout.EndHorizontal();
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 3ba58d22565742943b90bf3506b0cda6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaModifyObject))]
public class MegaModifyObjectEditor : Editor
{
Texture image;
//bool showhelp = false;
bool showorder = false;
bool showmulti = false;
bool showgroups = false;
//[DrawGizmo(GizmoType.SelectedOrChild)]
//static void RenderGizmoSelected(ModifyObject mod, GizmoType gizmoType)
//{
//mod.ColliderTest();
//}
public override void OnInspectorGUI()
{
MegaModifyObject mod = (MegaModifyObject)target;
//showhelp = EditorGUILayout.Foldout(showhelp, "Help");
//if ( showhelp )
//{
//if ( image == null )
//image = (Texture)EditorGUIUtility.LoadRequired("mod_help.png");
//if ( image != null )
//{
//float w = Screen.width - 12.0f;
//float h = (w / image.width) * image.height;
//GUILayout.Label((Texture)image, GUIStyle.none, GUILayout.Width(w), GUILayout.Height(h));
//}
//}
EditorGUIUtility.LookLikeInspector();
MegaModifiers.GlobalDisplay = EditorGUILayout.Toggle("GlobalDisplayGizmos", MegaModifiers.GlobalDisplay);
mod.Enabled = EditorGUILayout.Toggle("Enabled", mod.Enabled);
mod.recalcnorms = EditorGUILayout.Toggle("Recalc Normals", mod.recalcnorms);
MegaNormalMethod method = mod.NormalMethod;
mod.NormalMethod = (MegaNormalMethod)EditorGUILayout.EnumPopup("Normal Method", mod.NormalMethod);
mod.recalcbounds = EditorGUILayout.Toggle("Recalc Bounds", mod.recalcbounds);
mod.recalcCollider = EditorGUILayout.Toggle("Recalc Collider", mod.recalcCollider);
mod.recalcTangents = EditorGUILayout.Toggle("Recalc Tangents", mod.recalcTangents);
mod.DoLateUpdate = EditorGUILayout.Toggle("Do Late Update", mod.DoLateUpdate);
mod.GrabVerts = EditorGUILayout.Toggle("Grab Verts", mod.GrabVerts);
mod.DrawGizmos = EditorGUILayout.Toggle("Draw Gizmos", mod.DrawGizmos);
if ( mod.NormalMethod != method && mod.NormalMethod == MegaNormalMethod.Mega )
{
mod.BuildNormalMapping(mod.mesh, false);
}
//showmulti = EditorGUILayout.Foldout(showmulti, "Multi Core");
if ( GUILayout.Button("Threading Options") )
showmulti = !showmulti;
if ( showmulti )
{
MegaModifiers.ThreadingOn = EditorGUILayout.Toggle("Threading Enabled", MegaModifiers.ThreadingOn);
mod.UseThreading = EditorGUILayout.Toggle("Thread This Object", mod.UseThreading);
}
EditorGUIUtility.LookLikeControls();
if ( GUI.changed )
EditorUtility.SetDirty(target);
showorder = EditorGUILayout.Foldout(showorder, "Modifier Order");
if ( showorder && mod.mods != null )
{
for ( int i = 0; i < mod.mods.Length; i++ )
{
EditorGUILayout.LabelField("", i.ToString() + " - " + mod.mods[i].ModName() + " " + mod.mods[i].Order);
}
}
// Group stuff
if ( GUILayout.Button("Group Members") )
showgroups = !showgroups;
if ( showgroups )
{
//if ( GUILayout.Button("Add Object") )
//{
//MegaModifierTarget targ = new MegaModifierTarget();
// mod.group.Add(targ);
//}
for ( int i = 0; i < mod.group.Count; i++ )
{
EditorGUILayout.BeginHorizontal();
mod.group[i] = (GameObject)EditorGUILayout.ObjectField("Obj " + i, mod.group[i], typeof(GameObject), true);
if ( GUILayout.Button("Del") )
{
mod.group.Remove(mod.group[i]);
i--;
}
EditorGUILayout.EndHorizontal();
}
GameObject newobj = (GameObject)EditorGUILayout.ObjectField("Add", null, typeof(GameObject), true);
if ( newobj )
{
mod.group.Add(newobj);
}
if ( GUILayout.Button("Update") )
{
// for each group member check if it has a modify object comp, if not add one and copy values over
// calculate box for all meshes and set, and set the Offset for each one
// then for each modifier attached find or add and set instance value
// in theory each gizmo should overlap the others
// Have a method to update box and offsets if we allow moving in the group
}
}
}
}
fileFormatVersion: 2
guid: be83e9d9f7d2f32448f09b8515441d77
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaMorphAnim))]
public class MegaMorphAnimEditor : Editor
{
int GetIndex(string name, string[] channels)
{
int index = -1;
for ( int i = 0; i < channels.Length; i++ )
{
if ( channels[i] == name )
{
index = i;
break;
}
}
return index;
}
// TODO: Need none in the popup to clear a channel
public override void OnInspectorGUI()
{
MegaMorphAnim anim = (MegaMorphAnim)target;
MegaMorph morph = anim.gameObject.GetComponent<MegaMorph>();
if ( morph != null )
{
string[] channels = morph.GetChannelNames();
int index = GetIndex(anim.SrcChannel, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel = channels[index];
anim.SetChannel(morph, 0);
}
anim.Percent = EditorGUILayout.Slider("Percent", anim.Percent, 0.0f, 100.0f);
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel1, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel1 = channels[index];
anim.SetChannel(morph, 1);
}
anim.Percent1 = EditorGUILayout.Slider("Percent", anim.Percent1, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel2, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel2 = channels[index];
anim.SetChannel(morph, 2);
}
anim.Percent2 = EditorGUILayout.Slider("Percent", anim.Percent2, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel3, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel3 = channels[index];
anim.SetChannel(morph, 3);
}
anim.Percent3 = EditorGUILayout.Slider("Percent", anim.Percent3, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel4, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel4 = channels[index];
anim.SetChannel(morph, 4);
}
anim.Percent4 = EditorGUILayout.Slider("Percent", anim.Percent4, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel5, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel5 = channels[index];
anim.SetChannel(morph, 5);
}
anim.Percent5 = EditorGUILayout.Slider("Percent", anim.Percent5, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel6, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel6 = channels[index];
anim.SetChannel(morph, 6);
}
anim.Percent6 = EditorGUILayout.Slider("Percent", anim.Percent6, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel7, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel7 = channels[index];
anim.SetChannel(morph, 7);
}
anim.Percent7 = EditorGUILayout.Slider("Percent", anim.Percent7, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel8, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel8 = channels[index];
anim.SetChannel(morph, 8);
}
anim.Percent8 = EditorGUILayout.Slider("Percent", anim.Percent8, 0.0f, 100.0f);
}
if ( index != -1 )
{
index = GetIndex(anim.SrcChannel9, channels);
index = EditorGUILayout.Popup("Source Channel", index, channels);
if ( index != -1 )
{
anim.SrcChannel9 = channels[index];
anim.SetChannel(morph, 9);
}
anim.Percent9 = EditorGUILayout.Slider("Percent", anim.Percent9, 0.0f, 100.0f);
}
if ( GUI.changed )
{
EditorUtility.SetDirty(target);
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 452a4a5661ea1a147b4383812eccad71
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaMorphAnimator))]
public class MegaMorphAnimatorEditor : Editor
{
// TODO: Need none in the popup to clear a channel
public override void OnInspectorGUI()
{
MegaMorphAnimator anim = (MegaMorphAnimator)target;
string[] clips = anim.GetClipNames();
anim.current = EditorGUILayout.Popup("Playing Clip", anim.current, clips);
//anim.t = EditorGUILayout.FloatField("t", anim.t);
//anim.at = EditorGUILayout.FloatField("at", anim.at);
if ( GUILayout.Button("Add Clip") )
anim.AddClip("Clip " + anim.clips.Count, 0.0f, 1.0f, MegaRepeatMode.Loop);
EditorGUILayout.BeginVertical();
for ( int i = 0; i < anim.clips.Count; i++ )
{
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.TextArea("" + i + " - ");
anim.clips[i].name = EditorGUILayout.TextField(anim.clips[i].name);
anim.clips[i].start = EditorGUILayout.FloatField(anim.clips[i].start, GUILayout.Width(40));
anim.clips[i].end = EditorGUILayout.FloatField(anim.clips[i].end, GUILayout.Width(40));
anim.clips[i].loop = (MegaRepeatMode)EditorGUILayout.EnumPopup(anim.clips[i].loop);
if ( GUILayout.Button("-") )
{
anim.clips.Remove(anim.clips[i]);
}
EditorGUILayout.EndHorizontal();
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 94ad28898cb2bea40832ba64aa3e773d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
public class MegaTargetMesh
{
public string name;
public List<Vector3> verts = new List<Vector3>();
public List<int> faces = new List<int>();
static public List<MegaTargetMesh> LoadTargets(string path, float scale, bool flipzy, bool negx)
{
List<MegaTargetMesh> targets = new List<MegaTargetMesh>();
MegaTargetMesh current = null;
StreamReader stream = File.OpenText(path);
string entireText = stream.ReadToEnd();
stream.Close();
entireText = entireText.Replace("\n", "\r\n");
List<Vector3> verts = new List<Vector3>();
using ( StringReader reader = new StringReader(entireText) )
{
string currentText = reader.ReadLine();
char[] splitIdentifier = { ' ' };
string[] brokenString;
string name = "";
Vector3 p = Vector3.zero;
while ( currentText != null )
{
if ( !currentText.StartsWith("v ") && !currentText.StartsWith("g ") && !currentText.StartsWith("f ") )
{
currentText = reader.ReadLine();
if ( currentText != null )
currentText = currentText.Replace(" ", " ");
}
else
{
currentText = currentText.Trim();
brokenString = currentText.Split(splitIdentifier, 50);
switch ( brokenString[0] )
{
case "f":
if ( verts.Count > 0 )
{
current = new MegaTargetMesh();
current.name = name;
current.verts = new List<Vector3>(verts);
current.faces = new List<int>();
targets.Add(current);
verts.Clear();
}
break;
case "g":
name = brokenString[1];
break;
case "v":
p.x = System.Convert.ToSingle(brokenString[1]) * scale;
if ( negx )
{
p.x = -p.x;
}
if ( flipzy )
{
p.y = System.Convert.ToSingle(brokenString[3]) * scale;
p.z = System.Convert.ToSingle(brokenString[2]) * scale;
}
else
{
p.y = System.Convert.ToSingle(brokenString[2]) * scale;
p.z = System.Convert.ToSingle(brokenString[3]) * scale;
}
verts.Add(p);
break;
}
currentText = reader.ReadLine();
if ( currentText != null )
currentText = currentText.Replace(" ", " ");
}
}
}
return targets;
}
}
// Have a simple text format so can do a simple max exporter and others can do blender scripts etc
[CustomEditor(typeof(MegaMorph))]
public class MegaMorphEditor : Editor
{
static string lastpath = " ";
static public Color ChanCol1 = new Color(0.44f, 0.67f, 1.0f);
static public Color ChanCol2 = new Color(1.0f, 0.67f, 0.44f);
Stack<Color> bcol = new Stack<Color>();
Stack<Color> ccol = new Stack<Color>();
Stack<Color> col = new Stack<Color>();
bool extraparams = false;
int FindVert(Vector3 vert, List<Vector3> verts, float tolerance)
{
float closest = Vector3.SqrMagnitude(verts[0] - vert);
int find = 0;
for ( int i = 0; i < verts.Count; i++ )
{
float dif = Vector3.SqrMagnitude(verts[i] - vert);
if ( dif < closest )
{
closest = dif;
find = i;
}
}
if ( closest > tolerance ) //0.0001f ) // not exact
return -1;
return find; //0;
}
int FindVert(Vector3 vert, List<Vector3> verts, float tolerance, float scl, bool flipyz, bool negx, int vn)
{
int find = 0;
if ( negx )
vert.x = -vert.x;
if ( flipyz )
{
float z = vert.z;
vert.z = vert.y;
vert.y = z;
}
vert /= scl;
float closest = Vector3.SqrMagnitude(verts[0] - vert);
for ( int i = 0; i < verts.Count; i++ )
{
float dif = Vector3.SqrMagnitude(verts[i] - vert);
if ( dif < closest )
{
closest = dif;
find = i;
}
}
if ( closest > tolerance ) //0.0001f ) // not exact
return -1;
return find; //0;
}
bool FindMatch(Vector3 vert, Vector3[] verts, float tolerance)
{
float closest = Vector3.SqrMagnitude(verts[0] - vert);
for ( int i = 0; i < verts.Length; i++ )
{
float dif = Vector3.SqrMagnitude(verts[i] - vert);
if ( dif < closest )
closest = dif;
}
if ( closest > tolerance ) //0.0001f ) // not exact
return false;
return true;
}
Vector3 Extents(Vector3[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0];
max = verts[0];
for ( int i = 1; i < verts.Length; i++ )
{
if ( verts[i].x < min.x ) min.x = verts[i].x;
if ( verts[i].y < min.y ) min.y = verts[i].y;
if ( verts[i].z < min.z ) min.z = verts[i].z;
if ( verts[i].x > max.x ) max.x = verts[i].x;
if ( verts[i].y > max.y ) max.y = verts[i].y;
if ( verts[i].z > max.z ) max.z = verts[i].z;
}
extent = max - min;
}
return extent;
}
Vector3 Extents(List<Vector3> verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Count > 0 )
{
min = verts[0];
max = verts[0];
for ( int i = 1; i < verts.Count; i++ )
{
if ( verts[i].x < min.x ) min.x = verts[i].x;
if ( verts[i].y < min.y ) min.y = verts[i].y;
if ( verts[i].z < min.z ) min.z = verts[i].z;
if ( verts[i].x > max.x ) max.x = verts[i].x;
if ( verts[i].y > max.y ) max.y = verts[i].y;
if ( verts[i].z > max.z ) max.z = verts[i].z;
}
extent = max - min;
}
return extent;
}
// TODO: report error if target vert counts dont match base mapping
bool DoMapping(MegaModifiers mod, MegaMorph morph, MegaTargetMesh tm, int[] mapping, float scale, bool flipyz, bool negx)
{
for ( int i = 0; i < mod.verts.Length; i++ )
{
float a = (float)i / (float)mod.verts.Length;
EditorUtility.DisplayProgressBar("Mapping", "Mapping vertex " + i, a);
mapping[i] = FindVert(mod.verts[i], tm.verts, morph.tolerance, scale, flipyz, negx, i);
if ( mapping[i] == -1 )
{
// Failed
EditorUtility.ClearProgressBar();
return false;
}
}
EditorUtility.ClearProgressBar();
return true;
}
bool TryMapping(List<MegaTargetMesh> targets, MegaMorph morph)
{
MegaModifiers mod = morph.GetComponent<MegaModifiers>();
if ( mod == null )
{
//Debug.Log("No modifyobject found");
EditorUtility.DisplayDialog("Missing ModifyObject!", "No ModifyObject script found on the object", "OK");
return false;
}
int[] mapping = new int[mod.verts.Length];
for ( int i = 0; i < 18; i++ )
{
Debug.Log("v[" + i + "] " + mod.verts[i].ToString("0.00000"));
}
for ( int i = 0; i < 18; i++ )
{
Debug.Log("t[" + i + "] " + targets[0].verts[i].ToString("0.00000"));
}
for ( int t = 0; t < targets.Count; t++ )
{
MegaTargetMesh tm = targets[t];
// Get extents for mod verts and for imported meshes, if not the same then scale
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = Extents(mod.verts, out min1, out max1);
Vector3 ex2 = Extents(tm.verts, out min2, out max2);
Debug.Log("min1 " + min1.ToString("0.000"));
Debug.Log("max1 " + max1.ToString("0.000"));
Debug.Log("min2 " + min2.ToString("0.000"));
Debug.Log("max2 " + max2.ToString("0.000"));
// need min max on all axis so we can produce an offset to add
float d1 = ex1.x;
float d2 = ex2.x;
float scl = d1 / d2; //d2 / d1;
bool flipyz = false;
bool negx = false;
//Vector3 offset = (min2 * scl) - min1;
//Debug.Log("offset " + offset.ToString("0.0000"));
Debug.Log("scl " + scl);
// So try to match first vert using autoscale and no flip
bool mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped ) //DoMapping(mod, morph, tm, mapping, scl, flipyz, negx) )
{
flipyz = false;
negx = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
}
}
}
if ( mapped )
{
morph.importScale = scl;
morph.flipyz = flipyz;
morph.negx = negx;
morph.mapping = mapping;
// if mapping was ok set opoints
morph.oPoints = tm.verts.ToArray();
for ( int i = 0; i < morph.oPoints.Length; i++ )
{
Vector3 p = morph.oPoints[i];
if ( negx )
p.x = -p.x;
if ( flipyz )
{
float z = p.z;
p.z = p.y;
p.y = z;
}
morph.oPoints[i] = p * morph.importScale;
}
return true;
}
}
return false;
}
void LoadBase(MegaMorph morph)
{
string filename = EditorUtility.OpenFilePanel("Morph Base", lastpath, "obj");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
List<MegaTargetMesh> targets = MegaTargetMesh.LoadTargets(filename, 1.0f, false, false); //morph.importScale, morph.flipyz, morph.negx);
// only use first
if ( targets != null && targets.Count > 0 )
{
if ( !TryMapping(targets, morph) )
{
// No match found
EditorUtility.DisplayDialog("Mapping Failed!", "Mapping of " + Path.GetFileNameWithoutExtension(filename) + " failed!", "OK");
EditorUtility.ClearProgressBar();
return;
}
}
}
// remove mPoints from channel, just use target list, if targets.Count == 1 then use delta
// first target goes into mPoints
// guess we should update any targets who we have already, ie use name
void LoadTargets(MegaMorphChan channel)
{
MegaMorph mr = (MegaMorph)target;
string filename = EditorUtility.OpenFilePanel("Morph Targets", lastpath, "obj");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
List<MegaTargetMesh> targets = MegaTargetMesh.LoadTargets(filename, mr.importScale, mr.flipyz, mr.negx);
if ( targets != null )
{
if ( channel.mName == "Empty" )
channel.mName = Path.GetFileNameWithoutExtension(filename);
// Now need to check that each target has correct num verts and face list matches
for ( int i = 0; i < targets.Count; i++ )
{
MegaTargetMesh tm = targets[i];
if ( tm.verts.Count != mr.oPoints.Length )
EditorUtility.DisplayDialog("Target Vertex count mismatch!", "Target " + tm.name + " has wrong number of verts", "OK");
else
{
// See if we have a target with this name, if so update that
MegaMorphTarget mt = channel.GetTarget(tm.name);
if ( mt == null ) // add a new target
{
mt = new MegaMorphTarget();
mt.name = tm.name;
channel.mTargetCache.Add(mt);
}
mt.points = tm.verts.ToArray();
//for ( int v = 0; v < mt.points.Length; v++ )
//{
//if ( mt.points[v] == mr.oPoints[v] )
//Debug.Log("Vert " + v + " isnt morphed");
//}
}
}
channel.ResetPercent();
channel.Rebuild(mr); // rebuild delta for 1st channel
}
mr.BuildCompress();
}
void LoadTarget(MegaMorphTarget mt)
{
MegaMorph mr = (MegaMorph)target;
string filename = EditorUtility.OpenFilePanel("Morph Target", lastpath, "obj");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
List<MegaTargetMesh> targets = MegaTargetMesh.LoadTargets(filename, mr.importScale, mr.flipyz, mr.negx);
if ( targets != null && targets.Count > 0 )
{
MegaTargetMesh tm = targets[0];
if ( tm.verts.Count != mr.oPoints.Length )
{
EditorUtility.DisplayDialog("Target Vertex count mismatch!", "Target " + tm.name + " has wrong number of verts", "OK");
}
else
{
mt.points = tm.verts.ToArray();
mt.name = tm.name;
}
}
}
void SwapTargets(MegaMorphChan chan, int t1, int t2)
{
if ( t1 >= 0 && t1 < chan.mTargetCache.Count && t2 >= 0 && t2 < chan.mTargetCache.Count && t1 != t2 )
{
MegaMorphTarget mt1 = chan.mTargetCache[t1];
MegaMorphTarget mt2 = chan.mTargetCache[t2];
float per = mt1.percent;
mt1.percent = mt2.percent;
mt2.percent = per;
chan.mTargetCache.RemoveAt(t1);
chan.mTargetCache.Insert(t2, mt1);
EditorUtility.SetDirty(target);
}
}
// Still need to be able to add in unity meshes
void DisplayTarget(MegaMorph morph, MegaMorphChan channel, MegaMorphTarget mt, int num)
{
PushCols();
EditorGUI.indentLevel = 1;
mt.name = EditorGUILayout.TextField("Name", mt.name);
mt.percent = EditorGUILayout.Slider("Percent", mt.percent, 0.0f, 100.0f);
EditorGUILayout.BeginHorizontal();
if ( mt.points == null || mt.points.Length != morph.oPoints.Length)
GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f);
else
GUI.backgroundColor = new Color(0.0f, 1.0f, 0.0f);
if ( GUILayout.Button("Load") )
{
LoadTarget(mt);
}
GUI.backgroundColor = new Color(1.0f, 0.5f, 0.5f);
if ( GUILayout.Button("Delete") )
{
MegaMorphTarget mt0 = channel.mTargetCache[0];
channel.mTargetCache.Remove(mt);
channel.ResetPercent();
if ( channel.mTargetCache.Count > 0 && channel.mTargetCache[0] != mt0 )
channel.Rebuild(morph);
}
GUI.backgroundColor = new Color(1.0f, 1.0f, 0.5f);
if ( GUILayout.Button("Up") )
{
if ( num > 0 )
{
SwapTargets(channel, num, num - 1);
if ( num == 1 )
channel.Rebuild(morph);
}
}
GUI.backgroundColor = new Color(0.5f, 1.0f, 1.0f);
if ( GUILayout.Button("Dn") )
{
if ( num < channel.mTargetCache.Count - 1 )
{
SwapTargets(channel, num, num + 1);
if ( num == 0 )
channel.Rebuild(morph);
}
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel = 0;
PopCols();
}
void PushCols()
{
bcol.Push(GUI.backgroundColor);
ccol.Push(GUI.contentColor);
col.Push(GUI.color);
}
void PopCols()
{
GUI.backgroundColor = bcol.Pop();
GUI.contentColor = ccol.Pop();
GUI.color = col.Pop();
}
void DisplayChannel(MegaMorph morph, MegaMorphChan channel, int num)
{
if ( GUILayout.Button(num + " - " + channel.mName) )
channel.showparams = !channel.showparams;
GUI.backgroundColor = new Color(1, 1, 1);
if ( channel.showparams )
{
channel.mName = EditorGUILayout.TextField("Name", channel.mName);
if ( channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
{
channel.mActiveOverride = EditorGUILayout.Toggle("Active", channel.mActiveOverride);
channel.Percent = EditorGUILayout.Slider("Percent", channel.Percent, 0.0f, 100.0f);
channel.mCurvature = EditorGUILayout.FloatField("Tension", channel.mCurvature);
}
channel.mUseLimit = EditorGUILayout.Toggle("Use Limit", channel.mUseLimit);
if ( channel.mUseLimit )
{
channel.mSpinmin = EditorGUILayout.FloatField("Min", channel.mSpinmin);
channel.mSpinmax = EditorGUILayout.FloatField("Max", channel.mSpinmax);
}
EditorGUILayout.BeginHorizontal();
PushCols();
GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f);
if ( GUILayout.Button("Load Targets") )
LoadTargets(channel);
GUI.backgroundColor = new Color(0.5f, 1.0f, 0.5f);
if ( GUILayout.Button("Add Target") )
{
if ( channel.mTargetCache == null )
channel.mTargetCache = new List<MegaMorphTarget>();
MegaMorphTarget mt = new MegaMorphTarget();
channel.mTargetCache.Add(mt);
channel.ResetPercent();
}
GUI.backgroundColor = new Color(1.5f, 0.5f, 0.5f);
if ( GUILayout.Button("Delete Channel") )
morph.chanBank.Remove(channel);
EditorGUILayout.EndHorizontal();
PopCols();
if ( channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
{
channel.showtargets = EditorGUILayout.Foldout(channel.showtargets, "Targets");
if ( channel.showtargets )
{
if ( channel.mTargetCache != null )
{
for ( int i = 0; i < channel.mTargetCache.Count; i++ )
DisplayTarget(morph, channel, channel.mTargetCache[i], i);
}
}
}
}
else
{
if ( channel.mActiveOverride && channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
channel.Percent = EditorGUILayout.Slider("Percent", channel.Percent, 0.0f, 100.0f);
}
}
bool showmodparams = false;
bool showimport = false;
bool showchannels = true;
void ImportParams(MegaMorph morph)
{
showimport = EditorGUILayout.Foldout(showimport, "Import Params");
if ( showimport )
{
morph.importScale = EditorGUILayout.FloatField("Import Scale", morph.importScale);
morph.flipyz = EditorGUILayout.Toggle("FlipYZ", morph.flipyz);
morph.negx = EditorGUILayout.Toggle("Negate X", morph.negx);
morph.tolerance = EditorGUILayout.FloatField("Tolerance", morph.tolerance);
}
}
public override void OnInspectorGUI()
{
MegaMorph morph = (MegaMorph)target;
PushCols();
if ( GUILayout.Button("Import Morph File") )
{
LoadMorph();
EditorUtility.SetDirty(target);
}
// Basic mod stuff
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
{
morph.ModEnabled = EditorGUILayout.Toggle("Mod Enabled", morph.ModEnabled);
morph.DisplayGizmo = EditorGUILayout.Toggle("Display Gizmo", morph.DisplayGizmo);
morph.Order = EditorGUILayout.IntField("Order", morph.Order);
morph.gizCol1 = EditorGUILayout.ColorField("Giz Col 1", morph.gizCol1);
morph.gizCol2 = EditorGUILayout.ColorField("Giz Col 2", morph.gizCol2);
}
morph.animate = EditorGUILayout.Toggle("Animate", morph.animate);
if ( morph.animate )
{
morph.animtime = EditorGUILayout.FloatField("AnimTime", morph.animtime);
morph.looptime = EditorGUILayout.FloatField("LoopTime", morph.looptime);
morph.speed = EditorGUILayout.FloatField("Speed", morph.speed);
morph.repeatMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("RepeatMode", morph.repeatMode);
}
//ImportParams(morph);
EditorGUILayout.BeginHorizontal();
PushCols();
if ( morph.mapping == null || morph.mapping.Length == 0 )
GUI.backgroundColor = Color.red;
else
GUI.backgroundColor = Color.green;
if ( GUILayout.Button("Load Mapping") )
LoadBase(morph);
PopCols();
if ( GUILayout.Button("Add Channel") )
{
if ( morph.chanBank == null )
morph.chanBank = new List<MegaMorphChan>();
MegaMorphChan nc = new MegaMorphChan();
nc.mName = "Empty";
morph.chanBank.Add(nc);
//ChannelMapping(morph, nc); // Create 1 to 1 mapping
}
EditorGUILayout.EndHorizontal();
string bname = "Hide Channels";
if ( !showchannels )
bname = "Show Channels";
if ( GUILayout.Button(bname) )
showchannels = !showchannels;
if ( showchannels && morph.chanBank != null )
{
for ( int i = 0; i < morph.chanBank.Count; i++ )
{
PushCols();
if ( (i & 1) == 0 )
GUI.backgroundColor = ChanCol1;
else
GUI.backgroundColor = ChanCol2;
DisplayChannel(morph, morph.chanBank[i], i);
PopCols();
}
}
extraparams = EditorGUILayout.Foldout(extraparams, "Extra Params");
if ( extraparams )
{
ChanCol1 = EditorGUILayout.ColorField("Channel Col 1", ChanCol1);
ChanCol2 = EditorGUILayout.ColorField("Channel Col 2", ChanCol2);
//int mem = CalcMemoryUsage(morph) / 1024;
if ( morph.compressedmem == 0 )
{
morph.memuse = CalcMemoryUsage(morph);
morph.Compress();
}
EditorGUILayout.LabelField("Memory: ", (morph.memuse / 1024) + "KB");
EditorGUILayout.LabelField("Channel Compressed: ", (morph.compressedmem / 1024) + "KB");
}
PopCols();
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
int MorphedVerts(MegaMorph mr, MegaMorphChan channel)
{
int count = 0;
for ( int v = 0; v < mr.oPoints.Length; v++ )
{
Vector3 p = mr.oPoints[v];
bool morphed = false;
for ( int i = 0; i < channel.mTargetCache.Count; i++ )
{
MegaMorphTarget mt = channel.mTargetCache[i];
if ( !p.Equals(mt.points[v]) )
{
morphed = true;
break;
}
}
if ( morphed )
count++;
}
return count;
}
void ChannelMapping(MegaMorph mr, MegaMorphChan mc)
{
mc.mapping = new int[mr.oPoints.Length];
for ( int i = 0; i < mr.oPoints.Length; i++ )
{
mc.mapping[i] = i;
}
}
void CompressChannel(MegaMorph mr, MegaMorphChan mc)
{
// for now change system to work off mapping, just have 1 to 1 mapping to test its working
mc.mapping = new int[mr.oPoints.Length];
for ( int i = 0; i < mr.oPoints.Length; i++ )
{
mc.mapping[i] = i;
}
#if false
BitArray modded = new BitArray(mr.oPoints.Length);
modded.SetAll(false);
for ( int t = 0; t < mc.mTargetCache.Count; t++ )
{
MegaMorphTarget mt = mc.mTargetCache[t];
for ( int i = 0; i < mr.oPoints.Length; i++ )
{
if ( mt.points[i] != mr.oPoints[i] ) // Have a threshold for this
{
modded[i] = true;
break;
}
}
}
List<int> points = new List<int>();
for ( int i = 0; i < modded.Count; i++ )
{
if ( modded[i] )
points.Add(i);
}
// points now holds indexes of morphed verts for the channel, so now need to collapse points
Vector3[] pts = new Vector3[points.Count];
for ( int t = 0; t < mc.mTargetCache.Count; t++ )
{
MegaMorphTarget mt = mc.mTargetCache[t];
for ( int i = 0; i < points.Count; i++ )
{
pts[i] = mt.points[points[i]];
}
pts.CopyTo(mt.points, 0);
}
// If one target deal with deltas
#endif
}
int CalcCompressedMemory(MegaMorph mr)
{
int mem = 0;
for ( int i = 0; i < mr.chanBank.Count; i++ )
{
MegaMorphChan mc = mr.chanBank[i];
//mem += MorphedVerts(mr, mc) * 12 * mc.mTargetCache.Count;
int mv = MorphedVerts(mr, mc);
int m = mv * 12 * mc.mTargetCache.Count;
mem += m;
EditorGUILayout.LabelField(mc.mName, "Verts: " + mv + " mem: " + m);
}
EditorGUILayout.LabelField("Total: ", (mem / 1024) + "KB");
return mem;
}
int CalcMemoryUsage(MegaMorph mr)
{
int mem = 0;
for ( int i = 0; i < mr.chanBank.Count; i++ )
{
MegaMorphChan mc = mr.chanBank[i];
mem += mc.mTargetCache.Count * 12 * mr.oPoints.Length;
}
return mem;
}
//public delegate bool ParseBinCallbackType(BinaryReader br, string id);
//public delegate void ParseClassCallbackType(string classname, BinaryReader br);
public void ParseFile(String assetpath, ParseClassCallbackType cb)
{
FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
bool processing = true;
while ( processing )
{
string classname = MegaParse.ReadString(br);
if ( classname == "Done" )
break;
int chunkoff = br.ReadInt32();
long fpos = fs.Position;
cb(classname, br);
fs.Position = fpos + chunkoff;
}
br.Close();
}
#if false
static public void Parse(BinaryReader br, ParseBinCallbackType cb)
{
bool readchunk = true;
while ( readchunk )
{
string id = MegaUtils.ReadString(br);
if ( id == "eoc" )
break;
int skip = br.ReadInt32();
long fpos = br.BaseStream.Position;
if ( !cb(br, id) )
{
Debug.Log("Error Loading chunk id " + id);
readchunk = false; // done
break;
}
br.BaseStream.Position = fpos + skip;
}
}
#endif
void MorphCallback(string classname, BinaryReader br)
{
switch ( classname )
{
case "Morph": LoadMorph(br); break;
}
}
void LoadMorph()
{
MegaMorph mr = (MegaMorph)target;
//Modifiers mod = mr.GetComponent<Modifiers>(); // Do this at start and store
string filename = EditorUtility.OpenFilePanel("Morph File", lastpath, "mor");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
mr.chanBank.Clear();
ParseFile(filename, MorphCallback);
mr.animate = false;
float looptime = 0.0f;
// Set Looptime and animate if there is an anim
for ( int i = 0; i < mr.chanBank.Count; i++ )
{
MegaMorphChan mc = mr.chanBank[i];
if ( mc.control != null )
{
mr.animate = true;
float t = mc.control.Times[mc.control.Times.Length - 1];
if ( t > looptime )
looptime = t;
}
}
if ( mr.animate )
{
mr.looptime = looptime;
}
mr.compressedmem = 0;
mr.BuildCompress();
}
public void LoadMorph(BinaryReader br)
{
//Parse(br, ParseMorph);
MegaParse.Parse(br, ParseMorph);
}
bool AnimCallback(BinaryReader br, string id)
{
MegaMorph mr = (MegaMorph)target;
switch ( id )
{
case "Chan":
int cn = br.ReadInt32();
currentChan = mr.chanBank[cn]; break;
case "Anim": currentChan.control = LoadAnim(br); break;
default: return false;
}
return true;
}
void LoadAnimation(MegaMorph mr, BinaryReader br)
{
//Parse(br, AnimCallback);
MegaParse.Parse(br, AnimCallback);
}
// Fbx could have been exported any which way so still need to do try all mappings to find correct
public bool ParseMorph(BinaryReader br, string id)
{
MegaMorph mr = (MegaMorph)target;
//Debug.Log("ParseMorph " + id);
switch ( id )
{
case "Max": mr.Max = br.ReadSingle(); break;
case "Min": mr.Min = br.ReadSingle(); break;
case "UseLim": mr.UseLimit = (br.ReadInt32() == 1); break;
case "StartPoints": // Mapping
MegaTargetMesh tm = new MegaTargetMesh();
tm.verts = MegaParse.ReadP3l(br); // make a vector
if ( !TryMapping1(tm, mr) )
{
EditorUtility.DisplayDialog("Mapping Failed!", "Mapping failed!", "OK");
EditorUtility.ClearProgressBar();
return false;
}
//Debug.Log("StartPoints " + tm.verts.Count);
break;
case "Channel":
mr.chanBank.Add(LoadChan(br));
break;
case "Animation":
LoadAnimation(mr, br);
break;
default: return false;
}
return true;
}
MegaMorphChan currentChan;
public MegaMorphChan LoadChan(BinaryReader br)
{
MegaMorphChan chan = new MegaMorphChan();
chan.control = null;
chan.showparams = false;
chan.mTargetCache = new List<MegaMorphTarget>();
currentChan = chan;
//Parse(br, ParseChan);
MegaParse.Parse(br, ParseChan);
MegaMorph mr = (MegaMorph)target;
chan.Rebuild(mr);
return chan;
}
public static MegaBezFloatKeyControl LoadAnim(BinaryReader br)
{
//MegaBezFloatKeyControl con = new MegaBezFloatKeyControl();
//Parse(br, con.Parse);
//MegaParse.Parse(br, con.Parse);
//return con;
return MegaParseBezFloatControl.LoadBezFloatKeyControl(br);
}
public bool ParseChan(BinaryReader br, string id)
{
//Debug.Log("ParseChan " + id);
switch ( id )
{
case "Target": currentChan.mTargetCache.Add(LoadTarget(br)); break;
case "Name": currentChan.mName = MegaParse.ReadString(br); break;
case "Percent": currentChan.Percent = br.ReadSingle(); break;
case "SpinMax": currentChan.mSpinmax = br.ReadSingle(); break;
case "SpinMin": currentChan.mSpinmin = br.ReadSingle(); break;
case "UseLim": currentChan.mUseLimit = (br.ReadInt32() == 1); break;
case "Override": currentChan.mActiveOverride = (br.ReadInt32() == 1); break;
case "Curve": currentChan.mCurvature = br.ReadSingle(); break;
//case "Anim": currentChan.control = LoadAnim(br); break;
}
return true;
}
MegaMorphTarget currentTarget;
void ConvertPoints(Vector3[] verts)
{
MegaMorph mr = (MegaMorph)target;
for ( int i = 0; i < verts.Length; i++ )
{
Vector3 p = verts[i] * mr.importScale;
if ( mr.negx )
{
p.x = -p.x;
}
if ( mr.flipyz )
{
float y = p.y;
p.y = p.z;
p.z = y;
}
verts[i] = p;
}
}
public bool ParseTarget(BinaryReader br, string id)
{
//Debug.Log("ParseTarget " + id);
switch ( id )
{
case "Name": currentTarget.name = MegaParse.ReadString(br); break;
case "Percent": currentTarget.percent = br.ReadSingle(); break;
case "TPoints": currentTarget.points = MegaParse.ReadP3v(br); ConvertPoints(currentTarget.points); break;
case "MoPoints":
Debug.Log("Got morpho points");
break;
}
return true;
}
public MegaMorphTarget LoadTarget(BinaryReader br)
{
MegaMorphTarget target = new MegaMorphTarget();
currentTarget = target;
//Parse(br, ParseTarget);
MegaParse.Parse(br, ParseTarget);
return target;
}
bool TryMapping1(MegaTargetMesh tm, MegaMorph morph)
{
MegaModifiers mod = morph.GetComponent<MegaModifiers>();
if ( mod == null )
{
EditorUtility.DisplayDialog("Missing ModifyObject!", "No ModifyObject script found on the object", "OK");
return false;
}
int[] mapping = new int[mod.verts.Length];
//for ( int i = 0; i < 8; i++ )
//{
//Debug.Log("target vert " + tm.verts[i].ToString("0.000"));
//}
//for ( int i = 0; i < 8; i++ )
//{
//Debug.Log("base vert " + mod.verts[i].ToString("0.000"));
//}
// Get extents for mod verts and for imported meshes, if not the same then scale
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = Extents(mod.verts, out min1, out max1);
Vector3 ex2 = Extents(tm.verts, out min2, out max2);
// need min max on all axis so we can produce an offset to add
float d1 = ex1.x;
float d2 = ex2.x;
float scl = d1 / d2; //d2 / d1;
bool flipyz = false;
bool negx = false;
//Debug.Log("scale " + scl.ToString("0.0000"));
//Vector3 offset = (min2 * scl) - min1;
//Debug.Log("offset " + offset.ToString("0.0000"));
//for ( int i = 0; i < 8; i++ )
//{
//Vector3 p = tm.verts[i];
//p = (p * scl) + offset;
//Debug.Log("adj vert " + p.ToString("0.000"));
//}
// So try to match first vert using autoscale and no flip
bool mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped ) //DoMapping(mod, morph, tm, mapping, scl, flipyz, negx) )
{
flipyz = false;
negx = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, mapping, scl, flipyz, negx);
}
}
}
if ( mapped )
{
morph.importScale = scl;
morph.flipyz = flipyz;
morph.negx = negx;
morph.mapping = mapping;
// if mapping was ok set opoints
morph.oPoints = tm.verts.ToArray();
for ( int i = 0; i < morph.oPoints.Length; i++ )
{
Vector3 p = morph.oPoints[i];
if ( negx )
p.x = -p.x;
if ( flipyz )
{
float z = p.z;
p.z = p.y;
p.y = z;
}
morph.oPoints[i] = p * morph.importScale;
}
return true;
}
return false;
}
}
// 1497
\ No newline at end of file
fileFormatVersion: 2
guid: 9723af08f034cdb4f985812746ccb7c2
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System;
[CustomEditor(typeof(MegaMorphOMatic))]
public class MegaMorphOMaticEditor : Editor
{
static string lastpath = " ";
static public Color ChanCol1 = new Color(0.44f, 0.67f, 1.0f);
static public Color ChanCol2 = new Color(1.0f, 0.67f, 0.44f);
Stack<Color> bcol = new Stack<Color>();
Stack<Color> ccol = new Stack<Color>();
Stack<Color> col = new Stack<Color>();
bool extraparams = false;
bool showmodparams = false;
bool showchannels = true;
MegaMorphChan currentChan;
MegaMorphTarget currentTarget;
// Remove morph and pass tolerance then can morph to Utils
// TODO: report error if target vert counts dont match base mapping
bool DoMapping(MegaModifiers mod, MegaMorphOMatic morph, MegaTargetMesh tm, float scale, bool flipyz, bool negx)
{
for ( int i = 0; i < mod.verts.Length; i++ )
{
float a = (float)i / (float)mod.verts.Length;
EditorUtility.DisplayProgressBar("Mapping", "Mapping vertex " + i, a);
int map = MegaUtils.FindVert(mod.verts[i], tm.verts, morph.tolerance, scale, flipyz, negx, i);
if ( map == -1 )
{
// Failed
EditorUtility.ClearProgressBar();
return false;
}
}
EditorUtility.ClearProgressBar();
return true;
}
void DisplayTarget(MegaMorphOMatic morph, MegaMorphChan channel, MegaMorphTarget mt, int num)
{
PushCols();
EditorGUI.indentLevel = 1;
mt.name = EditorGUILayout.TextField("Name", mt.name);
//mt.percent = EditorGUILayout.Slider("Percent", mt.percent, 0.0f, 100.0f);
mt.percent = EditorGUILayout.Slider("Percent", mt.percent, channel.mSpinmin, channel.mSpinmax); //.0f, 100.0f);
EditorGUILayout.BeginHorizontal();
if ( mt.points == null || mt.points.Length != morph.oPoints.Length )
GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f);
else
GUI.backgroundColor = new Color(0.0f, 1.0f, 0.0f);
GUI.backgroundColor = new Color(1.0f, 0.5f, 0.5f);
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel = 0;
PopCols();
}
// These should be in EditorUtils
void PushCols()
{
bcol.Push(GUI.backgroundColor);
ccol.Push(GUI.contentColor);
col.Push(GUI.color);
}
void PopCols()
{
GUI.backgroundColor = bcol.Pop();
GUI.contentColor = ccol.Pop();
GUI.color = col.Pop();
}
// This is common to other morpher
void DisplayChannel(MegaMorphOMatic morph, MegaMorphChan channel)
{
if ( GUILayout.Button(channel.mName) )
channel.showparams = !channel.showparams;
GUI.backgroundColor = new Color(1, 1, 1);
if ( channel.showparams )
{
channel.mName = EditorGUILayout.TextField("Name", channel.mName);
if ( channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
{
channel.mActiveOverride = EditorGUILayout.Toggle("Active", channel.mActiveOverride);
channel.Percent = EditorGUILayout.Slider("Percent", channel.Percent, channel.mSpinmin, channel.mSpinmax); //.0f, 100.0f);
channel.mCurvature = EditorGUILayout.FloatField("Tension", channel.mCurvature);
}
channel.mUseLimit = EditorGUILayout.Toggle("Use Limit", channel.mUseLimit);
if ( channel.mUseLimit )
{
channel.mSpinmin = EditorGUILayout.FloatField("Min", channel.mSpinmin);
channel.mSpinmax = EditorGUILayout.FloatField("Max", channel.mSpinmax);
}
EditorGUILayout.BeginHorizontal();
PushCols();
GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f);
GUI.backgroundColor = new Color(1.5f, 0.5f, 0.5f);
if ( GUILayout.Button("Delete Channel") )
morph.chanBank.Remove(channel);
EditorGUILayout.EndHorizontal();
PopCols();
if ( channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
{
channel.showtargets = EditorGUILayout.Foldout(channel.showtargets, "Targets");
if ( channel.showtargets )
{
if ( channel.mTargetCache != null )
{
for ( int i = 0; i < channel.mTargetCache.Count; i++ )
DisplayTarget(morph, channel, channel.mTargetCache[i], i);
}
}
}
}
else
{
if ( channel.mActiveOverride && channel.mTargetCache != null && channel.mTargetCache.Count > 0 )
{
channel.Percent = EditorGUILayout.Slider("Percent", channel.Percent, channel.mSpinmin, channel.mSpinmax); //.0f, 100.0f);
}
}
}
public override void OnInspectorGUI()
{
MegaMorphOMatic morph = (MegaMorphOMatic)target;
PushCols();
if ( GUILayout.Button("Import MorphOMatic File") )
{
LoadMorph();
EditorUtility.SetDirty(target);
}
// Basic mod stuff
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
{
morph.ModEnabled = EditorGUILayout.Toggle("Mod Enabled", morph.ModEnabled);
morph.DisplayGizmo = EditorGUILayout.Toggle("Display Gizmo", morph.DisplayGizmo);
morph.Order = EditorGUILayout.IntField("Order", morph.Order);
morph.gizCol1 = EditorGUILayout.ColorField("Giz Col 1", morph.gizCol1);
morph.gizCol2 = EditorGUILayout.ColorField("Giz Col 2", morph.gizCol2);
}
morph.animate = EditorGUILayout.Toggle("Animate", morph.animate);
if ( morph.animate )
{
morph.animtime = EditorGUILayout.FloatField("AnimTime", morph.animtime);
morph.looptime = EditorGUILayout.FloatField("LoopTime", morph.looptime);
morph.speed = EditorGUILayout.FloatField("Speed", morph.speed);
morph.repeatMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("RepeatMode", morph.repeatMode);
}
EditorGUILayout.BeginHorizontal();
PushCols();
if ( morph.mapping == null || morph.mapping.Length == 0 )
GUI.backgroundColor = Color.red;
else
GUI.backgroundColor = Color.green;
PopCols();
if ( GUILayout.Button("Add Channel") )
{
if ( morph.chanBank == null )
morph.chanBank = new List<MegaMorphChan>();
MegaMorphChan nc = new MegaMorphChan();
nc.mName = "Empty";
morph.chanBank.Add(nc);
}
EditorGUILayout.EndHorizontal();
string bname = "Hide Channels";
if ( !showchannels )
bname = "Show Channels";
if ( GUILayout.Button(bname) )
showchannels = !showchannels;
if ( showchannels && morph.chanBank != null )
{
for ( int i = 0; i < morph.chanBank.Count; i++ )
{
PushCols();
if ( (i & 1) == 0 )
GUI.backgroundColor = ChanCol1;
else
GUI.backgroundColor = ChanCol2;
DisplayChannel(morph, morph.chanBank[i]);
PopCols();
}
}
extraparams = EditorGUILayout.Foldout(extraparams, "Extra Params");
if ( extraparams )
{
ChanCol1 = EditorGUILayout.ColorField("Channel Col 1", ChanCol1);
ChanCol2 = EditorGUILayout.ColorField("Channel Col 2", ChanCol2);
}
PopCols();
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
public void ParseFile(String assetpath, ParseClassCallbackType cb)
{
FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
bool processing = true;
while ( processing )
{
string classname = MegaParse.ReadString(br);
if ( classname == "Done" )
break;
int chunkoff = br.ReadInt32();
long fpos = fs.Position;
cb(classname, br);
fs.Position = fpos + chunkoff;
}
br.Close();
}
void MorphCallback(string classname, BinaryReader br)
{
switch ( classname )
{
case "Morph": LoadMorph(br); break;
}
}
void LoadMorph()
{
MegaMorphOMatic mr = (MegaMorphOMatic)target;
string filename = EditorUtility.OpenFilePanel("Morph-O-Matic Morph File", lastpath, "mmf");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
mr.chanBank.Clear();
ParseFile(filename, MorphCallback);
mr.animate = false;
float looptime = 0.0f;
// Set Looptime and animate if there is an anim
for ( int i = 0; i < mr.chanBank.Count; i++ )
{
MegaMorphChan mc = mr.chanBank[i];
if ( mc.control != null )
{
mr.animate = true;
float t = mc.control.Times[mc.control.Times.Length - 1];
if ( t > looptime )
looptime = t;
}
}
if ( mr.animate )
mr.looptime = looptime;
BuildData();
}
public void LoadMorph(BinaryReader br)
{
MegaParse.Parse(br, ParseMorph);
}
bool AnimCallback(BinaryReader br, string id)
{
MegaMorphOMatic mr = (MegaMorphOMatic)target;
switch ( id )
{
case "Chan":
int cn = br.ReadInt32();
currentChan = mr.chanBank[cn]; break;
case "Anim": currentChan.control = LoadAnim(br); break;
default: return false;
}
return true;
}
void LoadAnimation(MegaMorphOMatic mr, BinaryReader br)
{
MegaParse.Parse(br, AnimCallback);
}
// Fbx could have been exported any which way so still need to do try all mappings to find correct
public bool ParseMorph(BinaryReader br, string id)
{
MegaMorphOMatic mr = (MegaMorphOMatic)target;
switch ( id )
{
case "Max": mr.Max = br.ReadSingle(); break;
case "Min": mr.Min = br.ReadSingle(); break;
case "UseLim": mr.UseLimit = (br.ReadInt32() == 1); break;
// This will only be changed points, but we need scale
case "StartPoints": // Mapping
MegaTargetMesh tm = new MegaTargetMesh();
tm.verts = MegaParse.ReadP3l(br); // make a vector
if ( !TryMapping1(tm, mr) )
{
EditorUtility.DisplayDialog("Mapping Failed!", "Mapping failed!", "OK");
EditorUtility.ClearProgressBar();
return false;
}
break;
case "Channel": mr.chanBank.Add(LoadChan(br)); break;
case "Animation": LoadAnimation(mr, br); break;
default: return false;
}
return true;
}
public MegaMorphChan LoadChan(BinaryReader br)
{
MegaMorphChan chan = new MegaMorphChan();
chan.control = null;
chan.showparams = false;
chan.mTargetCache = new List<MegaMorphTarget>();
currentChan = chan;
MegaParse.Parse(br, ParseChan);
return chan;
}
public static MegaBezFloatKeyControl LoadAnim(BinaryReader br)
{
//MegaBezFloatKeyControl con = new MegaBezFloatKeyControl();
//MegaParse.Parse(br, con.Parse);
//return con;
return MegaParseBezFloatControl.LoadBezFloatKeyControl(br);
}
public bool ParseChan(BinaryReader br, string id)
{
switch ( id )
{
case "Target": currentChan.mTargetCache.Add(LoadTarget(br)); break;
case "Name": currentChan.mName = MegaParse.ReadString(br); break;
case "Percent": currentChan.Percent = br.ReadSingle(); break;
case "SpinMax": currentChan.mSpinmax = br.ReadSingle(); break;
case "SpinMin": currentChan.mSpinmin = br.ReadSingle(); break;
case "UseLim": currentChan.mUseLimit = (br.ReadInt32() == 1); break;
case "Override": currentChan.mActiveOverride = (br.ReadInt32() == 1); break;
case "Curve": currentChan.mCurvature = br.ReadSingle(); break;
}
return true;
}
Vector3 ConvertPoint(Vector3 v)
{
MegaMorphOMatic mr = (MegaMorphOMatic)target;
Vector3 p = v * mr.importScale;
if ( mr.negx )
p.x = -p.x;
if ( mr.flipyz )
{
float y = p.y;
p.y = p.z;
p.z = y;
}
return p;
}
public bool ParseTarget(BinaryReader br, string id)
{
switch ( id )
{
case "Name": currentTarget.name = MegaParse.ReadString(br); break;
case "Percent": currentTarget.percent = br.ReadSingle(); break;
case "MoPoints":
int count = br.ReadInt32();
if ( count > 0 )
{
currentTarget.loadpoints = new MOPoint[count];
for ( int i = 0; i < count; i++ )
{
MOPoint p = new MOPoint();
p.id = br.ReadInt32(); // we need to find the ids for this point (could be more than one)
p.p = ConvertPoint(MegaParse.ReadP3(br));
p.w = br.ReadSingle();
currentTarget.loadpoints[i] = p;
}
}
break;
}
return true;
}
public MegaMorphTarget LoadTarget(BinaryReader br)
{
MegaMorphTarget target = new MegaMorphTarget();
currentTarget = target;
MegaParse.Parse(br, ParseTarget);
return target;
}
// We should know the mapping
// remove morph pass tolerance instead
bool TryMapping1(MegaTargetMesh tm, MegaMorphOMatic morph)
{
MegaModifiers mod = morph.GetComponent<MegaModifiers>();
if ( mod == null )
{
EditorUtility.DisplayDialog("Missing ModifyObject!", "No ModifyObject script found on the object", "OK");
return false;
}
// Get extents for mod verts and for imported meshes, if not the same then scale
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = MegaUtils.Extents(mod.verts, out min1, out max1);
Vector3 ex2 = MegaUtils.Extents(tm.verts, out min2, out max2);
// need min max on all axis so we can produce an offset to add
float d1 = ex1.x;
float d2 = ex2.x;
float scl = d1 / d2; //d2 / d1;
bool flipyz = false;
bool negx = false;
// So try to match first vert using autoscale and no flip
bool mapped = DoMapping(mod, morph, tm, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, scl, flipyz, negx);
if ( !mapped ) //DoMapping(mod, morph, tm, mapping, scl, flipyz, negx) )
{
flipyz = false;
negx = true;
mapped = DoMapping(mod, morph, tm, scl, flipyz, negx);
if ( !mapped )
{
flipyz = true;
mapped = DoMapping(mod, morph, tm, scl, flipyz, negx);
}
}
}
if ( mapped )
{
morph.importScale = scl;
morph.flipyz = flipyz;
morph.negx = negx;
// if mapping was ok set opoints
morph.oPoints = tm.verts.ToArray();
for ( int i = 0; i < morph.oPoints.Length; i++ )
{
Vector3 p = morph.oPoints[i];
if ( negx )
p.x = -p.x;
if ( flipyz )
{
float z = p.z;
p.z = p.y;
p.y = z;
}
morph.oPoints[i] = p * morph.importScale;
}
morph.mapping = new MegaMomVertMap[morph.oPoints.Length];
for ( int i = 0; i < morph.oPoints.Length; i++ )
{
//int[] indices = morph.FindVerts(morph.oPoints[i], mod);
int[] indices = FindVerts(morph.oPoints[i], mod);
morph.mapping[i] = new MegaMomVertMap();
morph.mapping[i].indices = indices; //morph.FindVerts(morph.oPoints[i], mod);
}
return true;
}
return false;
}
bool GetDelta(MegaMorphTarget targ, int v, out Vector3 delta, out float w)
{
MegaMorphOMatic mod = (MegaMorphOMatic)target;
if ( targ.loadpoints != null )
{
for ( int i = 0; i < targ.loadpoints.Length; i++ )
{
int id = targ.loadpoints[i].id;
if ( id == v )
{
delta = targ.loadpoints[i].p - mod.oPoints[id];
w = targ.loadpoints[i].w;
return true;
}
}
}
delta = Vector3.zero;
w = 0.0f;
return false;
}
public int[] FindVerts(Vector3 p, MegaModifiers mods)
{
List<int> indices = new List<int>();
for ( int i = 0; i < mods.verts.Length; i++ )
{
float dist = Vector3.Distance(p, mods.verts[i]);
if ( dist < 0.0001f ) //mods.verts[i].Equals(p) )
indices.Add(i);
}
return indices.ToArray();
}
// Build the morphing data
// each target holds only the points that differe from the base so need to build table showing for each
// target the points that differ
public void BuildData()
{
MegaMorphOMatic mod = (MegaMorphOMatic)target;
List<MOMVert> verts = new List<MOMVert>();
for ( int c = 0; c < mod.chanBank.Count; c++ )
{
MegaMorphChan chan = mod.chanBank[c];
int maxverts = 0;
for ( int t = 0; t < chan.mTargetCache.Count - 1; t++ )
{
MegaMorphTarget targ = chan.mTargetCache[t];
MegaMorphTarget targ1 = chan.mTargetCache[t + 1];
// if t is 0 then just use the points
Vector3 delta = Vector3.zero;
Vector3 delta1 = Vector3.zero;
float w = 1.0f;
verts.Clear();
for ( int v = 0; v < mod.oPoints.Length; v++ )
{
bool t1 = GetDelta(targ, v, out delta, out w);
bool t2 = GetDelta(targ1, v, out delta1, out w);
if ( t1 || t2 ) //GetDelta(targ, v, out delta, out w) || GetDelta(targ1, v, out delta1, out w) )
{
MOMVert vert = new MOMVert();
vert.id = v;
vert.w = w;
vert.start = delta;
vert.delta = delta1 - delta;
verts.Add(vert);
}
}
if ( verts.Count > maxverts )
maxverts = verts.Count;
if ( verts.Count > 0 )
targ.mompoints = verts.ToArray();
}
for ( int t = 0; t < chan.mTargetCache.Count; t++ )
chan.mTargetCache[t].loadpoints = null;
chan.diff = new Vector3[maxverts];
}
}
}
fileFormatVersion: 2
guid: 86d0d361473dae24da397fb39a6af0fe
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaNoise))]
public class MegaNoiseEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Noise Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/noise_help.png"); }
public override bool Inspector()
{
MegaNoise mod = (MegaNoise)target;
EditorGUIUtility.LookLikeControls();
mod.Scale = EditorGUILayout.FloatField("Scale", mod.Scale);
mod.Freq = EditorGUILayout.FloatField("Freq", mod.Freq);
mod.Phase = EditorGUILayout.FloatField("Phase", mod.Phase);
mod.Fractal = EditorGUILayout.Toggle("Fractal", mod.Fractal);
if ( mod.Fractal )
{
mod.Iterations = EditorGUILayout.FloatField("Iterations", mod.Iterations);
mod.Rough = EditorGUILayout.FloatField("Rough", mod.Rough);
}
mod.Strength = EditorGUILayout.Vector3Field("Strength", mod.Strength);
mod.Animate = EditorGUILayout.Toggle("Animate", mod.Animate);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 383d612fed95d084dbab985e8eb39c50
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaPageFlip))]
public class MegaPageFlipEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Page Flip Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
bool advanced = false;
public override bool Inspector()
{
MegaPageFlip mod = (MegaPageFlip)target;
EditorGUIUtility.LookLikeControls();
mod.turn = EditorGUILayout.FloatField("Turn", mod.turn);
mod.ap1 = EditorGUILayout.FloatField("Ap1", mod.ap1);
mod.ap2 = EditorGUILayout.FloatField("Ap2", mod.ap2);
mod.ap3 = EditorGUILayout.FloatField("Ap3", mod.ap3);
mod.flipx = EditorGUILayout.Toggle("Flip X", mod.flipx);
advanced = EditorGUILayout.Foldout(advanced, "Advanced");
if ( advanced )
{
mod.animT = EditorGUILayout.Toggle("Anim T", mod.animT);
mod.autoMode = EditorGUILayout.Toggle("Auto Mode", mod.autoMode);
mod.lockRho = EditorGUILayout.Toggle("Lock Rho", mod.lockRho);
mod.lockTheta = EditorGUILayout.Toggle("Lock Theta", mod.lockTheta);
mod.timeStep = EditorGUILayout.FloatField("TimeStep", mod.timeStep);
mod.rho = EditorGUILayout.FloatField("Rho", mod.rho);
mod.theta = EditorGUILayout.FloatField("Theta", mod.theta);
mod.deltaT = EditorGUILayout.FloatField("DeltaT", mod.deltaT);
mod.kT = EditorGUILayout.FloatField("kT", mod.kT);
}
return false;
}
}
fileFormatVersion: 2
guid: 3c93b1c900a49b04c8a13aed577bd2a9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaPaint))]
public class MegaPaintEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Vertex Paint Modifier by Chris West"; }
public override bool Inspector()
{
MegaPaint mod = (MegaPaint)target;
EditorGUIUtility.LookLikeControls();
mod.radius = EditorGUILayout.FloatField("Radius", mod.radius);
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.usedecay = EditorGUILayout.Toggle("Use Decay", mod.usedecay);
if ( mod.usedecay )
mod.decay = EditorGUILayout.FloatField("Decay", mod.decay);
mod.fallOff = (MegaFallOff)EditorGUILayout.EnumPopup("Falloff Mode", mod.fallOff);
mod.gaussc = EditorGUILayout.FloatField("Falloff", mod.gaussc);
mod.useAvgNorm = EditorGUILayout.Toggle("Use Avg Norm", mod.useAvgNorm);
if ( !mod.useAvgNorm )
mod.normal = EditorGUILayout.Vector3Field("Normal", mod.normal);
mod.mode = (MegaPaintMode)EditorGUILayout.EnumPopup("Paint Mode", mod.mode);
return false;
}
}
fileFormatVersion: 2
guid: 7be40678aa61c224681e053ba5eee12c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
public class MegaParseBezFloatControl
{
static MegaBezFloatKeyControl con;
static public MegaBezFloatKeyControl LoadBezFloatKeyControl(BinaryReader br)
{
con = new MegaBezFloatKeyControl();
MegaParse.Parse(br, Parse);
return con;
}
static public bool Parse(BinaryReader br, string id)
{
switch ( id )
{
case "Num":
int num = br.ReadInt32();
con.Keys = new MegaBezFloatKey[num];
con.Times = new float[num];
break;
case "Keys":
for ( int i = 0; i < con.Keys.Length; i++ )
{
con.Keys[i] = new MegaBezFloatKey();
con.Keys[i].val = br.ReadSingle();
con.Keys[i].intan = br.ReadSingle();
con.Keys[i].outtan = br.ReadSingle();
con.Times[i] = br.ReadSingle();
}
con.InitKeys();
break;
case "BKeys": // Blender keys
Vector2 co = Vector2.zero;
Vector2 left = Vector2.zero;
Vector3 right = Vector2.zero;
Vector2 pco = Vector2.zero;
Vector2 pleft = Vector2.zero;
Vector3 pright = Vector2.zero;
for ( int i = 0; i < con.Keys.Length; i++ )
{
con.Keys[i] = new MegaBezFloatKey();
co.x = br.ReadSingle();
co.y = br.ReadSingle();
left.x = br.ReadSingle();
left.y = br.ReadSingle();
right.x = br.ReadSingle();
right.y = br.ReadSingle();
if ( i > 0 )
con.MakeKey(con.Keys[i - 1], pco, pleft, pright, co, left, right);
pco = co;
pleft = left;
pright = right;
con.Times[i] = co.x / 30.0f;
}
break;
}
return true;
}
}
public class MegaParseBezVector3Control
{
static MegaBezVector3KeyControl con;
static public MegaBezVector3KeyControl LoadBezVector3KeyControl(BinaryReader br)
{
con = new MegaBezVector3KeyControl();
MegaParse.Parse(br, Parse);
return con;
}
static public bool Parse(BinaryReader br, string id)
{
switch ( id )
{
case "Num":
int num = br.ReadInt32();
con.Keys = new MegaBezVector3Key[num];
con.Times = new float[num];
break;
case "Keys":
for ( int i = 0; i < con.Keys.Length; i++ )
{
con.Keys[i] = new MegaBezVector3Key();
con.Keys[i].val = MegaParse.ReadP3(br);
con.Keys[i].intan = MegaParse.ReadP3(br);
con.Keys[i].outtan = MegaParse.ReadP3(br);
con.Times[i] = br.ReadSingle();
}
con.InitKeys();
break;
}
return true;
}
}
public class MegaParse
{
static public Vector3 ReadP3(BinaryReader br)
{
Vector3 v = Vector3.zero;
v.x = br.ReadSingle();
v.y = br.ReadSingle();
v.z = br.ReadSingle();
return v;
}
static public string ReadString(BinaryReader br)
{
int len = br.ReadInt32();
string str = new string(br.ReadChars(len - 1));
br.ReadChar();
return str;
}
static public string ReadStr(BinaryReader br)
{
string str = "";
while ( true )
{
char c = br.ReadChar();
if ( c == 0 )
break;
str += c;
}
return str;
}
static public Vector3[] ReadP3v(BinaryReader br)
{
int count = br.ReadInt32();
Vector3[] tab = new Vector3[count];
for ( int i = 0; i < count; i++ )
{
tab[i].x = br.ReadSingle();
tab[i].y = br.ReadSingle();
tab[i].z = br.ReadSingle();
}
return tab;
}
static public List<Vector3> ReadP3l(BinaryReader br)
{
int count = br.ReadInt32();
List<Vector3> tab = new List<Vector3>(count);
Vector3 p = Vector3.zero;
for ( int i = 0; i < count; i++ )
{
p.x = br.ReadSingle();
p.y = br.ReadSingle();
p.z = br.ReadSingle();
tab.Add(p);
}
return tab;
}
static public float ReadMotFloat(BinaryReader br)
{
byte[] floatBytes = br.ReadBytes(4);
// swap the bytes
Array.Reverse(floatBytes);
// get the float from the byte array
return BitConverter.ToSingle(floatBytes, 0);
}
static public double ReadMotDouble(BinaryReader br)
{
byte[] floatBytes = br.ReadBytes(8);
// swap the bytes
Array.Reverse(floatBytes);
// get the float from the byte array
return BitConverter.ToDouble(floatBytes, 0);
}
static public int ReadMotInt(BinaryReader br)
{
byte[] floatBytes = br.ReadBytes(4);
// swap the bytes
Array.Reverse(floatBytes);
// get the float from the byte array
return BitConverter.ToInt32(floatBytes, 0);
}
//public delegate bool ParseBinCallbackType(BinaryReader br, string id);
//public delegate void ParseClassCallbackType(string classname, BinaryReader br);
static public void Parse(BinaryReader br, ParseBinCallbackType cb)
{
bool readchunk = true;
while ( readchunk )
{
string id = MegaParse.ReadString(br);
if ( id == "eoc" )
break;
int skip = br.ReadInt32();
long fpos = br.BaseStream.Position;
if ( !cb(br, id) )
{
Debug.Log("Error Loading chunk id " + id);
readchunk = false; // done
break;
}
br.BaseStream.Position = fpos + skip;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 870b6dc2ff38b9d49b6f69af483624ea
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaPathDeform))]
public class MegaPathDeformEditor : MegaModifierEditor
{
//void OnSceneGUI()
//{
//PathDeform pd = (PathDeform)target;
//Display(pd);
//}
public override bool Inspector()
{
MegaPathDeform mod = (MegaPathDeform)target;
EditorGUIUtility.LookLikeControls();
mod.percent = EditorGUILayout.FloatField("Percent", mod.percent);
mod.stretch = EditorGUILayout.FloatField("Stretch", mod.stretch);
mod.twist = EditorGUILayout.FloatField("Twist", mod.twist);
mod.rotate = EditorGUILayout.FloatField("Rotate", mod.rotate);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.flip = EditorGUILayout.Toggle("Flip", mod.flip);
mod.path = (MegaShape)EditorGUILayout.ObjectField("Path", mod.path, typeof(MegaShape), true);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.speed = EditorGUILayout.FloatField("Speed", mod.speed);
mod.drawpath = EditorGUILayout.Toggle("Draw Path", mod.drawpath);
mod.tangent = EditorGUILayout.FloatField("Tangent", mod.tangent);
mod.UseTwistCurve = EditorGUILayout.Toggle("Use Twist Curve", mod.UseTwistCurve);
mod.twistCurve = EditorGUILayout.CurveField("Twist Curve", mod.twistCurve);
mod.UseStretchCurve = EditorGUILayout.Toggle("Use Stretch Curve", mod.UseStretchCurve);
mod.stretchCurve = EditorGUILayout.CurveField("Stretch Curve", mod.stretchCurve);
return false;
}
void Display(MegaPathDeform pd)
{
if ( pd.path != null )
{
Matrix4x4 mat = pd.transform.localToWorldMatrix * pd.path.transform.localToWorldMatrix * pd.mat;
for ( int s = 0; s < pd.path.splines.Count; s++ )
{
float ldist = pd.path.stepdist;
if ( ldist < 0.1f )
ldist = 0.1f;
float ds = pd.path.splines[s].length / (pd.path.splines[s].length / ldist);
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref lk);
for ( float dist = ds; dist < pd.path.splines[s].length; dist += ds )
{
float alpha = dist / pd.path.splines[s].length;
Vector3 pos = pd.path.splines[s].Interpolate(alpha, pd.path.normalizedInterp, ref k);
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pd.path.splines[s].knots[lk].p));
first = pd.path.splines[s].knots[lk].p;
}
}
lk = k;
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
c++;
first = pos;
}
if ( pd.path.splines[s].closed )
{
Vector3 pos = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref k);
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
}
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 16c4538e4051f0a4cbfc5cec76eac022
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaPivotAdjust))]
public class MegaPivotAdjustEditor : MegaModifierEditor
{
public override bool Inspector()
{
//MegaPivotAdjust mod = (MegaPivotAdjust)target;
return false;
}
}
fileFormatVersion: 2
guid: 5acd69e52a08d2c469a8b0b423030391
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
// Support anim uvs here as well
[CustomEditor(typeof(MegaPointCache))]
public class MegaPointCacheEditor : MegaModifierEditor
{
static string lastpath = " ";
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
MegaModifiers mods;
List<MegaPCVert> Verts = new List<MegaPCVert>();
// Mapping values
float tolerance = 0.0001f;
float scl = 1.0f;
bool flipyz = false;
bool negx = false;
bool negz = false; // 8 cases now
string Read(BinaryReader br, int count)
{
byte[] buf = br.ReadBytes(count);
return System.Text.Encoding.ASCII.GetString(buf, 0, buf.Length);
}
struct MCCFrame
{
public Vector3[] points;
}
// Maya format
void LoadMCC()
{
MegaPointCache am = (MegaPointCache)target;
mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Maya Cache File", lastpath, "mc");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
string id = Read(br, 4);
if ( id != "FOR4" )
{
Debug.Log("wrong file");
return;
}
int offset = MegaParse.ReadMotInt(br);
br.ReadBytes(offset);
List<MCCFrame> frames = new List<MCCFrame>();
while ( true )
{
string btag = Read(br, 4);
if ( btag == "" )
break;
if ( btag != "FOR4" )
{
Debug.Log("File format error");
return;
}
int blocksize = MegaParse.ReadMotInt(br);
int bytesread = 0;
btag = Read(br, 4);
if ( btag != "MYCH" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
btag = Read(br, 4);
if ( btag != "TIME" )
{
Debug.Log("File format error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int time = MegaParse.ReadMotInt(br);
bytesread += 4;
am.maxtime = (float)time / 6000.0f;
while ( bytesread < blocksize )
{
btag = Read(br, 4);
if ( btag != "CHNM" )
{
Debug.Log("chm error");
return;
}
bytesread += 4;
int chnmsize = MegaParse.ReadMotInt(br);
bytesread += 4;
int mask = 3;
int chnmsizetoread = (chnmsize + mask) & (~mask);
//byte[] channelname = br.ReadBytes(chnmsize);
br.ReadBytes(chnmsize);
int paddingsize = chnmsizetoread - chnmsize;
if ( paddingsize > 0 )
br.ReadBytes(paddingsize);
bytesread += chnmsizetoread;
btag = Read(br, 4);
if ( btag != "SIZE" )
{
Debug.Log("Size error");
return;
}
bytesread += 4;
br.ReadBytes(4);
bytesread += 4;
int arraylength = MegaParse.ReadMotInt(br);
bytesread += 4;
MCCFrame frame = new MCCFrame();
frame.points = new Vector3[arraylength];
string dataformattag = Read(br, 4);
int bufferlength = MegaParse.ReadMotInt(br);
bytesread += 8;
if ( dataformattag == "FVCA" )
{
if ( bufferlength != arraylength * 3 * 4 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = MegaParse.ReadMotFloat(br);
frame.points[i].y = MegaParse.ReadMotFloat(br);
frame.points[i].z = MegaParse.ReadMotFloat(br);
}
bytesread += arraylength * 3 * 4;
}
else
{
if ( dataformattag == "DVCA" )
{
if ( bufferlength != arraylength * 3 * 8 )
{
Debug.Log("buffer len error");
return;
}
for ( int i = 0; i < arraylength; i++ )
{
frame.points[i].x = (float)MegaParse.ReadMotDouble(br);
frame.points[i].y = (float)MegaParse.ReadMotDouble(br);
frame.points[i].z = (float)MegaParse.ReadMotDouble(br);
}
bytesread += arraylength * 3 * 8;
}
else
{
Debug.Log("Format Error");
return;
}
}
frames.Add(frame);
}
}
// Build table
am.Verts = new MegaPCVert[frames[0].points.Length];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[frames.Count];
for ( int p = 0; p < am.Verts[i].points.Length; p++ )
am.Verts[i].points[p] = frames[p].points[i];
}
BuildData(mods, am, filename);
br.Close();
}
void LoadMDD()
{
MegaPointCache am = (MegaPointCache)target;
mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Motion Designer File", lastpath, "mdd");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
Verts.Clear();
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
int numSamples = MegaParse.ReadMotInt(br);
int numPoints = MegaParse.ReadMotInt(br);
float t = 0.0f;
for ( int i = 0; i < numSamples; i++ )
t = MegaParse.ReadMotFloat(br);
am.maxtime = t;
am.Verts = new MegaPCVert[numPoints];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[numSamples];
}
for ( int i = 0; i < numSamples; i++ )
{
for ( int v = 0; v < numPoints; v++ )
{
am.Verts[v].points[i].x = MegaParse.ReadMotFloat(br);
am.Verts[v].points[i].y = MegaParse.ReadMotFloat(br);
am.Verts[v].points[i].z = MegaParse.ReadMotFloat(br);
}
}
BuildData(mods, am, filename);
br.Close();
}
void BuildData(MegaModifiers mods, MegaPointCache am, string filename)
{
// Build vector3[] of base verts
Vector3[] baseverts = new Vector3[am.Verts.Length];
for ( int i = 0; i < am.Verts.Length; i++ )
baseverts[i] = am.Verts[i].points[0];
if ( !TryMapping1(baseverts, mods.verts) )
{
EditorUtility.DisplayDialog("Mapping Failed!", "Mapping of " + Path.GetFileNameWithoutExtension(filename) + " failed!", "OK");
EditorUtility.ClearProgressBar();
return;
}
// Remap vertices
for ( int i = 0; i < am.Verts.Length; i++ )
{
for ( int v = 0; v < am.Verts[i].points.Length; v++ )
{
if ( negx )
am.Verts[i].points[v].x = -am.Verts[i].points[v].x;
if ( flipyz )
{
float z = am.Verts[i].points[v].z;
am.Verts[i].points[v].z = am.Verts[i].points[v].y;
am.Verts[i].points[v].y = z;
}
if ( negz )
am.Verts[i].points[v].z = -am.Verts[i].points[v].z;
am.Verts[i].points[v] = am.Verts[i].points[v] * scl;
}
}
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i].indices = FindVerts(am.Verts[i].points[0]);
if ( am.Verts[i].indices.Length == 0 )
{
EditorUtility.DisplayDialog("Final Mapping Failed!", "Mapping of " + Path.GetFileNameWithoutExtension(filename) + " failed!", "OK");
EditorUtility.ClearProgressBar();
return;
}
}
}
void LoadPC2()
{
MegaPointCache am = (MegaPointCache)target;
mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Point Cache File", lastpath, "pc2");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
Verts.Clear();
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
string sig = MegaParse.ReadStr(br);
if ( sig != "POINTCACHE2" )
{
br.Close();
return;
}
int fileVersion = br.ReadInt32();
if ( fileVersion != 1 )
{
br.Close();
return;
}
int numPoints = br.ReadInt32();
br.ReadSingle();
br.ReadSingle();
int numSamples = br.ReadInt32();
am.Verts = new MegaPCVert[numPoints];
for ( int i = 0; i < am.Verts.Length; i++ )
{
am.Verts[i] = new MegaPCVert();
am.Verts[i].points = new Vector3[numSamples];
}
for ( int i = 0; i < numSamples; i++ )
{
for ( int v = 0; v < numPoints; v++ )
am.Verts[v].points[i] = MegaParse.ReadP3(br);
}
BuildData(mods, am, filename);
br.Close();
}
// Utils methods
int[] FindVerts(Vector3 p)
{
List<int> indices = new List<int>();
for ( int i = 0; i < mods.verts.Length; i++ )
{
float dist = Vector3.Distance(p, mods.verts[i]);
if ( dist < 0.0001f ) //mods.verts[i].Equals(p) )
indices.Add(i);
}
return indices.ToArray();
}
Vector3 Extents(Vector3[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0];
max = verts[0];
for ( int i = 1; i < verts.Length; i++ )
{
if ( verts[i].x < min.x ) min.x = verts[i].x;
if ( verts[i].y < min.y ) min.y = verts[i].y;
if ( verts[i].z < min.z ) min.z = verts[i].z;
if ( verts[i].x > max.x ) max.x = verts[i].x;
if ( verts[i].y > max.y ) max.y = verts[i].y;
if ( verts[i].z > max.z ) max.z = verts[i].z;
}
extent = max - min;
}
return extent;
}
Vector3 Extents(MegaPCVert[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0].points[0];
max = verts[0].points[0];
for ( int i = 1; i < verts.Length; i++ )
{
Vector3 p = verts[i].points[0];
if ( p.x < min.x ) min.x = p.x;
if ( p.y < min.y ) min.y = p.y;
if ( p.z < min.z ) min.z = p.z;
if ( p.x > max.x ) max.x = p.x;
if ( p.y > max.y ) max.y = p.y;
if ( p.z > max.z ) max.z = p.z;
}
extent = max - min;
}
return extent;
}
public override void OnInspectorGUI()
{
MegaPointCache am = (MegaPointCache)target;
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Import PC2") )
{
LoadPC2();
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Import MDD") )
{
LoadMDD();
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Import MC") )
{
LoadMCC();
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
// Basic mod stuff
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
CommonModParamsBasic(am);
am.time = EditorGUILayout.FloatField("Time", am.time);
am.maxtime = EditorGUILayout.FloatField("Loop Time", am.maxtime);
am.animated = EditorGUILayout.Toggle("Animated", am.animated);
am.speed = EditorGUILayout.FloatField("Speed", am.speed);
am.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", am.LoopMode);
am.interpMethod = (MegaInterpMethod)EditorGUILayout.EnumPopup("Interp Method", am.interpMethod);
am.blendMode = (MegaBlendAnimMode)EditorGUILayout.EnumPopup("Blend Mode", am.blendMode);
if ( am.blendMode == MegaBlendAnimMode.Additive )
am.weight = EditorGUILayout.FloatField("Weight", am.weight);
if ( am.Verts != null && am.Verts.Length > 0 )
{
int mem = am.Verts.Length * am.Verts[0].points.Length * 12;
EditorGUILayout.LabelField("Memory: ", (mem / 1024) + "KB");
}
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
// From here down could move to util class
int FindVert(Vector3 vert, Vector3[] tverts, float tolerance, float scl, bool flipyz, bool negx, bool negz, int vn)
{
int find = 0;
if ( negx )
vert.x = -vert.x;
if ( flipyz )
{
float z = vert.z;
vert.z = vert.y;
vert.y = z;
}
if ( negz )
vert.z = -vert.z;
vert /= scl;
float closest = Vector3.SqrMagnitude(tverts[0] - vert);
for ( int i = 0; i < tverts.Length; i++ )
{
float dif = Vector3.SqrMagnitude(tverts[i] - vert);
if ( dif < closest )
{
closest = dif;
find = i;
}
}
if ( closest > tolerance ) //0.0001f ) // not exact
return -1;
return find; //0;
}
bool DoMapping(Vector3[] verts, Vector3[] tverts, float scale, bool flipyz, bool negx, bool negz)
{
for ( int i = 0; i < verts.Length; i++ )
{
float a = (float)i / (float)verts.Length;
//Debug.Log("map " + i);
EditorUtility.DisplayProgressBar("Mapping", "Mapping vertex " + i, a);
int mapping = FindVert(verts[i], tverts, tolerance, scale, flipyz, negx, negz, i);
if ( mapping == -1 )
{
// Failed
EditorUtility.ClearProgressBar();
return false;
}
}
EditorUtility.ClearProgressBar();
return true;
}
// Out of this we need scl, negx, negz and flipyz
bool TryMapping1(Vector3[] tverts, Vector3[] verts)
{
//for ( int i = 0; i < 4; i++ )
// Debug.Log("cache vert " + tverts[i].ToString("0.00000"));
//for ( int i = 0; i < 4; i++ )
// Debug.Log("mesh vert " + verts[i].ToString("0.00000"));
// Get extents for mod verts and for imported meshes, if not the same then scale
Vector3 min1,max1;
Vector3 min2,max2;
Vector3 ex1 = Extents(verts, out min1, out max1);
Vector3 ex2 = Extents(tverts, out min2, out max2);
//Debug.Log("mesh extents " + ex1.ToString("0.00000"));
//Debug.Log("cache extents " + ex2.ToString("0.00000"));
//Debug.Log("mesh min " + min1.ToString("0.00000"));
//Debug.Log("cache min " + min2.ToString("0.00000"));
//Debug.Log("mesh max " + max1.ToString("0.00000"));
//Debug.Log("cache max " + max2.ToString("0.00000"));
int largest1 = MegaUtils.LargestComponent(ex1);
int largest2 = MegaUtils.LargestComponent(ex2);
//Debug.Log(largest1 + " " + largest2);
scl = ex1[largest1] / ex2[largest2];
//Debug.Log("scl " + scl);
//Vector3 offset = verts[0] - (tverts[0] * scl);
//Debug.Log("Offset " + offset.ToString("0.00000"));
// need min max on all axis so we can produce an offset to add
int map = 0;
for ( map = 0; map < 8; map++ )
{
flipyz = ((map & 4) != 0);
negx = ((map & 2) != 0);
negz = ((map & 1) != 0);
bool mapped = DoMapping(verts, tverts, scl, flipyz, negx, negz);
if ( mapped )
break;
}
if ( map == 8 ) // We couldnt find any mapping
return false;
//Debug.Log("scl " + scl + " negx " + negx + " negz " + negz + " flipyz " + flipyz);
return true;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 20f8c2c788b01ee4f8e7da30126561bd
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaPush))]
public class MegaPushEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Push Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/push_help.png"); }
public override bool Inspector()
{
MegaPush mod = (MegaPush)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.method = (MegaNormType)EditorGUILayout.EnumPopup("Method", mod.method);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 68e5680e4c4f617479828a66038f98ed
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaRadialSkew))]
public class MegaRadialSkewEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Radial Skew Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/skew_help.png"); }
public override bool Inspector()
{
MegaRadialSkew mod = (MegaRadialSkew)target;
EditorGUIUtility.LookLikeControls();
mod.angle = EditorGUILayout.FloatField("Angle", mod.angle);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.eaxis = (MegaAxis)EditorGUILayout.EnumPopup("Effective Axis", mod.eaxis);
mod.biaxial = EditorGUILayout.Toggle("Bi Axial", mod.biaxial);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 724864362d9bff84987eade342305b0a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaRipple))]
public class MegaRippleEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Ripple Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("ripple_help.png"); }
public override bool Inspector()
{
MegaRipple mod = (MegaRipple)target;
EditorGUIUtility.LookLikeControls();
mod.amp = EditorGUILayout.FloatField("Amp", mod.amp);
mod.amp2 = EditorGUILayout.FloatField("Amp 2", mod.amp2);
mod.flex = EditorGUILayout.FloatField("Flex", mod.flex);
mod.wave = EditorGUILayout.FloatField("Wave", mod.wave);
mod.phase = EditorGUILayout.FloatField("Phase", mod.phase);
mod.Decay = EditorGUILayout.FloatField("Decay", mod.Decay);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.Speed = EditorGUILayout.FloatField("Speed", mod.Speed);
mod.radius = EditorGUILayout.FloatField("Radius", mod.radius);
mod.segments = EditorGUILayout.IntField("Segments", mod.segments);
mod.circles = EditorGUILayout.IntField("Circles", mod.circles);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 214dd9231e1037547baa4ed6ae284b41
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class MegaRopeDeformEditor : Editor
{
static MegaRopeDeformEditor()
{
//EditorApplication.update += Update;
}
// Have a per object flag for editor update
static void Update1()
{
GameObject obj = Selection.activeGameObject;
if ( obj )
{
//MegaRopeDeform mr = (MegaRopeDeform)obj.GetComponent<MegaRopeDeform>();
//if ( mr )
{
MegaModifyObject mod = (MegaModifyObject)obj.GetComponent<MegaModifyObject>();
if ( mod )
{
mod.ModifyObject();
}
}
}
}
static void Update()
{
MegaModifyObject[] mods = (MegaModifyObject[])FindSceneObjectsOfType(typeof(MegaModifyObject));
for ( int i = 0; i < mods.Length; i++ )
mods[i].ModifyObject();
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 8f38c488656f01842875b18c1e05c882
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaRubber))]
public class MegaRubberEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Rubber Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool DisplayCommon() { return false; }
public override bool Inspector()
{
MegaRubber mod = (MegaRubber)target;
EditorGUIUtility.LookLikeControls();
mod.ModEnabled = EditorGUILayout.Toggle("Enabled", mod.ModEnabled);
MegaRubberType mattype = (MegaRubberType)EditorGUILayout.EnumPopup("Material", mod.Presets);
if ( mattype != mod.Presets )
{
mod.Presets = mattype;
mod.ChangeMaterial();
}
MegaWeightChannel channel = (MegaWeightChannel)EditorGUILayout.EnumPopup("Channel", mod.channel);
if ( channel != mod.channel )
{
mod.channel = channel;
mod.ChangeChannel();
}
channel = (MegaWeightChannel)EditorGUILayout.EnumPopup("Stiff Channel", mod.stiffchannel);
if ( channel != mod.stiffchannel )
{
mod.stiffchannel = channel;
mod.ChangeChannel();
}
mod.threshold = EditorGUILayout.Slider("Threshhold", mod.threshold, 0.0f, 1.0f);
if ( GUILayout.Button("Apply Threshold") )
{
mod.ChangeChannel();
EditorUtility.SetDirty(target);
}
mod.Intensity = EditorGUILayout.Vector3Field("Intensity", mod.Intensity);
mod.gravity = EditorGUILayout.FloatField("Gravity", mod.gravity);
mod.damping = EditorGUILayout.Vector3Field("Damping", mod.damping);
mod.mass = EditorGUILayout.FloatField("Mass", mod.mass);
mod.stiffness = EditorGUILayout.Vector3Field("Stiffness", mod.stiffness);
mod.showweights = EditorGUILayout.Toggle("Show Weights", mod.showweights);
mod.size = EditorGUILayout.FloatField("Size", mod.size * 100.0f) * 0.01f;
return false;
}
#if false
public override void DrawSceneGUI()
{
MegaRubber mod = (MegaRubber)target;
if ( mod.showweights && mod.vr != null )
{
Color col = Color.black;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = Matrix4x4.identity;
for ( int i = 0; i < mod.vr.Length; i++ )
{
float w = mod.vr[i].weight;
if ( w > 0.6666f )
col = Color.Lerp(Color.green, Color.red, (w - 0.6666f) * 3.0f);
else
{
if ( w > 0.3333f )
col = Color.Lerp(Color.blue, Color.green, (w - 0.3333f) * 3.0f);
else
{
Color nocol = new Color(0.0f, 0.0f, 1.0f, 0.0f);
col = Color.Lerp(nocol, Color.blue, w * 3.0f);
}
}
Handles.color = col;
Vector3 p = tm.MultiplyPoint(mod.vr[i].cpos);
Handles.DotCap(i, p, Quaternion.identity, mod.size);
}
Handles.matrix = Matrix4x4.identity;
}
}
#else
public override void DrawSceneGUI()
{
MegaRubber mod = (MegaRubber)target;
if ( mod.showweights && mod.vr != null )
{
Color col = Color.black;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = Matrix4x4.identity;
for ( int i = 0; i < mod.vr.Length; i++ )
{
float w = mod.vr[i].weight;
if ( w > 0.5f )
col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f);
else
col = Color.Lerp(Color.blue, Color.green, w * 2.0f);
Handles.color = col;
Vector3 p = tm.MultiplyPoint(mod.vr[i].cpos);
Handles.DotCap(i, p, Quaternion.identity, mod.size);
}
Handles.matrix = Matrix4x4.identity;
}
}
#endif
}
\ No newline at end of file
fileFormatVersion: 2
guid: 6150fc94cb1a82d4f8e86069d6add78a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

#if false
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSelection))]
public class MegaSelectionEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Selection Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool DisplayCommon() { return false; }
public override bool Inspector()
{
MegaSelection mod = (MegaSelection)target;
EditorGUIUtility.LookLikeControls();
mod.weight = EditorGUILayout.FloatField("Weight", mod.weight);
return false;
}
public override void DrawSceneGUI()
{
MegaSelection mod = (MegaSelection)target;
MegaModifiers mc = mod.gameObject.GetComponent<MegaModifiers>();
float[] sel = mod.GetSel();
if ( mc != null && sel != null )
{
Color col = Color.black;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = Matrix4x4.identity;
for ( int i = 0; i < sel.Length; i++ )
{
float w = sel[i];
if ( w > 0.5f )
col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f);
else
col = Color.Lerp(Color.blue, Color.green, w * 2.0f);
Handles.color = col;
Vector3 p = tm.MultiplyPoint(mc.sverts[i]);
Handles.DotCap(i, p, Quaternion.identity, 0.01f);
}
Handles.matrix = Matrix4x4.identity;
}
}
}
#endif
fileFormatVersion: 2
guid: dd995686638e47640aa508801c682f10
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 5114b1a06af8e61478efba65fd173cbb
folderAsset: yes
timeCreated: 1482163012
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaMeshPage))]
public class MegaMeshPageEditor : Editor
{
[MenuItem("GameObject/Create Other/MegaShape/Page Mesh")]
static void CreatePageMesh()
{
Vector3 pos = UnityEditor.SceneView.lastActiveSceneView.pivot;
GameObject go = new GameObject("Page Mesh");
MeshFilter mf = go.AddComponent<MeshFilter>();
if (mf.sharedMesh == null)
{
mf.sharedMesh = new Mesh();
}
MeshRenderer mr = go.AddComponent<MeshRenderer>();
Material[] mats = new Material[3];
mr.sharedMaterials = mats;
MegaMeshPage pm = go.AddComponent<MegaMeshPage>();
go.transform.position = pos;
Selection.activeObject = go;
pm.Rebuild();
}
public override void OnInspectorGUI()
{
MegaMeshPage mod = (MegaMeshPage)target;
//bool rebuild = DrawDefaultInspector();
EditorGUIUtility.LookLikeControls();
mod.Width = EditorGUILayout.FloatField("Width", mod.Width);
mod.Length = EditorGUILayout.FloatField("Length", mod.Length);
mod.Height = EditorGUILayout.FloatField("Height", mod.Height);
mod.WidthSegs = EditorGUILayout.IntField("Width Segs", mod.WidthSegs);
mod.LengthSegs = EditorGUILayout.IntField("Length Segs", mod.LengthSegs);
mod.HeightSegs = EditorGUILayout.IntField("Height Segs", mod.HeightSegs);
mod.genUVs = EditorGUILayout.Toggle("Gen UVs", mod.genUVs);
mod.rotate = EditorGUILayout.FloatField("Rotate", mod.rotate);
mod.PivotBase = EditorGUILayout.Toggle("Pivot Base", mod.PivotBase);
mod.PivotEdge = EditorGUILayout.Toggle("Pivot Edge", mod.PivotEdge);
mod.tangents = EditorGUILayout.Toggle("Tangents", mod.tangents);
mod.optimize = EditorGUILayout.Toggle("Optimize", mod.optimize);
if ( GUI.changed ) //rebuild )
mod.Rebuild();
}
}
fileFormatVersion: 2
guid: 038390c95703c2e488d784d3e3bea0c9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeArc))]
public class MegaShapeArcEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeArc shape = (MegaShapeArc)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Radius", shape.radius);
if ( v != shape.radius )
{
shape.radius = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("From", shape.from);
if ( v != shape.from )
{
shape.from = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("To", shape.to);
if ( v != shape.to )
{
shape.to = v;
rebuild = true;
}
bool bv = EditorGUILayout.Toggle("Pie", shape.pie);
if ( bv != shape.pie )
{
shape.pie = bv;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: a151adea34d2b3747b87518e6d481910
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeCircle))]
public class MegaShapeCircleEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeCircle shape = (MegaShapeCircle)target;
bool rebuild = false;
float radius = EditorGUILayout.FloatField("Radius", shape.Radius);
if ( radius != shape.Radius )
{
if ( radius < 0.001f )
radius = 0.001f;
shape.Radius = radius;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 4de8dc9d4f5a58c42913c7c3c37b87e7
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
// TODO: SVG import
// TODO: Button to recalc lengths
// TEST: Build a simple scene in max then have a road, barrier, fence etc
[CustomEditor(typeof(MegaShape))]
public class MegaShapeEditor : Editor
{
int selected = -1;
Vector3 pm = new Vector3();
Vector3 delta = new Vector3();
bool showsplines = false;
bool showknots = false;
float ImportScale = 1.0f;
static public Vector3 CursorPos = Vector3.zero; //0.0f;
static public Vector3 CursorSpline = Vector3.zero; //0.0f;
static public Vector3 CursorTangent = Vector3.zero; //0.0f;
public virtual bool Params() { return false; }
public bool showcommon = true;
public override void OnInspectorGUI()
{
bool buildmesh = false;
MegaShape shape = (MegaShape)target;
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Add Knot") )
{
if ( shape.splines == null || shape.splines.Count == 0 )
{
MegaSpline spline = new MegaSpline(); // Have methods for these
shape.splines.Add(spline);
}
//Undo.RegisterUndo(target, "Add Knot");
MegaKnot knot = new MegaKnot();
#if true
// Add a point at CursorPos
//sp = selected + 1;
//Debug.Log("CursorPos " + CursorPos + " CursorKnot " + CursorKnot);
float per = CursorPercent * 0.01f;
CursorTangent = shape.splines[0].Interpolate(per + 0.01f, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p;
CursorPos = shape.splines[0].Interpolate(per, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p;
knot.p = CursorPos;
//CursorTangent =
//Vector3 t = shape.splines[0].knots[selected].Interpolate(0.51f, shape.splines[0].knots[0]);
knot.outvec = (CursorTangent - knot.p);
knot.outvec.Normalize();
knot.outvec *= shape.splines[0].knots[CursorKnot].seglength * 0.25f;
knot.invec = -knot.outvec;
knot.invec += knot.p;
knot.outvec += knot.p;
shape.splines[0].knots.Insert(CursorKnot + 1, knot);
#else
int sp = 0;
if ( selected == -1 || shape.splines[0].knots.Count == 1 )
{
shape.splines[0].knots.Add(knot);
selected = shape.splines[0].knots.Count - 1;
}
else
{
if ( selected < shape.splines[0].knots.Count - 1 )
{
sp = selected + 1;
knot.p = shape.splines[0].knots[selected].Interpolate(0.5f, shape.splines[0].knots[selected + 1]);
Vector3 t = shape.splines[0].knots[selected].Interpolate(0.51f, shape.splines[0].knots[selected + 1]);
knot.outvec = (t - knot.p); //.Normalize();
knot.outvec.Normalize();
knot.outvec *= shape.splines[0].knots[selected].seglength * 0.25f;
knot.invec = -knot.outvec;
knot.invec += knot.p;
knot.outvec += knot.p;
}
else
{
if ( shape.splines[0].closed )
{
sp = selected + 1;
knot.p = shape.splines[0].knots[selected].Interpolate(0.5f, shape.splines[0].knots[0]);
Vector3 t = shape.splines[0].knots[selected].Interpolate(0.51f, shape.splines[0].knots[0]);
knot.outvec = (t - knot.p); //.Normalize();
knot.outvec.Normalize();
knot.outvec *= shape.splines[0].knots[selected].seglength * 0.25f;
knot.invec = -knot.outvec;
knot.invec += knot.p;
knot.outvec += knot.p;
}
else
{
sp = selected - 1;
//Debug.Log("selected " + selected + " count " + shape.splines[0].knots.Count + " sp " + sp);
knot.p = shape.splines[0].knots[sp].Interpolate(0.5f, shape.splines[0].knots[sp + 1]);
Vector3 t = shape.splines[0].knots[sp].Interpolate(0.51f, shape.splines[0].knots[sp + 1]);
knot.outvec = (t - knot.p); //.Normalize();
knot.outvec.Normalize();
knot.outvec *= shape.splines[0].knots[sp].seglength * 0.25f;
knot.invec = -knot.outvec;
knot.invec += knot.p;
knot.outvec += knot.p;
sp++;
}
}
shape.splines[0].knots.Insert(sp, knot);
selected = sp; //++;
}
#endif
shape.CalcLength(10);
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( GUILayout.Button("Delete Knot") )
{
if ( selected != -1 )
{
//Undo.RegisterUndo(target, "Delete Knot");
shape.splines[0].knots.RemoveAt(selected);
selected--;
shape.CalcLength(10);
}
EditorUtility.SetDirty(target);
buildmesh = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Match Handles") )
{
if ( selected != -1 )
{
//Undo.RegisterUndo(target, "Match Handles");
Vector3 p = shape.splines[0].knots[selected].p;
Vector3 d = shape.splines[0].knots[selected].outvec - p;
shape.splines[0].knots[selected].invec = p - d;
shape.CalcLength(10);
}
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( GUILayout.Button("Load") )
{
// Load a spl file from max, so delete everything and replace
LoadShape(ImportScale);
buildmesh = true;
}
EditorGUILayout.EndHorizontal();
showcommon = EditorGUILayout.Foldout(showcommon, "Common Params");
bool rebuild = false; //Params();
if ( showcommon )
{
//CursorPos = EditorGUILayout.Vector3Field("Cursor", CursorPos);
CursorPercent = EditorGUILayout.FloatField("Cursor", CursorPercent);
CursorPercent = Mathf.Repeat(CursorPercent, 100.0f);
ImportScale = EditorGUILayout.FloatField("Import Scale", ImportScale);
MegaAxis av = (MegaAxis)EditorGUILayout.EnumPopup("Axis", shape.axis);
if ( av != shape.axis )
{
shape.axis = av;
rebuild = true;
}
shape.col1 = EditorGUILayout.ColorField("Col 1", shape.col1);
shape.col2 = EditorGUILayout.ColorField("Col 2", shape.col2);
shape.KnotCol = EditorGUILayout.ColorField("Knot Col", shape.KnotCol);
shape.HandleCol = EditorGUILayout.ColorField("Handle Col", shape.HandleCol);
shape.VecCol = EditorGUILayout.ColorField("Vec Col", shape.VecCol);
shape.KnotSize = EditorGUILayout.FloatField("Knot Size", shape.KnotSize);
shape.stepdist = EditorGUILayout.FloatField("Step Dist", shape.stepdist);
if ( shape.stepdist < 0.01f )
shape.stepdist = 0.01f;
shape.normalizedInterp = EditorGUILayout.Toggle("Normalized Interp", shape.normalizedInterp);
shape.drawHandles = EditorGUILayout.Toggle("Draw Handles", shape.drawHandles);
shape.drawKnots = EditorGUILayout.Toggle("Draw Knots", shape.drawKnots);
shape.drawspline = EditorGUILayout.Toggle("Draw Spline", shape.drawspline);
shape.lockhandles = EditorGUILayout.Toggle("Lock Handles", shape.lockhandles);
shape.animate = EditorGUILayout.Toggle("Animate", shape.animate);
if ( shape.animate )
{
shape.time = EditorGUILayout.FloatField("Time", shape.time);
shape.MaxTime = EditorGUILayout.FloatField("Loop Time", shape.MaxTime);
shape.speed = EditorGUILayout.FloatField("Speed", shape.speed);
shape.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", shape.LoopMode);
}
// Mesher
shape.makeMesh = EditorGUILayout.Toggle("Make Mesh", shape.makeMesh);
if ( shape.makeMesh )
{
shape.meshType = (MeshShapeType)EditorGUILayout.EnumPopup("Mesh Type", shape.meshType);
shape.Pivot = EditorGUILayout.Vector3Field("Pivot", shape.Pivot);
shape.CalcTangents = EditorGUILayout.Toggle("Calc Tangents", shape.CalcTangents);
shape.GenUV = EditorGUILayout.Toggle("Gen UV", shape.GenUV);
shape.PhysUV = EditorGUILayout.Toggle("Physical UV", shape.PhysUV);
shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset);
shape.UVRotate = EditorGUILayout.Vector2Field("UV Rotate", shape.UVRotate);
shape.UVScale = EditorGUILayout.Vector2Field("UV Scale", shape.UVScale);
shape.UVOffset1 = EditorGUILayout.Vector2Field("UV Offset1", shape.UVOffset1);
shape.UVRotate1 = EditorGUILayout.Vector2Field("UV Rotate1", shape.UVRotate1);
shape.UVScale1 = EditorGUILayout.Vector2Field("UV Scale1", shape.UVScale1);
switch ( shape.meshType )
{
case MeshShapeType.Fill:
shape.DoubleSided = EditorGUILayout.Toggle("Double Sided", shape.DoubleSided);
shape.Height = EditorGUILayout.FloatField("Height", shape.Height);
shape.HeightSegs = EditorGUILayout.IntField("HeightSegs", shape.HeightSegs);
shape.UseHeightCurve = EditorGUILayout.Toggle("Use Height Crv", shape.UseHeightCurve);
if ( shape.UseHeightCurve )
shape.heightCrv = EditorGUILayout.CurveField("Height Curve", shape.heightCrv);
break;
case MeshShapeType.Line:
shape.DoubleSided = EditorGUILayout.Toggle("Double Sided", shape.DoubleSided);
shape.Height = EditorGUILayout.FloatField("Height", shape.Height);
shape.HeightSegs = EditorGUILayout.IntField("HeightSegs", shape.HeightSegs);
shape.heightCrv = EditorGUILayout.CurveField("Height Curve", shape.heightCrv);
shape.Start = EditorGUILayout.FloatField("Start", shape.Start);
shape.End = EditorGUILayout.FloatField("End", shape.End);
shape.Rotate = EditorGUILayout.FloatField("Rotate", shape.Rotate);
break;
case MeshShapeType.Tube:
shape.Sides = EditorGUILayout.IntField("Sides", shape.Sides);
shape.TubeStep = EditorGUILayout.FloatField("TubeStep", shape.TubeStep);
shape.Start = EditorGUILayout.FloatField("Start", shape.Start);
shape.End = EditorGUILayout.FloatField("End", shape.End);
break;
}
}
showsplines = EditorGUILayout.Foldout(showsplines, "Splines");
if ( showsplines )
{
for ( int i = 0; i < shape.splines.Count; i++ )
{
DisplaySpline(shape, shape.splines[i]);
}
}
}
if ( Params() )
{
rebuild = true;
}
if ( GUI.changed )
{
EditorUtility.SetDirty(target);
//shape.CalcLength(10);
buildmesh = true;
}
if ( rebuild )
{
shape.MakeShape();
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( buildmesh )
{
shape.BuildMesh();
}
}
void DisplayKnot(MegaShape shape, MegaSpline spline, MegaKnot knot)
{
bool recalc = false;
Vector3 p = EditorGUILayout.Vector3Field("Pos", knot.p);
#if false
Vector3 invec = EditorGUILayout.Vector3Field("In", knot.invec);
//Vector3 outvec = EditorGUILayout.Vector3Field("Out", knot.outvec);
if ( invec != knot.invec )
{
if ( shape.lockhandles )
{
Vector3 d = invec - knot.invec;
knot.outvec -= d;
}
knot.invec = invec;
recalc = true;
}
Vector3 outvec = EditorGUILayout.Vector3Field("Out", knot.outvec);
if ( outvec != knot.outvec )
{
if ( shape.lockhandles )
{
Vector3 d = outvec - knot.outvec;
knot.invec -= d;
}
knot.outvec = outvec;
recalc = true;
}
//Vector3 p = EditorGUILayout.Vector3Field("Pos", knot.p);
#endif
delta = p - knot.p;
knot.invec += delta;
knot.outvec += delta;
if ( knot.p != p )
{
recalc = true;
knot.p = p;
}
if ( recalc )
{
shape.CalcLength(10);
}
}
void DisplaySpline(MegaShape shape, MegaSpline spline)
{
bool closed = EditorGUILayout.Toggle("Closed", spline.closed);
if ( closed != spline.closed )
{
spline.closed = closed;
shape.CalcLength(10);
EditorUtility.SetDirty(target);
//shape.BuildMesh();
}
EditorGUILayout.LabelField("Length ", spline.length.ToString("0.000"));
showknots = EditorGUILayout.Foldout(showknots, "Knots");
if ( showknots )
{
for ( int i = 0; i < spline.knots.Count; i++ )
{
DisplayKnot(shape, spline, spline.knots[i]);
//EditorGUILayout.Separator();
}
}
}
public void OnSceneGUI()
{
Undo.RegisterUndo(target, "Move Shape Points");
MegaShape shape = (MegaShape)target;
float ksize = shape.KnotSize * 0.01f;
float ringratio = 1.3f;
float borderratio = 1.15f;
float knotsize = ksize;
//float ringsize = knotsize1.1f;
float handlesize = knotsize * 0.75f;
//float outdiscsize = ksize * 1.0f * 0.5f;
Handles.matrix = shape.transform.localToWorldMatrix;
bool recalc = false;
Vector3 dragplane = Vector3.one;
Vector3 camfwd = Camera.current.transform.forward;
if ( Mathf.Abs(camfwd.x) > Mathf.Abs(camfwd.y) )
{
if ( Mathf.Abs(camfwd.x) > Mathf.Abs(camfwd.z) )
dragplane.x = 0.0f;
else
dragplane.z = 0.0f;
}
else
{
if ( Mathf.Abs(camfwd.y) > Mathf.Abs(camfwd.z) )
dragplane.y = 0.0f;
else
dragplane.z = 0.0f;
}
//Debug.Log("Dragplane " + dragplane);
Color nocol = new Color(0, 0, 0, 0);
for ( int s = 0; s < shape.splines.Count; s++ )
{
for ( int p = 0; p < shape.splines[s].knots.Count; p++ )
{
Vector3 pp = shape.transform.TransformPoint(shape.splines[s].knots[p].p);
Vector3 normal = Camera.current.transform.forward;
if ( shape.drawKnots ) //&& recalc == false )
{
pm = shape.splines[s].knots[p].p;
Handles.color = Color.black;
Handles.color = shape.VecCol;
//Vector3 normal = (pp - Camera.current.transform.position).normalized;
Handles.DrawSolidDisc(pp, normal, knotsize * borderratio); //ksize * 0.55f);
if ( p == selected )
{
Handles.color = Color.white;
Handles.Label(pm, " Selected\n" + pm.ToString("0.000"));
}
else
{
Handles.color = shape.KnotCol;
Handles.Label(pm, " " + p);
}
//if ( p == selected )
//shape.splines[s].knots[p].p = Handles.PositionHandle(pm, Quaternion.identity);
//else
//{
Handles.color = shape.KnotCol;
Handles.DrawSolidDisc(pp, normal, knotsize);
//shape.splines[s].knots[p].p = Handles.FreeMoveHandle(pm, Quaternion.identity, ksize, Vector3.zero, Handles.SphereCap); //CubeCap);
Handles.color = nocol; //shape.VecCol;
Vector3 newp = Handles.FreeMoveHandle(pm, Quaternion.identity, knotsize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap);
shape.splines[s].knots[p].p += Vector3.Scale(newp - pm, dragplane);
//if ( shape.splines[s].knots[p].p != pm )
//selected = p;
//}
delta = shape.splines[s].knots[p].p - pm;
shape.splines[s].knots[p].invec += delta;
shape.splines[s].knots[p].outvec += delta;
if ( shape.splines[s].knots[p].p != pm )
{
selected = p;
recalc = true;
}
pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p);
//Handles.CubeCap(0, pm, Quaternion.identity, shape.KnotSize);
}
if ( shape.drawHandles ) //&& recalc == false )
{
Handles.color = shape.VecCol;
pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p);
Vector3 ip = shape.transform.TransformPoint(shape.splines[s].knots[p].invec);
Vector3 op = shape.transform.TransformPoint(shape.splines[s].knots[p].outvec);
Handles.DrawLine(pm, shape.transform.TransformPoint(shape.splines[s].knots[p].invec));
Handles.DrawLine(pm, shape.transform.TransformPoint(shape.splines[s].knots[p].outvec));
//Handles.color = Color.black;
//Vector3 normal = (op - Camera.current.transform.position).normalized;
Handles.DrawSolidDisc(op, normal, handlesize * borderratio); //ksize * 0.55f * ringratio);
//normal = Camera.current.transform.forward; //(ip - Camera.current.transform.position).normalized;
Handles.DrawSolidDisc(ip, normal, handlesize * borderratio); //ksize * 0.55f * ringratio);
Handles.color = shape.HandleCol;
//Handles.DrawSolidDisc(op, normal, ksize * 0.5f * ringratio);
//Handles.DrawSolidDisc(ip, normal, ksize * 0.5f * ringratio);
Handles.DrawSolidDisc(op, normal, handlesize);
Handles.DrawSolidDisc(ip, normal, handlesize);
//shape.splines[s].knots[p].invec = Handles.PositionHandle(shape.splines[s].knots[p].invec, Quaternion.identity); //shape.hsize);
//shape.splines[s].knots[p].outvec = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize);
Vector3 invec = shape.splines[s].knots[p].invec;
//if ( p == selected )
//invec = Handles.PositionHandle(shape.splines[s].knots[p].invec, Quaternion.identity); //shape.hsize);
//else
Handles.color = nocol;
Vector3 newinvec = Handles.FreeMoveHandle(shape.splines[s].knots[p].invec, Quaternion.identity, handlesize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap);
invec += Vector3.Scale(newinvec - invec, dragplane);
//Debug.Log("sel " + selected + " new " + invec.ToString("0.0000") + " old " + shape.splines[s].knots[p].invec.ToString("0.0000"));
if ( invec != shape.splines[s].knots[p].invec )
{
if ( shape.lockhandles )
{
Vector3 d = invec - shape.splines[s].knots[p].invec;
shape.splines[s].knots[p].outvec -= d;
}
shape.splines[s].knots[p].invec = invec;
selected = p;
recalc = true;
}
Vector3 outvec = shape.splines[s].knots[p].outvec; // = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize);
//if ( p == selected )
//outvec = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize);
//else
Vector3 newoutvec = Handles.FreeMoveHandle(shape.splines[s].knots[p].outvec, Quaternion.identity, handlesize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap);
outvec += Vector3.Scale(newoutvec - outvec, dragplane);
if ( outvec != shape.splines[s].knots[p].outvec )
{
if ( shape.lockhandles )
{
Vector3 d = outvec - shape.splines[s].knots[p].outvec;
shape.splines[s].knots[p].invec -= d;
}
shape.splines[s].knots[p].outvec = outvec;
selected = p;
recalc = true;
}
Vector3 hp = shape.transform.TransformPoint(shape.splines[s].knots[p].invec);
//Handles.CubeCap(0, hp, Quaternion.identity, shape.KnotSize);
if ( selected == p )
Handles.Label(hp, " " + p);
hp = shape.transform.TransformPoint(shape.splines[s].knots[p].outvec);
//Handles.CubeCap(0, hp, Quaternion.identity, shape.KnotSize);
if ( selected == p )
Handles.Label(hp, " " + p);
}
// Draw nearest point (use for adding knot)
//CursorPos = Handles.PositionHandle(CursorPos, Quaternion.identity);
#if false
if ( shape.drawKnots )
{
pm = shape.splines[s].knots[p].p;
if ( p == selected )
{
Handles.color = Color.white;
Handles.Label(pm, " Selected\n" + pm.ToString("0.000"));
}
else
{
Handles.color = shape.KnotCol;
Handles.Label(pm, " " + p);
}
//if ( p == selected )
shape.splines[s].knots[p].p = Handles.PositionHandle(pm, Quaternion.identity);
//else
//{
//shape.splines[s].knots[p].p = Handles.FreeMoveHandle(pm, Quaternion.identity, shape.KnotSize, Vector3.zero, Handles.CubeCap);
//if ( shape.splines[s].knots[p].p != pm )
//selected = p;
//}
delta = shape.splines[s].knots[p].p - pm;
shape.splines[s].knots[p].invec += delta;
shape.splines[s].knots[p].outvec += delta;
if ( shape.splines[s].knots[p].p != pm )
{
selected = p;
recalc = true;
}
pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p);
Handles.CubeCap(0, pm, Quaternion.identity, shape.KnotSize);
}
#endif
}
}
if ( recalc )
{
shape.CalcLength(10);
shape.BuildMesh();
}
Handles.matrix = Matrix4x4.identity;
}
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable)]
static void RenderGizmo(MegaShape shape, GizmoType gizmoType)
{
if ( (gizmoType & GizmoType.NotInSelectionHierarchy) != 0 )
{
if ( (gizmoType & GizmoType.Active) != 0 )
{
DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 1.0f));
Color col = Color.yellow;
col.a = 0.5f;
Gizmos.color = col; //Color.yellow;
//CursorPos = shape.FindNearestPoint(CursorPos, 5, ref CursorKnot, ref CursorTangent);
//CursorSpline = shape.FindNearestPoint(CursorPos, 5, ref CursorKnot, ref CursorTangent);
//Gizmos.DrawSphere(shape.transform.TransformPoint(CursorPos), shape.KnotSize);
CursorPos = shape.InterpCurve3D(0, CursorPercent * 0.01f, true);
Gizmos.DrawSphere(shape.transform.TransformPoint(CursorPos), shape.KnotSize * 0.01f);
Handles.color = Color.white;
Handles.Label(shape.transform.TransformPoint(CursorPos), "Cursor " + CursorPercent.ToString("0.00") + "% - " + CursorPos);
}
else
DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 0.25f));
}
Gizmos.DrawIcon(shape.transform.position, "MegaSpherify icon.png");
Handles.Label(shape.transform.position, " " + shape.name);
}
static public int CursorKnot = 0;
static public float CursorPercent = 0.0f;
// Dont want this in here, want in editor
// If we go over a knot then should draw to the knot
static void DrawGizmos(MegaShape shape, Color modcol)
{
if ( ((1 << shape.gameObject.layer) & Camera.current.cullingMask) == 0 )
return;
if ( !shape.drawspline )
return;
for ( int s = 0; s < shape.splines.Count; s++ )
{
float ldist = shape.stepdist * 0.1f;
if ( ldist < 0.01f )
ldist = 0.01f;
float ds = shape.splines[s].length / (shape.splines[s].length / ldist);
if ( ds > shape.splines[s].length )
{
ds = shape.splines[s].length;
}
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref lk);
for ( float dist = ds; dist < shape.splines[s].length; dist += ds )
{
float alpha = dist / shape.splines[s].length;
Vector3 pos = shape.splines[s].Interpolate(alpha, shape.normalizedInterp, ref k);
if ( (c & 1) == 1 )
Gizmos.color = shape.col1 * modcol;
else
Gizmos.color = shape.col2 * modcol;
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Gizmos.DrawLine(shape.transform.TransformPoint(first), shape.transform.TransformPoint(shape.splines[s].knots[lk].p));
first = shape.splines[s].knots[lk].p;
}
}
lk = k;
Gizmos.DrawLine(shape.transform.TransformPoint(first), shape.transform.TransformPoint(pos));
c++;
first = pos;
}
if ( (c & 1) == 1 )
Gizmos.color = shape.col1 * modcol;
else
Gizmos.color = shape.col2 * modcol;
Vector3 lastpos;
if ( shape.splines[s].closed )
lastpos = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref k);
else
lastpos = shape.splines[s].Interpolate(1.0f, shape.normalizedInterp, ref k);
Gizmos.DrawLine(shape.transform.TransformPoint(first), shape.transform.TransformPoint(lastpos));
}
//Gizmos.color = Color.yellow;
//CursorPos = shape.FindNearestPoint(CursorPos, 5, ref CursorKnot, ref CursorTangent);
//Gizmos.DrawWireSphere(shape.transform.TransformPoint(CursorPos), shape.KnotSize);
}
// Load stuff
string lastpath = "";
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
void LoadShape(float scale)
{
MegaShape ms = (MegaShape)target;
//Modifiers mod = mr.GetComponent<Modifiers>(); // Do this at start and store
string filename = EditorUtility.OpenFilePanel("Shape File", lastpath, "spl");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
ms.splines.Clear();
ParseFile(filename, ShapeCallback);
ms.Scale(scale);
ms.MaxTime = 0.0f;
for ( int s = 0; s < ms.splines.Count; s++ )
{
if ( ms.splines[s].animations != null )
{
for ( int a = 0; a < ms.splines[s].animations.Count; a++ )
{
MegaControl con = ms.splines[s].animations[a].con;
if ( con != null )
{
float t = con.Times[con.Times.Length - 1];
if ( t > ms.MaxTime )
ms.MaxTime = t;
}
}
}
}
}
public void ShapeCallback(string classname, BinaryReader br)
{
switch ( classname )
{
case "Shape": LoadShape(br); break;
}
}
public void LoadShape(BinaryReader br)
{
//MegaMorphEditor.Parse(br, ParseShape);
MegaParse.Parse(br, ParseShape);
}
public void ParseFile(string assetpath, ParseClassCallbackType cb)
{
FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
bool processing = true;
while ( processing )
{
string classname = MegaParse.ReadString(br);
if ( classname == "Done" )
break;
int chunkoff = br.ReadInt32();
long fpos = fs.Position;
cb(classname, br);
fs.Position = fpos + chunkoff;
}
br.Close();
}
static public Vector3 ReadP3(BinaryReader br)
{
Vector3 p = Vector3.zero;
p.x = br.ReadSingle();
p.y = br.ReadSingle();
p.z = br.ReadSingle();
return p;
}
bool SplineParse(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
MegaSpline ps = ms.splines[ms.splines.Count - 1];
switch ( cid )
{
case "Transform":
Vector3 pos = ReadP3(br);
Vector3 rot = ReadP3(br);
Vector3 scl = ReadP3(br);
rot.y = -rot.y;
ms.transform.position = pos;
ms.transform.rotation = Quaternion.Euler(rot * Mathf.Rad2Deg);
ms.transform.localScale = scl;
break;
case "Flags":
int count = br.ReadInt32();
ps.closed = (br.ReadInt32() == 1);
count = br.ReadInt32();
ps.knots = new List<MegaKnot>(count);
ps.length = 0.0f;
break;
case "Knots":
for ( int i = 0; i < ps.knots.Capacity; i++ )
{
MegaKnot pk = new MegaKnot();
pk.p = ReadP3(br);
pk.invec = ReadP3(br);
pk.outvec = ReadP3(br);
pk.seglength = br.ReadSingle();
ps.length += pk.seglength;
pk.length = ps.length;
ps.knots.Add(pk);
}
break;
}
return true;
}
MegaKnotAnim ma;
bool AnimParse(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
switch ( cid )
{
case "V":
int v = br.ReadInt32();
ma = new MegaKnotAnim();
int s = ms.GetSpline(v, ref ma); //.s, ref ma.p, ref ma.t);
if ( ms.splines[s].animations == null )
ms.splines[s].animations = new List<MegaKnotAnim>();
ms.splines[s].animations.Add(ma);
break;
case "Anim":
//ma.con = MegaBezVector3KeyControl.LoadBezVector3KeyControl(br);
ma.con = MegaParseBezVector3Control.LoadBezVector3KeyControl(br);
break;
}
return true;
}
bool ParseShape(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
switch ( cid )
{
case "Num":
int count = br.ReadInt32();
ms.splines = new List<MegaSpline>(count);
//id = 0;
break;
case "Spline":
MegaSpline spl = new MegaSpline();
ms.splines.Add(spl);
//MegaMorphEditor.Parse(br, SplineParse);
MegaParse.Parse(br, SplineParse);
break;
case "Anim":
//Debug.Log("Anim info");
//MegaMorphEditor.Parse(br, AnimParse);
MegaParse.Parse(br, AnimParse);
break;
}
return true;
}
}
fileFormatVersion: 2
guid: eb27e752f9d5b4246a4c99831e21bcaf
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeEllipse))]
public class MegaShapeEllipseEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeEllipse shape = (MegaShapeEllipse)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Length", shape.length);
if ( v != shape.length )
{
shape.length = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Width", shape.width);
if ( v != shape.width )
{
shape.width = v;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: dd10b13dfaba07b4084bd295f0f16e89
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeHelix))]
public class MegaShapeHelixEditor : MegaShapeEditor
{
public float radius1 = 1.0f;
public float radius2 = 1.0f;
public float height = 0.0f;
public float turns = 0.0f;
public float bias = 0.0f;
public bool clockwise = true;
public override bool Params()
{
MegaShapeHelix shape = (MegaShapeHelix)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Radius 1", shape.radius1);
if ( v != shape.radius1 )
{
shape.radius1 = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Radius 2", shape.radius2);
if ( v != shape.radius2 )
{
shape.radius2 = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Height", shape.height);
if ( v != shape.height )
{
shape.height = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Turns", shape.turns);
if ( v != shape.turns )
{
shape.turns = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Bias", shape.bias);
if ( v != shape.bias )
{
shape.bias = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Adjust", shape.adjust);
if ( v != shape.adjust )
{
shape.adjust = v;
rebuild = true;
}
int iv = EditorGUILayout.IntField("Points Per Turn", shape.PointsPerTurn);
if ( iv != shape.PointsPerTurn )
{
shape.PointsPerTurn = iv;
rebuild = true;
}
bool bv = EditorGUILayout.Toggle("Clockwise", shape.clockwise);
if ( bv != shape.clockwise )
{
shape.clockwise = bv;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: cf15e582f912c464191f5ba73d8d312a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeNGon))]
public class MegaShapeNGonEditor : MegaShapeEditor
{
public float fillet = 0.0f;
public int sides = 6;
public bool circular = false;
public bool scribe = false;
public override bool Params()
{
MegaShapeNGon shape = (MegaShapeNGon)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Radius", shape.radius);
if ( v != shape.radius )
{
shape.radius = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Fillet", shape.fillet);
if ( v != shape.fillet )
{
shape.fillet = v;
rebuild = true;
}
int iv = EditorGUILayout.IntField("Side", shape.sides);
if ( iv != shape.sides )
{
shape.sides = iv;
rebuild = true;
}
bool bv = EditorGUILayout.Toggle("Circular", shape.circular);
if ( bv != shape.circular )
{
shape.circular = bv;
rebuild = true;
}
bv = EditorGUILayout.Toggle("Circumscribed", shape.scribe);
if ( bv != shape.scribe )
{
shape.scribe = bv;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: a3da518f767adab4583835e14abd4298
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeRectangle))]
public class MegaShapeRectangleEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeRectangle shape = (MegaShapeRectangle)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Length", shape.length);
if ( v != shape.length )
{
shape.length = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Width", shape.width);
if ( v != shape.width )
{
shape.width = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Fillet", shape.fillet);
if ( v != shape.fillet )
{
shape.fillet = v;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: ae0dd6e50a1f56a4da5c3995b288d102
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaShapeStar))]
public class MegaShapeStarEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeStar shape = (MegaShapeStar)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Radius1", shape.radius1);
if ( v != shape.radius1 )
{
shape.radius1 = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Radius2", shape.radius2);
if ( v != shape.radius2 )
{
shape.radius2 = v;
rebuild = true;
}
int iv = EditorGUILayout.IntField("Points", shape.points);
if ( iv != shape.points )
{
shape.points = iv;
rebuild = true;
}
v = EditorGUILayout.FloatField("Distortion", shape.distortion);
if ( v != shape.distortion )
{
shape.distortion = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Fillet Radius 1", shape.fillet1);
if ( v != shape.fillet1 )
{
shape.fillet1 = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("Fillet Radius 2", shape.fillet2);
if ( v != shape.fillet2 )
{
shape.fillet2 = v;
rebuild = true;
}
return rebuild;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 9a9e2e774b48c234bbaa8374442dffe1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
// TODO: Select axis for shapes
// TODO: Add new spline to shape
// TODO: Button to recalc lengths
// TEST: Build a simple scene in max then have a road, barrier, fence etc
// Import of simple text file for path
public class MegaShapeWindow : EditorWindow
{
static bool showcommon;
//string name = "Shape";
static MegaAxis axis = MegaAxis.Y;
static bool drawknots = true;
static bool drawhandles = true;
static float stepdist = 0.5f;
static float knotsize = 2.0f;
static Color col1 = Color.white;
static Color col2 = Color.black;
static bool makemesh = false;
// Add menu named "My Window" to the Window menu
[MenuItem("GameObject/Mega Shapes")]
static void Init()
{
// Get existing open window or if none, make a new one:
//MegaShapeWindow window = (MegaShapeWindow)EditorWindow.GetWindow(typeof(MegaShapeWindow));
EditorWindow.GetWindow(typeof(MegaShapeWindow), false, "MegaShapes");
}
[MenuItem("GameObject/Create Other/MegaShape/Star Shape")] static void CreateStarShape() { CreateShape("Star", typeof(MegaShapeStar)); }
[MenuItem("GameObject/Create Other/MegaShape/Circle Shape")] static void CreateCircleShape() { CreateShape("Circle", typeof(MegaShapeCircle)); }
[MenuItem("GameObject/Create Other/MegaShape/NGon Shape")] static void CreateNGonShape() { CreateShape("NGon", typeof(MegaShapeNGon)); }
[MenuItem("GameObject/Create Other/MegaShape/Arc Shape")] static void CreateArcShape() { CreateShape("Arc", typeof(MegaShapeArc)); }
[MenuItem("GameObject/Create Other/MegaShape/Ellipse Shape")] static void CreateEllipseShape() { CreateShape("Ellipse", typeof(MegaShapeEllipse)); }
[MenuItem("GameObject/Create Other/MegaShape/Rectangle Shape")] static void CreateRectangleShape() { CreateShape("Rectangle", typeof(MegaShapeRectangle)); }
[MenuItem("GameObject/Create Other/MegaShape/Helix Shape")] static void CreateHelixShape() { CreateShape("Helix", typeof(MegaShapeHelix)); }
static Color butcol = new Color(0.75f, 0.75f, 1.0f);
static ModBut[] mods = new ModBut[] {
new ModBut("Arc", "Create a Arc Shape", typeof(MegaShapeArc), butcol),
new ModBut("Circle", "Create a Circle Shape", typeof(MegaShapeCircle), butcol),
new ModBut("Ellipse", "Create a Ellipse Shape", typeof(MegaShapeEllipse), butcol),
new ModBut("Helix", "Create a Helix Shape", typeof(MegaShapeHelix), butcol),
new ModBut("NGon", "Create a NGon Shape", typeof(MegaShapeNGon), butcol),
new ModBut("Rectangle", "Create a Rectangle Shape", typeof(MegaShapeRectangle), butcol),
new ModBut("Star", "Create a Star Shape", typeof(MegaShapeStar), butcol),
};
void DoButtons(ModBut[] buttons, float width, int bstep, bool modobj)
{
Color c = GUI.backgroundColor;
int off = 0;
GUI.backgroundColor = Color.blue;
Color guicol = GUI.color;
GUI.color = new Color(1, 1, 1, 1);
GUI.backgroundColor = new Color(0, 0, 0, 0);
GUI.contentColor = Color.white;
for ( int i = 0; i < buttons.Length; i++ )
{
//GUI.backgroundColor = buttons[i].color; //Color.blue;
GUI.contentColor = buttons[i].color; //Color.blue;
GUI.backgroundColor = buttons[i].color * 0.08f;
if ( off == 0 )
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button(buttons[i].content, GUILayout.Width(width)) )
{
CreateShape(buttons[i].name, buttons[i].classname);
}
off++;
if ( off == bstep )
{
off = 0;
EditorGUILayout.EndHorizontal();
}
}
if ( off != 0 )
EditorGUILayout.EndHorizontal();
GUI.backgroundColor = c;
GUI.color = guicol;
}
Vector2 scroll = Vector2.zero;
int toolbarInt = 0;
string[] toolbarStrings = { "Shapes", "Params" };
// Put common params in, and each shape has its sections
void OnGUI()
{
scroll = EditorGUILayout.BeginScrollView(scroll);
//name = EditorGUILayout.TextField("Name", name);
toolbarInt = GUILayout.Toolbar(toolbarInt, toolbarStrings, GUILayout.MaxWidth(150.0f));
float butwidth = 80.0f;
float width = this.position.width; // / 2.0f;
int bstep = (int)(width / butwidth);
if ( bstep == 0 )
bstep = 1;
if ( toolbarInt == 0 )
{
DoButtons(mods, (width / bstep) - 6.0f, bstep, true);
}
else
{
//showcommon = EditorGUILayout.Foldout(showcommon, "Common");
//if ( showcommon )
{
axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", axis);
stepdist = EditorGUILayout.FloatField("Step Dist", stepdist);
knotsize = EditorGUILayout.FloatField("Knot Size", knotsize);
drawknots = EditorGUILayout.Toggle("Draw Knots", drawknots);
drawhandles = EditorGUILayout.Toggle("Draw Handles", drawhandles);
col1 = EditorGUILayout.ColorField("Color 1", col1);
col2 = EditorGUILayout.ColorField("Color 2", col2);
makemesh = EditorGUILayout.Toggle("Make Mesh", makemesh);
}
}
EditorGUILayout.EndScrollView();
}
#if false
static void CreateShape(string type)
{
Vector3 pos = UnityEditor.SceneView.lastActiveSceneView.pivot;
MegaShape ms = null;
GameObject go = new GameObject(type + " Shape");
switch ( type )
{
case "Circle": ms = go.AddComponent<MegaShapeCircle>(); break;
case "Star": ms = go.AddComponent<MegaShapeStar>(); break;
case "NGon": ms = go.AddComponent<MegaShapeNGon>(); break;
case "Arc": ms = go.AddComponent<MegaShapeArc>(); break;
case "Ellipse": ms = go.AddComponent<MegaShapeEllipse>(); break;
case "Rectangle": ms = go.AddComponent<MegaShapeRectangle>(); break;
case "Helix": ms = go.AddComponent<MegaShapeHelix>(); break;
}
go.transform.position = pos;
Selection.activeObject = go;
if ( ms != null )
{
ms.axis = axis;
ms.drawHandles = drawhandles;
ms.drawKnots = drawknots;
ms.col1 = col1;
ms.col2 = col2;
ms.KnotSize = knotsize;
ms.stepdist = stepdist;
}
}
#endif
static void CreateShape(string type, System.Type classtype)
{
Vector3 pos = UnityEditor.SceneView.lastActiveSceneView.pivot;
GameObject go = new GameObject(type + " Shape");
MegaShape ms = (MegaShape)go.AddComponent(classtype);
go.transform.position = pos;
Selection.activeObject = go;
if ( ms != null )
{
ms.axis = axis;
ms.drawHandles = drawhandles;
ms.drawKnots = drawknots;
ms.col1 = col1;
ms.col2 = col2;
ms.KnotSize = knotsize;
ms.stepdist = stepdist;
ms.makeMesh = makemesh;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 6a0333c1fbd385d47b409dd884b8559b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
#if false
public class MegaShapeWizard : ScriptableWizard
{
public float range = 500;
public Color color = Color.red;
[MenuItem ("GameObject/Create Light Wizard")]
static void CreateWizard () {
ScriptableWizard.DisplayWizard<WizardCreateLight>("Create Light", "Create", "Apply");
//If you don't want to use the secondary button simply leave it out:
//ScriptableWizard.DisplayWizard<WizardCreateLight>("Create Light", "Create");
}
void OnWizardCreate () {
GameObject go = new GameObject ("New Light");
go.AddComponent("Light");
go.light.range = range;
go.light.color = color;
}
void OnWizardUpdate () {
helpString = "Please set the color of the light!";
}
// When the user pressed the "Apply" button OnWizardOtherButton is called.
void OnWizardOtherButton () {
if (Selection.activeTransform == null ||
Selection.activeTransform.light == null) return;
Selection.activeTransform.light.color = Color.red;
}
#endif
\ No newline at end of file
fileFormatVersion: 2
guid: 9f52e4a4cb80adb40831d60f64351cab
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSimpleMod))]
public class MegaSimpleEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Simple Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool Inspector()
{
MegaSimpleMod mod = (MegaSimpleMod)target;
EditorGUIUtility.LookLikeControls();
mod.a3 = EditorGUILayout.Vector3Field("A3", mod.a3);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: d33005a6858c047428d416bf55de3105
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaSimpleMod))]
public class MegaSimpleModEditor : MegaModifierEditor
{
}
fileFormatVersion: 2
guid: ba074197a8158d64aaef4d62e2945183
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSinusCurve))]
public class MegaSinusCurveEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Sinus Curve Modifier by Unity"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool Inspector()
{
MegaSinusCurve mod = (MegaSinusCurve)target;
EditorGUIUtility.LookLikeControls();
mod.scale = EditorGUILayout.FloatField("Scale", mod.scale);
mod.speed = EditorGUILayout.FloatField("Speed", mod.speed);
mod.phase = EditorGUILayout.FloatField("Phase", mod.phase);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
return false;
}
}
fileFormatVersion: 2
guid: c74ff05fbd13e9648a670f28e4aac03c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSkew))]
public class MegaSkewEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Skew Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("skew_help.png"); }
public override bool Inspector()
{
MegaSkew mod = (MegaSkew)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.dir = EditorGUILayout.FloatField("Dir", mod.dir);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2850186bc2cab03438bfe18b062ead72
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSpherify))]
public class MegaSpherifyEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Spherify Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("bend_help.png"); }
public override bool Inspector()
{
MegaSpherify mod = (MegaSpherify)target;
EditorGUIUtility.LookLikeControls();
mod.percent = EditorGUILayout.FloatField("Percent", mod.percent);
mod.FallOff = EditorGUILayout.FloatField("FallOff", mod.FallOff);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 38de8b87792f0a945a1de96cf6e54f09
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaSqueeze))]
public class MegaSqueezeEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Squeeze Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/taper_help.png"); }
public override bool Inspector()
{
MegaSqueeze mod = (MegaSqueeze)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.crv = EditorGUILayout.FloatField("Crv", mod.crv);
mod.radialamount = EditorGUILayout.FloatField("Radial Amount", mod.radialamount);
mod.radialcrv = EditorGUILayout.FloatField("Radial Crv", mod.radialcrv);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 6168ce9a80183464cb379ad396e93172
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaStretch))]
public class MegaStretchEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Stretch Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/stretch_help.png"); }
public override bool Inspector()
{
MegaStretch mod = (MegaStretch)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.amplify = EditorGUILayout.FloatField("Amplify", mod.amplify);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 9b115fb0d12a7604792a124229be297b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaTaper))]
public class MegaTaperEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Taper Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/taper_help.png"); }
public override bool Inspector()
{
MegaTaper mod = (MegaTaper)target;
EditorGUIUtility.LookLikeControls();
mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
mod.crv = EditorGUILayout.FloatField("Crv", mod.crv);
mod.dir = EditorGUILayout.FloatField("Dir", mod.dir);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.EAxis = (MegaEffectAxis)EditorGUILayout.EnumPopup("EAxis", mod.EAxis);
mod.sym = EditorGUILayout.Toggle("Sym", mod.sym);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 283aad75df2993d4ca33f79b79d9f6c9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaTwist))]
public class MegaTwistEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Twist Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/twist_help.png"); }
public override bool Inspector()
{
MegaTwist mod = (MegaTwist)target;
EditorGUIUtility.LookLikeControls();
mod.angle = EditorGUILayout.FloatField("Angle", mod.angle);
mod.Bias = EditorGUILayout.FloatField("Bias", mod.Bias);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.doRegion = EditorGUILayout.Toggle("Do Region", mod.doRegion);
mod.from = EditorGUILayout.FloatField("From", mod.from);
mod.to = EditorGUILayout.FloatField("To", mod.to);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 6776504b437e94b47ab40941baaa0328
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaTwistWarp))]
public class MegaTwistWarpEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
}
}
fileFormatVersion: 2
guid: 3b586e4f17769d64e87c6d08beaae04c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaUVAdjust))]
public class MegaUVAdjustEditor : MegaModifierEditor
{
public override bool Inspector()
{
MegaUVAdjust mod = (MegaUVAdjust)target;
EditorGUIUtility.LookLikeControls();
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.rotspeed = EditorGUILayout.FloatField("Rot Speed", mod.rotspeed);
mod.spiralspeed = EditorGUILayout.FloatField("Spiral Speed", mod.spiralspeed);
mod.speed = EditorGUILayout.Vector3Field("Speed", mod.speed);
mod.spiral = EditorGUILayout.FloatField("Spiral", mod.spiral);
mod.spirallim = EditorGUILayout.FloatField("Spiral Lim", mod.spirallim);
return false;
}
public override void DrawSceneGUI()
{
MegaModifier mod = (MegaModifier)target;
if ( mod.ModEnabled && mod.DisplayGizmo && MegaModifiers.GlobalDisplay )
{
MegaModifiers context = mod.GetComponent<MegaModifiers>();
if ( context != null && context.Enabled && context.DrawGizmos )
{
float a = mod.gizCol1.a;
Color col = Color.white;
Quaternion rot = mod.transform.localRotation;
Handles.matrix = Matrix4x4.identity;
if ( mod.Offset != Vector3.zero )
{
Vector3 pos = mod.transform.localToWorldMatrix.MultiplyPoint(Vector3.Scale(-mod.gizmoPos - mod.Offset, mod.bbox.Size()));
Handles.Label(pos, mod.ModName() + " Pivot\n" + mod.Offset.ToString("0.000"));
col = Color.blue;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(180.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.green;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(90.0f, 0.0f, 0.0f), mod.GizmoSize());
col = Color.red;
col.a = a;
Handles.color = col;
Handles.ArrowCap(0, pos, rot * Quaternion.Euler(0.0f, -90.0f, 0.0f), mod.GizmoSize());
}
Handles.matrix = Matrix4x4.identity;
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: ed638726bcf1e4449a1c19b986fb660d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaUVTiles))]
public class MegaUVTilesEditor : MegaModifierEditor
{
public override bool Inspector()
{
MegaUVTiles mod = (MegaUVTiles)target;
EditorGUIUtility.LookLikeControls();
mod.Frame = EditorGUILayout.IntField("Frame", mod.Frame);
mod.TileWidth = EditorGUILayout.IntField("Tile Width", mod.TileWidth);
mod.TileHeight = EditorGUILayout.IntField("Tile Height", mod.TileHeight);
mod.off = EditorGUILayout.Vector2Field("Off", mod.off);
mod.scale = EditorGUILayout.Vector2Field("Scale", mod.scale);
mod.Animate = EditorGUILayout.Toggle("Animate", mod.Animate);
mod.EndFrame = EditorGUILayout.IntField("End Frame", mod.EndFrame);
mod.fps = EditorGUILayout.FloatField("Fps", mod.fps);
mod.AnimTime = EditorGUILayout.FloatField("Anim Time", mod.AnimTime);
mod.flipx = EditorGUILayout.Toggle("Flip X", mod.flipx);
mod.flipy = EditorGUILayout.Toggle("Flip Y", mod.flipy);
mod.loopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", mod.loopMode);
return false;
}
}
fileFormatVersion: 2
guid: edb5b9be3c7ce5a4a98da3c94d6d89e4
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaVertColSelect))]
public class MegaVertColSelectEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Vertex Color Select Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool DisplayCommon() { return false; }
public override bool Inspector()
{
MegaVertColSelect mod = (MegaVertColSelect)target;
EditorGUIUtility.LookLikeControls();
mod.ModEnabled = EditorGUILayout.Toggle("Enabled", mod.ModEnabled);
mod.weight = EditorGUILayout.FloatField("Weight", mod.weight);
mod.threshold = EditorGUILayout.Slider("Threshold", mod.threshold, 0.0f, 1.0f);
mod.channel = (MegaChannel)EditorGUILayout.EnumPopup("Channel", mod.channel);
mod.displayWeights = EditorGUILayout.Toggle("Show Weights", mod.displayWeights);
//mod.gizCol = EditorGUILayout.ColorField("Gizmo Col", mod.gizCol);
mod.gizSize = EditorGUILayout.FloatField("Gizmo Size", mod.gizSize);
if ( GUI.changed )
{
mod.update = true;
}
return false;
}
public override void DrawSceneGUI()
{
MegaVertColSelect mod = (MegaVertColSelect)target;
MegaModifiers mc = mod.gameObject.GetComponent<MegaModifiers>();
float[] sel = mod.GetSel();
if ( mc != null && sel != null )
{
Color col = Color.black;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = Matrix4x4.identity;
if ( mod.displayWeights )
{
for ( int i = 0; i < sel.Length; i++ )
{
float w = sel[i];
if ( w > 0.5f )
col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f);
else
col = Color.Lerp(Color.blue, Color.green, w * 2.0f);
Handles.color = col;
Vector3 p = tm.MultiplyPoint(mc.sverts[i]);
if ( w > 0.001f )
Handles.DotCap(i, p, Quaternion.identity, mod.gizSize);
}
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: d51ceaff703d6094596fe0288af5da78
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaVertNoise))]
public class MegaVertNoiseEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Vertical Noise Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/noise_help.png"); }
public override bool Inspector()
{
MegaVertNoise mod = (MegaVertNoise)target;
EditorGUIUtility.LookLikeControls();
mod.Scale = EditorGUILayout.FloatField("Scale", mod.Scale);
mod.Freq = EditorGUILayout.FloatField("Freq", mod.Freq);
mod.Phase = EditorGUILayout.FloatField("Phase", mod.Phase);
mod.decay = EditorGUILayout.FloatField("Decay", mod.decay);
mod.Strength = EditorGUILayout.FloatField("Strength", mod.Strength);
mod.Animate = EditorGUILayout.Toggle("Animate", mod.Animate);
mod.Fractal = EditorGUILayout.Toggle("Fractal", mod.Fractal);
if ( mod.Fractal )
{
mod.Iterations = EditorGUILayout.FloatField("Iterations", mod.Iterations);
mod.Rough = EditorGUILayout.FloatField("Rough", mod.Rough);
}
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: b49c2c1e1b6c0bb4887c927f99531a47
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Collections;
// Support anim uvs here as well
[CustomEditor(typeof(MegaVertexAnim))]
public class MegaVertexAnimEditor : MegaModifierEditor //Editor
{
//bool showmodparams = true;
static string lastpath = " ";
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
MegaModifiers mods;
List<MegaAnimatedVert> Verts = new List<MegaAnimatedVert>();
void LoadVertexAnim()
{
MegaVertexAnim am = (MegaVertexAnim)target;
mods = am.gameObject.GetComponent<MegaModifiers>();
string filename = EditorUtility.OpenFilePanel("Vertex Animation File", lastpath, "mpc");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
Verts.Clear();
ParseFile(filename, AnimatedMeshCallback);
am.Verts = Verts.ToArray();
BitArray animated = new BitArray(mods.verts.Length);
int count = 0;
for ( int i = 0; i < Verts.Count; i++ )
{
for ( int v = 0; v < Verts[i].indices.Length; v++ )
{
if ( !animated[Verts[i].indices[v]] )
{
animated[Verts[i].indices[v]] = true;
count++;
}
}
}
am.NoAnim = new int[mods.verts.Length - count];
int index = 0;
for ( int i = 0; i < animated.Count; i++ )
{
if ( !animated[i] )
am.NoAnim[index++] = i;
}
am.maxtime = 0.0f;
for ( int i = 0; i < Verts.Count; i++ )
{
float t = Verts[i].con.Times[Verts[i].con.Times.Length - 1];
if ( t > am.maxtime )
am.maxtime = t;
}
}
void AnimatedMeshCallback(string classname, BinaryReader br)
{
switch ( classname )
{
case "AnimMesh": LoadAnimMesh(br); break;
}
}
public void LoadAnimMesh(BinaryReader br)
{
MegaParse.Parse(br, ParseAnimMesh);
}
int[] FindVerts(Vector3 p)
{
List<int> indices = new List<int>();
for ( int i = 0; i < mods.verts.Length; i++ )
{
float dist = Vector3.Distance(p, mods.verts[i]);
if ( dist < 0.0001f ) //mods.verts[i].Equals(p) )
indices.Add(i);
}
return indices.ToArray();
}
Vector3 Extents(Vector3[] verts, out Vector3 min, out Vector3 max)
{
Vector3 extent = Vector3.zero;
min = Vector3.zero;
max = Vector3.zero;
if ( verts != null && verts.Length > 0 )
{
min = verts[0];
max = verts[0];
for ( int i = 1; i < verts.Length; i++ )
{
if ( verts[i].x < min.x ) min.x = verts[i].x;
if ( verts[i].y < min.y ) min.y = verts[i].y;
if ( verts[i].z < min.z ) min.z = verts[i].z;
if ( verts[i].x > max.x ) max.x = verts[i].x;
if ( verts[i].y > max.y ) max.y = verts[i].y;
if ( verts[i].z > max.z ) max.z = verts[i].z;
}
extent = max - min;
}
return extent;
}
MegaAnimatedVert currentVert;
float scl = 1.0f;
public bool ParseAnimMesh(BinaryReader br, string id)
{
switch ( id )
{
case "Size":
Vector3 sz = MegaParse.ReadP3(br);
Vector3 min1,max1;
Vector3 ex1 = Extents(mods.verts, out min1, out max1);
int largest = 0;
if ( sz.x > sz.y )
{
if ( sz.x > sz.z )
largest = 0;
else
largest = 2;
}
else
{
if ( sz.y > sz.z )
largest = 1;
else
largest = 2;
}
scl = ex1[largest] / sz[largest];
break;
case "V":
Vector3 p = MegaParse.ReadP3(br) * scl;
// Find all matching verts
currentVert = new MegaAnimatedVert();
currentVert.startVert = p;
currentVert.indices = FindVerts(p);
if ( currentVert.indices == null )
Debug.Log("Error! No match found");
Verts.Add(currentVert);
break;
case "Anim":
//currentVert.con = MegaBezVector3KeyControl.LoadBezVector3KeyControl(br);
currentVert.con = MegaParseBezVector3Control.LoadBezVector3KeyControl(br);
currentVert.con.Scale(scl);
break;
default: return false;
}
return true;
}
public void ParseFile(string assetpath, ParseClassCallbackType cb)
{
FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
bool processing = true;
while ( processing )
{
string classname = MegaParse.ReadString(br);
if ( classname == "Done" )
break;
int chunkoff = br.ReadInt32();
long fpos = fs.Position;
cb(classname, br);
fs.Position = fpos + chunkoff;
}
br.Close();
}
public override void OnInspectorGUI()
{
MegaVertexAnim am = (MegaVertexAnim)target;
if ( GUILayout.Button("Import Vertex Anim File") )
{
LoadVertexAnim();
EditorUtility.SetDirty(target);
}
// Basic mod stuff
showmodparams = EditorGUILayout.Foldout(showmodparams, "Modifier Common Params");
if ( showmodparams )
{
CommonModParamsBasic(am);
#if false
am.ModEnabled = EditorGUILayout.Toggle("Mod Enabled", am.ModEnabled);
am.DisplayGizmo = EditorGUILayout.Toggle("Display Gizmo", am.DisplayGizmo);
am.Order = EditorGUILayout.IntField("Order", am.Order);
am.gizCol1 = EditorGUILayout.ColorField("Giz Col 1", am.gizCol1);
am.gizCol2 = EditorGUILayout.ColorField("Giz Col 2", am.gizCol2);
#endif
}
am.time = EditorGUILayout.FloatField("Time", am.time);
am.maxtime = EditorGUILayout.FloatField("Loop Time", am.maxtime);
am.animated = EditorGUILayout.Toggle("Animated", am.animated);
am.speed = EditorGUILayout.FloatField("Speed", am.speed);
am.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", am.LoopMode);
am.blendMode = (MegaBlendAnimMode)EditorGUILayout.EnumPopup("Blend Mode", am.blendMode);
if ( am.blendMode == MegaBlendAnimMode.Additive )
am.weight = EditorGUILayout.FloatField("Weight", am.weight);
if ( GUI.changed )
EditorUtility.SetDirty(target);
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: f8e1cde73b31dcc4eb049cf754f56148
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaVolSelect))]
public class MegaVolSelectEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Vol Select Modifier by Chris West"; }
//public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/bend_help.png"); }
public override bool DisplayCommon() { return false; }
public override bool Inspector()
{
MegaVolSelect mod = (MegaVolSelect)target;
EditorGUIUtility.LookLikeControls();
mod.ModEnabled = EditorGUILayout.Toggle("Enabled", mod.ModEnabled);
mod.radius = EditorGUILayout.FloatField("Radius", mod.radius);
mod.falloff = EditorGUILayout.FloatField("Falloff", mod.falloff);
mod.origin = EditorGUILayout.Vector3Field("Origin", mod.origin);
mod.useCurrentVerts = EditorGUILayout.Toggle("Use Stack Verts", mod.useCurrentVerts);
mod.displayWeights = EditorGUILayout.Toggle("Show Weights", mod.displayWeights);
mod.gizCol = EditorGUILayout.ColorField("Gizmo Col", mod.gizCol);
mod.gizSize = EditorGUILayout.FloatField("Gizmo Size", mod.gizSize);
return false;
}
// option to use base verts or current stack verts for distance calc
// flag to display weights
// size of weights and color of gizmo
public override void DrawSceneGUI()
{
MegaVolSelect mod = (MegaVolSelect)target;
MegaModifiers mc = mod.gameObject.GetComponent<MegaModifiers>();
float[] sel = mod.GetSel();
if ( mc != null && sel != null )
{
Color col = Color.black;
Matrix4x4 tm = mod.gameObject.transform.localToWorldMatrix;
Handles.matrix = Matrix4x4.identity;
if ( mod.displayWeights )
{
for ( int i = 0; i < sel.Length; i++ )
{
float w = sel[i];
if ( w > 0.5f )
col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f);
else
col = Color.Lerp(Color.blue, Color.green, w * 2.0f);
Handles.color = col;
Vector3 p = tm.MultiplyPoint(mc.sverts[i]);
if ( w > 0.001f )
Handles.DotCap(i, p, Quaternion.identity, mod.gizSize);
}
}
Handles.color = mod.gizCol; //new Color(0.5f, 0.5f, 0.5f, 0.2f);
//Handles.DrawWireDisc(0, tm.MultiplyPoint(mod.origin), Quaternion.identity, mod.radius);
//Handles.DrawWireDisc(tm.MultiplyPoint(mod.origin), Vector3.up, mod.radius);
//Handles.DrawWireDisc(tm.MultiplyPoint(mod.origin), Vector3.right, mod.radius);
//Handles.DrawWireDisc(tm.MultiplyPoint(mod.origin), Vector3.forward, mod.radius);
Handles.SphereCap(0, tm.MultiplyPoint(mod.origin), Quaternion.identity, mod.radius * 2.0f);
Handles.matrix = tm;
mod.origin = Handles.PositionHandle(mod.origin, Quaternion.identity);
Handles.matrix = Matrix4x4.identity;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: c530e550e64fa134681e5fecde7a1e8d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
[CustomEditor(typeof(MegaWarpBind))]
public class MegaWarpBindEditor : MegaModifierEditor
{
}
fileFormatVersion: 2
guid: 625472bc7da56cd448836d4c95fd699a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaWarp))]
public class MegaWarpEditor : Editor
{
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable)]
static void RenderGizmo(MegaWarp warp, GizmoType gizmoType)
{
if ( MegaModifiers.GlobalDisplay && warp.DisplayGizmo )
{
if ( (gizmoType & GizmoType.NotInSelectionHierarchy) != 0 )
{
if ( (gizmoType & GizmoType.Active) != 0 )
{
if ( warp.Enabled )
warp.DrawGizmo(Color.white);
else
warp.DrawGizmo(new Color(1.0f, 1.0f, 0.0f, 0.75f));
}
else
{
if ( warp.Enabled )
warp.DrawGizmo(new Color(0.0f, 1.0f, 0.0f, 0.5f));
else
warp.DrawGizmo(new Color(1.0f, 0.0f, 0.0f, 0.25f));
}
}
Gizmos.DrawIcon(warp.transform.position, warp.GetIcon());
}
}
//[DrawGizmo(GizmoType.SelectedOrChild)]
//static void RenderGizmoSelected(Warp warp, GizmoType gizmoType)
//{
//if ( Modifiers.GlobalDisplay && warp.DisplayGizmo )
//{
//if ( warp.Enabled )
//warp.DrawGizmo(Color.white);
//else
//warp.DrawGizmo(new Color(1.0f, 1.0f, 0.0f, 0.75f));
//Gizmos.DrawIcon(warp.transform.position, warp.GetIcon());
//}
//}
}
fileFormatVersion: 2
guid: a793a15a5210d3149b6a9fa05cc172b6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MegaWave))]
public class MegaWaveEditor : MegaModifierEditor
{
public override string GetHelpString() { return "Wave Modifier by Chris West"; }
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers/wave_help.png"); }
public override bool Inspector()
{
MegaWave mod = (MegaWave)target;
EditorGUIUtility.LookLikeControls();
mod.amp = EditorGUILayout.FloatField("Amp", mod.amp);
mod.amp2 = EditorGUILayout.FloatField("Amp 2", mod.amp2);
mod.wave = EditorGUILayout.FloatField("Wave", mod.wave);
mod.phase = EditorGUILayout.FloatField("Phase", mod.phase);
mod.Decay = EditorGUILayout.FloatField("Decay", mod.Decay);
mod.dir = EditorGUILayout.FloatField("Dir", mod.dir);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.Speed = EditorGUILayout.FloatField("Speed", mod.Speed);
mod.divs = EditorGUILayout.IntField("Divs", mod.divs);
mod.numSegs = EditorGUILayout.IntField("Num Segs", mod.numSegs);
mod.numSides = EditorGUILayout.IntField("Num Sides", mod.numSides);
return false;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: b296d8b6001f07142bf4c94d065bbc5a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MegaWorldPathDeform))]
public class MegaWorldPathDeformEditor : MegaModifierEditor
{
//void OnSceneGUI()
//{
//PathDeform pd = (PathDeform)target;
//Display(pd);
//}
public override bool Inspector()
{
MegaWorldPathDeform mod = (MegaWorldPathDeform)target;
EditorGUIUtility.LookLikeControls();
mod.percent = EditorGUILayout.FloatField("Percent", mod.percent);
mod.stretch = EditorGUILayout.FloatField("Stretch", mod.stretch);
mod.twist = EditorGUILayout.FloatField("Twist", mod.twist);
mod.rotate = EditorGUILayout.FloatField("Rotate", mod.rotate);
mod.axis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
mod.flip = EditorGUILayout.Toggle("Flip", mod.flip);
mod.path = (MegaShape)EditorGUILayout.ObjectField("Path", mod.path, typeof(MegaShape), true);
mod.animate = EditorGUILayout.Toggle("Animate", mod.animate);
mod.speed = EditorGUILayout.FloatField("Speed", mod.speed);
mod.tangent = EditorGUILayout.FloatField("Tangent", mod.tangent);
mod.UseTwistCurve = EditorGUILayout.Toggle("Use Twist Curve", mod.UseTwistCurve);
mod.twistCurve = EditorGUILayout.CurveField("Twist Curve", mod.twistCurve);
mod.UseStretchCurve = EditorGUILayout.Toggle("Use Stretch Curve", mod.UseStretchCurve);
mod.stretchCurve = EditorGUILayout.CurveField("Stretch Curve", mod.stretchCurve);
return false;
}
#if false
void Display(PathDeform pd)
{
if ( pd.path != null )
{
Matrix4x4 mat = pd.transform.localToWorldMatrix * pd.path.transform.localToWorldMatrix * pd.mat;
for ( int s = 0; s < pd.path.splines.Count; s++ )
{
float ldist = pd.path.stepdist;
if ( ldist < 0.1f )
ldist = 0.1f;
float ds = pd.path.splines[s].length / (pd.path.splines[s].length / ldist);
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref lk);
for ( float dist = ds; dist < pd.path.splines[s].length; dist += ds )
{
float alpha = dist / pd.path.splines[s].length;
Vector3 pos = pd.path.splines[s].Interpolate(alpha, pd.path.normalizedInterp, ref k);
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pd.path.splines[s].knots[lk].p));
first = pd.path.splines[s].knots[lk].p;
}
}
lk = k;
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
c++;
first = pos;
}
if ( pd.path.splines[s].closed )
{
Vector3 pos = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref k);
Handles.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
}
}
}
}
#endif
}
\ No newline at end of file
fileFormatVersion: 2
guid: fe16145e11caabc458933faf8716cb7e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(GlyphInfo))]
public class GlyphInfoDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_id = property.FindPropertyRelative("id");
SerializedProperty prop_x = property.FindPropertyRelative("x");
SerializedProperty prop_y = property.FindPropertyRelative("y");
SerializedProperty prop_width = property.FindPropertyRelative("width");
SerializedProperty prop_height = property.FindPropertyRelative("height");
SerializedProperty prop_xOffset = property.FindPropertyRelative("xOffset");
SerializedProperty prop_yOffset = property.FindPropertyRelative("yOffset");
SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance");
// We get Rect since a valid position may not be provided by the caller.
Rect rect = GUILayoutUtility.GetRect(position.width, 48);
rect.y -= 15;
GUI.enabled = false;
EditorGUIUtility.LookLikeControls(40, 45);
EditorGUI.IntField(new Rect(rect.x + 5f, rect.y, 80f, 18), new GUIContent("Ascii:"), prop_id.intValue);
EditorGUI.LabelField(new Rect(rect.x + 100f, rect.y, 80, 18), "Char: [ " + (char)prop_id.intValue + " ]");
EditorGUIUtility.labelWidth = 20f;
EditorGUIUtility.fieldWidth = 10f;
GUI.enabled = true;
float width = (rect.width - 5f) / 4;
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:"));
GUI.enabled = true;
EditorGUI.LabelField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), "Offset Values:");
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("X:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("Y:"));
GUI.enabled = true;
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("Advance:"));
}
}
}
fileFormatVersion: 2
guid: 02e0e69a1d7086f4492ba6ebadff6392
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(KerningPair))]
public class KerningPairDrawer : PropertyDrawer
{
private bool isEditingEnabled = false;
private string char_left;
private string char_right;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_ascii_left = property.FindPropertyRelative("AscII_Left");
SerializedProperty prop_ascii_right = property.FindPropertyRelative("AscII_Right");
SerializedProperty prop_xOffset = property.FindPropertyRelative("XadvanceOffset");
position.yMin += 4;
position.yMax += 4;
position.height -= 2;
float width = position.width / 3;
float padding = 5.0f;
Rect ascii_FieldPos;
Rect char_FieldPos;
isEditingEnabled = label == GUIContent.none ? false : true;
GUILayout.BeginHorizontal();
GUI.enabled = isEditingEnabled;
// Left Character
char_FieldPos = new Rect(position.x, position.y, 25f, position.height);
char_left = EditorGUI.TextArea(char_FieldPos, "" + (char)prop_ascii_left.intValue);
if (GUI.changed && char_left != "")
{
GUI.changed = false;
prop_ascii_left.intValue = char_left[0];
}
ascii_FieldPos = new Rect(position.x + char_FieldPos.width + padding, position.y, width - char_FieldPos.width - 10f, position.height);
EditorGUI.PropertyField(ascii_FieldPos, prop_ascii_left, GUIContent.none);
// Right Character
char_FieldPos = new Rect(position.x + (width * 1), position.y, 25f, position.height);
char_right = EditorGUI.TextArea(char_FieldPos, "" + (char)prop_ascii_right.intValue);
if (GUI.changed && char_right != "")
{
GUI.changed = false;
prop_ascii_right.intValue = char_right[0];
}
ascii_FieldPos = new Rect(position.x + (width * 1) + char_FieldPos.width + padding, position.y, width - char_FieldPos.width - 10f, position.height);
EditorGUI.PropertyField(ascii_FieldPos, prop_ascii_right, GUIContent.none);
// Kerning xOffset
GUI.enabled = true;
ascii_FieldPos = new Rect(position.x + (width * 2), position.y, width, position.height);
EditorGUIUtility.LookLikeControls(45, 50);
EditorGUI.PropertyField(ascii_FieldPos, prop_xOffset, new GUIContent("Offset"));
GUILayout.EndHorizontal();
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 1cd4a25f3285e1e4cbfdde3d8b82a97e
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(SpriteInfo))]
public class SpriteInfoDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//SerializedProperty prop_fileID = property.FindPropertyRelative("fileID");
SerializedProperty prop_id = property.FindPropertyRelative("id");
SerializedProperty prop_name = property.FindPropertyRelative("name");
SerializedProperty prop_x = property.FindPropertyRelative("x");
SerializedProperty prop_y = property.FindPropertyRelative("y");
SerializedProperty prop_width = property.FindPropertyRelative("width");
SerializedProperty prop_height = property.FindPropertyRelative("height");
SerializedProperty prop_xOffset = property.FindPropertyRelative("xOffset");
SerializedProperty prop_yOffset = property.FindPropertyRelative("yOffset");
SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance");
SerializedProperty prop_scale = property.FindPropertyRelative("scale");
//SerializedProperty prop_sprite = property.FindPropertyRelative("sprite");
// Get a reference to the sprite texture
Texture tex = (property.serializedObject.targetObject as SpriteAsset).spriteSheet;
Vector2 spriteSize = new Vector2(65, 65);
if (prop_width.floatValue >= prop_height.floatValue)
{
spriteSize.y = prop_height.floatValue * spriteSize.x / prop_width.floatValue;
position.y += (spriteSize.x - spriteSize.y) / 2;
}
else
{
spriteSize.x = prop_width.floatValue * spriteSize.y / prop_height.floatValue;
position.x += (spriteSize.y - spriteSize.x) / 2;
}
// Compute the normalized texture coordinates
Rect texCoords = new Rect(prop_x.floatValue / tex.width, prop_y.floatValue / tex.height, prop_width.floatValue / tex.width, prop_height.floatValue / tex.height);
GUI.DrawTextureWithTexCoords(new Rect(position.x + 5, position.y, spriteSize.x, spriteSize.y), tex, texCoords, true);
// We get Rect since a valid position may not be provided by the caller.
Rect rect = GUILayoutUtility.GetRect(position.width, 49);
rect.x += 70;
rect.y -= 15;
EditorGUIUtility.LookLikeControls(40, 45);
EditorGUI.BeginChangeCheck();
EditorGUI.LabelField(new Rect(rect.x + 5f, rect.y, 50f, 18), new GUIContent("ID: " + prop_id.intValue));
EditorGUI.LabelField(new Rect(rect.x + 60f, rect.y, 200f, 18), new GUIContent("Name: " + prop_name.stringValue));
//EditorGUI.LabelField(new Rect(rect.x + 280f, rect.y, 150f, 18), new GUIContent("File ID: " + prop_fileID.intValue));
if (EditorGUI.EndChangeCheck())
{
//string filepath = AssetDatabase.GetAssetPath(prop_sprite.objectReferenceValue);
//TextureImporter texImporter = AssetImporter.GetAtPath(filepath) as TextureImporter;
//texImporter
//AssetDatabase.RenameAsset()
}
EditorGUIUtility.labelWidth = 30f;
EditorGUIUtility.fieldWidth = 10f;
GUI.enabled = false;
float width = (rect.width - 75f) / 4;
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:"));
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("OX:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("OY:"));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("Adv."));
EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_scale, new GUIContent("SF."));
if (EditorGUI.EndChangeCheck())
{
//Sprite sprite = prop_sprite.objectReferenceValue as Sprite;
//sprite = Sprite.Create(sprite.texture, sprite.rect, new Vector2(0.1f, 0.8f));
//prop_sprite.objectReferenceValue = sprite;
//Debug.Log(sprite.bounds);
}
}
}
}
fileFormatVersion: 2
guid: 3d015705b1c6c50408a08e3094b37951
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
public static class TMP_UIStyleManager
{
//private static bool m_isInitialized;
public static GUISkin TMP_GUISkin;
public static GUIStyle Label;
public static GUIStyle Group_Label;
public static GUIStyle Group_Label_Left;
public static GUIStyle TextAreaBoxEditor;
public static GUIStyle TextAreaBoxWindow;
public static GUIStyle TextureAreaBox;
public static GUIStyle Section_Label;
public static GUIStyle SquareAreaBox85G;
// Alignment Button Textures
public static Texture2D alignLeft;
public static Texture2D alignCenter;
public static Texture2D alignRight;
public static Texture2D alignJustified;
public static Texture2D alignTop;
public static Texture2D alignMiddle;
public static Texture2D alignBottom;
public static Texture2D alignBaseline;
public static Texture2D alignMidline;
public static Texture2D progressTexture;
public static GUIContent[] alignContent_A;
public static GUIContent[] alignContent_B;
public static void GetUIStyles()
{
if (TMP_GUISkin != null)
return;
// Find to location of the TextMesh Pro Asset Folder (as users may have moved it)
string tmproAssetFolderPath = TMPro_EditorUtility.GetAssetLocation();
if (EditorGUIUtility.isProSkin)
{
TMP_GUISkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_DarkSkin.guiskin", typeof(GUISkin)) as GUISkin;
alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignLeft.psd", typeof(Texture2D)) as Texture2D;
alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignCenter.psd", typeof(Texture2D)) as Texture2D;
alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignRight.psd", typeof(Texture2D)) as Texture2D;
alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignJustified.psd", typeof(Texture2D)) as Texture2D;
alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignTop.psd", typeof(Texture2D)) as Texture2D;
alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignMiddle.psd", typeof(Texture2D)) as Texture2D;
alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignBottom.psd", typeof(Texture2D)) as Texture2D;
alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignBaseLine.psd", typeof(Texture2D)) as Texture2D;
alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignMidLine.psd", typeof(Texture2D)) as Texture2D;
progressTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/Progress Bar.psd", typeof(Texture2D)) as Texture2D;
}
else
{
TMP_GUISkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_LightSkin.guiskin", typeof(GUISkin)) as GUISkin;
alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignLeft_Light.psd", typeof(Texture2D)) as Texture2D;
alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignCenter_Light.psd", typeof(Texture2D)) as Texture2D;
alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignRight_Light.psd", typeof(Texture2D)) as Texture2D;
alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignJustified_Light.psd", typeof(Texture2D)) as Texture2D;
alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignTop_Light.psd", typeof(Texture2D)) as Texture2D;
alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignMiddle_Light.psd", typeof(Texture2D)) as Texture2D;
alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignBottom_Light.psd", typeof(Texture2D)) as Texture2D;
alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignBaseLine_Light.psd", typeof(Texture2D)) as Texture2D;
alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/btn_AlignMidLine_Light.psd", typeof(Texture2D)) as Texture2D;
progressTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/Textures/Progress Bar (Light).psd", typeof(Texture2D)) as Texture2D;
}
if (TMP_GUISkin != null)
{
Label = TMP_GUISkin.FindStyle("Label");
Section_Label = TMP_GUISkin.FindStyle("Section Label");
Group_Label = TMP_GUISkin.FindStyle("Group Label");
Group_Label_Left = TMP_GUISkin.FindStyle("Group Label - Left Half");
TextAreaBoxEditor = TMP_GUISkin.FindStyle("Text Area Box (Editor)");
TextAreaBoxWindow = TMP_GUISkin.FindStyle("Text Area Box (Window)");
TextureAreaBox = TMP_GUISkin.FindStyle("Texture Area Box");
SquareAreaBox85G = TMP_GUISkin.FindStyle("Square Area Box (85 Grey)");
alignContent_A = new GUIContent[] {
new GUIContent(alignLeft, "Left"),
new GUIContent(alignCenter, "Center"),
new GUIContent(alignRight, "Right"),
new GUIContent(alignJustified, "Justified") };
alignContent_B = new GUIContent[] {
new GUIContent(alignTop, "Top"),
new GUIContent(alignMiddle, "Middle"),
new GUIContent(alignBottom, "Bottom"),
new GUIContent(alignBaseline, "Baseline"),
new GUIContent(alignMidline, "Midline") };
}
//m_isInitialized = true;
}
}
}
fileFormatVersion: 2
guid: a58a71284970117429add3889cc994a9
timeCreated: 1480605657
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
namespace TMPro.EditorUtilities
{
public class TMPro_ContextMenus : MaterialEditor
{
private static Material m_copiedProperties;
private static Material m_copiedAtlasProperties;
// Add a Context Menu to allow easy duplication of the Material.
//[MenuItem("CONTEXT/MaterialComponent/Duplicate Material", false)]
[MenuItem("CONTEXT/Material/Duplicate Material", false)]
static void DuplicateMaterial(MenuCommand command)
{
// Get the type of text object
// If material is not a base material, we get material leaks...
Material source_Mat = (Material)command.context;
if (!EditorUtility.IsPersistent(source_Mat))
{
Debug.LogWarning("Material is an instance and cannot be converted into a permanent asset.");
return;
}
string assetPath = AssetDatabase.GetAssetPath(source_Mat).Split('.')[0];
Material duplicate = new Material(source_Mat);
// Need to manually copy the shader keywords
duplicate.shaderKeywords = source_Mat.shaderKeywords;
AssetDatabase.CreateAsset(duplicate, AssetDatabase.GenerateUniqueAssetPath(assetPath + ".mat"));
// Assign duplicate Material to selected object (if one is)
if (Selection.activeGameObject != null)
{
TextMeshPro textObject = Selection.activeGameObject.GetComponent<TextMeshPro>();
if (textObject != null)
textObject.fontSharedMaterial = duplicate;
else
{
#if UNITY_4_6 || UNITY_5
TextMeshProUGUI textObjectUGUI = Selection.activeGameObject.GetComponent<TextMeshProUGUI>();
textObjectUGUI.fontSharedMaterial = duplicate;
// Need to detect & assign base material.
#endif
}
}
}
//[MenuItem("CONTEXT/MaterialComponent/Copy Material Properties", false)]
[MenuItem("CONTEXT/Material/Copy Material Properties", false)]
static void CopyMaterialProperties(MenuCommand command)
{
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
#if UNITY_4_6 || UNITY_5
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
#endif
}
m_copiedProperties = new Material(mat);
m_copiedProperties.shaderKeywords = mat.shaderKeywords;
m_copiedProperties.hideFlags = HideFlags.DontSave;
}
// PASTE MATERIAL
//[MenuItem("CONTEXT/MaterialComponent/Paste Material Properties", false)]
[MenuItem("CONTEXT/Material/Paste Material Properties", false)]
static void PasteMaterialProperties(MenuCommand command)
{
if (m_copiedProperties == null)
{
Debug.LogWarning("No Material Properties to Paste. Use Copy Material Properties first.");
return;
}
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
#if UNITY_4_6 || UNITY_5
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
#endif
}
Undo.RecordObject(mat, "Paste Material");
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
if (mat.HasProperty(ShaderUtilities.ID_GradientScale))
{
// Preserve unique SDF properties from destination material.
m_copiedProperties.SetTexture(ShaderUtilities.ID_MainTex, mat.GetTexture(ShaderUtilities.ID_MainTex));
m_copiedProperties.SetFloat(ShaderUtilities.ID_GradientScale, mat.GetFloat(ShaderUtilities.ID_GradientScale));
m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureWidth, mat.GetFloat(ShaderUtilities.ID_TextureWidth));
m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureHeight, mat.GetFloat(ShaderUtilities.ID_TextureHeight));
}
EditorShaderUtilities.CopyMaterialProperties(m_copiedProperties, mat);
// Copy ShaderKeywords from one material to the other.
mat.shaderKeywords = m_copiedProperties.shaderKeywords;
// Let TextMeshPro Objects that this mat has changed.
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat);
}
// Enable Resetting of Material properties without losing unique properties of the font atlas.
//[MenuItem("CONTEXT/MaterialComponent/Reset", false, 2100)]
[MenuItem("CONTEXT/Material/Reset", false, 2100)]
static void ResetSettings(MenuCommand command)
{
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
#if UNITY_4_6 || UNITY_5
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
#endif
}
//Material mat = (Material)command.context;
Undo.RecordObject(mat, "Reset Material");
Material tmp_mat = new Material(mat.shader);
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
if (mat.HasProperty(ShaderUtilities.ID_GradientScale))
{
// Copy unique properties of the SDF Material over to the temp material.
tmp_mat.SetTexture(ShaderUtilities.ID_MainTex, mat.GetTexture(ShaderUtilities.ID_MainTex));
tmp_mat.SetFloat(ShaderUtilities.ID_GradientScale, mat.GetFloat(ShaderUtilities.ID_GradientScale));
tmp_mat.SetFloat(ShaderUtilities.ID_TextureWidth, mat.GetFloat(ShaderUtilities.ID_TextureWidth));
tmp_mat.SetFloat(ShaderUtilities.ID_TextureHeight, mat.GetFloat(ShaderUtilities.ID_TextureHeight));
tmp_mat.SetFloat(ShaderUtilities.ID_StencilID, mat.GetFloat(ShaderUtilities.ID_StencilID));
tmp_mat.SetFloat(ShaderUtilities.ID_StencilComp, mat.GetFloat(ShaderUtilities.ID_StencilComp));
mat.CopyPropertiesFromMaterial(tmp_mat);
// Reset ShaderKeywords
mat.shaderKeywords = new string[0]; // { "BEVEL_OFF", "GLOW_OFF", "UNDERLAY_OFF" };
}
else
{
mat.CopyPropertiesFromMaterial(tmp_mat);
}
DestroyImmediate(tmp_mat);
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat);
}
//This function is used for debugging and fixing potentially broken font atlas links.
[MenuItem("CONTEXT/Material/Copy Atlas", false, 2000)]
static void CopyAtlas(MenuCommand command)
{
Material mat = command.context as Material;
m_copiedAtlasProperties = new Material(mat);
m_copiedAtlasProperties.hideFlags = HideFlags.DontSave;
}
// This function is used for debugging and fixing potentially broken font atlas links
[MenuItem("CONTEXT/Material/Paste Atlas", false, 2001)]
static void PasteAtlas(MenuCommand command)
{
Material mat = command.context as Material;
Undo.RecordObject(mat, "Paste Texture");
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
mat.mainTexture = m_copiedAtlasProperties.mainTexture;
mat.SetFloat(ShaderUtilities.ID_GradientScale, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_GradientScale));
mat.SetFloat(ShaderUtilities.ID_TextureWidth, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureWidth));
mat.SetFloat(ShaderUtilities.ID_TextureHeight, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureHeight));
//DestroyImmediate(m_copiedAtlasProperties);
}
// Context Menus for TMPro Font Assets
//This function is used for debugging and fixing potentially broken font atlas links.
[MenuItem("CONTEXT/TextMeshProFont/Extract Atlas", false, 2000)]
static void ExtractAtlas(MenuCommand command)
{
TextMeshProFont font = command.context as TextMeshProFont;
Texture2D tex = Instantiate(font.material.mainTexture) as Texture2D;
string fontPath = AssetDatabase.GetAssetPath(font);
string texPath = Path.GetDirectoryName(fontPath) + "/" + Path.GetFileNameWithoutExtension(fontPath) + " Atlas.png";
Debug.Log(texPath);
// Saving File for Debug
var pngData = tex.EncodeToPNG();
File.WriteAllBytes(texPath, pngData);
AssetDatabase.Refresh();
DestroyImmediate(tex);
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 9af14103d0739514da98f1a5aafd79a4
timeCreated: 1480605655
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
#if UNITY_4_6 || UNITY_5
using UnityEngine.UI;
using UnityEngine.EventSystems;
#endif
namespace TMPro.EditorUtilities
{
public static class TMPro_CreateObjectMenu
{
#if UNITY_4_6 || UNITY_5
[MenuItem("GameObject/3D Object/TextMeshPro Text", false, 30)]
#else
[MenuItem("GameObject/Create Other/TextMeshPro Text", false, -1)]
#endif
static void CreateTextMeshProObjectPerform(MenuCommand command)
{
GameObject go = new GameObject("TextMeshPro");
TextMeshPro textMeshPro = go.AddComponent<TextMeshPro>();
textMeshPro.text = "Sample text";
textMeshPro.alignment = TextAlignmentOptions.TopLeft;
#if UNITY_4_6 || UNITY_5
if (command.context != null)
GameObjectUtility.SetParentAndAlign(go, command.context as GameObject);
#else
if (command.context != null)
go.transform.parent = (command.context as GameObject).transform;
#endif
}
#if UNITY_4_6 || UNITY_5
[MenuItem("GameObject/UI/TextMeshPro Text", false, 2003)]
static void CreateTextMeshProGuiObjectPerform(MenuCommand command)
{
// Check if there is a Canvas in the scene
Canvas canvas = Object.FindObjectOfType<Canvas>();
if (canvas == null)
{
// Create new Canvas since none exists in the scene.
canvas = new GameObject("Canvas").AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
// Add a Graphic Raycaster Component as well
canvas.gameObject.AddComponent<GraphicRaycaster>();
}
// Create the TextMeshProUGUI Object
GameObject go = new GameObject("TextMeshPro Text");
RectTransform goRectTransform = go.AddComponent<RectTransform>();
// Check if object is being create with left or right click
if (command.context == null)
{
goRectTransform.sizeDelta = new Vector2(200f, 50f);
GameObjectUtility.SetParentAndAlign(go, canvas.gameObject);
TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
textMeshPro.text = "New Text";
textMeshPro.alignment = TextAlignmentOptions.TopLeft;
}
else
{
GameObject parent = command.context as GameObject;
if (parent.GetComponent<Button>() != null)
{
goRectTransform.sizeDelta = Vector2.zero;
goRectTransform.anchorMin = Vector2.zero;
goRectTransform.anchorMax = Vector2.one;
GameObjectUtility.SetParentAndAlign(go, command.context as GameObject);
TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
textMeshPro.text = "Button";
textMeshPro.fontSize = 24;
textMeshPro.alignment = TextAlignmentOptions.Center;
}
else
{
goRectTransform.sizeDelta = new Vector2(200f, 50f);
GameObjectUtility.SetParentAndAlign(go, command.context as GameObject);
TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
textMeshPro.text = "New Text";
textMeshPro.alignment = TextAlignmentOptions.TopLeft;
}
}
// Check if an event system already exists in the scene
if (!Object.FindObjectOfType<EventSystem>())
{
GameObject eventObject = new GameObject("EventSystem", typeof(EventSystem));
eventObject.AddComponent<StandaloneInputModule>();
eventObject.AddComponent<TouchInputModule>();
}
}
#endif
}
}
fileFormatVersion: 2
guid: c9ca60a7f24cd95499feea7fe34907d0
timeCreated: 1480605662
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace TMPro.EditorUtilities
{
public static class TMPro_CreateSpriteAssetMenu
{
[MenuItem("Assets/Create/TextMeshPro - Sprite Asset", false, 100)]
public static void CreateTextMeshProObjectPerform()
{
Object target = Selection.activeObject;
// Make sure the selection is a texture.
if (target == null || target.GetType() != typeof(Texture2D))
return;
Texture2D sourceTex = target as Texture2D;
// Get the path to the selected texture.
string filePathWithName = AssetDatabase.GetAssetPath(sourceTex);
string fileNameWithExtension = Path.GetFileName(filePathWithName);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
string filePath = filePathWithName.Replace(fileNameWithExtension, "");
// Check if Sprite Asset already exists
SpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(filePath + fileNameWithoutExtension + ".asset", typeof(SpriteAsset)) as SpriteAsset;
bool isNewAsset = spriteAsset == null ? true : false;
if (isNewAsset)
{
// Create new Sprite Asset using this texture
spriteAsset = ScriptableObject.CreateInstance<SpriteAsset>();
AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset");
// Assign new Sprite Sheet texture to the Sprite Asset.
spriteAsset.spriteSheet = sourceTex;
spriteAsset.spriteInfoList = GetSpriteInfo(sourceTex);
//spriteAsset.UpdateSpriteArray(sourceTex);
//spriteSheet.hideFlags = HideFlags.HideInHierarchy;
//AssetDatabase.AddObjectToAsset(spriteSheet, spriteAsset);
//spriteAsset.spriteSheetWidth = sourceTex.width;
//spriteAsset.spriteSheetHeight = sourceTex.height;
}
else
{
spriteAsset.spriteInfoList = UpdateSpriteInfo(spriteAsset);
}
// Get the Sprites contained in the Sprite Sheet
EditorUtility.SetDirty(spriteAsset);
//spriteAsset.sprites = sprites;
// Set source texture back to Not Readable.
//texImporter.isReadable = false;
AssetDatabase.SaveAssets();
//AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset)); // Re-import font asset to get the new updated version.
//AssetDatabase.Refresh();
}
private static List<SpriteInfo> GetSpriteInfo(Texture source)
{
//Debug.Log("Creating new Sprite Asset.");
string filePath = UnityEditor.AssetDatabase.GetAssetPath(source);
// Get all the Sprites sorted by Index
Sprite[] sprites = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray();
List<SpriteInfo> spriteInfoList = new List<SpriteInfo>();
for (int i = 0; i < sprites.Length; i++)
{
SpriteInfo spriteInfo = new SpriteInfo();
Sprite sprite = sprites[i];
//spriteInfo.fileID = UnityEditor.Unsupported.GetLocalIdentifierInFile(sprite.GetInstanceID());
spriteInfo.id = i;
spriteInfo.name = sprite.name;
Rect spriteRect = sprite.rect;
spriteInfo.x = spriteRect.x;
spriteInfo.y = spriteRect.y;
spriteInfo.width = spriteRect.width;
spriteInfo.height = spriteRect.height;
// Compute Sprite pivot position
Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2));
spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height);
//spriteInfo.sprite = sprite;
// Properties the can be modified
spriteInfo.xAdvance = spriteRect.width;
spriteInfo.scale = 1.0f;
spriteInfo.xOffset = 0;
spriteInfo.yOffset = 0;
spriteInfoList.Add(spriteInfo);
}
return spriteInfoList;
}
// Update exsisting SpriteInfo
private static List<SpriteInfo> UpdateSpriteInfo(SpriteAsset spriteAsset)
{
//Debug.Log("Updating Sprite Asset.");
string filePath = UnityEditor.AssetDatabase.GetAssetPath(spriteAsset.spriteSheet);
// Get all the Sprites sorted Left to Right / Top to Bottom
Sprite[] sprites = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray();
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
// Check if sprite already exists in the SpriteInfoList
int index = spriteAsset.spriteInfoList.FindIndex(item => item.name == sprite.name);
//Debug.Log("")
// Use existing SpriteInfo is it already exists
SpriteInfo spriteInfo = index == -1 ? new SpriteInfo() : spriteAsset.spriteInfoList[index];
Rect spriteRect = sprite.rect;
spriteInfo.name = sprite.name;
spriteInfo.x = spriteRect.x;
spriteInfo.y = spriteRect.y;
spriteInfo.width = spriteRect.width;
spriteInfo.height = spriteRect.height;
// Get Sprite Pivot
Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2));
// The position of the pivot influences the Offset position.
spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height);
if (index == -1)
{
// Find the next available index for this Sprite
int[] ids = spriteAsset.spriteInfoList.Select(item => item.id).ToArray();
int id = 0;
for (int j = 0; j < ids.Length; j++ )
{
if (ids[0] != 0) break;
if (j > 0 && (ids[j] - ids[j - 1]) > 1)
{
id = ids[j - 1] + 1;
break;
}
id = j + 1;
}
//spriteInfo.fileID = fileID;
spriteInfo.id = id;
spriteInfo.xAdvance = spriteRect.width;
spriteInfo.scale = 1.0f;
spriteInfo.xOffset = 0;
spriteInfo.yOffset = 0;
spriteAsset.spriteInfoList.Add(spriteInfo);
}
else
{
spriteAsset.spriteInfoList[index] = spriteInfo;
}
}
return spriteAsset.spriteInfoList;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 730228a82f871db4fb4b839282bfbc1d
timeCreated: 1478780257
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshPro)), CanEditMultipleObjects]
public class TMPro_EditorPanel : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = false;
public static bool shadowSetting = false;
public static bool materialEditor = true;
}
private static int m_eventID;
private static string[] uiStateLabel = new string[] { "\t- <i>Click to expand</i> -", "\t- <i>Click to collapse</i> -" };
private const string k_UndoRedo = "UndoRedoPerformed";
//private static string[] k_sortingLayerNames =
public int selAlignGrid_A = 0;
public int selAlignGrid_B = 0;
// Serialized Properties
private SerializedProperty text_prop;
private SerializedProperty fontAsset_prop;
private SerializedProperty fontStyle_prop;
// Color Properties
private SerializedProperty fontColor_prop;
private SerializedProperty enableVertexGradient_prop;
private SerializedProperty fontColorGradient_prop;
private SerializedProperty overrideHtmlColor_prop;
private SerializedProperty fontSize_prop;
private SerializedProperty fontSizeBase_prop;
private SerializedProperty autoSizing_prop;
private SerializedProperty fontSizeMin_prop;
private SerializedProperty fontSizeMax_prop;
private SerializedProperty charSpacingMax_prop;
private SerializedProperty lineSpacingMax_prop;
private SerializedProperty characterSpacing_prop;
private SerializedProperty lineSpacing_prop;
private SerializedProperty paragraphSpacing_prop;
private SerializedProperty textAlignment_prop;
//private SerializedProperty textAlignment_prop;
private SerializedProperty horizontalMapping_prop;
private SerializedProperty verticalMapping_prop;
private SerializedProperty uvOffset_prop;
private SerializedProperty uvLineOffset_prop;
private SerializedProperty enableWordWrapping_prop;
private SerializedProperty wordWrappingRatios_prop;
private SerializedProperty textOverflowMode_prop;
private SerializedProperty pageToDisplay_prop;
private SerializedProperty enableKerning_prop;
private SerializedProperty inputSource_prop;
private SerializedProperty havePropertiesChanged_prop;
private SerializedProperty isInputPasingRequired_prop;
//private SerializedProperty isAffectingWordWrapping_prop;
private SerializedProperty isRichText_prop;
private SerializedProperty hasFontAssetChanged_prop;
private SerializedProperty enableExtraPadding_prop;
private SerializedProperty checkPaddingRequired_prop;
private SerializedProperty isOrthographic_prop;
//private SerializedProperty isOverlay_prop;
//private SerializedProperty textRectangle_prop;
//private SerializedProperty isMaskUpdateRequired_prop;
//private SerializedProperty mask_prop;
//private SerializedProperty maskOffset_prop;
//private SerializedProperty maskOffsetMode_prop;
//private SerializedProperty maskSoftness_prop;
private SerializedProperty vertexOffset_prop;
private int m_sortingLayerID;
private int m_sortingOrder;
private bool havePropertiesChanged = false;
private TextMeshPro m_textMeshProScript;
//private Transform m_transform;
private Renderer m_renderer;
private int m_currentMaterialID;
private int m_previousMaterialID;
//private Material m_currentMaterial;
//private TMPro_UpdateManager m_updateManager;
//private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };
private float prev_lineLenght;
public void OnEnable()
{
//Debug.Log("OnEnable() for Inspector ID " + this.GetInstanceID() + " has been called.");
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
text_prop = serializedObject.FindProperty("m_text");
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
fontStyle_prop = serializedObject.FindProperty("m_fontStyle");
fontSize_prop = serializedObject.FindProperty("m_fontSize");
fontSizeBase_prop = serializedObject.FindProperty("m_fontSizeBase");
autoSizing_prop = serializedObject.FindProperty("m_enableAutoSizing");
fontSizeMin_prop = serializedObject.FindProperty("m_fontSizeMin");
fontSizeMax_prop = serializedObject.FindProperty("m_fontSizeMax");
charSpacingMax_prop = serializedObject.FindProperty("m_charSpacingMax");
lineSpacingMax_prop = serializedObject.FindProperty("m_lineSpacingMax");
// Colors & Gradient
fontColor_prop = serializedObject.FindProperty("m_fontColor");
enableVertexGradient_prop = serializedObject.FindProperty ("m_enableVertexGradient");
fontColorGradient_prop = serializedObject.FindProperty ("m_fontColorGradient");
overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");
characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
paragraphSpacing_prop = serializedObject.FindProperty("m_paragraphSpacing");
textAlignment_prop = serializedObject.FindProperty("m_textAlignment");
horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
uvOffset_prop = serializedObject.FindProperty("m_uvOffset");
uvLineOffset_prop = serializedObject.FindProperty("m_uvLineOffset");
enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
textOverflowMode_prop = serializedObject.FindProperty("m_overflowMode");
pageToDisplay_prop = serializedObject.FindProperty("m_pageToDisplay");
enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
//isOverlay_prop = serializedObject.FindProperty("m_isOverlay");
havePropertiesChanged_prop = serializedObject.FindProperty("havePropertiesChanged");
inputSource_prop = serializedObject.FindProperty("m_inputSource");
isInputPasingRequired_prop = serializedObject.FindProperty("isInputParsingRequired");
//isAffectingWordWrapping_prop = serializedObject.FindProperty("isAffectingWordWrapping");
enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
isRichText_prop = serializedObject.FindProperty("m_isRichText");
checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
//isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
//mask_prop = serializedObject.FindProperty("m_mask");
//maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
//maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
//maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
//vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");
//m_sortingLayerID = serializedObject.FindProperty("m_sortingLayerID");
//m_sortingOrder = serializedObject.FindProperty("m_sortingOrder");
hasFontAssetChanged_prop = serializedObject.FindProperty("hasFontAssetChanged");
//renderer_prop = serializedObject.FindProperty("m_renderer");
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
m_textMeshProScript = target as TextMeshPro;
//m_transform = Selection.activeGameObject.transform;
m_renderer = m_textMeshProScript.GetComponent<Renderer>();
//m_sortingLayerID = m_renderer.sortingLayerID;
//m_sortingOrder = m_renderer.sortingOrder;
//if (m_renderer.sharedMaterial != null)
// m_currentMaterial = m_renderer.sharedMaterial;
//m_updateManager = Camera.main.gameObject.GetComponent<TMPro_UpdateManager>();
}
public void OnDisable()
{
//Debug.Log("OnDisable() for Inspector ID " + this.GetInstanceID() + " has been called.");
Undo.undoRedoPerformed -= OnUndoRedo;
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
Rect rect;
float labelWidth = EditorGUIUtility.labelWidth = 130f;
float fieldWidth = EditorGUIUtility.fieldWidth;
// TEXT INPUT BOX SECTION
if (GUILayout.Button("<b>TEXT INPUT BOX</b>" + (m_foldout.textInput ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.textInput = !m_foldout.textInput;
if (m_foldout.textInput)
{
EditorGUI.BeginChangeCheck();
text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, TMP_UIStyleManager.TextAreaBoxEditor, GUILayout.Height(125), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
inputSource_prop.enumValueIndex = 0;
isInputPasingRequired_prop.boolValue = true;
//isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
}
// FONT SETTINGS SECTION
if (GUILayout.Button("<b>FONT SETTINGS</b>" + (m_foldout.fontSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.fontSettings = !m_foldout.fontSettings;
if (m_foldout.fontSettings)
{
// FONT ASSET
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontAsset_prop);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(m_renderer, "Asset & Material Change");
havePropertiesChanged = true;
hasFontAssetChanged_prop.boolValue = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// FONT STYLE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Font Style");
int styleValue = fontStyle_prop.intValue;
int v1 = GUILayout.Toggle((styleValue & 1) == 1, "B", GUI.skin.button) ? 1 : 0; // Bold
int v2 = GUILayout.Toggle((styleValue & 2) == 2, "I", GUI.skin.button) ? 2 : 0; // Italics
int v3 = GUILayout.Toggle((styleValue & 4) == 4, "U", GUI.skin.button) ? 4 : 0; // Underline
int v4 = GUILayout.Toggle((styleValue & 8) == 8, "ab", GUI.skin.button) ? 8 : 0; // Lowercase
int v5 = GUILayout.Toggle((styleValue & 16) == 16, "AB", GUI.skin.button) ? 16 : 0; // Uppercase
int v6 = GUILayout.Toggle((styleValue & 32) == 32, "S", GUI.skin.button) ? 32 : 0; // Smallcaps
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
fontStyle_prop.intValue = v1 + v2 + v3 + v4 + v5 + v6;
havePropertiesChanged = true;
}
// FACE VERTEX COLOR
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Color (Vertex)"));
// VERTEX COLOR GRADIENT
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.PrefixLabel("Color Gradient");
EditorGUILayout.PropertyField(enableVertexGradient_prop, new GUIContent("Color Gradient"), GUILayout.MinWidth(140), GUILayout.MaxWidth(200));
EditorGUIUtility.labelWidth = 95;
EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Tags"));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (enableVertexGradient_prop.boolValue)
{
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topLeft"), new GUIContent("Top Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topRight"), new GUIContent("Top Right"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomLeft"), new GUIContent("Bottom Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomRight"), new GUIContent("Bottom Right"));
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// FONT SIZE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(fontSize_prop, new GUIContent("Font Size"), GUILayout.MinWidth(168), GUILayout.MaxWidth(200));
EditorGUIUtility.fieldWidth = fieldWidth;
if (EditorGUI.EndChangeCheck())
{
fontSizeBase_prop.floatValue = fontSize_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 70;
EditorGUILayout.PropertyField(autoSizing_prop, new GUIContent("Auto Size"));
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = labelWidth;
if (EditorGUI.EndChangeCheck())
{
if (autoSizing_prop.boolValue == false)
fontSize_prop.floatValue = fontSizeBase_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// Show auto sizing options
if (autoSizing_prop.boolValue)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Auto Size Options");
EditorGUIUtility.labelWidth = 30;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMin_prop, new GUIContent("Min"), GUILayout.MinWidth(50));
if (EditorGUI.EndChangeCheck())
{
fontSizeMin_prop.floatValue = Mathf.Min(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMax_prop, new GUIContent("Max"), GUILayout.MinWidth(50));
if (EditorGUI.EndChangeCheck())
{
fontSizeMax_prop.floatValue = Mathf.Max(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(charSpacingMax_prop, new GUIContent("Char"), GUILayout.MinWidth(50));
EditorGUILayout.PropertyField(lineSpacingMax_prop, new GUIContent("Line"), GUILayout.MinWidth(50));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
charSpacingMax_prop.floatValue = Mathf.Min(0, charSpacingMax_prop.floatValue);
lineSpacingMax_prop.floatValue = Mathf.Min(0, lineSpacingMax_prop.floatValue);
havePropertiesChanged = true;
}
}
// CHARACTER, LINE & PARAGRAPH SPACING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Spacing Options");
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(characterSpacing_prop, new GUIContent("Char"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(lineSpacing_prop, new GUIContent("Line"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(paragraphSpacing_prop, new GUIContent(" Par."), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// TEXT ALIGNMENT
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false, 17);
GUIStyle btn = new GUIStyle(GUI.skin.button);
btn.margin = new RectOffset(1, 1, 1, 1);
btn.padding = new RectOffset(1, 1, 1, 0);
selAlignGrid_A = textAlignment_prop.enumValueIndex & ~28;
selAlignGrid_B = (textAlignment_prop.enumValueIndex & ~3) / 4;
GUI.Label(new Rect(rect.x, rect.y, 100, rect.height), "Alignment");
float columnB = EditorGUIUtility.labelWidth + 15;
selAlignGrid_A = GUI.SelectionGrid(new Rect(columnB, rect.y, 23 * 4, rect.height), selAlignGrid_A, TMP_UIStyleManager.alignContent_A, 4, btn);
selAlignGrid_B = GUI.SelectionGrid(new Rect(columnB + 23 * 4 + 10, rect.y, 23 * 5, rect.height), selAlignGrid_B, TMP_UIStyleManager.alignContent_B, 5, btn);
if (EditorGUI.EndChangeCheck())
{
textAlignment_prop.enumValueIndex = selAlignGrid_A + selAlignGrid_B * 4;
havePropertiesChanged = true;
}
// WRAPPING RATIOS shown if Justified mode is selected.
EditorGUI.BeginChangeCheck();
if (textAlignment_prop.enumValueIndex == 3 || textAlignment_prop.enumValueIndex == 7 || textAlignment_prop.enumValueIndex == 11 || textAlignment_prop.enumValueIndex == 19)
DrawPropertySlider("Wrap Mix (W <-> C)", wordWrappingRatios_prop);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// TEXT WRAPPING & OVERFLOW
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("Wrapping & Overflow"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
int wrapSelection = EditorGUI.Popup(rect, enableWordWrapping_prop.boolValue ? 1 : 0, new string[] { "Disabled", "Enabled" });
if (EditorGUI.EndChangeCheck())
{
enableWordWrapping_prop.boolValue = wrapSelection == 1 ? true : false;
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXT OVERFLOW
EditorGUI.BeginChangeCheck();
if (textOverflowMode_prop.enumValueIndex != 5)
{
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
}
else
{
rect.x += rect.width + 5f;
rect.width /= 2;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
rect.x += rect.width;
rect.width -= 5;
EditorGUI.PropertyField(rect, pageToDisplay_prop, GUIContent.none);
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXTURE MAPPING OPTIONS
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("UV Mapping Options"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
EditorGUI.PropertyField(rect, horizontalMapping_prop, GUIContent.none);
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, verticalMapping_prop, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// UV OPTIONS
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("UV Offset");
EditorGUILayout.PropertyField(uvOffset_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(uvLineOffset_prop, new GUIContent("Line"), GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// KERNING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Enable Kerning?"));
if (EditorGUI.EndChangeCheck())
{
//isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
// EXTRA PADDING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding?"));
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
checkPaddingRequired_prop.boolValue = true;
}
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("<b>EXTRA SETTINGS</b>" + (m_foldout.extraSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.extraSettings = !m_foldout.extraSettings;
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel = 0;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Sorting Layer");
EditorGUI.BeginChangeCheck();
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_fieldWidth = EditorGUIUtility.fieldWidth;
// SORTING LAYERS
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(m_textMeshProScript.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = Array.IndexOf(sortingLayerNames, oldName);
// Show the popup for the names
EditorGUIUtility.fieldWidth = 0f;
int newLayerIndex = EditorGUILayout.Popup(string.Empty, oldLayerIndex, sortingLayerNames, GUILayout.MinWidth(80f));
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
//Undo.RecordObject(renderer, "Edit Sorting Layer");
m_textMeshProScript.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
//EditorUtility.SetDirty(renderer);
}
// Expose the manual sorting order
EditorGUIUtility.labelWidth = 40f;
EditorGUIUtility.fieldWidth = 80f;
int newSortingLayerOrder = EditorGUILayout.IntField("Order", m_textMeshProScript.sortingOrder);
if (newSortingLayerOrder != m_textMeshProScript.sortingOrder)
{
//Undo.RecordObject(renderer, "Edit Sorting Order");
m_textMeshProScript.sortingOrder = newSortingLayerOrder;
}
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_fieldWidth;
EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(isOverlay_prop, new GUIContent("Overlay Mode?"));
EditorGUILayout.PropertyField(isOrthographic_prop, new GUIContent("Orthographic Mode?"));
EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Enable Rich Text?"));
//EditorGUILayout.PropertyField(textRectangle_prop, true);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(mask_prop);
//EditorGUILayout.PropertyField(maskOffset_prop, true);
//EditorGUILayout.PropertyField(maskSoftness_prop);
//if (EditorGUI.EndChangeCheck())
//{
// isMaskUpdateRequired_prop.boolValue = true;
// havePropertiesChanged = true;
//}
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
// Mask Selection
}
/*
if (Event.current.type == EventType.DragExited)
{
m_currentMaterialID = m_renderer.sharedMaterial.GetInstanceID();
if (m_currentMaterialID != m_previousMaterialID)
{
Debug.Log("Material has been changed to " + m_currentMaterialID + ". Previous Material was " + m_previousMaterialID);
//m_targetMaterial = m_renderer.sharedMaterial;
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_targetMaterial);
m_previousMaterialID = m_currentMaterialID;
havePropertiesChanged = true;
}
}
*/
if (havePropertiesChanged)
{
havePropertiesChanged_prop.boolValue = true;
havePropertiesChanged = false;
//m_updateManager.ScheduleObjectForUpdate(m_textMeshProScript);
}
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
/*
Editor materialEditor = Editor.CreateEditor(m_renderer.sharedMaterial);
if (materialEditor != null)
{
if (GUILayout.Button("<b>MATERIAL SETTINGS</b> - <i>Click to expand</i> -", Section_Label))
m_foldout.materialEditor= !m_foldout.materialEditor;
if (m_foldout.materialEditor)
{
materialEditor.OnInspectorGUI();
}
}
*/
}
/*
public void OnSceneGUI()
{
if (enableWordWrapping_prop.boolValue)
{
// Show Handles to represent Line Lenght settings
Bounds meshExtents = m_textMeshProScript.bounds;
Vector3 lossyScale = m_transform.lossyScale;
handlePoints[0] = m_transform.TransformPoint(new Vector3(meshExtents.min.x * lossyScale.x, meshExtents.min.y, 0));
handlePoints[1] = m_transform.TransformPoint(new Vector3(meshExtents.min.x * lossyScale.x, meshExtents.max.y, 0));
handlePoints[2] = handlePoints[1] + m_transform.TransformDirection(new Vector3(m_textMeshProScript.lineLength * lossyScale.x, 0, 0));
handlePoints[3] = handlePoints[0] + m_transform.TransformDirection(new Vector3(m_textMeshProScript.lineLength * lossyScale.x, 0, 0));
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(0, 0, 0, 0), new Color32(255, 255, 0, 255));
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(m_transform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = new_right.x - old_right.x;
m_textMeshProScript.lineLength += delta / lossyScale.x;
}
}
*/
/* New Experimental Code
// Margin Frame & Handles
Vector3 rectPos = m_transform.position;
Vector4 textRect = m_textMeshProScript.textRectangle;
handlePoints[0] = rectPos + m_transform.TransformDirection(new Vector3(- textRect.x, - textRect.w, 0)); // BL
handlePoints[1] = rectPos + m_transform.TransformDirection(new Vector3(- textRect.x, + textRect.y, 0)); // TL
handlePoints[2] = rectPos + m_transform.TransformDirection(new Vector3(+ textRect.z, + textRect.y, 0)); // TR
handlePoints[3] = rectPos + m_transform.TransformDirection(new Vector3(+ textRect.z, - textRect.w, 0)); // BR
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
// LEFT HANDLE
Vector3 old_left = (handlePoints[0] + handlePoints[1]) * 0.5f;
Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
bool hasChanged = false;
if (old_left != new_left)
{
float delta = old_left.x - new_left.x;
textRect.x += delta;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 old_top = (handlePoints[1] + handlePoints[2]) * 0.5f;
Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_top != new_top)
{
float delta = old_top.y - new_top.y;
textRect.y -= delta;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = old_right.x - new_right.x;
textRect.z -= delta;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 old_bottom = (handlePoints[3] + handlePoints[0]) * 0.5f;
Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_bottom != new_bottom)
{
float delta = old_bottom.y - new_bottom.y;
textRect.w += delta;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
m_textMeshProScript.textRectangle = textRect;
//m_textMeshProScript.ForceMeshUpdate();
}
}
*/
void DrawPropertySlider(string label, SerializedProperty property)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
//EditorGUIUtility.labelWidth = m_labelWidth;
GUIContent content = label == "" ? GUIContent.none : new GUIContent(label);
EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDimensionProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Rect rectangle = property.rectValue;
float width_B = width - old_LabelWidth;
float fieldWidth = width_B / 4;
pos0.width = fieldWidth - 5;
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Width");
pos0.x += fieldWidth;
rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);
pos0.x += fieldWidth;
GUI.Label(pos0, "Height");
pos0.x += fieldWidth;
rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);
property.rectValue = rectangle;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDoubleEnumPopup(SerializedProperty property1, SerializedProperty property2, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
Rect pos0 = new Rect(rect.x, rect.y, EditorGUIUtility.labelWidth, rect.height);
EditorGUI.PrefixLabel(pos0, new GUIContent(label));
pos0.x += pos0.width;
pos0.width = (rect.width - pos0.x) / 2 + 5;
EditorGUI.PropertyField(pos0, property1, GUIContent.none);
pos0.x += pos0.width + 5;
EditorGUI.PropertyField(pos0, property2, GUIContent.none);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
void DrawPropertyBlock(string[] labels, SerializedProperty[] properties)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
GUI.Label(new Rect(rect.x, rect.y, old_LabelWidth, rect.height), labels[0]);
rect.x = old_LabelWidth + 15;
rect.width = (rect.width + 20 - rect.x) / labels.Length;
for (int i = 0; i < labels.Length; i++)
{
if (i == 0)
{
EditorGUIUtility.labelWidth = 20;
GUI.enabled = properties[i] == fontSize_prop && autoSizing_prop.boolValue ? GUI.enabled = false : GUI.enabled = true;
EditorGUI.PropertyField(new Rect(rect.x - 20, rect.y, 80, rect.height), properties[i], new GUIContent(" "));
rect.x += rect.width;
GUI.enabled = true;
}
else
{
EditorGUIUtility.labelWidth = GUI.skin.textArea.CalcSize(new GUIContent(labels[i])).x;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 5, rect.height), properties[i], new GUIContent(labels[i]));
rect.x += rect.width;
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
int undoEventID = Undo.GetCurrentGroup();
int LastUndoEventID = m_eventID;
if (undoEventID != LastUndoEventID)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
m_eventID = undoEventID;
}
}
}
/*
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
int eventID = Undo.GetCurrentGroup();
PropertyModification modifiedProp = modifications[0].propertyModification;
System.Type targetType = modifiedProp.target.GetType();
if (targetType == typeof(Material))
{
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + targetObject);
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, targetObject as Material);
//EditorUtility.SetDirty(targetObject);
}
//string propertyPath = modifications[0].propertyModification.propertyPath;
//if (propertyPath == "m_fontAsset")
//{
//int currentEvent = Undo.GetCurrentGroup();
//Undo.RecordObject(Selection.activeGameObject.renderer.sharedMaterial, "Font Asset Changed");
//Undo.CollapseUndoOperations(currentEvent);
//Debug.Log("Undo / Redo Event: Font Asset changed. Event ID:" + Undo.GetCurrentGroup());
//}
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + modifiedProp.propertyPath + " Undo Event ID:" + eventID + " Stored ID:" + TMPro_EditorUtility.UndoEventID);
//TextMeshPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, target as TextMeshPro);
return modifications;
}
*/
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: c91bcf9ab2d0961449742fc7b250a363
timeCreated: 1480605662
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections;
namespace TMPro.EditorUtilities
{
public static class EditorShaderUtilities
{
/// <summary>
/// Copy Shader properties from source to destination material.
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static void CopyMaterialProperties(Material source, Material destination)
{
MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source });
for (int i = 0; i < source_prop.Length; i++)
{
int property_ID = Shader.PropertyToID(source_prop[i].name);
if (destination.HasProperty(property_ID))
{
//Debug.Log(source_prop[i].name + " Type:" + ShaderUtil.GetPropertyType(source.shader, i));
switch (ShaderUtil.GetPropertyType(source.shader, i))
{
case ShaderUtil.ShaderPropertyType.Color:
destination.SetColor(property_ID, source.GetColor(property_ID));
break;
case ShaderUtil.ShaderPropertyType.Float:
destination.SetFloat(property_ID, source.GetFloat(property_ID));
break;
case ShaderUtil.ShaderPropertyType.Range:
destination.SetFloat(property_ID, source.GetFloat(property_ID));
break;
case ShaderUtil.ShaderPropertyType.TexEnv:
destination.SetTexture(property_ID, source.GetTexture(property_ID));
break;
case ShaderUtil.ShaderPropertyType.Vector:
destination.SetVector(property_ID, source.GetVector(property_ID));
break;
}
}
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2be0e7663436d7e489736e101798314d
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace TMPro.EditorUtilities
{
public static class TMPro_EditorUtility
{
// Static Fields Related to locating the TextMesh Pro Asset
private static bool isTMProFolderLocated;
private static string folderPath = "Not Found";
private static EditorWindow Gameview;
private static bool isInitialized = false;
private static void GetGameview()
{
System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly;
System.Type type = assembly.GetType("UnityEditor.GameView");
Gameview = EditorWindow.GetWindow(type);
}
public static void RepaintAll()
{
if (isInitialized == false)
{
GetGameview();
isInitialized = true;
}
SceneView.RepaintAll();
Gameview.Repaint();
}
// Function used to find all materials which reference a font atlas so we can update all their references.
public static Material[] FindMaterialReferences(Material mat)
{
// Find all Materials used in the project.
Material[] mats = Resources.FindObjectsOfTypeAll<Material>();
List<Material> refs = new List<Material>();
for (int i = 0; i < mats.Length; i++)
{
if (mats[i].HasProperty(ShaderUtilities.ID_MainTex) && mats[i].GetTexture(ShaderUtilities.ID_MainTex) == mat.GetTexture(ShaderUtilities.ID_MainTex))
{
refs.Add(mats[i]);
//Debug.Log(mats[i].name);
}
}
return refs.ToArray();
}
/// <summary>
/// Function to find the asset folder location in case it was moved by the user.
/// </summary>
/// <returns></returns>
public static string GetAssetLocation()
{
if (isTMProFolderLocated == false)
{
isTMProFolderLocated = true;
string projectPath = Directory.GetCurrentDirectory();
// Find all the directories that match "TextMesh Pro"
string[] matchingPaths = Directory.GetDirectories(projectPath + "/Assets", "TextMesh Pro", SearchOption.AllDirectories);
folderPath = ValidateLocation(matchingPaths);
if (folderPath != null) return folderPath;
// Check alternative Asset folder name.
matchingPaths = Directory.GetDirectories(projectPath + "/Assets", "TextMeshPro", SearchOption.AllDirectories);
folderPath = ValidateLocation(matchingPaths);
if (folderPath != null) return folderPath;
}
if (folderPath != null) return folderPath;
else
{
Debug.LogWarning("Could not located the \"TextMesh Pro/GUISkins\" Folder to load the Editor Skins.");
return null;
}
}
/// <summary>
/// Method to validate the location of the asset folder by making sure the GUISkins folder exists.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
private static string ValidateLocation(string[] paths)
{
for (int i = 0; i < paths.Length; i++)
{
// Check if any of the matching directories contain a GUISkins directory.
if (Directory.Exists(paths[i] + "/GUISkins"))
{
folderPath = "Assets" + paths[i].Split(new string[] { "/Assets" }, System.StringSplitOptions.None)[1];
return folderPath;
}
}
return null;
}
}
}
fileFormatVersion: 2
guid: 03df690944dcf5d46aba97d8b60c42ea
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.IO;
namespace TMPro.EditorUtilities
{
public class TMPro_FontAssetCreatorWindow : EditorWindow
{
[MenuItem("Window/TextMeshPro - Font Asset Creator")]
public static void ShowFontAtlasCreatorWindow()
{
var window = GetWindow<TMPro_FontAssetCreatorWindow>();
window.title = "Asset Creator";
window.Focus();
}
private string[] FontSizingOptions = { "Auto Sizing", "Custom Size" };
private int FontSizingOption_Selection = 0;
private string[] FontResolutionLabels = { "16","32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
private int[] FontAtlasResolutions = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
private string[] FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Custom Characters", "Characters from File" }; //, "Unicode" };
private enum FontPackingModes { Fast = 0, Optimum = 4 };
private FontPackingModes m_fontPackingSelection = 0;
private int font_CharacterSet_Selection = 0;
private enum PreviewSelectionTypes { PreviewFont, PreviewTexture, PreviewDistanceField };
private PreviewSelectionTypes previewSelection;
private string characterSequence = "";
private string output_feedback = "";
private string output_name_label = "Font: ";
private string output_size_label = "Pt. Size: ";
private string output_count_label = "Characters packed: ";
private int m_character_Count;
//private GUISkin TMP_GUISkin;
//private GUIStyle TextureAreaBox;
//private GUIStyle TextAreaBox;
//private GUIStyle Section_Label;
private Thread MainThread;
private Color[] Output;
private bool isDistanceMapReady = false;
private bool isRepaintNeeded = false;
private Rect progressRect;
public static float ProgressPercentage;
private float m_renderingProgress;
private bool isRenderingDone = false;
private bool isProcessing = false;
private Object font_TTF;
private TextAsset characterList;
private int font_size;
private int font_padding = 5;
private FaceStyles font_style = FaceStyles.Normal;
private float font_style_mod = 2;
private RenderModes font_renderMode = RenderModes.DistanceField16;
private int font_atlas_width = 512;
private int font_atlas_height = 512;
private int font_scaledownFactor = 1;
private int font_spread = 4;
private FT_FaceInfo m_font_faceInfo;
private FT_GlyphInfo[] m_font_glyphInfo;
private byte[] m_texture_buffer;
private Texture2D m_font_Atlas;
//private Texture2D m_texture_Atlas;
//private int m_packingMethod = 0;
private Texture2D m_destination_Atlas;
private bool includeKerningPairs = false;
private int[] m_kerningSet;
// Image Down Sampling Fields
private Texture2D sdf_Atlas;
private int downscale;
//private Object prev_Selection;
private EditorWindow m_editorWindow;
private Vector2 m_previewWindow_Size = new Vector2(768, 768);
private Rect m_UI_Panel_Size;
public void OnEnable()
{
m_editorWindow = this;
UpdateEditorWindowSize(768, 768);
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
// Locate the plugin files & move them to root of project if that hasn't already been done.
#if !UNITY_5
// Find to location of the TextMesh Pro Asset Folder (as users may have moved it)
string tmproAssetFolderPath = TMPro_EditorUtility.GetAssetLocation();
string projectPath = Path.GetFullPath("Assets/..");
if (System.IO.File.Exists(projectPath + "/TMPro_Plugin.dll") == false)
{
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll", projectPath + "/TMPro_Plugin.dll"); // Copy the .dll
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib", projectPath + "/TMPro_Plugin.dylib"); // Copy Mac .dylib
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/vcomp120.dll", projectPath + "/vcomp120.dll"); // Copy OpemMP .dll
}
else // Check if we are using the latest versions
{
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib") > System.IO.File.GetLastWriteTime(projectPath + "/TMPro_Plugin.dylib"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dylib", projectPath + "/TMPro_Plugin.dylib");
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll") > System.IO.File.GetLastWriteTime(projectPath + "/TMPro_Plugin.dll"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/TMPro_Plugin.dll", projectPath + "/TMPro_Plugin.dll");
if (System.IO.File.GetLastWriteTime(tmproAssetFolderPath + "/Plugins/vcomp120.dll") > System.IO.File.GetLastWriteTime(projectPath + "/vcomp120.dll"))
FileUtil.ReplaceFile(tmproAssetFolderPath + "/Plugins/vcomp120.dll", projectPath + "/vcomp120.dll");
}
#endif
// Add Event Listener related to Distance Field Atlas Creation.
TMPro_EventManager.COMPUTE_DT_EVENT += ON_COMPUTE_DT_EVENT;
// Debug Link to received message from Native Code
//TMPro_FontPlugin.LinkDebugLog(); // Link with C++ Plugin to get Debug output
}
public void OnDisable()
{
//Debug.Log("TextMeshPro Editor Window has been disabled.");
TMPro_EventManager.COMPUTE_DT_EVENT -= ON_COMPUTE_DT_EVENT;
// Destroy Enging only if it has been initialized already
if (TMPro_FontPlugin.Initialize_FontEngine() == 99)
{
TMPro_FontPlugin.Destroy_FontEngine();
}
// Cleaning up allocated Texture2D
if (m_destination_Atlas != null && EditorUtility.IsPersistent(m_destination_Atlas) == false)
{
//Debug.Log("Destroying destination_Atlas!");
DestroyImmediate(m_destination_Atlas);
}
if (m_font_Atlas != null && EditorUtility.IsPersistent(m_font_Atlas) == false)
{
//Debug.Log("Destroying font_Atlas!");
DestroyImmediate(m_font_Atlas);
}
}
public void OnGUI()
{
GUILayout.BeginHorizontal(GUILayout.Width(310));
DrawControls();
DrawPreview();
GUILayout.EndHorizontal();
}
public void ON_COMPUTE_DT_EVENT(object Sender, Compute_DT_EventArgs e)
{
if (e.EventType == Compute_DistanceTransform_EventTypes.Completed)
{
Output = e.Colors;
isProcessing = false;
isDistanceMapReady = true;
}
else if (e.EventType == Compute_DistanceTransform_EventTypes.Processing)
{
ProgressPercentage = e.ProgressPercentage;
isRepaintNeeded = true;
}
}
public void Update()
{
if (isDistanceMapReady)
{
if (m_font_Atlas != null)
{
m_destination_Atlas = new Texture2D(m_font_Atlas.width / font_scaledownFactor, m_font_Atlas.height / font_scaledownFactor, TextureFormat.Alpha8, false, true);
m_destination_Atlas.SetPixels(Output);
m_destination_Atlas.Apply(false, true);
}
//else if (m_texture_Atlas != null)
//{
// m_destination_Atlas = new Texture2D(m_texture_Atlas.width / font_scaledownFactor, m_texture_Atlas.height / font_scaledownFactor, TextureFormat.Alpha8, false, true);
// m_destination_Atlas.SetPixels(Output);
// m_destination_Atlas.Apply(false, true);
//}
isDistanceMapReady = false;
Repaint();
// Saving File for Debug
//var pngData = destination_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug SDF.png", pngData);
}
if (isRepaintNeeded)
{
//Debug.Log("Repainting...");
isRepaintNeeded = false;
Repaint();
}
// Update Progress bar is we are Rendering a Font.
if (isProcessing)
{
m_renderingProgress = TMPro_FontPlugin.Check_RenderProgress();
isRepaintNeeded = true;
}
// Update Feedback Window & Create Font Texture once Rendering is done.
if (isRenderingDone)
{
isProcessing = false;
isRenderingDone = false;
UpdateRenderFeedbackWindow();
CreateFontTexture();
}
}
int[] ParseNumberSequence(string sequence)
{
List<int> unicode_list = new List<int>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicode_list.Add(int.Parse(s1[0]));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (int j = int.Parse(s1[0]); j < int.Parse(s1[1]) + 1; j++)
{
unicode_list.Add(j);
}
}
}
return unicode_list.ToArray();
}
void DrawControls()
{
GUILayout.BeginVertical();
GUILayout.Label("<b>TextMeshPro - Font Asset Creator</b>", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
GUILayout.Label("Font Settings", TMP_UIStyleManager.Section_Label, GUILayout.Width(300));
GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox, GUILayout.Width(300));
EditorGUIUtility.LookLikeControls(120f, 160f);
// FONT TTF SELECTION
font_TTF = EditorGUILayout.ObjectField("Font Source", font_TTF, typeof(Font), false, GUILayout.Width(290)) as Font;
// FONT SIZING
if (FontSizingOption_Selection == 0)
{
FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(290));
}
else
{
EditorGUIUtility.LookLikeControls(120f, 40f);
GUILayout.BeginHorizontal(GUILayout.Width(290));
FontSizingOption_Selection = EditorGUILayout.Popup("Font Size", FontSizingOption_Selection, FontSizingOptions, GUILayout.Width(225));
font_size = EditorGUILayout.IntField(font_size);
GUILayout.EndHorizontal();
}
EditorGUIUtility.LookLikeControls(120f, 160f);
// FONT PADDING
font_padding = EditorGUILayout.IntField("Font Padding", font_padding, GUILayout.Width(290));
font_padding = (int)Mathf.Clamp(font_padding, 0f, 64f);
// FONT PACKING METHOD SELECTION
m_fontPackingSelection = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_fontPackingSelection, GUILayout.Width(225));
//font_renderingMode = (FontRenderingMode)EditorGUILayout.EnumPopup("Rendering Mode", font_renderingMode, GUILayout.Width(290));
// FONT ATLAS RESOLUTION SELECTION
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUI.changed = false;
EditorGUIUtility.LookLikeControls(120f, 40f);
GUILayout.Label("Atlas Resolution:", GUILayout.Width(116));
font_atlas_width = EditorGUILayout.IntPopup(font_atlas_width, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));
font_atlas_height = EditorGUILayout.IntPopup(font_atlas_height, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));
GUILayout.EndHorizontal();
// FONT CHARACTER SET SELECTION
GUI.changed = false;
font_CharacterSet_Selection = EditorGUILayout.Popup("Character Set", font_CharacterSet_Selection, FontCharacterSets, GUILayout.Width(290));
if (GUI.changed)
{
characterSequence = "";
//Debug.Log("Resetting Sequence!");
}
switch (font_CharacterSet_Selection)
{
case 0: // ASCII
//characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
characterSequence = "32 - 126, 8230";
break;
case 1: // EXTENDED ASCII
characterSequence = "32 - 126, 161 - 255, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
break;
case 2: // Lowercase
characterSequence = "32 - 64, 91 - 126";
break;
case 3: // Uppercase
characterSequence = "32 - 96, 123 - 126";
break;
case 4: // Numbers & Symbols
characterSequence = "32 - 64, 91 - 96, 123 - 126";
break;
case 5: // Custom Range
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUILayout.Label("Custom Range", GUILayout.Width(116));
// Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
GUILayout.EndHorizontal();
break;
case 6: // Custom Characters
GUILayout.BeginHorizontal(GUILayout.Width(290));
GUILayout.Label("Custom Characters", GUILayout.Width(116));
characterSequence = EditorGUILayout.TextArea(characterSequence, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(32), GUILayout.MaxWidth(170));
GUILayout.EndHorizontal();
break;
case 7: // Character List from File
characterList = EditorGUILayout.ObjectField("Character File", characterList, typeof(TextAsset), false, GUILayout.Width(290)) as TextAsset;
if (characterList != null)
{
characterSequence = characterList.text;
}
break;
}
EditorGUIUtility.LookLikeControls(120f, 40f);
// FONT STYLE SELECTION
GUILayout.BeginHorizontal(GUILayout.Width(290));
font_style = (FaceStyles)EditorGUILayout.EnumPopup("Font Style:", font_style, GUILayout.Width(225));
font_style_mod = EditorGUILayout.IntField((int)font_style_mod);
GUILayout.EndHorizontal();
// Render Mode Selection
font_renderMode = (RenderModes)EditorGUILayout.EnumPopup("Font Render Mode:", font_renderMode, GUILayout.Width(290));
includeKerningPairs = EditorGUILayout.Toggle("Get Kerning Pairs?", includeKerningPairs, GUILayout.MaxWidth(290));
EditorGUIUtility.LookLikeControls(120f, 160f);
GUILayout.Space(20);
GUI.enabled = font_TTF == null || isProcessing ? false : true; // Enable Preview if we are not already rendering a font.
if (GUILayout.Button("Generate Font Atlas", GUILayout.Width(290)) && characterSequence.Length != 0 && GUI.enabled)
{
if (font_TTF != null)
{
int error_Code;
error_Code = TMPro_FontPlugin.Initialize_FontEngine(); // Initialize Font Engine
if (error_Code != 0)
{
if (error_Code == 99)
{
//Debug.Log("Font Library was already initialized!");
error_Code = 0;
}
else
Debug.Log("Error Code: " + error_Code + " occurred while Initializing the FreeType Library.");
}
string fontPath = AssetDatabase.GetAssetPath(font_TTF); // Get file path of TTF Font.
if (error_Code == 0)
{
error_Code = TMPro_FontPlugin.Load_TrueType_Font(fontPath); // Load the selected font.
if (error_Code != 0)
{
if (error_Code == 99)
{
//Debug.Log("Font was already loaded!");
error_Code = 0;
}
else
Debug.Log("Error Code: " + error_Code + " occurred while Loading the font.");
}
}
if (error_Code == 0)
{
if (FontSizingOption_Selection == 0) font_size = 72; // If Auto set size to 72 pts.
error_Code = TMPro_FontPlugin.FT_Size_Font(font_size); // Load the selected font and size it accordingly.
if (error_Code != 0)
Debug.Log("Error Code: " + error_Code + " occurred while Sizing the font.");
}
// Define an array containing the characters we will render.
if (error_Code == 0)
{
int[] character_Set = null;
if (font_CharacterSet_Selection == 6 || font_CharacterSet_Selection == 7)
{
List<int> char_List = new List<int>();
for (int i = 0; i < characterSequence.Length; i++)
{
// Check to make sure we don't include duplicates
if (char_List.FindIndex(item => item == characterSequence[i]) == -1)
char_List.Add(characterSequence[i]);
else
{
//Debug.Log("Character [" + characterSequence[i] + "] is a duplicate.");
}
}
character_Set = char_List.ToArray();
}
else
{
character_Set = ParseNumberSequence(characterSequence);
}
m_character_Count = character_Set.Length;
m_texture_buffer = new byte[font_atlas_width * font_atlas_height];
m_font_faceInfo = new FT_FaceInfo();
m_font_glyphInfo = new FT_GlyphInfo[m_character_Count];
int padding = font_padding;
bool autoSizing = FontSizingOption_Selection == 0 ? true : false;
float strokeSize = font_style_mod;
if (font_renderMode == RenderModes.DistanceField16) strokeSize = font_style_mod * 16;
if (font_renderMode == RenderModes.DistanceField32) strokeSize = font_style_mod * 32;
isProcessing = true;
ThreadPool.QueueUserWorkItem(SomeTask =>
{
isRenderingDone = false;
error_Code = TMPro_FontPlugin.Render_Characters(m_texture_buffer, font_atlas_width, font_atlas_height, padding, character_Set, m_character_Count, font_style, strokeSize, autoSizing, font_renderMode,(int)m_fontPackingSelection, ref m_font_faceInfo, m_font_glyphInfo);
isRenderingDone = true;
//Debug.Log("Font Rendering is completed.");
});
previewSelection = PreviewSelectionTypes.PreviewFont;
}
}
}
// FONT RENDERING PROGRESS BAR
GUILayout.Space(1);
progressRect = GUILayoutUtility.GetRect(288, 20, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Width(288), GUILayout.Height(20));
GUI.BeginGroup(progressRect);
GUI.DrawTextureWithTexCoords(new Rect(2, 0, 288, 20), TMP_UIStyleManager.progressTexture, new Rect(1 - m_renderingProgress, 0, 1, 1));
GUI.EndGroup();
// FONT STATUS & INFORMATION
GUILayout.Space(5);
EditorGUILayout.LabelField(output_feedback, TMP_UIStyleManager.TextAreaBoxWindow, GUILayout.Height(48), GUILayout.MaxWidth(290));
GUILayout.Space(10);
// SAVE TEXTURE & CREATE and SAVE FONT XML FILE
GUI.enabled = m_font_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Save TextMeshPro Font Asset", GUILayout.Width(290)) && GUI.enabled)
{
string filePath = string.Empty;
if (font_renderMode < RenderModes.DistanceField16) // == RenderModes.HintedSmooth || font_renderMode == RenderModes.RasterHinted)
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name, "asset");
if (filePath.Length == 0)
return;
Save_Normal_FontAsset(filePath);
}
else if (font_renderMode >= RenderModes.DistanceField16)
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
if (filePath.Length == 0)
return;
Save_SDF_FontAsset(filePath);
}
}
GUI.enabled = true; // Re-enable GUI
GUILayout.Space(5);
GUILayout.EndVertical();
GUILayout.Space(25);
/*
// GENERATE DISTANCE FIELD TEXTURE
GUILayout.Label("Distance Field Options", SectionLabel, GUILayout.Width(300));
GUILayout.BeginVertical(textureAreaBox, GUILayout.Width(300));
GUILayout.Space(5);
font_spread = EditorGUILayout.IntField("Spread", font_spread, GUILayout.Width(280));
font_scaledownFactor = EditorGUILayout.IntField("Scale down factor", font_scaledownFactor, GUILayout.Width(280));
if (GUI.changed)
{
EditorPrefs.SetInt("Font_Spread", font_spread);
EditorPrefs.SetInt("Font_ScaleDownFactor", font_scaledownFactor);
}
GUILayout.Space(20);
GUI.enabled = m_font_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Preview Distance Field Font Atlas", GUILayout.Width(290)))
{
if (m_font_Atlas != null && isProcessing == false)
{
// Generate Distance Field
int width = m_font_Atlas.width;
int height = m_font_Atlas.height;
Color[] colors = m_font_Atlas.GetPixels(); // Should modify this to use Color32 instead
isProcessing = true;
ThreadPool.QueueUserWorkItem(SomeTask => { TMPro_DistanceTransform.Generate(colors, width, height, font_spread, font_scaledownFactor); });
previewSelection = PreviewSelectionTypes.PreviewDistanceField;
}
}
GUILayout.Space(1);
progressRect = GUILayoutUtility.GetRect(290, 20, textAreaBox, GUILayout.Width(290), GUILayout.Height(20));
GUI.BeginGroup(progressRect);
GUI.DrawTextureWithTexCoords(new Rect(0, 0, 290, 20), progressTexture, new Rect(1 - ProgressPercentage, 0, 1, 1));
GUI.EndGroup();
//GUILayout.Space(5);
GUI.enabled = m_destination_Atlas != null ? true : false; // Enable Save Button if font_Atlas is not Null.
if (GUILayout.Button("Save TextMeshPro (SDF) Font Asset", GUILayout.Width(290)))
{
string filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", new FileInfo(AssetDatabase.GetAssetPath(font_TTF)).DirectoryName, font_TTF.name + " SDF", "asset");
if (filePath.Length == 0)
return;
Save_SDF_FontAsset(filePath);
}
GUILayout.EndVertical();
*/
// Figure out the size of the current UI Panel
Rect rect = EditorGUILayout.GetControlRect(false, 5);
if (Event.current.type == EventType.Repaint)
m_UI_Panel_Size = rect;
GUILayout.EndVertical();
}
void UpdateRenderFeedbackWindow()
{
font_size = m_font_faceInfo.pointSize;
string colorTag = m_font_faceInfo.characterCount == m_character_Count ? "<color=#C0ffff>" : "<color=#ffff00>";
string colorTag2 = "<color=#C0ffff>";
output_feedback = output_name_label + "<b>" + colorTag2 + m_font_faceInfo.name + "</color></b>";
if (output_feedback.Length > 60)
output_feedback += "\n" + output_size_label + "<b>" + colorTag2 + m_font_faceInfo.pointSize + "</color></b>";
else
output_feedback += " " + output_size_label + "<b>" + colorTag2 + m_font_faceInfo.pointSize + "</color></b>";
output_feedback += "\n" + output_count_label + "<b>" + colorTag + m_font_faceInfo.characterCount + "/" + m_character_Count + "</color></b>";
}
void CreateFontTexture()
{
m_font_Atlas = new Texture2D(font_atlas_width, font_atlas_height, TextureFormat.Alpha8, false, true);
m_font_Atlas.hideFlags = HideFlags.DontSave;
Color32[] colors = new Color32[font_atlas_width * font_atlas_height];
for (int i = 0; i < (font_atlas_width * font_atlas_height); i++)
{
byte c = m_texture_buffer[i];
colors[i] = new Color32(c, c, c, c);
}
if (font_renderMode == RenderModes.RasterHinted)
m_font_Atlas.filterMode = FilterMode.Point;
m_font_Atlas.SetPixels32(colors, 0);
m_font_Atlas.Apply(false, false);
// Saving File for Debug
//var pngData = m_font_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData);
UpdateEditorWindowSize(m_font_Atlas.width, m_font_Atlas.height);
//previewSelection = PreviewSelectionTypes.PreviewFont;
}
void Save_Normal_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
if (filePath.IndexOf(dataPath) == -1)
{
Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
return;
}
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
TextMeshProFont font_asset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TextMeshProFont)) as TextMeshProFont;
if (font_asset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
font_asset = ScriptableObject.CreateInstance<TextMeshProFont>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(font_asset, tex_Path_NoExt + ".asset");
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, 1);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, 1);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = Shader.Find("TMPro/Bitmap");
Material tmp_material = new Material(default_Shader);
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_font_Atlas);
font_asset.material = tmp_material;
tmp_material.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(tmp_material, font_asset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TMPro_EditorUtility.FindMaterialReferences(font_asset.material);
// Destroy Assets that will be replaced.
DestroyImmediate(font_asset.atlas, true);
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, 1);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, 1);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Update the Texture reference on the Material
for (int i = 0; i < material_references.Length; i++)
{
material_references[i].SetTexture(ShaderUtilities.ID_MainTex, font_asset.atlas);
}
}
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(font_asset)); // Re-import font asset to get the new updated version.
//EditorUtility.SetDirty(font_asset);
font_asset.ReadFontDefinition();
AssetDatabase.Refresh();
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, font_asset);
}
void Save_SDF_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
if (filePath.IndexOf(dataPath) == -1)
{
Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
return;
}
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
TextMeshProFont font_asset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TextMeshProFont)) as TextMeshProFont;
if (font_asset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
font_asset = ScriptableObject.CreateInstance<TextMeshProFont>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(font_asset, tex_Path_NoExt + ".asset");
if (m_destination_Atlas != null)
m_font_Atlas = m_destination_Atlas;
// If using the C# SDF creation mode, we need the scaledown factor.
int scaleDownFactor = font_renderMode >= RenderModes.DistanceField16 ? 1 : font_scaledownFactor;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, scaleDownFactor);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, scaleDownFactor);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Line Breaking Rules
//LineBreakingTable lineBreakingTable = new LineBreakingTable();
//
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = Shader.Find("TMPro/Distance Field");
Material tmp_material = new Material(default_Shader);
//tmp_material.shaderKeywords = new string[] { "BEVEL_OFF", "GLOW_OFF", "UNDERLAY_OFF" };
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_font_Atlas);
tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, m_font_Atlas.width);
tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, m_font_Atlas.height);
tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, font_asset.NormalStyle);
tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, font_asset.BoldStyle);
int spread = font_renderMode >= RenderModes.DistanceField16 ? font_padding + 1 : font_spread;
tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
font_asset.material = tmp_material;
tmp_material.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(tmp_material, font_asset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TMPro_EditorUtility.FindMaterialReferences(font_asset.material);
// Destroy Assets that will be replaced.
DestroyImmediate(font_asset.atlas, true);
int scaleDownFactor = font_renderMode >= RenderModes.DistanceField16 ? 1 : font_scaledownFactor;
// Add FaceInfo to Font Asset
FaceInfo face = GetFaceInfo(m_font_faceInfo, scaleDownFactor);
font_asset.AddFaceInfo(face);
// Add GlyphInfo[] to Font Asset
GlyphInfo[] glyphs = GetGlyphInfo(m_font_glyphInfo, scaleDownFactor);
font_asset.AddGlyphInfo(glyphs);
// Get and Add Kerning Pairs to Font Asset
if (includeKerningPairs)
{
string fontFilePath = AssetDatabase.GetAssetPath(font_TTF);
KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);
font_asset.AddKerningInfo(kerningTable);
}
// Add Font Atlas as Sub-Asset
font_asset.atlas = m_font_Atlas;
m_font_Atlas.name = tex_FileName + " Atlas";
m_font_Atlas.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(m_font_Atlas, font_asset);
// Update the Texture reference on the Material
for (int i = 0; i < material_references.Length; i++)
{
material_references[i].SetTexture(ShaderUtilities.ID_MainTex, font_asset.atlas);
material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, m_font_Atlas.width);
material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, m_font_Atlas.height);
material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, font_asset.NormalStyle);
material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, font_asset.BoldStyle);
int spread = font_renderMode >= RenderModes.DistanceField16 ? font_padding + 1 : font_spread;
material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
}
}
// Saving File for Debug
//var pngData = destination_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData);
//font_asset.fontCreationSettings = SaveFontCreationSettings();
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(font_asset)); // Re-import font asset to get the new updated version.
font_asset.ReadFontDefinition();
AssetDatabase.Refresh();
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, font_asset);
}
FontCreationSetting SaveFontCreationSettings()
{
FontCreationSetting settings = new FontCreationSetting();
settings.fontSourcePath = AssetDatabase.GetAssetPath(font_TTF);
settings.fontSizingMode = FontSizingOption_Selection;
settings.fontSize = font_size;
settings.fontPadding = font_padding;
settings.fontPackingMode = (int)m_fontPackingSelection;
settings.fontAtlasWidth = font_atlas_width;
settings.fontAtlasHeight = font_atlas_height;
settings.fontCharacterSet = font_CharacterSet_Selection;
settings.fontStyle = (int)font_style;
settings.fontStlyeModifier = font_style_mod;
settings.fontRenderMode = (int)font_renderMode;
settings.fontKerning = includeKerningPairs;
return settings;
}
void UpdateEditorWindowSize(float width, float height)
{
m_previewWindow_Size = new Vector2(768, 768);
if (width > height)
{
m_previewWindow_Size = new Vector2(768, height / (width / 768));
}
else if (height > width)
{
m_previewWindow_Size = new Vector2(width / (height / 768), 768);
}
m_editorWindow.minSize = new Vector2(m_previewWindow_Size.x + 330, Mathf.Max(m_UI_Panel_Size.y + 20f, m_previewWindow_Size.y + 20f));
m_editorWindow.maxSize = m_editorWindow.minSize + new Vector2(.25f, 0);
}
void DrawPreview()
{
// Display Texture Area
GUILayout.BeginVertical(TMP_UIStyleManager.TextureAreaBox);
Rect pixelRect = GUILayoutUtility.GetRect(m_previewWindow_Size.x, m_previewWindow_Size.y, TMP_UIStyleManager.Section_Label);
if (m_destination_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewDistanceField)
{
EditorGUI.DrawTextureAlpha(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_destination_Atlas, ScaleMode.ScaleToFit);
}
//else if (m_texture_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewTexture)
//{
// GUI.DrawTexture(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_texture_Atlas, ScaleMode.ScaleToFit);
//}
else if (m_font_Atlas != null && previewSelection == PreviewSelectionTypes.PreviewFont)
{
EditorGUI.DrawTextureAlpha(new Rect(pixelRect.x, pixelRect.y, m_previewWindow_Size.x, m_previewWindow_Size.y), m_font_Atlas, ScaleMode.ScaleToFit);
}
GUILayout.EndVertical();
}
// Convert from FT_FaceInfo to FaceInfo
FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
{
FaceInfo face = new FaceInfo();
face.Name = ft_face.name;
face.PointSize = (float)ft_face.pointSize / scaleFactor;
face.Padding = 0; // ft_face.padding / scaleFactor;
face.LineHeight = ft_face.lineHeight / scaleFactor;
face.Baseline = 0;
face.Ascender = ft_face.ascender / scaleFactor;
face.Descender = ft_face.descender / scaleFactor;
face.CenterLine = ft_face.centerLine / scaleFactor;
face.Underline = ft_face.underline / scaleFactor;
face.UnderlineThickness = ft_face.underlineThickness == 0 ? 5 : ft_face.underlineThickness / scaleFactor; // Set Thickness to 5 if TTF value is Zero.
face.SuperscriptOffset = face.Ascender;
face.SubscriptOffset = face.Underline;
face.SubSize = 0.5f;
face.CharacterCount = ft_face.characterCount;
face.AtlasWidth = ft_face.atlasWidth / scaleFactor;
face.AtlasHeight = ft_face.atlasHeight / scaleFactor;
return face;
}
// Convert from FT_GlyphInfo[] to GlyphInfo[]
GlyphInfo[] GetGlyphInfo(FT_GlyphInfo[] ft_glyphs, int scaleFactor)
{
GlyphInfo[] glyphs = new GlyphInfo[ft_glyphs.Length];
m_kerningSet = new int[ft_glyphs.Length];
for (int i = 0; i < ft_glyphs.Length; i++)
{
GlyphInfo g = new GlyphInfo();
g.id = ft_glyphs[i].id;
g.x = ft_glyphs[i].x / scaleFactor;
g.y = ft_glyphs[i].y / scaleFactor;
g.width = ft_glyphs[i].width / scaleFactor;
g.height = ft_glyphs[i].height / scaleFactor;
g.xOffset = ft_glyphs[i].xOffset / scaleFactor;
g.yOffset = ft_glyphs[i].yOffset / scaleFactor;
g.xAdvance = ft_glyphs[i].xAdvance / scaleFactor;
glyphs[i] = g;
m_kerningSet[i] = g.id;
}
return glyphs;
}
// Get Kerning Pairs
public KerningTable GetKerningTable(string fontFilePath, int pointSize)
{
KerningTable kerningInfo = new KerningTable();
kerningInfo.kerningPairs = new List<KerningPair>();
// Temporary Array to hold the kerning paris from the Native Plugin.
FT_KerningPair[] kerningPairs = new FT_KerningPair[1000];
int kpCount = TMPro_FontPlugin.FT_GetKerningPairs(fontFilePath, m_kerningSet, m_kerningSet.Length, kerningPairs);
for (int i = 0; i < kpCount; i++)
{
// Proceed to add each kerning pairs.
KerningPair kp = new KerningPair(kerningPairs[i].ascII_Left, kerningPairs[i].ascII_Right, kerningPairs[i].xAdvanceOffset * pointSize);
kerningInfo.kerningPairs.Add(kp);
}
return kerningInfo;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: a7a3d2105d504af41bc244c1183faf43
timeCreated: 1480605657
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshProFont))]
public class TMPro_FontEditor : Editor
{
private struct UI_PanelState
{
public static bool fontInfoPanel = true;
public static bool glyphInfoPanel = false;
public static bool kerningInfoPanel = true;
}
private int m_page = 0;
private const string k_UndoRedo = "UndoRedoPerformed";
private SerializedProperty font_atlas_prop;
private SerializedProperty font_material_prop;
private SerializedProperty font_normalStyle_prop;
private SerializedProperty font_boldStyle_prop;
private SerializedProperty font_italicStyle_prop;
private SerializedProperty font_tabSize_prop;
private SerializedProperty m_fontInfo_prop;
private SerializedProperty m_glyphInfoList_prop;
private SerializedProperty m_kerningInfo_prop;
private KerningTable m_kerningTable;
private SerializedProperty m_kerningPair_prop;
private TextMeshProFont m_fontAsset;
private bool isAssetDirty = false;
private int errorCode;
private System.DateTime timeStamp;
private string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" };
public void OnEnable()
{
font_atlas_prop = serializedObject.FindProperty("atlas");
font_material_prop = serializedObject.FindProperty("material");
font_normalStyle_prop = serializedObject.FindProperty("NormalStyle");
font_boldStyle_prop = serializedObject.FindProperty("BoldStyle");
font_italicStyle_prop = serializedObject.FindProperty("ItalicStyle");
font_tabSize_prop = serializedObject.FindProperty("TabSize");
m_fontInfo_prop = serializedObject.FindProperty("m_fontInfo");
m_glyphInfoList_prop = serializedObject.FindProperty("m_glyphInfoList");
m_kerningInfo_prop = serializedObject.FindProperty("m_kerningInfo");
m_kerningPair_prop = serializedObject.FindProperty("m_kerningPair");
//m_isGlyphInfoListExpanded_prop = serializedObject.FindProperty("isGlyphInfoListExpanded");
//m_isKerningTableExpanded_prop = serializedObject.FindProperty("isKerningTableExpanded");
m_fontAsset = target as TextMeshProFont;
m_kerningTable = m_fontAsset.kerningInfo;
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
}
public override void OnInspectorGUI()
{
//Debug.Log("OnInspectorGUI Called.");
Event evt = Event.current;
serializedObject.Update();
GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", TMP_UIStyleManager.Section_Label);
// TextMeshPro Font Info Panel
GUILayout.Label("Face Info", TMP_UIStyleManager.Section_Label);
EditorGUI.indentLevel = 1;
GUI.enabled = false; // Lock UI
EditorGUIUtility.labelWidth = 135;
//EditorGUIUtility.fieldWidth = 80;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize"));
GUI.enabled = true;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight"));
//GUI.enabled = false;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline"));
GUI.enabled = true;
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline"));
//EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("UnderlineThickness"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset"));
SerializedProperty subSize_prop = m_fontInfo_prop.FindPropertyRelative("SubSize");
EditorGUILayout.PropertyField(subSize_prop);
subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f);
GUI.enabled = false;
//EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding"));
//GUILayout.Label("Atlas Size");
EditorGUI.indentLevel = 1;
GUILayout.Space(18);
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width"));
EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height"));
GUI.enabled = true;
EditorGUI.indentLevel = 0;
GUILayout.Space(20);
GUILayout.Label("Font Sub-Assets", TMP_UIStyleManager.Section_Label);
GUI.enabled = false;
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:"));
EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:"));
GUI.enabled = true;
// Font SETTINGS
GUILayout.Space(10);
GUILayout.Label("Face Style", TMP_UIStyleManager.Section_Label);
string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal weight"));
font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
Material mat = font_material_prop.objectReferenceValue as Material;
mat.SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
}
//Rect rect = EditorGUILayout.GetControlRect();
EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold weight"));
font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
Material mat = font_material_prop.objectReferenceValue as Material;
mat.SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: "));
font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);
EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple: "));
EditorGUILayout.EndHorizontal();
GUILayout.Space(10);
EditorGUI.indentLevel = 0;
if (GUILayout.Button("Glyph Info \t\t\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel;
if (UI_PanelState.glyphInfoPanel)
{
//Rect lastRect = GUILayoutUtility.GetLastRect();
int arraySize = m_glyphInfoList_prop.arraySize;
int itemsPerPage = 15;
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_page; i < arraySize && i < itemsPerPage * (m_page + 1); i++)
{
SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(i);
EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);
EditorGUILayout.PropertyField(glyphInfo);
EditorGUILayout.EndVertical();
}
}
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 2;
int shiftMultiplier = evt.shift ? 10 : 1;
if (m_page > 0) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Previous Page"))
m_page -= 1 * shiftMultiplier;
pagePos.x += pagePos.width;
if (itemsPerPage * (m_page + 1) < arraySize) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Next Page"))
m_page += 1 * shiftMultiplier;
m_page = Mathf.Clamp(m_page, 0, arraySize / itemsPerPage);
}
// KERNING TABLE PANEL
if (GUILayout.Button("Kerning Table Info\t\t\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel;
if (UI_PanelState.kerningInfoPanel)
{
Rect pos;
SerializedProperty kerningPairs_prop = m_kerningInfo_prop.FindPropertyRelative("kerningPairs");
int pairCount = kerningPairs_prop.arraySize;
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Left Char", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label("Right Char", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label("Offset Value", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.Label(GUIContent.none, GUILayout.Width(20));
EditorGUILayout.EndHorizontal();
GUILayout.BeginVertical(TMP_UIStyleManager.TMP_GUISkin.label);
for (int i = 0; i < pairCount; i++)
{
SerializedProperty kerningPair_prop = kerningPairs_prop.GetArrayElementAtIndex(i);
pos = EditorGUILayout.BeginHorizontal();
EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), kerningPair_prop, GUIContent.none);
// Button to Delete Kerning Pair
if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
{
m_kerningTable.RemoveKerningPair(i);
m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
serializedObject.Update(); // Get an updated version of the SerializedObject.
isAssetDirty = true;
break;
}
EditorGUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.Space(10);
// Add New Kerning Pair Section
GUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G);
pos = EditorGUILayout.BeginHorizontal();
// Draw Empty Kerning Pair
EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), m_kerningPair_prop);
GUILayout.Label(GUIContent.none, GUILayout.Height(19));
EditorGUILayout.EndHorizontal();
GUILayout.Space(5);
if (GUILayout.Button("Add New Kerning Pair"))
{
int asci_left = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue;
int asci_right = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue;
float xOffset = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue;
errorCode = m_kerningTable.AddKerningPair(asci_left, asci_right, xOffset);
// Sort Kerning Pairs & Reload Font Asset if new kerpair was added.
if (errorCode != -1)
{
m_kerningTable.SortKerningPairs();
m_fontAsset.ReadFontDefinition(); // Reload Font Definition.
serializedObject.Update(); // Get an updated version of the SerializedObject.
isAssetDirty = true;
}
else
{
timeStamp = System.DateTime.Now.AddSeconds(5);
}
}
if (errorCode == -1)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.TMP_GUISkin.label);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (System.DateTime.Now > timeStamp)
errorCode = 0;
}
GUILayout.EndVertical();
}
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
{
//Debug.Log("Serialized properties have changed.");
TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
isAssetDirty = false;
EditorUtility.SetDirty(target);
//TMPro_EditorUtility.RepaintAll(); // Consider SetDirty
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 6c1543462143bfd4c9b4e6b54f564ae0
timeCreated: 1478780257
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
using System.Runtime.InteropServices;
namespace TMPro.EditorUtilities
{
public class TMPro_FontPlugin
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void DebugLog(string log);
private static readonly DebugLog debugLog = DebugWrapper;
private static readonly IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(debugLog);
private static void DebugWrapper(string log)
{
Debug.Log(log);
}
public static void LinkDebugLog()
{
LinkDebug(functionPointer);
}
[DllImport("TMPro_Plugin")]
private static extern void LinkDebug([MarshalAs(UnmanagedType.FunctionPtr)]IntPtr debugCall);
[DllImport("TMPro_Plugin")]
public static extern
int Initialize_FontEngine();
[DllImport("TMPro_Plugin")]
public static extern
int Destroy_FontEngine();
[DllImport("TMPro_Plugin")]
public static extern
int Load_TrueType_Font(string fontPath);
[DllImport("TMPro_Plugin")]
public static extern
int FT_Size_Font(int fontSize);
[DllImport("TMPro_Plugin")]
public static extern
int Render_Character(byte[] buffer_fill, byte[] buffer_edge, int buffer_width, int buffer_height, int offset, int asc, FaceStyles style, float thickness, RenderModes rasterMode, ref FT_GlyphInfo glyphInfo);
[DllImport("TMPro_Plugin")]
public static extern
int Render_Characters(byte[] buffer, int buffer_width, int buffer_height, int character_padding, int[] asc_set, int char_count, FaceStyles style, float style_mod, bool autoSize, RenderModes renderMode, int method, ref FT_FaceInfo fontData, FT_GlyphInfo[] Output);
[DllImport("TMPro_Plugin")]
public static extern
int FT_GetKerningPairs(string fontPath, int[] characterSet, int setCount, FT_KerningPair[] kerningPairs);
[DllImport("TMPro_Plugin")]
public static extern
float Check_RenderProgress();
}
public enum FaceStyles { Normal, Bold, Italic, Bold_Italic, Outline, Bold_Sim };
public enum RenderModes { HintedSmooth = 0, Smooth = 1, RasterHinted = 2, Raster = 3, DistanceField16 = 6, DistanceField32 = 7 }; // SignedDistanceField64 = 8
[StructLayout(LayoutKind.Sequential)]
public struct FT_KerningPair
{
public int ascII_Left;
public int ascII_Right;
public float xAdvanceOffset;
}
[StructLayout(LayoutKind.Sequential)]
public struct FT_GlyphInfo
{
public int id;
public float x;
public float y;
public float width;
public float height;
public float xOffset;
public float yOffset;
public float xAdvance;
}
[StructLayout(LayoutKind.Sequential)]
public struct FT_FaceInfo
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string name;
public int pointSize;
public int padding;
public float lineHeight;
public float baseline;
public float ascender;
public float descender;
public float centerLine;
public float underline;
public float underlineThickness;
public int characterCount;
public int atlasWidth;
public int atlasHeight;
}
}
fileFormatVersion: 2
guid: 4edbb63168f708c4ab4ac69d7605c50a
timeCreated: 1478780257
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
using TMPro;
using TMPro.EditorUtilities;
public class TMPro_SDFMaterialEditor : MaterialEditor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool face = true;
public static bool outline = true;
public static bool underlay = false;
public static bool bevel = false;
public static bool light = false;
public static bool bump = false;
public static bool env = false;
public static bool glow = false;
public static bool debug = false;
}
private enum FoldoutType { face, outline, underlay, bevel, light, bump, env, glow, debug };
//private static PropertyModification m_modifiedProperties;
private static int m_eventID;
//private Material m_targetMaterial;
// Face Properties
private MaterialProperty m_faceColor;
private MaterialProperty m_faceTex;
private MaterialProperty m_faceUVSpeedX;
private MaterialProperty m_faceUVSpeedY;
private MaterialProperty m_faceDilate;
private MaterialProperty m_faceShininess;
//private MaterialProperty m_faceSoftness;
// Outline Properties
private MaterialProperty m_outlineColor;
private MaterialProperty m_outlineTex;
private MaterialProperty m_outlineUVSpeedX;
private MaterialProperty m_outlineUVSpeedY;
private MaterialProperty m_outlineThickness;
private MaterialProperty m_outlineSoftness;
private MaterialProperty m_outlineShininess;
// Properties Related to Bevel Options
private MaterialProperty m_bevel;
private MaterialProperty m_bevelOffset;
private MaterialProperty m_bevelWidth;
private MaterialProperty m_bevelClamp;
private MaterialProperty m_bevelRoundness;
// Properties for the Underlay Options
private MaterialProperty m_underlayColor;
private MaterialProperty m_underlayOffsetX;
private MaterialProperty m_underlayOffsetY;
private MaterialProperty m_underlayDilate;
private MaterialProperty m_underlaySoftness;
// Properties for Simulated Lighting
private MaterialProperty m_lightAngle;
private MaterialProperty m_specularColor;
private MaterialProperty m_specularPower;
private MaterialProperty m_reflectivity;
private MaterialProperty m_diffuse;
private MaterialProperty m_ambientLight;
// Bump Mapping Options
private MaterialProperty m_bumpMap;
private MaterialProperty m_bumpFace;
private MaterialProperty m_bumpOutline;
// Properties for Environmental Mapping
private MaterialProperty m_reflectFaceColor;
private MaterialProperty m_reflectOutlineColor;
private MaterialProperty m_reflectTex;
private MaterialProperty m_reflectRotation;
//private MaterialProperty m_envTiltX;
//private MaterialProperty m_envTiltY;
//private MaterialProperty m_envMatrix;
private MaterialProperty m_specColor;
// Properties for Glow Options
private MaterialProperty m_glowColor;
private MaterialProperty m_glowInner;
private MaterialProperty m_glowOffset;
private MaterialProperty m_glowPower;
private MaterialProperty m_glowOuter;
// Hidden properties used for debug
private MaterialProperty m_mainTex;
private MaterialProperty m_texSampleWidth;
private MaterialProperty m_texSampleHeight;
private MaterialProperty m_gradientScale;
private MaterialProperty m_scaleX;
private MaterialProperty m_scaleY;
private MaterialProperty m_PerspectiveFilter;
private MaterialProperty m_vertexOffsetX;
private MaterialProperty m_vertexOffsetY;
private MaterialProperty m_maskCoord;
private MaterialProperty m_maskSoftnessX;
private MaterialProperty m_maskSoftnessY;
// Stencil Properties
private MaterialProperty m_stencilID;
private MaterialProperty m_stencilOp;
private MaterialProperty m_stencilComp;
//private MaterialProperty m_weightNormal;
//private MaterialProperty m_weightBold;
private MaterialProperty m_shaderFlags; // _ShaderFlag useed to determine bevel type.
private MaterialProperty m_scaleRatio_A;
private MaterialProperty m_scaleRatio_B;
private MaterialProperty m_scaleRatio_C;
// Private Fields
private enum Bevel_Types { OuterBevel = 0, InnerBevel = 1 };
private enum Mask_Type { MaskOff = 0, MaskHard = 1, MaskSoft = 2 };
private string[] m_bevelOptions = { "Outer Bevel", "Inner Bevel", "--" };
private int m_bevelSelection;
private Mask_Type m_mask;
private enum Underlay_Types { Normal = 0, Inner = 1};
private Underlay_Types m_underlaySelection = Underlay_Types.Normal;
private string[] m_Keywords;
private Vector3 m_matrixRotation;
private bool isRatiosEnabled;
private bool isBevelEnabled;
private bool isGlowEnabled;
private bool isBumpEnabled;
private bool isEnvEnabled;
private bool isUnderlayEnabled;
private bool havePropertiesChanged = false;
//private TextMeshPro m_textMeshPro;
//private TextMeshProUGUI m_textMeshProUGUI;
private Rect m_inspectorStartRegion;
private Rect m_inspectorEndRegion;
public override void OnEnable()
{
base.OnEnable();
//Debug.Log("New Instance of SDF Material Editor with ID " + this.GetInstanceID());
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
// Get a reference to the TextMeshPro or TextMeshProUGUI object if possible
//if (Selection.activeGameObject != null)
//{
// if (Selection.activeGameObject.GetComponent<TextMeshPro>() != null)
// {
// m_textMeshPro = Selection.activeGameObject.GetComponent<TextMeshPro>();
// }
// else
// {
// m_textMeshProUGUI = Selection.activeGameObject.GetComponent<TextMeshProUGUI>();
// }
//}
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
}
public override void OnDisable()
{
//Debug.Log("OnDisable() called.");
// Remove Undo / Redo Event Listeners.
base.OnDisable();
Undo.undoRedoPerformed -= OnUndoRedo;
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
// if we are not visible... return
//if (!isVisible)
// return;
ReadMaterialProperties();
Material targetMaterial = target as Material;
// If multiple materials have been selected and are not using the same shader, we simply return.
if (targets.Length > 1)
{
for (int i = 0; i < targets.Length; i++)
{
Material mat = targets[i] as Material;
if (targetMaterial.shader != mat.shader)
{
return;
}
}
}
// Retrieve Shader Multi_Compile Keywords
m_Keywords = targetMaterial.shaderKeywords;
isBevelEnabled = m_Keywords.Contains("BEVEL_ON");
isGlowEnabled = m_Keywords.Contains("GLOW_ON");
//isUnderlayEnabled = m_Keywords.Contains("UNDERLAY_ON") | m_Keywords.Contains("UNDERLAY_INNER");
isRatiosEnabled = !m_Keywords.Contains("RATIOS_OFF");
if (m_Keywords.Contains("UNDERLAY_ON"))
{
isUnderlayEnabled = true;
m_underlaySelection = Underlay_Types.Normal;
}
else if (m_Keywords.Contains("UNDERLAY_INNER"))
{
isUnderlayEnabled = true;
m_underlaySelection = Underlay_Types.Inner;
}
else
isUnderlayEnabled = false;
if (m_Keywords.Contains("MASK_HARD")) m_mask = Mask_Type.MaskHard;
else if (m_Keywords.Contains("MASK_SOFT")) m_mask = Mask_Type.MaskSoft;
else m_mask = Mask_Type.MaskOff;
if (m_shaderFlags.hasMixedValue)
m_bevelSelection = 2;
else
m_bevelSelection = (int)m_shaderFlags.floatValue & 1;
// Define the Drag-n-Drop Region (Start)
m_inspectorStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check if Shader selection is compatible with Font Asset
// TODO
EditorGUIUtility.LookLikeControls(130, 50);
// FACE PANEL
EditorGUI.indentLevel = 0;
if (GUILayout.Button("<b>Face</b> - <i>Settings</i> -", TMP_UIStyleManager.Group_Label))
m_foldout.face = !m_foldout.face;
if (m_foldout.face)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
ColorProperty(m_faceColor, "Color");
if (targetMaterial.HasProperty("_FaceTex"))
{
DrawTextureProperty(m_faceTex, "Texture");
DrawUVProperty(new MaterialProperty[] { m_faceUVSpeedX, m_faceUVSpeedY }, "UV Speed");
}
DrawRangeProperty(m_outlineSoftness, "Softness");
DrawRangeProperty(m_faceDilate, "Dilate");
if (targetMaterial.HasProperty("_FaceShininess")) DrawRangeProperty(m_faceShininess, "Gloss");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
// OUTLINE PANEL
EditorGUI.indentLevel = 0;
if (GUILayout.Button("<b>Outline</b> - <i>Settings</i> -", TMP_UIStyleManager.Group_Label))
m_foldout.outline = !m_foldout.outline;
if (m_foldout.outline)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
ColorProperty(m_outlineColor, "Color");
if (targetMaterial.HasProperty("_OutlineTex"))
{
DrawTextureProperty(m_outlineTex, "Texture");
DrawUVProperty(new MaterialProperty[] { m_outlineUVSpeedX, m_outlineUVSpeedY }, "UV Speed");
}
DrawRangeProperty(m_outlineThickness, "Thickness");
if (targetMaterial.HasProperty("_OutlineShininess")) DrawRangeProperty(m_outlineShininess, "Gloss");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
// UNDERLAY PANEL
if (targetMaterial.HasProperty("_UnderlayColor"))
{
string underlayKeyword = m_underlaySelection == Underlay_Types.Normal ? "UNDERLAY_ON" : "UNDERLAY_INNER";
isUnderlayEnabled = DrawTogglePanel(FoldoutType.underlay, "<b>Underlay</b> - <i>Settings</i> -", isUnderlayEnabled, underlayKeyword);
if (m_foldout.underlay)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
m_underlaySelection = (Underlay_Types)EditorGUILayout.EnumPopup("Underlay Type", m_underlaySelection);
if (GUI.changed) SetUnderlayKeywords();
ColorProperty(m_underlayColor, "Color");
DrawRangeProperty(m_underlayOffsetX, "OffsetX");
DrawRangeProperty(m_underlayOffsetY, "OffsetY");
DrawRangeProperty(m_underlayDilate, "Dilate");
DrawRangeProperty(m_underlaySoftness, "Softness");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// BEVEL PANEL
if (targetMaterial.HasProperty("_Bevel"))
{
isBevelEnabled = DrawTogglePanel(FoldoutType.bevel, "<b>Bevel</b> - <i>Settings</i> -", isBevelEnabled, "BEVEL_ON");
if (m_foldout.bevel)
{
EditorGUI.indentLevel = 1;
GUI.changed = false;
m_bevelSelection = EditorGUILayout.Popup("Type", m_bevelSelection, m_bevelOptions) & 1;
if (GUI.changed)
{
havePropertiesChanged = true;
m_shaderFlags.floatValue = m_bevelSelection;
}
EditorGUI.BeginChangeCheck();
DrawRangeProperty(m_bevel, "Amount");
DrawRangeProperty(m_bevelOffset, "Offset");
DrawRangeProperty(m_bevelWidth, "Width");
DrawRangeProperty(m_bevelRoundness, "Roundness");
DrawRangeProperty(m_bevelClamp, "Clamp");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// LIGHTING PANEL
if (targetMaterial.HasProperty("_SpecularColor") || targetMaterial.HasProperty("_SpecColor"))
{
isBevelEnabled = DrawTogglePanel(FoldoutType.light, "<b>Lighting</b> - <i>Settings</i> -", isBevelEnabled, "BEVEL_ON");
if (m_foldout.light)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
if (targetMaterial.HasProperty("_LightAngle"))
{ // Non Surface Shader
DrawRangeProperty(m_lightAngle, "Light Angle");
ColorProperty(m_specularColor, "Specular Color");
DrawRangeProperty(m_specularPower, "Specular Power");
DrawRangeProperty(m_reflectivity, "Reflectivity Power");
DrawRangeProperty(m_diffuse, "Diffuse Shadow");
DrawRangeProperty(m_ambientLight, "Ambient Shadow");
}
else
ColorProperty(m_specColor, "Specular Color");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// BUMPMAP PANEL
if (targetMaterial.HasProperty("_BumpMap"))
{
isBevelEnabled = DrawTogglePanel(FoldoutType.bump, "<b>BumpMap</b> - <i>Settings</i> -", isBevelEnabled, "BEVEL_ON");
if (m_foldout.bump)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
DrawTextureProperty(m_bumpMap, "Texture");
DrawRangeProperty(m_bumpFace, "Face");
DrawRangeProperty(m_bumpOutline, "Outline");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// ENVMAP PANEL
if (targetMaterial.HasProperty("_Cube"))
{
isBevelEnabled = DrawTogglePanel(FoldoutType.env, "<b>EnvMap</b> - <i>Settings</i> -", isBevelEnabled, "BEVEL_ON");
if (m_foldout.env)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
ColorProperty(m_reflectFaceColor, "Face Color");
ColorProperty(m_reflectOutlineColor, "Outline Color");
DrawTextureProperty(m_reflectTex, "Texture");
if (targetMaterial.HasProperty("_Cube"))
{
DrawVectorProperty(m_reflectRotation, "EnvMap Rotation");
//var matrix = targetMaterial.GetMatrix("_EnvMatrix");
}
if (EditorGUI.EndChangeCheck())
{
//var m = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(m_matrixRotation), new Vector3(1f, 1f, 1f));
//targetMaterial.SetMatrix("_EnvMatrix", m);
havePropertiesChanged = true;
}
}
}
// GLOW PANEL
if (targetMaterial.HasProperty("_GlowColor"))
{
isGlowEnabled = DrawTogglePanel(FoldoutType.glow, "<b>Glow</b> - <i>Settings</i> -", isGlowEnabled, "GLOW_ON");
if (m_foldout.glow)
{
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel = 1;
ColorProperty(m_glowColor, "Color");
DrawRangeProperty(m_glowOffset, "Offset");
DrawRangeProperty(m_glowInner, "Inner");
DrawRangeProperty(m_glowOuter, "Outer");
DrawRangeProperty(m_glowPower, "Power");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// DEBUG PANEL
if (targetMaterial.HasProperty("_GradientScale"))
{
EditorGUI.indentLevel = 0;
if (GUILayout.Button("<b>Debug</b> - <i>Settings</i> -", TMP_UIStyleManager.Group_Label))
m_foldout.debug = !m_foldout.debug;
if (m_foldout.debug)
{
EditorGUI.indentLevel = 1;
EditorGUI.BeginChangeCheck();
DrawTextureProperty(m_mainTex, "Font Atlas");
DrawFloatProperty(m_gradientScale, "Gradient Scale");
DrawFloatProperty(m_texSampleWidth, "Texture Width");
DrawFloatProperty(m_texSampleHeight, "Texture Height");
GUILayout.Space(20);
DrawFloatProperty(m_scaleX, "Scale X");
DrawFloatProperty(m_scaleY, "Scale Y");
DrawRangeProperty(m_PerspectiveFilter, "Perspective Filter");
GUILayout.Space(20);
DrawFloatProperty(m_vertexOffsetX, "Offset X");
DrawFloatProperty(m_vertexOffsetY, "Offset Y");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
// Mask
if (targetMaterial.HasProperty("_MaskCoord"))
{
GUILayout.Space(15);
m_mask = (Mask_Type)EditorGUILayout.EnumPopup("Mask", m_mask);
if (GUI.changed)
{
havePropertiesChanged = true;
SetMaskKeywords(m_mask);
}
if (m_mask != Mask_Type.MaskOff)
{
EditorGUI.BeginChangeCheck();
Draw2DBoundsProperty(m_maskCoord, "Mask Bounds");
DrawFloatProperty(m_maskSoftnessX, "Softness X");
DrawFloatProperty(m_maskSoftnessY, "Softness Y");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
GUILayout.Space(15);
}
GUILayout.Space(20);
// Stencil
if (targetMaterial.HasProperty("_Stencil"))
{
FloatProperty(m_stencilID, "Stencil ID");
FloatProperty(m_stencilComp, "Stencil Comp");
FloatProperty(m_stencilOp, "Stencil Op");
}
GUILayout.Space(20);
// Ratios
GUI.changed = false;
isRatiosEnabled = EditorGUILayout.Toggle("Enable Ratios?", isRatiosEnabled);
if (GUI.changed)
{
SetKeyword(!isRatiosEnabled, "RATIOS_OFF");
}
EditorGUI.BeginChangeCheck();
DrawFloatProperty(m_scaleRatio_A, "Scale Ratio A");
DrawFloatProperty(m_scaleRatio_B, "Scale Ratio B");
DrawFloatProperty(m_scaleRatio_C, "Scale Ratio C");
if (EditorGUI.EndChangeCheck()) havePropertiesChanged = true;
}
}
// Define the Drag-n-Drop Region (End)
m_inspectorEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Handle Material Drag-n-Drop
DragAndDropGUI();
if (havePropertiesChanged)
{
//Debug.Log("Material Editor properties have changed. Target is " + target.name);
havePropertiesChanged = false;
PropertiesChanged();
EditorUtility.SetDirty(target);
//TMPro_EditorUtility.RepaintAll(); // Look into using SetDirty.
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, target as Material);
}
}
private void DragAndDropGUI()
{
Event evt = Event.current;
Rect dropArea = new Rect(m_inspectorStartRegion.x, m_inspectorStartRegion.y, m_inspectorEndRegion.width, m_inspectorEndRegion.y - m_inspectorStartRegion.y);
switch (evt.type)
{
case EventType.DragUpdated:
case EventType.DragPerform:
if (!dropArea.Contains(evt.mousePosition))
break;
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
// Do something
Material currentMaterial = target as Material;
Material newMaterial = DragAndDrop.objectReferences[0] as Material;
//Debug.Log("Drag-n-Drop Material is " + newMaterial + ". Target Material is " + currentMaterial); // + ". Canvas Material is " + m_uiRenderer.GetMaterial() );
// Check to make sure we have a valid material and that the font atlases match.
if (!newMaterial || newMaterial == currentMaterial || newMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != currentMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
if (newMaterial && newMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != currentMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
Debug.LogWarning("Drag-n-Drop Material [" + newMaterial.name + "]'s Atlas does not match the Atlas of the currently assigned Font Asset's Atlas.");
break;
}
// Check if this material is assigned to an object and active.
GameObject go = Selection.activeGameObject;
if (go != null && !go.activeInHierarchy)
{
if (go.GetComponent<TextMeshPro>() != null)
{
Undo.RecordObject(go.GetComponent<TextMeshPro>(), "Material Assignment");
go.GetComponent<TextMeshPro>().fontSharedMaterial = newMaterial;
}
#if UNITY_4_6 || UNITY_5
if (go.GetComponent<TextMeshProUGUI>() != null)
{
Undo.RecordObject(go.GetComponent<TextMeshProUGUI>(), "Material Assignment");
go.GetComponent<TextMeshProUGUI>().fontSharedMaterial = newMaterial;
}
#endif
}
TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(go, currentMaterial, newMaterial);
//SceneView.RepaintAll();
EditorUtility.SetDirty(go);
}
evt.Use();
break;
}
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
//Debug.Log("Undo / Redo Event ID (" + Undo.GetCurrentGroup() + ") occured.");
int UndoEventID = Undo.GetCurrentGroup();
int LastUndoEventID = m_eventID;
if (UndoEventID != LastUndoEventID)
{
//Debug.Log("Undo Redo Event processed by Material Editor. Affected Material is " + target + " with ID " + target.GetInstanceID()); // Event ID:" + UndoEventID + ". Target ID: " + m_modifiedProperties.target.GetInstanceID() + " Current Material: " + m_modifiedProperties.objectReference + " New Material: " + (m_modifiedProperties.target as Renderer).sharedMaterial);
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, target as Material);
//TMPro_EventManager.ON_BASE_MATERIAL_CHANGED(target as Material);
m_eventID = UndoEventID;
}
}
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
/*
//Debug.Log("Undo Event Registered in SDF Material Editor. # of Properties affected is " + modifications.Length);
PropertyModification modifiedProperties = modifications[0].propertyModification;
System.Type objType = modifiedProperties.target.GetType();
if (objType == typeof(MeshRenderer) || objType == typeof(Material)) // && UndoEventID != LastUndoEventID)
{
//Debug.Log("OnUndoRedoEvent() received in Material Editor."); // Event ID:" + UndoEventID + ". Target ID: " + m_modifiedProperties.target.GetInstanceID() + " Current Material: " + m_modifiedProperties.objectReference + " New Material: " + (m_modifiedProperties.target as Renderer).sharedMaterial);
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, target as Material);
}
if (target != null)
EditorUtility.SetDirty(target);
*/
return modifications;
}
// Function to draw title + enable toggle options as well as setting keyword.
private bool DrawTogglePanel(FoldoutType type, string label, bool toggle, string keyword)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
EditorGUI.indentLevel = 0;
Rect rect = EditorGUILayout.GetControlRect(false, 22);
GUI.Label(rect, GUIContent.none, TMP_UIStyleManager.Group_Label);
if (GUI.Button(new Rect(rect.x, rect.y, 250, rect.height), label, TMP_UIStyleManager.Group_Label_Left))
{
switch (type)
{
case FoldoutType.underlay:
m_foldout.underlay = !m_foldout.underlay;
break;
case FoldoutType.bevel:
m_foldout.bevel = !m_foldout.bevel;
break;
case FoldoutType.light:
m_foldout.light = !m_foldout.light;
break;
case FoldoutType.bump:
m_foldout.bump = !m_foldout.bump;
break;
case FoldoutType.env:
m_foldout.env = !m_foldout.env;
break;
case FoldoutType.glow:
m_foldout.glow = !m_foldout.glow;
break;
}
}
EditorGUIUtility.labelWidth = 70;
EditorGUI.BeginChangeCheck();
Material mat = target as Material;
if (mat.HasProperty("_FaceShininess") == false || keyword != "BEVEL_ON") // Show Enable Toggle only if material is not Surface Shader.
{
toggle = EditorGUI.Toggle(new Rect(rect.width - 90, rect.y + 3, 90, 22), new GUIContent("Enable ->"), toggle);
if (EditorGUI.EndChangeCheck())
{
SetKeyword(toggle, keyword);
havePropertiesChanged = true;
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
return toggle;
}
// Function to Draw UV Speed Property
private void DrawUVProperty(MaterialProperty[] properties, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 20);
Rect pos0 = new Rect(rect.x + 15, rect.y, rect.width - 55, 20);
Rect pos1 = new Rect(130, rect.y, 80, 18);
GUI.Label(pos0, label);
EditorGUIUtility.labelWidth = 35;
FloatProperty(pos1, properties[0], "X");
EditorGUIUtility.labelWidth = 35;
FloatProperty(new Rect(pos1.x + 70, pos1.y, pos1.width, pos1.height), properties[1], "Y");
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Function to Draw Material Property and make it look like a Slider with numericalf field.
private void DrawSliderProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
// Draw Slider
//EditorGUIUtility.labelWidth = 160;
Rect rect = EditorGUILayout.GetControlRect(false, 20);
Rect pos0 = new Rect(rect.x, rect.y, rect.width - 55, 20);
Rect pos1 = new Rect(rect.width - 46, rect.y, 60, 18);
// Draw Numerical Field
//EditorGUIUtility.labelWidth = 160;
RangeProperty(pos0, property, label);
EditorGUIUtility.labelWidth = 10;
FloatProperty(new Rect(pos1), property, null);
if (!property.hasMixedValue)
property.floatValue = Mathf.Round(property.floatValue * 1000) / 1000;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawTextureProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
EditorGUIUtility.fieldWidth = 70;
Rect rect = EditorGUILayout.GetControlRect(false, 75);
GUI.Label(new Rect(rect.x + 15, rect.y + 5, 100, rect.height), label);
TextureProperty(new Rect(rect.x, rect.y + 5, 200, rect.height), property, string.Empty, false);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawFloatProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
//EditorGUIUtility.labelWidth = 160;
Rect rect = EditorGUILayout.GetControlRect(false, 20);
Rect pos0 = new Rect(rect.x, rect.y, 225, 18);
//EditorGUIUtility.fieldWidth = 60;
FloatProperty(pos0, property, label);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawRangeProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 16);
Rect pos0 = new Rect(rect.x + 15, rect.y, rect.width, rect.height);
GUI.Label(pos0, label);
pos0.x += 100;
pos0.width -= 115;
RangeProperty(pos0, property, string.Empty);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawVectorProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
EditorGUIUtility.labelWidth = 160;
Rect rect = EditorGUILayout.GetControlRect(false, 20);
Rect pos0 = new Rect(rect.x + 15, rect.y + 2, rect.width - 120, 18);
Rect pos1 = new Rect(175, rect.y - 14, rect.width - 160, 18);
GUI.Label(pos0, label);
VectorProperty(pos1, property, "");
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Need to finish implementing this function
private void DrawVectorProperty(MaterialProperty property, string label, int floatCount)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
EditorGUIUtility.labelWidth = 160;
Rect rect = EditorGUILayout.GetControlRect(false, 20);
Rect pos0 = new Rect(rect.x + 15, rect.y + 2, rect.width - 120, 18);
Rect pos1 = new Rect(175, rect.y - 14, rect.width - 160, 18);
GUI.Label(pos0, label);
VectorProperty(pos1, property, "");
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void Draw2DBoundsProperty(MaterialProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
//EditorGUIUtility.labelWidth = 100;
Rect rect = EditorGUILayout.GetControlRect(false, 22);
Rect pos0 = new Rect(rect.x + 15, rect.y + 2, rect.width - 15, 18);
//Rect pos1 = new Rect(175, rect.y - 14, rect.width - 160, 18);
GUI.Label(pos0, label);
EditorGUIUtility.labelWidth = 30;
float width = (pos0.width - 15) / 5;
pos0.x += old_LabelWidth - 30;
Vector4 vec = property.vectorValue;
pos0.width = width;
vec.x = EditorGUI.FloatField(pos0, "X", vec.x);
pos0.x += width - 14;
vec.y = EditorGUI.FloatField(pos0, "Y", vec.y);
pos0.x += width - 14;
vec.z = EditorGUI.FloatField(pos0, "W", vec.z);
pos0.x += width - 14;
vec.w = EditorGUI.FloatField(pos0, "H", vec.w);
pos0.x = rect.width - 11;
pos0.width = 25;
property.vectorValue = vec;
if (GUI.Button(pos0, "X"))
{
Renderer _renderer = Selection.activeGameObject.GetComponent<Renderer>();
if (_renderer != null)
{
property.vectorValue = new Vector4(0, 0, Mathf.Round(_renderer.bounds.extents.x * 1000) / 1000, Mathf.Round(_renderer.bounds.extents.y * 1000) / 1000);
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Function to set keyword for each selected material.
private void SetKeyword(bool state, string keyword)
{
Undo.RecordObjects(targets, "Keyword State Change");
for (int i = 0; i < targets.Length; i++)
{
Material mat = targets[i] as Material;
if (state)
{
switch (keyword)
{
case "UNDERLAY_ON":
mat.EnableKeyword("UNDERLAY_ON");
mat.DisableKeyword("UNDERLAY_INNER");
break;
case "UNDERLAY_INNER":
mat.EnableKeyword("UNDERLAY_INNER");
mat.DisableKeyword("UNDERLAY_ON");
break;
default:
mat.EnableKeyword(keyword);
break;
}
}
else
{
switch (keyword)
{
case "UNDERLAY_ON":
mat.DisableKeyword("UNDERLAY_ON");
mat.DisableKeyword("UNDERLAY_INNER");
break;
case "UNDERLAY_INNER":
mat.DisableKeyword("UNDERLAY_INNER");
mat.DisableKeyword("UNDERLAY_ON");
break;
default:
mat.DisableKeyword(keyword);
break;
}
}
}
}
private void SetUnderlayKeywords()
{
for (int i = 0; i < targets.Length; i++)
{
Material mat = targets[i] as Material;
if (m_underlaySelection == Underlay_Types.Normal)
{
mat.EnableKeyword("UNDERLAY_ON");
mat.DisableKeyword("UNDERLAY_INNER");
}
else if (m_underlaySelection == Underlay_Types.Inner)
{
mat.EnableKeyword("UNDERLAY_INNER");
mat.DisableKeyword("UNDERLAY_ON");
}
}
}
private void SetMaskKeywords(Mask_Type mask)
{
for (int i = 0; i < targets.Length; i++)
{
Material mat = targets[i] as Material;
switch (mask)
{
case Mask_Type.MaskHard:
mat.EnableKeyword("MASK_HARD");
mat.DisableKeyword("MASK_SOFT");
mat.DisableKeyword("MASK_OFF");
//if (m_textMeshPro != null)
// m_textMeshPro.maskType = MaskingTypes.MaskHard;
//else if (m_textMeshProUGUI != null)
//m_textMeshProUGUI.maskType = MaskingTypes.MaskHard;
break;
case Mask_Type.MaskSoft:
mat.EnableKeyword("MASK_SOFT");
mat.DisableKeyword("MASK_HARD");
mat.DisableKeyword("MASK_OFF");
//if (m_textMeshPro != null)
// m_textMeshPro.maskType = MaskingTypes.MaskSoft;
//else if (m_textMeshProUGUI != null)
// m_textMeshProUGUI.maskType = MaskingTypes.MaskSoft;
break;
case Mask_Type.MaskOff:
mat.EnableKeyword("MASK_OFF");
mat.DisableKeyword("MASK_HARD");
mat.DisableKeyword("MASK_SOFT");
//if (m_textMeshPro != null)
// m_textMeshPro.maskType = MaskingTypes.MaskOff;
//else if (m_textMeshProUGUI != null)
// m_textMeshProUGUI.maskType = MaskingTypes.MaskOff;
break;
}
}
}
// Need to get material properties every update.
void ReadMaterialProperties()
{
Object[] target_Materials = this.targets;
m_faceColor = GetMaterialProperty(target_Materials, "_FaceColor");
m_faceTex = GetMaterialProperty(target_Materials, "_FaceTex");
m_faceUVSpeedX = GetMaterialProperty(target_Materials, "_FaceUVSpeedX");
m_faceUVSpeedY = GetMaterialProperty(target_Materials, "_FaceUVSpeedY");
m_faceDilate = GetMaterialProperty(target_Materials, "_FaceDilate");
m_faceShininess = GetMaterialProperty(target_Materials, "_FaceShininess");
// Border Properties
m_outlineColor = GetMaterialProperty(target_Materials, "_OutlineColor");
m_outlineThickness = GetMaterialProperty(target_Materials, "_OutlineWidth");
m_outlineSoftness = GetMaterialProperty(target_Materials, "_OutlineSoftness");
m_outlineTex = GetMaterialProperty(target_Materials, "_OutlineTex");
m_outlineUVSpeedX = GetMaterialProperty(target_Materials, "_OutlineUVSpeedX");
m_outlineUVSpeedY = GetMaterialProperty(target_Materials, "_OutlineUVSpeedY");
m_outlineShininess = GetMaterialProperty(target_Materials, "_OutlineShininess");
// Underlay Properties
m_underlayColor = GetMaterialProperty(target_Materials, "_UnderlayColor");
m_underlayOffsetX = GetMaterialProperty(target_Materials, "_UnderlayOffsetX");
m_underlayOffsetY = GetMaterialProperty(target_Materials, "_UnderlayOffsetY");
m_underlayDilate = GetMaterialProperty(target_Materials, "_UnderlayDilate");
m_underlaySoftness = GetMaterialProperty(target_Materials, "_UnderlaySoftness");
// Normal Map Options
m_bumpMap = GetMaterialProperty(target_Materials, "_BumpMap");
m_bumpFace = GetMaterialProperty(target_Materials, "_BumpFace");
m_bumpOutline = GetMaterialProperty(target_Materials, "_BumpOutline");
// Used by Unlit SDF Shader
//m_edgeSharpness = GetMaterialProperty(target_Materials, "_Edge");
// Material Properties for Beveling Options
m_bevel = GetMaterialProperty(target_Materials, "_Bevel");
m_bevelOffset = GetMaterialProperty(target_Materials, "_BevelOffset");
m_bevelWidth = GetMaterialProperty(target_Materials, "_BevelWidth");
m_bevelClamp = GetMaterialProperty(target_Materials, "_BevelClamp");
m_bevelRoundness = GetMaterialProperty(target_Materials, "_BevelRoundness");
m_specColor = GetMaterialProperty(target_Materials, "_SpecColor"); // Used by Surface Shader
// Bevel properties for Basic Shader & Hidden for Surface Shader
m_lightAngle = GetMaterialProperty(target_Materials, "_LightAngle");
m_specularColor = GetMaterialProperty(target_Materials, "_SpecularColor");
m_specularPower = GetMaterialProperty(target_Materials, "_SpecularPower");
m_reflectivity = GetMaterialProperty(target_Materials, "_Reflectivity");
m_diffuse = GetMaterialProperty(target_Materials, "_Diffuse");
m_ambientLight = GetMaterialProperty(target_Materials, "_Ambient");
// Material Properties for Glow Options
m_glowColor = GetMaterialProperty(target_Materials, "_GlowColor");
m_glowOffset = GetMaterialProperty(target_Materials, "_GlowOffset");
m_glowInner = GetMaterialProperty(target_Materials, "_GlowInner");
m_glowOuter = GetMaterialProperty(target_Materials, "_GlowOuter");
m_glowPower = GetMaterialProperty(target_Materials, "_GlowPower");
// Cube Map Options
m_reflectFaceColor = GetMaterialProperty(target_Materials, "_ReflectFaceColor");
m_reflectOutlineColor = GetMaterialProperty(target_Materials, "_ReflectOutlineColor");
m_reflectTex = GetMaterialProperty(target_Materials, "_Cube");
m_reflectRotation = GetMaterialProperty(target_Materials, "_EnvMatrixRotation");
//m_envTiltX = GetMaterialProperty(target_Materials, "_EnvTiltX");
//m_envTiltY = GetMaterialProperty(target_Materials, "_EnvTiltY");
//m_envMatrix = GetMaterialProperty(target_Materials, "_EnvMatrix");
// Properties specific to Surface Shader
//m_shininess = GetMaterialProperty(target_Materials, "_Shininess");
// Hidden Properties
m_mainTex = GetMaterialProperty(target_Materials, "_MainTex");
m_texSampleWidth = GetMaterialProperty(target_Materials, "_TextureWidth");
m_texSampleHeight = GetMaterialProperty(target_Materials, "_TextureHeight");
m_gradientScale = GetMaterialProperty(target_Materials, "_GradientScale");
m_PerspectiveFilter = GetMaterialProperty(target_Materials, "_PerspectiveFilter");
m_scaleX = GetMaterialProperty(target_Materials, "_ScaleX");
m_scaleY = GetMaterialProperty(target_Materials, "_ScaleY");
m_vertexOffsetX = GetMaterialProperty(target_Materials, "_VertexOffsetX");
m_vertexOffsetY = GetMaterialProperty(target_Materials, "_VertexOffsetY");
m_maskCoord = GetMaterialProperty(target_Materials, "_MaskCoord");
m_maskSoftnessX = GetMaterialProperty(target_Materials, "_MaskSoftnessX");
m_maskSoftnessY = GetMaterialProperty(target_Materials, "_MaskSoftnessY");
// Stencil
m_stencilID = GetMaterialProperty(target_Materials, "_Stencil");
m_stencilComp = GetMaterialProperty(target_Materials, "_StencilComp");
m_stencilOp = GetMaterialProperty(target_Materials, "_StencilOp");
//m_weightNormal = GetMaterialProperty(target_Materials, "_WeightNormal");
//m_weightBold = GetMaterialProperty(target_Materials, "_WeightBold");
m_shaderFlags = GetMaterialProperty(target_Materials, "_ShaderFlags");
m_scaleRatio_A = GetMaterialProperty(target_Materials, "_ScaleRatioA");
m_scaleRatio_B = GetMaterialProperty(target_Materials, "_ScaleRatioB");
m_scaleRatio_C = GetMaterialProperty(target_Materials, "_ScaleRatioC");
//m_fadeOut = GetMaterialProperty(target_Materials, "_Fadeout");
}
}
fileFormatVersion: 2
guid: a063642184ad060409efbd5cfe665ebf
timeCreated: 1480605656
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
/*
* Copyright (c) 2014, Nick Gravelyn.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;
namespace TMPro
{
// Helpers used by the different sorting layer classes.
public static class SortingLayerHelper
{
private static Type _utilityType;
private static PropertyInfo _sortingLayerNamesProperty;
private static MethodInfo _getSortingLayerUserIdMethod;
static SortingLayerHelper()
{
_utilityType = Type.GetType("UnityEditorInternal.InternalEditorUtility, UnityEditor");
_sortingLayerNamesProperty = _utilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
#if UNITY_5
_getSortingLayerUserIdMethod = _utilityType.GetMethod("GetSortingLayerUniqueID", BindingFlags.Static | BindingFlags.NonPublic);
#else
_getSortingLayerUserIdMethod = _utilityType.GetMethod("GetSortingLayerUserID", BindingFlags.Static | BindingFlags.NonPublic);
#endif
}
// Gets an array of sorting layer names.
// Since this uses reflection, callers should check for 'null' which will be returned if the reflection fails.
public static string[] sortingLayerNames
{
get
{
if (_sortingLayerNamesProperty == null)
{
return null;
}
return _sortingLayerNamesProperty.GetValue(null, null) as string[];
}
}
// Given the ID of a sorting layer, returns the sorting layer's name
public static string GetSortingLayerNameFromID(int id)
{
string[] names = sortingLayerNames;
if (names == null)
{
return null;
}
for (int i = 0; i < names.Length; i++)
{
if (GetSortingLayerIDForIndex(i) == id)
{
return names[i];
}
}
return null;
}
// Given the name of a sorting layer, returns the ID.
public static int GetSortingLayerIDForName(string name)
{
string[] names = sortingLayerNames;
if (names == null)
{
return 0;
}
return GetSortingLayerIDForIndex(Array.IndexOf(names, name));
}
// Helper to convert from a sorting layer INDEX to a sorting layer ID. These are not the same thing.
// IDs are based on the order in which layers were created and do not change when reordering the layers.
// Thankfully there is a private helper we can call to get the ID for a layer given its index.
public static int GetSortingLayerIDForIndex(int index)
{
if (_getSortingLayerUserIdMethod == null)
{
return 0;
}
return (int)_getSortingLayerUserIdMethod.Invoke(null, new object[] { index });
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2481ed331b06c764ba89816f298b7fb8
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
//using System.Collections.Generic;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(SpriteAsset))]
public class TMPro_SpriteAssetEditor : Editor
{
private struct UI_PanelState
{
public static bool spriteAssetInfoPanel = true;
public static bool spriteInfoPanel = false;
}
private int m_page = 0;
private const string k_UndoRedo = "UndoRedoPerformed";
private SerializedProperty m_spriteAtlas_prop;
private SerializedProperty m_spriteInfoList_prop;
private bool isAssetDirty = false;
private string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" };
private float m_xOffset;
private float m_yOffset;
private float m_xAdvance;
private float m_scale;
public void OnEnable()
{
m_spriteAtlas_prop = serializedObject.FindProperty("spriteSheet");
m_spriteInfoList_prop = serializedObject.FindProperty("spriteInfoList");
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
}
public override void OnInspectorGUI()
{
//Debug.Log("OnInspectorGUI Called.");
Event evt = Event.current;
string evt_cmd = evt.commandName; // Get Current Event CommandName to check for Undo Events
serializedObject.Update();
EditorGUIUtility.labelWidth = 135;
// HEADER
GUILayout.Label("<b>TextMeshPro - Sprite Asset</b>", TMP_UIStyleManager.Section_Label);
// TEXTMESHPRO SPRITE INFO PANEL
GUILayout.Label("Sprite Info", TMP_UIStyleManager.Section_Label);
EditorGUI.indentLevel = 1;
GUI.enabled = false; // Lock UI
EditorGUILayout.PropertyField(m_spriteAtlas_prop , new GUIContent("Sprite Atlas"));
// SPRITE LIST
GUI.enabled = true; // Unlock UI
GUILayout.Space(10);
EditorGUI.indentLevel = 0;
if (GUILayout.Button("Sprite List\t\t" + (UI_PanelState.spriteInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
UI_PanelState.spriteInfoPanel = !UI_PanelState.spriteInfoPanel;
if (UI_PanelState.spriteInfoPanel)
{
int arraySize = m_spriteInfoList_prop.arraySize;
int itemsPerPage = (Screen.height - 283) / 80;
if (arraySize > 0)
{
// Display each SpriteInfo entry using the SpriteInfo property drawer.
for (int i = itemsPerPage * m_page; i < arraySize && i < itemsPerPage * (m_page + 1); i++)
{
EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label, GUILayout.Height(60));
SerializedProperty spriteInfo = m_spriteInfoList_prop.GetArrayElementAtIndex(i);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(spriteInfo);
EditorGUILayout.EndVertical();
}
}
int shiftMultiplier = evt.shift ? 10 : 1; // Page + Shift goes 10 page forward
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 3;
// Previous Page
if (m_page > 0) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Previous"))
m_page -= 1 * shiftMultiplier;
// PAGE COUNTER
GUI.enabled = true;
pagePos.x += pagePos.width;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Label(pagePos, "Page " + (m_page + 1) + " / " + totalPages, GUI.skin.button);
// Next Page
pagePos.x += pagePos.width;
if (itemsPerPage * (m_page + 1) < arraySize) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Next"))
m_page += 1 * shiftMultiplier;
// Clamp page range
m_page = Mathf.Clamp(m_page, 0, arraySize / itemsPerPage);
// Global Settings
EditorGUIUtility.labelWidth = 40f;
EditorGUIUtility.fieldWidth = 20f;
GUI.enabled = true;
EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);
Rect rect = EditorGUILayout.GetControlRect(false, 40);
float width = (rect.width - 75f) / 4;
EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel);
rect.x += 70;
bool old_ChangedState = GUI.changed;
GUI.changed = false;
m_xOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset);
if (GUI.changed) UpdateGlobalProperty("xOffset", m_xOffset);
m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset);
if (GUI.changed) UpdateGlobalProperty("yOffset", m_yOffset);
m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance);
if (GUI.changed) UpdateGlobalProperty("xAdvance", m_xAdvance);
m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale);
if (GUI.changed) UpdateGlobalProperty("scale", m_scale);
EditorGUILayout.EndVertical();
GUI.changed = old_ChangedState;
}
//Rect rect = EditorGUILayout.GetControlRect(false, 20);
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
{
//Debug.Log("Serialized properties have changed.");
//TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
isAssetDirty = false;
EditorUtility.SetDirty(target);
//TMPro_EditorUtility.RepaintAll(); // Consider SetDirty
}
}
/// <summary>
/// Method to update the properties of all sprites
/// </summary>
/// <param name="property"></param>
/// <param name="value"></param>
void UpdateGlobalProperty(string property, float value)
{
int arraySize = m_spriteInfoList_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty spriteInfo = m_spriteInfoList_prop.GetArrayElementAtIndex(i);
spriteInfo.FindPropertyRelative(property).floatValue = value;
}
GUI.changed = false;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 4c105b9e717a10542bf9021d98907d59
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextContainer)), CanEditMultipleObjects]
public class TMPro_TextContainerEditor : Editor
{
// Serialized Properties
private SerializedProperty anchorPosition_prop;
private SerializedProperty pivot_prop;
private SerializedProperty rectangle_prop;
private SerializedProperty margins_prop;
private TextContainer m_textContainer;
private Transform m_transform;
private Vector3[] m_Rect_handlePoints = new Vector3[4];
private Vector3[] m_Margin_handlePoints = new Vector3[4];
private Vector2 m_anchorPosition;
private Vector3 m_mousePreviousPOS;
private Vector2 m_previousStartPOS;
//private int m_mouseDragFlag = 0;
private static Transform m_visualHelper;
void OnEnable()
{
// Serialized Properties
anchorPosition_prop = serializedObject.FindProperty("m_anchorPosition");
pivot_prop = serializedObject.FindProperty("m_pivot");
rectangle_prop = serializedObject.FindProperty("m_rect");
margins_prop = serializedObject.FindProperty("m_margins");
m_textContainer = (TextContainer)target;
m_transform = Selection.activeGameObject.transform;
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
/*
if (m_visualHelper == null)
{
m_visualHelper = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
m_visualHelper.localScale = new Vector3(0.25f, 0.25f, 0.25f);
}
*/
}
void OnDisable()
{
/*
if (m_visualHelper != null)
DestroyImmediate (m_visualHelper.gameObject);
*/
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.Label("<b>TEXT CONTAINER</b>", TMP_UIStyleManager.Section_Label, GUILayout.Height(23));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(anchorPosition_prop);
if (anchorPosition_prop.enumValueIndex == 9)
{
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(pivot_prop, new GUIContent("Pivot Position"));
EditorGUI.indentLevel -= 1;
}
DrawDimensionProperty(rectangle_prop, "Dimensions");
DrawMaginProperty(margins_prop, "Margins");
if (EditorGUI.EndChangeCheck())
{
// Re-compute pivot position when changes are made.
if (anchorPosition_prop.enumValueIndex != 9)
pivot_prop.vector2Value = GetAnchorPosition(anchorPosition_prop.enumValueIndex);
m_textContainer.hasChanged = true;
}
serializedObject.ApplyModifiedProperties();
}
void OnSceneGUI()
{
Event evt = Event.current;
Vector3 rectPos = m_transform.position;
Vector3 lossyScale = new Vector3(1, 1, 1); // m_transform.lossyScale;
Rect rectangle = m_textContainer.rect;
Vector2 pivot = m_textContainer.pivot; // GetAnchorPosition((int)m_textContainer.anchorPosition);
Vector3 pivotOffset = new Vector3((0.5f - pivot.x) * rectangle.width * lossyScale.x, (0.5f - pivot.y) * rectangle.height * lossyScale.y, 0);
m_Rect_handlePoints[0] = m_transform.TransformPoint(pivotOffset + new Vector3(-rectangle.width / 2 * lossyScale.x, -rectangle.height / 2 * lossyScale.y, 0)); // BL
m_Rect_handlePoints[1] = m_transform.TransformPoint(pivotOffset + new Vector3(-rectangle.width / 2 * lossyScale.x, +rectangle.height / 2 * lossyScale.y, 0)); // TL
m_Rect_handlePoints[2] = m_transform.TransformPoint(pivotOffset + new Vector3(+rectangle.width / 2 * lossyScale.x, +rectangle.height / 2 * lossyScale.y, 0)); // TR
m_Rect_handlePoints[3] = m_transform.TransformPoint(pivotOffset + new Vector3(+rectangle.width / 2 * lossyScale.x, -rectangle.height / 2 * lossyScale.y, 0)); // BR
Handles.DrawSolidRectangleWithOutline(m_Rect_handlePoints, new Color32(255, 255, 255, 0), new Color32(200, 200, 200, 255));
if (evt.mousePosition.x > HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[0]).x &&
evt.mousePosition.x < HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[2]).x &&
evt.mousePosition.y > HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[2]).y &&
evt.mousePosition.y < HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[0]).y)
{
HandleUtility.AddDefaultControl(512);
}
lossyScale = m_transform.lossyScale;
/*
if (HandleUtility.nearestControl == 512 && evt.type == EventType.mouseDown && evt.button == 0 || m_mouseDragFlag == 1)
{
m_mouseDragFlag = 1;
//Vector3 intersection = EditorHandleUtilities.GetIntersectingPoint(m_Rect_handlePoints[0], m_Rect_handlePoints[1], Camera.current, evt.mousePosition);
//Debug.DrawLine(intersection + new Vector3(-1, 0, 0), intersection + new Vector3(1, 0, 0), Color.green);
//Debug.DrawLine(intersection + new Vector3(0, 1, 0), intersection + new Vector3(0, -1, 0), Color.green);
//Vector3 currentPos = Camera.current.ScreenToWorldPoint(evt.mousePosition);
//Debug.Log("Delta: " + currentPos + " " + m_mousePreviousPOS + " Delta: " + (m_mousePreviousPOS - currentPos));
//m_transform.position += new Vector3(currentPos.x - m_mousePreviousPOS.x, m_mousePreviousPOS.y - currentPos.y, 0);
//m_mousePreviousPOS = currentPos;
}
*/
//Vector4 rectScreenSpace = new Vector4 (HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[0],HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[1], HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[2], HandleUtility.WorldToGUIPoint(m_Rect_handlePoints[3]);
//Vector3 intersection = EditorHandleUtilities.GetIntersectingPoint(m_Rect_handlePoints[2], m_Rect_handlePoints[3], Camera.current, evt.mousePosition);
//Debug.DrawLine(Camera.main.transform.position, intersection, Color.red, 0.1f);
//if (m_visualHelper != null)
// m_visualHelper.position = intersection;
//Debug.DrawLine(intersection + new Vector3(-1, 0, 0), intersection + new Vector3(1, 0, 0), Color.green, 0.1f);
//Debug.DrawLine(intersection + new Vector3(0, 1, 0), intersection + new Vector3(0, -1, 0), Color.green, 0.1f);
// Draw & process FreeMoveHandles
float handleSize = HandleUtility.GetHandleSize(rectPos) * 0.2f;
Handles.color = new Color(0, .4f, 1f, 1f);
bool hasChanged = false;
bool isShiftKey = evt.shift;
// BOTTOM LEFT HANDLE
Vector3 old_BottomLeft = m_Rect_handlePoints[0];
Vector3 new_BottomLeft = Handles.FreeMoveHandle(old_BottomLeft, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_BottomLeft != new_BottomLeft)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_BottomLeft - new_BottomLeft;
rectangle.width += delta.x / lossyScale.x;
rectangle.height += delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * (1 - pivot.x), -delta.y * (1 - pivot.y), 0));
hasChanged = true;
}
// LEFT HANDLE
Vector3 old_Left = (m_Rect_handlePoints[0] + m_Rect_handlePoints[1]) / 2;
Vector3 new_Left = Handles.FreeMoveHandle(old_Left, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_Left != new_Left)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector3 delta = old_Left - new_Left;
rectangle.width += delta.x / lossyScale.x;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * (1 - pivot.x), 0, 0));
hasChanged = true;
}
// TOP LEFT HANDLE
Vector3 old_TopLeft = m_Rect_handlePoints[1];
Vector3 new_TopLeft = Handles.FreeMoveHandle(old_TopLeft, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_TopLeft != new_TopLeft)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_TopLeft - new_TopLeft;
rectangle.width += delta.x / lossyScale.x;
rectangle.height -= delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * (1 - pivot.x), -delta.y * (pivot.y), 0));
hasChanged = true;
}
// TOP HANDLE
Vector3 old_Top = (m_Rect_handlePoints[1] + m_Rect_handlePoints[2]) / 2;
Vector3 new_Top = Handles.FreeMoveHandle(old_Top, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_Top != new_Top)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_Top - new_Top;
rectangle.height -= delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(0, -delta.y * (pivot.y), 0));
hasChanged = true;
}
// TOP RIGHT HANDLE
Vector3 old_TopRight = m_Rect_handlePoints[2];
Vector3 new_TopRight = Handles.FreeMoveHandle(old_TopRight, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_TopRight != new_TopRight)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_TopRight - new_TopRight;
rectangle.width -= delta.x / lossyScale.x;
rectangle.height -= delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * pivot.x, -delta.y * (pivot.y), 0));
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_Right = (m_Rect_handlePoints[2] + m_Rect_handlePoints[3]) / 2;
Vector3 new_Right = Handles.FreeMoveHandle(old_Right, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_Right != new_Right)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_Right - new_Right;
rectangle.width -= delta.x / lossyScale.x;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * pivot.x, 0, 0));
hasChanged = true;
}
// BOTTOM RIGHT HANDLE
Vector3 old_BottomRight = m_Rect_handlePoints[3];
Vector3 new_BottomRight = Handles.FreeMoveHandle(old_BottomRight, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_BottomRight != new_BottomRight)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_BottomRight - new_BottomRight;
rectangle.width -= delta.x / lossyScale.x;
rectangle.height += delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(-delta.x * pivot.x, -delta.y * (1 - pivot.y), 0));
hasChanged = true;
}
// BOTTOM HANDLE
Vector3 old_Bottom = (m_Rect_handlePoints[0] + m_Rect_handlePoints[3]) / 2;
Vector3 new_Bottom = Handles.FreeMoveHandle(old_Bottom, Quaternion.identity, handleSize, Vector3.zero, Handles.SphereCap);
if (old_Bottom != new_Bottom)
{
Undo.RecordObjects(new Object[] { m_textContainer, m_transform }, "Rectangle Dimension Changes");
Vector2 delta = old_Bottom - new_Bottom;
rectangle.height += delta.y / lossyScale.y;
if (!isShiftKey) m_transform.position += m_transform.TransformDirection(new Vector3(0, -delta.y * (1 - pivot.y), 0));
hasChanged = true;
}
//if (evt.type == EventType.mouseUp)
// m_mouseDragFlag = 0;
// Margin Frame & Handles
Vector4 textMargins = m_textContainer.margins;
m_Margin_handlePoints[0] = new_BottomLeft + m_transform.TransformDirection(new Vector3(textMargins.x * lossyScale.x, textMargins.w * lossyScale.y, 0)); // BL
m_Margin_handlePoints[1] = new_TopLeft + m_transform.TransformDirection(new Vector3(textMargins.x * lossyScale.x, - textMargins.y * lossyScale.y, 0)); // TL
m_Margin_handlePoints[2] = new_TopRight + m_transform.TransformDirection(new Vector3(- textMargins.z * lossyScale.x, - textMargins.y * lossyScale.y, 0)); // TR
m_Margin_handlePoints[3] = new_BottomRight + m_transform.TransformDirection(new Vector3(- textMargins.z * lossyScale.x, textMargins.w * lossyScale.y, 0)); // BR
Handles.color = Color.yellow;
Handles.DrawSolidRectangleWithOutline(m_Margin_handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
handleSize = HandleUtility.GetHandleSize(rectPos) * 0.05f;
Handles.color = Color.yellow;
// LEFT HANDLE
Vector3 old_left = (m_Margin_handlePoints[0] + m_Margin_handlePoints[1]) * 0.5f;
Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, handleSize, Vector3.zero, Handles.DotCap);
if (old_left != new_left)
{
Undo.RecordObject(target, "Margin Changes");
float delta = old_left.x - new_left.x;
textMargins.x -= delta / lossyScale.x;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 old_top = (m_Margin_handlePoints[1] + m_Margin_handlePoints[2]) * 0.5f;
Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, handleSize, Vector3.zero, Handles.DotCap);
if (old_top != new_top)
{
Undo.RecordObject(target, "Margin Changes");
float delta = old_top.y - new_top.y;
textMargins.y += delta / lossyScale.y;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_right = (m_Margin_handlePoints[2] + m_Margin_handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, handleSize, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
Undo.RecordObject(target, "Margin Changes");
float delta = old_right.x - new_right.x;
textMargins.z += delta / lossyScale.x;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 old_bottom = (m_Margin_handlePoints[3] + m_Margin_handlePoints[0]) * 0.5f;
Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, handleSize, Vector3.zero, Handles.DotCap);
if (old_bottom != new_bottom)
{
Undo.RecordObject(target, "Margin Changes");
float delta = old_bottom.y - new_bottom.y;
textMargins.w -= delta / lossyScale.y;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
hasChanged = false;
m_textContainer.rect = rectangle;
m_textContainer.margins = textMargins;
m_textContainer.hasChanged = true;
EditorUtility.SetDirty(m_transform);
}
}
private void DrawDimensionProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Rect rectangle = property.rectValue;
float width_B = width - old_LabelWidth;
float fieldWidth = width_B / 4;
pos0.width = fieldWidth - 5;
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Width");
pos0.x += fieldWidth;
rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);
pos0.x += fieldWidth;
GUI.Label(pos0, "Height");
pos0.x += fieldWidth;
rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);
property.rectValue = rectangle;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawMaginProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
//Vector4 vec = property.vector4Value;
Vector4 vec = Vector4.zero;
vec.x = property.FindPropertyRelative("x").floatValue;
vec.y = property.FindPropertyRelative("y").floatValue;
vec.z = property.FindPropertyRelative("z").floatValue;
vec.w = property.FindPropertyRelative("w").floatValue;
float widthB = width - old_LabelWidth;
float fieldWidth = widthB / 4;
pos0.width = fieldWidth - 5;
// Labels
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Left");
pos0.x += fieldWidth;
GUI.Label(pos0, "Top");
pos0.x += fieldWidth;
GUI.Label(pos0, "Right");
pos0.x += fieldWidth;
GUI.Label(pos0, "Bottom");
pos0.y += 18;
pos0.x = old_LabelWidth + 15;
vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x);
pos0.x += fieldWidth;
vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y);
pos0.x += fieldWidth;
vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z);
pos0.x += fieldWidth;
vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w);
//property.vector4Value = vec;
property.FindPropertyRelative("x").floatValue = vec.x;
property.FindPropertyRelative("y").floatValue = vec.y;
property.FindPropertyRelative("z").floatValue = vec.z;
property.FindPropertyRelative("w").floatValue = vec.w;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
Vector2 GetAnchorPosition(int index)
{
Vector2 anchorPosition = Vector2.zero;
switch (index)
{
case 0: // TOP LEFT
anchorPosition = new Vector2(0, 1);
break;
case 1: // TOP
anchorPosition = new Vector2(0.5f, 1);
break;
case 2: // TOP RIGHT
anchorPosition = new Vector2(1, 1);
break;
case 3: // LEFT
anchorPosition = new Vector2(0, 0.5f);
break;
case 4: // MIDDLE
anchorPosition = new Vector2(0.5f, 0.5f);
break;
case 5: // RIGHT
anchorPosition = new Vector2(1, 0.5f);
break;
case 6: // BOTTOM LEFT
anchorPosition = new Vector2(0, 0);
break;
case 7: // BOTTOM
anchorPosition = new Vector2(0.5f, 0);
break;
case 8: // BOTTOM RIGHT
anchorPosition = new Vector2(1, 0);
break;
}
return anchorPosition;
}
}
}
fileFormatVersion: 2
guid: 293ca108339990043ad3550e978a7418
timeCreated: 1478780256
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
public class TMPro_TexturePostProcessor : AssetPostprocessor
{
void OnPostprocessTexture(Texture2D texture)
{
//var importer = assetImporter as TextureImporter;
Texture2D tex = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D;
// Send Event to InlineGraphics ...
//Debug.Log(tex.GetInstanceID());
if (tex != null)
TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, tex);
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: a947892a3b8f7d747a446c2ea8c790c5
timeCreated: 1480605657
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
#if UNITY_4_6 || UNITY_5
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshProUGUI)), CanEditMultipleObjects]
public class TMPro_uiEditorPanel : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = false;
public static bool shadowSetting = false;
public static bool materialEditor = true;
}
private static int m_eventID;
private static string[] uiStateLabel = new string[] { "\t- <i>Click to expand</i> -", "\t- <i>Click to collapse</i> -" };
private const string k_UndoRedo = "UndoRedoPerformed";
public int selAlignGrid_A = 0;
public int selAlignGrid_B = 0;
// Serialized Properties
private SerializedProperty text_prop;
private SerializedProperty fontAsset_prop;
private SerializedProperty fontSharedMaterial_prop;
//private SerializedProperty fontBaseMaterial_prop;
private SerializedProperty isNewBaseMaterial_prop;
private SerializedProperty fontStyle_prop;
// Color Properties
private SerializedProperty fontColor_prop;
private SerializedProperty enableVertexGradient_prop;
private SerializedProperty fontColorGradient_prop;
private SerializedProperty overrideHtmlColor_prop;
private SerializedProperty fontSize_prop;
private SerializedProperty fontSizeBase_prop;
private SerializedProperty autoSizing_prop;
private SerializedProperty fontSizeMin_prop;
private SerializedProperty fontSizeMax_prop;
private SerializedProperty charSpacingMax_prop;
private SerializedProperty lineSpacingMax_prop;
private SerializedProperty characterSpacing_prop;
private SerializedProperty lineSpacing_prop;
private SerializedProperty paragraphSpacing_prop;
private SerializedProperty textAlignment_prop;
//private SerializedProperty textAlignment_prop;
private SerializedProperty horizontalMapping_prop;
private SerializedProperty verticalMapping_prop;
private SerializedProperty uvOffset_prop;
private SerializedProperty uvLineOffset_prop;
private SerializedProperty enableWordWrapping_prop;
private SerializedProperty wordWrappingRatios_prop;
private SerializedProperty textOverflowMode_prop;
private SerializedProperty pageToDisplay_prop;
private SerializedProperty enableKerning_prop;
private SerializedProperty inputSource_prop;
private SerializedProperty havePropertiesChanged_prop;
private SerializedProperty isInputPasingRequired_prop;
//private SerializedProperty isCalculateSizeRequired_prop;
private SerializedProperty isRichText_prop;
private SerializedProperty hasFontAssetChanged_prop;
private SerializedProperty enableExtraPadding_prop;
private SerializedProperty checkPaddingRequired_prop;
//private SerializedProperty isOrthographic_prop;
//private SerializedProperty textRectangle_prop;
private SerializedProperty margin_prop;
//private SerializedProperty isMaskUpdateRequired_prop;
//private SerializedProperty mask_prop;
private SerializedProperty maskOffset_prop;
//private SerializedProperty maskOffsetMode_prop;
//private SerializedProperty maskSoftness_prop;
private SerializedProperty vertexOffset_prop;
//private SerializedProperty sortingLayerID_prop;
//private SerializedProperty sortingOrder_prop;
private bool havePropertiesChanged = false;
private TextMeshProUGUI m_textMeshProScript;
private RectTransform m_rectTransform;
private CanvasRenderer m_uiRenderer;
private Editor m_materialEditor;
private Material m_targetMaterial;
private Rect m_inspectorStartRegion;
private Rect m_inspectorEndRegion;
//private TMPro_UpdateManager m_updateManager;
private Vector3[] m_rectCorners = new Vector3[4];
private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };
private float prev_lineLenght;
private bool m_isUndoSet;
public void OnEnable()
{
//Debug.Log("New Instance of TMPRO UGUI Editor with ID " + this.GetInstanceID());
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
text_prop = serializedObject.FindProperty("m_text");
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
fontSharedMaterial_prop = serializedObject.FindProperty("m_sharedMaterial");
//fontBaseMaterial_prop = serializedObject.FindProperty("m_baseMaterial");
isNewBaseMaterial_prop = serializedObject.FindProperty("m_isNewBaseMaterial");
fontStyle_prop = serializedObject.FindProperty("m_fontStyle");
fontSize_prop = serializedObject.FindProperty("m_fontSize");
fontSizeBase_prop = serializedObject.FindProperty("m_fontSizeBase");
autoSizing_prop = serializedObject.FindProperty("m_enableAutoSizing");
fontSizeMin_prop = serializedObject.FindProperty("m_fontSizeMin");
fontSizeMax_prop = serializedObject.FindProperty("m_fontSizeMax");
charSpacingMax_prop = serializedObject.FindProperty("m_charSpacingMax");
lineSpacingMax_prop = serializedObject.FindProperty("m_lineSpacingMax");
// Colors & Gradient
fontColor_prop = serializedObject.FindProperty("m_fontColor");
enableVertexGradient_prop = serializedObject.FindProperty ("m_enableVertexGradient");
fontColorGradient_prop = serializedObject.FindProperty ("m_fontColorGradient");
overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");
characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
paragraphSpacing_prop = serializedObject.FindProperty("m_paragraphSpacing");
textAlignment_prop = serializedObject.FindProperty("m_textAlignment");
enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
textOverflowMode_prop = serializedObject.FindProperty("m_overflowMode");
pageToDisplay_prop = serializedObject.FindProperty("m_pageToDisplay");
horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
uvOffset_prop = serializedObject.FindProperty("m_uvOffset");
uvLineOffset_prop = serializedObject.FindProperty("m_uvLineOffset");
enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
//isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
havePropertiesChanged_prop = serializedObject.FindProperty("havePropertiesChanged");
inputSource_prop = serializedObject.FindProperty("m_inputSource");
isInputPasingRequired_prop = serializedObject.FindProperty("isInputParsingRequired");
//isCalculateSizeRequired_prop = serializedObject.FindProperty("m_isCalculateSizeRequired");
enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
isRichText_prop = serializedObject.FindProperty("m_isRichText");
checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
margin_prop = serializedObject.FindProperty("m_margin");
//isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
//mask_prop = serializedObject.FindProperty("m_mask");
maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
//maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
//maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
//vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");
//sortingLayerID_prop = serializedObject.FindProperty("m_sortingLayerID");
//sortingOrder_prop = serializedObject.FindProperty("m_sortingOrder");
hasFontAssetChanged_prop = serializedObject.FindProperty("hasFontAssetChanged");
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
m_textMeshProScript = (TextMeshProUGUI)target;
m_rectTransform = Selection.activeGameObject.GetComponent<RectTransform>();
m_uiRenderer = Selection.activeGameObject.GetComponent<CanvasRenderer>();
// Add a Material Component if one does not exists
/*
m_materialComponent = Selection.activeGameObject.GetComponent<MaterialComponent> ();
if (m_materialComponent == null)
{
m_materialComponent = Selection.activeGameObject.AddComponent<MaterialComponent> ();
}
*/
// Create new Material Editor if one does not exists
if (m_uiRenderer != null && m_uiRenderer.GetMaterial() != null)
{
m_materialEditor = Editor.CreateEditor(m_uiRenderer.GetMaterial());
m_targetMaterial = m_uiRenderer.GetMaterial();
//Debug.Log("Currently Assigned Material is " + m_targetMaterial + ". Font Material is " + m_textMeshProScript.fontSharedMaterial);
}
//m_updateManager = Camera.main.gameObject.GetComponent<TMPro_UpdateManager>();
}
public void OnDisable()
{
//Debug.Log("OnDisable() for GUIEditor Panel called.");
Undo.undoRedoPerformed -= OnUndoRedo;
// Destroy material editor if one exists
if (m_materialEditor != null)
{
//Debug.Log("Destroying Inline Material Editor.");
DestroyImmediate(m_materialEditor);
}
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
//EditorGUIUtility.LookLikeControls(150, 30);
Rect rect;
float labelWidth = EditorGUIUtility.labelWidth = 130f;
float fieldWidth = EditorGUIUtility.fieldWidth;
// TEXT INPUT BOX SECTION
if (GUILayout.Button("<b>TEXT INPUT BOX</b>" + (m_foldout.textInput ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.textInput = !m_foldout.textInput;
if (m_foldout.textInput)
{
EditorGUI.BeginChangeCheck();
text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, TMP_UIStyleManager.TextAreaBoxEditor, GUILayout.Height(125), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
inputSource_prop.enumValueIndex = 0;
isInputPasingRequired_prop.boolValue = true;
//isCalculateSizeRequired_prop.boolValue = true;
havePropertiesChanged = true;
}
}
// FONT SETTINGS SECTION
if (GUILayout.Button("<b>FONT SETTINGS</b>" + (m_foldout.fontSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.fontSettings = !m_foldout.fontSettings;
if (m_foldout.fontSettings)
{
// FONT ASSET
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontAsset_prop);
if (EditorGUI.EndChangeCheck())
{
//Undo.RecordObject(m_textMeshProScript, "Material Change");
havePropertiesChanged = true;
hasFontAssetChanged_prop.boolValue = true;
}
// FONT STYLE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Font Style");
int styleValue = fontStyle_prop.intValue;
int v1 = GUILayout.Toggle((styleValue & 1) == 1, "B", GUI.skin.button) ? 1 : 0; // Bold
int v2 = GUILayout.Toggle((styleValue & 2) == 2, "I", GUI.skin.button) ? 2 : 0; // Italics
int v3 = GUILayout.Toggle((styleValue & 4) == 4, "U", GUI.skin.button) ? 4 : 0; // Underline
int v4 = GUILayout.Toggle((styleValue & 8) == 8, "ab", GUI.skin.button) ? 8 : 0; // Lowercase
int v5 = GUILayout.Toggle((styleValue & 16) == 16, "AB", GUI.skin.button) ? 16 : 0; // Uppercase
int v6 = GUILayout.Toggle((styleValue & 32) == 32, "S", GUI.skin.button) ? 32 : 0; // Smallcaps
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
fontStyle_prop.intValue = v1 + v2 + v3 + v4 + v5 + v6;
havePropertiesChanged = true;
}
// FACE VERTEX COLOR
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Color (Vertex)"));
// VERTEX COLOR GRADIENT
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.PrefixLabel("Color Gradient");
EditorGUILayout.PropertyField(enableVertexGradient_prop, new GUIContent("Color Gradient"), GUILayout.MinWidth(140), GUILayout.MaxWidth(200));
EditorGUIUtility.labelWidth = 95;
EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Tags"));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (enableVertexGradient_prop.boolValue)
{
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topLeft"), new GUIContent("Top Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topRight"), new GUIContent("Top Right"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomLeft"), new GUIContent("Bottom Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomRight"), new GUIContent("Bottom Right"));
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// FONT SIZE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(fontSize_prop, new GUIContent("Font Size"), GUILayout.MinWidth(168), GUILayout.MaxWidth(200));
EditorGUIUtility.fieldWidth = fieldWidth;
if (EditorGUI.EndChangeCheck())
{
fontSizeBase_prop.floatValue = fontSize_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 70;
EditorGUILayout.PropertyField(autoSizing_prop, new GUIContent("Auto Size"));
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = labelWidth;
if (EditorGUI.EndChangeCheck())
{
if (autoSizing_prop.boolValue == false)
fontSize_prop.floatValue = fontSizeBase_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// Show auto sizing options
if (autoSizing_prop.boolValue)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Auto Size Options");
EditorGUIUtility.labelWidth = 30;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMin_prop, new GUIContent("Min"), GUILayout.MinWidth(50));
if (EditorGUI.EndChangeCheck())
{
fontSizeMin_prop.floatValue = Mathf.Min(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMax_prop, new GUIContent("Max"), GUILayout.MinWidth(50));
if (EditorGUI.EndChangeCheck())
{
fontSizeMax_prop.floatValue = Mathf.Max(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(charSpacingMax_prop, new GUIContent("Char"), GUILayout.MinWidth(50));
EditorGUILayout.PropertyField(lineSpacingMax_prop, new GUIContent("Line"), GUILayout.MinWidth(50));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
charSpacingMax_prop.floatValue = Mathf.Min(0, charSpacingMax_prop.floatValue);
lineSpacingMax_prop.floatValue = Mathf.Min(0, lineSpacingMax_prop.floatValue);
havePropertiesChanged = true;
}
}
// CHARACTER, LINE & PARAGRAPH SPACING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Spacing Options");
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(characterSpacing_prop, new GUIContent("Char"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(lineSpacing_prop, new GUIContent("Line"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(paragraphSpacing_prop, new GUIContent(" Par."), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// TEXT ALIGNMENT
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false, 17);
GUIStyle btn = new GUIStyle(GUI.skin.button);
btn.margin = new RectOffset(1, 1, 1, 1);
btn.padding = new RectOffset(1, 1, 1, 0);
selAlignGrid_A = textAlignment_prop.enumValueIndex & ~28;
selAlignGrid_B = (textAlignment_prop.enumValueIndex & ~3) / 4;
GUI.Label(new Rect(rect.x, rect.y, 100, rect.height), "Alignment");
float columnB = EditorGUIUtility.labelWidth + 15;
selAlignGrid_A = GUI.SelectionGrid(new Rect(columnB, rect.y, 23 * 4, rect.height), selAlignGrid_A, TMP_UIStyleManager.alignContent_A, 4, btn);
selAlignGrid_B = GUI.SelectionGrid(new Rect(columnB + 23 * 4 + 10, rect.y, 23 * 5, rect.height), selAlignGrid_B, TMP_UIStyleManager.alignContent_B, 5, btn);
if (EditorGUI.EndChangeCheck())
{
textAlignment_prop.enumValueIndex = selAlignGrid_A + selAlignGrid_B * 4;
havePropertiesChanged = true;
}
// WRAPPING RATIOS shown if Justified mode is selected.
EditorGUI.BeginChangeCheck();
if (textAlignment_prop.enumValueIndex == 3 || textAlignment_prop.enumValueIndex == 7 || textAlignment_prop.enumValueIndex == 11 || textAlignment_prop.enumValueIndex == 19)
DrawPropertySlider("Wrap Mix (W <-> C)", wordWrappingRatios_prop);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// TEXT WRAPPING & OVERFLOW
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("Wrapping & Overflow"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
int wrapSelection = EditorGUI.Popup(rect, enableWordWrapping_prop.boolValue ? 1 : 0, new string[] { "Disabled", "Enabled" });
if (EditorGUI.EndChangeCheck())
{
enableWordWrapping_prop.boolValue = wrapSelection == 1 ? true : false;
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXT OVERFLOW
EditorGUI.BeginChangeCheck();
if (textOverflowMode_prop.enumValueIndex != 5)
{
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
}
else
{
rect.x += rect.width + 5f;
rect.width /= 2;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
rect.x += rect.width;
rect.width -= 5;
EditorGUI.PropertyField(rect, pageToDisplay_prop, GUIContent.none);
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXTURE MAPPING OPTIONS
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("UV Mapping Options"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
EditorGUI.PropertyField(rect, horizontalMapping_prop, GUIContent.none);
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect,verticalMapping_prop, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// UV OPTIONS
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("UV Offset");
EditorGUILayout.PropertyField(uvOffset_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(uvLineOffset_prop, new GUIContent("Line"), GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// KERNING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Enable Kerning?"));
if (EditorGUI.EndChangeCheck())
{
//isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
// EXTRA PADDING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding?"));
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
checkPaddingRequired_prop.boolValue = true;
}
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("<b>EXTRA SETTINGS</b>" + (m_foldout.extraSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.extraSettings = !m_foldout.extraSettings;
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel = 0;
DrawMaginProperty(margin_prop, "Margins");
DrawMaginProperty(maskOffset_prop, "Mask Offset");
//EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
//EditorGUILayout.EndHorizontal();
//EditorGUILayout.PropertyField(isOrthographic_prop, new GUIContent("Orthographic Mode?"));
EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Enable Rich Text?"));
//EditorGUILayout.PropertyField(textRectangle_prop, true);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(mask_prop);
//EditorGUILayout.PropertyField(maskOffset_prop, true);
//EditorGUILayout.PropertyField(maskSoftness_prop);
//if (EditorGUI.EndChangeCheck())
//{
// isMaskUpdateRequired_prop.boolValue = true;
// havePropertiesChanged = true;
//}
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
// Mask Selection
}
EditorGUILayout.Space();
// If a Custom Material Editor exists, we use it.
if (m_uiRenderer != null && m_uiRenderer.GetMaterial() != null)
{
Material mat = m_uiRenderer.GetMaterial();
//Debug.Log(mat + " " + m_targetMaterial);
if (mat != m_targetMaterial)
{
// Destroy previous Material Instance
//Debug.Log("New Material has been assigned.");
m_targetMaterial = mat;
DestroyImmediate(m_materialEditor);
}
if (m_materialEditor == null)
{
m_materialEditor = Editor.CreateEditor(mat);
}
// Define the Drag-n-Drop Region (Start)
//m_inspectorStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
m_materialEditor.DrawHeader();
//EditorGUILayout.PropertyField(fontSharedMaterial_prop);
m_materialEditor.OnInspectorGUI();
// Define the Drag-n-Drop Region (End)
//m_inspectorEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
}
if (havePropertiesChanged)
{
//Debug.Log("Properties have changed.");
havePropertiesChanged_prop.boolValue = true;
havePropertiesChanged = false;
EditorUtility.SetDirty(target);
}
serializedObject.ApplyModifiedProperties();
//m_targetMaterial = m_uiRenderer.GetMaterial();
}
private void DragAndDropGUI()
{
Event evt = Event.current;
Rect dropArea = new Rect(m_inspectorStartRegion.x, m_inspectorStartRegion.y, m_inspectorEndRegion.width, m_inspectorEndRegion.y - m_inspectorStartRegion.y);
switch (evt.type)
{
case EventType.dragUpdated:
case EventType.DragPerform:
if (!dropArea.Contains(evt.mousePosition))
break;
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
// Do something
Material mat = DragAndDrop.objectReferences[0] as Material;
//Debug.Log("Drag-n-Drop Material is " + mat + ". Target Material is " + m_targetMaterial + ". Canvas Material is " + m_uiRenderer.GetMaterial() );
// Check to make sure we have a valid material and that the font atlases match.
if (!mat || mat == m_uiRenderer.GetMaterial() || mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_textMeshProScript.font.atlas.GetInstanceID())
{
if (mat && mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_textMeshProScript.font.atlas.GetInstanceID())
Debug.LogWarning("Drag-n-Drop Material [" + mat.name + "]'s Atlas does not match the assigned Font Asset [" + m_textMeshProScript.font.name + "]'s Atlas.");
break;
}
fontSharedMaterial_prop.objectReferenceValue = mat;
//fontBaseMaterial_prop.objectReferenceValue = mat;
isNewBaseMaterial_prop.boolValue = true;
//TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(m_textMeshProScript, mat);
EditorUtility.SetDirty(target);
//havePropertiesChanged = true;
}
evt.Use();
break;
}
}
// DRAW MARGIN PROPERTY
private void DrawMaginProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Vector4 vec = property.vector4Value;
float widthB = width - old_LabelWidth;
float fieldWidth = widthB / 4;
pos0.width = fieldWidth - 5;
// Labels
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Left");
pos0.x += fieldWidth;
GUI.Label(pos0, "Top");
pos0.x += fieldWidth;
GUI.Label(pos0, "Right");
pos0.x += fieldWidth;
GUI.Label(pos0, "Bottom");
pos0.y += 18;
pos0.x = old_LabelWidth + 15;
vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x);
pos0.x += fieldWidth;
vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y);
pos0.x += fieldWidth;
vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z);
pos0.x += fieldWidth;
vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w);
property.vector4Value = vec;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
public void OnSceneGUI()
{
// Margin Frame & Handles
m_rectTransform.GetWorldCorners(m_rectCorners);
Vector4 marginOffset = m_textMeshProScript.margin;
Vector3 lossyScale = m_rectTransform.lossyScale;
handlePoints[0] = m_rectCorners[0] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, marginOffset.w * lossyScale.y, 0));
handlePoints[1] = m_rectCorners[1] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
handlePoints[2] = m_rectCorners[2] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
handlePoints[3] = m_rectCorners[3] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, marginOffset.w * lossyScale.y, 0));
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
// LEFT HANDLE
Vector3 old_left = (handlePoints[0] + handlePoints[1]) * 0.5f;
Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
bool hasChanged = false;
if (old_left != new_left)
{
float delta = old_left.x - new_left.x;
marginOffset.x += -delta / lossyScale.x;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 old_top = (handlePoints[1] + handlePoints[2]) * 0.5f;
Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_top != new_top)
{
float delta = old_top.y - new_top.y;
marginOffset.y += delta / lossyScale.y;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = old_right.x - new_right.x;
marginOffset.z += delta / lossyScale.x;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 old_bottom = (handlePoints[3] + handlePoints[0]) * 0.5f;
Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_bottom != new_bottom)
{
float delta = old_bottom.y - new_bottom.y;
marginOffset.w += -delta / lossyScale.y;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
Undo.RecordObjects(new Object[] {m_rectTransform, m_textMeshProScript }, "Margin Changes");
m_textMeshProScript.margin = marginOffset;
EditorUtility.SetDirty(target);
//m_textMeshProScript.ForceMeshUpdate();
}
}
void DrawPropertySlider(string label, SerializedProperty property)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
//EditorGUIUtility.labelWidth = m_labelWidth;
GUIContent content = label == "" ? GUIContent.none : new GUIContent(label);
EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDimensionProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Rect rectangle = property.rectValue;
float width_B = width - old_LabelWidth;
float fieldWidth = width_B / 4;
pos0.width = fieldWidth - 5;
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Width");
pos0.x += fieldWidth;
rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);
pos0.x += fieldWidth;
GUI.Label(pos0, "Height");
pos0.x += fieldWidth;
rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);
property.rectValue = rectangle;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
void DrawPropertyBlock(string[] labels, SerializedProperty[] properties)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
GUI.Label(new Rect(rect.x, rect.y, old_LabelWidth, rect.height), labels[0]);
rect.x = old_LabelWidth + 15;
rect.width = (rect.width + 20 - rect.x) / labels.Length;
for (int i = 0; i < labels.Length; i++)
{
if (i == 0)
{
EditorGUIUtility.labelWidth = 20;
EditorGUI.PropertyField(new Rect(rect.x - 20, rect.y, 75, rect.height), properties[i], new GUIContent(" "));
rect.x += rect.width;
}
else
{
EditorGUIUtility.labelWidth = GUI.skin.textArea.CalcSize(new GUIContent(labels[i])).x;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 5, rect.height), properties[i], new GUIContent(labels[i]));
rect.x += rect.width;
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
//int undoEventID = Undo.GetCurrentGroup();
//int LastUndoEventID = m_eventID;
//Debug.Log(m_textMeshProScript.fontMaterial);
/*
if (undoEventID != LastUndoEventID)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
m_eventID = undoEventID;
}
}
*/
}
/*
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
int eventID = Undo.GetCurrentGroup();
PropertyModification modifiedProp = modifications[0].propertyModification;
System.Type targetType = modifiedProp.target.GetType();
if (targetType == typeof(Material))
{
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + targetObject);
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, targetObject as Material);
//EditorUtility.SetDirty(targetObject);
}
//string propertyPath = modifications[0].propertyModification.propertyPath;
//if (propertyPath == "m_fontAsset")
//{
//int currentEvent = Undo.GetCurrentGroup();
//Undo.RecordObject(Selection.activeGameObject.renderer.sharedMaterial, "Font Asset Changed");
//Undo.CollapseUndoOperations(currentEvent);
//Debug.Log("Undo / Redo Event: Font Asset changed. Event ID:" + Undo.GetCurrentGroup());
//}
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + modifiedProp.propertyPath + " Undo Event ID:" + eventID + " Stored ID:" + TMPro_EditorUtility.UndoEventID);
//TextMeshPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, target as TextMeshPro);
return modifications;
}
*/
}
}
#endif
\ No newline at end of file
fileFormatVersion: 2
guid: eaf08e150ab6a164c803dc7681ee7e69
timeCreated: 1480605666
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment