Ejemplo n.º 1
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            // Create white texture
            _white = new Texture2D(GraphicsDevice, 1, 1);
            _white.SetData(new[] { Color.White });

            // Load image data into memory
            var path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            path = Path.Combine(path, "image.jpg");
            var buffer = File.ReadAllBytes(path);

            var image = StbImage.LoadFromMemory(buffer, StbImage.STBI_rgb_alpha);

            _image = new Texture2D(GraphicsDevice, image.Width, image.Height, false, SurfaceFormat.Color);
            _image.SetData(image.Data);

            // Load ttf
            buffer = File.ReadAllBytes("Fonts/DroidSans.ttf");
            var buffer2 = File.ReadAllBytes("Fonts/DroidSansJapanese.ttf");

            var tempBitmap = new byte[FontBitmapWidth * FontBitmapHeight];

            var fontBaker = new FontBaker();

            fontBaker.Begin(tempBitmap, FontBitmapWidth, FontBitmapHeight);
            fontBaker.Add(buffer, 32, new []
            {
                FontBakerCharacterRange.BasicLatin,
                FontBakerCharacterRange.Latin1Supplement,
                FontBakerCharacterRange.LatinExtendedA,
                FontBakerCharacterRange.Cyrillic,
            });

            fontBaker.Add(buffer2, 32, new []
            {
                FontBakerCharacterRange.Hiragana,
                FontBakerCharacterRange.Katakana
            });

            _charData = fontBaker.End();

            // Offset by minimal offset
            float minimumOffsetY = 10000;

            foreach (var pair in _charData)
            {
                if (pair.Value.yoff < minimumOffsetY)
                {
                    minimumOffsetY = pair.Value.yoff;
                }
            }

            var keys = _charData.Keys.ToArray();

            foreach (var key in keys)
            {
                var pc = _charData[key];
                pc.yoff       -= minimumOffsetY;
                _charData[key] = pc;
            }


            var rgb = new Color[FontBitmapWidth * FontBitmapHeight];

            for (var i = 0; i < tempBitmap.Length; ++i)
            {
                var b = tempBitmap[i];
                rgb[i].R = b;
                rgb[i].G = b;
                rgb[i].B = b;

                rgb[i].A = b;
            }

            _fontTexture = new Texture2D(GraphicsDevice, FontBitmapWidth, FontBitmapHeight);
            _fontTexture.SetData(rgb);

            // Load ogg
            path   = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            path   = Path.Combine(path, "Adeste_Fideles.ogg");
            buffer = File.ReadAllBytes(path);

            int chan, sampleRate;
            var audioShort = StbVorbis.decode_vorbis_from_memory(buffer, out sampleRate, out chan);

            byte[] audioData = new byte[audioShort.Length / 2 * 4];
            for (var i = 0; i < audioShort.Length; ++i)
            {
                if (i * 2 >= audioData.Length)
                {
                    break;
                }

                var b1 = (byte)(audioShort[i] >> 8);
                var b2 = (byte)(audioShort[i] & 256);

                audioData[i * 2 + 0] = b2;
                audioData[i * 2 + 1] = b1;
            }

            _effect = new DynamicSoundEffectInstance(sampleRate, AudioChannels.Stereo)
            {
                Volume = 0.5f
            };


            _effect.SubmitBuffer(audioData);

            GC.Collect();
        }
