Example #1
0
    private void EventHandler(SceneView sceneview)
    {
        if (m_myTarget == null)
        {
            m_myTarget = target as SnapToGrid;
        }


        if (m_myTarget.childToApplyBoxCollider != null)
        {
            BoxCollider _boxCollider = m_myTarget.GetComponent <BoxCollider>();
            _boxCollider.size   = m_myTarget.childToApplyBoxCollider.bounds.size;
            _boxCollider.center = m_myTarget.childToApplyBoxCollider.bounds.center;
        }


        HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Native));
        Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

        RaycastHit[] hits = Physics.RaycastAll(worldRay, 1000);

        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i].transform.gameObject.layer == LayerMask.NameToLayer("Grid"))
            {
                gridPos = hits[i].point;
            }
            else if (hits[i].transform.GetComponent <SnapToGrid>() != null)
            {
                //Debug.Log("Object name: " + hits[i].collider.name);
                onMouseOverGameObject = hits[i].transform.gameObject;
            }
        }

        if (hits.Length <= 1)
        {
            onMouseOverGameObject = null;
        }

        //Debug.Log(onMouseOverGameObject);


        if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.A || Event.current.keyCode == KeyCode.S))
        {
            m_aPressed = true;
        }

        if ((Event.current.type == EventType.keyUp) && (Event.current.keyCode == KeyCode.A || Event.current.keyCode == KeyCode.S))
        {
            m_aPressed = false;
        }

        //check if control is pressed.
        if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.LeftControl || Event.current.keyCode == KeyCode.RightControl))
        {
            m_controlPressed = true;
        }

        if ((Event.current.type == EventType.keyUp) && (Event.current.keyCode == KeyCode.LeftControl || Event.current.keyCode == KeyCode.RightControl))
        {
            m_controlPressed = false;
        }

        //mouse position in the grid
        float col = (float)gridPos.x / ((float)LevelGrid.Ins.gridSize * LevelGrid.Ins.scaleFactor);
        float row = (float)gridPos.z / ((float)LevelGrid.Ins.gridSize * LevelGrid.Ins.scaleFactor);

        if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
        {
            if (onMouseOverGameObject == m_myTarget.gameObject)
            {
                isThisObject = true;
            }
            else
            {
                isThisObject = false;
                if (onMouseOverGameObject != null)
                {
                    Selection.activeGameObject = onMouseOverGameObject;
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }

        //if (!isThisObject)
        //    return;

        //mouse click and dragandrop
        if (Event.current.type == EventType.MouseDrag && Event.current.button == 0)
        {
            if (Selection.activeGameObject == null)
            {
                return;
            }
            if (m_aPressed)
            {
                LevelGrid.Ins.selectedGameObject.transform.eulerAngles += new Vector3(0, 90f, 0);
                m_aPressed = false;
            }
            SnapToGrid((int)col, (int)row, LevelGrid.Ins.height);
        }

        LevelGrid.Ins.UpdateInputGridHeight();


        //if mouse released when control pressed, make a copy / otherwise, destroy old object.
        if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
        {
            m_instantiated = false;
            if (LevelGrid.Ins.selectedGameObject)
            {
                //make copy if control is pressed
                if (!m_controlPressed)
                {
                    Undo.IncrementCurrentGroup();
                    Undo.DestroyObjectImmediate(m_myTarget.gameObject);
                }
                Selection.activeGameObject = LevelGrid.Ins.selectedGameObject;
            }
        }
    }
Example #2
0
    public void HandleZoomAndPanEvents(Rect area)
    {
        area.x = 0;
        area.y = 0;
#if UNITY_5_5_OR_NEWER
        int id = GUIUtility.GetControlID(zoomableAreaHash, FocusType.Passive, area);
#else
        int id = GUIUtility.GetControlID(zoomableAreaHash, FocusType.Native, area);
#endif

        switch (Event.current.GetTypeForControl(id))
        {
        case EventType.mouseDown:
            if (area.Contains(Event.current.mousePosition))
            {
                // Catch keyboard control when clicked inside zoomable area
                // (used to restrict scrollwheel)
                GUIUtility.keyboardControl = id;

                if (IsZoomEvent() || IsPanEvent())
                {
                    GUIUtility.hotControl = id;
                    m_MouseDownPosition   = mousePositionInDrawing;

                    Event.current.Use();
                }
            }
            break;

        case EventType.mouseUp:
            //Debug.Log("mouse-up!");
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl = 0;

                // If we got the mousedown, the mouseup is ours as well
                // (no matter if the click was in the area or not)
                m_MouseDownPosition = new Vector2(-1000000, -1000000);
                //Event.current.Use();
            }
            break;

        case EventType.mouseDrag:
            if (GUIUtility.hotControl != id)
            {
                break;
            }

            if (IsZoomEvent())
            {
                // Zoom in around mouse down position
                Zoom(m_MouseDownPosition, false);
                Event.current.Use();
            }
            else if (IsPanEvent())
            {
                // Pan view
                Pan();
                Event.current.Use();
            }
            break;

        case EventType.scrollWheel:
            if (!area.Contains(Event.current.mousePosition))
            {
                break;
            }
            if (m_IgnoreScrollWheelUntilClicked && GUIUtility.keyboardControl != id)
            {
                break;
            }

            // Zoom in around cursor position
            Zoom(mousePositionInDrawing, true);
            Event.current.Use();
            break;
        }
    }
Example #3
0
 public static void MinMaxSlider(Rect position, ref float value, ref float size, float visualStart, float visualEnd, float startLimit, float endLimit, GUIStyle slider, GUIStyle thumb, bool horiz)
 {
     EditorGUIExt.DoMinMaxSlider(position, GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive), ref value, ref size, visualStart, visualEnd, startLimit, endLimit, slider, thumb, horiz);
 }
