コード例 #1
0
ファイル: MyExport.cs プロジェクト: tank90fc/fbx_wrapper
    public void WriteToFile(string Filename)
    {
        int  Major, Minor, Revision;
        bool Status = true;

        int  FileFormat  = -1;
        bool bEmbedMedia = false;

        // Create an exporter.
        FbxExporter Exporter = FbxExporter.Create(SdkManager, "");

        // set file format
        // Write in fall back format if pEmbedMedia is true
        FileFormat = SdkManager.GetIOPluginRegistry().GetNativeWriterFormat();
        FbxIOSettings IOS_REF = SdkManager.GetIOSettings();

        // Set the export states. By default, the export states are always set to
        // true except for the option eEXPORT_TEXTURE_AS_EMBEDDED. The code below
        // shows how to change these states.


        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_MATERIAL, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_TEXTURE, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_EMBEDDED, bEmbedMedia);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_SHAPE, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_GOBO, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_ANIMATION, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_GLOBAL_SETTINGS, true);

        string CompatibilitySetting = fbx_wrapper.FBX_2013_00_COMPATIBLE;

        if (!Exporter.SetFileExportVersion(new FbxString(CompatibilitySetting), FbxSceneRenamer.ERenamingMode.eNone))
        {
            Debug.LogWarning("Call to KFbxExporter::SetFileExportVersion(FBX_2013_00_COMPATIBLE) to export 2013 fbx file format failed.\n");
        }

        //// Initialize the exporter by providing a filename.
        if (!Exporter.Initialize(Filename, FileFormat, SdkManager.GetIOSettings()))
        {
            Debug.LogWarning("Call to KFbxExporter::Initialize() failed.\n");
            string errorString = Exporter.GetStatus().GetErrorString();
            Debug.LogWarning("Error returned:" + errorString);
            return;
        }

        //FbxManager.GetFileFormatVersion(Major, Minor, Revision);

        // Export the scene.
        Status = Exporter.Export(Scene);

        if (!Status)
        {
            string errorString = Exporter.GetStatus().GetErrorString();
            Debug.LogWarning("Error returned:" + errorString);
        }
        Clear();

        return;
    }
コード例 #2
0
            public static void OnExport()
            {
                try {
                    // Create the FBX manager
                    using (var fbxManager = FbxManager.Create())
                    {
                        var fbxScene = BuildScene(fbxManager);
                        if (fbxScene == null)
                        {
                            return;
                        }

                        // Create the exporter
                        var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                        // Find a random temp file
                        var path     = "";
                        var attempts = 0;
                        do
                        {
                            path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName() + ".fbx");
                            attempts++;
                        } while (System.IO.File.Exists(path) && attempts < 100);
                        if (attempts >= 100)
                        {
                            return;
                        }

                        // Initialize the exporter.
                        if (!fbxExporter.Initialize(path))
                        {
                            return;
                        }

                        // Set the progress callback.
                        fbxExporter.SetProgressCallback(ExportProgressCallback);

                        // Export the scene to the file.
                        if (!fbxExporter.Export(fbxScene))
                        {
                            if (fbxExporter.GetStatus().Error())
                            {
                                Debug.LogWarning("FBX Export failed: " + fbxExporter.GetStatus());
                            }
                            else
                            {
                                Debug.Log("FBX Export canceled by user.");
                            }
                        }
                    }
                } finally {
                    // You must clear the progress bar when you're done,
                    // otherwise it never goes away and many actions in Unity
                    // are blocked (e.g. you can't quit).
                    EditorUtility.ClearProgressBar();
                }
            }
コード例 #3
0
    void TaskOnClick()
    {
        // Build the fbx scene file path
        // (player/player_data/emptySceneFromRuntime.fbx)
        string fbxFilePath = Application.dataPath;

        fbxFilePath = Path.Combine(fbxFilePath, "emptySceneFromRuntime.fbx");
        fbxFilePath = Path.GetFullPath(fbxFilePath);

        Debug.Log(string.Format("The file that will be written is {0}", fbxFilePath));

        using (var fbxManager = FbxManager.Create())
        {
            FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);

            // Configure the IO settings.
            fbxManager.SetIOSettings(fbxIOSettings);

            // Create the exporter
            var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

            // Initialize the exporter.
            int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");

            bool status = fbxExporter.Initialize(fbxFilePath, fileFormat, fbxIOSettings);
            // Check that initialization of the fbxExporter was successful
            if (!status)
            {
                Debug.LogError(string.Format("failed to initialize exporter, reason: {0}",
                                             fbxExporter.GetStatus().GetErrorString()));
                return;
            }

            // Create a scene
            var fbxScene = FbxScene.Create(fbxManager, "Scene");

            // create scene info
            FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

            // set some scene info values
            fbxSceneInfo.mTitle    = "fromRuntime";
            fbxSceneInfo.mSubject  = "Exported from a Unity runtime";
            fbxSceneInfo.mAuthor   = "Unity Technologies";
            fbxSceneInfo.mRevision = "1.0";
            fbxSceneInfo.mKeywords = "export runtime";
            fbxSceneInfo.mComment  = "This is to demonstrate the capability of exporting from a Unity runtime, using the FBX SDK C# bindings";

            fbxScene.SetSceneInfo(fbxSceneInfo);

            // Export the scene to the file.
            status = fbxExporter.Export(fbxScene);

            // cleanup
            fbxScene.Destroy();
            fbxExporter.Destroy();
        }
    }
