Example #1
0
        public static Stream LoadNMSFileStream(string filepath, ref ResourceManager resMgr)
        {
            int load_mode = 0;

            string conv_filepath = filepath.TrimStart('/');

            filepath = filepath.Replace('\\', '/');
            string effective_filepath = filepath;

            string exmlpath = Path.ChangeExtension(filepath, "exml");

            exmlpath = exmlpath.ToUpper(); //Make upper case

            if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, exmlpath)))
            {
                load_mode = 0; //Load Exml
            }
            else if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, filepath)))
            {
                load_mode = 1; //Load MBIN from file
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey(filepath))
            {
                load_mode = 2; //Extract file from archive
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey("/" + filepath))
            {
                effective_filepath = "/" + filepath;
                load_mode          = 2; //Extract file from archive
            }
            else
            {
                CallBacks.Log("File: " + filepath + " Not found in PAKs or local folders. ");
                Util.showError("File: " + filepath + " Not found in PAKs or local folders. ", "Error");
                throw new FileNotFoundException("File not found\n " + filepath);
            }
            switch (load_mode)
            {
            case 0:     //Load EXML
                return(new FileStream(Path.Combine(RenderState.settings.UnpackDir, exmlpath), FileMode.Open));

            case 1:     //Load MBIN
                return(new FileStream(Path.Combine(RenderState.settings.UnpackDir, filepath), FileMode.Open));

            case 2:     //Load File from Archive
            {
                CallBacks.Log("Trying to export File" + effective_filepath);
                if (resMgr.NMSFileToArchiveMap.ContainsKey(effective_filepath))
                {
                    CallBacks.Log("File was found in archives. File Index: " + resMgr.NMSFileToArchiveMap[effective_filepath].GetFileIndex(effective_filepath));
                }

                int fileIndex = resMgr.NMSFileToArchiveMap[effective_filepath].GetFileIndex(effective_filepath);
                return(resMgr.NMSFileToArchiveMap[effective_filepath].ExtractFile(fileIndex));
            }
            }

            return(null);
        }
Example #2
0
        public static Dictionary <string, Dictionary <string, Vector4> > createPalette()
        {
            Dictionary <string, Dictionary <string, Vector4> > newPal;

            newPal = new Dictionary <string, Dictionary <string, Vector4> >();

            //ColourAlt ids
            int primary      = MVCore.Common.RenderState.randgen.Next(0, 64);
            int alternative1 = (primary + 1) % 64;
            int alternative2 = (alternative1 + 1) % 64;
            int alternative3 = (alternative2 + 1) % 64;
            int alternative4 = (alternative3 + 1) % 64;
            int unique       = (alternative4 + 1) % 64;

            Type t = typeof(Palettes);

            FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            foreach (FieldInfo f in fields)
            {
                //Check field type
                if (f.FieldType != typeof(List <Vector3>))
                {
                    continue;
                }
                //Get palette
                List <Vector3> palette = (List <Vector3>)f.GetValue(null);

                //Add palette to dictionary
                newPal[f.Name] = new Dictionary <string, Vector4>();
                //Add None option
                newPal[f.Name]["None"] = new Vector4(1.0f, 1.0f, 1.0f, 0.0f);
                //Add MatchGround option
                newPal[f.Name]["MatchGround"] = new Vector4(0.5f, 0.427f, 0.337f, 0.0f);

                try
                {
                    newPal[f.Name]["Primary"]      = new Vector4(palette[primary], 1.0f);
                    newPal[f.Name]["Alternative1"] = new Vector4(palette[alternative1], 1.0f);
                    newPal[f.Name]["Alternative2"] = new Vector4(palette[alternative2], 1.0f);
                    newPal[f.Name]["Alternative3"] = new Vector4(palette[alternative3], 1.0f);
                    newPal[f.Name]["Alternative4"] = new Vector4(palette[alternative4], 1.0f);
                    newPal[f.Name]["Unique"]       = new Vector4(palette[unique], 1.0f);
                }
                catch (ArgumentOutOfRangeException e)
                {
                    CallBacks.Log("Missing Options for Palette " + f.Name);
                    //Choose the first color in all cases that the palette files have not been properly imported
                    newPal[f.Name]["Primary"]      = new Vector4(palette[0], 1.0f);
                    newPal[f.Name]["Alternative1"] = new Vector4(palette[0], 1.0f);
                    newPal[f.Name]["Alternative2"] = new Vector4(palette[0], 1.0f);
                    newPal[f.Name]["Alternative3"] = new Vector4(palette[0], 1.0f);
                    newPal[f.Name]["Alternative4"] = new Vector4(palette[0], 1.0f);
                    newPal[f.Name]["Unique"]       = new Vector4(palette[0], 1.0f);
                }
            }
            return(newPal);
        }
