100% found this document useful (2 votes)
4 views85 pages

Where can buy Beginning Direct3D Game Programming Prima Tech s Game Development 1st Edition Wolfgang Engel ebook with cheap price

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Beginning Direct3D Game Programming Prima Tech s


Game Development 1st Edition Wolfgang Engel

_____ Click the link below to download _____


https://ebookultra.com/download/beginning-
direct3d-game-programming-prima-tech-s-game-
development-1st-edition-wolfgang-engel/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Beginning Java Game Programming 2nd Edition Jonathan S.


Harbour

https://ebookultra.com/download/beginning-java-game-programming-2nd-
edition-jonathan-s-harbour/

Beginning Game Level Design Premier Press Game Development


1st Edition John Harold Feil

https://ebookultra.com/download/beginning-game-level-design-premier-
press-game-development-1st-edition-john-harold-feil/

Beginning iOS Game Development 1st Edition Patrick Alessi

https://ebookultra.com/download/beginning-ios-game-development-1st-
edition-patrick-alessi/

Beginning C Game Programming 2nd ed. Edition John Horton

https://ebookultra.com/download/beginning-c-game-programming-2nd-ed-
edition-john-horton/
Beginning OpenGL Game Programming Second Edition Luke
(Luke Benstead) Benstead

https://ebookultra.com/download/beginning-opengl-game-programming-
second-edition-luke-luke-benstead-benstead/

Fable Prima Official Game Guide Casey Loe

https://ebookultra.com/download/fable-prima-official-game-guide-casey-
loe/

Beginning Android C Game Development 1st Edition Bruce


Sutherland (Auth.)

https://ebookultra.com/download/beginning-android-c-game-
development-1st-edition-bruce-sutherland-auth/

Special Effects Game Programming with DirectX The Premier


Press Game Development Series 1st Edition Mason Mccuskey

https://ebookultra.com/download/special-effects-game-programming-with-
directx-the-premier-press-game-development-series-1st-edition-mason-
mccuskey/

The Orange Box Prima Official Game Guide 1st Edition David
S. J. Hodgson

https://ebookultra.com/download/the-orange-box-prima-official-game-
guide-1st-edition-david-s-j-hodgson/
Beginning Direct3D Game Programming Prima Tech s
Game Development 1st Edition Wolfgang Engel Digital
Instant Download
Author(s): Wolfgang Engel, Amir Geva
ISBN(s): 9781417541904, 1417541903
Edition: 1
File Details: PDF, 7.01 MB
Year: 2001
Language: english
Beginning
Direct3D®
Game
Programming
Check the Web for Updates:
To check for updates or corrections relevant to this book and/or CD-ROM visit our updates page on the
Web at http://www.prima-tech.com/updates.

Send Us Your Comments:


To comment on this book or any other PRIMA TECH title, visit our reader response page on the Web at
http://www.prima-tech.com/comments.

How to Order:
For information on quantity discounts, contact the publisher: Prima Publishing, P.O. Box 1260BK, Rocklin,
CA 95677-1260; (916) 787-7000. On your letterhead, include information concerning the intended use
of the books and the number of books you want to purchase.
Beginning
Direct3D®
Game
Programming

Wolfgang F. Engel
Amir Geva
Series Editor
André LaMothe
CEO Xtreme Games LLC
©2001 by Prima Publishing. All rights reserved. No part of this book may be reproduced or transmitted in any form or
by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval sys-
tem without written permission from Prima Publishing, except for the inclusion of brief quotations in a review.
A Division of Prima Publishing
Prima Publishing and colophon are registered trademarks of Prima Communications, Inc. PRIMA TECH is a
trademark of Prima Communications, Inc., Roseville, California 95661.

Publisher: Stacy L. Hiquet


Managing Editor: Sandy Doell
Acquisitions Editor: Emi Smith
Associate Marketing Manager: Jenni Breece
Technical Reviewer: Mason McCuskey
Book Production and Editorial: Argosy
Cover Design: Prima Design Team
Copyright Microsoft Corporation, 2000. All rights reserved.
Important: Prima Publishing cannot provide software support. Please contact the appropriate software manufacturer’s techni-
cal support line or Web site for assistance.
Prima Publishing and the author have attempted throughout this book to distinguish proprietary trademarks from descrip-
tive terms by following the capitalization style used by the manufacturer.
Information contained in this book has been obtained by Prima Publishing from sources believed to be reliable. However,
because of the possibility of human or mechanical error by our sources, Prima Publishing, or others, the Publisher does
not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omis-
sions or the results obtained from use of such information. Readers should be particularly aware of the fact that the
Internet is an ever-changing entity. Some facts may have changed since this book went to press.

ISBN: 0-7615-3191-2
Library of Congress Catalog Card Number: 0-011047
Printed in the United States of America.
00 01 02 03 04 II 10 9 8 7 6 5 4 3 2 1
Für meine Frau, Katja Engel
vi Beginning Direct3D® Game Programming

Acknowledgments
This book couldn’t have been completed without the help of many people. In particular, I want to thank
my parents, who gave me a wonderful and warm childhood.
The first 90% of a book is normally easy to write. The problems arise in the second 90%. That was the
case with this book. The last four weeks of finishing up this project were really hard, both in my private
and professional life. So my corrections and reviews of edits were sometimes a little bit behind schedule.
Nevertheless, the team at Prima Publishing was very friendly and sensible. I would like to thank those peo-
ple, who also helped to make this book possible: Caroline Roop, Emi Smith, and Eve Minkoff.
I would also like to thank André LaMothe, for teaching me game programming with his books.
A lot of people wrote tutorials on game programming and published them on the Internet. I learned a lot
from these. So I would like to thank all those people on the Internet, for giving away their knowledge of
game programming for free.
—Wolfgang Engel
Contents at a Glance vii

Contents at a Glance
Introduction ...........................................xiv Part III Hardcore DirectX Graphics
Part I DirectX Graphics: Programming..............................209
Don’t Hurt Me ...............................1 Chapter 9: Working with Files................211
Chapter 1: History of Direct3D/DirectX Chapter 10: Quake 3 Model Files ...........247
Graphics................................................3 Chapter 11: Game Physics (written by
Chapter 2: Overview on DirectX Amir Geva) ........................................291
Graphics/HAL/COM .............................7 Chapter 12: Collision Detection (written by
Chapter 3: C++/COM Programming Rules Amir Geva) ........................................301
for Direct3D .........................................15
Part IV Appendices ....................343
Chapter 4: Geometry/Shading/Texture
Appendix A: Windows Game Programming
Mapping Basics ....................................23
Foundation.........................................345
Chapter 5: The Basics .............................35
Appendix B: C++ Primer........................373
Chapter 6: First Steps to Animation ..........73
Appendix C: The Common Files
Part II Knee-Deep in DirectX Framework .........................................401
Graphics Programming ..............125 Appendix D: Mathematic Primer............463
Chapter 7: Texture Mapping Appendix E: Game Programming
Fundamentals .....................................127 Resource.............................................485
Chapter 8: Using Multiple Textures.........153 Index ....................................................489
viii Beginning Direct3D® Game Programming

Contents
Introduction ..................................................xiv Render() ..................................................51
InvalidateDeviceObjects() ......................55
Part I: DirectX Graphics: DeleteDeviceObjects()............................55
Don’t Hurt Me......................1 FinalCleanup() ........................................55
Basic2 Example ............................................55
Chapter 1: History of Direct3D/ InitDeviceObjects().................................57
RestoreDeviceObjects() ..........................60
DirectX Graphics........................3 Render() ..................................................62
Chapter 2: Overview of DirectX InvalidateDeviceObjects() ......................64
DeleteDeviceObjects()............................65
Graphics/HAL/COM .................7 FinalCleanup() ........................................65
Direct3D HAL ................................................9 Basic3 Example ............................................65
Pluggable Software Devices.........................11 RestoreDeviceObjects() ..........................68
Reference Rasterizer....................................12 Render() ..................................................70
Controlling Devices......................................12 InvalidateDeviceObjects() ......................72
COM..............................................................13
Chapter 6: First Steps to
Chapter 3: C/C++ and COM Animation ................................73
Programming Rules for The Third Dimension .....................................75
Direct3D ..................................15 Transformation Pipeline .................................77
Code Style .....................................................18 Transformation Math.......................................80
Debugging DirectX......................................20 Matrices.............................................................80
Return Codes................................................21 The World Matrix.........................................82
The View Matrix...........................................86
Chapter 4: Geometry/Shading/ Camera Rotation about a Camera
Texture-Mapping Basics.............23 Axis .........................................................88
Orientation ...................................................26 Camera Rotation with Quaternions ......92
Faces ..............................................................27 The Projection Matrix .................................95
Normals.........................................................29 Lighting.............................................................96
Normals and Gouraud Shading..................29 Material .........................................................97
Texture-Mapping Basics...............................31 Lighting Models ...........................................97
Vertex Color (Optional)..............................99
Chapter 5: The Basics.................35 Depth Buffering .............................................100
The DirectX Graphics Common Down to the Code..........................................104
Architecture................................................37 OneTimeSceneInit() .................................105
Basic Example ..............................................38 InitDeviceObjects()....................................110
OneTimeSceneInit() ..............................40 RestoreDeviceObjects().............................110
InitDeviceObjects().................................41 FrameMove()..............................................113
RestoreDeviceObjects() ..........................41 Render() .....................................................117
FrameMove()...........................................51 InvalidateDeviceObjects().........................118
Table of Contents ix

DeleteDeviceObjects()...............................119 Dark Map Blended with Material Diffuse


FinalCleanup()...........................................119 Color .........................................................164
Next Steps to Animation ...............................119 Glow Mapping ............................................166
RestoreDeviceObjects().............................119 Detail Mapping...........................................167
FrameMove()..............................................120 Alpha Operations...........................................170
More Enhancements .................................120 Modulate Alpha..........................................172
Quiz...............................................................120 Environment Mapping ..................................173
Spherical Environment Mapping .............173
Additional Resources ..................................124
Cubic Environment Mapping ...................175
Part II: Knee-Deep in RestoreDeviceObjects() ........................176
RenderSceneIntoCube()......................177
DirectX Graphics RenderScene() ......................................179
Programming....................125 ConfirmDevice() ...................................181
Bump Mapping ..............................................182
Chapter 7: Texture-Mapping ApplyEnvironmentMap()..........................183
Fundamentals .........................127 InitBumpMap()..........................................187
Render() .....................................................191
Texture Coordinates......................................129
ConfirmDevice() ...................................193
Texture-Addressing Modes............................132
Dot Product Texture Blending.....................194
Wrap Texture-Addressing Mode...............132
InitDeviceObjects()....................................195
Mirror Texture-Addressing Mode.............133
Render() .....................................................198
Clamp Texture-Addressing Mode.............134
Multitexturing Support .................................200
Border Color Texture-Addressing Mode .135
Texture Management ....................................201
MirrorOnce Texture-Addressing Mode ...136
Quiz...............................................................201
Texture Wrapping........................................137
Additional Resources...................................206
Texture Filtering and Texture Anisotropy.......................................................207
Anti-Aliasing...............................................140 Detail Mapping ..............................................207
Mipmaps .........................................................142
Cubic Environment Mapping.......................207
Nearest-Point Sampling.................................143
Stencil Buffers ................................................207
Linear Texture Filtering................................143
Bump Mapping ..............................................207
Anisotropic Filtering......................................144
Dot Product Texture Blending.....................207
Full-Scene Anti-Aliasing.................................146
Alpha Blending ..............................................148
Part III: Hard-Core
Chapter 8: Using Multiple DirectX Graphics
Textures..................................153 Programming ....................209
Color Operations ...........................................156
Dark Mapping ............................................157 Chapter 9: Working with Files ...211
Animating the Dark ...................................161 Building Worlds with X Files ......................212
Blending a Texture with Material Diffuse 3-D File Formats .............................................213
Color .........................................................161 X File Format .................................................213
x Beginning Direct3D® Game Programming

Header ........................................................215 Chapter 11: Game Physics


Mesh ............................................................216
MeshMaterialList........................................218 (written by Amir Geva) ...........291
Normals.......................................................221 3-D Math .........................................................292
Textures.......................................................221 Newton’s Laws ................................................294
Transformation Matrices ...........................229 Calculating the Frame Time.........................296
Animation ...................................................233 Air Resistance .................................................297
Using X Files ..................................................235 Static Friction .................................................297
The Example ..................................................241 Kinetic Friction ..............................................298
InitDeviceObjects()....................................242 Chapter 12: Collision Detection
RestoreDeviceObjects() and
InvalidateDeviceObjects() ......................243 (written by Amir Geva) ...........301
Render() .....................................................243 The Most Basic Optimization .......................302
Extending X Files...........................................245 Bounding Volumes ........................................302
Additional Resources ..................................245 2-D Collision Detection .................................302
Brute Force ............................................304
Chapter 10: Quake III Bit Arrays ................................................304
Model Files.............................247 Sprite Bounds ........................................309
Group Processing...........................................313
Files of the Trade ...........................................249
Axis Sort .................................................314
Animation.cfg.................................................253
Grid.........................................................316
The .skin File..................................................255
Static Objects .........................................317
Textures and the Shader File........................256
Automatic Transparent Static Marking....319
Custom Sounds ..............................................262
3-D Collision Detection .................................319
The .md3 Format...........................................263
Dealing with this Complex Problem........320
Md3.h ..........................................................264
Portals.....................................................320
Md3.cpp ......................................................271
Calculating Distance of Cylinder
CreateModel().......................................271
from Wall .............................................322
CreateTextures() ...................................278
BSP (binary space partitioning) ..........323
CreateVB().............................................282
Sliding Off Walls....................................323
Render() ................................................283
3-D Mesh Collision Detection.......................324
DeleteTextures() ...................................284
Bounding Volumes.....................................324
DeleteVB().............................................285
Convexity of Models..............................325
DeleteModel() .......................................285
Convex Models Intersection.................326
Md3view.cpp ...............................................285
Concave Models Intersection...............326
OneTimeSceneInit() ............................286
Axis Aligned Bounding Boxes.........327
InitDeviceObjects()...............................286
Axis Aligned Bounding
Render() ................................................287
Boxes Tree.......................................327
DeleteDeviceObjects()..........................287
How to Divide the Box................329
FinalCleanup() ......................................288
Oriented Box Intersections ........330
MsgProc() ..............................................288
Triangle Intersection ...................332
Additional Resources ..................................289
Table of Contents xi