コード例 #4
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);

                    // Configure the IO settings.
                    fbxManager.SetIOSettings(fbxIOSettings);

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");

                    bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxIOSettings);
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        Debug.LogError(string.Format("failed to initialize exporter, reason:D {0}",
                                                     fbxExporter.GetStatus().GetErrorString()));
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    return(status == true ? NumNodes : 0);
                }
            }
コード例 #5
0
        public void EmptyExportImportTest()
        {
            int  N     = 10;
            long total = 0;

            for (int i = 0; i < N; i++)
            {
                m_stopwatch.Reset();
                m_stopwatch.Start();

                FbxIOSettings ioSettings = FbxIOSettings.Create(m_fbxManager, Globals.IOSROOT);
                m_fbxManager.SetIOSettings(ioSettings);

                FbxExporter exporter = FbxExporter.Create(m_fbxManager, "");

                string filename = "test.fbx";

                bool exportStatus = exporter.Initialize(filename, -1, m_fbxManager.GetIOSettings());

                // Check that export status is True
                Assert.IsTrue(exportStatus);

                // Create an empty scene to export
                FbxScene scene = FbxScene.Create(m_fbxManager, "myScene");

                // Export the scene to the file.
                exporter.Export(scene);

                exporter.Destroy();

                // Import to make sure file is valid

                FbxImporter importer = FbxImporter.Create(m_fbxManager, "");

                bool importStatus = importer.Initialize(filename, -1, m_fbxManager.GetIOSettings());

                Assert.IsTrue(importStatus);

                // Create a new scene so it can be populated
                FbxScene newScene = FbxScene.Create(m_fbxManager, "myScene2");

                importer.Import(newScene);

                importer.Destroy();

                m_stopwatch.Stop();

                total += m_stopwatch.ElapsedMilliseconds;

                // Delete the file once the test is complete
                File.Delete(filename);
            }

            CheckAgainstNative("EmptyExportImport", total / (float)N, N, 4);
        }
コード例 #6
0
        public override void TestBasics()
        {
            base.TestBasics();

            using (FbxImporter newImporter = CreateObject("MyImporter"))
            {
                // import a null document.
                Assert.IsFalse(newImporter.Import(null));

                // set a callback function
                newImporter.SetProgressCallback(null);
                newImporter.SetProgressCallback((float a, string b) => true);
                newImporter.SetProgressCallback(null);
            }

            // Export an empty scene to a temp file, then import.
            var filename = GetRandomFile();

            try {
                using (var exporter = FbxExporter.Create(Manager, "exporter")) {
                    using (var scene = FbxScene.Create(Manager, "exported scene")) {
                        Assert.IsTrue(exporter.Initialize(filename));
                        Assert.IsTrue(exporter.Export(scene));
                    }
                }
                var scene_in = FbxScene.Create(Manager, "imported scene");
                using (var importer = FbxImporter.Create(Manager, "import")) {
                    Assert.IsTrue(importer.Initialize(filename));
                    Assert.IsTrue(importer.Import(scene_in));
                    Assert.IsTrue(importer.IsFBX());

                    int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1;
                    FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision);
                    int fileMajor = -1, fileMinor = -1, fileRevision = -1;
                    importer.GetFileVersion(out fileMajor, out fileMinor, out fileRevision);
                    Assert.AreNotSame(fileMajor, -1);
                    Assert.AreNotSame(fileMinor, -1);
                    Assert.AreNotSame(fileRevision, -1);
                    Assert.AreEqual(sdkMajor, fileMajor);
                    Assert.AreEqual(sdkMinor, fileMinor);
                    Assert.AreEqual(sdkRevision, fileRevision);

                    Assert.IsEmpty(importer.GetActiveAnimStackName());
                    Assert.AreEqual(importer.GetAnimStackCount(), 0);

                    // test GetFileHeaderInfo()
                    TestGetter(importer.GetFileHeaderInfo());
                    Assert.IsNotNull(importer.GetFileHeaderInfo());
                }
                // we actually don't care about the scene itself!
            } finally {
                System.IO.File.Delete(filename);
            }
        }
