<<

CS 4204

ClippingClipping andand ClassClass ViewingViewing YongYong CaoCao VirginiaVirginia TechTech

References: Interactive Computer Graphics, Fourth Edition, Ed Angle Objectives

IntroduceIntroduceIntroduce basicbasicbasic implementationimplementationimplementation strategiesstrategiesstrategies ClippingClippingClipping Overview

AtAt endend ofof thethe geometricgeometric pipipeline,peline, verticesvertices havehave beenbeen assembledassembled intointo primitivesprimitives MustMust clipclip outout primitivesprimitives thatthat areare outsideoutside thethe viewview frustumfrustum •• Algorithms Algorithms basedbased onon representingrepresenting primitivesprimitives byby listslists ofof verticesvertices MustMust findfind whichwhich pixelspixels cancan bebe affectedaffected byby eacheach primitiveprimitive •• Fragment Fragment generationgeneration •• Rasterization Rasterization oror scanscan conversionconversion Required Tasks

ClippingClippingClipping RasterizationRasterizationRasterization ororor scanscanscan conversionconversionconversion TransformationsTransformationsTransformations SomeSomeSome taskstaskstasks deferreddeferreddeferred untiluntiluntil fragementfragementfragement processingprocessingprocessing •• Hidden Hidden surfacesurface removalremoval •• Antialiasing Antialiasing Clipping

2D2D againstagainst clippingclipping windowwindow 3D3D againstagainst clippingclipping volumevolume EasyEasy forfor lineline segmentssegments polygonspolygons HardHard forfor curvescurves andand texttext •• Convert Convert toto lineslines andand polygonspolygons firstfirst Clipping 2D Line Segments

BruteBruteBrute forceforceforce approach:approach:approach: computecomputecompute intersectionsintersectionsintersections withwithwith allallall sidessidessides ofofof clippingclippingclipping windowwindowwindow •••Inefficie InefficientInefficientnt Cohen-Sutherland Algorithm

•••Idea:Idea:Idea: eliminateeliminateeliminate asasas manymanymany casescasescases asasas possiblepossiblepossible withoutwithoutwithout computingcomputingcomputing intersectionsintersectionsintersections •••StartStartStart withwithwith fourfourfour lineslineslines thatthatthat determinedeterminedetermine thethethe sidessidessides ofofof thethethe clippingclippingclipping windowwindowwindow

y = ymax

x = xmin x = xmax

y = ymin The Cases

CaseCase 1:1: bothboth endpointsendpoints ofof lineline segmentsegment insideinside allall fourfour lineslines •• Draw Draw (accept)(accept) lineline segmentsegment asas isis

y = ymax

x = xmin x = xmax

y = ymin

CaseCase 2:2: bothboth endpointsendpoints outsideoutside allall lineslines andand onon samesame sideside ofof aa lineline •• Discard Discard (reject)(reject) thethe lineline segmentsegment The Cases

CaseCaseCase 3:3:3: OneOneOne endpointendpointendpoint inside,inside,inside, oneoneone outsideoutsideoutside •• Must Must dodo atat leastleast oneone intersectionintersection CaseCaseCase 4:4:4: BothBothBoth outsideoutsideoutside •• May May havehave partpart insideinside •• Must Must dodo atat leastleast oneone intersectionintersection

y = ymax

x = xmin x = xmax Defining Outcodes ForForFor eacheacheach endpoint,endpoint,endpoint, definedefinedefine ananan outcodeoutcodeoutcode

b0 b1 b2b 3

b0 = 1 if y > ymax , 0 otherwise b1 = 1 if y < ymin , 0 otherwise b2 = 1 if x > xmax , 0 otherwise b3 = 1 if x < xmin , 0 otherwise

OutcodesOutcodesOutcodes dividedividedivide spacespacespace intointointo 999 regionsregionsregions ComputationComputationComputation ofofof outcodeoutcodeoutcode requiresrequiresrequires atatat mostmostmost 444 subtractionssubtractionssubtractions Using Outcodes

ConsiderConsiderConsider thethethe 555 casescasescases belowbelowbelow AB:AB:AB: outcode(Aoutcode(Aoutcode(A))) === outcode(Boutcode(Boutcode(B))) === 000 •• Accept Accept lineline segmentsegment Using Outcodes