Example #3
0
        public static string getGameInstallationDir()
        {
            //Registry keys
            string gog32_keyname = @"HKEY_LOCAL_MACHINE\SOFTWARE\GOG.com\Games\1446213994";
            string gog32_keyval  = "PATH";

            string gog64_keyname = @"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\GOG.com\Games\1446213994";
            string gog64_keyval  = "PATH";

            //Check Steam
            string val;

            try
            {
                val = fetchSteamGameInstallationDir() as string;
            } catch (Exception e) {
                val = null;
            }

            if (val != null || val == "")
            {
                return(val);
            }
            else
            {
                CallBacks.Log("Unable to find Steam Version");
            }

            //Check GOG32
            val = Registry.GetValue(gog32_keyname, gog32_keyval, "") as string;
            if (val != null)
            {
                CallBacks.Log("Found GOG32 Version: " + val);
                return(val);
            }
            else
            {
                CallBacks.Log("Unable to find GOG32 Version: " + val);
            }


            //Check GOG64
            val = Registry.GetValue(gog64_keyname, gog64_keyval, "") as string;
            if (val != null)
            {
                CallBacks.Log("Found GOG64 Version: " + val);
                return(val);
            }
            else
            {
                CallBacks.Log("Unable to find GOG64 Version: " + val);
            }

            return(null);
        }
Example #4
0
 public void deleteTexture(string name)
 {
     if (GLtextures.ContainsKey(name))
     {
         GMDL.Texture t = GLtextures[name];
         t.Dispose();
         GLtextures.Remove(name);
     }
     else
     {
         CallBacks.Log("Texture not found\n");
     }
 }
Example #5
0
        public static void combineTextures(string path, Dictionary <string, Dictionary <string, Vector4> > pal_input, ref textureManager texMgr)
        {
            clear();
            palette = pal_input;

            //Contruct .mbin file from dds
            string[] split = path.Split('.');
            //Construct main filename
            string temp = split[0] + ".";

            string mbinPath = temp + "TEXTURE.MBIN";

            prepareTextures(texMgr, mbinPath);

            //Init framebuffer
            int tex_width  = 0;
            int tex_height = 0;
            int fbo_tex    = -1;
            int fbo        = -1;

            bool fbo_status = setupFrameBuffer(ref fbo, ref fbo_tex, ref tex_width, ref tex_height);

            if (!fbo_status)
            {
                CallBacks.Log("Unable to mix textures, probably 0x0 textures...\n");
                return;
            }

            Texture diffTex = mixDiffuseTextures(tex_width, tex_height);

            diffTex.name = temp + "DDS";

            Texture maskTex = mixMaskTextures(tex_width, tex_height);

            maskTex.name = temp + "MASKS.DDS";

            Texture normalTex = mixNormalTextures(tex_width, tex_height);

            normalTex.name = temp + "NORMAL.DDS";

            revertFrameBuffer(fbo, fbo_tex);

            //Add the new procedural textures to the textureManager
            texMgr.addTexture(diffTex);
            texMgr.addTexture(maskTex);
            texMgr.addTexture(normalTex);
        }