Ejemplo n.º 2
0
        private static void ThreadProc(string f)
        {
            try
            {
                var sw = new Stopwatch();

                if (!f.EndsWith(".bmp") && !f.EndsWith(".jpg") && !f.EndsWith(".png") &&
                    !f.EndsWith(".jpg") && !f.EndsWith(".psd") && !f.EndsWith(".pic") &&
                    !f.EndsWith(".tga"))
                {
                    return;
                }

                Log(string.Empty);
                Log("{0} -- #{1}: Loading {2} into memory", DateTime.Now.ToLongTimeString(), filesProcessed, f);
                var data = File.ReadAllBytes(f);
                Log("----------------------------");

                Log("Loading From Stream");
                int    x = 0, y = 0, comp = 0;
                int    stbSharpPassed, stbNativePassed;
                byte[] parsed = new byte[0];
                ParseTest(
                    sw,
                    (out int xx, out int yy, out int ccomp) =>
                {
                    using (var ms = new MemoryStream(data))
                    {
                        var loader = new ImageReader();
                        var img    = loader.Read(ms);

                        parsed = img.Data;
                        xx     = img.Width;
                        yy     = img.Height;
                        ccomp  = img.SourceComp;

                        x    = xx;
                        y    = yy;
                        comp = ccomp;
                        return(parsed);
                    }
                },
                    (out int xx, out int yy, out int ccomp) =>
                {
                    using (var ms = new MemoryStream(data))
                    {
                        return(Native.load_from_stream(ms, out xx, out yy, out ccomp, StbImage.STBI_default));
                    }
                },
                    out stbSharpPassed, out stbNativePassed
                    );
                stbSharpLoadingFromStream  += stbSharpPassed;
                stbNativeLoadingFromStream += stbNativePassed;

                Log("Loading from memory");
                ParseTest(
                    sw,
                    (out int xx, out int yy, out int ccomp) =>
                {
                    var img = StbImage.LoadFromMemory(data);

                    var res = img.Data;
                    xx      = img.Width;
                    yy      = img.Height;
                    ccomp   = img.SourceComp;

                    x    = xx;
                    y    = yy;
                    comp = ccomp;
                    return(res);
                },
                    (out int xx, out int yy, out int ccomp) =>
                    Native.load_from_memory(data, out xx, out yy, out ccomp, StbImage.STBI_default),
                    out stbSharpPassed, out stbNativePassed
                    );
                stbSharpLoadingFromMemory  += stbSharpPassed;
                stbNativeLoadingFromMemory += stbNativePassed;

                var image = new Image
                {
                    Comp   = comp,
                    Data   = parsed,
                    Width  = x,
                    Height = y
                };

                for (var k = 0; k <= 4; ++k)
                {
                    Log("Saving as {0} with StbSharp", FormatNames[k]);

                    if (k < 4)
                    {
                        var           writer = new ImageWriter();
                        WriteDelegate wd     = null;
                        switch (k)
                        {
                        case 0:
                            wd = writer.WriteBmp;
                            break;

                        case 1:
                            wd = writer.WriteTga;
                            break;

                        case 2:
                            wd = writer.WriteHdr;
                            break;

                        case 3:
                            wd = writer.WritePng;
                            break;
                        }

                        byte[] save;
                        BeginWatch(sw);
                        using (var stream = new MemoryStream())
                        {
                            wd(image, stream);
                            save = stream.ToArray();
                        }

                        var passed = EndWatch(sw);
                        stbSharpWrite += passed;
                        Log("Span: {0} ms", passed);
                        Log("StbSharp Size: {0}", save.Length);

                        Log("Saving as {0} with Stb.Native", FormatNames[k]);
                        BeginWatch(sw);
                        byte[] save2;
                        using (var stream = new MemoryStream())
                        {
                            Native.save_to_stream(parsed, x, y, comp, k, stream);
                            save2 = stream.ToArray();
                        }

                        passed          = EndWatch(sw);
                        stbNativeWrite += passed;

                        Log("Span: {0} ms", passed);
                        Log("Stb.Native Size: {0}", save2.Length);

                        if (save.Length != save2.Length)
                        {
                            throw new Exception(string.Format("Inconsistent output size: StbSharp={0}, Stb.Native={1}",
                                                              save.Length, save2.Length));
                        }

                        for (var i = 0; i < save.Length; ++i)
                        {
                            if (save[i] != save2[i])
                            {
                                throw new Exception(string.Format("Inconsistent data: index={0}, StbSharp={1}, Stb.Native={2}",
                                                                  i,
                                                                  (int)save[i],
                                                                  (int)save2[i]));
                            }
                        }
                    }
                    else
                    {
                        for (var qi = 0; qi < JpgQualities.Length; ++qi)
                        {
                            var quality = JpgQualities[qi];
                            Log("Saving as JPG with StbSharp with quality={0}", quality);
                            byte[] save;
                            BeginWatch(sw);
                            using (var stream = new MemoryStream())
                            {
                                var writer = new ImageWriter();
                                writer.WriteJpg(image, stream, quality);
                                save = stream.ToArray();
                            }

                            var passed = EndWatch(sw);
                            stbSharpWrite += passed;

                            Log("Span: {0} ms", passed);
                            Log("StbSharp Size: {0}", save.Length);

                            Log("Saving as JPG with Stb.Native with quality={0}", quality);
                            BeginWatch(sw);
                            byte[] save2;
                            using (var stream = new MemoryStream())
                            {
                                Native.save_to_jpg(parsed, x, y, comp, stream, quality);
                                save2 = stream.ToArray();
                            }

                            passed          = EndWatch(sw);
                            stbNativeWrite += passed;

                            Log("Span: {0} ms", passed);
                            Log("Stb.Native Size: {0}", save2.Length);

                            if (save.Length != save2.Length)
                            {
                                throw new Exception(string.Format("Inconsistent output size: StbSharp={0}, Stb.Native={1}",
                                                                  save.Length, save2.Length));
                            }

                            for (var i = 0; i < save.Length; ++i)
                            {
                                if (save[i] != save2[i])
                                {
                                    throw new Exception(string.Format("Inconsistent data: index={0}, StbSharp={1}, Stb.Native={2}",
                                                                      i,
                                                                      (int)save[i],
                                                                      (int)save2[i]));
                                }
                            }
                        }
                    }
                }

                // Compressing
                Log("Performing DXT compression with StbSharp");
                image = StbImage.LoadFromMemory(data, StbImage.STBI_rgb_alpha);

                BeginWatch(sw);
                var compressed = StbDxt.stb_compress_dxt(image);
                stbSharpCompression += EndWatch(sw);

                Log("Performing DXT compression with Stb.Native");
                BeginWatch(sw);
                var compressed2 = Native.compress_dxt(image.Data, image.Width, image.Height, true);
                stbNativeCompression += EndWatch(sw);

                if (compressed.Length != compressed2.Length)
                {
                    throw new Exception(string.Format("Inconsistent output size: StbSharp={0}, Stb.Native={1}",
                                                      compressed.Length, compressed2.Length));
                }

                for (var i = 0; i < compressed.Length; ++i)
                {
                    if (compressed[i] != compressed2[i])
                    {
                        throw new Exception(string.Format("Inconsistent data: index={0}, StbSharp={1}, Stb.Native={2}",
                                                          i,
                                                          (int)compressed[i],
                                                          (int)compressed2[i]));
                    }
                }


                Log("Total StbSharp Loading From Stream Time: {0} ms", stbSharpLoadingFromStream);
                Log("Total Stb.Native Loading From Stream Time: {0} ms", stbNativeLoadingFromStream);
                Log("Total StbSharp Loading From memory Time: {0} ms", stbSharpLoadingFromMemory);
                Log("Total Stb.Native Loading From memory Time: {0} ms", stbNativeLoadingFromMemory);
                Log("Total StbSharp Write Time: {0} ms", stbSharpWrite);
                Log("Total Stb.Native Write Time: {0} ms", stbNativeWrite);
                Log("Total StbSharp Compression Time: {0} ms", stbSharpCompression);
                Log("Total Stb.Native Compression Time: {0} ms", stbNativeCompression);

                Log("GC Memory: {0}", GC.GetTotalMemory(true));

                ++filesProcessed;
                Log(DateTime.Now.ToLongTimeString() + " -- " + " Files processed: " + filesProcessed);
            }
            catch (Exception ex)
            {
                Log("Error: " + ex.Message);
            }
            finally
            {
                --tasksStarted;
            }
        }