0% found this document useful (0 votes)
7 views

Linux Game Programming Wcd Prima Techs Game Development 1st Edition Mark Collins download

The document is a promotional and informational piece about the book 'Linux Game Programming' by Mark Collins, which is part of the Prima Tech's Game Development series. It includes links to download the book and other related resources, as well as details about the book's content and structure. Additionally, it provides information about the publisher and various contributors to the book's production.

Uploaded by

ninejaokeene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Linux Game Programming Wcd Prima Techs Game Development 1st Edition Mark Collins download

The document is a promotional and informational piece about the book 'Linux Game Programming' by Mark Collins, which is part of the Prima Tech's Game Development series. It includes links to download the book and other related resources, as well as details about the book's content and structure. Additionally, it provides information about the publisher and various contributors to the book's production.

Uploaded by

ninejaokeene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Linux Game Programming Wcd Prima Techs Game

Development 1st Edition Mark Collins download

https://ebookbell.com/product/linux-game-programming-wcd-prima-
techs-game-development-1st-edition-mark-collins-11359432

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Programming Linux Games 1st Edition Loki Software John R Hall

https://ebookbell.com/product/programming-linux-games-1st-edition-
loki-software-john-r-hall-922874

Cross Platform Game Development Make Pc Games For Windows Linux And
Mac Wordware Game Developers Library 1st Edition Alan Thorn

https://ebookbell.com/product/cross-platform-game-development-make-pc-
games-for-windows-linux-and-mac-wordware-game-developers-library-1st-
edition-alan-thorn-1320158

Minecraft The Unlikely Tale Of Markus Notch Persson And The Game That
Changed Everything Daniel Goldberg Linus Larsson Translated From The
Swedish By Jennifer Hawkins

https://ebookbell.com/product/minecraft-the-unlikely-tale-of-markus-
notch-persson-and-the-game-that-changed-everything-daniel-goldberg-
linus-larsson-translated-from-the-swedish-by-jennifer-hawkins-53017170

The State Of Play Creators And Critics On Video Game Culture Daniel
Goldberg

https://ebookbell.com/product/the-state-of-play-creators-and-critics-
on-video-game-culture-daniel-goldberg-48904176
Linux Command Line And Shell Scripting Bible 4th Edition Richard Blum

https://ebookbell.com/product/linux-command-line-and-shell-scripting-
bible-4th-edition-richard-blum-46090968

Linux The Complete Reference Sixth Edition 6th Richard Petersen

https://ebookbell.com/product/linux-the-complete-reference-sixth-
edition-6th-richard-petersen-46145398

Linux Basics For Hackers Occupytheweb

https://ebookbell.com/product/linux-basics-for-hackers-
occupytheweb-46410142

Linux Allinone For Dummies 7th Richard Blum

https://ebookbell.com/product/linux-allinone-for-dummies-7th-richard-
blum-46498774

Linux User Developer Issue 141 Gavin Thomas

https://ebookbell.com/product/linux-user-developer-issue-141-gavin-
thomas-46964020
EIMT SERIES
CD-INCLUDED

FRDGRfllYllYllNG

5v-iT!ir-iLJM i_ inT

Andre LalVlothe
CEO Xtreme Games LLC
Tr~" J|
f

Linux" G-hiyi-e
PRDGRfllYllYllNG

PRIMA TECH'S
C-HEC-K THE UlEE fDR UfDflT€5
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.

5end Us Your Coiyiiyients


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.

Hauu 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. For individual orders, turn
to the back of this book for more information.
Tr-"

Linux G-rfyi
Prdgra m nm n g
lYlflRK "Nurgle" Collins

PRIMA TECH'S

A DIVISION OF PRIMA PUBLISHING


Linux Cs-hm-e Progrfhyiiyiing

© 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 system 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 and the Game Development series are trademarks of Prima
TECH Communications, Inc., Roseville, California 95661.

Publisher: Stacy L. Hiquet


Associate Marketing Manager: Jennifer Breece
Managing Editor: Sandy Doell
Acquisitions Editor: Jody Kennen
Project Editor: Heather Talbot
Technical Reviewer: Zach Slater
Copy Editor: Alice Martina Smith
Interior Layout: Bill Hartman
Cover Design: Prima Design Team
Indexer: Johnna VanHoose Dinse
Proofreader: Fran Blauw

Linux is a registered trademark of Linus Torvalds.

OpenGL is a registered trademark of Silicon Graphics, Inc.

Loki and OpenAL are registered trademarks of Loki Software, Inc.

Important: Prima Publishing cannot provide software support. Please contact the appropriate
software manufacturer's technical support line or Web site for assistance.

Prima Publishing and the author have attempted throughout this book to distinguish proprietary
trademarks from descriptive 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 omissions 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-3255-2

Library of Congress Catalog Card Number: 00-1 10735

Printed in the United States of America

00 01 020304 II 109 8 765 43 2 1


Linux G^me FROGR-HnnnmNG

dntentb at a cL

Glance
1 N TR DDUCT1DN XXXI

CHflFTER 1

Introduction to Griyie DevELOFmENTiii.nl


CHAPTER S
Linux Development Toole 11

CHAPTER 3
The Structure of a G-hme EH
CHAPTER H-

ED Graphics Under Linux E3


CHAPTER 5
Input ujith 5DL i53
Linux Game FRaGRfimiYnNG

CHAPTER E
3D Grafhicb for Linux Gflmes B7
CHAPTER 7
r^ Using OfenGL in Games 117

CHAPTER B
Bound Under Linux 1H-7

CHAPTER 3
Networking 1B3
CH^^T^K ID
Artificial Intelligence 137
CH^JPTE.^ 11
DFENSDURCEB PR1END OR FOE?
APPENDIX A
Dfen5durce License Agreements S l
+3
APPENDIX E
Porting E73
Linux Gaiyie -FRaG-R-HiYiiYnNG vn

APPENDIX C
REf£RENC€5 E3 3
APPENDIX D
Globb-rry SD7
APPENDIX E
UUhatIs on the CD-RDIY1 .313

Index 315
Linux Gaiyie -PROGRAmmiNG

Jl

Jn
Linux G-hiyi-e PRciG-R-HpnnmNG

Contents Q^

Introduction xxxi
CflflFTER 1

Introduction to Gaiyie Develdpiyient 1

What Makes a Game? 2


Different Game Genres 2
Shoot-em-ups 2
Strategy Games 3

Simulations 3

Platform Games 3

Puzzle Games 4
Adventure Games 4
Role-Play Games 4
Card Games 4
Sports Games 4
What Makes a Successful Game? 5

The Game-Development Process 6


The Design Document 6
Development 7
Testing 7
Linux Gaiyie FRDGRflmiYiiNG

Releasing Your Game 8


1 OpenSource Games 8
Commercial Games 9
n Shareware Games 10

CHAPTER S
Linux Develop ment Tools ill

Development Tools 12
Compiler 12

Debugging Tools 15

Development Environments 18

Libraries 20
Simple DirectMedia Layer 20
OpenGL 21
libXIl 21

Other Libraries 21

CHAPTER 3
The Structure of a Gaiyie E3
The Parts of a Game 24
A Game Framework 24
Linux Gaiyie FROGRfliYimiNG

CHAPTER H-

ED Graphics Under Linux 23


n
The SDL API 30
Starting Up SDL 30
Creating a Window 32
Creating a Surface 33
Drawing a Bitmap Image 35
Drawing Directly to the Screen 36
Pixel Formats 36
Plotting Pixels 38
Using Palettes 39
Cleaning Up 40

The Xlib API 40


Creating a Window 41
Drawing to the Screen 43
Plotting a Pixel 43
Drawing Images 45
Double Buffering 47
Installing Color Maps 48
Cleaning Up 49

The SVGAlib API 49


Switching to a Graphics Mode 50
Drawing to the Screen 51
Linux Gaiyie FRDGRflmmiNG

Displaying Images 52
Tl Understanding the PCX Format 52
Displaying the Image 55
n Using Color Palettes 56
Cleaning Up 57

A Mini-Project 57

CHAPTER B
Input uht+h 5DL ..«53
Understanding Input Devices 60
Keyboard 60
Mouse 61

Joystick 61

Handling Methods 62
Event Queues 62
Polling 62

Using the SDL Event Queue 63


The SDL_Event Union 63
Layout 63
Interpreting Event Types 64
Reading from the Event Queue 64
Keyboard Events 68
Mouse Events 76
Joystick Events 78

Polling with SDL 83


Polling the Keyboard 83
Polling the Mouse 84

Configuring the Control System 84


Linux G-nnn-E FRDGRfiiYiiYiiNG

CHAPTER E
r
3D Graphics for Linux Gflmes B7
n
Some History: Mesa and OpenGL 88
What Is OpenGL? 88
Where Can Get OpenGL?
I 89

Buffers, Hidden Surface Elimination, and Animation 90


Getting Started 91

Compiling and Linking with OpenGL 93

Let's Draw Something! 93


Drawing Polygons, Lines, and Points 94
Drawing in 3D: Perspective and Movement 96
Perspective and the Projection Matrix 98
Drawing in Orthographic or Perspective Mode 100
Code That Moves the Object 101

Texturing and Other "State" Elements 1 02


The GL_CULL_FACE Option 104
The GL_LIGHTING Option 104
The GL_TEXTURE_2D Option 105
The GL_COLOR_MATERIAL Option 105
The GL_BLEND Option 105
The GL_ALPHA_TEST Option 105
The GL_DEPTH_TEST Option 1 05

Lighting 106
Specifying the Lighting Qualities of the Object 106
Establishing the Light Source 1 07
Setting Up Surface Normals 1 08
XIV Linux Gaiyie PROGRflmmiNG

Texturing the Model 110


1 Loading the Texture Image Ill

MIP Mapping the Image 112


Jl
Applying the Texture 113

Transparency and the Alpha Component 114


Solving Transparency Problems 115
Fogging 115

CHAPTER 7
Using DfenGL in Gaiyieb 117
Understanding Display Lists 118

Understanding Vertex Arrays 119

Drawing with Triangle Strips and Fans 1 20


Adding Text 121

Understanding Matrices 1 22
Working with Plane Equations, Line Equations,
and Distances in 3D 1 24
Using Billboards to Simulate 3D 1 26
Working with Particles 1 29
Detecting Collisions 1 29
Simplify the Shapes You Test 130
If the Objects Are Close, Test Again 131

Follow Surface Contours 1 32


m Linux G-riyi-e FROGRflmmiNG XV

The Next Layer: Scene Graph APIs 132


Field-of-View Culling 133 r
State Management 1 34
Scene Graphs 135 n

Moving the Camera 138

Advanced Lighting 139

Putting It All Together 1 40

CHAPTER B
Bound Under Linux 14-7
Open AL 148
A Simple OpenAL Application 148
Initializing and Loading Samples 148
Creating Listeners 1 50
Loading a Sound File 151

Creating Sound Sources 1 52


Playing Sounds 153
Getting the State of the Sound 153
Stopping Sounds 1 54
Deleting a Source 1 54
Moving the Source 1 54
Compiling the Sample 155
Advanced OpenAL 155
Volume Control 1 55
Velocity and Doppler Shift 156
Reverb and Echo 157
Streaming Buffers 1 58
Linux Gaiyie FKDGRflmmiNG

SDLAudio 159
Starting an Audio Session 1 59
Loading Samples 1 62
Using the Audio Callback Function 1 63
Playing a Sample 1 63
Pausing the Audio Stream 1 64
Cleaning Up 1 64
Mixing Different Samples 1 64

CD Audio 165
Using the i octl ( ) Function 1 65
Opening the Device 1 66
Getting a Track Listing 1 66
Playing a CD 1 67
Tracks and Indices 1 67
Some Code 1 68
Stopping a CD 1 68