Example #6
0
        public void init(textureManager input_texMgr)
        {
            texMgr  = input_texMgr;
            texUnit = new MyTextureUnit(Name);

            //Save texture to material
            switch (Name)
            {
            case "mpCustomPerMaterial.gDiffuseMap":
            case "mpCustomPerMaterial.gDiffuse2Map":
            case "mpCustomPerMaterial.gMasksMap":
            case "mpCustomPerMaterial.gNormalMap":
                prepTextures();
                break;

            default:
                CallBacks.Log("Not sure how to handle Sampler " + Name);
                break;
            }
        }
Example #7
0
        //Generate procedural textures
        private static void prepareTextures(textureManager texMgr, string path)
        {
            //At this point, at least one sampler exists, so for now I assume that the first sampler
            //is always the diffuse sampler and I can initiate the mixing process
            Console.WriteLine("Procedural Texture Detected: " + path);
            CallBacks.Log(string.Format("Parsing Procedural Texture"));

            TkProceduralTextureList template = NMSUtils.LoadNMSTemplate(path, ref Common.RenderState.activeResMgr) as TkProceduralTextureList;

            List <TkProceduralTexture> texList = new List <TkProceduralTexture>(8);

            for (int i = 0; i < 8; i++)
            {
                texList.Add(null);
            }
            ModelProcGen.parse_procTexture(ref texList, template, ref Common.RenderState.activeResMgr);

            Common.CallBacks.Log("Proc Texture Selection");
            for (int i = 0; i < 8; i++)
            {
                if (texList[i] != null)
                {
                    string partNameDiff = texList[i].Diffuse;
                    Common.CallBacks.Log(partNameDiff);
                }
            }

            Common.CallBacks.Log("Procedural Material. Trying to generate procTextures...");

            for (int i = 0; i < 8; i++)
            {
                TkProceduralTexture ptex = texList[i];
                //Add defaults
                if (ptex == null)
                {
                    baseLayersUsed[i]  = 0.0f;
                    alphaLayersUsed[i] = 0.0f;
                    continue;
                }

                string partNameDiff   = ptex.Diffuse;
                string partNameMask   = ptex.Mask;
                string partNameNormal = ptex.Normal;

                TkPaletteTexture paletteNode = ptex.Palette;
                string           paletteName = paletteNode.Palette.ToString();
                string           colorName   = paletteNode.ColourAlt.ToString();
                Vector4          palColor    = palette[paletteName][colorName];
                //Randomize palette Color every single time
                //Vector3 palColor = Model_Viewer.Palettes.get_color(paletteName, colorName);

                //Store pallete color to Recolouring List
                reColourings[i] = new float[] { palColor[0], palColor[1], palColor[2], palColor[3] };
                if (ptex.OverrideAverageColour)
                {
                    avgColourings[i] = new float[] { ptex.AverageColour.R, ptex.AverageColour.G, ptex.AverageColour.B, ptex.AverageColour.A }
                }
                ;

                //Create Palette Option
                PaletteOpt palOpt = new PaletteOpt();
                palOpt.PaletteName = paletteName;
                palOpt.ColorName   = colorName;
                palOpts[i]         = palOpt;
                Console.WriteLine("Index {0} Palette Selection {1} {2} ", i, palOpt.PaletteName, palOpt.ColorName);
                Console.WriteLine("Index {0} Color {1} {2} {3} {4}", i, palColor[0], palColor[1], palColor[2], palColor[3]);

                //DIFFUSE
                if (partNameDiff == "")
                {
                    //Add White
                    baseLayersUsed[i] = 0.0f;
                }
                else if (!texMgr.hasTexture(partNameDiff))
                {
                    //Configure the Diffuse Texture
                    try
                    {
                        Texture tex = new Texture(partNameDiff);
                        tex.palOpt    = palOpt;
                        tex.procColor = palColor;
                        //Store to master texture manager
                        Common.RenderState.activeResMgr.texMgr.addTexture(tex);

                        //Save Texture to material
                        difftextures[i]    = tex;
                        baseLayersUsed[i]  = 1.0f;
                        alphaLayersUsed[i] = 1.0f;
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        //Texture Not Found Continue
                        Console.WriteLine("Diffuse Texture " + partNameDiff + " Not Found, Appending White Tex");
                        CallBacks.Log(string.Format("Diffuse Texture {0} Not Found", partNameDiff));
                        baseLayersUsed[i] = 0.0f;
                    }
                }
                else
                //Load texture from dict
                {
                    Texture tex = texMgr.getTexture(partNameDiff);
                    //Save Texture to material
                    difftextures[i]   = tex;
                    baseLayersUsed[i] = 1.0f;
                }

                //MASK
                if (partNameMask == "")
                {
                    //Skip
                    alphaLayersUsed[i] = 0.0f;
                }
                else if (!texMgr.hasTexture(partNameMask))
                {
                    //Configure Mask
                    try
                    {
                        Texture texmask = new Texture(partNameMask);
                        //Store to master texture manager
                        Common.RenderState.activeResMgr.texMgr.addTexture(texmask);
                        //Store Texture to material
                        masktextures[i]    = texmask;
                        alphaLayersUsed[i] = 0.0f;
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        //Mask Texture not found
                        Console.WriteLine("Mask Texture " + partNameMask + " Not Found");
                        CallBacks.Log(string.Format("Mask Texture {0} Not Found", partNameMask));
                        alphaLayersUsed[i] = 0.0f;
                    }
                }
                else
                //Load texture from dict
                {
                    Texture tex = texMgr.getTexture(partNameMask);
                    //Store Texture to material
                    masktextures[i]    = tex;
                    alphaLayersUsed[i] = 1.0f;
                }


                //NORMALS
                if (partNameNormal == "")
                {
                    //Skip
                }
                else if (!texMgr.hasTexture(partNameNormal))
                {
                    try
                    {
                        Texture texnormal = new Texture(partNameNormal);
                        //Store to master texture manager
                        Common.RenderState.activeResMgr.texMgr.addTexture(texnormal);
                        //Store Texture to material
                        normaltextures[i] = texnormal;
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        //Normal Texture not found
                        CallBacks.Log(string.Format("Normal Texture {0} Not Found", partNameNormal));
                    }
                }
                else
                //Load texture from dict
                {
                    Texture tex = texMgr.getTexture(partNameNormal);
                    //Store Texture to material
                    normaltextures[i] = tex;
                }
            }
        }
