Esempio n. 1
0
        private void chk3D_Checked(object sender, RoutedEventArgs e)
        {
            const double ZKICK = RADIUS / 100;

            try
            {
                if (!_initialized)
                {
                    return;
                }

                Random rand = StaticRandom.GetRandomForThread();

                // When it's going from 2D to 3D, all the Zs will be zero.  So give them a slight push into 3D
                foreach (Dot dot in _dots)
                {
                    if (dot.Position.Z.IsNearZero())
                    {
                        dot.Position = new Point3D(dot.Position.X, dot.Position.Y, dot.Position.Z + rand.NextDouble(-ZKICK, ZKICK));
                        dot.Translate_3DDot.OffsetZ = dot.Position.Z;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 2
0
        private void CreateAsteroids()
        {
            double maxPos = _boundryMax.X * .9d;     // this form will start pushing back at .85, so some of them will be inbound  :)
            double asteroidSize;

            Random rand = StaticRandom.GetRandomForThread();

            // Small
            for (int cntr = 0; cntr < 65; cntr++)
            {
                asteroidSize = .5 + (rand.NextDouble() * 2);
                CreateAsteroidsSprtBuild(asteroidSize, CreateAsteroidsSprtPosition(maxPos));
            }

            // Medium
            for (int cntr = 0; cntr < 20; cntr++)
            {
                asteroidSize = 2 + (rand.NextDouble() * 3);
                CreateAsteroidsSprtBuild(asteroidSize, CreateAsteroidsSprtPosition(maxPos));
            }

            // Large
            for (int cntr = 0; cntr < 3; cntr++)
            {
                asteroidSize = 4.5 + (rand.NextDouble() * 5);
                CreateAsteroidsSprtBuild(asteroidSize, CreateAsteroidsSprtPosition(maxPos));
            }
        }
Esempio n. 3
0
            //TODO: Take in the points/sizes/colorindex instead of deriving them here
            public StarfieldVisual2(double size, double margin, int numStars, double starSizeMult, Tuple <Vector[], int> vectorField = null, Color?color = null)
            {
                this.Size = size;

                Brush[] brushes_Small;
                Brush[] brushes_Large;
                if (color == null)
                {
                    brushes_Small = _starBrushes_Small.Value;
                    brushes_Large = _starBrushes_Large.Value;
                }
                else
                {
                    brushes_Small = new[] { new SolidColorBrush(color.Value) };
                    brushes_Large = new[] { new SolidColorBrush(color.Value) };
                }

                Random rand = StaticRandom.GetRandomForThread();

                Point[] points = GetPoints(rand, size, margin, numStars, vectorField);

                _visual = new DrawingVisual();
                using (DrawingContext dc = _visual.RenderOpen())
                {
                    for (int cntr = 0; cntr < numStars; cntr++)
                    {
                        Brush  brush = null;
                        double radius;
                        double sizeRand = rand.NextDouble();
                        if (sizeRand > .995)
                        {
                            // Really Big
                            brush  = brushes_Large[rand.Next(brushes_Large.Length)];
                            radius = rand.NextDouble(2, 6);
                        }
                        else if (sizeRand > .9)
                        {
                            // Big
                            radius = rand.NextDouble(.9, 1.2);
                        }
                        else
                        {
                            // Small
                            radius = rand.NextDouble(.7, .9);
                        }

                        radius *= starSizeMult;

                        if (brush == null)
                        {
                            brush = brushes_Small[rand.Next(brushes_Small.Length)];
                        }

                        dc.DrawEllipse(brush, null, points[cntr], radius, radius);
                    }
                }

                //_visual.BitmapEffect
                //_visual.CacheMode
            }
Esempio n. 4
0
            private static FlagColorCategory GetRandomFlagColors_Category(FlagColorCategory[] chooseFrom, Tuple <ColorHSV, FlagColorCategory>[] existing)
            {
                if (chooseFrom.Length == 1)
                {
                    return(chooseFrom[0]);
                }

                Random rand = StaticRandom.GetRandomForThread();
                int    infiniteLoopDetector = 0;

                // There are more than one to choose from.  Pick one that hasn't been picked before
                // For example { Black, White }, and White is used.  Need to return Black
                int index = -1;

                while (true)
                {
                    index = rand.Next(chooseFrom.Length);

                    if (!existing.Any(o => o.Item2 == chooseFrom[index]))
                    {
                        return(chooseFrom[index]);
                    }

                    infiniteLoopDetector++;
                    if (infiniteLoopDetector > 1000)
                    {
                        throw new ApplicationException("Infinite loop detected");
                    }
                }
            }
Esempio n. 5
0
        /// <summary>
        /// This returns a random ball, with some optional fixed values
        /// </summary>
        public static WeaponSpikeBallDNA GetRandomDNA(WeaponSpikeBallMaterial?material = null, double?radius = null)
        {
            WeaponSpikeBallDNA retVal = new WeaponSpikeBallDNA();

            Random rand = StaticRandom.GetRandomForThread();

            // Radius
            if (radius != null)
            {
                retVal.Radius = radius.Value;
            }
            else
            {
                retVal.Radius = rand.NextDouble(.2, .5);
            }

            // Material
            if (material == null)
            {
                retVal.Material = UtilityCore.GetRandomEnum <WeaponSpikeBallMaterial>();
            }
            else
            {
                retVal.Material = material.Value;
            }

            return(retVal);
        }
Esempio n. 6
0
            public ColorHSV GetRandomColor(FlagColorCategory category, double?hue = null)
            {
                Random rand = StaticRandom.GetRandomForThread();

                double hueActual = hue ?? rand.NextDouble(360);

                ColorHSV retVal;

                if (category == FlagColorCategory.Other)
                {
                    // This category is under other category rectangles, so do a brute force repeat until match
                    FlagColorCategory cat;
                    do
                    {
                        retVal = new ColorHSV(hueActual, rand.NextDouble(100), rand.NextDouble(100));
                        cat    = Categorize(retVal);
                    } while (cat != category);
                }
                else
                {
                    // The color range is stored as a rectangle (X is saturation, Y is value)
                    Rect catRect = this.Categories.First(o => o.Item2 == category).Item1;
                    retVal = new ColorHSV(hueActual, rand.NextDouble(catRect.Left, catRect.Right), rand.NextDouble(catRect.Top, catRect.Bottom));
                }

                return(retVal);
            }
Esempio n. 7
0
        private void DrawPower()
        {
            double power;

            if (!double.TryParse(txtPow.Text, out power))
            {
                txtPow.Effect = _errorEffect;
                return;
            }

            txtPow.Effect = null;

            Random rand = StaticRandom.GetRandomForThread();

            IEnumerable <double> samples = Enumerable.Range(0, 200000).
                                           Select(o => rand.NextPow(power));

            IEnumerable <Point> idealLine = Enumerable.Range(0, 100).
                                            Select(o =>
            {
                double x = o / 100d;
                return(new Point(x, Math.Pow(x, power)));
            });

            DrawGraph(samples, idealLine);
        }
Esempio n. 8
0
        private static void LoadInventory(ListBox listbox, Inventory inventory, List <AnimateRotation> animations, double maxWeaponRadius)
        {
            // Clear existing
            listbox.Items.Clear();

            Random rand = StaticRandom.GetRandomForThread();

            if (inventory.Weapons.Count > 0)
            {
                #region Weapons


                foreach (Weapon weapon in inventory.Weapons)
                {
                    //NOTE: No need for a border, the ListBoxItem has been restyled to be a border

                    InventoryItem item = new InventoryItem();
                    item.SetItem(weapon, weapon.Radius / maxWeaponRadius);

                    listbox.Items.Add(item);

                    item.RotateTransform.Quaternion = new Quaternion(new Vector3D(1, 0, 0), StaticRandom.NextDouble(360d));
                    animations.Add(AnimateRotation.Create_Constant(item.RotateTransform, rand.NextDouble(4d, 7d)));
                }

                #endregion
            }
        }
Esempio n. 9
0
        private void MoveAllInitial(DateTime eventTime)
        {
            Random rand = StaticRandom.GetRandomForThread();

            foreach (Snapshot <T> item in _initialBuffer)
            {
                var rightPercent = GetPercent(item.Time, eventTime, _dontStoreTime, _tentativeTime, _dontStore_Seconds, _graySpan_Seconds);
                if (!rightPercent.Item1)
                {
                    // This is too close to the event, and shouldn't be stored
                    continue;
                }

                Snapshot <T> finalItem = ExaminePercents(item, rightPercent.Item2);

                if (finalItem.Percent == null)
                {
                    TransferToLongterm(finalItem, rand);
                }
                else
                {
                    TransferToTentative(finalItem);
                }
            }

            _initialBuffer.Clear();
        }
Esempio n. 10
0
        public T[] GetSamples(int count)
        {
            lock (_lock)
            {
                //TODO: May want to consider when count > one of these lists.  But probably not

                // This is used when the front of the list should be favored
                Random rand     = StaticRandom.GetRandomForThread();
                var    randFunc = new Func <int, int, int>((min, max) => min + UtilityCore.GetIndexIntoList(rand.NextPow(2), max - min));

                if (_longTermIndex < 0 && _tentativeBuffer.Count == 0)
                {
                    // Empty
                    return(new T[0]);
                }
                else if (_longTermIndex >= _abandonTentativeSize)
                {
                    #region all from longterm

                    return(UtilityCore.RandomRange(0, _longTermIndex + 1, count).       // the randrange function takes care of reducing count if greater than range
                           Select(o => _longTermBuffer[o].Item).
                           ToArray());

                    #endregion
                }
                else if (_longTermIndex < 0)
                {
                    #region all from tentative

                    // Don't pull uniform randomly from tentative.  Favor items at the front of the list
                    return(UtilityCore.RandomRange(0, _tentativeBuffer.Count, count, randFunc).
                           Select(o => _tentativeBuffer[o].Item).
                           ToArray());

                    #endregion
                }
                else
                {
                    #region mixture

                    // Pull from long term then tentative
                    return(UtilityCore.RandomRange(0, _longTermIndex + 1 + _tentativeBuffer.Count, count, randFunc).
                           Select(o =>
                    {
                        if (o <= _longTermIndex)
                        {
                            return _longTermBuffer[o].Item;
                        }
                        else
                        {
                            return _tentativeBuffer[o - (_longTermIndex + 1)].Item;
                        }
                    }).
                           ToArray());

                    #endregion
                }
            }
        }
Esempio n. 11
0
        //TODO: random chance of randomly placing metal fittings on the handle
        private static void GetModel_Rod_Wood(Model3DGroup geometries, WeaponHandleDNA dna, WeaponHandleDNA finalDNA, WeaponMaterialCache materials)
        {
            const double PERCENT = 1;

            Random rand = StaticRandom.GetRandomForThread();
            var    from = dna.KeyValues;
            var    to   = finalDNA.KeyValues;

            GeometryModel3D geometry = new GeometryModel3D();

            #region material

            switch (dna.HandleMaterial)
            {
            case WeaponHandleMaterial.Soft_Wood:
                geometry.Material = materials.Handle_SoftWood;
                break;

            case WeaponHandleMaterial.Hard_Wood:
                geometry.Material = materials.Handle_HardWood;
                break;

            default:
                throw new ApplicationException("Unexpected WeaponHandleMaterial: " + dna.HandleMaterial.ToString());
            }

            geometry.BackMaterial = geometry.Material;

            #endregion

            #region tube

            double maxX1 = WeaponDNA.GetKeyValue("maxX1", from, to, rand.NextDouble(.45, .7));
            double maxX2 = WeaponDNA.GetKeyValue("maxX2", from, to, rand.NextDouble(.45, .7));

            double maxY1 = WeaponDNA.GetKeyValue("maxY1", from, to, rand.NextDouble(.85, 1.05));
            double maxY2 = WeaponDNA.GetKeyValue("maxY2", from, to, rand.NextDouble(.85, 1.05));

            List <TubeRingBase> rings = new List <TubeRingBase>();
            rings.Add(new TubeRingRegularPolygon(0, false, maxX1 * .45, maxY1 * .75, true));
            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring1", from, to, rand.NextPercent(.5, PERCENT)), false, maxX1 * .5, maxY1 * 1, false));
            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring2", from, to, rand.NextPercent(2, PERCENT)), false, maxX1 * .4, maxY1 * .8, false));

            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring3", from, to, rand.NextPercent(5, PERCENT)), false, Math1D.Avg(maxX1, maxX2) * .35, Math1D.Avg(maxY1, maxY2) * .75, false));

            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring4", from, to, rand.NextPercent(5, PERCENT)), false, maxX2 * .4, maxY2 * .8, false));
            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring5", from, to, rand.NextPercent(2, PERCENT)), false, maxX2 * .5, maxY2 * 1, false));
            rings.Add(new TubeRingRegularPolygon(WeaponDNA.GetKeyValue("ring6", from, to, rand.NextPercent(.5, PERCENT)), false, maxX2 * .45, maxY2 * .75, true));

            rings = TubeRingBase.FitNewSize(rings, dna.Radius * Math.Max(maxX1, maxX2), dna.Radius * Math.Max(maxY1, maxY2), dna.Length);                        // multiplying x by maxX, because the rings were defined with x maxing at maxX, and y maxing at 1

            geometry.Geometry = UtilityWPF.GetMultiRingedTube(10, rings, true, true, new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 90))); // the tube builds along z, but this class wants along x

            #endregion

            geometries.Children.Add(geometry);
        }
Esempio n. 12
0
        private static SOMRules GetSOMRules_Rand()
        {
            Random rand = StaticRandom.GetRandomForThread();

            return(new SOMRules(
                       rand.Next(15, 50),
                       rand.Next(2000, 5000),
                       rand.NextDouble(.2, .4),
                       rand.NextDouble(.05, .15)));
        }
Esempio n. 13
0
        private static Vector3D GetRandomScale(double baseScale, double percent = .5)
        {
            Random rand = StaticRandom.GetRandomForThread();

            //NOTE: The parts that need the same values for X,Y,Z will take averages, so it's ok to be lazy here (they are designed to take imperfect mutated inputs)
            return(new Vector3D(
                       rand.NextPercent(baseScale, percent),
                       rand.NextPercent(baseScale, percent),
                       rand.NextPercent(baseScale, percent)
                       ));
        }
Esempio n. 14
0
        /// <summary>
        /// Get a random vector between boundry lower and boundry upper
        /// </summary>
        public static MyVector GetRandomVector(MyVector boundryLower, MyVector boundryUpper)
        {
            MyVector retVal = new MyVector();

            Random rand = StaticRandom.GetRandomForThread();

            retVal.X = boundryLower.X + (rand.NextDouble() * (boundryUpper.X - boundryLower.X));
            retVal.Y = boundryLower.Y + (rand.NextDouble() * (boundryUpper.Y - boundryLower.Y));
            retVal.Z = boundryLower.Z + (rand.NextDouble() * (boundryUpper.Z - boundryLower.Z));

            return(retVal);
        }
Esempio n. 15
0
        public void Activate()
        {
            // Don't even look at the input.  Just fill the output with random values

            Random rand = StaticRandom.GetRandomForThread();

            for (int cntr = 0; cntr < OutputSignalArray.Length; cntr++)
            {
                OutputSignalArray[cntr] = _isPositiveOnly ?
                                          rand.NextDouble(1) :
                                          rand.NextDouble(-1, 1);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Gets a value between -maxValue and maxValue
        /// </summary>
        public static double GetNearZeroValue(double maxValue)
        {
            Random rand = StaticRandom.GetRandomForThread();

            double retVal = rand.NextDouble() * maxValue;

            if (rand.Next(0, 2) == 1)
            {
                retVal *= -1;
            }

            return(retVal);
        }
Esempio n. 17
0
        /// <summary>
        /// Creates or adds to a set of colors to be used by klinth weapons
        /// </summary>
        /// <param name="existing">This is a material definition that may already exist, or partially filled out</param>
        /// <param name="basedOn">This is a way to force the return hue (a spike ball's colors could be based on the handle's colors)</param>
        public static MaterialDefinition[] GetRandomMaterials_Klinth(MaterialDefinition[] existing = null, ColorHSV?basedOn = null)
        {
            List <MaterialDefinition> retVal = new List <MaterialDefinition>();

            Random rand = StaticRandom.GetRandomForThread();

            if (existing != null)
            {
                retVal.AddRange(existing);
            }

            // Main color (in the case of a handle, the only color)
            if (retVal.Count < 1)
            {
                double hue;
                if (basedOn == null)
                {
                    hue = StaticRandom.NextDouble(0, 360);
                }
                else
                {
                    //hue = GetRandomHue(basedOn.Value.H);
                    hue = basedOn.Value.H;      // klinth shouldn't allow an opposite hue (it looks really bad)
                }

                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor  = UtilityWPF.HSVtoRGB(hue, StaticRandom.NextDouble(50, 80), StaticRandom.NextDouble(40, 90)).ToHex(),
                    SpecularColor = UtilityWPF.HSVtoRGB(StaticRandom.NextDouble(0, 360), StaticRandom.NextDouble(50, 80), StaticRandom.NextDouble(40, 90)).ToHex(),
                    EmissiveColor = UtilityWPF.GetRandomColor(0, 255).ToHex()
                });
            }

            // Secondary color (in the case of ball and spikes, this is the spikes)
            if (retVal.Count < 2)
            {
                ColorHSV firstDiff = UtilityWPF.ColorFromHex(retVal[0].DiffuseColor).ToHSV();
                ColorHSV firstSpec = UtilityWPF.ColorFromHex(retVal[0].SpecularColor).ToHSV();
                ColorHSV firstEmis = UtilityWPF.ColorFromHex(retVal[0].EmissiveColor).ToHSV();

                // Needs to be roughly the same color as the ball, just a bit darker
                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor  = UtilityWPF.HSVtoRGB(firstDiff.H, firstDiff.S * 1.25, firstDiff.V * .66d).ToHex(),
                    SpecularColor = UtilityWPF.HSVtoRGB(firstSpec.H, firstSpec.S * 1.1, firstSpec.V).ToHex(),
                    EmissiveColor = UtilityWPF.HSVtoRGB(firstEmis.H, firstEmis.S, firstEmis.V).ToHex(),
                });
            }

            return(retVal.ToArray());
        }
