Moho to Unity3D, improved .fbx import script

Have you come up with a good Moho trick? Need help solving an animation problem? Come on in.

Moderators: Víctor Paredes, Belgarath, slowtiger

Post Reply
the_royal_orchestra
Posts: 10
Joined: Tue Feb 14, 2017 1:24 am

Moho to Unity3D, improved .fbx import script

Post by the_royal_orchestra »

Hi,
I was a bit disappointed how the .fbx Files exported from Moho appear in Unity.
The provided import script from the extras folder makes it impossible to place characters in a 3D-Scene and if several .fbx files are imported they intersect randomly. So I improved the import script today by mapping the layer order of Moho to the sortingOrder inside Unity's sortingLayers. (The original script manipulates the drawing order of the materials).

To correct the drawing order in a 3D Scene based on the distance of the characters to the camera I wrote another script that has to be applied to the characters in the scene. Now it is possible to place characters in front or behind each other. This script also corrects the drawing of switch layers. It just switches on the first layer of every switch layer and turns off the others. I found that almost always no switch layer is visible at all in Moho's .fbx exports( inside the .fbx's animations they still work good.)
The script corrects the drawing order for the scene view in edit mode, and switches to correct the game view in play mode.
I don't know if it is possible to correct both at the same time.

Since I'm no programmer and these are my first c#-Scripts please suggest better ways of doing things.

Import script for Editor folder:
https://drive.google.com/open?id=0ByVfk ... V82SlJfTU0

script to apply to Moho .fbx gameObjects:
https://drive.google.com/open?id=0ByVfk ... E9velliZ1k

have fun!

MohoFBXImporter.cs

Code: Select all

using UnityEngine;
using UnityEditor;
using System;

// place in Editor folder

public class AnimeStudioPostProcessor : AssetPostprocessor
{
	private bool fIsAnimeStudioModel = false;

	void OnPreprocessModel()
	{
		fIsAnimeStudioModel = false;
		// resampleRotations only became part of Unity as of version 5.3.
		// If you're using an older version of Unity, comment out the following block of code.
		// Set resampleRotations to false to fix the "bouncy" handling of constant interpolation keyframes.
		try
		{
			var importer = assetImporter as ModelImporter;
			importer.resampleRotations = false;
		}
		catch
		{
		}
	}

	void OnPostprocessGameObjectWithUserProperties(GameObject g, string[] names, System.Object[] values)
	{
		// Only operate on FBX files
		if (assetPath.IndexOf(".fbx") == -1)
		{
			return;
		}

		for (int i = 0; i < names.Length; i++)
		{
			if (names[i] == "ASP_FBX")
			{
				fIsAnimeStudioModel = true; // at least some part of this comes from Anime Studio
				break;
			}
		}
	}

	void OnPostprocessModel(GameObject g)
	{
		// Only operate on FBX files
		if (assetPath.IndexOf(".fbx") == -1)
		{
			return;
		}

		if (!fIsAnimeStudioModel)
		{
			//Debug.Log("*** Not Moho ***");
			return;
		}

		Shader shader = Shader.Find("Sprites/Default");
		if (shader == null)
			return;

		Renderer[] renderers = g.GetComponentsInChildren<Renderer>();

		foreach (Renderer r in renderers)
		{
			int renderOrder = 0;
			if (r.name.Contains("|"))
			{
				string[] stringSeparators = new string[] {"|"};
				string[] parts = r.name.Split(stringSeparators, StringSplitOptions.None);
				int j;
				if (Int32.TryParse(parts[parts.Length - 1], out j))
					renderOrder = j; //was += j
			}
			r.sharedMaterial.shader = shader; // apply an unlit shader

			/* use sortingOrder on the default Layer instead of r.sharedMaterial.renderQueue
			 * sortingLayers are used not only by the Sprite Renderer:
			 */
			r.sortingOrder = renderOrder; 

		}
	}
}
MohoFBX.cs

Code: Select all

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System;

[ExecuteInEditMode]

// apply to Moho .fbx GameObjects in the scene

public class MohoFBX : MonoBehaviour {

	private Vector3 cam ;
	private Renderer[] allRs;
	public bool SceneViewCam = true;
	// Use this for initialization
	void Start () {

		// show the first layer of every switching layer

		if (Application.isEditor == true) {

			Transform[] allT = GetComponentsInChildren<Transform> ();
			foreach (Transform t in allT) {


				if (t.childCount > 0) {
					Transform child = t.GetComponentInChildren<Transform> ().GetChild (0);
					if (child.localScale == new Vector3 (0.000001f, 0.000001f, 0.000001f)) {

						child.transform.localScale = new Vector3 (1f, 1f, 1f);

						// don't show the other layers

						for (int i = 1; i < t.childCount; i++) {

							Transform otherChild = t.GetComponentInChildren<Transform> ().GetChild (i);
							otherChild.transform.localScale = new Vector3 (0.000001f, 0.000001f, 0.000001f);
						}
					}
				}
			}
		}



	}

