Exemplo n.º 1
0
    // import a model
    public void Example1()
    {
        string     objString      = objFile.text;
        GameObject importedObject = ObjImporter.Import(objString);

        Debug.Log("Imported the object:" + importedObject);
    }
Exemplo n.º 2
0
    // import a model and materials
    public void Example2()
    {
        string     objString      = objFile.text;
        string     mtlString      = mtlFile.text;
        GameObject importedObject = ObjImporter.Import(objString, mtlString, textures);

        Debug.Log("Imported the object:" + importedObject);
    }
Exemplo n.º 3
0
    public static GameObject loadOBJ(string filePath, bool useRightHandCoordinates = false)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError("The file does not exist.");
        }

        string readText = File.ReadAllText(filePath);

        //Console.WriteLine(readText);

        return(ObjImporter.Import(readText, Quaternion.identity, Vector3.one, Vector3.zero, null, null, false, false, useRightHandCoordinates));
    }
    /* Calls the ObjImporter script to create a gameobject out of an obj string
     * string objPath: The file path of the obj file to import
     */
    private void ImportObjFromPath(string objPath)
    {
        //Converts file at given location into a string of text
        string objText = File.ReadAllText(objPath);

        //Import new model
        DestroyPrevModel();
        GameObject importObject = ObjImporter.Import(objText);

        importObject.transform.SetParent(container.transform);
        importObject.transform.localPosition = Vector3.zero;
        RestrictModelSize(importObject, container.GetComponent <Renderer>().bounds.size.x);
    }
Exemplo n.º 5
0
    private IEnumerator DownloadAndImportOBJ(string url)
    {
        string     objString      = null;
        string     mtlString      = null;
        Hashtable  textures       = null;
        GameObject importedObject = null;

        yield return(StartCoroutine(DownloadFile(url, retval => objString = retval)));

        if (objString != null && objString.Length > 0)
        {
            importedObject = ObjImporter.Import(objString, mtlString, textures);
        }
    }
Exemplo n.º 6
0
 // import a model and materials and specify all parameters
 public void Example3()
 {
     string     objString      = objFile.text;
     string     mtlString      = mtlFile.text;
     GameObject importedObject = ObjImporter.Import(
         objString,
         Quaternion.identity,        // rotate the object
         Vector3.one,                // scale of the object
         Vector3.zero,               // translate the object
         mtlString,
         textures,
         false,                              // create a child gameObject for every group tag in the OBJ file
         false                               // create a submesh for every group tag in the OBJ file
         );
 }
Exemplo n.º 7
0
    private IEnumerator DownloadAndImportAll(string url)
    {
        string     objString      = null;
        string     mtlString      = null;
        Hashtable  textures       = null;
        GameObject importedObject = null;

        yield return(StartCoroutine(DownloadFile(url, retval => objString = retval)));

        yield return(StartCoroutine(DownloadFile(url.Substring(0, url.Length - 4) + ".mtl", retval => mtlString = retval)));

        if (mtlString != null && mtlString.Length > 0)
        {
            string path      = url;
            int    lastSlash = path.LastIndexOf('/', path.Length - 1);
            if (lastSlash >= 0)
            {
                path = path.Substring(0, lastSlash + 1);
            }
            Hashtable[] mtls = ObjImporter.ImportMaterialSpecs(mtlString);
            for (int i = 0; i < mtls.Length; i++)
            {
                if (mtls[i].ContainsKey("mainTexName"))
                {
                    Texture2D texture = null;
                    string    texUrl  = path + mtls[i]["mainTexName"];
                    yield return(StartCoroutine(DownloadTexture(texUrl, retval => texture = retval)));

                    if (texture != null)
                    {
                        if (textures == null)
                        {
                            textures = new Hashtable();
                        }
                        textures[mtls[i]["mainTexName"]] = texture;
                    }
                }
            }
        }

        yield return(StartCoroutine(DownloadFile(url, retval => objString = retval)));

        if (objString != null && objString.Length > 0)
        {
            importedObject = ObjImporter.Import(objString, mtlString, textures);
        }
    }
    /* Calls the ObjImporter script to create a gameobject out of an obj string
     * string objPath: The file path of the obj file to import
     * string mtlPath: The file path of the material to import with the obj
     */
    private void ImportObjFromPath(string objPath, string mtlPath, List <string> texturePaths)
    {
        //Converts file at given location into a string of text
        string objText = File.ReadAllText(objPath);
        string mtlText = File.ReadAllText(mtlPath);

        //Converts texture paths to an array of Texture2D objects
        Texture2D[] textures = new Texture2D[texturePaths.Count];
        for (int i = 0; i < texturePaths.Count; i++)
        {
            textures[i] = LoadPNG(texturePaths[i]);
        }

        //Import new model
        DestroyPrevModel();
        GameObject importObject = ObjImporter.Import(objText, mtlText, textures);

        importObject.transform.SetParent(container.transform);
        importObject.transform.localPosition = Vector3.zero;
        RestrictModelSize(importObject, container.transform.localScale.x);
    }
