Пример #1
0
            //IBundle
            public object Property(Interpreter interpreter, Token token, object argument)
            {
                string propertyName = (string)argument;

                //utility functions
                Func <double, double, double> NthRoot = (b, e) => {
                    if (e % 1 != 0 || e <= 0)
                    {
                        throw new ErrorHandler.RuntimeError(token, "Exponent must be a whole number above 0");
                    }
                    return(CSMath.Pow(b, 1 / e));
                };

                Func <double, double> Asinh = (x) => CSMath.Log(x + CSMath.Sqrt(x * x + 1));
                Func <double, double> Acosh = (x) => CSMath.Log(x + CSMath.Sqrt(x * x - 1));
                Func <double, double> Atanh = (x) => CSMath.Log((1 + x) / (1 - x)) / 2;

                switch (propertyName)
                {
                case "PI": return(3.14159265358979);

                case "E": return(2.71828182845905);

                case "Abs": return(new CallableArity1(this, CSMath.Abs));

                case "Floor": return(new CallableArity1(this, CSMath.Floor));

                case "Ceil": return(new CallableArity1(this, CSMath.Ceiling));

                case "Round": return(new CallableArity1(this, CSMath.Round));

                case "Pow": return(new CallableArity2(this, CSMath.Pow));

                case "Root": return(new CallableArity2(this, NthRoot));                        //doesn't exist in C# yet

                case "Log": return(new CallableArity1(this, CSMath.Log));

                case "Exp": return(new CallableArity1(this, CSMath.Exp));

                case "Sin": return(new CallableArity1(this, CSMath.Sin));

                case "Cos": return(new CallableArity1(this, CSMath.Cos));

                case "Tan": return(new CallableArity1(this, CSMath.Tan));

                case "Asin": return(new CallableArity1(this, CSMath.Asin));

                case "Acos": return(new CallableArity1(this, CSMath.Acos));

                case "Atan": return(new CallableArity1(this, CSMath.Atan));

                case "Sinh": return(new CallableArity1(this, CSMath.Sinh));

                case "Cosh": return(new CallableArity1(this, CSMath.Cosh));

                case "Tanh": return(new CallableArity1(this, CSMath.Tanh));

                case "Asinh": return(new CallableArity1(this, Asinh));                        //doesn't exist in C# yet

                case "Acosh": return(new CallableArity1(this, Acosh));                        //doesn't exist in C# yet

                case "Atanh": return(new CallableArity1(this, Atanh));                        //doesn't exist in C# yet

                default:
                    throw new ErrorHandler.RuntimeError(token, "Unknown property '" + propertyName + "'");
                }
            }
Пример #2
0
 /// <summary>
 ///     Raises a number to the specified power.
 /// </summary>
 /// <param name="number">Number to be raised to a power.</param>
 /// <param name="power">Power to raise the number to.</param>
 /// <returns name="result">Number raised to the power.</returns>
 /// <search>^,power,raise,exponent</search>
 public static double Pow(double number, double power)
 {
     return(CSMath.Pow(number, power));
 }
Пример #3
0
 private static float pow(float x, float y)
 {
     return((float)Math.Pow(x, y));
 }
Пример #4
0
 /// <summary>
 /// Calculates a square of dual number
 /// </summary>
 public static DualNumber Squared(this DualNumber value)
 {
     return(new DualNumber((float)SMath.Pow(value.Value, 2f), value.Derivative * 2f * value.Value));
 }
Пример #5
0
 public static double Pow(double value1, double value2)
 {
     return(CSMath.Pow(value1, value2));
 }
Пример #6
0
 public static double NextPowerOfTwo(double n)
 {
     return((double)SysMath.Pow(2.0, SysMath.Ceiling(SysMath.Log(n, 2.0))));
 }
Пример #7
0
        public bool Intersect(Planet planet)
        {
            var distance    = (float)Math.Sqrt(Math.Pow(planet.Transform.X - Transform.X, 2) + Math.Pow(planet.Transform.Y - Transform.Y, 2));
            var totalRadius = Radius + planet.Radius;

            if (distance <= totalRadius && planet.IsCheck == false)
            {
                var angle = (float)Math.Atan2(Transform.Y - planet.Transform.Y, Transform.X - planet.Transform.X);
                angle += (float)Math.PI / 2 - planet.Transform.Angle;

                //    planet.AngularVelocity = 0.04f;
                planet.CorrectAngle = -angle;
                //    planet.Angle = angle;
                planet.IsCheck = true;
                SetPlanet(planet);

                ((GameScreen)_engine.Screens.CurrentScreen).LayoutTop.IncrementBalls();
                IncrementBalls?.Invoke(null, null);
                return(true);
            }

            return(false);
        }