Example #4
0
        void OnSceneGUI()
        {
            HandleUtility.Repaint();

            // do not allow selection
            HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
            // get target class
            TrFlagPainter thisTarget = (TrFlagPainter)target;

            // cycle tile types
            if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.KeypadPlus)
            {
                if (thisTarget.DATA_FE.PAINT_MODE == E_PAINTMODE.TILE)
                {
                    switch (currentTileType)
                    {
                    case E_TILETYPE.FLOOR:
                        currentTileType = E_TILETYPE.BOOST;
                        break;

                    case E_TILETYPE.BOOST:
                        currentTileType = E_TILETYPE.WEAPON;
                        break;

                    case E_TILETYPE.WEAPON:
                        currentTileType = E_TILETYPE.RECHARGE;
                        break;

                    case E_TILETYPE.RECHARGE:
                        currentTileType = E_TILETYPE.SPAWN;
                        break;

                    case E_TILETYPE.SPAWN:
                        currentTileType = E_TILETYPE.FLOOR;
                        break;
                    }
                }
                else if (thisTarget.DATA_FE.PAINT_MODE == E_PAINTMODE.SECTION)
                {
                    switch (currentSectionType)
                    {
                    case E_SECTIONTYPE.NORMAL:
                        currentSectionType = E_SECTIONTYPE.LOGIC_STARTLINE;
                        break;

                    case E_SECTIONTYPE.LOGIC_STARTLINE:
                        currentSectionType = E_SECTIONTYPE.JUNCTION_START;
                        break;

                    case E_SECTIONTYPE.JUNCTION_START:
                        currentSectionType = E_SECTIONTYPE.JUNCTION_END;
                        break;

                    case E_SECTIONTYPE.JUNCTION_END:
                        currentSectionType = E_SECTIONTYPE.JUMP_START;
                        break;

                    case E_SECTIONTYPE.JUMP_START:
                        currentSectionType = E_SECTIONTYPE.JUMP_END;
                        break;

                    case E_SECTIONTYPE.JUMP_END:
                        currentSectionType = E_SECTIONTYPE.PITLANE_ENTRANCE;
                        break;

                    case E_SECTIONTYPE.PITLANE_ENTRANCE:
                        currentSectionType = E_SECTIONTYPE.NORMAL;
                        break;
                    }
                }
            }

            // raycast from scene view mouse position
            RaycastHit hit;
            Ray        ray   = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
            Mesh       m     = thisTarget.DATA_FE.MESH_TRACKFLOOR.sharedMesh;
            GUIStyle   label = new GUIStyle();

            label.fontStyle = FontStyle.Bold;
            if (Physics.Raycast(ray, out hit, 1 << LayerMask.NameToLayer("TrackFloor")))
            {
                TrTile tile = TrackDataHelper.TileFromTriangleIndex(hit.triangleIndex, E_TRACKMESH.FLOOR, thisTarget.TRACK_DATA);

                if (thisTarget.DATA_FE.PAINT_MODE == E_PAINTMODE.TILE)
                {
                    // draw mesh
                    Vector3[] verts = new Vector3[4];
                    int       t     = hit.triangleIndex * 3;

                    verts[0] = hit.transform.TransformPoint(m.vertices[m.triangles[t + 0]]);
                    verts[1] = hit.transform.TransformPoint(m.vertices[m.triangles[t + 1]]);
                    verts[2] = hit.transform.TransformPoint(m.vertices[m.triangles[t + 2]]);
                    verts[3] = hit.transform.TransformPoint(m.vertices[m.triangles[t + 0]]);

                    // change mesh color depending on face type
                    Color col     = Color.grey;
                    Color outline = col;

                    switch (tile.TILE_TYPE)
                    {
                    case E_TILETYPE.BOOST:
                        col = Color.blue;
                        break;

                    case E_TILETYPE.WEAPON:
                        col = Color.red;
                        break;

                    case E_TILETYPE.SPAWN:
                        col = Color.yellow;
                        break;

                    case E_TILETYPE.RECHARGE:
                        col = Color.green;
                        break;
                    }

                    switch (currentTileType)
                    {
                    case E_TILETYPE.BOOST:
                        outline = Color.blue;
                        break;

                    case E_TILETYPE.WEAPON:
                        outline = Color.red;
                        break;

                    case E_TILETYPE.SPAWN:
                        outline = Color.yellow;
                        break;

                    case E_TILETYPE.RECHARGE:
                        outline = Color.green;
                        break;
                    }

                    outline *= 0.8f;
                    col.a    = 0.2f;

                    Handles.DrawSolidRectangleWithOutline(verts, col, outline);

                    // draw label
                    string flip = tile.TILE_SECOND ? "Flipped" : "Normal";

                    Vector3 pos = tile.TILE_POSITION;
                    col.a = 1.0f;
                    label.normal.textColor = col;
                    Handles.Label(pos, "Current = " + tile.TILE_TYPE.ToString() + "_" + flip, label);

                    pos      += tile.TILE_SECTION.SECTION_NORMAL * 0.4f;
                    outline.a = 1.0f;
                    label.normal.textColor = outline;
                    Handles.Label(pos, "Paint = " + currentTileType.ToString() + "_" + flip, label);

                    if (Event.current.type == EventType.mouseUp && Event.current.button == 0)
                    {
                        // apply change
                        tile.TILE_TYPE = currentTileType;

                        // cache change
                        thisTarget.DATA_FE.CACHE_TILES[tile.TILE_INDEX] = currentTileType;
                    }
                    else if (Event.current.type == EventType.keyDown && Event.current.keyCode == KeyCode.R)
                    {
                        // apply change
                        tile.TILE_TYPE = E_TILETYPE.FLOOR;

                        // cache change
                        thisTarget.DATA_FE.CACHE_TILES[tile.TILE_INDEX] = currentTileType;
                    }
                }
                else if (thisTarget.DATA_FE.PAINT_MODE == E_PAINTMODE.SECTION)
                {
                    thisTarget.DATA_FE.highlightedSection = tile.TILE_SECTION;

                    // change mesh color depending on section type
                    Color col     = Color.grey;
                    Color outline = col;

                    switch (tile.TILE_SECTION.SECTION_TYPE)
                    {
                    case E_SECTIONTYPE.JUMP_START:
                        col = Color.green;
                        break;

                    case E_SECTIONTYPE.JUMP_END:
                        col  = Color.green;
                        col *= 0.5f;
                        break;

                    case E_SECTIONTYPE.JUNCTION_START:
                        col = Color.red;
                        break;

                    case E_SECTIONTYPE.JUNCTION_END:
                        col  = Color.red;
                        col *= 0.5f;
                        break;

                    case E_SECTIONTYPE.LOGIC_STARTLINE:
                        col = Color.blue;
                        break;

                    case E_SECTIONTYPE.PITLANE_ENTRANCE:
                        col = Color.yellow;
                        break;
                    }

                    switch (currentSectionType)
                    {
                    case E_SECTIONTYPE.JUMP_START:
                        outline = Color.green;
                        break;

                    case E_SECTIONTYPE.JUMP_END:
                        outline  = Color.green;
                        outline *= 0.5f;
                        break;

                    case E_SECTIONTYPE.JUNCTION_START:
                        outline = Color.red;
                        break;

                    case E_SECTIONTYPE.JUNCTION_END:
                        outline  = Color.red;
                        outline *= 0.5f;
                        break;

                    case E_SECTIONTYPE.LOGIC_STARTLINE:
                        outline = Color.blue;
                        break;

                    case E_SECTIONTYPE.PITLANE_ENTRANCE:
                        outline = Color.yellow;
                        break;
                    }

                    outline *= 0.8f;

                    outline.a = 1.0f;
                    col.a     = 1.0f;

                    Vector3 pos = tile.TILE_SECTION.SECTION_POSITION;
                    label.normal.textColor = col;
                    Handles.Label(pos, "Current = " + tile.TILE_SECTION.SECTION_TYPE.ToString(), label);

                    pos += tile.TILE_SECTION.SECTION_NORMAL * 0.4f;
                    label.normal.textColor = outline;
                    Handles.Label(pos, "Paint = " + currentSectionType.ToString(), label);

                    if (Event.current.type == EventType.mouseUp && Event.current.button == 0)
                    {
                        // apply change
                        tile.TILE_SECTION.SECTION_TYPE = currentSectionType;

                        // cache change
                        thisTarget.DATA_FE.CACHE_SECTIONS[tile.TILE_SECTION.SECTION_INDEX] = currentSectionType;
                    }
                }
            }
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
        EditorGUI.BeginProperty(position, label, property);

        Rect foldoutRect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight);

        property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, property.isExpanded ? "Hide" : "Show");

        if (property.isExpanded)
        {
            EditorGUI.indentLevel       = 0;
            EditorGUIUtility.labelWidth = 0.1f;

            SerializedProperty propIsRoom = property.FindPropertyRelative("IsRoom");
            Rect rectIsRoomLabel          = new Rect(position.x, position.y + EditorGUIUtility.singleLineHeight * 1.5f, position.width * 0.33f, EditorGUIUtility.singleLineHeight);
            Rect rectIsRoom = new Rect(position.x + rectIsRoomLabel.width, position.y + EditorGUIUtility.singleLineHeight * 1.5f, position.width * 0.66f, EditorGUIUtility.singleLineHeight);
            EditorGUI.LabelField(rectIsRoomLabel, "Is Room?");
            propIsRoom.boolValue = EditorGUI.Toggle(rectIsRoom, label, propIsRoom.boolValue);

            SerializedProperty propBlock  = property.FindPropertyRelative(isShowingBack ? "BlockBack" : "BlockFront");
            SerializedProperty propLine   = property.FindPropertyRelative(isShowingBack ? "LineBack" : "LineFront");
            SerializedProperty propSingle = property.FindPropertyRelative(isShowingBack ? "SingleBack" : "SingleFront");

            if (propBlock.arraySize != TileAssetBlock.MAX_WIDTH)
            {
                propBlock.arraySize = TileAssetBlock.MAX_WIDTH;
            }
            if (propLine.arraySize != TileAssetBlock.MAX_WIDTH)
            {
                propLine.arraySize = TileAssetBlock.MAX_WIDTH;
            }

            for (int x = 0; x < TileAssetBlock.MAX_WIDTH; x++)
            {
                SerializedProperty propBlockData = propBlock.GetArrayElementAtIndex(x).FindPropertyRelative("Data");
                if (propBlockData.arraySize != TileAssetBlock.MAX_HEIGHT)
                {
                    propBlockData.arraySize = TileAssetBlock.MAX_HEIGHT;
                }

                for (int y = 0; y < TileAssetBlock.MAX_HEIGHT; y++)
                {
                    SerializedProperty propElement = propBlockData.GetArrayElementAtIndex(y);
                    DrawField(propBlockData.GetArrayElementAtIndex(y), x, y, property, position);
                }

                DrawField(propLine.GetArrayElementAtIndex(x), x, TileAssetBlock.MAX_HEIGHT + 0.5f, property, position);
            }

            DrawField(propSingle, 0, TileAssetBlock.MAX_HEIGHT + 2.0f, property, position);

            Rect buttonRect = new Rect(position.x, position.y + GetPropertyHeight(property, label) - EditorGUIUtility.singleLineHeight * 2, position.width, EditorGUIUtility.singleLineHeight);
            if (isShowingBack && GUI.Button(buttonRect, "Show Front"))
            {
                isShowingBack = false;
            }
            else if (!isShowingBack && GUI.Button(buttonRect, "Show Back"))
            {
                isShowingBack = true;
            }
        }

        EditorGUI.EndProperty();
    }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            List <string> validTags = new List <string>();
            List <string> layerTags = new List <string>();

            layerTags.Add(FilterTag.DefaultTag);

            // Find all focus layers in scene
            InteractibleObject[] interactibleObjects = FilterTagDrawer.GetAllInteractibleObjects();

            // Get all layer tags from interactible objects
            for (int i = 0; i < interactibleObjects.Length; ++i)
            {
                InteractibleObject interactibleObject = interactibleObjects[i];
                if (interactibleObject != null && interactibleObject.FilterTag != null)
                {
                    string tag = interactibleObject.FilterTag.Tag;

                    if (!string.IsNullOrEmpty(tag) && !layerTags.Contains(tag))
                    {
                        layerTags.Add(tag);
                    }


                    // Get all layer tags from other components on interactible objects
                    Component[] accompanyingComponents = interactibleObject.GetComponents <Component>();
                    for (int j = 0; j < accompanyingComponents.Length; j++)
                    {
                        if (accompanyingComponents[j] == interactibleObject || accompanyingComponents[j] == null)
                        {
                            continue;
                        }

                        foreach (FieldInfo field in accompanyingComponents[j].GetType().GetFields())
                        {
                            if (field.IsPublic && field.FieldType == typeof(FilterTag))
                            {
                                FilterTag fieldFilterTag = (FilterTag)field.GetValue(accompanyingComponents[j]);
                                if (fieldFilterTag != null && !string.IsNullOrEmpty(fieldFilterTag.Tag))
                                {
                                    layerTags.Add(fieldFilterTag.Tag);
                                }
                            }
                        }
                    }
                }
            }

            // Sort alphabetically
            layerTags.Sort();

            EditorGUI.BeginProperty(position, label, property);
            int indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            // Label
            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            // Get the valid tags property
            SerializedProperty currentValidTagsProperty = property.FindPropertyRelative("ValidTags");

            // Add the current tags to the list
            for (int i = 0; i < currentValidTagsProperty.arraySize; ++i)
            {
                validTags.Add(currentValidTagsProperty.GetArrayElementAtIndex(i).stringValue);
            }

            // Get the current selected mask from the tags
            int mask = 0;

            for (int i = 0; i < layerTags.Count; ++i)
            {
                if (validTags.Contains(layerTags[i]))
                {
                    mask |= 1 << i;
                }
            }

            // Draw the mask feild
            Rect rect = new Rect(position.x, position.y, 150, 18);

            mask = EditorGUI.MaskField(rect, mask, layerTags.ToArray());

            // Get the new valid tags - the mask has changed
            validTags.Clear();
            for (int i = 0; i < layerTags.Count; ++i)
            {
                if ((mask & 1 << i) != 0)
                {
                    validTags.Add(layerTags[i]);
                }
            }

            // Set the tags
            currentValidTagsProperty.ClearArray();
            currentValidTagsProperty.arraySize = validTags.Count;

            for (int i = 0; i < currentValidTagsProperty.arraySize; ++i)
            {
                currentValidTagsProperty.GetArrayElementAtIndex(i).stringValue = validTags[i];
            }

            EditorGUI.indentLevel = indent;
            EditorGUI.EndProperty();
        }
Example #7
0
            private void AddLanPairFunc()
            {
                if (window.lanKeys.Count == 0)
                {
                    return;
                }
                Rect rect;

                this.EBeginHorizontal(out rect, Styles.Fold)
                .Foldout(ref createLanPairFlodon, "Create LanPair", true)
                .EEndHorizontal()
                .Pan(() =>
                {
                    if (!createLanPairFlodon)
                    {
                        return;
                    }
                    if (tmpLanPair == null)
                    {
                        tmpLanPair = new LanPair()
                        {
                            key = window.lanKeys[0]
                        }
                    }
                    ;
                    if (hashID == 0)
                    {
                        hashID = "CreateView".GetHashCode();
                    }
                    this.DrawVertical(() =>
                    {
                        this.BeginHorizontal()
                        .Label("Lan", GUILayout.Width(describeWidth))
                        .Pan(() => { tmpLanPair.lan = (SystemLanguage)EditorGUILayout.EnumPopup(tmpLanPair.lan); })
                        .EndHorizontal()
                        .BeginHorizontal()
                        .Label("Key", GUILayout.Width(describeWidth))
                        .Label(tmpLanPair.key)
                        .Label(EditorGUIUtility.IconContent("editicon.sml"), GUILayout.Width(smallBtnSize))
                        .EndHorizontal()
                        .Pan(() => {
                            Rect pos   = GUILayoutUtility.GetLastRect();
                            int ctrlId = GUIUtility.GetControlID(hashID, FocusType.Keyboard, pos);
                            {
                                if (DropdownButton(ctrlId, pos, new GUIContent(string.Format("Key: {0}", tmpLanPair.key))))
                                {
                                    int index = -1;
                                    for (int i = 0; i < window.lanKeys.Count; i++)
                                    {
                                        if (window.lanKeys[i] == tmpLanPair.key)
                                        {
                                            index = i; break;
                                        }
                                    }
                                    SearchablePopup.Show(pos, window.lanKeys.ToArray(), index, (i, str) =>
                                    {
                                        tmpLanPair.key = str;
                                        window.Repaint();
                                    });
                                }
                            }
                        })
                        .BeginHorizontal()
                        .Label("Val", GUILayout.Width(describeWidth))
                        .TextField(ref tmpLanPair.value)
                        .EndHorizontal()
                        .BeginHorizontal()
                        .FlexibleSpace()
                        .Button(() => {
                            //createLanPairFlodon = false;
                            window.AddLanPair(tmpLanPair);
                            //tmpLanPair = null;
                        }, Contents.OK)
                        .EndHorizontal();
                    }, Styles.BG);
                });
            }
