Exemplo n.º 1
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);
                }
            }
Exemplo n.º 2
0
 public void Init()
 {
     m_stopwatch  = new Stopwatch();
     m_fbxManager = FbxManager.Create();
 }
Exemplo n.º 3
0
 public void Init()
 {
     m_fbxManager = FbxManager.Create();
 }
Exemplo n.º 4
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);
        }
    }
Exemplo n.º 5
0
        void Run()
        {
            FbxManager    manager = FbxManager.Create();
            FbxIOSettings setting = FbxIOSettings.Create(manager, "IOSRoot");

            //fbxiosettingspath.h
            //PostProcessSteps.CalculateTangentSpace = #define EXP_TANGENTSPACE				EXP_GEOMETRY "|" IOSN_TANGENTS_BINORMALS
            //PostProcessSteps.JoinIdenticalVertices = #define IOSN_DXF_WELD_VERTICES           "WeldVertices"
            //PostProcessSteps.Triangulate = #define IOSN_TRIANGULATE                "Triangulate"
            //PostProcessSteps.RemoveComponent =
            //PostProcessSteps.GenerateSmoothNormals =
            //setting.AddProperty()
            setting.SetBoolProp("Import|AdvOptGrp|Dxf|WeldVertices", true);
            setting.SetBoolProp("Triangulate", true);

            manager.SetIOSettings(setting);

            FbxImporter impoter = FbxImporter.Create(manager, "");

            bool status = impoter.Initialize(@"1.fbx", -1, setting);

            Log.Info(status);

            if (!status)
            {
                return;
            }

            FbxScene scene = FbxScene.Create(manager, "scene1");

            status = impoter.Import(scene);
            Log.Info(status);


            int numTrack = scene.GetSrcObjectCount(FbxCriteria.ObjectType(FbxAnimStack.ClassId));

            Log.Info("num stack " + numTrack);

            FbxObject obj = scene.GetSrcObject(FbxCriteria.ObjectType(FbxAnimStack.ClassId), 0);

            FbxAnimStack stack = FbxAnimStack.Cast(obj);

            if (stack == null)
            {
                Log.Error("can not get anim stack!");
                return;
            }

            FbxCriteria cri      = FbxCriteria.ObjectTypeStrict(FbxAnimLayer.ClassId);
            int         numLayer = stack.GetMemberCount(cri);

            Log.Info("anim layer count : " + numLayer);

            FbxAnimLayer layer = null;

            if (numLayer > 0)
            {
                FbxObject layerobj = stack.GetMember(cri, 0);
                layer = FbxAnimLayer.Cast(layerobj);
                if (layer == null)
                {
                    Log.Error("anim layer is null!");
                    return;
                }

                Log.Info("anim layer name " + layer.GetName());
            }


            Log.Info("node count " + scene.GetNodeCount());
            for (int i = 0; i < scene.GetNodeCount(); i++)
            {
                FbxNode node = scene.GetNode(i);
                Log.Info("node " + i + " " + node.GetName() + " ChildCount:" + node.GetChildCount());

                //----------------
                //node.LclTranslation.IsAnimated
                //----------------
                //ToDo :

                if (node.LclTranslation.IsAnimated(layer))
                {
                    FbxAnimCurveNode curveNode = node.LclTranslation.GetCurveNode(layer);
                    if (curveNode == null)
                    {
                        Log.Error("curve node is null");
                    }
                    else
                    {
                        for (int c = 0; c < curveNode.GetCurveCount(0); c++)
                        {
                            FbxAnimCurve curve = curveNode.GetCurve(0, (uint)c);
                            if (curve != null)
                            {
                                Log.Info("curve " + curve.GetName());
                                Log.Info("key count " + curve.KeyGetCount());
                                FbxAnimCurveKey key = curve.KeyGet(0);
                                FbxTime         t   = key.GetTime();
                                Log.Info("key " + t.GetTimeString() + " value " + key.GetValue());
                            }
                        }
                    }
                }



                if (node.GetNodeAttribute() != null)
                {
                    Log.Info("got attribu");
                    FbxNodeAttribute att = node.GetNodeAttribute();
                    PrintAttribute(manager, att);
                }
                else
                {
                    Log.Info("att count " + node.GetNodeAttributeCount());
                    for (int j = 0; j < node.GetNodeAttributeCount(); j++)
                    {
                        FbxNodeAttribute att = node.GetNodeAttributeByIndex(j);
                        PrintAttribute(manager, att);
                    }
                }

                FbxVector4    rot = node.GetPostRotation(FbxNode.EPivotSet.eSourcePivot);
                FbxQuaternion q;
            }
        }
