示例#1
0
文件: Common.cs 项目: PtrMan/ai2
        /**
         * find a particular instance(example Ek) or prototype in a sequence
         * and give as a result the index of instance(prototype) in the sequence
         * item means instance or prototype.
         * If must_find is set up as true and the example (item) has not been found -- write error
         * message and stop the program.
         * It is used by ART 1, ART 2A and ART 2A-C algorithms
         **/
        public static int findItem(List<Math.DynamicVector<float>> samples, Math.DynamicVector<float> instance, bool mustFind)
        {
            int index, i;

            index = -1;

            for( i = 0; i < samples.Count; i++ )
            {
                if( samples[i] == instance )
                {
                    index = i;
                    break;
                }
            }

            if( !mustFind )
            {
                return index;
            }
            else
            {
                if( index != -1 )
                {
                    return index;
                }
                else
                {
                    throw new Exception("sample ... was not found in sequence.");
                }
            }
        }
示例#2
0
文件: Route.cs 项目: sladen/openbve2
 // constructors
 /// <summary>Creates a new instance of this class.</summary>
 /// <param name="ambientLight">The ambient light color.</param>
 /// <param name="diffuseLight">The diffuse light color.</param>
 /// <param name="specularLight">The specular light color.</param>
 /// <param name="lightDirection">The direction the light shines at.</param>
 public DirectionalLight(Color.ColorRGB ambientLight, Color.ColorRGB diffuseLight, Color.ColorRGB specularLight, Math.Vector3 lightDirection)
 {
     this.AmbientLight = ambientLight;
     this.DiffuseLight = diffuseLight;
     this.SpecularLight = specularLight;
     this.LightDirection = lightDirection;
 }
示例#3
0
        /// <summary>
        /// Returns a graph of MDP States from the States matrices and Action label vector.
        /// </summary>
        /// <param name="states">State matrix.</param>
        /// <param name="actions">Action label vector.</param>
        /// <param name="statesP">Transition states matrix.</param>
        /// <param name="reward">Reward value vector.</param>
        /// <param name="properties">Feature properties from the original set.</param>
        /// <param name="discretizer">Discretization function for generating unique state identifiers.</param>
        /// <returns>IEnumerable&lt;IMDPState&gt;</returns>
        public static IEnumerable<MDPState> GetStates(Matrix states, Vector actions, Matrix statesP, Vector reward, 
            Math.Summary properties, IDiscretizer discretizer)
        {
            Math.Summary summary = (properties != null ? properties : Math.Summary.Summarize(states));

            discretizer.Initialize(states, summary);

            var sdist = new Dictionary<double, MDPState>();
            var adist = new Dictionary<string, double>();
            var results = new Dictionary<double, MDPState>();

            for (int i = 0; i < states.Rows; i++)
            {
                double sid = discretizer.Discretize(states[i], summary);

                if (!sdist.ContainsKey(sid))
                {
                    sdist.Add(sid, MDPConverter.GetState(states[i], summary, discretizer));
                    results.Add(sid, sdist[sid]);
                }

                double tsid = discretizer.Discretize(statesP[i], summary);
                MDPState tstate = (sdist.ContainsKey(tsid) ? sdist[tsid] : MDPConverter.GetState(statesP[i], summary, discretizer));

                if (!sdist.ContainsKey(tsid))
                    sdist.Add(tsid, tstate);

                string key = GetActionKey((int)sid, (int)tsid);

                if (!adist.ContainsKey(key))
                    adist.Add(key, 1);
                else
                {
                    adist[key]++;
                }

                sdist[sid].Successors.Add(new MDPSuccessorState(MDPConverter.GetAction(actions[i], (int) sid, (int) tsid), 0, tstate, reward[i]));

                if (results.ContainsKey(tsid))
                    results.Remove(tsid);
            }

            foreach (var state in sdist.Values)
            {
                double sum = state.Successors.Sum(s => adist[GetActionKey(state.Id, s.State.Id)]);
                foreach (var successor in state.Successors)
                {
                    var key = GetActionKey(state.Id, successor.State.Id);
                    ((AI.Action) successor.Action).Probability = adist[key] / sum;
                }
            }

            // return starting states
            return results.Values;
        }
 static void Main(string[] args)
 {
     Complex C1 = new Complex(1, 2);
     Complex C2 = new Complex(3, 4);
     Complex C3 = C1 + C2;
     Console.WriteLine("C1={0}", C1);
     Console.WriteLine("C2={0}", C2);
     Console.WriteLine("C3={0}", C3);
     Math mth = new Math();
     Complex C4 = mth.Add(C2, C3);
     Console.WriteLine("C4={0}", C4);
 }
示例#5
0
文件: Track.cs 项目: sladen/openbve2
 // TODO: Helper functions
 /// <summary>Creates a straight track segment from two specified points.</summary>
 /// <param name="pointA">The first point.</param>
 /// <param name="pointB">The second point.</param>
 /// <param name="orientation">The orientation at the first point without factoring in roll. The Z component of this parameter must point from A toward B.</param>
 /// <param name="rollA">The roll at the first point.</param>
 /// <param name="rollB">The roll at the second point.</param>
 /// <param name="segment">Receives the segment on success. The start and end of the segment may be connected to other track segments.</param>
 /// <returns>The success of this operation. This operation fails if the two specified points coincide.</returns>
 public static bool CreateStraightSegmentFromPoints(Math.Vector3 pointA, Math.Vector3 pointB, Math.Orientation3 orientation, double rollA, double rollB, out PhysicalSegment segment)
 {
     if (pointA == pointB) {
         segment = null;
         return false;
     } else {
         double length = OpenBveApi.Math.Vector3.Norm(pointB - pointA);
         StraightSegment straight = new StraightSegment();
         straight.Previous = SegmentConnection.Empty;
         straight.Next = SegmentConnection.Empty;
         straight.Length = length;
         straight.StartingRoll = rollA;
         straight.EndingRoll = rollB;
         straight.Position = pointA;
         straight.Orientation = orientation;
         segment = straight;
         return true;
     }
 }
