Exemple #1
0
        public static void TestColorMath()
        {
            AssertEqualRgb("[1, 0, 0]", ColorMath.RgbToHsv(1, 0, 0));
            AssertEqualRgb("[0, 1, 0]", ColorMath.RgbToHsv(0, 1, 0));
            AssertEqualRgb("[0, 0, 1]", ColorMath.RgbToHsv(0, 0, 1));

            Assert.Equal(0, ColorMath.CalcBrightness(0, 0, 0));
            Assert.Equal(0.9278, ColorMath.CalcBrightness(1, 1, 0)); // Yellow is bright
            Assert.Equal(1, ColorMath.CalcBrightness(1, 1, 1));

            var whiteBrightnes = ColorMath.CalcBrightness(1, 1, 1);
            var blueBrightness = ColorMath.CalcBrightness(0, 0, 1);

            Assert.Equal(1, whiteBrightnes);
            Assert.Equal(0.0722, blueBrightness); // Blue is dark
            // Blue on white has a great contrast (is well readable):
            Assert.True(8 < ColorMath.CalcContrastRatio(whiteBrightnes, blueBrightness));

            var green = ColorMath.RgbToHsv(0, 1, 0);

            Assert.Equal("[0,3333333, 1, 1]", green.ToStringV2(c => "" + c));
            ColorMath.InvertHue(green);         // Green becomes purple
            Assert.Equal("[0,8333333, 1, 1]", green.ToStringV2(c => "" + c));
            AssertEqualRgb("[1, 0, 1]", green); // Purple is red + blue
        }
Exemple #2
0
        /// <summary>
        /// 统计每个色阶的像素数量
        /// </summary>
        /// <param name="enumCh"></param>
        /// <param name="pixelValue"></param>
        protected void CountPixels(string strCH, byte pixelValue)
        {
            int value = ColorMath.FixByte(pixelValue);

            switch (strCH)
            {
            case "RGB":
            {
                _objPixelCount.PixelCountRGB[value]++;
                break;
            }

            case "Blue":
            {
                _objPixelCount.PixelCountBlue[value]++;
                break;
            }

            case "Green":
            {
                _objPixelCount.PixelCountGreen[value]++;
                break;
            }

            case "Red":
            {
                _objPixelCount.PixelCountRed[value]++;
                break;
            }
            }
        }
        private Color GetGridColor(int x, int y)
        {
            if (x < 0)
            {
                return(GetGridColor(0, y));
            }
            if (y < 0)
            {
                return(GetGridColor(x, 0));
            }
            if (x >= tileCountX)
            {
                return(GetGridColor(tileCountX - 1, y));
            }
            if (y >= tileCountY)
            {
                return(GetGridColor(x, tileCountY - 1));
            }

            if (_grid[x, y].Fraction == null)
            {
                return(FlatColors.Background);
            }

            return(ColorMath.Blend(FlatColors.Background, _grid[x, y].Fraction.BackgroundColor, _grid[x, y].PowerCurr));
        }
        protected override void OnProgress(HUDTextBox owner, float progress, SAMTime gameTime, InputState istate)
        {
            var p = FloatMath.AbsSin(progress * (BLINK_COUNT / 2f) * FloatMath.TAU);

            owner.ColorBackground = ColorMath.Blend(baseColor1, highlightColor, p);
            owner.ColorFocused    = ColorMath.Blend(baseColor2, highlightColor, p);
        }
Exemple #5
0
 protected override void OnProgress(OverworldNode_SCCM node, float progress, SAMTime gameTime, InputState istate)
 {
     for (int i = 0; i < _colors.Count; i++)
     {
         node.Blocks[i].Item2 = ColorMath.Blend(_colors[i], Color.White, progress);
     }
 }
        protected override void BeforeProcess()
        {
            _lcArgs = _arg as LevelColorArg;
            if (_isFirstCount)
            {
                _lcArgs.ObjPixelCount.ClearPixelCount();
                CountHistPixel();
                _isFirstCount = false;
            }

            _inputMid  = _lcArgs.InputMiddle;
            _outputMin = _lcArgs.OutputMin;

            int    outputDif = _lcArgs.OutputMax - _outputMin;
            double inputDif  = _lcArgs.InputMax - _lcArgs.InputMin;
            double thanValue = _lcArgs.InputMin / inputDif;

            _rgbs = new byte[256];
            if (_lcArgs.IsChanged)
            {
                for (int i = 0; i < 256; i++)
                {
                    _rgbs[i] = ColorMath.FixByte(outputDif * Math.Pow((i / inputDif - thanValue), _inputMid) + _outputMin);
                }
            }
            else
            {
                for (int i = 0; i < 256; i++)
                {
                    _rgbs[i] = (byte)i;
                }
            }
        }
