public override void Draw(IParticle _particle)
        {
            var rect = new Rectangle(particlePoint(_particle).X - 2, particlePoint(_particle).Y - 2, 4, 4);
            tempGraph.FillEllipse(new SolidBrush(Color.GreenYellow), rect);
            tempGraph.DrawLine(new Pen(Color.Green, 2), particlePoint(_particle), particleSpeed(_particle));

        }
        public void OnActivate(IObjAiBase unit, IBuff buff, ISpell ownerSpell)
        {
            if (unit is IChampion c)
            {
                // TODO: Implement Animation Overrides for spells like these
                if (c.Skin == 0)
                {
                    pmodelname = "Aatrox_Base_RModel.troy";
                }
                else if (c.Skin == 1)
                {
                    pmodelname = "Aatrox_Skin01_RModel.troy";
                }
                else if (c.Skin == 2)
                {
                    pmodelname = "Aatrox_Skin02_RModel.troy";
                }
                pmodel = AddParticleTarget(c, pmodelname, c);
                pmodel.SetToRemove();

                StatsModifier.AttackSpeed.PercentBonus = (0.4f + (0.1f * (ownerSpell.Level - 1))) * buff.StackCount; // StackCount included here as an example
                StatsModifier.Range.FlatBonus          = 175f * buff.StackCount;

                unit.AddStatModifier(StatsModifier);
            }
        }
示例#3
0
        public void UpdateForce(IParticle particle, double duration)
        {
            if (particle.IsInfiniteMass == true)
            {
                return;
            }

            // Calculate relative position of the particle from the anchor
            Vector3 positionFromAnchor = particle.Position - Anchor;

            // Calculate the value for Gamma
            var gamma = 0.5 * Math.Sqrt((4 * SpringConstant) - (Damping * Damping));

            if (gamma == 0.0)
            {
                return;
            }

            // Calculate the value for the C constant
            var c = (positionFromAnchor * (Damping / (2.0 * gamma))) + (particle.Velocity * (1.0 / gamma));

            // Calculate the target position (in two parts)
            var tagetPosition = (positionFromAnchor * Math.Cos(gamma * duration)) + (c * Math.Sin(gamma * duration));

            tagetPosition *= Math.Exp(0.5 * duration * Damping);

            // Calculate the acceleration needed (and hence the force)
            var acceleration = ((tagetPosition - positionFromAnchor) * (1.0 / (duration * duration))) -
                               (particle.Velocity * duration);

            // Add the force to the particle
            particle.AddForce(acceleration * particle.Mass);
        }
示例#4
0
 public static void RecycleParticle(IParticle particle)
 {
     if (_particles.ContainsKey(particle.GetParticleType()))
     {
         _particles[particle.GetParticleType()].Enqueue(particle);
     }
 }
示例#5
0
        public void UpdateSpeed(IParticle otherParticle, int scale, int time = 1)
        {
            var particlesDistanceInMeters = PhysicsHelper.PixelsToMetersDistance(X, Y, otherParticle.X, otherParticle.Y, scale);
            var force = PhysicsHelper.AttractionForce(Charge, otherParticle.Charge, particlesDistanceInMeters);

            var accelerationFirstParticle = force / Weight;

            Velocity += accelerationFirstParticle * time;
            var alfaAngle1 = Math.Atan((double)(otherParticle.Y - Y) / (otherParticle.X - X)) * (180 / Math.PI);

            var vx1 = Velocity * Math.Cos(alfaAngle1);
            var vy1 = Velocity * Math.Sin(alfaAngle1);

            AjustXSpeed(vx1 * scale, time);
            AjustYSpeed(vy1 * scale, time);

            var accelerationSecondParticle = force / otherParticle.Weight;

            otherParticle.Velocity += accelerationSecondParticle * time;
            var alfaAngle2 = Math.Atan((double)(X - otherParticle.X) / Math.Sqrt(Math.Pow(X - otherParticle.X, 2) + Math.Pow(Y - otherParticle.Y, 2))) * (180 / Math.PI);

            var vx2 = otherParticle.Velocity * Math.Cos(alfaAngle2);
            var vy2 = otherParticle.Velocity * Math.Sin(alfaAngle2);

            otherParticle.AjustXSpeed(vx2 * scale, time);
            otherParticle.AjustYSpeed(vy2 * scale, time);
        }