コード例 #7
0
 public FbxExportGlobals(string outputFile)
 {
     m_outputFile        = outputFile;
     m_sanitizedFileName = System.Text.RegularExpressions.Regex.Replace(
         Path.GetFileNameWithoutExtension(m_outputFile),
         @"[^a-zA-Z0-9_]", "_");
     m_outputDir  = Path.GetDirectoryName(outputFile);
     m_manager    = FbxManager.Create();
     m_ioSettings = FbxIOSettings.Create(m_manager, Globals.IOSROOT);
     m_manager.SetIOSettings(m_ioSettings);
     m_exporter = FbxExporter.Create(m_manager, "");
 }
コード例 #8
0
        protected void ExportScene(string fileName)
        {
            // Export the scene
            using (FbxExporter exporter = FbxExporter.Create(FbxManager, "myExporter")) {
                // Initialize the exporter.
                bool status = exporter.Initialize(fileName, -1, FbxManager.GetIOSettings());

                // Check that export status is True
                Assert.IsTrue(status);

                // Create a new scene so it can be populated by the imported file.
                FbxScene scene = CreateScene(FbxManager);

                CheckScene(scene);

                // Export the scene to the file.
                exporter.Export(scene);

                // Check if file exists
                Assert.IsTrue(File.Exists(fileName));
            }
        }
コード例 #9
0
        public static void PackAnimations(string path, GameObject meshObject)
        {
            List <AnimationClip> clips = new List <AnimationClip>();
            List <ModelImporterClipAnimation> clipDatas = new List <ModelImporterClipAnimation>();

            var info     = new DirectoryInfo(path);
            var fileInfo = info.GetFiles();

            foreach (var file in fileInfo)
            {
                if (file.Extension == ".fbx" || file.Extension == ".FBX")
                {
                    string        relativePath = path + "/" + file.Name;
                    AnimationClip clip         = AssetDatabase.LoadAssetAtPath <AnimationClip>(relativePath);
                    //Debug.Log(relativePath);
                    if (clip != null)
                    {
                        clips.Add(clip);
                    }
                    if (alwaysFalse)
                    {
                        ModelImporter importer = AssetDatabase.LoadAssetAtPath <ModelImporter>(relativePath);
                        if (importer != null)
                        {
                            clipDatas.AddRange(importer.clipAnimations);
                        }
                    }
                }
            }
            Debug.Log(clips.Count);

            //---getting all curves/keyframes---
            if (alwaysFalse)
            {
                AnimationClip collectiveClip = new AnimationClip();
                Dictionary <string, Container> collectiveCurves = new Dictionary <string, Container>();
                float timeOffset = 0f;
                float maxTime    = 0f;
                for (int i = 0; i < clips.Count; i++)
                {
                    var bindings = AnimationUtility.GetCurveBindings(clips[i]);
                    Debug.Log("Clip[i] Count of bindings: " + bindings.Length);
                    foreach (var binding in bindings)
                    {
                        Debug.Log(binding.propertyName + ": Path: " + binding.path);
                        if (!collectiveCurves.ContainsKey(binding.propertyName))
                        {
                            collectiveCurves.Add(binding.propertyName, new Container(binding.type, binding.path));
                        }
                        var curveToWriteTo  = collectiveCurves[binding.propertyName];
                        var curveToReadFrom = AnimationUtility.GetEditorCurve(clips[i], binding);
                        //Debug.Log("Keys: " + curve.keys.Length);
                        maxTime = Mathf.Max(maxTime, curveToReadFrom.GetLastKey().time);
                        for (int frame = 0; frame < curveToReadFrom.length; frame++)
                        {
                            var keyFrame = curveToReadFrom.keys[frame];
                            keyFrame.time += timeOffset;
                            curveToWriteTo.curve.AddKey(keyFrame);
                        }
                        //collectiveClip.SetCurve()
                    }
                    timeOffset += maxTime;
                }

                foreach (var kvp in collectiveCurves)
                {
                    collectiveClip.SetCurve(kvp.Value.path, kvp.Value.typeOf, kvp.Key, kvp.Value.curve);
                }
            }

            //---instantiating go and adding animation component
            GameObject clone = Instantiate(meshObject);

            clone.name = meshObject.name;
            if (alwaysFalse)
            {
                var anim = clone.AddComponent <Animation>();
                AnimationUtility.SetAnimationClips(anim, clips.ToArray());
            }
            if (true)
            {
                var anim = clone.GetComponent <Animator>();
                if (!anim)
                {
                    anim = clone.AddComponent <Animator>();
                }
                var controller = AnimatorController.CreateAnimatorControllerAtPath(path + "/temp.controller");
                foreach (var clip in clips)
                {
                    controller.AddMotion(clip);
                }

                anim.runtimeAnimatorController = controller;
            }

            if (alwaysFalse)
            {
                var fbxManager = FbxManager.Create();
                var settings   = fbxManager.GetIOSettings();
                var exporter   = FbxExporter.Create(fbxManager, "name");
                //exporter.
            }
            if (true)
            {
                ModelExporter.ExportObject(path + "/combined.fbx", clone);
            }

            if (alwaysFalse)
            {
                using (FbxManager fbxManager = FbxManager.Create())
                {
                    // configure IO settings.
                    var settings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);
                    fbxManager.SetIOSettings(settings);
                    // Export the scene
                    using (FbxExporter exporter = FbxExporter.Create(fbxManager, "myExporter"))
                    {
                        // Initialize the exporter.
                        bool status = exporter.Initialize("combindObjects", -1, fbxManager.GetIOSettings());

                        // Create a new scene to export
                        FbxScene scene = FbxScene.Create(fbxManager, "myScene");
                        //FbxObject obj = FbxObject.Create(fbxManager, "combinedThings");
                        // Export the scene to the file.
                        exporter.Export(scene);
                    }
                }
            }


            //AssetDatabase.CreateAsset(collectiveClip, path + "/combined.anim");
            //AssetDatabase.SaveAssets();

            //Animation newAnimation = GetComponent<Animation>();
            //Debug.Log(newAnimation.name);
            //AnimationUtility.SetAnimationClips(newAnimation, clips.ToArray());
            //AssetDatabase.CreateAsset(newAnimation, path + "/combined.fbx");
            //AssetDatabase.CreateAsset(clips, path + "/testasset.fbx");
        }
