예제 #1
0
        private void FindAndSyncMeshesForR2()
        {
            CoreMesh[] meshes = gameObject.GetComponentsInChildren <CoreMesh>(true);
            foreach (CoreMesh mesh in meshes)
            {
                if (mesh.name.Contains("_LOD") == false && mesh.name.Contains("_CAP") == false)
                {
                    //assign feathered and opque for future use
                    if (mesh.name.ToLower().Contains("_feathered") == true)
                    {
                        feathered = mesh;
                    }
                    if (mesh.name.ToLower().Contains("_opaque") == true)
                    {
                        opaque = mesh;
                    }

                    //resync blendshapes as needed
                    if (blendshape_cache.Keys != null)
                    {
                        foreach (string bs in blendshape_cache.Keys)
                        {
                            mesh.SetUnityBlendshapeWeight(bs, blendshape_cache[bs]);
                        }
                    }
                }
            }
        }
예제 #2
0
 public RenderKit3d(IBackedByBitmap control, IView view)
     : base(control, view, view.StyleContext,
            new Camera(new Vector3(0, 0, 10.0f), new Vector3(), Vector3.Zero),
            null, null)
 {
     _mesh = (CoreMesh)view.Content;
 }
예제 #3
0
 /// <summary>
 /// Adds a given CoreMesh reference to the interal LOD list.
 /// </summary>
 /// <param name="cm">The CoreMesh reference to add.</param>
 override public void AddCoreMeshToLODlist(CoreMesh cm)
 {
     if (backupTexture == null)
     {
         backupTexture = cm.skinnedMeshRenderer.sharedMaterial.mainTexture as Texture2D;
     }
     base.AddCoreMeshToLODlist(cm);
 }
예제 #4
0
        public void AttachCoreMeshToNode(GameObject currentNode, AssetSchematic schematic, AssetSchematic rootSchematic)
        {
            CoreMesh coreMesh = currentNode.GetComponent <CoreMesh>();

            if (coreMesh == null)
            {
                coreMesh = currentNode.AddComponent <CoreMesh>();
            }

            //where are the runtime morph files (they are in a resources folder that artist tools exports from projection)
            coreMesh.runtimeMorphPath = rootSchematic.origin_and_description.vendor_name + "/" + rootSchematic.origin_and_description.collection_name + "/" + rootSchematic.origin_and_description.name + "/" + currentNode.name;
            //clean the path up
            coreMesh.runtimeMorphPath = coreMesh.runtimeMorphPath.Replace(" ", "_");
            Regex regex = new Regex(@"[^a-zA-Z0-9-_/]+"); //TODO: this regex or formatting should come from streaming morphs or morph extraction, not here

            coreMesh.runtimeMorphPath = regex.Replace(coreMesh.runtimeMorphPath, "");
            coreMesh.dazName          = ""; //this can't be null, but it can be blank

            switch (schematic.type_and_function.item_function)
            {
            case ItemFunction.soft_wearable:
                coreMesh.meshType = CONSTANTS.MESH_TYPE.CLOTH;
                break;

            case ItemFunction.hair:
                coreMesh.meshType = CONSTANTS.MESH_TYPE.HAIR;
                break;

            case ItemFunction.figure:
                coreMesh.meshType = CONSTANTS.MESH_TYPE.BODY;
                break;

            case ItemFunction.prop:
                coreMesh.meshType = CONSTANTS.MESH_TYPE.PROP;
                break;
            }

            if (schematic.structure_and_physics.item_structure.assigned_materials != null)
            {
                Renderer renderer = currentNode.GetComponent <Renderer>();
                if (renderer != null)
                {
                    Material[] mats = new Material[schematic.structure_and_physics.item_structure.assigned_materials.Length];
                    for (int i = 0; i < schematic.structure_and_physics.item_structure.assigned_materials.Length; i++)
                    {
                        string matGUID = schematic.structure_and_physics.item_structure.assigned_materials[i];
                        mats[i] = GetMaterialFromGUID(matGUID, basePath);
                    }

                    renderer.sharedMaterials = mats;
                }
            }
        }
예제 #5
0
		public void Test5()
		{
			var skeleton = new CoreSkeleton(skelPath);
			var mesh = new CoreMesh(meshPath, skeleton);
			var anim = new CoreAnimation(animPath, skeleton);

			var skelInstance = new Skeleton(skeleton);
			var mixer = new Mixer();

			// play the animation
			mixer.Play(anim).Once();
			mixer.Update(0);

			skelInstance.Animate(mixer);

			var verts = mesh.GetTransformedVertices(skelInstance);
			var indices = mesh.GetIndices();
		}
예제 #6
0
 private void FindAndSyncCap()
 {
     CoreMesh[] meshes = gameObject.GetComponentsInChildren <CoreMesh>(true);
     foreach (CoreMesh mesh in meshes)
     {
         if (mesh.name.Contains("_LOD") == false && mesh.name.Contains("_CAP") == true)
         {
             cap = mesh;
             //resync blendshapes as needed
             if (blendshape_cache.Keys != null)
             {
                 foreach (string bs in blendshape_cache.Keys)
                 {
                     cap.SetUnityBlendshapeWeight(bs, blendshape_cache[bs]);
                 }
             }
         }
     }
 }
