コード例 #1
0
ファイル: Data.cs プロジェクト: dreamsxin/engine-1
        public static Handle CreateCheckerboardTexture(IApi api)
        {
            Int32 texSize = 256;
            Int32 gridSize = 4;
            Int32 squareSize = texSize / gridSize;

            var colours = new Rgba32 [gridSize*gridSize];

            for (Int32 x = 0; x < gridSize; ++x)
            {
                for (Int32 y = 0; y < gridSize; ++y)
                {
                    colours [x + (y * gridSize)] = RandomColours.GetNext ();
                }
            }

            var texData = new byte[texSize*texSize*4];

            Int32 index = 0;
            for (Int32 x = 0; x < texSize; ++x)
            {
                for (Int32 y = 0; y < texSize; ++y)
                {
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].A;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].R;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].G;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].B;
                }
            }

            return api.gfx_CreateTexture (TextureFormat.Rgba32, texSize, texSize, texData);
        }
コード例 #2
0
ファイル: ColourChanger.cs プロジェクト: gitter-badger/blimey
 public ColourChanger()
 {
     _current = RandomGenerator.Default.GetRandomColour();
     _target = RandomGenerator.Default.GetRandomColour();
     _colourChangeTime = RandomGenerator.Default.GetRandomSingle(3f, 10f);
     _timer = _colourChangeTime;
 }
コード例 #3
0
        static LightingManager()
        {
            ambientLightColour = Rgba32.Black;
            emissiveColour = Rgba32.DarkSlateGrey;
            specularColour = Rgba32.DarkGrey;
            specularPower = 2f;

            fogEnabled = true;
            fogStart = 100f;
            fogEnd = 1000f;
            fogColour = Rgba32.BlueViolet;

            dirLight0Direction = new Vector3(-0.3f, -0.9f, +0.3f);
            Vector3.Normalise(ref dirLight0Direction, out dirLight0Direction);
            dirLight0DiffuseColour = Rgba32.DimGrey;
            dirLight0SpecularColour = Rgba32.DarkGreen;

            dirLight1Direction = new Vector3(0.3f, 0.1f, -0.3f);
            Vector3.Normalise(ref dirLight1Direction, out dirLight1Direction);
            dirLight1DiffuseColour = Rgba32.DimGrey;
            dirLight1SpecularColour = Rgba32.DarkRed;

            dirLight2Direction = new Vector3( -0.7f, -0.3f, +0.1f);
            Vector3.Normalise(ref dirLight2Direction, out dirLight2Direction);
            dirLight2DiffuseColour = Rgba32.DimGrey;
            dirLight2SpecularColour = Rgba32.DarkBlue;
        }
コード例 #4
0
ファイル: Triple.cs プロジェクト: gitter-badger/blimey
        public static Triple Create(Vector3 a, Vector3 b, Vector3 c, Rgba32 colour)
        {
            var t = new Triple ();
            t.v = new [] {
                new VertexPositionTextureColour (a, new Vector2 (0, 0), colour),
                new VertexPositionTextureColour (b, new Vector2 (0, 1), colour),
                new VertexPositionTextureColour (c, new Vector2 (1, 0), colour),
            };
            t.blend = BlendMode.Default;
            t.tex = null;

            return t;
        }
コード例 #5
0
ファイル: Quad.cs プロジェクト: dreamsxin/engine-1
        public static Quad Create(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Rgba32 colour)
        {
            var q = new Quad ();
            q.v = new [] {
                new VertexPositionTextureColour (a, new Vector2 (0, 0), colour),
                new VertexPositionTextureColour (b, new Vector2 (0, 1), colour),
                new VertexPositionTextureColour (c, new Vector2 (1, 1), colour),
                new VertexPositionTextureColour (d, new Vector2 (1, 0), colour),
            };
            q.blend = BlendMode.Default;
            q.tex = null;

            return q;
        }
コード例 #6
0
ファイル: ColourChanger.cs プロジェクト: gitter-badger/blimey
        public override void OnUpdate(AppTime time)
        {
            _timer -= time.Delta;

            if( _timer < 0f )
            {
                _timer = _colourChangeTime - _timer;
                _current = _target;
                _target = RandomGenerator.Default.GetRandomColour();
            }

            Single lerpVal = 1f - _timer;
            if(lerpVal < 0f) lerpVal = 0f;

            Rgba32 colToSet = Rgba32.Lerp(_current, _target, lerpVal);

            _renderer.Material.SetColour("MaterialColour", colToSet);
        }
コード例 #7
0
ファイル: BmpDecoder.cs プロジェクト: jtippet/IcoTools
        private static void ReadIndexedBitmap(ByteReader reader, ParseContext context, uint bitDepth, uint colorTableSize, int height, int width, IcoFrame source)
        {
            var anyReservedChannel  = false;
            var anyIndexOutOfBounds = false;

            if (colorTableSize == 0)
            {
                colorTableSize = 1u << (int)bitDepth;
            }

            source.Encoding.PaletteSize = colorTableSize;

            if (colorTableSize > 1u << (int)bitDepth)
            {
                throw new InvalidIcoFileException(IcoErrorCode.InvalidBitapInfoHeader_biClrUsed, $"BITMAPINFOHEADER.biClrUsed is greater than 2^biBitCount (biClrUsed == {colorTableSize}, biBitCount = {bitDepth}).", context);
            }
            else if (colorTableSize < 1u << (int)bitDepth)
            {
                context.Reporter.WarnLine(IcoErrorCode.UndersizedColorTable, $"This bitmap uses a color table that is smaller than the bit depth ({colorTableSize} < 2^{bitDepth})", context.DisplayedPath, context.ImageDirectoryIndex.Value);
            }

            var colorTable = new Rgba32[colorTableSize];

            for (var i = 0; i < colorTableSize; i++)
            {
                var c = new Bgra32
                {
                    PackedValue = reader.NextUint32()
                };

                if (c.A != 0)
                {
                    anyReservedChannel = true;
                }

                c.A           = 255;
                colorTable[i] = c.ToRgba32();
            }

            var padding = reader.SeekOffset % 4;

            for (var y = height - 1; y >= 0; y--)
            {
                var bits = new BitReader(reader);

                for (var x = 0; x < width; x++)
                {
                    var colorIndex = bits.NextBit(bitDepth);

                    if (colorIndex >= colorTableSize)
                    {
                        anyIndexOutOfBounds     = true;
                        source.CookedData[x, y] = Rgba32.Black;
                    }
                    else
                    {
                        source.CookedData[x, y] = colorTable[colorIndex];
                    }
                }

                while ((reader.SeekOffset % 4) != padding)
                {
                    reader.SeekOffset += 1;
                }
            }

            switch (bitDepth)
            {
            case 1:
                source.Encoding.PixelFormat = BitmapEncoding.Pixel_indexed1;
                break;

            case 2:
                source.Encoding.PixelFormat = BitmapEncoding.Pixel_indexed2;
                break;

            case 4:
                source.Encoding.PixelFormat = BitmapEncoding.Pixel_indexed4;
                break;

            case 8:
                source.Encoding.PixelFormat = BitmapEncoding.Pixel_indexed8;
                break;
            }

            ReadBitmapMask(reader, context, height, width, source);

            if (anyReservedChannel)
            {
                context.Reporter.WarnLine(IcoErrorCode.NonzeroAlpha, $"Reserved Alpha channel used in color table.", context.DisplayedPath, context.ImageDirectoryIndex.Value);
            }

            if (anyIndexOutOfBounds)
            {
                context.Reporter.WarnLine(IcoErrorCode.IndexedColorOutOfBounds, $"Bitmap uses color at illegal index; pixel filled with Black color.", context.DisplayedPath, context.ImageDirectoryIndex.Value);
            }
        }
