Esempio n. 1
0
        public void ExportModel()
        {
            using (System.Windows.Forms.SaveFileDialog a = new System.Windows.Forms.SaveFileDialog
            {
                DefaultExt = "dae",
                Filter = "SAModel Files|*.sa1mdl|Collada|*.dae|Wavefront|*.obj"
            })
            {
                if (a.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string ftype = "collada";
                    switch (System.IO.Path.GetExtension(a.FileName).ToLowerInvariant())
                    {
                    case ".sa1mdl":
                        ModelFile.CreateFile(a.FileName, COL.Model, null, null, null, null, COL.Model.GetModelFormat());
                        return;

                    case ".fbx":
                        ftype = "fbx";
                        break;

                    case ".obj":
                        ftype = "obj";
                        break;
                    }
                    Assimp.AssimpContext context = new Assimp.AssimpContext();
                    Assimp.Scene         scene   = new Assimp.Scene();
                    scene.Materials.Add(new Assimp.Material());
                    Assimp.Node n = new Assimp.Node();
                    n.Name         = "RootNode";
                    scene.RootNode = n;
                    string        rootPath     = System.IO.Path.GetDirectoryName(a.FileName);
                    List <string> texturePaths = new List <string>();
                    int           numSteps     = 0;
                    if (LevelData.TextureBitmaps != null && LevelData.TextureBitmaps.Count > 0)
                    {
                        numSteps = LevelData.TextureBitmaps[LevelData.leveltexs].Length;
                    }
                    for (int i = 0; i < numSteps; i++)
                    {
                        BMPInfo bmp = LevelData.TextureBitmaps[LevelData.leveltexs][i];
                        texturePaths.Add(System.IO.Path.Combine(rootPath, bmp.Name + ".png"));
                        bmp.Image.Save(System.IO.Path.Combine(rootPath, bmp.Name + ".png"));
                    }
                    SAEditorCommon.Import.AssimpStuff.AssimpExport(COL.Model, scene, Matrix.Identity, texturePaths.Count > 0 ? texturePaths.ToArray() : null, scene.RootNode);
                    context.ExportFile(scene, a.FileName, ftype, Assimp.PostProcessSteps.ValidateDataStructure | Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.FlipUVs);                    //
                }
            }
        }
