private decimal CalculatePriceForProductOrder(ProductOrder item)
        {
            decimal price       = 0;
            var     pricingRule = item.Product.PricingRule;

            if (pricingRule == null)
            {
                // standard pricing
                price = item.Quantity * item.Product.UnitPrice;
            }
            else
            {
                if (pricingRule.Quantity <= 0)
                {
                    throw new ArgumentOutOfRangeException("Cannot calculate price with invalid quantity on pricing rule");
                }

                if (pricingRule.Price <= 0)
                {
                    throw new ArgumentOutOfRangeException("Cannot calculate price with invalid pricing rule");
                }

                var nbrOfUnits = UnitsConverter.GetEquivalentUnit(item.Product.MeasureUnit, pricingRule.MeasureUnit);
                //price = item.Quantity * item.Product.UnitPrice;

                if (nbrOfUnits < 1)
                {
                    // don't apply the pricing rule
                    price = nbrOfUnits * item.Product.UnitPrice * item.Quantity;
                }
                else
                {
                    // apply the pricing rule
                    // get the total qunatity after unit conversion
                    var totalQty = item.Quantity * nbrOfUnits;

                    // calculate the number of discounts corresponding to pricing rule
                    var nbrOfDiscounts = Math.Floor(totalQty / pricingRule.Quantity);

                    // calculate the remaing quantity price
                    // may be calculated with applied pricing rule or with initial price
                    var restQty = totalQty % pricingRule.Quantity;

                    price = nbrOfDiscounts * pricingRule.Price;

                    // calculate the price of remaing quantity depending on the pricing rule
                    if (item.Product.UnitPrice > 0)
                    {
                        price += restQty * item.Product.UnitPrice;
                    }
                    else
                    {
                        // calculate the unitprice from princing rule
                        price += restQty * (pricingRule.Price / pricingRule.Quantity);
                    }
                }
            }

            return(price);
        }