Example #8
0
        public static float TextureScaleHandle(Vector3 position, Quaternion rotation, float handleSize, Handles.DrawCapFunction capfunc)
        {
            int id = GUIUtility.GetControlID(TexturePositionHandleXHash, FocusType.Passive);

            lastDragHandleId = id;
            Vector3 startScreenPosition   = Handles.matrix.MultiplyPoint(position);
            Vector3 pointerScreenPosition = position + (rotation * Vector3.forward * handleSize * 10);
//			Vector3 pointerScreenPosition = Handles.matrix.MultiplyPoint(position + (rotation * Vector3.forward * handleSize * 10));
            //			Vector3 screenDirectionVector = (pointerScreenPosition - startScreenPosition);
            Matrix4x4 cachedMatrix = Handles.matrix;

            float returnValue = 0f;

            switch (Event.current.GetTypeForControl(id))
            {
            case EventType.KeyDown:
                if (!holdingCtrl)
                {
                    if (Event.current.keyCode == KeyCode.LeftControl)
                    {
                        holdingCtrl = true;
                        stepBuffer  = 0f;
                    }
                    else
                    {
                        holdingCtrl = false;
                        stepBuffer  = 0f;
                    }
                }
                break;

            case EventType.KeyUp:
                holdingCtrl = false;
                stepBuffer  = 0f;
                break;

            case EventType.MouseDown:
                if (HandleUtility.nearestControl == id && Event.current.button == 0)
                {
                    GUIUtility.hotControl = id;
                    dragHandleMousePos    = Event.current.mousePosition;
//					dragHandleMousePos.y = TextureTilingEditorWindow.sceneCamera.pixelHeight - Event.current.mousePosition.y;
                    //Debug.Log ("mouse down dragHandleMousePos: " + dragHandleMousePos);
                    Event.current.Use();
                    EditorGUIUtility.SetWantsMouseJumping(1);
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == id && Event.current.button == 0)
                {
                    GUIUtility.hotControl = 0;
                    dragHandleMousePos    = Event.current.mousePosition;
//					dragHandleMousePos.y = TextureTilingEditorWindow.sceneCamera.pixelHeight - Event.current.mousePosition.y;
                    //Debug.Log ("mouse up dragHandleMousePos: " + dragHandleMousePos);
                    Event.current.Use();
                    EditorGUIUtility.SetWantsMouseJumping(0);
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == id)
                {
                    Vector2 newMousePos = Event.current.mousePosition;
//					newMousePos.y = TextureTilingEditorWindow.sceneCamera.pixelHeight - Event.current.mousePosition.y;
                    Vector2 dragDelta = newMousePos - dragHandleMousePos;
                    dragDelta.y *= -1f;
                    Vector2 screenDirectionVector = Camera.current.WorldToScreenPoint(pointerScreenPosition) - Camera.current.WorldToScreenPoint(startScreenPosition);
                    if ((screenDirectionVector + dragDelta).sqrMagnitude > screenDirectionVector.sqrMagnitude)
                    {
                        returnValue = (newMousePos - dragHandleMousePos).magnitude / 100f;
                    }
                    else
                    {
                        returnValue = (newMousePos - dragHandleMousePos).magnitude / (-100f);
                    }
                    if (holdingCtrl)
                    {
                        stepBuffer += returnValue;
                        if (Mathf.Abs(stepBuffer) >= TextureTilingEditorWindow.scaleStepSize)
                        {
                            returnValue = TextureTilingEditorWindow.scaleStepSize * Mathf.Sign(stepBuffer);
                            stepBuffer  = 0f;
                        }
                        else
                        {
                            returnValue = 0f;
                        }
                    }
//					Debug.Log ("old dragHandleMousePos: " + dragHandleMousePos);
//					Debug.Log ("Scale Delta: " + returnValue);
                    dragHandleMousePos = newMousePos;
//					Debug.Log ("new dragHandleMousePos: " + dragHandleMousePos);

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

            case EventType.Repaint:
                Color currentColor = Handles.color;
                if (GUIUtility.hotControl == id)
                {
                    Handles.color = Handles.selectedColor;
                }
                Handles.matrix = Matrix4x4.identity;
//				Vector3 handlePosition = position + (rotation * Vector3.forward * handleSize * 10);
                Handles.DrawLine(position, pointerScreenPosition);
//				Handles.BeginGUI();
//				EditorGUI.LabelField(new Rect(dragHandleMousePos.x, dragHandleMousePos.y, 100, 50), "Mouse Pos");
//				Handles.EndGUI();
                capfunc(id, pointerScreenPosition, rotation, handleSize * 1.25f);
                Handles.matrix = cachedMatrix;
                Handles.color  = currentColor;
                break;

            case EventType.Layout:
                Handles.matrix = Matrix4x4.identity;
                HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(pointerScreenPosition, 5 * handleSize));
                Handles.matrix = cachedMatrix;
                break;
            }
            return(returnValue);
        }
Example #9
0
        public static void OnSceneGUI(SceneView sceneview)
        {
            int dragBoneControlId = GUIUtility.GetControlID(FocusType.Passive);

            switch (Event.current.GetTypeForControl(dragBoneControlId))
            {
            case EventType.MouseMove:

                Bone2D bone = GetClosestBone(Event.current.mousePosition, 10f);

                if (bone != s_HoveredBone)
                {
                    s_HoveredBone = bone;
                    SceneView.RepaintAll();
                }

                break;

            case EventType.MouseDown:

                if (!ToolsExtra.viewToolActive &&
                    HandleUtility.nearestControl == dragBoneControlId &&
                    Event.current.button == 0)
                {
                    s_SelectedBone = s_HoveredBone;
                    Undo.IncrementCurrentGroup();

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

                break;

            case EventType.MouseUp:

                if (s_SelectedBone &&
                    GUIUtility.hotControl == dragBoneControlId &&
                    Event.current.button == 0)
                {
                    Selection.activeGameObject = s_SelectedBone.gameObject;

                    GUIUtility.hotControl = 0;
                    s_SelectedBone        = null;

                    Event.current.Use();
                }

                break;

            case EventType.MouseDrag:

                if (s_SelectedBone &&
                    GUIUtility.hotControl == dragBoneControlId &&
                    Event.current.button == 0)
                {
                    Ray   ray   = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                    Plane plane = new Plane(s_SelectedBone.transform.forward, s_SelectedBone.transform.position);
                    float distance;
                    if (plane.Raycast(ray, out distance))
                    {
                        Vector3 point = ray.GetPoint(distance);
                        float   angle = AngleAroundAxis(s_SelectedBone.transform.right, point - s_SelectedBone.transform.position, s_SelectedBone.transform.forward);

                        Vector3 eulerAngles = s_SelectedBone.transform.localEulerAngles;
                        eulerAngles.z += angle;

                        Undo.RecordObject(s_SelectedBone.transform, "Rotate");
                        s_SelectedBone.transform.localRotation = Quaternion.Euler(eulerAngles);

                        IkUtils.UpdateIK(s_SelectedBone, "Rotate");
                    }

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

                break;

            case EventType.Repaint:

                DrawBoneGizmos();

                break;

            case EventType.Layout:

                if (!ToolsExtra.viewToolActive && s_HoveredBone)
                {
                    float   radius         = BoneUtils.GetBoneRadius(s_HoveredBone);
                    Vector3 direction      = (s_HoveredBone.endPosition - s_HoveredBone.transform.position).normalized;
                    Vector2 screenPosition = HandleUtility.WorldToGUIPoint(s_HoveredBone.transform.position);

                    Vector3 endPoint = s_HoveredBone.endPosition - direction * radius;

                    if (s_HoveredBone.child)
                    {
                        endPoint -= direction * BoneUtils.GetBoneRadius(s_HoveredBone.child);
                    }

                    Vector2 screenEndPosition = HandleUtility.WorldToGUIPoint(endPoint);

                    float distance = MathUtils.SegmentDistance(Event.current.mousePosition, screenPosition, screenEndPosition);

                    HandleUtility.AddControl(dragBoneControlId, distance * 0.49f);
                }

                break;
            }
        }
Example #10
0
        public static float TextureRotationHandle(Vector3 position, Quaternion baseOrientation, Vector3 normal, Vector3 nullForward, float currentRotation, float handleSize, Handles.DrawCapFunction capfunc)
        {
            int id = GUIUtility.GetControlID(TexturePositionHandleXHash, FocusType.Passive);

            lastDragHandleId = id;
//			Vector3 startScreenPosition = Handles.matrix.MultiplyPoint(position);
            Vector3 pointerScreenPosition = Handles.matrix.MultiplyPoint(position + (baseOrientation * Vector3.forward * handleSize * 10));
            //			Vector3 screenDirectionVector = (pointerScreenPosition - startScreenPosition);
            Matrix4x4 cachedMatrix = Handles.matrix;

            float returnValue = 0f;

            normal.Normalize();
            nullForward.Normalize();

            switch (Event.current.GetTypeForControl(id))
            {
            case EventType.KeyDown:
                if (!holdingCtrl)
                {
                    if (Event.current.keyCode == KeyCode.LeftControl)
                    {
                        rotationStepStartPoint = currentRotation;
                        holdingCtrl            = true;
                    }
                    else
                    {
                        holdingCtrl            = false;
                        rotationStepStartPoint = 0f;
                    }
                }
                break;

            case EventType.KeyUp:
                holdingCtrl            = false;
                rotationStepStartPoint = 0f;
                break;

            case EventType.MouseDown:
                if (HandleUtility.nearestControl == id && Event.current.button == 0)
                {
                    GUIUtility.hotControl = id;
                    dragHandleMousePos    = Event.current.mousePosition;
                    Event.current.Use();
                    EditorGUIUtility.SetWantsMouseJumping(1);
                }
                break;

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

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == id)
                {
//					ATTHandles.currentRotation = currentRotation;
                    Vector2 newMousePos = Event.current.mousePosition;
                    newMousePos.y = TextureTilingEditorWindow.sceneCamera.pixelHeight - Event.current.mousePosition.y;
//					Debug.Log ("newMousePos = " + newMousePos);
//					Debug.Log ("Raycast Plane: " + raycastPlane..ToString());
//					Plane raycastPlane = new Plane(normal, position);
                    float distance;
                    Ray   rayCastRay = TextureTilingEditorWindow.sceneCamera.ScreenPointToRay(newMousePos);
                    if (new Plane(normal, position).Raycast(rayCastRay, out distance))
                    {
                        positionInWorld = rayCastRay.GetPoint(distance);                         //TextureTilingEditorWindow.sceneCamera.ScreenToWorldPoint(new Vector3(newMousePos.x, newMousePos.y, distance));
//						positionInWorld.y = (position + nullForward).y;
                        Vector3 referenceRight        = Vector3.Cross(normal, nullForward).normalized;
                        Vector3 currentRotationVector = (positionInWorld - position).normalized;
//						float angle = Vector3.Angle(nullForward, currentRotationVector);
//						float sign = 0f;
//						float dot = Vector3.Dot(referenceRight, currentRotationVector);
//						if (dot > 0) {
//							sign = -1f;
//						}
//						else {
//							sign = 1f;
//						}
                        returnValue = -1f * Mathf.Sign(Vector3.Dot(referenceRight, currentRotationVector)) * Vector3.Angle(nullForward, currentRotationVector);
                        if (holdingCtrl)
                        {
                            float diff = returnValue - rotationStepStartPoint;
                            while (diff < 0f)
                            {
                                diff += 360f;
                            }
                            while (diff > 180f)
                            {
                                diff -= 360f;
                            }
                            Debug.Log("Raw diff: " + diff);
                            if (diff >= 180f)
                            {
                                if (rotationStepStartPoint < 180f)
                                {
                                    diff = (returnValue - 360f) - rotationStepStartPoint;
                                }
                                else if (rotationStepStartPoint > 180f)
                                {
                                    diff = returnValue - (rotationStepStartPoint - 360f);
                                }
                            }
                            Debug.Log("Modified diff: " + diff);
                            if (Mathf.Abs(diff) >= TextureTilingEditorWindow.rotationStepSize)
                            {
                                if (diff > 0)
                                {
                                    returnValue = rotationStepStartPoint + TextureTilingEditorWindow.rotationStepSize;
                                    while (returnValue >= 360f)
                                    {
                                        returnValue -= 360f;
                                    }
                                    rotationStepStartPoint = returnValue;
                                }
                                else if (diff < 0)
                                {
                                    returnValue = rotationStepStartPoint - TextureTilingEditorWindow.rotationStepSize;
                                    while (returnValue < 0f)
                                    {
                                        returnValue += 360f;
                                    }
                                    rotationStepStartPoint = returnValue;
                                }
                            }
                            else
                            {
                                returnValue = rotationStepStartPoint;
                            }
                            Debug.Log("rotationStepStartPoint: " + rotationStepStartPoint);
                            Debug.Log("returnValue: " + returnValue);
                        }
//						Debug.Log("Raw Agnle: " + angle);
//						Debug.Log("sign: " + sign);
//						Debug.Log("New Angle: " + returnValue);
                    }
                    else
                    {
                        Debug.LogError("How can you NOT hit a plane??");
                    }
//					Debug.Log ("positionInWorld = " + positionInWorld);
//					float angle = Vector3.Angle(nullForward, positionInWorld);
//					Debug.Log ("angle = " + angle);
//					Vector2 dragDelta = newMousePos - dragHandleMousePos;
//					dragDelta.y *= -1f;
//					Vector2 screenDirectionVector = Camera.current.WorldToScreenPoint(pointerScreenPosition) - Camera.current.WorldToScreenPoint(startScreenPosition);
//					if ((screenDirectionVector + dragDelta).sqrMagnitude > screenDirectionVector.sqrMagnitude) {
//						returnValue += (newMousePos - dragHandleMousePos).magnitude / 500f;
//					}
//					else {
//						returnValue += (newMousePos - dragHandleMousePos).magnitude / (-500f);
//					}
//					returnValue = angle;

                    dragHandleMousePos = newMousePos;

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

            case EventType.Repaint:
                Color currentColor = Handles.color;
                if (GUIUtility.hotControl == id)
                {
                    Handles.color = Handles.selectedColor;
                }
                Handles.matrix = Matrix4x4.identity;
                Vector3 handlePosition = position + (baseOrientation * Vector3.forward * handleSize * 10);
                Handles.DrawLine(position, handlePosition);
                capfunc(id, handlePosition, baseOrientation, handleSize * 2);
//				Handles.DrawLine (position, positionInWorld);
//				Handles.DrawSolidDisc (positionInWorld, normal, 0.1f);
                Handles.matrix = cachedMatrix;
                Handles.color  = currentColor;
//				Handles.DrawLine (position, position + normal);
                break;

            case EventType.Layout:
                Handles.matrix = Matrix4x4.identity;
                HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(pointerScreenPosition, 5 * handleSize));
                Handles.matrix = cachedMatrix;
                break;
            }

            return(returnValue);
        }
Example #11
0
        public static float TexturePositionHandle(Vector3 position, Quaternion rotation, float handleSize, Handles.DrawCapFunction capfunc)
        {
            int id = GUIUtility.GetControlID(TexturePositionHandleXHash, FocusType.Passive);

            lastDragHandleId = id;
            Vector3 startScreenPosition   = Handles.matrix.MultiplyPoint(position);
            Vector3 pointerScreenPosition = Handles.matrix.MultiplyPoint(position + (rotation * Vector3.forward * handleSize));
//			Vector3 screenDirectionVector = (pointerScreenPosition - startScreenPosition);
            Matrix4x4 cachedMatrix = Handles.matrix;

            float returnValue = 0f;

            switch (Event.current.GetTypeForControl(id))
            {
            case EventType.MouseDown:
                if (HandleUtility.nearestControl == id && Event.current.button == 0)
                {
                    GUIUtility.hotControl = id;
                    dragHandleMousePos    = Event.current.mousePosition;
                    Event.current.Use();
                    EditorGUIUtility.SetWantsMouseJumping(1);
                }
                break;

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

            case EventType.KeyDown:
                if (!holdingCtrl)
                {
                    if (Event.current.keyCode == KeyCode.LeftControl)
                    {
                        holdingCtrl = true;
                        stepBuffer  = 0f;
                    }
                    else
                    {
                        holdingCtrl = false;
                        stepBuffer  = 0f;
                    }
                }
                break;

            case EventType.KeyUp:
                holdingCtrl = false;
                stepBuffer  = 0f;
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == id)
                {
                    Vector2 newMousePos = Event.current.mousePosition;
                    Vector2 dragDelta   = newMousePos - dragHandleMousePos;
                    dragDelta.y *= -1f;
                    Vector2 screenDirectionVector = Camera.current.WorldToScreenPoint(pointerScreenPosition) - Camera.current.WorldToScreenPoint(startScreenPosition);
                    if ((screenDirectionVector + dragDelta).sqrMagnitude > screenDirectionVector.sqrMagnitude)
                    {
                        returnValue = (newMousePos - dragHandleMousePos).magnitude / 500f;
                    }
                    else
                    {
                        returnValue = (newMousePos - dragHandleMousePos).magnitude / (-500f);
                    }
                    if (holdingCtrl)
                    {
                        stepBuffer += returnValue;
                        if (Mathf.Abs(stepBuffer) >= TextureTilingEditorWindow.offsetStepSize)
                        {
                            returnValue = TextureTilingEditorWindow.offsetStepSize * Mathf.Sign(stepBuffer);
                            stepBuffer  = 0f;
                        }
                        else
                        {
                            returnValue = 0f;
                        }
                    }
                    dragHandleMousePos = newMousePos;
                    GUI.changed        = true;
                    Event.current.Use();
                }
                break;

            case EventType.Repaint:
                Color currentColor = Handles.color;
                if (GUIUtility.hotControl == id)
                {
                    Handles.color = Handles.selectedColor;
                }
                Handles.matrix = Matrix4x4.identity;
                capfunc(id, startScreenPosition, rotation, handleSize);
                Handles.matrix = cachedMatrix;
                Handles.color  = currentColor;
                break;

            case EventType.Layout:
                Handles.matrix = Matrix4x4.identity;
                HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(pointerScreenPosition, handleSize / 2f));
                Handles.matrix = cachedMatrix;
                break;
            }

            return(returnValue);
        }
