100% found this document useful (1 vote)
346 views

Full download OpenGL Programming Guide 5th Edition Opengl Architecture Review Board pdf docx

Programming

Uploaded by

tomeistypavc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
346 views

Full download OpenGL Programming Guide 5th Edition Opengl Architecture Review Board pdf docx

Programming

Uploaded by

tomeistypavc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebook

OpenGL Programming Guide 5th Edition Opengl


Architecture Review Board

_____ Click the link below to download _____


https://ebookfinal.com/download/opengl-programming-
guide-5th-edition-opengl-architecture-review-board/

Explore and download more ebook at ebookfinal.com


Here are some recommended products that might interest you.
You can download now and explore!

Beginning OpenGL Game Programming 1st Edition Dave Astle

https://ebookfinal.com/download/beginning-opengl-game-programming-1st-
edition-dave-astle/

ebookfinal.com

Beginning OpenGL Game Programming 1st Edition Dave Astle

https://ebookfinal.com/download/beginning-opengl-game-programming-1st-
edition-dave-astle-2/

ebookfinal.com

Advanced Graphics Programming Using OpenGL 1st Edition Tom


Mcreynolds

https://ebookfinal.com/download/advanced-graphics-programming-using-
opengl-1st-edition-tom-mcreynolds/

ebookfinal.com

OpenGL SuperBible Comprehensive Tutorial and Reference 5th


Edition Richard S. Wright

https://ebookfinal.com/download/opengl-superbible-comprehensive-
tutorial-and-reference-5th-edition-richard-s-wright/

ebookfinal.com
OpenGL Game Programming Prima Tech s Game Development 1st
Edition Kevin Hawkins

https://ebookfinal.com/download/opengl-game-programming-prima-tech-s-
game-development-1st-edition-kevin-hawkins/

ebookfinal.com

OpenGL ES 2 for Android A Quick Start Guide 1st Edition


Kevin Brothaler

https://ebookfinal.com/download/opengl-es-2-for-android-a-quick-start-
guide-1st-edition-kevin-brothaler/

ebookfinal.com

Family Practice Examination Board Review Second Edition


McGraw Hill Specialty Board Review Mark Graber

https://ebookfinal.com/download/family-practice-examination-board-
review-second-edition-mcgraw-hill-specialty-board-review-mark-graber/

ebookfinal.com

Urology Board Review Stephen Leslie

https://ebookfinal.com/download/urology-board-review-stephen-leslie/

ebookfinal.com

Specialty Board Review Dermatology a Pictorial Review 2nd


Edition Ali Asra.

https://ebookfinal.com/download/specialty-board-review-dermatology-a-
pictorial-review-2nd-edition-ali-asra/

ebookfinal.com
OpenGL Programming Guide 5th Edition Opengl
Architecture Review Board Digital Instant Download
Author(s): OpenGL Architecture Review Board, Dave Shreiner, Mason Woo,
Jackie Neider, Tom Davis
ISBN(s): 9780321335739, 0321335732
Edition: 5
File Details: PDF, 54.80 MB
Year: 2005
Language: english
OpenGL®
Programming Guide
Fifth Edition

The Official Guide to


Learning OpenGL®, Version 2

OpenGL Architecture Review Board


Dave Shreiner Mason Woo
Jackie Neider Tom Davis

Addison-Wesley
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and the publisher was
aware of a trademark claim, the designations have been printed with initial capital letters or
in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales, which may include electronic versions and/or custom covers and
content particular to your business, training goals, marketing focus, and branding interests.
For more information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
[email protected]
For sales outside of the U.S., please contact:
International Sales
[email protected]
Visit us on the Web: www.awprofessional.com
Library of Congress Cataloging-in-Publication Data
OpenGL programming guide : the official guide to learning OpenGL, version 2 /
OpenGL Architecture Review Board, Dave Shreiner ... [et al.]. –5th ed.
p. cm.
Includes index.
ISBN 0-321-33573-2 (pbk. : alk. paper)
1. Computer graphics. 2. OpenGL. I. Shreiner, Dave. II. OpenGL Architecture
Review Board

T385.0635 2005
006.6'6—dc22 2005014386
Copyright © 2006 by Silicon Graphics, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
One Lake Street
Upper Saddle River, NJ 07458
ISBN 0-321-33573-2
Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts.
First printing, July 2005
For my family—Felicity, Max, Sarah, and Scout.
—JLN

For my family—Ellyn, Ricky, and Lucy.


—TRD

To Tom Doeppner and Andy van Dam, who started me along this path.

—MW
For my family—Vicki, Bonnie, Bob, Phantom, Toby, Squiggles, and Tuxedo.
—DRS

In memory of Phil Karlton and Celeste Fowler.


-
Contents

Figures xxi

Tables xxv

Examples xxix

About This Guide xxxv


What This Guide Contains xxxv
What's New in This Edition xxxviii
What You Should Know BefOre Reading This Guide xxxviii
How to Obtain the Sample Code xl
Nate Robins' OpenGL Tutors xl
Errata xl
Style Conventions xli

Acknowledgments xliii

1. Introduction to OpenGL 1
What Is OpenGL? 2
A Smidgen of OpenGL Code 5
OpenGL Command Syntax 7
OpenGL as a State Machine 9
OpenGL Rendering Pipeline 10
Display Lists 11
Evaluators 11
Per-Vertex Operations 12
Primitive Assembly 12

vii
Pixel Operations 12
Texture Assembly 13
Rasterization 13
Fragment Operations 13
OpenGL-Related Libraries 14
Include Files 15
GLUT, the OpenGL Utility Toolkit 16
Animation 20
The Refresh That Pauses 22
Motion = Redraw + Swap 23

2. State Management and Drawing Geometric Objects 27

A Drawing Survival Kit 29


Clearing the Window 30
Specifying a Color 32
Forcing Completion of Drawing 34
Coordinate System Survival Kit 36
Describing Points, Lines, and Polygons 37
What Are Points, Lines, and Polygons? 37
Specifying Vertices 41
OpenGL Geometric Drawing Primitives 42
Basic State Management 48
Displaying Points, Lines, and Polygons 50
Point Details 50
Line Details 51
Polygon Details 55
Normal Vectors 63
Vertex Arrays 65
Step 1: Enabling Arrays 67
Step 2: Specifying Data for the Arrays 68
Step 3: Dereferencing and Rendering 71
Interleaved Arrays 78
Vertex Arrays in Buffer Objects 82
Utilizing Buffer Objects with Vertex-Array Data 82
Creating Buffer Objects for Vertex Data 83
Making a Buffer Object Active 83

viii Contents
Allocating and Initializing Buffer Objects with Vertex Data 84
Updating Data Values in Buffer Objects 88
Cleaning up Buffer Objects 90
Attribute Groups 90
Some Hints for Building Polygonal Models of Surfaces 93
An Example: Building an Icosahedron 95

3. Viewing 103
Overview: The Camera Analogy 106
A Simple Example: Drawing a Cube 109
General-PurpOse TransfOrmation Commands 114
Viewing and Modeling Transformations 117
Thinking abOut Transformations 117
Modeling TransfOrmations 120
Viewing TransformatiOns 126
Projection TransfOrmations 133
Perspective Projection 133
Orthographic Projection 136
Viewing Volume Clipping 138
Viewport Transformation 138
Defining the Viewport 39
The Transformed Depth CoOrdinate 141
Troubleshooting Transformations 142
Manipulating the Matrix Stacks 145
The Modelview Matrix Stack 148
The Projection Matrix Stack 148
Additional Clipping Planes 149
Examples of Composing Several TransfOrmations 152
Building a SOlar System 153
Building an Articulated RObOt Arm 156
Reversing or Mimicking Transformations 160

4. Color 165
ColOr PerceptiOn 166
Computer Color 168
RGBA versus Color-Index Mode 170

Contents ix
RGBA Display Mode 171
Color-Index Display Mode 173
Choosing between RGBA and Color-Index Mode 1
175
Changing between Display Modes 176
Specifying a Color and a Shading Model 176
Specifying a Color in RGBA Mode 177
Specifying a Color in Color-Index Mode 178
Specifying a Shading Model 179

5. Lighting 183
A Hidden-Surface Removal Survival Kit 185
Real-World and OpenGL Lighting 187
Ambient, Diffuse, Specular, and Emissive Light 188
Material Colors 189
RGB Values for Lights and Materials 189
A Simple Example: Rendering a Lit Sphere 190
Creating Light Sources 194
Color 196
Position and Attenuation 197
Spotlights 199
Multiple Lights 200
Controlling a Light's Position and Direction 201
Selecting a Lighting Model 207
Global Ambient Light 208
Local Or Infinite ViewpOint 209
Two-Sided Lighting 209
Secondary Specular Color 210
Enabling Lighting 211
Defining Material Properties 211
Diffuse and Ambient Reflection 213
Specular Reflection 214
Emission 214
Changing Material Properties 215
Color Material Mode 217
The Mathematics of Lighting 220
Material Emission 221

X Contents
Scaled Global Ambient Light 222
Contributions from Light Sources 222
Putting It All Together 224
Secondary Specular Color 225
Lighting in Color-Index Mode 226
The Mathematics of Color-Index Mode Lighting 227

6. Blending, Antialiasing, Fog, and Polygon Offset 229

Blending 231
The Source and Destination Factors 232
Enabling Blending 235
Combining Pixels Using Blending EquatiOns 235
Sample Uses of Blending 238
A Blending Example 240
Three-Dimensional Blending with the Depth Buffer 243
Antialiasing 247
Antialiasing Points or Lines 249
Antialiasing Geometric Primitives with Multisampling 255
Antialiasing POlygons 259
Fog 261
Using Fog 261
Fog Equations 264
Point Parameters 271
PolygOn Offset 274

7. Display Lists 277

Why Use Display Lists? 278


An Example of Using a Display List 279
Display List Design Philosophy 282
Creating and Executing a Display List 285
Naming and Creating a Display List 286
What's Stored in a Display List? 287
Executing a Display List 289
Hierarchical Display Lists 290
Managing Display List Indices 291
Executing Multiple Display Lists 292

Contents xi
Managing State Variables with Display Lists 297
Encapsulating Mode Changes 299

8. Drawing Pixels, Bitmaps, Fonts, and Images 301