コード例 #10
0
        public static bool ExportToFBX(Component_Mesh sourceMesh, string realFileName, out string error)
        {
            //!!!!как для Vegetation. оверрайдить в Component_Mesh?

            //get mesh data
            var operations = new List <Component_RenderingPipeline.RenderSceneData.MeshDataRenderOperation>();

            foreach (var geometry in sourceMesh.GetComponents <Component_MeshGeometry>())
            {
                if (geometry.Enabled)
                {
                    geometry.CompileDataOfThisObject(out var operation);
                    if (operation != null)
                    {
                        operations.Add(operation);
                    }
                }
            }
            //foreach( var geometry in mesh.Result.MeshData.RenderOperations )
            //{
            //}

            FbxManager    manager  = null;
            FbxIOSettings setting  = null;
            FbxExporter   exporter = null;
            FbxScene      scene    = null;

            try
            {
                //init FBX manager
                manager = FbxManager.Create();
                setting = FbxIOSettings.Create(manager, "IOSRoot");
                manager.SetIOSettings(setting);

                scene = FbxScene.Create(manager, "scene");
                scene.GetGlobalSettings().SetAxisSystem(new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax));
                scene.GetGlobalSettings().SetSystemUnit(new FbxSystemUnit(100));

                //init FBX scene
                for (int nOper = 0; nOper < operations.Count; nOper++)
                {
                    var oper = operations[nOper];

                    //get data

                    Vector3F[]   positions = null;
                    Vector3F[]   normals   = null;
                    var          texCoords = new List <Vector2F[]>();
                    ColorValue[] colors    = null;
                    Vector3F[]   tangents  = null;
                    Vector3F[]   binormals = null;

                    //Position
                    {
                        if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Position, out VertexElement element) && element.Type == VertexElementType.Float3)
                        {
                            var buffer = oper.VertexBuffers[element.Source];
                            positions = buffer.ExtractChannel <Vector3F>(element.Offset);
                        }
                    }

                    //Normal
                    {
                        if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Normal, out VertexElement element) && element.Type == VertexElementType.Float3)
                        {
                            var buffer = oper.VertexBuffers[element.Source];
                            normals = buffer.ExtractChannel <Vector3F>(element.Offset);
                        }
                    }

                    //TexCoord
                    for (var channel = VertexElementSemantic.TextureCoordinate0; channel <= VertexElementSemantic.TextureCoordinate3; channel++)
                    {
                        if (oper.VertexStructure.GetElementBySemantic(channel, out VertexElement element) && element.Type == VertexElementType.Float2)
                        {
                            var buffer = oper.VertexBuffers[element.Source];
                            texCoords.Add(buffer.ExtractChannel <Vector2F>(element.Offset));
                        }
                    }

                    //Color
                    {
                        if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Color0, out VertexElement element))
                        {
                            if (element.Type == VertexElementType.Float4)
                            {
                                var buffer = oper.VertexBuffers[element.Source];
                                var values = buffer.ExtractChannel <Vector4F>(element.Offset);
                                colors = new ColorValue[positions.Length];
                                int destIndex = 0;
                                foreach (var p in values)
                                {
                                    colors[destIndex++] = p.ToColorValue();
                                }
                            }
                            else if (element.Type == VertexElementType.ColorABGR)
                            {
                                //!!!!check

                                var buffer = oper.VertexBuffers[element.Source];
                                var values = buffer.ExtractChannel <uint>(element.Offset);
                                colors = new ColorValue[positions.Length];
                                int destIndex = 0;
                                foreach (var p in values)
                                {
                                    colors[destIndex++] = new ColorValue(ColorByte.FromABGR(p));
                                }
                            }
                            else if (element.Type == VertexElementType.ColorARGB)
                            {
                                //!!!!check

                                var buffer = oper.VertexBuffers[element.Source];
                                var values = buffer.ExtractChannel <uint>(element.Offset);
                                colors = new ColorValue[positions.Length];
                                int destIndex = 0;
                                foreach (var p in values)
                                {
                                    colors[destIndex++] = new ColorValue(ColorByte.FromARGB(p));
                                }
                            }
                        }
                    }

                    //Tangent, Binormal
                    if (normals != null)
                    {
                        if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Tangent, out VertexElement element) && element.Type == VertexElementType.Float4)
                        {
                            var buffer    = oper.VertexBuffers[element.Source];
                            var tangents4 = buffer.ExtractChannel <Vector4F>(element.Offset);

                            tangents  = new Vector3F[tangents4.Length];
                            binormals = new Vector3F[tangents4.Length];

                            int destIndex = 0;
                            foreach (var p in tangents4)
                            {
                                tangents[destIndex]  = p.ToVector3F();
                                binormals[destIndex] = Vector3F.Cross(p.ToVector3F(), normals[destIndex]) * p.W;
                                destIndex++;
                            }
                        }
                    }

                    //indices
                    int[] indices = null;
                    if (oper.IndexBuffer != null)
                    {
                        indices = oper.IndexBuffer.Indices;
                    }


                    //create geometry

                    var geometryName = "Geometry " + nOper.ToString();
                    var mesh         = FbxMesh.Create(scene, geometryName);

                    mesh.InitControlPoints(positions.Length);

                    FbxLayerElementNormal elementNormals = null;
                    if (normals != null)
                    {
                        elementNormals = mesh.CreateElementNormal();
                        elementNormals.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint);
                        elementNormals.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
                    }

                    FbxLayerElementVertexColor elementColors = null;
                    if (colors != null)
                    {
                        elementColors = mesh.CreateElementVertexColor();
                        elementColors.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint);
                        elementColors.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
                    }

                    FbxLayerElementTangent elementTangents = null;
                    if (tangents != null)
                    {
                        elementTangents = mesh.CreateElementTangent();
                        elementTangents.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint);
                        elementTangents.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
                    }

                    FbxLayerElementBinormal elementBinormals = null;
                    if (binormals != null)
                    {
                        elementBinormals = mesh.CreateElementBinormal();
                        elementBinormals.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint);
                        elementBinormals.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
                    }

                    var uvElements = new List <FbxLayerElementUV>();
                    for (int uvIndex = 0; uvIndex < texCoords.Count; uvIndex++)
                    {
                        var pUVElement = mesh.CreateElementUV("texcoord" + uvIndex.ToString());
                        pUVElement.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint);
                        pUVElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);

                        uvElements.Add(pUVElement);
                    }

                    for (int n = 0; n < positions.Length; n++)
                    {
                        mesh.SetControlPointAt(ToFbxVector4(positions[n]), n);

                        if (normals != null)
                        {
                            elementNormals.GetDirectArray().Add(ToFbxVector4(normals[n]));
                        }

                        for (int uvIndex = 0; uvIndex < texCoords.Count; uvIndex++)
                        {
                            var texCoord = texCoords[uvIndex][n];
                            texCoord.Y = 1.0f - texCoord.Y;
                            uvElements[uvIndex].GetDirectArray().Add(ToFbxVector2(texCoord));
                        }

                        if (colors != null)
                        {
                            elementColors.GetDirectArray().Add(ToFbxColor(colors[n]));
                        }

                        if (tangents != null)
                        {
                            elementTangents.GetDirectArray().Add(ToFbxVector4(tangents[n]));
                        }

                        if (binormals != null)
                        {
                            elementBinormals.GetDirectArray().Add(ToFbxVector4(binormals[n]));
                        }
                    }

                    if (normals != null)
                    {
                        mesh.GetLayer(0).SetNormals(elementNormals);
                    }
                    if (colors != null)
                    {
                        mesh.GetLayer(0).SetVertexColors(elementColors);
                    }
                    if (tangents != null)
                    {
                        mesh.GetLayer(0).SetTangents(elementTangents);
                    }
                    if (binormals != null)
                    {
                        mesh.GetLayer(0).SetBinormals(elementBinormals);
                    }


                    int polygonCount = indices.Length / 3;
                    for (int i = 0; i < polygonCount; i++)
                    {
                        mesh.BeginPolygon(-1, -1, -1, false);
                        for (int j = 0; j < 3; j++)
                        {
                            int currentIndex = i * 3 + j;
                            int vertexIndex  = indices[currentIndex];
                            mesh.AddPolygon(vertexIndex);
                        }
                        mesh.EndPolygon();
                    }

                    var node = FbxNode.Create(scene, geometryName);
                    node.SetNodeAttribute(mesh);

                    scene.GetRootNode().AddChild(mesh.GetNode());
                }

                //save

                exporter = FbxExporter.Create(manager, "");
                if (!exporter.Initialize(realFileName, -1, manager.GetIOSettings()))
                {
                    error = "Can't initialize FBX exporter.";
                    return(false);
                }

                if (!exporter.Export(scene))
                {
                    error = "Export to FBX failed.";
                    return(false);
                }
            }
            finally
            {
                try { scene?.Destroy(); } catch { }
                try { exporter?.Destroy(); } catch { }
                try { setting?.Destroy(); } catch { }
                try { manager?.Destroy(); } catch { }
            }

            foreach (var op in operations)
            {
                op.DisposeBuffers();
            }

            error = "";
            return(true);
        }
