Load() public method

public Load ( Stream ms ) : bool
ms Stream
return bool
Example #1
0
        /// <summary>
        /// Go through our media/wheels/ directory and find all of the wheel definitions we have, then make dictionaries out of them
        /// and add them to our one big dictionary.		
        /// </summary>
        public void ReadWheelsFromFiles()
        {
            // since we can run this whenever (like when we're tweaking files), we want to clear our dictionary first
            wheels.Clear();

            // get all of the filenames of the files in media/wheels/
            IEnumerable<string> files = Directory.EnumerateFiles("media/vehicles/", "*.wheel", SearchOption.AllDirectories);

            foreach (string filename in files) {
                // I forgot ogre had this functionality already built in
                ConfigFile cfile = new ConfigFile();
                cfile.Load(filename, "=", true);

                // each .wheel file can have multiple [sections]. We'll use each section name as the wheel name
                ConfigFile.SectionIterator sectionIterator = cfile.GetSectionIterator();
                while (sectionIterator.MoveNext()) {
                    string wheelname = sectionIterator.CurrentKey;
                    // make a dictionary
                    var wheeldict = new Dictionary<string, float>();
                    // go over every property in the file and add it to the dictionary, parsing it as a float
                    foreach (KeyValuePair<string, string> pair in sectionIterator.Current) {
                        wheeldict.Add(pair.Key, float.Parse(pair.Value, culture));
                    }

                    wheels[wheelname] = wheeldict;
                }

                cfile.Dispose();
                sectionIterator.Dispose();
            }
        }
Example #2
0
        // Override resource sources (include Quake3 archives)
        public override void SetupResources()
        {
            ConfigFile cf = new ConfigFile();
            cf.Load("quake3settings.cfg", "\t:=", true);
            quakePk3 = cf.GetSetting("Pak0Location");
            quakeLevel = cf.GetSetting("Map");

            base.SetupResources();
            ResourceGroupManager.Singleton.AddResourceLocation(quakePk3, "Zip", ResourceGroupManager.Singleton.WorldResourceGroupName, true);
        }
Example #3
0
        public void Init()
        {
            // Create root object
             mRoot = new Root();

             // Define Resources
             ConfigFile cf = new ConfigFile();
             cf.Load("resources.cfg", "\t:=", true);
             ConfigFile.SectionIterator seci = cf.GetSectionIterator();
             String secName, typeName, archName;

             while (seci.MoveNext())
             {
            secName = seci.CurrentKey;
            ConfigFile.SettingsMultiMap settings = seci.Current;
            foreach (KeyValuePair<string, string> pair in settings)
            {
               typeName = pair.Key;
               archName = pair.Value;
               ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
            }
             }

             // Setup RenderSystem
             RenderSystem rs = mRoot.GetRenderSystemByName("Direct3D9 Rendering Subsystem");
             // or use "OpenGL Rendering Subsystem"
             mRoot.RenderSystem = rs;
             rs.SetConfigOption("Full Screen", "No");
             rs.SetConfigOption("Video Mode", "800 x 600 @ 32-bit colour");

             // Create Render Window
             mRoot.Initialise(false, "Main Ogre Window");
             NameValuePairList misc = new NameValuePairList();
             misc["externalWindowHandle"] = Handle.ToString();
             mWindow = mRoot.CreateRenderWindow("Main RenderWindow", 800, 600, false, misc);

             // Init resources
             TextureManager.Singleton.DefaultNumMipmaps = 5;
             ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

             // Create a Simple Scene
             SceneManager mgr = mRoot.CreateSceneManager(SceneType.ST_GENERIC);
             Camera cam = mgr.CreateCamera("Camera");
             cam.AutoAspectRatio = true;
             mWindow.AddViewport(cam);

             Entity ent = mgr.CreateEntity("ninja", "ninja.mesh");
             mgr.RootSceneNode.CreateChildSceneNode().AttachObject(ent);

             cam.Position = new Vector3(0, 200, -400);
             cam.LookAt(ent.BoundingBox.Center);
        }
        /// <summary>
        /// Basically adds all of the resource locations but doesn't actually load anything.
        /// </summary>
        private static void InitResources()
        {
            ConfigFile file = new ConfigFile();
            file.Load("media/plugins/resources.cfg", "\t:=", true);
            ConfigFile.SectionIterator sectionIterator = file.GetSectionIterator();

            while (sectionIterator.MoveNext()) {
                string currentKey = sectionIterator.CurrentKey;
                foreach (KeyValuePair<string, string> pair in sectionIterator.Current) {
                    string key = pair.Key;
                    string name = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(name, key, currentKey);
                }
            }

            file.Dispose();
            sectionIterator.Dispose();
        }
        public static IDbProvider Create(ConfigFile configFile)
        {
            configFile.Load();

            string dbType = configFile.Get(DbConstants.KEY_DB_TYPE);

            log.Info("Creating provider for" + dbType);

            switch (dbType)
            {
                case DbConstants.DB_TYPE_MYSQL:
                    return new MySqlDbProvider(configFile);
                case DbConstants.DB_TYPE_SQLITE:
                    return new SqliteDbProvider(configFile);
                default:
                    throw new Exception(string.Format("Don't know Data Provider type {0}", dbType));
            }
        }
Example #6
0
        public void TestDynamicConfig()
        {
            const string inputfile = "{ \"x\": 10, \"y\": \"hello\", \"z\": [ 10, \"yo\" ], \"w\": { \"a\": 20, \"b\": [ 500, 600 ] } }";
            var          filename  = Path.GetTempFileName();

            File.WriteAllText(filename, inputfile);

            var cfg = ConfigFile.Load <DynamicConfigFile>(filename);

            TestConfigFile(cfg);

            cfg.Save();
            cfg = ConfigFile.Load <DynamicConfigFile>(filename);

            TestConfigFile(cfg);

            File.Delete(filename);
        }
Example #7
0
        public static void Patch()
        {
            Config.Load();
            var configChanged = Config.TryGet(ref _x, "Scrap metal size", "x")
                                | Config.TryGet(ref _y, "Scrap metal size", "y");

            if (_x <= 0)
            {
                _x = 2;
                Config["Scrap metal size", "x"] = _x;
                Logger.Error("Size of the item can't be less or equal of 0! X was set to 2", LogType.Custom | LogType.Console);
                configChanged = true;
            }
            if (_y <= 0)
            {
                _y = 2;
                Config["Scrap metal size", "y"] = _y;
                Logger.Error("Size of the item can't be less or equal of 0! Y was set to 2", LogType.Custom | LogType.Console);
                configChanged = true;
            }
            if (configChanged)
            {
                Config.Save();
            }
            var techData = new TechDataHelper
            {
                _craftAmount = 2,
                _ingredients = new List <IngredientHelper>()
                {
                    new IngredientHelper(TechType.TitaniumIngot, 1)
                },
                _linkedItems = new List <TechType>()
                {
                    TechType.Titanium,
                    TechType.Titanium
                },
                _techType = TechType.ScrapMetal
            };

            CraftDataPatcher.customTechData.Add(TechType.ScrapMetal, techData);
            CraftTreePatcher.customCraftNodes.Add("Resources/BasicMaterials/ScrapMetal", TechType.ScrapMetal);
            CraftDataPatcher.customItemSizes[TechType.ScrapMetal] = new Vector2int(_x, _y);
            KnownTechPatcher.unlockedAtStart.Add(TechType.ScrapMetal);
        }
Example #8
0
        void DefineResources()
        {
            ConfigFile cf = new ConfigFile();
             cf.Load("resources.cfg", "\t:=", true);
             ConfigFile.SectionIterator seci = cf.GetSectionIterator();
             String secName, typeName, archName;

             while (seci.MoveNext())
             {
                 secName = seci.CurrentKey;
                 ConfigFile.SettingsMultiMap settings = seci.Current;
                 foreach (KeyValuePair<string, string> pair in settings)
                 {
                     typeName = pair.Key;
                     archName = pair.Value;
                     ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                 }
             }
        }
Example #9
0
        public static void Main(string[] args)
        {
//Debug.Active = true;
//Debug.DevelopmentInfo = true;
//Debug.Level = 10;
            ConsoleDebug.Connect();
            ApplicationPreferences.AddMasterConfiguration(typeof(TestPreferences), true);
            ConfigFile aFile = ApplicationPreferences.GetMasterConfiguration();

            aFile.Load();

            Application.Init();
            MainWindow win = new MainWindow();

            win.Show();
            Application.Run();

            aFile.Save();
        }
        protected virtual void LoadResources()
        {
            // Load resource paths from config file
            var cf = new ConfigFile();
            cf.Load(mResourcesCfg, "\t:=", true);

            // Go through all sections & settings in the file
            var seci = cf.GetSectionIterator();
            while (seci.MoveNext())
            {
                foreach (var pair in seci.Current)
                {
                    ResourceGroupManager.Singleton.AddResourceLocation(
                        pair.Value, pair.Key, seci.CurrentKey);
                }
            }

            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();
        }
Example #11
0
    void LoadConfig()
    {
        var config = new ConfigFile();
        var err    = config.Load(configPath);

        if (err != Error.Ok)
        {
            musicVolume = -10;
            sfxVolume   = -20;
            fullScreen  = false;
            GD.Print("Loi trong qua trinh load cai dat!");
            return;
        }

        musicVolume = (int)config.GetValue("audio", "music_volume");
        sfxVolume   = (int)config.GetValue("audio", "sfx_volume");
        fullScreen  = (bool)config.GetValue("display", "fullscreen");
        fastMode    = (bool)config.GetValue("game_mode", "fast_mode");
    }
Example #12
0
        /// <summary>
        /// Initializes the specified instance with a config root file.
        /// </summary>
        /// <returns>true if the config or assembly changed from the last run; otherwise returns false</returns>
        public bool Init()
        {
            _thisAssemblyPath  = GetType().GetTypeInfo().Assembly.Location;
            _assemblyCheckFile = Path.Combine(IntermediateOutputPath, $"SharpGen.check");
            _assemblyDatetime  = File.GetLastWriteTime(_thisAssemblyPath);
            _isAssemblyNew     = (_assemblyDatetime != File.GetLastWriteTime(_assemblyCheckFile));
            _generatedPath     = OutputDirectory ?? Path.GetDirectoryName(Path.GetFullPath(ConfigRootPath));

            Logger.Message("Loading config files...");

            if (Config == null)
            {
                Config = ConfigFile.Load(ConfigRootPath, Macros.ToArray(), Logger);
            }
            else
            {
                Config = ConfigFile.Load(Config, Macros.ToArray(), Logger);
            }

            if (Logger.HasErrors)
            {
                Logger.Fatal("Errors loading the config file");
            }

            var latestConfigTime = ConfigFile.GetLatestTimestamp(Config.ConfigFilesLoaded);

            _allConfigCheck = Path.Combine(IntermediateOutputPath, Config.Id + "-CodeGen.check");

            var isConfigFileChanged = !File.Exists(_allConfigCheck) || latestConfigTime > File.GetLastWriteTime(_allConfigCheck);

            if (_isAssemblyNew)
            {
                Logger.Message("Assembly [{0}] changed. All files will be generated", _thisAssemblyPath);
            }
            else if (isConfigFileChanged)
            {
                Logger.Message("Config files [{0}] changed", string.Join(",", Config.ConfigFilesLoaded.Select(file => Path.GetFileName(file.AbsoluteFilePath))));
            }


            // Return true if a config file changed or the assembly changed
            return(isConfigFileChanged || _isAssemblyNew);
        }