Пример #8
0
        static void Main()
        {
            Device    device;
            SwapChain swapChain;

            //var form = new RenderForm("CSharpRenderer");
            var form  = new CSharpRendererMainForm();
            var panel = form.GetRenderingPanel();

            form.ClientSize = new System.Drawing.Size(ResolutionX, ResolutionY);

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = panel.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(ResolutionX, ResolutionY, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);
            var swapChainResource = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            SamplerStates.Initialize(device);
            ShaderManager.Initialize(device);
            GPUProfiler.Initialize(device);
            ContextHelper.Initialize(device);
            RenderTargetManager.Initialize(device);
            PostEffectHelper.Initialize(device, ResolutionX, ResolutionY);
            CubemapRenderHelper.Initialize(device);

            Dictionary <CustomConstantBufferDefinition.ConstantBufferPropertyField, Tuple <TrackBar, TextBox> > propertyControlBindings =
                new Dictionary <CustomConstantBufferDefinition.ConstantBufferPropertyField, Tuple <TrackBar, TextBox> >();

            {
                TableLayoutPanel tableLayout = form.GetTableLayoutPanel();

                var contantBuffers = ShaderManager.GetConstantBufferDefinitions();

                int tableParamCounter = 1;
                foreach (var cb in contantBuffers)
                {
                    var paramProperties = cb.GetParamProperties();

                    if (paramProperties.Count > 0)
                    {
                        Label groupLabel = new Label();
                        groupLabel.Text        = cb.m_Name;
                        groupLabel.BorderStyle = BorderStyle.FixedSingle;
                        groupLabel.Anchor      = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                        tableLayout.Controls.Add(groupLabel, 0, tableParamCounter);
                        tableParamCounter++;

                        foreach (var param in paramProperties)
                        {
                            Label lb = new Label();
                            lb.Text   = param.name;
                            lb.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                            TextBox  text = new TextBox();
                            TrackBar tb   = new TrackBar();
                            tb.Size     = new System.Drawing.Size(400, 10);
                            tb.Anchor   = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                            tb.Minimum  = 0;
                            tb.Maximum  = 1024;
                            tb.Value    = (int)(((Single)param.paramValue - param.paramRangeMin) / (param.paramRangeMax - param.paramRangeMin) * 1024);
                            text.Text   = ((Single)param.paramValue).ToString();
                            text.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                            tableLayout.Controls.Add(lb, 0, tableParamCounter);
                            tableLayout.Controls.Add(tb, 1, tableParamCounter);
                            tableLayout.Controls.Add(text, 2, tableParamCounter);
                            propertyControlBindings.Add(param, new Tuple <TrackBar, TextBox>(tb, text));
                            tableParamCounter++;
                        }
                    }
                }
            }

            Scene scene = new Scene();

            scene.Initialize(device, form, panel, ResolutionX, ResolutionY);

            var resolvedRenderTarget = RenderTargetSet.CreateRenderTargetSet(device, ResolutionX, ResolutionY, Format.R8G8B8A8_UNorm, 1, false);

            RenderTargetSet.BindNull(device.ImmediateContext);

            // setting a viewport is required if you want to actually see anything
            var context = device.ImmediateContext;

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(panel.Handle, WindowAssociationFlags.IgnoreAltEnter);

            int counter = 0;

            Dictionary <string, double> profilers;

            profilers = new Dictionary <String, double>();

            MessagePump.Run(form, () =>
            {
                TemporalSurfaceManager.UpdateTemporalSurfaces();
                ShaderManager.UpdateShaderManager(device);

                GPUProfiler.BeginFrameProfiling(context);
                scene.RenderFrame(context, 0.0f, resolvedRenderTarget);
                context.CopyResource(resolvedRenderTarget.m_RenderTargets[0].m_TextureObject2D, swapChainResource);
                GPUProfiler.EndFrameProfiling(context);
                swapChain.Present(0, PresentFlags.None);
                context.PixelShader.SetShaderResource(null, 0);

                if (GPUProfiler.m_CurrentFrameProfilerTree != null)
                {
                    Action <GPUProfiler.ProfilerTreeMember, String> processLevel = null;

                    processLevel = (GPUProfiler.ProfilerTreeMember treeMember, String level) =>
                    {
                        string finalName = level + treeMember.m_Name;

                        if (profilers.ContainsKey(finalName))
                        {
                            profilers[finalName] += treeMember.m_Time;
                        }
                        else
                        {
                            profilers.Add(finalName, treeMember.m_Time);
                        }

                        foreach (var v in treeMember.m_ChildMembers)
                        {
                            processLevel(v, level + "_");
                        }
                    };

                    processLevel(GPUProfiler.m_CurrentFrameProfilerTree, "");
                }

                if (++counter == 10)
                {
                    foreach (var propertyBinding in propertyControlBindings)
                    {
                        var property = propertyBinding.Key;
                        var trackBar = propertyBinding.Value.Item1;
                        var textBox  = propertyBinding.Value.Item2;

                        float rawVal = (float)trackBar.Value / 1024.0f;
                        if (property.isGamma)
                        {
                            rawVal = (float)Math.Pow((double)rawVal, 2.2);
                        }
                        float val           = rawVal * (property.paramRangeMax - property.paramRangeMin) + property.paramRangeMin;
                        property.paramValue = val;
                        textBox.Text        = val.ToString("F");
                    }

                    DataGridView dataGridView = form.GetDataGridView();
                    dataGridView.Rows.Clear();

                    foreach (var profilerEntry in profilers)
                    {
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(dataGridView);
                        row.Cells[0].Value = profilerEntry.Key;
                        row.Cells[1].Value = String.Format("{0}", Math.Round(profilerEntry.Value * 100.0 / 10.0) / 100.0);
                        dataGridView.Rows.Add(row);
                    }

                    profilers.Clear();

                    counter = 0;
                }
                System.Threading.Thread.Sleep(15);
            });
        }