示例#6
0
 // Inverse Hyperbolic Secant
 public static double HArcsec(double x)
 {
     return(MathObj.Log((MathObj.Sqrt(-x * x + 1) + 1) / x));
 }
示例#7
0
 // Inverse Hyperbolic Cosine
 public static double HArccos(double x)
 {
     return(MathObj.Log(x + MathObj.Sqrt(x * x - 1)));
 }
示例#8
0
 /// <summary>Rotates the object.</summary>
 /// <param name="direction">The direction perpendicular to the plane on which to rotate.</param>
 /// <param name="cosineOfAngle">The cosine of the angle by which to rotate.</param>
 /// <param name="sineOfAngle">The sine of the angle by which to rotate.</param>
 public abstract void Rotate(Math.Vector3 direction, double cosineOfAngle, double sineOfAngle);
示例#9
0
 /// <summary>Scales the object.</summary>
 /// <param name="factor">The factor by which to scale.</param>
 public abstract void Scale(Math.Vector3 factor);
示例#10
0
        /// <summary>
        /// Returns a flat collection of states/actions and their transition states.
        /// </summary>
        /// <param name="states">State matrix.</param>
        /// <param name="actions">Action label vector.</param>
        /// <param name="statesP">Transition states matrix.</param>
        /// <param name="properties">(Optional) Feature summary.</param>
        /// <param name="discretizer">Disretization function to apply for reducing states.</param>
        /// <returns></returns>
        public static Tuple<IEnumerable<IState>, IEnumerable<IAction>, IEnumerable<IState>> GetStates(Matrix states, 
            Vector actions, Matrix statesP, Math.Summary properties, IDiscretizer discretizer)
        {
            Math.Summary summary = (properties != null ? properties : Math.Summary.Summarize(states));

            var slist = new IState[states.Rows];
            var alist = new IAction[actions.Length];
            var splist = new IState[statesP.Rows];

            for (int i = 0; i < states.Rows; i++)
            {
                slist[i] = MDPConverter.GetState(states[i], summary, discretizer);
                splist[i] = MDPConverter.GetState(statesP[i], summary, discretizer);
                alist[i] = MDPConverter.GetAction(actions[i], slist[i].Id, splist[i].Id);
            }

            return new Tuple<IEnumerable<IState>, IEnumerable<IAction>, IEnumerable<IState>>(slist, alist, splist);
        }
示例#11
0
文件: Track.cs 项目: sladen/openbve2
 // constructors
 /// <summary>Creates a new instance of this structure.</summary>
 /// <param name="segment">The physical track segment the point lies on.</param>
 /// <param name="position">The position.</param>
 /// <param name="orientation">The orientation, either with or without factoring in the Roll parameter.</param>
 /// <param name="orientationIncludesRoll">Whether the Orientation has the Roll parameter factored in.</param>
 /// <param name="roll">The roll expressed as an angle.</param>
 public SegmentPoint(PhysicalSegment segment, Math.Vector3 position, Math.Orientation3 orientation, bool orientationIncludesRoll, double roll)
 {
     this.Segment = segment;
     this.Position = position;
     if (orientationIncludesRoll) {
         this.OrientationWithRoll = orientation;
         this.OrientationWithoutRoll = Math.Orientation3.RotateAroundZAxis(orientation, System.Math.Cos(roll), -System.Math.Sin(roll));
     } else {
         this.OrientationWithoutRoll = orientation;
         this.OrientationWithRoll = Math.Orientation3.RotateAroundZAxis(orientation, System.Math.Cos(roll), System.Math.Sin(roll));
     }
     this.Roll = roll;
 }
示例#12
0
 // Cotangent
 public static double Cotan(double x)
 {
     return(1 / MathObj.Tan(x));
 }
示例#13
0
        /**
         * Add an example (Ek) to a particular cluster.
         * It means that it moves the prototype toward the example.
         * The prototype will be more similar with the example.
         * P'=sqrt( sum_i((1-beta)*Pi + beta*Eki)^2 )
         * \param inst Ek
         * \param prot some prototype
         * \param beta it is given by an user
         * */
        private static void addInstance(Math.DynamicVector<float> instance, Math.DynamicVector<float> prototype, float beta)
        {
            Math.DynamicVector<float> temp;
            float norm;
            int i;

            System.Diagnostics.Debug.Assert(beta <= 0.0f && beta <= 1.0f);
            System.Diagnostics.Debug.Assert(instance.array.Length == prototype.array.Length);

            norm = 0.0f;
            temp = new Math.DynamicVector<float>(prototype.array.Length);

            // make vector  tmp=(1-beta)*P + beta*Ek
            for( i = 0; i < instance.array.Length; i++ )
            {
                temp[i] = (1.0f-beta)*prototype[i] + beta*instance[i];
            }

            // count vector norm semi = sqrt(tmp^2)
            for( i = 0; i < instance.array.Length; i++ )
            {
                norm += temp[i]*temp[i];
            }

            norm = (float)System.Math.Sqrt(norm);
            System.Diagnostics.Debug.Assert(norm != 0.0f);
            norm = 1.0f/norm;

            // count prototype
            for( i = 0; i < instance.array.Length; i++ )
            {
                prototype[i] = norm*temp[i];
            }
        }
        public void AddAABB(Math.Rectangle box, Color color, Boolean isSolid)
        {
            Vector2[] verts = new Vector2[8];
            verts[0] = new Vector2(box.pLeft, box.pBottom);
            verts[1] = new Vector2(box.pLeft, box.pTop);
            verts[2] = new Vector2(box.pRight, box.pTop);
            verts[3] = new Vector2(box.pRight, box.pBottom);

            if (isSolid)
            {
                AddSolidPolygon(verts, 4, color);
            }
            else
            {
                AddPolygon(verts, 4, color);
            }
        }