CD:CD:CD: outcodeoutcodeoutcode (C)(C)(C) === 0,0,0, outcode(Doutcode(Doutcode(D))) ≠≠≠ 000 •• Compute Compute intersectionintersection •• Location Location ofof 11 inin outcode(Doutcode(D)) determinesdetermines whichwhich edgeedge toto intersectintersect withwith •• Note Note ifif therethere werewere aa segmentsegment fromfrom AA toto aa pointpoint inin aa regionregion withwith 22 onesones inin outcodeoutcode,, wewe mightmight havehave toto dodo twotwo intersectionsintersections Using Outcodes

EF:EF:EF: outcode(Eoutcode(Eoutcode(E))) logicallylogicallylogically ANDedANDedANDed withwithwith outcode(Foutcode(Foutcode(F))) (bitwise)(bitwise)(bitwise) ≠≠≠ 000 ••• BothBoth Both outcodesoutcodesoutcodes havehavehave aaa 111 bitbitbit ininin thethethe samesamesame placeplaceplace ••• LineLine Line segmentsegmentsegment isisis outsideoutsideoutside ofofof correspondingcorrespondingcorresponding sidesideside ofofof clippingclippingclipping windowwindowwindow ••• rejectreject reject Using Outcodes

•••GHGHGH andandand IJ:IJ:IJ: samesamesame outcodesoutcodesoutcodes,,, neitherneitherneither zerozerozero butbutbut logicallogicallogical ANDANDAND yieldsyieldsyields zerozerozero •••ShortenShortenShorten linelineline segmentsegmentsegment bybyby intersectingintersectingintersecting withwithwith oneoneone ofofof sidessidessides ofofof windowwindowwindow •••ComputeComputeCompute outcodeoutcodeoutcode ofofof intersectionintersectionintersection (new(new(new endpointendpointendpoint ofofof shortenedshortenedshortened linelineline segment)segment)segment) •••ReexecuteReexecuteReexecute algorithmalgorithmalgorithm Efficiency

InInIn manymanymany applications,applications,applications, thethethe clippingclippingclipping windowwindowwindow isisis smallsmallsmall relativerelativerelative tototo thethethe sizesizesize ofofof thethethe entireentireentire datadatadata basebasebase •• Most Most lineline segmentssegments areare outsideoutside oneone oror moremore sideside ofof thethe windowwindow andand cancan bebe eliminatedeliminated basedbased onon theirtheir outcodesoutcodes InefficiencyInefficiencyInefficiency whenwhenwhen codecodecode hashashas tototo bebebe reexecutedreexecutedreexecuted forforfor linelineline segmentssegmentssegments thatthatthat mustmustmust bebebe shortenedshortenedshortened ininin moremoremore thanthanthan oneoneone stepstepstep Cohen Sutherland in 3D

UseUse 66-bit-bit outcodesoutcodes WhenWhen needed,needed, clipclip lineline segmentsegment againstagainst planesplanes Viewing and Projection

CameraCamera Analogy:Analogy:

1.1. Set Set upup youryour tripodtripod andand pointingpointing thethe cameracamera atat thethe scenescene (viewing(viewing transformation).transformation).

2.2. Arrange Arrange thethe scenescene toto bebe photographedphotographed intointo thethe desireddesired compositioncomposition (modeling(modeling transformation).transformation).

3.3. Choose Choose aa cameracamera lenslens oror adjustadjust thethe zoomzoom (projection(projection transformation).transformation).

4.4. Determine Determine howhow largelarge youyou wantwant thethe finalfinal photographphotograph toto bebe -- forfor example,example, youyou mightmight wantwant itit enlargedenlarged (viewport(viewport transformation).transformation). Projection transformations Introduction to Projection Transformations

Mapping:Mapping: ff :: RRnn ÆÆ RRmm Projection:Projection: nn >> mm PlanarPlanar Projection:Projection: ProjectionProjection onon aa plane.plane. RR33ÆÆRR22 oror RR44ÆÆRR33 homogenoushomogenous coordinates.coordinates. Introduction to Projection Transformations Objectives