Using ColDet with DirectX 8.0.....................332 Polymorphism ............................................392


Collision Reaction......................................334 Inline Functions .........................................393
3-D Object Group Processing ...................336 C++ Enhancements to C............................394
Quiz...............................................................336 Default Function Arguments ...............395
Placement of Variable Declarations.....395
Additional Resources ..................................341
Const Variable........................................396
Part IV: Appendixes .........343 Enumeration..........................................397
Function Overloading and Operator
Appendix A: Windows Game Overloading.........................................397
Function Overloading...........................397
Programming Foundation........345 Operator Overloading .....................399
How to Look through a Window .................346
Additional Resources...................................400
How Windows 95/98/ME/NT/2000
Interacts with Your Game ...........................346 Appendix C: The Common
The Components of a Window ....................347 Files Framework .....................401
A Window Skeleton .......................................347
Create() ..........................................................407
Step 1: Define a Window Class .................351
Step 1: Create the Direct3D Object with
Windows Data Types .............................354
Direct3DCreate8()...................................409
Step 2: Register the Window Class ...........354
Step 2: Search for the Proper
Step 3: Creating a Window of
Device Driver with the Help of
that Class...................................................354
BuildDeviceList().....................................410
Step 4: Display the Window ......................357
Step 1 in BuildDeviceList() ..................419
Step 5: Create the Message Loop .............358
Step 2 in BuildDeviceList() ..................427
The Window Procedure ............................361
Step 3: Create a Window with
A Window Skeleton Optimized for
CreateWindow() ......................................428
Games ...........................................................361
Step 4: Initialize the Geometry Data
Windows Resources .......................................366
of your Game with OneTimeScene
Additional Resources ..................................371 Init() .........................................................428
Appendix B: C++ Primer ...........373 Step 5: Initialize the 3-D Environment
with Initialize3DEnvironment().............428
What’s Object-Oriented Programming? ......374
Step 1 in Initialize3DEnvironment() ...433
Abstraction..................................................374
Step 2 in Initialize3DEnvironment():
Classes..........................................................377
CreateDevice() ....................................433
Encapsulation .............................................378
Step 3 in Initialize3DEnvironment():
Declaring a Class ........................................379
SetWindowPos()..................................435
Constructor.................................................384
Step 4 in Initialize3DEnvironment():
Destructor ...................................................384
GetDeviceCaps() .................................435
This Pointer ...........................................385
Step 5 in Initialize3DEnvironment():
Class Hierarchies and Inheritance ...........386
GetDesc().............................................437
Inheriting Code.....................................387
Step 6 in Initialize3DEnvironment():
Inheriting an Interface .........................390
D3DUtil_SetDeviceCursor() ..............438
Virtual Functions........................................391
xii Beginning Direct3D® Game Programming

Step 7 in Initialize3DEnvironment(): Vector Addition: U + V .........................469


Initialize the Application’s Device Vector Subtraction: U – V.....................471
Objects .................................................438 Vector Multiplication ............................472
Step 8 in Initialize3DEnvironment() ...439 Scalar Product...................................472
Step 6: Starting the Timer with Dot Product.......................................473
DXUtil_Timer().......................................440 Cross Product....................................476
Run() ..............................................................444 Unit Vector .................................................477
Step 1 in Render3DEnvironment(): Matrices...........................................................478
TestCooperativeLevel() and Multiplication of a Matrix with
Resize3DEnvironment().....................448 a Vector.....................................................480
Step 2 in Render3DEnvironment(): Matrix Addition and Subtraction .............480
FrameMove().......................................451 Matrix Multiplication.................................481
Step 3 in Render3DEnvironment(): Translation Matrix......................................481
Render() ..............................................451 Scaling Matrix.............................................481
Step 4 in Render3DEnvironment(): Rotation Matrices .......................................482
Fill the Frame Count String...............452 Rotation about the y-axis ......................482
Step 5 in Render3DEnvironment(): Rotation about the x-axis......................482
Present() ..............................................453 Rotation about the z-axis ......................483
MsgProc().......................................................455
Appendix E: Game Programming
Appendix D: Mathematics Resources ...............................485
Primer ...................................463 General ...........................................................486
Points in 3-D ...................................................464 DirectX Graphics ...........................................486
Vectors.............................................................467 FAQ .................................................................487
Bound Vector..............................................467
Free Vector..................................................468 Index........................................489
Letter from the Series Editor xiii

Letter from the Series Editor

Dear Reader,
The 3D API wars on the PC are over. And no matter how you feel, Direct 3D is the victor on the PC
platform. Amazingly enough, it sure didn’t have to do with an over-abundance of clear documentation
about Direct 3D! In fact, after years of the Direct 3D API being available, only one or two books are of
any merit on the subject. With this in mind the Author of Beginning Direct 3D Game Programming, Mr.
Wolfgang Engel, set out to write a beginner’s book on Direct 3D that also covered Direct X and General
Game Programming theory. I can without hesitation state that he has succeeded, and succeeded where oth-
ers have failed.
This text is fantastic; it has a pace that is both challenging and cutting-edge, but not intimidating. You will
find yourself learning very complex ideas very easily. Moreover, this book is one of the most graphically
annotated books on Direct 3D, so you won’t be left wondering what something is suppose to look like!
Additionally, although this book is for beginners it doesn’t mean that the material is basic. In fact, as the
chapters progress you will cover advance concepts such as multitexturing, lighting, TnL, 3-D file formats,
and more!

André LaMothe
March 2001
xiv Beginning Direct3D® Game Programming

Introduction
When I finished my first degree in law back in 1993, I was very proud and a little bit exhausted from the
long learning period. So I decided to relax by playing a new game called Comanche by NovaLogic.
I started the night of January 11 and ended up about three days later with only a few hours of sleep. With
the new experience in my head, I decided to start computer game programming. My target was to program
a terrain engine like Comanche.
My then-girlfriend—now my wife—looked a little bit confused when a young, recently finished lawyer
told her that he’s going to be a game programmer.
About two years later, after becoming a member of the Gamedev Forum on Compuserve and reading a
few books on game programming by André La Mothe and a good article by Peter Freese on height-map-
ping engines, I got my own engine up and running under OS/2. I wrote a few articles on OpenGL and
OS/2 game programming in German journals, coauthored a German book, and started with the advent of
the Game SDK (software development kit) on Windows game programming.
In 1997 I wrote my first online tutorials on DirectX programming on my own Web site. After communi-
cating with John Munsch and the other administrators of www.gamedev.net, I decided to make my tutori-
als accessible through this Web site also. In the summer of 1998, as a Beta tester of the DirectX 6.0 SDK,
I decided to write the first tutorial on the Direct3D Immediate Mode Framework. At that time I used
www.netit.net as the URL of my Web site. There was a mailing list with a lot of interested people, and I
got a lot of e-mails with positive feedback.
It started to be real fun. In 1999 I fired up my new Web site at www.direct3d.net, which is now also
accesible through www.directxgraphics.net, with the sole purpose of providing understandable and
instructive tutorials on Direct3D programming.
This is also the target of the book that lies in front of you; it should help you to understand and learn
DirectX Graphics programming.
If you have any questions, don’t hesitate to e-mail me. A lot of things are implemented with the questions
of readers in mind.
Mainz, Germany, December 2000
Wolf ([email protected])

What You’re Going to Learn


This book covers all of the elements necessary to create a Windows 95/98/ME/NT/2000 or short
Windows-based Direct3D/DirectX Graphics game for the PC:
• 3-D graphics and algorithms
• Game programming techniques and data structures
Introduction xv

• Using 3-D files to construct game worlds


• Programming your own character engine with a character animation system
• DirectX Graphics programming
And more...

What You Need to Know


This book assumes that you can program in C with a dash of C++. I will use the less-esoteric features of
C++, the way that the Microsoft guys who programmed the Direct3D Immediate Mode samples in the
DirectX SDK did. In case you need a refresher, there’s a decent C++ primer in the appendix, so check it out.
You aren’t taking a stab at graphics/game programming to learn the math. If you can add, subtract, multi-
ply, divide, and maybe square a number, you will be able to understand 90 percent of the math and what’s
going on in this book. There’s a math primer provided in the appendix to be absolutely sure that you won’t
miss anything.

How This Book Is Organized


This book consists of four parts. The first part will show you the essentials of Direct3D game program-
ming. It deals with the programming conventions, basic algorithms, texture-mapping basics, 3-D math, the
transformation pipeline, lighting, and using depth buffers. It also provides a small DirectInput primer on
using the keyboard interface.
In the second part, you will learn how to use the transformation and lighting pipeline to map textures on
objects with different effects. All of the buzzwords, such as bump mapping, environment mapping, and
procedural textures, are explained, and the effects are shown in sample programs.
In the third part of this book, you’ll deal with file formats and how to integrate them into your game
engine. The file formats used are the greatly enhanced .X file format, introduced with the DirectX 8.0
SDK, and the MD3 file format used in most of the games driven by the Quake III engine.
The fourth part contains appendixes, which should be useful if you decide to refresh your Windows pro-
gramming, C++, or math skills. The Direct3D framework, which is used throughout this book, is
explained here in detail.

Using the CD-ROM


The companion CD includes all the code from this book and the Microsoft DirectX 8.0 SDK, which you
will need to install in order to compile and run the example programs discussed throughout the book (see
the installation instructions in the following section). The DirectX SDK contains the run-time files, head-
ers, and libraries you need to compile the book examples and provides a lot of example programs for every
component of DirectX.
xvi Beginning Direct3D® Game Programming

The book example code is located in directories named after the chapters of the book. In every example
directory, you’ll find the provided graphics and the source files. There’s a readme.txt file, which provides
you with additional information on compiling the application.
You’ll need a system that fulfills the requirements of DirectX to run the example programs. You should have
Microsoft Windows 98/ME/2000 and a Pentium II or higher card with a 3-D accelerator. To get a useful
development system, you should use at least 128MB RAM and a big hard disk (greater than 10 GB) to
store all of the files you’ll produce in your development cycle. A monitor with a resolution of at least 1,024
× 768 and a connection to the Internet to browse the news on game development may also be useful.

Installing the DirectX SDK


To install DirectX, you have to find the folder labeled DirectX on the CD that comes with this book.
Basically, you can run the Setup program, and it will load the DirectX run time and the SDK into a direc-
tory—usually called mssdk\—on your hard drive. You have to choose among Complete, Custom, and
drivers-only installations.

Figure I.1: Installation dialog


box
Introduction xvii

If you choose the Complete installation, everything is loaded onto your hard drive. The installation proce-
dure checks the installed DirectX drivers, and if they are outdated, it will install the ones that are delivered
with the CD-ROM. If you choose the Custom installation, the program will give you the choice to install
only parts of the SDK. For example, installing the Visual Basic samples wouldn’t make any sense if you
develop C++ games only.
You will also have to choose between the Retail and Debug builds. The Retail builds are stripped of lots
of debug checks and are also compiled to run faster. If you just plan to play DirectX games and not to
write your own, the Retail builds will be the best choice. The Debug builds help coders to get their
DirectX applications up and running. They help you in trapping down bugs by giving you debug messages.
The trade-off, however, is that they run slower than the Retail builds.

Figure I.2: Retail/Debug dialog


box

After you finish installing DirectX, take a look around all of the directories and get to know the location
of the libraries, include files, help, and samples. You need these locations to set up the Visual C++
compiler.
xviii Beginning Direct3D® Game Programming

Figure I.3: Directory structure

You will find the DirectX Graphics programming files in


C:\MSSDK\SAMPLES\MULTIMEDIA\Direct3D

All of the materials and concepts are compatible with all future versions of DirectX, so keep an eye on
updates at msdn.microsoft.com/directx.
The other piece of software you need to install is the newest drivers for your video card. You can pick
them up on the Web site of your video card manufacturer. The newest drivers often offer speed and stabili-
ty improvements and sometimes new features. Take a look at the always-provided readme file to get the
proper installation instructions.

Setting Up Visual C++ 6.0


After you have DirectX installed, you need to consider the rest of your software. The most important
piece of software is your IDE (integrated development environment), or short compiler. I suggest that you
use the Microsoft Visual C/C++ 6.x or better compiler. This compiler generates really good Windows
code, and you can get it for about $99 from your local software store. This is the path of least resistance.
Introduction xix