Esempio n. 2
0
        private void ExportObj()
        {
            SaveFileDialog a = new SaveFileDialog
            {
                DefaultExt = "obj",
                Filter     = "OBJ Files|*.obj"
            };

            if (a.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter objstream = new StreamWriter(a.FileName, false))
                    using (StreamWriter mtlstream = new StreamWriter(Path.ChangeExtension(a.FileName, "mtl"), false))
                    {
                        int stepCount = LevelData.TextureBitmaps[LevelData.leveltexs].Length + LevelData.geo.COL.Count;
                        if (LevelData.geo.Anim != null)
                        {
                            stepCount += LevelData.geo.Anim.Count;
                        }

                        List <NJS_MATERIAL> materials = new List <NJS_MATERIAL>();

                        ProgressDialog progress = new ProgressDialog("Exporting stage", stepCount, true, false);
                        progress.Show(this);
                        progress.SetTaskAndStep("Exporting...");

                        int totalVerts = 0;
                        int totalNorms = 0;
                        int totalUVs   = 0;

                        bool errorFlag = false;

                        for (int i = 0; i < LevelData.geo.COL.Count; i++)
                        {
                            Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.COL[i].Model, ref materials, new MatrixStack(),
                                                                ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);

                            progress.Step = String.Format("Mesh {0}/{1}", i + 1, LevelData.geo.COL.Count);
                            progress.StepProgress();
                            Application.DoEvents();
                        }
                        if (LevelData.geo.Anim != null)
                        {
                            for (int i = 0; i < LevelData.geo.Anim.Count; i++)
                            {
                                Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.Anim[i].Model, ref materials, new MatrixStack(),
                                                                    ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);

                                progress.Step = String.Format("Animation {0}/{1}", i + 1, LevelData.geo.Anim.Count);
                                progress.StepProgress();
                                Application.DoEvents();
                            }
                        }

                        if (errorFlag)
                        {
                            MessageBox.Show("Error(s) encountered during export. Inspect the output file for more details.", "Failure",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        #region Material Exporting
                        string materialPrefix = LevelData.leveltexs;

                        objstream.WriteLine("mtllib " + Path.GetFileNameWithoutExtension(a.FileName) + ".mtl");

                        for (int i = 0; i < materials.Count; i++)
                        {
                            NJS_MATERIAL material = materials[i];
                            mtlstream.WriteLine("newmtl material_{0}", i);
                            mtlstream.WriteLine("Ka 1 1 1");
                            mtlstream.WriteLine(string.Format("Kd {0} {1} {2}",
                                                              material.DiffuseColor.R / 255,
                                                              material.DiffuseColor.G / 255,
                                                              material.DiffuseColor.B / 255));

                            mtlstream.WriteLine(string.Format("Ks {0} {1} {2}",
                                                              material.SpecularColor.R / 255,
                                                              material.SpecularColor.G / 255,
                                                              material.SpecularColor.B / 255));
                            mtlstream.WriteLine("illum 1");

                            if (!string.IsNullOrEmpty(LevelData.leveltexs) && material.UseTexture)
                            {
                                mtlstream.WriteLine("Map_Kd " + LevelData.TextureBitmaps[LevelData.leveltexs][material.TextureID].Name + ".png");

                                // save texture
                                string  mypath = Path.GetDirectoryName(a.FileName);
                                BMPInfo item   = LevelData.TextureBitmaps[LevelData.leveltexs][material.TextureID];
                                item.Image.Save(Path.Combine(mypath, item.Name + ".png"));
                            }

                            //progress.Step = String.Format("Texture {0}/{1}", material.TextureID + 1, LevelData.TextureBitmaps[LevelData.leveltexs].Length);
                            //progress.StepProgress();
                            Application.DoEvents();
                        }
                        #endregion

                        progress.SetTaskAndStep("Export complete!");
                    }
            }
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = @"C:\SONICADVENTUREDX\Projects\ECPort";

            List <BMPInfo> textures  = new List <BMPInfo>(TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH01.PVM"));
            LandTable      landTable = LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 1\LandTable.sa1lvl");

            texmap = new Dictionary <int, int>();
            BMPInfo[] newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH03.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }
            foreach (COL col in LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 3\LandTable.sa1lvl").COL)
            {
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                landTable.COL.Add(col);
            }
            texmap  = new Dictionary <int, int>();
            newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH02.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }
            foreach (COL col in LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 2\LandTable.sa1lvl").COL)
            {
                col.Bounds.Center.Z  -= 2000;
                col.Model.Position.Z -= 2000;
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                landTable.COL.Add(col);
            }

            texmap  = new Dictionary <int, int>();
            newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\OBJ_BEACH.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }

            PAKFile     pak       = new PAKFile();
            List <byte> inf       = new List <byte>();
            string      filenoext = "beach01";
            string      longdir   = "..\\..\\..\\sonic2\\resource\\gd_pc\\prs\\" + filenoext;

            using (System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel())
                using (Direct3D d3d = new Direct3D())
                    using (Device dev = new Device(d3d, 0, DeviceType.Hardware, panel.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(640, 480)))
                    {
                        for (int i = 0; i < textures.Count; i++)
                        {
                            using (Texture tex = textures[i].Image.ToTexture(dev))
                                using (DataStream str = Surface.ToStream(tex.GetSurfaceLevel(0), ImageFileFormat.Dds))
                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        str.CopyTo(ms);
                                        pak.Files.Add(new PAKFile.File(filenoext + '\\' + Path.ChangeExtension(textures[i].Name, ".dds"), longdir + '\\' + Path.ChangeExtension(textures[i].Name, ".dds"), ms.ToArray()));
                                    }
                            int infsz = inf.Count;
                            inf.AddRange(Encoding.ASCII.GetBytes(Path.ChangeExtension(textures[i].Name, null)));
                            inf.AddRange(new byte[0x1C - (inf.Count - infsz)]);
                            inf.AddRange(BitConverter.GetBytes(i + 200));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(textures[i].Image.Width));
                            inf.AddRange(BitConverter.GetBytes(textures[i].Image.Height));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0x80000000));
                        }
                    }
            pak.Files.Insert(0, new PAKFile.File(filenoext + '\\' + filenoext + ".inf", longdir + '\\' + filenoext + ".inf", inf.ToArray()));
            pak.Save(@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\gd_PC\PRS\beach01.pak");

            List <COL> newcollist = new List <COL>();
            Dictionary <string, Attach> visitedAttaches = new Dictionary <string, Attach>();

            foreach (COL col in landTable.COL.Where((col) => col.Model != null && col.Model.Attach != null))
            {
                ConvertCOL(newcollist, visitedAttaches, col);
            }
            landTable.COL = newcollist;

            Console.WriteLine("Loading Object Definitions:");
            Console.WriteLine("Parsing...");

            LevelData.ObjDefs = new List <ObjectDefinition>();
            Dictionary <string, ObjectData> objdefini =
                IniSerializer.Deserialize <Dictionary <string, ObjectData> >("objdefs.ini");

            List <ObjectData> objectErrors = new List <ObjectData>();

            ObjectListEntry[] objlstini = ObjectList.Load(@"Levels\Emerald Coast\Object List.ini", false);
            Directory.CreateDirectory("dllcache").Attributes |= FileAttributes.Hidden;

            List <KeyValuePair <string, string> > compileErrors = new List <KeyValuePair <string, string> >();

            for (int ID = 0; ID < objlstini.Length; ID++)
            {
                string codeaddr = objlstini[ID].CodeString;

                if (!objdefini.ContainsKey(codeaddr))
                {
                    codeaddr = "0";
                }

                ObjectData       defgroup = objdefini[codeaddr];
                ObjectDefinition def;

                if (!string.IsNullOrEmpty(defgroup.CodeFile))
                {
                    Console.WriteLine("Compiling: " + defgroup.CodeFile);


                    def = CompileObjectDefinition(defgroup, out bool errorOccured, out string errorText);

                    if (errorOccured)
                    {
                        KeyValuePair <string, string> errorValue = new KeyValuePair <string, string>(
                            defgroup.CodeFile, errorText);

                        compileErrors.Add(errorValue);
                    }
                }
                else
                {
                    def = new DefaultObjectDefinition();
                }

                LevelData.ObjDefs.Add(def);

                // The only reason .Model is checked for null is for objects that don't yet have any
                // models defined for them. It would be annoying seeing that error all the time!
                if (string.IsNullOrEmpty(defgroup.CodeFile) && !string.IsNullOrEmpty(defgroup.Model))
                {
                    Console.WriteLine("Loading: " + defgroup.Model);
                    // Otherwise, if the model file doesn't exist and/or no texture file is defined,
                    // load the "default object" instead ("?").
                    if (!File.Exists(defgroup.Model))
                    {
                        ObjectData error = new ObjectData {
                            Name = defgroup.Name, Model = defgroup.Model, Texture = defgroup.Texture
                        };
                        objectErrors.Add(error);
                        defgroup.Model = null;
                    }
                }

                def.Init(defgroup, objlstini[ID].Name);
                def.SetInternalName(objlstini[ID].Name);
            }

            // Checks if there have been any errors added to the error list and does its thing
            // This thing is a mess. If anyone can think of a cleaner way to do this, be my guest.
            if (objectErrors.Count > 0)
            {
                int           count        = objectErrors.Count;
                List <string> errorStrings = new List <string> {
                    "The following objects failed to load:"
                };

                foreach (ObjectData o in objectErrors)
                {
                    bool texEmpty  = string.IsNullOrEmpty(o.Texture);
                    bool texExists = (!string.IsNullOrEmpty(o.Texture) && LevelData.Textures.ContainsKey(o.Texture));
                    errorStrings.Add("");
                    errorStrings.Add("Object:\t\t" + o.Name);
                    errorStrings.Add("\tModel:");
                    errorStrings.Add("\t\tName:\t" + o.Model);
                    errorStrings.Add("\t\tExists:\t" + File.Exists(o.Model));
                    errorStrings.Add("\tTexture:");
                    errorStrings.Add("\t\tName:\t" + ((texEmpty) ? "(N/A)" : o.Texture));
                    errorStrings.Add("\t\tExists:\t" + texExists);
                }

                // TODO: Proper logging. Who knows where this file may end up
                File.WriteAllLines("SADXLVL2.log", errorStrings.ToArray());
            }

            // Loading SET Layout
            Console.WriteLine("Loading SET items", "Initializing...");

            List <SETItem> setlist = new List <SETItem>();

            SonicRetro.SAModel.SAEditorCommon.UI.EditorItemSelection selection = new SonicRetro.SAModel.SAEditorCommon.UI.EditorItemSelection();
            if (LevelData.ObjDefs.Count > 0)
            {
                string setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0100S.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    setlist = SETItem.Load(setstr, selection);
                }
                setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0102B.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    setlist.AddRange(SETItem.Load(setstr, selection));
                }
                setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0101S.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    List <SETItem> newlist = SETItem.Load(setstr, selection);
                    foreach (SETItem item in newlist)
                    {
                        item.Position.Z -= 2000;
                    }
                    setlist.AddRange(newlist);
                }
            }

            MatrixStack         transform = new MatrixStack();
            List <SETItem>      add       = new List <SETItem>();
            List <SETItem>      del       = new List <SETItem>();
            List <PalmtreeData> trees     = new List <PalmtreeData>();

            foreach (SETItem item in setlist)
            {
                switch (item.ID)
                {
                case 0xD:                         // item box
                    item.ID      = 0xA;
                    item.Scale.X = itemboxmap[(int)item.Scale.X];
                    break;

                case 0x15:                         // ring group to rings
                    for (int i = 0; i < Math.Min(item.Scale.X + 1, 8); i++)
                    {
                        if (item.Scale.Z == 1)                                 // circle
                        {
                            double  v4 = i * 360.0;
                            Vector3 v7 = new Vector3(
                                ObjectHelper.NJSin((int)(v4 / item.Scale.X * 65536.0 * 0.002777777777777778)) * item.Scale.Y,
                                0,
                                ObjectHelper.NJCos((int)(v4 / item.Scale.X * 65536.0 * 0.002777777777777778)) * item.Scale.Y);
                            transform.Push();
                            transform.NJTranslate(item.Position);
                            transform.NJRotateObject(item.Rotation);
                            Vector3 pos = Vector3.TransformCoordinate(v7, transform.Top);
                            transform.Pop();
                            add.Add(new SETItem(0, selection)
                            {
                                Position = pos.ToVertex()
                            });
                        }
                        else                                 // line
                        {
                            transform.Push();
                            transform.NJTranslate(item.Position);
                            transform.NJRotateObject(item.Rotation);
                            double v5;
                            if (i % 2 == 1)
                            {
                                v5 = i * item.Scale.Y * -0.5;
                            }
                            else
                            {
                                v5 = Math.Ceiling(i * 0.5) * item.Scale.Y;
                            }
                            Vector3 pos = Vector3.TransformCoordinate(new Vector3(0, 0, (float)v5), transform.Top);
                            transform.Pop();
                            add.Add(new SETItem(0, selection)
                            {
                                Position = pos.ToVertex()
                            });
                        }
                    }
                    del.Add(item);
                    break;

                case 0x1A:                         // tikal -> omochao
                    item.ID          = 0x19;
                    item.Position.Y += 3;
                    break;

                case 0x1D:                         // kiki
                    item.ID       = 0x5B;
                    item.Rotation = new Rotation();
                    item.Scale    = new Vertex();
                    break;

                case 0x1F:                         // sweep ->beetle
                    item.ID       = 0x38;
                    item.Rotation = new Rotation();
                    item.Scale    = new Vertex(1, 0, 0);
                    break;

                case 0x28:                         // launch ramp
                    item.ID       = 6;
                    item.Scale.X /= 2.75f;
                    item.Scale.Z  = 0.799999952316284f;
                    break;

                case 0x4F:                         // updraft
                    item.ID      = 0x35;
                    item.Scale.X = Math.Max(Math.Min(item.Scale.X, 200), 10) / 2;
                    item.Scale.Y = Math.Max(Math.Min(item.Scale.Y, 200), 10) / 2;
                    item.Scale.Z = Math.Max(Math.Min(item.Scale.Z, 200), 10) / 2;
                    break;

                case 0x52:                         // item box air
                    item.ID      = 0xB;
                    item.Scale.X = itemboxmap[(int)item.Scale.X];
                    break;

                // palm trees
                case 32:
                case 33:
                case 34:
                case 35:
                    trees.Add(new PalmtreeData((byte)(item.ID - 32), item.Position, item.Rotation));
                    del.Add(item);
                    break;

                // nonsolid objects
                case 47:
                case 48:
                case 49:
                case 50:
                case 51:
                case 52:
                case 59:
                case 62:
                case 63:
                case 64:
                case 70:
                    ConvertSETItem(newcollist, item, false, setlist.IndexOf(item));
                    del.Add(item);
                    break;

                // solid objects
                case 36:
                case 37:
                case 39:
                case 41:
                case 42:
                case 43:
                case 44:
                case 45:
                case 46:
                case 54:
                case 58:
                case 66:
                case 71:
                case 72:
                case 73:
                case 74:
                    ConvertSETItem(newcollist, item, true, setlist.IndexOf(item));
                    del.Add(item);
                    break;

                case 81:                         // goal
                    item.ID          = 0xE;
                    item.Position.Y += 30;
                    break;

                default:
                    if (idmap.ContainsKey(item.ID))
                    {
                        item.ID = idmap[item.ID];
                    }
                    else
                    {
                        del.Add(item);
                    }
                    break;
                }
            }
            setlist.AddRange(add);
            foreach (SETItem item in del)
            {
                setlist.Remove(item);
            }
            setlist.Add(new SETItem(0x55, selection)
            {
                Position = new Vertex(6158.6f, -88f, 2384.97f), Scale = new Vertex(3, 0, 0)
            });
            {
                COL col = new COL()
                {
                    Model = new ModelFile(@"E:\Bridge Model.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Visible
                };
                col.Model.Position = new Vertex(2803, -1, 365);
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                ConvertCOL(newcollist, new Dictionary <string, Attach>(), col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\Bridge Model COL.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.Position = new Vertex(2803, -1, 365);
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment0.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment1.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment2.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment3.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
            }
            landTable.SaveToFile(@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\LandTable.sa2lvl", LandTableFormat.SA2);
            ByteConverter.BigEndian = true;
            SETItem.Save(setlist, @"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\gd_PC\set0013_s.bin");
            for (int i = 0; i < 4; i++)
            {
                ModelFile modelFile = new ModelFile($@"C:\SONICADVENTUREDX\Projects\Test\Objects\Levels\Emerald Coast\YASI{i}.sa1mdl");
                foreach (BasicAttach attach in modelFile.Model.GetObjects().Where(a => a.Attach != null).Select(a => a.Attach))
                {
                    foreach (NJS_MATERIAL mat in attach.Material)
                    {
                        mat.TextureID = texmap[mat.TextureID];
                    }
                }
                modelFile.SaveToFile($@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\YASI{i}.sa1mdl");
            }
            using (StreamWriter sw = File.CreateText(@"E:\Documents\Visual Studio 2017\Projects\LevelTest\LevelTest\pt.c"))
                sw.WriteLine(string.Join(",\r\n", trees));
        }
Esempio n. 4
0
        private void exportOBJToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog a = new SaveFileDialog
            {
                DefaultExt = "obj",
                Filter     = "OBJ Files|*.obj"
            };

            if (a.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter objstream = new StreamWriter(a.FileName, false))
                    using (StreamWriter mtlstream = new StreamWriter(Path.ChangeExtension(a.FileName, "mtl"), false))
                    {
                        #region Material Exporting
                        string materialPrefix = LevelData.leveltexs;

                        objstream.WriteLine("mtllib " + Path.GetFileNameWithoutExtension(a.FileName) + ".mtl");

                        // This is admittedly not an accurate representation of the materials used in the model - HOWEVER, it makes the materials more managable in MAX
                        // So we're doing it this way. In the future we should come back and add an option to do it this way or the original way.
                        for (int texIndx = 0; texIndx < LevelData.TextureBitmaps[LevelData.leveltexs].Length; texIndx++)
                        {
                            mtlstream.WriteLine(String.Format("newmtl {0}_material_{1}", materialPrefix, texIndx));
                            mtlstream.WriteLine("Ka 1 1 1");
                            mtlstream.WriteLine("Kd 1 1 1");
                            mtlstream.WriteLine("Ks 0 0 0");
                            mtlstream.WriteLine("illum 1");

                            if (!string.IsNullOrEmpty(LevelData.leveltexs))
                            {
                                mtlstream.WriteLine("Map_Kd " + LevelData.TextureBitmaps[LevelData.leveltexs][texIndx].Name + ".png");

                                // save texture
                                string  mypath = Path.GetDirectoryName(a.FileName);
                                BMPInfo item   = LevelData.TextureBitmaps[LevelData.leveltexs][texIndx];
                                item.Image.Save(Path.Combine(mypath, item.Name + ".png"));
                            }
                        }
                        #endregion

                        int totalVerts = 0;
                        int totalNorms = 0;
                        int totalUVs   = 0;

                        bool errorFlag = false;

                        for (int i = 0; i < LevelData.geo.COL.Count; i++)
                        {
                            Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.COL[i].Model, materialPrefix, new MatrixStack(), ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);
                        }
                        if (LevelData.geo.Anim != null)
                        {
                            for (int i = 0; i < LevelData.geo.Anim.Count; i++)
                            {
                                Direct3D.Extensions.WriteModelAsObj(objstream, LevelData.geo.Anim[i].Model, materialPrefix, new MatrixStack(), ref totalVerts, ref totalNorms, ref totalUVs, ref errorFlag);
                            }
                        }

                        if (errorFlag)
                        {
                            MessageBox.Show("Error(s) encountered during export. Inspect the output file for more details.");
                        }
                    }
            }
        }