Example #12
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);

        Vector3[] corners = mWidget.worldCorners;

        Handles.color = handlesColor;
        Handles.DrawLine(corners[0], corners[1]);
        Handles.DrawLine(corners[1], corners[2]);
        Handles.DrawLine(corners[2], corners[3]);
        Handles.DrawLine(corners[0], corners[3]);

        Vector3[] worldPos = new Vector3[8];

        worldPos[0] = corners[0];
        worldPos[1] = corners[1];
        worldPos[2] = corners[2];
        worldPos[3] = corners[3];

        worldPos[4] = (corners[0] + corners[1]) * 0.5f;
        worldPos[5] = (corners[1] + corners[2]) * 0.5f;
        worldPos[6] = (corners[2] + corners[3]) * 0.5f;
        worldPos[7] = (corners[0] + corners[3]) * 0.5f;

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

        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (actionUnderMouse == Action.None)
        {
            int   index = 0;
            float dist  = GetScreenDistance(worldPos, e.mousePosition, out index);

            if (mWidget.canResize && dist < 10f)
            {
                pivotUnderMouse  = mPivots[index];
                actionUnderMouse = Action.Scale;
            }
            else if (e.modifiers == 0 && NGUIEditorTools.SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f)
            {
                actionUnderMouse = Action.Move;
            }
            else if (dist < 30f)
            {
                actionUnderMouse = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
        {
            Vector2[] screenPos = new Vector2[8];
            for (int i = 0; i < 8; ++i)
            {
                screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
            }

            Bounds b = new Bounds(screenPos[0], Vector3.zero);
            for (int i = 1; i < 8; ++i)
            {
                b.Encapsulate(screenPos[i]);
            }

            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (actionUnderMouse == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (actionUnderMouse == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (actionUnderMouse == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else
            {
                SetCursorRect(rect, MouseCursor.Arrow);
            }
        }
#endif

        switch (type)
        {
        case EventType.Repaint:
        {
            Handles.BeginGUI();
            {
                for (int i = 0; i < 8; ++i)
                {
                    DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], mWidget.canResize, 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(corners, out mStartDrag))
            {
                mStartPos             = t.position;
                mStartRot             = t.localRotation.eulerAngles;
                mStartDir             = mStartDrag - t.position;
                mStartWidth           = mWidget.width;
                mStartHeight          = mWidget.height;
                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(corners, 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)
                                {
                                    mStartPos = t.position;
                                    NGUIEditorTools.RegisterUndo("Move widget", t);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                    NGUIEditorTools.RegisterUndo("Rotate widget", t);
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartPos    = t.localPosition;
                                    mStartWidth  = mWidget.width;
                                    mStartHeight = mWidget.height;
                                    mDragPivot   = pivotUnderMouse;
                                    NGUIEditorTools.RegisterUndo("Scale widget", t);
                                    NGUIEditorTools.RegisterUndo("Scale widget", mWidget);
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            if (mAction == Action.Move)
                            {
                                t.position      = mStartPos + (pos - mStartDrag);
                                pos             = t.localPosition;
                                pos.x           = Mathf.Round(pos.x);
                                pos.y           = Mathf.Round(pos.y);
                                pos.z           = Mathf.Round(pos.z);
                                t.localPosition = pos;
                            }
                            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;
                                    if (e.modifiers != EventModifiers.Shift)
                                    {
                                        angle = Mathf.Round(angle / 15f) * 15f;
                                    }
                                    else
                                    {
                                        angle = Mathf.Round(angle);
                                    }
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == 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
                                AdjustPosAndScale(mWidget, mStartPos, mStartWidth, mStartHeight, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        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: Select the widget below
                        NGUIEditorTools.SelectWidgetOrContainer(mWidget.gameObject, e.mousePosition, false);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the widget above
                            NGUIEditorTools.SelectWidgetOrContainer(mWidget.gameObject, e.mousePosition, true);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        mAction           = Action.None;
                        mActionUnderMouse = Action.None;
                        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)
                    {
                        mActionUnderMouse = Action.None;
                        mAction           = Action.None;
                        e.Use();
                    }
                }
            }
            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)
            {
                Vector3 pos = t.localPosition;
                pos.y          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        if (mAction == Action.Move)
                        {
                            t.position = mStartPos;
                        }
                        else if (mAction == Action.Rotate)
                        {
                            t.localRotation = Quaternion.Euler(mStartRot);
                        }
                        else if (mAction == Action.Scale)
                        {
                            t.position     = mStartPos;
                            mWidget.width  = mStartWidth;
                            mWidget.height = mStartHeight;
                        }
                    }

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

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Example #13
0
        protected void OnTimeRulerCursorAndCutOffCursorInput()
        {
            //
            // Mouse drag for cut off guideline
            //
            float timeToPos    = TimeToPixel(this.CutOffTime);
            Rect  cutOffRect   = new Rect(-ARROW_WIDTH + timeToPos - _rectTimeAreaRuler.x, base.position.height - ARROW_WIDTH * 2 - toolbarHeight, ARROW_WIDTH * 2, ARROW_WIDTH * 2);
            Event evt          = Event.current;
            int   controlId    = GUIUtility.GetControlID(kBlueCursorControlID, FocusType.Passive);
            int   redControlId = GUIUtility.GetControlID(kRedCursorControlID, FocusType.Passive);

            if (evt.rawType == EventType.MouseUp)
            {
                if (GUIUtility.hotControl == controlId || GUIUtility.hotControl == redControlId)
                {
                    GUIUtility.hotControl = 0;
                    evt.Use();
                }
                _dragCutOffTimeArrow = false;
            }
            Vector2 mousePos = new Vector2(evt.mousePosition.x - _rectTimeAreaTotal.x, evt.mousePosition.y - _rectTimeAreaTotal.y);

            if (!Application.isPlaying)
            {
                switch (evt.GetTypeForControl(controlId))
                {
                case EventType.MouseDown:
                {
                    if (cutOffRect.Contains(mousePos))
                    {
                        GUIUtility.hotControl = controlId;
                        evt.Use();
                    }
                }
                break;

                case EventType.MouseDrag:
                {
                    if (GUIUtility.hotControl == controlId)
                    {
                        Vector2 vec   = new Vector2(evt.mousePosition.x, evt.mousePosition.y);
                        double  fTime = GetSnappedTimeAtMousePosition(vec);
                        if (fTime <= 0)
                        {
                            fTime = 0;
                        }
                        this.CutOffTime      = fTime;
                        _dragCutOffTimeArrow = true;
                    }
                }
                break;

                default: break;
                }
            }

            //
            // Drag cut off time guide line
            //
            // Mouse for time guide line
            evt      = Event.current;
            mousePos = evt.mousePosition;

            if (!Application.isPlaying)
            {
                switch (evt.GetTypeForControl(redControlId))
                {
                case EventType.MouseDown:
                {
                    if (_rectTimeAreaRuler.Contains(mousePos))
                    {
                        GUIUtility.hotControl = redControlId;
                        evt.Use();
                        double fTime = GetSnappedTimeAtMousePosition(mousePos);
                        if (fTime <= 0)
                        {
                            fTime = 0.0;
                        }
                        this.RunningTime = fTime;
                    }
                }
                break;

                case EventType.MouseDrag:
                {
                    if (GUIUtility.hotControl == redControlId)
                    {
                        if (!IsLockDragHeaderArrow)
                        {
                            double fTime = GetSnappedTimeAtMousePosition(mousePos);
                            if (fTime <= 0)
                            {
                                fTime = 0.0;
                            }
                            this.RunningTime = fTime;
                        }
                    }
                }
                break;

                default: break;
                }
            }
        }
Example #14
0
 public override void OnToolGUI(EditorWindow window)
 {
     HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
     HandleMouse();
 }
        private static string DrawTypeSelectionControl(Rect position, GUIContent label, string classRef, ClassTypeConstraintAttribute filter)
        {
            if (label != null && label != GUIContent.none)
            {
                position = EditorGUI.PrefixLabel(position, label);
            }

            int controlID = GUIUtility.GetControlID(s_ControlHint, FocusType.Keyboard, position);

            bool triggerDropDown = false;

            switch (Event.current.GetTypeForControl(controlID))
            {
            case EventType.ExecuteCommand:
                if (Event.current.commandName == "TypeReferenceUpdated")
                {
                    if (SelectionControlID == controlID)
                    {
                        if (classRef != SelectedClassRef)
                        {
                            classRef    = SelectedClassRef;
                            GUI.changed = true;
                        }

                        SelectionControlID = 0;
                        SelectedClassRef   = null;
                    }
                }
                break;

            case EventType.MouseDown:
                if (GUI.enabled && position.Contains(Event.current.mousePosition))
                {
                    GUIUtility.keyboardControl = controlID;
                    triggerDropDown            = true;
                    Event.current.Use();
                }
                break;

            case EventType.KeyDown:
                if (GUI.enabled && GUIUtility.keyboardControl == controlID)
                {
                    if (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Space)
                    {
                        triggerDropDown = true;
                        Event.current.Use();
                    }
                }
                break;

            case EventType.Repaint:
                // Remove assembly name from content of popup control.
                string[] classRefParts = classRef.Split(',');

                s_TempContent.text = classRefParts[0].Trim();
                if (s_TempContent.text == "")
                {
                    s_TempContent.text = "(None)";
                }
                else if (ResolveType(classRef) == null)
                {
                    s_TempContent.text += " {Missing}";
                }

                EditorStyles.popup.Draw(position, s_TempContent, controlID);
                break;
            }

            if (triggerDropDown)
            {
                SelectionControlID = controlID;
                SelectedClassRef   = classRef;

                var filteredTypes = GetFilteredTypes(filter);
                DisplayDropDown(position, filteredTypes, ResolveType(classRef), filter.Grouping);
            }

            return(classRef);
        }
Example #16
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");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #17
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            List <string> layerTags = new List <string>();

            layerTags.Add(FilterTag.DefaultTag);

            // Find all focus layers in scene
            InteractibleObject[] interactibleObjects = GetAllInteractibleObjects();

            // Get all layer tags
            for (int i = 0; i < interactibleObjects.Length; ++i)
            {
                InteractibleObject interactibleObject = interactibleObjects[i];
                if (interactibleObject != null && interactibleObject.FilterTag != null)
                {
                    string tag = interactibleObject.FilterTag.Tag;

                    if (!string.IsNullOrEmpty(tag) && !layerTags.Contains(tag))
                    {
                        layerTags.Add(tag);
                    }

                    // Get all layer tags from other components on interactible objects
                    Component[] accompanyingComponents = interactibleObject.GetComponents <Component>();
                    for (int j = 0; j < accompanyingComponents.Length; j++)
                    {
                        if (accompanyingComponents[j] == interactibleObject || accompanyingComponents[j] == null)
                        {
                            continue;
                        }

                        foreach (FieldInfo field in accompanyingComponents[j].GetType().GetFields())
                        {
                            if (field.IsPublic && field.FieldType == typeof(FilterTag))
                            {
                                FilterTag fieldFilterTag = (FilterTag)field.GetValue(accompanyingComponents[j]);
                                if (fieldFilterTag != null && !string.IsNullOrEmpty(fieldFilterTag.Tag))
                                {
                                    layerTags.Add(fieldFilterTag.Tag);
                                }
                            }
                        }
                    }
                }
            }

            // Sort alphabetically
            layerTags.Sort();

            EditorGUI.BeginProperty(position, label, property);

            int indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            // Label
            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            // Current layer tag
            SerializedProperty currentLayerProperty = property.FindPropertyRelative("Tag");
            int tagIndex = layerTags.IndexOf(currentLayerProperty.stringValue);

            // Draw popup with all current tags in scene
            Rect rect = new Rect(position.x, position.y, 150, 18);

            tagIndex = EditorGUI.Popup(rect, tagIndex, layerTags.ToArray());

            // Set tag value
            if (tagIndex >= 0 && tagIndex < layerTags.Count)
            {
                currentLayerProperty.stringValue = layerTags.ElementAt(tagIndex);
            }
            else
            {
                currentLayerProperty.stringValue = FilterTag.DefaultTag;
            }

            // Draw tag
            rect = new Rect(position.x, position.y + 20, 150, 17);
            currentLayerProperty.stringValue = EditorGUI.TextField(rect, currentLayerProperty.stringValue);

            EditorGUI.indentLevel = indent;
            EditorGUI.EndProperty();
        }
Example #18
0
 private static Rect DrawLabel(Rect position, GUIContent label)
 {
     position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
     return(position);
 }
        void OnSceneGUI(SceneView sceneView)
        {
#if !UNITY_2018_2_OR_NEWER
            if (s_ResetOnSceneGUIState != null)
            {
                s_ResetOnSceneGUIState.Invoke(sceneView, null);
            }
#endif

            SceneStyles.Init();

            m_CurrentEvent = Event.current;

            if (m_CurrentEvent.type == EventType.MouseDown && m_CurrentEvent.button == 1)
            {
                m_IsRightMouseDown = true;
            }

            if (m_CurrentEvent.type == EventType.MouseUp && m_CurrentEvent.button == 1 || m_CurrentEvent.type == EventType.Ignore)
            {
                m_IsRightMouseDown = false;
            }

            EditorMeshHandles.DrawSceneHandles(SceneDragAndDropListener.isDragging ? SelectMode.None : selectMode);

            DrawHandleGUI(sceneView);

            if (!m_IsRightMouseDown && (m_CurrentEvent.type == EventType.KeyUp ? m_CurrentEvent.keyCode : KeyCode.None) != KeyCode.None)
            {
                if (ShortcutCheck(m_CurrentEvent))
                {
                    m_CurrentEvent.Use();
                    return;
                }
            }

            if (m_CurrentEvent.type == EventType.KeyDown)
            {
                if (s_Shortcuts.value.Any(x => x.Matches(m_CurrentEvent.keyCode, m_CurrentEvent.modifiers)))
                {
                    m_CurrentEvent.Use();
                }
            }

            if (selectMode == SelectMode.Object)
            {
                return;
            }

            // Check mouse position in scene and determine if we should highlight something
            if (s_ShowHoverHighlight &&
                m_CurrentEvent.type == EventType.MouseMove &&
                selectMode.IsMeshElementMode())
            {
                m_Hovering.CopyTo(m_HoveringPrevious);

                if (GUIUtility.hotControl == 0)
                {
                    EditorSceneViewPicker.MouseRayHitTest(m_CurrentEvent.mousePosition, selectMode, m_ScenePickerPreferences, m_Hovering);
                }
                else
                {
                    m_Hovering.Clear();
                }

                if (!m_Hovering.Equals(m_HoveringPrevious))
                {
                    SceneView.RepaintAll();
                }
            }

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

            // Overrides the toolbar transform tools
            if (Tools.current != Tool.None && Tools.current != m_CurrentTool)
            {
                SetTool_Internal(Tools.current);
            }

            Tools.current = Tool.None;

            if (selectMode.IsMeshElementMode() && MeshSelection.selectedVertexCount > 0)
            {
                var tool = GetToolForSelectMode(m_CurrentTool, m_SelectMode);

                if (tool != null)
                {
                    tool.OnSceneGUI(m_CurrentEvent);
                }
            }

            if (EditorHandleUtility.SceneViewInUse(m_CurrentEvent) || m_CurrentEvent.isKey)
            {
                m_IsDragging = false;
                return;
            }

            // This prevents us from selecting other objects in the scene,
            // and allows for the selection of faces / vertices.
            m_DefaultControl = GUIUtility.GetControlID(FocusType.Passive);
            HandleUtility.AddDefaultControl(m_DefaultControl);

            if (m_CurrentEvent.type == EventType.MouseDown)
            {
                // double clicking object
                if (m_CurrentEvent.clickCount > 1)
                {
                    DoubleClick(m_CurrentEvent);
                }

                m_InitialMousePosition = m_CurrentEvent.mousePosition;
                // readyForMouseDrag prevents a bug wherein after ending a drag an errant
                // MouseDrag event is sent with no corresponding MouseDown/MouseUp event.
                m_IsReadyForMouseDrag = true;
            }

            if (m_CurrentEvent.type == EventType.MouseDrag && m_IsReadyForMouseDrag)
            {
                if (!m_IsDragging && Vector2.Distance(m_CurrentEvent.mousePosition, m_InitialMousePosition) > k_MouseDragThreshold)
                {
                    sceneView.Repaint();
                    m_IsDragging = true;
                }
            }

            if (m_CurrentEvent.type == EventType.Ignore)
            {
                if (m_IsDragging)
                {
                    m_IsReadyForMouseDrag = false;
                    m_IsDragging          = false;
                    EditorSceneViewPicker.DoMouseDrag(m_MouseDragRect, selectMode, m_ScenePickerPreferences);
                }

                if (m_WasDoubleClick)
                {
                    m_WasDoubleClick = false;
                }
            }

            if (m_CurrentEvent.type == EventType.MouseUp)
            {
                if (m_WasDoubleClick)
                {
                    m_WasDoubleClick = false;
                }
                else
                {
                    if (!m_IsDragging)
                    {
                        if (UVEditor.instance)
                        {
                            UVEditor.instance.ResetUserPivot();
                        }

                        EditorSceneViewPicker.DoMouseClick(m_CurrentEvent, selectMode, m_ScenePickerPreferences);
                        UpdateSelection();
                        SceneView.RepaintAll();
                    }
                    else
                    {
                        m_IsDragging          = false;
                        m_IsReadyForMouseDrag = false;

                        if (UVEditor.instance)
                        {
                            UVEditor.instance.ResetUserPivot();
                        }

                        EditorSceneViewPicker.DoMouseDrag(m_MouseDragRect, selectMode, m_ScenePickerPreferences);
                    }
                }
            }
        }
Example #20
0
        private void OnGUI()
        {
            Event current = Event.current;

            LoadIcons();
            GUILayout.BeginHorizontal(Constants.Toolbar, new GUILayoutOption[0]);
            if (GUILayout.Button("Clear", Constants.MiniButton, new GUILayoutOption[0]))
            {
                LogEntries.Clear();
                GUIUtility.keyboardControl = 0;
            }
            int count = LogEntries.GetCount();

            if ((this.m_ListView.totalRows != count) && (this.m_ListView.scrollPos.y >= ((this.m_ListView.rowHeight * this.m_ListView.totalRows) - this.ms_LVHeight)))
            {
                this.m_ListView.scrollPos.y = (count * 0x20) - this.ms_LVHeight;
            }
            EditorGUILayout.Space();
            bool flag = this.HasFlag(ConsoleFlags.Collapse);

            this.SetFlag(ConsoleFlags.Collapse, GUILayout.Toggle(flag, "Collapse", Constants.MiniButtonLeft, new GUILayoutOption[0]));
            if (flag != this.HasFlag(ConsoleFlags.Collapse))
            {
                this.m_ListView.row         = -1;
                this.m_ListView.scrollPos.y = LogEntries.GetCount() * 0x20;
            }
            this.SetFlag(ConsoleFlags.ClearOnPlay, GUILayout.Toggle(this.HasFlag(ConsoleFlags.ClearOnPlay), "Clear on Play", Constants.MiniButtonMiddle, new GUILayoutOption[0]));
            this.SetFlag(ConsoleFlags.ErrorPause, GUILayout.Toggle(this.HasFlag(ConsoleFlags.ErrorPause), "Error Pause", Constants.MiniButtonRight, new GUILayoutOption[0]));
            EditorGUILayout.Space();
            if (this.m_DevBuild)
            {
                GUILayout.FlexibleSpace();
                this.SetFlag(ConsoleFlags.StopForAssert, GUILayout.Toggle(this.HasFlag(ConsoleFlags.StopForAssert), "Stop for Assert", Constants.MiniButtonLeft, new GUILayoutOption[0]));
                this.SetFlag(ConsoleFlags.StopForError, GUILayout.Toggle(this.HasFlag(ConsoleFlags.StopForError), "Stop for Error", Constants.MiniButtonRight, new GUILayoutOption[0]));
            }
            GUILayout.FlexibleSpace();
            int errorCount   = 0;
            int warningCount = 0;
            int logCount     = 0;

            LogEntries.GetCountsByType(ref errorCount, ref warningCount, ref logCount);
            bool val   = GUILayout.Toggle(this.HasFlag(ConsoleFlags.LogLevelLog), new GUIContent((logCount > 0x3e7) ? "999+" : logCount.ToString(), (logCount <= 0) ? iconInfoMono : iconInfoSmall), Constants.MiniButtonRight, new GUILayoutOption[0]);
            bool flag4 = GUILayout.Toggle(this.HasFlag(ConsoleFlags.LogLevelWarning), new GUIContent((warningCount > 0x3e7) ? "999+" : warningCount.ToString(), (warningCount <= 0) ? iconWarnMono : iconWarnSmall), Constants.MiniButtonMiddle, new GUILayoutOption[0]);
            bool flag5 = GUILayout.Toggle(this.HasFlag(ConsoleFlags.LogLevelError), new GUIContent((errorCount > 0x3e7) ? "999+" : errorCount.ToString(), (errorCount <= 0) ? iconErrorMono : iconErrorSmall), Constants.MiniButtonLeft, new GUILayoutOption[0]);

            this.SetFlag(ConsoleFlags.LogLevelLog, val);
            this.SetFlag(ConsoleFlags.LogLevelWarning, flag4);
            this.SetFlag(ConsoleFlags.LogLevelError, flag5);
            GUILayout.EndHorizontal();
            this.m_ListView.totalRows = LogEntries.StartGettingEntries();
            SplitterGUILayout.BeginVerticalSplit(this.spl, new GUILayoutOption[0]);
            EditorGUIUtility.SetIconSize(new Vector2(32f, 32f));
            GUIContent content   = new GUIContent();
            int        controlID = GUIUtility.GetControlID(FocusType.Native);

            try
            {
                bool        flag6      = false;
                bool        flag7      = this.HasFlag(ConsoleFlags.Collapse);
                IEnumerator enumerator = ListViewGUI.ListView(this.m_ListView, Constants.Box, new GUILayoutOption[0]).GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        ListViewElement element = (ListViewElement)enumerator.Current;
                        if (((current.type == EventType.MouseDown) && (current.button == 0)) && element.position.Contains(current.mousePosition))
                        {
                            if (current.clickCount == 2)
                            {
                                LogEntries.RowGotDoubleClicked(this.m_ListView.row);
                            }
                            flag6 = true;
                        }
                        if (current.type == EventType.Repaint)
                        {
                            int    mask      = 0;
                            string outString = null;
                            LogEntries.GetFirstTwoLinesEntryTextAndModeInternal(element.row, ref mask, ref outString);
                            (((element.row % 2) != 0) ? Constants.EvenBackground : Constants.OddBackground).Draw(element.position, false, false, this.m_ListView.row == element.row, false);
                            content.text = outString;
                            GetStyleForErrorMode(mask).Draw(element.position, content, controlID, this.m_ListView.row == element.row);
                            if (flag7)
                            {
                                Rect position = element.position;
                                content.text = LogEntries.GetEntryCount(element.row).ToString(CultureInfo.InvariantCulture);
                                Vector2 vector = Constants.CountBadge.CalcSize(content);
                                position.xMin  = position.xMax - vector.x;
                                position.yMin += ((position.yMax - position.yMin) - vector.y) * 0.5f;
                                position.x    -= 5f;
                                GUI.Label(position, content, Constants.CountBadge);
                            }
                        }
                    }
                }
                finally
                {
                    IDisposable disposable = enumerator as IDisposable;
                    if (disposable == null)
                    {
                    }
                    disposable.Dispose();
                }
                if (flag6 && (this.m_ListView.scrollPos.y >= ((this.m_ListView.rowHeight * this.m_ListView.totalRows) - this.ms_LVHeight)))
                {
                    this.m_ListView.scrollPos.y = ((this.m_ListView.rowHeight * this.m_ListView.totalRows) - this.ms_LVHeight) - 1;
                }
                if (((this.m_ListView.totalRows == 0) || (this.m_ListView.row >= this.m_ListView.totalRows)) || (this.m_ListView.row < 0))
                {
                    if (this.m_ActiveText.Length != 0)
                    {
                        this.SetActiveEntry(null);
                    }
                }
                else
                {
                    LogEntry outputEntry = new LogEntry();
                    LogEntries.GetEntryInternal(this.m_ListView.row, outputEntry);
                    this.SetActiveEntry(outputEntry);
                    LogEntries.GetEntryInternal(this.m_ListView.row, outputEntry);
                    if (this.m_ListView.selectionChanged || !this.m_ActiveText.Equals(outputEntry.condition))
                    {
                        this.SetActiveEntry(outputEntry);
                    }
                }
                if (((GUIUtility.keyboardControl == this.m_ListView.ID) && (current.type == EventType.KeyDown)) && ((current.keyCode == KeyCode.Return) && (this.m_ListView.row != 0)))
                {
                    LogEntries.RowGotDoubleClicked(this.m_ListView.row);
                    Event.current.Use();
                }
                if ((current.type != EventType.Layout) && (ListViewGUI.ilvState.rectHeight != 1))
                {
                    this.ms_LVHeight = ListViewGUI.ilvState.rectHeight;
                }
            }
            finally
            {
                LogEntries.EndGettingEntries();
                EditorGUIUtility.SetIconSize(Vector2.zero);
            }
            this.m_TextScroll = GUILayout.BeginScrollView(this.m_TextScroll, Constants.Box);
            float minHeight = Constants.MessageStyle.CalcHeight(GUIContent.Temp(this.m_ActiveText), base.position.width);

            GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true), GUILayout.MinHeight(minHeight) };
            EditorGUILayout.SelectableLabel(this.m_ActiveText, Constants.MessageStyle, options);
            GUILayout.EndScrollView();
            SplitterGUILayout.EndVerticalSplit();
            if (((current.type == EventType.ValidateCommand) || (current.type == EventType.ExecuteCommand)) && ((current.commandName == "Copy") && (this.m_ActiveText != string.Empty)))
            {
                if (current.type == EventType.ExecuteCommand)
                {
                    EditorGUIUtility.systemCopyBuffer = this.m_ActiveText;
                }
                current.Use();
            }
        }
Example #21
0
        // the main ObjectPreview function... it's called constantly, like other IMGUI On*GUI() functions
        public override void OnPreviewGUI(Rect r, GUIStyle background)
        {
            // if this is happening, you have bigger problems
            if (!ShaderUtil.hardwareSupportsRectRenderTexture)
            {
                if (Event.current.type == EventType.Repaint)
                {
                    EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f),
                                              "Mesh preview requires\nrender texture support");
                }
                return;
            }

            //previewDir = Drag2D(previewDir, r);
            {
                int   controlId = GUIUtility.GetControlID(sliderHash, FocusType.Passive);
                Event current   = Event.current;
                switch (current.GetTypeForControl(controlId))
                {
                case EventType.MouseDown:
                    if (r.Contains(current.mousePosition) && (double)r.width > 50.0)
                    {
                        GUIUtility.hotControl = controlId;
                        current.Use();
                        EditorGUIUtility.SetWantsMouseJumping(1);
                        break;
                    }
                    break;

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

                case EventType.MouseDrag:
                    if (GUIUtility.hotControl == controlId)
                    {
                        m_previewDir  -= current.delta * (!current.shift ? 1f : 3f) / Mathf.Min(r.width, r.height) * 140f;
                        m_previewDir.y = Mathf.Clamp(m_previewDir.y, -90f, 90f);
                        current.Use();
                        GUI.changed = true;
                        break;
                    }
                    break;

                case EventType.ScrollWheel:
                    //Debug.LogFormat("wheel: {0}", current.delta);
                    if (r.Contains(current.mousePosition))
                    {
                        if (current.delta.y > 0)
                        {
                            m_distance *= 1.1f;
                            Repaint();
                        }
                        else if (current.delta.y < 0)
                        {
                            m_distance *= 0.9f;
                            Repaint();
                        }
                    }
                    break;
                }
                //return scrollPosition;
            }
            //Debug.LogFormat("{0}", previewDir);

            if (Event.current.type != EventType.Repaint)
            {
                // if we don't need to update yet, then don't
                return;
            }

            if (m_renderer != null && m_scene != null)
            {
                var texture = m_renderer.Render(r, background, m_scene, m_previewDir, m_distance);
                if (texture != null)
                {
                    // draw the RenderTexture in the ObjectPreview pane
                    GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, false);
                }
            }
        }
