Exemplo n.º 1
0
        public void GEALOSinit()
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                Console.WriteLine($"There was an issue initilizing SDL. {SDL.SDL_GetError()}");
                Environment.Exit(-1);
            }

            if (SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_PNG |
                                   SDL_image.IMG_InitFlags.IMG_INIT_TIF | SDL_image.IMG_InitFlags.IMG_INIT_WEBP) < 0)
            {
                Console.WriteLine($"There was an issue initilizing SDL_image. {SDL.SDL_GetError()}");
                Environment.Exit(-1);
            }

            if (SDL_ttf.TTF_Init() < 0)
            {
                Console.WriteLine($"There was an issue initilizing SDL_ttf. {SDL.SDL_GetError()}");
                Environment.Exit(-1);
            }

            if (SDL_mixer.Mix_OpenAudio(22050, SDL_mixer.MIX_DEFAULT_FORMAT, 2, 4096) < 0 ||
                SDL_mixer.Mix_Init(SDL_mixer.MIX_InitFlags.MIX_INIT_FLAC | SDL_mixer.MIX_InitFlags.MIX_INIT_MID |
                                   SDL_mixer.MIX_InitFlags.MIX_INIT_MOD | SDL_mixer.MIX_InitFlags.MIX_INIT_MP3 |
                                   SDL_mixer.MIX_InitFlags.MIX_INIT_OGG | SDL_mixer.MIX_InitFlags.MIX_INIT_OPUS) < 0)
            {
                Console.WriteLine($"There was an issue initilizing SDL_mixer. {SDL.SDL_GetError()}");
                Environment.Exit(-1);
            }

            running = true;

            GEALOSprog();
        }
Exemplo n.º 2
0
Arquivo: Game.cs Projeto: MrK3w/Csharp
        private static bool InitSDL(ref IntPtr win, ref IntPtr ren)
        {
            SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, "1");
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                Console.WriteLine("SDL_Init Error: {0}", SDL.SDL_GetError());
                return(false);
            }

            win = SDL.SDL_CreateWindow("SDL in C#", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, scene.WidthInPixels, scene.HeightInPixels,
                                       SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE);
            if (win == IntPtr.Zero)
            {
                Console.WriteLine("SDL_CreateWindow Error: {0}", SDL.SDL_GetError());
                return(false);
            }

            ren = SDL.SDL_CreateRenderer(win, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);
            if (ren == IntPtr.Zero)
            {
                Console.WriteLine("SDL_CreateRenderer Error: {0}", SDL.SDL_GetError());
                return(false);
            }

            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            return(true);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Basic constructor
        /// </summary>
        public Output()
        {
#if DEBUG
            SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, "1");
