Esempio n. 1
0
        public static void DrawMarquee(Vector2 marqueeStart, Vector2 marqueeEnd)
        {
            Vector2 point1 = EditorHelper.ConvertMousePointPosition(marqueeStart);
            Vector2 point2 = EditorHelper.ConvertMousePointPosition(marqueeEnd);

            Rect rect = new Rect(point1.x, point1.y, point2.x - point1.x, point2.y - point1.y);

            SabreGraphics.GetSelectedBrushMaterial().SetPass(0);

            GL.PushMatrix();
            GL.LoadPixelMatrix();

            GL.Begin(GL.QUADS);
            GL.Color(new Color(0.2f, 0.3f, 0.8f, 0.3f));

            // Marquee fill (draw double sided)
            SabreGraphics.DrawScreenRectFill(rect);

            GL.End();

            // Marquee border
            GL.Begin(GL.LINES);
            GL.Color(Color.white);

            // Draw marquee box edges
            SabreGraphics.DrawScreenRectOuter(rect);

            GL.End();
            GL.PopMatrix();
        }
 public void OnRepaint(UnityEditor.SceneView sceneView, Event e)
 {
     // Selected brush green outline
     if (!isBrushConvex)
     {
         SabreGraphics.GetSelectedBrushMaterial().SetPass(0);
         DrawPolygons(Color.red, polygons);
     }
 }
Esempio n. 3
0
        private static void Draw()
        {
            SceneView sceneView = SceneView.currentDrawingSceneView;

            // If the user has turned on hiding of perspectve grid then hide it if perspective
            if (!sceneView.orthographic && CurrentSettings.HideGridInPerspective)
            {
                return;
            }

            // Cache additional references
            Camera    camera    = sceneView.camera;
            Transform transform = camera.transform;

            float fullSnapDistance = CurrentSettings.PositionSnapDistance;
            float snapDistance     = fullSnapDistance;

            // Calculate various camera positions and its orientation
            EditorHelper.SceneViewCamera cameraOrientation = EditorHelper.GetSceneViewCamera(sceneView);

            // True if the camera is both orthographic (iso) and axis-aligned
            bool orthographicAxisAligned = sceneView.orthographic && cameraOrientation != EditorHelper.SceneViewCamera.Other;

            Vector3 cameraPosition = transform.position;

            Vector3 roundedCameraPosition = MathHelper.RoundVector3(cameraPosition, snapDistance);

            // Calculate the world vectors to use for the X and Y grid axes
            Vector3 xDirection = orthographicAxisAligned ? transform.right : Vector3.right;
            Vector3 yDirection = orthographicAxisAligned ? transform.up : Vector3.forward;

            // Now calculate a depth offset to help with dealing with objects far from the origin
            Vector3 depthOffset = Vector3.zero;

            if (orthographicAxisAligned)
            {
                float depthFudge = 1;

                depthOffset = transform.forward * (camera.nearClipPlane + depthFudge + Vector3.Dot(cameraPosition, transform.forward));

//				Debug.Log(camera.nearClipPlane + " to " + camera.farClipPlane);
//				Debug.Log(depthOffset);
            }
            else
            {
                depthOffset = Vector3.zero;
            }

            // Line colors
            Color normalLine   = new Color32(200, 200, 200, 128);
            Color smallestLine = new Color32(50, 50, 50, 128);

            Color xAxisColor = ColorForVector(xDirection);
            Color yAxisColor = ColorForVector(yDirection);


            // How many lines to draw in each axis
            int xCount;
            int yCount;

            // Center point of the grid in each axis
            int xMid;
            int yMid;


            bool scaledUp = false;

            // Width of one world unit in screen pixels
            float gridWidthPixels = CalculateWorldUnitScreenSize(camera, 1);

            if (snapDistance >= 8)
            {
                gridWidthPixels = CalculateWorldUnitScreenSize(camera, snapDistance);
            }

            if (gridWidthPixels < MIN_VISIBLE)
            {
                if (snapDistance > 8)
                {
                    snapDistance    = Mathf.Pow(Mathf.Floor(Mathf.Log(snapDistance, 8)), 8);
                    gridWidthPixels = CalculateWorldUnitScreenSize(camera, snapDistance);
                }

                while (gridWidthPixels < MIN_VISIBLE)
                {
                    if (snapDistance < 8)
                    {
                        snapDistance = 8;
                    }
                    else
                    {
                        snapDistance *= 8;
                    }
                    scaledUp        = true;
                    gridWidthPixels = CalculateWorldUnitScreenSize(camera, snapDistance);
                }
            }

            // Alpha of the granular lines, generally based on distance
            float minorLineAlphaMultiplier = Mathf.InverseLerp(MIN_VISIBLE, MAX_VISIBLE, gridWidthPixels);

            float sanityScalar = Mathf.Max(1, snapDistance) * Mathf.Lerp(2, 1, minorLineAlphaMultiplier);

            if (orthographicAxisAligned)
            {
                float cameraHeight = camera.orthographicSize * 2;
                float cameraWidth  = camera.aspect * cameraHeight;

                xCount = Mathf.CeilToInt(cameraWidth / snapDistance);
                yCount = Mathf.CeilToInt(cameraHeight / snapDistance);

                xMid = (int)(Vector3.Dot(roundedCameraPosition, xDirection) / snapDistance);
                yMid = (int)(Vector3.Dot(roundedCameraPosition, yDirection) / snapDistance);
            }
            else
            {
                List <Vector3> pointsInGrid = GetGridMinMax(camera);

                Vector3 pivotPointOnGrid = sceneView.pivot;
                pivotPointOnGrid.y = 0;
                pointsInGrid.Add(pivotPointOnGrid);

                Vector3 min = pointsInGrid[0];
                Vector3 max = pointsInGrid[0];
                // Calculate min,max
                for (int i = 1; i < pointsInGrid.Count; i++)
                {
                    min.x = Mathf.Min(pointsInGrid[i].x, min.x);
                    min.z = Mathf.Min(pointsInGrid[i].z, min.z);

                    max.x = Mathf.Max(pointsInGrid[i].x, max.x);
                    max.z = Mathf.Max(pointsInGrid[i].z, max.z);
                }

                // Ensure the grid isn't crazily big
                min.x = Mathf.Max(min.x, pivotPointOnGrid.x - MAJOR_LINE_DISTANCE * sanityScalar);
                min.z = Mathf.Max(min.z, pivotPointOnGrid.z - MAJOR_LINE_DISTANCE * sanityScalar);

                max.x = Mathf.Min(max.x, pivotPointOnGrid.x + MAJOR_LINE_DISTANCE * sanityScalar);
                max.z = Mathf.Min(max.z, pivotPointOnGrid.z + MAJOR_LINE_DISTANCE * sanityScalar);

                // Now calculate grid line count
                xCount = Mathf.CeilToInt((max.x - min.x) / snapDistance);
                yCount = Mathf.CeilToInt((max.z - min.z) / snapDistance);

                xMid = Mathf.RoundToInt((min.x + max.x) / 2f / snapDistance);
                yMid = Mathf.RoundToInt((min.z + max.z) / 2f / snapDistance);
            }

            // Pad out the edge case
            xCount += 2;
            yCount += 2;

            int xStart = xMid - xCount / 2;
            int yStart = yMid - yCount / 2;

            int xEnd = xMid + xCount / 2;
            int yEnd = yMid + yCount / 2;


            Vector3 cameraPositionOnPlane = new Vector3(transform.position.x, 0, transform.position.z);

            // Start rendering
            SabreGraphics.GetSelectedBrushMaterial().SetPass(0);
            GL.Begin(GL.LINES);

            int lineDistributonWorld = 8;

            while (lineDistributonWorld <= snapDistance)
            {
                lineDistributonWorld *= 8;
            }

            // Calculate repetition count of the distribution lines
            int lineDistributionCount;

            if (snapDistance < lineDistributonWorld)
            {
                lineDistributionCount = (int)(lineDistributonWorld / snapDistance);
            }
            else
            {
                lineDistributionCount = 1;
            }

            int gridJump = 8;

            // Ensure we don't split grid lines at too high a density when drawing as that would kill performance
            if (snapDistance < 1)
            {
                gridJump = Mathf.RoundToInt(gridJump / snapDistance);
            }

            for (int y = yStart; y <= yEnd; y++)
            {
                Color sourceColor = normalLine;
                bool  majorLine   = true;
                if (y == 0)
                {
                    sourceColor = xAxisColor;
                }
                else if (y % lineDistributionCount != 0)
                {
                    majorLine = false;
                    if (!scaledUp)
                    {
                        sourceColor = smallestLine;
                    }

                    sourceColor.a *= minorLineAlphaMultiplier * 0.6f;
                }

                float activeDistance = sanityScalar * (majorLine ? MAJOR_LINE_DISTANCE : MINOR_LINE_DISTANCE);

                for (int x = xStart; x < xEnd; x += gridJump)
                {
                    Color color = sourceColor;

                    Vector3 yOffset = y * yDirection * snapDistance;

                    Vector3 center = depthOffset + yOffset;

                    Vector3 testPoint = center + xDirection * (x + gridJump / 2f) * snapDistance;
                    testPoint.y = 0;
                    float squareDistance = (testPoint - cameraPositionOnPlane).sqrMagnitude;

                    if (squareDistance > (activeDistance * activeDistance))
                    {
                        continue;
                    }

                    float distance = Mathf.Sqrt(squareDistance);

                    color.a *= Mathf.InverseLerp(activeDistance, activeDistance / 2f, distance);

                    GL.Color(color);

                    GL.Vertex(center + xDirection * (x + 0) * snapDistance);
                    GL.Vertex(center + xDirection * (x + gridJump) * snapDistance);
                }
            }

            for (int x = xStart; x <= xEnd; x++)
            {
                Color sourceColor = normalLine;
                bool  majorLine   = true;
                if (x == 0)
                {
                    sourceColor = yAxisColor;
                }
                else if (x % lineDistributionCount != 0)
                {
                    majorLine = false;
                    if (!scaledUp)
                    {
                        sourceColor = smallestLine;
                    }

                    sourceColor.a *= minorLineAlphaMultiplier * 0.6f;
                }

                float activeDistance = sanityScalar * (majorLine ? MAJOR_LINE_DISTANCE : MINOR_LINE_DISTANCE);

                for (int y = yStart; y < yEnd; y += gridJump)
                {
                    Color color = sourceColor;

                    Vector3 xOffset = x * xDirection * snapDistance;

                    Vector3 center = depthOffset + xOffset;

                    Vector3 testPoint = center + yDirection * (y + gridJump / 2f) * snapDistance;
                    testPoint.y = 0;
                    float squareDistance = (testPoint - cameraPositionOnPlane).sqrMagnitude;

                    if (squareDistance > (activeDistance * activeDistance))
                    {
                        continue;
                    }

                    float distance = Mathf.Sqrt(squareDistance);

                    color.a *= Mathf.InverseLerp(activeDistance, activeDistance * 0.5f, distance);


                    GL.Color(color);

                    GL.Vertex(center + yDirection * (y + 0) * snapDistance);
                    GL.Vertex(center + yDirection * (y + gridJump) * snapDistance);
                }
            }

            GL.End();
        }
Esempio n. 4
0
        void DrawVertices(SceneView sceneView, Event e)
        {
            Camera sceneViewCamera = sceneView.camera;

            SabreGraphics.GetVertexMaterial().SetPass(0);
            GL.PushMatrix();
            GL.LoadPixelMatrix();

            GL.Begin(GL.QUADS);

            // Draw each handle, colouring it if it's selected
            foreach (PrimitiveBrush brush in targetBrushes)
            {
                Polygon[] polygons = brush.GetPolygons();

                Vector3 target;

                for (int i = 0; i < polygons.Length; i++)
                {
                    for (int j = 0; j < polygons[i].Vertices.Length; j++)
                    {
                        Vertex vertex = polygons[i].Vertices[j];

                        if (selectedVertices.ContainsKey(vertex))
                        {
                            GL.Color(new Color32(0, 255, 128, 255));
                        }
                        else
                        {
                            GL.Color(Color.white);
                        }

                        target = sceneViewCamera.WorldToScreenPoint(brush.transform.TransformPoint(vertex.Position));
                        if (target.z > 0)
                        {
                            // Make it pixel perfect
                            target = MathHelper.RoundVector3(target);
                            SabreGraphics.DrawBillboardQuad(target, 8, 8);
                        }
                    }
                }
            }

            GL.End();

            // Draw lines for selected edges
            SabreGraphics.GetSelectedBrushMaterial().SetPass(0);

            GL.Begin(GL.LINES);
            GL.Color(Color.green);

            for (int edgeIndex = 0; edgeIndex < selectedEdges.Count; edgeIndex++)
            {
                Edge edge = selectedEdges[edgeIndex];

                if (selectedVertices.ContainsKey(edge.Vertex1))
                {
                    Brush brush = selectedVertices[edge.Vertex1];

                    Vector3 target1 = sceneViewCamera.WorldToScreenPoint(brush.transform.TransformPoint(edge.Vertex1.Position));
                    Vector3 target2 = sceneViewCamera.WorldToScreenPoint(brush.transform.TransformPoint(edge.Vertex2.Position));

                    if (target1.z > 0 && target2.z > 0)
                    {
                        SabreGraphics.DrawScreenLine(target1, target2);
                    }
                }
            }

            GL.End();

            GL.PopMatrix();
        }
Esempio n. 5
0
        public void OnSceneGUI(SceneView sceneView)
        {
            Event e = Event.current;

            //			if (e.type == EventType.Repaint)
            //			{
            //				if(CurrentSettings.GridMode == GridMode.SabreCSG)
            //				{
            //					CSGGrid.Activate();
            //				}
            //			}

            if (!EditMode)
            {
                return;
            }

            // Frame rate tracking
            if (e.type == EventType.Repaint)
            {
                currentFrameDelta     = Time.realtimeSinceStartup - currentFrameTimestamp;
                currentFrameTimestamp = Time.realtimeSinceStartup;
            }

            // Raw checks for tracking mouse events (use raw so that consumed events are not ignored)
            if (e.rawType == EventType.MouseDown)
            {
                mouseIsDragging = false;
                mouseIsHeld     = true;

                if (e.button == 0 && GUIUtility.hotControl == 0)
                {
                    GUIUtility.keyboardControl = 0;
                }
            }
            else if (e.rawType == EventType.MouseDrag)
            {
                mouseIsDragging = true;
            }
            else if (e.rawType == EventType.MouseUp)
            {
                mouseIsHeld = false;
            }

//			if (CurrentSettings.BrushesVisible)
            {
                // No idea what this line of code means, but it seems to stop normal mouse selection
                HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
            }

            if (EditMode)
            {
                // In CSG mode, prevent the normal tools, so that the user must use our tools instead
                Tools.current = UnityEditor.Tool.None;
            }

            int concaveBrushCount = 0;

            for (int i = 0; i < brushes.Count; i++)
            {
                if (brushes[i] != null && !brushes[i].IsBrushConvex)
                {
                    concaveBrushCount++;
                }
            }
            if (concaveBrushCount > 0)
            {
                Toolbar.WarningMessage = concaveBrushCount + " Concave Brush" + (concaveBrushCount > 1 ? "es" : "") + " Detected";
            }
            else
            {
                //				Toolbar.WarningMessage = "";
            }

            Toolbar.CSGModel = this;
            Toolbar.OnSceneGUI(sceneView, e);

            if (e.type == EventType.Repaint)            // || e.type == EventType.Layout)
            {
                if (tools[CurrentSettings.CurrentMode].BrushesHandleDrawing)
                {
                    SabreGraphics.GetSelectedBrushMaterial().SetPass(0);
                    // Selection
                    GL.Begin(GL.LINES);
                    Color outlineColor = Color.blue;

                    for (int brushIndex = 0; brushIndex < brushes.Count; brushIndex++)
                    {
                        Brush brush = brushes[brushIndex];
                        if (brush == null)
                        {
                            continue;
                        }
                        GameObject brushGameObject = brush.gameObject;

                        if (!brushGameObject.activeInHierarchy)
                        {
                            continue;
                        }

                        if (Selection.Contains(brushGameObject))
                        {
                            if (brushes[brushIndex].Mode == CSGMode.Add)
                            {
                                outlineColor = Color.cyan;
                            }
                            else
                            {
                                outlineColor = Color.yellow;
                            }
                        }
                        else if (CurrentSettings.BrushesVisible)
                        {
                            if (brushes[brushIndex].Mode == CSGMode.Add)
                            {
                                outlineColor = Color.blue;
                            }
                            else
                            {
                                outlineColor = new Color32(255, 130, 0, 255);
                            }
                        }
                        else
                        {
                            continue;
                        }

                        GL.Color(outlineColor);

                        Polygon[] polygons       = brush.GetPolygons();
                        Transform brushTransform = brush.transform;

                        // Brush Outline
                        for (int i = 0; i < polygons.Length; i++)
                        {
                            Polygon polygon = polygons[i];

                            for (int j = 0; j < polygon.Vertices.Length; j++)
                            {
                                Vector3 position = brushTransform.TransformPoint(polygon.Vertices[j].Position);
                                GL.Vertex(position);

                                if (j < polygon.Vertices.Length - 1)
                                {
                                    Vector3 position2 = brushTransform.TransformPoint(polygon.Vertices[j + 1].Position);
                                    GL.Vertex(position2);
                                }
                                else
                                {
                                    Vector3 position2 = brushTransform.TransformPoint(polygon.Vertices[0].Position);
                                    GL.Vertex(position2);
                                }
                            }
                        }
                    }

                    GL.End();

                    for (int i = 0; i < brushes.Count; i++)
                    {
                        if (brushes[i] is PrimitiveBrush && brushes[i] != null && brushes[i].gameObject.activeInHierarchy)
                        {
                            ((PrimitiveBrush)brushes[i]).OnRepaint(sceneView, e);
                        }
                    }
                }
            }

            if (e.type == EventType.Repaint)
            {
                Rect rect = new Rect(0, 0, Screen.width, Screen.height);
                EditorGUIUtility.AddCursorRect(rect, SabreMouse.ActiveCursor);
            }
            //

            //		int hotControl = GUIUtility.hotControl;
            //		if(hotControl != 0)
            //			Debug.Log (hotControl);
            //		Tools.viewTool = ViewTool.None;

            PrimitiveBrush primitiveBrush = null;

            if (Selection.activeGameObject != null)
            {
                primitiveBrush = Selection.activeGameObject.GetComponent <PrimitiveBrush>();
//				primitiveBrush = Selection.activeGameObject.GetComponentInChildren<PrimitiveBrush>();
            }

            List <PrimitiveBrush> primitiveBrushes = new List <PrimitiveBrush>();

            for (int i = 0; i < Selection.gameObjects.Length; i++)
            {
                PrimitiveBrush[] matchedBrushes = Selection.gameObjects[i].GetComponents <PrimitiveBrush>();
//				PrimitiveBrush[] matchedBrushes = Selection.gameObjects[i].GetComponentsInChildren<PrimitiveBrush>();
                if (matchedBrushes.Length > 0)
                {
                    primitiveBrushes.AddRange(matchedBrushes);
                }
            }

            Tool lastTool = activeTool;

            if (tools.ContainsKey(CurrentSettings.CurrentMode))
            {
                activeTool = tools[CurrentSettings.CurrentMode];
            }
            else
            {
                activeTool = null;
            }

            if (activeTool != null)
            {
                activeTool.CSGModel           = this;
                activeTool.PrimaryTargetBrush = primitiveBrush;
                activeTool.TargetBrushes      = primitiveBrushes.ToArray();
                activeTool.OnSceneGUI(sceneView, e);

                if (activeTool != lastTool)
                {
                    if (lastTool != null)
                    {
                        lastTool.Deactivated();
                    }
                    activeTool.ResetTool();
                }
            }

//			if(e.type == EventType.DragPerform)
//			{
//				Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
//
//				RaycastHit hit = new RaycastHit();
//
//				int layerMask = 1 << LayerMask.NameToLayer("CSGMesh");
//				// Invert the layer mask
//				layerMask = ~layerMask;
//
//				// Shift mode means only add what they click (clicking nothing does nothing)
//				if (Physics.Raycast(ray, out hit, float.PositiveInfinity, layerMask))
//				{
//										OnDragDrop(hit.collider.gameObject);
//				}
//			}

            if (e.type == EventType.MouseDown)
            {
            }
            else if (e.type == EventType.MouseDrag)
            {
            }
            else if (e.type == EventType.MouseUp)
            {
                OnMouseUp(sceneView, e);
                SabreMouse.ResetCursor();
            }
            else if (e.type == EventType.KeyDown || e.type == EventType.KeyUp)
            {
                OnKeyAction(sceneView, e);
            }

            if (CurrentSettings.OverrideFlyCamera)
            {
                LinearFPSCam.OnSceneGUI(sceneView);
            }
        }
Esempio n. 6
0
        void OnRepaint(SceneView sceneView, Event e)
        {
            if (primaryTargetBrush != null)
            {
                // Use a helper method to draw a visualisation of the clipping plane
                float largestExtent = GetBounds().GetLargestExtent();
                float planeSize     = largestExtent * 4f;
//				clipPlane.
                SabreGraphics.DrawPlane(displayPlane, planePosition, new Color(0f, 1f, 0f, .3f), new Color(1f, 0f, 0f, .3f), planeSize);

                // Selected brush green outline
                SabreGraphics.GetSelectedBrushMaterial().SetPass(0);

                // Draw black lines where the clip plane intersects the brushes
                if (!sceneView.camera.orthographic || EditorHelper.GetSceneViewCamera(sceneView) == EditorHelper.SceneViewCamera.Other)
                {
                    GL.Begin(GL.LINES);
                    GL.Color(Color.black);

                    foreach (PrimitiveBrush brush in targetBrushes)
                    {
                        Polygon[] polygons = brush.GenerateTransformedPolygons();
                        foreach (Polygon polygon in polygons)
                        {
                            Vector3 position1;
                            Vector3 position2;
                            if (Polygon.PlanePolygonIntersection(polygon, out position1, out position2, displayPlane))
                            {
                                GL.Vertex(position1);
                                GL.Vertex(position2);
                            }
                        }
                    }

                    GL.End();
                }

                if (displayPoint)
                {
                    Camera sceneViewCamera = sceneView.camera;

                    SabreGraphics.GetVertexMaterial().SetPass(0);
                    GL.PushMatrix();
                    GL.LoadPixelMatrix();

                    GL.Begin(GL.QUADS);


                    // Draw points in reverse order because we want the precedence to be Red, Green, Blue

                    GL.Color(Color.blue);

                    Vector3 target = sceneViewCamera.WorldToScreenPoint(points[2]);

                    if (target.z > 0)
                    {
                        // Make it pixel perfect
                        target = MathHelper.RoundVector3(target);
                        SabreGraphics.DrawBillboardQuad(target, 8, 8);
                    }

                    GL.Color(Color.green);

                    target = sceneViewCamera.WorldToScreenPoint(points[1]);

                    if (target.z > 0)
                    {
                        // Make it pixel perfect
                        target = MathHelper.RoundVector3(target);
                        SabreGraphics.DrawBillboardQuad(target, 8, 8);
                    }

                    GL.Color(Color.red);

                    target = sceneViewCamera.WorldToScreenPoint(points[0]);

                    if (target.z > 0)
                    {
                        // Make it pixel perfect
                        target = MathHelper.RoundVector3(target);
                        SabreGraphics.DrawBillboardQuad(target, 8, 8);
                    }

                    GL.End();
                    GL.PopMatrix();
                }
            }

            // Draw UI specific to this editor
//			GUI.backgroundColor = Color.red;
            Rect     rectangle = new Rect(0, 50, 210, 130);
            GUIStyle toolbar   = new GUIStyle(EditorStyles.toolbar);

            toolbar.normal.background = SabreGraphics.ClearTexture;
            toolbar.fixedHeight       = rectangle.height;
            GUILayout.Window(140006, rectangle, OnToolbarGUI, "", toolbar);
        }