/// <summary> /// Checks whether the specified line segment intersects the passed one. /// </summary> /// <remarks> /// See http://www.wyrmtale.com/blog/2013/115/2d-line-intersection-in-c for details. /// </remarks> /// <param name="first">Line segment to check.</param> /// <param name="second">Line segment to check.</param> /// <param name="intersectionPoint">Intersection point, if found.</param> /// <returns> /// <c>true</c>, if both line segments intersect each other, and <c>false</c> otherwise. /// </returns> public static bool Intersects(this LineSegment2F first, LineSegment2F second, out Vector2F intersectionPoint) { // Get A,B,C of first line - points ps1 to pe1. var a1 = first.Q.Y - first.P.Y; var b1 = first.P.X - first.Q.X; var c1 = a1 * first.P.X + b1 * first.P.Y; // Get A,B,C of second line - points ps2 to pe2. var a2 = second.Q.Y - second.P.Y; var b2 = second.P.X - second.Q.X; var c2 = a2 * second.P.X + b2 * second.P.Y; // Get delta and check if the lines are parallel. var delta = a1 * b2 - a2 * b1; if (Math.Abs(delta) < float.Epsilon) { intersectionPoint = Vector2F.Zero; return false; } // Return intersection point. intersectionPoint = new Vector2F((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); return first.Contains(intersectionPoint) && second.Contains(intersectionPoint); }
public ScalingWindow(IServiceLocator services) : base(services) { Title = "ScalingWindow"; Width = 200; Height = 100; Content = new TextBlock { Margin = new Vector4F(8), Text = "The 'RenderScale' of this window is animated.", WrapText = true, }; // Set the center of the scale transformation to the center of the window. RenderTransformOrigin = new Vector2F(0.5f, 0.5f); LoadingAnimation = new Vector2FFromToByAnimation { TargetProperty = "RenderScale", // Animate the property UIControl.RenderScale From = new Vector2F(0, 0), // from (0, 0) to its actual value (1, 1) Duration = TimeSpan.FromSeconds(0.3), // over 0.3 seconds. EasingFunction = new ElasticEase { Mode = EasingMode.EaseOut, Oscillations = 1 }, }; ClosingAnimation = new Vector2FFromToByAnimation { TargetProperty = "RenderScale", // Animate the property UIControl.RenderScale To = new Vector2F(0, 0), // from its current value to (0, 0) Duration = TimeSpan.FromSeconds(0.3), // over 0.3 seconds. EasingFunction = new HermiteEase { Mode = EasingMode.EaseIn }, }; }
public void IdentityTest() { var traits = Vector2FTraits.Instance; var value = new Vector2F(-1, 2); Assert.AreEqual(value, traits.Add(value, traits.Identity())); Assert.AreEqual(value, traits.Add(traits.Identity(), value)); }
/// <inheritdoc/> protected override void OnArrange(Vector2F position, Vector2F size) { // Get extreme positions of arrange area. float left = position.X; float top = position.Y; float right = left + size.X; float bottom = top + size.Y; if (Orientation == DigitalRune.Game.UI.Orientation.Horizontal) { // ----- Horizontal: // Each child gets its desired width or the rest of the available space. foreach (var child in VisualChildren) { float availableSize = Math.Max(0.0f, right - left); float sizeX = Math.Min(availableSize, child.DesiredWidth); float sizeY = size.Y; child.Arrange(new Vector2F(left, top), new Vector2F(sizeX, sizeY)); left += sizeX + 10; } } else { // ----- Vertical // Each child gets its desired height or the rest of the available space. foreach (var child in VisualChildren) { float sizeX = size.X; float availableSize = Math.Max(0.0f, bottom - top); float sizeY = Math.Min(availableSize, child.DesiredHeight); child.Arrange(new Vector2F(left, top), new Vector2F(sizeX, sizeY)); top += sizeY + 10; } } }
public void Addition() { Vector2F a = new Vector2F(1.0f, 2.0f); Vector2F b = new Vector2F(2.0f, 3.0f); Vector2F c = Vector2F.Add(a, b); Assert.AreEqual(new Vector2F(3.0f, 5.0f), c); }
public void AdditionOperator() { Vector2F a = new Vector2F(1.0f, 2.0f); Vector2F b = new Vector2F(2.0f, 3.0f); Vector2F c = a + b; Assert.AreEqual(new Vector2F(3.0f, 5.0f), c); }
public void AdditivePath() { var animation = new Path2FAnimation(); animation.Path = new Path2F { new PathKey2F { Parameter = 2.0f, Point = new Vector2F(2.0f, 22.0f), Interpolation = SplineInterpolation.Linear }, new PathKey2F { Parameter = 3.0f, Point = new Vector2F(3.0f, 33.0f), Interpolation = SplineInterpolation.Linear }, new PathKey2F { Parameter = 4.0f, Point = new Vector2F(4.0f, 44.0f), Interpolation = SplineInterpolation.Linear }, }; animation.Path.PreLoop = CurveLoopType.Linear; animation.Path.PostLoop = CurveLoopType.Cycle; animation.IsAdditive = true; animation.EndParameter = float.PositiveInfinity; Vector2F defaultSource = new Vector2F(1.0f, 2.0f); Vector2F defaultTarget = new Vector2F(10.0f, 20.0f); // Pre-Loop Assert.AreEqual(defaultSource + new Vector2F(0.0f, 0.0f), animation.GetValue(TimeSpan.FromSeconds(0.0), defaultSource, defaultTarget)); Assert.AreEqual(defaultSource + new Vector2F(1.0f, 11.0f), animation.GetValue(TimeSpan.FromSeconds(1.0), defaultSource, defaultTarget)); Assert.AreEqual(defaultSource + new Vector2F(2.0f, 22.0f), animation.GetValue(TimeSpan.FromSeconds(2.0), defaultSource, defaultTarget)); Assert.AreEqual(defaultSource + new Vector2F(3.0f, 33.0f), animation.GetValue(TimeSpan.FromSeconds(3.0), defaultSource, defaultTarget)); Assert.AreEqual(defaultSource + new Vector2F(4.0f, 44.0f), animation.GetValue(TimeSpan.FromSeconds(4.0), defaultSource, defaultTarget)); // Post-Loop Assert.AreEqual(defaultSource + new Vector2F(3.0f, 33.0f), animation.GetValue(TimeSpan.FromSeconds(5.0), defaultSource, defaultTarget)); }
/// <summary> /// Initializes a new instance of the <see cref="ImageBillboard"/> class. /// </summary> /// <param name="texture">The texture.</param> public ImageBillboard(PackedTexture texture) { Texture = texture; Size = new Vector2F(1, 1); _alphaTest = 0; _blendMode = 1; }
/// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class using given center point, axes and extents. /// </summary> /// <param name="center">The center of the box.</param> /// <param name="axis1">The first axis.</param> /// <param name="axis2">The second axis.</param> /// <param name="extent1">The extent on the first axis.</param> /// <param name="extent2">The extent on the second axis.</param> public OrientedBox(Vector2F center, Vector2F axis1, Vector2F axis2, float extent1, float extent2) { _center = center; _axis1 = axis1; _axis2 = axis2; _extent1 = extent1; _extent2 = extent2; }
public void TestPolygonContainsPoint() { // ARRANGE. var point = new Vector2F(3, 3); // ASSERT. Assert.IsTrue(this.polygon.Contains(point)); }
public void ShouldDoNothingWhenPathIsEmpty() { var animation = new Path2FAnimation(); animation.Path = new Path2F(); Vector2F defaultSource = new Vector2F(1.0f, 2.0f); Vector2F defaultTarget = new Vector2F(10.0f, 20.0f); Assert.AreEqual(defaultSource, animation.GetValue(TimeSpan.FromSeconds(0.0), defaultSource, defaultTarget)); }
public void TestRectangleFCenter() { // ARRANGE. var rectangle = new RectangleF(new Vector2F(2, 3), new Vector2F(6, 8)); var center = new Vector2F(5, 7); // ASSERT. Assert.AreEqual(center, rectangle.Center); }
public void InterpolationTest() { var traits = Vector2FTraits.Instance; var value0 = new Vector2F(2, 3); var value1 = new Vector2F(5, -6); Assert.IsTrue(Vector2F.AreNumericallyEqual(value0, traits.Interpolate(value0, value1, 0.0f))); Assert.IsTrue(Vector2F.AreNumericallyEqual(value1, traits.Interpolate(value0, value1, 1.0f))); Assert.IsTrue(Vector2F.AreNumericallyEqual(0.25f * value0 + 0.75f * value1, traits.Interpolate(value0, value1, 0.75f))); }
public void MultiplyTest() { var traits = Vector2FTraits.Instance; var value = new Vector2F(-1, 2); Assert.IsTrue(Vector2F.AreNumericallyEqual(Vector2F.Zero, traits.Multiply(value, 0))); Assert.IsTrue(Vector2F.AreNumericallyEqual(value, traits.Multiply(value, 1))); Assert.IsTrue(Vector2F.AreNumericallyEqual(value + value, traits.Multiply(value, 2))); Assert.IsTrue(Vector2F.AreNumericallyEqual(value + value + value, traits.Multiply(value, 3))); Assert.IsTrue(Vector2F.AreNumericallyEqual(-value, traits.Multiply(value, -1))); Assert.IsTrue(Vector2F.AreNumericallyEqual(-value - value, traits.Multiply(value, -2))); Assert.IsTrue(Vector2F.AreNumericallyEqual(-value - value - value, traits.Multiply(value, -3))); }
public void Normalize() { Vector2F v, n1, n2; float magnitude; v = new Vector2F(3.0f, 4.0f); n1 = v.Normalize(); n2 = v.Normalize(out magnitude); Assert.AreEqual(1.0f, n1.Magnitude, 1e-14); Assert.AreEqual(1.0f, n2.Magnitude, 1e-14); Assert.AreEqual(5.0f, magnitude, 1e-14); }
public Planet(IServiceProvider services, SystemMapPlanetViewModel viewModel) { ViewModel = viewModel; Scale = ViewModel.Scale; ImageControl = new Image(); _content = (ContentController)services.GetService(typeof(ContentController)); ImageControl.Texture = _content.GetContent<Texture2D>(@"SystemMap\Planet1"); Content = ImageControl; RenderScale = new Vector2F(Scale); }
public void AbsoluteStatic() { Vector2F v = new Vector2F(-1, -2); Vector2F absoluteV = Vector2F.Absolute(v); Assert.AreEqual(1, absoluteV.X); Assert.AreEqual(2, absoluteV.Y); v = new Vector2F(1, 2); absoluteV = Vector2F.Absolute(v); Assert.AreEqual(1, absoluteV.X); Assert.AreEqual(2, absoluteV.Y); }
public void Absolute() { Vector2F v = new Vector2F(-1, -2); v.Absolute(); Assert.AreEqual(1, v.X); Assert.AreEqual(2, v.Y); v = new Vector2F(1, 2); v.Absolute(); Assert.AreEqual(1, v.X); Assert.AreEqual(2, v.Y); }
public void Add() { Vector2F v1 = new Vector2F(1.0f, 2.0f); Vector2F v2 = new Vector2F(4.0f, 5.0f); Vector2F v3 = v1 + v2; Assert.AreEqual(5.0f, v3.X, 1e-14); Assert.AreEqual(7.0f, v3.Y, 1e-14); Vector2F v4 = v1.Add(v2); Assert.AreEqual(5.0f, v4.X, 1e-14); Assert.AreEqual(7.0f, v4.Y, 1e-14); }
public void Subtract() { Vector2F v1 = new Vector2F(1.0f, 2.0f); Vector2F v2 = new Vector2F(4.0f, 5.0f); Vector2F v3 = v1 - v2; Assert.AreEqual(-3.0f, v3.X, 1e-14); Assert.AreEqual(-3.0f, v3.Y, 1e-14); Vector2F v4 = v1.Subtract(v2); Assert.AreEqual(-3.0f, v4.X, 1e-14); Assert.AreEqual(-3.0f, v4.Y, 1e-14); }
private void Update(Context context) { if (_positionDirty) { DisposeVertexArray(); CreateVertexArray(context); Vector2F[] positions = new Vector2F[] { _position.ToVector2F() }; _positionBuffer.CopyFromSystemMemory(positions); _positionDirty = false; } }
/// <summary> /// Initializes a new instance of the <see cref="OrientedBox"/> class using given center point, axes and extents. /// </summary> /// <param name="center">The center of the box.</param> /// <param name="axes">The axes of the box.</param> /// <param name="extents">The extent values of the box..</param> public OrientedBox(Vector2F center, Vector2F[] axes, float[] extents) { Debug.Assert(axes.Length >= 2); Debug.Assert(extents.Length >= 2); _center = center; _axis1 = axes[0]; _axis2 = axes[1]; _extent1 = extents[0]; _extent2 = extents[1]; }
public void AreEqual() { float originalEpsilon = Numeric.EpsilonF; Numeric.EpsilonF = 1e-8f; Vector2F u = new Vector2F(1.0f, 2.0f); Vector2F v = new Vector2F(1.000001f, 2.000001f); Vector2F w = new Vector2F(1.00000001f, 2.00000001f); Assert.IsTrue(Vector2F.AreNumericallyEqual(u, u)); Assert.IsFalse(Vector2F.AreNumericallyEqual(u, v)); Assert.IsTrue(Vector2F.AreNumericallyEqual(u, w)); Numeric.EpsilonF = originalEpsilon; }
public void FromByTest() { // IAnimationValueTraits<T> is used in a from-by animation to a add a relative offset to // the start value. var traits = Vector2FTraits.Instance; var from = new Vector2F(-1, -2); var by = new Vector2F(4, -5); var to = traits.Add(from, by); Assert.IsTrue(Vector2F.AreNumericallyEqual(by + from, to)); Assert.IsTrue(Vector2F.AreNumericallyEqual(from, traits.Add(to, traits.Inverse(by)))); Assert.IsTrue(Vector2F.AreNumericallyEqual(by, traits.Add(traits.Inverse(from), to))); }
//-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="SkyObjectNode" /> class. /// </summary> public SkyObjectNode() { AngularDiameter = new Vector2F(MathHelper.ToRadians(5)); Alpha = 1; SunDirection = new Vector3F(1, 1, 1); SunLight = new Vector3F(1, 1, 1); AmbientLight = new Vector3F(0, 0, 0); LightWrap = 0.1f; LightSmoothness = 1; GlowColor0 = new Vector3F(0.1f); GlowExponent0 = 200; GlowColor1 = new Vector3F(0, 0, 0); GlowExponent0 = 4000; GlowCutoffThreshold = 0.001f; }
public void NormalizeZeroVector() { Vector2F v = new Vector2F(0.0f, 0.0f); Vector2F n1 = v.Normalize(); Assert.IsNaN(n1.X); Assert.IsNaN(n1.Y); Assert.IsTrue(n1.IsUndefined); float magnitude; Vector2F n2 = v.Normalize(out magnitude); Assert.IsNaN(n2.X); Assert.IsNaN(n2.Y); Assert.IsTrue(n2.IsUndefined); Assert.AreEqual(0.0f, magnitude); }
private int _blurLevel; // TODO: We could add more levels with Poisson blur, etc. #endregion Fields #region Constructors //-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="NormalMapDistortionFilter"/> class. /// </summary> /// <param name="graphicsService">The graphics service.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="graphicsService"/> is <see langword="null"/>. /// </exception> public NormalMapDistortionFilter(IGraphicsService graphicsService) : base(graphicsService) { _effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/NormalMapDistortionFilter"); _viewportSizeParameter = _effect.Parameters["ViewportSize"]; _scaleParameter = _effect.Parameters["Scale"]; _offsetParameter = _effect.Parameters["Offset"]; _strengthParameter = _effect.Parameters["Strength"]; _sourceTextureParameter = _effect.Parameters["SourceTexture"]; _normalMapParameter = _effect.Parameters["NormalMap"]; _basicPass = _effect.CurrentTechnique.Passes["Basic"]; _blur4Pass = _effect.CurrentTechnique.Passes["Blur4"]; Scale = new Vector2F(1); Strength = 10; }
internal void Update(Context context, ShaderProgram sp) { if (_va == null) { VertexBufferAttribute positionAttribute = new VertexBufferAttribute( _positionBuffer, ComponentDatatype.Float, 2); VertexBufferAttribute textureCoordinatesAttribute = new VertexBufferAttribute( _textureCoordinatesBuffer, ComponentDatatype.HalfFloat, 2); _va = context.CreateVertexArray(); _va.Attributes[sp.VertexAttributes["position"].Location] = positionAttribute; _va.Attributes[sp.VertexAttributes["textureCoordinates"].Location] = textureCoordinatesAttribute; } if (_viewport != context.Viewport) { // // Bottom and top swapped: MS -> OpenGL // float left = context.Viewport.Left; float bottom = context.Viewport.Top; float right = context.Viewport.Right; float top = context.Viewport.Bottom; Vector2F[] positions = new Vector2F[] { new Vector2F(left, bottom), new Vector2F(right, bottom), new Vector2F(left, top), new Vector2F(right, top) }; _positionBuffer.CopyFromSystemMemory(positions); Vector2H[] textureCoordinates = new Vector2H[] { new Vector2H(0, 0), new Vector2H(1, 0), new Vector2H(0, 1), new Vector2H(1, 1) }; _textureCoordinatesBuffer.CopyFromSystemMemory(textureCoordinates); _viewport = context.Viewport; } }
public void Transform1D() { // Transform forward and inverse and compare with initial values. var random = new Random(1234567); var s = new Vector2F[16]; var t = new Vector2F[16]; for (int i = 0; i < s.Length; i++) { s[i] = random.NextVector2F(-10, 10); t[i] = s[i]; } FastFourierTransformF.Transform1D(t, true); FastFourierTransformF.Transform1D(t, false); for (int i = 0; i < s.Length; i++) Assert.IsTrue(Vector2F.AreNumericallyEqual(s[i], t[i])); }
public void CycleOffsetTest() { // IAnimationValueTraits<T> is used in a cyclic animation to a add the cycle offset in // each iteration. var traits = Vector2FTraits.Instance; var first = new Vector2F(1, 2); // Animation value of first key frame. var last = new Vector2F(-4, 5); // Animation value of last key frame. var cycleOffset = traits.Add(traits.Inverse(first), last); // Cycle offset should be the difference between last and first key frame. Assert.IsTrue(Vector2F.AreNumericallyEqual(last, traits.Add(first, cycleOffset))); Assert.IsTrue(Vector2F.AreNumericallyEqual(last, cycleOffset + first)); // Check multiple cycles (post-loop). Assert.IsTrue(Vector2F.AreNumericallyEqual(last, traits.Add(first, traits.Multiply(cycleOffset, 1)))); Assert.IsTrue(Vector2F.AreNumericallyEqual(cycleOffset + cycleOffset + last, traits.Add(first, traits.Multiply(cycleOffset, 3)))); // Check multiple cycles (pre-loop). Assert.IsTrue(Vector2F.AreNumericallyEqual(first, traits.Add(last, traits.Multiply(cycleOffset, -1)))); Assert.IsTrue(Vector2F.AreNumericallyEqual(first - cycleOffset - cycleOffset, traits.Add(last, traits.Multiply(cycleOffset, -3)))); }
/// <summary> /// Initializes a new instance of the <see cref="AxisAlignedBox"/> class using given values from another box instance. /// </summary> /// <param name="box">A <see cref="AxisAlignedBox"/> instance to take values from.</param> public AxisAlignedBox(AxisAlignedBox box) { _min = box.Min; _max = box.Max; }
/// <summary> /// 指定した説明,色,大きさを持つ<see cref="ColorButton"/>の新しいインスタンスを生成する /// </summary> /// <param name="description">説明</param> /// <param name="color">色</param> /// <param name="size">大きさ</param> public ColorButton(string description, Color color, Vector2F size) { Description = description; Color = color; Size = size; }
public void Anchor() { var tc = new TestCore(new Configuration() { VisibleTransformInfo = true }); tc.Init(); var font = Font.LoadDynamicFont("TestData/Font/mplus-1m-regular.ttf", 64); Assert.NotNull(font); var texture = Texture2D.Load(@"TestData/IO/AltseedPink.png"); Assert.NotNull(texture); var sprite = new SpriteNode(); sprite.Texture = texture; sprite.ZOrder = 5; Vector2F rectSize = texture.Size; var parent = new AnchorTransformerNode(); parent.Position = Engine.WindowSize / 2; parent.Size = rectSize; parent.AnchorMode = AnchorMode.Fill; Engine.AddNode(sprite); sprite.AddChildNode(parent); var sprite2 = new SpriteNode(); sprite2.Texture = texture; sprite2.Color = new Color(255, 0, 0, 200); sprite2.ZOrder = 10; var child = new AnchorTransformerNode(); child.Position = rectSize / 2; child.Pivot = new Vector2F(0.5f, 0.5f); child.AnchorMin = new Vector2F(0.0f, 0.0f); child.AnchorMax = new Vector2F(0.5f, 1f); child.HorizontalAlignment = HorizontalAlignment.Left; child.VerticalAlignment = VerticalAlignment.Center; child.Size = sprite2.ContentSize; child.AnchorMode = AnchorMode.KeepAspect; sprite.AddChildNode(sprite2); sprite2.AddChildNode(child); var text = new TextNode(); text.Font = font; text.FontSize = 20; text.Color = new Color(0, 0, 0); text.Text = "あいうえお"; text.ZOrder = 15; var childText = new AnchorTransformerNode(); childText.Pivot = new Vector2F(0.5f, 0.5f); childText.AnchorMin = new Vector2F(0.5f, 0.5f); childText.AnchorMax = new Vector2F(0.5f, 0.5f); childText.Size = text.ContentSize; //childText.HorizontalAlignment = HorizontalAlignment.Center; //childText.VerticalAlignment = VerticalAlignment.Center; childText.AnchorMode = AnchorMode.ContentSize; sprite2.AddChildNode(text); text.AddChildNode(childText); var text2 = new TextNode() { Font = font, FontSize = 20, Text = "", ZOrder = 10, Scale = new Vector2F(0.8f, 0.8f), Color = new Color(255, 128, 0) }; Engine.AddNode(text2); tc.Duration = 10000; string infoText(AnchorTransformerNode n) => $"Scale:{n.Scale}\n" + $"Position:{n.Position}\n" + $"Pivot:{n.Pivot}\n" + $"Size:{n.Size}\n" + $"Margin: LT:{n.LeftTop} RB:{n.RightBottom}\n" + $"Anchor: {n.AnchorMin} {n.AnchorMax}\n"; tc.LoopBody(c => { if (Engine.Keyboard.GetKeyState(Key.Right) == ButtonState.Hold) { rectSize.X += 1.5f; } if (Engine.Keyboard.GetKeyState(Key.Left) == ButtonState.Hold) { rectSize.X -= 1.5f; } if (Engine.Keyboard.GetKeyState(Key.Down) == ButtonState.Hold) { rectSize.Y += 1.5f; } if (Engine.Keyboard.GetKeyState(Key.Up) == ButtonState.Hold) { rectSize.Y -= 1.5f; } if (Engine.Keyboard.GetKeyState(Key.D) == ButtonState.Hold) { parent.Position += new Vector2F(1.5f, 0); } if (Engine.Keyboard.GetKeyState(Key.A) == ButtonState.Hold) { parent.Position += new Vector2F(-1.5f, 0); } if (Engine.Keyboard.GetKeyState(Key.S) == ButtonState.Hold) { parent.Position += new Vector2F(0, 1.5f); } if (Engine.Keyboard.GetKeyState(Key.W) == ButtonState.Hold) { parent.Position += new Vector2F(0, -1.5f); } if (Engine.Keyboard.GetKeyState(Key.Q) == ButtonState.Hold) { child.Angle += 1.5f; } if (Engine.Keyboard.GetKeyState(Key.E) == ButtonState.Hold) { child.Angle -= 1.5f; } if (Engine.Keyboard.GetKeyState(Key.Z) == ButtonState.Hold) { parent.Scale += new Vector2F(0.1f, 0); } if (Engine.Keyboard.GetKeyState(Key.C) == ButtonState.Hold) { parent.Scale -= new Vector2F(0.1f, 0); } parent.Size = rectSize; text2.Text = infoText(parent) + '\n' + infoText(child) + '\n' + infoText(childText); }, null); tc.End(); }
private bool FindPathToEnemy(float deg, Vector2F originalDirectionToEnemyHitbox, ref double distanceToEnemy, ref Vector2F directionToEnemyPosition, ref Vector2F directionToEnemyHitbox) { //Find another path Vector2F v = (originalDirectionToEnemyHitbox * 2).RotateDeg(deg); if (!HasObstaclesInTheWay(characterNpc, enemyCharacter, characterNpcPosition, enemyCharacter.Position, sendDebugEvents: false)) { return(true); } //Try along the way for (int i = 4; i > 0; i--) { var alongWayPosition = characterNpc.Position + (v / i); if (!HasObstaclesInTheWay(characterNpc, enemyCharacter, characterNpcPosition, alongWayPosition, sendDebugEvents: false)) { SetDistanceTo(characterNpcPosition, npcWeaponOffset, alongWayPosition, 0.0, out distanceToEnemy, out directionToEnemyPosition, out directionToEnemyHitbox); if (!HasObstaclesInTheWay(characterNpc, enemyCharacter, alongWayPosition, enemyCharacter.Position, sendDebugEvents: false)) { return(true); } if (this.iteration < this.maxIterations) { bool done = false; using (FindPathHelper findPathHelper = new FindPathHelper(characterNpc, alongWayPosition, enemyCharacter, npcWeaponOffset, enemyWeaponOffset, this.maxIterations, this.iteration + 1)) { findPathHelper.FindPathToEnemy( out _, out _, out _, out _, out _, true); done = findPathHelper.PathFound; } if (done) { return(true); } } } } return(false); }
/// <inheritdoc/> protected override Vector2F OnMeasure(Vector2F availableSize) { // Similar to UIControl.OnMeasure, but we sum up the desired sizes in the stack panel // orientation. In the other direction we take the maximum of the children - unless a // Width or Height was set explicitly. If there are VisualChildren that are not Children, // they do not contribute to the DesiredSize. float width = Width; float height = Height; bool hasWidth = Numeric.IsPositiveFinite(width); bool hasHeight = Numeric.IsPositiveFinite(height); if (hasWidth && width < availableSize.X) { availableSize.X = width; } if (hasHeight && height < availableSize.Y) { availableSize.Y = height; } Vector4 padding = Padding; availableSize.X -= padding.X + padding.Z; availableSize.Y -= padding.Y + padding.W; foreach (var child in VisualChildren) { child.Measure(availableSize); } if (hasWidth && hasHeight) { return(new Vector2F(width, height)); } Vector2F desiredSize = new Vector2F(width, height); float maxWidth = 0; float sumWidth = 0; float maxHeight = 0; float sumHeight = 0; // Sum up widths and heights. foreach (var child in Children) { float childWidth = child.DesiredWidth; float childHeight = child.DesiredHeight; maxWidth = Math.Max(maxWidth, childWidth); maxHeight = Math.Max(maxHeight, childHeight); sumWidth += childWidth; sumHeight += childHeight; } if (!hasWidth) { if (Orientation == Orientation.Horizontal) { desiredSize.X = sumWidth; } else { desiredSize.X = maxWidth; } } if (!hasHeight) { if (Orientation == Orientation.Vertical) { desiredSize.Y = sumHeight; } else { desiredSize.Y = maxHeight; } } desiredSize.X += padding.X + padding.Z; desiredSize.Y += padding.Y + padding.W; return(desiredSize); }
private static string WriteVec2F(Vector2F vec2) { return($"!vec2[{vec2.X}, {vec2.Y}]"); }
/// <summary> /// Initializes a new instance of the <see cref="LensFlareElement" /> class. /// </summary> /// <param name="distance"> /// The distance of the element: 0 = light source, 1 = center of screen. /// Distance can be negative or greater than 1. The default value is 0. /// </param> /// <param name="scale"> /// The scale of the element relative to <see cref="LensFlare.Size"/>. /// </param> /// <param name="rotation"> /// The angle (in radians) to rotate the element around its center. <see cref="float.NaN"/> /// can be set to automatically rotate the element depending on the position of the light /// source. /// </param> /// <param name="color">The color of the element.</param> /// <param name="origin"> /// The origin relative to the image, where (0, 0) is the upper-left corner of the image and /// (1, 1) is the lower-right corner of the image. /// </param> /// <param name="texture">The texture containing the image.</param> public LensFlareElement(float distance, Vector2F scale, float rotation, Color color, Vector2F origin, PackedTexture texture) { Distance = distance; Scale = scale; Rotation = rotation; Color = color; Origin = origin; Texture = texture; }
public static Vector3D VectorWithZ(Vector2F v, float z) { return(new Vector3D(v.X, v.Y, z)); }
public static Vector2F ClosestPointOnLineSegment(Vector2F point, Vector2F lineStart, Vector2F lineEnd) { Vector2F line = lineEnd - lineStart; float lineMag = line.X * line.X + line.Y * line.Y; if (lineMag == 0f) { return(lineStart); } float t = Vector2F.Dot(point - lineStart, line) / lineMag; t = Math.Min(Math.Max(0, t), 1); return(lineStart + line * t); }
// 弾を撃つ private void Shot(Vector2F velocity) { // 敵弾を画面に追加 Parent.AddChildNode(new EnemyBullet(mainNode, Position, velocity)); }
/// <summary> /// Initializes a new instance of the <see cref="PackedTexture" /> class. /// </summary> /// <param name="name"> /// The original asset name of the packed texture. Can be <see langword="null"/> or empty. /// </param> /// <param name="texture">The texture atlas that contains the packed texture.</param> /// <param name="offset">The UV offset of the packed texture in the texture atlas.</param> /// <param name="scale">The scale of the packed texture relative to the texture atlas.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="texture"/> is <see langword="null"/>. /// </exception> public PackedTexture(string name, Texture2D texture, Vector2F offset, Vector2F scale) : this(name, texture, offset, scale, 1, 1) { }
/// <inheritdoc/> public void Recycle(ref Vector2F value) { }
/// <inheritdoc/> public void Create(ref Vector2F reference, out Vector2F value) { value = new Vector2F(); }
public static Point3D ToPoint3D(this Vector2F value, double z) => new Point3D(value.X, value.Y, z);
public virtual void OnSwingTilePeak(int angle, Vector2F hitPoint) { }
public static bool PointInRotatedRect(Vector2F point, Vector2F rectMidpointStart, Vector2F rectMidpointEnd, float rectHeight) { // create rectangle lengthwise from points, with specified height Vector2F beam_diff = rectMidpointStart - rectMidpointEnd; Vector2F beam_norm = Vector2F.Normalize(beam_diff); float length = beam_diff.Length(); float angX = -beam_norm.Y; float angY = beam_norm.X; // rectangle points float p1x = rectMidpointEnd.X - angX * rectHeight / 2; float p1y = rectMidpointEnd.Y - angY * rectHeight / 2; float p2x = p1x + angX * rectHeight; float p2y = p1y + angY * rectHeight; float p3x = p1x + beam_norm.X * length; float p3y = p1y + beam_norm.Y * length; float p4x = p3x + angX * rectHeight; float p4y = p3y + angY * rectHeight; return(PointInRectangle(point, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y)); }
/// <summary> /// Initializes a new instance of the <see cref="AxisAlignedBox"/> class using given minimum and maximum points. /// </summary> /// <param name="min">A <see cref="Vector2F"/> instance representing the minimum point.</param> /// <param name="max">A <see cref="Vector2F"/> instance representing the maximum point.</param> public AxisAlignedBox(Vector2F min, Vector2F max) { _min = min; _max = max; }
public ImplicitPoint(float x, float y, float radius) { m_vCenter = new Vector2F(x, y); m_radius = radius; }
//private static float RoundDownToGrid(float position, float cellSize) //{ // // Snap to top-left grid cell, e.g. if cellSize is 1 then 6.x snaps to 6.0. // // We add a small epsilon to avoid rounding 513.999999 down to 513. // return (float)Math.Floor(position / cellSize + 0.01f) * cellSize; //} //private static float RoundUpToGrid(float position, float cellSize) //{ // return (float)Math.Ceiling(position / cellSize - 0.01f) * cellSize; //} private static Vector2F RoundToGrid(Vector2F position, float cellSize) { position.X = RoundToGrid(position.X, cellSize); position.Y = RoundToGrid(position.Y, cellSize); return(position); }
private void SetDistanceTo(Vector2D positionFrom, double positionFromOffset, Vector2D positionTo, double positionToOffset, out double distanceToEnemy, out Vector2F directionToEnemyPosition, out Vector2F directionToEnemyHitbox) { var deltaPos = positionTo - positionFrom; directionToEnemyPosition = (Vector2F)deltaPos; deltaPos = (deltaPos.X, deltaPos.Y + positionToOffset - positionFromOffset); distanceToEnemy = deltaPos.Length; directionToEnemyHitbox = (Vector2F)deltaPos; }
/// <summary> /// Initializes a new instance of the <see cref="LensFlareElement" /> class. /// </summary> /// <param name="distance"> /// The distance of the element: 0 = light source, 1 = center of screen. /// Distance can be negative or greater than 1. The default value is 0. /// </param> /// <param name="scale"> /// The scale of the element relative to <see cref="LensFlare.Size"/>. /// </param> /// <param name="rotation"> /// The angle (in radians) to rotate the element around its center. <see cref="float.NaN"/> /// can be set to automatically rotate the element depending on the position of the light /// source. /// </param> /// <param name="color">The color of the element.</param> /// <param name="origin"> /// The origin relative to the image, where (0, 0) is the upper-left corner of the image and /// (1, 1) is the lower-right corner of the image. /// </param> /// <param name="texture">The texture containing the image.</param> public LensFlareElement(float distance, float scale, float rotation, Color color, Vector2F origin, PackedTexture texture) : this(distance, new Vector2F(scale), rotation, color, origin, texture) { }
/// <summary> /// Shows a tool tip. /// </summary> /// <param name="toolTip">The tool tip.</param> /// <param name="mousePosition">The mouse position.</param> public void ShowToolTip(object toolTip, Vector2F mousePosition) { if (toolTip == null) { return; } UIControl content = null; if (CreateToolTipContent != null) { content = CreateToolTipContent(toolTip); } if (content == null) { var control = toolTip as UIControl; if (control != null) { content = control; } else { content = new TextBlock { Style = "ToolTipText", Text = toolTip.ToString() } }; } ToolTipControl.Content = content; ToolTipControl.IsVisible = true; // If this is the first time, we have to add the control to the screen. // Otherwise, we make sure that the tool tip is on top. if (ToolTipControl.VisualParent == null) { Screen.Children.Add(ToolTipControl); } else { Screen.BringToFront(ToolTipControl); } // Determine position next to mouse. Position it so that it fits onto the screen. ToolTipControl.Measure(new Vector2F(float.PositiveInfinity)); float x = mousePosition.X; if (x + ToolTipControl.DesiredWidth > Screen.ActualWidth) { // Draw the tool tip on the left. x = x - ToolTipControl.DesiredWidth; } float y = mousePosition.Y + ToolTipOffset; if (y + ToolTipControl.DesiredHeight > Screen.ActualHeight) { // Draw the tool tip on top. // (We use 0.5 * offset if tool tip is above cursor. This assumes that the cursor is // similar to the typical arrow where the hot spot is at the top. If the cursor is a // different shape we might need to adjust the offset.) y = y - ToolTipControl.DesiredHeight - 1.5f * ToolTipOffset; } ToolTipControl.X = x; ToolTipControl.Y = y; }
//-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="LensFlareElement" /> class. /// </summary> public LensFlareElement() { Scale = Vector2F.One; Color = Color.White; Origin = new Vector2F(0.5f, 0.5f); }
public PsIn(Vector4F position, Vector2F textureCoordinate) { Position = position; TextureCoordinate = textureCoordinate; }
// OnUpdate() is called once per frame. protected override void OnUpdate(TimeSpan deltaTime) { // Mouse centering (controlled by the MenuComponent) is disabled if the game // is inactive or if the GUI is active. In these cases, we do not want to move // the player. if (!_inputService.EnableMouseCentering) { return; } if (!IsEnabled) { return; } float deltaTimeF = (float)deltaTime.TotalSeconds; // Compute new orientation from mouse movement, gamepad and touch. Vector2F mousePositionDelta = _inputService.MousePositionDelta; GamePadState gamePadState = _inputService.GetGamePadState(LogicalPlayerIndex.One); Vector2F touchDelta = Vector2F.Zero; #if MONOGAME || WINDOWS_PHONE foreach (var gesture in _inputService.Gestures) { if (gesture.GestureType == GestureType.FreeDrag) { touchDelta += (Vector2F)gesture.Delta; // If we have touch input, we ignore the mouse movement mousePositionDelta = Vector2F.Zero; } } #endif #if WINDOWS_PHONE || IOS // On Windows Phone touch input also sets the mouse input. --> Ignore mouse data. mousePositionDelta = Vector2F.Zero; #endif float deltaYaw = -mousePositionDelta.X - touchDelta.X - gamePadState.ThumbSticks.Right.X * ThumbStickFactor; orientationFilter.RawValue[0] += deltaYaw * deltaTimeF * AngularVelocityMagnitude; float deltaPitch = -mousePositionDelta.Y - touchDelta.Y + gamePadState.ThumbSticks.Right.Y * ThumbStickFactor; orientationFilter.RawValue[1] += deltaPitch * deltaTimeF * AngularVelocityMagnitude; // Limit the pitch angle to +/- 90°. orientationFilter.RawValue[1] = MathHelper.Clamp(orientationFilter.RawValue[1], -ConstantsF.PiOver2, ConstantsF.PiOver2); // Reset camera position if <Home> or <Right Stick> is pressed. if (_inputService.IsPressed(Keys.Home, false) || _inputService.IsPressed(Buttons.RightStick, false, LogicalPlayerIndex.One)) { ResetPose(); } // Compute new orientation of the camera. QuaternionF orientation = QuaternionF.CreateRotationY(orientationFilter.RawValue[0]) * QuaternionF.CreateRotationX(orientationFilter.RawValue[1]); // Create velocity from <W>, <A>, <S>, <D> and <R>, <F> keys. // <R> or DPad up is used to move up ("rise"). // <F> or DPad down is used to move down ("fall"). Vector3F velocity = Vector3F.Zero; KeyboardState keyboardState = _inputService.KeyboardState; if (keyboardState.IsKeyDown(Keys.W)) { velocity.Z--; } if (keyboardState.IsKeyDown(Keys.S)) { velocity.Z++; } if (keyboardState.IsKeyDown(Keys.A)) { velocity.X--; } if (keyboardState.IsKeyDown(Keys.D)) { velocity.X++; } if (keyboardState.IsKeyDown(Keys.R) || gamePadState.DPad.Up == ButtonState.Pressed) { velocity.Y++; } if (keyboardState.IsKeyDown(Keys.F) || gamePadState.DPad.Down == ButtonState.Pressed) { velocity.Y--; } // Add velocity from gamepad sticks. velocity.X += gamePadState.ThumbSticks.Left.X; velocity.Z -= gamePadState.ThumbSticks.Left.Y; // Rotate the velocity vector from view space to world space. velocity = orientation.Rotate(velocity); if (keyboardState.IsKeyDown(Keys.LeftShift)) { velocity *= SpeedBoost; } // Multiply the velocity by time to get the translation for this frame. Vector3F translation = velocity * LinearVelocityMagnitude * deltaTimeF; positionFilter.RawValue[0] += translation.X; positionFilter.RawValue[1] += translation.Y; positionFilter.RawValue[2] += translation.Z; positionFilter.Filter(deltaTimeF); orientationFilter.Filter(deltaTimeF); // Update SceneNode.LastPoseWorld - this is required for some effects, like // camera motion blur. CameraNode.LastPoseWorld = CameraNode.PoseWorld; // Set the new (filtered) camera pose. CameraNode.PoseWorld = new Pose( new Vector3F(positionFilter.FilteredValue[0], positionFilter.FilteredValue[1], positionFilter.FilteredValue[2]), QuaternionF.CreateRotationY(orientationFilter.FilteredValue[0]) * QuaternionF.CreateRotationX(orientationFilter.FilteredValue[1])); }
/// <summary> /// Initializes a new instance of the <see cref="AxisAlignedBox"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private AxisAlignedBox(SerializationInfo info, StreamingContext context) { _min = (Vector2F)info.GetValue("Min", typeof(Vector2F)); _max = (Vector2F)info.GetValue("Max", typeof(Vector2F)); }
/// <summary> /// Writes a <see cref="Vector2F"/> instance into the current stream. /// </summary> /// <param name="self">The extended <see cref="BinaryDataWriter"/>.</param> /// <param name="value">The <see cref="Vector2F"/> instance.</param> public static void Write(this BinaryDataWriter self, Vector2F value) { self.Write(value.X); self.Write(value.Y); }
protected override void OnProcess(RenderContext context) { context.ThrowIfCameraMissing(); context.ThrowIfGBuffer0Missing(); var graphicsDevice = GraphicsService.GraphicsDevice; var renderTargetPool = GraphicsService.RenderTargetPool; var source = context.SourceTexture; var target = context.RenderTarget; var viewport = context.Viewport; // Get temporary render targets. var sourceSize = new Vector2F(source.Width, source.Height); var isFloatingPointFormat = TextureHelper.IsFloatingPointFormat(source.Format); var sceneFormat = new RenderTargetFormat(source.Width, source.Height, false, source.Format, DepthFormat.None); var maskedScene = renderTargetPool.Obtain2D(sceneFormat); var rayFormat = new RenderTargetFormat( Math.Max(1, (int)(sourceSize.X / DownsampleFactor)), Math.Max(1, (int)(sourceSize.Y / DownsampleFactor)), false, source.Format, DepthFormat.None); var rayImage0 = renderTargetPool.Obtain2D(rayFormat); var rayImage1 = renderTargetPool.Obtain2D(rayFormat); // Get view and view-projection transforms. var cameraNode = context.CameraNode; Matrix projection = cameraNode.Camera.Projection.ToMatrix(); Matrix view = cameraNode.View; Matrix viewProjection = projection * view; // We simply place the light source "far away" in opposite light ray direction. Vector4 lightPositionWorld = new Vector4(-LightDirection * 10000, 1); // Convert to clip space. Vector4 lightPositionProj = viewProjection * lightPositionWorld; Vector3 lightPositionClip = Vector4.HomogeneousDivide(lightPositionProj); // Convert from clip space [-1, 1] to texture space [0, 1]. Vector2 lightPosition = new Vector2(lightPositionClip.X * 0.5f + 0.5f, -lightPositionClip.Y * 0.5f + 0.5f); // We use dot²(forward, -LightDirection) as a smooth S-shaped attenuation // curve to reduce the god ray effect when we look orthogonal or away from the sun. var lightDirectionView = view.TransformDirection(LightDirection); float z = Math.Max(0, lightDirectionView.Z); float attenuation = z * z; // Common effect parameters. _parameters0Parameter.SetValue(new Vector4(lightPosition.X, lightPosition.Y, LightRadius * LightRadius, Scale)); _parameters1Parameter.SetValue(new Vector2(Softness, graphicsDevice.Viewport.AspectRatio)); _intensityParameter.SetValue((Vector3)Intensity * attenuation); _numberOfSamplesParameter.SetValue(NumberOfSamples); _gBuffer0Parameter.SetValue(context.GBuffer0); // First, create a scene image where occluders are black. graphicsDevice.SetRenderTarget(maskedScene); _viewportSizeParameter.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height)); _sourceTextureParameter.SetValue(source); graphicsDevice.SamplerStates[0] = isFloatingPointFormat ? SamplerState.PointClamp : SamplerState.LinearClamp; graphicsDevice.SamplerStates[1] = SamplerState.PointClamp; // G-Buffer 0. _createMaskPass.Apply(); graphicsDevice.DrawFullScreenQuad(); // Downsample image. context.SourceTexture = maskedScene; context.RenderTarget = rayImage0; context.Viewport = new Viewport(0, 0, rayImage0.Width, rayImage0.Height); _downsampleFilter.Process(context); // Compute light shafts. _viewportSizeParameter.SetValue(new Vector2(context.Viewport.Width, context.Viewport.Height)); graphicsDevice.SamplerStates[0] = isFloatingPointFormat ? SamplerState.PointClamp : SamplerState.LinearClamp; for (int i = 0; i < NumberOfPasses; i++) { graphicsDevice.SetRenderTarget(rayImage1); _sourceTextureParameter.SetValue(rayImage0); _blurPass.Apply(); graphicsDevice.DrawFullScreenQuad(); // Put the current result in variable rayImage0. MathHelper.Swap(ref rayImage0, ref rayImage1); } // Combine light shaft image with scene. graphicsDevice.SetRenderTarget(target); graphicsDevice.Viewport = viewport; _viewportSizeParameter.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height)); _sourceTextureParameter.SetValue(source); _rayTextureParameter.SetValue(rayImage0); graphicsDevice.SamplerStates[0] = isFloatingPointFormat ? SamplerState.PointClamp : SamplerState.LinearClamp; graphicsDevice.SamplerStates[1] = isFloatingPointFormat ? SamplerState.PointClamp : SamplerState.LinearClamp; _combinePass.Apply(); graphicsDevice.DrawFullScreenQuad(); // Clean-up _sourceTextureParameter.SetValue((Texture2D)null); _gBuffer0Parameter.SetValue((Texture2D)null); _rayTextureParameter.SetValue((Texture2D)null); renderTargetPool.Recycle(maskedScene); renderTargetPool.Recycle(rayImage0); renderTargetPool.Recycle(rayImage1); context.SourceTexture = source; context.RenderTarget = target; context.Viewport = viewport; }
/// <summary> /// This method detects if two line segments intersect, /// and, if so, the point of intersection. /// Note: If two line segments are coincident, then /// no intersection is detected (there are actually /// infinite intersection points). /// </summary> /// <param name="point1"> The first point of the first line segment. </param> /// <param name="point2"> The second point of the first line segment. </param> /// <param name="point3"> The first point of the second line segment. </param> /// <param name="point4"> The second point of the second line segment. </param> /// <param name="intersectionPoint"> This is set to the intersection point if an intersection is detected. </param> /// <returns> True if an intersection is detected, false otherwise. </returns> public static bool Intersect( Vector2I point1, Vector2I point2, Vector2I point3, Vector2I point4, out Vector2F intersectionPoint) { return(Intersect(ref point1, ref point2, ref point3, ref point4, true, true, out intersectionPoint)); }
public static void ServerSetWorldOffset(IStaticWorldObject worldObject, Vector2F worldOffset) { var publicState = GetPublicState(worldObject); publicState.WorldOffset = worldOffset; }