#endif

            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO) < 0)
            {
                Logger.Fatal(nameof(SDL.SDL_Init));
            }

            if (SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG) != (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG)
            {
                SDL.SDL_SetError("IMG_Init failed.");
                Logger.Fatal(nameof(SDL_image.IMG_Init));
            }

            Window = SDL.SDL_CreateWindow("LogicGates", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
                                          Dimensions.Canvas.Width, Dimensions.Canvas.Height, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);

            if (Window == IntPtr.Zero)
            {
                Logger.Fatal(nameof(SDL.SDL_CreateWindow),
                             () => ReleaseAndQuit(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }

            Renderer = SDL.SDL_CreateRenderer(Window, -1,
                                              SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);

            if (Renderer == IntPtr.Zero)
            {
                Logger.Fatal(nameof(SDL.SDL_CreateRenderer),
                             () => ReleaseAndQuit(Window, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }
        }
Exemplo n.º 4
0
        private bool InitializeSdl()
        {
            int result;

            try
            {
                result = SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING);
            }
            catch (DllNotFoundException)
            {
                LogSdlError("Не найдена SDL2.dll в каталоге приложения.");
                return(false);
            }

            if (result != 0)
            {
                LogSdlError("Ошибка инциализации SDL");
                return(false);
            }

            result = SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            if (((int)SDL_image.IMG_InitFlags.IMG_INIT_PNG & result) != (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG)
            {
                LogSdlError("Ошибка инциализации SDL Image");
                return(false);
            }

            return(true);
        }
Exemplo n.º 5
0
        private static bool Init()
        {
            //Initialization flag
            bool success = true;

            //Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
                success = false;
            }
            else
            {
                //Set texture filtering to linear
                if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "1") == SDL.SDL_bool.SDL_FALSE)
                {
                    Console.WriteLine("Warning: Linear texture filtering not enabled!");
                }

                //Create window
                _Window = SDL.SDL_CreateWindow("SDL Tutorial", SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                                               SCREEN_WIDTH, SCREEN_HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);
                if (_Window == IntPtr.Zero)
                {
                    Console.WriteLine("Window could not be created! SDL_Error: {0}", SDL.SDL_GetError());
                    success = false;
                }
                else
                {
                    //Create vsynced renderer for window
                    var renderFlags = SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC;
                    Renderer = SDL.SDL_CreateRenderer(_Window, -1, renderFlags);
                    if (Renderer == IntPtr.Zero)
                    {
                        Console.WriteLine("Renderer could not be created! SDL Error: {0}", SDL.SDL_GetError());
                        success = false;
                    }
                    else
                    {
                        //Initialize renderer color
                        SDL.SDL_SetRenderDrawColor(Renderer, 0xFF, 0xFF, 0xFF, 0xFF);

                        //Initialize PNG loading
                        var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
                        if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                        {
                            Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                            success = false;
                        }
                    }
                }
            }

            return(success);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes SDL2.
        /// </summary>
        private void InitSDL()
        {
            //Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                throw new Exception($"SDL could not initialize! SDL_Error: {SDL.SDL_GetError()}");
            }
            else
            {
                //Set texture filtering to linear
                if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "1") == SDL.SDL_bool.SDL_FALSE)
                {
                    throw new Exception("Warning: Linear texture filtering not enabled!");
                }

                //Create window

                /*Usually the SDL.SDL_CreateWindow() method is used to create a window to render to.  In
                 * this case, the method below is used to render to a window using the pointer to that
                 * window as the parameter.  This this case, the pointer below _renderSurfacePtr ends
                 * up being the pointer to the WPF window which is the MainWindow.xaml file.
                 */
                _windowPtr = SDL.SDL_CreateWindowFrom(_renderSurfacePtr);

                if (_windowPtr == IntPtr.Zero)
                {
                    throw new Exception($"Window could not be created! SDL_Error: {SDL.SDL_GetError()}");
                }
                else
                {
                    //Create vsynced renderer for window
                    var renderFlags = SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED;
                    _rendererPtr = SDL.SDL_CreateRenderer(_windowPtr, -1, renderFlags);

                    if (_rendererPtr == IntPtr.Zero)
                    {
                        throw new Exception($"Renderer could not be created! SDL Error: {SDL.SDL_GetError()}");
                    }
                    else
                    {
                        //Initialize renderer color
                        SDL.SDL_SetRenderDrawColor(_rendererPtr, 48, 48, 48, 255);

                        //Initialize PNG loading
                        var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;

                        if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                        {
                            throw new Exception($"SDL_image could not initialize! SDL_image Error: {SDL.SDL_GetError()}");
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        private static bool init()
        {
            //Initialization flag
            bool success = true;

            //Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
                success = false;
            }
            else
            {
                //Set texture filtering to linear
                if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "1") == SDL.SDL_bool.SDL_FALSE)
                {
                    Console.WriteLine("Warning: Linear texture filtering not enabled!");
                }

                //Create window
                if (!gWindow.init())
                {
                    Console.WriteLine("Window could not be created! SDL_Error: {0}", SDL.SDL_GetError());
                    success = false;
                }
                else
                {
                    //Create renderer for window
                    gRenderer = gWindow.createRenderer();
                    if (gRenderer == IntPtr.Zero)
                    {
                        Console.WriteLine("Renderer could not be created! SDL Error: {0}", SDL.SDL_GetError());
                        success = false;
                    }
                    else
                    {
                        //Initialize renderer color
                        SDL.SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

                        //Initialize PNG loading
                        var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
                        if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                        {
                            Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                            success = false;
                        }
                    }
                }
            }

            return(success);
        }
Exemplo n.º 8
0
        private static void Main(string[] args)
        {
            SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING);
            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            var gameWindow = new GameWindow();

            gameWindow.Initialize();
            gameWindow.FrameLoop();

            SDL_image.IMG_Quit();
            SDL.SDL_Quit();
        }
Exemplo n.º 9
0
 public static void Start()
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         SetProcessDpiAwareness(2);
     }
     SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
     SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "linear");
     SDL_ttf.TTF_Init();
     SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG);
     asyncCallbacksAdded = SDL.SDL_RegisterEvents(1);
     SynchronizationContext.SetSynchronizationContext(new UiSyncronizationContext());
     mainThreadId = Thread.CurrentThread.ManagedThreadId;
 }
Exemplo n.º 10
0
        public void OpenImage()
        {
            var initResult = SDL_image.IMG_Init((int)SDL_image.IMG_InitFlags.IMG_INIT_PNG);
            var image      = SDL_image.IMG_Load("./Hi.png");

            Assert.NotEqual(IntPtr.Zero, image);

            var imageSurface = Marshal.PtrToStructure <SDL_surface.SDL_Surface>(image);

            Assert.Equal(400, imageSurface.w);
            Assert.Equal(400, imageSurface.h);

            SDL_image.IMG_Quit();
        }
Exemplo n.º 11
0
        private static void InitSDL2()
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
            }
            else
            {
                Console.WriteLine("SDL initialized!");
            }

            // OPTIONAL: init SDL_image
            var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_JPG | SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_WEBP;

            if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
            {
                Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
            }
            else
            {
                Console.WriteLine("SDL_image initialized!");
            }

            // OPTIONAL: init SDL_ttf

            if (SDL_ttf.TTF_Init() == -1)
            {
                Console.WriteLine("SDL_ttf could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
            }
            else
            {
                Console.WriteLine("SDL_ttf initialized!");
            }

            // OPTIONAL: init SDL_mixer
            if (SDL_mixer.Mix_OpenAudio(44100, SDL_mixer.MIX_DEFAULT_FORMAT, 2, 2048) < 0)
            {
                Console.WriteLine("SDL_mixer could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
            }
            else
            {
                Console.WriteLine("SDL_mixer initialized!");
            }

            if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "1") == SDL.SDL_bool.SDL_FALSE)
            {
                Console.WriteLine("Warning: Linear texture filtering not enabled!");
            }
        }