Exemple #7
0
        public EarthParticle()
        {
            Color(ColorMath.Random(0x444444, 0x777766));
            Angle = Random.Float(-30, 30);

            Lifespan = 0.5f;
        }
        /// <summary>
        /// 统计每个色阶的像素数量
        /// </summary>
        /// <param name="enumCh"></param>
        /// <param name="pixelValue"></param>
        protected void CountPixel(enumChannel enumCh, byte pixelValue)
        {
            int value = ColorMath.FixByte(pixelValue);

            switch (enumCh)
            {
            case enumChannel.RGB:
            {
                _lcArgs.ObjPixelCount.PixelCountRGB[value]++;
                break;
            }

            case enumChannel.B:
            {
                _lcArgs.ObjPixelCount.PixelCountBlue[value]++;
                break;
            }

            case enumChannel.G:
            {
                _lcArgs.ObjPixelCount.PixelCountGreen[value]++;
                break;
            }

            case enumChannel.R:
            {
                _lcArgs.ObjPixelCount.PixelCountRed[value]++;
                break;
            }
            }
        }
Exemple #9
0
        public static Color InvertMixedPerceivedLightnessAndValue(Color color,
                                                                  ColorRange range,
                                                                  params double[] filterParams)
        {
            double mix = 0.5;

            if (filterParams.Any())
            {
                mix = filterParams[0].Clamp(0, 1);
            }

            var brightness       = ColorMath.RgbPerceivedBrightness(color.Red, color.Green, color.Blue);
            var targetBrightness = (1 - brightness);

            // using brightness as lightness is not accurate but we can correct this later
            // how ever it seems that completely correct value produces worse outcome
            // so we may use something in between
            var inverted = Color.FromHsl(color.Hue, color.Saturation, targetBrightness, color.Alpha);

            var rangeFactor = FilterUtils.GetRangeFactor(range, color);
            var hslFiltered = Color.FromHsl(color.Hue, color.Saturation, targetBrightness, color.Alpha);
            var hsvFiltered = Color.FromHsv(color.HueHsv, color.SaturationHsv, targetBrightness, color.Alpha);
            var hsl         = color.InterpolateWith(hslFiltered, rangeFactor).Clone();
            var hsv         = color.InterpolateWith(hsvFiltered, rangeFactor).Clone();

            hsl.InterpolateWith(hsv, mix);
            return(hsl);
        }
Exemple #10
0
        public override void Emit(Emitter emitter, int index, float x, float y)
        {
            var positive = emitter.Recycle <LeafParticle>();

            positive.Color(ColorMath.Random(Dungeon.Level.color1, Dungeon.Level.color2));
            positive.Reset(x, y);
        }
Exemple #11
0
        public override void Emit(Emitter emitter, int index, float x, float y)
        {
            var positive = emitter.Recycle <LeafParticle>();

            positive.Color(ColorMath.Random(0x004400, 0x88CC44));
            positive.Reset(x, y);
        }
