public void ParseUsingDefaults()
        {
            NumberFormatter fmt = new NumberFormatter("en-US");
            Assert.AreEqual(1234, fmt.Parse("1,234.00"));
            Assert.AreEqual(1234.56, fmt.Parse("1,234.56"));
            Assert.AreEqual(-1234, fmt.Parse("-1,234.00"));
            Assert.AreEqual(-1234.56, fmt.Parse("-1,234.56"));

            fmt = new NumberFormatter("sr-SP-Latn");
            Assert.AreEqual(1234, fmt.Parse("1.234,00"));
            Assert.AreEqual(1234.56, fmt.Parse("1.234,56"));
            Assert.AreEqual(-1234, fmt.Parse("-1.234,00"));
            Assert.AreEqual(-1234.56, fmt.Parse("-1.234,56"));
        }
        public void FormatUsingDefaults()
        {
            NumberFormatter fmt = new NumberFormatter("en-US");
            Assert.AreEqual("1,234.00", fmt.Format(1234));
            Assert.AreEqual("1,234.56", fmt.Format(1234.56));
            Assert.AreEqual("-1,234.00", fmt.Format(-1234));
            Assert.AreEqual("-1,234.56", fmt.Format(-1234.56));

            fmt = new NumberFormatter("sr-SP-Latn");
            Assert.AreEqual("1.234,00", fmt.Format(1234));
            Assert.AreEqual("1.234,56", fmt.Format(1234.56));
            Assert.AreEqual("-1.234,00", fmt.Format(-1234));
            Assert.AreEqual("-1.234,56", fmt.Format(-1234.56));
        }
Esempio n. 3
0
 public override Color StatusTextColor()
 {
     // Use color to inform heat levels
     return(NumberFormatter.GetNumberColor(MaxHeatLoad - this.HeatLevel, MaxHeatLoad, 0f));
 }
Esempio n. 4
0
 public new string ToLocaleString()
 {
     // NumberFormatter does the hard work.
     return(NumberFormatter.ToString(this.value, 10, CultureInfo.CurrentCulture.NumberFormat, NumberFormatter.Style.Regular));
 }
 public void FormatNonNumber()
 {
     NumberFormatter fmt = new NumberFormatter();
     fmt.Format("not a number");
 }
 public void FormatNullValue()
 {
     NumberFormatter fmt = new NumberFormatter();
     fmt.Format(null);
 }
 public void FormatNonNumber()
 {
     NumberFormatter fmt = new NumberFormatter();
     Assert.Throws<ArgumentException>(() => fmt.Format("not a number"));
 }
Esempio n. 8
0
        public JobStepAreaVM(EvaluationContext context, Step step, int stepIndex, int updateCount)
        {
            Index       = stepIndex;
            Title       = step.SourceExpression.Title;
            Description = step.SourceExpression.Description;
            ImageUrl    = "/Home/GetStepImage?stepIndex=" + stepIndex + "&updateCount=" + updateCount;

            ResultVariables = new ResultVariableVM[step.OutVariables.Length];
            for (int i = 0; i <= step.OutVariables.Length - 1; i++)
            {
                string variableName = step.OutVariables[i];
                object value        = context.GetValue(variableName);
                Style  style        = context.Plan.Styles.FirstOrDefault(j => j.Target == variableName);

                int        columnCount = 0;
                string[]   rowNames    = null;
                string[]   columnNames = null;
                string[][] cells       = null;
                string     displayText = null;
                string     url         = null;

                if (value == null)
                {
                    displayText = "?";
                }
                else if (value is Matrix || value is Vector)
                {
                    Matrix m = value is Matrix ? value as Matrix : new Matrix(1, (value as Vector).Size, (value as Vector).Items);
                    cells = new string[m.RowCount][];


                    string   styleRowName  = style == null || string.IsNullOrEmpty(style.RowName) ? null : style.RowName;
                    string[] styleRowNames = styleRowName == null || !styleRowName.Contains(",") ? null : styleRowName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


                    rowNames = new string[m.RowCount];
                    for (int row = 0; row <= m.RowCount - 1; row++)
                    {
                        string rowName;

                        if (styleRowNames != null)
                        {
                            rowName = row <= styleRowNames.Length - 1 ? styleRowNames[row] : string.Format(styleRowName, row + 1);
                        }
                        else
                        {
                            rowName = styleRowName == null ? (row + 1).ToString() : string.Format(style.RowName, row + 1);
                        }


                        rowNames[row] = rowName;
                    }

                    columnCount = m.ColumnCount;
                    columnNames = new string[m.ColumnCount];
                    for (int column = 0; column <= m.ColumnCount - 1; column++)
                    {
                        columnNames[column] = style == null || style.ColumnNames == null || column > style.ColumnNames.Length - 1 ? (column + 1).ToString() : style.ColumnNames[column];
                    }

                    for (int row = 0; row <= m.RowCount - 1; row++)
                    {
                        cells[row] = new string[m.ColumnCount];
                        for (int column = 0; column <= m.ColumnCount - 1; column++)
                        {
                            double d = m[row, column];
                            cells[row][column] = double.IsNaN(d) ? "-" : NumberFormatter.ForDecimalDigits(context.Settings.DecimalDigitCount).ToText(d);
                        }
                    }
                }
                else if (value is Bitmap)
                {
                    url = string.Format("/Home/GetResultImage?stepIndex={0}&variableIndex={1}&timestamp={2}", stepIndex, i, DateTime.Now.ToString());
                }
                else if (value is double)
                {
                    displayText = NumberFormatter.ForDecimalDigits(context.Settings.DecimalDigitCount).ToText((double)value);
                }
                else if (value is int[] || value is double[])
                {
                    Array items = value as Array;

                    StringBuilder b = new StringBuilder();
                    b.Append("[");

                    for (int j = 0; j <= items.Length - 1; j++)
                    {
                        b.Append(NumberFormatter.ForDecimalDigits(context.Settings.DecimalDigitCount).ToText(Convert.ToDouble(items.GetValue(j))));
                        b.Append(j < items.Length - 1 ? "," : "");
                    }

                    b.Append("]");


                    displayText = b.ToString();
                }
                else
                {
                    displayText = value.ToString().Replace("\r\n", "<br />");
                }


                ResultVariables[i] = new ResultVariableVM()
                {
                    Name        = step.OutVariables[i],
                    ColumnCount = columnCount,
                    RowNames    = rowNames,
                    ColumnNames = columnNames,
                    Cells       = cells,
                    Value       = displayText,
                    Url         = url,
                    Description = context.Plan.Variables.FirstOrDefault(m => m.Name == step.OutVariables[i]) == null ? "" : context.Plan.Variables.FirstOrDefault(m => m.Name == step.OutVariables[i]).Description
                };
            }

            InVariables = new InVariableVM[step.InSourceVariables.Length];
            for (int i = 0; i <= step.InSourceVariables.Length - 1; i++)
            {
                SourceVariable variable = step.InSourceVariables[i];

                InVariables[i] = new InVariableVM()
                {
                    Index       = i,
                    Name        = variable.Name,
                    Type        = Strings.Of(variable),
                    IsMatrix    = variable.Type == DataType.Matrix || variable.Type == DataType.Vector,
                    Value       = step.InValues[i] == null ? string.Empty : getValue(step.InValues[i], context),
                    Description = step.InSourceVariables[i].Description,
                };
            }
        }