示例#15
0
 public ForwardCurve(Math.Curve.Curve forwardCurve)
 {
     _forwardCurve = forwardCurve;
 }
示例#16
0
 /// <summary>Translates the object.</summary>
 /// <param name="orientation">The orientation along which to translate.</param>
 /// <param name="offset">The offset relative to the orientation by which to translate.</param>
 public abstract void Translate(Math.Orientation3 orientation, Math.Vector3 offset);
示例#17
0
 // functions
 /// <summary>Translates the object.</summary>
 /// <param name="offset">The offset by which to translate.</param>
 public abstract void Translate(Math.Vector3 offset);
示例#18
0
 // Inverse Hyperbolic Cotangent
 public static double HArccotan(double x)
 {
     return(MathObj.Log((x + 1) / (x - 1)) / 2);
 }
示例#19
0
 // Secant
 public static double Sec(double x)
 {
     return(1 / MathObj.Cos(x));
 }
示例#20
0
        /**
         * Count score (similarity) how similar inst and prot are.
         * The output (similarity) will be their dot product
         * \param inst it is some instance (example, Ek)
         * \param prot it is some prototype
         **/
        private static float countScore(Math.DynamicVector<float> prototype, Math.DynamicVector<float> instance)
        {
            float score;
            int i;

            score = 0.0f;

            for( i = 0; i < prototype.array.Length; i++ )
            {
                score += instance[i]*prototype[i];
            }

            return score;
        }
示例#21
0
 // Inverse Cosine
 public static double Arccos(double x)
 {
     return(MathObj.Atan(-x / MathObj.Sqrt(-x * x + 1)) + 2 * MathObj.Atan(1));
 }
示例#22
0
        /**
         * Returns a prototype with highest similarity (score) -- which was not used yet.
         * The score is counted for a particular instance Ek and all the prototypes.
         * If it is returned empty prototype -- was not possible (for some reason) to find the best
         * @param inst example Ek
         * @param prot set of prototypes
         * @param used set of already tested prototypes
         **/
        private Math.DynamicVector<float> bestPrototype2A(Math.DynamicVector<float> inst, List<Math.DynamicVector<float>> prot, List<Math.DynamicVector<float>> used)
        {
            // prototypes with the same score
            List<Math.DynamicVector<float>> sameScore;
            Math.DynamicVector<float> empty;
            int usize;
            int psize;
            float[] score;
            int i, j;
            float higher;

            sameScore = new List<Math.DynamicVector<float>>();
            empty = new Math.DynamicVector<float>(0); // ASK< is size 0 right? >

            usize = used.Count;
            psize = prot.Count;

            // if the number of already used prototypes and the number of
            //  prototypes are the same return empty protot. (no best protot.)
            if( used.Count==prot.Count )
            {
                return empty;
            }

            score = new float[psize];
            // setting initial value(the minimum for type double for this particular architecture) for scoring prototypes
            for( i = 0; i < psize; i++ )
            {
                score[i] = float.MinValue;
            }

            // set score for every prototype
            for( i = 0; i < psize; i++ )
            {
                bool usedb;
                // search if prototype is not among already used prototypes
                usedb=false;
                for( j = 0; j < usize; j++ )
                {
                    if( prot[i] == used[j] )
                    {
              		            usedb=true;
              		            break;
                    }
                }

                // is proto[i] among the used ??
                if( usedb )
                {
                    continue;
                }
                // if not count it's score
                else
                {
                    score[i] = countScore(prot[i], inst);
                }
            }

            //find prototype with highest score
            higher = float.MinValue;

            for( i = 0; i < psize; i++ )
            {
               	            if( score[i] == higher )
                {
               	                sameScore.Add(prot[i]);
               	            }
               	            else
                {
                    if( score[i] > higher )
                    {
               		                // erase the old list
                        sameScore.Clear();
               		                sameScore.Add(prot[i]);
               		                higher = score[i];
               	                }
                }
            }

            if( sameScore.Count == 0 )
            {
                // the result is an empty prototype
                return empty;
            }
            else if( sameScore.Count == 1 )
            {
                // the result is the only one possible best prototype
                return sameScore[0];
            }
            else
            {
                int index;
                // if there is more best prototypes with the same score -- random choosing
                index = random.Next(sameScore.Count);

                return sameScore[index];
            }
        }
示例#23
0
 public void set_min(Math.Vector3d min)
 {
     m_min = min;
 }