The new DirectX 8.0 SDK installation routine sets


all of the proper paths for you. In case anything NOTE
goes wrong, you should be able to check the right Intel makes a package called VTune, which
paths. Therefore, select Options from the Tools might be integrated in the Visual C/C++
menu and choose the Directories tab. You should see environment. It provides high optimizing
something like the following dialog box: compilers with profiling tools, which are
faster than the standard Visual C/C++
compilers.Try to use them later in your
development cycle to optimize your game
before it’s shipped.

Figure I.4: Header files path

The main header directory should be D:\mssdk\include, where D is the hard drive and mssdk is the
directory where you might have installed the DirectX SDK.
If you choose the lib paths in the drop-down menu, you should see something like the following:

Figure I.5: Lib files path

The DirectX library files are located in the lib directory of the DirectX SDK installation.
xx Beginning Direct3D® Game Programming

These directories should always be at the top of the list, as shown in the Directories dialog box in Figures
4 and 5, because the compiler will search for these files beginning at the top of the list. You might see
something like the following message if you haven’t configured the include path properly:
d:\book\source\part 1\chapter6\animated objects\objects.cpp(68) : error C2146: syntax
error : missing ';' before 'g_Keyboard_pDI'

Even if the right path to the header and library files is provided, you might have to feed the names of these
files to the linker of your development environment. The proper path to these object/library modules
should be listed in your Link dialog box. To reach this dialog box, select Project/Settings and then the Link
tab. In the General category there is an entry field called Object/library modules. It holds all of the library
files, which should be linked with the application you’re currently developing. It should look like this:

Figure I.6: Linker path

In this entry field, you will need to name at least the following:
d3dx8.lib
d3dxof.lib
d3d8.lib
winmm.lib
dxguid.lib

If you missed a file, an error message appears, which might look like this:
d3dapp.obj : error LNK2001: unresolved external symbol _Direct3DCreate8@4
Introduction xxi

Here, the d3d8.lib is missing. The unresolved external symbols are part of the Component Object Model
(COM) interfaces of Direct3D (I will explain COM later).
You should also check another include path, the one that holds the path to the directories of the common
include files for the C/C++ compiler. Under Project Settings/C/C++, there’s an entry in the drop-down
menu called Preprocessor. You might choose as additional Include-Directories the following path:
..\..\common\include

In case something goes wrong here, an error message indicates that the
d3dframe.h

include file can’t be found by the compiler in this case. This is just another show stopper; normally you
include the Common files from the
..\..\common\source

in every project.

Figure I.7: Files in IDE


xxii Beginning Direct3D® Game Programming

If you drag-and-drop the directory to another place, the paths to these files might not be correct anymore.
So you have to add the Common files with Project->Add Files to Project->Files.
Now let’s compile our first project:
• Fire up your Visual C++ configured development environment.
• Click on Open Workspace.
• Choose basics.dsp in the book\chapter4 directory.
• Check whether you’ve configured the paths to the directories as described above.
• Choose Build/basics.exe build.
• When everything works fine, choose run basics.exe.
That’s it. If something went wrong, try to reread the previous passages on installing the DirectX SDK and
Visual C++ and the provided documentation.

Additional Resources
You should visit the Microsoft MSDN site for DirectX at msdn.microsoft.com/directx at regular inter-
vals and the mailing list at discuss.microsoft.com/SCRIPTS/WA-MSD.EXE?S1=DIRECTXDEV.
Daily news about the game developer community can be found at www.gamedev.net or www.flipcode.com.
I’ll provide additional information on www.direct3d.net.

Quiz
Q: What’s the difference between the Retail and Debug builds of the DirectX run times?
A: The Retail builds are stripped of lots of debug checks and are also compiled to run faster. The Debug
builds help in trapping down bugs by giving you debug messages.
Q: How do you configure the linker environment of your IDE?
A: Project/Settings and then under the Link tab.
Q: What is the most important resource that you should check often?
A: msdn.microsoft.com/directx
Part 1

DirectX
Graphics:
Don’t Hurt Me
We’ll deal with the most basic questions on graphics programming with Direct3D in this part of the
book. You will learn
• The essentials of programming with Direct3D
• The meaning of HAL
• How to use the COM binding to DX 8
• Coding conventions
• The basics of graphics programming, including orientation, faces, normals, and Gouraud shading
• Direct3D essentials
• Texture-mapping basics
• The ins and outs of the third dimension, especially 3-D math and the transformation pipeline
• The way Direct3D scenes are lit
• Scene management with depth buffering
• DirectInput essentials
CHAPTER I
History of
Direct3D/
DirectX
Graphics
4 History of Direct3D/DirectX Graphics

efore Windows, DOS was the most popular operating system for the PC. Games were pro-
B grammed in DOS exclusively for many years. Game developers resisted developing for
Windows because of its unacceptable graphics and audio performance at the time.
The direct access to hardware that DOS afforded came with its own complications, however. DOS games
had to support the full range of video and audio hardware. This forced developers to write complex code
to support dozens of different configurations just to provide consistent graphics and audio across all PCs.
With the advent of DirectX in 1995, Microsoft provided within Windows the performance previously
available only through DOS, without the complexity of supporting each vendor’s particular hardware solu-
tions. Since that time, every hardware vendor delivers its product with Windows drivers.
Direct3D, part of DirectX, appeared in 1996 in DirectX 2.0. Direct3D is designed to give access to the
advanced graphics capabilities of 3-D hardware accelerators, while promoting device independence and
hardware abstraction by providing a common interface to the programmer. Code properly written for
Direct3D will work on Direct3D devices now and in the future.
Let’s dive a little bit deeper into history: In the early ’90s, a lot of PC 3-D engines were built in Great
Britain. There were the well-known Renderware (www.renderware.com) and the BRender from Argonaut
(www.argonaut.com), which was ported in 1994 to OS/2 and a small British company called
RenderMorphics. RenderMorphics was founded in 1993 by Servan Keondjian, Kate Seekings, and Doug
Rabson with their savings and produced a product called Reality Lab. Keondjian played piano in a band at
night and programmed his 3-D engine by day. Seekings subsequently upped her credentials with a quick
master’s degree in computer graphics at Middlesex University. It’s interesting to note that her 3-D render-
ing library, developed with input from Keondjian and Rabson, was submitted as a school project and was
flunked for not following the assigned specs closely enough.
At the first trade show they attended (SIGGRAPH 94), they were spotted by Microsoft, and
RenderMorphics was acquired in February 1995.
After the acquisition of RenderMorphics, Microsoft integrated Reality Lab into its DirectX family of
APIs (application programming interfaces). The Immediate Mode component of Reality Lab absorbed
the standard 3-D Windows API of the time, 3-D-DDI, which was created by Michael Abrash, later one of
the creators of the Quake I engine at id Software.
Until the advent of DirectX 8.0, Direct3D consisted of two distinct APIs: Retained Mode and Immediate
Mode. At that time, the Immediate Mode API was difficult to use, but it was a flexible, low-level API that
ran as efficiently as possible. Retained Mode was built on top of Immediate Mode and provided addition-
al services, such as frame hierarchy and animation. Retained Mode was easier to learn and use than
Immediate Mode, but programmers wanted the added performance and flexibility that Immediate Mode
provided. Development of the Retained Mode API has been frozen with the release of DirectX 6.0.
Beginning Direct3D Game Programming 5

The major changes between the Direct3D Immediate Mode version 6.0 and version 7.0 were the support
of hardware accelerated transformation and lighting, and the reorganization of the lights, materials, and
viewport objects, which from now on are set directly by calling the methods of IDirect3DDevice7 and the
drop of a special interface to access textures. The IDirect3DDrawSurface7 interface also provided an easier
way to manage the textures.
With the advent of the DirectX 8.0 SDK came the biggest improvements in the history of Direct3D.
Direct3D got a fundamentally new architecture with version 8.0, which should be even more stable in
future versions. The initialization, allocation, and management of data were simplified by the integration
of DirectDraw and Direct3D into one interface, called DirectX Graphics, which led to a smaller memory
footprint and a simpler programming model.
With DirectX Graphics, you can now use vertex and pixel shaders with their own processing language
instead of the traditionally used transformation and lighting, or fixed function, pipeline. These shaders are
more flexible than the older approach and are a lot more powerful, when the graphics hardware supports
them. The shader language looks similar to x86 Assembler code. At the time of this writing, no widely
available hardware supports vertex or pixel shaders, and only vertex shaders may be emulated. But that will
change in the upcoming months, and they might get the killer features of Direct3D.
The new ability of DirectX 8 and of upcoming hardware to render a scene more than once—called
multisampling rendering—opens up a variety of effects, such as full-scene anti-aliasing, motion blur, and
depth of field.
Another new feature of DirectX 8.0 is the ability to use hardware sprites for your particle system to gener-
ate sparks, explosions, rain, snow, and so on. So-called point sprites are supported with their own pro-
gramming interface to help you in doing this.
Ever heard of voxels? Voxels are three-dimensional
entities that describe a 3-D volume (not the 2-D CAUTION
voxel engine used in Comanche-like games). With The first incarnation of Direct3DX in
3-D volumetric textures, something similar to voxels the DirectX 7.0 SDK was a little bit
can be done. Exact per-pixel lighting and atmos- buggy.There are a few known bugs,
pheric effects could be applied with these textures to especially D3DXCreateContext() and
your application. D3DXMatrixLookAtLH().They were
fixed in the DirectX 7.0a SDK, but
With Direct3D 7.0, a new utility library called that introduced a new bug,
Direct3DX appeared. It provides helper functionality D3DXMatrixLookAtRH().The bugs were
for enumerating device configurations, setting up a removed in DirectX 8.0, but you should
device, running full-screen or windowed mode uni- be careful with the older versions. Read
formly, running resizing operations, calculating vec- more on Microsoft’s mailing list by
tor and matrix operations, and simplifying image file searching the online archive at discuss.
loading and texture creation. In addition, it provides microsoft.com/SCRIPTS/WA-MSD.
functions for drawing simple shapes, sprites, and EXE?S1=DIRECTXDEV.
cube maps.
6 History of Direct3D/DirectX Graphics

Direct3DX has been greatly enhanced in DirectX 8.0. It now supports additionally skinned meshes, mul-
tiresolution level-of-detail (LOD) geometry, and higher-order surface data for .X files. It includes a skin-
ning library to work with meshes and functions to assemble vertex and pixel shaders. The D3DX image
file loader functions support BMP, TGA, PNG, JPG, DIB, PPM, and DDS files. It also provides helper
methods to port OpenGL applications to DirectX Graphics.
The DirectX 8.0 SDK provides a programming
framework that is similar to the framework used in
the DirectX 6.0 and 7.0 SDKs. The new SDK
NOTE
doesn’t call it framework anymore, instead it talks Its disadvantage is the lack of source
about Common files. These files give you the code. Every 3-D engine programmer
wants to be able to control everything
direct access you need and encapsulate the details
down to the metal.The programmer
of setting up Direct3D, great for your learning
won’t like another level of abstraction
curve. You can concentrate on the essential things between him and his hardware, which
while still being able to see everything on the low- is not transparent.
est level. This framework gives you a common
ground on which you can implement your individ-
ual features. As a beginner, you can avoid a lot of
basic mistakes with the fast and very well tested framework code, allowing you to concentrate your energy
on learning. Intermediate and professional programmers might use the framework as a good testing plat-
form, or perhaps professional programmers will write their own framework that suits their needs better by
looking at the DirectX Graphics Common files source code.

NOTE
A detailed description of these Common files is provided in
Appendix C. For example, ATI at
www.ati.com/na/pages/resource_centre/dev_rel/devrel.html
uses a slightly modified version of the framework used in the
DirectX 7.0 SDK. NVIDIA at www.nvidia.com has built a com-
pletely new framework, and Intel at www.intel.com has built
its own framework, which uses the Visual C/C++ 6.0 project
wizard to give you an interactive way to build a code template
that is sufficient for your needs.And there are a lot more
game companies that have built their own production libraries
without releasing the source.
CHAPTER 2
Overview of
DirectX
Graphics/
HAL/COM
8 Overview of DirectX Graphics/HAL/COM

