Exemplo n.º 1
0
        /// <summary>
        /// Handle points interation
        /// </summary>
        /// <param name="selected">Selected point</param>
        /// <param name="contents">Available poinst for selection</param>
        /// <param name="selectable">Are points can be selected</param>
        /// <returns></returns>
        public static int PointsHandle(int selected, SplineContent[] contents, bool selectable)
        {
            var           current = Handles.color;
            int           controlId = GUIUtility.GetControlID(PointSelectionHash, FocusType.Passive);
            int           i, n = contents.Length;
            SplineContent content;

            switch (Event.current.GetTypeForControl(controlId))
            {
            case EventType.MouseDown:
                selected = Array.FindIndex(contents, c => c.InternalHash == HandleUtility.nearestControl);
                if (selected < 0 || Event.current.button != 0)
                {
                    break;
                }
                GUIUtility.hotControl = controlId;
                GUI.changed           = true;
                EditorGUIUtility.SetWantsMouseJumping(1);
                Event.current.Use();
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlId)
                {
                    GUIUtility.hotControl = 0;
                    EditorGUIUtility.SetWantsMouseJumping(0);
                    Event.current.Use();
                }
                break;

            case EventType.Layout:
                if (!selectable)
                {
                    break;
                }
                for (i = 0; i < n; i++)
                {
                    content = contents[i];
                    HandleUtility.AddControl(content.InternalHash,
                                             HandleUtility.DistanceToCircle(content.P0, 0.16F));
                }
                break;

            case EventType.Repaint:
                for (i = 0; i < n; i++)
                {
                    content = contents[i];
                    if ((content.Info & PointInfo.Control) == PointInfo.Control)
                    {
                        Handles.color = SPSettings.Current.Normals;
                    }
                    if (selected == i)
                    {
                        Handles.color = SPSettings.Current.Selection;
                    }
                    Handles.DotHandleCap(content.InternalHash, content.P0, Quaternion.identity,
                                         SPSettings.Current.ControlSize, EventType.Repaint);
                    Handles.color = current;
                }
                break;
            }
            //Clean
            Handles.color = current;
            return(selected);
        }
        protected override void OnSceneGUI()
        {
            base.OnSceneGUI();

            // We skip the first point as it should always remain at the GameObject's local origin (Pose.ZeroIdentity)
            for (int i = 1; i < controlPoints?.arraySize; i++)
            {
                bool isTangentHandle = i % 3 != 0;

                serializedObject.Update();

                bool isLastPoint = i == controlPoints.arraySize - 1;

                var controlPointPosition = LineData.GetPoint(i);
                var controlPointProperty = controlPoints.GetArrayElementAtIndex(i);
                var controlPointRotation = controlPointProperty.FindPropertyRelative("rotation");

                // Draw our tangent lines
                Handles.color = Color.gray;
                if (i == 1)
                {
                    Handles.DrawLine(LineData.GetPoint(0), LineData.GetPoint(1));
                }
                else if (!isTangentHandle)
                {
                    Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i - 1));

                    if (!isLastPoint)
                    {
                        Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i + 1));
                    }
                }

                Handles.color = isTangentHandle ? Color.white : Color.green;
                float handleSize = HandleUtility.GetHandleSize(controlPointPosition);

                if (Handles.Button(controlPointPosition, controlPointRotation.quaternionValue, handleSize * HandleSizeModifier, handleSize * PickSizeModifier, Handles.DotHandleCap))
                {
                    selectedHandleIndex = i;
                }

                // Draw our handles
                if (Tools.current == Tool.Move && selectedHandleIndex == i)
                {
                    EditorGUI.BeginChangeCheck();

                    var newTargetPosition = Handles.PositionHandle(controlPointPosition, controlPointRotation.quaternionValue);

                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(LineData, "Change Spline Point Position");
                        LineData.SetPoint(i, newTargetPosition);
                    }

                    if (isLastPoint)
                    {
                        DrawSceneControlOptionButtons(controlPointPosition);
                    }
                }
                else if (Tools.current == Tool.Rotate && selectedHandleIndex == i)
                {
                    EditorGUI.BeginChangeCheck();
                    Quaternion newTargetRotation = Handles.RotationHandle(controlPointRotation.quaternionValue, controlPointPosition);

                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(LineData, "Change Spline Point Rotation");
                        controlPointRotation.quaternionValue = newTargetRotation;
                    }
                }

                serializedObject.ApplyModifiedProperties();
            }

            // Check for overlapping points
            OverlappingPointIndexes.Clear();

            for (int i = 0; i < splineData.ControlPoints.Length; i++)
            {
                for (int j = 0; j < splineData.ControlPoints.Length; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    if (Vector3.Distance(splineData.ControlPoints[i].Position, splineData.ControlPoints[j].Position) < OverlappingPointThreshold)
                    {
                        if (i != 0)
                        {
                            OverlappingPointIndexes.Add(i);
                        }

                        if (j != 0)
                        {
                            OverlappingPointIndexes.Add(j);
                        }

                        break;
                    }
                }
            }
        }
Exemplo n.º 3
0
    //SceneView Input manager
    void OnSceneGUI(SceneView sceneView)
    {
        if (!editor_enable)
        {
            return;
        }

        HandleUtility.AddDefaultControl(0); //Disable engine input

        //Shortcuts
        Event e = Event.current;

        //Paint (B)
        if (e.keyCode == KeyCode.B && e.type == EventType.keyDown)
        {
            tool = Tools.PAINT;
            UpdateToolCheck();
            Repaint();
        }

        //Erase (E)
        if (e.keyCode == KeyCode.E && e.type == EventType.keyDown)
        {
            tool = Tools.ERASE;
            UpdateToolCheck();
            Repaint();
        }

        //Rect (R)
        if (e.keyCode == KeyCode.R && e.type == EventType.keyDown)
        {
            tool = Tools.RECT;
            UpdateToolCheck();
            Repaint();
        }

        if (e.keyCode == KeyCode.I && e.type == EventType.keyDown)
        {
            tool = Tools.DROPPER;
            UpdateToolCheck();
            Repaint();
        }

        //Paint or Erase
        if (paint_enable || erase_enable)
        {
            //Continuous Painting
            if ((e.type == EventType.mouseDown || e.type == EventType.mouseDrag) && e.button == 0 && e.alt == false && brush_obj.continuous_painting)
            {
                if (paint_enable)
                {
                    CreateObject(e);
                }

                if (erase_enable)
                {
                    EraseObject(e);
                }
            }

            //Only one paint by click
            if (brush_obj.continuous_painting == false && e.button == 0 && e.type == EventType.mouseUp && e.alt == false)
            {
                if (paint_enable)
                {
                    CreateObject(e);
                }
                if (erase_enable)
                {
                    EraseObject(e);
                }
            }
        }

        //Draw Rect
        if (rect_enable)
        {
            RectTool(e);
        }

        //Dropper
        if (dropper_enable)
        {
            if (e.type == EventType.mouseDown && e.button == 0 && e.alt == false)
            {
                DropperTool(e);
            }
        }
    }
Exemplo n.º 4
0
    void DrawUnselectedKnots()
    {
        for (int i = 0; i < spline.KnotCount; i++)
        {
            if (selectedKnots.Contains(i))
            {
                continue;
            }
            Bezier3DSpline.Knot knot = spline.GetKnot(i);

            Vector3 knotWorldPos = spline.transform.TransformPoint(knot.position);
            if (knot.orientation.HasValue)
            {
                Handles.color = Handles.yAxisColor;
                Quaternion rot = spline.transform.rotation * knot.orientation.Value;
                Handles.ArrowHandleCap(0, knotWorldPos, rot * Quaternion.AngleAxis(90, Vector3.left), 0.15f, EventType.Repaint);
            }
            Handles.color = Color.white;
            if (Handles.Button(knotWorldPos, Camera.current.transform.rotation, HandleUtility.GetHandleSize(knotWorldPos) * handleSize, HandleUtility.GetHandleSize(knotWorldPos) * handleSize, Handles.CircleHandleCap))
            {
                SelectKnot(i, Event.current.control);
            }
        }
    }