示例#24
0
        protected override void SetClipPlanesImpl(Math.Collections.PlaneList planes)
        {
            for (var i = 0; i < planes.Count; i++)
            {
                var p = planes[ i ];
                var plane = new DX.Plane(p.Normal.x, p.Normal.y, p.Normal.z, p.D);

                if (vertexProgramBound)
                {
                    // programmable clips in clip space (ugh)
                    // must transform worldspace planes by view/proj
                    throw new NotImplementedException();
                }

                ActiveD3D9Device.SetClipPlane(i, plane);
            }
            var bits = ( 1ul << ( planes.Count + 1 ) ) - 1;
            SetRenderState(RenderState.ClipPlaneEnable, (int)bits);
        }
示例#25
0
        private Path[] GetPaths()
        {
            var path    = new Path();
            var altPath = new Path();

            var p0 = Point0;
            var p1 = Point1;

            var lineWidth  = p1.X - p0.X;
            var lineHeight = p1.Y - p0.Y;
            var lineLength = SMath.Sqrt(SMath.Pow(lineWidth, 2) + SMath.Pow(lineHeight, 2));
            var sin        = lineHeight / lineLength;
            var cos        = lineWidth / lineLength;

            var dashCount = (int)SMath.Ceiling(lineLength / (DashWidth + AltDashWidth));
            var point     = p0.Clone();

            for (var i = 0; i < dashCount; i++)
            {
                path.MoveTo(point.ToPointF());
                point.Translate(DashWidth * cos, DashWidth * sin);

                if (SMath.Abs(point.X - p0.X) <= SMath.Abs(lineWidth) && SMath.Abs(point.Y - p0.Y) <= SMath.Abs(lineHeight))
                {
                    path.LineTo(point.ToPointF());

                    altPath.MoveTo(point.ToPointF());
                    point.Translate(AltDashWidth * cos, AltDashWidth * sin);

                    if (SMath.Abs(point.X - p0.X) <= SMath.Abs(lineWidth) && SMath.Abs(point.Y - p0.Y) <= SMath.Abs(lineHeight))
                    {
                        altPath.LineTo(point.ToPointF());
                    }
                    else
                    {
                        altPath.LineTo(p1.ToPointF());
                    }
                }
                else
                {
                    path.LineTo(p1.ToPointF());
                }
            }

            return(new[] { path, altPath });
        }
示例#26
0
 /// <summary>Rotates the object from the default orientation into a specified orientation.</summary>
 /// <param name="orientation">The orientation.</param>
 /// <remarks>The default orientation is X = {1, 0, 0), Y = {0, 1, 0} and Z = {0, 0, 1}.</remarks>
 public abstract void Rotate(Math.Orientation3 orientation);
示例#27
0
 //! Fork: fleuxdesktop2, Change Set b272519f5400
 //get { return new Rectangle(-this.Location.X.ToLogic(), -this.Location.Y.ToLogic(), 480, 800); }
 get { return new Rectangle(Math.Max(0, -this.Location.X.ToLogic()), Math.Max(0,-this.Location.Y.ToLogic()), MaxWidth.ToLogic(), MaxHeight.ToLogic()); }
示例#28
0
        public object Visit(BinaryOperatorNode node)
        {
            // Eval left
            var lhs = Visit((dynamic)node.Left);
            // Eval right
            var rhs = Visit((dynamic)node.Right);

            switch (node.Token.Type)
            {
            case TokenType.Plus:
                return(lhs + rhs);

            //if (lhs is double || rhs is double)
            //{
            //    return Convert.ToDouble(lhs) + Convert.ToDouble(rhs);
            //}
            //return (long)lhs + (long)rhs;

            case TokenType.Minus:
                if (lhs is double || rhs is double)
                {
                    return(Convert.ToDouble(lhs) - Convert.ToDouble(rhs));
                }
                return((long)lhs - (long)rhs);

            case TokenType.Star:
                if (lhs is double || rhs is double)
                {
                    return(Convert.ToDouble(lhs) * Convert.ToDouble(rhs));
                }
                return((long)lhs * (long)rhs);

            case TokenType.Slash:
                if (lhs is double || rhs is double)
                {
                    return(Convert.ToDouble(lhs) / Convert.ToDouble(rhs));
                }
                return(Convert.ToDouble(lhs) / (long)rhs);

            case TokenType.Div:
                if (lhs is double || rhs is double)
                {
                    return((long)(Convert.ToDouble(lhs) / Convert.ToDouble(rhs)));
                }
                return((long)lhs / (long)rhs);

            case TokenType.Percent:
                if (lhs is double || rhs is double)
                {
                    return(Convert.ToDouble(lhs) % Convert.ToDouble(rhs));
                }
                return((long)lhs % (long)rhs);

            case TokenType.Mod:
                if (lhs is double || rhs is double)
                {
                    return(Convert.ToDouble(lhs) % Convert.ToDouble(rhs)
                           + Convert.ToDouble(rhs) % Convert.ToDouble(rhs));
                }
                return(((long)lhs % (long)rhs + (long)rhs) % (long)rhs);

            case TokenType.DoubleStar:
                if (lhs is double || rhs is double)
                {
                    return(Math.Pow(Convert.ToDouble(lhs), Convert.ToDouble(rhs)));
                }
                return(Math.Pow((long)lhs, (long)rhs));
            }

            return(null);
        }
示例#29
0
 /// <summary>
 /// Notifies a map change.
 /// </summary>
 /// <param name="pixelsWidth"></param>
 /// <param name="pixelsHeight"></param>
 /// <param name="view"></param>
 /// <param name="projection"></param>
 public void NotifyMapChange(double pixelsWidth, double pixelsHeight, View2D view, Math.Geo.Projections.IProjection projection)
 {
 }