コード例 #11
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager; it cleans everything up at the end of the using block.
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure the IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // Set compatibility to 2014
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m); // Unity unit is meters

                    // While Unity is Y-up, Z-forward, left-handed, the FBX SDK can't convert to
                    // right-handed. So we just lie and say that we're right-handed like Maya.
                    fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp);

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of objects
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);
                        if (!unityGo)
                        {
                            continue;
                        }

                        ExportComponents(unityGo, fbxScene, fbxRootNode);
                    }

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    return(status == true ? NumNodes : 0);
                }
            }
コード例 #12
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure the IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");

                    bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of object
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    if (!status)
                    {
                        return(0);
                    }
                }
                return(NumNodes);
            }
コード例 #13
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());

                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m); // Unity unit is meters

                    // The Unity axis system has Y up, Z forward, X to the right.
                    // Export as Maya axis system.
                    fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp);

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of objects
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            var unityGoIOSettings = unityGo.GetComponent <FbxSharp.IOSettings> ();
                            if (unityGoIOSettings)
                            {
                                if (unityGoIOSettings.SystemUnit == FbxSharp.SystemUnitType.m)
                                {
                                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);
                                }
                                if (unityGoIOSettings.AxisSystem == FbxSharp.AxisSystemType.Unity)
                                {
                                    Debug.Log("setting unity axis system");
                                    fbxSettings.SetAxisSystem(UnityAxisSystem);
                                }
                            }

                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    return(status == true ? NumNodes : 0);
                }
            }