Bitmaps and Fonts 303
The Current Raster PositiOn 305
Drawing the Bitmap 306
Choosing a Color for the Bitmap 308
Fonts and Display Lists 309
Defining and Using a Complete Font 310
Images 312
Reading, Writing, and Copying Pixel Data 313
Imaging Pipeline 321
Pixel Packing and Unpacking 324
Controlling Pixel-Storage Modes 325
Pixel-Transfer Operations 330
Pixel Mapping 333
Magnifying, Reducing, or Flipping an Image 334
Reading and Drawing Pixel Rectangles 337
The Pixel Rectangle Drawing Process 338
Tips for Improving Pixel Drawing Rates 341
Imaging Subset 342
Color Tables 344
Convolutions 349
Color Matrix 357
Histogram 359
Minmax 362

9. Texture Mapping 365

An Overview and an Example 371


Steps in Texture Mapping 371
A Sample Program 372
Specifying the Texture 375
Texture Proxy 380
Replacing All or Part of a Texture Image 382
One-DimensiOnal Textures 385

xii Contents
Three-Dimensional Textures 387
Compressed Texture Images 392
Using a Texture's Borders 395
Mipmaps: Multiple Levels of Detail 395
Filtering 406
Texture Objects 409
Naming a Texture Object 410
Creating and Using Texture Objects 410
Cleaning Up Texture Objects 413
A Working Set of Resident Textures 414
Texture Functions 416
Assigning Texture Coordinates 420
COmputing Appropriate Texture CoOrdinates 422
Repeating and Clamping Textures 423
Automatic Texture-Coordinate GeneratiOn 429
Creating COntOurs 430
Sphere Map 434
Cube Map Textures 436
Multitexturing 438
Texture Combiner Functions 444
The Interpolation Combiner Function 448
Applying Secondary Color after Texturing 450
SecOndary Color When Lighting Is Disabled 450
Secondary Specular Color When Lighting Is Enabled 450
The Texture Matrix Stack 451
Depth Textures 452
Creating a ShadOw Map 453
Generating Texture Coordinates and Rendering 454

10. The Framebuffer 457

Buffers and Their Uses 460


Color Buffers 461
Clearing Buffers 462
Selecting Color Buffers for Writing and Reading 463
Masking Buffers 465
Testing and Operating on Fragments 467

Contents xiii
Scissor Test 468
Alpha Test 468
Stencil Test 470
Depth Test 475
Occlusion Query 476
Blending, Dithering, and Logical Operations 479
The Accumulation Buffer 482
Scene Antialiasing 483
Motion Blur 489
Depth of Field 489
Soft Shadows 494
Jittering 494

11. Tessellators and Quadrics 497


POlygon Tessellation 498
Creating a Tessellation Object 500
Tessellation Callback Routines 500
Tessellation Properties 505
Polygon Definition 510
Deleting a Tessellation Object 513
Tessellation Performance Tips 513
Describing GLU Errors 514
Backward Compatibility 514
Quadrics: Rendering Spheres, Cylinders, and Disks 515
Managing Quadrics Objects 516
Controlling Quadrics Attributes 517
Quadrics Primitives 519

12. Evaluators and NURBS 525


Prerequisites 527
Evaluators 528
One-Dimensional Evaluators 528
Two-DimensiOnal Evaluators 534
Using Evaluators for Textures 540
The GLU NURBS Interface 542
A Simple NURBS Example 542
Managing a NURBS Object 547

xiv Contents
Creating a NURBS Curve Or Surface 551
Trimming a NURBS Surface 557

13. Selection and Feedback 561


Selection 562
The Basic Steps 563
Creating the Name Stack 564
The Hit Record 566
A Selection Example 567
Picking 570
Hints for Writing a Program That Uses Selection 581
Feedback 583
The Feedback Array 585
Using Markers in Feedback Mode 586
A Feedback Example 586

14. Now That You Know 591


Error Handling 593
Which Version Am I Using? 595
Utility Library Version 596
Window System ExtensiOn Versions 597
Extensions to the Standard 597
Extensions to the Standard for MicrosOft Windows (WGL) 599
Cheesy Translucency 600
An Easy Fade Effect 600
Object Selection Using the Back Buffer 602
Cheap Image Transformation 603
Displaying Layers 604
Antialiased Characters 605
Drawing Round Points 608
InterpOlating Images 608
Making Decals 608
Drawing Filled, Concave Polygons Using the Stencil Buffer 610
Finding Interference Regions 611
Shadows 613
Hidden-Line Removal 614

Contents xv
Hidden-Line Removal with Polygon Offset 614
Hidden-Line Removal with the Stencil Buffer 615
Texture Mapping Applications 616
Drawing Depth-Buffered Images 617
Dirichlet Domains 617
Life in the Stencil Buffer 619
Alternative Uses for glDrawPixels() and glCopyPixels() 620

15. OpenGL 2.0 and the OpenGL Shading Language 623

Why OpenGL 2.0? 624


Point Sprites 624
The OpenGL Graphics Pipeline and Programmable Shading 626
Vertex Processing 627
Fragment Processing 629
Using GLSL Shaders 630
A Sample Shader 630
OpenGL / GLSL Interface 631
The OpenGL Shading Language 638
Creating Shaders with GLSL 639
The Starting POint 639
Declaring Variables 639
Aggregate Types 641
Statements 648
FunctiOns 651
Using OpenGL State Values in GLSL Programs 653
Accessing Texture Maps in Shaders 653
Vertex Shader Specifics 655
Fragment Shaders 662

A. Order of Operations 665

Overview 666
Geometric Operations 667
Per-Vertex Operations 667
Primitive Assembly 668
Pixel Operations 668
Texture Memory 669

xvi Contents
Fragment Operations 669
Odds and Ends 670

B. State Variables 671

The Query Commands 672


OpenGL State Variables 674
Current Values and Associated Data 676
Vertex Array 677
Transformation 681
ColOring 683
Lighting 684
Rasterization 686
Multisampling 688
Texturing 689
Pixel Operations 695
Framebuffer COntrol 697
Pixels 698
Evaluators 704
Hints 705
Implementation-Dependent Values 706
Implementation-Dependent Pixel Depths 710
Miscellaneous 710

C. OpenGL and Window Systems 713

Accessing New OpenGL Functions 714


GLX: OpenGL Extension for the X Window System 715
Initialization 716
ContrOlling Rendering 717
GLX Prototypes 719
AGL: OpenGL Extensions for the Apple Macintosh 722
Initialization 722
Rendering and Contexts 723
Managing an OpenGL Rendering COntext 723
On-Screen Rendering 723
Off-Screen Rendering 724
Full-Screen Rendering 724

Contents xvii
Swapping Buffers 724
Updating the Rendering Buffers 724
Using an Apple Macintosh Font 724
Error Handling 725
AGL Prototypes 725
PGL: OpenGL Extension for IBM OS/2 Warp 727
Initialization 727
Controlling Rendering 728
PGL Prototypes 729
WGL: OpenGL Extension for Microsoft
Windows 95/98/NT/ME/2000/XP 731
Initialization 731
Controlling Rendering 732
WGL Prototypes 733

D. Basics of GLUT: The OpenGL Utility Toolkit 737


Initializing and Creating a Window 738
Handling Window and Input Events 739
Loading the Color Map 741
Initializing and Drawing Three-Dimensional Objects 741
Managing a Background Process 743
Running the Program 743

E. Calculating Normal Vectors 745


Finding Normals fOr Analytic Surfaces 747
Finding Normals from Polygonal Data 749

F. Homogeneous Coordinates and Transformation Matrices 751


Homogeneous CoOrdinates 752
Transforming Vertices 752
Transforming Normals 753
Transformation Matrices 753
Translation 754
Scaling 754
Rotation 754

xviii Contents
Perspective Projection 755
Orthographic Projection 756

G. Programming Tips 757

OpenGL Correctness Tips 758


OpenGL Performance Tips 760
GLX Tips 762

H. OpenGL Invariance 763

I. Built-In OpenGL Shading Language Variables and Functions 767

Variables 768
Vertex Shader Input Attributes Variables 768
Vertex Shader Special Output Variables 768
Vertex Shader Output Varying Variables 769
Built-In Implementation Constants 770
Built-In UnifOrm State Variables 771
Built-In Functions 780
Angle Conversion and Trigonometric Functions 780
Transcendental FunctiOns 781
Basic Numerical Functions 782
Vector-Operation Functions 783
Matrix Functions 784
VectOr-COmponent Relational Functions 784
Texture Lookup Functions 785
Fragment Processing Functions 790
Noise Functions 790

Glossary 791

Index 813

Contents xix
Figures

Figure 1-1 White Rectangle on a Black Background 6


Figure 1-2 Order of OperatiOns 11
Figure 1-3 Double-Buffered ROtating Square 24
Figure 2-1 Coordinate System Defined by w = 50, h = 50 37
Figure 2-2 Two Connected Series of Line Segments 38
Figure 2-3 Valid and Invalid Polygons 39
Figure 2-4 Nonplanar PolygOn Transformed to Nonsimple POlygon 40
Figure 2-5 Approximating Curves 41
Figure 2-6 Drawing a Polygon or a Set of Points 43
Figure 2-7 Geometric Primitive Types 44
Figure 2-8 Stippled Lines 53
Figure 2-9 Wide Stippled Lines 53
Figure 2-10 Constructing a POlygon Stipple Pattern 59
Figure 2-11 Stippled PolygOns 60
Figure 2-12 Subdividing a Nonconvex Polygon 62
Figure 2-13 Outlined Polygon Drawn Using Edge Flags 63
Figure 2-14 Six Sides, Eight Shared Vertices 66
Figure 2-15 Cube with Numbered Vertices 74
Figure 2-16 Modifying an Undesirable T-Intersection 95
Figure 2-17 Subdividing to ImprOve a Polygonal Approximation
tO a Surface 99
Figure 3-1 The Camera Analogy 107
Figure 3-2 Stages of Vertex Transformation 108
Figure 3-3 Transformed Cube 109
Figure 3-4 Rotating First or Translating First 118