Ejemplo n.º 2
0
        public void Update(GameTime dt)
        {
            ITransformable trans = Data[0] as ITransformable;
            Body           body1 = Data[1] as Body;
            Body           body2 = Data[2] as Body;

            bool ok = (trans != null && body1 != null && body2 != null);

            if (!ok)
            {
                return;
            }

            Vector2 line        = body2.Position - body1.Position;
            Vector2 newPosition = body1.Position + line / 2;

            line.Normalize();

            float newRotation = ( float )Math.Acos(line.X) * Math.Sign(Math.Asin(line.Y));

            float rotationDelta = Math.Abs(newRotation - _lastBodyRotation);
            float positionDelta = (newPosition - _lastBodyPosition).LengthSquared();

            if (rotationDelta > RotationError || positionDelta > PositionError)
            {
                trans.SetPosition(new Vector3(UnitsConverter.ToDisplayUnits(newPosition), 0f));
                trans.SetRotation(UnitsConverter.To3DRotation(newRotation));

                _lastBodyPosition = newPosition;
                _lastBodyRotation = newRotation;
            }
        }
    public void Repair(GameObject menuItem)
    {
        AudioManager.Instance.AudioSources["Tap"].Play();
        UpgradeTypes itemType     = menuItem.GetComponent <GUIMenuItem>().type;
        Upgrade      ownedUpgrade = instance.upgrades.GetOwnedUpgrade(itemType);

        float  healthBefore = ownedUpgrade.health;
        double repairCost   = ownedUpgrade.GetRepairCost();

        instance.speed.points -= repairCost;
        instance.upgradesController.RepairUpgrade(itemType);

        Text[] comps  = menuItem.GetComponentsInChildren <Text>();
        Text   txt    = comps[1];
        double hvalue = ownedUpgrade.health;
        string hunit  = "";

        UnitsConverter.Convert(ref hvalue, ref hunit);
        txt.text = "Health: " + hvalue.ToString("f" + instance.healthDecimals) + hunit;
        txt      = comps[2];
        double rvalue = ownedUpgrade.GetRepairCost();
        string runit  = "";

        UnitsConverter.Convert(ref rvalue, ref runit);
        txt.text = "Repair: $" + rvalue.ToString("f" + instance.priceDecimals) + runit;

        //rather than updating values of all items we just fix the value for the repaired item and update total with difference
        float healthAfter = ownedUpgrade.health;

        instance.totalHealth      += (healthAfter - healthBefore);
        instance.totalRepairPrice -= repairCost;
    }
        public SentientForceComponent()
        {
            Data = new List <object>();

            _type = ComponentType.SentientForce;

            float    distance  = UnitsConverter.ToSimUnits(Distance);
            Vertices coneShape = new Vertices();

            coneShape.Add(Vector2.Zero);

            coneShape.Add(new Vector2(( float )Math.Cos(-Angle / 2), ( float )Math.Sin(-Angle / 2)) * distance);
            coneShape.Add(new Vector2(( float )Math.Cos(-Angle / 4), ( float )Math.Sin(-Angle / 4)) * distance);
            coneShape.Add(new Vector2(1f, 0f) * distance);
            coneShape.Add(new Vector2(( float )Math.Cos(Angle / 4), ( float )Math.Sin(Angle / 4)) * distance);
            coneShape.Add(new Vector2(( float )Math.Cos(Angle / 2), ( float )Math.Sin(Angle / 2)) * distance);

            Cone          = new Body(Platform.Instance.PhysicsWorld);
            Cone.IsSensor = true;
            Cone.BodyType = BodyType.Dynamic;

            Cone.Position = Vector2.Zero;
            FixtureFactory.AttachPolygon(coneShape, 0f, Cone);

            _oldPosition = Vector2.Zero;
            UnitsConverter.ToSimUnits(Distance);

            if (GameWorldManager.Instance.GetEntity("saf1") == null)
            {
                GameWorldManager.Instance.SpawnEntity("Saf", "saf1", new Vector3(0, 0, 0), 15);
            }
            ConeEntity = GameWorldManager.Instance.GetEntity("saf1");
        }
Ejemplo n.º 5
0
        private string FormatDouble(MailTagTypes type, string param)
        {
            double      value = _factory.GetDoubleValue(type);
            SIUnitTypes unit  = ProgramSettings.Instance.ShowUnitType;

            Match paramMatch = Regex.Match(param, METHOD_PARAM, RegexOptions.IgnoreCase);

            while (paramMatch.Success)
            {
                if (paramMatch.Groups["method"].Value.ToUpper() == "ROUND")
                {
                    value = System.Math.Round(value, Int32.Parse(paramMatch.Groups["param"].Value));
                }
                else if (paramMatch.Groups["method"].Value.ToUpper() == "UNIT")
                {
                    switch (paramMatch.Groups["param"].Value.ToUpper())
                    {
                    case "G": unit = SIUnitTypes.Go; break;

                    case "M": unit = SIUnitTypes.Mo; break;

                    case "K": unit = SIUnitTypes.ko; break;
                    }
                }
                paramMatch = paramMatch.NextMatch();
            }

            return(UnitsConverter.SIUnitToString(value, unit));
        }
    public void UpdateMenu()
    {
        foreach (GameObject menuItem in menuItems)
        {
            if (menuItem == null)
            {
                break;
            }
            UpgradeTypes itemType     = menuItem.GetComponent <GUIMenuItem>().type;
            Upgrade      ownedUpgrade = upgrades.GetOwnedUpgrade(itemType);

            Text[] comps   = menuItem.GetComponentsInChildren <Text>();
            Text   txt     = comps[1];
            double hvalue  = ownedUpgrade.health;
            double mhvalue = ownedUpgrade.GetCurrentLevelHealth();
            string hunit   = "";
            string mhunit  = "";
            UnitsConverter.Convert(ref hvalue, ref hunit);
            UnitsConverter.Convert(ref mhvalue, ref mhunit);
            txt.text = "Health: " + hvalue.ToString("f" + healthDecimals) + hunit + "/" + mhvalue.ToString("f" + healthDecimals) + mhunit;
            txt      = comps[2];
            double repairCost = ownedUpgrade.GetRepairCost();
            string runit      = "";
            UnitsConverter.Convert(ref repairCost, ref runit);
            txt.text = "Repair: $" + repairCost.ToString("f" + priceDecimals) + runit;
        }
    }