Exemplo n.º 12
0
        public override void Initialize()
        {
            TypeO.RequireTypeO(new Core.Engine.Version(0, 1, 1));
            TypeO.RequireModule <DesktopModule>(new Core.Engine.Version(0, 1, 1));
            TypeO.AddService <ISDLService, SDLService>();
            ((ISDLService)TypeO.Context.Services[typeof(ISDLService)]).Option = Option;

            //Initial SDL
            foreach (var hint in Option.Hints)
            {
                SDL2.SDL.SDL_SetHint(hint.Key, hint.Value);
            }

            foreach (var eventState in Option.EventStates)
            {
                SDL2.SDL.SDL_EventState(eventState.Key, eventState.Value);
            }

            if (SDL2.SDL.SDL_Init(Option.SDLInitFlags) != 0)
            {
                var message = $"SDL_Init Error: {SDL2.SDL.SDL_GetError()}";
                Logger.Log(LogLevel.Fatal, message);
                TypeO.Context.Exit();
                throw new ApplicationException(message);
            }

            if (SDL_image.IMG_Init(Option.IMGInitFlags) == 0)
            {
                var message = $"IMG_Init Error: {SDL2.SDL.SDL_GetError()}";
                Logger.Log(LogLevel.Fatal, message);
                TypeO.Context.Exit();
                throw new ApplicationException(message);
            }

            if (SDL_ttf.TTF_Init() != 0)
            {
                var message = $"TTF_Init Error: {SDL2.SDL.SDL_GetError()}";
                Logger.Log(LogLevel.Fatal, message);
                TypeO.Context.Exit();
                throw new ApplicationException(message);
            }
        }
Exemplo n.º 13
0
        private static bool Init()
        {
            //Initialization flag
            bool success = true;

            //Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
                success = false;
            }
            else
            {
                //Create window
                _Window = SDL.SDL_CreateWindow("SDL Tutorial", SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                                               SCREEN_WIDTH, SCREEN_HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);
                if (_Window == IntPtr.Zero)
                {
                    Console.WriteLine("Window could not be created! SDL_Error: {0}", SDL.SDL_GetError());
                    success = false;
                }
                else
                {
                    //Initialize PNG loading
                    var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
                    if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                    {
                        Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                        success = false;
                    }
                    else
                    {
                        //Get window surface
                        _ScreenSurface = SDL.SDL_GetWindowSurface(_Window);
                    }
                }
            }

            return(success);
        }
Exemplo n.º 14
0
        bool INTERNAL_Init_SDLSystems(uint subsysFlags)
        {
            #if DEBUG
            // Need to add the no parachute flag for debuggers so SDL will interact with them nicely
            // According to the wiki (http://wiki.libsdl.org/), this does nothing in SDL2 however,
            // we'll do it anyway "just in case".
            subsysFlags |= SDL.SDL_INIT_NOPARACHUTE;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                // ¡Windows es muy estúpido!
                SDL.SDL_SetHint(
                    SDL.SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING,
                    "1"
                    );
            }
            #endif

            // SDL_Init returns 0 on success
            if (SDL.SDL_Init(subsysFlags) != 0)
            {
                return(false);
            }

            // IMG_Init returns same init flags on success
            var imgInit = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
            if (imgInit != (SDL_image.IMG_InitFlags)SDL_image.IMG_Init(imgInit))
            {
                return(false);
            }

            // TTF_Init returns 0 on success
            if (SDL_ttf.TTF_Init() != 0)
            {
                return(false);
            }

            // We made it through the gambit!
            return(true);
        }
Exemplo n.º 15
0
        public static bool InitEngine()
        {
            // Initialise the log
            log = new Log("harambae_runtime.log");
            log.Info("Engine starting");

            // Initialise required SDL2 components
            int result;

            result = SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING);

            if (result < 0)
            {
                log.Error("Could not init SDL2");
                return(false);
            }

            if (CreateContext(800, 600, false) == false)
            {
                log.Error("Could not create a context");
                return(false);
            }

            // SDL2_TTF

            result = SDL_ttf.TTF_Init();
            if (result < 0)
            {
                log.Error("Could not init SDL2_TTF");
                DestroyContext();
                SDL.SDL_Quit();
                return(false);
            }
            largefont = SDL_ttf.TTF_OpenFont("assets/papyrus.ttf", 32);
            smallfont = SDL_ttf.TTF_OpenFont("assets/papyrus.ttf", 16);

            // SDL2_image
            result = SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);
            return(true);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initialize SDL, SDL_image and SDL_ttf
        /// </summary>
        public static void InitGraphics()
        {
            // Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING) != 0)
            {
                throw new SDLException("SDL_Init");
            }

            // Initialize SDL PNG image loading
            if ((SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG) &
                 (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG) !=
                (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG)
            {
                throw new SDLException("IMG_Init");
            }

            // Initialize SDL TTF rendering
            if (SDL_ttf.TTF_Init() != 0)
            {
                throw new SDLException("TTF_Init");
            }
        }
Exemplo n.º 17
0
 public static void Start()
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         try
         {
             SetProcessDpiAwareness(2);
         }
         catch (Exception)
         {
             Console.WriteLine("DPI awareness setup failed"); // On older versions on Windows
         }
     }
     SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
     SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "linear");
     SDL.SDL_EnableScreenSaver();
     SDL_ttf.TTF_Init();
     SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG);
     asyncCallbacksAdded = SDL.SDL_RegisterEvents(1);
     SynchronizationContext.SetSynchronizationContext(new UiSyncronizationContext());
     mainThreadId = Thread.CurrentThread.ManagedThreadId;
 }