Example #8
0
        public static Dictionary <string, Dictionary <string, Vector4> > createPalettefromBasePalettes()
        {
            Dictionary <string, Dictionary <string, Vector4> > newPal;

            newPal = new Dictionary <string, Dictionary <string, Vector4> >();

            GcPaletteList template;

            try {
                template = NMSUtils.LoadNMSTemplate("METADATA\\SIMULATION\\SOLARSYSTEM\\COLOURS\\BASECOLOURPALETTES.MBIN",
                                                    ref MVCore.Common.RenderState.activeResMgr) as GcPaletteList;
            } catch (Exception ex) {
                CallBacks.Log("Using Default Palettes");
                return(createPalette());
            }

            TkPaletteTexture tkpt = new TkPaletteTexture();
            GcPaletteData    gcpd = new GcPaletteData();

            for (int i = 0; i < template.Palettes.Length; i++)
            {
                string pal_name = ((TkPaletteTexture.PaletteEnum)i).ToString();
                CallBacks.Log(string.Format("Palette {0} NumColors {1}", pal_name, template.Palettes[i].NumColours));
                newPal[pal_name] = new Dictionary <string, Vector4>();

                //Generate Bitmap for palette
                Bitmap bmp = new Bitmap(64, 1);

                for (int j = 0; j < template.Palettes[i].Colours.Length; j++)
                {
                    Colour colour = template.Palettes[i].Colours[j];

                    //Console.WriteLine("Color {0} {1} {2} {3} {4}",
                    //j, colour.R, colour.G, colour.B, colour.A);

                    //bmp.SetPixel(j, 0, Color.FromArgb((int)(colour.A * 255),
                    //                                    (int)(colour.R * 255),
                    //                                    (int)(colour.G * 255),
                    //                                    (int)(colour.B * 255)));
                }

                Vector4 primary, alt1, alt2, alt3, alt4, matchg, unique, none;
                int     index        = 0;
                int     index1       = 0;
                int     index2       = 0;
                int     index3       = 0;
                int     index4       = 0;
                int     unique_index = 0;
                none = new Vector4(1.0f, 1.0f, 1.0f, 0.0f);

                switch (template.Palettes[i].NumColours)
                {
                case GcPaletteData.NumColoursEnum.Inactive:     //Inactive
                    //Test by not saving anything
                    break;

                case GcPaletteData.NumColoursEnum._1:     //1 Color - All colors should be the same
                    index        = 0;
                    index1       = index;
                    index2       = index;
                    index3       = index;
                    index4       = index;
                    unique_index = 0;
                    break;

                case GcPaletteData.NumColoursEnum._4:     //4 Color
                case GcPaletteData.NumColoursEnum._8:     //8 Color NOTE: Not enough samples for that
                    index        = get_active_palette_index(4);
                    index1       = index + 1;
                    index2       = index + 2;
                    index3       = index + 3;
                    unique_index = get_active_palette_index(1);
                    break;

                case GcPaletteData.NumColoursEnum._16:     //16 Color
                    //Align to groups of 2
                    index        = get_active_palette_index(2);
                    index1       = index + 1;
                    index2       = get_active_palette_index(2);
                    index3       = index2 + 1;
                    index4       = get_active_palette_index(2);
                    unique_index = get_active_palette_index(1);
                    break;

                case GcPaletteData.NumColoursEnum.All:     //All
                    index        = get_active_palette_index(1);
                    index1       = get_active_palette_index(1);
                    index2       = get_active_palette_index(1);
                    index3       = get_active_palette_index(1);
                    index4       = get_active_palette_index(1);
                    unique_index = get_active_palette_index(1);
                    break;
                }

                //Set Colors
                primary = colour_to_vec4(template.Palettes[i].Colours[index]);
                alt1    = colour_to_vec4(template.Palettes[i].Colours[index1]);
                alt2    = colour_to_vec4(template.Palettes[i].Colours[index2]);
                alt3    = colour_to_vec4(template.Palettes[i].Colours[index3]);
                alt4    = colour_to_vec4(template.Palettes[i].Colours[index4]);
                matchg  = primary;
                unique  = colour_to_vec4(template.Palettes[i].Colours[unique_index]);
                none    = primary;

                //save the colors to the dictionary
                newPal[pal_name]["Primary"]      = primary;
                newPal[pal_name]["Alternative1"] = alt1;
                newPal[pal_name]["Alternative2"] = alt2;
                newPal[pal_name]["Alternative3"] = alt3;
                newPal[pal_name]["Alternative4"] = alt4;
                newPal[pal_name]["Unique"]       = unique;
                //Add MatchGround option
                newPal[pal_name]["MatchGround"] = new Vector4(0.5f, 0.427f, 0.337f, 0.0f);
                newPal[pal_name]["None"]        = none;

                //bmp.Save("Temp\\" + pal_name + ".bmp", ImageFormat.Bmp);
            }

            return(newPal);
        }