示例#6
0
        public void UpdateConnectedParticles(int stepsToRemoved)
        {
            UInt32 removalIteration = (UInt32)(this.FinalTopologyUpdate / (this.Particles.Count - 3));

            if (this.CurrentIteration <= this.FinalTopologyUpdate && this.CurrentIteration % removalIteration == (removalIteration - 1))
            {
                if (this.Id < (Particles.Count - 3 - this.TrimmingIterations) &&
                    this.ConnectedIds.Count > 3)
                {
                    LinkedListNode <int> currentNode = this.ConnectedIds.Find(this.Id);
                    for (int i = stepsToRemoved; i > 0; i--)
                    {
                        currentNode = currentNode.Next;
                    }
                    int       removedId       = currentNode.Value;
                    IParticle removedParticle = this.Particles.Find(p => p.Id == removedId);
                    if (removedParticle.GetType().GetInterfaces().Contains(typeof(IConnectedParticles)))
                    {
                        ((IConnectedParticles)removedParticle).ConnectedIds.Remove(this.Id);
                    }
                    this.ConnectedIds.Remove(currentNode);
                }
                this.TrimmingIterations++;
            }
        }
        /// <summary>
        /// Processes an active particle.
        /// </summary>
        /// <param name="totalTime">Total game time in whole and fractional seconds.</param>
        /// <param name="elapsedTime">Elapsed game time in whole and fractional seconds.</param>
        /// <param name="particle">The particle which is ready to be processed.</param>
        /// <param name="age">The age of the particle in the range 0-1.</param>
        public override void ProcessActiveParticle(float totalTime, float elapsedTime, IParticle particle, float age)
        {
            float distance;

            Vector2 particlePosition = particle.Position;

            Vector2.DistanceSquared(ref this._position, ref particlePosition, out distance);

            if (distance < this._radiusSq)
            {
                float effect = 1f - (distance / this._radiusSq);

                Vector2 force;

                Vector2.Subtract(ref this._position, ref particlePosition, out force);

                Vector2.Normalize(ref force, out force);

                Vector2.Transform(ref force, ref this._rotation, out force);

                Vector2.Multiply(ref force, effect * elapsedTime * this._vorticity, out force);

                particle.ApplyForce(ref force);
            }
        }
        //----------------------------------------------------------------------------
        //----------------------------------------------------------------------------
        public ParticleEmitter(IRenderLayer <TInfoType> renderLayer, Type particleType, ParticleController <TInfoType> controller, string szAssetName, Vector3 v3Position, int nMaxSprites)
        {
            m_RenderLayer      = renderLayer;
            m_Particles        = new List <IParticle>(nMaxSprites);
            m_freeParticleList = new Queue <IParticle>(nMaxSprites);

            SaveSerializationData("MaxSprites", nMaxSprites);
            SaveSerializationData("AssetName", szAssetName);
            SaveSerializationData("ParticleType", particleType);

            ParticleController = controller;

            m_bActive            = false;
            m_bContinuosEmission = false;
            m_bAllowGeneration   = false;
            Position             = v3Position;
            Enabled = true;

            EngineServices.GetSystem <IGameSystems>().Components.Add(this);

            for (int nCounter = 0; nCounter < nMaxSprites; ++nCounter)
            {
                IParticle particle = Activator.CreateInstance(particleType, new object[] { m_RenderLayer, szAssetName, Position, Vector3.Zero, 0, 0, false }) as IParticle;
                particle.ParticleDead += DeadParticle_Event;
                m_Particles.Add(particle);
                m_freeParticleList.Enqueue(particle);
            }
        }
示例#9
0
        public void OpacityFunction(IParticle p)
        {
            int opacity = (int)(p.Params[0] + (p.Age * 100) % 500);
            opacity = Math.Abs((opacity < 250 ? opacity : 250 - opacity) % 255);

            p.Color = ColorPicker.FromArgb(opacity, p.Color);
        }
示例#10
0
		public void UpdateForce(IParticle particle, double duration)
		{
			if (particle.IsInfiniteMass == true) return;

			// Calculate relative position of the particle from the anchor
			Vector3 positionFromAnchor = particle.Position - Anchor;

			// Calculate the value for Gamma
			var gamma = 0.5 * Math.Sqrt((4 * SpringConstant) - (Damping * Damping));
			
			if (gamma == 0.0) return;

			// Calculate the value for the C constant
			var c = (positionFromAnchor * (Damping / (2.0 * gamma))) + (particle.Velocity * (1.0 / gamma));

			// Calculate the target position (in two parts)
			var tagetPosition = (positionFromAnchor * Math.Cos(gamma * duration)) + (c * Math.Sin(gamma*duration));
			tagetPosition *= Math.Exp(0.5 * duration * Damping);

			// Calculate the acceleration needed (and hence the force)
			var acceleration = ((tagetPosition - positionFromAnchor) * (1.0 / (duration * duration))) -
				(particle.Velocity * duration);

			// Add the force to the particle
			particle.AddForce(acceleration * particle.Mass);
		}
示例#11
0
        public bool HaveCollision(IParticle missile, IParticle target, double dt, double hitDistance = 0)
        {
            var S = missile.Position - target.Position;
            var V = missile.Speed - target.Speed;
            var r = missile.Radius + target.Radius + hitDistance;

            if (missile is IMissile && target is IShip)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("S = {0} {1}, V = {2} {3}",
                                                                 S.Length, S, V, V.Length));
            }
            // Collision at t = 0
            if (S.Length <= r)
            {
                return(true);
            }
            var Vx2Vy2   = V.SquareLength;
            var VxSxVySy = V * S;

            // No collision within time interval
            if (Vx2Vy2 * dt <= Math.Abs(VxSxVySy))
            {
                return(false);
            }
            // Potential collision time
            var t = -VxSxVySy / Vx2Vy2;
            var s = S + V * t;

            // Was that near enough?
            return(s.Length <= r);
        }
示例#12
0
 public void UpdatePersonalBest(IParticle particle, IProblem problem)
 {
     if (particle.Position.IsInsideBounds(problem.ProblemDomain.DimensionBounds))
     {
         Delegate.UpdatePersonalBest(particle, problem);
     }
 }