ike all of the DirectX APIs, DirectX Graphics was designed to provide maximum speed on
L different hardware, with a common interface and backward compatibility in mind. This leads
to the following demands:
• The API needs consistency to be viable.
• If a feature is not supported by hardware, there has to be a fallback mechanism.
• Interface innovation must be possible with the lowest possible learning curve for programmers.
• All games developed in early versions of DirectX must be guaranteed to run in future versions of DirectX.
The answers to these demands are the HAL (hardware abstraction layer) or pluggable software device and
the COM (component object model), which you’ve probably heard before from other Microsoft APIs.
Let’s face the problem from a practical viewpoint. After reading this book, you program that great game,
which will make you happy and rich. It runs very well on your GeForce2-driven and Voodoo 5-driven
computers. To show it to your girl/boyfriend, you’d like to install it on her/his portable computer, which
is, by the way, one of those much-loved computers with its own name. After installing the newest DirectX
version and your masterpiece, you finally realize that this portable has 3-D hardware, which is suitable for
every IBM/Microsoft/HP/<insert the name of your company of choice> manager. After clicking on the
icon of your best work, the best possible visual experience that this computer can provide should appear.
The story shouldn’t end with a loud cry of <insert the name of your computer of choice> by your friend,
who thinks that the display of her/his small portable is broken.
The DirectX team knows this situation, so they provided a way to emulate features that are not supported
by the dedicated hardware. Until DirectX 7.0, this was called the HEL (hardware emulation layer). Since
DirectX 8.0, it’s referred to as a pluggable software device. Whereas the DirectX 7.0 SDK provided a
HEL, called the RGB device, the new pluggable software device would typically be developed by the soft-
ware manufacturer, if they wanted to target non-hardware accelerated machines. The HAL is your friend
within the first second you use Direct3D, because this piece of software, which is provided by the manu-
facturer of the graphics card, will allow you access to all of the hardware’s features. Now, what about fea-
tures that are not supported by hardware?
There are two possibilities: Your program checks the capabilities of your HAL device and switches the
missing features out, or you switch to the pluggable software device with the Change Device dialog box.
Yes, you’ve seen HAL before, if you’ve ever played a game driven by DirectX. There’s always a drop-down
box somewhere in the game that gives you the choice to pick a device or driver. In DirectX 7.0, depending
on the graphics hardware, a HAL, TnLHAL (transformation and lighting HAL), RGB, or reference raster-
izer driver could be chosen from such a dialog box. Since DirectX 8.0, depending on hardware, a HAL,
pluggable software device, or reference rasterizer might be chosen by the user or by the game automatically.
Beginning Direct3D Game Programming 9

In the DirectX Graphics samples in the DirectX 8.0 SDK, you might choose a device for yourself by using
the Change Device dialog box.
Figure 2.1: The Change Device
dialog box

This computer provides two devices. There’s no pluggable software device at the moment, but there is one
HAL driver and one reference rasterizer driver.

Direct3D HAL
This overview shows the relationships among the Direct3D API, HAL, and the GDI (Graphics Device
Interface) API:
Figure 2.2:
Direct3D/HAL/GDI
10 Overview of DirectX Graphics/HAL/COM

As you see, HAL is used by Direct3D to access the graphics hardware through the DDI (Device Driver
Interface). HAL is the primary device type, which supports hardware-accelerated rasterization and both
hardware and software vertex processing. If the display adapter of your computer supports Direct3D,
HAL will exist on your computer.
The behavior of the pluggable software
device and the reference device has to be NOTE
identical to that of the HAL device. In the old days, you had to distinguish between HAL
Application code authored to work with devices or drivers that support transformation and
the HAL device should work with the lighting on their own and devices that are used to
software or reference devices without get transformed and lit triangles. Formerly they
modifications. You have to check the were called HAL and transformation and lighting
capabilities for each device of course. HAL—TnLHAL for short.With the old HAL device,
The reference rasterizer supports all the Direct3D performed the transformation and light-
Direct3D 8 features, while a pluggable ing of the 3-D world and the 3-D models on its own
software device could possibly not even and supplied lit triangles, already transformed to
support texturing. screen space, to HAL and the 3-D card. Nowadays,
all tasks are handled by one HAL.The end user
One of the most exciting HAL applica- won’t see two different HALs anymore.
tions is the “tree demo” of NVIDIA.
You can find it with the source code at
www.nvidia.com.

TIP
A note on the use of hardware transformation and lighting in
games: Oftentimes the bottleneck of 3-D games is the transfor-
mation, lighting, and clipping steps, as these are very math inten-
sive (as you will see in the following chapters) and bog down the
processor.A graphic card with hardware transformation and
lighting is an amazing advantage, because it off-loads these tasks.
This hardware T&L (transformation and light) unit is often called
a GPU (graphics processing unit). Most games today, like Quake
III Arena, do their own lighting calculation but let the graphic API
do the transformation.They benefit from a graphic card that sup-
ports hardware transformation and lighting. It’s only a matter of
time until these games also use the hardware lighting features. In
the meantime, a combination of hardware and software lights
will be used.
Beginning Direct3D Game Programming 11

Figure 2.3: The tree


demo of NVIDIA: gobs
of textured, lit polygons
rendered in real time

If there’s no hardware accelerator in a user’s machine, attempting to create a HAL device will fail.

Pluggable Software Devices


If the user’s computer hardware doesn’t provide all of the 3-D operations needed at least to play the game,
your application might emulate 3-D hardware by using software with a pluggable software device, formerly
called an RGB device. This device doesn’t support 256-color or 8-bit color modes provided by the aban-
doned Ramp driver. It takes advantage of any special instructions supported by the user’s CPU to increase
performance, including the AMD 3D-Now! instruction set on some AMD processors and the
MMX/SIMD instruction set supported by many Intel processors.
Nowadays, the hardware emulation device has to be devel-
oped by the software/game manufacturer, whereas in
former incarnations of the DirectX run times, it was pro- NOTE
vided by Microsoft as the RGB device. Software devices These software device drivers com-
are loaded by the application and registered with the municate to Direct3D/DirectX
Direct3D object. Graphics through an interface similar
to the hardware DDI. The Direct3D
DDK provides the documentation
and headers for developing pluggable
software devices.
12 Overview of DirectX Graphics/HAL/COM

Reference Rasterizer
The reference rasterizer supports all Direct3D fea-
tures. It should be used only for testing features that TIP
your card doesn’t support. This device is optimized Direct3D doesn’t enumerate this device
for accuracy, not for speed. by default.The DirectX 8.0 SDK installer
will set the EnumReference value in the
HKEY_LOCAL_MACHINE\SOFTWARE\
Controlling Devices Microsoft\Direct3D\Drivers registry key
You can configure all these devices with the DirectX to a nonzero DWORD value.
Properties dialog box, which can be found in Neither hardware, software, nor refer-
Start/Settings/Control Panel/DirectX. ence devices can render to 8-bit render-
target surfaces.

Figure 2.4: DirectX Properties


dialog box
Beginning Direct3D Game Programming 13

With this HAL/pluggable software driver/reference driver approach, Microsoft can guarantee a consistent
API to fall back on if specialized 3-D hardware is absent. That’s great isn’t it? OK, what about the other
two postulated demands from the beginning of this chapter: How does Direct3D handle version changes?
Are they easy to learn, and are they handled so that they’re transparent to the programmer? This is where
the COM interface design of the DirectX SDK helps.

COM
If you’ve used other Microsoft APIs, there’s a good chance that you’re an old COM freak who can skip
over this section. All others have to invest a small learning effort and will get a good return on their invest-
ment by learning to use the COM interface, which has been used by DirectX since its inception.
In COM terms, a software component is simply a chunk of code that provides services through interfaces,
and an interface is a group of related methods. A COM component is normally a .DLL file that can be
accessed in a consistent and defined way. Period. Didn’t sound like something someone could write books
with more than 1,000 pages about, did it?
COM has a lot of advantages. I’d like to highlight only three, which I think are important for Direct3D
programmers like us:
• COM interfaces can never change.
• COM is language-independent.
• You can only access a COM component’s methods, never its data.
COM interfaces can never be modified in any way. Applications that use COM objects don’t need to be
recompiled whenever an interface changes, because COM can’t provide a standard way to communicate
with other objects when the interface of a published object could be changeable.
For example, the COM object A, produced by software company C, would be incompatible with COM
object B produced by software company D when the interface of object B is changed and software com-
pany C is too slow in implementing the new interface.
When a COM object has to be changed, a completely new interface with a new name will be added to the
DLL (dynamic-link library). So every COM DLL has to support the legacy interfaces since its release.
Direct3D 8.0 or DirectX Graphics supports the following interfaces: Idire ct3D, IDirect3D2, IDirect3D3,
IDirect3D7, and IDirect3D8. Whereas IDirect3D was the first incarnation of the Direct3D interface in
DirectX 2.0, IDirect3D2 was the interface used in DirectX 3.0, IDirect3D3 was the interface of DirectX
6.0, IDirect3D7 was used in DirectX 7.0, and IDirect3D8 is in DirectX 8.0. If a company produces a
game that is compatible with Windows NT 4.0, which only supports the IDirect3D2 interface of the
DirectX 3.0 SDK, the game company will have to use the IDirect3D2 interface for everything to work
fine. It’s implemented in every upcoming Direct3D DLL since the advent of DirectX 3.0 and will be
implemented in any future versions. The aforementioned game will run on every platform that runs at at
least the DirectX 3.0 run times or later.
14 Overview of DirectX Graphics/HAL/COM

NOTE
C++ and many other languages are
source-based languages; therefore, they
do not have a versioning strategy.
COM was designed to be a binary
based programming model. It doesn’t
allow you to change an interface once
you’ve designed it, but a COM object
can support multiple interfaces.

COM is language-independent. Whether your favorite language is Visual Basic, Pascal, or any other lan-
guage, you can access COM objects with your favorite compiler package. Delphi users especially like this
feature a lot, whereas Visual Basic gurus were provided with a fine implementation of their own with the
arrival of the DirectX 7.0 SDK. Language independence matters when parts of the game—for example,
the world editor—will be written in Delphi and other parts with the Visual C++ compiler, perhaps at dif-
ferent places in this world or on other planets with different time zones. What’s the time on Mars now?
COM can only be accessed via methods. There’s no possibility of accessing data objects directly. This is a
good object-oriented design. As you will see in a few pages, you can’t call a method directly. Instead, you
have to use double indirection through a virtual function table, called the v-table, or just VTBL. These
v-tables are also the key to a language-independent interface. With these advantages, COM helps to get
language-independent, guaranteed access to the legacy and current Direct3D interfaces. Now get access!
CHAPTER 3
C/C++ and
COM
Programming
Rules for
Direct3D
16 C/C++ and COM Programming Rules for Direct3D

hen you call a method in a COM component, you have to call the method by using a
W v-table. When you’re deciding whether to develop your code in C or C++, you need to
consider a few issues. I’ll start with an example. Let’s say you’d like to set a light in a scene of your
3-D world-class game. With C, you would use the following line of code:
hr = m_pd3dDevice->lpVtbl-
>SetLight(m_pd3dDevice, 0, &light );
NOTE
There are macros that help C programmers
You call the COM interface methods by pass-
make their life easier. For example, on line
ing the this pointer, called lpdd, as the first 1014 of ddraw.h
parameter of the method and by referencing the #define IDirectDraw_GetDisplayMode(p, a) \
interface’s method by using it as a pointer to (p)->lpVtbl->GetDisplayMode(p, a)
the interface v-table, which is called lpVtbl
here.

Figure 3.1: The v-table

With C++, there’s one advantage: COM objects and C++ objects are binary-compatible in such a way that
compilers handle COM interfaces and C++ abstract classes the same way.
So in C++, the lpVtbl pointer is implicitly dereferenced
and the parameter is implicitly passed. Thus, the call seen NOTE
above for C will look like this in C++ instead:
To be more precious: the In-Memory
hr = m_pd3dDevice->SetLight(0, &light ); layout in C++ of an instance of a class
that inherits from a pure virtual base
So in general, most DirectX calls in C++ look like this: class (a class with only methods that
are all virtual and equal to zero) has
lpinterface->methodname
the same memory representation as
a COM interface.
Beginning Direct3D Game Programming 17

As you’ve seen in the Introduction, to compile a DirectX program, you have to include a number of import
libraries:
d3dx8.lib
d3dxof.lib
d3d8.lib
winmm.lib
dxguid.lib

Most of these libraries are import libraries and provide the interface names to the linker of your develop-
ment environment.
Now that you understand that COM objects are collections of interfaces, which are simply method point-
ers and, more specifically, v-tables, you need to see an example of how to work with COM. There are three
things to be aware of:
• Direct3D run-time COM objects and DLLs must be registered to and loaded by Windows. The DirectX installer
will do this for you.
• The previously mentioned libraries must be included in your Windows project so that the wrapper methods you
call are linked in.
• The proper include files have to be included in your source file and in the include path entry forms of your IDE
(for example, Visual C++) so the compiler can see header information, prototypes, and data types for
DirectX Graphics.
Here’s the data type for IDirect3D8 interface pointer:
LPDIRECT3D8 g_pD3D = NULL;

To create IDirect3D8 COM object and retrieve an interface pointer on it, all you need to do is use the
Direct3DCreate8() method like this:
m_pD3D = Direct3DCreate8( D3D_SDK_VERSION );

The only parameter passed to Direct3DCreate8() should always be D3D_SDK_VERSION. This informs
Direct3D that the correct header files are being used. This value is incremented whenever a header or other
change would require applications to be rebuilt. If the version does not match, Direct3DCreate8() will fail.
The retrieved interface pointer gives you access to the interface of IDirect3D8. Now you might call a
method in that interface:
if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice ) ) )

This code creates the device with the default adapter by using the D3DADAPTER_DEFAULT flag. It indicates
that you prefer a hardware device over a software device by specifying D3DDEVTYPE_HAL for the DeviceType
18 C/C++ and COM Programming Rules for Direct3D

parameter and uses D3DCREATE_SOFTWARE_VERTEXPROCESSING to tell the system to use software vertex
processing (keep reading for the details).
That’s it for COM. You will use COM throughout this book. If you’re wondering about the strange and
cryptic parameter names, they will be explained now. . . .

Code Style
I use a simple variable tagging scheme that has its roots in the so-called Hungarian notation used by
Microsoft for its own development projects. The name came from its inventor, Charles Simonyi, a now-
legendary Microsoft programmer who happened to be Hungarian. It’s helpful to supply variables in the right
format to help others to read your code, but it could be confusing to people who haven’t seen it before.
The following table shows the prefixes I use and the types they represent. You might come across other
prefixes occasionally, but this table shows the common ones. Hungarian notation is just prefixing variables
with their types.