Ejemplo n.º 7
0
        protected override void Initialize()
        {
            base.Initialize();
#if WINDOWS
            _guiManager.Initialize();
#endif
            Platform.Instance.PhysicsWorld = new World(new Vector2(0f, 9.82f));

            Platform.Instance.Settings = new Settings();
            Platform.Instance.Settings.Load();
            Platform.Instance.SoundManager = new SoundManager(Platform.Instance.Settings);
            UnitsConverter.SetDisplayUnitToSimUnitRatio(64);

            InitializeInput();

#if USE_KINECT
            _kinectChooser.Initialize();
            _kinectChooser.DiscoverSensor();
#endif

            PhysicsContactManager.Instance.Initialize();
#if MODEL_VIEW
            StateManager.Instance.ChangeState(GameState.ModelView);
#elif EDITOR
            StateManager.Instance.ChangeState(GameState.Editor);
#elif TUTORIAL
            StateManager.Instance.ChangeState(GameState.TutorialLevel);
#else
            StateManager.Instance.ChangeState(GameState.Menu);
#endif
        }
Ejemplo n.º 8
0
    // Update is called once per frame
    void Update()
    {
        float currentTime = Time.time;

        if (currentTime > lastTime + updateInterval)
        {
            float seconds = Mathf.Floor((float)speed.ETA % 60.0f);
            float minutes = Mathf.Floor(((float)speed.ETA / 60.0f) % 60.0f);
            float hours   = Mathf.Floor(((float)speed.ETA / 3600.0f) % 24.0f);
            float days    = Mathf.Floor((float)speed.ETA / 86400);

            double val   = (double)days;
            string vunit = "";
            UnitsConverter.Convert(ref val, ref vunit);
            if (vunit == " Infinity")
            {
                displayText.text = "ETA: N/A";
            }
            else
            {
                displayText.text = "ETA: " + val.ToString("f0") + vunit + " d " + hours + "h " + minutes + "m " + seconds + "s";
            }
            lastTime = currentTime;
        }
    }
Ejemplo n.º 9
0
        private void CalculateFixedDeflection()
        {
            double desiredSpineAMO = radioInput2.Checked ?
                                     (double)numericInput2.Value :
                                     UnitsConverter.ASTMtoAMO((double)numericInput1.Value);

            double rawTension = Spinetester.instance.CurrentArrow.Spine.Raw;

            //double tension = 6750.87 * 0.06479891 / 1000.0; //* 0.00006479891

            // 5-15mm range
            double closestDeflection = 10.0;

            //for (double i = 1.0; i >= 0.01; i *= 0.1)
            //    closestDeflection = FindSpineClosestDeflection(tension, desiredSpineAMO, closestDeflection, i);

            // First pass 1.0
            closestDeflection = FindSpineClosestDeflection(rawTension, desiredSpineAMO, closestDeflection, 1.0);

            // Second pass 0.1
            closestDeflection = FindSpineClosestDeflection(rawTension, desiredSpineAMO, closestDeflection, 0.1);

            // Third pass 0.01
            closestDeflection = FindSpineClosestDeflection(rawTension, desiredSpineAMO, closestDeflection, 0.01);


            SetNumericValue(numericCalibration, (decimal)closestDeflection);
        }