Exemplo n.º 6
0
        public void TestEquality()
        {
            using (var manager = FbxManager.Create()) {
                // FbxProperty
                var node      = FbxNode.Create(manager, "node");
                var prop1     = FbxProperty.Create(node, Globals.FbxBoolDT, "bool1");
                var prop2     = FbxProperty.Create(node, Globals.FbxBoolDT, "bool2");
                var prop1copy = node.FindProperty("bool1");
                EqualityTester <FbxProperty> .TestEquality(prop1, prop2, prop1copy);

                // FbxPropertyT<bool>
                var vis1     = node.VisibilityInheritance;
                var vis2     = FbxNode.Create(manager, "node2").VisibilityInheritance;
                var vis1copy = vis1; // TODO: node.FindProperty("Visibility Inheritance"); -- but that has a different proxy type
                EqualityTester <FbxPropertyBool> .TestEquality(vis1, vis2, vis1copy);

                // FbxPropertyT<EInheritType>
                var inhType1     = node.InheritType;
                var inhType2     = FbxNode.Create(manager, "node3").InheritType;
                var inhType1Copy = inhType1; // TODO: node.FindProperty("InheritType");
                EqualityTester <FbxPropertyEInheritType> .TestEquality(inhType1, inhType2, inhType1Copy);

                // FbxPropertyT<double>
                var lambert      = FbxSurfaceLambert.Create(manager, "lambert");
                var emissiveCopy = lambert.EmissiveFactor; // TODO: lambert.FindProperty("EmissiveFactor");
                EqualityTester <FbxPropertyDouble> .TestEquality(lambert.EmissiveFactor, lambert.AmbientFactor, emissiveCopy);

                // FbxPropertyT<FbxDouble3>
                var lclTranslationCopy = node.LclTranslation; // TODO: node.FindProperty("Lcl Translation");
                EqualityTester <FbxPropertyDouble3> .TestEquality(node.LclTranslation, node.LclRotation, lclTranslationCopy);

                // FbxPropertyT<float>
                var light = FbxLight.Create(manager, "light");
                EqualityTester <FbxPropertyFloat> .TestEquality(light.LeftBarnDoor, light.RightBarnDoor, light.LeftBarnDoor);

                // FbxPropertyT<int>
                var constraint      = FbxConstraintAim.Create(manager, "constraint");
                var constraint2     = FbxConstraintAim.Create(manager, "constraint2");
                var worldUpTypeCopy = constraint.WorldUpType; // TODO: constraint.FindProperty("WorldUpType");
                EqualityTester <FbxPropertyInt> .TestEquality(constraint.WorldUpType, constraint2.WorldUpType, worldUpTypeCopy);

                // FbxPropertyT<> for FbxTexture enums
                var tex1      = FbxTexture.Create(manager, "tex1");
                var tex2      = FbxTexture.Create(manager, "tex2");
                var blendCopy = tex1.CurrentTextureBlendMode; // TODO: tex1.FindProperty(...)
                EqualityTester <FbxPropertyEBlendMode> .TestEquality(tex1.CurrentTextureBlendMode, tex2.CurrentTextureBlendMode, blendCopy);

                var wrapCopy = tex1.WrapModeU; // TODO: tex1.FindProperty(...)
                EqualityTester <FbxPropertyEWrapMode> .TestEquality(tex1.WrapModeU, tex2.WrapModeU, wrapCopy);

                // FbxPropertyT<FbxNull.ELook>
                var null1 = FbxNull.Create(manager, "null1");
                var null2 = FbxNull.Create(manager, "null2");
                EqualityTester <FbxPropertyNullELook> .TestEquality(null1.Look, null2.Look, null1.Look);

                // FbxPropertyT<FbxMarker.ELook>
                var marker1 = FbxMarker.Create(manager, "marker1");
                var marker2 = FbxMarker.Create(manager, "marker2");
                EqualityTester <FbxPropertyMarkerELook> .TestEquality(marker1.Look, marker2.Look, marker1.Look);

                // FbxPropertyT<string>
                var impl          = FbxImplementation.Create(manager, "impl");
                var renderAPIcopy = impl.RenderAPI; // TODO: impl.FindProperty("RenderAPI");
                EqualityTester <FbxPropertyString> .TestEquality(impl.RenderAPI, impl.RenderAPIVersion, renderAPIcopy);

                // FbxPropertyT<> for FbxCamera enum EProjectionType
                var cam1           = FbxCamera.Create(manager, "cam1");
                var cam2           = FbxCamera.Create(manager, "cam2");
                var projectionCopy = cam1.ProjectionType;
                EqualityTester <FbxPropertyEProjectionType> .TestEquality(cam1.ProjectionType, cam2.ProjectionType, projectionCopy);

                // FbxPropertyT<> for FbxLight enum EType
                var light1   = FbxLight.Create(manager, "light1");
                var light2   = FbxLight.Create(manager, "light2");
                var typeCopy = light1.LightType;
                EqualityTester <FbxPropertyELightType> .TestEquality(light1.LightType, light2.LightType, typeCopy);

                var lightShapeCopy = light1.AreaLightShape;
                EqualityTester <FbxPropertyEAreaLightShape> .TestEquality(light1.AreaLightShape, light2.AreaLightShape, lightShapeCopy);

                var decayCopy = light1.DecayType;
                EqualityTester <FbxPropertyEDecayType> .TestEquality(light1.DecayType, light2.DecayType, decayCopy);

                var floatCopy = light1.LeftBarnDoor;
                EqualityTester <FbxPropertyFloat> .TestEquality(light1.LeftBarnDoor, light2.LeftBarnDoor, floatCopy);
            }
        }
Exemplo n.º 7
0
        static bool LoadFBX(ImportContext context, string virtualFileName, out List <MeshData> geometries)
        {
            geometries = null;

            var settings = context.settings;

            ImportFBX.LoadNativeLibrary();

            FbxManager    manager  = null;
            FbxIOSettings setting  = null;
            FbxImporter   importer = null;
            FbxScene      scene    = null;

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

                importer = FbxImporter.Create(manager, "");
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(virtualFileName);
                //VirtualFileStream stream = null;
                //ToDo : FromStream
                bool status;
                if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName))
                {
                    status = importer.Initialize(realFileName, -1, setting);
                }
                else
                {
                    return(false);
                    //throw new NotImplementedException();
                    //ToDo : ....
                    //stream = VirtualFile.Open( settings.virtualFileName );
                    //FbxStream fbxStream = null;
                    //SWIGTYPE_p_void streamData = null;

                    //status = impoter.Initialize( fbxStream, streamData, -1, setting );
                }

                if (!status)
                {
                    return(false);
                }

                scene  = FbxScene.Create(manager, "scene1");
                status = importer.Import(scene);
                if (!status)
                {
                    return(false);
                }

                //convert axis
                if (context.settings.component.ForceFrontXAxis)
                {
                    //Через такой конструктор не получится создать такие же оси как EPreDefinedAxisSystem.eMax - Front Axis имеет обратное направление, а направление задать нельзя.
                    //new FbxAxisSystem( FbxAxisSystem.EUpVector.eZAxis, FbxAxisSystem.EFrontVector.eParityOdd, FbxAxisSystem.ECoordSystem.eRightHanded );
                    //FromFBX Docs:
                    //The enum values ParityEven and ParityOdd denote the first one and the second one of the remain two axes in addition to the up axis.
                    //For example if the up axis is X, the remain two axes will be Y And Z, so the ParityEven is Y, and the ParityOdd is Z ;

                    //We desire to convert the scene from Y-Up to Z-Up. Using the predefined axis system: Max (UpVector = +Z, FrontVector = -Y, CoordSystem = +X (RightHanded))
                    var maxAxisSystem = new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax);

                    if (!scene.GetGlobalSettings().GetAxisSystem().eq(maxAxisSystem))
                    {
                        maxAxisSystem.ConvertScene(scene);                           //No conversion will take place if the scene current axis system is equal to the new one. So condition can be removed.
                    }
                }

                //convert units
                if (!scene.GetGlobalSettings().GetSystemUnit().eq(FbxSystemUnit.m))
                {
                    FbxSystemUnit.m.ConvertScene(scene);
                }

                var additionalTransform = new Matrix4(settings.component.Rotation.Value.ToMatrix3() * Matrix3.FromScale(settings.component.Scale), settings.component.Position);

                var options = new ImportOptions
                {
                    NormalsOptions         = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    TangentsOptions        = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    ImportPostProcessFlags = ImportPostProcessFlags.FixInfacingNormals
                };
                options.ImportPostProcessFlags |= ImportPostProcessFlags.SmoothNormals | ImportPostProcessFlags.SmoothTangents;
                if (context.settings.component.FlipUVs)
                {
                    options.ImportPostProcessFlags |= ImportPostProcessFlags.FlipUVs;
                }
                //if( importContext.settings.component.MergeMeshGeometries )
                //	options.ImportPostProcessFlags |= ImportPostProcessFlags.MergeGeometriesByMaterials;

                var sceneLoader = new SceneLoader();
                sceneLoader.Load(scene, manager, options, additionalTransform);

                geometries = sceneLoader.Geometries;
                //foreach( var geometry in sceneLoader.Geometries )
                //	ImportGeometry( context, destinationMesh, geometry );

                ////check is it a billboard
                //MeshGetIsBillboard( context, destinationMesh );

                //stream?.Dispose();
            }
            finally
            {
                //Особенности удаления.
                //Создается через функцию: impoter = FbxImporter.Create(manager, "");
                //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает.
                //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor
                //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy.

                try { scene?.Destroy(); } catch { }
                try { importer?.Destroy(); } catch { }
                try { setting?.Destroy(); } catch { }
                try { manager?.Destroy(); } catch { }
            }

            return(true);
        }