Example #13
0
        public void AllScriptsShouldBeSavedToNewConfig()
        {
            var newConfigName = "newscripts.config";

            var newConfig = new ConfigFile <Scripts>(newConfigName);

            newConfig.Save(_scripts);
            Assert.AreEqual(File.Exists(newConfigName), true);

            newConfig.Save(_scripts);
            Assert.AreEqual(File.Exists(newConfigName + ".backup"), true);

            var scriptsFromNewFile = newConfig.Load();

            Assert.AreEqual(scriptsFromNewFile.List.Count, _scripts.List.Count);

            File.Delete(newConfigName);
            File.Delete(newConfigName + ".backup");
        }
Example #14
0
        void setupResources()
        {
            // Load resource paths from config file
            var cf = new ConfigFile();

            cf.Load(RESOURCES_CFG, "\t:=", true);

            // Go through all sections & settings in the file
            var seci = cf.GetSectionIterator();

            while (seci.MoveNext())
            {
                foreach (var pair in seci.Current)
                {
                    ResourceGroupManager.Singleton.AddResourceLocation(
                        pair.Value, pair.Key, seci.CurrentKey);
                }
            }
        }
Example #15
0
        protected CppModule ParseCpp(ConfigFile config, string[] additionalArguments = null)
        {
            var loaded = ConfigFile.Load(config, new string[0], Logger);

            var(filesWithIncludes, filesWithExtensionHeaders) = loaded.GetFilesWithIncludesAndExtensionHeaders();

            var configsWithIncludes = new HashSet <ConfigFile>();

            foreach (var cfg in loaded.ConfigFilesLoaded)
            {
                if (filesWithIncludes.Contains(cfg.Id))
                {
                    configsWithIncludes.Add(cfg);
                }
            }

            var cppHeaderGenerator = new CppHeaderGenerator(Logger, true, TestDirectory.FullName);

            var(updated, _) = cppHeaderGenerator.GenerateCppHeaders(loaded, configsWithIncludes, filesWithExtensionHeaders);

            var resolver = new IncludeDirectoryResolver(Logger);

            resolver.Configure(loaded);

            var castXml = new CastXml(Logger, resolver, CastXmlExecutablePath, additionalArguments ?? Array.Empty <string>())
            {
                OutputPath = TestDirectory.FullName
            };

            var extensionGenerator = new CppExtensionHeaderGenerator(new MacroManager(castXml));

            var skeleton = extensionGenerator.GenerateExtensionHeaders(loaded, TestDirectory.FullName, filesWithExtensionHeaders, updated);

            var parser = new CppParser(Logger, castXml)
            {
                OutputPath = TestDirectory.FullName
            };

            parser.Initialize(loaded);

            return(parser.Run(skeleton));
        }
Example #16
0
        public static IDbProvider Create(ConfigFile configFile)
        {
            configFile.Load();

            string dbType = configFile.Get(DbConstants.KEY_DB_TYPE);

            log.Info("Creating provider for" + dbType);

            switch (dbType)
            {
            case DbConstants.DB_TYPE_MYSQL:
                return(new MySqlDbProvider(configFile));

            case DbConstants.DB_TYPE_SQLITE:
                return(new SqliteDbProvider(configFile));

            default:
                throw new Exception(string.Format("Don't know Data Provider type {0}", dbType));
            }
        }
Example #17
0
        /// <summary>
        /// Initializes the resources which the program uses.
        /// </summary>
        protected virtual void InitResources()
        {
            ConfigFile cf = new ConfigFile();

            cf.Load("resources.cfg", "\t:=", true);
            ConfigFile.SectionIterator seci = cf.GetSectionIterator();
            String secName, typeName, archName;

            while (seci.MoveNext())
            {
                secName = seci.CurrentKey;
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair <string, string> pair in settings)
                {
                    typeName = pair.Key;
                    archName = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                }
            }
        }
Example #18
0
    private void _OnFullscreenToggled()
    {
        var node  = GetNode("GridContainer/FullscreenCheck") as CheckBox;
        var state = node.Pressed;
        var set   = new ConfigFile();

        set.Load("user://settings.cfg");
        set.SetValue("Main", "Fullscreen", state);
        if (state)
        {
            OS.WindowFullscreen = true;
        }
        else
        {
            OS.WindowFullscreen = false;
            var width  = set.GetValue("Main", "Width");
            var height = set.GetValue("Main", "Height");
            var size   = new Vector2((float)width, (float)height);
        }
    }
Example #19
0
        /// <summary>
        /// Finds and loads the file with the given name.
        /// This will overwrite any existing section+keys with the same value already in our configuration.
        /// </summary>
        /// <param name="name">The name of the file to load</param>
        /// <returns>True if it could be found and loaded, false if not</returns>
        public bool LoadConfiguration(string name)
        {
            string path = FindFile(name);

            if (path == "")
            {
                return(false);
            }

            MDLog.Trace(LOG_CAT, $"Loading config file {path}");
            ConfigFile conFile = new ConfigFile();

            conFile.Load(path);
            foreach (string section in conFile.GetSections())
            {
                foreach (string key in conFile.GetSectionKeys(section))
                {
                    if (!Configuration.ContainsKey(section))
                    {
                        MDLog.Trace(LOG_CAT, $"Adding section {section}");
                        // Add a new section
                        Configuration.Add(section, new Dictionary <string, object>());
                    }

                    if (!Configuration[section].ContainsKey(key))
                    {
                        MDLog.Trace(LOG_CAT, $"Adding section {section} key {key}");
                        // Add a new key
                        Configuration[section].Add(key, conFile.GetValue(section, key));
                    }
                    else
                    {
                        MDLog.Trace(LOG_CAT, $"Overwriting section {section} key {key}");
                        // Overwrite existing key
                        Configuration[section][key] = conFile.GetValue(section, key);
                    }
                }
            }
            return(true);
        }
Example #20
0
        public MogreRenderer(String handle, uint width, uint height)
        {
            _root = new Root("../plugins.cfg", "../ogre.cfg", "../flexrender.log");
            _root.RenderSystem = _root.GetRenderSystemByName("Direct3D9 Rendering Subsystem");
            _root.Initialise(false);

            ConfigFile file = new ConfigFile();

            file.Load("../resources.cfg", "\t:=", true);
            ConfigFile.SectionIterator secIter = file.GetSectionIterator();
            while (secIter.MoveNext())
            {
                String secName = secIter.CurrentKey;
                if (secIter.Current.IsEmpty)
                {
                    continue;
                }
                foreach (var entry in secIter.Current)
                {
                    ResourceGroupManager.Singleton.AddResourceLocation(entry.Value, entry.Key, secName);
                }
                ResourceGroupManager.Singleton.InitialiseResourceGroup(secName);
            }

            _timer = new Timer();

            NameValuePairList config = new NameValuePairList();

            config["externalWindowHandle"] = handle;

            /*
             * config["vsync"] = "False";
             * config["FSAA"] = "2";
             * config["Multithreaded"] = "False";
             */

            _renderWindow = _root.CreateRenderWindow("Mogre Window", width, height, false, config);
            _renderWindow.IsAutoUpdated = false;
        }
Example #21
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        ApplicationPreferences.AddMasterConfiguration(typeof(TimerList), false);
        configFile = ApplicationPreferences.GetMasterConfiguration();
        configFile.Load();

        Build();
        Timers.ItemsDataSource = list;
        selection.Target       = Timers.CurrentSelection;
        cntActive = new ActionController(selection, "", "",
                                         new ActionMonitor(ActionMonitorType.Sensitivity, removeAction,
                                                           new ActionMonitorDefaults(ActionMonitorDefaultsType.NotNullTarget)),
                                         new ActionMonitor(ActionMonitorType.Sensitivity, propertiesAction,
                                                           new ActionMonitorDefaults(ActionMonitorDefaultsType.NotNullTarget))
                                         );
        for (int i = 1; i <= 25; i++)
        {
            Timer tim = new Timer("Timer " + i, 0, 1, i);
            list.Add(tim);
            tim.Active = true;
        }
    }
        public static void Load()
        {
            //Creating ConfigFile
            ConfigFile config = new ConfigFile("config");

            //Load its data.
            config.Load();
            //Getting the config values, and also checking if the config was changed due to it.
            var configChanged = config.TryGet(ref FirstOption, "First option") |
                                config.TryGet(ref SecondOption, "Second option") |
                                config.TryGet(ref ThirdOption, "Third option") |
                                config.TryGet(ref RegularList, "Regular list example") |
                                config.TryGet(ref CustomList, "Custom list example") |
                                config.TryGet(ref RegularDictionary, "Regular dictionary example") |
                                config.TryGet(ref CustomDictionary, "Custom dictionary example");

            if (configChanged)
            {
                config.Save();
            }
            LogConfig();
        }
Example #23
0
        public void TestSaveAsConfiguration()
        {
            string configFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");

            try
            {
                using (Application installerEditor = Application.Launch(InstallerEditorExeUtils.Executable))
                {
                    Window mainWindow = installerEditor.GetWindow("Installer Editor", InitializeOption.NoCache);
                    UIAutomation.Find <MenuBar>(mainWindow, "Application").MenuItem("File", "New").Click();
                    UIAutomation.Find <MenuBar>(mainWindow, "Application").MenuItem("Edit", "Add", "Configurations", "Setup Configuration").Click();
                    Menu mainMenuFile = UIAutomation.Find <MenuBar>(mainWindow, "Application").MenuItem("File");
                    mainMenuFile.Click();
                    Assert.IsFalse(mainMenuFile.ChildMenus.Find("Save").Enabled);
                    mainMenuFile.ChildMenus.Find("Save As...").Click();
                    Window  openWindow      = mainWindow.ModalWindow("Save As");
                    TextBox filenameTextBox = openWindow.Get <TextBox>("File name:");
                    filenameTextBox.Text = configFileName;
                    openWindow.KeyIn(KeyboardInput.SpecialKeys.RETURN);
                    openWindow.WaitWhileBusy();
                    mainWindow.WaitWhileBusy();
                    Assert.IsTrue(File.Exists(configFileName));
                    Assert.IsTrue(UIAutomation.Find <MenuBar>(mainWindow, "Application").MenuItem("File", "Save").Enabled);
                    StatusStrip    statusStrip = UIAutomation.Find <StatusStrip>(mainWindow, "statusStrip");
                    WinFormTextBox statusLabel = (WinFormTextBox)statusStrip.Items[0];
                    Assert.AreEqual(string.Format("Written {0}", configFileName), statusLabel.Text);
                    ConfigFile savedConfigFile = new ConfigFile();
                    savedConfigFile.Load(configFileName);
                    Assert.AreEqual(1, savedConfigFile.Children.Count);
                }
            }
            finally
            {
                if (File.Exists(configFileName))
                {
                    File.Delete(configFileName);
                }
            }
        }