예제 #7
0
            public MorphManifest GetManifestForCoreMesh(CoreMesh coreMesh, ManifestSelection selectionMethod)
            {
                string meshKey = selectionMethod.ToString();

                if (selectionMethod == ManifestSelection.AutoDetect)
                {
                    // There is no easy way to detect to which base avatar (MCSFemale/MCSMale) our asset belongs.
                    // The most reliable way I could find is to check their morphdata for blendshapes that are unique to one gender.
                    // Not all objects are affected by all blendshapes (e.g. shoes don't have face morphs), so we'll pick a couple that affect the whole body to cover our bases.
                    // If this still wrongly identifies a mesh, pick manual selectionMethod.
                    bool isFemale = (GetMorphData(coreMesh.runtimeMorphPath, "FBMGogoBody") != null || GetMorphData(coreMesh.runtimeMorphPath, "FHMGogoHead") != null);
                    meshKey = (isFemale) ? "MCSFemale" : "MCSMale";
                }

                if (_currentReport != null && _currentReport.name == coreMesh.name)
                {
                    _currentReport.manifest = meshKey;
                }
                return(streamingMorphs.GetManifest(meshKey, false));
            }
예제 #8
0
    public static  void readTRIS(CoreMesh surf, int surfaceId,int vtStar)
    {

     //   trace("READ TRIS");


        int brushid = file.ReadInt32();
        int TriangleCount =(int)(getChunkSize() / 12);
        bool showwarning = false;
        var vertex_id = new int[3];


        B3DBone bone= new B3DBone();

        while (getChunkSize() != 0)
        {
            vertex_id[0] = file.ReadInt32();
            vertex_id[1] = file.ReadInt32();
            vertex_id[2] = file.ReadInt32();

       
            vertex_id[0] += vtStar;
            vertex_id[1] += vtStar;
            vertex_id[2] += vtStar;

            for (int i=0; i<3;i++)
            {
                if (vertex_id[i] >= AnimatedVertices_VertexID.Count)
                {
                    trace("Illegal vertex index found");
                    return ;
                }

                if (AnimatedVertices_VertexID[ vertex_id[i] ] != -1)
                {
                    if ( AnimatedVertices_BufferID[ vertex_id[i] ] != surfaceId ) //If this vertex is linked in a different meshbuffer
                    {
                        AnimatedVertices_VertexID[ vertex_id[i] ] = -1;
                        AnimatedVertices_BufferID[ vertex_id[i] ] = -1;
                        showwarning = true;

                    }
                }

                if (AnimatedVertices_VertexID[ vertex_id[i] ] == -1) //If this vertex is not in the meshbuffer
                {

                    var vertex = listVertex[ vertex_id[i] ];
                    surf.addVertex(vertex.Pos);
                    surf.addVertexColor(vertex.color);

                    if (vertex.useUv1)
                        surf.addTexCoords(vertex.TCoords0, 0);
                    
                    if (vertex.useUv2)
                        surf.addTexCoords(vertex.TCoords1, 1);
                    
                    if (vertex.useNormals)
                        surf.addNormal(vertex.Normal);


                    
                    
                    bone.vertex.Add(vertex);


                    //create vertex id to meshbuffer index link:
                    AnimatedVertices_VertexID[ vertex_id[i] ] = surf.vertices.Count-1;
                    AnimatedVertices_BufferID[ vertex_id[i] ] = surfaceId;

                }




            }
            surf.addFace(
                AnimatedVertices_VertexID[ vertex_id[0] ],
                AnimatedVertices_VertexID[ vertex_id[1] ],
                AnimatedVertices_VertexID[ vertex_id[2] ]);


          

        }


        if (showwarning)
        {
            Debug.LogWarning("Warning, different meshbuffers linking to the same vertex, this will cause problems with animated meshes");
        }



       
      
        Bones.Add(bone);

      //  surf.material.clone(brushes[brushid]);
      

    }
예제 #9
0
    private static void  readMESH(GameObject parent,GameObject root,string name)
    {

        int  brushID = file.ReadInt32();//brushID


        while (getChunkSize() != 0)
        {
            var ChunkName = ReadChunk();
            if(ChunkName=="VRTS") 
            {
                readVTS();
            } else  
                if(ChunkName=="TRIS") 
                {
                    CoreMesh surf = new CoreMesh(parent, root, name);
                    if (brushID == -1)  brushID = 0;
                    if (brushes.Count > 0)
                    {
                    surf.brush = brushes[brushID];
                    }
                    readTRIS(surf,surfaces.Count,VerticesStart);
                    surfaces.Add(surf);
                } 
            breakChunk();
        }  

    }