xxi
Figure 3-5 Translating an Object 121
Figure 3-6 Rotating an Object 122
Figure 3-7 Scaling and Reflecting an Object 123
Figure 3-8 Modeling Transformation Example 124
Figure 3-9 Object and Viewpoint at the Origin 127
Figure 3-10 Separating the Viewpoint and the Object 127
Figure 3-11 Default Camera Position 130
Figure 3-12 Using gluLookAt() 130
Figure 3-13 Perspective Viewing VOlume Specified by glFrustum() 134
Figure 3-14 Perspective Viewing Volume Specified
by gluPerspective() 135
Figure 3-15 Orthographic Viewing VOlume 137
Figure 3-16 Viewport Rectangle 139
Figure 3-17 Mapping the Viewing Volume to the Viewport 140
Figure 3-18 Perspective Projection and Transformed
Depth Coordinates 141
Figure 3-19 Using Trigonometry to Calculate the Field of View 143
Figure 3-20 Modelview and Projection Matrix Stacks 145
Figure 3-21 Pushing and Popping the Matrix Stack 146
Figure 3-22 Additional Clipping Planes and the Viewing Volume 149
Figure 3-23 Clipped Wireframe Sphere 151
Figure 3-24 Planet and Sun 153
Figure 3-25 Robot Arm 156
Figure 3-26 Robot Arm with Fingers 159
Figure 4-1 The Color Cube in Black and White 169
Figure 4-2 RGB Values from the Bitplanes 171
Figure 4-3 Dithering Black and White to Create Gray 173
Figure 4-4 A Color Map 174
Figure 4-5 Using a Color Map to Paint a Picture 174
Figure 5-1 A Lit and an Unlit Sphere 184
Figure 5-2 GL_SPOT_CUTOFF Parameter 199
Figure 6-1 Creating a Nonrectangular Raster Image 240
Figure 6-2 Aliased and Antialiased Lines 247
Figure 6-3 Determining Coverage Values 248
Figure 6-4 Fog-Density Equations 265

xxii Figures
Figure 6-5 Polygons and Their Depth Slopes 275
Figure 7-1 Stroked Font That Defines the Characters A, E, P, R, S 294
Figure 8-1 Bitmapped F and Its Data 304
Figure 8-2 Bitmap and Its Associated Parameters 307
Figure 8-3 Simplistic Diagram of Pixel Data FlOw 314
Figure 8-4 CompOnent Ordering for Some Data Types
and Pixel Formats 319
Figure 8-5 Imaging Pipeline 322
Figure 8-6 glCopyPixels() Pixel Path 323
Figure 8-7 glBitmap() Pixel Path 323
Figure 8-8 glTexImage*(), glTexSubImage*(), and
glGetTexImage() Pixel Paths 324
Figure 8-9 glCopyTexlmage*() and
glCopyTexSublmage*() Pixel Paths 324
Figure 8-10 Byte Swap Effect on Byte, Short, and Integer Data 328
Figure 8-11 *SKIP_ROWS, *SKIP_PIXELS, and
*ROW_LENGTH Parameters 329
Figure 8-12 Drawing Pixels with glDrawPixels() 338
Figure 8-13 Reading Pixels with glReadPixels() 340
Figure 8-14 Imaging Subset Operations 343
Figure 8-15 The Pixel COnvolution Operation 350
Figure 9-1 Texture-Mapping Process 367
Figure 9-2 Texture-Mapped Squares 373
Figure 9-3 Texture with Subimage Added 383
Figure 9-4 *IMAGE_HEIGHT Pixel-Storage Mode 391
Figure 9-5 *SKIP_IMAGES Pixel-Storage Mode 392
Figure 9-6 Mipmaps 396
Figure 9-7 Using a MOsaic Texture 401
Figure 9-8 Texture MagnificatiOn and Minification 407
Figure 9-9 Texture-Map Distortion 423
Figure 9-10 Repeating a Texture 425
Figure 9-11 Comparing GL_REPEAT to GL_MIRRORED_REPEAT 426
Figure 9-12 Clamping a Texture 426
Figure 9-13 Repeating and Clamping a Texture 426
Figure 9-14 Multitexture Processing Pipeline 439

Figures xxiii
Figure 10-1 Region Occupied by a Pixel 458
Figure 10-2 Motion-Blurred Object 489
Figure 10-3 Jittered Viewing Volume for Depth-of-Field Effects 491
Figure 11-1 Contours That Require Tessellation 499
Figure 11-2 Winding Numbers for Sample Contours 507
Figure 11-3 How Winding Rules Define Interiors 508
Figure 12-1 Bézier Curve 529
Figure 12-2 Bézier Surface 536
Figure 12-3 Lit, Shaded Bézier Surface Drawn with a Mesh 539
Figure 12-4 NURBS Surface 544
Figure 12-5 Parametric Trimming Curves 558
Figure 12-6 Trimmed NURBS Surface 559
Figure 14-1 Antialiased Characters 606
Figure 14-2 Concave Polygon 610
Figure 14-3 Dirichlet Domains 618
Figure 14-4 Six Generations from the Game of Life 619
Figure 15-1 Comparison of Antialiased Points and
Textured Point Sprites 625
Figure 15-2 Assignment of Texture Coordinates Based on the
Setting Of GL_POINT_SPRITE_COORD_ORIGIN 625
Figure 15-3 Overview of the OpenGL Fixed-Function Pipeline 626
Figure 15-4 Vertex Processing Pipeline 628
Figure 15-5 Fragment PrOcessing Pipeline 629
Figure 15-6 Shader Creation Flowchart 631
Figure 15-7 GLSL Vertex Shader Input and Output Variables 656
Figure 15-8 Fragment Shader Built-In Variables 662
Figure A-1 Order of Operations 666
Figure E-1 Rendering with Polygonal Normals versus
True Normals 746
Figure E-2 Averaging Normal Vectors 750

xxiv Figures
Tables

Table 1-1 Command Suffixes and Argument Data Types 8


Table 2-1 Clearing Buffers 32
Table 2-2 Geometric Primitive Names and Meanings 43
Table 2-3 Valid Commands Between glBegin() and glEnd() 46
Table 2-4 Vertex Array Sizes (Values per Vertex) and Data Types 70
Table 2-5 Variables That Direct gllnterleavedArrays() 81
Table 2-6 Values for usage Parameter of glBufferData() 86
Table 2-7 Attribute Groups 92
Table 2-8 Client Attribute Groups 93
Table 4-1 Converting Color Values to Floating-Point Numbers 178
Table 4-2 How OpenGL Selects a COlor for the ith
Flat-Shaded Polygon 182
Table 5-1 Default Values for pname Parameter of glLight*() 195
Table 5-2 Default Values for pname Parameter of glLightModel*() 208
Table 5-3 Default Values fOr pname Parameter of glMaterial*() 212
Table 6-1 Source and Destination Blending Factors 234
Table 6-2 Blending Equation Mathematical Operations 236
Table 6-3 Values for Use with glHint() 249
Table 7-1 OpenGL FunctiOns That CannOt Be
Stored in Display Lists 288
Table 8-1 Pixel Formats for glReadPixels() Or glDrawPixels() 315
Table 8-2 Data Types fOr glReadPixels() or glDrawPixels() 316
Table 8-3 Valid Pixel Formats for Packed Data Types 318
Table 8-4 glPixelStore() Parameters 326
Table 8-5 glPixelTransfer*() Parameters 331

xxv
Table 8-6 glPixelMap*() Parameter Names and Values 333
Table 8-7 When Color Table Operations Occur in the
Imaging Pipeline 344
Table 8-8 Color Table Pixel Replacement 345
Table 8-9 How Convolution Filters Affect RGBA
Pixel Components 351
Table 9-1 Mipmapping Level Parameter Controls 402
Table 9-2 Mipmapping Level-of-Detail Parameter Controls 403
Table 9-3 Filtering Methods fOr Magnification and Minification 407
Table 9-4 Deriving Color Values from Different Texture Formats 417
Table 9-5 Replace, Modulate, and Decal Texture Functions 418
Table 9-6 Blend and Add Texture FunctiOns 419
Table 9-7 glTexParameter*() Parameters 427
Table 9-8 Texture Environment Parameters If target Is
GL_TEXTURE_ENV 445
Table 9-9 GL_COMBINE_RGB and GL_COMBINE_ALPHA
Functions 446
Table 9-10 Default Values fOr Some Texture EnvirOnment Modes 449
Table 10-1 Query Parameters for Per-Pixel Buffer Storage 460
Table 10-2 glAlphaFunc() Parameter Values 469
Table 10-3 Query Values for the Stencil Test 471
Table 10-4 Sixteen Logical Operations 481
Table 10-5 Sample Jittering Values 494
Table 12-1 Types of Control Points for glMap1*() 532
Table 13-1 glFeedbackBuffer() type Values 584
Table 13-2 Feedback Array Syntax 585
Table 14-11 OpenGL Error Codes of Layers 594
Eight Combinations
Table 605
Table 15-1 Basic Data Types in GLSL 639
Table 15-2 GLSL VectOr and Matrix Types 641
Table 15-3 Vector Component Accessor y 643
Table 15-4 GLSL Type Modifiers 645
Table 15-5 GLSL Operators and Their Precedence 648
Table 15-6 GLSL Flow-Control Statements 651
Table 15-7 GLSL Function Parameter Access Modifiers 652

xxvi Tables
Table 15-8 Fragment Shader Texture Sampler Types 653
Table 15-9 Vertex Shader Attribute Global Variables 657
Table 15-10 Vertex Shader Special Global Variables 660
Table 15-11 Vertex Shader Varying Global Variables 661
Table 15-12 Fragment Shader Varying Global Variables 663
Table 15-13 Fragment Shader Output Global Variables 663
Table B-1 State Variables for Current Values and AssOciated Data 676
Table B-2 Vertex-Array State Variables 677
Table B-3 Vertex Buffer Object State Variables 680
Table B-4 Transformation State Variables 681
Table B-5 Coloring State Variables 683
Table B-6 Lighting State Variables 684
Table B-7 Rasterization State Variables 686
Table B-8 "Multisampling" 688
Table B-9 Texturing State Variables 689
Table B-10 Pixel Operations 695
Table B-11 Framebuffer Control State Variables 697
Table B-12 Pixel State Variables 698
Table B-13 Evaluator State Variables 704
Table B-14 Hint State Variables 705
Table B-15 Implementation-Dependent State Variables 706
Table B-16 Implementation-Dependent Pixel-Depth
State Variables 710
Table B-17 Miscellaneous State Variables 710
Table I-1 Global Vertex Shader Attribute Variables 768
Table I-2 Special Vertex Shader Output Variables 769
Table I-3 Varying Vertex Shader Output Variables 769
Table I-4 Varying Fragment Shader Input Variables 770
Table I-5 Implementation Maximum Value Variables 770
Table I-6 Transformation Matrix Variables 772
Table I-7 Depth Range Variables 774
Table I-8 Point Size and Attenuation Variables 775
Table I-9 Lighting Material Variables 776
Table I-10 Light Source Variables 777

Tables xxvii
Table I-11 Light Model Variables 778
Table I-12 Cached Light Model Value Variables 778
Table I-13 Cached Light Product Value Variables 779
Table I-14 Fog Variables and Cached Values 780
Table I-15 Angle Conversion and Trigonometric Functions 780
Table I-16 Transcendental Functions 781
Table I-17 Basic Numerical Functions 782
Table I-18 Vector-Operation Functions 783
Table I-19 Matrix Functions 784
Table I-20 Vector CompOnent Operation Functions 785
Table I-21 Basic Texture Access Functions 786
Table I-22 Projective Texture Access Functions 787
Table I-23 Vertex Shader Texture Access Functions 788
Table I-24 Cube-Map Texture Access Functions 788
Table I-25 Shadow-Map Texture Access Functions 789
Table I-26 Fragment Derivative Functions 790
Table I-27 Random-Noise Generation Functions 790