Exemple #12
0
        protected void DrawGridProgress(IBatchRenderer sbatch)
        {
            var outerBounds = FRectangle.CreateByCenter(Position, DrawingBoundingBox);
            var innerBounds = FRectangle.CreateByCenter(Position, new FSize(INNERSIZE, INNERSIZE));

            var scoreRectSize = innerBounds.Width / 8f;

            FlatRenderHelper.DrawRoundedBlurPanel(sbatch, outerBounds, clickArea.IsMouseDown() ? FlatColors.ButtonPressedHUD : FlatColors.Asbestos, 0.5f * GDConstants.TILE_WIDTH);
            SimpleRenderHelper.DrawRoundedRectOutline(sbatch, outerBounds.AsInflated(1f, 1f), FlatColors.MidnightBlue, 8, 2f, 0.5f * GDConstants.TILE_WIDTH);

            for (int x = 0; x < 8; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    var col = ColorMath.Blend(FlatColors.Background, GetCellColor(x, y), AlphaOverride);
                    sbatch.FillRectangle(new FRectangle(innerBounds.X + scoreRectSize * x, innerBounds.Y + scoreRectSize * y, scoreRectSize, scoreRectSize), col);
                }
            }

            for (int i = 0; i <= 8; i++)
            {
                sbatch.DrawLine(innerBounds.Left, innerBounds.Top + i * scoreRectSize, innerBounds.Right, innerBounds.Top + i * scoreRectSize, Color.Black * AlphaOverride, Owner.PixelWidth);
                sbatch.DrawLine(innerBounds.Left + i * scoreRectSize, innerBounds.Top, innerBounds.Left + i * scoreRectSize, innerBounds.Bottom, Color.Black * AlphaOverride, Owner.PixelWidth);
            }

            FontRenderHelper.DrawTextCentered(sbatch, Textures.HUDFontBold, 0.9f * GDConstants.TILE_WIDTH, L10N.T(_l10ndescription), FlatColors.TextHUD, Position + new Vector2(0, 2.25f * GDConstants.TILE_WIDTH));
        }
Exemple #13
0
        protected override void Process(ref byte pixelValue)
        {
            int greyValue = pixelValue;

            greyValue  = (int)((transRate[0][greyValue]) * 255);
            pixelValue = ColorMath.FixByte(greyValue);
        }
        protected override void DoUpdate(SAMTime gameTime, InputState istate)
        {
            _server.Update(gameTime, istate);

            _btnStart.BackgroundNormal = _btnStart.BackgroundNormal.WithColor(ColorMath.Blend(FlatColors.Emerald, FlatColors.GreenSea, FloatMath.PercSin(gameTime.TotalElapsedSeconds * 5)));


            if (_server.Mode == SAMNetworkConnection.ServerMode.Error)
            {
                Remove();

                Owner.HUD.ShowToast(null, L10NImplHelper.FormatNetworkErrorMessage(_server.Error, _server.ErrorData), 32, FlatColors.Flamingo, FlatColors.Foreground, 7f);
            }

            if (_server.Mode == SAMNetworkConnection.ServerMode.Stopped)
            {
                Remove();
            }

            if (_server.Mode == SAMNetworkConnection.ServerMode.InLobby && _server.SessionCount == _server.SessionCapacity)
            {
                _btnStart.IsVisible = true;
            }

            if (_server.Mode == SAMNetworkConnection.ServerMode.InGame)
            {
                MainGame.Inst.SetMultiplayerServerLevelScreen(Levels.LEVELS[_server.LevelID], _server.Speed, _server.MusicIndex, _server);
            }
        }
        internal static void Import(Entity entity, string schematic)
        {
            EntityCheck(entity);

            var target = PositionClone()[entity];

            var voxels = FoxCore.SaveDirectory.FetchDirectory("Exports").ImportCube(schematic);

            target.ClipBoardOffset = Vector3D.Zero;
            target.ClipBoard.Clear();

            Helpers.VectorLoop(new Vector3I(0, 0, 0), voxels.Voxels.Size, (x, y, z) => {
                var color = ColorMath.ToString(voxels.Voxels.Read(x, y, z));

                var mapping = voxels.JsonData.Mappings[color];

                if (!GameContext.TileDatabase.AllMaterials().Any(v => string.Equals(mapping.Code, v.Code)))
                {
                    target.ClipBoard.Clear();
                    throw new Exception("The schematic contains an invalid tile");
                }

                var tileConfig = GameContext.TileDatabase.GetTileConfiguration(mapping.Code);

                target.ClipBoard.Add(new Vector3I(x, y, z), tileConfig.MakeTile(tileConfig.BuildRotationVariant(mapping.Rotation)));
            });
        }