Esempio n. 5
0
        // Export models from stage (Assimp)
        private void ExportLevelObj(string fileName, bool selectedOnly)
        {
            int stepCount = 0;
            int numSteps  = 0;

            if (LevelData.TextureBitmaps != null && LevelData.TextureBitmaps.Count > 0)
            {
                stepCount = LevelData.TextureBitmaps[LevelData.leveltexs].Length;
                numSteps  = stepCount;
            }
            List <COL>         cols  = LevelData.geo.COL;
            List <GeoAnimData> anims = LevelData.geo.Anim;

            if (selectedOnly)
            {
                cols  = selectedItems.Items.OfType <LevelItem>().Select(a => a.CollisionData).ToList();
                anims = selectedItems.Items.OfType <LevelAnim>().Select(a => a.GeoAnimationData).ToList();
            }
            stepCount += cols.Count;
            stepCount += anims.Count;

            Assimp.AssimpContext context = new Assimp.AssimpContext();
            Assimp.Scene         scene   = new Assimp.Scene();
            scene.Materials.Add(new Assimp.Material());
            Assimp.Node n = new Assimp.Node();
            n.Name         = "RootNode";
            scene.RootNode = n;
            string        rootPath     = Path.GetDirectoryName(fileName);
            List <string> texturePaths = new List <string>();

            ProgressDialog progress = new ProgressDialog("Exporting stage: " + levelName, stepCount, true, false);

            progress.Show(this);
            progress.SetTaskAndStep("Exporting...");

            List <string> texlist = new List <string>();

            for (int i = 0; i < numSteps; i++)
            {
                BMPInfo bmp = LevelData.TextureBitmaps[LevelData.leveltexs][i];
                texlist.Add(bmp.Name);
                texturePaths.Add(Path.Combine(rootPath, bmp.Name + ".png"));
                if (!File.Exists(Path.Combine(rootPath, bmp.Name + ".png")))
                {
                    bmp.Image.Save(Path.Combine(rootPath, bmp.Name + ".png"));
                }
                progress.Step = $"Texture {i + 1}/{numSteps}";
                progress.StepProgress();
                Application.DoEvents();
            }

            // Save texture list
            SplitTools.NJS_TEXLIST textureNamesArray = new SplitTools.NJS_TEXLIST(texlist.ToArray());
            textureNamesArray.Save(Path.Combine(rootPath, Path.GetFileNameWithoutExtension(fileName) + ".satex"));

            for (int i = 0; i < cols.Count; i++)
            {
                SAEditorCommon.Import.AssimpStuff.AssimpExport(cols[i].Model, scene, Matrix.Identity, texturePaths.Count > 0 ? texturePaths.ToArray() : null, scene.RootNode);

                progress.Step = $"Mesh {i + 1}/{cols.Count}";
                progress.StepProgress();
                Application.DoEvents();
            }

            for (int i = 0; i < anims.Count; i++)
            {
                SAEditorCommon.Import.AssimpStuff.AssimpExport(anims[i].Model, scene, Matrix.Identity, texturePaths.Count > 0 ? texturePaths.ToArray() : null, scene.RootNode);
                progress.Step = $"Animation {i + 1}/{anims.Count}";
                progress.StepProgress();
                Application.DoEvents();
            }

            string ftype = "collada";

            switch (Path.GetExtension(fileName).ToLowerInvariant())
            {
            case ".fbx":
                ftype = "fbx";
                break;

            case ".obj":
                ftype = "obj";
                break;
            }
            context.ExportFile(scene, fileName, ftype, Assimp.PostProcessSteps.ValidateDataStructure | Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.FlipUVs);

            progress.SetTaskAndStep("Export complete!");
        }