コード例 #8
0
        static Texture CreateTextureFromImage(string path, string textureName, TextureSettings textureSettings, bool isDecalsWad)
        {
            // Load the main texture image, and any available mipmap images:
            using (var images = new DisposableList <Image <Rgba32> >(GetMipmapFilePaths(path).Prepend(path)
                                                                     .Select(imagePath => File.Exists(imagePath) ? ImageReading.ReadImage(imagePath) : null)))
            {
                // Verify image sizes:
                if (images[0].Width % 16 != 0 || images[0].Height % 16 != 0)
                {
                    throw new InvalidDataException($"Texture '{path}' width or height is not a multiple of 16.");
                }

                for (int i = 1; i < images.Count; i++)
                {
                    if (images[i] != null && (images[i].Width != images[0].Width >> i || images[i].Height != images[0].Height >> i))
                    {
                        throw new InvalidDataException($"Mipmap {i} for texture '{path}' width or height does not match texture size.");
                    }
                }

                if (isDecalsWad)
                {
                    return(CreateDecalTexture(textureName, images.ToArray(), textureSettings));
                }


                var filename             = Path.GetFileName(path);
                var isTransparentTexture = filename.StartsWith("{");
                var isAnimatedTexture    = AnimatedTextureNameRegex.IsMatch(filename);
                var isWaterTexture       = filename.StartsWith("!");

                // Create a suitable palette, taking special texture types into account:
                var transparencyThreshold = isTransparentTexture ? Clamp(textureSettings.TransparencyThreshold ?? 128, 0, 255) : 0;
                Func <Rgba32, bool> isTransparentPredicate = null;
                if (textureSettings.TransparencyColor != null)
                {
                    var transparencyColor = textureSettings.TransparencyColor.Value;
                    isTransparentPredicate = color => color.A < transparencyThreshold || (color.R == transparencyColor.R && color.G == transparencyColor.G && color.B == transparencyColor.B);
                }
                else
                {
                    isTransparentPredicate = color => color.A < transparencyThreshold;
                }

                var colorHistogram = ColorQuantization.GetColorHistogram(images.Where(image => image != null), isTransparentPredicate);
                var maxColors      = 256 - (isTransparentTexture ? 1 : 0) - (isWaterTexture ? 2 : 0);
                var colorClusters  = ColorQuantization.GetColorClusters(colorHistogram, maxColors);

                // Always make sure we've got a 256-color palette (some tools can't handle smaller palettes):
                if (colorClusters.Length < maxColors)
                {
                    colorClusters = colorClusters
                                    .Concat(Enumerable
                                            .Range(0, maxColors - colorClusters.Length)
                                            .Select(i => (new Rgba32(), new[] { new Rgba32() })))
                                    .ToArray();
                }

                // Make palette adjustments for special textures:
                if (isWaterTexture)
                {
                    var fogColor     = textureSettings.WaterFogColor ?? ColorQuantization.GetAverageColor(colorHistogram);
                    var fogIntensity = new Rgba32((byte)Clamp(textureSettings.WaterFogColor?.A ?? (int)((1f - GetBrightness(fogColor)) * 255), 0, 255), 0, 0);

                    colorClusters = colorClusters.Take(3)
                                    .Append((fogColor, new[] { fogColor }))         // Slot 3: water fog color
                                    .Append((fogIntensity, new[] { fogIntensity })) // Slot 4: fog intensity (stored in red channel)
                                    .Concat(colorClusters.Skip(3))
                                    .ToArray();
                }

                if (isTransparentTexture)
                {
                    var colorKey = new Rgba32(0, 0, 255);
                    colorClusters = colorClusters
                                    .Append((colorKey, new[] { colorKey })) // Slot 255: used for transparent pixels
                                    .ToArray();
                }

                // Create the actual palette, and a color index lookup cache:
                var palette = colorClusters
                              .Select(cluster => cluster.Item1)
                              .ToArray();
                var colorIndexMappingCache = new Dictionary <Rgba32, int>();
                for (int i = 0; i < colorClusters.Length; i++)
                {
                    (_, var colors) = colorClusters[i];
                    foreach (var color in colors)
                    {
                        colorIndexMappingCache[color] = i;
                    }
                }

                // Create any missing mipmaps:
                for (int i = 1; i < images.Count; i++)
                {
                    if (images[i] == null)
                    {
                        images[i] = images[0].Clone(context => context.Resize(images[0].Width >> i, images[0].Height >> i));
                    }
                }

                // Create texture data:
                var textureData = images
                                  .Select(image => CreateTextureData(image, palette, colorIndexMappingCache, textureSettings, isTransparentPredicate, disableDithering: isAnimatedTexture))
                                  .ToArray();

                return(Texture.CreateMipmapTexture(
                           name: textureName,
                           width: images[0].Width,
                           height: images[0].Height,
                           imageData: textureData[0],
                           palette: palette,
                           mipmap1Data: textureData[1],
                           mipmap2Data: textureData[2],
                           mipmap3Data: textureData[3]));
            }
        }
コード例 #9
0
        public static void SetLine4(Image <Rgba32> image, int x0, int y0, int x1, int y1, Rgba32 color)
        {
            var steep = Math.Abs(x0 - x1) < Math.Abs(y0 - y1);

            if (steep)
            {
                var tmp = x0;
                x0 = y0;
                y0 = tmp;

                tmp = x1;
                x1  = y1;
                y1  = tmp;
            }

            if (x0 > x1)
            {
                var tmp = x0;
                x0 = x1;
                x1 = tmp;

                tmp = y0;
                y0  = y1;
                y1  = tmp;
            }

            var   dx     = Math.Abs(x1 - x0);
            var   dy     = Math.Abs(y1 - y0);
            float derror = dy / (float)dx;
            float error  = 0;

            int y = y0;

            for (int x = x0; x <= x1; x++)
            {
                if (steep)
                {
                    image[y, x] = color;
                }
                else
                {
                    image[x, y] = color;
                }

                error += derror;

                if (!(error > 0.5f))
                {
                    continue;
                }
                y     += y1 > y0 ? 1 : -1;
                error -= 1f;
            }
        }
コード例 #10
0
ファイル: Fudge.Tests.cs プロジェクト: gitter-badger/blimey
        public void TestRandomValues_i()
        {
            var rand = new System.Random();
            var buff = new Byte[4];

            for(Int32 i = 0; i < Settings.NumTests; ++i)
            {
                rand.NextBytes(buff);
                UInt32 packed = BitConverter.ToUInt32(buff, 0);
                var packedObj = new Rgba32();
                packedObj.PackedValue = packed;
                Single realR, realG, realB, realA = 0f;
                packedObj.UnpackTo(out realR, out realG, out realB, out realA);
                var newPackedObj = new Rgba32(realR, realG, realB, realA);
                Assert.That(newPackedObj.PackedValue, Is.EqualTo(packed));
            }
        }
コード例 #11
0
ファイル: BasicApp.cs プロジェクト: dreamsxin/engine-1
        public Boolean Update(Platform platform, AppTime time)
        {
            if (platform.Input.Keyboard.IsFunctionalKeyDown (FunctionalKey.Escape))
                return true;

            colourChangeProgress += time.Delta / colourChangeTime;

            if (colourChangeProgress >= 1f)
            {
                colourChangeProgress = 0f;
                currentColour = nextColour;
                nextColour = RandomColours.GetNext();
            }

            foreach (var element in elements)
                element.Update (platform, time);

            return false;
        }
コード例 #12
0
ファイル: SpritePrimitive.cs プロジェクト: dreamsxin/engine-1
 /// <summary>
 /// Sets the colour of an individual Quad vertex.
 /// </summary>
 public void SetColour(Rgba32 zColour, Int32 zI)
 {
     System.Diagnostics.Debug.Assert (zI < 4 && zI >= 0);
     quad.v[zI].Colour = zColour;
 }
コード例 #13
0
        public IEnumerable <PPMFrame> BlackWhiteFrames(string Folder)
        {
            var images = Directory.GetFiles($"{Folder}", "*.png");

            MathUtils.NumericalSort(images);
            Rgba32   ColorBlack    = Rgba32.ParseHex("#000000");
            Rgba32   ColorWhite    = Rgba32.ParseHex("FFFFFF");
            PPMFrame PreviousFrame = null;

            for (int i = 0; i < images.Length; i++)
            {
                PPMFrame frame = new PPMFrame();

                var ColorImage = (Image <Rgba32>)Image.Load($"{Folder}/frame_{i}.png");

                int white = 0;
                int black = 0;
                for (int y = 0; y < 192; y++)
                {
                    frame.Layer1.SetLineEncoding(y, LineEncoding.InvertedCodedLine);
                    frame.Layer2.SetLineEncoding(y, LineEncoding.SkipLine);
                    for (int x = 0; x < 256; x++)
                    {
                        var ColorPixel = ColorImage[x, y];
                        var Black      = ColorPixel == ColorBlack;

                        if (Black)
                        {
                            frame.Layer1[x, y] = true;

                            black++;
                        }
                        else
                        {
                            frame.Layer1[x, y] = false;

                            white++;
                        }
                    }
                }

                if (black > white)
                {
                    for (int y = 0; y < 192; y++)
                    {
                        for (int x = 0; x < 256; x++)
                        {
                            var ColorPixel = ColorImage[x, y];
                            var Black      = ColorPixel == ColorBlack;

                            if (Black)
                            {
                                frame.Layer1[x, y] = false;
                            }
                            else
                            {
                                frame.Layer1[x, y] = true;
                            }
                        }
                    }
                }

                byte header = 0;
                if (i == 0)
                {
                    header |= 1 << 7; // no frame diffing
                }

                header |= (byte)(((int)PenColor.Red) << 3);
                header |= (byte)(((int)PenColor.Inverted) << 1);
                header |= (byte)((white > black ? 1 : 0) << 0);
                frame._firstByteHeader = header;

                if (i == 0)
                {
                    PreviousFrame = frame;
                    yield return(frame);
                }
                else
                {
                    var temp = frame.CreateDiff0(PreviousFrame);
                    PreviousFrame = frame;
                    yield return(temp);
                }
            }
        }