Пример #9
0
        /// <summary>
        /// This is a console example of importing zones of a specified type from a shape file set (.shp, .shx, .dbf) or csv file into a specified database.
        /// Included in this project is are sample shape files: owensboro
        ///
        /// 1) Process command line arguments: Server, Database, User name, Password, Options and load the specified shape/csv file set.
        /// 2) Process the shapes present in the shape file, using the Geotab.Geographical components to create zones from the shape points and names.
        /// 3) Create Geotab API object and Authenticate.
        /// 4) Import created zones into the database.
        /// The format of csv file is next:
        /// [Zone_name]
        /// [polygon_point_x], [polygon_point_y]
        /// [polygon_point_x], [polygon_point_y]
        /// .
        /// .
        /// [polygon_point_x], [polygon_point_y]
        /// [Zone_name]
        /// [polygon_point_x], [polygon_point_y]
        /// .
        /// .
        /// A complete Geotab API object and method reference is available at the Geotab Developer page.
        /// </summary>
        /// <param name="args">The command line arguments for the application. Note: When debugging these can be added by: Right click the project > Properties > Debug Tab > Start Options: Command line arguments.</param>
        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 5)
                {
                    Console.WriteLine();
                    Console.WriteLine("Command line parameters:");
                    Console.WriteLine("dotnet run <server> <database> <login> <password> [--nameAttr=<attr>] [--namePrefix=<prefix>] [--type=<name>] <inputfile>");
                    Console.WriteLine();
                    Console.WriteLine("Command line:             dotnet run server database username password --nameAttr=name --namePrefix=CA --type=home inputfile.shp");
                    Console.WriteLine("server                   - The server name (Example: my.geotab.com)");
                    Console.WriteLine("database                 - The database name (Example: G560)");
                    Console.WriteLine("username                 - The Geotab user name");
                    Console.WriteLine("password                 - The Geotab password");
                    Console.WriteLine("[--nameAttr=<attr>]      - Optional - Name of the shape's attribute to use as");
                    Console.WriteLine("                           the zone name. (Default: first attribute containing");
                    Console.WriteLine("                           the word 'name')");
                    Console.WriteLine("[--namePrefix=<prefix>]  - Optional - The name prefix. (Example: prefix + Name)");
                    Console.WriteLine("[--type=<name>]          - Optional - Specify zone type (Default: customer)");
                    Console.WriteLine("[--threshold=<number>]   - Optional - Simplify zones by removing redundant");
                    Console.WriteLine("                           points. Any point within approximately <threshold>");
                    Console.WriteLine("                           meters of a line connecting its neighbors will be");
                    Console.WriteLine("                           removed.");
                    Console.WriteLine("inputfile                - File name of the Shape file containing the shapes to");
                    Console.WriteLine("                           import with extension. (.shp, .shx, .dbf)");
                    Console.WriteLine();
                    return;
                }

                // Variables from command line
                int             last                 = args.Length - 1;
                string          server               = args[0];
                string          database             = args[1];
                string          username             = args[2];
                string          password             = args[3];
                List <ZoneType> zoneTypes            = new List <ZoneType>();
                string          fileName             = args[last];
                string          nameAttribute        = null;
                string          prefix               = "";
                double          distanceSquaredError = -1;
                Color           zonesColour          = customerZoneColor;

                // Create Geotab API object
                API api = new API(username, password, null, database, server);

                // Authenticate
                Console.WriteLine("Authenticating...");
                api.Authenticate();

                Console.WriteLine("Getting current user...");
                List <User> users = api.Call <List <User> >("Get", typeof(User), new { search = new UserSearch {
                                                                                           Name = api.UserName
                                                                                       } });
                if (users.Count != 1)
                {
                    Console.WriteLine($"Found {users.Count} users with name {api.UserName}.");
                    return;
                }

                // the user's groups will be used when creating the zones
                var groups = users[0].CompanyGroups;

                Console.WriteLine("Getting available zone types...");
                List <ZoneType> availableZoneTypes = api.Call <List <ZoneType> >("Get", typeof(ZoneType));

                // Options from args
                for (int i = 4; i < last; i++)
                {
                    string option = args[i].ToLowerInvariant();
                    int    index  = option.IndexOf('=');

                    // Check the option is in the established format
                    if (index >= 0 && option.Length > index + 1)
                    {
                        // Grab the value of the optional argument
                        string value = option.Substring(index + 1).ToLowerInvariant();

                        // Zone type option
                        if (option.Contains("type"))
                        {
                            ZoneType zoneType = GetZoneType(value, availableZoneTypes);

                            if (zoneType != null && !zoneTypes.Contains(zoneType))
                            {
                                // Setting a default colour
                                switch (zoneType.Name)
                                {
                                case "**Customer Zone":
                                    zonesColour = customerZoneColor;
                                    break;

                                case "**Home Zone":
                                    zonesColour = homeZoneColor;
                                    break;

                                case "**Office Zone":
                                    zonesColour = officeZoneColor;
                                    break;
                                }

                                zoneTypes.Add(zoneType);
                            }
                        }

                        // Name attribute option
                        else if (option.Contains("nameattr"))
                        {
                            nameAttribute = value;
                        }

                        // Name prefix option
                        else if (option.Contains("prefix"))
                        {
                            prefix = value.ToUpperInvariant();
                        }

                        // Zone shape simplification threshold option
                        else if (option.Contains("threshold"))
                        {
                            if (!double.TryParse(value, out double threshold))
                            {
                                Console.WriteLine("Threshold must be a number. Example: 2.5");
                            }
                            else
                            {
                                distanceSquaredError = Math.Pow(1e-5 * threshold, 2);
                            }
                        }

                        else
                        {
                            Console.WriteLine($"Unknown optional argument: {option}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Unknown format for optional argument: {option}");
                    }
                }

                // Use Customer Zone Type for default.
                if (zoneTypes.Count < 1)
                {
                    zoneTypes.Add(ZoneTypeCustomer.Value);
                }

                IList <ISimpleCoordinate> coordinates = new List <ISimpleCoordinate>();
                IList <Zone> zones = new List <Zone>();

                // Initialize variables to hold the shape file
                DateTime maxValue = System.TimeZoneInfo.ConvertTimeToUtc(DateTime.MaxValue);
                DateTime minValue = DateTime.MinValue;
                if (!string.IsNullOrEmpty(fileName) && Path.GetExtension(fileName).ToLower().Contains("csv"))
                {
                    if (!File.Exists(fileName))
                    {
                        Console.WriteLine($"The file {fileName} does not exist.");
                        return;
                    }
                    Console.WriteLine("Loading csv file...");
                    using (StreamReader reader = File.OpenText(fileName))
                    {
                        string line;
                        string zoneName = string.Empty;
                        while (!string.IsNullOrEmpty(line = reader.ReadLine()))
                        {
                            string[] values = line.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (values.Length == 0 || values.Length == 1 && string.IsNullOrWhiteSpace(values[0]))
                            {
                                continue;
                            }
                            switch (values.Length)
                            {
                            case 1:
                                if (!string.IsNullOrEmpty(values[0]))
                                {
                                    if (!string.IsNullOrEmpty(zoneName))
                                    {
                                        // Simplify the zone shape. This is an important step. Polygon complexity can drastically impact performance when loading/rendering zones.
                                        coordinates = SimplifyPolygon(coordinates, distanceSquaredError);

                                        // Create the zone object to be inserted later on
                                        zones.Add(new Zone(null, (string.IsNullOrEmpty(prefix) ? "" : prefix + " ") + zoneName, "", true, zoneTypes, coordinates, minValue, maxValue, zonesColour, true, groups));
                                    }
                                    coordinates = new List <ISimpleCoordinate>();
                                    zoneName    = values[0];
                                }
                                break;

                            case 2:

                                // read coordinates line by line
                                if (double.TryParse(values[0], out var xCoord) && double.TryParse(values[1], out var yCoord))
                                {
                                    coordinates.Add(new Coordinate(xCoord, yCoord));
                                }
                                break;

                            default:
                                Console.WriteLine($"Skipping a line with text '{line}'");
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(zoneName))
                        {
                            coordinates = SimplifyPolygon(coordinates, distanceSquaredError);
                            zones.Add(new Zone(null, (string.IsNullOrEmpty(prefix) ? "" : prefix + " ") + zoneName, "", true, zoneTypes, coordinates, minValue, maxValue, zonesColour, true, groups));
                        }
                    }
                }
                else
                {
                    FileInfo            shapeFile = new FileInfo(fileName);
                    FileMapLayerFactory factory   = new FileMapLayerFactory(shapeFile);
                    ShapeFileLayer      layer;

                    // Try to load the shape file
                    Console.WriteLine("Loading shape file...");
                    try
                    {
                        layer = (ShapeFileLayer)factory.GetMapLayer();
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine($"Could not load shape file: {exception.Message}");
                        return;
                    }

                    // Get the index of the feature attribute that holds the zone name
                    Console.WriteLine("__ " + nameAttribute);
                    int nameAttributeIndex = GetNameAttributeIndex(layer, ref nameAttribute);
                    if (nameAttributeIndex == -1)
                    {
                        Console.WriteLine("Could not find a valid attribute to use for naming the zones.");
                        return;
                    }

                    // Process shapes into zones
                    int featureIndex = 0;
                    for (int k = 0; k < layer.Features.Count; k++)
                    {
                        IEarthFeature earthFeature = layer.Features[k];

                        // Get the data we are interested in for the zone
                        IEarthPolygon polygon  = earthFeature as IEarthPolygon;
                        string        zoneName = layer.GetFeatureField(featureIndex, nameAttributeIndex).ToString();

                        // Filter out non-polygons and unnamed shapes
                        if (polygon == null || string.IsNullOrEmpty(zoneName))
                        {
                            featureIndex++;
                            continue;
                        }

                        // Get the points that define the polygon
                        coordinates = new List <ISimpleCoordinate>();
                        for (int i = 0; i < polygon.Count; i++)
                        {
                            EarthPoint        earthPoint = (EarthPoint)polygon[i];
                            ISimpleCoordinate coordinate = new Coordinate(earthPoint.X, earthPoint.Y);
                            coordinates.Add(coordinate);
                        }

                        // Simplify the polygon. This is an important step. Polygon complexity can drastically impact performance when loading/rendering zones.
                        coordinates = SimplifyPolygon(coordinates, distanceSquaredError);

                        zones.Add(new Zone(null, (string.IsNullOrEmpty(prefix) ? "" : prefix + " ") + zoneName, "", true, zoneTypes, coordinates, minValue, maxValue, zonesColour, true, groups));
                        featureIndex++;
                    }
                }

                Console.WriteLine($"Found {zones.Count} zones to import");

                if (zones.Count < 1)
                {
                    return;
                }

                // Start import
                Console.WriteLine("Importing zones...");

                foreach (Zone zone in zones)
                {
                    try
                    {
                        // Add the zone
                        api.Call <Id>("Add", typeof(Zone), new { entity = zone });
                        Console.WriteLine($"Zone: '{zone.Name}' added");
                    }
                    catch (Exception exception)
                    {
                        // Catch and display any error that occur when adding the zone
                        Console.WriteLine($"Error adding zone: '{zone.Name}'\n{exception.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                // Show miscellaneous exceptions
                Console.WriteLine($"Error: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey(true);
            }
        }
Пример #10
0
        /// <summary>
        /// Trigger a pressure and temperature conversion.
        /// </summary>
        /// <param name="temperature">The referenced temperature parameter is reported based upon user selected <see cref="TemperatureUnit"/> property.</param>
        /// <param name="pressure">The referenced pressure parameter is reported in Pascal units (1 Pa = 0.01 mBar or 1HectoPascals) either as <see cref="PressureCompensationModes.SeaLevelCompensated"/> or <see cref="PressureCompensationModes.Uncompensated"/>.</param>
        /// <param name="altitude">The referenced  altitude parameter is reported in meters.</param>
        /// <remarks>The altitude reading is a calculated value, based on well established mathematical formulas.</remarks>
        /// <example>Example usage:
        /// <code language = "C#">
        /// for (;;)
        /// {
        ///     _sensor.ReadSensor(out temperature, out pressure, out altitude);
        ///     Debug.Print("Temperature.........: " + temperature.ToString("F2") + " °C");
        ///     Debug.Print("Pressure............: " + pressure.ToString("F2") + " Pascals");
        ///     Debug.Print("Altitude............: " + altitude.ToString("F2") + " meters");
        ///     Debug.Print("-----------------------------------");
        ///     Thread.Sleep(2000);
        /// }
        /// </code>
        /// <code language = "VB">
        /// While True
        ///     _sensor.ReadSensor(temperature, pressure, altitude)
        ///     Debug.Print("Temperature.........: " <![CDATA[&]]> temperature.ToString("F2") <![CDATA[&]]> " °C")
        ///     Debug.Print("Pressure............: " <![CDATA[&]]> pressure.ToString("F2") <![CDATA[&]]> " Pascals")
        ///     Debug.Print("Altitude............: " <![CDATA[&]]> altitude.ToString("F2") <![CDATA[&]]> " meters")
        ///     Debug.Print("-----------------------------------")
        ///     Thread.Sleep(2000)
        /// End While
        /// </code>
        /// </example>
        public void ReadSensor(out Single temperature, out Single pressure, out Single altitude)
        {
            Single D2 = ReadADC(MS5607_CMD_ADC_D2, PressureOverSamplingRate);
            Single D1 = ReadADC(MS5607_CMD_ADC_D1, TemperatureOverSamplingRate);

            // Calcualte 1st order pressure and temperature compensation
            Single dT   = (Single)(D2 - CalibrationData[5] * Math.Pow(2, 8));
            Single OFF  = (Single)(CalibrationData[2] * Math.Pow(2, 17) + dT * CalibrationData[4] / Math.Pow(2, 6));
            Single SENS = (Single)(CalibrationData[1] * Math.Pow(2, 16) + dT * CalibrationData[3] / Math.Pow(2, 7));

            temperature = (Single)(2000 + dT * CalibrationData[6] / Math.Pow(2, 23)) / 100;
            pressure    = (Single)((D1 * SENS / Math.Pow(2, 21) - OFF) / Math.Pow(2, 15));
            altitude    = (Single)(44330.77 * (1.0 - Math.Pow(pressure / CalculatePressureAsl(pressure), 0.1902663538687809)));

            if (PressureCompensationMode == PressureCompensationModes.SeaLevelCompensated)
            {
                pressure = CalculatePressureAsl(pressure);
            }

            if (!(temperature * 100 < 2000))
            {
                temperature = ScaleTemperature(temperature);
                return;
            }

            // Calculate 2nd order pressure and temperature compensation
            Single T2    = (Single)(dT * dT / Math.Pow(2, 31));
            Single OFF2  = (Single)(61 * (temperature - 2000) * (temperature - 2000) / Math.Pow(2, 4));
            Single SENS2 = 2 * (temperature - 2000) * (temperature - 2000);

            if (temperature < -1500)
            {
                OFF2  += 15 * (temperature + 1500) * (temperature + 1500);
                SENS2 += 8 * (temperature + 1500) * (temperature + 1500);
            }

            OFF  -= OFF2;
            SENS -= SENS2;

            temperature -= T2;
            temperature  = ScaleTemperature(temperature);

            pressure = (Single)((D1 * SENS / Math.Pow(2, 21) - OFF) / Math.Pow(2, 15));

            if (PressureCompensationMode == PressureCompensationModes.SeaLevelCompensated)
            {
                pressure = CalculatePressureAsl(pressure);
            }
        }
 double getScaleFactor(double level)
 {
     return(Math.Pow(scaleFactor, level));
 }
Пример #12
0
        private static Single CalculatePressureAsl(Single uncompensatedPressure)
        {
            Single seaLevelCompensation = (Single)(101325 * Math.Pow((288 - 0.0065 * 143) / 288, 5.256));

            return(101325 + uncompensatedPressure - seaLevelCompensation);
        }
Пример #13
0
 public double altitude(double P, double P0)
 // Given a pressure measurement P (mb) and the pressure at a baseline P0 (mb),
 // return altitude (meters) above baseline.
 {
     return(44330.0 * (1 - Math.Pow(P / P0, 1 / 5.255)));
 }
Пример #14
0
        public bool begin()
        // Initialize library for subsequent pressure measurements
        {
            double c3, c4, b1;

            // Start up the Arduino's "wire" (I2C) library:

            i2cDevice = new I2CDevice(new I2CDevice.Configuration(BMP180_ADDR, 50));


            //Wire.begin();

            // The BMP180 includes factory calibration data stored on the device.
            // Each device has different numbers, these must be retrieved and
            // used in the calculations when taking pressure measurements.

            // Retrieve calibration data from device:
            fixed(short *ac1 = &AC1, ac2 = &AC2, ac3 = &AC3, vb1 = &VB1, vb2 = &VB2, mb = &MB, mcc = &MC, mdd = &MD)
            {
                fixed(ushort *ac4 = &AC4, ac5 = &AC5, ac6 = &AC6)
                {
                    if (readInt(0xAA, ac1) &&
                        readInt(0xAC, ac2) &&
                        readInt(0xAE, ac3) &&
                        readUInt(0xB0, ac4) &&
                        readUInt(0xB2, ac5) &&
                        readUInt(0xB4, ac6) &&
                        readInt(0xB6, vb1) &&
                        readInt(0xB8, vb2) &&
                        readInt(0xBA, mb) &&
                        readInt(0xBC, mcc) &&
                        readInt(0xBE, mdd))
                    {
                        // All reads completed successfully!

                        // If you need to check your math using known numbers,
                        // you can uncomment one of these examples.
                        // (The correct results are commented in the below functions.)

                        // Example from Bosch datasheet
                        // AC1 = 408; AC2 = -72; AC3 = -14383; AC4 = 32741; AC5 = 32757; AC6 = 23153;
                        // B1 = 6190; B2 = 4; MB = -32768; MC = -8711; MD = 2868;

                        // Example from http://wmrx00.sourceforge.net/Arduino/BMP180-Calcs.pdf
                        // AC1 = 7911; AC2 = -934; AC3 = -14306; AC4 = 31567; AC5 = 25671; AC6 = 18974;
                        // VB1 = 5498; VB2 = 46; MB = -32768; MC = -11075; MD = 2432;

                        /*
                         * Serial.print("AC1: "); Serial.println(AC1);
                         * Serial.print("AC2: "); Serial.println(AC2);
                         * Serial.print("AC3: "); Serial.println(AC3);
                         * Serial.print("AC4: "); Serial.println(AC4);
                         * Serial.print("AC5: "); Serial.println(AC5);
                         * Serial.print("AC6: "); Serial.println(AC6);
                         * Serial.print("VB1: "); Serial.println(VB1);
                         * Serial.print("VB2: "); Serial.println(VB2);
                         * Serial.print("MB: "); Serial.println(MB);
                         * Serial.print("MC: "); Serial.println(MC);
                         * Serial.print("MD: "); Serial.println(MD);
                         */

                        // Compute floating-point polynominals:

                        c3 = 160.0 * Math.Pow(2, -15) * AC3;
                        c4 = Math.Pow(10, -3) * Math.Pow(2, -15) * AC4;
                        b1 = Math.Pow(160, 2) * Math.Pow(2, -30) * VB1;
                        c5 = (Math.Pow(2, -15) / 160) * AC5;
                        c6 = AC6;
                        mc = (Math.Pow(2, 11) / Math.Pow(160, 2)) * MC;
                        md = MD / 160.0;
                        x0 = AC1;
                        x1 = 160.0 * Math.Pow(2, -13) * AC2;
                        x2 = Math.Pow(160, 2) * Math.Pow(2, -25) * VB2;
                        y0 = c4 * Math.Pow(2, 15);
                        y1 = c4 * c3;
                        y2 = c4 * b1;
                        p0 = (3791.0 - 8.0) / 1600.0;
                        p1 = 1.0 - 7357.0 * Math.Pow(2, -20);
                        p2 = 3038.0 * 100.0 * Math.Pow(2, -36);

                        /*
                         * Serial.println();
                         * Serial.print("c3: "); Serial.println(c3);
                         * Serial.print("c4: "); Serial.println(c4);
                         * Serial.print("c5: "); Serial.println(c5);
                         * Serial.print("c6: "); Serial.println(c6);
                         * Serial.print("b1: "); Serial.println(b1);
                         * Serial.print("mc: "); Serial.println(mc);
                         * Serial.print("md: "); Serial.println(md);
                         * Serial.print("x0: "); Serial.println(x0);
                         * Serial.print("x1: "); Serial.println(x1);
                         * Serial.print("x2: "); Serial.println(x2);
                         * Serial.print("y0: "); Serial.println(y0);
                         * Serial.print("y1: "); Serial.println(y1);
                         * Serial.print("y2: "); Serial.println(y2);
                         * Serial.print("p0: "); Serial.println(p0);
                         * Serial.print("p1: "); Serial.println(p1);
                         * Serial.print("p2: "); Serial.println(p2);
                         */

                        // Success!
                        return(true);
                    }
                    else
                    {
                        // Error reading calibration data; bad component or connection?
                        return(false);
                    }
                }
            }
        }
Пример #15
0
        private static Vec3 trace(Ray ray, Scene scene, int depth)
        {
            var    nearest = Num.MaxValue;
            Sphere obj     = null;

            // search the scene for nearest intersection
            foreach (var o in scene.Objects)
            {
                var distance = Num.MaxValue;
                if (Sphere.Intersect(o, ray, out distance))
                {
                    if (distance < nearest)
                    {
                        nearest = distance;
                        obj     = o;
                    }
                }
            }

            if (obj == null)
            {
                return(Vec3.Zero);
            }

            var  point_of_hit = ray.Org + (ray.Dir * nearest);
            var  normal       = Sphere.Normal(obj, point_of_hit);
            bool inside       = false;

            if (Vec3.Dot(normal, ray.Dir) > 0)
            {
                inside = true;
                normal = -normal;
            }

            Vec3 color            = Vec3.Zero;
            var  reflection_ratio = obj.Reflection;

            foreach (var l in scene.Lights)
            {
                var light_direction = Vec3.Normalize(l.Position - point_of_hit);
                Ray r;
                                #if BIT64
                r.Org = point_of_hit + (normal * 1e-5);
                                #else
                r.Org = point_of_hit + (normal * 1e-5f);
                                #endif
                r.Dir = light_direction;

                // go through the scene check whether we're blocked from the lights
                bool blocked = false;
                foreach (var o in scene.Objects)
                {
                    if (Sphere.Intersect(o, r))
                    {
                        blocked = true;
                        break;
                    }
                }

                if (!blocked)
                {
                    color += l.Color
                             * MATH.Max(0, Vec3.Dot(normal, light_direction))
                             * obj.Color
                             * (1.0f - reflection_ratio);
                }
            }

            var rayNormDot    = Vec3.Dot(ray.Dir, normal);
            Num facing        = MATH.Max(0, -rayNormDot);
            Num fresneleffect = reflection_ratio + ((1 - reflection_ratio) * MATH.Pow((1 - facing), 5));

            // compute reflection
            if (depth < maxDepth && reflection_ratio > 0)
            {
                var reflection_direction = ray.Dir + (normal * 2 * rayNormDot * (-1));
                Ray r;
                                #if BIT64
                r.Org = point_of_hit + (normal * 1e-5);
                                #else
                r.Org = point_of_hit + (normal * 1e-5f);
                                #endif
                r.Dir = reflection_direction;
                var reflection = trace(r, scene, depth + 1);
                color += reflection * fresneleffect;
            }

            // compute refraction
            if (depth < maxDepth && (obj.Transparency > 0))
            {
                                #if BIT64
                Num ior = 1.5;
                                #else
                Num ior = 1.5f;
                                #endif
                var CE = Vec3.Dot(ray.Dir, normal) * (-1);
                ior = inside ? 1 / ior : ior;
                Num eta      = 1 / ior;
                var GF       = (ray.Dir + normal * CE) * eta;
                Num sin_t1_2 = 1 - (CE * CE);
                Num sin_t2_2 = sin_t1_2 * (eta * eta);
                if (sin_t2_2 < 1)
                {
                    var GC = normal * MATH.Sqrt(1 - sin_t2_2);
                    var refraction_direction = GF - GC;
                    Ray r;
                                        #if BIT64
                    r.Org = point_of_hit - (normal * 1e-4);
                                        #else
                    r.Org = point_of_hit - (normal * 1e-4f);
                                        #endif
                    r.Dir = refraction_direction;
                    var refraction = trace(r, scene, depth + 1);
                    color += refraction * (1 - fresneleffect) * obj.Transparency;
                }
            }
            return(color);
        }
Пример #16
0
 private static double HillScale(int x, int z)
 {
     return(M.Pow(M.Abs(4.8 * (PerlinNoise(x, -1000, z, 15 * WORLD_SCALE, 2, 1) - 1)), 3));
 }
Пример #17
0
 public static float NextPowerOfTwo(float n)
 {
     return((float)SysMath.Pow(2.0, SysMath.Ceiling(SysMath.Log((double)n, 2.0))));
 }
Пример #18
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);
        }
 public static double Pow(double d, double p)
 => Math.Pow(d, p);
Пример #20
0
 public static double SHIFTRIGHT(double x, long places) => x / SysMath.Pow(R, places);
Пример #21
0
 /// <summary>
 /// Calculates a power of dual number
 /// </summary>
 public static DualNumber Pow(DualNumber value, float power)
 {
     return(new DualNumber((float)SMath.Pow(value.Value, power), value.Derivative * power * (float)SMath.Pow(value.Value, power - 1f)));
 }
Пример #22
0
 public static double SHIFTLEFT(double x, long places) => x *SysMath.Pow(R, places);
Пример #23
0
        internal void UpdatePitch()
        {
            lock (currentTrackLock)
            {
                if (currentTrack == null) // did not manage to obtain a track
                {
                    return;
                }

                var status = currentTrack.Track.SetPlaybackRate((int)(MathUtil.Clamp((float)Math.Pow(2, Pitch) * dopplerPitchFactor, 0.5f, 2f) * SoundEffectInstanceFrameRate)); // conversion octave to frequency
                if (status != (int)TrackStatus.Success)
                {
                    throw new AudioSystemInternalException("AudioTrack.SetPlaybackRate failed and failure was not handled. [error:" + status + "]");
                }
            }
        }
Пример #24
0
 public static double Pow(double d, double p)
 {
     return(Math.Pow(d, p));
 }
Пример #25
0
        /// <summary>
        /// 探测周跳
        /// </summary>
        /// <remarks>
        /// GPS周跳探测与修复的算法研究与实现.彭秀英.2004
        /// </remarks>
        public static bool DetectCycleSlip(ref OArc arc, out int index)
        {
            index = -1;

            // i-1历元宽巷模糊度估计值
            double NW1 = 0d;
            // i历元宽巷模糊度估计值
            double NW2 = 0d;
            // i+1历元宽巷模糊度估计值
            double NW3 = 0d;

            // i-1历元宽巷模糊度估计值精度
            double delta1 = 0d;
            // i历元宽巷模糊度估计值精度
            double delta2 = 0d;

            // GPS L1频率(Hz)
            double f1 = Common.GPS_F1;
            // GPS L2频率(Hz)
            double f2 = Common.GPS_F2;

            // GPS L1波长(m)
            double l1 = Common.GPS_L1;
            // GPS L2波长(m)
            double l2 = Common.GPS_L2;

            // L1精度(m)
            double dL1 = Common.DELTA_L1;
            // L2精度(m)
            double dL2 = Common.DELTA_L2;
            // P1精度(m)
            double dP1 = Common.DELTA_P1;
            // P2精度(m)
            double dP2 = Common.DELTA_P2;

            double vp1, vp2, vl1, vl2;

            GetMeas(arc[0], out vp1, out vp2, out vl1, out vl2, out dP1);
            // 初始化NW(i-1)
            NW1 = (1 / (f1 - f2) *
                   (f1 * vl1 * l1 - f2 * vl2 * l2) -
                   1 / (f1 + f2) *
                   (f1 * vp1 + f2 * vp2)) / Common.GPS_Lw;

            GetMeas(arc[1], out vp1, out vp2, out vl1, out vl2, out dP1);
            // 初始化NW(i)
            NW2 = (1 / (f1 - f2) *
                   (f1 * vl1 * l1 - f2 * vl2 * l2) -
                   1 / (f1 + f2) *
                   (f1 * vp1 + f2 * vp2)) / Common.GPS_Lw;

            // 初始化δ(i-1)
            delta1 = Math.Sqrt(
                1 / Math.Pow(f1 - f2, 2) * (f1 * f1 * dL1 + f2 * f2 * dL2) +
                1 / Math.Pow(f1 + f2, 2) * (f1 * f1 * dP1 + f2 * f2 + dP2)
                );

            // 前一历元gf值
            double lstGF = arc[0]["GF"];
            // 当前历元gf值
            double curGF = arc[0]["GF"];

            int arcLen = arc.Length - 1;

            for (int i = 1; i < arcLen; i++)
            {
                if (!GetMeas(arc[i + 1], out vp1, out vp2, out vl1, out vl2, out _))
                {
                    index = i + 1;
                    return(true);
                }

                NW3 = (1 / (f1 - f2) *
                       (f1 * vl1 * l1 - f2 * vl2 * l2) -
                       1 / (f1 + f2) *
                       (f1 * vp1 + f2 * vp2)) / Common.GPS_Lw;

                delta2 = Math.Sqrt(delta1 * delta1 * i / (i + 1) + Math.Pow(NW2 - NW1, 2) / (i + 1));

                // MW探测
                if (Math.Abs(NW2 - NW1) > 4 * delta1)
                {
                    if (Math.Abs(NW3 - NW2) < 1)
                    {
                        arc[i].CycleSlip = true;
                    }
                    else
                    {
                        arc[i].Outlier = true;
                    }

                    // 有周跳,分割成新弧段
                    //OArc newArc = arc.Split(i + 1);
                    //arc.Station.Arcs[arc.PRN].Add(newArc);
                    index = i + 1;
                    Common.msgBox.Print(string.Format("\r\n检测到周跳,时间:{0},历元:{1:0000},编号:{2}", arc[i + 1].Epoch, i + 1 + arc.StartIndex, arc[i + 1].SatPRN));
                    return(true);
                }

                NW1    = NW1 * i / (i + 1) + NW2 / (i + 1);
                NW2    = NW3;
                delta1 = delta2;

                lstGF = curGF;
                curGF = arc[i]["GF"];
                if (arc[i].CycleSlip || arc[i].Outlier)
                {
                    continue;
                }

                // GF探测
                if (!arc[i].CycleSlip)
                {
                    if (Math.Abs(curGF - lstGF) > Options.Threshold_GF)
                    {
                        arc[i].CycleSlip = true;
                    }
                }

                // 检查LLI
                if (!arc[i].CycleSlip)
                {
                    if (arc[i]["L1"] == 1 || arc[i]["L2"] == 1)
                    {
                        arc[i].CycleSlip = true;
                    }
                }
            }
            return(false);
        }
Пример #26
0
 public static float DefineDistance(Vec2 A, Vec2 B)
 {
     return((float)Math.Sqrt(Math.Pow(B.X - A.X, 2) + Math.Pow(B.Y - A.Y, 2)));
 }
Пример #27
0
        private static double StandardDeviation(IEnumerable <double> values)
        {
            double avg = values.Average();

            return(MathObj.Sqrt(values.Average(v => MathObj.Pow(v - avg, 2))));
        }
Пример #28
0
            /// <summary>
            /// The derivative of the phi function.
            /// https://www.wolframalpha.com/input/?i=derivative+of+a*(1-x*tanh(x))%2Bb*tanh(x)
            /// </summary>
            private static double dPhi(double s, double A, double B)
            {
                double sech_squared = 1 / Math.Pow(Math.Cosh(s), 2);

                return(A * (-Math.Tanh(s) - s * sech_squared) + B * sech_squared);
            }
Пример #29
0
        public static float[,] CalculateGaussianKernel(int W, double sigma)
        {
            float[,] kernel = new float[W, W];
            double mean = W / 2.0;
            float  sum  = 0.0f;

            for (int x = 0; x < W; ++x)
            {
                for (int y = 0; y < W; ++y)
                {
                    kernel[x, y] = (float)(Math.Exp(-0.5 * (Math.Pow((x - mean) / sigma, 2.0) + Math.Pow((y - mean) / sigma, 2.0)))
                                           / (2 * Math.PI * sigma * sigma));
                    sum += kernel[x, y];
                }
            }

            for (int x = 0; x < W; ++x)
            {
                for (int y = 0; y < W; ++y)
                {
                    kernel[x, y] *= (1.0f) / sum;
                }
            }

            return(kernel);
        }
Пример #30
0
        public void Test_Point_Crossover()
        {
            double prob   = 0.25;
            int    points = 5;
            int    length = 50;

            while (prob <= 1.0)
            {
                var crossover = new PointCrossover(points)
                {
                    Probability = prob
                };

                this.Test_Crossover(() => crossover, length,
                                    (p1, p2, child) =>
                {
                    bool result = false;

                    var sequence = child.Sequence;

                    double count1 = p1.Sequence.Intersect(sequence).Count();
                    double count2 = p2.Sequence.Intersect(sequence).Count();

                    double p = (MATH.Pow(prob, points)) / 2;

                    double c1 = 0, c2 = 0;

                    int i; double diff; double t1 = 0, t2 = 0;
                    for (i = 0; i < crossover.Points.Length - 1; i++)
                    {
                        diff = (crossover.Points[i + 1] - crossover.Points[i]);

                        if (i % 2 == 0)
                        {
                            c1 += diff;
                            t1 += (diff / length) * (1.0 - p);
                        }
                        else
                        {
                            c2 += diff;
                            t2 += (diff / length) * p;
                        }
                    }

                    diff = length - crossover.Points[i];

                    if (i % 2 == 0)
                    {
                        c1 += diff;
                        t1 += (diff / length) * (1.0 - p);
                    }
                    else
                    {
                        c2 += diff;
                        t2 += (diff / length) * p;
                    }

                    t1 = t1 / (t1 + t2);
                    t2 = t2 / (t1 + t2);

                    result = (t1 >= (1.0 - p * 2.0) && t2 <= p * 2.0);

                    return(result);
                });

                prob += 0.25;
            }
        }