ƒƒƒIntroduceIntroduceIntroduce thethethe classicalclassicalclassical viewsviewsviews ƒƒƒCompareCompareCompare andandand contrastcontrastcontrast imageimageimage formationformationformation bybyby computercomputercomputer withwithwith howhowhow imagesimagesimages havehavehave beenbeenbeen formedformedformed bybyby architects,architects,architects, artists,artists,artists, andandand engineersengineersengineers ƒƒƒLearnLearnLearn thethethe benefitsbenefitsbenefits andandand drawbacksdrawbacksdrawbacks ofofof eacheacheach typetypetype ofofof viewviewview Classical Viewing

ViewingViewing requiresrequires threethree basicbasic elementselements •• One One oror moremore objectsobjects •• A A viewerviewer withwith aa projectionprojection surfacesurface •• Projectors Projectors thatthat gogo fromfrom thethe objecobject(s)t(s) toto thethe projectionprojection surfacesurface ClassicalClassical viewsviews areare basedbased onon thethe relationshiprelationship amongamong thesethese elementselements •• The The viewerviewer pickspicks upup thethe objectobject andand orientsorients itit howhow sheshe wouldwould likelike toto seesee itit EachEach objectobject isis assumedassumed toto constructedconstructed fromfrom flatflat principalprincipal facesfaces •• Buildings, Buildings, polyhedrapolyhedra,, manufacturedmanufactured objectsobjects Planar Geometric Projections

StandardStandardStandard projectionsprojectionsprojections projectprojectproject ontoontoonto aaa planeplaneplane ProjectorsProjectorsProjectors areareare lineslineslines thatthatthat eithereithereither •• converge converge atat aa centercenter ofof projectionprojection •• are are parallelparallel SuchSuchSuch projectionsprojectionsprojections preservepreservepreserve lineslineslines •• but but notnot necessarilynecessarily anglesangles NonNonNon-planar--planarplanar projectionsprojectionsprojections areareare neededneededneeded forforfor applicationsapplicationsapplications suchsuchsuch asasas mapmapmap constructionconstructionconstruction Classical Projections vs Parallel

ƒƒƒComputerComputerComputer graphicsgraphicsgraphics treatstreatstreats allallall projectionsprojectionsprojections thethethe samesamesame andandand implementsimplementsimplements themthemthem withwithwith aaa singlesinglesingle pipelinepipelinepipeline

ƒƒƒClassicalClassicalClassical viewingviewingviewing developeddevelopeddeveloped differentdifferentdifferent techniquestechniquestechniques forforfor drawingdrawingdrawing eacheacheach typetypetype ofofof projectionprojectionprojection

ƒƒƒFundamentalFundamentalFundamental distinctiondistinctiondistinction isisis betweenbetweenbetween parallelparallelparallel andandand perspectiveperspectiveperspective viewingviewingviewing eveneveneven thoughthoughthough mathematicallymathematicallymathematically parallelparallelparallel viewingviewingviewing isisis thethethe limitlimitlimit ofofof perspectiveperspectiveperspective viewingviewingviewing Taxonomy of Planar Geometric Projections Examples Perspective Projection

ProjectorsProjectorsProjectors areareare orthogonalorthogonalorthogonal tototo projectionprojectionprojection surfacesurfacesurface Multiview Orthographic Projection

ProjectionProjection planeplane parallelparallel toto principalprincipal faceface UsuallyUsually formform front,front, top,top, sideside viewsviews isometric (not multiview orthographic view) front

in CAD and architecture, we often display three multiviews plus isometric

top side Advantages and Disadvantages

PreservesPreservesPreserves bothbothboth distancesdistancesdistances andandand anglesanglesangles ••• ShapesShapes Shapes preservedpreservedpreserved ••• CanCan Can bebebe usedusedused forforfor measurementsmeasurementsmeasurements ––– BuildingBuildingBuilding plansplansplans ––– ManualsManualsManuals CannotCannotCannot seeseesee whatwhatwhat objectobjectobject reallyreallyreally lookslookslooks likelikelike becausebecausebecause manymanymany surfacessurfacessurfaces hiddenhiddenhidden fromfromfrom viewviewview ••• OftenOften Often wewewe addaddadd thethethe isometricisometricisometric Axonometric Projections

AllowAllowAllow projectionprojectionprojection planeplaneplane tototo movemovemove relativerelativerelative tototo objectobjectobject

classify by how many angles of a corner of a projected cube are the same θ 1 none: trimetric θ 2 θ 3 two: dimetric three: isometric Types of Axonometric Projections Advantages and Disadvantages

