Download presentation
Presentation is loading. Please wait.
1
Computer Graphics Implementation
2
Line Drawing Algorithms
DDA algorithm Midpoint algorithm Bresenham’s line algorithm
3
Line Drawing 3
4
Scan Converting Lines Line Drawing
Draw a line on a raster screen between two points What’s wrong with statement of problem? doesn’t say anything about which points are allowed as endpoints doesn’t give a clear meaning of “draw” doesn’t say what constitutes a “line” in raster world doesn’t say how to measure success of proposed algorithms Problem Statement Given two points P and Q in XY plane, both with integer coordinates, determine which pixels on raster screen should be on in order to make picture of a unit-width line segment starting at P and ending at Q 4
5
Finding next pixel: Special case: Horizontal Line:
Draw pixel P and increment x coordinate value by 1 to get next pixel. Vertical Line: Draw pixel P and increment y coordinate value by 1 to get next pixel. Diagonal Line: Draw pixel P and increment both x and y coordinate by 1 to get next pixel. What should we do in general case? => Fast - Digital differential analyzer (DDA) algorithm - Mid-point algorithm - Bresenham algorithm There might include handruds of thousands lins in a graphics, so drawing algorithm should be as fast as possible. 5
6
Scan Conversion of Line Segments
Start with line segment in window coordinates with integer values for endpoints Assume implementation has a write_pixel function y = mx + h
7
Find equation of line that connects two points P(x1,y1) and Q(x2,y2)
Basic Algorithm Find equation of line that connects two points P(x1,y1) and Q(x2,y2) Starting with leftmost point P, increment xi by 1 to calculate yi = m*xi + h where m = slope, h = y intercept Draw pixel at (xi, Round(yi)) where Round (yi) = Floor (0.5 + yi) 7
8
Strategy 1 – DDA Algorithm
Digital Differential Analyzer DDA was a mechanical device for numerical solution of differential equations Line y=mx+ h satisfies differential equation dy/dx = m = Dy/Dx = (y2-y1)/(x2-x1) Along scan line Dx = 1 for(x=x1; x<=x2;x++) { y+=m; write_pixel(x, round(y), line_color); }
9
Example Code // Incremental Line Algorithm // Assume x0 < x1
void Line(int x0, int y0, int x1, int y1) { int x, y; float dy = y1 – y0; float dx = x1 – x0; float m = dy / dx; y = y0; for (x = x0; x < x1; x++) { WritePixel(x, Round(y)); y = y + m; } 9
10
10
11
DDA = for each x plot pixel at closest y
Problem DDA = for each x plot pixel at closest y Problems for steep lines
12
For m > 1, swap role of x and y
Using Symmetry Use for 1 m 0 For m > 1, swap role of x and y For each y, plot closest x
13
Problem void Line(int x0, int y0, int x1, int y1) { int x, y;
float dy = y1 – y0; float dx = x1 – x0; float m = dy / dx; y = y0; for (x = x0; x < x1; x++) { WritePixel(x, Round(y)); y = y + m; } Rounding takes time 13
14
Strategy 2 – Midpoint Line
Algorithm (1/3) Assume that line’s slope is shallow and positive (0 < slope < 1); other slopes can be handled by suitable reflections about principle axes Call lower left endpoint (x0, y0) and upper right endpoint (x1, y1) Assume that we have just selected pixel P at (xp, yp) Next, we must choose between pixel to right (E pixel) (xp+1, yp), or one right and one up (NE pixel) (xp+1, yp+1) Let Q be intersection point of line being scan-converted and vertical line x=xp+1 14
15
Strategy 2 – Midpoint Line Algorithm (2/3)
NE pixel Q Midpoint M E pixel Previous pixel Choices for current pixel Choices for next pixel 15
16
Strategy 2 – Midpoint Line
Algorithm (3/3) Line passes between E and NE Point that is closer to intersection point Q must be chosen Observe on which side of line midpoint M lies: E is closer to line if midpoint M lies above line, i.e., line crosses bottom half NE is closer to line if midpoint M lies below line, i.e., line crosses top half Error (vertical distance between chosen pixel and actual line) is always <= ½ E pixel NE pixel M Q Algorithm chooses NE as next pixel for line shown Now, need to find a way to calculate on which side of line midpoint lies 16
17
Line Line equation as function f(x):
Line equation as implicit function: for coefficients a, b, c, where a, b ≠ 0 from above, Properties (proof by case analysis): f(xm, ym) = 0 when any point M is on line f(xm, ym) < 0 when any point M is above line f(xm, ym) > 0 when any point M is below line Our decision will be based on value of function at midpoint M at (xp + 1, yp + ½) 17
18
void MidpointLine(int x0, int y0, int x1, int y1) {
int dx = x1 - x0; int dy = y1 - y0; int x = x0; int y = y0; float c = y0 * dx – dy * x0; writePixel(x, y); x++; while (x < x1) { d = dy * x – (y + 0.5) * dx + c; if (d > 0) { // Northeast Case y++; } } /* while */
19
Decision Variable Decision Variable d:
We only need sign of f(xp + 1, yp + ½) to see where line lies, and then pick nearest pixel d = f(xp + 1, yp + ½) - if d > 0 choose pixel NE - if d < 0 choose pixel E - if d = 0 choose either one consistently How do we incrementally update d? On basis of picking E or NE, figure out location of M for that pixel, and corresponding value d for next grid line We can derive d for the next pixel based on our current decision 19
20
Strategy 3 – Bresenham algorithm
If E was chosen: Increment M by one in x direction dnew = f(xp + 2, yp + ½) = a(xp + 2) + b(yp + ½) + c dold = a(xp + 1) + b(yp + ½) + c dnew - dold is the incremental difference E dnew = dold + a E = a = dy We can compute value of decision variable at next step incrementally without computing F(M) directly dnew = dold + E = dold + dy E can be thought of as correction or update factor to take dold to dnew It is referred to as forward difference 20
21
If NE was chosen: dnew = F(xp + 2, yp + 3/2)
Increment M by one in both x and y directions dnew = F(xp + 2, yp + 3/2) = a(xp + 2) + b(yp + 3/2) + c NE = dnew – dold dnew = dold + a + b NE = a + b = dy – dx Thus, incrementally, dnew = dold + NE = dold + dy – dx 21
22
Summary (1/2) At each step, algorithm chooses between 2 pixels based on sign of decision variable calculated in previous iteration. It then updates decision variable by adding either E or NE to old value depending on choice of pixel. Simple additions only! First pixel is first endpoint (x0, y0), so we can directly calculate initial value of d for choosing between E and NE. 22
23
Summary (2/2) use dstart to choose second pixel, etc.
First midpoint for first d = dstart is at (x0 + 1, y0 + ½) f(x0 + 1, y0 + ½) = a(x0 + 1) + b(y0 + ½) + c = a * x0 + b * y0 + c + a + b/2 = f(x0, y0) + a + b/2 But (x0, y0) is point on line and f(x0, y0) = 0 Therefore, dstart = a + b/2 = dy – dx/2 use dstart to choose second pixel, etc. To eliminate fraction in dstart : redefine f by multiplying it by 2; f(x,y) = 2(ax + by + c) this multiplies each constant and decision variable by 2, but does not change sign 23
24
Example Code 24 void Bresenham(int x0, int y0, int x1, int y1) {
int dx = x1 - x0; int dy = y1 - y0; int d = 2 * dy - dx; int incrE = 2 * dy; int incrNE = 2 * (dy - dx); int x = x0; int y = y0; writePixel(x, y); while (x < x1) { if (d <= 0) { // East Case d = d + incrE; } else { // Northeast Case d = d + incrNE; y++; } x++; } /* while */ } /* MidpointLine */ 24
25
Circle Generating Algorithms
Bresenham’s circle algorithm Extension to Ellipse drawing
26
Bresenham’s Circle Algorithm
Circle Equation (x-xc)2 + (y- yc)2 = R2 Problem simplifying Making the circle origin (xc, yc) in the coordinate origin Symmetry points (y,x), (y,-x),(x,-y),(-x,-y),(-y,-x),(-y,x),(-x,y)
27
Scan Converting Circles
Version 1: really bad For x = – R to R y = sqrt(R * R – x * x); Pixel (round(x), round(y)); Pixel (round(x), round(-y)); Version 2: slightly less bad For x = 0 to 360 Pixel (round (R • cos(x)), round(R • sin(x))); (17, 0) (0, 17) (17, 0) (0, 17)
28
Suppose circle origin is (xc,yc), radius is R.
Let D(x, y) = (x-xc)2+(y-yc)2–R2 If point(x,y) is outside the circle, D(x,y)>0。 If point(x,y) is inside the circle, D(x,y)<0。 (xc, yc)
29
Bresenham’s Circle Algorithm
(xi+1, yi) (xi+1, yi-1) (xi, yi) (xi, yi-1) (xi, yi) (xi+1, yi) (xi+1, yi-1) (xi, yi-1) 由前一个点判断下一步怎么走。 如果只画那八分之一圆的话,只有两个选择(xi+1, yi) or (xi+1, yi-1) ,那么为什么下一个点不可能是 (xi, yi-1) ? 由此可见画此八分之一圆的过程与画直线的过程有些类似,也是x每次都加1,而y或者不变,或者变化1。 Two choice: (xi+1, yi) or (xi+1, yi-1)
30
Use Symmetry R (x0 + a, y0 + b) (x0, y0) (x-x0)2 + (y-y0)2 = R2
Symmetry: If (x0 + a, y0 + b) is on circle also (x0 ± a, y0 ± b) and (x0 ± b, y0 ± a); hence 8-way symmetry. Reduce the problem to finding the pixels for 1/8 of the circle
31
Using the Symmetry Scan top right 1/8 of circle of radius R
Circle starts at (x0, y0 + R) Let’s use another incremental algorithm with decision variable evaluated at midpoint (x0, y0)
32
Sketch of Incremental Algorithm
SE x = x0; y = y0 + R; Pixel(x, y); for (x = x0+1; (x – x0) < (y – y0); x++) { if (decision_var < 0) { /* move east */ update decision_var; } else { /* move south east */ y--; Pixel(x, y);
33
What we need for Incremental Algorithm
Decision variable negative if we move E, positive if we move SE (or vice versa). Follow line strategy: Use implicit equation of circle f(x,y) = x2 + y2 – R2 = 0 f(x,y) is zero on circle, negative inside, positive outside If we are at pixel (x, y) examine (x + 1, y) and (x + 1, y – 1) Compute f at the midpoint
34
Decision Variable ÷ ø ö ç è æ - + 2 1 , y x 1 ) ( , R y x f - ÷ ø ö ç
P = (xp, yp) M ME SE MSE Evaluate f(x,y) = x2 + y2 – R2 at the point We are asking: “Is positive or negative?” (it is zero on circle) If negative, midpoint inside circle, choose E vertical distance to the circle is less at (x + 1, y) than at (x + 1, y–1). If positive, opposite is true, choose SE ÷ ø ö ç è æ - + 2 1 , y x 2 1 ) ( , R y x f - ÷ ø ö ç è æ + =
35
The right decision variable?
Decision based on vertical distance Ok for lines, since d and dvert are proportional For circles, not true: Which d is closer to zero? (i.e. which of the two values below is closer to R): R y x Circ d - + = 2 ) 1 ( ), , (( 2 ) 1 ( - + y x or
36
Alternate Phrasing (1/3)
We could ask instead: “Is (x + 1)2 + y2 or (x + 1)2 + (y – 1)2 closer to R2?” The two values in equation above differ by 1 2 ] ) ( [( - = + y x fE – fSE = 290 – 257 = 33 (0, 17) (1, 17) (1, 16) fE = = 290 E SE fSE = = 257 2y – 1 = 2(17) – 1 = 33
37
Alternate Phrasing (2/3)
The second value, which is always less, is closer if its difference from R2 is less than i.e., if then so ) 1 2 ( - ÷ ø ö ç è æ y < 2 ) 1 ( - y ] [( + x R ) 1 ( 2 R y x - + < 2 1 ) ( R y x - + < 2 1 ) ( R y x - + < 2 4 1 ) ( R y x - + ÷ ø ö ç è æ <
38
Alternate Phrasing (3/3)
The radial distance decision is whether is positive or negative And the vertical distance decision is whether is positive or negative; d1 and d2 are apart. The integer d1 is positive only if d is positive (except special case where d2 = 0). 2 4 1 ) ( R y x d - + ÷ ø ö ç è æ = 2 1 ) ( R y x d - ÷ ø ö ç è æ + =
39
Incremental Computation, Again
(1/2) How to compute the value of at successive points? Answer: Note that is just and that 2 1 ) ( , R y x f - ÷ ø ö ç è æ + = 2 3 ) , ( 1 SE E + - = D y x f
40
Incremental Computation (2/2)
If we move E, update by adding 2x + 3 If we move SE, update by adding 2x + 3 – 2y + 2. Forward differences of a 1st degree polynomial are constants and those of a 2nd degree polynomial are 1st degree polynomials this “first order forward difference,” like a partial derivative, is one degree lower F F’ F’’
41
Second Differences (1/2)
The function is linear, hence amenable to incremental computation, viz: Similarly 3 2 ) , ( E + = D x y 2 ) , ( 1 E = D - + y x 2 ) , ( 1 E = D - + y x 2 ) , ( 1 SE = D - + y x 4 ) , ( 1 SE = D - + y x
42
Second Differences (2/2)
For any step, can compute new ΔE(x, y) from old ΔE(x, y) by adding appropriate second constant increment – update delta terms as we move. This is also true of ΔSE(x, y) Having drawn pixel (a,b), decide location of new pixel at (a + 1, b) or (a + 1, b – 1), using previously computed d(a, b). Having drawn new pixel, must update d(a, b) for next iteration; need to find either d(a + 1, b) or d(a + 1, b – 1) depending on pixel choice Must add ΔE(a, b) or ΔSE(a, b) to d(a, b) So we… Look at d(i) to decide which to draw next, update x and y Update d using ΔE(a,b) or ΔSE(a,b) Update each of ΔE(a,b) and ΔSE(a,b) for future use Draw pixel
43
Bresenham’s Eighth Circle Algorithm
void MEC (int R) /* 1/8th of a circle w/ radius R */ { int x = 0, y = R; int delta_E, delta_SE; float decision; delta_E = 2*x + 3; delta_SE = 2*(x-y) + 5; decision = (x+1)*(x+1) + (y - 0.5)*(y - 0.5) –R*R; Pixel(x, y); while( y > x ) { if (decision < 0) {/* Move east */ decision += delta_E; delta_E += 2; delta_SE += 2; /*Update delta*/ } else {/* Move SE */ y--; decision += delta_SE; delta_E += 2; delta_SE += 4; /*Update delta*/} x++;
44
Analysis Uses floats! 1 test, 3 or 4 additions per pixel
Initialization can be improved Multiply everything by No Floats! Makes the components even, but sign of decision variable remains same Questions Are we getting all pixels whose distance from the circle is less than ½? Why is y > x the right stopping criterion? What if it were an ellipse?
45
Aligned Ellipses b a y x = + 1 = + b y a x D D Equation is i.e,
Computation of and is similar Only 4-fold symmetry When do we stop stepping horizontally and switch to vertical? 1 2 = + b y a x 2 b a y x = + E D SE D
46
Direction Changing Criterion (1/2)
When absolute value of slope of ellipse is more than 1, viz: How do you check this? At a point (x,y) for which f(x,y) = 0, a vector perpendicular to the level set is f(x,y) which is This vector points more right than up when Ñ ú û ù ê ë é ) , ( ), y x f ) , ( > - y x f
47
Direction Changing Criterion (2/2)
In our case, and so we check for i.e. This, too, can be computed incrementally x a y f 2 ) , ( = y b x f 2 ) , ( = 2 > - y b x a 2 > - y b x a
48
Other Scan Conversion Problems
Patterned primitives Non-integer primitives General conics
49
Patterned Lines Patterned line from P to Q is not same as patterned line from Q to P. Patterns can be geometric or cosmetic Cosmetic: Texture applied after transformations Geometric: Pattern subject to transformations Cosmetic patterned line Geometric patterned line Q P Q P
50
+ Geometric Pattern vs. Cosmetic Pattern
Geometric (Perspectivized/Filtered) Cosmetic
51
Polygon Filling Scan-line Conversion Area Filling
52
Vertex-edge representation Pixel set representation
Polygon Filling Vertex-edge representation Pixel set representation P0 P1 P2 P3 P4 P5 P6 P7
53
Scan-line Conversion P0 P1 P2 P3 P4 P5 P6 P7 Check pixel by pixel
54
How to judge a point inside or outside a polygon?
Shoot a radial from the point to intersect with the polygon edges; if there are odd number of intersection points, the point is inside the polygon; if even number, outside. Odd point: the intersection point is polygon’s vertex (special case).
55
Scan-line Conversion P0 P1 P2 P3 P4 P5 P6 P7 Improved (limit the pixel sets into the bounding box of the polygon for speeding up)
56
Scan-line polygon-fill algorithm
Scan-line Conversion Scan-line polygon-fill algorithm Taking full advantage of the coherence properties of pixels Three coherence properties Area coherence Scan-line coherence Edge coherence
57
Area Coherence The screen region between two scan-lines is partitioned into some trapezoids by the polygon. (1) Two types of trapezoid: the one inside the polygon and the one outside polygon. (2) The two types of trapezoids are arranged alternately.
58
Scan-line Coherence Suppose the intersection points of scan-line y=e and polygon edge ei (Pi-1Pi) is xei. Suppose the intersection points sequence arranged by the x-increase is xei1, xei2, xei3 … xein. According to area coherence, we can get: n is even number On the scan-line, only the segments (xeik, xeik+1), k=1,3,5,…n–1) are inside the polygon. Scan-line coherence is the reflection of area coherence on a scan-line.
59
Edge coherence is the reflection of area coherence on edges.
Suppose the intersection point sequence on y=e is xei1, xei2, …xein; point sequence on y=e-1 is xdi1, xdi2, … xdin. If edge er(Pr-1Pr) intersects with both y=e and y=e-1; the corresponding points xer and xdr have following relationship: xer = xdr + 1/mr Thus, we can calculate the intersection points on y=e from the points on y=e-1 Edge coherence is the reflection of area coherence on edges. Mr is the slope of edge er.
60
Polygon Filling Scan-line Conversion Area Filling
61
Area Filling Area Filling: To start from a given interior position (seed) and paint outward from this point until we encounter the specified boundary conditions. The “area” should be identified with its interior color or boundary color. Colorate all the interior pixels to a specified color Colorate all the boundary pixels to the boundary color We can display an unfilled polygon by rasterizing its edges into the frame buffer using Bresenham’s algorithm. Suppose that we have only two colors: a background color and a foreground, or drawing, color. We can use the foreground color to rasterize the edges. If we can find an initial point (x,y) inside the polygon-a seed point- then we can look at its neighbors recursively, coloring them with the foreground color if they are not edge points.
62
种子填充 4-connected Neighbourhood 8-connected Neighbourhood
Two kinds of connectivity 4-connected Neighbourhood 8-connected Neighbourhood When filling, it is done with one seed and extended to its neighbors. So there is problem about connectivity.
63
4-connected area and 8-connected area
4-connected area: Giving any two interior points A and B, we can travel from A to B by the 4-directions moving: right, left, up and down moving. To filling the 4-connected area, we only need to test its 4-direction neighbors 4-connected area 8-connected area
64
4-connected area and 8-connected area
The boundary of 8-connected area must be 4-connected The boundary of 4-connected area is 8-connected
65
Recursive Method for Filling a 4-connected Area
The area is identified by the boundary color void AreaFill4(int x, int y, int fillCol, int boundaryCol) { int currentCol = getPixel(x,y); if( (currentCol != boundaryCol)&& (currentCol != fillCol)) { setPixel(x, y, fillCol); AreaFill4(x, y+1, fillCol, boundaryCol); AreaFill4(x, y-1, fillCol, boundaryCol); AreaFill4(x-1, y, fillCol, boundaryCol); AreaFill4(x+1, y, fillCol, boundaryCol); }
66
Recursive Method for Filling a 4-connected Area
The area is identified by the interior color. Called flood-fill algorithm void FloodFill4(int x, int y, int fillCol, int interiorCol) { int currentCol = getPixel(x,y); if( currentCol == interiorCol ) { setPixel(x, y, fillCol); FloodFill4(x, y+1, fillCol, interiorCol); FloodFill4(x, y-1, fillCol, interiorCol); FloodFill4(x-1, y, fillCol, interiorCol); FloodFill4(x+1, y, fillCol, interiorCol); }
67
Recursive Method for Filling a 4-connected Area
J C B K P Its filling order is up, down, left and then right.
68
Recursive Method for Filling a 4-connected Area
Left pixel to 3 is the last one to be filled.
69
How to expand the algorithm for 4 –connected area to the algorithm for 8-connect area?
70
void AreaFill8(int x, int y, int fillCol, int boundaryCol) {
int currentCol = getPixel(x,y); if((currentCol != boundaryCol) && (currentCol != fillCol)) { setPixel(x, y, fillCol); AreaFill8(x, y+1, fillCol, boundaryCol); AreaFill8(x, y-1, fillCol, boundaryCol); AreaFill8(x-1, y, fillCol, boundaryCol); AreaFill8(x+1, y, fillCol, boundaryCol); AreaFill8(x+1, y+1, fillCol, boundaryCol); AreaFill8(x+1, y-1, fillCol, boundaryCol); AreaFill8(x-1, y+1, fillCol, boundaryCol); AreaFill8(x-1, y-1, fillCol, boundaryCol); } The recursive algorithm is not very good in time and space consuming. There are some other improved methods for Area Filling, such as the scan-line algorithm.
71
Comparison Between Scan-line Conversion (A) and Area Filling (B)
Basic idea: A changes the edge list representation into lattice representation. It uses the coherences of polygons. B does not change the representation of the area, but the color. It uses the connectivity of area. The requirements: For area filling, a seed point inside the area is needed. Boundary: For A, the number of the intersection points of each scan line with edges should be even. For B, the boundary of 4-connected area is closed 8-connected area and the boundary of 8-connected area is closed 4-connected area.
72
Aliasing Problems of Raster Graphics Antialiasing Methods
73
Aliasing Problems of Raster Graphics
What’s aliasing? The distortion of information due to low-frequency sampling ( undersampling ) is called aliasing
74
Aliasing Problems of Raster Graphics --- Jagged Boundaries
8 7 6 5 4 3 2 1 9 x y Rasterized line segments and edges of polygons often look jagged
75
Aliasing Problems of Raster Graphics --- Shape Distortion
Slim Primitives are lost
76
Aliasing Problems of Raster Graphics --- Sparking
The slim primitive sparks when it is moved
77
Aliasing Problems of Raster Graphics Antialiasing Methods
78
Adopting area-sampling instead of point-sampling
Antialiasing Methods Adopting area-sampling instead of point-sampling Supersampling
79
Using transitional color scales on the edges
Area-sampling Using transitional color scales on the edges
80
Using Transitional Color Scales on the Edges
For example, it paritally covers many pixel-sized boxes. It is our scan-conversion algorithm that forces us, for lines of slope less than 1, to choose exactly one pixel value for each value of x. if instead, we shade each box by the color scale with percentage of the ideal line that crosses it, we get the smoother-appearing image.
81
Exact area-sampling is time-consuming
Some approximate algorithms are always used Wu’s algorithm for drawing antialiasing lines Pitteway and Watkinson’s algorithm for drawing antialiasing polygons
82
Supersampling for Antialiasing
Hardware method: adopting high resolution raster display Software method: sampling objects at a high resolution and displaying the results at a lower resolution High resolution sampling: partition each pixel as several sub-pixels, such as the 3*3 partition. Then compute color for all the sub-pixels Low resolution display: compute the pixel’s color by adding up all its sub-pixels’ color with a weighting mask
83
Supersampling for Antialiasing
B H F D I G C A 4 2 1 Weight mask for the 3*3 partition 3*3 partition Pixel color = (ColA + 2*ColB + ColC + 2*ColD + 4*ColE + 2*ColF + ColG + 2*ColH + ColI ) / 16
84
Supersampling for Antialiasing
3 2 6 4 8 9 1 12 16 Weight mask for the 7*7 partition
85
Clipping
86
Clipping 86
87
Line Clipping Clipping endpoints
xmin < x < xmax and ymin < y < ymax point inside Endpoint analysis for lines: if both endpoints in , do “trivial acceptance” if one endpoint inside, one outside, must clip if both endpoints out, don’t know Brute force clip: solve simultaneous equations using y = mx + b for line and four clip edges slope-intercept formula handles infinite lines only doesn’t handle vertical lines (Xmin , Ymin) (Xmax , Ymax) 87
88
Parametric Line Formulation For Clipping
Parametric form for line segment X = x0 + t(x1 – x0) < t < 1 Y = y0 + t(y1 – y0) P(t) = P0 + t(P1 – P0) “true,” i.e., interior intersection, if sedge and tline in [0,1] 88
89
Outcodes for Cohen-Sutherland Line Clipping in 2D
Divide plane into 9 regions Compute the sign bit of 4 comparisons between a vertex and an edge ymax – y; y – ymin; xmax – x; x – xmin (>0 “0”; otherwise “1”) point lies inside only if all four sign bits are 0, otherwise exceeds edge 4 bit outcode records results of four bounds tests: “1” First bit: outside halfplane of top edge, above top edge Second bit: outside halfplane of bottom edge, below bottom edge Third bit: outside halfplane of right edge, to right of right edge Fourth bit: outside halfplane of left edge, to left of left edge o1=o2 =0, accept; AND(o1, o2) <>0 (in same side), discard. Clip Rectangle 89
90
Outcodes for Cohen-Sutherland Line Clipping in 3D
Very similar to 2D Divide volume into 27 regions (Picture a Rubik’s cube) 6-bit outcode records results of 6 bounds tests First bit: outside back plane, behind back plane Second bit: outside front plane, in front of front plane Third bit: outside top plane, above top plane Fourth bit: outside bottom plane, below bottom plane Fifth bit: outside right plane, to right of right plane Sixth bit: outside left plane, to left of left plane Top plane (above) (below) Bottom plane (above) (below) Front plane (in front) (behind) Back plane (in front) (behind) Left plane (to left of) (to right of) Right plane (to left of) (to right of) 90
91
Cohen-Sutherland Algorithm
If we can neither trivially reject/accept, divide and conquer subdivide line into two segments; then T/A or T/R one or both segments: use a clip edge to cut line use outcodes to choose edge that is crossed Edges where the two outcodes differ at that particular bit are crossed pick an order for checking edges top – bottom – right – left compute the intersection point the clip edge fixes either x or y can substitute into the line equation iterate for the newly shortened line “extra” clips may happen (e.g., E-I at H) Clip rectangle D C B A E F G H I 1010 0100 91
92
Pseudocode for the Cohen- Sutherland Algorithm
y = y0 + slope*(x - x0) and x = x0 + (1/slope)*(y - y0) ComputeOutCode(x0, y0, outcode0) ComputeOutCode(x1, y1, outcode1) repeat check for trivial reject or trivial accept pick the point that is outside the clip rectangle if TOP then x = x0 + (x1 – x0) * (ymax – y0)/(y1 – y0); y = ymax; else if BOTTOM then x = x0 + (x1 – x0) * (ymin – y0)/(y1 – y0); y = ymin; else if RIGHT then y = y0 + (y1 – y0) * (xmax – x0)/(x1 – x0); x = xmax; else if LEFT then y = y0 + (y1 – y0) * (xmin – x0)/(x1 – x0); x = xmin; if (x0, y0 is the outer point) then x0 = x; y0 = y; ComputeOutCode(x0, y0, outcode0) else x1 = x; y1 = y; ComputeOutCode(x1, y1, outcode1) until done 92
93
Cyrus-Beck/Liang-Barsky Parametric Line Clipping-1
Use parametric line formulation P(t) = P0 + (P1 – P0)t Determine where the line intersects the infinite line formed by each edge by solving for t 4 times. Decide which of these intersections actually occur on the rectangle For any point PEi on edge Ei Ni is the normal vector to the edge Ei 93
94
C-B/L-B Param. Line Clipping-2
Now solve for the value of t at the intersection of P0 P1 with the edge Ei: Ni • [P(t) – PEi] = 0 First, substitute for P(t): Ni • [P0 + (P1 – P0)t – PEi] = 0 Next, group terms and distribute dot product: Ni • [P0 – PEi] + Ni • [P1 – P0]t = 0 Let D be the vector from P0 to P1 = (P1 – P0), and solve for t: Note that this gives a valid value of t only if the denominator of the expression is nonzero. For this to be true, it must be the case that: Ni 0 (that is, the normal should not be 0; this could occur only as a mistake) D 0 (that is, P1 P0) Ni • D 0 (edge Ei and line D are not parallel; if they are, no intersection). The algorithm checks these conditions. Denominator should not be 0. 94
95
C-B/L-B Param. Line Clipping-3
Eliminate t’s outside [0,1] on the line (does not to be processed) Which remaining t’s produce interior intersections? Can’t just take the innermost t values! (decide PE and PL) Move from P0 to P1; for a given edge, just before crossing: if Ni • D < Potentially Entering (PE), if Ni • D > Potentially Leaving (PL) Pick inner PE, PL pair: tE for PPE with max t, tL for PPL with min t, and tE > 0, tL < 1. If tL < tE, no intersection (Line 2) 95
96
Pseudocode for Cyrus-Beck/ Liang-Barsky Line Clipping Algorithm
Pre-calculate Ni and select PEi for each edge; for each line segment to be clipped if P1 = P0 then line is degenerate so clip as a point; else begin tE = 0; tL = 1; for each candidate intersection with a clip edge if Ni • D 0 then {Ignore edges parallel to line} calculate t; {of line and clip edge intersection} use sign of Ni • D to categorize as PE or PL; if PE then tE = max(tE,t); if PL then tL = min(tL,t); end if tE > tL then return nil return P(tE) and P(tL) as true clip intersections 96
97
Calculations for Parametric Line Clipping Algorithm
D = P1 – P0 = (x1 – x0, y1 – y0) Leave PEi as an arbitrary point on the clip edge; it’s a free variable and drops out Calculations for Parametric Line Clipping Algorithm (x0-x,y0- ymax) (x, ymax) (0,1) top: y = ymax (x0-x,y0- ymin) (x, ymin) (0,-1) bottom: y = ymin (x0- xmax,y0-y) (xmax,y) (1,0) right: x = xmax (x0- xmin,y0-y) (xmin, y) (-1,0) left: x = xmin P0-PEi PEi Normal Ni Clip Edgei 97
98
Sutherland-Hodgman Polygon Clipping
98
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.