Example #24
0
    public void LoadAllProfiles()
    {
        if (!Directory.Exists("config/"))
        {
            Directory.CreateDirectory("config/");
        }

        config.Init();
        // Load config
        config.Load();
        ApplyConfig();

        foreach (PlayerProfile profile in savedGames)
        {
            Destroy(profile.gameObject);
        }
        savedGames.Clear();

        if (Directory.Exists("saves/"))
        {
            foreach (string filename in Directory.GetFiles("saves/"))
            {
                PlayerProfile profile = Instantiate <PlayerProfile>(playerProfilePrefab);
                profile.Init();
                profile.name = filename.Remove(0, "saves/".Length).Split('.') [0];
                profile.Load(filename);
                profile.transform.SetParent(transform);
                savedGames.Add(profile);
            }
        }
        else
        {
            Directory.CreateDirectory("saves/");
            Debug.Log("Did not find save directory.");
        }

        savedGames.Sort();
    }
Example #25
0
        private ConfigFile LoadConfig(ConfigFile config)
        {
            config = ConfigFile.Load(config, Macros, SharpGenLogger);

            var sdkResolver = new SdkResolver(SharpGenLogger);

            SharpGenLogger.Message("Resolving SDKs...");
            foreach (var cfg in config.ConfigFilesLoaded)
            {
                SharpGenLogger.Message("Resolving SDK for Config {0}", cfg);
                foreach (var sdk in cfg.Sdks)
                {
                    SharpGenLogger.Message("Resolving {0}: Version {1}", sdk.Name, sdk.Version);
                    foreach (var directory in sdkResolver.ResolveIncludeDirsForSdk(sdk))
                    {
                        SharpGenLogger.Message("Resolved include directory {0}", directory);
                        cfg.IncludeDirs.Add(directory);
                    }
                }
            }

            return(config);
        }
Example #26
0
    public void LoadConf()
    {
        GD.Print("Loading settings....");
        ConfigFile saveConf = new ConfigFile();

        saveConf.Load("user://userConfig.ini");
        difficulty       = (int)saveConf.GetValue("Game", "Difficulty", difficulty);
        mouseSensitivity = (float)saveConf.GetValue("Controls", "LookSensitivity", mouseSensitivity);
        AudioServer.SetBusVolumeDb(0, (float)saveConf.GetValue("Audio", "MasterVolume", AudioServer.GetBusVolumeDb(0)));
        AudioServer.SetBusVolumeDb(1, (float)saveConf.GetValue("Audio", "BgmVolume", AudioServer.GetBusVolumeDb(1)));
        AudioServer.SetBusVolumeDb(2, (float)saveConf.GetValue("Audio", "SfxVolume", AudioServer.GetBusVolumeDb(2)));
        OS.WindowFullscreen        = (bool)saveConf.GetValue("Video", "Fullscreen", OS.WindowFullscreen);
        OS.VsyncEnabled            = (bool)saveConf.GetValue("Video", "VSync", false);
        OS.WindowBorderless        = (bool)saveConf.GetValue("Video", "Borderless", false);
        GetViewport().Hdr          = (bool)saveConf.GetValue("Video", "HDR", false);
        GetViewport().Msaa         = (Viewport.MSAA)saveConf.GetValue("Video", "AntiAliasing", Viewport.MSAA.Msaa4x);
        GetViewport().Fxaa         = (bool)saveConf.GetValue("Video", "FXAA", true);
        Engine.TargetFps           = (int)saveConf.GetValue("Video", "TargetFPS", 0);
        Engine.IterationsPerSecond = (int)saveConf.GetValue("Video", "PhysicsRate", 120);
        resolutionScale            = (float)saveConf.GetValue("Video", "ResolutionScale", 1f);
        GetViewport().Size         = new Vector2(OS.WindowSize.x * resolutionScale, OS.WindowSize.y * resolutionScale);
        GD.Print("Loaded");
    }
    public override void _Ready()
    {
        continueButton = FindNode("Continue") as Button;
        newGameButton  = FindNode("NewGame") as Button;
        loadGameButton = FindNode("LoadGame") as Button;
        optionsButton  = FindNode("Options") as Button;
        exitButton     = FindNode("Exit") as Button;

        continueButton.Connect("pressed", this, nameof(_ContinueButtonPressed));
        newGameButton.Connect("pressed", this, nameof(_NewGameButtonPressed));
        loadGameButton.Connect("pressed", this, nameof(_LoadGameButtonPressed));
        optionsButton.Connect("pressed", this, nameof(_OptionsButtonPressed));
        exitButton.Connect("pressed", this, nameof(_ExitButtonPressed));

        if (cf.Load("user://" + cfName) != Error.Ok)
        {
            Save();
        }
        else
        {
            Load();
        }
    }
Example #28
0
        public void FakeTest2()
        {
            // Arrange
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string configName    = Settings.DefaultConfigName;

            configName = Path.Combine(baseDirectory, configName);
            string sqliteFile = "webgoat_coins.sqlite";

            sqliteFile = Path.Combine(baseDirectory, sqliteFile);
            string[] lines =
            {
                "dbtype=Sqlite",
                "filename=" + sqliteFile
            };
            File.WriteAllLines(configName, lines);
            ConfigFile configFile = new ConfigFile(configName);

            configFile.Load();
            IDbProvider dbProvider   = DbProviderFactory.Create(configFile);
            string      fakeEmail    = "someone@somewhere";
            string      fakePassword = DateTime.Now.ToString();
            string      goodEmail    = "*****@*****.**";
            string      goodPassword = Encoder.Decode("MTIzNDU2");
            string      hackEmail    = "' or 1 = 1 --";
            string      hackPassword = "";

            // Act
            bool loginFail = dbProvider.IsValidCustomerLogin(fakeEmail, fakePassword);
            bool loginOk   = dbProvider.IsValidCustomerLogin(goodEmail, goodPassword);
            bool hackFail  = dbProvider.IsValidCustomerLogin(hackEmail, hackPassword);

            // Assert
            Assert.IsTrue(loginOk);
            Assert.IsFalse(loginFail);
            Assert.IsFalse(hackFail);
        }
        /// <summary>
        /// Finds and loads the file with the given name.
        /// This will overwrite any existing section+keys with the same value already in our configuration.
        /// </summary>
        /// <param name="name">The name of the file to load</param>
        /// <returns>True if it could be found and loaded, false if not</returns>
        public bool LoadConfiguration(string name)
        {
            String path = FindFile(name);

            if (path == "")
            {
                return(false);
            }

            ConfigFile conFile = new ConfigFile();

            conFile.Load(path);
            foreach (string section in conFile.GetSections())
            {
                foreach (string key in conFile.GetSectionKeys(section))
                {
                    if (!Configuration.ContainsKey(section))
                    {
                        // Add a new section
                        Configuration.Add(section, new Dictionary <string, object>());
                    }

                    if (!Configuration[section].ContainsKey(key))
                    {
                        // Add a new key
                        Configuration[section].Add(key, conFile.GetValue(section, key));
                    }
                    else
                    {
                        // Overwrite existing key
                        Configuration[section][key] = conFile.GetValue(section, key);
                    }
                }
            }
            return(true);
        }
    // Start is called before the first frame update
    void Start()
    {
        if (!ConfigFile.IsLoaded)
        {
            ConfigFile.Load();
        }

        loadingLeft  = GameObject.Find("LoadingLeft").GetComponent <RectTransform>();
        loadingRight = GameObject.Find("LoadingRight").GetComponent <RectTransform>();

        Bg1.SetColor(ThemeColors.Pink);
        Bg2.SetColor(ThemeColors.Blue);
        Bg3.SetColor(ThemeColors.Yellow);

        Pools.GameSettingOptions = ScriptableObject.CreateInstance <ObjectPooler>();
        Pools.GameSettingOptions.SetPool(OptionBase, 10, true, this.gameObject);

        GameSettingsScreen.Initialize(Selection, ConfirmReject);
        GameSettingsScreen.SetConfig(ConfigFile.GetTable(Defines.GameConfig));

        ConfirmReject.SetActive(false);

        init = true;
    }
Example #31
0
        /// <summary>
        /// Initializes the specified instance with a config root file.
        /// </summary>
        /// <returns>true if the config or assembly changed from the last run; otherwise returns false</returns>
        public bool Init()
        {
            _thisAssemblyPath  = Assembly.GetExecutingAssembly().Location;
            _assemblyCheckFile = Path.ChangeExtension(_thisAssemblyPath, ".check");
            _assemblyDatetime  = File.GetLastWriteTime(_thisAssemblyPath);
            _isAssemblyNew     = (File.GetLastWriteTime(_thisAssemblyPath) != File.GetLastWriteTime(_assemblyCheckFile));
            _generatedPath     = Path.GetDirectoryName(_configRootPath);

            Logger.Message("Loading config files...");

#if STORE_APP
            Macros.Add("DIRECTX11_1");
            Macros.Add("STORE_APP");
#else
            Macros.Add("DIRECTX11_1");
            Macros.Add("DESKTOP_APP");
#endif

            Config = ConfigFile.Load(_configRootPath, Macros.ToArray());
            var latestConfigTime = ConfigFile.GetLatestTimestamp(Config.ConfigFilesLoaded);

            _allConfigCheck = Config.Id + "-CodeGen.check";

            var isConfigFileChanged = !File.Exists(_allConfigCheck) || latestConfigTime > File.GetLastWriteTime(_allConfigCheck);
            if (_isAssemblyNew)
            {
                Logger.Message("Assembly [{0}] changed. All files will be generated", _thisAssemblyPath);
            }
            else if (isConfigFileChanged)
            {
                Logger.Message("Config files [{0}] changed", string.Join(",", Config.ConfigFilesLoaded.Select(file => Path.GetFileName(file.AbsoluteFilePath))));
            }

            // Return true if a config file changed or the assembly changed
            return(isConfigFileChanged || _isAssemblyNew);
        }
Example #32
0
 private void frmConfig_Load(object sender, EventArgs e)
 {
     config.Load();
     foreach (Control item in GetAllControls(this))
     {
         if (item.Tag == null)
         {
             continue;
         }
         string tag = item.Tag.ToString();
         if (tag.StartsWith("."))
         {
             item.Text = config.Get(tag.Remove(0, 1));
         }
         else if (tag.StartsWith(":"))
         {
             ((CheckBox)item).Checked = bool.Parse(config.Get(tag.Remove(0, 1)));
         }
         else if (tag.StartsWith("-"))
         {
             ((NumericUpDown)item).Value = int.Parse(config.Get(tag.Remove(0, 1)));
         }
     }
 }