Prefix Type Example


w WORD wSpeed
dw DWORD dwHitList
f FLOAT fSpeed
d DOUBLE dDirection
p pointer pArray
m_v D3DVECTOR/D3DXVECTOR3 m_vLight
l LONG lPitch
s string sQuestion
sz string terminated by 0 byte szQuestion
h handle hResult
I COM Interface IDirect3D
m_p Member class pointer m_pFloorVertices
m_f member class float m_fStartTimeKey
c constant cText
b BOOL bCheck
Beginning Direct3D Game Programming 19

While the variable naming convention is to prefix the variables with their types, the naming convention for
methods just clarifies readability and the purpose of the method. In all methods, the first letters of subnames
are capitalized; an underscore is illegal.
HRESULT ConfirmDevice( DDCAPS* pddDriverCaps, D3DDEVICEDESC7* pd3dDeviceDesc );

HRESULT CreateInputDevice( HWND hWnd,


LPDIRECTINPUT7 pDI,
LPDIRECTINPUTDEVICE2 pDIdDevice,
GUID guidDevice,
const DIDATAFORMAT* pdidDataFormat,
DWORD dwFlags );

As you can see, parameters for functions follow the same naming conventions that normal variables do. The
parameter pddDriverCaps means a pointer on a DirectDraw device, which points to DriverCaps structure.
The other parameter, pd3dDeviceDesc, means a pointer on a Direct3D device, which points to a device
description structure.
Types and constants begin with an uppercase letter, but you’re allowed to use underscores in the names. For
example:
#define D3DPRESENT_BACK_BUFFERS_MAX 3L

All C++ classes must be prefixed by a capital C, and the first name of each subname of the class must be
capitalized, too. Here’s an example:
class CD3DMesh
{
public:
};

CD3DMesh class is used to handle the loading of .X files. It’s implemented in d3dfile.h of the Common
files.
Let’s try it. We’ll take a look at a typical Direct3D application class:
class CMyD3DApplication : public CD3DApplication
{
CD3DFont* m_pFont;
CUSTOMVERTEX m_QuadVertices[4];
LPDIRECT3DTEXTURE8 m_pCustomNormalMap;
LPDIRECT3DTEXTURE8 m_pFileBasedNormalMap;
D3DXVECTOR3 m_vLight;
BOOL m_bUseFileBasedTexture;
20 C/C++ and COM Programming Rules for Direct3D

BOOL m_bShowNormalMap;
HRESULT CreateFileBasedNormalMap();
HRESULT CreateCustomNormalMap();
HRESULT ConfirmDevice( D3DCAPS8*, DWORD, D3DFORMAT );
LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
protected:
HRESULT OneTimeSceneInit();
HRESULT InitDeviceObjects();
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
HRESULT Render();
HRESULT FrameMove();
HRESULT FinalCleanup();
public:
CMyD3DApplication();
};

There is a member class pointer on a font class at the beginning. There’s another member in the class, which
uses a custom vertex structure for a quad array of vertices. Two member class pointers are pointing to
Direct3D texture objects. A vector light is stored in D3DXVECTOR3. If a file-based texture is used,
m_bUseFileBasedTexture will indicate this. If the user likes to see the normal map, the switch
m_bShowNormalMap has to be set to TRUE. The rest are methods, which will be used throughout the sample.

Please read the COM sample at the beginning of this chapter again. Got it? Yep.

Debugging DirectX
Debugging DirectX applications can be a challenging task. Here are a few tips to give you a starting point:
• Use the DXDiag utility from the DirectX SDK to report your bugs, but be sure that you know exactly what is on
your system.
• The DirectX Control Panel allows developers to set the debug output level from 0 to 5. You can find it at
Start/Settings/Control Panel/DirectX/Direct3D. On the same tab, it’s possible to switch from the Retail
to the Debug run-time versions, or vice versa.
• The D3DX library is a static library. To help debugging, there’s a debug only dynamic library of D3DX. To use
this, link with the d3dx8d.lib, which is an import lib corresponding to the D3DX8D.DLL.
• The Visual C++ GUI debugger can debug full-screen exclusive apps only when using a multi-monitor system or
remote debugging.
With this is in mind, it’s usually wise to build the app in a windowed mode, like the one provided by the framework
that is implemented in the Common files.
Beginning Direct3D Game Programming 21

Return Codes NOTE


A return code is the value returned when the method You might use CRT as a debug memory
completes. It indicates the success or failure of a call manager. It comes with your Visual C++
and why the call fails. Checking the return codes is compiler package.You may find an
simplified by the macros SUCCEEDED() and extensive explanation at
FAILED() provided with the DirectX 8.0 SDK. msdn.microsoft.com.
They take a HRESULT as an argument and return
whether it indicates a success code or a failure code.
Don’t try to check HRESULT against S_OK; not every method returns S_OK if it succeeds. A function
might return a S_FALSE to indicate that it did nothing because there was no need to do anything.
Because every DirectX method returns an HRESULT, you need to structure your code to check for and
handle all potential errors. This work is frustrating at first, but it soon becomes second nature. Having a
program that might be more resistant to crashing is a good reward for this work.
This page intentionally left blank
Another Random Scribd Document
with Unrelated Content
bitterness and distrust in the minds and memories of her living
people.

Years afterward, when Henrietta was a happy wife and mother in


her quiet English home, and her friends, thanks to her generosity
and her husband's, were once more settled in that western land
which was dearer to them than all the shining kingdoms of the
earth, the music of that wild "Ha-till" would strike at times suddenly
on the chord of memory, and she would weep again almost as
bitterly as she had wept upon that late autumn morning when,
floating over the waters of Clew Bay, came those voices to her ear,
sadly singing:
"Mute in our grief, our fortunes broken.
Land of Eire, [Footnote 221] farewell, farewell!
Sad is that word—half-wept, half spoken—
Sad as the sound of the passing bell.
Ha-till, ha-till! we return no more,
Eire, beloved, to thy winding shore!

"Ever in dreams to see thee weep!


Ever to hear thy wail of pain!
Bitter as death, and as dark and deep.
The grief that we carry across the main.
Ha-till, ha-till! we return no more,
Eire, beloved, to thy winding shore!

"Happy the dead who have died for thee!


More happy the dead who died long ago!
Who never in sleep had learned to see
The grief and shame that have laid thee low.
Ha-till, ha-till we return no more,
Eire, beloved, to thy winding shore.

"Farewell! we have poured out our blood like rain,


We asked for naught but a soldier's grave;
Yet say not thou we have sought in vain.
While foes confess that thy sons are brave.
Ha-till, ha-till! we return no more,
Eire, beloved, to thy winding shore."

[Footnote 221: The ancient name for Ireland.]

The End.
The Holy Shepherdess of Pibrac,
Canonized By Pope Pius IX. In 1867.
In the latter part of the sixteenth century, beneath the walls of
Toulouse, bloomed, almost unseen and unknown, a little flower of
the fields, whose delicate chalice emitted a perfume scarcely
perceptible to mortal sense. It passed away, and seemed forgotten;
but its odor still lingered where it had blossomed; and after a few
years had gone, its dust was gathered into the sanctuary, that the
holy place might be filled with the celestial fragrance.

Germaine Cousin was born at Pibrac, a village of nearly two


hundred families in the environs of Toulouse, about the year 1579.
The parish church was dependent on the great Priory of the
Knights of Malta in that city. The chateau belonged to the Du Faur,
Lords of Pibrac. The actual proprietor was Guy, famous at once as
an orator, a poet, and a successful courtier. Once the proudest
remembrance of the place was the visit of Catharine de Medicis and
her daughter, Margaret of Navarre, who were magnificently
entertained by the Lord of Pibrac. But now the visit of the two
queens, and the fame and opulence of the great orator, are nearly
forgotten; while the memory of our holy shepherdess has lived for
nearly three centuries in the hearts of all the inhabitants of Pibrac.
The chateau is a forsaken ruin; but the church has become a place
of pilgrimage, because Germaine prayed beneath its arches, and
there found a tomb.

Her father was a poor husbandman, to whom tradition gives the


name of Lawrence. Her mother's name was Marie Laroche. From
the first moment of her existence, she seemed destined to suffering
and affliction. She was infirm from her birth, being unable to use
her right hand, and afflicted with scrofula. While yet a child, she
became motherless; and, as if these were not trials enough to
accumulate at once upon the head of one so frail, her father did
not long delay to fill the vacant place on his hearth. Absorbed in
her own children, this second wife, instead of pitying the hapless
orphan whom Providence had confided to her care, conceived an
aversion for her. But the trials to which Germaine was subjected
were proofs of the divine favor. To them she was indebted for the
brilliancy of her virtues, especially humility and patience.

As soon as she was old enough, her step-mother, who could not
endure her presence at home, sent her forth to guard the flocks.
This was her occupation the remainder of her life. But even in the
depths of her lonely life, our shepherdess created for herself a
more profound solitude. She was never seen in the company of the
young shepherds; their sports never attracted her; their jeers never
disturbed her thoughtful serenity; she only spoke sometimes to girls
of her own age, sweetly exhorting them to be mindful of God!

We know not from whom Germaine received her first religious


instructions—what hand, friendly to misfortune, revealed to her the
great truths of salvation. Doubtless, it was the curé of the parish;
for holy church despises not the meanest of her children; and her
sagacious eye is quick to discover the chosen of God. But, whoever
it was, he did but little, and there was little to be done. God
himself perfected the religious training of his handmaiden. She
early learned what must for ever remain unknown to those who do
not recognize in him the fountain of all wisdom. Living amid the
wonders of creation, she contemplated them with the intelligent
eye of innocence. Blessed are the pure in heart, for they shall see
God—see him in the brilliant stars, the burning sun, the
unfathomable heavens, and the changing clouds—see him in the
flowers and plants that cover the surface of the earth! Germaine
learned from the open book of nature a wondrous lore; and her
attuned ear caught and comprehended that mysterious, anthem of
praise, which, floating through creation, is unheard by more sinful
man. Her pure soul united in the eternal song: Benedicite omnia
opera Domini Domino: laudate et superexaltate eum in
saecula!

Although Germaine was a poor infirm orphan, subjected to the


heavy yoke of a severe step-mother, and exposed by her
occupation to the inclemency of the weather, she bore all her trials
with cheerfulness, never brooding over her sorrows. One of the
characteristics of the saints which particularly distinguishes them
from ordinary Christians, is, the use made of the common
occurrences of life. They share in common with other men, and
often in a greater degree, the trials common to humanity; but they
are chastened, purified by them, and they look upon the afflictions
of this life as a means of assimilating them to Him who was a man
of sorrows and acquainted with grief. Even in the manifest ill
treatment and injustice of the malignant and wicked, they disregard
the channel, but accept the suffering, as a means of perfection.

The extent to which this principle is carried, is peculiarly Catholic;


and, in reading the lives of our saints, we cannot but be struck by
it. They never struggled against their trials, and therefore were
cheerful under them; for the greater part of our wretchedness
proceeds from struggling against the current of life. This is the key
to the saying of Fénélon: Non-resistance is a remedy for every
ill.

The paternal roof was not for Germaine, as for most—even the
most wretched—a refuge and a place of repose. And yet neither
her poverty, nor sorrows, nor infirmities, could have rendered her
insensible to that which surpasses all the other pleasures of life—
the happiness of being loved. By a divine foresight, God has placed
in the hearts of parents, by the side of that fount of love for their
offspring, a well of singular tenderness for the unfortunate child,
the black lamb of the flock. This peculiar love Germaine had not.
She had not even the legitimate share of her father's heart. She
was denied a place at the fireside; she was hardly allowed shelter
in the house. Her step-mother, irritable and imperious, would send
her away to some obscure corner. She was not permitted to
approach the other children—those brothers and sisters whom she
loved so tenderly, and whom she was always ready to serve
without manifesting any envy on account of the preferences of
which they were the object, and she the victim. The inflexible
harshness of her step-mother obliged the infirm girl to seek a place
of repose in the stable, or upon a heap of vine branches in an out-
house.

But Germaine knew too well the value of sufferings not to accept
with joy these humiliations and this injustice. And, as if her cross
were yet too light, she imposed upon herself additional austerities.
During the greater part of her life, she denied herself all
nourishment but bread and water.

So great a conformity to her poor, suffering, and persecuted


Saviour, kindled in the heart of Germaine an ardent love for his
adorable humanity. Notwithstanding her feebleness and other
obstacles, she assisted every day at the Holy Sacrifice of the Mass.
Even the obligations of her calling could not keep her from church
at that hour. Confiding in God, she left her flock in the pasture, and
hastened to the foot of the altar. It is a misguided piety which
induces us to neglect the duties of our state of life in order to
satisfy our devotion; but with Germaine this was the result of
prompt obedience to a special inspiration. She knew who would
guard her sheep; while she, poor lamb of Christ's flock! went to
refresh herself at the fountain of living water.

Even when her sheep were feeding close by the wood of Boucone,
which skirted the fields of Pibrac, and abounded with wolves, at the
sound of the church bell she would plant her crook or her distaff in
the ground, and hasten to the feet of the divine Shepherd. At her
return, she always found her sheep unharmed. Not one was ever
devoured by the wolves, nor did they ever stray into the
neighboring fields.
Long after St. Germaine's death, the peasants of the hamlet
remembered the unearthly brightness of her face as, week after
week, she approached the holy sacraments.