Esempio n. 9
0
    private void SetText(string textTag, double value)
    {
        text.text = LocalizationManager.instance.StringForKey(textTag) + "<color=#22EE11>" + NumberFormatter.ToString(value, true, true) + "</color>?";

        noButton_Text.text  = LocalizationManager.instance.StringForKey("NoButtonText");
        yesButton_Text.text = LocalizationManager.instance.StringForKey("YesButtonText");
    }
    private void SetUpTexts(int index)
    {
        title.text              = LocalizationManager.instance.StringForKey("UpgradeEachFloor_Title");
        downPanelTitle.text     = LocalizationManager.instance.StringForKey("UpgradeEachFloor_DownPanelTitle");
        upgradeButton_Text.text = LocalizationManager.instance.StringForKey("UpgradeEachFloor_UpgradeButtonText");

        levelText.text  = LocalizationManager.instance.StringForKey("UpgradeEachFloor_Level");
        moneyText.text  = LocalizationManager.instance.StringForKey("UpgradeEachFloor_Money");
        profitText.text = LocalizationManager.instance.StringForKey("UpgradeEachFloor_Profit");
        costText.text   = LocalizationManager.instance.StringForKey("UpgradeEachFloor_Cost");

        if (index >= 3 && slot.DetermineMaximumNumberOfLevelsPlayerCanUpgrade() <= 0f)
        {
            levelValue.text  = slot.level + "+" + slot.DetermineMaximumNumberOfLevelsPlayerCanUpgrade();
            moneyValue.text  = "-";
            profitValue.text = "-";
            costValue.text   = "-";
            return;
        }

        levelValue.text = index < 3
            ?
                          slot.level + "<color=#8FFF64>" + "+" + Constant.BULK_UPGRADE_LEVELS[index] + "</color>" :
                          slot.level + "<color=#8FFF64>" + "+" + slot.DetermineMaximumNumberOfLevelsPlayerCanUpgrade() + "</color>";

        moneyValue.text = index < 3
            ?
                          moneyValue.text = "<color=#8FFF64>" + "+" + NumberFormatter.ToString(slot.CashPerSecondForLevel(Constant.BULK_UPGRADE_LEVELS[index]), true, true) + "/s" + "</color>" :
                                            moneyValue.text = "<color=#8FFF64>" + "+" + NumberFormatter.ToString(slot.CashPerSecondForLevel(slot.DetermineMaximumNumberOfLevelsPlayerCanUpgrade()), true, true) + "/s" + "</color>";

        profitValue.text = index < 3
            ?
                           LocalizationManager.instance.StringForKey("UpgradeEachFloor_Speed") + "<color=#8FFF64>" + " +" + Math.Round(slot.timeSpeedAfterEachUpgrade * Constant.BULK_UPGRADE_LEVELS[index], 2) + "s" + "</color>":
                           LocalizationManager.instance.StringForKey("UpgradeEachFloor_Speed") + "<color=#8FFF64>" + " +" + Math.Round(slot.timeSpeedAfterEachUpgrade * slot.DetermineMaximumNumberOfLevelsPlayerCanUpgrade(), 2) + "s" + "</color>";
        costValue.text = index < 3
            ?
                         NumberFormatter.ToString(slot.UpgreadeXLevelsCost(Constant.BULK_UPGRADE_LEVELS[index]), true) :
                         NumberFormatter.ToString(slot.UpgreadeMaxLevelsCost(), true);
    }
Esempio n. 11
0
        public static void WritePrimitiveValue(object value, object data, string literalValue, int maxStringLength, ref int column, NumberFormatter numberFormatter, Action <string, object, object> writer, Action <Role, string, object> writeToken)
        {
            if (literalValue != null)
            {
                Debug.Assert(data != null);
                writer(literalValue, null, data ?? BoxedTextColor.Text);
                column += literalValue.Length;
                return;
            }

            if (value == null)
            {
                // usually NullReferenceExpression should be used for this, but we'll handle it anyways
                writer("null", null, BoxedTextColor.Keyword);
                column += 4;
                return;
            }

            if (value is bool)
            {
                if ((bool)value)
                {
                    writer("true", null, BoxedTextColor.Keyword);
                    column += 4;
                }
                else
                {
                    writer("false", null, BoxedTextColor.Keyword);
                    column += 5;
                }
                return;
            }

            var s = value as string;

            if (s != null)
            {
                string tmp = "\"" + ConvertStringMaxLength(s, maxStringLength) + "\"";
                column += tmp.Length;
                writer(tmp, null, BoxedTextColor.String);
            }
            else if (value is char)
            {
                string tmp = "'" + ConvertCharLiteral((char)value) + "'";
                column += tmp.Length;
                writer(tmp, null, BoxedTextColor.Char);
            }
            else if (value is decimal)
            {
                string str = ((decimal)value).ToString(NumberFormatInfo.InvariantInfo) + "m";
                column += str.Length;
                writer(str, null, BoxedTextColor.Number);
            }
            else if (value is float)
            {
                float f = (float)value;
                if (float.IsInfinity(f) || float.IsNaN(f))
                {
                    // Strictly speaking, these aren't PrimitiveExpressions;
                    // but we still support writing these to make life easier for code generators.
                    writer("float", null, BoxedTextColor.Keyword);
                    column += 5;
                    writeToken(Roles.Dot, ".", BoxedTextColor.Operator);
                    if (float.IsPositiveInfinity(f))
                    {
                        writer("PositiveInfinity", null, BoxedTextColor.LiteralField);
                        column += "PositiveInfinity".Length;
                    }
                    else if (float.IsNegativeInfinity(f))
                    {
                        writer("NegativeInfinity", null, BoxedTextColor.LiteralField);
                        column += "NegativeInfinity".Length;
                    }
                    else
                    {
                        writer("NaN", null, BoxedTextColor.LiteralField);
                        column += 3;
                    }
                    return;
                }
                var number = f.ToString("R", NumberFormatInfo.InvariantInfo) + "f";
                if (f == 0 && 1 / f == float.NegativeInfinity)
                {
                    // negative zero is a special case
                    // (again, not a primitive expression, but it's better to handle
                    // the special case here than to do it in all code generators)
                    number = "-" + number;
                }
                column += number.Length;
                writer(number, value, BoxedTextColor.Number);
            }
            else if (value is double)
            {
                double f = (double)value;
                if (double.IsInfinity(f) || double.IsNaN(f))
                {
                    // Strictly speaking, these aren't PrimitiveExpressions;
                    // but we still support writing these to make life easier for code generators.
                    writer("double", null, BoxedTextColor.Keyword);
                    column += 6;
                    writeToken(Roles.Dot, ".", BoxedTextColor.Operator);
                    if (double.IsPositiveInfinity(f))
                    {
                        writer("PositiveInfinity", null, BoxedTextColor.LiteralField);
                        column += "PositiveInfinity".Length;
                    }
                    else if (double.IsNegativeInfinity(f))
                    {
                        writer("NegativeInfinity", null, BoxedTextColor.LiteralField);
                        column += "NegativeInfinity".Length;
                    }
                    else
                    {
                        writer("NaN", null, BoxedTextColor.LiteralField);
                        column += 3;
                    }
                    return;
                }
                string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
                if (f == 0 && 1 / f == double.NegativeInfinity)
                {
                    // negative zero is a special case
                    // (again, not a primitive expression, but it's better to handle
                    // the special case here than to do it in all code generators)
                    number = "-" + number;
                }
                if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0)
                {
                    number += ".0";
                }
                column += number.Length;
                writer(number, value, BoxedTextColor.Number);
            }
            else if (value is IFormattable)
            {
                string valueStr;
                switch (value)
                {
                case int v:
                    valueStr = numberFormatter.Format(v);
                    break;

                case uint v:
                    valueStr = numberFormatter.Format(v) + "U";
                    break;

                case long v:
                    valueStr = numberFormatter.Format(v) + "L";
                    break;

                case ulong v:
                    valueStr = numberFormatter.Format(v) + "UL";
                    break;

                case byte v:
                    valueStr = numberFormatter.Format(v);
                    break;

                case ushort v:
                    valueStr = numberFormatter.Format(v);
                    break;

                case short v:
                    valueStr = numberFormatter.Format(v);
                    break;

                case sbyte v:
                    valueStr = numberFormatter.Format(v);
                    break;

                default:
                    valueStr = ((IFormattable)value).ToString(null, NumberFormatInfo.InvariantInfo);
                    break;
                }
                writer(valueStr, value, BoxedTextColor.Number);
                column += valueStr.Length;
            }
            else
            {
                s = value.ToString();
                writer(s, null, CSharpMetadataTextColorProvider.Instance.GetColor(value));
                column += s.Length;
            }
        }
Esempio n. 12
0
        public override void WritePrimitiveValue(object value, object data = null, string literalValue = null)
        {
            var numberFormatter = NumberFormatter.GetCSharpInstance(hex: false, upper: true);

            WritePrimitiveValue(value, data, literalValue, maxStringLength, ref column, numberFormatter, (a, b, c) => textWriter.Write(a), WriteToken);
        }
Esempio n. 13
0
 private void Release()
 {
     if (this != userFormatProvider)
         threadNumberFormatter = this;
 }
