Esempio n. 1
0
        /// <summary>
        /// Constructs a <see cref="Xenon.Math.BoundingSphere"/> that is the as large as the total combined area of the two specified spheres.
        /// </summary>
        /// <param name="value1">The first sphere to merge.</param>
        /// <param name="value2">The second sphere to merge.</param>
        /// <param name="result">When the method completes, contains the newly constructed bounding sphere.</param>
        public static void Merge(ref BoundingSphere value1, ref BoundingSphere value2, out BoundingSphere result)
        {
            Vector3 difference = value2.Center - value1.Center;

            float length  = difference.Length;
            float radius  = value1.Radius;
            float radius2 = value2.Radius;

            if (radius + radius2 >= length)
            {
                if (radius - radius2 >= length)
                {
                    result = value1;
                    return;
                }

                if (radius2 - radius >= length)
                {
                    result = value2;
                    return;
                }
            }

            Vector3 vector = difference * (1.0f / length);
            float   min    = SMath.Min(-radius, length - radius2);
            float   max    = (SMath.Max(radius, length + radius2) - min) * 0.5f;

            result.Center = value1.Center + vector * (max + min);
            result.Radius = max;
        }
Esempio n. 2
0
        public static void SetWater(MapData[,] heightMap, Vector2 pos, WaterType waterType)
        {
            int x = Math.Max(Math.Min((int)pos.X, heightMap.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, heightMap.GetLength(1) - 1), 0);

            heightMap[x, y].Water = waterType;
        }
Esempio n. 3
0
 /// <summary>
 /// Implements the - operator.
 /// </summary>
 /// <param name="point1">The point1.</param>
 /// <param name="point2">The point2.</param>
 /// <returns>The result of the operator.</returns>
 public static Offset3D operator -(Point3D point1, Point3D point2)
 {
     return(new Offset3D(
                point1,
                point2,
                NMath.Min(point1.Tolerance, point2.Tolerance)));
 }
Esempio n. 4
0
        public static float GetHeight(float[,] heightMap, Vector2 pos)
        {
            int x = Math.Max(Math.Min((int)pos.X, heightMap.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, heightMap.GetLength(1) - 1), 0);

            return(heightMap[x, y]);
        }
Esempio n. 5
0
        public static WaterType GetWater(MapData[,] map, Vector2 pos)
        {
            int x = Math.Max(Math.Min((int)pos.X, map.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, map.GetLength(1) - 1), 0);

            return(map[x, y].Water);
        }
Esempio n. 6
0
        public static byte[] Render(Scene scene, byte[] pixels)
        {
            var eye = Vec3.Zero;
            Num h   = MATH.Tan(((fov / 360) * (2 * PI)) / 2) * 2;
            Num w   = (h * Width) / Height;

            for (int y = 0; y != Height; ++y)
            {
                for (int x = 0; x != Width; ++x)
                {
                    Num  xx = x, yy = y, ww = Width, hh = Height;
                    Vec3 dir;
                    dir.X = ((xx - (ww / 2.0f)) / ww) * w;
                    dir.Y = (((hh / 2.0f) - yy) / hh) * h;
                    dir.Z = -1.0f;
                    dir   = Vec3.Normalize(dir);

                    Ray r;
                    r.Org = eye;
                    r.Dir = dir;
                    var pixel = trace(r, scene, 0);
                    int i     = (x * 3) + (y * Width * 3);
                    pixels[i]     = (byte)MATH.Min(pixel.X * 255, 255);
                    pixels[i + 1] = (byte)MATH.Min(pixel.Y * 255, 255);
                    pixels[i + 2] = (byte)MATH.Min(pixel.Z * 255, 255);
                }
            }

            return(pixels);
        }
Esempio n. 7
0
 /// <summary>
 /// Implements the + operator.
 /// </summary>
 /// <param name="point1">The point1.</param>
 /// <param name="point2">The point2.</param>
 /// <returns>The result of the operator.</returns>
 public static Point operator +(Offset point1, Point point2)
 {
     return(new Point(
                point1.X() + point2.X,
                point1.Y() + point2.Y,
                NMath.Min(point1.Tolerance, point2.Tolerance)));
 }