"A celestial brightness, a more ethereal beauty,


Shone on her face and encircled her form when, after confession,
Homeward serenely she walked with God's benediction upon
her."

In the Holy Eucharist she found a compensation for every grief.


That divine Spouse to whom she was pledged placed himself as a
seal upon her heart, thereby strengthening it to endure the trials of
life, and enriching it with such abundant grace that, while dwelling
at large in the great temple of nature, her life gleamed before him,
brightly, and purely, and constantly, like the undying lamp of the
sanctuary!

Like all the saints, Germaine had a singular devotion to Mary—that


devotion so dear to the Catholic heart, and which is considered by
the fathers as a mark of predestination. The world does not realize
how much it has owed to Mary during these eighteen hundred
years; yet some, some of us know how dark and almost unbearable
it would be with its sorrows, and cares, and privations, if over all
were not diffused the beauty and softness, the sweet charm of
virginity and love, from the divine face of Mary!

To Germaine, the Ave Maria was another salutation of the angel


preluding the overshadowing of the Holy Ghost; and she murmured
the sacred words with infinite tenderness, above all, at the hour
when they are on every lip. As soon as she heard the Angelus bell,
which has three times a day, for six centuries, intoned the Ave
Maria between heaven and earth, it was remarked that, wherever
she might be, she immediately fell upon her knees as if insensible
to the incommodiousness of the place.
The Rosary was her only book; and to her this devotion was no
vain repetition. "Love," says Lacordaire, "has but one word, and, in
saying that for ever, it is never repeated."

"Ever transformed to meet our needs.


Oft as Devotion counts her beads,
As if those beads had caught the light
In her celestial girdle bright,
But each with its own colors dight.
Thus, whensoe'er that prayer is heard,
Fresh thoughts are in each solemn word:
An orb of light comes from the skies
To kindle holy liturgies;
It gathers and gives back their rays.
Now turned to prayer, and now to praise."

The love of God insensibly leads to the love of one's neighbor.


Germaine, when she could, used to draw around her the little
children of the village, and endeavor to explain to them the truths
of religion, and sweetly persuade them to love Jesus and Mary. This
little school, held in the shade of a thicket of the lone fields, was a
spectacle worthy of the admiration of angels, and is a proof of the
unselfishness of real piety, even in the most lowly.

Although the piety of Germaine produced a profound impression in


the village, yet the world is the same everywhere, and always
conceives a secret aversion to piety. It cannot avoid censuring it in
some way, however unobtrusive a piety it may be. Religion imposes
esteem upon the world, and the world avenges itself by raillery. So
the wits of Pibrac persecuted Germaine with mockery; they laughed
at her simplicity, and called her a bigot.

But if God permits, for the perfection of the saints, that their virtue
be turned into ridicule, he knows, when it pleaseth him, how to
render them glorious in the eyes of the world.
In order to reach the village church, Germaine was obliged to pass
the Courbet, a stream she generally crossed without difficulty in
ordinary weather; but after heavy rains, it was too wide and deep
to be passed on foot. One morning, as she was going to church,
according to her custom, some peasants who saw her afar off
stopped at a distance, and asked one another in a tone of mockery
how she would pass the stream, now so swollen by the rain that
the most vigorous man could hardly have stemmed the torrent.
Dreaming of no obstacle, and perhaps not seeing any, Germaine
approached as if none existed. ... O wonder of divine power and
goodness! As of old the waters of the Red Sea opened for the
passage of the children of Israel, so those of the Courbet divided
before the humble daughter of Lawrence Cousin, and she passed
through without wetting even the edge of her garments. At the
sight of this miracle, afterward often repeated, the peasants looked
at one another with fear; and from that time the boldest began to
respect the simple maiden whom they had hitherto scoffed at.

After having thus glorified the faith of Germaine by dissipating the


material obstacles to the performance of her duty, God wished also
to glorify her charity to the poor.

If any one could believe himself exempted from the obligation of


charity and alms-giving, it was certainly our shepherdess. She had
no superfluities; she lacked even the necessaries of life. What was
there, then, to retrench, in her life of extreme privation and severe
penance? How economize the reward of her labor, which consisted
only of a little bread and water? But charity is ingenious; and,
seeing only our suffering Lord in the person of the poor, Germaine
often deprived herself of a part of the bread which was allowed for
her nourishment, doubly glad to give it to the hungry, and increase
the treasure of her privations. Such are the deeds of the saints
which will one day reproach us with terrible power! What will the
rich man say when he beholds, rising up to confront his hardness
of heart, the alms of Lazarus!
The pious liberality of Germaine made her an object of suspicion to
her step-mother, who, not divining her resources, accused her of
stealing bread from the house. One day she learned that Germaine,
who had just gone with the flock, carried in her apron some pieces
of bread. Furious, and armed with a cudgel, she immediately ran
after her. Some of the other inhabitants of Pibrac happened to be
on their way at this very moment to the house of Lawrence Cousin.
Seeing this woman almost beside herself with passion, they divined
her intentions, and hastened to protect Germaine from the ill
treatment with which she was menaced. Overtaking the step-
mother, they learned the cause of her anger. Finding Germaine, she
seized her apron, and instead of bread, it was filled with bouquets
of roses, although it was a season when those flowers were not in
bloom. Thus God confounded the malice of her implacable enemy
by renewing a miracle, likewise wrought in favor of Saint Elizabeth
of Hungary and other saints.

From this time, Germaine was regarded as a saint. Lawrence


Cousin, conceiving more tender sentiments toward this pious child
whom he had so little known, forbade his wife's annoying her any
more, and wished to give her a place in his house with the other
children. But Germaine, accustomed to suffering and loving
privation, besought him to leave her in the obscure place which her
step-mother had assigned her.

It was now that Germaine attained and proved the perfection of


her humility. We must not consider it a trifling honor to have been
esteemed at Pibrac; nor a small reward to have had a place at the
fireside of Lawrence Cousin. Human nature is the same
everywhere. There is no theatre too small for ambition. We know
there are as many cabals for the first place in a village as for the
chief place in an empire.

Perhaps it may not be entirely useless to speak of the exterior of


the blessed Germaine. The manners and customs of the remote
provinces of France retain so much of primitive simplicity, they
change so little year after year, and the people in these localities
have such a marked appearance, that we may form a reasonable
idea of her person and habits.

She is represented in paintings and engravings as we see scores of


shepherdesses in the south of France at this day—seated on a
hillock in the fields, and surrounded by her flock. With a spindle in
her hand, and under her arm the distaff laden with flax, she is
spinning, after the primitive manner of that country. She is rather
below the medium size, and is slight in form. She has the long
head of the Toulousains, and their dark, Spanish complexion and
eyes. The face, half hidden by the picturesque scarlet capuchon, is
expressive of silence, interior silence; and forcibly speaks of the
deep, deep calm within. A pleasing sadness, or rather a subdued
joy, veils her face. There is an introspective look about the eyes
which shows that her spirit has passed the bounds of sense, and is
concentrated in one mysterious thought—some dream of a
heavenly world. Sitting alone, away from her kind, her thoughts
were pure and holy and bright, like the fragrant flowers of her own
green meadows. She must have seemed to the other peasants like
some phantom of unearthly love, as she sat there enveloped in a
divine ethereal atmosphere. In the distance rise the towers of the
church, and the antique château of the Lords of Pibrac, and
between murmurs the Courbet. Over all, is the sunlight of her own
bright clime.

Perhaps the miracle of the roses is the most popular representation


of Saint Germaine, as something not quite so unearthly. There is no
mystery about the look of the fierce step-mother, as with one hand
she raises the cudgel over the head of the resigned-looking girl,
and with the other grasps the apron from which tumble out the
bright and fragrant flowers. The face of Germaine is somewhat sad,
and her eyes are cast down in fear to the earth. Tremulous and
mute she stands before her step-mother, for she is humble and
sore afraid. There is a reflective charm about her of which she is
wholly unconscious, for it emanates from that spiritual beauty
visible only to the intelligences and bright ardors around the
throne.

Saint Germaine died soon after the miracle of the roses. Almighty
God, having sanctified her by humiliations and sufferings, withdrew
her from this world when men, becoming more just, began to
render her the honor her virtue merited. She terminated her
obscure and hidden life by a similar death, but according to
appearance this terrible moment, which confounds human
arrogance, gave her no terror or pain.

One morning, Lawrence Cousin, not seeing her come out as usual,
went to call her where she slept—under the stairs. She made no
reply. He entered and found her upon her bed of vine-branches.
She had fallen asleep while at prayer. God had called her to enjoy
the reward of eternal life. She had ceased to suffer.

It was about the commencement of the summer of the year 1601


that Saint Germaine entered into the joy of her Lord. She was
twenty-two years of age.

That same night two pious men were overtaken near Pibrac by the
darkness of night, and obliged to await the return of day in a
neighboring forest. All at once, in the middle of the night, the
woods were flooded with a light more brilliant than the dawn, and
a company of virgins, clothed in white garments and surrounded by
a dazzling light, floated by on the darkness toward the house of
Lawrence Cousin. Soon after they returned, but there was another
in their midst—more radiant still—who had on her head a chaplet of
fresh flowers. ...

People came in crowds to her funeral, wishing to honor her whom


they had too long despised, whom too late they had known. This
was the first testimony of public veneration. Her body was buried in
the church in front of the pulpit. Forty-three years after, it was
found entire and preserved from corruption. It had been embalmed
with her virginal purity. In her hands were a taper and a garland of
pinks and heads of grain. The flowers had scarcely faded. The grain
was fresh as at the time of harvest.

The holy body was removed and finally placed in the sacristy,
where people of all ranks, incited by the wonders wrought at her
tomb, came to offer their homage.

In 1843, more than four hundred legally attested miracles had been
wrought at her shrine, and so excited the faith of the people in her
power before God, that the Archbishop of Toulouse, and nearly all
the other prelates of France, petitioned the Holy See for her
beatification. It had been desired before the French Revolution, but
it was not attempted till the time of Gregory XVI.

When the commissioners went to examine the condition of the


remains of the venerable Germaine, a most extraordinary scene
took place. The inhabitants of Pibrac, thinking that the beatification
of their shepherdess might terminate in the loss of their holy
treasure, came in a body to the door of the church. They received
the commissioners with threats and even with stones, so it was
only with difficulty an entrance could be effected into the church.
The furious multitude followed, and the examination was made in
the midst of a frightful tumult. "No! no!" was heard on all sides.
"No beatification. St. Germaine cures us when we are sick; that is
enough. She belongs to us. We wish to keep her."

The brief for the beatification of Germaine Cousin was issued by


the order of his holiness Pius IX., on the 1st of July, 1853.

The Triduo which was held at Pibrac, in 1854, in honor of this


event, manifested the joy and the faith of the people. Altars,
lighted up by the bright sun of France, were erected in the fields
once trod by the feet of Germaine, so that hundreds of Masses
could be offered at once. The whole country around poured in.
Toulouse seemed vacated. There were eighty thousand persons
assembled around that shrine. On the first day there were fourteen
thousand communicants. In the procession were eighteen hundred
young ladies robed in white. They all held white lilies in one hand,
and wax tapers in the other, and as they entered the church and
passed the altar, they deposited their tapers on one side and their
lilies on the other. Conspicuous in the procession were those who
had been healed by the intervention of the holy shepherdess.
Lights were in their hands, and they made an offering of gratitude
at the altar.

The house in which the blessed Germaine had lived was


endangered during those days of religious triumph. It was in a
tolerable state of preservation, but every one seemed anxious to
secure a portion of the walls that once sheltered her, and especially
of the spot sanctified by the angel of death.

A resident in the south of France at the time of the beatification of


Saint Germaine, as she was even then, with one accord, called in
that country, I was forcibly impressed with the enthusiastic
veneration and confidence with which she was regarded by all
classes. Every week I heard of some new miracle at her tomb; so
they soon ceased to excite wonder, and seemed to belong to the
established order of events. There was scarcely an individual in my
circle of acquaintance who had not been, at least once, to prostrate
himself at her shrine, and there was a lively faith in her protection,
which proved to me how strongly the spirit of the middle ages still
animates the hearts of the faithful.

So popular a devotion was a novelty to me—a "native


American"—but I could not long remain insensible to its influence.
One misty October day found me likewise an humble pilgrim at the
shrine of the holy shepherdess of Pibrac.

The very air of that antique chapel inspires devotion. A


supernatural influence seemed to impregnate everything around
me. I saw, too, that I was not the only one who felt this subtle
influence penetrating to the very heart; for the faces of all the
pilgrims, priests, religious, and laymen of every rank who are
constantly arriving and departing, were indicative of a holy awe.
Though I got there at a late hour, and it was raining, Masses were
still being celebrated, and the church was full. It was no festival. It
was so every day. Masses were said at every altar from early dawn
till the latest canonical hour. Prostrate groups from different
parishes were always there, clustered in the nave, or gathered
about the shrine; and here and there were lone pilgrims who, like
me, had been brought from the ends of the earth. And around and
over all were constellations of brightly burning tapers, emblematic
of the prayer of faith, left there by the pilgrim as loth he slowly left
the hallowed sanctuary.