Example #22
0
        public void OnSceneView(SceneView sceneView)
        {
            EditorTextStyle = new GUIStyle()
            {
                normal = new GUIStyleState {
                    textColor = Color.white,
                },
                alignment = TextAnchor.MiddleCenter,
                fontStyle = FontStyle.Bold,
                fontSize  = 12
            };

            var river = target as RiverSystem;

            if (!river.IsEditable)
            {
                return;
            }

            HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

            foreach (var point in river.ControlPoints)
            {
                ShowControlPoint(point, river);
            }

            DrawCurvedLine(river);

            var currentEvent    = Event.current;
            var inWorldPosition = GetInWorldPoint(currentEvent.mousePosition, river);

            if (currentEvent.control)
            {
                var lastPoint         = river.ControlPoints.Last();
                var lastPointPosition = river.transform.position + lastPoint.Position;

                if (inWorldPosition.IsInRiver)
                {
                    if (currentEvent.type == EventType.MouseDown)
                    {
                        Undo.RecordObject(river, "Inserted control point");
                        river.InsertControlPoint(inWorldPosition.ControlPoints, inWorldPosition.Position);
                        currentEvent.Use();
                    }
                }
                else
                {
                    Handles.DrawLine(lastPointPosition, inWorldPosition.Position);

                    if (currentEvent.type == EventType.MouseDown)
                    {
                        Undo.RecordObject(river, "Added additional control point");
                        river.AddControlPoint(inWorldPosition.Position);
                        currentEvent.Use();
                    }
                }
            }
            else if (currentEvent.shift)
            {
                if (currentEvent.type == EventType.MouseDown)
                {
                    Undo.RecordObject(river, "Removed control point");
                    river.RemoveControlPoint(inWorldPosition.ControlPoints.First);
                    currentEvent.Use();
                }
            }
            else
            {
                Handles.Label(inWorldPosition.Position + Vector3.down * 2, "Hold control to place point\nHold shift to remove a point\nPress space to release", EditorTextStyle);
            }

            if (currentEvent.type == EventType.KeyDown && currentEvent.keyCode == KeyCode.Space)
            {
                river.IsEditable = false;
                currentEvent.Use();
            }

            sceneView.Repaint();
        }