コード例 #14
0
        public IEnumerable <PPMFrame> ThreeColorFrames(string Folder, PenColor color)
        {
            var images = Directory.GetFiles($"{Folder}", "*.png");

            MathUtils.NumericalSort(images);
            PPMFrame PreviousFrame = null;

            for (int i = 0; i < images.Length; i++)
            {
                PPMFrame frame = new PPMFrame();

                Rgba32 ColorBlue  = Rgba32.ParseHex("#0000ff");
                Rgba32 ColorRed   = Rgba32.ParseHex("#FF0000");
                Rgba32 ColorBlack = Rgba32.ParseHex("#000000");
                Rgba32 ColorWhite = Rgba32.ParseHex("FFFFFF");

                var ColorImage = (Image <Rgba32>)Image.Load($"{Folder}/frame_{i}.png");
                int black      = 0;
                int white      = 0;
                for (int x = 0; x < 256; x++)
                {
                    for (int y = 0; y < 192; y++)
                    {
                        frame.Layer1.SetLineEncoding(y, LineEncoding.CodedLine);
                        frame.Layer2.SetLineEncoding(y, LineEncoding.CodedLine);

                        var ColorPixel     = ColorImage[x, y];
                        var ColorLuminance = (0.299 * ColorPixel.R + 0.587 * ColorPixel.G + 0.114 * ColorPixel.B) / 255;

                        var Red   = ColorPixel == ColorRed;
                        var Blue  = ColorPixel == ColorBlue;
                        var White = ColorPixel == ColorWhite;
                        var Black = ColorPixel == ColorBlack;

                        if (Red)
                        {
                            frame.Layer2[x, y] = true;
                            frame.Layer1[x, y] = false;
                        }
                        if (Blue)
                        {
                            frame.Layer2[x, y] = true;
                            frame.Layer1[x, y] = false;
                        }
                        if (White)
                        {
                            frame.Layer2[x, y] = false;
                            frame.Layer1[x, y] = false;
                            white++;
                        }
                        if (Black)
                        {
                            frame.Layer2[x, y] = false;
                            frame.Layer1[x, y] = true;
                            black++;
                        }
                    }
                }

                if (black > white)
                {
                    for (int x = 0; x < 256; x++)
                    {
                        for (int y = 0; y < 192; y++)
                        {
                            var ColorPixel     = ColorImage[x, y];
                            var ColorLuminance = (0.299 * ColorPixel.R + 0.587 * ColorPixel.G + 0.114 * ColorPixel.B) / 255;

                            var Red   = ColorPixel == ColorRed;
                            var Blue  = ColorPixel == ColorBlue;
                            var White = ColorPixel == ColorWhite;
                            var Black = ColorPixel == ColorBlack;

                            if (Red)
                            {
                                frame.Layer2[x, y] = true;
                                frame.Layer1[x, y] = false;
                            }
                            if (Blue)
                            {
                                frame.Layer2[x, y] = true;
                                frame.Layer1[x, y] = false;
                            }
                            if (White)
                            {
                                frame.Layer2[x, y] = false;
                                frame.Layer1[x, y] = true;
                            }
                            if (Black)
                            {
                                frame.Layer2[x, y] = false;
                                frame.Layer1[x, y] = false;
                            }
                        }
                    }
                }
                byte header = 0;
                if (i == 0)
                {
                    header |= 1 << 7; // no frame diffing
                }
                header |= (byte)(((int)color) << 3);
                header |= (byte)(((int)PenColor.Inverted) << 1);
                header |= (byte)(white > black ? 1 : 0);
                frame._firstByteHeader = header;

                frame.PaperColor      = (PaperColor)(frame._firstByteHeader % 2);
                frame.Layer1.PenColor = (PenColor)((frame._firstByteHeader >> 1) & 3);
                frame.Layer2.PenColor = (PenColor)((frame._firstByteHeader >> 3) & 3);

                if (i == 0)
                {
                    PreviousFrame = frame;
                    yield return(frame);
                }
                else
                {
                    var temp = frame.CreateDiff0(PreviousFrame);
                    PreviousFrame = frame;
                    yield return(temp);
                }
            }
        }
コード例 #15
0
        public IEnumerable <PPMFrame> FullColorFrames(string Folder)
        {
            var images = Directory.GetFiles($"{Folder}", "*.png");

            MathUtils.NumericalSort(images);
            var      PreviousColor = PenColor.Red;
            PPMFrame PreviousFrame = null;

            for (int i = 0; i < images.Length; i++)
            {
                PPMFrame frame = new PPMFrame();

                int    black      = 0;
                int    white      = 0;
                Rgba32 ColorBlue  = Rgba32.ParseHex("#0000ff");
                Rgba32 ColorRed   = Rgba32.ParseHex("#FF0000");
                Rgba32 ColorBlack = Rgba32.ParseHex("#000000");
                Rgba32 ColorWhite = Rgba32.ParseHex("FFFFFF");

                var            ColorImage = (Image <Rgba32>)Image.Load($"{Folder}/frame_{i}.png");
                Image <Rgba32> GrayImage  = null;
                try
                {
                    GrayImage = (Image <Rgba32>)Image.Load($"tmp/frame_{i}.png");
                }
                catch (Exception e)
                {
                    GrayImage = (Image <Rgba32>)Image.Load($"tmp/frame_{i - 1}.png");
                }

                GrayImage.Mutate(x => x.BinaryThreshold(0.5f));

                //Set all the funny pixels
                for (int x = 0; x < 256; x++)
                {
                    for (int y = 0; y < 192; y++)
                    {
                        frame.Layer1.SetLineEncoding(y, LineEncoding.CodedLine);
                        frame.Layer2.SetLineEncoding(y, LineEncoding.CodedLine);
                        var ColorPixel     = ColorImage[x, y];
                        var ColorLuminance = (0.299 * ColorPixel.R + 0.587 * ColorPixel.G + 0.114 * ColorPixel.B) / 255;

                        var GrayPixel     = GrayImage[x, y];
                        var GrayLuminance = (0.299 * GrayPixel.R + 0.587 * GrayPixel.G + 0.114 * GrayPixel.B) / 255;

                        var Red   = ColorPixel == ColorRed;
                        var Blue  = ColorPixel == ColorBlue;
                        var White = ColorPixel == ColorWhite;
                        var Black = ColorPixel == ColorBlack;

                        if (Red)
                        {
                            if (PreviousColor == PenColor.Blue)
                            {
                                if (GrayLuminance < 0.5f)
                                {
                                    frame.Layer1[x, y] = true;
                                    frame.Layer2[x, y] = false;
                                    black++;
                                }
                                else
                                {
                                    white++;
                                }
                            }
                            else
                            {
                                frame.Layer1[x, y] = false;
                                frame.Layer2[x, y] = true;
                            }
                        }
                        if (Blue)
                        {
                            if (PreviousColor == PenColor.Red)
                            {
                                if (GrayLuminance < 0.5f)
                                {
                                    frame.Layer1[x, y] = true;
                                    frame.Layer2[x, y] = false;
                                    black++;
                                }
                                else
                                {
                                    white++;
                                }
                            }
                            else
                            {
                                frame.Layer1[x, y] = false;
                                frame.Layer2[x, y] = true;
                            }
                        }
                        if (White)
                        {
                            frame.Layer1[x, y] = false;
                            frame.Layer2[x, y] = false;
                            white++;
                        }
                        if (Black)
                        {
                            frame.Layer1[x, y] = true;
                            frame.Layer2[x, y] = false;
                            black++;
                        }
                    }
                }

                byte header = 0;

                if (i == 0)
                {
                    header |= 1 << 7; // no frame diffing
                }

                if (PreviousColor == PenColor.Red)
                {
                    header       |= (byte)((int)PenColor.Red << 3);
                    PreviousColor = PenColor.Blue;
                }
                else
                {
                    header       |= (byte)((int)PenColor.Blue << 3);
                    PreviousColor = PenColor.Red;
                }

                header |= (byte)(((int)PenColor.Inverted) << 1);
                header |= (byte)(white > black ? 1 : 0);
                frame._firstByteHeader = header;

                if (black > white)
                {
                    for (int x = 0; x < 256; x++)
                    {
                        for (int y = 0; y < 192; y++)
                        {
                            var ColorPixel     = ColorImage[x, y];
                            var ColorLuminance = (0.299 * ColorPixel.R + 0.587 * ColorPixel.G + 0.114 * ColorPixel.B) / 255;

                            var GrayPixel     = GrayImage[x, y];
                            var GrayLuminance = (0.299 * GrayPixel.R + 0.587 * GrayPixel.G + 0.114 * GrayPixel.B) / 255;

                            var Red   = ColorPixel == ColorRed;
                            var Blue  = ColorPixel == ColorBlue;
                            var White = ColorPixel == ColorWhite;
                            var Black = ColorPixel == ColorBlack;

                            if (Red)
                            {
                                if (PreviousColor == PenColor.Red)
                                {
                                    if (GrayLuminance > 0.5f)
                                    {
                                        frame.Layer1[x, y] = true;
                                        frame.Layer2[x, y] = false;
                                        black++;
                                    }
                                    else
                                    {
                                        frame.Layer1[x, y] = false;
                                        frame.Layer2[x, y] = false;
                                    }
                                }
                                else
                                {
                                    frame.Layer1[x, y] = false;
                                    frame.Layer2[x, y] = true;
                                }
                            }
                            if (Blue)
                            {
                                if (PreviousColor == PenColor.Blue)
                                {
                                    if (GrayLuminance > 0.5f)
                                    {
                                        frame.Layer1[x, y] = true;
                                        frame.Layer2[x, y] = false;
                                        black++;
                                    }
                                    else
                                    {
                                        frame.Layer1[x, y] = false;
                                        frame.Layer2[x, y] = false;
                                    }
                                }
                                else
                                {
                                    frame.Layer1[x, y] = false;
                                    frame.Layer2[x, y] = true;
                                }
                            }
                            if (White)
                            {
                                frame.Layer1[x, y] = true;
                                frame.Layer2[x, y] = false;
                            }
                            if (Black)
                            {
                                frame.Layer1[x, y] = false;
                                frame.Layer2[x, y] = false;
                            }
                        }
                    }
                }

                frame.PaperColor      = (PaperColor)(frame._firstByteHeader % 2);
                frame.Layer1.PenColor = (PenColor)((frame._firstByteHeader >> 1) & 3);
                frame.Layer2.PenColor = (PenColor)((frame._firstByteHeader >> 3) & 3);
                if (i == 0)
                {
                    PreviousFrame = frame;
                    yield return(frame);
                }
                else
                {
                    var temp = frame.CreateDiff0(PreviousFrame);
                    PreviousFrame = frame;
                    yield return(temp);
                }
            }
        }