The tomb of Saint Germaine is in a side chapel, protected by a


grate. Her relics are covered with gold and silver and precious
stones, ex votes, which gleam in the light of the votive candles
around. Involuntarily there comes to the heart in this fitting place,
and to the lips, the strain, Exaltavit humiles!

"Lord, behold, he whom thou lovest is sick!" is the cry of every


weary, sin-laden heart; above all here, where thou dost love to
display thy goodness and thy power. The sacred heart of thy
humanity, ever touched with feeling for our infirmities, is not
hardened. It is still as tender and as compassionate as when thou
didst weep over the grave at Bethany, and thy hand is as powerful.
I believe that thou, who art honored in thy saints, dost heal here
both soul and body of those who approach thee with faith and with
love, especially with love. "Many sins are forgiven her, because she
hath loved much," was uttered centuries ago, but has been
repeated times without number since, over penitent, loving souls. O
power of love over the divine heart! It is only the cold, the feeble
in faith, who have no power to draw from this inexhaustible well of
compassion.
If every Catholic heart were, as it should be, a chapelle ardente,
all aflame with the love of God, how soon would the spiritual
infirmities of entire humanity be healed, and the wounds of Christ's
bleeding body be bound up!

Reader! let the aspiration of divine love, indulgenced by our


sovereign pontiff on the 7th of May, 1854, in honor of the
beatification of Germaine Cousin, be often on our lips and in our
hearts: "Jesu, Deus MEUS, AMO TE SUPER OMNIA!" Jesus, my
God, I love thee above all things!
From The Latin Of Prudentius.
An Elegy.
Aurelics Prudentius Clemens, the glory of the early Christian poets,
was born in Spain in the year 348. He studied eloquence in his
youth under a celebrated master. He was twice made governor of
provinces and cities, raised to the highest rank, and placed at the
court by the Emperor Theodosius I., next in dignity to his own
person.

But in the vigor of his age, he quitted worldly honors and


employments, made a pilgrimage to Rome, and thence returning to
Spain, led a secluded life, consecrating his leisure to the
composition of sacred poems. He is esteemed the most learned of
the Christian poets, and, for the sweetness and elegance of his
verses, has been compared to Horace.
Venient citò saecula, quum jam
Socius calor ossa revisat,
Animataque sanguine vivo
Habitacula pristina gestet.

Quae pigra cadavera pridem


Tumulis putrefacta jacebant,
Volucres rapientur in auras,
Animas comitata priores.

Quid turba superstes inepta


Plangens ululamina miscet?
Cur tam bene condita jura,
Luctu dolor arguit amens?

Jam moesta quiesce querela,


Lacrymas suspendite matres,
Nullus sua pignora plangat:
Mors haec reparatio vitae est.

Sic semina sicca virescunt


Jam mortua, jamque sepulta,
Quae reddita cespite ab imo
Veteres meditantur aristas.

Nunc suscipe, terra, fovendum,


Gremioque hunc concipe molli;
Hominis tibi membra sequestro,
Generosa et fragmina credo.

Animae fuit haec domus olim


Factoris ab ore create;
Fervens habitavit in istis
Sapientia, principe Christo.
Tu depositum tege corpus;
Non immemor ille requiret
Sua munera fictor et auctor,
Propriique aenigmata vultûs.

Veniant modò tempora justa,


Quum spem Deus impleat omnem;
Reddas patefacta necesse est,
Qualem tibi trado figuram.

Non si cariosa vetustas


Dissolverit ossa favillis,
Fueritque cinisculus arens,
Minimi mensura pugilli;

Nee si vaga flamina, et aurae


Vacuum per inane volantes
Tulerint cum pulvere nervos,
Hominem periisse licebit.

Translation.
The hour is speeding on amain
When back into its olden form,
Once more with ruddy life-blood warm,
The spirit shall return again.

The freed soul soars aloft through space:


So, dust with dust, aloft through air,
This heavy clay swift gales shall bear
From its sepulchral resting-place..

Why doth the crowd surviving fill


The air with a lamenting vain?
Why with such idle griefs arraign
The justice of the Eternal will?

Oh! end these pangs with murmurs rife,


O mothers! cease your tears, your woe;
Weep not for your dead children so,
Death the renewal is of life.

The dead, dry seed lies hid from view,


To burst forth to new glorious bloom;
The former beauty to resume,
The ancient harvest to renew.

O earth! in thy soft bosom keep,


And quicken with new warmth this clay,
This sacred frame to rest we lay.
It smiles in thy embrace to sleep.

'Twas once the immortal spirit's cell.


That breath breathed from the lips divine;
Here was the living wisdom's shrine,
Here deigned the Christ supreme to dwell.
Guard it beneath thy faithful sod,
For He, one day, will re-demand
From thee this labor of his hand.
This breathing likeness of its God.

Oh! for the appointed hour to rend


The grave! the hope God gives is sure:
Safe, beauteous, through these gates obscure
What now descendeth shall ascend.

Yes, though this frame divinely planned


Be wasted by decay and rust,
And naught left save a little dust.
The filling of the smallest hand:

Though these strong sinews ashes be


On wandering breezes wafted wide,
Inviolate ever shall abide
The mortal's immortality.

C. E. B.
Translated From Der Katholik.
The Ancient Irish Church.
The history of the ancient Irish church, for many reasons, claims
our respectful attention. In the time of the migration of the
European races, this church had a great mission to accomplish
among the Germanic tribes. When the Goths had overrun Spain,
the Franks and Burgundians conquered Gaul, the Anglo-Saxons
invaded Britain, the Vandals spoiled Africa, and the Lombards
gained strongholds in Italy; when the Alemanni and Sueves had
penetrated into the valleys and claimed the mountains of ancient
Helvetia; who was it in those stormy times that elevated the moral
condition of those peoples, drew them out of the darkness of
German paganism, or converted them from Arianism; regenerated
them internally, civilized and incorporated them into the kingdom of
God, after they had devastated the provinces of the Western
empire, leaving ruins, deserts, confusion, and desolation behind
them in their plundering march? It was the missionaries of the
ancient Irish church that rescued Europe from the barbarism of that
period. Evidently sent by God, those Irish missionaries founded new
Christian colonies in different lands, hewed down the forests,
civilized the deserts, founded churches, schools, and monasteries.
As the Roman empire without the barbarians was nothing but an
abyss of slavery and rottenness, so would the barbarians have been
a wild chaos without the monks. The monks and barbarians
combined produced a new world which we call Christendom.

Germany also owes much to the missionaries of the ancient Irish


church. In the olden time Ireland was called the "island of saints
and sages;" as her people in our days receive from us the
honorable title of "martyr-nation of the west," for their inflexible
fidelity to their faith during three centuries of shameless and brutal
persecution. "No one but God in heaven knows the number of the
saints whose dust is mingled with Irish soil," wrote one of the
oldest Irish writers, the biographer of St. Ailbe of Emly. We count,
not by hundreds, but by thousands, the holy Irish bishops, abbots,
priests, monks, and virgins. Even in the days of St. Patrick, and still
more after his successful apostolate, Ireland was not only a great
training-school for foreign missionaries, but a second Thebais, in
which the exercises of the spiritual life were thoroughly practised,
and where students could devote themselves in solitude to the
study of philosophy and holy writ under the ablest professors. Pious
men went from Britain, from the European continent, from France,
and even from Rome, to the classic and holy "island of saints," to
learn the doctrines of Christian perfection, literature, and theology,
in the renowned monasteries of the land of Columba and
Colombanus.

Even to this day Ireland is specially favored by God. There are no


snakes in it or other venomous reptiles. The very dangerous portion
of the animal kingdom is entirely excluded from its sacred ground;
and all attempts to naturalize poisonous creatures there have been
unsuccessful. The old Irish rhyme reads:

"St. Patrick was a holy man,


He was a saint so clever,
He gave the snakes and toads his ban,
And drove them out for ever."

Throughout Ireland there are great fields of wheat and grain of


every description, and many lakes. The climate is mild, and snow
so rare that cattle can graze in the fields all the year round. Rain
showers are frequent, and give such fertility and verdure to the soil
as no other land in Europe possesses, so that the island is known
as "Green Erin," or the "Emerald isle." The plants, flowers, and
trees of Ireland, in their shape, color, and material, remind one
somewhat of Normandy in France, or of Asturia in northern Spain.
The History of the Ancient Irish Church has been just
presented to the public by an author who is in a better condition
than most of his contemporaries to write such a work, which
charms us more and more the more frequently we read it. We
speak of the recent work of the Bishop of St. Gall, Dr. Charles John
Greith, in which we recognize one of the greatest efforts of German
historical literature. We cannot, therefore, refrain from imparting to
our readers an epitome of the contents of this remarkable and
highly interesting production. The right reverend author considers
his work of four hundred and sixty-two pages as an "Introduction
to the history of the Bishopric of St. Gall." He published the book
on the commemoration and centenary of the consecration of the
cathedral of St. Gall, August 17th and 18th, 1867, and dedicated
his literary effort to the chapter and the clergy of his diocese. From
early youth the distinguished author has been familiar with the
legends and history of St. Gall, and studied them with love and
veneration. Love for that great Irish missionary saint, whose worthy
successor Dr. Greith is, inspired the work whose continuation we
desire most earnestly. "St. Gall has left behind him a world-wide
reputation as the apostle of the Swiss Alps. Centuries have not
diminished his fame, which the gratitude of Christians sanctions."

Veneration for St. Gall has been spread far beyond the boundaries
of Switzerland; from the foot of the Alps to Upper Burgundy and
Alsace, even to the limits of the Vosges; then into Brisgau and the
Black Forest, to the Suabian Alps, and thence into Nibelgau, and
Algau. In all these regions, the monks of St. Gall imparted the
blessings of religion and education. Full of admiration for the
Christian zeal of St. Gall and his disciples, our author recalls the
words spoken by Ermenreich of Reichenau, to Abbot Grimald of St.
Gall, over a thousand years ago: "How could we ever forget the
island of Ireland, from which the rays of Christian light and the sun
of Christian faith have shone upon us!" Taking this expression for
his motto, the right reverend writer gives us his magnificent
History of the Ancient Irish Church and its Connection with
Rome, Gaul, and Germany.
Divided into six books, the work describes in the two first the
migrations of the barbarians and the fall of the Roman empire;
then the heresies which swarmed in the church of the period; then
the school of the island of Lerins, where St. Patrick, the apostle of
Ireland, was instructed. The four last books are consecrated to St.
Patrick and his apostleship in Ireland; to St. Columba, the apostle
of Scotland; to St. Colombanus and his deeds in France, Flanders,
and the north of Italy; and to St. Gall, the apostle of Germany. The
sixth and last book treats of Christianity and its customs in the Irish
church.

The illustrious author made use of manuscripts as well as printed


works in the compilations of his history. Many manuscripts were at
his disposal in St. Gall itself. The original sources of ancient Irish
history consist of different materials; genealogies which trace the
origin of kings or saints and their relatives; annals which give the
year of the death of saints, or of other distinguished characters;
church calendars which give the day of the month on which the
death of a saint occurred; and finally, the lives of the saints
themselves. These biographies are copiously used. We cannot
restrain our desire to quote what the author thinks of those sources
of history. "Erudition is not sufficient for us to judge the biographies
of the ancient saints; we must have sympathy with them in their
zealous labor; and a spiritual relationship in their faith. Every age
must be judged according to the ideas, and customs which prevail
in it; and every saint according to the circumstances in which he
lives." The poetic as well as the historical element, the legendary as
well as the authentic, must be combined in forming a correct
estimate of a saint's character.

Even in the early part of the middle ages, every cathedral church,
large monastery, or distinguished hermitage, possessed its
hagiographers, who wrote the lives of the saints of the place, either
from authentic written documents, traditions, or from knowledge
acquired as eye-witnesses. Since John Moschus published his
collection of legends, extraordinary diligence in the criticism and
sifting of the ancient biographies of the saints has been manifested
in the church. The collection and critical works of the Bollandists, of
Lurius, Mabillon, d'Achery, and others, keep their reputation
undiminished to the present day. These writers display such a
thoroughness in their researches, that the modern rationalists have
been unable to find a flaw of any consequence in their criticism.
The truthful historian must describe those apostles of religion and
civilization among the Germans, such as they were, children of their
century, representatives of its ideas, views, and manners. Following
this method, he will not cast doubt on the purity of their motives,
or try to lessen their merit in drawing entire nations of barbarians
out of the darkness of paganism and immorality into the light of
Christianity and virtue. The blind party spirit of our times recognizes
no justice, and modern paganism is only satisfied when it can
throw everything that is noble and holy out of history. The modern
pagans tear with scorn the Holy Scriptures into shreds before our
eyes, and subject to a lawless criticism the ablest records of
ecclesiastical history, while they try to overturn every monument
that might shelter the weary pilgrims of earth on their road to
heaven.

II.

The most trustworthy documents regarding the first traces of