Ejemplo n.º 10
0
        public void Update(GameTime dt)
        {
            ITransformable trans  = Data[0] as ITransformable;
            Body           body   = Data[1] as Body;
            GameEntity     entity = Data[2] as GameEntity;

            bool ok = (trans != null && body != null && entity != null);

            if (!ok)
            {
                return;
            }

            float rotationDelta = Math.Abs(body.Rotation - _lastBodyRotation);
            float positionDelta = (body.Position - _lastBodyPosition).LengthSquared();

            if (rotationDelta > RotationError || positionDelta > PositionError || entity.HasExternalRotation())
            {
                trans.SetPosition(new Vector3(UnitsConverter.ToDisplayUnits(body.Position), trans.GetPosition().Z));
                trans.SetRotation(UnitsConverter.To3DRotation(body.Rotation) * entity.GetExternalRotation());

                _lastBodyPosition = body.Position;
                _lastBodyRotation = body.Rotation;
            }
        }
 public override void Update(GameTime dt)
 {
     if (Entity != null)
     {
         Vector3 position = UnitsConverter.ToSimUnits(Entity.GetPosition());
         Area.Position = new Vector2(position.X, position.Y);
     }
 }
Ejemplo n.º 12
0
 protected float ToMeters(float units)
 {
     if (m_convertUnits && m_settings != null && m_settings.SystemOfMeasurement == SystemOfMeasurement.Imperial)
     {
         return(UnitsConverter.FeetToMeters(units));
     }
     return(units);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Attaches the specified Xref to the current space in the current drawing.
        /// </summary>
        /// <param name="path">Path to the drawing file to attach as an Xref.</param>
        /// <param name="pos">Position of Xref in WCS coordinates.</param>
        /// <param name="name">Optional name for the Xref.</param>
        /// <returns>Whether the attach operation succeeded.</returns>
        public static bool XrefAttachAndInsert(this Database db, string path, Point3d pos, string name = null, bool overlay = false)
        {
            var ret = false;

            if (!File.Exists(path))
            {
                return(ret);
            }
            if (String.IsNullOrEmpty(name))
            {
                name = Path.GetFileNameWithoutExtension(path);
            }
            // We'll collect any xref definitions that need reloading after our
            // transaction (there should be at most one)
            var xIds = new ObjectIdCollection();

            try
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    // Attach or overlay the Xref - add it to the database's block table
                    var xId =
                        overlay ? db.OverlayXref(path, name) : db.AttachXref(path, name);
                    if (xId.IsValid)
                    {
                        // Open the newly created block, so we can get its units
                        var xbtr = (BlockTableRecord)tr.GetObject(xId, OpenMode.ForRead);
                        // Get the path of the current drawing
                        var loc = Path.GetDirectoryName(db.Filename);
                        if (xbtr.ChangePathToRelative(loc))
                        {
                            xIds.Add(xId);
                        }
                        // Determine the unit conversion between the xref and the target
                        // database
                        var sf = UnitsConverter.GetConversionFactor(xbtr.Units, db.Insunits);
                        // Create the block reference and scale it accordingly
                        var br = new BlockReference(pos, xId);
                        br.ScaleFactors = new Scale3d(sf);
                        // Add the block reference to the current space and the transaction
                        var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                        btr.AppendEntity(br);
                        tr.AddNewlyCreatedDBObject(br, true);
                        ret = true;
                    }
                    tr.Commit();
                }
                // If we modified our xref's path, let's reload it
                if (xIds.Count > 0)
                {
                    //db.ReloadXrefs(xIds);
                    System.Windows.Forms.MessageBox.Show("You need reload Xrefs!");
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception)
            { }
            return(ret);
        }
Ejemplo n.º 14
0
        public Quaternion GetRotation()
        {
            if (MainBody != null && PhysicsEntity.Enabled)
            {
                return(UnitsConverter.To3DRotation(MainBody.Rotation));
            }

            return(MainNode.GetRotation());
        }