コード例 #16
0
 public static void ReColour(this Image <Rgba32> img, System.Drawing.Point pos, Rgba32 newCol)
 {
     if (!img.ValidCoord(pos))
     {
         return;
     }
     img[pos.X, img.Height - pos.Y] = newCol;
 }
コード例 #17
0
ファイル: ImageGenerator.cs プロジェクト: kayyer/sigstat
 /// <summary> Initializes a new instance of the <see cref="ImageGenerator"/> class with specified settings. </summary>
 /// <param name="writeToFile">Whether to save the generated image into a png file.</param>
 /// <param name="foregroundColor">Ink color.</param>
 /// <param name="backgroundColor">Paper color.</param>
 public ImageGenerator(bool writeToFile, Rgba32 foregroundColor, Rgba32 backgroundColor)
 {
     this.WriteToFile = writeToFile;
     ForegroundColor  = foregroundColor;
     BackgroundColor  = backgroundColor;
 }
コード例 #18
0
ファイル: Util.cs プロジェクト: PJB3005/SS14.Noise
 public static Color4 Convert(this Rgba32 color)
 {
     return(new Color4(color.R, color.G, color.B, color.A));
 }
コード例 #19
0
 public AngularColorStop(Rgba32 color, double position, double angle = 0)
 {
     Color    = color;
     Position = position;
     Angle    = angle;
 }
コード例 #20
0
ファイル: PlatformDemo00.cs プロジェクト: dreamsxin/engine-1
        void Update()
        {
            var deltaTime = (Single)(timer.Elapsed.TotalSeconds - previousTimeSpan.TotalSeconds);
            previousTimeSpan = timer.Elapsed;
            elapsedTime += deltaTime;

            colourChangeProgress += deltaTime / colourChangeTime;

            if (colourChangeProgress >= 1f)
            {
                colourChangeProgress = 0f;
                currentColour = nextColour;
                nextColour = RandomColours.GetNext();
            }

            foreach (var element in elements)
                element.Update (api, elapsedTime);
        }
コード例 #21
0
ファイル: Rgb565.cs プロジェクト: steven1152/maplestory.io
 public void PackFromRgba32(Rgba32 source)
 {
     this.PackFromVector4(source.ToVector4());
 }
コード例 #22
0
        public TestSceneCircularProgress()
        {
            const int width = 128;

            var image = new Image <Rgba32>(width, 1);

            gradientTextureHorizontal = new Texture(width, 1, true);

            for (int i = 0; i < width; ++i)
            {
                float brightness = (float)i / (width - 1);
                image[i, 0] = new Rgba32((byte)(128 + (1 - brightness) * 127), (byte)(128 + brightness * 127), 128, 255);
            }

            gradientTextureHorizontal.SetData(new TextureUpload(image));

            image = new Image <Rgba32>(width, 1);

            gradientTextureVertical = new Texture(1, width, true);

            for (int i = 0; i < width; ++i)
            {
                float brightness = (float)i / (width - 1);
                image[i, 0] = new Rgba32((byte)(128 + (1 - brightness) * 127), (byte)(128 + brightness * 127), 128, 255);
            }

            gradientTextureVertical.SetData(new TextureUpload(image));

            image = new Image <Rgba32>(width, width);

            gradientTextureBoth = new Texture(width, width, true);

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < width; ++j)
                {
                    float brightness  = (float)i / (width - 1);
                    float brightness2 = (float)j / (width - 1);
                    image[i, j] = new Rgba32(
                        (byte)(128 + (1 + brightness - brightness2) / 2 * 127),
                        (byte)(128 + (1 + brightness2 - brightness) / 2 * 127),
                        (byte)(128 + (brightness + brightness2) / 2 * 127),
                        255);
                }
            }

            gradientTextureBoth.SetData(new TextureUpload(image));

            Children = new Drawable[]
            {
                clock = new CircularProgress
                {
                    Width            = 0.8f,
                    Height           = 0.8f,
                    RelativeSizeAxes = Axes.Both,
                    Anchor           = Anchor.Centre,
                    Origin           = Anchor.Centre,
                },
            };

            AddStep("Forward", delegate { setRotationMode(1); });
            AddStep("Backward", delegate { setRotationMode(2); });
            AddStep("Transition Focus", delegate { setRotationMode(3); });
            AddStep("Transition Focus 2", delegate { setRotationMode(4); });
            AddStep("Forward/Backward", delegate { setRotationMode(0); });

            AddStep("Horizontal Gradient Texture", delegate { setTexture(1); });
            AddStep("Vertical Gradient Texture", delegate { setTexture(2); });
            AddStep("2D Graident Texture", delegate { setTexture(3); });
            AddStep("White Texture", delegate { setTexture(0); });

            AddStep("Red Colour", delegate { setColour(1); });
            AddStep("Horzontal Gradient Colour", delegate { setColour(2); });
            AddStep("Vertical Gradient Colour", delegate { setColour(3); });
            AddStep("2D Gradient Colour", delegate { setColour(4); });
            AddStep("White Colour", delegate { setColour(0); });

            AddStep("Forward Transform", delegate { transform(0); });
            AddStep("Backward Transform", delegate { transform(1); });
            AddStep("Fwd/Bwd Transform", delegate { transform(2); });
            AddStep("Easing Transform", delegate { transform(3); });

            AddSliderStep("Fill", 0, 10, 10, fill => clock.InnerRadius = fill / 10f);
        }
コード例 #23
0
        public Rgba32 GetRandomColourNearby(Rgba32 zColour, float zVariation)
        {
            Vector4 data = zColour.ToVector4();

            float variation = zVariation / 2.0f;

            //float lowerW = data.W - variation;
            //float upperW = data.W + variation;
            //float w = Random_Float(lowerW, upperW);
            //data.W = Euclid.Limit(ref w, 0.0f, 1.0f);

            float lowerX = data.X - variation;
            float upperX = data.X + variation;
            float x = GetRandomSingle(lowerX, upperX);
            data.X = MathsUtils.Limit(ref x, 0.0f, 1.0f);

            float lowerY = data.Y - variation;
            float upperY = data.Y + variation;
            float y = GetRandomSingle(lowerY, upperY);
            data.Y = MathsUtils.Limit(ref y, 0.0f, 1.0f);

            float lowerZ = data.Z - variation;
            float upperZ = data.Z + variation;
            float z = GetRandomSingle(lowerZ, upperZ);
            data.Z = MathsUtils.Limit(ref z, 0.0f, 1.0f);

            Rgba32 col = new Rgba32(data.X, data.Y, data.Z, data.W);
            return col;
        }