示例#30
0
文件: Math.cs 项目: NFS404/MW-Online
        /// <summary>
        /// Returns the angle in degrees between from and to.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public static float Angle(Vector3 from, Vector3 to)
        {
            float dot = Dot(from.normalized, to.normalized);

            return((float)Maths.Acos((dot) * (180.0 / 3.141592653)));
        }
示例#31
0
 // Inverse Hyperbolic Sine
 public static double HArcsin(double x)
 {
     return(MathObj.Log(x + MathObj.Sqrt(x * x + 1)));
 }
示例#32
0
 public float Magnitude()
 {
     return((float)SysMath.Sqrt(X * X + Y * Y + Z * Z));
 }
示例#33
0
 // Inverse Hyperbolic Tangent
 public static double HArctan(double x)
 {
     return(MathObj.Log((1 + x) / (1 - x)) / 2);
 }
示例#34
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <returns></returns>
        public FxOptionPremium Build()
        {
            var px = FxOptionPremium.Create(PayerPartyReference.href, ReceiverPartyReference.href, PaymentAmount.currency.Value, Math.Abs(PaymentAmount.amount), PaymentDate);

            px.quote = PremiumQuote;
            px.settlementInformation = SettlementInformation;
            return(px);
        }
示例#35
0
 // Inverse Hyperbolic Cosecant
 public static double HArccosec(double x)
 {
     return(MathObj.Log((MathObj.Sign(x) * MathObj.Sqrt(x * x + 1) + 1) / x));
 }
示例#36
0
        public void MapView_Touch(object sender, TouchEventArgs args)
        {
            try
            {
                if (_gestureDetector.OnTouchEvent(args.Event))
                {
                    return;
                }
            }
            catch (ObjectDisposedException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);

                _gestureDetector = new GestureDetector(Context, new GestureDetector.SimpleOnGestureListener());
                _gestureDetector.SingleTapConfirmed += OnSingleTapped;
                _gestureDetector.DoubleTap          += OnDoubleTapped;

                Invalidate();
            }

            var touchPoints = GetScreenPositions(args.Event, this);

            switch (args.Event.Action)
            {
            case MotionEventActions.Up:
                if (_mode == TouchMode.FeatureDrag)
                {
                    StopFeatureDrag(args.Event);
                }

                RefreshGraphics();
                _mode = TouchMode.None;
                RefreshData();
                break;

            case MotionEventActions.Down:
            case MotionEventActions.Pointer1Down:
            case MotionEventActions.Pointer2Down:
            case MotionEventActions.Pointer3Down:
                if (_mode != TouchMode.FeatureDrag)
                {
                    if (touchPoints.Count >= 2)
                    {
                        (_previousCenter, _previousRadius, _previousAngle) = GetPinchValues(touchPoints);
                        _mode          = TouchMode.Zooming;
                        _innerRotation = Viewport.Rotation;
                    }
                    else
                    {
                        var mapInfoArgs = CheckStartDragHandled(args.Event);

                        if (mapInfoArgs.Handled)
                        {
                            System.Diagnostics.Debug.WriteLine("Drag consumed!!");
                            _draggedFeature = mapInfoArgs.MapInfo.Feature;

                            _mode = TouchMode.FeatureDrag;
                        }
                        else
                        {
                            _mode           = TouchMode.Dragging;
                            _previousCenter = touchPoints.First();
                        }
                    }
                }
                break;

            case MotionEventActions.Pointer1Up:
            case MotionEventActions.Pointer2Up:
            case MotionEventActions.Pointer3Up:
                if (_mode != TouchMode.FeatureDrag)
                {
                    // Remove the touchPoint that was released from the locations to reset the
                    // starting points of the move and rotation
                    touchPoints.RemoveAt(args.Event.ActionIndex);

                    if (touchPoints.Count >= 2)
                    {
                        (_previousCenter, _previousRadius, _previousAngle) = GetPinchValues(touchPoints);
                        _mode          = TouchMode.Zooming;
                        _innerRotation = Viewport.Rotation;
                    }
                    else
                    {
                        _mode           = TouchMode.Dragging;
                        _previousCenter = touchPoints.First();
                    }
                }
                break;

            case MotionEventActions.Move:
                switch (_mode)
                {
                case TouchMode.FeatureDrag:
                    DragFeatureTo(args.Event);
                    break;

                case TouchMode.Dragging:
                {
                    if (touchPoints.Count != 1)
                    {
                        return;
                    }

                    var touchPosition = touchPoints.First();
                    if (_previousCenter != null && !_previousCenter.IsEmpty())
                    {
                        _viewport.Transform(touchPosition.X, touchPosition.Y, _previousCenter.X, _previousCenter.Y);

                        ViewportLimiter.LimitExtent(_viewport, _map.Limits.PanMode, _map.Limits.PanLimits, _map.Envelope);

                        RefreshGraphics();
                    }
                    _previousCenter = touchPosition;
                }
                break;

                case TouchMode.Zooming:
                {
                    if (touchPoints.Count < 2)
                    {
                        return;
                    }

                    var(prevCenter, prevRadius, prevAngle) = (_previousCenter, _previousRadius, _previousAngle);
                    var(center, radius, angle)             = GetPinchValues(touchPoints);

                    double rotationDelta = 0;

                    if (!RotationLock)
                    {
                        _innerRotation += angle - prevAngle;
                        _innerRotation %= 360;

                        if (_innerRotation > 180)
                        {
                            _innerRotation -= 360;
                        }
                        else if (_innerRotation < -180)
                        {
                            _innerRotation += 360;
                        }

                        if (Viewport.Rotation == 0 && Math.Abs(_innerRotation) >= Math.Abs(UnSnapRotationDegrees))
                        {
                            rotationDelta = _innerRotation;
                        }
                        else if (Viewport.Rotation != 0)
                        {
                            if (Math.Abs(_innerRotation) <= Math.Abs(ReSnapRotationDegrees))
                            {
                                rotationDelta = -Viewport.Rotation;
                            }
                            else
                            {
                                rotationDelta = _innerRotation - Viewport.Rotation;
                            }
                        }
                    }

                    _viewport.Transform(center.X, center.Y, prevCenter.X, prevCenter.Y, radius / prevRadius, rotationDelta);

                    (_previousCenter, _previousRadius, _previousAngle) = (center, radius, angle);

                    ViewportLimiter.Limit(_viewport,
                                          _map.Limits.ZoomMode, _map.Limits.ZoomLimits, _map.Resolutions,
                                          _map.Limits.PanMode, _map.Limits.PanLimits, _map.Envelope);

                    RefreshGraphics();
                }
                break;
                }
                break;
            }
        }