3
C-H-R-PT-E-R
Networking IB 3
Introduction to Modern Networking 1 70
Peer-to-Peer Networking 1 70
Client/Server Networking 171

The TCP/IP Stack 171


TCP 171

UDP 172

$
Linux Gaiyie -P-RaG-R-RiYiiYiiNG

Socket Programming 1 72
Opening a Socket 1 72 Ir

Connecting the Socket 1 73


Sending Data 1 75
Opening a Socket as a File Stream 1 75
Using the send ( ) Function 1 75
The sendto( ) Function 1 76
A Mini-Exercise 1 76
Receiving Data 1 76
The recvf rom( Function ) 1 77
The select Function
( ) 178
Another Mini-Exercise 1 78
The Complete Mini-Web Browser 1 79
Creating a Server 1 80
Binding the Socket 1 80
Using the 1 i sten ( ) Function 181

Accepting Connections 181

Threads and Networking 1 82


Clients 183
Using Flags to Communicate between Threads 183
Using Message Queues to Communicate between Threads 185
Servers 186
Pings 186

Networking in Games 1 87
Dead Reckoning 187
Sending Controller Inputs 1 88
XVI 11 Linux Gaiyie PRDGRfimmiNG

Lobbies 1 88
1 What Is OpenLobby? 1 88
Using the Lobby Server 1 89
w Connecting to the Lobby Server 1 89
Logging In to the Lobby Server 1 90
FindingGames 191

Creating Games 1 92
Ending Games 1 93
Chatting in the Lobby 1 93
Listing Chat Rooms 1 93
Joining and Leaving Rooms 1 94
Sending Chat Messages 1 95
Cleaning Up 1 95

Security Issues 1 96
Buffer Overflows 1 96
Denial-of-Service Attacks 1 96

CHAPTER ID
flRTificifiL Intelligence 137
Basic Artificial Intelligence 198
Route Finding 1 98
State-Trees 1 98
Generate the State-Tree 1 99
Modify the Tree to Accommodate Multiple Routes 200
Search the Tree 200
The Nurgie Method 203
Linux G-hiyie FRDGRfliYimiNG xix

Grouping 205
Problem Solving 206
Trial and Error 206
Min-Max Trees 207
The Theory Behind the Tree 207
Putting It into Practice 209

Advanced Artificial Intelligence 212


Genetic Algorithms 212
Memes 213
The Genebot 213
Neural Networks 219
Artificial Neural Networks 220
Changing the Behavior of the Network 223
Personality 223

CHAPTER 11
OfenEourceS Friend or Foe? iSE5
What Is OpenSource? 226
Unlimited Redistribution 227
Ability to Charge for Expenses 227

The Development Models 227


The Cathedral 227
The Bazaar 228
Linux Gaiyie PRDGRfiiYiimNG

Reasons For and Against OpenSource 229


ll Ten Reasons to Use OpenSource 229
Peer Reviews 229
I
Security 229
Available Code 230
Free Software, Free Information 230
Many Developers 230
I Fame 230
The Community Aspect 23
Availability of the Software 23
The Cause 23
Because You Like It 23
Ten Reasons to Write Closed-Source Software 232
Money 232
Paranoia 232
Plagiarists 232
New Technologies 233
Contracts 233
Selfishness 233
The "He Didn't, So I Won't" Attitude 233
Politics 233
Ego 234
Security through Obscurity 234
The Middle Ground 234
Free Code, Private Data 234
OpenSource Later 235
Limited License 235
Key Technologies 236
1

Linux Gaiyie fROGRfliYiiniNG

The Indrema Debate 236


Big Red Warning 237 lr

Emulators 238
Time-Share 238 H

Registered Testers 238


The Solution 238

Which License to Use? 239


Viral Licenses 239
Open Licenses 240
Custom Licenses 240
Liability 24

R-F-P-END1X fl

Dpen5durce License Agreeiyiente h.E43


GNU General Public License 244
GNU Lesser General Public License 250
BSD License 259
Artistic License 260
Mozilla Public License 262
The Apache Software License 270
MIT License 271
XXII Linux Gfime FRDGRflimmiNG

w
flFFENDIX B
-Porting
Porting Strategy
273
275
Try Not to Fork the Codebase 275
Getting Started 276
#ifdef Is Your Friend 277
The Harder Stuff 277
First Light 278

Compiler Issues 278


Visual C/C++ Improper Scoping in for Loops 279
GCC Code Size 279
Mixing Signed and Unsigned Types 280
Assignment from void* 280
GCC Doesn't Complain About Missing Return Values 280
GCC Doesn't Complain About Use of Uninitialized Variables 281
GCC Is More Strict About Implicit Casting 281
Include Filenames 282
Struct Packing 282

File System Issues 283


Case Sensitivity 283
Drive Letters and Path Separators 284
Line Termination 285
File Attributes and Home Directories 286

Assembly Language 286


Operand Order 287
Naming
Register 287
Opcode Naming and Operand Size 287
1

Linux G-nm-E PRQGRfiiYiiYiiNQ XXlll

Immediate Values 288


Addressing Modes 288
Endianess 288

Windows Issues 289


Wi nMa i n ( ) and Message Loops 289
Timers 290
The Registry 29
Hungarian Notation 29

Graphics Issues 292


DirectDraw 292
DOS Frame Buffer 292
Direct3D 293
Coordinate Systems 294
Polygon Winding 294
Texture Management 294
OpenGL Extensions 295

Sound Issues 295


Networking Issues 295
Winsock 295
File and Socket Handles 296
Include Files 296
Return Codes 296
Different Calls 297
DirectPlay Is Evil 297

Useful Links 297


Footnotes 298
Linux Gaiyie FROGRflmmiNG

fIFFENDIX C
1
References 239
II

Web Sites 300


GameDev.Net 300
GamaSutra 300
Flipcode 300
Happy Penguin 30
Indrema Developer Network 301
Linux Games 301
Linux Game Developer Resource Centre 301

Books 302
II OpenGL Super Bible (The Red Book) 302
OpenGL Reference (The Blue Book) 302
Graphics Programming Black Book 302
Game Architecture and Design 302
TCP/IP Illustrated (Volume 2) 303
Linux Device Drivers 303
Game Development Series 303

Magazines 304
Game Developer Magazine 304
Develop 304
Edge 304

Newspapers 305
Computer Trade Weekly 305
MCV 305
Computer Weekly 305
Computing 305
Linux G-rhi-e -P«OG«-HrYirYnNG

Newsgroups 306
Mailing Lists r
306

flFFENDIX D
Glossary .3D7

flFFENDIX -E

UU+HflT^S ON THE CD-RDIY1 313


Running the CD-ROM with Windows 95/98/2000/NT 314
Running the CD with Linux 314

Index 315
Linux Gaiyie -PROGRAmmiNG
Linux Gaiyie FRQGRfimmiNG

Jl

RCKNDU1LEDGIY1ENT5
First of all, I'd like to thank my co-authors, Ben Campbell, and Martin Donlon, for taking
Steve Baker,
time out of their busy lives to help complete this book on time. If it weren't for their support, this book
may not have happened at all. I'd also like to thank all the guys and gals at Prima Publishing, namely
Jody Kennen and Heather Talbot, as well as Andre LaMothe (who may one day forgive me for not
speaking at the XGDC).
A big shout goes to all the staff and regulars at up with my ever-inflating ego
GameDev.Net for putting