Esempio n. 18
0
        /// <summary>
        /// Creates or adds to a set of colors to be used by composite weapons
        /// </summary>
        /// <param name="existing">This is a material definition that may already exist, or partially filled out</param>
        /// <param name="basedOn">This is a way to force the return hue (a spike ball's colors could be based on the handle's colors)</param>
        public static MaterialDefinition[] GetRandomMaterials_Composite(MaterialDefinition[] existing = null, ColorHSV?basedOn = null)
        {
            List <MaterialDefinition> retVal = new List <MaterialDefinition>();

            Random rand = StaticRandom.GetRandomForThread();

            if (existing != null)
            {
                retVal.AddRange(existing);
            }

            if (retVal.Count < 1)
            {
                if (basedOn == null)
                {
                    // For the first one, just pick any random color
                    retVal.Add(new MaterialDefinition()
                    {
                        DiffuseColor = UtilityWPF.GetRandomColor(0, 255).ToHex()
                    });
                }
                else
                {
                    // Make this based on the hue of the color passed in
                    retVal.Add(new MaterialDefinition()
                    {
                        DiffuseColor = UtilityWPF.HSVtoRGB(GetRandomHue(basedOn.Value.H), rand.NextDouble(100), rand.NextDouble(100)).ToHex()
                    });
                }
            }

            ColorHSV first = UtilityWPF.ColorFromHex(retVal[0].DiffuseColor).ToHSV();

            if (retVal.Count < 2)
            {
                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor = UtilityWPF.HSVtoRGB(GetRandomHue(first.H), rand.NextDouble(100), rand.NextDouble(100)).ToHex()
                });
            }

            if (retVal.Count < 3)
            {
                retVal.Add(new MaterialDefinition()
                {
                    DiffuseColor = UtilityWPF.HSVtoRGB(GetRandomHue(first.H), rand.NextDouble(100), rand.NextDouble(100)).ToHex()
                });
            }

            return(retVal.ToArray());
        }
