private static BoundingBox MeasureBounds(float height, Vector2[] points) { Vector2 min = new Vector2(points.Min(a => a.X), points.Min(a => a.Y)); Vector2 max = new Vector2(points.Max(a => a.X), points.Max(a => a.Y)); return new BoundingBox(new Vector3(min.X, -height / 2, min.Y), new Vector3(max.X, height / 2, max.Y)); }
/// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// @param callback a callback class that is called for each proxy that is hit by the ray. internal void RayCast(RayCastCallbackInternal callback, ref RayCastInput input) { Vector2 p1 = input.p1; Vector2 p2 = input.p2; Vector2 r = p2 - p1; Debug.Assert(r.LengthSquared() > 0.0f); r.Normalize(); // v is perpendicular to the segment. Vector2 v = MathUtils.Cross(1.0f, r); Vector2 abs_v = MathUtils.Abs(v); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float maxFraction = input.maxFraction; // Build a bounding box for the segment. AABB segmentAABB = new AABB(); { Vector2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = Vector2.Min(p1, t); segmentAABB.upperBound = Vector2.Max(p1, t); } int count = 0; stack[count++] = _root; while (count > 0) { int nodeId = stack[--count]; if (nodeId == NullNode) { continue; } DynamicTreeNode node = _nodes[nodeId]; if (AABB.TestOverlap(ref node.aabb, ref segmentAABB) == false) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) Vector2 c = node.aabb.GetCenter(); Vector2 h = node.aabb.GetExtents(); float separation = Math.Abs(Vector2.Dot(v, p1 - c)) - Vector2.Dot(abs_v, h); if (separation > 0.0f) { continue; } if (node.IsLeaf()) { RayCastInput subInput; subInput.p1 = input.p1; subInput.p2 = input.p2; subInput.maxFraction = maxFraction; float value = callback(ref subInput, nodeId); if (value == 0.0f) { // the client has terminated the raycast. return; } if (value > 0.0f) { // Update segment bounding box. maxFraction = value; Vector2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = Vector2.Min(p1, t); segmentAABB.upperBound = Vector2.Max(p1, t); } } else { if (count < k_stackSize) { stack[count++] = node.child1; } if (count < k_stackSize) { stack[count++] = node.child2; } } } }
public void UpdateLBounds(Vector2 _lMin, Vector2 _lMax) { lMin = Vector2.Min(lMin, _lMin); lMin.x = _lMin.x; lMax = Vector2.Max(lMax, _lMax); }
/// <summary> /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a Shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// </summary> /// <param name="callback">A callback class that is called for each proxy that is hit by the ray.</param> /// <param name="input">The ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).</param> public void RayCast(Func <RayCastInput, int, float> callback, ref RayCastInput input) { Vector2 p1 = input.Point1; Vector2 p2 = input.Point2; Vector2 r = p2 - p1; Debug.Assert(r.LengthSquared() > 0.0f); r.Normalize(); // v is perpendicular to the segment. Vector2 absV = MathUtils.Abs(new Vector2(-r.Y, r.X)); //Velcro: Inlined the 'v' variable // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float maxFraction = input.MaxFraction; // Build a bounding box for the segment. AABB segmentAABB = new AABB(); { Vector2 t = p1 + maxFraction * (p2 - p1); Vector2.Min(ref p1, ref t, out segmentAABB.LowerBound); Vector2.Max(ref p1, ref t, out segmentAABB.UpperBound); } _raycastStack.Clear(); _raycastStack.Push(_root); while (_raycastStack.Count > 0) { int nodeId = _raycastStack.Pop(); if (nodeId == NullNode) { continue; } TreeNode <T> node = _nodes[nodeId]; if (AABB.TestOverlap(ref node.AABB, ref segmentAABB) == false) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) Vector2 c = node.AABB.Center; Vector2 h = node.AABB.Extents; float separation = Math.Abs(Vector2.Dot(new Vector2(-r.Y, r.X), p1 - c)) - Vector2.Dot(absV, h); if (separation > 0.0f) { continue; } if (node.IsLeaf()) { RayCastInput subInput; subInput.Point1 = input.Point1; subInput.Point2 = input.Point2; subInput.MaxFraction = maxFraction; float value = callback(subInput, nodeId); if (value == 0.0f) { // the client has terminated the raycast. return; } if (value > 0.0f) { // Update segment bounding box. maxFraction = value; Vector2 t = p1 + maxFraction * (p2 - p1); segmentAABB.LowerBound = Vector2.Min(p1, t); segmentAABB.UpperBound = Vector2.Max(p1, t); } } else { _raycastStack.Push(node.Child1); _raycastStack.Push(node.Child2); } } }
/// <summary> /// Combine an AABB into this one. /// </summary> /// <param name="aabb">The AABB.</param> public void Combine(ref AABB aabb) { LowerBound = Vector2.Min(LowerBound, aabb.LowerBound); UpperBound = Vector2.Max(UpperBound, aabb.UpperBound); }
protected virtual void Update() { if (cachedRectTransformSet == false) { cachedRectTransform = GetComponent <RectTransform>(); cachedRectTransformSet = true; } var finalData = default(LeanTooltipData); var finalPoint = default(Vector2); switch (activation) { case ActivationType.HoverOrPress: { if (HoverShow == true) { finalData = HoverData; finalPoint = HoverPointer.position; } } break; case ActivationType.Hover: { if (HoverShow == true && PressShow == false) { finalData = HoverData; finalPoint = HoverPointer.position; } } break; case ActivationType.Press: { if (PressShow == true && HoverShow == true && HoverData == PressData) { finalData = PressData; finalPoint = PressPointer.position; } } break; } if (tooltip != finalData) { currentDelay = 0.0f; tooltip = finalData; shown = false; Hide(); } if (tooltip != null) { currentDelay += Time.unscaledDeltaTime; if (currentDelay >= showDelay) { if (shown == false) { Show(); } cachedRectTransform.position = finalPoint; } } if (boundary != BoundaryType.None) { cachedRectTransform.GetWorldCorners(corners); var min = Vector2.Min(corners[0], Vector2.Min(corners[1], Vector2.Min(corners[2], corners[3]))); var max = Vector2.Max(corners[0], Vector2.Max(corners[1], Vector2.Max(corners[2], corners[3]))); if (boundary == BoundaryType.Pivot) { var pivot = cachedRectTransform.pivot; if (min.x < 0.0f) { pivot.x = 0.0f; } else if (max.x > Screen.width) { pivot.x = 1.0f; } if (min.y < 0.0f) { pivot.y = 0.0f; } else if (max.y > Screen.height) { pivot.y = 1.0f; } cachedRectTransform.pivot = pivot; } if (boundary == BoundaryType.Position) { var position = cachedRectTransform.position; if (min.x < 0.0f) { position.x -= min.x; } else if (max.x > Screen.width) { position.x -= max.x - Screen.width; } if (min.y < 0.0f) { position.y -= min.y; } else if (max.y > Screen.height) { position.y -= max.y - Screen.height; } cachedRectTransform.position = position; } } }
/// <inheritdoc /> /// <summary> /// Saves the selected scene nodes to the clipboard by Ctrl+C. /// Pastes the scene nodes from the clipboard by Ctrl+V. /// Deletes the selected scene nodes from the scene by Delete. /// </summary> public override void KeyDown(object sender, KeyEventArgs e) { base.KeyDown(sender, e); // copy selected objects at the scene to the clipboard if (e.Control && e.KeyCode == Keys.C) { // clear the current clipboard Screen.Clipboard.Clear(); // rectangle of selected nodes for calculate clipboard position Vector2? lowerBound = null, upperBound = null; // add selected objects at the scene to the clipboard foreach (SceneNode selectedNode in Screen.SelectedNodes) { if (selectedNode.Visible) { Screen.Clipboard.Add(selectedNode); if (lowerBound == null) { lowerBound = selectedNode.Rectangle.LowerBound; upperBound = selectedNode.Rectangle.UpperBound; } else { lowerBound = Vector2.Min(lowerBound.Value, selectedNode.Rectangle.LowerBound); upperBound = Vector2.Max(upperBound.Value, selectedNode.Rectangle.UpperBound); } } } // calculate clipboard position if (lowerBound != null) Screen.ClipboardPosition = 0.5f * (lowerBound.Value + upperBound.Value); } // paste objects from clipboard to the scene else if (e.Control && e.KeyCode == Keys.V && Screen.Clipboard.Count != 0) { // compute move vector for placing objects at the correct position at the scene Vector2 moveVector = Screen.MouseScenePosition - Screen.ClipboardPosition; // save copied objects to the history CompositeCommand command = new CompositeCommand(); List<GameObject> objectsToCloned = new List<GameObject>(); // copy all objects from clipboard to the scene foreach (SceneNode node in Screen.Clipboard) { if (node.Visible && !ContainsAnyParent(Screen.Clipboard, node)) { objectsToCloned.Add(node.Tag); } } foreach (GameObject clonedObject in CloningHelper.Clone(objectsToCloned, Screen.Scene.SelectedLayer, true, true)) { // move object to the new position Screen.Find(clonedObject).Move(moveVector); command.Commands.Add(clonedObject.CreateAddCommand()); } // add command to history if (command.Commands.Count != 0) Screen.History.Add(command); } // delete selected objects from the scene and copy them to the clipboard // NOT WORKING when safe deleting is on because it will clear clipboard /*else if (e.Control && e.KeyCode == Keys.X) { // clear the current clipboard Screen.Clipboard.Clear(); // rectangle of selected nodes for calculate clipboard position Vector2? lowerBound = null, upperBound = null; // save deleted objects to the history CompositeCommand command = new CompositeCommand(); List<ItemForDeletion> itemsForDeletion = new List<ItemForDeletion>(); // add selected objects at the scene to the clipboard foreach (SceneNode selectedNode in Screen.SelectedNodes) { if (selectedNode.Visible) { command.Commands.Add(selectedNode.Tag.CreateDeleteCommand()); if (selectedNode.Tag is Actor) itemsForDeletion.Add(new ConsistentDeletionHelper.ActorForDeletion((Actor)selectedNode.Tag)); else if (selectedNode.Tag is Path) itemsForDeletion.Add(new ConsistentDeletionHelper.PathForDeletion((Path)selectedNode.Tag)); else { Debug.Assert(true, "Not supported game objects deleting."); selectedNode.Tag.Remove(); } // add to the clipboard Screen.Clipboard.Add(selectedNode); if (lowerBound == null) { lowerBound = selectedNode.Rectangle.LowerBound; upperBound = selectedNode.Rectangle.UpperBound; } else { lowerBound = Vector2.Min(lowerBound.Value, selectedNode.Rectangle.LowerBound); upperBound = Vector2.Max(upperBound.Value, selectedNode.Rectangle.UpperBound); } } } // calculate clipboard position if (lowerBound != null) Screen.ClipboardPosition = 0.5f * (lowerBound.Value + upperBound.Value); if ((new ConsistentDeletionForm(itemsForDeletion) { ProcessWhenEmptyList = true }).ShowDialog() == DialogResult.OK) { if (command.Commands.Count != 0) Screen.History.Add(command); // clear selected objects at the scene Screen.SelectedNodes.Clear(); // selected nodes changed Screen.InvokeSelectedNodesChanged(); } }*/ // delete selected objects from the scene else if (e.KeyCode == Keys.Delete) { // save deleted objects to the history CompositeCommand command = new CompositeCommand(); List<ItemForDeletion> itemsForDeletion = new List<ItemForDeletion>(); // remove all selected objects from the scene foreach (SceneNode selectedNode in Screen.SelectedNodes) { if (selectedNode.Visible) { command.Commands.Add(selectedNode.Tag.CreateDeleteCommand()); if (selectedNode.Tag is Actor) itemsForDeletion.Add(new ConsistentDeletionHelper.ActorForDeletion((Actor)selectedNode.Tag)); else if (selectedNode.Tag is Path) itemsForDeletion.Add(new ConsistentDeletionHelper.PathForDeletion((Path)selectedNode.Tag)); else { Debug.Assert(true, "Not supported game objects deleting."); selectedNode.Tag.Remove(); } } } if ((new ConsistentDeletionForm(itemsForDeletion) { ProcessWhenEmptyList = true }).ShowDialog() == DialogResult.OK) { if (command.Commands.Count != 0) Screen.History.Add(command); // clear selected objects at the scene Screen.SelectedNodes.Clear(); // selected nodes changed Screen.InvokeSelectedNodesChanged(); } } }
public AABB Combine(Vector2 point) => new AABB() { Min = Vector2.Min(Min, point), Max = Vector2.Max(Max, point) };
public virtual Vector2 GetPlacePosition(int FactionNumber) { float BestScore = -500000; Vector2 BestPosition = Vector2.Zero; float Distance = 1000; float JumpSize = 100; Vector2 MinPos = new Vector2(10000); Vector2 MaxPos = new Vector2(-10000); foreach (MiningPlatform m in GameManager.GetLevel().getCurrentScene().Enumerate(typeof(MiningPlatform))) { if (m.GetTeam() == FactionManager.GetTeam(FactionNumber) && !m.Dead) { MinPos = Vector2.Min(MinPos, m.Position.get() - new Vector2(Distance)); MaxPos = Vector2.Max(MaxPos, m.Position.get() + new Vector2(Distance)); } } Basic2DScene b = (Basic2DScene)GameManager.GetLevel().getCurrentScene(); MinPos = Vector2.Max(MinPos, b.MinBoundary.get()); MaxPos = Vector2.Min(MaxPos, b.MaxBoundary.get()); for (float x = MinPos.X; x < MaxPos.X; x += JumpSize) { for (float y = MinPos.Y; y < MaxPos.Y; y += JumpSize) { if (TestFree(new Vector2(x, y), TurretSize, FactionNumber) && PathFindingManager.GetCellValue(new Vector2(x, y)) != PathFindingManager.DeadCell) { float score = 5000; if (GetTurretFragility() != 0) { if (PathFindingManager.CollisionLine(new Vector2(x, y), 1, 0, 3)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), -1, 0, 3)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), 0, 1, 3)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), 0, -1, 3)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), -1, -1, 2)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), 1, -1, 2)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), -1, 1, 2)) { score += 100 * GetTurretFragility(); } if (PathFindingManager.CollisionLine(new Vector2(x, y), 1, 1, 2)) { score += 100 * GetTurretFragility(); } } foreach (NeutralSpawn spawn in NeutralManager.SpawnList) { if (PathFindingManager.GetCellValue(spawn.Position.get()) > PathFindingManager.StartingCell - 50 && PathFindingManager.GetCellValue(spawn.Position.get()) < PathFindingManager.StartingCell - 20 && PathFindingManager.GetAreaClear(spawn.Position.get())) { if (GetTurretFragility() != 0 && PathFindingManager.CollisionLine(new Vector2(x, y), spawn.Position.get())) { score += 500 * GetTurretFragility(); } if (score > BestScore) { MiningPlatform NearestMiningPlatform = null; float NearestDistance = 10000; foreach (MiningPlatform m2 in GameManager.GetLevel().getCurrentScene().Enumerate(typeof(MiningPlatform))) { if (m2.GetTeam() == FactionManager.GetTeam(FactionNumber) && !m2.Dead) { float d = Vector2.Distance(m2.Position.get(), spawn.Position.get()); if (d < NearestDistance) { NearestDistance = d; NearestMiningPlatform = m2; } } } score -= Logic.DistanceLineSegmentToPoint(spawn.Position.get(), NearestMiningPlatform.Position.get(), new Vector2(x, y)) * GetTurretAgression(); } } } if (score > BestScore) { Basic2DScene Parent2DScene = (Basic2DScene)GameManager.GetLevel().getCurrentScene(); QuadGrid quad = Parent2DScene.quadGrids.First.Value; foreach (Basic2DObject o in quad.Enumerate(new Vector2(x, y), new Vector2(200))) { if (o.GetType().IsSubclassOf(typeof(UnitBuilding))) { UnitBuilding s = (UnitBuilding)o; if (s.GetTeam() == FactionManager.GetTeam(FactionNumber)) { float d = Vector2.Distance(o.Position.get(), new Vector2(x, y)); if (d < 2000) { score -= (2000 - d) * GetBuildingAvoidence(); if (s.GetType().IsSubclassOf(typeof(MiningPlatform))) { score -= (2000 - d) * GetBaseAvoidence(); } else if (s.GetType().IsSubclassOf(typeof(UnitTurret))) { UnitTurret t = (UnitTurret)s; if (t.MyCard != null) { if (t.MyCard.StrongVs.Equals(StrongVs)) { score -= (2000 - d) * GetTurretAvoidence(); } } else { if (StrongVs.Equals("Heavy")) { score -= (2000 - d) * GetTurretAvoidence(); } } } } } } } if (score > BestScore) { BestScore = score; BestPosition = new Vector2(x, y); } } } } } return(BestPosition); }
public void ExpandToInclude(GeoAABB2 b) { mMin = Vector2.Min(mMin, b.mMin); mMax = Vector2.Max(mMax, b.mMax); mExtent = mMax - mMin; }
public void ExpandToInclude(Vector2 p) { mMin = Vector2.Min(mMin, p); mMax = Vector2.Max(mMax, p); mExtent = mMax - mMin; }
public void Build(ImGui gui, float height) { this.gui = gui; this.height = height; var rect = gui.statePosition; var width = rect.Width; if (vertical) { width -= ScrollbarSize; } if (gui.isBuilding) { var innerRect = rect; innerRect.Width = width; contentSize = MeasureContent(innerRect, gui); maxScroll = Vector2.Max(contentSize - new Vector2(innerRect.Width, height), Vector2.Zero); var realHeight = collapsible ? MathF.Min(contentSize.Y, height) : height; innerRect.Height = rect.Height = realHeight; if (horizontal && maxScroll.X > 0) { realHeight -= ScrollbarSize; innerRect.Height = realHeight; } gui.EncapsulateRect(rect); scroll2d = Vector2.Clamp(scroll2d, Vector2.Zero, maxScroll); PositionContent(gui, innerRect); } else { var realHeight = collapsible ? MathF.Min(contentSize.Y, height) : height; if (horizontal && maxScroll.X > 0) { realHeight -= ScrollbarSize; } rect.Height = realHeight; gui.EncapsulateRect(rect); } var size = new Vector2(width, height); var scrollSize = (size * size) / (size + maxScroll); scrollSize = Vector2.Max(scrollSize, Vector2.One); var scrollStart = (_scroll / maxScroll) * (size - scrollSize); if ((gui.action == ImGuiAction.MouseDown || gui.action == ImGuiAction.MouseScroll) && rect.Contains(gui.mousePosition)) { InputSystem.Instance.SetKeyboardFocus(this); } if (gui.action == ImGuiAction.MouseScroll) { if (gui.ConsumeEvent(rect)) { if (vertical && (!horizontal || !InputSystem.Instance.control)) { scroll += gui.actionParameter * 3f; } else { scrollX += gui.actionParameter * 3f; } } } else { if (horizontal && maxScroll.X > 0f) { var fullScrollRect = new Rect(rect.X, rect.Bottom - ScrollbarSize, rect.Width, ScrollbarSize); var scrollRect = new Rect(rect.X + scrollStart.X, fullScrollRect.Y, scrollSize.X, ScrollbarSize); BuildScrollBar(gui, 0, in fullScrollRect, in scrollRect); } if (vertical && maxScroll.Y > 0f) { var fullScrollRect = new Rect(rect.Right - ScrollbarSize, rect.Y, ScrollbarSize, rect.Height); var scrollRect = new Rect(fullScrollRect.X, rect.Y + scrollStart.Y, ScrollbarSize, scrollSize.Y); BuildScrollBar(gui, 1, in fullScrollRect, in scrollRect); } } }
protected virtual void Update() { if (cachedRectTransformSet == false) { cachedRectTransform = GetComponent <RectTransform>(); cachedRectTransformSet = true; } var finalData = CurrentShow == true ? CurrentData : null; if (tooltip != finalData) { currentDelay = 0.0f; tooltip = finalData; shown = false; Hide(); } if (tooltip != null) { currentDelay += Time.unscaledDeltaTime; if (currentDelay >= showDelay) { if (shown == false) { Show(); } if (CurrentPointer != null) { cachedRectTransform.position = CurrentPointer.position; } } } if (boundary != BoundaryType.None) { cachedRectTransform.GetWorldCorners(corners); var min = Vector2.Min(corners[0], Vector2.Min(corners[1], Vector2.Min(corners[2], corners[3]))); var max = Vector2.Max(corners[0], Vector2.Max(corners[1], Vector2.Max(corners[2], corners[3]))); if (boundary == BoundaryType.Pivot) { var pivot = cachedRectTransform.pivot; if (min.x < 0.0f) { pivot.x = 0.0f; } else if (max.x > Screen.width) { pivot.x = 1.0f; } if (min.y < 0.0f) { pivot.y = 0.0f; } else if (max.y > Screen.height) { pivot.y = 1.0f; } cachedRectTransform.pivot = pivot; } if (boundary == BoundaryType.Position) { var position = cachedRectTransform.position; if (min.x < 0.0f) { position.x -= min.x; } else if (max.x > Screen.width) { position.x -= max.x - Screen.width; } if (min.y < 0.0f) { position.y -= min.y; } else if (max.y > Screen.height) { position.y -= max.y - Screen.height; } cachedRectTransform.position = position; } } }
public static void FillPolygon(this Texture2D texture, Vector2[] points, Color color) { // http://alienryderflex.com/polygon_fill/ var IMAGE_BOT = (int)points.Max(p => p.y); var IMAGE_TOP = (int)points.Min(p => p.y); var IMAGE_LEFT = (int)points.Min(p => p.x); var IMAGE_RIGHT = (int)points.Max(p => p.x); var MAX_POLY_CORNERS = points.Count(); var polyCorners = MAX_POLY_CORNERS; var polyY = points.Select(p => p.y).ToArray(); var polyX = points.Select(p => p.x).ToArray(); int[] nodeX = new int[MAX_POLY_CORNERS]; int nodes, pixelX, i, j, swap; // Loop through the rows of the image. for (int pixelY = IMAGE_TOP; pixelY <= IMAGE_BOT; pixelY++) { // Build a list of nodes. nodes = 0; j = polyCorners - 1; for (i = 0; i < polyCorners; i++) { if (polyY[i] < (float)pixelY && polyY[j] >= (float)pixelY || polyY[j] < (float)pixelY && polyY[i] >= (float)pixelY) { nodeX[nodes++] = (int)(polyX[i] + (pixelY - polyY[i]) / (polyY[j] - polyY[i]) * (polyX[j] - polyX[i])); } j = i; } // Sort the nodes, via a simple “Bubble” sort. i = 0; while (i < nodes - 1) { if (nodeX[i] > nodeX[i + 1]) { swap = nodeX[i]; nodeX[i] = nodeX[i + 1]; nodeX[i + 1] = swap; if (i != 0) i--; } else { i++; } } // Fill the pixels between node pairs. for (i = 0; i < nodes; i += 2) { if (nodeX[i] >= IMAGE_RIGHT) break; if (nodeX[i + 1] > IMAGE_LEFT) { if (nodeX[i] < IMAGE_LEFT) nodeX[i] = IMAGE_LEFT; if (nodeX[i + 1] > IMAGE_RIGHT) nodeX[i + 1] = IMAGE_RIGHT; for (j = nodeX[i]; j < nodeX[i + 1]; j++) texture.SetPixel(j, pixelY, color); } } } }
private void ProcessSpriteDefinition(String name) { // Strip folder names. int index = name.LastIndexOfAny(new char[] { '/', '\\' }); if (index != -1) { name = name.Substring(index + 1); } tk2dSpriteDefinition def = sprites.inst.GetSpriteDefinition(name); if (def == null) { Debug.Log("Sprite not found in atlas: " + name, sprites); throw new Exception("Sprite not found in atlas: " + name); } if (def.complexGeometry) { throw new NotImplementedException("Complex geometry is not supported: " + name); } if (def.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW) { throw new NotImplementedException("Only 2D Toolkit atlases are supported: " + name); } Vector2 minTexCoords = Vector2.one, maxTexCoords = Vector2.zero; for (int i = 0; i < def.uvs.Length; ++i) { Vector2 uv = def.uvs[i]; minTexCoords = Vector2.Min(minTexCoords, uv); maxTexCoords = Vector2.Max(maxTexCoords, uv); } regionRotated = def.flipped == tk2dSpriteDefinition.FlipMode.Tk2d; if (regionRotated) { float temp = minTexCoords.x; minTexCoords.x = maxTexCoords.x; maxTexCoords.x = temp; } u = minTexCoords.x; v = maxTexCoords.y; u2 = maxTexCoords.x; v2 = minTexCoords.y; regionOriginalWidth = (int)(def.untrimmedBoundsData[1].x / def.texelSize.x); regionOriginalHeight = (int)(def.untrimmedBoundsData[1].y / def.texelSize.y); regionWidth = (int)(def.boundsData[1].x / def.texelSize.x); regionHeight = (int)(def.boundsData[1].y / def.texelSize.y); float x0 = def.untrimmedBoundsData[0].x - def.untrimmedBoundsData[1].x / 2; float x1 = def.boundsData[0].x - def.boundsData[1].x / 2; regionOffsetX = (int)((x1 - x0) / def.texelSize.x); float y0 = def.untrimmedBoundsData[0].y - def.untrimmedBoundsData[1].y / 2; float y1 = def.boundsData[0].y - def.boundsData[1].y / 2; regionOffsetY = (int)((y1 - y0) / def.texelSize.y); material = def.material; }
void DrawHandleGUI(SceneView sceneView) { if (sceneView != SceneView.lastActiveSceneView) { return; } if (m_CurrentEvent.type == EventType.Repaint && !SceneDragAndDropListener.isDragging && m_Hovering != null && GUIUtility.hotControl == 0 && HandleUtility.nearestControl == m_DefaultControl && selectMode.IsMeshElementMode()) { try { EditorMeshHandles.DrawSceneSelection(m_Hovering); } catch { // this happens on undo, when c++ object is destroyed but c# side thinks it's still alive } } using (new HandleGUI()) { int screenWidth = (int)sceneView.position.width; int screenHeight = (int)sceneView.position.height; switch ((SceneToolbarLocation)s_SceneToolbarLocation) { case SceneToolbarLocation.BottomCenter: m_ElementModeToolbarRect.x = (screenWidth / 2 - 64); m_ElementModeToolbarRect.y = screenHeight - m_ElementModeToolbarRect.height * 3; break; case SceneToolbarLocation.BottomLeft: m_ElementModeToolbarRect.x = 12; m_ElementModeToolbarRect.y = screenHeight - m_ElementModeToolbarRect.height * 3; break; case SceneToolbarLocation.BottomRight: m_ElementModeToolbarRect.x = screenWidth - (m_ElementModeToolbarRect.width + 12); m_ElementModeToolbarRect.y = screenHeight - m_ElementModeToolbarRect.height * 3; break; case SceneToolbarLocation.UpperLeft: m_ElementModeToolbarRect.x = 12; m_ElementModeToolbarRect.y = 10; break; case SceneToolbarLocation.UpperRight: m_ElementModeToolbarRect.x = screenWidth - (m_ElementModeToolbarRect.width + 96); m_ElementModeToolbarRect.y = 10; break; default: case SceneToolbarLocation.UpperCenter: m_ElementModeToolbarRect.x = (screenWidth / 2 - 64); m_ElementModeToolbarRect.y = 10; break; } selectMode = UI.EditorGUIUtility.DoElementModeToolbar(m_ElementModeToolbarRect, selectMode); if (s_ShowSceneInfo) { Vector2 size = UI.EditorStyles.sceneTextBox.CalcSize(m_SceneInfo); m_SceneInfoRect.width = size.x; m_SceneInfoRect.height = size.y; GUI.Label(m_SceneInfoRect, m_SceneInfo, UI.EditorStyles.sceneTextBox); } if (m_IsDragging) { if (m_CurrentEvent.type == EventType.Repaint) { // Always draw from lowest to largest values var start = Vector2.Min(m_InitialMousePosition, m_CurrentEvent.mousePosition); var end = Vector2.Max(m_InitialMousePosition, m_CurrentEvent.mousePosition); m_MouseDragRect = new Rect(start.x, start.y, end.x - start.x, end.y - start.y); SceneStyles.selectionRect.Draw(m_MouseDragRect, false, false, false, false); } else if (m_CurrentEvent.isMouse) { HandleUtility.Repaint(); } } } }
public void AddPoint(NormalizedPoint point) { m_Points.Add(point); m_Rect.min = Vector2.Min(m_Rect.min, point.Position); m_Rect.max = Vector2.Max(m_Rect.max, point.Position); }
public static Vector2 vector2_max(Vector2 v1, Vector2 v2) { return(Vector2.Max(v1, v2)); }
public static Vector2 origFramePos; //can't use screenRect position (since mouse could be moved up left) public static void UpdateFrame() { Event eventCurrent = Event.current; bool isAlt = eventCurrent.alt; //just pressed if (eventCurrent.type == EventType.MouseDown && eventCurrent.button == 0 && !isAlt) { justStarted = true; isDragging = true; origFramePos = eventCurrent.mousePosition; frameRect = new Rect(origFramePos, new Vector2(0, 0)); //eventCurrent.Use(); if (UnityEditor.EditorWindow.focusedWindow != null) { UnityEditor.EditorWindow.focusedWindow.Repaint(); } return; } //just released if (eventCurrent.rawType == EventType.MouseUp) //any button, any drag state { if (isFrame) { justReleased = true; //if (Event.current.isMouse) eventCurrent.Use(); if (UnityEditor.EditorWindow.focusedWindow != null) { UnityEditor.EditorWindow.focusedWindow.Repaint(); } //isDragging = false; //disabling next frame //isFrame = false; } else { isDragging = false; isFrame = false; } return; } //frame after released - disabling both released and dragged if (justReleased) { isFrame = false; isDragging = false; justReleased = false; } //creating frame if dragged 5 pixels from origin if (isDragging && !isFrame && !isAlt) { if ((eventCurrent.mousePosition - origFramePos).sqrMagnitude > 250) { isFrame = true; } } if (isFrame && !eventCurrent.alt) { Vector2 max = Vector2.Max(eventCurrent.mousePosition, origFramePos); Vector2 min = Vector2.Min(eventCurrent.mousePosition, origFramePos); frameRect = new Rect(min, max - min); DrawSelectionFrame(frameRect); //eventCurrent.Use(); if (UnityEditor.EditorWindow.focusedWindow != null) { UnityEditor.EditorWindow.focusedWindow.Repaint(); } return; } //making frame equal to mouse cursor if not dragging if (!isDragging) { frameRect = new Rect(eventCurrent.mousePosition, Vector2.zero); } }
public IBufferValue[] ActionHandle(BuffHandlerVar buffHandlerVar) { Buff_RangeDetection buff_RangeDetection = (Buff_RangeDetection)buffHandlerVar.data; if (!buffHandlerVar.GetBufferValue(out BufferValue_Pos bufferValue_Pos)) { return(null); } //主要目的是返回多个群体目标对象 BufferValue_TargetUnits bufferValue_TargetUnits = new BufferValue_TargetUnits(); PolyshapeQueryCallback polyshapeQueryCallback = new PolyshapeQueryCallback(); AABB ab = new AABB(); switch (buff_RangeDetection.shapeType) { case Buff_RangeDetection.CollisionShape.Box: //根据传入进来的方向和位置计算做范围检测的区域 if (!buffHandlerVar.GetBufferValue(out BufferValue_Dir bufferValue_Dir)) { Log.Error("Box检测没有收到方向 " + buffHandlerVar.skillId); return(null); } Vector2 pos = bufferValue_Pos.aimPos.ToVector2(); var transform = new Transform(in pos, bufferValue_Dir.dir.ToRotation2D().Angle); var Vertices = new Vector2[4]; float hx = buff_RangeDetection.shapeValue.x; float hy = buff_RangeDetection.shapeValue.y; Vertices[0].Set(-hx, -hy); Vertices[1].Set(hx, -hy); Vertices[2].Set(hx, hy); Vertices[3].Set(-hx, hy); for (var i = 0; i < 4; ++i) { Vertices[i] = MathUtils.Mul(transform, Vertices[i]); } ab.UpperBound = ab.LowerBound = Vertices[0]; for (var i = 1; i < 4; ++i) { var v = Vertices[i]; ab.LowerBound = Vector2.Min(ab.LowerBound, v); ab.UpperBound = Vector2.Max(ab.UpperBound, v); } var r = new Vector2(Settings.PolygonRadius, Settings.PolygonRadius); ab.LowerBound -= r; ab.UpperBound += r; break; case Buff_RangeDetection.CollisionShape.Circle: pos = bufferValue_Pos.aimPos.ToVector2(); transform = new Transform(in pos, 0); var p = MathUtils.Mul(transform.Rotation, transform.Position); float raidus = buff_RangeDetection.shapeValue.x; ab.LowerBound.Set(p.X - raidus, p.Y - raidus); ab.UpperBound.Set(p.X + raidus, p.Y + raidus); break; } //Log.Debug(ab.LowerBound.ToString() + ab.UpperBound.ToString()); PhysicWorldComponent.Instance.world.QueryAABB(polyshapeQueryCallback, ab); if (polyshapeQueryCallback.units == null || polyshapeQueryCallback.units.Count == 0) { Log.Debug("没有检测到任何单位"); return(null); } for (int i = polyshapeQueryCallback.units.Count - 1; i >= 0; i--) { //默认层(一般是特效,墙壁等) if (polyshapeQueryCallback.units[i].UnitData.groupIndex == GroupIndex.Default || polyshapeQueryCallback.units[i].UnitData.unitLayer == UnitLayer.Default) { polyshapeQueryCallback.units.RemoveAt(i); continue; } if (buff_RangeDetection.FindFriend) { if (polyshapeQueryCallback.units[i].UnitData.groupIndex != buffHandlerVar.source.UnitData.groupIndex) { polyshapeQueryCallback.units.RemoveAt(i); continue; } } else { if (polyshapeQueryCallback.units[i].UnitData.groupIndex == buffHandlerVar.source.UnitData.groupIndex) { polyshapeQueryCallback.units.RemoveAt(i); continue; } } //高度区域检测 if (Math.Abs((bufferValue_Pos.aimPos.y + buff_RangeDetection.halfHeight) - (polyshapeQueryCallback.units[i].Position.y + polyshapeQueryCallback.units[i].OffsetY)) > (buff_RangeDetection.halfHeight + polyshapeQueryCallback.units[i].HalfHeight)) { polyshapeQueryCallback.units.RemoveAt(i); Log.Debug("目前高度不在检测的范围内!"); continue; } else { Log.Debug("目前高度在检测的范围内!"); } } //拿到了所有检测到的Unit bufferValue_TargetUnits.targets = polyshapeQueryCallback.units.ToArray(); // Log.Debug("范围检测到了 " + bufferValue_TargetUnits.targets.Length+ " 个目标"); return(new IBufferValue[] { bufferValue_TargetUnits }); }
public static void DrawHandles(HDAdditionalLightData additionalData, Editor owner) { Light light = additionalData.legacyLight; Color wireframeColorAbove = (owner as HDLightEditor).legacyLightColor; Color handleColorAbove = CoreLightEditorUtilities.GetLightHandleColor(wireframeColorAbove); Color wireframeColorBehind = CoreLightEditorUtilities.GetLightBehindObjectWireframeColor(wireframeColorAbove); Color handleColorBehind = CoreLightEditorUtilities.GetLightHandleColor(wireframeColorBehind); switch (additionalData.lightTypeExtent) { case LightTypeExtent.Punctual: switch (light.type) { case LightType.Directional: case LightType.Point: //use legacy handles for those cases: //See HDLightEditor break; case LightType.Spot: switch (additionalData.spotLightShape) { case SpotLightShape.Cone: using (new Handles.DrawingScope(Matrix4x4.TRS(light.transform.position, light.transform.rotation, Vector3.one))) { Vector3 outterAngleInnerAngleRange = new Vector3(light.spotAngle, light.spotAngle * additionalData.GetInnerSpotPercent01(), light.range); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = wireframeColorBehind; CoreLightEditorUtilities.DrawSpotlightWireframe(outterAngleInnerAngleRange, additionalData.shadowNearPlane); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = wireframeColorAbove; CoreLightEditorUtilities.DrawSpotlightWireframe(outterAngleInnerAngleRange, additionalData.shadowNearPlane); EditorGUI.BeginChangeCheck(); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = handleColorBehind; outterAngleInnerAngleRange = CoreLightEditorUtilities.DrawSpotlightHandle(outterAngleInnerAngleRange); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = handleColorAbove; outterAngleInnerAngleRange = CoreLightEditorUtilities.DrawSpotlightHandle(outterAngleInnerAngleRange); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(new UnityEngine.Object[] { light, additionalData }, "Adjust Cone Spot Light"); additionalData.m_InnerSpotPercent = 100f * outterAngleInnerAngleRange.y / Mathf.Max(0.1f, outterAngleInnerAngleRange.x); light.spotAngle = outterAngleInnerAngleRange.x; light.range = outterAngleInnerAngleRange.z; } // Handles.color reseted at end of scope } break; case SpotLightShape.Pyramid: using (new Handles.DrawingScope(Matrix4x4.TRS(light.transform.position, light.transform.rotation, Vector3.one))) { Vector4 aspectFovMaxRangeMinRange = new Vector4(additionalData.aspectRatio, light.spotAngle, light.range); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = wireframeColorBehind; CoreLightEditorUtilities.DrawSpherePortionWireframe(aspectFovMaxRangeMinRange, additionalData.shadowNearPlane); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = wireframeColorAbove; CoreLightEditorUtilities.DrawSpherePortionWireframe(aspectFovMaxRangeMinRange, additionalData.shadowNearPlane); EditorGUI.BeginChangeCheck(); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = handleColorBehind; aspectFovMaxRangeMinRange = CoreLightEditorUtilities.DrawSpherePortionHandle(aspectFovMaxRangeMinRange, false); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = handleColorAbove; aspectFovMaxRangeMinRange = CoreLightEditorUtilities.DrawSpherePortionHandle(aspectFovMaxRangeMinRange, false); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(new UnityEngine.Object[] { light, additionalData }, "Adjust Pyramid Spot Light"); additionalData.aspectRatio = aspectFovMaxRangeMinRange.x; light.spotAngle = aspectFovMaxRangeMinRange.y; light.range = aspectFovMaxRangeMinRange.z; } // Handles.color reseted at end of scope } break; case SpotLightShape.Box: using (new Handles.DrawingScope(Matrix4x4.TRS(light.transform.position, light.transform.rotation, Vector3.one))) { Vector4 widthHeightMaxRangeMinRange = new Vector4(additionalData.shapeWidth, additionalData.shapeHeight, light.range); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = wireframeColorBehind; CoreLightEditorUtilities.DrawOrthoFrustumWireframe(widthHeightMaxRangeMinRange, additionalData.shadowNearPlane); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = wireframeColorAbove; CoreLightEditorUtilities.DrawOrthoFrustumWireframe(widthHeightMaxRangeMinRange, additionalData.shadowNearPlane); EditorGUI.BeginChangeCheck(); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = handleColorBehind; widthHeightMaxRangeMinRange = CoreLightEditorUtilities.DrawOrthoFrustumHandle(widthHeightMaxRangeMinRange, false); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = handleColorAbove; widthHeightMaxRangeMinRange = CoreLightEditorUtilities.DrawOrthoFrustumHandle(widthHeightMaxRangeMinRange, false); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(new UnityEngine.Object[] { light, additionalData }, "Adjust Box Spot Light"); additionalData.shapeWidth = widthHeightMaxRangeMinRange.x; additionalData.shapeHeight = widthHeightMaxRangeMinRange.y; light.range = widthHeightMaxRangeMinRange.z; } // Handles.color reseted at end of scope } break; } break; } break; case LightTypeExtent.Rectangle: case LightTypeExtent.Tube: bool withYAxis = additionalData.lightTypeExtent == LightTypeExtent.Rectangle; using (new Handles.DrawingScope(Matrix4x4.TRS(light.transform.position, light.transform.rotation, Vector3.one))) { Vector2 widthHeight = new Vector4(additionalData.shapeWidth, withYAxis ? additionalData.shapeHeight : 0f); float range = light.range; EditorGUI.BeginChangeCheck(); Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = wireframeColorBehind; CoreLightEditorUtilities.DrawAreaLightWireframe(widthHeight); range = Handles.RadiusHandle(Quaternion.identity, Vector3.zero, range); //also draw handles Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = wireframeColorAbove; CoreLightEditorUtilities.DrawAreaLightWireframe(widthHeight); range = Handles.RadiusHandle(Quaternion.identity, Vector3.zero, range); //also draw handles Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater; Handles.color = handleColorBehind; widthHeight = CoreLightEditorUtilities.DrawAreaLightHandle(widthHeight, withYAxis); Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; Handles.color = handleColorAbove; widthHeight = CoreLightEditorUtilities.DrawAreaLightHandle(widthHeight, withYAxis); widthHeight = Vector2.Max(Vector2.one * k_MinLightSize, widthHeight); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(new UnityEngine.Object[] { light, additionalData }, withYAxis ? "Adjust Area Rectangle Light" : "Adjust Area Tube Light"); additionalData.shapeWidth = widthHeight.x; if (withYAxis) { additionalData.shapeHeight = widthHeight.y; } light.range = range; } // Handles.color reseted at end of scope } break; } }
private void DrawPreview(Rect r) { if (r.height <= 0) { return; } if (m_ZoomablePreview == null) { m_ZoomablePreview = new ZoomableArea(true); m_ZoomablePreview.hRangeMin = 0.0f; m_ZoomablePreview.vRangeMin = 0.0f; m_ZoomablePreview.hRangeMax = 1.0f; m_ZoomablePreview.vRangeMax = 1.0f; m_ZoomablePreview.SetShownHRange(0, 1); m_ZoomablePreview.SetShownVRange(0, 1); m_ZoomablePreview.uniformScale = true; m_ZoomablePreview.scaleWithWindow = true; } m_ZoomablePreview.rect = r; m_ZoomablePreview.BeginViewGUI(); m_ZoomablePreview.hSlider = m_ZoomablePreview.shownArea.width < 1; m_ZoomablePreview.vSlider = m_ZoomablePreview.shownArea.height < 1; Rect drawableArea = m_ZoomablePreview.drawRect; GITextureType textureType = GetSelectedTextureType(); UpdateCachedTexture(textureType); if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureNotAvailable || m_CachedTexture.textureAvailability == GITextureAvailability.GITextureUnknown) { if (!isRealtimeLightmap) { if (!LightmapVisualizationUtility.IsAtlasTextureType(textureType) && isIndexBased) { GUI.Label(drawableArea, Styles.TextureNotAvailableBakedAlbedoEmissive, Styles.PreviewLabel); } else if (textureType == GITextureType.BakedShadowMask) { GUI.Label(drawableArea, Styles.TextureNotAvailableBakedShadowmask, Styles.PreviewLabel); } else { GUI.Label(drawableArea, Styles.TextureNotAvailableBaked, Styles.PreviewLabel); } } else { GUI.Label(drawableArea, Styles.TextureNotAvailableRealtime, Styles.PreviewLabel); } return; } if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureLoading && m_CachedTexture.texture == null) { GUI.Label(drawableArea, Styles.TextureLoading, Styles.PreviewLabel); return; } LightmapType lightmapType = LightmapVisualizationUtility.GetLightmapType(textureType); switch (Event.current.type) { // 'F' will zoom to uv bounds case EventType.ValidateCommand: case EventType.ExecuteCommand: if (Event.current.commandName == EventCommandNames.FrameSelected && IsActiveGameObjectInLightmap(textureType)) { // There are instance based baked textures where we don't get any STs and can't do the framing if (!isRealtimeLightmap && !LightmapVisualizationUtility.IsAtlasTextureType(textureType)) { break; } Vector4 lightmapTilingOffset = LightmapVisualizationUtility.GetLightmapTilingOffset(lightmapType); Vector2 min = new Vector2(lightmapTilingOffset.z, lightmapTilingOffset.w); Vector2 max = min + new Vector2(lightmapTilingOffset.x, lightmapTilingOffset.y); min = Vector2.Max(min, Vector2.zero); max = Vector2.Min(max, Vector2.one); Texture2D texture = m_CachedTexture.texture; Rect textureRect = new Rect(r.x, r.y, texture.width, texture.height); textureRect = ResizeRectToFit(textureRect, drawableArea); float offsetX = 0.0f, offsetY = 0.0f; if (textureRect.height == drawableArea.height) { offsetX = (drawableArea.width - textureRect.width) / drawableArea.width; } else { offsetY = (drawableArea.height - textureRect.height) / drawableArea.height; } // Make sure that the focus rectangle is a even square Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y); rect.width = rect.height = Mathf.Max(rect.width, rect.height); rect.x -= (offsetX * min.x); rect.y += (offsetY * (1 - max.y)); m_ZoomablePreview.shownArea = rect; Event.current.Use(); } break; // Scale and draw texture and uv's case EventType.Repaint: { Texture2D texture = m_CachedTexture.texture; if (texture) { Rect textureRect = new Rect(r.x, r.y, texture.width, texture.height); textureRect = ResizeRectToFit(textureRect, drawableArea); textureRect = ScaleRectByZoomableArea(textureRect, m_ZoomablePreview); const int padding = 5; textureRect.x += padding; textureRect.width -= padding * 2; textureRect.height -= padding; // Texture shouldn't be filtered since it will make previewing really blurry FilterMode prevMode = texture.filterMode; texture.filterMode = FilterMode.Point; LightmapVisualizationUtility.DrawTextureWithUVOverlay(texture, (m_ShowUVOverlay && IsActiveGameObjectInLightmap(textureType)) ? Selection.activeGameObject : null, m_ShowUVOverlay ? m_CachedTextureObjects : new GameObject[] {}, drawableArea, textureRect, textureType, exposure); texture.filterMode = prevMode; } } break; } m_ZoomablePreview.EndViewGUI(); }
/// <inheritdoc /> public override void Draw() { var style = Style.Current; var mediaBackground = _timeline.MediaBackground; var tracks = _timeline.Tracks; var linesColor = style.BackgroundNormal; var areaLeft = -X; var areaRight = Parent.Width + mediaBackground.ControlsBounds.BottomRight.X; var height = Height; var leftSideMin = PointFromParent(Vector2.Zero); var leftSideMax = BottomLeft; var rightSideMin = UpperRight; var rightSideMax = PointFromParent(Parent.BottomRight) + mediaBackground.ControlsBounds.BottomRight; // Draw lines between tracks Render2D.DrawLine(new Vector2(areaLeft, 0.5f), new Vector2(areaRight, 0.5f), linesColor); for (int i = 0; i < tracks.Count; i++) { var track = tracks[i]; if (track.Visible) { var top = track.Bottom + 0.5f; Render2D.DrawLine(new Vector2(areaLeft, top), new Vector2(areaRight, top), linesColor); } } // Highlight selected tracks for (int i = 0; i < tracks.Count; i++) { var track = tracks[i]; if (track.Visible && _timeline.SelectedTracks.Contains(track) && _timeline.ContainsFocus) { Render2D.FillRectangle(new Rectangle(areaLeft, track.Top, areaRight, track.Height), style.BackgroundSelected); } } // Setup time axis ticks int minDistanceBetweenTicks = 4000; int maxDistanceBetweenTicks = 6000; var zoom = Timeline.UnitsPerSecond * _timeline.Zoom; var left = Vector2.Min(leftSideMin, rightSideMax).X; var right = Vector2.Max(leftSideMin, rightSideMax).X; var pixelRange = (right - left) * zoom; var leftFrame = Mathf.Floor((left - Timeline.StartOffset) / zoom) * _timeline.FramesPerSecond; var rightFrame = Mathf.Ceil((right - Timeline.StartOffset) / zoom) * _timeline.FramesPerSecond; var min = leftFrame; var max = rightFrame; var range = max - min; int smallestTick = 0; int biggestTick = _tickSteps.Length - 1; for (int i = _tickSteps.Length - 1; i >= 0; i--) { // Calculate how far apart these modulo tick steps are spaced float tickSpacing = _tickSteps[i] * pixelRange / range; // Calculate the strength of the tick markers based on the spacing _tickStrengths[i] = Mathf.Saturate((tickSpacing - minDistanceBetweenTicks) / (maxDistanceBetweenTicks - minDistanceBetweenTicks)); // Beyond threshold the ticks don't get any bigger or fatter if (_tickStrengths[i] >= 1) { biggestTick = i; } // Do not show small tick markers if (tickSpacing <= minDistanceBetweenTicks) { smallestTick = i; break; } } int tickLevels = biggestTick - smallestTick + 1; // Draw vertical lines for time axis for (int level = 0; level < tickLevels; level++) { float strength = _tickStrengths[smallestTick + level]; if (strength <= Mathf.Epsilon) { continue; } // Draw all ticks int l = Mathf.Clamp(smallestTick + level, 0, _tickSteps.Length - 1); int startTick = Mathf.FloorToInt(min / _tickSteps[l]); int endTick = Mathf.CeilToInt(max / _tickSteps[l]); Color lineColor = style.ForegroundDisabled.RGBMultiplied(0.7f).AlphaMultiplied(strength); for (int i = startTick; i <= endTick; i++) { if (l < biggestTick && (i % Mathf.RoundToInt(_tickSteps[l + 1] / _tickSteps[l]) == 0)) { continue; } var tick = i * _tickSteps[l]; var time = tick / _timeline.FramesPerSecond; var x = time * zoom + Timeline.StartOffset; // Draw line Render2D.FillRectangle(new Rectangle(x - 0.5f, 0, 1.0f, height), lineColor); } } DrawChildren(); // Disabled overlay for (int i = 0; i < tracks.Count; i++) { var track = tracks[i]; if (track.DrawDisabled && track.IsExpandedAll) { Render2D.FillRectangle(new Rectangle(areaLeft, track.Top, areaRight, track.Height), new Color(0, 0, 0, 100)); } } // Darken area outside the duration var outsideDurationAreaColor = new Color(0, 0, 0, 100); Render2D.FillRectangle(new Rectangle(leftSideMin, leftSideMax.X - leftSideMin.X, height), outsideDurationAreaColor); Render2D.FillRectangle(new Rectangle(rightSideMin, rightSideMax.X - rightSideMin.X, height), outsideDurationAreaColor); // Draw time axis header var timeAxisHeaderOffset = -_timeline.MediaBackground.ViewOffset.Y; var verticalLinesHeaderExtend = Timeline.HeaderTopAreaHeight * 0.5f; var timeShowMode = _timeline.TimeShowMode; Render2D.FillRectangle(new Rectangle(areaLeft, timeAxisHeaderOffset - Timeline.HeaderTopAreaHeight, areaRight - areaLeft, Timeline.HeaderTopAreaHeight), style.Background.RGBMultiplied(0.7f)); for (int level = 0; level < tickLevels; level++) { float strength = _tickStrengths[smallestTick + level]; if (strength <= Mathf.Epsilon) { continue; } // Draw all ticks int l = Mathf.Clamp(smallestTick + level, 0, _tickSteps.Length - 1); int startTick = Mathf.FloorToInt(min / _tickSteps[l]); int endTick = Mathf.CeilToInt(max / _tickSteps[l]); Color lineColor = style.Foreground.RGBMultiplied(0.8f).AlphaMultiplied(strength); Color labelColor = style.ForegroundDisabled.AlphaMultiplied(strength); for (int i = startTick; i <= endTick; i++) { if (l < biggestTick && (i % Mathf.RoundToInt(_tickSteps[l + 1] / _tickSteps[l]) == 0)) { continue; } var tick = i * _tickSteps[l]; var time = tick / _timeline.FramesPerSecond; var x = time * zoom + Timeline.StartOffset; // Header line var lineRect = new Rectangle(x - 0.5f, -verticalLinesHeaderExtend + timeAxisHeaderOffset, 1.0f, verticalLinesHeaderExtend); Render2D.FillRectangle(lineRect, lineColor); // Time label string labelText; switch (timeShowMode) { case Timeline.TimeShowModes.Frames: labelText = tick.ToString("0000"); break; case Timeline.TimeShowModes.Seconds: labelText = time.ToString("###0.##'s'", CultureInfo.InvariantCulture); break; case Timeline.TimeShowModes.Time: labelText = TimeSpan.FromSeconds(time).ToString("g"); break; default: throw new ArgumentOutOfRangeException(); } var labelRect = new Rectangle(x + 2, -verticalLinesHeaderExtend + timeAxisHeaderOffset, 50, verticalLinesHeaderExtend); Render2D.DrawText( style.FontSmall, labelText, labelRect, labelColor, TextAlignment.Near, TextAlignment.Center, TextWrapping.NoWrap, 1.0f, 0.8f ); } } }
/// <summary> /// Combine two AABBs into this one. /// </summary> /// <param name="aabb1">The aabb1.</param> /// <param name="aabb2">The aabb2.</param> public void Combine(ref AABB aabb1, ref AABB aabb2) { LowerBound = Vector2.Min(aabb1.LowerBound, aabb2.LowerBound); UpperBound = Vector2.Max(aabb1.UpperBound, aabb2.UpperBound); }
private void TryConnect(Box startBox, Box endBox) { if (startBox == null || endBox == null) { if (IsConnecting) { ConnectingEnd(null); } return; } // If the user is patiently waiting for his box to get connected to the newly created one fulfill his wish! _connectionInstigator = startBox; if (!IsConnecting) { ConnectingStart(startBox); } ConnectingEnd(endBox); // Smart-Select next box /* * Output and Output => undefined * Output and Input => Connect and move to next on input-node * Input and Output => Connect and move to next on input-node * Input and Input => undefined, cannot happen */ Box inputBox = endBox.IsOutput ? startBox : endBox; Box nextBox = inputBox.ParentNode.GetNextBox(inputBox); // If we are going backwards and the end-node has an input box we want to edit backwards if (!startBox.IsOutput) { Box endNodeInputBox = endBox.ParentNode.GetBoxes().DefaultIfEmpty(null).FirstOrDefault(b => !b.IsOutput); if (endNodeInputBox != null) { nextBox = endNodeInputBox; } } // TODO: What if we reached the end (nextBox == null)? Do we travel along the nodes? /* * while (nextBox == null && _inputBoxStack.Count > 0) * { * // We found the last box on this node but there are still boxes on previous nodes on the stack * nextBox = GetNextBox(_inputBoxStack.Pop()); * } */ if (nextBox != null) { Select(nextBox.ParentNode); nextBox.ParentNode.SelectBox(nextBox); Vector2 padding = new Vector2(20); Vector2 delta = Vector2.Min(_rootControl.PointToParent(nextBox.ParentNode.Location) - padding, Vector2.Zero) + Vector2.Max((_rootControl.PointToParent(nextBox.ParentNode.BottomRight) + padding) - Size, Vector2.Zero); _rootControl.Location -= delta; } }
void IUpdatable.update() { if (_isPaused) { return; } // prep data for the particle.update method var rootPosition = entity.transform.position + _localOffset; // if the emitter is active and the emission rate is greater than zero then emit particles if (_active && _emitterConfig.emissionRate > 0) { var rate = 1.0f / _emitterConfig.emissionRate; if (_particles.Count < _emitterConfig.maxParticles) { _emitCounter += Time.deltaTime; } while (_emitting && _particles.Count < _emitterConfig.maxParticles && _emitCounter > rate) { addParticle(rootPosition); _emitCounter -= rate; } _elapsedTime += Time.deltaTime; if (_emitterConfig.duration != -1 && _emitterConfig.duration < _elapsedTime) { // when we hit our duration we dont emit any more particles _emitting = false; // once all our particles are done we stop the emitter if (_particles.Count == 0) { stop(); } } } var min = new Vector2(float.MaxValue, float.MaxValue); var max = new Vector2(float.MinValue, float.MinValue); var maxParticleSize = float.MinValue; // loop through all the particles updating their location and color for (var i = _particles.Count - 1; i >= 0; i--) { // get the current particle and update it var currentParticle = _particles[i]; // if update returns true that means the particle is done if (currentParticle.update(_emitterConfig, ref collisionConfig, rootPosition)) { Pool <Particle> .free(currentParticle); _particles.RemoveAt(i); } else { // particle is good. collect min/max positions for the bounds var pos = _emitterConfig.simulateInWorldSpace ? currentParticle.spawnPosition : rootPosition; pos += currentParticle.position; Vector2.Min(ref min, ref pos, out min); Vector2.Max(ref max, ref pos, out max); maxParticleSize = System.Math.Max(maxParticleSize, currentParticle.particleSize); } } _bounds.location = min; _bounds.width = max.X - min.X; _bounds.height = max.Y - min.Y; if (_emitterConfig.subtexture == null) { _bounds.inflate(1 * maxParticleSize, 1 * maxParticleSize); } else { maxParticleSize /= _emitterConfig.subtexture.sourceRect.Width; _bounds.inflate(_emitterConfig.subtexture.sourceRect.Width * maxParticleSize, _emitterConfig.subtexture.sourceRect.Height * maxParticleSize); } }
void RefreshContentScale() { ContentWidget.Scale = RootWidget.Size / Vector2.Max(Vector2.One, ContentWidget.Size); }
public Bounds(Vector2 min, Vector2 max) { this.Min = Vector2.Min(min, max); this.Max = Vector2.Max(min, max); }
//public bool Intersects(Line line) //{ // var b = new AABB() { Min = line.Start, Max = line.End }; // b.Validate(); // return Intersects(b); //} public AABB Clamp(AABB bounds) => new AABB() { Min = Vector2.Max(Min, bounds.Min), Max = Vector2.Min(Max, bounds.Max) };
public void ReserveShadows(Camera camera, HDShadowManager shadowManager, HDShadowInitParameters initParameters, CullingResults cullResults, FrameSettings frameSettings, int lightIndex) { Bounds bounds; float cameraDistance = Vector3.Distance(camera.transform.position, transform.position); #if ENABLE_RAYTRACING m_WillRenderShadows = m_Light.shadows != LightShadows.None && frameSettings.IsEnabled(FrameSettingsField.Shadow) && lightTypeExtent == LightTypeExtent.Punctual; #else m_WillRenderShadows = m_Light.shadows != LightShadows.None && frameSettings.IsEnabled(FrameSettingsField.Shadow) && !IsAreaLight(lightTypeExtent); #endif m_WillRenderShadows &= cullResults.GetShadowCasterBounds(lightIndex, out bounds); // When creating a new light, at the first frame, there is no AdditionalShadowData so we can't really render shadows m_WillRenderShadows &= m_ShadowData != null && m_ShadowData.shadowDimmer > 0; // If the shadow is too far away, we don't render it if (m_ShadowData != null) { m_WillRenderShadows &= m_Light.type == LightType.Directional || cameraDistance < (m_ShadowData.shadowFadeDistance); } if (!m_WillRenderShadows) { return; } // Create shadow requests array using the light type if (shadowRequests == null || m_ShadowRequestIndices == null) { const int maxLightShadowRequestsCount = 6; shadowRequests = new HDShadowRequest[maxLightShadowRequestsCount]; m_ShadowRequestIndices = new int[maxLightShadowRequestsCount]; for (int i = 0; i < maxLightShadowRequestsCount; i++) { shadowRequests[i] = new HDShadowRequest(); } } Vector2 viewportSize = new Vector2(m_ShadowData.shadowResolution, m_ShadowData.shadowResolution); // Compute dynamic shadow resolution if (initParameters.useDynamicViewportRescale && m_Light.type != LightType.Directional) { // resize viewport size by the normalized size of the light on screen // When we will have access to the non screen clamped bounding sphere light size, we could use it to scale the shadow map resolution // For the moment, this will be enough viewportSize *= Mathf.Lerp(64f / viewportSize.x, 1f, m_Light.range / (camera.transform.position - transform.position).magnitude); viewportSize = Vector2.Max(new Vector2(64f, 64f) / viewportSize, viewportSize); // Prevent flickering caused by the floating size of the viewport viewportSize.x = Mathf.Round(viewportSize.x); viewportSize.y = Mathf.Round(viewportSize.y); } viewportSize = Vector2.Max(viewportSize, new Vector2(16, 16)); // Update the directional shadow atlas size if (m_Light.type == LightType.Directional) { shadowManager.UpdateDirectionalShadowResolution((int)viewportSize.x, m_ShadowSettings.cascadeShadowSplitCount); } // Reserver wanted resolution in the shadow atlas bool allowResize = m_Light.type != LightType.Directional; int count = GetShadowRequestCount(); for (int index = 0; index < count; index++) { m_ShadowRequestIndices[index] = shadowManager.ReserveShadowResolutions(viewportSize, allowResize); } }
public AABB Combine(AABB target) => new AABB() { Min = Vector2.Min(Min, target.Min), Max = Vector2.Max(Max, target.Max) };
public static Vector2 Clamp(Vector2 a, Vector2 low, Vector2 high) { return(Vector2.Max(low, Vector2.Min(a, high))); }
public scBoundingBox getBoundingBox(scTransform transform) { var lower = new Vector2(); var upper = new Vector2(); var rotated = new Vector2[4]; rotated[0] = transform.position + vertices[0].Rotate(transform.rotation.radians); rotated[1] = transform.position + vertices[1].Rotate(transform.rotation.radians); rotated[2] = transform.position + vertices[2].Rotate(transform.rotation.radians); rotated[3] = transform.position + vertices[3].Rotate(transform.rotation.radians); lower.X = rotated.Min(v => v.X); lower.Y = rotated.Min(v => v.Y); upper.X = rotated.Max(v => v.X); upper.Y = rotated.Max(v => v.Y); return scBoundingUtils.createFromBoundingVertices(lower, upper); }