and for not banning me from the message boards. (Although if they did, who'd run the Linux forum?)
In the same breath, I'd like to say "hi" to all the lame software pirates in the Syndicate of London,
namely Paris, Llama, Comrade, and Cronus (I shall enjoy watching you die, Mr. Anderson), and to all

the 133t people at #hackerzlair on DALnet.

A big thanks to my ex-ex-ex-ex-ex-ex-ex-ex-ex-ex-girlfriend, Sima, for supporting me throughout this lit-

tle adventure (when we weren't arguing), and to all my friends from Bath, many of whom owe me
large quantities of alcohol.

In true hacker fashion, these acknowledgments wouldn't be complete without a list of shouts. So in no
particular order, shouts to: ShinyEyedMermaid, JerryLee, TheHermit, Nurse, Mistress Demonica,
nes8bit, pouya, Myopic Rhino, jhky, TANSTAAFL, JadeFalcon, Dulie, Paris, Comrade, Llama, A cronus A ,

A Maryjayne, the guys and gals at


Infinity Matrix, Fwaggle, DysfunksiOn, Trax, Lockpick, Laura , all

Silicon Dreams (especially Lara, she's hot), Gumby, Trev, Ruth, Puppy, Mike, Lil' Chris, Roper, Amy,
Jonsey—and last, but not least, Invisible Bob (the unofficial Indrema mascot).

The Infamous Mark "Nurgle" Collins, [email protected]

Lead Author, Linux Game Programming


Linux G-riyi-e P-ROG-R-HmmiNG

Author -Bio
The Infamous Mark "Nurgle" Collins, the teenager with an ego that dwarfs Texas, has worked in just
about every area of the IT industry, from Web design to network consultancy, but one field has repeat-
edly attracted his expertise and outside-the-box thinking. That area is game development.
In addition to all his hobbyist involvement, Mark has worked for one of the largest developers in

Europe, and he acts as a freelance consultant to various commercial developers all over the globe.
Having skills in networking, AI, and graphics, he believes that games should be fun, rather than yet
another Quake clone.
Linux G-nm-E FRDGRfimiYnNG

am t-h
1 Editor
Dear Reader,

A long time ago, in a cubicle far, far away, UNIX was created. UNIX has shown itself

to be a reliable and robust platform for workstations, mainframes, and even PCs.
But, UNIX had never really gained much momentum on the PC platform for anv-
one other than the power user or technically minded. However, the time has come
when the PC version of UNIX, named Linux, has begun to make major in-roads
into the average user's home, and game programmers are taking notice! Now is the
time that gamers and developers alike want to play and develop games for Linux.
However, Linux, like UNIX, wasn't a simple platform to learn to program games
for — until now...

Linux Game Programming is without a doubt one of the most ambitious game pro-
gramming books ever written. There are so manv aspects to basic Linux program-
ming, it boggles the mind to even begin to think about writing 2D 3D games for
Linux. But, I can sav that Linux Game Programming does it all. The author. Mark
"Nurgle" Collins, starts from square one setting up the compiler, explaining the
tools and libraries of Linux, and covering general game programming theory.

This book is not just a bridge for Windows game programmers who want to learn

how to port to Linux, but an entire treatise on game programming on the Linux
platform. This book covers it all! .And I mean evervthing-from 2D and the SDL
(Simple DirectMedia Laver) to open GL and full 3D game programming.

In conclusion, this book sets the standard for Linux game programming and will

definitely be a jewel in vour game programming library

.^Q%&^
Andre LaxMothe
March 2001
Linux Gflme FROGRflmnmNG
Linux Gflm-E FROGRfliYiiniNG

lNTRDDUCTlDN
j
I ell, it's been a long time coming, but now there is finally a book on Linux game program-
^^^J ming. With the growing interest in both the commercial and desktop uses of the free Linux
operating system, it was only a matter of time until people started thinking about writing games for it.

Sure, many people have written little games in the past, such as x^7/and xboing (and a plethora of titles
starting with the letter x), but only in recent years have games that are almost commercial quality been
available for Linux.

With companies such as Loki porting successful titles such as Descent 3 and SimCity 3000, it's only a mat-
ter of time until software houses start developing original titles for the Linux platform. With the immi-
nent launch of the Indrema console, a Linux-based system, that future is set to become a reality.

But what is Linux? In 1991, a student in some country in Scandinavia made an announcement on a
message board with this immortal line: "I'm working on a minix-based operating system; it won't be as
big as the GNU project, though." (I'm paraphrasing here.) Since then, the "small" operating system
that was never going to be as big as the GNU project has grown to several million users worldwide, with

uses ranging from enterprise Web servers to games consoles.

Linux is a semi-POSIX-compatible, UNIX-like operating system that runs on almost every platform
available today, ranging from i386s to PalmPilots. Until the past few years, however, few people consid-
ered using Linux as a desktop environment, but with projects such as KDE and Gnome paving the way,
more and more people are wiping out Windows and switching to one of the many Linux distributions
available.

lYlv Jdyb wit-h Linux


I first played with Linux in 1994, running an old version of Slackware on a CD-ROM. .After finding that
the version of Doom included with that program refused to get past the title screen, I started looking for
other games on the CDs XWindows working back then). That's when I discovered
(I couldn't get
Abuse, the classic side-scrolling platform game with a rather innovative feature: You aim with the mouse

while moving with the keyboard. I was impressed with this feature but knew it wasn't going to last.
Linux Gaiyie FRDGRfliYiiYiiNG

After a few weeks, I tried to install a few things from the CD, but horror struck! I was running on a
UMSDOS partition, co-existing with Chicago (later renamed Windows 95). A broken installation pro-
ll
gram wiped out all the partitions on my hard disk completely, without even having the courtesy to ask
first.
n
A few years later (and after the phenomenal success of Spong, a DOS, which really bad Pong clone for

everyone in my school became addicted to), I decided to try Linux again. So I popped down to the
shop and bought a RedHat boxed set, and I was away. After a few problems getting XWindows running
in anything higher than standard VGA, everything ran perfectly. I was happily playing around with
stuff, reconfiguring files here and there, setting up security, and so on. But I never actually used it.

Why? Because there was nothing to do. Every time I wanted to play Dungeon Keeper, I would reboot into
Windows and load it from there.

After some time, I did start playing some of the Linux games that were in existence, but none of them
really impressed me. So I started looking for ways to write my own games. I downloaded SDL and start-

ed playing around with it. Then the worst thing in the world happened: I got a job. Working on server-
side Java for Web sites, I had no time for personal projects. Soon I moved up to network consultancy
and still had no time for games. About a year after that, however, things changed.

I was looking for a career change, and boy did I find one. Within a week after sending my curriculum
vitae to an agency, I had an interview at Silicon Dreams. And I got the job. I stayed in that job until
December 2000, at which point I decided to write this book full time. (I was fired.)

While I was at Silicon Dreams, I learned many things (one of which was to not annoy Microsoft;
they'll complain to your boss if you do). One of the most important things I learned is this: No one
in the "professional" industry cares about Linux development — at least officially, that is. Many of
my co-workers at Dreams were closet die-hard Linux fans; as soon as they found out that I was writing
this book, I had the sudden urge to kill many of them.
As unlikely as it may seem, the small project that was never destined for big things may actually become
a hardcore gaming platform. I, for one, would like to see that happen.
1j-" \i

CHAPTER I

Introduction
TO GflFYl
D-EV-ELO-FIY1-ENT
Linux G-nm-E FRDGRflinmiNG

f
Listen my children, for I will tell a tale of a quest for glory, an adventure most heroic. A long time
ago, in a place far away, a young man sat in front of a magic box and decided to give something
to the world. He spent many moons working on his creation. And when it was complete, he looked
upon his creation and saw that it was good. This creation was a computer game. (After this he went
down to the pub for a few drinks because he really needed a good night out.)
i

LU-Hf=IT IY1-RK-E5 -R GfllYlE?


Why is a game different from any other type of application? There are several major differences:
Games more input and output devices than other applications. Games generally run
generally use
faster than normal applications and make use of a lot of CPU time. The differences between games

and other software are recognized by large software developers such as Microsoft and have forced
these companies to create additional tools to allow developers to access the hardware directly.

Let's compare a game to a word What do you do in a word processor? You type stuff in, add
processor.

a bit of formatting, stick in some random comments for your editor to have a chuckle over, and save
the file. But in a game, a lot more is involved. You have to update the screen as many times as possible
during a single second. You need enemies reacting to the player's actions, you need a goal to achieve,
and most important, the game has to be fun.

Different G-Hm-E Genres


There are many different types of games on the market, ranging from shoot-em-ups to strategy, from
card games to simulations. Although some genres are generally more popular than others (such as
first-person shooters), others have much more playability (such as card games).

bHDDT"€fn-U
The shoot-em-up type of game is probably one of the most popular game genres at the moment. This
category includes games such as Quake and Unreal Tournament. There are several types of shoot-em-up,
ranging from first-person perspective to scrolling games such as Defender. Most games in this genre have
but one goal: to kill anything that moves, from a shotgun to space ship.

Many newer shoot-em-ups have multiplayer capabilities, while others are written only for use as
multiplayer games (for example, Quake HI: Arena). These games have come under a lot of fire from the
media in recent years and have been blamed for the Columbine shootings.
Introduction to Gflme Dcvelopiyient

Games of this genre generally have very little in the way of a storyline —who needs an excuse to kill the
alien invaders? Although some games make an effort to craft a story, original stories are harder to
come up with these days.

Many games based on films fall into this category, such as Die Hard Tribgy and Alien versus Predator. [

5T-R-RT-EGY GflfYlES
d_
There are two types of strategy games: real-time and turn-based. Games such as Command and Conquer,

StarCraft, and Dune are real-time, whereas the hugely successful Civilization series is turn-based.

Real-time strategy games generally consist of two or more sides battling it out for an area of land. These
games usually require the mining of raw materials to build new structures and units. These games are
nearly as popular as shoot-em-ups but require a lot more time to play (a single level of Command and
Conquer can take several hours of playing before it's completed) Consequendy,
. it takes a lot of patience
to play these games, and they can become very frustrating.

Games that require the building of a civilization, such as Sid Miers Civilization, tend to be turn based.
Turn-based games can be played for days on end with only regular cups of coffee to keep you going.
Turn-based games allow a player to move all of their units before allowing the other players to have
their turns.

5llYlULflTlDN5
Any game that attempts to simulate a real event is a simulator, be it a flight simulator or a fishing game.
These games are designed to emulate real life as much as possible, allowing the users to gain

experience in areas they wouldn't normally get a chance to experience.

Some simulators are used for training, such as the Concorde simulator at British Aerospace Filton in

the United Kingdom. This multimillion-dollar computer game emulates the real behavior of the

aircraft exacdy (except that they won't let you barrel roll it). A few years ago, I had the opportunity to

browse through the source code for the simulator (written in Assembler) — all several million lines
worth of code! Accurate simulators are big projects and are not suited for the weekend programmer.

PLflTfORm GfllYlEB
Some of the most successful games ever have been platform games, such as the Mario series. This genre
consists of a character moving around on a level that usually scrolls from side to side, but that in more
recent years has become a full three-dimensional environment, with the character jumping around like
a hyperactive frog on anti-depressants.

Many people new to games development choose a platform game as one of their earlier projects

(usually after a few puzzle games). This is because platform games are generally uncomplicated from
the developer's point of view and can result in hours of entertainment for the player.
Linux GfimE P-ROG«flrYimiNG

FUZZLE GfllYl€5
There are probably more puzzle games in the world than any other type of game. Puzzle games are
very easy to code and can be very addictive for the player. This type of game requires very little in the

way of artificial intelligence and tends to be relatively small compared to games from other genres that

require large numbers of external data files to run.

Examples of puzzle games include Tetris and Minesweeper. These games require patience and planning
to win. Like strategy games, puzzle games can get very frustrating over time.

RDV-ENTU-R-E G-HIY1-E5
Adventure games run the gamut of complexity, from the text-based Zork to the full 3D Tomb Raider.
This genre usually consists of the main character interacting with various NPCs (Non-Player
Characters) to achieve a goal, whether that goal is up with a sexy
rescuing a lost artifact or hooking
babe (as in Leisure Suit Larry, by Sierra). These games tend to be highly immersive and can suck away
many days of life from a dedicated adventurer.

Rdle-Flay GfllYl€5
Similar to adventure games, role-play games often involve going on a quest of some description, but
tend to be a lot more open ended. Players can spend years building up a character, giving it a
personality, and collecting a large stash of cash.

Some RPGs (Role-Play Games), such as Ultima, used very simple graphics but proved
of the earlier
highly successful, and some are still played today. Multiplayer RPGs have traditionally been text-based
MUDs (Multi-User Dungeons), but some of the more recent games have been graphical, such as
Ultima: Online and EverQuest.

Card Gflm-ES
Everyone has played Solitaire or FreeCell. These card games tend to be played when the user is waiting
for something to be done or is on the phone with an annoying customer. Card games can become very
addictive; I know some people who wouldn't get out of bed if it weren't for FreeCell

5FDRT5 GfllYlE5
Another highly successful game genre is the sports genre. Here in the United Kingdom, every gamer
out there has played at least one soccer game, one racing simulation, and at least one beat-em-up.
Some of the first games ever created fall into this genre (Pong being very similar to a game of tennis
without any nets).
.

Introduction to Game Developitient

Games such as the FIFA series are always bestsellers, and with good reason. They bring out the
competitive instinct in the player and allow the user to kick ass without actually hurting anyone. Many
H
a time my brother challenged me to a quick game of Actua Soccer, and many a time I won (and many a
time he beat me up for winning)

Sports games are generally highly addictive and can lead to large tournaments among groups of
friends. People like sports, and they like them even more if they don't have to get injured in the
process.

WJ-H-HT IYlflK€B -H 5 UCC-E55-FUL GfllYIE? J


This is a tough question because everyone has different opinions about what makes a game good, but
there are always some common factors. Successful games are always (and most important) playable.

Nobody likes to play a game where you have to type for ten minutes just to get a square to move one
pixel to the left.

The game also needs to have a user-friendly interface, with easy-to-navigate menus that get the player
into the game as soon as it loads. Continuing from this, a good game should be very easy to learn but
should take a lifetime to master. A good example of this criterion is Street Fighter. Anybody can play the
game well, but very few are really good at it. This is because the game controls are intuitive; randomly
hitting them allows even a new player to win a fight against a master. However, a master can learn the

special moves and use them to their full effect.

Some games have overly complex control systems, such as Alien versus Predator. This game had too
many controls to master before you could get into the game. This meant only a dedicated gamer could
play it for more than five minutes without deleting it from the hard disk out of frustration. Having to
constantly jump around the keyboard just to select a gun and fire it puts most players off for life.

Another key requirement to the success of some games (although not all) is a good plot. It's all very

well to run around killing ever)' goblin in sight, but why are you killing them? Did they murder your
second-cousin's pet cat? Or are you just killingthem because they are there to kill? Even a simple
background story can contribute a huge amount to the game's success, even if the actual story has no
relevance to the game itself.

Good story lines don't have to be predictable to be interesting. Take, for example, the film From Dusk
Till Dawn. Half the film is about two criminals trying to get to Mexico, when suddenly, out of nowhere,
they are attacked by a hoard of vampires. This surprising twist made the film much more interesting.

Games with sudden plot twists have done very well. A good example of this is Wing Commander III, in

which the Kil'rathi pilot who defected changes sides halfway through the story, even though he showed
complete loyalty to the Terran struggle.

Sometimes, being a well-known game developer means that all your games will be a huge success, even
if there is nothing special about your project. A good example of this condition is Doom 2, the sequel to
Linux G-riyi-e F-ROG-R-RiYinmNG

the highly successful Doom. There weren't any brand-spanking new features or a supersmart AI system

in this sequel to the successful Doom game, but people like id software, and they will buy
their games.

However, fame has a price. People are more than willing to jump on any bugs in a game from a

successful developer, while a lesser-known developer might manage to sneak a few "inconsistencies"
past the critics.

T4H-E GflfYl-E-D-EV-ELO-FIYl-ENT PRDCE55


Game development, like any form of software engineering, isn't a simple code-it-and-you' re-done
process. There are several stages to go through to get your game from the drawing board to being
played.

T+h-e Design Ddcuiyient


A good design document is probably the most helpful tool for any game developer. It helps you
develop a solid idea on which you can base your game. The design document can also help you get a
publisher if you choose to write a commercial game (as explained later in this chapter).

What goes into a design document? Just about everything from the story line to the 3D engine you're
going to use. Some design documents are several hundred pages long and cover every single detail in
the game; simpler games can use shorter design documents. Even the smallest documents should
contain the following:

• General Overview. This section of the document covers the game story line, the main characters, a basic

overview of the development timeline, and the development staff required.

• Screen and User Interface. This section of the document covers the in-game menus, the in-game HUD
(Heads-up Display) you might use, as well as any icons used in the game.
• Art Specification. This section of the document lists any in-game artwork, cut-scenes, and sprites. Include
any appropriate storyboards and sketches.
• Sound and Music. All sound effects and music must be documented in this section, as well as any voice
talents the game will need.
• Technical Specification. This section covers how the game is going to run, including flowcharts and any
benchmarking you plan to perform.

• Legal Information. This section includes the copyright and a disclaimer.

After you have written your design document, you should share it with everyone on the development
team so that they can give you feedback on your ideas. You will probably get through several versions of
the design document before you all agree on what it contains, but that isn't a bad thing. The revision
process will help form new ideas from old ones and might point out some serious problems that might
otherwise occur only later in the development process.
Introduction to G«iyi-e Develdfiyient

DeveLa-pmeNT
IT
After your team has agreed on a design, you can actually get to work on writing the code. But where do
you begin? Do you write the game engine or the menus first? And which part of the game engine?
have to make when new project, but n
Where to start is one of the toughest choices you'll starting a

fortunately, you have a design document.

One of the best places to start when writing your game is at the beginning.mean that you
I don't
should write the whole thing in order, from intro sequence to closing mean that you should
credits, I

start where the program starts: the initialization routine where you prepare any variables you may need
or fire up any graphics APIs you use. Without this vital part of the program, you can't do anything.

WTiere you go from there is up to you, but I like to continue by developing the graphics engine. This
allows me to code the core of the game next, but does make it difficult to add or modify features later

in the development process.

If you are on a team that is developing a large project, you will need a way of sharing files. E-mail is a
fine exchange medium if everyone is working on completely separate parts of the program and you
have a clearly defined interface to work with. How ever,
T
if you have problems with version concurrency
you might want to look into a CVS (Concurrency Versioning System) repository. A CVS repository
allows multiple developers to work on the same problem by checking files in and out of a "repository."
I'll go into further detail about CVS options in Chapter 2, "Linux Development Tools."

Testing
One of the most important steps in the development process is testing your funky new game. If anv
serious bugs show up after you release the game, your reputation will be ruined. Frontier II: First

Encounters is a good example of incomplete testing resulting in a buggy release (although I can't reallv
place the whole blame on the developers). Because of a tight deadline, the program wasn't fullv tested

and several major bugs caused serious problems in the game. These bugs seriously damaged the
reputation of the developer, even though it had created Elite, one of the most popular games ever.

There are several stages to testing your game, commonly referred to as Alpha, Beta, and Gamma
testing phases. The Alpha testing stage done by the developers, in which they fix any obvious bugs
is

and glitches they find wiiile writing the code. Beta testing is performed by a third partv (usuallv a
dedicated gamer) who will try to find any of the hidden bugs; finally, Gamma testing is performed by
the general game playing community. When a bug is found in the game, chances are you will hear
about it. WTien you do, you try to reproduce the problem and then generate a patch to fix the

program.

When it comes to testing, one of the most useful tools you can create is a debug cheat. A cheat allows
you to jump to any part of the game, gives you any extras you need (such as cash, weapons, or bonus
points) , and can save you hours of time. Because all cheats are removed before the game is released
Linux G-riyi-e FROGRfHYinniNG

(honest), there are some funky tricks you can use to enable or disable them at compile time using
preprocessor directives.

If your compiler allows a flag to add a symbol at compile time, you can use that flag to specify a release

type, depending on whether the code you are compiling is a debug or release version of the game. For
example, you can include the following code in your game program.

// test.c
//include <stdio.h>
main ( ) {

#ifdef DEBUG
puts("This is a debugging version!");
#el se
(
puts " Th i s is a release version");
#endi f

If you then compile the program with the following command and run the program, you should get
This is the release version.

gcc -o testl test.c

However, if you include the -DDE BUG option on the command line, as shown in the following

command, the program will output the line This is a debugging version!

gcc -DDEBUG -o test2 test.c

This trick allows you to add cheats using #i fdef blocks of code. You can then turn off the cheats when
you are ready to release the game, if you wish. You can also add simple debugging statements in #i fdef
blocks to track the program flow without the use of an external debugger (as discussed in Chapter 2).

R-EL-E-R51NG YOU-R GfllYl€


After you have tested your game as much as is humanly possible, you can release it. You have several

choices about what to do at this stage, and I will discuss three of your options here: OpenSource,
commercial, and shareware.

DP€N5DURC€ GfllTlEB
OpenSource is probably the simplest and quickest route to getting your games on the market. If you
want people to play your game as soon as possible, you can release the game while you're still writing it.

Not only does this approach let people know your game exists long before it's finished, it also lets
other people work with you to help fix any problems they may find or to make suggestions for
improvement.
lNT-RODUCITION TO G-RIYie D€V€LDPIYI£NT

The OpenSource route also means that you'll have a larger number of testers working for free. This
approach can speed up the development process dramatically and might even mean that your game
will be ported to other operating systems by third parties.

Although many people claim that it is impossible to make any money out of OpenSource software, this
has been proved false too many times to count. Companies such as RedHat and SuSE have made a
huge success out of distributing OpenSource
software for years by offering support and printed
manuals. NOTE
Make sure that you don't choose a
The first step to releasing an OpenSource project
license just because everyone else is
is to make it publicly available, including the
using Read through several licenses
it.
source code. After you have made it possible for
(printed versions of which can be
everyone to get your program, make an found in the back of this book) and
announcement on a few mailing lists and on sites choose the one you agree with the
such as Freshmeat (http://freshmeat.net) .
most.

FRE5HrYl£flT: HTTf='!//FRe5HrYieflT.NeT

made your announcement, expect input from users within a very short period of time.
After you have
Some may have patches, others may have criticisms, and others may need help using your game. It is
good practice in the OpenSource community to reply to all e-mail messages you receive regarding the
product; doing so will help you gain a name for yourself in the OpenSource community.

CammERciflL G-riyi-es
Many developers have realized that Linux is a viable option for commercial software, including games.
Companies such as Loki have made a name for themselves by porting successful games; other
companies such as Epic (Unreal) are also starting to develop games specifically for Linux machines.

Getting a game published commercially is not the easiest thing to do, especially for die Linux platform.
The process is long and complicated, involving several contracts, XDAs (Non-Disclosure Agreements),
and tough milestones. However, the rewards far outweigh the costs. Cash advances, high rovalties, and
fame encourage many independent developers to strive for bigger, better, and faster games.

To get published, you must first approach a publisher. Look around at your local Electronics Boutique to

see what publishers are out there. Names and sometimes addresses of games publishers appear on the
packaging of the products you'll see.Be aware that many publishers such as Electronic Arts have in-
house development teams and refuse unsolicited submissions. Look for companies that publish games
from a wide range of developers, such as GT Interactive and ActiVision. When you have determined
who you want to publish your game, request a submission pack from the publisher. This packet will
contain an NDA, which protects all parties involved from any legal problems that may arise (for
example, plagiarism).
Linux CE-fhyi-e P-RDG-R-RmmiNG

When you have returned the NDA with your completed design document —and hopefully a working

demo of your game the publisher will tell you whether it is interested in your submission. If it turns
you down, don't give up. Keep trying until you get a new publisher.

If the publisher approves your game, negotiations will begin. It might be a good idea to contact a

lawyer because legal documents will be involved; unless you are fluent in legalese, the contracts will
probably be a bit confusing.

A good guide to getting your games published has been written by Geoff Howland of Lupine Games.
You can find the guide at http://www.lupinegames.com/articles/getstart.html.

Guide to Getting Your Games Published:


HTTA "//w WW. LUfllNeGflme5.COM/flflTICLe5/GeT5TflRT.flTmL

5+Hfl-R-Eui-H-R-E G-nmes
Another option when it comes to releasing your game is the shareware route. Some of the most
successful games ever, such as Doom and Quake, were released initially as shareware. Releasing a game as

shareware is very similar to releasing a game in the OpenSource route, except that you generally don't
distribute the source code. (Note, however, that id software has now made the source code to Quake
available, although it still requires a license for the in-game data.)

You have several options to choose from when making your game shareware. You can use an honor
system and ask the user to pay you after a certain amount of time has elapsed, or you can restrict the

game in some way (such as only including the first few levels) until the user has paid you for the
complete version.

After you have decided how you're going


money from the users, you have to set a price ($20 is
to claim

usually a good start) and add a message to the game letting the users know where they have to send
the money. In games such as Doom and Quake, a message was displayed when you quit the game, giving
the user registration details. Some games use pop-up messages during the game to get the shareware
message across.

When it comes to distributing your game, you have several options. You can try and have it stuck on
the cover CD of your favorite magazine, or you can upload it to the Internet and have some download
sites such as Tucows (http://www.tucows.com), sending random surfers to get your game. The
possibilities are endless.

TUCOWSl HTTA '//wWW.TUCOWS.COm


CHAPTER 2

Linux
Develdfiyient
Tools

-ol
!:.^S/fts3tlw

-Jlj—l 3

'5»»*Z!5
Linux Gaiyie FRDGRflmiYnNG

nl

Just as every plumber needs a plunger and every surgeon needs a scalpel, game developers have
certain tools they need to create the next hit games. These tools range from development
environments to debuggers and profilers. In this chapter, you'll learn what types of tools make up the
successful game developer's toolkit.

Develofiyient Tools
You will use several key tools when you write any software, including compilers, interpreters, debuggers,
and version management tools such as make. Some tools, such as KDevelop, integrate all of these
utilities into one environment.

Cdiyifiler
The most important tool you will need is a compiler. Without one, your code is about as useful as a

bikini in the Arctic Circle. Although some languages such as bash are not strictly compiled, you will still

need an interpreter of some kind. Because the code in this book is written in C, I will focus on the
GNU C compiler, GCC, available from http://www.gnu.org/software/gcc/gcc.html.

GNU C COnflPlLGR: HTTf '//uJUJUJiGNUiORG/5a<=TUJflRe/GCc/GCC.4HTmL

Compiling with the GCC can be a problem and isn't covered by this book; if you download the source
code that's available for distribution, you should read all the documentation before you begin to use
the compiler. Note, however, that almost all Linux distributions include the GCC as part of the default
installation, so you probably already have the compiler.

The GCC incorporates most of the tools you will ever need into one easy-to-use program. The GCC
includes preprocessors, compilers, and linkers for various platforms (you can cross-compile to a Win32
executable, for example). To demonstrate GCC, copy the following example:
/* gcc-test.c - GCC test application */

main(int argc, char **argv) {

pri ntf (
" Li Number of arguments: %d\n",
ne: %d -
LI NE argc);
printf "Li ne: %d
( First argument: %s\n
-
LI NE argv[l]); , .

pri ntf ("Compiled on %s %s\n" _DATE_, _TIME_); ,

return 0;
(

Linux Developiyient Tools

This simple program demonstrates several features


GCC. To compile this file, use the console
of the NOTE I
command gcc. The command line to compile the
Unless you specify - o < fi 1 ename>,
program is as follows:
the GCC will generate a file called 1
gcc -o gcc-test gcc-test.c a . out in the current directory.

When you run the compiled test program, it will

display a few details about itself, including the date


and time at which it was compiled. This information is supplied by the DATE and TIME macros.
Another useful macro to know is the LINE macro, which contains the current line number being ]
executed (useful for debugging).

The gcc -o gcc-test gcc-test.c command is fine for simple, single-file projects, but what if your
program spans multiple files? If you include the -c option on the command line, the GCC does not
generate an executable file but instead generates a linkable object file. Try the following sample
program. In one file (gcc-funcl .c), type the following code:

/* gcc-funcl. c - GCC function sample */

void f unction( ) {

printfC'Hello world\n");

Before you can call this function (cleverly named f uncti on )), you must have a mai n( ) somewhere. So
let's create a second file (gcc-func2.c) that contains the ma i n ( ) function:

/* gcc-func2.c - GCC function sample */

void f unction( void) ;

main( ) {

f uncti on( ) ;

return 0;

In normal situations, you'd use a makefile for multiple source files, but I'll cover that technique later in
this chapter. For this example, we'll use the command line to compile this two-file program. For each
file you want to compile, you use the -
c parameter. When you want to link the program, you tell the

compiler to use the object files for input instead of the source code, like so:

gcc -c -o gcc-funcl. o gcc-funcl. c

gcc -c -o gcc-func2.o gcc-func2.c


gcc -o gcc-func gcc-funcl. o gcc-func2.o
Linux Gaiyie FRDGRfiiYiiYiiNG

Like any standard compiler, GCC supports multiple warning levels. You set the level with the -
W

command-line switch. It is generally considered good practice to enable all warnings by using the -Wal 1

switch. In addition to warning levels, the GCC also has several levels of optimization. By default, GCC
disables optimization for debugging purposes (0); for release versions of your programs, you will
« probably want to enable A word of warning, however: Full
full optimization with the 03 switch.
optimization may introduce stability problems to your program, so people generally use the 02 switch
instead.

If you're developing for multiple platforms, you may want to make use of the - D switch to define
symbols such as architecture. Chapter contained a simple example of the use of the - D switch to
i enable or disable debugging commands
1

(such as cheats) at compile time. You are not limited to


specifying a single symbol on the command line. In fact, you can specify as many symbols as you like.

The following example demonstrates this:

/* gcc-define. c - GCC command line symbols */

#ifdef LINUX
# ifdef 1386
char *platform = "Linux x86\n";
# else ifdef SPARC
char *platform = "Linux SPARCXn";
# end i f

//else
char *platform = "Unknown\n";
#endi f

main( ) {

pri ntf (pi atform) ;

return 0;

There are three possible options when compiling this program. The first is to add the -
DLI NUX - DI 386

switches to the command line, to add the -


DL I NUX - DSPARC switches, or to add nothing. By now, you
should be able to figure out how to compile this program.

One last set of command-line switches you'll need


to know about are the ones for including libraries
NOTE
and setting include/library paths. When you need
GCC automatically adds 1 i b to the
to link another library to your program, you
start of the library name, so you need
specify -
1 <name> on the command line; for
to specify only the name.
example, -1X11.
; ;

Linux Evei_o-Fm-ENT Tools

If the library you want to use is not on the library search path, use the - Kpa th> switch, or set the

LI BRARY_DI R environment variable to point to the directory in which the library is located. You use a
similar method for includes, except that you use the -Kpdth> switch or the INCLUDE_DIR environment
variable.

Debugging Tools
How many times have you compiled a program with no compilation errors, yet found a strange bug
that was nearly impossible to trace? Personally, I have lost weeks of coding rime tracking down
annoying bugs like this, and only found out what was going on by using my trusty debugger.

There are several debuggers available, but my personal favorite is the DDD/GDB combination. DDD is

available from http://www.gnu.org/software/ddd/, and GDB can be downloaded from


http://www.gnu.org/software/gdb/gdb.html. One of the main reasons I use these two debuggers is

that DDD can render runtime variables into easy-to-read graphs that allow at-a-glance checking of your
variables.

DDD! HTTf S//UJ WLAJiGNU.ORG/50FTUJflRe/DDD/


GD-B: HTTfi//uiWWiGNUiDflG/50FTWflRe/GDfi/GDfiif(Tll1L

To demonstrate the power of DDD and how to use it, let's create a short test program. The following
example should display a simple table of names, except that there is a small and stupid bug that causes
unexpected results.

/* chapter2-l.c - A bad program */


main() {

i nt I = 0, row = 1

/* A simple table of name */


char *string[] = {

"Title", "First name", "Last name",


"Mr", "Mark", "Collins",
"Mr", "Ernest", "Pazera",
"Miss", "Hellen", "Russell",
"Miss", "Joan", "O'Arc",
0, 0. 0):

/* Display table headings */


while (i < 3) {

printf("%s\t". string[i++]

printf ("\n" )
Linux G-riyi-e -F-ROGf^-HnnrYnNG

/* Display table data */


while (string[(row * 3) + i] != 0) {

printf("%s\t", string[i + (row * 3)]);


i++;
I if (1 == 3) /* At end of row */
{

(
pr i ntf " \ n " ) ;

row++;
i = 0;

[ NOTE
This sample program is based on a bug

that I couldn't work out for a week


until someone suggested that I run it

through a debugger. As soon as I real-

When you compile and run this program, you'd ized what I did wrong, I hated myself.

expect it to display a small table of names.


However, good Murphy has struck again, and
ol'

there is something very wrong with this simple program. Time to fire up the debugger.

Before we load DDD, we must compile the program with debugging symbols. This can be done quite
easily by adding the -g option to the gcc command line, as shown here:

gcc -g -o chapter2-l chapter2-l.c

After the program has finished compiling, load DDD and open the new executable file we just created.
The main window should look something like the one shown in Figure 2.1.

Now that we can see our misbehaving program in DDD, we need to find out where the fault is. Let's try

to narrow down the potential areas where the problem could occur. The program displays the table

headers okay, but everything after that is just plain screwed up. If we set a breakpoint on line 20, we
can interrupt the program when things start to go wrong. There are two ways of doing this. The first

one is to type chapter2- 1 . c : 22 in the textboxjust above the code window, the other is to select line 22
(printf "\n" (
) ;) in the code display.

Next, we also want toknow what the values of our two variables (i and row) are. We can see this by
right-clicking the variable names and selecting Display <variable> from the context menu. If we then
click the Run button in the floating toolbox, the program will execute up to line 20. After all these
manipulations, the DDD window should look like the one in Figure 2.2.

The floating toolbox contains several buttons that will be useful in our debugging efforts. The buttons
we will use here are Next and Step. The differences between the two buttons are subde, but important.
When you click Step, the program runs to the next line of the program; if you click Next, the program
continues to the next instruction. If you want to debug a bit of Assembler, for example, you will

probably use the Next button most.


Other documents randomly have
different content
neighbours, for implements and objects of adornment, and the
commerce of an age when fleets traverse the seas, and eventually
ships course through the air, uniting the peoples of all parts of the
world into one great commercial community! We cannot undertake
to delineate all aspects of this development, for the latter includes
the entire history of mankind. Our concern is merely to indicate the
outstanding psychological factors fundamental to the progression of
the later from that which was original, of the more perfect from the
primitive, partly under the pressure of external conditions of life and
partly as a result of man's own creative power.

CHAPTER I

PRIMITIVE MAN

1. THE DISCOVERY OF PRIMITIVE MAN.

Who is the primitive man? Where is he to be found? What are his


characteristics? These are the important questions which here at
once confront us. But they are questions to which, strangely enough,
the answer has, up to very recent times, been sought, not in the
facts of experience, history, or ethnology, but purely by the path of
speculation. At the outset the search was not, for the most part,
based on investigations of primitive culture itself, but took as its
starting-point contemporary culture and present-day man. It was
primarily by means of an abstract opposition of culture to nature
that philosophy, and even anthropology, constructed natural man.
The endeavour was not to find or to observe, but to invent him. It
was simply by antithesis to cultural man that the image of natural
man took shape; the latter is one who lacks all the attainments of
culture. This is the negative criterion by means of which the
philosophy of the Enlightenment, with its conceited estimate of
cultural achievements, formed its idea of primitive man. Primitive
man is the savage; the savage, however, is essentially an animal
equipped with a few human qualities, with language and a fragment
of reason just sufficient to enable him to advance beyond his
deplorable condition. Man in his natural state, says Thomas Hobbes,
is toward man as a wolf. He lives with his fellow-beings as an animal
among animals, in a struggle for survival. It is the contrast of wild
nature with peaceful culture, of ordered State with unorganized herd
or horde, that underlies this conception.
But this antithesis between the concepts of culture and of nature, as
objectively considered, is not the only factor here operative; even
more influential is the contrast between the subjective moods
aroused by the actual world and by the realm disclosed by
imagination or reason. Hence it is that the repelling picture of
primitive man is modified as soon as the mood changes. To an age
that is satiated with culture and feels the traditional forms of life to
be a burdensome constraint, the state of nature becomes an ideal
once realized in a bygone world. In contrast to the wild creature of
Thomas Hobbes and his contemporaries, we have the natural man of
Jean Jacques Rousseau. The state of nature is a state of peace,
where men, united in love, lead a life that is unfettered and free
from want.
Alongside of these constructions of the character of natural man,
however, there early appeared a different method of investigation,
whose aim it was to adhere more closely to empirical facts. Why
should we not regard those of our human institutions which still
appear to be a direct result of natural conditions as having existed in
the earliest period of our race? Marriage and the family, for example,
are among such permanent cultural institutions, the one as the
natural union of the sexes, the other as its necessary result. If
marriage and family existed from the beginning, then all culture has
grown out of the extension of these primitive associations. The
family first developed into the patriarchal joint family; from this the
village community arose, and then, through the union of several
village communities, the State. The theory of a natural development
of society from the family was first elaborated by Aristotle, but it
goes back in its fundamental idea to legend and myth. Peoples
frequently trace their origin to an original pair of ancestors. From a
single marriage union is derived the single tribe, and then, through a
further extension of this idea, the whole of mankind. The legend of
an original ancestral pair, however, is not to be found beyond the
limits of the monogamous family. Thus, it is apparently a projection
of monogamous marriage into the past, into the beginnings of a
race, a tribe, or of mankind. Wherever, therefore, monogamous
marriage is not firmly established, legend accounts for the origin of
men and peoples in various other ways. It thinks of them as coming
forth from stones, from the earth, or from caverns; it regards
animals as their ancestors, etc. Even the Greek legend of Deukalion
and Pyrrha contains a survival of such an earlier view, combined
with the legend of an original ancestral pair. Deukalion and Pyrrha
throw stones behind them, from which there springs a new race of
men.
The thought of an original family, thus, represents simply a
projection of the present-day family into an inaccessible past.
Clearly, therefore, it is to be regarded as only an hypothesis or,
rather, a fiction. Without the support which it received from the
Biblical legend, it could scarcely have maintained itself almost down
to the present, as it did in the patriarchal theory of the original state
of man to which it gave rise. The Aristotelian theory of the gradual
origin of more comprehensive organizations, terminating in the
State, is no less a fiction; the social communities existing side by
side in the period of Greece were arbitrarily represented as having
emerged successively in the course of history. Quite naturally,
therefore, this philosophical hypothesis, in common with the
corresponding legend of the original family, presupposes primitive
man to have possessed the same characteristics as the man of to-
day. Thus, it gives no answer at all to the question concerning the
nature of this primitive man.
When, therefore, modern anthropology made the first attempt to
answer this question on the basis of empirical facts, it was but
natural to assume that the characteristics of original man were not
to be learned from a study of existing peoples, nor, indeed, from
history, but that the data for the solution of the problem were of a
prehistoric nature, to be found particularly in those human remains
and those products of man's activity that have been preserved in the
strata of the earth's crust. What we no longer find on the earth, so it
was held, we must seek under the earth. And thus, about six
decades ago, prehistoric anthropology began to gather material, and
this has gradually grown to a considerable bulk. Upon the
completion of this task, however, it appeared, as might, of course,
have been expected, that psychology could gain but little in this way.
The only source from which it might derive information lay in the
exhumed objects of art. Then, however, the very disappointing
discovery was made that, as regards implements of stone, drawings
on the walls of caves which he inhabited, and pictures cut into horn
or bone, the artistic achievements of the man of diluvial times did
not differ essentially from those of the present-day savage. In so far
as physical characteristics are concerned, however, the discovered
remains of bones seemed to point to certain differences. While these
differences, of course, were incapable of establishing any direct
psychological conclusions, the fact that the measurements of the
skeletal parts more closely resembled those of animals, and, in
particular, that the measurements of the interior of the skull were
smaller than those of the savages of our own time, offered indirect
evidence of a lower development. Because of the close relation of
cranial capacity to size of brain, moreover, a lower degree of
intelligence was also indicated. Nevertheless, the remains that have
been brought to light have not as yet led to any indubitable
conclusions. There have been fairly numerous discoveries pointing to
races that resemble the lower tribes among contemporary peoples,
and but a few cases in which uncertainty is possible, and concerning
which, therefore, there exists a conflict of opinions. A typical
instance is the history of one of the first discoveries made in Europe
of the remains of a prehistoric man. It was in 1856, in German
territory, that there was discovered, in a grotto or cave in the
Neander valley, near Duesseldorf, a very remarkable skull, though
only, of course, the bones of the cranium and not the facial bones.
All were at once agreed that these were the remains of a very
primitive man. This was indicated particularly by characteristics
which are still to be found, though scarcely in so pronounced a form,
among certain lower races of men. Of special significance were the
strongly developed, prominent bone-elevations above the eye-
sockets. Some of the investigators believed that the long-sought
'homo primigenius' had perhaps at last been discovered. It was
generally agreed that the form of the skull resembled most closely
that of the modern Australian. In more recent years, however,
anthropologists have developed somewhat more exact methods of
measurement and of the reconstruction of a skeleton from parts only
incompletely given. When Hermann Klaatsch, equipped with this
knowledge, carried out such a reconstruction of the Neanderthal
skull, he came upon the surprising fact that its capacity was
somewhat greater than that of the present-day Australian. Little as
this tells us concerning the actual intelligence of these primitive
men, it nevertheless clearly indicates how uncertain the conclusions
of prehistoric anthropology still are. A number of other recent
discoveries in Germany, France, and elsewhere, have proved that
several prehistoric races of men once lived in Europe. Some of these,
no doubt, date back far beyond the last glacial period, and perhaps
even beyond the period preceding this, for we now know that
several glacial periods here succeeded one another. Nevertheless, no
important divergencies from still existent races of men have been
found. This, of course, does not imply that no differences exist; it
means merely that none has as yet been positively detected, and
that therefore the anatomy of prehistoric man can give us no
information concerning the psychological aspect of the question
regarding the nature of primitive man.
Considerably more light is thrown on this question when we examine
the products of human activity, such as implements, weapons, and
works of art. Traces of man, in the form of objects hammered out of
flint and shaped into clubs, chisels, knives, and daggers, capable of
serving as implements of daily use no less than as weapons, are to
be found as far back as the first diluvian epoch, and, in their crudest
forms, perhaps even as early as the tertiary period. The more
polished objects of similar form belong to a later age. Still more
remarkable are the works of art—in particular, the cave pictures of
prehistoric animals, such as the cave bear and the mammoth.
Nevertheless, none of these achievements is of such a nature as to
afford positive evidence of a culture essentially different from, or
lower than, that of the primitive man of to-day. Two outstanding
facts, especially, make a comparison difficult. On the one hand,
wood plays an important rôle in the life of modern primitive man,
being used for the construction of tools, weapons, and, in part, also
of baskets and vessels. But the utensils of wood that may have
existed in prehistoric times could not have withstood the destructive
forces of decomposition and decay. All such utensils, therefore, that
prehistoric man may have possessed have been lost. Thus, for
example, it will be difficult ever to ascertain whether or not he was
familiar with the bow and arrow, since the arrow, as well as the bow,
was originally made of wood. Secondly, there is at the present time
no primitive tribe, however much shut off from its more remote
environment, into which barter, which is nowhere entirely absent,
may not introduce some objects representing a higher form of
civilization, particularly metals and metal implements. If, however,
we bear in mind that, in the one case, products have suffered
destruction and that, in the other, articles have been introduced from
without, the impression made by prehistoric utensils and products of
art—aside from certain doubtful remains dating back beyond the
diluvial epoch—is not essentially different from that made by the
analogous products of the Negritos of the Philippines or the inland
tribes of Ceylon. Though the material of which the implements are
constructed differs, the knives, hammers, and axes in both instances
possess the usual form. Thus, the wooden knife which the Veddah of
Ceylon still carves out of bamboo is formed precisely like some of
the stone knives of the diluvial period. We find a similar
correspondence when we examine the traces of dwellings and
decorations that have been preserved, as well as certain remains
that throw light upon customs. The oldest prehistoric people of
Europe dwelt in caves, just as the primitive man of the tropics does
to-day in the rainy season. In a rock cavern near Le Moustier, in
France, there was discovered a skeleton whose crouching position
points to a mode of burial still prevalent among primitive peoples,
and one which is doubtless always a fairly positive indication of a
belief in demons such as arises in connection with the impression
made by death. The dead person is bound in the position that will
best prevent his return. Thus, all these prehistoric remains suggest a
culture similar to that of primitive tribes of to-day. But, just because
they reveal conditions not essentially different from those of the
present, these remains make another important contribution to our
knowledge of primitive man. They indicate the great stability of
primitive culture in general, and render it probable that, unless there
are special conditions making for change, such as migrations and
racial fusions, the stability increases in proportion to the antiquity.
Though this may at first glance seem surprising, it becomes
intelligible when we consider that isolation from his surroundings is
an important characteristic of primitive man. Having very little
contact with other peoples, he is in no wise impelled to change the
modes of action to which his environment has led him from
immemorial times.
Thus, the correspondence of the prehistoric with that which is to-day
primitive indicates a high degree of permanence on the part of
primitive culture. But, even apart from this consideration, it is
apparent that we must really seek primitive man in the inhabited
world of the present, since it is here alone that we can gain a
relatively accurate knowledge of his characteristics. Our information
concerning primitive man, therefore, must be derived from
ethnology. We must not seek him under the earth, but on the earth.
Just where, however, is he to be found? For decades the natives of
Australia were believed to represent a perfect example of primitive
culture. And, as a matter of fact, their material culture and some of
their mythological ideas still seem to be of a very primitive character.
Because of the conjecture that it was here dealing with a relatively
primitive type of man, modern anthropology has for two decades
applied itself with great partiality to the study of Australian tribes.
English and German investigators have given us many works, some
of them excellent, treating of the continent of Australia, which
appears almost as unique with respect to its population as in its flora
and its fauna. From these investigations, however, which are
reported particularly in the volume by Howitt published in 1900, in
the works of Spencer and Gillen, and, finally, in those of Strehlow, a
German missionary, it is apparent that the Australian culture is
anything but primitive: it represents, rather, a stage of development
already somewhat advanced. In certain respects, indeed, it may
contain very primitive elements, such as are not to be found even
among tribes that are, on the whole, on a lower level. Australian
culture, however, possesses an enormously complex social
organization, and this places it above that which may be called
primitive. In its present form, it presupposes a development of
probably thousands of years. Assuredly, therefore, the Australian
should not be included in a chapter on primitive man. He will rather
claim our attention in the next chapter, as a well-defined type of the
totemic age. Indeed, he is beginning, in part, to lose even the
characteristics of this age, mainly, no doubt as a result of racial
fusion, whose influence is here also in evidence.
Although the races of Australia are unquestionably not primitive, as
was formerly believed and is still held in certain quarters, there are
other parts of the earth which, in all probability, really harbour men
who are primitive in that relative sense of the term which alone, of
course, we are justified in using. If one were to connect the
discovery of this primitive man with any single name, the honour
would belong to a German traveller and investigator, George
Schweinfurth. He was the first to discover a really primitive tribe—
that is, one which remained practically untouched by external
cultural influences. When Schweinfurth, sailing up the Upper Nile in
1870, listened to the narratives of the Nubian sailors in charge of his
boat, he repeatedly heard accounts of a nation of dwarfs, of people
two feet tall (so the exaggerated reports went), living in the
impenetrable forests beyond the great lakes which constitute the
source of the Nile. Schweinfurth was at once reminded of the old
legends regarding pygmies. Such legends are mentioned even by
Homer and are introduced also into the writings of Herodotus and of
Aristotle. Aristotle, indeed, expressly says that these dwarf peoples
of Central Africa exist in reality, and not merely in tales. When
Schweinfurth arrived in the country of the Monbuttus, he was
actually fortunate enough to gain sight of these pygmies. It is true,
they did not exactly correspond to the fantastic descriptions of the
sailors—descriptions such as are current here and there even to-day.
The sailors represented the pygmies as having long beards, reaching
to the earth, and gigantic heads; in short, they imputed to them the
characteristics of the dwarf gnome, who appears also in German
folk-lore. In reality, it was found that the pygmies are, indeed, small
—far below the average normal size of man—but that they are of
excellent proportions, have small heads, and almost beardless faces.
Subsequent to Schweinfurth's discovery, similar tribes were found in
various parts of the earth. Emin Pasha, together with his companion
Stuhlmann, had the good fortune to be able to observe the pygmies
of the Congo more closely even than had been possible for
Schweinfurth. In the Negritos of the Philippines a similar dwarf
people was discovered. They also are of small stature, and,
according to their own belief and that of the neighbouring Malays,
are the original inhabitants of their forests. Besides these, there are
the inland tribes of the Malay Peninsula, the Semangs and Senoi,
and, finally, the Veddahs of Ceylon, studied particularly by the
cousins Paul and Fritz Sarasin. All of the peoples just mentioned live
in forests and have probably been isolated from civilization for
thousands of years. The Bushmen of South Africa, of whom we have
long known, also belong to this group, although they have not to the
same extent been free from the influence of surrounding peoples. In
all these cases we have to do with tribes which at one time probably
occupied wider territories, but which have now been crowded back
into the forest or wilderness. In addition to these tribes,
furthermore, there are remnants of peoples in Hindustan, in Celebes,
Sumatra, the Sunda Islands, etc. Concerning these, however, we as
yet have little knowledge. In some respects, doubtless, the
inhabitants of the Andaman Islands should also be here included,
although they cannot, on the whole, be regarded as primitive in the
strict sense of the word. This is precluded by their external culture,
and especially by their legends, the latter of which point to the
influence of Asiatic culture.
Observations of these relatively most primitive tribes—and this is
especially worth noting—-show them to be remarkably similar. If we
read a description of the characteristics, habits, and customs of the
Negritos of the Philippines and then pass on to the Malaccans, to the
Semangs and Senoi, or, further, to the Veddahs of Ceylon, we
constantly meet with almost the same phenomena, there being but
slight differences depending on the specific character of the natural
environment. We are thus in possession of data that are now
observable. The statements and conclusions which these enable us
to make are more than mere speculations with regard to the past;
and they are more than inferences drawn from the silent fragments
of the bones and from a few of the art products of primitive man.
According as the phenomena are simpler in character and require
fewer antecedent conditions for their explanation, may we be
confident that we are really dealing with primitive conditions. This in
itself implies that the criteria of primitive culture are essentially
psychological in nature, and that racial characteristics and original
tribal relationships are probably negligible so far as this question is
concerned. A culture would be absolutely primitive if no antecedent
mental development whatsoever could be presupposed. Such an
absolute concept can never be realized in experience, here any more
than elsewhere. We shall, therefore, call that man primitive in the
relative sense of the term—our only remaining alternative—whose
culture approximates most nearly to the lowest mental achievements
conceivable within the limits of universal human characteristics. The
most convenient measure of these achievements, and the one lying
nearest at hand, is that afforded by external culture, as expressed in
dress, habitation, and food, in self-made implements, weapons, and
other productions serving to satisfy the most urgent needs of life.

2. THE CULTURE OF PRIMITIVE MAN IN ITS EXTERNAL


EXPRESSIONS.

Following the above-mentioned criteria as to what may be regarded


as primitive, the question concerning the external culture of primitive
man may, in general, be briefly answered. Of dress there are only
meagre beginnings: about the loins a cord of bast, to which twigs of
trees are attached to cover the genitals—that is generally all, unless,
through secret barter with neighbouring peoples, cotton goods,
leather, and the like, have been imported. As regards personal
decoration, conditions are much the same. On the next stage of
development, the totemic, there is, as we shall later see, a desire for
lavish decoration, especially as regards the adornment of the body
by painting and tatooing. Little of this, however, is to be found
among primitive tribes, and that which exists has probably been
introduced from without. Some examples of such decoration are the
scanty tatooing in single lines, the painting of the face with several
red and white dots, and the wooden plug bored through the bridge
of the nose. The Negritos of the Philippines bore holes through their
lips for the insertion of a row of blades of grass. Other decorations
found are necklaces and bracelets, fillets, combs, hair ornaments
made of twigs and flowers, and the like.
What is true of his dress holds also of the dwelling of primitive man.
Everything indicates that the first permanent dwelling was the cave.
Natural caves in the hillsides, or, less frequently, artificially
constructed hollows in the sand, are the places of refuge that
primitive man seeks when the rainy season of the tropics drives him
to shelter. During the dry season, no shelter at all is necessary; he
makes his bed under a tree, or climbs the tree to gain protection
from wild animals. Only in the open country, under the compulsion
of wind and rain, does he construct a wind-break of branches and
leaves after the pattern supplied by nature in the leafy shelter of the
forest. When the supports of this screen are inclined toward one
another and set up in a circle, the result is the original hut.
Closely connected with the real dwelling of primitive man, the cave,
are two further phenomena that date back to earliest culture. As his
constant companion, primitive man has a single animal, the dog,
doubtless the earliest of domestic animals. Of all domestic animals
this is the one that has remained most faithful to man down to the
present time. The inhabitant of the modern city still keeps a dog if
he owns any domestic animal at all, and as early as primitive times
the dog was man's faithful companion. The origin of this first
domestic animal remains obscure. The popular notion would seem to
be that man felt the need of such a companion, and therefore
domesticated the dog. But if one calls to mind the dogs that run wild
in the streets of Constantinople, or the dog's nearest relative, the
wolf, one can scarcely believe that men ever had a strong desire to
make friends of these animals. According to another widely current
view, it was man's need of the dog as a helper in the chase that led
to its domestication. But this also is one of those rationalistic
hypotheses based on the presupposition that man always acts in
accordance with a preconceived plan, and thus knew in advance that
the dog would prove a superior domestic animal, and one especially
adapted to assist in the chase. Since the dog possessed these
characteristics only after its domestication, they could not have been
known until this had occurred, and the hypothesis is clearly
untenable. How, then, did the dog and man come together in the
earliest beginnings of society? The answer to this question, I believe,
is to be found in the cave, the original place of shelter from rain and
storm. Not only was the cave a refuge for man, but it was equally so
for animals, and especially for the dog. Thus it brought its dwellers
into companionship. Furthermore, the kindling of the fire, once man
had learned the art, may have attracted the animal to its warmth.
After the dog had thus become the companion of man, it
accompanied him in his activities, including that of the chase. Here,
of course, the nature of the carnivorous animal asserted itself; as
man hunted, so also did the animal. The dog's training, therefore,
did not at all consist in being taught to chase the game. It did this of
itself, as may be observed in the case of dogs that are not
specifically hunting dogs. The training consisted rather in breaking
the dog of the habit of devouring the captured game. This was
accomplished only through a consciously directed effort on the part
of man, an effort to which he was driven by his own needs. Thus, it
is the cave that accounts for the origin of the first domestic animal,
and also, probably, for the first attempt at training an animal. But
there is still another gain for the beginnings of culture that may
probably be attributed to the cave in its capacity of a permanent
habitation. Among primitive peoples, some of whom are already
advanced beyond the level here in question, it is especially in caves
that artistic productions may be found. These consist of crude
drawings of animals and, less frequently, of men. Among the
Bushmen, such cave pictures are frequently preserved from
destruction for a considerable period of time. Natural man, roaming
at will through the forests, has neither time nor opportunity to
exercise his imagination except upon relatively small objects or upon
the adornment of his own body. But the semi-darkness of the cave
tends, as do few other places, to stimulate the reproductive
imagination. Undisturbed by external influences, and with
brightnesses and colours enhanced by the darkness, the memory
images of things seen in the open, particularly those of the animals
of the primeval forest, rise to consciousness and impel the lonely
and unoccupied inhabitant to project them upon the wall. Such
activity is favoured by the fact, verifiable by personal introspection,
that memory images are much more vivid in darkness and semi-
darkness than in the light of day. Thus, it was in the cave, the first
dwelling-place of man, that the transition was made, perhaps for the
first time, from the beginnings of a graphic art, serving the purposes
of adornment or magic, to an art unfettered except by memory. It
was an art of memory in a twofold sense: it patterned its objects
after the memory of things actually observed, and it sought to
preserve to memory that which it created.
From the consideration of dress and habitation we turn to that of
food. Primitive man was not bound to fixed hours for his meals.
Among civilized peoples, so close a connection has grown up
between meals and definite hours of the day that the German word
for meal, Mahlzeit, reminds us of this regularity by twice repeating
the word for time—-for Mahl also means time. Primitive man knew
nothing of the sort. If he found food and was hungry, he ate; if he
found none, he went hungry. Sometimes, moreover, in order to
provide for the future, he gorged to such an extent as to injure his
health. As concerns the food itself, there is an old theory which has
led to misconceptions concerning primitive man. He was a hunter,
we are told; the chase supplied him with food; only incidentally and
occasionally did he enjoy parts of plants or fruits that he had
gathered or accidentally discovered. It is scarcely correct, however,
to assume that systematic hunting was practised by primitive man.
Doubtless he did engage in this occupation. Yet this furnished him
with only an incidental part of his food supply—apart with which,
living as he did from hand to mouth, he satisfied only his momentary
needs. It was with plant food, if at all, that he made provision for
the future. Here may be found also the first traces of a division of
labour: woman gathered the plant food—roots, bulbs, and berries—
while man occasionally found it necessary to hunt. Plant food being
capable of longer preservation, it was woman who first learned to
economize and to make provision for the future. In part, indeed, the
influence of these cultural beginnings persists even to-day. Moreover,
just as mixed food, part plant and part animal, is by far the most
common to-day, so also was it the original diet of man. The
proportion, however, varied more than in later times, according as
the external conditions of life were propitious or otherwise. Of this
the Bushmen afford a striking illustration. Fifty years ago they were
still by preference huntsmen. Armed with their bows, they dared to
hunt the elephant and the giraffe. But after the surrounding peoples
of South Africa—the Hottentots, Betschuans, and Herero—came into
the possession of firearms, which the Bushman scornfully rejects,
the game was, in part, exterminated, and to-day the Bushmen,
crowded back into rocky wastes, derive but a small part of their
living from the chase. They gather bulbs, roots, and other parts of
plants, such as can be rendered edible by boiling or roasting. Their
animal food, moreover, is no longer wild game, but consists, for the
most part, of small animals found while gathering the plant food—
frogs, lizards, worms, and even insects. Hunting, therefore, was
never more than one of the customary means of providing food; and
primitive man, especially, was a gatherer rather than a hunter. The
word 'gatherer' implies also that he took from nature only what it
directly offered, and that he was familiar neither with agriculture nor
with the raising of animals. In procuring his food, moreover, he was
aided by a knowledge, often surprising, of the properties of the
objects gathered. This knowledge, probably gained as a result of
many disastrous experiences in his search for food, enabled primitive
man to utilize even such roots and fruits as are not wholesome in
their raw state, either because they are not edible until prepared by
means of fire, or because they are poisonous. Primitive man learned
to overcome the injurious effects of many of these plants. By
reducing them to small pieces, washing them in a solution of lye,
and heating them, he converted them into palatable food. The bulbs
and roots were secured from beneath the surface of the ground by
means of the most primitive of all agricultural implements and the
progenitor of all succeeding ones, the digging-stick. This is a wooden
stick, with a pointed end that has been hardened by fire.
Connected with the removal of poison, by means of water and fire,
from parts of plants that are otherwise edible, is still another
primitive discovery—the utilization of the poisons themselves. Only
when the arrow is smeared with plant poisons does the bow become
a real weapon. In itself the arrow wound is not sufficient to kill
either game or enemy; the arrow must be poisoned if the wound is
to cause death or even temporary disability. The Veddahs and the
inland tribes of Malacca therefore use the juice of the upas-tree
mixed with that of strychnos-trees. The best known of these arrow
poisons, curare, used in South America and especially in Guiana, is
likewise prepared from the juice of strychnos-trees.
This brings us to the weapons of primitive man. In this connection it
is highly important to note that all of the primitive peoples
mentioned above are familiar with the use of bow and arrow, but we
must also bear in mind that this is practically their only weapon.
Contrary to what archæological excavations would suggest
concerning the earliest age of peoples, primitive culture, in respect
to implements and weapons, depended only to a small extent upon
the working of stone. We might better speak of this period as an age
of wood. Wood is not only decidedly easier to manipulate than
stone, but it is always more easily obtainable in shapes suitable for
constructive purposes. Possibly even the arrow-head was originally
always made of wood, as it sometimes is even to-day. Only in later
times was the wood replaced by a sharpened stone or by iron
acquired through barter.
It is not difficult to see how wood, in the forms which it possesses
by nature, came to be fashioned into clubs, axes, and digging-sticks,
and how bones, horns, shells, and the like were converted into tools
and objects of adornment. But how did primitive man acquire bow
and arrow? The general belief seems to be that this weapon was
invented by some resourceful mind of an early age. But an inventor,
in the proper sense of the word, must know in advance what he
wishes to invent. The man, therefore, who constructed the bow and
arrow for the first time must already have had some previous idea of
it. To effect a combination of existing implements, or to improve
them in useful ways, is a comparatively easy matter. But no one can
manufacture implements if he possesses nothing over and above
material that is in itself somehow suitable for the purpose. The most
primitive implements, therefore, such as the digging-stick, the club,
and the hammer, are all products of nature, at most changed slightly
by man as their use requires. But this is obviously not true of bow
and arrow. We may, perhaps, find a suggestion for the solution of
our problem in a hunting weapon which, though belonging, of
course, to the later totemic culture, is in principle simpler than the
bow and arrow—the boomerang of the Australians. The word is
probably familiar to all, but the nature of the weapon is not so well
known, especially its peculiarly characteristic form by virtue of which,
if it fails to strike its object, it flies back to the one who hurled it.
The boomerang, which possesses this useful characteristic, is, in the
first place, a bent wooden missile, pointed at both ends. That this
curved form has a greater range and strikes truer to aim than a
straight spear, the Australian, of course, first learned from
experience. The boomerang, however, will not return if it is very
symmetrically constructed; on the contrary, it then falls to the
ground, where it remains. Now it appears that the two halves of this
missile are asymmetrical. One of the halves is twisted spirally, so
that the weapon, if thrown forward obliquely, will, in accordance
with the laws of ballistics, describe a curve that returns upon itself.
This asymmetry, likewise, was discovered accidentally. In this case,
the discovery was all the more likely, for primitive weapons were
never fashioned with exactitude. That this asymmetry serves a
useful purpose, therefore, was first revealed by experience. As a
result, however, primitive man began to copy as faithfully as possible
those implements which most perfectly exhibited this characteristic.
Thus, this missile is not a weapon that required exceptional inventive
ability, though, of course, it demanded certain powers of
observation. The characteristics, accordingly, that insured the
survival of the boomerang were discovered accidentally and then
fixed through an attentive regard to those qualities that had once
been found advantageous. Now, can we conceive of the origin of
bow and arrow in an analogous way? Surely this weapon also was
not devised in all its parts at a single time. The man of nature,
pressing his way through the dense underbrush of the forest and
experiencing in person the hard blows of branches that he has bent
back, gains a lively impression of the elastic power of bent wood.
How easily the attention is forced to the observation that this effect
increases when the wood is bent out of its natural shape, appears
strikingly in the case of a kind of bow found in Asia and the Asiatic
islands. The bow is here constructed out of a piece of wood bent by
nature, not in such a way, however, that the natural curve of the
wood forms the curve of the bow, but contrariwise. Thus arises a
reflexive bow, whose elastic power is, of course, considerably
increased. In order that such a bow may be bent back more easily,
some people of a more advanced culture construct it out of several
layers of wood, horn, sinew, or the like. Having first observed the
powerful impulsive force which a rod gains through being bent, it
was a simple matter to render this force permanently available by
bending the rod back and binding its ends together with a cord of
bast, or, if bamboo was used, with strips torn from the bamboo
itself. Thus originated the common form of the bow. Next, it was, of
course, easy to observe that the bowstring thus contrived would
communicate a powerful impetus to a lighter piece of wood placed
against it. In addition to the bow, we then have the arrow, which is
hurled into the distance by the combined propelling power of the
bow and its string. But at this point a new factor appeared, clearly
indicating that several motives generally co-operated in the case of
such so-called primitive inventions. In these inventions nature itself
played no less a part than did the inventive genius of the individual.
The arrow but rarely consists merely of a piece of wood one of
whose ends is somehow pointed or provided with a stone head, or,
at a later period, with an iron head. As is well known, the other end
is feathered, either with genuine bird feathers or, as in the case of
the pygmies of Central Africa, with an imitation of bird feathers
made of palm-leaves. The feathers are usually supposed to have
been added to insure the accurate flight of the arrow. And this
accuracy is, indeed, the resultant effect. As in the case of the
boomerang, however, we must again raise the question: How did
man come to foresee this effect, of whose mechanical conditions he
had, of course, not the slightest knowledge? The solution of this
problem probably lies in the fact of an association of the discharged
arrow with a flying bird that pierces the air by the movement of its
feathers. Thus, in the arrow, man copied the mode of movement of
the bird. He certainly did not copy it, however, with the thought that
he was causing movement in a mechanical way. We must bear in
mind that for primitive man the image of a thing is in reality always
equivalent to the thing itself. Just as he believes that his spirit
resides in his picture, with the result that he is frequently seized with
fright when a painter draws his likeness and carries it away with
him, so also does the feathered arrow become for him a bird. In his
opinion, the qualities of the bird are transferred by force of magic to
the arrow. In this case, indeed, the magical motive is in harmony
with the mechanical effect.
Nature directly supplies primitive man not only with the patterns of
his implements and weapons, but also with those of the vessels
which he uses. Of the primitive tribes none is familiar, at the outset,
with pottery. In its stead, suitable natural objects are utilized for
storing what is gathered. The Negritos of the Philippines, for
example, employ coconut shells. The inland tribes of the Malay
Peninsula use bamboo, whose varying thicknesses, and, particularly,
whose internodes enable it to be converted into the desired vessels
by cutting the stem at the upper end of an internode and
immediately below it, thus securing a vessel with a bottom.
Wherever primitive peoples cut vessels out of wood, as occurs
among the Veddahs and the Bushmen, we may be sure that this
represents a comparatively late acquirement, following upon a
knowledge of metals and the use of stone implements. Primitive
man possesses no vessels for cooking purposes. He prepares his
food directly in the fire or in hot ashes.
We are now confronted by a final and an especially interesting
question of primitive culture, that of the acquisition of fire. This
acquisition made a deep impression on the human mind, and one
whose effects long survived in legend. The totemic age, as we shall
see, is replete with legends of beneficent animals which brought fire
to man. In the heroic age, the fire-bringing animal is displaced by
the fire-bringing hero. We may call to mind Prometheus, who
brought fire from heaven, and by so doing drew upon himself the
vengeance of the gods. Nevertheless, the question concerning the
original production of fire is a very simple one. As in the case of very
many utensils and tools, we must look to natural conditions that
present themselves in the course of experience. Man did not invent
the art of kindling fire; it would be nearer the truth to say that he
found it, inasmuch as he discovered it while making his utensils. In
this connection, particularly, it is highly important to note that the
first age, if we would designate it by its tools, was not an age of
stone but an age of wood. We have already referred to the way in
which bamboo was worked up into vessels for the storing of fruits
and liquids. With a sharp sliver of bamboo, a bamboo-stem is sawed
into pieces in order that its parts may be utilized. If this sawing
occurs during dry weather, the wood is pulverized and the heated
sawdust finally becomes ignited. As soon as it begins to glow, the
worker blows upon it and the fire flames up. This mode of kindling
fire has been called that of sawing, and is probably the oldest in
origin. After fire was thus accidentally produced, it became possible
to kindle it at will, and this developed into a skilful art. At a later
stage, however, there came the further need of drilling holes into
wood. This gave rise to a second method of kindling fire, that of
drilling. A piece of wood is bored through with a sharpened stick of
hard wood, and the same results occur as in the case of the sawing.
The method of drilling is the more effective; it produces fire more
quickly. Nevertheless, both methods are laborious and tedious, and
we cannot blame the savage for regarding as a magician the
European who before his very eyes lights a match by friction.
Because of the difficulty in producing fire, its preservation plays an
important rôle in the life of the savage. When he changes his
dwelling-place, his first consideration, as a rule, is to take with him
some live fire so that he will not be obliged to kindle it anew.
In conclusion, we may supplement these sketches of external culture
by mention of a feature that is particularly characteristic of the
relation of primitive man to his environment. Primitive man lives in
close association with his fellow-tribesmen, but he secludes himself
from other tribes of the neighbourhood. He is led to do so because
they threaten his means of subsistence; indeed, he himself may fall
a prey to them, as do the Pygmies of Central Africa to the
anthropophagic customs of the Monbuttus. And yet, primitive man
early feels the need of such useful articles as he cannot himself
produce but with which he has, in some accidental manner, become
acquainted. This gives rise to what is generally called 'secret barter.'
An illuminating example of this occurs in the records of the Sarasin
cousins as relating to the Veddahs. The Veddah goes by night to the
house of a neighbouring Singhalese smith and there deposits what
he has to offer in barter, such as captured game, ivory, etc. With this
he places a representation of an arrow-head, made of palm-leaves.
The next night he returns and finds real arrows of iron which the
smith has laid out in exchange for the proffered goods. It might be
thought that such a system of barter would imply an excessive
measure of confidence. The smith, however, knows that, should he
take away that which was brought to him without delivering the
arrows, he would himself be struck by an arrow shot from some
sheltered ambush. Thus, many things, especially iron, materials for
clothing, and articles of adornment, come into the possession of
primitive man through secret barter, raising his external culture to a
somewhat higher level.
A retrospective survey of this culture brings to notice especially the
fact that the concept 'primitive' is never valid, as applied to man,
except in a relative sense. Of an absolutely primitive man we know
nothing at all. Moreover, the knowledge of such a being could hardly
render explicable his further development, since he would really
belong to the animal level and therefore to the prehuman stage of
existence. Primitive man is relatively primitive, for, while he does
possess certain beginnings of culture, these are in no respect more
than mere beginnings, all of which are borrowed from nature and
from the direct means of assistance which it offers. It is precisely
these elementary acquisitions, however, that already differentiate
primitive man from the animal. He has the beginnings of a dwelling
and of dress, even though he does no more in either case than
merely to utilize the means which nature offers, or than partly to
imitate and partly to combine these means, as he does in the case
of the leafy wind-break and of the weapons which doubtless
represent the highest achievement of this age—namely, the bow and
arrow. But these are all beginnings which already contain within
themselves the possibilities of higher achievements. The
development of the hut out of the wind-break, of the lance out of
the staff and the arrow, of the woven basket out of the coconut or
the gourd, severally represent easy steps in the advance from nature
to culture. Next there comes the preparation of food by means of
fire. This is closely connected with the discovery of the art of
kindling fire, which, in its turn, was partly an accidental discovery
connected with the manufacture of primitive tools out of wood and
partly a real invention. Thus, the manufacture of tools, on the one
hand, and the kindling of fire, which was connected with it, on the
other, are the two primary features which from early times on
distinguished primitive man from animals. Furthermore, there is the
bow and arrow, which is the first real weapon and differs markedly
from all other implements. Its construction also was dependent upon
the assistance of nature. The fact that this was the only weapon of
primitive society throws an important light on the nature of the
latter. The bow and arrow continued to be used for a long time
afterwards—indeed, even down to the appearance of firearms; it
served not only as a weapon of warfare but also as an implement for
hunting. With it alone, however, no organized strife or warfare of any
sort is possible. While, therefore, it is true that the archer appears
on the earliest monuments of cultural peoples, it is only as the
fellow-combatant of the warrior who is armed with shield and lance.
With lance and shield it is possible to fight in closed ranks. The
archer must fight single-handed. Primitive man, therefore, does not
engage in tribal wars; he is familiar only with the strife of individual
with individual. In fact, wherever the bow and arrow is used
exclusively, open warfare is impossible. With it, primitive man slays
his enemy from behind a sheltering bush. It is thus that the Veddah
of nature serves the cultural Veddah, or the Singhalese who has
deceived him in secret barter, or even the fellow-tribesman who
steals his wife. Just as secret barter is carried on in concealment, so
also is warfare. This, however, indicates that the bow and arrow was
originally intended for hunting and not for warfare. From this
consideration alone it is evident that primitive life was not a war of
all against all, as it was described by Thomas Hobbes. On the
contrary, there doubtless existed a state of peace, interrupted only
occasionally by the strife of individual with individual—a strife that
resulted from a conflict of interests, such as occurred even during
this early period.

3. THE ORIGIN OF MARRIAGE AND THE FAMILY.

That the origin of marriage and the family really constitutes a


problem, long failed to be recognized. Because of the natural
relations of the sexes it was supposed that man lived in a state of
marriage from the very beginning. Furthermore, the monogamous
marriage of the present was projected back into an indefinite past,
where it found final termination in the idea of a primal pair of
ancestors. But, even apart from this mythological belief, there were
also positive grounds for supposing an original state of monogamy.
Do not many animals live in monogamous union? In addition to nest-
building birds, monogamy prevails particularly among mammals,
and, of the latter, among those that have the closest physical
relationship to man. We might cite the gorilla, the primate that most
resembles man, and probably also the chimpanzee, although in this
case we lack positive proof. Why, then, should not man have carried
over monogamous marriage from his animal state into his primitive
culture? This theory, therefore, was regarded as almost self-evident
until after the middle of the last century. But in 1861, a Swiss jurist
and antiquarian, J. Bachofen, published a remarkable work on
"Mother-right." In this book Bachofen attempted to prove the falsity
of the doctrine—previously almost uncontested—that monogamy
was the original form of marriage, and to refute the view, regarded
as equally self-evident, that within this marriage union man held the
supremacy—in brief, the patriarchal theory. Bachofen started with a
discussion of the Lycians as described by Herodotus. According to
this writer, the kinship of the children, among the Lycians, was
determined by the mother, not by the father. The sons and
daughters belonged to the family of the mother, and descent was
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like