Esempio n. 14
0
            private static NumberFormatter GetInstance(IFormatProvider fp)
            {
                if (fp != null)
                {
                    if (userFormatProvider == null)
                    {
                        Interlocked.CompareExchange(ref userFormatProvider, new NumberFormatter(null), null);
                    }

                    return userFormatProvider;
                }

                NumberFormatter res = threadNumberFormatter;
                threadNumberFormatter = null;
                if (res == null)
                    return new NumberFormatter(Thread.CurrentThread);
                res.CurrentCulture = Thread.CurrentThread.CurrentCulture;
                return res;
            }
        private void UpdateStatusIcons()
        {
            if (!powerIconsInitialized)
            {
                return;
            }

            if (Time.time < iconUpdateDelay)
            {
                return;
            }

            iconUpdateDelay = Time.time + delayInterval;

            HidePowerIcons();
            if (settings.ShowThermometer)
            {
                float temperature = Cyclops.GetTemperature();
                TemperatureReadout.Text.text  = NumberFormatter.FormatValue(temperature) + "°C";
                TemperatureReadout.Text.color = GetHeatColor(temperature);
                TemperatureReadout.SetEnabled(true);
            }
            else
            {
                TemperatureReadout.SetEnabled(false);
            }

            if (settings.HidePowerIcons)
            {
                return;
            }

            bool isEven = true;

            for (int i = 0; i < StatusIcons.Count; i++)
            {
                if (StatusIcons[i].ShowStatusIcon)
                {
                    isEven = !isEven;
                }
            }

            IndicatorIcon[] helmRow      = isEven ? HelmIndicatorsEven : HelmIndicatorsOdd;
            IndicatorIcon[] healthBarRow = isEven ? HealthBarIndicatorsEven : HealthBarIndicatorsOdd;

            bool showIconsOnHoloDisplay = settings.ShowIconsOnHoloDisplay;
            bool showIconsWhilePiloting = settings.ShowIconsWhilePiloting;

            int iconIndex = 0;

            for (int c = 0; c < StatusIcons.Count; c++)
            {
                CyclopsStatusIcon statusIcon = StatusIcons[c];

                if (!statusIcon.ShowStatusIcon)
                {
                    continue;
                }

                IndicatorIcon helmIcon = helmRow[iconIndex];
                IndicatorIcon hpIcon   = healthBarRow[iconIndex++];

                hpIcon.SetEnabled(showIconsOnHoloDisplay);
                helmIcon.SetEnabled(showIconsWhilePiloting);

                hpIcon.Icon.sprite = helmIcon.Icon.sprite = statusIcon.StatusSprite();

                hpIcon.Text.enabled = powerIconTextVisibility;
                hpIcon.Text.text    = helmIcon.Text.text = statusIcon.StatusText();

                hpIcon.Text.color = helmIcon.Text.color = statusIcon.StatusTextColor();
            }
        }
Esempio n. 16
0
        public static string ImageLoadOrStore(CodeGenContext context, AstOperation operation)
        {
            AstTextureOperation texOp = (AstTextureOperation)operation;

            bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;

            bool isArray   = (texOp.Type & SamplerType.Array) != 0;
            bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;

            string texCall = texOp.Inst == Instruction.ImageLoad ? "imageLoad" : "imageStore";

            int srcIndex = isBindless ? 1 : 0;

            string Src(VariableType type)
            {
                return(GetSoureExpr(context, texOp.GetSource(srcIndex++), type));
            }

            string indexExpr = null;

            if (isIndexed)
            {
                indexExpr = Src(VariableType.S32);
            }

            string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);

            texCall += "(" + imageName;

            int coordsCount = texOp.Type.GetDimensions();

            int pCount = coordsCount + (isArray ? 1 : 0);

            void Append(string str)
            {
                texCall += ", " + str;
            }

            if (pCount > 1)
            {
                string[] elems = new string[pCount];

                for (int index = 0; index < pCount; index++)
                {
                    elems[index] = Src(VariableType.S32);
                }

                Append("ivec" + pCount + "(" + string.Join(", ", elems) + ")");
            }
            else
            {
                Append(Src(VariableType.S32));
            }

            if (texOp.Inst == Instruction.ImageStore)
            {
                VariableType type = texOp.Format.GetComponentType();

                string[] cElems = new string[4];

                for (int index = 0; index < 4; index++)
                {
                    if (srcIndex < texOp.SourcesCount)
                    {
                        cElems[index] = Src(type);
                    }
                    else
                    {
                        cElems[index] = type switch
                        {
                            VariableType.S32 => NumberFormatter.FormatInt(0),
                            VariableType.U32 => NumberFormatter.FormatUint(0),
                            _ => NumberFormatter.FormatFloat(0)
                        };
                    }
                }

                string prefix = type switch
                {
                    VariableType.S32 => "i",
                    VariableType.U32 => "u",
                    _ => string.Empty
                };

                Append(prefix + "vec4(" + string.Join(", ", cElems) + ")");
            }

            texCall += ")" + (texOp.Inst == Instruction.ImageLoad ? GetMask(texOp.Index) : "");

            return(texCall);
        }