xxviii Tables
Examples

Example 1-1 Chunk of OpenGL Code 6


Example 1-2 Simple OpenGL Program Using GLUT: hello.c 18
Example 1-3 Double-Buffered Program: double.c 24
Example 2-1 Reshape Callback Function 36
Example 2-2 Legal Uses Of glVertex*() 42
Example 2-3 Filled Polygon 42
Example 2-4 Other Constructs Between glBegin() and glEnd() 47
Example 2-5 Line Stipple Patterns: lines.c 54
Example 2-6 Polygon Stipple Patterns: polys.c 60
Example 2-7 Marking PolygOn Boundary Edges 63
Example 2-8 Surface Normals at Vertices 64
Example 2-9 Enabling and Loading Vertex Arrays: varray.c 70
Example 2-10 Using glArrayElement() to Define Colors and Vertices 72
Example 2-11 Using glDrawElements() to Dereference Several
Array Elements 74
Example 2-12 Compacting Several glDrawElements() Calls into One 75
Example 2-13 Two glDrawElements() Calls That Render Two
Line Strips 75
Example 2-14 Use Of glMultiDrawElements(): mvarray.c 76
Example 2-15 Effect Of gllnterleavedArrays(format, stride, pointer) 80
Example 2-16 Using Buffer Objects with Vertex Data 87
Example 2-17 Drawing an Icosahedron 96
Example 2-18 Generating Normal Vectors fOr a Surface 97
Example 2-19 Calculating the Normalized Cross Product of
Two Vectors 97
Example 2-20 Single Subdivision 99
Example 2-21 Recursive Subdivision 100
Example 2-22 Generalized Subdivision 101
Example 3-1 Transformed Cube: cube.c 110
Example 3-2 Using Modeling Transformations: model.c 125
Example 3-3 Calculating Field of View 144
Example 3-4 Pushing and Popping the Matrix 147
Example 3-5 Wireframe Sphere with Two Clipping Planes: clip.c 151
Example 3-6 Planetary System: planet.c 154
Example 3-7 RObot Arm: robot.c 157
Example 3-8 Reversing the Geometric Processing Pipeline:
unproject.c 161
Example 4-1 Drawing a SmoOth-Shaded Triangle: smooth.c 180
Example 5-1 Drawing a Lit Sphere: light.c 190
Example 5-2 Defining Colors and Position for a Light Source 195
Example 5-3 Second Light Source 201
Example 5-4 Stationary Light Source 202
Example 5-5 Independently Moving Light SOurce 203
Example 5-6 Moving a Light with MOdeling Transformations:
movelight.c 204
Example 5-7 Light SOurce That Moves with the Viewpoint 206
Example 5-8 Different Material Properties: material.c 215
Example 5-9 Using glColorMaterial(): colormat.c 218
Example 6-1 Demonstrating the Blend Equation Modes:
blendeqn.c 236
Example 6-2 Blending Example: alpha.c 241
Example 6-3 Three-Dimensional Blending: alpha3D.c 244
Example 6-4 Antialiased Lines: aargb.c 250
Example 6-5 Antialiasing in ColOr-Index Mode: aaindex.c 252
Example 6-6 Enabling Multisampling: multisamp.c 256
Example 6-7 Five Fogged Spheres in RGBA Mode: fog.c 262
Example 6-8 Fog in Color-Index Mode: fogindex.c 266
Example 6-9 Fog CoOrdinates: fogcoord.c 269
Example 6-10 Point Parameters: pointp.c 273
Example 6-11 Polygon Offset to Eliminate Visual Artifacts: polyoff.c 276

xxx Examples
Example 7-1 Creating a Display List: torus.c 279
Example 7-2 Using a Display List: list.c 285
Example 7-3 Hierarchical Display List 291
Example 7-4 Defining Multiple Display Lists 293
Example 7-5 Multiple Display Lists to Define a Stroked
Font: stroke.c 294
Example 7-6 Persistence of State Changes after Execution of a
Display List 298
Example 7-7 Restoring State Variables within a Display List 298
Example 7-8 The Display List May or May Not Affect drawLine() 299
Example 7-9 Display Lists for Mode Changes 300
Example 8-1 Drawing a Bitmapped Character: drawf.c 304
Example 8-2 Drawing a Complete Font: font.c 311
Example 8-3 Use of glDrawPixels(): image.c 320
Example 8-4 Drawing, Copying, and Zooming Pixel Data: image.c 335
Example 8-5 Pixel Replacement Using Color Tables: colortable.c 346
Example 8-6 Using TwO-Dimensional Convolution Filters:
convolution.c 351
Example 8-7 Exchanging Color Components Using the ColOr
Matrix: colormatrix.c 358
Example 8-8 Computing and Diagramming an Image's Histogram:
histogram.c 360
Example 8-9 Computing Minimum and Maximum Pixel Values:
minmax.c 363
Example 9-1 Texture-Mapped Checkerboard: checker.c 373
Example 9-2 Querying Texture Resources with a Texture Proxy 381
Example 9-3 Replacing a Texture Subimage: texsub.c 383
Example 9-4 Three-Dimensional Texturing: texture3d.c 388
Example 9-5 Mipmap Textures: mipmap.c 398
Example 9-6 Setting Base and Maximum Mipmap Levels 403
Example 9-7 Binding Texture Objects: texbind.c 411
Example 9-8 Automatic Texture-Coordinate Generation: texgen.c 430
Example 9-9 Generating Cube Map Texture Coordinates:
cubemap.c 438
Example 9-10 Initializing Texture Units for Multitexturing:
multitex.c 441

Examples xxxi
Example 9-11 Specifying Vertices for Multitexturing 442
Example 9-12 Reverting to Texture Unit 0 443
Example 9-13 Setting the Programmable Combiner Functions 446
Example 9-14 Setting the Combiner Function Sources 446
Example 9-15 Using an Alpha Value for RGB Combiner Operations 447
Example 9-16 Interpolation Combiner Function: combiner.c 448
Example 9-17 Rendering Scene with Viewpoint at Light Source:
shadowmap.c 454
Example 9-18 Calculating Texture Coordinates: shadowmap.c 455
Example 9-19 Rendering Scene Comparing r CoOrdinate:
shadowmap.c 456
Example 10-1 Using the Stencil Test: stencil.c 472
Example 10-2 Rendering Geometry with Occlusion Query 478
Example 10-3 Retrieving the Results of an Occlusion Query 479
Example 10-4 Routines for Jittering the Viewing Volume: accpersp.c 484
Example 10-5 Scene Antialiasing: accpersp.c 485
Example 10-6 Jittering with an Orthographic Projection: accanti.c 488
Example 10-7 Depth-of-Field Effect: dof.c 490
Example 11-1 Registering Tessellation Callbacks: tess.c 502
Example 11-2 Vertex and Combine Callbacks: tess.c 504
Example 11-3 Polygon Definition: tess.c 512
Example 11-4 Quadrics Objects: quadric.c 521
Example 12-1 Bézier Curve with Four Control Points: bezcurve.c 529
Example 12-2 Bézier Surface: bersurf.c 536
Example 12-3 Lit, Shaded Bézier Surface Using a Mesh: bezmesh.c 538
Example 12-4 Using Evaluators for Textures: texturesurf.c 540
Example 12-5 NURBS Surface: surface.c 544
Example 12-6 Registering NURBS Tessellation Callbacks: surfpoints.c 555
Example 12-7 The NURBS Tessellation Callbacks: surfpoints.c 556
Example 12-8 Trimming a NURBS Surface: trim.c 559
Example 13-1 Creating a Name Stack 565
Example 13-2 SelectiOn Example: select.c 567
Example 13-3 Picking Example: picksquare.c 572
Example 13-4 Creating Multiple Names 575
Example 13-5 Using Multiple Names 576

xxxii Examples
Example 13-6 Picking with Depth Values: pickdepth.c 577
Example 13-7 Feedback MOde: feedback.c 587
Example 14-1 Querying and Printing an Error 595
Example 14-2 Determining if an Extension Is Supported
(Prior to GLU 1.3) 598
Example 14-3 Locating an OpenGL Extension with
wglGetProcAddress() 599
Example 15-1 COnfiguring a Point Sprite for Texture Mapping:
sprite . c 626
Example 15-2 A Sample GLSL Vertex Shader 630
Example 15-3 Creating and Liking GLSL shaders 636
Example 15-4 Obtaining a Uniform Variable's Index and
Assigning Values 647
Example 15-5 Associating Texture Units with Sampler Variables 654
Example 15-6 Sampling a Texture Within a GLSL Shader 654
Example 15-7 Dependent Texture Reads in GLSL 655

Examples xxxiii
About This Guide

The OpenGL graphics system is a software interface to graphics hardware.


(The GL stands fOr Graphics Library.) It allows you to create interactive
programs that produce color images of moving three-dimensional objects.
With OpenGL, you can control cOmputer-graphics technology to produce
realistic pictures or ones that depart from reality in imaginative ways. This
guide explains how to program with the OpenGL graphics system to deliver
the visual effect you want.

What This Guide Contains


This guide has 15 chapters. The first five chapters present basic information
that you need to understand to be able to draw a properly colored and lit
three-dimensional object on the screen.

• Chapter 1, "Introduction to OpenGL," provides a glimpse into the


kinds of things OpenGL can do. It also presents a simple OpenGL pro-
gram and explains essential programming details you need to know for
subsequent chapters.

• Chapter 2, "State Management and Drawing Geometric Objects,"


explains how to create a three-dimensional geOmetric description of an
object that is eventually drawn on the screen.

• Chapter 3, "Viewing," describes how such three-dimensional models


are transformed before being drawn on a two-dimensional screen. You
can control these transfOrmations to show a particular view of a model.
• Chapter 4, "Color," describes how to specify the color and shading
method used to draw an object.

xxxv
• Chapter 5, "Lighting," explains how to control the lighting condi-
tions surrounding an object and how that object responds to light
(that is, how it reflects or absorbs light). Lighting is an important topic,
since objects usually don't look three-dimensional until they're lit.

The remaining chapters explain how to optimize or add sophisticated


features to your three-dimensional scene. You might choose not to take
advantage Of many of these features until you're more comfortable with
OpenGL. Particularly advanced topics are noted in the text where they
occur.