示例#13
0
 public void PerformIteration(IParticle particle, IProblem problem)
 {
     VelocityProvider.UpdateVelocity(particle);
     particle.UpdatePreviousPosition();
     PositionProvider.UpdatePosition(particle);
     BoundaryConstraint.Enforce(particle, problem);
 }
示例#14
0
        public virtual void Draw(IParticle _particle)
        {
            var rect = new Rectangle(particlePoint(_particle).X - 1, particlePoint(_particle).Y - 1, 2, 2);

            tempGraph.DrawEllipse(new Pen(Color.Black, 2), rect);
            tempGraph.DrawLine(new Pen(Color.Blue, 2), particlePoint(_particle), particleSpeed(_particle));
        }
        public override void Draw(IParticle _particle)
        {
            var rect = new Rectangle(particlePoint(_particle).X - 2, particlePoint(_particle).Y - 2, 4, 4);

            tempGraph.FillEllipse(new SolidBrush(Color.GreenYellow), rect);
            tempGraph.DrawLine(new Pen(Color.Green, 2), particlePoint(_particle), particleSpeed(_particle));
        }
示例#16
0
 public void AdjustY(IParticle p)
 {
     int direction = (p.Y < GameEnvironment.Mouse.Y ? 1 : -1);
     double speed = Math.Abs(p.Y - GameEnvironment.Mouse.Y) * direction;
     p.Params[1] += speed * GameEnvironment.ElapsedTime;
     p.Y += (float)(p.Params[1] * GameEnvironment.ElapsedTime * 10);
 }
示例#17
0
        public static IParticle Create(PsoParticleType type,
                                       int locationDim,
                                       int fitnessDim,
                                       IFitnessFunction <double[], double[]> function,
                                       double restartEpsilon   = double.MaxValue,
                                       int iterationsToRestart = int.MaxValue,
                                       DimensionBound[] bounds = null,
                                       double[] initVelocity   = null
                                       )
        {
            IParticle particle = null;
            var       rand     = RandomGenerator.GetInstance();

            switch (type)
            {
            case PsoParticleType.Standard:
            case PsoParticleType.FullyInformed:
                particle = new StandardParticle(restartEpsilon, iterationsToRestart);
                break;

            case PsoParticleType.ChargedParticle:
                particle = new ChargedParticle();
                break;

            case PsoParticleType.DummyParticle:
                particle = new DummyParticle();
                break;
            }

            var x = bounds != null?rand.RandomVector(locationDim, bounds) : rand.RandomVector(locationDim);

            particle.Init(new ParticleState(x, function.Evaluate(x)),
                          initVelocity ?? rand.RandomVector(locationDim, MinInitialVelocity, MaxInitialVelocity), bounds);
            return(particle);
        }
        public void ResampleParticles_DefaultRouletteWheel()
        {
            IParticle[] p = new IParticle[mParticleCount];

            double mw = 0;

            for (int i = 0; i < mParticleCount; ++i)
            {
                mw = System.Math.Max(mw, mParticleWeights[i]);
            }

            double beta  = 0;
            int    index = (int)(mParticleCount * RandomEngine.NextDouble());

            for (int i = 0; i < mParticleCount; ++i)
            {
                beta += mw * 2 * RandomEngine.NextDouble();
                while (beta > mParticleWeights[index])
                {
                    beta -= mParticleWeights[index];
                    index = (index + 1) % mParticleCount;
                }
                p[i] = mParticles[index];
            }

            mParticles = p;
        }
示例#19
0
        /// <summary>
        /// 螺旋の動きを計算して葉っぱの位置や回転を調整する
        /// </summary>
        private void Spiral(IParticle leaf, float progress, Vector3 direction, float rotationBias)
        {
            const float SPIRAL_ROTATION = 180f * 3f; // スパイラルする回転量
            const float SPIRAL_POWER    = 4f;        // スパイラルの強さ
            const float POSITION_BIAS   = 0.05f;     // 位置の偏り
            const float POSITION_ADJUST = 0.5f;      // 位置調整値
            const float MIN_SCALE       = 0.5f;      // 最小サイズ
            const float ROTATION        = 540f;      // 回転量

            // 位置を計算
            var rotation
                = Quaternion.AngleAxis(progress * SPIRAL_ROTATION, Vector3.forward);

            var length
                = (POSITION_BIAS + progress * POSITION_ADJUST + Mathf.Pow(progress, SPIRAL_POWER));

            leaf.CacheTransform.position
                = CacheTransform.position + rotation * direction * length;

            // スケールを計算
            var scale = Mathf.Min(1, progress + MIN_SCALE);

            leaf.CacheTransform.localScale
                = Vector3.one * scale;

            // 回転を計算
            var angle = progress * ROTATION + rotationBias;

            leaf.CacheTransform.rotation
                = Quaternion.AngleAxis(angle, Vector3.forward);
        }
示例#20
0
        private bool Collision(IParticle missile, IParticle target, double dt, double crossRadius = 0)
        {
            var S = missile.Position - target.Position;
            var V = missile.Speed - target.Speed;

            // Collision at t = 0
            if (S.Length <= crossRadius)
            {
                return(true);
            }
            var Vx2Vy2   = V.SquareLength;
            var VxSxVySy = V * S;

            // No collision within time interval
            if (Vx2Vy2 * dt <= Math.Abs(VxSxVySy))
            {
                return(false);
            }
            // Potential collision time
            var t = -VxSxVySy / Vx2Vy2;
            var s = S + V * t;

            // Was that near enough?
            return(s.Length <= crossRadius);
        }