Example #33
0
        /// <summary>
        /// Process the config file and add all the proper resource locations
        /// </summary>
        private void DefineResources()
        {
            // load the configuration file
            ConfigFile cf = new ConfigFile();

            cf.Load(RESOURCE_FILE, "\t:=", true);

            // process each section in the configuration file
            ConfigFile.SectionIterator itr = cf.GetSectionIterator();
            while (itr.MoveNext())
            {
                string sectionName = itr.CurrentKey;
                ConfigFile.SettingsMultiMap smm = itr.Current;

                // each section is set of key/value pairs
                // value is the resource type (FileSystem, Zip, etc)
                // key is the location of the resource set
                foreach (KeyValuePair <string, string> kv in smm)
                {
                    // add the resource location to Ogre
                    ResourceGroupManager.Singleton.AddResourceLocation(kv.Value, kv.Key, sectionName);
                }
            }
        }
        protected CppModule ParseCpp(ConfigFile config)
        {
            var loaded = ConfigFile.Load(config, new string[0], Logger);

            loaded.GetFilesWithIncludesAndExtensionHeaders(out var configsWithIncludes,
                                                           out var configsWithExtensionHeaders);

            CppHeaderGenerator cppHeaderGenerator = new(TestDirectory.FullName, Ioc);

            var updated = cppHeaderGenerator
                          .GenerateCppHeaders(loaded, configsWithIncludes, configsWithExtensionHeaders)
                          .UpdatedConfigs;

            var castXml = GetCastXml(loaded);

            var macro = new MacroManager(castXml);
            var extensionGenerator = new CppExtensionHeaderGenerator();

            var skeleton = loaded.CreateSkeletonModule();

            macro.Parse(Path.Combine(TestDirectory.FullName, loaded.HeaderFileName), skeleton);

            extensionGenerator.GenerateExtensionHeaders(
                loaded, TestDirectory.FullName, skeleton, configsWithExtensionHeaders, updated
                );

            CppParser parser = new(loaded, Ioc)
            {
                OutputPath = TestDirectory.FullName
            };

            using var xmlReader = castXml.Process(parser.RootConfigHeaderFileName);

            return(parser.Run(skeleton, xmlReader));
        }
    }
Example #35
0
        /// <summary>
        /// Process the config file and add all the proper resource locations
        /// </summary>
        private void DefineResources()
        {
            // load the configuration file
            ConfigFile cf = new ConfigFile();
            cf.Load(RESOURCE_FILE, "\t:=", true);

            // process each section in the configuration file
            ConfigFile.SectionIterator itr = cf.GetSectionIterator();
            while (itr.MoveNext())
            {
                string sectionName = itr.CurrentKey;
                ConfigFile.SettingsMultiMap smm = itr.Current;

                // each section is set of key/value pairs
                // value is the resource type (FileSystem, Zip, etc)
                // key is the location of the resource set
                foreach (KeyValuePair<string, string> kv in smm)
                {
                    // add the resource location to Ogre
                    ResourceGroupManager.Singleton.AddResourceLocation(kv.Value, kv.Key, sectionName);
                }
            }
        }
Example #36
0
        /// <summary>
        /// Creates the folder and file if they don't exist, and either prints some data to it (if it doesn't exist) or reads from it (if it does)
        /// </summary>
        public static void Initialise()
        {
            SetupDictionaries();
            #if DEBUG
            string pkPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ponykart";

            // if a folder doesn't exist there, create it
            if (!Directory.Exists(pkPath))
                Directory.CreateDirectory(pkPath);

            string optionsPath = pkPath + "\\options.ini";
            #else
            string optionsPath = "options.ini";
            #endif

            // create it if the file doesn't exist, and write out some defaults
            if (!File.Exists(optionsPath)) {
                using (FileStream stream = File.Create(optionsPath)) {
                    using (StreamWriter writer = new StreamWriter(stream)) {
                        foreach (KeyValuePair<string, string> pair in defaults) {
                            writer.WriteLine(pair.Key + "=" + pair.Value);
                        }
                    }
                }
                ModelDetail = ModelDetailOption.Medium;
            }
            // otherwise we just read from it
            else {
                ConfigFile cfile = new ConfigFile();
                cfile.Load(optionsPath, "=", true);

                ConfigFile.SectionIterator sectionIterator = cfile.GetSectionIterator();
                sectionIterator.MoveNext();
                foreach (KeyValuePair<string, string> pair in sectionIterator.Current) {
                    dict[pair.Key] = pair.Value;
                }
                ModelDetail = (ModelDetailOption) Enum.Parse(typeof(ModelDetailOption), dict["ModelDetail"], true);
                ShadowDetail = (ShadowDetailOption) Enum.Parse(typeof(ShadowDetailOption), dict["ShadowDetail"], true);

                cfile.Dispose();
                sectionIterator.Dispose();
            }

            #if DEBUG
            // since we sometimes add new options, we want to make sure the .ini file has all of them
            Save();
            #endif
        }
Example #37
0
        void setupResources() {
            // Load resource paths from config file
            var cf = new ConfigFile();
            cf.Load(RESOURCES_CFG, "\t:=", true);

            // Go through all sections & settings in the file
            var seci = cf.GetSectionIterator();
            while (seci.MoveNext()) {
                foreach (var pair in seci.Current) {
                    ResourceGroupManager.Singleton.AddResourceLocation(
                        pair.Value, pair.Key, seci.CurrentKey);
                }
            }
        }
Example #38
0
        public bool Initiliase(bool autoCreateWindow)
        {
            root = new Root();

            ConfigFile cf = new ConfigFile();
            cf.Load("resources.cfg", "\t:=", true);

            // Go through all sections & settings in the file
            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            String secName, typeName, archName;

            // Normally we would use the foreach syntax, which enumerates the values, but in this case we need CurrentKey too;
            while (seci.MoveNext())
            {
                secName = seci.CurrentKey;
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                {
                    typeName = pair.Key;
                    archName = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                }
            }

            //-----------------------------------------------------
            // 3 Configures the application and creates the window
            //-----------------------------------------------------
            string renderSystem = "Direct3D9 Rendering Subsystem";

            if (!FindRenderSystem(renderSystem))
                throw new Exception("Unable to find render system: " + renderSystem);

            //we found it, we might as well use it!
            root.RenderSystem.SetConfigOption("VSync", "Yes");      // graphics card doesn't work so hard, physics engine should be more stable
            root.RenderSystem.SetConfigOption("Full Screen", "No");
            root.RenderSystem.SetConfigOption("Video Mode", "1024 x 768 @ 32-bit colour");

            // scene manager
            sceneManager = root.CreateSceneManager(SceneType.ST_GENERIC);

            // render window
            this.renderWindow = root.Initialise(autoCreateWindow, "GlueEngine");
            return true;
        }
Example #39
0
        protected bool _InitOgre()
        {
            lock (this)
            {
                IntPtr hWnd = IntPtr.Zero;

                foreach (PresentationSource source in PresentationSource.CurrentSources)
                {
                    var hwndSource = (source as HwndSource);
                    if (hwndSource != null)
                    {
                        hWnd = hwndSource.Handle;
                        break;
                    }
                }

                if (hWnd == IntPtr.Zero)
                {
                    return(false);
                }

                CallResourceItemLoaded(new ResourceLoadEventArgs("Engine", 0));

                // load the OGRE engine
                //
                _root = new Root();

                // configure resource paths from : "resources.cfg" file
                //
                var configFile = new ConfigFile();
                configFile.Load("resources.cfg", "\t:=", true);

                // Go through all sections & settings in the file
                //
                ConfigFile.SectionIterator seci = configFile.GetSectionIterator();

                // Normally we would use the foreach syntax, which enumerates the values,
                // but in this case we need CurrentKey too;
                while (seci.MoveNext())
                {
                    string secName = seci.CurrentKey;

                    ConfigFile.SettingsMultiMap settings = seci.Current;
                    foreach (var pair in settings)
                    {
                        string typeName = pair.Key;
                        string archName = pair.Value;
                        ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                    }
                }

                // Configures the application and creates the Window
                // A window HAS to be created, even though we'll never use it.
                //
                bool foundit = false;
                foreach (RenderSystem rs in _root.GetAvailableRenderers())
                {
                    if (rs == null)
                    {
                        continue;
                    }

                    _root.RenderSystem = rs;
                    String rname = _root.RenderSystem.Name;
                    if (rname == "Direct3D9 Rendering Subsystem")
                    {
                        foundit = true;
                        break;
                    }
                }

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

                _root.RenderSystem.SetConfigOption("Full Screen", "No");
                _root.RenderSystem.SetConfigOption("Video Mode", "1024 x 768 @ 32-bit colour");

                _root.Initialise(false);

                var misc = new NameValuePairList();
                misc["externalWindowHandle"] = hWnd.ToString();
                _renderWindow = _root.CreateRenderWindow("OgreImageSource Windows", 0, 0, false, misc);
                _renderWindow.IsAutoUpdated = false;

                InitResourceLoad();
                ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

                this.Dispatcher.Invoke(
                    (MethodInvoker) delegate
                {
                    if (CreateDefaultScene)
                    {
                        //-----------------------------------------------------
                        // 4 Create the SceneManager
                        //
                        //		ST_GENERIC = octree
                        //		ST_EXTERIOR_CLOSE = simple terrain
                        //		ST_EXTERIOR_FAR = nature terrain (depreciated)
                        //		ST_EXTERIOR_REAL_FAR = paging landscape
                        //		ST_INTERIOR = Quake3 BSP
                        //-----------------------------------------------------
                        _sceneManager = _root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
                        _sceneManager.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f);

                        //-----------------------------------------------------
                        // 5 Create the camera
                        //-----------------------------------------------------
                        _camera          = _sceneManager.CreateCamera("DefaultCamera");
                        _camera.Position = new Vector3(0f, 0f, 500f);
                        // Look back along -Z
                        _camera.LookAt(lockat);

                        _camera.NearClipDistance = 5;
                        _camera.FarClipDistance  = 3000f;
                    }

                    //初始化平面
                    PublicPlane.normal = Vector3.UNIT_Z;
                    PublicPlane.d      = 0;

                    IsFrontBufferAvailableChanged += _isFrontBufferAvailableChanged;

                    if (Initialised != null)
                    {
                        Initialised(this, new RoutedEventArgs());
                    }

                    ReInitRenderTarget();
                    AttachRenderTarget(true);

                    OnFrameRateChanged(this.FrameRate);

                    _currentThread = null;
                });


                return(true);
            }
        }