Exemplo n.º 5
0
    void DrawSelectedSplitters()
    {
        Handles.color = Color.white;
        //Start add
        if (!spline.closed && activeKnot == 0)
        {
            Bezier3DCurve curve = spline.GetCurve(0);
            Vector3
                a = spline.transform.TransformPoint(curve.a),
                b = spline.transform.TransformDirection(curve.b.normalized) * 2f;

            float handleScale = HandleUtility.GetHandleSize(a);
            b *= handleScale;
            Handles.DrawDottedLine(a, a - b, 3f);
            if (Handles.Button(a - b, Camera.current.transform.rotation, handleScale * handleSize * 0.4f, handleScale * handleSize * 0.4f, Handles.DotHandleCap))
            {
                Undo.RecordObject(spline, "Add Bezier Point");
                Bezier3DSpline.Knot knot = spline.GetKnot(activeKnot);
                spline.InsertKnot(0, new Bezier3DSpline.Knot(curve.a - (curve.b.normalized * handleScale * 2), Vector3.zero, curve.b.normalized * 0.5f, knot.auto, knot.orientation));
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
        }

        //End add
        if (!spline.closed && activeKnot == spline.CurveCount)
        {
            Bezier3DCurve curve = spline.GetCurve(spline.CurveCount - 1);
            Vector3
                c             = spline.transform.TransformDirection(curve.c.normalized) * 2f,
                d             = spline.transform.TransformPoint(curve.d);
            float handleScale = HandleUtility.GetHandleSize(d);
            c *= handleScale;
            Handles.DrawDottedLine(d, d - c, 3f);
            if (Handles.Button(d - c, Camera.current.transform.rotation, handleScale * handleSize * 0.4f, handleScale * handleSize * 0.4f, Handles.DotHandleCap))
            {
                Undo.RecordObject(spline, "Add Bezier Point");
                Bezier3DSpline.Knot knot = spline.GetKnot(activeKnot);
                spline.AddKnot(new Bezier3DSpline.Knot(curve.d - (curve.c.normalized * handleScale * 2), curve.c.normalized * 0.5f, Vector3.zero, knot.auto, knot.orientation));
                SelectKnot(spline.CurveCount, false);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
        }

        // Prev split
        if (spline.closed || activeKnot != 0)
        {
            Bezier3DCurve curve       = spline.GetCurve(activeKnot == 0 ? spline.CurveCount - 1 : activeKnot - 1);
            Vector3       centerLocal = curve.GetPoint(curve.Dist2Time(curve.length * 0.5f));
            Vector3       center      = spline.transform.TransformPoint(centerLocal);

            Vector3 a           = curve.a + curve.b;
            Vector3 b           = curve.c + curve.d;
            Vector3 ab          = (b - a) * 0.3f;
            float   handleScale = HandleUtility.GetHandleSize(center);

            if (Handles.Button(center, Camera.current.transform.rotation, handleScale * handleSize * 0.4f, handleScale * handleSize * 0.4f, Handles.DotHandleCap))
            {
                Undo.RecordObject(spline, "Add Bezier Point");
                Bezier3DSpline.Knot knot = spline.GetKnot(activeKnot);
                spline.InsertKnot(activeKnot == 0 ? spline.CurveCount : activeKnot, new Bezier3DSpline.Knot(centerLocal, -ab, ab, knot.auto, knot.orientation));
                if (activeKnot == 0)
                {
                    SelectKnot(spline.CurveCount - 1, false);
                }
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
        }

        // Next split
        if (activeKnot != spline.CurveCount)
        {
            Bezier3DCurve curve       = spline.GetCurve(activeKnot);
            Vector3       centerLocal = curve.GetPoint(curve.Dist2Time(curve.length * 0.5f));
            Vector3       center      = spline.transform.TransformPoint(centerLocal);

            Vector3 a           = curve.a + curve.b;
            Vector3 b           = curve.c + curve.d;
            Vector3 ab          = (b - a) * 0.3f;
            float   handleScale = HandleUtility.GetHandleSize(center);
            if (Handles.Button(center, Camera.current.transform.rotation, handleScale * handleSize * 0.4f, handleScale * handleSize * 0.4f, Handles.DotHandleCap))
            {
                Undo.RecordObject(spline, "Add Bezier Point");
                spline.InsertKnot(activeKnot + 1, new Bezier3DSpline.Knot(centerLocal, -ab, ab));
                SelectKnot(activeKnot + 1, false);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
        }
    }
Exemplo n.º 6
0
        void ProcessBezierPathInput(Event e)
        {
            // Find which handle mouse is over. Start by looking at previous handle index first, as most likely to still be closest to mouse
            int previousMouseOverHandleIndex = (mouseOverHandleIndex == -1) ? 0 : mouseOverHandleIndex;

            mouseOverHandleIndex = -1;
            for (int i = 0; i < bezierPath.NumPoints; i += 3)
            {
                int     handleIndex     = (previousMouseOverHandleIndex + i) % bezierPath.NumPoints;
                float   handleRaDefeses = GetHandleDiameter(globalDisplaySettings.anchorSize * data.bezierHandleScale, bezierPath[handleIndex]) / 2f;
                Vector3 pos             = MathUtility.TransformPoint(bezierPath[handleIndex], creator.transform, bezierPath.Space);
                float   dst             = HandleUtility.DistanceToCircle(pos, handleRaDefeses);
                if (dst == 0)
                {
                    mouseOverHandleIndex = handleIndex;
                    break;
                }
            }

            // Shift-left click (when mouse not over a handle) to split or add segment
            if (mouseOverHandleIndex == -1)
            {
                if (e.type == EventType.MouseDown && e.button == 0 && e.shift)
                {
                    UpdatePathMouseInfo();
                    // Insert point along selected segment
                    if (selectedSegmentIndex != -1 && selectedSegmentIndex < bezierPath.NumSegments)
                    {
                        Vector3 newPathPoint = pathMouseInfo.closestWorldPointToMouse;
                        newPathPoint = MathUtility.InverseTransformPoint(newPathPoint, creator.transform, bezierPath.Space);
                        Undo.RecordObject(creator, "Split segment");
                        bezierPath.SplitSegment(newPathPoint, selectedSegmentIndex, pathMouseInfo.timeOnBezierSegment);
                    }
                    // If path is not a closed loop, add new point on to the end of the path
                    else if (!bezierPath.IsClosed)
                    {
                        // insert new point at same dst from scene camera as the point that comes before it (for a 3d path)
                        float   dstCamToEndpoint = (Camera.current.transform.position - bezierPath[bezierPath.NumPoints - 1]).magnitude;
                        Vector3 newPathPoint     = MouseUtility.GetMouseWorldPosition(bezierPath.Space, dstCamToEndpoint);
                        newPathPoint = MathUtility.InverseTransformPoint(newPathPoint, creator.transform, bezierPath.Space);

                        Undo.RecordObject(creator, "Add segment");
                        if (e.control || e.command)
                        {
                            bezierPath.AddSegmentToStart(newPathPoint);
                        }
                        else
                        {
                            bezierPath.AddSegmentToEnd(newPathPoint);
                        }
                    }
                }
            }

            // Control click or backspace/delete to remove point
            if (e.keyCode == KeyCode.Backspace || e.keyCode == KeyCode.Delete || ((e.control || e.command) && e.type == EventType.MouseDown && e.button == 0))
            {
                if (mouseOverHandleIndex != -1)
                {
                    Undo.RecordObject(creator, "Delete segment");
                    bezierPath.DeleteSegment(mouseOverHandleIndex);
                    if (mouseOverHandleIndex == handleIndexToDisplayAsTransform)
                    {
                        handleIndexToDisplayAsTransform = -1;
                    }
                    mouseOverHandleIndex = -1;
                    Repaint();
                }
            }

            // Holding shift and moving mouse (but mouse not over a handle/dragging a handle)
            if (draggingHandleIndex == -1 && mouseOverHandleIndex == -1)
            {
                bool shiftDown = e.shift && !shiftLastFrame;
                if (shiftDown || ((e.type == EventType.MouseMove || e.type == EventType.MouseDrag) && e.shift))
                {
                    UpdatePathMouseInfo();

                    if (pathMouseInfo.mouseDstToLine < segmentSelectDistanceThreshold)
                    {
                        if (pathMouseInfo.closestSegmentIndex != selectedSegmentIndex)
                        {
                            selectedSegmentIndex = pathMouseInfo.closestSegmentIndex;
                            HandleUtility.Repaint();
                        }
                    }
                    else
                    {
                        selectedSegmentIndex = -1;
                        HandleUtility.Repaint();
                    }
                }
            }

            shiftLastFrame = e.shift;
        }
Exemplo n.º 7
0
        protected override void InsertMode(Vector3 screenCoordinates)
        {
            base.InsertMode(screenCoordinates);
            double percent = ProjectScreenSpace(screenCoordinates);

            editor.evaluate(percent, evalResult);
            if (editor.eventModule.mouseRight)
            {
                SplineEditorHandles.DrawCircle(evalResult.position, Quaternion.LookRotation(editorCamera.transform.position - evalResult.position), HandleUtility.GetHandleSize(evalResult.position) * 0.2f);
                return;
            }
            if (SplineEditorHandles.CircleButton(evalResult.position, Quaternion.LookRotation(editorCamera.transform.position - evalResult.position), HandleUtility.GetHandleSize(evalResult.position) * 0.2f, 1.5f, color))
            {
                RecordUndo("Create Point");
                SplinePoint newPoint = new SplinePoint(evalResult.position, evalResult.position);
                newPoint.size   = evalResult.size;
                newPoint.color  = evalResult.color;
                newPoint.normal = evalResult.up;
                SplinePoint[] newPoints  = new SplinePoint[points.Length + 1];
                double        floatIndex = (points.Length - 1) * percent;
                int           pointIndex = Mathf.Clamp(DMath.FloorInt(floatIndex), 0, points.Length - 2);
                for (int i = 0; i < newPoints.Length; i++)
                {
                    if (i <= pointIndex)
                    {
                        newPoints[i] = points[i];
                    }
                    else if (i == pointIndex + 1)
                    {
                        newPoints[i] = newPoint;
                    }
                    else
                    {
                        newPoints[i] = points[i - 1];
                    }
                }
                SplineComputer spline = dsEditor.spline;
                points      = newPoints;
                lastCreated = points.Length - 1;
                dsEditor.UpdateSpline();
                spline.ShiftNodes(pointIndex + 1, spline.pointCount - 1, 1);
                if (createNode)
                {
                    CreateNodeForPoint(pointIndex + 1);
                }
            }
        }
Exemplo n.º 8
0
    private void DrawSplineInfo(Spline spline)
    {
        if (Event.current.alt && !Event.current.shift)
        {
            foreach (SplineNode splineNode in spline.SplineNodes)
            {
                Handles.Label(LabelPosition2D(splineNode.Position, -0.2f), splineNode.name, sceneGUIStyle);
            }

            foreach (SplineSegment segment in spline.SplineSegments)
            {
                for (int i = 0; i < 10; i++)
                {
                    float splineParam = segment.ConvertSegmentToSplineParamter(i / 10f);

                    Vector3 position = spline.GetPositionOnSpline(splineParam);
                    Vector3 normal   = spline.GetNormalToSpline(splineParam);

                    Handles.color = new Color(.3f, 1f, .20f, 0.75f);
                    Handles.ArrowCap(0, position, Quaternion.LookRotation(normal), HandleUtility.GetHandleSize(position) * 0.5f);
                }
            }

            Vector3 tangentPosition0 = spline.GetPositionOnSpline(0);

            Handles.color = new Color(.2f, 0.4f, 1f, 1);
            Handles.ArrowCap(0, tangentPosition0, Quaternion.LookRotation(spline.GetTangentToSpline(0)), HandleUtility.GetHandleSize(tangentPosition0) * 0.5f);

            Vector3 tangentPosition1 = spline.GetPositionOnSpline(1);
            Handles.ArrowCap(0, tangentPosition1, Quaternion.LookRotation(spline.GetTangentToSpline(1)), HandleUtility.GetHandleSize(tangentPosition1) * 0.5f);
        }
        else if (Event.current.alt && Event.current.shift)
        {
            foreach (SplineSegment item in spline.SplineSegments)
            {
                Vector3 positionOnSpline = spline.GetPositionOnSpline(item.ConvertSegmentToSplineParamter(0.5f));

                Handles.Label(LabelPosition2D(positionOnSpline, -0.2f), item.Length.ToString( ), sceneGUIStyle);
            }

            Handles.Label(LabelPosition2D(spline.transform.position, -0.3f), "Length: " + spline.Length.ToString( ), sceneGUIStyle);
        }
    }
Exemplo n.º 9
0
 private Vector3 LabelPosition2D(Vector3 position, float offset)
 {
     return(position - Camera.current.transform.up * HandleUtility.GetHandleSize(position) * offset);
 }
Exemplo n.º 10
0
        public static void OnSceneGUI(SceneView sceneview)
        {
            for (int i = 0; i < s_Bones.Count; i++)
            {
                Bone2D bone = s_Bones[i];

                if (bone && IsVisible(bone))
                {
                    int       controlID = GUIUtility.GetControlID("BoneHandle".GetHashCode(), FocusType.Passive);
                    EventType eventType = Event.current.GetTypeForControl(controlID);

                    if (!IsLocked(bone))
                    {
                        if (eventType == EventType.MouseDown)
                        {
                            if (HandleUtility.nearestControl == controlID &&
                                Event.current.button == 0)
                            {
                                GUIUtility.hotControl = controlID;
                                Event.current.Use();
                            }
                        }

                        if (eventType == EventType.MouseUp)
                        {
                            if (GUIUtility.hotControl == controlID &&
                                Event.current.button == 0)
                            {
                                if (EditorGUI.actionKey)
                                {
                                    List <Object> objects = new List <Object>(Selection.objects);
                                    objects.Add(bone.gameObject);
                                    Selection.objects = objects.ToArray();
                                }
                                else
                                {
                                    Selection.activeObject = bone;
                                }

                                GUIUtility.hotControl = 0;
                                Event.current.Use();
                            }
                        }

                        if (eventType == EventType.MouseDrag)
                        {
                            if (GUIUtility.hotControl == controlID &&
                                Event.current.button == 0)
                            {
                                Handles.matrix = bone.transform.localToWorldMatrix;
                                Vector3 position = HandlesExtra.GUIToWorld(Event.current.mousePosition);

                                BoneUtils.OrientToLocalPosition(bone, position, Event.current.shift, "Rotate", true);

                                EditorUpdater.SetDirty("Rotate");

                                GUI.changed = true;
                                Event.current.Use();
                            }
                        }
                    }

                    if (eventType == EventType.Repaint)
                    {
                        if ((HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0) ||
                            GUIUtility.hotControl == controlID ||
                            Selection.gameObjects.Contains(bone.gameObject))
                        {
                            Color color = Color.yellow;

                            float outlineSize = HandleUtility.GetHandleSize(bone.transform.position) * 0.015f * bone.color.a;
                            BoneUtils.DrawBoneOutline(bone, outlineSize, color);

                            Bone2D outlineBone = bone.child;
                            color.a *= 0.5f;

                            while (outlineBone)
                            {
                                if (Selection.gameObjects.Contains(outlineBone.gameObject))
                                {
                                    outlineBone = null;
                                }
                                else
                                {
                                    if (outlineBone.color.a == 0f)
                                    {
                                        outlineSize = HandleUtility.GetHandleSize(outlineBone.transform.position) * 0.015f * outlineBone.color.a;
                                        BoneUtils.DrawBoneOutline(outlineBone, outlineSize, color);
                                        outlineBone = outlineBone.child;
                                        color.a    *= 0.5f;
                                    }
                                    else
                                    {
                                        outlineBone = null;
                                    }
                                }
                            }
                        }

                        if (bone.parentBone && !bone.linkedParentBone)
                        {
                            Color color = bone.color;
                            color.a       *= 0.25f;
                            Handles.matrix = Matrix4x4.identity;
                            BoneUtils.DrawBoneBody(bone.transform.position, bone.parentBone.transform.position, BoneUtils.GetBoneRadius(bone), color);
                        }

                        BoneUtils.DrawBoneBody(bone);

                        Color innerColor = bone.color * 0.25f;

                        if (bone.attachedIK && bone.attachedIK.isActiveAndEnabled)
                        {
                            innerColor = new Color(0f, 0.75f, 0.75f, 1f);
                        }

                        innerColor.a = bone.color.a;

                        BoneUtils.DrawBoneCap(bone, innerColor);
                    }

                    if (!IsLocked(bone) && eventType == EventType.Layout)
                    {
                        HandleUtility.AddControl(controlID, HandleUtility.DistanceToLine(bone.transform.position, bone.endPosition));
                    }
                }
            }

            foreach (Control control in s_Controls)
            {
                if (control && control.isActiveAndEnabled && IsVisible(control.gameObject))
                {
                    Transform transform = control.transform;

                    if (Selection.activeTransform != transform)
                    {
                        if (!control.bone ||
                            (control.bone && !Selection.transforms.Contains(control.bone.transform)))
                        {
                            Handles.matrix = Matrix4x4.identity;
                            Handles.color  = control.color;

                            if (Tools.current == Tool.Move)
                            {
                                EditorGUI.BeginChangeCheck();

                                Quaternion cameraRotation = Camera.current.transform.rotation;

                                if (Event.current.type == EventType.Repaint)
                                {
                                    Camera.current.transform.rotation = transform.rotation;
                                }

                                float size = HandleUtility.GetHandleSize(transform.position) / 5f;
                                //Handles.DrawLine(transform.position + transform.rotation * new Vector3(size,0f,0f), transform.position + transform.rotation * new Vector3(-size,0f,0f));
                                //Handles.DrawLine(transform.position + transform.rotation * new Vector3(0f,size,0f), transform.position + transform.rotation * new Vector3(0f,-size,0f));

                                bool guiEnabled = GUI.enabled;
                                GUI.enabled = !IsLocked(control.gameObject);

#if UNITY_5_6_OR_NEWER
                                Vector3 newPosition = Handles.FreeMoveHandle(transform.position, transform.rotation, size, Vector3.zero, Handles.RectangleHandleCap);
#else
                                Vector3 newPosition = Handles.FreeMoveHandle(transform.position, transform.rotation, size, Vector3.zero, Handles.RectangleCap);
#endif

                                GUI.enabled = guiEnabled;

                                if (Event.current.type == EventType.Repaint)
                                {
                                    Camera.current.transform.rotation = cameraRotation;
                                }

                                if (EditorGUI.EndChangeCheck())
                                {
                                    Undo.RecordObject(transform, "Move");
                                    transform.position = newPosition;

                                    if (control.bone)
                                    {
                                        Undo.RecordObject(control.bone.transform, "Move");

                                        control.bone.transform.position = newPosition;

                                        BoneUtils.OrientToChild(control.bone.parentBone, Event.current.shift, "Move", true);

                                        EditorUpdater.SetDirty("Move");
                                    }
                                }
                            }
                            else if (Tools.current == Tool.Rotate)
                            {
                                EditorGUI.BeginChangeCheck();

                                float size = HandleUtility.GetHandleSize(transform.position) * 0.5f;
                                //Handles.DrawLine(transform.position + transform.rotation * new Vector3(size,0f,0f), transform.position + transform.rotation * new Vector3(-size,0f,0f));
                                //Handles.DrawLine(transform.position + transform.rotation * new Vector3(0f,size,0f), transform.position + transform.rotation * new Vector3(0f,-size,0f));

                                bool guiEnabled = GUI.enabled;
                                GUI.enabled = !IsLocked(control.gameObject);

                                Quaternion newRotation = Handles.Disc(transform.rotation, transform.position, transform.forward, size, false, 0f);

                                GUI.enabled = guiEnabled;

                                if (EditorGUI.EndChangeCheck())
                                {
                                    Undo.RecordObject(transform, "Rotate");
                                    transform.rotation = newRotation;

                                    if (control.bone)
                                    {
                                        Undo.RecordObject(control.bone.transform, "Rotate");

                                        control.bone.transform.rotation = newRotation;

                                        EditorUpdater.SetDirty("Rotate");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
    private void DrawHandles(Spline spline)
    {
        if (Event.current.alt || EditorGUI.actionKey)
        {
            return;
        }

        if (Tools.current == Tool.None || Tools.current == Tool.View)
        {
            return;
        }

        Handles.lighting = true;

        foreach (SplineNode node in spline.SplineNodes)
        {
            switch (Tools.current)
            {
            case Tool.Rotate:
                Undo.SetSnapshotTarget(node.transform, "Rotate Spline Node: " + node.name);

                Quaternion newRotation = Handles.RotationHandle(node.Rotation, node.Position);

                Handles.color = new Color(.2f, 0.4f, 1f, 1);
                Handles.ArrowCap(0, node.Position, Quaternion.LookRotation(node.transform.forward), HandleUtility.GetHandleSize(node.Position) * 0.5f);
                Handles.color = new Color(.3f, 1f, .20f, 1);
                Handles.ArrowCap(0, node.Position, Quaternion.LookRotation(node.transform.up), HandleUtility.GetHandleSize(node.Position) * 0.5f);
                Handles.color = Color.white;

                if (!GUI.changed)
                {
                    break;
                }

                node.Rotation = newRotation;

                EditorUtility.SetDirty(target);

                break;

            case Tool.Move:
            case Tool.Scale:
                Undo.SetSnapshotTarget(node.transform, "Move Spline Node: " + node.name);

                Vector3 newPosition = Handles.PositionHandle(node.Position, (Tools.pivotRotation == PivotRotation.Global) ? Quaternion.identity : node.transform.rotation);

                if (!GUI.changed)
                {
                    break;
                }

                node.Position = newPosition;

                EditorUtility.SetDirty(target);

                break;
            }

            CreateSnapshot( );
        }
    }
Exemplo n.º 12
0
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }

        UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer);

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
        if (cam == null || !cam.cachedCamera.isOrthoGraphic)
        {
            return;
        }
#else
        if (cam == null || !cam.cachedCamera.orthographic)
        {
            return;
        }
#endif

        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);
        Transform t    = mPanel.cachedTransform;

        Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);

        // Time to figure out what kind of action is underneath the mouse
        UIWidgetInspector.Action actionUnderMouse = mAction;

        Color handlesColor = new Color(0.5f, 0f, 0.5f);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        if (mPanel.isAnchored)
        {
            UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mPanel) && mPanel.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
            }
        }

        bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);

        // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
        if (canResize && mPanel.isAnchored)
        {
            Quaternion rot = mPanel.cachedTransform.localRotation;
            if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f)
            {
                canResize = false;
            }
        }

        bool[] resizable = new bool[8];

        resizable[4] = canResize;                    // left
        resizable[5] = canResize;                    // top
        resizable[6] = canResize;                    // right
        resizable[7] = canResize;                    // bottom

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], id, resizable[i]);
                    }

                    if (Mathf.Abs(v1.y - v0.y) > 80f)
                    {
                        if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], id, resizable[4]);
                        }

                        if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], id, resizable[6]);
                        }
                    }

                    if (Mathf.Abs(v3.x - v0.x) > 80f)
                    {
                        if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], id, resizable[5]);
                        }

                        if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], id, resizable[7]);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != UIWidgetInspector.Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
                         UIWidgetInspector.Raycast(handles, out mStartDrag))
                {
                    mWorldPos             = t.position;
                    mLocalPos             = t.localPosition;
                    mStartRot             = t.localRotation.eulerAngles;
                    mStartDir             = mStartDrag - t.position;
                    mStartCR              = mPanel.baseClipRegion;
                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == UIWidgetInspector.Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = UIWidgetInspector.Action.None;
                mAction           = UIWidgetInspector.Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
                {
                    Vector3 pos;

                    if (UIWidgetInspector.Raycast(handles, out pos))
                    {
                        if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == UIWidgetInspector.Action.Move)
                                {
                                    NGUISnap.Recalculate(mPanel);
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
                                {
                                    mStartCR   = mPanel.baseClipRegion;
                                    mDragPivot = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != UIWidgetInspector.Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mPanel);

                            if (mAction == UIWidgetInspector.Action.Move)
                            {
                                Vector3 before      = t.position;
                                Vector3 beforeLocal = t.localPosition;
                                t.position = mWorldPos + (pos - mStartDrag);
                                pos        = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
                                                           e.modifiers != EventModifiers.Control) - beforeLocal;
                                t.position = before;

                                NGUIMath.MoveRect(mPanel, pos.x, pos.y);
                            }
                            else if (mAction == UIWidgetInspector.Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == UIWidgetInspector.Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != UIWidgetInspector.Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = UIWidgetInspector.Action.None;
                    mAction           = UIWidgetInspector.Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Exemplo n.º 13
0
 public static void LockFromUnselect()
 {
     HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
 }
    void HandleEvents(SceneView view)
    {
        if (!tool)
        {
            tool = (target as AshTerrainPainter);
        }
        if (!tool && hooked)
        {
            hooked = false;
            SceneView.duringSceneGui -= HandleEvents;
            return;
        }
        if (selected_Tex > 0 && stroke_Channel == Vector4.zero)
        {
            Select_Texure(selected_Tex);
        }

        var e = Event.current;

        if (e.control || e.alt || e.shift)
        {
            return;
        }

        if (brushMode && e.isMouse && e.button == 0)
        {
            var mp = e.mousePosition;
            switch (e.type)
            {
            case EventType.MouseDown:
            case EventType.MouseDrag:
                var        ray = HandleUtility.GUIPointToWorldRay(mp);
                RaycastHit rHit;
                if (Physics.Raycast(ray, out rHit))
                {
                    tool.ApplyStroke(rHit.textureCoord, stroke_Channel, stroke_Opacity, stroke_Size);
                    GUIUtility.hotControl = GUIUtility.GetControlID(FocusType.Passive);
                    Event.current.Use();
                }
                break;
            }
        }

        if (e.type == EventType.KeyDown && e.isKey)
        {
            switch (e.keyCode)
            {
            case KeyCode.BackQuote:
                Selection.activeGameObject = tool.gameObject;
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.B:
                brushMode = !brushMode;
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.Q:
                if (!brushMode)
                {
                    break;
                }
                stroke_Size = Mathf.Clamp(stroke_Size - 1, 1f, 500f);
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.E:
                if (!brushMode)
                {
                    break;
                }
                stroke_Size = Mathf.Clamp(stroke_Size + 1, 1f, 500f);
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.F:
                if (!brushMode)
                {
                    break;
                }
                stroke_Opacity = Mathf.Clamp(stroke_Opacity - 0.05f, 0.1f, 1f);
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.R:
                if (!brushMode)
                {
                    break;
                }
                stroke_Opacity = Mathf.Clamp(stroke_Opacity + 0.05f, 0.1f, 1f);
                EditorUtility.SetDirty(target);
                Event.current.Use();
                break;

            case KeyCode.G:
                if (!brushMode)
                {
                    break;
                }
                Select_Texure(0);
                Event.current.Use();
                break;

            case KeyCode.Z:
                if (!brushMode)
                {
                    break;
                }
                Select_Texure(1);
                Event.current.Use();
                break;

            case KeyCode.X:
                if (!brushMode)
                {
                    break;
                }
                Select_Texure(2);
                Event.current.Use();
                break;

            case KeyCode.C:
                if (!brushMode)
                {
                    break;
                }
                Select_Texure(3);
                Event.current.Use();
                break;

            case KeyCode.V:
                if (!brushMode)
                {
                    break;
                }
                Select_Texure(4);
                Event.current.Use();
                break;
            }
        }
    }
Exemplo n.º 15
0
    void OnSceneGUI()
    {
        BezierPath path = (BezierPath)target;

        if (Event.current.type == EventType.mouseDown)
        {
            // record positions
            pointPos  = selectedPoint.p1;
            handlePos = selectedPoint.h1;
        }
        if (Event.current.type == EventType.mouseUp)
        {
            if (selectedPoint.p1 != pointPos || selectedPoint.h1 != handlePos)
            {
                // put them back, register undo
                Vector3 newPos    = selectedPoint.p1;
                Vector3 newHandle = selectedPoint.h1;
                selectedPoint.p1 = pointPos;
                selectedPoint.h1 = handlePos;
                Undo.RegisterUndo(path, "moving point");
                selectedPoint.p1 = newPos;
                selectedPoint.h1 = newHandle;
                EditorUtility.SetDirty(path);
            }
        }
        bool needCreatePoint = false;
        bool needDeletePoint = false;

        if (selectedPoint != null && Event.current.type != EventType.repaint)
        {
            // add + and - buttons
            Handles.BeginGUI();
            Vector2 screenpos = HandleUtility.WorldToGUIPoint(selectedPoint.p1);
            // inverse y
            //screenpos.y = Screen.height - screenpos.y;
            if (GUI.Button(new Rect(screenpos.x - 10 + 20, screenpos.y - 20, 20, 20), "+"))
            {
                needCreatePoint = true;
            }
            if (GUI.Button(new Rect(screenpos.x - 10 - 20, screenpos.y - 20, 20, 20), "-"))
            {
                needDeletePoint = true;
            }
            Handles.EndGUI();
        }


        // disable transform tool if selected
        if (Selection.activeGameObject == path.gameObject)
        {
            Tools.current = Tool.None;
            if (selectedPoint == null && path.points.Count > 0)
            {
                selectedPoint = path.points[0];
            }
        }

        // draw the handles for the points
        foreach (BezierPath.PathPoint point in path.points)
        {
            if (point == selectedPoint)
            {
                //if (GUI.changed)
                //    EditorUtility.SetDirty(target);
                point.p1 = Handles.PositionHandle(point.p1, Quaternion.identity);

                point.h1 = Handles.PositionHandle(point.h1 + point.p1, Quaternion.identity) - point.p1;
                Handles.CubeCap(0, point.p1, Quaternion.identity, 1);
                Handles.CubeCap(0, point.h1 + point.p1, Quaternion.identity, 0.5f);
            }
            else
            {
                // draw button
                float size = 1;//HandleUtility.GetHandleSize(point.p1) / 3;
                if (Handles.Button(point.p1, Quaternion.identity, 1, size, Handles.CubeCap))
                {
                    selectedPoint = point;
                }
            }
        }

        Handles.color = path.lineColor;
        // draw the lines
        for (int i = 0; i < path.points.Count - 1; i++)
        {
            // draw line from point i to point i+1
            path.points[i].bezier.p1 = path.points[i].p1;
            path.points[i].bezier.h1 = path.points[i].h1;
            path.points[i].bezier.p2 = path.points[i + 1].p1;
            path.points[i].bezier.h2 = -path.points[i + 1].h1; // negative of this handle

            Vector3 oldPos = path.points[i].bezier.GetPointAtTime(0);
            for (float t = 0; t < 1.01; t += 0.1f)
            {
                Vector3 newPos = path.points[i].bezier.GetPointAtTime(t);
                Handles.DrawLine(oldPos, newPos);
                oldPos = newPos;
            }
        }

        if (selectedPoint != null && Event.current.type == EventType.repaint)
        {
            // add + and - buttons
            Handles.BeginGUI();
            Vector2 screenpos = HandleUtility.WorldToGUIPoint(selectedPoint.p1);
            // inverse y
            //screenpos.y = Screen.height - screenpos.y;
            if (GUI.Button(new Rect(screenpos.x - 10 + 20, screenpos.y - 20, 20, 20), "+"))
            {
                needCreatePoint = true;
            }
            if (GUI.Button(new Rect(screenpos.x - 10 - 20, screenpos.y - 20, 20, 20), "-"))
            {
                needDeletePoint = true;
            }
            Handles.EndGUI();
        }

        if (needCreatePoint)
        {
            addPoint(path, selectedPoint);
        }

        if (needDeletePoint)
        {
            deletePoint(path, selectedPoint);
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
Exemplo n.º 16
0
    private void HandleMouseInput(Spline spline)
    {
        if (!EditorGUI.actionKey)
        {
            toolSphereSize  = 10f;
            toolSphereAlpha = 0f;
            return;
        }
        else
        {
            toolSphereAlpha = Mathf.Lerp(toolSphereAlpha, 0.75f, deltaTime * 4f);
            toolSphereSize  = Mathf.Lerp(toolSphereSize, toolTargetSphereSize + Mathf.Sin(Time.realtimeSinceStartup * 2f) * 0.1f, deltaTime * 15f);
        }

        Ray     mouseRay    = Camera.current.ScreenPointToRay(new Vector2(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 32f));
        float   splineParam = spline.GetClosestPointParamToRay(mouseRay, 3);
        Vector3 position    = spline.GetPositionOnSpline(splineParam);

        float currentDistance = Vector3.Cross(mouseRay.direction, position - mouseRay.origin).magnitude;

        SplineNode selectedNode = null;

        foreach (SplineNode node in spline.SplineNodes)
        {
            float newDistance = Vector3.Distance(node.Position, position);

            if (newDistance < currentDistance || newDistance < 0.2f * HandleUtility.GetHandleSize(node.Position))
            {
                currentDistance = newDistance;

                selectedNode = node;
            }
        }

        if (selectedNode != null)
        {
            position = selectedNode.Position;

            Handles.color = new Color(.7f, 0.15f, 0.1f, toolSphereAlpha);
            Handles.SphereCap(0, position, Quaternion.identity, HandleUtility.GetHandleSize(position) * 0.25f * toolSphereSize);

            Handles.color = Color.white;
            Handles.Label(LabelPosition2D(position, 0.3f), "Delete Node (" + selectedNode.gameObject.name + ")", sceneGUIStyleToolLabel);

            toolTargetSphereSize = 1.35f;
        }
        else
        {
            Handles.color = new Color(.5f, 1f, .1f, toolSphereAlpha);
            Handles.SphereCap(0, position, Quaternion.identity, HandleUtility.GetHandleSize(position) * 0.25f * toolSphereSize);

            Handles.color = Color.white;
            Handles.Label(LabelPosition2D(position, 0.3f), "Insert Node", sceneGUIStyleToolLabel);

            toolTargetSphereSize = 0.8f;
        }

        if (Event.current.type == EventType.mouseDown && Event.current.button == 1)
        {
            Undo.RegisterSceneUndo((selectedNode != null) ? "Delete Spline Node (" + selectedNode.name + ")" : "Insert Spline Node");

            if (selectedNode != null)
            {
                spline.RemoveSplineNode(selectedNode.gameObject);
                DestroyImmediate(selectedNode.gameObject);
            }
            else
            {
                InsertNode(spline, splineParam);
            }

            ApplyChangesToTarget(spline);
        }

        HandleUtility.Repaint( );
    }
Exemplo n.º 17
0
    void Input()
    {
        Event   guiEvent = Event.current;
        Vector2 mousePos = HandleUtility.GUIPointToWorldRay(guiEvent.mousePosition).origin;

        if (guiEvent.type == EventType.MouseDown && guiEvent.button == 0 && guiEvent.shift)
        {
            if (selectedSegmentIndex != -1)
            {
                Undo.RecordObject(creator, "Split segment");
                Path.SplitSegment(mousePos, selectedSegmentIndex);
            }
            else if (!Path.IsClosed)
            {
                Undo.RecordObject(creator, "Add segment");
                Path.AddSegment(mousePos);
            }
        }

        if (guiEvent.type == EventType.MouseDown && guiEvent.button == 1)
        {
            float minDstToAnchor     = creator.anchorDiameter * .5f;
            int   closestAnchorIndex = -1;

            for (int i = 0; i < Path.NumPoints; i += 3)
            {
                float dst = Vector2.Distance(mousePos, Path[i]);
                if (dst < minDstToAnchor)
                {
                    minDstToAnchor     = dst;
                    closestAnchorIndex = i;
                }
            }

            if (closestAnchorIndex != -1)
            {
                Undo.RecordObject(creator, "Delete segment");
                Path.DeleteSegment(closestAnchorIndex);
            }
        }

        if (guiEvent.type == EventType.MouseMove)
        {
            float minDstToSegment         = segmentSelectDistanceThreshold;
            int   newSelectedSegmentIndex = -1;

            for (int i = 0; i < Path.NumSegments; i++)
            {
                Vector2[] points = Path.GetPointsInSegment(i);
                float     dst    = HandleUtility.DistancePointBezier(mousePos, points[0], points[3], points[1], points[2]);
                if (dst < minDstToSegment)
                {
                    minDstToSegment         = dst;
                    newSelectedSegmentIndex = i;
                }
            }

            if (newSelectedSegmentIndex != selectedSegmentIndex)
            {
                selectedSegmentIndex = newSelectedSegmentIndex;
                HandleUtility.Repaint();
            }
        }
    }
Exemplo n.º 18
0
        private Vector2 DotHandle(Vector2 aPosition, float aSize = 0.05f)
        {
            float s = HandleUtility.GetHandleSize(aPosition) * aSize;

            return(Handles.FreeMoveHandle(aPosition, Quaternion.identity, s, Vector3.zero, Handles.DotHandleCap));
        }
Exemplo n.º 19
0
    public void OnSceneGUI()
    {
        UnityEngine.Event currentEvent = UnityEngine.Event.current;

        //NodeUtils.DrawCircle(node.Position, 3f);

        // Delete the Node
        if (InputHelpers.Pressed(KeyCode.D))
        {
            nodeBehaviour.Node.Delete();
            return;
        }


        /*****************-  Position-Changes -************************************************************/
        // Update Positions for single or multi-select
        if (nodeBehaviour.transform.position != oldPosition)
        {
            oldPosition = nodeBehaviour.transform.position;

            foreach (Node_Behaviour go in nodeBehaviours)
            {
                NodeUtils.DrawAnglePieGizmo(go.Node);
                if (Event.current.control)
                {
                    go.transform.position = go.transform.position.SnapToGrid();
                    go.Node._position     = go.transform.position;
                }
                else
                {
                    go.Node._position = go.transform.position;
                }

                this.nodeBehaviour.GraphBehaviour.UpdateEdgeIntersections();
            }
            //// fire change-events


            foreach (Node_Behaviour go in nodeBehaviours)
            {
                //Debug.Log(go.name + "OnNodePosition Node2D_Editor");
                go.Node.OnNodeChanged();
            }
        }
        /*****************************************************************************************************/

        // Get the mousepointer on XZ-plane and draw a line
        Vector3 worldPoint = InputHelpers.GetXZPlaneCollisionInEditorFixedHeight(0f, currentEvent); //InputHelpers.GetXZPlaneCollisionInEditor(currentEvent);

        if (Event.current.control)
        {
            worldPoint = worldPoint.SnapToGrid();
        }

        Handles.color = Color.green;
        Handles.DrawLine(nodeBehaviour.transform.position, worldPoint);



        if (InputHelpers.ClickedLeft())
        {
            //if()

            // if another Node is within distance, connect the two nodes with a new edge
            Node_Behaviour foundNode = nodeBehaviour.GraphBehaviour.GetNodeInDistance(worldPoint, 1f);

            if (foundNode != null)
            {
                if (foundNode != nodeBehaviour)
                {
                    // Create a new EdgeBehaviour with the given nodes
                    Edge_Behaviour newEdgeBehaviour = nodeBehaviour.GraphBehaviour.CreateEdgeBehaviour(nodeBehaviour, foundNode);

                    foundNode.gameObject.SelectInEditor();

                    //newEdgeBehaviour.Edge.OnFromToChanged();
                    //}
                    //if (currentEvent.control || currentEvent.shift)
                    //{
                    //Node_Behaviour.combineWithLastSelectedNode = true;
                    //currentEvent.Use();
                }
            }
            else
            {
                Vector3        pointOnEdge;
                float          pointOnEdgeParameter;
                Edge_Behaviour foundEdge = nodeBehaviour.GraphBehaviour.GetEdgeInDistanceWithPoint(worldPoint, 1f, out pointOnEdge, out pointOnEdgeParameter);
                if (foundEdge != null)
                {
                    Debug.Log("Found Edge: " + foundEdge.name + "  hit at t = " + pointOnEdgeParameter + " at position " + pointOnEdge);

                    // Create new Node at the cutting-point on the Edge
                    Node_Behaviour newNodeBehaviour = nodeBehaviour.GraphBehaviour.CreateNodeBehaviour(pointOnEdge);

                    // Create new Edge for first part
                    Edge_Behaviour cutEdge1 = nodeBehaviour.GraphBehaviour.CreateEdgeBehaviour(foundEdge.FromBehaviour, newNodeBehaviour);

                    // Create new Edge for second part
                    Edge_Behaviour cutEdge2 = nodeBehaviour.GraphBehaviour.CreateEdgeBehaviour(newNodeBehaviour, foundEdge.ToBehaviour);

                    if (foundEdge.FromBehaviour != nodeBehaviour && foundEdge.ToBehaviour != nodeBehaviour)
                    {
                        // Create new Edge from the lastNode (this) to the new Node
                        Edge_Behaviour newEdgeBehaviour = nodeBehaviour.GraphBehaviour.CreateEdgeBehaviour(nodeBehaviour, newNodeBehaviour);
                        //Debug.Log("#############  Done creating a new Wall  ##################");
                    }

                    foundEdge.Edge.Delete();

                    newNodeBehaviour.Node.OnNodeChanged();
                    newNodeBehaviour.gameObject.SelectInEditor();
                }
                else //if (nodeBehaviour.GraphBehaviour != null)
                {
                    //Debug.Log("#############  Start creating a new Wall  ##################");
                    Node_Behaviour newNodeBehaviour = nodeBehaviour.GraphBehaviour.CreateNodeBehaviour(worldPoint);
                    Edge_Behaviour newEdgeBehaviour = nodeBehaviour.GraphBehaviour.CreateEdgeBehaviour(nodeBehaviour, newNodeBehaviour);
                    //Debug.Log("#############  Done creating a new Wall  ##################");

                    newNodeBehaviour.gameObject.SelectInEditor();

                    currentEvent.Use();
                }
            }
        }
        HandleUtility.Repaint();


        //if (InputHelpers.MouseUp())
        //{
        //    Debug.Log("RoomRecognition");
        //    ////this is sooooo NOT good....
        //    foreach (Wall wall in node.Graph.Iem.Prefab.Walls)
        //        wall.RoomRecognition();
        //}

        //if (GUI.changed)
        //    EditorUtility.SetDirty(nodeBehaviour);
    }
Exemplo n.º 20
0
        private void OnSceneGUI()
        {
            bool dirty         = false;
            bool removePressed = ((Event.current.modifiers & (EventModifiers.Command | EventModifiers.Control)) != 0);
            bool addPressed    = ((Event.current.modifiers & (EventModifiers.Shift)) != 0);

            Handles.matrix = _self.transform.localToWorldMatrix;

            if (removePressed)
            {
                Handles.color = Color.red;
                for (int i = 0, n = _self.wayPoints.Count; i < n; i++)
                {
                    if (Handles.Button(_self.wayPoints[i], Quaternion.identity, 0.05f, 0.05f, Handles.DotHandleCap))
                    {
                        _self.wayPoints.RemoveAt(i);
                        dirty = true;
                        break;
                    }
                }
            }
            else if (addPressed)
            {
                var mouse = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin;
                var p     = _self.transform.InverseTransformPoint(mouse);

                AntDrawer.BeginHandles(Handles.matrix);
                AntDrawer.DrawCircle((Vector2)p, _self.linkRadius, Color.yellow);
                AntDrawer.EndHandles();

                if (Handles.Button(p, Quaternion.identity, 0.05f, 0.05f, Handles.DotHandleCap))
                {
                    _self.wayPoints.Add((Vector2)p);
                    dirty = true;
                }

                Handles.color = Color.white;
                float s = HandleUtility.GetHandleSize(p) * 0.05f;
                for (int i = 0, n = _self.wayPoints.Count; i < n; i++)
                {
                    Handles.DotHandleCap(0, _self.wayPoints[i], Quaternion.identity, s, EventType.dragUpdated);
                }

                HandleUtility.Repaint();
            }
            else
            {
                Handles.color = Color.white;
                for (int i = 0, n = _self.wayPoints.Count; i < n; i++)
                {
                    Vector2 p     = _self.wayPoints[i];
                    Vector2 delta = DotHandle(p) - p;
                    if (delta != Vector2.zero)
                    {
                        _self.wayPoints[i] = p + delta;

                        dirty = true;
                    }
                }
            }

            DrawLinks();

            if (dirty)
            {
                EditorUtility.SetDirty(target);
            }
        }
	public override void DrawSceneGUI ()
	{
		if(springBody == null || multiEditing)
			return;

		//draw the hovered over spring
		if(drawIndex != -1)
		{	
			JelloSpring spring = springBody.getSpring(drawIndex);
			Vector3 posA;
			Vector3 posB;
			
			posA = springBody.transform.TransformPoint(springBody.Shape.getVertex(spring.pointMassA));
			posB = springBody.transform.TransformPoint(springBody.Shape.getVertex(spring.pointMassB));
				
			Handles.color = Color.magenta;
				
			if(spring.lengthMultiplier != 1f)
			{
				float dist = Vector2.Distance(posA, posB) * spring.lengthMultiplier;
				Vector3 mid = (posA + posB) * 0.5f;
				posA = mid + (mid - posA).normalized * dist * 0.5f;
				posB = mid + (mid - posB).normalized * dist * 0.5f;
			}
				
			Handles.DrawLine(posA,posB);
		}
			
		//TODO make it remember the selected spring?
		//draw the currently selected spring
		if(editIndex != -1 && editIndex < springBody.SpringCount)
		{
			JelloSpring spring = springBody.getSpring(editIndex);
			Handles.color = Color.cyan;

			Vector3[] globalHandlePositions = new Vector3[2];
			for(int i = 0; i < handlePositions.Length; i++)
				globalHandlePositions[i] = springBody.transform.TransformPoint(handlePositions[i]);
			CalculateHandleSizes(handlePositions);

			bool mouseUp = false;
			
			if(Event.current.type == EventType.mouseUp)
				mouseUp = true;
				
			for(int i = 0; i < handlePositions.Length; i++)
				handlePositions[i] = springBody.transform.InverseTransformPoint( Handles.FreeMoveHandle(springBody.transform.TransformPoint(handlePositions[i]), Quaternion.identity, handleSizes[i], Vector3.zero, Handles.CircleCap));
			//handlePositions[1] = springBody.transform.InverseTransformPoint( Handles.FreeMoveHandle(springBody.transform.TransformPoint(handlePositions[1]), Quaternion.identity, HandleUtility.GetHandleSize(handlePositions[1]) * 0.15f, Vector3.zero, Handles.CircleCap));
				
			Handles.color = Color.magenta;
			Handles.DrawLine(springBody.transform.TransformPoint(handlePositions[0]), springBody.transform.TransformPoint(handlePositions[1]));
				
			if(mouseUp)
			{
				if((Vector2)handlePositions[0] != springBody.Shape.getVertex(spring.pointMassA))
				{
					Vector2[] points = new Vector2[springBody.Shape.VertexCount];
					for(int i = 0; i < springBody.Shape.VertexCount; i++)
						points[i] = springBody.Shape.getVertex(i);
					
					spring.pointMassA = JelloShapeTools.FindClosestVertexOnShape(handlePositions[0], points);
					
					handlePositions[0] = springBody.Shape.getVertex(spring.pointMassA);
					
					spring.length = Vector2.Distance(springBody.Shape.getVertex(spring.pointMassA), springBody.Shape.getVertex(spring.pointMassB));

					EditorUtility.SetDirty(springBody);
				}
				
				if((Vector2)handlePositions[1] != springBody.Shape.getVertex(spring.pointMassB))
				{
					Vector2[] points = new Vector2[springBody.Shape.VertexCount];
					for(int i = 0; i < springBody.Shape.VertexCount; i++)
						points[i] = springBody.Shape.getVertex(i);
					
					spring.pointMassB = JelloShapeTools.FindClosestVertexOnShape(handlePositions[1], points);
					
					handlePositions[1] = springBody.Shape.getVertex(spring.pointMassB);
					
					spring.length = Vector2.Distance(springBody.Shape.getVertex(spring.pointMassA), springBody.Shape.getVertex(spring.pointMassB));

					EditorUtility.SetDirty(springBody);
				}
			}
				
			Vector3 posA = springBody.transform.TransformPoint(springBody.Shape.getVertex(spring.pointMassA));
			Vector3 posB = springBody.transform.TransformPoint(springBody.Shape.getVertex(spring.pointMassB));
				
			if(spring.lengthMultiplier != 1f)
			{
				float dist = Vector2.Distance(posA, posB) * spring.lengthMultiplier;
				Vector3 mid = (posA + posB) * 0.5f;
				posA = mid + (mid - posA).normalized * dist * 0.5f;
				posB = mid + (mid - posB).normalized * dist * 0.5f;
			}
			
			Handles.color = Color.blue;
			
			Handles.DrawLine(posA,posB);
		}
			
		if(newSubComponentState != AddSubComponentState.inactive)
		{
			
			if(Event.current.isKey && Event.current.keyCode == KeyCode.Escape)
			{
				newSubComponentState = AddSubComponentState.inactive;
			}
			
			
			int controlID = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive);
			
			if(Event.current.type == EventType.Layout)
				HandleUtility.AddDefaultControl(controlID);
			
			Handles.color = Color.red;
			
			Vector3 pos = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin; //need where this ray intersects the zplane
			Plane plane = new Plane(Vector3.forward, new Vector3(0, 0, springBody.transform.position.z));
			Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
			float dist = 0f;
			plane.Raycast(ray, out dist);
			pos = ray.GetPoint(dist);
			Vector3 mousePosWorld = new Vector3(pos.x, pos.y, springBody.transform.position.z);
			
			if(newSubComponentState == AddSubComponentState.assignedFirst)
			{
				pos = springBody.transform.TransformPoint(springBody.Shape.getVertex(newSpring.pointMassA));
				Handles.CircleCap(3, pos, Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.15f);
				Handles.DrawLine( pos, mousePosWorld);
				
				Handles.color = Color.blue;
				Handles.CircleCap(3, mousePosWorld, Quaternion.identity, HandleUtility.GetHandleSize(mousePosWorld) * 0.15f);
				
				if(Event.current.type == EventType.MouseUp)
				{
					Vector2[] points = new Vector2[springBody.Shape.VertexCount];
					for(int i = 0; i < springBody.Shape.VertexCount; i++)
						points[i] = springBody.Shape.getVertex(i);
					
					newSpring.pointMassB = JelloShapeTools.FindClosestVertexOnShape(springBody.transform.InverseTransformPoint(mousePosWorld), points);
					newSpring.length = Vector2.Distance(springBody.Shape.getVertex(newSpring.pointMassA), springBody.Shape.getVertex(newSpring.pointMassB));
					newSpring.stiffness = springBody.DefaultCustomSpringStiffness;
					newSpring.damping = springBody.DefaultCustomSpringDamping;
					
					editIndex = springBody.SpringCount;
					springBody.addCustomSpring(newSpring);
					newSubComponentState = AddSubComponentState.inactive;

					handlePositions[0] = springBody.Shape.getVertex(newSpring.pointMassA);
					handlePositions[1] = springBody.Shape.getVertex(newSpring.pointMassB);

					eCustomSprings.isExpanded = true;
					eEdgeSprings.isExpanded = false;
					eInternalSprings.isExpanded = false;

					EditorUtility.SetDirty(springBody);
				}
			}
			if(newSubComponentState == AddSubComponentState.initiated)
			{
				Handles.CircleCap(3, mousePosWorld, Quaternion.identity, HandleUtility.GetHandleSize(mousePosWorld) * 0.15f);
				
				if(Event.current.type == EventType.MouseUp)
				{
					Vector2[] points = new Vector2[springBody.Shape.VertexCount];
					for(int i = 0; i < springBody.Shape.VertexCount; i++)
						points[i] = springBody.Shape.getVertex(i);
					
					newSpring = new JelloSpring();
					newSpring.pointMassA = JelloShapeTools.FindClosestVertexOnShape(springBody.transform.InverseTransformPoint(mousePosWorld), points);
					newSubComponentState = AddSubComponentState.assignedFirst;
				}
			}
			
			SceneView.RepaintAll();
		}
		
		if(newSubComponentState != AddSubComponentState.inactive || editIndex != -1)
		{
			Handles.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
			
			for(int i = springBody.EdgeSpringCount; i < springBody.SpringCount; i++)
			{
				if(editIndex == i)
					continue;
				Handles.DrawLine(springBody.transform.TransformPoint(springBody.Shape.getVertex(springBody.getSpring(i).pointMassA)), springBody.transform.TransformPoint(springBody.Shape.getVertex(springBody.getSpring(i).pointMassB)));
			}
			
			mainEditor.DrawPointMasses(springBody, false);
		}
	}
Exemplo n.º 22
0
        internal static bool DrawEdge(Vector3 start, Vector3 startDirection, Vector3 end, Vector3 endDirection, Color startColor, Color endColor, Color startColorHighlighted, Color endColorHighlighted, float thickness = 3, Action onContextClick = null, bool highlightAndContextClick = true, float minDistanceFromStartEnd = 0)
        {
            int segments = 40;

            float dirFactor       = Mathf.Clamp((end - start).magnitude, 10f, 120);
            float correctionAngle = 22.5F;

            if (start.x > end.x)
            {
                if (start.y < end.y)
                {
                    if (Mathf.Approximately(startDirection.y, 0))
                    {
                        startDirection = (Quaternion.AngleAxis(-correctionAngle, new Vector3(0, 0, 1)) * startDirection) * 3;
                    }

                    if (Mathf.Approximately(endDirection.y, 0))
                    {
                        endDirection = (Quaternion.AngleAxis(-correctionAngle, new Vector3(0, 0, 1)) * endDirection) * 3;
                    }
                }
                else
                {
                    if (Mathf.Approximately(startDirection.y, 0))
                    {
                        startDirection = (Quaternion.AngleAxis(correctionAngle, new Vector3(0, 0, 1)) * startDirection) * 3;
                    }

                    if (Mathf.Approximately(endDirection.y, 0))
                    {
                        endDirection = (Quaternion.AngleAxis(correctionAngle, new Vector3(0, 0, 1)) * endDirection) * 3;
                    }
                }
            }


            Vector2 startTan = start + new Vector3(startDirection.x, -startDirection.y) * dirFactor;
            Vector2 endTan   = end + new Vector3(endDirection.x, -endDirection.y) * dirFactor;


            Vector3[] points     = Handles.MakeBezierPoints(start, end, startTan, endTan, segments);
            bool      selectLine = HandleUtility.DistancePointBezier(Event.current.mousePosition, start, end, startTan, endTan) < thickness * 2 && highlightAndContextClick;

            Color oldColor = Handles.color;

            Handles.BeginGUI();

            for (int i = 1; i < points.Length; i++)
            {
                float t = (i * 1F) / points.Length;

                float t1 = Math.Clamp01(t, 0, 0.3F);
                float t2 = Math.Clamp01(t, 0.7F, 1F);

                Color colorStart = selectLine ? startColorHighlighted : Color.Lerp(startColorHighlighted, startColor, t1);
                Color colorEnd   = selectLine ? endColorHighlighted : Color.Lerp(endColor, endColorHighlighted, t2);
                Color color      = Color.Lerp(colorStart, colorEnd, t);

                Handles.color = color;
                Handles.DrawAAPolyLine(thickness, points[i - 1], points[i]);
            }

            Handles.EndGUI();

            Handles.color = oldColor;

            if (selectLine && Event.current.type == EventType.MouseDown && Event.current.button == 1)
            {
                // use sqr distance for better performance.
                float sqrDistanceFromStart = (Event.current.mousePosition - (Vector2)start).sqrMagnitude;
                float sqrDistanceFromEnd   = (Event.current.mousePosition - (Vector2)end).sqrMagnitude;

                if (sqrDistanceFromStart > minDistanceFromStartEnd * minDistanceFromStartEnd && sqrDistanceFromEnd > minDistanceFromStartEnd * minDistanceFromStartEnd)
                {
                    if (onContextClick != null)
                    {
                        onContextClick();
                        Event.current.Use();
                        return(true);
                    }
                }
            }

            return(selectLine);
        }
Exemplo n.º 23
0
    void DrawSelectedKnot()
    {
        Bezier3DSpline.Knot knot = spline.GetKnot(activeKnot);
        Handles.color = Color.green;

        Vector3 knotWorldPos = spline.transform.TransformPoint(knot.position);

        if (Tools.current == Tool.Move)
        {
            //Position handle
            EditorGUI.BeginChangeCheck();
            knotWorldPos = Handles.PositionHandle(knotWorldPos, Tools.handleRotation);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(spline, "Edit Bezier Point");
                knot.position = spline.transform.InverseTransformPoint(knotWorldPos);
                spline.SetKnot(activeKnot, knot);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
        }
        else if (Tools.current == Tool.Rotate)
        {
            //Draw arrow

            //Rotation handle
            EditorGUI.BeginChangeCheck();
            Quaternion rot = knot.orientation.HasValue ? knot.orientation.Value : Quaternion.identity;
            Handles.color = Handles.yAxisColor;
            Handles.ArrowHandleCap(0, knotWorldPos, rot * Quaternion.AngleAxis(90, Vector3.left), HandleUtility.GetHandleSize(knotWorldPos), EventType.Repaint);
            rot = Handles.RotationHandle(rot, knotWorldPos);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(spline, "Edit Bezier Point");
                knot.orientation = rot;
                spline.SetKnot(activeKnot, knot);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
                Repaint();
            }
        }

        Handles.color = Handles.zAxisColor;

        //In Handle
        if (knot.handleIn != Vector3.zero)
        {
            EditorGUI.BeginChangeCheck();
            Vector3 inHandleWorldPos = spline.transform.TransformPoint(knot.position + knot.handleIn);
            //inHandleWorldPos = Handles.PositionHandle(inHandleWorldPos, Tools.handleRotation);
            if (knot.auto == 0)
            {
                inHandleWorldPos = SmallPositionHandle(inHandleWorldPos, Tools.handleRotation, 0.5f, 1f);
            }
            else
            {
                inHandleWorldPos = SmallPositionHandle(inHandleWorldPos, Tools.handleRotation, 0.5f, 0.5f);
            }
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(spline, "Edit Bezier Handle");
                knot.handleIn = spline.transform.InverseTransformPoint(inHandleWorldPos) - knot.position;
                knot.auto     = 0;
                if (mirror)
                {
                    knot.handleOut = -knot.handleIn;
                }
                spline.SetKnot(activeKnot, knot);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
            Handles.DrawLine(knotWorldPos, inHandleWorldPos);
        }

        //outHandle
        if (knot.handleOut != Vector3.zero)
        {
            EditorGUI.BeginChangeCheck();
            Vector3 outHandleWorldPos = spline.transform.TransformPoint(knot.position + knot.handleOut);
            //outHandleWorldPos = Handles.PositionHandle(outHandleWorldPos, Tools.handleRotation);
            if (knot.auto == 0)
            {
                outHandleWorldPos = SmallPositionHandle(outHandleWorldPos, Tools.handleRotation, 0.5f, 1f);
            }
            else
            {
                outHandleWorldPos = SmallPositionHandle(outHandleWorldPos, Tools.handleRotation, 0.5f, 0.5f);
            }
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(spline, "Edit Bezier Handle");
                knot.handleOut = spline.transform.InverseTransformPoint(outHandleWorldPos) - knot.position;
                knot.auto      = 0;
                if (mirror)
                {
                    knot.handleIn = -knot.handleOut;
                }
                spline.SetKnot(activeKnot, knot);
                if (onUpdateSpline != null)
                {
                    onUpdateSpline(spline);
                }
            }
            Handles.DrawLine(knotWorldPos, outHandleWorldPos);
        }

        // Hotkeys
        Event e = Event.current;

        switch (e.type)
        {
        case EventType.KeyDown:
            if (e.keyCode == KeyCode.Delete)
            {
                if (spline.KnotCount > 2)
                {
                    Undo.RecordObject(spline, "Remove Bezier Point");
                    spline.RemoveKnot(activeKnot);
                    SelectKnot(-1, false);
                    if (onUpdateSpline != null)
                    {
                        onUpdateSpline(spline);
                    }
                }
                e.Use();
            }
            if (e.keyCode == KeyCode.Escape)
            {
                SelectKnot(-1, false);
                e.Use();
            }
            break;
        }
    }
        public void OnSceneGUI()
        {
            var navLink = (NavMeshLink)target;

            if (!navLink.enabled)
            {
                return;
            }

            var mat = UnscaledLocalToWorldMatrix(navLink.transform);

            var startPt   = mat.MultiplyPoint(navLink.startPoint);
            var endPt     = mat.MultiplyPoint(navLink.endPoint);
            var midPt     = Vector3.Lerp(startPt, endPt, 0.35f);
            var startSize = HandleUtility.GetHandleSize(startPt);
            var endSize   = HandleUtility.GetHandleSize(endPt);
            var midSize   = HandleUtility.GetHandleSize(midPt);

            var zup   = Quaternion.FromToRotation(Vector3.forward, Vector3.up);
            var right = mat.MultiplyVector(CalcLinkRight(navLink));

            var oldColor = Handles.color;

            Handles.color = s_HandleColor;

            Vector3 pos;

            if (navLink.GetInstanceID() == s_SelectedID && s_SelectedPoint == 0)
            {
                EditorGUI.BeginChangeCheck();
                Handles.CubeHandleCap(0, startPt, zup, 0.1f * startSize, Event.current.type);
                pos = Handles.PositionHandle(startPt, navLink.transform.rotation);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(navLink, "Move link point");
                    navLink.startPoint = mat.inverse.MultiplyPoint(pos);
                }
            }
            else
            {
                if (Handles.Button(startPt, zup, 0.1f * startSize, 0.1f * startSize, Handles.CubeHandleCap))
                {
                    s_SelectedPoint = 0;
                    s_SelectedID    = navLink.GetInstanceID();
                }
            }

            if (navLink.GetInstanceID() == s_SelectedID && s_SelectedPoint == 1)
            {
                EditorGUI.BeginChangeCheck();
                Handles.CubeHandleCap(0, endPt, zup, 0.1f * startSize, Event.current.type);
                pos = Handles.PositionHandle(endPt, navLink.transform.rotation);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(navLink, "Move link point");
                    navLink.endPoint = mat.inverse.MultiplyPoint(pos);
                }
            }
            else
            {
                if (Handles.Button(endPt, zup, 0.1f * endSize, 0.1f * endSize, Handles.CubeHandleCap))
                {
                    s_SelectedPoint = 1;
                    s_SelectedID    = navLink.GetInstanceID();
                }
            }

            EditorGUI.BeginChangeCheck();
            pos = Handles.Slider(midPt + right * navLink.width * 0.5f, right, midSize * 0.03f, Handles.DotHandleCap, 0);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(navLink, "Adjust link width");
                navLink.width = Mathf.Max(0.0f, 2.0f * Vector3.Dot(right, (pos - midPt)));
            }

            EditorGUI.BeginChangeCheck();
            pos = Handles.Slider(midPt - right * navLink.width * 0.5f, -right, midSize * 0.03f, Handles.DotHandleCap, 0);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(navLink, "Adjust link width");
                navLink.width = Mathf.Max(0.0f, 2.0f * Vector3.Dot(-right, (pos - midPt)));
            }

            Handles.color = oldColor;
        }