Christianity in Ireland, inform us that up to the time of Pope
Celestine I., (a.d. 422-432,) that country had not been converted.
Up to the year of our Lord 432, no Christian missionary had
trodden the soil of the island, or caused the light of faith to shine
over the hills and through the valleys of green Erin. Palladius and
Patrick were the first apostles, (A.D. 430.) It is true, several High-
Church English writers have endeavored to prove the establishment
of an Irish church prior to St. Patrick; but this theory is
unsupported by any authentic documents. Besides, the attempt of
those writers was prompted by the partisan desire of proving an
original separation in belief between Ireland and Rome.
Nevertheless, it is not improbable that many non-commissioned
Christians may have gone from Britain and Gaul into Ireland before
the year 430, and formed small communities, or lived scattered
among the heathens. "On the wings of every day commerce, the
flower-seeds of Christian faith must have been borne to Erin from
Britain and Gaul; as from the earliest times direct business relations
were kept up between Nantes, other harbors of Armoric Gaul, and
Ireland. To the north-west of Gaul also came the Irish rovers, under
the guidance of some distinguished chieftain, in quest of plunder,
and frequently carried off Christians into captivity. In this way St.
Patrick, when a youth of sixteen years of age, was taken from the
coast of Armorica by the pirates of King Niall, and with many
thousand others detained in bondage, as he informs us himself in
his writings," (p. 86.)

Besides the fact that there was no Irish church prior to St. Patrick,
though there may have been individual Christians in the country,
we must prove that the Christianity imported into Ireland was
Roman, and that her apostles received their mission from the pope.
Pope Celestine, in the year 431, sent Palladius, deacon or arch-
deacon of the Roman church, as the first missionary. This apostolic
man, who had long been casting his eyes toward Britain and the
other western islands of Europe, had a double and very important
task to execute in Ireland, namely, to strengthen the dispersed
Catholics in the faith, and to evangelize the heathens. He landed in
Hay-Garrchon, penetrated into the interior of the country, baptized
many, built three churches in the province of Leinster; but, taken
altogether, his mission was unsuccessful, and he met with much
opposition. "But when Palladius understood that he could not do
much good in Ireland, he wanted to return to Rome, and died on
the voyage, in the territory of the Picts. Others say that he received
the crown of martyrdom in Ireland."

What Palladius begun—but which God's providence willed to remain


incomplete—Patrick accomplished in sixty years of apostolic labor.
Him God chose as the instrument, and fitted him for this holy work.
That he received his commission from Rome from the hands of
Pope Celestine, A.D. 432, cannot be doubted; for the fact is
confirmed by a crowd of witnesses, both Roman and Irish. We
must, therefore, consider and reverence Patrick as the apostle of
the Irish people.

All the early Irish annalists unanimously agree that his mission
began in the year 432, and that he died in 493—an apostleship of
sixty years! How great and glorious for him and for his people!

Patrick was born A.D. 387, in Boulogne-sur-Mer, in modern Picardy,


and was of noble Roman origin. In his sixteenth year, in a
marauding expedition of an Irish clan called Niall, he was carried
prisoner to Armoric Gaul; thence to Ireland, and there sold to a
pagan officer named Milcho, whose swine he herded for six years.
After this, he escaped, and returned to his native land. Having fully
determined to consecrate himself to the service of God, he went to
Marmontiers, the monastery of St. Martin of Tours, to study there
the principles of Christian science and perfection. A few years after,
he visited the happy island of Lerins, near Marseilles, at that time
one of the most famous schools in Christendom, and met there, as
fellow-students, the holy monks Honoratus, Hilary, Eucherius,
Lupus, and others. An interior voice there told him that he should
return to Ireland to preach the Gospel in that country; and he
therefore travelled from Lerins to Rome, in order to represent to
the holy see the darkness of heathenism which brooded over
Ireland. But, as the apostolic see was not then in a condition to
provide for the Irish mission, Patrick went back to Gaul, and
remained with St. Germain of Auxerre, under whose guidance he
made further progress in holiness and learning. Such was his life up
to the year 429.

In this year he accompanied Bishop Germanus and Lupus to Britain,


who were sent by the pope to root out Pelagianism in that country.
Thus was Patrick prepared for his apostleship.
It was then he heard of the mission of Palladius, and its failure.
(A.D. 431.) The holy Bishop Germanus cast his eyes on Patrick,
who knew the Irish language, people, and country from personal
observations. Did he not seem peculiarly fitted—sent, in fact, from
heaven, to undertake the conversion of the Irish nation?

Patrick, therefore, with the priest Legetius as his companion, went


to Rome, and received from Pope Celestine his blessing and the
necessary authority to undertake the task of converting Ireland. It
is hard to tell now whether he was consecrated bishop by Celestine
before his departure, or by Bishop Amatorex, of Eboria, a city in
north-western Gaul. He reached Ireland in the first year of
Celestine III. A life of continual triumphs began for him. He was
repulsed from the coast of Dublin: no matter; he sailed for Ulster,
and landed at Strangford. He converts the chieftain Dicho and his
whole house, and celebrates his first Mass in Ireland in a
neighboring barn. At the royal city of Tara, he meets King
Leoghaire, with all his clan; defends and explains Christianity in
their presence, and gains a victory over the Druids. Dublach, a
Druid and poet, is converted, and sings, for the future, only hymns
in the honor of the true God. The daughters of the king, Ethana
and Fethlimia, also bow to the yoke of the Gospel, and consecrate
their virginity to God, and many other holy women follow their
example. Thus, a happy beginning was made in the island.

Soon the converts number thousands. Everything succeeds; the


conversion of the Irish people was effected without persecution or
martyrs. Patrick frequented the national assemblies, and used the
occasion to preach to the multitudes. He destroyed idolatry and
idolatrous practices throughout the whole land, and built churches
to the living God on places that had hitherto been dedicated to the
worship of idols. Wherever he went, he baptized crowds of men,
provided the new Christian communities with churches, made the
most virtuous of his disciples priests and bishops, and appointed
them to govern the faithful, and extend the reign of the Gospel.
Thus did he labor year after year, going about preaching, baptizing,
and blessing, in Leinster, Ulster, Munster, and Connaught; and
everywhere his astonishing activity and self sacrifice effected
wonderful results. Everywhere the people were ready and docile for
the reception of Christianity. Divine Providence wonderfully
protected him from all danger.

But when the whole island was converted to Christ, congregations


formed, and churches erected in all parts of the country, St. Patrick
thought of building a metropolitan cathedral for the primate of
Ireland. He chose for this purpose the heights of Admarcha, or
Armagh, near which stood the old royal fortress of Emania. After
the building of his cathedral and the conversion of the Irish, St.
Patrick passed the remaining years of his life partly at Armagh,
partly at his favorite spot at Sabhul, where he began his missionary
career. He assembled a few synods, wrote his Confession, as it is
called, on the approach of death, and was attacked by his last
illness at Sabhul. When he felt his end approaching, he collected
his remaining strength, and endeavored to go to Armagh, which he
had chosen as the place of his burial; but, warned by a voice from
heaven, he returned to Sabhul, and died there eight days after, on
the 17th of March, 493.

III.

Let us now glance at the disciples and followers of this great man.
They followed up his work with such zeal and indefatigable activity
that, at the end of the sixth century, Christianity was spread over
all Ireland. We distinguish, in the Irish church, "Fathers of the First
Order," and "Fathers of the Second Order." The holy men from
Rome, Italy, Gaul, and especially from Wales or Cambria, who
followed St. Patrick as their leader, and aided him in his labors, are
the "Fathers of the First Order." Patrick brought with him from
Rome, in the year 432, nine assistants; in the year 439,
Secundinus, Auxilius, and Iserninus, were sent to him from Rome.
The two former of these, together with Benignus, were present as
bishops at the first synod of Armagh, in the year 456. Bishop
Trianius, a Roman, another disciple of St. Patrick, imitated so
exactly the life of the great apostle, that his food was nothing but
the milk of one cow, which he took care of himself. The first mitred
abbot of Sabhul was Dunnius; and the first bishop of Antrim was
Leoman, Patrick's nephew. The oldest Irish bishops appointed by
Patrick, were Patrick of Armagh, Fiech of Sletty, Mochua of
Aendrun, Carbreus of Cubratham, and Maccarthen, of Aurghialla.
Seven nephews of St. Patrick, who followed him from Cambria, are
invoked in the Irish litanies as bishops. They are the sons of
Tigriada, Brochad, Brochan, Mogenoch, Luman; and the sons of
Darercha, Mel, Rioch, and Muna. When the heathen Anglo-Saxons
conquered Britain in the year 450, and sought to destroy the old
British church, many learned and pious men fled to Ireland, and
joined Patrick. Thirty of them were made bishops, and devoted
themselves to the special task of converting the neighboring
islands. The most renowned of these Welsh missionaries are
Carantoc, Mochta of Lugmagh, and Modonnoc, who introduced the
rearing of bees into Ireland, where they had never been seen
before. Three companions of St. Patrick—Essa, Bitmus, and Tesach
—were expert bell-founders, and makers of church-vessels. The fact
that Patrick was sent from Rome, that his first assistants were
Romans, and that his co-laborers from Gaul and Britain were sons
of the Roman church, completely destroys the Anglican hypothesis
of an Irish church independent of Rome. Even Albeus, who, on
account of his services, was called the second Patrick, Declau, and
Ihac, the apostles of the Mumons; Enna, or Enda, the founder of
the great monastery of Aran; Condland, Bishop of Kildare, all
disciples of St. Patrick, were educated and consecrated bishops in
Rome. There also were Lugach, Colman, Meldan, Lugaidh, Cassan,
and Ciaran, consecrated and afterward numbered among the
earliest bishops and fathers of the Irish church.

From the time of St. Patrick, continual communication was kept up


between Rome and Ireland by countless pilgrims, as many
documents attest, (Greith, p. 142-156.) Patrick left his love and
reverence for the Apostolic See of Peter as a precious legacy to his
immediate disciples; and they, in turn, to their successors up to the
present day. The frequent pilgrimages of Irish bishops, abbots, and
monks, are facts so well proven, that the Anglican theory of a
separate Irish church is shown to be a pure invention, no longer
contended for as truth by any respectable historian.

Let us now pass to the fathers of the second order in the Irish
church, and their illustrious foundations. The founders of those
numerous Irish monasteries, which counted their inmates by
hundreds and thousands, those men who were mostly brought up
by the immediate successors of St. Patrick, belong to the "Second
Order of Irish Fathers." Twelve of them, instructed by the renowned
Abbot Finnian, at Clonard, are called the twelve apostles of Ireland.
At their head stands Columba, the apostle of the Picts, shining
among them like the sun among the stars. Their names are,
Columba, of Iona, Corngall, of Bangor, Cormac, of Deormagh,
Cainech, of Achedbo, Ciaran, of Clonmacnoise, Mobhi, of
Clareinech, Brendan, of Clonfert, Brendan, of Birr, Fintan, Columba,
of Tirgelass, Molua Fillan and Molasch, of Damhs-Inis. These holy
men erected all over Ireland and in the adjacent isles churches and
convents, which became centres of art, learning, and sanctity. The
monastery of Clonard, founded in Meath by Abbot Finnian,
contained during his lifetime three thousand monks. At
Clonmacnoise, a monastery founded by St. Ciaran, in the middle of
Ireland, agriculture was made a special study; and Monastereven
on the Barrow, Monasterboyce in the valley of the Boyne,
Dearmach, etc., were renowned institutions. These first and oldest
Irish monasteries were not large, regularly-built houses, but
composed of numbers of separate cells or huts, made of wicker-
work, stalks, and rushes. The church or oratory stood in the midst
of the huts, and was made of the same material. It was at a later
period that the Roman architecture was introduced into Ireland;
and then stone edifices took the place of the primitive structures.
Special mention is always made in the Irish annals of the erection
of a stone church, for the people preferred wooden buildings, and
their preference shows itself up to the twelfth century. The stone
churches were looked upon as the fruit of foreign architecture, as
St. Bernard informs us in his life of St. Malachy. The Roman church
gradually introduced into Ireland the fine arts and a higher order of
architecture, as she had done at an earlier date in Gaul and Britain.
Choral singing became usual. The church hymns took the place of
the Druidical rhapsodies; and the muses of Inisfail forgot to sing of
heroes, and learned to tune their harps to sing the praise of Christ
and his saints.

The Irish missionaries reclaimed barren lands and made them


fertile, ameliorated the condition of agriculture, spread commerce,
and discovered new islands in the sea. Many of the Irish saints, at
the period of which we are writing, were great navigators.

Dr. Greith paints in glowing colors the life of St. Columba and his
labors in Ireland, the Hebrides, and Scotland, as well as the
discipline and rules of the Abbey of Hy, which was founded by him.
We cannot enter into details, but refer the reader to Dr. Greith's
book. Columba was born on the 7th of December, 521. In the first
half of his life, Ireland was the scene of his zeal; the second half
was spent among the Scots and Picts. In Ireland he founded
Durrow, Derry, and Kells. He went with twelve disciples to
Caledonia in the year 563. Christianity among the Scots had
degenerated; and the Picts were still pagans. The king of the Picts,
Brudrius, gave him the island of Iona or Hy, where his works began
which God crowned with wonderful success. He soon became the
beacon light for all the faithful priests and laity of Ireland and
Caledonia. He visited Ireland to counsel his noble relatives, settle
their disputes, or oversee the churches and monasteries which he
had established, and travelled among the Picts preaching the
Gospel, founding monasteries, and erecting churches which should
consider Iona as their mother. He built thirty-two churches, to most
of which monasteries were attached, in Scotland; and eighteen
among the Picts, in the space of thirty-three years, (563-597.) Even
during his lifetime he was so celebrated that, from all sides,
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!

ebookultra.com

You might also like