Example #23
0
        public static void OnSceneGUI(ClipBrushTool tool)
        {
            doCommit = false;             // unity bug workaround
            doCancel = false;             // unity bug workaround

            GUIStyleUtility.InitStyles();
            InitLocalStyles();
            GUILayout.BeginHorizontal(GUIStyleUtility.ContentEmpty);
            {
                GUILayout.BeginVertical(GUIStyleUtility.ContentEmpty);
                {
                    GUILayout.BeginVertical(GUIStyleUtility.ContentEmpty);
                    {
                        GUILayout.FlexibleSpace();

                        GUIStyleUtility.ResetGUIState();

                        GUIStyle windowStyle = GUI.skin.window;
                        GUILayout.BeginVertical(ContentClipLabel, windowStyle, GUIStyleUtility.ContentEmpty);
                        {
                            OnGUIContents(true, tool);
                        }
                        GUILayout.EndVertical();
                        var currentArea = GUILayoutUtility.GetLastRect();
                        lastGuiRect = currentArea;

                        var buttonArea = currentArea;
                        buttonArea.x     += buttonArea.width - 17;
                        buttonArea.y     += 2;
                        buttonArea.height = 13;
                        buttonArea.width  = 13;
                        if (GUI.Button(buttonArea, GUIContent.none, "WinBtnClose"))
                        {
                            CSGBrushEditorWindow.GetWindow();
                        }
                        TooltipUtility.SetToolTip(GUIStyleUtility.PopOutTooltip, buttonArea);

                        int controlID = GUIUtility.GetControlID(SceneViewMeshOverlayHash, FocusType.Passive, currentArea);
                        switch (Event.current.GetTypeForControl(controlID))
                        {
                        case EventType.MouseDown:       { if (currentArea.Contains(Event.current.mousePosition))
                                                          {
                                                              GUIUtility.hotControl = controlID; GUIUtility.keyboardControl = controlID; Event.current.Use();
                                                          }
                                                          break; }

                        case EventType.MouseMove:       { if (currentArea.Contains(Event.current.mousePosition))
                                                          {
                                                              Event.current.Use();
                                                          }
                                                          break; }

                        case EventType.MouseUp:         { if (GUIUtility.hotControl == controlID)
                                                          {
                                                              GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; Event.current.Use();
                                                          }
                                                          break; }

                        case EventType.MouseDrag:       { if (GUIUtility.hotControl == controlID)
                                                          {
                                                              Event.current.Use();
                                                          }
                                                          break; }

                        case EventType.ScrollWheel: { if (currentArea.Contains(Event.current.mousePosition))
                                                      {
                                                          Event.current.Use();
                                                      }
                                                      break; }
                        }
                    }
                    GUILayout.EndVertical();
                }
                GUILayout.EndVertical();
                GUILayout.FlexibleSpace();
            }
            GUILayout.EndHorizontal();

            if (tool != null)
            {
                if (doCommit)
                {
                    tool.Commit();                              // unity bug workaround
                }
                if (doCancel)
                {
                    tool.Cancel();                              // unity bug workaround
                }
            }
        }