LinesLinesLines areareare scaledscaledscaled (((foreshortenedforeshortenedforeshortened))) butbutbut cancancan findfindfind scalingscalingscaling factorsfactorsfactors LinesLinesLines preservedpreservedpreserved butbutbut anglesanglesangles areareare notnotnot •• Projection Projection ofof aa circlecircle inin aa planeplane notnot parallelparallel toto thethe projectionprojection planeplane isis anan ellipseellipse CanCanCan seeseesee threethreethree principalprincipalprincipal facesfacesfaces ofofof aaa boxboxbox-like--likelike objectobjectobject SomeSomeSome opticalopticaloptical illusionsillusionsillusions possiblepossiblepossible •• Parallel Parallel lineslines appearappear toto divergediverge DoesDoesDoes notnotnot looklooklook realrealreal becausebecausebecause farfarfar objectsobjectsobjects areareare scaledscaledscaled thethethe samesamesame asasas nearnearnear objectsobjectsobjects UsedUsedUsed ininin CADCADCAD applicationsapplicationsapplications

ArbitraryArbitrary relationshiprelationship betweenbetween projectorsprojectors andand projectionprojection planeplane Advantages and Disadvantages

CanCanCan pickpickpick thethethe anglesanglesangles tototo emphasizeemphasizeemphasize aaa particularparticularparticular facefaceface ••• Architecture:Architecture: Architecture: planplanplan oblique,oblique,oblique, elevationelevationelevation obliqueobliqueoblique AnglesAnglesAngles ininin facesfacesfaces parallelparallelparallel tototo projectionprojectionprojection planeplaneplane areareare preservedpreservedpreserved whilewhilewhile wewewe cancancan stillstillstill seeseesee “““around”aroundaround”” sidesideside

InInIn physicalphysicalphysical world,world,world, cannotcannotcannot createcreatecreate withwithwith simplesimplesimple camera;camera;camera; possiblepossiblepossible withwithwith bellowsbellowsbellows cameracameracamera ororor specialspecialspecial lenslenslens (architectural)(architectural)(architectural) Perspective Projection

ProjectorsProjectorsProjectors convergeconvergeconverge atatat centercentercenter ofofof projectionprojectionprojection Vanishing Points

ƒƒƒParallelParallelParallel lineslineslines (not(not(not parallelparallelparallel tototo thethethe projectionprojectionprojection )plan)plan) ononon thethethe objectobjectobject convergeconvergeconverge atatat aaa singlesinglesingle pointpointpoint ininin thethethe projectionprojectionprojection (the(the(the vanishingvanishingvanishing pointpointpoint))) ƒƒƒDrawingDrawingDrawing simplesimplesimple perspectivesperspectivesperspectives bybyby handhandhand usesusesuses thesethesethese vanishingvanishingvanishing point(s)point(s)point(s)

Three-Point Perspective

NoNoNo principalprincipalprincipal facefaceface parallelparallelparallel tototo projectionprojectionprojection planeplaneplane ThreeThreeThree vanishingvanishingvanishing pointspointspoints forforfor cubecubecube Two-Point Perspective

OnOnOn principalprincipalprincipal directiondirectiondirection parallelparallelparallel tototo projectionprojectionprojection planeplaneplane TwoTwoTwo vanishingvanishingvanishing pointspointspoints forforfor cubecubecube One-Point Perspective

OneOneOne principalprincipalprincipal facefaceface parallelparallelparallel tototo projectionprojectionprojection planeplaneplane OneOneOne vanishingvanishingvanishing pointpointpoint forforfor cubecubecube Advantages and Disadvantages

ƒƒƒObjectsObjects furtherfurther fromfrom viewerviewer areare projectedprojected smallersmaller thanthan thethe samesame sizedsized objectsobjects closercloser toto thethe viewerviewer ((diminutiondiminution)) ••• LooksLooks realisticrealistic ƒƒƒEqualEqual distancesdistances alongalong aa lineline areare notnot projectedprojected intointo equalequal distancesdistances ((nonnon-uniform-uniform foreshorteningforeshortening)) ƒƒƒAnglesAngles preservedpreserved onlyonly inin planesplanes parallelparallel toto thethe projectionprojection planeplane ƒƒƒMoreMore difficultdifficult toto constructconstruct byby handhand thanthan parallelparallel projectionsprojections (but(but notnot moremore difficultdifficult byby computer)computer)