public void SetSimulationDisplay(Precision Precision, Point Origo, double Radius = -1) { if (this.precision != Precision) precision = Precision; this.origo = Origo; if (Radius < commonRadius) Radius = commonRadius; switch (Precision) { case Precision.NoTag: Hide(); break; case Precision.OneTag: Visible(); this.radius = Radius; break; case Precision.TwoTag: Visible(); this.radius = Radius; break; case Precision.ThreeOrMoreTag: Visible(); this.radius = commonRadius; break; } ApplyRadius(); label_devicepos.Content = String.Format("({0} ; {1})", Math.Round(Origo.X, 2), Math.Round(Origo.Y, 2)); Canvas.SetLeft(label_devicepos, Origo.X + 10); Canvas.SetTop(label_devicepos, Origo.Y - 20); }
public MGRSorUSNGCoordinates(CoordinateType.Enum coordinateType, string warningMessage, string MGRSString, Precision.Enum precision) { this.coordinateType = coordinateType; this.precision = precision; this.MGRSString = MGRSString; this.warningMessage = warningMessage; }
public static extern void glslopt_shader_get_input_desc(IntPtr shader, int index, out IntPtr outName, out BasicType outType, out Precision outPrec, out int outVecSize, out int outMatSize, out int outArraySize, out int outLocation);
public static DateTime ToPrecision(this DateTime dateTime, Precision precision) { switch (precision) { case Precision.Date: return dateTime.Date; case Precision.Hour: return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0); case Precision.Minute: return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0); case Precision.Second: return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second); default: return dateTime; } }
public static double GetPrecision(double x, Precision? thisPrecision) { if(thisPrecision.HasValue) { double dif = 0; switch (thisPrecision) { case Precision.EXACT: return x; case Precision.TWOFEET: dif = x%0.0001; break; case Precision.TWENTYFEET: dif = x%0.001; break; case Precision.TWOHUNDREDFEET: dif = x%0.01; break; } return x - dif; } return x; }
private void addJudgementOffsetAssert(OsuHitObject hitObject, double offset) { AddAssert($"({hitObject.GetType().ReadableName()} @ {hitObject.StartTime}) judged at {offset}", () => Precision.AlmostEquals(judgementResults.Single(r => r.HitObject == hitObject).TimeOffset, offset, 100)); }
/// <summary> /// Gets ratio value selected of signal strength estimation precision. /// </summary> public static double GetPrecisionValue(Precision pPrecision) { return double.Parse(XmlParser.GetValue("Precision", pPrecision.ToString())); }
private void addSeekStep(Func <double> time) { AddStep("seek to time", () => Player.GameplayClockContainer.Seek(time())); AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(time(), Player.DrawableRuleset.FrameStableClock.CurrentTime, 100)); }
//Start void Start() { //Data from option speedmod = DataManager.Instance.speedmodSelected*speedmodRate; DataManager.Instance.LoadScoreJudge(DataManager.Instance.scoreJudgeSelected); DataManager.Instance.LoadHitJudge(DataManager.Instance.hitJudgeSelected); DataManager.Instance.LoadLifeJudge(DataManager.Instance.lifeJudgeSelected); isFullComboRace = DataManager.Instance.raceSelected == 9; isFullExComboRace = DataManager.Instance.raceSelected == 10; targetScoreInverse = DataManager.Instance.giveTargetScoreOfRace(DataManager.Instance.raceSelected); typeOfDeath = DataManager.Instance.deathSelected; KeyCodeDown = DataManager.Instance.KeyCodeDown; KeyCodeUp = DataManager.Instance.KeyCodeUp; KeyCodeLeft = DataManager.Instance.KeyCodeLeft; KeyCodeRight = DataManager.Instance.KeyCodeRight; SecondaryKeyCodeDown = DataManager.Instance.SecondaryKeyCodeDown; SecondaryKeyCodeUp = DataManager.Instance.SecondaryKeyCodeUp; SecondaryKeyCodeLeft = DataManager.Instance.SecondaryKeyCodeLeft; SecondaryKeyCodeRight = DataManager.Instance.SecondaryKeyCodeRight; speedmodSelected = DataManager.Instance.speedmodSelected; speedmodstring = DataManager.Instance.speedmodSelected.ToString("0.00"); speedmodok = true; var rand = (int)(UnityEngine.Random.value*DataManager.Instance.skyboxList.Count); if(rand == DataManager.Instance.skyboxList.Count){ rand--; } //Arrows for(int i=0;i<4;i++){ if(i != DataManager.Instance.skinSelected){ var go = GameObject.Find("ArrowSkin" + i); Destroy(go); var go2 = GameObject.Find("ArrowModelSkin" + i); Destroy(go2); } } arrow = typeArrow.ElementAt(DataManager.Instance.skinSelected); var modelskin = GameObject.Find("ArrowModelSkin" + DataManager.Instance.skinSelected); modelskin.SetActiveRecursively(false); arrowLeft = (GameObject) Instantiate(modelskin, new Vector3(0f, 0f, 2f), modelskin.transform.rotation); if(DataManager.Instance.skinSelected == 3){ arrowLeft.transform.FindChild("RotationCenter").Rotate(0f, 0f, 90f); }else if(DataManager.Instance.skinSelected != 0){ arrowLeft.transform.Rotate(0f, 0f, 90f); arrowLeft.transform.FindChild("ParticulePrec").Rotate(0f, 0f, -90f); arrowLeft.transform.FindChild("ParticulePrec").localPosition = new Vector3(-1f, 0f, 0f); } arrowLeft.transform.parent = MainCamera.gameObject.transform; arrowRight = (GameObject) Instantiate(modelskin, new Vector3(6f, 0f, 2f), modelskin.transform.rotation); if(DataManager.Instance.skinSelected == 3){ arrowRight.transform.FindChild("RotationCenter").Rotate(0f, 0f, -90f); }else if(DataManager.Instance.skinSelected == 1){ arrowRight.transform.Rotate(0f, 0f, -90f); arrowRight.transform.FindChild("ParticulePrec").Rotate(0f, 0f, 90f); arrowRight.transform.FindChild("ParticulePrec").localPosition = new Vector3(1f, 0f, 0f); } arrowRight.transform.parent = MainCamera.gameObject.transform; arrowDown = (GameObject) Instantiate(modelskin, new Vector3(2f, 0f, 2f), modelskin.transform.rotation); if(DataManager.Instance.skinSelected == 3){ arrowDown.transform.FindChild("RotationCenter").Rotate(0f, 0f, 180f); }else if(DataManager.Instance.skinSelected == 1){ arrowDown.transform.Rotate(0f, 0f, 180f); arrowDown.transform.FindChild("ParticulePrec").Rotate(0f, 0f, -180f); arrowDown.transform.FindChild("ParticulePrec").localPosition = new Vector3(0f, 1f, 0f); } arrowDown.transform.parent = MainCamera.gameObject.transform; arrowUp = (GameObject) Instantiate(modelskin, new Vector3(4f, 0f, 2f), modelskin.transform.rotation); arrowUp.transform.parent = MainCamera.gameObject.transform; arrowTarget = new Transform[4]; arrowTarget[0] = arrowLeft.transform; arrowTarget[1] = arrowDown.transform; arrowTarget[2] = arrowUp.transform; arrowTarget[3] = arrowRight.transform; scaleBase = arrowTarget[0].localScale.x; matArrowModel = matSkinModel[DataManager.Instance.skinSelected]; RenderSettings.skybox = DataManager.Instance.skyboxList.ElementAt(rand); DataManager.Instance.skyboxIndexSelected = rand; displayValue = DataManager.Instance.displaySelected; firstArrow = -10f; lastArrow = -10f; thesong = DataManager.Instance.songSelected; songLoaded = thesong.GetAudioClip(); audio.loop = false; createTheChart(thesong); Application.targetFrameRate = -1; QualitySettings.vSyncCount = 0; nextSwitchBPM = 1; nextSwitchStop = 0; actualBPM = thesong.bpms.First().Value; actualstop = (double)0; changeBPM = 0; _count = 0L; timebpm = (double)0; timechart = 0f;//-(float)thesong.offset; timetotalchart = (double)0; arrowFrozen = new Dictionary<Arrow, float>(); precRight = new Dictionary<string, ParticleSystem>(); precLeft = new Dictionary<string, ParticleSystem>(); precUp = new Dictionary<string, ParticleSystem>(); precDown = new Dictionary<string, ParticleSystem>(); clearcombo = new Dictionary<string, ParticleSystem>(); //Prepare the scene foreach(var el in Enum.GetValues(typeof(PrecParticle))){ precLeft.Add( el.ToString(), (ParticleSystem) arrowLeft.transform.FindChild("ParticulePrec").gameObject.transform.FindChild(el.ToString()).particleSystem ); precDown.Add( el.ToString(), (ParticleSystem) arrowDown.transform.FindChild("ParticulePrec").gameObject.transform.FindChild(el.ToString()).particleSystem ); precRight.Add( el.ToString(), (ParticleSystem) arrowRight.transform.FindChild("ParticulePrec").gameObject.transform.FindChild(el.ToString()).particleSystem ); precUp.Add( el.ToString(), (ParticleSystem) arrowUp.transform.FindChild("ParticulePrec").gameObject.transform.FindChild(el.ToString()).particleSystem ); } for(int i=0; i< particleComboCam.transform.GetChildCount(); i++){ clearcombo.Add(particleComboCam.transform.GetChild(i).name, particleComboCam.transform.GetChild(i).particleSystem); } precAverage = new List<double>(); timeCombo = new Dictionary<double, int>(); lifeGraph = new Dictionary<double, double>(); TMainCamera = MainCamera.transform; MoveCameraBefore(); //Textures TextureBase = new Dictionary<string, Texture2D>(); TextureBase.Add("FANTASTIC", (Texture2D) Resources.Load("Fantastic")); TextureBase.Add("EXCELLENT", (Texture2D) Resources.Load("Excellent")); TextureBase.Add("GREAT", (Texture2D) Resources.Load("Great")); TextureBase.Add("DECENT", (Texture2D) Resources.Load("Decent")); TextureBase.Add("WAYOFF", (Texture2D) Resources.Load("Wayoff")); TextureBase.Add("MISS", (Texture2D) Resources.Load("Miss")); for(int i=0; i<10; i++){ TextureBase.Add("S" + i, (Texture2D) Resources.Load("Numbers/S" + i)); TextureBase.Add("C" + i, (Texture2D) Resources.Load("Numbers/C" + i)); } TextureBase.Add("PERCENT", (Texture2D) Resources.Load("Numbers/Percent")); TextureBase.Add("DOT", (Texture2D) Resources.Load("Numbers/Dot")); TextureBase.Add("COMBODISPLAY", (Texture2D) Resources.Load("DisplayCombo")); TextureBase.Add("BLACK", (Texture2D) Resources.Load("black")); TextureBase.Add("FAIL", (Texture2D) Resources.Load("Fail")); TextureBase.Add("CLEAR", (Texture2D) Resources.Load("Clear")); TextureBase.Add("FC", (Texture2D) Resources.Load("FC")); TextureBase.Add("FEC", (Texture2D) Resources.Load("FEC")); TextureBase.Add("FFC", (Texture2D) Resources.Load("FFC")); TextureBase.Add("PERFECT", (Texture2D) Resources.Load("Perfect")); //stuff scoreToDisplay = Precision.NONE; timeDisplayScore = Mathf.Infinity; sensFantastic = true; alpha = 1f; scenechartfaded = false; //init score and lifebase scoreBase = new Dictionary<string, float>(); scoreCount = new Dictionary<string, int>(); lifeBase = new Dictionary<string, float>(); fantasticValue = 100f/(thesong.numberOfStepsWithoutJumps + thesong.numberOfJumps + thesong.numberOfFreezes + thesong.numberOfRolls); foreach(Precision el in Enum.GetValues(typeof(Precision))){ if(el != Precision.NONE){ scoreBase.Add(el.ToString(), fantasticValue*DataManager.Instance.ScoreWeightValues[el.ToString()]); lifeBase.Add(el.ToString(), DataManager.Instance.LifeWeightValues[el.ToString()]); } } foreach(ScoreCount el2 in Enum.GetValues(typeof(ScoreCount))){ if(el2 != ScoreCount.NONE){ scoreCount.Add(el2.ToString(), 0); } } life = 50f; lifeGraph.Add(0, life); score = 0f; scoreInverse = 100f; firstEx = -1; firstGreat = -1; firstMisteak = -1; theLifeBar = lifeBar.GetComponent<LifeBar>(); //var bps = thesong.getBPS(actualBPM); //changeBPM -= (float)(bps*thesong.offset)*speedmod; firstUpdate = true; oneSecond = 0f; startTheSong = (float)thesong.offset + DataManager.Instance.globalOffsetSeconds; //bump nextBump = 0; //combo ct = ComboType.FULLFANTASTIC; matProgressBar = progressBarEmpty.renderer.material; matProgressBarFull = progressBar.renderer.material; colorCombo = 1f; comboMisses = 0; alphaCombo = 0.5f; //GUI /*wd = posPercent.width*128; hg = posPercent.height*1024; hgt = posPercent.height*254;*/ //ecart = 92f; displaying = scoreDecoupe(); thetab = comboDecoupe(); //Fail and clear fail = false; clear = false; fullCombo = false; fullExCombo = false; fullFantCombo = false; perfect = false; dead = false; zwip = 0; appearFailok = false; disappearFailok = false; zoomfail = 0f; failalpha = 0f; passalpha = 0f; cacheFailed = true; timeGiveUp = 0f; //Transformation display if(displayValue[4]){ //No judge limitDisplayScore = -1f; } if(displayValue[5]){ //No background RenderSettings.skybox = null; Background.GetComponent<MoveBackground>().enabled = false; Background.SetActiveRecursively(false); } if(displayValue[6]){ //No target arrowLeft.renderer.enabled = false; arrowDown.renderer.enabled = false; arrowUp.renderer.enabled = false; arrowRight.renderer.enabled = false; } //No score : inside the code //No UI if(displayValue[8]){ for(int i=0;i<lifeBar.transform.childCount; i++){ lifeBar.transform.GetChild(i).renderer.enabled = false; } progressBar.renderer.enabled = false; progressBarEmpty.renderer.enabled = false; slow.renderer.enabled = false; fast.renderer.enabled = false; } }
public Font(Device device, int height, int width, FontWeight weight, int mipLevels, bool italic, CharacterSet characterSet, Precision outputPrecision, FontQuality quality, PitchAndFamily pitchAndFamily, string faceName) : base(device, height, width, weight, mipLevels, italic, characterSet, outputPrecision, quality, pitchAndFamily, faceName) { }
//--------------------------------------------------------------------- /// <summary> /// Alternative constructor. /// </summary> /// <param name="rows"> /// The number of rows of the elevation matrix. /// </param> /// <param name="cols"> /// The number of columns of the elevation matrix. /// </param> /// <param name="bottomLeft"> /// A <see cref="Points.Point"/> object that represents the coordinates /// of the bottom left corner of the elevation matrix. /// </param> /// <param name="altitude"> /// The elevation matrix /// </param> /// <param name="noData"> /// The value that represent whether there is no altitude data in a /// specified cell. /// </param> /// <param name="cellSize"> /// The geometric distance among adjacent cells. /// </param> //--------------------------------------------------------------------- protected ArcInfo( int rows, int cols, Point bottomLeft, double[,] altitude, double noData, double cellSize, int metCellSize, Precision precision) : base(rows, cols, bottomLeft, altitude, noData, cellSize, metCellSize, precision) { }
private void pressAndCheckTime(Key key, double expectedTime) { AddStep($"press {key}", () => InputManager.Key(key)); AddUntilStep($"time is {expectedTime}", () => Precision.AlmostEquals(expectedTime, EditorClock.CurrentTime, 1)); }
/// <summary> /// Return a String representation of this MGRS reference to 1m, 10m, 100m, 1000m or 10000m precision. /// </summary> /// <param name="precision"> The required precision. </param> /// <returns> A string representation of this MGRS reference to the required precision. </returns> public string ToString(Precision precision) { var eastingR = (int) Math.Floor(Easting/(int) precision); var northingR = (int) Math.Floor(Northing/(int) precision); var padding = 5; switch (precision) { case Precision.Precision10M: padding = 4; break; case Precision.Precision100M: padding = 3; break; case Precision.Precision1000M: padding = 2; break; case Precision.Precision10000M: padding = 1; break; } var eastingRs = eastingR.ToString(); var ez = padding - eastingRs.Length; while (ez > 0) { eastingRs = "0" + eastingRs; ez--; } var northingRs = northingR.ToString(); var nz = padding - northingRs.Length; while (nz > 0) { northingRs = "0" + northingRs; nz--; } var utmZonePadding = ""; if (LngZone < 10) { utmZonePadding = "0"; } return utmZonePadding + LngZone + LatZone + CollumLetter + RowLetter + eastingRs + northingRs; }
private void UpdateEstimationParameters() { mPrecision = mNodeNetwork.EstimationPrecision; mTreshold = mNodeNetwork.SignalTreshold; //Log.Write(LogLevel.Debug, string.Format("Setting basic estimation parameters:\nPrecision: {0}\nSignal Treshold: {1}", mPrecision, mTreshold)); }
public BinaryDataArray() { Data = null; Precision = Precision.Precision32; ArrayType = ArrayType.m_z_array; ArrayLength = 0; }
public void GainCombo(int c, Precision prec) { combo+= c; alphaCombo = 1f; if(ct != ComboType.NONE && prec != Precision.FANTASTIC){ if(ct == ComboType.FULLFANTASTIC){ switch(prec){ case Precision.EXCELLENT: ct = ComboType.FULLEXCELLENT; firstEx = timetotalchart; break; case Precision.GREAT: ct = ComboType.FULLCOMBO; firstEx = timetotalchart; firstGreat = timetotalchart; break; default: firstEx = timetotalchart; firstGreat = timetotalchart; firstMisteak = timetotalchart; ct = ComboType.NONE; break; } }else if(ct == ComboType.FULLEXCELLENT && prec > Precision.EXCELLENT){ if( prec == Precision.GREAT){ firstGreat = timetotalchart; ct = ComboType.FULLCOMBO; } else { firstGreat = timetotalchart; firstMisteak = timetotalchart; ct = ComboType.NONE; } }else if(ct == ComboType.FULLCOMBO && prec > Precision.GREAT){ firstMisteak = timetotalchart; ct = ComboType.NONE; } } thetab = comboDecoupe(); if(isFullExComboRace && ct == ComboType.FULLCOMBO){ //Debug.Log("Fail at FEC race"); fail = true; } }
public void displayPrec(double prec) { timeDisplayScore = 0f; zoom = baseZoom; scoreToDisplay = timeToPrec(prec); }
void StartParticleUp(Precision prec) { var displayPrec = prec.ToString(); if(prec < Precision.DECENT && combo >= 100) displayPrec += "C"; var ps = precUp[displayPrec]; if(!ps.gameObject.active) ps.gameObject.active = true; ps.Play(); }
protected override double StrainValueOf(DifficultyHitObject current) { var maniaCurrent = (ManiaDifficultyHitObject)current; var endTime = maniaCurrent.EndTime; var column = maniaCurrent.BaseObject.Column; double holdFactor = 1.0; // Factor to all additional strains in case something else is held double holdAddition = 0; // Addition to the current note in case it's a hold and has to be released awkwardly // Fill up the holdEndTimes array for (int i = 0; i < holdEndTimes.Length; ++i) { // If there is at least one other overlapping end or note, then we get an addition, buuuuuut... if (Precision.DefinitelyBigger(holdEndTimes[i], maniaCurrent.StartTime, 1) && Precision.DefinitelyBigger(endTime, holdEndTimes[i], 1)) { holdAddition = 1.0; } // ... this addition only is valid if there is _no_ other note with the same ending. Releasing multiple notes at the same time is just as easy as releasing 1 if (Precision.AlmostEquals(endTime, holdEndTimes[i], 1)) { holdAddition = 0; } // We give a slight bonus to everything if something is held meanwhile if (Precision.DefinitelyBigger(holdEndTimes[i], endTime, 1)) { holdFactor = 1.25; } // Decay individual strains individualStrains[i] = applyDecay(individualStrains[i], current.DeltaTime, individual_decay_base); } holdEndTimes[column] = endTime; // Increase individual strain in own column individualStrains[column] += 2.0 * holdFactor; individualStrain = individualStrains[column]; overallStrain = applyDecay(overallStrain, current.DeltaTime, overall_decay_base) + (1 + holdAddition) * holdFactor; return(individualStrain + overallStrain - CurrentStrain); }
public DistanceHandler(Dictionary<int, double> distances, Dictionary<string, double> distanceLookupCache, Precision precision) { _distances = distances; _distanceLookupCache = distanceLookupCache; _precision = precision; }
/// <summary> /// Subscribes to order book updates for a symbol /// </summary> /// <param name="symbol">The symbol to subscribe to</param> /// <param name="precision">The precision of the updates</param> /// <param name="frequency">The frequency of updates</param> /// <param name="length">The range for the order book updates, either 25 or 100</param> /// <param name="handler">The handler for the data</param> /// <param name="checksumHandler">The handler for the checksum, can be used to validate a order book implementation</param> /// <returns></returns> public async Task <CallResult <UpdateSubscription> > SubscribeToBookUpdatesAsync(string symbol, Precision precision, Frequency frequency, int length, Action <IEnumerable <BitfinexOrderBookEntry> > handler, Action <int>?checksumHandler = null) { symbol.ValidateBitfinexSymbol(); length.ValidateIntValues(nameof(length), 25, 100); var internalHandler = new Action <JToken>(data => { if (data[1].ToString() == "cs") { // Process checksumHandler?.Invoke((int)data[2]); } else { var dataArray = (JArray)data[1]; if (dataArray[0].Type == JTokenType.Array) { HandleData("Book snapshot", dataArray, handler, _bookSerializer); } else { HandleSingleToArrayData("Book update", dataArray, handler, _bookSerializer); } } }); var sub = new BitfinexBookSubscriptionRequest( symbol, JsonConvert.SerializeObject(precision, new PrecisionConverter(false)), JsonConvert.SerializeObject(frequency, new FrequencyConverter(false)), length); return(await Subscribe(sub, null, false, internalHandler).ConfigureAwait(false)); }
/// <summary> /// Create a new MGRS reference object from the given paramaters. It is assumed /// that this MGRS reference represents a point using the GRS 1980, /// International or WGS84 ellipsoids. An IllegalArgumentException is thrown if /// any of the parameters are invalid. /// </summary> /// <param name="utmZoneNumber">The UTM zone number representing the longitude.</param> /// <param name="utmZoneChar">The UTM zone character representing the latitude.</param> /// <param name="eastingID">Character representing the 100,000km easting square.</param> /// <param name="northingID">Character representing the 100,000km northing square.</param> /// <param name="easting">Easting in metres.</param> /// <param name="northing">Northing in metres.</param> /// <param name="precision">The precision of the given easting and northing.</param> /// <exception cref="ArgumentException">If any of the given parameters are invalid.</exception> public MGRSRef(int utmZoneNumber, char utmZoneChar, char eastingID, char northingID, int easting, int northing, Precision precision) : this(utmZoneNumber, utmZoneChar, eastingID, northingID, easting, northing, precision, false) { }
/// <summary>Create a font object</summary> public Font CreateFont(Device device, int height, int width, FontWeight weight, int mip, bool italic, CharacterSet charSet, Precision outputPrecision, FontQuality quality, PitchAndFamily pandf, string fontName) { // Create the font description FontDescription desc = new FontDescription(); desc.Height = height; desc.Width = width; desc.Weight = weight; desc.MipLevels = mip; desc.IsItalic = italic; desc.CharSet = charSet; desc.OutputPrecision = outputPrecision; desc.Quality = quality; desc.PitchAndFamily = pandf; desc.FaceName = fontName; // return the font return CreateFont(device, desc); }
//--------------------------------------------------------------------- /// <summary> /// Alternative constructor. Use it when a header file is needed to be /// loaded. /// </summary> /// <param name="path"> /// The elevation matrix container file path. /// </param> /// <param name="headerPath"> /// The header container file path. /// </param> //--------------------------------------------------------------------- public Srtm(string path, string headerPath, Precision precision) : base(path, headerPath, precision) { }
//--------------------------------------------------------------------- /// <summary> /// Alternative Constructor. /// </summary> /// <param name="rows"> /// Number of rows of the altitude matrix. /// </param> /// <param name="cols"> /// Number of columns of the altitude matrix. /// </param> /// <param name="bottomLeft"> /// Waypoint that represents the bottom left corner position of /// altitude matrix. /// </param> /// <param name="altitude"> /// The altitude matrix. /// </param> /// <param name="noData"> /// The value that represent whether there is no altitude data in a /// specified cell. /// </param> /// <param name="cellSize"> /// The geometric distance among adjacent cells. /// </param> /// <param name="coordSystem"> /// The coordinate system that DEM is referred. /// </param> //--------------------------------------------------------------------- protected Dem(int rows, int cols, Point bottomLeft, double[,] altitude, double noData, double cellSize, int metCellSize, Precision precision) { this.rows = rows; this.cols = cols; this.bottomLeft = bottomLeft; this.altitude = altitude; this.noData = noData; this.cellSize = cellSize; this.metCellSize = metCellSize; this.precision = precision; }
private bool positionAlmostSame(Vector2 previous, Vector2 current) => Precision.AlmostEquals(previous, current, 1);
/// <summary> /// Calculate Mandelbrot set iteration /// </summary> /// <param name="zx">Starting real part</param> /// <param name="zy">Starting imaginary part</param> /// <param name="cx">Offset constant real part</param> /// <param name="cy">Offset constant imaginary part</param> /// <param name="maxiters">Maximum number of iterations</param> /// <param name="precision">Precision to use</param> /// <returns>Adjusted iteration count</returns> public static double iterate(Fixed128 zx, Fixed128 zy, Fixed128 cx, Fixed128 cy, int maxiters, Precision precision) { return iterate_cs(ref zx, ref zy, ref cx, ref cy, maxiters, (int)precision); }
double precToTime(Precision prec) { if(prec <= Precision.WAYOFF){ return DataManager.Instance.PrecisionValues[prec]; } return 0; /*switch(prec){ case Precision.FANTASTIC: return 0.0215; case Precision.EXCELLENT: return 0.043; case Precision.GREAT: return 0.102; case Precision.DECENT: return 0.135; case Precision.WAYOFF: return 0.180; default: return 0; }*/ }
/// <summary> /// Create a new MGRS reference object from the given String. Must be correctly /// formatted otherwise an ArgumentException will be thrown. /// /// Matching regex: (\d{1,2})([A-Z])([A-Z])([A-Z])(\d{2,10}) /// </summary> /// <param name="gridRef">a string to create an MGRS reference from.</param> /// <param name="isBessel">True if the parameters represent an MGRS reference using the /// Bessel 1841 ellipsoid; false is the parameters represent an MGRS /// reference using the GRS 1980, International or WGS84 ellipsoids.</param> /// <exception cref="ArgumentException">if the given String is not correctly formatted.</exception> public MGRSRef(string gridRef, bool isBessel) : base(WGS84Datum.Instance) { if (String.IsNullOrEmpty(gridRef) || gridRef.Length < 6) throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")", "gridRef"); int begin = 0; int length = 1; char[] gridRefArray = gridRef.ToCharArray(); if (char.IsDigit(gridRefArray[1])) length = 2; this.utmZoneNumber = int.Parse(gridRef.Substring(begin, length)); begin += length; if (!(char.IsUpper(gridRefArray[begin]) && char.IsUpper(gridRefArray[begin + 1]) && char.IsUpper(gridRefArray[begin + 2]))) throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")", "gridRef"); this.utmZoneChar = gridRefArray[begin]; this.eastingID = gridRefArray[begin + 1]; this.northingID = gridRefArray[begin + 2]; begin += 3; for (length = 0; begin + length < gridRefArray.Length; length++) { if (!char.IsDigit(gridRefArray[begin + length])) throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")", "gridRef"); } if (length < 2 || length % 2 != 0) throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")", "gridRef"); this.precision = (Precision)Math.Pow(10, 5 - (length / 2)); this.easting = int.Parse(gridRef.Substring(begin, length / 2)) * (int)this.precision; this.northing = int.Parse(gridRef.Substring(begin + length / 2)) * (int)this.precision; }
private bool cursorCenteredInContainer() => Precision.AlmostEquals( cursorContainer.ActiveCursor.ScreenSpaceDrawQuad.Centre, container.ScreenSpaceDrawQuad.Centre);
private bool showCutOff() { // nur wenn beide Kurven gültig sind if ((iCurve1 != null) && (iCurve2 != null) && (iCurve1 != iCurve2)) { Plane pl; // nur bei gemeisamer Ebene if (Curves.GetCommonPlane(iCurve1, iCurve2, out pl)) { // !!! // owner = (iCurve1 as IGeoObject).Owner; // owner merken für löschen und Einfügen pl.Align(base.ActiveDrawingPlane, false); // Winkel anpassen ICurve2D curve1_2D = iCurve1.GetProjectedCurve(pl); // die 2D-Kurven if (curve1_2D is Path2D) { (curve1_2D as Path2D).Flatten(); } ICurve2D curve2_2D = iCurve2.GetProjectedCurve(pl); if (curve2_2D is Path2D) { (curve2_2D as Path2D).Flatten(); } ICurve newCurve = iCurve1.Clone(); // neue Kurve bis zum Schnittpunkt // hier die Schnittpunkte bestimmen und den cutPoint auf den nächsten Schnittpunt setzen GeoPoint2DWithParameter cutPoint; if (Curves2D.NearestPoint(curve1_2D.Intersect(curve2_2D), pl.Project(objectPoint), out cutPoint)) // runden war möglich { GeoVector2D v1 = curve1_2D.DirectionAt(cutPoint.par1); // die Richtung im Schnittpunkt if (cutPoint.par1 > 0.5) { v1 = v1.Opposite(); // evtl rumdrehen, falls am Ende } v1.Norm(); GeoVector2D v2 = curve2_2D.DirectionAt(cutPoint.par2); // die Richtung im Schnittpunkt if (cutPoint.par2 > 0.5) { v2 = v2.Opposite(); // evtl rumdrehen, falls am Ende } v2.Norm(); GeoVector2D v = (v1 + v2); // Winkelhalbierende if (Precision.IsNullVector(pl.ToGlobal(v))) { return(false); } v.Norm(); v = cutOffLen * v; // Winkelhalbierende mit Fas-Abstand GeoPoint2D dirPoint = cutPoint.p + v; // wird unten auch als Auswahlpunkt für die Richtung genutzt Line2D line2D = new Line2D(dirPoint, cutPoint.p); // Linie vorbesetzen, Punkte eigentlich egal if ((methodSelect == 0) || (methodSelect == 1)) { // 0: Länge cutOffLen = Seitenlänge Kurve1 1: Länge cutOffLen = Fasenlänge double sideLength; if (methodSelect == 1) // Länge cutOffLen = Fasenlänge // Geometrie, Pythagoras, bekannt Seite=cutOffLen, Winkel 1 = cutOffAng, Winkel 2 = Winkel der Kurven im Schnittpunkt { sideLength = cutOffLen * (Math.Cos(cutOffAng.Radian) + (Math.Sin(cutOffAng.Radian) / Math.Tan(Math.Abs(new SweepAngle(v1, v2).Radian)))); } else { sideLength = cutOffLen; } // neue Kurve bis zum Schnittpunkt synthetisieren, dazu: Schnittpunkt finden des Abschnitts mit der iCurve1 Ellipse arcTmp = Ellipse.Construct(); arcTmp.SetCirclePlaneCenterRadius(pl, pl.ToGlobal(cutPoint.p), sideLength); ICurve2D curveArc_2D = (arcTmp as ICurve).GetProjectedCurve(pl); // die 2D-Kurve GeoPoint2DWithParameter cutArc; GeoPoint2D startPoint; if (Curves2D.NearestPoint(curve1_2D.Intersect(curveArc_2D), dirPoint, out cutArc)) // war möglich { startPoint = cutArc.p; } else { return(false); } /* * double parCut; * // neue Kurve bis zum Schnittpunkt sythetisieren: * if (cutPoint.par1 <= 0.5) * { * newCurve.StartPoint = iCurve1.PointAt(cutPoint.par1); * parCut = (sideLength)/newCurve.Length; // der Parameter des Fasenpunktes * } * else * { * newCurve.EndPoint = iCurve1.PointAt(cutPoint.par1); * parCut = (newCurve.Length-sideLength)/newCurve.Length; // der Parameter des Fasenpunktes * } * GeoPoint2D startPoint = pl.Project(newCurve.PointAt(parCut)); * GeoVector2D vc = curve1_2D.DirectionAt(parCut); // die Richtung im Schnittpunkt */ GeoVector2D vc = curve1_2D.DirectionAt(curve1_2D.PositionOf(startPoint)); // die Richtung im Schnittpunkt if (cutPoint.par1 <= 0.5) { vc = vc.Opposite(); // evtl rumdrehen, falls am Ende } if (Geometry.OnLeftSide(dirPoint, startPoint, vc)) // Richtung festlegen für Winkeloffset { vc.Angle = vc.Angle + new SweepAngle(cutOffAng); } else { vc.Angle = vc.Angle - new SweepAngle(cutOffAng); } // Hilfslinie im Fasabstand, im Offsetwinkel line2D = new Line2D(startPoint, startPoint + vc); } if (methodSelect == 2) // Länge cutOffLen = Winkelhalbierendenlänge { v.Angle = v.Angle + new SweepAngle(cutOffAng); // Winkelhalbierendenwinkel + Offset // Hilfslinie im Fasabstand, senkrecht auf der Winkelhalbierenden v line2D = new Line2D(dirPoint, dirPoint + v.ToLeft()); } GeoPoint2DWithParameter cutPoint1; GeoPoint2DWithParameter cutPoint2; // schnittpunkte der Hilfslinie mit den beiden Kurven if (Curves2D.NearestPoint(curve1_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint1)) { if (Curves2D.NearestPoint(curve2_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint2)) { // da isse, die Fas-Linie, nur, wenn die Punkte echt auf der Kurve bis zum Schnittpunkt liegen: bool onCurve1, onCurve2; if (cutPoint.par1 > 0.5) { onCurve1 = (cutPoint1.par1 > 0.0) & (cutPoint1.par1 < 100); } // im Quasi-Parallelfall stehen in par1 riesige Werte else { onCurve1 = (cutPoint1.par1 < 1.0) & (cutPoint1.par1 > -100); } if (cutPoint.par2 > 0.5) { onCurve2 = (cutPoint2.par1 > 0.0) & (cutPoint2.par1 < 100); } else { onCurve2 = (cutPoint2.par1 < 1.0) & (cutPoint2.par1 > -100); } if (onCurve1 && onCurve2) { Line line = Line.Construct(); line.SetTwoPoints(pl.ToGlobal(cutPoint1.p), pl.ToGlobal(cutPoint2.p)); // Fasenlänge vorgegeben, aber mit obiger Berechnung falsch, da dort Linien vorausgesetzt werden if ((methodSelect == 1) && (Math.Abs(line.Length - cutOffLen) > Precision.eps)) { // jetzt mit Iteration annähern double parInd = 0.5; double parIndDelta = 0.25; for (int i = 0; i < 49; ++i) // 48 Schritte müssen reichen, par kann zwischen 0 und 1 liegen { GeoPoint2D startPoint = pl.Project(newCurve.PointAt(parInd)); GeoVector2D vc = curve1_2D.DirectionAt(parInd); // die Richtung im Schnittpunkt if (cutPoint.par1 <= 0.5) { vc = vc.Opposite(); // evtl rumdrehen, falls am Ende } if (Geometry.OnLeftSide(dirPoint, startPoint, vc)) // Richtung festlegen für Winkeloffset { vc.Angle = vc.Angle + new SweepAngle(cutOffAng); } else { vc.Angle = vc.Angle - new SweepAngle(cutOffAng); } // Hilfslinie im Fasabstand, im Offsetwinkel line2D = new Line2D(startPoint, startPoint + vc); if (Curves2D.NearestPoint(curve1_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint1)) { if (Curves2D.NearestPoint(curve2_2D.Intersect(line2D as ICurve2D), cutPoint.p + v, out cutPoint2)) { // da isse, die Fas-Linie, nur, wenn die Punkte echt auf der Kurvr liegen: if (cutPoint.par1 > 0.5) { onCurve1 = (cutPoint1.par1 > 0.0) & (cutPoint1.par1 < 100); } // im Quasi-Parallelfall stehen in par1 riesige Werte else { onCurve1 = (cutPoint1.par1 < 1.0) & (cutPoint1.par1 > -100); } if (cutPoint.par2 > 0.5) { onCurve2 = (cutPoint2.par1 > 0.0) & (cutPoint2.par1 < 100); } else { onCurve2 = (cutPoint2.par1 < 1.0) & (cutPoint2.par1 > -100); } if (onCurve1 && onCurve2) { line.SetTwoPoints(pl.ToGlobal(cutPoint1.p), pl.ToGlobal(cutPoint2.p)); if ((Math.Abs(line.Length - cutOffLen) < Precision.eps)) // gefunden und raus { break; } else { if (line.Length < cutOffLen) { // Fase ist zu klein: Parameter parInd vergrößern parInd = parInd + parIndDelta; parIndDelta = parIndDelta / 2.0; // delta halbieren (Bisection!!) continue; // nächster Schritt in der For-Schleife } } } } } // alle anderen Fälle: // Fase ist zu gross: Parameter parInd verkleinern parInd = parInd - parIndDelta; parIndDelta = parIndDelta / 2.0; // delta halbieren (Bisection!!) } // for schleife Iteration } // Ende Iteration objectPoint = pl.ToGlobal(cutPoint.p); if (iCurve1.PositionOf(objectPoint) > 0.5) // am oberen Ende geklickt { iCurve1.Trim(0.0, iCurve1.PositionOf(line.StartPoint)); } else { iCurve1.Trim(iCurve1.PositionOf(line.StartPoint), 1.0); } if (iCurve2.PositionOf(objectPoint) > 0.5) // am oberen Ende geklickt { iCurve2.Trim(0.0, iCurve2.PositionOf(line.EndPoint)); objectPoint = iCurve2.StartPoint; } else { iCurve2.Trim(iCurve2.PositionOf(line.EndPoint), 1.0); objectPoint = iCurve2.EndPoint; } (line as IGeoObject).CopyAttributes(iCurve1 as IGeoObject); // objectPoint = pl.ToGlobal(cutPoint2.p); blk.Add(iCurve1 as IGeoObject); blk.Add(line); // base.FeedBack.AddSelected(iCurve1 as IGeoObject);// darstellen // base.FeedBack.AddSelected(line);// darstellen iCurve1 = iCurve2; // getrimmte Curve2 als Grundlage zur nächsten Berechnung return(true); } } } } } blk.Add(iCurve1 as IGeoObject); // unveränderte 1. Kurve zufügen, da kein Fasen möglich // base.FeedBack.AddSelected(iCurve1 as IGeoObject);// darstellen iCurve1 = iCurve2; // unveränderte Curve2 als Grundlage zur nächsten Berechnung } // base.ActiveObject = null; return(false); }
private bool cursorAtMouseScreenSpace() => Precision.AlmostEquals( cursorContainer.ActiveCursor.ScreenSpaceDrawQuad.Centre, InputManager.CurrentState.Mouse.Position);
private void addSeekStep(Func <Slider> slider) { AddStep("seek to slider", () => Player.GameplayClockContainer.Seek(slider().StartTime)); AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(slider().StartTime, Player.DrawableRuleset.FrameStableClock.CurrentTime, 100)); }
public override bool HandleScale(Vector2 scale, Anchor anchor) { // convert scale to screen space scale = ToScreenSpace(scale) - ToScreenSpace(Vector2.Zero); adjustScaleFromAnchor(ref scale, anchor); // the selection quad is always upright, so use an AABB rect to make mutating the values easier. var selectionRect = getSelectionQuad().AABBFloat; // If the selection has no area we cannot scale it if (selectionRect.Area == 0) { return(false); } // copy to mutate, as we will need to compare to the original later on. var adjustedRect = selectionRect; // first, remove any scale axis we are not interested in. if (anchor.HasFlagFast(Anchor.x1)) { scale.X = 0; } if (anchor.HasFlagFast(Anchor.y1)) { scale.Y = 0; } bool shouldAspectLock = // for now aspect lock scale adjustments that occur at corners.. (!anchor.HasFlagFast(Anchor.x1) && !anchor.HasFlagFast(Anchor.y1)) // ..or if any of the selection have been rotated. // this is to avoid requiring skew logic (which would likely not be the user's expected transform anyway). || SelectedBlueprints.Any(b => !Precision.AlmostEquals(((Drawable)b.Item).Rotation, 0)); if (shouldAspectLock) { if (anchor.HasFlagFast(Anchor.x1)) { // if dragging from the horizontal centre, only a vertical component is available. scale.X = scale.Y / selectionRect.Height * selectionRect.Width; } else { // in all other cases (arbitrarily) use the horizontal component for aspect lock. scale.Y = scale.X / selectionRect.Width * selectionRect.Height; } } if (anchor.HasFlagFast(Anchor.x0)) { adjustedRect.X -= scale.X; } if (anchor.HasFlagFast(Anchor.y0)) { adjustedRect.Y -= scale.Y; } adjustedRect.Width += scale.X; adjustedRect.Height += scale.Y; // scale adjust applied to each individual item should match that of the quad itself. var scaledDelta = new Vector2( adjustedRect.Width / selectionRect.Width, adjustedRect.Height / selectionRect.Height ); foreach (var b in SelectedBlueprints) { var drawableItem = (Drawable)b.Item; // each drawable's relative position should be maintained in the scaled quad. var screenPosition = b.ScreenSpaceSelectionPoint; var relativePositionInOriginal = new Vector2( (screenPosition.X - selectionRect.TopLeft.X) / selectionRect.Width, (screenPosition.Y - selectionRect.TopLeft.Y) / selectionRect.Height ); var newPositionInAdjusted = new Vector2( adjustedRect.TopLeft.X + adjustedRect.Width * relativePositionInOriginal.X, adjustedRect.TopLeft.Y + adjustedRect.Height * relativePositionInOriginal.Y ); updateDrawablePosition(drawableItem, newPositionInAdjusted); drawableItem.Scale *= scaledDelta; } return(true); }
// Converts the object to string public override string ToString() { string str; str = "Leap Indicator: "; switch (LeapIndicator) { case _LeapIndicator.NoWarning: str += "No warning"; break; case _LeapIndicator.LastMinute61: str += "Last minute has 61 seconds"; break; case _LeapIndicator.LastMinute59: str += "Last minute has 59 seconds"; break; case _LeapIndicator.Alarm: str += "Alarm Condition (clock not synchronized)"; break; } str += "\r\nVersion number: " + VersionNumber.ToString() + "\r\n"; str += "Mode: "; switch (Mode) { case _Mode.Unknown: str += "Unknown"; break; case _Mode.SymmetricActive: str += "Symmetric Active"; break; case _Mode.SymmetricPassive: str += "Symmetric Pasive"; break; case _Mode.Client: str += "Client"; break; case _Mode.Server: str += "Server"; break; case _Mode.Broadcast: str += "Broadcast"; break; } str += "\r\nStratum: "; switch (Stratum) { case _Stratum.Unspecified: case _Stratum.Reserved: str += "Unspecified"; break; case _Stratum.PrimaryReference: str += "Primary Reference"; break; case _Stratum.SecondaryReference: str += "Secondary Reference"; break; } str += "\r\nLocal time: " + TransmitTimestamp.ToString(); str += "\r\nPrecision: " + Precision.ToString() + " ms"; str += "\r\nPoll Interval: " + PollInterval.ToString() + " s"; str += "\r\nReference ID: " + ReferenceID.ToString(); str += "\r\nRoot Dispersion: " + RootDispersion.ToString() + " ms"; str += "\r\nRound Trip Delay: " + RoundTripDelay.ToString() + " ms"; str += "\r\nLocal Clock Offset: " + LocalClockOffset.ToString() + " ms"; str += "\r\n"; return(str); }
public bool Equals(ConvertValue other) => Precision.AlmostEquals(StartTime, other.StartTime, conversion_lenience) && Precision.AlmostEquals(EndTime, other.EndTime, conversion_lenience) && Column == other.Column;
private bool showLineDiam() { ArrayList usable1Curves = new ArrayList(); ArrayList usable2Curves = new ArrayList(); Plane pl; double mindist = double.MaxValue; if (tangCurves == null) { return(false); } if (tang2Curves == null) { return(false); } // if (tang3Curves == null) return false; for (int i = 0; i < tangCurves.Length; ++i) { for (int j = 0; j < tang2Curves.Length; ++j) { if (Curves.GetCommonPlane(tangCurves[i], tang2Curves[j], out pl)) { if (Precision.IsPointOnPlane(radiusPoint, pl)) { ICurve2D l2D1 = tangCurves[i].GetProjectedCurve(pl); ICurve2D l2D2 = tang2Curves[j].GetProjectedCurve(pl); ICurve2D l2D3 = new Circle2D(pl.Project(radiusPoint), 0.0); GeoPoint2D[] tangentPoints = Curves2D.TangentCircle(l2D1, l2D2, l2D3, pl.Project(objectPoint), pl.Project(object2Point), pl.Project(radiusPoint)); if (tangentPoints.Length > 0) { // eine gültige Linie ist gefunden //if (curve1Input.Fixed & curve2Input.Fixed & (tangentPoints.Length > 4)) //{ // int debug = 0; //} usable1Curves.Add(tangCurves[i]); // zur lokalen Liste zufügen usable2Curves.Add(tang2Curves[j]); // zur lokalen Liste zufügen for (int l = 0; l < tangentPoints.Length; l += 4) { double dist = Geometry.Dist(tangentPoints[l + 1], pl.Project(objectPoint)) + Geometry.Dist(tangentPoints[l + 2], pl.Project(object2Point)) + Geometry.Dist(tangentPoints[l + 3], pl.Project(radiusPoint)); if (dist < mindist) { mindist = dist; selected = usable1Curves.Count - 1; // merken, welche Kurven die aktuell benutzten sind selected2 = usable2Curves.Count - 1; // selSol / 6 entspricht div 6, um einige Zeilen tiefer weitere 6 Möglichkeiten auswählen zu können // (/ 4) und (* 4), da pro Lösung vier Punkte geliefert werden int m = (l + 4 * (Math.Abs(selSol) % (tangentPoints.Length / 4))) % tangentPoints.Length; center = tangentPoints[m]; circRadCalc = Geometry.Dist(tangentPoints[m + 1], center) * 2.0; } } } if (mindist < double.MaxValue) { // base.MultiSolution = true; base.MultiSolutionCount = tangentPoints.Length / 4; circ.SetCirclePlaneCenterRadius(pl, pl.ToGlobal(center), circRad); tangCurves = (ICurve[])usable1Curves.ToArray(typeof(ICurve)); // überschreibt die eigentliche Liste und wird unten an den Sender zurückgeliefert tang2Curves = (ICurve[])usable2Curves.ToArray(typeof(ICurve)); // überschreibt die eigentliche Liste und wird unten an den Sender zurückgeliefert base.ShowActiveObject = true; return(true); } } } } } base.ShowActiveObject = false; base.MultiSolutionCount = 0; // base.MultiSolution = false; return(false); }
//-------------------------------------------------------------------------------------------------- bool _HasTriangulation(TopoDS_Shape shape) { var faces = shape.Faces(); return(faces.Any(face => BRepTools.Triangulation(face, Precision.Infinite()))); }
public override HitObject Parse(string text) { try { string[] split = text.Split(','); Vector2 pos = new Vector2((int)Parsing.ParseFloat(split[0], Parsing.MAX_COORDINATE_VALUE), (int)Parsing.ParseFloat(split[1], Parsing.MAX_COORDINATE_VALUE)); double startTime = Parsing.ParseDouble(split[2]) + Offset; ConvertHitObjectType type = (ConvertHitObjectType)Parsing.ParseInt(split[3]); int comboOffset = (int)(type & ConvertHitObjectType.ComboOffset) >> 4; type &= ~ConvertHitObjectType.ComboOffset; bool combo = type.HasFlag(ConvertHitObjectType.NewCombo); type &= ~ConvertHitObjectType.NewCombo; var soundType = (LegacySoundType)Parsing.ParseInt(split[4]); var bankInfo = new SampleBankInfo(); HitObject result = null; if (type.HasFlag(ConvertHitObjectType.Circle)) { result = CreateHit(pos, combo, comboOffset); if (split.Length > 5) { readCustomSampleBanks(split[5], bankInfo); } } else if (type.HasFlag(ConvertHitObjectType.Slider)) { PathType pathType = PathType.Catmull; double length = 0; string[] pointSplit = split[5].Split('|'); int pointCount = 1; foreach (var t in pointSplit) { if (t.Length > 1) { pointCount++; } } var points = new Vector2[pointCount]; int pointIndex = 1; foreach (string t in pointSplit) { if (t.Length == 1) { switch (t) { case @"C": pathType = PathType.Catmull; break; case @"B": pathType = PathType.Bezier; break; case @"L": pathType = PathType.Linear; break; case @"P": pathType = PathType.PerfectCurve; break; } continue; } string[] temp = t.Split(':'); points[pointIndex++] = new Vector2((int)Parsing.ParseDouble(temp[0], Parsing.MAX_COORDINATE_VALUE), (int)Parsing.ParseDouble(temp[1], Parsing.MAX_COORDINATE_VALUE)) - pos; } // osu-stable special-cased colinear perfect curves to a CurveType.Linear bool isLinear(Vector2[] p) => Precision.AlmostEquals(0, (p[1].Y - p[0].Y) * (p[2].X - p[0].X) - (p[1].X - p[0].X) * (p[2].Y - p[0].Y)); if (points.Length == 3 && pathType == PathType.PerfectCurve && isLinear(points)) { pathType = PathType.Linear; } int repeatCount = Parsing.ParseInt(split[6]); if (repeatCount > 9000) { throw new ArgumentOutOfRangeException(nameof(repeatCount), @"Repeat count is way too high"); } // osu-stable treated the first span of the slider as a repeat, but no repeats are happening repeatCount = Math.Max(0, repeatCount - 1); if (split.Length > 7) { length = Math.Max(0, Parsing.ParseDouble(split[7])); } if (split.Length > 10) { readCustomSampleBanks(split[10], bankInfo); } // One node for each repeat + the start and end nodes int nodes = repeatCount + 2; // Populate node sample bank infos with the default hit object sample bank var nodeBankInfos = new List <SampleBankInfo>(); for (int i = 0; i < nodes; i++) { nodeBankInfos.Add(bankInfo.Clone()); } // Read any per-node sample banks if (split.Length > 9 && split[9].Length > 0) { string[] sets = split[9].Split('|'); for (int i = 0; i < nodes; i++) { if (i >= sets.Length) { break; } SampleBankInfo info = nodeBankInfos[i]; readCustomSampleBanks(sets[i], info); } } // Populate node sound types with the default hit object sound type var nodeSoundTypes = new List <LegacySoundType>(); for (int i = 0; i < nodes; i++) { nodeSoundTypes.Add(soundType); } // Read any per-node sound types if (split.Length > 8 && split[8].Length > 0) { string[] adds = split[8].Split('|'); for (int i = 0; i < nodes; i++) { if (i >= adds.Length) { break; } int sound; int.TryParse(adds[i], out sound); nodeSoundTypes[i] = (LegacySoundType)sound; } } // Generate the final per-node samples var nodeSamples = new List <List <HitSampleInfo> >(nodes); for (int i = 0; i < nodes; i++) { nodeSamples.Add(convertSoundType(nodeSoundTypes[i], nodeBankInfos[i])); } result = CreateSlider(pos, combo, comboOffset, points, length, pathType, repeatCount, nodeSamples); // The samples are played when the slider ends, which is the last node result.Samples = nodeSamples[nodeSamples.Count - 1]; } else if (type.HasFlag(ConvertHitObjectType.Spinner)) { double endTime = Math.Max(startTime, Parsing.ParseDouble(split[5]) + Offset); result = CreateSpinner(new Vector2(512, 384) / 2, combo, comboOffset, endTime); if (split.Length > 6) { readCustomSampleBanks(split[6], bankInfo); } } else if (type.HasFlag(ConvertHitObjectType.Hold)) { // Note: Hold is generated by BMS converts double endTime = Math.Max(startTime, Parsing.ParseDouble(split[2])); if (split.Length > 5 && !string.IsNullOrEmpty(split[5])) { string[] ss = split[5].Split(':'); endTime = Math.Max(startTime, Parsing.ParseDouble(ss[0])); readCustomSampleBanks(string.Join(":", ss.Skip(1)), bankInfo); } result = CreateHold(pos, combo, comboOffset, endTime + Offset); } if (result == null) { Logger.Log($"Unknown hit object type: {type}. Skipped.", level: LogLevel.Error); return(null); } result.StartTime = startTime; if (result.Samples.Count == 0) { result.Samples = convertSoundType(soundType, bankInfo); } FirstObject = false; return(result); } catch (FormatException) { Logger.Log("A hitobject could not be parsed correctly and will be ignored", LoggingTarget.Runtime, LogLevel.Important); } catch (OverflowException) { Logger.Log("A hitobject could not be parsed correctly and will be ignored", LoggingTarget.Runtime, LogLevel.Important); } return(null); }
private void assertHeight(int index) => AddAssert($"hitobject {index} height", () => { var d = getDrawableHitObject(index); return(d != null && Precision.AlmostEquals(d.DrawHeight, yScale * (float)(d.HitObject.Duration / time_range), 0.1f)); });
/// <summary> /// Subscribes to order book updates for a symbol /// </summary> /// <param name="symbol">The symbol to subscribe to</param> /// <param name="precision">The precision of the updates</param> /// <param name="frequency">The frequency of updates</param> /// <param name="length">The range for the order book updates</param> /// <param name="handler">The handler for the data</param> /// <param name="checksumHandler">The handler for the checksum, can be used to validate a order book implementation</param> /// <returns></returns> public CallResult <UpdateSubscription> SubscribeToBookUpdates(string symbol, Precision precision, Frequency frequency, int length, Action <IEnumerable <BitfinexOrderBookEntry> > handler, Action <int>?checksumHandler = null) => SubscribeToBookUpdatesAsync(symbol, precision, frequency, length, handler, checksumHandler).Result;
private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}", () => Precision.AlmostEquals(getDrawableHitObject(index)?.DrawPosition.Y ?? -1, yScale * relativeY));
private void addSeekStep(double time) { AddStep($"seek to {time}", () => MusicController.SeekTo(time)); AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(time, Player.DrawableRuleset.FrameStableClock.CurrentTime, 100)); }
private void checkLastScrollDelta(Vector2 expected) => AddAssert("correct scroll delta", () => Precision.AlmostEquals(s1.CounterFor("Scroll").LastState.Mouse.ScrollDelta, expected) && Precision.AlmostEquals(s2.CounterFor("Scroll").LastState.Mouse.ScrollDelta, expected));
public void TestZoom0() { reset(); AddAssert("Box at 0", () => Precision.AlmostEquals(boxQuad.TopLeft, scrollQuad.TopLeft)); AddAssert("Box width = 1x", () => Precision.AlmostEquals(boxQuad.Size, scrollQuad.Size)); }
/// <summary> /// Finds all the timing points in a specified time range. /// </summary> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <returns></returns> public List <TimingPoint> GetTimingPointsInTimeRange(double startTime, double endTime) { return(TimingPoints.Where(tp => Precision.DefinitelyBigger(tp.Offset, startTime) && Precision.DefinitelyBigger(endTime, tp.Offset)).ToList()); }
//--------------------------------------------------------------------- /// <summary> /// Main constructor. /// </summary> /// <param name="path">The path of the file.</param> //--------------------------------------------------------------------- protected ArcInfo(string path, Precision precision) : base(path, precision) { }
/// <summary> /// Finds the nearest uninherited timing point which starts after a given time. /// </summary> /// <param name="time"></param> /// <returns></returns> public TimingPoint GetRedlineAfterTime(double time) { return(TimingPoints.FirstOrDefault(tp => Precision.DefinitelyBigger(tp.Offset, time) && tp.Uninherited)); }
public override Metric GetMetric(double numerator, double denominator) { Metric metric = new Precision(); metric.Calculate(numerator, denominator); return metric; }
private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}", () => Precision.AlmostEquals(drawableRuleset.Playfield.AllHitObjects.ElementAt(index).DrawPosition.Y, drawableRuleset.Playfield.HitObjectContainer.DrawHeight * relativeY));
//--------------------------------------------------------------------- /// <summary> /// Alternative constructor. Use it when a header file is needed to be /// loaded. /// </summary> /// <param name="path"> /// The elevation matrix container file path. /// </param> /// <param name="headerPath"> /// The header container file path. /// </param> /// <param name="precision"> /// A <see cref="Precision"/>. /// </param> //--------------------------------------------------------------------- protected Dem(string path, string headerPath, Precision precision) { this.precision = precision; this.path = path; this.headerPath = headerPath; readHeader(); readAltitudes(); }
public override string ToSql() { string sqltype = Type; if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar")) { if (Type.Equals("nchar") || Type.Equals("nvarchar")) { sqltype += " (" + (Size / 2).ToString(CultureInfo.InvariantCulture) + ")"; } else { sqltype += " (" + Size.ToString(CultureInfo.InvariantCulture) + ")"; } } if (Type.Equals("numeric") || Type.Equals("decimal")) { sqltype += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")"; } if (((Database)Parent).Info.Version >= DatabaseInfo.SQLServerVersion.SQLServer2008) { if (Type.Equals("datetime2") || Type.Equals("datetimeoffset") || Type.Equals("time")) { sqltype += "(" + Scale.ToString(CultureInfo.InvariantCulture) + ")"; } } string sql = "CREATE PARTITION FUNCTION [" + Name + "](" + sqltype + ") AS RANGE\r\n "; if (IsBoundaryRight) { sql += "RIGHT"; } else { sql += "LEFT"; } sql += " FOR VALUES ("; string sqlvalues = ""; int valueType = ValueItem(Type); if (valueType == IS_STRING) { Values.ForEach(item => { sqlvalues += "N'" + item + "',"; }); } else if (valueType == IS_DATE) { Values.ForEach(item => { sqlvalues += "'" + DateTime.Parse(item).ToString("yyyyMMdd HH:mm:ss.fff") + "',"; }); } else if (valueType == IS_UNIQUE) { Values.ForEach(item => { sqlvalues += "'{" + item + "}',"; }); } else if (valueType == IS_NUMERIC) { Values.ForEach(item => { sqlvalues += item.Replace(",", ".") + ","; }); } else { Values.ForEach(item => { sqlvalues += item + ","; }); } sql += sqlvalues.Substring(0, sqlvalues.Length - 1) + ")"; return(sql + "\r\nGO\r\n"); }
/// <summary> /// Create a new MGRS reference object from the given String. Must be correctly /// formatted otherwise an ArgumentException will be thrown. /// </summary> /// <param name="gridRef">a string to create an MGRS reference from.</param> /// <param name="isBessel">True if the parameters represent an MGRS reference using the /// Bessel 1841 ellipsoid; false is the parameters represent an MGRS /// reference using the GRS 1980, International or WGS84 ellipsoids.</param> /// <exception cref="ArgumentException">if the given String is not correctly formatted.</exception> public MGRSRef(string gridRef, bool isBessel) : base(WGS84Datum.Instance) { //throw new NotImplementedException(); Regex regex = new Regex(@"(\d{1,2})([A-Z])([A-Z])([A-Z])(\d{2,10})"); Match match = regex.Match(gridRef); if (!match.Success) throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")"); this.utmZoneNumber = int.Parse(match.Groups[1].Value); this.utmZoneChar = match.Groups[2].Value[0]; this.eastingID = match.Groups[3].Value[0]; this.northingID = match.Groups[4].Value[0]; string en = match.Groups[5].Value; int enl = en.Length; if (enl % 2 != 0) { throw new ArgumentException("Invalid MGRS reference (" + gridRef + ")"); } else { this.precision = (Precision)Math.Pow(10, 5 - (enl / 2)); this.easting = int.Parse(en.Substring(0, enl / 2)) * (int)this.precision; this.northing = int.Parse(en.Substring(enl / 2)) * (int)this.precision; } }
public override string ToSql() { string sql = ""; if (((Database)Parent).Info.Version != DatabaseInfo.VersionNumber.SQLServer2000) { sql = "CREATE TYPE " + FullName; if (!IsAssembly) { sql += " FROM [" + Type + "]"; if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar")) { sql += "(" + Size.ToString(CultureInfo.InvariantCulture) + ")"; } if (Type.Equals("numeric") || Type.Equals("decimal")) { sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")"; } if (AllowNull) { sql += " NULL"; } else { sql += " NOT NULL"; } } else { sql += " EXTERNAL NAME [" + AssemblyName + "].[" + AssemblyClass + "]"; } } else { if (!IsAssembly) { sql = "EXEC sp_addtype '" + Name + "', '" + Type; if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar")) { sql += "(" + Size.ToString(CultureInfo.InvariantCulture) + ")"; } if (Type.Equals("numeric") || Type.Equals("decimal")) { sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")"; } sql += "'"; if (AllowNull) { sql += ", 'NULL'"; } else { sql += ", 'NOT NULL'"; } } } sql += "\r\nGO\r\n"; return(sql + ToSQLAddBinds()); }
/// <summary> /// Create a new MGRS reference object from the given UTM reference. It is /// assumed that this MGRS reference represents a point using the GRS 1980, /// International or WGS84 ellipsoids. It is assumed that the UTMRef object is /// valid. /// </summary> /// <param name="utm">A UTM reference.</param> /// <param name="isBessel">true if the parameters represent an MGRS reference using the /// Bessel 1841 ellipsoid; false is the parameters represent an MGRS /// reference using the GRS 1980, International or WGS84 ellipsoids.</param> public MGRSRef(UTMRef utm, bool isBessel) : base(utm.Datum) { int lngZone = utm.LngZone; int set = ((lngZone - 1) % 6) + 1; int eID = (int) Math.Floor(utm.Easting / 100000.0) + (8 * ((set - 1) % 3)); int nID = (int) Math.Floor((utm.Northing % 2000000) / 100000.0); if (eID > 8) eID++; // Offset for no I character if (eID > 14) eID++; // Offset for no O character char eIDc = (char) (eID + 64); // Northing ID offset for sets 2, 4 and 6 if (set % 2 == 0) { nID += 5; } if (isBessel) { nID += 10; } if (nID > 19) { nID -= 20; } char nIDc = northingIDs[nID]; this.utmZoneNumber = lngZone; this.utmZoneChar = utm.LatZone; this.eastingID = eIDc; this.northingID = nIDc; this.easting = (int) Math.Round(utm.Easting) % 100000; this.northing = (int) Math.Round(utm.Northing) % 100000; this.precision = Precision.Precision1M; this.isBessel = isBessel; }
private void seek(int direction, bool snapped, double amount = 1) { if (amount <= 0) { throw new ArgumentException("Value should be greater than zero", nameof(amount)); } var timingPoint = ControlPointInfo.TimingPointAt(CurrentTime); if (direction < 0 && timingPoint.Time == CurrentTime) { // When going backwards and we're at the boundary of two timing points, we compute the seek distance with the timing point which we are seeking into timingPoint = ControlPointInfo.TimingPointAt(CurrentTime - 1); } double seekAmount = timingPoint.BeatLength / beatDivisor.Value * amount; double seekTime = CurrentTime + seekAmount * direction; if (!snapped || ControlPointInfo.TimingPoints.Count == 0) { Seek(seekTime); return; } // We will be snapping to beats within timingPoint seekTime -= timingPoint.Time; // Determine the index from timingPoint of the closest beat to seekTime, accounting for scrolling direction int closestBeat; if (direction > 0) { closestBeat = (int)Math.Floor(seekTime / seekAmount); } else { closestBeat = (int)Math.Ceiling(seekTime / seekAmount); } seekTime = timingPoint.Time + closestBeat * seekAmount; // Due to the rounding above, we may end up on the current beat. This will effectively cause 0 seeking to happen, but we don't want this. // Instead, we'll go to the next beat in the direction when this is the case if (Precision.AlmostEquals(CurrentTime, seekTime)) { closestBeat += direction > 0 ? 1 : -1; seekTime = timingPoint.Time + closestBeat * seekAmount; } if (seekTime < timingPoint.Time && timingPoint != ControlPointInfo.TimingPoints.First()) { seekTime = timingPoint.Time; } var nextTimingPoint = ControlPointInfo.TimingPoints.FirstOrDefault(t => t.Time > timingPoint.Time); if (seekTime > nextTimingPoint?.Time) { seekTime = nextTimingPoint.Time; } // Ensure the sought point is within the boundaries seekTime = MathHelper.Clamp(seekTime, 0, TrackLength); Seek(seekTime); }
/// <summary> /// Create a new MGRS reference object from the given parameters. An /// ArgumentException is thrown if any of the parameters are invalid. /// </summary> /// <param name="utmZoneNumber">The UTM zone number representing the longitude.</param> /// <param name="utmZoneChar">The UTM zone character representing the latitude.</param> /// <param name="eastingId">Character representing the 100,000km easting square.</param> /// <param name="northingId">Character representing the 100,000km northing square.</param> /// <param name="easting">Easting in metres.</param> /// <param name="northing">Northing in metres.</param> /// <param name="precision">The precision of the given easting and northing.</param> /// <param name="isBessel">true if the parameters represent an MGRS reference using the /// Bessel 1841 ellipsoid; false is the parameters represent an MGRS /// reference using the GRS 1980, International or WGS84 ellipsoids.</param> /// <exception cref="ArgumentException">If any of the given parameters are invalid. Note that the /// parameters are only checked for the range of values that they can /// take on. Being able to create an MGRSRef object does not /// necessarily imply that the reference is valid.</exception> public MGRSRef(int utmZoneNumber, char utmZoneChar, char eastingId, char northingId, int easting, int northing, Precision precision, bool isBessel) : base(WGS84Datum.Instance) { if (utmZoneNumber < 1 || utmZoneNumber > 60) { throw new ArgumentException("Invalid utmZoneNumber (" + utmZoneNumber + ")"); } if (utmZoneChar < 'A' || utmZoneChar > 'Z') { throw new ArgumentException("Invalid utmZoneChar (" + utmZoneChar + ")"); } if (eastingId < 'A' || eastingId > 'Z' || eastingId == 'I' || eastingId == 'O') { throw new ArgumentException("Invalid eastingId (" + eastingId + ")"); } if (northingId < 'A' || northingId > 'Z' || northingId == 'I' || northingId == 'O') { throw new ArgumentException("Invalid northingID (" + northingId + ")"); } if (easting < 0 || easting > 99999) { throw new ArgumentException("Invalid easting (" + easting + ")"); } if (northing < 0 || northing > 99999) { throw new ArgumentException("Invalid northing (" + northing + ")"); } this.utmZoneNumber = utmZoneNumber; this.utmZoneChar = utmZoneChar; this.eastingID = eastingId; this.northingID = northingId; this.easting = easting; this.northing = northing; this.precision = precision; this.isBessel = isBessel; }
private void assertHealthNotEqualTo(double value) => AddAssert($"health != {value}", () => !Precision.AlmostEquals(value, processor.Health.Value, 0.0001f));
/// <summary> /// Return a String representation of this MGRS reference to 1m, 10m, 100m, /// 1000m or 10000m precision. /// </summary> /// <param name="precision">The required precision.</param> /// <returns>A string representation of this MGRS reference to the required /// precision.</returns> public string ToString(Precision precision) { int eastingR = (int) Math.Floor((double)(easting / (int)precision)); int northingR = (int)Math.Floor((double)(northing / (int)precision)); int padding = 5; switch (precision) { case Precision.Precision10M: padding = 4; break; case Precision.Precision100M: padding = 3; break; case Precision.Precision1000M: padding = 2; break; case Precision.Precision10000M: padding = 1; break; } string eastingRs = eastingR.ToString(); int ez = padding - eastingRs.Length; while (ez > 0) { eastingRs = "0" + eastingRs; ez--; } string northingRs = northingR.ToString(); int nz = padding - northingRs.Length; while (nz > 0) { northingRs = "0" + northingRs; nz--; } String utmZonePadding = ""; if (utmZoneNumber < 10) { utmZonePadding = "0"; } return utmZonePadding + utmZoneNumber + utmZoneChar + eastingID + northingID + eastingRs + northingRs; }
protected override void Update() { base.Update(); if (isDead) { return; } var elapsedFrameTime = Clock.ElapsedFrameTime; var timeDifference = elapsedFrameTime / 21; if (horizontalDirection > 0) { horizontalSpeed = 3; rightwards = true; } else if (horizontalDirection < 0) { rightwards = false; horizontalSpeed = -3; } else { horizontalSpeed = 0; } if (horizontalSpeed != 0) { updateSpriteDirection(); } if (midAir) { if (Precision.AlmostEquals(verticalSpeed, 0, 0.0001)) { verticalSpeed = 0; } verticalSpeed -= (verticalSpeed > 0 ? IWannaExtensions.PLAYER_GRAVITY_UP : IWannaExtensions.PLAYER_GRAVITY_DOWN) * timeDifference; if (verticalSpeed < -IWannaExtensions.PLAYER_MAX_VERTICAL_SPEED) { verticalSpeed = -IWannaExtensions.PLAYER_MAX_VERTICAL_SPEED; } } var replayState = (GetContainingInputManager().CurrentState as RulesetInputManagerInputState <BosuAction>)?.LastReplayState as BosuFramedReplayInputHandler.BosuReplayState; if (replayState?.Position.Value != null) { movingPlayer.X = replayState.Position.Value.X; movingPlayer.Y = replayState.Position.Value.Y; // Required for accurate jump sounds if (verticalSpeed <= 0 && Precision.AlmostEquals(movingPlayer.Y + IWannaExtensions.PLAYER_HALF_HEIGHT, BosuPlayfield.BASE_SIZE.Y - IWannaExtensions.TILE_SIZE, 0.01f)) { resetJumpLogic(); } } else { if (horizontalSpeed > 0) { moveRight(elapsedFrameTime); } if (horizontalSpeed < 0) { moveLeft(elapsedFrameTime); } if (midAir) { moveVertical(timeDifference); } if (verticalSpeed <= 0) { if (movingPlayer.Y + IWannaExtensions.PLAYER_HALF_HEIGHT > BosuPlayfield.BASE_SIZE.Y - IWannaExtensions.TILE_SIZE) { movingPlayer.Y = BosuPlayfield.BASE_SIZE.Y - IWannaExtensions.TILE_SIZE - IWannaExtensions.PLAYER_HALF_HEIGHT; resetJumpLogic(); } } } updatePlayerSprite(); }