Esempio n. 19
0
        private static Convolution2D GetRandomFilter_Positive(bool isSquare)
        {
            Random rand = StaticRandom.GetRandomForThread();

            var size = GetFilterSize(rand, isSquare);

            double[] values = Enumerable.Range(0, size.Item1 * size.Item2).
                              Select(o => rand.NextDouble()).
                              ToArray();

            values = Convolutions.ToUnit(values);

            return(new Convolution2D(values, size.Item1, size.Item2, false));
        }
Esempio n. 20
0
        private void RandomizePrices()
        {
            Random rand = StaticRandom.GetRandomForThread();

            RandomBellArgs bell = new RandomBellArgs(1, -45, 1, -45);

            _partPriceAdjustments = BotConstructor.AllPartTypes.Value.
                                    Select(o => Tuple.Create(o, RandomizePrices_Percent(rand, bell))).
                                    ToArray();

            _mineralPriceAdjustments = UtilityCore.GetEnums <MineralType>().
                                       Select(o => Tuple.Create(o, RandomizePrices_Percent(rand, bell))).
                                       ToArray();
        }
Esempio n. 21
0
        /// <summary>
        /// This returns a random axe, with some optional fixed values
        /// </summary>
        public static WeaponAxeDNA GetRandomDNA(double?sizeSingleSide = null, WeaponAxeType?axeType = null, WeaponAxeSides?sides = null, WeaponAxeStye?style = null)
        {
            WeaponAxeDNA retVal = new WeaponAxeDNA();

            Random rand = StaticRandom.GetRandomForThread();

            // Size
            if (sizeSingleSide != null)
            {
                retVal.SizeSingle = sizeSingleSide.Value;
            }
            else
            {
                retVal.SizeSingle = rand.NextDouble(.4, 1);
            }

            // AxeType
            if (axeType != null)
            {
                retVal.AxeType = axeType.Value;
            }
            else
            {
                retVal.AxeType = UtilityCore.GetRandomEnum <WeaponAxeType>();
            }

            // Sides
            if (sides != null)
            {
                retVal.Sides = sides.Value;
            }
            else
            {
                retVal.Sides = UtilityCore.GetRandomEnum <WeaponAxeSides>();
            }

            // Style
            if (style != null)
            {
                retVal.Style = style.Value;
            }
            else
            {
                retVal.Style = UtilityCore.GetRandomEnum <WeaponAxeStye>();
            }

            return(retVal);
        }