Exemplo n.º 25
0
    public override void DealWithEvent()
    {
        Event   current      = Event.current;
        int     controlID    = GUIUtility.GetControlID(FocusType.Passive);
        Vector3 collisionPos = MapModifier.Instance.CaculateCollisionPosFromGUIPoint(current.mousePosition);

        if (collisionPos.y == float.MaxValue)
        {
            return;
        }
        collisionPos = new Vector3(collisionPos.x, 0, collisionPos.z);
        Vector3 lefttopcenter = MapModifier.Instance.CaculateCellCenterByPos(collisionPos);
        int     lefttopindex  = MapModifier.Instance.CaculateIndexForPos(lefttopcenter);
        Vector3 size          = new Vector3(1, 0, 1);
        var     flag          = MapModifier.Instance.CheckContainUnreachable(lefttopindex, size);

        Handles.color = Color.green;
        Handles.DrawWireDisc(collisionPos, Vector3.up, .5f);
        //Debug.Log(current.type);
        if (isDrag == true)
        {
            MapAux.DrawRectHandles(startpoint, endpoint);
        }
        HandleUtility.AddDefaultControl(controlID);
        switch (current.type)
        {
        case EventType.mouseDown:
            if (current.button == 0 && (!isDrag))
            {
                startpoint = collisionPos;
            }
            break;

        case EventType.mouseUp:
            if (current.button == 0 && (isDrag == false))
            {
                MapModifier.Instance.AddPoint(startpoint);
            }
            else if (current.button == 0 && (isDrag == true))
            {
                endpoint = collisionPos;
                MapModifier.Instance.AddArea(startpoint, endpoint);
                isDrag = false;
            }
            break;

        case EventType.mouseDrag:
            if (current.button == 0)
            {
                endpoint = collisionPos;
                isDrag   = true;
            }
            break;

        default:
            break;
        }
        int curID = GUIUtility.hotControl;

        if (HandleRecorder.handleIDAndTarget.ContainsKey(curID))
        {
            curFocusID = curID;
        }
        if (HandleRecorder.handleIDAndTarget.ContainsKey(curFocusID))
        {
            // Handles.BeginGUI();
            // var re = SceneView.lastActiveSceneView.position;
            // GUILayout.BeginArea(new Rect(re.width / 4, re.height - 120, re.width/2, 120), EditorStyles.textArea);
            EditDetailsWindow.deleteAction = () =>
            {
                MapModifier.Instance.RemoveInfo(HandleRecorder.handleIDAndTarget[curFocusID]);
                HandleRecorder.handleIDAndTarget.Remove(curFocusID);
            };
            EditDetailsWindow.toDraw = ExposeProperties.GetProperties(HandleRecorder.handleIDAndTarget[curFocusID], out EditDetailsWindow.toDrawType);
            //ExposeProperties.Expose(m_fields);

            // GUILayout.EndArea();
            // Handles.EndGUI();
        }
        SceneView.RepaintAll();
    }