Example #24
0
/*AUTO SCRIPT*/         // Draw the property inside the given rect
/*AUTO SCRIPT*/ public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ label    = EditorGUI.BeginProperty(position, label, property);
/*AUTO SCRIPT*/ position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
/*AUTO SCRIPT*/ EditorGUI.BeginChangeCheck();
/*AUTO SCRIPT*/ var indent = EditorGUI.indentLevel;

/*AUTO SCRIPT*/ EditorGUI.indentLevel = 0;
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/                 //CODE STARTS HERE
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ var height = base.GetPropertyHeight(property, label);
/*AUTO SCRIPT*/                 //draw object field
/*AUTO SCRIPT*/ var rect1 = new Rect(position.x, position.y, position.width, height);

/*AUTO SCRIPT*/ EditorGUI.PropertyField(rect1, property, GUIContent.none);
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ var              name                     = property.name;
/*AUTO SCRIPT*/ var              obj                      = property.serializedObject.targetObject;
/*AUTO SCRIPT*/ Type             t                        = obj.GetType();
/*AUTO SCRIPT*/ var              variableField            = t.GetField(name);
/*AUTO SCRIPT*/ var              variableObject           = (Texture2DVariable)variableField.GetValue(obj);
/*AUTO SCRIPT*/ SerializedObject variableSerializedObject = null;

/*AUTO SCRIPT*/
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/                 //if object not null, draw value field
/*AUTO SCRIPT*/ if (variableObject != null)
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ numLines = 2;
/*AUTO SCRIPT*/ var rect2 = new Rect(position.x, position.y + height, position.width, height);
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ variableSerializedObject = new SerializedObject(variableObject);
/*AUTO SCRIPT*/ var valueSerializedProperty = variableSerializedObject.FindProperty("value");
/*AUTO SCRIPT*/ var useMinMax = variableSerializedObject.FindProperty("useMinMax").boolValue;
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ if (useMinMax && valueSerializedProperty.propertyType == SerializedPropertyType.Float)
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ var min = variableSerializedObject.FindProperty("min").floatValue;
/*AUTO SCRIPT*/ var max = variableSerializedObject.FindProperty("max").floatValue;
/*AUTO SCRIPT*/ EditorGUI.Slider(rect2, valueSerializedProperty, min, max, GUIContent.none);
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/ else if (useMinMax && valueSerializedProperty.propertyType == SerializedPropertyType.Integer)
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ var min = variableSerializedObject.FindProperty("min").intValue;
/*AUTO SCRIPT*/ var max = variableSerializedObject.FindProperty("max").intValue;
/*AUTO SCRIPT*/ EditorGUI.IntSlider(rect2, valueSerializedProperty, min, max, GUIContent.none);
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/ else
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ EditorGUI.PropertyField(rect2, valueSerializedProperty, GUIContent.none);
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/ else
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ numLines = 1;
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ if (EditorGUI.EndChangeCheck())
/*AUTO SCRIPT*/ {
/*AUTO SCRIPT*/ property.serializedObject.ApplyModifiedProperties();
/*AUTO SCRIPT*/ if (variableSerializedObject != null)
                {
/*AUTO SCRIPT*/ variableSerializedObject.ApplyModifiedProperties();
                }
/*AUTO SCRIPT*/ }
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/                 //AND ENDS HERE
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/
/*AUTO SCRIPT*/ EditorGUI.indentLevel = indent;
/*AUTO SCRIPT*/ EditorGUI.EndProperty();
/*AUTO SCRIPT*/ }
Example #25
0
        public void DoTimeControl(Rect rect)
        {
            if (TimeControl.s_Styles == null)
            {
                TimeControl.s_Styles = new TimeControl.Styles();
            }
            Event current   = Event.current;
            int   controlID = GUIUtility.GetControlID(TimeControl.kScrubberIDHash, FocusType.Keyboard);
            Rect  rect2     = rect;

            rect2.height = 21f;
            Rect rect3 = rect2;

            rect3.xMin += 33f;
            switch (current.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                if (rect.Contains(current.mousePosition))
                {
                    GUIUtility.keyboardControl = controlID;
                }
                if (rect3.Contains(current.mousePosition))
                {
                    EditorGUIUtility.SetWantsMouseJumping(1);
                    GUIUtility.hotControl  = controlID;
                    this.m_MouseDrag       = current.mousePosition.x - rect3.xMin;
                    this.nextCurrentTime   = this.m_MouseDrag * (this.stopTime - this.startTime) / rect3.width + this.startTime;
                    this.m_WrapForwardDrag = false;
                    current.Use();
                }
                break;

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

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlID)
                {
                    this.m_MouseDrag += current.delta.x * this.playbackSpeed;
                    if (this.loop && ((this.m_MouseDrag < 0f && this.m_WrapForwardDrag) || this.m_MouseDrag > rect3.width))
                    {
                        if (this.m_MouseDrag > rect3.width)
                        {
                            this.currentTime -= this.stopTime - this.startTime;
                        }
                        else
                        {
                            if (this.m_MouseDrag < 0f)
                            {
                                this.currentTime += this.stopTime - this.startTime;
                            }
                        }
                        this.m_WrapForwardDrag = true;
                        this.m_MouseDrag       = Mathf.Repeat(this.m_MouseDrag, rect3.width);
                    }
                    this.nextCurrentTime = Mathf.Clamp(this.m_MouseDrag, 0f, rect3.width) * (this.stopTime - this.startTime) / rect3.width + this.startTime;
                    current.Use();
                }
                break;

            case EventType.KeyDown:
                if (GUIUtility.keyboardControl == controlID)
                {
                    if (current.keyCode == KeyCode.LeftArrow)
                    {
                        if (this.currentTime - this.startTime > 0.01f)
                        {
                            this.deltaTime = -0.01f;
                        }
                        current.Use();
                    }
                    if (current.keyCode == KeyCode.RightArrow)
                    {
                        if (this.stopTime - this.currentTime > 0.01f)
                        {
                            this.deltaTime = 0.01f;
                        }
                        current.Use();
                    }
                }
                break;
            }
            GUI.Box(rect2, GUIContent.none, TimeControl.s_Styles.timeScrubber);
            this.playing = GUI.Toggle(rect2, this.playing, (!this.playing) ? TimeControl.s_Styles.playIcon : TimeControl.s_Styles.pauseIcon, TimeControl.s_Styles.playButton);
            float num = Mathf.Lerp(rect3.x, rect3.xMax, this.normalizedTime);

            if (GUIUtility.keyboardControl == controlID)
            {
                Handles.color = new Color(1f, 0f, 0f, 1f);
            }
            else
            {
                Handles.color = new Color(1f, 0f, 0f, 0.5f);
            }
            Handles.DrawLine(new Vector2(num, rect3.yMin), new Vector2(num, rect3.yMax));
            Handles.DrawLine(new Vector2(num + 1f, rect3.yMin), new Vector2(num + 1f, rect3.yMax));
        }