Exemplo n.º 8
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);
                }
            }
Exemplo n.º 9
0
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Открытие файла
            /// </summary>
            //---------------------------------------------------------------------------------------------------------
            public void OpenFile(TreeView model_tree_view)
            {
                if (mIsLoading)
                {
                    return;
                }
                String path = XFileDialog.OpenUseExtension("Открыть 3D файл", OpenFileFilter);

                if (path == null)
                {
                    return;
                }
                StopAnimation();



                // Create the FBX SDK manager
                FbxManager lSdkManager = FbxManager.Create();

                // Create an IOSettings object.
                FbxIOSettings ios = FbxIOSettings.Create(lSdkManager, Globals.IOSROOT);

                lSdkManager.SetIOSettings(ios);

                // ... Configure the FbxIOSettings object ...

                // Create an importer.
                FbxImporter lImporter = FbxImporter.Create(lSdkManager, "");

                // Initialize the importer.
                bool lImportStatus = lImporter.Initialize(path, -1, lSdkManager.GetIOSettings());



                mIsLoading = true;
                Task.Run(() =>
                {
                    var loader = new Importer();

                    //loader.Configuration.AssimpPostProcessSteps =
                    //loader.Configuration.AssimpPostProcessSteps |
                    //Assimp.PostProcessSteps.OptimizeGraph;

                    return(loader.Load(path));
                }).ContinueWith((result) =>
                {
                    mIsLoading = false;
                    if (result.IsCompleted)
                    {
                        HelixToolkitScene helix_toolkit_scene = result.Result;
                        if (helix_toolkit_scene == null)
                        {
                            return;
                        }
                        mSceneRoot       = helix_toolkit_scene.Root;
                        mSceneAnimations = helix_toolkit_scene.Animations;
                        Animations.Clear();
                        GroupModel.Clear();
                        if (helix_toolkit_scene != null)
                        {
                            if (helix_toolkit_scene.Root != null)
                            {
                                foreach (var node in helix_toolkit_scene.Root.Traverse())
                                {
                                    if (node is MaterialGeometryNode m)
                                    {
                                        if (m.Material is PBRMaterialCore pbr)
                                        {
                                            pbr.RenderEnvironmentMap = RenderEnvironmentMap;
                                        }
                                        else if (m.Material is PhongMaterialCore phong)
                                        {
                                            phong.RenderEnvironmentMap = RenderEnvironmentMap;
                                        }
                                    }
                                }
                            }

                            GroupModel.AddNode(helix_toolkit_scene.Root);
                            if (helix_toolkit_scene.HasAnimation)
                            {
                                var dict = helix_toolkit_scene.Animations.CreateAnimationUpdaters();
                                foreach (var animation in dict.Values)
                                {
                                    Animations.Add(animation);
                                }
                            }
                            foreach (var node in helix_toolkit_scene.Root.Traverse())
                            {
                                //node.Tag = new AttachedNodeViewModel(node);
                            }
                        }

                        Boolean is_y_up            = threeViewer.IsModelUpDirectionY();
                        checkBoxYUpModel.IsChecked = is_y_up;
                        if (is_y_up)
                        {
                        }

                        model_tree_view.ItemsSource = mSceneRoot.Items;
                        //Scene = new CScene3D()
                    }
                    else if (result.IsFaulted && result.Exception != null)
                    {
                        MessageBox.Show(result.Exception.Message);
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
Exemplo n.º 10
0
        public void TestBasics()
        {
            Assert.That(!string.IsNullOrEmpty(ModelExporter.GetVersionFromReadme()));

            // Test GetOrCreateLayer
            using (var fbxManager = FbxManager.Create()) {
                var fbxMesh = FbxMesh.Create(fbxManager, "name");
                var layer0  = ModelExporter.GetOrCreateLayer(fbxMesh);
                Assert.That(layer0, Is.Not.Null);
                Assert.That(ModelExporter.GetOrCreateLayer(fbxMesh), Is.EqualTo(layer0));
                var layer5 = ModelExporter.GetOrCreateLayer(fbxMesh, layer: 5);
                Assert.That(layer5, Is.Not.Null);
                Assert.That(layer5, Is.Not.EqualTo(layer0));
            }

            // Test axis conversion: a x b in left-handed is the same as b x a
            // in right-handed (that's why we need to flip the winding order).
            var a         = new Vector3(1, 0, 0);
            var b         = new Vector3(0, 0, 1);
            var crossLeft = Vector3.Cross(a, b);

            Assert.That(ModelExporter.DefaultMaterial);

            // Test non-static functions.
            using (var fbxManager = FbxManager.Create()) {
                var fbxScene = FbxScene.Create(fbxManager, "scene");
                var fbxNode  = FbxNode.Create(fbxScene, "node");
                var exporter = new ModelExporter();

                // Test ExportMaterial: it exports and it re-exports
                bool result = exporter.ExportMaterial(ModelExporter.DefaultMaterial, fbxScene, fbxNode);
                Assert.IsTrue(result);
                var fbxMaterial = fbxNode.GetMaterial(0);
                Assert.That(fbxMaterial, Is.Not.Null);

                result = exporter.ExportMaterial(ModelExporter.DefaultMaterial, fbxScene, fbxNode);
                var fbxMaterial2 = fbxNode.GetMaterial(1);
                Assert.AreEqual(fbxMaterial, fbxMaterial2);

                // Test ExportTexture: it finds the same texture for the default-material (it doesn't create a new one)
                var fbxMaterialNew = FbxSurfaceLambert.Create(fbxScene, "lambert");
                exporter.ExportTexture(ModelExporter.DefaultMaterial, "_MainTex",
                                       fbxMaterialNew, FbxSurfaceLambert.sBump);
                Assert.AreEqual(
                    fbxMaterial.FindProperty(FbxSurfaceLambert.sDiffuse).GetSrcObject(),
                    fbxMaterialNew.FindProperty(FbxSurfaceLambert.sBump).GetSrcObject()
                    );

                // Test ExportMesh: make sure we exported a mesh with welded vertices.
                var cube     = GameObject.CreatePrimitive(PrimitiveType.Cube);
                var cubeNode = FbxNode.Create(fbxScene, "cube");
                exporter.ExportMesh(cube.GetComponent <MeshFilter>().sharedMesh, cubeNode);
                Assert.That(cubeNode.GetMesh(), Is.Not.Null);
                Assert.That(cubeNode.GetMesh().GetControlPointsCount(), Is.EqualTo(8));
            }

            // Test exporting a skinned-mesh. Make sure it doesn't leak (it did at one point)
            {
                var cube      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                var character = new GameObject();
                var smr       = character.AddComponent <SkinnedMeshRenderer>();
                smr.sharedMesh = cube.GetComponent <MeshFilter>().sharedMesh;
                var meshCount = Object.FindObjectsOfType <Mesh>().Length;
                ModelExporter.ExportObject(GetRandomFbxFilePath(), character);
                Assert.AreEqual(meshCount, Object.FindObjectsOfType <Mesh>().Length);
            }

            // Test euler to quaternion conversion
            {
                // EulerToQuaternionZXY
                var v         = new Vector3(50, 45, 190);
                var quat      = ModelExporter.EulerToQuaternionZXY(v);
                var unityQuat = Quaternion.Euler(v);
                Assert.That((float)quat.X, Is.EqualTo(unityQuat.x));
                Assert.That((float)quat.Y, Is.EqualTo(unityQuat.y));
                Assert.That((float)quat.Z, Is.EqualTo(unityQuat.z));
                Assert.That((float)quat.W, Is.EqualTo(unityQuat.w));

                // EulerToQuaternionXYZ
                var fbxV    = new FbxVector4(v.x, v.y, v.z);
                var xyzQuat = ModelExporter.EulerToQuaternionXYZ(fbxV);

                // get the vector from the quaternion
                FbxAMatrix m = new FbxAMatrix();
                m.SetR(fbxV);
                var actualQuat = m.GetQ();

                // since this quaternion is XYZ instead of ZXY, it should not match the quaternion
                // created with EulerToQuaternionZXY
                Assert.That(xyzQuat, Is.Not.EqualTo(quat));
                Assert.That(xyzQuat, Is.EqualTo(actualQuat));
            }
        }
Exemplo n.º 11
0
        public void TestBasics()
        {
            Assert.That(!string.IsNullOrEmpty(ModelExporter.GetVersionFromReadme()));

            // Test GetOrCreateLayer
            using (var fbxManager = FbxManager.Create()) {
                var fbxMesh = FbxMesh.Create(fbxManager, "name");
                var layer0  = ModelExporter.GetOrCreateLayer(fbxMesh);
                Assert.That(layer0, Is.Not.Null);
                Assert.That(ModelExporter.GetOrCreateLayer(fbxMesh), Is.EqualTo(layer0));
                var layer5 = ModelExporter.GetOrCreateLayer(fbxMesh, layer: 5);
                Assert.That(layer5, Is.Not.Null);
                Assert.That(layer5, Is.Not.EqualTo(layer0));
            }

            // Test axis conversion: a x b in left-handed is the same as b x a
            // in right-handed (that's why we need to flip the winding order).
            var a         = new Vector3(1, 0, 0);
            var b         = new Vector3(0, 0, 1);
            var crossLeft = Vector3.Cross(a, b);

            var afbx = ModelExporter.ConvertToRightHanded(a);
            var bfbx = ModelExporter.ConvertToRightHanded(b);

            Assert.AreEqual(ModelExporter.ConvertToRightHanded(crossLeft), bfbx.CrossProduct(afbx));

            // Test scale conversion. Nothing complicated here...
            var afbxPosition = ModelExporter.ConvertToRightHanded(a, ModelExporter.UnitScaleFactor);

            Assert.AreEqual(100, afbxPosition.Length());

            // Test rotation conversion.
            var q         = Quaternion.Euler(new Vector3(0, 90, 0));
            var fbxAngles = ModelExporter.ConvertQuaternionToXYZEuler(q);

            Assert.AreEqual(fbxAngles.X, 0);
            Assert.That(fbxAngles.Y, Is.InRange(-90.001, -89.999));
            Assert.AreEqual(fbxAngles.Z, 0);

            Assert.That(ModelExporter.DefaultMaterial);

            // Test non-static functions.
            using (var fbxManager = FbxManager.Create()) {
                var fbxScene = FbxScene.Create(fbxManager, "scene");
                var fbxNode  = FbxNode.Create(fbxScene, "node");
                var exporter = new ModelExporter();

                // Test ExportMaterial: it exports and it re-exports
                bool result = exporter.ExportMaterial(ModelExporter.DefaultMaterial, fbxScene, fbxNode);
                Assert.IsTrue(result);
                var fbxMaterial = fbxNode.GetMaterial(0);
                Assert.That(fbxMaterial, Is.Not.Null);

                result = exporter.ExportMaterial(ModelExporter.DefaultMaterial, fbxScene, fbxNode);
                var fbxMaterial2 = fbxNode.GetMaterial(1);
                Assert.AreEqual(fbxMaterial, fbxMaterial2);

                // Test ExportTexture: it finds the same texture for the default-material (it doesn't create a new one)
                var fbxMaterialNew = FbxSurfaceLambert.Create(fbxScene, "lambert");
                exporter.ExportTexture(ModelExporter.DefaultMaterial, "_MainTex",
                                       fbxMaterialNew, FbxSurfaceLambert.sBump);
                Assert.AreEqual(
                    fbxMaterial.FindProperty(FbxSurfaceLambert.sDiffuse).GetSrcObject(),
                    fbxMaterialNew.FindProperty(FbxSurfaceLambert.sBump).GetSrcObject()
                    );

                // Test ExportMesh: make sure we exported a mesh with welded vertices.
                var cube     = GameObject.CreatePrimitive(PrimitiveType.Cube);
                var cubeNode = FbxNode.Create(fbxScene, "cube");
                exporter.ExportMesh(cube.GetComponent <MeshFilter>().sharedMesh, cubeNode);
                Assert.That(cubeNode.GetMesh(), Is.Not.Null);
                Assert.That(cubeNode.GetMesh().GetControlPointsCount(), Is.EqualTo(8));
            }

            // Test exporting a skinned-mesh. Make sure it doesn't leak (it did at one point)
            {
                var cube      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                var character = new GameObject();
                var smr       = character.AddComponent <SkinnedMeshRenderer>();
                smr.sharedMesh = cube.GetComponent <MeshFilter>().sharedMesh;
                var meshCount = Object.FindObjectsOfType <Mesh>().Length;
                ModelExporter.ExportObject(GetRandomFbxFilePath(), character);
                Assert.AreEqual(meshCount, Object.FindObjectsOfType <Mesh>().Length);
            }
        }
Exemplo n.º 12
0
            /// <summary>
            /// Import all from scene.
            /// Return the number of objects we imported.
            /// </summary>
            public int ImportAll(IEnumerable <UnityEngine.Object> unitySelectionSet)
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);

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

                    // Get the version number of the FBX files generated by the
                    // version of FBX SDK that you are using.
                    int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1;

                    FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision);

                    // Create the importer
                    var fbxImporter = FbxImporter.Create(fbxManager, "Importer");

                    // Initialize the importer.
                    int fileFormat = -1;

                    bool      status    = fbxImporter.Initialize(LastFilePath, fileFormat, fbxIOSettings);
                    FbxStatus fbxStatus = fbxImporter.GetStatus();

                    // Get the version number of the FBX file format.
                    int fileMajor = -1, fileMinor = -1, fileRevision = -1;
                    fbxImporter.GetFileVersion(out fileMajor, out fileMinor, out fileRevision);

                    // Check that initialization of the fbxImporter was successful
                    if (!status)
                    {
                        Debug.LogError(string.Format("failed to initialize FbxImporter, error returned {0}",
                                                     fbxStatus.GetErrorString()));

                        if (fbxStatus.GetCode() == FbxStatus.EStatusCode.eInvalidFileVersion)
                        {
                            Debug.LogError(string.Format("Invalid file version detected\nSDK version: {0}.{1}.{2}\nFile version: {3}.{4}.{5}",
                                                         sdkMajor, sdkMinor, sdkRevision,
                                                         fileMajor, fileMinor, fileRevision));
                        }

                        return(0);
                    }

                    MsgLine.Add("Import Scene Report");
                    MsgLine.Add(kBorderLine);

                    MsgLine.Add(kPadding + string.Format("FilePath: {0}", LastFilePath));
                    MsgLine.Add(kPadding + string.Format("SDK version: {0}.{1}.{2}",
                                                         sdkMajor, sdkMinor, sdkRevision));

                    if (!fbxImporter.IsFBX())
                    {
                        Debug.LogError(string.Format("file does not contain FBX data {0}", LastFilePath));
                        return(0);
                    }

                    MsgLine.Add(kPadding + string.Format("File version: {0}.{1}.{2}",
                                                         fileMajor, fileMinor, fileRevision));

                    MsgLine.Add(kBorderLine);
                    MsgLine.Add("Animation");
                    MsgLine.Add(kBorderLine);

                    int numAnimStack = fbxImporter.GetAnimStackCount();

                    MsgLine.Add(kPadding + string.Format("number of stacks: {0}", numAnimStack));
                    MsgLine.Add(kPadding + string.Format("active animation stack: \"{0}\"\n", fbxImporter.GetActiveAnimStackName()));

                    for (int i = 0; i < numAnimStack; i++)
                    {
#if UNI_18972
                        FbxTakeInfo fbxTakeInfo = fbxImporter.GetTakeInfo(i);
                        MsgLine.Add(kPadding + string.Format("Animation Stack ({0})", i));
                        MsgLine.Add(kPadding + string.Format("name: \"{0}\"", fbxTakeInfo.mName) + string.kNewLine);
                        MsgLine.Add(kPadding + string.Format("description: \"{0}\"", fbxTakeInfo.mDescription));
                        MsgLine.Add(kPadding + string.Format("import name: \"{0}\"", fbxTakeInfo.mImportName));
                        MsgLine.Add(kPadding + string.Format("import state: \"{0}\"", fbxTakeInfo.mSelect));
#endif
                    }

                    // Import options. Determine what kind of data is to be imported.
                    // The default is true, but here we set the options explictly.
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_MATERIAL, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_TEXTURE, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_ANIMATION, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_EXTRACT_EMBEDDED_DATA, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_GLOBAL_SETTINGS, true);

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

                    // Import the scene to the file.
                    status    = fbxImporter.Import(fbxScene);
                    fbxStatus = fbxImporter.GetStatus();

                    if (status == false)
                    {
                        if (fbxStatus.GetCode() == FbxStatus.EStatusCode.ePasswordError)
                        {
                            Debug.LogError(string.Format("failed to import, file is password protected ({0})", fbxStatus.GetErrorString()));
                        }
                        else
                        {
                            Debug.LogError(string.Format("failed to import file ({0})", fbxStatus.GetErrorString()));
                        }
                    }
                    else
                    {
                        // import data into scene
                        ProcessScene(fbxScene, unitySelectionSet);
                    }

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

                    return(status == true ? NumNodes : 0);
                }
            }
        // Start is called before the first frame update
        void Start()
        {
#if FBXSDK_RUNTIME
            // Build the fbx scene file path
            // (player/player_data/emptySceneFromRuntime.fbx)
            string fbxFilePath = Application.dataPath;
            fbxFilePath = Path.Combine(fbxFilePath, "emptySceneFromRuntimeBuild.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();
            }
#endif

            // Immediately close the standalone application after
            // exporting the FBX
            Application.Quit();
        }