Exemplo n.º 26
0
	public void DrawPointMasses(JelloBody body, bool editable)
	{
		Handles.color = new Color(0.75f, 0.75f, 0.2f, 0.5f);
		
		for(int i = 0; i < body.Shape.EdgeVertexCount; i++)
		{
			Vector2 pos = body.transform.TransformPoint (body.Shape.EdgeVertices[i]);
			if(editable)
			{
				int hot = GUIUtility.hotControl;
				
				Handles.FreeMoveHandle(pos, Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.075f, Vector3.zero, Handles.DotCap);
				if(GUIUtility.hotControl != hot)
				{
					if(currentSubEditor == 1)//point mass editor!
					{
						subEditors[currentSubEditor].SetEditIndex(i);
						Repaint();
					}
				}
			}
			else
			{
				Handles.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
				Handles.DotCap(3, pos, Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.075f);
			}
		}

		for(int i = 0; i < body.Shape.InternalVertexCount; i++)
		{
			Handles.color = new Color(0.75f, 0f, 0.75f, 0.5f);
			Vector2 pos = body.transform.TransformPoint (body.Shape.InternalVertices[i]);
			
			if(editable)
			{
				int hot = GUIUtility.hotControl;

				EditorGUI.BeginChangeCheck();
				pos = Handles.FreeMoveHandle(pos, Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.075f, Vector3.zero, Handles.DotCap);
				if(EditorGUI.EndChangeCheck())
				{
					if(!JelloShapeTools.Contains(body.Shape.EdgeVertices, body.transform.InverseTransformPoint(pos)) || JelloShapeTools.PointOnPerimeter(body.Shape.EdgeVertices, body.transform.InverseTransformPoint(pos)))
					{
						JelloClosedShape newShape = new JelloClosedShape(body.Shape.EdgeVertices, null, false);

						for(int a = 0; a < body.Shape.InternalVertexCount; a++)
						{
							//dont add this point
							if(a == i)
								continue;

							newShape.addInternalVertex(body.Shape.InternalVertices[a]);
						}

						newShape.finish(false);

						body.smartSetShape(newShape, JelloBody.ShapeSettingOptions.MovePointMasses, smartShapeSettingOptions);

						EditorUtility.SetDirty(body);
						GUIUtility.hotControl = 0;
						subEditors[currentSubEditor].SetEditIndex(-1);
						Repaint();
						break;
					}

					body.Shape.changeInternalVertexPosition(i, body.transform.InverseTransformPoint(pos));
					body.Shape.finish(false);

					EditorUtility.SetDirty(body);

				}
				if(GUIUtility.hotControl != hot && GUIUtility.hotControl != 0)
				{

					if(currentSubEditor == 1)//point mass editor!
					{
						subEditors[currentSubEditor].SetEditIndex(i + body.EdgePointMassCount);
						Repaint();
					}
				}
			}
			else
			{
				Handles.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
				Handles.DotCap(3, pos, Quaternion.identity, HandleUtility.GetHandleSize(pos) * 0.075f);
			}

	
		}

	}