示例#21
0
 public void UpdateForce(IParticle particle, double duration)
 {
     if (particle.IsInfiniteMass == false)
     {
         particle.AddForce(Gravity * particle.Mass);
     }
 }
示例#22
0
        public override bool BounceContain(IParticle particle)
        {
            Vector3d velocity = particle.Velocity;

            Curve[] feelers = GetFeelerCrvs(particle, particle.BodySize, false);

            foreach (Brep[] borderWalls in borderWallsArray)
            {
                foreach (Brep brep in borderWalls)
                {
                    foreach (Curve feeler in feelers)
                    {
                        //Check feeler intersection with each brep face
                        foreach (BrepFace face in brep.Faces)
                        {
                            Curve[]   overlapCrvs;
                            Point3d[] intersectPts;
                            Intersection.CurveBrepFace(feeler, face, Constants.AbsoluteTolerance, out overlapCrvs, out intersectPts);
                            if (intersectPts.Length > 0)
                            {
                                Point3d testPt = intersectPts[0];
                                double  u, v;
                                face.ClosestPoint(testPt, out u, out v);
                                Vector3d normal = face.NormalAt(u, v);
                                normal.Reverse();
                                velocity          = Vector.Reflect(velocity, normal);
                                particle.Velocity = velocity;
                                return(true);
                            }
                        }
                    }
                }
            }
            return(false);
        }
        /// <summary>
        /// Calculate the velocity as an unbounded vector using the standard inertia weight model.
        /// </summary>
        /// <param name="particle">The particle to calculate velocity.</param>
        /// <returns>An unbounded Vector containing the velocity.</returns>
        public void UpdateVelocity(IParticle particle)
        {
            ExtendedParticle sp = particle as ExtendedParticle;
            //TODO: update previous velocity
            int    dim    = sp.Position.Length;
            double w      = sp.Parameters.InertiaWeight.Parameter;
            double c1     = sp.Parameters.CognitiveAcceleration.Parameter;
            double c2     = sp.Parameters.SocialAcceleration.Parameter;
            double c3     = sp.Parameters.ExtendedAcceleration.Parameter;
            double lambda = sp.Parameters.Lambda;

            Vector velocity = sp.Velocity;
            Vector pos      = sp.Position;
            Vector lGuide   = LocalGuideProvider.GetGuide(sp);
            Vector nGuide   = NeighbourhoodGuideProvider.GetGuide(sp);
            Vector aGuide   = AdditionalGuideProvider.GetGuide(sp);

            for (int i = 0; i < dim; i++)
            {
                double inertiaTerm    = w * sp.Velocity[i];
                double cognitiveTerm  = c1 * RandomProvider.NextDouble() * (lGuide[i] - pos[i]);
                double socialTerm     = lambda * c2 * RandomProvider.NextDouble() * (nGuide[i] - pos[i]);
                double additionalTerm = (1 - lambda) * c3 * RandomProvider.NextDouble() * (aGuide[i] - pos[i]);
                velocity[i] = inertiaTerm + cognitiveTerm + socialTerm + additionalTerm;
            }
        }
示例#24
0
        /// <summary>
        /// Calculates likelihood of the distance between particle and measurement (point).
        /// </summary>
        /// <param name="particle">Particle.</param>
        /// <param name="measurement">Measurement (coordinate).</param>
        /// <param name="likelihoodFunc">
        /// Likelihood function.
        /// <para>Can be used as parameter in <see cref="Update"/> function to calculate measurement-track association likelihood.</para>
        /// </param>
        /// <returns>Measurement-track likelihood.</returns>
        public static double DistanceLikelihood(IParticle <ConstantVelocity2DModel> particle, PointF measurement, Func <double, double> likelihoodFunc)
        {
            var delta      = measurement.DistanceTo(particle.State.Position);
            var likelihood = likelihoodFunc(delta);

            return(likelihood);
        }
        // Given two vehicles, based on their current positions and velocities,
        // determine the time until nearest approach
        //
        // XXX should this return zero if they are already in contact?
        private double PredictNearestApproachTime(IParticle neighbor)
        {
            // imagine we are at the origin with no velocity,
            // compute the relative velocity of the other vehicle
            Vector3d agentVelocity    = agent.Velocity;
            Vector3d neighborVelocity = neighbor.Velocity;
            Vector3d relativeVelocity = neighborVelocity - agentVelocity;
            double   relativeSpeed    = relativeVelocity.Length;

            // for parallel paths, the vehicles will always be at the same distance,
            // so return 0 (aka "now") since "there is no time like the present"
            if (relativeSpeed == 0)
            {
                return(0);
            }

            // Now consider the path of the other vehicle in this relative
            // space, a line defined by the relative position and velocity.
            // The distance from the origin (our vehicle) to that line is
            // the nearest approach.

            // Take the unit tangent along the other vehicle's path
            Vector3d relativeTangent = relativeVelocity / relativeSpeed;

            // find distance from its path to origin (compute offset from
            // other to us, find length of projection onto path)
            Vector3d relativePosition = agent.Position - neighbor.Position;
            double   projection       = Util.Vector.DotProduct(relativeTangent, relativePosition);

            return(projection / relativeSpeed);
        }