Example #9
0
        private static string fetchSteamGameInstallationDir()
        {
            //At first try to find the steam installation folder

            //Try to fetch the installation dir
            string steam_keyname = @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam";
            string steam_keyval  = "InstallPath";
            string nms_id        = "275850";

            //Fetch Steam Installation Folder

            string steam_path = Registry.GetValue(steam_keyname, steam_keyval, null) as string;

            if (steam_path is null)
            {
                CallBacks.Log("Failed to find Steam Installation: ");
                return(null);
            }

            CallBacks.Log("Found Steam Installation: " + steam_path);
            CallBacks.Log("Searching for NMS in the default steam directory...");

            //At first try to find acf entries in steam installation dir
            foreach (string path in Directory.GetFiles(Path.Combine(steam_path, "steamapps")))
            {
                if (!path.EndsWith(".acf"))
                {
                    continue;
                }

                if (path.Contains(nms_id))
                {
                    return(Path.Combine(steam_path, @"steamapps\common\No Man's Sky\GAMEDATA"));
                }
            }

            CallBacks.Log("NMS not found in default folders. Searching Steam Libraries...");

            //If that did't work try to load the libraryfolders.vdf
            StreamReader  sr           = new StreamReader(Path.Combine(steam_path, @"steamapps\libraryfolders.vdf"));
            List <string> libraryPaths = new List <string>();

            int line_count = 0;

            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                if (line_count < 4)
                {
                    line_count++;
                    continue;
                }

                if (!line.StartsWith("\t"))
                {
                    continue;
                }

                string[] split = line.Split('\t');
                string   path  = split[split.Length - 1];
                path = path.Trim('\"');
                path = path.Replace("\\\\", "\\");
                libraryPaths.Add(Path.Combine(path, "steamapps"));
            }

            //Check all library paths for the acf file

            foreach (string path in libraryPaths)
            {
                foreach (string filepath in Directory.GetFiles(path))
                {
                    if (!filepath.EndsWith(".acf"))
                    {
                        continue;
                    }

                    if (filepath.Contains(nms_id))
                    {
                        return(Path.Combine(path, @"common\No Man's Sky\GAMEDATA"));
                    }
                }
            }

            CallBacks.Log("Unable to locate Steam Installation...");
            return(null);
        }