Exemplo n.º 9
0
    /// <summary>
    /// Initialises models read from OBJ files in the persistent data path
    /// </summary>

    /*
     * private void initialiseModels()
     * {
     *  // Read object file through url (WWW object)
     *  {
     *      string[] objFilenames = Directory.GetFiles(Application.persistentDataPath, "*.obj");
     *
     *      for (int i = 0; i < objFilenames.Length; i++)
     *      {
     *          WWW www = WWW.LoadFromCacheOrDownload("file:///" + objFilenames[i], 1);
     *
     *          while (!www.isDone)
     *          {
     *              // TODO: use coroutine for loading screen
     *          }
     *
     *          AssetBundle bundle = www.assetBundle;
     *          AssetBundleRequest request = bundle.LoadAssetAsync<GameObject>("bugatti");
     *
     *          GameObject go = request.asset as GameObject;
     *          Instantiate(go);
     *          go.transform.SetParent(transform);
     *      }
     *  }
     *
     *  //    StreamReader objSR = File.OpenText(objFilenames[i]);
     *
     *  //    string objStr = objSR.ReadLine();
     *  //    Debug.Log("first line: " + objStr);
     *  //    while (!objSR.EndOfStream)
     *  //    {
     *  //        string str = objSR.ReadLine();
     *  //        Debug.Log("line: <" + str + ">");
     *  //        objStr += '\n' + str;
     *
     *  //        if (objSR.EndOfStream)
     *  //        {
     *  //            Debug.Log("end of stream");
     *  //        }
     *  //    }
     *
     *  //    objSR.Close();
     *  //    Debug.Log(objStr);
     *
     *  //    StreamReader matSR = File.OpenText(objFilenames[i].Replace(".obj", ".mtl"));
     *  //    string matStr = matSR.ReadToEnd();
     *  //    matSR.Close();
     *
     *  //    //string objStr = File.ReadAllText(objFilenames[i]);
     *  //    //string matStr = File.ReadAllText(objFilenames[i].Replace(".obj", ".mtl"));
     *  //    //Debug.Log(objStr);
     *
     *  //    int index = objFilenames[i].LastIndexOf('/') > objFilenames[i].LastIndexOf('\\') ? objFilenames[i].LastIndexOf('/') : objFilenames[i].LastIndexOf('\\');
     *  //    int length = objFilenames[i].Substring(index).Length;
     *  //    string name = objFilenames[i].Substring(index + 1, length - 5);
     *  //    //Debug.Log("name: " + name);
     *
     *  //    List<Texture2D> textures = new List<Texture2D>();
     *  //    string[] texFilenames = Directory.GetFiles(Application.persistentDataPath, name + "_*.png");
     *
     *  //    for (int j = 0; j < texFilenames.Length; j++)
     *  //    {
     *  //        byte[] fileData = File.ReadAllBytes(texFilenames[j]);
     *  //        Texture2D tex = new Texture2D(2, 2);
     *  //        tex.LoadImage(fileData);
     *  //        textures.Add(tex);
     *  //    }
     *
     *  //    GameObject model = ObjImporter.Import(objStr, matStr, textures.ToArray());
     *  //    model.name = name;
     *  //    model.transform.SetParent(transform, false);
     *  //    model.SetActive(false);
     *
     *  //    modelList.Add(model);
     *  //}
     *
     *  //if (modelList.Count > 0)
     *  //{
     *  //    selectVessel(modelList[0].name);
     *  //}
     * }
     */

    /// <summary>
    /// Initialises models read from OBJ files in the persistent data path
    /// </summary>
    private void initialiseModels()
    {
        string[] objFilenames = Directory.GetFiles(Application.persistentDataPath, "*_obj.*");
        for (int i = 0; i < objFilenames.Length; i++)
        {
            string objStr = File.ReadAllText(objFilenames[i]);
            string matStr = File.ReadAllText(objFilenames[i].Replace("_obj.", "_mtl."));

            int    index  = objFilenames[i].LastIndexOf('/') > objFilenames[i].LastIndexOf('\\') ? objFilenames[i].LastIndexOf('/') : objFilenames[i].LastIndexOf('\\');
            int    length = objFilenames[i].Substring(index).Length;
            string name   = objFilenames[i].Substring(index + 1, length - 9);

            List <Texture2D> textures     = new List <Texture2D>();
            string[]         texFilenames = Directory.GetFiles(Application.persistentDataPath, name + "_tex*.png");

            for (int j = 0; j < texFilenames.Length; j++)
            {
                byte[]    fileData = File.ReadAllBytes(texFilenames[j]);
                Texture2D tex      = new Texture2D(2, 2);
                tex.LoadImage(fileData);
                textures.Add(tex);
            }

            GameObject model = ObjImporter.Import(objStr, matStr, textures.ToArray());
            model.name = name;
            model.transform.SetParent(transform, false);
            model.SetActive(false);

            modelList.Add(model);
        }

        if (modelList.Count > 0)
        {
            selectVessel(modelList[0].name);
        }
    }