示例#26
0
        public override void Draw(IParticle _particle)
        {
            var rect = new Rectangle(particlePoint(_particle).X - 2, particlePoint(_particle).Y - 2, 2, 2);

            tempGraph.DrawEllipse(new Pen(Color.Red, 2), rect);
            tempGraph.DrawLine(new Pen(Color.Blue, 2), particlePoint(_particle), particleSpeed(_particle));
        }
示例#27
0
 public void AdjustX(IParticle p)
 {
     int direction = (p.X < GameEnvironment.Mouse.X ? 1 : -1);
     double speed = Math.Abs(p.X - GameEnvironment.Mouse.X) * direction;
     p.Params[0] += speed * GameEnvironment.ElapsedTime;
     p.X += (float)(p.Params[0] * GameEnvironment.ElapsedTime * 10);
 }
示例#28
0
        protected override Point particlePoint(IParticle _particle)
        {
            var x = (int)Math.Floor(_particle.CoordinatesInDouble.First);
            var y = (int)Math.Floor(_particle.CoordinatesInDouble.Second);

            return(new Point(x, y));
        }
示例#29
0
 public override void Draw(IParticle _particle)
 {
     var rect = new Rectangle(particlePoint(_particle).X - 2, particlePoint(_particle).Y - 2, 2, 2);
     
     tempGraph.DrawEllipse(new Pen(Color.Red, 2), rect);
     tempGraph.DrawLine(new Pen(Color.Blue, 2), particlePoint(_particle), particleSpeed(_particle));
 }
        public Vector GetGuide(IParticle particle)
        {
            PSO pso = AbstractAlgorithm.CurrentInstance as PSO;

            return(CenterStrategy.GetCenter(pso.Particles)); //TODO: this recalculates for each particle... -> is this needed? For async, it makes sense
                                                             //for sync, this would be affected by each particle update though...
        }
示例#31
0
		public void UpdateForce(IParticle particle, double duration)
		{
			if (particle.IsInfiniteMass == false)
			{
				particle.AddForce(Gravity * particle.Mass);
			}
		}
        /// <summary>
        /// Each iteration strategy follows the following steps.
        ///
        /// For all particles:
        /// <list type="number">
        /// <item>Perform iteration.</item>
        /// <item>Calculate fitness.</item>
        /// </list>
        ///
        /// For all particles:
        /// <list type="number">
        /// <item>Update particles in the current particle's neighbourhood.</item>
        /// </list>
        ///
        /// </summary>
        public void PerformIteration(PSO algorithm)
        {
            IParticle particle;

            //update each particle
            for (int i = 0; i < algorithm.Particles.Count; i++)
            {
                particle = algorithm.Particles[i];
                particle.PerformIteration(algorithm);
                particle.CalculateFitness(algorithm.Problem);
            }

            //update neighbourhood bests
            for (int i = 0; i < algorithm.Particles.Count; i++)
            {
                particle = algorithm.Particles[i];
                List <IParticle> neighbours = algorithm.Topology.GetNeighbours(particle, algorithm.Particles);
                for (int j = 0; j < neighbours.Count; j++)
                {
                    IParticle other = neighbours[j];
                    if (particle.BestFitness.CompareTo(other.NeighbourhoodBest.BestFitness) > 0)
                    {
                        other.NeighbourhoodBest = particle;
                    }
                }
            }
        }
示例#33
0
        /// <summary>
        /// Draws all of the particle systems
        /// </summary>
        /// <remarks>
        /// An efficient SpriteBatch-based method by Shawn Hargreaves.
        /// Thoroughly documented at http://blogs.msdn.com/b/shawnhar/archive/2011/01/12/spritebatch-billboards-in-a-3d-world.aspx
        /// </remarks>
        public void Draw(SpriteBatch spriteBatch)
        {
            basicEffect.Projection = Projection;

            foreach (KeyValuePair <BlendState, List <IParticleSystem> > particleSystemBatch in particleSystems)
            {
                //spriteBatch.Begin(0, particleSystemBatch.Key, null, DepthStencilState.DepthRead, RasterizerState.CullNone, basicEffect);
                spriteBatch.Begin(0, particleSystemBatch.Key, null, DepthStencilState.None, RasterizerState.CullNone, basicEffect);

                foreach (IParticleSystem particleSystem in particleSystemBatch.Value)
                {
                    if (particleSystem.Enabled)
                    {
                        for (int i = 0; i < particleSystem.ParticleCount; i++)
                        {
                            IParticle particle = particleSystem[i];

                            Vector3 viewSpacePosition = Vector3.Transform(particle.Position, View);

                            spriteBatch.Draw(particleSystem.Texture, new Vector2(viewSpacePosition.X, viewSpacePosition.Y), null, particle.Color, particle.Angle, particleSystem.TextureOrigin, particle.Scale, 0, viewSpacePosition.Z);
                        }
                    }
                }

                spriteBatch.End();
            }
        }
