Esempio n. 1
0
        //Loads image at specified path
        public bool loadFromFile(string path)
        {
            //Get rid of preexisting texture
            free();

            //The final texture
            IntPtr newTexture = IntPtr.Zero;

            //Load image at specified path
            IntPtr loadedSurface = SDL_image.IMG_Load(path);

            if (loadedSurface == IntPtr.Zero)
            {
                Console.WriteLine("Unable to load image {0}! SDL Error: {1}", path, SDL.SDL_GetError());
            }
            else
            {
                var s = Marshal.PtrToStructure <SDL.SDL_Surface>(loadedSurface);

                //Color key image
                SDL.SDL_SetColorKey(loadedSurface, (int)SDL.SDL_bool.SDL_TRUE, SDL.SDL_MapRGB(s.format, 0, 0xFF, 0xFF));

                //Create texture from surface pixels
                newTexture = SDL.SDL_CreateTextureFromSurface(Program.gRenderer, loadedSurface);
                if (newTexture == IntPtr.Zero)
                {
                    Console.WriteLine("Unable to create texture from {0}! SDL Error: {1}", path, SDL.SDL_GetError());
                }
                else
                {
                    //Get image dimensions
                    mWidth  = s.w;
                    mHeight = s.h;
                }

                //Get rid of old loaded surface
                SDL.SDL_FreeSurface(loadedSurface);
            }

            //Return success
            mTexture = newTexture;
            return(mTexture != IntPtr.Zero);
        }
        public static void OnImageLoad(object sender, HtmlImageLoadEventArgs args)
        {
            Console.WriteLine(directory + args.Src);
            if (!_imageSurface.ContainsKey(args.Src))
            {
                var img_surface = SDL_image.IMG_Load(directory + args.Src);
                if (img_surface.ShowSDLError("OnImageLoad: Unable to IMG_Load!"))
                {
                    return;
                }

                _imageSurface[args.Src] = img_surface;
            }
            args.Handled = true;
            //foreach (var kv in args.Attributes)
            //Console.WriteLine("{0}: {1}", kv.Key, kv.Value);

            args.Callback(_imageSurface[args.Src]);
        }
Esempio n. 3
0
        public void Load(string filename)
        {
            var surface = SDL_image.IMG_Load(filename);

            if (surface == null)
            {
                Log.Instance.Debug($"Failed to load image! SDL error: {SDL.SDL_GetError()}");
                throw new InvalidOperationException(SDL.SDL_GetError());
            }

            _texturePtr = SDL.SDL_CreateTextureFromSurface(SDLRenderer.Instance.RenderPtr, surface);
            SDL.SDL_DestroyTexture(surface);

            if (_texturePtr == null)
            {
                Log.Instance.Debug($"Failed to create texture! SDL error: {SDL.SDL_GetError()}");
                throw new InvalidOperationException(SDL.SDL_GetError());
            }
        }
Esempio n. 4
0
        public static PixelBuffer PixelBuffer(string path)
        {
            if (pixelBuffers == null)
            {
                pixelBuffers = new Dictionary <string, PixelBuffer>();
            }
            if (!pixelBuffers.ContainsKey(path))
            {
                var pixelBufferPath = LoadPath(path);

                var surfPointer = SDL_image.IMG_Load(pixelBufferPath);

                var surface = System.Runtime.InteropServices.Marshal.PtrToStructure <SDL.SDL_Surface>(
                    surfPointer
                    );

                if (System.Runtime.InteropServices.Marshal.PtrToStructure <SDL.SDL_PixelFormat>(surface.format).format != SDL.SDL_PIXELFORMAT_RGBA8888)
                {
                    surfPointer = SDL.SDL_ConvertSurfaceFormat(surfPointer, SDL.SDL_PIXELFORMAT_ABGR8888, 0);
                    surface     = System.Runtime.InteropServices.Marshal.PtrToStructure <SDL.SDL_Surface>(
                        surfPointer
                        );
                }

                Color32[] pixels = new Color32[surface.w * surface.h];
                unsafe
                {
                    var colors = ((Color32 *)surface.pixels);
                    for (int i = 0; i < pixels.Length; i++)
                    {
                        pixels[i] = colors[i];
                    }
                }

                var pixelBuffer = new PixelBuffer(
                    pixels,
                    surface.w
                    );
                pixelBuffers.Add(path, pixelBuffer);
            }
            return(pixelBuffers[path]);
        }