コード例 #14
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                Verbose = true;

                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure the IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    var  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    // set system units, Unity unit is meters
                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);

                    // set axis system
                    // The Unity axis system has Y up, Z forward, X to the right but since
                    // FbxAxisSystem.ConvertScene doesn't work we'll set it to right handed so
                    // that it will import into Maya right way up just mirrored.
                    var fbxAxisSystem = new FbxAxisSystem(FbxAxisSystem.EUpVector.eYAxis,
                                                          FbxAxisSystem.EFrontVector.eParityOdd,
                                                          FbxAxisSystem.ECoordSystem.eRightHanded);
                    fbxSettings.SetAxisSystem(fbxAxisSystem);

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of object
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    return(status == true ? NumNodes : 0);
                }
            }
コード例 #15
0
    public void TestWriteEmptyFbxFile()
    {
        /*
         * Runtime test that writes an fbx scene file in the directory where the
         * player is (temp folder while running tests)
         */

        // Build the fbx scene file path
        // (player/player_data/emptySceneFromRuntime.fbx)
        string fbxFilePath = Application.dataPath;

        fbxFilePath = Path.Combine(fbxFilePath, "emptySceneFromRuntime.fbx");

        // The file should not exist. We are running the test from the Test
        // Runner, which should always create a new player with its own fresh
        // data directory
        FileInfo fbxFileInfo = new FileInfo(fbxFilePath);

        Assert.That(!fbxFileInfo.Exists, string.Format("\"{0}\" already exists but the test did not create it yet", fbxFilePath));

        using (var fbxManager = FbxManager.Create())
        {
            FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);

            // Configure the IO settings.
            fbxManager.SetIOSettings(fbxIOSettings);

            // Create the exporter
            var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

            // Initialize the exporter.
            int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
            bool status     = fbxExporter.Initialize(fbxFilePath, fileFormat, fbxIOSettings);

            Assert.That(status, string.Format("failed to initialize exporter, reason:D {0}",
                                              fbxExporter.GetStatus().GetErrorString()));
            // Create a scene
            var fbxScene = FbxScene.Create(fbxManager, "Scene");

            // create scene info
            FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

            // set some scene info values
            fbxSceneInfo.mTitle    = "emptySceneFromRuntime";
            fbxSceneInfo.mSubject  = "Exported from a Unity runtime while testing in play mode";
            fbxSceneInfo.mAuthor   = "Unity Technologies";
            fbxSceneInfo.mRevision = "1.0";
            fbxSceneInfo.mKeywords = "export fbx runtime player play mode";
            fbxSceneInfo.mComment  = "This is to test the capability of exporting from a Unity runtime, using the FBX SDK C# bindings";

            fbxScene.SetSceneInfo(fbxSceneInfo);

            // Export the scene to the file.
            status = fbxExporter.Export(fbxScene);
            Assert.That(status, string.Format("Failed to export scene, reason: {0}",
                                              fbxExporter.GetStatus().GetErrorString()));

            // cleanup
            fbxScene.Destroy();
            fbxExporter.Destroy();
        }

        // Test that the file exists
        fbxFileInfo = new FileInfo(fbxFilePath);
        Assert.That(fbxFileInfo.Exists, string.Format("\"{0}\" was not created", fbxFilePath));
    }