Esempio n. 22
0
        public double GetDamage_Collision(IMapObject collidedWith, Point3D positionModel, Vector3D velocityModel, double mass1, double mass2)
        {
            const double MAXMASSRATIO = 3;

            TakesDamageWorker_Props props = GetTypeModifier(collidedWith);

            double speed = velocityModel.Length;

            // If the impact velocity is low enough, there won't be damage
            if (speed < props.VelocityThreshold)
            {
                return(0);
            }

            // Restrict mass
            // If the difference in mass is large enough, then the larger could just be considered as a stationary object.  Including more of the larger's
            // mass would make it appear like there is more energy than there actually is (a probe hitting a large asteroid or a planet will feel the
            // same impulse, even though the masses are very different)
            UtilityCore.MinMax(ref mass1, ref mass2);
            if (mass2 > mass1 * MAXMASSRATIO)
            {
                mass2 = mass1 * MAXMASSRATIO;
            }

            // Next check is the collision energy
            // Energy = m/2 * v^2
            double energy = ((mass1 + mass2) / 2d) * speed * speed;

            //May or may not want this check
            // If one of the masses is significantly small relative to the other, then velocity will need to be very large for damage to occur

            // Next is the min energy threshold
            if (energy < props.EnergyTheshold)
            {
                return(0);
            }

            // Final step should just be to convert energy into hitpoint loss
            // HitPointLoss = Energy * c
            double retVal = energy * props.EnergyToHitpointMult;

            // Finally, run it through a randomization
            retVal *= StaticRandom.GetRandomForThread().NextBellPercent(ItemOptions.DAMAGE_RANDOMBELL, props.RandomPercent);

            //LogHit(mass1, mass2, speed, energy);

            return(retVal);
        }