• Chapter 6, "Blending, Antialiasing, Fog, and Polygon Offset,"


describes techniques essential to creating a realistic scene—alpha
blending (to create transparent objects), antialiasing (to eliminate
jagged edges), atmospheric effects (to simulate fog or smog), and
polygon offset (to remove visual artifacts when highlighting the
edges of filled polygOns).

• Chapter 7, "Display Lists," discusses how to store a series of OpenGL


commands for execution at a later time. You'll want to use this feature
to increase the performance of your OpenGL program.

• Chapter 8, "Drawing Pixels, Bitmaps, Fonts, and Images," discusses


how to work with sets of two-dimensional data as bitmaps or images.
One typical use for bitmaps is describing characters in fonts.

• Chapter 9, "Texture Mapping," explains how to map one-, two-, and


three-dimensional images called textures onto three-dimensional
objects. Many marvelous effects can be achieved through texture
mapping.

• Chapter 10, "The Framebuffer," describes all the possible buffers that
can exist in an OpenGL implementation and how you can control
them. You can use the buffers fOr such effects as hidden-surface elimi-
nation, stenciling, masking, motion blur, and depth-of-field focusing.

• Chapter 11, "Tessellators and Quadrics," shows how to use the


tessellation and quadrics routines in the GLU (OpenGL Utility Library).

• Chapter 12, "Evaluators and NURBS," gives an introduction to


advanced techniques for efficient generation of curves or surfaces.
• Chapter 13, "Selection and Feedback," explains how you can use
OpenGL's selection mechanism to select an object on the screen.
Additionally, the chapter explains the feedback mechanism, which
allows you to collect the drawing information OpenGL produces,
rather than having it be used to draw on the screen.

xxxvi About This Guide


• Chapter 14, "Now That You Know,"describes how to use OpenGL in
several clever and unexpected ways to produce interesting results.
These techniques are drawn from years of experience with both
OpenGL and the technological precursor to OpenGL, the Silicon
Graphics IRIS Graphics Library.
• Chapter 15, Chapter 15, "OpenGL 2.0 and the OpenGL Shading
Language," discusses the changes that OpenGL 2.0 introduces. This
includes an intrOduction to the OpenGL Shading Language, alsO
commonly called the "GLSL," which allows you to take control of
portions of OpenGL's prOcessing for vertices and fragments. This
functionality can greatly enhance the image quality and
computational power of OpenGL.
In addition, there are several appendices that you will likely find useful:
• Appendix A, "Order of Operations," gives a technical overview of the
operations OpenGL performs, briefly describing them in the order in
which they occur as an application executes.
• Appendix B, "State Variables," lists the state variables that OpenGL
maintains and describes hOw tO Obtain their values.
• Appendix C, "OpenGL and Window Systems," briefly describes the
rOutines available in window-system-specific libraries, which are
extended to support OpenGL rendering. Window system interfaces
to the X Window System, Apple MacIntosh, IBM OS/2, and Microsoft
Windows are discussed here.
• Appendix D, "Basics of GLUT: The OpenGL Utility Toolkit," dis-
cusses the library that handles window system operations. GLUT is
portable and it makes code examples shorter and more comprehensible.
• Appendix E, "Calculating Normal Vectors," tells you how to calculate
normal vectors for different types of geometric objects.
• Appendix F, "Homogeneous Coordinates and Transformation
Matrices," explains some of the mathematics behind matrix
transformations.
• Appendix G, "Programming Tips," lists some programming tips based
on the intentions of the designers of OpenGL that you might find
useful.
• Appendix H, "OpenGL Invariance," describes when and where an
OpenGL implementation must generate the exact pixel values
described in the OpenGL specification.

About This Guide xxxvii


• Appendix I, "Built-In OpenGL Shading Language VAriables and
Functions," lists all of the built-in variables and functions available in
the OpenGL Shading Language.

Finally, an extensive Glossary defines the key terms used in this guide.

What's New in This Edition


The fifth edition of the OpenGL Programming Guide includes new and
updated material, covering both OpenGL Versions 1.5 and 2.0:

• Coverage of the following new core capabilities of OpenGL Version 1.5


has been added:
- Storage of vertex arrays in buffer objects
- Occlusion queries
- Addition of GL_LEQUAL and GL_GEQUAL texture comparison
functions for use with shadow-mapping
- Minor token updates

• Coverage of the following OpenGL 2.0 core features:


- Addition of the OpenGL Shading Language for programming
vertex and fragment shaders
- Output of different color values to multiple color buffers from
programmable shaders
- Relaxation of the power-of-two size requirement for texture maps
- Rendering of texture-mapped pOint sprites
- Separate stencil operations for front- and back- facing polygons
• Bug fixes

What You Should Know Before Reading This Guide


This guide assumes only that you know how tO program in the C language
and that you have some background in mathematics (geometry, trigonom-
etry, linear algebra, calculus, and differential geometry). Even if you have
little or no experience with computer graphics technology, you should be
able to follow most of the discussions in this book. Of course, computer

xxxviii About This Guide


graphics is a huge subject, so you may want to enrich your learning experi-
ence with supplemental reading:

• Computer Graphics: Principles and Practice by James D. Foley, Andries van


Dam, Steven K. Feiner, and John F. Hughes (Addison-Wesley, 1990)—
This bOok is an encyclopedic treatment of the subject of computer
graphics. It includes a wealth of information but is probably best read
after you have sOme experience with the subject.

• 3D Computer Graphics by Andrew S. Glassner (The Lyons Press, 1994)—


This book is a nontechnical, gentle intrOduction to computer graphics.
It focuses on the visual effects that can be achieved, rather than on the
techniques needed to achieve them.

Another great place for all sorts of general information is the Official
OpenGL Web Site. This Web site contains software, documentation, FAQs,
and news. It is always a good place to start any search for answers to your
OpenGL questions:
http://www.opengl.org/

Once you begin programming with OpenGL, you might want to obtain the
OpenGL Reference Manual by the OpenGL Architecture Review Board (also
published by Addison-Wesley), which is designed as a companion volume
to this guide. The Reference Manual provides a technical view of how OpenGL
operates on data that describes a geometric object or an image to produce
an image on the screen. It also contains full descriptions of each set of
related OpenGL commands—the parameters used by the commands, the
default values for those parameters, and what the commands accomplish.
Many OpenGL implementatiOns have this same material online, in the
form of manual pages or other help documents, which are probably more
up-to-date. There are also versions on the World Wide Web; consult the
previously mentioned Official OpenGL Web Site.

OpenGL is really a hardware-independent specification of a programming


interface, and you use a particular implementatiOn of it on a particular kind
of hardware. This guide explains how to program with any OpenGL imple-
mentation. However, since implementations may vary slightly—in perfor-
mance and in providing additional, optional features, for example—you
might want to investigate whether supplementary documentation is avail-
able for the particular implementation you're using. In addition, yOu might
have OpenGL-related utilities, toolkits, programming and debugging sup-
port, widgets, sample programs, and demos available to you with your
system.

About This Guide xxxix


How to Obtain the Sample Code
This guide contains many sample programs to illustrate the use of particular
OpenGL programming techniques. These programs make use of Mark
Kilgard's OpenGL Utility Toolkit (GLUT). GLUT is documented in OpenGL
Programming for the X Window System by Mark Kilgard (Addison-Wesley, 1996).
The section "OpenGL-Related Libraries" in Chapter 1 and Appendix D give
more information about using GLUT. If you have access to the Internet, you
can obtain the source code for bOth the sample programs and GLUT for free
via anonymous ftp (file-transfer protocol).

For the source code examples found in this book, please visit
http://www.opengl-redbook.com/code/

For Mark Kilgard's source code for GLUT (for Microsoft Windows or the
X Window System), check this Web page to find out what current version
of GLUT is available and where to download the source code from:
http://www.opengl.org/developers/documentation/glut/index.html

Many implementations of OpenGL might also include the cOde samples as


part of the system. This source code is probably the best source for your
implementation, because it might have been optimized for your system.
Read your machine-specific OpenGL documentatiOn to see where the code
samples can be found.

Nate Robins' OpenGL Tutors


Nate Robins has written a suite of tutorial programs that demonstrate basic
OpenGL programming concepts by allowing the user to modify the param-
eters of a function and interactively see their effects. Topics covered include
transformations, lighting, fog, and texturing. These highly recommended
tutOrials are portable and require the aforementioned GLUT. To get the
source code for these tutorials, see this Web site:

http://www.xmission.com/~nate/tutors.html

Errata
Undoubtedly this book has errors. An error list is maintained at the
following Web site:

xl About This Guide


http://www.opengl-redbook.com/errata/

If you find any bugs, you can use the pointer at this Web site to report them.

Style Conventions
These style conventions are used in this guide:

• Bold—Command and routine names and matrices


• Italics—Variables, arguments, parameter names, spatial dimensions,
matrix components, and first occurrences of key terms
• Regular—Enumerated types and defined constants

Code examples are set off from the text in a monospace font, and command
summaries are shaded with gray boxes.

In a command summary, braces are used to identify options among data


types. In the following example, glCommand has four possible suffixes:
s, i, f, and d, which stand for the data types GLshort, GLint, GLfloat, and
GLdouble. In the function protOtype for glCommand, TYPE is a wildcard
that represents the data type indicated by the suffix.

void glCommand{sifd} (TYPE xl, TYPE yl , TYPE x2, TYPE y2);

About This Guide xli