예제 #10
0
        /// <summary>
        /// Overrideable method to add all CoreMesh Componenets attached as to components
        /// to any child GameObject of the GameObject to which this CostumeItem is attached
        /// to <see cref="LODlist"/>.
        /// </summary>
        virtual public void DetectCoreMeshes()
        {
            CoreMesh[] meshes = gameObject.GetComponentsInChildren <CoreMesh>(true);
            if (meshes.Length <= 0)
            {
                UnityEngine.Debug.LogWarning("DetectCoreMeshes found 0 coreMesh from: " + gameObject.name);
            }
            LODlist = new List <CoreMesh>();

            foreach (CoreMesh mesh in meshes)
            {
                if (mesh.meshType != meshType)
                {
                    //the CoreMesh does not match the CostumeItem mesh type, skip it
                    continue;
                }

                //make sure this costume item "owns" this coremesh, only do this if we're not a prop though
                if (mesh.meshType != MESH_TYPE.PROP && !EnsureNoOtherCostumeItemBetweenCoreMesh(mesh.gameObject))
                {
                    if (mesh.meshType == MESH_TYPE.PROP)
                    {
                        //this is a common case for props, just move along, this is b/c CIBody will trigger props since props are under the skeleton of CIBody
                        continue;
                    }
                    UnityEngine.Debug.LogWarning("I do not own this mesh, skipping: " + mesh.gameObject.name + " from: " + gameObject.name);
                    UnityEngine.Debug.LogWarning("Please try removing the content pack, reimporting the asset's .mon file, then reattaching");
                }

                bool addMesh = false;
                switch (meshType)
                {
                case MESH_TYPE.HAIR:
                    //we need to check for skull caps

                    string tmpName = mesh.name.ToLower();
                    if (tmpName.Contains("_cap") || tmpName.Contains("_feathered") || tmpName.Contains("_opaque"))
                    {
                        //these are all "skull caps" and we should not include them in the lod list
                    }
                    else
                    {
                        //these are normal hair items, include them
                        addMesh = true;
                    }
                    break;

                case MESH_TYPE.BODY:
                //TODO: do we need to do anything specifically for the eyes, gen2 has LOD for eyes...
                //genesis 3 has embedded eyes (submesh), without lods
                default:
                    addMesh = true;
                    break;
                }

                if (addMesh)
                {
                    AddCoreMeshToLODlist(mesh);
                }
            }

            //if current core mesh is null, assign the first lod we found to the "active" mesh
            if (_currentCoreMesh == null)
            {
                _currentCoreMesh = LODlist.FirstOrDefault();
            }

            //is it still null, if so this is bad
            if (_currentCoreMesh == null)
            {
                UnityEngine.Debug.LogWarning("Unable to find first CoreMesh/LOD in costume item: " + gameObject.name + ", your asset will likely break and not work");
            }
        }
예제 #11
0
        /// <summary>
        /// Overrideable method for setting the LOD level.
        /// </summary>
        /// <param name="lodlevel">Lodlevel.</param>
        /// <param name="broadcast_change">If set to <c>true</c> broadcast change.</param>
        virtual public bool setLODLevel(float lodlevel, bool broadcast_change = false)
        {
            Cleanup();

            _currentCoreMesh = (_currentCoreMesh == null) ? LODlist.FirstOrDefault() : _currentCoreMesh;              // there must always be one!!!!
            CoreMesh bestCoreMesh = null;


            float bestQuality = Mathf.Infinity;

            //find the closest matching mesh
            foreach (CoreMesh cm in LODlist)
            {
                if (cm.meshQuality >= lodlevel && cm.meshQuality < bestQuality)
                {
                    bestCoreMesh = cm;
                    bestQuality  = cm.meshQuality;
                }
            }


            if (bestCoreMesh == null)
            {
                UnityEngine.Debug.LogWarning("Could not detect best core mesh to show for: " + gameObject.name + " LOD: " + lodlevel + " forcing default: " + _currentCoreMesh.name);
                bestCoreMesh = _currentCoreMesh;
            }


            bool hasChanged = bestCoreMesh != _currentCoreMesh;

            foreach (CoreMesh cm in LODlist)
            {
                if (cm != bestCoreMesh)
                {
                    cm.setVisibility(false);
                }
                else
                {
                    cm.setVisibility(isVisible);
                }
            }

            if (hasChanged)
            {
                _currentCoreMesh = bestCoreMesh;

                if (blendshape_cache.Keys != null)
                {
                    foreach (string bs in blendshape_cache.Keys)
                    {
                        currentCoreMesh.SetUnityBlendshapeWeight(bs, blendshape_cache[bs]);
                    }
                }

                //if we modified the body, force a recalculation of alpha injection
                CIbody cibody = gameObject.GetComponent <CIbody>();
                if (cibody != null)
                {
                    charman.SyncAlphaInjection();
                }

                if (broadcast_change)
                {
                    BroadcastLODChange();
                }

                currentLODlevel = bestQuality;
            }

            return(hasChanged);
        }
예제 #12
0
        /// <summary>
        /// Adds a given CoreMesh reference to the interal LOD list.
        /// </summary>
        /// <param name="cm">Cm.</param>
        virtual public void AddCoreMeshToLODlist(CoreMesh cm)
        {
            Cleanup();

            if (LODlist == null)
            {
                LODlist = new List <CoreMesh> ();
            }

            //make sure we can find a mesh, otherwise skip it
            Mesh m = null;
            SkinnedMeshRenderer smr = cm.GetComponent <SkinnedMeshRenderer>();
            MeshFilter          mf  = cm.GetComponent <MeshFilter>();

            if (smr != null)
            {
                m = smr.sharedMesh;
            }
            else if (mf != null)
            {
                m = mf.sharedMesh;
            }

            if (m == null)
            {
                if (Application.isEditor)
                {
                    UnityEngine.Debug.LogError("Could not locate a mesh for CoreMesh: " + cm.name + ", skipping. Try removing the content pack from your figure, reimport, then re-add.");
                }
                return;
            }


            LODlist.Add(cm);
            List <CoreMesh> new_list = LODlist.OrderByDescending(o => o.vertexCount).ToList();

            LODlist = new_list;

            // float base_verts = (float) new_list.First ().vertexCount;
            // sets meshquality based on vertcount from of highest
            // foreach (CoreMesh c in new_list) {
            //      float compare_verts = (float) c.vertexCount;
            //      c.meshQuality = compare_verts/base_verts;
            // }

            // set meshquality by index of total list size
            int i     = 0;
            int count = LODlist.Count;

            for (; i < count; i++)
            {
                float value = 1f / (float)Math.Pow(2, i);
                new_list[i].meshQuality = value;
            }

            setLODLevel(currentLODlevel);

            // make new current mesh have updated blendshapes
            if (blendshape_cache.Keys != null)
            {
                foreach (string bs in blendshape_cache.Keys)
                {
                    foreach (CoreMesh mesh in LODlist)
                    {
                        mesh.SetUnityBlendshapeWeight(bs, blendshape_cache[bs]);
                    }
                }
            }
        }