	// Update is called once per frame
	void Update () {

		// use main Camera to calculate drawing order
		cam = Camera.main.transform.position;

		// this corrects drawing the Scene view if not playing:
		if (Camera.current != null && Application.isPlaying == false && SceneViewCam == true) {
			cam = Camera.current.transform.position;
		}

		// draw in layers in order but also use distance from camera

		float dist2cam = Vector3.Distance (cam, transform.position) * -100; 

		Renderer[] allRs = GetComponentsInChildren<Renderer> ();
		foreach (Renderer r in allRs) {

			int renderOrder = 0;
			if (r.name.Contains("|"))
			{
				string[] stringSeparators = new string[] {"|"};
				string[] parts = r.name.Split(stringSeparators, StringSplitOptions.None);
				int j;
				if (Int32.TryParse(parts[parts.Length - 1], out j))
					renderOrder = j + (int)dist2cam;
			}


			r.GetComponent<Renderer> ().sortingOrder = renderOrder;
		}

	}
}

And here is an additional optional Editor script that applies changing the drawing mode (game view / scene view) in one MohoFBX object to all others in the scene automatically:

MohoFBXInspector.cs
https://drive.google.com/open?id=0ByVfk ... nY4Vnh4b1U

Code: Select all

using UnityEditor;
using UnityEngine;
using System.Collections;

// place this script in Editor folder
// move an object to update if it does not redraw by itself instantly

// Custom Editor using SerializedProperties.
// Automatic handling of multi-object editing, undo, and prefab overrides.
[CustomEditor(typeof(MohoFBX))]
[CanEditMultipleObjects] // not really needed here
public class updater : Editor {
	SerializedProperty useAllSceneViews;


	void OnEnable () {
		// Setup the SerializedProperties.
		useAllSceneViews = serializedObject.FindProperty ("SceneViewCam");

	}

	public override void OnInspectorGUI() {
		// Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
		serializedObject.Update ();

		// Show the custom GUI controls.
		EditorGUILayout.PropertyField (useAllSceneViews, new GUIContent("Game / Scene View") );

		//  find all MohoFBX objects and change their drawing mode, too:
		MohoFBX[] mohoFBXs = (MohoFBX[])GameObject.FindObjectsOfType (typeof(MohoFBX));
		foreach (MohoFBX m in mohoFBXs) {
			m.SceneViewCam = useAllSceneViews.boolValue;
		}
			

		// Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
		serializedObject.ApplyModifiedProperties ();

	}


}
Last edited by the_royal_orchestra on Fri Feb 24, 2017 1:13 am, edited 1 time in total.
dkwroot
Posts: 677
Joined: Thu May 02, 2013 6:56 am
Location: USA
Contact:

Re: Moho to Unity3D, improved .fbx import script

Post by dkwroot »

This is fantastic! Thank you for making this.
the_royal_orchestra
Posts: 10
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Post by the_royal_orchestra »

Just updated the downloadable files.
Now it is possible to set the camera used to calculate the sorting order with the Inspector.
The repair mechanism of switch layers is a bit smarter now.
It does not correct animations, though-
If the fbx exporter of Moho fails somehow, try adding keyframes on frame 1.

I could not figure out how to update the scene view yet.
After you orbit around in scene view, or switching from game view mode you have to move an object to redraw everything correctly.
There is " SceneView.RepaintAll(); ", but I couldn't get it to work properly. Does someone have a clue?
the_royal_orchestra
Posts: 10
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Post by the_royal_orchestra »

Here is an update that also corrects the visibility of Layers which are affected by more than one bone (Flexi-bind,..).
The corrections also work on animations now.
Make sure to place a freeze pose keyframe when you set a layer visible again in an animation.
Since the corrections may have unwanted side-effects (?) it is possible to turn them off from the inspector.

https://drive.google.com/open?id=0ByVfk ... WZ1X2ZhSTA
hano
Posts: 27
Joined: Sun Jan 01, 2017 7:37 pm

Re: Moho to Unity3D, improved .fbx import script

Post by hano »

Thanks man, I'll try this one for sure.
I wish we didn't have to go through this.
Maybe Smith Micro can pay you to help them out once things are better for them.
the_royal_orchestra
Posts: 10
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Post by the_royal_orchestra »

Yeah, pay me :-)
Gogi
Posts: 1
Joined: Sun Jan 07, 2018 2:49 am

Re: Moho to Unity3D, improved .fbx import script

Post by Gogi »

Hey Guys.
I'm absolutely new to all of this.
Hope my question doesn't sound silly but where does MohoFBX.cs goes? Where do you place it?
And one more question - when I put the MohoFBXImporter.cs to Unity Editor folder, it does solve the layer order of the object but the order of all objects in Unity isn't working right. Some objects aren't visible through others (even though I gave one object Z position 0.002 and the other Z position 0.001, some parts of "object 0.002" aren't visible through "object 0.001"). Do you know where is the problem?

Thank you a lot :)
the_royal_orchestra
Posts: 10
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Post by the_royal_orchestra »

New googledrive link to the script above:
https://drive.google.com/file/d/0ByVfkx ... zz4-D9BNoA

It is still necessary i guess. I did not use Unity for a while.
Best regards
User avatar
dueyftw
Posts: 2174
Joined: Thu Sep 14, 2006 10:32 am
Location: kingston NY
Contact:

Re: Moho to Unity3D, improved .fbx import script

Post by dueyftw »

I've long since given up on using fbx with Moho. The technique I use is controlling the camera. You can control the distance the camera sees. Then you make two passes one for the foreground and one for the background. After that you render out your Moho animation with some fake shadows done in Moho that match the unity scene.

Dale
Post Reply