Exemplo n.º 18
0
        public SDLGame()
        {
            Logger.AddLogger(new ConsoleLogger());
            fileResolver = new SDLFileResolver("Content");

            SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "best");
            SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO);
            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            win        = SDL.SDL_CreateWindow("SDL Tiles", SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI);
            ren        = SDL.SDL_CreateRenderer(win, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);
            fontEngine = new SDLFontEngine();
            graphics   = new SDLGraphics(this, 800, 600, fontEngine, new DebugOptions()
            {
                ShowGrid        = false,
                ShowHighlight   = false,
                ShowSelected    = true,
                ShowTileCounter = false,
                ShowCoordinates = false
            });
            sounds = new SDLSounds();
            engine = new Engine(fileResolver, graphics, fontEngine, sounds);
        }
Exemplo n.º 19
0
        private static bool Init()
        {
            //Init the video card
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
                return(false);
            }
            else
            {
                //Create an SDL window to render graphics upon.
                _windowPtr = SDL.SDL_CreateWindow("SDL2 Keyboard Sample", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);

                _rendererPtr = SDL.SDL_CreateRenderer(_windowPtr, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED);

                if (_windowPtr == IntPtr.Zero)
                {
                    Console.WriteLine("The window could not be created!!");
                    Console.ReadLine();
                    return(false);
                }
                else
                {
                    //Initialize PNG loading
                    var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
                    if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                    {
                        //TODO: Convert to exception
                        Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                        return(false);
                    }
                }
            }


            return(true);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="hero">The hero.</param>
        /// <param name="map">The map.</param>
        /// <param name="renderer">The renderer.</param>
        public Graphics(Hero hero, Map map, IntPtr renderer)
        {
            this.hero     = hero;
            this.map      = map;
            this.renderer = renderer;

            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_JPG);
            SDL.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0);

            // Load the images from the media folder.
            var heroImg      = SDL_image.IMG_Load("media//hero.jpg");
            var wallImg      = SDL_image.IMG_Load("media//wall.jpg");
            var boxImg       = SDL_image.IMG_Load("media//box.jpg");
            var slotImg      = SDL_image.IMG_Load("media//slot.jpg");
            var boxOnSlotImg = SDL_image.IMG_Load("media//boxOnSlot.jpg");
            var victoryImg   = SDL_image.IMG_Load("media//victory.jpg");

            HeroTex      = SDL.SDL_CreateTextureFromSurface(renderer, heroImg);
            WallTex      = SDL.SDL_CreateTextureFromSurface(renderer, wallImg);
            BoxTex       = SDL.SDL_CreateTextureFromSurface(renderer, boxImg);
            SlotTex      = SDL.SDL_CreateTextureFromSurface(renderer, slotImg);
            BoxOnSlotTex = SDL.SDL_CreateTextureFromSurface(renderer, boxOnSlotImg);
            VictoryTex   = SDL.SDL_CreateTextureFromSurface(renderer, victoryImg);
        }
Exemplo n.º 21
0
        /// <summary>Initializes the game by calling initialize on the SDL2 instance with the passed flags
        /// or "EVERYTHING" if 0. Additionally, this method will initialize SDL_ttf and SDL_image to load fonts and images.
        /// </summary>
        /// <param name="types">Bit flags indicating the way in which SDL should be initialized</param>
        private void InitializeBase(GameEngineInitializeType types)
        {
            if (SDL.SDL_Init((uint)types) != 0)
            {
                throw new InvalidOperationException($"SDL_Init: {SDL.SDL_GetError()}");
            }

            if (SDL_ttf.TTF_Init() != 0)
            {
                throw new InvalidOperationException($"TTF_Init: {SDL.SDL_GetError()}");
            }

            SDL_image.IMG_InitFlags initImageFlags =
                SDL_image.IMG_InitFlags.IMG_INIT_JPG
                | SDL_image.IMG_InitFlags.IMG_INIT_PNG
                | SDL_image.IMG_InitFlags.IMG_INIT_TIF
                | SDL_image.IMG_InitFlags.IMG_INIT_WEBP;
            int initImageResult = SDL_image.IMG_Init(initImageFlags);

            if ((initImageResult & (int)initImageFlags) != (int)initImageFlags)
            {
                throw new InvalidOperationException($"IMG_Init: {SDL.SDL_GetError()}");
            }
        }