Example #40
0
        public bool Initialise()
        {
            m_Shutdown = false;

            m_Rand = new Random();

            new Mogre.LogManager();
            m_Log = Mogre.LogManager.Singleton.CreateLog("OgreLogfile.log", true, true, false);

            m_Root = new Root();
            ConfigFile cf = new ConfigFile();
            cf.Load("Resources.cfg", "\t:=", true);

            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            while (seci.MoveNext())
            {
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                    ResourceGroupManager.Singleton.AddResourceLocation(pair.Value, pair.Key, seci.CurrentKey);
            }

            if (!m_Root.RestoreConfig())    // comment this line to view configuration dialog box
                if (!m_Root.ShowConfigDialog())
                    return false;

            m_RenderWindow = m_Root.Initialise(true);
            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            m_SceneManager = m_Root.CreateSceneManager(SceneType.ST_GENERIC);
            m_Camera = m_SceneManager.CreateCamera("MainCamera");
            m_Viewport = m_RenderWindow.AddViewport(m_Camera);
            m_Camera.NearClipDistance = 0.1f;
            m_Camera.FarClipDistance = 1000.0f;

            MOIS.ParamList pl = new MOIS.ParamList();
            IntPtr windowHnd;
            m_RenderWindow.GetCustomAttribute("WINDOW", out windowHnd);
            pl.Insert("WINDOW", windowHnd.ToString());

            m_InputManager = MOIS.InputManager.CreateInputSystem(pl);

            m_Keyboard = (MOIS.Keyboard)m_InputManager.CreateInputObject(MOIS.Type.OISKeyboard, true);
            m_Mouse = (MOIS.Mouse)m_InputManager.CreateInputObject(MOIS.Type.OISMouse, true);

            m_NewtonWorld = new World();
            m_NewtonWorld.SetWorldSize(new AxisAlignedBox(-500, -500, -500, 500, 500, 500));
            m_NewtonDebugger = new Debugger(m_NewtonWorld);
            m_NewtonDebugger.Init(m_SceneManager);

            m_GameCamera = new GameCamera();
            m_ObjectManager = new ObjectManager();
            m_StateManager = new StateManager();
            m_PhysicsManager = new PhysicsManager();
            m_SoundDict = new SoundDict();

            /*
             * To co tu mamy nalezy przeniesc jak najszybciej do ogitora
             * Materialy dla kazdej mapy moga byc inne inne parametry inne powiazania itp wiec tworzone
             * sa oddzielnie dla kazdej nowej mapy, a potem przy obiektach konkretny material jest przypsiywany
             * przy starcie ladowania physicsmanager powinien byc wyczyszczony
             */

            //inicjalizacja konkretnych obiektow, w sumie tylko nadanie nazw w dictionary
            m_PhysicsManager.addMaterial("Metal");
            //podstawowe
            m_PhysicsManager.addMaterial("Ground");
            m_PhysicsManager.addMaterial("Trigger");
            m_PhysicsManager.addMaterial("Player");
            m_PhysicsManager.addMaterial("NPC");

            //laczenie materialow w pary
            //dla kazdej mapy rozne powiazania (zapewne beda sie powtarzac ale im wieksza ilosc
            //materialow tym wieksze obciazenie dla silnika wiec nalezy to ograniczac
            //dla kazdej pary materialow mozna ustawic rozne parametry kolizji
            //jak tarcie, elastycznosc, miekkosc kolizji oraz callback ktory jest wywolywany przy kolizji
            m_PhysicsManager.addMaterialPair("Metal", "Metal");
            m_PhysicsManager.getMaterialPair("MetalMetal").SetDefaultFriction(1.5f, 1.4f);
            m_PhysicsManager.setPairCallback("MetalMetal", "MetalCallback");

            //obowiazkowe
            m_PhysicsManager.addMaterialPair("Trigger", "Player");//wyzwalacze pozycja obowiazkowa
            m_PhysicsManager.setPairCallback("TriggerPlayer", "TriggerCallback");

            //obowiazkowe
            m_PhysicsManager.addMaterialPair("Ground", "Player");//ground material podstawowy
            m_PhysicsManager.getMaterialPair("GroundPlayer").SetDefaultElasticity(0);
            m_PhysicsManager.setPairCallback("GroundPlayer", "GroundPlayerCallback");

            // NPC:
            //m_PhysicsManager.addMaterialPair("NPC", "NPC");//ground material podstawowy
            //m_PhysicsManager.getMaterialPair("NPCNPC").SetDefaultElasticity(0);
            //m_PhysicsManager.setPairCallback("NPCNPC", "NPCNPCCallback");

            //m_PhysicsManager.addMaterialPair("Ground", "NPC");//ground material podstawowy
            //m_PhysicsManager.getMaterialPair("GroundNPC").SetDefaultElasticity(0);
            // m_PhysicsManager.setPairCallback("GroundNPC", "GroundPlayerCallback");
            /*
                                    * Koniec inicjalizacji materialow ktora musi sie znalezc w opisie mapy, dla niekumatych w ogitorze.
                                    */

            CreateOgitorScene();
            //CreateScene();

            /*
             *  Rejestracja listenerów
             **/
            m_Root.FrameRenderingQueued += new FrameListener.FrameRenderingQueuedHandler(Update);

            m_Keyboard.KeyPressed += new MOIS.KeyListener.KeyPressedHandler(KeyPressed);
            m_Keyboard.KeyReleased += new MOIS.KeyListener.KeyReleasedHandler(KeyReleased);

            m_Keyboard.KeyPressed += new MOIS.KeyListener.KeyPressedHandler(m_StateManager.KeyPressed);
            m_Keyboard.KeyReleased += new MOIS.KeyListener.KeyReleasedHandler(m_StateManager.KeyReleased);
            m_Mouse.MouseMoved += new MOIS.MouseListener.MouseMovedHandler(m_StateManager.MouseMoved);
            m_Mouse.MousePressed += new MOIS.MouseListener.MousePressedHandler(m_StateManager.MousePressed);
            m_Mouse.MouseReleased += new MOIS.MouseListener.MouseReleasedHandler(m_StateManager.MouseReleased);

            Tools.ConsoleParser.Init();
            m_RenderWindow.SetDeactivateOnFocusChange(false);

            return true;
        }
        private void DefineResources()
        {
            ConfigFile configFile = new ConfigFile();
            configFile.Load("resources.cfg", "\t:=", true);

            var section = configFile.GetSectionIterator();
            while (section.MoveNext())
            {
                foreach (var line in section.Current)
                {
                    ResourceGroupManager.Singleton.AddResourceLocation(
                        line.Value, line.Key, section.CurrentKey);
                }
            }
        }
Example #42
0
        public void Initialise()
        {
            Root = new Root();
            ConfigFile cf = new ConfigFile();
            cf.Load("Resources.cfg", "\t:=", true);

            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            while (seci.MoveNext())
            {
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                    ResourceGroupManager.Singleton.AddResourceLocation(pair.Value, pair.Key, seci.CurrentKey);
            }

            if (!Root.RestoreConfig())
                if (!Root.ShowConfigDialog())
                    return;

            Root.RenderSystem.SetConfigOption("VSync", "Yes");
            RenderWindow = Root.Initialise(true, "Kolejny epicki erpeg");  // @@@@@@@@@@@@@@@ Nazwa okna gry.

            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            SceneManager = Root.CreateSceneManager(SceneType.ST_GENERIC);
            Camera = SceneManager.CreateCamera("MainCamera");
            Viewport = RenderWindow.AddViewport(Camera);
            Camera.NearClipDistance = 0.1f;
            Camera.FarClipDistance = 1000.0f;
            Camera.AspectRatio = ((float)RenderWindow.Width / (float)RenderWindow.Height);

            MOIS.ParamList pl = new MOIS.ParamList();
            IntPtr windowHnd;
            RenderWindow.GetCustomAttribute("WINDOW", out windowHnd);
            pl.Insert("WINDOW", windowHnd.ToString());

            InputManager = MOIS.InputManager.CreateInputSystem(pl);

            Keyboard = (MOIS.Keyboard)InputManager.CreateInputObject(MOIS.Type.OISKeyboard, true);
            Mouse = (MOIS.Mouse)InputManager.CreateInputObject(MOIS.Type.OISMouse, true);

            NewtonWorld = new World();
            NewtonDebugger = new Debugger(NewtonWorld);
            NewtonDebugger.Init(SceneManager);

            GameCamera = new GameCamera();
            ObjectManager = new ObjectManager();

            MaterialManager = new MaterialManager();
            MaterialManager.Initialise();

            Items = new Items();
            PrizeManager = new PrizeManager();  //////////////////// @@ Brand nju staff. Nawet trochę działa :Δ
            CharacterProfileManager = new CharacterProfileManager();
            Quests = new Quests();
            NPCManager = new NPCManager();

            Labeler = new TextLabeler(5);
            Random = new Random();
            HumanController = new HumanController();

            TypedInput = new TypedInput();

            SoundManager = new SoundManager();

            Dialog = new Dialog();
            Mysz = new MOIS.MouseState_NativePtr();
            Conversations = new Conversations();

            TriggerManager = new TriggerManager();

            Engine.Singleton.Keyboard.KeyPressed += new MOIS.KeyListener.KeyPressedHandler(TypedInput.onKeyPressed);
            Mouse.MouseReleased += new MOIS.MouseListener.MouseReleasedHandler(MouseReleased);

            IngameConsole = new IngameConsole();
            IngameConsole.Init();
            IngameConsole.AddCommand("dupa", "soundOddawajPiec");
            IngameConsole.AddCommand("tp", "ZejscieDoPiwnicy");
            IngameConsole.AddCommand("exit", "Exit", "Wychodzi z gry. Ale odkrywcze. Super. Musze sprawdzic jak sie zachowa konsola przy duzej dlugosci linii xD llllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmiiiiiiiiiiiiiiii");
            IngameConsole.AddCommand("play", "playSound", "Odtwarza dzwiek. Skladnia: play <sciezka do pliku>. Np. play other/haa.mp3");
            IngameConsole.AddCommand("map", "ChangeMap");
            IngameConsole.AddCommand("save", "SaveGame");
            IngameConsole.AddCommand("load", "LoadGame");
            IngameConsole.AddCommand("help", "ConsoleHelp");
            IngameConsole.AddCommand("h", "CommandHelp");
        }
        /// <summary>
        /// Go through our media/physicsmaterials/ directory and find all of the material definitions we have, then make objects out
        /// of them and add them to our dictionary.
        /// </summary>
        public void ReadMaterialsFromFiles()
        {
            // since we can run this whenever (like when we're tweaking files), we want to clear this first
            materials.Clear();

            // get all of the filenames of the files in media/physicsmaterials
            IEnumerable<string> files = Directory.EnumerateFiles("media/physicsmaterials/", "*.physmat");

            foreach (string filename in files) {
                // rev up those files
                ConfigFile cfile = new ConfigFile();
                cfile.Load(filename, "=", true);

                ConfigFile.SectionIterator sectionIterator = cfile.GetSectionIterator();
                while (sectionIterator.MoveNext()) {
                    string matname = sectionIterator.CurrentKey;

                    PhysicsMaterial mat = new PhysicsMaterial {
                        Friction = float.Parse(cfile.GetSetting("Friction", matname, PhysicsMaterial.DEFAULT_FRICTION.ToString()), culture),
                        Bounciness = float.Parse(cfile.GetSetting("Bounciness", matname, PhysicsMaterial.DEFAULT_BOUNCINESS.ToString()), culture),
                        AngularDamping = float.Parse(cfile.GetSetting("AngularDamping", matname, PhysicsMaterial.DEFAULT_ANGULAR_DAMPING.ToString()), culture),
                        LinearDamping = float.Parse(cfile.GetSetting("LinearDamping", matname, PhysicsMaterial.DEFAULT_LINEAR_DAMPING.ToString()), culture),
                    };

                    materials[matname] = mat;
                }

                cfile.Dispose();
                sectionIterator.Dispose();
            }
        }
