/// <summary> /// Creates a generic avatar for a UMA character. /// </summary> /// <returns>The generic avatar.</returns> /// <param name="umaData">UMA data.</param> public static Avatar CreateGenericAvatar(UMAData umaData) { Avatar res = AvatarBuilder.BuildGenericAvatar(umaData.gameObject, umaData.umaRecipe.GetRace().genericRootMotionTransformName); res.name = umaData.name; return(res); }
public override object WriteTo(object obj) { if (obj is Avatar) { obj = base.WriteTo(obj); if (obj == null) { return(null); } return(obj); } Animator animator = (Animator)obj; if (isHuman) { HumanDescription desc = (HumanDescription)humanDescription.WriteTo(new HumanDescription()); desc.skeleton[0].name = animator.gameObject.name; animator.avatar = AvatarBuilder.BuildHumanAvatar(animator.gameObject, desc); base.WriteTo(animator.avatar); } else { animator.avatar = AvatarBuilder.BuildGenericAvatar(animator.gameObject, ""); } return(obj); }
bool CreatePlayableGraph() { var animator = GetComponent <Animator>(); if (animator.avatar == null) { animator.avatar = AvatarBuilder.BuildGenericAvatar(animator.gameObject, transform.name); animator.avatar.name = "Avatar"; } var deltaTimeProperty = animator.BindSceneProperty(transform, typeof(Kinematica), "_deltaTime"); job = new UpdateAnimationPoseJob(); if (!job.Setup(animator, GetComponentsInChildren <Transform>(), ref Synthesizer.Ref, deltaTimeProperty)) { return(false); } playableGraph = PlayableGraph.Create( $"Kinematica_{animator.transform.name}"); var output = AnimationPlayableOutput.Create(playableGraph, "output", animator); var playable = AnimationScriptPlayable.Create(playableGraph, job); output.SetSourcePlayable(playable); playableGraph.Play(); return(true); }
static int BuildGenericAvatar(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 2); GameObject arg0 = LuaScriptMgr.GetNetObject <GameObject>(L, 1); string arg1 = LuaScriptMgr.GetLuaString(L, 2); Avatar o = AvatarBuilder.BuildGenericAvatar(arg0, arg1); LuaScriptMgr.Push(L, o); return(1); }
private static Avatar GetDummyAvatar() { if (_dummyAvatar == null) { GameObject temp = new GameObject(); _dummyAvatar = AvatarBuilder.BuildGenericAvatar(temp, ""); _dummyAvatar.name = "GPU Animated Avatar"; Destroy(temp); } return(_dummyAvatar); }
private static void CreateAvatar() { GameObject activeGameObject = Selection.activeGameObject; if (activeGameObject != null) { Avatar avatar = AvatarBuilder.BuildGenericAvatar(activeGameObject, ""); avatar.name = activeGameObject.name; Debug.Log(avatar.isHuman ? "is human" : "is generic"); var path = string.Format("Assets/{0}.ht", avatar.name.Replace(':', '_')); AssetDatabase.CreateAsset(avatar, path); } }
public Avatar Create() { // check if it's a valid mecanim avatar var boneName = HumanTrait.BoneName; for (var x = 0; x < boneName.Length; x++) { if (!HumanTrait.RequiredBone(x)) { continue; } var requiredBoneType = Naming.MecanimNameToBoneType(boneName[x]); if (!_boneMapping.ContainsKey(requiredBoneType)) { return(AvatarBuilder.BuildGenericAvatar(_root, "")); } } var humanBones = new HumanBone[_boneMapping.Count]; var skeletonBones = GetSkeletonBones(); for (var x = 0; x < _boneMapping.Count; x++) { var item = _boneMapping.ElementAt(x); var boneType = item.Key; var go = item.Value; var mecanimBoneName = Naming.BoneTypeToMecanimName(boneType); if (mecanimBoneName == "default") { mecanimBoneName = go.name; } var humanBone = new HumanBone { humanName = mecanimBoneName, boneName = go.name, limit = { useDefaultValues = true } }; humanBones[x] = humanBone; } var humanDescription = new HumanDescription() { skeleton = skeletonBones, human = humanBones }; return(AvatarBuilder.BuildHumanAvatar(_root, humanDescription)); }
static void CreateAvatar(SpineArmatureEditor armatureEditor, Animator animator, string path) { Avatar avatar = AvatarBuilder.BuildGenericAvatar(armatureEditor.armature.gameObject, ""); animator.avatar = avatar; AvatarMask avatarMask = new AvatarMask(); string[] transofrmPaths = GetTransformPaths(armatureEditor); avatarMask.transformCount = transofrmPaths.Length; for (int i = 0; i < transofrmPaths.Length; i++) { avatarMask.SetTransformPath(i, transofrmPaths[i]); avatarMask.SetTransformActive(i, true); } AssetDatabase.CreateAsset(avatar, path + "/" + armatureEditor.armature.name + "Avatar.asset"); AssetDatabase.CreateAsset(avatarMask, path + "/" + armatureEditor.armature.name + "Mask.asset"); }
// Use this for initialization void Start() { SkinnedMeshRenderer rend = gameObject.GetComponent <SkinnedMeshRenderer>(); mesh = new Mesh(); Utils.LoadMesh(meshpath, mesh, rend, transform); Animation anim = GetComponent <Animation>(); Utils.LoadAnim(anipath, anim); //anim.Play("test"); //anim.Play("站立01"); avatar = AvatarBuilder.BuildGenericAvatar(gameObject, ""); avatar.name = "Bob"; Debug.Log(avatar.isHuman ? "is human" : "is generic"); }
public static void builAvatarMask(GameObject gameObject, SpineData spineData, Animator animator, string directory, string name) { Avatar avatar = AvatarBuilder.BuildGenericAvatar(gameObject, ""); animator.avatar = avatar; AvatarMask avatarMask = new AvatarMask(); string[] transofrmPaths = getTransformPaths(gameObject, spineData); avatarMask.transformCount = transofrmPaths.Length; for (int i = 0; i < transofrmPaths.Length; i++) { avatarMask.SetTransformPath(i, transofrmPaths[i]); avatarMask.SetTransformActive(i, true); } createFolderIfNoExists(directory, ANIMATION_FOLDER); AssetDatabase.CreateAsset(avatar, directory + "/" + ANIMATION_FOLDER + "/" + name + ".anim.asset"); AssetDatabase.CreateAsset(avatarMask, directory + "/" + ANIMATION_FOLDER + "/" + name + ".mask.asset"); }
public static int BuildGenericAvatar_s(IntPtr l) { int result; try { GameObject go; LuaObject.checkType <GameObject>(l, 1, out go); string rootMotionTransformName; LuaObject.checkType(l, 2, out rootMotionTransformName); Avatar o = AvatarBuilder.BuildGenericAvatar(go, rootMotionTransformName); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
private static Avatar CreateAvatar(RuntimeAnimatorController controller, AvatarMask avatarMask) { GameObject avatarGameObject = new GameObject(controller.name + " LOD Avatar"); if (avatarMask != null) { for (int i = 0; i < avatarMask.transformCount; i++) { if (avatarMask.GetTransformActive(i)) { string[] pathObjects = avatarMask.GetTransformPath(i).Split('/'); AddPath(avatarGameObject.transform, pathObjects, 0); } } } Avatar avatar = AvatarBuilder.BuildGenericAvatar(avatarGameObject, ""); Destroy(avatarGameObject); return(avatar); }
private static void GenerateAvatarData(string file, List <SkinBone> bones) { string basePath = Path.GetDirectoryName(file) + "/" + Path.GetFileNameWithoutExtension(file); SkinAvatar skinAvatar = ScriptableObject.CreateInstance <SkinAvatar>(); skinAvatar.bonesParent = new int[bones.Count]; skinAvatar.bonesName = new string[bones.Count]; skinAvatar.invBindPose = new float[bones.Count * 7]; for (int i = 0; i < bones.Count; ++i) { skinAvatar.bonesParent[i] = bones[i].parent; skinAvatar.bonesName[i] = bones[i].transform.name; var inv = bones[i].transform.worldToLocalMatrix; var pos = inv.GetColumn(3); var rot = Quaternion.LookRotation(inv.GetColumn(2), inv.GetColumn(1)); skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 0] = pos.x; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 1] = pos.y; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 2] = pos.z; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 3] = rot.x; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 4] = rot.y; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 5] = rot.z; skinAvatar.invBindPose[i * SkinAnimationClip.STRIDE + 6] = rot.w; } AssetDatabase.CreateAsset(skinAvatar, basePath + "_SkeletonAvatar.asset"); GameObject gameObject = new GameObject(); gameObject.name = "Empty"; Avatar avatar = AvatarBuilder.BuildGenericAvatar(gameObject, "Empty"); AssetDatabase.CreateAsset(avatar, basePath + "_Empty.avatar.asset"); GameObject.DestroyImmediate(gameObject); }
/// <summary> /// 汎用アバダーを設定する /// </summary> /// <returns>アニメーター</returns> public Animator SettingGenericAvatar() { //アバタールートトランスフォームの取得 Transform avatar_root_transform = root_game_object_.transform.Find("Model"); if (null == avatar_root_transform) { //ルートゲームオブジェクト直下にモデルルートオブジェクトが無い(PMDConverter)なら //ルートゲームオブジェクトをアバタールートオブジェクトとする avatar_root_transform = root_game_object_.transform; } //ジェネリックアバター作成 string root_name = ((HasBone("全ての親"))? "全ての親": ""); avatar_ = AvatarBuilder.BuildGenericAvatar(avatar_root_transform.gameObject, root_name); //アバターをアニメーターに設定 animator_ = root_game_object_.AddComponent <Animator>(); animator_.avatar = avatar_; return(animator_); }
public override void OnInspectorGUI() { var obj = target as AnimatorParameterSetter; if (obj == null) { return; } Animator animator = obj.GetComponentInParent <Animator>() as Animator; //as of 5_6_f3, putting an empty avatar onto the animator seems to fix the "animator is not playing an AnimatorController" warning if (animator.runtimeAnimatorController != null && animator.avatar == null) { if (GUILayout.Button("Generate Avatar")) { string path = AssetDatabase.GetAssetPath(animator.runtimeAnimatorController); path = path.Split(new string[1] { ".controller" }, StringSplitOptions.RemoveEmptyEntries)[0] + "_avatar.avatar"; var avatar = AvatarBuilder.BuildGenericAvatar(animator.transform.root.gameObject, ""); AssetDatabase.CreateAsset(avatar, path); animator.avatar = avatar; } } if (animator != null && animator.runtimeAnimatorController != null) { var serializedUpdateMode = serializedObject.FindProperty("mode"); EditorGUILayout.PropertyField(serializedUpdateMode, new GUIContent("Mode: ")); if (animator.parameterCount == 0) { return; } AnimatorControllerParameter[] parameters = new AnimatorControllerParameter[animator.parameterCount]; string[] parameterNames = new string[animator.parameterCount]; for (int i = 0; i < animator.parameterCount; ++i) { parameters[i] = animator.GetParameter(i); parameterNames[i] = parameters[i].name; } SerializedProperty serializedParameter = serializedObject.FindProperty("parameter"); int parameterIndex = 0; for (int i = 0; i < parameterNames.Length; ++i) { if (string.Equals(parameterNames[i], serializedParameter.stringValue, StringComparison.Ordinal)) { parameterIndex = i; break; } } parameterIndex = EditorGUILayout.Popup("Parameter: ", parameterIndex, parameterNames); if (parameterIndex >= 0 && parameterIndex < parameterNames.Length) { serializedParameter.stringValue = parameterNames[parameterIndex]; AnimatorControllerParameter selectedParameter = parameters[parameterIndex]; if (selectedParameter != null) { switch (selectedParameter.type) { case AnimatorControllerParameterType.Bool: SerializedProperty boolProp = serializedObject.FindProperty("value_bool"); EditorGUILayout.PropertyField(boolProp, new GUIContent("Value: ")); break; case AnimatorControllerParameterType.Float: SerializedProperty floatProp = serializedObject.FindProperty("value_number"); EditorGUILayout.PropertyField(floatProp, new GUIContent("Value: ")); break; case AnimatorControllerParameterType.Int: SerializedProperty intProp = serializedObject.FindProperty("value_number"); EditorGUILayout.PropertyField(intProp, new GUIContent("Value: ")); break; case AnimatorControllerParameterType.Trigger: break; } } } } serializedObject.ApplyModifiedProperties(); }
public void BuildPrefab(bool erase = false) { ToolBox.DirExNorCreate("Assets/Resources/Prefabs/Zones/"); string zoneFolder = "Assets/Resources/Prefabs/Zones/Zone" + ZoneID + "/"; ToolBox.DirExNorCreate(zoneFolder); string path = zoneFolder + "Unit" + UnitID + ".prefab"; GameObject pref = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject; if (pref != null && erase == false) { return; } else { if (erase) { AssetDatabase.DeleteAsset(path); } } #if UNITY_EDITOR GameObject shapeGO = null; GameObject weaponGO; GameObject shieldGO; if (zudShape != null) { shapeGO = zudShape.BuildGameObject(); AssetDatabase.AddObjectToAsset(zudShape.mesh, path); AssetDatabase.AddObjectToAsset(zudShape.texture, path); AssetDatabase.AddObjectToAsset(zudShape.material, path); } if (zudWeapon != null) { weaponGO = zudWeapon.BuildGameObject(); if (shapeGO) { weaponGO.transform.parent = shapeGO.transform; } AssetDatabase.AddObjectToAsset(zudWeapon.mesh, path); AssetDatabase.AddObjectToAsset(zudWeapon.texture, path); AssetDatabase.AddObjectToAsset(zudWeapon.material, path); } if (zudShield != null) { shieldGO = zudShield.BuildGameObject(); if (shapeGO) { shieldGO.transform.parent = shapeGO.transform; } AssetDatabase.AddObjectToAsset(zudShield.mesh, path); AssetDatabase.AddObjectToAsset(zudShield.texture, path); AssetDatabase.AddObjectToAsset(zudShield.material, path); } AnimatorController ac; if ((zudComSeq != null || zudBatSeq != null) && shapeGO != null) { Avatar ava = AvatarBuilder.BuildGenericAvatar(shapeGO, ""); //Avatar ava = AvatarBuilder.BuildHumanAvatar(shapeGO, new HumanDescription()); ava.name = FileName + "_Ava"; //ava.humanDescription. AssetDatabase.AddObjectToAsset(ava, path); Animator animator = shapeGO.GetComponent <Animator>(); if (!animator) { animator = shapeGO.AddComponent <Animator>(); } ac = AnimatorController.Instantiate(AssetDatabase.LoadAssetAtPath <AnimatorController>("Assets/Resources/Prefabs/DefaultAC.controller") as AnimatorController); ac.name = FileName + "_AC"; animator.runtimeAnimatorController = ac; animator.avatar = ava; AssetDatabase.AddObjectToAsset(ac, path); int i = 0; if (zudComSeq != null && shapeGO != null) { zudComSeq.FirstPoseModel(shapeGO); AnimationClip[] clips = zudComSeq.BuildAnimationClips(shapeGO); ac.AddLayer(FileName + "_COM"); i++; foreach (AnimationClip clip in clips) { if (clip != null) { AssetDatabase.AddObjectToAsset(clip, path); AnimatorState state = ac.layers[i].stateMachine.AddState(clip.name); state.motion = clip; } } } if (zudBatSeq != null && shapeGO != null) { if (zudComSeq == null) { zudBatSeq.FirstPoseModel(shapeGO); } AnimationClip[] clips = zudBatSeq.BuildAnimationClips(shapeGO); ac.AddLayer(FileName + "_BAT"); i++; foreach (AnimationClip clip in clips) { if (clip != null) { AssetDatabase.AddObjectToAsset(clip, path); AnimatorState state = ac.layers[i].stateMachine.AddState(clip.name); state.motion = clip; } } } } GameObject prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(shapeGO, path, InteractionMode.AutomatedAction); AssetDatabase.SaveAssets(); GameObject.DestroyImmediate(shapeGO); #endif }
/* * * Convert Meshes */ public Dictionary <long, Mesh> ConvertMeshes(AMF amf, Dictionary <string, Material> mats, Dictionary <string, AMFShaderInfo> matHelpers, GameObject root) { //List<Mesh> meshList = new List<Mesh>(); Dictionary <long, Mesh> meshCache = new Dictionary <long, Mesh>(); float meshComplete = 0; float totalMeshCount = 0; List <GameObject> meshNodes = new List <GameObject>(); List <Transform> nodes = null; if (CreateSkinnedMeshes) { nodes = CreateRigging(amf); nodes[0].parent = root.transform; Animator anim = root.AddComponent <Animator>(); //Transform rigRoot=root.GetComponentInChildren<SkinnedMeshRenderer>().rootBone; if (copyAvatar) { //ctx.AddObjectToAsset(m_LastHumanDescriptionAvatarSource.name,m_LastHumanDescriptionAvatarSource); anim.avatar = m_LastHumanDescriptionAvatarSource; } else { //EditorUtility.DisplayProgressBar("Parsing "+ctx.assetPath,"Creating Avatar",(5f/5f)); List <string> reports = new List <string>(); HumanDescription hd = new HumanDescription(); AvatarSetupTool.SkeletonBone[] skeletonBones; bool hasTranslationDOF; reports = AvatarSetupTool.SetupHumanSkeleton(nodes[0].parent.gameObject, ref hd.human, out skeletonBones, out hasTranslationDOF); hd.hasTranslationDoF = hasTranslationDOF; SkeletonBone[] sb = new SkeletonBone[skeletonBones.Length + 1]; Array.Copy(Array.ConvertAll(skeletonBones, (p => (SkeletonBone)p)), sb, sb.Length - 1); sb[sb.Length - 1].name = nodes[0].parent.name; sb[sb.Length - 1].position = nodes[0].parent.localPosition; sb[sb.Length - 1].rotation = nodes[0].parent.localRotation; sb[sb.Length - 1].scale = nodes[0].parent.localScale; hd.skeleton = sb; Avatar a; if (rigType == RigType.Humanoid) { a = AvatarBuilder.BuildHumanAvatar(nodes[0].parent.gameObject, hd); } else { a = AvatarBuilder.BuildGenericAvatar(nodes[0].parent.gameObject, nodes[0].parent.name); } a.name = root.name + "Avatar"; //ctx.AddObjectToAsset(a.name,a); anim.avatar = a; } } foreach (AMF_RegionInfo ri in amf.regionInfo) { totalMeshCount += ri.permutations.Count; } for (int ri = 0; ri < amf.regionInfo.Count; ri++) { GameObject riNode = new GameObject(amf.regionInfo[ri].name); GameObjectUtility.SetParentAndAlign(riNode, root); foreach (AMF_Permutations perm in amf.regionInfo[ri].permutations) { EditorUtility.DisplayProgressBar("Creating Meshes", perm.pName, (meshComplete / totalMeshCount)); Mesh temp; if (createDuplicateInstances || !meshCache.ContainsKey(perm.vAddress)) { temp = ConvertInstanceToMesh(perm); //we have to flip the normals due to the coordinate system translation temp.FlipNormals(); temp.RecalculateNormals(); if (GenerateLightmapUVs) { EditorUtility.DisplayProgressBar("Generating Lightmap UVs", perm.pName, (meshComplete / totalMeshCount)); uvSettings.angleError = angleError; uvSettings.areaError = areaError; uvSettings.hardAngle = hardAngle; uvSettings.packMargin = packMargin; Unwrapping.GenerateSecondaryUVSet(temp, uvSettings); } meshCache.Add(perm.vAddress, temp); } else { temp = meshCache[perm.vAddress]; } GameObject meshNode = new GameObject(perm.pName); Matrix4x4 matr = Matrix4x4.identity; if (!float.IsNaN(perm.mult)) { Matrix4x4 scalerM = new Matrix4x4(); scalerM.SetRow(0, new Vector4(100f * m_FileScaleFactor, 0)); scalerM.SetRow(1, new Vector4(0, 100f * m_FileScaleFactor)); scalerM.SetRow(2, new Vector4(0, 0, 100f * m_FileScaleFactor)); scalerM.SetRow(3, new Vector4(0, 0, 0, 1)); matr.SetRow(0, new Vector4(perm.mult, 0)); matr.SetRow(1, new Vector4(0, perm.mult)); matr.SetRow(2, new Vector4(0, 0, perm.mult)); matr.SetRow(3, new Vector4(0, 0, 0, 1)); matr *= perm.matrix4x4; matr *= scalerM; Matrix4x4 unityMatr = matr.Convert3DSMatrixToUnity(); meshNode.transform.localScale = unityMatr.ExtractScale(); meshNode.transform.localRotation = unityMatr.GetRotation(); meshNode.transform.localPosition = unityMatr.ExtractPosition(); } else { meshNode.transform.localScale = new Vector3(m_FileScaleFactor, m_FileScaleFactor, m_FileScaleFactor); } //GameObjectUtility.SetParentAndAlign(meshNode,riNode); //meshNode.transform.localToWorldMatrix=matr; Renderer mr; if (temp.boneWeights.Length > 0 && CreateSkinnedMeshes) { mr = meshNode.AddComponent <SkinnedMeshRenderer>(); meshNode.transform.localRotation = Quaternion.Euler(0, 90, 0); Matrix4x4[] bindPoses = new Matrix4x4[nodes.Count]; for (int m = 0; m < bindPoses.Length; m++) { bindPoses[m] = nodes[m].worldToLocalMatrix * meshNode.transform.localToWorldMatrix; } temp.bindposes = bindPoses; ((SkinnedMeshRenderer)mr).sharedMesh = temp; ((SkinnedMeshRenderer)mr).bones = nodes.ToArray(); ((SkinnedMeshRenderer)mr).rootBone = nodes[0]; } else { MeshFilter mf = meshNode.AddComponent <MeshFilter>(); mf.sharedMesh = temp; mr = meshNode.AddComponent <MeshRenderer>(); if (RecenterPivots && !splitSubmeshes) { //for safety, lets guard this against splitting submeshes. mf.RecenterPivot(); } } meshNode.transform.parent = riNode.transform; if (GenerateMeshCollidersOnClusters && amf.regionInfo[ri].name.Equals("Clusters")) { MeshCollider mc = meshNode.AddComponent <MeshCollider>(); mc.sharedMesh = temp; } Material[] materials = new Material[temp.subMeshCount]; List <AMFShaderInfo> si = new List <AMFShaderInfo>(); for (int i = 0; i < materials.Length; i++) { materials[i] = mats[amf.shaderInfos[perm.meshes[i].shaderIndex].sName]; si.Add(matHelpers[amf.shaderInfos[perm.meshes[i].shaderIndex].sName]); //si[i].SaveData(amf.shaderInfos[perm.meshes[i].shaderIndex]); } mr.sharedMaterials = materials; AMFMaterialHelper mh = meshNode.AddComponent <AMFMaterialHelper>(); mh.shaderSettings = si; //mh.SaveData(amf.shaderInfos[perm.meshes[0].shaderIndex]); //Debug.LogFormat("Transform: Pos:{0} Rot:{1} Scale:{2}",perm.matrix4x4.ExtractPosition(),perm.matrix4x4.ExtractRotation(),perm.matrix4x4.ExtractScale()); meshComplete++; meshNodes.Add(meshNode); } } //This is annoying to do this here, but we have to wait until after the mesh cache is fully populated before we start splitting submeshes out. if (splitSubmeshes) { meshCache.Clear(); long fakeKey = 0; foreach (GameObject go in meshNodes) { MeshFilter mf = go.GetComponent <MeshFilter>(); if (mf != null && mf.sharedMesh.subMeshCount > 1) { Renderer r = go.GetComponent <MeshRenderer>(); for (int i = 0; i < mf.sharedMesh.subMeshCount; i++) { int matIndex = Mathf.Min(i, r.sharedMaterials.Length); GameObject tempGo = new GameObject(go.name + "_" + r.sharedMaterials[matIndex].name); MeshFilter tempMF = tempGo.AddComponent <MeshFilter>(); tempMF.sharedMesh = mf.sharedMesh.ExtractSubmesh(i); tempGo.AddComponent <MeshRenderer>().sharedMaterial = r.sharedMaterials[matIndex]; GameObjectUtility.SetParentAndAlign(tempGo, go); if (RecenterPivots) { tempMF.RecenterPivot(); } meshCache.Add(fakeKey, tempGo.GetComponent <MeshFilter>().sharedMesh); fakeKey++; } DestroyImmediate(mf); DestroyImmediate(r); } else { if (RecenterPivots) { go.GetComponent <MeshFilter>().RecenterPivot(); } meshCache.Add(fakeKey, go.GetComponent <MeshFilter>().sharedMesh); fakeKey++; } } } return(meshCache); }
public override void OnImportAsset(AssetImportContext ctx) { string[] text = ReadFile(ctx.assetPath); this.Populate(text); var root = new GameObject(); root.name = Path.GetFileNameWithoutExtension(ctx.assetPath); GameObject[] nodes = this.GenerateNodes(); this.GenerateMarkers(nodes); nodes[0].transform.parent = root.transform; Material[] materials = this.materials.Select( m => { var material = new Material(Shader.Find("Diffuse")); material.name = m.name; return(material); } ).ToArray(); Mesh[] meshes = this.GenerateMeshesh(); GameObject[] models = meshes.Select( mesh => { var model = new GameObject(mesh.name); MeshFilter meshFilter = model.AddComponent <MeshFilter>(); SkinnedMeshRenderer skinnedMeshRenderer = model.AddComponent <SkinnedMeshRenderer>(); meshFilter.sharedMesh = mesh; skinnedMeshRenderer.sharedMesh = mesh; skinnedMeshRenderer.quality = SkinQuality.Bone2; mesh.bindposes = nodes.Select( node => node.transform.worldToLocalMatrix * model.transform.localToWorldMatrix ).ToArray(); skinnedMeshRenderer.bones = nodes.Select(e => e.transform).ToArray(); skinnedMeshRenderer.rootBone = nodes[0].transform; skinnedMeshRenderer.sharedMaterials = materials; model.transform.parent = root.transform; return(model); } ).ToArray(); foreach (Material mat in materials) { ctx.AddObjectToAsset(mat.name, mat); } foreach (Mesh mesh in meshes) { ctx.AddObjectToAsset(mesh.name, mesh); } // avatar Avatar avatar = AvatarBuilder.BuildGenericAvatar(root, nodes[0].transform.name); avatar.name = root.name + "Avatar"; avatar.hideFlags = HideFlags.None; Animator animator = root.AddComponent <Animator>(); animator.avatar = avatar; AvatarMask mask = new AvatarMask(); mask.name = root.name + "AvatarMask"; foreach (var node in nodes) { mask.AddTransformPath(node.transform); } ctx.AddObjectToAsset(avatar.name, avatar); ctx.AddObjectToAsset(mask.name, mask); ctx.AddObjectToAsset("root", root); ctx.SetMainObject(root); }
public void Build(bool buildPrefab = false) { // Building Model for (int i = 0; i < numFaces; i++) { for (int j = 0; j < faces[i].verticesCount; j++) { if (tim != null) { float u = faces[i].uv[j].x / tim.width; float v = faces[i].uv[j].y / tim.height; faces[i].uv[j] = (new Vector2(u, v)); } else { faces[i].uv[j] = Vector2.zero; } } } Mesh shapeMesh = new Mesh(); List <Vector3> meshVertices = new List <Vector3>(); List <int> meshTriangles = new List <int>(); List <Vector2> meshTrianglesUV = new List <Vector2>(); List <BoneWeight> meshWeights = new List <BoneWeight>(); List <Color32> meshColors = new List <Color32>(); for (int i = 0; i < faces.Count; i++) { //Debug.Log("faces["+i+"] .type : " + faces[i].type + " || .size : " + faces[i].size + " || .side : " + faces[i].side + " || .alpha : " + faces[i].alpha); if (faces[i].type == 0x2C || faces[i].type == 0x3C) { if (faces[i].side != 4) { meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTrianglesUV.Add(faces[i].uv[0]); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[2]); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[3]].position); meshWeights.Add(vertices[faces[i].vertices[3]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTrianglesUV.Add(faces[i].uv[3]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[1]); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[0]); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[3]].position); meshWeights.Add(vertices[faces[i].vertices[3]].boneWeight); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[3]); if (excpFaces) { // we have colored vertices meshColors.Add(faces[i].colors[0]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[3]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[0]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[3]); } } else { meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTrianglesUV.Add(faces[i].uv[0]); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[2]); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[3]].position); meshWeights.Add(vertices[faces[i].vertices[3]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTrianglesUV.Add(faces[i].uv[3]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[1]); if (excpFaces) { // we have colored vertices meshColors.Add(faces[i].colors[0]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[3]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[1]); } } } else if (faces[i].type == 0x24 || faces[i].type == 0x34) { if (faces[i].side != 4) { meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[0]); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTrianglesUV.Add(faces[i].uv[0]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[1]); if (excpFaces) { // we have colored vertices meshColors.Add(faces[i].colors[0]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[2]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[0]); } } else { meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[0]].position); meshWeights.Add(vertices[faces[i].vertices[0]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[1]].position); meshWeights.Add(vertices[faces[i].vertices[1]].boneWeight); meshTriangles.Add(meshVertices.Count); meshVertices.Add(vertices[faces[i].vertices[2]].position); meshWeights.Add(vertices[faces[i].vertices[2]].boneWeight); meshTrianglesUV.Add(faces[i].uv[1]); meshTrianglesUV.Add(faces[i].uv[2]); meshTrianglesUV.Add(faces[i].uv[0]); if (excpFaces) { // we have colored vertices meshColors.Add(faces[i].colors[0]); meshColors.Add(faces[i].colors[1]); meshColors.Add(faces[i].colors[2]); } } } } shapeMesh.name = FileName + "_mesh"; shapeMesh.vertices = meshVertices.ToArray(); shapeMesh.triangles = meshTriangles.ToArray(); shapeMesh.uv = meshTrianglesUV.ToArray(); shapeMesh.boneWeights = meshWeights.ToArray(); if (excpFaces) { shapeMesh.colors32 = meshColors.ToArray(); } if (tim != null) { texture = tim.textures[0]; texture.filterMode = FilterMode.Trilinear; texture.anisoLevel = 4; #if UNITY_EDITOR texture.alphaIsTransparency = true; #endif texture.wrapMode = TextureWrapMode.Repeat; texture.Compress(true); } else { texture = new Texture2D(128, 128); } Material mat = null; if (excpFaces) { Shader shader = Shader.Find("Particles/Standard Unlit"); mat = new Material(shader); mat.name = string.Concat("Material_SHP_", FileName); mat.SetTexture("_MainTex", texture); mat.SetFloat("_Mode", 0); mat.SetFloat("_ColorMode", 0); mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); mat.SetInt("_ZWrite", 1); mat.EnableKeyword("_ALPHATEST_ON"); mat.DisableKeyword("_ALPHABLEND_ON"); mat.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mat.SetTextureScale("_MainTex", new Vector2(1, -1)); } else { Shader shader = Shader.Find("Standard"); mat = new Material(shader); mat.name = string.Concat("Material_SHP_", FileName); mat.SetTexture("_MainTex", texture); mat.SetFloat("_Mode", 1); mat.SetFloat("_Cutoff", 0.5f); mat.SetFloat("_Glossiness", 0.0f); mat.SetFloat("_SpecularHighlights", 0.0f); mat.SetFloat("_GlossyReflections", 0.0f); mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); mat.SetInt("_ZWrite", 1); mat.EnableKeyword("_ALPHATEST_ON"); mat.DisableKeyword("_ALPHABLEND_ON"); mat.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mat.SetTextureScale("_MainTex", new Vector2(1, -1)); } material = mat; GameObject shapeGo = new GameObject(FileName); GameObject meshGo = new GameObject(FileName + "_mesh"); meshGo.transform.parent = shapeGo.transform; Transform[] meshBones = new Transform[numBones]; Matrix4x4[] bindPoses = new Matrix4x4[numBones]; for (int i = 0; i < numBones; i++) { meshBones[i] = new GameObject(bones[i].name).transform; meshBones[i].localRotation = Quaternion.identity; bindPoses[i] = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one); if (bones[i].parentIndex == -1) { meshBones[i].parent = shapeGo.transform; meshBones[i].localPosition = Vector3.zero; } else { meshBones[i].parent = meshBones[bones[i].parentIndex]; meshBones[i].localPosition = new Vector3((float)(bones[bones[i].parentIndex].length) / 100, 0, 0); } } SkinnedMeshRenderer mr = meshGo.AddComponent <SkinnedMeshRenderer>(); mr.material = mat; mr.bones = meshBones; shapeMesh.bindposes = bindPoses; mr.rootBone = meshBones[0]; mr.sharedMesh = shapeMesh; mesh = shapeMesh; this.shapeGo = shapeGo; string modFolder = "Assets/Resources/Prefabs/Models/"; string modFilename = string.Concat(modFolder, "SHP_", FileName, ".prefab"); #if UNITY_EDITOR if (buildPrefab == true) { GameObject shpBase = shapeGo; GameObject prefab = PrefabUtility.SaveAsPrefabAsset(shpBase, modFilename); string shpId = FileName; if (shpId == "06" || shpId == "99" || shpId == "C9" || shpId == "CA") { shpId = "00"; // Ashley Shapes } if (shpId == "7C") { shpId = "02"; // Rozencrantz } if (shpId == "9B") { shpId = "03"; // Merlose } if (shpId == "98") { shpId = "83"; // Sydney } // Animations seeker Avatar ava = AvatarBuilder.BuildGenericAvatar(shpBase, "bone_0"); ava.name = FileName + "_Ava"; AssetDatabase.AddObjectToAsset(ava, modFilename); Animator animator = shpBase.GetComponent <Animator>(); if (!animator) { animator = shpBase.AddComponent <Animator>(); } AnimatorController ac = AnimatorController.Instantiate(AssetDatabase.LoadAssetAtPath <AnimatorController>("Assets/Resources/Prefabs/DefaultAC.controller") as AnimatorController); ac.name = FileName + "_AC"; animator.runtimeAnimatorController = ac; animator.avatar = ava; AssetDatabase.AddObjectToAsset(ac, modFilename); string[] hash = FilePath.Split("/"[0]); hash[hash.Length - 1] = ""; string[] files = Directory.GetFiles(String.Join("/", hash), "*.SEQ"); bool posed = false; uint i = 0; foreach (string file in files) { List <string> topa = new List <string>(); topa.Add("_COM.SEQ"); topa.Add("_BT1.SEQ"); topa.Add("_BT2.SEQ"); topa.Add("_BT3.SEQ"); topa.Add("_BT4.SEQ"); topa.Add("_BT5.SEQ"); topa.Add("_BT6.SEQ"); topa.Add("_BT7.SEQ"); topa.Add("_BT8.SEQ"); topa.Add("_BT9.SEQ"); topa.Add("_BTA.SEQ"); hash = file.Split("/"[0]); if (hash[hash.Length - 1].StartsWith(shpId) && file.EndsWith(".SEQ")) { if (topa.Contains(hash[hash.Length - 1].Substring(2, 8))) { SEQ _seq = new SEQ(); _seq.Parse(file); if (!posed || file == shpId + "_COM.SEQ") { posed = true; _seq.FirstPoseModel(shpBase); Mesh baked = new Mesh(); baked.name = string.Concat("Baked_Mesh_SHP_", FileName); mr.BakeMesh(baked); //baked.bindposes = bindPoses; // need to recalculate this before using the baked mesh //baked.boneWeights = meshWeights.ToArray(); //mr.sharedMesh = baked; //shapeMesh.RecalculateNormals(); shapeMesh.RecalculateTangents(); shapeMesh.Optimize(); //AssetDatabase.RemoveObjectFromAsset(mesh); AssetDatabase.AddObjectToAsset(baked, modFilename); } AnimationClip[] clips = _seq.BuildAnimationClips(shpBase); AnimatorControllerLayer layer = new AnimatorControllerLayer(); layer.name = hash[hash.Length - 1].Substring(0, 6); layer.stateMachine = new AnimatorStateMachine(); layer.stateMachine.states = ac.layers[0].stateMachine.states; ac.AddLayer(hash[hash.Length - 1].Substring(0, 6)); i++; foreach (AnimationClip clip in clips) { if (clip != null) { AssetDatabase.AddObjectToAsset(clip, modFilename); AnimatorState state = ac.layers[i].stateMachine.AddState(clip.name); state.motion = clip; } } } } } if (shpBase != null) { mesh = shapeMesh; AssetDatabase.AddObjectToAsset(mesh, modFilename); AssetDatabase.AddObjectToAsset(material, modFilename); AssetDatabase.AddObjectToAsset(texture, modFilename); } //PrefabUtility.ReplacePrefab(shpBase, prefab); prefab = PrefabUtility.SaveAsPrefabAsset(shpBase, modFilename); AssetDatabase.SaveAssets(); GameObject.DestroyImmediate(shpBase); } #endif mesh = shapeMesh; }
protected void UpdateAvatar() { Undo.RecordObject(animationObject, "Update Avatar"); string assetPath = ""; if (animationObject.avatar != null && AssetDatabase.Contains(animationObject.avatar)) { assetPath = AssetDatabase.GetAssetPath(animationObject.avatar); } animationObject.avatar = null; switch (animationObject.rigAnimationType) { case VoxelSkinnedAnimationObject.RigAnimationType.Legacy: break; case VoxelSkinnedAnimationObject.RigAnimationType.Generic: if (animationObject.rootBone != null) { Dictionary <Transform, Transform> saveList = new Dictionary <Transform, Transform>(); List <Transform> findList = new List <Transform>(); for (int j = 0; j < animationObject.transform.childCount; j++) { findList.Add(animationObject.transform.GetChild(j)); } for (int i = 0; i < findList.Count; i++) { for (int j = 0; j < findList[i].childCount; j++) { findList.Add(findList[i].GetChild(j)); } if (findList[i].GetComponent <VoxelSkinnedAnimationObjectBone>() == null) { saveList.Add(findList[i], findList[i].parent); findList[i].SetParent(null); } } animationObject.avatar = AvatarBuilder.BuildGenericAvatar(animationObject.gameObject, animationObject.rootBone.gameObject.name); { var enu = saveList.GetEnumerator(); while (enu.MoveNext()) { enu.Current.Key.SetParent(enu.Current.Value); } } } break; case VoxelSkinnedAnimationObject.RigAnimationType.Humanoid: if (animationObject.rootBone != null) { HumanDescription humanDescription = new HumanDescription() { upperArmTwist = animationObject.humanDescription.upperArmTwist, lowerArmTwist = animationObject.humanDescription.lowerArmTwist, upperLegTwist = animationObject.humanDescription.upperLegTwist, lowerLegTwist = animationObject.humanDescription.lowerLegTwist, armStretch = animationObject.humanDescription.armStretch, legStretch = animationObject.humanDescription.legStretch, feetSpacing = animationObject.humanDescription.feetSpacing, hasTranslationDoF = animationObject.humanDescription.hasTranslationDoF, }; #region CreateHumanAndSkeleton { List <HumanBone> humanBones = new List <HumanBone>(); List <SkeletonBone> skeletonBones = new List <SkeletonBone>(); if (!animationObject.humanDescription.firstAutomapDone) { AutomapHumanDescriptionHuman(); animationObject.humanDescription.firstAutomapDone = true; } for (int i = 0; i < VoxelSkinnedAnimationObject.HumanTraitBoneNameTable.Length; i++) { var index = VoxelSkinnedAnimationObject.HumanTraitBoneNameTable[i]; if (animationObject.humanDescription.bones[(int)index] == null) { continue; } humanBones.Add(new HumanBone() { boneName = animationObject.humanDescription.bones[(int)index].name, humanName = HumanTrait.BoneName[i], limit = new HumanLimit() { useDefaultValues = true }, }); } #region FindBones { skeletonBones.Add(new SkeletonBone() { name = animationObject.rootBone.parent.name, position = animationObject.rootBone.parent.localPosition, rotation = animationObject.rootBone.parent.localRotation, scale = animationObject.rootBone.parent.localScale, }); for (int i = 0; i < VoxelSkinnedAnimationObject.HumanTraitBoneNameTable.Length; i++) { var index = VoxelSkinnedAnimationObject.HumanTraitBoneNameTable[i]; if (animationObject.humanDescription.bones[(int)index] == null) { continue; } skeletonBones.Add(new SkeletonBone() { name = animationObject.humanDescription.bones[(int)index].name, position = animationObject.humanDescription.bones[(int)index].transform.localPosition, rotation = Quaternion.identity, scale = Vector3.one, }); } } #endregion humanDescription.human = humanBones.ToArray(); humanDescription.skeleton = skeletonBones.ToArray(); } #endregion animationObject.avatar = AvatarBuilder.BuildHumanAvatar(animationObject.gameObject, humanDescription); } break; } if (animationObject.avatar != null) { animationObject.avatar.name = animationObject.gameObject.ToString(); if (!string.IsNullOrEmpty(assetPath)) { AssetDatabase.DeleteAsset(assetPath); AssetDatabase.CreateAsset(animationObject.avatar, assetPath); } } }