コード例 #16
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure the IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    var fbxSettings = fbxScene.GetGlobalSettings();
                    /// Set system units : Unity unit is meters
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);
                    /// Set axis system : Unity Y Up, Z Forward, X Right (left-handed with odd parity)
                    /// The Maya axis system has Y up, Z forward, X Left (right handed system with odd parity).
                    /// We export right-handed for Maya because ConvertScene can't switch handedness:
                    /// https://forums.autodesk.com/t5/fbx-forum/get-confused-with-fbxaxissystem-convertscene/td-p/4265472
                    /// NOTE: models will flipped about the -X axis.
                    fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp);

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of object
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    // Export animations
                    ExportAllAnimation(fbxScene);

                    // Set the scene's ambient lighting.
                    SetAmbientLighting(fbxScene);

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    if (!status)
                    {
                        return(0);
                    }
                }
                return(NumNodes);
            }
コード例 #17
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                Verbose = true;

                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure fbx IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Export texture as embedded
                    fbxManager.GetIOSettings().SetBoolProp(Globals.EXP_FBX_EMBEDDED, true);

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // Set compatibility to 2014
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // set up the scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;
                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    // Set up the axes (Y up, Z forward, X to the right) and units (meters)
                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);

                    // The Unity axis system has Y up, Z forward, X to the right (left handed system with odd parity).
                    // The Maya axis system has Y up, Z forward, X to the left (right handed system with odd parity).
                    // We need to export right-handed for Maya because ConvertScene can't switch handedness:
                    // https://forums.autodesk.com/t5/fbx-forum/get-confused-with-fbxaxissystem-convertscene/td-p/4265472
                    fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp);

                    // export set of object
                    FbxNode fbxRootNode = fbxScene.GetRootNode();
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    return(status == true ? NumNodes : 0);
                }
            }