Ejemplo n.º 15
0
    // Update is called once per frame
    void Update()
    {
        double value = (double)(entity.GetComponent <Speed>().GetType().GetField(var).GetValue(entity.GetComponent <Speed>()));

        string unit = "";

        UnitsConverter.Convert(ref value, ref unit);
        text.text = "" + value.ToString("f" + numberOfDecimals) + unit + " " + postfix;
    }
Ejemplo n.º 16
0
 /// <summary>
 /// Отрисовать картинку глифа.
 /// </summary>
 /// <param name="gfx">Graphics.</param>
 protected override void DrawGlyph(Graphics gfx)
 {
     gfx.DrawLine(
         Pens.Black,
         UnitsConverter.MMToPx(FirstPoint.XInMM),
         UnitsConverter.MMToPx(FirstPoint.YInMM),
         UnitsConverter.MMToPx(SecondPoint.XInMM),
         UnitsConverter.MMToPx(SecondPoint.YInMM));
 }
Ejemplo n.º 17
0
 public GameStateEditor(ContentManager content)
 {
     _contentManager    = content;
     _saveAction        = false;
     _inputAggregator   = Platform.Instance.Input;
     _debugViewGridstep = UnitsConverter.ToSimUnits(1f);
     _gridColor         = new Color(128, 128, 128, 80);
     _debugViewGrid     = true;
 }
 private WeatherResult MapResponseToWeatherResult(OpenWeatherMapResponse response)
 {
     return(response == null ? null : new WeatherResult(
                response.WeatherDescription?.FirstOrDefault()?.Title,
                response.WeatherDescription?.FirstOrDefault()?.FullDescription,
                (int)Math.Round(UnitsConverter.ConvertTemperatureKelvinToCelsius((double)(response.WeatherGeneralInformation?.Temperature ?? 0M)), 0),
                response.WeatherGeneralInformation?.Pressure ?? 0
                ));
 }
Ejemplo n.º 19
0
    // Update is called once per frame
    void Update()
    {
        double value = speed.currentPlanet.distanceToTravel;

        string unit = "";

        UnitsConverter.Convert(ref value, ref unit);
        text.text = "" + value.ToString("f" + numberOfDecimals) + unit + " " + postfix;
    }
Ejemplo n.º 20
0
        public Vector3 GetPosition()
        {
            if (MainBody != null && PhysicsEntity.Enabled)
            {
                return(new Vector3(UnitsConverter.ToDisplayUnits(MainBody.Position), MainNode.GetPosition().Z));
            }

            return(MainNode.GetPosition());
        }
Ejemplo n.º 21
0
        public override void OnUpdate(GameTime gameTime)
        {
            if (!_levelLoaded)
            {
                return;
            }

            base.OnUpdate(gameTime);
            _pausePhysics = true;


            if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && Keyboard.GetState().IsKeyDown(Keys.S) && !_saveAction)
            {
                _saveAction = true;
                GameWorldManager.Instance.SaveState();
                _level = PrefabRepository.Instance.GetLevelPrefab(@"Content\Levels\" + _levelName + ".eql");
                _level.SetState(GameWorldManager.Instance.GetState());
                _level.SerializeLevel();
                HintManager.Instance.SpawnHint("Saved " + _levelName, new Vector2(200, 200), 5000, 13);
            }
            else if (Keyboard.GetState().IsKeyUp(Keys.S) || Keyboard.GetState().IsKeyUp(Keys.LeftControl))
            {
                _saveAction = false;
            }

            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.D))
            {
                if (!_actionToggleDebugView)
                {
                    _debugViewState        = !_debugViewState;
                    _actionToggleDebugView = true;
                }
            }

            if (Keyboard.GetState(PlayerIndex.One).IsKeyUp(Keys.D))
            {
                _actionToggleDebugView = false;
            }

            if (_inputAggregator.HasEvent(UISButton.G, true))
            {
                _debugViewGrid = !_debugViewGrid;
            }

            // debug view segments
            _debugViewGridstep = UnitsConverter.ToSimUnits(1f);
            if (_inputAggregator.HasEvent(UISButton.LeftControl) || _inputAggregator.HasEvent(UISButton.RightControl))
            {
                _debugViewGridstep *= 2f;
            }
            else if (_inputAggregator.HasEvent(UISButton.LeftShift) || _inputAggregator.HasEvent(UISButton.RightShift))
            {
                _debugViewGridstep *= 0.1f;
            }
        }
