// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void TestClampRange <T>(T value, Range <int>?range, T expectedResult, IEqualityComparer <T> equalityComparer = null) where T : IComparable { // ReSharper disable once InvokeAsExtensionMethod T actualResult = MathExtensions.Clamp(value, range?.CastToType(equalityComparer)); Assert.Equal(expectedResult, actualResult); }
public override void EncodePixel(byte[] source, int sourceIndex, byte[] destination, int destinationIndex) { byte colorR = source[sourceIndex + 2]; byte colorG = source[sourceIndex + 1]; byte colorB = source[sourceIndex]; double x = colorR / 255.0 * 2.0 - 1.0; double y = colorG / 255.0 * 2.0 - 1.0; double z = colorB / 255.0 * 2.0 - 1.0; double radius = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2)); double rRadian = Math.Atan2(y, x); double sRadian = Math.Asin(z / radius); double rAngle = MathHelper.RadiansToDegrees(rRadian); rAngle = rAngle < 0.0 ? rAngle + 360.0 : rAngle; double sAngle = MathHelper.RadiansToDegrees(sRadian); rAngle = MathExtensions.Clamp(rAngle, 0.0f, 360.0f); sAngle = MathExtensions.Clamp(sAngle, 0.0f, 90.0f); byte r = (byte)Math.Round(rAngle / 360.0f * 255.0f); byte s = (byte)Math.Round(sAngle / 90.0f * 255.0f); destination[destinationIndex + 1] = s; destination[destinationIndex + 0] = r; }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void TestClampRange <T>(T value, Range <T>?range, T expectedResult) where T : IComparable { // ReSharper disable once InvokeAsExtensionMethod T actualResult = MathExtensions.Clamp(value, range); Assert.Equal(expectedResult, actualResult); }
public override void OnInputKey(SInputEvent arg) { if (_earthquake == null) { return; } if (arg.KeyDown(EKeyId.eKI_W)) { _earthquake.Position += Vec3.Right * 4f * FrameTime.Delta; } if (arg.KeyDown(EKeyId.eKI_S)) { _earthquake.Position += -Vec3.Right * 4f * FrameTime.Delta; } if (arg.KeyDown(EKeyId.eKI_A)) { if (_earthquake.MinAmplitude > 0.5f) { _earthquake.MinAmplitude -= 0.5f; _earthquake.MaxAmplitude -= 0.5f; } } if (arg.KeyDown(EKeyId.eKI_D)) { _earthquake.MinAmplitude += 0.5f; _earthquake.MaxAmplitude += 0.5f; } if (arg.KeyDown(EKeyId.eKI_Q)) { _earthquake.Radius -= 0.1f; _earthquake.Radius = MathExtensions.Clamp(_earthquake.Radius, 0.25f, _earthquake.Radius); } if (arg.KeyDown(EKeyId.eKI_E)) { _earthquake.Radius += 0.1f; } if (arg.KeyPressed(EKeyId.eKI_R)) { _earthquake.RandomOffset += 1f; } if (arg.KeyPressed(EKeyId.eKI_F)) { _earthquake.RandomOffset -= 1f; _earthquake.RandomOffset = MathExtensions.Clamp(_earthquake.RandomOffset, 0f, _earthquake.RandomOffset); } if (arg.KeyPressed(EKeyId.eKI_V)) { _earthquake.Visualize = !_earthquake.Visualize; } }
/// <inheritdoc /> public void Process(WaveFormat waveFormat, float[] channelSamples) { for (int c = 0; c < waveFormat.Channels; c++) { channelSamples[c] *= _module.Volume; MathExtensions.Clamp(ref channelSamples[c], -1f, 1f); } }
public static Collision CheckCollision(Rectangle a, Circle b) { Collision collision = new Collision(); // Vector from A to B. var n = b.GetPosition() + b.GetHalfSize() - a.GetCentre(); // Get rectangle-vertex closest to circle center by clamping vector to rectangle bounds. var closest = new Vector2f(n.X, n.Y); closest.X = MathExtensions.Clamp(closest.X, -a.GetHalfSize().X, a.GetHalfSize().X); closest.Y = MathExtensions.Clamp(closest.Y, -a.GetHalfSize().Y, a.GetHalfSize().Y); // If clamping vector had no effect, then circle center is inside rectangle. bool inside = (n == closest); // Recalculate rectangle-vertex closest to circle center. if (inside) { if (MathExtensions.Abs(n.X) > MathExtensions.Abs(n.Y)) { closest.X = (closest.X > 0) ? a.GetHalfSize().X : -a.GetHalfSize().X; } else { closest.Y = (closest.Y > 0) ? a.GetHalfSize().Y : -a.GetHalfSize().Y; } } // Calculate vector from circle center to closest rectangle-vertex. var nn = n - closest; float d = nn.MagnitudeSquared(); float r = b.GetRadius(); // No collision if vector is greater than circle radius. if (d > (r * r) && !inside) { return(null); } // Avoided square root until needed. d = MathExtensions.Sqrt(d); // Collision resolution. if (inside) { collision.Normal = -1.0f * nn / d; collision.Depth = r + d; } else { collision.Normal = nn / d; collision.Depth = r - d; } return(collision); }
public void TestClamp() { var a = MathExtensions.Clamp(-5, -1, 1); var b = MathExtensions.Clamp(5, -1, 1); var c = MathExtensions.Clamp(0, -1, 1); Assert.That(a, Is.EqualTo(-1)); Assert.That(b, Is.EqualTo(1)); Assert.That(c, Is.EqualTo(0)); }
public void AdvanceFrame() { float previousFrameTime = nextFrameTime; long currentTimestamp = Stopwatch.GetTimestamp(); float timeRemaining = OpenVR.Compositor.GetFrameTimeRemaining(); double currentTime = (double)(currentTimestamp - initialTimestamp) / Stopwatch.Frequency; nextFrameTime = (float)(currentTime + timeRemaining); timeDelta = MathExtensions.Clamp(nextFrameTime - previousFrameTime, 0, MaxTimeDelta); }
private Vec3 GetRandomPosition(Vec3 origin, int radius, float minZ) { var rnd = new Random(); var x = rnd.Next(-radius, radius); var y = rnd.Next(-radius, radius); var z = rnd.Next(-radius, radius); var newVec = origin + new Vec3(x, y, z); return(new Vec3(newVec.x, newVec.y, MathExtensions.Clamp(z, minZ, z))); }
public static float GetJumpHeight(float burden, uint jumpSkill, float power, float scaling) { power = MathExtensions.Clamp(power, 0.0f, 1.0f); var result = EncumbranceSystem.GetBurdenMod(burden) * (jumpSkill / (jumpSkill + 1300.0f) * 22.2f + 0.05f) * power / scaling; if (result < 0.35f) { result = 0.35f; } return(result); }
public async Task <object> SaveSettingAsync(object value) { var iValue = Convert.ToInt32(value); MathExtensions.Clamp(ref iValue, 1, Globals.MaxVacCount); var a = Globals.DriverUtility.ArgumentNameChars[0]; try { await _engineApiClient.StopAsync().ConfigureAwait(false); var process = new Process { StartInfo = new ProcessStartInfo { FileName = Globals.DriverUtility.ProgramName, Arguments = $"{a}{Globals.DriverUtility.Arguments.DeviceCount} {iValue}", WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Verb = "runas", UseShellExecute = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden } }; if (!process.Start()) { _logger.Error("Could not start the driver utility."); } else if (!process.WaitForExit(30000)) { _logger.Error("The driver utility did not finish within 30 seconds. Aborting..."); process.Kill(); } if (process.ExitCode != Globals.DriverUtility.ReturnCodes.Success) { _logger.Error($"Driver utility returned with exit code {process.ExitCode}"); } } catch (Exception ex) { _logger.Error(ex); } finally { await _engineApiClient.StartAsync().ConfigureAwait(false); } return(GetRegistryValue()); }
public void ApplyDamage(float damage) { if (CurrentHealth <= 0) { return; } CurrentHealth -= damage; ReceivedDamage?.Invoke(damage); if (CurrentHealth <= 0) { NoHealth?.Invoke(); } CurrentHealth = MathExtensions.Clamp(CurrentHealth, 0, MaxHealth); }
public override void SetState(ModuleState state) { base.SetState(state); var quality = Quality; MathExtensions.Clamp(ref quality, 1, 10); var pitch = Pitch; MathExtensions.Clamp(ref pitch, -1f, 1f); // [256..4096] -> map quality [1..10] to [8..12] var qualityFactor = MathExtensions.InverseLerp(1f, 10f, quality); var fftQualityPow = (int)MathExtensions.Lerp(8, 12, qualityFactor); FftSize = (int)Math.Pow(2, fftQualityPow); Oversampling = (int)MathExtensions.Lerp(4f, 8f, qualityFactor); PitchFactor = pitch < 0f ? MathExtensions.Lerp(0.5f, 1f, pitch + 1) : MathExtensions.Lerp(1f, 2f, pitch); }
public void ClampInt() { Assert.Equal(2000, MathExtensions.Clamp(200, 2000, 10000)); Assert.Equal(-10, MathExtensions.Clamp(-100, -10, 100)); Assert.Equal(500, MathExtensions.Clamp(600, -10, 500)); }
public void ClampByte() { Assert.Equal(23, MathExtensions.Clamp((byte)23, (byte)0, (byte)100)); Assert.Equal(0, MathExtensions.Clamp((byte)0, (byte)0, (byte)100)); Assert.Equal(100, MathExtensions.Clamp((byte)200, (byte)0, (byte)100)); }
public void ClampDouble() { Assert.Equal(23.0, MathExtensions.Clamp(23.0, 0.0, 100.0)); Assert.Equal(0.0, MathExtensions.Clamp(-10, 0.0, 100.0)); Assert.Equal(100.0, MathExtensions.Clamp(222, 0.0, 100.0)); }
public async void CreateMinimap() { await Task.Delay(300); var brushes = new Brush[] { Brushes.RoyalBlue, Brushes.Coral, Brushes.Crimson, Brushes.HotPink, Brushes.LimeGreen, Brushes.BlueViolet, }; int index = 0; Brush get_random_brush() { return(brushes[(index++) % brushes.Length]); } var timer = new DispatcherTimer(); var canvas = new Canvas() { Background = Brushes.Gray, Opacity = 0.8, }; Console.WriteLine(canvas.Width); Dictionary <INodeControl, Border> map = new Dictionary <INodeControl, Border>(); var nodesControl = NetworkView.FindChild <NodeItemsControl>(); var scrollViewer = this.FindChild <InfiniteScrollViewer>(); var visualBrush = new VisualBrush(); MiniMap.Background = visualBrush; var thumb = new Thumb() { Width = ActualWidth * scrollViewer.Scale, Height = ActualHeight * scrollViewer.Scale, Background = Brushes.RoyalBlue, Opacity = 0.5, BorderBrush = Brushes.Yellow, BorderThickness = new Thickness(2) }; Point start; Point translate; thumb.PreviewMouseDown += (s, e) => { start = e.GetPosition(scrollViewer); translate = scrollViewer.GetTranslateToPosition(); update_thumb(thumb, scrollViewer); }; thumb.DragDelta += (s, e) => { var rect = NetworkView.ItemsRect.ValidateRect(ActualWidth, ActualHeight) .ToOffset(scrollViewer.ViewRectOffset); var p = Mouse.GetPosition(scrollViewer) - start; var x = e.HorizontalChange * (rect.Width / MiniMap.Width); var y = e.VerticalChange * (rect.Height / MiniMap.Height); x = MathExtensions.Clamp(x, rect.Left, rect.Right); y = MathExtensions.Clamp(y, rect.Left, rect.Right); scrollViewer.TranslateX(-x); scrollViewer.TranslateY(-y); update_thumb(thumb, scrollViewer); }; MiniMap.Children.Add(thumb); timer.Interval = TimeSpan.FromMilliseconds(30); timer.Tick += (s, e) => { var rect = NetworkView.ItemsRect.ValidateRect(ActualWidth, ActualHeight).ToOffset(scrollViewer.ViewRectOffset); var point = scrollViewer.TransformPoint(0, 0); thumb.Width = ActualWidth * (1.0 / scrollViewer.Scale); thumb.Height = ActualHeight * (1.0 / scrollViewer.Scale); thumb.Width = MiniMap.Width * (thumb.Width / rect.Width); thumb.Height = MiniMap.Height * (thumb.Height / rect.Height); Canvas.SetLeft(thumb, point.X / (rect.Width / MiniMap.Width)); Canvas.SetTop(thumb, point.Y / (rect.Height / MiniMap.Height)); canvas.Width = rect.Width; canvas.Height = rect.Height; foreach (var node in nodesControl.GetNodes()) { if (map.ContainsKey(node) is false) { map[node] = new Border() { Width = node.ActualWidth * (rect.Width / rect.Height), Height = node.ActualHeight * (rect.Width / rect.Height), Background = get_random_brush() }; } if (canvas.Children.Contains(map[node]) is false) { canvas.Children.Add(map[node]); } var converted_x = node.X - rect.Left; Canvas.SetLeft(map[node], converted_x); Canvas.SetTop(map[node], node.Y - rect.Top); } foreach (var key_value in map) { if (nodesControl.Items.Contains(key_value.Key.DataContext) is false) { canvas.Children.Remove(key_value.Value); } } visualBrush.Visual = canvas; }; timer.Start(); }
float GetAmplitude(float min, float max) { min = MathExtensions.Clamp(min, min, max); max = MathExtensions.Clamp(max, min, max); return(new Random().Next((int)min, (int)max)); }
public void ClampTest(int min, int max, int value, int expected) { int actual = MathExtensions.Clamp(value, min, max); Assert.Equal(expected, actual); }
public void ClampUint() { Assert.Equal(2000u, MathExtensions.Clamp(200u, 2000u, 10000u)); Assert.Equal(10u, MathExtensions.Clamp(0u, 10u, 100u)); Assert.Equal(500u, MathExtensions.Clamp(600u, 10u, 500u)); }
/// <summary> /// Toggle the state of a led /// </summary> /// <param name="led">The led from 0 to 10</param> public void ToggleLeds(byte led) { led = MathExtensions.Clamp(led, (byte)0, (byte)10); _grovePi.WriteCommand(GrovePiCommand.LedBarToggleOneLed, _port, led, 0); }
private void StartMotor(int port, int speed) { speed = MathExtensions.Clamp(speed, -255, 255); _brick.SetMotorPower((byte)port, speed); }
/// <summary> /// Set the speed of the motor /// </summary> /// <param name="speed">speed is between -255 and +255</param> public void SetSpeed(int speed) { speed = MathExtensions.Clamp(speed, -255, 255); _goPiGo.SetMotorPower(Port, speed); }
public Utilities.Color CastRay(Ray ray, Scene scene, ref int depth) { Utilities.Color newColor = new Utilities.Color(); Utilities.Color AmbientColor = new Utilities.Color(0.1, 0.1, 0.1); Utilities.Color SpecularColor = new Utilities.Color(1.0, 1.0, 1.0); if (depth > rs.MaxDepth) { return(Utilities.Color.Background); } RayHit hit = Trace(scene, ray); if (hit.isHit) { Vector3 hitPoint = hit.hitPoint; Vector3 Normal = scene.SceneObjects[hit.HitObjectID].Mesh.GetNormal(hit.index); Vector2 st = new Vector2(); //St Coordinates //GetSurfaceProperties Vector3 temp = hitPoint; //Get Material Type Material mat = scene.SceneObjects[hit.HitObjectID].Material; //Default if (mat.Type == 0) { newColor = mat.MainColor; } //Flat Shading if (mat.Type == 1) { newColor = mat.MainColor * Math.Max(0, Vector3.Dot(Normal, -ray.Direction)); } //Smooth Shading - Need to vertex normals if (mat.Type == 2) { Mesh mesh = scene.SceneObjects[hit.HitObjectID].Mesh; Vector3 n0 = mesh.normals[mesh.triangles[hit.index]]; Vector3 n1 = mesh.normals[mesh.triangles[hit.index + 1]]; Vector3 n2 = mesh.normals[mesh.triangles[hit.index + 2]]; Normal = n0 * (1 - hit.uv.x - hit.uv.y); Normal += (n1 * hit.uv.x); Normal += (n2 * hit.uv.y); newColor = mat.MainColor * Math.Max(0, Vector3.Dot(Normal, -ray.Direction)); } //Diffuse if (mat.Type == 3) { Utilities.Color ambient = (AmbientColor * mat.MainColor); Utilities.Color textureColor = Utilities.Color.Set(0.0, 0.0, 0.0); Utilities.Color vertexColor = Utilities.Color.Set(0.0, 0.0, 0.0); double LightIntesity = 0; double inShadow = 1; Utilities.Color LightColor = Utilities.Color.Set(0.0, 0.0, 0.0); for (int i = 0; i < scene.Lights.Count; i++) { //RayHit shadowHit = new RayHit(); //Ray shadowRay = new Ray(); //shadowRay.Origin = hit.hitPoint + (hit.normal * rs.Bias); //shadowRay.Direction = Vector3.Normalize(scene.Lights[i].Position - shadowRay.Origin); //shadowHit = Trace(scene, shadowRay); //if (shadowHit.isHit == false) //{ //inShadow = 1; Vector3 L = -scene.Lights[i].Direction; double distance = Vector3.Magnitude(scene.Lights[i].Position - hit.hitPoint); double dist = 1 / (distance * distance); double cosTheta = MathExtensions.Clamp(Vector3.Dot(Normal, L), 0.0, 1.0); Vector3 R = Vector3.Reflect(-L, Normal); double cosAlpha = MathExtensions.Clamp(Vector3.Dot(Normal, R), 0.0, 1.0); LightColor += (scene.Lights[i].LightColor * scene.Lights[i].Intensity * cosTheta * dist); // } } if (inShadow == 1) { if (mat.MainTexture.PixelMap != null) { //Texture Coordinates Vector2 st0 = scene.SceneObjects[hit.HitObjectID].Mesh.uv[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index]]; Vector2 st1 = scene.SceneObjects[hit.HitObjectID].Mesh.uv[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index + 1]]; Vector2 st2 = scene.SceneObjects[hit.HitObjectID].Mesh.uv[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index + 2]]; Vector2 tex = st0 * (1 - hit.uv.x - hit.uv.y) + st1 * hit.uv.x + st2 * hit.uv.y; //Vertex Color Utilities.Color vc0 = scene.SceneObjects[hit.HitObjectID].Mesh.colors[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index]]; Utilities.Color vc1 = scene.SceneObjects[hit.HitObjectID].Mesh.colors[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index + 1]]; Utilities.Color vc2 = scene.SceneObjects[hit.HitObjectID].Mesh.colors[scene.SceneObjects[hit.HitObjectID].Mesh.triangles[hit.index + 2]]; vertexColor = vc0 * (1 - hit.uv.x - hit.uv.y) + vc1 * hit.uv.x + vc2 * hit.uv.y; int tx = (int)(tex.x * mat.MainTexture.Width); int ty = (int)(tex.y * mat.MainTexture.Height); textureColor = mat.MainTexture.GetPixel(tx, ty); } } Utilities.Color diffuse = vertexColor * textureColor * LightColor; ////Utilities.Color specular = SpecularColor * scene.Lights[0].LightColor * scene.Lights[0].Intensity * Math.Pow(cosAlpha, 5) * dist; newColor = ambient + diffuse; //ambient + diffuse + SpecularColor; } } else { newColor = Utilities.Color.Background; } return(newColor); }
private FrameworkElement CreateItem(MenuItemViewMessage message) { SolidColorBrush backgroundBrush; if (message.Type == MenuItemViewType.UpLevelButton) { backgroundBrush = UpLevelButtonBackground; } else if (message.Type == MenuItemViewType.SubLevelButton) { backgroundBrush = SubLevelButtonBackground; } else if (message.Type == MenuItemViewType.Range) { if (message.IsEditing) { backgroundBrush = RangeEditingBackground; } else { backgroundBrush = RangeBackground; } } else if (message.Type == MenuItemViewType.Toggle) { if (message.IsSet) { backgroundBrush = ToggleSetBackground; } else { backgroundBrush = DefaultBackground; } } else { backgroundBrush = DefaultBackground; } var textOverlayGrid = new Grid { Background = backgroundBrush }; if (message.Type == MenuItemViewType.Range) { double min = message.Min; double max = message.Max; double value = MathExtensions.Clamp(message.Value, min, max); double centerLeft, centerRight; if (value < 0) { centerLeft = value; centerRight = Math.Min(0, max); } else { centerLeft = Math.Max(0, min); centerRight = value; } var leftRect = new Rectangle { }; var middleRect = new Rectangle { Fill = message.IsEditing ? RangeEditingForeground : RangeForeground }; var rightRect = new Rectangle { }; var rectGrid = new Grid { Children = { leftRect, middleRect, rightRect }, }; rectGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(centerLeft - min, GridUnitType.Star) }); rectGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(centerRight - centerLeft + (max - min) * 0.002, GridUnitType.Star) }); rectGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(max - centerRight, GridUnitType.Star) }); Grid.SetColumn(leftRect, 0); Grid.SetColumn(middleRect, 1); Grid.SetColumn(rightRect, 2); textOverlayGrid.Children.Add(rectGrid); } var labelTextBlock = new TextBlock { Foreground = Brushes.White, Text = message.Label, FontSize = 48, FontWeight = FontWeights.SemiBold, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; textOverlayGrid.Children.Add(labelTextBlock); var border = new Border { Child = textOverlayGrid, BorderThickness = new Thickness(5), CornerRadius = new CornerRadius(5), BorderBrush = message.Active ? (message.IsEditing ? EditingBorderStroke : ActiveBorderStroke) : DefaultBorderStroke, Margin = new Thickness(2) }; return(border); }
/// <summary> /// Set the speed of the motor /// </summary> /// <param name="speed">speed is between -255 and +255</param> public void SetSpeed(int speed) { speed = MathExtensions.Clamp(speed, -255, 255); _brick.SetMotorPower((byte)Port, speed); OnPropertyChanged(nameof(Speed)); }
private void StartMotor(MotorPort port, int speed) { speed = MathExtensions.Clamp(speed, -255, 255); _goPiGo.SetMotorPower(port, speed); }