Exploring the Variety of Random
Documents with Different Content
“There is only one sweetheart in the world for me,” returned his
son proudly.
Major Jervis drew himself up with an air of formidable dignity, and
deliberately surveyed the speaker in sarcastic silence. Suddenly his
expression changed, and became charged with fury; he made a
frantic gesture, as if he would sweep both son and his sweetheart off
the face of the earth. Then he tore back a purdah, beyond which he
instantly disappeared—leaving it quivering behind him.
After waiting for a quarter of an hour, Mark went up to his own
room, which he began to pace from end to end. Presently he turned
down the lamp, flung open the window, looked out, and drew a long,
long breath. His temples throbbed like engines in his burning head,
every fibre of his being, every shred of his understanding, was now
engaged in an inner soul-struggle.
On one side was arrayed Honor Gordon, his good-hearted,
indulgent uncle, to whom he was sincerely attached—friends,
wealth, the life to which he was accustomed—a life of ease and
sunshine. On the other hand, there was this!—and he gravely
surveyed the dim, weird landscape, the starlit sky, stretching to the
mysterious horizon, and shuddered—his afflicted, forlorn father, who
would not be removed, and who could not be abandoned.
His father, who had cared for him in his childhood. Yes! it was his
turn now; and would he be behind Osman, the Mahomedan, who
had done from love, what he should do from duty?
“But his father might live years! Was he a brute to wish him dead?
Did he wish his father dead?” he asked himself fiercely, and
shuddered again. What was he coming to? Had two days in the
jungle turned him into a beast?
If he accepted what was plainly his duty, his uncle would cast him
off, and he must renounce Honor Gordon! Was this a home to bring
her to? common sense grimly demanded. And he would now be
penniless indeed! He was tortured with heart-wearing doubts and
temptations, as duty or inclination gained the upper hand. Two nights
ago he could not sleep for happiness; now, he could not rest for
misery! He resolved to walk down this raging fever, to quell this
mental turmoil, by sheer bodily fatigue. He made his way through the
silent house, where he found all the doors open, and nearly fell over
a goat and two kids who were dozing in the hall, otherwise the lower
regions were untenanted.
Suddenly he became aware of a great noise and brilliant light
outside; laughing, loud chattering, and the complacent humming of
dissipated tom-toms! The compound was illuminated by a large fire,
and half a dozen flaming torches, and crowded with a mob of
natives, who were enjoying, with intense appreciation, the solemn
gyrations, and shrill high-pitched songs of a couple of tawdry Nautch
girls. The surrounding go-downs were full of animated visitors. One
was evidently a drinking den, whilst in another were gamblers.
Standing in the shadow on the steps, unnoticed, Jervis surveyed
these orgies entirely at his leisure. He distinguished the khitmatghar,
though without a turban, his sleek black hair parted like a woman’s,
and falling over his shoulders. He was playing cards with three other
men; a bottle and a beaker stood by for general enjoyment. The
“khit” was absorbed in the game, his eyes seemed to protrude from
his head as they greedily followed the cards. Meanwhile Fuzzil was
solemnly superintending the Nautch, and applauding occasionally,
with fitful, tipsy condescension.
A few sharp words from the young sahib, who appeared among
them like a spirit, had an electrical effect. An awed and immediate
silence was followed by a simultaneous helter-skelter rush and
scurry.
“What is the meaning of this madness?” demanded the sahib
sternly of Fuzzil, who with drunken valour stood his ground, whilst
the Nautch girls, tom-toms, and spectators, melted away like so
many rabbits scuttling to their burrows.
“Madness!” repeated Fuzzil, with an air of outraged dignity; “it is a
grand tamasha for the marriage of my wife’s brother’s son. Does the
sahib not like Nautches, and cards, and drink, like other young
sahibs? Of a surety he does”—answering his own question with
insolent emphasis, and a little stagger. “As for madness; this house
is a poggle-khana” (madhouse).
“What do you mean, you rascal?” said Jervis, sharply.
“Of a truth, all the world know that. Is the fair-haired sahib, his son,
the last to learn that the old man is mad? Ask the doctor; ask
Cardozo Sahib. Sometimes for one year he never speaks.
Sometimes bobbery and trying to kill himself; but Osman took care of
him. Now, lo! Osman is dead; there will be an end soon. This house
will cease to be a poggle-khana, and all the worthy ‘nouker log’
(servants) can return to their own country.”
“You, for one, can return to-morrow,” responded the sahib, in
surprisingly fluent Hindostani.
“You are not the master here,” blustered Fuzzil, in amazement. “I
taking no orders.”
“You will find that I am; and if you ever again come into my
presence, with your shoes on your feet, I will thrash you within an
inch of your life. Send away all these people; tell them the tamasha
is over for to-night; put out the lights, and get to your go-down, and
sleep yourself sober.”
Fuzzil stared, swallowed, gasped. The young man’s resolute air
and stern eye were altogether too much for him, and he obediently
slunk off, without further dispute.
Major Jervis did not appear the next morning, and his son
mounted his pony and went for a long ride. Where he went he but
vaguely remembered; his thoughts were far too preoccupied to note
his surroundings. There was no doubt that his father’s mind was
affected; no doubt this was attributable to the fall over the khud, and
injury to his head. The vital question remained to be decided, was
he, Mark Jervis, to sacrifice his youth to filial duty?—one would soon
grow old in the Yellow Kothi—to renounce friends, fortune,
sweetheart, to lead a semi-savage existence, entirely cut off from
what is called Life.
But, on the other hand, if he set his pony’s head for Shirani, and
returned to Honor, to all the delights of the world, would not the
recollection of the miserable father he had abandoned to strangers
poison every pleasure, and force itself into every joy?
“But to live there”—and he drew rein and gazed down upon the
square house, standing out distinctly against a blue, purplish
background—“will be,” he exclaimed aloud, “a living death. Like a
vain young fool, I wanted a chance to do something—some special
task, some heroic deed, that would set me apart from other men;
but, God knows, I never thought of this!”
It was late in the afternoon when he rode up to the verandah, and
was amazed to meet a coolie leading away a steaming-hot hill pony
—a hired animal—and more surprised still to discover a visitor
comfortably established in a long chair, with his fat legs elevated
above his head, enjoying a peg and a cheroot. Evidently there was
no occasion to ask him to make himself at home! The stranger
slowly put down his feet and stood on them, when he first caught
sight of Mark.
After staring hard for a few seconds, he said, with an air of great
affability, “I am Fernandez Cardozo, and you are Major Jervis’s son
—my cousin.”
“I am Major Jervis’s son,” assented the young man, stiffly; and he,
in turn, critically surveyed his father’s heir. He was low-sized, fleshy,
and swarthy, about forty years of age; he had a closely cropped
bullet head, sprinkled with grey hairs, a round good-natured face, a
pair of merry black eyes, and a large mouthful of flashing white teeth.
An Eurasian, and possibly not a bad sort of fellow, was Mark’s
verdict.
The other was thinking, “What a fine young man! Quite tip-top.
How strange it seemed that he should be the son of the poor, crazy
old major inside.” And his eyes travelled over his smart country-bred
pony, his English saddlery, his well-cut boots and clothes.
“Yes—you are his son,” he said at last, “but I am his heir. We are,
son and heir,” and he laughed—an oily laugh.
“You are heir of course to Mrs. Cardozo—I mean Mrs. Jervis’s
fortune. Won’t you sit down?”
“You have not been long here, have you?” now reseating himself.
“No; only two or three days.”
“And how,” with a jerk of his thumb in the direction of the major’s
apartments, “do you find the old man?”
“Well, I never knew until now, that his mind was rather—affected.
He has not written to me for years, and I only got his address with
difficulty.”
“Yes, he prefers to lie low—as Mr. Jones. But ‘rather affected,’ is
putting it mildly.”
“Do you think so?” considering Cardozo with a pair of hostile eyes.
“You will think so too before long. Now don’t be vexed with me, my
dear boy. No one is ever angry with Ferdy Cardozo, they know I am
a good fellow, and that I mean well. Shall we go inside and see if
there is anything to be had to eat?”
“Certainly, I ought to have thought of it before.”
“Oh, please don’t apologize, I’m quite at home. Fuzzil, you fat lazy
swine,” to the now obsequious bearer, “get me something to eat,
none of your dogs’ food—such as brain cutlets or Irish stew, and
bring up some of my wine. It’s very hot in here, awfully frousty,”
opening a window. “The major hates me like poison, and when he
hears I’m in the house he won’t come out, he will go to ground like a
snake, but I shall be off to-morrow.”
“Yes?” interrogatively.
“Are you in the army?” continued Fernandez with half-closed eyes.
“No, I am not in the regular army; I’m in the yeomanry.”
“No profession then?” raising his arched brows in rather
supercilious surprise.
“No, not any.” His profession as heir to his Uncle Dan, would soon
be a thing of the past.
Mr. Cardozo’s surmise was perfectly correct. Major Jervis did not
appear, he merely sent his salaams and dined in his own
apartments, leaving his son and his heir to consume that meal tête-
à-tête. It was a great improvement on the usual menu. Evidently
Fuzzil had resources that he drew upon on worthy occasions.
“It’s a fine moonlight night,” remarked Fernandez. “Let us go and
smoke in front of the house, it’s better than being indoors, and I like
to make the most of the hill air when I’m up, and we are out of the
way of eavesdroppers.”
In a few moments they were sitting on the low wall in front of the
Pela Kothi.
“Osman was a desperate loss,” began Fernandez as he struck a
fuzee—“a desperate loss.”
“So I gather from what I hear,” assented his companion.
“That’s partly what brought me up. I have business round here, of
course, though. I live in Calcutta. I like to keep my eye on the
property, and I look after the major and manage his affairs as well as
I can—I feel it my duty.” And he began to smoke.
Was here yet another man, of no kin to Major Jervis, who was to
put his own flesh and blood to shame?
“I wish you would tell me something about my father—the last
seven years are a sealed page to me.”
“Well, first of all he got a fall on his head pig-sticking, and that
made him rather foggy for a bit, he saw everything double. Then of
course the tonga business was a finisher. Osman brought him here,
and at times he was perfectly well, as sane as you or I, and
interested in the garden, and the news, and all that, but he got worse
by degrees, fits of silence and depression, never opening his lips for
maybe a whole year—melancholy, suicidal mania—tried to hang
himself with a stirrup leather, you understand,” lowering his voice
expressively.
“I—I—understand,” acquiesced the other, almost in a whisper.
“He must have some one always with him, more or less. Some
one whom he likes, and who has influence and a strong will, such as
Osman—he was invaluable. I don’t know how we are to find a
substitute for him,” continued Fernandez thoughtfully, as he crossed
his legs, leant his elbow on his knees, and puffed meditatively.
“The servants he has about him now must be shunted,” said Mark,
emphatically. “I never saw such a pack! They had a feast and tom-
toms last night. They are lazy, insolent, useless blackguards!”
“Not a doubt of it,” agreed Fernandez, cheerfully. “And Fuzzil will
retire a rich man, keep a gharry, and send his sons to college. They
come here fairly decent servants—but the desperately dull life, no
bazaar, no other ‘nauker log’ to bukh with, is a want no wages can
repay. Then the household has no head, no regular hours, and so
they all do as they please and go to the bad. I don’t know what is to
be done now—your father won’t allow a stranger near him. The
question is, Who is to replace Osman? Tell me that”—and he flung
out his hand with a dramatic gesture.
“I will replace Osman,” was the totally unexpected reply.
“You!” cried Cardozo, gazing at the speaker with round-eyed
incredulity. The young man’s face was pallid, his lips set hard. “You
don’t know what you are saying”—and he took his cheroot out of his
mouth and continued to stare at his companion exhaustively. “You
are accustomed to the big world of London; you have seen and done
what I have only read about—for I have never been home; you are
accustomed to a whirl of society, to novelty, excitement, luxuries, and
immense wealth. You to live here? Upon my word, excuse me, my
dear fellow, the very idea makes me laugh. Even I, born and bred in
the country, would go mad in a very short time. I could not stand the
life for more than a week—a month would kill me!”
“I am not so easily killed as you imagine. I am tougher than you
think,” rejoined Jervis.
“But you do not know what you would have to endure”—throwing
out his arms excitedly. “The solitude, the silence, day after day,
exactly the same—breakfast, tiffin, dinner, bed—nothing to do,
nothing to hope for, no one to see, except the hill-folk or a
missionary. I tell you that you would do one of two things—either cut
your throat, or take to drink.”
“Your eloquence is a loss to the bar, Cardozo.”
“So I have often been told”—with a hasty movement of his hand;
“but it is not a question now of my eloquence, but of your future. Do
you genuinely mean what you say? Do you intend to live here as
your father’s sole companion?”
“I do,” replied the young man, answering his look with eyes full of
indomitable fire.
Mr. Cardozo puffed away in solemn silence for some time, but
there was a certain brisk cheerfulness in his air as he suddenly
remarked—
“The major is going downhill rapidly, poor old chap! His health is
bad; I see a great change in him. His mind will never recover. Of
course that is not to be expected; you know that it runs in the family
—it is hereditary.”
“What runs in the family? What is hereditary?” demanded the
other, with a look full of pain and excitement.
“Insanity. He told Mércèdes, who told me, that his brother jumped
overboard at sea, going home in charge of two keepers; and his
father died in Richmond lunatic asylum.”
“Is—this—true?” Mark brought out the words in three quick gasps.
“You don’t mean to say that you never knew? Oh, I’m awfully
vexed! I entirely forgot you were his son. You look so different, upon
my word, as you stand there, that I cannot realize that he is anything
to you.”
Jervis struggled to articulate again, but signally failed. With a
shaking hand he tossed his cigarette over the parapet, and then
walked away up the steps, and was instantly merged in the gloom of
the entrance.
“Hereditary.” The word seemed written before him in letters of
flame—“hereditary.”
CHAPTER XXXIV.
THE INITIALS “H. G.”