Exemplo n.º 22
0
        public void Run()
        {
            SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG);

            var window = SDL.SDL_CreateWindow("Testing SDL2", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, 400, 800, 0);

            renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);

            field = new int[M, N];

            tilesTexture = SDL_image.IMG_LoadTexture(renderer, @"img\Tiles.png");
            if (tilesTexture == IntPtr.Zero)
            {
                Console.WriteLine("Error loading texture: " + SDL.SDL_GetError());
            }


            for (int i = 0; i < 4; i++)
            {
                point[i].X = shapes[shapeToDraw, i] % 2;
                point[i].Y = shapes[shapeToDraw, i] / 2;
            }

            running = true;

            while (running)
            {
                HandelInput();
                Update();
                Render();
            }

            SDL.SDL_DestroyWindow(window);
            SDL.SDL_Quit();
        }
Exemplo n.º 23
0
 //Inits SDL,SDL_image and SDL_ttf or exits the aplication if it fails
 static Hardware()
 {
     if (SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING) < 0)
     {
         SDL.SDL_ShowSimpleMessageBox
             (SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, "Error",
             "Could not init SDL", screen);
         Environment.Exit(1);
     }
     if (SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG) < 0)
     {
         SDL.SDL_ShowSimpleMessageBox
             (SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, "Error",
             "Could not init SDL_Image", screen);
         Environment.Exit(1);
     }
     if (SDL_ttf.TTF_Init() < 0)
     {
         SDL.SDL_ShowSimpleMessageBox
             (SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, "Error",
             "Could not init SDL_ttf", screen);
         Environment.Exit(1);
     }
 }
