public void AnotherButtonClick(PdxShape go) { if (self != go) { buttonImage.color = initialColor; } }
public void ClearScene() { meshBase = null; animBase = null; bonesByName.Clear(); foreach (GameObject g in loadedObjects) { Destroy(g); } loadedObjects.Clear(); selectedObject = null; selectedShape = null; attachedObject = null; }
public void SelectObjectInHierarchy(PdxShape go) { if (!firstHL) { go.Highlight(); } firstHL = false; loader.selectedShape = go; matShader.text = go.shader; matDiffuse.text = string.IsNullOrEmpty(go.diffuse) ? "no diffuse" : Path.GetFileName(go.diffuse); matNormal.text = string.IsNullOrEmpty(go.normal) ? "no normal" : Path.GetFileName(go.normal); matSpecular.text = string.IsNullOrEmpty(go.specular) ? "no specular" : Path.GetFileName(go.specular); ObjectButton[] buttons = FindObjectsOfType <ObjectButton>(); foreach (ObjectButton b in buttons) { b.AnotherButtonClick(go); } }
public Base BaseFromGameObject(GameObject target) { Matrix4x4 world = target.transform.localToWorldMatrix; Vector3 lastPos = target.transform.position; PdxAnimationPlayer player = target.GetComponent <PdxAnimationPlayer>(); if (player != null) { player.SetTpose(); } target.transform.position = Vector3.zero; List <Transform> shapes = new List <Transform>(); FindTagInChildren(shapes, target.transform, "Shape", target.transform); Base _base = new Base("PdxData", "object"); Base _pdxasset = new Base("pdxasset", "int", _base); _pdxasset.value = new List <Base.Data>() { Base.Data.Int(1), Base.Data.Int(0) }; Base _object = new Base("object", "object", _base); foreach (Transform sh in shapes) { MeshFilter mf = sh.GetComponent <MeshFilter>(); MeshRenderer mr = sh.GetComponent <MeshRenderer>(); SkinnedMeshRenderer smr = sh.GetComponent <SkinnedMeshRenderer>(); PdxShape shapeData = sh.GetComponent <PdxShape>(); bool isCollider = sh.gameObject.tag == "Collider"; bool skinned = smr != null; Mesh mesh; Material mat; if (isCollider) { mesh = mf.mesh; mat = null; } else if (skinned) { mesh = smr.sharedMesh; mat = smr.material; } else { mesh = mf.mesh; mat = mr.material; } Base _shape = _object.subNodes.ContainsKey(sh.name) ? _object.subNodes[sh.name] : new Base(sh.name.Replace(" Instance", ""), "object", _object); Base _mesh = new Base("mesh", "object", _shape); Base _p = new Base("p", "float", _mesh); foreach (Vector3 p in mesh.vertices) { Vector3 pW = world.MultiplyPoint3x4(p); _p.value.Add(Base.Data.Float(pW.x)); _p.value.Add(Base.Data.Float(pW.y)); _p.value.Add(Base.Data.Float(pW.z)); } if (!isCollider) { Base _n = new Base("n", "float", _mesh); foreach (Vector3 n in mesh.normals) { Vector3 nW = world.MultiplyPoint3x4(n); _n.value.Add(Base.Data.Float(nW.x)); _n.value.Add(Base.Data.Float(nW.y)); _n.value.Add(Base.Data.Float(nW.z)); } Base _ta = new Base("ta", "float", _mesh); foreach (Vector4 ta in mesh.tangents) { Vector4 taW = world * ta; _ta.value.Add(Base.Data.Float(taW.x)); _ta.value.Add(Base.Data.Float(taW.y)); _ta.value.Add(Base.Data.Float(taW.z)); _ta.value.Add(Base.Data.Float(taW.w)); } Base _uv = new Base("u0", "float", _mesh); foreach (Vector2 uv in mesh.uv) { _uv.value.Add(Base.Data.Float(uv.x)); _uv.value.Add(Base.Data.Float(uv.y)); } if (mesh.uv2 != null && mesh.uv2.Length > 0) { Base _uv1 = new Base("u1", "float", _mesh); foreach (Vector2 uv2 in mesh.uv2) { _uv1.value.Add(Base.Data.Float(uv2.x)); _uv1.value.Add(Base.Data.Float(uv2.y)); } } } Base _tri = new Base("tri", "int", _mesh); foreach (int tri in mesh.triangles) { _tri.value.Add(Base.Data.Int(tri)); } Base _aabb = new Base("aabb", "object", _mesh); Base _min = new Base("min", "float", _aabb); _min.value.Add(Base.Data.Float(mesh.bounds.min.x)); _min.value.Add(Base.Data.Float(mesh.bounds.min.y)); _min.value.Add(Base.Data.Float(mesh.bounds.min.z)); Base _max = new Base("max", "float", _aabb); _max.value.Add(Base.Data.Float(mesh.bounds.max.x)); _max.value.Add(Base.Data.Float(mesh.bounds.max.y)); _max.value.Add(Base.Data.Float(mesh.bounds.max.z)); Base _material = new Base("material", "object", _mesh); Base _shader = new Base("shader", "string", _material); _shader.nullByteString = true; if (!isCollider) { _shader.value.Add(Base.Data.String(shapeData.shader)); if (!string.IsNullOrEmpty(shapeData.diffuse)) { Base _diff = new Base("diff", "string", _material); _diff.nullByteString = true; _diff.value.Add(Base.Data.String(Path.GetFileName(shapeData.diffuse))); } if (!string.IsNullOrEmpty(shapeData.normal)) { Base _normal = new Base("n", "string", _material); _normal.nullByteString = true; _normal.value.Add(Base.Data.String(Path.GetFileName(shapeData.normal))); } if (!string.IsNullOrEmpty(shapeData.specular)) { Base _spec = new Base("spec", "string", _material); _spec.nullByteString = true; _spec.value.Add(Base.Data.String(Path.GetFileName(shapeData.specular))); } } else { _shader.value.Add(Base.Data.String("Collision")); } if (skinned) { Dictionary <Transform, int> newBoneIndices = new Dictionary <Transform, int>(); Dictionary <int, Transform> oldBoneIndices = new Dictionary <int, Transform>(); if (!_shape.subNodes.ContainsKey("skeleton")) { Transform root = null; Base _skeleton = new Base("skeleton", "object", _shape); Dictionary <string, Base> nameBones = new Dictionary <string, Base>(); foreach (Transform b in smr.bones) { oldBoneIndices.Add(Array.IndexOf(smr.bones, b), b); if (b.name.ToLower().Equals("root")) { root = b; } Base _bone = new Base(b.name, "object"); Base _btx = new Base("tx", "float", _bone); Matrix4x4 m = b.localToWorldMatrix.inverse; _btx.value = new List <Base.Data>() { new Base.Data() { f = m.m00 }, new Base.Data() { f = m.m10 }, new Base.Data() { f = m.m20 }, //new Base.Data() { f = m.m03 }, new Base.Data() { f = m.m01 }, new Base.Data() { f = m.m11 }, new Base.Data() { f = m.m21 }, //new Base.Data() { f = m.m13 }, new Base.Data() { f = m.m02 }, new Base.Data() { f = m.m12 }, new Base.Data() { f = m.m22 }, //new Base.Data() { f = m.m23 }, new Base.Data() { f = m.m03 }, new Base.Data() { f = m.m13 }, new Base.Data() { f = m.m23 }, //new Base.Data() { f = m.m33 }, }; nameBones.Add(b.name, _bone); } List <Transform> hierBones = new List <Transform>(); ObjectHierarchy(hierBones, root); foreach (var hb in hierBones) { newBoneIndices.Add(hb, hierBones.IndexOf(hb)); Base _bone = nameBones[hb.name]; Base _bix = new Base("ix", "int", _bone); _bix.value.Add(Base.Data.Int(hierBones.IndexOf(hb))); _skeleton.Add(_bone); if (hb != smr.rootBone) { Base _bpa = new Base("pa", "int", _bone); _bpa.value.Add(Base.Data.Int(hierBones.IndexOf(hb.parent))); } } } Base _skin = new Base("skin", "object", _mesh); Base _bonesPerVert = new Base("bones", "int", _skin); int num = 1; foreach (BoneWeight bw in mesh.boneWeights) { if (num < 2 && bw.weight1 > 0) { num = 2; } if (num < 3 && bw.weight2 > 0) { num = 3; } if (num < 4 && bw.weight3 > 0) { num = 4; break; } } _bonesPerVert.value.Add(Base.Data.Int(num)); int ixCount = mesh.vertexCount; Base _ix = new Base("ix", "int", _skin); Base _w = new Base("w", "float", _skin); for (int i = 0; i < ixCount; i++) { BoneWeight w = mesh.boneWeights[i]; int bi0 = newBoneIndices[oldBoneIndices[w.boneIndex0]]; int bi1 = newBoneIndices[oldBoneIndices[w.boneIndex1]]; int bi2 = newBoneIndices[oldBoneIndices[w.boneIndex2]]; int bi3 = newBoneIndices[oldBoneIndices[w.boneIndex3]]; _ix.value.Add(Base.Data.Int((bi0 == 0 && w.weight0 == 0) ? -1 : bi0)); _ix.value.Add(Base.Data.Int((bi1 == 0 && w.weight1 == 0) ? -1 : bi1)); _ix.value.Add(Base.Data.Int((bi2 == 0 && w.weight2 == 0) ? -1 : bi2)); _ix.value.Add(Base.Data.Int((bi3 == 0 && w.weight3 == 0) ? -1 : bi3)); _w.value.Add(Base.Data.Float(w.weight0)); _w.value.Add(Base.Data.Float(w.weight1)); _w.value.Add(Base.Data.Float(w.weight2)); _w.value.Add(Base.Data.Float(w.weight3)); } } } Base _locator = new Base("locator", "object", _base); List <Transform> locators = new List <Transform>(); FindTagInChildren(locators, target.transform, "Locator", target.transform); foreach (Transform loc in locators) { Base _loc = new Base(loc.name, "object", _locator); Base _p = new Base("p", "float", _loc); Base _q = new Base("q", "float", _loc); Base _pa = new Base("pa", "string", _loc); _pa.nullByteString = true; Vector3 pos = loc.transform.localPosition; Quaternion rot = loc.transform.localRotation; _p.value.Add(Base.Data.Float(pos.x)); _p.value.Add(Base.Data.Float(pos.y)); _p.value.Add(Base.Data.Float(pos.z)); _q.value.Add(Base.Data.Float(rot.x)); _q.value.Add(Base.Data.Float(rot.y)); _q.value.Add(Base.Data.Float(rot.z)); _q.value.Add(Base.Data.Float(rot.w)); _pa.value.Add(Base.Data.String(loc.transform.parent.name)); } target.transform.position = lastPos; return(_base); }
void BuildMesh(string path, PdxDataService.Base _baseMesh, Transform attach) { Matrix4x4 m = Matrix4x4.identity; PdxDataService.Base pdxData = _baseMesh; float min = float.MaxValue; GameObject goRoot = new GameObject(); goRoot.name = Path.GetFileName(path); List <Material> snow = new List <Material>(); List <Material> color = new List <Material>(); List <Material> atlas = new List <Material>(); for (int i = 0; i < pdxData.subNodes["object"].subNodes.Count; i++) { List <string> ikeys = new List <string>(pdxData.subNodes["object"].subNodes.Keys); if (pdxData.subNodes["object"].subNodes[ikeys[i]].type != "object") { continue; } PdxDataService.Base pdxShape = pdxData.subNodes["object"].subNodes[ikeys[i]]; bool skinned = false; Transform[] bones = null; string shapeName = pdxShape.name; if (pdxShape.subNodes.ContainsKey("skeleton")) { PdxDataService.Base skeleton = pdxShape.subNodes["skeleton"]; bones = new Transform[skeleton.subNodes.Count]; for (int j = 0; j < skeleton.subNodes.Count; j++) { List <string> jkeys = new List <string>(skeleton.subNodes.Keys); GameObject bone = new GameObject(skeleton.subNodes[jkeys[j]].name); bone.tag = "Bone"; var pdxBone = skeleton.subNodes[jkeys[j]].subNodes; List <PdxDataService.Base.Data> boneTx = pdxBone["tx"].value; //Transform parent = null; //if (pdxBone.ContainsKey("pa")) parent = bones[pdxBone["pa"].value[0].i]; Matrix4x4 matrix = new Matrix4x4(); matrix.SetRow(0, new Vector4(boneTx[0].f, boneTx[3].f, boneTx[6].f, boneTx[9].f)); matrix.SetRow(1, new Vector4(boneTx[1].f, boneTx[4].f, boneTx[7].f, boneTx[10].f)); matrix.SetRow(2, new Vector4(boneTx[2].f, boneTx[5].f, boneTx[8].f, boneTx[11].f)); matrix.SetRow(3, new Vector4(0, 0, 0, 1)); bone.transform.FromMatrix(matrix.inverse); //bone.transform.parent = parent; bones[j] = bone.transform; bonesByName[bone.name] = bone.transform; } for (int j = 0; j < skeleton.subNodes.Count; j++) { List <string> jkeys = new List <string>(skeleton.subNodes.Keys); Transform bone = bones[j]; var pdxBone = skeleton.subNodes[jkeys[j]].subNodes; if (pdxBone.ContainsKey("pa")) { bone.parent = bones[pdxBone["pa"].value[0].i]; } else { bone.parent = goRoot.transform; } } } for (int j = 0; j < pdxShape.subNodes.Count; j++) { List <string> jkeys = new List <string>(pdxShape.subNodes.Keys); if (pdxShape.subNodes[jkeys[j]].type != "object") { continue; } var pdxMesh = pdxShape.subNodes[jkeys[j]].subNodes; if (pdxMesh.ContainsKey("p")) { List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Vector4> tangents = new List <Vector4>(); List <Vector2> uv = new List <Vector2>(); List <Vector2> uv2 = new List <Vector2>(); List <int> triangles = new List <int>(); List <BoneWeight> boneWeights = new List <BoneWeight>(); List <PdxDataService.Base.Data> vValue = pdxMesh["p"].value; for (int k = 0; k < vValue.Count; k += 3) { vertices.Add(new Vector3(vValue[k].f, vValue[k + 1].f, vValue[k + 2].f)); } if (pdxMesh.ContainsKey("n")) { List <PdxDataService.Base.Data> nValue = pdxMesh["n"].value; for (int k = 0; k < nValue.Count; k += 3) { normals.Add(new Vector3(nValue[k].f, nValue[k + 1].f, nValue[k + 2].f)); } } if (pdxMesh.ContainsKey("ta")) { List <PdxDataService.Base.Data> taValue = pdxMesh["ta"].value; for (int k = 0; k < taValue.Count; k += 4) { tangents.Add(new Vector4(taValue[k].f, taValue[k + 1].f, taValue[k + 2].f, taValue[k + 3].f)); } } if (pdxMesh.ContainsKey("u0")) { List <PdxDataService.Base.Data> uvValue = pdxMesh["u0"].value; for (int k = 0; k < uvValue.Count; k += 2) { uv.Add(new Vector2(uvValue[k].f, uvValue[k + 1].f)); } } if (pdxMesh.ContainsKey("u1")) { List <PdxDataService.Base.Data> uv2Value = pdxMesh["u1"].value; for (int k = 0; k < uv2Value.Count; k += 2) { uv2.Add(new Vector2(uv2Value[k].f, uv2Value[k + 1].f)); } } if (pdxShape.subNodes[jkeys[j]].subNodes.ContainsKey("skin")) { skinned = true; var skin = pdxShape.subNodes[jkeys[j]].subNodes["skin"].subNodes; int influencesPerVertex = skin["bones"].value[0].i; int indexCount = skin["ix"].value.Count; for (int k = 0; k < indexCount; k += 4) { BoneWeight bw = new BoneWeight(); var ixValue = skin["ix"].value; bw.boneIndex0 = ixValue[k].i; if (influencesPerVertex > 1) { bw.boneIndex1 = ixValue[k + 1].i; } if (influencesPerVertex > 2) { bw.boneIndex2 = ixValue[k + 2].i; } if (influencesPerVertex > 3) { bw.boneIndex3 = ixValue[k + 3].i; } if (bw.boneIndex0 < 0) { bw.boneIndex0 = 0; } if (bw.boneIndex1 < 0) { bw.boneIndex1 = 0; } if (bw.boneIndex2 < 0) { bw.boneIndex2 = 0; } if (bw.boneIndex3 < 0) { bw.boneIndex3 = 0; } var wvalue = skin["w"].value; bw.weight0 = wvalue[k].f; if (influencesPerVertex > 1) { bw.weight1 = wvalue[k + 1].f; } if (influencesPerVertex > 2) { bw.weight2 = wvalue[k + 2].f; } if (influencesPerVertex > 3) { bw.weight3 = wvalue[k + 3].f; } boneWeights.Add(bw); } } else { skinned = false; } List <PdxDataService.Base.Data> triValue = pdxMesh["tri"].value; for (int k = 0; k < triValue.Count; k++) { triangles.Add(triValue[k].i); } Texture2D diffuse = null; Texture2D normal = null; Texture2D specular = null; bool collisionMesh = false; string shaderName = ""; string texDiffusePath = ""; string texNormalPath = ""; string texSpecularPath = ""; if (pdxShape.subNodes[jkeys[j]].subNodes.ContainsKey("material")) { string folderPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar; PdxDataService.Base matBase = pdxShape.subNodes[jkeys[j]].subNodes["material"]; shaderName = matBase.subNodes["shader"].value[0].s; switch (shaderName) { case "Collision": collisionMesh = true; break; default: texDiffusePath = folderPath + matBase.subNodes["diff"].value[0].s; diffuse = LoadDDS(texDiffusePath); if (diffuse != null) { diffuse.name = Path.GetFileName(texDiffusePath); } texNormalPath = folderPath + matBase.subNodes["n"].value[0].s; normal = LoadDDS(texNormalPath); if (normal != null) { normal.name = Path.GetFileName(texNormalPath); } texSpecularPath = folderPath + matBase.subNodes["spec"].value[0].s; specular = LoadDDS(texSpecularPath); if (specular != null) { specular.name = Path.GetFileName(texSpecularPath); } //Grayscale(specular); break; } } Mesh mesh = new Mesh(); mesh.name = shapeName; mesh.vertices = vertices.ToArray(); mesh.normals = normals.ToArray(); mesh.triangles = triangles.ToArray(); mesh.tangents = tangents.ToArray(); mesh.uv = uv.ToArray(); if (uv2.Count > 0) { mesh.uv2 = uv2.ToArray(); } mesh.RecalculateBounds(); //mesh.RecalculateNormals(); mesh.RecalculateTangents(); GameObject go = new GameObject(); go.name = shapeName; go.tag = "Shape"; go.transform.SetParent(goRoot.transform); //if (!collisionMesh && bones != null && bones.Length > 0) bones[0].SetParent(goRoot.transform); if (!skinned && !collisionMesh) { MeshFilter mf = go.AddComponent <MeshFilter>(); mf.mesh = mesh; } SkinnedMeshRenderer smr = null; MeshRenderer mr = null; if (skinned) { smr = go.AddComponent <SkinnedMeshRenderer>(); } else if (!collisionMesh) { mr = go.AddComponent <MeshRenderer>(); } Material _mat = null; if (pdxMaterials.ContainsKey(shaderName)) { _mat = new Material(pdxMaterials[shaderName]); } else { _mat = new Material(pdxMaterials["PdxMeshStandard"]); } _mat.name = shaderName; switch (shaderName) { case "PdxMeshSnow": snow.Add(_mat); break; case "PdxMeshColor": color.Add(_mat); break; case "PdxMeshTextureAtlas": atlas.Add(_mat); _mat.SetTexture("_Atlas", atlasExample); break; } Material _hl = new Material(materialHighlight); _mat.SetTexture("_Diffuse", diffuse); _mat.SetTexture("_Normal", normal); _mat.SetTexture("_Specular", specular); if (skinned) { smr.bones = bones; smr.rootBone = FindBone(bones, "root"); smr.quality = SkinQuality.Bone4; smr.updateWhenOffscreen = true; Matrix4x4[] bindposes = new Matrix4x4[bones.Length]; for (int b = 0; b < bones.Length; b++) { bindposes[b] = bones[b].worldToLocalMatrix * goRoot.transform.localToWorldMatrix; } mesh.RecalculateBounds(); mesh.bindposes = bindposes; mesh.boneWeights = boneWeights.ToArray(); smr.sharedMesh = mesh; smr.sharedMaterials = new Material[] { _mat, _hl }; } else if (!collisionMesh) { //mr.material = _mat; mr.sharedMaterials = new Material[] { _mat, _hl }; } if (collisionMesh) { //go.tag = "Collision"; MeshFilter mc = go.AddComponent <MeshFilter>(); mc.mesh = mesh; MeshRenderer cmr = go.AddComponent <MeshRenderer>(); cmr.sharedMaterial = _mat; } if (attach == null) { PdxShape sh = go.AddComponent <PdxShape>(); if (smr != null) { sh.smr = smr; } else { sh.mr = mr; } sh.shader = shaderName; sh.diffuse = texDiffusePath; sh.normal = texNormalPath; sh.specular = texSpecularPath; if (min > mesh.bounds.min.y) { min = mesh.bounds.min.y; } } } } } if (attach == null && _baseMesh.subNodes.ContainsKey("locator") && _baseMesh.subNodes["locator"].subNodes.Count > 0) { var locators = _baseMesh.subNodes["locator"].subNodes; //print(locators.Count); for (int l = 0; l < locators.Count; l++) { List <string> lkeys = new List <string>(locators.Keys); GameObject loc = new GameObject(locators[lkeys[l]].name); loc.tag = "Locator"; var lks = locators[lkeys[l]].subNodes; if (lks.ContainsKey("pa") && bonesByName.ContainsKey(lks["pa"].value[0].s)) { loc.transform.SetParent(bonesByName[lks["pa"].value[0].s]); } else if (bonesByName.ContainsKey("Root")) { loc.transform.SetParent(bonesByName["Root"]); } else if (bonesByName.ContainsKey("root")) { loc.transform.SetParent(bonesByName["root"]); } var lP = lks["p"].value; loc.transform.localPosition = new Vector3(lP[0].f, lP[1].f, lP[2].f); var lQ = lks["q"].value; loc.transform.localRotation = new Quaternion(lQ[0].f, lQ[1].f, lQ[2].f, lQ[3].f); Locator locComp = loc.AddComponent <Locator>(); locComp.Init(loc.name); } } if (attach != null) { attachedObject = goRoot; SkinnedMeshRenderer smr = goRoot.GetComponentInChildren <SkinnedMeshRenderer>(); if (smr != null) { smr.rootBone.transform.SetParent(attach); smr.rootBone.transform.localPosition = Vector3.zero; smr.rootBone.transform.localRotation = Quaternion.identity; } else { goRoot.transform.SetParent(attach); goRoot.transform.localPosition = Vector3.zero; goRoot.transform.localRotation = Quaternion.identity; } } else { selectedObject = goRoot; loadedObjects.Add(goRoot); goRoot.transform.Translate(0, -min, 0, Space.World); goRoot.AddComponent <BoneViewer>(); EditorController.instance.SceneHasSnowMaterial(snow.Count > 0 ? snow.ToArray() : null); EditorController.instance.SceneHasColorMaterial(color.Count > 0 ? color.ToArray() : null); EditorController.instance.SceneHasAtlasMaterial(atlas.Count > 0 ? atlas.ToArray() : null); } }
public void ExportMesh(GameObject go, string path) { Vector3 lastPos = go.transform.position; go.transform.position = Vector3.zero; Scene scene = new Scene(); List <string> sameNames = new List <string>(); List <Transform> children = new List <Transform>(); Dictionary <Transform, Node> nodesByTransform = new Dictionary <Transform, Node>(); GetAllChildren(children, go.transform); foreach (Transform child in children) { string nname = child.name; if (sameNames.Contains(nname)) { nname += "_"; } else { sameNames.Add(nname); } Node node = new Node(nname); UnityEngine.Matrix4x4 m = child.localToWorldMatrix.inverse; node.Transform = new Assimp.Matrix4x4( m.m00, m.m01, m.m02, m.m03, m.m10, m.m11, m.m12, m.m13, m.m20, m.m21, m.m22, m.m23, m.m30, m.m31, m.m32, m.m33 ); nodesByTransform.Add(child, node); if (child == go.transform) { Node rootNode = new Node(Path.GetFileNameWithoutExtension(path)); rootNode.Children.Add(node); scene.RootNode = rootNode; } } foreach (Transform child in children) { foreach (Transform c in child) { if (child == go.transform) { scene.RootNode.Children.Add(nodesByTransform[c]); } else { nodesByTransform[child].Children.Add(nodesByTransform[c]); } } } sameNames.Clear(); MeshFilter[] mfs = go.GetComponentsInChildren <MeshFilter>(); SkinnedMeshRenderer[] smrs = go.GetComponentsInChildren <SkinnedMeshRenderer>(); int meshIndex = 0; foreach (var mf in mfs) { PdxShape shape = mf.GetComponent <PdxShape>(); Assimp.Material mat = new Assimp.Material(); mat.Name = shape.shader; TextureSlot diff = new TextureSlot(); diff.FilePath = shape.diffuse; diff.TextureType = TextureType.Diffuse; diff.UVIndex = 0; //mat.TextureDiffuse = diff; mat.AddMaterialTexture(ref diff); TextureSlot norm = new TextureSlot(); norm.FilePath = shape.normal; norm.TextureType = TextureType.Normals; norm.UVIndex = 0; //mat.TextureNormal = norm; mat.AddMaterialTexture(ref norm); TextureSlot spec = new TextureSlot(); spec.FilePath = shape.specular; spec.TextureType = TextureType.Specular; spec.UVIndex = 0; //mat.TextureSpecular = spec; mat.AddMaterialTexture(ref spec); scene.Materials.Add(mat); Assimp.Mesh am = null; am = FromUnityMesh(mf.mesh, "pShape" + meshIndex, go.transform); if (sameNames.Contains(am.Name)) { am.Name += "_"; } else { sameNames.Add(am.Name); } am.MaterialIndex = meshIndex; scene.Meshes.Add(am); nodesByTransform[mf.transform].MeshIndices.Add(meshIndex); meshIndex++; } foreach (var smr in smrs) { PdxShape shape = smr.GetComponent <PdxShape>(); Assimp.Material mat = new Assimp.Material(); mat.Name = shape.shader; TextureSlot diff = new TextureSlot(); diff.FilePath = shape.diffuse; diff.TextureType = TextureType.Diffuse; diff.UVIndex = 0; //mat.TextureDiffuse = diff; mat.AddMaterialTexture(ref diff); TextureSlot norm = new TextureSlot(); norm.FilePath = shape.normal; norm.TextureType = TextureType.Normals; norm.UVIndex = 0; //mat.TextureNormal = norm; mat.AddMaterialTexture(ref norm); TextureSlot spec = new TextureSlot(); spec.FilePath = shape.specular; spec.TextureType = TextureType.Specular; spec.UVIndex = 0; //mat.TextureSpecular = spec; mat.AddMaterialTexture(ref spec); scene.Materials.Add(mat); Assimp.Mesh am = null; UnityEngine.Mesh baked = new UnityEngine.Mesh(); smr.BakeMesh(baked); am = FromUnityMesh(baked /*smr.sharedMesh*/, "pShape" + meshIndex, go.transform); if (sameNames.Contains(am.Name)) { am.Name += "_"; } else { sameNames.Add(am.Name); } am.MaterialIndex = meshIndex; scene.Meshes.Add(am); nodesByTransform[smr.transform].MeshIndices.Add(meshIndex); meshIndex++; } AssimpContext context = new AssimpContext(); bool result = context.ExportFile(scene, path, "obj", PostProcessSteps.MakeLeftHanded | PostProcessSteps.FlipWindingOrder); context.Dispose(); go.transform.position = lastPos; if (result) { EditorController.instance.Status("Object saved as " + path); } else { EditorController.instance.Status("Export failed :(", 2); } }
public GameObject LoadMesh(string path) { AssimpContext context = new AssimpContext(); Scene scene = context.ImportFile(path, PostProcessSteps.MakeLeftHanded | PostProcessSteps.FlipWindingOrder); if (!scene.HasMeshes) { return(null); } List <UnityEngine.Material> snow = new List <UnityEngine.Material>(); List <UnityEngine.Material> color = new List <UnityEngine.Material>(); List <UnityEngine.Material> atlas = new List <UnityEngine.Material>(); Dictionary <string, Transform> bonesByName = new Dictionary <string, Transform>(); GameObject goRoot = new GameObject(Path.GetFileName(path)); float min = 0; int idx = 0; foreach (Assimp.Mesh sceneMesh in scene.Meshes) { GameObject go = new GameObject("pShape" + idx); go.tag = "Shape"; bool skinned = false; UnityEngine.Mesh mesh = new UnityEngine.Mesh(); mesh.name = "pMeshShape" + idx; idx++; List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Vector2> uv = new List <Vector2>(); List <Vector2> uv2 = null; List <BoneWeight> boneWeights = new List <BoneWeight>(); Transform[] bones = null; foreach (var sceneVertex in sceneMesh.Vertices) { vertices.Add(new Vector3(sceneVertex.X, sceneVertex.Y, sceneVertex.Z)); } foreach (var sceneNormal in sceneMesh.Normals) { normals.Add(new Vector3(sceneNormal.X, sceneNormal.Y, sceneNormal.Z)); } foreach (var sceneUV in sceneMesh.TextureCoordinateChannels[0]) { uv.Add(new Vector2(sceneUV.X, 1f - sceneUV.Y)); } if (sceneMesh.TextureCoordinateChannelCount > 1) { uv2 = new List <Vector2>(); foreach (var sceneUV2 in sceneMesh.TextureCoordinateChannels[1]) { uv2.Add(new Vector2(sceneUV2.X, 1f - sceneUV2.Y)); } } Transform rootBone = null; if (sceneMesh.HasBones) { for (int j = 0; j < sceneMesh.VertexCount; j++) { boneWeights.Add(new BoneWeight()); } skinned = true; bones = new Transform[sceneMesh.BoneCount]; int boneIndex = 0; foreach (var sceneBone in sceneMesh.Bones) { GameObject bone = new GameObject(sceneBone.Name); bone.tag = "Bone"; UnityEngine.Matrix4x4 matrix = new UnityEngine.Matrix4x4(); matrix.SetRow(0, new Vector4(sceneBone.OffsetMatrix.A1, sceneBone.OffsetMatrix.A2, sceneBone.OffsetMatrix.A3, sceneBone.OffsetMatrix.A4)); matrix.SetRow(1, new Vector4(sceneBone.OffsetMatrix.B1, sceneBone.OffsetMatrix.B2, sceneBone.OffsetMatrix.B3, sceneBone.OffsetMatrix.B4)); matrix.SetRow(2, new Vector4(sceneBone.OffsetMatrix.C1, sceneBone.OffsetMatrix.C2, sceneBone.OffsetMatrix.C3, sceneBone.OffsetMatrix.C4)); matrix.SetRow(3, new Vector4(sceneBone.OffsetMatrix.D1, sceneBone.OffsetMatrix.D2, sceneBone.OffsetMatrix.D3, sceneBone.OffsetMatrix.D4)); bone.transform.FromMatrix(matrix.inverse); bonesByName[bone.name] = bone.transform; bones[boneIndex] = bone.transform; if (sceneBone.HasVertexWeights) { for (int i = 0; i < sceneBone.VertexWeights.Count; i++) { BoneWeight bw = boneWeights[sceneBone.VertexWeights[i].VertexID]; if (bw.boneIndex0 == 0 && bw.weight0 == 0) { bw.boneIndex0 = boneIndex; bw.weight0 = sceneBone.VertexWeights[i].Weight; } else if (bw.boneIndex1 == 0 && bw.weight1 == 0) { bw.boneIndex1 = boneIndex; bw.weight1 = sceneBone.VertexWeights[i].Weight; } else if (bw.boneIndex2 == 0 && bw.weight2 == 0) { bw.boneIndex2 = boneIndex; bw.weight2 = sceneBone.VertexWeights[i].Weight; } else if (bw.boneIndex3 == 0 && bw.weight3 == 0) { bw.boneIndex3 = boneIndex; bw.weight3 = sceneBone.VertexWeights[i].Weight; } /*if (bw.weight0 < 0.0011f) bw.weight0 = 0f; * if (bw.weight1 < 0.0011f) bw.weight1 = 0f; * if (bw.weight2 < 0.0011f) bw.weight2 = 0f; * if (bw.weight3 < 0.0011f) bw.weight3 = 0f;*/ boneWeights[sceneBone.VertexWeights[i].VertexID] = bw; } } boneIndex++; } foreach (var bone in bonesByName) { if (bone.Key.ToLower().Equals("root")) { rootBone = bone.Value; } string parent = ""; FindParentInHierarchy(bone.Key, scene.RootNode, out parent); if (parent.Length > 0 && bonesByName.ContainsKey(parent)) { bone.Value.SetParent(bonesByName[parent]); } else { bone.Value.SetParent(goRoot.transform); } } } UnityEngine.Matrix4x4[] bindposes = null; if (bones != null) { bindposes = new UnityEngine.Matrix4x4[bones.Length]; for (int b = 0; b < bones.Length; b++) { bindposes[b] = bones[b].worldToLocalMatrix * go.transform.localToWorldMatrix; } } mesh.vertices = vertices.ToArray(); mesh.normals = normals.ToArray(); mesh.triangles = sceneMesh.GetIndices(); mesh.uv = uv.ToArray(); mesh.RecalculateBounds(); mesh.RecalculateTangents(); if (min < mesh.bounds.max.z) { min = mesh.bounds.max.z; } //print(mesh.bounds.min.ToString()); //print(mesh.bounds.max.ToString()); PdxShape shape = go.AddComponent <PdxShape>(); Assimp.Material _mat = scene.Materials[sceneMesh.MaterialIndex]; //print(_mat.Name); Shader shader = Shader.Find("PDX/" + _mat.Name); shape.shader = _mat.Name; if (shader == null) { shader = Shader.Find("PDX/PdxMeshStandard"); shape.shader = "PdxMeshStandard"; } UnityEngine.Material mat = new UnityEngine.Material(shader); bool collision = false; switch (shape.shader) { case "Collision": collision = true; break; case "PdxMeshSnow": snow.Add(mat); break; case "PdxMeshColor": color.Add(mat); break; case "PdxMeshTextureAtlas": atlas.Add(mat); mat.SetTexture("_Atlas", atlasExample); break; } if (_mat.HasTextureDiffuse) { if (_mat.TextureDiffuse.FilePath.EndsWith(".dds")) { string texPath = _mat.TextureDiffuse.FilePath; if (texPath[1] != ':') { texPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + _mat.TextureDiffuse.FilePath; } if (File.Exists(texPath)) { shape.diffuse = texPath; Texture2D tex = PdxLoader.LoadDDS(texPath); tex.name = Path.GetFileName(texPath); mat.SetTexture("_Diffuse", tex); } } } if (_mat.HasTextureHeight) { if (_mat.TextureHeight.FilePath.EndsWith(".dds")) { string texPath = _mat.TextureHeight.FilePath; if (texPath[1] != ':') { texPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + _mat.TextureHeight.FilePath; } if (File.Exists(texPath)) { shape.normal = texPath; Texture2D tex = PdxLoader.LoadDDS(texPath); tex.name = Path.GetFileName(texPath); mat.SetTexture("_Normal", tex); } } } if (_mat.HasTextureSpecular) { if (_mat.TextureSpecular.FilePath.EndsWith(".dds")) { string texPath = _mat.TextureSpecular.FilePath; if (texPath[1] != ':') { texPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + _mat.TextureSpecular.FilePath; } if (File.Exists(texPath)) { shape.specular = texPath; Texture2D tex = PdxLoader.LoadDDS(texPath); tex.name = Path.GetFileName(texPath); mat.SetTexture("_Specular", tex); } } } if (skinned) { SkinnedMeshRenderer smr = go.AddComponent <SkinnedMeshRenderer>(); smr.bones = bones; smr.rootBone = rootBone; mesh.bindposes = bindposes; mesh.boneWeights = boneWeights.ToArray(); smr.sharedMesh = mesh; if (collision) { smr.sharedMaterial = mat; } else { smr.sharedMaterials = new UnityEngine.Material[] { mat, highlightMaterial } }; shape.smr = smr; } else { MeshFilter mf = go.AddComponent <MeshFilter>(); mf.mesh = mesh; MeshRenderer mr = go.AddComponent <MeshRenderer>(); if (collision) { mr.sharedMaterial = mat; } else { mr.sharedMaterials = new UnityEngine.Material[] { mat, highlightMaterial } }; shape.mr = mr; } go.transform.SetParent(goRoot.transform); } #region import animation foreach (var a in scene.Animations) { if ((int)a.TicksPerSecond == 1) { EditorController.instance.Status("Can't load animation with custom frame rate", 1); break; } bool resampled = false; if (a.HasNodeAnimations) { PdxDataService.AnimationData adata = new PdxDataService.AnimationData(); #if UNITY_EDITOR print("fps: " + a.TicksPerSecond + ", duration: " + a.DurationInTicks); #endif adata.fps = 15;// (float)a.TicksPerSecond; adata.sampleCount = (int)a.DurationInTicks; adata.length = adata.sampleCount / adata.fps; foreach (var nac in a.NodeAnimationChannels) { resampled = nac.PositionKeyCount == adata.sampleCount + 1 || nac.RotationKeyCount == adata.sampleCount + 1 || nac.ScalingKeyCount == adata.sampleCount + 1; if (resampled) { break; } } #if UNITY_EDITOR print("resampled " + resampled); #endif foreach (var nac in a.NodeAnimationChannels) { if (!bonesByName.ContainsKey(nac.NodeName)) { continue; } var animation = new PdxDataService.AnimationData.Animation(); animation.name = nac.NodeName; animation.parent = bonesByName[nac.NodeName]; animation.keys = new List <PdxDataService.AnimationData.Key>(); for (int i = 0; i < adata.sampleCount + 1; i++) { animation.keys.Add(new PdxDataService.AnimationData.Key()); } animation.keys[0].pos = animation.parent.transform.localPosition; animation.keys[0].rot = animation.parent.transform.localRotation; animation.keys[0].scl = animation.parent.transform.localScale; //animation.sampleT = true; // or joint mistmatch error if (nac.HasPositionKeys) { if (resampled) { foreach (var pk in nac.PositionKeys) { int i = (int)pk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].pos = new Vector3(pk.Value.X, pk.Value.Y, pk.Value.Z); animation.keys[i].time = (float)pk.Time / (float)adata.fps; } } else { List <VectorKey> posKeys = nac.PositionKeys; if (ListVectorKey(ref posKeys, adata.sampleCount)) { animation.sampleT = true; foreach (var pk in posKeys) { int i = (int)pk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].pos = new Vector3(pk.Value.X, pk.Value.Y, pk.Value.Z); animation.keys[i].time = (float)pk.Time / (float)adata.fps; } } } } if (nac.HasRotationKeys) { if (resampled) { foreach (var rk in nac.RotationKeys) { int i = (int)rk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].rot = new UnityEngine.Quaternion(rk.Value.X, rk.Value.Y, rk.Value.Z, rk.Value.W); animation.keys[i].time = (float)rk.Time / (float)adata.fps; } } else { List <QuaternionKey> rotKeys = nac.RotationKeys; if (ListQuaternionKey(ref rotKeys, adata.sampleCount)) { animation.sampleQ = true; foreach (var rk in rotKeys) { int i = (int)rk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].rot = new UnityEngine.Quaternion(rk.Value.X, rk.Value.Y, rk.Value.Z, rk.Value.W); animation.keys[i].time = (float)rk.Time / (float)adata.fps; } } } } if (nac.HasScalingKeys) { if (resampled) { foreach (var sk in nac.ScalingKeys) { int i = (int)sk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].scl = new Vector3(sk.Value.X, sk.Value.Y, sk.Value.Z); animation.keys[i].time = (float)sk.Time / (float)adata.fps; } } else { List <VectorKey> sclKeys = nac.ScalingKeys; if (ListVectorKey(ref sclKeys, adata.sampleCount)) { animation.sampleS = true; foreach (var sk in sclKeys) { int i = (int)sk.Time + 1; if (i >= animation.keys.Count) { break; } animation.keys[i].scl = new Vector3(sk.Value.X, sk.Value.Y, sk.Value.Z); animation.keys[i].time = (float)sk.Time / (float)adata.fps; } } } } adata.hierarchy.Add(animation); } var player = goRoot.AddComponent <PdxAnimationPlayer>(); adata.Fix(); player.animationData = adata; } } #endregion EditorController.instance.SceneHasSnowMaterial(snow.Count > 0 ? snow.ToArray() : null); EditorController.instance.SceneHasColorMaterial(color.Count > 0 ? color.ToArray() : null); EditorController.instance.SceneHasAtlasMaterial(atlas.Count > 0 ? atlas.ToArray() : null); if (!path.ToLower().EndsWith(".obj")) { goRoot.transform.Translate(0, min, 0, Space.World); goRoot.transform.rotation = UnityEngine.Quaternion.Euler(90, 0, 0); } context.Dispose(); return(goRoot); }
public void SetObject(PdxShape go) { self = go; buttonText.text = go.name; }