Exemple #16
0
        protected override void BeforeProcess()
        {
            _bcArgs = _arg as BrightContrastArg;
            int    bright = _bcArgs.BrightAdjustValue;
            double change = _bcArgs.Brightchangevalue;
            double dstepC = (_bcArgs.ContrastAdjustValue + PARA_1) * PARA_2;

            if (dstepC > 1)
            {
                dstepC = dstepC * dstepC * dstepC;
            }
            double bChange = bright * change * dstepC - PARA_MIDDLE * dstepC + PARA_MIDDLE;

            _rgbs = new byte[256];
            if (_bcArgs.IsChanged)
            {
                for (int i = 0; i < 256; i++)
                {
                    _rgbs[i] = ColorMath.FixByte(i * dstepC + bChange);
                }
            }
            else
            {
                for (int i = 0; i < 256; i++)
                {
                    _rgbs[i] = (byte)i;
                }
            }
        }
Exemple #17
0
        public void RGBtoHSL()
        {
            // Correctly converts RGB to HSL
            Assert.AreEqual(ColorMath.RgbToHsl(Color.FromArgb(255, 0, 0)), new HslColor(0, 255, 128));

            // Does not return True for no reason :)
            Assert.AreNotEqual(ColorMath.RgbToHsl(Color.FromArgb(42, 42, 42)), new HslColor(0, 255, 128));
        }
Exemple #18
0
 private void ProcessValue(ref byte p, int min, int max)
 {
     if (min == max)
     {
         return;
     }
     p = ColorMath.FixByte(255 * Math.Pow(p - min, 2) / Math.Pow(max - min, 2));
 }
Exemple #19
0
 public override void Update()
 {
     base.Update();
     // alpha: 1 -> 0; size: 1 -> 4
     Size(4 - (Am = Left / Lifespan) * 3);
     // color: 0x8844FF -> 0x00FF00
     Color(ColorMath.Interpolate(0x00FF00, 0x8844FF, Am));
 }
Exemple #20
0
        public EarthParticle()
        {
            Lifespan = 0.5f;

            Color(ColorMath.Random(0x555555, 0x777766));

            Acc.Set(0, +40);
        }
Exemple #21
0
            public WaterParticle()
            {
                Acc.Y = 50;
                Am    = 0.5f;

                Color(ColorMath.Random(0xb6ccc2, 0x3b6653));
                Size(2);
            }
Exemple #22
0
 public override void Update()
 {
     base.Update();
     // alpha: 1 -> 0; size: 1 -> 5
     Size(5 - (Am = Left / Lifespan) * 4);
     // color: 0xFF0044 -> 0x220066
     Color(ColorMath.Interpolate(0x220066, 0xFF0044, Am));
 }
        protected override void Process(ref byte pixelBlue, ref byte pixelGreen, ref byte pixelRed)
        {
            double pixelHue = 0, pixelSaturation = 0, pixelLum = 0;
            int    min = Math.Min(pixelRed, Math.Min(pixelGreen, pixelBlue));
            int    max = Math.Max(pixelRed, Math.Max(pixelGreen, pixelBlue));

            pixelLum = (min + max) / 2d / 255;
            ColorMath.HSL2RGB(pixelHue, pixelSaturation, pixelLum, ref pixelRed, ref pixelGreen, ref pixelBlue);
        }
Exemple #24
0
        public static Color InvertValue(Color color, ColorRange colorRange, params double[] filterParams)
        {
            var rangeFactor = FilterUtils.GetRangeFactor(colorRange, color);
            var filtered    = new Color(color);

            filtered.Value = ColorMath.Invert(color.Value);
            color.InterpolateWith(filtered, rangeFactor);
            return(color);
        }
        public ColorPicker()
        {
            InitializeComponent();

            Primary   = ColorMath.ParseString("F5C900");
            Secondary = Microsoft.Xna.Framework.Color.Black;

            BtnRefresh();
        }
        public override void RestoreFromPersistedData(Blob data, EntityUniverseFacade facade)
        {
            if (data.Contains("construct"))
            {
                Construct(data.FetchBlob("construct"), facade);
            }

            if (data.Contains("position"))
            {
                Entity.Physics.ForcedPosition(data.FetchBlob("position").GetVector3D());
            }

            if (data.Contains("destination"))
            {
                _destination = data.FetchBlob("destination").GetVector3D();
            }

            if (data.Contains("rotation"))
            {
                Rotation = (int)data.GetLong("rotation");
            }

            if (data.Contains("botTile"))
            {
                BotTile = data.GetString("botTile");

                BotComponent = GameContext.TileDatabase.GetTileConfiguration(BotTile).Components.Get <BotComponent>();
            }

            if (data.Contains("owner"))
            {
                Owner = data.GetString("owner");
            }

            if (data.Contains("uid"))
            {
                OwnerUid = data.GetString("uid");
            }

            if (data.Contains("colorReplace"))
            {
                var colorReplace = new Dictionary <Color, Color>();

                foreach (var entry in data.FetchBlob("colorReplace").KeyValueIteratable)
                {
                    if (uint.TryParse(entry.Key, out var colKey))
                    {
                        if (uint.TryParse(entry.Value.GetString(), out var colVal))
                        {
                            colorReplace.Add(ColorMath.FromRgba(colKey), ColorMath.FromRgba(colVal));
                        }
                    }
                }

                ColorReplace = colorReplace;
            }
        }