Exemplo n.º 24
0
        /// <summary>Initializes the game by calling initialize on the SDL2 instance with the passed flags
        /// or "EVERYTHING" if 0. Additionally, this method will initialize SDL_ttf and SDL_image to load fonts and images.
        /// </summary>
        /// <param name="flags">Bit flags indicating the way in which SDL should be initialized</param>
        protected virtual void Initialize(uint flags)
        {
            if (flags == EMPTY_UINT)
            {
                flags = SDL.SDL_INIT_EVERYTHING;
            }

            if (SDL.SDL_Init(flags) != 0)
            {
                throw new InvalidOperationException(String.Format("SDL_Init: {0}", SDL.SDL_GetError()));
            }

            if (SDL_ttf.TTF_Init() != 0)
            {
                throw new InvalidOperationException(String.Format("TTF_Init: {0}", SDL.SDL_GetError()));
            }

            int initImageResult = SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            if ((initImageResult & (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG) != (int)SDL_image.IMG_InitFlags.IMG_INIT_PNG)
            {
                throw new InvalidOperationException(String.Format("IMG_Init: {0}", SDL.SDL_GetError()));
            }
        }
        public void Execute()
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                SdlLogger.Fatal(nameof(SDL.SDL_Init));
            }

            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            var window = SDL.SDL_CreateWindow(TITLE, 0, 0, WIDTH, HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);

            if (window == IntPtr.Zero)
            {
                SdlLogger.Fatal(nameof(SDL.SDL_CreateWindow),
                                () => ReleaseAndQuit(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }

            var renderer = SDL.SDL_CreateRenderer(
                window, -1,
                SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);

            if (renderer == IntPtr.Zero)
            {
                SdlLogger.Fatal(
                    nameof(SDL.SDL_CreateRenderer),
                    () => ReleaseAndQuit(window, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }

            var image = Resources.LoadTextureFromImage(Resources.GetFilePath(@"lesson5/image.png"), renderer);

            if (image == IntPtr.Zero)
            {
                SdlLogger.Fatal(
                    nameof(Resources.LoadTextureFromImage),
                    () => ReleaseAndQuit(window, renderer, IntPtr.Zero, image));
            }

            var quit = false;
            int x, y, iW = 100, iH = 100, useClip = 0;

            x = WIDTH / 2 - iW / 2;
            y = HEIGHT / 2 - iH / 2;

            var clips = new SDL.SDL_Rect[4];

            for (var i = 0; i < clips.Length; i++)
            {
                clips[i] = new SDL.SDL_Rect
                {
                    x = i / 2 * iW,
                    y = i % 2 * iH,
                    w = iW,
                    h = iH,
                };
            }

            var e = new SDL.SDL_Event();

            while (!quit)
            {
                // event handling
                while (SDL.SDL_PollEvent(out e) > 0)
                {
                    if (e.type == SDL.SDL_EventType.SDL_QUIT)
                    {
                        quit = true;
                    }

                    if (e.type == SDL.SDL_EventType.SDL_KEYDOWN)
                    {
                        switch (e.key.keysym.sym)
                        {
                        case SDL.SDL_Keycode.SDLK_LEFT:
                            useClip = useClip > 0 ? useClip - 1 : clips.Length - 1;
                            break;

                        case SDL.SDL_Keycode.SDLK_RIGHT:
                            useClip = useClip < clips.Length - 1 ? useClip + 1 : 0;
                            break;

                        case SDL.SDL_Keycode.SDLK_ESCAPE:
                            quit = true;
                            break;
                        }
                    }
                }

                // rendering
                SDL.SDL_RenderClear(renderer);

                SdlDrawing.RenderTexture(image, renderer, x, y, clips[useClip]);

                SDL.SDL_RenderPresent(renderer);
            }

            ReleaseAndQuit(window, renderer, IntPtr.Zero, image);
        }
Exemplo n.º 26
0
    public void Init()
    {
        SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING);
        Window = SDL.SDL_CreateWindow("SDL2 GUI",
                                      WindowSize[0], WindowSize[1],
                                      WindowSize[2], WindowSize[3],
                                      SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE |
                                      SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN |
                                      SDL.SDL_WindowFlags.SDL_WINDOW_INPUT_FOCUS);

        SDL.SDL_SetWindowResizable(Window, SDL.SDL_bool.SDL_FALSE);

        int drivers = SDL.SDL_GetNumRenderDrivers();

        for (int i = 0; i < drivers; i++)
        {
            SDL.SDL_RendererInfo info;
            SDL.SDL_GetRenderDriverInfo(i, out info);

            Renderer = SDL.SDL_CreateRenderer(Window, i, (SDL.SDL_RendererFlags)info.flags);
            if (Renderer.ToInt32() != 0)
            {
                Printer.Instance.Init(Renderer);
                break;
            }
        }

        SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

        LoadImages();

        SDL.SDL_Rect sliceParams;
        sliceParams.x = 4;
        sliceParams.y = 4;
        sliceParams.w = 27;
        sliceParams.h = 27;

        _images[0].Slice(sliceParams);
        _images[1].Slice(sliceParams);
        _images[2].Slice(sliceParams);
        _images[3].Slice(sliceParams);

        _gui = new MyGUI(Renderer, WindowSize[2], WindowSize[3]);

        Canvas window = new Canvas(_gui);

        for (int i = 0; i < 4; i++)
        {
            Button b = new Button(_images[0], _images[1], _images[2], _images[3], 0, i * 25, 100, 25, "Click Me!");
            b.OnMouseClick = ClickHandler;

            if (i == 3)
            {
                b.Disable();
                b.SetText("Disabled");
                _toEnableRef = b;
            }
            else
            {
                _countersByButtonId.Add(b.ObjectId, 0);
            }

            window.AddElement(b);
        }

        Button enabler = new Button(_images[0], _images[1], _images[2], _images[3], 0, 5 * 25, 100, 25, "Enabler");

        enabler.OnMouseClick = EnablerHandler;
        window.AddElement(enabler);

        Button b2 = new Button(_images[0], _images[1], _images[2], _images[3], 775, 0, 25, 25, "X");

        b2.TextScale    = 1.5f;
        b2.OnMouseClick = ExitApp;

        window.AddElement(b2);

        _gui.PushCanvas(window);
    }
Exemplo n.º 27
0
        public void RunGame(Game game, bool borderless = false, Action a = null)
        {
            NativeLibraryLoader.SetNativeLibaryFolder();


            SDL.SDL_Init(SDL.SDL_INIT_VIDEO);

            var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG;

            if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
            {
                Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                return;
            }



            var cpus = SDL.SDL_GetCPUCount();

            Console.WriteLine("SYSTEM: CPU Count:" + cpus);

            var ramMb = SDL.SDL_GetSystemRAM();

            Console.WriteLine("SYSTEM: RAM MB:" + ramMb);

            // Init OpenAL
            var audioDevice = new AudioDevice();

            audioDevice.Initalise();

            GameInput = new GameInput();

            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MAJOR_VERSION, 3);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MINOR_VERSION, 3);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1);

            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLESAMPLES, 8);

            // TODO Register the Audio device in the dependancy locator
            var windowStyle = /*SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS |*/ SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL;

            if (borderless == true)
            {
                windowStyle = windowStyle | SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS;
            }
            WindowPtr = SDL.SDL_CreateWindow(m_WindowName, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, windowStyle);
            OpenGLPtr = SDL.SDL_GL_CreateContext(WindowPtr);

            // Get the Win32 HWND from the SDL2 window
            SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo();
            SDL.SDL_GetWindowWMInfo(WindowPtr, ref info);
            Win32Ptr = info.info.win.window;

            OpenGL.GlBindings.InitaliseOpenGLEntryPoints();



            var graphicsDevice = new OpenGLGraphicsDevice(OpenGLPtr);

            SetVSync(VSyncStatus.VSYNC_ENABLE);

            GraphicsDevice = graphicsDevice;
            AudioDevice    = audioDevice;

            game.Init(audioDevice, graphicsDevice, this, GameInput);

            // TODO Rename to OnLoadedWindow
            if (a != null)
            {
                a.Invoke();
            }

            // TODO Embed these as resources
            QuadBatchShader  = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.quadbatch.glsl", "Resources/Shaders/Fragment/f.quadbatch.glsl");
            FullScreenShader = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.fullscreenquad.glsl", "Resources/Shaders/Fragment/f.fullscreenquad.glsl");
            using (TracedStopwatch.Start("Loading Game Resources"))
            {
                game.Load();
            }

            var stopwatch = new Stopwatch();
            var isRunning = true;

            while (isRunning)
            {
                // TODO Reset stats counters

                stopwatch.Restart();
                ProcessEvents();

                if (this.HasQuit)
                {
                    break;
                }
                game.Update();
                game.UpdateCoroutines();


                GraphicsDevice.Enable(OpenGL.Enable.GL_DEPTH_TEST);
                game.RenderScene();

                GraphicsDevice.Disable(OpenGL.Enable.GL_DEPTH_TEST);
                game.Render2D();

                // TODO Multimedia Timer or sleep for time...
                // TODO Stats for frame time and fps

                // Update window with OpenGL rendering
                SDL.SDL_GL_SwapWindow(WindowPtr);
                GameInput.Swap();

                stopwatch.Stop();
                GameTime.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                GameTime.ElapsedSeconds      = stopwatch.Elapsed.TotalSeconds;
                GameTime.TotalSeconds       += GameTime.ElapsedSeconds;
            }

            // Unload Resources
            SDL.SDL_Quit();
        }