Exemplo n.º 27
0
        void OnSceneGUI()
        {
            Handles.color = Color.green;

            if (bone.editMode)
            {
                Event current = Event.current;

                if (bone.enabled && !current.control)
                {
                    EditorGUI.BeginChangeCheck();

                    Vector3 v = Handles.FreeMoveHandle(bone.Head, Quaternion.identity, 0.1f, Vector3.zero, Handles.RectangleHandleCap);

                    Undo.RecordObject(bone.transform, "Change bone transform");
                    Undo.RecordObject(bone, "Change bone");

                    bone.length       = Vector2.Distance(v, bone.transform.position);
                    bone.transform.up = (v - bone.transform.position).normalized;

                    if (EditorGUI.EndChangeCheck())
                    {
                        EditorUtility.SetDirty(bone);
                    }
                }

                int controlID = GUIUtility.GetControlID(FocusType.Passive);

                if (current.control)
                {
                    switch (current.GetTypeForControl(controlID))
                    {
                    case EventType.MouseDown:
                        current.Use();
                        break;

                    case EventType.MouseUp:
                        Undo.FlushUndoRecordObjects();
                        Bone b = Bone.Create();
                        Selection.activeGameObject = b.gameObject;

                        Vector3 p = HandleUtility.GUIPointToWorldRay(current.mousePosition).origin;
                        p              = new Vector3(p.x, p.y);
                        b.length       = Vector3.Distance(p, bone.Head);
                        b.transform.up = p - (Vector3)bone.Head;

                        Event.current.Use();
                        break;

                    case EventType.Layout:
                        HandleUtility.AddDefaultControl(controlID);
                        break;
                    }
                }

                if (Event.current.control && Event.current.type == EventType.MouseDown)
                {
                }
            }
            else
            {
                if (bone.parent != null &&
                    (bone.ik == null ||
                     bone.ik != null && !bone.ik.enabled ||
                     bone.ik != null && bone.ik.influence == 0) &&
                    bone.snapToParent)
                {
                    length = Vector3.Distance(bone.parent.transform.position, bone.transform.position);

                    if (Mathf.Abs(bone.parent.length - length) > 0.0001)
                    {
                        bone.transform.parent           = null;
                        bone.parent.transform.parent.up = (bone.transform.position - bone.parent.transform.position).normalized;
                        bone.parent.length    = length;
                        bone.transform.parent = bone.parent.transform;
                    }
                }
            }
        }