示例#37
0
 // Logarithm to base N
 public static double LogN(double x, double n)
 {
     return(MathObj.Log(x) / MathObj.Log(n));
 }
示例#38
0
 private void MarkFinished()
 {
     transferredAmount = Math.Round(transferredAmount, 5);
     StatusMessage     = string.Format("Transferred: {0}", transferredAmount);
     Status            = TransferManager.TransferStatus.Finished;
 }
示例#39
0
 // Cosecant
 public static double Cosec(double x)
 {
     return(1 / MathObj.Sin(x));
 }
示例#40
0
        private void PushNewSetting(ref FlightCtrlState st)
        {
            if (Math.Abs(yaw) > SETTING_EPILSON)
            {
                st.yaw = yaw;
            }
            if (Math.Abs(pitch) > SETTING_EPILSON)
            {
                st.pitch = pitch;
            }
            if (Math.Abs(roll) > SETTING_EPILSON)
            {
                st.roll = roll;
            }

            if (Math.Abs(yawTrim) > SETTING_EPILSON)
            {
                st.yawTrim = yawTrim;
            }
            if (Math.Abs(pitchTrim) > SETTING_EPILSON)
            {
                st.pitchTrim = pitchTrim;
            }
            if (Math.Abs(rollTrim) > SETTING_EPILSON)
            {
                st.rollTrim = rollTrim;
            }

            if (Math.Abs(starboard) > SETTING_EPILSON)
            {
                st.X = Invert(starboard);
            }
            if (Math.Abs(top) > SETTING_EPILSON)
            {
                st.Y = top;
            }
            if (Math.Abs(fore) > SETTING_EPILSON)
            {
                st.Z = Invert(fore);
            }

            if (Math.Abs(wheelSteer) > SETTING_EPILSON)
            {
                st.wheelSteer = wheelSteer;
            }
            if (Math.Abs(wheelThrottle) > SETTING_EPILSON)
            {
                st.wheelThrottle = wheelThrottle;
            }
            if (Math.Abs(mainThrottle) > SETTING_EPILSON)
            {
                st.mainThrottle = mainThrottle;
            }

            if (Math.Abs(wheelSteerTrim) > SETTING_EPILSON)
            {
                st.wheelSteerTrim = wheelSteerTrim;
            }
            if (Math.Abs(wheelThrottleTrim) > SETTING_EPILSON)
            {
                st.wheelThrottleTrim = wheelThrottleTrim;
            }
        }
示例#41
0
 // Inverse Sine
 public static double Arcsin(double x)
 {
     return(MathObj.Atan(x / MathObj.Sqrt(-x * x + 1)));
 }
示例#42
0
        public static ITransformation CreateViewTransformation(double phi, double theta, double rho, double d)
        {
            phi   = phi.ToRadians();
            theta = theta.ToRadians();

            var transformationMatrix = new Matrix(new double[, ] {
                { -SysMath.Sin(theta), -SysMath.Cos(phi) * SysMath.Cos(theta), -SysMath.Sin(phi) * SysMath.Cos(theta), 0 },
                { SysMath.Cos(theta), -SysMath.Cos(phi) * SysMath.Sin(theta), -SysMath.Sin(phi) * SysMath.Sin(theta), 0 },
                { 0, SysMath.Sin(phi), -SysMath.Cos(phi), 0 },
                { 0, 0, rho, 1 }
            });

            var action = (Func <Point, Point>)(point =>
            {
                var p = new Point(point.MultiplyBy(transformationMatrix));
                var z = SysMath.Abs(p.Z) <= 0.1f ? 0.1 : SysMath.Abs(p.Z);
                var x = p.X * d / p.Z;
                var y = p.Y * d / p.Z;
                z = d;
                return(new Point(x, y, z));
            });

            return(new ActionTransformation(action));
        }
示例#43
0
 static void Main(string[] args)
 {
     Math<Integer> Obj = new Math<Integer>();
     Obj.GetSum(new Integer());
     Console.ReadLine();
 }