Esempio n. 23
0
            public StarfieldVisual1(double size, double margin, int numLayers, double starSizeMult, Color?color = null)
            {
                const double DENSITY = .002;

                int numStars = Convert.ToInt32((DENSITY / numLayers) * size * size);

                Brush[] brushes;
                if (color == null)
                {
                    brushes = _starBrushes.Value;
                }
                else
                {
                    brushes = new[] { new SolidColorBrush(color.Value) };
                }

                Random rand          = StaticRandom.GetRandomForThread();
                double sizeMinMargin = size - margin;

                _visual = new DrawingVisual();
                using (DrawingContext dc = _visual.RenderOpen())
                {
                    for (int cntr = 0; cntr < numStars; cntr++)
                    {
                        //NOTE: Can't go all the way to the edge, stars would get cut off (the caller has to know the margin so it can properly overlap the images)
                        Point  point = new Point(rand.NextDouble(margin, sizeMinMargin), rand.NextDouble(margin, sizeMinMargin));
                        double radius;
                        if (rand.NextDouble() > .9)
                        {
                            // Big
                            radius = rand.NextDouble(.9, 1.2);
                        }
                        else
                        {
                            // Small
                            radius = rand.NextDouble(.7, .9);
                        }

                        radius *= starSizeMult;

                        Brush brush = brushes[rand.Next(brushes.Length)];

                        //TODO: Blur these a bit
                        dc.DrawEllipse(brush, null, point, radius, radius);
                    }
                }
            }