When it became known at the club, and subsequently all over


Shirani, that young Jervis had suddenly disappeared the night of the
bachelors’ ball, great was the sensation.
No, no, there was no suspicion of foul play; there were his
servants to be questioned. Jan Mahomed, his respectable, grey-
bearded attendant, had declared that the night his master had come
home, he had got straight from his evening clothes into his riding
things, and had taken the grey pony and galloped away into the
darkness. Whither? How could he say? holding out a pair of lean,
empty hands, with a gesture of pitiable ignorance. He made no
mention of the letter; for this prudent retainer had lived with bachelor
sahibs before.
Mrs. Langrishe and Lalla were for once agreed. They were
convinced that Mr. Jervis had gone further than he had intended with
Miss Gordon, and to repair the error, had subsequently put miles
between them—was probably by this time on blue water. But they
did not venture to air this opinion openly; it was reserved for “ladies
only.” Major Langrishe had laughed it to scorn; and as for Toby Joy,
he and Lalla almost had a quarrel on the subject—their very first
quarrel.
“Jervis to propose to a girl, and then run away!” he cried
indignantly. “About the last fellow in Shirani to do such a mean trick.
Jervis is a gentleman to the soles of his boots, and a real good chap,
worth fifty of Waring.”
“Yes, so we all learn now, when it’s rather late in the day,” retorted
Lalla, sarcastically.
“You mean about the money! But I mean in other ways. He took it
awfully well the day I nearly smashed up him and Mrs. Sladen; you
saw that yourself! He certainly lay low with regard to the fact of his
being wealthy. He is the least ostentatious fellow I ever met, and as
straight as a die, a complete contrast to the great Clarence, who has
been playing the deuce up at Simla, by all accounts, and making
ducks and drakes of any quantity of coin.”
“Well, at least, we know where he is, and what he is doing!”
retorted Lalla. “But no one can say the same of the cousin. Where is
he, and what is he doing? He was always very close about himself,
and I consider the whole thing most suspicious. Supposing a man
proposed for me.”
“Yes, supposing a man proposed for you,” repeated Toby, edging
nearer to the lady.
“And I accepted him. Now, don’t look so utterly idiotic, for mercy’s
sake! And he simply took to his heels and ran away, would I not think
that peculiar conduct? I must say Honor Gordon takes it better than I
should, under the circumstances.”
“How soon are you going to get rid of that fellow Gloster?” inquired
Toby irrelevantly.
Sir Gloster was bringing a tedious convalescence to an end, and
taking daily airings in Mrs. Langrishe’s rickshaw; and people, who
were disappointed of a wedding in one quarter, were eagerly
expecting to hear of one in another.
“I don’t know,” coquettishly. “Perhaps I may never get rid of him!”
“You know you only say that to make me wretched. You don’t
really mean it, do you?” pleaded Toby, with such a look of misery on
his usually merry face, that Miss Paske burst into an uncontrollable
scream of laughter, and said—
“Toby, how can you be so exquisitely silly?”
The few days Mark Jervis had written of had grown into ten, and
he had almost slipped out of people’s minds, save when a string of
ponies being led along by their syces, and wearing smart jhools, with
the initials M. J., brought him momentarily to remembrance.
And now Captain Waring suddenly reappeared. He came direct
from Simla, back to despised Shirani, and in anything but his usual
cheery spirits. How he had cursed his coolies and ponies on the way
up! What a life the débonnaire Clarence had led his miserable
servants, as if the poor wretches were responsible for his
discomfiture, his bad luck, his ruin, for it had come to that—and it
was a desperate man, who spurred his distressed country-bred pony
up the last two miles of the dusty cart road.
He was surprised to find Haddon Hall tenantless; but when the
bearer explained how “a Pahari had brought a note, and his master
had gone ‘ek dum,’” i.e. on the spot, he nodded his head
sagaciously, and appeared to understand all about it. What he could
not comprehend was Mark’s prolonged absence. “Ten days gone,”
Mahomed said; two days, were he in Mark’s shoes, would be amply
sufficient time to devote to his eccentric parent.
Clarence was in a bad plight, and almost at the end of his
resources, which had hitherto been as unfailing as the widow’s
cruse. He had gambled recklessly, with stronger men than himself;
he had thrown good money after bad, in the usual wild attempt to
recover both. His I.O.U.’s and debts of honour and lottery accounts
came to a large total; he would be posted in a few days if he did not
pay up. As to other debts, they were legion—shop bills, club and
mess accounts, wages—they poured down on him in all directions,
ever since that little brute Binks had peached at Simla and spoiled
everything. Miss Potter had bitterly upbraided him, and subsequently
snubbed him unmistakably; the men at the club looked coldly on him;
the high players in the card-room had seemed stiff and curiously
averse to his “cutting in.” People suddenly stopped talking when he
joined them; yes, he was at a crisis in his life, a crisis brought on by
his own insane recklessness, and raging passion for play. He had
come expressly to Shirani to get Mark to assist him; if he failed him,
if he refused to stretch out a hand, and drag him back from the gulf
of insolvency and disgrace, on the brink of which he tottered, down
he must go, and be swept away and swallowed up, among the
thousands and thousands who have similarly gone under!
After a bath, a meal, and a smoke, Captain Waring felt better, and
set to work to think things out steadily, and to pull himself together.
He had sold his own ponies and guns, their price was a sop to his
most urgent creditors. He would now proceed to dispose of Mark’s
battery. Yes, they were fine weapons—he would put them and the
ponies on the notice board at the club at once—the price of them
would pay their passages and immediate expenses; Mark’s £500
would cover all debts; he had not a rupee left at the agent’s, and he
would make Mark come home at once. It was true that their year’s
leave had yet four months to run, this was the middle of June, but he
had made India too hot to hold him for the second time. The sooner
he set about winding up affairs the better, and he rose on the spur of
the moment, resolved to cast an eye over his cousin’s saleable
effects.
He went into Jervis’s room, the smaller and worst of the
bedrooms, and very plainly furnished. There was a bare camp bed, a
rickety chest of drawers, a washed-out dhurrie on the floor, also a
long row of boots; a couple of saddles on a stand, and a first-rate
battery of guns—“a double-barrel central-fire breach-loader, by
Purdy, that will fetch 250 rupees; a 500 express, by Lancaster, 400
rupees; 8-bore rifle, 600 rupees; rook rifle, 100—say, 1300 rupees,”
was his mental calculation.
When he had examined these, a parcel on the chest of drawers
arrested his attention; there was also a programme. He took it up
and looked it over; he was extremely inquisitive in such small
matters. The card was full, and opposite three dances were scribbled
the initials “H. G.”
“Humph!” he muttered aloud. “So that is going on!” And as his
gaze travelled to a ladylike parcel in silver paper—“What the dickens
is this?”
He promptly unrolled it, and beheld a most superior white ostrich
feather-fan, with the monogram H. G. on the handle. Captain Waring
unfurled it, fanned himself slowly, folded it up once more, and said—
“A feather shows how the wind blows, Mark my boy! Well, I’ll go
over to the club and hear what is going on, look up the mail
steamers, and offer your ponies and rifles, my fine fellow. You will
have to come home with me sooner than you think, and I’ll get great
kudos from the uncle for carrying you off from a dangerous
entanglement—in other words, from H. G.”
And Captain Waring sauntered out to the stables in a surprisingly
good humour.
“I’m sorry he has got the grey with him!” he muttered to himself;
“the grey is a long way the best of the three! The grey is worth five
hundred rupees.”
Strange to say, the grey, carrying his owner, arrived home that
same day about four o’clock, much to the bearer’s joy. His master
spent the afternoon packing, making arrangements, giving orders,
writing letters. He announced that he was going away again the next
morning, and Jan Mahomed and his son were to follow with all his
baggage. In future he would live with his father near Ramghur.
Jan Mahomed received this astounding piece of information in the
usual native fashion, merely with a stolid face and a long salaam.
Yes, his choice was made, the die cast, to Major Jervis’s intense
satisfaction, and to Fernandez Cardozo’s intense amazement. The
former had been ill, and had detained his son from an earlier return
to Haddon Hall to wind up his affairs, and open his letters, the latter
including one from his uncle, which had been lying on the writing-
table for a whole week. It said—
“Dear Mark,
“Yours received, and I answer it within the hour. I note all
you say about the young lady, and I don’t like the idea at all.
My boy, you know I have never refused you anything, but I
must say no to this. I have only your welfare at heart. I cannot
allow you to throw yourself away on an ordinary Indian spin.
You are right to tell me all about it; and, as you have not yet
proposed for her, don’t. You must marry some pretty, well-
born girl, who has never been through the Suez Canal. Come
home immediately; these idle days in a hill station have had a
bad effect on your steady brain. Come home as soon as ever
you can. Your father has evidently become naturalized; he
does not want you—I do. As for the girl, you might give her a
pony, or a diamond brooch—anything—everything, but
yourself.
“Your affectionate uncle,
“D. Pollitt.”
As Mark looked up from this letter he met the scrutinizing black
eyes of Jan Mahomed which were fixed upon his face.
“This sahib has been ill,” he said, severely. “Jungle fever getting?”
“No, Jan, I am all right. This is the day the English dâk goes out,
and I want you to take a letter to the post for me, it will be ready in
twenty minutes, and send word to the Captain Sahib, that I have
come back.”
Then he drew his writing-case towards him and began a letter to
his uncle. Evidently this letter was not an easy composition, in fact,
he had already written it several times at Ramghur, and then
instantly destroyed it, but it must be written somehow, and now. The
post left within the hour. At length he wrote—
“Dear Uncle Dan,
“Since I last wrote to you I have been with my father; he
sent for me suddenly, and I went off the same hour, as his
note said that he was very ill. I found him living forty miles
from this, in an isolated house, part of the Cardozo property,
and under the name of Mr. Jones—a name he has adopted
for the last seven years. I never would have recognized him,
he is so broken down, and quite an infirm old man. This is the
effect of the accident that killed his wife. But this is not the
worst. His mind is deranged, which accounts for his strange
silence and many other things. At times, such as at the
present moment, he is perfectly clear and collected, but at
others he suffers from depression and melancholia, and sits
silent for days and weeks. He is alive to his own infirmity, and
that is why he has chosen this life of seclusion. Until recently
he had one of his former sowars living with him, an invaluable
companion; and now that he is dead—an irreparable loss—
Uncle Dan, I am going to tell you something that will be a
shock, as well as displeasing, to you—I am about to take the
place of this faithful servant, and endeavour to be his
substitute. My father is a forlorn and stricken man; he has no
one but me to look to—he does look to me, and I will not fail
him. He is not wealthy—the begum’s riches, Mrs. Jervis’s
fortune (minus a certain annuity), is strictly reserved for her
next of kin, Fernandez Cardozo. He is not a bad sort, and has
been looking after my father and his affairs—in short, fulfilling
my duty; but I shall relieve him of all this, and remain out here
as long as my father lives. I am afraid that at first you will think
I am treating you badly and ungratefully; but this I know, that,
were you in my place, you would do the same yourself. Of
course I forfeit all claim on you by such a step as I am about
to take, and it is a step which has cost a struggle. I am going
to lead a different life to that to which I have been brought up.
I shall be isolated and out of the world, for I can never leave
my father even for a day. Once I take up my post, I shall stick
to it.
“I have found your letter here awaiting me—your letter
about Miss Gordon. Of course that is all at an end now. As for
her not being good enough for me, it is the other way about.
She is the only girl I ever cared for. I shall never marry now,
but will adopt the profession I chose as a child, and live and
die a bachelor. I wonder that I can joke, for I need hardly tell
you that I am not in a merry mood. I feel as if everything had
gone from me at one blow, and I am left face to face with a
new life and an inflexible duty. Whatever you may think of me,
Uncle Dan, my feelings towards you will never change; I shall
always think of you with affection and gratitude.
“Clarence came back to-day from Simla. I have not seen
him as yet. I only arrived a couple of hours ago, to collect my
kit, dismiss my servants, and say good-bye to Miss Gordon. If
you had ever seen her, and spoken to her, you would not
have written that suggestion about a pony or a brooch. I go
back to Ramghur to-morrow. My lot is not likely to be a very
bright one; do not make it harder, Uncle Dan, by being
implacable. I know that at first you will feel certain that you
never can forgive me, but you will by-and-by. Write to me and
send me papers to care of Mr. Jones, Ramghur, viâ Shirani.
You may as well take my name off the clubs, sell the horses
down at the farm, and tell Windover not to put the drag in
hand.
“Your affectionate nephew,
“M. Jervis.”
This letter, hastily written, with numerous erasures, the writer did
not trust himself to read over, but thrust it into an envelope,
addressed and despatched it on the spot, as if he almost feared that
he might be tempted to recall it, and change his mind.
CHAPTER XXXV.
“OSMAN’S SUBSTITUTE.”