示例#34
0
        public const double Megatonn = 4184; // 4.184 E 15, Дж = кг м2 с-2 -> 1E-9 т км2 с-2

        public bool HaveCollision(IParticle missile, IParticle target, double dt, double hitDistance = 0)
        {
            var S = missile.Position - target.Position;
            var V = missile.Speed - target.Speed;
            var r = missile.Radius + target.Radius + hitDistance;

            // Collision at t = 0
            if (S.Length <= r)
            {
                return(true);
            }
            var Vx2Vy2   = V.SquareLength;
            var VxSxVySy = V * S;

            // No collision within time interval
            if (Vx2Vy2 * dt <= Math.Abs(VxSxVySy))
            {
                return(false);
            }
            // Potential collision time
            var t = -VxSxVySy / Vx2Vy2;
            var s = S + V * t;

            // Was that near enough?
            return(s.Length <= r);
        }
示例#35
0
        public virtual void Draw(IParticle _particle)
        {
            var rect = new Rectangle(particlePoint(_particle).X - 1, particlePoint(_particle).Y - 1, 2, 2);

            tempGraph.DrawEllipse(new Pen(Color.Black, 2), rect);
            tempGraph.DrawLine(new Pen(Color.Blue, 2), particlePoint(_particle), particleSpeed(_particle));
        }
示例#36
0
        //---------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------

        //---------------------------------------------------------------
        #region Methods
        //---------------------------------------------------------------
        /// <summary>
        /// Creates a new particle.
        /// </summary>
        /// <param name="frameTime">The factor that indicates at which time during the frame, the
        /// particle gets be emitted. (For interpolation purposes)</param>
        protected override IParticle CreateParticle(float frameTime)
        {
            IParticle particle = base.CreateParticle(frameTime);

            Particle.SetPosition(particle, position);
            return(particle);
        }
示例#37
0
 /// <summary>
 /// Emits the particle.
 /// </summary>
 /// <param name="particleSystem">The particleSystem that manages the emitted particles.</param>
 /// <param name="particle">Particle to emit.</param>
 /// <param name="frameTime">The factor that indicates at which time during the frame, the
 /// particle gets emitted. (For interpolation purposes)</param>
 protected void Emit(IParticleSystem particleSystem, IParticle particle, float frameTime)
 {
     if (OnEmit != null)
     {
         OnEmit(particle, frameTime);
     }
     particleSystem.Emit(particle);
 }
示例#38
0
		public SpringForceGenerator(IParticle otherParticle, double springConstant, double restLength,
			bool isBungeeSpring = false)
		{
			OtherParticle = otherParticle;
			SpringConstant = springConstant;
			RestLength = restLength;
			IsBungeeSpring = isBungeeSpring;
		}
示例#39
0
 public SpringForceGenerator(IParticle otherParticle, double springConstant, double restLength,
                             bool isBungeeSpring = false)
 {
     OtherParticle  = otherParticle;
     SpringConstant = springConstant;
     RestLength     = restLength;
     IsBungeeSpring = isBungeeSpring;
 }
        private float _strength;    //Gravity strength in pixels per second.

        /// <summary>
        /// Processes an active particle.
        /// </summary>
        /// <param name="totalTime">Total game time in whole and fractional seconds.</param>
        /// <param name="elapsedTime">Elapsed game time in whole and fractional seconds.</param>
        /// <param name="particle">The particle to be updated.</param>
        /// <param name="age">The age of the particle in the range of zero to one inclusive.</param>
        public override void ProcessActiveParticle(float totalTime, float elapsedTime, IParticle particle, float age)
        {
            Vector2 force = this._gravity;

            Vector2.Multiply(ref force, this._strength * elapsedTime, out force);

            particle.ApplyForce(ref force);
        }
示例#41
0
        //---------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------

        //---------------------------------------------------------------
        #region Methods
        //---------------------------------------------------------------
        /// <summary>
        /// Updates the particles of the array.
        /// </summary>
        /// <param name="particles">Particles to affect.</param>
        /// <param name="filled">The number of active particles in the particles list.</param>
        /// <param name="deltaTime">The time since the last frame.</param>
        public void Affect(IList particles, int filled, float deltaTime)
        {
            for (int i = 0; i < filled; i++)
            {
                IParticle particle = (particles[i] as IParticle);
                (particles[i] as IParticleIndex).TextureIndex += deltaTime / timePerFrame;
            }
        }
示例#42
0
 /// <summary>
 /// Creates PsoAlgorithm with specific parameters to solve given problem using precreated particles
 /// </summary>
 /// <param name="parameters">takes PsoParameters to check what stop conditions are defined.
 ///  PsoAlgorithm looks for TargetValue, Epsilon, TargetValueCondition, IterationsLimit, IterationsLimitCondition
 /// </param>
 /// <param name="fitnessFunction">function whose optimum is to be found</param>
 /// <param name="particles"> particles traversing the search space </param>
 /// <param name="logger"></param>
 public PsoAlgorithm(PsoParameters parameters, IFitnessFunction<double[], double[]> fitnessFunction, IParticle[] particles, ILogger logger = null)
 {
     _parameters = parameters;
     _fitnessFunction = fitnessFunction;
     _particles = particles;
     _iteration = 0;
     _logger = logger;
     _optimizer = PsoServiceLocator.Instance.GetService<IOptimization<double[]>>();
 }