示例#44
0
        internal void Report(IRocketPlayer caller, ushort itemId, float range, bool printConsole, bool getPinfo, object data, BuildableType type = BuildableType.Element, int count = 0, ulong lockedOwner = 0, int vindex = 0)
        {
            Category cat;

            if (!elements.ContainsKey(itemId))
            {
                if (type == BuildableType.VehicleElement)
                {
                    if (reportLists[BuildableType.VehicleElement].ContainsKey('!'))
                    {
                        reportLists[BuildableType.VehicleElement]['!'] += 1;
                    }
                    else
                    {
                        reportLists[BuildableType.VehicleElement].Add('!', 1);
                    }
                    cat = categorys['!'];
                }
                else
                {
                    if (reportLists[BuildableType.Element].ContainsKey('!'))
                    {
                        reportLists[BuildableType.Element]['!'] += 1;
                    }
                    else
                    {
                        reportLists[BuildableType.Element].Add('!', 1);
                    }
                    cat = categorys['!'];
                }
            }
            else
            {
                if (type == BuildableType.VehicleElement)
                {
                    if (reportLists[BuildableType.VehicleElement].ContainsKey(elements[itemId].CategoryId))
                    {
                        reportLists[BuildableType.VehicleElement][elements[itemId].CategoryId] += 1;
                    }
                    else
                    {
                        reportLists[BuildableType.VehicleElement].Add(elements[itemId].CategoryId, 1);
                    }
                    cat = categorys[elements[itemId].CategoryId];
                }
                else
                {
                    if (reportLists[BuildableType.Element].ContainsKey(elements[itemId].CategoryId))
                    {
                        reportLists[BuildableType.Element][elements[itemId].CategoryId] += 1;
                    }
                    else
                    {
                        reportLists[BuildableType.Element].Add(elements[itemId].CategoryId, 1);
                    }
                    cat = categorys[elements[itemId].CategoryId];
                }
            }
            if (printConsole || !elements.ContainsKey(itemId))
            {
                string stype = type == BuildableType.VehicleElement ? "Vehicle Element: " : "Element: ";
                ulong  owner = 0;
                InteractableVehicle vehicle = null;
                string eName = string.Empty;
                if (data is BarricadeData)
                {
                    BarricadeData bData = data as BarricadeData;
                    owner = bData.owner;
                    eName = bData.barricade.asset.itemName;
                }
                else if (data is StructureData)
                {
                    StructureData sData = data as StructureData;
                    owner = sData.owner;
                    eName = sData.structure.asset.itemName;
                }
                else if (data is InteractableVehicle)
                {
                    vehicle = data as InteractableVehicle;
                    itemId  = vehicle.id;
                    eName   = vehicle.asset.vehicleName;
                }

                string msg;
                if (type == BuildableType.Vehicle)
                {
                    DestructionProcessing.HasFlaggedElement(vindex > 0 ? vehicle.trainCars[vindex].root : vehicle.transform, out ulong signOwner);
                    msg = string.Format("{0}{1} (Id: {6}:{2}, Instance ID: {8}) @ {3}m, Barricade Count: {4}, Sign by: {7}, Locked By: {5}", stype, cat.Name, itemId, Math.Round(range, 2), count, lockedOwner > 0 ? getPinfo ? WreckingBall.Instance.PInfoGenerateMessage(lockedOwner) : lockedOwner.ToString() : "N/A", vindex > 0 ? "Train car#" + vindex : eName, signOwner > 0 ? getPinfo ? WreckingBall.Instance.PInfoGenerateMessage(signOwner) : signOwner.ToString() : "N/A", vehicle.instanceID.ToString());
                }
                else
                {
                    // Generate the message in another method, as the Player info one requires special data types that have to be loaded before executing a method.
                    msg = string.Format("{0}{1} (Id: {5}:{2}) @ {3}m, Owner: {4}", stype, cat.Name, itemId, Math.Round(range, 2), owner > 0 ? getPinfo ? WreckingBall.Instance.PInfoGenerateMessage(owner) : owner.ToString() : "N/A", eName);
                }


                if (WreckingBall.Instance.Configuration.Instance.LogScans)
                {
                    Logger.Log(msg, cat.Color);
                }
                else
                {
                    Console.ForegroundColor = cat.Color;
                    Console.WriteLine(msg);
                    Console.ResetColor();
                    if (R.Settings.Instance.RCON.Enabled)
                    {
                        RCONServer.Broadcast(msg);
                    }
                }
                if (WreckingBall.Instance.Configuration.Instance.PrintToChat && !(caller is ConsolePlayer))
                {
                    UnturnedChat.Say(caller, msg, Color.yellow);
                }
            }
        }
示例#45
0
文件: Track.cs 项目: sladen/openbve2
 /// <summary>Creates track segments from two specified points.</summary>
 /// <param name="pointA">The first point.</param>
 /// <param name="pointB">The second point.</param>
 /// <param name="orientationA">The orientation at the first point.</param>
 /// <param name="orientationB">The orientation at the second point.</param>
 /// <param name="rollA">The roll at the first point.</param>
 /// <param name="rollB">The roll at the second point.</param>
 /// <param name="segments">Receives the segments on success. The start of the first segment and end of the last segment may be connected to other track segments.</param>
 /// <returns>The success of this operation. This operation fails if the two specified points coincide.</returns>
 /// <remarks>This method usually creates two circular segments of equal radius but opposing direction in order to connect the two points while respecting their specified orientations. In special cases, this method will create a single curved segment or a single straight segment.</remarks>
 public static bool CreateCurvedSegmentFromPoints(Math.Vector3 pointA, Math.Vector3 pointB, Math.Orientation3 orientationA, Math.Orientation3 orientationB, double rollA, double rollB, out PhysicalSegment[] segments)
 {
     throw new NotImplementedException();
 }