예제 #13
0
    private static void readMesh(string path, string filename, string texturepath)
    {
        

        if (File.Exists(path + "/" + filename))
        {
                string nm = Path.GetFileNameWithoutExtension(filename);
                importingAssetsDir = "Assets/Prefabs/" + nm + "/";

                if (saveAssets)
                {
                if (!Directory.Exists(importingAssetsDir))
                {
                    Directory.CreateDirectory(importingAssetsDir);
                }
               
                }


            trace("load file :"+path + "/" + filename);

            using (FileStream fs = File.OpenRead(path + "/" + filename))
            {

              
                file = new BinaryReader(fs);
                file.BaseStream.Position = 0;


                string id =readUTFBytes(10);
                int version = readInt();

                Debug.Log("ID:" + id + ", version:" + version);


                int numVerts = (int)file.ReadInt16();

                Debug.Log("Numer of vertex:" + numVerts);
                List<MS3DVertex> vertices = new List<MS3DVertex>();
                for (int i=0; i<numVerts; i++)
                {
                    MS3DVertex vertex = new MS3DVertex();
                    vertices.Add(vertex);
                    
                }

                List<MS3DTriangle> triangles = new List<MS3DTriangle>();
                int numTriangles = (int)file.ReadInt16();

                Debug.Log("Numer of triangles:" + numTriangles);
                for (int i=0; i<numTriangles; i++)
                {
                    MS3DTriangle tri = new MS3DTriangle();
                    triangles.Add(tri);

                }
                 

                int numMeshes=(int)file.ReadInt16();
                Debug.Log("Numer of meshes:" + numMeshes);

                List<MS3DMesh> meshes = new List<MS3DMesh>();
                for (int i = 0; i < numMeshes; i++)
                {
                    MS3DMesh mesh = new MS3DMesh();
                    meshes.Add(mesh);
                }

                int numMaterials=(int)file.ReadInt16();
                Debug.Log("Number  of Materials:" + numMaterials);
                List<MS3DMaterial> materials = new List<MS3DMaterial>();
                for (int i = 0; i < numMaterials; i++)
                {
                    MS3DMaterial material = new MS3DMaterial();

                    if (File.Exists(path + "/" + material.alphaMap))
                    {
                        material.textureDetail = loadexture(path + "/" + material.alphaMap);
                    }
                        
                    if (File.Exists(path + "/" + material.textureMap))
                    {
                        material.texture = loadexture(path + "/" + material.textureMap);
                    }



                    materials.Add(material);
                }

                framesPerSecond = file.ReadSingle();
                float currentTime =file.ReadSingle();
                NumFrames =file.ReadInt32();
                int numJoints = file.ReadInt16();


                Debug.Log("fps:"+framesPerSecond+", time:"+currentTime+", total frames:"+NumFrames+", num joints:"+numJoints);

              
                GameObject ObjectRoot = new GameObject(nm);
                GameObject meshContainer = new GameObject("Surfaces");
                meshContainer.transform.parent = ObjectRoot.transform;

                if (numJoints > 1)
                {
                    AnimationClip clip = new AnimationClip();
                    clip.name = nm + "take00";
                    clip.wrapMode = WrapMode.Loop;

               
                    for (int i = 0; i < numJoints; i++)
                    {
                        isStatic = false;

                        CoreJoint Joint = new CoreJoint();
                        byte flags = file.ReadByte();
                        char[] name = file.ReadChars(32);
                        char[] parentName = file.ReadChars(32);

                   
                        Joint.Name = "";
                        for (int k = 0; k < 32; k++)
                        {
                            if (name[k] == (char)0)
                                break;
                            Joint.Name += name[k];
                        }
                        Joint.ParentName = "";
                        for (int k = 0; k < 32; k++)
                        {
                            if (parentName[k] == (char)0)
                                break;
                            Joint.ParentName += parentName[k];
                        }

                        Joint.joint.name = Joint.Name;


                        //       Debug.Log("Joint name:" + Joint.Name + " , Join Parent:" + Joint.ParentName);

                  
                   
                        Vector3 rotation = Vector3.zero;
                        rotation.x = file.ReadSingle();
                        rotation.y = file.ReadSingle();
                        rotation.z = file.ReadSingle();

                        Joint.position = Vector3.zero;
                        Joint.position.x = file.ReadSingle();
                        Joint.position.y = file.ReadSingle();
                        Joint.position.z = file.ReadSingle();
                        Joint.rotation = QuaternionCreate(rotation);


                        CoreJoint parent = getBoneByName(Joint.ParentName);
                        if (parent != null)
                        {
                            Joint.parent = parent;
                            Joint.joint.transform.parent = parent.joint.transform;    
                            Joint.Path += parent.Path + "/";

                            //    Debug.Log("Bone:"+ Joint.Name+" Parent"+ Joint.ParentName); 

                        }
                        else
                        {
                            Joint.joint.transform.parent = ObjectRoot.transform;
                            //  Debug.LogWarning("Bone:"+ Joint.Name+" dont have parent"); 
                        }
                        Joint.Path += Joint.Name;

                        Joint.joint.transform.localPosition = Joint.position;
                        Joint.joint.transform.localRotation = Joint.rotation;


                 


                 

                        // Debug.Log("Joint: "+Joint.Name+", Position:" + Joint.position +", Rotation: "+rotation);
                        //    Debug.Log("Joint :"+Joint.Name+" , Path:"+Joint.Path);


           
              
                        Joint.numRotKeyFrames = file.ReadInt16();
                        Joint.numPosKeyFrames = file.ReadInt16();
                  
                        float fps = 1.0f/ framesPerSecond;
                    
                        for (int k = 0; k < Joint.numRotKeyFrames; k++)
                        {
                       
                            float time = file.ReadSingle();
                            Vector3 rot = ReadVector3();
                            Quaternion qrot = QuaternionCreate(rot) * Joint.rotation;
                            Joint.addRotationCurve(qrot, time );


                       //     Debug.Log("Frame:" + time + " , time:" + (time*fps));

                        }
                        for (int k = 0; k < Joint.numPosKeyFrames; k++)
                        {
                            float time = file.ReadSingle();
                            Vector3 pos = Joint.position + ReadVector3();
                            Joint.addPositionCurve(pos.x, pos.y, pos.z, time );

                

                           


                        }
                        Joint.addCurves(clip);
                       
                        if (Joint.numRotKeyFrames != Joint.numPosKeyFrames)
                        {
                            Debug.LogError(Joint.numPosKeyFrames + " != " + Joint.numRotKeyFrames);
                        }
                  



                  

               
                        listJoints.Add(Joint);



                   
                    }

                    clip.frameRate = framesPerSecond;
                    clip.legacy = true;
                    Animation anim = (UnityEngine.Animation)ObjectRoot.AddComponent(typeof(Animation));
                    anim.AddClip(clip, clip.name);
                    anim.clip = clip;
                    anim.playAutomatically = true;
         
                    if (saveAssets)
                    {

                        string clipAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + clip.name + ".asset");
                        AssetDatabase.CreateAsset(clip, clipAssetPath);

                    }
                }//JOINTS

             
                for (int i = 0; i < meshes.Count; i++)
                {
                    MS3DMesh mesh = meshes[i];

                    CoreMesh cmesh = new CoreMesh(meshContainer, ObjectRoot, mesh.name);


                    if (mesh.MaterialIndex >= 0 && mesh.MaterialIndex <= materials.Count)
                    {
                        MS3DMaterial material = materials[mesh.MaterialIndex];    
                        bool isDetail = material.textureDetail != null;
                        if (isDetail)
                        {
                        }
                        else
                        {
                            cmesh.material=new Material(Shader.Find("Diffuse"));
                            cmesh.material.name = material.name;
                            if (material.texture != null)
                            {
                                cmesh.material.mainTexture = material.texture;
                            }

                            if (saveAssets)
                            {
                                string meshAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + cmesh.material.name + ".asset");
                       
                                AssetDatabase.CreateAsset(cmesh.material, meshAssetPath);
                            }

                        }


                    }



                    for (int j = 0; j < mesh.numTriangles; j++)
                    {
                        if(!isStatic)
                        {
                   
                            VertexBone vtx0 = new VertexBone();
                            cmesh.vertex.Add(vtx0);

                            VertexBone vtx1 = new VertexBone();
                  
                            cmesh.vertex.Add(vtx1);

                            VertexBone vtx2 = new VertexBone();
                     
                            cmesh.vertex.Add(vtx2);

                        }

                        
                        int index0 = triangles[mesh.TriangleIndices[j]].indice0;
                        Vector3 v0 = vertices[index0].Vertex;
                        Vector3 n0 = triangles[mesh.TriangleIndices[j]].normal0;
                        float u0 = triangles[mesh.TriangleIndices[j]].s.x;
                        float t0 = 1f * -triangles[mesh.TriangleIndices[j]].t.x;

                        int index1 = triangles[mesh.TriangleIndices[j]].indice1;
                        Vector3 v1 = vertices[index1].Vertex;
                        Vector3 n1 = triangles[mesh.TriangleIndices[j]].normal1;
                        float u1 = triangles[mesh.TriangleIndices[j]].s.y;
                        float t1 = 1f * -triangles[mesh.TriangleIndices[j]].t.y;


                        int index2 = triangles[mesh.TriangleIndices[j]].indice2;
                        Vector3 v2 = vertices[index2].Vertex;
                        Vector3 n2 = triangles[mesh.TriangleIndices[j]].normal2;
                        float u2 = triangles[mesh.TriangleIndices[j]].s.z;
                        float t2 = 1f * -triangles[mesh.TriangleIndices[j]].t.z;

                        int f0 = cmesh.addVertex(v0);
                                 cmesh.addNormal(n0);
                                 cmesh.addTexCoords(new Vector2(u0, t0), 0);


                        int f1 = cmesh.addVertex(v1);
                        cmesh.addNormal(n1);
                        cmesh.addTexCoords(new Vector2(u1, t1), 0);


                        int f2 = cmesh.addVertex(v2);
                        cmesh.addNormal(n2);
                        cmesh.addTexCoords(new Vector2(u2, t2), 0);

                        cmesh.addFace(f0, f1, f2);

                        if (!isStatic)
                        {
                            
                            int Bone0 = vertices[index0].boneId;
                            int Bone1 = vertices[index1].boneId;
                            int Bone2 = vertices[index2].boneId;

                            cmesh.vertex[f0].addBone(Bone0, 1);
                            cmesh.vertex[f1].addBone(Bone1, 1);
                            cmesh.vertex[f2].addBone(Bone2, 1);

                        }

                     

                    

                    }
                   
                    surfaces.Add(cmesh);
                }

                for (int i = 0; i < meshes.Count; i++)
                {
                    MS3DMesh mesh = meshes[i];
                    CoreMesh cmesh = surfaces[i];

                    if (!isStatic)
                    {
                        
                        for (int j = 0; j < cmesh.vertex.Count; j++)
                        {
                            isStatic = false;

                            VertexBone vertex = cmesh.vertex[j];
                            //  Debug.Log("Num Bone:" + vertex.numBones);

                            BoneWeight b = new BoneWeight();
                            b.boneIndex0 = vertex.bones[0].boneId;
                            b.weight0 = vertex.bones[0].Weight;

                      

                            cmesh.addBone(b);


                        }
                    }
                    cmesh.build();
                    if (saveAssets)
                    {
                        string meshAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + cmesh.name+"_"+i + ".asset");
                        AssetDatabase.CreateAsset(cmesh.geometry, meshAssetPath);
                    }
                }



                if (saveAssets)
                {

                    string prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + filename + ".prefab");
                    var prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
                    PrefabUtility.ReplacePrefab(ObjectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
                    AssetDatabase.Refresh();
                }

                materials.Clear();
                meshes.Clear();
                triangles.Clear();
                vertices.Clear();

                materials = null;
                meshes = null;
                triangles = null;
                vertices = null;


               




            
            }//file open

            Debug.Log(path + "/" + filename + " Imported ;) ");
        }

    }