Esempio n. 17
0
        private void Listen()
        {
            try
            {
                UdpClient udpSvr = m_udpListener;

                if (udpSvr == null)
                {
                    logger.Error("The UDP server was not correctly initialised in the RTP sink when attempting to start the listener, the RTP stream has not been intialised.");
                    return;
                }
                else
                {
                    logger.Debug("RTP Listener now listening on " + m_localEndPoint.Address + ":" + m_localEndPoint.Port + ".");
                }

                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[]     rcvdBytes      = null;

                m_startRTPReceiveTime = DateTime.MinValue;
                m_lastRTPReceivedTime = DateTime.MinValue;
                DateTime previousRTPReceiveTime = DateTime.MinValue;
                uint     previousTimestamp      = 0;
                UInt16   sequenceNumber         = 0;
                UInt16   previousSeqNum         = 0;
                uint     senderSendSpacing      = 0;
                uint     lastSenderSendSpacing  = 0;

                while (!StopListening)
                {
                    rcvdBytes = null;

                    try
                    {
                        rcvdBytes = udpSvr.Receive(ref remoteEndPoint);
                    }
                    catch
                    {
                        //logger.Warn("Remote socket closed on receive. Last RTP received " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ", last RTP successfull send " +  m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss") + ".");
                    }

                    if (rcvdBytes != null && rcvdBytes.Length > 0)
                    {
                        // Check whether this is an RTCP report.
                        UInt16 firstWord = BitConverter.ToUInt16(rcvdBytes, 0);
                        if (BitConverter.IsLittleEndian)
                        {
                            firstWord = NetConvert.DoReverseEndian(firstWord);
                        }

                        ushort packetType = 0;
                        if (BitConverter.IsLittleEndian)
                        {
                            packetType = Convert.ToUInt16(firstWord & 0x00ff);
                        }

                        if (packetType == RTCPHeader.RTCP_PACKET_TYPE)
                        {
                            logger.Debug("RTP Listener received remote RTCP report from " + remoteEndPoint + ".");

                            try
                            {
                                RTCPPacket       rtcpPacket       = new RTCPPacket(rcvdBytes);
                                RTCPReportPacket rtcpReportPacket = new RTCPReportPacket(rtcpPacket.Reports);

                                if (RTCPReportReceived != null)
                                {
                                    RTCPReportReceived(this, rtcpReportPacket);
                                }
                            }
                            catch (Exception rtcpExcp)
                            {
                                logger.Error("Exception processing remote RTCP report. " + rtcpExcp.Message);
                            }

                            continue;
                        }

                        // Channel statistics.
                        DateTime rtpReceiveTime = DateTime.Now;
                        if (m_startRTPReceiveTime == DateTime.MinValue)
                        {
                            m_startRTPReceiveTime = rtpReceiveTime;
                            //m_sampleStartTime = rtpReceiveTime;
                        }
                        previousRTPReceiveTime = new DateTime(m_lastRTPReceivedTime.Ticks);
                        m_lastRTPReceivedTime  = rtpReceiveTime;
                        m_packetsReceived++;
                        m_bytesReceived += rcvdBytes.Length;

                        previousSeqNum = sequenceNumber;

                        // This stops the thread running the ListenerTimeout method from deciding the strema has recieved no RTP and therefore should be shutdown.
                        m_lastPacketReceived.Set();

                        // Let whoever has subscribed that an RTP packet has been received.
                        if (DataReceived != null)
                        {
                            try
                            {
                                DataReceived(m_streamId, rcvdBytes, remoteEndPoint);
                            }
                            catch (Exception excp)
                            {
                                logger.Error("Exception RTPSink DataReceived. " + excp.Message);
                            }
                        }

                        if (m_packetsReceived % 500 == 0)
                        {
                            logger.Debug("Total packets received from " + remoteEndPoint.ToString() + " " + m_packetsReceived + ", bytes " + NumberFormatter.ToSIByteFormat(m_bytesReceived, 2) + ".");
                        }

                        try
                        {
                            RTPPacket rtpPacket  = new RTPPacket(rcvdBytes);
                            uint      syncSource = rtpPacket.Header.SyncSource;
                            uint      timestamp  = rtpPacket.Header.Timestamp;
                            sequenceNumber = rtpPacket.Header.SequenceNumber;

                            //logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestamp=" + timestamp);

                            if (previousRTPReceiveTime != DateTime.MinValue)
                            {
                                //uint senderSendSpacing = rtpPacket.Header.Timestamp - previousTimestamp;
                                // Need to cope with cases where the timestamp has looped, if this timestamp is < last timesatmp and there is a large difference in them then it's because the timestamp counter has looped.
                                lastSenderSendSpacing = senderSendSpacing;
                                senderSendSpacing     = (Math.Abs(timestamp - previousTimestamp) > (uint.MaxValue / 2)) ? timestamp + uint.MaxValue - previousTimestamp : timestamp - previousTimestamp;

                                if (previousTimestamp > timestamp)
                                {
                                    logger.Error("BUG: Listener previous timestamp (" + previousTimestamp + ") > timestamp (" + timestamp + "), last seq num=" + previousSeqNum + ", seqnum=" + sequenceNumber + ".");

                                    // Cover for this bug until it's nailed down.
                                    senderSendSpacing = lastSenderSendSpacing;
                                }

                                double senderSpacingMilliseconds = (double)senderSendSpacing / (double)TIMESTAMP_FACTOR;
                                double interarrivalReceiveTime   = m_lastRTPReceivedTime.Subtract(previousRTPReceiveTime).TotalMilliseconds;

                                #region RTCP reporting.

                                if (m_rtcpSampler == null)
                                {
                                    //resultsLogger.Info("First Packet: " + rtpPacket.Header.SequenceNumber + "," + m_arrivalTime.ToString("HH:mm:fff"));

                                    m_rtcpSampler = new RTCPReportSampler(m_streamId, syncSource, remoteEndPoint, rtpPacket.Header.SequenceNumber, m_lastRTPReceivedTime, rcvdBytes.Length);
                                    m_rtcpSampler.RTCPReportReady += new RTCPSampleReadyDelegate(m_rtcpSampler_RTCPReportReady);
                                    m_rtcpSampler.StartSampling();
                                }
                                else
                                {
                                    //m_receiverReports[syncSource].RecordRTPReceive(rtpPacket.Header.SequenceNumber, sendTime, rtpReceiveTime, rcvdBytes.Length);
                                    // Transit time is calculated by knowing that the sender sent a packet at a certain time after the last send and the receiver received a pakcet a certain time after the last receive.
                                    // The difference in these two times is the jitter present. The transit time can change with each transimission and as this methid relies on two sends two packet
                                    // arrivals to calculate the transit time it's not going to be perfect (you'd need synchronised NTP clocks at each end to be able to be accurate).
                                    // However if used tor an average calculation it should be pretty close.
                                    //double transitTime = Math.Abs(interarrivalReceiveTime - senderSpacingMilliseconds);
                                    uint jitter = (interarrivalReceiveTime - senderSpacingMilliseconds > 0) ? Convert.ToUInt32(interarrivalReceiveTime - senderSpacingMilliseconds) : 0;

                                    if (jitter > 75)
                                    {
                                        logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestmap=" + timestamp + ", ts-prev=" + previousTimestamp + ", receive spacing=" + interarrivalReceiveTime + ", send spacing=" + senderSpacingMilliseconds + ", jitter=" + jitter);
                                    }
                                    else
                                    {
                                        //logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", receive spacing=" + interarrivalReceiveTime + ", timestamp=" + timestamp + ", transit time=" + transitTime);
                                    }

                                    m_rtcpSampler.RecordRTPReceive(m_lastRTPReceivedTime, rtpPacket.Header.SequenceNumber, rcvdBytes.Length, jitter);
                                }

                                #endregion
                            }
                            else
                            {
                                logger.Debug("RTPSink Listen SyncSource=" + rtpPacket.Header.SyncSource + ".");
                            }

                            previousTimestamp = timestamp;
                        }
                        catch (Exception excp)
                        {
                            logger.Error("Received data was not a valid RTP packet. " + excp.Message);
                        }

                        #region Switching endpoint if required to cope with NAT.

                        // If a packet is recieved from an endpoint that wasn't expected treat the stream as being NATted and switch the endpoint to the socket on the NAT server.
                        try
                        {
                            if (m_streamEndPoint != null && m_streamEndPoint.Address != null && remoteEndPoint != null && remoteEndPoint.Address != null && (m_streamEndPoint.Address.ToString() != remoteEndPoint.Address.ToString() || m_streamEndPoint.Port != remoteEndPoint.Port))
                            {
                                logger.Debug("Expecting RTP on " + IPSocket.GetSocketString(m_streamEndPoint) + " but received on " + IPSocket.GetSocketString(remoteEndPoint) + ", now sending to " + IPSocket.GetSocketString(remoteEndPoint) + ".");
                                m_streamEndPoint = remoteEndPoint;

                                if (RemoteEndPointChanged != null)
                                {
                                    try
                                    {
                                        RemoteEndPointChanged(m_streamId, remoteEndPoint);
                                    }
                                    catch (Exception changeExcp)
                                    {
                                        logger.Error("Exception RTPListener Changing Remote EndPoint. " + changeExcp.Message);
                                    }
                                }
                            }
                        }
                        catch (Exception setSendExcp)
                        {
                            logger.Error("Exception RTPListener setting SendTo Socket. " + setSendExcp.Message);
                        }

                        #endregion
                    }
                    else if (!StopListening) // Empty packet was received possibly indicating connection closure so check for timeout.
                    {
                        double noRTPRcvdDuration = (m_lastRTPReceivedTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPReceivedTime).TotalSeconds : 0;
                        double noRTPSentDuration = (m_lastRTPSentTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPSentTime).TotalSeconds : 0;

                        //logger.Warn("Remote socket closed on receive on " + m_localEndPoint.Address.ToString() + ":" + + m_localEndPoint.Port + ", reinitialising. No rtp for " + noRTPRcvdDuration + "s. last rtp " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ".");

                        // If this check is not done then the stream will never time out if it doesn't receive the first packet.
                        if (m_lastRTPReceivedTime == DateTime.MinValue)
                        {
                            m_lastRTPReceivedTime = DateTime.Now;
                        }

                        remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                        if ((noRTPRcvdDuration > NO_RTP_TIMEOUT || noRTPSentDuration > NO_RTP_TIMEOUT) && StopIfNoData)
                        {
                            logger.Warn("Disconnecting RTP listener on " + m_localEndPoint.ToString() + " due to not being able to send or receive any RTP for " + NO_RTP_TIMEOUT + "s.");
                            Shutdown();
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception Listen RTPSink: " + excp.Message);
            }
            finally
            {
                #region Shut down socket.

                Shutdown();

                if (ListenerClosed != null)
                {
                    try
                    {
                        ListenerClosed(m_streamId, m_callDescriptorId);
                    }
                    catch (Exception excp)
                    {
                        logger.Error("Exception RTPSink ListenerClosed. " + excp.Message);
                    }
                }

                #endregion
            }
        }
 public override string StatusText()
 {
     return(this.SolarEnergyAvailable ? NumberFormatter.FormatValue(energyStatus) + "%Θ" : string.Empty);
 }
Esempio n. 19
0
        public static string TextureSample(CodeGenContext context, AstOperation operation)
        {
            AstTextureOperation texOp = (AstTextureOperation)operation;

            bool isBindless     = (texOp.Flags & TextureFlags.Bindless) != 0;
            bool isGather       = (texOp.Flags & TextureFlags.Gather) != 0;
            bool hasDerivatives = (texOp.Flags & TextureFlags.Derivatives) != 0;
            bool intCoords      = (texOp.Flags & TextureFlags.IntCoords) != 0;
            bool hasLodBias     = (texOp.Flags & TextureFlags.LodBias) != 0;
            bool hasLodLevel    = (texOp.Flags & TextureFlags.LodLevel) != 0;
            bool hasOffset      = (texOp.Flags & TextureFlags.Offset) != 0;
            bool hasOffsets     = (texOp.Flags & TextureFlags.Offsets) != 0;

            bool isArray       = (texOp.Type & SamplerType.Array) != 0;
            bool isIndexed     = (texOp.Type & SamplerType.Indexed) != 0;
            bool isMultisample = (texOp.Type & SamplerType.Multisample) != 0;
            bool isShadow      = (texOp.Type & SamplerType.Shadow) != 0;

            // This combination is valid, but not available on GLSL.
            // For now, ignore the LOD level and do a normal sample.
            // TODO: How to implement it properly?
            if (hasLodLevel && isArray && isShadow)
            {
                hasLodLevel = false;
            }

            string texCall = intCoords ? "texelFetch" : "texture";

            if (isGather)
            {
                texCall += "Gather";
            }
            else if (hasDerivatives)
            {
                texCall += "Grad";
            }
            else if (hasLodLevel && !intCoords)
            {
                texCall += "Lod";
            }

            if (hasOffset)
            {
                texCall += "Offset";
            }
            else if (hasOffsets)
            {
                texCall += "Offsets";
            }

            int srcIndex = isBindless ? 1 : 0;

            string Src(VariableType type)
            {
                return(GetSoureExpr(context, texOp.GetSource(srcIndex++), type));
            }

            string indexExpr = null;

            if (isIndexed)
            {
                indexExpr = Src(VariableType.S32);
            }

            string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);

            texCall += "(" + samplerName;

            int coordsCount = texOp.Type.GetDimensions();

            int pCount = coordsCount;

            int arrayIndexElem = -1;

            if (isArray)
            {
                arrayIndexElem = pCount++;
            }

            // The sampler 1D shadow overload expects a
            // dummy value on the middle of the vector, who knows why...
            bool hasDummy1DShadowElem = texOp.Type == (SamplerType.Texture1D | SamplerType.Shadow);

            if (hasDummy1DShadowElem)
            {
                pCount++;
            }

            if (isShadow && !isGather)
            {
                pCount++;
            }

            // On textureGather*, the comparison value is
            // always specified as an extra argument.
            bool hasExtraCompareArg = isShadow && isGather;

            if (pCount == 5)
            {
                pCount = 4;

                hasExtraCompareArg = true;
            }

            void Append(string str)
            {
                texCall += ", " + str;
            }

            VariableType coordType = intCoords ? VariableType.S32 : VariableType.F32;

            string AssemblePVector(int count)
            {
                if (count > 1)
                {
                    string[] elems = new string[count];

                    for (int index = 0; index < count; index++)
                    {
                        if (arrayIndexElem == index)
                        {
                            elems[index] = Src(VariableType.S32);

                            if (!intCoords)
                            {
                                elems[index] = "float(" + elems[index] + ")";
                            }
                        }
                        else if (index == 1 && hasDummy1DShadowElem)
                        {
                            elems[index] = NumberFormatter.FormatFloat(0);
                        }
                        else
                        {
                            elems[index] = Src(coordType);
                        }
                    }

                    string prefix = intCoords ? "i" : string.Empty;

                    return(prefix + "vec" + count + "(" + string.Join(", ", elems) + ")");
                }
                else
                {
                    return(Src(coordType));
                }
            }

            Append(AssemblePVector(pCount));

            string AssembleDerivativesVector(int count)
            {
                if (count > 1)
                {
                    string[] elems = new string[count];

                    for (int index = 0; index < count; index++)
                    {
                        elems[index] = Src(VariableType.F32);
                    }

                    return("vec" + count + "(" + string.Join(", ", elems) + ")");
                }
                else
                {
                    return(Src(VariableType.F32));
                }
            }

            if (hasExtraCompareArg)
            {
                Append(Src(VariableType.F32));
            }

            if (hasDerivatives)
            {
                Append(AssembleDerivativesVector(coordsCount)); // dPdx
                Append(AssembleDerivativesVector(coordsCount)); // dPdy
            }

            if (isMultisample)
            {
                Append(Src(VariableType.S32));
            }
            else if (hasLodLevel)
            {
                Append(Src(coordType));
            }

            string AssembleOffsetVector(int count)
            {
                if (count > 1)
                {
                    string[] elems = new string[count];

                    for (int index = 0; index < count; index++)
                    {
                        elems[index] = Src(VariableType.S32);
                    }

                    return("ivec" + count + "(" + string.Join(", ", elems) + ")");
                }
                else
                {
                    return(Src(VariableType.S32));
                }
            }

            if (hasOffset)
            {
                Append(AssembleOffsetVector(coordsCount));
            }
            else if (hasOffsets)
            {
                texCall += $", ivec{coordsCount}[4](";

                texCall += AssembleOffsetVector(coordsCount) + ", ";
                texCall += AssembleOffsetVector(coordsCount) + ", ";
                texCall += AssembleOffsetVector(coordsCount) + ", ";
                texCall += AssembleOffsetVector(coordsCount) + ")";
            }

            if (hasLodBias)
            {
                Append(Src(VariableType.F32));
            }

            // textureGather* optional extra component index,
            // not needed for shadow samplers.
            if (isGather && !isShadow)
            {
                Append(Src(VariableType.S32));
            }

            texCall += ")" + (isGather || !isShadow ? GetMask(texOp.Index) : "");

            return(texCall);
        }
 public override Color StatusTextColor()
 {
     return(this.SolarEnergyAvailable ? NumberFormatter.GetNumberColor(energyStatus, 90f, 5f) : Color.white);
 }
Esempio n. 21
0
 public override Color StatusTextColor()
 {
     return(NumberFormatter.GetNumberColor(totalBioCharge, totalBioCapacity, 0f));
 }
Esempio n. 22
0
    private void UpdateUI()
    {
        //cashtext
        cashText.text = NumberFormatter.ToString(number: PlayerManager.instance.cash, showDecimalPlaces: true);
        goldText.text = NumberFormatter.ToString(number: PlayerManager.instance.gold, showDecimalPlaces: false, showDollarSign: false);
        adBoosterExtraCashCounter.text = PlayerManager.instance.extraCashBoosterCounter.ToString();

        UpdateStatusExtraCashButton(PlayerManager.instance.extraCashBoosterCounter);
        if (PlayerManager.instance.isBooster)
        {
            if (adBoosterButton.IsInteractable())
            {
                adBoosterButton.interactable = false;
            }

            ulong diff = ((ulong)DateTime.Now.Ticks - PlayerManager.instance.lastBoosterStartDateTime);
            ulong m    = diff / TimeSpan.TicksPerMillisecond;

            secondsLeft = (float)(Constant.msToBoosterWait - m) / 1000.0f;

            string r = "";
            //H
            r           += ((int)secondsLeft / 3600).ToString() + ":";
            secondsLeft -= ((int)secondsLeft / 3600) * 3600;
            //M
            r += ((int)secondsLeft / 60).ToString("00") + ":";
            //S
            r += (secondsLeft % 60).ToString("00") + "";

            adBoosterTimerText.alignment = TextAnchor.MiddleCenter;
            adBoosterTimerText.text      = r;
        }
        else
        {
            if (!adBoosterButton.IsInteractable())
            {
                adBoosterButton.interactable = true;
            }

            adBoosterTimerText.fontStyle = FontStyle.Normal;
            adBoosterTimerText.text      = "2x\nprofit";
        }
        //update slot panels
        for (int i = 0; i < panels.Length; i++)
        {
            //boosters
            if (panels[i].GetComponent <SlotPanel>() != null)
            {
                Slot slot = PlayerManager.instance.GetSlot(i);
                //show tap to gain money
                if (!slot.isProducing && !PlayerManager._instance.HasBoughtManager(i))
                {
                    panels[i].GetComponent <SlotPanel>().TapToGainMoney(true);
                }
                else
                {
                    panels[i].GetComponent <SlotPanel>().TapToGainMoney(false);
                }

                //show tap to speed up text
                if (slot.isProducing && PlayerManager.instance.HasBoughtManager(slot.index))
                {
                    //panels[i].GetComponent<SlotPanel>().TapToSpeedUpShow(true);
                    panels[i].GetComponent <SlotPanel>().TapToSpeedUpDialogShow(true);
                }
                else
                {
                    //panels[i].GetComponent<SlotPanel>().TapToSpeedUpShow(false);
                    panels[i].GetComponent <SlotPanel>().TapToSpeedUpDialogShow(false);
                }

                //show x2
                if (PlayerManager.instance.isBooster)
                {
                    panels[i].GetComponent <SlotPanel>().SlotIsBoosting(true);
                }
                else
                {
                    panels[i].GetComponent <SlotPanel>().SlotIsBoosting(false);
                }
            }

            if (panels[i].GetComponent <BuySlotPanel>() != null)
            {
                (panels[i] as BuySlotPanel).interactable =
                    PlayerManager.instance.cash >= PlayerManager.instance.GetSlot(i).costToUnlock&&
                    panels[i - 1].GetComponent <SlotPanel>() != null &&
                    PlayerManager.instance.buyButtonParamsToUnlock[i].unlockingIsActive == false;
            }
            else if (panels[i].GetComponent <SlotPanel>() != null)
            {
                (panels[i] as SlotPanel).Refresh();
            }
        }
        //upgreade
        bool upgreadeIsSomething = false;

        //check 10 (max number of upgrades)
        for (int i = numberOfBuilding * 10 - 10; i < 10; i++)
        {
            if (!PlayerManager.instance.HasBoughtUpgreade(i))
            {
                upgreadeIsSomething = true;
                if (PlayerManager.instance.cash >= PlayerManager.instance.GetUpgreadeCost(i) &&
                    panels[i].GetComponent <SlotPanel>() != null)
                {
                    upgreadesNotification.alpha  = 1f;
                    upgradesBlurBackground.alpha = 1f;
                }
                else
                {
                    upgreadesNotification.alpha  = 0f;
                    upgradesBlurBackground.alpha = 0f;
                }
                break;
            }

            //list is empty
            if (upgreadeIsSomething == false)
            {
                upgreadesNotification.alpha  = 0f;
                upgradesBlurBackground.alpha = 0f;
            }
        }
        if (upgreadePopup.GetStatus())
        {
            for (int upgreadeIndex = 0; upgreadeIndex < upgreadePopup.panels.Count; upgreadeIndex++)
            {
                if (upgreadePopup.panels[upgreadeIndex].cost <= PlayerManager.instance.cash)
                {
                    upgreadePopup.panels[upgreadeIndex].RefreshBuyButtonStatus(true);
                }
                else
                {
                    upgreadePopup.panels[upgreadeIndex].RefreshBuyButtonStatus(false);
                }
            }
        }
        //manager
        bool managerIsSomething = false;

        //check 20 (max number of upgrades)
        for (int i = numberOfBuilding * 20 - 20; i < 20; i++)
        {
            if (!PlayerManager.instance.HasBoughtManager(i))
            {
                managerIsSomething = true;
                float tmp = PlayerManager.instance.GetManagerCost(i);
                if (PlayerManager.instance.cash >= PlayerManager.instance.GetManagerCost(i) &&
                    panels[i].GetComponent <SlotPanel>() != null)
                {
                    managersNotification.alpha   = 1f;
                    managersBlurBackground.alpha = 1f;
                }
                else
                {
                    managersNotification.alpha   = 0f;
                    managersBlurBackground.alpha = 0f;
                }
                break;
            }

            //list is empty
            if (managerIsSomething == false)
            {
                managersNotification.alpha   = 0f;
                managersBlurBackground.alpha = 0f;
            }
        }
        if (managersPopup.GetStatus())
        {
            for (int managerIndex = 0; managerIndex < managersPopup.panels.Count; managerIndex++)
            {
                if (managersPopup.panels[managerIndex].cost <= PlayerManager.instance.cash)
                {
                    managersPopup.panels[managerIndex].RefreshBuyButtonStatus(true);
                }
                else
                {
                    managersPopup.panels[managerIndex].RefreshBuyButtonStatus(false);
                }
            }
        }
        if (PlayerManager.instance.shouldConsiderContract)
        {
            officeNotification.alpha   = 1f;
            officeBlurBackground.alpha = 1f;
        }
        else
        {
            officeNotification.alpha   = 0f;
            officeBlurBackground.alpha = 0f;
        }

        //contract Panel
        if (officePopup != null && officePopup.isShow)
        {
            contract.RefreshContractPanel();
        }
        //map buildings
        if (mapPopup.GetStatus())
        {
            for (int i = 0; i < mapPopup.buildingMap.Length; i++)
            {
                if (PlayerManager.instance.cash >= PlayerManager.instance.GetBuildingMapCost(i))
                {
                    mapPopup.buildingMap[i].RefreshBuyButton(true);
                }
                else
                {
                    mapPopup.buildingMap[i].RefreshBuyButton(false);
                }
            }
        }
        //upgrade each floor panel
        if (upgradeEachFloorPopup.isVisible)
        {
            upgradeEachFloorPopup.Refresh();
        }

        if (upgradeEachFloorPopup.typeOfUpgradeSystem == TypeOfUpgradeSystem.ADVANCED)
        {
            bulkSimpleTypeButton.gameObject.SetActive(false);
        }
        else //SIMPLE
        {
            bulkSimpleTypeButton.gameObject.SetActive(true);
        }
    }
Esempio n. 23
0
 public void ParseNullOrEmptyValue()
 {
     NumberFormatter fmt = new NumberFormatter();
     Assert.AreEqual(0, fmt.Parse(null));
     Assert.IsTrue(fmt.Parse("") is double);
 }
Esempio n. 24
0
        /// <summary>
        /// Обработчик второго варианта действия
        /// </summary>
        public override void OnSecondButtonClick(EventManager eventManager)
        {
            HideEventButtons(eventManager.FirstButton, eventManager.SecondButton, eventManager.OkButton);
            eventManager.EventContent.text = "Рекламный ролик стал вирусным, а вы - мемом. Многие фанаты остались сильно разочарованы...";
            var playerInfo   = PlayerManager.GetInfo();
            var fansDecrease = PlayerManager.GetFansPercentValue() * 3;
            var income       = playerInfo.Money > 500 ? playerInfo.Money / 100 * 5 : 50;

            if (playerInfo.Fans < fansDecrease)
            {
                fansDecrease = playerInfo.Fans;
            }
            playerInfo.Fans  -= fansDecrease;
            playerInfo.Money += income;
            eventManager.EventReward.text = $"От вас ушло {NumberFormatter.FormatValue(fansDecrease)} фанатов. Заработано: {NumberFormatter.FormatValue(income)}";
            eventManager.StatsManager.UpdateStats();
        }
Esempio n. 25
0
 public void Setup()
 {
     formatter = new NumberFormatter();
 }
 public string GetIndicatorText()
 {
     return(NumberFormatter.FormatNumber(Mathf.CeilToInt(this.NuclearCharger.TotalBatteryCharge), NumberFormat.Amount));
 }
Esempio n. 27
0
        public void FormatUsingCustomSettings()
        {
            NumberFormatter fmt = new NumberFormatter("en-US");
            fmt.DecimalDigits = 0;
            fmt.NegativePattern = 0;
            Assert.AreEqual("1,234", fmt.Format(1234));
            Assert.AreEqual("1,235", fmt.Format(1234.56));
            Assert.AreEqual("(1,234)", fmt.Format(-1234));
            Assert.AreEqual("(1,235)", fmt.Format(-1234.56));

            fmt = new NumberFormatter("sr-SP-Cyrl");
            fmt.GroupSizes = new int[] {1, 2};
            fmt.GroupSeparator = "'";
            Assert.AreEqual("1'23'4,00", fmt.Format(1234));
            Assert.AreEqual("1'23'4,56", fmt.Format(1234.56));
            Assert.AreEqual("-1'23'4,00", fmt.Format(-1234));
            Assert.AreEqual("-1'23'4,56", fmt.Format(-1234.56));
        }
 public Color GetIndicatorTextColor()
 {
     return(NumberFormatter.GetNumberColor(this.NuclearCharger.TotalBatteryCharge, this.NuclearCharger.TotalBatteryCapacity, 0f));
 }
Esempio n. 29
0
 public override string StatusText()
 {
     return(NumberFormatter.FormatValue(this.NuclearHandler.TotalBatteryCharge));
 }
Esempio n. 30
0
 /// <summary>
 /// Отображает информацию о выбранном месте концерта
 /// </summary>
 protected override void ParseActionModel()
 {
     place         = places.First(e => e.Name == PlaceSelector.captionText.text);
     City.text     = place.City;
     Capacity.text = $"Вместимость: {NumberFormatter.FormatValue(place.Capacity)}";
 }
Esempio n. 31
0
        public void UpdateInfo(IEnumerable <MapTile> selectedMapTiles, RouteManagementViewModel rmVm)
        {
            int nSelected = 0;
            int forests   = 0;
            //double prestige = 1;
            double food         = 1;
            double foodCart     = 1;
            double wood         = 1;
            double woodCart     = 1;
            double science      = 1;
            double scienceCart  = 1;
            double foragingHuts = 1;

            foreach (var hexItem in selectedMapTiles)
            {
                nSelected++;

                if (hexItem.TileType == TileType.Forest)
                {
                    forests++;
                }

                var shrine = hexItem as ShrineTile;

                if (shrine == null)
                {
                    continue;
                }

                //prestige *= shrine.PrestigeMultiplier;
                food         *= shrine.FoodMultiplier;
                foodCart     *= shrine.FoodCartMultiplier;
                wood         *= shrine.WoodMultiplier;
                woodCart     *= shrine.WoodCartMultiplier;
                science      *= shrine.ScienceMultiplier;
                foragingHuts *= shrine.FoodMultiplier * shrine.ForagingHutMultiplier;

                var aMultiplier = shrine.AllCartMultiplier;
                if (aMultiplier > 1)
                {
                    foodCart    *= aMultiplier;
                    woodCart    *= aMultiplier;
                    scienceCart *= aMultiplier;
                }
            }

            var tileCosts = TileCostHelper.Values(nSelected + 2);

            var nextTileCost  = tileCosts[tileCosts.Count - 1];
            var totalTileCost = tileCosts.Sum() - nextTileCost;

            //var prestigeOnReset = nSelected - 9 > 0 ? (nSelected - 9) * prestige : 0;

            NextTileCostText    = (nSelected + 1 < TileCostHelper.KnownValues.Length ? "" : "~") + NumberFormatter.FormatNumber(nextTileCost);
            TileCostTotalText   = (nSelected < TileCostHelper.KnownValues.Length ? "" : "~") + NumberFormatter.FormatNumber(totalTileCost);
            SelectedTilesText   = nSelected.ToString();
            SelectedForestsText = forests.ToString();
            //PrestigeMultiplierText = NumberFormatter.FormatNumber(prestige);
            //PrestigeTotalText = NumberFormatter.FormatNumber(prestigeOnReset);
            FoodMultiplierText        = NumberFormatter.FormatNumber(food);
            FoodCartMultiplierText    = NumberFormatter.FormatNumber(foodCart);
            WoodMultiplierText        = NumberFormatter.FormatNumber(wood);
            WoodCartMultiplierText    = NumberFormatter.FormatNumber(woodCart);
            ScienceMultiplierText     = NumberFormatter.FormatNumber(science);
            ScienceCartMultiplierText = NumberFormatter.FormatNumber(scienceCart);
            ForagingHutMultiplierText = NumberFormatter.FormatNumber(foragingHuts);

            //var averageFoodPerSecond = NumberFormatter.UnformatNumber(rmVm.AverageFoodPerSecondText);


            //var estimateTimeInSeconds = (totalTileCost / averageFoodPerSecond) / 2; // divide by 2 assumed always double production

            //if (double.IsNaN(estimateTimeInSeconds) || estimateTimeInSeconds > 3153600000)
            //{
            //    EstimatedTimeText = "\u221E"; // infinity
            //    PrestigePerSecondText = $"0";
            //}
            //else
            //{
            //    var estimateTimeSpan = TimeSpan.FromSeconds(estimateTimeInSeconds);

            //    if (estimateTimeSpan.Days > 0)
            //    {
            //        EstimatedTimeText = $"{estimateTimeSpan.Days}:{estimateTimeSpan:hh\\:mm} Days";
            //    }
            //    else if (estimateTimeSpan.Hours > 0)
            //    {
            //        EstimatedTimeText = $"{estimateTimeSpan:hh\\:mm} Hours";
            //    }
            //    else
            //    {
            //        EstimatedTimeText = $"{estimateTimeSpan:mm\\:ss} Mins";
            //    }

            //    //var prestigePerSecond = prestigeOnReset / estimateTimeInSeconds;
            //    //PrestigePerSecondText = NumberFormatter.FormatNumber(prestigePerSecond);
            //}

            //if (Math.Min(food, foodCart) != _previousLowestFoodMultiplier)
            //{
            //    averageFoodPerSecond *= Math.Min(food, foodCart) / _previousLowestFoodMultiplier;
            //    _previousLowestFoodMultiplier = Math.Min(food, foodCart);
            //    rmVm.AverageFoodPerSecondText = NumberFormatter.FormatNumber(averageFoodPerSecond);
            //}
        }
Esempio n. 32
0
 internal string EnergyStatusText()
 {
     return(NumberFormatter.FormatValue(energyStatus) + this.PercentNotation);
 }
Esempio n. 33
0
        public static string ImageLoadOrStore(CodeGenContext context, AstOperation operation)
        {
            AstTextureOperation texOp = (AstTextureOperation)operation;

            bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;

            // TODO: Bindless texture support. For now we just return 0/do nothing.
            if (isBindless)
            {
                return(texOp.Inst == Instruction.ImageLoad ? NumberFormatter.FormatFloat(0) : "// imageStore(bindless)");
            }

            bool isArray   = (texOp.Type & SamplerType.Array) != 0;
            bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;

            string texCall = texOp.Inst == Instruction.ImageLoad ? "imageLoad" : "imageStore";

            int srcIndex = isBindless ? 1 : 0;

            string Src(VariableType type)
            {
                return(GetSoureExpr(context, texOp.GetSource(srcIndex++), type));
            }

            string indexExpr = null;

            if (isIndexed)
            {
                indexExpr = Src(VariableType.S32);
            }

            string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);

            texCall += "(" + imageName;

            int coordsCount = texOp.Type.GetDimensions();

            int pCount = coordsCount + (isArray ? 1 : 0);

            void Append(string str)
            {
                texCall += ", " + str;
            }

            string ApplyScaling(string vector)
            {
                int index = context.FindImageDescriptorIndex(texOp);

                if ((context.Config.Stage == ShaderStage.Fragment || context.Config.Stage == ShaderStage.Compute) &&
                    texOp.Inst == Instruction.ImageLoad &&
                    !isBindless &&
                    !isIndexed)
                {
                    // Image scales start after texture ones.
                    int scaleIndex = context.Config.GetTextureDescriptors().Length + index;

                    if (pCount == 3 && isArray)
                    {
                        // The array index is not scaled, just x and y.
                        vector = "ivec3(Helper_TexelFetchScale((" + vector + ").xy, " + scaleIndex + "), (" + vector + ").z)";
                    }
                    else if (pCount == 2 && !isArray)
                    {
                        vector = "Helper_TexelFetchScale(" + vector + ", " + scaleIndex + ")";
                    }
                }

                return(vector);
            }

            if (pCount > 1)
            {
                string[] elems = new string[pCount];

                for (int index = 0; index < pCount; index++)
                {
                    elems[index] = Src(VariableType.S32);
                }

                Append(ApplyScaling("ivec" + pCount + "(" + string.Join(", ", elems) + ")"));
            }
            else
            {
                Append(Src(VariableType.S32));
            }

            if (texOp.Inst == Instruction.ImageStore)
            {
                int texIndex = context.FindImageDescriptorIndex(texOp);

                VariableType type = texOp.Format.GetComponentType();

                string[] cElems = new string[4];

                for (int index = 0; index < 4; index++)
                {
                    if (srcIndex < texOp.SourcesCount)
                    {
                        cElems[index] = Src(type);
                    }
                    else
                    {
                        cElems[index] = type switch
                        {
                            VariableType.S32 => NumberFormatter.FormatInt(0),
                            VariableType.U32 => NumberFormatter.FormatUint(0),
                            _ => NumberFormatter.FormatFloat(0)
                        };
                    }
                }

                string prefix = type switch
                {
                    VariableType.S32 => "i",
                    VariableType.U32 => "u",
                    _ => string.Empty
                };

                Append(prefix + "vec4(" + string.Join(", ", cElems) + ")");
            }

            texCall += ")" + (texOp.Inst == Instruction.ImageLoad ? GetMask(texOp.Index) : "");

            return(texCall);
        }
Esempio n. 34
0
 internal string ReservePowerText()
 {
     return(NumberFormatter.FormatValue(this.AmbientEnergyUpgrade.TotalBatteryCharge));
 }
Esempio n. 35
0
        private void Send()
        {
            try
            {
                int       payloadSize = RTPPacketSendSize;
                RTPPacket rtpPacket   = new RTPPacket(RTPPacketSendSize);
                byte[]    rtpBytes    = rtpPacket.GetBytes();

                RTPHeader rtpHeader = new RTPHeader();
                rtpHeader.SequenceNumber = (UInt16)65000;  //Convert.ToUInt16(Crypto.GetRandomInt(0, UInt16.MaxValue));
                uint   sendTimestamp     = uint.MaxValue - 5000;
                uint   lastSendTimestamp = sendTimestamp;
                UInt16 lastSeqNum        = 0;

                logger.Debug("RTP send stream starting to " + IPSocket.GetSocketString(m_streamEndPoint) + " with payload size " + payloadSize + " bytes.");

                Sending            = true;
                m_startRTPSendTime = DateTime.MinValue;
                m_lastRTPSentTime  = DateTime.MinValue;
                m_sampleStartSeqNo = rtpHeader.SequenceNumber;

                DateTime lastRTPSendAttempt = DateTime.Now;

                while (m_udpListener != null && !StopListening)
                {
                    // This may be changed by the listener so it needs to be set each iteration.
                    IPEndPoint dstEndPoint = m_streamEndPoint;

                    //logger.Info("Sending RTP packet to " + dstEndPoint.Address + ":"  + dstEndPoint.Port);

                    if (payloadSize != m_rtpPacketSendSize)
                    {
                        payloadSize = m_rtpPacketSendSize;
                        logger.Info("Changing RTP payload to " + payloadSize);
                        rtpPacket = new RTPPacket(RTP_HEADER_SIZE + m_rtpPacketSendSize);
                        rtpBytes  = rtpPacket.GetBytes();
                    }

                    try
                    {
                        if (m_startRTPSendTime == DateTime.MinValue)
                        {
                            m_startRTPSendTime  = DateTime.Now;
                            rtpHeader.MarkerBit = 0;

                            logger.Debug("RTPSink Send SyncSource=" + rtpPacket.Header.SyncSource + ".");
                        }
                        else
                        {
                            lastSendTimestamp = sendTimestamp;
                            double milliSinceLastSend = DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds;
                            sendTimestamp = Convert.ToUInt32((lastSendTimestamp + (milliSinceLastSend * TIMESTAMP_FACTOR)) % uint.MaxValue);

                            if (lastSendTimestamp > sendTimestamp)
                            {
                                logger.Error("RTP Sender previous timestamp (" + lastSendTimestamp + ") > timestamp (" + sendTimestamp + ") ms since last send=" + milliSinceLastSend + ", lastseqnum=" + lastSeqNum + ", seqnum=" + rtpHeader.SequenceNumber + ".");
                            }

                            if (DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds > 75)
                            {
                                logger.Debug("delayed send: " + rtpHeader.SequenceNumber + ", time since last send " + DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds + "ms.");
                            }
                        }

                        rtpHeader.Timestamp = sendTimestamp;
                        byte[] rtpHeaderBytes = rtpHeader.GetBytes();
                        Array.Copy(rtpHeaderBytes, 0, rtpBytes, 0, rtpHeaderBytes.Length);

                        // Send RTP packets and any extra channels required to emulate mutliple calls.
                        for (int channelCount = 0; channelCount < m_channels; channelCount++)
                        {
                            //logger.Debug("Send rtp getting wallclock timestamp for " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff"));
                            //DateTime sendTime = DateTime.Now;
                            //rtpHeader.Timestamp = RTPHeader.GetWallclockUTCStamp(sendTime);
                            //logger.Debug(rtpHeader.SequenceNumber + "," + rtpHeader.Timestamp);

                            m_udpListener.Send(rtpBytes, rtpBytes.Length, dstEndPoint);
                            m_lastRTPSentTime = DateTime.Now;

                            m_packetsSent++;
                            m_bytesSent += rtpBytes.Length;

                            if (m_packetsSent % 500 == 0)
                            {
                                logger.Debug("Total packets sent to " + dstEndPoint.ToString() + " " + m_packetsSent + ", bytes " + NumberFormatter.ToSIByteFormat(m_bytesSent, 2) + ".");
                            }

                            //sendLogger.Info(m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss:fff") + "," + m_lastRTPSentTime.Subtract(m_startRTPSendTime).TotalMilliseconds.ToString("0") + "," + rtpHeader.SequenceNumber + "," + rtpBytes.Length);

                            //sendLogger.Info(rtpHeader.SequenceNumber + "," + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff"));

                            if (DataSent != null)
                            {
                                try
                                {
                                    DataSent(m_streamId, rtpBytes, dstEndPoint);
                                }
                                catch (Exception excp)
                                {
                                    logger.Error("Exception RTPSink DataSent. " + excp.Message);
                                }
                            }

                            lastSeqNum = rtpHeader.SequenceNumber;
                            if (rtpHeader.SequenceNumber == UInt16.MaxValue)
                            {
                                //logger.Debug("RTPSink looping  the sequence number in sample.");
                                rtpHeader.SequenceNumber = 0;
                            }
                            else
                            {
                                rtpHeader.SequenceNumber++;
                            }
                        }
                    }
                    catch (Exception excp)
                    {
                        logger.Error("Exception RTP Send. " + excp.GetType() + ". " + excp.Message);

                        if (excp.GetType() == typeof(SocketException))
                        {
                            logger.Error("socket exception errorcode=" + ((SocketException)excp).ErrorCode + ".");
                        }

                        logger.Warn("Remote socket closed on send. Last RTP recevied " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ", last RTP successfull send " + m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss") + ".");
                    }

                    Thread.Sleep(RTPFrameSize);

                    #region Check for whether the stream has timed out on a send or receive and if so shut down the stream.

                    double noRTPRcvdDuration = (m_lastRTPReceivedTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPReceivedTime).TotalSeconds : 0;
                    double noRTPSentDuration = (m_lastRTPSentTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPSentTime).TotalSeconds : 0;
                    double testDuration      = DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds;

                    if ((
                            noRTPRcvdDuration > NO_RTP_TIMEOUT ||
                            noRTPSentDuration > NO_RTP_TIMEOUT ||
                            (m_lastRTPReceivedTime == DateTime.MinValue && testDuration > NO_RTP_TIMEOUT)) && // If the test request comes from a private or unreachable IP address then no RTP will ever be received.
                        StopIfNoData)
                    {
                        logger.Warn("Disconnecting RTP stream on " + m_localEndPoint.Address.ToString() + ":" + m_localEndPoint.Port + " due to not being able to send any RTP for " + NO_RTP_TIMEOUT + "s.");
                        StopListening = true;
                    }

                    // Shutdown the socket even if there is still RTP but the stay alive limit has been exceeded.
                    if (RTPMaxStayAlive > 0 && DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds > RTPMaxStayAlive)
                    {
                        logger.Warn("Shutting down RTPSink due to passing RTPMaxStayAlive time.");
                        Shutdown();
                        StopListening = true;
                    }

                    #endregion
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception Send RTPSink: " + excp.Message);
            }
            finally
            {
                #region Shut down socket.

                Shutdown();

                if (SenderClosed != null)
                {
                    try
                    {
                        SenderClosed(m_streamId, m_callDescriptorId);
                    }
                    catch (Exception excp)
                    {
                        logger.Error("Exception RTPSink SenderClosed. " + excp.Message);
                    }
                }

                #endregion
            }
        }
Esempio n. 36
0
 public override Color StatusTextColor()
 {
     return(ambientEnergyAvailable
         ? NumberFormatter.GetNumberColor(energyStatus, this.MaximumEnergyStatus, this.MinimumEnergyStatus)
         : NumberFormatter.GetNumberColor(this.AmbientEnergyUpgrade.TotalBatteryCharge, this.AmbientEnergyUpgrade.TotalBatteryCapacity, 0f));
 }
Esempio n. 37
0
        public static string ImageStore(CodeGenContext context, AstOperation operation)
        {
            AstTextureOperation texOp = (AstTextureOperation)operation;

            bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;

            bool isArray   = (texOp.Type & SamplerType.Array) != 0;
            bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;

            string texCall = "imageStore";

            int srcIndex = isBindless ? 1 : 0;

            string Src(VariableType type)
            {
                return(GetSoureExpr(context, texOp.GetSource(srcIndex++), type));
            }

            string indexExpr = null;

            if (isIndexed)
            {
                indexExpr = Src(VariableType.S32);
            }

            string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);

            texCall += "(" + imageName;

            int coordsCount = texOp.Type.GetDimensions();

            int pCount = coordsCount;

            int arrayIndexElem = -1;

            if (isArray)
            {
                arrayIndexElem = pCount++;
            }

            void Append(string str)
            {
                texCall += ", " + str;
            }

            if (pCount > 1)
            {
                string[] elems = new string[pCount];

                for (int index = 0; index < pCount; index++)
                {
                    elems[index] = Src(VariableType.S32);
                }

                Append("ivec" + pCount + "(" + string.Join(", ", elems) + ")");
            }
            else
            {
                Append(Src(VariableType.S32));
            }

            string[] cElems = new string[4];

            for (int index = 0; index < 4; index++)
            {
                if (srcIndex < texOp.SourcesCount)
                {
                    cElems[index] = Src(VariableType.F32);
                }
                else
                {
                    cElems[index] = NumberFormatter.FormatFloat(0);
                }
            }

            Append("vec4(" + string.Join(", ", cElems) + ")");

            texCall += ")";

            return(texCall);
        }
Esempio n. 38
0
 public override string StatusText()
 {
     return(NumberFormatter.FormatValue(totalBioCharge) + (producingPower ? "+" : string.Empty));
 }
Esempio n. 39
0
        /// <summary>
        /// Serializes a value into a JSON string.  Does not serialize "undefined", check for that
        /// value before calling this method.
        /// </summary>
        /// <param name="value"> The value to serialize. </param>
        /// <param name="result"> The StringBuilder to write the JSON representation of the
        /// value to. </param>
        private void SerializePropertyValue(object value, StringBuilder result)
        {
            // Transform boolean, numeric and string objects into their primitive equivalents.
            if (value is NumberInstance)
            {
                value = ((NumberInstance)value).Value;
            }
            else if (value is StringInstance)
            {
                value = ((StringInstance)value).Value;
            }
            else if (value is BooleanInstance)
            {
                value = ((BooleanInstance)value).Value;
            }

            // Serialize a null value.
            if (value == Null.Value)
            {
                result.Append("null");
                return;
            }

            // Serialize a boolean value.
            if (value is bool)
            {
                if ((bool)value == false)
                {
                    result.Append("false");
                }
                else
                {
                    result.Append("true");
                }
                return;
            }

            // Serialize a string value.
            if (value is string || value is ConcatenatedString)
            {
                QuoteString(value.ToString(), result);
                return;
            }

            // Serialize a numeric value.
            if (value is double)
            {
                if (double.IsInfinity((double)value) == true || double.IsNaN((double)value))
                {
                    result.Append("null");
                }
                else
                {
                    result.Append(NumberFormatter.ToString((double)value, 10, NumberFormatter.Style.Regular));
                }
                return;
            }
            if (value is int)
            {
                result.Append(((int)value).ToString());
                return;
            }

            // Serialize an array.
            if (value is ArrayInstance)
            {
                SerializeArray((ArrayInstance)value, result);
                return;
            }

            // Serialize an object.
            if (value is ObjectInstance && (value is FunctionInstance) == false)
            {
                SerializeObject((ObjectInstance)value, result);
                return;
            }

            // The value is of a type we cannot serialize.
            throw new NotSupportedException(string.Format("Unsupported value type: {0}", value.GetType()));
        }
 public void FormatNullValue()
 {
     NumberFormatter fmt = new NumberFormatter();
     Assert.Throws<ArgumentNullException>(() => fmt.Format(null));
 }