Example #44
0
        protected bool _InitOgre()
        {
            lock (this)
            {
                IntPtr hWnd = IntPtr.Zero;

                foreach (PresentationSource source in PresentationSource.CurrentSources)
                {
                    var hwndSource = (source as HwndSource);
                    if (hwndSource != null)
                    {
                        hWnd = hwndSource.Handle;
                        break;
                    }
                }

                if (hWnd == IntPtr.Zero) return false;

                CallResourceItemLoaded(new ResourceLoadEventArgs("Engine", 0));

                // load the OGRE engine
                //
                _root = new Root();

                // configure resource paths from : "resources.cfg" file
                //
                var configFile = new ConfigFile();
                configFile.Load("resources.cfg", "\t:=", true);

                // Go through all sections & settings in the file
                //
                ConfigFile.SectionIterator seci = configFile.GetSectionIterator();

                // Normally we would use the foreach syntax, which enumerates the values,
                // but in this case we need CurrentKey too;
                while (seci.MoveNext())
                {
                    string secName = seci.CurrentKey;

                    ConfigFile.SettingsMultiMap settings = seci.Current;
                    foreach (var pair in settings)
                    {
                        string typeName = pair.Key;
                        string archName = pair.Value;
                        ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                    }
                }

                // Configures the application and creates the Window
                // A window HAS to be created, even though we'll never use it.
                //
                bool foundit = false;
                foreach (RenderSystem rs in _root.GetAvailableRenderers())
                {
                    if (rs == null) continue;

                    _root.RenderSystem = rs;
                    String rname = _root.RenderSystem.Name;
                    if (rname == "Direct3D9 Rendering Subsystem")
                    {
                        foundit = true;
                        break;
                    }
                }

                if (!foundit)
                    return false;

                _root.RenderSystem.SetConfigOption("Full Screen", "No");
                _root.RenderSystem.SetConfigOption("Video Mode", "1024 x 768 @ 32-bit colour");

                _root.Initialise(false);

                var misc = new NameValuePairList();
                misc["externalWindowHandle"] = hWnd.ToString();
                _renderWindow = _root.CreateRenderWindow("OgreImageSource Windows", 0, 0, false, misc);
                _renderWindow.IsAutoUpdated = false;

                InitResourceLoad();
                ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

                this.Dispatcher.Invoke(
                    (MethodInvoker)delegate
                                       {
                                           if (CreateDefaultScene)
                                           {
                                               //-----------------------------------------------------
                                               // 4 Create the SceneManager
                                               //
                                               //		ST_GENERIC = octree
                                               //		ST_EXTERIOR_CLOSE = simple terrain
                                               //		ST_EXTERIOR_FAR = nature terrain (depreciated)
                                               //		ST_EXTERIOR_REAL_FAR = paging landscape
                                               //		ST_INTERIOR = Quake3 BSP
                                               //-----------------------------------------------------
                                               _sceneManager = _root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
                                               _sceneManager.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f);

                                               //-----------------------------------------------------
                                               // 5 Create the camera
                                               //-----------------------------------------------------
                                               _camera = _sceneManager.CreateCamera("DefaultCamera");
                                               _camera.Position = new Vector3(0f, 0f, 500f);
                                               // Look back along -Z
                                               _camera.LookAt(lockat);

                                               _camera.NearClipDistance = 5;
                                               _camera.FarClipDistance = 3000f;

                                           }

                                           //初始化平面
                                           PublicPlane.normal = Vector3.UNIT_Z;
                                           PublicPlane.d = 0;

                                           IsFrontBufferAvailableChanged += _isFrontBufferAvailableChanged;

                                           if (Initialised != null)
                                               Initialised(this, new RoutedEventArgs());

                                           ReInitRenderTarget();
                                           AttachRenderTarget(true);

                                           OnFrameRateChanged(this.FrameRate);

                                           _currentThread = null;
                                       });

                return true;
            }
        }
Example #45
0
        private void ImportResources()
        {
            ConfigFile config = new ConfigFile();
            config.Load("resources.cfg", "=", true);

            ConfigFile.SectionIterator itr = config.GetSectionIterator();
            while (itr.MoveNext())
            {
                foreach (var line in itr.Current)
                    ResourceGroupManager.Singleton.AddResourceLocation(line.Value, line.Key, itr.CurrentKey);
            }
        }
Example #46
0
        /// Method which will define the source of resources (other than current folder)
        public virtual void SetupResources()
        {
            // Load resource paths from config file
            ConfigFile cf = new ConfigFile();
            cf.Load("resources.cfg", "\t:=", true);

            // Go through all sections & settings in the file
            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            String secName, typeName, archName;

            // Normally we would use the foreach syntax, which enumerates the values, but in this case we need CurrentKey too;
            while (seci.MoveNext())
            {
                secName = seci.CurrentKey;
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                {
                    typeName = pair.Key;
                    archName = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                }
            }
        }
Example #47
0
        public void InitMogre()
        {
            //-----------------------------------------------------
            // 1 enter ogre
            //-----------------------------------------------------
            root = new Root();

            //-----------------------------------------------------
            // 2 configure resource paths
            //-----------------------------------------------------
            ConfigFile cf = new ConfigFile();
            cf.Load("resources.cfg", "\t:=", true);

            // Go through all sections & settings in the file
            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            String secName, typeName, archName;

            // Normally we would use the foreach syntax, which enumerates the values, but in this case we need CurrentKey too;
            while (seci.MoveNext()) {
                secName = seci.CurrentKey;
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings) {
                    typeName = pair.Key;
                    archName = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                }
            }

            //-----------------------------------------------------
            // 3 Configures the application and creates the window
            //-----------------------------------------------------
            bool foundit = false;
            foreach (RenderSystem rs in root.GetAvailableRenderers()) {
                root.RenderSystem = rs;
                String rname = root.RenderSystem.Name;
                if (rname == "Direct3D9 Rendering Subsystem") {
                    foundit = true;
                    break;
                }
            }

            if (!foundit)
                return; //we didn't find it... Raise exception?

            //we found it, we might as well use it!
            root.RenderSystem.SetConfigOption("Full Screen", "No");
            root.RenderSystem.SetConfigOption("Video Mode", "640 x 480 @ 32-bit colour");

            root.Initialise(false);
            NameValuePairList misc = new NameValuePairList();
            misc["externalWindowHandle"] = hWnd.ToString();
            window = root.CreateRenderWindow("Simple Mogre Form Window", 0, 0, false, misc);
            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            //-----------------------------------------------------
            // 4 Create the SceneManager
            //
            //		ST_GENERIC = octree
            //		ST_EXTERIOR_CLOSE = simple terrain
            //		ST_EXTERIOR_FAR = nature terrain (depreciated)
            //		ST_EXTERIOR_REAL_FAR = paging landscape
            //		ST_INTERIOR = Quake3 BSP
            //-----------------------------------------------------
            sceneMgr = root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
            sceneMgr.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f);

            //-----------------------------------------------------
            // 5 Create the camera
            //-----------------------------------------------------
            camera = sceneMgr.CreateCamera("SimpleCamera");
            camera.Position = new Vector3(0f, 0f, 100f);
            // Look back along -Z
            camera.LookAt(new Vector3(0f, 0f, -300f));
            camera.NearClipDistance = 5;

            viewport = window.AddViewport(camera);
            viewport.BackgroundColour = new ColourValue(0.0f, 0.0f, 0.0f, 1.0f);

            Entity ent = sceneMgr.CreateEntity("ogre", "ogrehead.mesh");
            SceneNode node = sceneMgr.RootSceneNode.CreateChildSceneNode("ogreNode");
            node.AttachObject(ent);
        }
        protected virtual void LoadResources()
        {
            // Load resource paths from config file
            var cf = new ConfigFile();
            cf.Load(mResourcesCfg, "\t:=", true);

            // Go through all sections & settings in the file
            var seci = cf.GetSectionIterator();
            while (seci.MoveNext()) {
                foreach (var pair in seci.Current) {
                    ResourceGroupManager.Singleton.AddResourceLocation(
                        pair.Value, pair.Key, seci.CurrentKey);
                }
            }

            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();
        }
Example #49
0
        public void Init(String handle)
        {
            try
            {
                // Create root object
                mRoot = new Root();

                // Define Resources
                ConfigFile cf = new ConfigFile();
                cf.Load("./resources.cfg", "\t:=", true);
                ConfigFile.SectionIterator seci = cf.GetSectionIterator();
                String secName, typeName, archName;

                while (seci.MoveNext())
                {
                    secName = seci.CurrentKey;
                    ConfigFile.SettingsMultiMap settings = seci.Current;
                    foreach (KeyValuePair<string, string> pair in settings)
                    {
                        typeName = pair.Key;
                        archName = pair.Value;
                        ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                    }
                }

                //Load the resources from resources.cfg and selected tab (_ConfigurationPaths)
                //LoadResourceLocations(_ConfigurationPaths);

                //example of manual add: _FileSystemPaths.Add("../../Media/models");
                foreach (string foo in _ConfigurationPaths)
                {
                    AddResourceLocation(foo);
                }

                // Setup RenderSystem
                mRSys = mRoot.GetRenderSystemByName("Direct3D9 Rendering Subsystem");
                //mRSys = mRoot.GetRenderSystemByName("OpenGL Rendering Subsystem");

                // or use "OpenGL Rendering Subsystem"
                mRoot.RenderSystem = mRSys;

                mRSys.SetConfigOption("Full Screen", "No");
                mRSys.SetConfigOption("Video Mode", "800 x 600 @ 32-bit colour");

                // Create Render Window
                mRoot.Initialise(false, "Main Ogre Window");
                NameValuePairList misc = new NameValuePairList();
                misc["externalWindowHandle"] = handle;
                misc["FSAA"] = "4";
                // misc["VSync"] = "True"; //not sure how to enable vsync to remove those warnings in Ogre.log
                mWindow = mRoot.CreateRenderWindow("Main RenderWindow", 800, 600, false, misc);

                // Init resources
                MaterialManager.Singleton.SetDefaultTextureFiltering(TextureFilterOptions.TFO_ANISOTROPIC);
                TextureManager.Singleton.DefaultNumMipmaps = 5;
                ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

                // Create a Simple Scene
                //SceneNode node = null;
                // mMgr = mRoot.CreateSceneManager(SceneType.ST_GENERIC, "SceneManager");
                mMgr = mRoot.CreateSceneManager(SceneType.ST_EXTERIOR_CLOSE, "SceneManager");

                mMgr.AmbientLight = new ColourValue(0.8f, 0.8f, 0.8f);

                mCamera = mMgr.CreateCamera("Camera");
                mWindow.AddViewport(mCamera);

                mCamera.AutoAspectRatio = true;
                mCamera.Viewport.SetClearEveryFrame(false);

                //Entity ent = mMgr.CreateEntity(displayMesh, displayMesh);

                //ent.SetMaterialName(displayMaterial);
                //node = mMgr.RootSceneNode.CreateChildSceneNode(displayMesh + "node");
                //node.AttachObject(ent);

                mCamera.Position = new Vector3(0, 0, 0);
                //mCamera.Position = new Vector3(0, 0, -400);
                mCamera.LookAt(0, 0, 1);

                //Create a single point light source
                Light light2 = mMgr.CreateLight("MainLight");
                light2.Position = new Vector3(0, 10, -25);
                light2.Type = Light.LightTypes.LT_POINT;
                light2.SetDiffuseColour(1.0f, 1.0f, 1.0f);
                light2.SetSpecularColour(0.1f, 0.1f, 0.1f);

                mWindow.WindowMovedOrResized();

                IsInitialized = true;

                // Create the camera's top node (which will only handle position).
                cameraNode = mMgr.RootSceneNode.CreateChildSceneNode();
                cameraNode.Position = new Vector3(0, 0, 0);

                //cameraNode = mMgr->getRootSceneNode()->createChildSceneNode();
                //cameraNode->setPosition(0, 0, 500);

                // Create the camera's yaw node as a child of camera's top node.
                cameraYawNode = cameraNode.CreateChildSceneNode();

                // Create the camera's pitch node as a child of camera's yaw node.
                cameraPitchNode = cameraYawNode.CreateChildSceneNode();

                // Create the camera's roll node as a child of camera's pitch node
                // and attach the camera to it.
                cameraRollNode = cameraPitchNode.CreateChildSceneNode();
                cameraRollNode.AttachObject(mCamera);

                mRaySceneQuery = mMgr.CreateRayQuery(new Ray());
            }
            catch (Exception ex)
            {
                Console.WriteLine("[Error,OgreForm.cs]: " + ex.Message + "," + ex.StackTrace);
            }
        }