コード例 #24
0
        public static string GenerateOneDay(WeatherObject day, string output)
        {
            string border = "Weather/one.png";


            var fontCollection = new FontCollection();
            var parentFont     = fontCollection.Install("Weather/main.ttf").CreateFont(70, FontStyle.Bold);
            var childFont      = new Font(parentFont, 90);
            var subFont        = new Font(parentFont, 35);

            using (Image <Rgba32> backgroundImage = Image.Load(border))
            {
                int    imageX  = 105;
                string maxTemp = day.High + "°C";
                string minTemp = day.Low + "°C";

                var maxSize = TextMeasurer.Measure(maxTemp, new RendererOptions(parentFont));

                var maxOffset = 180 - maxSize.Width / 2;

                var minSize = TextMeasurer.Measure(minTemp, new RendererOptions(parentFont));

                var minOffset = 405 - minSize.Width / 2;

                string dayString = DateTime.Today.ToString($"ddd, dd MMM");

                var dateSize = TextMeasurer.Measure(dayString, new RendererOptions(parentFont));

                var dateOffset = 307 - dateSize.Width / 2;

                string windDescriptor = "";
                if (day.WindSpeed < 15)
                {
                    windDescriptor = "Light";
                }
                if (day.WindSpeed >= 15 && day.WindSpeed < 30)
                {
                    windDescriptor = "Moderate";
                }
                if (day.WindSpeed >= 30 && day.WindSpeed < 60)
                {
                    windDescriptor = "Strong";
                }
                if (day.WindSpeed >= 60)
                {
                    windDescriptor = "Gale Force";
                }

                string wind = $"{windDescriptor}, {day.WindSpeed} km/h {day.WindDirection}";

                var windSize = TextMeasurer.Measure(wind, new RendererOptions(subFont));

                var windOffset = 307 - windSize.Width / 2;

                Coords.GeoDate = day.Date;
                string sunrise = "Sunrise: " + Coords.CelestialInfo.SunRise.GetValueOrDefault().ToString("hh:mm tt");
                string sunset  = "Sunset: " + Coords.CelestialInfo.SunSet.GetValueOrDefault().ToString("hh:mm tt");

                var sunriseSize = TextMeasurer.Measure(sunrise, new RendererOptions(subFont));

                var sunriseOffset = 307 - sunriseSize.Width / 2;

                var sunsetSize = TextMeasurer.Measure(sunset, new RendererOptions(subFont));

                var sunsetOffset = 307 - sunsetSize.Width / 2;

                string humidity     = "Humidity: " + day.Humidity + "%";
                var    humiditySize = TextMeasurer.Measure(humidity, new RendererOptions(subFont));

                var humidityOffset = 307 - humiditySize.Width / 2;

                var image1 = Image.Load($"Weather/{day.Type.ToString()}.png");
                backgroundImage.Mutate(x => x.DrawImage(image1, 1, new Point(imageX, 825)).DrawText(dayString, parentFont, Rgba32.Black, new PointF(dateOffset, 370)).DrawText(maxTemp, childFont, Rgba32.Black, new PointF(maxOffset, 445)).DrawText(minTemp, childFont, Rgba32.FromHex("#4E4E4E"), new PointF(minOffset, 445)).DrawText(wind, subFont, Rgba32.Black, new PointF(windOffset, 570)).DrawText(sunrise, subFont, Rgba32.Black, new PointF(sunriseOffset, 620)).DrawText(sunset, subFont, Rgba32.Black, new PointF(sunsetOffset, 670)).DrawText(humidity, subFont, Rgba32.Black, new PointF(humidityOffset, 720)));

                backgroundImage.Save($"Weather/{output}.png");
                return($"Weather/{output}.png");
            }
        }
コード例 #25
0
        public ParticlePrimitive(ParticlePrimitive o)
        {
            this.vecLocation = o.vecLocation;
            this.vecVelocity = o.vecVelocity;

            this.fGravity = o.fGravity;
            this.fRadialAccel = o.fRadialAccel;
            this.fTangentialAccel = o.fTangentialAccel;
            this.fSpin = o.fSpin;
            this.fSpinDelta = o.fSpinDelta;

            this.fSize = o.fSize;
            this.fSizeDelta = o.fSizeDelta;

            this.colColour = o.colColour;     // + alpha
            this.colColourStart = o.colColourStart;
            this.colColourEnd = o.colColourEnd;

            this.fAge = o.fAge;
            this.fTerminalAge = o.fTerminalAge;
        }
コード例 #26
0
 public void FromRgba32(Rgba32 source) => this.FromScaledVector4(source.ToScaledVector4());
コード例 #27
0
                /// <summary>
                /// Add a color into the tree
                /// </summary>
                /// <param name="pixel">The pixel color</param>
                /// <param name="colorBits">The number of significant color bits</param>
                /// <param name="level">The level in the tree</param>
                /// <param name="octree">The tree to which this node belongs</param>
                /// <param name="rgba">The color to map to.</param>
                public void AddColor(TPixel pixel, int colorBits, int level, Octree octree, ref Rgba32 rgba)
                {
                    // Update the color information if this is a leaf
                    if (this.leaf)
                    {
                        this.Increment(pixel, ref rgba);

                        // Setup the previous node
                        octree.TrackPrevious(this);
                    }
                    else
                    {
                        // Go to the next level down in the tree
                        int shift = 7 - level;
                        pixel.ToRgba32(ref rgba);

                        int index = ((rgba.B & Mask[level]) >> (shift - 2)) |
                                    ((rgba.G & Mask[level]) >> (shift - 1)) |
                                    ((rgba.R & Mask[level]) >> shift);

                        OctreeNode child = this.children[index];

                        if (child == null)
                        {
                            // Create a new child node and store it in the array
                            child = new OctreeNode(level + 1, colorBits, octree);
                            this.children[index] = child;
                        }

                        // Add the color to the child node
                        child.AddColor(pixel, colorBits, level + 1, octree, ref rgba);
                    }
                }
コード例 #28
0
 public void ToRgba32(ref Rgba32 dest)
 {
     dest.FromScaledVector4(this.ToScaledVector4());
 }
コード例 #29
0
ファイル: Fudge.Tests.cs プロジェクト: gitter-badger/blimey
 public void TestMemberFn_GetHashCode_i ()
 {
     HashSet<Int32> hs = new HashSet<Int32>();
     var rand = new System.Random();
     var buff = new Byte[4];
     UInt32 collisions = 0;
     for(Int32 i = 0; i < Settings.NumTests; ++i)
     {
         rand.NextBytes(buff);
         UInt32 packed = BitConverter.ToUInt32(buff, 0);
         var packedObj = new Rgba32();
         packedObj.PackedValue = packed;
         Int32 hc = packedObj.GetHashCode ();
         if(hs.Contains(hc)) ++collisions;
         hs.Add(hc);
     }
     Assert.That(collisions, Is.LessThan(10));
 }
コード例 #30
0
 public ImagePreprocessor(Rgba32 backgroundColor, Rgba32 foregroundColor)
 {
     _backgroundColor = backgroundColor;
     _foregroundColor = foregroundColor;
 }
コード例 #31
0
        public Image <Rgba32> ToImage(uint[] palette)
        {
            var totalPixels = SubImages.Sum(x => (long)x.Size.X * (long)x.Size.Y);
            var width       = Math.Max((int)Math.Sqrt(totalPixels), SubImages.Max(x => (int)x.Size.X));

            width = ApiUtil.NextPowerOfTwo(width);

            // First arrange to determine required size and positions, then create the image.
            var positions = new Dictionary <int, (int, int)>();
            int rowHeight = 0;
            int curX = 0, curY = 0;

            for (var index = 0; index < SubImages.Count; index++)
            {
                var si = SubImages[index];
                int w  = (int)si.Size.X;
                int h  = (int)si.Size.Y;

                if (width - (curX + w) >= 0) // Still room left on this row
                {
                    positions[index] = (curX, curY);
                    curX            += w;
                    if (h > rowHeight)
                    {
                        rowHeight = h;
                    }
                }
                else // Start a new row
                {
                    curY            += rowHeight;
                    rowHeight        = h;
                    positions[index] = (0, curY);
                    curX             = w;
                }
            }

            if (curX > 0)
            {
                curY += rowHeight;
            }

            var height = curY;

            Rgba32[] rgbaPixels = new Rgba32[width * height];
            unsafe
            {
                fixed(Rgba32 *pixelPtr = rgbaPixels)
                {
                    for (var index = 0; index < SubImages.Count; index++)
                    {
                        GetSubImageOffset(index, out var siw, out var sih, out var offset, out var stride);
                        ReadOnlySpan <byte> fromSlice = TextureData.Slice(offset, siw + (sih - 1) * stride);
                        var from = new ReadOnlyByteImageBuffer((uint)siw, (uint)sih, (uint)stride, fromSlice);
                        var(toX, toY) = positions[index];
                        Span <uint> toBuffer = new Span <uint>((uint *)pixelPtr, rgbaPixels.Length);
                        toBuffer = toBuffer.Slice(toX + toY * width);
                        var to = new UIntImageBuffer((uint)siw, (uint)sih, width, toBuffer);
                        CoreUtil.Blit8To32(from, to, palette, 255, 0);
                    }
                }
            }

            Image <Rgba32> image = new Image <Rgba32>(width, height);

            image.Frames.AddFrame(rgbaPixels);
            image.Frames.RemoveFrame(0);
            return(image);
        }