Esempio n. 24
0
        private static Tuple <int, int, double>[] BuildLinksRandomSprtLinks(int fromCount, int toCount, int count, bool isSameList)
        {
            SortedList <Tuple <int, int>, double> retVal = new SortedList <Tuple <int, int>, double>();

            Random rand = StaticRandom.GetRandomForThread();

            int    fromIndex, toIndex;
            double weight;

            // Come up with links
            for (int cntr = 0; cntr < count; cntr++)
            {
                fromIndex = rand.Next(fromCount);

                if (isSameList)
                {
                    toIndex = rand.Next(toCount - 1);           // a neuron can't point to itself, so pick from one less than the size of the list
                    if (toIndex >= fromIndex)
                    {
                        toIndex++;
                    }
                }
                else
                {
                    toIndex = rand.Next(toCount);
                }

                weight = Math1D.GetNearZeroValue(MAXWEIGHT);

                Tuple <int, int> key = new Tuple <int, int>(fromIndex, toIndex);

                // Add to the return (don't allow dupes)
                if (retVal.ContainsKey(key))
                {
                    retVal[key] += weight;
                }
                else
                {
                    retVal.Add(key, weight);
                }
            }

            // Exit Function
            return(retVal.Keys.Select(o => new Tuple <int, int, double>(o.Item1, o.Item2, retVal[o])).ToArray());
        }