Exemplo n.º 14
0
        //static bool ContainsMeshesRecursive( Node node )
        //{
        //	if( node.HasMeshes )
        //		return true;
        //	foreach( var child in node.Children )
        //	{
        //		if( ContainsMeshesRecursive( child ) )
        //			return true;
        //	}
        //	return false;
        //}

        public static void DoImport(Settings settings, out string error)
        {
            error = "(NO ERROR MESSAGE)";
            LoadNativeLibrary();

            FbxManager    manager  = null;
            FbxIOSettings setting  = null;
            FbxImporter   importer = null;
            FbxScene      scene    = null;

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

                importer = FbxImporter.Create(manager, "");
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(settings.virtualFileName);
                //VirtualFileStream stream = null;
                //ToDo : FromStream
                bool status;
                if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName))
                {
                    status = importer.Initialize(realFileName, -1, setting);
                }
                else
                {
                    error = "File is not exists.";
                    return;
                    //throw new NotImplementedException();
                    //ToDo : ....
                    //stream = VirtualFile.Open( settings.virtualFileName );
                    //FbxStream fbxStream = null;
                    //SWIGTYPE_p_void streamData = null;

                    //status = impoter.Initialize( fbxStream, streamData, -1, setting );
                }

                if (!status)
                {
                    return;
                }

                scene  = FbxScene.Create(manager, "scene1");
                status = importer.Import(scene);
                if (!status)
                {
                    return;
                }

                error = "";
                var importContext = new ImportContext();
                importContext.manager       = manager;
                importContext.scene         = scene;
                importContext.settings      = settings;
                importContext.directoryName = Path.GetDirectoryName(settings.virtualFileName);

                ImportScene(importContext);

                ////create meshes (Scene mode)
                //if( settings.component.Mode.Value == Component_Import3D.ModeEnum.Scene /*&& scene.HasMeshes && scene.MeshCount != 0 */)
                //{
                //	importContext.meshesGroup = settings.component.GetComponentByName( "Meshes" ) as Component_Mesh;
                //	if( importContext.meshesGroup == null )
                //	{
                //		importContext.meshesGroup = settings.component.CreateComponent<Component>( -1, false );
                //		importContext.meshesGroup.Name = "Meshes";
                //	}
                //	else
                //		importContext.meshesGroup.Enabled = false;
                //}

                ////enable groups
                //if( importContext.meshesGroup != null )
                //	importContext.meshesGroup.Enabled = true;
                //if( importContext.sceneObjectsGroup != null )
                //	importContext.sceneObjectsGroup.Enabled = true;

                //stream?.Dispose();
            }
            finally
            {
                //Особенности удаления.
                //Создается через функцию: impoter = FbxImporter.Create(manager, "");
                //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает.
                //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor
                //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy.

                try { scene?.Destroy(); } catch { }
                try { importer?.Destroy(); } catch { }
                try { setting?.Destroy(); } catch { }
                try { manager?.Destroy(); } catch { }
            }
        }