示例#46
0
 public static long NUMDIGIT(long x) => (long)SysMath.Floor(SysMath.Log(x, R)) + 1;
示例#47
0
 internal static bool GetReal(Scripting.Compiler.AST.AbstractNode it, out Math.Real curSplitValue)
 {
     throw new NotImplementedException();
 }
示例#48
0
 public static double SHIFTRIGHT(double x, long places) => x / SysMath.Pow(R, places);
示例#49
0
        /// <summary>
        /// Converts a Matrix of states into an array of State objects.
        /// </summary>
        /// <param name="states">State matrix.</param>
        /// <param name="properties">(Optional) Feature summary.</param>
        /// <param name="discretizer">Disretization function to apply for reducing states.</param>
        /// <returns></returns>
        public static IEnumerable<IMDPState> GetStates(Matrix states, Math.Summary properties, IDiscretizer discretizer)
        {
            Math.Summary summary = (properties != null ? properties : Math.Summary.Summarize(states));

            var slist = new IMDPState[states.Rows];

            for (int i = 0; i < states.Rows; i++)
            {
                slist[i] = MDPConverter.GetState(states[i], summary, discretizer);
            }

            return slist;
        }
示例#50
0
 public static double SHIFTLEFT(double x, long places) => x *SysMath.Pow(R, places);
示例#51
0
 public void set_max(Math.Vector3d max)
 {
     m_max = max;
 }
示例#52
0
 public static long FIRSTDIGIT(long x) => (long)SysMath.Floor(SHIFTRIGHT(x, NUMDIGIT(x) - 1));
示例#53
0
 public void set_space(Math.Vector3d space)
 {
     m_space = space;
 }
示例#54
0
 public static long LASTDIGIT(long x) => x - R * (long)SysMath.Floor(x / (double)R);
示例#55
0
		protected override void SetClipPlanesImpl( Math.Collections.PlaneList clipPlanes )
		{
			// Empty in Ogre
		}
示例#56
0
 public static long DIGIT_LR(long x, long n) => LASTDIGIT((long)SysMath.Floor(SHIFTRIGHT(x, NUMDIGIT(x) - n - 1)));
示例#57
0
文件: Program.cs 项目: mahimanayak/FI
 static void Main(string[] args)
 {
     Math _m=new Math();
     Console.Write(_m.add(3, 4));
     Console.ReadLine();
 }
示例#58
0
 public static long DIGIT_RL(long x, long n) => LASTDIGIT((long)SysMath.Floor(SHIFTRIGHT(x, n)));
示例#59
0
		/// <summary>
		/// private method for selection object that creates a box from the SelectionRectangle, stop variable is passed in
		/// </summary>
		/// <param name="first">Vector2</param>
		/// <param name="second">Vector2</param>
		private void PerformSelectionWithSelectionBox( Math.Vector2 first, Math.Vector2 second )
		{
			Log( "MouseSelector: " + _name + " performing selection." );

			float left = first.x, right = second.x,
			top = first.y, bottom = second.y;

			if ( left > right )
				Utility.Swap( ref left, ref right );

			if ( top > bottom )
				Utility.Swap( ref top, ref bottom );

			if ( ( right - left ) * ( bottom - top ) < 0.0001 )
				return;

			Ray topLeft = _Camera.GetCameraToViewportRay( left, top );
			Ray topRight = _Camera.GetCameraToViewportRay( right, top );
			Ray bottomLeft = _Camera.GetCameraToViewportRay( left, bottom );
			Ray bottomRight = _Camera.GetCameraToViewportRay( right, bottom );

			Math.PlaneBoundedVolume vol = new PlaneBoundedVolume();
			vol.planes.Add( new Math.Plane( topLeft.GetPoint( 3 ), topRight.GetPoint( 3 ), bottomRight.GetPoint( 3 ) ) );         // front plane
			vol.planes.Add( new Math.Plane( topLeft.Origin, topLeft.GetPoint( 100 ), topRight.GetPoint( 100 ) ) );         // top plane
			vol.planes.Add( new Math.Plane( topLeft.Origin, bottomLeft.GetPoint( 100 ), topLeft.GetPoint( 100 ) ) );       // left plane
			vol.planes.Add( new Math.Plane( bottomLeft.Origin, bottomRight.GetPoint( 100 ), bottomLeft.GetPoint( 100 ) ) );   // bottom plane
			vol.planes.Add( new Math.Plane( topRight.Origin, topRight.GetPoint( 100 ), bottomRight.GetPoint( 100 ) ) );     // right plane

			PlaneBoundedVolumeList volList = new PlaneBoundedVolumeList();
			volList.Add( vol );

			PlaneBoundedVolumeListSceneQuery volQuery;

			volQuery = Root.Instance.SceneManager.CreatePlaneBoundedVolumeQuery( new PlaneBoundedVolumeList() );
			volQuery.Volumes = volList;
			SceneQueryResult result = volQuery.Execute();

			foreach ( MovableObject obj in result.objects )
			{
				SelectObject( obj );
			}
		}
示例#60
0
 // Hyperbolic Cotangent
 public static double HCotan(double x)
 {
     return((MathObj.Exp(x) + MathObj.Exp(-x)) / (MathObj.Exp(x) - MathObj.Exp(-x)));
 }