示例#43
0
		public void UpdateForce(IParticle particle, double duration)
		{
			var springVector = particle.Position - OtherParticle.Position;
			var springExtension = springVector.Magnitude - RestLength;

			if (((springExtension < 0.0f) && IsBungeeSpring)) return;

			var springForce = (SpringConstant * springExtension) * springVector.Normal.Inverse;
			particle.AddForce(springForce);
		}
示例#44
0
        public void TrackToTarget(IParticle p)
        {
            if (p.Sprite.Animation.CurrentFrame > 2)
                p.Sprite.Animation.CurrentFrame = 2;

            if (p.Age > 0.2)
            {
                p.Color = AdjustOpacity(p.Color, 255 - (int)((p.Age / 0.5) * 255));
            }
        }
示例#45
0
        protected override Point particleSpeed(IParticle _particle)
        {
            var x = (int) Math.Floor(_particle.CoordinatesInDouble.First);
            var y = (int) Math.Floor(_particle.CoordinatesInDouble.Second);

            var vx = (int) Math.Floor(5*Miscelaneous.SpeedDrawMultiplayer*_particle.SpeedInDouble.First);
            var vy = (int) Math.Floor(5*Miscelaneous.SpeedDrawMultiplayer*_particle.SpeedInDouble.Second);

            return new Point(x + vx, y + vy);
        }
        private float _coefficient;     //The damping coefficient.

        /// <summary>
        /// Processes an active particle.
        /// </summary>
        /// <param name="totalTime">Total game time in whole and fractional seconds.</param>
        /// <param name="elapsedTime">Elapsed game time in whole and fractional seconds.</param>
        /// <param name="particle">The particle to be processed.</param>
        /// <param name="age">The age of the particle in the range 0-1.</param>
        public override void ProcessActiveParticle(float totalTime, float elapsedTime, IParticle particle, float age)
        {
            Vector2 momentum = particle.Momentum;

            Vector2.Multiply(ref momentum, this._coefficient, out momentum);

            Vector2.Negate(ref momentum, out momentum);

            particle.ApplyForce(ref momentum);
        }
示例#47
0
        public FadeDecorator(int start, int duration, float endAlpha, IParticle particle)
            : base(particle)
        {
            fading = false;
            done = false;

            this.endAlpha = endAlpha;
            this.duration = duration;
            this.start = start;
            this.timer = TimeSpan.Zero;
        }
示例#48
0
		public void UpdateForce(IParticle particle, double duration)
		{
			var speedSquared = particle.Velocity.SquareMagnitude;
			var speed = Math.Sqrt(speedSquared);

			var dragMagnitude = (K1 * speed) + (K2 * speedSquared);

			var force = new Vector3(particle.Velocity.Normal.Inverse * dragMagnitude);

			particle.AddForce(force);
		}
示例#49
0
 public void InitializeVelocity(IParticle particle)
 {
     if (Velocity == null)
     {
         return;
     }
     for (var i = 0; i < Velocity.Length; i++)
     {
         Velocity[i] = (particle.CurrentState.Location[i] - CurrentState.Location[i])/2;
     }
 }
        public InflationDecorator(int start, int duration, float inflationAmount, IParticle particle)
            : base(particle)
        {
            startTime = start;
            this.duration = duration;
            endTime = startTime + duration;
            amount = inflationAmount;

            expanding = false;
            done = false;
        }
示例#51
0
 //For Construct Agent Settings
  public AgentType(IParticle p, double maxSpeed, double maxForce, double visionRadius, double visionAngle)
    : base(p.Up, p.Acceleration, p.Lifespan, p.Mass, p.BodySize, p.HistoryLength)
  {
    SteerAcceleration = Vector3d.Zero;
    MaxSpeed = maxSpeed;
    MaxForce = maxForce;
    VisionRadius = visionRadius;
    VisionAngle = visionAngle;
    Lat = 0;//Util.Random.RandomDouble(0, RS.TWO_PI);
    Lon = 0;//Util.Random.RandomDouble(-RS.HALF_PI, RS.HALF_PI);
  }
示例#52
0
 public static void AddParticle(IParticle particle)
 {
     for (int i = 0; i < Particles.Length; i++)
     {
         IParticle p = Particles[i];
         if (p == null || !p.isActive)
         {
             Particles[i] = particle;
             return;
         }
     }
 }
示例#53
0
 public virtual double CalkDistance(IParticle _particle)
 {
     var diff = CoordinatesInDouble - _particle.CoordinatesInDouble;
     if (diff.First > (Miscelaneous.Width - 2 * Miscelaneous.InterractionR))
     {
         diff.First -= Miscelaneous.Width;
     }
     if (!Miscelaneous.RestrictingBoards && diff.Second > Miscelaneous.Height - Miscelaneous.InterractionR)
     {
         diff.Second -= Miscelaneous.Height;
     }
     return diff.ABS();
 }