Exemplo n.º 15
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);
            }
Exemplo n.º 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);

                    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);
            }
 public virtual void Init()
 {
     m_fbxManager   = FbxManager.Create();
     LayerContainer = FbxLayerContainer.Create(m_fbxManager, "layer container");
 }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
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));
    }
Exemplo n.º 20
0
        // tests that should work for any subclass of FbxProperty
        public static void GenericPropertyTests <T>(T property, FbxObject parent, string propertyName, FbxDataType dataType) where T : FbxProperty
        {
            Assert.IsTrue(property.IsValid());
            Assert.AreEqual(dataType, property.GetPropertyDataType());
            Assert.AreEqual(propertyName, property.GetName());
            Assert.AreEqual(propertyName, property.ToString());
            Assert.AreEqual(propertyName, property.GetHierarchicalName());
            Assert.AreEqual(propertyName, property.GetLabel(true));
            property.SetLabel("label");
            Assert.AreEqual("label", property.GetLabel());
            Assert.AreEqual(parent, property.GetFbxObject());
            Assert.AreEqual(property.GetFbxObject(), parent); // test it both ways just in case equals is busted

            // test the flags using the animatable flag
            property.ModifyFlag(FbxPropertyFlags.EFlags.eAnimatable, true);
            Assert.IsTrue(property.GetFlag(FbxPropertyFlags.EFlags.eAnimatable));
            Assert.AreNotEqual(0, property.GetFlags() | FbxPropertyFlags.EFlags.eAnimatable);
            property.SetFlagInheritType(FbxPropertyFlags.EFlags.eAnimatable, FbxPropertyFlags.EInheritType.eInherit);
            Assert.AreEqual(FbxPropertyFlags.EInheritType.eInherit, property.GetFlagInheritType(FbxPropertyFlags.EFlags.eAnimatable));

            // not clear when this ever returns true: whether we set animatable
            // to true or false it says it has the default value.
            Assert.IsFalse(property.ModifiedFlag(FbxPropertyFlags.EFlags.eAnimatable));

            // Test setting the value with the generic float accessor.
            // The value may not round-trip: a bool property will go to 1.0
            property.Set(5.0f);
            TestGetter(property.GetFloat());
            TestGetter(property.GetBool());
            TestGetter(property.GetDouble());
            TestGetter(property.GetFbxColor());
            TestGetter(property.GetFbxDouble3());
            TestGetter(property.GetString());
            TestGetter(property.GetInt());

            // Test setting the value with color accessor
            property.Set(new FbxColor());

            // test GetCurve(). Just make sure it doesn't crash. We can't
            // generically test actually getting curves, because the details
            // (channel names etc) depend on the type of property and its
            // flags.
            FbxAnimLayer layer = FbxAnimLayer.Create(parent, "layer");

            property.GetCurve(layer);
            property.GetCurve(layer, true);
            property.GetCurve(layer, "asdf");
            property.GetCurve(layer, "asdf", true);
            property.GetCurve(layer, "asdf", "hjkl", true);
            Assert.That(() => { property.GetCurve(null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

            // test GetCurveNode() (make sure it doesn't crash)
            FbxAnimCurveNode curveNode = property.GetCurveNode();

            Assert.IsNull(curveNode);  // didn't create one so should be null

            curveNode = property.GetCurveNode(true);
            // TODO: figure out why the curve node doesn't get created
            //Assert.IsNotNull (curveNode);

            property.GetCurveNode(FbxAnimStack.Create(parent, "anim stack"));
            property.GetCurveNode(FbxAnimStack.Create(parent, "anim stack"), true);
            property.GetCurveNode(FbxAnimLayer.Create(parent, "anim layer"));
            property.GetCurveNode(FbxAnimLayer.Create(parent, "anim layer"), true);

            Assert.That(() => { property.GetCurveNode((FbxAnimStack)null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());
            Assert.That(() => { property.GetCurveNode((FbxAnimLayer)null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

            using (FbxManager manager = FbxManager.Create()) {
                // Test ConnectSrcObject functions
                FbxObject obj    = FbxObject.Create(manager, "obj");
                bool      result = property.ConnectSrcObject(obj);
                Assert.IsTrue(result);
                Assert.IsTrue(property.IsConnectedSrcObject(obj));
                Assert.AreEqual(1, property.GetSrcObjectCount());
                Assert.AreEqual(obj, property.GetSrcObject());
                Assert.AreEqual(obj, property.GetSrcObject(0));
                Assert.AreEqual(obj, property.FindSrcObject("obj"));
                Assert.IsNull(property.FindSrcObject("obj", 1));
                Assert.That(() => { property.FindSrcObject(null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

                Assert.IsTrue(property.DisconnectSrcObject(obj));
                Assert.IsFalse(property.IsConnectedSrcObject(obj));

                Assert.That(() => { property.ConnectSrcObject(null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

                Assert.IsTrue(property.ConnectSrcObject(obj, FbxConnection.EType.eData));

                Assert.IsTrue(property.DisconnectAllSrcObject());

                // Test ConnectDstObject functions
                result = property.ConnectDstObject(obj);
                Assert.IsTrue(result);
                Assert.IsTrue(property.IsConnectedDstObject(obj));
                Assert.AreEqual(1, property.GetDstObjectCount());
                Assert.AreEqual(obj, property.GetDstObject());
                Assert.AreEqual(obj, property.GetDstObject(0));
                Assert.AreEqual(obj, property.FindDstObject("obj"));
                Assert.IsNull(property.FindDstObject("obj", 1));
                Assert.That(() => { property.FindDstObject(null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

                Assert.IsTrue(property.DisconnectDstObject(obj));
                Assert.IsFalse(property.IsConnectedDstObject(obj));

                Assert.That(() => { property.ConnectDstObject(null); }, Throws.Exception.TypeOf <System.ArgumentNullException>());

                Assert.IsTrue(property.ConnectDstObject(obj, FbxConnection.EType.eData));

                Assert.IsTrue(property.DisconnectAllDstObject());
            }

            // verify this in the future: will dispose destroy?
            property.Dispose();
        }
        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");
        }
Exemplo n.º 22
0
        public void BasicTests()
        {
            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<FbxBool> example: VisibilityInheritance on a node
                var node = FbxNode.Create(manager, "node");
                GenericPropertyTests <FbxPropertyBool> (node.VisibilityInheritance, node, "Visibility Inheritance", Globals.FbxVisibilityInheritanceDT);

                var property = node.VisibilityInheritance;
                property.Set(false);
                Assert.AreEqual(false, property.Get());
                Assert.AreEqual(false, property.EvaluateValue());
                Assert.AreEqual(false, property.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(false, property.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<FbxDouble> example: several of them on a Lambert shader
                var obj = FbxSurfaceLambert.Create(manager, "lambert");
                GenericPropertyTests <FbxPropertyDouble> (obj.EmissiveFactor, obj, "EmissiveFactor", Globals.FbxDoubleDT);

                var property = obj.EmissiveFactor;
                property.Set(5.0); // bool Set<float> is not accessible here!
                Assert.AreEqual(5.0, property.Get());
                Assert.AreEqual(5.0, property.EvaluateValue());
                Assert.AreEqual(5.0, property.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(5.0, property.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<Double3> example: the LclTranslation on a node
                var node = FbxNode.Create(manager, "node");
                GenericPropertyTests <FbxPropertyDouble3> (node.LclTranslation, node, "Lcl Translation", Globals.FbxLocalTranslationDT);

                var property = node.LclTranslation;
                property.Set(new FbxDouble3(1, 2, 3));
                Assert.AreEqual(new FbxDouble3(1, 2, 3), property.Get());
                Assert.AreEqual(new FbxDouble3(1, 2, 3), property.EvaluateValue());
                Assert.AreEqual(new FbxDouble3(1, 2, 3), property.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(new FbxDouble3(1, 2, 3), property.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<float> example: the LeftBarnDoor on a light
                var light = FbxLight.Create(manager, "light");
                GenericPropertyTests(light.LeftBarnDoor, light, "LeftBarnDoor", Globals.FbxFloatDT);

                var property = light.LeftBarnDoor;
                light.LeftBarnDoor.Set(5.0f);
                Assert.AreEqual(5.0f, light.LeftBarnDoor.Get());
                Assert.AreEqual(5.0f, property.EvaluateValue());
                Assert.AreEqual(5.0f, property.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(5.0f, property.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<int> example: the WorldUpType on an aim constraint
                var constraint = FbxConstraintAim.Create(manager, "constraint");
                GenericPropertyTests(constraint.WorldUpType, constraint, "WorldUpType", Globals.FbxEnumDT);

                var property = constraint.WorldUpType;
                int value    = (int)FbxConstraintAim.EWorldUp.eAimAtObjectUp;
                constraint.WorldUpType.Set(value);
                Assert.That(constraint.WorldUpType.Get(), Is.EqualTo(value));
                Assert.That(property.EvaluateValue(), Is.EqualTo(value));
                Assert.That(property.EvaluateValue(FbxTime.FromSecondDouble(5)), Is.EqualTo(value));
                Assert.That(property.EvaluateValue(FbxTime.FromSecondDouble(5), true), Is.EqualTo(value));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<FbxString> example: the description of a shader implementation
                var impl = FbxImplementation.Create(manager, "name");
                GenericPropertyTests <FbxPropertyString> (impl.RenderAPI, impl, "RenderAPI", Globals.FbxStringDT);

                var property = impl.RenderAPI;
                property.Set("a value");
                Assert.AreEqual("a value", property.Get());

                // animated strings come out as empty-string
                Assert.AreEqual("", property.EvaluateValue());
                Assert.AreEqual("", property.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual("", property.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT for FbxTexture enums EBlendMode and EWrapMode
                var tex = FbxTexture.Create(manager, "tex");

                FbxPropertyTest.GenericPropertyTests(tex.CurrentTextureBlendMode, tex, "CurrentTextureBlendMode", Globals.FbxEnumDT);
                tex.CurrentTextureBlendMode.Set(FbxTexture.EBlendMode.eAdditive);
                Assert.AreEqual(FbxTexture.EBlendMode.eAdditive, tex.CurrentTextureBlendMode.Get());
                Assert.AreEqual(FbxTexture.EBlendMode.eAdditive, tex.CurrentTextureBlendMode.EvaluateValue());
                Assert.AreEqual(FbxTexture.EBlendMode.eAdditive, tex.CurrentTextureBlendMode.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxTexture.EBlendMode.eAdditive, tex.CurrentTextureBlendMode.EvaluateValue(FbxTime.FromSecondDouble(5), true));

                FbxPropertyTest.GenericPropertyTests(tex.WrapModeU, tex, "WrapModeU", Globals.FbxEnumDT);
                tex.WrapModeU.Set(FbxTexture.EWrapMode.eClamp);
                Assert.AreEqual(FbxTexture.EWrapMode.eClamp, tex.WrapModeU.Get());
                Assert.AreEqual(FbxTexture.EWrapMode.eClamp, tex.WrapModeU.EvaluateValue());
                Assert.AreEqual(FbxTexture.EWrapMode.eClamp, tex.WrapModeU.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxTexture.EWrapMode.eClamp, tex.WrapModeU.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<FbxNull.ELook>
                var null1 = FbxNull.Create(manager, "null1");

                FbxPropertyTest.GenericPropertyTests(null1.Look, null1, "Look", Globals.FbxEnumDT);
                null1.Look.Set(FbxNull.ELook.eCross);
                Assert.AreEqual(FbxNull.ELook.eCross, null1.Look.Get());
                Assert.AreEqual(FbxNull.ELook.eCross, null1.Look.EvaluateValue());
                Assert.AreEqual(FbxNull.ELook.eCross, null1.Look.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxNull.ELook.eCross, null1.Look.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<FbxMarker.ELook>
                var marker1 = FbxMarker.Create(manager, "marker1");

                FbxPropertyTest.GenericPropertyTests(marker1.Look, marker1, "Look", Globals.FbxEnumDT);
                marker1.Look.Set(FbxMarker.ELook.eCapsule);
                Assert.AreEqual(FbxMarker.ELook.eCapsule, marker1.Look.Get());
                Assert.AreEqual(FbxMarker.ELook.eCapsule, marker1.Look.EvaluateValue());
                Assert.AreEqual(FbxMarker.ELook.eCapsule, marker1.Look.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxMarker.ELook.eCapsule, marker1.Look.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT for FbxCamera enum EProjectionType
                var camera = FbxCamera.Create(manager, "camera");

                FbxPropertyTest.GenericPropertyTests(camera.ProjectionType, camera, "CameraProjectionType", Globals.FbxEnumDT);
                camera.ProjectionType.Set(FbxCamera.EProjectionType.ePerspective);
                Assert.AreEqual(FbxCamera.EProjectionType.ePerspective, camera.ProjectionType.Get());
                Assert.AreEqual(FbxCamera.EProjectionType.ePerspective, camera.ProjectionType.EvaluateValue());
                Assert.AreEqual(FbxCamera.EProjectionType.ePerspective, camera.ProjectionType.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxCamera.EProjectionType.ePerspective, camera.ProjectionType.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT for FbxCamera enum EGateFit
                var camera = FbxCamera.Create(manager, "camera");

                FbxPropertyTest.GenericPropertyTests(camera.GateFit, camera, "GateFit", Globals.FbxEnumDT);
                camera.GateFit.Set(FbxCamera.EGateFit.eFitHorizontal);
                Assert.AreEqual(FbxCamera.EGateFit.eFitHorizontal, camera.GateFit.Get());
                Assert.AreEqual(FbxCamera.EGateFit.eFitHorizontal, camera.GateFit.EvaluateValue());
                Assert.AreEqual(FbxCamera.EGateFit.eFitHorizontal, camera.GateFit.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxCamera.EGateFit.eFitHorizontal, camera.GateFit.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT<EInheritType>
                var node = FbxNode.Create(manager, "node");

                FbxPropertyTest.GenericPropertyTests(node.InheritType, node, "InheritType", Globals.FbxEnumDT);
                node.InheritType.Set(FbxTransform.EInheritType.eInheritRSrs);
                Assert.AreEqual(FbxTransform.EInheritType.eInheritRSrs, node.InheritType.Get());
                Assert.AreEqual(FbxTransform.EInheritType.eInheritRSrs, node.InheritType.EvaluateValue());
                Assert.AreEqual(FbxTransform.EInheritType.eInheritRSrs, node.InheritType.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxTransform.EInheritType.eInheritRSrs, node.InheritType.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // FbxPropertyT for FbxLight enums
                var light = FbxLight.Create(manager, "light");

                FbxPropertyTest.GenericPropertyTests(light.LightType, light, "LightType", Globals.FbxEnumDT);
                light.LightType.Set(FbxLight.EType.eSpot);
                Assert.AreEqual(FbxLight.EType.eSpot, light.LightType.Get());
                Assert.AreEqual(FbxLight.EType.eSpot, light.LightType.EvaluateValue());
                Assert.AreEqual(FbxLight.EType.eSpot, light.LightType.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxLight.EType.eSpot, light.LightType.EvaluateValue(FbxTime.FromSecondDouble(5), true));

                FbxPropertyTest.GenericPropertyTests(light.AreaLightShape, light, "AreaLightShape", Globals.FbxEnumDT);
                light.AreaLightShape.Set(FbxLight.EAreaLightShape.eSphere);
                Assert.AreEqual(FbxLight.EAreaLightShape.eSphere, light.AreaLightShape.Get());
                Assert.AreEqual(FbxLight.EAreaLightShape.eSphere, light.AreaLightShape.EvaluateValue());
                Assert.AreEqual(FbxLight.EAreaLightShape.eSphere, light.AreaLightShape.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxLight.EAreaLightShape.eSphere, light.AreaLightShape.EvaluateValue(FbxTime.FromSecondDouble(5), true));

                FbxPropertyTest.GenericPropertyTests(light.DecayType, light, "DecayType", Globals.FbxEnumDT);
                light.DecayType.Set(FbxLight.EDecayType.eCubic);
                Assert.AreEqual(FbxLight.EDecayType.eCubic, light.DecayType.Get());
                Assert.AreEqual(FbxLight.EDecayType.eCubic, light.DecayType.EvaluateValue());
                Assert.AreEqual(FbxLight.EDecayType.eCubic, light.DecayType.EvaluateValue(FbxTime.FromSecondDouble(5)));
                Assert.AreEqual(FbxLight.EDecayType.eCubic, light.DecayType.EvaluateValue(FbxTime.FromSecondDouble(5), true));
            }

            using (var manager = FbxManager.Create()) {
                // Test all the create and destroy operations
                FbxProperty root, child;
                var         obj = FbxObject.Create(manager, "obj");

                Assert.IsNotNull(FbxProperty.Create(obj, Globals.FbxStringDT, "a"));
                Assert.IsNotNull(FbxProperty.Create(obj, Globals.FbxStringDT, "b", "label"));
                Assert.IsNotNull(FbxProperty.Create(obj, Globals.FbxStringDT, "c", "label", false));
                bool didFind;
                Assert.IsNotNull(FbxProperty.Create(obj, Globals.FbxStringDT, "c", "label", true, out didFind));
                Assert.IsTrue(didFind);

                root = FbxProperty.Create(obj, Globals.FbxCompoundDT, "root");

                child = FbxProperty.Create(root, Globals.FbxStringDT, "a");
                Assert.IsNotNull(child);
                Assert.IsNotNull(FbxProperty.Create(root, Globals.FbxStringDT, "b", "label"));
                Assert.IsNotNull(FbxProperty.Create(root, Globals.FbxStringDT, "c", "label", false));
                Assert.IsNotNull(FbxProperty.Create(root, Globals.FbxStringDT, "c", "label", true, out didFind));
                Assert.IsTrue(didFind);

                child.Destroy();

                root.DestroyChildren();
                Assert.IsNotNull(FbxProperty.Create(root, Globals.FbxStringDT, "c", "label", true, out didFind));
                Assert.IsFalse(didFind);

                root.DestroyRecursively();
            }
        }
Exemplo n.º 23
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);
                }
            }
Exemplo n.º 24
0
            /// <summary>
            /// Import all from scene.
            /// Return the number of objects we imported.
            /// </summary>
            public int ImportAll()
            {
                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT);

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

                    // Get the version number of the FBX files generated by the
                    // version of FBX SDK that you are using.
                    int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1;
                    FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision);

                    // Create the importer
                    var fbxImporter = FbxImporter.Create(fbxManager, "Importer");

                    // Initialize the importer.
                    int fileFormat = -1;

                    bool      status    = fbxImporter.Initialize(LastFilePath, fileFormat, fbxIOSettings);
                    FbxStatus fbxStatus = fbxImporter.GetStatus();

                    // Get the version number of the FBX file format.
                    int fileMajor = -1, fileMinor = -1, fileRevision = -1;
                    fbxImporter.GetFileVersion(out fileMajor, out fileMinor, out fileRevision);

                    // Check that initialization of the fbxImporter was successful
                    if (!status)
                    {
                        Debug.LogError(string.Format("failed to initialize FbxImporter, error returned {0}",
                                                     fbxStatus.GetErrorString()));

                        if (fbxStatus.GetCode() == FbxStatus.EStatusCode.eInvalidFileVersion)
                        {
                            Debug.LogError(string.Format("Invalid file version detected\nSDK version: {0}.{1}.{2}\nFile version: {3}.{4}.{5}",
                                                         sdkMajor, sdkMinor, sdkRevision,
                                                         fileMajor, fileMinor, fileRevision));
                        }

                        return(0);
                    }

                    // Import options. Determine what kind of data is to be imported.
                    // The default is true, but here we set the options explictly.
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_MATERIAL, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_TEXTURE, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_ANIMATION, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_EXTRACT_EMBEDDED_DATA, false);
                    fbxIOSettings.SetBoolProp(Globals.IMP_FBX_GLOBAL_SETTINGS, true);

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

                    // Import the scene to the file.
                    status = fbxImporter.Import(fbxScene);

                    if (status == false)
                    {
                        Debug.LogError(string.Format("failed to import file ({0})",
                                                     fbxImporter.GetStatus().GetErrorString()));
                    }
                    else
                    {
                        // import data into scene
                        ProcessScene(fbxScene);
                    }

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

                    return(status == true ? NumNodes : 0);
                }
            }
Exemplo n.º 25
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);
                }
            }
Exemplo n.º 26
0
 public virtual void Init()
 {
     Manager = FbxManager.Create();
 }
Exemplo n.º 27
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);
                }
            }