Exemplo n.º 1
0
        public static int Main(string[] args)
        {
            EngineLaunchOptions launchOptions = new EngineLaunchOptions(args);

            ProjectManifest projectManifest;
            string          currentDir   = AppContext.BaseDirectory;
            string          manifestName = null;

            foreach (var file in Directory.EnumerateFiles(currentDir))
            {
                if (file.EndsWith("manifest"))
                {
                    if (manifestName != null)
                    {
                        Console.WriteLine("Error: Multiple project manifests in this directory: " + currentDir);
                        return(-1);
                    }

                    manifestName = file;
                }
            }

            using (var fs = File.OpenRead(manifestName))
                using (var sr = new StreamReader(fs))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        var js = new JsonSerializer();
                        try
                        {
                            projectManifest = js.Deserialize <ProjectManifest>(jtr);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("An error was encountered while loading the project manifest.");
                            Console.WriteLine(e);
                            return(-1);
                        }
                    }

            Game game = new Game();

            AssemblyLoadSystem als = new AssemblyLoadSystem();

            als.LoadFromProjectManifest(projectManifest, AppContext.BaseDirectory);
            game.SystemRegistry.Register(als);

            GraphicsPreferencesProvider graphicsProvider;
            string graphicsProviderName = projectManifest.GraphicsPreferencesProviderTypeName;

            if (graphicsProviderName != null)
            {
                graphicsProvider = GetProvider(als, graphicsProviderName);
            }
            else
            {
                graphicsProvider = new DefaultGraphicsPreferencesProvider();
            }

            var          desiredInitialState = GraphicsPreferencesUtil.MapPreferencesState(graphicsProvider.WindowStatePreference);
            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? (OpenTKWindow) new DedicatedThreadWindow(960, 540, desiredInitialState)
                : new SameThreadWindow(960, 540, desiredInitialState);

            window.Title = "ge.Main";
            GraphicsSystem gs = new GraphicsSystem(window, graphicsProvider);

            game.SystemRegistry.Register(gs);
            window.Closed += game.Exit;

            game.LimitFrameRate = false;

            InputSystem inputSystem = new InputSystem(window);

            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
                if (input.GetKeyDown(Key.F11))
                {
                    window.WindowState = window.WindowState == WindowState.Normal ? WindowState.BorderlessFullScreen : WindowState.Normal;
                }
            });
            game.SystemRegistry.Register(inputSystem);

            SceneLoaderSystem sls = new SceneLoaderSystem(game, game.SystemRegistry.GetSystem <GameObjectQuerySystem>());

            game.SystemRegistry.Register(sls);
            sls.AfterSceneLoaded += () => game.ResetDeltaTime();

            EngineLaunchOptions.AudioEnginePreference?audioPreference = launchOptions.AudioPreference;
            AudioEngineOptions audioEngineOptions =
                !audioPreference.HasValue ? AudioEngineOptions.Default
                : audioPreference == EngineLaunchOptions.AudioEnginePreference.None ? AudioEngineOptions.UseNullAudio
                : AudioEngineOptions.UseOpenAL;
            AudioSystem audioSystem = new AudioSystem(audioEngineOptions);

            game.SystemRegistry.Register(audioSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);

            gs.SetImGuiRenderer(imGuiRenderer);

            AssetSystem assetSystem = new AssetSystem(Path.Combine(AppContext.BaseDirectory, projectManifest.AssetRoot), als.Binder);

            game.SystemRegistry.Register(assetSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);

            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem(projectManifest.PhysicsLayers);

            game.SystemRegistry.Register(ps);

#if DEBUG
            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);
            game.SystemRegistry.Register(ccs);
#endif

            game.SystemRegistry.Register(new SynchronizationHelperSystem());

            SceneAsset scene;
            AssetID    mainSceneID = projectManifest.OpeningScene.ID;
            if (mainSceneID.IsEmpty)
            {
                var scenes = assetSystem.Database.GetAssetsOfType(typeof(SceneAsset));
                if (!scenes.Any())
                {
                    Console.WriteLine("No scenes were available to load.");
                    return(-1);
                }
                else
                {
                    mainSceneID = scenes.First();
                }
            }

            scene = assetSystem.Database.LoadAsset <SceneAsset>(mainSceneID);
            scene.GenerateGameObjects();

            RunStartupFunctions(projectManifest, als, game);

            game.RunMainLoop();

            return(0);
        }