Example #26
0
        public static bool DragSelection(Rect[] positions, ref bool[] selections, GUIStyle style)
        {
            int   controlID = GUIUtility.GetControlID(34553287, FocusType.Keyboard);
            Event current   = Event.current;
            int   num       = -1;

            for (int i = positions.Length - 1; i >= 0; i--)
            {
                if (positions[i].Contains(current.mousePosition))
                {
                    num = i;
                    break;
                }
            }
            bool result;

            switch (current.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                if (current.button == 0 && num >= 0)
                {
                    GUIUtility.keyboardControl = 0;
                    bool flag = false;
                    if (selections[num])
                    {
                        int    num2  = 0;
                        bool[] array = selections;
                        for (int j = 0; j < array.Length; j++)
                        {
                            bool flag2 = array[j];
                            if (flag2)
                            {
                                num2++;
                                if (num2 > 1)
                                {
                                    break;
                                }
                            }
                        }
                        if (num2 == 1)
                        {
                            flag = true;
                        }
                    }
                    if (!current.shift && !EditorGUI.actionKey)
                    {
                        for (int k = 0; k < positions.Length; k++)
                        {
                            selections[k] = false;
                        }
                    }
                    EditorGUIExt.initIndex      = num;
                    EditorGUIExt.initSelections = (bool[])selections.Clone();
                    EditorGUIExt.adding         = true;
                    if ((current.shift || EditorGUI.actionKey) && selections[num])
                    {
                        EditorGUIExt.adding = false;
                    }
                    selections[num]       = (!flag && EditorGUIExt.adding);
                    GUIUtility.hotControl = controlID;
                    current.Use();
                    result = true;
                    return(result);
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlID)
                {
                    GUIUtility.hotControl = 0;
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlID)
                {
                    if (current.button == 0)
                    {
                        if (num < 0)
                        {
                            Rect rect = new Rect(positions[0].x, positions[0].y - 200f, positions[0].width, 200f);
                            if (rect.Contains(current.mousePosition))
                            {
                                num = 0;
                            }
                            rect.y = positions[positions.Length - 1].yMax;
                            if (rect.Contains(current.mousePosition))
                            {
                                num = selections.Length - 1;
                            }
                        }
                        if (num < 0)
                        {
                            result = false;
                            return(result);
                        }
                        int num3 = Mathf.Min(EditorGUIExt.initIndex, num);
                        int num4 = Mathf.Max(EditorGUIExt.initIndex, num);
                        for (int l = 0; l < selections.Length; l++)
                        {
                            if (l >= num3 && l <= num4)
                            {
                                selections[l] = EditorGUIExt.adding;
                            }
                            else
                            {
                                selections[l] = EditorGUIExt.initSelections[l];
                            }
                        }
                        current.Use();
                        result = true;
                        return(result);
                    }
                }
                break;

            case EventType.Repaint:
                for (int m = 0; m < positions.Length; m++)
                {
                    style.Draw(positions[m], GUIContent.none, controlID, selections[m]);
                }
                break;
            }
            result = false;
            return(result);
        }
Example #27
0
        public static float FloatAngle(Rect rect, float value, float snap, float min, float max)
        {
            int id = GUIUtility.GetControlID(FocusType.Passive, rect);

            Rect knobRect = new Rect(rect.x, rect.y, rect.height, rect.height);

            float delta;

            if (min != max)
            {
                delta = ((max - min) / 360);
            }
            else
            {
                delta = 1;
            }

            if (Event.current != null)
            {
                if (Event.current.type == EventType.MouseDown && knobRect.Contains(Event.current.mousePosition))
                {
                    GUIUtility.hotControl    = id;
                    mAngle_lastMousePosition = Event.current.mousePosition;
                }
                else if (Event.current.type == EventType.MouseUp && GUIUtility.hotControl == id)
                {
                    GUIUtility.hotControl = -1;
                }
                else if (Event.current.type == EventType.MouseDrag && GUIUtility.hotControl == id)
                {
                    Vector2 move = mAngle_lastMousePosition - Event.current.mousePosition;
                    value += delta * (-move.x - move.y);

                    if (snap > 0)
                    {
                        float mod = value % snap;

                        if (mod < (delta * 3) || Mathf.Abs(mod - snap) < (delta * 3))
                        {
                            value = Mathf.Round(value / snap) * snap;
                        }
                    }

                    mAngle_lastMousePosition = Event.current.mousePosition;
                    GUI.changed = true;
                }
            }

            GUI.DrawTexture(knobRect, pAngle_TextureCircle);
            Matrix4x4 matrix = GUI.matrix;

            if (min != max)
            {
                GUIUtility.RotateAroundPivot(value * (360 / (max - min)), knobRect.center);
            }
            else
            {
                GUIUtility.RotateAroundPivot(value, knobRect.center);
            }

            knobRect.height = 5;
            knobRect.width  = 5;
            GUI.DrawTexture(knobRect, pAngle_TextureCircle);
            GUI.matrix = matrix;

            Rect label = new Rect(rect.x + rect.height, rect.y + (rect.height / 2) - 9, rect.height, 18);

            value = EditorGUI.FloatField(label, value);

            if (min != max)
            {
                value = Mathf.Clamp(value, min, max);
            }

            return(value);
        }
        private void GridListArea()
        {
            int controlID = GUIUtility.GetControlID(FocusType.Keyboard);

            this.m_ListArea.OnGUI(this.listPosition, controlID);
        }
Example #29
0
        public static bool DragSelection(Rect[] positions, ref bool[] selections, GUIStyle style)
        {
            int   controlId = GUIUtility.GetControlID(34553287, FocusType.Keyboard);
            Event current   = Event.current;
            int   b         = -1;

            for (int index = positions.Length - 1; index >= 0; --index)
            {
                if (positions[index].Contains(current.mousePosition))
                {
                    b = index;
                    break;
                }
            }
            switch (current.GetTypeForControl(controlId))
            {
            case EventType.MouseDown:
                if (current.button == 0 && b >= 0)
                {
                    GUIUtility.keyboardControl = 0;
                    bool flag1 = false;
                    if (selections[b])
                    {
                        int num = 0;
                        foreach (bool flag2 in selections)
                        {
                            if (flag2)
                            {
                                ++num;
                                if (num > 1)
                                {
                                    break;
                                }
                            }
                        }
                        if (num == 1)
                        {
                            flag1 = true;
                        }
                    }
                    if (!current.shift && !EditorGUI.actionKey)
                    {
                        for (int index = 0; index < positions.Length; ++index)
                        {
                            selections[index] = false;
                        }
                    }
                    EditorGUIExt.initIndex      = b;
                    EditorGUIExt.initSelections = (bool[])selections.Clone();
                    EditorGUIExt.adding         = true;
                    if ((current.shift || EditorGUI.actionKey) && selections[b])
                    {
                        EditorGUIExt.adding = false;
                    }
                    selections[b]         = !flag1 && EditorGUIExt.adding;
                    GUIUtility.hotControl = controlId;
                    current.Use();
                    return(true);
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlId)
                {
                    GUIUtility.hotControl = 0;
                    break;
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlId && current.button == 0)
                {
                    if (b < 0)
                    {
                        Rect rect = new Rect(positions[0].x, positions[0].y - 200f, positions[0].width, 200f);
                        if (rect.Contains(current.mousePosition))
                        {
                            b = 0;
                        }
                        rect.y = positions[positions.Length - 1].yMax;
                        if (rect.Contains(current.mousePosition))
                        {
                            b = selections.Length - 1;
                        }
                    }
                    if (b < 0)
                    {
                        return(false);
                    }
                    int num1 = Mathf.Min(EditorGUIExt.initIndex, b);
                    int num2 = Mathf.Max(EditorGUIExt.initIndex, b);
                    for (int index = 0; index < selections.Length; ++index)
                    {
                        selections[index] = index <num1 || index> num2 ? EditorGUIExt.initSelections[index] : EditorGUIExt.adding;
                    }
                    current.Use();
                    return(true);
                }
                break;

            case EventType.Repaint:
                for (int index = 0; index < positions.Length; ++index)
                {
                    style.Draw(positions[index], GUIContent.none, controlId, selections[index]);
                }
                break;
            }
            return(false);
        }
Example #30
0
        public static void OnSceneGUI(Rect windowRect, EditModePlace tool)
        {
            CSG_GUIStyleUtility.InitStyles();
            InitLocalStyles();
            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
            {
                GUILayout.FlexibleSpace();

                GUILayout.BeginVertical(CSG_GUIStyleUtility.ContentEmpty);
                {
                    GUILayout.BeginVertical(CSG_GUIStyleUtility.ContentEmpty);
                    {
                        GUILayout.FlexibleSpace();

                        CSG_GUIStyleUtility.ResetGUIState();

                        GUIStyle windowStyle = GUI.skin.window;
                        GUILayout.BeginVertical(ContentTitleLabel, windowStyle, CSG_GUIStyleUtility.ContentEmpty);
                        {
                            OnGUIContents(true, tool);
                        }
                        GUILayout.EndVertical();

                        var currentArea = GUILayoutUtility.GetLastRect();
                        lastGuiRect = currentArea;

                        var buttonArea = currentArea;
                        buttonArea.x     += buttonArea.width - 17;
                        buttonArea.y     += 2;
                        buttonArea.height = 13;
                        buttonArea.width  = 13;
                        if (GUI.Button(buttonArea, GUIContent.none, "WinBtnClose"))
                        {
                            EditModeToolWindowSceneGUI.GetWindow();
                        }
                        TooltipUtility.SetToolTip(CSG_GUIStyleUtility.PopOutTooltip, buttonArea);

                        int controlID = GUIUtility.GetControlID(SceneViewMeshOverlayHash, FocusType.Keyboard, currentArea);
                        switch (Event.current.GetTypeForControl(controlID))
                        {
                        case EventType.MouseDown: { if (currentArea.Contains(Event.current.mousePosition))
                                                    {
                                                        GUIUtility.hotControl = controlID; GUIUtility.keyboardControl = controlID; Event.current.Use();
                                                    }
                                                    break; }

                        case EventType.MouseMove: { if (currentArea.Contains(Event.current.mousePosition))
                                                    {
                                                        Event.current.Use();
                                                    }
                                                    break; }

                        case EventType.MouseUp: { if (GUIUtility.hotControl == controlID)
                                                  {
                                                      GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; Event.current.Use();
                                                  }
                                                  break; }

                        case EventType.MouseDrag: { if (GUIUtility.hotControl == controlID)
                                                    {
                                                        Event.current.Use();
                                                    }
                                                    break; }

                        case EventType.ScrollWheel: { if (currentArea.Contains(Event.current.mousePosition))
                                                      {
                                                          Event.current.Use();
                                                      }
                                                      break; }
                        }
                    }
                    GUILayout.EndVertical();
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();
        }