コード例 #32
0
        protected static IEnumerable <Point> GetEncapsulatedPixels(Image <Rgba32> image, Rgba32 color, Rgba32 borderColor, int?maxDistanceToSearch = null, int colorTolerance = 30)
        {
            var imageHeight = image.Height;
            var imageWidth  = image.Width;

            for (var y = 0; y < imageHeight; y++)
            {
                for (var x = 0; x < imageWidth; x++)
                {
                    if (image[x, y] != color)
                    {
                        continue;
                    }
                    var leftBorderFound   = false;
                    var rightBorderFound  = false;
                    var topBorderFound    = false;
                    var bottomBorderFound = false;
                    // Ok we found a pixel with the given color, let's check if it's encapsulated
                    var maxDistance = maxDistanceToSearch ?? Math.Max(x, imageWidth - x);
                    for (var increment = 1; increment < maxDistance; increment++)
                    {
                        // Check left
                        var xLeft = x - increment;
                        if (xLeft >= 0 && !leftBorderFound)
                        {
                            if (IsColorWithinTolerance(image[xLeft, y], borderColor, colorTolerance))
                            {
                                leftBorderFound = true;
                            }
                        }

                        // Check right
                        var xRight = x + increment;
                        if (xRight < (imageWidth - 1) && !rightBorderFound)
                        {
                            if (IsColorWithinTolerance(image[xRight, y], borderColor, colorTolerance))
                            {
                                rightBorderFound = true;
                            }
                        }

                        if (leftBorderFound && rightBorderFound)
                        {
                            yield return(new Point(x, y));

                            leftBorderFound = rightBorderFound = false;
                            // We do not have to check more pixels as they lay within the same border
                            //x = Math.Min(xRight, imageWidth-1);
                        }

                        // Check top
                        var yTop = y - increment;
                        if (yTop >= 0 && !topBorderFound)
                        {
                            if (IsColorWithinTolerance(image[x, yTop], borderColor, colorTolerance))
                            {
                                topBorderFound = true;
                            }
                        }

                        // Check bottom
                        var yBottom = y + increment;
                        if (yBottom < (imageHeight - 1) && !bottomBorderFound)
                        {
                            if (IsColorWithinTolerance(image[x, yBottom], borderColor, colorTolerance))
                            {
                                bottomBorderFound = true;
                            }
                        }

                        if (topBorderFound && bottomBorderFound)
                        {
                            yield return(new Point(x, y));

                            topBorderFound = bottomBorderFound = false;
                            // We do not have to check more pixels as they lay within the same border
                            //y = Math.Min(yBottom, imageHeight - 1);
                        }
                    }
                }
            }
        }
コード例 #33
0
 static int GetBrightness(Rgba32 color) => (int)(color.R * 0.21 + color.G * 0.72 + color.B * 0.07);
コード例 #34
0
 public static bool IsColorWithinTolerance(Rgba32 pixel, Rgba32 color, int tolerance)
 {
     return((pixel.R >= color.R - tolerance) && (pixel.R <= color.R + tolerance) &&
            (pixel.G >= color.G - tolerance) && (pixel.G <= color.G + tolerance) &&
            (pixel.G >= color.B - tolerance) && (pixel.B <= color.B + tolerance));
 }
コード例 #35
0
 public void FromRgba32(ref Rgba32 source) => throw new System.NotImplementedException();
コード例 #36
0
        protected static IEnumerable <Point> PixelsWithColorAtBorder(Image <Rgba32> image, Rgba32 color)
        {
            var imageHeight = image.Height;
            var imageWidth  = image.Width;

            for (var y = 0; y < imageHeight; y++)
            {
                if (y > 0 && y < (imageHeight - 1))
                {
                    if (image[0, y] == color)
                    {
                        yield return(new Point(0, y));
                    }
                    if (image[imageWidth - 1, y] == color)
                    {
                        yield return(new Point(imageWidth - 1, y));
                    }

                    continue;
                }

                for (var x = 0; x < imageWidth; x++)
                {
                    if (image[x, y] == color)
                    {
                        yield return(new Point(x, y));
                    }
                }
            }
        }
コード例 #37
0
ファイル: PlatformDemo00.cs プロジェクト: dreamsxin/engine-1
 public Demo(IApi zApi)
 {
     api = zApi;
     currentColour = RandomColours.GetNext();
     nextColour = RandomColours.GetNext();
 }
コード例 #38
0
        public static void ProcessImages(List <string> readErrors)
        {
            //Clean up any old and bad paths
            Console.WriteLine("Cleaning up old image conversions...");
            if (Directory.Exists("./Lib/UModel/in_temp/"))
            {
                Directory.Delete("./Lib/UModel/in_temp/", true);
            }
            if (Directory.Exists("./Lib/UModel/out_temp/"))
            {
                Directory.Delete("./Lib/UModel/out_temp/", true);
            }

            //Make structre
            Directory.CreateDirectory("./Lib/UModel/in_temp/");
            Directory.CreateDirectory("./Lib/UModel/out_temp/");

            //First, we copy all packages to a temporary path with their index
            Console.WriteLine($"Now copying {queue.Count} images...");
            for (int i = 0; i < queue.Count; i++)
            {
                string source = queue[i].pathname;
                File.Copy(source, $"./Lib/UModel/in_temp/{i}.uasset");
            }

            //Now, run the conversion
            Console.WriteLine("Now converting images using UModel...");
            Process p = Process.Start(new ProcessStartInfo
            {
                Arguments        = "",
                FileName         = "go.bat",
                WorkingDirectory = "Lib\\UModel\\",
                UseShellExecute  = true
            });

            p.WaitForExit();

            //Now, load and process these images
            int ok = 0;

            Console.WriteLine($"Now processing {queue.Count} images...");
            for (int i = 0; i < queue.Count; i += 1)
            {
                QueuedImage q = queue[i];

                try
                {
                    //Get the directory. It's a little janky, as files are stored in subdirs
                    string[] results = Directory.GetFiles($"./Lib/UModel/out_temp/{i}/");
                    if (results.Length != 1)
                    {
                        throw new Exception("None or too many results found for image.");
                    }

                    //Open FileStream on this
                    using (FileStream imgStream = new FileStream(results[0], FileMode.Open, FileAccess.Read))
                    {
                        //Now, begin reading the TGA data https://en.wikipedia.org/wiki/Truevision_TGA
                        IOMemoryStream imgReader = new IOMemoryStream(imgStream, true);
                        imgReader.position += 3 + 5; //Skip intro, it will always be known
                        imgReader.ReadShort();       //Will always be 0
                        imgReader.ReadShort();       //Will aways be 0
                        short width      = imgReader.ReadShort();
                        short height     = imgReader.ReadShort();
                        byte  colorDepth = imgReader.ReadByte();
                        imgReader.ReadByte();

                        //Now, we can begin reading image data
                        //This appears to be bugged for non-square images right now.
                        using (Image <Rgba32> img = new Image <Rgba32>(width, height))
                        {
                            //Read file
                            byte[] channels;
                            for (int y = 0; y < height; y++)
                            {
                                for (int x = 0; x < width; x++)
                                {
                                    if (colorDepth == 32)
                                    {
                                        //Read four channels
                                        channels = imgReader.ReadBytes(4);

                                        //Set pixel
                                        img[x, width - y - 1] = new Rgba32(channels[2], channels[1], channels[0], channels[3]);
                                    }
                                    else if (colorDepth == 24)
                                    {
                                        //Read three channels
                                        channels = imgReader.ReadBytes(3);

                                        //Set pixel
                                        img[x, width - y - 1] = new Rgba32(channels[2], channels[1], channels[0]);
                                    }
                                }
                            }

                            //Apply mods
                            if (q.mods == ImageModifications.White)
                            {
                                ApplyWhiteMod(img);
                            }

                            //Save original image
                            using (FileStream fs = new FileStream(Program.GetOutputDir() + "assets\\" + q.hiId + FORMAT_TYPE, FileMode.Create))
                                img.SaveAsPng(fs);

                            //Now, downscale
                            img.Mutate(x => x.Resize(64, 64));

                            //Save thumbnail
                            using (FileStream fs = new FileStream(Program.GetOutputDir() + "assets\\" + q.loId + FORMAT_TYPE, FileMode.Create))
                                img.SaveAsPng(fs, new PngEncoder
                                {
                                    CompressionLevel = 9
                                });

                            ok++;
                        }
                    }
                } catch (Exception ex)
                {
                    Console.WriteLine($"Failed to process image {q.classname} with error {ex.Message}");
                    readErrors.Add($"Failed to process image {q.classname} with error {ex.Message} {ex.StackTrace}");
                }
            }

            Console.WriteLine($"Processed {ok}/{queue.Count} images.");

            //Clean up any old and bad paths
            Console.WriteLine("Cleaning up...");
            if (Directory.Exists("./Lib/UModel/in_temp/"))
            {
                Directory.Delete("./Lib/UModel/in_temp/", true);
            }
            if (Directory.Exists("./Lib/UModel/out_temp/"))
            {
                Directory.Delete("./Lib/UModel/out_temp/", true);
            }
        }
コード例 #39
0
ファイル: SpritePrimitive.cs プロジェクト: dreamsxin/engine-1
 // SETTERS
 // ────────────────────────────────────────────────────────────────────────────────────────────────────────── //
 public void SetColour(Rgba32 zColour)
 {
     quad.v[0].Colour =
     quad.v[1].Colour =
     quad.v[2].Colour =
     quad.v[3].Colour = zColour;
 }
コード例 #40
0
 public void FromRgba32(ref Rgba32 source)
 {
     this = Unsafe.As <Rgba32, TestRgba>(ref source);
 }
