ebook img

OpenGL Graphics Through Applications PDF

334 Pages·2008·6.649 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview OpenGL Graphics Through Applications

Robert Whitrow OpenGL Graphics Through Applications RobertWhitrowBSc,PhD LondonMetropolitanUniversity,UK ISBN:978-1-84800-022-3 e-ISBN:978-1-84800-023-0 BritishLibraryCataloguinginPublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary LibraryofCongressControlNumber:2007938325 (cid:2)c Springer-VerlagLondonLimited2008 Apart from any fair dealing for the purposes of research or private study, or criticism or review, as permittedundertheCopyright,DesignsandPatentsAct1988,thispublicationmayonlybereproduced, stored or transmitted, in any form or by any means, with the prior permission in writing of the publishers,orinthecaseofreprographicreproductioninaccordancewiththetermsoflicencesissued bytheCopyrightLicensingAgency.Enquiriesconcerningreproductionoutsidethosetermsshouldbe senttothepublishers. Theuseofregisterednames,trademarks,etc.inthispublicationdoesnotimply,evenintheabsenceofa specificstatement,thatsuchnamesareexemptfromtherelevantlawsandregulationsandthereforefree forgeneraluse. Thepublishermakesnorepresentation,expressorimplied,withregardtotheaccuracyoftheinformation containedinthisbookandcannotacceptanylegalresponsibilityorliabilityforanyerrorsoromissions thatmaybemade. Printedonacid-freepaper 9 8 7 6 5 4 3 2 1 SpringerScience+BusinessMedia springer.com Preface This book is the result of teaching computer graphics for one and two semester, yeartwo/threeundergraduateandpostgraduatelecturecoursesinComputerGraph- ics.Throughoutthebook,theoryisfollowedbyimplementationusingC/C++and complete programs are provided with suggestions for change to enhance student understanding.During30yearsofuniversityteachingtheauthorhasbecomeaware of the frustration that many students suffer, of code fragments that ‘never quite work’andprogramsthatonadifferentsystemrequiresystemdependentadditions! Withthisinmindalltheprograms given have been testedusingMSC++ v6 and mosthavebeentestedusingSolaris4.2andBorlandC++v5. ThereareanumberoftextswhichgiveamoreindepthapproachtotheOpenGL pipelineandrepetitionhasthereforebeenavoidedbyreferencingsuchtextsforthe interestedreader.Theobjectiveistogetstudentsimmersedingraphicsapplications as rapidly as possible, to develop confidence, which in turn leads to experimenta- tion, which is so vital to the enthusiastic programmer. Theory and practice have beendevelopedinparallelsothatinmanycasesthereaderbeginstounderstandthe strengthsandweaknessesofaparticularalgorithm. After a rapid ‘getting started’ introduction we look at the structure of bit map (.bmp)filesasaprecursortounderstandingaudiovisualfiles(.avi).Thisworkforms a foundation for later sections on image processing and texturing. These are very simple file structures that can be converted from other image file formats using commerciallyavailablesoftwarepackages.Thechapterintroducingimageprocess- ingcoversedgedetection,enhancementanddatacapturefromCATscans.Theory andpracticecanbequitedifferentandsomeprocessingappearsmoreofanartthana scienceduetothevariabilityintheimagequalityandthenatureoftheimageitself. The example of edge finding on CAT scans where different slices may have well definededgesandothermorefuzzyedgesduetograyhairisnotalwaysapparentto theeye.Weaddresstheseproblemswithalternativesolutionswithvaryingdegrees ofsuccesstoenablereaderstocomprehendthatalgorithmicdevelopmentisstillan inexactscienceforsuchapplications. InChapter4wemovetothefirstchapter,whichmightbeconsideredtobecom- putergraphicswithallthemathematicsthatisrequired.Idonotencouragestudents toskipovertheseareasofunderstandingforthe‘blackbox’approachwillonlyget yousofarandgapsinknowledgeatanearlystagewillcometohauntonelateron. The toil of getting to grips with material will be amply repaid as students grow in knowledge–althoughIamawarethatmanyavoidthejoysofmathematicalrigor! v vi Preface Early on in computer graphics students are often heard to say; “why is there noerrormessageandnothingonthescreen?”.Knowingwhereoneisin3Dspace has been another difficult area to communicate. Conceptually compressing a 3D modelontoa2Dscreendoesnotcomeeasilytomanystudents’mindsandherewe introduce viewing. In OpenGL the viewing process is concerned with two opera- tions;themappinganobjectintoaviewingvolumeforscreendisplayandcalledthe PROJECTION process, while the orientation and size operations on the object is referredtoastheMODELVIEWprocess.Beinginthewrongplace,whetherviewer or object can leave nothing on a screen and much confusion as how to proceed. The author maintains that there is little alternative to debugging than printing out a few well-chosen coordinates to see if they lie in the field of view! With practice onebecomesawareoflocation,butintheearlystages3Dspaceseemslikelearning toflyincloud–fewreferencepointsandadegreeofpanicifyoudon’ttrustyour instruments(coordinatevaluesinourcase). Lightingbeginstobringrealismtodisplaysandinthissectionwecoverthedif- ferentformsoflightingavailableandseetheeffectsaswemoveobjectsinrelation toalightsource.Wealsolinktheearlyworkonthetransformationsasweseehow illumination varies across a surface and adjust the surface properties to produce highlights. In Chapter 7 we return to bit map images and use them to cover surfaces with pictures,initiallyonsimpleflatplanesandthendeveloplinearmappingmethodsfor more complex surfaces. We introduce the concept of mapping onto terrain with a givenheightprofiletosimulatetheideaofmountainsandvalleys.Multipletextures are used to simulate scenery as seen through windows and the changes apparent from movement in a room are implemented. An introduction to 3D texturing is includedandfinallyreconstructionof3Dvolumesfrom2DCATscanslices. Object orientation has played a lesser part in the text up to this section and we now use the concept to build artifacts based on work in the previous chapters. Objects such as cylinders and ‘stretched cubes’ are textured with an appropriate image and result in building blocks for furniture. The tables built are then placed within the context of say a room to introduce students to applications of furniture androomdecoration.Thewritingratherthanonlyusingobjectshasprovedfruitful in student projects, where an understanding of mass manufacture has led students to consider in some depth the flexibility required in design for object use to be economic. ThefinalchapterconsidersthedevelopmentofcurvesandsurfacesusingSplines and Bezier interpolation and fractals. A section on fractals explores the role they canplayinaddingobjectstosceneryandoutliningcomplexshapes. Approach Thisbooksetsouttosolveproblemsbycompleteexampleratherthandiscursively hintofhowitmaybedone.Weliveinaneraofmasseducationwhereasever,the veryablethrivewithoutmuchneedofteachingbutwherethelargemassofstudents Preface vii have less access to staff due to funding constraints. Some believe technology will overcometheseobstaclesandtheauthorbelievesthatonecontributiontothesolu- tion of the problem is doing by example. However, a black box recipe approach leaves students vulnerable when circumstances change and thus I have included theory followed by worked examples. The initial implementation sometimes pro- duces inefficient code and I have left this deliberately in order that students can followwherealgorithmsoriginatefromtheory.Goodprogramdesignandefficient code comes from an in depth understanding that is the result of a long process of assimilation. SupportingMaterial SupportmaterialsmaybefoundmaybefoundontheaccompanyingSpringerweb sitehttp://www.springer.com/978-1-84800-022-3 Theyinclude: Programcode Datafiles OpenGLincludefiles OpenGLlinklibrariesfromtheMesasite. RobertWhitrow DepartmentofComputing CommunicationsTechnologyandMathematics LondonMetropolitanUniversity,UK Acknowledgements The enthusiasm of my students has made a major contribution to making this text possible. I would particularly thank George Fordham, A Saadat, Paul Kunka, AbidKhan,MichelleStafford,CecilleBoulanger,PaulArmstrongandmanyothers whose names escape me now who I learnt from and who inspired me with their enquiringmindsandneverendingquestions.Theirworkandeffortsarepartofthis book and without out meeting first hand the problems of learning, I would have neverbeendriventowritethistext. As with any course, material develops over time and occasionally the original sourcecanbeeasilyforgotten.InthistextIhavereferencedsourcesthathavebeen particularly helpful in my teaching, developing this text and will be valuable to readerswhowishtoexplorefurtherassupportingmaterial. I would also thank Dr Ronnie Burton who first welcomed me to his OpenGL courseintheautumnof2001andwithhisencouragementsuggestedItakeateach- ingroleinthepresentationatLondonMetropolitanUniversity.Ronnieunstintingly gave of his time and knowledge, which made this work possible. I cannot let pass the support of Professor Jim Yip and Professor Ian Haines who appointed me and providedthetimeandspacetocompletethetext.Theirenthusiasm,encouragement andleadershipwasanexampletoall–thankyou. Aswithmanytasksthereisoftenafrequentlyhiddenunseensupportintheback- ground – my wife Despoulla who has cajouled and pressed for completion when I could find reasons for vaccilation! I recognise and thank her for the persistent determinationthatwasamajorcontributiontothesuccessofthework. Theprimarypurposeofeducationistomakeone’smindapleasantplaceinwhichtospend one’sleisure–S.J.Harris ix Contents 1 GettingStarted ................................................. 1 1.1 Introduction................................................ 1 1.2 AccesstoLibraries.......................................... 2 1.3 DataTypes ................................................ 2 1.4 Terminology ............................................... 3 1.5 TheOpenGLUtilityToolkit–GLUT ........................... 3 1.6 OurFirstProgram........................................... 4 1.6.1 DrawingPrimitives .................................. 7 1.6.2 Gaps,LinesandBlobs ............................... 10 1.6.3 OtherLineTypes.................................... 11 1.6.4 SurfacePatternsandPolygonStippling ................. 12 1.6.5 CharacterGeneration ................................ 15 1.7 ParametricRepresentationofCurves........................... 17 1.7.1 TheGrowthorLogarithmicSpiral...................... 19 1.8 ApproximationandProcessingEfficiency....................... 21 1.8.1 LineDrawing....................................... 22 1.8.2 TheDigitalDifferenceAnalyser ....................... 23 1.8.3 Bresenham’sAlgorithm .............................. 25 1.8.4 Bresenham’sAlgorithmforaCircle .................... 27 1.9 ProblemSolvingThroughGraphics............................ 31 1.10TheApplicationProgrammingInterface(API)................... 34 1.10.1 TheOpenGLUtilityToolkit(GLUT)Library ............ 34 1.10.2 MouseInteraction ................................... 35 1.10.3 KeyboardInteraction................................. 36 1.11Exercises .................................................. 37 1.12Conclusion ................................................ 37 2 ImageFileFormats.............................................. 39 2.1 Introduction................................................ 39 2.2 TheBitmapFile ............................................ 39 2.2.1 Bitmap-fileStructure................................. 40 2.2.2 ATypicalFileLayout ................................ 41 xi xii Contents 2.2.3 ReadingandDrawingaBitmapFile .................... 42 2.2.4 CreatingaDisplayWindow ........................... 45 2.2.5 CreatingtheImageforDisplay ........................ 46 2.2.6 MonochromeBitmaps................................ 46 2.2.7 AGeneralClassforInputofBit MapFiles ......................................... 47 2.2.8 ManipulatingBitMaps–Embossing ................... 49 2.3 Audio/VideoInterleaved(AVI)FileFormat ..................... 51 2.3.1 ChunkHierarchy .................................... 53 2.3.2 AnExampleofWebCamDisplay...................... 55 2.3.3 Compression ....................................... 58 2.4 Exercises .................................................. 59 2.5 Conclusion ................................................ 59 3 ImageProcessing................................................ 61 3.1 Introduction................................................ 61 3.2 FindingObjects ............................................ 61 3.2.1 EdgeDetection...................................... 62 3.2.2 NumericalImplementation............................ 63 3.2.3 SobelOperator...................................... 63 3.2.4 Convolution ........................................ 64 3.2.5 LaplacianOperator .................................. 66 3.2.6 SmoothingandEdgeFinding.......................... 69 3.3 HistogramEqualisation ...................................... 71 3.4 Component(object)Labelling ................................ 73 3.4.1 ExploringConnectivity(1)............................ 74 3.4.2 ExploringConnectivity(2)............................ 76 3.4.3 MultipleRegions.................................... 77 3.5 DrawingontheScreenandDataCapture ....................... 77 3.5.1 OutliningofAreasofInterestonImages ................ 80 3.5.2 AnApproachtoAutomatingEdgeDetection............. 82 3.6 Exercises .................................................. 85 3.7 Conclusion ................................................ 85 4 Transformations ................................................ 87 4.1 Introduction................................................ 87 4.2 RepresentingPointsandVectors............................... 87 4.2.1 VectorDotProducts ................................. 89 4.2.2 TheVectorCrossProduct............................. 89 4.2.3 UsingtheCrossProducttoProvideColourVariation toaCylinder....................................... 91 4.3 CoordinateSystems ......................................... 94 4.4 Transformations ............................................ 95 4.4.1 Rotation ........................................... 96 4.4.2 ASimpleExampleofRotation ........................ 98 Contents xiii 4.4.3 GeneralRotationsAboutAnyPoint .................... 99 4.5 TheModelViewMatrix .....................................103 4.6 AddingSomeMovement.....................................103 4.6.1 MovementofCompositeObjects.......................104 4.6.2 TheOrrery .........................................104 4.6.3 TheInternalCombustionEngine.......................107 4.6.4 Arms,Robots,ActuatorsandMovement ................113 4.6.5 DataCaptureofLimbMovement ......................114 4.6.6 Animation–AWalkingRobot.........................116 4.7 CollisionDetection .........................................120 4.8 Exercises ..................................................124 4.9 Conclusion ................................................124 5 ViewingandProjection ..........................................125 5.1 Introduction................................................125 5.2 VertexPipeline .............................................125 5.3 TheViewingProcess ........................................126 5.3.1 EngineeringDrawings................................128 5.4 OrthographicorParallelProjection ............................132 5.4.1 FromRealWorldtoScreenWindow....................132 5.4.2 InsidetheMatrix ....................................134 5.4.3 GettingtoGripswithWhereThingsAre ................137 5.4.4 PerspectiveProjection................................139 5.4.5 UnderstandingtheView ..............................143 5.5 Exercises ..................................................145 5.6 Conclusion ................................................146 6 LightingandColour.............................................147 6.1 Introduction................................................147 6.2 TheElectromagneticSpectrum................................147 6.2.1 Colour.............................................148 6.2.2 MixingColours .....................................149 6.2.3 TheShadingModel..................................150 6.3 LightingandIllumination ....................................151 6.3.1 SettinguptheLighting ...............................152 6.3.2 AdditionofSpecularLight............................157 6.4 ASyntheticFace ...........................................162 6.4.1 GettingtheVertexCoordinates ........................162 6.4.2 MovingtheEyeandLightSourceTogether..............163 6.5 Shadows–AProjection......................................164 6.5.1 DerivationoftheShadowOutlineUsingEquation ofaLine ..........................................164 6.5.2 APolygonMovingShadow ...........................166 6.6 Exercises ..................................................168 6.7 Conclusion ................................................169 xiv Contents 7 TextureMapping................................................171 7.1 Introduction................................................171 7.2 TheMappingProcess........................................171 7.3 SettingupTextures..........................................172 7.3.1 DrawingtheTexture .................................174 7.4 MappingontoCurvedSurfaces................................176 7.4.1 MercatorLinesofProjection ..........................176 7.4.2 QuadricSurfaces ....................................177 7.4.3 MappingontoaSphericalSurface......................178 7.4.4 MappingoneImagetoSphere .........................182 7.4.5 CylinderTexturingMapping ..........................184 7.4.6 MappingtoaCircle..................................185 7.4.7 MappingtoaCone ..................................186 7.4.8 MappingontoaGeneralSurface .......................189 7.4.9 MappingontoaContourSurface.......................191 7.5 AddingSomeMovement–ARotatingHemisphere ..............193 7.5.1 MovementviatheMouse .............................196 7.6 UsingBitMapstoProvideContext ............................200 7.6.1 Blending...........................................202 7.6.2 ManipulatingPixels..................................206 7.7 Three-DimensionalTexturing.................................212 7.7.1 SimulationofaSphericalObject.......................213 7.7.2 BuildingaSolidModelofaHead ......................219 7.8 Exercises ..................................................226 7.9 Conclusion ................................................226 8 ObjectstoArtefacts .............................................227 8.1 Introduction................................................227 8.2 ArtefactHierarchy ..........................................227 8.2.1 ConstructionDoubleSidedSquares ....................228 8.2.2 ABoxasaBasicBuildingBlock ......................232 8.2.3 BuildingaTable.....................................233 8.3 IntegratingtoaSystem ......................................235 8.4 ChangingtheFurnitureStyle .................................243 8.5 Exercises ..................................................247 8.6 Conclusion ................................................247 9 Curves,SurfacesandPatterns ....................................249 9.1 Introduction................................................249 9.2 FittingaLineoraCurve .....................................250 9.2.1 StraightLineFittingtoDataPoints.....................250 9.2.2 LagrangePolynomialsandCurveFitting ................251 9.2.3 APracticalApproachtoCurveFitting ..................251 9.2.4 CurveFittingUsingCubicSplines .....................252 9.2.5 SurfaceConstructionfromContourMaps ...............256

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.