Esempio n. 25
0
        public static Tuple <FlagBackType, FlagOverlayType?, FlagOverlayType?> GetRandomEnums()
        {
            Random rand = StaticRandom.GetRandomForThread();

            double overlayProb = rand.NextDouble();

            // Choose a background
            FlagBackType backType = UtilityCore.GetRandomEnum <FlagBackType>();

            FlagOverlayType[] backTypeFilter = _similarOptions.Value.
                                               Where(o => o.Item2.Any(p => p == backType)).
                                               SelectMany(o => o.Item1).
                                               ToArray();

            // Choose overlay one
            FlagOverlayType?overlayType1 = null;

            if (overlayProb > .33)
            {
                overlayType1 = UtilityCore.GetRandomEnum <FlagOverlayType>(backTypeFilter);
            }

            // Choose overlay two
            FlagOverlayType?overlayType2 = null;

            if (overlayProb > .66)
            {
                var test = _notAbove.Value.
                           Where(o => o.Item2.Any(p => p == overlayType1.Value)).
                           SelectMany(o => o.Item1).
                           ToArray();


                IEnumerable <FlagOverlayType> filter2 = UtilityCore.Iterate(
                    new[] { overlayType1.Value },
                    backTypeFilter,
                    _similarOptions.Value.Where(o => o.Item1.Any(p => p == overlayType1.Value)).SelectMany(o => o.Item1),
                    _notAbove.Value.Where(o => o.Item2.Any(p => p == overlayType1.Value)).SelectMany(o => o.Item1)
                    );

                overlayType2 = UtilityCore.GetRandomEnum <FlagOverlayType>(filter2);
            }

            return(Tuple.Create(backType, overlayType1, overlayType2));
        }
Esempio n. 26
0
            private static double GetRandomFlagColors_Hue(double[] existing)
            {
                Random rand = StaticRandom.GetRandomForThread();

                double retVal = 0;

                while (true)
                {
                    retVal = rand.NextDouble(360);

                    if (!existing.Any(o => UtilityWPF.GetHueDistance(o, retVal) < 60))
                    {
                        break;
                    }
                }

                return(retVal);
            }