コード例 #41
0
ファイル: Scene.cs プロジェクト: dreamsxin/engine-1
 public void ChangeBackgroundColour(Rgba32? colour)
 {
     parent.configuration.BackgroundColour = colour;
 }
コード例 #42
0
 public void CopyToRgba32(ref Rgba32 dest)
 {
     dest = Unsafe.As <TestRgba, Rgba32>(ref this);
 }
コード例 #43
0
ファイル: BasicApp.cs プロジェクト: dreamsxin/engine-1
        public void Start(Platform platform)
        {
            shader = Shaders.CreateUnlit (platform);

            Int32 texSize = 256;
            Int32 gridSize = 4;
            Int32 squareSize = texSize / gridSize;

            var colours = new Rgba32 [gridSize*gridSize];

            for (Int32 x = 0; x < gridSize; ++x)
            {
                for (Int32 y = 0; y < gridSize; ++y)
                {
                    colours [x + (y * gridSize)] = RandomColours.GetNext ();
                }
            }

            var texData = new byte[texSize*texSize*4];

            Int32 index = 0;
            for (Int32 x = 0; x < texSize; ++x)
            {
                for (Int32 y = 0; y < texSize; ++y)
                {
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].A;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].R;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].G;
                    texData [index++] = colours[(x/squareSize) + (y/squareSize*gridSize)].B;
                }
            }

            tex = platform.Graphics.CreateTexture (TextureFormat.Rgba32, texSize, texSize, texData );

            elements = new IElement[]
            {
                new Element <CubePosTex, VertPosTex> (shader, tex),
                new Element <CylinderPosTex, VertPosTex> (shader, tex),
                new Element <BillboardPosTexCol, VertPosTexCol> (shader, tex),
                new Element <BillboardPosTex, VertPosTex> (shader, tex),
                new Element <CylinderPosNormTex, VertPosNormTex> (shader, tex),
                new Element <CylinderNormTexPos, VertNormTexPos> (shader, tex),
                new Element <FlowerPosCol, VertPosCol> (shader, null),
                new Element <FlowerPos, VertPos> (shader, null),
            };

            Double s = Math.Sqrt (elements.Length);

            numCols = (Int32) Math.Ceiling (s);

            numRows = (Int32) Math.Floor (s);

            while (elements.Length > numCols * numRows) ++numRows;

            foreach (var element in elements) element.Load (platform);
        }
コード例 #44
0
ファイル: SpriteTrait.cs プロジェクト: dreamsxin/engine-1
        // Called when something has changed to update the sprite's state.
        void ApplyChanges(bool forceApply)
        {
            if( currentWidth != desiredWidth ||
                currentHeight != desiredHeight ||
                currentDepth != desiredDepth ||
                currentPosition != desiredPosition ||
                currentRotation != desiredRotation ||
                currentScale != desiredScale ||
                forceApply)
            {
                //--------------------------------------------------------------
                // PT 1
                // work out where the object is in sprite space
                // from the sprites settingY
                Vector3 ssLocalPostion = new Vector3(desiredPosition.X, desiredDepth, -desiredPosition.Y);

                Quaternion ssLocalRotation;
                Vector3 rotationAxis = Vector3.Up;
                Quaternion.CreateFromAxisAngle(ref rotationAxis, ref desiredRotation, out ssLocalRotation);
                ssLocalRotation.Normalise();

                Vector3 ssLocalScale = new Vector3(
                    desiredWidth * desiredScale,
                    desiredScale,
                    desiredHeight * desiredScale
                    );

                //--------------------------------------------------------------
                // PT 2
                // Convert this to a Matrix44
                Matrix44 scale;
                Matrix44.CreateScale(ref ssLocalScale, out scale);

                Matrix44 rotation;
                Matrix44.CreateFromQuaternion(ref ssLocalRotation, out rotation);

                Matrix44 spriteSpaceLocalLocation =  rotation * scale;

                //Matrix44 translation;
                //Matrix44.CreateScale(ref ssLocalPostion, out translation);
                //spriteSpaceLocalLocation = translation * spriteSpaceLocalLocation;
                spriteSpaceLocalLocation.Translation = ssLocalPostion;

                //--------------------------------------------------------------
                // PT 3
                // next use the inverse SpriteSpace matrix to transform the above into world space
                Matrix44 newLocation =  spriteSpaceLocalLocation * inverseSpriteSpaceMatrix;

                //--------------------------------------------------------------
                // PT 4
                // Decompose the inverted matrix to get the result.
                Vector3 resultPos;
                Quaternion resultRot;
                Vector3 resultScale;
                Boolean decomposeOk;

                Matrix44.Decompose(
                    ref newLocation, out resultScale, out resultRot,
                    out resultPos, out decomposeOk);

                resultRot.Normalise();

                //--------------------------------------------------------------
                // PT 5
                // Apply the result to the parent Scene Object

                this.Parent.Transform.LocalScale = ssLocalScale / this.conf.SpriteSpaceScale; //why not resultScale!
                this.Parent.Transform.LocalRotation = resultRot;
                this.Parent.Transform.LocalPosition = resultPos;

                //this.Parent.Transform.Rotation = newLocation.

                currentWidth = desiredWidth;
                currentHeight = desiredHeight;
                currentDepth = desiredDepth;
                currentPosition = desiredPosition;
                currentRotation = desiredRotation;
                currentScale = desiredScale;
            }

            if(currentTexture != desiredTexture || forceApply)
            {
                currentTexture = desiredTexture;

                if(meshRendererTrait.Material == null)
                    return;

                // then we need to tell the shader which slot to look at
                meshRendererTrait.Material.SetTexture("TextureSampler", desiredTexture);

                // todo: this is all a bit hard coded, it would be good if Platform! had a way of requesting that
                // a texture gets about to an unused slot, then reporting the slot number so we can use it.
            }

            if(currentFlipHorizontal != desiredFlipHorizontal || forceApply)
            {
                currentFlipHorizontal = desiredFlipHorizontal;
            }

            if(currentFlipVertical != desiredFlipVertical || forceApply)
            {
                currentFlipVertical = desiredFlipVertical;
            }

            if(currentColour != desiredColour || forceApply)
            {
                if(meshRendererTrait.Material == null)
                {
                    return;
                }

                meshRendererTrait.Material.SetColour("MaterialColour", desiredColour);

                currentColour = desiredColour;
            }
        }
コード例 #45
0
ファイル: App.cs プロジェクト: gitter-badger/blimey
            public void Update(AppTime time)
            {
                colourChangeTimer += time.Delta;

                if (colourChangeTimer > colourChangeTime)
                {
                    colourChangeTimer = 0.0f;
                    randomColour = RandomGenerator.Default.GetRandomColour();
                }
            }
コード例 #46
0
        private static ConsoleColor GetNearestConsoleColor(Rgba32 color)
        {
            // this is very likely to be awful and hilarious
            var r             = color.R;
            var g             = color.G;
            var b             = color.B;
            var total         = r + g + b;
            var darkThreshold = 0.35m; // how dark a color has to be overall to be the dark version of a color

            var cons = ConsoleColor.White;

            if (total >= 39 && total < 100 && AreClose(r, g) && AreClose(g, b) && AreClose(r, b))
            {
                cons = ConsoleColor.DarkGray;
            }

            if (total >= 100 && total < 180 && AreClose(r, g) && AreClose(g, b) && AreClose(r, b))
            {
                cons = ConsoleColor.Gray;
            }


            // if green is the highest value
            if (g > b && g > r)
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkGreen;
                }
                else
                {
                    cons = ConsoleColor.Green;
                }
            }

            // if red is the highest value
            if (r > g && r > b)
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkRed;
                }
                else
                {
                    cons = ConsoleColor.Red;
                }
            }

            // if blue is the highest value
            if (b > g && b > r)
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkBlue;
                }
                else
                {
                    cons = ConsoleColor.Blue;
                }
            }


            if (r > b && g > b && AreClose(r, g))
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkYellow;
                }
                else
                {
                    cons = ConsoleColor.Yellow;
                }
            }

            if (b > r && g > r && AreClose(b, g))
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkCyan;
                }
                else
                {
                    cons = ConsoleColor.Cyan;
                }
            }

            if (r > g && b > g && AreClose(r, b))
            {
                // ..and color is less that 25% of color
                if (Convert.ToDecimal(total / 765m) < darkThreshold)
                {
                    cons = ConsoleColor.DarkMagenta;
                }
                else
                {
                    cons = ConsoleColor.Magenta;
                }
            }

            if (total >= 180 && AreClose(r, g) && AreClose(g, b) && AreClose(r, b))
            {
                cons = ConsoleColor.White;
            }

            // BLACK
            if (total < 39)
            {
                cons = ConsoleColor.Black;
            }

            return(cons);
        }