Exemplo n.º 10
0
 // import a model
 public void Example1()
 {
     string     objString      = objFile.text;
     GameObject importedObject = ObjImporter.Import(objString);
 }
Exemplo n.º 11
0
    /* ------------------------------------------------------------------------------------- */
    /* ------------------------------- Downloading files  ---------------------------------- */

    private IEnumerator DownloadAndImportFile(string url, Quaternion rotate, Vector3 scale, Vector3 translate, bool gameObjectPerGrp, bool subMeshPerGrp, bool usesRightHanded)
    {
        string    objString = null;
        string    mtlString = null;
        Hashtable textures  = null;

        yield return(StartCoroutine(DownloadFile(url, retval => objString = retval)));

        yield return(StartCoroutine(DownloadFile(url.Substring(0, url.Length - 4) + ".mtl", retval => mtlString = retval)));

        if (mtlString != null && mtlString.Length > 0)
        {
            string path      = url;
            int    lastSlash = path.LastIndexOf('/', path.Length - 1);
            if (lastSlash >= 0)
            {
                path = path.Substring(0, lastSlash + 1);
            }
            Hashtable[] mtls = ObjImporter.ImportMaterialSpecs(mtlString);
            for (int i = 0; i < mtls.Length; i++)
            {
                if (mtls[i].ContainsKey("mainTexName"))
                {
                    Texture2D texture = null;
                    string    texUrl  = path + mtls[i]["mainTexName"];
                    yield return(StartCoroutine(DownloadTexture(texUrl, retval => texture = retval)));

                    if (texture != null)
                    {
                        if (textures == null)
                        {
                            textures = new Hashtable();
                        }
                        textures[mtls[i]["mainTexName"]] = texture;
                    }
                }
            }
        }

        if (objString != null && objString.Length > 0)
        {
//			yield return StartCoroutine(ObjImporter.ImportInBackground(objString, mtlString, textures, rotate, scale, translate, retval => targetObject = retval, gameObjectPerGrp, subMeshPerGrp, usesRightHanded));
            targetObject = ObjImporter.Import(objString, mtlString, textures, rotate, scale, translate);
            AddToLog("Done importing model:" + targetObject);
            if (targetObject != null)
            {
                if (mtlString == null || mtlString.Length <= 0)
                {
                    SetDftTextureInAllMaterials(targetObject, defaultTexture);
                    SetDftColorInAllMaterials(targetObject, defaultTexture);
                }
                // rename the object if needed
                if (targetObject.name == "Imported OBJ file")
                {
                    string[] path = url.Split(new char[] { '/', '.' });
                    if (path.Length > 1)
                    {
                        targetObject.name = path[path.Length - 2];
                    }
                }

                // place the bottom on the floor
                overallBounds = GetBounds(targetObject);
                targetObject.transform.position = new Vector3(0, overallBounds.min.y * -1f, 0);
                overallBounds = GetBounds(targetObject);

                modelInfoText.text = GetModelInfo(targetObject, overallBounds);
                ResetCameraPosition();
            }
        }
    }