コード例 #18
0
    public static void ExportMesh(Mesh mesh, string directory, string fileName)
    {
        var filePath = Path.Combine(directory, fileName);
        // Make a temporary copy of the mesh to modify it
        Mesh tempMesh = Object.Instantiate(mesh);

        tempMesh.name = mesh.name;

        // If meters, divide by 100 since default is cm. Assume centered at origin.
        if (fbxUnit == FbxSystemUnit.m)
        {
            Vector3[] vertices = tempMesh.vertices;
            for (int i = 0; i < vertices.Length; ++i)
            {
                vertices[i] /= 100.0f;
            }
            tempMesh.vertices = vertices;
        }
        // You could handle other SystemUnits here

        // FBX Manager
        FbxManager manager = FbxManager.Create();

        manager.SetIOSettings(FbxIOSettings.Create(manager, Globals.IOSROOT));

        // FBX Exporter
        FbxExporter fbxExporter = FbxExporter.Create(manager, "Exporter");

        // Binary
        int fileFormat = -1;

        // Ascii
        if (saveFbxAsAscii)
        {
            fileFormat = manager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
        }

        fbxExporter.Initialize(filePath, fileFormat, manager.GetIOSettings());
        fbxExporter.SetFileExportVersion("FBX201400");

        // FBX Scene
        FbxScene        fbxScene  = FbxScene.Create(manager, "Scene");
        FbxDocumentInfo sceneInfo = FbxDocumentInfo.Create(manager, "SceneInfo");

        // Set up scene info
        sceneInfo.mTitle    = fbxFileTitle;
        sceneInfo.mSubject  = fbxFileSubject;
        sceneInfo.mComment  = fbxFileComment;
        sceneInfo.mAuthor   = fbxFileAuthor;
        sceneInfo.mRevision = fbxFileRevision;
        sceneInfo.mKeywords = fbxFileKeywords;
        sceneInfo.Original_ApplicationName.Set(fbxFileApplication);
        sceneInfo.LastSaved_ApplicationName.Set(fbxFileApplication);
        fbxScene.SetSceneInfo(sceneInfo);

        // Set up Global settings
        FbxGlobalSettings globalSettings = fbxScene.GetGlobalSettings();

        globalSettings.SetSystemUnit(fbxUnit);
        globalSettings.SetAxisSystem(fbxAxisSystem);

        FbxNode modelNode = FbxNode.Create(fbxScene, tempMesh.name);

        // Add mesh to a node in the scene
        // TODO Wat???
//        using (ModelExporter modelExporter = new ModelExporter())
//        {
//            if (!modelExporter.ExportMesh(tempMesh, modelNode))
//                Debug.LogError("Problem Exporting Mesh");
//        }
        // add the model to the scene
        fbxScene.GetRootNode().AddChild(modelNode);

        // Finally actually save the scene
        bool sceneSuccess = fbxExporter.Export(fbxScene);

        AssetDatabase.Refresh();

        // clean up temporary model
        if (Application.isPlaying)
        {
            Object.Destroy(tempMesh);
        }
        else
        {
            Object.DestroyImmediate(tempMesh);
        }
    }
コード例 #19
0
            /// <summary>
            /// Export all the objects in the set.
            /// Return the number of objects in the set that we exported.
            /// </summary>
            public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create()) {
                    // Configure the IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Create the exporter
                    var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                    // Initialize the exporter.
                    int  fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)");
                    bool status     = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings());
                    // Check that initialization of the fbxExporter was successful
                    if (!status)
                    {
                        return(0);
                    }

                    // By default, FBX exports in its most recent version. You might want to specify
                    // an older version for compatibility with other applications.
                    fbxExporter.SetFileExportVersion("FBX201400");

                    // Create a scene
                    var fbxScene = FbxScene.Create(fbxManager, "Scene");

                    // create scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");

                    // set some scene info values
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;

                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);      // Unity unit is meters

                    // TODO: Uni-15896
                    //fbxSettings.SetAxisSystem(FbxAxisSystem.OpenGL); // Unity axes are Y-up, odd parity, right-handed

                    FbxNode fbxRootNode = fbxScene.GetRootNode();

                    // export set of object
                    foreach (var obj in unityExportSet)
                    {
                        var unityGo = GetGameObject(obj);

                        if (unityGo)
                        {
                            this.ExportComponents(unityGo, fbxScene, fbxRootNode);
                        }
                    }

                    fbxSceneInfo.mComment =
                        string.Format("Mesh Count : {0}, Triangle Count: {1}, Vertex Count: {2} ",
                                      NumMeshes, NumTriangles, NumVertices);

                    // Export the scene to the file.
                    status = fbxExporter.Export(fbxScene);

                    // cleanup
                    fbxScene.Destroy();
                    fbxExporter.Destroy();

                    return(status == true ? NumNodes : 0);
                }
            }