コード例 #47
0
        public TextureInfo ConstructTextureWithGpxTrack(TileRange tiles, BoundingBox bbox, string fileName,
                                                        TextureImageFormat mimeType, IEnumerable <GeoPoint> gpxPoints, bool drawGpxVertices = false, Rgba32 color = default(Rgba32), float lineWidth = 5f)
        {
            // where is the bbox in the final image ?

            // get pixel in full map
            int zoomLevel     = tiles.Tiles.First().TileInfo.Zoom;
            var projectedBbox = ConvertWorldToMap(bbox, zoomLevel, tiles.TileSize);
            var tilesBbox     = GetTilesBoundingBox(tiles);
            int xOffset       = (int)(tilesBbox.xMin - projectedBbox.xMin);
            int yOffset       = (int)(tilesBbox.yMin - projectedBbox.yMin);


            //DrawDebugBmpBbox(tiles, localBbox, tilesBbox, fileName, mimeType);
            int tileSize = tiles.TileSize;

            var pointsOnTexture = gpxPoints
                                  .Select(pt => TileUtils.PositionToGlobalPixel(new LatLong(pt.Latitude, pt.Longitude), zoomLevel, tiles.TileSize))
                                  .Select(pt => new PointF((float)(pt.X - (int)projectedBbox.xMin), (float)(pt.Y - (int)projectedBbox.yMin)));


            using (Image <Rgba32> outputImage = new Image <Rgba32>((int)projectedBbox.Width, (int)projectedBbox.Height))
            {
                foreach (var tile in tiles.Tiles)
                {
                    using (Image <Rgba32> tileImg = Image.Load(tile.Image))
                    {
                        int x = (tile.TileInfo.X - tiles.Start.X) * tileSize + xOffset;
                        int y = (tile.TileInfo.Y - tiles.Start.Y) * tileSize + yOffset;

                        outputImage.Mutate(o => o
                                           .DrawImage(tileImg, new Point(x, y), 1f)
                                           );
                    }
                }

                outputImage.Mutate(o => o
                                   .DrawLines(color == default(Rgba32) ? new Rgba32(1, 0, 0, 1f) : color, lineWidth, pointsOnTexture.ToArray())
                                   );

                if (drawGpxVertices)
                {
                    PathCollection pc = new PathCollection(pointsOnTexture.Select(p => new EllipsePolygon(p, new SizeF(10f, 10f))));
                    outputImage.Mutate(o => o.Draw(GraphicsOptions.Default, Pens.Solid(Rgba32.Violet, 3), pc));
                }

                // with encoder
                //IImageEncoder encoder = ConvertFormat(mimeType);
                //outputImage.Save(fileName, encoder);

                outputImage.Save(fileName);
            }

            return(new TextureInfo(fileName, mimeType, (int)projectedBbox.Width, (int)projectedBbox.Height, zoomLevel,
                                   projectedBbox));
        }
コード例 #48
0
ファイル: VertexFormats.cs プロジェクト: gitter-badger/blimey
 public VertPosTexCol(Vector3 position, Vector2 uv, Rgba32 colour)
 {
     this.Position = position;
     this.UV = uv;
     this.Colour = colour;
 }
コード例 #49
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
 public void AddLine(string renderPass, Vector3 a, Vector3 b, Rgba32 rgba)
 {
     AddLine(renderPass, a, b, rgba, 0f);
 }
コード例 #50
0
 /// <summary>
 /// Get the palette index for the passed color
 /// </summary>
 /// <param name="pixel">The pixel data.</param>
 /// <param name="rgba">The color to map to.</param>
 /// <returns>
 /// The <see cref="int"/>.
 /// </returns>
 public int GetPaletteIndex(TPixel pixel, ref Rgba32 rgba)
 {
     return(this.root.GetPaletteIndex(pixel, 0, ref rgba));
 }
コード例 #51
0
ファイル: SpriteTrait.cs プロジェクト: dreamsxin/engine-1
 //--------------------------------------------------------------------//
 public SpriteTrait()
 {
     Configuration = SpriteConfiguration.Default;
     desiredColour = Rgba32.White;
     desiredScale = 1f;
 }
コード例 #52
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
        public void AddLine(string renderPass, Vector3 a, Vector3 b, Rgba32 rgba, float life)
        {
            // Get a DebugShape we can use to draw the line
            DebugShape shape = GetShapeForLines(renderPass, 1, life);

            // Add the two vertices to the shape
            shape.Vertices[0] = new VertexPositionColour(a, rgba);
            shape.Vertices[1] = new VertexPositionColour(b, rgba);
        }
コード例 #53
0
ファイル: VertexFormats.cs プロジェクト: gitter-badger/blimey
 public VertPosCol(Vector3 position, Rgba32 colour)
 {
     this.Position = position;
     this.Colour = colour;
 }
コード例 #54
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
 public void AddQuad(string renderPass, Vector3 a, Vector3 b, Vector3 c, Vector3 d, Rgba32 rgba)
 {
     AddQuad (renderPass, a, b, c, d, rgba, 0f);
 }
コード例 #55
0
        public void AddLine(String pass, Vector3 a, Vector3 b, Rgba32 zColour)
        {
            if (!passState.ContainsKey (pass))
                passState [pass] = new RenderPassState ();

            // If the array does not hold lines, or it is full
            // or the texture has changed, or the blend mode
            if (passState[pass].currentPrimitiveType != Type.PRIM_LINES
                || passState[pass].nPrimsInBuffer >= VERT_BUFFER_SIZE / (uint)Type.PRIM_LINES
                || passState[pass].currentTexture != null
                || passState[pass].currentBlendMode != BlendMode.Default)
            {
                if (passState[pass].nPrimsInBuffer > 0)
                    _enqueue_batch (pass);

                passState[pass].currentPrimitiveType = Type.PRIM_LINES;
                passState[pass].currentBlendMode = BlendMode.Default;
                passState[pass].currentTexture = null;
            }

            uint i = passState[pass].nPrimsInBuffer * (uint)Type.PRIM_LINES;
            passState[pass].vertBuffer[i].Position = a; passState[pass].vertBuffer[i + 1].Position = b;
            passState[pass].vertBuffer[i].Colour = passState[pass].vertBuffer[i + 1].Colour = zColour;
            passState[pass].vertBuffer[i].UV.X = passState[pass].vertBuffer[i + 1].UV.X =
            passState[pass].vertBuffer[i].UV.Y = passState[pass].vertBuffer[i + 1].UV.Y = 0.0f;

            passState[pass].nPrimsInBuffer++;
        }
コード例 #56
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
 public void AddQuad(string renderPass, Vector3 a, Vector3 b, Vector3 c, Vector3 d, Rgba32 rgba, float life)
 {
     AddLine(renderPass, a, b, rgba, life);
     AddLine(renderPass, b, c, rgba, life);
     AddLine(renderPass, c, d, rgba, life);
     AddLine(renderPass, d, a, rgba, life);
 }
コード例 #57
0
ファイル: Fudge.Tests.cs プロジェクト: gitter-badger/blimey
 public void TestMemberFn_ToString_i()
 {
     var testCase = new Rgba32();
     testCase.PackFrom(0.656f, 0.125f, 0.222f, 0.861f);
     String s = testCase.ToString ();
     Assert.That(s, Is.EqualTo("{R:167 G:32 B:57 A:220}"));
 }
コード例 #58
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
 public void AddTriangle(string renderPass, Vector3 a, Vector3 b, Vector3 c, Rgba32 rgba)
 {
     AddTriangle(renderPass, a, b, c, rgba, 0f);
 }
コード例 #59
0
ファイル: DebugRenderer.cs プロジェクト: dreamsxin/engine-1
        public void AddTriangle(string renderPass, Vector3 a, Vector3 b, Vector3 c, Rgba32 rgba, float life)
        {
            // Get a DebugShape we can use to draw the triangle
            DebugShape shape = GetShapeForLines(renderPass, 3, life);

            // Add the vertices to the shape
            shape.Vertices[0] = new VertexPositionColour(a, rgba);
            shape.Vertices[1] = new VertexPositionColour(b, rgba);
            shape.Vertices[2] = new VertexPositionColour(b, rgba);
            shape.Vertices[3] = new VertexPositionColour(c, rgba);
            shape.Vertices[4] = new VertexPositionColour(c, rgba);
            shape.Vertices[5] = new VertexPositionColour(a, rgba);
        }
コード例 #60
0
        public static void SetLine3(Image <Rgba32> image, int x0, int y0, int x1, int y1, Rgba32 color)
        {
            var steep = System.Math.Abs(x0 - x1) < System.Math.Abs(y0 - y1);

            if (steep)
            {
                var tmp = x0;
                x0 = y0;
                y0 = tmp;

                tmp = x1;
                x1  = y1;
                y1  = tmp;
            }

            if (x0 > x1)
            {
                var tmp = x0;
                x0 = x1;
                x1 = tmp;

                tmp = y0;
                y0  = y1;
                y1  = tmp;
            }

            var dx = x1 - x0;
            var dy = y1 - y0;

            for (int x = x0; x <= x1; x++)
            {
                var t = (x - x0) / (float)(x1 - x0);
                int y = (int)(y0 * (1 - t) + y1 * t);
                if (steep)
                {
                    image[y, x] = color;
                }
                else
                {
                    image[x, y] = color;
                }
            }
        }