예제 #14
0
        //todo: expand this...

        /**
         * schematic.origin_and_description.gender = MCS.Utility.Schematic.Enumeration.Gender.male;
         * schematic.origin_and_description.vendor_name = "DAZ3D";
         * schematic.type_and_function.item_function = MCS.Utility.Schematic.Enumeration.ItemFunction.soft_wearable;
         * schematic.origin_and_description.collection_name = "UrbanMetro";
         * schematic.origin_and_description.id = "UMPants";
         * schematic.origin_and_description.name = "UMPants";
         * schematic.version_and_control.item_version = 0.01;
         * schematic.origin_and_description.description = "/Urban Metro Outfit for Genesis 2 Male(s)/Pants";
         * schematic.version_and_control.compatibilities = new string[1]{ "/Genesis 2/Male" };
         * schematic.version_and_control.mcs_version = 1.5;
         */
        public GameObject CreateMorphGameObjectFromFbx(GameObject go, AssetSchematic schematic, Dictionary <string, Texture2D> textures, bool InstantiateNewObjectUponCreation = true)
        {
            UnityEngine.Debug.Log("CreateMorphGameObjectFromFbx: " + go.name + " | " + schematic.stream_and_path.source_path);

            GameObject gameObject = null;

            if (InstantiateNewObjectUponCreation)
            {
                gameObject = GameObject.Instantiate(go) as GameObject;
            }
            else
            {
                gameObject = go;
            }
            GameObject child = gameObject.transform.GetChild(0).gameObject;

            child.AddComponent <MCSItemModel> ();
            child.GetComponent <MCSItemModel> ().schematic = schematic;
            GameObject child2 = child.transform.GetChild(0).gameObject;

            //Adding the coremesh component to the root...ish gameobject of the item. Then we set the various values from the asset schematic (.mon file)
            child2.AddComponent <CoreMeshMetaData>();
            CoreMeshMetaData cmmd = child2.GetComponent <CoreMeshMetaData>();

            cmmd.vendorId  = schematic.origin_and_description.vendor_name;
            cmmd.versionId = schematic.version_and_control.item_version.ToString();

            switch (schematic.type_and_function.item_function)
            {
            case MCS.Utility.Schematic.Enumeration.ItemFunction.soft_wearable:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.CLOTH;
                break;

            case MCS.Utility.Schematic.Enumeration.ItemFunction.rigid_wearable:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.CLOTH;
                break;

            case MCS.Utility.Schematic.Enumeration.ItemFunction.figure:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.BODY;
                break;

            case MCS.Utility.Schematic.Enumeration.ItemFunction.hair:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.HAIR;
                break;

            case MCS.Utility.Schematic.Enumeration.ItemFunction.prop:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.PROP;
                break;

            case MCS.Utility.Schematic.Enumeration.ItemFunction.unknown:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.UNKNOWN;
                break;

            default:
                cmmd.meshType = MCS.CONSTANTS.MESH_TYPE.UNKNOWN;
                break;
            }
            cmmd.geometryId      = schematic.origin_and_description.mcs_id;
            cmmd.ID              = schematic.origin_and_description.mcs_id;
            cmmd.declarativeUse  = schematic.origin_and_description.description;
            cmmd.mcs_version     = schematic.version_and_control.mcs_version;
            cmmd.collection_name = schematic.origin_and_description.collection_name;

            //Adding all the coremesh components to anything that has a skinned mesh renderer. We also add the paths to the runtime morphs here
            foreach (SkinnedMeshRenderer rend in gameObject.GetComponentsInChildren <SkinnedMeshRenderer>())
            {
                rend.gameObject.AddComponent <CoreMesh>();

                CoreMesh cm = rend.gameObject.GetComponent <CoreMesh> ();
                cm.dazName  = schematic.origin_and_description.name;
                cm.ID       = schematic.origin_and_description.mcs_id;
                cm.meshType = cmmd.meshType;
                int index = -1;

                for (int i = 0; i < schematic.structure_and_physics.morph_structure.lodMorphObjectNames.Length; i++)
                {
                    if (schematic.structure_and_physics.morph_structure.lodMorphObjectNames [i] == cm.gameObject.name)
                    {
                        index = i;
                    }
                }

                if (index > -1)
                {
                    cm.runtimeMorphPath = schematic.structure_and_physics.morph_structure.lodMorphLocations[index];
                }
            }

            //Adding the different CICostumeItem classes, ie. CIClothing, CIBody, CIHair, CIProp.
            switch (cmmd.meshType)
            {
            case MCS.CONSTANTS.MESH_TYPE.CLOTH:
                child2.AddComponent <CIclothing>();
                CIclothing cicl = child2.GetComponent <CIclothing>();
                cicl.dazName  = schematic.origin_and_description.name;
                cicl.ID       = schematic.origin_and_description.mcs_id;
                cicl.meshType = cmmd.meshType;
                cicl.DetectCoreMeshes();
                //TODO: textures is a list of textures, not a dictionary, right?

                /*
                 *              if (textures.ContainsKey ("alphaMask")) {
                 *                      cicl.alphaMask = textures ["alphaMask"];
                 *              }
                 */
                cicl.isAttached = false;
                break;

            case MCS.CONSTANTS.MESH_TYPE.BODY:
                //todo: all the figure stuff needs to be added here, ie. CharacterManager, Core Morphs, JCT stuff, etc

                child2.AddComponent <CIbody>();
                CIbody body = child2.GetComponent <CIbody>();

                break;

            case MCS.CONSTANTS.MESH_TYPE.HAIR:
                child2.AddComponent <CIhair>();
                CIhair hair = child2.GetComponent <CIhair>();
                hair.dazName  = schematic.origin_and_description.name;
                hair.ID       = schematic.origin_and_description.mcs_id;
                hair.meshType = cmmd.meshType;
                hair.DetectCoreMeshes();
                break;

            case MCS.CONSTANTS.MESH_TYPE.PROP:
                child2.AddComponent <CIprop>();
                CIprop prop = child2.GetComponent <CIprop>();
                prop.dazName  = schematic.origin_and_description.name;
                prop.ID       = schematic.origin_and_description.mcs_id;
                prop.meshType = cmmd.meshType;
                prop.DetectCoreMeshes();
                prop.basePosition = prop.transform.localPosition;
                prop.baseRotation = prop.transform.localEulerAngles;

                //todo: add bone and attachment point stuff to the prop object
                break;

            case MCS.CONSTANTS.MESH_TYPE.UNKNOWN:
                //Unknown
                break;
            }

            return(gameObject);
        }