Ejemplo n.º 22
0
 public void SetExternalRotation(float newRot)
 {
     if (PhysicsEntity.Enabled)
     {
         _externalRotation = UnitsConverter.To3DRotation(newRot);
     }
     else
     {
         MainNode.SetRotation(UnitsConverter.To3DRotation(newRot));
     }
 }
Ejemplo n.º 23
0
 public void SetRotation(float newRot)
 {
     if (MainBody != null && PhysicsEntity.Enabled)
     {
         PhysicsEntity.SetRotation(MainBody, newRot);
     }
     else
     {
         MainNode.SetRotation(UnitsConverter.To3DRotation(newRot));
     }
 }
        public void Given_I_Have_A_Value_Of_7_The_Value_Returned_Should_Be_Seven()
        {
            // Given I have a value of 7
            var value = 7;
            // When I pass the value into the word converter
            IUnitsConverter converter = new UnitsConverter();
            string          result    = converter.ConvertSingleNumberToWord(value);

            // Then I expect the value returned is "seven"
            Assert.AreEqual("seven", result);
        }
Ejemplo n.º 25
0
 public void SetPosition(Vector3 newPos)
 {
     if (MainBody != null && PhysicsEntity.Enabled)
     {
         PhysicsEntity.SetPosition(MainBody, UnitsConverter.ToSimUnits(new Vector2(newPos.X, newPos.Y)));
         MainNode.SetPosition(Vector3.UnitZ * newPos.Z);
     }
     else
     {
         MainNode.SetPosition(newPos);
     }
 }