Esempio n. 5
0
        public static bool LoadFrom(string Path, out Image img)
        {
            var p = Path;
            // SDL_Surface* IMG_Load(const char* path);
            var sur     = SDL_image.IMG_Load(p);
            var raw_sur = Marshal.PtrToStructure <SDL_Surface>(sur);

            var tex = SDL_GPU.GPU_CopyImageFromSurface(sur);

            // I'll free the surface right here and see if weirdness happens
            SDL_FreeSurface(sur);

            img = new Image()
            {
                Texture = tex,
                Width   = raw_sur.w,
                Height  = raw_sur.h
            };
            return(true);
        }
Esempio n. 6
0
        internal Surface(string filePath, SurfaceType surfaceType)
        {
            if (String.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            FilePath = filePath;
            Type     = surfaceType;

            IntPtr unsafeHandle = SDL_image.IMG_Load(FilePath);

            if (unsafeHandle == IntPtr.Zero)
            {
                throw new InvalidOperationException($"Error while loading image surface: {SDL.SDL_GetError()}");
            }

            safeHandle = new SafeSurfaceHandle(unsafeHandle);

            GetSurfaceMetaData();
        }
Esempio n. 7
0
        public void Load(AtlasPage page, string path)
        {
            IntPtr tmp = SDL_image.IMG_Load(path);

            tmp = SDL.SDL_ConvertSurfaceFormat(tmp, SDL.SDL_PIXELFORMAT_ABGR8888, 0);
            SDL.SDL_Surface surface = Marshal.PtrToStructure <SDL.SDL_Surface>(tmp);

            var textureIdList = new uint[1];

            _gl.GenTextures(1, textureIdList);
            var textureId = textureIdList[0];

            _gl.BindTexture(OpenGL.GL_TEXTURE_2D, textureId);
            _gl.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, OpenGL.GL_RGBA, surface.w, surface.h, 0, OpenGL.GL_RGBA, OpenGL.GL_UNSIGNED_BYTE, surface.pixels);
            _gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
            _gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);

            SDL.SDL_FreeSurface(tmp);

            page.rendererObject = textureId;
        }
Esempio n. 8
0
        private void LoadImages()
        {
            // Пока загружаем все файлы с расширением PNG из каталога Assets.
            // Идентификатором  будет являться наименование файла.
            var assetsPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            assetsPath = Path.Combine(assetsPath, "Assets");

            foreach (var texturePath in Directory.GetFiles(assetsPath, "*.png", SearchOption.AllDirectories))
            {
                var texture = SDL_image.IMG_Load(texturePath);

                if (texture == IntPtr.Zero)
                {
                    _logger.Error("Ошибка при загруке файла изображения {texturePath}. Текстура не создана.", texturePath);
                    continue;
                }

                var textureIndent = Path.GetFileNameWithoutExtension(texturePath);
                _logger.Debug("Загружено изображение \"{textureIndent}\" из {texturePath}", textureIndent, texturePath);

                _textures.Add(textureIndent, texture);
            }
        }