Esempio n. 8
0
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        public bool Equals(PolarOffset other)
        {
            double tolerance = NMath.Min(Tolerance, other.Tolerance);

            return(Radius().IsEqualTo(other.Radius(), tolerance) &&
                   Azimuth().Radians.IsEqualTo(other.Azimuth().Radians, tolerance));
        }
Esempio n. 9
0
        private IEnumerable <Task> ScheduleJobs(float deltaTime, Task inputDeps)
        {
            ReadOnlyMemory <PositionComponent> allPositions = this.positionComponents;

            //Velocity to be modified
            ReadOnlyMemory <PositionComponent>           positions           = allPositions.Slice(0, this.length);
            ReadOnlyMemory <VelocityConstraintComponent> velocityConstraints = this.constraintComponents.Slice(0, this.length);
            Memory <VelocityComponent> velocities = this.velocityComponents.Slice(0, this.length);

            //Velocity modifier data
            ReadOnlyMemory <VelocityModifierComponent> modifiers         = this.modifierComponents;
            ReadOnlyMemory <PositionComponent>         modifierPositions = allPositions.Slice(this.length);
            ReadOnlyMemory <SizeComponent>             modifierSizes     = this.sizeComponents;

            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                var startIndex  = i * this.sliceLength;
                var sliceLength = Math.Min(this.sliceLength, this.length - startIndex);

                var positionsSlice           = positions.Slice(startIndex, sliceLength);
                var velocityConstraintsSlice = velocityConstraints.Slice(startIndex, sliceLength);
                var velocitiesSlice          = velocities.Slice(startIndex, sliceLength);
                yield return(inputDeps.ContinueWith((x) => RunJob(
                                                        deltaTime,
                                                        sliceLength,
                                                        this.modifierLength,
                                                        positionsSlice,
                                                        velocityConstraintsSlice,
                                                        velocitiesSlice,
                                                        modifiers,
                                                        modifierPositions,
                                                        modifierSizes)));
            }
        }