예제 #15
0
        public static bool RemapMorphsIfRequired(GameObject go)
        {
            SkinnedMeshRenderer[] smrArray = go.GetComponentsInChildren <SkinnedMeshRenderer>();
            StreamingMorphs       sb       = new StreamingMorphs();

            StreamingMorphs.LoadMainThreadAssetPaths();

            bool remapped = false;


            //we'll refresh this folder when we're done if we need to
            //string refreshDir = null;

            foreach (SkinnedMeshRenderer smr in smrArray)
            {
                Dictionary <int, int> tsMap = new Dictionary <int, int>();
                bool isTargetMapGenerated   = false;
                //InferredMeta meta = new InferredMeta(assetPath, go, smr);
                CoreMesh coreMesh = smr.GetComponent <CoreMesh>();
                if (coreMesh == null)
                {
                    Debug.LogWarning("Skipping: " + smr.name + ", it does not contain a CoreMesh Component");
                    continue;
                }

                //ConvertBlendshapeFromMap
                #region Remapping
                ProjectionMeshMap pmm = new ProjectionMeshMap();
                string            incompatMorphPath = coreMesh.runtimeMorphPath + "_incompat";
                string            compatMorphPath   = coreMesh.runtimeMorphPath;

                string incompatMorphPathAbsolute = Path.Combine(Application.streamingAssetsPath, incompatMorphPath);
                string compatMorphPathAbsolute   = Path.Combine(Application.streamingAssetsPath, compatMorphPath);

                string incompatMorphPathAbsoluteMeta = incompatMorphPathAbsolute + ".meta";
                string compatMorphPathAbsoluteMeta   = compatMorphPathAbsolute + ".meta";

                string mrPath = compatMorphPathAbsolute + ".morphs.mr";
                mrPath = mrPath.Replace(@"\", "/");

                bool incompatExists = Directory.Exists(incompatMorphPathAbsolute);
                bool compatExists   = Directory.Exists(compatMorphPathAbsolute);

                if (compatExists)
                {
                    string compatProjectionFilePath   = Path.Combine(compatMorphPathAbsolute, "projectionmap.bin");
                    string incompatProjectionFilePath = Path.Combine(incompatMorphPathAbsolute, "projectionmap.bin");
                    bool   didFindProjectionFile      = File.Exists(compatProjectionFilePath);

                    if (didFindProjectionFile)
                    {
                        var manifest = MCS_Utilities.MorphExtraction.MorphExtraction.GenerateManifestByCrawling(compatMorphPathAbsolute, compatMorphPathAbsolute.Substring(compatMorphPathAbsolute.LastIndexOf("/")));

                        if (manifest.names.Length <= 0)
                        {
                            UnityEngine.Debug.LogError("Unable to generate proper manifest in: " + compatMorphPathAbsolute + " => " + compatMorphPathAbsolute.Substring(compatMorphPathAbsolute.LastIndexOf("/")));
                        }

                        MCS_Utilities.Morph.MorphData sourceMD = sb.GetMorphDataFromResources(compatMorphPathAbsolute, manifest.names[0]);
                        pmm.Read(compatProjectionFilePath);

                        if (pmm.IsReMappingNeeded(smr, sourceMD, false))
                        {
                            try
                            {
                                int count = 0;
                                int total = manifest.names.Length;
                                if (incompatExists)
                                {
                                    //Delete the incompat directory.
                                    MCS_Utilities.Paths.TryDirectoryDelete(incompatMorphPathAbsolute);
                                }
                                //Move contents to incompat directory
                                Directory.Move(compatMorphPathAbsolute, incompatMorphPathAbsolute);
                                //Delete compat directory - clean up
                                //Directory.Delete(compatMorphPathAbsolute);
                                //Create compat directory.
                                Directory.CreateDirectory(compatMorphPathAbsolute);

                                foreach (string morph in manifest.names)
                                {
                                    EditorUtility.DisplayProgressBar("Processing Morphs...", morph, ((float)count / (float)total));
                                    try
                                    {
                                        MCS_Utilities.Morph.MorphData targetMD;
                                        //does this blendshape already exist, if so just continue and ignore it, and don't lookup from disk
                                        int blendshapeIndex = smr.sharedMesh.GetBlendShapeIndex(morph);
                                        if (blendshapeIndex >= 0)
                                        {
                                            continue;
                                        }

                                        sourceMD = sb.GetMorphDataFromResources(incompatMorphPathAbsolute, morph);

                                        //"Assets/MCS/Content/RRMale/Morph/Resources/LaidBack/LaidBackPants/projectionmap.bin");
                                        if (!isTargetMapGenerated)
                                        {
                                            tsMap = pmm.GenerateTargetToSourceMap(smr);
                                            isTargetMapGenerated = true;
                                        }
                                        targetMD = pmm.ConvertMorphDataFromMap(smr, sourceMD, tsMap);
                                        //MorphData mData = new MorphData { name = bsNew.name, meshName = smr.name, blendshapeState = bsNew };
                                        //var morphPath = meta.morphPathKey + "_NEW";

                                        MCS_Utilities.MorphExtraction.MorphExtraction.WriteMorphDataToFile(targetMD, compatMorphPathAbsolute + "/" + targetMD.name + ".morph", false, false);
                                        sourceMD = targetMD;
                                        //UnityEngine.Debug.Log("Converted");
                                    } catch (Exception e)
                                    {
                                        UnityEngine.Debug.LogException(e);
                                    }
                                    count++;
                                }
                                EditorUtility.ClearProgressBar();
                                //Copy the projectionmap.bin file to new folder.
                                if (isTargetMapGenerated)
                                {
                                    string saPath = Application.streamingAssetsPath;
                                    File.Copy(incompatProjectionFilePath, compatProjectionFilePath);
                                    //coreMesh.runtimeMorphPath = regeneratedMorphPath;
                                }

                                //generate an mr file
                                UnityEngine.Debug.Log("Creating MR: " + mrPath);
                                string baseMRPath = compatMorphPathAbsolute.Replace(@"\", @"/");
                                MCS_Utilities.MorphExtraction.MorphExtraction.MergeMorphsIntoMR(baseMRPath, mrPath);

                                if (Directory.Exists(compatMorphPathAbsolute))
                                {
                                    MCS_Utilities.Paths.TryDirectoryDelete(compatMorphPathAbsolute);
                                }
                                if (Directory.Exists(incompatMorphPathAbsolute))
                                {
                                    MCS_Utilities.Paths.TryDirectoryDelete(incompatMorphPathAbsolute);
                                }
                                if (File.Exists(incompatMorphPathAbsoluteMeta))
                                {
                                    File.Delete(incompatMorphPathAbsoluteMeta);
                                }
                                if (File.Exists(compatMorphPathAbsoluteMeta))
                                {
                                    File.Delete(compatMorphPathAbsoluteMeta);
                                }

                                remapped = true;
                            }
                            catch (Exception e)
                            {
                                Debug.LogException(e);
                            }
                        }
                    }
                    else
                    {
                        Debug.LogError("Missing projection file. Can't remap!");
                    }
                }
                else
                {
                    //Debug.LogWarning("Directory containing morphs does not exist!");
                }
                #endregion
            }

            //NOTE: this does not work

            /*
             * UnityEngine.Debug.LogWarning("Refresh Dir: " + refreshDir);
             *
             * if (!String.IsNullOrEmpty(refreshDir))
             * {
             *  if (Directory.Exists(refreshDir))
             *  {
             *      UnityEngine.Debug.Log("Refreshing: " + refreshDir);
             *      AssetDatabase.ImportAsset(refreshDir);
             *  }
             * }
             */
            return(remapped);
        }