Esempio n. 27
0
        /// <summary>
        /// This is exposed so it can be called externally on a separate thread, then call this asteroid's constructor
        /// in the main thread once this returns
        /// </summary>
        public static ITriangleIndexed[] GetHullTriangles(double radius)
        {
            const int NUMPOINTS = 60;           // too many, and it looks too perfect

            Exception lastException = null;
            Random    rand          = StaticRandom.GetRandomForThread();

            for (int infiniteLoopCntr = 0; infiniteLoopCntr < 50; infiniteLoopCntr++)           // there is a slight chance that the convex hull generator will choke on the inputs.  If so just retry
            {
                try
                {
                    double minRadius = radius * .9d;

                    Point3D[] points = new Point3D[NUMPOINTS];

                    // Make a point cloud
                    for (int cntr = 0; cntr < NUMPOINTS; cntr++)
                    {
                        points[cntr] = Math3D.GetRandomVector_Spherical(minRadius, radius).ToPoint();
                    }

                    // Squash it
                    Transform3DGroup transform = new Transform3DGroup();
                    transform.Children.Add(new ScaleTransform3D(.33d + (rand.NextDouble() * .66d), .33d + (rand.NextDouble() * .66d), 1d)); // squash it
                    transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));                    // giving it a random rotation, since it's always squashed along the same axiis
                    transform.Transform(points);

                    // Get a hull that wraps those points
                    ITriangleIndexed[] retVal = Math3D.GetConvexHull(points.ToArray());

                    // Get rid of unused points
                    retVal = TriangleIndexed.Clone_CondensePoints(retVal);

                    // Exit Function
                    return(retVal);
                }
                catch (Exception ex)
                {
                    lastException = ex;
                }
            }

            throw new ApplicationException(lastException.ToString());
        }
Esempio n. 28
0
        private void DrawBell3()
        {
            Point[] points = GetBellPoints(txtBell3.Text);
            if (points == null)
            {
                txtBell3.Effect = _errorEffect;
                return;
            }

            txtBell3.Effect = null;

            BezierSegment3D bezier = new BezierSegment3D(0, 1, points.Select(o => o.ToPoint3D()).ToArray(), new[] { new Point3D(0, 0, 0), new Point3D(1, 1, 0) });

            Random rand = StaticRandom.GetRandomForThread();

            IEnumerable <double> samples = Enumerable.Range(0, 100000).
                                           Select(o => BezierUtil.GetPoint(rand.NextDouble(), bezier).Y);

            IEnumerable <Point> idealLine = BezierUtil.GetPoints(100, bezier).
                                            Select(o => o.ToPoint2D());

            DrawGraph(samples, idealLine);

            Rect bounds = GetBounds();

            for (int cntr = 0; cntr < bezier.ControlPoints.Length - 1; cntr++)
            {
                Point from = GetScaledPoint(bezier.ControlPoints[cntr], bounds);
                Point to   = GetScaledPoint(bezier.ControlPoints[cntr + 1], bounds);
                AddLine(from, to, _brushLightBlue);
            }

            if (bezier.ControlPoints.Length > 0)
            {
                Point from = GetScaledPoint(bezier.EndPoint0, bounds);
                Point to   = GetScaledPoint(bezier.ControlPoints[0], bounds);
                AddLine(from, to, _brushLightBlue);

                from = GetScaledPoint(bezier.EndPoint1, bounds);
                to   = GetScaledPoint(bezier.ControlPoints[bezier.ControlPoints.Length - 1], bounds);
                AddLine(from, to, _brushLightBlue);
            }
        }
Esempio n. 29
0
        private static Convolution2D GetRandomFilter_PosNeg(bool isSquare)
        {
            Random rand = StaticRandom.GetRandomForThread();

            var size = GetFilterSize(rand, isSquare);

            double[] values = Enumerable.Range(0, size.Item1 * size.Item2).
                              Select(o => rand.NextDouble(-1, 1)).
                              ToArray();

            if (values.All(o => o > 0) || values.All(o => o < 0))
            {
                // They are all positive or all negative.  Flip one of them
                values[rand.Next(values.Length)] *= -1d;
            }

            values = Convolutions.ToUnit(values);

            return(new Convolution2D(values, size.Item1, size.Item2, true));
        }
Esempio n. 30
0
        /// <summary>
        /// This method removes how many it's told, or figures out how many to remove
        /// </summary>
        private static void RemoveRandomItems <T>(IList <T> list, int?removeCount = null)
        {
            if (list.Count == 0)
            {
                return;
            }

            Random rand = StaticRandom.GetRandomForThread();

            if (removeCount == null)
            {
                double percent = rand.NextDouble(.33, 1);

                removeCount = Convert.ToInt32(list.Count * percent);
            }

            for (int cntr = 0; cntr < removeCount.Value; cntr++)
            {
                list.RemoveAt(rand.Next(list.Count));
            }
        }