Exemple #27
0
        private void GetState(float time, out FRectangle rect, out Color col, out float rot)
        {
            rect = _rect0;
            foreach (var tf in transformationsBounding)
            {
                if (time < tf.TimeStart)
                {
                    // nothing
                }
                else if (time > tf.TimeEnd)
                {
                    rect = tf.BoundingsFinal;
                }
                else
                {
                    var p = tf.TimeTransform((time - tf.TimeStart) / (tf.TimeEnd - tf.TimeStart));
                    rect = FRectangle.Lerp(tf.BoundingsStart, tf.BoundingsFinal, p);
                }
            }

            col = _col0;
            foreach (var tf in transformationsColor)
            {
                if (time < tf.TimeStart)
                {
                    // nothing
                }
                else if (time > tf.TimeEnd)
                {
                    col = tf.ColorFinal;
                }
                else
                {
                    var p = tf.TimeTransform((time - tf.TimeStart) / (tf.TimeEnd - tf.TimeStart));
                    col = ColorMath.Blend(tf.ColorStart, tf.ColorFinal, p);
                }
            }

            rot = _rot0;
            foreach (var tf in transformationsRotation)
            {
                if (time < tf.TimeStart)
                {
                    // nothing
                }
                else if (time > tf.TimeEnd)
                {
                    rot = tf.RotationFinal;
                }
                else
                {
                    var p = tf.TimeTransform((time - tf.TimeStart) / (tf.TimeEnd - tf.TimeStart));
                    rot = FloatMath.Lerp(tf.RotationStart, tf.RotationFinal, p);
                }
            }
        }
Exemple #28
0
 /// <summary> Converts hsv values to Color32 values (range 0 to 255) </summary>
 /// <param name="hue0To360"> From 0 (red) to 360 (also red, wraps around) </param>
 /// <param name="saturation0To1"> From 0 to 1 </param>
 /// <param name="value0To1"> From 0 to 1 </param>
 /// <param name="alpha0To255"> From 0 to 255 </param>
 public static Color32 HsvToColor32(float hue0To360, float saturation0To1, float value0To1, byte alpha0To255 = 255)
 {
     if (saturation0To1.Equals(0f))
     {
         var normV = (byte)(value0To1 * 255f);
         return(new Color32(normV, normV, normV, alpha0To255));
     }
     float[] rgb = ColorMath.HsvToRgb(hue0To360, saturation0To1, value0To1);
     return(new Color32((byte)(rgb[0] * 255), (byte)(rgb[1] * 255), (byte)(rgb[2] * 255), alpha0To255));
 }
Exemple #29
0
 private Fraction(Color c, Fraction nfrac, FractionType type, float multBullet, float multLaser, FractionDifficulty diff)
 {
     Color               = c;
     Type                = type;
     Difficulty          = diff;
     neutralFraction     = (Type == FractionType.NeutralFraction) ? this : nfrac;
     BulletMultiplicator = multBullet;
     LaserMultiplicator  = multLaser;
     BackgroundColor     = IsNeutral ? Color.Magenta : ColorMath.Blend(FlatColors.Background, c, 0.25f);
 }
        protected override void Process(ref byte pixelBlue, ref byte pixelGreen, ref byte pixelRed)
        {
            float diff       = ColorMath.ColorDistance(pixelRed, pixelGreen, pixelBlue, _red, _green, _blue);
            bool  needAdjust = diff < _colorTorence;

            if (needAdjust)
            {
                ColorAdjust(ref pixelRed, ref pixelGreen, ref pixelBlue, _hue, _saturation, _lightness);
            }
        }