Exemplo n.º 28
0
        public static Engine Create(EngineOptions options, IController controller, IEventsCycle eventsCycle,
                                    ISceneRenderer sceneRenderer)
        {
            if (SDL_Init(SDL_INIT_VIDEO) < 0)
            {
                throw new InvalidOperationException($"Cant initialize SDL2: {SDL_GetError()}");
            }

            if (SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_JPG | SDL_image.IMG_InitFlags.IMG_INIT_PNG) < 0)
            {
                throw new InvalidOperationException($"Cant initialize SDL_image: {SDL_GetError()}");
            }

            if (SDL_ttf.TTF_Init() < 0)
            {
                throw new InvalidOperationException($"TTF_Init: {SDL_GetError()}");
            }

            if (SDL_ShowCursor(0) < 0)
            {
                throw new InvalidOperationException($"Cant disable cursor: {SDL_GetError()}");
            }

            if (SDL_mixer.Mix_Init(
                    SDL_mixer.MIX_InitFlags.MIX_INIT_MP3
                    | SDL_mixer.MIX_InitFlags.MIX_INIT_MID
                    | SDL_mixer.MIX_InitFlags.MIX_INIT_MOD
                    | SDL_mixer.MIX_InitFlags.MIX_INIT_OGG
                    | SDL_mixer.MIX_InitFlags.MIX_INIT_FLAC
                    | SDL_mixer.MIX_InitFlags.MIX_INIT_OPUS) < 0)
            {
                throw new InvalidOperationException($"MixInit: {SDL_GetError()}");
            }

            if (SDL_mixer.Mix_OpenAudio(22050, SDL_mixer.MIX_DEFAULT_FORMAT, 2, 4096) < 0)
            {
                throw new InvalidOperationException($"OpenAudio: {SDL_GetError()}");
            }

            if (SDL_mixer.Mix_AllocateChannels(16) < 0)
            {
                throw new InvalidOperationException($"Cant allocate channels: {SDL_GetError()}");
            }

            if (SDL_mixer.Mix_Volume(-1, 64) < 0)
            {
                throw new InvalidOperationException($"Min_Volume: {SDL_GetError()}");
            }


            var screen = Ui.Screen.Create(options.WindowTitle, options.ScreenHeight, options.ScreenWidth,
                                          options.FullScreen);
            var miniMapRenderer       = new MiniMapRenderer();
            var statusBarHeight       = screen.Height / 8;
            var statusBarWidth        = screen.Width;
            var statusBarSprite       = Sprite.Load(UiResourcesHelper.StatusBarSpritePath);
            var bowSprite             = Sprite.Load(UiResourcesHelper.BowMiniSpritePath);
            var frameSprite           = Sprite.Load(UiResourcesHelper.FrameSpritePath);
            var crossSprite           = options.CrossSpritePath == null ? null : Sprite.Load(options.CrossSpritePath);
            var arrowSprite           = Sprite.Load(UiResourcesHelper.ArrowSpritePath);
            var swordSprite           = Sprite.Load(UiResourcesHelper.SwordSpritePath);
            var fireBallSprite        = Sprite.Load(UiResourcesHelper.FireBallSpritePath);
            var shockBallSprite       = Sprite.Load(UiResourcesHelper.ShockBallSpritePath);
            var faceSprite            = Sprite.Load(UiResourcesHelper.FaceSprintPath);
            var faceHurtedSprite      = Sprite.Load(UiResourcesHelper.FaceHurtedSpritePath);
            var faceBadSprite         = Sprite.Load(UiResourcesHelper.FaceBadSpritePath);
            var logTextRenderer       = TextRenderer.Load(options.FontPath, screen.Height / 50);
            var notesTextRenderer     = TextRenderer.Load(options.FontPath, screen.Height / 50);
            var statusTextRenderer    = TextRenderer.Load(options.FontPath, screen.Height / 20);
            var notesRenderer         = new NotesRenderer(Sprite.Load(options.NotesSpritePath), notesTextRenderer, statusBarHeight);
            var monologueTextRenderer = TextRenderer.Load(options.FontPath, screen.Height / 50);
            var monologueRenderer     = new MonologueRenderer(monologueTextRenderer, statusBarHeight);
            var statusBarRenderer     = new StatusRenderer(
                statusBarSprite,
                crossSprite,
                statusBarHeight,
                logTextRenderer,
                notesRenderer,
                monologueRenderer,
                bowSprite,
                swordSprite,
                frameSprite,
                statusTextRenderer,
                arrowSprite,
                fireBallSprite,
                shockBallSprite,
                faceSprite,
                faceHurtedSprite,
                faceBadSprite);
            var textRenderer = options.FontPath == null ? null : TextRenderer.Load(options.FontPath, 24);

            return(new Engine(screen, controller, eventsCycle, sceneRenderer, miniMapRenderer, statusBarRenderer,
                              textRenderer));
        }
        public void Execute()
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                SdlLogger.Fatal(nameof(SDL.SDL_Init));
            }

            SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG);

            if (SDL_ttf.TTF_Init() != 0)
            {
                SdlLogger.Fatal(nameof(SDL_ttf.TTF_Init));
            }

            var window = SDL.SDL_CreateWindow(TITLE, 0, 0, WIDTH, HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);

            if (window == IntPtr.Zero)
            {
                SdlLogger.Fatal(nameof(SDL.SDL_CreateWindow),
                                () => ReleaseAndQuit(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }

            var renderer = SDL.SDL_CreateRenderer(
                window, -1,
                SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);

            if (renderer == IntPtr.Zero)
            {
                SdlLogger.Fatal(
                    nameof(SDL.SDL_CreateRenderer),
                    () => ReleaseAndQuit(window, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
            }

            var font = SDL_ttf.TTF_OpenFont(Resources.GetFilePath("lesson6/long_pixel-7.ttf"), 16);

            if (font == IntPtr.Zero)
            {
                SdlLogger.Fatal(
                    nameof(Resources.LoadTextureFromImage),
                    () => ReleaseAndQuit(window, renderer, IntPtr.Zero, IntPtr.Zero));
            }

            var colorWhite = new SDL.SDL_Color();

            colorWhite.r = 255;
            colorWhite.g = 255;
            colorWhite.b = 255;

            var image = SdlDrawing.CreateTextureFromText(@"SDL2_TTF - крутота!", font, colorWhite, renderer);

            var quit = false;
            int x, y, iW = 100, iH = 100;

            x = WIDTH / 2 - iW / 2;
            y = HEIGHT / 2 - iH / 2;

            var e = new SDL.SDL_Event();

            while (!quit)
            {
                // event handling
                while (SDL.SDL_PollEvent(out e) > 0)
                {
                    if (e.type == SDL.SDL_EventType.SDL_QUIT)
                    {
                        quit = true;
                    }

                    if (e.type == SDL.SDL_EventType.SDL_KEYDOWN)
                    {
                        switch (e.key.keysym.sym)
                        {
                        case SDL.SDL_Keycode.SDLK_ESCAPE:
                            quit = true;
                            break;
                        }
                    }
                }

                // rendering
                SDL.SDL_RenderClear(renderer);

                SdlDrawing.RenderTexture(image, renderer, x, y);

                SDL.SDL_RenderPresent(renderer);
            }

            ReleaseAndQuit(window, renderer, font, image);
        }
Exemplo n.º 30
0
        private static bool init()
        {
            //Initialization flag
            bool success = true;

            //Initialize SDL
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_JOYSTICK | SDL.SDL_INIT_HAPTIC) < 0)
            {
                Console.WriteLine("SDL could not initialize! SDL_Error: {0}", SDL.SDL_GetError());
                success = false;
            }
            else
            {
                //Set texture filtering to linear
                if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "1") == SDL.SDL_bool.SDL_FALSE)
                {
                    Console.WriteLine("Warning: Linear texture filtering not enabled!");
                }

                //Check for joysticks
                if (SDL.SDL_NumJoysticks() < 1)
                {
                    Console.WriteLine("Warning: No joysticks connected!");
                }
                else
                {
                    //Load joystick
                    _GameController = SDL.SDL_JoystickOpen(0);
                    if (_GameController == IntPtr.Zero)
                    {
                        Console.WriteLine("Warning: Unable to open game controller! SDL Error: {0}", SDL.SDL_GetError());
                    }
                    else
                    {
                        //Get controller haptic device
                        _ControllerHaptic = SDL.SDL_HapticOpenFromJoystick(_GameController);
                        if (_ControllerHaptic == IntPtr.Zero)
                        {
                            Console.WriteLine("Warning: Controller does not support haptics! SDL Error: {0}", SDL.SDL_GetError());
                        }
                        else
                        {
                            //Get initialize rumble
                            if (SDL.SDL_HapticRumbleInit(_ControllerHaptic) < 0)
                            {
                                Console.WriteLine("Warning: Unable to initialize rumble! SDL Error: {0}", SDL.SDL_GetError());
                            }
                        }
                    }
                }

                //Create window
                _Window = SDL.SDL_CreateWindow("SDL Tutorial", SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                                               SCREEN_WIDTH, SCREEN_HEIGHT, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);
                if (_Window == IntPtr.Zero)
                {
                    Console.WriteLine("Window could not be created! SDL_Error: {0}", SDL.SDL_GetError());
                    success = false;
                }
                else
                {
                    //Create vsynced renderer for window
                    var renderFlags = SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC;
                    Renderer = SDL.SDL_CreateRenderer(_Window, -1, renderFlags);
                    if (Renderer == IntPtr.Zero)
                    {
                        Console.WriteLine("Renderer could not be created! SDL Error: {0}", SDL.SDL_GetError());
                        success = false;
                    }
                    else
                    {
                        //Initialize renderer color
                        SDL.SDL_SetRenderDrawColor(Renderer, 0xFF, 0xFF, 0xFF, 0xFF);

                        //Initialize PNG loading
                        var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG;
                        if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
                        {
                            Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                            success = false;
                        }
                    }
                }
            }

            return(success);
        }