Example #10
0
        //Load Game Archive Handles

        public static void loadNMSArchives(string filepath, string gameDir, ref ResourceManager resMgr, ref int status)
        {
            CallBacks.Log("Trying to load PAK files from " + gameDir);
            if (!Directory.Exists(gameDir))
            {
                Util.showError("Unable to locate game Directory. PAK files (Vanilla + Mods) not loaded. You can still work using unpacked files", "Info");
                status = -1;
                return;
            }

            //Load the handles to the resource manager

            //Fetch .pak files
            string[] pak_files = Directory.GetFiles(gameDir);
            resMgr.NMSArchiveMap.Clear();

            CallBacks.updateStatus("Loading Vanilla NMS Archives...");

            foreach (string pak_path in pak_files)
            {
                if (!pak_path.EndsWith(".pak"))
                {
                    continue;
                }

                try
                {
                    FileStream             arc_stream = new FileStream(pak_path, FileMode.Open);
                    libPSARC.PSARC.Archive psarc      = new libPSARC.PSARC.Archive(arc_stream, true);
                    CallBacks.Log("Loaded :" + pak_path);
                    resMgr.NMSArchiveMap[pak_path] = psarc;
                }
                catch (Exception ex)
                {
                    Util.showError("An Error Occured : " + ex.Message, "Error");
                    CallBacks.Log("Pak file " + pak_path + " failed to load");
                    CallBacks.Log("Error : " + ex.GetType().Name + " " + ex.Message);
                }
            }

            if (Directory.Exists(Path.Combine(gameDir, "MODS")))
            {
                pak_files = Directory.GetFiles(Path.Combine(gameDir, "MODS"));
                Common.CallBacks.updateStatus("Loading Modded NMS Archives...");
                foreach (string pak_path in pak_files)
                {
                    if (pak_path.Contains("CUSTOMMODELS"))
                    {
                        Console.WriteLine(pak_path);
                    }

                    if (!pak_path.EndsWith(".pak"))
                    {
                        continue;
                    }

                    try
                    {
                        FileStream             arc_stream = new FileStream(pak_path, FileMode.Open);
                        libPSARC.PSARC.Archive psarc      = new libPSARC.PSARC.Archive(arc_stream, true);
                        resMgr.NMSArchiveMap[pak_path] = psarc;
                    }
                    catch (Exception ex)
                    {
                        Util.showError("An Error Occured : " + ex.Message, "Error");
                        CallBacks.Log("Pak file " + pak_path + " failed to load");
                        CallBacks.Log("Error : " + ex.GetType().Name + " " + ex.Message);
                    }
                }
            }

            if (resMgr.NMSArchiveMap.Keys.Count == 0)
            {
                CallBacks.Log("No pak files found");
                CallBacks.Log("Not creating/reading manifest file");
                return;
            }

            //Populate resource manager with the files
            CallBacks.updateStatus("Populating Resource Manager...");
            foreach (string arc_path in resMgr.NMSArchiveMap.Keys.Reverse())
            {
                libPSARC.PSARC.Archive arc = resMgr.NMSArchiveMap[arc_path];

                foreach (string f in arc.filePaths)
                {
                    resMgr.NMSFileToArchiveMap[f] = resMgr.NMSArchiveMap[arc_path];
                }
            }

            //NOT WORTH TO USE MANIFEST FILES


            /*
             * //Check if manifest file exists
             * if (File.Exists(filepath))
             * {
             *  Common.CallBacks.updateStatus("Loading NMS File manifest...");
             *
             *  //Read Input Data
             *  FileStream fs = new FileStream(filepath, FileMode.Open);
             *  byte[] comp_data = new byte[fs.Length];
             *  fs.Read(comp_data, 0, (int) fs.Length);
             *  fs.Close();
             *
             *  MemoryStream decomp_ms = new MemoryStream();
             *  zlib.ZOutputStream zout = new zlib.ZOutputStream(decomp_ms);
             *  zout.Write(comp_data, 0, comp_data.Length);
             *  zout.finish();
             *
             *  //Read the assignment from the files
             *  decomp_ms.Seek(0, SeekOrigin.Begin);
             *  StreamReader sr = new StreamReader(decomp_ms);
             *
             *  while (!sr.EndOfStream)
             *  {
             *      string line = sr.ReadLine();
             *      string[] sp = line.Split('\t');
             *      if (sp.Length != 2)
             *          Console.WriteLine(sp[0] + "   " + sp[1]);
             *      resMgr.NMSFileToArchiveMap[sp[0]] = resMgr.NMSArchiveMap[sp[1]];
             *  }
             *
             *  sr.Close();
             *  zout.Close();
             *
             * }
             * else
             * {
             *  Common.CallBacks.updateStatus("NMS File Manifest not found. Creating...");
             *
             *  MemoryStream ms = new MemoryStream();
             *  MemoryStream comp_ms = new MemoryStream();
             *  StreamWriter sw = new StreamWriter(ms);
             *
             *  foreach (string arc_path in resMgr.NMSArchiveMap.Keys.Reverse())
             *  {
             *      libPSARC.PSARC.Archive arc = resMgr.NMSArchiveMap[arc_path];
             *
             *      foreach (string f in arc.filePaths)
             *      {
             *          sw.WriteLine(f + '\t' + arc_path);
             *          resMgr.NMSFileToArchiveMap[f] = resMgr.NMSArchiveMap[arc_path];
             *      }
             *  }
             *
             *  //Compress memorystream
             *  zlib.ZOutputStream zout = new zlib.ZOutputStream(comp_ms, zlib.zlibConst.Z_DEFAULT_COMPRESSION);
             *
             *  //Copy Data to the zlib stream\
             *  sw.Flush();
             *  byte[] comp_data = ms.ToArray();
             *
             *  zout.Write(comp_data, 0, (int) ms.Length);
             *  zout.finish(); //Compress
             *
             *  //Write memorystream to file
             *  comp_ms.Seek(0, SeekOrigin.Begin);
             *  FileStream fs = new FileStream(filepath, FileMode.CreateNew);
             *  fs.Write(comp_ms.ToArray(), 0, (int) comp_ms.Length);
             *  fs.Close();
             *  comp_ms.Close();
             *  ms.Close();
             *
             * }
             */

            status = 0; // All good
            Common.CallBacks.updateStatus("Ready");
        }