Esempio n. 9
0
        private TextureStruct BMPToTexture(string imagePath, byte r, byte g, byte b)
        {
            TextureStruct finalTexture = new TextureStruct(IntPtr.Zero, 0, 0);
            IntPtr        sprite       = IntPtr.Zero;

            //loads all (supported) images, not only BMP
            sprite = SDL_image.IMG_Load(imagePath);
            //sprite = SDL_LoadBMP(imagePath);
            if (sprite == IntPtr.Zero)
            {
                Console.Write("Unable to load image: " + imagePath + " SDL Error:" + SDL_GetError() + " \n");
                SDL_FreeSurface(sprite);
                return(finalTexture);
            }
            //Set Colorkey
            var format = ((SDL_Surface)Marshal.PtrToStructure(sprite, typeof(SDL_Surface))).format;

            SDL_SetColorKey(sprite, 1, SDL_MapRGB(format, r, g, b));

            IntPtr myTexture = SDL_CreateTextureFromSurface(renderer, sprite);

            if (myTexture == IntPtr.Zero)
            {
                Console.Write("Unable to create texture! SDL Error:" + SDL_GetError() + " \n");
                Console.Write(imagePath + " \n");
                SDL_FreeSurface(sprite);
                return(finalTexture);
            }

            finalTexture.h       = ((SDL_Surface)Marshal.PtrToStructure(sprite, typeof(SDL_Surface))).h;
            finalTexture.w       = ((SDL_Surface)Marshal.PtrToStructure(sprite, typeof(SDL_Surface))).w;
            finalTexture.texture = myTexture;

            SDL_FreeSurface(sprite);
            return(finalTexture);
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
 public static SDLSurface Load(string File)
 {
     return(new SDLSurface(SDL_image.IMG_Load(File)));
 }
Esempio n. 12
0
        public void Run()
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                Console.WriteLine("Unable to init SDL. Error: {0}", SDL.SDL_GetError());
                return;
            }

            windowPtr = SDL.SDL_CreateWindow("WARWARRIOR4", SDL.SDL_WINDOWPOS_UNDEFINED,
                                             SDL.SDL_WINDOWPOS_UNDEFINED, WindowWidth, WindowHeight,
                                             SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE);

            if (windowPtr == IntPtr.Zero)
            {
                Console.WriteLine("Unable to init window. Error: {0}", SDL.SDL_GetError());
                return;
            }

            IntPtr iconImage = SDL_image.IMG_Load("assets/textures/player.png");

            SDL.SDL_SetWindowIcon(windowPtr, iconImage);

            // Init hardware accelerated graphics if possible, fall back on software
            rendererPtr = SDL.SDL_CreateRenderer(windowPtr, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED | SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC);
            if (rendererPtr == IntPtr.Zero)
            {
                Console.WriteLine("Unable to init accelerated graphics. {0}", SDL.SDL_GetError());
                SDL.SDL_ClearError();
                Console.WriteLine("Fall back on software");

                rendererPtr = SDL.SDL_CreateRenderer(windowPtr, -1, SDL.SDL_RendererFlags.SDL_RENDERER_SOFTWARE);
                if (rendererPtr == IntPtr.Zero)
                {
                    Console.WriteLine("Unable to init software renderer. Error: {0}", SDL.SDL_GetError());
                    return;
                }

                DebugDelay = 16;
            }

            Init();
            Load(rendererPtr);

            Stopwatch stopwatch = new Stopwatch();
            long      frames    = 0;

            stopwatch.Start();
            long lastTime = stopwatch.ElapsedMilliseconds;

            while (!quit)
            {
                float deltaTime = (stopwatch.ElapsedMilliseconds - lastTime) / 1000.0f;
                lastTime            = stopwatch.ElapsedMilliseconds;
                elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

                HandleEvents();
                UpdateLogic(deltaTime);
                RenderScene(rendererPtr);
                frames++;

                SDL.SDL_Delay(DebugDelay); // used for testing frame rate independent code
            }

            stopwatch.Stop();
            long fps = frames / ((stopwatch.ElapsedMilliseconds / 1000) > 0 ? (stopwatch.ElapsedMilliseconds / 1000) : 1);

            Console.WriteLine($"Average FPS: {fps}");

            Cleanup();
        }