Ejemplo n.º 26
0
        public void AttachToBody(Body body, Vector2 scale)
        {
            float scaleD = (scale.X + scale.Y) / 2f;

            switch (Type)
            {
            case ShapeType.Circle:
                FixtureFactory.AttachCircle(UnitsConverter.ToSimUnits(XRadius) * scaleD, Density, body);
                break;

            case ShapeType.Ellipse:
                FixtureFactory.AttachEllipse(UnitsConverter.ToSimUnits(XRadius) * scale.X, UnitsConverter.ToSimUnits(YRadius) * scale.Y, Edges, Density, body);
                break;

            case ShapeType.Edge:
                FixtureFactory.AttachEdge(UnitsConverter.ToSimUnits(Start) * scale, UnitsConverter.ToSimUnits(End) * scale, body);
                break;

            case ShapeType.Rectangle:
                FixtureFactory.AttachRectangle(UnitsConverter.ToSimUnits(Width) * scale.X, UnitsConverter.ToSimUnits(Height) * scale.Y, Density, UnitsConverter.ToSimUnits(Offset) * scale, body);
                break;

            case ShapeType.Polygon:

                Vertices p = new Vertices();
                foreach (Vector2 node in Polygon[0])
                {
                    p.Add(UnitsConverter.ToSimUnits(node) * scale);
                }

                FixtureFactory.AttachPolygon(p, Density, body);
                break;

            case ShapeType.CompoundPolygon:

                List <Vertices> cp = new List <Vertices>();
                foreach (Vertices v in Polygon)
                {
                    Vertices polygon = new Vertices();
                    foreach (Vector2 node in v)
                    {
                        polygon.Add(UnitsConverter.ToSimUnits(node) * scale);
                    }
                    cp.Add(polygon);
                }

                FixtureFactory.AttachCompoundPolygon(cp, Density, body);
                break;

            default:
                return;
            }
        }
        protected override void UpdateOverride()
        {
            base.UpdateOverride();

            RaycastHit hit;

            if (Physics.Raycast(Window.Pointer, out hit))
            {
                Vector3 point = SnapToVertex(hit.point);

                if (Editor.Input.GetPointerDown(0))
                {
                    if (m_points.Count == 2)
                    {
                        m_points.Clear();
                    }
                    else
                    {
                        m_points.Add(point);
                        m_points.Add(point);
                    }

                    Renderer.Vertices = m_points.ToArray();
                    Renderer.Refresh();
                }
                else
                {
                    PointerRenderer.transform.position = point;

                    if (m_points.Count == 2)
                    {
                        m_points[1]       = point;
                        Renderer.Vertices = m_points.ToArray();
                        Renderer.Refresh(true);
                    }

                    if (Output != null)
                    {
                        Output.transform.position = point;
                        if (m_points.Count == 2)
                        {
                            float mag = (m_points[1] - m_points[0]).magnitude;
                            Output.text  = m_metric ? mag.ToString("F2") : UnitsConverter.MetersToFeetInches(mag);
                            Output.text += System.Environment.NewLine + System.Environment.NewLine;
                        }
                        else
                        {
                            Output.text = "";
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
        protected override void OnTimedUpdate()
        {
            base.OnTimedUpdate();

            SetText(labelGrainsL, Spinetester.instance.Tension.Left.ToString("0.0"));
            SetText(labelGrainsR, Spinetester.instance.Tension.Right.ToString("0.0"));
            SetText(labelGrainsVal, Spinetester.instance.Tension.Total.ToString("0.0"));

            SetText(labelGramsL, UnitsConverter.GrainsToGrams(Spinetester.instance.Tension.Left).ToString("0.0"));
            SetText(labelGramsR, UnitsConverter.GrainsToGrams(Spinetester.instance.Tension.Right).ToString("0.0"));
            SetText(labelGramsVal, UnitsConverter.GrainsToGrams(Spinetester.instance.Tension.Total).ToString("0.0"));
        }
    void BuildMenu()
    {
        totalRepairPrice = 0;
        totalHealth      = 0;
        totalMaxHealth   = 0;
        int j = 0;

        foreach (KeyValuePair <UpgradeTypes, Upgrade> upgradeItem in ownedUpgrades)
        {
            if (upgradeItem.Key != UpgradeTypes.Clicker && upgradeItem.Key != UpgradeTypes.AutoPilot1h && upgradeItem.Key != UpgradeTypes.AutoPilot6h && upgradeItem.Key != UpgradeTypes.AutoPilot12h && upgradeItem.Key != UpgradeTypes.AutoPilot3d && upgradeItem.Key != UpgradeTypes.AutoPilot1w)
            {
                Upgrade upgrade = upgradeItem.Value;

                string name       = upgrade.type.ToString();
                float  health     = upgrade.health;
                double repaircost = upgrade.GetRepairCost();
                float  maxhealth  = upgrade.GetCurrentLevelHealth();

                totalRepairPrice += repaircost;
                totalHealth      += health;
                totalMaxHealth   += maxhealth;

                GameObject menuItem = GameObject.Instantiate(Resources.Load("Prefabs/RepairMenuItem")) as GameObject;
                menuItem.GetComponentInChildren <UpdateItemHealthBar> ().SetItemUpgrade(upgrade);
                menuItem.GetComponent <GUIMenuItem>().type = upgrade.type;

                Text[] comps = menuItem.GetComponentsInChildren <Text>();
                Text   txt   = comps[0];
                txt.text = name.ToUpper();
                txt      = comps[1];
                double hvalue  = (double)health;
                double mhvalue = (double)maxhealth;
                string hunit   = "";
                string mhunit  = "";
                UnitsConverter.Convert(ref hvalue, ref hunit);
                UnitsConverter.Convert(ref mhvalue, ref mhunit);
                txt.text = "Health: " + hvalue.ToString("f" + healthDecimals) + hunit + "/" + mhvalue.ToString("f" + healthDecimals) + mhunit;
                txt      = comps[2];
                string runit = "";
                UnitsConverter.Convert(ref repaircost, ref runit);
                txt.text = "Repair: $" + repaircost.ToString("f" + priceDecimals) + runit;

                menuItem.transform.SetParent(transform, false);

                menuItems[j] = menuItem;
                //parent = menuItems[i].transform;
                j++;
            }
        }
        //menuItems [3].transform.SetSiblingIndex (0);
    }
Ejemplo n.º 30
0
        /// <summary>
        /// Creates maps based on surface results. The maps can be displayed in the documentation.
        /// </summary>
        /// <param name="element">Revit element for which result document is built</param>
        /// <param name="resultsInPoints">Result in point collection</param>
        /// <param name="resultTypes">The type of results, values and description that can be displayed on the maps.</param>
        /// <returns>Returns list of documets maps based on results that can be displayed in the documentation</returns>
        private List <DocumentMap> CreateResultMapSeriesForSurfaceElements(Element element, ICollection <ResultInPointSurface> resultsInPoints, IEnumerable <Tuple <ResultTypeSurface, string> > resultTypes)
        {
            List <DocumentMap> vDocMap   = new List <DocumentMap>();
            MapDataGenerator   mapPoints = new MapDataGenerator();

            foreach (Tuple <ResultTypeSurface, string> forceDesc in resultTypes)
            {
                List <double> resData = resultsInPoints.Select(s => s[forceDesc.Item1]).ToList();
                if (resData.Max(s => (Math.Abs(s))) < 1.0e-8)
                {
                    continue;
                }
                AnalyticalModel slab        = element as AnalyticalModel;
                DisplayUnit     displayUnit = DisplayUnit.IMPERIAL;
                if (Server.UnitSystem == Autodesk.Revit.DB.ResultsBuilder.UnitsSystem.Metric)
                {
                    displayUnit = DisplayUnit.METRIC;
                }
                ElementAnalyser elementAnalyser = new ElementAnalyser(displayUnit);
                ElementInfo     info            = elementAnalyser.Analyse(element);
                XYZ             xyz             = new XYZ();
                if (info != null)
                {
                    foreach (ResultInPointSurface resInPt in resultsInPoints)
                    {
                        mapPoints.AddPoint(new XYZ(resInPt[ResultTypeSurface.X], resInPt[ResultTypeSurface.Y], resInPt[ResultTypeSurface.Z]), resInPt[forceDesc.Item1]);
                    }
                    var contourAndHoles = getContourAndHolePoints(info);
                    contourAndHoles.Item1.ForEach(s => mapPoints.AddPointToContour(s));
                    contourAndHoles.Item2.ForEach(s => mapPoints.AddHole(s));
                    UnitType    ut     = forceDesc.Item1.GetUnitType();
                    DocumentMap docMap = new DocumentMap(ut, UnitsConverter.GetInternalUnit(ut));
                    docMap.Title = forceDesc.Item2;
                    int nofPoints = mapPoints.Count;
                    for (int ptId = 0; ptId < nofPoints; ptId++)
                    {
                        UV pt = mapPoints.GetPoint(ptId);
                        docMap.AddPoint(pt.U, pt.V, mapPoints.GetValue(ptId));
                    }
                    List <List <int> > holes = mapPoints.Holes;
                    foreach (List <int> hole in holes)
                    {
                        docMap.AddHole(hole);
                    }
                    docMap.DefineContour(mapPoints.Contour);
                    vDocMap.Add(docMap);
                }
                mapPoints.Clear();
            }
            return(vDocMap);
        }