Example #50
0
            public bool init()
            {
                // Start with a new root to get this party started
                root = new Root();

                // Configuration buisness
                ConfigFile config = new ConfigFile();
                config.Load("resources.cfg", "\t:=", true);

                // Go through all our configuration settings
                ConfigFile.SectionIterator itor = config.GetSectionIterator();
                string secName, typeName, archName;

                // Move through all of the sections
                while (itor.MoveNext())
                {
                  secName = itor.CurrentKey;
                  ConfigFile.SettingsMultiMap settings = itor.Current;
                  foreach (KeyValuePair<string, string> pair in settings)
                  {
                typeName = pair.Key;
                archName = pair.Value;
                ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                  }
                }

                // Configure our window and set up the RenderSystem
                bool found = false;
                foreach (RenderSystem rs in root.GetAvailableRenderers())
                {
                  root.RenderSystem = rs;
                  string rname = root.RenderSystem.Name;
                  if (rname == "Direct3D9 Rendering Subsystem")
                  {
                found = true;
                break;
                  }
                }

                // If we can't find the DirectX rendering system somethign is seriously wrong
                if (!found)
                  return false;

                root.RenderSystem.SetConfigOption("Full Screen", "No");
                root.RenderSystem.SetConfigOption("Video Mode", "640 x 480 @ 32-bit colour");

                root.Initialise(false);
                NameValuePairList misc = new NameValuePairList();
                misc["externalWindowHandle"] = hWnd.ToString();
                window = root.CreateRenderWindow("Simple Mogre Form Window", 0, 0, false, misc);
                ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

                // Create our SceneManager
                sceneMgr = root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
                sceneMgr.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f);
                sceneMgr.ShadowTechnique = ShadowTechnique.SHADOWTYPE_STENCIL_ADDITIVE;

                // Create the camera
                camMgr = new CamManager();
                camMgr.Initialize(ref sceneMgr);

                viewport = window.AddViewport(camMgr.mainCam);
                viewport.BackgroundColour = new ColourValue(0, 0, 0, 1);

                // Load our stick here
                LoadModel("TEStick.mesh");

                // Set up ground
                Plane plane = new Plane(Mogre.Vector3.UNIT_Y, 0);
                MeshManager.Singleton.CreatePlane("ground", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, plane,
                  1500, 1500, 20, 20, true, 1, 5, 5, Mogre.Vector3.UNIT_Z);
                Entity ground = sceneMgr.CreateEntity("GroundEnt", "ground");
                sceneMgr.RootSceneNode.CreateChildSceneNode().AttachObject(ground);

                ground.SetMaterialName("Examples/Rockwall");
                ground.CastShadows = false;

                // Set up some lights
                Light pointLight = sceneMgr.CreateLight("pointLight");
                pointLight.Type = Light.LightTypes.LT_POINT;
                pointLight.Position = new Mogre.Vector3(0, 150, 250);
                pointLight.DiffuseColour = ColourValue.White;
                pointLight.SpecularColour = ColourValue.White;

                Light directionalLight = sceneMgr.CreateLight("directionalLight");
                directionalLight.Type = Light.LightTypes.LT_DIRECTIONAL;
                directionalLight.DiffuseColour = new ColourValue(.25f, .25f, 0);
                directionalLight.SpecularColour = new ColourValue(.25f, .25f, 0);
                directionalLight.Direction = new Mogre.Vector3(0, -1, 1);

                Light spotLight = sceneMgr.CreateLight("spotLight");
                spotLight.Type = Light.LightTypes.LT_SPOTLIGHT;
                spotLight.DiffuseColour = ColourValue.White;
                spotLight.SpecularColour = ColourValue.White;
                spotLight.Direction = new Mogre.Vector3(-1, -1, 0);
                spotLight.Position = new Mogre.Vector3(300, 300, 0);
                spotLight.SetSpotlightRange(new Degree(35), new Degree(50));

                // Set up our Input
                root.FrameRenderingQueued += new FrameListener.FrameRenderingQueuedHandler(Input);

                // Set up for picking
                raySceneQuery = sceneMgr.CreateRayQuery(new Ray(), SceneManager.WORLD_GEOMETRY_TYPE_MASK);
                if (null == raySceneQuery)
                  return false;
                raySceneQuery.SetSortByDistance(true);

                return true;
            }
Example #51
0
        public void Initialise()
        {
            m_Root = new Root();
            ConfigFile cf = new ConfigFile();
            cf.Load("Resources.cfg", "\t:=", true);

            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            while (seci.MoveNext())
            {
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                    ResourceGroupManager.Singleton.AddResourceLocation(pair.Value, pair.Key, seci.CurrentKey);
            }

            if (!m_Root.RestoreConfig())
                if (!m_Root.ShowConfigDialog())
                    return;

            m_RenderWindow = m_Root.Initialise(true);
            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            m_SceneManager = m_Root.CreateSceneManager(SceneType.ST_GENERIC);
            m_Camera = m_SceneManager.CreateCamera("MainCamera");
            m_Viewport = m_RenderWindow.AddViewport(m_Camera);
            m_Camera.NearClipDistance = 0.1f;
            m_Camera.FarClipDistance = 1000.0f;

            MOIS.ParamList pl = new MOIS.ParamList();
            IntPtr windowHnd;
            m_RenderWindow.GetCustomAttribute("WINDOW", out windowHnd);
            pl.Insert("WINDOW", windowHnd.ToString());

            m_InputManager = MOIS.InputManager.CreateInputSystem(pl);

            m_Keyboard = (MOIS.Keyboard)m_InputManager.CreateInputObject(MOIS.Type.OISKeyboard, false);
            m_Mouse = (MOIS.Mouse)m_InputManager.CreateInputObject(MOIS.Type.OISMouse, false);

            m_NewtonWorld = new World();
            m_NewtonDebugger = new Debugger(m_NewtonWorld);
            m_NewtonDebugger.Init(m_SceneManager);

            m_GameCamera = new GameCamera();
            m_ObjectManager = new ObjectManager();
        }
Example #52
0
        public void InitMogre()
        {
            //-----------------------------------------------------
            // 1 enter ogre
            //-----------------------------------------------------
            root = new Root();

            //-----------------------------------------------------
            // 2 configure resource paths
            //-----------------------------------------------------
            ConfigFile cf = new ConfigFile();
            cf.Load("resources.cfg", "\t:=", true);

            // Go through all sections & settings in the file
            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            String secName, typeName, archName;

            // Normally we would use the foreach syntax, which enumerates the values, but in this case we need CurrentKey too;
            while (seci.MoveNext())
            {
                secName = seci.CurrentKey;
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                {
                    typeName = pair.Key;
                    archName = pair.Value;
                    ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                }
            }

            //-----------------------------------------------------
            // 3 Configures the application and creates the window
            //-----------------------------------------------------
            bool foundit = false;
            foreach (RenderSystem rs in root.GetAvailableRenderers())
            {
                root.RenderSystem = rs;
                String rname = root.RenderSystem.Name;
                if (rname == "Direct3D9 Rendering Subsystem")
                {
                    foundit = true;
                    break;
                }
            }

            if (!foundit)
                return; //we didn't find it... Raise exception?

            //we found it, we might as well use it!
            root.RenderSystem.SetConfigOption("Full Screen", "No");
            root.RenderSystem.SetConfigOption("Video Mode", "640 x 480 @ 32-bit colour");

            root.Initialise(false);
            NameValuePairList misc = new NameValuePairList();
            misc["externalWindowHandle"] = hWnd.ToString();
            window = root.CreateRenderWindow("Simple Mogre Form Window", 0, 0, false, misc);
            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            //-----------------------------------------------------
            // 4 Create the SceneManager
            //
            //		ST_GENERIC = octree
            //		ST_EXTERIOR_CLOSE = simple terrain
            //		ST_EXTERIOR_FAR = nature terrain (depreciated)
            //		ST_EXTERIOR_REAL_FAR = paging landscape
            //		ST_INTERIOR = Quake3 BSP
            //-----------------------------------------------------
            sceneMgr = root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
            sceneMgr.AmbientLight = new ColourValue(1f, 1f, 1f);

            //-----------------------------------------------------
            // 5 Create the camera
            //-----------------------------------------------------
            camera = sceneMgr.CreateCamera("SimpleCamera");
            camera.Position = new Vector3(400f, 0f, 0f);
            // Look back along -Z
            camera.LookAt(new Vector3(-1f, 0f, 0f));
            camera.NearClipDistance = 5;

            viewport = window.AddViewport(camera);
            viewport.BackgroundColour = new ColourValue(0.0f, 0.0f, 0.0f, 1.0f);

            material = MaterialManager.Singleton.Create("front", "General");
            material.GetTechnique(0).GetPass(0).CreateTextureUnitState("snow3.jpg");
            material = MaterialManager.Singleton.Create("other", "General");
            material.GetTechnique(0).GetPass(0).CreateTextureUnitState("snow.jpg");
            material = MaterialManager.Singleton.Create("back", "General");
            material.GetTechnique(0).GetPass(0).CreateTextureUnitState("back2.jpg");

            Vector3 moveVector3 = new Vector3(0f,-60f,110f);
            for (int i = 0; i < cubeCount; i++)
            {
                Cube cube = new Cube();
                cube.CubeName = "cube" + i.ToString();
                cube.BuildCube("front", ref sceneMgr);

                ManualObject manual = sceneMgr.GetManualObject(cube.CubeName);
                manual.ConvertToMesh("cubeMesh"+i.ToString());
                Entity ent = sceneMgr.CreateEntity("box"+i.ToString(), "cubeMesh"+i.ToString());
                SceneNode node = sceneMgr.RootSceneNode.CreateChildSceneNode("boxNode"+i.ToString());
                ent.CastShadows = true;
                node.AttachObject(ent);
                float y = i * (Cube.cubeHeight + 10) + moveVector3.y;
                node.Position = new Vector3(0f, y, moveVector3.z);
            }

            Plane plane = new Plane();
            plane.BuildPlane("back",ref sceneMgr);
            ManualObject manualPlane = sceneMgr.GetManualObject(plane.PlaneName);
            manualPlane.ConvertToMesh("planeMesh");
            Entity planeEntity = sceneMgr.CreateEntity("planeEntity", "planeMesh");
            SceneNode planeNode = sceneMgr.RootSceneNode.CreateChildSceneNode("planeNode");
            planeNode.AttachObject(planeEntity);
        }