示例#54
0
        public override void Interract(IParticle _particle, int _index)
        {
            var ptPos = _particle.CoordinatesInDouble;
            var ptSpeed = _particle.SpeedInDouble;
            var ptPosNext = ptSpeed + ptPos;

            var ptBordFirst = Borders[_index].First;
            var ptBordSecond = Borders[_index].Second;

            var ang = Miscelaneous.GetDegreeBetveen(ptPos, ptPosNext, ptBordFirst, ptBordSecond);
            var intersectionPt = Miscelaneous.IntersectionPoint(ptPos, ptPosNext, ptBordFirst, ptBordSecond);

            PairDouble newPos;
            if (_index == 0)
            {
                newPos = _particle.CoordinatesInDouble + new PairDouble(m_SizeX, 0);
                _particle.UpdCoordinates(newPos + _particle.SpeedInDouble);
            }
            if (_index == 1)
            {
                ang = -2 * ang;

                _particle.UpdCoordinates(Miscelaneous.Rotate(intersectionPt, ptPosNext, ang));
                _particle.UpdSpeed(Miscelaneous.Rotate(ptSpeed, ang));
            }
            if (_index == 2)
            {
                newPos = _particle.CoordinatesInDouble - new PairDouble(m_SizeX, 0);
                _particle.UpdCoordinates(newPos + _particle.SpeedInDouble);
            }
            if (_index == 3)
            {
                if (ang > 90)
                {
                    ang = 2 * (180 - ang);
                }
                else
                {
                    ang = -2 * ang;
                }
                _particle.UpdCoordinates(Miscelaneous.Rotate(intersectionPt, ptPosNext, ang));

                _particle.UpdSpeed(Miscelaneous.Rotate(ptSpeed, ang));

            }
            
        }
示例#55
0
        public int? Check(IParticle _particle)
        {
            for (int i = 0; i < Borders.Count; i++)
            {
                var pt1 = _particle.CoordinatesInDouble;
                var pt2 = _particle.SpeedInDouble + pt1;

                var pt3 = Borders[i].First;
                var pt4 = Borders[i].Second;

                var isIntersection = Miscelaneous.Intersect(pt1, pt2, (PairDouble)pt3, (PairDouble)pt4);

                if (isIntersection)
                {
                    return i;
                }
            }
            return null;
        }
		public void UpdateForce(IParticle particle, double duration)
		{
			 var particleHeight = particle.Position.Y;

			// Check if we are out of the water - if so, return as there is no buoyancy force to add
			if (particleHeight >= LiquidHeight + MaximumDepth) return;

			// Fully submerged buoyancy force
			var force = new Vector3 {Y = LiquidDensity * Volume};

			// If partially submerged, adjust the buoyancy force based on how deep the object is
			if (particleHeight > LiquidHeight - MaximumDepth)
			{
				var amountSubmerged = (LiquidHeight - particleHeight) / (MaximumDepth);
				force.Y *= amountSubmerged;
			}
		
			particle.AddForce(force);
		}
示例#57
0
 public override void Interract(IParticle _particle, int _index)
 {
  
     PairDouble newPos = new PairDouble(0,0);
     if (_index == 0)
     {
         newPos = _particle.CoordinatesInDouble +  new PairDouble(m_SizeX, 0);
     }
     if (_index == 1)
     {
         newPos = _particle.CoordinatesInDouble - new PairDouble(0, m_SizeY);
     }
     if (_index == 2)
     {
         newPos = _particle.CoordinatesInDouble - new PairDouble(m_SizeX, 0);
     }
     if (_index==3)
     {
         newPos = _particle.CoordinatesInDouble + new PairDouble(0, m_SizeY);
     }
     _particle.UpdCoordinates(newPos + _particle.SpeedInDouble);
 }
    private static Curve[] GetFeelerCrvs(IParticle particle, double visionDistance,
                                  bool accurate)
    {
      Curve[] feelers;
      if (accurate)
      {
        feelers = new Curve[5];
      }
      else
      {
        feelers = new Curve[1];
      }

      double feelerAngle = RS.HALF_PI;
      //Calculate straight ahead feeler with length visionDistance
      Vector3d feelerVec = particle.Velocity;
      feelerVec.Unitize();
      feelerVec = Vector3d.Multiply(feelerVec, visionDistance);
      feelers[0] = new Line(particle.Position3D, feelerVec).ToNurbsCurve();

      if (!accurate)
      {
        return feelers;
      }

      //Calculate tertiary feelers with length bodySize
      feelerVec = particle.Velocity;
      feelerVec.Unitize();
      Plane rotPln = new Plane(particle.Position3D, particle.Velocity);
      Vector3d rotAxis = rotPln.XAxis;
      feelers[1] = GetFeelerCrv(feelerVec, particle.Position, particle.BodySize, feelerAngle, rotAxis);
      feelers[2] = GetFeelerCrv(feelerVec, particle.Position, particle.BodySize, -feelerAngle, rotAxis);
      rotAxis = rotPln.YAxis;
      feelers[3] = GetFeelerCrv(feelerVec, particle.Position, particle.BodySize, feelerAngle, rotAxis);
      feelers[4] = GetFeelerCrv(feelerVec, particle.Position, particle.BodySize, -feelerAngle, rotAxis);

      return feelers;
    }
示例#59
0
 public SlowDownDecorator(IParticle particle)
     : base(particle)
 {
 }
示例#60
0
 public SpinDecorator(int spinrate, IParticle particle)
     : base(particle)
 {
     this.spinRate = spinrate;
     timer = TimeSpan.FromMilliseconds(spinrate);
 }