Esempio n. 13
0
        public unsafe static void Pack(Config config)
        {
            Console.WriteLine("Checking directories...");

            for (int i = 0; i < config.Directories.Count; i++)
            {
                if (!Directory.Exists(config.Directories[i]))
                {
                    throw new Exception($"Input directory: '{config.Directories[i]}' does not exist.");
                }
            }
            if (!Directory.Exists(config.Output))
            {
                _ = Directory.CreateDirectory(config.Output);
            }

            // Clear out previously built atlases
            foreach (string file in Directory.GetFiles(config.Output, $"*{config.Name}*.png"))
            {
                File.Delete(file);
            }
            foreach (string file in Directory.GetFiles(config.Output, $"*{config}.xml"))
            {
                File.Delete(file);
            }

            Console.WriteLine("Loading surfaces...");

            List <(string, IntPtr)> surfaces = new List <(string, IntPtr)>();

            int err = SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG | SDL_image.IMG_InitFlags.IMG_INIT_TIF);

            if (err < 0)
            {
                throw new Exception(SDL_GetError());
            }

            foreach (string dir in config.Directories)
            {
                List <string> dirs = new List <string>()
                {
                    dir
                };
                dirs.AddRange(Directory.GetDirectories(dir, "*", new EnumerationOptions()
                {
                    RecurseSubdirectories = true
                }));

                foreach (string file in dirs.SelectMany(d => Directory.GetFiles(d, config.FileFilter)))
                {
                    string ext = Path.GetExtension(file);
                    switch (ext)
                    {
                    case ".png":
                    case ".bmp":
                    case ".jpeg":
                    case ".jpg":
                    case ".tiff":
                    case ".tif":
                    case ".gif":
                    case ".tga":
                        IntPtr image = SDL_image.IMG_Load(file);
                        if (((SDL_PixelFormat *)((SDL_Surface *)image)->format)->format != SDL_PIXELFORMAT_ABGR8888)
                        {
                            image = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ABGR8888, 0);
                        }
                        surfaces.Add((file.Substring(dir.Length).Replace('\\', '/').TrimStart('/'), image));
                        break;

                    default:
                        continue;
                    }
                }
            }

            Console.WriteLine("Computing, blitting and saving atlases...");

            int count   = 0;
            var atlas   = SDL_CreateRGBSurfaceWithFormat(0, config.AtlasWidth, config.AtlasHeight, 32, SDL_PIXELFORMAT_ABGR8888);
            var sources = new List <(string id, int index, bool rot, SDL_Rect rect)>();
            var mrbp    = new MaxRectsBinPack(config.AtlasWidth, config.AtlasHeight, config.AllowRotations);

            // Until the full list is emptied out, find the next best image to place
            // If the mrbp starts returning 0 rectangles, create a new atlas and continue
            while (surfaces.Count > 0)
            {
                int      lowestScore1 = int.MaxValue;
                int      lowestScore2 = int.MaxValue;
                int      bestIndex    = -1;
                SDL_Rect best         = new SDL_Rect();

                for (int i = 0; i < surfaces.Count; ++i)
                {
                    int      score1  = 0;
                    int      score2  = 0;
                    SDL_Rect newNode = mrbp.ScoreRect(((SDL_Surface *)surfaces[i].Item2)->w, ((SDL_Surface *)surfaces[i].Item2)->h,
                                                      MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestShortSideFit, ref score1, ref score2);

                    if (score1 < lowestScore1 || score1 == lowestScore1 && score2 < lowestScore2)
                    {
                        lowestScore1 = score1;
                        lowestScore2 = score2;
                        best         = newNode;
                        bestIndex    = i;
                    }
                }

                if (bestIndex == -1)
                {
                    _ = SDL_image.IMG_SavePNG(atlas, Path.Combine(config.Output, config.Name + count.ToString() + ".png"));
                    SDL_FreeSurface(atlas);
                    atlas = SDL_CreateRGBSurfaceWithFormat(0, config.AtlasWidth, config.AtlasHeight, 32, SDL_PIXELFORMAT_ABGR8888);

                    mrbp.Init(config.AtlasWidth, config.AtlasHeight, config.AllowRotations);
                    count++;
                }
                else
                {
                    var  sptr    = (SDL_Surface *)surfaces[bestIndex].Item2;
                    bool flipped = sptr->h == best.w;
                    if (flipped)
                    {
                        var flipd = (SDL_Surface *)SDL_CreateRGBSurfaceWithFormat(0, sptr->h, sptr->w, 32, SDL_PIXELFORMAT_ABGR8888);

                        for (int y = 0; y < sptr->h; y++)
                        {
                            for (int x = 0; x < sptr->w; x++)
                            {
                                // swapping the coords and inverting one produces rotation
                                uint *target = (uint *)(flipd->pixels + x * flipd->pitch + (sptr->h - y - 1) * 4);
                                *     target = *(uint *)(sptr->pixels + y * sptr->pitch + x * 4);
                            }
                        }

                        _ = SDL_BlitSurface(new IntPtr(flipd), IntPtr.Zero, atlas, ref best);
                        SDL_FreeSurface(new IntPtr(flipd));
                        SDL_FreeSurface(new IntPtr(sptr));
                    }
                    else
                    {
                        _ = SDL_BlitSurface(new IntPtr(sptr), IntPtr.Zero, atlas, ref best);
                        SDL_FreeSurface(new IntPtr(sptr));
                    }

                    sources.Add((surfaces[bestIndex].Item1, count, flipped, best));
                    surfaces.RemoveAt(bestIndex);
                    mrbp.PlaceRect(best);
                }
            }

            // save current/last atlas
            _ = SDL_image.IMG_SavePNG(atlas, Path.Combine(config.Output, config.Name + count.ToString() + ".png"));
            SDL_FreeSurface(atlas);

            Console.WriteLine("Writing json data to disk...");

            // Write JSON data
            File.WriteAllText(Path.Combine(config.Output, config.Name + ".json"), Newtonsoft.Json.JsonConvert.SerializeObject(sources));

            sources.Clear();
            Console.WriteLine("Done");
        }