“Hullo, Mark!” cried his travelling companion, with cordial,


outstretched hands. “So you are back? I only arrived this morning—
came straight through from Simla. What’s the matter, eh? You seem
rather choop.”
“Oh, I’ll tell you presently. Let us have your news first.”
“On the principle of keeping the best for the last, eh? for mine is
bad. Well, as for news”—removing his cap and sitting down—“I
suppose you have heard that our secret is now public property. That
blatant ass, little Binks, had it all over Simla. What business had he
to thrust himself into our private affairs?”
“It was never what you would call private,” rejoined Mark, who was
leaning against the end of a real old-fashioned hill sofa, with his
hands in his pockets. “I am only surprised that it never came out
before.”
“Yes, now that you mention it, so am I. We had a good many
fellow-passengers, but they none of them came up this way; they
were mostly for Burmah, or Madras, or globe-trotters. I could not give
the name of one of them if I got a thousand pounds. There is nothing
one forgets so soon as a fellow-passenger. Of course you have been
to see your governor?”
“Yes. I’ve been away nearly a fortnight.”
“And how did you find him?”
“I am sorry to say very broken down—ill and desolate.”
“But with sacks of gold mohurs all round the rooms, and
chandeliers of real diamonds. I hope you have some in your
pockets?” said Waring, gaily.
“No. He is a comparatively poor man; at least he has just enough
to live upon—an annuity. The bulk of his fortune goes, as it ought to
go, to the Cardozo family.”
“Well, one fortune is enough for you,” rejoined Clarence. “I came
up post haste. I rode your bay pony in the last ten miles, and, by
Jove! I thought I had killed him. It was frightfully hot, and I put on the
pace. I gave him a whole bottle of whisky when I got in.”
“A whole bottle! Well, I hope you will give him some soda-water to-
morrow morning. What a head the poor brute will have!” he added,
with a wintry smile. “But what was the reason for such desperate
riding? Has Miss Potter come back?”
“Miss Potter be hanged!” was the unchivalrous reply. “I came up
as hard as I could lay leg to the ground to get you to help me out of
an awful hole—an infernal money muddle.”
“To help you again! I thought that five hundred pounds would put
you straight.”
“Good heavens, man! it’s not hundreds, but thousands that would
do that!” cried the prodigal.
Jervis ceased to lounge, and now assumed a more
uncompromising attitude.
“Explain,” he said laconically.
“Yes; I’ve been going it, my boy,” admitted Waring, with a reckless
laugh. “Old faces, old places, were too much for me, and I dropped a
pot of money. There was a fellow from New Orleans, a long-headed
chap, a born gambler, and a wild-looking Hungarian count; they
carried too many guns for me. One night we had three thousand
pounds on the turn of a card. Ah, that is living! There is excitement, if
you like! Better twenty hours of Simla than a cycle of Shirani.”
“Nevertheless you have returned to Shirani?”
“Yes, only because I am cleared out,” was the absolutely
unabashed reply.
“I’m sorry to hear it, Clarence; but it is not in my power to help you
beyond the five hundred pounds that will pay our expenses here.
The table was papered with bills when I came back.”
“Oh, those!” with a gesture of scorn, “rubbishy little shoeing
accounts, stable accounts, and rent. I don’t mind them, it’s others.
I’m really in an awful hat this time and no mistake, and you must
assist me.”
“I cannot.”
“I tell you again that you must!” cried Waring, throwing himself
back in his chair, with an energy that made that venerable piece of
furniture creak most piteously.
“There is no ‘must’ in the matter,” retorted the other steadily, “and if
I were in the humour for joking—which I am not—the comic side of
the situation would make me laugh. You were sent out by Uncle Dan
as my mentor, to keep me straight, to give me the benefit of your
experience and to show me round. Wasn’t that the arrangement?
But, by Jove,” suddenly springing up and beginning to pace the
room, “I have been lugging you out of scrapes ever since we landed
in the country!”
“It is a true bill, oh wise, cool-headed, and most virtuous Saint
Mark! This, I most solemnly swear to you, is my last and worst
scrape. Get me a cheque for a certain sum, wire to the uncle to
lodge it at the agents, and I’ll be a truly reformed character, and
never touch another card, for ever and ever, amen.”
“And afterwards?”
“Afterwards we will reward the old man, and rejoice his heart, by
packing up and going home by the next steamer. He would give
many thousand pounds to get you back again—you are the apple of
his little pig’s eye. This country does not agree with me—I don’t
mean physically, but morally. It’s an enervating, corrupting, beguiling
land. We will sell off your guns and ponies, dear boy. I’ve put them
up at the club—I hope I have not broken the wind of that dark bay—
we will go down in the mail tonga this day week, en route for
Bombay. There are temptations for you in this Indian Empire too.
The sooner you say good-bye to H. G. the better. Now, there is my
programme for you—my new leaf. What have you to say to it?”
Brisk and confident as his speech had been, there was a certain
unmistakable lameness in its conclusion. Waring had secretly winced
under his listener’s eyes—his listener, who sat motionless,
contemplating him with an expression of cool contempt.
“The first thing I have to say is, that my guns and the ponies are
not for sale, or only the chestnut with the white legs.”
“Great Scot! You don’t mean to tell me that you intend to take
three ponies home! And what do you want with an express rifle and
an elephant gun in England?”
“I may require them out here. I am not going back to England.”
Captain Waring sat suddenly erect.
“Of course this is all humbug and rot!” he exclaimed vehemently.
“No. I am quite in earnest. I intend to remain with my father; it is
the right thing for me to do. He is alone in the world; his mind is
weak.”
“So is his son’s, I should say,” burst out Waring, throwing his
cigarette into the verandah. “Get him a keeper—two keepers, by all
means; a baby house, a barrel organ, every comfort, but don’t you
be a lunatic. Come home with me. Think of Uncle Dan!”
“Yes, I know very well that Uncle Dan will cast me off; he told me
he would, if I remained out here with my father.”
“Cast you off!” almost screamed the other. “Do you mean to tell me
that you will never see the colour of his money again?”
“Never.”
“I believe that Miss Gordon has something to say to this scheme,
as well as this mad Quixotic idea about your father,” cried Clarence,
crimson with excitement. “As for the girl, you must let her slide, we
have all been through that; but, for God’s sake, hang on to the uncle,
and the coin. You are the only mortal for whom he will open his
purse-strings.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like