Exemplo n.º 28
0
 public bool IsPointOverConnection(Vector2 point)
 {
     return(HandleUtility.DistancePointLine(point, StartPoint, EndPoint) <= ClickableExtraRange);
 }
Exemplo n.º 29
0
        void CheckSnap(Segment selectedSegment, Transform draggedJoint)
        {
            if (SegmentSnapperEditor.Segments == null)
            {
                SegmentSnapperEditor.Populate();
            }
            if (SegmentSnapperEditor.Segments.Any(s => s.joints.Any(j => j == null)))
            {
                SegmentSnapperEditor.Populate();
            }

            foreach (var segment in SegmentSnapperEditor.Segments)
            {
                if (segment == selectedSegment)
                {
                    continue;
                }
                Transform snapToJoint = segment.joints
                                        .FirstOrDefault(j => (HandleUtility.WorldToGUIPoint(j.position) - HandleUtility.WorldToGUIPoint(draggedJoint.position)).magnitude < 35);

                if (snapToJoint == null)
                {
                    continue;
                }

                SegmentUtility.SnapJoints(selectedSegment.transform, draggedJoint, snapToJoint);
            }
        }
Exemplo n.º 30
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Transform t = mWidget.cachedTransform;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);

        Action actionUnderMouse = mAction;

        Vector3[] handles = GetHandles(mWidget.worldCorners);

        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        // If the widget is anchored, draw the anchors
        if (mWidget.isAnchored)
        {
            DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
            DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
            DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
            DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mWidget) && mWidget.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
            }
        }

        // Presence of the legacy stretch component prevents resizing
        bool canResize = (mWidget.GetComponent <UIStretch>() == null);

        bool[] resizable = new bool[8];

        resizable[4] = canResize;               // left
        resizable[5] = canResize;               // top
        resizable[6] = canResize;               // right
        resizable[7] = canResize;               // bottom

        UILabel lbl = mWidget as UILabel;

        if (lbl != null)
        {
            if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
            {
                resizable[4] = false;                   // left
                resizable[5] = false;                   // top
                resizable[6] = false;                   // right
                resizable[7] = false;                   // bottom
            }
            else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
            {
                resizable[5] = false;                   // top
                resizable[7] = false;                   // bottom
            }
        }

        if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
        {
            resizable[4] = false;
            resizable[6] = false;
        }
        else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
        {
            resizable[5] = false;
            resizable[7] = false;
        }

        resizable[0] = resizable[7] && resizable[4];         // bottom-left
        resizable[1] = resizable[5] && resizable[4];         // top-left
        resizable[2] = resizable[5] && resizable[6];         // top-right
        resizable[3] = resizable[7] && resizable[6];         // bottom-right

        UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
                    }

                    if ((v1 - v0).magnitude > 80f)
                    {
                        if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
                        }

                        if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
                        }
                    }

                    if ((v3 - v0).magnitude > 80f)
                    {
                        if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
                        }

                        if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            mStartMouse     = e.mousePosition;
            mAllowSelection = true;

            if (e.button == 1)
            {
                if (e.modifiers == 0)
                {
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
            else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
            {
                mWorldPos      = t.position;
                mLocalPos      = t.localPosition;
                mStartRot      = t.localRotation.eulerAngles;
                mStartDir      = mStartDrag - t.position;
                mStartWidth    = mWidget.width;
                mStartHeight   = mWidget.height;
                mStartLeft.x   = mWidget.leftAnchor.relative;
                mStartLeft.y   = mWidget.leftAnchor.absolute;
                mStartRight.x  = mWidget.rightAnchor.relative;
                mStartRight.y  = mWidget.rightAnchor.absolute;
                mStartBottom.x = mWidget.bottomAnchor.relative;
                mStartBottom.y = mWidget.bottomAnchor.absolute;
                mStartTop.x    = mWidget.topAnchor.relative;
                mStartTop.y    = mWidget.topAnchor.absolute;

                mDragPivot            = pivotUnderMouse;
                mActionUnderMouse     = actionUnderMouse;
                GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                e.Use();
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != Action.None || mActionUnderMouse != Action.None)
                {
                    Vector3 pos;

                    if (Raycast(handles, out pos))
                    {
                        if (mAction == Action.None && mActionUnderMouse != Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == Action.Move)
                                {
                                    NGUISnap.Recalculate(mWidget);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartWidth  = mWidget.width;
                                    mStartHeight = mWidget.height;
                                    mDragPivot   = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mWidget);

                            // Reset the widget before adjusting anything
                            t.position     = mWorldPos;
                            mWidget.width  = mStartWidth;
                            mWidget.height = mStartHeight;
                            mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
                            mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
                            mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
                            mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);

                            if (mAction == Action.Move)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Snap the widget
                                Vector3 after = NGUISnap.Snap(t.localPosition, mWidget.localCorners, e.modifiers != EventModifiers.Control);

                                // Calculate the final delta
                                Vector3 localDelta = (after - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget by the delta
                                NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
                            }
                            else if (mAction == Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == Action.Scale)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Calculate the final delta
                                Vector3 localDelta = (t.localPosition - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
                                ReEvaluateAnchorType();
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = Action.None;
                mAction           = Action.None;
            }
            else if (mAllowSelection)
            {
                BetterList <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.size > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }