1. Topics Addressed in the Chapter

    1. Geometry of almost all drawing objects is based on a set of control points

      Examples:

      • A line is defined by its two endpoints
      • A rectangle is defined by its upper left and lower right corners or, alternatively, by its upper left corner and its width and height (selection handles added to the edges of a rectangle typically permit only the width or height to be adjusted).

    2. Distance from a Point to an Object: Used for selection

    3. Bounds of an Object

      1. Bounding Box: The smallest rectangle that completely encloses an object

      2. Uses

        1. display: determines the regions of the screen that must be redrawn when the object is modified

        2. simplifies containment checks: if we know the bounding box for a complex object, we can check to see whether a point lies within the bounding box before performing a more mathematically complicated containment check

    4. Nearest Point to an Object: Useful when we are not trying to select an object but rather some point on the object

      Example: If we are using snapping, then as the mouse cursor approaches an object, we would like to snap the mouse cursor to the nearest point on the object

    5. Intersections: Determines the point(s) where two objects intersect

      Example: Finding the point on a circle where a line that connects the centers of two circles intersects the circle

    6. Inside/Outside: For filled objects we often want to know whether a point is inside or outside the object

  2. Geometric Equations: We need equations that we can solve to answer the above questions

    1. Implicit Equations: Implicit equations have the form
              F(x,y) = 0
      	  
      Example: The equation for a line is Ax + By + C = 0

      1. Advantages

        1. Implicit equations often divide a plane into two regions and can help us determine whether a point lies inside or outside a region

          Example: The implicit equation for a circle whose center lies at the origin is

          	       F(x, y) = x2 + y2 - r2
          	  
          where r is the radius of the circle. The following statements are all true:

          • F(x,y) > 0: point is outside the circle
          • F(x,y) < 0: point is inside the circle
          • F(x,y) = 0: point is on the boundary of the circle

        2. We can often normalize an implicit equation so that it returns a distance of a point from an object. Normalization is accomplished by dividing by constant coefficients

    2. Parametric Equations: Parametric equations are ones in which the x and y points are determined by one or more parameters:

      Example: A circle has the following parametric equations

                 x = xc + R*cos 2πt
      	   y = yc + R*sin 2πt
          
      where t is in the range [0,1)

      1. Parametric equations are good for calculating the nearest point on a shape using a variation of binary search (Figure 12.19). The book's algorithm divides the t-interval into 10 increments with 11 "dividers". The initial dividers are 0, .1, .2, ..., .9, 1.0.

        1. Each divider represents a point on the parametric shape.
        2. At each divider the algorithm computes the distance from the mouse to the parametric shape. It selects the closest divider point from the 11 it computes, then narrows the interval to the divider to the left and right of this divider point. For example if the mouse is closest to the parametric shape at t = 0.6, then the next interval will be chosen as t = [0.5, 0.7], which are the intervals to the left and right of 0.6.
        3. The interval is again divided into 10 increments and the same computation is performed.
        4. When the distance between the points represented by the beginning and ending of the t-range is less than 1, the algorithm returns the point at the middle of the t-range, because at a distance of less than 1, you're close enough for pixel resolution. For example, suppose the interval has been reduced to t = [0.54, 0.56] and that the distance between the points at (x(.54), y(.54)) and (x(.56), y(.56)) is less than 1
        5. Then we would return the point (x(.55), y(.55)) as the nearest point to the mouse.

      2. Parametric equations are also good for handling animated movement, because it is easy to vary the t parameter

  3. Path-Defined Shapes (i.e., shapes that are not filled)

    1. Lines

      1. Implicit Equation: ax + by + c = 0

        1. To derive the coefficients, remember that the familiar version of the line is:
          	
          		y = slope * x + c.
          	     
          where c is often called the y-intercept (where the line intercepts the y-axis). In an interface, we typically are given the two endpoints of a line line as P1 and P2. However, the book uses A and B as the two endpoints so I will use them here as well. Then the above equation can be rewritten as:
                              B.y - A.y
          		y = ----------- * x + c 
                              B.x - A.x
          	     
          Multiplying both sides by (B.x - A.x) yields:
          		(B.x - A.x) * y = (B.y - A.y) * x + c
          		
          We can now easily derive the implicit equation by moving y to the right side of the equation:
          		0 = (B.y - A.y) * x - (B.x - A.x) * y + c
          		
          Clearly A = B.y - A.y and B = -(B.x - A.x) or alternatively, (A.x - B.x).

          How to derive c:

          	       ax + by + c = 0
          	       => c = -ax - by
                         => c = -aA.x - bA.y  (fill in one of the known pts for the line)
          	       
        2. We can normalize the implicit equation by dividing the coefficients of the implicit equation by the length of the line segment. If we do so, then the implicit equation will return the distance of a point from the line segment. Note that the coefficients a and b capture the x and y increments of the line segment, so we can obtain the line segment length via the following equation:

          1. line seg length = sqrt(a2 + b2)
          2. Line(x,y) = (ax + by + c) / line seg length
          3. Distance from a mouse point to a line is given by the equation:
             
                              dist(M,a,b,c) = (a*M.x + b*M.y + c) / line seg length
            		  

        3. Nearest point calculation

          1. The normalized line yields the distance of the point from the line

          2. This distance measures the perpendicular distance of the point from the line

          3. The implication of points (i) and (ii) is that we can follow the line's normalized perpendicular vector to find the nearest point:
            		    Nearest point = (x,y) - Line(x,y) * [a,b] / size(a,b)
            		 
            or
            		    Nx = x - a * Line(x,y) / size(a,b)
            		    Ny = y - b * Line(x,y) / size(a,b)
            		 
          4. The disadvantage of this calculation is that a line is infinite but your line segment is finite. It may well be that (Nx, Ny) does not fall on your line segment because it falls outside the endpoints, A and B.

      2. Parametric Equations: L = A + t(B - A)
                    x = A.x + t(B.x-A.x)
                    y = A.y + t(B.y-A.y)
        	    
        1. These equations are often used when animating the motion of an object between two points. t represents the proportion of time that has passed thus far in the animation.

        2. Figure 12.22 in the book shows how to compute the nearest point L, on a parametric line, to point M. The advantage of this equation is that it solves for t and hence you know whether or not L falls on the line segment (it does if t is in the range [0,1]). The rationale for the calculation is that it minimizes the distance of the distance calculation dist2(L,M) by taking the derivative of the equation with respect to t and setting the derivative to 0. Remember that when the derivative is 0 you have either a local min or local max. In this case the distance has an unbounded max so you know that when the derivative is 0, you have a min. Solving the equation for t and plugging t back into your parametric equation for the line gives you the nearest point.

      3. Convex Hull Property: The convex hull of a set of points is the smallest polygon that will contain all of the points

        1. Convex Hull Property of a Geometric Object: All points on the object are guaranteed to lie in the convex hull of that object's control points

        2. If an object satisfies the convex hull property then its bounding box can be obtained from the control points

        3. A line fulfills the convex hull property

    2. Circles

      1. A circle can be defined in two ways

        1. By a center point and a radius
        2. By a center point and a point on the circle

          Given a center point and a point on the circle, the radius can be derived as:

          	    radius = sqrt((xp - xc)2 + (yp - yc)2)
          	    
      2. Implicit equation: (x - xc)2 + (y - yc)2 - R2 = 0

      3. Parametric Equations
                   x = xc + R * cos 2πt
        	   y = yc + R * sin 2πt
        	   
        where t is in the range [0,1)

      4. Distance from a Point to a Circle
        	   dist(x,y) = sqrt((x - xc)2 + (y - yc)2) - R
        	   
      5. Containment of a Point in the Circle: If F(x,y) represents the implicit equation for the circle, then:

        • F(x,y) > 0: point is outside the circle
        • F(x,y) < 0: point is inside the circle
        • F(x,y) = 0: point is on the boundary of the circle

        1. If containment is the only property we care about, then use the implicit equation rather than finding the distance and determining if the distance is positive or negative. Computing the distance requires a square root to be computed and that is an expensive operation

      6. Nearest Point on a Circle

        1. The nearest point on the circle is on the line that goes from the center of the circle to (x,y).

        2. If we think of this line as a vector, then we can

          1. normalize its length to 1,
          2. multiply the resulting vector by R, and
          3. add the circle's center point to the resulting vector to obtain the nearest point
            [x - xc, y - yc] is the vector
            		  
            Let len = sqrt((x - xc)2 + (y - yc)2)

            Then:

            • the normalized vector is [(x - xc) / len, (y - yc) / len]

            • the nearest point on the circle is
              xn = xc + R * (x - xc) / len
              yn = yc + R * (y - yc) / len
              		  

    3. Ellipses

      1. Think of an ellipse as a stretched unit circle, with the x dimension stretched for a distance of a and the y dimension stretched for a distance of b. a equals half the actual width of the ellipse and b equals half the acutal height of the ellipse

      2. Control points: upper left and lower right corners of the ellipse
        1. a upper left corner and width/height model is also often used in graphics packages

      3. Implicit Equation: The implicit equation for an ellipse can be derived from the implicit equation for a circle. First normalize the circle's equation by dividing by R, then replace R by a and b, the new radii for the ellipse
        	        (x - xc)2   (y - yc)2
        		--------- + --------- - 1 = 0
        		   a2          b2
        		
      4. Parametric Equations
        	        x = xc + a * cos(2πt)
        	        y = yc + b * sin(2πt)
        	      
      5. Nearest point: Ignore the book. There is an easy way to find the nearest point based on similar triangles. Let M be your mouse point and C be the center of your ellipse. You know that the nearest point is on the line defined by the vector M-C. Let:
                            dy = M.y - C.y
        		    dx = M.x - C.x
        	      
        The point that lies on the ellipse satisfies the equation (a*cos(2πt), b*sin(2πt)). Using similar triangles, we know that:
        		    dy / dx = (b*sin(2πt)) / (a*cos(2πt))
        		=>  (a / b) * (dy / dx) = sin(2πt) / cos(2πt)
        		=>  (a / b) * (dy / dx) = tan(2πt)
               		=>  tan-1[(a / b) * (dy / dx)] = 2πt
               		=>  atan2(a * dy, b * dx) = 2πt
        		 
        You can now plug the atan2 expression into the parametric equations to get the (x,y) point corresponding to the nearest point on the ellipse. Note that atan2 is a function used in many programming languages that takes two arguments, so that it knows the signs of the numerator and denominator and hence can place the angle in the proper quadrant. With just one argument, there are two possible solutions.

      6. Distance calculation: Calculate the nearest point L, then calculate the length of the line segment M-L.

      7. Containment of a Point in the Ellipse: If F(x,y) represents the implicit equation for the ellipse, then:

        • F(x,y) > 0: point is outside the ellipse
        • F(x,y) < 0: point is inside the ellipse
        • F(x,y) = 0: point is on the boundary of the ellipse

        1. If containment is the only property we care about, then use the implicit equation rather than finding the distance and determining if the distance is positive or negative. Computing the distance requires a square root to be computed and that is an expensive operation

    4. Arcs: It's easiest to use a parametric form for arcs since they comprise a subpart of a circle or ellipse. For simplicity we will only consider circular arcs. You can use the same mathematical treatment shown below to derive similar equations for elliptical arcs

      1. Parametric Equations

        Let:

        • sp = the start point (a real number between 0 and 1)
        • fp = the stop point

        Then:

        • x = xc + R * cos[2*pi*(sp + t * (fp - sp))]
        • y = yc + R * sin[2*pi*(sp + t * (fp - sp))]

      2. Distance of a point from an arc/Nearest point: typically you care about the nearest point only when the distance from the point to the arc is small. You can use the distance and nearest point computations for a circle with the caveat that your point must be close to the arc for the calculation to make sense. If the point is far away from the arc, then the distance calculation will yield the wrong result because the distance will be to a point on the opposite side of a circle.

        Here is one set of calculations for selecting the nearest point on an arc:

        1. Use the nearest point circle equation

        2. Determine if the computed nearest point actually lies on the arc by solving for the angle that the mouse point makes with the center of the circle and calculating t as:
                             t = angle / (2*pi)
          		   angle = cos-1[(M.x - C.x / |M-C|] or
                                     sin-1[(M.y - C.y / |M-C|] or
                                     tan-1[(M.y - C.y) / (M.x - C.x)]
                             
          where M.x is the x-coordinate of the mouse point and C.x is the x-coordinate of the center point. if t lies between sp and fp then we have the nearest point.

        This last equation can be modified for our distance calculation.

        1. Calculate the distance using the circle distance formula. If the distance lies within the prescribed threshold, then

        2. Determine if the point lies within the proper t coordinates by calculating:
          		   t = cos-1[(x - xc) / len] / (2*pi)
          		   
          where len = sqrt((x - xc)2 + (y - yc)2)

          Note that:

          1. a nearest point calculation is not required--we can use x rather than xn

          2. you already have computed len when you did the distance calculation so it does not introduce an additional calculation.

      3. Bounds of an Arc

        1. An arc does not satisfy the convex hull property

        2. Calculating the bounding box

          1. Calculate the bounding box from the set t = {sp, fp, 0.0, 0.25, 0.5, and 0.75}.

          2. Use the parametric equations for a circle, not the arc (i.e., use cos(2πt) not cos(2π(sp + t * (fp - sp)))).
          3. Eliminate any point that does not lie between sp and fp. The values 0.0, 0.25, 0.5, and 0.75 will test the 0, 90, 180, and 270 degree values of the circle, which are its 4 extrema.

      4. Containment of a point in an arc

        1. Check for containment using the circle test

        2. Check for angle containment by calculating the angle, converting it to a number between 0 and 1, and comparing it with the bounds for t:
                                          x - xc
          	       cos-1[----------------------------]
                               sqrt((x - xc)2 + (y - yc)2)
                     t = ------------------------------------
                                         2*pi
          		    

    5. Curves: Curves are normally constructed in graphical interfaces using piecewise cubic curves. The reason for using cubic curves is that curves with more points have polynomial equations that become too complicated.

      1. Control points: Cubic curves are defined using four control points

      2. Continuity requirements: When piecing together cubic curves, you normally want the curves to flow smoothly at the meeting points.

        1. C(0) continuity: two adjacent curves share the same point where they join.

        2. C(1) continuity: the first derivatives are identical at the join point. This property ensures that there is a smooth transition between curves with no sharp points, because the tangent vectors of each curve are aligned at the join point. This property is the most common requirement for piecing together smooth curves

        3. C(2) continuity: the second derivatives are identical at the join point. Recall that in physics, the first derivative represents acceleration and the second derivative represents the change in velocity of the first derivative. hence when the second derivatives are equal, the two curves are accelerating at the same rate across the join point. This makes the joined surface look especially smooth. Wikipedia describes the joined surfaces as looking "perfectly smooth" and as causing the two joined surfaces to "appear as one".

        Note that both C(1) and C(2) continuity allow the joined surface to continue either in the same direction, or to reverse direction. You might initially think that C(2) continuity precludes the joined surface from reversing direction, but that is not true (e.g., try joining x3 and -x3 at the origin with x3 going from (-∞,0] and -x3 going from [0,∞)).

      3. Bezier curves

        1. defined by two endpoints and two intermediate control points.

        2. The curves can be made more pronounced by pulling on the two intermediate control points

        3. C(0) continuity is obtained by making the P1 point of the second curve be the P4 point of the first curve

        4. C(1) continuity is achieved by making P3-P4 of the first curve collinear with P1-P2 of the second curve (i.e., P3-(P4/P1)-P2 lie on the same line). Most interactive packages will automatically maintain this continuity

        5. C(2) continuity is foregone

        6. Bezier curves obey the convex hull property

        7. Advantages of Bezier curves

          1. An advantage of Bezier curves is that the curves always go through the two endpoints so it is easy to join two curves in precise places on the screen.

          2. The Bezier representation has a very efficient algorithm for scan-converting cubic curves that avoids repeated evaluation of the cubic polynomial and thus increases drawing speed.

          3. You can obtain a bounding box for a Bezier curve from its control points because it obeys the convex hull property.

          4. Graphical editors make it easy to manipulate Bezier curves by automatically keeping the control points on two adjacent curves co-linear when interior control points (P2/P3) are manipulated.

      4. B-splines

        1. Each curve shares three points with the preceding and succeeding curve

        2. C(0), C(1), and C(2) continuity are all achieved

        3. The curve may not go through any of the control points, which makes controlling B-splines more difficult because it can make it difficult to join two splines at a precise point on the screen and also harder to control where the B-spline goes.

        4. B-splines obey the convex hull property

        5. Advantages of B-splines

          1. They have C(2) continuity, so they can produce extremely smooth curves at the join points

          2. You can obtain a bounding box for a B-spline from its control points because it obeys the convex hull property.

      5. Catmull-Rom curves

        1. Guarantees that the curve goes through all the control points. However, a segment is usually thought of as being defined by two control points and two additional control points on either side of the endpoints. Thus the first and last segments may have an additional control point to their left and right respectively. In this case the curve would pass through all but the first and last control points.

        2. Guarantees C(0) and C(1) continuity, but not C(2) continuity

        3. Like B-splines in that each curve shares three points with the preceding and succeeding curve

        4. Catmull-Rom curves do not satisfy the convex hull property. However, Catmull-Rom geometry can be converted into Bezier geometry using calculations shown in the book and from the converted geometry a bounding box can be calculated

        5. Advantage of Catmull-Rom curves: They pass through every control point, thus making them easy to control interactively.

    6. Polygons

      1. Nearest point/nearest distance: Compare point with each of the line segments and use equations for a line

      2. Bounding box: Is the maximum and minimum of the vertex points in X/Y

      3. Containment of a point:

        1. First check the bounding box. If it's in the bounding box, then do the odd-even test

        2. Odd-Even test: Draw a horizontal line through the point and count the number of intersections of the line with the shape whose x-coordinate is less than the mouse-point (i.e., to the left of the point). If the number is odd then the point is inside the shape, otherwise it is outside the shape. Intuitively, if you start from outside the polygon, each time you cross a boundary you transition from outside to inside, inside to outside, and so on.

        3. Refinements to the odd-even test

          1. If the line intersects the shape at an edge intersection, then count the intersection twice if the edges are tangential to the line and once if the line passes through the edges

          2. to compute tangency, traverse the edges counterclockwise and compute the dY of the point. If the sign changes you have tangency; otherwise the line goes through the edges