Example #11
0
        public static NMSTemplate LoadNMSTemplate(string filepath, ref ResourceManager resMgr)
        {
            int         load_mode = 0;
            NMSTemplate template  = null;

            filepath = filepath.Replace('\\', '/');
            string effective_filepath = filepath;

            //Checks to prevent malformed paths from further processing
            if (filepath.Contains(' '))
            {
                return(null);
            }

            string exmlpath = Path.ChangeExtension(filepath, "exml");

            exmlpath = exmlpath.ToUpper(); //Make upper case


            if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, exmlpath)))
            {
                load_mode = 0; //Load Exml
            }
            else if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, filepath)))
            {
                load_mode = 1; //Load MBIN from file
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey(filepath))
            {
                load_mode = 2;                                               //Extract file from archive
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey("/" + filepath)) //AMUMSS BULLSHIT
            {
                effective_filepath = "/" + filepath;
                load_mode          = 2; //Extract file from archive
            }
            else
            {
                CallBacks.Log("File: " + filepath + " Not found in PAKs or local folders. ");
                Util.showError("File: " + filepath + " Not found in PAKs or local folders. ", "Error");
                return(null);
            }

            try
            {
                switch (load_mode)
                {
                case 0:     //Load EXML
                {
                    string xml = File.ReadAllText(Path.Combine(RenderState.settings.UnpackDir, exmlpath));
                    template = EXmlFile.ReadTemplateFromString(xml);
                    break;
                }

                case 1:     //Load MBIN
                {
                    string   eff_path = Path.Combine(RenderState.settings.UnpackDir, filepath);
                    MBINFile mbinf    = new MBINFile(eff_path);
                    mbinf.Load();
                    template = mbinf.GetData();
                    mbinf.Dispose();
                    break;
                }

                case 2:     //Load File from Archive
                {
                    Stream   file  = resMgr.NMSFileToArchiveMap[effective_filepath].ExtractFile(effective_filepath);
                    MBINFile mbinf = new MBINFile(file);
                    mbinf.Load();
                    template = mbinf.GetData();
                    mbinf.Dispose();
                    break;
                }
                }
            } catch (Exception ex)
            {
                if (ex is System.IO.DirectoryNotFoundException || ex is System.IO.FileNotFoundException)
                {
                    Util.showError("File " + effective_filepath + " Not Found...", "Error");
                }
                else if (ex is System.IO.IOException)
                {
                    Util.showError("File " + effective_filepath + " problem...", "Error");
                }
                else if (ex is System.Reflection.TargetInvocationException)
                {
                    Util.showError("libMBIN failed to decompile file. If this is a vanilla file, contact the MbinCompiler developer",
                                   "Error");
                }
                else
                {
                    Util.showError("Unhandled Exception " + ex.Message, "Error");
                }
                return(null);
            }

#if DEBUG
            //Save NMSTemplate to exml
            string data = EXmlFile.WriteTemplate(template);
            string path = Path.Combine("Temp", filepath + ".exml");
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            File.WriteAllText(path, data);
#endif
            return(template);
        }