Esempio n. 10
0
        public static Bitmap ResizeBitmapFromUri(this Uri uri, int newWidth, int newHeight)
        {
            try
            {
                var bmOptions = new BitmapFactory.Options {
                    InJustDecodeBounds = true
                };
                BitmapFactory.DecodeFile(uri.EncodedPath, bmOptions);
                var photoW      = bmOptions.OutWidth;
                var photoH      = bmOptions.OutHeight;
                var scaleFactor = 1;

                if ((newWidth > 0) || (newHeight > 0))
                {
                    scaleFactor = Math.Min(photoW / newWidth, photoH / newHeight);
                }

                bmOptions.InJustDecodeBounds = false;
                bmOptions.InSampleSize       = scaleFactor;
                bmOptions.InPurgeable        = true;
                return(BitmapFactory.DecodeFile(uri.EncodedPath, bmOptions));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 11
0
    private static void Transfer(Socket socket)
    {
        int txDataLen = random.Next(maxDataLen);
        int rxDataLen;

        TransferHeaders(socket, txDataLen, out rxDataLen);
        // System.Console.WriteLine ("txDataLen="+txDataLen+" rxDataLen="+rxDataLen);
        socket.Blocking = false;
        socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
        // Disable the Nagle algorithm for send coalescing.
        int txPos = 0;
        int rxPos = 0;

        while (txPos < txDataLen || rxPos < rxDataLen)
        {
            // System.Console.WriteLine ("txPos="+txPos+"/"+txDataLen+" rxPos="+rxPos+"/"+rxDataLen);
            int txReqLen = Math.Min(txDataLen - txPos, 1 + random.Next(maxBlockLen));
            int txTrLen  = Send(socket, txReqLen);
            txPos += txTrLen;
            int rxReqLen = Math.Min(rxDataLen - rxPos, maxBlockLen);
            int rxTrLen  = Receive(socket, rxReqLen);
            rxPos += rxTrLen;
            if (random.Next(1000) == 0)
            {
                Thread.Sleep(50);
            }
            else if ((txTrLen < txReqLen && rxTrLen < rxReqLen) || random.Next(50) == 0)
            {
                Thread.Sleep(1);
            }
        }
        socket.Shutdown(SocketShutdown.Both);
    }
Esempio n. 12
0
        // Takes Hue value as input, returns RGB vector.
        // Copied from POV-Ray
        public static Vector3D CH2RGB(double H)
        {
            double R = 0, G = 0, B = 0;

            if (H >= 0 && H < 120)
            {
                R = (120 - H) / 60;
                G = (H - 0) / 60;
                B = 0;
            }
            else if (H >= 120 && H < 240)
            {
                R = 0;
                G = (240 - H) / 60;
                B = (H - 120) / 60;
            }
            else if (H >= 240 && H <= 360)
            {
                R = (H - 240) / 60;
                G = 0;
                B = (360 - H) / 60;
            }

            return(new Vector3D(
                       Math.Min(R, 1),
                       Math.Min(G, 1),
                       Math.Min(B, 1)));
        }
Esempio n. 13
0
            static public SkryptObject Min(SkryptObject[] Values)
            {
                var a = TypeConverter.ToNumeric(Values, 0);
                var b = TypeConverter.ToNumeric(Values, 1);

                return((Numeric)SysMath.Min(a, b));
            }
Esempio n. 14
0
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        public bool Equals(CartesianCoordinate other)
        {
            double tolerance = NMath.Min(Tolerance, other.Tolerance);

            return(X.IsEqualTo(other.X, tolerance) &&
                   Y.IsEqualTo(other.Y, tolerance));
        }
        /// <summary>
        /// Requests the resource from all parts in the collection
        /// </summary>
        /// <param name="parts">All of the donor parts</param>
        /// <param name="transferGoal">the aggregate amount we are seeking to remove from parts</param>
        /// <returns>the amount we were successful at pulling</returns>
        private double PullResources(IList <global::Part> parts, double transferGoal, double deltaTime)
        {
            double toReturn           = 0.0;
            var    availableResources = CalculateAvailableResource(parts);

            foreach (var part in parts)
            {
                var resource = part.Resources.Get(resourceInfo.id);
                if (resource == null)
                {
                    continue;
                }

                var thisPartsPercentage = resource.amount / availableResources;

                // Throttle the transfer
                var thisPartsShare = transferGoal * thisPartsPercentage;
                var thisPartsRate  = resource.maxAmount * RESOURCE_SHARE_PER_UPDATE * deltaTime / 0.02;

                // The amount you pull must be negative
                thisPartsShare = -Math.Min(thisPartsShare, thisPartsRate);
                // the amount is subject to floating point lameness, if we round it here it is not material to the request but should make the numbers work out nicer.
                thisPartsShare = Math.Round(thisPartsShare, 5);

                toReturn += part.TransferResource(resourceInfo.id, thisPartsShare);
            }
            return(toReturn);
        }
Esempio n. 16
0
        public void SetPosition2(IntFloatVector2 pos)
        {
            var x    = pos.X.Integer * 2 + 1;
            var y    = pos.Y.Integer * 2 + 1;
            var oldX = Position.X.Integer * 2 + 1;
            var oldY = Position.Y.Integer * 2 + 1;

            Position = pos;

            // for slice updates we are only interested in the integer part
            if (x == oldX && y == oldY)
            {
                return;
            }

            if (y > oldY)
            {
                UpdateRows((_n - oldY) & _n, Math.Min((y - oldY), _n));
            }
            else if (oldY > y)
            {
                UpdateRows((_n - y) & _n, Math.Min((oldY - y), _n));
            }

            if (x > oldX)
            {
                UpdateColumns((_n - oldX) & _n, Math.Min((x - oldX), _n));
            }
            else if (oldX > x)
            {
                UpdateColumns((_n - x) & _n, Math.Min((oldX - x), _n));
            }
        }
Esempio n. 17
0
    private float IntersectionOverUnion(Rect boundingBoxA, Rect boundingBoxB)
    {
        var areaA = boundingBoxA.width * boundingBoxA.height;

        if (areaA <= 0)
        {
            return(0);
        }

        var areaB = boundingBoxB.width * boundingBoxB.height;

        if (areaB <= 0)
        {
            return(0);
        }

        var minX = Math.Max(boundingBoxA.xMin, boundingBoxB.xMin);
        var minY = Math.Max(boundingBoxA.yMin, boundingBoxB.yMin);
        var maxX = Math.Min(boundingBoxA.xMax, boundingBoxB.xMax);
        var maxY = Math.Min(boundingBoxA.yMax, boundingBoxB.yMax);

        var intersectionArea = Math.Max(maxY - minY, 0) * Math.Max(maxX - minX, 0);

        return(intersectionArea / (areaA + areaB - intersectionArea));
    }
Esempio n. 18
0
        public Move ComputeMove(Position dest)
        {
            var move = new Move
            {
                Pos = new Position
                {
                    X = dest.X - this.Speed.Vx,
                    Y = dest.Y - this.Speed.Vy
                }
            };

            // Acc
            var dist = this.Pos.Dist(move.Pos);

            if (Math.Abs(dist) <= 0.0001)
            {
                return(move);
            }

            //var expectedVx = Math.Abs(move.Pos.X - this.Pos.X) / (1 - this.Friction);
            //var expectedVy = Math.Abs(move.Pos.Y - this.Pos.Y) / (1 - this.Friction);

            //var accX = (int)Math.Round(expectedVx * dist * this.Mass);
            //var accY = (int)Math.Round(expectedVy * dist * this.Mass);

            //Program.ConsoleHelper.Debug($"accX={accX}|accY={accY}");
            //move.Acc = Math.Min((accX + accY) / 2, 300);

            var acc = (int)Math.Round(this.Mass * dist);

            move.Acc = Math.Min(acc, 300);
            return(move);
        }
Esempio n. 19
0
        public static double SolveParam_2(double len, double r1, double r2)
        {
            Func <double, double> f = (a) =>
            {
                double fs1, fc1;
                FresnelUtils.Fresnel(a / (r1 * sqrtpi), out fs1, out fc1);

                double fs2, fc2;
                FresnelUtils.Fresnel(a / (r2 * sqrtpi), out fs2, out fc2);

                double fc21 = (fc2 - fc1);
                double fs21 = (fs2 - fs1);

                return(a * a * SysMath.PI * (fc21 * fc21 + fs21 * fs21) - len * len);
            };

            int maxEval = 50; // 30

            try
            {
                double min = 0;
                double max = SysMath.Min(SysMath.Abs(r1), SysMath.Abs(r2)) * MAX_L;
                return(Solver.Solve(f, min, max, Solver.Type.Brent, Solver.DEFAULT_ABSOLUTE_ACCURACY, maxEval));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }
        }
Esempio n. 20
0
        public void GenerateWater(VoxelChunk chunk, float maxHeight)
        {
            int waterHeight = Math.Min((int)(VoxelConstants.ChunkSizeY * NormalizeHeight(SeaLevel + 1.0f / VoxelConstants.ChunkSizeY, maxHeight)), VoxelConstants.ChunkSizeY - 1);
            var iceID       = VoxelLibrary.GetVoxelType("Ice");

            for (var x = 0; x < VoxelConstants.ChunkSizeX; ++x)
            {
                for (var z = 0; z < VoxelConstants.ChunkSizeZ; ++z)
                {
                    var biome    = Overworld.GetBiomeAt(new Vector3(x, 0, z) + chunk.Origin, chunk.Manager.World.WorldScale, chunk.Manager.World.WorldOrigin);
                    var topVoxel = VoxelHelpers.FindFirstVoxelBelow(new VoxelHandle(
                                                                        chunk, new LocalVoxelCoordinate(x, VoxelConstants.ChunkSizeY - 1, z)));

                    for (var y = 0; y <= waterHeight; ++y)
                    {
                        var vox = new VoxelHandle(chunk, new LocalVoxelCoordinate(x, y, z));
                        if (vox.IsEmpty && y > topVoxel.Coordinate.Y)
                        {
                            if (biome.WaterSurfaceIce && y == waterHeight)
                            {
                                vox.RawSetType(iceID);
                            }
                            else
                            {
                                vox.QuickSetLiquid(biome.WaterIsLava ? LiquidType.Lava : LiquidType.Water, WaterManager.maxWaterLevel);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        public static void SetHeight(float[,] heightMap, Vector2 pos, float height)
        {
            int x = Math.Max(Math.Min((int)pos.X, heightMap.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, heightMap.GetLength(1) - 1), 0);

            heightMap[x, y] = height;
        }
Esempio n. 22
0
            /// <summary>
            /// Create beacon message
            /// </summary>
            /// <param name="msgBytes"></param>
            /// <param name="etx">Estimated distance from Base</param>
            /// <param name="beaconNum">Beacon sequence counter</param>
            /// <returns>Size of message</returns>
            public static int CreateBeacon(byte[] msgBytes, byte etx, ushort beaconNum, byte ewmarnp, ushort parent)
            {
                var idx = 0;

                msgBytes[idx] = (byte)MessageIds.Beacon;
                idx          += sizeof(byte);
                //Debug.Print("\tIdx: " + idx);

                msgBytes[idx] = etx;
                idx          += sizeof(byte);
                //Debug.Print("\tIdx: " + idx);

                var beaconAdj = (ushort)Math.Min(beaconNum, ushort.MaxValue);

                BitConverter.InsertValueIntoArray(msgBytes, idx, beaconAdj);
                idx += sizeof(ushort);

                msgBytes[idx] = ewmarnp;
                idx          += sizeof(byte);

                BitConverter.InsertValueIntoArray(msgBytes, idx, parent);
                idx += sizeof(ushort);

                return(idx);
            }
Esempio n. 23
0
        public static float GetValue(MapData[,] map, Vector2 pos, ScalarFieldType value)
        {
            int x = Math.Max(Math.Min((int)pos.X, map.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, map.GetLength(1) - 1), 0);

            return(map[x, y].GetValue(value));
        }
Esempio n. 24
0
        public void EmitLoadAddress(Format12OpCode opCode, LowRegister targetRegister, int target, bool thumbAdjustment)
        {
            var offset = target - ((CurrentAddress + 4) & ~2);

            if (offset >= 0)
            {
                Emit(opCode, targetRegister, target);
                if (thumbAdjustment)
                {
                    Emit(Format3OpCode.ADD, targetRegister, 1);
                }
            }
            else
            {
                //While the Format12 instruction will clear the 1 bit of the PC, this code does not
                var remainder = -(target - (CurrentAddress + 4));
                if (thumbAdjustment)
                {
                    --remainder;
                }
                Emit(Format5OpCode.MOV, targetRegister, Register.PC);
                while (remainder != 0)
                {
                    var amountToUse = Math.Min(remainder, 255);
                    Emit(Format3OpCode.SUB, targetRegister, (byte)remainder);
                    remainder -= amountToUse;
                }
            }
        }
Esempio n. 25
0
        public static void AddValue(MapData[,] map, Vector2 pos, ScalarFieldType value, float amount)
        {
            int x = Math.Max(Math.Min((int)pos.X, map.GetLength(0) - 1), 0);
            int y = Math.Max(Math.Min((int)pos.Y, map.GetLength(1) - 1), 0);

            map[x, y].SetValue(value, map[x, y].GetValue(value) + amount);
        }
Esempio n. 26
0
        public static List <Vector3Int> MakeWalls(WorldEdit.AreaSelection area, int border = 1)
        {
            List <Vector3Int> affected = new List <Vector3Int>();

            int minX = Math.Min(area.posA.x, area.posB.x);
            int maxX = Math.Max(area.posA.x, area.posB.x);
            int minZ = Math.Min(area.posA.z, area.posB.z);
            int maxZ = Math.Max(area.posA.z, area.posB.z);

            Vector3Int relative;

            for (int x = area.cornerB.x; x >= area.cornerA.x; x--)
            {
                for (int y = area.cornerB.y; y >= area.cornerA.y; y--)
                {
                    for (int z = area.cornerB.z; z >= area.cornerA.z; z--)
                    {
                        relative = new Vector3Int(x, y, z);
                        if (relative.x > (maxX - border) || relative.x < (minX + border) || relative.z > (maxZ - border) || relative.z < (minZ + border))
                        {
                            affected.Add(relative);
                        }
                    }
                }
            }

            return(affected);
        }
Esempio n. 27
0
        /// <summary>
        ///     Resuelve el parametro de la clotoide dado los radios <c>r0</c> y <c>r1</c> Con una distancia <c>d</c> entre los
        ///     puntos.
        /// </summary>
        private static double SolveParam(double d, double r0, double r1)
        {
            Func <double, double> f = (a) =>
            {
                double fs0, fc0;
                ClothoUtils.Fresnel(a / (r0 * sqrtpi), out fs0, out fc0);

                double fs1, fc1;
                ClothoUtils.Fresnel(a / (r1 * sqrtpi), out fs1, out fc1);

                double fc10 = (fc1 - fc0);
                double fs10 = (fs1 - fs0);

                return(a * a * SysMath.PI * (fc10 * fc10 + fs10 * fs10) - d * d);
            };

            int maxEval = 50; // 30

            try
            {
                double min = 0;
                double max = SysMath.Min(SysMath.Abs(r0), SysMath.Abs(r1)) * ClothoUtils.MAX_L;
                double v   = Solver.Solve(f, min, max, Solver.Type.BrentSolver, DEFAULT_ABSOLUTE_ACCURACY, maxEval);
                return(v);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// Transfers resources into the specified parts
        /// </summary>
        /// <param name="parts">All of the recipient parts</param>
        /// <param name="pulledAmount">the aggregate amount we are seeking to add to the parts</param>
        private void PutResources(IList <global::Part> parts, double pulledAmount)
        {
            var retries   = 0;
            var evenShare = pulledAmount / parts.Count;

            var remaining = pulledAmount;

            while (remaining > 0.0001)
            {
                if (retries > 10)
                {
                    MarkFailed("Error in putting resource with " + remaining + " remaining.");
                    break;
                }
                foreach (var part in parts)
                {
                    var resource = part.Resources.Get(resourceInfo.id);
                    if (resource == null)
                    {
                        continue;
                    }

                    var transferAmount = Math.Min(remaining, evenShare);

                    remaining += part.TransferResource(resource.info.id, transferAmount);
                }
                retries++;
            }
        }
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        public bool Equals(PolarCoordinate other)
        {
            double tolerance = NMath.Min(Tolerance, other.Tolerance);

            return(Azimuth.Radians.IsEqualTo(other.Azimuth.Radians, tolerance) &&
                   Radius.IsEqualTo(other.Radius, tolerance));
        }
Esempio n. 30
0
 /// <summary>
 /// Implements the + operator.
 /// </summary>
 /// <param name="point1">The point1.</param>
 /// <param name="point2">The point2.</param>
 /// <returns>The result of the operator.</returns>
 public static PolarCoordinate operator +(PolarCoordinate point1, PolarCoordinate point2)
 {
     return(new PolarCoordinate(
                point1.Radius + point2.Radius,
                point1.Rotation + point2.Rotation,
                NMath.Min(point1.Tolerance, point2.Tolerance)));
 }