Exemplo n.º 12
0
    IEnumerator RemoteSocketLoad()
    {
        WebSocket w = new WebSocket(new Uri("ws://localhost:8001"));

        yield return(StartCoroutine(w.Connect()));

        int i = 0;

        while (true)
        {
            byte[] reply = w.Recv();
            if (reply != null)
            {
                string replyString = System.Text.Encoding.UTF8.GetString(reply, 0, reply.Length);
                if (replyString.Contains("START_OBJECT"))
                {
                    Debug.Log("Starting reading in object");
                    readingInObject = true;
                    int arrLength = Int32.Parse(replyString.Split(' ') [1]);
                    textureArray = new Texture2D[arrLength];
                }
                else
                {
                    switch (replyString)
                    {
                    case "incomingObj":
                        listeningForObj = true;
                        break;

                    case "incomingMtl":
                        listeningForMtl = true;
                        break;

                    case "incomingTexture":
                        listeningForTexture = true;
                        break;

                    case "END_OBJECT":
                        readingInObject = false;
                        Debug.Log("FULL OBJECT RECEIVED");
                        yield return(new WaitForSeconds(0.1f));

                        Array.Reverse(textureArray);
                        if (textureArray.Length > 0 && materialString != null)
                        {
                            GameObject temp = ObjImporter.Import(objectString, materialString, textureArray);
                        }
                        else if (textureArray.Length == 0 || materialString == null)
                        {
                            GameObject temp = ObjImporter.Import(objectString);
                        }
                        //GameObject temp = ObjImporter.Import (objectString, materialString, textureArray);
                        materialString = null;
                        objectString   = null;
                        textureIndex   = 0;
                        break;

                    case "START_OBJECT":
                        readingInObject = true;
                        break;

                    default:
                        if (listeningForObj)
                        {
                            Debug.Log("Mesh incoming...");
                            Debug.Log("Received: " + replyString);
                            objectString    = replyString;
                            listeningForObj = false;
                        }
                        else if (listeningForMtl)
                        {
                            Debug.Log("Material incoming...");
                            Debug.Log("Received: " + replyString);
                            materialString  = replyString;
                            listeningForMtl = false;
                        }
                        else if (listeningForTexture)
                        {
                            Debug.Log("Texture incoming...");
                            Texture2D tempTexture = new Texture2D(1, 1);
                            tempTexture.LoadImage(reply);
                            textureArray[textureIndex] = tempTexture;
                            //textureArray [i] = tempTexture; //OLD ARRAY IMPLEMENTATION
                            //i++;
                            textureIndex++;
                            listeningForTexture = false;
                        }
                        break;
                    }
                }

                /*
                 * if (replyString.Contains ("newmtl")) {
                 *      Debug.Log ("Material incoming...");
                 *      Debug.Log ("Received: "+replyString);
                 *      materialString = replyString;
                 * } else if (replyString.Contains ("object")) {
                 *      Debug.Log ("Mesh incoming...");
                 *      Debug.Log ("Received: "+replyString);
                 *      objectString = replyString;
                 * } else if (replyString == "END_TEXTURES") {
                 *      Debug.Log ("ALL TEXTURES RECEIVED");
                 *      Array.Reverse (textureArray);
                 *      GameObject temp = ObjImporter.Import (objectString, materialString, textureArray);
                 * }
                 * else {
                 *      Debug.Log ("Texture incoming...");
                 *      Texture2D tempTexture = new Texture2D (1, 1);
                 *      tempTexture.LoadImage (reply);
                 *      textureArray [i] = tempTexture;
                 *      i++;
                 * }
                 */

                //GameObject temp = ObjImporter.Import (reply);
                //MeshRenderer renderer = temp.GetComponent<MeshRenderer> ();
                //renderer.materials = DefineMaterial(
                //w.SendString("Hi there"+i++);
                //i++;
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(null);
        }
        w.Close();
    }
Exemplo n.º 13
0
    public static GameObject LoadObj(string objPath, string mtlPath)
    {
        //ObjImporter.shader = Shader.Find(AssetManager.instance.defaultColorShaderName);//AssetManager.instance.defaultColorShader;
        //if (ObjImporter.shader == null)
        //    ObjImporter.shader = AssetManager.instance.fallbackShader;
        ObjImporter.material = AssetManager.instance.objMaterial;
        //Debug.Log("*****ERR: can't find shader " + AssetManager.instance.defaultColorShaderName);
        GameObject result = null;

        Hashtable textures = new Hashtable();

        Debug.Log("Loading obj " + objPath + " mtl " + mtlPath);
        if (mtlPath == null || !File.Exists(mtlPath))
        {
            Debug.Log("Material path " + mtlPath + " doesn't exist, switching to " + objPath);
            mtlPath = objPath.Substring(0, objPath.Length - ".obj".Length) + ".mtl";
            Debug.Log("New path " + mtlPath);
        }

        string objContents = ReadFile(objPath);
        string matContents = ReadFile(mtlPath);//resourcePath + ".mtl");

        //bool hasTexture = false;
        Hashtable[] mtls = null;
        if (matContents != null)
        {
            mtls = ObjImporter.ImportMaterialSpecs(matContents);

            //Debug.Log("Material count " + mtls.Length);

            for (int i = 0; i < mtls.Length; i++)
            {
                if (mtls[i].ContainsKey("mainTexName"))
                {
                    var    resDir  = Path.GetDirectoryName(mtlPath);
                    string texName = ((string)mtls[i]["mainTexName"]).Replace(' ', '_');
                    var    texPath = Path.Combine(resDir, texName);

                    //Debug.Log("****************************************TEX PATH " + texPath);
                    var texture = Utils.LoadTexture(texPath);
                    if (texture != null)
                    {
                        //hasTexture = true;
                        //ObjImporter.shader = Shader.Find(AssetManager.instance.defaultTextureShaderName);//AssetManager.instance.defaultTextureShader;
                        //if (ObjImporter.shader == null)
                        //    ObjImporter.shader = AssetManager.instance.fallbackShader;
                        //Debug.Log("*****ERR: can't find shader " + AssetManager.instance.defaultColorShaderName);
                        textures[mtls[i]["mainTexName"]] = texture;
                    }
                }
            }
        }

        result = ObjImporter.Import(objContents, matContents, textures);
        if (result == null)
        {
            Debug.LogError("Oops. GameObject not loaded from path: " + objPath + "||" + mtlPath);
            //throw new Exception("GameObject could not be loaded from " + resourcePath);
        }

        //Shader shader = Shader.Find("LightweightRenderPipeline/Unlit");

        //Renderer[] renderers = result.GetComponentsInChildren<Renderer>();
        //foreach (Renderer r in renderers)
        //{
        //    Material[] mats = r.materials;
        //    for (int i = 0; i < mats.Length; i++)
        //    {
        //        if (hasTexture)
        //            mats[i].shader = AssetManager.instance.defaultTextureShader;
        //        else
        //            mats[i].shader = AssetManager.instance.defaultColorShader;
        //        /*
        //        //mats[i] = AssetManager.Instance.testMaterial;
        //        //break;
        //        if (unlit)
        //        {
        //            mats[i].shader = AssetManager.Instance.unlitShader;
        //        }
        //        else if (translucid)
        //        {
        //            mats[i].shader = AssetManager.Instance.translucidShader;
        //        }
        //        else
        //        {
        //            mats[i].shader = AssetManager.Instance.defaultShader;
        //        }

        //        if (colorTweak != Color.white)
        //        {
        //            //Debug.Log("SETTING TINT!!!!!!!!!--------------------------------------------------------------------- " + mats[i].name + " " + template.name);
        //            //mats[i].color = new Color((mats[i].color.r + colorTweak.r) / 2, (mats[i].color.g + colorTweak.g) / 2, (mats[i].color.b + colorTweak.b) / 2, (mats[i].color.a + colorTweak.a) / 2);

        //            Color originalColor = mats[i].color;
        //            float a = colorTweak.a;
        //            float oneMinusA = 1 - colorTweak.a;
        //            mats[i].color = new Color(mats[i].color.r * oneMinusA + colorTweak.r * a, mats[i].color.g * oneMinusA + colorTweak.g * a, mats[i].color.b * oneMinusA + colorTweak.b * a);

        //            //mats[i].color = new Color((mats[i].color.r + colorTweak.r * colorTweak.a), (mats[i].color.g + colorTweak.g * colorTweak.a), (mats[i].color.b + colorTweak.b * colorTweak.a));//, (mats[i].color.a + colorTweak.a));
        //        }
        //         * */
        //    }

        //    r.materials = mats;
        //}
        return(result);
    }
Exemplo n.º 14
0
    IEnumerator ImportObject(string url)
    {
        print("import called");
        WWW www = new WWW(url);

        yield return(www);

        string zip_path   = "";
        string write_path = "";

        if (!string.IsNullOrEmpty(www.error))
        {
            // debug.text = "download failed";
        }
        else
        {
            if (device == "android")
            {
                zip_path   = Application.persistentDataPath + "/download.obj.zip";
                write_path = Application.persistentDataPath + "/download.obj";
            }
            else if (device == "pc")
            {
                zip_path   = Application.dataPath + "download.obj.zip";
                write_path = Application.dataPath + "/download.obj";
            }

            System.IO.File.WriteAllBytes(zip_path, www.bytes);
            ZipUtil.Unzip(zip_path, write_path);

            // debug.text = "downloaded and saved";
            sceneText.text = debug.text;
            string[] objFiles = Directory.GetFiles(write_path);
            string   objFile  = "";
            string   textFile = "";
            foreach (string file in objFiles)
            {
                string[] splitFile = file.Split('/');
                if (splitFile[splitFile.Length - 1].Contains(".obj"))
                {
                    objFile = file;
                }
                if (splitFile[splitFile.Length - 1].Contains(".jpg"))
                {
                    textFile = file;
                }
            }
            print("importing: " + objFile);
            importer.Import(objFile, textFile);
        }

        try
        {
            /*
             * GameObject spawnedPrefab;
             * FastObjImport importTool = new FastObjImport();
             * Mesh peanuts = importTool.ImportFile(write_path);
             * spawnedPrefab = Instantiate(emptyPrefabWithMeshRenderer);
             * spawnedPrefab.GetComponent<MeshFilter>().mesh = peanuts;
             * spawnedPrefab.transform.position = new Vector3(0, 0, 0);
             * debug.text = "done";
             */
        }

        catch (Exception e)
        {
            debug.text = "saved, but..." + e.ToString();
        }

        /*
         * Mesh importedMesh = objImporter.ImportFile(Application.dataPath + "/Objects/" + modelName);
         *
         * spawnedPrefab = Instantiate(emptyPrefabWithMeshRenderer);
         * spawnedPrefab.transform.position = new Vector3(0, 0, 0);
         * spawnedPrefab.GetComponent<MeshFilter>().mesh = importedMesh;
         */
    }