public void OnSceneGUI() { var script = target as GraphUpdateScene; // Don't allow editing unless it is the active object if (Selection.activeGameObject != script.gameObject || script.legacyMode) { return; } // Make sure the points array is not null if (script.points == null) { script.points = new Vector3[0]; EditorUtility.SetDirty(script); } List <Vector3> points = Pathfinding.Util.ListPool <Vector3> .Claim(); points.AddRange(script.points); Matrix4x4 invMatrix = script.transform.worldToLocalMatrix; Matrix4x4 matrix = script.transform.localToWorldMatrix; for (int i = 0; i < points.Count; i++) { points[i] = matrix.MultiplyPoint3x4(points[i]); } float minScreenDist = float.PositiveInfinity; if (Tools.current != Tool.View && Event.current.type == EventType.Layout) { for (int i = 0; i < script.points.Length; i++) { float dist = HandleUtility.DistanceToLine(points[i], points[i]); HandleUtility.AddControl(-i - 1, dist); minScreenDist = Mathf.Min(dist, minScreenDist); } } // If there is a point sort of close to the cursor, but not close enough // to receive a click event, then prevent the user from accidentally clicking // which would deselect the current object and be kinda annoying. if (Tools.current != Tool.View && minScreenDist < 50) { HandleUtility.AddDefaultControl(0); } for (int i = 0; i < points.Count; i++) { if (i == selectedPoint && Tools.current == Tool.Move) { Handles.color = PointSelectedColor; SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius * 2); Vector3 pre = points[i]; Vector3 post = Handles.PositionHandle(points[i], Quaternion.identity); if (pre != post) { Undo.RecordObject(script, "Moved Point"); script.points[i] = invMatrix.MultiplyPoint3x4(post); } } else { Handles.color = PointColor; SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius); } } if (Event.current.type == EventType.MouseDown) { int pre = selectedPoint; selectedPoint = -(HandleUtility.nearestControl + 1); if (pre != selectedPoint) { GUI.changed = true; } } if (Tools.current == Tool.Move) { var darkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); Handles.BeginGUI(); float width = 220; float height = 76; float margin = 10; AstarPathEditor.LoadStyles(); GUILayout.BeginArea(new Rect(Camera.current.pixelWidth - width, Camera.current.pixelHeight - height, width - margin, height - margin), "Shortcuts", AstarPathEditor.astarSkin.FindStyle("SceneBoxDark")); GUILayout.Label("Shift+Click: Add new point", darkSkin.label); GUILayout.Label("Backspace: Delete selected point", darkSkin.label); // Invisible button to capture clicks. This prevents a click inside the box from causing some other GameObject to be selected. GUI.Button(new Rect(0, 0, width - margin, height - margin), "", GUIStyle.none); GUILayout.EndArea(); Handles.EndGUI(); } if (Tools.current == Tool.Move && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Backspace && selectedPoint >= 0 && selectedPoint < points.Count) { Undo.RecordObject(script, "Removed Point"); var arr = new List <Vector3>(script.points); arr.RemoveAt(selectedPoint); points.RemoveAt(selectedPoint); script.points = arr.ToArray(); GUI.changed = true; } if (Event.current.shift && Tools.current == Tool.Move) { HandleUtility.Repaint(); // Find the closest segment int insertionIndex = points.Count; float minDist = float.PositiveInfinity; for (int i = 0; i < points.Count; i++) { float dist = HandleUtility.DistanceToLine(points[i], points[(i + 1) % points.Count]); if (dist < minDist) { insertionIndex = i + 1; minDist = dist; } } var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); System.Object hit = HandleUtility.RaySnap(ray); Vector3 rayhit = Vector3.zero; bool didHit = false; if (hit != null) { rayhit = ((RaycastHit)hit).point; didHit = true; } else { var plane = new Plane(script.transform.up, script.transform.position); float distance; plane.Raycast(ray, out distance); if (distance > 0) { rayhit = ray.GetPoint(distance); didHit = true; } } if (didHit) { if (Event.current.type == EventType.MouseDown) { points.Insert(insertionIndex, rayhit); Undo.RecordObject(script, "Added Point"); var arr = new List <Vector3>(script.points); arr.Insert(insertionIndex, invMatrix.MultiplyPoint3x4(rayhit)); script.points = arr.ToArray(); GUI.changed = true; } else if (points.Count > 0) { Handles.color = Color.green; Handles.DrawDottedLine(points[(insertionIndex - 1 + points.Count) % points.Count], rayhit, 8); Handles.DrawDottedLine(points[insertionIndex % points.Count], rayhit, 8); SphereCap(0, rayhit, Quaternion.identity, HandleUtility.GetHandleSize(rayhit) * pointGizmosRadius); // Project point down onto a plane var zeroed = invMatrix.MultiplyPoint3x4(rayhit); zeroed.y = 0; Handles.color = new Color(1, 1, 1, 0.5f); Handles.DrawDottedLine(matrix.MultiplyPoint3x4(zeroed), rayhit, 4); } } if (Event.current.type == EventType.MouseDown) { Event.current.Use(); } } // Make sure the convex hull stays up to date script.RecalcConvex(); Pathfinding.Util.ListPool <Vector3> .Release(ref points); if (GUI.changed) { HandleUtility.Repaint(); } }
private void DrawSpecifPositions() { var doors = target as Generators.Common.RoomTemplates.Doors.Doors; foreach (var door in doors.DoorsList) { DrawOutline(door.From, door.To, Color.red); } if (highlightInfo != null) { DrawOutline(highlightInfo.From, highlightInfo.To, Color.yellow); } if (addSpecificDoorPositions) { var go = doors.transform.gameObject; var e = Event.current; Selection.activeGameObject = go; var mouseWorldPosition = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin; mouseWorldPosition -= doors.transform.position; mouseWorldPosition.z = 0; mouseWorldPosition.x = (float)Math.Floor(mouseWorldPosition.x); mouseWorldPosition.y = (float)Math.Floor(mouseWorldPosition.y); var controlId = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlId); switch (e.type) { case EventType.MouseDown: if (e.button == 0) { firstPoint = mouseWorldPosition; hasFirstPoint = true; hasSecondPoint = false; Event.current.Use(); } break; case EventType.MouseUp: if (e.button == 0) { if (hasFirstPoint) { hasSecondPoint = true; } Event.current.Use(); } break; } if (hasFirstPoint) { highlightInfo = null; var from = firstPoint; var to = mouseWorldPosition; if (from.x != to.x && from.y != to.y) { to.x = from.x; } DrawOutline(from, to, Color.yellow, false); if (hasSecondPoint) { hasFirstPoint = false; hasSecondPoint = false; var newDoorInfo = new DoorInfoEditor() { From = from, To = to, }; if (!doors.DoorsList.Contains(newDoorInfo)) { Undo.RecordObject(target, "Added door position"); doors.DoorsList.Add(newDoorInfo); EditorUtility.SetDirty(target); } } SceneView.RepaintAll(); } } }
void Painter() { Transform CurrentSelect = Selection.activeTransform; MeshFilter temp = CurrentSelect.GetComponent <MeshFilter>(); //获取当前模型的MeshFilter float orthographicSize = (brushSize * CurrentSelect.localScale.x) * (temp.sharedMesh.bounds.size.x / 200); //笔刷在模型上的正交大小 MaskTex = (Texture2D)CurrentSelect.gameObject.GetComponent <MeshRenderer>().sharedMaterial.GetTexture("_Control"); //从材质球中获取Control贴图 brushSizeInPourcent = (int)Mathf.Round((brushSize * MaskTex.width) / 100); //笔刷在模型上的大小 bool ToggleF = false; Event e = Event.current; //检测输入 HandleUtility.AddDefaultControl(0); RaycastHit raycastHit = new RaycastHit(); Ray terrain = HandleUtility.GUIPointToWorldRay(e.mousePosition); //从鼠标位置发射一条射线 if (Physics.Raycast(terrain, out raycastHit, Mathf.Infinity, 1 << LayerMask.NameToLayer("ground"))) //射线检测名为"ground"的层 { Handles.color = new Color(1f, 1f, 0f, 1f); //颜色 Handles.DrawWireDisc(raycastHit.point, raycastHit.normal, orthographicSize); //根据笔刷大小在鼠标位置显示一个圆 //鼠标点击或按下并拖动进行绘制 if ((e.type == EventType.MouseDown && e.alt == false && e.control == false && e.shift == false && e.button == 0) || (e.type == EventType.MouseDown && e.shift == false && e.alt == false && e.control == false && e.button == 0 && ToggleF == false)) { //选择绘制的通道 Color targetColor = new Color(1f, 0f, 0f, 0f); switch (selTex) { case 0: targetColor = new Color(1f, 0f, 0f, 0f); break; case 1: targetColor = new Color(0f, 1f, 0f, 0f); break; case 2: targetColor = new Color(0f, 0f, 1f, 0f); break; case 3: targetColor = new Color(0f, 0f, 0f, 1f); break; } Vector2 pixelUV = raycastHit.textureCoord; //计算笔刷所覆盖的区域 int PuX = Mathf.FloorToInt(pixelUV.x * MaskTex.width); int PuY = Mathf.FloorToInt(pixelUV.y * MaskTex.height); int x = Mathf.Clamp(PuX - brushSizeInPourcent / 2, 0, MaskTex.width - 1); int y = Mathf.Clamp(PuY - brushSizeInPourcent / 2, 0, MaskTex.height - 1); int width = Mathf.Clamp((PuX + brushSizeInPourcent / 2), 0, MaskTex.width) - x; int height = Mathf.Clamp((PuY + brushSizeInPourcent / 2), 0, MaskTex.height) - y; Color[] terrainBay = MaskTex.GetPixels(x, y, width, height, 0); //获取Control贴图被笔刷所覆盖的区域的颜色 Texture2D TBrush = brushTex[selBrush] as Texture2D; //获取笔刷性状贴图 float[] brushAlpha = new float[brushSizeInPourcent * brushSizeInPourcent]; //笔刷透明度 //根据笔刷贴图计算笔刷的透明度 for (int i = 0; i < brushSizeInPourcent; i++) { for (int j = 0; j < brushSizeInPourcent; j++) { brushAlpha[j * brushSizeInPourcent + i] = TBrush.GetPixelBilinear(((float)i) / brushSizeInPourcent, ((float)j) / brushSizeInPourcent).a; } } //计算绘制后的颜色 for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int index = (i * width) + j; float Stronger = brushAlpha[Mathf.Clamp((y + i) - (PuY - brushSizeInPourcent / 2), 0, brushSizeInPourcent - 1) * brushSizeInPourcent + Mathf.Clamp((x + j) - (PuX - brushSizeInPourcent / 2), 0, brushSizeInPourcent - 1)] * brushStronger; terrainBay[index] = Color.Lerp(terrainBay[index], targetColor, Stronger); } } Undo.RegisterCompleteObjectUndo(MaskTex, "meshPaint"); //保存历史记录以便撤销 MaskTex.SetPixels(x, y, width, height, terrainBay, 0); //把绘制后的Control贴图保存起来 MaskTex.Apply(); ToggleF = true; } else if (e.type == EventType.MouseUp && e.alt == false && e.button == 0 && ToggleF == true) { SaveTexture();//绘制结束保存Control贴图 ToggleF = false; } } }
public static void DrawSceneGUI(MapMagicObject mapMagic, ref SelectionMode selectionMode) { if (selectionMode != SelectionMode.none && !Event.current.alt) { Dictionary <Coord, TerrainTile> tilesLut = new Dictionary <Coord, TerrainTile>(mapMagic.tiles.grid); //returning if no scene veiw (right after script compile) SceneView sceneview = UnityEditor.SceneView.lastActiveSceneView; if (sceneview == null || sceneview.camera == null) { return; } //disabling selection HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); //canceling any pin on esc, alt or right-click if (Event.current.keyCode == KeyCode.Escape || Event.current.alt) { selectionMode = SelectionMode.none; Select.CancelFrame(); // EditorWindow.GetWindow FindObjectOfType<Core.GUI.MapMagicInspector>().Repaint(); } //preparing the sets of both custom and tile terrains HashSet <Terrain> pinnedCustomTerrains = new HashSet <Terrain>(); //custom terrains that were already pinned before foreach (TerrainTile tile in mapMagic.tiles.customTiles) { if (tile.main != null) { pinnedCustomTerrains.Add(tile.main.terrain); } if (tile.draft != null) { pinnedCustomTerrains.Add(tile.draft.terrain); } } HashSet <Terrain> pinnedTileTerrains = new HashSet <Terrain>(); foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main != null) { pinnedTileTerrains.Add(tile.main.terrain); } if (tile.draft != null) { pinnedTileTerrains.Add(tile.draft.terrain); } } if (selectionMode == SelectionMode.pin) { Handles.color = FrameDraw.pinColor; List <Coord> selectedCoords = TerrainAiming.SelectTiles((Vector3)mapMagic.tileSize, false, tilesLut, mapMagic.transform); if (selectedCoords != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Terrains"); foreach (Coord coord in selectedCoords) { mapMagic.tiles.Pin(coord, false, mapMagic); } foreach (Coord coord in selectedCoords) { UnityEditor.Undo.RegisterCreatedObjectUndo(mapMagic.tiles[coord].gameObject, "MapMagic Pin Terrains"); } } } if (selectionMode == SelectionMode.pinLowres) { Handles.color = FrameDraw.pinColor; List <Coord> selectedCoords = TerrainAiming.SelectTiles((Vector3)mapMagic.tileSize, true, tilesLut, mapMagic.transform); if (selectedCoords != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Draft Terrains"); foreach (Coord coord in selectedCoords) { mapMagic.tiles.Pin(coord, true, mapMagic); } foreach (Coord coord in selectedCoords) { UnityEditor.Undo.RegisterCreatedObjectUndo(mapMagic.tiles[coord].gameObject, "MapMagic Pin Terrains"); } } } if (selectionMode == SelectionMode.pinExisting) { //excluding tiles HashSet <Terrain> possibleTerrains = new HashSet <Terrain>(); Terrain[] allTerrains = GameObject.FindObjectsOfType <Terrain>(); foreach (Terrain terrain in allTerrains) { if (!pinnedTileTerrains.Contains(terrain)) { possibleTerrains.Add(terrain); } } HashSet <Terrain> selectedTerrains = TerrainAiming.SelectTerrains(possibleTerrains, FrameDraw.pinColor, false); if (selectedTerrains != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Terrains"); foreach (Terrain terrain in selectedTerrains) { if (pinnedCustomTerrains.Contains(terrain)) { continue; } terrain.transform.parent = mapMagic.transform; TerrainTile tile = terrain.gameObject.GetComponent <TerrainTile>(); if (tile == null) { tile = terrain.gameObject.AddComponent <TerrainTile>(); } tile.main.terrain = terrain; //tile.main.area = new Terrains.Area(terrain); //tile.main.use = true; //tile.lodData = null; mapMagic.tiles.PinCustom(tile); mapMagic.StartGenerate(tile); } } } if (selectionMode == SelectionMode.selectPreview) { //hash set of all pinned terrains contains main data HashSet <Terrain> pinnedMainTerrains = new HashSet <Terrain>(); foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main != null) { pinnedMainTerrains.Add(tile.main.terrain); } } pinnedMainTerrains.UnionWith(pinnedCustomTerrains); HashSet <Terrain> selectedTerrains = TerrainAiming.SelectTerrains(pinnedMainTerrains, FrameDraw.selectPreviewColor, false); if (selectedTerrains != null && selectedTerrains.Count == 1) { UnityEditor.Undo.RegisterCompleteObjectUndo(mapMagic, "MapMagic Select Preview"); Terrain selectedTerrain = selectedTerrains.Any(); //clearing preview if (selectedTerrain == mapMagic.AssignedPreviewTerrain) { mapMagic.ClearPreviewTile(); TerrainTile.OnPreviewAssigned(mapMagic.PreviewData); } //assigning new else { foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main?.terrain == selectedTerrain && mapMagic.AssignedPreviewTerrain != selectedTerrain) { mapMagic.AssignPreviewTile(tile); mapMagic.AssignedPreviewData.isPreview = true; TerrainTile.OnPreviewAssigned(mapMagic.AssignedPreviewData); UI.RepaintAllWindows(); } } } } } if (selectionMode == SelectionMode.export || selectionMode == SelectionMode.exportCopy) { HashSet <Terrain> allTerrains = new HashSet <Terrain>(pinnedTileTerrains); allTerrains.UnionWith(pinnedCustomTerrains); HashSet <Terrain> selectedTerrains = TerrainAiming.SelectTerrains(allTerrains, FrameDraw.exportColor, false); if (selectedTerrains != null) { foreach (Terrain terrain in selectedTerrains) { if (!terrain.gameObject.activeSelf) { continue; } //finding coordinate to get proper name bool coordFound = false; Coord coord = new Coord(); foreach (var kvp in tilesLut) { if (kvp.Value.ContainsTerrain(terrain)) { coordFound = true; coord = kvp.Key; } } string terrainName = coordFound ? $"Terrain {coord.x}, {coord.z}" : terrain.name; bool saved = SaveTerrainData(terrain.terrainData, terrainName, asCopy: selectionMode == SelectionMode.exportCopy); } } } if (selectionMode == SelectionMode.unpin) { HashSet <Terrain> possibleTerrains = new HashSet <Terrain>(pinnedTileTerrains); possibleTerrains.UnionWith(pinnedCustomTerrains); HashSet <Terrain> selectedTerrains = TerrainAiming.SelectTerrains(possibleTerrains, FrameDraw.unpinColor, false); if (selectedTerrains != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Unpin Terrains"); foreach (Terrain terrain in selectedTerrains) { //terrain-to-coord lut (to pick tile terrain coord faster) Dictionary <Terrain, Coord> terrainToCoordLut = new Dictionary <Terrain, Coord>(); foreach (var kvp in tilesLut) { Coord coord = kvp.Key; TerrainTile tile = kvp.Value; if (tile.main != null) { terrainToCoordLut.Add(tile.main.terrain, coord); } if (tile.draft != null) { terrainToCoordLut.Add(tile.draft.terrain, coord); } } //if it's tile if (terrainToCoordLut.ContainsKey(terrain)) { Coord coord = terrainToCoordLut[terrain]; mapMagic.tiles.Unpin(coord); } //if it's custom if (pinnedCustomTerrains.Contains(terrain)) { TerrainTile tileComponent = terrain.gameObject.GetComponent <TerrainTile>(); mapMagic.tiles.UnpinCustom(tileComponent); GameObject.DestroyImmediate(tileComponent); } } } } //redrawing scene SceneView.lastActiveSceneView.Repaint(); } }
void OnSceneGUI() { if (PrefabUtility.GetPrefabType(_myTerrainEditor2D.gameObject) == PrefabType.Prefab || _myTerrainEditor2D == null) { return; } #region Scene view events //Switch tab if (Event.current.type == EventType.KeyUp) { if (Event.current.keyCode == _hotKeys["ShowEditTab"]) { SwitchTab("Edit settings"); } if (Event.current.keyCode == _hotKeys["ShowCapTab"]) { SwitchTab("Cap settings"); } if (Event.current.keyCode == _hotKeys["ShowMainTab"]) { SwitchTab("Main settings"); } } if (Event.current.Equals(Event.KeyboardEvent("#" + _hotKeys["SwitchEditMode"]))) { SwitchEditMode(); } //Undo & redo (values) if (Event.current.commandName == "UndoRedoPerformed") { if (!EditorApplication.isPlaying) { _myTerrainEditor2D.EditTerrain(_myTerrainEditor2D.GetVertsPos(), true); } else { _myTerrainEditor2D.EditTerrain(_myTerrainEditor2D.GetVertsPos(), false); } } #endregion if (!_editMode) { return; } #region Draw handles if (GetSceneViewCamera() != null) { _mousePos = Camera.current.ScreenToWorldPoint(new Vector2(Event.current.mousePosition.x, (Camera.current.pixelHeight - Event.current.mousePosition.y))); _handleLocalPos = _mousePos - new Vector2(_myTerrainEditor2D.transform.position.x, _myTerrainEditor2D.transform.position.y); if (_brushLockMode) { _handleLocalPos.y = _brushHandleLockPos.y; } Vector2 finalHandlePos = _handleLocalPos + (Vector2)_myTerrainEditor2D.transform.position; Handles.color = Color.green; Handles.CircleCap(0, finalHandlePos, Quaternion.identity, BrushSize); if (_brushLockMode) { Handles.DrawLine(finalHandlePos + new Vector2(-BrushSize, BrushSize), finalHandlePos + new Vector2(BrushSize, BrushSize)); Handles.DrawLine(finalHandlePos + new Vector2(-BrushSize, -BrushSize), finalHandlePos + new Vector2(BrushSize, -BrushSize)); } //Draw cap tile errors if (_myTerrainEditor2D.GenerateCap && _myTerrainEditor2D.SmartCap) { if (_myTerrainEditor2D.SmartCapAreas != null) { foreach (var smartCapArea in _myTerrainEditor2D.SmartCapAreas) { Handles.color = Color.red; if (smartCapArea.CorruptedTilesVertsPoints.Count >= 2) { Handles.DrawLine(smartCapArea.CorruptedTilesVertsPoints[0] + _myTerrainEditor2D.transform.position, smartCapArea.CorruptedTilesVertsPoints[1] + _myTerrainEditor2D.transform.position); } Handles.color = Color.green; } } } } #endregion #region Draw terrain borders Vector3 terrainPos = _myTerrainEditor2D.transform.position; Handles.color = new Color(1, 1, 1, 0.5f); Handles.DrawLine(terrainPos, terrainPos + new Vector3(0, _myTerrainEditor2D.Height)); Handles.DrawLine(terrainPos, terrainPos + new Vector3(_myTerrainEditor2D.Width, 0)); Handles.DrawLine(terrainPos + new Vector3(0, _myTerrainEditor2D.Height), terrainPos + new Vector3(0, _myTerrainEditor2D.Height) + new Vector3(_myTerrainEditor2D.Width, 0)); Handles.DrawLine(terrainPos + new Vector3(_myTerrainEditor2D.Width, 0), terrainPos + new Vector3(0, _myTerrainEditor2D.Height) + new Vector3(_myTerrainEditor2D.Width, 0)); if (_myTerrainEditor2D.FixSides) { Vector3 leftFixedPoint = terrainPos + new Vector3(0, _myTerrainEditor2D.LeftFixedPoint); Vector3 rightFixedPoint = terrainPos + new Vector3(_myTerrainEditor2D.Width, _myTerrainEditor2D.RightFixedPoint); Handles.DrawLine(leftFixedPoint, leftFixedPoint - new Vector3(1, 0)); Handles.DrawLine(rightFixedPoint, rightFixedPoint + new Vector3(1, 0)); } #endregion #region Edit mode events //Start edit if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { _startEdit = true; } //End edit if (Event.current.type == EventType.MouseUp) { _startEdit = false; //Register custom undo _lastRecordedVerts = new RecordedTerrainVerts(_myTerrainEditor2D.GetVertsPos()); if (_recordedVerts.Count > 0) { if (!IsRecordedTerrainVertsEquals(_recordedVerts[_recordedVerts.Count - 1], _lastRecordedVerts)) { if (_curUndoRecordedVertsId < _recordedVerts.Count - 1) { _recordedVerts.RemoveRange(_curUndoRecordedVertsId + 1, (_recordedVerts.Count - _curUndoRecordedVertsId - 1)); } if (_recordedVerts.Count > 75) { _recordedVerts.RemoveAt(0); } _recordedVerts.Add(_lastRecordedVerts); _curUndoRecordedVertsId = _recordedVerts.Count - 1; } } else { _recordedVerts.Add(_lastRecordedVerts); } } //Dig mode if (Event.current.keyCode == _hotKeys["DigMode"]) { if (Event.current.type == EventType.KeyDown) { _digMode = true; } if (Event.current.type == EventType.keyUp) { _digMode = false; } } //Brush lock if (Event.current.shift) { if (!_brushLockMode) { _brushHandleLockPos = _handleLocalPos; _brushLockMode = true; } } else { _brushLockMode = false; } //Brush size if (Event.current.alt) { if (Event.current.type == EventType.ScrollWheel) { float sizeDelta = 0.2f; if (Event.current.control) { sizeDelta += 0.8f; } if (Event.current.delta.y > 0) { BrushSize -= sizeDelta; } if (Event.current.delta.y < 0) { BrushSize += sizeDelta; } Event.current.Use(); } if (BrushSize <= 0.1f) { BrushSize = 0.1f; } } //Undo & redo (edit Mode) if (Event.current.shift) { if (Event.current.type == EventType.KeyUp) { //Undo if (Event.current.keyCode == _hotKeys["EditModeUndo"]) { if (_recordedVerts.Count > 0 && _curUndoRecordedVertsId > 0) { _curUndoRecordedVertsId--; _myTerrainEditor2D.EditTerrain(_recordedVerts[_curUndoRecordedVertsId].TerrainVerts, true); } } //Redo if (Event.current.keyCode == _hotKeys["EditModeRedo"]) { if (_curUndoRecordedVertsId < _recordedVerts.Count - 1) { _curUndoRecordedVertsId++; _myTerrainEditor2D.EditTerrain(_recordedVerts[_curUndoRecordedVertsId].TerrainVerts, true); } } } } #endregion #region Start edit mesh if (_startEdit) { Vector3[] vertsPos = _myTerrainEditor2D.GetVertsPos(); for (int i = 0; i < vertsPos.Length; i += 2) { if (Vector2.Distance(vertsPos[i], _handleLocalPos) <= BrushSize) { float vertOffset = BrushSize - Vector2.Distance(vertsPos[i], _handleLocalPos); if (_digMode) { vertsPos[i] -= new Vector3(0, vertOffset * (BrushHardness * 0.1f)); } else { vertsPos[i] += new Vector3(0, vertOffset * (BrushHardness * 0.1f)); } if (BrushNoise > 0f) { vertsPos[i] += new Vector3(0, Random.Range(-BrushNoise * 0.25f, BrushNoise * 0.25f)); } if (BrushHeightLimitEnabled) { if (vertsPos[i].y > BrushHeightLimit) { vertsPos[i].y = BrushHeightLimit; } } if (vertsPos[i].y < 0) { vertsPos[i].y = 0; } if (vertsPos[i].y > _myTerrainEditor2D.Height) { vertsPos[i].y = _myTerrainEditor2D.Height; } } } if (!EditorApplication.isPlaying) { _myTerrainEditor2D.EditTerrain(vertsPos, true); } else { _myTerrainEditor2D.EditTerrain(vertsPos, false); } Selection.activeGameObject = _myTerrainEditor2D.gameObject; } #endregion #region Configure handles HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); if (_myTerrainEditor2D.GetComponent <Renderer>() != null) { EditorUtility.SetSelectedWireframeHidden(_myTerrainEditor2D.GetComponent <Renderer>(), true); } if (_myTerrainEditor2D.CapObj != null) { if (_myTerrainEditor2D.CapObj.GetComponent <Renderer>() != null) { EditorUtility.SetSelectedWireframeHidden(_myTerrainEditor2D.CapObj.GetComponent <Renderer>(), true); } } #endregion SceneView.RepaintAll(); EditorUtility.SetDirty(_myTerrainEditor2D); }
void OnSceneGUI() { // Clear the previously calculated mouseRayHit, since it's a new "frame". mouseRayHit.Clear(); Event current = Event.current; //note: current.button == 0 works only the frame you press it. if (state != EditingState.None) { if (dragging) { MovePreview(); } int ID = GUIUtility.GetControlID(hash, FocusType.Passive); switch (current.type) { //For focus purposes case EventType.Layout: HandleUtility.AddDefaultControl(ID); break; //White sphere creation and dragging = true case EventType.mouseDown: if (current.button == 1) //ignore right clicks, use them to cancel the dragging { dragging = false; if (previewSphere != null) { DestroyImmediate(previewSphere); } } else { CreatePreview(); } break; //Point creation if necessary case EventType.mouseUp: if (current.button == 1) { break; } if (!dragging) { break; } dragging = false; if (previewSphere != null) { DestroyImmediate(previewSphere); } var mousePoint = GetMousePoint(); if (state == EditingState.Adding) { CreateLink(mousePoint); } else if (state == EditingState.Removing) { RemoveLink(mousePoint); } waypointClicked = null; waypointDestiny = null; break; } } }
void OnSceneGUI() { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); Event e = Event.current; Vector2 mousePosition = e.mousePosition; switch (e.type) { case EventType.Repaint: Handles.color = new Color(1, 1, 1, 0.2f); Handles.DrawSolidArc(BrushPosition, Vector3.forward, Vector3.right, 360, BrushScale * BrushScale); HandleUtility.Repaint(); break; case EventType.MouseMove: if (ResizingBrush) { BrushScale += (mousePosition.x - BrushResizeBasis.x) / 100f; BrushScale = Mathf.Max(BrushScale, 0f); } else { Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition); float scalar = -ray.origin.z / ray.direction.z; BrushPosition = ray.origin + scalar * ray.direction; if (Painting) { float scale = BrushScale * BrushScale; for (int x = (int)(mousePosition.x - scale), xMax = x + (int)(scale + 1); x < xMax; x++) { for (int y = (int)(mousePosition.y - scale), yMax = y + (int)(scale + 1); y < yMax; y++) { //VoxelGrid grid = target as VoxelGrid; //grid.Cells[x * grid.XResolution + y] = true; //grid.RequestRedraw(); //Debug.Log("Painted"); } } } } BrushResizeBasis = mousePosition; break; case EventType.MouseDown: Painting = true; break; case EventType.MouseUp: Painting = false; break; case EventType.KeyDown: switch (e.keyCode) { case KeyCode.LeftControl: ResizingBrush = true; break; } break; case EventType.KeyUp: ResizingBrush = false; break; } }
void OnSceneGUI(SceneView view) { view.wantsMouseMove = true; view.wantsMouseEnterLeaveWindow = true; if (selected == null) { ClearPlacingObj(); return; } int control = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.Repaint(); if (ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Escape) { Deselect(); } if (ev.isMouse) { mousePos = ev.mousePosition; } if (ev.type == EventType.MouseLeaveWindow) { ClearPlacingObj(); } else if (ev.isMouse || ev.type == EventType.MouseEnterWindow) { UpdatePlacingObj(); } switch (ev.type) { case EventType.Layout: HandleUtility.AddDefaultControl(control); break; case EventType.MouseDown: if (ev.button == 0) { Tools.current = Tool.None; ev.Use(); lastMousePos = mousePos; currentScale = 1f; scaleMode = false; posZMode = false; dragMode = true; lastScale = placingObj.transform.localScale; lastPosZ = placingObj.transform.localPosition.z; } break; case EventType.MouseDrag: if (ev.button == 0) { if (Mathf.Abs((mousePos - lastMousePos).y) > 10f) { scaleMode = true; } if (Mathf.Abs((mousePos - lastMousePos).x) > 10f) { posZMode = true; } if (scaleMode) { currentScale = Mathf.Pow(2f, -(mousePos - lastMousePos).y / 40f); placingObj.transform.localScale = lastScale * currentScale; } if (posZMode) { currentPosZ = (mousePos - lastMousePos).x / 40f; var pos = placingObj.transform.position; pos.z = lastPosZ + currentPosZ; placingObj.transform.position = pos; } } break; case EventType.MouseUp: if (ev.button == 0) { Tools.current = Tool.None; ev.Use(); PlaceObj(); currentScale = 1f; dragMode = false; } break; } if (placingObj != null) { Handles.RectangleHandleCap(control, placePos, Quaternion.FromToRotation(Vector3.down, placeNor), 0.45f * currentScale, EventType.Repaint); } Handles.BeginGUI(); GUILayout.BeginArea(new Rect(4f, 4f, 300f, EditorGUIUtility.singleLineHeight * 3f)); var r = GUILayoutUtility.GetRect(300f, EditorGUIUtility.singleLineHeight); GUI.Label(r, "X: " + placePos.x.ToString("0.00"), EditorStyles.whiteBoldLabel); r = GUILayoutUtility.GetRect(300f, EditorGUIUtility.singleLineHeight); r.y -= 4f; GUI.Label(r, "Y: " + placePos.y.ToString("0.00"), EditorStyles.whiteBoldLabel); r = GUILayoutUtility.GetRect(300f, EditorGUIUtility.singleLineHeight); r.y -= 8f; GUI.Label(r, "Z: " + placePos.z.ToString("0.00"), EditorStyles.whiteBoldLabel); GUILayout.EndArea(); Handles.EndGUI(); }
private void DragSelect(Ferr2D_Path path) { if (Event.current.type == EventType.Repaint) { if (drag) { Vector3 pt1 = HandleUtility.GUIPointToWorldRay(dragStart).GetPoint(0.2f); Vector3 pt2 = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).GetPoint(0.2f); Vector3 pt3 = HandleUtility.GUIPointToWorldRay(new Vector2(dragStart.x, Event.current.mousePosition.y)).GetPoint(0.2f); Vector3 pt4 = HandleUtility.GUIPointToWorldRay(new Vector2(Event.current.mousePosition.x, dragStart.y)).GetPoint(0.2f); Handles.DrawSolidRectangleWithOutline(new Vector3[] { pt1, pt3, pt2, pt4 }, Ferr2D_Visual.DragBoxInnerColor, Ferr2D_Visual.DragBoxOuterColor); } } if (Event.current.shift && Event.current.control) { switch (Event.current.type) { case EventType.MouseDrag: SceneView.RepaintAll(); break; case EventType.MouseMove: SceneView.RepaintAll(); break; case EventType.MouseDown: if (Event.current.button != 0) { break; } dragStart = Event.current.mousePosition; drag = true; break; case EventType.MouseUp: if (Event.current.button != 0) { break; } Vector2 dragEnd = Event.current.mousePosition; selectedPoints.Clear(); for (int i = 0; i < path.pathVerts.Count; i += 1) { float left = Mathf.Min(dragStart.x, dragStart.x + (dragEnd.x - dragStart.x)); float right = Mathf.Max(dragStart.x, dragStart.x + (dragEnd.x - dragStart.x)); float top = Mathf.Min(dragStart.y, dragStart.y + (dragEnd.y - dragStart.y)); float bottom = Mathf.Max(dragStart.y, dragStart.y + (dragEnd.y - dragStart.y)); Rect r = new Rect(left, top, right - left, bottom - top); if (r.Contains(HandleUtility.WorldToGUIPoint(path.transform.TransformPoint(path.pathVerts[i])))) { selectedPoints.Add(i); } } HandleUtility.AddDefaultControl(0); drag = false; SceneView.RepaintAll(); break; case EventType.Layout: HandleUtility.AddDefaultControl(GetHashCode()); break; } } else if (drag == true) { drag = false; Repaint(); } }
private void OnSceneGUI() { //float currentTime = (float)EditorApplication.timeSinceStartup; spline = target as BezierSpline; handleTransform = spline.transform; handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; /* if (GUIUtility.hotControl > 0 && spline.numberOfClicks>0) * { * Debug.Log("clicked on some shit"+ GUIUtility.hotControl+" sdfjsdjfjh "); * // GUIUtility.GetControlID(); * //Vector3 currentPos = Handles * // GUIUtility.GetStateObject * // Debug.Log("list of point space"+listOfControlIds.IndexOf(GUIUtility.hotControl)); * * //GUIUtility.GetStateObject(GUIUtility.hotControl); * };*/ Vector3 p0 = ShowPoint(0); if (toggleAdd) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.ArrowPlus); } else { if (toggleRemove) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.ArrowMinus); } } Handles.BeginGUI(); GUILayout.BeginArea(new Rect(0, 5, 220, 200)); GUILayout.Label((Texture)Resources.Load("evvvvil-3d-splines")); //GUI.skin.button.fontSize = 12; GUILayout.BeginHorizontal(); //GUI.skin.button.padding = new RectOffset(0,0,0,0); GUILayout.Space(14); GUISkin mySkin = (GUISkin)Resources.Load("evvvvil-spline-skin"); SetAdd(GUILayout.Toggle(toggleAdd, "", mySkin.customStyles[0])); GUILayout.Space(11); GUI.Box(new Rect(51, 63, 100, 100), "", mySkin.customStyles[3]); SetRemove(GUILayout.Toggle(toggleRemove, "", mySkin.customStyles[1])); /* * if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) * { * Debug.Log("Mouse over!"); * } * * else * { * Debug.Log("Mouse somewhere else"); * } */ GUILayout.EndHorizontal(); //GUI.skin.button.fontSize = 8; //GUI.skin.button.alignment = TextAnchor.MiddleCenter; bool yobro = GUILayout.Button("", mySkin.customStyles[2]); if (yobro) { spline.Reset(); } GUILayout.EndArea(); GUILayout.BeginArea(new Rect(14, Screen.height - 70, 500, 25)); GUILayout.Label(sarcasticString); GUILayout.EndArea(); Handles.EndGUI(); // Debug.Log("before main gui loop number of points is: "+spline.ControlPointCount); for (int i = 1; i < spline.ControlPointCount; i += 3) { // Debug.Log("loop index is: " + i); Vector3 p1 = ShowPoint(i); Vector3 p2 = ShowPoint(i + 1); // Debug.Log("loop index is i+1: " + (i+1)); Vector3 p3 = ShowPoint(i + 2); // Debug.Log("loop index is i+2: " + (i+2)); if ((spline.ShowHandlesMode == BezierShowHandlesMode.All || (spline.ShowHandlesMode == BezierShowHandlesMode.OnlySelected && (selectedIndex > -1 && (selectedIndex == i - 1 || selectedIndex == i - 2 || selectedIndex == i) || (spline.numberOfClicks - i < 3 && toggleAdd)))) && !toggleRemove) { if (i - 2 > 0) { Vector3 previousP = ShowPoint(i - 2); Handles.color = Color.gray; Handles.DrawLine(previousP, p0); } Handles.color = Color.gray; Handles.DrawLine(p0, p1); } if (i + 2 < spline.numberOfClicks) { Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f); } p0 = p3; } /*if (spline.ShowDir) * { * ShowDirections(); * }*/ /* code tkane from: * * http://forum.unity3d.com/threads/solved-custom-editor-onscenegui-scripting.34137/ * */ // int controlID = GUIUtility.GetControlID(spline, FocusType.Passive); Event current = Event.current; if (current.type == EventType.layout) { //int controlID = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive); int controlID = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlID); if (doTheTwist >= 0) { if (spline.numberOfClicks % 3 == 1) { Debug.Log("throw bug?"); spline.numberOfClicks += 2; } spline.RemoveControlPoint(doTheTwist); doTheTwist = -1; } } else if (current.type == EventType.MouseDown && toggleAdd) { if (current.button == 0) { current.Use(); sarcasticString = GetSarcasm(); if (Camera.current != null) { SetPointWithMouse(current); if (spline.numberOfClicks % 3 == 0 && spline.numberOfClicks > 0) { spline.AddCurve(); } spline.numberOfClicks++; } } } else if (current.type == EventType.MouseDrag && toggleAdd) { currentLife++; if (current.button == 0) { current.Use(); if (Camera.current != null) { SetPointWithMouse(current); } } } else if (current.type == EventType.MouseUp && toggleAdd) { //Debug.Log("mouseup "); if (current.button == 0) { current.Use(); spline.numberOfClicks += 2; } } else if (current.type == EventType.MouseMove && toggleAdd) { if (spline.numberOfClicks % 3 == 1) { //Debug.Log("throw bug?"); spline.numberOfClicks += 2; } } /* end of code */ }
private void HandleAddDoors() { var doors = target as Doors; var gameObject = doors.transform.gameObject; var e = Event.current; var grid = gameObject.GetComponentInChildren <Grid>(); // Make sure that the current active object in the inspector is not deselected Selection.activeGameObject = gameObject; var controlId = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlId); // Compute tile position below the mouse cursor var tilePosition = GetCurrentTilePosition(); switch (e.type) { case EventType.MouseDown: if (e.button == 0) { firstPoint = tilePosition; hasFirstTile = true; hasSecondTile = false; e.Use(); } break; case EventType.MouseUp: if (e.button == 0) { if (hasFirstTile) { hasSecondTile = true; } e.Use(); } break; } // If we have the first tile, we can show how would the door look like if we released the mouse button if (hasFirstTile) { var from = firstPoint; var to = tilePosition; if (from.x != to.x && from.y != to.y) { to.x = from.x; } GridUtils.DrawRectangleOutline(grid, from, to, Color.red, new Vector2(0.1f, 0.1f)); // If we also have the second tile, we can complete the door if (hasSecondTile) { hasFirstTile = false; hasSecondTile = false; var newDoorInfo = new DoorInfoEditor() { From = from, To = to, }; if (!doors.DoorsList.Contains(newDoorInfo)) { Undo.RecordObject(target, "Added door position"); doors.DoorsList.Add(newDoorInfo); EditorUtility.SetDirty(target); } } SceneView.RepaintAll(); } }
/// <summary> /// Implements the PolyShapeTool in the Unity Editor. This method is called when the PolyShapeTool is activated. /// </summary> /// <param name="window">The window calling the tool (SceneView).</param> public override void OnToolGUI(EditorWindow window) { Event evt = Event.current; // todo refactor overlays to use `Overlay` class #pragma warning disable 618 SceneViewOverlay.Window(m_OverlayTitle, OnOverlayGUI, 0, SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle); #pragma warning restore 618 if (polygon == null) { return; } if (polygon.polyEditMode == PolyShape.PolyEditMode.None) { return; } // used when finishing a loop by clicking the first created point if (m_NextMouseUpAdvancesMode && evt.type == EventType.MouseUp) { evt.Use(); m_NextMouseUpAdvancesMode = false; if (SceneCameraIsAlignedWithPolyUp()) { SetPolyEditMode(PolyShape.PolyEditMode.Edit); } else { SetPolyEditMode(PolyShape.PolyEditMode.Height); } } if (m_IsModifyingVertices && ( evt.type == EventType.MouseUp || evt.type == EventType.Ignore || evt.type == EventType.KeyDown || evt.type == EventType.KeyUp)) { OnFinishVertexMovement(); } if (evt.type == EventType.KeyDown) { HandleKeyEvent(evt); } //The user can press a key to exit editing mode, //leading to null polygon at this point if (polygon == null) { return; } if (EditorHandleUtility.SceneViewInUse(evt)) { return; } m_ControlId = GUIUtility.GetControlID(FocusType.Passive); if (evt.type == EventType.Layout) { HandleUtility.AddDefaultControl(m_ControlId); } if (polygon.polyEditMode == PolyShape.PolyEditMode.Path && !m_PlacingPoint) { m_MouseCursor = MouseCursor.ArrowPlus; } else if ((GUIUtility.hotControl != 0) || m_PlacingPoint) { m_MouseCursor = MouseCursor.MoveArrow; } else { m_MouseCursor = MouseCursor.Arrow; } if (evt.type == EventType.MouseMove) { SceneView.RepaintAll(); } DoPointPlacement(); DoExistingPointsGUI(); if (evt.type == EventType.Repaint) { DoExistingLinesGUI(); Rect sceneViewRect = window.position; sceneViewRect.x = 0; sceneViewRect.y = 0; SceneView.AddCursorRect(sceneViewRect, m_MouseCursor); } }
private void OnSceneGUI(SceneView sceneView) { if (propertyPicking == null) { StopPicking(); return; } // Make sure we update the sceneview whenever the mouse moves. if (Event.current.type == EventType.MouseMove) { bestCandidate = FindBestCandidate(sceneView); FindNearbyCandidates(sceneView); sceneView.Repaint(); } // Draw the current best candidate. if (bestCandidate.IsValid) { Vector3 objectPosWorld = bestCandidate.Position; Vector2 mousePosGui = Event.current.mousePosition; Vector3 mouseWorld = HandleUtility.GUIPointToWorldRay(mousePosGui) .GetPoint(10); Handles.color = new Color(1, 1, 1, 0.75f); Handles.DrawDottedLine(objectPosWorld, mouseWorld, 2.0f); Handles.color = Color.white; Handles.BeginGUI(); string text = bestCandidate.Name; // The 'nearby candidates' includes the best candidate, if there's more than one, there are others. if (nearbyCandidates.Count > 1) { text += " + " + (nearbyCandidates.Count - 1) + " nearby"; } Vector2 labelSize = PickingTextStyle.CalcSize(new GUIContent(text)); labelSize += Vector2.one * 4; Rect nameRect = new Rect( Event.current.mousePosition + Vector2.down * 10 - labelSize * 0.5f, labelSize); // Draw shadow. GUI.backgroundColor = new Color(0, 0, 0, 1.0f); PickingTextStyle.normal.textColor = Color.black; EditorGUI.LabelField(nameRect, text, PickingTextStyle); // Draw white text. nameRect.position += new Vector2(-1, -1); GUI.backgroundColor = new Color(0, 0, 0, 0); PickingTextStyle.normal.textColor = Color.white; EditorGUI.LabelField(nameRect, text, PickingTextStyle); Handles.EndGUI(); } // This makes sure that clicks are not handled by the scene itself. if (Event.current.type == EventType.Layout) { controlID = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlID); return; } if (Event.current.type != EventType.MouseDown || Event.current.alt || Event.current.control) { return; } // Left click to pick a candidate, every other button is a cancel. if (Event.current.button == 0) { PickCandidate(bestCandidate); } else if (Event.current.button == 2 && nearbyCandidates.Count > 1) { PickNearbyCandidate(); } else { StopPicking(); } Event.current.Use(); }
private void OnSceneGUI() { current = Event.current; t.selectedGO = Selection.activeGameObject; if (current.type == EventType.MouseDown) { if (current.button == 1) { t.isSelecting = true; OpenSelectionPanel(); } else if (current.button == 0) { if (!selectionRect.Contains(HandleUtility.GUIPointToWorldRay(current.mousePosition).origin)) { t.isSelecting = false; } t.isMouse0Pressed = true; } } else if (current.type == EventType.MouseUp) { if (current.button == 0) { t.isMouse0Pressed = false; } } if (t.isSelecting) { DrawSelectionRects(); HandleUtility.AddDefaultControl(0); } if (t.canDraw) { DrawLines(); t.LinkPointsToGameObject(); t.currentAction = "Creating A Line"; } if (t.isDrawingLine) { if (t.firstSelectedGO == null) { t.currentAction = "Selecting First GameObject : " + t.selectedGO; } else { t.currentAction = "Selecting Second GameObject : " + t.selectedGO; } } if (current.type == EventType.KeyDown) { if (current.keyCode == KeyCode.A) { if (t.canDraw) { MyUndo("Create Line"); t.currentAction = ""; t.CreateLine(); current.Use(); } } else if (current.keyCode == KeyCode.E) { if (t.canDraw) { MyUndo("Change Tangent To A Line"); t.ChangeTangentToALine(); current.Use(); } } else if (current.keyCode == KeyCode.R) { if (t.canDraw) { MyUndo("Change Tangent To A Right Angle"); t.ChangeTangentToUpLeft(); current.Use(); } } else if (current.keyCode == KeyCode.T) { if (t.canDraw) { MyUndo("Change Tangent To A Right Angle"); t.ChangeTangentToDownLeft(); current.Use(); } } else if (current.keyCode == KeyCode.Escape) { MyUndo("Reset"); t.MyReset(); current.Use(); } else if (current.keyCode == KeyCode.Space) { if (t.isDrawingLine) { if (t.firstSelectedGO == null) { MyUndo("Select First Object"); t.firstSelectedGO = t.selectedGO; current.Use(); } else if (t.secondSelectedGO == null) { MyUndo("Select Second Object"); t.secondSelectedGO = t.selectedGO; t.AddLine(); current.Use(); } } } } DrawLabels(); SceneView.currentDrawingSceneView.Repaint(); HandleUtility.Repaint(); }
private void OnSceneGUI() { callForAddNode = (selectedIndex > -1 && Event.current.control && !Event.current.shift && Event.current.type == EventType.mouseUp); callForRemoveNode = (selectedIndex > -1 && Event.current.control && Event.current.shift && Event.current.type == EventType.mouseUp); handleTransform = spline.transform; handleRotation = UnityEditor.Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; bezierHandleRotation = Camera.current.transform.rotation; Event e = Event.current; if (toolboxFoldout) { if (selectedIndex < 0) { foldoutHeight = 68; } else { foldoutHeight = 120; } } else { foldoutHeight = 0; } Rect toolboxRect = new Rect(10f, Screen.height - (70f + foldoutHeight), 300f, 103f + foldoutHeight); // Don't deselect upon click if (toolboxFoldout && e.type == EventType.Layout) { HandleUtility.AddDefaultControl(0); } // Toolbox Handles.BeginGUI(); GUILayout.BeginArea(toolboxRect); if (boxStyle == null) { boxStyle = GUI.skin.FindStyle("box"); } GUILayout.BeginVertical(boxStyle); toolboxFoldout = GUILayout.Toggle(toolboxFoldout, playgroundLanguage.playgroundSpline, EditorStyles.foldout); if (toolboxFoldout) { DrawSelectedPointInspector(); } GUILayout.EndVertical(); GUILayout.EndArea(); Handles.EndGUI(); Vector3 p0 = ShowPoint(0); for (int i = 1; i < spline.ControlPointCount; i += 3) { Vector3 p1 = ShowPoint(i); Vector3 p2 = ShowPoint(i + 1); Vector3 p3 = ShowPoint(i + 2); Handles.color = new Color(1f, .8f, 0f); Handles.DrawLine(p0, p1); Handles.DrawLine(p2, p3); p0 = p3; } if (callForAddNode) { Undo.RecordObject(spline, "Add Node"); spline.AddNode(selectedNode); EditorUtility.SetDirty(spline); selectedIndex = SelectIndex((selectedNode + 1) * 3); } if (callForRemoveNode) { Undo.RecordObject(spline, "Remove Node"); spline.RemoveNode(selectedNode); EditorUtility.SetDirty(spline); if (selectedIndex >= spline.ControlPointCount) { selectedIndex = SelectIndex(spline.ControlPointCount - 1); } } }
void OnSceneGUI(SceneView sceneView) { SceneStyles.Init(); m_CurrentEvent = Event.current; EditorHandleDrawing.DrawSceneHandles(SceneDragAndDropListener.isDragging ? SelectMode.None : selectMode); DrawHandleGUI(sceneView); if (m_CurrentEvent.type == EventType.KeyDown) { // Escape isn't assignable as a shortcut if (m_CurrentEvent.keyCode == KeyCode.Escape && selectMode != SelectMode.Object) { selectMode = SelectMode.Object; m_IsDragging = false; m_IsReadyForMouseDrag = false; m_CurrentEvent.Use(); } } if (selectMode == SelectMode.Object) { return; } bool pathSelectionModifier = EditorHandleUtility.IsSelectionPathModifier(m_CurrentEvent.modifiers); // Check mouse position in scene and determine if we should highlight something if (s_ShowHoverHighlight && selectMode.IsMeshElementMode() && (m_CurrentEvent.type == EventType.MouseMove || (m_wasSelectingPath != pathSelectionModifier && m_CurrentEvent.isKey))) { m_Hovering.CopyTo(m_HoveringPrevious); if (GUIUtility.hotControl != 0 || EditorSceneViewPicker.MouseRayHitTest(m_CurrentEvent.mousePosition, selectMode, m_ScenePickerPreferences, m_Hovering) > ScenePickerPreferences.maxPointerDistance) { m_Hovering.Clear(); } if (!m_Hovering.Equals(m_HoveringPrevious)) { if (pathSelectionModifier) { EditorSceneViewPicker.DoMouseHover(m_Hovering); } SceneView.RepaintAll(); } } m_wasSelectingPath = pathSelectionModifier; if (Tools.current == Tool.View) { return; } switch (m_CurrentEvent.type) { case EventType.ValidateCommand: case EventType.ExecuteCommand: bool execute = m_CurrentEvent.type == EventType.ExecuteCommand; switch (m_CurrentEvent.commandName) { case "SelectAll": if (execute) { SelectAll(); } m_CurrentEvent.Use(); break; case "DeselectAll": if (execute) { DeselectAll(); } m_CurrentEvent.Use(); break; case "InvertSelection": if (execute) { InvertSelection(); } m_CurrentEvent.Use(); break; } break; } #if !UNITY_2020_2_OR_NEWER if (m_CheckForToolUpdate) { SetToolForSelectMode(m_CurrentTool); m_CheckForToolUpdate = false; } #endif if (EditorHandleUtility.SceneViewInUse(m_CurrentEvent)) { if (m_IsDragging) { m_IsDragging = false; } if (GUIUtility.hotControl == m_DefaultControl) { GUIUtility.hotControl = 0; } 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); if (Event.current.type == EventType.Layout) { HandleUtility.AddDefaultControl(m_DefaultControl); } if (m_CurrentEvent.type == EventType.MouseDown && HandleUtility.nearestControl == m_DefaultControl) { // 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; GUIUtility.hotControl = m_DefaultControl; } if (m_CurrentEvent.type == EventType.MouseDrag && m_IsReadyForMouseDrag && GUIUtility.hotControl == m_DefaultControl) { 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 (GUIUtility.hotControl == m_DefaultControl) { GUIUtility.hotControl = 0; } } if (m_CurrentEvent.type == EventType.MouseUp && GUIUtility.hotControl == m_DefaultControl) { GUIUtility.hotControl = 0; 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); if (GUIUtility.hotControl == m_DefaultControl) { GUIUtility.hotControl = 0; } } } } }
void OnSceneGUI(SceneView sceneView) { if (!tgl_Paint) { return; } Event current = Event.current; Ray ray = HandleUtility.GUIPointToWorldRay(current.mousePosition); RaycastHit hit; //Events int controlID = GUIUtility.GetControlID(sceneView.GetHashCode(), FocusType.Passive); switch (current.GetTypeForControl(controlID)) { case EventType.Layout: { if (!tgl_Paint) { return; } HandleUtility.AddDefaultControl(controlID); } break; case EventType.MouseDown: case EventType.MouseDrag: { if (current.GetTypeForControl(controlID) == EventType.MouseDrag && GUIUtility.hotControl != controlID) { return; } if (current.alt || current.control) { return; } if (current.button != 0) { return; } if (!tgl_Paint) { return; } if (HandleUtility.nearestControl != controlID) { return; } if (current.type == EventType.MouseDown) { GUIUtility.hotControl = controlID; } //Do painting if (Physics.Raycast(ray, out hit, float.MaxValue)) { if (hit.transform == go.transform) { Vector3 hitPos = Vector3.Scale(go.transform.InverseTransformPoint(hit.point), go.transform.localScale); for (int i = 0; i < vertices.Length; i++) { Vector3 vertPos = Vector3.Scale(vertices[i], go.transform.localScale); float mag = (vertPos - hitPos).magnitude; if (mag > gui_BrushSize) { continue; } debugColors[i] = Color.Lerp(debugColors[i], gui_BrushColor, gui_BrushOpacity); } mesh.colors = debugColors; } } current.Use(); } break; case EventType.MouseUp: { if (!tgl_Paint) { return; } if (GUIUtility.hotControl != controlID) { return; } GUIUtility.hotControl = 0; current.Use(); } break; case EventType.Repaint: { //Draw paint brush if (Physics.Raycast(ray, out hit, float.MaxValue)) { if (hit.transform == go.transform) { Color brushColor = new Color(gui_BrushColor.r, gui_BrushColor.g, gui_BrushColor.b, 1.0f); Handles.color = new Color(gui_BrushColor.r, gui_BrushColor.g, gui_BrushColor.b, 1.0f); Handles.DrawWireDisc(hit.point, hit.normal, gui_BrushSize); Handles.color = Color.red; Handles.DrawLine(hit.point, hit.point + Vector3.right); Handles.color = Color.green; Handles.DrawLine(hit.point, hit.point + Vector3.up); Handles.color = Color.blue; Handles.DrawLine(hit.point, hit.point + Vector3.forward); Vector3 dir = new Vector3(brushColor.r, brushColor.g, brushColor.b) * 2f - Vector3.one; Quaternion rotation = Quaternion.LookRotation(dir); Handles.ArrowHandleCap(controlID, hit.point, rotation, gui_BrushSize / 2f, EventType.Repaint); } } HandleUtility.Repaint(); } break; } }
void Planting() { if (State != 2) { State = 2; } Event e = Event.current; if (e.type == EventType.KeyDown && e.keyCode == KeyCode.T) { if (T4MSC.T4MActived != "Activated") { T4MSC.T4MActived = "Activated"; } else { T4MSC.T4MActived = "Deactivated"; } } if (!Play && EditorApplication.isPlaying == true) { Play = true; } else if (Play && EditorApplication.isPlaying == false) { SaveInPlayingMode(); Play = false; } if (PlantObjPreview && T4MSC.T4MActived == "Activated" && OldActivStat != T4MSC.T4MActived) { T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); for (int i = 0; i < T4MPlantRenderer.Length; i++) { if (T4MPlantRenderer[i].renderer.enabled == false) { T4MPlantRenderer[i].renderer.enabled = true; } } OldActivStat = T4MSC.T4MActived; } else if (PlantObjPreview && T4MSC.T4MActived == "Deactivated" && OldActivStat != T4MSC.T4MActived) { T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); for (int i = 0; i < T4MPlantRenderer.Length; i++) { if (T4MPlantRenderer[i].renderer.enabled == true) { T4MPlantRenderer[i].renderer.enabled = false; } } OldActivStat = T4MSC.T4MActived; } if (T4MSC.T4MActived == "Activated") { if (oldRandomRot != T4MSC.T4MRandomRot) { if (PlantObjPreview) { PlantObjPreview.transform.rotation = Quaternion.FromToRotation(Vector3.up, Vector3.zero); } oldRandomRot = T4MSC.T4MRandomRot; } if (PlantObjPreview && PlantObjPreview.transform.localScale != new Vector3(T4MSC.T4MObjSize, T4MSC.T4MObjSize, T4MSC.T4MObjSize) && T4MSC.T4MSizeVar == 0 || PlantObjPreview && oldSize != T4MSC.T4MObjSize) { PlantObjPreview.transform.localScale = new Vector3(T4MSC.T4MObjSize, T4MSC.T4MObjSize, T4MSC.T4MObjSize); oldSize = T4MSC.T4MObjSize; } HandleUtility.AddDefaultControl(0); RaycastHit raycastHit = new RaycastHit(); Ray terrain = HandleUtility.GUIPointToWorldRay(e.mousePosition); GameObject CurrentObject = T4MSC.T4MObjectPlant[T4MSC.T4MPlantSel]; if (Physics.Raycast(terrain, out raycastHit, Mathf.Infinity, layerMask)) { if (CurrentObject) { if (T4MSC.T4MDistanceMin != T4MSC.T4MDistanceMax && T4MSC.T4MRandomSpa && RandomDistance == 0 || RandomDistance < T4MSC.T4MDistanceMin || RandomDistance > T4MSC.T4MDistanceMax) { RandomDist(); } if (e.type == EventType.KeyDown && e.keyCode == KeyCode.H) { rotationCorrect = -1; } else if (e.type == EventType.KeyDown && e.keyCode == KeyCode.G) { rotationCorrect = 1; } else { rotationCorrect = 0; } if (e.type == EventType.KeyDown && e.keyCode == KeyCode.KeypadPlus) { T4MSC.T4MYOrigin += 0.1f; } else if (e.type == EventType.KeyDown && e.keyCode == KeyCode.KeypadMinus) { T4MSC.T4MYOrigin -= 0.1f; } if (!PlantObjPreview || currentObjPreview != CurrentObject) { rotationCorrect = 0f; if (PlantObjPreview) { DestroyImmediate(PlantObjPreview); } PlantObjPreview = Instantiate(CurrentObject, raycastHit.point, Quaternion.identity) as GameObject; T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); for (int i = 0; i < T4MPlantRenderer.Length; i++) { if (T4MPlantRenderer[i].renderer && T4MPlantRenderer[i].renderer.sharedMaterial.HasProperty("_MainTex")) { Texture Text = T4MPlantRenderer[i].renderer.sharedMaterial.GetTexture("_MainTex"); Material NewPMat = new Material("Shader \"Hidden/Preview\" {\n Properties {\n _TintColor (\"Tint Color\", Color) = (0.5,0.5,0.5,0.1)\n _MainTex (\"Texture\", 2D) = \"white\" {}\n }\n Category {\n Tags { \"Queue\"=\"Transparent\" \"IgnoreProjector\"=\"True\" \"RenderType\"=\"Transparent\" }\n Blend SrcAlpha OneMinusSrcAlpha\n Cull Off Lighting Off ZWrite Off Fog { Color (0,0,0,0) }\n BindChannels {\n Bind \"Color\", color\n Bind \"Vertex\", vertex\n Bind \"TexCoord\", texcoord\n }\n SubShader {\n Pass {\n SetTexture [_MainTex] {\n constantColor [_TintColor]\n combine constant * primary\n }\n SetTexture [_MainTex] {\n combine texture * previous DOUBLE\n }\n }\n }\n }\n }"); T4MPlantRenderer[i].renderer.sharedMaterial = NewPMat; T4MPlantRenderer[i].renderer.sharedMaterial.SetTexture("_MainTex", Text); } } T4MPreviewColl = PlantObjPreview.GetComponentsInChildren <Collider>(); for (int j = 0; j < T4MPreviewColl.Length; j++) { DestroyImmediate(T4MPreviewColl[j]); } PlantObjPreview.transform.rotation = Quaternion.FromToRotation(Vector3.up, Vector3.zero); PlantObjPreview.name = "previewT4M"; T4MPlantObjSC removeScript = PlantObjPreview.GetComponent <T4MPlantObjSC>(); DestroyImmediate(removeScript); PlantObjPreview.hideFlags = HideFlags.HideInHierarchy; currentObjPreview = CurrentObject; } PlantObjPreview.transform.position = raycastHit.point + (raycastHit.normal * T4MSC.T4MYOrigin); if (T4MSC.T4MSizeVar == 0) { PlantObjPreview.transform.localScale = new Vector3(T4MSC.T4MObjSize, T4MSC.T4MObjSize, T4MSC.T4MObjSize); } if (T4MSC.T4MPlantMod == T4MSC.PlantMode.Follow_Normals) { if (e.type == EventType.MouseMove) { PlantObjPreview.transform.up = PlantObjPreview.transform.up + raycastHit.normal; plantmodval = 1; } } else { if (plantmodval == 1) { PlantObjPreview.transform.rotation = Quaternion.FromToRotation(Vector3.up, Vector3.zero); plantmodval = 0; } } if (rotationCorrect != 0) { PlantObjPreview.transform.Rotate(0, rotationCorrect * 100 * 0.02f, 0); } if (e.shift == false && e.control == false) { T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); if (CheckPlacement != 0) { for (int i = 0; i < T4MPlantRenderer.Length; i++) { T4MPlantRenderer[i].renderer.sharedMaterial.SetColor("_TintColor", new Color(1f, 0.5f, 0.5f, 0.071f)); } } else { for (int i = 0; i < T4MPlantRenderer.Length; i++) { T4MPlantRenderer[i].renderer.sharedMaterial.SetColor("_TintColor", new Color(0.5f, 0.5f, 0.5f, 0.2f)); } } for (int i = 0; i < T4MPlantRenderer.Length; i++) { T4MPlantRenderer[i].renderer.enabled = true; } Handles.color = new Color(0f, 1f, 0f, 0.03f); Handles.DrawSolidDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MDistanceMin); if (T4MSC.T4MDistanceMin != T4MSC.T4MDistanceMax && T4MSC.T4MRandomSpa) { Handles.color = new Color(1f, 1f, 0f, 0.05f); Handles.DrawSolidDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MDistanceMax); Handles.color = new Color(1f, 1f, 0f, 0.5f); if (RandomDistance > T4MSC.T4MDistanceMin && RandomDistance < T4MSC.T4MDistanceMax) { Handles.DrawWireDisc(raycastHit.point, raycastHit.normal, RandomDistance); } } } else if (e.shift == true && e.control == false) { T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); for (int i = 0; i < T4MPlantRenderer.Length; i++) { T4MPlantRenderer[i].renderer.enabled = false; } Handles.color = new Color(1f, 0f, 0f, 0.1f); Handles.DrawSolidDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MDistanceMin); } else if (e.shift == false && e.control == true) { T4MPlantRenderer = PlantObjPreview.GetComponentsInChildren <Renderer>(); for (int i = 0; i < T4MPlantRenderer.Length; i++) { T4MPlantRenderer[i].renderer.enabled = false; } Handles.color = new Color(1f, 1f, 0f, 0.1f); Handles.DrawSolidDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MDistanceMin); } if (ToggleF == false) { T4MPlantObjGet = GameObject.FindObjectsOfType(typeof(T4MPlantObjSC)) as T4MPlantObjSC[]; ToggleF = true; } CheckPlacement = 0; Vector3 fix = raycastHit.point; if (T4MPlantObjGet != null && T4MPlantObjGet.Length > 0 && ToggleF == true) { for (int i = 0; i < T4MPlantObjGet.Length; i++) { if (T4MSC.T4MDistanceMin != T4MSC.T4MDistanceMax && T4MSC.T4MRandomSpa) { if (Vector3.Distance(T4MPlantObjGet[i].transform.position, new Vector3(fix.x, T4MPlantObjGet[i].transform.position.y, fix.z)) < RandomDistance) { CheckPlacement += 1; } } else { if (Vector3.Distance(T4MPlantObjGet[i].transform.position, new Vector3(fix.x, T4MPlantObjGet[i].transform.position.y, fix.z)) < T4MSC.T4MDistanceMin) { CheckPlacement += 1; } } } } } if (e.type == EventType.mouseDown && e.alt == false && e.button == 0 && e.shift == false && e.control == false && PlantObjPreview || e.type == EventType.mouseDrag && e.alt == false && e.button == 0 && e.shift == false && e.control == false && PlantObjPreview) { if (CurrentObject) { if (CheckPlacement == 0) { PlantObj = null; PlantObj = PrefabUtility.InstantiatePrefab(CurrentObject) as GameObject; if (!PlantObj.GetComponent <T4MPlantObjSC>()) { PlantObj.AddComponent <T4MPlantObjSC>(); } PlantObj.transform.position = PlantObjPreview.transform.position; PlantObj.transform.rotation = PlantObjPreview.transform.rotation; PlantObj.transform.localScale = PlantObjPreview.transform.localScale; LodObj = PlantObj.GetComponentsInChildren <Renderer>(); for (int t = 0; t < LodObj.Length; t++) { if (T4MSC.ViewDistance[T4MSC.T4MPlantSel] == T4MSC.ViewD.Close) { LodObj[t].gameObject.layer = 26; } else if (T4MSC.ViewDistance[T4MSC.T4MPlantSel] == T4MSC.ViewD.Middle) { LodObj[t].gameObject.layer = 27; } else if (T4MSC.ViewDistance[T4MSC.T4MPlantSel] == T4MSC.ViewD.Far) { LodObj[t].gameObject.layer = 28; } else if (T4MSC.ViewDistance[T4MSC.T4MPlantSel] == T4MSC.ViewD.BackGround) { LodObj[t].gameObject.layer = 29; } } ToggleF = false; GameObject Group = GameObject.Find(T4MSC.T4MGroupName); if (!Group) { Group = new GameObject(T4MSC.T4MGroupName); } PlantObj.transform.parent = Group.transform; if (PlantObj.GetComponent <T4MLodObjSC>()) { T4MSC.LodActivate = false; PlantObj.isStatic = T4MSC.T4MStaticObj; } else if (PlantObj.GetComponent <T4MBillBObjSC>()) { PlantObj.isStatic = false; T4MSC.billActivate = false; } else { PlantObj.isStatic = T4MSC.T4MStaticObj; } if (T4MSC.T4MCreateColl && !PlantObj.GetComponent <Collider>()) { PlantObj.AddComponent <MeshCollider>(); } if (T4MSC.T4MRandomSpa) { RandomDist(); } if (T4MSC.T4MRandomRot) { RandomRot(); } if (T4MSC.T4MSizeVar != 0) { RandomSize(); } if (T4MSC.T4MselectObj > 1) { RandomObject(); } if (EditorApplication.isPlaying == true) { InPlayingAdd(CurrentObject as GameObject, Group.name as string); } } } } else if (e.type == EventType.mouseDown && e.alt == false && e.button == 0 && e.shift == true && e.control == false && PlantObjPreview || e.type == EventType.mouseDrag && e.alt == false && e.button == 0 && e.shift == true && e.control == false && PlantObjPreview) { if (ToggleF == false) { T4MPlantObjGet = GameObject.FindObjectsOfType(typeof(T4MPlantObjSC)) as T4MPlantObjSC[]; ToggleF = true; } for (int i = 0; i < T4MPlantObjGet.Length; i++) { Vector3 fix = raycastHit.point; if (Vector3.Distance(T4MPlantObjGet[i].transform.position, new Vector3(fix.x, T4MPlantObjGet[i].transform.position.y, fix.z)) < T4MSC.T4MDistanceMin) { if (EditorApplication.isPlaying == true) { onPlayModeDestroyed.Add(T4MPlantObjGet[i].gameObject.transform.position); } if (T4MPlantObjGet[i].GetComponent <T4MBillBObjSC>()) { T4MSC.billActivate = false; } else if (T4MPlantObjGet[i].GetComponent <T4MLodObjSC>()) { T4MSC.LodActivate = false; } DestroyImmediate(T4MPlantObjGet[i].gameObject); ToggleF = false; } } } else if (e.type == EventType.mouseDown && e.alt == false && e.button == 0 && e.shift == false && e.control == true && PlantObjPreview || e.type == EventType.mouseDrag && e.alt == false && e.button == 0 && e.shift == false && e.control == true && PlantObjPreview) { if (ToggleF == false) { T4MPlantObjGet = GameObject.FindObjectsOfType(typeof(T4MPlantObjSC)) as T4MPlantObjSC[]; ToggleF = true; } for (int i = 0; i < T4MPlantObjGet.Length; i++) { Vector3 fix = raycastHit.point; if (Vector3.Distance(T4MPlantObjGet[i].transform.position, new Vector3(fix.x, T4MPlantObjGet[i].transform.position.y, fix.z)) < T4MSC.T4MDistanceMin) { Quaternion rot = T4MPlantObjGet[i].gameObject.transform.rotation; Vector3 pos = T4MPlantObjGet[i].gameObject.transform.position; Vector3 scale = T4MPlantObjGet[i].gameObject.transform.localScale; int lay = T4MPlantObjGet[i].gameObject.layer; bool Static = T4MPlantObjGet[i].gameObject.isStatic; int LODBILL = 0; if (T4MPlantObjGet[i].gameObject.GetComponent <T4MLodObjSC>()) { LODBILL = 1; } else if (T4MPlantObjGet[i].gameObject.GetComponent <T4MBillBObjSC>()) { LODBILL = 2; } DestroyImmediate(T4MPlantObjGet[i].gameObject); ToggleF = false; PlantObj = null; PlantObj = PrefabUtility.InstantiatePrefab(CurrentObject) as GameObject; if (!PlantObj.GetComponent <T4MPlantObjSC>()) { PlantObj.AddComponent <T4MPlantObjSC>(); } PlantObj.transform.position = pos; PlantObj.transform.rotation = rot; PlantObj.transform.localScale = scale; LodObj = PlantObj.GetComponentsInChildren <Renderer>(); for (int t = 0; t < LodObj.Length; t++) { LodObj[t].gameObject.layer = lay; } if (LODBILL == 1) { T4MSC.LodActivate = false; } else if (LODBILL == 2) { T4MSC.billActivate = false; } if (PlantObj.GetComponent <T4MLodObjSC>()) { T4MSC.LodActivate = false; PlantObj.isStatic = Static; } else if (PlantObj.GetComponent <T4MBillBObjSC>()) { PlantObj.isStatic = false; T4MSC.billActivate = false; } else { PlantObj.isStatic = Static; } GameObject Group = GameObject.Find(T4MSC.T4MGroupName); if (!Group) { Group = new GameObject(T4MSC.T4MGroupName); } PlantObj.transform.parent = Group.transform; } } } else if (e.type == EventType.mouseUp && ToggleF == true) { ToggleF = false; } } } }
private void OnSceneGUI() { //So you we cant click on anything else in the scene HandleUtility.AddDefaultControl(0); }
void Painter() { if (State != 1) { State = 1; } Event e = Event.current; if (e.type == EventType.KeyDown && e.keyCode == KeyCode.T) { if (T4MSC.T4MActived != "Activated") { T4MSC.T4MActived = "Activated"; } else { T4MSC.T4MActived = "Deactivated"; } } if (T4MSC.T4MPreview && T4MSC.T4MActived == "Activated" && T4MSC.T4MPreview.enabled == false || T4MSC.T4MPreview.enabled == false) { if ( T4MSC.PaintPrev != T4MSC.PaintHandle.Follow_Normal_Circle && T4MSC.PaintPrev != T4MSC.PaintHandle.Follow_Normal_WireCircle && T4MSC.PaintPrev != T4MSC.PaintHandle.Hide_preview ) { T4MSC.T4MPreview.enabled = true; } } else if (T4MSC.T4MPreview && T4MSC.T4MActived == "Deactivated" && T4MSC.T4MPreview.enabled == true || T4MSC.T4MPreview.enabled == true) { if (T4MSC.PaintPrev != T4MSC.PaintHandle.Classic) { T4MSC.T4MPreview.enabled = false; } } if (T4MSC.T4MActived == "Activated") { HandleUtility.AddDefaultControl(0); RaycastHit raycastHit = new RaycastHit(); Ray terrain = HandleUtility.GUIPointToWorldRay(e.mousePosition); if (e.type == EventType.KeyDown && e.keyCode == KeyCode.KeypadPlus) { T4MSC.brushSize += 1; } else if (e.type == EventType.KeyDown && e.keyCode == KeyCode.KeypadMinus) { T4MSC.brushSize -= 1; } if (Physics.Raycast(terrain, out raycastHit, Mathf.Infinity, layerMask)) { if (T4MSC.CurrentSelect.gameObject.GetComponent <T4MObjSC>().ConvertType != "UT") { T4MSC.T4MPreview.transform.localEulerAngles = new Vector3(90, 180 + T4MSC.CurrentSelect.localEulerAngles.y, 0); } else { T4MSC.T4MPreview.transform.localEulerAngles = new Vector3(90, -90 + T4MSC.CurrentSelect.localEulerAngles.y, 0); } T4MSC.T4MPreview.transform.position = raycastHit.point; if (T4MSC.PaintPrev != T4MSC.PaintHandle.Classic && T4MSC.PaintPrev != T4MSC.PaintHandle.Hide_preview && T4MSC.PaintPrev != T4MSC.PaintHandle.Follow_Normal_WireCircle) { Handles.color = new Color(1f, 1f, 0f, 0.05f); Handles.DrawSolidDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MPreview.orthographicSize * 0.9f); } else if (T4MSC.PaintPrev != T4MSC.PaintHandle.Classic && T4MSC.PaintPrev != T4MSC.PaintHandle.Hide_preview && T4MSC.PaintPrev != T4MSC.PaintHandle.Follow_Normal_Circle) { Handles.color = new Color(1f, 1f, 0f, 1f); Handles.DrawWireDisc(raycastHit.point, raycastHit.normal, T4MSC.T4MPreview.orthographicSize * 0.9f); } if ((e.type == EventType.mouseDrag && e.alt == false && e.shift == false && e.button == 0) || (e.shift == false && e.alt == false && e.button == 0 && ToggleF == false)) { Vector2 pixelUV = raycastHit.textureCoord * T4MSC.T4MMaskTexUVCoord; //0.14f; int PuX = Mathf.FloorToInt(pixelUV.x * T4MSC.T4MMaskTex.width); int PuY = Mathf.FloorToInt(pixelUV.y * T4MSC.T4MMaskTex.height); int x = Mathf.Clamp(PuX - T4MSC.T4MBrushSizeInPourcent / 2, 0, T4MSC.T4MMaskTex.width - 1); int y = Mathf.Clamp(PuY - T4MSC.T4MBrushSizeInPourcent / 2, 0, T4MSC.T4MMaskTex.height - 1); int width = Mathf.Clamp((PuX + T4MSC.T4MBrushSizeInPourcent / 2), 0, T4MSC.T4MMaskTex.width) - x; int height = Mathf.Clamp((PuY + T4MSC.T4MBrushSizeInPourcent / 2), 0, T4MSC.T4MMaskTex.height) - y; Color[] terrainBay = T4MSC.T4MMaskTex.GetPixels(x, y, width, height, 0); if (T4MSC.T4MMaskTex2) { terrainBay2 = T4MSC.T4MMaskTex2.GetPixels(x, y, width, height, 0); } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int index = (i * width) + j; float Stronger = T4MSC.T4MBrushAlpha[Mathf.Clamp((y + i) - (PuY - T4MSC.T4MBrushSizeInPourcent / 2), 0, T4MSC.T4MBrushSizeInPourcent - 1) * T4MSC.T4MBrushSizeInPourcent + Mathf.Clamp((x + j) - (PuX - T4MSC.T4MBrushSizeInPourcent / 2), 0, T4MSC.T4MBrushSizeInPourcent - 1)] * T4MSC.T4MStronger; if (T4MSC.T4MselTexture < 3) { terrainBay[index] = Color.Lerp(terrainBay[index], T4MSC.T4MtargetColor, Stronger); } else { terrainBay[index] = Color.Lerp(terrainBay[index], T4MSC.T4MtargetColor, Stronger); //*0.3f); if (T4MSC.T4MMaskTex2) { terrainBay2[index] = Color.Lerp(terrainBay2[index], T4MSC.T4MtargetColor2, Stronger); ///0.3f); } } } } T4MSC.T4MMaskTex.SetPixels(x, y, width, height, terrainBay, 0); T4MSC.T4MMaskTex.Apply(); if (T4MSC.T4MMaskTex2) { T4MSC.T4MMaskTex2.SetPixels(x, y, width, height, terrainBay2, 0); T4MSC.T4MMaskTex2.Apply(); UndoObj = new Texture2D[2]; UndoObj[0] = T4MSC.T4MMaskTex; UndoObj[1] = T4MSC.T4MMaskTex2; } else { UndoObj = new Texture2D[1]; UndoObj[0] = T4MSC.T4MMaskTex; } Undo.RegisterUndo(UndoObj, "T4MMask"); ToggleF = true; } else if (e.type == EventType.mouseUp && e.alt == false && e.button == 0 && ToggleF == true) { T4MSC.SaveTexture(); ToggleF = false; } } } }
public void OnSceneGUI() { if (roadCreator == null) { roadCreator = (RoadCreator)target; } HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); guiEvent = Event.current; Ray ray = HandleUtility.GUIPointToWorldRay(guiEvent.mousePosition); RaycastHit raycastHit; if (Physics.Raycast(ray, out raycastHit, 100f, ~(1 << roadCreator.globalSettings.ignoreMouseRayLayer))) { hitPosition = raycastHit.point; if (guiEvent.control == true) { Vector3 nearestGuideline = Misc.GetNearestGuidelinePoint(hitPosition); if (nearestGuideline != Misc.MaxVector3) { hitPosition = nearestGuideline; } else { hitPosition = Misc.Round(hitPosition); } } if (guiEvent.type == EventType.MouseDown) { if (guiEvent.button == 0) { if (guiEvent.shift == true) { CreatePoints(); } } else if (guiEvent.button == 1 && guiEvent.shift == true) { RemovePoints(); } } if (roadCreator.transform.GetChild(0).childCount > 0 && roadCreator.transform.GetChild(0).GetChild(roadCreator.transform.GetChild(0).childCount - 1).GetChild(0).childCount == 2 && (guiEvent.type == EventType.MouseDrag || guiEvent.type == EventType.MouseMove || guiEvent.type == EventType.MouseDown)) { points = CalculateTemporaryPoints(hitPosition); } if (roadCreator.transform.childCount > 0) { Draw(hitPosition); } } if (Physics.Raycast(ray, out raycastHit, 100f, ~(1 << roadCreator.globalSettings.roadLayer))) { Vector3 hitPosition = raycastHit.point; if (guiEvent.control == true) { hitPosition = Misc.Round(hitPosition); } if (guiEvent.shift == false) { MovePoints(raycastHit); } } GameObject.Find("Road System").GetComponent <RoadSystem>().ShowCreationButtons(); }
private void OnSceneGUI() { var mapRenderer = target as MapRenderer; if (mapRenderer == null) { return; } if (Event.current.modifiers == EventModifiers.Control) { // Turn off the translation tool. Tools.hidden = true; // Change the cursor to make it obvious you can move the map around. Make the rect big enough to cover the scene view. EditorGUIUtility.AddCursorRect(new Rect(0, 0, 999999, 999999), MouseCursor.MoveArrow); var currentEvent = Event.current; if (currentEvent.type == EventType.Layout) { // Adding a control ID disables left-click-and-drag from creating a selection rect, rather than translating the map. int controlID = GUIUtility.GetControlID(ControlIdHint, FocusType.Passive); HandleUtility.AddDefaultControl(controlID); } else if (currentEvent.type == EventType.ScrollWheel) { // Zoom map based on scroll wheel. var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (mapRenderer.Raycast(ray, out var hitInfo)) { Undo.RecordObject(mapRenderer, "Change ZoomLevel."); var delta = -Event.current.delta; mapRenderer.ZoomLevel += delta.y / 50; currentEvent.Use(); EditorApplication.QueuePlayerLoopUpdate(); } } else if (currentEvent.type == EventType.MouseDown) { // Begin panning if the mouse ray hits the map. var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (mapRenderer.Raycast(ray, out var hitInfo)) { _startingHitPointInWorldSpace = hitInfo.Point; _startingCenterInMercatorSpace = mapRenderer.Center.ToMercatorPosition(); _isDragging = true; currentEvent.Use(); } } else if (_isDragging && currentEvent.type == EventType.MouseDrag) { // Update center var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); var plane = new Plane(mapRenderer.transform.up, _startingHitPointInWorldSpace); if (plane.Raycast(ray, out var enter)) { var updatedHitPointInWorldSpace = ray.GetPoint(enter); var newDeltaInWorldSpace = updatedHitPointInWorldSpace - _startingHitPointInWorldSpace; var newDeltaInLocalSpace = mapRenderer.transform.worldToLocalMatrix * newDeltaInWorldSpace; var newDeltaInMercator = new Vector2D(newDeltaInLocalSpace.x, newDeltaInLocalSpace.z) / Math.Pow(2, mapRenderer.ZoomLevel - 1); var newCenter = LatLon.FromMercatorPosition(_startingCenterInMercatorSpace - newDeltaInMercator); Undo.RecordObject(mapRenderer, "Change Center."); mapRenderer.Center = newCenter; EditorApplication.QueuePlayerLoopUpdate(); } currentEvent.Use(); } else if (_isDragging && currentEvent.type == EventType.MouseUp) { _isDragging = false; currentEvent.Use(); } } else { Tools.hidden = false; } }
void OnSceneGUI() { if (polygon.polyEditMode == PolyShape.PolyEditMode.None) { return; } if (polygon == null || Tools.current != Tool.None) { SetPolyEditMode(PolyShape.PolyEditMode.None); return; } if (m_LineMaterial != null) { m_LineMaterial.SetPass(0); Graphics.DrawMeshNow(m_LineMesh, polygon.transform.localToWorldMatrix, 0); } Event evt = Event.current; // used when finishing a loop by clicking the first created point if (m_NextMouseUpAdvancesMode && evt.type == EventType.MouseUp) { evt.Use(); m_NextMouseUpAdvancesMode = false; if (SceneCameraIsAlignedWithPolyUp()) { SetPolyEditMode(PolyShape.PolyEditMode.Edit); } else { SetPolyEditMode(PolyShape.PolyEditMode.Height); } } if (m_IsModifyingVertices && ( evt.type == EventType.MouseUp || evt.type == EventType.Ignore || evt.type == EventType.KeyDown || evt.type == EventType.KeyUp)) { OnFinishVertexMovement(); } DoExistingPointsGUI(); if (evt.type == EventType.KeyDown) { HandleKeyEvent(evt); } if (EditorHandleUtility.SceneViewInUse(evt)) { return; } int controlID = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlID); DoPointPlacement(); }
private void OnSceneGUI() { Event e = Event.current; if (e == null) { return; } Ray ray = HandleUtility.GUIPointToWorldRay(e.mousePosition); if (Physics.Raycast(ray, out RaycastHit hit) && e.type == EventType.MouseDown && e.button == 0) { //Add a new waypoint on mouseclick + shift if (e.shift) { if (wps.curSegment == null) { return; } EditorHelper.BeginUndoGroup("Add Waypoint", wps); AddWaypoint(hit.point); //Close Undo Group Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } //Create a segment + add a new waypoint on mouseclick + ctrl else if (e.control) { EditorHelper.BeginUndoGroup("Add Segment", wps); AddSegment(hit.point); AddWaypoint(hit.point); //Close Undo Group Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } //Create an intersection type else if (e.alt) { EditorHelper.BeginUndoGroup("Add Intersection", wps); AddIntersection(hit.point); //Close Undo Group Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } } //Set waypoint system as the selected gameobject in hierarchy Selection.activeGameObject = wps.gameObject; //Handle the selected waypoint if (lastWaypoint != null) { //Uses a endless plain for the ray to hit Plane plane = new Plane(Vector3.up.normalized, lastWaypoint.GetVisualPos()); plane.Raycast(ray, out float dst); Vector3 hitPoint = ray.GetPoint(dst); //Reset lastPoint if the mouse button is pressed down the first time if (e.type == EventType.MouseDown && e.button == 0) { lastPoint = hitPoint; startPosition = lastWaypoint.transform.position; } //Move the selected waypoint if (e.type == EventType.MouseDrag && e.button == 0) { Vector3 realDPos = new Vector3(hitPoint.x - lastPoint.x, 0, hitPoint.z - lastPoint.z); lastWaypoint.transform.position += realDPos; lastPoint = hitPoint; } //Release the selected waypoint if (e.type == EventType.MouseUp && e.button == 0) { Vector3 curPos = lastWaypoint.transform.position; lastWaypoint.transform.position = startPosition; Undo.RegisterFullObjectHierarchyUndo(lastWaypoint, "Move Waypoint"); lastWaypoint.transform.position = curPos; } //Draw a Sphere Handles.SphereHandleCap(0, lastWaypoint.GetVisualPos(), Quaternion.identity, wps.waypointSize * 2f, EventType.Repaint); HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); SceneView.RepaintAll(); } //Set the current hovering waypoint if (lastWaypoint == null) { lastWaypoint = wps.GetAllWaypoints().FirstOrDefault(i => EditorHelper.SphereHit(i.GetVisualPos(), wps.waypointSize, ray)); } //Update the current segment to the currently interacting one if (lastWaypoint != null && e.type == EventType.MouseDown) { wps.curSegment = lastWaypoint.segment; } //Reset current waypoint else if (lastWaypoint != null && e.type == EventType.MouseMove) { lastWaypoint = null; } }
void OnSceneGUI() { if (target == null) { return; } if (KeyPressed(editKey)) { editing = !editing; } if (editing) { //Update lists if (keyPoints == null) { keyPoints = new List <Vector3>(polyMesh.keyPoints); curvePoints = new List <Vector3>(polyMesh.curvePoints); isCurve = new List <bool>(polyMesh.isCurve); } //Crazy hack to register undo if (undoCallback == null) { undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static); if (undoCallback != null) { undoCallback.SetValue(null, new EditorApplication.CallbackFunction(OnUndoRedo)); } } //Load handle matrix Handles.matrix = polyMesh.transform.localToWorldMatrix; //Draw points and lines DrawAxis(); Handles.color = Color.white; for (int i = 0; i < keyPoints.Count; i++) { Handles.color = nearestLine == i ? Color.green : Color.white; DrawSegment(i); if (selectedIndices.Contains(i)) { Handles.color = Color.green; DrawCircle(keyPoints[i], 0.08f); } else { Handles.color = Color.white; } DrawKeyPoint(i); if (isCurve[i]) { Handles.color = (draggingCurve && dragIndex == i) ? Color.white : Color.blue; DrawCurvePoint(i); } } //Quit on tool change if (e.type == EventType.KeyDown) { switch (e.keyCode) { case KeyCode.Q: case KeyCode.W: case KeyCode.E: case KeyCode.R: return; } } //Quit if panning or no camera exists if (Tools.current == Tool.View || (e.isMouse && e.button > 0) || Camera.current == null || e.type == EventType.ScrollWheel) { return; } //Quit if laying out if (e.type == EventType.Layout) { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); return; } //Cursor rectangle EditorGUIUtility.AddCursorRect(new Rect(0, 0, Camera.current.pixelWidth, Camera.current.pixelHeight), mouseCursor); mouseCursor = MouseCursor.Arrow; //Extrude key state if (e.keyCode == extrudeKey) { if (extrudeKeyDown) { if (e.type == EventType.KeyUp) { extrudeKeyDown = false; } } else if (e.type == EventType.KeyDown) { extrudeKeyDown = true; } } //Update matrices and snap worldToLocal = polyMesh.transform.worldToLocalMatrix; inverseRotation = Quaternion.Inverse(polyMesh.transform.rotation) * Camera.current.transform.rotation; snap = gridSnap; //Update mouse position screenMousePosition = new Vector3(e.mousePosition.x, Camera.current.pixelHeight - e.mousePosition.y); var plane = new Plane(-polyMesh.transform.forward, polyMesh.transform.position); var ray = Camera.current.ScreenPointToRay(screenMousePosition); float hit; if (plane.Raycast(ray, out hit)) { mousePosition = worldToLocal.MultiplyPoint(ray.GetPoint(hit)); } else { return; } //Update nearest line and split position nearestLine = NearestLine(out splitPosition); //Update the state and repaint var newState = UpdateState(); if (state != newState) { SetState(newState); } HandleUtility.Repaint(); e.Use(); } }
void OnSceneGUI(SceneView sceneView) { if (mode == null) { return; } Event e = Event.current; CheckForEscapeKey(e); if (Tools.current != Tool.None) { SetTool(BrushTool.None); } if (brushSettings == null) { SetBrushSettings(PolyEditorUtility.GetFirstOrNew <BrushSettings>()); } if (PolySceneUtility.SceneViewInUse(e) || tool == BrushTool.None) { // Force exit the current brush if user's mouse left // the SceneView while a brush was still in use. if (m_ApplyingBrush) { OnFinishApplyingBrush(); } return; } int controlID = GUIUtility.GetControlID(FocusType.Passive); if (Util.IsValid(brushTarget)) { HandleUtility.AddDefaultControl(controlID); } switch (e.GetTypeForControl(controlID)) { case EventType.MouseMove: // Handles: // OnBrushEnter // OnBrushExit // OnBrushMove if (EditorApplication.timeSinceStartup - m_LastBrushUpdate > GetTargetFramerate(brushTarget)) { m_LastBrushUpdate = EditorApplication.timeSinceStartup; UpdateBrush(e.mousePosition, Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); } break; case EventType.MouseDown: case EventType.MouseDrag: // Handles: // OnBrushBeginApply // OnBrushApply // OnBrushFinishApply if (EditorApplication.timeSinceStartup - m_LastBrushUpdate > GetTargetFramerate(brushTarget)) { m_LastBrushUpdate = EditorApplication.timeSinceStartup; UpdateBrush(e.mousePosition, Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); ApplyBrush(Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); } break; case EventType.MouseUp: if (m_ApplyingBrush) { OnFinishApplyingBrush(); UpdateBrush(e.mousePosition, Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); } break; case EventType.ScrollWheel: ScrollBrushSettings(e); break; case EventType.KeyDown: // Key down event continues as long as the key is held down. However, we only need to update the brush once while the key is down. // Check if the key has already been marked as pressed in the brush settings, and don't update if it is. if (((e.keyCode == KeyCode.LeftControl || e.keyCode == KeyCode.RightControl) && !brushSettings.isUserHoldingControl) || ((e.keyCode == KeyCode.LeftShift || e.keyCode == KeyCode.RightShift) && !brushSettings.isUserHoldingShift)) { m_LastBrushUpdate = EditorApplication.timeSinceStartup; UpdateBrush(e.mousePosition, Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); } break; case EventType.KeyUp: // Key up only happens once, so don't need to check if we were already holding control/shift if ((e.keyCode == KeyCode.LeftControl || e.keyCode == KeyCode.RightControl) || (e.keyCode == KeyCode.LeftShift || e.keyCode == KeyCode.RightShift)) { m_LastBrushUpdate = EditorApplication.timeSinceStartup; UpdateBrush(e.mousePosition, Event.current.control, Event.current.shift && Event.current.type != EventType.ScrollWheel); } break; case EventType.Repaint: if (Util.IsValid(brushTarget)) { mode.DrawGizmos(brushTarget, brushSettings); } break; } // foreach(var secondaryBrushTarget in m_SecondaryBrushTargets) // { // if(Util.IsValid(secondaryBrushTarget)) // mode.DrawGizmos(secondaryBrushTarget, brushSettings); // } }
public void OnSceneGUI() { var script = target as GraphUpdateScene; // Don't allow editing unless it is the active object if (Selection.activeGameObject != script.gameObject || script.legacyMode) { return; } // Make sure the points array is not null if (script.points == null) { script.points = new Vector3[0]; EditorUtility.SetDirty(script); } List <Vector3> points = Pathfinding.Util.ListPool <Vector3> .Claim(); points.AddRange(script.points); Matrix4x4 invMatrix = script.transform.worldToLocalMatrix; Matrix4x4 matrix = script.transform.localToWorldMatrix; for (int i = 0; i < points.Count; i++) { points[i] = matrix.MultiplyPoint3x4(points[i]); } if (Tools.current != Tool.View && Event.current.type == EventType.Layout) { for (int i = 0; i < script.points.Length; i++) { HandleUtility.AddControl(-i - 1, HandleUtility.DistanceToLine(points[i], points[i])); } } if (Tools.current != Tool.View) { HandleUtility.AddDefaultControl(0); } for (int i = 0; i < points.Count; i++) { if (i == selectedPoint && Tools.current == Tool.Move) { Handles.color = PointSelectedColor; SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius * 2); Vector3 pre = points[i]; Vector3 post = Handles.PositionHandle(points[i], Quaternion.identity); if (pre != post) { Undo.RecordObject(script, "Moved Point"); script.points[i] = invMatrix.MultiplyPoint3x4(post); } } else { Handles.color = PointColor; SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius); } } if (Event.current.type == EventType.MouseDown) { int pre = selectedPoint; selectedPoint = -(HandleUtility.nearestControl + 1); if (pre != selectedPoint) { GUI.changed = true; } } if (Event.current.shift && Tools.current == Tool.Move) { HandleUtility.Repaint(); if (((int)Event.current.modifiers & (int)EventModifiers.Alt) != 0) { if (Event.current.type == EventType.MouseDown && selectedPoint >= 0 && selectedPoint < points.Count) { Undo.RecordObject(script, "Removed Point"); var arr = new List <Vector3>(script.points); arr.RemoveAt(selectedPoint); points.RemoveAt(selectedPoint); script.points = arr.ToArray(); GUI.changed = true; } else if (points.Count > 0) { var index = -(HandleUtility.nearestControl + 1); if (index >= 0 && index < points.Count) { Handles.color = Color.red; SphereCap(0, points[index], Quaternion.identity, HandleUtility.GetHandleSize(points[index]) * 2f * pointGizmosRadius); } } } else { // Find the closest segment int insertionIndex = points.Count; float minDist = float.PositiveInfinity; for (int i = 0; i < points.Count; i++) { float dist = HandleUtility.DistanceToLine(points[i], points[(i + 1) % points.Count]); if (dist < minDist) { insertionIndex = i + 1; minDist = dist; } } var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); System.Object hit = HandleUtility.RaySnap(ray); Vector3 rayhit = Vector3.zero; bool didHit = false; if (hit != null) { rayhit = ((RaycastHit)hit).point; didHit = true; } else { var plane = new Plane(script.transform.up, script.transform.position); float distance; plane.Raycast(ray, out distance); if (distance > 0) { rayhit = ray.GetPoint(distance); didHit = true; } } if (didHit) { if (Event.current.type == EventType.MouseDown) { points.Insert(insertionIndex, rayhit); Undo.RecordObject(script, "Added Point"); var arr = new List <Vector3>(script.points); arr.Insert(insertionIndex, invMatrix.MultiplyPoint3x4(rayhit)); script.points = arr.ToArray(); GUI.changed = true; } else if (points.Count > 0) { Handles.color = Color.green; Handles.DrawDottedLine(points[(insertionIndex - 1 + points.Count) % points.Count], rayhit, 8); Handles.DrawDottedLine(points[insertionIndex % points.Count], rayhit, 8); SphereCap(0, rayhit, Quaternion.identity, HandleUtility.GetHandleSize(rayhit) * pointGizmosRadius); // Project point down onto a plane var zeroed = invMatrix.MultiplyPoint3x4(rayhit); zeroed.y = 0; Handles.color = new Color(1, 1, 1, 0.5f); Handles.DrawDottedLine(matrix.MultiplyPoint3x4(zeroed), rayhit, 4); } } } if (Event.current.type == EventType.MouseDown) { Event.current.Use(); } } // Make sure the convex hull stays up to date script.RecalcConvex(); Pathfinding.Util.ListPool <Vector3> .Release(ref points); if (GUI.changed) { HandleUtility.Repaint(); } }
private void SceneGUI(SceneView sceneView) { //Hides the Manipulators so the user can't accidentally move the camera. if (Selection.activeGameObject == miniMapCameraObject) { Tools.current = Tool.None; } //Creates MiniMap window and updates the texture miniMapRect = GUI.Window(0, miniMapRect, DoMyWindow, "MiniMap"); //Turns on hold left Ctrl if (Event.current.type == EventType.KeyDown) { if (Event.current.keyCode == KeyCode.LeftControl) { if (Event.current.type == EventType.KeyDown) { Event.current.Use(); } holdingCtrl = true; } } //turns on hold MiniMap if pressed LMB on the mini map if (checkMouseBodyRect.Contains(Event.current.mousePosition)) { //This makes it possible for MosueUp events to register HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); if (Event.current.type == EventType.MouseDown) { if (Event.current.button == 0) { holdingMiniMap = true; } else if (Event.current.button == 2) { Cursor.visible = false; //Disable the panning of the viewport camera when panning the mini map if (Event.current.type == EventType.MouseDown) { Event.current.Use(); } mouseStartPos = Event.current.mousePosition; miniMapCameraStartPos = miniMapCameraObject.transform.position; movingMiniMap = true; } } else if (Event.current.type == EventType.ScrollWheel) { //Disable the zooming of the viewport camera when zooming the mini map if (Event.current.type == EventType.ScrollWheel) { Event.current.Use(); } if (holdingCtrl == false) { miniMapCamera.orthographicSize += Event.current.delta.y; miniMapCamera.orthographicSize = Mathf.Clamp(miniMapCamera.orthographicSize, minimapHeightRange.x, minimapHeightRange.y); } else { miniMapCameraObject.transform.position += new Vector3(0.0f, Event.current.delta.y, 0.0f); miniMapCameraObject.transform.position = new Vector3(miniMapCameraObject.transform.position.x, Mathf.Clamp(miniMapCameraObject.transform.position.y, minimapHeightRange.x, minimapHeightRange.y), miniMapCameraObject.transform.position.z); } } } //turns on hold Ribbon if pressed LMB on the mini map ribbon if (checkMouseRibbonRect.Contains(Event.current.mousePosition)) { //This makes it possible for MouseUp events to register HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); if (Event.current.type == EventType.MouseDown) { if (Event.current.button == 0) { SetStartPositions(); holdingRibbon = true; } } } if (holdingMiniMap == true) { sceneView.pivot = GetLocationOnMap(); } if (holdingRibbon == true) { MoveMiniMapWindow(); } if (movingMiniMap == true) { MoveMiniMapCamera(); } //Let go of mouse buttons if (Event.current.type == EventType.MouseUp) { if (Event.current.button == 0 || Event.current.button == 2) { holdingMiniMap = false; holdingRibbon = false; movingMiniMap = false; Cursor.visible = true; } } //Let go of left Ctrl if (Event.current.type == EventType.KeyUp) { if (Event.current.keyCode == KeyCode.LeftControl) { holdingCtrl = false; } } //If the mouse goes out of screen, the holding of LMB will be released if ((holdingMiniMap == true || holdingRibbon == true || movingMiniMap == true || holdingCtrl == true) && MouseInScreen(sceneView) == false) { holdingMiniMap = false; holdingRibbon = false; movingMiniMap = false; holdingCtrl = false; Cursor.visible = true; } //Repaint to update the MiniMap window position HandleUtility.Repaint(); }
private void EventHandler() { if (Event.current.alt) { return; } if (Event.current.type == EventType.KeyDown) { HotkeyFunction(Event.current.keyCode.ToString()); Event.current.Use(); return; } if (currentEditMode != EditMode.View) { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); int button = Event.current.button; switch (currentEditMode) { case EditMode.Voxel: case EditMode.VoxelLayer: volume.useBox = true; break; default: volume.useBox = false; break; } switch (currentEditMode) { case EditMode.Voxel: if (button == 0) { DrawMarker(false); } else if (button <= 1) { DrawMarker(true); } if (Event.current.type == EventType.MouseDown) { if (button == 0) { Paint(false); } else if (button == 1) { Paint(true); Tools.viewTool = ViewTool.None; Event.current.Use(); } } if (Event.current.type == EventType.MouseUp) { UpdateDirtyChunks(); } break; case EditMode.VoxelLayer: DrawLayerMarker(); if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag) { if (button == 0) { PaintLayer(false); } else if (button == 1) { PaintLayer(true); Tools.viewTool = ViewTool.None; Event.current.Use(); } } if (Event.current.type == EventType.MouseUp) { UpdateDirtyChunks(); } break; case EditMode.Object: case EditMode.ObjectLayer: if (Event.current.type == EventType.MouseDown) { if (button == 0) { PaintPieces(false); } else if (button == 1) { PaintPieces(true); Tools.viewTool = ViewTool.None; Event.current.Use(); } } DrawGridMarker(); break; default: break; } } }
/* #region Inspector GUI * * public override void OnInspectorGUI() * { * //Get tilemap * if (tileMap == null) * tileMap = (TileMap)target; * * //Crazy hack to register undo * if (undoCallback == null) * { * undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", BindingFlags.NonPublic | BindingFlags.Static); * if (undoCallback != null) * undoCallback.SetValue(null, new EditorApplication.CallbackFunction(OnUndoRedo)); * } * * //Toggle editing mode * if (editing) * { * if (GUILayout.Button("Stop Editing")) * editing = false; * else * { * EditorGUILayout.BeginHorizontal(); * if (GUILayout.Button("Update All")) * UpdateAll(); * if (GUILayout.Button("Clear")) * Clear(); * EditorGUILayout.EndHorizontal(); * } * } * else if (GUILayout.Button("Edit TileMap")) * editing = true; * * //Tile Size * EditorGUI.BeginChangeCheck(); * var newTileSize = EditorGUILayout.FloatField("Tile Size", tileMap.tileSize); * if (EditorGUI.EndChangeCheck()) * { * RecordDeepUndo(); * tileMap.tileSize = newTileSize; * UpdatePositions(); * } * * //Tile Prefab * EditorGUI.BeginChangeCheck(); * var newTilePrefab = (Transform)EditorGUILayout.ObjectField("Tile Prefab", tileMap.tilePrefab, typeof(Transform), false); * if (EditorGUI.EndChangeCheck()) * { * RecordUndo(); * tileMap.tilePrefab = newTilePrefab; * } * * //Tile Map * EditorGUI.BeginChangeCheck(); * var newTileSet = (TileSet)EditorGUILayout.ObjectField("Tile Set", tileMap.tileSet, typeof(TileSet), false); * if (EditorGUI.EndChangeCheck()) * { * RecordUndo(); * tileMap.tileSet = newTileSet; * } * * //Tile Prefab selector * if (tileMap.tileSet != null) * { * EditorGUI.BeginChangeCheck(); * var names = new string[tileMap.tileSet.prefabs.Length + 1]; * var values = new int[names.Length + 1]; * names[0] = tileMap.tilePrefab != null ? tileMap.tilePrefab.name : ""; * values[0] = 0; * for (int i = 1; i < names.Length; i++) * { * names[i] = tileMap.tileSet.prefabs[i - 1] != null ? tileMap.tileSet.prefabs[i - 1].name : ""; * //if (i < 10) * // names[i] = i + ". " + names[i]; * values[i] = i; * } * var index = EditorGUILayout.IntPopup("Select Tile", 0, names, values); * if (EditorGUI.EndChangeCheck() && index > 0) * { * RecordUndo(); * tileMap.tilePrefab = tileMap.tileSet.prefabs[index - 1]; * } * } * * //Selecting direction * EditorGUILayout.BeginHorizontal(GUILayout.Width(60)); * EditorGUILayout.PrefixLabel("Direction"); * EditorGUILayout.BeginVertical(GUILayout.Width(20)); * GUILayout.Space(20); * if (direction == 3) * GUILayout.Box("<", GUILayout.Width(20)); * else if (GUILayout.Button("<")) * direction = 3; * GUILayout.Space(20); * EditorGUILayout.EndVertical(); * EditorGUILayout.BeginVertical(GUILayout.Width(20)); * if (direction == 0) * GUILayout.Box("^", GUILayout.Width(20)); * else if (GUILayout.Button("^")) * direction = 0; * if (direction == -1) * GUILayout.Box("?", GUILayout.Width(20)); * else if (GUILayout.Button("?")) * direction = -1; * if (direction == 2) * GUILayout.Box("v", GUILayout.Width(20)); * else if (GUILayout.Button("v")) * direction = 2; * EditorGUILayout.EndVertical(); * EditorGUILayout.BeginVertical(GUILayout.Width(20)); * GUILayout.Space(20); * if (direction == 1) * GUILayout.Box(">", GUILayout.Width(20)); * else if (GUILayout.Button(">")) * direction = 1; * GUILayout.Space(20); * EditorGUILayout.EndVertical(); * EditorGUILayout.EndHorizontal(); * * //Connect diagonals * EditorGUI.BeginChangeCheck(); * var newConnectDiagonals = EditorGUILayout.Toggle("Connect Diagonals", tileMap.connectDiagonals); * if (EditorGUI.EndChangeCheck()) * { * RecordUndo(); * tileMap.connectDiagonals = newConnectDiagonals; * updateConnections = true; * SceneView.RepaintAll(); * } * * //Connect diagonals * if (tileMap.connectDiagonals) * { * EditorGUI.BeginChangeCheck(); * var newCutCorners = EditorGUILayout.Toggle("Cut Corners", tileMap.cutCorners); * if (EditorGUI.EndChangeCheck()) * { * RecordUndo(); * tileMap.cutCorners = newCutCorners; * updateConnections = true; * SceneView.RepaintAll(); * } * } * * //Draw path tiles * EditorGUI.BeginChangeCheck(); * drawPathMap = EditorGUILayout.Toggle("Draw Path Map", drawPathMap); * if (EditorGUI.EndChangeCheck()) * SceneView.RepaintAll(); * } * #endregion */ #region Scene GUI void OnSceneGUI() { //Get tilemap if (tileMap == null) { tileMap = (TileMap)target; } //Update paths if (updateConnections) { updateConnections = false; tileMap.UpdateConnections(); } //Toggle editing if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Tab) { editing = !editing; EditorUtility.SetDirty(target); } //Toggle selected tile /*if (tileMap.tileSet != null) * { * if (e.type == EventType.KeyDown) * { * var code = (int)e.keyCode - (int)KeyCode.Alpha1; * if (code >= 0 && code < tileMap.tileSet.prefabs.Length) * { * RecordUndo(); * tileMap.tilePrefab = tileMap.tileSet.prefabs[code]; * e.Use(); * return; * } * } * }*/ //Draw path nodes if (drawPathMap) { Handles.color = new Color(0, 0, 1, 0.5f); foreach (var instance in tileMap.instances) { var tile = instance.GetComponent <PathTile>(); if (tile != null) { Handles.DotCap(0, tile.transform.localPosition, Quaternion.identity, tileMap.tileSize / 17); foreach (var other in tile.connections) { if (other != null && tile.GetInstanceID() > other.GetInstanceID()) { Handles.DrawLine(tile.transform.localPosition, other.transform.localPosition); } } } } } if (editing) { //Hide mesh HideWireframe(true); //Quit on tool change if (e.type == EventType.KeyDown) { switch (e.keyCode) { case KeyCode.Q: case KeyCode.W: case KeyCode.E: case KeyCode.R: return; } } //Quit if panning or no camera exists if (Tools.current == Tool.View || (e.isMouse && e.button > 1) || Camera.current == null || e.type == EventType.ScrollWheel) { return; } //Quit if laying out if (e.type == EventType.Layout) { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); return; } //Update matrices Handles.matrix = tileMap.transform.localToWorldMatrix; worldToLocal = tileMap.transform.worldToLocalMatrix; //Draw axes Handles.color = Color.red; Handles.DrawLine(new Vector3(-tileMap.tileSize, 0, 0), new Vector3(tileMap.tileSize, 0, 0)); Handles.DrawLine(new Vector3(0, 0, -tileMap.tileSize), new Vector3(0, 0, tileMap.tileSize)); //Update mouse position var plane = new Plane(tileMap.transform.up, tileMap.transform.position); var ray = Camera.current.ScreenPointToRay(new Vector3(e.mousePosition.x, Camera.current.pixelHeight - e.mousePosition.y)); float hit; if (!plane.Raycast(ray, out hit)) { return; } var mousePosition = worldToLocal.MultiplyPoint(ray.GetPoint(hit)); cursorX = Mathf.RoundToInt(mousePosition.x / tileMap.tileSize); cursorZ = Mathf.RoundToInt(mousePosition.z / tileMap.tileSize); //Update the state and repaint state = UpdateState(); HandleUtility.Repaint(); e.Use(); } else { HideWireframe(false); } }