Example #53
0
        private void Run(string[] args)
        {
            if (args.Length < 1)
            {
                printUsage();
                return;
            }
            cfgFile = new ConfigFile(args[0]);

            Config  connectionConfig;
            Config  programConfig;
            Message heartbeatMessage;
            Field   tempField;
            string  configValue;
            string  tempSubject;
            //Config Variables
            short globalHeartbeatCount = 0;
            short heartbeatHolder      = 0;
            short heartbeatCountdown   = 0;
            short loopCountdown        = 0;
            short updateRate           = 0;

            //Subscription Callback
            LogCallback cb = new LogCallback();

            //Load Config File
            result = cfgFile.Load();
            check("ConfigFileLoad", result);

            //Look up configuration for the middleware
            result = cfgFile.LookupConfig("connection-config", out connectionConfig);
            check("LookUpConfig", result);

            //Create connection from configuration
            result = ConnectionFactory.Create(connectionConfig, out conn);
            check("Creating Connection", result);

            //Connect to the Network
            result = conn.Connect();
            check("Connect", result);

            //Output Info
            Console.Out.WriteLine(ConnectionFactory.GetAPIVersion());
            Console.Out.WriteLine("Middleware version= " + conn.GetLibraryVersion());

            //Lookup additional program configuration info
            result = cfgFile.LookupConfig("program-config", out programConfig);
            check("LookUpConfig", result);

            //Set Program Config Values
            result = programConfig.GetValue("update-rate", out configValue);
            check("GetValue", result);
            updateRate = Convert.ToInt16(configValue);
            result     = programConfig.GetValue("loop-time", out configValue);
            check("GetValue", result);
            loopCountdown = Convert.ToInt16(configValue);

            //Create Subscriptions from subscriptions in configFile
            result = cfgFile.LookupSubscription("RECEIVE-LOG", out tempSubject);
            check("LookUpSubscription", result);
            result = conn.Subscribe(tempSubject, cb);
            check("Subscribe", result);

            result = cfgFile.LookupSubscription("SEND-LOG", out tempSubject);
            check("LookUpSubscription", result);
            result = conn.Subscribe(tempSubject, cb);
            check("Subscribe", result);

            //Create a generic message container for the heartbeat message
            result = conn.CreateMessage(out heartbeatMessage);
            check("CreateMessage", result);

            //Load Heartbeat Definition
            result = cfgFile.LookupMessage("C2CX-HEARTBEAT-REC", heartbeatMessage);
            check("LookUpMessage", result);

            //Obtain publish rate field from heartbeat message
            result = heartbeatMessage.GetField("PUB-RATE", out tempField);
            if (!result.IsError())
            {
                result = tempField.GetValue(out heartbeatHolder);
                check("GetValue", result);
            }
            else
            {
                //Default Value
                heartbeatHolder = 30;
            }

            //Ouput some Program Info
            Console.Out.WriteLine("Publishing for " + loopCountdown + " seconds.");
            Console.Out.WriteLine("Publishing Heartbeat Messages every " + heartbeatHolder
                                  + " seconds.");

            result = conn.StartAutoDispatch();
            check("Starting AutoDispatch", result);
            Console.Out.WriteLine("Start Time: " + DateTime.Now.ToString());

            //Publish Loop
            for (; loopCountdown > 0; loopCountdown--)
            {
                //When Countdown reaches 0 publish heartbeat & reset
                if (heartbeatCountdown < 1)
                {
                    globalHeartbeatCount++;

                    //Update Message Counter
                    tempField.SetType(GMSECTypeDefs.I32);
                    tempField.SetName("COUNTER");
                    tempField.SetValue(globalHeartbeatCount);
                    result = heartbeatMessage.AddField(tempField);
                    check("AddField", result);

                    //Publish Heartbeat Message
                    result = conn.Publish(heartbeatMessage);
                    check("Publish", result);

                    //Output Heartbeat marker and reset the counter
                    Console.Out.WriteLine("Published Heartbeat");
                    heartbeatCountdown = heartbeatHolder;
                }
                //Decrement the Counters
                heartbeatCountdown -= updateRate;
                //Sleep for 1 second
                System.Threading.Thread.Sleep(updateRate * 1000);
            }
            //EndTime
            Console.Out.WriteLine("End Time: " + DateTime.Now.ToString());
            result = conn.StopAutoDispatch();
            check("StopAutoDispatch", result);
            result = conn.DestroyMessage(heartbeatMessage);
            check("Destory Message", result);
        }
Example #54
0
		protected virtual void LoadResources()
		{
			if (!string.IsNullOrEmpty(ConfigDirectory))
				ResourcesCfg = Path.Combine(ConfigDirectory, ResourcesCfg);

			// Load resource paths from config file
			var cf = new ConfigFile();
			cf.Load(ResourcesCfg);

			// Go through all sections & settings in the file
			var settings =
				from section in cf.GetSections()
				from setting in section.Value
				select new {
					Section = section.Key,
					Setting = setting.Key,
					setting.Value
				};

			foreach (var setting in settings) {
				ResourceGroupManager.Instance.AddResourceLocation(
					setting.Value, setting.Setting, setting.Section);
			}

			ResourceGroupManager.Instance.InitializeAllResourceGroups();
		}
Example #55
0
        public void InitRenderer()
        {
            try
            {
                OgreRoot = new Root();

                {	//Load config file data
                    ConfigFile cf = new ConfigFile();
                    cf.Load("./resources.cfg", "\t:=", true);
                    ConfigFile.SectionIterator seci = cf.GetSectionIterator();
                    String secName, typeName, archName;

                    while (seci.MoveNext())
                    {
                        secName = seci.CurrentKey;
                        ConfigFile.SettingsMultiMap settings = seci.Current;
                        foreach (KeyValuePair<String, String> pair in settings)
                        {
                            typeName = pair.Key;
                            archName = pair.Value;
                            ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
                        }
                    }
                }

                OgreRenderSystem = OgreRoot.GetRenderSystemByName("Direct3D9 Rendering Subsystem");
                OgreRenderSystem.SetConfigOption("Full Screen", "No");
                OgreRenderSystem.SetConfigOption("Video Mode", "800 x 600 @ 32-bit colour");

                OgreRoot.RenderSystem = OgreRenderSystem;
                OgreRoot.Initialise(false, "Main Ogre Window");

                NameValuePairList misc = new NameValuePairList();
                misc["externalWindowHandle"] = RenderPanel.Handle.ToString();
                misc["FSAA"] = "4";
                OgreRenderWindow = OgreRoot.CreateRenderWindow("Main RenderWindow", 800, 600, false, misc);

                OgreRenderWindow.IsActive = true;
                OgreRenderWindow.IsAutoUpdated = true;

                MaterialManager.Singleton.SetDefaultTextureFiltering(TextureFilterOptions.TFO_ANISOTROPIC);

                //Trigger background resource load
                StartResourceThread();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during renderer initialization:" + ex.Message + "," + ex.StackTrace);
            }
        }
Example #56
0
        public void Initialise()
        {
            Root = new Root();
            ConfigFile cf = new ConfigFile();
            cf.Load("Resources.cfg", "\t:=", true);

            ConfigFile.SectionIterator seci = cf.GetSectionIterator();

            while (seci.MoveNext())
            {
                ConfigFile.SettingsMultiMap settings = seci.Current;
                foreach (KeyValuePair<string, string> pair in settings)
                    ResourceGroupManager.Singleton.AddResourceLocation(pair.Value, pair.Key, seci.CurrentKey);
            }

            if (!Root.RestoreConfig())
                if (!Root.ShowConfigDialog())
                    return;

            Root.RenderSystem.SetConfigOption("VSync", "Yes");
            RenderWindow = Root.Initialise(true, "WorldCreator");  // @@@@@@@@@@@@@@@ Nazwa okna gry.
            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            SceneManager = Root.CreateSceneManager(SceneType.ST_GENERIC);
            Camera = SceneManager.CreateCamera("MainCamera");
            Viewport = RenderWindow.AddViewport(Camera);
            Camera.NearClipDistance = 0.1f;
            Camera.FarClipDistance = 1000.0f;
            Camera.AspectRatio = ((float)RenderWindow.Width / (float)RenderWindow.Height);

            MOIS.ParamList pl = new MOIS.ParamList();
            IntPtr windowHnd;
            RenderWindow.GetCustomAttribute("WINDOW", out windowHnd);
            pl.Insert("WINDOW", windowHnd.ToString());

            InputManager = MOIS.InputManager.CreateInputSystem(pl);

            Keyboard = (MOIS.Keyboard)InputManager.CreateInputObject(MOIS.Type.OISKeyboard, false);
            Mouse = (MOIS.Mouse)InputManager.CreateInputObject(MOIS.Type.OISMouse, false);

            NewtonWorld = new World();
            NewtonDebugger = new Debugger(NewtonWorld);
            NewtonDebugger.Init(SceneManager);

            ObjectManager = new ObjectManager();

            MaterialManager = new MaterialManager();
            MaterialManager.Initialise();

            //CharacterProfileManager = new CharacterProfileManager();
            Items = new Items();
            //PrizeManager = new PrizeManager();  //////////////////// @@ Brand nju staff. Nawet trochę działa :Δ
            //Quests = new Quests();
            //NPCManager = new NPCManager();

            Labeler = new TextLabeler(5);

            User = new Player();

            CharacterProfileManager = new CharacterProfileManager();

            NPCManager = new NPCManager();

            HumanController = new HumanController();

            TypedInput = new TypedInput();

            //SoundManager = new SoundManager();
        }