Exemplo n.º 2
0
        public GlitchDemo()
        {
            // Window & Graphics Device
            // --------------------------------------------------
            WindowCreateInfo windowCI = new WindowCreateInfo
            {
                X                  = 50,
                Y                  = 50,
                WindowWidth        = 960,
                WindowHeight       = 540,
                WindowInitialState = WindowState.Normal,
                WindowTitle        = "Glitch Demo"
            };
            GraphicsDeviceOptions gdOptions = new GraphicsDeviceOptions(false, null, false, ResourceBindingModel.Improved, true);

#if DEBUG
            gdOptions.Debug = true;
#endif

            VeldridStartup.CreateWindowAndGraphicsDevice(
                windowCI,
                gdOptions,
                //GraphicsBackend.Metal,
                //GraphicsBackend.Vulkan,
                GraphicsBackend.OpenGL,
                //GraphicsBackend.OpenGLES,
                out _window,
                out _gd);
            _window.Resized += () => _windowResized = true;


            // Project Manifest
            // --------------------------------------------------
            ProjectManifest projectManifest;
            string          currentDir   = AppContext.BaseDirectory;
            string          manifestName = null;

            foreach (var file in Directory.EnumerateFiles(currentDir + "Assets"))
            {
                if (file.EndsWith("manifest"))
                {
                    if (manifestName != null)
                    {
                        string errorMessage = "Error: Multiple project manifests in this directory: " + currentDir;
                        Console.WriteLine(errorMessage);
                        throw new System.Exception(errorMessage);
                    }
                    manifestName = file;
                }
            }

            using (var fs = File.OpenRead(manifestName))
                using (var sr = new StreamReader(fs))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        var js = new JsonSerializer();
                        try
                        {
                            projectManifest = js.Deserialize <ProjectManifest>(jtr);
                        }
                        catch (Exception e)
                        {
                            string errorMessage = "An error was encountered while loading the project manifest.";
                            Console.WriteLine(errorMessage);
                            Console.WriteLine(e);
                            throw new System.NullReferenceException(errorMessage);
                        }
                    }

            // Initialize Game()
            // --------------------------------------------------
            _game = new Game();

            // Assembly & Asset System
            // --------------------------------------------------
            AssemblyLoadSystem als = new AssemblyLoadSystem();
            als.LoadFromProjectManifest(projectManifest, AppContext.BaseDirectory);
            _game.SystemRegistry.Register(als);

            AssetSystem assetSystem = new AssetSystem(Path.Combine(AppContext.BaseDirectory, projectManifest.AssetRoot), als.Binder);
            _game.SystemRegistry.Register(assetSystem);

            // Graphics System
            // --------------------------------------------------
            _gs = new GraphicsSystem(_gd);
            _game.SystemRegistry.Register(_gs);

            // Scene
            // --------------------------------------------------
            _scene = new Scene(_gd, _window.Width, _window.Height);

            // [For Debugging] - Custom SceneAsset Serializer
            // --------------------------------------------------
            SceneAsset programaticSceneAsset = new SceneAsset();
            programaticSceneAsset.Name = "MainMenu";
            // Custom GameObject (for camera & skybox)
            GameObject go1 = new GameObject();
            go1.Name    = "PlayerCamera";
            go1.Enabled = true;
            // Add custom camera to GameObject
            Camera camera = new Camera();
            camera.WindowHeight = _window.Height;
            camera.WindowWidth  = _window.Width;
            go1.AddComponent(camera);
            go1.Transform.LocalPosition = new Vector3(0f, 0f, 0f);
            // Add custom skybox to GameObject
            Skybox skybox = Skybox.LoadDefaultSkybox(_game.SystemRegistry);
            go1.AddComponent(skybox);
            // Custom GameObject (for sphere mesh)
            GameObject go2 = new GameObject();
            go2.Name    = "My Sphere";
            go2.Enabled = true;
            // Add custom sphere MeshRenderer component to GameObject
            Vector3    scale2           = new Vector3(1f);
            Vector3    offset2          = new Vector3(0f, 0f, -5f);
            Quaternion rotation2        = Quaternion.Identity;
            var        meshAssetID2     = new AssetID("Internal:SphereModel");
            var        meshAssetRef2    = new AssetRef <MeshData>(meshAssetID2);
            var        textureAssetID2  = new AssetID("Textures/rust.jpg");
            var        textureAssetRef2 = new AssetRef <ImageSharpTexture>(textureAssetID2);
            go2.Transform.LocalPosition = offset2;
            go2.Transform.LocalRotation = rotation2;
            go2.Transform.LocalScale    = scale2;
            MeshRenderer meshrenderer2 = new MeshRenderer(meshAssetRef2, textureAssetRef2);
            go2.AddComponent(meshrenderer2);
            // Custom GameObject (for plane mesh)
            GameObject go3 = new GameObject();
            go3.Name    = "My Plane Model";
            go3.Enabled = true;
            // Add custom Plane MeshRenderer component to GameObject
            Vector3    scale3           = new Vector3(10f);
            Vector3    offset3          = new Vector3(0f, -1f, -5f);
            Quaternion rotation3        = Quaternion.Identity;
            var        meshAssetID3     = new AssetID("Internal:PlaneModel");
            var        meshAssetRef3    = new AssetRef <MeshData>(meshAssetID3);
            var        textureAssetID3  = new AssetID("Textures/Wood.png");
            var        textureAssetRef3 = new AssetRef <ImageSharpTexture>(textureAssetID3);
            go3.Transform.LocalPosition = offset3;
            go3.Transform.LocalRotation = rotation3;
            go3.Transform.LocalScale    = scale3;
            MeshRenderer meshrenderer3 = new MeshRenderer(meshAssetRef3, textureAssetRef3);
            go3.AddComponent(meshrenderer3);
            // Custom GameObject (another sphere mesh)
            GameObject go4 = new GameObject();
            go4.Name    = "Another Sphere";
            go4.Enabled = true;
            Vector3    scale4           = new Vector3(0.5f);
            Vector3    offset4          = new Vector3(2f, -0.5f, -3f);
            Quaternion rotation4        = Quaternion.Identity;
            var        meshAssetID4     = new AssetID("Internal:SphereModel");
            var        meshAssetRef4    = new AssetRef <MeshData>(meshAssetID4);
            var        textureAssetID4  = new AssetID("Textures/rust.jpg");
            var        textureAssetRef4 = new AssetRef <ImageSharpTexture>(textureAssetID4);
            go4.Transform.LocalPosition = offset4;
            go4.Transform.LocalRotation = rotation4;
            go4.Transform.LocalScale    = scale4;
            MeshRenderer meshrenderer4 = new MeshRenderer(meshAssetRef4, textureAssetRef4);
            go4.AddComponent(meshrenderer4);
            // Add custom GameObject to SceneAsset
            SerializedGameObject sgo1 = new SerializedGameObject(go1);
            SerializedGameObject sgo2 = new SerializedGameObject(go2);
            SerializedGameObject sgo3 = new SerializedGameObject(go3);
            SerializedGameObject sgo4 = new SerializedGameObject(go4);
            programaticSceneAsset.GameObjects    = new SerializedGameObject[4];
            programaticSceneAsset.GameObjects[0] = sgo1;
            programaticSceneAsset.GameObjects[1] = sgo2;
            programaticSceneAsset.GameObjects[2] = sgo3;
            programaticSceneAsset.GameObjects[3] = sgo4;
            // Serialize SceneAsset
            LooseFileDatabase lfd          = new LooseFileDatabase("/Assets");
            StringWriter      stringwriter = new StringWriter(new StringBuilder());
            using (StreamWriter file = File.CreateText(@"DebugSceneAsset.json"))
            {
                JsonSerializer serializer = lfd.DefaultSerializer;
                serializer.Serialize(file, programaticSceneAsset);
            }

            // Scene Assets
            // --------------------------------------------------
            SceneAsset sceneAsset;
            AssetID    mainSceneID = projectManifest.OpeningScene.ID;
            if (mainSceneID.IsEmpty)
            {
                var scenes = assetSystem.Database.GetAssetsOfType(typeof(SceneAsset));
                if (!scenes.Any())
                {
                    Console.WriteLine("No scenes were available to load.");
                    throw new System.Exception("No scenes were available to load.");
                }
                else
                {
                    mainSceneID = scenes.First();
                }
            }

            var readSceneFromProgramaticAsset = true;
            sceneAsset = assetSystem.Database.LoadAsset <SceneAsset>(mainSceneID);
            _scene.LoadSceneAsset(readSceneFromProgramaticAsset ? programaticSceneAsset : sceneAsset);
            _gs.SetCurrentScene(_scene);

            // GUI
            // --------------------------------------------------
            _igRenderable   = new ImGuiRenderable(_window.Width, _window.Height);
            _resizeHandled += (w, h) => _igRenderable.WindowResized(w, h);
            _scene.AddRenderable(_igRenderable);
            _scene.AddUpdateable(_igRenderable);

            // Duplicate Screen (for post-processing filters)
            // --------------------------------------------------
            ScreenDuplicator duplicator = new ScreenDuplicator();
            _scene.AddRenderable(duplicator);

            // TODO: rename FullScreenQuad to FinalBufferObject or something
            _fsq = new FullScreenQuad();
            _scene.AddRenderable(_fsq);

            CreateAllObjects();
        }